186 lines
6.4 KiB
TypeScript
186 lines
6.4 KiB
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import { AppError } from '../common/errors/app-error';
|
|
import { DatabaseService } from '../database/database.service';
|
|
import { AccessStore } from '../identity/access.store';
|
|
import { recordAudit } from '../identity/audit';
|
|
import type { Principal } from '../identity/identity.types';
|
|
import type { PageInput } from '../identity/identity.schemas';
|
|
import { invoiceLineTotal, invoiceTotals } from './supplier-invoice-money';
|
|
import type {
|
|
SupplierInvoiceInput,
|
|
SupplierInvoiceVoidInput,
|
|
} from './supplier-invoice.schemas';
|
|
import { scaled } from './purchase-order-money';
|
|
|
|
const invoiceView = { lines: { orderBy: { id: 'asc' as const } }, void: true };
|
|
const addQuantity = (totals: Map<string, bigint>, id: string, amount: string) =>
|
|
totals.set(id, (totals.get(id) ?? 0n) + scaled(amount, 3));
|
|
|
|
@Injectable()
|
|
export class SupplierInvoiceStore {
|
|
constructor(
|
|
private readonly db: DatabaseService,
|
|
private readonly access: AccessStore,
|
|
) {}
|
|
|
|
async list(actor: Principal, orderId: string, query: PageInput) {
|
|
const order = await this.db.purchaseOrder.findFirst({
|
|
where: { id: orderId, organizationId: actor.organizationId },
|
|
select: { id: true },
|
|
});
|
|
if (!order) throw new AppError('PURCHASE_ORDER_NOT_FOUND');
|
|
return this.db.supplierInvoice.findMany({
|
|
where: { organizationId: actor.organizationId, purchaseOrderId: orderId },
|
|
include: invoiceView,
|
|
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
|
take: query.limit,
|
|
skip: query.offset,
|
|
});
|
|
}
|
|
|
|
async find(actor: Principal, id: string) {
|
|
const invoice = await this.db.supplierInvoice.findFirst({
|
|
where: { id, organizationId: actor.organizationId },
|
|
include: invoiceView,
|
|
});
|
|
if (!invoice) throw new AppError('INVOICE_NOT_FOUND');
|
|
return invoice;
|
|
}
|
|
|
|
create(actor: Principal, orderId: string, input: SupplierInvoiceInput) {
|
|
return this.access.mutate(actor, 'procurement.manage', async (tx) => {
|
|
const order = await tx.purchaseOrder.findFirst({
|
|
where: { id: orderId, organizationId: actor.organizationId },
|
|
include: { lines: true },
|
|
});
|
|
if (!order) throw new AppError('PURCHASE_ORDER_NOT_FOUND');
|
|
if (order.status !== 'ISSUED') throw new AppError('INVOICE_ORDER_STATE');
|
|
const duplicate = await tx.supplierInvoice.findFirst({
|
|
where: {
|
|
organizationId: actor.organizationId,
|
|
supplierId: order.supplierId,
|
|
invoiceNumber: input.invoiceNumber,
|
|
},
|
|
select: { id: true },
|
|
});
|
|
if (duplicate) throw new AppError('INVOICE_NUMBER_CONFLICT');
|
|
const orderLines = new Map(order.lines.map((line) => [line.id, line]));
|
|
const receipts = await tx.goodsReceiptLine.findMany({
|
|
where: {
|
|
organizationId: actor.organizationId,
|
|
purchaseOrderId: orderId,
|
|
},
|
|
include: { inspection: true },
|
|
});
|
|
const accepted = new Map<string, bigint>();
|
|
for (const receipt of receipts)
|
|
if (receipt.inspection)
|
|
addQuantity(
|
|
accepted,
|
|
receipt.purchaseOrderLineId,
|
|
receipt.inspection.acceptedQuantity.toFixed(3),
|
|
);
|
|
const prior = await tx.supplierInvoice.findMany({
|
|
where: {
|
|
organizationId: actor.organizationId,
|
|
purchaseOrderId: orderId,
|
|
void: { is: null },
|
|
},
|
|
include: { lines: true },
|
|
});
|
|
const billed = new Map<string, bigint>();
|
|
for (const invoice of prior)
|
|
for (const line of invoice.lines)
|
|
addQuantity(
|
|
billed,
|
|
line.purchaseOrderLineId,
|
|
line.quantity.toFixed(3),
|
|
);
|
|
const lines = input.lines.map((line) => {
|
|
const ordered = orderLines.get(line.purchaseOrderLineId);
|
|
if (!ordered) throw new AppError('INVOICE_LINE_INVALID');
|
|
const available = accepted.get(line.purchaseOrderLineId) ?? 0n;
|
|
if (available === 0n) throw new AppError('INVOICE_QC_REQUIRED');
|
|
if (
|
|
(billed.get(line.purchaseOrderLineId) ?? 0n) +
|
|
scaled(line.quantity, 3) >
|
|
available
|
|
)
|
|
throw new AppError('INVOICE_QUANTITY_LIMIT');
|
|
const unitPrice = ordered.unitPrice.toFixed(2);
|
|
return {
|
|
organizationId: actor.organizationId,
|
|
purchaseOrderId: orderId,
|
|
purchaseOrderLineId: ordered.id,
|
|
quantity: line.quantity,
|
|
unitPrice,
|
|
lineTotal: invoiceLineTotal(line.quantity, unitPrice),
|
|
};
|
|
});
|
|
const totals = invoiceTotals(
|
|
lines,
|
|
input.taxAmount,
|
|
input.shippingAmount,
|
|
);
|
|
const invoice = await tx.supplierInvoice.create({
|
|
data: {
|
|
organizationId: actor.organizationId,
|
|
purchaseOrderId: orderId,
|
|
supplierId: order.supplierId,
|
|
createdById: actor.userId,
|
|
invoiceNumber: input.invoiceNumber,
|
|
invoiceDate: input.invoiceDate,
|
|
currency: order.currency,
|
|
taxAmount: input.taxAmount,
|
|
shippingAmount: input.shippingAmount,
|
|
...totals,
|
|
},
|
|
});
|
|
await tx.supplierInvoiceLine.createMany({
|
|
data: lines.map((line) => ({ ...line, invoiceId: invoice.id })),
|
|
});
|
|
await recordAudit(
|
|
tx,
|
|
actor.organizationId,
|
|
actor.userId,
|
|
'supplier_invoice.created',
|
|
invoice.id,
|
|
);
|
|
return tx.supplierInvoice.findUniqueOrThrow({
|
|
where: { id: invoice.id },
|
|
include: invoiceView,
|
|
});
|
|
});
|
|
}
|
|
|
|
void(actor: Principal, id: string, input: SupplierInvoiceVoidInput) {
|
|
return this.access.mutate(actor, 'procurement.manage', async (tx) => {
|
|
const invoice = await tx.supplierInvoice.findFirst({
|
|
where: { id, organizationId: actor.organizationId },
|
|
include: { void: true },
|
|
});
|
|
if (!invoice) throw new AppError('INVOICE_NOT_FOUND');
|
|
if (invoice.void) throw new AppError('INVOICE_ALREADY_VOID');
|
|
await tx.supplierInvoiceVoid.create({
|
|
data: {
|
|
invoiceId: id,
|
|
organizationId: actor.organizationId,
|
|
voidedById: actor.userId,
|
|
reason: input.reason,
|
|
},
|
|
});
|
|
await recordAudit(
|
|
tx,
|
|
actor.organizationId,
|
|
actor.userId,
|
|
'supplier_invoice.voided',
|
|
id,
|
|
);
|
|
return tx.supplierInvoice.findUniqueOrThrow({
|
|
where: { id },
|
|
include: invoiceView,
|
|
});
|
|
});
|
|
}
|
|
}
|