Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: complete prepaid BAA signing

Richie McIlroy264cff2d77e4
diff --git a/apps/web/__tests__/unit/signed-baa-card.test.ts b/apps/web/__tests__/unit/signed-baa-card.test.ts
new file mode 100644
index 000000000..2a71b78f1
--- /dev/null
+++ b/apps/web/__tests__/unit/signed-baa-card.test.ts
@@ -0,0 +1,553 @@
+// @vitest-environment jsdom
+
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { act, type ComponentProps, createElement, type ReactNode } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from "vitest";
+import {
+ confirmSignedBaaPayment,
+ getSignedBaaStatus,
+ purchaseSignedBaa,
+ type SignedBaaStatus,
+ signPaidBaa,
+} from "@/actions/organization/signed-baa";
+import { SignedBaaCard } from "@/app/(org)/dashboard/settings/organization/components/SignedBaaCard";
+
+const mocks = vi.hoisted(() => ({
+ organizationId: "org-1",
+ searchParams: new URLSearchParams(),
+ refresh: vi.fn(),
+ replace: vi.fn(),
+ success: vi.fn(),
+ error: vi.fn(),
+}));
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ refresh: mocks.refresh, replace: mocks.replace }),
+ useSearchParams: () => mocks.searchParams,
+}));
+
+vi.mock("@/app/(org)/dashboard/Contexts", () => ({
+ useDashboardContext: () => ({
+ activeOrganization: { organization: { id: mocks.organizationId } },
+ user: { name: "Jane", lastName: "Smith", email: "[email protected]" },
+ }),
+}));
+
+vi.mock("@/actions/organization/signed-baa", () => ({
+ getSignedBaaStatus: vi.fn(),
+ confirmSignedBaaPayment: vi.fn(),
+ purchaseSignedBaa: vi.fn(),
+ signPaidBaa: vi.fn(),
+}));
+
+vi.mock("sonner", () => ({
+ toast: { success: mocks.success, error: mocks.error },
+}));
+
+vi.mock("@fortawesome/react-fontawesome", () => ({
+ FontAwesomeIcon: () => null,
+}));
+
+vi.mock("@cap/ui", async () => {
+ const { createElement } = await import("react");
+ const container = ({ children }: { children?: ReactNode }) =>
+ createElement("div", null, children);
+ return {
+ Card: container,
+ CardDescription: container,
+ CardHeader: container,
+ CardTitle: container,
+ DialogContent: container,
+ DialogHeader: container,
+ DialogTitle: container,
+ Dialog: ({ open, children }: { open: boolean; children?: ReactNode }) =>
+ open ? createElement("div", { role: "dialog" }, children) : null,
+ Button: ({ children, disabled, onClick, type }: ComponentProps<"button">) =>
+ createElement("button", { disabled, onClick, type }, children),
+ Input: (props: ComponentProps<"input">) => createElement("input", props),
+ };
+});
+
+vi.mock(
+ "@/app/(org)/dashboard/settings/organization/components/SignaturePad",
+ async () => {
+ const { createElement } = await import("react");
+ return {
+ SignaturePad: ({
+ onChange,
+ disabled,
+ }: {
+ onChange: (signature: string | null) => void;
+ disabled: boolean;
+ }) =>
+ createElement(
+ "button",
+ {
+ type: "button",
+ disabled,
+ onClick: () => onChange("data:image/png;base64,fresh-signature"),
+ },
+ "Draw signature",
+ ),
+ };
+ },
+);
+
+const details = {
+ entityName: "Acme Health LLC",
+ entityType: "LLC",
+ entityAddress: "123 Main Street",
+ signerName: "Jane Smith",
+ signerTitle: "Director",
+ noticesEmail: "[email protected]",
+};
+
+const createStatus = (
+ overrides: Partial<SignedBaaStatus> = {},
+): SignedBaaStatus => ({
+ status: "none",
+ signedAt: null,
+ entityName: null,
+ emailSentAt: null,
+ canPurchase: true,
+ details: null,
+ ...overrides,
+});
+
+const paidStatus = createStatus({
+ status: "paid",
+ details,
+ canPurchase: false,
+});
+const activeStatus = createStatus({
+ status: "active",
+ signedAt: "2026-08-26T12:00:00.000Z",
+ entityName: details.entityName,
+});
+
+const actEnvironment = globalThis as typeof globalThis & {
+ IS_REACT_ACT_ENVIRONMENT?: boolean;
+};
+
+let root: Root;
+let container: HTMLDivElement;
+let queryClient: QueryClient;
+
+const deferred = <T>() => {
+ let resolve: (value: T) => void;
+ const promise = new Promise<T>((resolvePromise) => {
+ resolve = resolvePromise;
+ });
+ return { promise, resolve: (value: T) => resolve(value) };
+};
+
+const button = (text: string) =>
+ Array.from(container.querySelectorAll("button")).find(
+ (element) => element.textContent === text,
+ );
+
+const click = async (text: string) => {
+ const target = button(text);
+ expect(target).toBeDefined();
+ await act(async () => target?.click());
+};
+
+const render = async () => {
+ await act(async () => {
+ root.render(
+ createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ createElement(SignedBaaCard),
+ ),
+ );
+ });
+};
+
+const waitFor = async (assertion: () => void) => {
+ await vi.waitFor(async () => {
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+ assertion();
+ });
+};
+
+const redirect = () => {
+ window.history.replaceState(
+ window.history.state,
+ "",
+ "/dashboard/settings/organization/billing?baaRedirect=true&session_id=cs_paid",
+ );
+ mocks.searchParams = new URLSearchParams(window.location.search);
+};
+
+describe("Signed BAA payment and signing", () => {
+ beforeAll(() => {
+ actEnvironment.IS_REACT_ACT_ENVIRONMENT = true;
+ });
+
+ beforeEach(() => {
+ mocks.organizationId = "org-1";
+ mocks.searchParams = new URLSearchParams();
+ window.history.replaceState(
+ window.history.state,
+ "",
+ "/dashboard/settings/organization/billing",
+ );
+ mocks.replace.mockImplementation((href: string) => {
+ window.history.replaceState(window.history.state, "", href);
+ mocks.searchParams = new URLSearchParams(window.location.search);
+ });
+ vi.mocked(getSignedBaaStatus).mockReset().mockResolvedValue(createStatus());
+ vi.mocked(confirmSignedBaaPayment)
+ .mockReset()
+ .mockResolvedValue(paidStatus);
+ vi.mocked(purchaseSignedBaa)
+ .mockReset()
+ .mockResolvedValue({ success: true, emailSent: true });
+ vi.mocked(signPaidBaa)
+ .mockReset()
+ .mockResolvedValue({ success: true, emailSent: true });
+ queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+ });
+
+ afterEach(async () => {
+ await act(async () => root.unmount());
+ queryClient.clear();
+ document.body.replaceChildren();
+ });
+
+ afterAll(() => {
+ delete actEnvironment.IS_REACT_ACT_ENVIRONMENT;
+ });
+
+ it("verifies the checkout before showing paid and opening a fresh signature form", async () => {
+ redirect();
+ const confirmation = deferred<SignedBaaStatus>();
+ vi.mocked(confirmSignedBaaPayment).mockReturnValue(confirmation.promise);
+ await render();
+
+ expect(container.textContent).toContain("Confirming your BAA payment");
+ expect(container.querySelector('[role="dialog"]')).toBeNull();
+ expect(button("Get Signed BAA")).toBeUndefined();
+ expect(confirmSignedBaaPayment).toHaveBeenCalledWith("org-1", "cs_paid");
+
+ vi.mocked(getSignedBaaStatus).mockResolvedValue(paidStatus);
+ await act(async () => confirmation.resolve(paidStatus));
+ await waitFor(() => {
+ expect(container.textContent).toContain("Paid — awaiting signature");
+ expect(container.querySelector('[role="dialog"]')).not.toBeNull();
+ });
+
+ expect(queryClient.getQueryData(["signed-baa", "org-1"])).toEqual(
+ paidStatus,
+ );
+ expect(getSignedBaaStatus).toHaveBeenCalledTimes(2);
+ expect(container.querySelector("input")?.value).toBe(details.entityName);
+ expect(button("Sign BAA")?.disabled).toBe(true);
+ expect(container.textContent).toContain("no additional charge");
+ expect(container.textContent).not.toContain("authorize Cap to charge");
+ expect(button("Sign & pay $99/mo")).toBeUndefined();
+
+ await click("Cancel");
+ await act(async () => {
+ await queryClient.invalidateQueries({
+ queryKey: ["signed-baa", "org-1"],
+ });
+ });
+ await render();
+ expect(container.querySelector('[role="dialog"]')).toBeNull();
+ });
+
+ it("consumes a verified redirect without losing other URL state or blocking the next organization", async () => {
+ window.history.replaceState(
+ window.history.state,
+ "",
+ "/dashboard/settings/organization/billing?tab=invoices&baaRedirect=true&session_id=cs_paid&tag=one&tag=two#signed-baa",
+ );
+ mocks.searchParams = new URLSearchParams(window.location.search);
+ vi.mocked(getSignedBaaStatus).mockResolvedValue(paidStatus);
+ await render();
+ await waitFor(() => expect(button("Sign BAA")).toBeDefined());
+
+ expect(mocks.replace).toHaveBeenCalledOnce();
+ expect(mocks.replace).toHaveBeenCalledWith(
+ "/dashboard/settings/organization/billing?tab=invoices&tag=one&tag=two#signed-baa",
+ { scroll: false },
+ );
+ expect(window.location.search).not.toContain("session_id");
+ expect(window.location.search).not.toContain("baaRedirect");
+ await click("Cancel");
+ mocks.organizationId = "org-2";
+ vi.mocked(getSignedBaaStatus).mockResolvedValue(createStatus());
+ await render();
+ await waitFor(() => expect(button("Get Signed BAA")?.disabled).toBe(false));
+
+ expect(confirmSignedBaaPayment).toHaveBeenCalledOnce();
+ expect(container.querySelector('[role="alert"]')).toBeNull();
+ expect(container.querySelector('[role="dialog"]')).toBeNull();
+ });
+
+ it("keeps failed confirmation blocked and lets the customer retry without paying", async () => {
+ redirect();
+ vi.mocked(getSignedBaaStatus).mockResolvedValue(paidStatus);
+ vi.mocked(confirmSignedBaaPayment).mockRejectedValueOnce(
+ new Error("The payment is still pending."),
+ );
+ await render();
+ await waitFor(() => {
+ expect(container.textContent).toContain("The payment is still pending.");
+ });
+
+ expect(container.textContent).toContain("Do not pay again");
+ expect(button("Get Signed BAA")).toBeUndefined();
+ expect(button("Complete and sign BAA")).toBeUndefined();
+ expect(container.querySelector('[role="dialog"]')).toBeNull();
+ expect(mocks.replace).not.toHaveBeenCalled();
+ vi.mocked(getSignedBaaStatus).mockResolvedValue(paidStatus);
+ await click("Retry payment confirmation");
+ await waitFor(() => expect(button("Sign BAA")).toBeDefined());
+ expect(confirmSignedBaaPayment).toHaveBeenCalledTimes(2);
+ expect(purchaseSignedBaa).not.toHaveBeenCalled();
+ });
+
+ it("does not overwrite verified payment with an earlier in-flight status lookup", async () => {
+ redirect();
+ const oldStatus = deferred<SignedBaaStatus>();
+ vi.mocked(getSignedBaaStatus)
+ .mockReturnValueOnce(oldStatus.promise)
+ .mockResolvedValue(paidStatus);
+ await render();
+ await waitFor(() => expect(button("Sign BAA")).toBeDefined());
+ await act(async () => oldStatus.resolve(createStatus()));
+
+ expect(queryClient.getQueryData(["signed-baa", "org-1"])).toEqual(
+ paidStatus,
+ );
+ expect(button("Get Signed BAA")).toBeUndefined();
+ expect(button("Sign BAA")).toBeDefined();
+ });
+
+ it("does not treat an untrusted redirect flag without a session as payment", async () => {
+ mocks.searchParams = new URLSearchParams("baaRedirect=true");
+ await render();
+
+ expect(container.textContent).toContain("confirmation link is incomplete");
+ expect(container.textContent).not.toContain("Paid — awaiting signature");
+ expect(container.querySelector('[role="dialog"]')).toBeNull();
+ expect(button("Get Signed BAA")).toBeUndefined();
+ expect(confirmSignedBaaPayment).not.toHaveBeenCalled();
+ expect(purchaseSignedBaa).not.toHaveBeenCalled();
+ });
+
+ it("does not open the purchase form when verification returns an unpaid status", async () => {
+ redirect();
+ vi.mocked(confirmSignedBaaPayment).mockResolvedValue(createStatus());
+ await render();
+ await waitFor(() => {
+ expect(container.textContent).toContain("payment could not be confirmed");
+ });
+
+ expect(container.querySelector('[role="dialog"]')).toBeNull();
+ expect(button("Get Signed BAA")).toBeUndefined();
+ expect(purchaseSignedBaa).not.toHaveBeenCalled();
+ });
+
+ it("signs a paid BAA with a fresh signature without invoking purchase", async () => {
+ vi.mocked(getSignedBaaStatus).mockResolvedValue(paidStatus);
+ const signing = deferred<{
+ success: true;
+ emailSent: boolean;
+ }>();
+ vi.mocked(signPaidBaa).mockReturnValue(signing.promise);
+ await render();
+ await waitFor(() => expect(button("Complete and sign BAA")).toBeDefined());
+ expect(container.querySelector('[role="dialog"]')).toBeNull();
+ await click("Complete and sign BAA");
+ expect(button("Sign BAA")?.disabled).toBe(true);
+ await click("Draw signature");
+ expect(button("Sign BAA")?.disabled).toBe(false);
+ await click("Sign BAA");
+ await waitFor(() => expect(button("Processing...")?.disabled).toBe(true));
+
+ expect(signPaidBaa).toHaveBeenCalledWith("org-1", {
+ ...details,
+ signatureDataUrl: "data:image/png;base64,fresh-signature",
+ });
+ expect(purchaseSignedBaa).not.toHaveBeenCalled();
+ expect(button("Complete and sign BAA")?.disabled).toBe(true);
+ expect(button("Draw signature")?.disabled).toBe(true);
+
+ vi.mocked(getSignedBaaStatus).mockResolvedValue(activeStatus);
+ await act(async () => signing.resolve({ success: true, emailSent: true }));
+ await waitFor(() => expect(button("Download signed copy")).toBeDefined());
+ expect(container.querySelector('[role="dialog"]')).toBeNull();
+ expect(mocks.refresh).toHaveBeenCalledOnce();
+ });
+
+ it("preserves ordinary purchase and its payment authorization", async () => {
+ mocks.searchParams = new URLSearchParams("session_id=cs_other_product");
+ vi.mocked(getSignedBaaStatus).mockResolvedValue(createStatus({ details }));
+ await render();
+ await waitFor(() => expect(button("Get Signed BAA")?.disabled).toBe(false));
+ expect(container.querySelector('[role="dialog"]')).toBeNull();
+ await click("Get Signed BAA");
+ expect(container.textContent).toContain("authorize Cap to charge");
+ await click("Draw signature");
+ await click("Sign & pay $99/mo");
+ await waitFor(() => expect(purchaseSignedBaa).toHaveBeenCalledOnce());
+ expect(purchaseSignedBaa).toHaveBeenCalledWith("org-1", {
+ ...details,
+ signatureDataUrl: "data:image/png;base64,fresh-signature",
+ });
+ expect(confirmSignedBaaPayment).not.toHaveBeenCalled();
+ expect(signPaidBaa).not.toHaveBeenCalled();
+ });
+
+ it("refreshes payment status after a failed purchase instead of offering another charge", async () => {
+ vi.mocked(getSignedBaaStatus).mockResolvedValue(createStatus({ details }));
+ vi.mocked(purchaseSignedBaa).mockRejectedValue(
+ new Error(
+ "The payment succeeded but the agreement could not be completed.",
+ ),
+ );
+ await render();
+ await waitFor(() => expect(button("Get Signed BAA")?.disabled).toBe(false));
+ await click("Get Signed BAA");
+ await click("Draw signature");
+ vi.mocked(getSignedBaaStatus).mockResolvedValue(paidStatus);
+ await click("Sign & pay $99/mo");
+ await waitFor(() => expect(button("Sign BAA")).toBeDefined());
+
+ expect(container.textContent).toContain("Paid — awaiting signature");
+ expect(button("Sign & pay $99/mo")).toBeUndefined();
+ expect(button("Sign BAA")?.disabled).toBe(true);
+ expect(mocks.error).toHaveBeenCalledWith(
+ "The payment succeeded but the agreement could not be completed.",
+ );
+ expect(purchaseSignedBaa).toHaveBeenCalledOnce();
+ });
+
+ it("preserves the active agreement download without opening another signing form", async () => {
+ redirect();
+ vi.mocked(getSignedBaaStatus).mockResolvedValue(activeStatus);
+ vi.mocked(confirmSignedBaaPayment).mockResolvedValue(activeStatus);
+ await render();
+ await waitFor(() => expect(button("Download signed copy")).toBeDefined());
+
+ expect(container.textContent).toContain("Active");
+ expect(container.textContent).toContain(details.entityName);
+ expect(container.querySelector('[role="dialog"]')).toBeNull();
+ expect(button("Get Signed BAA")).toBeUndefined();
+ expect(button("Complete and sign BAA")).toBeUndefined();
+ expect(mocks.replace).toHaveBeenCalledWith(
+ "/dashboard/settings/organization/billing",
+ { scroll: false },
+ );
+ });
+
+ it("keeps a processing redirect until the agreement is ready for its signature", async () => {
+ redirect();
+ const processing = createStatus({ status: "processing" });
+ vi.mocked(getSignedBaaStatus).mockResolvedValue(processing);
+ vi.mocked(confirmSignedBaaPayment).mockResolvedValue(processing);
+ await render();
+ await waitFor(() => {
+ expect(container.textContent).toContain("Your BAA is processing");
+ });
+ expect(mocks.replace).not.toHaveBeenCalled();
+ expect(window.location.search).toContain("session_id=cs_paid");
+
+ await act(async () => {
+ queryClient.setQueryData(["signed-baa", "org-1"], paidStatus);
+ });
+ await waitFor(() => expect(button("Sign BAA")).toBeDefined());
+ expect(mocks.replace).toHaveBeenCalledWith(
+ "/dashboard/settings/organization/billing",
+ { scroll: false },
+ );
+ expect(window.location.search).toBe("");
+ });
+
+ it("blocks duplicate actions while the server is processing a BAA", async () => {
+ vi.mocked(getSignedBaaStatus).mockResolvedValue(
+ createStatus({ status: "processing" }),
+ );
+ await render();
+ await waitFor(() => {
+ expect(container.textContent).toContain("Your BAA is processing");
+ });
+ expect(button("Get Signed BAA")).toBeUndefined();
+ expect(button("Complete and sign BAA")).toBeUndefined();
+ });
+
+ it("never applies an old organization's confirmation to the newly selected organization", async () => {
+ redirect();
+ const previousConfirmation = deferred<SignedBaaStatus>();
+ vi.mocked(confirmSignedBaaPayment)
+ .mockReturnValueOnce(previousConfirmation.promise)
+ .mockRejectedValueOnce(
+ new Error("Payment belongs to another organization."),
+ );
+ await render();
+ mocks.organizationId = "org-2";
+ await render();
+ await waitFor(() => {
+ expect(container.textContent).toContain(
+ "Payment belongs to another organization.",
+ );
+ });
+
+ await act(async () => previousConfirmation.resolve(paidStatus));
+ await waitFor(() => {
+ expect(queryClient.getQueryData(["signed-baa", "org-1"])).toEqual(
+ paidStatus,
+ );
+ });
+ expect(queryClient.getQueryData(["signed-baa", "org-2"])).toEqual(
+ createStatus(),
+ );
+ expect(container.textContent).not.toContain("Paid — awaiting signature");
+ expect(container.querySelector('[role="dialog"]')).toBeNull();
+ expect(confirmSignedBaaPayment).toHaveBeenNthCalledWith(
+ 2,
+ "org-2",
+ "cs_paid",
+ );
+ });
+
+ it("clears company details and the signature when the organization changes", async () => {
+ vi.mocked(getSignedBaaStatus).mockResolvedValue(paidStatus);
+ await render();
+ await waitFor(() => expect(button("Complete and sign BAA")).toBeDefined());
+ await click("Complete and sign BAA");
+ await click("Draw signature");
+ expect(button("Sign BAA")?.disabled).toBe(false);
+
+ mocks.organizationId = "org-2";
+ vi.mocked(getSignedBaaStatus).mockResolvedValue(createStatus());
+ await render();
+ await waitFor(() => expect(button("Get Signed BAA")?.disabled).toBe(false));
+ expect(container.querySelector('[role="dialog"]')).toBeNull();
+ await click("Get Signed BAA");
+ expect(container.querySelector("input")?.value).toBe("");
+ expect(button("Sign & pay $99/mo")?.disabled).toBe(true);
+ expect(purchaseSignedBaa).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/__tests__/unit/signed-baa-webhook.test.ts b/apps/web/__tests__/unit/signed-baa-webhook.test.ts
index 3d4337823..1ffbcee88 100644
--- a/apps/web/__tests__/unit/signed-baa-webhook.test.ts
+++ b/apps/web/__tests__/unit/signed-baa-webhook.test.ts
@@ -1,8 +1,11 @@
+import { sendEmail } from "@cap/database/emails/config";
+import { signedBaas, users } from "@cap/database/schema";
import { beforeEach, describe, expect, it, vi } from "vitest";
const mockDbChain = {
select: vi.fn(),
from: vi.fn(),
+ innerJoin: vi.fn(),
where: vi.fn(),
limit: vi.fn(),
insert: vi.fn(),
@@ -18,6 +21,7 @@ function resetDbChain() {
}
mockDbChain.select.mockReturnValue(mockDbChain);
mockDbChain.from.mockReturnValue(mockDbChain);
+ mockDbChain.innerJoin.mockReturnValue(mockDbChain);
mockDbChain.where.mockReturnValue(mockDbChain);
mockDbChain.limit.mockReturnValue(Promise.resolve([]));
mockDbChain.insert.mockReturnValue(mockDbChain);
@@ -50,8 +54,17 @@ vi.mock("@cap/database/schema", () => ({
organizationId: "signedBaaOrganizationId",
stripeSubscriptionId: "signedBaaStripeSubscriptionId",
status: "signedBaaStatus",
+ userId: "signedBaaUserId",
+ signedAt: "signedBaaSignedAt",
+ updatedAt: "signedBaaUpdatedAt",
},
- users: { id: "id", email: "email" },
+ users: {
+ id: "id",
+ email: "email",
+ stripeCustomerId: "stripeCustomerId",
+ stripeSubscriptionId: "stripeSubscriptionId",
+ },
+ organizations: { id: "organizationId", ownerId: "ownerId" },
}));
vi.mock("@cap/env", () => ({
@@ -86,12 +99,21 @@ const mockStripe = {
vi.mock("@cap/utils", () => ({
stripe: () => mockStripe,
+ STRIPE_SIGNED_BAA_PRICE_IDS: {
+ production: "price_baa",
+ development: "price_baa_test",
+ },
}));
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 })),
+ ne: vi.fn((a: unknown, b: unknown) => ({ ne: [a, b] })),
+ sql: (parts: TemplateStringsArray, ...values: unknown[]) => ({
+ parts: [...parts],
+ values,
+ }),
or: vi.fn((...args: unknown[]) => args),
}));
@@ -112,6 +134,40 @@ function makeWebhookRequest(body = "{}") {
describe("Stripe webhook — Signed BAA", () => {
let POST: typeof import("@/app/api/webhooks/stripe/route").POST;
+ const directOwner = {
+ stripeCustomerId: "cus_pro",
+ stripeSubscriptionId: "sub_pro",
+ };
+ const directProSubscription = {
+ id: "sub_pro",
+ customer: "cus_pro",
+ status: "active",
+ metadata: {},
+ items: { data: [{ price: { id: "price_pro" } }] },
+ };
+
+ function mockDirectBaaRecovery(
+ subscription: Record<string, unknown>,
+ proStatus = "active",
+ ) {
+ mockStripe.subscriptions.retrieve.mockImplementation(async (id: string) =>
+ id === "sub_pro"
+ ? { ...directProSubscription, status: proStatus }
+ : subscription,
+ );
+ mockDbChain.limit
+ .mockResolvedValueOnce([
+ {
+ id: "baa-1",
+ userId: "user-1",
+ organizationId: "org-1",
+ status: "processing",
+ stripeSubscriptionId: subscription.id,
+ signedAt: null,
+ },
+ ])
+ .mockResolvedValueOnce([directOwner]);
+ }
beforeEach(async () => {
vi.clearAllMocks();
@@ -121,6 +177,13 @@ describe("Stripe webhook — Signed BAA", () => {
});
it("attaches an entitled BAA subscription to a row missing the Stripe ID", async () => {
+ const subscription = {
+ id: "sub_baa_1",
+ status: "active",
+ metadata: { type: "signed_baa", organizationId: "org-1" },
+ latest_invoice: { status: "paid" },
+ };
+ mockDirectBaaRecovery(subscription);
mockStripe.webhooks.constructEvent.mockReturnValue({
type: "customer.subscription.updated",
data: {
@@ -139,13 +202,27 @@ describe("Stripe webhook — Signed BAA", () => {
expect(res.status).toBe(200);
expect(mockDbChain.set).toHaveBeenCalledWith({
- status: "active",
stripeSubscriptionId: "sub_baa_1",
+ updatedAt: expect.any(Object),
+ });
+ expect(mockDbChain.set).toHaveBeenCalledWith({
+ status: expect.objectContaining({
+ values: expect.arrayContaining(["paid"]),
+ }),
+ stripeSubscriptionId: "sub_baa_1",
+ updatedAt: expect.any(Object),
});
expect(mockStripe.customers.retrieve).not.toHaveBeenCalled();
});
it("associates the BAA subscription from its creation event", async () => {
+ const subscription = {
+ id: "sub_baa_new",
+ status: "active",
+ metadata: { type: "signed_baa", organizationId: "org-1" },
+ latest_invoice: { status: "paid" },
+ };
+ mockDirectBaaRecovery(subscription);
mockStripe.webhooks.constructEvent.mockReturnValue({
type: "customer.subscription.created",
data: {
@@ -164,12 +241,78 @@ describe("Stripe webhook — Signed BAA", () => {
expect(res.status).toBe(200);
expect(mockDbChain.set).toHaveBeenCalledWith({
- status: "active",
stripeSubscriptionId: "sub_baa_new",
+ updatedAt: expect.any(Object),
+ });
+ expect(mockDbChain.set).toHaveBeenCalledWith({
+ status: expect.objectContaining({
+ values: expect.arrayContaining(["paid"]),
+ }),
+ stripeSubscriptionId: "sub_baa_new",
+ updatedAt: expect.any(Object),
});
expect(mockStripe.customers.retrieve).not.toHaveBeenCalled();
});
+ it("cancels a recovered BAA when Pro ended before its creation event", async () => {
+ const subscription = {
+ id: "sub_baa_lost_response",
+ status: "active",
+ metadata: {
+ type: "signed_baa",
+ organizationId: "org-1",
+ userId: "user-1",
+ },
+ latest_invoice: { status: "paid" },
+ };
+ mockDirectBaaRecovery(subscription, "canceled");
+ mockStripe.webhooks.constructEvent.mockReturnValue({
+ type: "customer.subscription.created",
+ data: { object: subscription },
+ });
+
+ const res = await POST(makeWebhookRequest());
+
+ expect(res.status).toBe(200);
+ expect(mockStripe.subscriptions.cancel).toHaveBeenCalledExactlyOnceWith(
+ "sub_baa_lost_response",
+ );
+ expect(mockDbChain.set).toHaveBeenCalledWith({ status: "canceled" });
+ expect(mockDbChain.set).toHaveBeenCalledTimes(2);
+ });
+
+ it("retries recovered BAA association when its owner is missing", async () => {
+ const subscription = {
+ id: "sub_baa_missing_owner",
+ status: "active",
+ metadata: { type: "signed_baa", organizationId: "org-1" },
+ latest_invoice: { status: "paid" },
+ };
+ mockStripe.subscriptions.retrieve.mockResolvedValue(subscription);
+ mockDbChain.limit
+ .mockResolvedValueOnce([
+ {
+ id: "baa-1",
+ userId: "missing-user",
+ organizationId: "org-1",
+ status: "processing",
+ stripeSubscriptionId: subscription.id,
+ signedAt: null,
+ },
+ ])
+ .mockResolvedValueOnce([]);
+ mockStripe.webhooks.constructEvent.mockReturnValue({
+ type: "customer.subscription.created",
+ data: { object: subscription },
+ });
+
+ const res = await POST(makeWebhookRequest());
+
+ expect(res.status).toBe(400);
+ expect(mockDbChain.set).toHaveBeenCalledTimes(1);
+ expect(mockStripe.subscriptions.cancel).not.toHaveBeenCalled();
+ });
+
it("cancels Signed BAA when Pro becomes unpaid", async () => {
mockStripe.webhooks.constructEvent.mockReturnValue({
type: "customer.subscription.updated",
@@ -385,3 +528,276 @@ describe("Stripe webhook — Signed BAA", () => {
expect(res.status).toBe(400);
});
});
+
+describe("Signed BAA Payment Link webhooks", () => {
+ let POST: typeof import("@/app/api/webhooks/stripe/route").POST;
+ const subscription = {
+ id: "sub_link_baa",
+ customer: "cus_link",
+ status: "active",
+ metadata: {},
+ items: { data: [{ price: { id: "price_baa" }, quantity: 1 }] },
+ latest_invoice: { status: "paid" },
+ };
+ const session = {
+ id: "cs_link_baa",
+ mode: "subscription",
+ status: "complete",
+ payment_status: "paid",
+ customer: "cus_link",
+ customer_details: { email: "[email protected]" },
+ subscription: "sub_link_baa",
+ metadata: {},
+ };
+ const owner = {
+ id: "user-1",
+ email: "[email protected]",
+ stripeCustomerId: "cus_pro",
+ stripeSubscriptionId: "sub_pro",
+ };
+ const proSubscription = {
+ id: "sub_pro",
+ customer: "cus_pro",
+ status: "active",
+ metadata: {},
+ items: { data: [{ price: { id: "price_pro" }, quantity: 1 }] },
+ };
+ const pending = {
+ id: "baa-1",
+ userId: "user-1",
+ organizationId: "org-1",
+ status: "pending",
+ stripeSubscriptionId: null,
+ signedAt: null,
+ };
+ const paid = {
+ ...pending,
+ status: "paid",
+ stripeSubscriptionId: "sub_link_baa",
+ };
+
+ beforeEach(async () => {
+ vi.clearAllMocks();
+ resetDbChain();
+ mockStripe.subscriptions.retrieve
+ .mockReset()
+ .mockImplementation(async (id: string) =>
+ id === "sub_pro" ? proSubscription : subscription,
+ );
+ mockStripe.subscriptions.cancel
+ .mockReset()
+ .mockResolvedValue({ id: "sub_link_baa", status: "canceled" });
+ POST = (await import("@/app/api/webhooks/stripe/route")).POST;
+ });
+
+ it.each([
+ "checkout.session.completed",
+ "checkout.session.async_payment_succeeded",
+ ])("attaches %s without overwriting Pro billing", async (eventType) => {
+ mockStripe.webhooks.constructEvent.mockReturnValue({
+ type: eventType,
+ data: { object: session },
+ });
+ mockDbChain.limit
+ .mockResolvedValueOnce([owner])
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([pending])
+ .mockResolvedValueOnce([{ ownerId: owner.id }])
+ .mockResolvedValueOnce([{ ...paid, status: "pending" }])
+ .mockResolvedValueOnce([paid]);
+ expect((await POST(makeWebhookRequest())).status).toBe(200);
+ expect(mockDbChain.update).toHaveBeenCalledWith(signedBaas);
+ expect(mockDbChain.set).toHaveBeenCalledWith({
+ stripeSubscriptionId: "sub_link_baa",
+ });
+ expect(mockDbChain.set).toHaveBeenCalledWith({ status: "paid" });
+ expect(mockDbChain.update).not.toHaveBeenCalledWith(users);
+ expect(mockStripe.customers.retrieve).not.toHaveBeenCalled();
+ expect(sendEmail).not.toHaveBeenCalled();
+ });
+
+ it("acknowledges an unpaid BAA checkout without granting payment or Pro", async () => {
+ mockStripe.webhooks.constructEvent.mockReturnValue({
+ type: "checkout.session.completed",
+ data: { object: { ...session, payment_status: "unpaid" } },
+ });
+ expect((await POST(makeWebhookRequest())).status).toBe(200);
+ expect(mockDbChain.update).not.toHaveBeenCalled();
+ });
+
+ it.each(["canceled", "unpaid"])(
+ "cancels delayed paid checkout when Pro is already %s",
+ async (status) => {
+ mockStripe.webhooks.constructEvent.mockReturnValue({
+ type: "checkout.session.completed",
+ data: { object: session },
+ });
+ mockStripe.subscriptions.retrieve.mockImplementation(
+ async (id: string) =>
+ id === "sub_pro" ? { ...proSubscription, status } : subscription,
+ );
+ mockDbChain.limit
+ .mockResolvedValueOnce([owner])
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([pending])
+ .mockResolvedValueOnce([{ ownerId: owner.id }])
+ .mockResolvedValueOnce([{ ...paid, status: "pending" }]);
+ expect((await POST(makeWebhookRequest())).status).toBe(200);
+ expect(mockStripe.subscriptions.cancel).toHaveBeenCalledExactlyOnceWith(
+ "sub_link_baa",
+ );
+ expect(mockDbChain.set).toHaveBeenCalledWith({ status: "canceled" });
+ expect(mockDbChain.set).not.toHaveBeenCalledWith({ status: "paid" });
+ expect(mockDbChain.update).not.toHaveBeenCalledWith(users);
+ },
+ );
+
+ it("is idempotent after the same subscription has already been attached", async () => {
+ mockStripe.webhooks.constructEvent.mockReturnValue({
+ type: "checkout.session.completed",
+ data: { object: session },
+ });
+ mockDbChain.limit
+ .mockResolvedValueOnce([owner])
+ .mockResolvedValueOnce([paid])
+ .mockResolvedValueOnce([{ ownerId: owner.id }]);
+ expect((await POST(makeWebhookRequest())).status).toBe(200);
+ expect(mockDbChain.update).not.toHaveBeenCalled();
+ });
+
+ it("cancels a second checkout while preserving the existing paid BAA and Pro", async () => {
+ const previous = { ...paid, stripeSubscriptionId: "sub_existing" };
+ mockStripe.webhooks.constructEvent.mockReturnValue({
+ type: "checkout.session.completed",
+ data: { object: session },
+ });
+ mockDbChain.limit
+ .mockResolvedValueOnce([owner])
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([previous])
+ .mockResolvedValueOnce([{ ownerId: owner.id }]);
+ mockStripe.subscriptions.retrieve.mockImplementation(
+ async (id: string) => ({ ...subscription, id }),
+ );
+ expect((await POST(makeWebhookRequest())).status).toBe(200);
+ expect(mockStripe.subscriptions.cancel).toHaveBeenCalledExactlyOnceWith(
+ "sub_link_baa",
+ );
+ expect(mockDbChain.update).not.toHaveBeenCalled();
+ });
+
+ it("recognizes price-only BAA subscription updates before Pro handling", async () => {
+ mockStripe.webhooks.constructEvent.mockReturnValue({
+ type: "customer.subscription.updated",
+ data: { object: subscription },
+ });
+ expect((await POST(makeWebhookRequest())).status).toBe(200);
+ expect(mockDbChain.update).toHaveBeenCalledWith(signedBaas);
+ expect(mockDbChain.update).not.toHaveBeenCalledWith(users);
+ expect(mockStripe.customers.retrieve).not.toHaveBeenCalled();
+ });
+
+ it("uses current cancellation state instead of a stale active event", async () => {
+ mockStripe.webhooks.constructEvent.mockReturnValue({
+ type: "customer.subscription.updated",
+ data: {
+ object: {
+ ...subscription,
+ metadata: { type: "signed_baa", organizationId: "org-1" },
+ },
+ },
+ });
+ mockStripe.subscriptions.retrieve.mockResolvedValue({
+ ...subscription,
+ status: "canceled",
+ metadata: { type: "signed_baa", organizationId: "org-1" },
+ });
+ expect((await POST(makeWebhookRequest())).status).toBe(200);
+ expect(mockDbChain.set).toHaveBeenCalledWith(
+ expect.objectContaining({ status: "canceled" }),
+ );
+ expect(mockDbChain.where).toHaveBeenCalledWith([
+ { eq: ["signedBaaStripeSubscriptionId", "sub_link_baa"] },
+ ]);
+ });
+
+ it("does not send Pro payment failure emails for a price-only BAA invoice", async () => {
+ mockStripe.webhooks.constructEvent.mockReturnValue({
+ type: "invoice.payment_failed",
+ data: {
+ object: {
+ id: "in_baa",
+ billing_reason: "subscription_cycle",
+ attempt_count: 1,
+ next_payment_attempt: null,
+ lines: { data: [{ price: { id: "price_baa" } }] },
+ },
+ },
+ });
+ expect((await POST(makeWebhookRequest())).status).toBe(200);
+ expect(sendEmail).not.toHaveBeenCalled();
+ expect(mockStripe.customers.retrieve).not.toHaveBeenCalled();
+ });
+
+ it("cancels the BAA on its separate customer when Pro becomes unpaid", async () => {
+ const pro = {
+ id: "sub_pro",
+ status: "unpaid",
+ customer: "cus_pro",
+ metadata: {},
+ items: { data: [{ price: { id: "price_pro" }, quantity: 3 }] },
+ };
+ mockStripe.webhooks.constructEvent.mockReturnValue({
+ type: "customer.subscription.updated",
+ data: { object: pro },
+ });
+ mockStripe.customers.retrieve.mockResolvedValue({
+ id: "cus_pro",
+ email: owner.email,
+ metadata: { userId: owner.id },
+ });
+ mockStripe.subscriptions.list.mockResolvedValue({ data: [pro] });
+ mockDbChain.limit
+ .mockResolvedValueOnce([owner])
+ .mockResolvedValueOnce([{ subscriptionId: "sub_link_baa" }]);
+ expect((await POST(makeWebhookRequest())).status).toBe(200);
+ expect(mockStripe.subscriptions.cancel).toHaveBeenCalledExactlyOnceWith(
+ "sub_link_baa",
+ );
+ expect(mockDbChain.set).toHaveBeenCalledWith({ status: "canceled" });
+ });
+
+ it("preserves ordinary Pro checkout and its seat quota", async () => {
+ const pro = {
+ id: "sub_pro",
+ status: "active",
+ customer: "cus_pro",
+ metadata: {},
+ items: { data: [{ price: { id: "price_pro" }, quantity: 3 }] },
+ };
+ mockStripe.webhooks.constructEvent.mockReturnValue({
+ type: "checkout.session.completed",
+ data: {
+ object: { ...session, subscription: "sub_pro", customer: "cus_pro" },
+ },
+ });
+ mockStripe.subscriptions.retrieve.mockResolvedValue(pro);
+ mockStripe.customers.retrieve.mockResolvedValue({
+ id: "cus_pro",
+ email: owner.email,
+ metadata: { userId: owner.id },
+ });
+ mockDbChain.limit.mockResolvedValueOnce([owner]);
+ expect((await POST(makeWebhookRequest())).status).toBe(200);
+ expect(mockDbChain.update).toHaveBeenCalledWith(users);
+ expect(mockDbChain.set).toHaveBeenCalledWith(
+ expect.objectContaining({
+ stripeSubscriptionId: "sub_pro",
+ stripeCustomerId: "cus_pro",
+ inviteQuota: 3,
+ }),
+ );
+ expect(mockDbChain.update).not.toHaveBeenCalledWith(signedBaas);
+ });
+});
diff --git a/apps/web/__tests__/unit/signed-baa.test.ts b/apps/web/__tests__/unit/signed-baa.test.ts
index ae7e3184d..8bc0ed6d1 100644
--- a/apps/web/__tests__/unit/signed-baa.test.ts
+++ b/apps/web/__tests__/unit/signed-baa.test.ts
@@ -1,6 +1,10 @@
import { getCurrentUser } from "@cap/database/auth/session";
import { sendEmail } from "@cap/database/emails/config";
+import { signedBaas } from "@cap/database/schema";
+import { STRIPE_SIGNED_BAA_PRICE_IDS } from "@cap/utils";
+import type Stripe from "stripe";
import { beforeEach, describe, expect, it, vi } from "vitest";
+import { attachPaidBaaCheckout } from "@/lib/baa/billing";
import { generateSignedBaaPdf } from "@/lib/baa/generate-signed-baa-pdf";
const mockDb = {
@@ -15,10 +19,12 @@ const mockDb = {
};
const mockStripe = {
+ checkout: { sessions: { retrieve: vi.fn() } },
subscriptions: {
retrieve: vi.fn(),
list: vi.fn(),
create: vi.fn(),
+ cancel: vi.fn(),
},
customers: {
retrieve: vi.fn(),
@@ -59,7 +65,9 @@ vi.mock("@cap/database/schema", () => ({
status: "signedBaaStatus",
updatedAt: "signedBaaUpdatedAt",
stripeSubscriptionId: "signedBaaStripeSubscriptionId",
+ userId: "signedBaaUserId",
},
+ users: { id: "userId", email: "email", stripeCustomerId: "stripeCustomerId" },
}));
vi.mock("@cap/env", () => ({
@@ -80,6 +88,7 @@ vi.mock("drizzle-orm", () => ({
eq: vi.fn((field: unknown, value: unknown) => ({ field, value })),
lt: vi.fn((field: unknown, value: unknown) => ({ field, value })),
ne: vi.fn((field: unknown, value: unknown) => ({ field, value })),
+ isNull: vi.fn((field: unknown) => ({ isNull: field })),
or: vi.fn((...args: unknown[]) => args),
}));
@@ -103,7 +112,7 @@ function resetMockDb() {
mockDb.insert.mockReturnValue(mockDb);
mockDb.update.mockReturnValue(mockDb);
mockDb.from.mockReturnValue(mockDb);
- mockDb.where.mockReturnValue(mockDb);
+ mockDb.where.mockReturnValue({ ...mockDb, affectedRows: 1 });
mockDb.set.mockReturnValue(mockDb);
mockDb.values.mockResolvedValue(undefined);
mockDb.limit.mockResolvedValue([]);
@@ -271,6 +280,7 @@ async function setupPurchaseAttempt() {
vi.mocked(sendEmail).mockResolvedValue(undefined as never);
mockStripe.subscriptions.retrieve.mockResolvedValue({
id: "sub_active",
+ customer: "cus_1",
status: "active",
default_payment_method: "pm_1",
});
@@ -342,6 +352,7 @@ describe("Signed BAA Stripe recovery", () => {
expect(mockDb.where).toHaveBeenCalledWith([
{ field: "signedBaaId", value: "baa-record-1" },
{ field: "signedBaaStatus", value: "processing" },
+ { field: "signedBaaUpdatedAt", value: expect.any(Date) },
]);
});
@@ -368,6 +379,7 @@ describe("Signed BAA Stripe recovery", () => {
vi.mocked(sendEmail).mockResolvedValue(undefined as never);
mockStripe.subscriptions.retrieve.mockResolvedValue({
id: "sub_active",
+ customer: "cus_1",
status: "active",
default_payment_method: "pm_1",
});
@@ -387,4 +399,513 @@ describe("Signed BAA Stripe recovery", () => {
}),
);
});
+
+ it("cancels a newly purchased BAA if Pro ends while payment is in flight", async () => {
+ await setupPurchaseAttempt();
+ const pro = {
+ id: "sub_active",
+ customer: "cus_1",
+ status: "active",
+ default_payment_method: "pm_1",
+ };
+ mockStripe.subscriptions.retrieve
+ .mockReset()
+ .mockResolvedValueOnce(pro)
+ .mockResolvedValueOnce(pro)
+ .mockResolvedValueOnce({ ...pro, status: "canceled" });
+ mockStripe.subscriptions.list.mockResolvedValue({ data: [] });
+ mockStripe.subscriptions.create.mockResolvedValue(recoveredSubscription);
+ mockStripe.subscriptions.cancel.mockResolvedValue({
+ id: recoveredSubscription.id,
+ status: "canceled",
+ });
+ const { purchaseSignedBaa } = await import(
+ "@/actions/organization/signed-baa"
+ );
+ await expect(
+ purchaseSignedBaa("org-1" as never, VALID_INPUT),
+ ).rejects.toThrow("Cap Pro ended");
+ expect(mockStripe.subscriptions.cancel).toHaveBeenCalledWith(
+ recoveredSubscription.id,
+ );
+ expect(mockDb.set).toHaveBeenCalledWith(
+ expect.objectContaining({
+ stripeSubscriptionId: recoveredSubscription.id,
+ }),
+ );
+ expect(mockDb.set).toHaveBeenCalledWith({ status: "canceled" });
+ expect(mockDb.set).not.toHaveBeenCalledWith(
+ expect.objectContaining({ status: "active" }),
+ );
+ expect(sendEmail).not.toHaveBeenCalled();
+ });
+
+ it("recovers paid state after the create response is lost but the webhook linked it", async () => {
+ await setupPurchaseAttempt();
+ const pro = {
+ id: "sub_active",
+ customer: "cus_1",
+ status: "active",
+ default_payment_method: "pm_1",
+ };
+ mockStripe.subscriptions.retrieve
+ .mockReset()
+ .mockResolvedValueOnce(pro)
+ .mockResolvedValueOnce(pro)
+ .mockResolvedValueOnce(pro)
+ .mockResolvedValueOnce({
+ ...recoveredSubscription,
+ latest_invoice: { status: "paid" },
+ })
+ .mockResolvedValueOnce(pro);
+ mockDb.limit.mockResolvedValueOnce([
+ { subscriptionId: recoveredSubscription.id },
+ ]);
+ mockStripe.subscriptions.list.mockResolvedValue({ data: [] });
+ mockStripe.subscriptions.create.mockRejectedValue(
+ new Error("response lost"),
+ );
+ const { purchaseSignedBaa } = await import(
+ "@/actions/organization/signed-baa"
+ );
+ await expect(
+ purchaseSignedBaa("org-1" as never, VALID_INPUT),
+ ).rejects.toThrow("couldn't confirm");
+ expect(mockDb.set).toHaveBeenCalledWith({ status: "paid" });
+ expect(mockDb.set).not.toHaveBeenCalledWith({ status: "pending" });
+ });
+
+ it("cancels an unlinked direct subscription when another payment wins association", async () => {
+ await setupPurchaseAttempt();
+ mockStripe.subscriptions.list.mockResolvedValue({ data: [] });
+ mockStripe.subscriptions.create.mockResolvedValue(recoveredSubscription);
+ mockDb.where
+ .mockReturnValueOnce(mockDb)
+ .mockReturnValueOnce(mockDb)
+ .mockReturnValueOnce({ affectedRows: 0 });
+ mockDb.limit.mockResolvedValueOnce([
+ { status: "paid", stripeSubscriptionId: "sub_payment_link" },
+ ]);
+ const { purchaseSignedBaa } = await import(
+ "@/actions/organization/signed-baa"
+ );
+ await expect(
+ purchaseSignedBaa("org-1" as never, VALID_INPUT),
+ ).rejects.toThrow("changed while confirming");
+ expect(mockStripe.subscriptions.cancel).toHaveBeenCalledExactlyOnceWith(
+ recoveredSubscription.id,
+ );
+ expect(mockDb.set).not.toHaveBeenCalledWith(
+ expect.objectContaining({ status: "active" }),
+ );
+ expect(sendEmail).not.toHaveBeenCalled();
+ });
+});
+
+const paidRecord = {
+ id: "baa-record-1",
+ organizationId: "org-1",
+ userId: "owner-1",
+ status: "paid",
+ stripeSubscriptionId: "sub_baa_paid" as string | null,
+ signedAt: null,
+ emailSentAt: null,
+ updatedAt: new Date(),
+ ...VALID_INPUT,
+ signatureData: VALID_INPUT.signatureDataUrl,
+};
+
+const paidSubscription = {
+ id: "sub_baa_paid",
+ customer: "cus_payment_link",
+ status: "active",
+ metadata: {},
+ items: { data: [{ price: { id: STRIPE_SIGNED_BAA_PRICE_IDS.development } }] },
+ latest_invoice: { status: "paid" },
+} as unknown as Stripe.Subscription;
+
+const paidSession = {
+ id: "cs_paid_baa",
+ mode: "subscription",
+ status: "complete",
+ payment_status: "paid",
+ customer: "cus_payment_link",
+ customer_details: { email: "[email protected]" },
+ subscription: "sub_baa_paid",
+} as Stripe.Checkout.Session;
+
+const checkoutOwner = {
+ id: "owner-1" as never,
+ email: "[email protected]",
+ stripeCustomerId: "cus_pro",
+ stripeSubscriptionId: "sub_pro",
+};
+
+const proSubscription = {
+ id: "sub_pro",
+ customer: "cus_pro",
+ status: "active",
+ metadata: {},
+};
+
+describe("Paid BAA signing", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ resetMockDb();
+ mockStripe.subscriptions.retrieve
+ .mockReset()
+ .mockResolvedValue(proSubscription);
+ });
+
+ async function setupPaidSigning(record = paidRecord) {
+ mockOwner({
+ stripeCustomerId: "cus_pro",
+ stripeSubscriptionId: "sub_pro",
+ stripeSubscriptionStatus: "active",
+ });
+ mockDb.limit.mockResolvedValueOnce([record]);
+ mockStripe.subscriptions.retrieve.mockResolvedValueOnce({
+ id: "sub_pro",
+ customer: "cus_pro",
+ status: "active",
+ });
+ if (record.stripeSubscriptionId) {
+ mockStripe.subscriptions.retrieve.mockResolvedValueOnce(paidSubscription);
+ }
+ vi.mocked(generateSignedBaaPdf).mockResolvedValue(new Uint8Array([1]));
+ vi.mocked(sendEmail).mockResolvedValue(undefined as never);
+ return import("@/actions/organization/signed-baa");
+ }
+
+ it("signs using the paid subscription on a different Stripe customer", async () => {
+ const { signPaidBaa } = await setupPaidSigning();
+ const result = await signPaidBaa("org-1" as never, VALID_INPUT);
+ expect(result).toEqual({ success: true, emailSent: true });
+ expect(mockStripe.subscriptions.create).not.toHaveBeenCalled();
+ expect(mockStripe.subscriptions.list).not.toHaveBeenCalled();
+ expect(mockDb.set).toHaveBeenCalledWith(
+ expect.objectContaining({
+ status: "active",
+ stripeSubscriptionId: "sub_baa_paid",
+ signedAt: expect.any(Date),
+ }),
+ );
+ });
+
+ it("also prevents a duplicate charge through the old purchase action", async () => {
+ const { purchaseSignedBaa } = await setupPaidSigning();
+ await purchaseSignedBaa("org-1" as never, VALID_INPUT);
+ expect(mockStripe.subscriptions.create).not.toHaveBeenCalled();
+ });
+
+ it("keeps payment when the new signature cannot generate a PDF", async () => {
+ const { signPaidBaa } = await setupPaidSigning();
+ vi.mocked(generateSignedBaaPdf).mockRejectedValueOnce(new Error("bad PNG"));
+ await expect(signPaidBaa("org-1" as never, VALID_INPUT)).rejects.toThrow(
+ "generate the agreement",
+ );
+ expect(mockDb.set).toHaveBeenCalledWith({ status: "paid" });
+ expect(mockStripe.subscriptions.create).not.toHaveBeenCalled();
+ });
+
+ it("does not charge when signing an unpaid row", async () => {
+ const { signPaidBaa } = await setupPaidSigning({
+ ...paidRecord,
+ status: "pending",
+ stripeSubscriptionId: null,
+ });
+ await expect(signPaidBaa("org-1" as never, VALID_INPUT)).rejects.toThrow(
+ "confirmed BAA payment is required",
+ );
+ expect(mockStripe.subscriptions.create).not.toHaveBeenCalled();
+ expect(mockDb.update).not.toHaveBeenCalled();
+ });
+
+ it("rejects a canceled paid subscription without attempting a new purchase", async () => {
+ const { signPaidBaa } = await setupPaidSigning();
+ mockStripe.subscriptions.retrieve.mockReset();
+ mockStripe.subscriptions.retrieve
+ .mockResolvedValueOnce({ id: "sub_pro", status: "active" })
+ .mockResolvedValueOnce({ ...paidSubscription, status: "canceled" });
+ await expect(signPaidBaa("org-1" as never, VALID_INPUT)).rejects.toThrow(
+ "payment is not confirmed",
+ );
+ expect(mockStripe.subscriptions.create).not.toHaveBeenCalled();
+ });
+
+ it("does not finalize or email if cancellation wins while signing", async () => {
+ const { signPaidBaa } = await setupPaidSigning();
+ mockDb.where
+ .mockReturnValueOnce(mockDb)
+ .mockReturnValueOnce(mockDb)
+ .mockReturnValueOnce({ affectedRows: 1 })
+ .mockReturnValueOnce({ affectedRows: 1 })
+ .mockReturnValueOnce({ affectedRows: 0 });
+ await expect(signPaidBaa("org-1" as never, VALID_INPUT)).rejects.toThrow(
+ "changed while signing",
+ );
+ expect(sendEmail).not.toHaveBeenCalled();
+ });
+
+ it("returns paid details without returning the saved signature", async () => {
+ mockOwner({
+ stripeCustomerId: "cus_pro",
+ stripeSubscriptionStatus: "active",
+ });
+ mockDb.limit.mockResolvedValueOnce([paidRecord]);
+ const { getSignedBaaStatus } = await import(
+ "@/actions/organization/signed-baa"
+ );
+ const status = await getSignedBaaStatus("org-1" as never);
+ expect(status.status).toBe("paid");
+ expect(status.details?.entityName).toBe(VALID_INPUT.entityName);
+ expect(status.details).not.toHaveProperty("signatureData");
+ expect(status.signedAt).toBeNull();
+ });
+
+ it("does not claim a row if a checkout changes its payment state first", async () => {
+ const { signPaidBaa } = await setupPaidSigning();
+ mockDb.where
+ .mockReturnValueOnce(mockDb)
+ .mockReturnValueOnce(mockDb)
+ .mockReturnValueOnce({ affectedRows: 0 });
+ await expect(signPaidBaa("org-1" as never, VALID_INPUT)).rejects.toThrow(
+ "already in progress",
+ );
+ expect(mockDb.where).toHaveBeenCalledWith([
+ { field: "signedBaaId", value: "baa-record-1" },
+ { field: "signedBaaStatus", value: "paid" },
+ { field: "signedBaaStripeSubscriptionId", value: "sub_baa_paid" },
+ expect.any(Array),
+ ]);
+ expect(mockStripe.subscriptions.create).not.toHaveBeenCalled();
+ expect(generateSignedBaaPdf).not.toHaveBeenCalled();
+ });
+
+ it("requires authentication before retrieving a checkout session", async () => {
+ mockGetCurrentUser.mockResolvedValue(null);
+ const { confirmSignedBaaPayment } = await import(
+ "@/actions/organization/signed-baa"
+ );
+ await expect(
+ confirmSignedBaaPayment("org-1" as never, "cs_paid_baa"),
+ ).rejects.toThrow("Unauthorized");
+ expect(mockStripe.checkout.sessions.retrieve).not.toHaveBeenCalled();
+ });
+
+ it("requires the actual organization owner before confirming payment", async () => {
+ mockGetCurrentUser.mockResolvedValue({ id: "other-owner" });
+ mockDb.limit.mockResolvedValueOnce([{ id: "org-1", ownerId: "owner-1" }]);
+ const { confirmSignedBaaPayment } = await import(
+ "@/actions/organization/signed-baa"
+ );
+ await expect(
+ confirmSignedBaaPayment("org-1" as never, "cs_paid_baa"),
+ ).rejects.toThrow("Only the organization owner");
+ expect(mockStripe.checkout.sessions.retrieve).not.toHaveBeenCalled();
+ });
+
+ it("confirms a Stripe session and returns the refreshed paid status", async () => {
+ mockOwner({
+ stripeCustomerId: "cus_pro",
+ stripeSubscriptionId: "sub_pro",
+ stripeSubscriptionStatus: "active",
+ });
+ mockStripe.checkout.sessions.retrieve.mockResolvedValueOnce(paidSession);
+ mockStripe.subscriptions.retrieve
+ .mockReset()
+ .mockResolvedValueOnce(paidSubscription)
+ .mockResolvedValueOnce(proSubscription);
+ mockDb.limit
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([
+ { ...paidRecord, status: "pending", stripeSubscriptionId: null },
+ ])
+ .mockResolvedValueOnce([{ ownerId: "owner-1" }])
+ .mockResolvedValueOnce([{ ...paidRecord, status: "pending" }])
+ .mockResolvedValueOnce([paidRecord])
+ .mockResolvedValueOnce([{ id: "org-1", ownerId: "owner-1" }])
+ .mockResolvedValueOnce([paidRecord]);
+ const { confirmSignedBaaPayment } = await import(
+ "@/actions/organization/signed-baa"
+ );
+ expect(
+ (await confirmSignedBaaPayment("org-1" as never, "cs_paid_baa")).status,
+ ).toBe("paid");
+ expect(mockStripe.checkout.sessions.retrieve).toHaveBeenCalledWith(
+ "cs_paid_baa",
+ );
+ expect(mockStripe.subscriptions.create).not.toHaveBeenCalled();
+ });
+});
+
+describe("Paid BAA checkout association", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ resetMockDb();
+ mockStripe.subscriptions.retrieve
+ .mockReset()
+ .mockResolvedValue(proSubscription);
+ });
+
+ const expected = { owner: checkoutOwner, organizationId: "org-1" as never };
+ const pendingRecord = {
+ ...paidRecord,
+ status: "pending",
+ stripeSubscriptionId: null,
+ };
+
+ it("attaches a paid link with no metadata and a different Stripe customer", async () => {
+ mockDb.limit
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([pendingRecord])
+ .mockResolvedValueOnce([{ ownerId: "owner-1" }])
+ .mockResolvedValueOnce([{ ...paidRecord, status: "pending" }])
+ .mockResolvedValueOnce([paidRecord]);
+ const record = await attachPaidBaaCheckout(
+ paidSession,
+ paidSubscription,
+ expected,
+ );
+ expect(record?.status).toBe("paid");
+ expect(mockDb.update).toHaveBeenCalledWith(signedBaas);
+ expect(mockDb.set).toHaveBeenCalledWith({
+ stripeSubscriptionId: "sub_baa_paid",
+ });
+ expect(mockDb.set).toHaveBeenCalledWith({ status: "paid" });
+ });
+
+ it.each(["unpaid", "no_payment_required"])(
+ "does not accept %s checkout",
+ async (paymentStatus) => {
+ const result = await attachPaidBaaCheckout(
+ {
+ ...paidSession,
+ payment_status: paymentStatus,
+ } as Stripe.Checkout.Session,
+ paidSubscription,
+ expected,
+ );
+ expect(result).toBeNull();
+ expect(mockDb.update).not.toHaveBeenCalled();
+ },
+ );
+
+ it("does not accept a paid non-BAA subscription", async () => {
+ const result = await attachPaidBaaCheckout(
+ paidSession,
+ {
+ ...paidSubscription,
+ items: { data: [{ price: { id: "price_pro" } }] },
+ } as Stripe.Subscription,
+ expected,
+ );
+ expect(result).toBeNull();
+ expect(mockDb.update).not.toHaveBeenCalled();
+ });
+
+ it("rejects payment belonging to a different email", async () => {
+ await expect(
+ attachPaidBaaCheckout(
+ {
+ ...paidSession,
+ customer_details: { email: "[email protected]" },
+ } as Stripe.Checkout.Session,
+ paidSubscription,
+ expected,
+ ),
+ ).rejects.toThrow("different account");
+ expect(mockDb.update).not.toHaveBeenCalled();
+ });
+
+ it("rejects a subscription already attached to another organization", async () => {
+ mockDb.limit.mockResolvedValueOnce([
+ { ...paidRecord, organizationId: "org-2" },
+ ]);
+ await expect(
+ attachPaidBaaCheckout(paidSession, paidSubscription, expected),
+ ).rejects.toThrow("different organization");
+ expect(mockDb.update).not.toHaveBeenCalled();
+ });
+
+ it("does not guess between multiple pending organizations", async () => {
+ mockDb.limit
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([
+ pendingRecord,
+ { ...pendingRecord, id: "other", organizationId: "org-2" },
+ ]);
+ expect(
+ await attachPaidBaaCheckout(paidSession, paidSubscription, expected),
+ ).toBeNull();
+ expect(mockDb.update).not.toHaveBeenCalled();
+ });
+
+ it("does not overwrite the signature or paid state on duplicate checkout delivery", async () => {
+ mockDb.limit
+ .mockResolvedValueOnce([paidRecord])
+ .mockResolvedValueOnce([{ ownerId: "owner-1" }]);
+ expect(
+ await attachPaidBaaCheckout(paidSession, paidSubscription, expected),
+ ).toEqual(paidRecord);
+ expect(mockDb.update).not.toHaveBeenCalled();
+ });
+
+ it("cancels a second paid checkout instead of replacing the existing subscription", async () => {
+ const previous = { ...paidRecord, stripeSubscriptionId: "sub_existing" };
+ mockDb.limit
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([previous])
+ .mockResolvedValueOnce([{ ownerId: "owner-1" }]);
+ mockStripe.subscriptions.retrieve.mockResolvedValueOnce({
+ ...paidSubscription,
+ id: "sub_existing",
+ });
+ expect(
+ await attachPaidBaaCheckout(paidSession, paidSubscription, expected),
+ ).toEqual(previous);
+ expect(mockStripe.subscriptions.cancel).toHaveBeenCalledExactlyOnceWith(
+ paidSubscription.id,
+ );
+ expect(mockDb.update).not.toHaveBeenCalled();
+ });
+
+ it("cancels the losing checkout when two paid subscriptions race for the pending row", async () => {
+ const winner = { ...paidRecord, stripeSubscriptionId: "sub_winner" };
+ mockDb.limit
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([pendingRecord])
+ .mockResolvedValueOnce([{ ownerId: "owner-1" }])
+ .mockResolvedValueOnce([winner]);
+ mockStripe.subscriptions.retrieve.mockResolvedValueOnce({
+ ...paidSubscription,
+ id: "sub_winner",
+ });
+ expect(
+ await attachPaidBaaCheckout(paidSession, paidSubscription, expected),
+ ).toEqual(winner);
+ expect(mockStripe.subscriptions.cancel).toHaveBeenCalledExactlyOnceWith(
+ paidSubscription.id,
+ );
+ expect(mockDb.set).not.toHaveBeenCalledWith({ status: "paid" });
+ });
+
+ it("fails closed when another subscription wins the association race", async () => {
+ mockDb.limit
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([pendingRecord])
+ .mockResolvedValueOnce([{ ownerId: "owner-1" }])
+ .mockResolvedValueOnce([
+ { ...paidRecord, stripeSubscriptionId: "sub_other" },
+ ]);
+ await expect(
+ attachPaidBaaCheckout(paidSession, paidSubscription, expected),
+ ).rejects.toThrow("changed while confirming");
+ expect(mockDb.where).toHaveBeenCalledWith([
+ { field: "signedBaaId", value: "baa-record-1" },
+ { field: "signedBaaStatus", value: "pending" },
+ { isNull: "signedBaaStripeSubscriptionId" },
+ ]);
+ });
});
diff --git a/apps/web/actions/organization/signed-baa.ts b/apps/web/actions/organization/signed-baa.ts
index 344c14eba..f4f876f98 100644
--- a/apps/web/actions/organization/signed-baa.ts
+++ b/apps/web/actions/organization/signed-baa.ts
@@ -9,9 +9,16 @@ import { organizations, signedBaas } from "@cap/database/schema";
import { serverEnv } from "@cap/env";
import { STRIPE_SIGNED_BAA_PRICE_IDS, stripe } from "@cap/utils";
import type { Organisation } from "@cap/web-domain";
-import { and, eq, lt, ne, or } from "drizzle-orm";
+import { and, eq, isNull, lt, ne, or } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import type Stripe from "stripe";
+import {
+ attachPaidBaaCheckout,
+ BAA_ENTITLED_STATUSES,
+ ensureBaaHasPro,
+ hasPaidBaaInvoice,
+ isSignedBaaSubscription,
+} from "@/lib/baa/billing";
import {
formatBaaDate,
generateSignedBaaPdf,
@@ -59,11 +66,12 @@ export type SignedBaaInput = {
};
export type SignedBaaStatus = {
- status: "none" | "active" | "canceled";
+ status: "none" | "paid" | "active" | "canceled" | "processing";
signedAt: string | null;
entityName: string | null;
emailSentAt: string | null;
canPurchase: boolean;
+ details: Omit<SignedBaaInput, "signatureDataUrl"> | null;
};
function getBaaPriceId() {
@@ -106,12 +114,21 @@ export async function getSignedBaaStatus(
.where(eq(signedBaas.organizationId, organizationId))
.limit(1);
- const status =
- record?.status === "active"
+ const processing =
+ record?.status === "processing" &&
+ Date.now() - record.updatedAt.getTime() < PROCESSING_STALE_MS;
+ const status = processing
+ ? "processing"
+ : record?.status === "active" && record.signedAt
? "active"
: record?.status === "canceled"
? "canceled"
- : "none";
+ : record?.stripeSubscriptionId &&
+ (record.status === "paid" ||
+ record.status === "active" ||
+ record.status === "processing")
+ ? "paid"
+ : "none";
return {
status,
@@ -125,9 +142,49 @@ export async function getSignedBaaStatus(
? record.emailSentAt.toISOString()
: null,
canPurchase: ownerCanPurchaseSignedBaa(user),
+ details: record
+ ? {
+ entityName: record.entityName,
+ entityType: record.entityType,
+ entityAddress: record.entityAddress,
+ signerName: record.signerName,
+ signerTitle: record.signerTitle,
+ noticesEmail: record.noticesEmail,
+ }
+ : null,
};
}
+export async function confirmSignedBaaPayment(
+ organizationId: Organisation.OrganisationId,
+ sessionId: string,
+): Promise<SignedBaaStatus> {
+ const { user } = await getOwnerContext(organizationId);
+ if (!sessionId.startsWith("cs_") || sessionId.length > 255) {
+ throw new Error("Invalid payment confirmation. Please contact support.");
+ }
+ const session = await stripe().checkout.sessions.retrieve(sessionId);
+ const subscriptionId =
+ typeof session.subscription === "string"
+ ? session.subscription
+ : session.subscription?.id;
+ if (!subscriptionId) {
+ throw new Error("No BAA subscription was found for this payment.");
+ }
+ const subscription = await stripe().subscriptions.retrieve(subscriptionId);
+ const record = await attachPaidBaaCheckout(session, subscription, {
+ owner: user,
+ organizationId,
+ });
+ if (!record) {
+ throw new Error(
+ "We couldn't confirm a paid BAA for this organization. Please retry once payment completes, or contact support. Do not pay again.",
+ );
+ }
+ revalidatePath("/dashboard/settings/organization/billing");
+ return getSignedBaaStatus(organizationId);
+}
+
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const SIGNATURE_PREFIX = "data:image/png;base64,";
@@ -287,6 +344,21 @@ async function createBaaSubscription({
export async function purchaseSignedBaa(
organizationId: Organisation.OrganisationId,
input: SignedBaaInput,
+): Promise<{ success: true; emailSent: boolean }> {
+ return completeSignedBaa(organizationId, input, false);
+}
+
+export async function signPaidBaa(
+ organizationId: Organisation.OrganisationId,
+ input: SignedBaaInput,
+): Promise<{ success: true; emailSent: boolean }> {
+ return completeSignedBaa(organizationId, input, true);
+}
+
+async function completeSignedBaa(
+ organizationId: Organisation.OrganisationId,
+ input: SignedBaaInput,
+ requirePaid: boolean,
): Promise<{ success: true; emailSent: boolean }> {
const details = validateInput(input);
const { user } = await getOwnerContext(organizationId);
@@ -313,7 +385,10 @@ export async function purchaseSignedBaa(
"Your organization needs an active Cap Pro subscription before adding the Signed BAA add-on.",
);
}
- if (!CAP_PRO_STATUSES.has(liveProSubscription.status)) {
+ if (
+ !CAP_PRO_STATUSES.has(liveProSubscription.status) ||
+ isSignedBaaSubscription(liveProSubscription)
+ ) {
throw new Error(
"Your organization needs an active Cap Pro subscription before adding the Signed BAA add-on.",
);
@@ -328,11 +403,33 @@ export async function purchaseSignedBaa(
if (existing?.status === "active" && existing.emailSentAt) {
throw new Error("A Signed BAA is already active for this organization.");
}
+ let paidSubscription: Stripe.Subscription | null = null;
+ if (existing?.stripeSubscriptionId && existing.status !== "canceled") {
+ paidSubscription = await stripe().subscriptions.retrieve(
+ existing.stripeSubscriptionId,
+ { expand: ["latest_invoice"] },
+ );
+ if (
+ !isSignedBaaSubscription(paidSubscription) ||
+ !BAA_ENTITLED_STATUSES.has(paidSubscription.status) ||
+ (!existing.signedAt &&
+ existing.status !== "paid" &&
+ !hasPaidBaaInvoice(paidSubscription))
+ ) {
+ throw new Error(
+ "The existing BAA payment is not confirmed. Please contact support; no additional payment was taken.",
+ );
+ }
+ }
+ if (requirePaid && !paidSubscription) {
+ throw new Error("A confirmed BAA payment is required before signing.");
+ }
const { signatureDataUrl, ...contractFields } = details;
const recordFields = { ...contractFields, signatureData: signatureDataUrl };
const isEmailRetry = existing?.status === "active";
+ const claimedAt = new Date(Math.floor(Date.now() / 1000) * 1000);
let recordId: string;
if (existing) {
recordId = existing.id;
@@ -341,6 +438,7 @@ export async function purchaseSignedBaa(
.update(signedBaas)
.set({
status: "processing",
+ updatedAt: claimedAt,
userId: user.id,
...recordFields,
// A stale ID from a canceled subscription would stop the
@@ -350,12 +448,16 @@ export async function purchaseSignedBaa(
: {
signedAt: null,
emailSentAt: null,
- stripeSubscriptionId: null,
+ stripeSubscriptionId: paidSubscription?.id ?? null,
}),
})
.where(
and(
eq(signedBaas.id, existing.id),
+ eq(signedBaas.status, existing.status),
+ existing.stripeSubscriptionId
+ ? eq(signedBaas.stripeSubscriptionId, existing.stripeSubscriptionId)
+ : isNull(signedBaas.stripeSubscriptionId),
or(
ne(signedBaas.status, "processing"),
lt(signedBaas.updatedAt, staleBefore),
@@ -377,6 +479,7 @@ export async function purchaseSignedBaa(
organizationId,
userId: user.id,
status: "processing",
+ updatedAt: claimedAt,
...recordFields,
});
} catch {
@@ -390,11 +493,45 @@ export async function purchaseSignedBaa(
// The subscription.created webhook can associate and activate the record
// mid-flight when Stripe's create response was lost, so the revert must
// only touch rows still claimed by this purchase attempt.
+ let status = paidSubscription
+ ? "paid"
+ : existing?.status === "canceled"
+ ? "canceled"
+ : "pending";
+ if (!paidSubscription) {
+ const [current] = await db()
+ .select({ subscriptionId: signedBaas.stripeSubscriptionId })
+ .from(signedBaas)
+ .where(eq(signedBaas.id, recordId))
+ .limit(1);
+ if (current?.subscriptionId) {
+ try {
+ const recovered = await stripe().subscriptions.retrieve(
+ current.subscriptionId,
+ { expand: ["latest_invoice"] },
+ );
+ if (
+ isSignedBaaSubscription(recovered) &&
+ BAA_ENTITLED_STATUSES.has(recovered.status) &&
+ hasPaidBaaInvoice(recovered)
+ ) {
+ if (!(await ensureBaaHasPro(user, recovered, recordId))) return;
+ status = "paid";
+ }
+ } catch {
+ return;
+ }
+ }
+ }
await db()
.update(signedBaas)
- .set({ status: existing?.status === "canceled" ? "canceled" : "pending" })
+ .set({ status })
.where(
- and(eq(signedBaas.id, recordId), eq(signedBaas.status, "processing")),
+ and(
+ eq(signedBaas.id, recordId),
+ eq(signedBaas.status, "processing"),
+ eq(signedBaas.updatedAt, claimedAt),
+ ),
);
};
@@ -417,17 +554,8 @@ export async function purchaseSignedBaa(
);
}
- let subscription: Stripe.Subscription | null = null;
- try {
- subscription = await createBaaSubscription({
- customerId,
- organizationId,
- userId: user.id,
- recordId,
- proSubscriptionId: user.stripeSubscriptionId,
- priceId,
- });
- } catch (error) {
+ let subscription: Stripe.Subscription | null = paidSubscription;
+ if (!subscription) {
try {
subscription = await createBaaSubscription({
customerId,
@@ -437,9 +565,20 @@ export async function purchaseSignedBaa(
proSubscriptionId: user.stripeSubscriptionId,
priceId,
});
- } catch (retryError) {
- await revertToPending();
- throwSignedBaaStripeError(retryError ?? error);
+ } catch (error) {
+ try {
+ subscription = await createBaaSubscription({
+ customerId,
+ organizationId,
+ userId: user.id,
+ recordId,
+ proSubscriptionId: user.stripeSubscriptionId,
+ priceId,
+ });
+ } catch (retryError) {
+ await revertToPending();
+ throwSignedBaaStripeError(retryError ?? error);
+ }
}
}
@@ -449,15 +588,73 @@ export async function purchaseSignedBaa(
"We couldn't confirm the Signed BAA subscription. Please try again or contact support if you were charged.",
);
}
+ const association = await db()
+ .update(signedBaas)
+ .set({ stripeSubscriptionId: subscription.id, updatedAt: claimedAt })
+ .where(
+ and(
+ eq(signedBaas.id, recordId),
+ eq(signedBaas.status, "processing"),
+ eq(signedBaas.updatedAt, claimedAt),
+ or(
+ isNull(signedBaas.stripeSubscriptionId),
+ eq(signedBaas.stripeSubscriptionId, subscription.id),
+ ),
+ ),
+ );
+ const cancelIfUnlinked = async () => {
+ const [current] = await db()
+ .select()
+ .from(signedBaas)
+ .where(eq(signedBaas.id, recordId))
+ .limit(1);
+ if (
+ !paidSubscription &&
+ current?.stripeSubscriptionId !== subscription.id
+ ) {
+ await stripe().subscriptions.cancel(subscription.id);
+ }
+ return current;
+ };
+ if (getAffectedRows(association) === 0) {
+ const current = await cancelIfUnlinked();
+ if (
+ current?.stripeSubscriptionId !== subscription.id ||
+ current.status !== "processing" ||
+ current.updatedAt.getTime() !== claimedAt.getTime()
+ ) {
+ throw new Error(
+ "The BAA changed while confirming payment. Please refresh or contact support; do not pay again.",
+ );
+ }
+ }
+ if (!(await ensureBaaHasPro(user, subscription, recordId))) {
+ throw new Error(
+ "Cap Pro ended before the BAA could be signed. The BAA subscription has been canceled; please contact support about your payment.",
+ );
+ }
- await db()
+ const finalized = await db()
.update(signedBaas)
.set({
status: "active",
stripeSubscriptionId: subscription.id,
signedAt,
})
- .where(eq(signedBaas.id, recordId));
+ .where(
+ and(
+ eq(signedBaas.id, recordId),
+ eq(signedBaas.status, "processing"),
+ eq(signedBaas.updatedAt, claimedAt),
+ eq(signedBaas.stripeSubscriptionId, subscription.id),
+ ),
+ );
+ if (getAffectedRows(finalized) === 0) {
+ await cancelIfUnlinked();
+ throw new Error(
+ "The BAA changed while signing. Please refresh or contact support; do not pay again.",
+ );
+ }
let emailSent = Boolean(existing?.emailSentAt);
if (!emailSent) {
@@ -498,6 +695,7 @@ export async function purchaseSignedBaa(
}
revalidatePath("/dashboard/settings/organization");
+ revalidatePath("/dashboard/settings/organization/billing");
return { success: true, emailSent };
}
diff --git a/apps/web/app/(org)/dashboard/settings/organization/components/SeatManagementCard.tsx b/apps/web/app/(org)/dashboard/settings/organization/components/SeatManagementCard.tsx
index 5f6912e57..448df6854 100644
--- a/apps/web/app/(org)/dashboard/settings/organization/components/SeatManagementCard.tsx
+++ b/apps/web/app/(org)/dashboard/settings/organization/components/SeatManagementCard.tsx
@@ -135,7 +135,7 @@ export function SeatManagementCard() {
const canDecrease = desiredQuantity > minQuantity;
const canIncrease = desiredQuantity < MAX_SEATS;
const isCancelRequest = desiredQuantity === 0;
- const baaActive = baa?.status === "active";
+ const baaActive = baa?.status === "active" || baa?.status === "paid";
return (
<Card>
diff --git a/apps/web/app/(org)/dashboard/settings/organization/components/SignedBaaCard.tsx b/apps/web/app/(org)/dashboard/settings/organization/components/SignedBaaCard.tsx
index 136488dbc..a5f521c6a 100644
--- a/apps/web/app/(org)/dashboard/settings/organization/components/SignedBaaCard.tsx
+++ b/apps/web/app/(org)/dashboard/settings/organization/components/SignedBaaCard.tsx
@@ -16,27 +16,30 @@ import { faFileSignature } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { format } from "date-fns";
-import { useRouter } from "next/navigation";
-import { useId, useState } from "react";
+import { useRouter, useSearchParams } from "next/navigation";
+import {
+ Suspense,
+ useCallback,
+ useEffect,
+ useId,
+ useRef,
+ useState,
+} from "react";
import { toast } from "sonner";
import {
+ confirmSignedBaaPayment,
getSignedBaaStatus,
purchaseSignedBaa,
+ type SignedBaaInput,
type SignedBaaStatus,
+ signPaidBaa,
} from "@/actions/organization/signed-baa";
import { useDashboardContext } from "@/app/(org)/dashboard/Contexts";
import { SignaturePad } from "./SignaturePad";
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
-type FormState = {
- entityName: string;
- entityType: string;
- entityAddress: string;
- signerName: string;
- signerTitle: string;
- noticesEmail: string;
-};
+type FormState = Omit<SignedBaaInput, "signatureDataUrl">;
const EMPTY_FORM: FormState = {
entityName: "",
@@ -48,17 +51,41 @@ const EMPTY_FORM: FormState = {
};
export function SignedBaaCard() {
+ const { activeOrganization } = useDashboardContext();
+
+ return (
+ <Suspense
+ fallback={<div className="h-32 rounded-xl animate-pulse bg-gray-4" />}
+ >
+ <SignedBaaCardContent key={activeOrganization?.organization.id} />
+ </Suspense>
+ );
+}
+
+function SignedBaaCardContent() {
const { activeOrganization, user } = useDashboardContext();
const router = useRouter();
+ const searchParams = useSearchParams();
const queryClient = useQueryClient();
const organizationId = activeOrganization?.organization.id;
+ const isBaaRedirect = searchParams.get("baaRedirect") === "true";
+ const sessionId = searchParams.get("session_id");
const fieldIdPrefix = useId();
+ const handledSessionId = useRef<string | null>(null);
const [dialogOpen, setDialogOpen] = useState(false);
const [form, setForm] = useState<FormState>(EMPTY_FORM);
- const [signature, setSignature] = useState<string | null>(null);
+ const [signature, setSignature] = useState<{
+ paid: boolean;
+ dataUrl: string;
+ } | null>(null);
- const { data: baa, isLoading } = useQuery<SignedBaaStatus | null>({
+ const {
+ data: baa,
+ isLoading,
+ isError: statusFailed,
+ refetch: refetchStatus,
+ } = useQuery<SignedBaaStatus | null>({
queryKey: ["signed-baa", organizationId],
queryFn: () => {
if (!organizationId) return null;
@@ -66,16 +93,72 @@ export function SignedBaaCard() {
},
enabled: !!organizationId,
staleTime: 60 * 1000,
+ refetchInterval: (query) =>
+ query.state.data?.status === "processing" ? 3000 : false,
});
- const purchaseMutation = useMutation({
+ const paymentConfirmation = useQuery({
+ queryKey: ["signed-baa-payment", organizationId, sessionId],
+ queryFn: async () => {
+ if (!organizationId || !sessionId) {
+ throw new Error("The payment confirmation link is incomplete.");
+ }
+ const result = await confirmSignedBaaPayment(organizationId, sessionId);
+ if (result.status === "none" || result.status === "canceled") {
+ throw new Error("Your BAA payment could not be confirmed.");
+ }
+ const queryKey = ["signed-baa", organizationId];
+ await queryClient.cancelQueries({ queryKey, exact: true });
+ queryClient.setQueryData(queryKey, result);
+ await queryClient.invalidateQueries({ queryKey, exact: true });
+ return result;
+ },
+ enabled: isBaaRedirect && !!organizationId && !!sessionId,
+ retry: false,
+ refetchOnWindowFocus: false,
+ refetchOnReconnect: false,
+ gcTime: 0,
+ });
+
+ const verificationPending =
+ isBaaRedirect &&
+ !!sessionId &&
+ (paymentConfirmation.isPending || paymentConfirmation.isFetching);
+ const verificationError = isBaaRedirect
+ ? !sessionId
+ ? "The payment confirmation link is incomplete. Reopen the link from checkout or contact [email protected]."
+ : paymentConfirmation.error?.message
+ : null;
+ const verificationBlocked =
+ isBaaRedirect &&
+ (!sessionId || !paymentConfirmation.isSuccess || verificationPending);
+ const isActive = baa?.status === "active";
+ const isPaid = baa?.status === "paid";
+ const signatureDataUrl =
+ signature?.paid === isPaid ? signature.dataUrl : null;
+ const isProcessing = baa?.status === "processing";
+ const canPurchase = Boolean(baa?.canPurchase);
+ const actionsBlocked =
+ !organizationId ||
+ isLoading ||
+ statusFailed ||
+ verificationBlocked ||
+ isProcessing ||
+ isActive ||
+ (!isPaid && !canPurchase);
+
+ const signatureMutation = useMutation({
mutationFn: () => {
if (!organizationId) throw new Error("No organization");
- if (!signature) throw new Error("Please add your signature");
- return purchaseSignedBaa(organizationId, {
+ if (actionsBlocked) throw new Error("Please wait for your BAA status.");
+ if (!signatureDataUrl) throw new Error("Please add your signature");
+ const input = {
...form,
- signatureDataUrl: signature,
- });
+ signatureDataUrl,
+ };
+ return isPaid
+ ? signPaidBaa(organizationId, input)
+ : purchaseSignedBaa(organizationId, input);
},
onSuccess: (result) => {
toast.success(
@@ -92,27 +175,64 @@ export function SignedBaaCard() {
router.refresh();
},
onError: (error) => {
+ queryClient.invalidateQueries({
+ queryKey: ["signed-baa", organizationId],
+ });
toast.error(
error instanceof Error
? error.message
- : "Failed to complete the Signed BAA purchase",
+ : "Failed to complete your Signed BAA",
);
},
});
- const isActive = baa?.status === "active";
- const canPurchase = Boolean(baa?.canPurchase);
-
- const openDialog = () => {
- setForm((current) => ({
- ...current,
+ const openDialog = useCallback(() => {
+ setForm({
+ ...(baa?.details ?? EMPTY_FORM),
signerName:
- current.signerName ||
+ baa?.details?.signerName ||
[user.name, user.lastName].filter(Boolean).join(" "),
- noticesEmail: current.noticesEmail || user.email,
- }));
+ noticesEmail: baa?.details?.noticesEmail || user.email,
+ });
+ setSignature(null);
setDialogOpen(true);
- };
+ }, [baa?.details, user.name, user.lastName, user.email]);
+
+ useEffect(() => {
+ if (
+ isBaaRedirect &&
+ sessionId &&
+ !verificationBlocked &&
+ !statusFailed &&
+ !isLoading &&
+ (isPaid || isActive) &&
+ handledSessionId.current !== sessionId
+ ) {
+ handledSessionId.current = sessionId;
+ if (isPaid) openDialog();
+ const url = new URL(window.location.href);
+ if (
+ url.searchParams.get("baaRedirect") === "true" &&
+ url.searchParams.get("session_id") === sessionId
+ ) {
+ url.searchParams.delete("baaRedirect");
+ url.searchParams.delete("session_id");
+ router.replace(`${url.pathname}${url.search}${url.hash}`, {
+ scroll: false,
+ });
+ }
+ }
+ }, [
+ isBaaRedirect,
+ sessionId,
+ verificationBlocked,
+ statusFailed,
+ isLoading,
+ isPaid,
+ isActive,
+ openDialog,
+ router,
+ ]);
const updateField =
(field: keyof FormState) => (e: React.ChangeEvent<HTMLInputElement>) =>
@@ -125,7 +245,7 @@ export function SignedBaaCard() {
form.signerName.trim().length >= 2 &&
form.signerTitle.trim().length >= 2 &&
EMAIL_REGEX.test(form.noticesEmail.trim()) &&
- Boolean(signature);
+ Boolean(signatureDataUrl);
const downloadUrl = organizationId
? `/api/settings/billing/baa/download?organizationId=${organizationId}`
@@ -175,7 +295,40 @@ export function SignedBaaCard() {
</CardDescription>
</CardHeader>
<div className="flex flex-wrap gap-5 justify-between items-center pt-4 mt-auto">
- {isLoading ? (
+ {verificationPending ? (
+ <output className="text-sm text-gray-11">
+ Confirming your BAA payment...
+ </output>
+ ) : verificationError ? (
+ <div className="flex flex-col gap-3 text-sm text-gray-11">
+ <p role="alert">{verificationError}</p>
+ <p>Do not pay again. We need to verify your existing payment.</p>
+ {sessionId && (
+ <Button
+ type="button"
+ size="sm"
+ variant="gray"
+ onClick={() => paymentConfirmation.refetch()}
+ >
+ Retry payment confirmation
+ </Button>
+ )}
+ </div>
+ ) : statusFailed ? (
+ <div className="flex flex-col gap-3 text-sm text-gray-11">
+ <p role="alert">
+ Unable to load your BAA status. Please try again.
+ </p>
+ <Button
+ type="button"
+ size="sm"
+ variant="gray"
+ onClick={() => refetchStatus()}
+ >
+ Retry
+ </Button>
+ </div>
+ ) : isLoading ? (
<div className="h-5 w-64 rounded animate-pulse bg-gray-4" />
) : isActive ? (
<>
@@ -201,6 +354,30 @@ export function SignedBaaCard() {
Download signed copy
</Button>
</>
+ ) : isPaid ? (
+ <>
+ <div className="flex flex-col gap-1 text-sm text-gray-11">
+ <span className="font-medium text-gray-12">
+ Paid — awaiting signature
+ </span>
+ <span>
+ Payment received. Complete your details and sign your agreement.
+ </span>
+ </div>
+ <Button
+ type="button"
+ size="sm"
+ variant="primary"
+ disabled={actionsBlocked || signatureMutation.isPending}
+ onClick={openDialog}
+ >
+ Complete and sign BAA
+ </Button>
+ </>
+ ) : isProcessing ? (
+ <output className="text-sm text-gray-11">
+ Your BAA is processing. Please wait before trying again.
+ </output>
) : (
<>
<div className="flex flex-col gap-1 text-sm text-gray-11">
@@ -218,7 +395,7 @@ export function SignedBaaCard() {
type="button"
size="sm"
variant="primary"
- disabled={!canPurchase}
+ disabled={actionsBlocked || signatureMutation.isPending}
onClick={openDialog}
>
Get Signed BAA
@@ -228,9 +405,9 @@ export function SignedBaaCard() {
</div>
<Dialog
- open={dialogOpen}
+ open={dialogOpen && !verificationBlocked && !isActive}
onOpenChange={(open) => {
- if (!purchaseMutation.isPending) setDialogOpen(open);
+ if (!signatureMutation.isPending) setDialogOpen(open);
}}
>
<DialogContent className="p-0 w-[calc(100%-20px)] max-w-lg rounded-xl border bg-gray-2 border-gray-4">
@@ -263,7 +440,7 @@ export function SignedBaaCard() {
value={form[field.key]}
placeholder={field.placeholder}
onChange={updateField(field.key)}
- disabled={purchaseMutation.isPending}
+ disabled={actionsBlocked || signatureMutation.isPending}
/>
</div>
))}
@@ -273,20 +450,30 @@ export function SignedBaaCard() {
Signature
</span>
<SignaturePad
- onChange={setSignature}
- disabled={purchaseMutation.isPending}
+ key={isPaid ? "paid" : "purchase"}
+ onChange={(dataUrl) =>
+ setSignature(dataUrl ? { paid: isPaid, dataUrl } : null)
+ }
+ disabled={actionsBlocked || signatureMutation.isPending}
/>
</div>
</div>
<div className="flex flex-col gap-4 p-5 border-t border-gray-4">
<p className="text-xs leading-5 text-gray-11">
- By signing, you execute the Business Associate Agreement and
- authorize Cap to charge the card on file{" "}
- <span className="font-medium text-gray-12">$99/month</span>{" "}
- starting today. This is a separate subscription from Cap Pro and
- is not prorated. Once purchased, the Signed BAA can't be disabled;
- it ends automatically if your Cap Pro subscription is canceled. A
- countersigned PDF will be emailed to you and [email protected].
+ {isPaid ? (
+ "Payment has already been received. Signing completes your Business Associate Agreement with no additional charge. Your existing $99/month BAA subscription continues on its current billing schedule, separately from Cap Pro, and ends if your Cap Pro subscription is canceled."
+ ) : (
+ <>
+ By signing, you execute the Business Associate Agreement and
+ authorize Cap to charge the card on file{" "}
+ <span className="font-medium text-gray-12">$99/month</span>{" "}
+ starting today. This is a separate subscription from Cap Pro
+ and is not prorated. Once purchased, the Signed BAA can't be
+ disabled; it ends automatically if your Cap Pro subscription
+ is canceled.
+ </>
+ )}{" "}
+ A countersigned PDF will be emailed to you and [email protected].
</p>
<div className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
<Button
@@ -294,7 +481,7 @@ export function SignedBaaCard() {
size="sm"
variant="gray"
onClick={() => setDialogOpen(false)}
- disabled={purchaseMutation.isPending}
+ disabled={signatureMutation.isPending}
>
Cancel
</Button>
@@ -302,13 +489,17 @@ export function SignedBaaCard() {
type="button"
size="sm"
variant="primary"
- spinner={purchaseMutation.isPending}
- disabled={!formValid || purchaseMutation.isPending}
- onClick={() => purchaseMutation.mutate()}
+ spinner={signatureMutation.isPending}
+ disabled={
+ !formValid || actionsBlocked || signatureMutation.isPending
+ }
+ onClick={() => signatureMutation.mutate()}
>
- {purchaseMutation.isPending
+ {signatureMutation.isPending
? "Processing..."
- : "Sign & pay $99/mo"}
+ : isPaid
+ ? "Sign BAA"
+ : "Sign & pay $99/mo"}
</Button>
</div>
</div>
diff --git a/apps/web/app/api/webhooks/stripe/route.ts b/apps/web/app/api/webhooks/stripe/route.ts
index afbeba3e0..077e88796 100644
--- a/apps/web/app/api/webhooks/stripe/route.ts
+++ b/apps/web/app/api/webhooks/stripe/route.ts
@@ -10,9 +10,16 @@ import {
import { serverEnv } from "@cap/env";
import { stripe } from "@cap/utils";
import { Organisation, User } from "@cap/web-domain";
-import { and, eq, isNull, or } from "drizzle-orm";
+import { and, eq, isNull, ne, or, sql } from "drizzle-orm";
import { NextResponse } from "next/server";
import type Stripe from "stripe";
+import {
+ attachPaidBaaCheckout,
+ ensureBaaHasPro,
+ hasPaidBaaInvoice,
+ isSignedBaaPrice,
+ isSignedBaaSubscription,
+} from "@/lib/baa/billing";
import { addCreditsToAccount } from "@/lib/developer-credits";
import { trackServerEvent } from "@/lib/server-analytics";
@@ -99,13 +106,9 @@ const ENTITLED_SUBSCRIPTION_STATUSES = new Set([
"past_due",
]);
-// The Signed BAA add-on lives on its own subscription for the same customer.
+// The Signed BAA add-on lives on its own subscription.
// It must never be treated as the Pro subscription: it would otherwise
// overwrite users.stripeSubscriptionId/Status and inflate the seat quota.
-function isSignedBaaSubscription(subscription: Stripe.Subscription) {
- return subscription.metadata?.type === "signed_baa";
-}
-
function hasEntitledProSubscription(subscriptions: Stripe.Subscription[]) {
return subscriptions.some(
(sub) =>
@@ -116,10 +119,37 @@ function hasEntitledProSubscription(subscriptions: Stripe.Subscription[]) {
async function cancelEntitledBaaSubscriptions(
subscriptions: Stripe.Subscription[],
+ customerId: string,
) {
+ const linked = await db()
+ .select({ subscriptionId: signedBaas.stripeSubscriptionId })
+ .from(signedBaas)
+ .innerJoin(users, eq(signedBaas.userId, users.id))
+ .where(
+ and(
+ eq(users.stripeCustomerId, customerId),
+ ne(signedBaas.status, "canceled"),
+ ),
+ )
+ .limit(100);
+ const allSubscriptions = [...subscriptions];
+ for (const record of linked) {
+ if (
+ record.subscriptionId &&
+ !allSubscriptions.some((sub) => sub.id === record.subscriptionId)
+ ) {
+ const subscription = await stripe().subscriptions.retrieve(
+ record.subscriptionId,
+ );
+ if (!isSignedBaaSubscription(subscription)) {
+ throw new Error("Refusing to cancel a non-BAA subscription.");
+ }
+ allSubscriptions.push(subscription);
+ }
+ }
// BAA terms end with the services agreement, so the add-on must stop
// billing when no entitled Pro subscription remains.
- for (const sub of subscriptions) {
+ for (const sub of allSubscriptions) {
if (!isSignedBaaSubscription(sub)) continue;
if (ENTITLED_SUBSCRIPTION_STATUSES.has(sub.status)) {
await stripe().subscriptions.cancel(sub.id);
@@ -135,34 +165,94 @@ async function cancelEntitledBaaSubscriptions(
}
async function syncSignedBaaStatus(
- subscription: Stripe.Subscription,
+ eventSubscription: Stripe.Subscription,
): Promise<Response> {
- const status = ENTITLED_SUBSCRIPTION_STATUSES.has(subscription.status)
- ? "active"
- : "canceled";
+ const subscription = await stripe().subscriptions.retrieve(
+ eventSubscription.id,
+ { expand: ["latest_invoice"] },
+ );
+ const entitled = ENTITLED_SUBSCRIPTION_STATUSES.has(subscription.status);
+ const unsignedStatus = hasPaidBaaInvoice(subscription) ? "paid" : "pending";
const organizationId = subscription.metadata?.organizationId
? Organisation.OrganisationId.make(subscription.metadata.organizationId)
: undefined;
+ if (entitled) {
+ await db()
+ .update(signedBaas)
+ .set({
+ stripeSubscriptionId: subscription.id,
+ updatedAt: sql`CASE WHEN ${signedBaas.status} = 'processing' THEN ${signedBaas.updatedAt} ELSE CURRENT_TIMESTAMP END`,
+ })
+ .where(
+ and(
+ ne(signedBaas.status, "canceled"),
+ organizationId
+ ? or(
+ eq(signedBaas.stripeSubscriptionId, subscription.id),
+ and(
+ eq(signedBaas.organizationId, organizationId),
+ isNull(signedBaas.stripeSubscriptionId),
+ ),
+ )
+ : eq(signedBaas.stripeSubscriptionId, subscription.id),
+ ),
+ );
+ const records = await db()
+ .select()
+ .from(signedBaas)
+ .where(eq(signedBaas.stripeSubscriptionId, subscription.id))
+ .limit(2);
+ if (records.length === 0) {
+ return NextResponse.json({ received: true });
+ }
+ const [record] = records;
+ if (records.length !== 1 || !record) {
+ throw new Error("The BAA subscription is linked to multiple records.");
+ }
+ if (
+ subscription.metadata?.userId &&
+ subscription.metadata.userId !== record.userId
+ ) {
+ throw new Error("The BAA subscription belongs to a different account.");
+ }
+ const [owner] = await db()
+ .select({
+ stripeCustomerId: users.stripeCustomerId,
+ stripeSubscriptionId: users.stripeSubscriptionId,
+ })
+ .from(users)
+ .where(eq(users.id, record.userId))
+ .limit(1);
+ if (!owner) {
+ throw new Error("The BAA owner could not be found.");
+ }
+ if (!(await ensureBaaHasPro(owner, subscription, record.id))) {
+ return NextResponse.json({ received: true });
+ }
+ }
await db()
.update(signedBaas)
.set({
- status,
+ status: entitled
+ ? sql`CASE
+ WHEN ${signedBaas.status} = 'processing' THEN 'processing'
+ WHEN ${signedBaas.signedAt} IS NOT NULL THEN 'active'
+ WHEN ${signedBaas.status} = 'paid' THEN 'paid'
+ ELSE ${unsignedStatus}
+ END`
+ : "canceled",
stripeSubscriptionId: subscription.id,
+ updatedAt: sql`CASE WHEN ${signedBaas.status} = 'processing' AND ${entitled} THEN ${signedBaas.updatedAt} ELSE CURRENT_TIMESTAMP END`,
})
.where(
- organizationId
- ? or(
- eq(signedBaas.stripeSubscriptionId, subscription.id),
- and(
- eq(signedBaas.organizationId, organizationId),
- isNull(signedBaas.stripeSubscriptionId),
- ),
- )
- : eq(signedBaas.stripeSubscriptionId, subscription.id),
+ and(
+ ...(entitled ? [ne(signedBaas.status, "canceled")] : []),
+ eq(signedBaas.stripeSubscriptionId, subscription.id),
+ ),
);
console.log("Signed BAA subscription synced", {
subscriptionId: subscription.id,
- status,
+ status: subscription.status,
});
return NextResponse.json({ received: true });
}
@@ -287,6 +377,34 @@ export const POST = async (req: Request) => {
if (relevantEvents.has(event.type)) {
try {
+ let checkoutSubscription: Stripe.Subscription | undefined;
+ if (
+ event.type === "checkout.session.completed" ||
+ event.type === "checkout.session.async_payment_succeeded"
+ ) {
+ const session = event.data.object as Stripe.Checkout.Session;
+ const subscriptionId =
+ typeof session.subscription === "string"
+ ? session.subscription
+ : session.subscription?.id;
+ if (subscriptionId) {
+ checkoutSubscription =
+ await stripe().subscriptions.retrieve(subscriptionId);
+ if (isSignedBaaSubscription(checkoutSubscription)) {
+ const record = await attachPaidBaaCheckout(
+ session,
+ checkoutSubscription,
+ );
+ if (!record && session.payment_status === "paid") {
+ console.error("Paid BAA checkout needs reconciliation", {
+ sessionId: session.id,
+ subscriptionId,
+ });
+ }
+ return NextResponse.json({ received: true });
+ }
+ }
+ }
if (event.type === "checkout.session.completed") {
console.log("Processing checkout.session.completed event");
const session = event.data.object as Stripe.Checkout.Session;
@@ -375,9 +493,11 @@ export const POST = async (req: Request) => {
name: dbUser.name,
});
- const subscription = await stripe().subscriptions.retrieve(
- session.subscription as string,
- );
+ const subscription =
+ checkoutSubscription ??
+ (await stripe().subscriptions.retrieve(
+ session.subscription as string,
+ ));
console.log("Retrieved subscription:", {
id: subscription.id,
status: subscription.status,
@@ -514,7 +634,7 @@ export const POST = async (req: Request) => {
// when the customer cannot be mapped to a user; the 202 below is
// treated as delivered and the event is never redelivered.
if (!hasEntitledProSubscription(subscriptions.data)) {
- await cancelEntitledBaaSubscriptions(subscriptions.data);
+ await cancelEntitledBaaSubscriptions(subscriptions.data, customer.id);
}
if (!dbUser) {
@@ -595,7 +715,10 @@ export const POST = async (req: Request) => {
// Signed BAA renewals must not trigger the Cap Pro dunning email;
// its status is tracked via customer.subscription.updated instead.
- if (invoice.subscription_details?.metadata?.type === "signed_baa") {
+ if (
+ invoice.subscription_details?.metadata?.type === "signed_baa" ||
+ invoice.lines?.data.some((line) => isSignedBaaPrice(line.price?.id))
+ ) {
return NextResponse.json({ received: true });
}
@@ -680,7 +803,10 @@ export const POST = async (req: Request) => {
limit: 100,
});
if (!hasEntitledProSubscription(remainingSubscriptions.data)) {
- await cancelEntitledBaaSubscriptions(remainingSubscriptions.data);
+ await cancelEntitledBaaSubscriptions(
+ remainingSubscriptions.data,
+ customer.id,
+ );
}
let foundUserId: User.UserId | undefined;
diff --git a/apps/web/lib/baa/billing.ts b/apps/web/lib/baa/billing.ts
new file mode 100644
index 000000000..0efb4764f
--- /dev/null
+++ b/apps/web/lib/baa/billing.ts
@@ -0,0 +1,314 @@
+import { db } from "@cap/database";
+import { organizations, signedBaas, users } from "@cap/database/schema";
+import { STRIPE_SIGNED_BAA_PRICE_IDS, stripe } from "@cap/utils";
+import type { Organisation, User } from "@cap/web-domain";
+import { and, eq, isNull, ne, or } from "drizzle-orm";
+import type Stripe from "stripe";
+
+export const BAA_ENTITLED_STATUSES = new Set([
+ "active",
+ "trialing",
+ "past_due",
+]);
+
+export function isSignedBaaPrice(priceId: string | undefined) {
+ return Boolean(
+ priceId && Object.values(STRIPE_SIGNED_BAA_PRICE_IDS).includes(priceId),
+ );
+}
+
+export function isSignedBaaSubscription(subscription: Stripe.Subscription) {
+ return (
+ subscription.metadata?.type === "signed_baa" ||
+ subscription.items?.data.some((item) =>
+ isSignedBaaPrice(item.price?.id),
+ ) === true
+ );
+}
+
+export function hasPaidBaaInvoice(subscription: Stripe.Subscription) {
+ const invoice = subscription.latest_invoice;
+ return Boolean(
+ invoice && typeof invoice !== "string" && invoice.status === "paid",
+ );
+}
+
+type CheckoutOwner = {
+ id: User.UserId;
+ email: string;
+ stripeCustomerId: string | null;
+ stripeSubscriptionId: string | null;
+};
+
+export async function ensureBaaHasPro(
+ owner: Pick<CheckoutOwner, "stripeCustomerId" | "stripeSubscriptionId">,
+ subscription: Stripe.Subscription,
+ recordId: string,
+) {
+ if (!isSignedBaaSubscription(subscription)) {
+ throw new Error("The subscription is not a Signed BAA.");
+ }
+ const proSubscription = owner.stripeSubscriptionId
+ ? await stripe().subscriptions.retrieve(owner.stripeSubscriptionId)
+ : null;
+ const proCustomerId = proSubscription
+ ? typeof proSubscription.customer === "string"
+ ? proSubscription.customer
+ : proSubscription.customer.id
+ : null;
+ if (
+ proSubscription &&
+ proCustomerId === owner.stripeCustomerId &&
+ !isSignedBaaSubscription(proSubscription) &&
+ BAA_ENTITLED_STATUSES.has(proSubscription.status)
+ ) {
+ return true;
+ }
+ await stripe().subscriptions.cancel(subscription.id);
+ await db()
+ .update(signedBaas)
+ .set({ status: "canceled" })
+ .where(
+ and(
+ eq(signedBaas.id, recordId),
+ eq(signedBaas.stripeSubscriptionId, subscription.id),
+ ),
+ );
+ return false;
+}
+
+async function cancelDuplicateBaa(
+ subscription: Stripe.Subscription,
+ previous: typeof signedBaas.$inferSelect,
+) {
+ if (
+ !previous.stripeSubscriptionId ||
+ previous.stripeSubscriptionId === subscription.id
+ )
+ return false;
+ const previousSubscription = await stripe().subscriptions.retrieve(
+ previous.stripeSubscriptionId,
+ );
+ if (
+ !isSignedBaaSubscription(previousSubscription) ||
+ !BAA_ENTITLED_STATUSES.has(previousSubscription.status)
+ )
+ return false;
+ await stripe().subscriptions.cancel(subscription.id);
+ console.warn("Canceled duplicate Signed BAA subscription", {
+ subscriptionId: subscription.id,
+ existingSubscriptionId: previousSubscription.id,
+ });
+ return true;
+}
+
+export async function attachPaidBaaCheckout(
+ session: Stripe.Checkout.Session,
+ subscription: Stripe.Subscription,
+ expected?: {
+ owner: CheckoutOwner;
+ organizationId: Organisation.OrganisationId;
+ },
+) {
+ if (
+ session.mode !== "subscription" ||
+ session.status !== "complete" ||
+ session.payment_status !== "paid" ||
+ !isSignedBaaSubscription(subscription) ||
+ !subscription.items?.data.some((item) =>
+ isSignedBaaPrice(item.price?.id),
+ ) ||
+ !BAA_ENTITLED_STATUSES.has(subscription.status)
+ ) {
+ return null;
+ }
+
+ const customerId =
+ typeof session.customer === "string"
+ ? session.customer
+ : session.customer?.id;
+ const subscriptionCustomerId =
+ typeof subscription.customer === "string"
+ ? subscription.customer
+ : subscription.customer.id;
+ const subscriptionId =
+ typeof session.subscription === "string"
+ ? session.subscription
+ : session.subscription?.id;
+ if (
+ !customerId ||
+ customerId !== subscriptionCustomerId ||
+ subscriptionId !== subscription.id
+ ) {
+ throw new Error("The checkout does not match the BAA subscription.");
+ }
+
+ const email = (
+ session.customer_details?.email ??
+ session.customer_email ??
+ ""
+ )
+ .trim()
+ .toLowerCase();
+ let owner = expected?.owner;
+ if (!owner) {
+ const matches = await db()
+ .select()
+ .from(users)
+ .where(
+ or(
+ eq(users.stripeCustomerId, customerId),
+ ...(email ? [eq(users.email, email)] : []),
+ ),
+ )
+ .limit(2);
+ if (matches.length !== 1) return null;
+ owner = matches[0];
+ }
+ if (
+ !owner ||
+ (owner.stripeCustomerId !== customerId &&
+ owner.email.toLowerCase() !== email) ||
+ (subscription.metadata?.userId && subscription.metadata.userId !== owner.id)
+ ) {
+ throw new Error("This BAA payment belongs to a different account.");
+ }
+
+ const linked = await db()
+ .select()
+ .from(signedBaas)
+ .where(eq(signedBaas.stripeSubscriptionId, subscription.id))
+ .limit(2);
+ const records = linked.length
+ ? linked
+ : await db()
+ .select()
+ .from(signedBaas)
+ .where(
+ and(
+ eq(signedBaas.userId, owner.id),
+ isNull(signedBaas.stripeSubscriptionId),
+ eq(signedBaas.status, "pending"),
+ ...(subscription.metadata?.organizationId
+ ? [
+ eq(
+ signedBaas.organizationId,
+ subscription.metadata
+ .organizationId as Organisation.OrganisationId,
+ ),
+ ]
+ : []),
+ ),
+ )
+ .limit(2);
+ const record = records[0];
+ if (records.length !== 1 || !record) {
+ if (records.length !== 0) return null;
+ const organizationId =
+ expected?.organizationId ?? subscription.metadata?.organizationId;
+ const existing = await db()
+ .select()
+ .from(signedBaas)
+ .where(
+ and(
+ eq(signedBaas.userId, owner.id),
+ ne(signedBaas.status, "canceled"),
+ ...(organizationId
+ ? [
+ eq(
+ signedBaas.organizationId,
+ organizationId as Organisation.OrganisationId,
+ ),
+ ]
+ : []),
+ ),
+ )
+ .limit(2);
+ const previous = existing[0];
+ if (
+ existing.length !== 1 ||
+ !previous?.stripeSubscriptionId ||
+ previous.stripeSubscriptionId === subscription.id
+ )
+ return null;
+ const [organization] = await db()
+ .select({ ownerId: organizations.ownerId })
+ .from(organizations)
+ .where(eq(organizations.id, previous.organizationId))
+ .limit(1);
+ if (organization?.ownerId !== owner.id) return null;
+ return (await cancelDuplicateBaa(subscription, previous)) ? previous : null;
+ }
+ if (
+ record.userId !== owner.id ||
+ (expected && record.organizationId !== expected.organizationId) ||
+ (subscription.metadata?.organizationId &&
+ record.organizationId !== subscription.metadata.organizationId)
+ ) {
+ throw new Error("This BAA payment belongs to a different organization.");
+ }
+ const [organization] = await db()
+ .select({ ownerId: organizations.ownerId })
+ .from(organizations)
+ .where(eq(organizations.id, record.organizationId))
+ .limit(1);
+ if (organization?.ownerId !== owner.id) {
+ throw new Error("Only the organization owner can confirm the BAA payment.");
+ }
+ if (record.status === "canceled") return null;
+ let attached = record;
+ if (record.stripeSubscriptionId !== subscription.id) {
+ await db()
+ .update(signedBaas)
+ .set({ stripeSubscriptionId: subscription.id })
+ .where(
+ and(
+ eq(signedBaas.id, record.id),
+ eq(signedBaas.status, "pending"),
+ isNull(signedBaas.stripeSubscriptionId),
+ ),
+ );
+ const [result] = await db()
+ .select()
+ .from(signedBaas)
+ .where(eq(signedBaas.id, record.id))
+ .limit(1);
+ if (result?.stripeSubscriptionId !== subscription.id) {
+ if (result && (await cancelDuplicateBaa(subscription, result)))
+ return result;
+ throw new Error(
+ "The BAA changed while confirming payment. Please refresh or contact support.",
+ );
+ }
+ attached = result;
+ }
+
+ // Link before checking Pro so a concurrent Pro cancellation can find this
+ // subscription even when Checkout created a different Stripe customer.
+ if (!(await ensureBaaHasPro(owner, subscription, record.id))) {
+ return null;
+ }
+ if (attached.status !== "pending") return attached;
+
+ await db()
+ .update(signedBaas)
+ .set({ status: "paid" })
+ .where(
+ and(
+ eq(signedBaas.id, record.id),
+ eq(signedBaas.status, "pending"),
+ eq(signedBaas.stripeSubscriptionId, subscription.id),
+ ),
+ );
+ const [confirmed] = await db()
+ .select()
+ .from(signedBaas)
+ .where(eq(signedBaas.id, record.id))
+ .limit(1);
+ if (confirmed?.stripeSubscriptionId !== subscription.id) {
+ throw new Error(
+ "The BAA changed while confirming payment. Please refresh or contact support.",
+ );
+ }
+ return confirmed;
+}