- Teacher picks a day of the month in Settings; an hourly job creates the fees of all monthly groups on that day in the teacher's time zone (one run per teacher and month, partial unique index per attendee/period). - One Mercado Pago link per payer (PaymentCheckout): the adult in charge bundles their kids and their own fees; external_reference chk_<id>, dedicated webhook and reconciliation mark every fee PAID at once. - Person.payWithMercadoPago toggle (default on): off creates the fee without a link so the student pays by transfer. - A fee paid some other way supersedes its combined link and expires the preference; renewing rebuilds the combined link or a single one. - Optional WhatsApp delivery (PAYMENT_LINK kind, new Kapso template); weekly reminders now go once per combined link. - Web: auto charge settings card, per-student toggle, combined link label in Cobros and "Pay all" in the student app, in the four locales. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
91 lines
3.9 KiB
TypeScript
91 lines
3.9 KiB
TypeScript
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<PrismaClient, 'autoChargeSettings' | 'paymentRun' | 'user'>;
|
|
planGuard?: Pick<PlanGuard, 'requireFeature'>;
|
|
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<Result<AutoChargeSettingsDto, ProblemDetails>> {
|
|
return ok(await this.load(ownerId));
|
|
}
|
|
|
|
async update(ownerId: string, input: UpdateAutoChargeSettings): Promise<Result<AutoChargeSettingsDto, ProblemDetails>> {
|
|
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<AutoChargeSettingsDto> {
|
|
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,
|
|
};
|
|
}
|
|
}
|