Files
gruperly/apps/backend/src/modules/admin/features/update-plan-price/use-case.ts
Jose Selesan aac142d324 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>
2026-11-11 07:50:14 -03:00

90 lines
3.2 KiB
TypeScript

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