feat: add country selection during onboarding and implement payment management features
- Introduced CountryStep component for selecting the country during onboarding, affecting payment currency. - Updated FirstGroupStep to include country information. - Enhanced PaymentsProvider to manage payment states and renewals. - Created PaymentRow component for displaying individual payment details. - Implemented PaymentsView for listing and filtering payments by group and status. - Added API endpoints for fetching and creating payments, including batch processing. - Defined payment schemas for validation and data handling. - Updated GroupHeader and GroupDetailView to include charging functionality for group members.
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
-- Country of the professor (onboarding) + Mercado Pago Checkout Pro payment links.
|
||||
|
||||
-- AlterTable (users)
|
||||
ALTER TABLE "users" ADD COLUMN "country_code" TEXT;
|
||||
|
||||
-- AlterTable (payments)
|
||||
ALTER TABLE "payments" ADD COLUMN "description" TEXT;
|
||||
ALTER TABLE "payments" ADD COLUMN "checkout_url" TEXT;
|
||||
ALTER TABLE "payments" ADD COLUMN "mp_preference_id" TEXT;
|
||||
ALTER TABLE "payments" ADD COLUMN "mp_payment_id" TEXT;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "payments_mp_preference_id_key" ON "payments"("mp_preference_id");
|
||||
@@ -7,6 +7,7 @@ model User {
|
||||
emailVerified Boolean @default(false) @map("email_verified")
|
||||
image String?
|
||||
onboardingCompleted Boolean @default(false) @map("onboarding_completed")
|
||||
country String? @map("country_code")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
|
||||
@@ -95,9 +95,13 @@ model Payment {
|
||||
groupId String @map("group_id")
|
||||
attendeeId String @map("attendee_id")
|
||||
amount Decimal @db.Decimal(10, 2)
|
||||
currency String @default("MXN")
|
||||
currency String @default("ARS")
|
||||
status PaymentStatus @default(PENDING) // PENDING, PAID, OVERDUE, CANCELLED
|
||||
dueDate DateTime @map("due_date")
|
||||
description String? @map("description")
|
||||
checkoutUrl String? @map("checkout_url")
|
||||
mpPreferenceId String? @unique(map: "payments_mp_preference_id_key") @map("mp_preference_id")
|
||||
mpPaymentId String? @map("mp_payment_id")
|
||||
paidAt DateTime? @map("paid_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
@@ -142,4 +142,18 @@ export function attendeeHasPaymentsProblem(): ProblemDetails {
|
||||
detail: 'Este miembro tiene cobros asociados. Gestiona o cancela sus cobros antes de quitarlo del grupo.',
|
||||
code: 'attendee_has_payments',
|
||||
});
|
||||
}
|
||||
|
||||
export function groupWithoutPriceProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'Definí el precio del grupo antes de generar los cobros.',
|
||||
code: 'group_without_price',
|
||||
});
|
||||
}
|
||||
|
||||
export function noAttendeesToBillProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'No hay miembros activos con un cobro pendiente para este grupo.',
|
||||
code: 'no_attendees_to_bill',
|
||||
});
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import removeAttendeeRoute from '../attendees/features/remove/route';
|
||||
import updateAttendeeRoute from '../attendees/features/update/route';
|
||||
import groupPreRegistrationRoutes from '../group-preregistrations/routes';
|
||||
import groupWaitlistRoutes from '../group-waitlist/routes';
|
||||
import createPaymentsBatchRoute from '../payments/features/create-batch/route';
|
||||
import createGroupRoute from './features/create/route';
|
||||
import getAllRoute from './features/get-all/route';
|
||||
import getByIdRoute from './features/get-by-id/route';
|
||||
@@ -24,6 +25,7 @@ routes.route('/', listAttendeesRoute);
|
||||
routes.route('/', createAttendeeRoute);
|
||||
routes.route('/', bulkCreateAttendeesRoute);
|
||||
routes.route('/', getByIdRoute);
|
||||
routes.route('/', createPaymentsBatchRoute);
|
||||
routes.route('/', addToGroupWaitlistRoute);
|
||||
routes.route('/', groupWaitlistRoutes);
|
||||
routes.route('/', groupPreRegistrationRoutes);
|
||||
|
||||
@@ -6,6 +6,14 @@ export {
|
||||
openToken,
|
||||
sealToken,
|
||||
} from './crypto';
|
||||
export {
|
||||
createCheckoutPreference,
|
||||
MP_API_URL,
|
||||
type MpCreatePreferenceInput,
|
||||
type MpPreference,
|
||||
type MpSearchedPayment,
|
||||
searchMpPaymentByExternalReference,
|
||||
} from './mp-http';
|
||||
export {
|
||||
buildAuthorizationUrl,
|
||||
exchangeAuthorizationCode,
|
||||
|
||||
138
apps/backend/src/modules/mp/lib/mp-http.ts
Normal file
138
apps/backend/src/modules/mp/lib/mp-http.ts
Normal file
@@ -0,0 +1,138 @@
|
||||
import { logger } from '@/logger';
|
||||
import { MpApiError } from './mp-oauth';
|
||||
|
||||
export const MP_API_URL = 'https://api.mercadopago.com';
|
||||
|
||||
// Mercado Pago runs the seller's money straight into the professor's own
|
||||
// account: no platform_id of ours and no fee split.
|
||||
|
||||
export type MpCreatePreferenceInput = {
|
||||
title: string;
|
||||
unitPrice: number;
|
||||
currencyId: string;
|
||||
externalReference: string;
|
||||
/** Where the buyer lands after paying (pending/success/failure). */
|
||||
backUrl: string;
|
||||
};
|
||||
|
||||
export type MpPreference = {
|
||||
id: string;
|
||||
initPoint: string;
|
||||
sandboxInitPoint: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a Checkout Pro preference in the seller's account. This is a payment
|
||||
* *link*: nothing is charged, and creating it again after a lost connection is
|
||||
* safe (same external_reference would be a new link for the same payment).
|
||||
*/
|
||||
export async function createCheckoutPreference(
|
||||
accessToken: string,
|
||||
input: MpCreatePreferenceInput,
|
||||
): Promise<MpPreference> {
|
||||
let response: Response;
|
||||
|
||||
try {
|
||||
response = await fetch(`${MP_API_URL}/checkout/preferences`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
items: [
|
||||
{
|
||||
title: input.title,
|
||||
currency_id: input.currencyId,
|
||||
quantity: 1,
|
||||
unit_price: input.unitPrice,
|
||||
},
|
||||
],
|
||||
external_reference: input.externalReference,
|
||||
auto_return: 'approved',
|
||||
back_urls: {
|
||||
success: input.backUrl,
|
||||
pending: input.backUrl,
|
||||
failure: input.backUrl,
|
||||
},
|
||||
}),
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error({ err: error }, 'Mercado Pago preferences endpoint unreachable');
|
||||
throw new MpApiError(0, null);
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const payload = (await response.json().catch(() => null)) as Record<string, unknown> | null;
|
||||
const reason = typeof payload?.error === 'string' ? payload.error : null;
|
||||
logger.error(
|
||||
{ status: response.status, reason },
|
||||
'Mercado Pago preferences request failed',
|
||||
);
|
||||
throw new MpApiError(response.status, reason);
|
||||
}
|
||||
|
||||
const payload = (await response.json()) as Record<string, unknown>;
|
||||
return {
|
||||
id: String(payload.id),
|
||||
initPoint: String(payload.init_point),
|
||||
sandboxInitPoint: payload.sandbox_init_point == null ? null : String(payload.sandbox_init_point),
|
||||
};
|
||||
}
|
||||
|
||||
export type MpSearchedPayment = {
|
||||
id: string;
|
||||
status: string;
|
||||
externalReference: string;
|
||||
liveMode: boolean;
|
||||
dateApproved: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Finds a payment created for one of our payment rows.
|
||||
*
|
||||
* This is the reconciliation path: instead of trusting a webhook, the job asks
|
||||
* the seller's account for payments whose `external_reference` is our payment
|
||||
* id. Only an approved payment whose reference matches ours is a PAID row.
|
||||
*/
|
||||
export async function searchMpPaymentByExternalReference(
|
||||
accessToken: string,
|
||||
externalReference: string,
|
||||
): Promise<MpSearchedPayment | null> {
|
||||
const url = new URL(`${MP_API_URL}/v1/payments/search`);
|
||||
url.searchParams.set('external_reference', externalReference);
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(url, {
|
||||
headers: { Accept: 'application/json', Authorization: `Bearer ${accessToken}` },
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error({ err: error }, 'Mercado Pago payments search unreachable');
|
||||
throw new MpApiError(0, null);
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
logger.error({ status: response.status }, 'Mercado Pago payments search failed');
|
||||
throw new MpApiError(response.status, null);
|
||||
}
|
||||
|
||||
const payload = (await response.json()) as { results?: Record<string, unknown>[] } | null;
|
||||
const results = payload?.results ?? [];
|
||||
const match = results.find(
|
||||
(payment) => payment.external_reference === externalReference,
|
||||
);
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
id: String(match.id),
|
||||
status: String(match.status),
|
||||
externalReference: String(match.external_reference),
|
||||
liveMode: Boolean(match.live_mode),
|
||||
dateApproved:
|
||||
typeof match.date_approved === 'string' ? match.date_approved : null,
|
||||
};
|
||||
}
|
||||
@@ -60,7 +60,7 @@ export class CreateFirstGroup {
|
||||
|
||||
await tx.user.update({
|
||||
where: { id: userId },
|
||||
data: { onboardingCompleted: true },
|
||||
data: { onboardingCompleted: true, country: data.country },
|
||||
});
|
||||
|
||||
return ok(created);
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { CreatePaymentsBatch } from '@gruperly/shared';
|
||||
import { CreatePaymentsBatchSchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { CreatePaymentBatch } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.post(
|
||||
'/:groupId/payments/batch',
|
||||
validate.json(CreatePaymentsBatchSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) {
|
||||
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
}
|
||||
|
||||
const groupId = c.req.param('groupId');
|
||||
const body = c.req.valid('json') as CreatePaymentsBatch;
|
||||
const result = await new CreatePaymentBatch().execute(groupId, user.id, body);
|
||||
|
||||
return resultJson(c, result, { status: 201 });
|
||||
},
|
||||
);
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,159 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type {
|
||||
CountryCode,
|
||||
CreatePaymentsBatch,
|
||||
CreatePaymentsBatchResult,
|
||||
PaymentBatchItem,
|
||||
ProblemDetails,
|
||||
Result,
|
||||
} from '@gruperly/shared';
|
||||
import { currencyForCountry, err, ok } from '@gruperly/shared';
|
||||
import {
|
||||
groupWithoutPriceProblem,
|
||||
noAttendeesToBillProblem,
|
||||
noGroupAccessProblem,
|
||||
notFoundResourceProblem,
|
||||
} from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { logger } from '@/logger';
|
||||
import { getMpAccessToken } from '@/modules/mp';
|
||||
import { createCheckoutPreference, getWebOrigin, MpApiError } from '@/modules/mp/lib';
|
||||
|
||||
type BatchDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'payment' | 'user'>;
|
||||
createPreference?: typeof createCheckoutPreference;
|
||||
getToken?: typeof getMpAccessToken;
|
||||
webOrigin?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates one Checkout Pro payment link per active attendee of a group.
|
||||
*
|
||||
* The rows are created first (they are the single source of truth); a preference
|
||||
* that fails leaves its row PENDING without a link, and the professor retries
|
||||
* that one with `POST /payments/:id/renew` from the Cobros screen. A duplicate
|
||||
* batch call for the same period is up to the professor: each run creates new
|
||||
* links and creating a link never charges anyone.
|
||||
*/
|
||||
export class CreatePaymentBatch {
|
||||
constructor(private readonly deps: BatchDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
groupId: string,
|
||||
userId: string,
|
||||
input: CreatePaymentsBatch,
|
||||
): Promise<Result<CreatePaymentsBatchResult, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
|
||||
const group = await db.group.findUnique({
|
||||
where: { id: groupId },
|
||||
include: { members: { where: { userId } } },
|
||||
});
|
||||
|
||||
if (!group) {
|
||||
return err(notFoundResourceProblem('Group', groupId));
|
||||
}
|
||||
|
||||
const isOwner = group.createdById === userId;
|
||||
const isMember = group.members.length > 0;
|
||||
if (!isOwner && !isMember) {
|
||||
return err(noGroupAccessProblem());
|
||||
}
|
||||
|
||||
if (group.price == null) {
|
||||
return err(groupWithoutPriceProblem());
|
||||
}
|
||||
|
||||
const attendees = await db.attendee.findMany({
|
||||
where: {
|
||||
groupId,
|
||||
status: 'ACTIVE',
|
||||
...(input.attendeeIds ? { id: { in: input.attendeeIds } } : {}),
|
||||
},
|
||||
});
|
||||
if (attendees.length === 0) {
|
||||
return err(noAttendeesToBillProblem());
|
||||
}
|
||||
|
||||
const owner = await db.user.findUnique({ where: { id: group.createdById } });
|
||||
const currency = currencyForCountry((owner?.country as CountryCode | null) ?? null);
|
||||
const unitPrice = Number(group.price.toString());
|
||||
|
||||
const getToken = this.deps.getToken ?? getMpAccessToken;
|
||||
const token = await getToken(group.createdById);
|
||||
if (!token.ok) {
|
||||
return token;
|
||||
}
|
||||
|
||||
const backUrl = `${this.deps.webOrigin ?? getWebOrigin()}/payments`;
|
||||
const dueDate = new Date(input.dueDate);
|
||||
const title = input.description?.trim() || group.name;
|
||||
const createPreference = this.deps.createPreference ?? createCheckoutPreference;
|
||||
|
||||
const items: PaymentBatchItem[] = [];
|
||||
let failed = 0;
|
||||
|
||||
for (const attendee of attendees) {
|
||||
const payment = await db.payment.create({
|
||||
data: {
|
||||
groupId,
|
||||
attendeeId: attendee.id,
|
||||
amount: group.price,
|
||||
currency,
|
||||
dueDate,
|
||||
description: input.description?.trim() || null,
|
||||
status: 'PENDING',
|
||||
},
|
||||
});
|
||||
|
||||
let link: { initPoint: string; id: string } | null = null;
|
||||
let reason: string | null = null;
|
||||
|
||||
try {
|
||||
const preference = await createPreference(token.value.accessToken, {
|
||||
title,
|
||||
unitPrice,
|
||||
currencyId: currency,
|
||||
externalReference: payment.id,
|
||||
backUrl,
|
||||
});
|
||||
link = preference;
|
||||
} catch (error) {
|
||||
failed += 1;
|
||||
if (error instanceof MpApiError) {
|
||||
reason = 'mp_provider_error';
|
||||
} else {
|
||||
// Never swallow a real bug: log it, but keep the rest of the batch going.
|
||||
reason = 'unknown_error';
|
||||
logger.error({ err: error }, 'Unexpected Mercado Pago preference failure');
|
||||
}
|
||||
}
|
||||
|
||||
if (link) {
|
||||
await db.payment.update({
|
||||
where: { id: payment.id },
|
||||
data: { checkoutUrl: link.initPoint, mpPreferenceId: link.id },
|
||||
});
|
||||
}
|
||||
|
||||
items.push({
|
||||
paymentId: payment.id,
|
||||
attendeeId: attendee.id,
|
||||
attendeeName: attendee.fullName,
|
||||
amount: unitPrice,
|
||||
currency,
|
||||
checkoutUrl: link?.initPoint ?? null,
|
||||
outcome: link ? 'LINKED' : 'FAILED',
|
||||
reason,
|
||||
});
|
||||
}
|
||||
|
||||
return ok({
|
||||
groupId,
|
||||
total: attendees.length,
|
||||
linked: attendees.length - failed,
|
||||
failed,
|
||||
items,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,20 @@
|
||||
import type { PaymentQuery } from '@gruperly/shared';
|
||||
import { PaymentQuerySchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { resultJson } from '@/http/problem-details';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { ListPayments } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.get('/', validate.query(PaymentQuerySchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) {
|
||||
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
}
|
||||
|
||||
const query = c.req.valid('query') as PaymentQuery;
|
||||
const useCase = new ListPayments();
|
||||
const result = await useCase.execute(query);
|
||||
const result = await new ListPayments().execute(query, user.id);
|
||||
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
@@ -1,57 +1,52 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { PaymentDto, PaymentList, PaymentQuery, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import type { PaymentList, PaymentQuery, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { buildGroupWhereForUser } from '@/modules/groups/lib';
|
||||
import { type PaymentRecord, toPaymentDto } from '../../lib';
|
||||
|
||||
type ListPaymentsDeps = {
|
||||
db?: Pick<PrismaClient, 'payment'>;
|
||||
db?: Pick<PrismaClient, 'payment' | 'group'>;
|
||||
};
|
||||
|
||||
type PaymentRecord = {
|
||||
id: string;
|
||||
groupId: string;
|
||||
attendeeId: string;
|
||||
amount: { toString(): string };
|
||||
currency: string;
|
||||
status: PaymentDto['status'];
|
||||
dueDate: Date;
|
||||
paidAt: Date | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
};
|
||||
|
||||
function toPaymentDto(record: PaymentRecord): PaymentDto {
|
||||
return {
|
||||
id: record.id,
|
||||
groupId: record.groupId,
|
||||
attendeeId: record.attendeeId,
|
||||
amount: Number(record.amount.toString()),
|
||||
currency: record.currency,
|
||||
status: record.status,
|
||||
dueDate: record.dueDate.toISOString(),
|
||||
paidAt: record.paidAt ? record.paidAt.toISOString() : null,
|
||||
createdAt: record.createdAt.toISOString(),
|
||||
updatedAt: record.updatedAt.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
export class ListPayments {
|
||||
constructor(private readonly deps: ListPaymentsDeps = {}) {}
|
||||
|
||||
async execute(query: PaymentQuery): Promise<Result<PaymentList, ProblemDetails>> {
|
||||
async execute(
|
||||
query: PaymentQuery,
|
||||
userId: string,
|
||||
): Promise<Result<PaymentList, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
|
||||
// Only the professor's own groups (owner or member) are visible.
|
||||
const accessibleGroups = await db.group.findMany({
|
||||
where: buildGroupWhereForUser(userId),
|
||||
select: { id: true },
|
||||
});
|
||||
const groupIds = accessibleGroups.map((group) => group.id);
|
||||
const where = {
|
||||
groupId: { in: groupIds },
|
||||
...(query.groupId ? { groupId: query.groupId } : {}),
|
||||
...(query.status ? { status: query.status } : {}),
|
||||
};
|
||||
|
||||
const [records, total] = await Promise.all([
|
||||
db.payment.findMany({
|
||||
where,
|
||||
include: {
|
||||
group: { select: { name: true, price: true } },
|
||||
attendee: { select: { fullName: true } },
|
||||
},
|
||||
skip: getPaginationOffset(query),
|
||||
take: query.pageSize,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
}),
|
||||
db.payment.count(),
|
||||
db.payment.count({ where }),
|
||||
]);
|
||||
|
||||
return ok({
|
||||
data: records.map(toPaymentDto),
|
||||
data: records.map((record) => toPaymentDto(record as unknown as PaymentRecord)),
|
||||
pagination: getPaginationMetadata(query, total),
|
||||
});
|
||||
}
|
||||
|
||||
19
apps/backend/src/modules/payments/features/renew/route.ts
Normal file
19
apps/backend/src/modules/payments/features/renew/route.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { RenewPaymentLink } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.post('/:id/renew', async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) {
|
||||
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
}
|
||||
|
||||
const paymentId = c.req.param('id');
|
||||
const result = await new RenewPaymentLink().execute(paymentId, user.id);
|
||||
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
106
apps/backend/src/modules/payments/features/renew/use-case.ts
Normal file
106
apps/backend/src/modules/payments/features/renew/use-case.ts
Normal file
@@ -0,0 +1,106 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { CountryCode, PaymentDto, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { currencyForCountry, err, ok } from '@gruperly/shared';
|
||||
import {
|
||||
groupWithoutPriceProblem,
|
||||
mpProviderErrorProblem,
|
||||
noGroupAccessProblem,
|
||||
notFoundResourceProblem,
|
||||
} from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { logger } from '@/logger';
|
||||
import { getMpAccessToken } from '@/modules/mp';
|
||||
import { createCheckoutPreference, getWebOrigin } from '@/modules/mp/lib';
|
||||
import { type PaymentRecord, toPaymentDto } from '../../lib';
|
||||
|
||||
type RenewDeps = {
|
||||
db?: Pick<PrismaClient, 'payment' | 'user'>;
|
||||
createPreference?: typeof createCheckoutPreference;
|
||||
getToken?: typeof getMpAccessToken;
|
||||
webOrigin?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Re-creates the Checkout Pro link of a payment that lost it (a failed batch
|
||||
* item). Idempotent: a payment that already has a link keeps it.
|
||||
*/
|
||||
export class RenewPaymentLink {
|
||||
constructor(private readonly deps: RenewDeps = {}) {}
|
||||
|
||||
async execute(paymentId: string, userId: string): Promise<Result<PaymentDto, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
|
||||
const payment = await db.payment.findUnique({
|
||||
where: { id: paymentId },
|
||||
include: {
|
||||
attendee: { select: { fullName: true } },
|
||||
group: {
|
||||
select: {
|
||||
name: true,
|
||||
price: true,
|
||||
createdById: true,
|
||||
members: { where: { userId } },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!payment) {
|
||||
return err(notFoundResourceProblem('Payment', paymentId));
|
||||
}
|
||||
|
||||
const isOwner = payment.group.createdById === userId;
|
||||
const isMember = payment.group.members.length > 0;
|
||||
if (!isOwner && !isMember) {
|
||||
return err(noGroupAccessProblem());
|
||||
}
|
||||
|
||||
if (payment.checkoutUrl) {
|
||||
return ok(toPaymentDto(payment as unknown as PaymentRecord));
|
||||
}
|
||||
|
||||
if (payment.group.price == null) {
|
||||
return err(groupWithoutPriceProblem());
|
||||
}
|
||||
|
||||
const owner = await db.user.findUnique({ where: { id: payment.group.createdById } });
|
||||
const currency = currencyForCountry((owner?.country as CountryCode | null) ?? null);
|
||||
const unitPrice = Number(payment.amount.toString());
|
||||
|
||||
const getToken = this.deps.getToken ?? getMpAccessToken;
|
||||
const token = await getToken(payment.group.createdById);
|
||||
if (!token.ok) {
|
||||
return token;
|
||||
}
|
||||
|
||||
const backUrl = `${this.deps.webOrigin ?? getWebOrigin()}/payments`;
|
||||
const createPreference = this.deps.createPreference ?? createCheckoutPreference;
|
||||
|
||||
let preference: { initPoint: string; id: string };
|
||||
try {
|
||||
preference = await createPreference(token.value.accessToken, {
|
||||
title: payment.description ?? payment.group.name,
|
||||
unitPrice,
|
||||
currencyId: currency,
|
||||
externalReference: payment.id,
|
||||
backUrl,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
logger.error({ err: error }, 'Mercado Pago preference renew failed');
|
||||
}
|
||||
return err(mpProviderErrorProblem());
|
||||
}
|
||||
|
||||
const updated = await db.payment.update({
|
||||
where: { id: payment.id },
|
||||
data: { checkoutUrl: preference.initPoint, mpPreferenceId: preference.id },
|
||||
include: {
|
||||
attendee: { select: { fullName: true } },
|
||||
group: { select: { name: true, price: true } },
|
||||
},
|
||||
});
|
||||
|
||||
return ok(toPaymentDto(updated as unknown as PaymentRecord));
|
||||
}
|
||||
}
|
||||
@@ -1 +1,2 @@
|
||||
export { startPaymentJobs } from './jobs';
|
||||
export { default as paymentsRoutes } from './routes';
|
||||
9
apps/backend/src/modules/payments/jobs/index.ts
Normal file
9
apps/backend/src/modules/payments/jobs/index.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
export {
|
||||
MarkOverduePayments,
|
||||
type MarkOverduePaymentsResult,
|
||||
} from './mark-overdue-payments';
|
||||
export {
|
||||
ReconcilePayments,
|
||||
type ReconcilePaymentsResult,
|
||||
} from './reconcile-payments';
|
||||
export { startPaymentJobs } from './schedule';
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import prisma from '@/lib/prisma';
|
||||
|
||||
/**
|
||||
* Marks overdue rows. A payment whose due date (plus a day of grace) passed and
|
||||
* is still PENDING becomes OVERDUE; it stays billable, so the professor can
|
||||
* renew its link from Cobros.
|
||||
*/
|
||||
const GRACE_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
export type MarkOverduePaymentsResult = {
|
||||
marked: number;
|
||||
};
|
||||
|
||||
type MarkOverduePaymentsDeps = {
|
||||
db?: PrismaClient;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
export class MarkOverduePayments {
|
||||
constructor(private readonly deps: MarkOverduePaymentsDeps = {}) {}
|
||||
|
||||
async execute(): Promise<MarkOverduePaymentsResult> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const now = this.deps.now ?? new Date();
|
||||
const horizon = new Date(now.getTime() - GRACE_MS);
|
||||
|
||||
const updated = await db.payment.updateMany({
|
||||
where: { status: 'PENDING', dueDate: { lt: horizon } },
|
||||
data: { status: 'OVERDUE' },
|
||||
});
|
||||
|
||||
return { marked: updated.count };
|
||||
}
|
||||
}
|
||||
87
apps/backend/src/modules/payments/jobs/reconcile-payments.ts
Normal file
87
apps/backend/src/modules/payments/jobs/reconcile-payments.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { logger } from '@/logger';
|
||||
import { getMpAccessToken } from '@/modules/mp';
|
||||
import { MpApiError, searchMpPaymentByExternalReference } from '@/modules/mp/lib';
|
||||
|
||||
/**
|
||||
* Pulls payments from Mercado Pago instead of trusting a webhook. A payment
|
||||
* link is just a preference until someone pays it; this job asks the seller's
|
||||
* account for our `external_reference` and marks approved payments as PAID.
|
||||
*
|
||||
* This is the stopgap and the source of truth: if a webhook is ever added it
|
||||
* gives you the confirmation, but this job is what keeps the Cobros screen
|
||||
* correct even when a notification is lost.
|
||||
*/
|
||||
const RECONCILE_AFTER_MS = 5 * 60 * 1000;
|
||||
const BATCH_LIMIT = 50;
|
||||
|
||||
export type ReconcilePaymentsResult = {
|
||||
paid: number;
|
||||
skipped: number;
|
||||
failed: number;
|
||||
};
|
||||
|
||||
type ReconcilePaymentsDeps = {
|
||||
db?: PrismaClient;
|
||||
getToken?: typeof getMpAccessToken;
|
||||
search?: typeof searchMpPaymentByExternalReference;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
export class ReconcilePayments {
|
||||
constructor(private readonly deps: ReconcilePaymentsDeps = {}) {}
|
||||
|
||||
async execute(): Promise<ReconcilePaymentsResult> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const now = this.deps.now ?? new Date();
|
||||
const getToken = this.deps.getToken ?? getMpAccessToken;
|
||||
const search = this.deps.search ?? searchMpPaymentByExternalReference;
|
||||
|
||||
const awaiting = await db.payment.findMany({
|
||||
where: {
|
||||
status: 'PENDING',
|
||||
checkoutUrl: { not: null },
|
||||
createdAt: { lt: new Date(now.getTime() - RECONCILE_AFTER_MS) },
|
||||
},
|
||||
include: { group: { select: { createdById: true } } },
|
||||
take: BATCH_LIMIT,
|
||||
});
|
||||
|
||||
const totals: ReconcilePaymentsResult = { paid: 0, skipped: 0, failed: 0 };
|
||||
|
||||
for (const payment of awaiting) {
|
||||
const token = await getToken(payment.group.createdById);
|
||||
if (!token.ok) {
|
||||
// No usable token (not linked, or needs re-auth). Not a payment problem:
|
||||
// the row stays PENDING and the account notice tells the professor what to do.
|
||||
totals.skipped += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const found = await search(token.value.accessToken, payment.id);
|
||||
if (found && found.status === 'approved' && found.externalReference === payment.id) {
|
||||
await db.payment.update({
|
||||
where: { id: payment.id },
|
||||
data: {
|
||||
status: 'PAID',
|
||||
mpPaymentId: found.id,
|
||||
paidAt: found.dateApproved ? new Date(found.dateApproved) : new Date(),
|
||||
},
|
||||
});
|
||||
totals.paid += 1;
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof MpApiError) {
|
||||
totals.failed += 1;
|
||||
} else {
|
||||
logger.error({ err: error }, 'Unexpected payment reconciliation failure');
|
||||
totals.failed += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return totals;
|
||||
}
|
||||
}
|
||||
40
apps/backend/src/modules/payments/jobs/schedule.ts
Normal file
40
apps/backend/src/modules/payments/jobs/schedule.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { logger } from '@/logger';
|
||||
import { MarkOverduePayments } from './mark-overdue-payments';
|
||||
import { ReconcilePayments } from './reconcile-payments';
|
||||
|
||||
const RECONCILE_CRON = '*/15 * * * *';
|
||||
const OVERDUE_CRON = '4 4 * * *';
|
||||
|
||||
/**
|
||||
* Registers the payment background jobs. Called once from `server.ts`, following
|
||||
* the same guards as `startMpJobs`: Bun's in-process cron treats a rejected
|
||||
* promise as an unhandledRejection (which would crash the process), and `unref`
|
||||
* keeps the jobs from holding the process alive on their own.
|
||||
*/
|
||||
export function startPaymentJobs(): void {
|
||||
Bun.cron(
|
||||
RECONCILE_CRON,
|
||||
async () => {
|
||||
try {
|
||||
const totals = await new ReconcilePayments().execute();
|
||||
logger.info(totals, 'Mercado Pago payments reconciliation finished');
|
||||
} catch (error) {
|
||||
logger.error({ err: error }, 'Mercado Pago payments reconciliation failed');
|
||||
}
|
||||
},
|
||||
{ tz: 'UTC' },
|
||||
).unref();
|
||||
|
||||
Bun.cron(
|
||||
OVERDUE_CRON,
|
||||
async () => {
|
||||
try {
|
||||
const totals = await new MarkOverduePayments().execute();
|
||||
logger.info(totals, 'Overdue payments marked');
|
||||
} catch (error) {
|
||||
logger.error({ err: error }, 'Marking overdue payments failed');
|
||||
}
|
||||
},
|
||||
{ tz: 'UTC' },
|
||||
).unref();
|
||||
}
|
||||
37
apps/backend/src/modules/payments/lib/helpers.ts
Normal file
37
apps/backend/src/modules/payments/lib/helpers.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import type { PaymentDto } from '@gruperly/shared';
|
||||
|
||||
export type PaymentRecord = {
|
||||
id: string;
|
||||
groupId: string;
|
||||
attendeeId: string;
|
||||
amount: { toString(): string } | number;
|
||||
currency: string;
|
||||
status: PaymentDto['status'];
|
||||
description: string | null;
|
||||
checkoutUrl: string | null;
|
||||
dueDate: Date;
|
||||
paidAt: Date | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
group: { name: string; price: unknown };
|
||||
attendee: { fullName: string };
|
||||
};
|
||||
|
||||
export function toPaymentDto(record: PaymentRecord): PaymentDto {
|
||||
return {
|
||||
id: record.id,
|
||||
groupId: record.groupId,
|
||||
groupName: record.group.name,
|
||||
attendeeId: record.attendeeId,
|
||||
attendeeName: record.attendee.fullName,
|
||||
amount: Number(record.amount.toString()),
|
||||
currency: record.currency,
|
||||
status: record.status,
|
||||
description: record.description,
|
||||
checkoutUrl: record.checkoutUrl,
|
||||
dueDate: record.dueDate.toISOString(),
|
||||
paidAt: record.paidAt ? record.paidAt.toISOString() : null,
|
||||
createdAt: record.createdAt.toISOString(),
|
||||
updatedAt: record.updatedAt.toISOString(),
|
||||
};
|
||||
}
|
||||
1
apps/backend/src/modules/payments/lib/index.ts
Normal file
1
apps/backend/src/modules/payments/lib/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { type PaymentRecord, toPaymentDto } from './helpers';
|
||||
@@ -1,8 +1,10 @@
|
||||
import { Hono } from 'hono';
|
||||
import getAllRoute from './features/get-all/route';
|
||||
import renewRoute from './features/renew/route';
|
||||
|
||||
const routes = new Hono();
|
||||
|
||||
routes.route('/', getAllRoute);
|
||||
routes.route('/', renewRoute);
|
||||
|
||||
export default routes;
|
||||
@@ -2,6 +2,7 @@ import app from '@/app';
|
||||
import { getPrismaClient } from '@/lib/prisma';
|
||||
import { logger } from '@/logger';
|
||||
import { startMpJobs } from '@/modules/mp';
|
||||
import { startPaymentJobs } from '@/modules/payments';
|
||||
|
||||
const port = Number(process.env.PORT ?? 4000);
|
||||
|
||||
@@ -13,6 +14,7 @@ const server = Bun.serve({
|
||||
});
|
||||
|
||||
startMpJobs();
|
||||
startPaymentJobs();
|
||||
|
||||
async function shutdown(): Promise<void> {
|
||||
server.stop(true);
|
||||
|
||||
@@ -64,6 +64,7 @@ const firstGroupPayload = {
|
||||
price: group.price,
|
||||
billingType: group.billingType,
|
||||
dueDay: group.dueDay,
|
||||
country: 'AR',
|
||||
};
|
||||
|
||||
describe('onboarding routes', () => {
|
||||
@@ -185,7 +186,7 @@ describe('onboarding routes', () => {
|
||||
});
|
||||
expect(prisma.user.update).toHaveBeenCalledWith({
|
||||
where: { id: userId },
|
||||
data: { onboardingCompleted: true },
|
||||
data: { onboardingCompleted: true, country: 'AR' },
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
247
apps/backend/test/payments-batch.test.ts
Normal file
247
apps/backend/test/payments-batch.test.ts
Normal file
@@ -0,0 +1,247 @@
|
||||
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
|
||||
const db = {
|
||||
mpAccount: {
|
||||
findUnique: mock(),
|
||||
},
|
||||
group: {
|
||||
findUnique: mock(),
|
||||
},
|
||||
attendee: {
|
||||
findMany: mock(),
|
||||
},
|
||||
payment: {
|
||||
create: mock(),
|
||||
update: mock(),
|
||||
},
|
||||
user: {
|
||||
findUnique: mock(),
|
||||
},
|
||||
};
|
||||
|
||||
mock.module('@/lib/prisma', () => ({
|
||||
default: db,
|
||||
getPrismaClient: mock(),
|
||||
UnitOfWork: class {},
|
||||
}));
|
||||
|
||||
import prisma from '@/lib/prisma';
|
||||
import { groupsRoutes } from '@/modules/groups';
|
||||
import { MpApiError } from '@/modules/mp/lib/mp-oauth';
|
||||
import { CreatePaymentBatch } from '@/modules/payments/features/create-batch/use-case';
|
||||
|
||||
const userId = 'user-1';
|
||||
const webOrigin = 'http://localhost:6173';
|
||||
|
||||
function makeApp(userValue: unknown) {
|
||||
const app = new Hono();
|
||||
app.use('*', async (c, next) => {
|
||||
c.set('user', userValue as never);
|
||||
await next();
|
||||
});
|
||||
app.route('/groups', groupsRoutes);
|
||||
return app;
|
||||
}
|
||||
|
||||
function okAccount() {
|
||||
return {
|
||||
ok: true,
|
||||
value: { accountId: 'acc-1', accessToken: 'token-1', expiresAt: new Date() },
|
||||
};
|
||||
}
|
||||
|
||||
const groupOwner = {
|
||||
id: 'group-1',
|
||||
name: 'Vinyasa',
|
||||
createdById: userId,
|
||||
price: { toString: () => '120.00' } as { toString(): string },
|
||||
members: [],
|
||||
};
|
||||
|
||||
let getToken: ReturnType<typeof mock>;
|
||||
let createPreference: ReturnType<typeof mock>;
|
||||
|
||||
function batchUseCase() {
|
||||
getToken = mock(async () => okAccount());
|
||||
createPreference = mock(async () => ({
|
||||
id: 'pref-1',
|
||||
initPoint: 'https://mp.link/pay-1',
|
||||
sandboxInitPoint: null,
|
||||
}));
|
||||
return new CreatePaymentBatch({ getToken, createPreference, webOrigin });
|
||||
}
|
||||
|
||||
describe('create payments batch', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('creates one link per active attendee; keeps going when one preference fails', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(groupOwner);
|
||||
prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' });
|
||||
prisma.attendee.findMany.mockResolvedValue([
|
||||
{ id: 'att-1', fullName: 'Juana' },
|
||||
{ id: 'att-2', fullName: 'Pedro' },
|
||||
]);
|
||||
prisma.payment.create
|
||||
.mockResolvedValueOnce({ id: 'pay-1' })
|
||||
.mockResolvedValueOnce({ id: 'pay-2' });
|
||||
const useCase = batchUseCase();
|
||||
createPreference.mockResolvedValueOnce({
|
||||
id: 'pref-1',
|
||||
initPoint: 'https://mp.link/pay-1',
|
||||
sandboxInitPoint: null,
|
||||
});
|
||||
createPreference.mockRejectedValue(new MpApiError(502, 'bad_gateway'));
|
||||
|
||||
const result = await useCase.execute('group-1', userId, {
|
||||
dueDate: '2026-10-05T12:00:00.000Z',
|
||||
description: 'Octubre',
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw new Error('expected ok');
|
||||
expect(result.value).toEqual({
|
||||
groupId: 'group-1',
|
||||
total: 2,
|
||||
linked: 1,
|
||||
failed: 1,
|
||||
items: [
|
||||
{
|
||||
paymentId: 'pay-1',
|
||||
attendeeId: 'att-1',
|
||||
attendeeName: 'Juana',
|
||||
amount: 120,
|
||||
currency: 'ARS',
|
||||
checkoutUrl: 'https://mp.link/pay-1',
|
||||
outcome: 'LINKED',
|
||||
reason: null,
|
||||
},
|
||||
{
|
||||
paymentId: 'pay-2',
|
||||
attendeeId: 'att-2',
|
||||
attendeeName: 'Pedro',
|
||||
amount: 120,
|
||||
currency: 'ARS',
|
||||
checkoutUrl: null,
|
||||
outcome: 'FAILED',
|
||||
reason: 'mp_provider_error',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(prisma.payment.create).toHaveBeenCalledTimes(2);
|
||||
expect(prisma.payment.update).toHaveBeenCalledTimes(1);
|
||||
expect(prisma.payment.update).toHaveBeenCalledWith({
|
||||
where: { id: 'pay-1' },
|
||||
data: { checkoutUrl: 'https://mp.link/pay-1', mpPreferenceId: 'pref-1' },
|
||||
});
|
||||
expect(createPreference).toHaveBeenNthCalledWith(1, 'token-1', {
|
||||
title: 'Octubre',
|
||||
unitPrice: 120,
|
||||
currencyId: 'ARS',
|
||||
externalReference: 'pay-1',
|
||||
backUrl: `${webOrigin}/payments`,
|
||||
});
|
||||
});
|
||||
|
||||
it('derives the currency from the owner country and defaults when there is none', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue({ ...groupOwner, price: { toString: () => '80.00' } });
|
||||
prisma.user.findUnique.mockResolvedValue({ id: userId, country: null });
|
||||
prisma.attendee.findMany.mockResolvedValue([{ id: 'att-2', fullName: 'Pedro' }]);
|
||||
prisma.payment.create.mockResolvedValueOnce({ id: 'pay-2' });
|
||||
const useCase = batchUseCase();
|
||||
createPreference.mockResolvedValueOnce({
|
||||
id: 'pref-2',
|
||||
initPoint: 'https://mp.link/pay-2',
|
||||
sandboxInitPoint: null,
|
||||
});
|
||||
|
||||
const result = await useCase.execute('group-1', userId, {
|
||||
dueDate: '2026-10-05T12:00:00.000Z',
|
||||
attendeeIds: ['att-2'],
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw new Error('expected ok');
|
||||
expect(result.value.items).toHaveLength(1);
|
||||
expect(result.value.items[0]).toMatchObject({ attendeeId: 'att-2', currency: 'ARS' });
|
||||
expect(prisma.attendee.findMany).toHaveBeenCalledWith({
|
||||
where: { groupId: 'group-1', status: 'ACTIVE', id: { in: ['att-2'] } },
|
||||
});
|
||||
});
|
||||
|
||||
it('propagates the not-connected problem and creates no rows', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(groupOwner);
|
||||
prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' });
|
||||
prisma.attendee.findMany.mockResolvedValue([{ id: 'att-1', fullName: 'Juana' }]);
|
||||
getToken = mock(async () => ({
|
||||
ok: false,
|
||||
error: {
|
||||
type: 'https://gruperly.app/problems/conflict',
|
||||
title: 'Conflict',
|
||||
status: 409,
|
||||
detail: 'No tenés una cuenta de Mercado Pago vinculada.',
|
||||
code: 'mp_not_connected',
|
||||
},
|
||||
}));
|
||||
const createPreference = mock(async () => {
|
||||
throw new Error('should not be called');
|
||||
});
|
||||
|
||||
const result = await new CreatePaymentBatch({ getToken, createPreference, webOrigin }).execute(
|
||||
'group-1',
|
||||
userId,
|
||||
{ dueDate: '2026-10-05T12:00:00.000Z' },
|
||||
);
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
expect(prisma.payment.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('answers 409 over HTTP when the owner has no linked account', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(groupOwner);
|
||||
prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' });
|
||||
prisma.attendee.findMany.mockResolvedValue([{ id: 'att-1', fullName: 'Juana' }]);
|
||||
prisma.mpAccount.findUnique.mockResolvedValue(null);
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/groups/group-1/payments/batch', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ dueDate: '2026-10-05T12:00:00.000Z' }),
|
||||
});
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
expect(prisma.payment.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects a group without price', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue({ ...groupOwner, price: null });
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/groups/group-1/payments/batch', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ dueDate: '2026-10-05T12:00:00.000Z' }),
|
||||
});
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
expect(prisma.attendee.findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects a group the user has no access to', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue({
|
||||
...groupOwner,
|
||||
createdById: 'someone-else',
|
||||
members: [],
|
||||
});
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/groups/group-1/payments/batch', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ dueDate: '2026-10-05T12:00:00.000Z' }),
|
||||
});
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
});
|
||||
43
apps/backend/test/payments-overdue.test.ts
Normal file
43
apps/backend/test/payments-overdue.test.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
|
||||
|
||||
const db = {
|
||||
payment: {
|
||||
updateMany: mock(),
|
||||
},
|
||||
};
|
||||
|
||||
mock.module('@/lib/prisma', () => ({
|
||||
default: db,
|
||||
getPrismaClient: mock(),
|
||||
UnitOfWork: class {},
|
||||
}));
|
||||
|
||||
import prisma from '@/lib/prisma';
|
||||
import { MarkOverduePayments } from '@/modules/payments/jobs';
|
||||
|
||||
describe('mark overdue payments', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('marks PENDING payments whose due date passed more than a day ago', async () => {
|
||||
prisma.payment.updateMany.mockResolvedValue({ count: 3 });
|
||||
const now = new Date('2026-10-08T12:00:00.000Z');
|
||||
|
||||
const result = await new MarkOverduePayments({ now }).execute();
|
||||
|
||||
expect(result).toEqual({ marked: 3 });
|
||||
expect(prisma.payment.updateMany).toHaveBeenCalledWith({
|
||||
where: { status: 'PENDING', dueDate: { lt: new Date('2026-10-07T12:00:00.000Z') } },
|
||||
data: { status: 'OVERDUE' },
|
||||
});
|
||||
});
|
||||
|
||||
it('leaves payments inside the grace period alone', async () => {
|
||||
prisma.payment.updateMany.mockResolvedValue({ count: 0 });
|
||||
|
||||
const result = await new MarkOverduePayments({ now: new Date() }).execute();
|
||||
|
||||
expect(result).toEqual({ marked: 0 });
|
||||
});
|
||||
});
|
||||
129
apps/backend/test/payments-reconcile.test.ts
Normal file
129
apps/backend/test/payments-reconcile.test.ts
Normal file
@@ -0,0 +1,129 @@
|
||||
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
|
||||
|
||||
const db = {
|
||||
payment: {
|
||||
findMany: mock(),
|
||||
update: mock(),
|
||||
},
|
||||
};
|
||||
|
||||
mock.module('@/lib/prisma', () => ({
|
||||
default: db,
|
||||
getPrismaClient: mock(),
|
||||
UnitOfWork: class {},
|
||||
}));
|
||||
|
||||
import prisma from '@/lib/prisma';
|
||||
import { MpApiError } from '@/modules/mp/lib/mp-oauth';
|
||||
import { ReconcilePayments } from '@/modules/payments/jobs';
|
||||
|
||||
const ownerId = 'user-1';
|
||||
const pendingPayment = (id: string, overrides: Record<string, unknown> = {}) => ({
|
||||
id,
|
||||
groupId: 'group-1',
|
||||
status: 'PENDING',
|
||||
checkoutUrl: 'https://mp.link/pay',
|
||||
createdAt: new Date(Date.now() - 10 * 60 * 1000),
|
||||
group: { createdById: ownerId },
|
||||
...overrides,
|
||||
});
|
||||
|
||||
function okAccount() {
|
||||
return {
|
||||
ok: true,
|
||||
value: { accountId: 'acc-1', accessToken: 'token-1', expiresAt: new Date() },
|
||||
};
|
||||
}
|
||||
|
||||
describe('reconcile payments', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('marks an approved Mercado Pago payment as PAID', async () => {
|
||||
prisma.payment.findMany.mockResolvedValue([pendingPayment('pay-1')]);
|
||||
const getToken = mock(async () => okAccount());
|
||||
const search = mock(async () => ({
|
||||
id: '999999999',
|
||||
status: 'approved',
|
||||
externalReference: 'pay-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(prisma.payment.update).toHaveBeenCalledWith({
|
||||
where: { id: 'pay-1' },
|
||||
data: {
|
||||
status: 'PAID',
|
||||
mpPaymentId: '999999999',
|
||||
paidAt: new Date('2026-10-01T12:30:00.000Z'),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('skips a payment that is still pending in Mercado Pago', async () => {
|
||||
prisma.payment.findMany.mockResolvedValue([pendingPayment('pay-1')]);
|
||||
const getToken = mock(async () => okAccount());
|
||||
const search = mock(async () => ({
|
||||
id: '999999999',
|
||||
status: 'pending',
|
||||
externalReference: 'pay-1',
|
||||
liveMode: true,
|
||||
dateApproved: null,
|
||||
}));
|
||||
|
||||
const result = await new ReconcilePayments({ getToken, search }).execute();
|
||||
|
||||
expect(result).toEqual({ paid: 0, skipped: 0, failed: 0 });
|
||||
expect(prisma.payment.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('skips rows when the owner has no usable token', async () => {
|
||||
prisma.payment.findMany.mockResolvedValue([pendingPayment('pay-1')]);
|
||||
const getToken = mock(async () => ({
|
||||
ok: false,
|
||||
error: { type: 'x', title: 'Conflict', status: 409, detail: 'x', code: 'mp_not_connected' },
|
||||
}));
|
||||
const search = mock(async () => {
|
||||
throw new Error('should not be called');
|
||||
});
|
||||
|
||||
const result = await new ReconcilePayments({ getToken, search }).execute();
|
||||
|
||||
expect(result).toEqual({ paid: 0, skipped: 1, failed: 0 });
|
||||
expect(search).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('counts an unreachable Mercado Pago as failed and leaves the row pending', async () => {
|
||||
prisma.payment.findMany.mockResolvedValue([pendingPayment('pay-1')]);
|
||||
const getToken = mock(async () => okAccount());
|
||||
const search = mock(async () => {
|
||||
throw new MpApiError(0, null);
|
||||
});
|
||||
|
||||
const result = await new ReconcilePayments({ getToken, search }).execute();
|
||||
|
||||
expect(result).toEqual({ paid: 0, skipped: 0, failed: 1 });
|
||||
expect(prisma.payment.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('only reconciles payments linked for at least five minutes', async () => {
|
||||
prisma.payment.findMany.mockResolvedValue([]);
|
||||
const now = new Date('2026-10-01T12:00:00.000Z');
|
||||
|
||||
await new ReconcilePayments({ now }).execute();
|
||||
|
||||
expect(prisma.payment.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: {
|
||||
status: 'PENDING',
|
||||
checkoutUrl: { not: null },
|
||||
createdAt: { lt: new Date('2026-10-01T11:55:00.000Z') },
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
158
apps/backend/test/payments-renew.test.ts
Normal file
158
apps/backend/test/payments-renew.test.ts
Normal file
@@ -0,0 +1,158 @@
|
||||
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
|
||||
const db = {
|
||||
payment: {
|
||||
findUnique: mock(),
|
||||
update: mock(),
|
||||
},
|
||||
user: {
|
||||
findUnique: mock(),
|
||||
},
|
||||
};
|
||||
|
||||
mock.module('@/lib/prisma', () => ({
|
||||
default: db,
|
||||
getPrismaClient: mock(),
|
||||
UnitOfWork: class {},
|
||||
}));
|
||||
|
||||
import prisma from '@/lib/prisma';
|
||||
import { paymentsRoutes } from '@/modules/payments';
|
||||
import { RenewPaymentLink } from '@/modules/payments/features/renew/use-case';
|
||||
|
||||
const userId = 'user-1';
|
||||
const webOrigin = 'http://localhost:6173';
|
||||
|
||||
function makeApp(userValue: unknown) {
|
||||
const app = new Hono();
|
||||
app.use('*', async (c, next) => {
|
||||
c.set('user', userValue as never);
|
||||
await next();
|
||||
});
|
||||
app.route('/payments', paymentsRoutes);
|
||||
return app;
|
||||
}
|
||||
|
||||
function paymentWithoutLink(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 'pay-1',
|
||||
groupId: 'group-1',
|
||||
attendeeId: 'att-1',
|
||||
amount: { toString: () => '120.00' } as { toString(): string },
|
||||
currency: 'ARS',
|
||||
status: 'PENDING',
|
||||
description: null,
|
||||
checkoutUrl: null,
|
||||
mpPreferenceId: null,
|
||||
dueDate: new Date('2026-10-05T12:00:00.000Z'),
|
||||
paidAt: null,
|
||||
createdAt: new Date('2026-10-01T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-10-01T10:00:00.000Z'),
|
||||
attendee: { fullName: 'Juana Pérez' },
|
||||
group: {
|
||||
name: 'Vinyasa',
|
||||
price: { toString: () => '120.00' },
|
||||
createdById: userId,
|
||||
members: [],
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('renew payment link', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('creates a new link for a payment that lost it and returns the payment', async () => {
|
||||
prisma.payment.findUnique.mockResolvedValue(paymentWithoutLink());
|
||||
prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' });
|
||||
prisma.payment.update.mockResolvedValue({
|
||||
...paymentWithoutLink(),
|
||||
checkoutUrl: 'https://mp.link/pay-1',
|
||||
group: { name: 'Vinyasa', price: { toString: () => '120.00' } },
|
||||
});
|
||||
const getToken = mock(async () => ({
|
||||
ok: true,
|
||||
value: { accountId: 'acc-1', accessToken: 'token-1', expiresAt: new Date() },
|
||||
}));
|
||||
const createPreference = mock(async () => ({
|
||||
id: 'pref-new',
|
||||
initPoint: 'https://mp.link/pay-1',
|
||||
sandboxInitPoint: null,
|
||||
}));
|
||||
|
||||
const result = await new RenewPaymentLink({ getToken, createPreference, webOrigin }).execute(
|
||||
'pay-1',
|
||||
userId,
|
||||
);
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw new Error('expected ok');
|
||||
expect(result.value).toMatchObject({
|
||||
id: 'pay-1',
|
||||
groupName: 'Vinyasa',
|
||||
attendeeName: 'Juana Pérez',
|
||||
checkoutUrl: 'https://mp.link/pay-1',
|
||||
});
|
||||
expect(createPreference).toHaveBeenCalledWith('token-1', {
|
||||
title: 'Vinyasa',
|
||||
unitPrice: 120,
|
||||
currencyId: 'ARS',
|
||||
externalReference: 'pay-1',
|
||||
backUrl: `${webOrigin}/payments`,
|
||||
});
|
||||
expect(prisma.payment.update).toHaveBeenCalledWith({
|
||||
where: { id: 'pay-1' },
|
||||
data: { checkoutUrl: 'https://mp.link/pay-1', mpPreferenceId: 'pref-new' },
|
||||
include: {
|
||||
attendee: { select: { fullName: true } },
|
||||
group: { select: { name: true, price: true } },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps an existing link: idempotent, no Mercado Pago call', async () => {
|
||||
prisma.payment.findUnique.mockResolvedValue(
|
||||
paymentWithoutLink({ checkoutUrl: 'https://mp.link/pay-1' }),
|
||||
);
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/payments/pay-1/renew', { method: 'POST' });
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(prisma.payment.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('answers 409 when the owner has no linked account', async () => {
|
||||
prisma.payment.findUnique.mockResolvedValue(paymentWithoutLink());
|
||||
prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' });
|
||||
const getToken = mock(async () => ({
|
||||
ok: false,
|
||||
error: { type: 'x', title: 'Conflict', status: 409, detail: 'x', code: 'mp_not_connected' },
|
||||
}));
|
||||
|
||||
const result = await new RenewPaymentLink({ getToken }).execute('pay-1', userId);
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
expect(prisma.payment.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects a payment of a group the user has no access to', async () => {
|
||||
prisma.payment.findUnique.mockResolvedValue(
|
||||
paymentWithoutLink({
|
||||
group: {
|
||||
name: 'Vinyasa',
|
||||
price: { toString: () => '120.00' },
|
||||
createdById: 'someone-else',
|
||||
members: [],
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/payments/pay-1/renew', { method: 'POST' });
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(prisma.payment.update).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,13 +1,18 @@
|
||||
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
|
||||
mock.module('@/lib/prisma', () => ({
|
||||
default: {
|
||||
payment: {
|
||||
findMany: mock(),
|
||||
count: mock(),
|
||||
},
|
||||
const db = {
|
||||
group: {
|
||||
findMany: mock(),
|
||||
},
|
||||
payment: {
|
||||
findMany: mock(),
|
||||
count: mock(),
|
||||
},
|
||||
};
|
||||
|
||||
mock.module('@/lib/prisma', () => ({
|
||||
default: db,
|
||||
getPrismaClient: mock(),
|
||||
UnitOfWork: class {},
|
||||
}));
|
||||
@@ -15,43 +20,61 @@ mock.module('@/lib/prisma', () => ({
|
||||
import prisma from '@/lib/prisma';
|
||||
import { paymentsRoutes } from '@/modules/payments';
|
||||
|
||||
const app = new Hono();
|
||||
app.route('/payments', paymentsRoutes);
|
||||
const userId = 'user-1';
|
||||
|
||||
const payment = {
|
||||
id: 'payment-1',
|
||||
groupId: 'group-1',
|
||||
attendeeId: 'attendee-1',
|
||||
groupId: 'group-1',
|
||||
attendeeId: 'attendee-1',
|
||||
amount: { toString: () => '150.50' } as { toString(): string },
|
||||
currency: 'MXN',
|
||||
status: 'pending',
|
||||
currency: 'ARS',
|
||||
status: 'PENDING',
|
||||
description: 'Mensualidad de Septiembre',
|
||||
checkoutUrl: 'https://mercadopago.com/checkout/payment-1',
|
||||
dueDate: new Date('2026-09-01T10:00:00.000Z'),
|
||||
paidAt: null,
|
||||
createdAt: new Date('2026-08-01T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-08-01T10:00:00.000Z'),
|
||||
group: { name: 'Cuadrilla Alfa', price: 150.5 },
|
||||
attendee: { fullName: 'Juana Pérez' },
|
||||
};
|
||||
|
||||
function makeApp(userValue: unknown) {
|
||||
const app = new Hono();
|
||||
app.use('*', async (c, next) => {
|
||||
c.set('user', userValue as never);
|
||||
await next();
|
||||
});
|
||||
app.route('/payments', paymentsRoutes);
|
||||
return app;
|
||||
}
|
||||
|
||||
describe('payments routes', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('lists payments with pagination and converts Decimal amounts', async () => {
|
||||
it('lists payments scoped to the user, with attendee and group names', async () => {
|
||||
prisma.group.findMany.mockResolvedValue([{ id: 'group-1' }]);
|
||||
prisma.payment.findMany.mockResolvedValue([payment]);
|
||||
prisma.payment.count.mockResolvedValue(1);
|
||||
|
||||
const res = await app.request('/payments');
|
||||
const res = await makeApp({ id: userId }).request('/payments');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({
|
||||
data: [
|
||||
{
|
||||
id: 'payment-1',
|
||||
groupId: 'group-1',
|
||||
attendeeId: 'attendee-1',
|
||||
groupId: 'group-1',
|
||||
groupName: 'Cuadrilla Alfa',
|
||||
attendeeId: 'attendee-1',
|
||||
attendeeName: 'Juana Pérez',
|
||||
amount: 150.5,
|
||||
currency: 'MXN',
|
||||
status: 'pending',
|
||||
currency: 'ARS',
|
||||
status: 'PENDING',
|
||||
description: 'Mensualidad de Septiembre',
|
||||
checkoutUrl: payment.checkoutUrl,
|
||||
dueDate: payment.dueDate.toISOString(),
|
||||
paidAt: null,
|
||||
createdAt: payment.createdAt.toISOString(),
|
||||
@@ -60,15 +83,49 @@ groupId: 'group-1',
|
||||
],
|
||||
pagination: { page: 1, pageSize: 10, total: 1, totalPages: 1 },
|
||||
});
|
||||
expect(prisma.group.findMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
OR: [{ createdById: userId }, { members: { some: { userId } } }],
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
expect(prisma.payment.findMany).toHaveBeenCalledWith({
|
||||
where: { groupId: { in: ['group-1'] } },
|
||||
include: {
|
||||
group: { select: { name: true, price: true } },
|
||||
attendee: { select: { fullName: true } },
|
||||
},
|
||||
skip: 0,
|
||||
take: 10,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
});
|
||||
|
||||
it('filters payments by group and status', async () => {
|
||||
prisma.group.findMany.mockResolvedValue([{ id: 'group-1' }]);
|
||||
prisma.payment.findMany.mockResolvedValue([]);
|
||||
prisma.payment.count.mockResolvedValue(0);
|
||||
|
||||
const res = await makeApp({ id: userId }).request(
|
||||
'/payments?groupId=group-1&status=OVERDUE',
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(prisma.payment.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { groupId: 'group-1', status: 'OVERDUE' },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects requests without a session user', async () => {
|
||||
const res = await makeApp(null).request('/payments');
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it('rejects invalid pagination query parameters', async () => {
|
||||
const res = await app.request('/payments?pageSize=101');
|
||||
const res = await makeApp({ id: userId }).request('/payments?pageSize=101');
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user