252 lines
11 KiB
TypeScript
252 lines
11 KiB
TypeScript
// @vitest-environment node
|
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
|
|
|
const mocks = vi.hoisted(() => ({
|
|
getTranslations: vi.fn(),
|
|
getTenantIdFromUrl: vi.fn(),
|
|
verifyUserHasPermission: vi.fn(),
|
|
getUserInfo: vi.fn(),
|
|
getUser: vi.fn(),
|
|
getTenant: vi.fn(),
|
|
getOrPersistTenantSubscription: vi.fn(),
|
|
getTenantSubscription: vi.fn(),
|
|
cancelTenantSubscription: vi.fn(),
|
|
getPlanFeaturesUsage: vi.fn(),
|
|
validateCSRFToken: vi.fn(),
|
|
tenantHasModule: vi.fn(),
|
|
listCustomerBillingInvoices: vi.fn(),
|
|
getAllSubscriptionProducts: vi.fn(),
|
|
createSelfServiceCheckout: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
|
|
vi.mock("react-hot-toast", () => ({ default: { error: vi.fn(), success: vi.fn() } }));
|
|
vi.mock("~/components/ui/layouts/EditPageLayout", () => ({ default: () => null }));
|
|
vi.mock("~/modules/users/components/SubscriptionSettings", () => ({ default: () => null }));
|
|
vi.mock("~/utils/helpers/PermissionsHelper", () => ({ getUserHasPermission: vi.fn(() => true) }));
|
|
vi.mock("~/utils/data/useAppData", () => ({ useAppData: vi.fn(() => ({ mySubscription: null, currentTenant: { slug: "acme" } })) }));
|
|
vi.mock("~/modules/metrics/services/.server/MetricTracker", () => ({
|
|
createMetrics: vi.fn(async () => ({
|
|
time: async (value: unknown) => await value,
|
|
getServerTimingHeader: () => ({}),
|
|
})),
|
|
}));
|
|
vi.mock("~/modules/metrics/utils/defaultHeaders", () => ({ serverTimingHeaders: vi.fn() }));
|
|
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/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: (...args: unknown[]) => mocks.verifyUserHasPermission(...args) }));
|
|
vi.mock("~/utils/session.server", () => ({
|
|
getUserInfo: (...args: unknown[]) => mocks.getUserInfo(...args),
|
|
validateCSRFToken: (...args: unknown[]) => mocks.validateCSRFToken(...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/db/tenantSubscriptions.db.server", () => ({
|
|
getOrPersistTenantSubscription: (...args: unknown[]) => mocks.getOrPersistTenantSubscription(...args),
|
|
getTenantSubscription: (...args: unknown[]) => mocks.getTenantSubscription(...args),
|
|
}));
|
|
vi.mock("~/utils/services/.server/subscriptionService", () => ({
|
|
cancelTenantSubscription: (...args: unknown[]) => mocks.cancelTenantSubscription(...args),
|
|
getPlanFeaturesUsage: (...args: unknown[]) => mocks.getPlanFeaturesUsage(...args),
|
|
}));
|
|
vi.mock("~/utils/connector/tenantConnector.server", () => ({
|
|
tenantHasModule: (...args: unknown[]) => mocks.tenantHasModule(...args),
|
|
}));
|
|
vi.mock("~/services/billing/customer-invoices.server", () => ({
|
|
CustomerBillingInvoiceError: class CustomerBillingInvoiceError extends Error {
|
|
readonly i18nKey = "settings.subscription.errors.INVOICE_LIST_UNAVAILABLE";
|
|
},
|
|
listCustomerBillingInvoices: (...args: unknown[]) => mocks.listCustomerBillingInvoices(...args),
|
|
}));
|
|
vi.mock("~/utils/db/subscriptionProducts.db.server", () => ({
|
|
getAllSubscriptionProducts: (...args: unknown[]) => mocks.getAllSubscriptionProducts(...args),
|
|
}));
|
|
vi.mock("~/utils/helpers/PricingHelper", () => ({
|
|
getCurrenciesAndPeriods: (prices: unknown[]) => ({
|
|
currencies: { value: "eur", options: ["eur"] },
|
|
billingPeriods: { value: 3, options: [3] },
|
|
prices,
|
|
}),
|
|
}));
|
|
vi.mock("~/services/billing/self-service-checkout.server", () => ({
|
|
SelfServiceCheckoutError: class SelfServiceCheckoutError extends Error {
|
|
readonly i18nKey = "settings.subscription.errors.CHECKOUT_URL_MISSING";
|
|
},
|
|
createSelfServiceCheckout: (...args: unknown[]) => mocks.createSelfServiceCheckout(...args),
|
|
}));
|
|
import { action, loader } from "./subscription";
|
|
|
|
const tenantId = "tenant-1";
|
|
const userId = "user-1";
|
|
const params = { tenant: "acme" };
|
|
const tenantSubscription = {
|
|
billingProviderCustomerId: "cus_123",
|
|
products: [{ billingProviderSubscriptionId: "sub_123" }],
|
|
};
|
|
|
|
function formRequest(form: FormData) {
|
|
return new Request("https://app.example.test/app/acme/settings/subscription", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
body: new URLSearchParams(form as unknown as Record<string, string>),
|
|
});
|
|
}
|
|
|
|
function createForm(overrides: Record<string, string> = {}) {
|
|
const form = new FormData();
|
|
form.set("action", "cancel");
|
|
form.set("csrf", "csrf-token");
|
|
Object.entries(overrides).forEach(([key, value]) => form.set(key, value));
|
|
return form;
|
|
}
|
|
|
|
async function callAction(form: FormData) {
|
|
return action({
|
|
request: formRequest(form),
|
|
params,
|
|
context: {},
|
|
unstable_pattern: "app.$tenant/settings/subscription",
|
|
} as ActionFunctionArgs) as Promise<Response>;
|
|
}
|
|
|
|
describe("tenant subscription settings route", () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
mocks.getTranslations.mockResolvedValue({ t: (key: string) => key });
|
|
mocks.getTenantIdFromUrl.mockResolvedValue(tenantId);
|
|
mocks.verifyUserHasPermission.mockResolvedValue(undefined);
|
|
mocks.getUserInfo.mockResolvedValue({ userId });
|
|
mocks.getUser.mockResolvedValue({ id: userId, email: "user@example.test" });
|
|
mocks.getTenant.mockResolvedValue({ id: tenantId, name: "Acme", slug: "acme" });
|
|
mocks.getOrPersistTenantSubscription.mockResolvedValue(tenantSubscription);
|
|
mocks.getTenantSubscription.mockResolvedValue(tenantSubscription);
|
|
mocks.getPlanFeaturesUsage.mockResolvedValue([{ name: "seats" }]);
|
|
mocks.validateCSRFToken.mockResolvedValue(undefined);
|
|
mocks.tenantHasModule.mockResolvedValue(true);
|
|
mocks.listCustomerBillingInvoices.mockResolvedValue([
|
|
{
|
|
id: "invoice_1",
|
|
number: "LAG-001",
|
|
issuingDate: "2026-07-04",
|
|
amountCents: 4900,
|
|
currency: "EUR",
|
|
status: "finalized",
|
|
paymentStatus: "succeeded",
|
|
invoiceType: "subscription",
|
|
downloadHref: "/acme/settings/subscription/invoices/invoice_1/download",
|
|
},
|
|
]);
|
|
mocks.getAllSubscriptionProducts.mockResolvedValue([
|
|
{
|
|
id: "plan_grow",
|
|
billingProviderId: "local_product_grow",
|
|
order: 1,
|
|
title: "Grow",
|
|
description: null,
|
|
badge: null,
|
|
active: true,
|
|
model: 2,
|
|
public: true,
|
|
prices: [{ id: "price_grow_month", price: 49, currency: "eur", billingPeriod: 3 }],
|
|
features: [],
|
|
},
|
|
]);
|
|
mocks.createSelfServiceCheckout.mockResolvedValue({ checkoutUrl: "https://www.mollie.com/checkout/test" });
|
|
mocks.cancelTenantSubscription.mockResolvedValue(undefined);
|
|
});
|
|
|
|
it("loads local subscription feature usage", async () => {
|
|
mocks.verifyUserHasPermission.mockImplementation(async (_request: Request, permission: string) => {
|
|
if (permission === "app.settings.subscription.invoices.view") throw new Response("Forbidden", { status: 403 });
|
|
});
|
|
|
|
const response = await loader({
|
|
request: new Request("https://app.example.test/app/acme/settings/subscription"),
|
|
params,
|
|
context: {},
|
|
unstable_pattern: "app.$tenant/settings/subscription",
|
|
} as LoaderFunctionArgs);
|
|
const data = await response.json();
|
|
|
|
expect(data.myFeatures).toEqual([{ name: "seats" }]);
|
|
expect(data.canViewInvoices).toBe(false);
|
|
expect(data.availablePlans).toHaveLength(1);
|
|
expect(data.canManageSubscription).toBe(true);
|
|
expect(data.myInvoices).toEqual([]);
|
|
expect(mocks.listCustomerBillingInvoices).not.toHaveBeenCalled();
|
|
expect(mocks.getAllSubscriptionProducts).toHaveBeenCalledWith(true);
|
|
});
|
|
|
|
it("loads Lago invoices when the user may view subscription invoices", async () => {
|
|
const response = await loader({
|
|
request: new Request("https://app.example.test/app/acme/settings/subscription"),
|
|
params,
|
|
context: {},
|
|
unstable_pattern: "app.$tenant/settings/subscription",
|
|
} as LoaderFunctionArgs);
|
|
const data = await response.json();
|
|
|
|
expect(data.canViewInvoices).toBe(true);
|
|
expect(data.myInvoices).toEqual([
|
|
expect.objectContaining({
|
|
id: "invoice_1",
|
|
number: "LAG-001",
|
|
}),
|
|
]);
|
|
expect(mocks.listCustomerBillingInvoices).toHaveBeenCalledWith({ tenantId, tenantSlug: "acme" });
|
|
});
|
|
|
|
it("checks delete permission before cancelling a subscription product", async () => {
|
|
const response = await callAction(createForm({ action: "cancel", "tenant-subscription-product-id": "tsp_1" }));
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(mocks.verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "app.settings.subscription.update", tenantId);
|
|
expect(mocks.verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "app.settings.subscription.delete", tenantId);
|
|
expect(mocks.cancelTenantSubscription).toHaveBeenCalledWith("tsp_1", expect.objectContaining({ tenantId, userId }));
|
|
});
|
|
|
|
it("starts a self-service checkout and redirects to Mollie when a plan is selected", async () => {
|
|
const form = createForm({
|
|
action: "subscribe",
|
|
"product-id": "plan_grow",
|
|
"billing-period": "3",
|
|
currency: "eur",
|
|
quantity: "4",
|
|
"tenant-slug-context": "acme",
|
|
});
|
|
|
|
const response = await callAction(form);
|
|
|
|
expect(response.status).toBe(302);
|
|
expect(response.headers.get("Location")).toBe("https://www.mollie.com/checkout/test");
|
|
expect(mocks.createSelfServiceCheckout).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
tenantId,
|
|
tenantSlug: "acme",
|
|
tenantName: "Acme",
|
|
userId,
|
|
userEmail: "user@example.test",
|
|
productId: "plan_grow",
|
|
billingPeriod: 3,
|
|
currency: "eur",
|
|
quantity: 4,
|
|
})
|
|
);
|
|
});
|
|
|
|
it("keeps cancel internals out of tenant-facing errors", async () => {
|
|
mocks.cancelTenantSubscription.mockRejectedValueOnce(new Error("Payment provider raw failure"));
|
|
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
|
|
|
|
const response = await callAction(createForm({ action: "cancel", "tenant-subscription-product-id": "tsp_1" }));
|
|
const data = await response.json();
|
|
|
|
expect(response.status).toBe(400);
|
|
expect(data).toEqual({ error: "shared.unexpectedError" });
|
|
expect(JSON.stringify(data)).not.toContain("Payment provider raw failure");
|
|
expect(consoleError).toHaveBeenCalledWith(expect.any(Error));
|
|
consoleError.mockRestore();
|
|
});
|
|
});
|