feat(billing): configurable plans from the backoffice and MP payment notifications
Plans: - Plan limits and Pro prices per country live in the database (plan_configs, plan_prices, seeded with the previous constants) and are read through PlanCatalog (30 s cache, defaults as fallback). - /admin/plans edits limits (with the count of accounts that would become read-only) and prices, optionally pushing the new price to live subscriptions from their next charge (MP preapproval amount, Stripe item without proration) via the ApplyPriceChanges job, with an email and a notice on /billing. - GET /billing/plans feeds the onboarding and the billing screen. Mercado Pago: - The Pro checkout returns through GET /billing/return on API_PUBLIC_URL, since MP refuses a back_url on localhost. - The OAuth callback bounces from the tunnel to BETTER_AUTH_URL to find the session, requires the session to own the state, and redirects instead of answering JSON on unexpected errors. - Checkout Pro links skip auto_return off public HTTPS and carry a notification_url to POST /payments/webhooks/mp/:paymentId, which confirms the payment with the owner's token (same rule as the polling job, which stays as fallback). The search now prefers the approved attempt. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
108
apps/backend/src/modules/billing/lib/catalog.ts
Normal file
108
apps/backend/src/modules/billing/lib/catalog.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
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<Plan, PlanLimits>;
|
||||
/** Monthly price of Pro, in the currency of each country. */
|
||||
proPrices: Record<CountryCode, number>;
|
||||
};
|
||||
|
||||
export function defaultPlanCatalog(): PlanCatalogSnapshot {
|
||||
return {
|
||||
limits: { FREE: { ...PLAN_LIMITS.FREE }, PRO: { ...PLAN_LIMITS.PRO } },
|
||||
proPrices: { ...PRO_PRICE_BY_COUNTRY },
|
||||
};
|
||||
}
|
||||
|
||||
type PlanCatalogDeps = {
|
||||
db?: Pick<PrismaClient, 'planConfig' | 'planPrice'>;
|
||||
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<PlanCatalogSnapshot> {
|
||||
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,
|
||||
};
|
||||
}
|
||||
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<PlanLimits> {
|
||||
return (await this.snapshot()).limits[plan];
|
||||
}
|
||||
|
||||
async getProPrice(country: CountryCode): Promise<number> {
|
||||
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<PlanCatalog, 'snapshot' | 'getLimits' | 'getProPrice'>;
|
||||
|
||||
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 };
|
||||
}
|
||||
Reference in New Issue
Block a user