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; catalog?: Pick; /** Kicks the job that pushes queued prices to the providers. */ applyQueued?: () => Promise; }; /** * 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> { 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 }); } }