Track HiveGrid Cloud planning reference
This commit is contained in:
1 parent
b3d5ea6764
commit
e341c5938a
5784 files changed
+1104929
-3
No files matched your search
@@ -0,0 +1,239 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ActionFunctionArgs } from "react-router";
|
||||
import { PricingModel } from "~/application/enums/subscriptions/PricingModel";
|
||||
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
vi.mock("~/components/core/settings/subscription/plans/PlansGrouped", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/modals/ErrorModal", () => ({ default: () => null }));
|
||||
vi.mock("~/utils/helpers/PermissionsHelper", () => ({ getUserHasPermission: vi.fn(() => true) }));
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/db/tenants.db.server", () => ({
|
||||
getTenant: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/db/users.db.server", () => ({
|
||||
getUser: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/session.server", () => ({
|
||||
requireUserId: vi.fn(),
|
||||
validateCSRFToken: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/services/.server/urlService", () => ({
|
||||
getTenantIdFromUrl: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
||||
verifyUserHasPermission: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/db/tenantSubscriptions.db.server", () => ({
|
||||
createTenantSubscription: vi.fn(),
|
||||
getTenantSubscription: vi.fn(),
|
||||
updateTenantSubscriptionCustomerId: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/db/subscriptionProducts.db.server", () => ({
|
||||
getSubscriptionProduct: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/stripe.server", () => ({
|
||||
createStripeCheckoutSession: vi.fn(),
|
||||
createStripeCustomer: vi.fn(),
|
||||
getStripeCoupon: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/url.server", () => ({
|
||||
getAbsoluteCurrentUrl: vi.fn(),
|
||||
getAbsoluteUrl: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/data/.server/appData", () => ({ loadAppData: vi.fn() }));
|
||||
vi.mock("@toolctrl/db/subscriptions.server", () => ({
|
||||
getAllSubscriptionProducts: vi.fn(),
|
||||
getSubscriptionProductsInIds: vi.fn(),
|
||||
}));
|
||||
vi.mock("@toolctrl/config", () => ({
|
||||
loadRequiredWebConfig: vi.fn(() => ({ routing: {} })),
|
||||
}));
|
||||
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getTenant } from "~/utils/db/tenants.db.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { getTenantSubscription, createTenantSubscription, updateTenantSubscriptionCustomerId } from "~/utils/db/tenantSubscriptions.db.server";
|
||||
import { getSubscriptionProduct } from "~/utils/db/subscriptionProducts.db.server";
|
||||
import { createStripeCheckoutSession, createStripeCustomer } from "~/utils/stripe.server";
|
||||
import { getAbsoluteCurrentUrl, getAbsoluteUrl } from "~/utils/url.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { requireUserId, validateCSRFToken } from "~/utils/session.server";
|
||||
import { action } from "./subscribe.$tenant";
|
||||
|
||||
const params = { tenant: "acme" };
|
||||
const tenant = { id: "tenant-1", name: "Acme Inc.", slug: "acme" };
|
||||
const user = { id: "user-1", email: "ada@example.test" };
|
||||
const product = {
|
||||
id: "product-pro",
|
||||
title: "Pro",
|
||||
model: PricingModel.FLAT_RATE,
|
||||
billingAddressCollection: "auto",
|
||||
prices: [
|
||||
{
|
||||
id: "price-db-1",
|
||||
stripeId: "price_stripe_monthly",
|
||||
currency: "usd",
|
||||
billingPeriod: SubscriptionBillingPeriod.MONTHLY,
|
||||
trialDays: 14,
|
||||
},
|
||||
],
|
||||
usageBasedPrices: [],
|
||||
};
|
||||
|
||||
function createForm(overrides: Record<string, string> = {}) {
|
||||
const form = new FormData();
|
||||
form.set("action", "subscribe");
|
||||
form.set("product-id", product.id);
|
||||
form.set("billing-period", SubscriptionBillingPeriod.MONTHLY.toString());
|
||||
form.set("currency", "usd");
|
||||
form.set("quantity", "3");
|
||||
form.set("tenant-slug-context", params.tenant);
|
||||
Object.entries(overrides).forEach(([key, value]) => form.set(key, value));
|
||||
return form;
|
||||
}
|
||||
|
||||
function createRequest(form: FormData) {
|
||||
return new Request("https://app.example.test/subscribe/acme", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams(form as unknown as Record<string, string>),
|
||||
});
|
||||
}
|
||||
|
||||
async function callAction(form: FormData) {
|
||||
return action({
|
||||
request: createRequest(form),
|
||||
params,
|
||||
context: {},
|
||||
unstable_pattern: "subscribe.$tenant",
|
||||
} as ActionFunctionArgs) as Promise<Response>;
|
||||
}
|
||||
|
||||
async function json(response: Response) {
|
||||
return response.json() as Promise<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
describe("subscribe.$tenant action checkout wiring", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(getTranslations).mockResolvedValue({
|
||||
t: (key: string, values?: Record<string, unknown>) => {
|
||||
const translations: Record<string, string> = {
|
||||
"settings.subscription.checkout.tenantMismatch":
|
||||
'Tenant mismatch: the form was rendered for "{{formTenantSlug}}" but submitted to "{{submittedTenantSlug}}". Refresh the page and try again.',
|
||||
"settings.subscription.checkout.updateFailed": "Could not update subscription.",
|
||||
"settings.subscription.errors.invalidStripeCustomer": "Invalid Stripe customer",
|
||||
};
|
||||
const template = translations[key];
|
||||
if (template) {
|
||||
return template.replace(/\{\{(\w+)\}\}/gu, (_match, name: string) => String(values?.[name] ?? ""));
|
||||
}
|
||||
return key;
|
||||
},
|
||||
} as never);
|
||||
vi.mocked(requireUserId).mockResolvedValue(user.id as never);
|
||||
vi.mocked(getTenantIdFromUrl).mockResolvedValue(tenant.id);
|
||||
vi.mocked(validateCSRFToken).mockResolvedValue(undefined as never);
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getUser).mockResolvedValue(user as never);
|
||||
vi.mocked(getTenant).mockResolvedValue(tenant as never);
|
||||
vi.mocked(getTenantSubscription).mockResolvedValue({ tenantId: tenant.id, stripeCustomerId: "cus_existing" } as never);
|
||||
vi.mocked(createTenantSubscription).mockResolvedValue({ tenantId: tenant.id, stripeCustomerId: "" } as never);
|
||||
vi.mocked(updateTenantSubscriptionCustomerId).mockResolvedValue({ tenantId: tenant.id, stripeCustomerId: "cus_created" } as never);
|
||||
vi.mocked(getSubscriptionProduct).mockResolvedValue(product as never);
|
||||
vi.mocked(createStripeCustomer).mockResolvedValue({ id: "cus_created" } as never);
|
||||
vi.mocked(createStripeCheckoutSession).mockResolvedValue({ id: "cs_123", url: "https://checkout.stripe.test/session/cs_123" } as never);
|
||||
vi.mocked(getAbsoluteUrl).mockImplementation((_request: Request, path: string) => `https://app.example.test${path}`);
|
||||
vi.mocked(getAbsoluteCurrentUrl).mockReturnValue("https://app.example.test/subscribe/acme");
|
||||
});
|
||||
|
||||
it("redirects an existing Stripe customer to the checkout URL", async () => {
|
||||
const response = await callAction(createForm());
|
||||
|
||||
expect(response.status).toBe(302);
|
||||
expect(response.headers.get("Location")).toBe("https://checkout.stripe.test/session/cs_123");
|
||||
expect(createStripeCustomer).not.toHaveBeenCalled();
|
||||
expect(updateTenantSubscriptionCustomerId).not.toHaveBeenCalled();
|
||||
expect(createStripeCheckoutSession).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
customer: "cus_existing",
|
||||
line_items: [{ price: "price_stripe_monthly", quantity: 3 }],
|
||||
mode: "subscription",
|
||||
success_url: "https://app.example.test/subscribe/acme/{CHECKOUT_SESSION_ID}/success",
|
||||
cancel_url: "https://app.example.test/subscribe/acme",
|
||||
freeTrialDays: 14,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("creates and persists a missing Stripe customer before checkout", async () => {
|
||||
vi.mocked(getTenantSubscription).mockResolvedValueOnce(null as never);
|
||||
|
||||
const response = await callAction(createForm());
|
||||
|
||||
expect(response.status).toBe(302);
|
||||
expect(createTenantSubscription).toHaveBeenCalledWith(tenant.id, "");
|
||||
expect(createStripeCustomer).toHaveBeenCalledWith(user.email, tenant.name);
|
||||
expect(updateTenantSubscriptionCustomerId).toHaveBeenCalledWith(tenant.id, { stripeCustomerId: "cus_created" });
|
||||
expect(createStripeCheckoutSession).toHaveBeenCalledWith(expect.objectContaining({ customer: "cus_created" }));
|
||||
expect(vi.mocked(updateTenantSubscriptionCustomerId).mock.invocationCallOrder[0]).toBeLessThan(
|
||||
vi.mocked(createStripeCheckoutSession).mock.invocationCallOrder[0]
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects stale tenant slug context before calling Stripe", async () => {
|
||||
const response = await callAction(createForm({ "tenant-slug-context": "old-acme" }));
|
||||
const data = await json(response);
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(data.error).toContain("Tenant mismatch");
|
||||
expect(getTenantSubscription).not.toHaveBeenCalled();
|
||||
expect(createStripeCustomer).not.toHaveBeenCalled();
|
||||
expect(createStripeCheckoutSession).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns a translated invalid-customer failure without exposing Stripe details", async () => {
|
||||
vi.mocked(getTenantSubscription).mockResolvedValueOnce({ tenantId: tenant.id, stripeCustomerId: "" } as never);
|
||||
vi.mocked(createStripeCustomer).mockResolvedValueOnce(null as never);
|
||||
|
||||
const response = await callAction(createForm());
|
||||
const data = await json(response);
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(data).toEqual({ error: "Invalid Stripe customer" });
|
||||
expect(createStripeCheckoutSession).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("stops checkout mutation when CSRF validation fails", async () => {
|
||||
const csrfError = new Error("CSRF tokens do not match");
|
||||
vi.mocked(validateCSRFToken).mockRejectedValueOnce(csrfError as never);
|
||||
|
||||
await expect(callAction(createForm())).rejects.toBe(csrfError);
|
||||
|
||||
expect(verifyUserHasPermission).not.toHaveBeenCalled();
|
||||
expect(getTenantSubscription).not.toHaveBeenCalled();
|
||||
expect(createTenantSubscription).not.toHaveBeenCalled();
|
||||
expect(createStripeCustomer).not.toHaveBeenCalled();
|
||||
expect(updateTenantSubscriptionCustomerId).not.toHaveBeenCalled();
|
||||
expect(createStripeCheckoutSession).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns a safe 400 failure when checkout session creation has no URL", async () => {
|
||||
vi.mocked(createStripeCheckoutSession).mockResolvedValueOnce({ id: "cs_without_url", url: null } as never);
|
||||
|
||||
const response = await callAction(createForm());
|
||||
const data = await json(response);
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(data).toEqual({ error: "Could not update subscription." });
|
||||
expect(JSON.stringify(data)).not.toContain("cs_without_url");
|
||||
expect(createStripeCheckoutSession).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user