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(payments): support configured Dodo subscription upgrades and downgrades

Timothy Yineb89c55f0abe
diff --git a/apps/cloud/app/components/CloudPricing.vue b/apps/cloud/app/components/CloudPricing.vue
index 4f9874c0..6f99d581 100644
--- a/apps/cloud/app/components/CloudPricing.vue
+++ b/apps/cloud/app/components/CloudPricing.vue
@@ -110,9 +110,75 @@ async function resume() {
const offer = (plan: any) =>
payment.value?.enabled &&
payment.value?.canManage &&
+ !payment.value?.hasActiveSubscription &&
payment.value.offers.some(
(v: any) => v.plan_id === plan.id && v.interval === interval.value,
)
+const changeQuote = ref<any>(null),
+ changeOpen = ref(false),
+ changeBusy = ref(false),
+ changeError = ref('')
+const changeFor = (plan: any) =>
+ payment.value?.enabled &&
+ payment.value?.canManage &&
+ !payment.value?.planChange &&
+ payment.value?.changes?.find(
+ (c: any) => c.planId === plan.id && c.interval === interval.value,
+ )
+async function previewChange(plan: any) {
+ if (changeBusy.value || !billing?.selected.value) return
+ changeBusy.value = true
+ changeError.value = ''
+ changeQuote.value = null
+ changeOpen.value = true
+ try {
+ changeQuote.value = await $fetch('/api/billing/payments', {
+ method: 'POST',
+ timeout: 15000,
+ body: {
+ action: 'preview-change',
+ workspaceId: billing.selected.value,
+ planId: plan.id,
+ },
+ })
+ } catch {
+ changeError.value = t('cloud.payments.changeFailed')
+ } finally {
+ changeBusy.value = false
+ }
+}
+async function confirmChange() {
+ if (changeBusy.value || !changeQuote.value || !billing?.selected.value) return
+ changeBusy.value = true
+ changeError.value = ''
+ try {
+ await $fetch('/api/billing/payments', {
+ method: 'POST',
+ timeout: 25000,
+ body: {
+ action: 'change-plan',
+ workspaceId: billing.selected.value,
+ quoteId: changeQuote.value.id,
+ },
+ })
+ changeOpen.value = false
+ } catch {
+ changeError.value = t('cloud.payments.changeFailed')
+ } finally {
+ await Promise.all([
+ payments?.refresh({ reconcile: false }),
+ billing?.refresh(),
+ ])
+ changeBusy.value = false
+ }
+}
+watch(
+ () => billing?.selected.value,
+ () => {
+ changeOpen.value = false
+ changeQuote.value = null
+ },
+)
async function checkout(plan: any) {
if (paying.value || !billing?.selected.value) return
const workspaceId = billing.selected.value,
@@ -183,6 +249,25 @@ async function checkout(plan: any) {
: $t('cloud.billing.purchaseHelp')
}}
</p>
+ <p
+ v-if="payment?.planChange"
+ class="cf-notice"
+ role="status"
+ >
+ {{
+ $t(
+ payment.planChange.state === 'scheduled'
+ ? 'cloud.payments.changeScheduled'
+ : 'cloud.payments.changePending',
+ )
+ }}
+ <CfButton
+ variant="ghost"
+ :disabled="payments?.busy.value"
+ @click="payments?.refresh()"
+ >{{ $t('cloud.payments.checkAgain') }}</CfButton
+ >
+ </p>
<p
v-if="payment?.pending?.state === 'uncertain'"
class="cf-field-hint"
@@ -344,6 +429,19 @@ async function checkout(plan: any) {
variant="secondary"
>{{ $t('cloud.billing.current') }}</CfButton
>
+ <CfButton
+ v-else-if="portal && changeFor(plan)"
+ :disabled="changeBusy || !!payment.pending"
+ :variant="plan.featured ? 'default' : 'secondary'"
+ @click="previewChange(plan)"
+ >{{
+ $t(
+ changeFor(plan).direction === 'upgrade'
+ ? 'cloud.payments.upgrade'
+ : 'cloud.payments.downgrade',
+ )
+ }}</CfButton
+ >
<CfButton
v-else-if="portal && offer(plan)"
:loading="paying === plan.id + ':' + interval"
@@ -447,6 +545,74 @@ async function checkout(plan: any) {
>{{ $t('cloud.billing.redeem') }}</NuxtLink
>
</div>
+ <UModal
+ v-model:open="changeOpen"
+ :title="$t('cloud.payments.changeTitle')"
+ :dismissible="!changeBusy"
+ :close="!changeBusy"
+ >
+ <template #body
+ ><div class="cf-form">
+ <p
+ v-if="changeBusy && !changeQuote"
+ role="status"
+ >
+ {{ $t('cloud.billing.loading') }}
+ </p>
+ <template v-if="changeQuote">
+ <p>
+ {{
+ $t(
+ changeQuote.direction === 'upgrade'
+ ? 'cloud.payments.upgradeHelp'
+ : 'cloud.payments.downgradeHelp',
+ )
+ }}
+ </p>
+ <p>
+ {{ $t('cloud.payments.chargeNow') }}
+ <strong>{{
+ price(
+ changeQuote.charge.total_amount,
+ changeQuote.charge.currency,
+ locale,
+ )
+ }}</strong>
+ </p>
+ <p>
+ {{ $t('cloud.payments.newRecurring') }}
+ <strong>{{
+ price(changeQuote.renewalAmount, changeQuote.currency, locale)
+ }}</strong>
+ /
+ {{
+ $t(
+ changeQuote.interval === 1
+ ? 'cloud.billing.month'
+ : 'cloud.billing.quarter',
+ )
+ }}
+ </p>
+ <p class="cf-field-hint">{{ $t('cloud.payments.savedMethod') }}</p>
+ </template>
+ <p
+ v-if="changeError"
+ class="cf-error-message"
+ role="alert"
+ >
+ {{ changeError }}
+ </p>
+ </div></template
+ >
+ <template #footer
+ ><CfButton
+ :disabled="changeBusy || !changeQuote"
+ :loading="changeBusy"
+ @click="confirmChange"
+ >{{ $t('cloud.payments.confirmChange') }}</CfButton
+ ></template
+ >
+ </UModal>
<CloudLegalLinks />
</div>
</template>
diff --git a/apps/cloud/app/composables/useCloudPayments.ts b/apps/cloud/app/composables/useCloudPayments.ts
index 70e3bbd9..6eb2fb9e 100644
--- a/apps/cloud/app/composables/useCloudPayments.ts
+++ b/apps/cloud/app/composables/useCloudPayments.ts
@@ -30,7 +30,7 @@ export function useCloudPayments(
current === generation &&
reconcile &&
result.canManage &&
- result.pending?.canRefresh
+ (result.pending?.canRefresh || result.planChange)
) {
// A stored checkout must converge even when the return URL parameters are gone.
try {
@@ -38,9 +38,9 @@ export function useCloudPayments(
method: 'POST',
timeout: 15000,
body: {
- action: 'refresh',
+ action: result.planChange ? 'check-change' : 'refresh',
workspaceId: id,
- checkoutId: result.pending.id,
+ checkoutId: result.pending?.id,
},
})
} catch {
@@ -51,7 +51,12 @@ export function useCloudPayments(
query: { workspaceId: id },
timeout: 15000,
})
- if (alive && current === generation && !result.pending)
+ if (
+ alive &&
+ current === generation &&
+ !result.pending &&
+ !result.planChange
+ )
await onReconciled?.()
}
if (alive && current === generation) {
diff --git a/apps/cloud/app/pages/account/plan.vue b/apps/cloud/app/pages/account/plan.vue
index 57080941..f1f6ac0d 100644
--- a/apps/cloud/app/pages/account/plan.vue
+++ b/apps/cloud/app/pages/account/plan.vue
@@ -21,6 +21,25 @@ const latestSubscription = computed(() => {
rows[0]
)
})
+const portalBusy = ref(false),
+ portalError = ref('')
+async function openBillingPortal() {
+ if (portalBusy.value) return
+ portalBusy.value = true
+ portalError.value = ''
+ try {
+ const result = await $fetch<{ url: string }>('/api/billing/payments', {
+ method: 'POST',
+ timeout: 15000,
+ body: { action: 'portal', workspaceId: selected.value },
+ })
+ await navigateTo(result.url, { external: true })
+ } catch {
+ portalError.value = t('cloud.payments.portalFailed')
+ } finally {
+ portalBusy.value = false
+ }
+}
const quotaKeys = BILLING_LIMITS.filter((key) => key !== 'byos')
await ready
useSeoMeta({
@@ -132,6 +151,20 @@ const date = (time: number) => new Date(time).toLocaleString(locale.value)
</p>
</div>
<div class="cf-plan-management">
+ <CfButton
+ v-if="payments.data.value?.canOpenPortal"
+ variant="secondary"
+ :loading="portalBusy"
+ @click="openBillingPortal"
+ >{{ $t('cloud.payments.manage') }}</CfButton
+ >
+ <p
+ v-if="portalError"
+ class="cf-error-message"
+ role="alert"
+ >
+ {{ portalError }}
+ </p>
<CfButton
v-if="data.workspace.role === 'admin'"
as-child
diff --git a/apps/cloud/i18n/locales/en.json b/apps/cloud/i18n/locales/en.json
index 498c7dbd..7f46d416 100644
--- a/apps/cloud/i18n/locales/en.json
+++ b/apps/cloud/i18n/locales/en.json
@@ -414,6 +414,19 @@
"draft": "Draft",
"photograph": "Photograph",
"photographs": "Photographs",
+ "upgrade": "Upgrade plan",
+ "downgrade": "Downgrade plan",
+ "changeTitle": "Confirm subscription change",
+ "changeFailed": "The change could not be confirmed. Refresh subscription status before trying again; do not create another subscription.",
+ "upgradeHelp": "The upgrade applies after Dodo confirms the change. Dodo prorates the price difference for the remaining billing period; the renewal date stays the same.",
+ "downgradeHelp": "The downgrade is scheduled for the next billing date. Your current plan remains available until then.",
+ "chargeNow": "Estimated charge now:",
+ "newRecurring": "New recurring price:",
+ "savedMethod": "Confirming authorizes Dodo to charge the payment method saved on this subscription where payment is due. The final charge is calculated when the change is submitted.",
+ "confirmChange": "Confirm change",
+ "changeScheduled": "A plan change is scheduled for the next billing date. Your current entitlements remain in place.",
+ "changePending": "Your plan change is being confirmed. Do not submit another change or purchase another subscription.",
+ "portalFailed": "Could not open the billing portal. Only the original subscriber can access it; retry or contact support.",
"confirmationReview": "Your payment is being verified. Do not pay again. If verification reports an error, contact support with the code below.",
"processing": "Processing",
"yourPublicAddressAndSharedLinksWillReturn40": "Your public address and shared links will return 404. Your photographs, albums and storage will remain in your workspace. You can publish again later.",
@@ -712,6 +725,19 @@
},
"waiting": "Waiting for confirmation",
"checkingStatus": "Checking subscription…",
+ "upgrade": "Upgrade plan",
+ "downgrade": "Downgrade plan",
+ "changeTitle": "Confirm subscription change",
+ "changeFailed": "The change could not be confirmed. Refresh subscription status before trying again; do not create another subscription.",
+ "upgradeHelp": "The upgrade applies after Dodo confirms the change. Dodo prorates the price difference for the remaining billing period; the renewal date stays the same.",
+ "downgradeHelp": "The downgrade is scheduled for the next billing date. Your current plan remains available until then.",
+ "chargeNow": "Estimated charge now:",
+ "newRecurring": "New recurring price:",
+ "savedMethod": "Confirming authorizes Dodo to charge the payment method saved on this subscription where payment is due. The final charge is calculated when the change is submitted.",
+ "confirmChange": "Confirm change",
+ "changeScheduled": "A plan change is scheduled for the next billing date. Your current entitlements remain in place.",
+ "changePending": "Your plan change is being confirmed. Do not submit another change or purchase another subscription.",
+ "portalFailed": "Could not open the billing portal. Only the original subscriber can access it; retry or contact support.",
"confirmationReview": "Your payment is being verified. Do not pay again. If verification reports an error, contact support with the code below.",
"processing": "Processing payment",
"return_checking": "Confirming your payment and updating your plan…",
diff --git a/apps/cloud/i18n/locales/zh-Hans.json b/apps/cloud/i18n/locales/zh-Hans.json
index cea59f12..06bd7b18 100644
--- a/apps/cloud/i18n/locales/zh-Hans.json
+++ b/apps/cloud/i18n/locales/zh-Hans.json
@@ -414,6 +414,19 @@
"draft": "草稿",
"photograph": "照片",
"photographs": "照片",
+ "upgrade": "升级套餐",
+ "downgrade": "降级套餐",
+ "changeTitle": "确认订阅变更",
+ "changeFailed": "暂时无法确认变更,请先检查订阅状态后重试,不要另建订阅。",
+ "upgradeHelp": "升级在 Dodo 确认变更后生效,按当前周期剩余时间计算补差价,续费日期保持不变。",
+ "downgradeHelp": "降级将在下次续费时生效,此前继续使用当前套餐权益。",
+ "chargeNow": "预计本次扣款:",
+ "newRecurring": "新套餐续费价格:",
+ "savedMethod": "确认后,如需付款,将由 Dodo 向此订阅已保存的支付方式扣款。实际金额以提交变更时的计算结果为准。",
+ "confirmChange": "确认变更",
+ "changeScheduled": "套餐变更已预约,将在下次续费时生效;当前权益保持不变。",
+ "changePending": "正在核对套餐变更,请勿重复提交或另购订阅。",
+ "portalFailed": "暂时无法打开账单门户,仅原付款人可访问。请重试或联系支持。",
"confirmationReview": "这笔付款正在核验,请勿重复支付。如果核验异常,请携带下方错误码联系支持。",
"processing": "处理中",
"yourPublicAddressAndSharedLinksWillReturn40": "公开地址和分享链接将返回 404。照片、相簿和存储会保留在工作区中,你可以稍后重新发布。",
@@ -712,6 +725,19 @@
},
"waiting": "等待确认",
"checkingStatus": "正在核对订阅…",
+ "upgrade": "升级套餐",
+ "downgrade": "降级套餐",
+ "changeTitle": "确认订阅变更",
+ "changeFailed": "暂时无法确认变更,请先检查订阅状态后重试,不要另建订阅。",
+ "upgradeHelp": "升级在 Dodo 确认变更后生效,按当前周期剩余时间计算补差价,续费日期保持不变。",
+ "downgradeHelp": "降级将在下次续费时生效,此前继续使用当前套餐权益。",
+ "chargeNow": "预计本次扣款:",
+ "newRecurring": "新套餐续费价格:",
+ "savedMethod": "确认后,如需付款,将由 Dodo 向此订阅已保存的支付方式扣款。实际金额以提交变更时的计算结果为准。",
+ "confirmChange": "确认变更",
+ "changeScheduled": "套餐变更已预约,将在下次续费时生效;当前权益保持不变。",
+ "changePending": "正在核对套餐变更,请勿重复提交或另购订阅。",
+ "portalFailed": "暂时无法打开账单门户,仅原付款人可访问。请重试或联系支持。",
"confirmationReview": "这笔付款正在核验,请勿重复支付。如果核验异常,请携带下方错误码联系支持。",
"processing": "正在处理支付",
"return_checking": "正在确认付款并更新套餐与额度…",
diff --git a/apps/cloud/server/api/billing/payments.post.ts b/apps/cloud/server/api/billing/payments.post.ts
index aa464ad0..01768608 100644
--- a/apps/cloud/server/api/billing/payments.post.ts
+++ b/apps/cloud/server/api/billing/payments.post.ts
@@ -1,3 +1,8 @@
+import {
+ previewPaymentPlanChange,
+ checkPaymentPlanChange,
+ commitPaymentPlanChange,
+} from '../../../../../packages/platform/src/subscription-changes'
import {
createPaymentCheckout,
createPaymentPortal,
@@ -10,13 +15,34 @@ import {
} from '../../../../shared/platform/runtime'
import { requirePlatformSession } from '../../../../shared/platform/context'
import { siteManagementBody } from '../../utils/site-management'
-import { createError } from 'h3'
+import { createError, setResponseHeader } from 'h3'
export default definePlatformHandler(async (event) => {
+ setResponseHeader(event, 'Cache-Control', 'no-store')
const config = useRuntimeConfig(event).platform
const user = await requirePlatformSession(event, config)
platformPortalOrigin(event, config.portalOrigin, true)
const b = await siteManagementBody(event, 4096),
db = platformDatabase(event)
+ if (b.action === 'check-change')
+ return checkPaymentPlanChange(
+ db,
+ config.storageSecret,
+ user.userId,
+ Number(b.workspaceId),
+ )
+ if (b.action === 'preview-change')
+ return previewPaymentPlanChange(db, config.storageSecret, user.userId, {
+ workspaceId: Number(b.workspaceId),
+ planId: String(b.planId),
+ })
+ if (b.action === 'change-plan')
+ return commitPaymentPlanChange(
+ db,
+ config.storageSecret,
+ user.userId,
+ Number(b.workspaceId),
+ String(b.quoteId),
+ )
if (b.action === 'checkout')
return createPaymentCheckout(
db,
diff --git a/packages/platform/migrations/0032_subscription_changes.sql b/packages/platform/migrations/0032_subscription_changes.sql
new file mode 100644
index 00000000..f9b70f55
--- /dev/null
+++ b/packages/platform/migrations/0032_subscription_changes.sql
@@ -0,0 +1,37 @@
+CREATE TABLE platform_payment_plan_rules (
+ from_plan TEXT NOT NULL REFERENCES platform_plans(id),
+ to_plan TEXT NOT NULL REFERENCES platform_plans(id),
+ direction TEXT NOT NULL CHECK(direction IN('upgrade','downgrade')),
+ enabled INTEGER NOT NULL DEFAULT 1,
+ revision INTEGER NOT NULL DEFAULT 1,
+ PRIMARY KEY(from_plan,to_plan),
+ CHECK(from_plan<>to_plan)
+);
+ALTER TABLE platform_payment_subscriptions ADD COLUMN price INTEGER;
+ALTER TABLE platform_payment_subscriptions ADD COLUMN currency TEXT;
+UPDATE platform_payment_subscriptions SET price=(SELECT c.price FROM platform_payment_checkouts c WHERE c.id=checkout_id),currency=(SELECT c.currency FROM platform_payment_checkouts c WHERE c.id=checkout_id);
+CREATE TABLE platform_payment_plan_changes (
+ id TEXT PRIMARY KEY,
+ workspace_id INTEGER NOT NULL REFERENCES platform_workspaces(id) ON DELETE CASCADE,
+ user_id INTEGER REFERENCES platform_users(id) ON DELETE SET NULL,
+ subscription_id TEXT NOT NULL REFERENCES platform_payment_subscriptions(id) ON DELETE CASCADE,
+ provider_key TEXT NOT NULL REFERENCES platform_payment_providers(id),
+ credential_revision INTEGER NOT NULL,
+ from_product TEXT NOT NULL,
+ from_plan TEXT NOT NULL,
+ to_product TEXT NOT NULL,
+ to_plan TEXT NOT NULL,
+ interval INTEGER NOT NULL CHECK(interval IN(1,3)),
+ price INTEGER NOT NULL,
+ currency TEXT NOT NULL,
+ direction TEXT NOT NULL CHECK(direction IN('upgrade','downgrade')),
+ rule_revision INTEGER NOT NULL,
+ plan_revision INTEGER NOT NULL,
+ subscription_revision INTEGER NOT NULL,
+ quote_json TEXT NOT NULL,
+ state TEXT NOT NULL CHECK(state IN('quoted','submitting','pending','scheduled','uncertain','applied','failed')),
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL
+);
+CREATE UNIQUE INDEX platform_payment_change_pending ON platform_payment_plan_changes(workspace_id) WHERE state IN('submitting','pending','scheduled','uncertain');
+CREATE INDEX platform_payment_change_subscription ON platform_payment_plan_changes(subscription_id,state);
diff --git a/packages/platform/src/dodo-payments.ts b/packages/platform/src/dodo-payments.ts
index 47c800f7..4df8aec1 100644
--- a/packages/platform/src/dodo-payments.ts
+++ b/packages/platform/src/dodo-payments.ts
@@ -495,7 +495,7 @@ export async function receiveDodoEvent(
}
/** Read authoritative payment and subscription state; browser and webhook bodies never grant access. */
-async function reconcileDodoSubscription(
+export async function reconcileDodoSubscription(
db: PlatformD1,
secret: string,
environment: DodoEnvironment,
@@ -524,7 +524,7 @@ async function reconcileDodoSubscription(
subscription.metadata?.chronoframe_profile_id !== key
)
return
- const checkout = await db
+ let checkout = await db
.prepare(
"SELECT * FROM platform_payment_checkouts WHERE id=? AND provider='dodo' AND environment=? AND provider_key=?",
)
@@ -569,6 +569,46 @@ async function reconcileDodoSubscription(
subscription.metadata?.chronoframe_profile_id !== key
)
fail('payment_subscription_mismatch', 422)
+ const localId = dodoId(key, subscriptionId)
+ const known = await db
+ .prepare('SELECT * FROM platform_payment_subscriptions WHERE id=?')
+ .bind(localId)
+ .first<any>()
+ let confirmedChange: any = null
+ if (known) {
+ checkout = {
+ ...checkout,
+ product_id: known.product_id,
+ plan_id: known.plan_id,
+ interval: known.interval,
+ price: known.price ?? checkout.price,
+ currency: known.currency ?? checkout.currency,
+ }
+ if (subscription.product_id !== known.product_id) {
+ confirmedChange = await db
+ .prepare(
+ "SELECT * FROM platform_payment_plan_changes WHERE subscription_id=? AND provider_key=? AND from_product=? AND to_product=? AND state IN('submitting','pending','scheduled','uncertain') ORDER BY created_at DESC LIMIT 1",
+ )
+ .bind(localId, key, known.product_id, subscription.product_id)
+ .first<any>()
+ // prevent_change is explicitly used for every locally authorized request.
+ // Dodo's authoritative product switch confirms the outcome, including zero-charge credits.
+ if (
+ !confirmedChange ||
+ subscription.status !== 'active' ||
+ subscription.customer.customer_id !== known.customer_id
+ )
+ fail('payment_subscription_mismatch', 422)
+ checkout = {
+ ...checkout,
+ product_id: confirmedChange.to_product,
+ plan_id: confirmedChange.to_plan,
+ interval: confirmedChange.interval,
+ price: confirmedChange.price,
+ currency: confirmedChange.currency,
+ }
+ }
+ }
if (
subscription.subscription_id !== subscriptionId ||
subscription.product_id !== checkout.product_id ||
@@ -580,11 +620,6 @@ async function reconcileDodoSubscription(
)
fail('payment_subscription_mismatch', 422)
// An initial grant must also be bound to the payment returned by our stored checkout session.
- const localId = dodoId(key, subscriptionId)
- const known = await db
- .prepare('SELECT * FROM platform_payment_subscriptions WHERE id=?')
- .bind(localId)
- .first<any>()
if (!known && checkout.provider_id) {
const session = await dodoRequest(() =>
client.checkoutSessions.retrieve(rawDodoId(checkout.provider_id)),
@@ -655,6 +690,12 @@ async function reconcileDodoSubscription(
await checkoutState('expired', 'payment_subscription_inactive')
return checkout.id as string
}
+ if (
+ confirmedChange &&
+ payment?.metadata?.chronoframe_change_id === confirmedChange.id &&
+ (payment?.refunds?.length || payment?.disputes?.length)
+ )
+ fail('payment_refunded_or_disputed', 422)
// Adaptive pricing charges the customer in a local currency. Compare the
// provider's settlement amount in the immutable product currency, never a
// browser amount, guessed exchange rate, or a numeric total in another currency.
@@ -667,21 +708,23 @@ async function reconcileDodoSubscription(
: payment.settlement_currency === checkout.currency &&
payment.settlement_amount === checkout.price)
const successful =
- payment?.status === 'succeeded' &&
- !identityError &&
- amountMatches &&
- !payment.refunds?.length &&
- !payment.disputes?.length
+ !!confirmedChange ||
+ (payment?.status === 'succeeded' &&
+ !identityError &&
+ amountMatches &&
+ !payment.refunds?.length &&
+ !payment.disputes?.length)
if (!known && payment?.status === 'succeeded' && !successful) {
if (payment.refunds?.length || payment.disputes?.length)
fail('payment_refunded_or_disputed', 422)
fail('payment_amount_mismatch', 422)
}
- const period = successful
- ? payment.service_periods?.find(
- (p) => p.subscription_id === subscriptionId,
- )
- : null
+ const period =
+ successful && !confirmedChange
+ ? payment?.service_periods?.find(
+ (p) => p.subscription_id === subscriptionId,
+ )
+ : null
if (!successful && !known) fail('payment_confirmation_pending')
// Older Dodo responses can omit service_periods for the initial payment.
// Only recover the first, checkout-bound period: subscription dates alone
@@ -699,16 +742,20 @@ async function reconcileDodoSubscription(
Math.abs(initialStart - initialPaymentTime) <= 300000 &&
initialEnd > now &&
initialEnd - initialStart <= (checkout.interval * 31 + 1) * 86400000
- let start = period
- ? timestamp(period.starts_at)
- : initialPeriod
- ? initialStart
- : known?.period_start
- let end = period
- ? timestamp(period.ends_at)
- : initialPeriod
- ? initialEnd
- : known?.period_end
+ let start = confirmedChange
+ ? timestamp(subscription.previous_billing_date)
+ : period
+ ? timestamp(period.starts_at)
+ : initialPeriod
+ ? initialStart
+ : known?.period_start
+ let end = confirmedChange
+ ? timestamp(subscription.next_billing_date)
+ : period
+ ? timestamp(period.ends_at)
+ : initialPeriod
+ ? initialEnd
+ : known?.period_end
if (
!Number.isFinite(start) ||
!Number.isFinite(end) ||
@@ -737,7 +784,11 @@ async function reconcileDodoSubscription(
const active =
['active', 'scheduled_cancel', 'past_due'].includes(status) &&
end > now &&
- !(payment && (payment.refunds?.length || payment.disputes?.length))
+ !(
+ payment &&
+ !confirmedChange &&
+ (payment.refunds?.length || payment.disputes?.length)
+ )
// A failed/refunded payment may revoke but may never extend a paid-through boundary.
if (!successful && known) end = known.period_end
const prior = await db
@@ -766,7 +817,7 @@ async function reconcileDodoSubscription(
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) SELECT ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'dodo',?,? WHERE ${fence} ON CONFLICT(id) DO UPDATE SET 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 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,
@@ -786,6 +837,8 @@ async function reconcileDodoSubscription(
canAssign ? null : 'payment_grant_superseded',
environment,
key,
+ checkout.price,
+ checkout.currency,
...bindFence,
),
db
@@ -841,6 +894,39 @@ async function reconcileDodoSubscription(
...subscriptionInvalidation(db, checkout.workspace_id, eventId),
)
}
+ if (confirmedChange)
+ writes.push(
+ db
+ .prepare(
+ `UPDATE platform_payment_plan_changes SET state='applied',updated_at=? WHERE id=? AND ${fence}`,
+ )
+ .bind(now, confirmedChange.id, ...bindFence),
+ )
+ if (
+ known &&
+ (['canceled', 'expired', 'failed'].includes(status) ||
+ (payment?.status === 'failed' &&
+ payment.charge_type === 'plan_change' &&
+ identifier(payment.metadata?.chronoframe_change_id)))
+ ) {
+ writes.push(
+ db
+ .prepare(
+ `UPDATE platform_payment_plan_changes SET state='failed',updated_at=? WHERE subscription_id=? AND state IN('submitting','pending','scheduled','uncertain') AND (? IS NULL OR id=?) AND ${fence}`,
+ )
+ .bind(
+ now,
+ localId,
+ ['canceled', 'expired', 'failed'].includes(status)
+ ? null
+ : String(payment?.metadata?.chronoframe_change_id ?? ''),
+ ['canceled', 'expired', 'failed'].includes(status)
+ ? null
+ : String(payment?.metadata?.chronoframe_change_id ?? ''),
+ ...bindFence,
+ ),
+ )
+ }
await db.batch(writes)
return checkout.id as string
} catch (error) {
@@ -1061,6 +1147,12 @@ export async function reconcileDodoPayments(
return
const environment = settings.environment as DodoEnvironment,
key = settings.currentProvider!
+ await db
+ .prepare(
+ "DELETE FROM platform_payment_plan_changes WHERE id IN(SELECT id FROM platform_payment_plan_changes WHERE state='quoted' AND created_at<? LIMIT 100)",
+ )
+ .bind(now - 86400000)
+ .run()
const due = await allRows<any>(
db
.prepare(
diff --git a/packages/platform/src/payments.ts b/packages/platform/src/payments.ts
index ef957796..994eec25 100644
--- a/packages/platform/src/payments.ts
+++ b/packages/platform/src/payments.ts
@@ -193,6 +193,48 @@ export async function paymentStatus(
)
: [],
subscriptions,
+ hasActiveSubscription: !!(await db
+ .prepare(
+ "SELECT 1 FROM platform_payment_subscriptions WHERE workspace_id=? AND provider='dodo' AND provider_key=? AND environment=? AND status NOT IN('canceled','expired','failed') LIMIT 1",
+ )
+ .bind(workspaceId, settings.currentProvider, settings.environment)
+ .first()),
+ canOpenPortal: !!(
+ settings.enabled &&
+ settings.providerAvailable &&
+ settings.configured &&
+ 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>?",
+ )
+ .bind(
+ workspaceId,
+ userId,
+ settings.currentProvider,
+ settings.environment,
+ Date.now(),
+ )
+ .first())
+ ),
+ 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",
+ )
+ .bind(
+ workspaceId,
+ settings.currentProvider,
+ settings.environment,
+ Date.now(),
+ ),
+ ),
+ planChange: await db
+ .prepare(
+ "SELECT id,to_plan AS planId,direction,state FROM platform_payment_plan_changes WHERE workspace_id=? AND provider_key=? AND state IN('submitting','pending','scheduled','uncertain') ORDER BY created_at DESC LIMIT 1",
+ )
+ .bind(workspaceId, settings.currentProvider)
+ .first(),
pending:
settings.enabled &&
settings.providerAvailable &&
@@ -243,13 +285,68 @@ export async function createPaymentCheckout(
)
}
export async function createPaymentPortal(
- _db: PlatformD1,
- _rootKey: string,
- _userId: number,
- _workspaceId: number,
- _transport: PaymentFetch = fetch,
+ db: PlatformD1,
+ rootKey: string,
+ userId: number,
+ workspaceId: number,
+ transport: PaymentFetch = fetch,
) {
- throw new SubscriptionError(410, 'payment_provider_retired')
+ const settings = await paymentSettings(db)
+ if (!settings.providerAvailable)
+ throw new SubscriptionError(410, 'payment_provider_retired')
+ await paymentMember(db, userId, workspaceId, true)
+ if (!settings.enabled || !settings.providerAvailable || !settings.configured)
+ throw new SubscriptionError(503, 'payment_unavailable')
+ // 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",
+ )
+ .bind(
+ workspaceId,
+ userId,
+ settings.currentProvider,
+ settings.environment,
+ Date.now(),
+ )
+ .first<any>()
+ if (!sub) throw new SubscriptionError(403, 'payment_portal_unavailable')
+ const { dodoClient, dodoRequest, rawDodoId } =
+ await import('./dodo-client.ts')
+ const { client } = await dodoClient(
+ db,
+ rootKey,
+ sub.environment,
+ transport as typeof fetch,
+ false,
+ sub.provider_key,
+ )
+ const actual = await dodoRequest(() =>
+ client.subscriptions.retrieve(rawDodoId(sub.id)),
+ )
+ if (actual.customer.customer_id !== sub.customer_id)
+ throw new SubscriptionError(422, 'payment_customer_mismatch')
+ const portal = await dodoRequest(() =>
+ client.customers.customerPortal.create(sub.customer_id, {
+ send_email: false,
+ }),
+ )
+ let url: URL
+ try {
+ url = new URL(portal.link)
+ } catch {
+ throw new SubscriptionError(502, 'payment_redirect_invalid')
+ }
+ if (
+ url.origin !==
+ (sub.environment === 'test'
+ ? 'https://test.customer.dodopayments.com'
+ : 'https://customer.dodopayments.com') ||
+ url.username ||
+ url.password
+ )
+ throw new SubscriptionError(502, 'payment_redirect_invalid')
+ return { url: url.href }
}
/** Retired callbacks cannot enter the durable inbox. */
diff --git a/packages/platform/src/subscription-changes.ts b/packages/platform/src/subscription-changes.ts
new file mode 100644
index 00000000..08521727
--- /dev/null
+++ b/packages/platform/src/subscription-changes.ts
@@ -0,0 +1,448 @@
+import type { PlatformD1 } from './index.ts'
+import { allRows, SubscriptionError } from './subscriptions.ts'
+import { paymentMember, paymentSettings } from './payments.ts'
+import {
+ dodoClient,
+ dodoRequest,
+ rawDodoId,
+ DodoProviderError,
+} from './dodo-client.ts'
+
+const invalid = (code: string, status = 409): never => {
+ throw new SubscriptionError(status, code)
+}
+export async function paymentPlanRules(db: PlatformD1) {
+ return allRows<any>(
+ db.prepare(
+ 'SELECT r.*,a.name AS from_name,b.name AS to_name FROM platform_payment_plan_rules r JOIN platform_plans a ON a.id=r.from_plan JOIN platform_plans b ON b.id=r.to_plan ORDER BY a.sort_order,b.sort_order,a.id,b.id',
+ ),
+ )
+}
+export async function savePaymentPlanRule(
+ db: PlatformD1,
+ actor: number,
+ input: any,
+ now = Date.now(),
+) {
+ if (
+ typeof input.fromPlan !== 'string' ||
+ typeof input.toPlan !== 'string' ||
+ input.fromPlan === input.toPlan ||
+ !['upgrade', 'downgrade'].includes(input.direction) ||
+ typeof input.enabled !== 'boolean' ||
+ !Number.isSafeInteger(input.revision) ||
+ input.revision < 0 ||
+ typeof input.reason !== 'string' ||
+ input.reason.trim().length < 5 ||
+ input.reason.length > 500
+ )
+ invalid('payment_change_rule_invalid', 400)
+ const plans = await allRows<any>(
+ db
+ .prepare(
+ 'SELECT id FROM platform_plans WHERE id IN(?,?) AND active=1 AND listed=1 AND (monthly_price>0 OR quarterly_price>0)',
+ )
+ .bind(input.fromPlan, input.toPlan),
+ )
+ if (input.enabled && plans.length !== 2)
+ invalid('payment_change_rule_invalid', 400)
+ const before = await db
+ .prepare(
+ 'SELECT * FROM platform_payment_plan_rules WHERE from_plan=? AND to_plan=?',
+ )
+ .bind(input.fromPlan, input.toPlan)
+ .first<any>()
+ if ((before?.revision ?? 0) !== input.revision) invalid('revision_conflict')
+ const id = crypto.randomUUID()
+ const guard =
+ input.revision === 0
+ ? 'NOT EXISTS(SELECT 1 FROM platform_payment_plan_rules WHERE from_plan=? AND to_plan=?)'
+ : 'EXISTS(SELECT 1 FROM platform_payment_plan_rules WHERE from_plan=? AND to_plan=? AND revision=?)'
+ const values = [
+ input.fromPlan,
+ input.toPlan,
+ ...(input.revision ? [input.revision] : []),
+ ]
+ const result = await db.batch([
+ db
+ .prepare(
+ `INSERT INTO platform_admin_audit(id,actor_id,action,target,reason,after_json,created_at) SELECT ?,?,'payment.plan-rule',?,?,?,? WHERE ${guard}`,
+ )
+ .bind(
+ id,
+ actor,
+ input.fromPlan + ':' + input.toPlan,
+ input.reason.trim(),
+ JSON.stringify({
+ from: input.fromPlan,
+ to: input.toPlan,
+ direction: input.direction,
+ enabled: input.enabled,
+ }),
+ now,
+ ...values,
+ ),
+ db
+ .prepare(
+ 'INSERT INTO platform_payment_plan_rules(from_plan,to_plan,direction,enabled) SELECT ?,?,?,? WHERE EXISTS(SELECT 1 FROM platform_admin_audit WHERE id=?) ON CONFLICT(from_plan,to_plan) DO UPDATE SET direction=excluded.direction,enabled=excluded.enabled,revision=platform_payment_plan_rules.revision+1',
+ )
+ .bind(
+ input.fromPlan,
+ input.toPlan,
+ input.direction,
+ input.enabled ? 1 : 0,
+ id,
+ ),
+ ])
+ if (!result[0]?.meta?.changes) invalid('revision_conflict')
+ return { saved: true }
+}
+const mode = (direction: string) =>
+ direction === 'upgrade'
+ ? {
+ proration_billing_mode: 'prorated_immediately_keep_cycle' as const,
+ effective_at: 'immediately' as const,
+ }
+ : {
+ proration_billing_mode: 'full_immediately' as const,
+ effective_at: 'next_billing_date' as const,
+ }
+
+async function validateTarget(
+ client: Awaited<ReturnType<typeof dodoClient>>['client'],
+ target: any,
+) {
+ const product = await dodoRequest(() =>
+ client.products.retrieve(target.product_id),
+ )
+ const price = product.price
+ if (
+ product.product_id !== target.product_id ||
+ !product.is_recurring ||
+ price.type !== 'recurring_price' ||
+ price.price !== target.price ||
+ price.currency !== target.currency ||
+ price.payment_frequency_count !== target.interval ||
+ price.payment_frequency_interval !== 'Month' ||
+ !price.tax_inclusive ||
+ (price.discount_bps ?? (price.discount ?? 0) * 100) !==
+ target.discount_bps ||
+ price.purchasing_power_parity ||
+ (price.trial_period_days ?? 0) !== 0 ||
+ product.addons?.length
+ )
+ invalid('payment_product_mismatch', 422)
+}
+
+async function context(
+ db: PlatformD1,
+ secret: string,
+ user: number,
+ workspace: number,
+ transport: typeof fetch,
+) {
+ await paymentMember(db, user, workspace, true)
+ const settings = await paymentSettings(db)
+ if (
+ !settings.enabled ||
+ !settings.providerAvailable ||
+ !settings.configured ||
+ settings.purchaseMethod !== 'payment'
+ )
+ invalid('payment_unavailable', 503)
+ const sub = await db
+ .prepare(
+ "SELECT s.* FROM platform_payment_subscriptions s JOIN platform_workspace_plans w ON w.payment_subscription_id=s.id AND w.workspace_id=s.workspace_id WHERE s.workspace_id=? AND s.provider='dodo' AND s.provider_key=? AND s.environment=? AND s.status='active' AND s.period_end>? AND w.source='payment'",
+ )
+ .bind(workspace, settings.currentProvider, settings.environment, Date.now())
+ .first<any>()
+ if (!sub) invalid('payment_active_subscription_required')
+ const provider = await dodoClient(
+ db,
+ secret,
+ settings.environment as 'test' | 'live',
+ transport,
+ true,
+ settings.currentProvider!,
+ )
+ return { sub, ...provider }
+}
+export async function previewPaymentPlanChange(
+ db: PlatformD1,
+ secret: string,
+ user: number,
+ input: { workspaceId: number; planId: string },
+ transport: typeof fetch = fetch,
+ now = Date.now(),
+) {
+ const { sub, client, key, revision } = await context(
+ db,
+ secret,
+ user,
+ input.workspaceId,
+ transport,
+ )
+ const budget = await db
+ .prepare(
+ 'INSERT INTO platform_payment_requests(user_id,window_start,attempts) VALUES(?,?,1) ON CONFLICT(user_id,window_start) DO UPDATE SET attempts=attempts+1 RETURNING attempts',
+ )
+ .bind(user, Math.floor(now / 60000) * 60000)
+ .first<any>()
+ if (budget.attempts > 10) invalid('payment_rate_limited', 429)
+ if (
+ await db
+ .prepare(
+ "SELECT id FROM platform_payment_plan_changes WHERE workspace_id=? AND state IN('submitting','pending','scheduled','uncertain')",
+ )
+ .bind(input.workspaceId)
+ .first()
+ )
+ invalid('payment_change_pending')
+ const rule = await db
+ .prepare(
+ 'SELECT * FROM platform_payment_plan_rules WHERE from_plan=? AND to_plan=? AND enabled=1',
+ )
+ .bind(sub.plan_id, input.planId)
+ .first<any>()
+ if (!rule) invalid('payment_change_not_allowed', 403)
+ const target = await db
+ .prepare(
+ 'SELECT d.*,p.revision FROM platform_dodo_products d JOIN platform_plans p ON p.id=d.plan_id WHERE d.provider_key=? AND d.plan_id=? AND d.interval=? AND d.plan_revision=p.revision AND d.credential_revision=? AND p.active=1 AND p.listed=1 AND d.effective_price>0 AND d.currency=?',
+ )
+ .bind(key, input.planId, sub.interval, revision, sub.currency)
+ .first<any>()
+ if (!target) invalid('payment_plan_unavailable')
+ await validateTarget(client, target)
+ const actual = await dodoRequest(() =>
+ client.subscriptions.retrieve(rawDodoId(sub.id)),
+ )
+ if (
+ actual.product_id !== sub.product_id ||
+ actual.status !== 'active' ||
+ actual.cancel_at_next_billing_date ||
+ actual.scheduled_change ||
+ actual.customer.customer_id !== sub.customer_id
+ )
+ invalid('payment_subscription_changed')
+ const params = {
+ product_id: target.product_id,
+ quantity: 1,
+ ...mode(rule.direction),
+ on_payment_failure: 'prevent_change' as const,
+ discount_codes: [],
+ }
+ const quote = await dodoRequest(() =>
+ client.subscriptions.previewChangePlan(rawDodoId(sub.id), params),
+ )
+ if (
+ quote.new_plan.product_id !== target.product_id ||
+ quote.new_plan.quantity !== 1 ||
+ !Number.isSafeInteger(quote.immediate_charge.summary.total_amount)
+ )
+ invalid('payment_quote_invalid', 502)
+ const id = crypto.randomUUID()
+ await db
+ .prepare(
+ "INSERT INTO platform_payment_plan_changes(id,workspace_id,user_id,subscription_id,provider_key,credential_revision,from_product,from_plan,to_product,to_plan,interval,price,currency,direction,rule_revision,plan_revision,subscription_revision,quote_json,state,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'quoted',?,?)",
+ )
+ .bind(
+ id,
+ input.workspaceId,
+ user,
+ sub.id,
+ key,
+ revision,
+ sub.product_id,
+ sub.plan_id,
+ target.product_id,
+ target.plan_id,
+ target.interval,
+ target.effective_price,
+ target.currency,
+ rule.direction,
+ rule.revision,
+ target.revision,
+ sub.revision,
+ JSON.stringify(quote.immediate_charge),
+ now,
+ now,
+ )
+ .run()
+ return {
+ id,
+ direction: rule.direction,
+ planId: target.plan_id,
+ interval: target.interval,
+ renewalAmount: target.effective_price,
+ currency: target.currency,
+ charge: quote.immediate_charge.summary,
+ effectiveAt: quote.immediate_charge.effective_at,
+ expiresAt: now + 600000,
+ }
+}
+export async function commitPaymentPlanChange(
+ db: PlatformD1,
+ secret: string,
+ user: number,
+ workspace: number,
+ id: string,
+ transport: typeof fetch = fetch,
+ now = Date.now(),
+) {
+ const { sub, client, key, revision } = await context(
+ db,
+ secret,
+ user,
+ workspace,
+ transport,
+ )
+ const row = await db
+ .prepare(
+ 'SELECT * FROM platform_payment_plan_changes WHERE id=? AND workspace_id=? AND user_id=? AND subscription_id=? AND provider_key=?',
+ )
+ .bind(id, workspace, user, sub.id, key)
+ .first<any>()
+ if (!row) invalid('payment_change_unavailable', 404)
+ if (row.state === 'failed') invalid('payment_change_failed')
+ if (row.state !== 'quoted') return { state: row.state }
+ if (
+ row.created_at < now - 600000 ||
+ row.credential_revision !== revision ||
+ row.subscription_revision !== sub.revision ||
+ row.from_product !== sub.product_id
+ )
+ invalid('payment_quote_expired')
+ const actual = await dodoRequest(() =>
+ client.subscriptions.retrieve(rawDodoId(sub.id)),
+ )
+ if (
+ actual.product_id !== sub.product_id ||
+ actual.status !== 'active' ||
+ actual.cancel_at_next_billing_date ||
+ actual.scheduled_change ||
+ actual.customer.customer_id !== sub.customer_id
+ )
+ invalid('payment_subscription_changed')
+ const target = await db
+ .prepare(
+ 'SELECT * FROM platform_dodo_products WHERE provider_key=? AND product_id=? AND plan_revision=? AND credential_revision=?',
+ )
+ .bind(key, row.to_product, row.plan_revision, revision)
+ .first<any>()
+ if (!target) invalid('payment_quote_expired')
+ await validateTarget(client, target)
+ const changed = await db
+ .prepare(
+ "UPDATE platform_payment_plan_changes SET state='submitting',updated_at=? WHERE id=? AND state='quoted' AND EXISTS(SELECT 1 FROM platform_payment_plan_rules WHERE from_plan=? AND to_plan=? AND enabled=1 AND revision=?) AND EXISTS(SELECT 1 FROM platform_dodo_products d JOIN platform_plans p ON p.id=d.plan_id WHERE d.provider_key=? AND d.plan_id=? AND d.interval=? AND d.product_id=? AND d.plan_revision=p.revision AND p.revision=? AND d.credential_revision=? AND p.active=1 AND p.listed=1) AND EXISTS(SELECT 1 FROM platform_payment_settings s JOIN platform_payment_providers p ON p.id=s.current_provider WHERE s.enabled=1 AND s.purchase_method='payment' AND p.id=? AND p.revision=?) AND EXISTS(SELECT 1 FROM platform_payment_subscriptions s JOIN platform_workspace_plans w ON w.payment_subscription_id=s.id AND w.source='payment' WHERE s.id=? AND s.revision=? AND s.product_id=?)",
+ )
+ .bind(
+ now,
+ id,
+ row.from_plan,
+ row.to_plan,
+ row.rule_revision,
+ key,
+ row.to_plan,
+ row.interval,
+ row.to_product,
+ row.plan_revision,
+ revision,
+ key,
+ revision,
+ sub.id,
+ sub.revision,
+ sub.product_id,
+ )
+ .run()
+ .catch(() => invalid('payment_change_pending'))
+ if (!changed.meta.changes) invalid('payment_quote_expired')
+ try {
+ await dodoRequest(() =>
+ client.subscriptions.changePlan(
+ rawDodoId(sub.id),
+ {
+ product_id: row.to_product,
+ quantity: 1,
+ ...mode(row.direction),
+ on_payment_failure: 'prevent_change',
+ discount_codes: [],
+ metadata: { ...actual.metadata, chronoframe_change_id: id },
+ },
+ { headers: { 'Idempotency-Key': `cf-change-${id}` } },
+ ),
+ )
+ const state = row.direction === 'downgrade' ? 'scheduled' : 'pending'
+ await db
+ .prepare(
+ "UPDATE platform_payment_plan_changes SET state=?,updated_at=? WHERE id=? AND state='submitting'",
+ )
+ .bind(state, now, id)
+ .run()
+ await db
+ .prepare(
+ 'UPDATE platform_payment_subscriptions SET next_check_at=0 WHERE id=?',
+ )
+ .bind(sub.id)
+ .run()
+ await checkPaymentPlanChange(
+ db,
+ secret,
+ user,
+ workspace,
+ transport,
+ now,
+ ).catch(() => undefined)
+ const latest = await db
+ .prepare('SELECT state FROM platform_payment_plan_changes WHERE id=?')
+ .bind(id)
+ .first<any>()
+ return { state: latest.state }
+ } catch (error) {
+ // An ambiguous response may already have charged the saved payment method. Never resend it.
+ await db
+ .prepare(
+ "UPDATE platform_payment_plan_changes SET state=?,updated_at=? WHERE id=? AND state='submitting'",
+ )
+ .bind(
+ error instanceof DodoProviderError &&
+ [400, 401, 403, 404, 422].includes(error.providerStatus ?? 0)
+ ? 'failed'
+ : 'uncertain',
+ now,
+ id,
+ )
+ .run()
+ throw error
+ }
+}
+
+export async function checkPaymentPlanChange(
+ db: PlatformD1,
+ secret: string,
+ user: number,
+ workspace: number,
+ transport: typeof fetch = fetch,
+ now = Date.now(),
+) {
+ await paymentMember(db, user, workspace, true)
+ const settings = await paymentSettings(db)
+ const row = await db
+ .prepare(
+ "SELECT s.* FROM platform_payment_subscriptions s JOIN platform_payment_plan_changes c ON c.subscription_id=s.id WHERE c.workspace_id=? AND c.provider_key=? AND c.state IN('submitting','pending','scheduled','uncertain') ORDER BY c.created_at DESC LIMIT 1",
+ )
+ .bind(workspace, settings.currentProvider)
+ .first<any>()
+ if (!row) return { state: 'idle' }
+ const { reconcileDodoSubscription } = await import('./dodo-payments.ts')
+ await reconcileDodoSubscription(
+ db,
+ secret,
+ row.environment,
+ rawDodoId(row.id),
+ undefined,
+ transport,
+ now,
+ row.provider_key,
+ )
+ return { checked: true }
+}
diff --git a/tests/dodo-payments.test.ts b/tests/dodo-payments.test.ts
index c2cf0b4e..bfc6fc33 100644
--- a/tests/dodo-payments.test.ts
+++ b/tests/dodo-payments.test.ts
@@ -1,3 +1,9 @@
+import {
+ savePaymentPlanRule,
+ previewPaymentPlanChange,
+ commitPaymentPlanChange,
+ checkPaymentPlanChange,
+} from '../packages/platform/src/subscription-changes.ts'
import test from 'node:test'
import { discountedPrice } from '../packages/contracts/src/pricing.ts'
import {
@@ -16,6 +22,7 @@ import {
paymentSettings,
paymentStatus,
createPaymentCheckout,
+ createPaymentPortal,
closeAccountPayments,
} from '../packages/platform/src/payments.ts'
import {
@@ -1566,3 +1573,418 @@ test('failed payments without a subscription close the unpaid checkout', async (
await f.mf.dispose()
}
})
+
+async function changeFixture() {
+ const f = await fixture()
+ await f.db
+ .prepare(
+ "INSERT INTO platform_plans(id,name,policy_json,currency,monthly_price,quarterly_price,sort_order) SELECT 'studio','Studio',policy_json,'USD',2400,6000,3 FROM platform_plans WHERE id='free'",
+ )
+ .run()
+ await syncDodoProducts(f.db, root, f.transport, f.now, 20)
+ const checkout = await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ input(),
+ 'https://portal.example',
+ f.transport,
+ )
+ const paid = await f.paid(checkout)
+ await refreshDodoCheckout(f.db, root, 1, 1, checkout.id, f.transport)
+ const mutations: any[] = []
+ let outcome = 'apply'
+ let scheduled: any = null
+ let portalURL = 'https://test.customer.dodopayments.com/session/fixture'
+ const apply = (body: any, now = f.now) => {
+ paid.sub.product_id = body.product_id
+ paid.sub.previous_billing_date = new Date(now - 1000).toISOString()
+ paid.sub.next_billing_date = new Date(now + 28 * 86400000).toISOString()
+ ;(paid.sub as any).scheduled_change = null
+ }
+ const transport: typeof fetch = async (input, init) => {
+ const url = new URL(
+ typeof input === 'string'
+ ? input
+ : input instanceof URL
+ ? input.href
+ : input.url,
+ )
+ const body = init?.body ? JSON.parse(String(init.body)) : null
+ if (url.pathname.endsWith('/change-plan/preview')) {
+ return Response.json({
+ new_plan: { ...paid.sub, product_id: body.product_id },
+ immediate_charge: {
+ effective_at:
+ body.effective_at === 'next_billing_date'
+ ? paid.sub.next_billing_date
+ : new Date(f.now).toISOString(),
+ line_items: [],
+ summary: {
+ currency: 'USD',
+ total_amount: body.effective_at === 'next_billing_date' ? 0 : 600,
+ settlement_currency: 'USD',
+ settlement_amount: 600,
+ customer_credits: 0,
+ customer_credits_currency: 'USD',
+ },
+ },
+ })
+ }
+ if (url.pathname.endsWith('/change-plan')) {
+ mutations.push(body)
+ assert.equal(body.on_payment_failure, 'prevent_change')
+ assert.deepEqual(body.discount_codes, [])
+ if (outcome === 'timeout') throw Error('network after provider accepted')
+ if (outcome === 'reject')
+ return Response.json({ code: 'invalid' }, { status: 422 })
+ if (body.effective_at === 'next_billing_date') {
+ scheduled = body
+ ;(paid.sub as any).scheduled_change = { product_id: body.product_id }
+ } else if (outcome === 'apply') apply(body)
+ return Response.json({})
+ }
+ if (url.pathname.endsWith('/customer-portal/session'))
+ return Response.json({ link: portalURL })
+ return f.transport(input, init)
+ }
+ const rule = async (from: string, to: string, direction = 'upgrade') =>
+ savePaymentPlanRule(f.db, 1, {
+ fromPlan: from,
+ toPlan: to,
+ direction,
+ enabled: true,
+ revision: 0,
+ reason: 'Configure allowed subscription transitions',
+ })
+ const assignment = () =>
+ f.db
+ .prepare('SELECT * FROM platform_workspace_plans WHERE workspace_id=1')
+ .first<any>()
+ return {
+ ...f,
+ ...paid,
+ checkout,
+ transport,
+ mutations,
+ rule,
+ assignment,
+ setOutcome: (value: string) => {
+ outcome = value
+ },
+ setPortal: (value: string) => {
+ portalURL = value
+ },
+ applyScheduled: (now: number) => apply(scheduled, now),
+ }
+}
+
+test('directed subscription rules validate paid plans and audit changes with revision checks', async () => {
+ const f = await changeFixture()
+ try {
+ await assert.rejects(f.rule('free', 'studio'), {
+ code: 'payment_change_rule_invalid',
+ })
+ await f.rule('pro', 'studio')
+ await assert.rejects(f.rule('pro', 'studio'), { code: 'revision_conflict' })
+ await assert.rejects(
+ previewPaymentPlanChange(
+ f.db,
+ root,
+ 1,
+ { workspaceId: 1, planId: 'free' },
+ f.transport,
+ ),
+ { code: 'payment_change_not_allowed' },
+ )
+ await assert.rejects(
+ previewPaymentPlanChange(
+ f.db,
+ root,
+ 2,
+ { workspaceId: 1, planId: 'studio' },
+ f.transport,
+ ),
+ { code: 'workspace_admin_required' },
+ )
+ const audit = await f.db
+ .prepare(
+ "SELECT after_json FROM platform_admin_audit WHERE action='payment.plan-rule'",
+ )
+ .first<any>()
+ assert.equal(JSON.parse(audit.after_json).to, 'studio')
+ await savePaymentPlanRule(f.db, 1, {
+ fromPlan: 'pro',
+ toPlan: 'studio',
+ direction: 'upgrade',
+ enabled: false,
+ revision: 1,
+ reason: 'Disable this transition',
+ })
+ await assert.rejects(
+ previewPaymentPlanChange(
+ f.db,
+ root,
+ 1,
+ { workspaceId: 1, planId: 'studio' },
+ f.transport,
+ ),
+ { code: 'payment_change_not_allowed' },
+ )
+ assert.equal(f.mutations.length, 0)
+ } finally {
+ await f.mf.dispose()
+ }
+})
+
+test('previewed upgrades change the existing subscription without resetting the quota anchor or original checkout', async () => {
+ const f = await changeFixture()
+ try {
+ await f.rule('pro', 'studio')
+ const before = await f.assignment()
+ const quote = await previewPaymentPlanChange(
+ f.db,
+ root,
+ 1,
+ { workspaceId: 1, planId: 'studio' },
+ f.transport,
+ )
+ assert.equal(quote.charge.total_amount, 600)
+ assert.equal((await f.assignment()).plan_id, 'pro')
+ assert.equal(
+ (await commitPaymentPlanChange(f.db, root, 1, 1, quote.id, f.transport))
+ .state,
+ 'applied',
+ )
+ assert.equal(f.mutations.length, 1)
+ assert.equal(
+ f.mutations[0].proration_billing_mode,
+ 'prorated_immediately_keep_cycle',
+ )
+ assert.equal(f.mutations[0].effective_at, 'immediately')
+ const after = await f.assignment()
+ assert.equal(after.plan_id, 'studio')
+ assert.equal(after.starts_at, before.starts_at)
+ const original = await f.db
+ .prepare('SELECT * FROM platform_payment_checkouts WHERE id=?')
+ .bind(f.checkout.id)
+ .first<any>()
+ assert.notEqual(original.product_id, f.sub.product_id)
+ assert.equal(original.price, 1200)
+ assert.equal(
+ (
+ await f.db
+ .prepare('SELECT COUNT(*) AS n FROM platform_payment_subscriptions')
+ .first<any>()
+ ).n,
+ 1,
+ )
+ assert.equal((await paymentStatus(f.db, 1, 1)).planChange, null)
+ assert.equal((await paymentStatus(f.db, 1, 1)).hasActiveSubscription, true)
+ assert.equal((await paymentStatus(f.db, 1, 1)).canOpenPortal, true)
+ assert.equal(
+ (await createPaymentPortal(f.db, root, 1, 1, f.transport)).url,
+ 'https://test.customer.dodopayments.com/session/fixture',
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+})
+
+test('scheduled downgrades retain the paid tier until the provider switches at renewal', async () => {
+ const f = await changeFixture()
+ try {
+ await f.rule('pro', 'studio')
+ const up = await previewPaymentPlanChange(
+ f.db,
+ root,
+ 1,
+ { workspaceId: 1, planId: 'studio' },
+ f.transport,
+ )
+ await commitPaymentPlanChange(f.db, root, 1, 1, up.id, f.transport)
+ await f.rule('studio', 'pro', 'downgrade')
+ const down = await previewPaymentPlanChange(
+ f.db,
+ root,
+ 1,
+ { workspaceId: 1, planId: 'pro' },
+ f.transport,
+ )
+ assert.equal(down.charge.total_amount, 0)
+ assert.equal(
+ (await commitPaymentPlanChange(f.db, root, 1, 1, down.id, f.transport))
+ .state,
+ 'scheduled',
+ )
+ assert.equal((await f.assignment()).plan_id, 'studio')
+ assert.equal(f.mutations[1].effective_at, 'next_billing_date')
+ assert.equal(f.mutations[1].proration_billing_mode, 'full_immediately')
+ const later = f.now + 28 * 86400000
+ f.applyScheduled(later)
+ await checkPaymentPlanChange(f.db, root, 1, 1, f.transport, later)
+ assert.equal((await f.assignment()).plan_id, 'pro')
+ assert.equal((await paymentStatus(f.db, 1, 1)).planChange, null)
+ } finally {
+ await f.mf.dispose()
+ }
+})
+
+test('failed and ambiguous plan changes never grant benefits or repeat a saved-method charge', async () => {
+ const f = await changeFixture()
+ try {
+ await f.rule('pro', 'studio')
+ let quote = await previewPaymentPlanChange(
+ f.db,
+ root,
+ 1,
+ { workspaceId: 1, planId: 'studio' },
+ f.transport,
+ )
+ f.setOutcome('reject')
+ await assert.rejects(
+ commitPaymentPlanChange(f.db, root, 1, 1, quote.id, f.transport),
+ )
+ assert.equal((await f.assignment()).plan_id, 'pro')
+ assert.equal((await paymentStatus(f.db, 1, 1)).planChange, null)
+ quote = await previewPaymentPlanChange(
+ f.db,
+ root,
+ 1,
+ { workspaceId: 1, planId: 'studio' },
+ f.transport,
+ )
+ f.setOutcome('timeout')
+ await assert.rejects(
+ commitPaymentPlanChange(f.db, root, 1, 1, quote.id, f.transport),
+ )
+ assert.equal(
+ (await commitPaymentPlanChange(f.db, root, 1, 1, quote.id, f.transport))
+ .state,
+ 'uncertain',
+ )
+ assert.equal(f.mutations.length, 2)
+ assert.equal((await f.assignment()).plan_id, 'pro')
+ await assert.rejects(
+ previewPaymentPlanChange(
+ f.db,
+ root,
+ 1,
+ { workspaceId: 1, planId: 'studio' },
+ f.transport,
+ ),
+ { code: 'payment_change_pending' },
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+})
+
+test('revoked rules, stale quotes, disabled payments and unsafe customer portal links fail closed', async () => {
+ const f = await changeFixture()
+ try {
+ await f.rule('pro', 'studio')
+ const quote = await previewPaymentPlanChange(
+ f.db,
+ root,
+ 1,
+ { workspaceId: 1, planId: 'studio' },
+ f.transport,
+ )
+ await savePaymentPlanRule(f.db, 1, {
+ fromPlan: 'pro',
+ toPlan: 'studio',
+ direction: 'upgrade',
+ enabled: false,
+ revision: 1,
+ reason: 'Revoke this transition',
+ })
+ await assert.rejects(
+ commitPaymentPlanChange(f.db, root, 1, 1, quote.id, f.transport),
+ { code: 'payment_quote_expired' },
+ )
+ assert.equal(f.mutations.length, 0)
+ f.setPortal('https://untrusted.example/steal')
+ await assert.rejects(createPaymentPortal(f.db, root, 1, 1, f.transport), {
+ code: 'payment_redirect_invalid',
+ })
+ await f.db
+ .prepare(
+ "UPDATE platform_memberships SET role='admin' WHERE workspace_id=1 AND user_id=2",
+ )
+ .run()
+ await assert.rejects(createPaymentPortal(f.db, root, 2, 1, f.transport), {
+ code: 'payment_portal_unavailable',
+ })
+ await f.db.prepare('UPDATE platform_payment_settings SET enabled=0').run()
+ const calls = f.calls.length
+ await assert.rejects(
+ commitPaymentPlanChange(f.db, root, 1, 1, quote.id, f.transport),
+ { code: 'payment_unavailable' },
+ )
+ await assert.rejects(createPaymentPortal(f.db, root, 1, 1, f.transport), {
+ code: 'payment_unavailable',
+ })
+ assert.equal(f.calls.length, calls)
+ } finally {
+ await f.mf.dispose()
+ }
+})
+
+test('accepted changes await provider application; failed change payments retain the existing paid plan', async () => {
+ const f = await changeFixture()
+ try {
+ await f.rule('pro', 'studio')
+ f.setOutcome('delayed')
+ const quote = await previewPaymentPlanChange(
+ f.db,
+ root,
+ 1,
+ { workspaceId: 1, planId: 'studio' },
+ f.transport,
+ )
+ assert.equal(
+ (await commitPaymentPlanChange(f.db, root, 1, 1, quote.id, f.transport))
+ .state,
+ 'pending',
+ )
+ assert.equal((await f.assignment()).plan_id, 'pro')
+ assert.equal(
+ (await commitPaymentPlanChange(f.db, root, 1, 1, quote.id, f.transport))
+ .state,
+ 'pending',
+ )
+ assert.equal(f.mutations.length, 1)
+ const failed = {
+ ...f.payment,
+ payment_id: 'pay_change_failed',
+ status: 'failed',
+ charge_type: 'plan_change',
+ metadata: { ...f.payment.metadata, chronoframe_change_id: quote.id },
+ }
+ f.payments.set(failed.payment_id, failed)
+ const event = await f.sign('payment.failed', failed, 'evt_change_failed')
+ await receiveDodoEvent(
+ f.db,
+ root,
+ 'test',
+ event.body,
+ event.headers,
+ f.transport,
+ )
+ await processDodoEvents(f.db, root, f.transport)
+ assert.equal((await f.assignment()).plan_id, 'pro')
+ assert.equal((await paymentStatus(f.db, 1, 1)).planChange, null)
+ assert.equal(
+ (
+ await f.db
+ .prepare('SELECT state FROM platform_payment_plan_changes WHERE id=?')
+ .bind(quote.id)
+ .first<any>()
+ ).state,
+ 'failed',
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+})
diff --git a/tests/portal-review-regressions.test.ts b/tests/portal-review-regressions.test.ts
index e5b6fbb8..c005622f 100644
--- a/tests/portal-review-regressions.test.ts
+++ b/tests/portal-review-regressions.test.ts
@@ -699,3 +699,42 @@ test('passive payment refreshes read state without duplicating provider confirma
scope.stop()
}
})
+
+test('explicit subscription-change checks refresh the plan without confusing them with checkout confirmation', async () => {
+ let reads = 0
+ const bodies: any[] = []
+ let refreshes = 0
+ const module = load('apps/cloud/app/composables/useCloudPayments.ts', {
+ toValue,
+ $fetch: async (_path: string, options: any) => {
+ if (options.method === 'POST') {
+ bodies.push(options.body)
+ return { checked: true }
+ }
+ return {
+ canManage: true,
+ planChange: reads++ === 0 ? { id: 'change', state: 'pending' } : null,
+ pending: null,
+ }
+ },
+ onMounted: () => {},
+ onBeforeUnmount: () => {},
+ useIntervalFn: () => {},
+ })
+ const scope = effectScope()
+ try {
+ const payments = scope.run(() =>
+ module.useCloudPayments(1, async () => {
+ refreshes++
+ }),
+ )!
+ await payments.refresh()
+ assert.equal(bodies.length, 1)
+ assert.equal(bodies[0].action, 'check-change')
+ assert.equal(bodies[0].workspaceId, 1)
+ assert.equal(refreshes, 1)
+ assert.equal(payments.data.value.planChange, null)
+ } finally {
+ scope.stop()
+ }
+})