import { randomUUID } from 'node:crypto'; import { identityApp, type IdentityApp } from './helpers/identity-app'; import { secondActor } from './helpers/commerce'; import { createBatch, seedActiveBom } from './helpers/production'; describe('production 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}/material-stock-posting`) .auth(ctx.token, auth) .send(body); const get = (batchId: string) => ctx .api() .get(`/api/v1/production-batches/${batchId}/material-stock-posting`) .auth(ctx.token, auth); const seed = async (balance = '250.000') => { const bom = await seedActiveBom(ctx); const batch = await createBatch(ctx, bom.bomId).expect(201); const warehouse = await ctx .api() .post('/api/v1/inventory/warehouses') .auth(ctx.token, auth) .send({ name: `Production ${randomUUID().slice(0, 8)}` }) .expect(201); const stock = await ctx.db.materialStockItem.create({ data: { organizationId: ctx.owner.organizationId, materialId: bom.materialId, warehouseId: warehouse.body.id, onHand: balance, }, }); return { ...bom, batchId: batch.body.id as string, warehouseId: warehouse.body.id as string, stockId: stock.id, }; }; const use = async ( batchId: string, bomLineId: string, kind: 'CONSUMED' | 'WASTED', quantity: string, ) => ctx .api() .post(`/api/v1/production-batches/${batchId}/material-usage`) .auth(ctx.token, auth) .send({ bomLineId, kind, quantity, ...(kind === 'WASTED' ? { reason: 'Spillage' } : {}), idempotencyKey: randomUUID(), }) .expect(201); const start = (batchId: string) => ctx .api() .post(`/api/v1/production-batches/${batchId}/start`) .auth(ctx.token, auth) .expect(201); const complete = (batchId: string) => ctx .api() .post(`/api/v1/production-batches/${batchId}/complete`) .auth(ctx.token, auth) .send({ goodQuantity: 20, rejectedQuantity: 0 }) .expect(201); beforeAll(async () => { ctx = await identityApp(); }, 60000); afterAll(async () => { await ctx?.close(); }); beforeEach(async () => { await ctx.clearLimits(); }); it('deducts consumed and wasted quantities from the chosen warehouse once', async () => { const data = await seed(); await start(data.batchId); await use(data.batchId, data.bomLineId, 'CONSUMED', '200.000'); await use(data.batchId, data.bomLineId, 'WASTED', '10.125'); await complete(data.batchId); const body = { warehouseId: data.warehouseId, idempotencyKey: randomUUID(), }; const result = await post(data.batchId, body).expect(201); expect( result.body.entries.map((entry: { kind: string }) => entry.kind).sort(), ).toEqual(['PRODUCTION_CONSUMED', 'PRODUCTION_WASTED']); expect( ( await ctx.db.materialStockItem.findUniqueOrThrow({ where: { id: data.stockId }, }) ).onHand.toFixed(3), ).toBe('39.875'); 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: { productionPostingId: result.body.id }, }), ).toBe(2); }); it('rejects incomplete state, changed retries and duplicate posting', async () => { const data = await seed(); const body = { warehouseId: data.warehouseId, idempotencyKey: randomUUID(), }; expect((await post(data.batchId, body).expect(409)).body.code).toBe( 'PRODUCTION_STOCK_BATCH_STATE', ); await start(data.batchId); await complete(data.batchId); expect((await post(data.batchId, body).expect(409)).body.code).toBe( 'PRODUCTION_STOCK_USAGE_INCOMPLETE', ); expect( await ctx.db.productionStockPosting.count({ where: { batchId: data.batchId }, }), ).toBe(0); // A separate completed batch with recorded use exercises replay and duplicate guards. const other = await seed(); await start(other.batchId); await use(other.batchId, other.bomLineId, 'CONSUMED', '1.000'); await complete(other.batchId); const request = { warehouseId: other.warehouseId, idempotencyKey: randomUUID(), }; await post(other.batchId, request).expect(201); expect( ( await post(other.batchId, { ...request, warehouseId: data.warehouseId, }).expect(409) ).body.code, ).toBe('PRODUCTION_STOCK_REPLAY_CONFLICT'); expect( ( await post(other.batchId, { ...request, idempotencyKey: randomUUID(), }).expect(409) ).body.code, ).toBe('PRODUCTION_STOCK_ALREADY_POSTED'); }); it('rejects an insufficient warehouse atomically and enforces tenant scope', async () => { const data = await seed('5.000'); await start(data.batchId); await use(data.batchId, data.bomLineId, 'CONSUMED', '5.000'); await use(data.batchId, data.bomLineId, 'WASTED', '0.001'); await complete(data.batchId); const body = { warehouseId: data.warehouseId, idempotencyKey: randomUUID(), }; expect((await post(data.batchId, body).expect(409)).body.code).toBe( 'PRODUCTION_STOCK_INSUFFICIENT', ); expect( await ctx.db.productionStockPosting.count({ where: { batchId: data.batchId }, }), ).toBe(0); expect( ( await ctx.db.materialStockItem.findUniqueOrThrow({ where: { id: data.stockId }, }) ).onHand.toFixed(3), ).toBe('5.000'); const reader = await secondActor(ctx, true, ['inventory.read']); await ctx .api() .post(`/api/v1/production-batches/${data.batchId}/material-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}/material-stock-posting`) .auth(outsider.token, auth) .expect(404); }); it('rejects direct alteration of a posted ledger entry', async () => { const data = await seed(); await start(data.batchId); await use(data.batchId, data.bomLineId, 'CONSUMED', '1.000'); await complete(data.batchId); const result = await post(data.batchId, { warehouseId: data.warehouseId, idempotencyKey: randomUUID(), }).expect(201); await expect( ctx.db.materialStockLedger.update({ where: { id: result.body.entries[0].id }, data: { delta: '-2.000' }, }), ).rejects.toThrow(); }); });