manicanldes-backend/test/finished-goods-receipt.spec.ts

296 lines
8.5 KiB
TypeScript

import { randomUUID } from 'node:crypto';
import { identityApp, type IdentityApp } from './helpers/identity-app';
import { secondActor } from './helpers/commerce';
import {
completeCostBatch,
packageCostBatch,
prepareCostBatch,
recordCostUsage,
startCostBatch,
} from './helpers/batch-cost';
describe('finished-goods receipt', () => {
let ctx: IdentityApp;
const auth = { type: 'bearer' as const };
const post = (batchId: string, body: object) =>
ctx
.api()
.post(`/api/v1/production-batches/${batchId}/finished-goods-receipt`)
.auth(ctx.token, auth)
.send(body);
const get = (batchId: string) =>
ctx
.api()
.get(`/api/v1/production-batches/${batchId}/finished-goods-receipt`)
.auth(ctx.token, auth);
const warehouse = async () =>
(
await ctx
.api()
.post('/api/v1/inventory/warehouses')
.auth(ctx.token, auth)
.send({ name: `Output ${randomUUID().slice(0, 8)}` })
.expect(201)
).body.id as string;
const prepare = async () => {
const batch = await prepareCostBatch(ctx);
const warehouseId = await warehouse();
await ctx.db.materialStockItem.createMany({
data: [
{
organizationId: ctx.owner.organizationId,
warehouseId,
materialId: batch.productionMaterialId,
onHand: '250.000',
},
{
organizationId: ctx.owner.organizationId,
warehouseId,
materialId: batch.packagingMaterialId,
onHand: '25.000',
},
],
});
return { ...batch, warehouseId };
};
const complete = async (
batch: Awaited<ReturnType<typeof prepare>>,
goodQuantity = 20,
) => {
await startCostBatch(ctx, batch.batchId);
await recordCostUsage(
ctx,
batch.batchId,
batch.productionLineId,
'CONSUMED',
'200.000',
);
await completeCostBatch(ctx, batch.batchId, goodQuantity);
await packageCostBatch(
ctx,
batch.batchId,
batch.packagingBomId,
batch.packagingLineId,
);
};
const postMaterials = async (batch: Awaited<ReturnType<typeof prepare>>) => {
await ctx
.api()
.post(
`/api/v1/production-batches/${batch.batchId}/material-stock-posting`,
)
.auth(ctx.token, auth)
.send({ warehouseId: batch.warehouseId, idempotencyKey: randomUUID() })
.expect(201);
await ctx
.api()
.post(
`/api/v1/production-batches/${batch.batchId}/packaging-stock-posting`,
)
.auth(ctx.token, auth)
.send({ warehouseId: batch.warehouseId, idempotencyKey: randomUUID() })
.expect(201);
};
const ready = async (goodQuantity = 20) => {
const batch = await prepare();
await complete(batch, goodQuantity);
await postMaterials(batch);
return batch;
};
beforeAll(async () => {
ctx = await identityApp();
}, 60000);
afterAll(async () => {
await ctx?.close();
});
beforeEach(async () => {
await ctx.clearLimits();
});
it('receives only good completed units into the selected warehouse once', async () => {
const batch = await ready(10);
const otherWarehouse = await warehouse();
const body = {
warehouseId: batch.warehouseId,
idempotencyKey: randomUUID(),
};
const receipt = await post(batch.batchId, body).expect(201);
expect(receipt.body).toMatchObject({
batchId: batch.batchId,
variantId: batch.variantId,
warehouseId: batch.warehouseId,
quantity: 10,
});
const stock = await ctx.db.stockItem.findUniqueOrThrow({
where: { id: receipt.body.stockItemId },
});
expect(stock.onHand).toBe(10);
expect(
await ctx.db.stockItem.count({
where: { variantId: batch.variantId, warehouseId: otherWarehouse },
}),
).toBe(0);
const entry = await ctx.db.stockLedger.findUniqueOrThrow({
where: { finishedGoodsReceiptId: receipt.body.id },
});
expect(entry).toMatchObject({
delta: 10,
reason: 'PRODUCTION_OUTPUT',
stockItemId: stock.id,
});
expect((await post(batch.batchId, body).expect(201)).body.id).toBe(
receipt.body.id,
);
expect((await get(batch.batchId).expect(200)).body.ledgerEntryId).toBe(
entry.id,
);
});
it('requires packaging and both material postings before receiving output', async () => {
const batch = await prepare();
const body = {
warehouseId: batch.warehouseId,
idempotencyKey: randomUUID(),
};
expect((await post(batch.batchId, body).expect(409)).body.code).toBe(
'FINISHED_GOODS_BATCH_STATE',
);
await startCostBatch(ctx, batch.batchId);
await recordCostUsage(
ctx,
batch.batchId,
batch.productionLineId,
'CONSUMED',
'200.000',
);
await completeCostBatch(ctx, batch.batchId);
expect((await post(batch.batchId, body).expect(409)).body.code).toBe(
'FINISHED_GOODS_PACKAGING_REQUIRED',
);
await packageCostBatch(
ctx,
batch.batchId,
batch.packagingBomId,
batch.packagingLineId,
);
expect((await post(batch.batchId, body).expect(409)).body.code).toBe(
'FINISHED_GOODS_PRODUCTION_STOCK_REQUIRED',
);
await ctx
.api()
.post(
`/api/v1/production-batches/${batch.batchId}/material-stock-posting`,
)
.auth(ctx.token, auth)
.send({ warehouseId: batch.warehouseId, idempotencyKey: randomUUID() })
.expect(201);
expect((await post(batch.batchId, body).expect(409)).body.code).toBe(
'FINISHED_GOODS_PACKAGING_STOCK_REQUIRED',
);
expect(
await ctx.db.finishedGoodsReceipt.count({
where: { batchId: batch.batchId },
}),
).toBe(0);
});
it('does not receive a fully rejected batch', async () => {
const batch = await prepare();
await startCostBatch(ctx, batch.batchId);
await completeCostBatch(ctx, batch.batchId, 0);
expect(
(
await post(batch.batchId, {
warehouseId: batch.warehouseId,
idempotencyKey: randomUUID(),
}).expect(409)
).body.code,
).toBe('FINISHED_GOODS_NO_OUTPUT');
});
it('rejects changed retries, duplicate receipt and capacity overflow', async () => {
const batch = await ready();
const body = {
warehouseId: batch.warehouseId,
idempotencyKey: randomUUID(),
};
await post(batch.batchId, body).expect(201);
expect(
(
await post(batch.batchId, {
...body,
warehouseId: await warehouse(),
}).expect(409)
).body.code,
).toBe('FINISHED_GOODS_REPLAY_CONFLICT');
expect(
(
await post(batch.batchId, {
...body,
idempotencyKey: randomUUID(),
}).expect(409)
).body.code,
).toBe('FINISHED_GOODS_ALREADY_POSTED');
const another = await ready();
const stock = await ctx.db.stockItem.create({
data: {
organizationId: ctx.owner.organizationId,
warehouseId: another.warehouseId,
variantId: another.variantId,
onHand: 2_000_000_000,
},
});
expect(
(
await post(another.batchId, {
warehouseId: another.warehouseId,
idempotencyKey: randomUUID(),
}).expect(409)
).body.code,
).toBe('FINISHED_GOODS_STOCK_CAPACITY');
expect(
await ctx.db.finishedGoodsReceipt.count({
where: { batchId: another.batchId },
}),
).toBe(0);
expect(
(await ctx.db.stockItem.findUniqueOrThrow({ where: { id: stock.id } }))
.onHand,
).toBe(2_000_000_000);
});
it('enforces permission, tenant scope and an immutable source receipt', async () => {
const batch = await ready();
const body = {
warehouseId: batch.warehouseId,
idempotencyKey: randomUUID(),
};
const reader = await secondActor(ctx, true, ['inventory.read']);
await ctx
.api()
.post(
`/api/v1/production-batches/${batch.batchId}/finished-goods-receipt`,
)
.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/${batch.batchId}/finished-goods-receipt`)
.auth(outsider.token, auth)
.expect(404);
const receipt = await post(batch.batchId, body).expect(201);
await expect(
ctx.db.finishedGoodsReceipt.update({
where: { id: receipt.body.id },
data: { quantity: 21 },
}),
).rejects.toThrow();
});
});