import { randomUUID } from 'node:crypto'; import type { IdentityApp } from './identity-app'; import { createBatch, seedActiveBom } from './production'; const auth = { type: 'bearer' as const }; export async function prepareCostBatch(ctx: IdentityApp) { const production = await seedActiveBom(ctx); const box = await ctx .api() .post('/api/v1/materials') .auth(ctx.token, auth) .send({ code: `P-${randomUUID().slice(0, 8)}`, name: 'Box', kind: 'PACKAGING', unit: 'PIECE', }) .expect(201); const packaging = await ctx .api() .post(`/api/v1/variants/${production.variantId}/packaging-boms`) .auth(ctx.token, auth) .send({ outputQuantity: 10, lines: [{ materialId: box.body.id, quantity: '10.000' }], }) .expect(201); await ctx .api() .post(`/api/v1/packaging-boms/${packaging.body.id}/activate`) .auth(ctx.token, auth) .expect(201); const batch = await createBatch(ctx, production.bomId).expect(201); return { batchId: batch.body.id as string, productionLineId: production.bomLineId, productionMaterialId: production.materialId, packagingBomId: packaging.body.id as string, packagingLineId: packaging.body.lines[0].id as string, packagingMaterialId: box.body.id as string, }; } export async function startCostBatch(ctx: IdentityApp, batchId: string) { await ctx .api() .post(`/api/v1/production-batches/${batchId}/start`) .auth(ctx.token, auth) .expect(201); } export async function recordCostUsage( ctx: IdentityApp, batchId: string, bomLineId: string, kind: 'CONSUMED' | 'WASTED', quantity: string, ) { return ctx .api() .post(`/api/v1/production-batches/${batchId}/material-usage`) .auth(ctx.token, auth) .send({ bomLineId, kind, quantity, ...(kind === 'WASTED' ? { reason: 'Spill' } : {}), idempotencyKey: randomUUID(), }) .expect(201); } export async function completeCostBatch( ctx: IdentityApp, batchId: string, goodQuantity = 20, ) { await ctx .api() .post(`/api/v1/production-batches/${batchId}/complete`) .auth(ctx.token, auth) .send({ goodQuantity, rejectedQuantity: 20 - goodQuantity, ...(goodQuantity < 20 ? { rejectionReason: 'Rejected' } : {}), }) .expect(201); } export async function packageCostBatch( ctx: IdentityApp, batchId: string, bomId: string, bomLineId: string, ) { await ctx .api() .post(`/api/v1/production-batches/${batchId}/packaging`) .auth(ctx.token, auth) .send({ bomId, idempotencyKey: randomUUID(), lines: [ { bomLineId, usedQuantity: '19.000', wastedQuantity: '1.000', wasteReason: 'Torn', }, ], }) .expect(201); } export async function setCostRate( ctx: IdentityApp, materialId: string, unitCost: string, ) { return ctx .api() .post(`/api/v1/materials/${materialId}/cost-rates`) .auth(ctx.token, auth) .send({ currency: 'INR', unitCost }) .expect(201); }