Files
ManagerAccount/backend/robot-bom.test.js
2026-11-02 15:09:59 +07:00

213 lines
13 KiB
JavaScript

const test = require('node:test');
const assert = require('node:assert/strict');
const { normalizeLines, quantity } = require('./robot-bom');
const { createBomFixture } = require('./robot-bom-test-fixture');
const line = extra => ({ name: 'Động cơ servo 400W', model: 'SV-400', unit: 'cái', quantity: 2,
sourceInfo: 'https://example.com/servo', notes: '', ...extra });
async function fixture(t, options) {
const f = createBomFixture(options);
const server = f.app.listen(0, '127.0.0.1');
await new Promise(resolve => server.once('listening', resolve));
t.after(() => { server.closeAllConnections(); return new Promise(resolve => server.close(resolve)); });
f.request = async (suffix = '', method = 'GET', body) => {
const response = await fetch(`http://127.0.0.1:${server.address().port}/api/robot-boms${suffix}`, { method,
...(body === undefined ? {} : { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }) });
return { status: response.status, ...(response.headers.get('content-type')?.includes('application/json')
? await response.json() : { message: await response.text() }) };
};
return f;
}
test('BOM stores editable names/models, quantities and supplier sources without touching inventory', async t => {
const f = await fixture(t);
const created = await f.request('', 'POST', { robotId: 1 });
assert.equal(created.status, 201);
const id = created.data.BomId;
const saved = await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line()] });
assert.equal(saved.status, 200); assert.equal(saved.data.LockVersion, 2);
const reopened = await f.request(`/${id}`);
assert.equal(reopened.data.Lines[0].Name, 'Động cơ servo 400W');
assert.equal(reopened.data.Lines[0].Model, 'SV-400');
assert.equal(reopened.data.Lines[0].SourceInfo, 'https://example.com/servo');
assert.equal(reopened.data.Lines[0].SourceId, null);
assert.equal(reopened.data.Lines[0].SourceType, 'manual');
const revisions = await f.request('?model=AMR-500&typeId=1');
assert.equal(revisions.data[0].LineCount, 1);
assert.equal(f.queries.some(({ query }) => /\b(?:AssetInventory|ConsumableInventory)\b/i.test(query)), false);
});
test('asset picker exposes names/models with no stock quantities, including assets with zero stock', async t => {
const f = await fixture(t);
f.state.catalog[0].Available = 0;
const result = await f.request('/catalog');
assert.equal(result.status, 200); assert.equal(result.data.length, 3);
assert.deepEqual(Object.keys(result.data[0]).sort(), ['Code', 'Id', 'Model', 'Name', 'Unit']);
assert.doesNotMatch(f.queries[0].query, /EndingBalance|Quantity|Available/);
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
assert.equal((await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line({ quantity: 2000 })] })).status, 200);
assert.equal(f.state.catalog[0].Available, 0);
});
test('publishing freezes the saved snapshot; copying produces an editable independent revision', async t => {
const f = await fixture(t);
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
assert.equal((await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line()] })).status, 200);
assert.equal((await f.request(`/${id}/publish`, 'POST', { lockVersion: 2 })).status, 200);
assert.equal((await f.request(`/${id}`, 'PUT', { lockVersion: 3, lines: [] })).status, 409);
assert.equal((await f.request(`/${id}/publish`, 'POST', { lockVersion: 3 })).status, 409);
f.state.catalog[0].Name = 'New inventory name';
const snapshot = await f.request(`/${id}`);
assert.equal(snapshot.data.Lines[0].Name, 'Động cơ servo 400W');
const copied = await f.request('', 'POST', { robotId: 1, copyFromId: id });
assert.equal(copied.data.Revision, 2); assert.equal(copied.data.Status, 'draft');
await f.request(`/${copied.data.BomId}`, 'PUT', { lockVersion: 1, lines: [line({ quantity: 3 })] });
assert.equal((await f.request(`/${id}`)).data.Lines[0].Quantity, 2);
assert.equal((await f.request(`/${copied.data.BomId}`)).data.Lines[0].Quantity, 3);
assert.equal((await f.request(`/${copied.data.BomId}`)).data.Lines[0].SourceInfo, 'https://example.com/servo');
});
test('concurrent stale saves are rejected without overwriting newer quantities', async t => {
const f = await fixture(t);
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line()] });
assert.equal((await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line({ quantity: 99 })] })).status, 409);
assert.equal((await f.request(`/${id}/publish`, 'POST', { lockVersion: 1 })).status, 409);
assert.equal((await f.request(`/${id}`)).data.Lines[0].Quantity, 2);
});
test('an insert failure rolls back a complete BOM save including deleted old lines', async t => {
let fail = false;
const f = await fixture(t, { failQuery: query => fail && query.includes('INSERT dbo.RobotBomLines') });
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line()] });
fail = true;
assert.equal((await f.request(`/${id}`, 'PUT', { lockVersion: 2, lines: [line({ quantity: 3 })] })).status, 500);
assert.equal((await f.request(`/${id}`)).data.Lines[0].Quantity, 2);
assert.equal((await f.request(`/${id}`)).data.LockVersion, 2);
assert.equal(f.transactions.at(-1).rolledBack, true);
});
test('external parts and supplier descriptions work without any inventory records', async t => {
const f = await fixture(t);
f.state.catalog = [];
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
const lines = [line({ name: 'Khung gia công bên ngoài', model: 'CUSTOM-01', quantity: 12, sourceInfo: 'Nhà sản xuất: Cơ khí ABC, liên hệ bộ phận kỹ thuật' }), { name: 'Bulong M6' }];
assert.equal((await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines })).status, 200);
const saved = (await f.request(`/${id}`)).data.Lines;
assert.equal(saved[0].Quantity, 12); assert.equal(saved[1].Quantity, 1);
assert.equal(saved[0].SourceInfo, lines[0].sourceInfo);
assert.equal((await f.request(`/${id}/publish`, 'POST', { lockVersion: 2 })).status, 200);
assert.equal((await f.request('/requirements/check', 'POST', {})).status, 404);
assert.equal(f.queries.some(({ query }) => /Inventory/.test(query)), false);
});
test('viewers can read BOMs and descriptive asset choices but cannot create, edit, publish or delete', async t => {
const f = await fixture(t, { role: 'user' });
for (const suffix of ['/models', '/catalog', '?model=AMR-500&typeId=1']) assert.equal((await f.request(suffix)).status, 200);
for (const [suffix, method] of [['', 'POST'], ['/1', 'PUT'], ['/1/publish', 'POST'], ['/1', 'DELETE']]) assert.equal((await f.request(suffix, method, { robotId: 1 })).status, 403);
assert.equal(f.transactions.length, 0);
});
for (const role of ['admin', 'asset']) {
for (const released of [false, true]) {
test(`${role} can delete a ${released ? 'released' : 'draft'} BOM with its lines while preserving copied revisions and inventory`, async t => {
const f = await fixture(t, { role });
const catalog = structuredClone(f.state.catalog);
const models = structuredClone(f.state.models);
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line()] });
if (released) await f.request(`/${id}/publish`, 'POST', { lockVersion: 2 });
const copiedId = (await f.request('', 'POST', { copyFromId: id })).data.BomId;
const result = await f.request(`/${id}`, 'DELETE', { lockVersion: released ? 3 : 2 });
assert.equal(result.status, 200); assert.equal(result.success, true);
assert.equal((await f.request(`/${id}`)).status, 404);
assert.equal(f.state.lines.some(item => item.BomId === id), false);
assert.deepEqual((await f.request('?model=AMR-500&typeId=1')).data.map(item => item.BomId), [copiedId]);
assert.equal((await f.request(`/${copiedId}`)).data.Lines[0].Quantity, 2);
assert.deepEqual(f.state.catalog, catalog); assert.deepEqual(f.state.models, models);
const deletes = f.queries.filter(({ query }) => query.startsWith('DELETE'));
assert.equal(deletes.at(-1).transaction, deletes.at(-2).transaction);
assert.equal(f.transactions.at(-1).committed, true);
});
}
}
test('deletion rejects stale or invalid versions and invalid or missing BOM identifiers', async t => {
const f = await fixture(t);
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line()] });
assert.equal((await f.request(`/${id}`, 'DELETE', { lockVersion: 1 })).status, 409);
for (const lockVersion of [undefined, 0, -1, 'invalid']) {
assert.equal((await f.request(`/${id}`, 'DELETE', { lockVersion })).status, 400);
}
for (const badId of ['abc', '0', '-1', '2147483648']) {
assert.equal((await f.request(`/${badId}`, 'DELETE', { lockVersion: 2 })).status, 400);
}
assert.equal((await f.request('/999', 'DELETE', { lockVersion: 2 })).status, 404);
assert.equal((await f.request(`/${id}`)).data.Lines[0].Quantity, 2);
assert.equal(f.queries.some(({ query }) => query.startsWith('DELETE FROM dbo.RobotBomRevisions')), false);
});
test('a header deletion failure rolls back removed BOM lines and allows retry', async t => {
let fail = true;
const f = await fixture(t, { failQuery: query => fail && query.includes('DELETE FROM dbo.RobotBomRevisions') });
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line()] });
assert.equal((await f.request(`/${id}`, 'DELETE', { lockVersion: 2 })).status, 500);
assert.equal(f.transactions.at(-1).rolledBack, true);
const retained = (await f.request(`/${id}`)).data;
assert.equal(retained.LockVersion, 2); assert.equal(retained.Lines[0].Quantity, 2);
fail = false;
assert.equal((await f.request(`/${id}`, 'DELETE', { lockVersion: 2 })).status, 200);
assert.equal((await f.request(`/${id}`, 'DELETE', { lockVersion: 2 })).status, 404);
});
test('deleting the final historical BOM removes its orphaned model and supports an empty BOM', async t => {
const f = await fixture(t);
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
f.state.models = [];
assert.equal((await f.request('/models')).data.length, 1);
assert.equal((await f.request(`/${id}`, 'DELETE', { lockVersion: 1 })).status, 200);
assert.deepEqual((await f.request('/models')).data, []);
assert.deepEqual((await f.request('?model=AMR-500&typeId=1')).data, []);
});
test('bad identifiers, empty publications, invalid lines and unsafe quantities are rejected', async t => {
const f = await fixture(t);
assert.equal((await f.request('/abc')).status, 400);
assert.equal((await f.request('/999')).status, 404);
assert.equal((await f.request('', 'POST', { robotId: 999 })).status, 404);
assert.equal((await f.request('', 'POST')).status, 400);
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
assert.equal((await f.request(`/${id}/publish`, 'POST', { lockVersion: 1 })).status, 400);
for (const bad of [null, [null], [line({ name: '' })], [line({ name: ' '.repeat(2) })], [line({ model: 'x'.repeat(256) })], [line({ sourceInfo: 'x'.repeat(1001) })], [line({ quantity: -1 })], [line({ quantity: 0.5 })], Array(501).fill(line())]) {
assert.equal((await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: bad })).status, 400);
}
for (const value of [0, -1, 100001, 'NaN', Infinity, '1e4', 0.00001]) assert.throws(() => quantity(value, 'm'));
assert.equal(quantity(0.125, 'm'), 0.125);
});
test('a name alone is sufficient; inventory identity is discarded while descriptive metadata is retained', () => {
const normalized = normalizeLines([{ name: 'Cảm biến ngoài', sourceType: 'asset', sourceId: 999 }])[0];
assert.equal(normalized.Name, 'Cảm biến ngoài'); assert.equal(normalized.Quantity, 1);
assert.equal(normalized.Model, ''); assert.equal(normalized.Unit, '');
assert.equal(normalized.SourceType, 'manual'); assert.equal(normalized.SourceId, null);
assert.equal(normalizeLines([line(), line()]).length, 2);
assert.equal(normalizeLines([line({ unit: '', quantity: 0.125 })])[0].Quantity, 0.125);
assert.deepEqual(normalizeLines([]), []);
});
test('historical models and revisions remain accessible after their last robot is removed', async t => {
const f = await fixture(t);
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line()] });
f.state.models = [];
const models = await f.request('/models');
assert.equal(models.data[0].Model, 'AMR-500'); assert.equal(models.data[0].RobotId, null);
assert.equal((await f.request('?model=AMR-500&typeId=1')).data.length, 1);
const copied = await f.request('', 'POST', { copyFromId: id });
assert.equal(copied.status, 201); assert.equal(copied.data.Revision, 2);
assert.equal((await f.request(`/${copied.data.BomId}`)).data.Lines.length, 1);
});