Skip to content

Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.

fix(payments): recover initial Dodo periods and improve checkout return UI

Timothy Yin4dd5da375eab
diff --git a/apps/cloud/app/assets/cloud.css b/apps/cloud/app/assets/cloud.css
index e1bbc826..565c21c0 100644
--- a/apps/cloud/app/assets/cloud.css
+++ b/apps/cloud/app/assets/cloud.css
@@ -2097,8 +2097,11 @@ a.cf-domain-address:hover {
gap: 18px;
}
.cf-pricing-card {
- display: flex;
- flex-direction: column;
+ position: relative;
+ overflow: hidden;
+ display: grid;
+ grid-row: span 8;
+ grid-template-rows: subgrid;
gap: 18px;
background: var(--card);
padding: 26px;
@@ -2110,6 +2113,7 @@ a.cf-domain-address:hover {
box-shadow: 0 0 0 1px var(--primary);
}
.cf-plan-card-heading {
+ padding-right: 36px;
display: flex;
align-items: center;
justify-content: space-between;
@@ -2445,7 +2449,7 @@ a.cf-domain-address:hover {
font-size: 30px;
}
.cf-plan-options .cf-plan-description {
- min-height: 0;
+ min-height: 42px;
}
.cf-plan-options .cf-pricing-card.is-current {
border-color: var(--primary);
@@ -3007,3 +3011,56 @@ a.cf-domain-address:hover {
outline: 2px solid var(--ring);
outline-offset: 3px;
}
+
+.cf-plan-original-price {
+ min-height: 18px;
+ font-size: 12px;
+ line-height: 18px;
+ color: var(--muted-foreground);
+ margin-bottom: -8px;
+}
+.cf-plan-discount-ribbon {
+ position: absolute;
+ top: 15px;
+ right: -33px;
+ width: 128px;
+ padding: 5px 0;
+ transform: rotate(45deg);
+ text-align: center;
+ background: var(--primary);
+ color: var(--primary-foreground);
+ font-size: 12px;
+ font-weight: 650;
+ letter-spacing: 0.02em;
+ pointer-events: none;
+}
+.cf-payment-processing-modal {
+ max-width: 320px;
+}
+.cf-payment-processing {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 22px;
+ padding: 48px 24px;
+ text-align: center;
+}
+.cf-payment-spinner {
+ width: 36px;
+ height: 36px;
+ border: 3px solid var(--border);
+ border-top-color: var(--primary);
+ border-radius: 50%;
+ animation: cf-payment-spin 0.8s linear infinite;
+}
+@keyframes cf-payment-spin {
+ to {
+ transform: rotate(360deg);
+ }
+}
+@media (prefers-reduced-motion: reduce) {
+ .cf-payment-spinner {
+ animation-duration: 2s;
+ }
+}
diff --git a/apps/cloud/app/components/CloudPricing.vue b/apps/cloud/app/components/CloudPricing.vue
index 8616c6f8..64207baa 100644
--- a/apps/cloud/app/components/CloudPricing.vue
+++ b/apps/cloud/app/components/CloudPricing.vue
@@ -225,6 +225,15 @@ async function checkout(plan: any) {
'is-current': portal && plan.id === currentPlan,
}"
>
+ <span
+ v-if="discountBps(plan) > 0 && originalAmount(plan) > 0"
+ class="cf-plan-discount-ribbon"
+ >−{{
+ new Intl.NumberFormat(locale, {
+ maximumFractionDigits: 2,
+ }).format(discountBps(plan) / 100)
+ }}%</span
+ >
<div class="cf-plan-card-heading">
<h2>{{ plan.name }}</h2>
<CfBadge v-if="portal && plan.id === currentPlan">{{
@@ -237,18 +246,10 @@ async function checkout(plan: any) {
<p class="cf-plan-description">
{{ plan.description || $t('cloud.billing.simplePlan') }}
</p>
- <p
- v-if="discountBps(plan) > 0 && originalAmount(plan) > 0"
- class="cf-price-caption cf-plan-discount"
- >
- <del>{{ price(originalAmount(plan), plan.currency, locale) }}</del>
- <CfBadge
- >−{{
- new Intl.NumberFormat(locale, {
- maximumFractionDigits: 2,
- }).format(discountBps(plan) / 100)
- }}%</CfBadge
- >
+ <p class="cf-plan-original-price">
+ <del v-if="discountBps(plan) > 0 && originalAmount(plan) > 0">{{
+ price(originalAmount(plan), plan.currency, locale)
+ }}</del>
</p>
<div class="cf-plan-price">
<strong>{{
diff --git a/apps/cloud/app/composables/useDodoCheckoutReturn.ts b/apps/cloud/app/composables/useDodoCheckoutReturn.ts
index 050ffe71..4d553f4c 100644
--- a/apps/cloud/app/composables/useDodoCheckoutReturn.ts
+++ b/apps/cloud/app/composables/useDodoCheckoutReturn.ts
@@ -27,6 +27,7 @@ export function useDodoCheckoutReturn(
'/api/billing/payments',
{
method: 'POST',
+ timeout: 15000,
body: { action: 'refresh', workspaceId: id, checkoutId: checkout },
},
)
@@ -40,7 +41,7 @@ export function useDodoCheckoutReturn(
} catch (error: any) {
if (!alive || current !== generation) return
if (
- [400, 401, 403, 404, 410, 503].includes(
+ [400, 401, 403, 404, 410, 422, 503].includes(
error?.statusCode ?? error?.status,
)
) {
diff --git a/apps/cloud/app/pages/account/plan.vue b/apps/cloud/app/pages/account/plan.vue
index d4cd22a5..9a7771aa 100644
--- a/apps/cloud/app/pages/account/plan.vue
+++ b/apps/cloud/app/pages/account/plan.vue
@@ -50,8 +50,34 @@ const date = (time: number) => new Date(time).toLocaleString(locale.value)
<p class="cf-page-description">{{ $t('cloud.billing.planHelp') }}</p>
</div>
</div>
+ <UModal
+ :open="returned.state.value === 'checking'"
+ :dismissible="false"
+ :close="false"
+ :title="$t('cloud.payments.processing')"
+ :ui="{
+ content: 'cf-payment-processing-modal',
+ header: 'sr-only',
+ body: 'p-0',
+ }"
+ >
+ <template #body>
+ <div
+ class="cf-payment-processing"
+ role="status"
+ aria-live="polite"
+ aria-busy="true"
+ >
+ <span
+ class="cf-payment-spinner"
+ aria-hidden="true"
+ />
+ <p>{{ $t('cloud.payments.processing') }}</p>
+ </div>
+ </template>
+ </UModal>
<p
- v-if="returned.state.value !== 'idle'"
+ v-if="!['idle', 'checking'].includes(returned.state.value)"
class="cf-notice"
role="status"
>
diff --git a/apps/cloud/i18n/locales/en.json b/apps/cloud/i18n/locales/en.json
index ed3fd862..9c8a33c0 100644
--- a/apps/cloud/i18n/locales/en.json
+++ b/apps/cloud/i18n/locales/en.json
@@ -690,7 +690,7 @@
"payments": {
"billing": "Subscription billing",
"test": "Test mode",
- "testHelp": "Creem sandbox checkout. No real charges.",
+ "testHelp": "Dodo sandbox checkout. No real charges.",
"failed": "The billing action could not be completed. Refresh billing status before retrying.",
"pending": "Waiting for provider confirmation. Do not start another subscription.",
"manage": "Manage billing and subscription",
@@ -711,6 +711,7 @@
},
"waiting": "Waiting for confirmation",
"checkingStatus": "Checking subscription…",
+ "processing": "Processing payment",
"return_checking": "Confirming your payment and updating your plan…",
"return_pending": "Your payment is still being confirmed. You can check again; do not start another checkout.",
"return_completed": "Payment confirmed. Your plan and allowances are up to date.",
diff --git a/apps/cloud/i18n/locales/zh-Hans.json b/apps/cloud/i18n/locales/zh-Hans.json
index 62c6ee69..acebdef8 100644
--- a/apps/cloud/i18n/locales/zh-Hans.json
+++ b/apps/cloud/i18n/locales/zh-Hans.json
@@ -690,7 +690,7 @@
"payments": {
"billing": "订阅账单",
"test": "测试环境",
- "testHelp": "使用 Creem 测试付款,不产生真实扣费。",
+ "testHelp": "使用 Dodo 测试付款,不产生真实扣费。",
"failed": "暂时无法完成支付操作,请刷新账单状态后重试。",
"pending": "正在等待渠道确认付款,请勿重复订阅。",
"manage": "管理账单与订阅",
@@ -711,6 +711,7 @@
},
"waiting": "等待确认",
"checkingStatus": "正在核对订阅…",
+ "processing": "正在处理支付",
"return_checking": "正在确认付款并更新套餐与额度…",
"return_pending": "付款仍在确认中,可以稍后再次检查,请勿重复发起付款。",
"return_completed": "付款已确认,套餐与额度已更新。",
diff --git a/packages/platform/src/dodo-payments.ts b/packages/platform/src/dodo-payments.ts
index e7463154..ba92dfbc 100644
--- a/packages/platform/src/dodo-payments.ts
+++ b/packages/platform/src/dodo-payments.ts
@@ -616,8 +616,33 @@ async function reconcileDodoSubscription(
(p) => p.subscription_id === subscriptionId,
)
: null
- let start = period ? timestamp(period.starts_at) : known?.period_start
- let end = period ? timestamp(period.ends_at) : known?.period_end
+ 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
+ // must never extend an existing grant or turn a usage-only renewal into access.
+ const initialStart = timestamp(subscription.previous_billing_date)
+ const initialEnd = timestamp(subscription.next_billing_date)
+ const initialPaymentTime = timestamp(payment?.created_at)
+ const initialPeriod =
+ successful &&
+ !known &&
+ !period &&
+ !payment?.service_periods?.length &&
+ (!payment?.charge_type || payment.charge_type === 'new') &&
+ subscription.status === 'active' &&
+ 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
if (
!Number.isFinite(start) ||
!Number.isFinite(end) ||
@@ -649,7 +674,6 @@ async function reconcileDodoSubscription(
!(payment && (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
- if (!successful && !known) fail('payment_confirmation_pending')
const prior = await db
.prepare('SELECT * FROM platform_workspace_plans WHERE workspace_id=?')
.bind(checkout.workspace_id)
diff --git a/tests/dodo-checkout-return.test.ts b/tests/dodo-checkout-return.test.ts
new file mode 100644
index 00000000..0650868d
--- /dev/null
+++ b/tests/dodo-checkout-return.test.ts
@@ -0,0 +1,142 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import vm from 'node:vm'
+import ts from 'typescript'
+import { ref, toValue, watch, nextTick, effectScope } from 'vue'
+
+function fixture(
+ fetch: (...args: any[]) => Promise<any>,
+ refresh = async () => {},
+) {
+ const exports: Record<string, any> = {}
+ const timers: (() => void)[] = []
+ const mounted: (() => void)[] = []
+ const unmounted: (() => void)[] = []
+ vm.runInNewContext(
+ ts.transpileModule(
+ readFileSync(
+ 'apps/cloud/app/composables/useDodoCheckoutReturn.ts',
+ 'utf8',
+ ),
+ {
+ compilerOptions: { module: ts.ModuleKind.CommonJS },
+ },
+ ).outputText,
+ {
+ exports,
+ ref,
+ toValue,
+ watch,
+ useRoute: () => ({
+ query: {
+ checkout: 'local-checkout',
+ payment_id: 'untrusted-payment',
+ status: 'active',
+ },
+ }),
+ onMounted: (fn: () => void) => mounted.push(fn),
+ onBeforeUnmount: (fn: () => void) => unmounted.push(fn),
+ $fetch: fetch,
+ setTimeout: (fn: () => void) => {
+ timers.push(fn)
+ return timers.length
+ },
+ clearTimeout: () => {},
+ },
+ )
+ const scope = effectScope()
+ const returned = scope.run(() => {
+ const returned = exports.useDodoCheckoutReturn(1, true, refresh)
+ mounted.forEach((fn) => fn())
+ return returned
+ })!
+ return {
+ returned,
+ timers,
+ dispose: () => {
+ unmounted.forEach((fn) => fn())
+ scope.stop()
+ },
+ }
+}
+const flush = async () => {
+ for (let n = 0; n < 8; n++) await nextTick()
+}
+
+test('checkout return waits for entitlement refresh before closing its processing state and ignores browser payment IDs', async () => {
+ let resolveRefresh!: () => void
+ const refreshed = new Promise<void>((resolve) => {
+ resolveRefresh = resolve
+ })
+ const f = fixture(
+ async (path, options) => {
+ assert.equal(path, '/api/billing/payments')
+ assert.equal(
+ JSON.stringify(options.body),
+ JSON.stringify({
+ action: 'refresh',
+ workspaceId: 1,
+ checkoutId: 'local-checkout',
+ }),
+ )
+ return { state: 'completed' }
+ },
+ () => refreshed,
+ )
+ try {
+ await flush()
+ assert.equal(f.returned.state.value, 'checking')
+ resolveRefresh()
+ await flush()
+ assert.equal(f.returned.state.value, 'completed')
+ assert.equal(f.timers.length, 0)
+ } finally {
+ f.dispose()
+ }
+})
+
+test('422 exits processing without polling forever and allows an explicit retry', async () => {
+ let fail = true
+ const f = fixture(async () => {
+ if (fail)
+ throw { statusCode: 422, data: { code: 'payment_period_invalid' } }
+ return { state: 'completed' }
+ })
+ try {
+ await flush()
+ assert.equal(f.returned.state.value, 'failed')
+ assert.equal(f.timers.length, 0)
+ fail = false
+ await f.returned.retry()
+ assert.equal(f.returned.state.value, 'completed')
+ } finally {
+ f.dispose()
+ }
+})
+
+test('delayed confirmation has bounded polling and ignores late results after leaving the page', async () => {
+ const f = fixture(async () => ({ state: 'open' }))
+ try {
+ await flush()
+ for (let n = 0; n < 7; n++) {
+ f.timers.shift()!()
+ await flush()
+ }
+ assert.equal(f.returned.state.value, 'pending')
+ assert.equal(f.timers.length, 0)
+ } finally {
+ f.dispose()
+ }
+ let resolve!: (value: any) => void
+ const late = fixture(
+ () =>
+ new Promise((r) => {
+ resolve = r
+ }),
+ )
+ late.dispose()
+ resolve({ state: 'completed' })
+ await flush()
+ assert.equal(late.returned.state.value, 'checking')
+})
diff --git a/tests/dodo-payments.test.ts b/tests/dodo-payments.test.ts
index 1c4d5d63..f8779c34 100644
--- a/tests/dodo-payments.test.ts
+++ b/tests/dodo-payments.test.ts
@@ -1275,3 +1275,69 @@ test('manual synchronization retries immediately and reports only safe HTTP and
await f.mf.dispose()
}
})
+
+for (const months of [1, 3]) {
+ test(`initial ${months}-month checkout recovers missing service periods without accepting unrelated billing dates`, async () => {
+ const f = await fixture()
+ try {
+ await syncDodoProducts(f.db, root, f.transport)
+ const checkout = await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ { ...input(), interval: months },
+ 'https://portal.example',
+ f.transport,
+ )
+ const { sub, payment } = await f.paid(checkout, months)
+ const legacy = payment as any
+ if (months === 1) delete legacy.service_periods
+ else legacy.service_periods = []
+ legacy.charge_type = 'renewal'
+ const refresh = () =>
+ refreshDodoCheckout(f.db, root, 1, 1, checkout.id, f.transport)
+ await assert.rejects(refresh(), { code: 'payment_period_invalid' })
+ legacy.charge_type = 'new'
+ const start = sub.previous_billing_date
+ sub.previous_billing_date = new Date(f.now - 86400000).toISOString()
+ await assert.rejects(refresh(), { code: 'payment_period_invalid' })
+ sub.previous_billing_date = start
+ const end = sub.next_billing_date
+ sub.next_billing_date = new Date(
+ f.now + (months * 31 + 2) * 86400000,
+ ).toISOString()
+ await assert.rejects(refresh(), { code: 'payment_period_invalid' })
+ sub.next_billing_date = end
+ // A service period for another subscription must not trigger the fallback.
+ legacy.service_periods = [
+ { subscription_id: 'sub_other', starts_at: start, ends_at: end },
+ ]
+ await assert.rejects(refresh(), { code: 'payment_period_invalid' })
+ delete legacy.service_periods
+ delete legacy.charge_type // Older API responses can omit both new fields.
+ assert.equal((await refresh()).state, 'completed')
+ const assignment = () =>
+ f.db
+ .prepare(
+ 'SELECT * FROM platform_workspace_plans WHERE workspace_id=1',
+ )
+ .first<any>()
+ const granted = await assignment()
+ assert.equal(granted.plan_id, 'pro')
+ assert.equal(granted.starts_at, Date.parse(start))
+ assert.equal(granted.expires_at, Date.parse(end))
+ await refresh()
+ assert.equal((await assignment()).starts_at, granted.starts_at)
+ assert.equal((await assignment()).revision, granted.revision)
+ // Subscription dates moving forward cannot extend access without a paid service period.
+ sub.previous_billing_date = end
+ sub.next_billing_date = new Date(
+ f.now + months * 56 * 86400000,
+ ).toISOString()
+ await refresh()
+ assert.equal((await assignment()).expires_at, granted.expires_at)
+ } finally {
+ await f.mf.dispose()
+ }
+ })
+}