manicanldes-backend/src/production/batch.store.ts

214 lines
6.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 { plannedMaterialQuantity } from './batch-quantity';
import type {
BatchListQuery,
CancelBatchInput,
CompleteBatchInput,
CreateBatchInput,
} from './batch.schemas';
const batchView = {
bom: { include: { lines: { orderBy: { materialCode: 'asc' as const } } } },
completion: true,
cancellation: true,
};
function present<
T extends {
plannedQuantity: number;
bom: {
outputQuantity: number;
lines: { quantity: { toString(): string } }[];
};
},
>(batch: T) {
const factor = batch.plannedQuantity / batch.bom.outputQuantity;
return {
...batch,
plannedMaterials: batch.bom.lines.map((line) => ({
...line,
plannedQuantity: plannedMaterialQuantity(
line.quantity.toString(),
factor,
),
})),
};
}
@Injectable()
export class BatchStore {
constructor(
private readonly db: DatabaseService,
private readonly access: AccessStore,
) {}
list(actor: Principal, query: BatchListQuery) {
return this.db.productionBatch.findMany({
where: {
organizationId: actor.organizationId,
...(query.status ? { status: query.status } : {}),
...(query.variantId ? { bom: { variantId: query.variantId } } : {}),
},
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
take: query.limit,
skip: query.offset,
});
}
async find(actor: Principal, id: string) {
const batch = await this.db.productionBatch.findFirst({
where: { id, organizationId: actor.organizationId },
include: batchView,
});
if (!batch) throw new AppError('BATCH_NOT_FOUND');
return present(batch);
}
create(actor: Principal, input: CreateBatchInput) {
return this.access.mutate(actor, 'production.manage', async (tx) => {
const duplicate = await tx.productionBatch.findFirst({
where: {
organizationId: actor.organizationId,
reference: input.reference,
},
select: { id: true },
});
if (duplicate) throw new AppError('BATCH_REFERENCE_CONFLICT');
const bom = await tx.productBom.findFirst({
where: { id: input.bomId, organizationId: actor.organizationId },
include: { variant: { select: { active: true } }, lines: true },
});
if (!bom) throw new AppError('BOM_NOT_FOUND');
if (bom.kind !== 'PRODUCTION') throw new AppError('BATCH_BOM_KIND');
if (bom.status !== 'ACTIVE') throw new AppError('BATCH_BOM_NOT_ACTIVE');
if (!bom.variant.active) throw new AppError('BATCH_VARIANT_INACTIVE');
if (input.plannedQuantity % bom.outputQuantity !== 0)
throw new AppError('BATCH_YIELD_MISMATCH');
const factor = input.plannedQuantity / bom.outputQuantity;
for (const line of bom.lines)
plannedMaterialQuantity(line.quantity.toString(), factor);
const batch = await tx.productionBatch.create({
data: {
...input,
organizationId: actor.organizationId,
createdById: actor.userId,
},
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'batch.created',
batch.id,
);
return this.load(tx, batch.id);
});
}
start(actor: Principal, id: string) {
return this.access.mutate(actor, 'production.manage', async (tx) => {
const batch = await this.requireBatch(tx, actor, id);
if (batch.status !== 'DRAFT') throw new AppError('BATCH_START_STATE');
await tx.productionBatch.update({
where: { id },
data: { status: 'IN_PROGRESS', startedAt: new Date() },
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'batch.started',
id,
);
return this.load(tx, id);
});
}
complete(actor: Principal, id: string, input: CompleteBatchInput) {
return this.access.mutate(actor, 'production.manage', async (tx) => {
const batch = await this.requireBatch(tx, actor, id);
if (batch.status !== 'IN_PROGRESS')
throw new AppError('BATCH_COMPLETE_STATE');
if (input.goodQuantity + input.rejectedQuantity !== batch.plannedQuantity)
throw new AppError('BATCH_QUANTITY_MISMATCH');
if (input.rejectedQuantity > 0 && !input.rejectionReason)
throw new AppError('BATCH_REJECTION_REASON_REQUIRED');
await tx.productionBatch.update({
where: { id },
data: { status: 'COMPLETED' },
});
await tx.productionBatchCompletion.create({
data: {
...input,
batchId: id,
organizationId: actor.organizationId,
completedById: actor.userId,
},
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'batch.completed',
id,
);
return this.load(tx, id);
});
}
cancel(actor: Principal, id: string, input: CancelBatchInput) {
return this.access.mutate(actor, 'production.manage', async (tx) => {
const batch = await this.requireBatch(tx, actor, id);
if (batch.status !== 'DRAFT' && batch.status !== 'IN_PROGRESS')
throw new AppError('BATCH_CANCEL_STATE');
await tx.productionBatch.update({
where: { id },
data: { status: 'CANCELLED' },
});
await tx.productionBatchCancellation.create({
data: {
batchId: id,
organizationId: actor.organizationId,
cancelledById: actor.userId,
reason: input.reason,
},
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'batch.cancelled',
id,
);
return this.load(tx, id);
});
}
private async requireBatch(
tx: Prisma.TransactionClient,
actor: Principal,
id: string,
) {
const batch = await tx.productionBatch.findFirst({
where: { id, organizationId: actor.organizationId },
select: { status: true, plannedQuantity: true },
});
if (!batch) throw new AppError('BATCH_NOT_FOUND');
return batch;
}
private async load(tx: Prisma.TransactionClient, id: string) {
const batch = await tx.productionBatch.findUniqueOrThrow({
where: { id },
include: batchView,
});
return present(batch);
}
}