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:
Jose Selesan
2026-10-28 15:39:09 -03:00
parent b99bc4d519
commit 060a4f09e4
146 changed files with 7994 additions and 32 deletions

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

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

View File

@@ -0,0 +1,32 @@
import { type UpdateTransferDetails, UpdateTransferDetailsSchema } from '@gruperly/shared';
import { Hono } from 'hono';
import { problemJson, unauthorizedProblem } from '@/http/problem-details';
import { validate } from '@/http/validate';
import prisma from '@/lib/prisma';
/* Bank transfer details (Ajustes) that students see when reporting a payment. */
const route = new Hono();
route.get('/transfer-details', async (c) => {
const user = c.get('user');
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
const row = await prisma.user.findUniqueOrThrow({
where: { id: user.id },
select: { transferAlias: true, transferHolder: true },
});
return c.json({ alias: row.transferAlias, holder: row.transferHolder });
});
route.put('/transfer-details', validate.json(UpdateTransferDetailsSchema), async (c) => {
const user = c.get('user');
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
const { alias, holder } = c.req.valid('json') as UpdateTransferDetails;
const row = await prisma.user.update({
where: { id: user.id },
data: { transferAlias: alias || null, transferHolder: holder || null },
select: { transferAlias: true, transferHolder: true },
});
return c.json({ alias: row.transferAlias, holder: row.transferHolder });
});
export default route;

View File

@@ -6,7 +6,7 @@ import prisma from '@/lib/prisma';
* 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 const OVERDUE_GRACE_MS = 24 * 60 * 60 * 1000;
export type MarkOverduePaymentsResult = {
marked: number;
@@ -23,7 +23,7 @@ export class MarkOverduePayments {
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 horizon = new Date(now.getTime() - OVERDUE_GRACE_MS);
const updated = await db.payment.updateMany({
where: { status: 'PENDING', dueDate: { lt: horizon } },

View File

@@ -0,0 +1,56 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { CountryCode } from '@gruperly/shared';
import { type EmailProvider, emailProvider } from '@/lib/email';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import { formatAmount } from '@/modules/whatsapp/lib/format';
// Long enough to cover the "Deshacer" on the card: an undone review emails nothing.
const NOTIFY_DELAY_MS = 60 * 1000;
export type ReviewNotifier = (reportId: string, reviewedAt: Date) => void;
/* Tells the student by email (only if they confirmed a recovery email) once
the review settles. The in-app banner is the main channel; this is a
courtesy, so an in-process timer lost on a restart is acceptable. */
export const scheduleReviewNotification: ReviewNotifier = (reportId, reviewedAt) => {
const timer = setTimeout(() => {
void sendReviewNotification(reportId, reviewedAt).catch((error) =>
logger.error({ error, reportId }, 'Payment review notification failed'),
);
}, NOTIFY_DELAY_MS);
timer.unref?.();
};
export async function sendReviewNotification(
reportId: string,
reviewedAt: Date,
deps: { db?: Pick<PrismaClient, 'reportedPayment'>; email?: Pick<EmailProvider, 'sendStudentPaymentReviewed'> } = {},
): Promise<boolean> {
const db = deps.db ?? prisma;
const report = await db.reportedPayment.findUnique({
where: { id: reportId },
select: {
status: true,
reviewedAt: true,
rejectionReason: true,
totalAmount: true,
currency: true,
group: { select: { owner: { select: { country: true } } } },
account: { select: { name: true, recoveryEmail: true, recoveryEmailVerifiedAt: true } },
},
});
// Undone or reviewed again since: this notification is stale.
if (!report || report.status === 'REPORTED' || report.reviewedAt?.getTime() !== reviewedAt.getTime()) return false;
const account = report.account;
if (!account?.recoveryEmail || !account.recoveryEmailVerifiedAt) return false;
await (deps.email ?? emailProvider).sendStudentPaymentReviewed({
email: account.recoveryEmail,
name: account.name,
confirmed: report.status === 'CONFIRMED',
amount: formatAmount(report.totalAmount.toNumber(), report.currency, report.group.owner.country as CountryCode | null),
reason: report.rejectionReason,
});
return true;
}

View File

@@ -1,10 +1,14 @@
import { Hono } from 'hono';
import getAllRoute from './features/get-all/route';
import renewRoute from './features/renew/route';
import reportedRoute from './features/reported/route';
import transferDetailsRoute from './features/transfer-details/route';
const routes = new Hono();
routes.route('/', getAllRoute);
routes.route('/', reportedRoute);
routes.route('/', transferDetailsRoute);
routes.route('/', renewRoute);
export default routes;