169 lines
5.5 KiB
TypeScript
169 lines
5.5 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 {
|
|
formatMaterialQuantity,
|
|
parseMaterialQuantity,
|
|
} from './batch-quantity';
|
|
import {
|
|
requireAvailableMaterials,
|
|
stockPostingHash,
|
|
} from './material-stock-posting.helpers';
|
|
import type { MaterialStockPostingInput } from './material-stock-posting.schemas';
|
|
|
|
const postingView = {
|
|
run: { select: { batchId: true } },
|
|
entries: {
|
|
orderBy: [{ packagingRunLineId: 'asc' as const }, { kind: 'asc' as const }],
|
|
},
|
|
};
|
|
type Posting = Prisma.PackagingStockPostingGetPayload<{
|
|
include: typeof postingView;
|
|
}>;
|
|
function present(posting: Posting) {
|
|
return {
|
|
id: posting.id,
|
|
batchId: posting.run.batchId,
|
|
runId: posting.runId,
|
|
warehouseId: posting.warehouseId,
|
|
postedById: posting.postedById,
|
|
createdAt: posting.createdAt,
|
|
entries: posting.entries.map((entry) => ({
|
|
id: entry.id,
|
|
stockItemId: entry.stockItemId,
|
|
materialId: entry.materialId,
|
|
packagingRunLineId: entry.packagingRunLineId,
|
|
kind: entry.kind,
|
|
delta: entry.delta.toFixed(3),
|
|
})),
|
|
};
|
|
}
|
|
|
|
@Injectable()
|
|
export class PackagingStockPostingStore {
|
|
constructor(
|
|
private readonly db: DatabaseService,
|
|
private readonly access: AccessStore,
|
|
) {}
|
|
|
|
async find(actor: Principal, batchId: string) {
|
|
const posting = await this.db.packagingStockPosting.findFirst({
|
|
where: { organizationId: actor.organizationId, run: { batchId } },
|
|
include: postingView,
|
|
});
|
|
if (!posting) throw new AppError('PACKAGING_STOCK_POSTING_NOT_FOUND');
|
|
return present(posting);
|
|
}
|
|
|
|
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.packagingStockPosting.findFirst({
|
|
where: {
|
|
organizationId: actor.organizationId,
|
|
idempotencyKey: input.idempotencyKey,
|
|
},
|
|
include: postingView,
|
|
});
|
|
if (prior) {
|
|
if (prior.requestHash !== hash)
|
|
throw new AppError('PACKAGING_STOCK_REPLAY_CONFLICT');
|
|
return present(prior);
|
|
}
|
|
const batch = await tx.productionBatch.findFirst({
|
|
where: { id: batchId, organizationId: actor.organizationId },
|
|
select: { id: true },
|
|
});
|
|
if (!batch) throw new AppError('BATCH_NOT_FOUND');
|
|
const run = await tx.packagingRun.findFirst({
|
|
where: { batchId, organizationId: actor.organizationId },
|
|
include: {
|
|
lines: { include: { bomLine: true }, orderBy: { id: 'asc' } },
|
|
},
|
|
});
|
|
if (!run) throw new AppError('PACKAGING_RUN_NOT_FOUND');
|
|
if (
|
|
await tx.packagingStockPosting.findUnique({
|
|
where: { runId: run.id },
|
|
select: { id: true },
|
|
})
|
|
)
|
|
throw new AppError('PACKAGING_STOCK_ALREADY_POSTED');
|
|
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 stock = await tx.materialStockItem.findMany({
|
|
where: {
|
|
organizationId: actor.organizationId,
|
|
warehouseId: warehouse.id,
|
|
materialId: { in: run.lines.map((line) => line.bomLine.materialId) },
|
|
},
|
|
});
|
|
const byMaterial = requireAvailableMaterials(
|
|
stock,
|
|
run.lines.flatMap((line) => [
|
|
{
|
|
materialId: line.bomLine.materialId,
|
|
quantity: line.usedQuantity.toFixed(3),
|
|
},
|
|
{
|
|
materialId: line.bomLine.materialId,
|
|
quantity: line.wastedQuantity.toFixed(3),
|
|
},
|
|
]),
|
|
'PACKAGING_STOCK_INSUFFICIENT',
|
|
);
|
|
const posting = await tx.packagingStockPosting.create({
|
|
data: {
|
|
organizationId: actor.organizationId,
|
|
runId: run.id,
|
|
warehouseId: warehouse.id,
|
|
postedById: actor.userId,
|
|
idempotencyKey: input.idempotencyKey,
|
|
requestHash: hash,
|
|
},
|
|
});
|
|
for (const line of run.lines) {
|
|
for (const [kind, quantity] of [
|
|
['PACKAGING_USED', line.usedQuantity.toFixed(3)],
|
|
['PACKAGING_WASTED', line.wastedQuantity.toFixed(3)],
|
|
] as const) {
|
|
const scaled = parseMaterialQuantity(quantity);
|
|
if (scaled === 0n) continue;
|
|
const materialId = line.bomLine.materialId;
|
|
await tx.materialStockLedger.create({
|
|
data: {
|
|
organizationId: actor.organizationId,
|
|
stockItemId: byMaterial.get(materialId)!.id,
|
|
materialId,
|
|
packagingPostingId: posting.id,
|
|
packagingRunLineId: line.id,
|
|
kind,
|
|
delta: formatMaterialQuantity(-scaled),
|
|
},
|
|
});
|
|
}
|
|
}
|
|
await recordAudit(
|
|
tx,
|
|
actor.organizationId,
|
|
actor.userId,
|
|
'batch.packaging_stock_posted',
|
|
posting.id,
|
|
);
|
|
return present(
|
|
await tx.packagingStockPosting.findUniqueOrThrow({
|
|
where: { id: posting.id },
|
|
include: postingView,
|
|
}),
|
|
);
|
|
});
|
|
}
|
|
}
|