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:
Jose Selesan
2026-11-11 07:50:14 -03:00
parent abb18f1815
commit aac142d324
90 changed files with 2642 additions and 104 deletions

View File

@@ -1,9 +1,16 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { AdminAccountDetail, ProblemDetails, Result } from '@gruperly/shared';
import { err, ok, PLAN_LIMITS } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import { notFoundResourceProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { exceedsLimits, getGraceDays, isBillingEnforced, toBillingChargeDto } from '@/modules/billing/lib';
import {
exceedsLimits,
getGraceDays,
isBillingEnforced,
type PlanCatalogReader,
planCatalog,
toBillingChargeDto,
} from '@/modules/billing/lib';
import { accountPlan, toAccountListItem } from '../../lib';
const RECENT_CHARGES = 12;
@@ -13,6 +20,7 @@ type GetAccountDeps = {
enforced?: boolean;
graceDays?: number;
now?: () => Date;
catalog?: PlanCatalogReader;
};
/** One professor's account: plan, links, groups and the latest Pro charges. */
@@ -65,18 +73,16 @@ export class GetAccount {
const { graceUntil } = accountPlan(user, context);
const enforced = this.deps.enforced ?? isBillingEnforced();
const subscription = user.subscription;
// Same rule as the PlanGuard: an account without a plan is held to Free.
const limits = await (this.deps.catalog ?? planCatalog).getLimits(summary.plan ?? 'FREE');
return ok({
...summary,
planSelectedAt: user.planSelectedAt?.toISOString() ?? null,
graceUntil: graceUntil?.toISOString() ?? null,
// Same rule as the PlanGuard: an account without a plan is held to Free.
readOnly:
enforced
&& exceedsLimits(PLAN_LIMITS[summary.plan ?? 'FREE'], {
groups: usage.groupsCount,
attendees: usage.attendeesCount,
}),
enforced && exceedsLimits(limits, { groups: usage.groupsCount, attendees: usage.attendeesCount }),
limits,
subscription:
summary.subscription && subscription
? {

View File

@@ -0,0 +1,12 @@
import { Hono } from 'hono';
import { resultJson } from '@/http/problem-details';
import { GetPlans } from './use-case';
const route = new Hono();
route.get('/plans', async (c) => {
const result = await new GetPlans().execute();
return resultJson(c, result);
});
export default route;

View File

@@ -0,0 +1,55 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { AdminPlansDto, ProblemDetails, Result } from '@gruperly/shared';
import { billingProviderForCountry, COUNTRY_CURRENCY, countryCodeSchema, ok } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { MAX_PRICE_CHANGE_ATTEMPTS } from '@/modules/billing/jobs';
import { type PlanCatalogReader, planCatalog } from '@/modules/billing/lib';
/** The subscriptions "apply to existing" moves: live, with a provider subscription. */
export const LIVE_SUBSCRIPTION_STATUSES = ['AUTHORIZED', 'PAUSED'] as const;
type GetPlansDeps = {
db?: Pick<PrismaClient, 'planPrice' | 'billingSubscription'>;
catalog?: PlanCatalogReader;
};
/** Limits of both plans and, per country, the price of Pro and how it reached live subscriptions. */
export class GetPlans {
constructor(private readonly deps: GetPlansDeps = {}) {}
async execute(): Promise<Result<AdminPlansDto, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const catalog = await (this.deps.catalog ?? planCatalog).snapshot();
const [priceRows, live] = await Promise.all([
db.planPrice.findMany({ select: { country: true, updatedAt: true } }),
db.billingSubscription.findMany({
where: { status: { in: [...LIVE_SUBSCRIPTION_STATUSES] }, externalId: { not: null } },
select: { country: true, amount: true, pendingAmount: true, priceChangeAttempts: true },
}),
]);
const updatedAt = new Map(priceRows.map((row) => [row.country, row.updatedAt]));
const prices = countryCodeSchema.options.map((country) => {
const amount = catalog.proPrices[country];
const rows = live.filter((row) => row.country === country);
const queued = rows.filter((row) => row.pendingAmount !== null);
const failed = queued.filter((row) => row.priceChangeAttempts >= MAX_PRICE_CHANGE_ATTEMPTS);
return {
country,
amount,
currency: COUNTRY_CURRENCY[country],
provider: billingProviderForCountry(country),
updatedAt: updatedAt.get(country)?.toISOString() ?? null,
liveSubscriptions: rows.length,
atOtherPrice: rows.filter(
(row) => Number((row.pendingAmount ?? row.amount).toString()) !== amount,
).length,
pendingChanges: queued.length - failed.length,
failedChanges: failed.length,
};
});
return ok({ limits: catalog.limits, prices });
}
}

View File

@@ -0,0 +1,23 @@
import type { PlanLimitsImpactQuery } from '@gruperly/shared';
import { PlanLimitsImpactQuerySchema, planSchema } from '@gruperly/shared';
import { Hono } from 'hono';
import { z } from 'zod';
import { resultJson } from '@/http/problem-details';
import { validate } from '@/http/validate';
import { PlanLimitsImpact } from './use-case';
const route = new Hono();
route.get(
'/plans/:plan/impact',
validate.param(z.object({ plan: planSchema })),
validate.query(PlanLimitsImpactQuerySchema),
async (c) => {
const { plan } = c.req.valid('param');
const query = c.req.valid('query') as PlanLimitsImpactQuery;
const result = await new PlanLimitsImpact().execute(plan, query);
return resultJson(c, result);
},
);
export default route;

View File

@@ -0,0 +1,52 @@
import type { Prisma, PrismaClient } from '@generated/prisma/client';
import type { Plan, PlanLimitsImpactDto, PlanLimitsImpactQuery, ProblemDetails, Result } from '@gruperly/shared';
import { ok } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { getGraceDays, proSubscriptionWhere } from '@/modules/billing/lib';
type PlanLimitsImpactDeps = {
db?: Pick<PrismaClient, 'group' | 'person' | 'user'>;
graceDays?: number;
now?: () => Date;
};
/**
* How many accounts on a plan would exceed new limits, i.e. become read only
* as soon as they are saved (limits apply at once). Usage is the PlanGuard's:
* groups owned, and people with at least one ACTIVE membership.
*/
export class PlanLimitsImpact {
constructor(private readonly deps: PlanLimitsImpactDeps = {}) {}
async execute(plan: Plan, query: PlanLimitsImpactQuery): Promise<Result<PlanLimitsImpactDto, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const now = this.deps.now?.() ?? new Date();
const graceDays = this.deps.graceDays ?? getGraceDays();
const [overGroups, overAttendees] = await Promise.all([
query.maxGroups === null
? []
: db.group.groupBy({
by: ['createdById'],
having: { id: { _count: { gt: query.maxGroups } } },
}),
query.maxAttendees === null
? []
: db.person.groupBy({
by: ['createdById'],
where: { attendees: { some: { status: 'ACTIVE' } } },
having: { id: { _count: { gt: query.maxAttendees } } },
}),
]);
const candidates = [...new Set([...overGroups, ...overAttendees].map((row) => row.createdById))];
if (candidates.length === 0) return ok({ affectedAccounts: 0 });
// Same split as the PlanGuard: anyone without a live Pro is held to Free.
const isPro: Prisma.UserWhereInput = { subscription: { is: proSubscriptionWhere(now, graceDays) } };
const affectedAccounts = await db.user.count({
where: { id: { in: candidates }, ...(plan === 'PRO' ? isPro : { NOT: isPro }) },
});
return ok({ affectedAccounts });
}
}

View File

@@ -0,0 +1,26 @@
import type { UpdatePlanLimitsInput } from '@gruperly/shared';
import { planSchema, UpdatePlanLimitsInputSchema } from '@gruperly/shared';
import { Hono } from 'hono';
import { z } from 'zod';
import type { BackendEnv } from '@/http/env';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { validate } from '@/http/validate';
import { UpdatePlanLimits } from './use-case';
const route = new Hono<BackendEnv>();
route.put(
'/plans/:plan/limits',
validate.param(z.object({ plan: planSchema })),
validate.json(UpdatePlanLimitsInputSchema),
async (c) => {
const user = c.get('user');
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
const { plan } = c.req.valid('param');
const input = c.req.valid('json') as UpdatePlanLimitsInput;
const result = await new UpdatePlanLimits().execute(plan, input, user.id);
return resultJson(c, result);
},
);
export default route;

View File

@@ -0,0 +1,29 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { Plan, PlanLimits, ProblemDetails, Result, UpdatePlanLimitsInput } from '@gruperly/shared';
import { ok } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import { type PlanCatalog, planCatalog } from '@/modules/billing/lib';
type UpdatePlanLimitsDeps = {
db?: Pick<PrismaClient, 'planConfig'>;
catalog?: Pick<PlanCatalog, 'invalidate'>;
};
/** New limits for a plan. They apply at once to every account on it. */
export class UpdatePlanLimits {
constructor(private readonly deps: UpdatePlanLimitsDeps = {}) {}
async execute(
plan: Plan,
input: UpdatePlanLimitsInput,
adminId: string,
): Promise<Result<PlanLimits, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const data = { ...input, updatedById: adminId };
await db.planConfig.upsert({ where: { plan }, create: { plan, ...data }, update: data });
(this.deps.catalog ?? planCatalog).invalidate();
logger.info({ plan, adminId, limits: input }, 'Plan limits updated');
return ok(input);
}
}

View File

@@ -0,0 +1,27 @@
import type { UpdatePlanPriceInput } from '@gruperly/shared';
import { countryCodeSchema, UpdatePlanPriceInputSchema } from '@gruperly/shared';
import { Hono } from 'hono';
import { z } from 'zod';
import type { BackendEnv } from '@/http/env';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { validate } from '@/http/validate';
import { runPriceChanges } from '@/modules/billing/jobs';
import { UpdatePlanPrice } from './use-case';
const route = new Hono<BackendEnv>();
route.put(
'/plans/prices/:country',
validate.param(z.object({ country: countryCodeSchema })),
validate.json(UpdatePlanPriceInputSchema),
async (c) => {
const user = c.get('user');
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
const { country } = c.req.valid('param');
const input = c.req.valid('json') as UpdatePlanPriceInput;
const result = await new UpdatePlanPrice({ applyQueued: runPriceChanges }).execute(country, input, user.id);
return resultJson(c, result);
},
);
export default route;

View File

@@ -0,0 +1,89 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { CountryCode, ProblemDetails, Result, UpdatePlanPriceInput, UpdatePlanPriceResultDto } from '@gruperly/shared';
import { COUNTRY_CURRENCY, ok } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import { type PlanCatalog, planCatalog } from '@/modules/billing/lib';
import { LIVE_SUBSCRIPTION_STATUSES } from '../get-plans/use-case';
type UpdatePlanPriceDeps = {
db?: Pick<PrismaClient, '$transaction'>;
catalog?: Pick<PlanCatalog, 'invalidate' | 'getProPrice'>;
/** Kicks the job that pushes queued prices to the providers. */
applyQueued?: () => Promise<void>;
};
/**
* New monthly price of Pro in a country. New subscriptions take it right away.
* With `applyToExisting`, the country's live subscriptions are queued to move
* to it (`pending_amount`); the job tells each provider to charge it from the
* next charge on, and emails the professor.
*
* PENDING subscriptions are left alone: a checkout half done keeps its amount,
* and trying again starts a new one at the new price.
*/
export class UpdatePlanPrice {
constructor(private readonly deps: UpdatePlanPriceDeps = {}) {}
async execute(
country: CountryCode,
input: UpdatePlanPriceInput,
adminId: string,
): Promise<Result<UpdatePlanPriceResultDto, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const catalog = this.deps.catalog ?? planCatalog;
catalog.invalidate();
const previousAmount = await catalog.getProPrice(country);
const currency = COUNTRY_CURRENCY[country];
const queued = await db.$transaction(async (tx) => {
await tx.planPrice.upsert({
where: { country },
create: { country, amount: input.amount, updatedById: adminId },
update: { amount: input.amount, updatedById: adminId },
});
const change = await tx.planPriceChange.create({
data: {
country,
previousAmount,
newAmount: input.amount,
currency,
applyToExisting: input.applyToExisting,
createdById: adminId,
},
});
if (!input.applyToExisting) return 0;
// Rows already at the new price (or already moving to it) are not touched.
const moved = await tx.billingSubscription.updateMany({
where: {
country,
status: { in: [...LIVE_SUBSCRIPTION_STATUSES] },
externalId: { not: null },
OR: [
{ pendingAmount: null, amount: { not: input.amount } },
{ pendingAmount: { not: null, notIn: [input.amount] } },
],
},
data: {
pendingAmount: input.amount,
priceChangeId: change.id,
priceChangeAttempts: 0,
priceChangeError: null,
},
});
await tx.planPriceChange.update({ where: { id: change.id }, data: { queued: moved.count } });
return moved.count;
});
catalog.invalidate();
logger.info({ country, adminId, amount: input.amount, queued }, 'Pro price updated');
if (queued > 0 && this.deps.applyQueued) {
// In the background: the providers are slow, and the cron retries anyway.
void this.deps.applyQueued();
}
return ok({ country, amount: input.amount, queued });
}
}

View File

@@ -1,7 +1,11 @@
import { Hono } from 'hono';
import getAccountRoute from './features/get-account/route';
import getPlansRoute from './features/get-plans/route';
import listAccountsRoute from './features/list-accounts/route';
import meRoute from './features/me/route';
import planLimitsImpactRoute from './features/plan-limits-impact/route';
import updatePlanLimitsRoute from './features/update-plan-limits/route';
import updatePlanPriceRoute from './features/update-plan-price/route';
import { adminOnlyMiddleware } from './lib';
const routes = new Hono();
@@ -11,7 +15,13 @@ routes.route('/', meRoute);
// Everything below `/me` is the backoffice itself.
routes.use('/accounts', adminOnlyMiddleware());
routes.use('/accounts/*', adminOnlyMiddleware());
routes.use('/plans', adminOnlyMiddleware());
routes.use('/plans/*', adminOnlyMiddleware());
routes.route('/', listAccountsRoute);
routes.route('/', getAccountRoute);
routes.route('/', getPlansRoute);
routes.route('/', planLimitsImpactRoute);
routes.route('/', updatePlanLimitsRoute);
routes.route('/', updatePlanPriceRoute);
export default routes;