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,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;

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

View File

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

View File

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

View 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;

View 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));
}
}

View File

@@ -1 +1,2 @@
export { startPaymentJobs } from './jobs';
export { default as paymentsRoutes } from './routes';

View File

@@ -0,0 +1,9 @@
export {
MarkOverduePayments,
type MarkOverduePaymentsResult,
} from './mark-overdue-payments';
export {
ReconcilePayments,
type ReconcilePaymentsResult,
} from './reconcile-payments';
export { startPaymentJobs } from './schedule';

View File

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

View 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;
}
}

View 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();
}

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

View File

@@ -0,0 +1 @@
export { type PaymentRecord, toPaymentDto } from './helpers';

View File

@@ -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;