Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.
TypeScript albumsexif-extractiongeocodinglive-photomotion-photophoto-galleryphoto-sharingwebgl-viewer
fix(payments): require paid downgrade periods and settle abandoned changes
Timothy Yin199478a4677e
diff --git a/packages/platform/src/dodo-payments.ts b/packages/platform/src/dodo-payments.tsindex 4df8aec1..f2433a23 100644--- a/packages/platform/src/dodo-payments.ts+++ b/packages/platform/src/dodo-payments.ts@@ -707,24 +707,23 @@ export async function reconcileDodoSubscription(? payment.total_amount === checkout.price: payment.settlement_currency === checkout.currency &&payment.settlement_amount === checkout.price)- const successful =- !!confirmedChange ||- (payment?.status === 'succeeded' &&- !identityError &&- amountMatches &&- !payment.refunds?.length &&- !payment.disputes?.length)+ const paid =+ payment?.status === 'succeeded' &&+ !identityError &&+ amountMatches &&+ !payment.refunds?.length &&+ !payment.disputes?.length+ const successful = !!confirmedChange || paidif (!known && payment?.status === 'succeeded' && !successful) {if (payment.refunds?.length || payment.disputes?.length)fail('payment_refunded_or_disputed', 422)fail('payment_amount_mismatch', 422)}- const period =- successful && !confirmedChange- ? payment?.service_periods?.find(- (p) => p.subscription_id === subscriptionId,- )- : null+ const period = paid+ ? payment?.service_periods?.find(+ (p) => p.subscription_id === subscriptionId,+ )+ : nullif (!successful && !known) fail('payment_confirmation_pending')// Older Dodo responses can omit service_periods for the initial payment.// Only recover the first, checkout-bound period: subscription dates alone@@ -742,14 +741,16 @@ export async function reconcileDodoSubscription(Math.abs(initialStart - initialPaymentTime) <= 300000 &&initialEnd > now &&initialEnd - initialStart <= (checkout.interval * 31 + 1) * 86400000- let start = confirmedChange+ // Only a successful renewal can extend a scheduled downgrade's paid-through period.+ const sameCycleUpgrade = confirmedChange?.direction === 'upgrade'+ let start = sameCycleUpgrade? timestamp(subscription.previous_billing_date): period? timestamp(period.starts_at): initialPeriod? initialStart: known?.period_start- let end = confirmedChange+ let end = sameCycleUpgrade? timestamp(subscription.next_billing_date): period? timestamp(period.ends_at)@@ -927,6 +928,62 @@ export async function reconcileDodoSubscription(),)}+ if (+ known &&+ !confirmedChange &&+ subscription.product_id === known.product_id+ ) {+ const stale = await allRows<any>(+ db+ .prepare(+ "SELECT id,to_product,created_at FROM platform_payment_plan_changes WHERE subscription_id=? AND provider_key=? AND from_product=? AND state IN('submitting','pending','scheduled','uncertain') AND updated_at<?",+ )+ .bind(localId, key, known.product_id, now - 900000),+ )+ const abandoned = stale.filter(+ (change) =>+ subscription.scheduled_change?.product_id !== change.to_product,+ )+ if (abandoned.length) {+ // An unchanged product alone is insufficient while a charge still awaits settlement.+ const charges = await dodoRequest(() =>+ client.payments.list({+ subscription_id: subscriptionId,+ created_at_gte: new Date(+ Math.min(...abandoned.map((c) => c.created_at)) - 60000,+ ).toISOString(),+ page_size: 100,+ }),+ )+ for (const change of abandoned) {+ const unsettled =+ charges.items.length >= 100 ||+ charges.items.some(+ (p) =>+ (p.metadata?.chronoframe_change_id === change.id ||+ (!p.metadata?.chronoframe_change_id &&+ p.charge_type === 'plan_change' &&+ timestamp(p.created_at) >= change.created_at - 60000)) &&+ !['failed', 'cancelled'].includes(p.status ?? ''),+ )+ if (!unsettled)+ writes.push(+ db+ .prepare(+ `UPDATE platform_payment_plan_changes SET state='failed',updated_at=? WHERE id=? AND subscription_id=? AND from_product=? AND state IN('submitting','pending','scheduled','uncertain') AND updated_at<? AND ${fence}`,+ )+ .bind(+ now,+ change.id,+ localId,+ known.product_id,+ now - 900000,+ ...bindFence,+ ),+ )+ }+ }+ }await db.batch(writes)return checkout.id as string} catch (error) {diff --git a/tests/dodo-payments.test.ts b/tests/dodo-payments.test.tsindex bfc6fc33..b7f79702 100644--- a/tests/dodo-payments.test.ts+++ b/tests/dodo-payments.test.ts@@ -1823,7 +1823,62 @@ test('scheduled downgrades retain the paid tier until the provider switches at rconst later = f.now + 28 * 86400000f.applyScheduled(later)await checkPaymentPlanChange(f.db, root, 1, 1, f.transport, later)+ // The provider product switch alone must not buy the next billing period.+ assert.equal((await f.assignment()).plan_id, 'free')+ const unpaid = await f.db+ .prepare('SELECT period_end FROM platform_payment_subscriptions')+ .first<any>()+ assert.ok(unpaid.period_end <= later)+ f.sub.status = 'on_hold'+ await refreshDodoCheckout(+ f.db,+ root,+ 1,+ 1,+ f.checkout.id,+ f.transport,+ later,+ )+ assert.equal((await f.assignment()).plan_id, 'free')+ assert.equal(+ (+ await f.db+ .prepare('SELECT period_end FROM platform_payment_subscriptions')+ .first<any>()+ ).period_end,+ unpaid.period_end,+ )+ f.sub.status = 'active'+ const renewed = {+ ...f.payment,+ payment_id: 'pay_paid_downgrade',+ charge_type: 'renewal',+ created_at: new Date(later).toISOString(),+ service_periods: [+ {+ subscription_id: f.sub.subscription_id,+ starts_at: new Date(later).toISOString(),+ ends_at: new Date(later + 28 * 86400000).toISOString(),+ },+ ],+ }+ f.payments.set(renewed.payment_id, renewed)+ const event = await f.sign(+ 'payment.succeeded',+ renewed,+ 'evt_paid_downgrade',+ )+ await receiveDodoEvent(+ f.db,+ root,+ 'test',+ event.body,+ event.headers,+ f.transport,+ )+ await processDodoEvents(f.db, root, f.transport, later)assert.equal((await f.assignment()).plan_id, 'pro')+ assert.equal((await f.assignment()).expires_at, later + 28 * 86400000)assert.equal((await paymentStatus(f.db, 1, 1)).planChange, null)} finally {await f.mf.dispose()@@ -1988,3 +2043,77 @@ test('accepted changes await provider application; failed change payments retainawait f.mf.dispose()}})++for (const state of ['submitting', 'pending', 'scheduled', 'uncertain']) {+ test(`stale ${state} plan changes settle without retrying a charge, while live schedules and payments remain protected`, async () => {+ const f = await changeFixture()+ try {+ await f.rule('pro', 'studio')+ const quote = await previewPaymentPlanChange(+ f.db,+ root,+ 1,+ { workspaceId: 1, planId: 'studio' },+ f.transport,+ )+ await f.db+ .prepare('UPDATE platform_payment_plan_changes SET state=? WHERE id=?')+ .bind(state, quote.id)+ .run()+ const change = await f.db+ .prepare('SELECT * FROM platform_payment_plan_changes WHERE id=?')+ .bind(quote.id)+ .first<any>()+ const getState = async () =>+ (+ await f.db+ .prepare(+ 'SELECT state FROM platform_payment_plan_changes WHERE id=?',+ )+ .bind(quote.id)+ .first<any>()+ ).state+ await checkPaymentPlanChange(f.db, root, 1, 1, f.transport)+ assert.equal(await getState(), state) // Grace period has not elapsed.+ const later = Date.now() + 16 * 60000+ ;(f.sub as any).scheduled_change = { product_id: change.to_product }+ await checkPaymentPlanChange(f.db, root, 1, 1, f.transport, later)+ assert.equal(await getState(), state)+ ;(f.sub as any).scheduled_change = null+ const charge = {+ ...f.payment,+ payment_id: 'pay_unsettled_change',+ status: 'processing',+ charge_type: 'plan_change',+ created_at: new Date(change.created_at).toISOString(),+ metadata: { ...f.payment.metadata, chronoframe_change_id: quote.id },+ }+ f.payments.set(charge.payment_id, charge)+ await checkPaymentPlanChange(f.db, root, 1, 1, f.transport, later)+ assert.equal(await getState(), state)+ charge.status = 'succeeded' // A settled charge waiting for application is also protected.+ await checkPaymentPlanChange(f.db, root, 1, 1, f.transport, later)+ assert.equal(await getState(), state)+ f.payments.delete(charge.payment_id)+ ;(f.sub as any).scheduled_change = {+ product_id: 'pdt_some_other_schedule',+ }+ await checkPaymentPlanChange(f.db, root, 1, 1, f.transport, later)+ assert.equal(await getState(), 'failed')+ assert.equal((await paymentStatus(f.db, 1, 1)).planChange, null)+ assert.equal((await f.assignment()).plan_id, 'pro')+ assert.equal(f.mutations.length, 0)+ ;(f.sub as any).scheduled_change = null+ await previewPaymentPlanChange(+ f.db,+ root,+ 1,+ { workspaceId: 1, planId: 'studio' },+ f.transport,+ )+ assert.equal(f.mutations.length, 0)+ } finally {+ await f.mf.dispose()+ }+ })+}