manicanldes-backend/test/material-warehouse-transfer...

239 lines
7.4 KiB
TypeScript

import { randomUUID } from 'node:crypto';
import { identityApp, type IdentityApp } from './helpers/identity-app';
import { secondActor } from './helpers/commerce';
import { receiveAccepted, seedPurchaseOrder } from './helpers/procurement';
describe('material warehouse transfers', () => {
let ctx: IdentityApp;
const auth = { type: 'bearer' as const };
const warehouse = async () =>
(
await ctx
.api()
.post('/api/v1/inventory/warehouses')
.auth(ctx.token, auth)
.send({ name: `Transfer ${randomUUID().slice(0, 8)}` })
.expect(201)
).body.id as string;
const post = (body: object) =>
ctx
.api()
.post('/api/v1/inventory/material-transfers')
.auth(ctx.token, auth)
.send(body);
const ready = async () => {
const order = await seedPurchaseOrder(ctx);
const line = await ctx.db.purchaseOrderLine.findUniqueOrThrow({
where: { id: order.lineId },
});
const receipt = await receiveAccepted(ctx, order, '1.000');
const fromWarehouseId = await warehouse();
const toWarehouseId = await warehouse();
await ctx
.api()
.post(`/api/v1/goods-receipts/${receipt.id}/stock-posting`)
.auth(ctx.token, auth)
.send({ warehouseId: fromWarehouseId, idempotencyKey: randomUUID() })
.expect(201);
const source = await ctx.db.materialStockItem.findFirstOrThrow({
where: { materialId: line.materialId, warehouseId: fromWarehouseId },
});
return {
materialId: line.materialId,
fromWarehouseId,
toWarehouseId,
sourceId: source.id,
};
};
const request = (
data: Awaited<ReturnType<typeof ready>>,
quantity = '0.600',
) => ({
materialId: data.materialId,
fromWarehouseId: data.fromWarehouseId,
toWarehouseId: data.toWarehouseId,
quantity,
idempotencyKey: randomUUID(),
});
beforeAll(async () => {
ctx = await identityApp();
}, 60000);
afterAll(async () => {
await ctx?.close();
});
beforeEach(async () => {
await ctx.clearLimits();
});
it('conserves material across warehouses and exposes both ledger entries', async () => {
const data = await ready();
const body = request(data);
const transfer = await post(body).expect(201);
expect(transfer.body).toMatchObject({
materialId: data.materialId,
fromWarehouseId: data.fromWarehouseId,
toWarehouseId: data.toWarehouseId,
quantity: '0.600',
});
expect(
transfer.body.entries
.map((entry: { kind: string; delta: string }) => [
entry.kind,
entry.delta,
])
.sort(),
).toEqual([
['TRANSFER_IN', '0.600'],
['TRANSFER_OUT', '-0.600'],
]);
const source = await ctx.db.materialStockItem.findUniqueOrThrow({
where: { id: data.sourceId },
});
const destination = await ctx.db.materialStockItem.findUniqueOrThrow({
where: { id: transfer.body.toStockItemId },
});
expect(source.onHand.toFixed(3)).toBe('0.400');
expect(destination.onHand.toFixed(3)).toBe('0.600');
expect((await post(body).expect(201)).body.id).toBe(transfer.body.id);
expect(
(
await ctx
.api()
.get(`/api/v1/inventory/material-transfers/${transfer.body.id}`)
.auth(ctx.token, auth)
.expect(200)
).body.id,
).toBe(transfer.body.id);
const listing = await ctx
.api()
.get(`/api/v1/inventory/material-transfers?materialId=${data.materialId}`)
.auth(ctx.token, auth)
.expect(200);
expect(
listing.body.some((item: { id: string }) => item.id === transfer.body.id),
).toBe(true);
});
it('rejects changed retries, an empty quantity and the same warehouse', async () => {
const data = await ready();
const body = request(data, '0.001');
await post(body).expect(201);
expect(
(await post({ ...body, quantity: '0.002' }).expect(409)).body.code,
).toBe('MATERIAL_TRANSFER_REPLAY_CONFLICT');
await post({ ...request(data), quantity: '0.000' }).expect(400);
expect(
(
await post({
...request(data),
toWarehouseId: data.fromWarehouseId,
}).expect(400)
).body.code,
).toBe('MATERIAL_TRANSFER_SAME_WAREHOUSE');
});
it('rejects insufficient source stock and destination overflow atomically', async () => {
const data = await ready();
const short = await post(request(data, '1.001')).expect(409);
expect(short.body.code).toBe('MATERIAL_TRANSFER_INSUFFICIENT');
expect(
await ctx.db.materialStockTransfer.count({
where: { materialId: data.materialId },
}),
).toBe(0);
const destination = await ctx.db.materialStockItem.create({
data: {
organizationId: ctx.owner.organizationId,
materialId: data.materialId,
warehouseId: data.toWarehouseId,
onHand: '999999999.700',
},
});
const capacity = await post(request(data, '0.500')).expect(409);
expect(capacity.body.code).toBe('MATERIAL_TRANSFER_DESTINATION_CAPACITY');
expect(
(
await ctx.db.materialStockItem.findUniqueOrThrow({
where: { id: data.sourceId },
})
).onHand.toFixed(3),
).toBe('1.000');
expect(
(
await ctx.db.materialStockItem.findUniqueOrThrow({
where: { id: destination.id },
})
).onHand.toFixed(3),
).toBe('999999999.700');
expect(
await ctx.db.materialStockTransfer.count({
where: { materialId: data.materialId },
}),
).toBe(0);
});
it('requires scoped warehouses and prevents cross-organization reads or writes', async () => {
const data = await ready();
expect(
(
await post({ ...request(data), fromWarehouseId: randomUUID() }).expect(
404,
)
).body.code,
).toBe('MATERIAL_TRANSFER_SOURCE_WAREHOUSE_NOT_FOUND');
expect(
(
await post({ ...request(data), toWarehouseId: randomUUID() }).expect(
404,
)
).body.code,
).toBe('MATERIAL_TRANSFER_DESTINATION_WAREHOUSE_NOT_FOUND');
const reader = await secondActor(ctx, true, ['inventory.read']);
await ctx
.api()
.post('/api/v1/inventory/material-transfers')
.auth(reader.token, auth)
.send(request(data))
.expect(403);
const transfer = await post(request(data)).expect(201);
const outsider = await secondActor(ctx, false, [
'inventory.read',
'inventory.manage',
]);
await ctx
.api()
.get(`/api/v1/inventory/material-transfers/${transfer.body.id}`)
.auth(outsider.token, auth)
.expect(404);
await ctx
.api()
.get('/api/v1/inventory/material-transfers')
.auth(outsider.token, auth)
.expect(200, []);
await ctx
.api()
.post('/api/v1/inventory/material-transfers')
.auth(outsider.token, auth)
.send(request(data))
.expect(404);
});
it('keeps the transfer and ledger immutable in PostgreSQL', async () => {
const data = await ready();
const transfer = await post(request(data)).expect(201);
await expect(
ctx.db.materialStockTransfer.update({
where: { id: transfer.body.id },
data: { quantity: '0.100' },
}),
).rejects.toThrow();
await expect(
ctx.db.materialStockLedger.update({
where: { id: transfer.body.entries[0].id },
data: { delta: '0.100' },
}),
).rejects.toThrow();
});
});