import type { PrismaClient } from '@generated/prisma/client'; import type { AutoChargeSettingsDto, ProblemDetails, Result, UpdateAutoChargeSettings } from '@gruperly/shared'; import { AUTO_CHARGE_DEFAULT_DUE_IN_DAYS, ok } from '@gruperly/shared'; import prisma from '@/lib/prisma'; import { PlanGuard } from '@/modules/billing/lib/entitlements'; import { teacherTimeZone } from '@/modules/student-portal/lib/schedule'; import { localDateIn, monthKey, nextAutoChargeDate } from '../../lib/auto-charge-schedule'; type AutoChargeSettingsDeps = { db?: Pick; planGuard?: Pick; now?: Date; }; const DEFAULTS = { enabled: false, chargeDay: 1, dueInDays: AUTO_CHARGE_DEFAULT_DUE_IN_DAYS, sendWhatsapp: false, enabledAt: null }; /** * Settings → "Cobro automático": the teacher's day of the month, due days and * whether the links go out by WhatsApp. Turning something on goes through the * plan (Mercado Pago charges; WhatsApp automations for the sending); turning it * off always works. */ export class AutoChargeSettingsUseCase { constructor(private readonly deps: AutoChargeSettingsDeps = {}) {} private get db() { return this.deps.db ?? prisma; } async get(ownerId: string): Promise> { return ok(await this.load(ownerId)); } async update(ownerId: string, input: UpdateAutoChargeSettings): Promise> { const planGuard = this.deps.planGuard ?? new PlanGuard(); if (input.enabled === true) { const allowed = await planGuard.requireFeature(ownerId, 'mpCharges'); if (!allowed.ok) return allowed; } if (input.sendWhatsapp === true) { const allowed = await planGuard.requireFeature(ownerId, 'whatsappAutomations'); if (!allowed.ok) return allowed; } const current = await this.db.autoChargeSettings.findUnique({ where: { ownerId } }); const turningOn = input.enabled === true && !current?.enabled; const data = { ...(input.enabled !== undefined ? { enabled: input.enabled } : {}), ...(input.chargeDay !== undefined ? { chargeDay: input.chargeDay } : {}), ...(input.dueInDays !== undefined ? { dueInDays: input.dueInDays } : {}), ...(input.sendWhatsapp !== undefined ? { sendWhatsapp: input.sendWhatsapp } : {}), ...(turningOn ? { enabledAt: this.deps.now ?? new Date() } : {}), }; await this.db.autoChargeSettings.upsert({ where: { ownerId }, create: { ownerId, ...data }, update: data }); return ok(await this.load(ownerId)); } private async load(ownerId: string): Promise { const now = this.deps.now ?? new Date(); const [settings, owner, lastRun] = await Promise.all([ this.db.autoChargeSettings.findUnique({ where: { ownerId } }), this.db.user.findUnique({ where: { id: ownerId }, select: { country: true } }), this.db.paymentRun.findFirst({ where: { ownerId }, orderBy: { createdAt: 'desc' } }), ]); const current = settings ?? DEFAULTS; const timeZone = teacherTimeZone(owner?.country); const ranThisMonth = lastRun?.periodKey === monthKey(localDateIn(now, timeZone)); return { enabled: current.enabled, chargeDay: current.chargeDay, dueInDays: current.dueInDays, sendWhatsapp: current.sendWhatsapp, nextRunDate: current.enabled ? nextAutoChargeDate(current, now, timeZone, ranThisMonth) : null, lastRun: lastRun ? { periodKey: lastRun.periodKey, status: lastRun.status, skipReason: lastRun.skipReason, fees: lastRun.fees, checkouts: lastRun.checkouts, linked: lastRun.linked, failed: lastRun.failed, sent: lastRun.sent, createdAt: lastRun.createdAt.toISOString(), } : null, }; } }