Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.
TypeScript albumsexif-extractiongeocodinglive-photomotion-photophoto-galleryphoto-sharingwebgl-viewer
feat(billing): cancel unpaid checkout attempts and create fresh payment links
Timothy Yin2b46890b9be1
diff --git a/apps/cloud/app/components/CloudPricing.vue b/apps/cloud/app/components/CloudPricing.vueindex 84dc8c7b..5efa393d 100644--- a/apps/cloud/app/components/CloudPricing.vue+++ b/apps/cloud/app/components/CloudPricing.vue@@ -126,11 +126,37 @@ watch({ immediate: true },)const pendingFor = (plan: any) => payment.value?.pending?.planId === plan.id+const resuming = ref(false)async function resume() {- if (payment.value?.pending?.url)- await navigateTo(payment.value.pending.url, { external: true })- else await Promise.all([payments?.refresh(), billing?.refresh()])+ const pending = payment.value?.pending,+ workspaceId = billing?.selected.value+ if (+ !pending?.canRefresh ||+ !workspaceId ||+ payments?.busy.value ||+ resuming.value+ )+ return+ resuming.value = true+ try {+ const result = await $fetch<{ state: string }>('/api/billing/payments', {+ method: 'POST',+ timeout: 15000,+ body: { action: 'refresh', workspaceId, checkoutId: pending.id },+ })+ await payments?.refresh({ reconcile: false })+ if (!mounted || workspaceId !== billing?.selected.value) return+ if (result.state === 'awaiting_payment') openCancelCheckout(true)+ else if (result.state === 'open' && payment.value?.pending?.url)+ await navigateTo(payment.value.pending.url, { external: true })+ } catch {+ paymentError.value = t('cloud.payments.failed')+ await payments?.refresh({ reconcile: false })+ } finally {+ resuming.value = false+ }}+const offer = (plan: any) =>payment.value?.enabled &&payment.value?.canManage &&@@ -215,6 +241,93 @@ const checkoutOpen = ref(false),replaceConfirmed = ref(false),cancelOpen = ref(false),cancelling = ref(false)+const cancelCheckoutOpen = ref(false),+ cancelCheckoutRetry = ref(false),+ cancelCheckoutBusy = ref(false),+ cancellationTarget = ref<any>(null)+function openCancelCheckout(retry = false) {+ const pending = payment.value?.pending+ if (!pending?.canCancel || !billing?.selected.value) return+ cancellationTarget.value = { ...pending, workspaceId: billing.selected.value }+ cancelCheckoutRetry.value = retry+ paymentError.value = ''+ cancelCheckoutOpen.value = true+}+async function clearCheckoutReturn(id: string) {+ if (route.query.checkout !== id) return+ const query = { ...route.query }+ for (const key of [+ 'checkout',+ 'subscription_id',+ 'payment_id',+ 'status',+ 'email',+ ])+ delete query[key]+ await navigateTo({ path: route.path, query }, { replace: true })+}+async function cancelCheckout() {+ const target = cancellationTarget.value+ if (!target || cancelCheckoutBusy.value) return+ cancelCheckoutBusy.value = true+ paymentError.value = ''+ try {+ await $fetch('/api/billing/payments', {+ method: 'POST',+ timeout: 15000,+ body: {+ action: 'cancel-checkout',+ workspaceId: target.workspaceId,+ checkoutId: target.id,+ },+ })+ cancelCheckoutOpen.value = false+ await Promise.all([+ payments?.refresh({ reconcile: false }),+ billing?.refresh(),+ ])+ if (mounted && target.workspaceId === billing?.selected.value)+ await clearCheckoutReturn(target.id)+ if (+ mounted &&+ target.workspaceId === billing?.selected.value &&+ cancelCheckoutRetry.value+ ) {+ const plan = data.value?.plans?.find((p: any) => p.id === target.planId)+ if (plan) {+ interval.value = target.interval+ checkout(plan)+ }+ }+ } catch (error: any) {+ const code = error?.data?.data?.code ?? error?.data?.code+ if (mounted && target.workspaceId === billing?.selected.value)+ paymentError.value = t(+ code === 'payment_cancellation_unavailable'+ ? 'cloud.payments.checkoutCannotCancel'+ : 'cloud.payments.checkoutCancelFailed',+ )+ await Promise.all([+ payments?.refresh({ reconcile: false }),+ billing?.refresh(),+ ])+ if (+ mounted &&+ target.workspaceId === billing?.selected.value &&+ payment.value?.pending?.id !== target.id+ )+ await clearCheckoutReturn(target.id)+ } finally {+ cancelCheckoutBusy.value = false+ }+}+watch(+ () => billing?.selected.value,+ () => {+ cancelCheckoutOpen.value = false+ cancellationTarget.value = null+ },+)const entitlement = computed(() => payment.value?.entitlement)const date = (value: number) => new Date(value).toLocaleString(locale.value)function checkout(plan: any) {@@ -364,6 +477,18 @@ async function submitCheckout(plan: any, mode?: string) {>{{ payment.pending.error }}</code></p>+ <CfCard+ v-if="payment?.pending?.canCancel"+ class="cf-notice"+ >+ <p>{{ $t('cloud.payments.awaitingPayment') }}</p>+ <CfButton+ variant="secondary"+ :disabled="cancelCheckoutBusy"+ @click="openCancelCheckout(false)"+ >{{ $t('cloud.payments.cancelCheckout') }}</CfButton+ >+ </CfCard><pv-if="paymentError"class="cf-error-message"@@ -524,6 +649,7 @@ async function submitCheckout(plan: any, mode?: string) {v-else-if="portal && pendingFor(plan)":disabled="!!paying ||+ resuming ||payments?.busy.value ||(!payment.pending.url && !payment.pending.canRefresh)"@@ -531,9 +657,11 @@ async function submitCheckout(plan: any, mode?: string) {>{{$t(- payment.pending.url- ? 'cloud.payments.resume'- : 'cloud.payments.checkAgain',+ payment.pending.canCancel+ ? 'cloud.payments.restartCheckout'+ : payment.pending.url+ ? 'cloud.payments.resume'+ : 'cloud.payments.checkAgain',)}}</CfButton>@@ -805,6 +933,50 @@ async function submitCheckout(plan: any, mode?: string) {></template></UModal>+ <UModal+ v-model:open="cancelCheckoutOpen"+ :dismissible="!cancelCheckoutBusy"+ :close="!cancelCheckoutBusy"+ :title="+ $t(+ cancelCheckoutRetry+ ? 'cloud.payments.restartCheckout'+ : 'cloud.payments.cancelCheckout',+ )+ "+ :description="$t('cloud.payments.cancelCheckoutSummary')"+ >+ <template #body+ ><div class="cf-form">+ <p>{{ $t('cloud.payments.cancelCheckoutHelp') }}</p>+ <p+ v-if="paymentError"+ class="cf-error-message"+ role="alert"+ >+ {{ paymentError }}+ </p>+ </div></template+ >+ <template #footer+ ><CfButton+ variant="secondary"+ :disabled="cancelCheckoutBusy"+ @click="cancelCheckoutOpen = false"+ >{{ $t('cloud.billing.cancel') }}</CfButton+ ><CfButton+ :loading="cancelCheckoutBusy"+ @click="cancelCheckout"+ >{{+ $t(+ cancelCheckoutRetry+ ? 'cloud.payments.confirmRestartCheckout'+ : 'cloud.payments.cancelCheckout',+ )+ }}</CfButton+ ></template+ >+ </UModal><UModalv-model:open="changeOpen":title="$t('cloud.payments.changeTitle')"diff --git a/apps/cloud/app/composables/useDodoCheckoutReturn.ts b/apps/cloud/app/composables/useDodoCheckoutReturn.tsindex b8906aab..82090e41 100644--- a/apps/cloud/app/composables/useDodoCheckoutReturn.ts+++ b/apps/cloud/app/composables/useDodoCheckoutReturn.ts@@ -67,9 +67,13 @@ export function useDodoCheckoutReturn(await refresh()if (!isCurrent()) returnif (- ['completed', 'scheduled', 'expired', 'inactive'].includes(- result.state,- )+ [+ 'completed',+ 'scheduled',+ 'expired',+ 'inactive',+ 'awaiting_payment',+ ].includes(result.state)) {if (deadlineTimer) clearTimeout(deadlineTimer)state.value = result.statediff --git a/apps/cloud/i18n/locales/en.json b/apps/cloud/i18n/locales/en.jsonindex 8abdb345..0ab54374 100644--- a/apps/cloud/i18n/locales/en.json+++ b/apps/cloud/i18n/locales/en.json@@ -762,7 +762,16 @@"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."+ "trialUnavailable": "Deferred billing is unavailable for this checkout. No reservation was created; please contact support.",+ "return_awaiting_payment": "Payment has not been completed. You can cancel this checkout or start again below.",+ "awaitingPayment": "This payment has not started. If the checkout link has expired, cancel it or start again with a new link.",+ "cancelCheckout": "Cancel this payment",+ "restartCheckout": "Start a new checkout",+ "confirmRestartCheckout": "Cancel and start again",+ "cancelCheckoutHelp": "Cancel this unpaid checkout after verifying its current status. Existing entitlements and transaction history are preserved. Payments already processing or completed cannot be canceled here. Starting again creates a new checkout link.",+ "checkoutCannotCancel": "This payment cannot currently be canceled. It may have started processing or completed. Check the updated status before trying again.",+ "checkoutCancelFailed": "Could not confirm cancellation. No new checkout was created. Please retry or contact support.",+ "cancelCheckoutSummary": "Verify and cancel this unpaid checkout."},"dashboard": {"workspaceOverview": "Workspace overview",diff --git a/apps/cloud/i18n/locales/zh-Hans.json b/apps/cloud/i18n/locales/zh-Hans.jsonindex 2f8c5ccf..c9d2ca25 100644--- a/apps/cloud/i18n/locales/zh-Hans.json+++ b/apps/cloud/i18n/locales/zh-Hans.json@@ -762,7 +762,16 @@"replaceExplanation": "立即扣款并切换套餐,剩余试用或激活码权益将被替换,不折抵、不恢复。","replaceConsent": "我同意替换剩余权益,并立即开始付费订阅。","continueCheckout": "前往结账",- "trialUnavailable": "当前结账不支持延期扣款,未创建订阅预约,请联系客服。"+ "trialUnavailable": "当前结账不支持延期扣款,未创建订阅预约,请联系客服。",+ "return_awaiting_payment": "尚未完成付款,可在下方取消本次支付或重新发起。",+ "awaitingPayment": "这次付款尚未开始。如果结账链接已过期,可取消本次支付,或使用新链接重新发起。",+ "cancelCheckout": "取消本次支付",+ "restartCheckout": "重新发起支付",+ "confirmRestartCheckout": "取消并重新发起",+ "cancelCheckoutHelp": "核验当前状态后取消这次尚未付款的结账,保留已有权益及交易历史。已开始处理或已完成的付款无法在此取消。重新发起会创建新的结账链接。",+ "checkoutCannotCancel": "当前无法取消这笔付款,可能已开始处理或已完成。请先查看更新后的状态。",+ "checkoutCancelFailed": "暂未确认取消成功,未创建新的结账。请重试或联系客服。",+ "cancelCheckoutSummary": "核验并取消这次尚未付款的结账。"},"dashboard": {"workspaceOverview": "工作区概览",diff --git a/apps/cloud/server/api/billing/payments.post.ts b/apps/cloud/server/api/billing/payments.post.tsindex 3bb1ae81..d138e2ea 100644--- a/apps/cloud/server/api/billing/payments.post.ts+++ b/apps/cloud/server/api/billing/payments.post.ts@@ -1,4 +1,7 @@-import { cancelDeferredSubscription } from '../../../../../packages/platform/src/dodo-payments'+import {+ cancelDeferredSubscription,+ cancelDodoCheckout,+} from '../../../../../packages/platform/src/dodo-payments'import {previewPaymentPlanChange,checkPaymentPlanChange,@@ -24,6 +27,14 @@ export default definePlatformHandler(async (event) => {platformPortalOrigin(event, config.portalOrigin, true)const b = await siteManagementBody(event, 4096),db = platformDatabase(event)+ if (b.action === 'cancel-checkout')+ return cancelDodoCheckout(+ db,+ config.storageSecret,+ user.userId,+ Number(b.workspaceId),+ String(b.checkoutId),+ )if (b.action === 'cancel-reservation')return cancelDeferredSubscription(db,diff --git a/packages/platform/src/deferred-payments.ts b/packages/platform/src/deferred-payments.tsindex 2598095c..19e90a87 100644--- a/packages/platform/src/deferred-payments.ts+++ b/packages/platform/src/deferred-payments.ts@@ -1,4 +1,7 @@-import { closeFailedInitialCheckout } from './unpaid-checkout.ts'+import {+ closeFailedInitialCheckout,+ markAwaitingInitialCheckout,+} from './unpaid-checkout.ts'import type { PlatformD1 } from './index.ts'import { DAY } from './payment-handover.ts'import { SubscriptionError, subscriptionInvalidation } from './subscriptions.ts'@@ -19,6 +22,7 @@ export async function reconcileDeferredAuthorization(fence: string,fenceValues: (string | number | null)[],localId: string,+ cancelInitial = false,) {if (!checkout.handover_json || known?.activation_state === 'paid')return { handled: false, paymentId }@@ -140,6 +144,20 @@ export async function reconcileDeferredAuthorization(now,fence,fenceValues,+ cancelInitial,+ )+ )+ return { handled: true, paymentId }+ if (+ await markAwaitingInitialCheckout(+ db,+ checkout,+ subscription,+ payment,+ known,+ now,+ fence,+ fenceValues,))return { handled: true, paymentId }diff --git a/packages/platform/src/dodo-payments.ts b/packages/platform/src/dodo-payments.tsindex 779c7658..bfc649a6 100644--- a/packages/platform/src/dodo-payments.ts+++ b/packages/platform/src/dodo-payments.ts@@ -1,4 +1,7 @@-import { closeFailedInitialCheckout } from './unpaid-checkout.ts'+import {+ closeFailedInitialCheckout,+ markAwaitingInitialCheckout,+} from './unpaid-checkout.ts'import { checkoutHandover } from './payment-handover.ts'import { reconcileDeferredAuthorization } from './deferred-payments.ts'import { discountedPrice } from '../../contracts/src/pricing.ts'@@ -542,6 +545,7 @@ export async function reconcileDodoSubscription(transport: typeof fetch,now: number,key: string,+ cancelInitial = false,) {if (!identifier(subscriptionId)) fail('payment_subscription_invalid', 422)const { client, revision } = await dodoClient(@@ -682,6 +686,7 @@ export async function reconcileDodoSubscription(`${activeFence} AND EXISTS(SELECT 1 FROM platform_payment_locks WHERE workspace_id=? AND token=?)`,[key, revision, checkout.workspace_id, token],localId,+ cancelInitial,)if (deferred.handled) return checkout.id as stringpaymentId = deferred.paymentId@@ -758,6 +763,21 @@ export async function reconcileDodoSubscription(now,`${activeFence} AND EXISTS(SELECT 1 FROM platform_payment_locks WHERE workspace_id=? AND token=?)`,[key, revision, checkout.workspace_id, token],+ cancelInitial,+ ))+ )+ return checkout.id as string+ if (+ !identityError &&+ (await markAwaitingInitialCheckout(+ db,+ checkout,+ subscription,+ payment,+ known,+ now,+ `${activeFence} AND EXISTS(SELECT 1 FROM platform_payment_locks WHERE workspace_id=? AND token=?)`,+ [key, revision, checkout.workspace_id, token],)))return checkout.id as string@@ -1191,6 +1211,7 @@ export async function refreshDodoCheckout(checkoutId: string,transport: typeof fetch = fetch,now = Date.now(),+ cancelInitial = false,) {await paymentMember(db, userId, workspaceId, true)const budget = await db@@ -1260,6 +1281,7 @@ export async function refreshDodoCheckout(transport,now,key,+ cancelInitial,)}if (session.payment_id) {@@ -1294,6 +1316,7 @@ export async function refreshDodoCheckout(transport,now,key,+ cancelInitial,)} else if (now - row.created_at > 86400000)await db@@ -1322,7 +1345,10 @@ export async function refreshDodoCheckout(: latest.activation_state === 'authorized' &&latest.state === 'completed'? 'scheduled'- : latest.state,+ : latest.state === 'open' &&+ latest.error === 'payment_awaiting_payment'+ ? 'awaiting_payment'+ : latest.state,}}export async function reconcileDodoPayments(@@ -1532,3 +1558,37 @@ export async function cancelDeferredSubscription()return { state: 'cancelled' }}++/** Explicit cancellation still uses only the stored session and authoritative provider data. */+export async function cancelDodoCheckout(+ db: PlatformD1,+ secret: string,+ userId: number,+ workspaceId: number,+ checkoutId: string,+ transport: typeof fetch = fetch,+ now = Date.now(),+) {+ try {+ const result = await refreshDodoCheckout(+ db,+ secret,+ userId,+ workspaceId,+ checkoutId,+ transport,+ now,+ true,+ )+ if (!['expired', 'inactive'].includes(result.state))+ throw new SubscriptionError(409, 'payment_cancellation_unavailable')+ return result+ } catch (error) {+ if (+ error instanceof SubscriptionError &&+ error.code === 'payment_confirmation_pending'+ )+ throw new SubscriptionError(409, 'payment_cancellation_unavailable')+ throw error+ }+}diff --git a/packages/platform/src/payments.ts b/packages/platform/src/payments.tsindex 69faeaa9..e32205fe 100644--- a/packages/platform/src/payments.ts+++ b/packages/platform/src/payments.ts@@ -249,13 +249,15 @@ export async function paymentStatus(settings.purchaseMethod === 'payment'? await db.prepare(- "SELECT id,state,plan_id AS planId,interval,error,CASE WHEN user_id=? AND ?='admin' THEN 1 ELSE 0 END AS canRefresh,CASE WHEN state='open' AND user_id=? AND ?='admin' THEN checkout_url ELSE NULL END AS url FROM platform_payment_checkouts WHERE workspace_id=? AND provider='dodo' AND environment=? AND provider_key=? AND state IN('creating','open','uncertain') ORDER BY created_at DESC LIMIT 1",+ "SELECT id,state,plan_id AS planId,interval,error,CASE WHEN user_id=? AND ?='admin' THEN 1 ELSE 0 END AS canRefresh,CASE WHEN error='payment_awaiting_payment' AND user_id=? AND ?='admin' THEN 1 ELSE 0 END AS canCancel,CASE WHEN state='open' AND (error IS NULL OR error<>'payment_awaiting_payment') AND user_id=? AND ?='admin' THEN checkout_url ELSE NULL END AS url FROM platform_payment_checkouts WHERE workspace_id=? AND provider='dodo' AND environment=? AND provider_key=? AND state IN('creating','open','uncertain') ORDER BY created_at DESC LIMIT 1",).bind(userId,membership.role,userId,membership.role,+ userId,+ membership.role,workspaceId,settings.environment,settings.currentProvider,diff --git a/packages/platform/src/unpaid-checkout.ts b/packages/platform/src/unpaid-checkout.tsindex 143083b1..53672db7 100644--- a/packages/platform/src/unpaid-checkout.ts+++ b/packages/platform/src/unpaid-checkout.ts@@ -2,6 +2,19 @@ import type { PlatformD1 } from './index.ts'import { dodoRequest } from './dodo-client.ts'import { SubscriptionError } from './subscriptions.ts'+export const awaitingInitialPayment = (+ subscription: any,+ payment: any,+ known: any,+) =>+ !known &&+ subscription.status === 'pending' &&+ ['requires_payment_method', 'requires_confirmation'].includes(+ payment?.status,+ ) &&+ !payment.refunds?.length &&+ !payment.disputes?.length+/** Call only after binding the authoritative payment and subscription to our checkout. */export async function closeFailedInitialCheckout(db: PlatformD1,@@ -13,14 +26,13 @@ export async function closeFailedInitialCheckout(now: number,fence: string,fenceValues: (string | number | null)[],+ cancelRequested = false,) {// Session links last 24 hours. Only pre-charge states may be abandoned on age;// processing, customer authentication, and capture states must keep reconciling.const expiredBeforeCharge =- now - checkout.created_at > 86400000 &&- ['requires_payment_method', 'requires_confirmation'].includes(- payment?.status,- )+ (cancelRequested || now - checkout.created_at > 86400000) &&+ awaitingInitialPayment(subscription, payment, known)if (known ||subscription.status !== 'pending' ||@@ -49,3 +61,26 @@ export async function closeFailedInitialCheckout(throw new SubscriptionError(409, 'payment_entitlement_changed')return true}++/** Record a verified pre-charge state without creating or extending any entitlement. */+export async function markAwaitingInitialCheckout(+ db: PlatformD1,+ checkout: any,+ subscription: any,+ payment: any,+ known: any,+ now: number,+ fence: string,+ values: (string | number | null)[],+) {+ if (!awaitingInitialPayment(subscription, payment, known)) return false+ const result = await db+ .prepare(+ `UPDATE platform_payment_checkouts SET state='open',error='payment_awaiting_payment',updated_at=? WHERE id=? AND state IN('creating','open','uncertain') AND NOT EXISTS(SELECT 1 FROM platform_payment_subscriptions WHERE checkout_id=platform_payment_checkouts.id) AND ${fence}`,+ )+ .bind(now, checkout.id, ...values)+ .run()+ if (!result.meta.changes)+ throw new SubscriptionError(409, 'payment_entitlement_changed')+ return true+}diff --git a/tests/dodo-checkout-return.test.ts b/tests/dodo-checkout-return.test.tsindex 85e9de75..d972bfaa 100644--- a/tests/dodo-checkout-return.test.ts+++ b/tests/dodo-checkout-return.test.ts@@ -357,3 +357,15 @@ for (const stage of ['fetch', 'refresh', 'error'])f.dispose()}})++test('awaiting a payment method closes the processing modal without repeated polling', async () => {+ const f = fixture(async () => ({ state: 'awaiting_payment' }))+ try {+ await flush()+ assert.equal(f.returned.state.value, 'awaiting_payment')+ assert.equal(f.timers.length, 0)+ assert.equal(f.watchdogs.length, 0)+ } finally {+ f.dispose()+ }+})diff --git a/tests/dodo-payments.test.ts b/tests/dodo-payments.test.tsindex 74d2aacb..50a993f4 100644--- a/tests/dodo-payments.test.ts+++ b/tests/dodo-payments.test.ts@@ -3145,3 +3145,271 @@ test('lost checkout update fences reject closure and a later reconciliation canawait f.mf.dispose()}})++for (const state of ['requires_payment_method', 'requires_confirmation'])+ test(`manual cancellation of ${state} ends pending checkout and permits a fresh link before the age limit`, async () => {+ const f = await fixture()+ try {+ await syncDodoProducts(f.db, root, f.transport)+ const checkout = await createPaymentCheckout(+ f.db,+ root,+ 1,+ input(),+ origin,+ f.transport,+ f.now,+ )+ const { sub, payment } = await f.paid(checkout)+ sub.status = 'pending'+ payment.status = state+ assert.equal(+ (+ await refreshDodoCheckout(+ f.db,+ root,+ 1,+ 1,+ checkout.id,+ f.transport,+ f.now + 1000,+ )+ ).state,+ 'awaiting_payment',+ )+ const pending = (await paymentStatus(f.db, 1, 1)).pending+ assert.equal(pending.canCancel, 1)+ assert.equal(pending.url, null)+ const { cancelDodoCheckout } =+ await import('../packages/platform/src/dodo-payments.ts')+ await assert.rejects(+ cancelDodoCheckout(+ f.db,+ root,+ 2,+ 1,+ checkout.id,+ f.transport,+ f.now + 2000,+ ),+ { code: 'workspace_admin_required' },+ )+ assert.equal(+ (+ await cancelDodoCheckout(+ f.db,+ root,+ 1,+ 1,+ checkout.id,+ f.transport,+ f.now + 2000,+ )+ ).state,+ 'expired',+ )+ assert.equal(sub.status, 'cancelled')+ assert.equal((await paymentStatus(f.db, 1, 1)).pending, null)+ assert.equal(+ (+ await f.db+ .prepare(+ 'SELECT source FROM platform_workspace_plans WHERE workspace_id=1',+ )+ .first<any>()+ ).source,+ 'default',+ )+ await cancelDodoCheckout(+ f.db,+ root,+ 1,+ 1,+ checkout.id,+ f.transport,+ f.now + 3000,+ )+ const next = await createPaymentCheckout(+ f.db,+ root,+ 1,+ input('explicit_retry'),+ origin,+ f.transport,+ f.now + 4000,+ )+ assert.notEqual(next.url, checkout.url)+ } finally {+ await f.mf.dispose()+ }+ })+test('manual cancellation never cancels processing or successful payments and requires verified revocation', async () => {+ const f = await fixture()+ try {+ await syncDodoProducts(f.db, root, f.transport)+ const checkout = await createPaymentCheckout(+ f.db,+ root,+ 1,+ input(),+ origin,+ f.transport,+ f.now,+ )+ const { sub, payment } = await f.paid(checkout)+ sub.status = 'pending'+ const { cancelDodoCheckout } =+ await import('../packages/platform/src/dodo-payments.ts')+ for (const state of [+ 'processing',+ 'requires_customer_action',+ 'requires_capture',+ ]) {+ payment.status = state+ const calls = f.calls.length+ await assert.rejects(+ cancelDodoCheckout(+ f.db,+ root,+ 1,+ 1,+ checkout.id,+ f.transport,+ f.now + 1000,+ ),+ { code: 'payment_cancellation_unavailable' },+ )+ assert.ok(!f.calls.slice(calls).some((c) => c.method === 'PATCH'))+ }+ payment.status = 'requires_payment_method'+ const denied: typeof fetch = async (url, init) =>+ init?.method === 'PATCH' ? Response.json(sub) : f.transport(url, init)+ await assert.rejects(+ cancelDodoCheckout(f.db, root, 1, 1, checkout.id, denied, f.now + 1000),+ { code: 'payment_cancellation_unavailable' },+ )+ assert.ok((await paymentStatus(f.db, 1, 1)).pending)+ sub.status = 'active'+ payment.status = 'succeeded'+ const calls = f.calls.length+ await assert.rejects(+ cancelDodoCheckout(+ f.db,+ root,+ 1,+ 1,+ checkout.id,+ f.transport,+ f.now + 2000,+ ),+ { code: 'payment_cancellation_unavailable' },+ )+ assert.ok(!f.calls.slice(calls).some((c) => c.method === 'PATCH'))+ assert.equal(+ (+ await f.db+ .prepare(+ 'SELECT source FROM platform_workspace_plans WHERE workspace_id=1',+ )+ .first<any>()+ ).source,+ 'payment',+ )+ } finally {+ await f.mf.dispose()+ }+})+test('manual cancellation cannot locally discard a still-valid session with no bound payment', async () => {+ const f = await fixture()+ try {+ await syncDodoProducts(f.db, root, f.transport)+ const checkout = await createPaymentCheckout(+ f.db,+ root,+ 1,+ input(),+ origin,+ f.transport,+ f.now,+ )+ const { cancelDodoCheckout } =+ await import('../packages/platform/src/dodo-payments.ts')+ await assert.rejects(+ cancelDodoCheckout(+ f.db,+ root,+ 1,+ 1,+ checkout.id,+ f.transport,+ f.now + 1000,+ ),+ { code: 'payment_cancellation_unavailable' },+ )+ assert.ok((await paymentStatus(f.db, 1, 1)).pending)+ } finally {+ await f.mf.dispose()+ }+})+test('unpaid deferred authorization can be canceled without extending the original entitlement', async () => {+ const f = await handoverFixture()+ try {+ const checkout = await createPaymentCheckout(+ f.db,+ root,+ 1,+ { ...input(), startMode: 'after_entitlement' },+ origin,+ f.transport,+ f.now,+ )+ const { sub, payment, session } = await f.paid(checkout)+ sub.status = 'pending'+ sub.trial_period_days = session.trial_period_days+ payment.status = 'requires_payment_method'+ payment.total_amount = 0+ assert.equal(+ (+ await refreshDodoCheckout(+ f.db,+ root,+ 1,+ 1,+ checkout.id,+ f.transport,+ f.now + 1000,+ )+ ).state,+ 'awaiting_payment',+ )+ const { cancelDodoCheckout } =+ await import('../packages/platform/src/dodo-payments.ts')+ assert.equal(+ (+ await cancelDodoCheckout(+ f.db,+ root,+ 1,+ 1,+ checkout.id,+ f.transport,+ f.now + 2000,+ )+ ).state,+ 'expired',+ )+ assert.equal(+ (+ await f.db+ .prepare(+ 'SELECT expires_at FROM platform_workspace_plans WHERE workspace_id=1',+ )+ .first<any>()+ ).expires_at,+ f.originalEnd,+ )+ assert.equal((await paymentStatus(f.db, 1, 1)).reservation, null)+ } finally {+ await f.mf.dispose()+ }+})