Skip to content

Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.

feat(billing): support Dodo coupon invoices and discounted renewals

Timothy Yinc64661971ca2
diff --git a/packages/platform/migrations/0034_checkout_discount_codes.sql b/packages/platform/migrations/0034_checkout_discount_codes.sql
new file mode 100644
index 00000000..4d8ebd69
--- /dev/null
+++ b/packages/platform/migrations/0034_checkout_discount_codes.sql
@@ -0,0 +1 @@
+ALTER TABLE platform_payment_checkouts ADD COLUMN coupon_enabled INTEGER NOT NULL DEFAULT 0 CHECK(coupon_enabled IN(0,1));
diff --git a/packages/platform/src/deferred-payments.ts b/packages/platform/src/deferred-payments.ts
index 19e90a87..06285322 100644
--- a/packages/platform/src/deferred-payments.ts
+++ b/packages/platform/src/deferred-payments.ts
@@ -1,3 +1,4 @@
+import { appliedDiscounts, freeDiscountPeriod } from './payment-discounts.ts'
import {
closeFailedInitialCheckout,
markAwaitingInitialCheckout,
@@ -29,6 +30,9 @@ export async function reconcileDeferredAuthorization(
if (known && known.customer_id !== subscription.customer.customer_id)
fail('payment_customer_mismatch')
const snapshot = JSON.parse(checkout.handover_json)
+ const paidBoundary =
+ known?.handover_at ??
+ Math.max(snapshot.expiresAt, checkout.created_at + snapshot.trialDays * DAY)
// The caller has verified provider metadata and product ownership. Do not leave
// a new, rejected trial running without a local reservation to manage it.
async function rejectNewAuthorization(code: string): Promise<never> {
@@ -92,7 +96,9 @@ export async function reconcileDeferredAuthorization(
.filter(
(p: any) =>
p.status === 'succeeded' &&
- p.total_amount > 0 &&
+ (p.total_amount > 0 ||
+ (p.total_amount === 0 &&
+ time(p.created_at) >= paidBoundary - 60000)) &&
(p.subscription_id === subscription.subscription_id ||
p.subscription_ids?.includes(subscription.subscription_id)),
)
@@ -102,20 +108,34 @@ export async function reconcileDeferredAuthorization(
payment = await dodoRequest(() => client.payments.retrieve(paymentId))
}
}
- if (payment?.status === 'succeeded' && payment.total_amount > 0) {
+ const freePeriod =
+ payment?.charge_type === 'renewal'
+ ? freeDiscountPeriod(payment, subscription, checkout, paidBoundary)
+ : null
+ const couponCycle =
+ payment?.total_amount === 0 &&
+ payment.charge_type === 'renewal' &&
+ appliedDiscounts(payment, checkout) &&
+ (payment.service_periods?.some(
+ (p: any) =>
+ p.subscription_id === subscription.subscription_id &&
+ time(p.starts_at) >= paidBoundary - 60000,
+ ) ||
+ freePeriod)
+ if (
+ payment?.status === 'succeeded' &&
+ (payment.total_amount > 0 || couponCycle)
+ ) {
if (
known?.status === 'canceled' ||
checkout.error === 'payment_handover_cancelled'
)
fail('payment_handover_cancelled')
- const period = payment.service_periods?.find(
- (p: any) => p.subscription_id === subscription.subscription_id,
- )
- if (
- !period ||
- time(period.starts_at) <
- (known?.handover_at ?? snapshot.expiresAt) - 60000
- )
+ const period =
+ payment.service_periods?.find(
+ (p: any) => p.subscription_id === subscription.subscription_id,
+ ) ?? freePeriod
+ if (!period || time(period.starts_at) < paidBoundary - 60000)
fail('payment_period_invalid')
return { handled: false, paymentId }
}
diff --git a/packages/platform/src/dodo-payments.ts b/packages/platform/src/dodo-payments.ts
index bfc649a6..43ac1e55 100644
--- a/packages/platform/src/dodo-payments.ts
+++ b/packages/platform/src/dodo-payments.ts
@@ -1,3 +1,7 @@
+import {
+ discountedPaymentMatches,
+ freeDiscountPeriod,
+} from './payment-discounts.ts'
import {
closeFailedInitialCheckout,
markAwaitingInitialCheckout,
@@ -104,6 +108,8 @@ export async function syncDodoProducts(
tax_category: 'saas' as const,
price: {
type: 'recurring_price' as const,
+ zero_amount_payment_method_optional: false,
+ trial_payment_method_optional: false,
currency: plan.currency,
price,
payment_frequency_count: plan.period,
@@ -354,6 +360,8 @@ export async function createDodoCheckout(
(price.trial_amount ?? 0) !== 0 ||
(price.discount_bps ?? (price.discount ?? 0) * 100) !==
product.discount_bps ||
+ price.zero_amount_payment_method_optional ||
+ price.trial_payment_method_optional ||
price.purchasing_power_parity ||
providerProduct.addons?.length
)
@@ -377,7 +385,7 @@ export async function createDodoCheckout(
try {
const result = await db
.prepare(
- `INSERT INTO platform_payment_checkouts(id,workspace_id,user_id,request_id,plan_id,interval,product_id,price,currency,assignment_revision,state,created_at,updated_at,provider,environment,provider_key,handover_json) SELECT ?,?,?,?,?,?,?,?,?,?,'creating',?,?,'dodo',?,?,? WHERE ${activeFence} AND EXISTS(SELECT 1 FROM platform_workspace_plans WHERE workspace_id=? AND revision=?)`,
+ `INSERT INTO platform_payment_checkouts(id,workspace_id,user_id,request_id,plan_id,interval,product_id,price,currency,assignment_revision,state,created_at,updated_at,provider,environment,provider_key,handover_json,coupon_enabled) SELECT ?,?,?,?,?,?,?,?,?,?,'creating',?,?,'dodo',?,?,?,1 WHERE ${activeFence} AND EXISTS(SELECT 1 FROM platform_workspace_plans WHERE workspace_id=? AND revision=?)`,
)
.bind(
id,
@@ -425,7 +433,7 @@ export async function createDodoCheckout(
).href,
feature_flags: {
allow_currency_selection: false,
- allow_discount_code: false,
+ allow_discount_code: true,
allow_customer_editing_email: false,
allow_editing_addons: false,
},
@@ -801,14 +809,19 @@ export async function reconcileDodoSubscription(
// Adaptive pricing charges the customer in a local currency. Compare the
// provider's settlement amount in the immutable product currency, never a
// browser amount, guessed exchange rate, or a numeric total in another currency.
- const amountMatches =
+ const couponMatches =
+ !identityError &&
payment &&
- Number.isSafeInteger(payment.total_amount) &&
- payment.total_amount > 0 &&
- (payment.currency === checkout.currency
- ? payment.total_amount === checkout.price
- : payment.settlement_currency === checkout.currency &&
- payment.settlement_amount === checkout.price)
+ (await discountedPaymentMatches(client, checkout, payment))
+ const amountMatches =
+ couponMatches ||
+ (payment &&
+ Number.isSafeInteger(payment.total_amount) &&
+ payment.total_amount > 0 &&
+ (payment.currency === checkout.currency
+ ? payment.total_amount === checkout.price
+ : payment.settlement_currency === checkout.currency &&
+ payment.settlement_amount === checkout.price))
const paid =
payment?.status === 'succeeded' &&
!identityError &&
@@ -822,9 +835,19 @@ export async function reconcileDodoSubscription(
fail('payment_amount_mismatch', 422)
}
const period = paid
- ? payment?.service_periods?.find(
+ ? (payment?.service_periods?.find(
(p) => p.subscription_id === subscriptionId,
- )
+ ) ??
+ (couponMatches
+ ? freeDiscountPeriod(
+ payment,
+ subscription,
+ checkout,
+ known?.activation_state === 'authorized'
+ ? known.handover_at
+ : (known?.period_end ?? checkout.created_at),
+ )
+ : null))
: null
if (!successful && !known) fail('payment_confirmation_pending')
// Older Dodo responses can omit service_periods for the initial payment.
diff --git a/packages/platform/src/payment-discounts.ts b/packages/platform/src/payment-discounts.ts
new file mode 100644
index 00000000..cbe0308e
--- /dev/null
+++ b/packages/platform/src/payment-discounts.ts
@@ -0,0 +1,124 @@
+import { dodoRequest } from './dodo-client.ts'
+
+/** Applied discount snapshots are read only from the authenticated payment response. */
+export function appliedDiscounts(payment: any, checkout: any) {
+ if (
+ !checkout.coupon_enabled ||
+ !Array.isArray(payment?.discounts) ||
+ payment.discounts.length < 1 ||
+ payment.discounts.length > 20 ||
+ !payment.business_id
+ )
+ return false
+ const ids = new Set<string>()
+ for (const [position, discount] of payment.discounts.entries()) {
+ if (
+ !discount ||
+ typeof discount.discount_id !== 'string' ||
+ !/^[a-zA-Z0-9_-]{1,160}$/.test(discount.discount_id) ||
+ ids.has(discount.discount_id) ||
+ discount.position !== position ||
+ discount.business_id !== payment.business_id ||
+ !['percentage', 'flat'].includes(discount.type) ||
+ !Number.isSafeInteger(discount.amount) ||
+ discount.amount < 1 ||
+ (discount.type === 'percentage' && discount.amount > 10000) ||
+ !Array.isArray(discount.restricted_to) ||
+ (discount.restricted_to.length &&
+ !discount.restricted_to.includes(checkout.product_id))
+ )
+ return false
+ ids.add(discount.discount_id)
+ }
+ return (
+ !payment.discount_id ||
+ payment.discount_id === payment.discounts[0].discount_id
+ )
+}
+
+/** Verify the billed product and final discounted total using its settled line item. */
+export async function discountedPaymentMatches(
+ client: any,
+ checkout: any,
+ payment: any,
+) {
+ if (
+ !appliedDiscounts(payment, checkout) ||
+ payment.status !== 'succeeded' ||
+ payment.includes_usage ||
+ payment.refunds?.length ||
+ payment.disputes?.length ||
+ !Number.isSafeInteger(payment.total_amount) ||
+ payment.total_amount < 0
+ )
+ return false
+ const expected =
+ payment.currency === checkout.currency
+ ? payment.total_amount
+ : payment.settlement_currency === checkout.currency
+ ? payment.settlement_amount
+ : null
+ if (
+ !Number.isSafeInteger(expected) ||
+ expected < 0 ||
+ expected > checkout.price
+ )
+ return false
+ const lines = (await dodoRequest(() =>
+ client.payments.retrieveLineItems(
+ payment.payment_id,
+ payment.currency === checkout.currency
+ ? { currency: payment.currency }
+ : undefined,
+ ),
+ )) as any
+ if (lines.currency !== checkout.currency || lines.items?.length !== 1)
+ return false
+ const item = lines.items[0]
+ return (
+ item.items_id === checkout.product_id &&
+ Number.isSafeInteger(item.amount) &&
+ item.amount >= 0 &&
+ Number.isSafeInteger(item.tax) &&
+ item.tax >= 0 &&
+ Number.isSafeInteger(item.amount + item.tax) &&
+ item.amount + item.tax === expected
+ )
+}
+
+/** A free recurring invoice may omit service_periods; never infer a period from a setup authorization. */
+export function freeDiscountPeriod(
+ payment: any,
+ subscription: any,
+ checkout: any,
+ notBefore: number,
+) {
+ if (
+ !appliedDiscounts(payment, checkout) ||
+ payment.status !== 'succeeded' ||
+ payment.total_amount !== 0 ||
+ payment.includes_usage ||
+ payment.is_update_payment_method ||
+ payment.is_multi_subscription ||
+ !['new', 'renewal'].includes(payment.charge_type) ||
+ subscription.status !== 'active' ||
+ payment.service_periods?.length
+ )
+ return null
+ const start = Date.parse(subscription.previous_billing_date),
+ end = Date.parse(subscription.next_billing_date),
+ created = Date.parse(payment.created_at)
+ if (
+ ![start, end, created].every(Number.isFinite) ||
+ start < notBefore - 60000 ||
+ Math.abs(start - created) > 300000 ||
+ end <= start ||
+ end - start > (checkout.interval * 31 + 1) * 86400000
+ )
+ return null
+ return {
+ subscription_id: subscription.subscription_id,
+ starts_at: subscription.previous_billing_date,
+ ends_at: subscription.next_billing_date,
+ }
+}
diff --git a/packages/platform/src/subscription-changes.ts b/packages/platform/src/subscription-changes.ts
index 08521727..ffba44fe 100644
--- a/packages/platform/src/subscription-changes.ts
+++ b/packages/platform/src/subscription-changes.ts
@@ -229,7 +229,6 @@ export async function previewPaymentPlanChange(
quantity: 1,
...mode(rule.direction),
on_payment_failure: 'prevent_change' as const,
- discount_codes: [],
}
const quote = await dodoRequest(() =>
client.subscriptions.previewChangePlan(rawDodoId(sub.id), params),
@@ -273,7 +272,13 @@ export async function previewPaymentPlanChange(
direction: rule.direction,
planId: target.plan_id,
interval: target.interval,
- renewalAmount: target.effective_price,
+ renewalAmount:
+ quote.new_plan.tax_inclusive === true &&
+ quote.new_plan.currency === target.currency &&
+ Number.isSafeInteger(quote.new_plan.recurring_pre_tax_amount) &&
+ quote.new_plan.recurring_pre_tax_amount >= 0
+ ? quote.new_plan.recurring_pre_tax_amount
+ : target.effective_price,
currency: target.currency,
charge: quote.immediate_charge.summary,
effectiveAt: quote.immediate_charge.effective_at,
@@ -365,7 +370,6 @@ export async function commitPaymentPlanChange(
quantity: 1,
...mode(row.direction),
on_payment_failure: 'prevent_change',
- discount_codes: [],
metadata: { ...actual.metadata, chronoframe_change_id: id },
},
{ headers: { 'Idempotency-Key': `cf-change-${id}` } },
diff --git a/tests/dodo-payments.test.ts b/tests/dodo-payments.test.ts
index 50a993f4..57566f44 100644
--- a/tests/dodo-payments.test.ts
+++ b/tests/dodo-payments.test.ts
@@ -188,6 +188,30 @@ async function fixture() {
return Response.json({ items: [...subscriptions.values()] })
if (url.pathname === '/payments')
return Response.json({ items: [...payments.values()] })
+ if (url.pathname.endsWith('/line-items')) {
+ const payment = payments.get(url.pathname.split('/')[2]!)
+ const sub = subscriptions.get(payment.subscription_id)
+ const currency =
+ url.searchParams.get('currency') ??
+ payment.settlement_currency ??
+ payment.currency
+ const total =
+ currency === payment.currency
+ ? payment.total_amount
+ : payment.settlement_amount
+ return Response.json(
+ payment.lineItems ?? {
+ currency,
+ items: [
+ {
+ items_id: sub.product_id,
+ amount: total - (payment.tax ?? 0),
+ tax: payment.tax ?? 0,
+ },
+ ],
+ },
+ )
+ }
if (url.pathname.startsWith('/payments/'))
return Response.json(payments.get(url.pathname.split('/')[2]!))
throw Error('Unexpected request ' + url.href)
@@ -1650,7 +1674,7 @@ async function changeFixture() {
if (url.pathname.endsWith('/change-plan')) {
mutations.push(body)
assert.equal(body.on_payment_failure, 'prevent_change')
- assert.deepEqual(body.discount_codes, [])
+ assert.equal(body.discount_codes, undefined)
if (outcome === 'timeout') throw Error('network after provider accepted')
if (outcome === 'reject')
return Response.json({ code: 'invalid' }, { status: 422 })
@@ -3413,3 +3437,485 @@ test('unpaid deferred authorization can be canceled without extending the origin
await f.mf.dispose()
}
})
+
+function coupon(
+ payment: any,
+ productId: string,
+ type = 'percentage',
+ amount = 2000,
+ position = 0,
+) {
+ payment.business_id = 'bus_fixture'
+ return {
+ discount_id: 'dsc_fixture_' + position,
+ business_id: payment.business_id,
+ code: 'SAVE' + position,
+ type,
+ amount,
+ position,
+ restricted_to: [productId],
+ }
+}
+for (const kind of [
+ 'percentage',
+ 'flat',
+ 'stacked',
+ 'free',
+ 'adaptive',
+ 'taxed',
+])
+ test(`hosted checkout coupons fulfill verified ${kind} invoices without changing catalog prices`, async () => {
+ const f = await fixture()
+ try {
+ await syncDodoProducts(f.db, root, f.transport)
+ const checkout = await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ input(),
+ origin,
+ f.transport,
+ f.now,
+ )
+ const request = f.calls.find(
+ (c) => new URL(c.url).pathname === '/checkouts' && c.method === 'POST',
+ )!
+ assert.equal(request.body.feature_flags.allow_discount_code, true)
+ const { payment, sub } = await f.paid(checkout)
+ const paid = payment as any
+ paid.discounts = [
+ coupon(
+ paid,
+ sub.product_id,
+ kind === 'flat' ? 'flat' : 'percentage',
+ kind === 'free' ? 10000 : 2000,
+ ),
+ ]
+ paid.total_amount = kind === 'free' ? 0 : kind === 'flat' ? 1000 : 960
+ if (kind === 'stacked') {
+ paid.discounts.push(coupon(paid, sub.product_id, 'flat', 100, 1))
+ paid.total_amount = 860
+ }
+ if (kind === 'adaptive') {
+ paid.currency = 'CNY'
+ paid.total_amount = 6800
+ paid.settlement_currency = 'USD'
+ paid.settlement_amount = 960
+ }
+ if (kind === 'taxed') paid.tax = 160
+ if (kind === 'free') {
+ paid.service_periods = []
+ paid.charge_type = 'new'
+ }
+ assert.equal(
+ (
+ await refreshDodoCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.id,
+ f.transport,
+ f.now + 1000,
+ )
+ ).state,
+ 'completed',
+ )
+ assert.equal(
+ (
+ await f.db
+ .prepare(
+ 'SELECT plan_id FROM platform_workspace_plans WHERE workspace_id=1',
+ )
+ .first<any>()
+ ).plan_id,
+ 'pro',
+ )
+ assert.equal(
+ (
+ await f.db
+ .prepare('SELECT price FROM platform_payment_checkouts WHERE id=?')
+ .bind(checkout.id)
+ .first<any>()
+ ).price,
+ 1200,
+ )
+ assert.equal(
+ (
+ await f.db
+ .prepare("SELECT monthly_price FROM platform_plans WHERE id='pro'")
+ .first<any>()
+ ).monthly_price,
+ 1200,
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+ })
+test('coupon scope, business and invoice mismatches cannot fulfill discounted payments; legacy checkouts stay strict', async () => {
+ const f = await fixture()
+ try {
+ await syncDodoProducts(f.db, root, f.transport)
+ const checkout = await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ input(),
+ origin,
+ f.transport,
+ f.now,
+ )
+ const { payment, sub } = await f.paid(checkout),
+ paid = payment as any
+ paid.total_amount = 600
+ const valid = coupon(paid, sub.product_id)
+ for (const invalid of [
+ [],
+ [{ ...valid, restricted_to: ['other_product'] }],
+ [{ ...valid, business_id: 'other_business' }],
+ [{ ...valid, position: 2 }],
+ [{ ...valid, type: 'unknown' }],
+ ]) {
+ paid.discounts = invalid
+ await assert.rejects(
+ refreshDodoCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.id,
+ f.transport,
+ f.now + 1000,
+ ),
+ { code: 'payment_amount_mismatch' },
+ )
+ }
+ paid.discounts = [valid]
+ for (const lines of [
+ {
+ currency: 'USD',
+ items: [{ items_id: 'wrong_product', amount: 600, tax: 0 }],
+ },
+ {
+ currency: 'USD',
+ items: [{ items_id: sub.product_id, amount: 500, tax: 0 }],
+ },
+ {
+ currency: 'EUR',
+ items: [{ items_id: sub.product_id, amount: 600, tax: 0 }],
+ },
+ ]) {
+ paid.lineItems = lines
+ await assert.rejects(
+ refreshDodoCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.id,
+ f.transport,
+ f.now + 1000,
+ ),
+ { code: 'payment_amount_mismatch' },
+ )
+ }
+ delete paid.lineItems
+ await f.db
+ .prepare(
+ 'UPDATE platform_payment_checkouts SET coupon_enabled=0 WHERE id=?',
+ )
+ .bind(checkout.id)
+ .run()
+ await assert.rejects(
+ refreshDodoCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.id,
+ f.transport,
+ f.now + 1000,
+ ),
+ { code: 'payment_amount_mismatch' },
+ )
+ assert.equal(
+ (
+ await f.db
+ .prepare(
+ 'SELECT plan_id FROM platform_workspace_plans WHERE workspace_id=1',
+ )
+ .first<any>()
+ ).plan_id,
+ 'free',
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+})
+
+test('coupons combine with catalog discounts, renew at the billed amount, then expire back to the base contract', async () => {
+ const f = await fixture()
+ try {
+ await f.db
+ .prepare(
+ "UPDATE platform_plans SET monthly_discount_bps=1000,revision=revision+1 WHERE id='pro'",
+ )
+ .run()
+ await syncDodoProducts(f.db, root, f.transport)
+ const checkout = await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ input(),
+ origin,
+ f.transport,
+ f.now,
+ )
+ const { sub, payment } = await f.paid(checkout),
+ paid = payment as any
+ paid.discounts = [coupon(paid, sub.product_id)]
+ paid.total_amount = 864
+ await refreshDodoCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.id,
+ f.transport,
+ f.now + 1000,
+ )
+ const initial = await f.db
+ .prepare('SELECT * FROM platform_workspace_plans WHERE workspace_id=1')
+ .first<any>()
+ const { reconcileDodoSubscription } =
+ await import('../packages/platform/src/dodo-payments.ts')
+ for (const [index, total, discounted] of [
+ [1, 0, true],
+ [2, 1080, false],
+ ] as const) {
+ const start = f.now + index * 28 * 86400000,
+ end = start + 28 * 86400000
+ sub.previous_billing_date = new Date(start).toISOString()
+ sub.next_billing_date = new Date(end).toISOString()
+ const renewal = {
+ ...paid,
+ payment_id: 'pay_coupon_cycle_' + index,
+ charge_type: 'renewal',
+ total_amount: total,
+ discounts: discounted
+ ? [coupon(paid, sub.product_id, 'percentage', 10000)]
+ : [],
+ created_at: new Date(start).toISOString(),
+ service_periods: discounted
+ ? []
+ : [
+ {
+ subscription_id: sub.subscription_id,
+ starts_at: sub.previous_billing_date,
+ ends_at: sub.next_billing_date,
+ },
+ ],
+ }
+ f.payments.set(renewal.payment_id, renewal)
+ await reconcileDodoSubscription(
+ f.db,
+ root,
+ 'test',
+ sub.subscription_id,
+ renewal.payment_id,
+ f.transport,
+ start + 1000,
+ 'dodo_test',
+ )
+ const grant = await f.db
+ .prepare('SELECT * FROM platform_workspace_plans WHERE workspace_id=1')
+ .first<any>()
+ assert.equal(grant.expires_at, end)
+ assert.equal(grant.starts_at, initial.starts_at)
+ }
+ } finally {
+ await f.mf.dispose()
+ }
+})
+test('a zero-dollar coupon is not a trial payment; it activates only at the reserved paid-cycle boundary', async () => {
+ const f = await handoverFixture()
+ try {
+ const { checkout, sub, payment, at } = await authorizeHandover(f)
+ const auth = payment as any
+ auth.discounts = [coupon(auth, sub.product_id, 'percentage', 10000)]
+ auth.charge_type = 'new'
+ await refreshDodoCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.id,
+ f.transport,
+ f.now + 2000,
+ )
+ assert.equal(
+ (
+ await f.db
+ .prepare(
+ 'SELECT source FROM platform_workspace_plans WHERE workspace_id=1',
+ )
+ .first<any>()
+ ).source,
+ 'activation',
+ )
+ sub.previous_billing_date = new Date(at).toISOString()
+ sub.next_billing_date = new Date(at + 28 * 86400000).toISOString()
+ const renewal = {
+ ...auth,
+ payment_id: 'pay_free_first_cycle',
+ charge_type: 'renewal',
+ created_at: new Date(at).toISOString(),
+ service_periods: [],
+ }
+ f.payments.set(renewal.payment_id, renewal)
+ assert.equal(
+ (
+ await refreshDodoCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.id,
+ f.transport,
+ at + 1000,
+ )
+ ).state,
+ 'completed',
+ )
+ const grant = await f.db
+ .prepare('SELECT * FROM platform_workspace_plans WHERE workspace_id=1')
+ .first<any>()
+ assert.equal(grant.source, 'payment')
+ assert.equal(grant.starts_at, at)
+ assert.equal(grant.expires_at, at + 28 * 86400000)
+ } finally {
+ await f.mf.dispose()
+ }
+})
+
+test('refunded coupon payments revoke only their linked grant without fetching refund-sensitive invoice details', async () => {
+ const f = await fixture()
+ try {
+ await syncDodoProducts(f.db, root, f.transport)
+ const checkout = await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ input(),
+ origin,
+ f.transport,
+ f.now,
+ )
+ const { sub, payment } = await f.paid(checkout),
+ paid = payment as any
+ paid.discounts = [coupon(paid, sub.product_id)]
+ paid.total_amount = 960
+ await refreshDodoCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.id,
+ f.transport,
+ f.now + 1000,
+ )
+ paid.refunds = [{ refund_id: 'ref_coupon', status: 'succeeded' }]
+ const noLines: typeof fetch = async (url, init) => {
+ if (String(url).includes('/line-items'))
+ assert.fail('a refund must not depend on line-item retrieval')
+ return f.transport(url, init)
+ }
+ await refreshDodoCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.id,
+ noLines,
+ f.now + 2000,
+ )
+ assert.equal(
+ (
+ await f.db
+ .prepare(
+ 'SELECT source FROM platform_workspace_plans WHERE workspace_id=1',
+ )
+ .first<any>()
+ ).source,
+ 'expired_default',
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+})
+
+test('a late trial authorization with a 100% coupon cannot become a paid cycle after the old entitlement expires', async () => {
+ const f = await handoverFixture()
+ try {
+ await f.db
+ .prepare(
+ 'UPDATE platform_workspace_plans SET expires_at=? WHERE workspace_id=1',
+ )
+ .bind(f.now + 6 * 3600000)
+ .run()
+ const checkout = await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ { ...input(), startMode: 'after_entitlement' },
+ origin,
+ f.transport,
+ f.now,
+ )
+ const { sub, payment, session } = await f.paid(checkout),
+ auth = payment as any
+ const authorizedAt = f.now + 12 * 3600000,
+ startsPaidAt = authorizedAt + 86400000
+ sub.trial_period_days = session.trial_period_days
+ sub.previous_billing_date = new Date(authorizedAt).toISOString()
+ sub.next_billing_date = new Date(startsPaidAt).toISOString()
+ auth.total_amount = 0
+ auth.charge_type = 'new'
+ auth.service_periods = []
+ auth.created_at = sub.previous_billing_date
+ auth.discounts = [coupon(auth, sub.product_id, 'percentage', 10000)]
+ assert.equal(
+ (
+ await refreshDodoCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.id,
+ f.transport,
+ authorizedAt + 1000,
+ )
+ ).state,
+ 'scheduled',
+ )
+ const ledger = await f.db
+ .prepare(
+ 'SELECT activation_state,handover_at FROM platform_payment_subscriptions',
+ )
+ .first<any>()
+ assert.equal(ledger.activation_state, 'authorized')
+ assert.equal(ledger.handover_at, startsPaidAt)
+ assert.equal(
+ (
+ await f.db
+ .prepare(
+ 'SELECT source FROM platform_workspace_plans WHERE workspace_id=1',
+ )
+ .first<any>()
+ ).source,
+ 'activation',
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+})