import { assertKnownFeatureKey, billingCadences, customerPortalCommercialProducts, emailMarketingCommercialProducts, entitlementLimitTypes, getBillingCatalogVariantForSelection, getCommercialProductFeatureLimit, getFeatureGate, standardEntitlementPlans, type BillingCatalogPlanVariant, type CommercialProductDefinition, type EntitlementLimitType, type EntitlementPlanStub, type FeatureKey, } from "@hivegrid/entitlements"; import { getDbClient } from "./client.server.js"; import type { SubscriptionFeature, SubscriptionPrice, SubscriptionProduct } from "./prisma-browser.js"; import type { SubscriptionFeatureCreateInput, SubscriptionPriceCreateInput, SubscriptionPriceUpdateInput, SubscriptionProductCreateInput, SubscriptionProductUpdateInput, } from "./subscriptions.server.js"; const SEEDED_BILLING_PROVIDER_ID_PREFIX = "hivegrid_entitlement_plan"; const SEEDED_PRICE_PROVIDER_ID_PREFIX = "hivegrid_entitlement_price"; const REDACTED = "[redacted]"; const PRICE_TYPE_RECURRING = 1; const BILLING_PERIOD_MONTHLY = 3; const BILLING_PERIOD_YEARLY = 4; const BILLING_PERIOD_ONE_TIME = 0; const SEEDED_COMMERCIAL_PRODUCT_PREFIX = "hivegrid_commercial_product"; const SEEDED_COMMERCIAL_PRICE_PREFIX = "hivegrid_commercial_price"; export type EntitlementsSeedPhase = "start" | "plan-seeded" | "success" | "failure"; export type EntitlementsSeedDiagnosticEvent = { phase: EntitlementsSeedPhase; planCount: number; featureCount: number; createdProducts: number; updatedProducts: number; createdPrices: number; updatedPrices: number; deletedFeatures: number; createdFeatures: number; planId?: string; error?: { name: string; message: string; }; }; export type EntitlementsSeedDiagnostics = (event: EntitlementsSeedDiagnosticEvent) => void | Promise; export type EntitlementsSeedResult = { planCount: number; featureCount: number; createdProducts: number; updatedProducts: number; createdPrices: number; updatedPrices: number; deletedFeatures: number; createdFeatures: number; }; export type EntitlementsSeedSubscriptionProductClient = { findFirst(args: { where: { OR: [{ billingProviderId: string }, { title: string }] } }): Promise | null>; create(args: { data: SubscriptionProductCreateInput }): Promise>; update(args: { where: { id: string }; data: SubscriptionProductUpdateInput }): Promise>; }; export type EntitlementsSeedSubscriptionFeatureClient = { deleteMany(args: { where: { subscriptionProductId: string } }): Promise<{ count: number }>; create(args: { data: SubscriptionFeatureCreateInput & { subscriptionProductId: string } }): Promise; }; export type EntitlementsSeedSubscriptionPriceClient = { findFirst(args: { where: { subscriptionProductId: string; currency: string; billingPeriod: number } }): Promise | null>; create(args: { data: SubscriptionPriceCreateInput }): Promise; update(args: { where: { id: string }; data: SubscriptionPriceUpdateInput }): Promise; }; export type EntitlementsSeedClient = { subscriptionProduct: EntitlementsSeedSubscriptionProductClient; subscriptionFeature: EntitlementsSeedSubscriptionFeatureClient; subscriptionPrice: EntitlementsSeedSubscriptionPriceClient; }; export type SeedStandardEntitlementsOptions = { client?: EntitlementsSeedClient; plans?: readonly EntitlementPlanStub[]; includeCustomerPortalCommercialProducts?: boolean; includeEmailMarketingCommercialProducts?: boolean; diagnostics?: EntitlementsSeedDiagnostics; }; function getInitialResult(plans: readonly EntitlementPlanStub[], commercialProducts: readonly CommercialProductDefinition[]): EntitlementsSeedResult { return { planCount: plans.length + commercialProducts.length, featureCount: plans.reduce((total, plan) => total + plan.features.length, 0) + commercialProducts.reduce((total, product) => total + product.featureKeys.length, 0), createdProducts: 0, updatedProducts: 0, createdPrices: 0, updatedPrices: 0, deletedFeatures: 0, createdFeatures: 0, }; } function diagnosticFromResult(phase: EntitlementsSeedPhase, result: EntitlementsSeedResult, planId?: string): EntitlementsSeedDiagnosticEvent { return { phase, planCount: result.planCount, featureCount: result.featureCount, createdProducts: result.createdProducts, updatedProducts: result.updatedProducts, createdPrices: result.createdPrices, updatedPrices: result.updatedPrices, deletedFeatures: result.deletedFeatures, createdFeatures: result.createdFeatures, ...(planId ? { planId } : {}), }; } async function emitDiagnostic(diagnostics: EntitlementsSeedDiagnostics | undefined, event: EntitlementsSeedDiagnosticEvent): Promise { await diagnostics?.(event); } export function getEntitlementPlanBillingProviderId(plan: Pick): string { return `${SEEDED_BILLING_PROVIDER_ID_PREFIX}_${plan.id}`; } function mapPlanToProductCreateInput(plan: EntitlementPlanStub): SubscriptionProductCreateInput { return { billingProviderId: getEntitlementPlanBillingProviderId(plan), code: plan.id, lagoPlanCode: plan.id, kind: "base_plan", order: plan.metadata.sortOrder, title: plan.metadata.publicName, model: 0, public: plan.metadata.isPublic, active: true, description: plan.metadata.description, badge: null, groupTitle: null, groupDescription: null, billingAddressCollection: "auto", hasQuantity: false, canBuyAgain: false, }; } function mapPlanToProductUpdateInput(plan: EntitlementPlanStub): SubscriptionProductUpdateInput { const product = mapPlanToProductCreateInput(plan); return { billingProviderId: product.billingProviderId, code: product.code, lagoPlanCode: product.lagoPlanCode, kind: product.kind, order: product.order, title: product.title, model: product.model, public: product.public, description: product.description, badge: product.badge, groupTitle: product.groupTitle, groupDescription: product.groupDescription, billingAddressCollection: product.billingAddressCollection, hasQuantity: product.hasQuantity, canBuyAgain: product.canBuyAgain, }; } function commercialProductBillingProviderId(product: CommercialProductDefinition): string { return `${SEEDED_COMMERCIAL_PRODUCT_PREFIX}_${product.code}`; } function commercialPriceBillingProviderId(product: CommercialProductDefinition): string { return `${SEEDED_COMMERCIAL_PRICE_PREFIX}_${product.code}`; } function commercialAmountDecimal(amountCents: number): string { if (!Number.isSafeInteger(amountCents) || amountCents <= 0) throw new RangeError("Commercial product amount must be a positive cent integer."); return (amountCents / 100).toFixed(2); } function mapCommercialProductCreateInput(product: CommercialProductDefinition): SubscriptionProductCreateInput { return { billingProviderId: commercialProductBillingProviderId(product), code: product.code, lagoPlanCode: product.source === "recurring_add_on" ? product.code : null, kind: product.source, order: product.catalogOrder, title: product.title, model: 0, public: product.public, active: true, description: product.description, badge: null, groupTitle: product.groupTitle, groupDescription: null, billingAddressCollection: "auto", hasQuantity: false, canBuyAgain: product.source === "one_time_setup", }; } function mapCommercialProductUpdateInput(product: CommercialProductDefinition): SubscriptionProductUpdateInput { return mapCommercialProductCreateInput(product); } async function seedCommercialProduct( client: EntitlementsSeedClient, productDefinition: CommercialProductDefinition ): Promise> { const productData = mapCommercialProductCreateInput(productDefinition); const existingProduct = await client.subscriptionProduct.findFirst({ where: { OR: [{ billingProviderId: productData.billingProviderId }, { title: productData.title }] }, }); const product = existingProduct ? await client.subscriptionProduct.update({ where: { id: existingProduct.id }, data: mapCommercialProductUpdateInput(productDefinition) }) : await client.subscriptionProduct.create({ data: productData }); const deletedFeatures = await client.subscriptionFeature.deleteMany({ where: { subscriptionProductId: product.id } }); for (const [index, featureKey] of productDefinition.featureKeys.entries()) { assertKnownFeatureKey(featureKey); const registryItem = getFeatureGate(featureKey); if (!registryItem) throw new RangeError(`Unknown feature key: ${featureKey}`); const featureLimit = getCommercialProductFeatureLimit(productDefinition, featureKey); await client.subscriptionFeature.create({ data: { subscriptionProductId: product.id, order: index + 1, title: registryItem.title, name: featureKey, type: featureLimit.limitType, value: featureLimit.limit ?? featureLimit.limitType, href: null, badge: registryItem.title, accumulate: featureLimit.limitType === entitlementLimitTypes.monthly, }, }); } let createdPrices = 0; let updatedPrices = 0; if (productDefinition.amountCents !== null && productDefinition.currency !== null) { const billingPeriod = productDefinition.source === "recurring_add_on" ? BILLING_PERIOD_MONTHLY : BILLING_PERIOD_ONE_TIME; const billingProviderId = commercialPriceBillingProviderId(productDefinition); const priceData: SubscriptionPriceCreateInput = { subscriptionProductId: product.id, billingProviderId, lagoPlanCode: productDefinition.source === "recurring_add_on" ? productDefinition.code : null, lagoFeeCode: productDefinition.code, molliePriceReference: billingProviderId, billingCadence: "monthly", contractMonths: 1, requiredPaymentMethod: "any", type: productDefinition.source === "recurring_add_on" ? PRICE_TYPE_RECURRING : 0, billingPeriod, price: commercialAmountDecimal(productDefinition.amountCents), currency: productDefinition.currency.toLowerCase(), trialDays: 0, active: true, }; const existingPrice = await client.subscriptionPrice.findFirst({ where: { subscriptionProductId: product.id, currency: priceData.currency, billingPeriod }, }); if (existingPrice) { await client.subscriptionPrice.update({ where: { id: existingPrice.id }, data: { billingProviderId: priceData.billingProviderId, lagoPlanCode: priceData.lagoPlanCode, lagoFeeCode: priceData.lagoFeeCode, molliePriceReference: priceData.molliePriceReference, billingCadence: priceData.billingCadence, contractMonths: priceData.contractMonths, requiredPaymentMethod: priceData.requiredPaymentMethod, type: priceData.type, price: priceData.price, trialDays: priceData.trialDays, active: priceData.active, }, }); updatedPrices = 1; } else { await client.subscriptionPrice.create({ data: priceData }); createdPrices = 1; } } return { createdProducts: existingProduct ? 0 : 1, updatedProducts: existingProduct ? 1 : 0, createdPrices, updatedPrices, deletedFeatures: deletedFeatures.count, createdFeatures: productDefinition.featureKeys.length, }; } function getPriceBillingProviderId(plan: Pick, billingPeriod: number): string { return `${SEEDED_PRICE_PROVIDER_ID_PREFIX}_${plan.id}_${billingPeriod === BILLING_PERIOD_YEARLY ? "yearly" : "monthly"}`; } function getLagoFeeCode(variant: BillingCatalogPlanVariant): string { return `${variant.code}_base`; } function mapPlanPriceToInput( plan: EntitlementPlanStub, subscriptionProductId: string, billingPeriod: number, variant: BillingCatalogPlanVariant ): SubscriptionPriceCreateInput { const billingProviderId = getPriceBillingProviderId(plan, billingPeriod); return { subscriptionProductId, billingProviderId, lagoPlanCode: variant.code, lagoFeeCode: getLagoFeeCode(variant), molliePriceReference: billingProviderId, billingCadence: variant.cadence, contractMonths: variant.contractMonths, requiredPaymentMethod: variant.requiredPaymentMethod, type: PRICE_TYPE_RECURRING, billingPeriod, price: (variant.baseAmountCents / 100).toFixed(2), currency: "eur", trialDays: 0, active: true, }; } async function seedPlanPrice( client: EntitlementsSeedClient, plan: EntitlementPlanStub, productId: string, billingPeriod: number, variant: BillingCatalogPlanVariant ) { const priceData = mapPlanPriceToInput(plan, productId, billingPeriod, variant); const existingPrice = await client.subscriptionPrice.findFirst({ where: { subscriptionProductId: productId, currency: priceData.currency, billingPeriod: priceData.billingPeriod, }, }); if (existingPrice) { await client.subscriptionPrice.update({ where: { id: existingPrice.id }, data: { billingProviderId: priceData.billingProviderId, lagoPlanCode: priceData.lagoPlanCode, lagoFeeCode: priceData.lagoFeeCode, molliePriceReference: priceData.molliePriceReference, billingCadence: priceData.billingCadence, contractMonths: priceData.contractMonths, requiredPaymentMethod: priceData.requiredPaymentMethod, type: priceData.type, price: priceData.price, trialDays: priceData.trialDays, active: priceData.active, }, }); return { createdPrices: 0, updatedPrices: 1 }; } await client.subscriptionPrice.create({ data: priceData }); return { createdPrices: 1, updatedPrices: 0 }; } function getFeatureValue(limitType: EntitlementLimitType, limit: number | null): number { return limit ?? limitType; } function mapPlanFeatureToCreateInput(feature: EntitlementPlanStub["features"][number]): SubscriptionFeatureCreateInput { assertKnownFeatureKey(feature.featureKey); const registryItem = getFeatureGate(feature.featureKey as FeatureKey); if (!registryItem) { throw new RangeError(`Unknown feature key: ${feature.featureKey}`); } return { order: feature.order, title: feature.label, name: feature.featureKey, type: feature.limitType, value: getFeatureValue(feature.limitType, feature.limit), href: null, badge: registryItem.title, accumulate: feature.limitType === 2, }; } function redactMessage(value: string): string { return value .replace(/\b(?:prod|price|sub|cus|tenant|user|acct|sk|pk|rk|cs|plan)_[A-Za-z0-9_-]+\b/g, REDACTED) .replace(/postgres(?:ql)?:\/\/\S+/gi, REDACTED) .replace(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g, REDACTED); } export function redactSeedError(error: unknown): { name: string; message: string } { if (error instanceof Error) { return { name: error.name || "Error", message: redactMessage(error.message), }; } return { name: "Error", message: redactMessage(String(error)), }; } async function seedOnePlan(client: EntitlementsSeedClient, plan: EntitlementPlanStub): Promise> { const productData = mapPlanToProductCreateInput(plan); const existingProduct = await client.subscriptionProduct.findFirst({ where: { OR: [{ billingProviderId: productData.billingProviderId }, { title: productData.title }] }, }); const product = existingProduct ? await client.subscriptionProduct.update({ where: { id: existingProduct.id }, data: mapPlanToProductUpdateInput(plan), }) : await client.subscriptionProduct.create({ data: productData }); const deletedFeatures = await client.subscriptionFeature.deleteMany({ where: { subscriptionProductId: product.id } }); let createdPrices = 0; let updatedPrices = 0; const monthlyVariant = getBillingCatalogVariantForSelection(plan.id, billingCadences.monthly); const annualSepaVariant = getBillingCatalogVariantForSelection(plan.id, billingCadences.annualSepa); if (monthlyVariant && annualSepaVariant) { const monthly = await seedPlanPrice(client, plan, product.id, BILLING_PERIOD_MONTHLY, monthlyVariant); const yearly = await seedPlanPrice(client, plan, product.id, BILLING_PERIOD_YEARLY, annualSepaVariant); createdPrices += monthly.createdPrices + yearly.createdPrices; updatedPrices += monthly.updatedPrices + yearly.updatedPrices; } for (const feature of plan.features) { await client.subscriptionFeature.create({ data: { subscriptionProductId: product.id, ...mapPlanFeatureToCreateInput(feature), }, }); } return { createdProducts: existingProduct ? 0 : 1, updatedProducts: existingProduct ? 1 : 0, createdPrices, updatedPrices, deletedFeatures: deletedFeatures.count, createdFeatures: plan.features.length, }; } export async function seedStandardEntitlements({ client = getDbClient(), plans = standardEntitlementPlans, includeCustomerPortalCommercialProducts = false, includeEmailMarketingCommercialProducts = false, diagnostics, }: SeedStandardEntitlementsOptions = {}): Promise { const commercialProducts = [ ...(includeCustomerPortalCommercialProducts ? Object.values(customerPortalCommercialProducts) : []), ...(includeEmailMarketingCommercialProducts ? emailMarketingCommercialProducts : []), ]; const result = getInitialResult(plans, commercialProducts); await emitDiagnostic(diagnostics, diagnosticFromResult("start", result)); try { for (const plan of plans) { const planResult = await seedOnePlan(client, plan); result.createdProducts += planResult.createdProducts; result.updatedProducts += planResult.updatedProducts; result.createdPrices += planResult.createdPrices; result.updatedPrices += planResult.updatedPrices; result.deletedFeatures += planResult.deletedFeatures; result.createdFeatures += planResult.createdFeatures; await emitDiagnostic(diagnostics, diagnosticFromResult("plan-seeded", result, plan.id)); } for (const product of commercialProducts) { const productResult = await seedCommercialProduct(client, product); result.createdProducts += productResult.createdProducts; result.updatedProducts += productResult.updatedProducts; result.createdPrices += productResult.createdPrices; result.updatedPrices += productResult.updatedPrices; result.deletedFeatures += productResult.deletedFeatures; result.createdFeatures += productResult.createdFeatures; await emitDiagnostic(diagnostics, diagnosticFromResult("plan-seeded", result, product.code)); } await emitDiagnostic(diagnostics, diagnosticFromResult("success", result)); return result; } catch (error) { await emitDiagnostic(diagnostics, { ...diagnosticFromResult("failure", result), error: redactSeedError(error), }); throw error; } }