manicanldes-backend/src/procurement/supplier-payment.store.ts

172 lines
5.5 KiB
TypeScript

import { Injectable } from '@nestjs/common';
import { AppError } from '../common/errors/app-error';
import { commandHash } from '../common/idempotency';
import { DatabaseService } from '../database/database.service';
import { AccessStore } from '../identity/access.store';
import { recordAudit } from '../identity/audit';
import type { PageInput } from '../identity/identity.schemas';
import type { Principal } from '../identity/identity.types';
import { assertCanPay, paymentBalance } from './supplier-payment-money';
import type {
SupplierPaymentInput,
SupplierPaymentReversalInput,
} from './supplier-payment.schemas';
const paymentView = { reversal: true };
const activePayments = (organizationId: string, invoiceId: string) => ({
organizationId,
invoiceId,
reversal: { is: null },
});
const requestHash = (invoiceId: string, input: SupplierPaymentInput) =>
commandHash(
invoiceId,
input.reference,
input.method,
input.amount,
input.paidDate.toISOString().slice(0, 10),
);
@Injectable()
export class SupplierPaymentStore {
constructor(
private readonly db: DatabaseService,
private readonly access: AccessStore,
) {}
async list(actor: Principal, invoiceId: string, query: PageInput) {
const invoice = await this.db.supplierInvoice.findFirst({
where: { id: invoiceId, organizationId: actor.organizationId },
});
if (!invoice) throw new AppError('INVOICE_NOT_FOUND');
const [sum, payments] = await Promise.all([
this.db.supplierPayment.aggregate({
where: activePayments(actor.organizationId, invoiceId),
_sum: { amount: true },
}),
this.db.supplierPayment.findMany({
where: { organizationId: actor.organizationId, invoiceId },
include: paymentView,
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
take: query.limit,
skip: query.offset,
}),
]);
return {
invoiceId,
currency: invoice.currency,
payableTotal: invoice.payableTotal.toFixed(2),
...paymentBalance(
invoice.payableTotal.toFixed(2),
sum._sum.amount?.toFixed(2) ?? '0.00',
),
payments,
};
}
async find(actor: Principal, id: string) {
const payment = await this.db.supplierPayment.findFirst({
where: { id, organizationId: actor.organizationId },
include: paymentView,
});
if (!payment) throw new AppError('PAYMENT_NOT_FOUND');
return payment;
}
create(actor: Principal, invoiceId: string, input: SupplierPaymentInput) {
return this.access.mutate(actor, 'supplier_payment.manage', async (tx) => {
const hash = requestHash(invoiceId, input);
const replay = await tx.supplierPayment.findUnique({
where: {
organizationId_idempotencyKey: {
organizationId: actor.organizationId,
idempotencyKey: input.idempotencyKey,
},
},
include: paymentView,
});
if (replay) {
if (replay.requestHash !== hash)
throw new AppError('PAYMENT_REPLAY_CONFLICT');
return replay;
}
const invoice = await tx.supplierInvoice.findFirst({
where: { id: invoiceId, organizationId: actor.organizationId },
include: { void: true },
});
if (!invoice) throw new AppError('INVOICE_NOT_FOUND');
if (invoice.void) throw new AppError('PAYMENT_INVOICE_VOID');
const duplicate = await tx.supplierPayment.findFirst({
where: {
organizationId: actor.organizationId,
reference: input.reference,
},
select: { id: true },
});
if (duplicate) throw new AppError('PAYMENT_REFERENCE_CONFLICT');
const sum = await tx.supplierPayment.aggregate({
where: activePayments(actor.organizationId, invoiceId),
_sum: { amount: true },
});
assertCanPay(
invoice.payableTotal.toFixed(2),
sum._sum.amount?.toFixed(2) ?? '0.00',
input.amount,
);
const payment = await tx.supplierPayment.create({
data: {
organizationId: actor.organizationId,
invoiceId,
createdById: actor.userId,
idempotencyKey: input.idempotencyKey,
requestHash: hash,
reference: input.reference,
method: input.method,
currency: invoice.currency,
amount: input.amount,
paidAt: input.paidDate,
},
include: paymentView,
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'supplier_payment.recorded',
payment.id,
);
return payment;
});
}
reverse(actor: Principal, id: string, input: SupplierPaymentReversalInput) {
return this.access.mutate(actor, 'supplier_payment.manage', async (tx) => {
const payment = await tx.supplierPayment.findFirst({
where: { id, organizationId: actor.organizationId },
include: paymentView,
});
if (!payment) throw new AppError('PAYMENT_NOT_FOUND');
if (payment.reversal) throw new AppError('PAYMENT_ALREADY_REVERSED');
await tx.supplierPaymentReversal.create({
data: {
paymentId: id,
organizationId: actor.organizationId,
reversedById: actor.userId,
reason: input.reason,
},
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'supplier_payment.reversed',
id,
);
return tx.supplierPayment.findUniqueOrThrow({
where: { id },
include: paymentView,
});
});
}
}