302 lines
12 KiB
TypeScript
302 lines
12 KiB
TypeScript
// @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(),
|
|
resolveTenantBillingState: vi.fn(),
|
|
runWithRlsContext: vi.fn((_context: unknown, operation: () => unknown) => operation()),
|
|
}));
|
|
|
|
vi.mock("@hivegrid/db/rls-context.server", () => ({
|
|
runWithRlsContext: (...args: unknown[]) => mocks.runWithRlsContext(...args),
|
|
}));
|
|
vi.mock("@hivegrid/db/billing-domain.server", () => ({
|
|
resolveTenantBillingState: (...args: unknown[]) => mocks.resolveTenantBillingState(...args),
|
|
}));
|
|
|
|
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("@hivegrid/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,
|
|
status: {
|
|
status: "paid",
|
|
amountCents: 23_681,
|
|
planCode: "starter",
|
|
billingCadence: "monthly",
|
|
officeSeatQuantity: 2,
|
|
fieldSeatQuantity: 5,
|
|
storageAddOnCodes: [],
|
|
currency: "EUR",
|
|
},
|
|
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<Response>;
|
|
}
|
|
|
|
async function captureRedirect(promise: Promise<unknown>) {
|
|
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);
|
|
mocks.resolveTenantBillingState.mockResolvedValue({
|
|
status: "active",
|
|
trialEndsAt: null,
|
|
currentPeriodEnd: new Date("2026-07-27T00:00:00.000Z"),
|
|
});
|
|
});
|
|
|
|
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,
|
|
checkoutReceipt: {
|
|
subscriptionStatus: "active",
|
|
trialEndsAt: null,
|
|
currentPeriodEnd: "2026-07-27T00:00:00.000Z",
|
|
amountCents: 23_681,
|
|
recurringGrossTotalCents: 23_681,
|
|
currency: "EUR",
|
|
billingCadence: "monthly",
|
|
},
|
|
})
|
|
);
|
|
expect(mocks.verifyUserHasPermission).toHaveBeenCalledWith(req, "app.settings.subscription.update", tenantId);
|
|
expect(mocks.runWithRlsContext).toHaveBeenCalledWith({ userId }, expect.any(Function));
|
|
expect(mocks.runWithRlsContext).toHaveBeenCalledWith({ tenantId, userId }, expect.any(Function));
|
|
expect(mocks.persistCheckoutSessionStatus).toHaveBeenCalledWith({
|
|
request: req,
|
|
id: params.session,
|
|
fromUrl: "/subscribe/acme/cs_test_123/success",
|
|
fromUserId: userId,
|
|
tenantId,
|
|
});
|
|
expect(mocks.getAcquiredItemsFromCheckoutSession).toHaveBeenCalledWith(params.session, { tenantId });
|
|
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");
|
|
expect(mocks.resolveTenantBillingState).toHaveBeenCalledWith(tenantId);
|
|
});
|
|
|
|
it("normalizes an annual provider variant before calculating the gross receipt total", async () => {
|
|
mocks.getAcquiredItemsFromCheckoutSession.mockResolvedValueOnce({
|
|
...checkoutSession,
|
|
status: {
|
|
...checkoutSession.status,
|
|
amountCents: 53_431,
|
|
planCode: "pro_annual_sepa",
|
|
billingCadence: "annual_sepa",
|
|
officeSeatQuantity: 5,
|
|
fieldSeatQuantity: 15,
|
|
},
|
|
});
|
|
|
|
const response = await callLoader();
|
|
const data = await response.json();
|
|
|
|
expect(data.checkoutReceipt).toMatchObject({
|
|
amountCents: 53_431,
|
|
recurringGrossTotalCents: 53_431,
|
|
currency: "EUR",
|
|
billingCadence: "annual_sepa",
|
|
});
|
|
});
|
|
|
|
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 the session cannot be resolved", async () => {
|
|
mocks.getAcquiredItemsFromCheckoutSession.mockResolvedValueOnce(null);
|
|
|
|
const response = await callLoader();
|
|
const data = await response.json();
|
|
|
|
expect(data).toEqual(
|
|
expect.objectContaining({
|
|
title: "t:pricing.subscribe | ToolCtrl",
|
|
currentTenant: tenant,
|
|
checkoutSession: null,
|
|
checkoutState: "invalid",
|
|
})
|
|
);
|
|
expect(mocks.persistCheckoutSessionStatus).toHaveBeenCalledTimes(1);
|
|
expect(mocks.addTenantProductsFromCheckoutSession).not.toHaveBeenCalled();
|
|
expect(mocks.createLog).not.toHaveBeenCalled();
|
|
expect(mocks.resolveTenantBillingState).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it.each([
|
|
["pending", "processing"],
|
|
["canceled", "cancelled"],
|
|
["failed", "failed"],
|
|
["expired", "expired"],
|
|
] as const)("projects Mollie %s without activating the workspace", async (providerStatus, checkoutState) => {
|
|
mocks.getAcquiredItemsFromCheckoutSession.mockResolvedValueOnce({
|
|
...checkoutSession,
|
|
status: { ...checkoutSession.status, status: providerStatus, pending: true },
|
|
});
|
|
|
|
const response = await callLoader();
|
|
const data = await response.json();
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(data).toMatchObject({ checkoutState, checkoutReceipt: null });
|
|
expect(mocks.addTenantProductsFromCheckoutSession).not.toHaveBeenCalled();
|
|
expect(mocks.createLog).not.toHaveBeenCalled();
|
|
expect(mocks.resolveTenantBillingState).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();
|
|
expect(mocks.resolveTenantBillingState).not.toHaveBeenCalled();
|
|
});
|
|
});
|