340 lines
12 KiB
TypeScript
340 lines
12 KiB
TypeScript
import {
|
|
assertKnownFeatureKey,
|
|
getFeatureGate,
|
|
standardEntitlementPlans,
|
|
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 STANDARD_PLAN_PRICES_EUR: Record<string, { monthly: string; yearly: string }> = {
|
|
starter: { monthly: "199", yearly: "179" },
|
|
pro: { monthly: "499", yearly: "449" },
|
|
business: { monthly: "999", yearly: "899" },
|
|
};
|
|
|
|
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<void>;
|
|
|
|
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<Pick<SubscriptionProduct, "id"> | null>;
|
|
create(args: { data: SubscriptionProductCreateInput }): Promise<Pick<SubscriptionProduct, "id">>;
|
|
update(args: { where: { id: string }; data: SubscriptionProductUpdateInput }): Promise<Pick<SubscriptionProduct, "id">>;
|
|
};
|
|
|
|
export type EntitlementsSeedSubscriptionFeatureClient = {
|
|
deleteMany(args: { where: { subscriptionProductId: string } }): Promise<{ count: number }>;
|
|
create(args: { data: SubscriptionFeatureCreateInput & { subscriptionProductId: string } }): Promise<SubscriptionFeature>;
|
|
};
|
|
|
|
export type EntitlementsSeedSubscriptionPriceClient = {
|
|
findFirst(args: { where: { subscriptionProductId: string; currency: string; billingPeriod: number } }): Promise<Pick<SubscriptionPrice, "id"> | null>;
|
|
create(args: { data: SubscriptionPriceCreateInput }): Promise<SubscriptionPrice>;
|
|
update(args: { where: { id: string }; data: SubscriptionPriceUpdateInput }): Promise<SubscriptionPrice>;
|
|
};
|
|
|
|
export type EntitlementsSeedClient = {
|
|
subscriptionProduct: EntitlementsSeedSubscriptionProductClient;
|
|
subscriptionFeature: EntitlementsSeedSubscriptionFeatureClient;
|
|
subscriptionPrice: EntitlementsSeedSubscriptionPriceClient;
|
|
};
|
|
|
|
export type SeedStandardEntitlementsOptions = {
|
|
client?: EntitlementsSeedClient;
|
|
plans?: readonly EntitlementPlanStub[];
|
|
diagnostics?: EntitlementsSeedDiagnostics;
|
|
};
|
|
|
|
function getInitialResult(plans: readonly EntitlementPlanStub[]): EntitlementsSeedResult {
|
|
return {
|
|
planCount: plans.length,
|
|
featureCount: plans.reduce((total, plan) => total + plan.features.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<void> {
|
|
await diagnostics?.(event);
|
|
}
|
|
|
|
export function getEntitlementPlanBillingProviderId(plan: Pick<EntitlementPlanStub, "id">): string {
|
|
return `${SEEDED_BILLING_PROVIDER_ID_PREFIX}_${plan.id}`;
|
|
}
|
|
|
|
function mapPlanToProductCreateInput(plan: EntitlementPlanStub): SubscriptionProductCreateInput {
|
|
return {
|
|
billingProviderId: getEntitlementPlanBillingProviderId(plan),
|
|
code: plan.id,
|
|
lagoPlanCode: plan.id,
|
|
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,
|
|
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 getPriceBillingProviderId(plan: Pick<EntitlementPlanStub, "id">, billingPeriod: number): string {
|
|
return `${SEEDED_PRICE_PROVIDER_ID_PREFIX}_${plan.id}_${billingPeriod === BILLING_PERIOD_YEARLY ? "yearly" : "monthly"}`;
|
|
}
|
|
|
|
function getLagoFeeCode(plan: Pick<EntitlementPlanStub, "id">, billingPeriod: number): string {
|
|
return `${plan.id}_${billingPeriod === BILLING_PERIOD_YEARLY ? "yearly" : "monthly"}`;
|
|
}
|
|
|
|
function mapPlanPriceToInput(plan: EntitlementPlanStub, subscriptionProductId: string, billingPeriod: number, price: string): SubscriptionPriceCreateInput {
|
|
const billingProviderId = getPriceBillingProviderId(plan, billingPeriod);
|
|
return {
|
|
subscriptionProductId,
|
|
billingProviderId,
|
|
lagoFeeCode: getLagoFeeCode(plan, billingPeriod),
|
|
molliePriceReference: billingProviderId,
|
|
type: PRICE_TYPE_RECURRING,
|
|
billingPeriod,
|
|
price,
|
|
currency: "eur",
|
|
trialDays: 0,
|
|
active: true,
|
|
};
|
|
}
|
|
|
|
async function seedPlanPrice(client: EntitlementsSeedClient, plan: EntitlementPlanStub, productId: string, billingPeriod: number, price: string) {
|
|
const priceData = mapPlanPriceToInput(plan, productId, billingPeriod, price);
|
|
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,
|
|
lagoFeeCode: priceData.lagoFeeCode,
|
|
molliePriceReference: priceData.molliePriceReference,
|
|
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<Omit<EntitlementsSeedResult, "planCount" | "featureCount">> {
|
|
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 standardPrices = STANDARD_PLAN_PRICES_EUR[plan.id];
|
|
if (standardPrices) {
|
|
const monthly = await seedPlanPrice(client, plan, product.id, BILLING_PERIOD_MONTHLY, standardPrices.monthly);
|
|
const yearly = await seedPlanPrice(client, plan, product.id, BILLING_PERIOD_YEARLY, standardPrices.yearly);
|
|
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,
|
|
diagnostics,
|
|
}: SeedStandardEntitlementsOptions = {}): Promise<EntitlementsSeedResult> {
|
|
const result = getInitialResult(plans);
|
|
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));
|
|
}
|
|
|
|
await emitDiagnostic(diagnostics, diagnosticFromResult("success", result));
|
|
return result;
|
|
} catch (error) {
|
|
await emitDiagnostic(diagnostics, {
|
|
...diagnosticFromResult("failure", result),
|
|
error: redactSeedError(error),
|
|
});
|
|
throw error;
|
|
}
|
|
}
|