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.

fix(billing): reconcile inactive discounted subscriptions without invoice dependency

Timothy Yin0d3b9497567b
diff --git a/packages/platform/src/dodo-payments.ts b/packages/platform/src/dodo-payments.ts
index 43ac1e55..046bad0c 100644
--- a/packages/platform/src/dodo-payments.ts
+++ b/packages/platform/src/dodo-payments.ts
@@ -812,6 +812,7 @@ export async function reconcileDodoSubscription(
const couponMatches =
!identityError &&
payment &&
+ (!known || subscription.status === 'active') &&
(await discountedPaymentMatches(client, checkout, payment))
const amountMatches =
couponMatches ||
diff --git a/packages/platform/src/payment-discounts.ts b/packages/platform/src/payment-discounts.ts
index cbe0308e..8f067e0b 100644
--- a/packages/platform/src/payment-discounts.ts
+++ b/packages/platform/src/payment-discounts.ts
@@ -1,7 +1,18 @@
+import type DodoPayments from 'dodopayments'
+import type { Payment } from 'dodopayments/resources/payments'
+import type { Subscription } from 'dodopayments/resources/subscriptions'
import { dodoRequest } from './dodo-client.ts'
+interface DiscountCheckout {
+ coupon_enabled: number
+ product_id: string
+ currency: string
+ price: number
+ interval: number
+}
+
/** Applied discount snapshots are read only from the authenticated payment response. */
-export function appliedDiscounts(payment: any, checkout: any) {
+export function appliedDiscounts(payment: Payment, checkout: DiscountCheckout) {
if (
!checkout.coupon_enabled ||
!Array.isArray(payment?.discounts) ||
@@ -32,15 +43,15 @@ export function appliedDiscounts(payment: any, checkout: any) {
}
return (
!payment.discount_id ||
- payment.discount_id === payment.discounts[0].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,
+ client: Pick<DodoPayments, 'payments'>,
+ checkout: DiscountCheckout,
+ payment: Payment,
) {
if (
!appliedDiscounts(payment, checkout) ||
@@ -59,23 +70,25 @@ export async function discountedPaymentMatches(
? payment.settlement_amount
: null
if (
+ expected === null ||
!Number.isSafeInteger(expected) ||
expected < 0 ||
expected > checkout.price
)
return false
- const lines = (await dodoRequest(() =>
+ 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 &&
item.items_id === checkout.product_id &&
Number.isSafeInteger(item.amount) &&
item.amount >= 0 &&
@@ -88,9 +101,9 @@ export async function discountedPaymentMatches(
/** 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,
+ payment: Payment,
+ subscription: Subscription,
+ checkout: DiscountCheckout,
notBefore: number,
) {
if (
@@ -100,7 +113,7 @@ export function freeDiscountPeriod(
payment.includes_usage ||
payment.is_update_payment_method ||
payment.is_multi_subscription ||
- !['new', 'renewal'].includes(payment.charge_type) ||
+ !['new', 'renewal'].includes(payment.charge_type ?? '') ||
subscription.status !== 'active' ||
payment.service_periods?.length
)
diff --git a/tests/dodo-payments.test.ts b/tests/dodo-payments.test.ts
index 57566f44..91998726 100644
--- a/tests/dodo-payments.test.ts
+++ b/tests/dodo-payments.test.ts
@@ -3919,3 +3919,81 @@ test('a late trial authorization with a 100% coupon cannot become a paid cycle a
await f.mf.dispose()
}
})
+
+for (const providerStatus of ['cancelled', 'expired'] as const) {
+ test(`known discounted ${providerStatus} subscription revokes access without line-item availability`, 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,
+ )
+ const before = await f.db
+ .prepare(
+ 'SELECT * FROM platform_payment_subscriptions WHERE checkout_id=?',
+ )
+ .bind(checkout.id)
+ .first<any>()
+ assert.equal(before.status, 'active')
+ sub.status = providerStatus
+ let lineRequests = 0
+ const unavailable: typeof fetch = async (url, options) => {
+ if (String(url).includes('/line-items')) {
+ lineRequests++
+ return Response.json({ message: 'Unavailable' }, { status: 503 })
+ }
+ return f.transport(url, options)
+ }
+ const { reconcileDodoSubscription } =
+ await import('../packages/platform/src/dodo-payments.ts')
+ await reconcileDodoSubscription(
+ f.db,
+ root,
+ 'test',
+ sub.subscription_id,
+ paid.payment_id,
+ unavailable,
+ f.now + 2000,
+ 'dodo_test',
+ )
+ const after = await f.db
+ .prepare(
+ 'SELECT * FROM platform_payment_subscriptions WHERE checkout_id=?',
+ )
+ .bind(checkout.id)
+ .first<any>()
+ assert.equal(lineRequests, 0)
+ assert.equal(
+ after.status,
+ providerStatus === 'cancelled' ? 'canceled' : providerStatus,
+ )
+ assert.equal(after.period_end, before.period_end)
+ const grant = await f.db
+ .prepare('SELECT * FROM platform_workspace_plans WHERE workspace_id=1')
+ .first<any>()
+ assert.equal(grant.source, 'expired_default')
+ assert.equal(grant.plan_id, 'free')
+ } finally {
+ await f.mf.dispose()
+ }
+ })
+}