update quản lí dự án

This commit is contained in:
2026-09-23 15:54:40 +07:00
parent bd8ba94301
commit 3201a18fd4
15 changed files with 674 additions and 197 deletions

View File

@@ -1,90 +1,6 @@
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 };
}
const { createFixture } = require('./helpers/asset-route-fixture');
test('deleting an asset archives it without deleting any history or links', async () => {
const fixture = createFixture(() => ({ recordset: [{ AssetId: 17 }] }));
@@ -210,7 +126,7 @@ test('approving an archived return updates only its original inventory and borro
});
test('import matches the active version of a reused asset code only', async () => {
const fixture = createFixture(() => ({ recordset: [{ MergeAction: 'INSERT' }] }));
const fixture = createFixture(({ query }) => ({ recordset: query.includes('MERGE AssetInventory') ? [{ MergeAction: 'INSERT' }] : [] }));
const response = await fixture.invoke('post', '/api/assets/import', {
body: { rows: [{ assetCode: 'SAME-CODE', assetName: 'Replacement drill', model: 'D2', quantity: 5 }] }
});

View File

@@ -0,0 +1,38 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { normalizeExportAllocations, addAllocations, releaseAllocations } = require('../backend/asset-project-allocations');
test('multiple exports retain project quantities and normalize duplicate project rows', () => {
const rows = normalizeExportAllocations({ allocations: [
{ projectName: ' A ', quantity: 2 }, { projectName: 'B', quantity: 3 }, { projectName: 'a', quantity: '1' }
] });
assert.deepEqual(rows, [{ projectName: 'A', quantity: 3 }, { projectName: 'B', quantity: 3 }]);
const current = [{ projectName: 'Old', borrowerName: 'An', quantity: 2 }];
assert.equal(addAllocations(JSON.stringify(current), rows, 'Binh').reduce((sum, row) => sum + row.quantity, 0), 8);
assert.equal(current.length, 1);
});
test('invalid project quantities are rejected instead of silently rounded', () => {
for (const quantity of [0, -1, 1.5, '2abc', true, null, {}, 2147483648]) {
assert.throws(() => normalizeExportAllocations({ allocations: [{ projectName: 'A', quantity }] }));
}
for (const allocations of [[], null, {}, [{ quantity: 1 }], [{ projectName: 'x'.repeat(151), quantity: 1 }]]) {
assert.throws(() => normalizeExportAllocations({ allocations }));
}
assert.deepEqual(normalizeExportAllocations({ projectName: 'Legacy API', quantity: 2 }), [{ projectName: 'Legacy API', quantity: 2 }]);
});
test('returns consume unattributed loans then the borrower’s oldest project exports', () => {
const current = [
{ projectName: 'A', borrowerName: 'An', quantity: 2 },
{ projectName: 'B', borrowerName: 'An', quantity: 4 },
{ projectName: 'C', borrowerName: 'Binh', quantity: 3 }
];
assert.deepEqual(releaseAllocations(current, 'An', 2, 8), current);
assert.deepEqual(releaseAllocations(current, 'an', 5, 8), [
{ projectName: 'B', borrowerName: 'An', quantity: 3 },
{ projectName: 'C', borrowerName: 'Binh', quantity: 3 }
]);
assert.equal(current[0].quantity, 2);
assert.deepEqual(releaseAllocations(current, 'An', 8, 8), [current[2]]);
});

View File

@@ -0,0 +1,110 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { createFixture } = require('./helpers/asset-route-fixture');
function inventory(overrides = {}) {
return { AssetId: 17, AssetCode: 'A', AssetName: 'Drill', Quantity: 10, ImportInPeriod: 2,
ExportInPeriod: 2, EndingBalance: 10, NewQuantity: 8, UsedQuantity: 2, Borrower: 'An (2)',
ProjectAllocations: JSON.stringify([{ projectName: 'Old', borrowerName: 'An', quantity: 2 }]), ...overrides };
}
function exportFixture(asset = inventory(), failHistory = false) {
let historyId = 0;
return createFixture(({ query, inputs }) => {
if (query.includes('SELECT TOP 1') && query.includes('FROM AssetInventory')) return { recordset: [asset] };
if (query.includes('INSERT INTO AssetExportHistory')) {
if (failHistory) throw Error('test history failure');
return { recordset: [{ ExportHistoryId: ++historyId, ProjectName: inputs.projectName, ExportQuantity: inputs.exportQuantity }] };
}
return { recordset: [] };
});
}
const exportRequest = (allocations, extra = {}) => ({ params: { id: '17' }, body: { borrowerName: 'Binh', allocations, ...extra } });
test('one atomic export distributes to multiple projects and preserves prior allocations', async () => {
const fixture = exportFixture();
const response = await fixture.invoke('post', '/api/assets/:id/export', exportRequest([
{ projectName: 'A', quantity: 3 }, { projectName: 'B', quantity: 7 }
]));
assert.equal(response.statusCode, 200);
const write = fixture.queries.find(call => call.query.includes('UPDATE AssetInventory'));
assert.equal(write.inputs.exportInPeriod, 12);
assert.equal(write.inputs.endingBalance, 0);
assert.equal(write.inputs.newQuantity + write.inputs.usedQuantity, 0);
assert.equal(JSON.parse(write.inputs.projectAllocations).length, 3);
assert.doesNotMatch(write.query, /SET Project =/);
const histories = fixture.queries.filter(call => call.query.includes('INSERT INTO AssetExportHistory'));
assert.deepEqual(histories.map(call => [call.inputs.projectName, call.inputs.exportQuantity]), [['A', 3], ['B', 7]]);
assert.ok(fixture.queries.every(call => call.transaction === fixture.transactions[0]));
assert.match(fixture.queries[0].query, /UPDLOCK/);
assert.equal(fixture.transactions[0].committed, true);
});
test('combined project exports cannot exceed available stock or the inventory total', async () => {
for (const asset of [inventory(), inventory({ EndingBalance: 100 })]) {
const fixture = exportFixture(asset);
const response = await fixture.invoke('post', '/api/assets/:id/export', exportRequest([
{ projectName: 'A', quantity: 6 }, { projectName: 'B', quantity: 5 }
]));
assert.equal(response.statusCode, 400);
assert.equal(fixture.queries.length, 1);
assert.equal(fixture.transactions[0].rolledBack, true);
}
});
test('invalid export rows fail before opening a transaction', async () => {
for (const allocations of [[], [{ projectName: '', quantity: 1 }], [{ projectName: 'A', quantity: 1.5 }]]) {
const fixture = exportFixture();
assert.equal((await fixture.invoke('post', '/api/assets/:id/export', exportRequest(allocations))).statusCode, 400);
assert.equal(fixture.transactions.length, 0);
}
});
test('history insertion failure rolls back the entire multi-project export', async () => {
const fixture = exportFixture(inventory(), true);
const response = await fixture.invoke('post', '/api/assets/:id/export', exportRequest([{ projectName: 'A', quantity: 1 }]));
assert.equal(response.statusCode, 500);
assert.equal(fixture.transactions[0].rolledBack, true);
assert.equal(fixture.transactions[0].committed, undefined);
});
test('editing uses the locked export ledger and rejects total below already-issued quantity', async () => {
for (const quantity of [1, 15]) {
const fixture = createFixture(({ query }) => ({ recordset: query.includes('SELECT *') ? [inventory()] : [{ AssetId: 17 }] }));
const response = await fixture.invoke('put', '/api/assets/:id', {
params: { id: '17' }, body: { assetCode: 'A', model: 'Drill', quantity, exportInPeriod: 0, borrower: '' }
});
assert.equal(response.statusCode, quantity === 1 ? 400 : 200);
const write = fixture.queries.find(call => call.query.includes('UPDATE AssetInventory'));
if (quantity === 1) assert.equal(write, undefined);
else {
assert.equal(write.inputs.exportInPeriod, 2);
assert.equal(write.inputs.endingBalance, 13);
assert.equal(write.inputs.borrower, 'An (2)');
}
}
});
test('spreadsheet import cannot overwrite an active project allocation', async () => {
const fixture = createFixture(({ query }) => ({ recordset: query.includes('ProjectAllocations IS NOT NULL') ? [{ AssetId: 17 }] : [] }));
const response = await fixture.invoke('post', '/api/assets/import', {
body: { rows: [{ assetCode: 'A', assetName: 'Drill', model: 'D', quantity: 1 }] }
});
assert.equal(response.statusCode, 409);
assert.equal(fixture.transactions[0].rolledBack, true);
assert.ok(!fixture.queries.some(call => call.query.includes('MERGE AssetInventory')));
});
test('approved partial returns reduce only the borrower’s current project allocations', async () => {
const asset = inventory({ BorrowId: 41, RequestType: 'return', RequestStatus: 'pending',
BorrowerName: 'An', BorrowQuantity: 1, CreatedBy: 1, IsArchived: false });
const fixture = createFixture(({ query }) => ({ recordset: query.includes('WHERE br.BorrowId = @borrowId') ? [asset] : [] }));
const response = await fixture.invoke('post', '/api/asset-borrows/:id/process', { params: { id: '41' }, body: { action: 'approved' } });
assert.equal(response.statusCode, 200);
const write = fixture.queries.find(call => call.query.includes('UPDATE AssetInventory'));
assert.equal(JSON.parse(write.inputs.projectAllocations)[0].quantity, 1);
assert.equal(write.inputs.exportInPeriod, 1);
assert.equal(write.inputs.endingBalance, 11);
assert.equal(fixture.transactions[0].committed, true);
});

View File

@@ -0,0 +1,87 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const source = fs.readFileSync(require.resolve('../public/js/app.js'), 'utf8');
function fixture() {
const nodes = {
borrowAssetIdInput: { value: '17' }, borrowAssetUserInput: { value: 'An' },
borrowAssetProjectInput: { value: 'A' }, borrowQuantityInput: { value: '2' },
borrowAssetNoteInput: { value: '' }, borrowCurrentEndingInput: { value: '7' },
borrowAllocationSummary: { classList: { toggle() {} } }
};
const extra = [{ projectName: 'B', quantity: 3 }];
const tbody = { innerHTML: '' };
const button = { disabled: false };
const requests = [], warnings = [];
const fetch = async (url, options) => { requests.push({ url, options }); return { ok: true, json: async () => ({ success: true }) }; };
const document = {
addEventListener() {}, getElementById: id => nodes[id] || null,
querySelector: selector => selector === '.assets-table-body' ? tbody : selector.includes('button[type="submit"]') ? button : null,
querySelectorAll: selector => selector.includes('borrow-project-row') ? extra.map(row => ({ querySelector: kind => ({ value: kind === 'select' ? row.projectName : String(row.quantity) }) })) : []
};
const context = vm.createContext({ document, window: { fetch }, fetch, console });
vm.runInContext(`${source}\napp = Object.create(AccountManager.prototype); globalThis.manager = app;`, context);
const manager = context.manager;
Object.assign(manager, {
assets: [{ AssetId: 17, AssetCode: 'D', AssetName: 'Drill', Quantity: 10, ImportInPeriod: 0,
ExportInPeriod: 3, EndingBalance: 7, Unit: 'cái', Project: 'Last project',
ProjectAllocations: JSON.stringify([{ projectName: '<Alpha>', borrowerName: 'An', quantity: 1 },
{ projectName: 'Beta', borrowerName: 'Binh', quantity: 2 }]) }],
assetPage: 1, assetPageSize: 20, selectedAssetIds: new Set(), apiBase: '/api',
ensureAssetManagePermission: () => true, canCurrentUserManageAssets: () => true,
getAuthHeaders: () => ({}), notifyWarning: message => warnings.push(message),
notifyFailure: message => warnings.push(message), notifySuccess() {}, closeModals() {},
refreshAssetsUI: async () => {}, setupAssetRowListeners() {}, setupAssetPagerListeners() {}
});
return { manager, nodes, extra, requests, warnings, tbody, button };
}
test('initial table, refreshed table and mobile show all projects with escaped names and quantities', () => {
const { manager, tbody } = fixture();
for (const html of [manager.getAssetsContent(), manager.getAssetMobileCardHtml(manager.assets[0], 1, true)]) {
assert.match(html, /&lt;Alpha&gt;: <strong>1<\/strong>/);
assert.match(html, /Beta: <strong>2<\/strong>/);
assert.doesNotMatch(html, /<Alpha>/);
}
manager.renderAssetsTableBody();
assert.match(tbody.innerHTML, /Beta: <strong>2<\/strong>/);
manager.assetSearchTerm = 'alpha';
assert.equal(manager.getFilteredAssets().length, 1);
});
test('unknown legacy exports are explicit and zero outstanding exports show no project', () => {
const { manager } = fixture();
const asset = { Quantity: 5, ExportInPeriod: 3, Project: 'Last project' };
assert.match(manager.formatAssetProjectsText(asset), /Chưa xác định dự án: 3/);
assert.doesNotMatch(manager.formatAssetProjectsText(asset), /Last project/);
assert.equal(manager.formatAssetProjectsHtml({ ...asset, ExportInPeriod: 0 }), '-');
});
test('export form submits every project in a single request and updates combined total', async () => {
const { manager, requests, nodes, button } = fixture();
manager.updateBorrowAllocationSummary();
assert.match(nodes.borrowAllocationSummary.textContent, /Tổng xuất: 5 \/ 7/);
assert.match(nodes.borrowAllocationSummary.textContent, /Còn lại: 2/);
await manager.handleBorrowAssetSubmit({ preventDefault() {} });
assert.equal(requests.length, 1);
assert.deepEqual(JSON.parse(requests[0].options.body).allocations, [{ projectName: 'A', quantity: 2 }, { projectName: 'B', quantity: 3 }]);
assert.equal(button.disabled, false);
});
test('form rejects missing projects, fractional quantities and combined over-allocation', async () => {
for (const row of [{ projectName: '', quantity: 1 }, { projectName: 'B', quantity: 1.5 }, { projectName: 'B', quantity: 6 }]) {
const { manager, requests, extra, warnings } = fixture();
extra[0] = row;
await manager.handleBorrowAssetSubmit({ preventDefault() {} });
assert.equal(requests.length, 0);
assert.equal(warnings.length, 1);
}
});
test('available quantity is capped by total even when an imported balance is inflated', () => {
const { manager } = fixture();
manager.assets[0].EndingBalance = 100;
assert.equal(manager.getAssetAvailableForExport(manager.assets[0]), 7);
});

View File

@@ -0,0 +1,88 @@
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 };
}
module.exports = { createFixture };