development #14
@@ -0,0 +1,2 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "reported_payments" ADD COLUMN "note" TEXT;
|
||||||
@@ -203,6 +203,8 @@ model ReportedPayment {
|
|||||||
receiptMime String @map("receipt_mime")
|
receiptMime String @map("receipt_mime")
|
||||||
receiptName String @map("receipt_name")
|
receiptName String @map("receipt_name")
|
||||||
receiptSize Int @map("receipt_size")
|
receiptSize Int @map("receipt_size")
|
||||||
|
// Optional message from the student to the teacher.
|
||||||
|
note String?
|
||||||
status ReportedPaymentStatus @default(REPORTED)
|
status ReportedPaymentStatus @default(REPORTED)
|
||||||
reviewedById String? @map("reviewed_by_id")
|
reviewedById String? @map("reviewed_by_id")
|
||||||
reviewedAt DateTime? @map("reviewed_at")
|
reviewedAt DateTime? @map("reviewed_at")
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ const reportSelect = {
|
|||||||
createdAt: true,
|
createdAt: true,
|
||||||
totalAmount: true,
|
totalAmount: true,
|
||||||
currency: true,
|
currency: true,
|
||||||
|
note: true,
|
||||||
receiptKey: true,
|
receiptKey: true,
|
||||||
receiptMime: true,
|
receiptMime: true,
|
||||||
receiptName: true,
|
receiptName: true,
|
||||||
@@ -206,6 +207,7 @@ export class ReportedPayments {
|
|||||||
createdAt: row.createdAt.toISOString(),
|
createdAt: row.createdAt.toISOString(),
|
||||||
totalAmount: row.totalAmount.toNumber(),
|
totalAmount: row.totalAmount.toNumber(),
|
||||||
currency: row.currency,
|
currency: row.currency,
|
||||||
|
note: row.note,
|
||||||
fees: row.items
|
fees: row.items
|
||||||
.map(({ payment }) => ({
|
.map(({ payment }) => ({
|
||||||
id: payment.id,
|
id: payment.id,
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ route.get('/fees', studentSession, validate.query(StudentAttendeeQuerySchema), a
|
|||||||
return resultJson(c, await new GetStudentFees().execute(accountId, attendeeId));
|
return resultJson(c, await new GetStudentFees().execute(accountId, attendeeId));
|
||||||
});
|
});
|
||||||
|
|
||||||
// multipart/form-data: attendeeId, paymentIds (repeated) and file.
|
// multipart/form-data: attendeeId, paymentIds (repeated), file and an optional note.
|
||||||
route.post('/payment-reports', studentSession, async (c) => {
|
route.post('/payment-reports', studentSession, async (c) => {
|
||||||
const { accountId } = currentStudent(c);
|
const { accountId } = currentStudent(c);
|
||||||
// Reject oversized bodies before buffering them (10 MB + room for the fields).
|
// Reject oversized bodies before buffering them (10 MB + room for the fields).
|
||||||
@@ -35,6 +35,7 @@ route.post('/payment-reports', studentSession, async (c) => {
|
|||||||
const attendeeId = form.get('attendeeId');
|
const attendeeId = form.get('attendeeId');
|
||||||
const paymentIds = form.getAll('paymentIds').filter((value): value is string => typeof value === 'string' && value.length > 0);
|
const paymentIds = form.getAll('paymentIds').filter((value): value is string => typeof value === 'string' && value.length > 0);
|
||||||
const file = form.get('file');
|
const file = form.get('file');
|
||||||
|
const note = form.get('note');
|
||||||
if (typeof attendeeId !== 'string' || paymentIds.length === 0 || !(file instanceof File)) {
|
if (typeof attendeeId !== 'string' || paymentIds.length === 0 || !(file instanceof File)) {
|
||||||
return problemJson(c, validationProblem({ detail: 'Elegí al menos una cuota y adjuntá el comprobante.' }));
|
return problemJson(c, validationProblem({ detail: 'Elegí al menos una cuota y adjuntá el comprobante.' }));
|
||||||
}
|
}
|
||||||
@@ -42,6 +43,7 @@ route.post('/payment-reports', studentSession, async (c) => {
|
|||||||
const result = await new ReportStudentPayment().execute(accountId, {
|
const result = await new ReportStudentPayment().execute(accountId, {
|
||||||
attendeeId,
|
attendeeId,
|
||||||
paymentIds,
|
paymentIds,
|
||||||
|
note: typeof note === 'string' ? note : null,
|
||||||
file: { name: file.name, bytes: new Uint8Array(await file.arrayBuffer()) },
|
file: { name: file.name, bytes: new Uint8Array(await file.arrayBuffer()) },
|
||||||
});
|
});
|
||||||
return resultJson(c, result, { status: 201 });
|
return resultJson(c, result, { status: 201 });
|
||||||
|
|||||||
@@ -54,6 +54,7 @@ export class GetStudentFees {
|
|||||||
status: true,
|
status: true,
|
||||||
createdAt: true,
|
createdAt: true,
|
||||||
reviewedAt: true,
|
reviewedAt: true,
|
||||||
|
note: true,
|
||||||
rejectionReason: true,
|
rejectionReason: true,
|
||||||
items: { select: { payment: { select: { id: true, description: true, dueDate: true } } } },
|
items: { select: { payment: { select: { id: true, description: true, dueDate: true } } } },
|
||||||
},
|
},
|
||||||
@@ -85,6 +86,7 @@ export class GetStudentFees {
|
|||||||
status: REPORT_STATUS[report.status],
|
status: REPORT_STATUS[report.status],
|
||||||
createdAt: report.createdAt.toISOString(),
|
createdAt: report.createdAt.toISOString(),
|
||||||
reviewedAt: report.reviewedAt?.toISOString() ?? null,
|
reviewedAt: report.reviewedAt?.toISOString() ?? null,
|
||||||
|
note: report.note,
|
||||||
rejectionReason: report.rejectionReason,
|
rejectionReason: report.rejectionReason,
|
||||||
fees: report.items.map(({ payment }) => ({
|
fees: report.items.map(({ payment }) => ({
|
||||||
id: payment.id,
|
id: payment.id,
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { randomBytes } from 'node:crypto';
|
import { randomBytes } from 'node:crypto';
|
||||||
import { Prisma, type PrismaClient } from '@generated/prisma/client';
|
import { Prisma, type PrismaClient } from '@generated/prisma/client';
|
||||||
import type { ProblemDetails, Result } from '@gruperly/shared';
|
import type { ProblemDetails, Result } from '@gruperly/shared';
|
||||||
import { err, ok } from '@gruperly/shared';
|
import { err, ok, REPORTED_PAYMENT_NOTE_MAX } from '@gruperly/shared';
|
||||||
import { conflictProblem, validationProblem } from '@/http/problem-builders';
|
import { conflictProblem, validationProblem } from '@/http/problem-builders';
|
||||||
import { detectReceiptType, RECEIPT_EXTENSIONS, RECEIPT_MAX_BYTES } from '@/lib/file-type';
|
import { detectReceiptType, RECEIPT_EXTENSIONS, RECEIPT_MAX_BYTES } from '@/lib/file-type';
|
||||||
import prisma, { UnitOfWork } from '@/lib/prisma';
|
import prisma, { UnitOfWork } from '@/lib/prisma';
|
||||||
@@ -19,6 +19,7 @@ type ReportPaymentDeps = {
|
|||||||
export type ReportPaymentInput = {
|
export type ReportPaymentInput = {
|
||||||
attendeeId: string;
|
attendeeId: string;
|
||||||
paymentIds: string[];
|
paymentIds: string[];
|
||||||
|
note?: string | null;
|
||||||
file: { name: string; bytes: Uint8Array };
|
file: { name: string; bytes: Uint8Array };
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -37,6 +38,11 @@ export class ReportStudentPayment {
|
|||||||
const attendee = await findLinkedAttendee(db, accountId, input.attendeeId);
|
const attendee = await findLinkedAttendee(db, accountId, input.attendeeId);
|
||||||
if (!attendee) return err(studentAttendeeNotFoundProblem());
|
if (!attendee) return err(studentAttendeeNotFoundProblem());
|
||||||
|
|
||||||
|
const note = input.note?.trim() || null;
|
||||||
|
if (note && note.length > REPORTED_PAYMENT_NOTE_MAX) {
|
||||||
|
return err(validationProblem({ detail: `La nota puede tener hasta ${REPORTED_PAYMENT_NOTE_MAX} caracteres.`, errors: { note: ['too_long'] } }));
|
||||||
|
}
|
||||||
|
|
||||||
if (input.file.bytes.length === 0 || input.file.bytes.length > RECEIPT_MAX_BYTES) {
|
if (input.file.bytes.length === 0 || input.file.bytes.length > RECEIPT_MAX_BYTES) {
|
||||||
return err(validationProblem({ detail: 'El comprobante tiene que pesar hasta 10 MB.', errors: { file: ['too_large'] } }));
|
return err(validationProblem({ detail: 'El comprobante tiene que pesar hasta 10 MB.', errors: { file: ['too_large'] } }));
|
||||||
}
|
}
|
||||||
@@ -83,6 +89,7 @@ export class ReportStudentPayment {
|
|||||||
receiptMime: mime,
|
receiptMime: mime,
|
||||||
receiptName: input.file.name.slice(0, 200) || `comprobante.${RECEIPT_EXTENSIONS[mime]}`,
|
receiptName: input.file.name.slice(0, 200) || `comprobante.${RECEIPT_EXTENSIONS[mime]}`,
|
||||||
receiptSize: input.file.bytes.length,
|
receiptSize: input.file.bytes.length,
|
||||||
|
note,
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
items: { create: paymentIds.map((paymentId) => ({ paymentId })) },
|
items: { create: paymentIds.map((paymentId) => ({ paymentId })) },
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { describe, expect, it } from 'bun:test';
|
import { describe, expect, it } from 'bun:test';
|
||||||
|
import { REPORTED_PAYMENT_NOTE_MAX } from '@gruperly/shared';
|
||||||
import { detectReceiptType, RECEIPT_MAX_BYTES } from '@/lib/file-type';
|
import { detectReceiptType, RECEIPT_MAX_BYTES } from '@/lib/file-type';
|
||||||
import type { FileStorage } from '@/lib/storage';
|
import type { FileStorage } from '@/lib/storage';
|
||||||
import { occurrencesBetween, startOfWeekInTimeZone } from '@/modules/home/lib/scheduler';
|
import { occurrencesBetween, startOfWeekInTimeZone } from '@/modules/home/lib/scheduler';
|
||||||
@@ -45,6 +46,15 @@ describe('tipo real del comprobante (magic bytes)', () => {
|
|||||||
const noStorage = new ReportStudentPayment({ db: db as never, storage: null });
|
const noStorage = new ReportStudentPayment({ db: db as never, storage: null });
|
||||||
const unavailable = await noStorage.execute('acc', { attendeeId: 'a1', paymentIds: ['p1'], file: { name: 'a.pdf', bytes: pad(ascii('%PDF-1.7')) } });
|
const unavailable = await noStorage.execute('acc', { attendeeId: 'a1', paymentIds: ['p1'], file: { name: 'a.pdf', bytes: pad(ascii('%PDF-1.7')) } });
|
||||||
expect(!unavailable.ok && unavailable.error.status).toBe(503);
|
expect(!unavailable.ok && unavailable.error.status).toBe(503);
|
||||||
|
|
||||||
|
const longNote = await useCase.execute('acc', {
|
||||||
|
attendeeId: 'a1',
|
||||||
|
paymentIds: ['p1'],
|
||||||
|
note: 'x'.repeat(REPORTED_PAYMENT_NOTE_MAX + 1),
|
||||||
|
file: { name: 'a.pdf', bytes: pad(ascii('%PDF-1.7')) },
|
||||||
|
});
|
||||||
|
expect(!longNote.ok && longNote.error.errors).toEqual({ note: ['too_long'] });
|
||||||
|
expect(puts).toEqual([]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -116,6 +116,13 @@ export function ReportedPaymentCard({ report, onOpenReceipt, onConfirm, onReject
|
|||||||
<ChevronRight className="size-4 shrink-0 text-foreground" aria-hidden="true" />
|
<ChevronRight className="size-4 shrink-0 text-foreground" aria-hidden="true" />
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
|
{report.note ? (
|
||||||
|
<p className="mt-3 whitespace-pre-line break-words rounded-xl border border-border px-3 py-2 text-sm text-primary">
|
||||||
|
<span className="block text-xs font-medium text-secondary">Nota del alumno</span>
|
||||||
|
{report.note}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
|
||||||
{rejecting ? (
|
{rejecting ? (
|
||||||
<form
|
<form
|
||||||
className="mt-3 space-y-2"
|
className="mt-3 space-y-2"
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { Link } from '@tanstack/react-router'
|
import { Link } from '@tanstack/react-router'
|
||||||
import { ArrowLeft, Info, Loader2 } from 'lucide-react'
|
import { ArrowLeft, Info, Loader2 } from 'lucide-react'
|
||||||
import { Button } from '../../components/ui'
|
import { REPORTED_PAYMENT_NOTE_MAX } from '@gruperly/shared'
|
||||||
|
import { Button, Label } from '../../components/ui'
|
||||||
import { ApiError } from '../../lib/api'
|
import { ApiError } from '../../lib/api'
|
||||||
import { formatPrice } from '../../lib/format'
|
import { formatPrice } from '../../lib/format'
|
||||||
import { FeeStatusBadge } from './FeeStatusBadge'
|
import { FeeStatusBadge } from './FeeStatusBadge'
|
||||||
@@ -17,6 +18,7 @@ export function ReportPaymentView() {
|
|||||||
const { student, fees, reportPayment } = useStudentApp()
|
const { student, fees, reportPayment } = useStudentApp()
|
||||||
const [selected, setSelected] = useState<string[] | null>(null)
|
const [selected, setSelected] = useState<string[] | null>(null)
|
||||||
const [file, setFile] = useState<File | null>(null)
|
const [file, setFile] = useState<File | null>(null)
|
||||||
|
const [note, setNote] = useState('')
|
||||||
|
|
||||||
if (!student || !fees) {
|
if (!student || !fees) {
|
||||||
return (
|
return (
|
||||||
@@ -51,7 +53,7 @@ export function ReportPaymentView() {
|
|||||||
|
|
||||||
const submit = () => {
|
const submit = () => {
|
||||||
if (chosen.length === 0 || !file) return
|
if (chosen.length === 0 || !file) return
|
||||||
reportPayment.mutate({ paymentIds: chosen, file })
|
reportPayment.mutate({ paymentIds: chosen, note: note.trim() || null, file })
|
||||||
}
|
}
|
||||||
|
|
||||||
const errorText =
|
const errorText =
|
||||||
@@ -106,6 +108,19 @@ export function ReportPaymentView() {
|
|||||||
<ReceiptDropzone file={file} onChange={setFile} />
|
<ReceiptDropzone file={file} onChange={setFile} />
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label htmlFor="report-note">Nota para {teacher} (opcional)</Label>
|
||||||
|
<textarea
|
||||||
|
id="report-note"
|
||||||
|
value={note}
|
||||||
|
onChange={(event) => setNote(event.target.value)}
|
||||||
|
maxLength={REPORTED_PAYMENT_NOTE_MAX}
|
||||||
|
rows={3}
|
||||||
|
placeholder="Ej.: pagué desde la cuenta de mi mamá"
|
||||||
|
className="w-full rounded-xl border border-border bg-surface px-3 py-2 text-base text-primary placeholder:text-foreground/50 focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30 sm:text-sm"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
<p className="flex gap-2 text-xs text-secondary">
|
<p className="flex gap-2 text-xs text-secondary">
|
||||||
<Info className="mt-0.5 size-4 shrink-0" aria-hidden="true" />
|
<Info className="mt-0.5 size-4 shrink-0" aria-hidden="true" />
|
||||||
{teacher} va a confirmar el pago. Mientras tanto figura como Informado.
|
{teacher} va a confirmar el pago. Mientras tanto figura como Informado.
|
||||||
|
|||||||
@@ -87,7 +87,7 @@ function useCancelAbsence(attendeeId: string | null) {
|
|||||||
function useReportPayment(attendeeId: string | null) {
|
function useReportPayment(attendeeId: string | null) {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (input: { paymentIds: string[]; file: File }) =>
|
mutationFn: (input: { paymentIds: string[]; note: string | null; file: File }) =>
|
||||||
reportStudentPayment({ ...input, attendeeId: attendeeId ?? '' }),
|
reportStudentPayment({ ...input, attendeeId: attendeeId ?? '' }),
|
||||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['student', 'fees', attendeeId] }),
|
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['student', 'fees', attendeeId] }),
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -100,6 +100,9 @@ export function StudentPaymentsView() {
|
|||||||
<Badge variant={REPORT_BADGE[report.status].variant}>{REPORT_BADGE[report.status].label}</Badge>
|
<Badge variant={REPORT_BADGE[report.status].variant}>{REPORT_BADGE[report.status].label}</Badge>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
{report.note ? (
|
||||||
|
<p className="mt-2 whitespace-pre-line break-words text-xs text-secondary">Tu nota: {report.note}</p>
|
||||||
|
) : null}
|
||||||
{report.status === 'rejected' && report.rejectionReason ? (
|
{report.status === 'rejected' && report.rejectionReason ? (
|
||||||
<p className="mt-2 rounded-lg bg-danger-soft px-3 py-2 text-xs text-primary">Motivo: {report.rejectionReason}</p>
|
<p className="mt-2 rounded-lg bg-danger-soft px-3 py-2 text-xs text-primary">Motivo: {report.rejectionReason}</p>
|
||||||
) : null}
|
) : null}
|
||||||
|
|||||||
@@ -507,10 +507,11 @@ export const cancelStudentAbsence = (noticeId: string) =>
|
|||||||
export const getStudentFees = (attendeeId: string) =>
|
export const getStudentFees = (attendeeId: string) =>
|
||||||
apiFetch<StudentFeesDto>(`${STUDENT_API}/fees?attendeeId=${encodeURIComponent(attendeeId)}`)
|
apiFetch<StudentFeesDto>(`${STUDENT_API}/fees?attendeeId=${encodeURIComponent(attendeeId)}`)
|
||||||
|
|
||||||
export const reportStudentPayment = (payload: { attendeeId: string; paymentIds: string[]; file: File }) => {
|
export const reportStudentPayment = (payload: { attendeeId: string; paymentIds: string[]; note?: string | null; file: File }) => {
|
||||||
const form = new FormData()
|
const form = new FormData()
|
||||||
form.set('attendeeId', payload.attendeeId)
|
form.set('attendeeId', payload.attendeeId)
|
||||||
for (const id of payload.paymentIds) form.append('paymentIds', id)
|
for (const id of payload.paymentIds) form.append('paymentIds', id)
|
||||||
|
if (payload.note) form.set('note', payload.note)
|
||||||
form.set('file', payload.file)
|
form.set('file', payload.file)
|
||||||
return apiFetch<{ id: string }>(`${STUDENT_API}/payment-reports`, { method: 'POST', body: form })
|
return apiFetch<{ id: string }>(`${STUDENT_API}/payment-reports`, { method: 'POST', body: form })
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -194,6 +194,7 @@ export const StudentPaymentReportSchema = z.object({
|
|||||||
status: reportedPaymentStatusSchema,
|
status: reportedPaymentStatusSchema,
|
||||||
createdAt: isoDateTimeSchema,
|
createdAt: isoDateTimeSchema,
|
||||||
reviewedAt: isoDateTimeSchema.nullable(),
|
reviewedAt: isoDateTimeSchema.nullable(),
|
||||||
|
note: z.string().nullable(),
|
||||||
rejectionReason: z.string().nullable(),
|
rejectionReason: z.string().nullable(),
|
||||||
fees: z.array(z.object({ id: z.string(), description: z.string().nullable(), dueDate: isoDateTimeSchema })),
|
fees: z.array(z.object({ id: z.string(), description: z.string().nullable(), dueDate: isoDateTimeSchema })),
|
||||||
});
|
});
|
||||||
@@ -216,6 +217,8 @@ export const StudentFeesDtoSchema = z.object({
|
|||||||
export type StudentFeesDto = z.output<typeof StudentFeesDtoSchema>;
|
export type StudentFeesDto = z.output<typeof StudentFeesDtoSchema>;
|
||||||
|
|
||||||
export const RECEIPT_MAX_MB = 10;
|
export const RECEIPT_MAX_MB = 10;
|
||||||
|
/** Max length of the optional note the student adds to a reported payment. */
|
||||||
|
export const REPORTED_PAYMENT_NOTE_MAX = 500;
|
||||||
export const RECEIPT_ACCEPT = 'image/jpeg,image/png,image/webp,image/heic,image/heif,application/pdf';
|
export const RECEIPT_ACCEPT = 'image/jpeg,image/png,image/webp,image/heic,image/heif,application/pdf';
|
||||||
|
|
||||||
// — Teacher side: reported payments to verify —
|
// — Teacher side: reported payments to verify —
|
||||||
@@ -228,6 +231,8 @@ export const ReportedPaymentDtoSchema = z.object({
|
|||||||
createdAt: isoDateTimeSchema,
|
createdAt: isoDateTimeSchema,
|
||||||
totalAmount: z.number(),
|
totalAmount: z.number(),
|
||||||
currency: z.string(),
|
currency: z.string(),
|
||||||
|
/** Optional message from the student. */
|
||||||
|
note: z.string().nullable(),
|
||||||
fees: z.array(
|
fees: z.array(
|
||||||
z.object({
|
z.object({
|
||||||
id: z.string(),
|
id: z.string(),
|
||||||
|
|||||||
Reference in New Issue
Block a user