import type { PrismaClient } from '@generated/prisma/client'; import type { CountryCode, Plan, PlanCatalogDto, PlanLimits } from '@gruperly/shared'; import { COUNTRY_CURRENCY, countryCodeSchema, PLAN_LIMITS, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared'; import prisma from '@/lib/prisma'; import { logger } from '@/logger'; /** Limits and prices are read often (every plan guard) and edited rarely. */ const CACHE_TTL_MS = 30 * 1000; export type PlanCatalogSnapshot = { limits: Record; /** Monthly price of Pro, in the currency of each country. */ proPrices: Record; }; export function defaultPlanCatalog(): PlanCatalogSnapshot { return { limits: { FREE: { ...PLAN_LIMITS.FREE }, PRO: { ...PLAN_LIMITS.PRO } }, proPrices: { ...PRO_PRICE_BY_COUNTRY }, }; } type PlanCatalogDeps = { db?: Pick; ttlMs?: number; now?: () => number; }; /** * What each plan allows and what Pro costs, as edited from the backoffice * (`plan_configs`, `plan_prices`). A missing row falls back to the defaults in * shared (`PLAN_LIMITS`, `PRO_PRICE_BY_COUNTRY`), which also seed the tables. * * Cached in memory for a few seconds; the backoffice invalidates it on save, so * the instance that saved sees the change at once and the others within the TTL. */ export class PlanCatalog { private cached: { snapshot: PlanCatalogSnapshot; at: number } | null = null; constructor(private readonly deps: PlanCatalogDeps = {}) {} invalidate(): void { this.cached = null; } async snapshot(): Promise { const now = this.deps.now?.() ?? Date.now(); const ttl = this.deps.ttlMs ?? CACHE_TTL_MS; if (this.cached && now - this.cached.at < ttl) return this.cached.snapshot; const snapshot = defaultPlanCatalog(); try { const db = this.deps.db ?? prisma; const [configs, prices] = await Promise.all([db.planConfig.findMany(), db.planPrice.findMany()]); for (const config of configs) { snapshot.limits[config.plan] = { maxGroups: config.maxGroups, maxAttendees: config.maxAttendees, whatsappAutomations: config.whatsappAutomations, mpCharges: config.mpCharges, kidsGroups: config.kidsGroups, }; } for (const price of prices) { const country = countryCodeSchema.safeParse(price.country); if (country.success) snapshot.proPrices[country.data] = Number(price.amount.toString()); } } catch (error) { // The defaults keep the guards working; not cached, so the next call retries. logger.warn({ err: error }, 'Could not read the plan catalog, using the defaults'); return snapshot; } this.cached = { snapshot, at: now }; return snapshot; } async getLimits(plan: Plan): Promise { return (await this.snapshot()).limits[plan]; } async getProPrice(country: CountryCode): Promise { return (await this.snapshot()).proPrices[country]; } } /** The catalog every use-case shares, so an invalidation reaches all of them. */ export const planCatalog = new PlanCatalog(); /** A fixed catalog, for tests and callers that already hold a snapshot. */ export function staticPlanCatalog(snapshot: PlanCatalogSnapshot = defaultPlanCatalog()): PlanCatalogReader { return { snapshot: async () => snapshot, getLimits: async (plan) => snapshot.limits[plan], getProPrice: async (country) => snapshot.proPrices[country], }; } export type PlanCatalogReader = Pick; export function toPlanCatalogDto(snapshot: PlanCatalogSnapshot): PlanCatalogDto { const proPrices = Object.fromEntries( countryCodeSchema.options.map((country) => [ country, { amount: snapshot.proPrices[country], currency: COUNTRY_CURRENCY[country] }, ]), ) as PlanCatalogDto['proPrices']; return { limits: snapshot.limits, proPrices }; }