From df0381e2bf354cf9bb7263df37fe126783d34377 Mon Sep 17 00:00:00 2001 From: Anish Mehta Date: Wed, 18 Nov 2026 15:06:06 +0530 Subject: [PATCH 1/2] fix(fees): settle only pending payments for their own order, and pay only what is owed Verification now settles a payment only while it is PENDING (conditional update), only for the order it was created for, and never flips a completed payment to FAILED. Orders refuse draft and void invoices, charge the balance still owed, and take only online methods. The invoice becomes PAID once its completed payments cover it. Invoice and receipt numbers can no longer clash, a reused Razorpay payment id is a 409, and bad fee input is a 400. Also pins a timing-dependent announcement test to a fixed time. --- .../announcements.service.spec.ts | 3 +- apps/api/src/fees/fees.dto.ts | 40 +++--- apps/api/src/fees/fees.service.spec.ts | 127 +++++++++++++++++- apps/api/src/fees/fees.service.ts | 107 ++++++++++----- apps/web/src/app/dashboard/fees/page.tsx | 15 ++- docs/api.md | 11 ++ 6 files changed, 240 insertions(+), 63 deletions(-) diff --git a/apps/api/src/announcements/announcements.service.spec.ts b/apps/api/src/announcements/announcements.service.spec.ts index 7a3cc22..978f42c 100644 --- a/apps/api/src/announcements/announcements.service.spec.ts +++ b/apps/api/src/announcements/announcements.service.spec.ts @@ -48,7 +48,8 @@ function setup() { findUniqueOrThrow: jest.fn().mockImplementation(({ where }: { where: { id: string } }) => Promise.resolve(rows.get(where.id) ?? stored({ id: where.id }))), updateMany: jest.fn().mockResolvedValue({ count: 1 }), findFirst: jest.fn().mockResolvedValue(stored({ notifiedAt: new Date('2026-11-18T09:00:00Z'), publishedAt: new Date('2026-11-18T09:00:00Z') })), - findFirstOrThrow: jest.fn().mockImplementation(() => Promise.resolve(stored({ notifiedAt: new Date() }))), + // A fixed past time: a fresh new Date() here could land a millisecond after the service's own clock and read as scheduled. + findFirstOrThrow: jest.fn().mockImplementation(() => Promise.resolve(stored({ notifiedAt: new Date('2026-11-18T09:00:00Z'), publishedAt: new Date('2026-11-18T09:00:00Z') }))), }, enrollment: { findMany: jest.fn().mockResolvedValue([place('sec-a', 3, 'dept-cse')]) }, class: { findMany: jest.fn().mockResolvedValue([place('sec-b', 5, 'dept-cse')]) }, diff --git a/apps/api/src/fees/fees.dto.ts b/apps/api/src/fees/fees.dto.ts index 42f8edf..8307697 100644 --- a/apps/api/src/fees/fees.dto.ts +++ b/apps/api/src/fees/fees.dto.ts @@ -1,5 +1,14 @@ +import { BadRequestException } from '@nestjs/common'; import { InvoiceStatus, PaymentMethod } from '@prisma/client'; +/** Bad input is the client's mistake: a 400 with the reason, not a plain Error that surfaced as a 500. */ +function invalid(message: string): never { + throw new BadRequestException({ code: 'INVALID_INPUT', message }); +} + +/** Methods Razorpay can take online. Cash and bank transfers are paid at the accounts office, not through an order. */ +export const ONLINE_METHODS: PaymentMethod[] = [PaymentMethod.ONLINE, PaymentMethod.UPI, PaymentMethod.CARD]; + export type CreateFeeStructureDto = { name: string; amount: number; @@ -40,16 +49,16 @@ export function parseCreateFeeStructureDto(body: unknown): CreateFeeStructureDto const b = (body ?? {}) as Record; if (typeof b.name !== 'string' || !b.name.trim()) { - throw new Error('Fee structure name is required'); + invalid('Fee structure name is required'); } const amount = Number(b.amount); if (isNaN(amount) || amount <= 0) { - throw new Error('amount must be a positive number'); + invalid('amount must be a positive number'); } if (typeof b.activeFrom !== 'string' || isNaN(Date.parse(b.activeFrom))) { - throw new Error('Valid activeFrom date is required'); + invalid('Valid activeFrom date is required'); } let activeUntil: string | undefined; @@ -72,12 +81,12 @@ export function parseCreateInvoiceDto(body: unknown): CreateInvoiceDto { const b = (body ?? {}) as Record; if (typeof b.studentId !== 'string' || !b.studentId.trim()) { - throw new Error('studentId is required'); + invalid('studentId is required'); } const amountDue = Number(b.amountDue); if (isNaN(amountDue) || amountDue <= 0) { - throw new Error('amountDue must be a positive number'); + invalid('amountDue must be a positive number'); } let dueOn: string | undefined; @@ -97,15 +106,14 @@ export function parseCreateRazorpayOrderDto(body: unknown): CreateRazorpayOrderD const b = (body ?? {}) as Record; if (typeof b.invoiceId !== 'string' || !b.invoiceId.trim()) { - throw new Error('invoiceId is required'); + invalid('invoiceId is required'); } let method: PaymentMethod = PaymentMethod.ONLINE; - if (typeof b.method === 'string') { - const m = b.method.toUpperCase(); - if (Object.values(PaymentMethod).includes(m as PaymentMethod)) { - method = m as PaymentMethod; - } + if (b.method !== undefined && b.method !== null && b.method !== '') { + const m = typeof b.method === 'string' ? b.method.toUpperCase() : ''; + if (!ONLINE_METHODS.includes(m as PaymentMethod)) invalid('An online payment must use ONLINE, UPI or CARD.'); + method = m as PaymentMethod; } return { @@ -118,16 +126,16 @@ export function parseVerifyRazorpayPaymentDto(body: unknown): VerifyRazorpayPaym const b = (body ?? {}) as Record; if (typeof b.paymentId !== 'string' || !b.paymentId.trim()) { - throw new Error('paymentId is required'); + invalid('paymentId is required'); } if (typeof b.razorpayOrderId !== 'string' || !b.razorpayOrderId.trim()) { - throw new Error('razorpayOrderId is required'); + invalid('razorpayOrderId is required'); } if (typeof b.razorpayPaymentId !== 'string' || !b.razorpayPaymentId.trim()) { - throw new Error('razorpayPaymentId is required'); + invalid('razorpayPaymentId is required'); } if (typeof b.razorpaySignature !== 'string' || !b.razorpaySignature.trim()) { - throw new Error('razorpaySignature is required'); + invalid('razorpaySignature is required'); } return { @@ -144,7 +152,7 @@ export function parseFeesListQuery(query: unknown): FeesListQuery { const pageSize = q.pageSize ? Number(q.pageSize) : 20; if (!Number.isInteger(page) || page < 1 || !Number.isInteger(pageSize) || pageSize < 1 || pageSize > 100) { - throw new Error('Invalid pagination parameters'); + invalid('Invalid pagination parameters'); } let status: InvoiceStatus | undefined; diff --git a/apps/api/src/fees/fees.service.spec.ts b/apps/api/src/fees/fees.service.spec.ts index 9731b54..baa25de 100644 --- a/apps/api/src/fees/fees.service.spec.ts +++ b/apps/api/src/fees/fees.service.spec.ts @@ -1,5 +1,5 @@ import { createHmac } from 'node:crypto'; -import { BadRequestException, ForbiddenException, NotFoundException, ServiceUnavailableException } from '@nestjs/common'; +import { BadRequestException, ConflictException, ForbiddenException, NotFoundException, ServiceUnavailableException } from '@nestjs/common'; import { InvoiceStatus, PaymentStatus } from '@prisma/client'; import { FeesService } from './fees.service'; import type { AuthorizationContext } from '../authorization/authorization.types'; @@ -7,6 +7,8 @@ import type { DatabaseService } from '../database.service'; import { parseCreateFeeStructureDto, parseCreateInvoiceDto, + parseCreateRazorpayOrderDto, + parseFeesListQuery, parseVerifyRazorpayPaymentDto, } from './fees.dto'; @@ -26,11 +28,15 @@ describe('FeesService', () => { findMany: jest.fn(), count: jest.fn(), update: jest.fn(), + updateMany: jest.fn().mockResolvedValue({ count: 1 }), }, payment: { create: jest.fn(), findFirst: jest.fn(), update: jest.fn(), + updateMany: jest.fn().mockResolvedValue({ count: 1 }), + aggregate: jest.fn().mockResolvedValue({ _sum: { amount: null } }), + findUniqueOrThrow: jest.fn().mockResolvedValue({ id: 'pay-1', status: PaymentStatus.COMPLETED }), }, receipt: { create: jest.fn(), @@ -141,6 +147,8 @@ describe('FeesService', () => { invoiceId: 'inv-1', amount: 25000, status: PaymentStatus.PENDING, + transactionRef: 'order_123', + invoice: { amountDue: 25000 }, }); const dto = parseVerifyRazorpayPaymentDto({ @@ -151,10 +159,12 @@ describe('FeesService', () => { }); await expect(service.verifyRazorpayPayment(dto, studentContext)).rejects.toThrow(BadRequestException); - expect(database.payment.update).toHaveBeenCalledWith({ - where: { id: 'pay-1' }, + // Failed only while still pending. + expect(database.payment.updateMany).toHaveBeenCalledWith({ + where: { id: 'pay-1', collegeId: 'col-a', status: PaymentStatus.PENDING }, data: { status: PaymentStatus.FAILED }, }); + expect(database.receipt.create).not.toHaveBeenCalled(); }); it('settles payment and generates receipt on valid test signature', async () => { @@ -164,7 +174,10 @@ describe('FeesService', () => { invoiceId: 'inv-1', amount: 25000, status: PaymentStatus.PENDING, + transactionRef: 'order_123', + invoice: { amountDue: 25000 }, }); + database.payment.aggregate.mockResolvedValueOnce({ _sum: { amount: 25000 } }); database.payment.update.mockResolvedValue({ id: 'pay-1', status: PaymentStatus.COMPLETED, @@ -190,6 +203,101 @@ describe('FeesService', () => { expect(result.success).toBe(true); expect(result.receipt).toHaveProperty('id', 'rec-1'); + expect(database.payment.updateMany).toHaveBeenCalledWith({ + where: { id: 'pay-1', collegeId: 'col-a', status: PaymentStatus.PENDING }, + data: { status: PaymentStatus.COMPLETED, transactionRef: 'pay_rzp_123', paidAt: expect.any(Date) }, + }); + expect(database.invoice.update).toHaveBeenCalledWith({ where: { id: 'inv-1' }, data: { status: InvoiceStatus.PAID } }); + expect(database.receipt.create).toHaveBeenCalledWith({ + data: expect.objectContaining({ paymentId: 'pay-1', receiptNumber: expect.stringMatching(/^REC-\d{4}-[0-9A-F]{10}$/) }), + }); + }); + }); + + describe('payment rules', () => { + const pending = { id: 'pay-1', collegeId: 'col-a', invoiceId: 'inv-1', amount: 15000, status: PaymentStatus.PENDING, transactionRef: 'order_1', invoice: { amountDue: 25000 } }; + const verify = (overrides: Record = {}) => + parseVerifyRazorpayPaymentDto({ paymentId: 'pay-1', razorpayOrderId: 'order_1', razorpayPaymentId: 'pay_rzp_1', razorpaySignature: 'test_sig_pay_rzp_1', ...overrides }); + beforeEach(() => database.student.findFirst.mockResolvedValue({ id: 'stu-1' })); + + it.each([InvoiceStatus.DRAFT, InvoiceStatus.VOID])('refuses an order for a %s invoice', async (status) => { + database.invoice.findFirst.mockResolvedValue({ id: 'inv-1', status, amountDue: 25000, invoiceNumber: 'INV-1' }); + await expect(service.createRazorpayOrder({ invoiceId: 'inv-1' }, studentContext)).rejects.toMatchObject({ response: { code: 'INVOICE_NOT_PAYABLE' } }); + expect(database.payment.create).not.toHaveBeenCalled(); + }); + + it('orders only what is still owed after a part payment', async () => { + database.invoice.findFirst.mockResolvedValue({ id: 'inv-1', status: InvoiceStatus.PARTIALLY_PAID, amountDue: 25000, invoiceNumber: 'INV-1' }); + database.payment.aggregate.mockResolvedValueOnce({ _sum: { amount: 10000 } }); + database.payment.create.mockResolvedValue({ id: 'pay-1' }); + await expect(service.createRazorpayOrder({ invoiceId: 'inv-1' }, studentContext)).resolves.toMatchObject({ amount: 15000 }); + expect(database.payment.aggregate).toHaveBeenCalledWith({ where: { collegeId: 'col-a', invoiceId: 'inv-1', status: PaymentStatus.COMPLETED }, _sum: { amount: true } }); + expect(database.payment.create).toHaveBeenCalledWith({ data: expect.objectContaining({ amount: 15000, status: PaymentStatus.PENDING }) }); + }); + + it('refuses an order when the payments already cover the invoice', async () => { + database.invoice.findFirst.mockResolvedValue({ id: 'inv-1', status: InvoiceStatus.ISSUED, amountDue: 25000, invoiceNumber: 'INV-1' }); + database.payment.aggregate.mockResolvedValueOnce({ _sum: { amount: 25000 } }); + await expect(service.createRazorpayOrder({ invoiceId: 'inv-1' }, studentContext)).rejects.toMatchObject({ response: { code: 'INVOICE_ALREADY_PAID' } }); + expect(database.payment.create).not.toHaveBeenCalled(); + }); + + it.each([PaymentStatus.COMPLETED, PaymentStatus.FAILED])('never changes a %s payment, whatever the signature', async (status) => { + database.payment.findFirst.mockResolvedValue({ ...pending, status }); + await expect(service.verifyRazorpayPayment(verify(), studentContext)).rejects.toMatchObject({ response: { code: 'PAYMENT_NOT_PENDING' } }); + await expect(service.verifyRazorpayPayment(verify({ razorpaySignature: 'bad' }), studentContext)).rejects.toBeInstanceOf(ConflictException); + expect(database.payment.updateMany).not.toHaveBeenCalled(); + expect(database.receipt.create).not.toHaveBeenCalled(); + }); + + it('refuses a signature for a different order', async () => { + database.payment.findFirst.mockResolvedValue(pending); + await expect(service.verifyRazorpayPayment(verify({ razorpayOrderId: 'order_other' }), studentContext)).rejects.toMatchObject({ response: { code: 'ORDER_MISMATCH' } }); + expect(database.payment.updateMany).not.toHaveBeenCalled(); + }); + + it('settles a payment once even if two verifications race', async () => { + database.payment.findFirst.mockResolvedValue(pending); + database.payment.updateMany.mockResolvedValueOnce({ count: 0 }); + await expect(service.verifyRazorpayPayment(verify(), studentContext)).rejects.toMatchObject({ response: { code: 'PAYMENT_NOT_PENDING' } }); + expect(database.invoice.update).not.toHaveBeenCalled(); + expect(database.receipt.create).not.toHaveBeenCalled(); + }); + + it('refuses a Razorpay payment id that was already recorded for another order', async () => { + database.payment.findFirst.mockResolvedValue(pending); + database.payment.updateMany.mockRejectedValueOnce({ code: 'P2002', meta: { target: ['collegeId', 'transactionRef'] } }); + await expect(service.verifyRazorpayPayment(verify(), studentContext)).rejects.toMatchObject({ response: { code: 'PAYMENT_ALREADY_RECORDED' } }); + expect(database.receipt.create).not.toHaveBeenCalled(); + }); + + it('marks the invoice partly paid while money is still owed', async () => { + database.payment.findFirst.mockResolvedValue(pending); + database.payment.aggregate.mockResolvedValueOnce({ _sum: { amount: 15000 } }); + database.receipt.create.mockResolvedValue({ id: 'rec-1' }); + await expect(service.verifyRazorpayPayment(verify(), studentContext)).resolves.toMatchObject({ success: true }); + // The invoice row is locked before its payments are added up. + expect(database.invoice.updateMany).toHaveBeenCalledWith({ where: { id: 'inv-1', collegeId: 'col-a' }, data: { updatedAt: expect.any(Date) } }); + expect(database.invoice.update).toHaveBeenCalledWith({ where: { id: 'inv-1' }, data: { status: InvoiceStatus.PARTIALLY_PAID } }); + }); + + it('gives bad input a 400 and takes only online methods for an order', () => { + expect(() => parseCreateRazorpayOrderDto({})).toThrow(BadRequestException); + expect(() => parseCreateRazorpayOrderDto({ invoiceId: 'inv-1', method: 'CASH' })).toThrow(BadRequestException); + expect(() => parseCreateRazorpayOrderDto({ invoiceId: 'inv-1', method: 'bank_transfer' })).toThrow(BadRequestException); + expect(parseCreateRazorpayOrderDto({ invoiceId: 'inv-1', method: 'upi' })).toEqual({ invoiceId: 'inv-1', method: 'UPI' }); + expect(parseCreateRazorpayOrderDto({ invoiceId: 'inv-1' })).toEqual({ invoiceId: 'inv-1', method: 'ONLINE' }); + expect(() => parseVerifyRazorpayPaymentDto({ paymentId: 'pay-1' })).toThrow(BadRequestException); + expect(() => parseCreateInvoiceDto({ studentId: 'stu-1', amountDue: -5 })).toThrow(BadRequestException); + expect(() => parseCreateFeeStructureDto({ name: '', amount: 1, activeFrom: '2026-01-01' })).toThrow(BadRequestException); + expect(() => parseFeesListQuery({ page: 'abc' })).toThrow(BadRequestException); + }); + + it('numbers invoices so that a clash is practically impossible', async () => { + database.student.findFirst.mockResolvedValue({ id: 'stu-1' }); + database.invoice.create.mockResolvedValue({ id: 'inv-9' }); + await service.createInvoice(parseCreateInvoiceDto({ studentId: 'stu-1', amountDue: 1000 }), admin); + expect(database.invoice.create).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ invoiceNumber: expect.stringMatching(/^INV-\d{4}-[0-9A-F]{10}$/) }) })); }); }); }); @@ -230,8 +338,15 @@ describe('FeesService access and payment checks', () => { const hod: AuthorizationContext = { userId: 'hod-1', collegeId: 'col-a', roles: ['HOD'], permissions: [], departmentId: 'dept-a' }; const database = { student: { findFirst: jest.fn().mockResolvedValue({ id: 'stu-1' }) }, - invoice: { findFirst: jest.fn(), update: jest.fn() }, - payment: { create: jest.fn().mockResolvedValue({ id: 'pay-1' }), findFirst: jest.fn(), update: jest.fn() }, + invoice: { findFirst: jest.fn(), update: jest.fn(), updateMany: jest.fn() }, + payment: { + create: jest.fn().mockResolvedValue({ id: 'pay-1' }), + findFirst: jest.fn(), + update: jest.fn(), + updateMany: jest.fn().mockResolvedValue({ count: 1 }), + aggregate: jest.fn().mockResolvedValue({ _sum: { amount: null } }), + findUniqueOrThrow: jest.fn().mockResolvedValue({ id: 'pay-1' }), + }, receipt: { findFirst: jest.fn(), create: jest.fn() }, feeStructure: { create: jest.fn() }, $transaction: jest.fn(), @@ -261,7 +376,7 @@ describe('FeesService access and payment checks', () => { it('rejects the simulated signature once a real secret is configured, and accepts the real one', async () => { process.env.RAZORPAY_KEY_SECRET = 'real-secret'; - database.payment.findFirst.mockResolvedValue({ id: 'pay-1', invoiceId: 'inv-1', amount: 100, status: PaymentStatus.PENDING }); + database.payment.findFirst.mockResolvedValue({ id: 'pay-1', invoiceId: 'inv-1', amount: 100, status: PaymentStatus.PENDING, transactionRef: 'order_1', invoice: { amountDue: 100 } }); await expect(service.verifyRazorpayPayment(dto('test_sig_pay_rzp_1'), studentContext)).rejects.toBeInstanceOf(BadRequestException); const real = createHmac('sha256', 'real-secret').update('order_1|pay_rzp_1').digest('hex'); database.receipt.findFirst.mockResolvedValue(null); diff --git a/apps/api/src/fees/fees.service.ts b/apps/api/src/fees/fees.service.ts index 1aa1bb5..c017924 100644 --- a/apps/api/src/fees/fees.service.ts +++ b/apps/api/src/fees/fees.service.ts @@ -1,6 +1,7 @@ import { BadRequestException, ConflictException, ForbiddenException, Inject, Injectable, NotFoundException, ServiceUnavailableException } from '@nestjs/common'; -import { createHmac } from 'crypto'; +import { createHmac, randomBytes } from 'crypto'; import { InvoiceStatus, PaymentMethod, PaymentStatus } from '@prisma/client'; +import type { Prisma } from '@prisma/client'; import { DatabaseService } from '../database.service'; import type { AuthorizationContext } from '../authorization/authorization.types'; import type { @@ -21,6 +22,27 @@ const invoiceMissing = (): never => { throw new NotFoundException({ code: 'INVOICE_NOT_FOUND', message: 'Invoice was not found in this college.' }); }; +/** Invoices a student can pay online: issued and not yet fully paid. Draft invoices aren't issued yet; void ones are cancelled. */ +const PAYABLE: InvoiceStatus[] = [InvoiceStatus.ISSUED, InvoiceStatus.PARTIALLY_PAID, InvoiceStatus.OVERDUE]; + +/** + * A document number such as INV-2026-3FA9C1B2D4. Ten random hex characters make a clash practically impossible, so + * the unique constraint on invoice and receipt numbers never turns a payment into a 500 (six random digits could). + */ +const documentNumber = (prefix: 'INV' | 'REC'): string => `${prefix}-${new Date().getFullYear()}-${randomBytes(5).toString('hex').toUpperCase()}`; + +const isUniqueViolation = (error: unknown): boolean => typeof error === 'object' && error !== null && 'code' in error && (error as { code?: string }).code === 'P2002'; + +const notPending = (): never => { + throw new ConflictException({ code: 'PAYMENT_NOT_PENDING', message: 'This payment has already been processed.' }); +}; + +/** What has been paid on an invoice so far: its completed payments. */ +const paidSoFar = async (client: Pick, collegeId: string, invoiceId: string): Promise => { + const paid = await client.payment.aggregate({ where: { collegeId, invoiceId, status: PaymentStatus.COMPLETED }, _sum: { amount: true } }); + return Number(paid._sum.amount ?? 0); +}; + /** Without a Razorpay secret, outside production, payments run in a test mode that accepts simulated signatures. */ const paymentsInTestMode = (): boolean => process.env.NODE_ENV !== 'production' && !process.env.RAZORPAY_KEY_SECRET; @@ -109,7 +131,7 @@ export class FeesService { throw new NotFoundException({ code: 'STUDENT_NOT_FOUND', message: 'Student profile was not found.' }); } - const invoiceNumber = `INV-${new Date().getFullYear()}-${Math.floor(100000 + Math.random() * 900000)}`; + const invoiceNumber = documentNumber('INV'); return this.database.invoice.create({ data: { @@ -229,6 +251,17 @@ export class FeesService { if (invoice.status === InvoiceStatus.PAID) { throw new BadRequestException({ code: 'INVOICE_ALREADY_PAID', message: 'Invoice has already been paid.' }); } + if (!PAYABLE.includes(invoice.status)) { + throw new ConflictException({ + code: 'INVOICE_NOT_PAYABLE', + message: invoice.status === InvoiceStatus.VOID ? 'This invoice was cancelled and cannot be paid.' : 'This invoice has not been issued yet.', + }); + } + // The order is for what is still owed, so an earlier part-payment is never charged again. + const balance = Number(invoice.amountDue) - (await paidSoFar(this.database, context.collegeId, invoice.id)); + if (balance <= 0) { + throw new BadRequestException({ code: 'INVOICE_ALREADY_PAID', message: 'Invoice has already been paid.' }); + } const razorpayOrderId = `order_${Date.now()}_${Math.floor(1000 + Math.random() * 9000)}`; @@ -236,8 +269,8 @@ export class FeesService { data: { collegeId: context.collegeId, invoiceId: invoice.id, - amount: invoice.amountDue, - method: input.method || PaymentMethod.ONLINE, + amount: balance, + method: input.method ?? PaymentMethod.ONLINE, status: PaymentStatus.PENDING, transactionRef: razorpayOrderId, }, @@ -248,7 +281,7 @@ export class FeesService { return { paymentId: payment.id, razorpayOrderId, - amount: Number(invoice.amountDue), + amount: balance, currency: 'INR', keyId, invoiceNumber: invoice.invoiceNumber, @@ -267,12 +300,18 @@ export class FeesService { if (!payment) { throw new NotFoundException({ code: 'PAYMENT_NOT_FOUND', message: 'Payment record was not found.' }); } + // Only a pending payment is settled: a completed or failed one can't be flipped by verifying it again. + if (payment.status !== PaymentStatus.PENDING) notPending(); + // The signature covers the order, so it must be the order this payment was created for. + if (input.razorpayOrderId !== payment.transactionRef) { + throw new BadRequestException({ code: 'ORDER_MISMATCH', message: 'This payment was not made for that order.' }); + } // A real Razorpay signature is checked against the configured secret. The simulated test signature is only - // accepted in test mode (outside production, with no secret configured); before, it was accepted everywhere. + // accepted in test mode (outside production, with no secret configured). const secret = process.env.RAZORPAY_KEY_SECRET; const expectedSignature = secret - ? createHmac('sha256', secret).update(`${input.razorpayOrderId}|${input.razorpayPaymentId}`).digest('hex') + ? createHmac('sha256', secret).update(`${payment.transactionRef}|${input.razorpayPaymentId}`).digest('hex') : null; const isValidSignature = @@ -280,8 +319,8 @@ export class FeesService { (paymentsInTestMode() && input.razorpaySignature === `test_sig_${input.razorpayPaymentId}`); if (!isValidSignature) { - await this.database.payment.update({ - where: { id: payment.id }, + await this.database.payment.updateMany({ + where: { id: payment.id, collegeId: context.collegeId, status: PaymentStatus.PENDING }, data: { status: PaymentStatus.FAILED }, }); throw new BadRequestException({ @@ -290,47 +329,43 @@ export class FeesService { }); } - // Mark payment completed & invoice paid in a transaction + const now = new Date(); + return this.settle(payment, input.razorpayPaymentId, now, context).catch((error: unknown) => { + // A Razorpay payment id is unique per college, so one payment can never be counted against two orders. + if (isUniqueViolation(error)) throw new ConflictException({ code: 'PAYMENT_ALREADY_RECORDED', message: 'This Razorpay payment has already been recorded.' }); + throw error; + }); + } + + /** Completes a pending payment, updates its invoice and issues the receipt, all in one transaction. */ + private settle(payment: { id: string; invoiceId: string; invoice: { amountDue: Prisma.Decimal | number } }, razorpayPaymentId: string, now: Date, context: AuthorizationContext) { return this.database.$transaction(async (tx) => { - const updatedPayment = await tx.payment.update({ - where: { id: payment.id }, - data: { - status: PaymentStatus.COMPLETED, - transactionRef: input.razorpayPaymentId, - paidAt: new Date(), - }, + // Settle it only if it is still pending, so two verifications of one payment can't both complete it. + const settled = await tx.payment.updateMany({ + where: { id: payment.id, collegeId: context.collegeId, status: PaymentStatus.PENDING }, + data: { status: PaymentStatus.COMPLETED, transactionRef: razorpayPaymentId, paidAt: now }, }); + if (settled.count !== 1) notPending(); + // Lock the invoice before adding up its payments, so two payments settling together see each other. + await tx.invoice.updateMany({ where: { id: payment.invoiceId, collegeId: context.collegeId }, data: { updatedAt: now } }); + const paid = await paidSoFar(tx, context.collegeId, payment.invoiceId); await tx.invoice.update({ where: { id: payment.invoiceId }, - data: { - status: InvoiceStatus.PAID, - }, + data: { status: paid >= Number(payment.invoice.amountDue) ? InvoiceStatus.PAID : InvoiceStatus.PARTIALLY_PAID }, }); - const existingReceipt = await tx.receipt.findFirst({ - where: { collegeId: context.collegeId, paymentId: payment.id }, + const receipt = await tx.receipt.create({ + data: { collegeId: context.collegeId, paymentId: payment.id, receiptNumber: documentNumber('REC'), issuedAt: now }, }); - - let receipt = existingReceipt; - if (!receipt) { - const receiptNumber = `REC-${new Date().getFullYear()}-${Math.floor(100000 + Math.random() * 900000)}`; - receipt = await tx.receipt.create({ - data: { - collegeId: context.collegeId, - paymentId: payment.id, - receiptNumber, - issuedAt: new Date(), - }, - }); - } + const updatedPayment = await tx.payment.findUniqueOrThrow({ where: { id: payment.id } }); return { success: true, payment: updatedPayment, receipt, }; - }); + }, { timeout: 30_000 }); } async getReceipts(context: AuthorizationContext) { diff --git a/apps/web/src/app/dashboard/fees/page.tsx b/apps/web/src/app/dashboard/fees/page.tsx index 67db1b6..f8edf3a 100644 --- a/apps/web/src/app/dashboard/fees/page.tsx +++ b/apps/web/src/app/dashboard/fees/page.tsx @@ -22,6 +22,9 @@ import type { Receipt, } from '@/lib/fees-api'; +/** Invoices that can be paid online: issued and not fully paid. Draft invoices aren't issued yet; void ones are cancelled. */ +const PAYABLE: InvoiceStatus[] = ['ISSUED', 'PARTIALLY_PAID', 'OVERDUE']; + const STATUS_COLORS: Record = { DRAFT: 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200 border-gray-300', ISSUED: 'bg-amber-100 text-amber-800 dark:bg-amber-950 dark:text-amber-200 border-amber-300', @@ -113,7 +116,7 @@ export default function FeesPage() { }); setPaymentSuccess( - `Test payment of ₹${Number(inv.amountDue).toLocaleString('en-IN')} recorded (test mode, no money was charged). Receipt Number: ${ + `Test payment of ₹${Number(order.amount).toLocaleString('en-IN')} recorded (test mode, no money was charged). Receipt Number: ${ res.receipt?.receiptNumber || 'Generated' }`, ); @@ -301,11 +304,11 @@ export default function FeesPage() { )} - {inv.status !== 'PAID' && onlinePayments && !onlinePayments.onlinePaymentsAvailable ? ( + {PAYABLE.includes(inv.status) && onlinePayments && !onlinePayments.onlinePaymentsAvailable ? (

Online payment isn't available yet. Please pay at the accounts office.

- ) : inv.status !== 'PAID' ? ( + ) : PAYABLE.includes(inv.status) ? ( - ) : ( + ) : inv.status === 'PAID' ? (
Payment Complete
+ ) : ( +

+ {inv.status === 'VOID' ? 'Cancelled: nothing to pay.' : 'Not issued yet.'} +

)} diff --git a/docs/api.md b/docs/api.md index d80a3e8..1a886e9 100644 --- a/docs/api.md +++ b/docs/api.md @@ -179,6 +179,17 @@ FACULTY responses leave out phone and address; ADMIN and HOD receive them. HOD a - POST /api/v1/fees/invoices/:id/create-razorpay-order and POST /api/v1/fees/payments/verify-razorpay: STUDENT only, for their own invoices (404 otherwise). Orders include `testMode`. - GET /api/v1/fees/payment-mode: ADMIN and STUDENT. Returns { testMode, onlinePaymentsAvailable }. The web app has no Razorpay Checkout step yet, so it only offers payment when this says it can complete; this avoids creating pending payments that can never finish. - Signature checks: a real Razorpay signature is verified against `RAZORPAY_KEY_SECRET`. The simulated `test_sig_` signature is accepted only in test mode, meaning outside production with no secret configured. In production, both endpoints return 503 PAYMENTS_NOT_CONFIGURED until `RAZORPAY_KEY_ID` and `RAZORPAY_KEY_SECRET` are set. +- Orders: + - Only an ISSUED, PARTIALLY_PAID or OVERDUE invoice can be paid. A DRAFT or VOID invoice returns 409 INVOICE_NOT_PAYABLE, and one already covered by its payments returns 400 INVOICE_ALREADY_PAID. + - The order is for the balance still owed (the amount due minus completed payments), not the whole amount again. + - `method` is optional and must be ONLINE (the default), UPI or CARD. Cash and bank transfers aren't made through an online order. +- Verification: + - Only a PENDING payment is settled. Verifying a COMPLETED or FAILED one returns 409 PAYMENT_NOT_PENDING and changes nothing. + - `razorpayOrderId` must be the order the payment was created for (400 ORDER_MISMATCH otherwise), and the signature is checked against that order. + - A bad signature marks the payment FAILED only while it is still pending. + - Settling claims the payment with a conditional update, so two verifications can't both complete it. It locks the invoice, then sets it to PAID once its completed payments cover the amount due, or PARTIALLY_PAID before that. +- Invoice and receipt numbers end in ten random hex characters (for example REC-2026-3FA9C1B2D4), so a clash with the unique number can't fail an invoice or a payment. +- Bad fee input returns 400 INVALID_INPUT with the reason, instead of a 500. ## Faculty Performance From 8aa420ad6b83b8ddb4e5d2fc2d69f63fe483ba13 Mon Sep 17 00:00:00 2001 From: Anish Mehta Date: Wed, 18 Nov 2026 15:11:42 +0530 Subject: [PATCH 2/2] fix(fees): keep one open order per invoice A second order for the same invoice, from another tab or a retry, now gets the open order back instead of a new one, so the balance can't be ordered and charged twice. Any other open order is closed, one for an out-of-date amount is replaced, and orders for an invoice are made one at a time with the invoice row locked. --- apps/api/src/fees/fees.service.spec.ts | 24 +++++++++++++ apps/api/src/fees/fees.service.ts | 50 +++++++++++++++++--------- docs/api.md | 1 + 3 files changed, 58 insertions(+), 17 deletions(-) diff --git a/apps/api/src/fees/fees.service.spec.ts b/apps/api/src/fees/fees.service.spec.ts index baa25de..2e0d5a4 100644 --- a/apps/api/src/fees/fees.service.spec.ts +++ b/apps/api/src/fees/fees.service.spec.ts @@ -229,12 +229,36 @@ describe('FeesService', () => { it('orders only what is still owed after a part payment', async () => { database.invoice.findFirst.mockResolvedValue({ id: 'inv-1', status: InvoiceStatus.PARTIALLY_PAID, amountDue: 25000, invoiceNumber: 'INV-1' }); database.payment.aggregate.mockResolvedValueOnce({ _sum: { amount: 10000 } }); + database.payment.findFirst.mockResolvedValueOnce(null); database.payment.create.mockResolvedValue({ id: 'pay-1' }); await expect(service.createRazorpayOrder({ invoiceId: 'inv-1' }, studentContext)).resolves.toMatchObject({ amount: 15000 }); expect(database.payment.aggregate).toHaveBeenCalledWith({ where: { collegeId: 'col-a', invoiceId: 'inv-1', status: PaymentStatus.COMPLETED }, _sum: { amount: true } }); expect(database.payment.create).toHaveBeenCalledWith({ data: expect.objectContaining({ amount: 15000, status: PaymentStatus.PENDING }) }); }); + it('gives a second tab the open order instead of a second one, and closes any others', async () => { + database.invoice.findFirst.mockResolvedValue({ id: 'inv-1', status: InvoiceStatus.ISSUED, amountDue: 25000, invoiceNumber: 'INV-1' }); + database.payment.findFirst.mockResolvedValueOnce({ id: 'pay-open', amount: 25000, status: PaymentStatus.PENDING, transactionRef: 'order_open' }); + await expect(service.createRazorpayOrder({ invoiceId: 'inv-1' }, studentContext)).resolves.toMatchObject({ paymentId: 'pay-open', razorpayOrderId: 'order_open', amount: 25000 }); + expect(database.payment.create).not.toHaveBeenCalled(); + // The invoice is locked first, and every other open order for it is closed. + expect(database.invoice.updateMany).toHaveBeenCalledWith({ where: { id: 'inv-1', collegeId: 'col-a' }, data: { updatedAt: expect.any(Date) } }); + expect(database.payment.updateMany).toHaveBeenCalledWith({ + where: { collegeId: 'col-a', invoiceId: 'inv-1', status: PaymentStatus.PENDING, id: { not: 'pay-open' } }, + data: { status: PaymentStatus.FAILED }, + }); + }); + + it('replaces an open order for an out-of-date amount', async () => { + database.invoice.findFirst.mockResolvedValue({ id: 'inv-1', status: InvoiceStatus.PARTIALLY_PAID, amountDue: 25000, invoiceNumber: 'INV-1' }); + database.payment.aggregate.mockResolvedValueOnce({ _sum: { amount: 10000 } }); + database.payment.findFirst.mockResolvedValueOnce({ id: 'pay-old', amount: 25000, status: PaymentStatus.PENDING, transactionRef: 'order_old' }); + database.payment.create.mockResolvedValue({ id: 'pay-new', transactionRef: 'order_new' }); + await expect(service.createRazorpayOrder({ invoiceId: 'inv-1' }, studentContext)).resolves.toMatchObject({ paymentId: 'pay-new', razorpayOrderId: 'order_new', amount: 15000 }); + expect(database.payment.updateMany).toHaveBeenCalledWith({ where: { collegeId: 'col-a', invoiceId: 'inv-1', status: PaymentStatus.PENDING }, data: { status: PaymentStatus.FAILED } }); + expect(database.payment.create).toHaveBeenCalledWith({ data: expect.objectContaining({ amount: 15000, transactionRef: expect.stringMatching(/^order_/) }) }); + }); + it('refuses an order when the payments already cover the invoice', async () => { database.invoice.findFirst.mockResolvedValue({ id: 'inv-1', status: InvoiceStatus.ISSUED, amountDue: 25000, invoiceNumber: 'INV-1' }); database.payment.aggregate.mockResolvedValueOnce({ _sum: { amount: 25000 } }); diff --git a/apps/api/src/fees/fees.service.ts b/apps/api/src/fees/fees.service.ts index c017924..aafa5ff 100644 --- a/apps/api/src/fees/fees.service.ts +++ b/apps/api/src/fees/fees.service.ts @@ -257,30 +257,46 @@ export class FeesService { message: invoice.status === InvoiceStatus.VOID ? 'This invoice was cancelled and cannot be paid.' : 'This invoice has not been issued yet.', }); } - // The order is for what is still owed, so an earlier part-payment is never charged again. - const balance = Number(invoice.amountDue) - (await paidSoFar(this.database, context.collegeId, invoice.id)); - if (balance <= 0) { - throw new BadRequestException({ code: 'INVOICE_ALREADY_PAID', message: 'Invoice has already been paid.' }); - } + const { payment, balance } = await this.database.$transaction(async (tx) => { + // Lock the invoice, so orders for it are made one at a time. + await tx.invoice.updateMany({ where: { id: invoice.id, collegeId: context.collegeId }, data: { updatedAt: new Date() } }); + // The order is for what is still owed, so an earlier part-payment is never charged again. + const owed = Number(invoice.amountDue) - (await paidSoFar(tx, context.collegeId, invoice.id)); + if (owed <= 0) { + throw new BadRequestException({ code: 'INVOICE_ALREADY_PAID', message: 'Invoice has already been paid.' }); + } - const razorpayOrderId = `order_${Date.now()}_${Math.floor(1000 + Math.random() * 9000)}`; + // One open order per invoice: a second tab or a retry gets the same order, so the balance can't be charged twice. + const open = await tx.payment.findFirst({ + where: { collegeId: context.collegeId, invoiceId: invoice.id, status: PaymentStatus.PENDING }, + orderBy: { createdAt: 'desc' }, + }); + const reuse = open && Number(open.amount) === owed ? open : null; + // Any other open order is closed: one for a different amount is out of date, because the balance has changed. + await tx.payment.updateMany({ + where: { collegeId: context.collegeId, invoiceId: invoice.id, status: PaymentStatus.PENDING, ...(reuse ? { id: { not: reuse.id } } : {}) }, + data: { status: PaymentStatus.FAILED }, + }); + if (reuse) return { payment: reuse, balance: owed }; - const payment = await this.database.payment.create({ - data: { - collegeId: context.collegeId, - invoiceId: invoice.id, - amount: balance, - method: input.method ?? PaymentMethod.ONLINE, - status: PaymentStatus.PENDING, - transactionRef: razorpayOrderId, - }, - }); + const created = await tx.payment.create({ + data: { + collegeId: context.collegeId, + invoiceId: invoice.id, + amount: owed, + method: input.method ?? PaymentMethod.ONLINE, + status: PaymentStatus.PENDING, + transactionRef: `order_${Date.now()}_${Math.floor(1000 + Math.random() * 9000)}`, + }, + }); + return { payment: created, balance: owed }; + }, { timeout: 30_000 }); const keyId = process.env.RAZORPAY_KEY_ID || 'rzp_test_campusos_demo'; return { paymentId: payment.id, - razorpayOrderId, + razorpayOrderId: payment.transactionRef, amount: balance, currency: 'INR', keyId, diff --git a/docs/api.md b/docs/api.md index 1a886e9..1599a5c 100644 --- a/docs/api.md +++ b/docs/api.md @@ -182,6 +182,7 @@ FACULTY responses leave out phone and address; ADMIN and HOD receive them. HOD a - Orders: - Only an ISSUED, PARTIALLY_PAID or OVERDUE invoice can be paid. A DRAFT or VOID invoice returns 409 INVOICE_NOT_PAYABLE, and one already covered by its payments returns 400 INVOICE_ALREADY_PAID. - The order is for the balance still owed (the amount due minus completed payments), not the whole amount again. + - An invoice has at most one open order. Asking again, for example from a second tab, returns the same order, so the balance can't be charged twice. An open order for a different amount is out of date: it is marked FAILED and replaced. Orders for one invoice are made one at a time, with the invoice row locked. - `method` is optional and must be ONLINE (the default), UPI or CARD. Cash and bank transfers aren't made through an online order. - Verification: - Only a PENDING payment is settled. Verifying a COMPLETED or FAILED one returns 409 PAYMENT_NOT_PENDING and changes nothing.