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:
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();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user