feat(payments): automatic monthly charges with combined links per payer
- 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>
This commit is contained in:
@@ -89,6 +89,7 @@ describe('GET /groups/:groupId/attendees/:attendeeId', () => {
|
||||
guardianPhone: '5598765432',
|
||||
guardianEmail: null,
|
||||
notes: null,
|
||||
payWithMercadoPago: true,
|
||||
notifyToken: 'token-1',
|
||||
createdAt: '2026-08-01T10:00:00.000Z',
|
||||
updatedAt: '2026-08-01T10:00:00.000Z',
|
||||
|
||||
@@ -25,6 +25,7 @@ const personSelect = {
|
||||
email: true,
|
||||
phone: true,
|
||||
notes: true,
|
||||
payWithMercadoPago: true,
|
||||
guardians: {
|
||||
take: 1,
|
||||
orderBy: { createdAt: 'asc' },
|
||||
@@ -82,6 +83,7 @@ describe('attendees routes', () => {
|
||||
guardianPhone: '1199990000',
|
||||
guardianEmail: null,
|
||||
notes: person.notes,
|
||||
payWithMercadoPago: true,
|
||||
createdAt: attendeeRow.createdAt.toISOString(),
|
||||
updatedAt: attendeeRow.updatedAt.toISOString(),
|
||||
// The query comes most recent first; the row shows them
|
||||
|
||||
290
apps/backend/test/payments-auto-charge.test.ts
Normal file
290
apps/backend/test/payments-auto-charge.test.ts
Normal file
@@ -0,0 +1,290 @@
|
||||
import { describe, expect, it, mock } from 'bun:test';
|
||||
import { GenerateMonthlyCharges } from '@/modules/payments/features/auto-charge/generate-monthly-charges';
|
||||
import { isAutoChargeDue, nextAutoChargeDate } from '@/modules/payments/lib/auto-charge-schedule';
|
||||
import { paymentLinkDetail } from '@/modules/whatsapp/jobs/send-payment-links';
|
||||
|
||||
const ownerId = 'owner-1';
|
||||
const BA = 'America/Argentina/Buenos_Aires';
|
||||
// 2026-12-05 12:00 in Buenos Aires (UTC-3).
|
||||
const NOW = new Date('2026-12-05T15:00:00.000Z');
|
||||
|
||||
type PersonRow = { id: string; payWithMercadoPago: boolean; guardian?: { id: string } };
|
||||
type AttendeeRow = { id: string; groupId: string; person: PersonRow };
|
||||
|
||||
const decimal = (value: number) => ({ toString: () => String(value) });
|
||||
|
||||
/** In-memory stand-in for the Prisma calls the generator makes. */
|
||||
function fakeDb(input: {
|
||||
groups: { id: string; name: string; price: number }[];
|
||||
attendees: AttendeeRow[];
|
||||
people: Record<string, string>;
|
||||
settings?: { dueInDays: number; sendWhatsapp: boolean } | null;
|
||||
runExists?: boolean;
|
||||
}) {
|
||||
const payments: Record<string, unknown>[] = [];
|
||||
const checkouts: Record<string, unknown>[] = [];
|
||||
const runs: Record<string, unknown>[] = [];
|
||||
let seq = 0;
|
||||
const groupName = (id: string) => input.groups.find((group) => group.id === id)?.name ?? '';
|
||||
const attendeeById = (id: string) => input.attendees.find((attendee) => attendee.id === id) as AttendeeRow;
|
||||
|
||||
const client = {
|
||||
payments,
|
||||
checkouts,
|
||||
runs,
|
||||
user: {
|
||||
findUnique: mock(async () => ({
|
||||
country: 'AR',
|
||||
autoCharge:
|
||||
input.settings === null
|
||||
? null
|
||||
: { enabled: true, chargeDay: 5, dueInDays: 10, sendWhatsapp: false, ...input.settings },
|
||||
})),
|
||||
},
|
||||
paymentRun: {
|
||||
create: mock(async ({ data }: { data: Record<string, unknown> }) => {
|
||||
if (input.runExists) throw Object.assign(new Error('unique'), { code: 'P2002' });
|
||||
const run = { id: `run-${++seq}`, ...data };
|
||||
runs.push(run);
|
||||
return run;
|
||||
}),
|
||||
update: mock(async ({ data }: { data: Record<string, unknown> }) => Object.assign(runs[0] ?? {}, data)),
|
||||
},
|
||||
group: {
|
||||
findMany: mock(async () => input.groups.map((group) => ({ id: group.id, price: decimal(group.price) }))),
|
||||
},
|
||||
attendee: {
|
||||
findMany: mock(async () =>
|
||||
input.attendees.map((attendee) => ({
|
||||
id: attendee.id,
|
||||
groupId: attendee.groupId,
|
||||
person: {
|
||||
id: attendee.person.id,
|
||||
payWithMercadoPago: attendee.person.payWithMercadoPago,
|
||||
guardians: attendee.person.guardian
|
||||
? [{ guardian: { id: attendee.person.guardian.id, fullName: '', phone: null, email: null } }]
|
||||
: [],
|
||||
},
|
||||
})),
|
||||
),
|
||||
},
|
||||
paymentCheckout: {
|
||||
create: mock(async ({ data }: { data: Record<string, unknown> }) => {
|
||||
const checkout = { id: `chk-${++seq}`, status: 'OPEN', ...data };
|
||||
checkouts.push(checkout);
|
||||
return { id: checkout.id };
|
||||
}),
|
||||
findUnique: mock(async ({ where }: { where: { id: string } }) => {
|
||||
const checkout = checkouts.find((row) => row.id === where.id);
|
||||
if (!checkout) return null;
|
||||
return {
|
||||
...checkout,
|
||||
payments: payments
|
||||
.filter((payment) => payment.checkoutId === checkout.id)
|
||||
.map((payment) => ({
|
||||
id: payment.id,
|
||||
amount: payment.amount,
|
||||
group: { name: groupName(payment.groupId as string) },
|
||||
attendee: { person: { fullName: input.people[attendeeById(payment.attendeeId as string).person.id] } },
|
||||
})),
|
||||
};
|
||||
}),
|
||||
update: mock(async ({ where, data }: { where: { id: string }; data: Record<string, unknown> }) =>
|
||||
Object.assign(checkouts.find((row) => row.id === where.id) ?? {}, data),
|
||||
),
|
||||
},
|
||||
payment: {
|
||||
create: mock(async ({ data }: { data: Record<string, unknown> }) => {
|
||||
const payment = { id: `pay-${++seq}`, ...data };
|
||||
payments.push(payment);
|
||||
return payment;
|
||||
}),
|
||||
updateMany: mock(async ({ where, data }: { where: { id: { in: string[] } }; data: Record<string, unknown> }) => {
|
||||
for (const payment of payments) if (where.id.in.includes(payment.id as string)) Object.assign(payment, data);
|
||||
return { count: where.id.in.length };
|
||||
}),
|
||||
},
|
||||
$transaction: mock(async (callback: (tx: unknown) => Promise<unknown>) => callback(client)),
|
||||
};
|
||||
return client;
|
||||
}
|
||||
|
||||
const okToken = mock(async () => ({ ok: true as const, value: { accountId: 'acc', accessToken: 'token', expiresAt: new Date() } }));
|
||||
const allowAll = { hasFeature: mock(async () => true) };
|
||||
|
||||
function generator(db: ReturnType<typeof fakeDb>, overrides: Record<string, unknown> = {}) {
|
||||
let preference = 0;
|
||||
const createPreference = mock(async () => ({ id: `pref-${++preference}`, initPoint: `https://mp.link/${preference}`, sandboxInitPoint: null }));
|
||||
const sendLinks = mock(async (_owner: string, ids: string[]) => ids.length);
|
||||
const instance = new GenerateMonthlyCharges({
|
||||
db: db as never,
|
||||
getToken: okToken as never,
|
||||
createPreference,
|
||||
planGuard: allowAll,
|
||||
sendLinks,
|
||||
webOrigin: 'https://app',
|
||||
apiOrigin: 'https://api',
|
||||
now: NOW,
|
||||
...overrides,
|
||||
});
|
||||
return { instance, createPreference, sendLinks };
|
||||
}
|
||||
|
||||
// A mother (guardian g-1) with two kids in two groups; she also takes Pilates herself.
|
||||
// An adult (p-4) alone. A kid (p-5) of another adult (g-2) who pays by transfer.
|
||||
const family = {
|
||||
groups: [
|
||||
{ id: 'swim', name: 'Natación', price: 20000 },
|
||||
{ id: 'yoga', name: 'Yoga', price: 15000 },
|
||||
{ id: 'pilates', name: 'Pilates', price: 10000 },
|
||||
],
|
||||
people: { 'p-1': 'Juan Gómez', 'p-2': 'Ana Gómez', 'g-1': 'Laura Gómez', 'p-4': 'Carlos Ruiz', 'p-5': 'Tomás Díaz' },
|
||||
attendees: [
|
||||
{ id: 'a-1', groupId: 'swim', person: { id: 'p-1', payWithMercadoPago: true, guardian: { id: 'g-1' } } },
|
||||
{ id: 'a-2', groupId: 'yoga', person: { id: 'p-2', payWithMercadoPago: true, guardian: { id: 'g-1' } } },
|
||||
{ id: 'a-3', groupId: 'pilates', person: { id: 'g-1', payWithMercadoPago: true } },
|
||||
{ id: 'a-4', groupId: 'yoga', person: { id: 'p-4', payWithMercadoPago: true } },
|
||||
{ id: 'a-5', groupId: 'swim', person: { id: 'p-5', payWithMercadoPago: false, guardian: { id: 'g-2' } } },
|
||||
],
|
||||
};
|
||||
|
||||
describe('automatic monthly charges', () => {
|
||||
it('bundles the fees of each payer into one Mercado Pago link with the total', async () => {
|
||||
const db = fakeDb(family);
|
||||
const { instance, createPreference } = generator(db);
|
||||
|
||||
const result = await instance.execute(ownerId);
|
||||
|
||||
expect(result).toEqual({ outcome: 'done', fees: 5, checkouts: 2, linked: 2, failed: 0, sent: 0 });
|
||||
expect(db.payments).toHaveLength(5);
|
||||
expect(db.payments.every((payment) => payment.periodKey === '2026-12')).toBe(true);
|
||||
// Due 10 days after the local charge date.
|
||||
expect(db.payments[0]?.dueDate).toEqual(new Date('2026-12-15T12:00:00.000Z'));
|
||||
|
||||
const [mother, adult] = db.checkouts;
|
||||
expect(mother).toMatchObject({ payerPersonId: 'g-1', amount: 45000, currency: 'ARS', checkoutUrl: 'https://mp.link/1' });
|
||||
expect(adult).toMatchObject({ payerPersonId: 'p-4', amount: 15000 });
|
||||
expect(createPreference).toHaveBeenCalledWith('token', {
|
||||
title: 'Natación · Juan Gómez',
|
||||
unitPrice: 45000,
|
||||
items: [
|
||||
{ title: 'Natación · Juan Gómez', unitPrice: 20000 },
|
||||
{ title: 'Yoga · Ana Gómez', unitPrice: 15000 },
|
||||
{ title: 'Pilates · Laura Gómez', unitPrice: 10000 },
|
||||
],
|
||||
currencyId: 'ARS',
|
||||
externalReference: `chk_${mother?.id}`,
|
||||
backUrl: 'https://app/student/payments',
|
||||
notificationUrl: `https://api/api/v1/payments/webhooks/mp/checkout/${mother?.id}?source_news=webhooks`,
|
||||
});
|
||||
// Each fee carries the shared link.
|
||||
const motherFees = db.payments.filter((payment) => payment.checkoutId === mother?.id);
|
||||
expect(motherFees.map((payment) => payment.checkoutUrl)).toEqual(Array(3).fill('https://mp.link/1'));
|
||||
});
|
||||
|
||||
it('creates the fee without a link for someone who pays by transfer', async () => {
|
||||
const db = fakeDb(family);
|
||||
await generator(db).instance.execute(ownerId);
|
||||
|
||||
const transfer = db.payments.find((payment) => payment.attendeeId === 'a-5');
|
||||
expect(transfer).toMatchObject({ status: 'PENDING', checkoutId: null, periodKey: '2026-12' });
|
||||
expect(transfer?.checkoutUrl).toBeUndefined();
|
||||
// The other adult has nobody paying with Mercado Pago: no checkout for them.
|
||||
expect(db.checkouts.some((checkout) => checkout.payerPersonId === 'g-2')).toBe(false);
|
||||
});
|
||||
|
||||
it('sends the generated links by WhatsApp only when the teacher turned it on', async () => {
|
||||
const off = fakeDb(family);
|
||||
const quiet = generator(off);
|
||||
await quiet.instance.execute(ownerId);
|
||||
expect(quiet.sendLinks).not.toHaveBeenCalled();
|
||||
|
||||
const on = fakeDb({ ...family, settings: { dueInDays: 10, sendWhatsapp: true } });
|
||||
const loud = generator(on);
|
||||
const result = await loud.instance.execute(ownerId);
|
||||
expect(loud.sendLinks).toHaveBeenCalledWith(ownerId, on.checkouts.map((checkout) => checkout.id));
|
||||
expect(result).toMatchObject({ outcome: 'done', sent: 2 });
|
||||
});
|
||||
|
||||
it('is a no-op the second time in the same month', async () => {
|
||||
const db = fakeDb({ ...family, runExists: true });
|
||||
const { instance, createPreference } = generator(db);
|
||||
|
||||
expect(await instance.execute(ownerId)).toEqual({ outcome: 'already_ran' });
|
||||
expect(db.payments).toHaveLength(0);
|
||||
expect(createPreference).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('skips the month when Mercado Pago is not linked', async () => {
|
||||
const db = fakeDb(family);
|
||||
const getToken = mock(async () => ({ ok: false as const, error: { status: 409, code: 'mp_not_connected' } }));
|
||||
const result = await generator(db, { getToken }).instance.execute(ownerId);
|
||||
|
||||
expect(result).toEqual({ outcome: 'skipped', reason: 'mp_not_connected' });
|
||||
expect(db.runs[0]).toMatchObject({ status: 'SKIPPED', skipReason: 'mp_not_connected' });
|
||||
expect(db.payments).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('skips the month without the Mercado Pago charges plan feature', async () => {
|
||||
const db = fakeDb(family);
|
||||
const result = await generator(db, { planGuard: { hasFeature: mock(async () => false) } }).instance.execute(ownerId);
|
||||
expect(result).toEqual({ outcome: 'skipped', reason: 'plan_feature_required' });
|
||||
});
|
||||
|
||||
it('keeps going when one link fails: its checkout stays without a link', async () => {
|
||||
const db = fakeDb(family);
|
||||
let calls = 0;
|
||||
const createPreference = mock(async () => {
|
||||
calls += 1;
|
||||
if (calls === 1) throw new (await import('@/modules/mp/lib/mp-oauth')).MpApiError(500, null);
|
||||
return { id: 'pref-2', initPoint: 'https://mp.link/2', sandboxInitPoint: null };
|
||||
});
|
||||
const result = await generator(db, { createPreference }).instance.execute(ownerId);
|
||||
|
||||
expect(result).toMatchObject({ outcome: 'done', checkouts: 2, linked: 1, failed: 1 });
|
||||
expect(db.checkouts[0]?.checkoutUrl).toBeUndefined();
|
||||
expect(db.checkouts[1]?.checkoutUrl).toBe('https://mp.link/2');
|
||||
});
|
||||
});
|
||||
|
||||
describe('auto charge schedule', () => {
|
||||
const settings = { chargeDay: 5, enabledAt: new Date('2026-11-01T12:00:00.000Z') };
|
||||
|
||||
it('is due from 9 a.m. local on the day, and for a few days after', () => {
|
||||
expect(isAutoChargeDue(settings, new Date('2026-12-05T11:00:00.000Z'), BA)).toBe(false); // 8 a.m.
|
||||
expect(isAutoChargeDue(settings, new Date('2026-12-05T12:00:00.000Z'), BA)).toBe(true); // 9 a.m.
|
||||
expect(isAutoChargeDue(settings, new Date('2026-12-08T02:00:00.000Z'), BA)).toBe(true); // 7th, 11 p.m.
|
||||
expect(isAutoChargeDue(settings, new Date('2026-12-09T12:00:00.000Z'), BA)).toBe(false);
|
||||
expect(isAutoChargeDue(settings, new Date('2026-12-04T12:00:00.000Z'), BA)).toBe(false);
|
||||
});
|
||||
|
||||
it('uses the teacher clock: 1 a.m. UTC on the 6th is still the 5th in Buenos Aires', () => {
|
||||
const lateEnabled = { chargeDay: 6, enabledAt: null };
|
||||
expect(isAutoChargeDue(lateEnabled, new Date('2026-12-06T01:00:00.000Z'), BA)).toBe(false);
|
||||
});
|
||||
|
||||
it('does not bill a month whose day had passed when it was turned on', () => {
|
||||
const late = { chargeDay: 5, enabledAt: new Date('2026-12-06T12:00:00.000Z') };
|
||||
expect(isAutoChargeDue(late, new Date('2026-12-07T12:00:00.000Z'), BA)).toBe(false);
|
||||
expect(nextAutoChargeDate(late, new Date('2026-12-07T12:00:00.000Z'), BA, false)).toBe('2027-01-05');
|
||||
});
|
||||
|
||||
it('tells the next run date', () => {
|
||||
expect(nextAutoChargeDate(settings, new Date('2026-12-02T12:00:00.000Z'), BA, false)).toBe('2026-12-05');
|
||||
expect(nextAutoChargeDate(settings, new Date('2026-12-06T12:00:00.000Z'), BA, true)).toBe('2027-01-05');
|
||||
expect(nextAutoChargeDate(settings, new Date('2026-12-20T12:00:00.000Z'), BA, false)).toBe('2027-01-05');
|
||||
});
|
||||
});
|
||||
|
||||
describe('payment link detail', () => {
|
||||
it('names each kid and leaves the payer own group bare', () => {
|
||||
expect(
|
||||
paymentLinkDetail('g-1', [
|
||||
{ groupName: 'Natación', personId: 'p-1', fullName: 'Juan Gómez' },
|
||||
{ groupName: 'Yoga', personId: 'p-2', fullName: 'Ana Gómez' },
|
||||
{ groupName: 'Pilates', personId: 'g-1', fullName: 'Laura Gómez' },
|
||||
]),
|
||||
).toBe('Natación (Juan), Yoga (Ana) y Pilates');
|
||||
expect(paymentLinkDetail('p-4', [{ groupName: 'Yoga', personId: 'p-4', fullName: 'Carlos Ruiz' }])).toBe('Yoga');
|
||||
});
|
||||
});
|
||||
239
apps/backend/test/payments-checkouts.test.ts
Normal file
239
apps/backend/test/payments-checkouts.test.ts
Normal file
@@ -0,0 +1,239 @@
|
||||
import { describe, expect, it, mock } from 'bun:test';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import { AutoChargeSettingsUseCase } from '@/modules/payments/features/auto-charge-settings/use-case';
|
||||
import { HandleMpCheckoutNotification } from '@/modules/payments/features/webhook/use-case';
|
||||
import { buildCheckoutLink, supersedeCheckoutsOf } from '@/modules/payments/lib/checkouts';
|
||||
import { SendPaymentLinks } from '@/modules/whatsapp/jobs/send-payment-links';
|
||||
import type { MessagingProvider } from '@/modules/whatsapp/providers/messaging-provider';
|
||||
|
||||
const ownerId = 'owner-1';
|
||||
|
||||
describe('combined links (checkouts)', () => {
|
||||
it('supersedes the open link of a fee paid some other way and drops the shared link', async () => {
|
||||
const tx = {
|
||||
paymentCheckout: {
|
||||
findMany: mock(async () => [{ id: 'chk-1', ownerId, mpPreferenceId: 'pref-1' }]),
|
||||
updateMany: mock(async () => ({ count: 1 })),
|
||||
},
|
||||
payment: { updateMany: mock(async () => ({ count: 3 })) },
|
||||
};
|
||||
|
||||
const expired = await supersedeCheckoutsOf(tx as never, ['pay-1']);
|
||||
|
||||
expect(expired).toEqual([{ ownerId, mpPreferenceId: 'pref-1' }]);
|
||||
expect(tx.paymentCheckout.updateMany).toHaveBeenCalledWith({
|
||||
where: { id: { in: ['chk-1'] }, status: 'OPEN' },
|
||||
data: { status: 'SUPERSEDED' },
|
||||
});
|
||||
expect(tx.payment.updateMany).toHaveBeenCalledWith({
|
||||
where: { checkoutId: { in: ['chk-1'] } },
|
||||
data: { checkoutUrl: null },
|
||||
});
|
||||
});
|
||||
|
||||
it('does nothing for fees outside a combined link', async () => {
|
||||
const tx = {
|
||||
paymentCheckout: { findMany: mock(async () => []), updateMany: mock() },
|
||||
payment: { updateMany: mock() },
|
||||
};
|
||||
expect(await supersedeCheckoutsOf(tx as never, ['pay-1'])).toEqual([]);
|
||||
expect(tx.paymentCheckout.updateMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rebuilds the link only from the fees still unpaid', async () => {
|
||||
const db = {
|
||||
paymentCheckout: {
|
||||
findUnique: mock(async () => ({
|
||||
id: 'chk-1',
|
||||
ownerId,
|
||||
currency: 'ARS',
|
||||
status: 'OPEN',
|
||||
payments: [
|
||||
{
|
||||
id: 'pay-2',
|
||||
amount: { toString: () => '15000' },
|
||||
group: { name: 'Yoga' },
|
||||
attendee: { person: { fullName: 'Ana' } },
|
||||
},
|
||||
],
|
||||
})),
|
||||
update: mock(async () => ({})),
|
||||
},
|
||||
payment: { updateMany: mock(async () => ({ count: 1 })) },
|
||||
};
|
||||
const createPreference = mock(async () => ({ id: 'pref-9', initPoint: 'https://mp.link/9', sandboxInitPoint: null }));
|
||||
|
||||
const outcome = await buildCheckoutLink(
|
||||
db as never,
|
||||
'chk-1',
|
||||
{ webOrigin: 'https://app', apiOrigin: 'https://api', accessToken: 'token' },
|
||||
{ createPreference },
|
||||
);
|
||||
|
||||
expect(outcome).toEqual({ ok: true, checkoutUrl: 'https://mp.link/9' });
|
||||
expect(db.paymentCheckout.update).toHaveBeenCalledWith({
|
||||
where: { id: 'chk-1' },
|
||||
data: { checkoutUrl: 'https://mp.link/9', mpPreferenceId: 'pref-9', amount: 15000 },
|
||||
});
|
||||
expect(db.payment.updateMany).toHaveBeenCalledWith({
|
||||
where: { id: { in: ['pay-2'] } },
|
||||
data: { checkoutUrl: 'https://mp.link/9' },
|
||||
});
|
||||
});
|
||||
|
||||
it('ignores a notification for an unknown or already paid link', async () => {
|
||||
const db = { paymentCheckout: { findFirst: mock(async () => null) }, $transaction: mock() };
|
||||
const result = await new HandleMpCheckoutNotification({ db: db as never }).execute('chk-x');
|
||||
expect(result).toEqual(ok({ outcome: 'ignored' }));
|
||||
});
|
||||
});
|
||||
|
||||
describe('auto charge settings', () => {
|
||||
function settingsDb(current: Record<string, unknown> | null = null) {
|
||||
return {
|
||||
autoChargeSettings: {
|
||||
findUnique: mock(async () => current),
|
||||
upsert: mock(async () => ({})),
|
||||
},
|
||||
paymentRun: { findFirst: mock(async () => null) },
|
||||
user: { findUnique: mock(async () => ({ country: 'AR' })) },
|
||||
};
|
||||
}
|
||||
|
||||
it('starts off with the defaults', async () => {
|
||||
const result = await new AutoChargeSettingsUseCase({ db: settingsDb() as never }).get(ownerId);
|
||||
expect(result).toEqual(
|
||||
ok({ enabled: false, chargeDay: 1, dueInDays: 10, sendWhatsapp: false, nextRunDate: null, lastRun: null }),
|
||||
);
|
||||
});
|
||||
|
||||
it('records when it is turned on', async () => {
|
||||
const db = settingsDb();
|
||||
const now = new Date('2026-12-02T12:00:00.000Z');
|
||||
await new AutoChargeSettingsUseCase({ db: db as never, planGuard: { requireFeature: mock(async () => ok(undefined)) }, now }).update(
|
||||
ownerId,
|
||||
{ enabled: true, chargeDay: 5 },
|
||||
);
|
||||
expect(db.autoChargeSettings.upsert).toHaveBeenCalledWith({
|
||||
where: { ownerId },
|
||||
create: { ownerId, enabled: true, chargeDay: 5, enabledAt: now },
|
||||
update: { enabled: true, chargeDay: 5, enabledAt: now },
|
||||
});
|
||||
});
|
||||
|
||||
it('asks the plan for WhatsApp automations before sending links', async () => {
|
||||
const problem = { type: 'x', title: 'Payment Required', status: 402, detail: 'x', code: 'plan_feature_required' };
|
||||
const requireFeature = mock(async (_owner: string, feature: string) =>
|
||||
feature === 'whatsappAutomations' ? { ok: false as const, error: problem } : ok(undefined),
|
||||
);
|
||||
const db = settingsDb();
|
||||
const result = await new AutoChargeSettingsUseCase({ db: db as never, planGuard: { requireFeature } }).update(ownerId, {
|
||||
sendWhatsapp: true,
|
||||
});
|
||||
expect(result).toEqual({ ok: false, error: problem });
|
||||
expect(db.autoChargeSettings.upsert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('can always be turned off', async () => {
|
||||
const requireFeature = mock();
|
||||
const db = settingsDb({ enabled: true, chargeDay: 5, dueInDays: 10, sendWhatsapp: true, enabledAt: null });
|
||||
await new AutoChargeSettingsUseCase({ db: db as never, planGuard: { requireFeature } }).update(ownerId, {
|
||||
enabled: false,
|
||||
sendWhatsapp: false,
|
||||
});
|
||||
expect(requireFeature).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('sending the monthly links by WhatsApp', () => {
|
||||
const account = { id: 'wa-1', ownerId, provider: 'OPENWA', status: 'ACTIVE', externalId: 's', displayPhoneNumber: null, providerData: null };
|
||||
|
||||
function provider(overrides: Partial<MessagingProvider> = {}): MessagingProvider {
|
||||
return {
|
||||
id: 'OPENWA',
|
||||
readiness: mock(async () => 'ready' as const),
|
||||
resolveRecipient: mock(async (_account, e164: string) => ({ ok: true as const, to: `${e164.slice(1)}@c.us` })),
|
||||
send: mock(async () => ({ ok: true as const, providerMessageId: 'wamid-1' })),
|
||||
...overrides,
|
||||
} as unknown as MessagingProvider;
|
||||
}
|
||||
|
||||
function linksDb() {
|
||||
return {
|
||||
whatsappAccount: { findFirst: mock(async () => account) },
|
||||
user: { findUnique: mock(async () => ({ country: 'AR' })) },
|
||||
paymentCheckout: {
|
||||
findMany: mock(async () => [
|
||||
{
|
||||
id: 'chk-1',
|
||||
amount: { toString: () => '35000' },
|
||||
currency: 'ARS',
|
||||
dueDate: new Date('2026-12-15T12:00:00.000Z'),
|
||||
checkoutUrl: 'https://mp.link/1',
|
||||
payer: { id: 'g-1', fullName: 'Laura Gómez', phone: '1123456789' },
|
||||
payments: [
|
||||
{ groupId: 'swim', attendeeId: 'a-1', periodKey: '2026-12', group: { name: 'Natación' }, attendee: { person: { id: 'p-1', fullName: 'Juan Gómez' } } },
|
||||
{ groupId: 'yoga', attendeeId: 'a-2', periodKey: '2026-12', group: { name: 'Yoga' }, attendee: { person: { id: 'p-2', fullName: 'Ana Gómez' } } },
|
||||
],
|
||||
},
|
||||
]),
|
||||
},
|
||||
outboundMessage: {
|
||||
create: mock(async () => ({ id: 'msg-1' })),
|
||||
update: mock(async () => ({})),
|
||||
delete: mock(),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
it('sends one message to the payer, keyed by the month, with what it pays', async () => {
|
||||
const db = linksDb();
|
||||
const fake = provider();
|
||||
const totals = await new SendPaymentLinks({
|
||||
db: db as never,
|
||||
provider: fake,
|
||||
planGuard: { hasFeature: mock(async () => true) },
|
||||
intervalMs: 0,
|
||||
}).execute(ownerId, ['chk-1']);
|
||||
|
||||
expect(totals).toEqual({ sent: 1, skipped: 0, failed: 0 });
|
||||
expect(db.outboundMessage.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({
|
||||
attendeeId: 'a-1',
|
||||
checkoutId: 'chk-1',
|
||||
kind: 'PAYMENT_LINK',
|
||||
periodKey: '2026-12',
|
||||
toPhone: '+5491123456789',
|
||||
}),
|
||||
select: { id: true },
|
||||
});
|
||||
const [, , message] = (fake.send as ReturnType<typeof mock>).mock.calls[0] ?? [];
|
||||
expect(message).toMatchObject({
|
||||
kind: 'PAYMENT_LINK',
|
||||
studentName: 'Laura Gómez',
|
||||
detail: 'Natación (Juan) y Yoga (Ana)',
|
||||
paymentLink: 'https://mp.link/1',
|
||||
});
|
||||
});
|
||||
|
||||
it('sends nothing while the template is not approved', async () => {
|
||||
const db = linksDb();
|
||||
const totals = await new SendPaymentLinks({
|
||||
db: db as never,
|
||||
provider: provider({ readiness: mock(async () => 'pending' as const) }),
|
||||
planGuard: { hasFeature: mock(async () => true) },
|
||||
}).execute(ownerId, ['chk-1']);
|
||||
expect(totals).toEqual({ sent: 0, skipped: 0, failed: 0 });
|
||||
expect(db.outboundMessage.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('sends nothing without WhatsApp automations in the plan', async () => {
|
||||
const db = linksDb();
|
||||
await new SendPaymentLinks({
|
||||
db: db as never,
|
||||
provider: provider(),
|
||||
planGuard: { hasFeature: mock(async () => false) },
|
||||
}).execute(ownerId, ['chk-1']);
|
||||
expect(db.outboundMessage.create).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,19 @@
|
||||
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
|
||||
|
||||
const tx = {
|
||||
paymentCheckout: { update: mock() },
|
||||
payment: { updateMany: mock() },
|
||||
};
|
||||
|
||||
const db = {
|
||||
payment: {
|
||||
findMany: mock(),
|
||||
update: mock(),
|
||||
},
|
||||
paymentCheckout: {
|
||||
findMany: mock(async () => [] as unknown[]),
|
||||
},
|
||||
$transaction: mock(async (callback: (client: typeof tx) => Promise<unknown>) => callback(tx)),
|
||||
};
|
||||
|
||||
mock.module('@/lib/prisma', () => ({
|
||||
@@ -121,9 +130,54 @@ describe('reconcile payments', () => {
|
||||
where: {
|
||||
status: 'PENDING',
|
||||
checkoutUrl: { not: null },
|
||||
checkoutId: null,
|
||||
createdAt: { lt: new Date('2026-10-01T11:55:00.000Z') },
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('marks every unpaid fee of an approved combined link as PAID', async () => {
|
||||
prisma.payment.findMany.mockResolvedValue([]);
|
||||
db.paymentCheckout.findMany.mockResolvedValueOnce([{ id: 'chk-1', ownerId }]);
|
||||
const getToken = mock(async () => okAccount());
|
||||
const search = mock(async () => ({
|
||||
id: '777',
|
||||
status: 'approved',
|
||||
externalReference: 'chk_chk-1',
|
||||
liveMode: true,
|
||||
dateApproved: '2026-10-01T12:30:00.000Z',
|
||||
}));
|
||||
|
||||
const result = await new ReconcilePayments({ getToken, search }).execute();
|
||||
|
||||
expect(result).toEqual({ paid: 1, skipped: 0, failed: 0 });
|
||||
expect(search).toHaveBeenCalledWith('token-1', 'chk_chk-1');
|
||||
const paidAt = new Date('2026-10-01T12:30:00.000Z');
|
||||
expect(tx.paymentCheckout.update).toHaveBeenCalledWith({
|
||||
where: { id: 'chk-1' },
|
||||
data: { status: 'PAID', mpPaymentId: '777', paidAt },
|
||||
});
|
||||
expect(tx.payment.updateMany).toHaveBeenCalledWith({
|
||||
where: { checkoutId: 'chk-1', status: { in: ['PENDING', 'OVERDUE'] } },
|
||||
data: { status: 'PAID', mpPaymentId: '777', paidAt },
|
||||
});
|
||||
});
|
||||
|
||||
it('ignores a payment of a combined link whose reference is not the checkout', async () => {
|
||||
prisma.payment.findMany.mockResolvedValue([]);
|
||||
db.paymentCheckout.findMany.mockResolvedValueOnce([{ id: 'chk-1', ownerId }]);
|
||||
const search = mock(async () => ({
|
||||
id: '777',
|
||||
status: 'approved',
|
||||
externalReference: 'chk-1',
|
||||
liveMode: true,
|
||||
dateApproved: null,
|
||||
}));
|
||||
|
||||
const result = await new ReconcilePayments({ getToken: mock(async () => okAccount()), search }).execute();
|
||||
|
||||
expect(result).toEqual({ paid: 0, skipped: 0, failed: 0 });
|
||||
expect(tx.payment.updateMany).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -106,10 +106,11 @@ describe('renew payment link', () => {
|
||||
});
|
||||
expect(prisma.payment.update).toHaveBeenCalledWith({
|
||||
where: { id: 'pay-1' },
|
||||
data: { checkoutUrl: 'https://mp.link/pay-1', mpPreferenceId: 'pref-new' },
|
||||
data: { checkoutUrl: 'https://mp.link/pay-1', mpPreferenceId: 'pref-new', checkoutId: null },
|
||||
include: {
|
||||
attendee: { select: { person: { select: { fullName: true } } } },
|
||||
group: { select: { name: true, price: true } },
|
||||
checkout: { select: { _count: { select: { payments: true } } } },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -75,6 +75,9 @@ describe('payments routes', () => {
|
||||
status: 'PENDING',
|
||||
description: 'Mensualidad de Septiembre',
|
||||
checkoutUrl: payment.checkoutUrl,
|
||||
checkoutId: null,
|
||||
checkoutItemCount: null,
|
||||
periodKey: null,
|
||||
dueDate: payment.dueDate.toISOString(),
|
||||
paidAt: null,
|
||||
createdAt: payment.createdAt.toISOString(),
|
||||
@@ -94,6 +97,7 @@ describe('payments routes', () => {
|
||||
include: {
|
||||
group: { select: { name: true, price: true } },
|
||||
attendee: { select: { person: { select: { fullName: true } } } },
|
||||
checkout: { select: { _count: { select: { payments: true } } } },
|
||||
},
|
||||
skip: 0,
|
||||
take: 10,
|
||||
|
||||
@@ -35,6 +35,9 @@ describe('session auth', () => {
|
||||
expect(isPublicApiRequest('GET', '/api/v1/health')).toBe(true);
|
||||
expect(isPublicApiRequest('POST', '/api/v1/auth/sign-in/email')).toBe(true);
|
||||
expect(isPublicApiRequest('GET', '/api/v1/groups')).toBe(false);
|
||||
expect(isPublicApiRequest('POST', '/api/v1/payments/webhooks/mp/pay-1')).toBe(true);
|
||||
expect(isPublicApiRequest('POST', '/api/v1/payments/webhooks/mp/checkout/chk-1')).toBe(true);
|
||||
expect(isPublicApiRequest('POST', '/api/v1/payments/webhooks/mp/checkout/chk-1/extra')).toBe(false);
|
||||
expect(isPublicApiRequest('GET', '/api/v1/attendees')).toBe(false);
|
||||
});
|
||||
|
||||
|
||||
@@ -197,7 +197,7 @@ describe('status', () => {
|
||||
displayPhoneNumber: null,
|
||||
connectedAt: null,
|
||||
qrCode: null,
|
||||
readiness: { PAYMENT_REMINDER: 'blocked', REENGAGEMENT: 'blocked' },
|
||||
readiness: { PAYMENT_REMINDER: 'blocked', REENGAGEMENT: 'blocked', PAYMENT_LINK: 'blocked' },
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -279,6 +279,7 @@ describe('status', () => {
|
||||
expect(result.ok && result.value.readiness).toEqual({
|
||||
PAYMENT_REMINDER: 'ready',
|
||||
REENGAGEMENT: 'pending',
|
||||
PAYMENT_LINK: 'ready',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -93,6 +93,36 @@ function reengagement(provider: MessagingProvider) {
|
||||
}
|
||||
|
||||
describe('payment reminders', () => {
|
||||
it('reminds a combined link once, to whoever pays it, with the total', async () => {
|
||||
const checkout = {
|
||||
id: 'chk-1',
|
||||
status: 'OPEN',
|
||||
amount: { toString: () => '40000' },
|
||||
payer: { id: 'g-1', fullName: 'Laura Gómez', phone: '11 2345-6789' },
|
||||
payments: [
|
||||
{ group: { name: 'Yoga Martes' }, attendee: { person: { id: 'p-1', fullName: 'Juan Gómez' } } },
|
||||
{ group: { name: 'Yoga Martes' }, attendee: { person: { id: 'p-2', fullName: 'Ana Gómez' } } },
|
||||
],
|
||||
};
|
||||
db.payment.findMany.mockResolvedValue([
|
||||
payment('pay-1', { id: 'att-1', fullName: 'Juan Gómez' }, { checkout, checkoutUrl: 'https://mpago.la/chk' }),
|
||||
payment('pay-2', { id: 'att-2', fullName: 'Ana Gómez' }, { checkout, checkoutUrl: 'https://mpago.la/chk' }),
|
||||
]);
|
||||
const provider = fakeProvider();
|
||||
|
||||
const totals = await reminders(provider).execute();
|
||||
|
||||
expect(totals).toEqual({ sent: 1, skipped: 0, failed: 0 });
|
||||
const [, , message] = (provider.send as ReturnType<typeof mock>).mock.calls[0] ?? [];
|
||||
expect(message).toMatchObject({
|
||||
kind: 'PAYMENT_REMINDER',
|
||||
studentName: 'Laura Gómez',
|
||||
groupName: 'Yoga Martes (Juan) y Yoga Martes (Ana)',
|
||||
paymentLink: 'https://mpago.la/chk',
|
||||
});
|
||||
expect((message as { amount: string }).amount).toContain('40.000');
|
||||
});
|
||||
|
||||
it('only looks at groups with the automation on and an active account of this provider', async () => {
|
||||
await reminders(fakeProvider()).execute();
|
||||
|
||||
@@ -135,6 +165,7 @@ describe('payment reminders', () => {
|
||||
groupId: 'group-1',
|
||||
attendeeId: 'att-1',
|
||||
paymentId: 'pay-1',
|
||||
checkoutId: null,
|
||||
kind: 'PAYMENT_REMINDER',
|
||||
provider: 'OPENWA',
|
||||
periodKey: '2026-W43',
|
||||
|
||||
@@ -490,12 +490,13 @@ describe('Kapso provider', () => {
|
||||
expect(templates.map((call) => (call.body as { name: string; category: string }))).toEqual([
|
||||
expect.objectContaining({ name: 'gruperly_payment_reminder', category: 'UTILITY' }),
|
||||
expect.objectContaining({ name: 'gruperly_reengagement', category: 'MARKETING' }),
|
||||
expect.objectContaining({ name: 'gruperly_payment_link', category: 'UTILITY' }),
|
||||
]);
|
||||
expect(db.whatsappAccount.update).toHaveBeenCalledWith({
|
||||
where: { id: 'wa-1' },
|
||||
data: { providerData: { customerId: 'cust-1', businessAccountId: 'waba-1', webhookId: 'wh-1' } },
|
||||
});
|
||||
expect(db.whatsappTemplate.create).toHaveBeenCalledTimes(2);
|
||||
expect(db.whatsappTemplate.create).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it('is ready only once the template is approved', async () => {
|
||||
|
||||
Reference in New Issue
Block a user