233 lines
11 KiB
JavaScript
233 lines
11 KiB
JavaScript
const test = require('node:test');
|
|
const assert = require('node:assert/strict');
|
|
const fs = require('node:fs');
|
|
const path = require('node:path');
|
|
const vm = require('node:vm');
|
|
const { createRequire } = require('node:module');
|
|
|
|
const serverPath = path.resolve(__dirname, '../backend/server.js');
|
|
const serverSource = fs.readFileSync(serverPath, 'utf8');
|
|
const serverRequire = createRequire(serverPath);
|
|
|
|
// Run the real route handlers with an isolated pool so these regressions do not
|
|
// need credentials or alter a developer's inventory.
|
|
function createFixture(answer = () => ({ recordset: [] })) {
|
|
const queries = [];
|
|
const transactions = [];
|
|
class Request {
|
|
constructor(transaction) {
|
|
this.transaction = transaction;
|
|
this.inputs = {};
|
|
}
|
|
input(name, _type, value) {
|
|
this.inputs[name] = value;
|
|
return this;
|
|
}
|
|
async query(query) {
|
|
const call = { query, inputs: this.inputs, transaction: this.transaction };
|
|
queries.push(call);
|
|
return answer(call);
|
|
}
|
|
}
|
|
class Transaction {
|
|
constructor() { transactions.push(this); }
|
|
async begin() { this.begun = true; }
|
|
async commit() { this.committed = true; }
|
|
async rollback() { this.rolledBack = true; }
|
|
}
|
|
const sql = { ...serverRequire('mssql'), Request, Transaction };
|
|
const module = { exports: {} };
|
|
const context = {
|
|
require(name) { return name === 'mssql' ? sql : serverRequire(name); },
|
|
module,
|
|
exports: module.exports,
|
|
__dirname: path.dirname(serverPath),
|
|
__filename: serverPath,
|
|
Buffer,
|
|
URL,
|
|
console,
|
|
process: {
|
|
env: {
|
|
...process.env,
|
|
NODE_ENV: 'test',
|
|
DATA_ENCRYPTION_SECRET: 'test-only-archive-key-with-more-than-32-characters'
|
|
},
|
|
on() {}
|
|
},
|
|
testPool: { request: () => new Request() }
|
|
};
|
|
vm.runInNewContext(`${serverSource}
|
|
pool = testPool;
|
|
getUserDisplayNameById = async () => 'Borrower A';
|
|
safeCreateSystemNotification = async () => {};
|
|
ensureDepartmentExists = async () => {};
|
|
syncAssetDepartmentsFromInventory = async () => {};
|
|
syncAssetProjectsFromInventory = async () => {};
|
|
`, context, { filename: serverPath });
|
|
|
|
async function invoke(method, routePath, overrides = {}) {
|
|
const route = module.exports.app.router.stack.find(layer => (
|
|
layer.route?.path === routePath && layer.route.methods[method]
|
|
)).route;
|
|
const handler = route.stack.at(-1).handle;
|
|
const req = {
|
|
params: {}, query: {}, body: {},
|
|
user: { UserId: 1, Role: 'asset', FullName: 'Borrower A' },
|
|
...overrides
|
|
};
|
|
const response = {
|
|
statusCode: 200,
|
|
status(value) { this.statusCode = value; return this; },
|
|
json(value) { this.body = value; return this; }
|
|
};
|
|
await handler(req, response);
|
|
return response;
|
|
}
|
|
return { invoke, queries, transactions };
|
|
}
|
|
|
|
test('deleting an asset archives it without deleting any history or links', async () => {
|
|
const fixture = createFixture(() => ({ recordset: [{ AssetId: 17 }] }));
|
|
const response = await fixture.invoke('delete', '/api/assets/:id', { params: { id: '17' } });
|
|
assert.equal(response.statusCode, 200);
|
|
assert.equal(fixture.queries.length, 1);
|
|
assert.match(fixture.queries[0].query, /SET IsArchived = 1/);
|
|
assert.match(fixture.queries[0].query, /WHERE AssetId = @assetId AND IsArchived = 0/);
|
|
assert.doesNotMatch(fixture.queries[0].query, /DELETE\s/i);
|
|
assert.equal(fixture.queries[0].inputs.assetId, 17);
|
|
assert.equal(fixture.transactions[0].committed, true);
|
|
});
|
|
|
|
test('bulk archive changes only active inventory and reports the committed count', async () => {
|
|
const fixture = createFixture(() => ({ recordset: [{ ArchivedCount: 42 }] }));
|
|
const response = await fixture.invoke('post', '/api/assets/archive-all');
|
|
assert.equal(response.body.data.archivedCount, 42);
|
|
assert.equal(fixture.queries.length, 1);
|
|
assert.match(fixture.queries[0].query, /WITH \(UPDLOCK, HOLDLOCK\)/);
|
|
assert.match(fixture.queries[0].query, /WHERE IsArchived = 0/);
|
|
assert.doesNotMatch(fixture.queries[0].query, /DELETE\s|AssetBorrowRequestLinks/i);
|
|
assert.equal(fixture.transactions[0].committed, true);
|
|
});
|
|
|
|
test('current and archived inventory are selected separately', async () => {
|
|
const fixture = createFixture();
|
|
await fixture.invoke('get', '/api/assets');
|
|
await fixture.invoke('get', '/api/assets', { query: { archived: '1' } });
|
|
assert.equal(fixture.queries[0].inputs.isArchived, 0);
|
|
assert.equal(fixture.queries[1].inputs.isArchived, 1);
|
|
for (const call of fixture.queries) {
|
|
assert.match(call.query, /WHERE IsArchived = @isArchived/);
|
|
assert.match(call.query, /IsArchived, ArchivedDate/);
|
|
}
|
|
});
|
|
|
|
test('borrow and return history includes requests linked to archived assets', async () => {
|
|
const oldBorrow = { BorrowId: 21, AssetId: 17, RequestType: 'borrow', IsArchived: true };
|
|
const oldReturn = { BorrowId: 22, AssetId: 17, RequestType: 'return', IsArchived: true };
|
|
const fixture = createFixture(() => ({ recordset: [oldBorrow, oldReturn] }));
|
|
const response = await fixture.invoke('get', '/api/asset-borrows');
|
|
assert.deepEqual(Array.from(response.body.data, row => row.BorrowId), [21, 22]);
|
|
assert.match(fixture.queries[0].query, /FROM AssetBorrowRequests br\s+LEFT JOIN AssetInventory ai ON ai.AssetId = br.AssetId/);
|
|
assert.doesNotMatch(fixture.queries[0].query, /WHERE\s+(?:br\.|ai\.)?IsArchived\s*=\s*0/i);
|
|
});
|
|
|
|
test('new borrow requests cannot target an archived asset', async () => {
|
|
const fixture = createFixture(() => ({ recordset: [{
|
|
AssetId: 17, IsArchived: true, Quantity: 10, EndingBalance: 7,
|
|
Borrower: 'Borrower A - so luong: 3'
|
|
}] }));
|
|
const response = await fixture.invoke('post', '/api/asset-borrows', {
|
|
body: { assetId: 17, requestType: 'borrow', quantity: 1 }
|
|
});
|
|
assert.equal(response.statusCode, 409);
|
|
assert.equal(fixture.transactions[0].rolledBack, true);
|
|
assert.equal(fixture.queries.length, 1);
|
|
assert.match(fixture.queries[0].query, /UPDLOCK, HOLDLOCK/);
|
|
});
|
|
|
|
test('pending borrow approval is blocked after its inventory was archived', async () => {
|
|
const fixture = createFixture(() => ({ recordset: [{
|
|
BorrowId: 21, AssetId: 17, IsArchived: true,
|
|
RequestType: 'borrow', RequestStatus: 'pending', BorrowQuantity: 1
|
|
}] }));
|
|
const response = await fixture.invoke('post', '/api/asset-borrows/:id/process', {
|
|
params: { id: '21' }, body: { action: 'approved' }
|
|
});
|
|
assert.equal(response.statusCode, 409);
|
|
assert.equal(fixture.transactions[0].rolledBack, true);
|
|
assert.equal(fixture.queries.length, 1);
|
|
});
|
|
|
|
test('return creation for an archived borrow retains the original asset and link', async () => {
|
|
const fixture = createFixture(({ query }) => {
|
|
if (query.includes('SELECT TOP 1')) return { recordset: [{
|
|
BorrowId: 21, AssetId: 17, IsArchived: true, RequestType: 'borrow',
|
|
RequestStatus: 'approved', BorrowerName: 'Borrower A', BorrowQuantity: 3,
|
|
ReturnedQuantity: 1, ActiveReturnQuantity: 1, Unit: 'cai', CreatedBy: 1,
|
|
Borrower: 'Borrower A - so luong: 2'
|
|
}] };
|
|
if (query.includes('SCOPE_IDENTITY')) return { recordset: [{ BorrowId: 22 }] };
|
|
return { recordset: [] };
|
|
});
|
|
const response = await fixture.invoke('post', '/api/asset-borrows/:id/return', {
|
|
params: { id: '21' }
|
|
});
|
|
assert.equal(response.statusCode, 200);
|
|
const insert = fixture.queries.find(call => call.query.includes('INSERT INTO AssetBorrowRequests'));
|
|
assert.equal(insert.inputs.assetId, 17);
|
|
assert.equal(insert.inputs.borrowQuantity, 2);
|
|
const link = fixture.queries.find(call => call.query.includes('INSERT INTO AssetBorrowRequestLinks'));
|
|
assert.equal(link.inputs.borrowId, 21);
|
|
assert.equal(link.inputs.returnId, 22);
|
|
assert.equal(fixture.transactions[0].committed, true);
|
|
});
|
|
|
|
test('approving an archived return updates only its original inventory and borrow', async () => {
|
|
const fixture = createFixture(({ query }) => {
|
|
if (query.includes('SELECT TOP 1')) return { recordset: [{
|
|
BorrowId: 22, AssetId: 17, IsArchived: true, RequestType: 'return',
|
|
RequestStatus: 'pending', BorrowerName: 'Borrower A', BorrowQuantity: 2,
|
|
Quantity: 10, ImportInPeriod: 0, ExportInPeriod: 2, EndingBalance: 8,
|
|
NewQuantity: 8, UsedQuantity: 0, Borrower: 'Borrower A - so luong: 2', CreatedBy: 1
|
|
}] };
|
|
if (query.includes('FROM AssetBorrowRequestLinks links')) {
|
|
return { recordset: [{ BorrowId: 21, Quantity: 2, BorrowQuantity: 3, ReturnedQuantity: 1 }] };
|
|
}
|
|
return { recordset: [] };
|
|
});
|
|
const response = await fixture.invoke('post', '/api/asset-borrows/:id/process', {
|
|
params: { id: '22' }, body: { action: 'approved' }
|
|
});
|
|
assert.equal(response.statusCode, 200);
|
|
const inventoryWrites = fixture.queries.filter(call => call.query.includes('UPDATE AssetInventory'));
|
|
assert.equal(inventoryWrites.length, 1);
|
|
assert.equal(inventoryWrites[0].inputs.assetId, 17);
|
|
assert.equal(inventoryWrites[0].inputs.borrower, null);
|
|
const borrowWrite = fixture.queries.find(call => call.query.includes('SET ReturnedQuantity'));
|
|
assert.equal(borrowWrite.inputs.borrowId, 21);
|
|
assert.equal(borrowWrite.inputs.quantity, 2);
|
|
assert.equal(fixture.transactions[0].committed, true);
|
|
});
|
|
|
|
test('import matches the active version of a reused asset code only', async () => {
|
|
const fixture = createFixture(() => ({ recordset: [{ MergeAction: 'INSERT' }] }));
|
|
const response = await fixture.invoke('post', '/api/assets/import', {
|
|
body: { rows: [{ assetCode: 'SAME-CODE', assetName: 'Replacement drill', model: 'D2', quantity: 5 }] }
|
|
});
|
|
assert.equal(response.statusCode, 200);
|
|
assert.equal(response.body.data.inserted, 1);
|
|
const merge = fixture.queries.find(call => call.query.includes('MERGE AssetInventory'));
|
|
assert.match(merge.query, /WITH \(HOLDLOCK\)/);
|
|
assert.match(merge.query, /ON target.AssetCode = source.AssetCode AND target.IsArchived = 0/);
|
|
assert.equal(merge.inputs.assetCode, 'SAME-CODE');
|
|
});
|
|
|
|
test('editing an archived asset cannot modify the historical inventory', async () => {
|
|
const fixture = createFixture();
|
|
const response = await fixture.invoke('put', '/api/assets/:id', {
|
|
params: { id: '17' }, body: { assetCode: 'SAME-CODE', assetName: 'Modified', model: 'D2' }
|
|
});
|
|
assert.equal(response.statusCode, 404);
|
|
assert.match(fixture.queries[0].query, /WHERE AssetId = @assetId AND IsArchived = 0/);
|
|
});
|