import { randomUUID } from 'node:crypto'; import { identityApp, type IdentityApp } from './helpers/identity-app'; import { secondActor } from './helpers/commerce'; import { completeCostBatch, packageCostBatch, prepareCostBatch, startCostBatch, } from './helpers/batch-cost'; describe('packaging material stock posting', () => { let ctx: IdentityApp; const auth = { type: 'bearer' as const }; const post = (batchId: string, body: object) => ctx .api() .post(`/api/v1/production-batches/${batchId}/packaging-stock-posting`) .auth(ctx.token, auth) .send(body); const get = (batchId: string) => ctx .api() .get(`/api/v1/production-batches/${batchId}/packaging-stock-posting`) .auth(ctx.token, auth); const warehouse = async () => ( await ctx .api() .post('/api/v1/inventory/warehouses') .auth(ctx.token, auth) .send({ name: `Packaging ${randomUUID().slice(0, 8)}` }) .expect(201) ).body.id as string; const ready = async (balance = '25.000') => { const batch = await prepareCostBatch(ctx); const warehouseId = await warehouse(); const stock = await ctx.db.materialStockItem.create({ data: { organizationId: ctx.owner.organizationId, warehouseId, materialId: batch.packagingMaterialId, onHand: balance, }, }); await startCostBatch(ctx, batch.batchId); await completeCostBatch(ctx, batch.batchId); await packageCostBatch( ctx, batch.batchId, batch.packagingBomId, batch.packagingLineId, ); return { ...batch, warehouseId, stockId: stock.id }; }; beforeAll(async () => { ctx = await identityApp(); }, 60000); afterAll(async () => { await ctx?.close(); }); beforeEach(async () => { await ctx.clearLimits(); }); it('posts used and wasted packaging quantities once to the selected warehouse', async () => { const data = await ready(); const otherWarehouse = await warehouse(); const otherStock = await ctx.db.materialStockItem.create({ data: { organizationId: ctx.owner.organizationId, warehouseId: otherWarehouse, materialId: data.packagingMaterialId, onHand: '12.000', }, }); const body = { warehouseId: data.warehouseId, idempotencyKey: randomUUID(), }; const result = await post(data.batchId, body).expect(201); expect( result.body.entries .map((entry: { kind: string; delta: string }) => [ entry.kind, entry.delta, ]) .sort(), ).toEqual([ ['PACKAGING_USED', '-19.000'], ['PACKAGING_WASTED', '-1.000'], ]); expect( ( await ctx.db.materialStockItem.findUniqueOrThrow({ where: { id: data.stockId }, }) ).onHand.toFixed(3), ).toBe('5.000'); expect( ( await ctx.db.materialStockItem.findUniqueOrThrow({ where: { id: otherStock.id }, }) ).onHand.toFixed(3), ).toBe('12.000'); expect((await post(data.batchId, body).expect(201)).body.id).toBe( result.body.id, ); expect((await get(data.batchId).expect(200)).body.id).toBe(result.body.id); expect( await ctx.db.materialStockLedger.count({ where: { packagingPostingId: result.body.id }, }), ).toBe(2); }); it('requires a packaging record and rejects changed retries or duplicate posting', async () => { const batch = await prepareCostBatch(ctx); const warehouseId = await warehouse(); const body = { warehouseId, idempotencyKey: randomUUID() }; expect((await post(batch.batchId, body).expect(404)).body.code).toBe( 'PACKAGING_RUN_NOT_FOUND', ); const data = await ready(); const request = { warehouseId: data.warehouseId, idempotencyKey: randomUUID(), }; await post(data.batchId, request).expect(201); expect( (await post(data.batchId, { ...request, warehouseId }).expect(409)).body .code, ).toBe('PACKAGING_STOCK_REPLAY_CONFLICT'); expect( ( await post(data.batchId, { ...request, idempotencyKey: randomUUID(), }).expect(409) ).body.code, ).toBe('PACKAGING_STOCK_ALREADY_POSTED'); }); it('checks total used plus wasted before any stock is deducted', async () => { const data = await ready('19.000'); expect( ( await post(data.batchId, { warehouseId: data.warehouseId, idempotencyKey: randomUUID(), }).expect(409) ).body.code, ).toBe('PACKAGING_STOCK_INSUFFICIENT'); expect( await ctx.db.packagingStockPosting.count({ where: { run: { batchId: data.batchId } }, }), ).toBe(0); expect( ( await ctx.db.materialStockItem.findUniqueOrThrow({ where: { id: data.stockId }, }) ).onHand.toFixed(3), ).toBe('19.000'); }); it('enforces permission, tenant scope and immutable stock entries', async () => { const data = await ready(); const body = { warehouseId: data.warehouseId, idempotencyKey: randomUUID(), }; const reader = await secondActor(ctx, true, ['inventory.read']); await ctx .api() .post( `/api/v1/production-batches/${data.batchId}/packaging-stock-posting`, ) .auth(reader.token, auth) .send(body) .expect(403); const outsider = await secondActor(ctx, false, [ 'inventory.read', 'inventory.manage', ]); await ctx .api() .get(`/api/v1/production-batches/${data.batchId}/packaging-stock-posting`) .auth(outsider.token, auth) .expect(404); const posted = await post(data.batchId, body).expect(201); await expect( ctx.db.materialStockLedger.update({ where: { id: posted.body.entries[0].id }, data: { delta: '-2.000' }, }), ).rejects.toThrow(); }); });