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 Creem customer portal resubscriptions

Timothy Yin5e49d0b1dd2e
diff --git a/apps/cloud/app/composables/useCheckoutReturn.ts b/apps/cloud/app/composables/useCheckoutReturn.ts
index 0b0590b2..a85b03d2 100644
--- a/apps/cloud/app/composables/useCheckoutReturn.ts
+++ b/apps/cloud/app/composables/useCheckoutReturn.ts
@@ -5,7 +5,14 @@ export function useCheckoutReturn(
) {
const route = useRoute(),
state = ref<
- 'idle' | 'checking' | 'pending' | 'completed' | 'failed' | 'expired'
+ | 'idle'
+ | 'checking'
+ | 'pending'
+ | 'completed'
+ | 'failed'
+ | 'expired'
+ | 'inactive'
+ | 'superseded'
>(typeof route.query.checkout === 'string' ? 'checking' : 'idle')
let generation = 0,
alive = true,
@@ -28,14 +35,26 @@ export function useCheckoutReturn(
'/api/billing/payments',
{
method: 'POST',
- body: { action: 'refresh', workspaceId: id, checkoutId },
+ body: {
+ action: 'refresh',
+ workspaceId: id,
+ checkoutId,
+ providerCheckoutId:
+ typeof route.query.checkout_id === 'string'
+ ? route.query.checkout_id
+ : undefined,
+ subscriptionId:
+ typeof route.query.subscription_id === 'string'
+ ? route.query.subscription_id
+ : undefined,
+ },
},
)
if (!alive || current !== generation) return
await refresh()
if (!alive || current !== generation) return
- if (result.state === 'completed') {
- state.value = 'completed'
+ if (['completed', 'inactive', 'superseded'].includes(result.state)) {
+ state.value = result.state as 'completed' | 'inactive' | 'superseded'
return
}
if (result.state === 'expired') {
@@ -44,7 +63,7 @@ export function useCheckoutReturn(
}
} catch (e: any) {
if (!alive || current !== generation) return
- if ([400, 401, 403, 404].includes(e?.statusCode ?? e?.status)) {
+ if ([400, 401, 403, 404, 422].includes(e?.statusCode ?? e?.status)) {
state.value = 'failed'
return
}
@@ -59,7 +78,12 @@ export function useCheckoutReturn(
}
onMounted(() => {
watch(
- () => [route.query.checkout, toValue(workspaceId)],
+ () => [
+ route.query.checkout,
+ route.query.checkout_id,
+ route.query.subscription_id,
+ toValue(workspaceId),
+ ],
() => void check(),
{ immediate: true },
)
diff --git a/apps/cloud/i18n/locales/en.json b/apps/cloud/i18n/locales/en.json
index bc41bbeb..c865ea92 100644
--- a/apps/cloud/i18n/locales/en.json
+++ b/apps/cloud/i18n/locales/en.json
@@ -712,7 +712,9 @@
"return_completed": "Payment confirmed. Your plan and allowances are up to date.",
"return_failed": "We could not verify this checkout. Check your account or try again.",
"return_expired": "This checkout has expired. You can start a new one from the plans below.",
- "checkAgain": "Check payment status"
+ "checkAgain": "Check payment status",
+ "return_inactive": "This subscription is no longer active. Your current plan and usage are shown below.",
+ "return_superseded": "Payment confirmed. Your current plan is controlled by another entitlement; contact support if you need help."
},
"dashboard": {
"workspaceOverview": "Workspace overview",
diff --git a/apps/cloud/i18n/locales/zh-Hans.json b/apps/cloud/i18n/locales/zh-Hans.json
index fec566d5..07fe753d 100644
--- a/apps/cloud/i18n/locales/zh-Hans.json
+++ b/apps/cloud/i18n/locales/zh-Hans.json
@@ -712,7 +712,9 @@
"return_completed": "付款已确认,套餐与额度已更新。",
"return_failed": "无法核验这笔付款,请检查登录账号或重试。",
"return_expired": "这笔付款已过期,可以在下方选择套餐重新发起。",
- "checkAgain": "检查付款状态"
+ "checkAgain": "检查付款状态",
+ "return_inactive": "此订阅已不再生效。当前套餐与用量如下。",
+ "return_superseded": "付款已确认,当前套餐由其他授权管理。如需帮助,请联系客服。"
},
"dashboard": {
"workspaceOverview": "工作区概览",
diff --git a/apps/cloud/server/api/billing/payments.post.ts b/apps/cloud/server/api/billing/payments.post.ts
index 170471ae..aa464ad0 100644
--- a/apps/cloud/server/api/billing/payments.post.ts
+++ b/apps/cloud/server/api/billing/payments.post.ts
@@ -37,6 +37,16 @@ export default definePlatformHandler(async (event) => {
user.userId,
Number(b.workspaceId),
String(b.checkoutId),
+ undefined,
+ undefined,
+ {
+ providerCheckoutId:
+ b.providerCheckoutId === undefined
+ ? undefined
+ : String(b.providerCheckoutId),
+ subscriptionId:
+ b.subscriptionId === undefined ? undefined : String(b.subscriptionId),
+ },
)
if (b.action === 'portal')
return createPaymentPortal(
diff --git a/packages/platform/migrations/0024_payment_resubscription_lineage.sql b/packages/platform/migrations/0024_payment_resubscription_lineage.sql
new file mode 100644
index 00000000..1fe360ed
--- /dev/null
+++ b/packages/platform/migrations/0024_payment_resubscription_lineage.sql
@@ -0,0 +1,3 @@
+ALTER TABLE platform_payment_checkouts ADD COLUMN origin_checkout_id TEXT REFERENCES platform_payment_checkouts(id);
+ALTER TABLE platform_payment_checkouts ADD COLUMN predecessor_subscription_id TEXT REFERENCES platform_payment_subscriptions(id) ON DELETE SET NULL;
+CREATE INDEX platform_payment_checkout_origin ON platform_payment_checkouts(origin_checkout_id);
diff --git a/packages/platform/src/payments.ts b/packages/platform/src/payments.ts
index 95a8100e..c14cb95e 100644
--- a/packages/platform/src/payments.ts
+++ b/packages/platform/src/payments.ts
@@ -715,6 +715,103 @@ export async function receivePaymentEvent(
return { received: true }
}
+async function paymentRecordId(prefix: string, providerId: string) {
+ const hash = await crypto.subtle.digest('SHA-256', enc.encode(providerId))
+ return (
+ prefix +
+ '_' +
+ [...new Uint8Array(hash)]
+ .map((v) => v.toString(16).padStart(2, '0'))
+ .join('')
+ )
+}
+/** A portal repurchase is a new immutable checkout, linked to a proven prior subscription. */
+async function portalResubscriptionCheckout(
+ db: PlatformD1,
+ origin: any,
+ c: any,
+ s: any,
+ credentials: PaymentSecrets,
+ transport: PaymentFetch,
+ now: number,
+) {
+ const predecessorId = c.metadata?.resubscribed_from_subscription_id
+ if (
+ origin.state !== 'completed' ||
+ !origin.provider_id ||
+ !identifier(predecessorId) ||
+ s.metadata?.resubscribed_from_subscription_id !== predecessorId ||
+ s.metadata?.chronoframe_checkout_id !== origin.id ||
+ !checkoutBound(c, origin.id)
+ )
+ fail(422, 'payment_binding_invalid')
+ const predecessor = await db
+ .prepare(
+ 'SELECT s.*,c.origin_checkout_id,c.user_id FROM platform_payment_subscriptions s JOIN platform_payment_checkouts c ON c.id=s.checkout_id WHERE s.id=?',
+ )
+ .bind(predecessorId)
+ .first<any>()
+ if (
+ !predecessor ||
+ predecessor.workspace_id !== origin.workspace_id ||
+ predecessor.user_id !== origin.user_id ||
+ ![predecessor.checkout_id, predecessor.origin_checkout_id].includes(
+ origin.id,
+ ) ||
+ predecessor.customer_id !== objectId(c.customer) ||
+ predecessor.customer_id !== objectId(s.customer)
+ )
+ fail(422, 'payment_binding_invalid')
+ await paymentMember(db, origin.user_id, origin.workspace_id, true)
+ const old = await creemRequest(
+ credentials,
+ '/v1/subscriptions?subscription_id=' + encodeURIComponent(predecessorId),
+ undefined,
+ transport,
+ )
+ if (
+ old.id !== predecessorId ||
+ old.mode !== 'test' ||
+ !['canceled', 'expired'].includes(old.status) ||
+ objectId(old.customer) !== predecessor.customer_id
+ )
+ fail(422, 'payment_binding_invalid')
+ const mapping = await db
+ .prepare(
+ 'SELECT * FROM platform_payment_products WHERE product_id=? AND enabled=1',
+ )
+ .bind(objectId(c.product))
+ .first<any>()
+ if (!mapping || objectId(s.product) !== mapping.product_id)
+ fail(422, 'payment_product_unavailable')
+ const quote = await validatePaymentProduct(
+ db,
+ credentials,
+ mapping.plan_id,
+ mapping.interval,
+ mapping.product_id,
+ transport,
+ )
+ return {
+ ...origin,
+ id: await paymentRecordId('resub', c.id),
+ origin_checkout_id: origin.id,
+ predecessor_subscription_id: predecessorId,
+ provider_id: c.id,
+ request_id: 'portal_' + crypto.randomUUID(),
+ plan_id: mapping.plan_id,
+ interval: mapping.interval,
+ product_id: mapping.product_id,
+ price: quote.price,
+ currency: quote.currency,
+ checkout_url: null,
+ state: 'completed',
+ error: null,
+ created_at: now,
+ updated_at: now,
+ }
+}
+
async function synchronizePayment(
db: PlatformD1,
rootKey: string,
@@ -723,7 +820,10 @@ async function synchronizePayment(
now: number,
) {
const credentials = await paymentSecrets(db, rootKey)
- let checkout: any, providerCheckout: any, subscriptionId: string
+ let checkout: any,
+ providerCheckout: any,
+ subscriptionId: string,
+ awaitingPortalCheckout = false
if (event.type === 'checkout.completed') {
providerCheckout = await creemRequest(
credentials,
@@ -731,16 +831,26 @@ async function synchronizePayment(
undefined,
transport,
)
- checkout = await db
- .prepare('SELECT * FROM platform_payment_checkouts WHERE id=?')
- .bind(
- String(
- providerCheckout.request_id ??
- providerCheckout.metadata?.chronoframe_checkout_id ??
- '',
- ),
- )
- .first<any>()
+ if (
+ providerCheckout.id !== event.object_id ||
+ providerCheckout.mode !== 'test'
+ )
+ fail(422, 'payment_binding_invalid')
+ checkout =
+ (await db
+ .prepare('SELECT * FROM platform_payment_checkouts WHERE provider_id=?')
+ .bind(providerCheckout.id)
+ .first<any>()) ??
+ (await db
+ .prepare('SELECT * FROM platform_payment_checkouts WHERE id=?')
+ .bind(
+ String(
+ providerCheckout.request_id ??
+ providerCheckout.metadata?.chronoframe_checkout_id ??
+ '',
+ ),
+ )
+ .first<any>())
subscriptionId = objectId(providerCheckout.subscription)
} else {
const known = await db
@@ -769,6 +879,10 @@ async function synchronizePayment(
),
)
.first<any>()
+ // The new subscription's metadata identifies the origin, not its new checkout ID.
+ // Wait for checkout.completed (or an authenticated return) to prove that checkout.
+ awaitingPortalCheckout =
+ !known && !!probe?.metadata?.resubscribed_from_subscription_id
subscriptionId = event.object_id
}
if (!checkout || !checkout.user_id) {
@@ -779,6 +893,7 @@ async function synchronizePayment(
return 'ignored'
}
if (checkout.error === 'payment_test_abandoned') return 'ignored'
+ if (awaitingPortalCheckout) fail(409, 'payment_confirmation_pending')
if (!identifier(subscriptionId)) fail(409, 'payment_confirmation_pending')
const token = await acquireWorkspace(db, checkout.workspace_id, now)
try {
@@ -810,11 +925,24 @@ async function synchronizePayment(
transport,
)
}
+ const stored = await db
+ .prepare('SELECT * FROM platform_payment_checkouts WHERE provider_id=?')
+ .bind(providerCheckout.id)
+ .first<any>()
+ if (stored) {
+ if (
+ stored.workspace_id !== checkout.workspace_id ||
+ stored.user_id !== checkout.user_id
+ )
+ fail(422, 'payment_binding_invalid')
+ checkout = stored
+ }
if (
+ !identifier(providerCheckout.id) ||
+ (event.type === 'checkout.completed' &&
+ providerCheckout.id !== event.object_id) ||
providerCheckout.mode !== 'test' ||
providerCheckout.status !== 'completed' ||
- !checkoutBound(providerCheckout, checkout.id) ||
- objectId(providerCheckout.product) !== checkout.product_id ||
objectId(providerCheckout.subscription) !== subscriptionId ||
s.id !== subscriptionId ||
s.mode !== 'test' ||
@@ -822,6 +950,31 @@ async function synchronizePayment(
!identifier(objectId(s.customer))
)
fail(422, 'payment_binding_invalid')
+ const materialize = providerCheckout.id !== checkout.provider_id
+ if (materialize)
+ checkout = await portalResubscriptionCheckout(
+ db,
+ checkout,
+ providerCheckout,
+ s,
+ credentials,
+ transport,
+ now,
+ )
+ if (
+ !checkoutBound(
+ providerCheckout,
+ checkout.origin_checkout_id ?? checkout.id,
+ ) ||
+ objectId(providerCheckout.product) !== checkout.product_id ||
+ (checkout.predecessor_subscription_id &&
+ (providerCheckout.metadata?.resubscribed_from_subscription_id !==
+ checkout.predecessor_subscription_id ||
+ s.metadata?.resubscribed_from_subscription_id !==
+ checkout.predecessor_subscription_id ||
+ s.metadata?.chronoframe_checkout_id !== checkout.origin_checkout_id))
+ )
+ fail(422, 'payment_binding_invalid')
const known = await db
.prepare('SELECT * FROM platform_payment_subscriptions WHERE id=?')
.bind(subscriptionId)
@@ -901,9 +1054,13 @@ async function synchronizePayment(
const canAssign = known
? prior?.payment_subscription_id === subscriptionId &&
['payment', 'expired_default'].includes(prior.source)
- : (prior?.revision ?? 0) === checkout.assignment_revision ||
- (prior?.source === 'expired_default' &&
- prior.revision === checkout.assignment_revision + 1)
+ : checkout.predecessor_subscription_id
+ ? prior?.payment_subscription_id ===
+ checkout.predecessor_subscription_id &&
+ ['payment', 'expired_default'].includes(prior.source)
+ : (prior?.revision ?? 0) === checkout.assignment_revision ||
+ (prior?.source === 'expired_default' &&
+ prior.revision === checkout.assignment_revision + 1)
const entitled = [
'active',
'trialing',
@@ -968,6 +1125,34 @@ async function synchronizePayment(
environment: 'test',
}
const statements = [
+ ...(materialize
+ ? [
+ db
+ .prepare(
+ `INSERT OR IGNORE INTO platform_payment_checkouts(id,workspace_id,user_id,request_id,plan_id,interval,product_id,price,currency,assignment_revision,provider_id,checkout_url,state,created_at,updated_at,origin_checkout_id,predecessor_subscription_id) SELECT ?,?,?,?,?,?,?,?,?,?,?,NULL,'completed',?,?,?,? WHERE ${fence}`,
+ )
+ .bind(
+ checkout.id,
+ checkout.workspace_id,
+ checkout.user_id,
+ checkout.request_id,
+ checkout.plan_id,
+ checkout.interval,
+ checkout.product_id,
+ checkout.price,
+ checkout.currency,
+ prior?.revision ?? 0,
+ checkout.provider_id,
+ now,
+ now,
+ checkout.origin_checkout_id,
+ checkout.predecessor_subscription_id,
+ checkout.workspace_id,
+ token,
+ now,
+ ),
+ ]
+ : []),
db
.prepare(
`INSERT INTO platform_subscription_events(id,workspace_id,kind,before_json,after_json,created_at) SELECT ?,?,'payment',?,?,? WHERE ${fence}`,
@@ -1048,7 +1233,8 @@ async function synchronizePayment(
)
}
const results = await db.batch(statements)
- if (!results[0]?.meta.changes) fail(409, 'payment_lease_lost')
+ if (!results[materialize ? 1 : 0]?.meta.changes)
+ fail(409, 'payment_lease_lost')
return 'done'
} finally {
await releaseWorkspace(db, checkout.workspace_id, token)
@@ -1375,9 +1561,16 @@ export async function refreshPaymentCheckout(
checkoutId: string,
transport: PaymentFetch = fetch,
now = Date.now(),
+ hints: { providerCheckoutId?: string; subscriptionId?: string } = {},
) {
await paymentMember(db, userId, workspaceId, true)
- if (!identifier(checkoutId)) fail(400, 'payment_checkout_invalid')
+ if (
+ !identifier(checkoutId) ||
+ (hints.providerCheckoutId !== undefined &&
+ !identifier(hints.providerCheckoutId)) ||
+ (hints.subscriptionId !== undefined && !identifier(hints.subscriptionId))
+ )
+ fail(400, 'payment_checkout_invalid')
await paymentRequestBudget(db, userId, now)
const row = await db
.prepare(
@@ -1386,50 +1579,73 @@ export async function refreshPaymentCheckout(
.bind(checkoutId, workspaceId, userId)
.first<any>()
if (!row) fail(404, 'payment_checkout_unavailable')
- if (['completed', 'expired'].includes(row.state)) return { state: row.state }
- if (!row.provider_id) return { state: 'pending' }
+ const providerId = hints.providerCheckoutId ?? row.provider_id
+ if (!providerId) return { state: 'pending' }
+ if (row.state === 'expired' && providerId === row.provider_id)
+ return { state: 'expired' }
const checkout = await creemRequest(
await paymentSecrets(db, rootKey),
- '/v1/checkouts?checkout_id=' + encodeURIComponent(row.provider_id),
+ '/v1/checkouts?checkout_id=' + encodeURIComponent(providerId),
undefined,
transport,
)
if (
- checkout.id !== row.provider_id ||
+ checkout.id !== providerId ||
checkout.mode !== 'test' ||
- !checkoutBound(checkout, row.id) ||
- objectId(checkout.product) !== row.product_id
+ !checkoutBound(checkout, row.origin_checkout_id ?? row.id) ||
+ (providerId === row.provider_id &&
+ objectId(checkout.product) !== row.product_id) ||
+ (hints.subscriptionId !== undefined &&
+ objectId(checkout.subscription) !== hints.subscriptionId)
)
fail(422, 'payment_binding_invalid')
if (checkout.status === 'expired') {
- await db
- .prepare(
- "UPDATE platform_payment_checkouts SET state='expired',updated_at=?,error=NULL WHERE id=? AND state IN('open','uncertain')",
- )
- .bind(now, row.id)
- .run()
+ if (providerId === row.provider_id)
+ await db
+ .prepare(
+ "UPDATE platform_payment_checkouts SET state='expired',updated_at=?,error=NULL WHERE id=? AND state IN('open','uncertain')",
+ )
+ .bind(now, row.id)
+ .run()
const current = await db
.prepare('SELECT state FROM platform_payment_checkouts WHERE id=?')
.bind(row.id)
.first<any>()
return {
- state: ['expired', 'completed'].includes(current?.state)
- ? current.state
- : 'pending',
+ state:
+ providerId === row.provider_id && current?.state === 'completed'
+ ? 'pending'
+ : 'expired',
}
}
if (checkout.status !== 'completed') return { state: 'pending' }
- const eventId = 'return_' + row.id
+ // Bounded authenticated reads reconcile current provider truth, including historical returns.
+ const eventId = 'return_' + crypto.randomUUID()
await db
.prepare(
- "INSERT OR IGNORE INTO platform_payment_events(id,type,object_id,reference_id,created_at,available_at) VALUES(?,'checkout.completed',?,?,?,?)",
+ "INSERT INTO platform_payment_events(id,type,object_id,reference_id,created_at,available_at) VALUES(?,'checkout.completed',?,?,?,?)",
)
- .bind(eventId, row.provider_id, row.id, now, now)
+ .bind(eventId, providerId, row.id, now, now)
.run()
await processPaymentEvents(db, rootKey, transport, now, 1, eventId)
const current = await db
- .prepare('SELECT state FROM platform_payment_checkouts WHERE id=?')
- .bind(row.id)
+ .prepare(
+ 'SELECT s.id,s.status,s.period_end,p.payment_subscription_id,p.source FROM platform_payment_subscriptions s JOIN platform_payment_checkouts c ON c.id=s.checkout_id JOIN platform_workspace_plans p ON p.workspace_id=s.workspace_id WHERE c.provider_id=? AND c.workspace_id=? AND c.user_id=?',
+ )
+ .bind(providerId, workspaceId, userId)
.first<any>()
- return { state: current?.state === 'completed' ? 'completed' : 'pending' }
+ if (!current) return { state: 'pending' }
+ if (
+ !['active', 'trialing', 'scheduled_cancel', 'past_due'].includes(
+ current.status,
+ ) ||
+ current.period_end <= now
+ )
+ return { state: 'inactive' }
+ if (
+ current.payment_subscription_id !== current.id ||
+ current.source !== 'payment'
+ )
+ return { state: 'superseded' }
+ return { state: 'completed' }
}
diff --git a/tests/platform-payments.test.ts b/tests/platform-payments.test.ts
index 44a0723b..042a74f6 100644
--- a/tests/platform-payments.test.ts
+++ b/tests/platform-payments.test.ts
@@ -1467,7 +1467,7 @@ test('Checkout return reconciliation verifies provider truth and ownership witho
f.transport,
f.now + 3,
)
- assert.equal(f.calls.length, calls)
+ assert.ok(f.calls.length > calls)
assert.equal(
(await resolveSubscription(f.db, 1, f.now + 3)).assignment_revision,
revision,
@@ -1915,3 +1915,613 @@ test('An authoritative expired checkout return releases the pending checkout wit
await f.mf.dispose()
}
})
+
+test('Customer portal resubscription keeps the canceled purchase and binds a new paid subscription', async () => {
+ const f = await fixture()
+ try {
+ await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ f.input,
+ 'https://app.chronoframe.art',
+ f.transport,
+ f.now,
+ )
+ const first = await f.complete()
+ await (
+ await f.event(
+ 'evt_portal_first',
+ 'checkout.completed',
+ f.checkouts.get('chk_1'),
+ )
+ ).receive()
+ await processPaymentEvents(f.db, root, f.transport, f.now)
+ first.status = 'canceled'
+ first.updated_at = new Date(f.now + 1000).toISOString()
+ await (
+ await f.event(
+ 'evt_portal_canceled',
+ 'subscription.canceled',
+ first,
+ f.now + 1000,
+ )
+ ).receive()
+ await processPaymentEvents(f.db, root, f.transport, f.now + 1000)
+ assert.equal((await resolveSubscription(f.db, 1, f.now + 1000)).id, 'free')
+ const original = f.checkouts.get('chk_1'),
+ metadata = {
+ ...original.metadata,
+ resubscribed_from_subscription_id: first.id,
+ }
+ const replacement = {
+ ...first,
+ id: 'sub_portal_replacement',
+ status: 'active',
+ metadata,
+ current_period_start_date: new Date(f.now + 2000).toISOString(),
+ current_period_end_date: new Date(f.now + 31 * 86400000).toISOString(),
+ updated_at: new Date(f.now + 2000).toISOString(),
+ }
+ const checkout = {
+ ...original,
+ id: 'chk_portal_replacement',
+ metadata,
+ subscription: replacement.id,
+ }
+ f.checkouts.set(checkout.id, checkout)
+ f.subscriptions.set(replacement.id, replacement)
+ await (
+ await f.event(
+ 'evt_portal_paid',
+ 'subscription.paid',
+ replacement,
+ f.now + 2000,
+ )
+ ).receive()
+ await processPaymentEvents(f.db, root, f.transport, f.now + 2000)
+ await (
+ await f.event(
+ 'evt_portal_completed',
+ 'checkout.completed',
+ checkout,
+ f.now + 2001,
+ )
+ ).receive()
+ await processPaymentEvents(f.db, root, f.transport, f.now + 2001)
+ const errors = (
+ await f.db
+ .prepare(
+ 'SELECT type,error FROM platform_payment_events WHERE error IS NOT NULL',
+ )
+ .all<any>()
+ ).results
+ assert.equal(
+ (await resolveSubscription(f.db, 1, f.now + 2001)).id,
+ 'pro',
+ JSON.stringify(errors),
+ )
+ const rows = (
+ await f.db
+ .prepare(
+ 'SELECT id,checkout_id,status FROM platform_payment_subscriptions ORDER BY id',
+ )
+ .all<any>()
+ ).results
+ assert.equal(rows.length, 2)
+ assert.notEqual(rows[0].checkout_id, rows[1].checkout_id)
+ assert.equal(
+ rows.find((row: any) => row.id === first.id).status,
+ 'canceled',
+ )
+ assert.equal(
+ rows.find((row: any) => row.id === replacement.id).status,
+ 'active',
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+})
+
+async function portalCase() {
+ const f = await fixture()
+ try {
+ const local = await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ f.input,
+ 'https://app.chronoframe.art',
+ f.transport,
+ f.now,
+ )
+ const old = await f.complete()
+ await (
+ await f.event(
+ 'evt_base_paid',
+ 'checkout.completed',
+ f.checkouts.get('chk_1'),
+ )
+ ).receive()
+ await processPaymentEvents(f.db, root, f.transport, f.now)
+ old.status = 'canceled'
+ old.updated_at = new Date(f.now + 1000).toISOString()
+ await (
+ await f.event(
+ 'evt_base_cancel',
+ 'subscription.canceled',
+ old,
+ f.now + 1000,
+ )
+ ).receive()
+ await processPaymentEvents(f.db, root, f.transport, f.now + 1000)
+ const metadata = {
+ ...old.metadata,
+ resubscribed_from_subscription_id: old.id,
+ }
+ const subscription = {
+ ...old,
+ id: 'sub_repurchase',
+ metadata,
+ status: 'active',
+ current_period_start_date: new Date(f.now + 2000).toISOString(),
+ current_period_end_date: new Date(f.now + 31 * 86400000).toISOString(),
+ updated_at: new Date(f.now + 2000).toISOString(),
+ }
+ const checkout = {
+ ...f.checkouts.get('chk_1'),
+ id: 'chk_repurchase',
+ metadata,
+ subscription: subscription.id,
+ }
+ f.subscriptions.set(subscription.id, subscription)
+ f.checkouts.set(checkout.id, checkout)
+ return { ...f, local, old, subscription, checkout, at: f.now + 2001 }
+ } catch (error) {
+ await f.mf.dispose()
+ throw error
+ }
+}
+
+test('Portal return verifies the new checkout before webhooks and historical canceled returns stay inactive', async () => {
+ const f = await portalCase()
+ try {
+ assert.deepEqual(
+ await refreshPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ f.local.checkoutId,
+ f.transport,
+ f.at,
+ ),
+ { state: 'inactive' },
+ )
+ assert.deepEqual(
+ await refreshPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ f.local.checkoutId,
+ f.transport,
+ f.at,
+ {
+ providerCheckoutId: f.checkout.id,
+ subscriptionId: f.subscription.id,
+ },
+ ),
+ { state: 'completed' },
+ )
+ assert.equal((await resolveSubscription(f.db, 1, f.at)).id, 'pro')
+ assert.equal(
+ (
+ await f.db
+ .prepare(
+ 'SELECT provider_id FROM platform_payment_checkouts WHERE id=?',
+ )
+ .bind(f.local.checkoutId)
+ .first<any>()
+ ).provider_id,
+ 'chk_1',
+ )
+ await assert.rejects(
+ refreshPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ f.local.checkoutId,
+ f.transport,
+ f.at,
+ { providerCheckoutId: f.checkout.id, subscriptionId: 'sub_wrong' },
+ ),
+ { code: 'payment_binding_invalid' },
+ )
+ await assert.rejects(
+ refreshPaymentCheckout(
+ f.db,
+ root,
+ 2,
+ 1,
+ f.local.checkoutId,
+ f.transport,
+ f.at,
+ { providerCheckoutId: f.checkout.id },
+ ),
+ { statusCode: 403 },
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+})
+
+test('Portal replay and late predecessor cancellation cannot downgrade the replacement or duplicate grants', async () => {
+ for (const paidFirst of [true, false]) {
+ const f = await portalCase()
+ try {
+ const paid = await f.event(
+ 'evt_new_paid',
+ 'subscription.paid',
+ f.subscription,
+ f.at,
+ ),
+ completed = await f.event(
+ 'evt_new_checkout',
+ 'checkout.completed',
+ f.checkout,
+ f.at,
+ )
+ await (paidFirst ? paid : completed).receive()
+ await processPaymentEvents(f.db, root, f.transport, f.at)
+ if (paidFirst)
+ assert.equal(
+ (
+ await f.db
+ .prepare(
+ "SELECT error FROM platform_payment_events WHERE id='evt_new_paid'",
+ )
+ .first<any>()
+ ).error,
+ 'payment_confirmation_pending',
+ )
+ await (paidFirst ? completed : paid).receive()
+ await processPaymentEvents(f.db, root, f.transport, f.at + 1)
+ await processPaymentEvents(f.db, root, f.transport, f.at + 31000)
+ const before = await resolveSubscription(f.db, 1, f.at + 31000)
+ assert.equal(before.id, 'pro')
+ const revision = before.subscription.revision
+ await completed.receive()
+ await paid.receive()
+ f.old.updated_at = new Date(f.at + 32000).toISOString()
+ await (
+ await f.event(
+ 'evt_old_cancel_late',
+ 'subscription.canceled',
+ f.old,
+ f.at + 32000,
+ )
+ ).receive()
+ await (
+ await f.event(
+ 'evt_new_paid_duplicate',
+ 'subscription.paid',
+ f.subscription,
+ f.at + 32000,
+ )
+ ).receive()
+ await Promise.all([
+ processPaymentEvents(f.db, root, f.transport, f.at + 32000),
+ processPaymentEvents(f.db, root, f.transport, f.at + 32000),
+ ])
+ await processPaymentEvents(f.db, root, f.transport, f.at + 100000)
+ const after = await resolveSubscription(f.db, 1, f.at + 100000)
+ assert.equal(after.id, 'pro')
+ assert.equal(after.subscription.revision, revision)
+ assert.equal(
+ (
+ await f.db
+ .prepare('SELECT COUNT(*) AS n FROM platform_payment_checkouts')
+ .first<any>()
+ ).n,
+ 2,
+ )
+ assert.equal(
+ (
+ await f.db
+ .prepare('SELECT COUNT(*) AS n FROM platform_payment_subscriptions')
+ .first<any>()
+ ).n,
+ 2,
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+ }
+})
+
+test('Portal lineage rejects foreign customers, conflicting metadata, active predecessors and unavailable products', async () => {
+ for (const scenario of [
+ 'customer',
+ 'marker',
+ 'origin',
+ 'predecessor',
+ 'active',
+ 'disabled',
+ 'unlisted',
+ 'member',
+ 'future',
+ 'request',
+ ]) {
+ const f = await portalCase()
+ try {
+ if (scenario === 'customer') {
+ f.checkout.customer = { id: 'cust_other' }
+ f.subscription.customer = { id: 'cust_other' }
+ }
+ if (scenario === 'marker')
+ f.subscription.metadata = {
+ ...f.subscription.metadata,
+ resubscribed_from_subscription_id: 'sub_other',
+ }
+ if (scenario === 'origin')
+ f.subscription.metadata = {
+ ...f.subscription.metadata,
+ chronoframe_checkout_id: 'other_origin',
+ }
+ if (scenario === 'predecessor') {
+ f.checkout.metadata = {
+ ...f.checkout.metadata,
+ resubscribed_from_subscription_id: 'sub_missing',
+ }
+ f.subscription.metadata = f.checkout.metadata
+ }
+ if (scenario === 'active') f.old.status = 'active'
+ if (scenario === 'disabled')
+ await f.db
+ .prepare('UPDATE platform_payment_products SET enabled=0')
+ .run()
+ if (scenario === 'unlisted')
+ await f.db
+ .prepare("UPDATE platform_plans SET listed=0 WHERE id='pro'")
+ .run()
+ if (scenario === 'member')
+ await f.db
+ .prepare(
+ "UPDATE platform_memberships SET role='member' WHERE workspace_id=1 AND user_id=1",
+ )
+ .run()
+ if (scenario === 'future')
+ f.subscription.current_period_start_date = new Date(
+ f.at + 86400000,
+ ).toISOString()
+ if (scenario === 'request')
+ f.checkout.request_id = 'contradicting_request'
+ await (
+ await f.event('evt_bad_portal', 'checkout.completed', f.checkout, f.at)
+ ).receive()
+ await processPaymentEvents(f.db, root, f.transport, f.at)
+ assert.equal(
+ (await resolveSubscription(f.db, 1, f.at)).id,
+ 'free',
+ scenario,
+ )
+ assert.equal(
+ (
+ await f.db
+ .prepare('SELECT COUNT(*) AS n FROM platform_payment_subscriptions')
+ .first<any>()
+ ).n,
+ 1,
+ scenario,
+ )
+ assert.equal(
+ (
+ await f.db
+ .prepare('SELECT COUNT(*) AS n FROM platform_payment_checkouts')
+ .first<any>()
+ ).n,
+ 1,
+ scenario,
+ )
+ const event = await f.db
+ .prepare(
+ "SELECT state,error FROM platform_payment_events WHERE id='evt_bad_portal'",
+ )
+ .first<any>()
+ assert.ok(event.error || event.state === 'ignored', scenario)
+ } finally {
+ await f.mf.dispose()
+ }
+ }
+})
+
+test('Portal replacement records payment without overriding a later manual grant', async () => {
+ const f = await portalCase()
+ try {
+ await f.db
+ .prepare(
+ "UPDATE platform_workspace_plans SET plan_id='free',source='manual',payment_subscription_id=NULL,revision=revision+1 WHERE workspace_id=1",
+ )
+ .run()
+ assert.deepEqual(
+ await refreshPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ f.local.checkoutId,
+ f.transport,
+ f.at,
+ {
+ providerCheckoutId: f.checkout.id,
+ subscriptionId: f.subscription.id,
+ },
+ ),
+ { state: 'superseded' },
+ )
+ const current = await resolveSubscription(f.db, 1, f.at)
+ assert.equal(current.id, 'free')
+ assert.equal(current.subscription.source, 'manual')
+ assert.equal(
+ (
+ await f.db
+ .prepare(
+ 'SELECT error FROM platform_payment_subscriptions WHERE id=?',
+ )
+ .bind(f.subscription.id)
+ .first<any>()
+ ).error,
+ 'payment_grant_superseded',
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+})
+
+test('Portal subscription chains preserve origin history and remain removable by account erasure', async () => {
+ const f = await portalCase()
+ try {
+ await (
+ await f.event('evt_chain_first', 'checkout.completed', f.checkout, f.at)
+ ).receive()
+ await processPaymentEvents(f.db, root, f.transport, f.at)
+ f.subscription.status = 'canceled'
+ f.subscription.updated_at = new Date(f.at + 1000).toISOString()
+ await (
+ await f.event(
+ 'evt_chain_cancel',
+ 'subscription.canceled',
+ f.subscription,
+ f.at + 1000,
+ )
+ ).receive()
+ await processPaymentEvents(f.db, root, f.transport, f.at + 1000)
+ const metadata = {
+ ...f.checkout.metadata,
+ resubscribed_from_subscription_id: f.subscription.id,
+ }
+ const next = {
+ ...f.subscription,
+ id: 'sub_repurchase_again',
+ status: 'active',
+ metadata,
+ updated_at: new Date(f.at + 2000).toISOString(),
+ }
+ const checkout = {
+ ...f.checkout,
+ id: 'chk_repurchase_again',
+ metadata,
+ subscription: next.id,
+ }
+ f.subscriptions.set(next.id, next)
+ f.checkouts.set(checkout.id, checkout)
+ await (
+ await f.event(
+ 'evt_chain_second',
+ 'checkout.completed',
+ checkout,
+ f.at + 2000,
+ )
+ ).receive()
+ await processPaymentEvents(f.db, root, f.transport, f.at + 2000)
+ assert.equal((await resolveSubscription(f.db, 1, f.at + 2000)).id, 'pro')
+ assert.equal(
+ (
+ await f.db
+ .prepare('SELECT COUNT(*) AS n FROM platform_payment_subscriptions')
+ .first<any>()
+ ).n,
+ 3,
+ )
+ await markAccount(
+ f.db,
+ 1,
+ 'Requested account erasure',
+ 'admin',
+ null,
+ f.at + 3000,
+ )
+ await purgeAccounts(
+ f.db,
+ {
+ billing: (id) => closeAccountPayments(f.db, root, id, f.transport),
+ domains: async () => true,
+ storage: async () => true,
+ },
+ f.at + 16 * 86400000,
+ )
+ assert.equal(
+ await f.db.prepare('SELECT id FROM platform_users WHERE id=1').first(),
+ null,
+ )
+ assert.equal(
+ (
+ await f.db
+ .prepare(
+ 'SELECT COUNT(*) AS n FROM platform_payment_checkouts WHERE workspace_id=1',
+ )
+ .first<any>()
+ ).n,
+ 0,
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+})
+
+test('A late portal repurchase cannot replace a newer independently purchased subscription', async () => {
+ const f = await portalCase()
+ try {
+ await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ { ...f.input, requestId: 'client_new_purchase' },
+ 'https://app.chronoframe.art',
+ f.transport,
+ f.at,
+ )
+ const newer = await f.complete('chk_3')
+ newer.current_period_start_date = new Date(f.at).toISOString()
+ newer.updated_at = new Date(f.at).toISOString()
+ await (
+ await f.event(
+ 'evt_newer_independent',
+ 'checkout.completed',
+ f.checkouts.get('chk_3'),
+ f.at,
+ )
+ ).receive()
+ await processPaymentEvents(f.db, root, f.transport, f.at)
+ await (
+ await f.event(
+ 'evt_late_portal',
+ 'checkout.completed',
+ f.checkout,
+ f.at + 1,
+ )
+ ).receive()
+ await processPaymentEvents(f.db, root, f.transport, f.at + 1)
+ const assignment = await f.db
+ .prepare(
+ 'SELECT payment_subscription_id FROM platform_workspace_plans WHERE workspace_id=1',
+ )
+ .first<any>()
+ assert.equal(assignment.payment_subscription_id, newer.id)
+ assert.equal(
+ (
+ await f.db
+ .prepare(
+ 'SELECT error FROM platform_payment_subscriptions WHERE id=?',
+ )
+ .bind(f.subscription.id)
+ .first<any>()
+ ).error,
+ 'payment_grant_superseded',
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+})