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