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;

View File

@@ -0,0 +1,16 @@
import { ok } from '@gruperly/shared';
import { Hono } from 'hono';
import { resultJson } from '@/http/problem-details';
import { planCatalog, toPlanCatalogDto } from '../../lib';
const route = new Hono();
/**
* What each plan allows and what Pro costs in every country. The onboarding
* asks before the professor's country is stored, so it gets all of them.
*/
route.get('/plans', async (c) => {
return resultJson(c, ok(toPlanCatalogDto(await planCatalog.snapshot())));
});
export default route;

View File

@@ -0,0 +1,19 @@
import { billingReturnToSchema } from '@gruperly/shared';
import { Hono } from 'hono';
import { getWebOrigin } from '@/modules/mp/lib';
import { buildSubscriptionReturnUrl } from '../../lib';
const route = new Hono();
/**
* The `back_url` of the Pro checkout (Mercado Pago and Stripe). Public: the
* browser comes from the provider, maybe through a tunnel without the session
* cookie. It only redirects to a fixed page of the web, so whatever the
* provider appends to the query is dropped and nothing can steer the redirect.
*/
route.get('/return', (c) => {
const parsed = billingReturnToSchema.safeParse(c.req.query('to'));
return c.redirect(buildSubscriptionReturnUrl(getWebOrigin(), parsed.success ? parsed.data : 'billing'));
});
export default route;

View File

@@ -1,17 +1,18 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { BillingStatusDto, ProblemDetails, Result } from '@gruperly/shared';
import { billingProviderForCountry, COUNTRY_CURRENCY, err, ok, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared';
import { billingProviderForCountry, COUNTRY_CURRENCY, err, ok } from '@gruperly/shared';
import { notFoundResourceProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { countryOf, PlanGuard, SyncSubscription } from '../../lib';
import { countryOf, type PlanCatalogReader, PlanGuard, planCatalog, SyncSubscription } from '../../lib';
import { type BillingProviderResolver, getBillingProvider } from '../../providers';
/** A PENDING subscription is re-read from Mercado Pago at most this often. */
const PENDING_SYNC_INTERVAL_MS = 30 * 1000;
type GetBillingStatusDeps = {
db?: Pick<PrismaClient, 'user' | 'billingSubscription'>;
db?: Pick<PrismaClient, 'user' | 'billingSubscription' | 'billingCharge'>;
guard?: PlanGuard;
catalog?: PlanCatalogReader;
sync?: Pick<SyncSubscription, 'execute'>;
providers?: BillingProviderResolver;
now?: () => Date;
@@ -54,6 +55,24 @@ export class GetBillingStatus {
live && live.status !== 'PENDING' ? live.provider : billingProviderForCountry(country),
);
const priceAmount = live
? Number(live.amount.toString())
: await (this.deps.catalog ?? planCatalog).getProPrice(country);
// A price change from the backoffice applies from the next charge: show it
// while it is queued, and after it reached the provider until it is charged.
let nextPriceAmount: number | null = null;
if (live?.pendingAmount) {
nextPriceAmount = Number(live.pendingAmount.toString());
} else if (live?.status === 'AUTHORIZED') {
const lastCharge = await db.billingCharge.findFirst({
where: { subscriptionId: live.id, status: 'approved' },
orderBy: { paidAt: 'desc' },
select: { amount: true },
});
if (lastCharge && Number(lastCharge.amount.toString()) !== priceAmount) nextPriceAmount = priceAmount;
}
return ok({
plan: entitlements.plan,
status: subscription?.status ?? null,
@@ -65,7 +84,8 @@ export class GetBillingStatus {
? (subscription.nextPaymentDate?.toISOString() ?? null)
: null,
payerEmail: subscription?.payerEmail ?? null,
priceAmount: live ? Number(live.amount.toString()) : PRO_PRICE_BY_COUNTRY[country],
priceAmount,
nextPriceAmount,
currency: live ? live.currency : COUNTRY_CURRENCY[country],
country,
provider: provider.id,

View File

@@ -1,6 +1,6 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { ProblemDetails, Result, SubscribeInput, SubscribeResultDto } from '@gruperly/shared';
import { billingProviderForCountry, COUNTRY_CURRENCY, err, ok, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared';
import { billingProviderForCountry, COUNTRY_CURRENCY, err, ok } from '@gruperly/shared';
import {
billingNotAvailableProblem,
notFoundResourceProblem,
@@ -9,15 +9,20 @@ import {
} from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import { getWebOrigin } from '@/modules/mp/lib';
import { buildSubscriptionBackUrl, countryOf, subscriptionRefOf } from '../../lib';
import {
buildSubscriptionBackUrl,
countryOf,
getApiPublicOrigin,
type PlanCatalogReader, planCatalog, subscriptionRefOf } from '../../lib';
import { type BillingProviderResolver, getBillingProvider, toBillingProblem } from '../../providers';
type SubscribeDeps = {
db?: Pick<PrismaClient, 'user' | 'billingSubscription'>;
providers?: BillingProviderResolver;
webOrigin?: string;
/** Public origin of the API, where the provider sends the browser back. */
apiOrigin?: string;
now?: () => Date;
catalog?: PlanCatalogReader;
};
/**
@@ -60,7 +65,7 @@ export class Subscribe {
}
}
const amount = PRO_PRICE_BY_COUNTRY[country];
const amount = await (this.deps.catalog ?? planCatalog).getProPrice(country);
const currency = COUNTRY_CURRENCY[country];
const fields = {
country,
@@ -82,6 +87,10 @@ export class Subscribe {
checkoutRef: null,
authorizedAt: null,
nextPaymentDate: null,
pendingAmount: null,
priceChangeId: null,
priceChangeAttempts: 0,
priceChangeError: null,
},
});
@@ -97,7 +106,7 @@ export class Subscribe {
amount,
currency,
payerEmail: input.payerEmail ?? null,
backUrl: buildSubscriptionBackUrl(this.deps.webOrigin ?? getWebOrigin(), input.returnTo),
backUrl: buildSubscriptionBackUrl(this.deps.apiOrigin ?? getApiPublicOrigin(), input.returnTo),
startDate,
});
} catch (error) {

View File

@@ -0,0 +1,117 @@
import type { PrismaClient } from '@generated/prisma/client';
import { COUNTRY_TIME_ZONES } from '@gruperly/shared';
import type { EmailProvider } from '@/lib/email';
import { emailProvider } from '@/lib/email';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import { getWebOrigin } from '@/modules/mp/lib';
import { formatAmount } from '@/modules/whatsapp/lib/format';
import { countryOf } from '../lib';
import {
BillingProviderNotConfigured,
type BillingProviderResolver,
getBillingProvider,
} from '../providers';
const BATCH_SIZE = 20;
/** After this many refusals the change stays visible as failed in the backoffice. */
export const MAX_PRICE_CHANGE_ATTEMPTS = 5;
type ApplyPriceChangesDeps = {
db?: Pick<PrismaClient, 'billingSubscription'>;
providers?: BillingProviderResolver;
email?: Pick<EmailProvider, 'sendProPriceChanged'>;
webOrigin?: string;
};
export type ApplyPriceChangesTotals = { applied: number; failed: number; dropped: number };
/**
* Pushes the prices the backoffice queued (`pending_amount`) to each live
* subscription's provider, from its next charge on, and tells the professor.
*
* The provider call is idempotent (it sets an amount), so two instances racing
* over a row are harmless: only the one whose conditional update moves
* `pending_amount` into `amount` sends the email.
*/
export class ApplyPriceChanges {
constructor(private readonly deps: ApplyPriceChangesDeps = {}) {}
async execute(): Promise<ApplyPriceChangesTotals> {
const db = this.deps.db ?? prisma;
const providers = this.deps.providers ?? getBillingProvider;
const totals: ApplyPriceChangesTotals = { applied: 0, failed: 0, dropped: 0 };
const rows = await db.billingSubscription.findMany({
where: { pendingAmount: { not: null }, priceChangeAttempts: { lt: MAX_PRICE_CHANGE_ATTEMPTS } },
include: { user: { select: { name: true, email: true, country: true } } },
orderBy: { updatedAt: 'asc' },
take: BATCH_SIZE,
});
for (const row of rows) {
const pendingAmount = row.pendingAmount;
if (!pendingAmount) continue;
const unchanged = { id: row.id, pendingAmount };
// Cancelled (or never completed) meanwhile: nothing left to reprice.
if (row.status === 'CANCELLED' || row.status === 'PENDING' || !row.externalId) {
await db.billingSubscription.updateMany({
where: unchanged,
data: { pendingAmount: null, priceChangeId: null, priceChangeAttempts: 0, priceChangeError: null },
});
totals.dropped += 1;
continue;
}
const amount = Number(pendingAmount.toString());
const country = countryOf({ country: row.country });
try {
await providers(row.provider).updateAmount(
{ country, externalId: row.externalId, checkoutRef: row.checkoutRef },
amount,
row.currency,
);
} catch (error) {
// Never the provider's message: it can echo what we sent.
const reason = error instanceof BillingProviderNotConfigured ? 'not_configured' : 'provider_error';
logger.warn({ subscriptionId: row.id, provider: row.provider, reason }, 'Could not apply a Pro price change');
await db.billingSubscription.updateMany({
where: unchanged,
data: { priceChangeAttempts: { increment: 1 }, priceChangeError: reason },
});
totals.failed += 1;
continue;
}
const moved = await db.billingSubscription.updateMany({
where: unchanged,
data: { amount: pendingAmount, pendingAmount: null, priceChangeAttempts: 0, priceChangeError: null },
});
if (moved.count !== 1) continue;
totals.applied += 1;
try {
await (this.deps.email ?? emailProvider).sendProPriceChanged({
email: row.user.email,
name: row.user.name,
amount: formatAmount(amount, row.currency, country),
nextPaymentDate: row.nextPaymentDate
? new Intl.DateTimeFormat('es-AR', {
day: 'numeric',
month: 'long',
year: 'numeric',
timeZone: COUNTRY_TIME_ZONES[country],
}).format(row.nextPaymentDate)
: null,
billingUrl: `${this.deps.webOrigin ?? getWebOrigin()}/billing`,
});
} catch (error) {
// The price already changed; a lost email is not worth a retry loop.
logger.warn({ err: error, subscriptionId: row.id }, 'Could not email a Pro price change');
}
}
return totals;
}
}

View File

@@ -1,2 +1,3 @@
export { ApplyPriceChanges, type ApplyPriceChangesTotals, MAX_PRICE_CHANGE_ATTEMPTS } from './apply-price-changes';
export { ReconcileSubscriptions, type ReconcileTotals } from './reconcile-subscriptions';
export { startBillingJobs } from './schedule';
export { runPriceChanges, startBillingJobs } from './schedule';

View File

@@ -1,7 +1,9 @@
import { logger } from '@/logger';
import { ApplyPriceChanges } from './apply-price-changes';
import { ReconcileSubscriptions } from './reconcile-subscriptions';
const RECONCILE_CRON = '*/30 * * * *';
const PRICE_CHANGES_CRON = '*/5 * * * *';
/**
* Registers the billing background jobs. Called once from `server.ts`, with the
@@ -21,4 +23,27 @@ export function startBillingJobs(): void {
},
{ tz: 'UTC' },
).unref();
Bun.cron(
PRICE_CHANGES_CRON,
async () => {
await runPriceChanges();
},
{ tz: 'UTC' },
).unref();
}
/**
* Applies the Pro price changes queued by the backoffice. Also called right
* after a save, so the change does not wait for the next tick. Never throws.
*/
export async function runPriceChanges(): Promise<void> {
try {
const totals = await new ApplyPriceChanges().execute();
if (totals.applied + totals.failed + totals.dropped > 0) {
logger.info(totals, 'Pro price changes applied');
}
} catch (error) {
logger.error({ err: error }, 'Applying Pro price changes failed');
}
}

View 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 };
}

View File

@@ -14,3 +14,5 @@ export function getGraceDays(env: Record<string, string | undefined> = process.e
const value = Number(env.BILLING_GRACE_DAYS);
return Number.isInteger(value) && value >= 0 ? value : DEFAULT_GRACE_DAYS;
}
export { getApiPublicOrigin } from '@/lib/public-origin';

View File

@@ -1,12 +1,13 @@
import type { Prisma, PrismaClient, SubscriptionStatus } from '@generated/prisma/client';
import type { Plan, PlanFeature, PlanLimits, ProblemDetails, Result } from '@gruperly/shared';
import { err, ok, PLAN_LIMITS } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import {
planFeatureRequiredProblem,
planLimitReachedProblem,
planReadOnlyProblem,
} from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { type PlanCatalogReader, planCatalog } from './catalog';
import { getGraceDays, isBillingEnforced } from './config';
const DAY_MS = 24 * 60 * 60 * 1000;
@@ -90,6 +91,7 @@ type PlanGuardDeps = {
enforced?: boolean;
graceDays?: number;
now?: () => Date;
catalog?: PlanCatalogReader;
};
/**
@@ -123,7 +125,7 @@ export class PlanGuard {
]);
const resolution = resolvePlan(subscription, now, this.deps.graceDays ?? getGraceDays());
const limits = PLAN_LIMITS[resolution.plan];
const limits = await (this.deps.catalog ?? planCatalog).getLimits(resolution.plan);
const usage = { groups, attendees };
const enforced = this.enforced;

View File

@@ -19,8 +19,18 @@ export function countryOf(user: { country: string | null } | null): CountryCode
return parsed.success ? parsed.data : DEFAULT_COUNTRY;
}
/** Where the billing provider sends the professor after authorizing (or abandoning). */
export function buildSubscriptionBackUrl(webOrigin: string, returnTo: BillingReturnTo): string {
/**
* Where the billing provider sends the professor after authorizing (or
* abandoning): a public API route that bounces to the web
* (`GET /billing/return`), because Mercado Pago refuses a `back_url` on
* localhost and the web is not tunneled in local development.
*/
export function buildSubscriptionBackUrl(apiOrigin: string, returnTo: BillingReturnTo): string {
return `${apiOrigin}/api/v1/billing/return?to=${returnTo}`;
}
/** The web page the professor lands on after the provider's checkout. */
export function buildSubscriptionReturnUrl(webOrigin: string, returnTo: BillingReturnTo): string {
return `${webOrigin}/${returnTo === 'onboarding' ? 'onboarding' : 'billing'}?sub=return`;
}

View File

@@ -1,4 +1,13 @@
export { getGraceDays, isBillingEnforced } from './config';
export {
defaultPlanCatalog,
PlanCatalog,
type PlanCatalogReader,
type PlanCatalogSnapshot,
planCatalog,
staticPlanCatalog,
toPlanCatalogDto,
} from './catalog';
export { getApiPublicOrigin, getGraceDays, isBillingEnforced } from './config';
export {
type Entitlements,
exceedsLimits,
@@ -9,5 +18,5 @@ export {
resolvePlan,
type SubscriptionSnapshot,
} from './entitlements';
export { buildSubscriptionBackUrl, countryOf, toBillingChargeDto } from './helpers';
export { buildSubscriptionBackUrl, buildSubscriptionReturnUrl, countryOf, toBillingChargeDto } from './helpers';
export { SyncSubscription, type SyncSubscriptionDeps, subscriptionRefOf } from './sync';

View File

@@ -105,6 +105,8 @@ export interface BillingProvider {
/** `null` while the professor has not completed the checkout. */
fetch(ref: SubscriptionRef): Promise<ProviderSubscription | null>;
listCharges(ref: SubscriptionRef & { externalId: string }): Promise<ProviderCharge[]>;
/** New monthly amount from the next charge on; what was already charged stays. */
updateAmount(ref: SubscriptionRef & { externalId: string }, amount: number, currency: string): Promise<void>;
/** Stops the monthly charge, or voids a checkout never completed. */
cancel(ref: SubscriptionRef): Promise<void>;
parseWebhook(request: BillingWebhookRequest): Promise<Result<BillingWebhookHint, BillingWebhookFailure>>;

View File

@@ -137,6 +137,13 @@ export class MercadoPagoBillingProvider implements BillingProvider {
await this.client.cancelPreapproval(this.tokenFor(ref.country), ref.externalId);
}
async updateAmount(ref: SubscriptionRef & { externalId: string }, amount: number, currency: string): Promise<void> {
await this.client.updatePreapprovalAmount(this.tokenFor(ref.country), ref.externalId, {
amount,
currencyId: currency,
});
}
/**
* One URL per country, because each country is a different Gruperly account
* with its own secret. Mercado Pago signs a manifest of the notified id, the

View File

@@ -129,6 +129,23 @@ export async function cancelPreapproval(accessToken: string, id: string): Promis
);
}
/**
* Changes the monthly amount of a live preapproval. Mercado Pago applies it to
* the debits that follow; the ones already made are untouched.
*/
export async function updatePreapprovalAmount(
accessToken: string,
id: string,
input: { amount: number; currencyId: string },
): Promise<MpPreapproval> {
return toPreapproval(
await request(accessToken, `/preapproval/${encodeURIComponent(id)}`, {
method: 'PUT',
body: { auto_recurring: { transaction_amount: input.amount, currency_id: input.currencyId } },
}),
);
}
function toAuthorizedPayment(payload: Record<string, unknown>): MpAuthorizedPayment {
const payment = (payload.payment ?? null) as Record<string, unknown> | null;
return {
@@ -181,6 +198,7 @@ export type PreapprovalClient = {
createPreapproval: typeof createPreapproval;
getPreapproval: typeof getPreapproval;
cancelPreapproval: typeof cancelPreapproval;
updatePreapprovalAmount: typeof updatePreapprovalAmount;
getAuthorizedPayment: typeof getAuthorizedPayment;
searchAuthorizedPayments: typeof searchAuthorizedPayments;
};
@@ -189,6 +207,7 @@ export const mpPreapprovalClient: PreapprovalClient = {
createPreapproval,
getPreapproval,
cancelPreapproval,
updatePreapprovalAmount,
getAuthorizedPayment,
searchAuthorizedPayments,
};

View File

@@ -214,6 +214,39 @@ export class StripeBillingProvider implements BillingProvider {
}
}
/**
* Moves the subscription to a new monthly amount from its next invoice on:
* the item gets a new inline price on the same product, without proration,
* so the period already paid is not touched.
*/
async updateAmount(ref: SubscriptionRef & { externalId: string }, amount: number, currency: string): Promise<void> {
const request = this.request;
const path = `/subscriptions/${encodeURIComponent(ref.externalId)}`;
const subscription = await request(path);
const item = objectOf((objectOf(subscription.items)?.data as unknown[] | undefined)?.[0]);
const itemId = idOf(item?.id);
const product = idOf(objectOf(item?.price)?.product);
if (!itemId || !product) throw new Error('Stripe subscription came back without its item');
await request(path, {
method: 'POST',
form: {
proration_behavior: 'none',
items: [
{
id: itemId,
price_data: {
currency: currency.toLowerCase(),
unit_amount: toStripeUnitAmount(amount, currency),
recurring: { interval: 'month' },
product,
},
},
],
},
});
}
/** A single endpoint for the whole account; the event id is the dedupe key. */
async parseWebhook(
request: BillingWebhookRequest,

View File

@@ -1,6 +1,8 @@
import { Hono } from 'hono';
import cancelRoute from './features/cancel/route';
import chargesRoute from './features/charges/route';
import plansRoute from './features/plans/route';
import returnRoute from './features/return/route';
import statusRoute from './features/status/route';
import subscribeRoute from './features/subscribe/route';
import webhookRoute from './features/webhook/route';
@@ -11,6 +13,8 @@ routes.route('/', statusRoute);
routes.route('/', subscribeRoute);
routes.route('/', cancelRoute);
routes.route('/', chargesRoute);
routes.route('/', plansRoute);
routes.route('/', returnRoute);
routes.route('/', webhookRoute);
export default routes;

View File

@@ -25,8 +25,14 @@ route.get('/', validate.query(MpCallbackQuerySchema), async (c) => {
return c.redirect(new URL('/login', getWebOrigin()).toString());
}
const useCase = new CompleteMpAuthorization();
const result = await useCase.execute({ code, state, error });
let result: Awaited<ReturnType<CompleteMpAuthorization['execute']>>;
try {
result = await new CompleteMpAuthorization().execute({ code, state, error, userId: user.id });
} catch (unexpected) {
// A broken deployment (e.g. TOKEN_ENCRYPTION_KEY) still lands back in the app.
logger.error({ err: unexpected }, 'Mercado Pago callback crashed');
return c.redirect(buildMpReturnUrl(getWebOrigin(), 'settings', { kind: 'error', reason: 'mp_error' }));
}
if (!result.ok) {
logger.warn(

View File

@@ -39,6 +39,8 @@ export class CompleteMpAuthorization {
code?: string;
state?: string;
error?: string;
/** The signed-in teacher; has to be the one who started the flow. */
userId: string;
}): Promise<Result<MpCallbackResult, ProblemDetails>> {
let config: ReturnType<typeof getMpOAuthConfig>;
try {
@@ -70,6 +72,14 @@ export class CompleteMpAuthorization {
const returnTo: MpReturnTo = stored.returnTo === 'onboarding' ? 'onboarding' : DEFAULT_RETURN_TO;
// A state started by someone else (a link sent to this teacher) would attach
// this teacher's Mercado Pago account to the other account. Not burned: it
// is not this session's to spend.
if (stored.ownerId !== input.userId) {
logger.warn('Mercado Pago callback with a state from another account');
return failure('invalid_state', returnTo);
}
// Single use, and burned *before* we talk to Mercado Pago: a `count` of zero
// means someone replayed a state we already consumed.
const consumed = await db.mpOAuthState.deleteMany({ where: { state: input.state } });

View File

@@ -0,0 +1,39 @@
import type { MiddlewareHandler } from 'hono';
type Env = Record<string, string | undefined>;
function hostOf(value: string | undefined): string | null {
if (!value?.trim()) return null;
try {
return new URL(value.trim()).host;
} catch {
return null;
}
}
/**
* Where a callback that arrived through the public tunnel has to be replayed,
* or `null` when it is already on the origin that holds the session.
*
* In local development Mercado Pago only accepts an HTTPS Redirect URL, so it
* comes back through ngrok, while the session cookie belongs to the API on
* localhost (`BETTER_AUTH_URL`). In production both are the same host and this
* never fires, so it cannot loop behind the proxy.
*/
export function mpCallbackBounceUrl(requestUrl: string, requestHost: string | undefined, env: Env = process.env): string | null {
const tunnelHost = hostOf(env.MP_REDIRECT_URI);
const sessionOrigin = env.BETTER_AUTH_URL?.trim();
const sessionHost = hostOf(sessionOrigin);
if (!tunnelHost || !sessionOrigin || !sessionHost || tunnelHost === sessionHost) return null;
if (requestHost !== tunnelHost) return null;
const url = new URL(requestUrl);
return `${new URL(sessionOrigin).origin}${url.pathname}${url.search}`;
}
/** Runs before the session middleware, which would answer 401 on the tunnel. */
export const mpCallbackOriginMiddleware: MiddlewareHandler = async (c, next) => {
const target = mpCallbackBounceUrl(c.req.url, c.req.header('x-forwarded-host') ?? c.req.header('host'));
if (target) return c.redirect(target);
await next();
};

View File

@@ -1,3 +1,4 @@
export { mpCallbackBounceUrl, mpCallbackOriginMiddleware } from './callback-origin';
export { getMpOAuthConfig, getWebOrigin, type MpOAuthConfig } from './config';
export {
codeChallengeFromVerifier,

View File

@@ -13,6 +13,8 @@ export type MpCreatePreferenceInput = {
externalReference: string;
/** Where the buyer lands after paying (pending/success/failure). */
backUrl: string;
/** Where Mercado Pago notifies the payment (`POST /payments/webhooks/mp/:id`). */
notificationUrl?: string;
};
export type MpPreference = {
@@ -21,6 +23,21 @@ export type MpPreference = {
sandboxInitPoint: string | null;
};
/**
* Mercado Pago refuses `auto_return` (`invalid_auto_return`) and notification
* URLs unless they are public HTTPS. In local development the web is on
* localhost: the buyer then gets MP's "back to the site" button instead of the
* automatic redirect, and without a tunnel only the polling confirms payments.
*/
export function isPublicHttpsUrl(value: string): boolean {
try {
const url = new URL(value);
return url.protocol === 'https:' && !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
} catch {
return false;
}
}
/**
* Creates a Checkout Pro preference in the seller's account. This is a payment
* *link*: nothing is charged, and creating it again after a lost connection is
@@ -50,7 +67,10 @@ export async function createCheckoutPreference(
},
],
external_reference: input.externalReference,
auto_return: 'approved',
...(isPublicHttpsUrl(input.backUrl) ? { auto_return: 'approved' } : {}),
...(input.notificationUrl && isPublicHttpsUrl(input.notificationUrl)
? { notification_url: input.notificationUrl }
: {}),
back_urls: {
success: input.backUrl,
pending: input.backUrl,
@@ -120,9 +140,10 @@ export async function searchMpPaymentByExternalReference(
const payload = (await response.json()) as { results?: Record<string, unknown>[] } | null;
const results = payload?.results ?? [];
const match = results.find(
(payment) => payment.external_reference === externalReference,
);
// A rejected attempt and a later approved one share the reference: the
// approved one wins, whatever order Mercado Pago lists them in.
const ours = results.filter((payment) => payment.external_reference === externalReference);
const match = ours.find((payment) => payment.status === 'approved') ?? ours[0];
if (!match) {
return null;
}

View File

@@ -15,17 +15,20 @@ import {
notFoundResourceProblem,
} from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { getApiPublicOrigin } from '@/lib/public-origin';
import { logger } from '@/logger';
import { PlanGuard } from '@/modules/billing/lib/entitlements';
import { getMpAccessToken } from '@/modules/mp';
import { createCheckoutPreference, getWebOrigin, MpApiError } from '@/modules/mp/lib';
import { CHECKOUT_BACK_PATH } from '../../lib';
import { CHECKOUT_BACK_PATH, paymentNotificationUrl } from '../../lib';
type BatchDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee' | 'payment' | 'user'>;
createPreference?: typeof createCheckoutPreference;
getToken?: typeof getMpAccessToken;
webOrigin?: string;
/** Public origin of the API, where Mercado Pago notifies the payment. */
apiOrigin?: string;
planGuard?: Pick<PlanGuard, 'requireFeature'>;
};
@@ -128,6 +131,7 @@ export class CreatePaymentBatch {
currencyId: currency,
externalReference: payment.id,
backUrl,
notificationUrl: paymentNotificationUrl(this.deps.apiOrigin ?? getApiPublicOrigin(), payment.id),
});
link = preference;
} catch (error) {

View File

@@ -8,17 +8,20 @@ import {
notFoundResourceProblem,
} from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { getApiPublicOrigin } from '@/lib/public-origin';
import { logger } from '@/logger';
import { PlanGuard } from '@/modules/billing/lib/entitlements';
import { getMpAccessToken } from '@/modules/mp';
import { createCheckoutPreference, getWebOrigin } from '@/modules/mp/lib';
import { CHECKOUT_BACK_PATH, type PaymentRecord, toPaymentDto } from '../../lib';
import { CHECKOUT_BACK_PATH, type PaymentRecord, paymentNotificationUrl, toPaymentDto } from '../../lib';
type RenewDeps = {
db?: Pick<PrismaClient, 'payment' | 'user'>;
createPreference?: typeof createCheckoutPreference;
getToken?: typeof getMpAccessToken;
webOrigin?: string;
/** Public origin of the API, where Mercado Pago notifies the payment. */
apiOrigin?: string;
planGuard?: Pick<PlanGuard, 'requireFeature'>;
};
@@ -94,6 +97,7 @@ export class RenewPaymentLink {
currencyId: currency,
externalReference: payment.id,
backUrl,
notificationUrl: paymentNotificationUrl(this.deps.apiOrigin ?? getApiPublicOrigin(), payment.id),
});
} catch (error) {
if (error instanceof Error) {

View File

@@ -0,0 +1,17 @@
import { Hono } from 'hono';
import { problemJson } from '@/http/problem-details';
import { HandleMpPaymentNotification } from './use-case';
const route = new Hono();
/**
* Public (`isPublicApiRequest`): Mercado Pago calls it with the URL each
* Checkout Pro link carries as `notification_url`.
*/
route.post('/webhooks/mp/:paymentId', async (c) => {
const result = await new HandleMpPaymentNotification().execute(c.req.param('paymentId'));
if (!result.ok) return problemJson(c, result.error);
return c.json({ received: true });
});
export default route;

View File

@@ -0,0 +1,45 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { ProblemDetails, Result } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import { mpProviderErrorProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import { MpApiError } from '@/modules/mp/lib';
import { type ConfirmMpPaymentDeps, type ConfirmMpPaymentOutcome, confirmMpPayment } from '../../lib';
type HandleMpPaymentNotificationDeps = ConfirmMpPaymentDeps & {
db?: Pick<PrismaClient, 'payment'>;
};
export type MpPaymentNotificationOutcome = ConfirmMpPaymentOutcome | 'ignored';
/**
* Mercado Pago says something happened to the payment of one of our links. The
* body is not read: the payment id in the URL picks the row, and the owner's
* account says whether it was approved (`confirmMpPayment`), so a forged or
* repeated notification costs one lookup and changes nothing.
*/
export class HandleMpPaymentNotification {
constructor(private readonly deps: HandleMpPaymentNotificationDeps = {}) {}
async execute(paymentId: string): Promise<Result<{ outcome: MpPaymentNotificationOutcome }, ProblemDetails>> {
const db = this.deps.db ?? prisma;
// OVERDUE too: a student can still pay a link after its due date.
const payment = await db.payment.findFirst({
where: { id: paymentId, status: { in: ['PENDING', 'OVERDUE'] }, checkoutUrl: { not: null } },
select: { id: true, group: { select: { createdById: true } } },
});
if (!payment) return ok({ outcome: 'ignored' });
try {
const outcome = await confirmMpPayment(db, { id: payment.id, ownerId: payment.group.createdById }, this.deps);
return ok({ outcome });
} catch (error) {
if (!(error instanceof MpApiError)) throw error;
// Not a 2xx, so Mercado Pago retries; the polling job is the fallback anyway.
logger.warn({ paymentId: payment.id, status: error.status }, 'Could not confirm a notified Mercado Pago payment');
return err(mpProviderErrorProblem());
}
}
}

View File

@@ -3,15 +3,13 @@ import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import { getMpAccessToken } from '@/modules/mp';
import { MpApiError, searchMpPaymentByExternalReference } from '@/modules/mp/lib';
import { confirmMpPayment } from '../lib';
/**
* Pulls payments from Mercado Pago instead of trusting a webhook. A payment
* link is just a preference until someone pays it; this job asks the seller's
* account for our `external_reference` and marks approved payments as PAID.
*
* This is the stopgap and the source of truth: if a webhook is ever added it
* gives you the confirmation, but this job is what keeps the Cobros screen
* correct even when a notification is lost.
* Pulls payments from Mercado Pago. The notification
* (`POST /payments/webhooks/mp/:id`) confirms them right away; this job is the
* fallback for links created before it existed and for lost notifications.
* Both go through `confirmMpPayment`.
*/
const RECONCILE_AFTER_MS = 5 * 60 * 1000;
const BATCH_LIMIT = 50;
@@ -51,34 +49,21 @@ export class ReconcilePayments {
const totals: ReconcilePaymentsResult = { paid: 0, skipped: 0, failed: 0 };
for (const payment of awaiting) {
const token = await getToken(payment.group.createdById);
if (!token.ok) {
// No usable token (not linked, or needs re-auth). Not a payment problem:
// the row stays PENDING and the account notice tells the professor what to do.
totals.skipped += 1;
continue;
}
try {
const found = await search(token.value.accessToken, payment.id);
if (found && found.status === 'approved' && found.externalReference === payment.id) {
await db.payment.update({
where: { id: payment.id },
data: {
status: 'PAID',
mpPaymentId: found.id,
paidAt: found.dateApproved ? new Date(found.dateApproved) : new Date(),
},
});
totals.paid += 1;
}
const outcome = await confirmMpPayment(
db,
{ id: payment.id, ownerId: payment.group.createdById },
{ getToken, search },
);
// No usable token is not a payment problem: the row stays PENDING and
// the account notice tells the professor what to do.
if (outcome === 'no_token') totals.skipped += 1;
if (outcome === 'paid') totals.paid += 1;
} catch (error) {
if (error instanceof MpApiError) {
totals.failed += 1;
} else {
if (!(error instanceof MpApiError)) {
logger.error({ err: error }, 'Unexpected payment reconciliation failure');
totals.failed += 1;
}
totals.failed += 1;
}
}

View File

@@ -0,0 +1,45 @@
import type { PrismaClient } from '@generated/prisma/client';
import { getMpAccessToken } from '@/modules/mp';
import { searchMpPaymentByExternalReference } from '@/modules/mp/lib';
export type ConfirmMpPaymentDeps = {
getToken?: typeof getMpAccessToken;
search?: typeof searchMpPaymentByExternalReference;
};
/** `no_token`: the owner has no usable Mercado Pago link (not linked, or needs re-auth). */
export type ConfirmMpPaymentOutcome = 'paid' | 'unpaid' | 'no_token';
/**
* Asks the owner's Mercado Pago account whether this payment was approved and,
* if so, marks it PAID. The only rule for a Checkout Pro payment, shared by the
* polling job and the notification: whatever triggered it is never trusted, the
* owner's account is. Throws `MpApiError` when Mercado Pago cannot answer.
*/
export async function confirmMpPayment(
db: Pick<PrismaClient, 'payment'>,
payment: { id: string; ownerId: string },
deps: ConfirmMpPaymentDeps = {},
): Promise<ConfirmMpPaymentOutcome> {
const token = await (deps.getToken ?? getMpAccessToken)(payment.ownerId);
if (!token.ok) return 'no_token';
const found = await (deps.search ?? searchMpPaymentByExternalReference)(token.value.accessToken, payment.id);
if (found?.status !== 'approved' || found.externalReference !== payment.id) return 'unpaid';
await db.payment.update({
where: { id: payment.id },
data: {
status: 'PAID',
mpPaymentId: found.id,
paidAt: found.dateApproved ? new Date(found.dateApproved) : new Date(),
},
});
return 'paid';
}
/** Where Mercado Pago notifies a payment of this link (public: see `isPublicApiRequest`). */
export function paymentNotificationUrl(apiOrigin: string, paymentId: string): string {
// `source_news=webhooks`: only the webhook format, not the legacy IPN copy.
return `${apiOrigin}/api/v1/payments/webhooks/mp/${encodeURIComponent(paymentId)}?source_news=webhooks`;
}

View File

@@ -1 +1,7 @@
export {
type ConfirmMpPaymentDeps,
type ConfirmMpPaymentOutcome,
confirmMpPayment,
paymentNotificationUrl,
} from './confirm-mp-payment';
export { CHECKOUT_BACK_PATH, type PaymentRecord, toPaymentDto } from './helpers';

View File

@@ -3,6 +3,7 @@ import getAllRoute from './features/get-all/route';
import renewRoute from './features/renew/route';
import reportedRoute from './features/reported/route';
import transferDetailsRoute from './features/transfer-details/route';
import webhookRoute from './features/webhook/route';
const routes = new Hono();
@@ -10,5 +11,6 @@ routes.route('/', getAllRoute);
routes.route('/', reportedRoute);
routes.route('/', transferDetailsRoute);
routes.route('/', renewRoute);
routes.route('/', webhookRoute);
export default routes;