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

@@ -38,6 +38,11 @@ TOKEN_ENCRYPTION_KEY=""
# son las del OAuth del profesor). Sin las dos, Pro queda "no disponible" (503).
MP_PLATFORM_ACCESS_TOKEN_AR=""
MP_PLATFORM_WEBHOOK_SECRET_AR=""
# Origen público de esta API, adonde MP y Stripe devuelven el navegador después
# del checkout de Pro (GET /api/v1/billing/return, que redirige a la web). MP
# rechaza localhost: en local poné el túnel (https://TU-DOMINIO.ngrok-free.app).
# Vacío = BETTER_AUTH_URL.
API_PUBLIC_URL=""
# Stripe: una sola cuenta para BR, CL, CO, MX, PE y UY, cobrando en la moneda
# de cada país. Secret key (sk_test_… en local) y el signing secret del webhook
# (whsec_…; en local lo imprime `stripe listen`). Sin las dos, 503 en esos países.

View File

@@ -0,0 +1,67 @@
-- CreateEnum
CREATE TYPE "PlanId" AS ENUM ('FREE', 'PRO');
-- AlterTable
ALTER TABLE "billing_subscriptions" ADD COLUMN "pending_amount" DECIMAL(12,2),
ADD COLUMN "price_change_attempts" INTEGER NOT NULL DEFAULT 0,
ADD COLUMN "price_change_error" TEXT,
ADD COLUMN "price_change_id" TEXT;
-- CreateTable
CREATE TABLE "plan_configs" (
"plan" "PlanId" NOT NULL,
"max_groups" INTEGER,
"max_attendees" INTEGER,
"whatsapp_automations" BOOLEAN NOT NULL,
"mp_charges" BOOLEAN NOT NULL,
"updated_by_id" TEXT,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "plan_configs_pkey" PRIMARY KEY ("plan")
);
-- CreateTable
CREATE TABLE "plan_prices" (
"country_code" TEXT NOT NULL,
"amount" DECIMAL(12,2) NOT NULL,
"updated_by_id" TEXT,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "plan_prices_pkey" PRIMARY KEY ("country_code")
);
-- CreateTable
CREATE TABLE "plan_price_changes" (
"id" TEXT NOT NULL,
"country_code" TEXT NOT NULL,
"previous_amount" DECIMAL(12,2),
"new_amount" DECIMAL(12,2) NOT NULL,
"currency" TEXT NOT NULL,
"apply_to_existing" BOOLEAN NOT NULL,
"queued" INTEGER NOT NULL DEFAULT 0,
"created_by_id" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "plan_price_changes_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "plan_price_changes_country_created_at_idx" ON "plan_price_changes"("country_code", "created_at");
-- CreateIndex
CREATE INDEX "billing_subscriptions_pending_amount_idx" ON "billing_subscriptions"("pending_amount");
-- Seed with the defaults that lived in code (`PLAN_LIMITS`, `PRO_PRICE_BY_COUNTRY`
-- in packages/shared), so nothing changes on deploy.
INSERT INTO "plan_configs" ("plan", "max_groups", "max_attendees", "whatsapp_automations", "mp_charges", "updated_at") VALUES
('FREE', 1, 15, false, false, CURRENT_TIMESTAMP),
('PRO', NULL, NULL, true, true, CURRENT_TIMESTAMP);
INSERT INTO "plan_prices" ("country_code", "amount", "updated_at") VALUES
('AR', 15000, CURRENT_TIMESTAMP),
('BR', 49, CURRENT_TIMESTAMP),
('CL', 9900, CURRENT_TIMESTAMP),
('CO', 39900, CURRENT_TIMESTAMP),
('MX', 199, CURRENT_TIMESTAMP),
('PE', 39, CURRENT_TIMESTAMP),
('UY', 390, CURRENT_TIMESTAMP);

View File

@@ -39,6 +39,12 @@ model BillingSubscription {
// period, even after a cancellation or a failed renewal.
paidThrough DateTime? @map("paid_through")
lastSyncedAt DateTime? @map("last_synced_at")
// A new price queued by the backoffice for this live subscription: the job
// pushes it to the provider (from the next charge) and moves it to `amount`.
pendingAmount Decimal? @db.Decimal(12, 2) @map("pending_amount")
priceChangeId String? @map("price_change_id")
priceChangeAttempts Int @default(0) @map("price_change_attempts")
priceChangeError String? @map("price_change_error")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@ -47,6 +53,7 @@ model BillingSubscription {
// The reconciliation job walks PENDING and stale AUTHORIZED rows.
@@index([status, lastSyncedAt], map: "billing_subscriptions_status_lastSyncedAt_idx")
@@index([pendingAmount], map: "billing_subscriptions_pending_amount_idx")
@@map("billing_subscriptions")
}
@@ -80,3 +87,52 @@ model BillingWebhookEvent {
@@index([receivedAt], map: "billing_webhook_events_receivedAt_idx")
@@map("billing_webhook_events")
}
enum PlanId {
FREE
PRO
}
// What each plan allows, edited from the backoffice. Seeded with the defaults
// of `PLAN_LIMITS` (shared); a missing row falls back to them. Applies at once.
model PlanConfig {
plan PlanId @id
// Null means no limit.
maxGroups Int? @map("max_groups")
maxAttendees Int? @map("max_attendees")
whatsappAutomations Boolean @map("whatsapp_automations")
mpCharges Boolean @map("mp_charges")
updatedById String? @map("updated_by_id")
updatedAt DateTime @updatedAt @map("updated_at")
@@map("plan_configs")
}
// Monthly price of Pro per country, in the country's currency. Seeded with
// `PRO_PRICE_BY_COUNTRY` (shared). New subscriptions take it; live ones keep
// their own `amount` unless a price change is applied to them.
model PlanPrice {
country String @id @map("country_code")
amount Decimal @db.Decimal(12, 2)
updatedById String? @map("updated_by_id")
updatedAt DateTime @updatedAt @map("updated_at")
@@map("plan_prices")
}
// Audit of every price edit from the backoffice.
model PlanPriceChange {
id String @id @default(cuid())
country String @map("country_code")
previousAmount Decimal? @db.Decimal(12, 2) @map("previous_amount")
newAmount Decimal @db.Decimal(12, 2) @map("new_amount")
currency String
applyToExisting Boolean @map("apply_to_existing")
// Live subscriptions queued to move to the new price.
queued Int @default(0)
createdById String? @map("created_by_id")
createdAt DateTime @default(now()) @map("created_at")
@@index([country, createdAt], map: "plan_price_changes_country_created_at_idx")
@@map("plan_price_changes")
}

View File

@@ -25,6 +25,7 @@ import { healthCheckRoutes } from './modules/health-check';
import { homeRoutes } from './modules/home';
import { invitationsRoutes } from './modules/invitations';
import { mpRoutes } from './modules/mp';
import { mpCallbackOriginMiddleware } from './modules/mp/lib';
import { onboardingRoutes } from './modules/onboarding';
import { paymentsRoutes } from './modules/payments';
import { peopleRoutes } from './modules/people';
@@ -43,6 +44,9 @@ app.get('/', (c) => c.json({ name: 'Gruperly API', status: 'ok' }));
const api = app.basePath('/api/v1');
// Local development: the MP callback comes back through the tunnel, without the
// session cookie of localhost. Replay it there before asking for a session.
api.use('/mp/callback', mpCallbackOriginMiddleware);
api.use('*', sessionAuthMiddleware);
// Read-only accounts (Free over its limits) cannot write domain data. Billing,

View File

@@ -47,6 +47,15 @@ export function isPublicApiRequest(method: string, path: string): boolean {
if (method === 'POST' && /^\/api\/v1\/billing\/webhooks\/mp\/[a-z]{2}$/i.test(normalizedPath)) {
return true;
}
// Mercado Pago notifications about a Checkout Pro payment: no session; the
// owner's Mercado Pago account is asked before anything changes.
if (method === 'POST' && /^\/api\/v1\/payments\/webhooks\/mp\/[A-Za-z0-9_-]+$/.test(normalizedPath)) {
return true;
}
// Back from the Pro checkout: only redirects to the web, which has the session.
if (method === 'GET' && normalizedPath === '/api/v1/billing/return') {
return true;
}
// Stripe notifications about Pro subscriptions: authenticated by `Stripe-Signature`.
if (method === 'POST' && normalizedPath === '/api/v1/billing/webhooks/stripe') {
return true;

View File

@@ -6,6 +6,15 @@ type PasswordResetEmailData = { email: string; url: string; name?: string }
type InvitationEmailData = { email: string; url: string; organizationName: string }
type StudentEmailConfirmationData = { email: string; url: string; name: string }
type StudentRecoveryEmailData = { email: string; links: { name: string; url: string }[] }
type ProPriceChangedData = {
email: string
name: string
/** Already formatted in the professor's currency. */
amount: string
/** Already formatted; `null` when the provider has not scheduled the next charge. */
nextPaymentDate: string | null
billingUrl: string
}
type StudentPaymentReviewedData = {
email: string
name: string
@@ -42,6 +51,7 @@ export interface EmailProvider {
sendStudentEmailConfirmation(data: StudentEmailConfirmationData): Promise<void>
sendStudentRecoveryLinks(data: StudentRecoveryEmailData): Promise<void>
sendStudentPaymentReviewed(data: StudentPaymentReviewedData): Promise<void>
sendProPriceChanged(data: ProPriceChangedData): Promise<void>
}
// Names come from what teachers and students type: never raw into the HTML.
@@ -176,6 +186,20 @@ class SMTPEmailProvider implements EmailProvider {
this.layout(confirmed ? 'Pago confirmado' : 'Pago rechazado', body),
)
}
async sendProPriceChanged({ email, name, amount, nextPaymentDate, billingUrl }: ProPriceChangedData) {
const when = nextPaymentDate
? `desde tu próximo cobro, el ${escapeHtml(nextPaymentDate)}`
: 'desde tu próximo cobro'
await this.send(
email,
'Cambia el precio de Gruperly Pro',
this.layout(
'Nuevo precio de Gruperly Pro',
`Hola ${escapeHtml(name)}, te avisamos que el precio de tu suscripción a Gruperly Pro pasa a ser de ${escapeHtml(amount)} por mes ${when}. Lo que ya pagaste no cambia.<br/><br/>Si no querés seguir, podés cancelar la suscripción cuando quieras y vas a seguir con Pro hasta el final del período pago.<br/><br/>${button(billingUrl, 'Ver mi plan')}`,
),
)
}
}
// Future: transactional providers (Resend, SendGrid, Postmark).

View File

@@ -0,0 +1,17 @@
const DEFAULT_API_ORIGIN = 'http://localhost:4000';
/**
* Public origin of this API, as the billing providers reach it. Mercado Pago
* refuses a non-public `back_url` and `notification_url` (localhost), so in local development it is the
* ngrok tunnel. Falls back to `BETTER_AUTH_URL`, which is the API's base URL
* (in production the same origin as the web, since nginx proxies `/api`).
*/
export function getApiPublicOrigin(env: Record<string, string | undefined> = process.env): string {
const configured = env.API_PUBLIC_URL?.trim() || env.BETTER_AUTH_URL?.trim();
if (!configured) return DEFAULT_API_ORIGIN;
try {
return new URL(configured).origin;
} catch {
return DEFAULT_API_ORIGIN;
}
}

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;

View File

@@ -114,6 +114,25 @@ describe('admin access', () => {
expect(db.user.findUnique).not.toHaveBeenCalled();
});
it('forbids the plans to anyone outside the allowlist', async () => {
const app = makeApp('profe@gmail.com');
expect((await app.request('/admin/plans')).status).toBe(403);
expect((await app.request('/admin/plans/FREE/impact?maxGroups=1')).status).toBe(403);
const json = { 'Content-Type': 'application/json' };
const limits = await app.request('/admin/plans/FREE/limits', {
method: 'PUT',
headers: json,
body: JSON.stringify({ maxGroups: 1, maxAttendees: 1, whatsappAutomations: false, mpCharges: false }),
});
expect(limits.status).toBe(403);
const price = await app.request('/admin/plans/prices/AR', {
method: 'PUT',
headers: json,
body: JSON.stringify({ amount: 1, applyToExisting: true }),
});
expect(price.status).toBe(403);
});
it('asks for a session without a user', async () => {
const response = await makeApp(null).request('/admin/accounts');
expect(response.status).toBe(401);

View File

@@ -1,4 +1,5 @@
import { describe, expect, it, mock } from 'bun:test';
import { staticPlanCatalog } from '@/modules/billing/lib/catalog';
import { PlanGuard, resolvePlan } from '@/modules/billing/lib/entitlements';
const now = new Date('2026-10-22T12:00:00.000Z');
@@ -18,7 +19,7 @@ function makeDb(params: {
}
function makeGuard(db: ReturnType<typeof makeDb>, enforced = true) {
return new PlanGuard({ db: db as never, enforced, graceDays: 7, now: () => now });
return new PlanGuard({ db: db as never, enforced, graceDays: 7, now: () => now, catalog: staticPlanCatalog() });
}
describe('resolvePlan', () => {

View File

@@ -0,0 +1,266 @@
import { describe, expect, it, mock } from 'bun:test';
import { PLAN_LIMITS, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared';
import { UpdatePlanPrice } from '@/modules/admin/features/update-plan-price/use-case';
import { ApplyPriceChanges } from '@/modules/billing/jobs/apply-price-changes';
import { defaultPlanCatalog, PlanCatalog, PlanGuard, staticPlanCatalog } from '@/modules/billing/lib';
import { MercadoPagoBillingProvider } from '@/modules/billing/providers/mercado-pago';
import { StripeBillingProvider } from '@/modules/billing/providers/stripe';
const decimal = (value: number) => ({ toString: () => String(value) });
function catalogDb(configs: unknown[] = [], prices: unknown[] = []) {
return {
planConfig: { findMany: mock(async () => configs) },
planPrice: { findMany: mock(async () => prices) },
};
}
describe('PlanCatalog', () => {
it('falls back to the shared defaults when the tables are empty', async () => {
const catalog = new PlanCatalog({ db: catalogDb() as never });
expect(await catalog.getLimits('FREE')).toEqual(PLAN_LIMITS.FREE);
expect(await catalog.getProPrice('AR')).toBe(PRO_PRICE_BY_COUNTRY.AR);
});
it('reads the limits and prices edited from the backoffice', async () => {
const db = catalogDb(
[{ plan: 'FREE', maxGroups: 2, maxAttendees: 30, whatsappAutomations: true, mpCharges: false }],
[{ country: 'AR', amount: decimal(18000) }, { country: 'XX', amount: decimal(1) }],
);
const catalog = new PlanCatalog({ db: db as never });
expect(await catalog.getLimits('FREE')).toEqual({
maxGroups: 2,
maxAttendees: 30,
whatsappAutomations: true,
mpCharges: false,
});
expect(await catalog.getLimits('PRO')).toEqual(PLAN_LIMITS.PRO);
expect(await catalog.getProPrice('AR')).toBe(18000);
expect(await catalog.getProPrice('MX')).toBe(PRO_PRICE_BY_COUNTRY.MX);
});
it('caches within the TTL until invalidated', async () => {
let clock = 0;
const db = catalogDb();
const catalog = new PlanCatalog({ db: db as never, ttlMs: 1000, now: () => clock });
await catalog.snapshot();
clock = 500;
await catalog.snapshot();
expect(db.planConfig.findMany).toHaveBeenCalledTimes(1);
catalog.invalidate();
await catalog.snapshot();
expect(db.planConfig.findMany).toHaveBeenCalledTimes(2);
clock = 2000;
await catalog.snapshot();
expect(db.planConfig.findMany).toHaveBeenCalledTimes(3);
});
it('keeps working on the defaults if the database fails, without caching them', async () => {
const db = {
planConfig: { findMany: mock(async () => Promise.reject(new Error('down'))) },
planPrice: { findMany: mock(async () => []) },
};
const catalog = new PlanCatalog({ db: db as never });
expect(await catalog.getLimits('FREE')).toEqual(PLAN_LIMITS.FREE);
await catalog.snapshot();
expect(db.planConfig.findMany).toHaveBeenCalledTimes(2);
});
it('feeds the PlanGuard', async () => {
const snapshot = defaultPlanCatalog();
snapshot.limits.FREE = { ...snapshot.limits.FREE, maxGroups: 3 };
const guard = new PlanGuard({
enforced: true,
catalog: staticPlanCatalog(snapshot),
db: {
billingSubscription: { findUnique: async () => null },
group: { count: async () => 2 },
person: { count: async () => 0 },
} as never,
});
expect((await guard.canCreateGroup('owner-1')).ok).toBe(true);
});
});
function priceTx(updated = 3) {
const tx = {
planPrice: { upsert: mock(async () => ({})) },
planPriceChange: { create: mock(async () => ({ id: 'change-1' })), update: mock(async () => ({})) },
billingSubscription: { updateMany: mock(async () => ({ count: updated })) },
};
const db = { $transaction: mock(async (run: (client: typeof tx) => unknown) => run(tx)) };
return { tx, db };
}
describe('UpdatePlanPrice', () => {
const catalog = { invalidate: mock(), getProPrice: mock(async () => 15000) };
it('queues the live subscriptions of the country and kicks the job', async () => {
const { tx, db } = priceTx(3);
const applyQueued = mock(async () => {});
const result = await new UpdatePlanPrice({ db: db as never, catalog, applyQueued }).execute(
'AR',
{ amount: 18000, applyToExisting: true },
'staff-1',
);
expect(result).toEqual({ ok: true, value: { country: 'AR', amount: 18000, queued: 3 } });
expect(tx.planPrice.upsert).toHaveBeenCalled();
expect(tx.planPriceChange.create.mock.calls[0]?.[0]).toMatchObject({
data: { country: 'AR', previousAmount: 15000, newAmount: 18000, currency: 'ARS', applyToExisting: true },
});
expect(tx.billingSubscription.updateMany.mock.calls[0]?.[0]).toMatchObject({
where: {
country: 'AR',
status: { in: ['AUTHORIZED', 'PAUSED'] },
externalId: { not: null },
},
});
expect(tx.planPriceChange.update).toHaveBeenCalledWith({ where: { id: 'change-1' }, data: { queued: 3 } });
expect(catalog.invalidate).toHaveBeenCalled();
expect(applyQueued).toHaveBeenCalledTimes(1);
});
it('only changes the price for new subscriptions when not applied to existing ones', async () => {
const { tx, db } = priceTx();
const applyQueued = mock(async () => {});
const result = await new UpdatePlanPrice({ db: db as never, catalog, applyQueued }).execute(
'AR',
{ amount: 18000, applyToExisting: false },
'staff-1',
);
expect(result.ok && result.value.queued).toBe(0);
expect(tx.billingSubscription.updateMany).not.toHaveBeenCalled();
expect(applyQueued).not.toHaveBeenCalled();
});
});
function row(overrides: Record<string, unknown> = {}) {
return {
id: 'sub-1',
country: 'AR',
currency: 'ARS',
provider: 'MERCADO_PAGO',
status: 'AUTHORIZED',
externalId: 'pre-1',
checkoutRef: null,
amount: decimal(15000),
pendingAmount: decimal(18000),
nextPaymentDate: new Date('2026-12-05T12:00:00.000Z'),
user: { name: 'Ana', email: 'ana@gruperly.test', country: 'AR' },
...overrides,
};
}
function applyHarness(rows: unknown[], { fail = false, moved = 1 } = {}) {
const db = {
billingSubscription: {
findMany: mock(async () => rows),
updateMany: mock(async () => ({ count: moved })),
},
};
const provider = {
updateAmount: mock(async () => {
if (fail) throw new Error('boom');
}),
};
const email = { sendProPriceChanged: mock(async () => {}) };
const job = new ApplyPriceChanges({
db: db as never,
providers: () => provider as never,
email,
webOrigin: 'http://web',
});
return { db, provider, email, job };
}
describe('ApplyPriceChanges', () => {
it('pushes the price to the provider, moves it to amount and emails the professor', async () => {
const pending = row();
const { db, provider, email, job } = applyHarness([pending]);
expect(await job.execute()).toEqual({ applied: 1, failed: 0, dropped: 0 });
expect(provider.updateAmount).toHaveBeenCalledWith(
{ country: 'AR', externalId: 'pre-1', checkoutRef: null },
18000,
'ARS',
);
expect(db.billingSubscription.updateMany).toHaveBeenCalledWith({
where: { id: 'sub-1', pendingAmount: pending.pendingAmount },
data: { amount: pending.pendingAmount, pendingAmount: null, priceChangeAttempts: 0, priceChangeError: null },
});
expect(email.sendProPriceChanged).toHaveBeenCalledTimes(1);
const sent = (email.sendProPriceChanged.mock.calls[0] as unknown[])[0] as Record<string, string>;
expect(sent).toMatchObject({ email: 'ana@gruperly.test', name: 'Ana', billingUrl: 'http://web/billing' });
expect(sent.amount).toContain('18.000');
});
it('counts a refusal as an attempt and keeps the change queued', async () => {
const { db, email, job } = applyHarness([row()], { fail: true });
expect(await job.execute()).toEqual({ applied: 0, failed: 1, dropped: 0 });
expect(db.billingSubscription.updateMany.mock.calls[0]?.[0]).toMatchObject({
data: { priceChangeAttempts: { increment: 1 }, priceChangeError: 'provider_error' },
});
expect(email.sendProPriceChanged).not.toHaveBeenCalled();
});
it('drops the change of a subscription cancelled meanwhile', async () => {
const { provider, job } = applyHarness([row({ status: 'CANCELLED' })]);
expect(await job.execute()).toEqual({ applied: 0, failed: 0, dropped: 1 });
expect(provider.updateAmount).not.toHaveBeenCalled();
});
it('does not email twice when another instance already applied it', async () => {
const { email, job } = applyHarness([row()], { moved: 0 });
expect(await job.execute()).toEqual({ applied: 0, failed: 0, dropped: 0 });
expect(email.sendProPriceChanged).not.toHaveBeenCalled();
});
});
describe('updateAmount', () => {
it('Mercado Pago changes the preapproval amount', async () => {
const client = { updatePreapprovalAmount: mock(async () => ({})) };
const provider = new MercadoPagoBillingProvider({
client: client as never,
credentials: () => ({ accessToken: 'platform-token', webhookSecret: 'secret' }),
});
await provider.updateAmount({ country: 'AR', externalId: 'pre-1', checkoutRef: null }, 18000, 'ARS');
expect(client.updatePreapprovalAmount).toHaveBeenCalledWith('platform-token', 'pre-1', {
amount: 18000,
currencyId: 'ARS',
});
});
it('Stripe reprices the item on its product without proration', async () => {
const calls: { method: string; path: string; body: URLSearchParams | null }[] = [];
const fetch = mock(async (input: string, init: RequestInit) => {
const method = init.method ?? 'GET';
calls.push({
method,
path: new URL(input).pathname,
body: init.body ? new URLSearchParams(String(init.body)) : null,
});
return new Response(
JSON.stringify({ id: 'sub_1', items: { data: [{ id: 'si_1', price: { product: 'prod_1' } }] } }),
);
});
const provider = new StripeBillingProvider({
config: () => ({ secretKey: 'sk_test', webhookSecret: 'whsec' }),
fetch: fetch as never,
});
await provider.updateAmount({ country: 'MX', externalId: 'sub_1', checkoutRef: null }, 249, 'MXN');
expect(calls.map((call) => `${call.method} ${call.path}`)).toEqual([
'GET /v1/subscriptions/sub_1',
'POST /v1/subscriptions/sub_1',
]);
const body = calls[1]?.body;
expect(body?.get('proration_behavior')).toBe('none');
expect(body?.get('items[0][id]')).toBe('si_1');
expect(body?.get('items[0][price_data][product]')).toBe('prod_1');
expect(body?.get('items[0][price_data][unit_amount]')).toBe('24900');
expect(body?.get('items[0][price_data][currency]')).toBe('mxn');
expect(body?.get('items[0][price_data][recurring][interval]')).toBe('month');
});
});

View File

@@ -0,0 +1,55 @@
import { afterEach, describe, expect, it } from 'bun:test';
import { Hono } from 'hono';
import { isPublicApiRequest } from '@/http/session-auth';
import returnRoute from '@/modules/billing/features/return/route';
import { getApiPublicOrigin } from '@/modules/billing/lib';
const previousWebUrl = process.env.WEB_URL;
function makeApp() {
return new Hono().basePath('/api/v1').route('/billing', returnRoute);
}
describe('GET /billing/return', () => {
afterEach(() => {
process.env.WEB_URL = previousWebUrl;
});
it('bounces the browser to the billing screen of the web', async () => {
process.env.WEB_URL = 'https://app.example.com';
const res = await makeApp().request('/api/v1/billing/return?to=billing&preapproval_id=pre-1');
expect(res.status).toBe(302);
expect(res.headers.get('location')).toBe('https://app.example.com/billing?sub=return');
});
it('goes back to the onboarding step when it started there', async () => {
process.env.WEB_URL = 'https://app.example.com';
const res = await makeApp().request('/api/v1/billing/return?to=onboarding');
expect(res.headers.get('location')).toBe('https://app.example.com/onboarding?sub=return');
});
it('never redirects anywhere but the web', async () => {
process.env.WEB_URL = 'https://app.example.com';
const res = await makeApp().request('/api/v1/billing/return?to=https://evil.example');
expect(res.headers.get('location')).toBe('https://app.example.com/billing?sub=return');
});
it('is reachable without a session', () => {
expect(isPublicApiRequest('GET', '/api/v1/billing/return')).toBe(true);
expect(isPublicApiRequest('POST', '/api/v1/billing/return')).toBe(false);
});
});
describe('getApiPublicOrigin', () => {
it('prefers API_PUBLIC_URL, then BETTER_AUTH_URL, then localhost', () => {
expect(
getApiPublicOrigin({ API_PUBLIC_URL: 'https://x.ngrok-free.app/', BETTER_AUTH_URL: 'http://localhost:4000' }),
).toBe('https://x.ngrok-free.app');
expect(getApiPublicOrigin({ BETTER_AUTH_URL: 'https://app.example.com' })).toBe('https://app.example.com');
expect(getApiPublicOrigin({})).toBe('http://localhost:4000');
expect(getApiPublicOrigin({ API_PUBLIC_URL: 'not a url' })).toBe('http://localhost:4000');
});
});

View File

@@ -1,6 +1,7 @@
import { beforeEach, describe, expect, it, mock } from 'bun:test';
import { CancelSubscription } from '@/modules/billing/features/cancel/use-case';
import { Subscribe } from '@/modules/billing/features/subscribe/use-case';
import { staticPlanCatalog } from '@/modules/billing/lib/catalog';
import type { BillingProvider } from '@/modules/billing/providers';
import { MercadoPagoBillingProvider, type PreapprovalClient } from '@/modules/billing/providers/mercado-pago';
@@ -53,7 +54,7 @@ function subscribe(db: ReturnType<typeof makeDb>, client = makeClient()) {
return {
client,
run: (returnTo: 'billing' | 'onboarding' = 'billing') =>
new Subscribe({ db: db as never, providers: () => provider, webOrigin: 'http://web', now: () => now }).execute(
new Subscribe({ catalog: staticPlanCatalog(), db: db as never, providers: () => provider, apiOrigin: 'https://api', now: () => now }).execute(
userId,
{ payerEmail: 'profe@mail.com', returnTo },
),
@@ -79,7 +80,7 @@ describe('Subscribe', () => {
payerEmail: 'profe@mail.com',
amount: 15000,
currencyId: 'ARS',
backUrl: 'http://web/billing?sub=return',
backUrl: 'https://api/api/v1/billing/return?to=billing',
startDate: undefined,
});
expect(db.billingSubscription.update).toHaveBeenCalledWith({
@@ -93,7 +94,7 @@ describe('Subscribe', () => {
await run('onboarding');
expect((client.createPreapproval as ReturnType<typeof mock>).mock.calls[0]?.[1]).toMatchObject({
backUrl: 'http://web/onboarding?sub=return',
backUrl: 'https://api/api/v1/billing/return?to=onboarding',
});
});
@@ -131,7 +132,7 @@ describe('Subscribe', () => {
const db = makeDb(null, 'AR');
const client = makeClient();
const provider = new MercadoPagoBillingProvider({ client, credentials: () => null });
const result = await new Subscribe({ db: db as never, providers: () => provider }).execute(userId, {
const result = await new Subscribe({ catalog: staticPlanCatalog(), db: db as never, providers: () => provider }).execute(userId, {
payerEmail: 'profe@mail.com',
returnTo: 'billing',
});
@@ -224,13 +225,13 @@ describe('Subscribe outside Argentina (Stripe)', () => {
const stripe = fakeStripe();
const resolved: string[] = [];
const result = await new Subscribe({
const result = await new Subscribe({ catalog: staticPlanCatalog(),
db: db as never,
providers: (id) => {
resolved.push(id);
return stripe;
},
webOrigin: 'http://web',
apiOrigin: 'https://api',
now: () => now,
}).execute(userId, { returnTo: 'billing' });
@@ -242,7 +243,7 @@ describe('Subscribe outside Argentina (Stripe)', () => {
amount: 199,
currency: 'MXN',
payerEmail: null,
backUrl: 'http://web/billing?sub=return',
backUrl: 'https://api/api/v1/billing/return?to=billing',
startDate: undefined,
});
expect((db.billingSubscription.upsert.mock.calls[0] as unknown as [{ create: Record<string, unknown> }])[0].create).toMatchObject({
@@ -261,10 +262,10 @@ describe('Subscribe outside Argentina (Stripe)', () => {
const mp = mpProvider(client);
const stripe = fakeStripe();
await new Subscribe({
await new Subscribe({ catalog: staticPlanCatalog(),
db: db as never,
providers: (id) => (id === 'MERCADO_PAGO' ? mp : stripe),
webOrigin: 'http://web',
apiOrigin: 'https://api',
now: () => now,
}).execute(userId, { returnTo: 'billing' });
@@ -275,7 +276,7 @@ describe('Subscribe outside Argentina (Stripe)', () => {
const db = makeDb(null, 'CL');
const stripe = fakeStripe({ isAvailable: () => false });
const result = await new Subscribe({ db: db as never, providers: () => stripe }).execute(userId, {
const result = await new Subscribe({ catalog: staticPlanCatalog(), db: db as never, providers: () => stripe }).execute(userId, {
returnTo: 'billing',
});
@@ -288,7 +289,7 @@ describe('Subscribe outside Argentina (Stripe)', () => {
const db = makeDb(null, 'AR');
const provider = mpProvider(makeClient());
const result = await new Subscribe({ db: db as never, providers: () => provider }).execute(userId, {
const result = await new Subscribe({ catalog: staticPlanCatalog(), db: db as never, providers: () => provider }).execute(userId, {
returnTo: 'billing',
});

View File

@@ -0,0 +1,78 @@
import { afterEach, describe, expect, it } from 'bun:test';
import { createCheckoutPreference, isPublicHttpsUrl, searchMpPaymentByExternalReference } from '@/modules/mp/lib/mp-http';
describe('isPublicHttpsUrl', () => {
it('only asks Mercado Pago for the automatic return on public HTTPS', () => {
expect(isPublicHttpsUrl('https://app.gruperly.com/student/payments')).toBe(true);
expect(isPublicHttpsUrl('http://localhost:6173/student/payments')).toBe(false);
expect(isPublicHttpsUrl('https://localhost:6173/student/payments')).toBe(false);
expect(isPublicHttpsUrl('http://app.gruperly.com/student/payments')).toBe(false);
expect(isPublicHttpsUrl('not a url')).toBe(false);
});
});
describe('createCheckoutPreference', () => {
const realFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = realFetch;
});
async function sentBody(input: { backUrl: string; notificationUrl?: string }) {
let body: Record<string, unknown> = {};
globalThis.fetch = (async (_url: string, init: RequestInit) => {
body = JSON.parse(String(init.body));
return new Response(JSON.stringify({ id: 'pref-1', init_point: 'https://mp/pay' }), { status: 201 });
}) as unknown as typeof fetch;
await createCheckoutPreference('token', {
title: 'Octubre',
unitPrice: 100,
currencyId: 'ARS',
externalReference: 'pay-1',
...input,
});
return body;
}
it('asks for the automatic return and the notification on public HTTPS', async () => {
const body = await sentBody({
backUrl: 'https://app.gruperly.com/student/payments',
notificationUrl: 'https://app.gruperly.com/api/v1/payments/webhooks/mp/pay-1?source_news=webhooks',
});
expect(body.auto_return).toBe('approved');
expect(body.notification_url).toBe(
'https://app.gruperly.com/api/v1/payments/webhooks/mp/pay-1?source_news=webhooks',
);
});
it('leaves both out on localhost, which Mercado Pago refuses', async () => {
const body = await sentBody({
backUrl: 'http://localhost:6173/student/payments',
notificationUrl: 'http://localhost:4000/api/v1/payments/webhooks/mp/pay-1',
});
expect(body).not.toHaveProperty('auto_return');
expect(body).not.toHaveProperty('notification_url');
});
});
describe('searchMpPaymentByExternalReference', () => {
const realFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = realFetch;
});
it('prefers the approved attempt over an earlier rejected one', async () => {
globalThis.fetch = (async () =>
new Response(
JSON.stringify({
results: [
{ id: 1, status: 'rejected', external_reference: 'pay-1' },
{ id: 2, status: 'approved', external_reference: 'pay-1', date_approved: '2026-11-11T03:00:00.000Z' },
],
}),
{ status: 200 },
)) as unknown as typeof fetch;
const found = await searchMpPaymentByExternalReference('token', 'pay-1');
expect(found).toMatchObject({ id: '2', status: 'approved' });
});
});

View File

@@ -27,6 +27,7 @@ import prisma from '@/lib/prisma';
import { getMpAccessToken, mpRoutes } from '@/modules/mp';
import { RefreshExpiringMpTokens } from '@/modules/mp/jobs/refresh-expiring-mp-tokens';
import { RefreshMpAccount } from '@/modules/mp/jobs/refresh-mp-account';
import { mpCallbackBounceUrl } from '@/modules/mp/lib/callback-origin';
import { codeChallengeFromVerifier, openToken, sealToken } from '@/modules/mp/lib/crypto';
import { MpApiError } from '@/modules/mp/lib/mp-oauth';
@@ -579,6 +580,17 @@ describe('modules/mp', () => {
expect(location.href).not.toContain(storedState.codeVerifier);
});
it('refuses a state started by another teacher, without spending it', async () => {
prisma.mpOAuthState.findUnique.mockResolvedValue({ ...storedState, ownerId: otherOwnerId });
const res = await makeApp({ id: ownerId }).request(callbackUrl('?code=auth-code-123&state=state-abc'));
expect(res.status).toBe(302);
expect(locationOf(res).searchParams.get('reason')).toBe('invalid_state');
expect(prisma.mpOAuthState.deleteMany).not.toHaveBeenCalled();
expect(prisma.mpAccount.upsert).not.toHaveBeenCalled();
});
it('sends a teacher without a session to the login screen', async () => {
const res = await makeApp(null).request(callbackUrl('?code=code&state=state-abc'));
@@ -1040,3 +1052,30 @@ describe('modules/mp RefreshExpiringMpTokens', () => {
expect(totals).toEqual({ refreshed: 1, requiresReauth: 1, failed: 1 });
});
});
describe('mpCallbackBounceUrl', () => {
const env = {
MP_REDIRECT_URI: 'https://tunnel.ngrok-free.app/api/v1/mp/callback',
BETTER_AUTH_URL: 'http://localhost:4000',
};
const url = 'https://tunnel.ngrok-free.app/api/v1/mp/callback?code=c&state=s';
it('replays a callback that came through the tunnel on the origin with the session', () => {
expect(mpCallbackBounceUrl(url, 'tunnel.ngrok-free.app', env)).toBe(
'http://localhost:4000/api/v1/mp/callback?code=c&state=s',
);
});
it('leaves it alone once it is on the session origin', () => {
expect(mpCallbackBounceUrl('http://localhost:4000/api/v1/mp/callback?code=c', 'localhost:4000', env)).toBeNull();
});
it('never fires when the redirect and the session share a host (production)', () => {
const prod = {
MP_REDIRECT_URI: 'https://app.gruperly.com/api/v1/mp/callback',
BETTER_AUTH_URL: 'https://app.gruperly.com',
};
expect(mpCallbackBounceUrl('http://api:4000/api/v1/mp/callback?code=c', 'app.gruperly.com', prod)).toBeNull();
expect(mpCallbackBounceUrl('http://api:4000/api/v1/mp/callback?code=c', 'api:4000', prod)).toBeNull();
});
});

View File

@@ -69,7 +69,7 @@ function batchUseCase() {
initPoint: 'https://mp.link/pay-1',
sandboxInitPoint: null,
}));
return new CreatePaymentBatch({ getToken, createPreference, webOrigin });
return new CreatePaymentBatch({ getToken, createPreference, webOrigin, apiOrigin: 'https://api' });
}
describe('create payments batch', () => {
@@ -143,6 +143,7 @@ describe('create payments batch', () => {
currencyId: 'ARS',
externalReference: 'pay-1',
backUrl: `${webOrigin}/student/payments`,
notificationUrl: 'https://api/api/v1/payments/webhooks/mp/pay-1?source_news=webhooks',
});
});
@@ -191,7 +192,7 @@ describe('create payments batch', () => {
throw new Error('should not be called');
});
const result = await new CreatePaymentBatch({ getToken, createPreference, webOrigin }).execute(
const result = await new CreatePaymentBatch({ getToken, createPreference, webOrigin, apiOrigin: 'https://api' }).execute(
'group-1',
userId,
{ dueDate: '2026-10-05T12:00:00.000Z' },

View File

@@ -83,7 +83,7 @@ describe('renew payment link', () => {
sandboxInitPoint: null,
}));
const result = await new RenewPaymentLink({ getToken, createPreference, webOrigin }).execute(
const result = await new RenewPaymentLink({ getToken, createPreference, webOrigin, apiOrigin: 'https://api' }).execute(
'pay-1',
userId,
);
@@ -102,6 +102,7 @@ describe('renew payment link', () => {
currencyId: 'ARS',
externalReference: 'pay-1',
backUrl: `${webOrigin}/student/payments`,
notificationUrl: 'https://api/api/v1/payments/webhooks/mp/pay-1?source_news=webhooks',
});
expect(prisma.payment.update).toHaveBeenCalledWith({
where: { id: 'pay-1' },

View File

@@ -0,0 +1,103 @@
import { describe, expect, it, mock } from 'bun:test';
import { isPublicApiRequest } from '@/http/session-auth';
import { MpApiError } from '@/modules/mp/lib/mp-oauth';
import { HandleMpPaymentNotification } from '@/modules/payments/features/webhook/use-case';
import { paymentNotificationUrl } from '@/modules/payments/lib';
const ownerId = 'user-1';
const tokenOk = () =>
mock(async () => ({ ok: true, value: { accountId: 'acc-1', accessToken: 'token-1', expiresAt: new Date() } }));
function makeDb(row: unknown) {
return {
payment: {
findFirst: mock(async () => row),
update: mock(async () => ({})),
},
};
}
const linked = { id: 'pay-1', group: { createdById: ownerId } };
describe('HandleMpPaymentNotification', () => {
it('marks the payment PAID once the owner account confirms it was approved', async () => {
const db = makeDb(linked);
const getToken = tokenOk();
const search = mock(async () => ({
id: '999',
status: 'approved',
externalReference: 'pay-1',
liveMode: true,
dateApproved: '2026-11-11T03:00:00.000Z',
}));
const result = await new HandleMpPaymentNotification({ db: db as never, getToken, search }).execute('pay-1');
expect(result).toEqual({ ok: true, value: { outcome: 'paid' } });
expect(getToken).toHaveBeenCalledWith(ownerId);
expect(search).toHaveBeenCalledWith('token-1', 'pay-1');
expect(db.payment.update).toHaveBeenCalledWith({
where: { id: 'pay-1' },
data: { status: 'PAID', mpPaymentId: '999', paidAt: new Date('2026-11-11T03:00:00.000Z') },
});
expect(db.payment.findFirst).toHaveBeenCalledWith(
expect.objectContaining({
where: { id: 'pay-1', status: { in: ['PENDING', 'OVERDUE'] }, checkoutUrl: { not: null } },
}),
);
});
it('changes nothing while the payment is not approved', async () => {
const db = makeDb(linked);
const search = mock(async () => ({
id: '999',
status: 'rejected',
externalReference: 'pay-1',
liveMode: true,
dateApproved: null,
}));
const result = await new HandleMpPaymentNotification({ db: db as never, getToken: tokenOk(), search }).execute(
'pay-1',
);
expect(result).toEqual({ ok: true, value: { outcome: 'unpaid' } });
expect(db.payment.update).not.toHaveBeenCalled();
});
it('ignores an unknown, already paid or link-less payment without asking Mercado Pago', async () => {
const db = makeDb(null);
const search = mock(async () => null);
const result = await new HandleMpPaymentNotification({ db: db as never, getToken: tokenOk(), search }).execute(
'pay-x',
);
expect(result).toEqual({ ok: true, value: { outcome: 'ignored' } });
expect(search).not.toHaveBeenCalled();
});
it('answers an error when Mercado Pago cannot be asked, so it retries', async () => {
const db = makeDb(linked);
const search = mock(async () => {
throw new MpApiError(503, null);
});
const result = await new HandleMpPaymentNotification({ db: db as never, getToken: tokenOk(), search }).execute(
'pay-1',
);
expect(result.ok).toBe(false);
expect(db.payment.update).not.toHaveBeenCalled();
});
});
describe('payment notification URL', () => {
it('points at the public payment webhook, which needs no session', () => {
const url = paymentNotificationUrl('https://x.ngrok-free.app', 'cmabc123');
expect(url).toBe('https://x.ngrok-free.app/api/v1/payments/webhooks/mp/cmabc123?source_news=webhooks');
expect(isPublicApiRequest('POST', new URL(url).pathname)).toBe(true);
expect(isPublicApiRequest('GET', new URL(url).pathname)).toBe(false);
expect(isPublicApiRequest('POST', '/api/v1/payments/webhooks/mp/a/b')).toBe(false);
});
});