diff --git a/web/app/pages/billing/index.component.test.ts b/web/app/pages/billing/index.component.test.ts new file mode 100644 index 000000000..10e3290b8 --- /dev/null +++ b/web/app/pages/billing/index.component.test.ts @@ -0,0 +1,341 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { test } from 'node:test' +import { setImmediate } from 'node:timers/promises' +import { runInNewContext } from 'node:vm' +import ts from 'typescript' +import * as vue from 'vue' +import type { Component } from 'vue' +import { compileScript, parse } from 'vue/compiler-sfc' +import * as icons from '@mdi/js' +import * as countries from '../../utils/countries' +import * as apiError from '../../utils/api-error' +import * as blackFriday from '../../utils/black-friday' + +const { descriptor } = parse( + readFileSync(new URL('./index.vue', import.meta.url), 'utf8'), +) +const compiled = compileScript(descriptor, { + id: 'billing-component-test', + inlineTemplate: true, +}) +const { outputText } = ts.transpileModule(compiled.content, { + compilerOptions: { + target: ts.ScriptTarget.ESNext, + module: ts.ModuleKind.CommonJS, + }, +}) + +interface RenderNode { + type: string + text: string + props: Record + children: RenderNode[] + parent: RenderNode | null +} + +function node(type: string, text = ''): RenderNode { + return { type, text, props: {}, children: [], parent: null } +} + +function remove(child: RenderNode) { + if (!child.parent) return + child.parent.children.splice(child.parent.children.indexOf(child), 1) + child.parent = null +} + +const renderer = vue.createRenderer({ + createElement: (type) => node(type), + createText: (text) => node('#text', text), + createComment: (text) => node('#comment', text), + setText: (element, text) => { + element.text = text + }, + setElementText: (element, text) => { + element.text = text + element.children = [] + }, + patchProp: (element, key, _previous, value) => { + element.props[key] = value + }, + insert: (child, parent, anchor) => { + remove(child) + const index = anchor ? parent.children.indexOf(anchor) : -1 + parent.children.splice(index < 0 ? parent.children.length : index, 0, child) + child.parent = parent + }, + remove, + parentNode: (element) => element.parent, + nextSibling: (element) => { + const siblings = element.parent?.children ?? [] + return siblings[siblings.indexOf(element) + 1] ?? null + }, +}) + +function text(element: RenderNode): string { + return element.text + element.children.map(text).join('') +} + +function find( + element: RenderNode, + predicate: (element: RenderNode) => boolean, +): RenderNode[] { + return [ + ...(predicate(element) ? [element] : []), + ...element.children.flatMap((child) => find(child, predicate)), + ] +} + +function mountBilling(holdInitialLoad = false) { + const notifications: { message: string; type: string }[] = [] + let responseStatus = 'active' + const authStore = vue.reactive({ + user: { + id: 'account-a', + subscription_name: 'pro-monthly', + subscription_status: 'active', + api_key: 'original-key', + subscription_renews_at: '2027-01-01T00:00:00Z', + subscription_ends_at: '2027-01-01T00:00:00Z', + }, + authUser: null, + loadUser: async () => {}, + }) + const billingStore = { + billingUsage: null, + billingUsageHistory: [], + loadBillingUsage: async () => { + if (holdInitialLoad) await new Promise(() => {}) + }, + loadBillingUsageHistory: async () => {}, + cancelSubscription: async () => {}, + } + const imports: Record = { + vue, + '@mdi/js': icons, + '~/utils/countries': countries, + '~/utils/api-error': apiError, + '~/utils/black-friday': blackFriday, + } + const component = runInNewContext(`${outputText}\nexports.default`, { + exports: {}, + require: (name: string) => { + assert.ok(name in imports, `Unexpected import: ${name}`) + return imports[name] + }, + ref: vue.ref, + computed: vue.computed, + watch: vue.watch, + onMounted: vue.onMounted, + onBeforeUnmount: vue.onBeforeUnmount, + definePageMeta: () => {}, + useHead: () => {}, + useRuntimeConfig: () => ({ + public: { + checkoutUrl: 'https://checkout.example.test', + enterpriseCheckoutUrl: 'https://checkout.example.test/enterprise', + }, + }), + useVDisplay: () => ({ lgAndUp: false }), + useAuthStore: () => authStore, + useBillingStore: () => billingStore, + useApi: () => ({ + apiFetch: async () => ({ + data: { + ...authStore.user, + subscription_status: responseStatus, + api_key: 'response-key', + }, + }), + }), + useBlackFridayStore: () => ({ active: false, now: 0 }), + useNotificationsStore: () => ({ + addNotification: (notification: { message: string; type: string }) => + notifications.push(notification), + }), + useFilters: () => ({ + formatDecimal: String, + formatTimestamp: String, + }), + Date, + setTimeout, + clearTimeout, + AbortController, + URL, + }) as Component + const app = renderer.createApp(component) + const names = new Set( + [...descriptor.template!.content.matchAll(/<([A-Z]\w*)/g)].map( + (match) => match[1]!, + ), + ) + names.delete('VDialog') + names.add('v-code') + for (const name of names) { + app.component( + name, + vue.defineComponent({ + inheritAttrs: false, + setup: + (_props, { attrs, slots }) => + () => + vue.h(name, attrs, slots.default?.()), + }), + ) + } + app.component( + 'VDialog', + vue.defineComponent({ + props: { modelValue: Boolean, persistent: Boolean }, + emits: ['update:modelValue'], + setup: + (props, { slots, emit }) => + () => + vue.h('VDialog', { ...props }, [ + slots.activator?.({ + props: { onClick: () => emit('update:modelValue', true) }, + }), + props.modelValue ? slots.default?.() : null, + ]), + }), + ) + const root = node('root') + app.mount(root) + return { + app, + root, + authStore, + notifications, + confirmCancellation: () => { + responseStatus = 'cancelled' + }, + } +} + +function buttons(root: RenderNode, label: string) { + return find( + root, + (element) => element.type === 'VBtn' && text(element).trim() === label, + ) +} + +async function click(button: RenderNode) { + const handler = button.props.onClick + assert.equal(typeof handler, 'function') + if (typeof handler === 'function') return handler() +} + +test('the mounted billing page keeps the dialog persistent, then renders pending and confirmed plan cards', async (context) => { + context.mock.timers.enable({ apis: ['Date', 'setTimeout'], now: 0 }) + const { app, root, authStore, notifications } = mountBilling() + try { + await setImmediate() + await click(buttons(root, 'Cancel Plan')[0]!) + await vue.nextTick() + const cancellation = click(buttons(root, 'Cancel Plan').at(-1)!) + await setImmediate() + + const dialog = find( + root, + (element) => + element.type === 'VDialog' && element.props.modelValue === true, + )[0]! + assert.equal(dialog.props.persistent, true) + assert.equal(buttons(root, 'Keep Subscription')[0]?.props.disabled, true) + assert.equal(notifications.length, 0) + + context.mock.timers.tick(10000) + await cancellation + await vue.nextTick() + + assert.match(text(root), /Cancellation in progress.*still updating/) + assert.equal(buttons(root, 'Cancel Plan').length, 0) + assert.equal(buttons(root, 'Update Plan').length, 0) + assert.equal(notifications.length, 1) + + authStore.user.subscription_status = 'cancelled' + await vue.nextTick() + assert.doesNotMatch(text(root), /still updating/) + assert.match(text(root), /You will be downgraded/) + assert.ok(buttons(root, 'Upgrade Plan').length > 0) + + authStore.user.subscription_name = 'free' + authStore.user.subscription_status = 'expired' + await vue.nextTick() + assert.doesNotMatch(text(root), /still updating|Your next bill/) + assert.equal(buttons(root, 'Cancel Plan').length, 0) + assert.ok(buttons(root, 'Upgrade Plan').length > 0) + } finally { + app.unmount() + context.mock.timers.reset() + } +}) + +test('unrelated billing loading does not lock the cancellation dialog', async () => { + const { app, root } = mountBilling(true) + try { + await setImmediate() + await click(buttons(root, 'Cancel Plan')[0]!) + await vue.nextTick() + + const dialog = find( + root, + (element) => + element.type === 'VDialog' && element.props.modelValue === true, + )[0]! + assert.equal(dialog.props.persistent, false) + assert.equal(buttons(root, 'Keep Subscription')[0]?.props.disabled, false) + } finally { + app.unmount() + } +}) + +test('confirmed cancellation updates the mounted billing card without modifying auth state', async () => { + const { app, root, authStore, notifications, confirmCancellation } = + mountBilling() + try { + await setImmediate() + await click(buttons(root, 'Cancel Plan')[0]!) + await vue.nextTick() + confirmCancellation() + await click(buttons(root, 'Cancel Plan').at(-1)!) + await vue.nextTick() + + assert.match(text(root), /You will be downgraded/) + assert.equal(buttons(root, 'Cancel Plan').length, 0) + assert.equal(authStore.user.subscription_status, 'active') + assert.equal(authStore.user.api_key, 'original-key') + assert.equal(notifications.length, 1) + assert.equal(notifications[0]?.type, 'success') + + authStore.user = { + ...authStore.user, + subscription_status: 'active', + } + await vue.nextTick() + assert.match(text(root), /You will be downgraded/) + assert.equal(buttons(root, 'Cancel Plan').length, 0) + + authStore.user = { + ...authStore.user, + subscription_name: 'free', + subscription_status: 'expired', + } + await vue.nextTick() + assert.doesNotMatch(text(root), /You will be downgraded/) + assert.equal(buttons(root, 'Cancel Plan').length, 0) + assert.ok(buttons(root, 'Upgrade Plan').length > 0) + + authStore.user = { + ...authStore.user, + id: 'account-b', + subscription_name: 'pro-monthly', + subscription_status: 'active', + } + await vue.nextTick() + assert.doesNotMatch(text(root), /You will be downgraded/) + assert.ok(buttons(root, 'Cancel Plan').length > 0) + } finally { + app.unmount() + } +}) diff --git a/web/app/pages/billing/index.test.ts b/web/app/pages/billing/index.test.ts new file mode 100644 index 000000000..17dbe8882 --- /dev/null +++ b/web/app/pages/billing/index.test.ts @@ -0,0 +1,342 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { test } from 'node:test' +import { setImmediate } from 'node:timers/promises' +import { runInNewContext } from 'node:vm' +import ts from 'typescript' +import { parse } from 'vue/compiler-sfc' +import { getApiErrorMessage } from '../../utils/api-error' + +const { descriptor } = parse( + readFileSync(new URL('./index.vue', import.meta.url), 'utf8'), +) +const script = ts.createSourceFile( + 'billing.ts', + descriptor.scriptSetup!.content, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TS, +) +const cancelPlan = script.statements.find( + (statement) => + ts.isFunctionDeclaration(statement) && + statement.name?.text === 'cancelPlan', +)! +const { outputText } = ts.transpileModule(cancelPlan.getText(script), { + compilerOptions: { target: ts.ScriptTarget.ESNext }, +}) +const unmountHook = script.statements.find( + (statement) => + ts.isExpressionStatement(statement) && + ts.isCallExpression(statement.expression) && + statement.expression.expression.getText(script) === 'onBeforeUnmount', +) +const unmountCode = unmountHook?.getText(script) ?? '' + +function setupCancellation( + cancelSubscription: () => Promise, + refreshError?: unknown, + statuses = ['cancelled'], +) { + let reloads = 0 + let refreshes = 0 + let elapsed = 0 + let deadlineCallback: (() => void) | undefined + let unmount = () => {} + let refreshSignal: AbortSignal | undefined + const waitingStates: { dialog: boolean; notifications: number }[] = [] + const navigations: string[] = [] + const notifications: { message: string; type: string }[] = [] + const loading = { value: false } + const dialog = { value: true } + const cancellationPending = { value: false } + const billingUser: { + value: { id: string; subscription_status: string; api_key: string } | null + } = { value: null } + const authStore = { + user: { + id: 'account-a', + subscription_status: 'active', + api_key: 'original-key', + }, + } + const api = { + apiFetch: async (_path: string, options: { signal?: AbortSignal }) => { + refreshSignal = options.signal + if (refreshError) throw refreshError + return { + data: { + id: 'account-a', + subscription_status: + statuses[Math.min(refreshes++, statuses.length - 1)]!, + api_key: 'response-key', + }, + } + }, + } + const cancel = runInNewContext(`${unmountCode}\n${outputText}\ncancelPlan`, { + loading, + dialog, + cancellationPending, + cancellingSubscription: { value: false }, + billingPageActive: true, + stopCancellationWait: undefined, + cancellationRefresh: undefined, + AbortController, + onBeforeUnmount: (callback: () => void) => { + unmount = callback + }, + authStore, + billingUser, + apiFetch: (path: string, options: { signal?: AbortSignal }) => + api.apiFetch(path, options), + billingStore: { cancelSubscription }, + notificationsStore: { + addNotification: (notification: { message: string; type: string }) => { + notifications.push(notification) + }, + }, + window: { location: { reload: () => reloads++ } }, + navigateTo: (path: string) => navigations.push(path), + getApiErrorMessage, + Date: { now: () => elapsed }, + setTimeout: (callback: () => void, delay: number) => { + if (delay === 10000) { + deadlineCallback = callback + } else { + waitingStates.push({ + dialog: dialog.value, + notifications: notifications.length, + }) + elapsed += delay + callback() + if (elapsed >= 10000) deadlineCallback?.() + } + return 1 + }, + clearTimeout: () => { + deadlineCallback = undefined + }, + }) as () => Promise + + return { + cancel, + loading, + dialog, + cancellationPending, + authStore, + billingUser, + api, + notifications, + navigations, + reloads: () => reloads, + refreshes: () => refreshes, + refreshSignal: () => refreshSignal, + elapsed: () => elapsed, + expireDeadline: () => { + elapsed = 10000 + deadlineCallback?.() + }, + waitingStates, + unmount: () => unmount(), + } +} + +test('successful cancellation updates billing status in place without a browser reload', async () => { + const pending = setupCancellation(async () => {}) + + await pending.cancel() + + assert.equal(pending.reloads(), 0) + assert.deepEqual(pending.navigations, []) + assert.equal(pending.billingUser.value?.subscription_status, 'cancelled') + assert.equal(pending.authStore.user.subscription_status, 'active') + assert.equal(pending.authStore.user.api_key, 'original-key') + assert.equal(pending.dialog.value, false) + assert.equal(pending.loading.value, false) + assert.equal(pending.cancellationPending.value, false) + assert.equal(pending.notifications.at(-1)?.type, 'success') + assert.equal(pending.notifications.length, 1) +}) + +test('failed cancellation stays on the page without refreshing and displays an error', async () => { + const pending = setupCancellation(async () => { + throw new Error('Cancellation failed') + }) + + await pending.cancel() + + assert.equal(pending.reloads(), 0) + assert.deepEqual(pending.navigations, []) + assert.equal(pending.notifications.at(-1)?.type, 'error') + assert.equal(pending.loading.value, false) + assert.equal(pending.authStore.user.subscription_status, 'active') + assert.equal(pending.dialog.value, false) +}) + +test('a refresh failure after cancellation reports the refresh error rather than a cancellation failure', async () => { + const pending = setupCancellation(async () => {}, { + data: { message: 'Account fetch failed' }, + }) + + await pending.cancel() + + assert.equal(pending.reloads(), 0) + assert.deepEqual(pending.navigations, []) + assert.equal(pending.dialog.value, false) + assert.equal(pending.loading.value, false) + assert.equal(pending.notifications.at(-1)?.type, 'error') + assert.match(pending.notifications.at(-1)!.message, /cancelled.*refresh/) + assert.match(pending.notifications.at(-1)!.message, /Account fetch failed/) + assert.equal(pending.notifications.length, 1) +}) + +test('cancellation waits for the webhook when the first account response is stale', async () => { + const pending = setupCancellation(async () => {}, undefined, [ + 'active', + 'cancelled', + ]) + + await pending.cancel() + + assert.equal(pending.billingUser.value?.subscription_status, 'cancelled') + assert.equal(pending.cancellationPending.value, false) + assert.ok(pending.refreshes() > 1) + assert.equal(pending.loading.value, false) + assert.equal(pending.reloads(), 0) + assert.deepEqual(pending.waitingStates, [{ dialog: true, notifications: 0 }]) + assert.equal(pending.dialog.value, false) + assert.equal(pending.notifications.length, 1) +}) + +test('a delayed webhook leaves a visible pending state after bounded polling', async () => { + const pending = setupCancellation(async () => {}, undefined, ['active']) + + await pending.cancel() + + assert.equal(pending.cancellationPending.value, true) + assert.ok(pending.refreshes() > 1 && pending.refreshes() <= 20) + assert.equal(pending.loading.value, false) + assert.equal(pending.notifications.at(-1)?.type, 'info') + assert.match(pending.notifications.at(-1)!.message, /cancellation.*progress/i) + assert.equal(pending.elapsed(), 10000) + assert.ok( + pending.waitingStates.every( + (state) => state.dialog && state.notifications === 0, + ), + ) + assert.equal(pending.dialog.value, false) + assert.equal(pending.notifications.length, 1) +}) + +test('the dialog closes at ten seconds even if the account refresh is still in flight', async () => { + const pending = setupCancellation(async () => {}) + let signal: AbortSignal | undefined + pending.api.apiFetch = (_path, options) => { + signal = options.signal + return new Promise(() => {}) + } + const cancellation = pending.cancel() + await setImmediate() + + assert.equal(pending.dialog.value, true) + assert.equal(pending.notifications.length, 0) + pending.expireDeadline() + await cancellation + + assert.equal(pending.dialog.value, false) + assert.equal(pending.loading.value, false) + assert.equal(pending.notifications.length, 1) + assert.equal(pending.notifications[0]?.type, 'info') + assert.equal(signal?.aborted, true) +}) + +test('leaving billing stops polling and prevents a notification on the next page', async () => { + const pending = setupCancellation(async () => {}) + let resolveRefresh!: () => void + let refreshes = 0 + pending.api.apiFetch = async () => { + refreshes++ + await new Promise((resolve) => { + resolveRefresh = resolve + }) + + return { + data: { + id: 'account-a', + subscription_status: 'cancelled', + api_key: 'response-key', + }, + } + } + const cancellation = pending.cancel() + await setImmediate() + + pending.unmount() + pending.expireDeadline() + await cancellation + resolveRefresh() + await setImmediate() + + assert.equal(pending.notifications.length, 0) + assert.equal(refreshes, 1) + assert.equal(pending.billingUser.value, null) + assert.equal(pending.authStore.user.api_key, 'original-key') +}) + +test('the total deadline includes a cancellation request that is still in progress', async () => { + let resolveCancellation!: () => void + const pending = setupCancellation( + () => + new Promise((resolve) => { + resolveCancellation = resolve + }), + ) + const cancellation = pending.cancel() + await setImmediate() + + assert.equal(pending.dialog.value, true) + assert.equal(pending.loading.value, true) + assert.equal(pending.notifications.length, 0) + pending.expireDeadline() + await cancellation + + assert.equal(pending.dialog.value, false) + assert.equal(pending.loading.value, false) + assert.equal(pending.notifications.length, 1) + assert.match(pending.notifications[0]!.message, /cancellation.*progress/i) + resolveCancellation() + await setImmediate() + assert.equal(pending.billingUser.value, null) + assert.equal(pending.refreshes(), 0) + assert.equal(pending.notifications.length, 1) +}) + +test('an old cancellation response cannot update billing or notify after the account changes', async () => { + const pending = setupCancellation(async () => {}) + let resolveRefresh!: () => void + pending.api.apiFetch = async () => { + await new Promise((resolve) => { + resolveRefresh = resolve + }) + return { + data: { + id: 'account-a', + subscription_status: 'cancelled', + api_key: 'response-key', + }, + } + } + const cancellation = pending.cancel() + await setImmediate() + pending.authStore.user.id = 'account-b' + pending.expireDeadline() + await cancellation + resolveRefresh() + await setImmediate() + + assert.equal(pending.billingUser.value, null) + assert.equal(pending.notifications.length, 0) + assert.equal(pending.authStore.user.id, 'account-b') + assert.equal(pending.authStore.user.api_key, 'original-key') +}) diff --git a/web/app/pages/billing/index.vue b/web/app/pages/billing/index.vue index 1106358f2..f2b17f7e2 100644 --- a/web/app/pages/billing/index.vue +++ b/web/app/pages/billing/index.vue @@ -9,6 +9,7 @@ import { mdiInvoice, } from '@mdi/js' import type { + EntitiesUser, RequestsUserPaymentInvoice, ResponsesUserSubscriptionPaymentsResponse, } from '~~/shared/types/api' @@ -31,6 +32,24 @@ useHead({ const config = useRuntimeConfig() const { lgAndUp } = useVDisplay() const authStore = useAuthStore() +const { apiFetch } = useApi() +const billingUser = ref(null) +const billingAccount = computed(() => + authStore.user && billingUser.value?.id === authStore.user.id + ? billingUser.value + : authStore.user, +) +watch( + () => authStore.user, + (account) => { + if ( + account?.subscription_status === 'cancelled' || + account?.subscription_name === 'free' + ) { + billingUser.value = null + } + }, +) const promotion = useBlackFridayStore() const billingStore = useBillingStore() const notificationsStore = useNotificationsStore() @@ -39,6 +58,27 @@ const { formatDecimal, formatTimestamp } = useFilters() const loading = ref(true) const loadingSubscriptionPayments = ref(false) const dialog = ref(false) +const cancellationPending = ref(false) +const cancellingSubscription = ref(false) +let billingPageActive = true +let stopCancellationWait: (() => void) | undefined +let cancellationRefresh: AbortController | undefined + +onBeforeUnmount(() => { + billingPageActive = false + cancellationRefresh?.abort() + stopCancellationWait?.() +}) + +watch( + () => authStore.user?.id, + () => { + billingUser.value = null + cancellationPending.value = false + cancellationRefresh?.abort() + stopCancellationWait?.() + }, +) const subscriptionInvoiceDialog = ref(false) const payments = ref(null) const selectedPayment = ref(null) @@ -124,17 +164,17 @@ const plans: PaymentPlan[] = [ const plan = computed(() => { return (plans.find( - (x) => x.id === (authStore.user?.subscription_name || 'free'), + (x) => x.id === (billingAccount.value?.subscription_name || 'free'), ) ?? plans[0])! }) const isOnFreePlan = computed(() => plan.value.id === 'free') const blackFridayDiscountAvailable = computed( - () => authStore.user?.subscription_name === 'free' && promotion.active, + () => billingAccount.value?.subscription_name === 'free' && promotion.active, ) const isOnLifetimePlan = computed(() => plan.value.id === 'pro-lifetime') const subscriptionIsCancelled = computed( - () => authStore.user?.subscription_status === 'cancelled', + () => billingAccount.value?.subscription_status === 'cancelled', ) const invoiceStateOptions = computed(() => @@ -163,7 +203,7 @@ const checkoutURL = computed(() => { } return getBlackFridayCheckoutUrl( url, - authStore.user?.subscription_name, + billingAccount.value?.subscription_name, promotion.now, ) }) @@ -182,7 +222,7 @@ const enterpriseCheckoutURL = computed(() => { } return getBlackFridayCheckoutUrl( url, - authStore.user?.subscription_name, + billingAccount.value?.subscription_name, promotion.now, ) }) @@ -198,7 +238,7 @@ async function loadData() { } async function loadSubscriptionInvoices() { - if (!authStore.user?.subscription_id) return + if (!billingAccount.value?.subscription_id) return loadingSubscriptionPayments.value = true try { payments.value = await billingStore.indexSubscriptionPayments() @@ -225,22 +265,80 @@ async function updateDetails() { async function cancelPlan() { loading.value = true + cancellingSubscription.value = true + cancellationPending.value = true + cancellationRefresh = new AbortController() + const signal = cancellationRefresh.signal + const accountId = authStore.user?.id + const accountActive = () => + billingPageActive && !signal.aborted && authStore.user?.id === accountId + const deadline = Date.now() + 10000 + let timeout: ReturnType | undefined + let cancellationRequested = false try { - await billingStore.cancelSubscription() - notificationsStore.addNotification({ - message: 'Subscription cancelled successfully', - type: 'success', - }) - navigateTo('/') + await Promise.race([ + (async () => { + await billingStore.cancelSubscription() + if (!accountActive()) return + cancellationRequested = true + while (accountActive() && Date.now() < deadline) { + const response = await apiFetch<{ data: EntitiesUser }>( + '/v1/users/me', + { + signal, + }, + ) + if (!accountActive()) return + if ( + response.data.subscription_status === 'cancelled' || + response.data.subscription_name === 'free' + ) { + billingUser.value = response.data + cancellationPending.value = false + return + } + const remaining = deadline - Date.now() + if (remaining <= 0) return + await new Promise((resolve) => + setTimeout(resolve, Math.min(1000, remaining)), + ) + } + })(), + new Promise((resolve) => { + stopCancellationWait = resolve + timeout = setTimeout(resolve, 10000) + }), + ]) + if (!accountActive()) return + if (cancellationPending.value) { + notificationsStore.addNotification({ + message: + 'Cancellation is in progress. Please check your billing status shortly.', + type: 'info', + }) + } else { + notificationsStore.addNotification({ + message: 'Subscription cancelled successfully', + type: 'success', + }) + } } catch (error: unknown) { + if (!accountActive()) return + if (!cancellationRequested) cancellationPending.value = false notificationsStore.addNotification({ - message: getApiErrorMessage( - error, - 'We could not cancel your subscription.', - ), + message: cancellationRequested + ? `Your subscription was cancelled, but we could not refresh your billing details. ${getApiErrorMessage(error, 'Please try again later.')}` + : getApiErrorMessage(error, 'We could not cancel your subscription.'), type: 'error', }) + } finally { + clearTimeout(timeout) + cancellationRefresh.abort() + cancellationRefresh = undefined + stopCancellationWait = undefined + dialog.value = false loading.value = false + cancellingSubscription.value = false } } @@ -301,9 +399,34 @@ onMounted(async () => {

Current Plan

- + - + +

+ Cancellation in progress +

+

+ Your billing details are still updating. +

+
+

{ Your next bill is for ${{ plan.price }} on {{ new Date( - authStore.user.subscription_renews_at!, + billingAccount.subscription_renews_at!, ).toLocaleDateString() }}

@@ -340,7 +463,7 @@ onMounted(async () => { You will be downgraded to the FREE plan on {{ new Date( - authStore.user.subscription_ends_at!, + billingAccount.subscription_ends_at!, ).toLocaleDateString() }}

@@ -374,11 +497,13 @@ onMounted(async () => { @@ -401,7 +526,7 @@ onMounted(async () => { of the current billing period on {{ new Date( - authStore.user.subscription_renews_at!, + billingAccount.subscription_renews_at!, ).toLocaleDateString() }}

@@ -410,6 +535,7 @@ onMounted(async () => { Keep Subscription @@ -418,7 +544,7 @@ onMounted(async () => { @@ -540,7 +666,7 @@ onMounted(async () => { -