Reorganize repo structure and standards references
This commit is contained in:
1 parent
3cb93a81be
commit
be2054274d
5885 files changed
+2588
-195
No files matched your search
@@ -0,0 +1,237 @@
|
||||
import {
|
||||
assertKnownFeatureKey,
|
||||
getFeatureGate,
|
||||
standardEntitlementPlans,
|
||||
type EntitlementLimitType,
|
||||
type EntitlementPlanStub,
|
||||
type FeatureKey,
|
||||
} from "@toolctrl/entitlements";
|
||||
|
||||
import { getDbClient } from "./client.server.js";
|
||||
import type { SubscriptionFeature, SubscriptionProduct } from "./prisma-browser.js";
|
||||
import type { SubscriptionFeatureCreateInput, SubscriptionProductCreateInput, SubscriptionProductUpdateInput } from "./subscriptions.server.js";
|
||||
|
||||
const SEEDED_STRIPE_ID_PREFIX = "toolctrl_entitlement_plan";
|
||||
const REDACTED = "[redacted]";
|
||||
|
||||
export type EntitlementsSeedPhase = "start" | "plan-seeded" | "success" | "failure";
|
||||
|
||||
export type EntitlementsSeedDiagnosticEvent = {
|
||||
phase: EntitlementsSeedPhase;
|
||||
planCount: number;
|
||||
featureCount: number;
|
||||
createdProducts: number;
|
||||
updatedProducts: 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;
|
||||
deletedFeatures: number;
|
||||
createdFeatures: number;
|
||||
};
|
||||
|
||||
export type EntitlementsSeedSubscriptionProductClient = {
|
||||
findFirst(args: { where: { OR: [{ stripeId: 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 EntitlementsSeedClient = {
|
||||
subscriptionProduct: EntitlementsSeedSubscriptionProductClient;
|
||||
subscriptionFeature: EntitlementsSeedSubscriptionFeatureClient;
|
||||
};
|
||||
|
||||
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,
|
||||
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,
|
||||
deletedFeatures: result.deletedFeatures,
|
||||
createdFeatures: result.createdFeatures,
|
||||
...(planId ? { planId } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
async function emitDiagnostic(diagnostics: EntitlementsSeedDiagnostics | undefined, event: EntitlementsSeedDiagnosticEvent): Promise<void> {
|
||||
await diagnostics?.(event);
|
||||
}
|
||||
|
||||
export function getEntitlementPlanStripeId(plan: Pick<EntitlementPlanStub, "id">): string {
|
||||
return `${SEEDED_STRIPE_ID_PREFIX}_${plan.id}`;
|
||||
}
|
||||
|
||||
function mapPlanToProductCreateInput(plan: EntitlementPlanStub): SubscriptionProductCreateInput {
|
||||
return {
|
||||
stripeId: getEntitlementPlanStripeId(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 {
|
||||
stripeId: product.stripeId,
|
||||
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 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: [{ stripeId: productData.stripeId }, { 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 } });
|
||||
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,
|
||||
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.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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user