Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changeset/brown-guests-roll.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@clerk/localizations': minor
'@clerk/clerk-js': minor
'@clerk/shared': minor
'@clerk/ui': minor
---

Add support for applying promo codes at checkout
8 changes: 8 additions & 0 deletions .changeset/green-dolphins-discount.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@clerk/clerk-js': patch
'@clerk/localizations': patch
'@clerk/shared': patch
'@clerk/ui': patch
---

Show applied discounts in the subscription overview.
6 changes: 6 additions & 0 deletions .changeset/render-discounts-payment-statement.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@clerk/ui': patch
'@clerk/backend': patch
---

Show applied discount on billing payment attempts and statements.
2 changes: 1 addition & 1 deletion integration/tests/pricing-table.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,7 @@ testAgainstRunningApps({})('pricing table @billing', ({ app }) => {

await expect(matchLineItem(u.po.checkout.root, 'Total Due after')).toBeHidden();
await expect(matchLineItem(u.po.checkout.root, 'Total due today', '$999.00')).toBeVisible();
expect(await countLineItems(u.po.checkout.root)).toBe(3);
expect(await countLineItems(u.po.checkout.root)).toBe(4);

await u.po.checkout.root.getByRole('button', { name: /^pay\s\$/i }).waitFor({ state: 'visible' });
await u.po.checkout.clickPayOrSubscribe();
Expand Down
14 changes: 14 additions & 0 deletions packages/backend/src/util/billing.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import type {
BillingAppliedDiscount,
BillingAppliedDiscountJSON,
BillingCredits,
BillingCreditsJSON,
BillingDiscounts,
Expand Down Expand Up @@ -51,6 +53,17 @@ const billingCreditsFromJSON = (credits: BillingCreditsJSON): BillingCredits =>
total: billingMoneyAmountFromJSON(credits.total),
});

const billingAppliedDiscountFromJSON = (discount: BillingAppliedDiscountJSON): BillingAppliedDiscount => ({
amount: billingMoneyAmountFromJSON(discount.amount),
discountId: discount.discount_id,
name: discount.name,
effect: discount.effect,
percentOff: discount.percent_off,
amountOff: discount.amount_off ? billingMoneyAmountFromJSON(discount.amount_off) : undefined,
promoCode: discount.promo_code,
cyclesRemaining: discount.cycles_remaining,
});

const billingDiscountsFromJSON = (discounts: BillingDiscountsJSON): BillingDiscounts => ({
proration: discounts.proration
? {
Expand All @@ -60,6 +73,7 @@ const billingDiscountsFromJSON = (discounts: BillingDiscountsJSON): BillingDisco
cyclePassedPercent: discounts.proration.cycle_passed_percent,
}
: null,
discount: discounts.discount ? billingAppliedDiscountFromJSON(discounts.discount) : undefined,
total: billingMoneyAmountFromJSON(discounts.total),
});

Expand Down
4 changes: 2 additions & 2 deletions packages/clerk-js/bundlewatch.config.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
{
"files": [
{ "path": "./dist/clerk.js", "maxSize": "549KB" },
{ "path": "./dist/clerk.browser.js", "maxSize": "75KB" },
{ "path": "./dist/clerk.legacy.browser.js", "maxSize": "117KB" },
{ "path": "./dist/clerk.browser.js", "maxSize": "77KB" },
{ "path": "./dist/clerk.legacy.browser.js", "maxSize": "119KB" },
{ "path": "./dist/clerk.no-rhc.js", "maxSize": "316KB" },
{ "path": "./dist/clerk.native.js", "maxSize": "76KB" },
{ "path": "./dist/vendors*.js", "maxSize": "7KB" },
Expand Down
14 changes: 14 additions & 0 deletions packages/clerk-js/src/core/modules/billing/namespace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import type {
GetPlansParams,
GetStatementsParams,
GetSubscriptionParams,
UpdateCheckoutParams,
} from '@clerk/shared/types';

import { convertPageToOffsetSearchParams } from '../../../utils/convertPageToOffsetSearchParams';
Expand Down Expand Up @@ -149,6 +150,19 @@ export class Billing implements BillingNamespace {
return new BillingCheckout(json);
};

updateCheckout = async (params: UpdateCheckoutParams) => {
const { id, orgId, ...rest } = params;
const json = (
await BaseResource._fetch<BillingCheckoutJSON>({
path: Billing.path(`/checkouts/${id}`, { orgId }),
method: 'PATCH',
body: rest as any,
})
)?.response as unknown as BillingCheckoutJSON;

return new BillingCheckout(json);
};

getCreditBalance = async (params: GetCreditBalanceParams): Promise<BillingCreditBalanceResource> => {
return await BaseResource._fetch({
path: Billing.path('/credits', { orgId: params.orgId }),
Expand Down
42 changes: 37 additions & 5 deletions packages/clerk-js/src/core/resources/BillingCheckout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import type {
CheckoutSignalValue,
ConfirmCheckoutParams,
CreateCheckoutParams,
UpdateCheckoutParams,
} from '@clerk/shared/types';
import { computed, endBatch, signal, startBatch } from 'alien-signals';

Expand Down Expand Up @@ -117,7 +118,7 @@ export const createSignals = () => {
return { resourceSignal, errorSignal, fetchSignal, computedSignal };
};

type CheckoutTask = 'start' | 'confirm' | 'finalize';
type CheckoutTask = 'start' | 'update' | 'confirm' | 'finalize';

export class CheckoutFlow implements CheckoutFlowResourceNonStrict {
private resource = new BillingCheckout(null);
Expand Down Expand Up @@ -197,6 +198,24 @@ export class CheckoutFlow implements CheckoutFlowResourceNonStrict {
});
}

async update(params: Pick<UpdateCheckoutParams, 'promoCode'>): Promise<{ error: ClerkError | null }> {
if (!this.resource.id) {
throw new Error('Clerk: `start()` must be called before `update()`');
}
return this.runAsyncCheckoutTask(
'update',
async () => {
this.resource = (await BillingCheckout.clerk.billing?.updateCheckout({
id: this.resource.id,
orgId: this.resource.payer.organizationId || undefined,
...params,
})) as BillingCheckout;
},
undefined,
false,
);
}

async finalize(params?: CheckoutFlowFinalizeParams): Promise<{ error: ClerkError | null }> {
const { navigate } = params || {};
return this.runAsyncCheckoutTask('finalize', async () => {
Expand All @@ -208,13 +227,23 @@ export class CheckoutFlow implements CheckoutFlowResourceNonStrict {
});
}

private runAsyncCheckoutTask<T>(operationType: CheckoutTask, task: () => Promise<T>, beforeTask?: () => void) {
private runAsyncCheckoutTask<T>(
operationType: CheckoutTask,
task: () => Promise<T>,
beforeTask?: () => void,
updateErrorSignal = true,
) {
// Noops during transitive state
if (typeof BillingCheckout.clerk.user === 'undefined') {
console.warn('Clerk: Checkout operations cannot be performed during transitive state');
return { error: null };
}
return createRunAsyncCheckoutTask(this, this.signals, this.pendingOperations)(operationType, task, beforeTask);
return createRunAsyncCheckoutTask(this, this.signals, this.pendingOperations)(
operationType,
task,
beforeTask,
updateErrorSignal,
);
}
}

Expand All @@ -226,8 +255,9 @@ function createRunAsyncCheckoutTask(
operationType: CheckoutTask,
task: () => Promise<T>,
beforeTask?: () => void,
updateErrorSignal?: boolean,
) => Promise<{ error: ClerkError | null }> {
return async (operationType, task, beforeTask?: () => void) => {
return async (operationType, task, beforeTask?: () => void, updateErrorSignal = true) => {
if (pendingOperations.get(operationType)) {
// Wait for the existing operation to complete and return its result
// If it fails, all callers should receive the same error
Expand All @@ -246,7 +276,9 @@ function createRunAsyncCheckoutTask(
signals.resourceSignal({ resource: resource });
return { error: null };
} catch (err) {
signals.errorSignal({ error: err });
if (updateErrorSignal) {
signals.errorSignal({ error: err });
}
return { error: err };
} finally {
pendingOperations.delete(operationType);
Expand Down
4 changes: 4 additions & 0 deletions packages/clerk-js/src/core/resources/BillingSubscription.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type {
BillingCredits,
BillingDiscountRedemption,
BillingMoneyAmount,
BillingSubscriptionItemJSON,
BillingSubscriptionItemNextPayment,
Expand All @@ -18,6 +19,7 @@ import { unixEpochToDate } from '@/utils/date';

import {
billingCreditsFromJSON,
billingDiscountRedemptionFromJSON,
billingMoneyAmountFromJSON,
billingPerUnitTotalTierFromJSON,
billingSubscriptionItemNextPaymentFromJSON,
Expand Down Expand Up @@ -85,6 +87,7 @@ export class BillingSubscriptionItem extends BaseResource implements BillingSubs
};
seats?: BillingSubscriptionItemSeats;
credits?: BillingCredits;
appliedDiscount?: BillingDiscountRedemption;
nextPayment?: BillingSubscriptionItemNextPayment | null;
isFreeTrial!: boolean;

Expand Down Expand Up @@ -122,6 +125,7 @@ export class BillingSubscriptionItem extends BaseResource implements BillingSubs
: undefined;

this.credits = data.credits ? billingCreditsFromJSON(data.credits) : undefined;
this.appliedDiscount = data.applied_discount ? billingDiscountRedemptionFromJSON(data.applied_discount) : undefined;
this.nextPayment =
data.next_payment === undefined
? undefined
Expand Down
84 changes: 84 additions & 0 deletions packages/clerk-js/src/utils/__tests__/billing.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import type {
import { describe, expect, it } from 'vitest';

import {
billingDiscountRedemptionFromJSON,
billingPaymentTotalsFromJSON,
billingSubscriptionItemNextPaymentFromJSON,
billingSubscriptionNextPaymentFromJSON,
Expand Down Expand Up @@ -40,6 +41,15 @@ const nextPaymentTotalsJSON = (): BillingTotalsJSON => ({
cycle_days_total: 30,
cycle_passed_percent: 50,
},
discount: {
amount: moneyJSON(1000),
discount_id: 'discount_123',
name: 'Welcome',
effect: 'percentage',
percent_off: 20,
promo_code: 'WELCOME20',
cycles_remaining: 2,
},
total: moneyJSON(500),
},
total_due_after_free_trial: null,
Expand Down Expand Up @@ -109,6 +119,14 @@ describe('billingPaymentTotalsFromJSON', () => {
cycle_days_total: 30,
cycle_passed_percent: 3,
},
discount: {
amount: moneyJSON(100),
discount_id: 'discount_123',
name: 'Fixed discount',
effect: 'fixed_amount',
amount_off: moneyJSON(100),
cycles_remaining: null,
},
total: moneyJSON(16),
},
};
Expand All @@ -117,6 +135,14 @@ describe('billingPaymentTotalsFromJSON', () => {

expect(totals.discounts?.proration?.amount.amount).toBe(16);
expect(totals.discounts?.proration?.cycleDaysPassed).toBe(1);
expect(totals.discounts?.discount).toMatchObject({
amount: { amount: 100 },
discountId: 'discount_123',
name: 'Fixed discount',
effect: 'fixed_amount',
amountOff: { amount: 100, amountFormatted: '1.00', currency: 'USD', currencySymbol: '$' },
cyclesRemaining: null,
});
expect(totals.discounts?.total.amount).toBe(16);
});

Expand Down Expand Up @@ -209,6 +235,15 @@ describe('billingSubscriptionNextPaymentFromJSON', () => {
cycleDaysTotal: 30,
cyclePassedPercent: 50,
},
discount: {
amount: { amount: 1000 },
discountId: 'discount_123',
name: 'Welcome',
effect: 'percentage',
percentOff: 20,
promoCode: 'WELCOME20',
cyclesRemaining: 2,
},
total: { amount: 500 },
},
perUnitTotals: [{ name: 'seats', blockSize: 1 }],
Expand All @@ -223,6 +258,55 @@ describe('billingSubscriptionNextPaymentFromJSON', () => {
});
});

describe('billingDiscountRedemptionFromJSON', () => {
it('maps an applied subscription item discount', () => {
const discount = billingDiscountRedemptionFromJSON({
object: 'commerce_discount_redemption',
id: 'redemption_123',
subscription_item_id: 'sub_item_123',
discount_id: 'discount_123',
name: 'Welcome',
source: 'promo_code',
promo_code: 'WELCOME20',
effect: 'fixed_amount',
amount_off: moneyJSON(500),
amount: moneyJSON(400),
cycles_remaining: 2,
cycles_applied: 1,
status: 'active',
redeemed_at: 1_609_459_200_000,
redeemed_by: 'user_123',
});

expect(discount).toMatchObject({
id: 'redemption_123',
subscriptionItemId: 'sub_item_123',
discountId: 'discount_123',
name: 'Welcome',
source: 'promo_code',
promoCode: 'WELCOME20',
effect: 'fixed_amount',
amountOff: {
amount: 500,
amountFormatted: '5.00',
currency: 'USD',
currencySymbol: '$',
},
amount: {
amount: 400,
amountFormatted: '4.00',
currency: 'USD',
currencySymbol: '$',
},
cyclesRemaining: 2,
cyclesApplied: 1,
status: 'active',
redeemedAt: new Date('2021-01-01T00:00:00.000Z'),
redeemedBy: 'user_123',
});
});
});

describe('billingSubscriptionItemNextPaymentFromJSON', () => {
it('maps amount, date, and per_unit_totals', () => {
const data: BillingSubscriptionItemNextPaymentJSON = {
Expand Down
Loading
Loading