manicanldes-backend/src/production/production-stock-posting.st...

160 lines
5.3 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 = { entries: { orderBy: { usageEventId: 'asc' as const } } };
type Posting = Prisma.ProductionStockPostingGetPayload<{
include: typeof postingView;
}>;
function present(posting: Posting) {
return {
id: posting.id,
batchId: posting.batchId,
warehouseId: posting.warehouseId,
postedById: posting.postedById,
createdAt: posting.createdAt,
entries: posting.entries.map((entry) => ({
id: entry.id,
stockItemId: entry.stockItemId,
materialId: entry.materialId,
usageEventId: entry.usageEventId,
kind: entry.kind,
delta: entry.delta.toFixed(3),
})),
};
}
@Injectable()
export class ProductionStockPostingStore {
constructor(
private readonly db: DatabaseService,
private readonly access: AccessStore,
) {}
async find(actor: Principal, batchId: string) {
const posting = await this.db.productionStockPosting.findFirst({
where: { batchId, organizationId: actor.organizationId },
include: postingView,
});
if (!posting) throw new AppError('PRODUCTION_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.productionStockPosting.findFirst({
where: {
organizationId: actor.organizationId,
idempotencyKey: input.idempotencyKey,
},
include: postingView,
});
if (prior) {
if (prior.requestHash !== hash)
throw new AppError('PRODUCTION_STOCK_REPLAY_CONFLICT');
return present(prior);
}
const batch = await tx.productionBatch.findFirst({
where: { id: batchId, organizationId: actor.organizationId },
include: {
bom: { include: { lines: true } },
materialUsage: { include: { bomLine: true }, orderBy: { id: 'asc' } },
},
});
if (!batch) throw new AppError('BATCH_NOT_FOUND');
if (
await tx.productionStockPosting.findUnique({
where: { batchId },
select: { id: true },
})
)
throw new AppError('PRODUCTION_STOCK_ALREADY_POSTED');
if (batch.status !== 'COMPLETED')
throw new AppError('PRODUCTION_STOCK_BATCH_STATE');
if (
batch.bom.lines.some(
(line) =>
!batch.materialUsage.some((usage) => usage.bomLineId === line.id),
)
)
throw new AppError('PRODUCTION_STOCK_USAGE_INCOMPLETE');
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: batch.bom.lines.map((line) => line.materialId) },
},
});
const byMaterial = requireAvailableMaterials(
stock,
batch.materialUsage.map((usage) => ({
materialId: usage.bomLine.materialId,
quantity: usage.quantity.toFixed(3),
})),
'PRODUCTION_STOCK_INSUFFICIENT',
);
const posting = await tx.productionStockPosting.create({
data: {
organizationId: actor.organizationId,
batchId,
warehouseId: warehouse.id,
postedById: actor.userId,
idempotencyKey: input.idempotencyKey,
requestHash: hash,
},
});
for (const usage of batch.materialUsage) {
const materialId = usage.bomLine.materialId;
await tx.materialStockLedger.create({
data: {
organizationId: actor.organizationId,
stockItemId: byMaterial.get(materialId)!.id,
materialId,
productionPostingId: posting.id,
usageEventId: usage.id,
kind:
usage.kind === 'CONSUMED'
? 'PRODUCTION_CONSUMED'
: 'PRODUCTION_WASTED',
delta: formatMaterialQuantity(
-parseMaterialQuantity(usage.quantity.toFixed(3)),
),
},
});
}
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'batch.material_stock_posted',
posting.id,
);
return present(
await tx.productionStockPosting.findUniqueOrThrow({
where: { id: posting.id },
include: postingView,
}),
);
});
}
}