Files

370 lines
16 KiB
TypeScript

// @vitest-environment node
import { createHash } from "node:crypto";
import type { DbClient } from "@hivegrid/db/client.server";
import {
customerPortalCommercialProducts,
entitlementLimitTypes,
featureKeys,
getFeatureGate,
standardEntitlementPlans,
type EntitlementPlanId,
} from "@hivegrid/entitlements";
import { describe, expect, it, vi } from "vitest";
import {
assessDatabaseCatalog,
buildCustomerPortalCatalogPlan,
customerPortalCatalogPlanIsBlocked,
customerPortalCatalogPlanIsComplete,
LagoCatalogClient,
planProviderCatalog,
reconcileBasePlanPortalFeatures,
type DatabaseCatalogSnapshot,
type DatabaseBasePlanSnapshot,
type DatabaseProductSnapshot,
type ProviderCatalogSnapshot,
} from "./catalog";
const testLagoOrganizationId = "test-staging-organization-id";
const testLagoIdentity = {
expectedOrganizationIdSha256: createHash("sha256").update(testLagoOrganizationId).digest("hex"),
};
function lagoOrganizationResponse(name = "HiveGrid Staging", id = testLagoOrganizationId): Response {
return Response.json({ organization: { lago_id: id, name } });
}
function providerSnapshot(): ProviderCatalogSnapshot {
return {
plan: {
code: "customer_portal_monthly",
name: "Customer Portal",
description: customerPortalCommercialProducts.monthlyAddOn.description,
interval: "monthly",
amount_cents: 1_999,
amount_currency: "EUR",
pay_in_advance: true,
taxes: [{ code: "de-vat-19" }],
},
addOn: {
code: "customer_portal_domain_setup",
name: "Customer Portal Domain Setup",
description: customerPortalCommercialProducts.customDomainSetup.description,
amount_cents: 29_999,
amount_currency: "EUR",
taxes: [{ code: "de-vat-19" }],
},
};
}
function commercialProduct(definition: (typeof customerPortalCommercialProducts)[keyof typeof customerPortalCommercialProducts]): DatabaseProductSnapshot {
return {
billingProviderId: `hivegrid_commercial_product_${definition.code}`,
code: definition.code,
title: definition.title,
description: definition.description,
kind: definition.source,
order: definition.catalogOrder,
model: 0,
active: true,
public: definition.public,
groupTitle: "Customer Portal",
groupDescription: null,
badge: null,
billingAddressCollection: "auto",
hasQuantity: false,
canBuyAgain: definition.source === "one_time_setup",
lagoPlanCode: definition.source === "recurring_add_on" ? definition.code : null,
features: definition.featureKeys.map((name, index) => ({
order: index + 1,
title: getFeatureGate(name)!.title,
name,
code: null,
type: entitlementLimitTypes.included,
value: definition.includedQuantity ?? entitlementLimitTypes.included,
quotaValue: null,
href: null,
badge: getFeatureGate(name)!.title,
accumulate: false,
})),
prices:
definition.amountCents === null || definition.currency === null
? []
: [
{
billingProviderId: `hivegrid_commercial_price_${definition.code}`,
lagoFeeCode: definition.code,
molliePriceReference: `hivegrid_commercial_price_${definition.code}`,
type: definition.source === "recurring_add_on" ? 1 : 0,
billingPeriod: definition.source === "recurring_add_on" ? 3 : 0,
price: (definition.amountCents / 100).toFixed(2),
currency: definition.currency.toLowerCase(),
trialDays: 0,
active: true,
},
],
};
}
function databaseSnapshot(): DatabaseCatalogSnapshot {
return {
commercialProducts: Object.values(customerPortalCommercialProducts).map(commercialProduct),
basePlans: [basePlan("starter"), basePlan("pro"), basePlan("business")],
};
}
function basePlan(planCode: EntitlementPlanId): DatabaseBasePlanSnapshot {
const plan = standardEntitlementPlans.find((candidate) => candidate.id === planCode)!;
const feature = plan.features.find((candidate) => candidate.featureKey === featureKeys.customerPortal)!;
return {
id: `${planCode}-product-id`,
code: planCode,
kind: "base_plan",
portalFeatures: [
{
order: Math.round(feature.order),
title: feature.label,
name: feature.featureKey,
code: null,
type: feature.limitType,
value: feature.limit ?? feature.limitType,
quotaValue: null,
href: null,
badge: getFeatureGate(featureKeys.customerPortal)!.title,
accumulate: feature.limitType === entitlementLimitTypes.monthly,
},
],
};
}
describe("customer-portal catalog plan", () => {
it("recognizes the canonical provider and database state", () => {
const plan = buildCustomerPortalCatalogPlan(providerSnapshot(), databaseSnapshot());
expect(customerPortalCatalogPlanIsComplete(plan)).toBe(true);
expect(customerPortalCatalogPlanIsBlocked(plan)).toBe(false);
});
it("creates missing resources, safely updates tax-only drift, and blocks commercial provider drift", () => {
expect(planProviderCatalog({ plan: null, addOn: null }).map((action) => action.action)).toEqual(["create", "create"]);
const missingTax = providerSnapshot();
missingTax.plan!.taxes = [];
missingTax.addOn!.taxes = [];
expect(planProviderCatalog(missingTax)).toEqual([
expect.objectContaining({ action: "update", driftFields: ["taxCodes"] }),
expect.objectContaining({ action: "update", driftFields: ["taxCodes"] }),
]);
const drifted = providerSnapshot();
drifted.plan!.amount_cents = 1;
const actions = planProviderCatalog(drifted);
expect(actions[0]).toMatchObject({ action: "drift", driftFields: ["amountCents"] });
});
it("distinguishes reconcilable commercial rows from a safely missing base-plan portal feature", () => {
const missing = databaseSnapshot();
const reconcilable = assessDatabaseCatalog({ ...missing, commercialProducts: missing.commercialProducts.slice(1) });
expect(reconcilable.reconcileIssues).toContain("customer_portal_monthly: product missing");
expect(reconcilable.blockingIssues).toEqual([]);
const missingFeature = databaseSnapshot();
const baseFeatureReconciliation = assessDatabaseCatalog({
...missingFeature,
basePlans: missingFeature.basePlans.map((plan) => (plan.code === "business" ? { ...plan, portalFeatures: [] } : plan)),
});
expect(baseFeatureReconciliation.reconcileIssues).toContain("business: canonical customer_portal feature missing");
expect(baseFeatureReconciliation.blockingIssues).toEqual([]);
});
it("blocks a missing base-plan product and never invents a replacement", () => {
const snapshot = databaseSnapshot();
const assessment = assessDatabaseCatalog({
...snapshot,
basePlans: snapshot.basePlans.filter((plan) => plan.code !== "business"),
});
expect(assessment.blockingIssues).toContain("business: expected exactly one canonical base-plan product");
expect(assessment.reconcileIssues).not.toContain("business: canonical customer_portal feature missing");
const duplicateAssessment = assessDatabaseCatalog({
...snapshot,
basePlans: [...snapshot.basePlans, basePlan("business")],
});
expect(duplicateAssessment.blockingIssues).toContain("business: expected exactly one canonical base-plan product");
});
it("blocks an existing wrong or duplicate portal feature instead of updating or deleting it", () => {
const snapshot = databaseSnapshot();
const business = snapshot.basePlans.find((plan) => plan.code === "business")!;
const wrongFeature = {
...business,
portalFeatures: business.portalFeatures.map((feature) => ({ ...feature, type: entitlementLimitTypes.notIncluded, value: 0 })),
};
const wrongAssessment = assessDatabaseCatalog({
...snapshot,
basePlans: snapshot.basePlans.map((plan) => (plan === business ? wrongFeature : plan)),
});
expect(wrongAssessment.blockingIssues).toContain("business: existing customer_portal feature differs from the canonical contract");
const duplicateAssessment = assessDatabaseCatalog({
...snapshot,
basePlans: snapshot.basePlans.map((plan) =>
plan === business ? { ...business, portalFeatures: [...business.portalFeatures, ...business.portalFeatures] } : plan
),
});
expect(duplicateAssessment.blockingIssues).toContain("business: duplicate customer_portal feature rows");
});
it("creates only a missing canonical portal feature and leaves every other plan feature untouched", async () => {
const snapshot = databaseSnapshot();
const baseProducts = snapshot.basePlans.map((plan) => ({
id: plan.id,
code: plan.code,
kind: "base_plan",
features: plan.code === "business" ? [] : plan.portalFeatures,
prices: [],
}));
const create = vi.fn().mockResolvedValue({});
const db = {
subscriptionProduct: { findMany: vi.fn().mockResolvedValue(baseProducts) },
subscriptionFeature: { create },
} as unknown as DbClient;
await expect(reconcileBasePlanPortalFeatures(db)).resolves.toEqual(["business"]);
expect(create).toHaveBeenCalledTimes(1);
expect(create).toHaveBeenCalledWith({
data: expect.objectContaining({
subscriptionProductId: "business-product-id",
order: Math.round(
standardEntitlementPlans
.find((candidate) => candidate.id === "business")!
.features.find((candidate) => candidate.featureKey === featureKeys.customerPortal)!.order
),
name: featureKeys.customerPortal,
type: entitlementLimitTypes.included,
value: entitlementLimitTypes.included,
}),
});
});
it("blocks a title collision that the shared seed helper could otherwise take over", () => {
const snapshot = databaseSnapshot();
const monthly = snapshot.commercialProducts.find((product) => product.code === "customer_portal_monthly")!;
const collision = { ...monthly, billingProviderId: "legacy-product", code: "legacy_customer_portal" };
const assessment = assessDatabaseCatalog({
...snapshot,
commercialProducts: [collision, ...snapshot.commercialProducts.filter((product) => product !== monthly)],
});
expect(assessment.blockingIssues).toContain("customer_portal_monthly: existing seed-key collision would mutate another product");
});
it("does not report checkout-relevant product or price drift as complete", () => {
const snapshot = databaseSnapshot();
const monthly = snapshot.commercialProducts.find((product) => product.code === "customer_portal_monthly")!;
const driftedMonthly = {
...monthly,
canBuyAgain: true,
prices: monthly.prices.map((price) => ({ ...price, molliePriceReference: "wrong-reference", trialDays: 14 })),
};
const assessment = assessDatabaseCatalog({
...snapshot,
commercialProducts: snapshot.commercialProducts.map((product) => (product === monthly ? driftedMonthly : product)),
});
expect(assessment.reconcileIssues).toEqual(
expect.arrayContaining(["customer_portal_monthly: product metadata differs", "customer_portal_monthly: canonical price contract differs"])
);
});
it("does not report commercial feature property drift as complete", () => {
const snapshot = databaseSnapshot();
const monthly = snapshot.commercialProducts.find((product) => product.code === "customer_portal_monthly")!;
const driftedMonthly = {
...monthly,
features: monthly.features.map((feature, index) =>
index === 0 ? { ...feature, order: 99, title: "Wrong", type: entitlementLimitTypes.notIncluded, value: 0, badge: null, accumulate: true } : feature
),
};
const assessment = assessDatabaseCatalog({
...snapshot,
commercialProducts: snapshot.commercialProducts.map((product) => (product === monthly ? driftedMonthly : product)),
});
expect(assessment.reconcileIssues).toContain("customer_portal_monthly: feature contract differs");
});
it("blocks additional active prices that the shared seed helper cannot remove", () => {
const snapshot = databaseSnapshot();
const monthly = snapshot.commercialProducts.find((product) => product.code === "customer_portal_monthly")!;
const withUnexpectedActivePrice = {
...monthly,
prices: [...monthly.prices, { ...monthly.prices[0]!, billingPeriod: 4, billingProviderId: "unexpected-yearly", lagoFeeCode: "unexpected-yearly" }],
};
const assessment = assessDatabaseCatalog({
...snapshot,
commercialProducts: snapshot.commercialProducts.map((product) => (product === monthly ? withUnexpectedActivePrice : product)),
});
expect(assessment.blockingIssues).toContain("customer_portal_monthly: unexpected active price cannot be removed by reconciliation");
});
});
describe("Lago customer-portal catalog client", () => {
it("treats 404 reads as missing without leaking credentials", async () => {
const fetchImpl = vi
.fn<typeof fetch>()
.mockImplementation(async (url) => (String(url).endsWith("/organizations") ? lagoOrganizationResponse() : new Response(null, { status: 404 })));
const client = new LagoCatalogClient({ apiUrl: "https://lago.example.test", apiKey: "secret-key", fetchImpl }, testLagoIdentity);
await expect(client.readCatalog()).resolves.toEqual({ plan: null, addOn: null });
for (const call of fetchImpl.mock.calls) {
expect(String(call[0])).not.toContain("secret-key");
expect(new Headers(call[1]?.headers).get("authorization")).toBe("Bearer secret-key");
}
});
it("creates and updates the exact taxed recurring plan and one-time add-on contracts", async () => {
const fetchImpl = vi.fn<typeof fetch>().mockImplementation(async (url, init) => {
if (String(url).endsWith("/organizations")) return lagoOrganizationResponse();
const body = JSON.parse(String(init?.body)) as { plan?: unknown; add_on?: unknown };
if (body.plan) return Response.json({ plan: providerSnapshot().plan });
return Response.json({ add_on: providerSnapshot().addOn });
});
const client = new LagoCatalogClient({ apiUrl: "https://lago.example.test", apiKey: "secret-key", fetchImpl }, testLagoIdentity);
await client.createPlan();
await client.createAddOn();
await client.updatePlan();
await client.updateAddOn();
expect(JSON.parse(String(fetchImpl.mock.calls[1]?.[1]?.body))).toEqual({
plan: expect.objectContaining({
code: "customer_portal_monthly",
interval: "monthly",
amount_cents: 1_999,
pay_in_advance: true,
tax_codes: ["de-vat-19"],
}),
});
expect(JSON.parse(String(fetchImpl.mock.calls[3]?.[1]?.body))).toEqual({
add_on: expect.objectContaining({
code: "customer_portal_domain_setup",
amount_cents: 29_999,
amount_currency: "EUR",
tax_codes: ["de-vat-19"],
}),
});
expect(fetchImpl.mock.calls[5]?.[1]?.method).toBe("PUT");
expect(JSON.parse(String(fetchImpl.mock.calls[5]?.[1]?.body))).toEqual({
plan: expect.objectContaining({ code: "customer_portal_monthly", tax_codes: ["de-vat-19"] }),
});
expect(fetchImpl.mock.calls[7]?.[1]?.method).toBe("PUT");
expect(JSON.parse(String(fetchImpl.mock.calls[7]?.[1]?.body))).toEqual({
add_on: expect.objectContaining({ code: "customer_portal_domain_setup", tax_codes: ["de-vat-19"] }),
});
});
it.each([
["different name", "HiveGrid Production", testLagoOrganizationId],
["different id fingerprint", "HiveGrid Staging", "different-organization-id"],
])("rejects a Lago organization with a %s before catalog reads or mutations", async (_label, name, id) => {
const fetchImpl = vi.fn<typeof fetch>().mockResolvedValue(lagoOrganizationResponse(name, id));
const client = new LagoCatalogClient({ apiUrl: "https://lago.example.test", apiKey: "secret-key", fetchImpl }, testLagoIdentity);
await expect(client.readCatalog()).rejects.toThrow("Lago organization does not match the canonical staging identity");
expect(fetchImpl).toHaveBeenCalledTimes(1);
});
});