diff --git a/.changeset/provider-subscriptions.md b/.changeset/provider-subscriptions.md new file mode 100644 index 0000000..d9f123e --- /dev/null +++ b/.changeset/provider-subscriptions.md @@ -0,0 +1,12 @@ +--- +"@dashcommerce/core": minor +--- + +Add a provider-neutral subscription seam. + +- `PaymentProvider` gains optional `getSubscription`, `cancelSubscription` and `resumeSubscription`. Stripe keeps its existing Billing path; providers that manage billing themselves can use these. +- `charge.succeeded` and `PaymentStatusResult` can carry `ProviderSubscriptionInfo`, so a provider can identify the subscription/plan behind a charge. +- A normalised `subscription.updated` event lets a provider report a cancellation or status change outside a charge; core updates the local row. +- New `subscriptions/provider.ts` stores a provider-managed subscription and its invoices in the existing collections. The provider id is part of the unique storage key for both subscriptions and invoices (`${providerId}:${id}`), so two providers cannot collide on a numeric plan or transaction id. The first charge creates an order and a local subscription; later charges are recorded as invoices and extend the period, not as new orders. +- `subscriptions/lifecycle.ts` dispatches cancel/resume to a provider-managed subscription. Pause and in-place plan changes are refused for providers that do not support them. The admin and customer portal hide pause and the Stripe billing portal for those subscriptions. +- Stripe's `stripeSubscriptionId`/`stripeInvoiceId` fields keep their names for compatibility; they now hold the provider's subscription/plan and invoice id. diff --git a/packages/core/README.md b/packages/core/README.md index 5e9a141..841da55 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -70,6 +70,8 @@ For provider authors, `PaymentProvider` can declare: - `credentialFields`: the label, accepted prefixes and help text for the settings form. - `webhookHeaders`: the headers that identify its webhooks, besides `x--signature`. `verifyWebhook` receives every request header, and `credentials` (the provider's saved secret key and webhook secret) for headers signed with the API key rather than the webhook secret. - `checkConnection`: one read-only call with the saved keys, behind a "Test connection" button in Settings. Return `{ ok, message }`, with `ok: false` and a message the merchant can act on for a wrong or under-permitted key. +- `capabilities.subscriptions` plus optional `getSubscription`, `cancelSubscription` and `resumeSubscription`: core stores the provider's subscription/plan id from the first `charge.succeeded` that carries `subscription`, records later charges as invoices, and dispatches cancel/resume. Return `ProviderSubscriptionInfo`. A provider that cannot pause or change plans in place can omit those methods; core refuses the action with a readable error. +- `parseWebhookEvent` may return `subscription.updated` for a cancellation or status change outside a charge. Core updates the local row and does not create an order. `parseWebhookEvent` may return `refund.updated` to move a pending refund to `succeeded` or `failed`. A failed refund stops counting against its order: the refunded total, payment status and order status are worked out again, and stock the refund put back is taken back off. diff --git a/packages/core/src/admin/pages/SubscriptionsPage.tsx b/packages/core/src/admin/pages/SubscriptionsPage.tsx index 1cdcd34..7cfe49b 100644 --- a/packages/core/src/admin/pages/SubscriptionsPage.tsx +++ b/packages/core/src/admin/pages/SubscriptionsPage.tsx @@ -3,9 +3,9 @@ * `useListControls`, plus cancel/pause/resume with confirm dialogs, * per-row pending states, and toast feedback. * - * Stripe is the source of truth for subscription state, so we deliberately - * avoid optimistic updates: after every action we reload the list so the - * row reflects whatever webhook response came back. + * The payment provider is the source of truth for subscription state, so we + * deliberately avoid optimistic updates: after every action we reload the + * list so the row reflects whatever webhook response came back. */ import { useCallback, useMemo, useState } from "react"; @@ -64,19 +64,21 @@ function isCancellable(sub: Subscription): boolean { return !cancelled.includes(sub.status) && !sub.cancelAtPeriodEnd; } +function isProviderManaged(sub: Subscription): boolean { + return Boolean(sub.providerId && sub.providerId !== "stripe"); +} + function isPausable(sub: Subscription): boolean { - return sub.status === "active" || sub.status === "trialing"; + return (sub.status === "active" || sub.status === "trialing") && !isProviderManaged(sub); } function isResumable(sub: Subscription): boolean { - return sub.status === "paused"; + return sub.status === "paused" || (isProviderManaged(sub) && sub.status === "canceled"); } export function SubscriptionsPage() { const api = usePluginAPI(); - const [pending, setPending] = useState<{ id: string; action: Action } | null>( - null, - ); + const [pending, setPending] = useState<{ id: string; action: Action } | null>(null); const buildQuery = useMemo( () => (f: SubscriptionsFilters) => ({ @@ -89,23 +91,14 @@ export function SubscriptionsPage() { [], ); - const { - filters, - setFilter, - resetFilters, - items, - loading, - error, - hasMore, - loadMore, - reload, - } = useListControls({ - api, - endpoint: "admin/subscriptions", - initialFilters: INITIAL, - buildQuery, - limit: 50, - }); + const { filters, setFilter, resetFilters, items, loading, error, hasMore, loadMore, reload } = + useListControls({ + api, + endpoint: "admin/subscriptions", + initialFilters: INITIAL, + buildQuery, + limit: 50, + }); const act = useCallback( async (sub: Subscription, action: Action): Promise => { @@ -116,7 +109,7 @@ export function SubscriptionsPage() { title: immediate ? "Cancel subscription now?" : "Cancel at period end?", description: immediate ? "The customer loses access immediately. Any remaining time in the current period is not refunded automatically." - : `Access continues until ${new Date(sub.currentPeriodEnd).toLocaleDateString()}, then Stripe will cancel the subscription.`, + : `Access continues until ${new Date(sub.currentPeriodEnd).toLocaleDateString()}, then the payment provider will cancel the subscription.`, confirmLabel: immediate ? "Cancel now" : "Cancel at period end", destructive: true, }); @@ -126,7 +119,7 @@ export function SubscriptionsPage() { const ok = await confirm({ title: "Pause subscription?", description: - "Stripe stops generating invoices until the subscription is resumed. The customer keeps their record but won't be billed.", + "The payment provider stops generating invoices until the subscription is resumed. The customer keeps their record but won't be billed.", confirmLabel: "Pause", }); if (!ok) return; @@ -153,10 +146,7 @@ export function SubscriptionsPage() { } await reload(); } catch (err) { - toast.error( - "Action failed", - err instanceof Error ? err.message : String(err), - ); + toast.error("Action failed", err instanceof Error ? err.message : String(err)); } finally { setPending(null); } @@ -186,12 +176,7 @@ export function SubscriptionsPage() { label="Status" value={filters.status} options={STATUS_FILTERS} - onChange={(e) => - setFilter( - "status", - e.currentTarget.value as SubscriptionStatus | "", - ) - } + onChange={(e) => setFilter("status", e.currentTarget.value as SubscriptionStatus | "")} /> 0 ? "No subscriptions match" : "No subscriptions yet" - } + title={activeFilters > 0 ? "No subscriptions match" : "No subscriptions yet"} description={ activeFilters > 0 ? "Try widening your filters." @@ -259,6 +242,16 @@ export function SubscriptionsPage() { data={items} getRowKey={(s) => s.id} columns={[ + { + key: "provider", + header: "Provider", + render: (s) => { + const provider = s.providerId ?? "stripe"; + if (provider === "stripe") return "Stripe"; + if (provider === "flutterwave") return "Flutterwave"; + return provider; + }, + }, { key: "status", header: "Status", @@ -272,9 +265,7 @@ export function SubscriptionsPage() { > {s.cancelAtPeriodEnd && ( - - Cancels at period end - + Cancels at period end )} ), @@ -306,11 +297,7 @@ export function SubscriptionsPage() { key: "act", header: "", render: (s) => ( - act(s, a)} - /> + act(s, a)} /> ), }, ]} @@ -379,14 +366,16 @@ function SubscriptionActions({ )} {isCancellable(sub) && ( <> - + {!isProviderManaged(sub) && ( + + )} )} - {sub.status !== "canceled" && sub.status !== "paused" && ( + {!providerManaged && sub.status !== "canceled" && sub.status !== "paused" && ( )} - {sub.status === "paused" && ( + {(sub.status === "paused" || (providerManaged && sub.status === "canceled")) && ( )} - + {!providerManaged && ( + + )} ); diff --git a/packages/core/src/payment-provider/index.ts b/packages/core/src/payment-provider/index.ts index a1c3078..8385447 100644 --- a/packages/core/src/payment-provider/index.ts +++ b/packages/core/src/payment-provider/index.ts @@ -46,6 +46,7 @@ export type { PaymentProviderRuntimeContext, PaymentProviderShippingOption, PaymentStatusResult, + ProviderSubscriptionInfo, RefundResult, VerifyWebhookInput, VerifyWebhookResult, diff --git a/packages/core/src/payment-provider/types.ts b/packages/core/src/payment-provider/types.ts index 006dd4e..7b384fa 100644 --- a/packages/core/src/payment-provider/types.ts +++ b/packages/core/src/payment-provider/types.ts @@ -201,6 +201,12 @@ export type NormalizedPaymentEvent = shippingAddress?: PaymentProviderAddress; billingAddress?: PaymentProviderAddress; channel?: string; + /** + * Present when this charge belongs to a provider-managed + * subscription. Core records the first payment as an order and + * later charges as subscription invoices. + */ + subscription?: ProviderSubscriptionInfo; raw: unknown; } | { @@ -213,6 +219,23 @@ export type NormalizedPaymentEvent = reason?: string; raw: unknown; } + | { + /** + * A provider-managed subscription changed state outside a charge + * (e.g. Flutterwave's `subscription.cancelled`). Core updates the + * local row; it does not create an order or an invoice. + */ + type: "subscription.updated"; + providerId: string; + providerEventId: string; + providerSubscriptionId: string; + status: ProviderSubscriptionInfo["status"]; + currentPeriodStart?: string; + currentPeriodEnd?: string; + cancelAtPeriodEnd?: boolean; + canceledAt?: string; + raw: unknown; + } | { /** * A refund this store created moved on at the provider (e.g. @@ -304,12 +327,42 @@ export interface ConnectionCheckResult { mode?: "test" | "live"; } +/** + * Provider-reported subscription state. `providerSubscriptionId` is the id + * the provider uses for cancel/resume; for Flutterwave it is the payment + * plan id, because DashCommerce creates one plan per subscription. + */ +export interface ProviderSubscriptionInfo { + providerSubscriptionId: string; + status: + | "active" + | "trialing" + | "past_due" + | "canceled" + | "paused" + | "unpaid" + | "incomplete" + | "incomplete_expired"; + currentPeriodStart?: string; + currentPeriodEnd?: string; + cancelAtPeriodEnd?: boolean; + canceledAt?: string; + trialEndsAt?: string; + /** Integer minor units, when the provider reports it. */ + amount?: number; + currency?: string; + interval?: "day" | "week" | "month" | "year"; + intervalCount?: number; +} + export interface PaymentStatusResult { status: "pending" | "succeeded" | "failed"; paymentReference?: string; amount?: number; currency?: string; reason?: string; + /** Present when the payment is a subscription charge. */ + subscription?: ProviderSubscriptionInfo; } export interface PaymentProvider { @@ -396,6 +449,29 @@ export interface PaymentProvider { credentials: PaymentProviderCredentials, ): Promise; + /** + * Provider-managed subscription lifecycle. Optional and independent; + * core falls back to its Stripe Billing path for Stripe subscriptions. + * The provider id is the one core stored on the local subscription. + */ + getSubscription?( + ctx: PaymentProviderRuntimeContext, + providerSubscriptionId: string, + credentials: PaymentProviderCredentials, + ): Promise; + + cancelSubscription?( + ctx: PaymentProviderRuntimeContext, + input: { providerSubscriptionId: string; atPeriodEnd?: boolean }, + credentials: PaymentProviderCredentials, + ): Promise; + + resumeSubscription?( + ctx: PaymentProviderRuntimeContext, + input: { providerSubscriptionId: string }, + credentials: PaymentProviderCredentials, + ): Promise; + /** * Optional check behind the "Test connection" button in Settings: one * read-only call with the saved credentials. It must not create or change diff --git a/packages/core/src/routes/admin-api.ts b/packages/core/src/routes/admin-api.ts index f45cce3..12a00d2 100644 --- a/packages/core/src/routes/admin-api.ts +++ b/packages/core/src/routes/admin-api.ts @@ -1128,8 +1128,7 @@ async function postSubscriptionAction( action: string, routeCtx: RouteContext, ): Promise { - const client = await loadStripeClient(ctx); - if (!client) return json({ error: "Stripe not configured" }, 500); + const client = (await loadStripeClient(ctx)) ?? undefined; const body = (routeCtx.input ?? {}) as { mode?: "immediate" | "at_period_end"; resumesAt?: number; diff --git a/packages/core/src/routes/checkout.ts b/packages/core/src/routes/checkout.ts index a80bce0..c57ccc7 100644 --- a/packages/core/src/routes/checkout.ts +++ b/packages/core/src/routes/checkout.ts @@ -589,6 +589,20 @@ export const checkoutRoutes = { { status: 409, headers: { "Content-Type": "application/json" } }, ); } + // Recurring vendor splits are not implemented for any provider: + // Stripe's subscription path does not send transfer_data, and + // Flutterwave's Payment Plans do not guarantee subaccount payouts on + // renewal. Refuse rather than underpay the vendor. + if (isSubscriptionCart && recalculated.items.some((item) => item.vendorId)) { + return new Response( + JSON.stringify({ + error: + "Subscription carts with vendor-owned items are not supported yet. Split the subscription from the vendor items.", + code: "subscription_vendor_items", + }), + { status: 409, headers: { "Content-Type": "application/json" } }, + ); + } let transferDataPreview: { destination: string; amount?: number } | undefined; let applicationFeePreview: number | undefined; diff --git a/packages/core/src/routes/subscriptions-public.ts b/packages/core/src/routes/subscriptions-public.ts index 8e4dce6..88fa965 100644 --- a/packages/core/src/routes/subscriptions-public.ts +++ b/packages/core/src/routes/subscriptions-public.ts @@ -60,6 +60,8 @@ export interface PublicSubscription { intervalCount: number; currentPeriodEnd: Subscription["currentPeriodEnd"]; cancelAtPeriodEnd: boolean; + /** Gateway that owns the subscription. Unset means Stripe. */ + providerId?: string; } export function toPublicSubscription(sub: Subscription): PublicSubscription { @@ -72,6 +74,7 @@ export function toPublicSubscription(sub: Subscription): PublicSubscription { intervalCount: sub.intervalCount, currentPeriodEnd: sub.currentPeriodEnd, cancelAtPeriodEnd: sub.cancelAtPeriodEnd, + ...(sub.providerId ? { providerId: sub.providerId } : {}), }; } @@ -127,8 +130,7 @@ async function handleCancel(routeCtx: RouteContext, _ctx?: PluginContext): Promi const loaded = await loadAuthorisedSub(ctx, extractToken(routeCtx.request, input)); if (!loaded.ok) return loaded.response; - const client = await loadStripeClient(ctx); - if (!client) return jsonResponse({ error: "Stripe not configured" }, 500); + const client = (await loadStripeClient(ctx)) ?? undefined; try { const updated = await cancel(ctx, { @@ -158,8 +160,7 @@ async function handlePause(routeCtx: RouteContext, _ctx?: PluginContext): Promis const loaded = await loadAuthorisedSub(ctx, extractToken(routeCtx.request, input)); if (!loaded.ok) return loaded.response; - const client = await loadStripeClient(ctx); - if (!client) return jsonResponse({ error: "Stripe not configured" }, 500); + const client = (await loadStripeClient(ctx)) ?? undefined; try { const updated = await pause(ctx, { @@ -186,8 +187,7 @@ async function handleResume(routeCtx: RouteContext, _ctx?: PluginContext): Promi const loaded = await loadAuthorisedSub(ctx, extractToken(routeCtx.request, input)); if (!loaded.ok) return loaded.response; - const client = await loadStripeClient(ctx); - if (!client) return jsonResponse({ error: "Stripe not configured" }, 500); + const client = (await loadStripeClient(ctx)) ?? undefined; try { const updated = await resume(ctx, { @@ -223,6 +223,16 @@ async function handlePortal(routeCtx: RouteContext, _ctx?: PluginContext): Promi const loaded = await loadAuthorisedSub(ctx, extractToken(routeCtx.request, input)); if (!loaded.ok) return loaded.response; + if (loaded.subscription.providerId && loaded.subscription.providerId !== "stripe") { + return jsonResponse( + { + error: + "This subscription is managed by its payment provider. Use Cancel or Resume here instead.", + }, + 400, + ); + } + // Portal requires a Stripe customer id. Resolve via the local // customer row the subscription is linked to. const customerId = loaded.subscription.customerId; diff --git a/packages/core/src/routes/webhook.ts b/packages/core/src/routes/webhook.ts index 3d043e2..0de8d8c 100644 --- a/packages/core/src/routes/webhook.ts +++ b/packages/core/src/routes/webhook.ts @@ -29,7 +29,11 @@ import type { PluginContext, RouteContext, StorageCollection } from "emdash"; import { deleteLock, getLock } from "../cart/lock"; import { clear as clearCart } from "../cart/store"; import { sendSubscriptionRenewed, sendVendorActivated, sendVendorPayout } from "../emails"; -import { createOrderFromPaymentIntent, findOrderByPaymentIntent } from "../orders/create"; +import { + createOrderFromPaymentIntent, + findOrderByPaymentIntent, + loadOrderItems, +} from "../orders/create"; import { applyProviderRefundUpdate, recordRefundFromWebhook } from "../orders/refund"; import { type NormalizedPaymentEvent, @@ -53,8 +57,15 @@ import { upsertInvoiceFromStripe, } from "../subscriptions/create"; import { handleInvoicePaymentFailed } from "../subscriptions/dunning"; +import { + addSubscriptionInterval, + findProviderSubscription, + providerSubsStore, + recordProviderSubscriptionInvoice, + upsertProviderSubscription, +} from "../subscriptions/provider"; import type { CartState, StripeEventRecord } from "../types"; -import type { Address, CountryCode, Customer, Order } from "../types"; +import type { Address, CountryCode, CurrencyCode, Customer, Order } from "../types"; import { randomId } from "../util/ids"; import { isUniqueViolation } from "../util/storage"; import { findVendorByStripeAccountId, upsertVendorFromStripeAccount } from "../vendors/onboarding"; @@ -258,6 +269,11 @@ async function loadStripeClient(ctx: PluginContext): Promise; +function ordersStore(ctx: PluginContext): OrdersStore { + return (ctx.storage as unknown as { orders: OrdersStore }).orders; +} + type CustomersStore = StorageCollection; function customersStore(ctx: PluginContext): CustomersStore { return (ctx.storage as unknown as { customers: CustomersStore }).customers; @@ -670,6 +686,93 @@ async function handleNormalizedChargeSucceeded( }); } + const provider = requirePaymentProvider(event.providerId); + let amount = event.amount; + let currency = event.currency; + let paymentReference = event.paymentReference; + let subscription = event.subscription; + + if (provider.getPaymentStatus) { + const creds = await loadPaymentProviderCredentials(ctx.kv, provider.id); + if (creds) { + let live: Awaited>>; + try { + live = await provider.getPaymentStatus(ctx, event.paymentReference, creds); + } catch (err) { + throw new ConfirmationFailure( + `Provider status check failed: ${err instanceof Error ? err.message : String(err)}`, + ); + } + if (live.status !== "succeeded") { + ctx.log.error("Provider retrieve did not confirm a succeeded payment", { + providerId: provider.id, + paymentReference: event.paymentReference, + status: live.status, + reason: live.reason, + }); + throw new ConfirmationFailure("Payment not succeeded at provider"); + } + if (typeof live.amount === "number") amount = live.amount; + if (live.currency) currency = live.currency; + if (live.paymentReference) paymentReference = live.paymentReference; + subscription = live.subscription ?? subscription; + } + } + + // A renewal has no checkout draft and must not create a second order. + // Record it as a subscription invoice and extend the local period. + if (subscription) { + const existingSub = await findProviderSubscription( + ctx, + provider.id, + subscription.providerSubscriptionId, + ); + if (existingSub) { + // The provider may still report the subscription's old period on a + // renewal charge. Extend from the local period, which is the last + // period we recorded. + const periodStart = existingSub.currentPeriodEnd; + const periodEnd = addSubscriptionInterval( + periodStart, + existingSub.interval, + existingSub.intervalCount, + ); + const invoice = await recordProviderSubscriptionInvoice(ctx, { + subscription: existingSub, + providerId: provider.id, + providerInvoiceId: paymentReference, + amount, + currency: currency.toUpperCase() as CurrencyCode, + status: "paid", + periodStart, + periodEnd, + }); + return new Response( + JSON.stringify({ + received: true, + subscriptionId: existingSub.id, + invoiceId: invoice.id, + renewal: true, + }), + { status: 200, headers: { "Content-Type": "application/json" } }, + ); + } + } + + // A charge with no draft and no local subscription is not ours (for + // example another payment on the same Flutterwave account). Acknowledge + // it instead of returning 500 and making the provider retry. + if (!event.orderDraftId) { + ctx.log.info("Ignoring a charge with no checkout draft and no subscription", { + providerId: provider.id, + paymentReference: event.paymentReference, + }); + return new Response(JSON.stringify({ received: true, ignored: "no_draft" }), { + status: 200, + headers: { "Content-Type": "application/json" }, + }); + } + const snapshot = await ctx.kv.get(draftKey(event.orderDraftId)); if (!snapshot) { ctx.log.error("No cart snapshot for orderDraftId", { @@ -707,36 +810,6 @@ async function handleNormalizedChargeSucceeded( } } - let amount = event.amount; - let currency = event.currency; - let paymentReference = event.paymentReference; - const provider = requirePaymentProvider(event.providerId); - if (provider.getPaymentStatus) { - const creds = await loadPaymentProviderCredentials(ctx.kv, provider.id); - if (creds) { - let live: Awaited>>; - try { - live = await provider.getPaymentStatus(ctx, event.paymentReference, creds); - } catch (err) { - throw new ConfirmationFailure( - `Provider status check failed: ${err instanceof Error ? err.message : String(err)}`, - ); - } - if (live.status !== "succeeded") { - ctx.log.error("Provider retrieve did not confirm a succeeded payment", { - providerId: provider.id, - paymentReference: event.paymentReference, - status: live.status, - reason: live.reason, - }); - throw new ConfirmationFailure("Payment not succeeded at provider"); - } - if (typeof live.amount === "number") amount = live.amount; - if (live.currency) currency = live.currency; - if (live.paymentReference) paymentReference = live.paymentReference; - } - } - const { order, duplicate } = await createOrderFromPaymentIntent(ctx, { paymentIntent: { id: paymentReference, @@ -767,6 +840,60 @@ async function handleNormalizedChargeSucceeded( } } + // The first subscription payment also creates the local subscription. + // A failure here must not fail the order: the payment is captured. + if (subscription) { + try { + const items = await loadOrderItems(ctx, order.id); + const item = items.find((row) => row.subscriptionConfig); + const config = item?.subscriptionConfig; + if (!item || !config) { + ctx.log.warn("Subscription charge created an order with no subscription item", { + orderId: order.id, + providerId: provider.id, + providerSubscriptionId: subscription.providerSubscriptionId, + }); + } else { + const periodStart = + subscription.currentPeriodStart ?? order.paidAt ?? new Date().toISOString(); + const periodEnd = + subscription.currentPeriodEnd ?? + addSubscriptionInterval(periodStart, config.interval, config.intervalCount); + const local = await upsertProviderSubscription(ctx, { + providerId: provider.id, + providerSubscriptionId: subscription.providerSubscriptionId, + customerId: order.customerId, + productId: item.productId, + ...(item.variantId ? { variantId: item.variantId } : {}), + status: subscription.status ?? "active", + currency: order.currency, + unitAmount: item.unitPrice.amount, + quantity: item.quantity, + interval: config.interval, + intervalCount: config.intervalCount, + currentPeriodStart: periodStart, + currentPeriodEnd: periodEnd, + ...(subscription.trialEndsAt ? { trialEndsAt: subscription.trialEndsAt } : {}), + cancelAtPeriodEnd: subscription.cancelAtPeriodEnd ?? false, + ...(subscription.canceledAt ? { canceledAt: subscription.canceledAt } : {}), + }); + const subscriptionIds = [...new Set([...(order.subscriptionIds ?? []), local.id])]; + await ordersStore(ctx).put(order.id, { + ...order, + subscriptionIds, + updatedAt: new Date().toISOString(), + }); + } + } catch (err) { + ctx.log.error("Could not record the provider subscription", { + orderId: order.id, + providerId: provider.id, + providerSubscriptionId: subscription.providerSubscriptionId, + error: err instanceof Error ? err.message : String(err), + }); + } + } + return new Response( JSON.stringify({ received: true, orderId: order.id, orderNumber: order.orderNumber }), { status: 200, headers: { "Content-Type": "application/json" } }, @@ -896,6 +1023,44 @@ export const webhookRoutes = { if (normalized.type === "charge.failed") { return await handleNormalizedChargeFailed(ctx, normalized); } + if (normalized.type === "subscription.updated") { + if (normalized.providerId !== provider.id) { + return new Response( + JSON.stringify({ error: "Subscription event from another provider" }), + { status: 400, headers: { "Content-Type": "application/json" } }, + ); + } + const sub = await findProviderSubscription( + ctx, + provider.id, + normalized.providerSubscriptionId, + ); + if (!sub) { + return new Response(JSON.stringify({ received: true, orphan: true }), { + status: 200, + headers: { "Content-Type": "application/json" }, + }); + } + await providerSubsStore(ctx).put(sub.id, { + ...sub, + status: normalized.status, + ...(normalized.currentPeriodStart + ? { currentPeriodStart: normalized.currentPeriodStart } + : {}), + ...(normalized.currentPeriodEnd + ? { currentPeriodEnd: normalized.currentPeriodEnd } + : {}), + ...(normalized.cancelAtPeriodEnd !== undefined + ? { cancelAtPeriodEnd: normalized.cancelAtPeriodEnd } + : {}), + ...(normalized.canceledAt ? { canceledAt: normalized.canceledAt } : {}), + updatedAt: new Date().toISOString(), + }); + return new Response(JSON.stringify({ received: true, subscriptionId: sub.id }), { + status: 200, + headers: { "Content-Type": "application/json" }, + }); + } if (normalized.type === "refund.updated") { if (normalized.providerId !== provider.id) { return new Response(JSON.stringify({ error: "Refund event from another provider" }), { diff --git a/packages/core/src/subscriptions/lifecycle.ts b/packages/core/src/subscriptions/lifecycle.ts index f8c2271..7ae181a 100644 --- a/packages/core/src/subscriptions/lifecycle.ts +++ b/packages/core/src/subscriptions/lifecycle.ts @@ -1,13 +1,19 @@ /** * Subscription lifecycle — merchant + customer self-service actions. * - * All paths call Stripe first (with Idempotency-Key) and then wait for the - * resulting `customer.subscription.updated` webhook to refresh our local - * row — we do NOT optimistically mutate local state, to keep Stripe the - * single source of truth. + * Stripe subscriptions call Stripe first (with Idempotency-Key) and wait for + * the resulting `customer.subscription.updated` webhook to refresh the local + * row. Provider-managed subscriptions (Flutterwave Payment Plans) call the + * provider and update the local row immediately, because their cancellation + * is not delivered as a subscription webhook. */ import type { PluginContext } from "emdash"; +import { + type ProviderSubscriptionInfo, + loadPaymentProviderCredentials, + requirePaymentProvider, +} from "../payment-provider"; import type { StripeClientOptions } from "../stripe/client"; import { cancelSubscription as stripeCancel, @@ -15,30 +21,42 @@ import { type StripeSubscription, } from "../stripe/subscriptions"; import type { Subscription } from "../types"; -import { findSubscription } from "./create"; +import { findSubscription, subsStore } from "./create"; export type CancelMode = "immediate" | "at_period_end"; export interface CancelInput { subscriptionId: string; // our local id mode: CancelMode; - client: StripeClientOptions; + /** Required for Stripe; ignored for a provider-managed subscription. */ + client?: StripeClientOptions; } export async function cancel( ctx: PluginContext, input: CancelInput, -): Promise { +): Promise { const local = await loadLocal(ctx, input.subscriptionId); + if (isProviderManaged(local)) { + const info = await providerCancel(ctx, local, input.mode); + await saveProviderState(ctx, local, info, { + cancelAtPeriodEnd: info.cancelAtPeriodEnd ?? input.mode === "at_period_end", + canceledAt: + info.status === "canceled" ? (info.canceledAt ?? new Date().toISOString()) : undefined, + }); + return info; + } + + const client = requireStripeClient(input.client); const idemKey = `sub-cancel:${local.stripeSubscriptionId}:${input.mode}`; if (input.mode === "immediate") { - return stripeCancel(ctx, local.stripeSubscriptionId, input.client, idemKey); + return stripeCancel(ctx, local.stripeSubscriptionId, client, idemKey); } return stripeUpdate( ctx, local.stripeSubscriptionId, { cancelAtPeriodEnd: true }, - input.client, + client, idemKey, ); } @@ -47,14 +65,15 @@ export interface PauseInput { subscriptionId: string; behavior?: "keep_as_draft" | "mark_uncollectible" | "void"; resumesAt?: number; // unix seconds - client: StripeClientOptions; + client?: StripeClientOptions; } -export async function pause( - ctx: PluginContext, - input: PauseInput, -): Promise { +export async function pause(ctx: PluginContext, input: PauseInput): Promise { const local = await loadLocal(ctx, input.subscriptionId); + if (isProviderManaged(local)) { + throw new Error(`${local.providerId} does not support pausing subscriptions`); + } + const client = requireStripeClient(input.client); const idemKey = `sub-pause:${local.stripeSubscriptionId}:${input.resumesAt ?? "open"}`; return stripeUpdate( ctx, @@ -65,29 +84,33 @@ export async function pause( ...(input.resumesAt !== undefined ? { resumesAt: input.resumesAt } : {}), }, }, - input.client, + client, idemKey, ); } export interface ResumeInput { subscriptionId: string; - client: StripeClientOptions; + client?: StripeClientOptions; } export async function resume( ctx: PluginContext, input: ResumeInput, -): Promise { +): Promise { const local = await loadLocal(ctx, input.subscriptionId); + if (isProviderManaged(local)) { + const info = await providerResume(ctx, local); + await saveProviderState(ctx, local, info, { + cancelAtPeriodEnd: false, + canceledAt: undefined, + }); + return info; + } + + const client = requireStripeClient(input.client); const idemKey = `sub-resume:${local.stripeSubscriptionId}`; - return stripeUpdate( - ctx, - local.stripeSubscriptionId, - { pauseCollection: null }, - input.client, - idemKey, - ); + return stripeUpdate(ctx, local.stripeSubscriptionId, { pauseCollection: null }, client, idemKey); } export interface ChangePlanInput { @@ -97,7 +120,7 @@ export interface ChangePlanInput { newPriceId: string; quantity?: number; prorationBehavior?: "create_prorations" | "none" | "always_invoice"; - client: StripeClientOptions; + client?: StripeClientOptions; } export async function changePlan( @@ -105,6 +128,10 @@ export async function changePlan( input: ChangePlanInput, ): Promise { const local = await loadLocal(ctx, input.subscriptionId); + if (isProviderManaged(local)) { + throw new Error(`${local.providerId} does not support changing plans in place`); + } + const client = requireStripeClient(input.client); const idemKey = `sub-change:${local.stripeSubscriptionId}:${input.newPriceId}`; return stripeUpdate( ctx, @@ -119,18 +146,85 @@ export async function changePlan( ], prorationBehavior: input.prorationBehavior ?? "create_prorations", }, - input.client, + client, idemKey, ); } +function isProviderManaged(sub: Subscription): boolean { + return Boolean(sub.providerId && sub.providerId !== "stripe"); +} + +function requireStripeClient(client: StripeClientOptions | undefined): StripeClientOptions { + if (!client) throw new Error("Stripe not configured"); + return client; +} + +async function providerCancel( + ctx: PluginContext, + local: Subscription, + mode: CancelMode, +): Promise { + const provider = requirePaymentProvider(local.providerId ?? ""); + if (!provider.cancelSubscription) { + throw new Error(`${provider.label} does not support cancelling subscriptions`); + } + const creds = await loadPaymentProviderCredentials(ctx.kv, provider.id); + if (!creds) throw new Error(`Payment provider "${provider.id}" is not configured`); + return provider.cancelSubscription( + ctx, + { + providerSubscriptionId: local.providerSubscriptionId ?? local.stripeSubscriptionId, + atPeriodEnd: mode === "at_period_end", + }, + creds, + ); +} + +async function providerResume( + ctx: PluginContext, + local: Subscription, +): Promise { + const provider = requirePaymentProvider(local.providerId ?? ""); + if (!provider.resumeSubscription) { + throw new Error(`${provider.label} does not support resuming subscriptions`); + } + const creds = await loadPaymentProviderCredentials(ctx.kv, provider.id); + if (!creds) throw new Error(`Payment provider "${provider.id}" is not configured`); + return provider.resumeSubscription( + ctx, + { providerSubscriptionId: local.providerSubscriptionId ?? local.stripeSubscriptionId }, + creds, + ); +} + +async function saveProviderState( + ctx: PluginContext, + local: Subscription, + info: ProviderSubscriptionInfo, + extra: { cancelAtPeriodEnd?: boolean; canceledAt?: string | undefined }, +): Promise { + const now = new Date().toISOString(); + await subsStore(ctx).put(local.id, { + ...local, + status: info.status, + ...(info.currentPeriodStart ? { currentPeriodStart: info.currentPeriodStart } : {}), + ...(info.currentPeriodEnd ? { currentPeriodEnd: info.currentPeriodEnd } : {}), + cancelAtPeriodEnd: extra.cancelAtPeriodEnd ?? local.cancelAtPeriodEnd, + ...(extra.canceledAt ? { canceledAt: extra.canceledAt } : {}), + updatedAt: now, + }); +} + async function loadLocal(ctx: PluginContext, id: string): Promise { - // Accept either our uuid or the Stripe id for convenience. - const directRes = await (ctx.storage as unknown as { - subscriptions: { get(id: string): Promise }; - }).subscriptions.get(id); + // Accept either our uuid or the provider id for convenience. + const directRes = await ( + ctx.storage as unknown as { + subscriptions: { get(id: string): Promise }; + } + ).subscriptions.get(id); if (directRes) return { ...(directRes as Subscription), id }; - const byStripe = await findSubscription(ctx, id); - if (byStripe) return byStripe; + const byProvider = await findSubscription(ctx, id); + if (byProvider) return byProvider; throw new Error(`Subscription ${id} not found`); } diff --git a/packages/core/src/subscriptions/provider.ts b/packages/core/src/subscriptions/provider.ts new file mode 100644 index 0000000..0c4ab48 --- /dev/null +++ b/packages/core/src/subscriptions/provider.ts @@ -0,0 +1,209 @@ +/** + * Provider-neutral subscription storage. + * + * Stripe subscriptions still go through `create.ts` and `lifecycle.ts`; this + * module is the additive path for providers that manage billing themselves + * (Flutterwave Payment Plans). It reuses the existing `Subscription` and + * `SubscriptionInvoice` collections and their unique indexes, keyed on the + * provider's subscription/plan id. + */ + +import type { PluginContext, StorageCollection } from "emdash"; +import { money } from "../money"; +import type { + CurrencyCode, + IsoDateTime, + Subscription, + SubscriptionInvoice, + SubscriptionStatus, +} from "../types"; +import { randomId } from "../util/ids"; + +type SubsStore = StorageCollection; +type InvoiceStore = StorageCollection; + +export function providerSubsStore(ctx: PluginContext): SubsStore { + return (ctx.storage as unknown as { subscriptions: SubsStore }).subscriptions; +} + +function invoiceStore(ctx: PluginContext): InvoiceStore { + return (ctx.storage as unknown as { subscription_invoices: InvoiceStore }).subscription_invoices; +} + +/** Add a billing interval to an ISO date, clamping month-end. */ +export function addSubscriptionInterval( + start: IsoDateTime, + interval: Subscription["interval"], + count: number, +): IsoDateTime { + const date = new Date(start); + const n = Math.max(1, Math.trunc(count)); + if (interval === "day") { + date.setUTCDate(date.getUTCDate() + n); + return date.toISOString(); + } + if (interval === "week") { + date.setUTCDate(date.getUTCDate() + n * 7); + return date.toISOString(); + } + const months = interval === "year" ? n * 12 : n; + const day = date.getUTCDate(); + date.setUTCDate(1); + date.setUTCMonth(date.getUTCMonth() + months); + const lastDay = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 0)).getUTCDate(); + date.setUTCDate(Math.min(day, lastDay)); + return date.toISOString(); +} + +function providerStorageKey(providerId: string, providerSubscriptionId: string): string { + return `${providerId}:${providerSubscriptionId}`; +} + +export async function findProviderSubscription( + ctx: PluginContext, + providerId: string, + providerSubscriptionId: string, +): Promise { + const result = await providerSubsStore(ctx).query({ + where: { stripeSubscriptionId: providerStorageKey(providerId, providerSubscriptionId) }, + limit: 1, + }); + const row = result.items[0]; + if (!row) return null; + const sub = { ...(row.data as Subscription), id: row.id }; + // Rows written before `providerId` existed are Stripe rows. + if ((sub.providerId ?? "stripe") !== providerId) return null; + return sub; +} + +export interface UpsertProviderSubscriptionInput { + providerId: string; + providerSubscriptionId: string; + customerId: string; + productId: string; + variantId?: string; + status: SubscriptionStatus; + currency: CurrencyCode; + /** Integer minor units. */ + unitAmount: number; + quantity: number; + interval: Subscription["interval"]; + intervalCount: number; + currentPeriodStart?: IsoDateTime; + currentPeriodEnd?: IsoDateTime; + trialEndsAt?: IsoDateTime; + cancelAtPeriodEnd?: boolean; + canceledAt?: IsoDateTime; +} + +export async function upsertProviderSubscription( + ctx: PluginContext, + input: UpsertProviderSubscriptionInput, +): Promise { + const existing = await findProviderSubscription( + ctx, + input.providerId, + input.providerSubscriptionId, + ); + const now = new Date().toISOString(); + const currentPeriodStart = input.currentPeriodStart ?? existing?.currentPeriodStart ?? now; + const currentPeriodEnd = + input.currentPeriodEnd ?? + existing?.currentPeriodEnd ?? + addSubscriptionInterval(currentPeriodStart, input.interval, input.intervalCount); + + const record: Subscription = { + id: existing?.id ?? randomId(), + stripeSubscriptionId: providerStorageKey(input.providerId, input.providerSubscriptionId), + providerId: input.providerId, + providerSubscriptionId: input.providerSubscriptionId, + customerId: input.customerId, + productId: input.productId, + ...(input.variantId ? { variantId: input.variantId } : {}), + status: input.status, + currency: input.currency, + unitAmount: money(input.currency, input.unitAmount), + quantity: input.quantity, + interval: input.interval, + intervalCount: input.intervalCount, + ...(input.trialEndsAt ? { trialEndsAt: input.trialEndsAt } : {}), + currentPeriodStart, + currentPeriodEnd, + cancelAtPeriodEnd: input.cancelAtPeriodEnd ?? existing?.cancelAtPeriodEnd ?? false, + ...(input.canceledAt ? { canceledAt: input.canceledAt } : {}), + createdAt: existing?.createdAt ?? now, + updatedAt: now, + }; + await providerSubsStore(ctx).put(record.id, record); + return record; +} + +export interface RecordProviderInvoiceInput { + subscription: Subscription; + providerId: string; + providerInvoiceId: string; + /** Integer minor units. */ + amount: number; + currency: CurrencyCode; + status?: SubscriptionInvoice["status"]; + paidAt?: IsoDateTime; + attemptCount?: number; + /** When paid, the new billing period. */ + periodStart?: IsoDateTime; + periodEnd?: IsoDateTime; +} + +export async function recordProviderSubscriptionInvoice( + ctx: PluginContext, + input: RecordProviderInvoiceInput, +): Promise { + const storageKey = `${input.providerId}:${input.providerInvoiceId}`; + const existingResult = await invoiceStore(ctx).query({ + where: { stripeInvoiceId: storageKey }, + limit: 1, + }); + const existing = existingResult.items[0]; + const existingInvoice = existing?.data as SubscriptionInvoice | undefined; + const status = input.status ?? "paid"; + // A paid invoice is final. Returning it avoids extending the period a + // second time if the same charge is delivered with a different event id. + if (existingInvoice?.status === "paid" && status === "paid") { + return { ...existingInvoice, id: existing?.id ?? existingInvoice.id }; + } + const id = existing?.id ?? randomId(); + const now = new Date().toISOString(); + + const invoice: SubscriptionInvoice = { + id, + stripeInvoiceId: storageKey, + providerId: input.providerId, + providerInvoiceId: input.providerInvoiceId, + subscriptionId: input.subscription.id, + amount: money(input.currency, input.amount), + status, + ...(status === "paid" ? { paidAt: input.paidAt ?? now } : {}), + attemptCount: input.attemptCount ?? 0, + createdAt: (existing?.data as SubscriptionInvoice | undefined)?.createdAt ?? now, + }; + await invoiceStore(ctx).put(id, invoice); + + if (status === "paid") { + const periodStart = input.periodStart ?? input.subscription.currentPeriodStart; + const periodEnd = + input.periodEnd ?? + addSubscriptionInterval( + periodStart, + input.subscription.interval, + input.subscription.intervalCount, + ); + await providerSubsStore(ctx).put(input.subscription.id, { + ...input.subscription, + status: "active", + currentPeriodStart: periodStart, + currentPeriodEnd: periodEnd, + updatedAt: now, + }); + } + + return invoice; +} diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index fd5d2de..bce4c68 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -473,7 +473,20 @@ export type SubscriptionStatus = export interface Subscription { id: string; - stripeSubscriptionId: string; // unique + /** + * Provider subscription id. Unique. Stripe uses `sub_…`; Flutterwave + * uses the payment plan id, because DashCommerce creates one plan per + * subscription. The field name is legacy. + */ + stripeSubscriptionId: string; + /** Gateway that owns this subscription. Unset means Stripe. */ + providerId?: string; + /** + * The provider's raw subscription/plan id, without the storage prefix. + * Provider-managed rows store `${providerId}:${id}` in + * `stripeSubscriptionId` so two providers cannot collide on a numeric id. + */ + providerSubscriptionId?: string; customerId: string; productId: string; variantId?: string; @@ -494,7 +507,15 @@ export interface Subscription { export interface SubscriptionInvoice { id: string; - stripeInvoiceId: string; // unique + /** + * Provider invoice/charge id. Unique. Stripe uses `in_…`; Flutterwave + * uses the recurring transaction id. The field name is legacy. + */ + stripeInvoiceId: string; + /** Gateway that owns this invoice. Unset means Stripe. */ + providerId?: string; + /** The provider's raw invoice/charge id, without the storage prefix. */ + providerInvoiceId?: string; subscriptionId: string; amount: Money; status: "draft" | "open" | "paid" | "uncollectible" | "void"; diff --git a/packages/core/test/provider-subscriptions.test.ts b/packages/core/test/provider-subscriptions.test.ts new file mode 100644 index 0000000..8e0bc40 --- /dev/null +++ b/packages/core/test/provider-subscriptions.test.ts @@ -0,0 +1,533 @@ +/** + * Provider-managed subscriptions: the first charge creates an order and a + * local subscription; later charges are invoices, not orders. Flutterwave + * uses one payment plan per subscription, so the plan id is the local key. + */ + +import { afterEach, describe, expect, it } from "bun:test"; +import type { PluginContext, RouteContext } from "emdash"; +import { + type NormalizedPaymentEvent, + type PaymentProvider, + type ProviderSubscriptionInfo, + createMockPaymentProvider, + registerPaymentProvider, + resetPaymentProviders, +} from "../src/payment-provider"; +import sandbox from "../src/sandbox-entry"; +import { cancel, pause, resume } from "../src/subscriptions/lifecycle"; +import { + addSubscriptionInterval, + findProviderSubscription, + recordProviderSubscriptionInvoice, + upsertProviderSubscription, +} from "../src/subscriptions/provider"; +import type { CartState, Order, Subscription, SubscriptionInvoice } from "../src/types"; +import { makeRouteContext, ticketCart } from "./helpers/route-harness"; + +afterEach(() => resetPaymentProviders()); + +const DRAFT_ID = "0123456789abcdef0123456789abcdef"; +const RENEWAL_DRAFT_ID = "fedcba9876543210fedcba9876543210"; + +function subscriptionCart(sessionId: string): CartState { + const cart = ticketCart(sessionId); + cart.items = cart.items.map((item) => ({ + ...item, + subscriptionConfig: { interval: "month", intervalCount: 1 }, + })); + return cart; +} + +function provider(current: { paymentReference: string; subscription: ProviderSubscriptionInfo }) { + const base = createMockPaymentProvider({ id: "acme" }); + const impl: PaymentProvider = { + ...base, + webhookHeaders: ["x-acme-signature"], + parseWebhookEvent(raw): NormalizedPaymentEvent { + const body = JSON.parse(raw) as { + id: string; + orderDraftId: string; + paymentReference: string; + }; + return { + type: "charge.succeeded", + orderDraftId: body.orderDraftId, + providerId: "acme", + providerEventId: body.id, + paymentReference: body.paymentReference, + amount: 150_000, + currency: "KES", + customer: { email: "supporter@example.com" }, + subscription: current.subscription, + raw: body, + }; + }, + async getPaymentStatus() { + return { + status: "succeeded", + paymentReference: current.paymentReference, + amount: 150_000, + currency: "KES", + subscription: current.subscription, + }; + }, + }; + return impl; +} + +async function deliver(ctx: PluginContext, payload: string): Promise { + const request = new Request("http://test/checkout/webhook", { + method: "POST", + headers: { "x-acme-signature": "signed" }, + body: payload, + }); + const routeCtx = { ...ctx, request } as unknown as RouteContext; + return (await sandbox.routes["checkout/webhook"].handler(routeCtx, ctx)) as Response; +} + +function setup(current: { paymentReference: string; subscription: ProviderSubscriptionInfo }) { + registerPaymentProvider(provider(current)); + const harness = makeRouteContext({ + "settings:paymentProvider": "acme", + "settings:acmeSecretKey": "acme-key", + "settings:acmeWebhookSecret": "test-secret", + }); + harness.ctx.kv.set(`draft:${DRAFT_ID}`, { + cart: subscriptionCart("sess_sub"), + ttlMs: 900_000, + createdAt: new Date().toISOString(), + }); + return harness; +} + +describe("addSubscriptionInterval", () => { + it("clamps a month-end start to the last day of the next month", () => { + expect(addSubscriptionInterval("2026-01-31T00:00:00.000Z", "month", 1)).toBe( + "2026-02-28T00:00:00.000Z", + ); + }); + + it("adds weeks and years", () => { + expect(addSubscriptionInterval("2026-01-01T00:00:00.000Z", "week", 2)).toBe( + "2026-01-15T00:00:00.000Z", + ); + expect(addSubscriptionInterval("2026-01-01T00:00:00.000Z", "year", 1)).toBe( + "2027-01-01T00:00:00.000Z", + ); + }); +}); + +describe("provider-managed subscriptions", () => { + it("creates an order and a local subscription from the first charge", async () => { + const current = { + paymentReference: "pay_sub_1", + subscription: { + providerSubscriptionId: "plan_1", + status: "active" as const, + currentPeriodStart: "2026-01-01T00:00:00.000Z", + currentPeriodEnd: "2026-02-01T00:00:00.000Z", + }, + }; + const { ctx, getCol } = setup(current); + + const res = await deliver( + ctx, + JSON.stringify({ + id: "evt_sub_1", + orderDraftId: DRAFT_ID, + paymentReference: "pay_sub_1", + }), + ); + expect(res.status).toBe(200); + + const order = Array.from(getCol("orders").values())[0] as Order; + expect(order.subscriptionIds?.length).toBe(1); + const sub = Array.from(getCol("subscriptions").values())[0] as Subscription; + expect(sub).toMatchObject({ + stripeSubscriptionId: "acme:plan_1", + providerId: "acme", + providerSubscriptionId: "plan_1", + customerId: order.customerId, + status: "active", + currency: "KES", + interval: "month", + intervalCount: 1, + currentPeriodStart: "2026-01-01T00:00:00.000Z", + currentPeriodEnd: "2026-02-01T00:00:00.000Z", + }); + expect(sub.unitAmount).toEqual({ amount: 150_000, currency: "KES" }); + expect(getCol("subscription_invoices").size).toBe(0); + }); + + it("records a later charge as an invoice and does not create a second order", async () => { + const current = { + paymentReference: "pay_sub_1", + subscription: { + providerSubscriptionId: "plan_1", + status: "active" as const, + currentPeriodStart: "2026-01-01T00:00:00.000Z", + currentPeriodEnd: "2026-02-01T00:00:00.000Z", + }, + }; + const { ctx, getCol } = setup(current); + + await deliver( + ctx, + JSON.stringify({ + id: "evt_sub_1", + orderDraftId: DRAFT_ID, + paymentReference: "pay_sub_1", + }), + ); + expect(getCol("orders").size).toBe(1); + + current.paymentReference = "pay_sub_2"; + const res = await deliver( + ctx, + JSON.stringify({ + id: "evt_sub_2", + orderDraftId: RENEWAL_DRAFT_ID, + paymentReference: "pay_sub_2", + }), + ); + expect(res.status).toBe(200); + expect(getCol("orders").size).toBe(1); + + const sub = Array.from(getCol("subscriptions").values())[0] as Subscription; + expect(sub.currentPeriodStart).toBe("2026-02-01T00:00:00.000Z"); + expect(sub.currentPeriodEnd).toBe("2026-03-01T00:00:00.000Z"); + const invoice = Array.from(getCol("subscription_invoices").values())[0] as SubscriptionInvoice; + expect(invoice).toMatchObject({ + stripeInvoiceId: "acme:pay_sub_2", + providerId: "acme", + providerInvoiceId: "pay_sub_2", + subscriptionId: sub.id, + status: "paid", + }); + expect(invoice.amount).toEqual({ amount: 150_000, currency: "KES" }); + }); + + it("does not extend the period twice for the same paid invoice", async () => { + const { ctx } = makeRouteContext({}); + const sub = await upsertProviderSubscription(ctx, { + providerId: "acme", + providerSubscriptionId: "plan_dup", + customerId: "cus_1", + productId: "prod_1", + status: "active", + currency: "KES", + unitAmount: 150_000, + quantity: 1, + interval: "month", + intervalCount: 1, + currentPeriodStart: "2026-01-01T00:00:00.000Z", + currentPeriodEnd: "2026-02-01T00:00:00.000Z", + }); + const first = await recordProviderSubscriptionInvoice(ctx, { + subscription: sub, + providerId: "acme", + providerInvoiceId: "pay_dup", + amount: 150_000, + currency: "KES", + status: "paid", + periodStart: "2026-02-01T00:00:00.000Z", + }); + const afterFirst = await findProviderSubscription(ctx, "acme", "plan_dup"); + expect(afterFirst?.currentPeriodEnd).toBe("2026-03-01T00:00:00.000Z"); + const second = await recordProviderSubscriptionInvoice(ctx, { + subscription: afterFirst ?? sub, + providerId: "acme", + providerInvoiceId: "pay_dup", + amount: 150_000, + currency: "KES", + status: "paid", + }); + expect(second.id).toBe(first.id); + const afterSecond = await findProviderSubscription(ctx, "acme", "plan_dup"); + expect(afterSecond?.currentPeriodEnd).toBe("2026-03-01T00:00:00.000Z"); + }); + + it("applies a subscription.updated webhook to the local row", async () => { + const base = createMockPaymentProvider({ id: "acme" }); + registerPaymentProvider({ + ...base, + webhookHeaders: ["x-acme-signature"], + parseWebhookEvent(): NormalizedPaymentEvent { + return { + type: "subscription.updated", + providerId: "acme", + providerEventId: "sub-cancel-1", + providerSubscriptionId: "plan_1", + status: "canceled", + canceledAt: "2026-02-01T00:00:00.000Z", + raw: {}, + }; + }, + }); + const { ctx, getCol } = makeRouteContext({ + "settings:paymentProvider": "acme", + "settings:acmeSecretKey": "acme-key", + "settings:acmeWebhookSecret": "test-secret", + }); + const sub = await upsertProviderSubscription(ctx, { + providerId: "acme", + providerSubscriptionId: "plan_1", + customerId: "cus_1", + productId: "prod_1", + status: "active", + currency: "KES", + unitAmount: 150_000, + quantity: 1, + interval: "month", + intervalCount: 1, + }); + + const res = await deliver(ctx, JSON.stringify({ cancel: true })); + expect(res.status).toBe(200); + const stored = getCol("subscriptions").get(sub.id) as Subscription; + expect(stored.status).toBe("canceled"); + expect(stored.canceledAt).toBe("2026-02-01T00:00:00.000Z"); + }); + + it("records a renewal when the webhook has no draft or plan field", async () => { + const base = createMockPaymentProvider({ id: "acme" }); + registerPaymentProvider({ + ...base, + webhookHeaders: ["x-acme-signature"], + parseWebhookEvent(raw): NormalizedPaymentEvent { + const body = JSON.parse(raw) as { id: string; paymentReference: string }; + return { + type: "charge.succeeded", + orderDraftId: "", + providerId: "acme", + providerEventId: body.id, + paymentReference: body.paymentReference, + amount: 150_000, + currency: "KES", + customer: { email: "supporter@example.com" }, + raw: body, + }; + }, + async getPaymentStatus() { + return { + status: "succeeded", + paymentReference: "pay_renewal_no_draft", + amount: 150_000, + currency: "KES", + subscription: { + providerSubscriptionId: "plan_1", + status: "active" as const, + }, + }; + }, + }); + const { ctx, getCol } = makeRouteContext({ + "settings:paymentProvider": "acme", + "settings:acmeSecretKey": "acme-key", + "settings:acmeWebhookSecret": "test-secret", + }); + await upsertProviderSubscription(ctx, { + providerId: "acme", + providerSubscriptionId: "plan_1", + customerId: "cus_1", + productId: "prod_1", + status: "active", + currency: "KES", + unitAmount: 150_000, + quantity: 1, + interval: "month", + intervalCount: 1, + currentPeriodStart: "2026-01-01T00:00:00.000Z", + currentPeriodEnd: "2026-02-01T00:00:00.000Z", + }); + + const res = await deliver( + ctx, + JSON.stringify({ id: "evt_no_draft", paymentReference: "pay_renewal_no_draft" }), + ); + expect(res.status).toBe(200); + expect(getCol("orders").size).toBe(0); + expect(getCol("subscription_invoices").size).toBe(1); + const sub = Array.from(getCol("subscriptions").values())[0] as Subscription; + expect(sub.currentPeriodEnd).toBe("2026-03-01T00:00:00.000Z"); + }); + + it("ignores a charge with no draft and no subscription", async () => { + const base = createMockPaymentProvider({ id: "acme" }); + registerPaymentProvider({ + ...base, + webhookHeaders: ["x-acme-signature"], + parseWebhookEvent(raw): NormalizedPaymentEvent { + const body = JSON.parse(raw) as { id: string; paymentReference: string }; + return { + type: "charge.succeeded", + orderDraftId: "", + providerId: "acme", + providerEventId: body.id, + paymentReference: body.paymentReference, + amount: 150_000, + currency: "KES", + customer: { email: "someone@example.com" }, + raw: body, + }; + }, + async getPaymentStatus() { + return { + status: "succeeded", + paymentReference: "pay_other", + amount: 150_000, + currency: "KES", + }; + }, + }); + const { ctx, getCol } = makeRouteContext({ + "settings:paymentProvider": "acme", + "settings:acmeSecretKey": "acme-key", + "settings:acmeWebhookSecret": "test-secret", + }); + + const res = await deliver( + ctx, + JSON.stringify({ id: "evt_other", paymentReference: "pay_other" }), + ); + expect(res.status).toBe(200); + expect(await res.json()).toMatchObject({ received: true, ignored: "no_draft" }); + expect(getCol("orders").size).toBe(0); + expect(getCol("subscriptions").size).toBe(0); + }); + + it("does not hand a provider's plan id to another provider", async () => { + const current = { + paymentReference: "pay_sub_1", + subscription: { + providerSubscriptionId: "plan_1", + status: "active" as const, + }, + }; + const { ctx, getCol } = setup(current); + await deliver( + ctx, + JSON.stringify({ + id: "evt_sub_1", + orderDraftId: DRAFT_ID, + paymentReference: "pay_sub_1", + }), + ); + expect(await findProviderSubscription(ctx, "acme", "plan_1")).not.toBeNull(); + expect(await findProviderSubscription(ctx, "other", "plan_1")).toBeNull(); + expect(getCol("subscriptions").size).toBe(1); + }); +}); + +describe("subscription checkout guards", () => { + it("refuses a subscription cart with vendor-owned items", async () => { + const current = { + paymentReference: "pay_guard", + subscription: { providerSubscriptionId: "plan_guard", status: "active" as const }, + }; + registerPaymentProvider(provider(current)); + const { ctx } = makeRouteContext({ + "settings:paymentProvider": "acme", + "settings:checkoutMode": "hosted", + "settings:acmeSecretKey": "acme-key", + "settings:acmeWebhookSecret": "test-secret", + }); + const sessionId = `sess_guard_${Math.random()}`; + const cart = subscriptionCart(sessionId); + cart.items = cart.items.map((item) => ({ ...item, vendorId: "v1" })); + await ctx.kv.set(`cart:${sessionId}`, cart); + const routeCtx = { + ...ctx, + request: new Request("http://test/checkout/create-session", { + method: "POST", + headers: { Cookie: `dashcommerce_sid=${sessionId}` }, + }), + input: {}, + } as unknown as RouteContext; + const res = (await sandbox.routes["checkout/create-session"].handler( + routeCtx, + ctx, + )) as Response; + expect(res.status).toBe(409); + expect(await res.json()).toMatchObject({ code: "subscription_vendor_items" }); + }); +}); + +describe("provider-managed lifecycle", () => { + it("cancels and resumes through the provider, not Stripe", async () => { + const calls: Array<{ action: string; id: string }> = []; + const base = createMockPaymentProvider({ id: "acme" }); + registerPaymentProvider({ + ...base, + async cancelSubscription(_ctx, input) { + calls.push({ action: "cancel", id: input.providerSubscriptionId }); + return { + providerSubscriptionId: input.providerSubscriptionId, + status: "canceled" as const, + canceledAt: "2026-02-01T00:00:00.000Z", + }; + }, + async resumeSubscription(_ctx, input) { + calls.push({ action: "resume", id: input.providerSubscriptionId }); + return { + providerSubscriptionId: input.providerSubscriptionId, + status: "active" as const, + }; + }, + }); + const { ctx, getCol } = makeRouteContext({ + "settings:paymentProvider": "acme", + "settings:acmeSecretKey": "acme-key", + }); + const sub = await upsertProviderSubscription(ctx, { + providerId: "acme", + providerSubscriptionId: "plan_1", + customerId: "cus_1", + productId: "prod_1", + status: "active", + currency: "KES", + unitAmount: 150_000, + quantity: 1, + interval: "month", + intervalCount: 1, + }); + + const canceled = await cancel(ctx, { subscriptionId: sub.id, mode: "immediate" }); + expect(canceled.status).toBe("canceled"); + expect(calls).toEqual([{ action: "cancel", id: "plan_1" }]); + expect((getCol("subscriptions").get(sub.id) as Subscription).status).toBe("canceled"); + + const resumed = await resume(ctx, { subscriptionId: sub.id }); + expect(resumed.status).toBe("active"); + expect(calls).toEqual([ + { action: "cancel", id: "plan_1" }, + { action: "resume", id: "plan_1" }, + ]); + expect((getCol("subscriptions").get(sub.id) as Subscription).status).toBe("active"); + }); + + it("refuses to pause a provider-managed subscription", async () => { + const base = createMockPaymentProvider({ id: "acme" }); + registerPaymentProvider(base); + const { ctx } = makeRouteContext({ + "settings:paymentProvider": "acme", + "settings:acmeSecretKey": "acme-key", + }); + const sub = await upsertProviderSubscription(ctx, { + providerId: "acme", + providerSubscriptionId: "plan_1", + customerId: "cus_1", + productId: "prod_1", + status: "active", + currency: "KES", + unitAmount: 150_000, + quantity: 1, + interval: "month", + intervalCount: 1, + }); + await expect(pause(ctx, { subscriptionId: sub.id })).rejects.toThrow( + /does not support pausing/i, + ); + }); +}); diff --git a/packages/core/test/subscriptions-public.test.ts b/packages/core/test/subscriptions-public.test.ts index 0f85aac..10d0af1 100644 --- a/packages/core/test/subscriptions-public.test.ts +++ b/packages/core/test/subscriptions-public.test.ts @@ -37,22 +37,26 @@ const storedSub: Subscription = { updatedAt: "2026-11-14T00:00:00.000Z", }; -function ctxWithSub(opts: { stripeConfigured?: boolean } = {}): PluginContext { +function ctxWithSub(opts: { stripeConfigured?: boolean; providerId?: string } = {}): PluginContext { const stripeConfigured = opts.stripeConfigured ?? true; + const sub = { + ...storedSub, + ...(opts.providerId ? { providerId: opts.providerId } : {}), + }; return { storage: { subscriptions: { query: async (q: { where?: { stripeSubscriptionId?: string } }) => { if (q.where?.stripeSubscriptionId === STRIPE_SUB) { return { - items: [{ id: storedSub.id, data: storedSub }], + items: [{ id: sub.id, data: sub }], cursor: null, hasMore: false, }; } return { items: [], cursor: null, hasMore: false }; }, - get: async (id: string) => (id === storedSub.id ? storedSub : null), + get: async (id: string) => (id === sub.id ? sub : null), }, }, kv: { @@ -163,6 +167,24 @@ describe("subscription mutation routes", () => { } }); + it("refuses the Stripe portal for a provider-managed subscription", async () => { + const ctx = ctxWithSub({ providerId: "flutterwave" }); + const token = await tokenFor(ctx); + const res = await subscriptionsPublicRoutes["subscriptions/portal"].handler( + { + request: new Request( + "http://localhost/_emdash/api/plugins/dashcommerce/subscriptions/portal", + { method: "POST" }, + ), + input: { token }, + } as RouteContext, + ctx, + ); + expect(res.status).toBe(400); + const body = (await res.json()) as { error?: string }; + expect(body.error).toMatch(/managed by its payment provider/i); + }); + it("cancel without a token is 400", async () => { const res = await subscriptionsPublicRoutes["subscriptions/cancel"].handler( {