Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/routes/admin/system/billing.test.ts
T

132 lines
5.6 KiB
TypeScript

// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { getTranslations } from "~/locale/i18next.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
import { getUser } from "~/utils/db/users.db.server";
import { listAdminBillingRows, requestManualBillingSync, setTenantBillingPlanSeats } from "~/services/admin/billing-admin.server";
import { action, loader } from "./billing";
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string, params?: Record<string, string>) => (params?.provider ? `${key}:${params.provider}` : key) }),
}));
vi.mock("~/components/ui/buttons/ButtonPrimary", () => ({ default: () => null }));
vi.mock("~/components/ui/buttons/ButtonSecondary", () => ({ default: () => null }));
vi.mock("~/components/ui/errors/ServerError", () => ({ default: () => null }));
vi.mock("~/components/ui/layouts/EditPageLayout", () => ({ default: () => null }));
vi.mock("~/utils/data/useRootData", () => ({ useRootData: () => ({ csrf: "csrf" }) }));
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn() }));
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: vi.fn() }));
vi.mock("~/utils/session.server", () => ({ getUserInfo: vi.fn(), validateCSRFToken: vi.fn() }));
vi.mock("~/utils/db/users.db.server", () => ({ getUser: vi.fn() }));
vi.mock("~/services/admin/billing-admin.server", async () => {
const actual = await vi.importActual<typeof import("~/services/admin/billing-admin.server")>("~/services/admin/billing-admin.server");
return {
...actual,
listAdminBillingRows: vi.fn(),
requestManualBillingSync: vi.fn(),
setTenantBillingPlanSeats: vi.fn(),
};
});
function requestWithForm(form: Record<string, string>) {
return new Request("https://admin.example.test/system/billing", {
method: "POST",
body: new URLSearchParams(form),
});
}
describe("admin accounts billing route", () => {
beforeEach(() => {
vi.clearAllMocks();
process.env.APP_NAME = "HiveGrid";
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
vi.mocked(getTranslations).mockResolvedValue({
t: (key: string, params?: Record<string, string>) => (params?.provider ? `${key}:${params.provider}` : key),
} as never);
vi.mocked(validateCSRFToken).mockResolvedValue(undefined as never);
vi.mocked(getUserInfo).mockResolvedValue({ userId: "user_1" } as never);
vi.mocked(getUser).mockResolvedValue({ id: "user_1", email: "ops@hivegrid.de" } as never);
vi.mocked(listAdminBillingRows).mockResolvedValue([
{
tenantId: "tenant_1",
tenantName: "Acme",
tenantSlug: "acme",
status: "active",
readOnly: false,
planCode: "starter",
seatQuantity: 3,
lagoCustomerId: "lago_1",
mollieCustomerId: "mollie_1",
lastInvoiceExternalId: "inv_1",
lastPaymentExternalId: "pay_1",
currentPeriodStart: null,
currentPeriodEnd: null,
pastDueSince: null,
frozenAt: null,
cancelledAt: null,
entitlementCount: 1,
},
] as never);
});
it("checks subscription permission before loading billing rows", async () => {
const body = await loader({
request: new Request("https://admin.example.test/system/billing"),
params: {},
context: {},
} as LoaderFunctionArgs);
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.account.subscription");
expect(vi.mocked(verifyUserHasPermission).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(listAdminBillingRows).mock.invocationCallOrder[0]);
expect(body.vm.status).toBe("ready");
expect(body.vm.data.rows[0].tenantName).toBe("Acme");
});
it("routes plan/seat override actions to the admin service", async () => {
vi.mocked(setTenantBillingPlanSeats).mockImplementationOnce(async () => {
expect(getRlsExecutionContext()?.tenantId).toBe("tenant_1");
});
const response = (await action({
request: requestWithForm({
csrf: "csrf",
action: "set-plan-seats",
tenantId: "tenant_1",
planCode: "pro",
seatQuantity: "7",
reason: "Sonderkunde",
}),
params: {},
context: {},
} as ActionFunctionArgs)) as Response;
await expect(response.json()).resolves.toEqual({ success: "admin.billing.actions.planSeatsUpdated" });
expect(setTenantBillingPlanSeats).toHaveBeenCalledWith(
expect.objectContaining({
tenantId: "tenant_1",
planCode: "pro",
seatQuantity: "7",
reason: "Sonderkunde",
actorUserId: "user_1",
actorEmail: "ops@hivegrid.de",
})
);
});
it("routes manual provider sync actions to the admin service", async () => {
vi.mocked(requestManualBillingSync).mockImplementationOnce(async () => {
expect(getRlsExecutionContext()?.tenantId).toBe("tenant_1");
});
const response = (await action({
request: requestWithForm({ csrf: "csrf", action: "request-sync", tenantId: "tenant_1", provider: "lago" }),
params: {},
context: {},
} as ActionFunctionArgs)) as Response;
await expect(response.json()).resolves.toEqual({ success: "admin.billing.actions.syncRequested:admin.billing.providers.lago" });
expect(requestManualBillingSync).toHaveBeenCalledWith(expect.objectContaining({ tenantId: "tenant_1", provider: "lago", actorUserId: "user_1" }));
});
});