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:
Jose Selesan
2026-10-08 11:42:13 -03:00
parent b11dd47534
commit 8c5caecdda
49 changed files with 2367 additions and 90 deletions

View File

@@ -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,
});
}
}