import { createHash } from "node:crypto"; import { normalizeLagoApiUrl } from "../../packages/billing/src/lago"; import type { DbClient } from "@hivegrid/db/client.server"; import { customerPortalCommercialProducts, customerPortalProductCodes, entitlementLimitTypes, featureKeys, getFeatureGate, hiveGridVat, standardEntitlementPlans, type EntitlementPlanId, } from "@hivegrid/entitlements"; import { z } from "zod"; import { CustomerPortalUatError, normalizeCustomerPortalStagingLagoApiUrl } from "./contracts"; const DEFAULT_TIMEOUT_MS = 10_000; const BASE_PLAN_CODES = ["starter", "pro", "business"] as const; const COMMERCIAL_PRODUCT_CODES = Object.values(customerPortalProductCodes); const STAGING_LAGO_ORGANIZATION_NAME = "HiveGrid Staging"; const STAGING_LAGO_ORGANIZATION_ID_SHA256 = "3b1134a731c67b704bb0b3298ce031213079966b348aa762800f9c92556085a8"; const desiredLagoPlan = Object.freeze({ code: customerPortalCommercialProducts.monthlyAddOn.code, name: customerPortalCommercialProducts.monthlyAddOn.title, description: customerPortalCommercialProducts.monthlyAddOn.description, interval: "monthly" as const, amountCents: customerPortalCommercialProducts.monthlyAddOn.amountCents!, amountCurrency: customerPortalCommercialProducts.monthlyAddOn.currency!, payInAdvance: true, taxCodes: Object.freeze([hiveGridVat.code]), }); const desiredLagoAddOn = Object.freeze({ code: customerPortalCommercialProducts.customDomainSetup.code, name: customerPortalCommercialProducts.customDomainSetup.title, description: customerPortalCommercialProducts.customDomainSetup.description, amountCents: customerPortalCommercialProducts.customDomainSetup.amountCents!, amountCurrency: customerPortalCommercialProducts.customDomainSetup.currency!, taxCodes: Object.freeze([hiveGridVat.code]), }); const lagoAppliedTaxSchema = z.object({ code: z.string() }); const lagoPlanSchema = z.object({ code: z.string(), name: z.string(), description: z.string().nullable().optional(), interval: z.string(), amount_cents: z.number().int(), amount_currency: z.string(), pay_in_advance: z.boolean(), taxes: z.array(lagoAppliedTaxSchema).default([]), }); const lagoAddOnSchema = z.object({ code: z.string(), name: z.string(), description: z.string().nullable().optional(), amount_cents: z.number().int(), amount_currency: z.string(), taxes: z.array(lagoAppliedTaxSchema).default([]), }); const lagoPlanResponseSchema = z.object({ plan: lagoPlanSchema }); const lagoAddOnResponseSchema = z.object({ add_on: lagoAddOnSchema }); const lagoOrganizationResponseSchema = z.object({ organization: z.object({ lago_id: z.string().min(1), name: z.string() }), }); export type LagoPlanSnapshot = z.infer; export type LagoAddOnSnapshot = z.infer; export type ProviderCatalogSnapshot = { readonly plan: LagoPlanSnapshot | null; readonly addOn: LagoAddOnSnapshot | null; }; export type ProviderCatalogAction = { readonly resource: "plan" | "add_on"; readonly code: string; readonly action: "create" | "update" | "noop" | "drift"; readonly driftFields: readonly string[]; }; export type DatabasePriceSnapshot = { readonly billingProviderId: string; readonly lagoFeeCode: string | null; readonly molliePriceReference: string | null; readonly type: number; readonly billingPeriod: number; readonly price: string; readonly currency: string; readonly trialDays: number; readonly active: boolean; }; export type DatabaseProductSnapshot = { readonly billingProviderId: string; readonly code: string | null; readonly title: string; readonly description: string | null; readonly kind: string; readonly order: number; readonly model: number; readonly active: boolean; readonly public: boolean; readonly groupTitle: string | null; readonly groupDescription: string | null; readonly badge: string | null; readonly billingAddressCollection: string; readonly hasQuantity: boolean; readonly canBuyAgain: boolean; readonly lagoPlanCode: string | null; readonly features: readonly DatabaseFeatureSnapshot[]; readonly prices: readonly DatabasePriceSnapshot[]; }; export type DatabaseFeatureSnapshot = { readonly order: number; readonly title: string; readonly name: string; readonly code: string | null; readonly type: number; readonly value: number; readonly quotaValue: unknown; readonly href: string | null; readonly badge: string | null; readonly accumulate: boolean; }; export type DatabaseBasePlanSnapshot = { readonly id: string; readonly code: string | null; readonly kind: string; readonly portalFeatures: readonly DatabaseFeatureSnapshot[]; }; export type DatabaseCatalogSnapshot = { readonly commercialProducts: readonly DatabaseProductSnapshot[]; readonly basePlans: readonly DatabaseBasePlanSnapshot[]; }; export type DatabaseCatalogAssessment = { readonly reconcileIssues: readonly string[]; readonly blockingIssues: readonly string[]; }; export type CustomerPortalCatalogPlan = { readonly provider: readonly ProviderCatalogAction[]; readonly database: { readonly action: "noop" | "reconcile" | "blocked"; readonly reconcileIssues: readonly string[]; readonly blockingIssues: readonly string[]; }; }; function differentFields>(actual: T, desired: T, fields: readonly (keyof T)[]): string[] { return fields.filter((field) => actual[field] !== desired[field]).map(String); } export function planProviderCatalog(snapshot: ProviderCatalogSnapshot): ProviderCatalogAction[] { const planDrift = snapshot.plan ? differentFields( { code: snapshot.plan.code, name: snapshot.plan.name, description: snapshot.plan.description ?? "", interval: snapshot.plan.interval, amountCents: snapshot.plan.amount_cents, amountCurrency: snapshot.plan.amount_currency.toUpperCase(), payInAdvance: snapshot.plan.pay_in_advance, taxCodes: snapshot.plan.taxes .map((tax) => tax.code) .sort() .join(","), }, { ...desiredLagoPlan, taxCodes: [...desiredLagoPlan.taxCodes].sort().join(",") }, ["code", "name", "description", "interval", "amountCents", "amountCurrency", "payInAdvance", "taxCodes"] ) : []; const addOnDrift = snapshot.addOn ? differentFields( { code: snapshot.addOn.code, name: snapshot.addOn.name, description: snapshot.addOn.description ?? "", amountCents: snapshot.addOn.amount_cents, amountCurrency: snapshot.addOn.amount_currency.toUpperCase(), taxCodes: snapshot.addOn.taxes .map((tax) => tax.code) .sort() .join(","), }, { ...desiredLagoAddOn, taxCodes: [...desiredLagoAddOn.taxCodes].sort().join(",") }, ["code", "name", "description", "amountCents", "amountCurrency", "taxCodes"] ) : []; return [ { resource: "plan", code: desiredLagoPlan.code, action: snapshot.plan ? (planDrift.length === 0 ? "noop" : planDrift.every((field) => field === "taxCodes") ? "update" : "drift") : "create", driftFields: planDrift, }, { resource: "add_on", code: desiredLagoAddOn.code, action: snapshot.addOn ? (addOnDrift.length === 0 ? "noop" : addOnDrift.every((field) => field === "taxCodes") ? "update" : "drift") : "create", driftFields: addOnDrift, }, ]; } type BasePlanPortalFeatureAction = { readonly planCode: EntitlementPlanId; readonly productId: string | null; readonly action: "create" | "noop" | "blocked"; readonly issue: string | null; }; function getBasePlanPortalFeatureDefinition(planCode: EntitlementPlanId): DatabaseFeatureSnapshot { const plan = standardEntitlementPlans.find((candidate) => candidate.id === planCode); const feature = plan?.features.find((candidate) => candidate.featureKey === featureKeys.customerPortal); const registryItem = getFeatureGate(featureKeys.customerPortal); if (!feature || !registryItem) { throw new CustomerPortalUatError(`customer-portal UAT: canonical ${planCode} portal feature definition is unavailable`); } return { // SubscriptionFeature.order is an Int. The entitlement registry deliberately // uses fractional values to place adjacent features, while Prisma/Postgres // persists those values as the nearest integer. 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: registryItem.title, accumulate: feature.limitType === entitlementLimitTypes.monthly, }; } function databaseFeatureMatches(actual: DatabaseFeatureSnapshot, expected: DatabaseFeatureSnapshot): boolean { return ( actual.order === expected.order && actual.title === expected.title && actual.name === expected.name && actual.code === expected.code && actual.type === expected.type && actual.value === expected.value && actual.quotaValue === expected.quotaValue && actual.href === expected.href && actual.badge === expected.badge && actual.accumulate === expected.accumulate ); } function commercialFeaturesMatch( product: DatabaseProductSnapshot, definition: (typeof customerPortalCommercialProducts)[keyof typeof customerPortalCommercialProducts] ): boolean { if (product.features.length !== definition.featureKeys.length) return false; return definition.featureKeys.every((featureKey, index) => { const matches = product.features.filter((feature) => feature.name === featureKey); const registryItem = getFeatureGate(featureKey); if (matches.length !== 1 || !registryItem) return false; return databaseFeatureMatches(matches[0]!, { order: index + 1, title: registryItem.title, name: featureKey, code: null, type: entitlementLimitTypes.included, value: definition.includedQuantity ?? entitlementLimitTypes.included, quotaValue: null, href: null, badge: registryItem.title, accumulate: false, }); }); } export function planBasePlanPortalFeatureReconciliation(snapshot: DatabaseCatalogSnapshot): readonly BasePlanPortalFeatureAction[] { return BASE_PLAN_CODES.map((planCode) => { const matches = snapshot.basePlans.filter((plan) => plan.code === planCode); if (matches.length !== 1) { return { planCode, productId: null, action: "blocked", issue: `${planCode}: expected exactly one canonical base-plan product`, }; } const plan = matches[0]!; if (plan.kind !== "base_plan") { return { planCode, productId: plan.id, action: "blocked", issue: `${planCode}: canonical product is not a base plan`, }; } if (plan.portalFeatures.length > 1) { return { planCode, productId: plan.id, action: "blocked", issue: `${planCode}: duplicate customer_portal feature rows`, }; } const feature = plan.portalFeatures[0]; if (!feature) { return { planCode, productId: plan.id, action: "create", issue: `${planCode}: canonical customer_portal feature missing`, }; } if (!databaseFeatureMatches(feature, getBasePlanPortalFeatureDefinition(planCode))) { return { planCode, productId: plan.id, action: "blocked", issue: `${planCode}: existing customer_portal feature differs from the canonical contract`, }; } return { planCode, productId: plan.id, action: "noop", issue: null }; }); } export function assessDatabaseCatalog(snapshot: DatabaseCatalogSnapshot): DatabaseCatalogAssessment { const reconcileIssues: string[] = []; const blockingIssues: string[] = []; for (const definition of Object.values(customerPortalCommercialProducts)) { const expectedBillingProviderId = `hivegrid_commercial_product_${definition.code}`; const seedCollisions = snapshot.commercialProducts.filter( (product) => product.code !== definition.code && (product.title === definition.title || product.billingProviderId === expectedBillingProviderId) ); if (seedCollisions.length > 0) { blockingIssues.push(`${definition.code}: existing seed-key collision would mutate another product`); continue; } const matches = snapshot.commercialProducts.filter((product) => product.code === definition.code); if (matches.length > 1) { blockingIssues.push(`${definition.code}: duplicate database products`); continue; } const product = matches[0]; if (!product) { reconcileIssues.push(`${definition.code}: product missing`); continue; } if (product.title !== definition.title && product.billingProviderId !== expectedBillingProviderId) { blockingIssues.push(`${definition.code}: canonical code is not reachable through the existing seed keys`); continue; } const expectedLagoPlanCode = definition.source === "recurring_add_on" ? definition.code : null; if ( product.billingProviderId !== expectedBillingProviderId || product.title !== definition.title || product.description !== definition.description || product.kind !== definition.source || product.order !== definition.catalogOrder || product.model !== 0 || product.active !== true || product.public !== definition.public || product.groupTitle !== "Customer Portal" || product.groupDescription !== null || product.badge !== null || product.billingAddressCollection !== "auto" || product.hasQuantity !== false || product.canBuyAgain !== (definition.source === "one_time_setup") || product.lagoPlanCode !== expectedLagoPlanCode ) { reconcileIssues.push(`${definition.code}: product metadata differs`); } if (!commercialFeaturesMatch(product, definition)) { reconcileIssues.push(`${definition.code}: feature contract differs`); } const activePrices = product.prices.filter((price) => price.active); if (definition.amountCents === null || definition.currency === null) { if (activePrices.length > 0) blockingIssues.push(`${definition.code}: unexpected active price cannot be removed by reconciliation`); continue; } const expectedPeriod = definition.source === "recurring_add_on" ? 3 : 0; const expectedPrice = (definition.amountCents / 100).toFixed(2); const expectedCurrency = definition.currency.toLowerCase(); const seedPriceCandidates = product.prices.filter((price) => price.billingPeriod === expectedPeriod && price.currency.toLowerCase() === expectedCurrency); if (seedPriceCandidates.length > 1) { blockingIssues.push(`${definition.code}: duplicate seed-key prices`); continue; } const price = seedPriceCandidates[0]; if (!price) { reconcileIssues.push(`${definition.code}: canonical active price missing`); } else { const expectedPriceProviderId = `hivegrid_commercial_price_${definition.code}`; const expectedType = definition.source === "recurring_add_on" ? 1 : 0; if ( price.billingProviderId !== expectedPriceProviderId || price.lagoFeeCode !== definition.code || price.molliePriceReference !== expectedPriceProviderId || price.type !== expectedType || price.price !== expectedPrice || price.currency !== expectedCurrency || price.trialDays !== 0 || !price.active ) { reconcileIssues.push(`${definition.code}: canonical price contract differs`); } } const unexpectedActivePrices = activePrices.filter((candidate) => candidate !== price); if (unexpectedActivePrices.length > 0) { blockingIssues.push(`${definition.code}: unexpected active price cannot be removed by reconciliation`); } } for (const action of planBasePlanPortalFeatureReconciliation(snapshot)) { if (action.action === "create") reconcileIssues.push(action.issue!); if (action.action === "blocked") blockingIssues.push(action.issue!); } return { reconcileIssues, blockingIssues }; } export function buildCustomerPortalCatalogPlan(provider: ProviderCatalogSnapshot, database: DatabaseCatalogSnapshot): CustomerPortalCatalogPlan { const providerPlan = planProviderCatalog(provider); const databaseAssessment = assessDatabaseCatalog(database); return { provider: providerPlan, database: { action: databaseAssessment.blockingIssues.length > 0 ? "blocked" : databaseAssessment.reconcileIssues.length > 0 ? "reconcile" : "noop", ...databaseAssessment, }, }; } export function customerPortalCatalogPlanIsComplete(plan: CustomerPortalCatalogPlan): boolean { return plan.provider.every((action) => action.action === "noop") && plan.database.action === "noop"; } export function customerPortalCatalogPlanIsBlocked(plan: CustomerPortalCatalogPlan): boolean { return plan.provider.some((action) => action.action === "drift") || plan.database.action === "blocked"; } export async function readDatabaseCatalog(db: DbClient): Promise { const commercialTitles = Object.values(customerPortalCommercialProducts).map((product) => product.title); const commercialBillingProviderIds = Object.values(customerPortalCommercialProducts).map((product) => `hivegrid_commercial_product_${product.code}`); const products = await db.subscriptionProduct.findMany({ where: { OR: [ { code: { in: [...COMMERCIAL_PRODUCT_CODES, ...BASE_PLAN_CODES] } }, { title: { in: commercialTitles } }, { billingProviderId: { in: commercialBillingProviderIds } }, ], }, select: { id: true, billingProviderId: true, code: true, title: true, description: true, kind: true, order: true, model: true, active: true, public: true, groupTitle: true, groupDescription: true, badge: true, billingAddressCollection: true, hasQuantity: true, canBuyAgain: true, lagoPlanCode: true, features: { select: { order: true, title: true, name: true, code: true, type: true, value: true, quotaValue: true, href: true, badge: true, accumulate: true, }, }, prices: { select: { billingProviderId: true, lagoFeeCode: true, molliePriceReference: true, type: true, billingPeriod: true, price: true, currency: true, trialDays: true, active: true, }, }, }, }); const snapshots: DatabaseProductSnapshot[] = products.map((product) => ({ ...product, kind: String(product.kind), features: product.features, prices: product.prices.map((price) => ({ ...price, price: price.price.toFixed(2) })), })); return { commercialProducts: snapshots.filter( (product) => (product.code !== null && COMMERCIAL_PRODUCT_CODES.includes(product.code as never)) || commercialTitles.includes(product.title) || commercialBillingProviderIds.includes(product.billingProviderId) ), basePlans: products .filter((product) => product.code !== null && BASE_PLAN_CODES.includes(product.code as never)) .map((product) => ({ id: product.id, code: product.code, kind: String(product.kind), portalFeatures: product.features.filter((feature) => feature.name === featureKeys.customerPortal), })), }; } export async function reconcileBasePlanPortalFeatures(db: DbClient): Promise { const actions = planBasePlanPortalFeatureReconciliation(await readDatabaseCatalog(db)); const blocked = actions.find((action) => action.action === "blocked"); if (blocked) { throw new CustomerPortalUatError(`customer-portal UAT: ${blocked.issue}`); } const created: EntitlementPlanId[] = []; for (const action of actions) { if (action.action !== "create" || !action.productId) continue; const feature = getBasePlanPortalFeatureDefinition(action.planCode); await db.subscriptionFeature.create({ data: { subscriptionProductId: action.productId, order: feature.order, title: feature.title, name: feature.name, code: feature.code, type: feature.type, value: feature.value, href: feature.href, badge: feature.badge, accumulate: feature.accumulate, }, }); created.push(action.planCode); } return created; } export class LagoCatalogClient { private readonly apiUrl: string; private readonly apiKey: string; private readonly fetchImpl: typeof fetch; private readonly timeoutMs: number; private readonly expectedOrganizationIdSha256: string; constructor( input: { apiUrl: string; apiKey: string; fetchImpl?: typeof fetch; timeoutMs?: number }, testOverrides?: { expectedOrganizationIdSha256: string } ) { if (testOverrides && !input.fetchImpl) { throw new CustomerPortalUatError("customer-portal UAT: Lago identity test override requires an injected transport"); } try { this.apiUrl = testOverrides ? normalizeLagoApiUrl(input.apiUrl) : normalizeCustomerPortalStagingLagoApiUrl(input.apiUrl); } catch { throw new CustomerPortalUatError("customer-portal UAT: LAGO_API_URL is invalid"); } this.apiKey = input.apiKey.trim(); if (!this.apiKey) throw new CustomerPortalUatError("customer-portal UAT: LAGO_API_KEY is required"); this.fetchImpl = input.fetchImpl ?? fetch; this.timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; this.expectedOrganizationIdSha256 = testOverrides?.expectedOrganizationIdSha256 ?? STAGING_LAGO_ORGANIZATION_ID_SHA256; } async readCatalog(): Promise { await this.assertStagingOrganization(); const [plan, addOn] = await Promise.all([ this.request(`/plans/${encodeURIComponent(desiredLagoPlan.code)}`, "GET", undefined, lagoPlanResponseSchema, true), this.request(`/add_ons/${encodeURIComponent(desiredLagoAddOn.code)}`, "GET", undefined, lagoAddOnResponseSchema, true), ]); return { plan: plan?.plan ?? null, addOn: addOn?.add_on ?? null }; } async createPlan(): Promise { await this.assertStagingOrganization(); await this.request( "/plans", "POST", { plan: { name: desiredLagoPlan.name, code: desiredLagoPlan.code, description: desiredLagoPlan.description, interval: desiredLagoPlan.interval, amount_cents: desiredLagoPlan.amountCents, amount_currency: desiredLagoPlan.amountCurrency, pay_in_advance: desiredLagoPlan.payInAdvance, tax_codes: desiredLagoPlan.taxCodes, }, }, lagoPlanResponseSchema ); } async updatePlan(): Promise { await this.assertStagingOrganization(); await this.request( `/plans/${encodeURIComponent(desiredLagoPlan.code)}`, "PUT", { plan: { name: desiredLagoPlan.name, code: desiredLagoPlan.code, description: desiredLagoPlan.description, interval: desiredLagoPlan.interval, amount_cents: desiredLagoPlan.amountCents, amount_currency: desiredLagoPlan.amountCurrency, pay_in_advance: desiredLagoPlan.payInAdvance, tax_codes: desiredLagoPlan.taxCodes, }, }, lagoPlanResponseSchema ); } async createAddOn(): Promise { await this.assertStagingOrganization(); await this.request( "/add_ons", "POST", { add_on: { name: desiredLagoAddOn.name, code: desiredLagoAddOn.code, description: desiredLagoAddOn.description, amount_cents: desiredLagoAddOn.amountCents, amount_currency: desiredLagoAddOn.amountCurrency, tax_codes: desiredLagoAddOn.taxCodes, }, }, lagoAddOnResponseSchema ); } async updateAddOn(): Promise { await this.assertStagingOrganization(); await this.request( `/add_ons/${encodeURIComponent(desiredLagoAddOn.code)}`, "PUT", { add_on: { name: desiredLagoAddOn.name, code: desiredLagoAddOn.code, description: desiredLagoAddOn.description, amount_cents: desiredLagoAddOn.amountCents, amount_currency: desiredLagoAddOn.amountCurrency, tax_codes: desiredLagoAddOn.taxCodes, }, }, lagoAddOnResponseSchema ); } private async assertStagingOrganization(): Promise { const response = await this.request("/organizations", "GET", undefined, lagoOrganizationResponseSchema); const organization = response?.organization; const idSha256 = organization ? createHash("sha256").update(organization.lago_id).digest("hex") : ""; if (organization?.name !== STAGING_LAGO_ORGANIZATION_NAME || idSha256 !== this.expectedOrganizationIdSha256) { throw new CustomerPortalUatError("customer-portal UAT: Lago organization does not match the canonical staging identity"); } } private async request(path: string, method: "GET" | "POST" | "PUT", body: unknown, schema: z.ZodType, allowNotFound = false): Promise { const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), this.timeoutMs); try { const response = await this.fetchImpl(`${this.apiUrl}/api/v1${path}`, { method, headers: { authorization: `Bearer ${this.apiKey}`, accept: "application/json", ...(body === undefined ? {} : { "content-type": "application/json" }), }, body: body === undefined ? undefined : JSON.stringify(body), redirect: "error", signal: controller.signal, }); if (allowNotFound && response.status === 404) return null; if (!response.ok) throw new CustomerPortalUatError(`customer-portal UAT: Lago catalog request failed with status ${response.status}`); const parsed = schema.safeParse(await response.json()); if (!parsed.success) throw new CustomerPortalUatError("customer-portal UAT: Lago catalog response shape is invalid"); return parsed.data; } catch (error) { if (error instanceof CustomerPortalUatError) throw error; throw new CustomerPortalUatError("customer-portal UAT: Lago catalog request failed"); } finally { clearTimeout(timeout); } } }