manicanldes-backend/src/production/finished-goods-receipt.stor...

168 lines
5.7 KiB
TypeScript

import { Injectable } from '@nestjs/common';
import { AppError } from '../common/errors/app-error';
import { DatabaseService } from '../database/database.service';
import type { Prisma } from '../generated/prisma/client';
import { AccessStore } from '../identity/access.store';
import { recordAudit } from '../identity/audit';
import type { Principal } from '../identity/identity.types';
import { stockPostingHash } from './material-stock-posting.helpers';
import type { MaterialStockPostingInput } from './material-stock-posting.schemas';
const MAX_STOCK = 2_000_000_000;
const receiptView = {
entry: true,
batch: { include: { bom: { select: { variantId: true } } } },
};
type Receipt = Prisma.FinishedGoodsReceiptGetPayload<{
include: typeof receiptView;
}>;
function present(receipt: Receipt) {
return {
id: receipt.id,
batchId: receipt.batchId,
variantId: receipt.batch.bom.variantId,
warehouseId: receipt.warehouseId,
stockItemId: receipt.stockItemId,
quantity: receipt.quantity,
postedById: receipt.postedById,
createdAt: receipt.createdAt,
ledgerEntryId: receipt.entry?.id,
};
}
@Injectable()
export class FinishedGoodsReceiptStore {
constructor(
private readonly db: DatabaseService,
private readonly access: AccessStore,
) {}
async find(actor: Principal, batchId: string) {
const receipt = await this.db.finishedGoodsReceipt.findFirst({
where: { batchId, organizationId: actor.organizationId },
include: receiptView,
});
if (!receipt) throw new AppError('FINISHED_GOODS_RECEIPT_NOT_FOUND');
return present(receipt);
}
create(actor: Principal, batchId: string, input: MaterialStockPostingInput) {
return this.access.mutate(actor, 'inventory.manage', async (tx) => {
const hash = stockPostingHash(batchId, input.warehouseId);
const prior = await tx.finishedGoodsReceipt.findFirst({
where: {
organizationId: actor.organizationId,
idempotencyKey: input.idempotencyKey,
},
include: receiptView,
});
if (prior) {
if (prior.requestHash !== hash)
throw new AppError('FINISHED_GOODS_REPLAY_CONFLICT');
return present(prior);
}
const batch = await tx.productionBatch.findFirst({
where: { id: batchId, organizationId: actor.organizationId },
include: {
bom: { select: { variantId: true } },
completion: true,
packagingRun: {
select: { id: true, stockPosting: { select: { id: true } } },
},
stockPosting: { select: { id: true } },
},
});
if (!batch) throw new AppError('BATCH_NOT_FOUND');
if (
await tx.finishedGoodsReceipt.findUnique({
where: { batchId },
select: { id: true },
})
)
throw new AppError('FINISHED_GOODS_ALREADY_POSTED');
if (batch.status !== 'COMPLETED' || !batch.completion)
throw new AppError('FINISHED_GOODS_BATCH_STATE');
const quantity = batch.completion.goodQuantity;
if (quantity === 0) throw new AppError('FINISHED_GOODS_NO_OUTPUT');
if (!batch.packagingRun)
throw new AppError('FINISHED_GOODS_PACKAGING_REQUIRED');
if (!batch.stockPosting)
throw new AppError('FINISHED_GOODS_PRODUCTION_STOCK_REQUIRED');
if (!batch.packagingRun.stockPosting)
throw new AppError('FINISHED_GOODS_PACKAGING_STOCK_REQUIRED');
const warehouse = await tx.warehouse.findFirst({
where: { id: input.warehouseId, organizationId: actor.organizationId },
select: { id: true },
});
if (!warehouse) throw new AppError('WAREHOUSE_NOT_FOUND');
const variantId = batch.bom.variantId;
let stock = await tx.stockItem.findFirst({
where: {
organizationId: actor.organizationId,
warehouseId: warehouse.id,
variantId,
},
});
if (!stock)
stock = await tx.stockItem.create({
data: {
organizationId: actor.organizationId,
warehouseId: warehouse.id,
variantId,
},
});
await tx.$queryRaw`SELECT id FROM stock_items WHERE id = ${stock.id}::uuid FOR UPDATE`;
stock = await tx.stockItem.findUniqueOrThrow({ where: { id: stock.id } });
if (stock.onHand > MAX_STOCK - quantity)
throw new AppError('FINISHED_GOODS_STOCK_CAPACITY');
if (
await tx.stockLedger.findFirst({
where: {
organizationId: actor.organizationId,
idempotencyKey: input.idempotencyKey,
},
select: { id: true },
})
)
throw new AppError('FINISHED_GOODS_KEY_CONFLICT');
const receipt = await tx.finishedGoodsReceipt.create({
data: {
organizationId: actor.organizationId,
batchId,
warehouseId: warehouse.id,
stockItemId: stock.id,
postedById: actor.userId,
quantity,
idempotencyKey: input.idempotencyKey,
requestHash: hash,
},
});
await tx.stockLedger.create({
data: {
organizationId: actor.organizationId,
stockItemId: stock.id,
actorId: actor.userId,
delta: quantity,
reason: 'PRODUCTION_OUTPUT',
idempotencyKey: input.idempotencyKey,
requestHash: hash,
finishedGoodsReceiptId: receipt.id,
},
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'batch.finished_goods_received',
receipt.id,
);
return present(
await tx.finishedGoodsReceipt.findUniqueOrThrow({
where: { id: receipt.id },
include: receiptView,
}),
);
});
}
}