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): defer paid subscriptions until granted entitlements expire

Timothy Yinac0489c205c9
diff --git a/apps/cloud/app/assets/cloud.css b/apps/cloud/app/assets/cloud.css
index 150dae4a..9c7c32b6 100644
--- a/apps/cloud/app/assets/cloud.css
+++ b/apps/cloud/app/assets/cloud.css
@@ -3072,3 +3072,17 @@ a.cf-domain-address:hover {
animation: none;
}
}
+
+.cf-handover-options {
+ display: grid;
+ gap: 16px;
+}
+.cf-handover-options label {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ line-height: 1.5;
+}
+.cf-handover-options input {
+ flex-shrink: 0;
+}
diff --git a/apps/cloud/app/components/CloudPricing.vue b/apps/cloud/app/components/CloudPricing.vue
index 321ddcd1..4b55c9bf 100644
--- a/apps/cloud/app/components/CloudPricing.vue
+++ b/apps/cloud/app/components/CloudPricing.vue
@@ -135,6 +135,10 @@ const offer = (plan: any) =>
payment.value?.enabled &&
payment.value?.canManage &&
!payment.value?.hasActiveSubscription &&
+ (!payment.value.entitlement ||
+ (plan.id === payment.value.entitlement.planId
+ ? payment.value.entitlement.expiresAt !== null
+ : payment.value.entitlement.upgradePlans.includes(plan.id))) &&
payment.value.offers.some(
(v: any) => v.plan_id === plan.id && v.interval === interval.value,
)
@@ -200,10 +204,61 @@ watch(
() => billing?.selected.value,
() => {
changeOpen.value = false
+ checkoutOpen.value = false
+ cancelOpen.value = false
changeQuote.value = null
},
)
-async function checkout(plan: any) {
+const checkoutOpen = ref(false),
+ checkoutPlan = ref<any>(null),
+ startMode = ref('immediate'),
+ replaceConfirmed = ref(false),
+ cancelOpen = ref(false),
+ cancelling = ref(false)
+const entitlement = computed(() => payment.value?.entitlement)
+const date = (value: number) => new Date(value).toLocaleString(locale.value)
+function checkout(plan: any) {
+ if (entitlement.value) {
+ checkoutPlan.value = plan
+ startMode.value =
+ plan.id === entitlement.value.planId ? 'after_entitlement' : 'immediate'
+ replaceConfirmed.value = false
+ checkoutOpen.value = true
+ } else void submitCheckout(plan)
+}
+async function cancelReservation() {
+ if (cancelling.value || !billing?.selected.value) return
+ cancelling.value = true
+ paymentError.value = ''
+ try {
+ await $fetch('/api/billing/payments', {
+ method: 'POST',
+ timeout: 15000,
+ body: {
+ action: 'cancel-reservation',
+ workspaceId: billing.selected.value,
+ },
+ })
+ cancelOpen.value = false
+ await Promise.all([
+ payments?.refresh({ reconcile: false }),
+ billing.refresh(),
+ ])
+ } catch {
+ paymentError.value = t('cloud.payments.cancelReservationFailed')
+ } finally {
+ cancelling.value = false
+ }
+}
+async function confirmCheckout() {
+ if (
+ !checkoutPlan.value ||
+ (startMode.value === 'immediate' && !replaceConfirmed.value)
+ )
+ return
+ await submitCheckout(checkoutPlan.value, startMode.value)
+}
+async function submitCheckout(plan: any, mode?: string) {
if (paying.value || !billing?.selected.value) return
const workspaceId = billing.selected.value,
key = plan.id + ':' + interval.value
@@ -218,13 +273,20 @@ async function checkout(plan: any) {
planId: plan.id,
interval: interval.value,
requestId: crypto.randomUUID(),
+ startMode: mode,
+ replaceEntitlement: mode === 'immediate' && replaceConfirmed.value,
},
})
if (mounted && workspaceId === billing.selected.value)
await navigateTo(result.url, { external: true })
- } catch {
+ } catch (error: any) {
if (mounted) {
- paymentError.value = t('cloud.payments.failed')
+ const code = error?.data?.data?.code ?? error?.data?.code
+ paymentError.value = t(
+ code === 'payment_trial_unavailable'
+ ? 'cloud.payments.trialUnavailable'
+ : 'cloud.payments.failed',
+ )
await payments?.refresh()
}
} finally {
@@ -334,6 +396,31 @@ async function checkout(plan: any) {
{{ $t('cloud.billing.current') }}: {{ billing.data.value.plan.name }}
</p>
</template>
+ <CfCard
+ v-if="portal && payment?.reservation"
+ class="cf-notice"
+ >
+ <p>
+ {{
+ $t('cloud.payments.reservationStatus', {
+ plan: payment.reservation.planName,
+ date: date(payment.reservation.startsAt),
+ })
+ }}
+ </p>
+ <p v-if="payment.reservation.status === 'past_due'">
+ {{ $t('cloud.payments.reservationPaymentDue') }}
+ </p>
+ <CfButton
+ v-if="payment.reservation.canCancel"
+ variant="secondary"
+ :disabled="
+ cancelling || payment.reservation.startsAt <= Date.now() + 60000
+ "
+ @click="cancelOpen = true"
+ >{{ $t('cloud.payments.cancelReservation') }}</CfButton
+ >
+ </CfCard>
<CfCard
v-if="error"
role="alert"
@@ -455,7 +542,9 @@ async function checkout(plan: any) {
}}
</CfButton>
<CfButton
- v-else-if="portal && plan.id === currentPlan"
+ v-else-if="
+ portal && plan.id === currentPlan && !(entitlement && offer(plan))
+ "
disabled
variant="secondary"
>{{ $t('cloud.billing.current') }}</CfButton
@@ -622,6 +711,104 @@ async function checkout(plan: any) {
>{{ $t('cloud.billing.redeem') }}</NuxtLink
>
</div>
+ <UModal
+ v-model:open="checkoutOpen"
+ :title="$t('cloud.payments.subscribeConfirm')"
+ :description="checkoutPlan?.name"
+ >
+ <template #body
+ ><div
+ class="cf-handover-options"
+ v-if="entitlement && checkoutPlan"
+ >
+ <p>
+ {{
+ $t('cloud.payments.currentEntitlement', {
+ plan: entitlement.name,
+ date:
+ entitlement.expiresAt === null
+ ? $t('cloud.billing.noExpiry')
+ : date(entitlement.expiresAt),
+ })
+ }}
+ </p>
+ <label v-if="checkoutPlan.id !== entitlement.planId"
+ ><input
+ v-model="startMode"
+ type="radio"
+ value="immediate"
+ />{{ $t('cloud.payments.startImmediately') }}</label
+ >
+ <label v-if="entitlement.expiresAt !== null"
+ ><input
+ v-model="startMode"
+ type="radio"
+ value="after_entitlement"
+ />{{ $t('cloud.payments.startAfterEntitlement') }}</label
+ >
+ <p>
+ {{
+ $t(
+ startMode === 'after_entitlement'
+ ? 'cloud.payments.deferredExplanation'
+ : 'cloud.payments.replaceExplanation',
+ )
+ }}
+ </p>
+ <label v-if="startMode === 'immediate'"
+ ><input
+ v-model="replaceConfirmed"
+ type="checkbox"
+ />{{ $t('cloud.payments.replaceConsent') }}</label
+ >
+ <p
+ v-if="paymentError"
+ role="alert"
+ class="cf-error-message"
+ >
+ {{ paymentError }}
+ </p>
+ </div></template
+ >
+ <template #footer
+ ><CfButton
+ variant="secondary"
+ :disabled="!!paying"
+ @click="checkoutOpen = false"
+ >{{ $t('cloud.billing.cancel') }}</CfButton
+ ><CfButton
+ :loading="!!paying"
+ :disabled="startMode === 'immediate' && !replaceConfirmed"
+ @click="confirmCheckout"
+ >{{ $t('cloud.payments.continueCheckout') }}</CfButton
+ ></template
+ >
+ </UModal>
+ <UModal
+ v-model:open="cancelOpen"
+ :title="$t('cloud.payments.cancelReservation')"
+ :description="$t('cloud.payments.cancelReservationHelp')"
+ ><template #body
+ ><p
+ v-if="paymentError"
+ role="alert"
+ class="cf-error-message"
+ >
+ {{ paymentError }}
+ </p></template
+ ><template #footer
+ ><CfButton
+ variant="secondary"
+ :disabled="cancelling"
+ @click="cancelOpen = false"
+ >{{ $t('cloud.billing.cancel') }}</CfButton
+ ><CfButton
+ :loading="cancelling"
+ @click="cancelReservation"
+ >{{ $t('cloud.payments.cancelReservation') }}</CfButton
+ ></template
+ ></UModal
+ >
<UModal
v-model:open="changeOpen"
:title="$t('cloud.payments.changeTitle')"
diff --git a/apps/cloud/app/composables/useCloudPayments.ts b/apps/cloud/app/composables/useCloudPayments.ts
index 6eb2fb9e..d9f0b03f 100644
--- a/apps/cloud/app/composables/useCloudPayments.ts
+++ b/apps/cloud/app/composables/useCloudPayments.ts
@@ -30,7 +30,9 @@ export function useCloudPayments(
current === generation &&
reconcile &&
result.canManage &&
- (result.pending?.canRefresh || result.planChange)
+ (result.pending?.canRefresh ||
+ result.planChange ||
+ result.reservation?.canCancel)
) {
// A stored checkout must converge even when the return URL parameters are gone.
try {
@@ -40,7 +42,7 @@ export function useCloudPayments(
body: {
action: result.planChange ? 'check-change' : 'refresh',
workspaceId: id,
- checkoutId: result.pending?.id,
+ checkoutId: result.pending?.id ?? result.reservation?.checkoutId,
},
})
} catch {
diff --git a/apps/cloud/app/composables/useDodoCheckoutReturn.ts b/apps/cloud/app/composables/useDodoCheckoutReturn.ts
index 0b77dd94..45edb6a0 100644
--- a/apps/cloud/app/composables/useDodoCheckoutReturn.ts
+++ b/apps/cloud/app/composables/useDodoCheckoutReturn.ts
@@ -34,7 +34,11 @@ export function useDodoCheckoutReturn(
if (!alive || current !== generation) return
await refresh()
if (!alive || current !== generation) return
- if (['completed', 'expired', 'inactive'].includes(result.state)) {
+ if (
+ ['completed', 'scheduled', 'expired', 'inactive'].includes(
+ result.state,
+ )
+ ) {
state.value = result.state
return
}
diff --git a/apps/cloud/app/utils/billing-format.ts b/apps/cloud/app/utils/billing-format.ts
index 6b9772e2..d32f0a56 100644
--- a/apps/cloud/app/utils/billing-format.ts
+++ b/apps/cloud/app/utils/billing-format.ts
@@ -67,6 +67,7 @@ export function billingError(error: any, t: (key: string) => string) {
const key = (
{
invalid_activation_code: 'invalidCode',
+ payment_handover_exists: 'reservationActive',
permanent_plan_active: 'permanentActive',
activation_rate_limit: 'rateLimit',
subscription_changed: 'changed',
diff --git a/apps/cloud/i18n/locales/en.json b/apps/cloud/i18n/locales/en.json
index 7f46d416..6bcb6b33 100644
--- a/apps/cloud/i18n/locales/en.json
+++ b/apps/cloud/i18n/locales/en.json
@@ -699,7 +699,8 @@
"purchaseHelp": "Choose monthly or quarterly billing. Review the payment details before confirming your subscription.",
"buyPlan": "Subscribe to {plan}",
"purchaseUnavailable": "Currently unavailable",
- "purchaseUnavailableHelp": "This plan is not currently available for purchase. Please contact support or try again later."
+ "purchaseUnavailableHelp": "This plan is not currently available for purchase. Please contact support or try again later.",
+ "reservationActive": "Cancel your reserved subscription before redeeming an activation code."
},
"payments": {
"billing": "Subscription billing",
@@ -747,7 +748,23 @@
"return_expired": "This checkout has expired. You can start a new one from the plans below.",
"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."
+ "return_superseded": "Payment confirmed. Your current plan is controlled by another entitlement; contact support if you need help.",
+ "return_scheduled": "Subscription authorized. Your existing entitlement remains active until the first charge.",
+ "reservationStatus": "{plan} subscription reserved. First charge is scheduled for {date}.",
+ "reservationPaymentDue": "The first payment has not completed. Paid benefits will activate only after successful payment. Use subscription management to update your payment method or cancel.",
+ "cancelReservation": "Cancel reserved subscription",
+ "cancelReservationHelp": "This stops the reserved subscription. Your original trial or activation-code entitlement remains until its original expiry; any complimentary bridge period ends.",
+ "cancelReservationFailed": "Could not cancel the reservation. If billing is imminent or has started, use subscription management to check or cancel it.",
+ "convertSubscription": "Convert to a paid subscription",
+ "subscribeConfirm": "Confirm subscription timing",
+ "currentEntitlement": "Current entitlement: {plan}, valid until {date}.",
+ "startImmediately": "Pay and upgrade immediately",
+ "startAfterEntitlement": "Start billing after the current entitlement",
+ "deferredExplanation": "No recurring charge today. Dodo trials use whole days rounded up, so the first charge will not precede your current expiry. The exact date is shown by Dodo; your current tier is extended free until then. The new tier activates after the first successful payment. Cancel the reservation before redeeming another activation code.",
+ "replaceExplanation": "Payment starts immediately. This replaces the remaining trial or activation-code entitlement without credit or restoration.",
+ "replaceConsent": "I agree to replace my remaining entitlement and start billing now.",
+ "continueCheckout": "Continue to checkout",
+ "trialUnavailable": "Deferred billing is unavailable for this checkout. No reservation was created; please contact support."
},
"dashboard": {
"workspaceOverview": "Workspace overview",
diff --git a/apps/cloud/i18n/locales/zh-Hans.json b/apps/cloud/i18n/locales/zh-Hans.json
index 06bd7b18..15f872ef 100644
--- a/apps/cloud/i18n/locales/zh-Hans.json
+++ b/apps/cloud/i18n/locales/zh-Hans.json
@@ -699,7 +699,8 @@
"purchaseHelp": "支持按月或按季订阅,请在确认订阅前核对付款详情。",
"buyPlan": "购买 {plan}",
"purchaseUnavailable": "暂不可购买",
- "purchaseUnavailableHelp": "该套餐目前暂不可购买,请联系客服或稍后重试。"
+ "purchaseUnavailableHelp": "该套餐目前暂不可购买,请联系客服或稍后重试。",
+ "reservationActive": "请先取消预约订阅,再兑换激活码。"
},
"payments": {
"billing": "订阅账单",
@@ -747,7 +748,23 @@
"return_expired": "这笔付款已过期,可以在下方选择套餐重新发起。",
"checkAgain": "检查付款状态",
"return_inactive": "此订阅已不再生效。当前套餐与用量如下。",
- "return_superseded": "付款已确认,当前套餐由其他授权管理。如需帮助,请联系客服。"
+ "return_superseded": "付款已确认,当前套餐由其他授权管理。如需帮助,请联系客服。",
+ "return_scheduled": "订阅已授权,当前权益将保留至首次扣款日,尚未开始付费账期。",
+ "reservationStatus": "已预约 {plan} 订阅,预计首次扣款时间:{date}。",
+ "reservationPaymentDue": "首次付款尚未完成,成功后才会开通付费权益。请在订阅管理中更新付款方式或取消。",
+ "cancelReservation": "取消预约订阅",
+ "cancelReservationHelp": "取消后停止此预约订阅。原试用或激活码权益仍保留至原到期日,额外赠送的衔接时段结束。",
+ "cancelReservationFailed": "未能取消预约。若已临近首扣或已进入扣款流程,请在订阅管理中核对或取消。",
+ "convertSubscription": "转为正式订阅",
+ "subscribeConfirm": "确认订阅生效方式",
+ "currentEntitlement": "当前权益:{plan},有效期至 {date}。",
+ "startImmediately": "立即付款并升级",
+ "startAfterEntitlement": "当前权益到期后开始计费",
+ "deferredExplanation": "今天不收取订阅费用。Dodo 按整天折算并向上取整,首扣不早于当前权益到期日,准确日期以 Dodo 结账页为准;当前等级免费延续至首扣日。新等级在首次付款成功后开通。再次兑换激活码前,需要先取消预约。",
+ "replaceExplanation": "立即扣款并切换套餐,剩余试用或激活码权益将被替换,不折抵、不恢复。",
+ "replaceConsent": "我同意替换剩余权益,并立即开始付费订阅。",
+ "continueCheckout": "前往结账",
+ "trialUnavailable": "当前结账不支持延期扣款,未创建订阅预约,请联系客服。"
},
"dashboard": {
"workspaceOverview": "工作区概览",
diff --git a/apps/cloud/server/api/billing/payments.post.ts b/apps/cloud/server/api/billing/payments.post.ts
index 01768608..3bb1ae81 100644
--- a/apps/cloud/server/api/billing/payments.post.ts
+++ b/apps/cloud/server/api/billing/payments.post.ts
@@ -1,3 +1,4 @@
+import { cancelDeferredSubscription } from '../../../../../packages/platform/src/dodo-payments'
import {
previewPaymentPlanChange,
checkPaymentPlanChange,
@@ -23,6 +24,13 @@ export default definePlatformHandler(async (event) => {
platformPortalOrigin(event, config.portalOrigin, true)
const b = await siteManagementBody(event, 4096),
db = platformDatabase(event)
+ if (b.action === 'cancel-reservation')
+ return cancelDeferredSubscription(
+ db,
+ config.storageSecret,
+ user.userId,
+ Number(b.workspaceId),
+ )
if (b.action === 'check-change')
return checkPaymentPlanChange(
db,
@@ -53,6 +61,8 @@ export default definePlatformHandler(async (event) => {
planId: String(b.planId),
interval: Number(b.interval),
requestId: String(b.requestId),
+ startMode: b.startMode === undefined ? undefined : String(b.startMode),
+ replaceEntitlement: b.replaceEntitlement === true,
},
config.portalOrigin,
)
diff --git a/packages/platform/migrations/0033_subscription_handover.sql b/packages/platform/migrations/0033_subscription_handover.sql
new file mode 100644
index 00000000..23e32e90
--- /dev/null
+++ b/packages/platform/migrations/0033_subscription_handover.sql
@@ -0,0 +1,4 @@
+ALTER TABLE platform_payment_checkouts ADD COLUMN handover_json TEXT;
+ALTER TABLE platform_payment_subscriptions ADD COLUMN activation_state TEXT NOT NULL DEFAULT 'paid' CHECK(activation_state IN('authorized','paid'));
+ALTER TABLE platform_payment_subscriptions ADD COLUMN handover_at INTEGER;
+ALTER TABLE platform_payment_subscriptions ADD COLUMN handover_revision INTEGER;
diff --git a/packages/platform/src/activation.ts b/packages/platform/src/activation.ts
index 726a57eb..8588a237 100644
--- a/packages/platform/src/activation.ts
+++ b/packages/platform/src/activation.ts
@@ -1,3 +1,4 @@
+import { NO_HANDOVER, requireNoHandover } from './payment-handover.ts'
import type { PlatformD1 } from './index.ts'
import {
duration,
@@ -192,6 +193,7 @@ export async function previewActivation(
now = Date.now(),
) {
await permitted(db, userId, workspaceId)
+ await requireNoHandover(db, workspaceId)
await attempt(db, userId, now)
const hash = await activationHash(value),
code = await available(db, hash, userId, now)
@@ -244,6 +246,7 @@ export async function redeemActivation(
return row ? JSON.parse(row.receipt_json) : null
}
await attempt(db, userId, now)
+ await requireNoHandover(db, workspaceId)
const hash = await activationHash(input.code),
code = await available(db, hash, userId, now)
if (!code) {
@@ -265,7 +268,7 @@ export async function redeemActivation(
grant,
redeemedAt: now,
}
- const guard = `EXISTS(SELECT 1 FROM platform_activation_codes c JOIN platform_plans p ON p.id=c.plan_id WHERE c.id=? AND c.revision=? AND c.enabled=1 AND p.active=1 AND (c.redeem_until IS NULL OR c.redeem_until>?) AND (c.max_uses IS NULL OR c.uses<c.max_uses)) AND COALESCE((SELECT revision FROM platform_workspace_plans WHERE workspace_id=?),0)=? AND EXISTS(SELECT 1 FROM platform_memberships m JOIN platform_users u ON u.id=m.user_id LEFT JOIN platform_account_controls ac ON ac.user_id=u.id WHERE m.workspace_id=? AND m.user_id=? AND m.role='admin' AND u.email_verified=1 AND COALESCE(ac.suspended,0)=0)`
+ const guard = `EXISTS(SELECT 1 FROM platform_activation_codes c JOIN platform_plans p ON p.id=c.plan_id WHERE c.id=? AND c.revision=? AND c.enabled=1 AND p.active=1 AND (c.redeem_until IS NULL OR c.redeem_until>?) AND (c.max_uses IS NULL OR c.uses<c.max_uses)) AND COALESCE((SELECT revision FROM platform_workspace_plans WHERE workspace_id=?),0)=? AND EXISTS(SELECT 1 FROM platform_memberships m JOIN platform_users u ON u.id=m.user_id LEFT JOIN platform_account_controls ac ON ac.user_id=u.id WHERE m.workspace_id=? AND m.user_id=? AND m.role='admin' AND u.email_verified=1 AND COALESCE(ac.suspended,0)=0) AND ${NO_HANDOVER}`
try {
await db.batch([
db
@@ -287,6 +290,8 @@ export async function redeemActivation(
Number(input.revision),
workspaceId,
userId,
+ workspaceId,
+ workspaceId,
),
db
.prepare(
diff --git a/packages/platform/src/deferred-payments.ts b/packages/platform/src/deferred-payments.ts
new file mode 100644
index 00000000..095139af
--- /dev/null
+++ b/packages/platform/src/deferred-payments.ts
@@ -0,0 +1,264 @@
+import type { PlatformD1 } from './index.ts'
+import { DAY } from './payment-handover.ts'
+import { SubscriptionError, subscriptionInvalidation } from './subscriptions.ts'
+import { dodoRequest } from './dodo-client.ts'
+const fail = (code: string): never => {
+ throw new SubscriptionError(422, code)
+}
+const time = (v: unknown) => (typeof v === 'string' ? Date.parse(v) : NaN)
+/** Called only under the workspace payment lock and the active credential fence. */
+export async function reconcileDeferredAuthorization(
+ db: PlatformD1,
+ client: any,
+ checkout: any,
+ subscription: any,
+ known: any,
+ paymentId: string | undefined,
+ now: number,
+ fence: string,
+ fenceValues: (string | number | null)[],
+ localId: string,
+) {
+ if (!checkout.handover_json || known?.activation_state === 'paid')
+ return { handled: false, paymentId }
+ if (known && known.customer_id !== subscription.customer.customer_id)
+ fail('payment_customer_mismatch')
+ const snapshot = JSON.parse(checkout.handover_json)
+ if (subscription.trial_period_days !== snapshot.trialDays)
+ fail('payment_subscription_mismatch')
+ if (!known) {
+ if (!checkout.provider_id) fail('payment_checkout_mismatch')
+ const session = (await dodoRequest(() =>
+ client.checkoutSessions.retrieve(checkout.provider_id.split(':').pop()),
+ )) as any
+ if (
+ session.id !== checkout.provider_id.split(':').pop() ||
+ (session.customer_email &&
+ session.customer_email.toLowerCase() !== snapshot.email.toLowerCase())
+ )
+ fail('payment_checkout_mismatch')
+ paymentId ??= session.payment_id ?? undefined
+ }
+ let payment = paymentId
+ ? ((await dodoRequest(() => client.payments.retrieve(paymentId))) as any)
+ : null
+ if (
+ !payment ||
+ (known &&
+ now >= known.handover_at &&
+ !(payment.status === 'succeeded' && payment.total_amount > 0))
+ ) {
+ const results = (await dodoRequest(() =>
+ client.payments.list({
+ subscription_id: subscription.subscription_id,
+ status: 'succeeded',
+ page_size: 10,
+ }),
+ )) as any
+ const latest = results.items
+ .filter(
+ (p: any) =>
+ p.status === 'succeeded' &&
+ p.total_amount > 0 &&
+ (p.subscription_id === subscription.subscription_id ||
+ p.subscription_ids?.includes(subscription.subscription_id)),
+ )
+ .sort((a: any, b: any) => time(b.created_at) - time(a.created_at))[0]
+ if (latest) {
+ paymentId = latest.payment_id
+ payment = await dodoRequest(() => client.payments.retrieve(paymentId))
+ }
+ }
+ if (payment?.status === 'succeeded' && payment.total_amount > 0) {
+ 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
+ )
+ fail('payment_period_invalid')
+ return { handled: false, paymentId }
+ }
+ if (
+ payment &&
+ (payment.payment_id !== paymentId ||
+ payment.customer?.customer_id !== subscription.customer.customer_id ||
+ !(
+ payment.subscription_id === subscription.subscription_id ||
+ payment.subscription_ids?.includes(subscription.subscription_id)
+ ) ||
+ payment.is_update_payment_method ||
+ payment.is_multi_subscription ||
+ payment.refunds?.length ||
+ payment.disputes?.length)
+ )
+ fail('payment_subscription_mismatch')
+ const at = known?.handover_at ?? time(subscription.next_billing_date)
+ if (
+ !Number.isSafeInteger(at) ||
+ at < snapshot.expiresAt ||
+ (!known &&
+ (at > checkout.created_at + (snapshot.trialDays + 1) * DAY ||
+ time(subscription.previous_billing_date) > checkout.created_at + DAY))
+ )
+ fail('payment_handover_date_invalid')
+ const prior = await db
+ .prepare('SELECT * FROM platform_workspace_plans WHERE workspace_id=?')
+ .bind(checkout.workspace_id)
+ .first<any>()
+ if (!prior) fail('workspace_unavailable')
+ const accountDeleted = !!(await db
+ .prepare(
+ 'SELECT 1 FROM platform_account_deletions WHERE user_id=(SELECT owner_user_id FROM platform_workspaces WHERE id=?)',
+ )
+ .bind(checkout.workspace_id)
+ .first())
+ fence +=
+ ' AND EXISTS(SELECT 1 FROM platform_workspace_plans WHERE workspace_id=? AND revision=?)'
+ fenceValues = [...fenceValues, checkout.workspace_id, prior.revision]
+ const expectedRevision = known?.handover_revision ?? snapshot.revision
+ const bound =
+ prior &&
+ ((prior.revision === expectedRevision &&
+ prior.plan_id === snapshot.planId &&
+ prior.source === snapshot.source) ||
+ (prior.source === 'expired_default' &&
+ prior.revision === expectedRevision + 1))
+ let terminal =
+ ['cancelled', 'expired', 'failed'].includes(subscription.status) ||
+ checkout.error === 'payment_handover_cancelled'
+ if (
+ (!bound ||
+ accountDeleted ||
+ subscription.cancel_at_next_billing_date ||
+ terminal) &&
+ subscription.status === 'active' &&
+ at > Math.max(now, Date.now()) + 60000
+ ) {
+ await dodoRequest(() =>
+ client.subscriptions.update(
+ subscription.subscription_id,
+ { status: 'cancelled' },
+ { headers: { 'Idempotency-Key': `cf-cancel-handover-${checkout.id}` } },
+ ),
+ )
+ const actual = (await dodoRequest(() =>
+ client.subscriptions.retrieve(subscription.subscription_id),
+ )) as any
+ if (actual.status !== 'cancelled') fail('payment_confirmation_pending')
+ terminal = true
+ }
+ if ((!bound || accountDeleted) && !terminal) fail('payment_grant_superseded')
+ const extend = !terminal && bound && now < at && prior.expires_at !== at
+ const restore =
+ terminal &&
+ !accountDeleted &&
+ known &&
+ bound &&
+ prior.revision === expectedRevision &&
+ prior.expires_at === at
+ const grantRevision =
+ extend || restore ? prior.revision + 1 : (prior?.revision ?? null)
+ const status = terminal
+ ? 'canceled'
+ : now >= at ||
+ ['on_hold', 'past_due', 'paused'].includes(subscription.status)
+ ? 'past_due'
+ : 'active'
+ const eventId = crypto.randomUUID()
+ const writes = [
+ db
+ .prepare(
+ `INSERT INTO platform_payment_subscriptions(id,workspace_id,checkout_id,customer_id,product_id,plan_id,interval,quota_anchor,status,period_start,period_end,provider_updated_at,checked_at,next_check_at,error,provider,environment,provider_key,price,currency,activation_state,handover_at,handover_revision) SELECT ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'dodo',?,?,?,?,'authorized',?,? WHERE ${fence} ON CONFLICT(id) DO UPDATE SET status=excluded.status,checked_at=excluded.checked_at,next_check_at=excluded.next_check_at,error=excluded.error,handover_revision=excluded.handover_revision,revision=platform_payment_subscriptions.revision+1`,
+ )
+ .bind(
+ localId,
+ checkout.workspace_id,
+ checkout.id,
+ subscription.customer.customer_id,
+ checkout.product_id,
+ checkout.plan_id,
+ checkout.interval,
+ at,
+ status,
+ Math.min(now, at - 1),
+ at,
+ now,
+ now,
+ now + 300000,
+ terminal
+ ? 'payment_handover_cancelled'
+ : now >= at
+ ? 'payment_confirmation_pending'
+ : null,
+ checkout.environment,
+ checkout.provider_key,
+ checkout.price,
+ checkout.currency,
+ at,
+ terminal ? null : grantRevision,
+ ...fenceValues,
+ ),
+ db
+ .prepare(
+ `UPDATE platform_payment_checkouts SET state=?,error=?,updated_at=? WHERE id=? AND ${fence}`,
+ )
+ .bind(
+ terminal ? 'expired' : 'completed',
+ terminal ? 'payment_handover_cancelled' : null,
+ now,
+ checkout.id,
+ ...fenceValues,
+ ),
+ ]
+ if (extend || restore) {
+ const expiresAt = restore ? snapshot.expiresAt : at
+ writes.push(
+ db
+ .prepare(
+ `INSERT INTO platform_subscription_events(id,workspace_id,kind,before_json,after_json,created_at) SELECT ?,?,'payment_handover',?,?,? WHERE ${fence} AND EXISTS(SELECT 1 FROM platform_workspace_plans WHERE workspace_id=? AND revision=?)`,
+ )
+ .bind(
+ eventId,
+ checkout.workspace_id,
+ JSON.stringify({ expiresAt: prior.expires_at, source: prior.source }),
+ JSON.stringify({
+ expiresAt,
+ source: snapshot.source,
+ reservation: localId,
+ }),
+ now,
+ ...fenceValues,
+ checkout.workspace_id,
+ prior.revision,
+ ),
+ )
+ writes.push(
+ db
+ .prepare(
+ 'UPDATE platform_workspace_plans SET plan_id=?,source=?,starts_at=?,expires_at=?,revision=revision+1 WHERE workspace_id=? AND revision=? AND EXISTS(SELECT 1 FROM platform_subscription_events WHERE id=?)',
+ )
+ .bind(
+ snapshot.planId,
+ snapshot.source,
+ snapshot.startsAt,
+ expiresAt,
+ checkout.workspace_id,
+ prior.revision,
+ eventId,
+ ),
+ ...subscriptionInvalidation(db, checkout.workspace_id, eventId),
+ )
+ }
+ const results = await db.batch(writes)
+ if (!results[0]?.meta.changes)
+ throw new SubscriptionError(409, 'payment_entitlement_changed')
+ return { handled: true, paymentId }
+}
diff --git a/packages/platform/src/dodo-payments.ts b/packages/platform/src/dodo-payments.ts
index 731c4854..361fda11 100644
--- a/packages/platform/src/dodo-payments.ts
+++ b/packages/platform/src/dodo-payments.ts
@@ -1,3 +1,5 @@
+import { checkoutHandover } from './payment-handover.ts'
+import { reconcileDeferredAuthorization } from './deferred-payments.ts'
import { discountedPrice } from '../../contracts/src/pricing.ts'
import { paymentProductSnapshot } from './payment-product-sync.ts'
import type { PlatformD1 } from './index.ts'
@@ -238,6 +240,8 @@ export async function createDodoCheckout(
planId: string
interval: number
requestId: string
+ startMode?: string
+ replaceEntitlement?: boolean
},
origin: string,
transport: typeof fetch = fetch,
@@ -275,7 +279,9 @@ export async function createDodoCheckout(
existing.interval !== input.interval ||
existing.provider !== 'dodo' ||
existing.provider_key !== key ||
- existing.environment !== environment
+ existing.environment !== environment ||
+ (input.startMode !== undefined &&
+ !!existing.handover_json !== (input.startMode === 'after_entitlement'))
)
fail('payment_request_conflict')
if (existing.state === 'open' && existing.checkout_url)
@@ -299,6 +305,17 @@ export async function createDodoCheckout(
.bind(input.workspaceId)
.first<any>()
if (!prior) fail('workspace_unavailable', 404)
+ const handover = await checkoutHandover(
+ db,
+ input.workspaceId,
+ input.planId,
+ input.startMode,
+ input.replaceEntitlement,
+ now,
+ )
+ const handoverJson = handover
+ ? JSON.stringify({ ...handover, email: member.email })
+ : null
// Rate limit includes failed attempts, and the partial unique index serializes new sessions per workspace.
const budget = await db
.prepare(
@@ -330,17 +347,33 @@ export async function createDodoCheckout(
price.payment_frequency_count !== input.interval ||
!price.tax_inclusive ||
(price.trial_period_days ?? 0) !== 0 ||
+ (price.trial_amount ?? 0) !== 0 ||
(price.discount_bps ?? (price.discount ?? 0) * 100) !==
product.discount_bps ||
price.purchasing_power_parity ||
providerProduct.addons?.length
)
fail('payment_product_mismatch', 422)
+ if (handover) {
+ const preview = await dodoRequest(() =>
+ client.checkoutSessions.preview({
+ product_cart: [{ product_id: product.product_id, quantity: 1 }],
+ billing_currency: product.currency,
+ subscription_data: { trial_period_days: handover.trialDays },
+ }),
+ )
+ if (
+ preview.payment_method_required !== true ||
+ preview.current_breakup.total_amount !== 0 ||
+ (preview.trial_amount ?? 0) !== 0
+ )
+ fail('payment_trial_unavailable', 422)
+ }
const id = crypto.randomUUID()
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) SELECT ?,?,?,?,?,?,?,?,?,?,'creating',?,?,'dodo',?,? WHERE ${activeFence}`,
+ `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=?)`,
)
.bind(
id,
@@ -357,8 +390,11 @@ export async function createDodoCheckout(
now,
environment,
key,
+ handoverJson,
key,
revision,
+ input.workspaceId,
+ prior.revision,
)
.run()
if (!result.meta.changes) fail('payment_unavailable', 503)
@@ -372,6 +408,7 @@ export async function createDodoCheckout(
{
product_cart: [{ product_id: product.product_id, quantity: 1 }],
billing_currency: product.currency,
+ subscription_data: { trial_period_days: handover?.trialDays ?? 0 },
customer: { email: member.email },
metadata: {
chronoframe_checkout_id: id,
@@ -616,11 +653,40 @@ export async function reconcileDodoSubscription(
subscription.payment_frequency_interval !== 'Month' ||
subscription.payment_frequency_count !== checkout.interval ||
subscription.on_demand ||
- subscription.trial_period_days !== 0
+ !(
+ known?.activation_state === 'paid'
+ ? [
+ 0,
+ checkout.handover_json
+ ? JSON.parse(checkout.handover_json).trialDays
+ : 0,
+ ]
+ : [
+ checkout.handover_json
+ ? JSON.parse(checkout.handover_json).trialDays
+ : 0,
+ ]
+ ).includes(subscription.trial_period_days)
)
fail('payment_subscription_mismatch', 422)
+ if (checkout.handover_json) {
+ const deferred = await reconcileDeferredAuthorization(
+ db,
+ client,
+ checkout,
+ subscription,
+ known,
+ paymentId,
+ now,
+ `${activeFence} AND EXISTS(SELECT 1 FROM platform_payment_locks WHERE workspace_id=? AND token=?)`,
+ [key, revision, checkout.workspace_id, token],
+ localId,
+ )
+ if (deferred.handled) return checkout.id as string
+ paymentId = deferred.paymentId
+ }
// An initial grant must also be bound to the payment returned by our stored checkout session.
- if (!known && checkout.provider_id) {
+ if (!known && checkout.provider_id && !checkout.handover_json) {
const session = await dodoRequest(() =>
client.checkoutSessions.retrieve(rawDodoId(checkout.provider_id)),
)
@@ -805,20 +871,29 @@ export async function reconcileDodoSubscription(
.first()
)
fail('payment_account_unavailable')
- const canAssign = known
- ? prior?.payment_subscription_id === localId &&
- ['payment', 'expired_default'].includes(prior.source)
- : prior?.revision === checkout.assignment_revision ||
+ const initialHandover =
+ !!checkout.handover_json &&
+ (!known || known.activation_state === 'authorized')
+ const handoverRevision =
+ known?.handover_revision ?? checkout.assignment_revision
+ const canAssign = initialHandover
+ ? prior?.revision === handoverRevision ||
(prior?.source === 'expired_default' &&
- prior.revision === checkout.assignment_revision + 1)
- const anchor = known?.quota_anchor ?? start
+ prior.revision === handoverRevision + 1)
+ : known
+ ? prior?.payment_subscription_id === localId &&
+ ['payment', 'expired_default'].includes(prior.source)
+ : prior?.revision === checkout.assignment_revision ||
+ (prior?.source === 'expired_default' &&
+ prior.revision === checkout.assignment_revision + 1)
+ const anchor = initialHandover ? start : (known?.quota_anchor ?? start)
const eventId = crypto.randomUUID()
const fence = `${activeFence} AND EXISTS(SELECT 1 FROM platform_payment_locks WHERE workspace_id=? AND token=?)`
const bindFence = [key, revision, checkout.workspace_id, token]
const writes = [
db
.prepare(
- `INSERT INTO platform_payment_subscriptions(id,workspace_id,checkout_id,customer_id,product_id,plan_id,interval,quota_anchor,status,period_start,period_end,provider_updated_at,checked_at,next_check_at,error,provider,environment,provider_key,price,currency) SELECT ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'dodo',?,?,?,? WHERE ${fence} ON CONFLICT(id) DO UPDATE SET product_id=excluded.product_id,plan_id=excluded.plan_id,interval=excluded.interval,price=excluded.price,currency=excluded.currency,status=excluded.status,period_start=excluded.period_start,period_end=excluded.period_end,checked_at=excluded.checked_at,next_check_at=excluded.next_check_at,error=excluded.error,revision=platform_payment_subscriptions.revision+1`,
+ `INSERT INTO platform_payment_subscriptions(id,workspace_id,checkout_id,customer_id,product_id,plan_id,interval,quota_anchor,status,period_start,period_end,provider_updated_at,checked_at,next_check_at,error,provider,environment,provider_key,price,currency) SELECT ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'dodo',?,?,?,? WHERE ${fence} ON CONFLICT(id) DO UPDATE SET quota_anchor=CASE WHEN platform_payment_subscriptions.activation_state='authorized' THEN excluded.quota_anchor ELSE platform_payment_subscriptions.quota_anchor END,activation_state='paid',product_id=excluded.product_id,plan_id=excluded.plan_id,interval=excluded.interval,price=excluded.price,currency=excluded.currency,status=excluded.status,period_start=excluded.period_start,period_end=excluded.period_end,checked_at=excluded.checked_at,next_check_at=excluded.next_check_at,error=excluded.error,revision=platform_payment_subscriptions.revision+1`,
)
.bind(
localId,
@@ -1133,6 +1208,44 @@ export async function refreshDodoCheckout(
)
if (session.id !== rawDodoId(row.provider_id))
fail('payment_checkout_mismatch', 422)
+ if (row.handover_json && !session.payment_id) {
+ const known = await db
+ .prepare(
+ 'SELECT id FROM platform_payment_subscriptions WHERE checkout_id=?',
+ )
+ .bind(row.id)
+ .first<any>()
+ let subscriptionId = known ? rawDodoId(known.id) : undefined
+ if (!subscriptionId) {
+ const subscriptions = await dodoRequest(() =>
+ client.subscriptions.list({
+ product_id: row.product_id,
+ created_at_gte: new Date(row.created_at - 60000).toISOString(),
+ created_at_lte: new Date(row.created_at + 86400000).toISOString(),
+ page_size: 100,
+ }),
+ )
+ const matching = subscriptions.items.filter(
+ (s) =>
+ s.metadata?.chronoframe_checkout_id === row.id &&
+ s.metadata?.chronoframe_profile_id === key &&
+ s.metadata?.chronoframe_environment === environment,
+ )
+ if (matching.length > 1) fail('payment_subscription_mismatch', 422)
+ subscriptionId = matching[0]?.subscription_id
+ }
+ if (subscriptionId)
+ await reconcileDodoSubscription(
+ db,
+ secret,
+ environment,
+ subscriptionId,
+ undefined,
+ transport,
+ now,
+ key,
+ )
+ }
if (session.payment_id) {
const payment = await dodoRequest(() =>
client.payments.retrieve(session.payment_id!),
@@ -1169,7 +1282,7 @@ export async function refreshDodoCheckout(
} else if (now - row.created_at > 86400000)
await db
.prepare(
- "UPDATE platform_payment_checkouts SET state='expired',updated_at=? WHERE id=? AND state='open'",
+ "UPDATE platform_payment_checkouts SET state='expired',updated_at=? WHERE id=? AND state='open' AND NOT EXISTS(SELECT 1 FROM platform_payment_subscriptions WHERE checkout_id=platform_payment_checkouts.id)",
)
.bind(now, row.id)
.run()
@@ -1181,7 +1294,7 @@ export async function refreshDodoCheckout(
.run()
const latest = await db
.prepare(
- 'SELECT c.state,c.error,s.status FROM platform_payment_checkouts c LEFT JOIN platform_payment_subscriptions s ON s.checkout_id=c.id WHERE c.id=?',
+ 'SELECT c.state,c.error,s.status,s.activation_state FROM platform_payment_checkouts c LEFT JOIN platform_payment_subscriptions s ON s.checkout_id=c.id WHERE c.id=?',
)
.bind(row.id)
.first<any>()
@@ -1190,7 +1303,10 @@ export async function refreshDodoCheckout(
latest.error === 'payment_subscription_inactive' ||
['canceled', 'expired', 'failed'].includes(latest.status)
? 'inactive'
- : latest.state,
+ : latest.activation_state === 'authorized' &&
+ latest.state === 'completed'
+ ? 'scheduled'
+ : latest.state,
}
}
export async function reconcileDodoPayments(
@@ -1332,3 +1448,71 @@ export async function closeDodoAccountPayments(
.bind(userId, userId)
.first())
}
+
+export async function cancelDeferredSubscription(
+ db: PlatformD1,
+ secret: string,
+ userId: number,
+ workspaceId: number,
+ transport: typeof fetch = fetch,
+ now = Date.now(),
+) {
+ await paymentMember(db, userId, workspaceId, true)
+ const environment = await selectedEnvironment(db),
+ key = (await paymentSettings(db)).currentProvider!
+ const row = await db
+ .prepare(
+ "SELECT s.* FROM platform_payment_subscriptions s JOIN platform_payment_checkouts c ON c.id=s.checkout_id WHERE s.workspace_id=? AND c.user_id=? AND s.provider_key=? AND s.activation_state='authorized' AND s.status NOT IN('canceled','expired','failed')",
+ )
+ .bind(workspaceId, userId, key)
+ .first<any>()
+ if (!row) fail('payment_handover_unavailable', 404)
+ const { client } = await dodoClient(
+ db,
+ secret,
+ environment,
+ transport,
+ true,
+ key,
+ )
+ const actual = await dodoRequest(() =>
+ client.subscriptions.retrieve(rawDodoId(row.id)),
+ )
+ if (
+ actual.customer.customer_id !== row.customer_id ||
+ actual.metadata?.chronoframe_checkout_id !== row.checkout_id
+ )
+ fail('payment_subscription_mismatch', 422)
+ if (
+ Math.max(now, Date.now()) >= row.handover_at - 60000 ||
+ timestamp(actual.next_billing_date) !== row.handover_at
+ )
+ fail('payment_handover_due')
+ if (actual.status !== 'cancelled')
+ await dodoRequest(() =>
+ client.subscriptions.update(
+ rawDodoId(row.id),
+ { status: 'cancelled' },
+ {
+ headers: {
+ 'Idempotency-Key': `cf-cancel-handover-${row.checkout_id}`,
+ },
+ },
+ ),
+ )
+ const confirmed = await dodoRequest(() =>
+ client.subscriptions.retrieve(rawDodoId(row.id)),
+ )
+ if (confirmed.status !== 'cancelled') fail('payment_confirmation_pending')
+ await reconcileDodoSubscription(
+ db,
+ secret,
+ environment,
+ rawDodoId(row.id),
+ undefined,
+ transport,
+ now,
+ key,
+ )
+ return { state: 'cancelled' }
+}
diff --git a/packages/platform/src/payment-handover.ts b/packages/platform/src/payment-handover.ts
new file mode 100644
index 00000000..af892bc5
--- /dev/null
+++ b/packages/platform/src/payment-handover.ts
@@ -0,0 +1,80 @@
+import type { PlatformD1 } from './index.ts'
+import {
+ allRows,
+ resolveSubscription,
+ SubscriptionError,
+} from './subscriptions.ts'
+export const DAY = 86400000
+export async function handoverContext(
+ db: PlatformD1,
+ workspaceId: number,
+ now = Date.now(),
+) {
+ const current = await resolveSubscription(db, workspaceId, now)
+ if (
+ !['promotion', 'activation', 'manual'].includes(current.source) ||
+ !(Number(current.monthly_price) > 0 || Number(current.quarterly_price) > 0)
+ )
+ return null
+ const upgrades = await allRows<any>(
+ db
+ .prepare(
+ "SELECT r.to_plan FROM platform_payment_plan_rules r JOIN platform_plans p ON p.id=r.to_plan WHERE r.from_plan=? AND r.direction='upgrade' AND r.enabled=1 AND p.active=1 AND p.listed=1",
+ )
+ .bind(current.id),
+ )
+ return {
+ planId: current.id,
+ name: current.name,
+ source: current.source,
+ startsAt: current.subscription.startsAt,
+ expiresAt: current.subscription.expiresAt,
+ revision: current.assignment_revision,
+ upgradePlans: upgrades.map((r) => r.to_plan) as string[],
+ }
+}
+export async function checkoutHandover(
+ db: PlatformD1,
+ workspaceId: number,
+ planId: string,
+ mode: unknown,
+ replace: unknown,
+ now: number,
+) {
+ if (
+ mode !== undefined &&
+ !['immediate', 'after_entitlement'].includes(String(mode))
+ )
+ throw new SubscriptionError(400, 'payment_start_mode_invalid')
+ const context = await handoverContext(db, workspaceId, now)
+ if (!context) {
+ if (mode === 'after_entitlement')
+ throw new SubscriptionError(409, 'payment_entitlement_changed')
+ return null
+ }
+ if (planId !== context.planId && !context.upgradePlans.includes(planId))
+ throw new SubscriptionError(409, 'payment_upgrade_not_allowed')
+ const chosen =
+ mode ?? (planId === context.planId ? 'after_entitlement' : 'immediate')
+ if (chosen === 'immediate') {
+ if (planId === context.planId || replace !== true)
+ throw new SubscriptionError(400, 'payment_replace_confirmation_required')
+ return null
+ }
+ if (context.expiresAt === null)
+ throw new SubscriptionError(409, 'permanent_plan_active')
+ const trialDays = Math.ceil((context.expiresAt - now) / DAY)
+ if (trialDays < 1 || trialDays > 10000)
+ throw new SubscriptionError(409, 'payment_handover_date_unavailable')
+ return { ...context, trialDays }
+}
+export const NO_HANDOVER = `NOT EXISTS(SELECT 1 FROM platform_payment_checkouts h WHERE h.workspace_id=? AND h.handover_json IS NOT NULL AND h.state IN('creating','open','uncertain')) AND NOT EXISTS(SELECT 1 FROM platform_payment_subscriptions h WHERE h.workspace_id=? AND h.activation_state='authorized' AND h.status NOT IN('canceled','expired','failed'))`
+export async function requireNoHandover(db: PlatformD1, workspaceId: number) {
+ if (
+ !(await db
+ .prepare(`SELECT 1 AS allowed WHERE ${NO_HANDOVER}`)
+ .bind(workspaceId, workspaceId)
+ .first())
+ )
+ throw new SubscriptionError(409, 'payment_handover_exists')
+}
diff --git a/packages/platform/src/payments.ts b/packages/platform/src/payments.ts
index 994eec25..69faeaa9 100644
--- a/packages/platform/src/payments.ts
+++ b/packages/platform/src/payments.ts
@@ -1,3 +1,4 @@
+import { handoverContext } from './payment-handover.ts'
import {
createDodoCheckout,
refreshDodoCheckout,
@@ -163,12 +164,19 @@ export async function paymentStatus(
const subscriptions = await allRows<any>(
db
.prepare(
- 'SELECT id,status,period_start,period_end,plan_id,interval,error FROM platform_payment_subscriptions WHERE workspace_id=? ORDER BY checked_at DESC LIMIT 10',
+ 'SELECT id,status,period_start,period_end,plan_id,interval,error,activation_state,handover_at FROM platform_payment_subscriptions WHERE workspace_id=? ORDER BY checked_at DESC LIMIT 10',
)
.bind(workspaceId),
)
return {
+ entitlement: await handoverContext(db, workspaceId),
+ reservation: await db
+ .prepare(
+ "SELECT s.id,s.checkout_id AS checkoutId,s.plan_id AS planId,p.name AS planName,s.handover_at AS startsAt,s.status,s.error,CASE WHEN c.user_id=? AND ?='admin' THEN 1 ELSE 0 END AS canCancel FROM platform_payment_subscriptions s JOIN platform_plans p ON p.id=s.plan_id JOIN platform_payment_checkouts c ON c.id=s.checkout_id WHERE s.workspace_id=? AND s.provider_key=? AND s.activation_state='authorized' AND s.status NOT IN('canceled','expired','failed') ORDER BY s.checked_at DESC LIMIT 1",
+ )
+ .bind(userId, membership.role, workspaceId, settings.currentProvider)
+ .first(),
environment: settings.environment,
purchaseMethod: settings.enabled
? settings.purchaseMethod
@@ -206,7 +214,7 @@ export async function paymentStatus(
membership.role === 'admin' &&
(await db
.prepare(
- "SELECT 1 FROM platform_payment_subscriptions s JOIN platform_payment_checkouts c ON c.id=s.checkout_id WHERE s.workspace_id=? AND c.user_id=? AND s.provider='dodo' AND s.provider_key=? AND s.environment=? AND s.status IN('active','scheduled_cancel','past_due') AND s.period_end>?",
+ "SELECT 1 FROM platform_payment_subscriptions s JOIN platform_payment_checkouts c ON c.id=s.checkout_id WHERE s.workspace_id=? AND c.user_id=? AND s.provider='dodo' AND s.provider_key=? AND s.environment=? AND s.status IN('active','scheduled_cancel','past_due') AND (s.period_end>? OR s.activation_state='authorized')",
)
.bind(
workspaceId,
@@ -220,7 +228,7 @@ export async function paymentStatus(
changes: await allRows<any>(
db
.prepare(
- "SELECT r.to_plan AS planId,r.direction,d.interval,d.effective_price AS price,d.currency FROM platform_payment_plan_rules r JOIN platform_payment_subscriptions s ON s.plan_id=r.from_plan JOIN platform_workspace_plans w ON w.payment_subscription_id=s.id AND w.source='payment' JOIN platform_dodo_products d ON d.plan_id=r.to_plan AND d.provider_key=s.provider_key AND d.interval=s.interval JOIN platform_plans p ON p.id=d.plan_id JOIN platform_payment_providers v ON v.id=d.provider_key WHERE s.workspace_id=? AND s.provider_key=? AND s.environment=? AND s.status='active' AND s.period_end>? AND r.enabled=1 AND p.active=1 AND p.listed=1 AND d.plan_revision=p.revision AND d.credential_revision=v.revision AND d.effective_price>0 AND d.currency=s.currency",
+ "SELECT r.to_plan AS planId,r.direction,d.interval,d.effective_price AS price,d.currency FROM platform_payment_plan_rules r JOIN platform_payment_subscriptions s ON s.plan_id=r.from_plan JOIN platform_workspace_plans w ON w.payment_subscription_id=s.id AND w.source='payment' JOIN platform_dodo_products d ON d.plan_id=r.to_plan AND d.provider_key=s.provider_key AND d.interval=s.interval JOIN platform_plans p ON p.id=d.plan_id JOIN platform_payment_providers v ON v.id=d.provider_key WHERE s.workspace_id=? AND s.provider_key=? AND s.environment=? AND s.status='active' AND s.activation_state='paid' AND s.period_end>? AND r.enabled=1 AND p.active=1 AND p.listed=1 AND d.plan_revision=p.revision AND d.credential_revision=v.revision AND d.effective_price>0 AND d.currency=s.currency",
)
.bind(
workspaceId,
@@ -267,6 +275,8 @@ export async function createPaymentCheckout(
planId: string
interval: number
requestId: string
+ startMode?: string
+ replaceEntitlement?: boolean
},
portalOrigin: string,
transport: PaymentFetch = fetch,
@@ -300,7 +310,7 @@ export async function createPaymentPortal(
// A customer portal exposes every subscription for that customer, not just this workspace.
const sub = await db
.prepare(
- "SELECT s.* FROM platform_payment_subscriptions s JOIN platform_payment_checkouts c ON c.id=s.checkout_id WHERE s.workspace_id=? AND c.user_id=? AND s.provider='dodo' AND s.provider_key=? AND s.environment=? AND s.status IN('active','scheduled_cancel','past_due') AND s.period_end>? ORDER BY s.checked_at DESC LIMIT 1",
+ "SELECT s.* FROM platform_payment_subscriptions s JOIN platform_payment_checkouts c ON c.id=s.checkout_id WHERE s.workspace_id=? AND c.user_id=? AND s.provider='dodo' AND s.provider_key=? AND s.environment=? AND s.status IN('active','scheduled_cancel','past_due') AND (s.period_end>? OR s.activation_state='authorized') ORDER BY s.checked_at DESC LIMIT 1",
)
.bind(
workspaceId,
diff --git a/tests/dodo-checkout-return.test.ts b/tests/dodo-checkout-return.test.ts
index 81b5c71b..fb5fd431 100644
--- a/tests/dodo-checkout-return.test.ts
+++ b/tests/dodo-checkout-return.test.ts
@@ -220,3 +220,21 @@ test('actual workspace and payment availability changes still restart the return
f.dispose()
}
})
+
+test('a confirmed deferred reservation closes the processing modal without further polls', async () => {
+ let refreshes = 0
+ const f = fixture(
+ async () => ({ state: 'scheduled' }),
+ async () => {
+ refreshes++
+ },
+ )
+ try {
+ await flush()
+ assert.equal(f.returned.state.value, 'scheduled')
+ assert.equal(refreshes, 1)
+ assert.equal(f.timers.length, 0)
+ } finally {
+ f.dispose()
+ }
+})
diff --git a/tests/dodo-payments.test.ts b/tests/dodo-payments.test.ts
index f2e0da51..c6921945 100644
--- a/tests/dodo-payments.test.ts
+++ b/tests/dodo-payments.test.ts
@@ -26,6 +26,7 @@ import {
closeAccountPayments,
} from '../packages/platform/src/payments.ts'
import {
+ cancelDeferredSubscription,
syncDodoProducts,
receiveDodoEvent,
processDodoEvents,
@@ -154,6 +155,12 @@ async function fixture() {
}
if (url.pathname.startsWith('/products/'))
return Response.json(products.get(url.pathname.split('/')[2]!))
+ if (url.pathname === '/checkouts/preview')
+ return Response.json({
+ payment_method_required: true,
+ current_breakup: { total_amount: 0 },
+ trial_amount: null,
+ })
if (url.pathname === '/checkouts' && init?.method === 'POST') {
if (createUncertain) throw Error('provider raw secret')
const id = 'cks_' + environment + '_' + sessions.size
@@ -163,6 +170,7 @@ async function fixture() {
product_id: body.product_cart[0].product_id,
payment_id: null,
payment_status: null,
+ trial_period_days: body.subscription_data?.trial_period_days ?? 0,
})
return Response.json({
session_id: id,
@@ -171,8 +179,13 @@ async function fixture() {
}
if (url.pathname.startsWith('/checkouts/'))
return Response.json(sessions.get(url.pathname.split('/')[2]!))
- if (url.pathname.startsWith('/subscriptions/'))
- return Response.json(subscriptions.get(url.pathname.split('/')[2]!))
+ if (url.pathname.startsWith('/subscriptions/')) {
+ const sub = subscriptions.get(url.pathname.split('/')[2]!)
+ if (init?.method === 'PATCH') Object.assign(sub, body)
+ return Response.json(sub)
+ }
+ if (url.pathname === '/subscriptions')
+ return Response.json({ items: [...subscriptions.values()] })
if (url.pathname === '/payments')
return Response.json({ items: [...payments.values()] })
if (url.pathname.startsWith('/payments/'))
@@ -2120,3 +2133,447 @@ for (const state of ['submitting', 'pending', 'scheduled', 'uncertain']) {
}
})
}
+
+const origin = 'https://app.chronoframe.art'
+async function handoverFixture(source = 'activation', higher = false) {
+ const f = await fixture(),
+ originalStart = f.now - 2 * 86400000,
+ originalEnd = f.now + 3.4 * 86400000
+ await f.db
+ .prepare(
+ "UPDATE platform_workspace_plans SET plan_id='pro',source=?,starts_at=?,expires_at=?,revision=revision+1 WHERE workspace_id=1",
+ )
+ .bind(source, originalStart, originalEnd)
+ .run()
+ if (higher) {
+ await f.db
+ .prepare(
+ "INSERT INTO platform_plans(id,name,policy_json,currency,monthly_price,quarterly_price) SELECT 'studio','Studio',policy_json,'USD',2400,6000 FROM platform_plans WHERE id='pro'",
+ )
+ .run()
+ await savePaymentPlanRule(
+ f.db,
+ 1,
+ {
+ fromPlan: 'pro',
+ toPlan: 'studio',
+ direction: 'upgrade',
+ enabled: true,
+ revision: 0,
+ reason: 'Allow paid tier upgrades',
+ },
+ f.now,
+ )
+ }
+ await syncDodoProducts(f.db, root, f.transport, f.now, 10)
+ return { ...f, originalStart, originalEnd }
+}
+async function authorizeHandover(
+ f: Awaited<ReturnType<typeof handoverFixture>>,
+ planId = 'pro',
+) {
+ const checkout = await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ { ...input('handover_checkout'), planId, startMode: 'after_entitlement' },
+ origin,
+ f.transport,
+ f.now,
+ )
+ const { sub, payment, session } = await f.paid(checkout)
+ sub.trial_period_days = session.trial_period_days
+ sub.previous_billing_date = new Date(f.now).toISOString()
+ const at = f.now + sub.trial_period_days * 86400000
+ sub.next_billing_date = new Date(at).toISOString()
+ payment.total_amount = 0
+ payment.service_periods = []
+ const result = await refreshDodoCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.id,
+ f.transport,
+ f.now + 1000,
+ )
+ assert.equal(result.state, 'scheduled')
+ return { checkout, sub, payment, session, at }
+}
+for (const source of ['promotion', 'activation'])
+ test(`${source} same-tier conversion authorizes without charging, preserves quota anchor, then activates only a paid service period`, async () => {
+ const f = await handoverFixture(source)
+ try {
+ const { checkout, sub, payment, at } = await authorizeHandover(f)
+ assert.equal(sub.trial_period_days, 4)
+ assert.ok(at >= f.originalEnd)
+ const before = await f.db
+ .prepare('SELECT * FROM platform_workspace_plans WHERE workspace_id=1')
+ .first<any>()
+ assert.equal(before.source, source)
+ assert.equal(before.starts_at, f.originalStart)
+ assert.equal(before.expires_at, at)
+ const status = await paymentStatus(f.db, 1, 1)
+ assert.equal((status.reservation as any).startsAt, at)
+ assert.equal(status.hasActiveSubscription, true)
+ assert.equal(status.canOpenPortal, true)
+ const { requireNoHandover } =
+ await import('../packages/platform/src/payment-handover.ts')
+ await assert.rejects(requireNoHandover(f.db, 1), {
+ code: 'payment_handover_exists',
+ })
+ await refreshDodoCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.id,
+ f.transport,
+ f.now + 2000,
+ )
+ assert.equal(
+ (
+ await f.db
+ .prepare(
+ 'SELECT revision FROM platform_workspace_plans WHERE workspace_id=1',
+ )
+ .first<any>()
+ ).revision,
+ before.revision,
+ )
+ sub.previous_billing_date = new Date(at).toISOString()
+ sub.next_billing_date = new Date(at + 28 * 86400000).toISOString()
+ const first = {
+ ...payment,
+ payment_id: 'pay_first_handover',
+ total_amount: 1200,
+ created_at: new Date(at + 1000).toISOString(),
+ service_periods: [
+ {
+ subscription_id: sub.subscription_id,
+ starts_at: sub.previous_billing_date,
+ ends_at: sub.next_billing_date,
+ },
+ ],
+ }
+ f.payments.set(first.payment_id, first)
+ const completed = await refreshDodoCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.id,
+ f.transport,
+ at + 2000,
+ )
+ assert.equal(completed.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.plan_id, 'pro')
+ assert.equal(grant.starts_at, at)
+ assert.equal(grant.expires_at, at + 28 * 86400000)
+ assert.equal(
+ (
+ await f.db
+ .prepare(
+ 'SELECT activation_state FROM platform_payment_subscriptions',
+ )
+ .first<any>()
+ ).activation_state,
+ 'paid',
+ )
+ await refreshDodoCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.id,
+ f.transport,
+ at + 3000,
+ )
+ assert.equal(
+ (
+ await f.db
+ .prepare(
+ 'SELECT starts_at FROM platform_workspace_plans WHERE workspace_id=1',
+ )
+ .first<any>()
+ ).starts_at,
+ at,
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+ })
+test('deferred higher-tier purchase keeps the old tier until first payment; failure cannot extend complimentary access', async () => {
+ const f = await handoverFixture('activation', true)
+ try {
+ const { checkout, sub, payment, at } = await authorizeHandover(f, 'studio')
+ assert.equal(
+ (
+ await f.db
+ .prepare(
+ 'SELECT plan_id FROM platform_workspace_plans WHERE workspace_id=1',
+ )
+ .first<any>()
+ ).plan_id,
+ 'pro',
+ )
+ payment.status = 'failed'
+ payment.total_amount = 2400
+ sub.status = 'on_hold'
+ sub.next_billing_date = new Date(at + 28 * 86400000).toISOString()
+ await refreshDodoCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.id,
+ f.transport,
+ at + 2000,
+ )
+ const grant = await f.db
+ .prepare('SELECT * FROM platform_workspace_plans WHERE workspace_id=1')
+ .first<any>()
+ assert.equal(grant.plan_id, 'pro')
+ assert.equal(grant.expires_at, at)
+ assert.equal((await paymentStatus(f.db, 1, 1)).canOpenPortal, true)
+ const { resolveSubscription } =
+ await import('../packages/platform/src/subscriptions.ts')
+ assert.equal((await resolveSubscription(f.db, 1, at + 2000)).id, 'free')
+ } finally {
+ await f.mf.dispose()
+ }
+})
+test('reservation cancellation restores original expiry and releases code redemption; wrong owners and imminent billing cannot cancel', async () => {
+ const f = await handoverFixture()
+ try {
+ const { checkout, sub, at } = await authorizeHandover(f)
+ await assert.rejects(
+ cancelDeferredSubscription(f.db, root, 2, 1, f.transport, f.now + 1000),
+ { code: 'workspace_admin_required' },
+ )
+ await assert.rejects(
+ cancelDeferredSubscription(f.db, root, 1, 1, f.transport, at - 1000),
+ { code: 'payment_handover_due' },
+ )
+ await cancelDeferredSubscription(
+ f.db,
+ root,
+ 1,
+ 1,
+ f.transport,
+ f.now + 2000,
+ )
+ assert.equal(sub.status, 'cancelled')
+ const grant = await f.db
+ .prepare('SELECT * FROM platform_workspace_plans WHERE workspace_id=1')
+ .first<any>()
+ assert.equal(grant.expires_at, f.originalEnd)
+ assert.equal(grant.starts_at, f.originalStart)
+ assert.equal(grant.source, 'activation')
+ assert.equal(
+ (
+ await refreshDodoCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.id,
+ f.transport,
+ f.now + 3000,
+ )
+ ).state,
+ 'inactive',
+ )
+ const { requireNoHandover } =
+ await import('../packages/platform/src/payment-handover.ts')
+ await requireNoHandover(f.db, 1)
+ assert.equal((await paymentStatus(f.db, 1, 1)).hasActiveSubscription, false)
+ } finally {
+ await f.mf.dispose()
+ }
+})
+test('explicit immediate upgrades require replacement consent; invalid transitions and permanent same-tier conversion are rejected', async () => {
+ const f = await handoverFixture('activation', true)
+ try {
+ await assert.rejects(
+ createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ {
+ ...input('upgrade_missing_consent'),
+ planId: 'studio',
+ startMode: 'immediate',
+ },
+ origin,
+ f.transport,
+ f.now,
+ ),
+ { code: 'payment_replace_confirmation_required' },
+ )
+ const checkout = await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ {
+ ...input('upgrade_with_consent'),
+ planId: 'studio',
+ startMode: 'immediate',
+ replaceEntitlement: true,
+ },
+ origin,
+ f.transport,
+ f.now,
+ )
+ assert.equal(
+ f.sessions.get(checkout.url.split('/').pop()!)?.trial_period_days,
+ 0,
+ )
+ await f.paid(checkout)
+ await refreshDodoCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.id,
+ f.transport,
+ f.now + 1000,
+ )
+ assert.equal(
+ (
+ await f.db
+ .prepare(
+ 'SELECT plan_id FROM platform_workspace_plans WHERE workspace_id=1',
+ )
+ .first<any>()
+ ).plan_id,
+ 'studio',
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+ const permanent = await handoverFixture()
+ try {
+ await permanent.db
+ .prepare(
+ 'UPDATE platform_workspace_plans SET expires_at=NULL WHERE workspace_id=1',
+ )
+ .run()
+ await assert.rejects(
+ createPaymentCheckout(
+ permanent.db,
+ root,
+ 1,
+ input('permanent_conversion'),
+ origin,
+ permanent.transport,
+ permanent.now,
+ ),
+ { code: 'permanent_plan_active' },
+ )
+ } finally {
+ await permanent.mf.dispose()
+ }
+})
+
+test('handover refuses cardless authorization and preserves the original grant', async () => {
+ const f = await handoverFixture()
+ try {
+ const transport: typeof fetch = async (url, init) =>
+ String(url).includes('/checkouts/preview')
+ ? Response.json({
+ payment_method_required: false,
+ current_breakup: { total_amount: 0 },
+ })
+ : f.transport(url, init)
+ await assert.rejects(
+ createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ input('cardless_handover'),
+ origin,
+ transport,
+ f.now,
+ ),
+ { code: 'payment_trial_unavailable' },
+ )
+ assert.equal(f.sessions.size, 0)
+ assert.equal(
+ (
+ await f.db
+ .prepare(
+ 'SELECT expires_at FROM platform_workspace_plans WHERE workspace_id=1',
+ )
+ .first<any>()
+ ).expires_at,
+ f.originalEnd,
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+})
+test('superseded handovers cancel without overwriting a newer entitlement', async () => {
+ const f = await handoverFixture()
+ try {
+ const { checkout, sub } = await authorizeHandover(f)
+ await f.db
+ .prepare(
+ "UPDATE platform_workspace_plans SET source='manual',expires_at=?,revision=revision+1 WHERE workspace_id=1",
+ )
+ .bind(f.originalEnd + 10 * 86400000)
+ .run()
+ await refreshDodoCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.id,
+ f.transport,
+ f.now + 2000,
+ )
+ assert.equal(sub.status, 'cancelled')
+ const grant = await f.db
+ .prepare(
+ 'SELECT source,expires_at FROM platform_workspace_plans WHERE workspace_id=1',
+ )
+ .first<any>()
+ assert.equal(grant.source, 'manual')
+ assert.equal(grant.expires_at, f.originalEnd + 10 * 86400000)
+ } finally {
+ await f.mf.dispose()
+ }
+})
+test('an authorization without a payment ID converges and blocks redemption until canceled', async () => {
+ const f = await handoverFixture()
+ try {
+ const { checkout, session } = await authorizeHandover(f)
+ session.payment_id = null
+ f.payments.clear()
+ assert.equal(
+ (
+ await refreshDodoCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.id,
+ f.transport,
+ f.now + 2000,
+ )
+ ).state,
+ 'scheduled',
+ )
+ const { requireNoHandover } =
+ await import('../packages/platform/src/payment-handover.ts')
+ await assert.rejects(requireNoHandover(f.db, 1), {
+ code: 'payment_handover_exists',
+ })
+ } finally {
+ await f.mf.dispose()
+ }
+})