feat: app de alumnos sin contraseña (invitación de un solo uso, avisos de falta y pagos informados)
- Acceso del alumno o tutor con link de un solo uso (hash SHA-256, consumo atómico, el GET no consume), sesión propia de 90 días deslizante, passkeys opcionales (SimpleWebAuthn) y mail de recuperación con rate limit. - Lado alumno (/i/:token, /acceso, /alumno/*): inicio, clases, avisar falta, pagos, informar pago con comprobante (S3 privado, magic bytes) y perfil. - Lado profe: acceso a la app en la ficha del alumno (invitar/reinvitar), "Pagos para verificar" en Cobros con badge, faltas avisadas en la ficha de grupo y datos para transferir en Ajustes. - "Requiere atención" y el recordatorio de WhatsApp excluyen cuotas informadas. - Zona horaria por defecto: Buenos Aires. - Migración add_student_access, tests contra Postgres real (test:db) y docs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
40
apps/backend/src/modules/payments/features/reported/route.ts
Normal file
40
apps/backend/src/modules/payments/features/reported/route.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { type RejectReportedPayment, RejectReportedPaymentSchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { ReportedPayments } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.get('/reported', async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
return resultJson(c, await new ReportedPayments().list(user.id));
|
||||
});
|
||||
|
||||
route.get('/reported/:reportId/receipt', async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
return resultJson(c, await new ReportedPayments().receiptUrl(user.id, c.req.param('reportId')));
|
||||
});
|
||||
|
||||
route.post('/reported/:reportId/confirm', async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
return resultJson(c, await new ReportedPayments().confirm(user.id, c.req.param('reportId')));
|
||||
});
|
||||
|
||||
route.post('/reported/:reportId/reject', validate.json(RejectReportedPaymentSchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
const { reason } = c.req.valid('json') as RejectReportedPayment;
|
||||
return resultJson(c, await new ReportedPayments().reject(user.id, c.req.param('reportId'), reason ?? null));
|
||||
});
|
||||
|
||||
route.post('/reported/:reportId/undo', async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
return resultJson(c, await new ReportedPayments().undo(user.id, c.req.param('reportId')));
|
||||
});
|
||||
|
||||
export default route;
|
||||
226
apps/backend/src/modules/payments/features/reported/use-case.ts
Normal file
226
apps/backend/src/modules/payments/features/reported/use-case.ts
Normal file
@@ -0,0 +1,226 @@
|
||||
import type { Prisma, PrismaClient } from '@generated/prisma/client';
|
||||
import type { ProblemDetails, ReceiptUrlDto, ReportedPaymentDto, ReportedPaymentList, Result } from '@gruperly/shared';
|
||||
import { err, ok, REVIEW_UNDO_MINUTES } from '@gruperly/shared';
|
||||
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma, { UnitOfWork } from '@/lib/prisma';
|
||||
import { type FileStorage, getFileStorage } from '@/lib/storage';
|
||||
import { buildGroupWhereForUser } from '@/modules/groups/lib';
|
||||
import { storageNotAvailableProblem } from '@/modules/student-portal/lib/problems';
|
||||
import { OVERDUE_GRACE_MS } from '../../jobs/mark-overdue-payments';
|
||||
import { type ReviewNotifier, scheduleReviewNotification } from '../../lib/review-notifications';
|
||||
|
||||
export const RECEIPT_URL_TTL_SECONDS = 5 * 60;
|
||||
const PREVIEWABLE = new Set(['image/jpeg', 'image/png', 'image/webp']);
|
||||
|
||||
type ReportedDeps = {
|
||||
db?: Pick<PrismaClient, 'reportedPayment'>;
|
||||
unitOfWork?: Pick<UnitOfWork, 'executeResult'>;
|
||||
storage?: FileStorage | null;
|
||||
notify?: ReviewNotifier;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
const reportSelect = {
|
||||
id: true,
|
||||
status: true,
|
||||
createdAt: true,
|
||||
totalAmount: true,
|
||||
currency: true,
|
||||
receiptKey: true,
|
||||
receiptMime: true,
|
||||
receiptName: true,
|
||||
receiptSize: true,
|
||||
attendee: { select: { id: true, fullName: true } },
|
||||
group: { select: { id: true, name: true } },
|
||||
items: { select: { payment: { select: { id: true, description: true, dueDate: true, amount: true } } } },
|
||||
} satisfies Prisma.ReportedPaymentSelect;
|
||||
|
||||
type ReportRow = Prisma.ReportedPaymentGetPayload<{ select: typeof reportSelect }>;
|
||||
|
||||
const STATUS = { REPORTED: 'reported', CONFIRMED: 'confirmed', REJECTED: 'rejected' } as const;
|
||||
|
||||
function accessible(userId: string): Prisma.ReportedPaymentWhereInput {
|
||||
return { group: buildGroupWhereForUser(userId) as Prisma.GroupWhereInput };
|
||||
}
|
||||
|
||||
/* Cobros → "Pagos para verificar": reports waiting for the teacher, across
|
||||
their groups, oldest first. */
|
||||
export class ReportedPayments {
|
||||
constructor(private readonly deps: ReportedDeps = {}) {}
|
||||
|
||||
private get db() {
|
||||
return this.deps.db ?? prisma;
|
||||
}
|
||||
|
||||
private get storage(): FileStorage | null {
|
||||
return this.deps.storage === undefined ? getFileStorage() : this.deps.storage;
|
||||
}
|
||||
|
||||
private get now(): Date {
|
||||
return this.deps.now ?? new Date();
|
||||
}
|
||||
|
||||
async list(userId: string): Promise<Result<ReportedPaymentList, ProblemDetails>> {
|
||||
const rows = await this.db.reportedPayment.findMany({
|
||||
where: { ...accessible(userId), status: 'REPORTED' },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
select: reportSelect,
|
||||
});
|
||||
return ok({ data: rows.map((row) => this.toDto(row)) });
|
||||
}
|
||||
|
||||
async receiptUrl(userId: string, reportId: string): Promise<Result<ReceiptUrlDto, ProblemDetails>> {
|
||||
const row = await this.db.reportedPayment.findFirst({
|
||||
where: { id: reportId, ...accessible(userId) },
|
||||
select: { receiptKey: true, receiptMime: true, receiptName: true },
|
||||
});
|
||||
if (!row?.receiptKey) return err(notFoundResourceProblem('Receipt', reportId));
|
||||
const storage = this.storage;
|
||||
if (!storage) return err(storageNotAvailableProblem());
|
||||
return ok({
|
||||
url: storage.signedUrl(row.receiptKey, RECEIPT_URL_TTL_SECONDS),
|
||||
mime: row.receiptMime,
|
||||
name: row.receiptName,
|
||||
expiresAt: new Date(this.now.getTime() + RECEIPT_URL_TTL_SECONDS * 1000).toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
/* Confirm: the report and its fees become paid, in one transaction. A fee
|
||||
already PAID (e.g. through Mercado Pago meanwhile) is left as it is. */
|
||||
async confirm(userId: string, reportId: string): Promise<Result<ReportedPaymentDto, ProblemDetails>> {
|
||||
return this.review(userId, reportId, 'CONFIRMED', null);
|
||||
}
|
||||
|
||||
/* Reject: the fees stay as they were, and they come back to the overdue alert. */
|
||||
async reject(userId: string, reportId: string, reason: string | null): Promise<Result<ReportedPaymentDto, ProblemDetails>> {
|
||||
return this.review(userId, reportId, 'REJECTED', reason);
|
||||
}
|
||||
|
||||
/* "Deshacer", for a few minutes after the review: back to REPORTED. A confirm
|
||||
is reverted only on the fees it paid (paid_at equal to the review and no MP
|
||||
payment), which go back to PENDING or OVERDUE by the overdue job's rule. */
|
||||
async undo(userId: string, reportId: string): Promise<Result<ReportedPaymentDto, ProblemDetails>> {
|
||||
const now = this.now;
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
|
||||
const undone = await unitOfWork.executeResult(async (tx) => {
|
||||
const report = await tx.reportedPayment.findFirst({
|
||||
where: {
|
||||
id: reportId,
|
||||
...accessible(userId),
|
||||
status: { in: ['CONFIRMED', 'REJECTED'] },
|
||||
reviewedAt: { gt: new Date(now.getTime() - REVIEW_UNDO_MINUTES * 60 * 1000) },
|
||||
},
|
||||
select: { status: true, reviewedAt: true, items: { select: { paymentId: true } } },
|
||||
});
|
||||
if (!report?.reviewedAt) {
|
||||
return err(conflictProblem({ detail: 'Ya no se puede deshacer.', code: 'review_undo_expired' }));
|
||||
}
|
||||
const claimed = await tx.reportedPayment.updateMany({
|
||||
where: { id: reportId, status: report.status, reviewedAt: report.reviewedAt },
|
||||
data: { status: 'REPORTED', reviewedAt: null, reviewedById: null, rejectionReason: null },
|
||||
});
|
||||
if (claimed.count !== 1) {
|
||||
return err(conflictProblem({ detail: 'Ya no se puede deshacer.', code: 'review_undo_expired' }));
|
||||
}
|
||||
if (report.status === 'CONFIRMED') {
|
||||
const paidByReview = {
|
||||
id: { in: report.items.map((item) => item.paymentId) },
|
||||
status: 'PAID' as const,
|
||||
paidAt: report.reviewedAt,
|
||||
mpPaymentId: null,
|
||||
};
|
||||
const overdueBefore = new Date(now.getTime() - OVERDUE_GRACE_MS);
|
||||
await tx.payment.updateMany({
|
||||
where: { ...paidByReview, dueDate: { lt: overdueBefore } },
|
||||
data: { status: 'OVERDUE', paidAt: null },
|
||||
});
|
||||
await tx.payment.updateMany({
|
||||
where: { ...paidByReview, dueDate: { gte: overdueBefore } },
|
||||
data: { status: 'PENDING', paidAt: null },
|
||||
});
|
||||
}
|
||||
return ok(null);
|
||||
});
|
||||
if (!undone.ok) return undone;
|
||||
return this.load(reportId);
|
||||
}
|
||||
|
||||
private async review(
|
||||
userId: string,
|
||||
reportId: string,
|
||||
status: 'CONFIRMED' | 'REJECTED',
|
||||
reason: string | null,
|
||||
): Promise<Result<ReportedPaymentDto, ProblemDetails>> {
|
||||
const now = this.now;
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
|
||||
|
||||
const reviewed = await unitOfWork.executeResult(async (tx) => {
|
||||
const claimed = await tx.reportedPayment.updateMany({
|
||||
where: { id: reportId, ...accessible(userId), status: 'REPORTED' },
|
||||
data: {
|
||||
status,
|
||||
reviewedById: userId,
|
||||
reviewedAt: now,
|
||||
rejectionReason: status === 'REJECTED' ? reason || null : null,
|
||||
},
|
||||
});
|
||||
if (claimed.count !== 1) {
|
||||
const exists = await tx.reportedPayment.findFirst({ where: { id: reportId, ...accessible(userId) }, select: { id: true } });
|
||||
return err(
|
||||
exists
|
||||
? conflictProblem({ detail: 'Este pago ya fue revisado.', code: 'payment_report_already_reviewed' })
|
||||
: notFoundResourceProblem('ReportedPayment', reportId),
|
||||
);
|
||||
}
|
||||
if (status === 'CONFIRMED') {
|
||||
const items = await tx.reportedPaymentItem.findMany({ where: { reportedPaymentId: reportId }, select: { paymentId: true } });
|
||||
await tx.payment.updateMany({
|
||||
where: { id: { in: items.map((item) => item.paymentId) }, status: { in: ['PENDING', 'OVERDUE'] } },
|
||||
data: { status: 'PAID', paidAt: now },
|
||||
});
|
||||
}
|
||||
return ok(null);
|
||||
});
|
||||
if (!reviewed.ok) return reviewed;
|
||||
|
||||
(this.deps.notify ?? scheduleReviewNotification)(reportId, now);
|
||||
return this.load(reportId);
|
||||
}
|
||||
|
||||
private async load(reportId: string): Promise<Result<ReportedPaymentDto, ProblemDetails>> {
|
||||
const row = await this.db.reportedPayment.findUniqueOrThrow({ where: { id: reportId }, select: reportSelect });
|
||||
return ok(this.toDto(row));
|
||||
}
|
||||
|
||||
private toDto(row: ReportRow): ReportedPaymentDto {
|
||||
const storage = this.storage;
|
||||
const thumbnailUrl =
|
||||
row.receiptKey && storage && PREVIEWABLE.has(row.receiptMime)
|
||||
? storage.signedUrl(row.receiptKey, RECEIPT_URL_TTL_SECONDS)
|
||||
: null;
|
||||
return {
|
||||
id: row.id,
|
||||
status: STATUS[row.status],
|
||||
attendee: row.attendee,
|
||||
group: row.group,
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
totalAmount: row.totalAmount.toNumber(),
|
||||
currency: row.currency,
|
||||
fees: row.items
|
||||
.map(({ payment }) => ({
|
||||
id: payment.id,
|
||||
description: payment.description,
|
||||
dueDate: payment.dueDate.toISOString(),
|
||||
amount: payment.amount.toNumber(),
|
||||
}))
|
||||
.sort((a, b) => a.dueDate.localeCompare(b.dueDate)),
|
||||
receipt: {
|
||||
mime: row.receiptMime,
|
||||
name: row.receiptName,
|
||||
size: row.receiptSize,
|
||||
thumbnailUrl,
|
||||
available: row.receiptKey !== null,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user