// @vitest-environment node import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { LoaderFunctionArgs } from "react-router"; const mocks = vi.hoisted(() => ({ getTranslations: vi.fn(), getTenantIdFromUrl: vi.fn(), getUserInfo: vi.fn(), getUser: vi.fn(), getTenant: vi.fn(), verifyUserHasPermission: vi.fn(), persistCheckoutSessionStatus: vi.fn(), getAcquiredItemsFromCheckoutSession: vi.fn(), addTenantProductsFromCheckoutSession: vi.fn(), loadAppData: vi.fn(), createLog: vi.fn(), })); vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) })); vi.mock("~/components/brand/Logo", () => ({ default: () => null })); vi.mock("~/locale/format", () => ({ useLocaleFormatters: () => ({ currency: (amount: number, currency: string) => `${currency} ${amount}`, date: (date: Date) => date.toISOString(), }), })); vi.mock("~/modules/metrics/services/.server/MetricTracker", () => ({ createMetrics: vi.fn(async () => ({ time: async (value: unknown) => await value, getServerTimingHeader: () => ({ "Server-Timing": "test" }), })), })); vi.mock("~/locale/i18next.server", () => ({ getTranslations: (...args: unknown[]) => mocks.getTranslations(...args) })); vi.mock("~/utils/services/.server/urlService", () => ({ getTenantIdFromUrl: (...args: unknown[]) => mocks.getTenantIdFromUrl(...args) })); vi.mock("~/utils/session.server", () => ({ getUserInfo: (...args: unknown[]) => mocks.getUserInfo(...args) })); vi.mock("~/utils/db/users.db.server", () => ({ getUser: (...args: unknown[]) => mocks.getUser(...args) })); vi.mock("~/utils/db/tenants.db.server", () => ({ getTenant: (...args: unknown[]) => mocks.getTenant(...args) })); vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: (...args: unknown[]) => mocks.verifyUserHasPermission(...args), })); vi.mock("~/utils/services/.server/subscriptionService", () => ({ persistCheckoutSessionStatus: (...args: unknown[]) => mocks.persistCheckoutSessionStatus(...args), })); vi.mock("~/utils/services/.server/pricingService", () => ({ getAcquiredItemsFromCheckoutSession: (...args: unknown[]) => mocks.getAcquiredItemsFromCheckoutSession(...args), addTenantProductsFromCheckoutSession: (...args: unknown[]) => mocks.addTenantProductsFromCheckoutSession(...args), })); vi.mock("~/utils/data/.server/appData", () => ({ loadAppData: (...args: unknown[]) => mocks.loadAppData(...args) })); vi.mock("~/utils/db/logs.db.server", () => ({ createLog: (...args: unknown[]) => mocks.createLog(...args) })); vi.mock("@toolctrl/config", () => ({ loadRequiredWebConfig: vi.fn(() => ({ routing: {} })) })); vi.mock("~/utils/app/CrossHostUrls", () => ({ absoluteAppRootPath: vi.fn(() => "https://app.example.test/") })); vi.mock("~/utils/app/CanonicalUrlUtils", () => ({ appPath: vi.fn(({ tenantSlug, path }: { tenantSlug: string; path?: string }) => `/${tenantSlug}${path ? `/${path}` : ""}`), })); import { loader } from "./subscribe.$tenant.$session.success"; const tenantId = "tenant-1"; const userId = "user-1"; const params = { tenant: "acme", session: "cs_test_123" }; const user = { id: userId, email: "ada@example.test" }; const tenant = { id: tenantId, name: "Acme Inc.", slug: "acme" }; const checkoutSession = { id: params.session, products: [ { id: "product-pro", title: "pricing.products.pro", prices: [] }, { id: "product-team", title: "pricing.products.team", prices: [] }, ], }; function request(path = "/subscribe/acme/cs_test_123/success") { return new Request(`https://app.example.test${path}`); } function callLoader(req = request(), routeParams = params) { return loader({ request: req, params: routeParams, context: {}, unstable_pattern: "subscribe.$tenant.$session.success", } as LoaderFunctionArgs) as Promise; } async function captureRedirect(promise: Promise) { try { await promise; } catch (error) { return error as Response; } throw new Error("Expected loader to throw a redirect response"); } describe("subscribe.$tenant.$session.success loader", () => { beforeEach(() => { vi.clearAllMocks(); vi.spyOn(console, "log").mockImplementation(() => undefined); process.env.APP_NAME = "ToolCtrl"; mocks.getTranslations.mockResolvedValue({ t: (key: string) => `t:${key}`, }); mocks.getTenantIdFromUrl.mockResolvedValue(tenantId); mocks.getUserInfo.mockResolvedValue({ userId }); mocks.getUser.mockResolvedValue(user); mocks.getTenant.mockResolvedValue(tenant); mocks.verifyUserHasPermission.mockResolvedValue(undefined); mocks.persistCheckoutSessionStatus.mockResolvedValue(undefined); mocks.getAcquiredItemsFromCheckoutSession.mockResolvedValue(checkoutSession); mocks.addTenantProductsFromCheckoutSession.mockResolvedValue(undefined); mocks.loadAppData.mockResolvedValue({ currentTenant: tenant, user }); mocks.createLog.mockResolvedValue(undefined); }); afterEach(() => { vi.restoreAllMocks(); }); it("persists the checkout session, scopes product activation to the tenant, and returns success data", async () => { const req = request("/subscribe/acme/cs_test_123/success?ignored=true"); const response = await callLoader(req); const data = await response.json(); expect(response.status).toBe(200); expect(response.headers.get("Server-Timing")).toBe("test"); expect(data).toEqual( expect.objectContaining({ title: "t:pricing.subscribe | ToolCtrl", currentTenant: tenant, user, checkoutSession, }) ); expect(mocks.verifyUserHasPermission).toHaveBeenCalledWith(req, "app.settings.subscription.update", tenantId); expect(mocks.persistCheckoutSessionStatus).toHaveBeenCalledWith({ request: req, id: params.session, fromUrl: "/subscribe/acme/cs_test_123/success", fromUserId: userId, fromTenantId: tenantId, }); expect(mocks.getAcquiredItemsFromCheckoutSession).toHaveBeenCalledWith(params.session); expect(mocks.addTenantProductsFromCheckoutSession).toHaveBeenCalledWith( expect.objectContaining({ request: req, tenantId, user, checkoutSession, createdUserId: null, createdTenantId: null, }) ); expect(mocks.createLog).toHaveBeenCalledTimes(2); expect(mocks.createLog).toHaveBeenNthCalledWith(1, req, tenantId, "Subscribed", "t:pricing.products.pro"); expect(mocks.createLog).toHaveBeenNthCalledWith(2, req, tenantId, "Subscribed", "t:pricing.products.team"); }); it("redirects anonymous sessions to login before tenant mutation work", async () => { mocks.getUser.mockResolvedValueOnce(null); const response = await captureRedirect(callLoader()); expect(response.status).toBe(302); expect(response.headers.get("Location")).toBe("/login"); expect(mocks.getTenant).not.toHaveBeenCalled(); expect(mocks.verifyUserHasPermission).not.toHaveBeenCalled(); expect(mocks.persistCheckoutSessionStatus).not.toHaveBeenCalled(); expect(mocks.addTenantProductsFromCheckoutSession).not.toHaveBeenCalled(); }); it("redirects missing tenants to the app root before persisting checkout state", async () => { mocks.getTenant.mockResolvedValueOnce(null); const response = await captureRedirect(callLoader()); expect(response.status).toBe(302); expect(response.headers.get("Location")).toBe("https://app.example.test/"); expect(mocks.verifyUserHasPermission).not.toHaveBeenCalled(); expect(mocks.persistCheckoutSessionStatus).not.toHaveBeenCalled(); expect(mocks.addTenantProductsFromCheckoutSession).not.toHaveBeenCalled(); }); it("returns invalid checkout data without activating products when Stripe has no acquired items", async () => { mocks.getAcquiredItemsFromCheckoutSession.mockResolvedValueOnce(null); const response = (await callLoader()) as unknown as { title: string; currentTenant: typeof tenant; checkoutSession: null; }; expect(response).toEqual( expect.objectContaining({ title: "t:pricing.subscribe | ToolCtrl", currentTenant: tenant, checkoutSession: null, }) ); expect(mocks.persistCheckoutSessionStatus).toHaveBeenCalledTimes(1); expect(mocks.addTenantProductsFromCheckoutSession).not.toHaveBeenCalled(); expect(mocks.createLog).not.toHaveBeenCalled(); }); it("returns a safe 500 payload and does not write logs when tenant product activation fails", async () => { mocks.addTenantProductsFromCheckoutSession.mockRejectedValueOnce(new Error("activation failed")); const response = await callLoader(); const data = await response.json(); expect(response.status).toBe(500); expect(data).toEqual( expect.objectContaining({ currentTenant: tenant, checkoutSession, error: "t:shared.unexpectedError", }) ); expect(JSON.stringify(data)).not.toContain("activation failed"); expect(mocks.persistCheckoutSessionStatus).toHaveBeenCalledTimes(1); expect(mocks.createLog).not.toHaveBeenCalled(); }); });