Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix(billing): recover orphaned Signed BAA subscriptions
Richie McIlroy25fda577c1b9
diff --git a/apps/web/__tests__/unit/signed-baa-webhook.test.ts b/apps/web/__tests__/unit/signed-baa-webhook.test.tsnew file mode 100644index 000000000..0d8365714--- /dev/null+++ b/apps/web/__tests__/unit/signed-baa-webhook.test.ts@@ -0,0 +1,147 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const mockDbChain = {+ select: vi.fn(),+ from: vi.fn(),+ where: vi.fn(),+ limit: vi.fn(),+ insert: vi.fn(),+ update: vi.fn(),+ set: vi.fn(),+ values: vi.fn(),+};++function resetDbChain() {+ for (const key of Object.keys(mockDbChain)) {+ const fn = mockDbChain[key as keyof typeof mockDbChain];+ fn.mockClear();+ }+ mockDbChain.select.mockReturnValue(mockDbChain);+ mockDbChain.from.mockReturnValue(mockDbChain);+ mockDbChain.where.mockReturnValue(mockDbChain);+ mockDbChain.limit.mockReturnValue(Promise.resolve([]));+ mockDbChain.insert.mockReturnValue(mockDbChain);+ mockDbChain.update.mockReturnValue(mockDbChain);+ mockDbChain.set.mockReturnValue(mockDbChain);+ mockDbChain.values.mockReturnValue(Promise.resolve());+}++vi.mock("@cap/database", () => ({+ db: () => mockDbChain,+}));++vi.mock("@cap/database/helpers", () => ({+ nanoId: vi.fn(() => "test-nano-id"),+}));++vi.mock("@cap/database/emails/config", () => ({+ sendEmail: vi.fn(),+}));++vi.mock("@cap/database/schema", () => ({+ developerCreditTransactions: {+ id: "id",+ accountId: "accountId",+ referenceId: "referenceId",+ referenceType: "referenceType",+ },+ signedBaas: {+ id: "signedBaaId",+ organizationId: "signedBaaOrganizationId",+ stripeSubscriptionId: "signedBaaStripeSubscriptionId",+ status: "signedBaaStatus",+ },+ users: { id: "id", email: "email" },+}));++vi.mock("@cap/env", () => ({+ buildEnv: {},+ serverEnv: () => ({+ STRIPE_WEBHOOK_SECRET: "whsec_test",+ }),+}));++vi.mock("@/lib/developer-credits", () => ({+ addCreditsToAccount: vi.fn(),+}));++vi.mock("@cap/web-domain", () => ({+ Organisation: { OrganisationId: { make: (v: string) => v } },+ User: { UserId: { make: (v: string) => v } },+}));++const mockStripe = {+ webhooks: {+ constructEvent: vi.fn(),+ },+ customers: {+ retrieve: vi.fn(),+ },+ subscriptions: {+ retrieve: vi.fn(),+ list: vi.fn(),+ cancel: vi.fn(),+ },+};++vi.mock("@cap/utils", () => ({+ stripe: () => mockStripe,+}));++vi.mock("drizzle-orm", () => ({+ and: vi.fn((...args: unknown[]) => args),+ eq: vi.fn((a: unknown, b: unknown) => ({ eq: [a, b] })),+ isNull: vi.fn((a: unknown) => ({ isNull: a })),+ or: vi.fn((...args: unknown[]) => args),+}));++vi.mock("@/lib/server-analytics", () => ({+ trackServerEvent: vi.fn().mockResolvedValue(undefined),+}));++function makeWebhookRequest(body = "{}") {+ return new Request("https://cap.test/api/webhooks/stripe", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ "Stripe-Signature": "sig_test",+ },+ body,+ });+}++describe("Stripe webhook — Signed BAA", () => {+ let POST: typeof import("@/app/api/webhooks/stripe/route").POST;++ beforeEach(async () => {+ vi.clearAllMocks();+ resetDbChain();+ const mod = await import("@/app/api/webhooks/stripe/route");+ POST = mod.POST;+ });++ it("attaches an entitled BAA subscription to a row missing the Stripe ID", async () => {+ mockStripe.webhooks.constructEvent.mockReturnValue({+ type: "customer.subscription.updated",+ data: {+ object: {+ id: "sub_baa_1",+ status: "active",+ metadata: {+ type: "signed_baa",+ organizationId: "org-1",+ },+ },+ },+ });++ const res = await POST(makeWebhookRequest());++ expect(res.status).toBe(200);+ expect(mockDbChain.set).toHaveBeenCalledWith({+ status: "active",+ stripeSubscriptionId: "sub_baa_1",+ });+ expect(mockStripe.customers.retrieve).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/__tests__/unit/signed-baa.test.ts b/apps/web/__tests__/unit/signed-baa.test.tsindex 284a3a384..3e45798d5 100644--- a/apps/web/__tests__/unit/signed-baa.test.ts+++ b/apps/web/__tests__/unit/signed-baa.test.ts@@ -1,5 +1,7 @@import { getCurrentUser } from "@cap/database/auth/session";+import { sendEmail } from "@cap/database/emails/config";import { beforeEach, describe, expect, it, vi } from "vitest";+import { generateSignedBaaPdf } from "@/lib/baa/generate-signed-baa-pdf";const mockDb = {select: vi.fn(),@@ -178,3 +180,100 @@ describe("Signed BAA entitlement", () => {expect(mockStripe.subscriptions.create).not.toHaveBeenCalled();});});++const VALID_INPUT = {+ entityName: "Acme Health, Inc.",+ entityType: "Delaware corporation",+ entityAddress: "123 Main St, San Francisco, CA 94105",+ signerName: "Jane Smith",+ signerTitle: "CEO",+ noticesEmail: "[email protected]",+ signatureDataUrl: `data:image/png;base64,${"A".repeat(200)}`,+};++const recoveredSubscription = {+ id: "sub_baa_1",+ status: "active",+ metadata: { type: "signed_baa", organizationId: "org-1" },+};++async function setupPurchaseAttempt() {+ mockOwner({+ stripeCustomerId: "cus_1",+ stripeSubscriptionId: "sub_active",+ stripeSubscriptionStatus: "active",+ });+ mockDb.limit.mockResolvedValueOnce([]);+ vi.mocked(generateSignedBaaPdf).mockResolvedValue(new Uint8Array([1, 2, 3]));+ vi.mocked(sendEmail).mockResolvedValue(undefined as never);+ mockStripe.subscriptions.retrieve.mockResolvedValue({+ id: "sub_active",+ default_payment_method: "pm_1",+ });+}++describe("Signed BAA Stripe recovery", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ resetMockDb();+ });++ it("uses a stable Stripe idempotency key for the record", async () => {+ await setupPurchaseAttempt();+ mockStripe.subscriptions.list.mockResolvedValue({ data: [] });+ mockStripe.subscriptions.create.mockResolvedValue(recoveredSubscription);+ const { purchaseSignedBaa } = await import(+ "@/actions/organization/signed-baa"+ );++ await purchaseSignedBaa("org-1" as never, VALID_INPUT);++ expect(mockStripe.subscriptions.create).toHaveBeenCalledWith(+ expect.objectContaining({+ customer: "cus_1",+ }),+ { idempotencyKey: "signed-baa-baa-record-1" },+ );+ });++ it("activates an existing Stripe subscription after a lost create response", async () => {+ await setupPurchaseAttempt();+ mockStripe.subscriptions.list+ .mockResolvedValueOnce({ data: [] })+ .mockResolvedValueOnce({ data: [recoveredSubscription] });+ mockStripe.subscriptions.create.mockRejectedValueOnce(+ new Error("socket hang up"),+ );+ const { purchaseSignedBaa } = await import(+ "@/actions/organization/signed-baa"+ );++ const result = await purchaseSignedBaa("org-1" as never, VALID_INPUT);++ expect(result.success).toBe(true);+ expect(mockDb.set).toHaveBeenCalledWith(+ expect.objectContaining({+ status: "active",+ stripeSubscriptionId: "sub_baa_1",+ }),+ );+ });++ it("does not claim the customer was not charged when Stripe is ambiguous", async () => {+ await setupPurchaseAttempt();+ mockStripe.subscriptions.list.mockResolvedValue({ data: [] });+ mockStripe.subscriptions.create.mockRejectedValue(+ new Error("socket hang up"),+ );+ const { purchaseSignedBaa } = await import(+ "@/actions/organization/signed-baa"+ );++ await expect(+ purchaseSignedBaa("org-1" as never, VALID_INPUT),+ ).rejects.toThrow("couldn't confirm the Signed BAA subscription");+ expect(mockDb.set).toHaveBeenCalledWith(+ expect.objectContaining({ status: "pending" }),+ );+ });+});diff --git a/apps/web/actions/organization/signed-baa.ts b/apps/web/actions/organization/signed-baa.tsindex 14d77979c..db41264c1 100644--- a/apps/web/actions/organization/signed-baa.ts+++ b/apps/web/actions/organization/signed-baa.ts@@ -209,6 +209,63 @@ async function findExistingBaaSubscription();}+function throwSignedBaaStripeError(error: unknown): never {+ const stripeError = error as { type?: string; message?: string };+ if (stripeError.type === "StripeCardError") {+ throw new Error(+ `Your card was declined: ${stripeError.message ?? "payment failed"}. No subscription was started.`,+ );+ }+ if (error instanceof Error && error.message.includes("payment method")) {+ throw error;+ }+ console.error("Signed BAA: subscription creation failed", error);+ throw new Error(+ "We couldn't confirm the Signed BAA subscription. Please try again or contact support if you were charged.",+ );+}++async function createBaaSubscription({+ customerId,+ organizationId,+ userId,+ recordId,+ proSubscriptionId,+ priceId,+}: {+ customerId: string;+ organizationId: string;+ userId: string;+ recordId: string;+ proSubscriptionId: string | null;+ priceId: string;+}): Promise<Stripe.Subscription> {+ const existing = await findExistingBaaSubscription(+ customerId,+ organizationId,+ );+ if (existing) return existing;++ const { paymentMethod } = await resolvePaymentMethod(+ customerId,+ proSubscriptionId,+ );+ return stripe().subscriptions.create(+ {+ customer: customerId,+ items: [{ price: priceId, quantity: 1 }],+ ...(paymentMethod ? { default_payment_method: paymentMethod } : {}),+ payment_behavior: "error_if_incomplete",+ metadata: {+ type: "signed_baa",+ organizationId,+ userId,+ },+ },+ { idempotencyKey: `signed-baa-${recordId}` },+ );+}+export async function purchaseSignedBaa(organizationId: Organisation.OrganisationId,input: SignedBaaInput,@@ -314,44 +371,34 @@ export async function purchaseSignedBaa(let subscription: Stripe.Subscription | null = null;try {- subscription = await findExistingBaaSubscription(+ subscription = await createBaaSubscription({customerId,organizationId,- );- if (!subscription) {- const { paymentMethod } = await resolvePaymentMethod(+ userId: user.id,+ recordId,+ proSubscriptionId: user.stripeSubscriptionId,+ priceId,+ });+ } catch (error) {+ try {+ subscription = await createBaaSubscription({customerId,- user.stripeSubscriptionId,- );- subscription = await stripe().subscriptions.create(- {- customer: customerId,- items: [{ price: priceId, quantity: 1 }],- ...(paymentMethod ? { default_payment_method: paymentMethod } : {}),- payment_behavior: "error_if_incomplete",- metadata: {- type: "signed_baa",- organizationId,- userId: user.id,- },- },- { idempotencyKey: `signed-baa-${recordId}-${nanoId()}` },- );+ organizationId,+ userId: user.id,+ recordId,+ proSubscriptionId: user.stripeSubscriptionId,+ priceId,+ });+ } catch (retryError) {+ await revertToPending();+ throwSignedBaaStripeError(retryError ?? error);}- } catch (error) {+ }++ if (!subscription) {await revertToPending();- const stripeError = error as { type?: string; message?: string };- if (stripeError.type === "StripeCardError") {- throw new Error(- `Your card was declined: ${stripeError.message ?? "payment failed"}. No subscription was started.`,- );- }- if (error instanceof Error && error.message.includes("payment method")) {- throw error;- }- console.error("Signed BAA: subscription creation failed", error);throw new Error(- "We couldn't start the Signed BAA subscription. You have not been charged. Please try again.",+ "We couldn't confirm the Signed BAA subscription. Please try again or contact support if you were charged.",);}diff --git a/apps/web/app/api/webhooks/stripe/route.ts b/apps/web/app/api/webhooks/stripe/route.tsindex f9b6c0c21..1a7ddf389 100644--- a/apps/web/app/api/webhooks/stripe/route.ts+++ b/apps/web/app/api/webhooks/stripe/route.ts@@ -10,7 +10,7 @@ import {import { serverEnv } from "@cap/env";import { stripe } from "@cap/utils";import { Organisation, User } from "@cap/web-domain";-import { and, eq } from "drizzle-orm";+import { and, eq, isNull, or } from "drizzle-orm";import { NextResponse } from "next/server";import type Stripe from "stripe";import { addCreditsToAccount } from "@/lib/developer-credits";@@ -107,10 +107,24 @@ async function syncSignedBaaStatus(const status = BAA_ENTITLED_STATUSES.has(subscription.status)? "active": "canceled";+ const organizationId = subscription.metadata?.organizationId;await db().update(signedBaas)- .set({ status })- .where(eq(signedBaas.stripeSubscriptionId, subscription.id));+ .set({+ status,+ stripeSubscriptionId: subscription.id,+ })+ .where(+ organizationId+ ? or(+ eq(signedBaas.stripeSubscriptionId, subscription.id),+ and(+ eq(signedBaas.organizationId, organizationId),+ isNull(signedBaas.stripeSubscriptionId),+ ),+ )+ : eq(signedBaas.stripeSubscriptionId, subscription.id),+ );console.log("Signed BAA subscription synced", {subscriptionId: subscription.id,status,