gititnore
This commit is contained in:
2
.gitignore
vendored
2
.gitignore
vendored
@@ -9,6 +9,6 @@ scripts
|
||||
.codex-server.out.log
|
||||
tmp
|
||||
outputs
|
||||
test
|
||||
test/
|
||||
tools
|
||||
|
||||
|
||||
@@ -1,148 +0,0 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
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 }] }));
|
||||
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(({ 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 }] }
|
||||
});
|
||||
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/);
|
||||
});
|
||||
@@ -1,290 +0,0 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { randomBytes } = require('node:crypto');
|
||||
const sql = require('mssql');
|
||||
const { ensureAssetArchiveSchema } = require('../backend/asset-archive-schema');
|
||||
const { ensureAssetExportDocumentSchema } = require('../backend/asset-export-documents');
|
||||
|
||||
// Explicit opt-in to a disposable, local SQL Server. Never read .env or reuse the
|
||||
// application's database configuration. The runner creates its own database.
|
||||
const integrationEnabled = process.env.ACCMANAGER_ARCHIVE_SQL_TEST === '1';
|
||||
const integrationOptions = {
|
||||
skip: integrationEnabled ? false : 'Set ACCMANAGER_ARCHIVE_SQL_TEST=1 to run against disposable local SQL Server',
|
||||
timeout: 120_000
|
||||
};
|
||||
|
||||
async function withTestDatabase(run) {
|
||||
const password = process.env.ACCMANAGER_ARCHIVE_TEST_SQL_PASSWORD;
|
||||
const port = Number(process.env.ACCMANAGER_ARCHIVE_TEST_SQL_PORT || 14339);
|
||||
assert.ok(password, 'ACCMANAGER_ARCHIVE_TEST_SQL_PASSWORD must be explicitly set');
|
||||
assert.ok(Number.isInteger(port) && port > 0 && port < 65536, 'Invalid local test SQL port');
|
||||
const database = `AccManagerArchiveTest_${Date.now()}_${randomBytes(6).toString('hex')}`;
|
||||
const config = {
|
||||
server: '127.0.0.1',
|
||||
port,
|
||||
user: 'sa',
|
||||
password,
|
||||
database: 'master',
|
||||
options: { encrypt: false, trustServerCertificate: true, enableArithAbort: true },
|
||||
pool: { min: 0, max: 1, idleTimeoutMillis: 1000 },
|
||||
connectionTimeout: 15_000,
|
||||
requestTimeout: 30_000
|
||||
};
|
||||
const admin = new sql.ConnectionPool(config);
|
||||
let created = false;
|
||||
let pool;
|
||||
try {
|
||||
await admin.connect();
|
||||
await admin.request().query(`CREATE DATABASE [${database}]`);
|
||||
created = true;
|
||||
pool = await new sql.ConnectionPool({ ...config, database }).connect();
|
||||
await run(pool);
|
||||
} finally {
|
||||
if (pool) await pool.close();
|
||||
try {
|
||||
if (created) {
|
||||
// This name is generated above, never accepted from the environment.
|
||||
assert.match(database, /^AccManagerArchiveTest_\d+_[a-f0-9]{12}$/);
|
||||
await admin.request().query(`ALTER DATABASE [${database}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE`);
|
||||
await admin.request().query(`DROP DATABASE [${database}]`);
|
||||
}
|
||||
} finally {
|
||||
await admin.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const legacySchema = `
|
||||
CREATE TABLE dbo.AssetInventory (
|
||||
AssetId INT IDENTITY PRIMARY KEY,
|
||||
AssetCode NVARCHAR(100) NOT NULL UNIQUE,
|
||||
AssetName NVARCHAR(255) NOT NULL,
|
||||
Quantity INT NOT NULL DEFAULT 0,
|
||||
EndingBalance INT NOT NULL DEFAULT 0
|
||||
);
|
||||
-- Exercise removal of both an auto-named constraint and a standalone index.
|
||||
CREATE UNIQUE INDEX LegacyAssetCodeIndex ON dbo.AssetInventory(AssetCode);
|
||||
CREATE TABLE dbo.AssetBorrowRequests (
|
||||
BorrowId INT IDENTITY PRIMARY KEY,
|
||||
AssetId INT NOT NULL REFERENCES dbo.AssetInventory(AssetId) ON DELETE CASCADE,
|
||||
RequestType NVARCHAR(20) NOT NULL,
|
||||
RequestStatus NVARCHAR(20) NOT NULL,
|
||||
BorrowerName NVARCHAR(100) NOT NULL,
|
||||
BorrowQuantity INT NOT NULL,
|
||||
ReturnedQuantity INT NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE TABLE dbo.AssetBorrowRequestLinks (
|
||||
LinkId INT IDENTITY PRIMARY KEY,
|
||||
BorrowId INT NOT NULL REFERENCES dbo.AssetBorrowRequests(BorrowId),
|
||||
ReturnId INT NOT NULL REFERENCES dbo.AssetBorrowRequests(BorrowId),
|
||||
Quantity INT NOT NULL
|
||||
);
|
||||
CREATE TABLE dbo.AssetExportHistory (
|
||||
ExportHistoryId INT IDENTITY PRIMARY KEY,
|
||||
AssetId INT NOT NULL REFERENCES dbo.AssetInventory(AssetId) ON DELETE CASCADE,
|
||||
ExportQuantity INT NOT NULL
|
||||
);
|
||||
CREATE TABLE dbo.AssetDamageDisposalHistory (
|
||||
DamageHistoryId INT IDENTITY PRIMARY KEY,
|
||||
AssetId INT NOT NULL REFERENCES dbo.AssetInventory(AssetId) ON DELETE CASCADE,
|
||||
ActionQuantity INT NOT NULL
|
||||
);
|
||||
`;
|
||||
|
||||
async function historySnapshot(pool) {
|
||||
return (await pool.request().query(`
|
||||
SELECT * FROM dbo.AssetBorrowRequests ORDER BY BorrowId;
|
||||
SELECT * FROM dbo.AssetBorrowRequestLinks ORDER BY LinkId;
|
||||
SELECT * FROM dbo.AssetExportHistory ORDER BY ExportHistoryId;
|
||||
SELECT * FROM dbo.AssetDamageDisposalHistory ORDER BY DamageHistoryId;
|
||||
`)).recordsets;
|
||||
}
|
||||
|
||||
test('SQL Server document migration preserves legacy rows and saved files across repeated startup and archiving', integrationOptions, async () => {
|
||||
await withTestDatabase(async pool => {
|
||||
await pool.request().batch(legacySchema);
|
||||
await pool.request().query(`
|
||||
INSERT dbo.AssetInventory (AssetCode, AssetName) VALUES ('TEST', N'Test asset');
|
||||
INSERT dbo.AssetExportHistory (AssetId, ExportQuantity) VALUES (1, 1);
|
||||
`);
|
||||
await ensureAssetArchiveSchema(pool);
|
||||
await ensureAssetExportDocumentSchema(pool);
|
||||
const oldRow = (await pool.request().query('SELECT * FROM dbo.AssetExportHistory')).recordset[0];
|
||||
assert.equal(oldRow.ExportDocumentId, null);
|
||||
const bytes = Buffer.from('original TEST workbook bytes');
|
||||
const documentId = 'f13b142b-913b-44b8-b15c-d719bd45d197';
|
||||
await pool.request().input('id', sql.UniqueIdentifier, documentId).input('bytes', sql.VarBinary(sql.MAX), bytes).query(`
|
||||
INSERT dbo.AssetExportDocuments (ExportDocumentId, FileName, MimeType, FileContent, SnapshotJson, ExportedDate)
|
||||
VALUES (@id, N'TEST.xlsx', N'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
@bytes, N'{"items":[]}', DATEADD(HOUR, 7, SYSUTCDATETIME()));
|
||||
INSERT dbo.AssetExportHistory (AssetId, ExportQuantity, ExportDocumentId) VALUES (1, 2, @id);
|
||||
UPDATE dbo.AssetInventory SET IsArchived = 1, AssetName = N'Changed asset' WHERE AssetId = 1;
|
||||
`);
|
||||
await ensureAssetArchiveSchema(pool);
|
||||
await ensureAssetExportDocumentSchema(pool);
|
||||
const saved = (await pool.request().query('SELECT * FROM dbo.AssetExportDocuments')).recordset;
|
||||
assert.equal(saved.length, 1);
|
||||
assert.deepEqual(saved[0].FileContent, bytes);
|
||||
assert.equal(saved[0].SnapshotJson, '{"items":[]}');
|
||||
assert.equal((await pool.request().query('SELECT COUNT(*) AS total FROM dbo.AssetExportHistory')).recordset[0].total, 2);
|
||||
await assert.rejects(pool.request().query('DELETE FROM dbo.AssetExportDocuments'), error => error.number === 547);
|
||||
});
|
||||
});
|
||||
|
||||
test('SQL Server migration preserves asset history across inventory replacement', integrationOptions, async t => {
|
||||
await withTestDatabase(async pool => {
|
||||
await pool.request().batch(legacySchema);
|
||||
await pool.request().query(`
|
||||
INSERT dbo.AssetInventory (AssetCode, AssetName, Quantity, EndingBalance) VALUES
|
||||
('SHARED-CODE', N'Original drill', 10, 6),
|
||||
('EXPORT-ONLY', N'Exported asset', 4, 3),
|
||||
('DISPOSAL-ONLY', N'Disposed asset', 3, 2);
|
||||
INSERT dbo.AssetBorrowRequests
|
||||
(AssetId, RequestType, RequestStatus, BorrowerName, BorrowQuantity, ReturnedQuantity)
|
||||
VALUES (1, 'borrow', 'approved', N'Loan owner', 5, 1),
|
||||
(1, 'return', 'approved', N'Loan owner', 1, 0);
|
||||
INSERT dbo.AssetBorrowRequestLinks (BorrowId, ReturnId, Quantity) VALUES (1, 2, 1);
|
||||
INSERT dbo.AssetExportHistory (AssetId, ExportQuantity) VALUES (2, 1);
|
||||
INSERT dbo.AssetDamageDisposalHistory (AssetId, ActionQuantity) VALUES (3, 1);
|
||||
`);
|
||||
const originalHistory = await historySnapshot(pool);
|
||||
|
||||
await t.test('legacy migration defaults existing assets to active and preserves every history row', async () => {
|
||||
await ensureAssetArchiveSchema(pool);
|
||||
const assets = (await pool.request().query('SELECT IsArchived, ArchivedDate FROM dbo.AssetInventory')).recordset;
|
||||
assert.equal(assets.length, 3);
|
||||
assert.ok(assets.every(asset => asset.IsArchived === false && asset.ArchivedDate === null));
|
||||
assert.deepEqual(await historySnapshot(pool), originalHistory);
|
||||
const keys = (await pool.request().query(`
|
||||
SELECT delete_referential_action AS action
|
||||
FROM sys.foreign_keys
|
||||
WHERE referenced_object_id = OBJECT_ID('dbo.AssetInventory')
|
||||
`)).recordset;
|
||||
assert.equal(keys.length, 3);
|
||||
assert.ok(keys.every(key => key.action === 0), 'All asset history foreign keys must prevent cascading deletes');
|
||||
});
|
||||
|
||||
await t.test('archiving inventory retains original asset identity and outstanding loan quantity', async () => {
|
||||
await pool.request().query(`
|
||||
UPDATE dbo.AssetInventory
|
||||
SET IsArchived = 1, ArchivedDate = DATEADD(HOUR, 7, SYSUTCDATETIME())
|
||||
WHERE IsArchived = 0;
|
||||
`);
|
||||
assert.deepEqual(await historySnapshot(pool), originalHistory);
|
||||
const result = await pool.request().query(`
|
||||
SELECT br.BorrowId, ai.AssetCode, ai.AssetName, ai.IsArchived, ai.ArchivedDate,
|
||||
br.BorrowQuantity - br.ReturnedQuantity AS OutstandingQuantity
|
||||
FROM dbo.AssetBorrowRequests br
|
||||
JOIN dbo.AssetInventory ai ON ai.AssetId = br.AssetId
|
||||
WHERE br.RequestType = 'borrow' AND br.RequestStatus = 'approved'
|
||||
AND br.BorrowQuantity > br.ReturnedQuantity;
|
||||
SELECT COUNT(*) AS ActiveCount FROM dbo.AssetInventory WHERE IsArchived = 0;
|
||||
`);
|
||||
assert.equal(result.recordsets[1][0].ActiveCount, 0);
|
||||
assert.equal(result.recordset.length, 1);
|
||||
assert.equal(result.recordset[0].OutstandingQuantity, 4);
|
||||
assert.equal(result.recordset[0].AssetName, 'Original drill');
|
||||
assert.equal(result.recordset[0].IsArchived, true);
|
||||
assert.ok(result.recordset[0].ArchivedDate instanceof Date);
|
||||
});
|
||||
|
||||
await t.test('same-code replacement receives a new identity without relinking old history', async () => {
|
||||
const inserted = await pool.request().query(`
|
||||
INSERT dbo.AssetInventory (AssetCode, AssetName, Quantity, EndingBalance)
|
||||
OUTPUT INSERTED.AssetId, INSERTED.IsArchived
|
||||
VALUES ('SHARED-CODE', N'Replacement drill', 20, 20);
|
||||
`);
|
||||
assert.notEqual(inserted.recordset[0].AssetId, 1);
|
||||
assert.equal(inserted.recordset[0].IsArchived, false);
|
||||
assert.deepEqual(await historySnapshot(pool), originalHistory);
|
||||
const assets = (await pool.request().query(`
|
||||
SELECT ai.AssetName, ai.IsArchived, COUNT(br.BorrowId) AS HistoryCount
|
||||
FROM dbo.AssetInventory ai
|
||||
LEFT JOIN dbo.AssetBorrowRequests br ON br.AssetId = ai.AssetId
|
||||
WHERE ai.AssetCode = 'SHARED-CODE'
|
||||
GROUP BY ai.AssetName, ai.IsArchived ORDER BY ai.IsArchived DESC;
|
||||
`)).recordset;
|
||||
assert.deepEqual(assets, [
|
||||
{ AssetName: 'Original drill', IsArchived: true, HistoryCount: 2 },
|
||||
{ AssetName: 'Replacement drill', IsArchived: false, HistoryCount: 0 }
|
||||
]);
|
||||
});
|
||||
|
||||
await t.test('active duplicates remain forbidden while repeated migration accepts archived duplicates', async () => {
|
||||
await assert.rejects(pool.request().query(`
|
||||
INSERT dbo.AssetInventory (AssetCode, AssetName) VALUES ('SHARED-CODE', N'Duplicate');
|
||||
`), error => [2601, 2627].includes(error.number));
|
||||
await ensureAssetArchiveSchema(pool);
|
||||
const indexes = (await pool.request().query(`
|
||||
SELECT name, has_filter AS HasFilter
|
||||
FROM sys.indexes WHERE object_id = OBJECT_ID('dbo.AssetInventory')
|
||||
AND is_unique = 1 AND is_primary_key = 0;
|
||||
`)).recordset;
|
||||
assert.deepEqual(indexes, [{ name: 'UX_AssetInventory_ActiveAssetCode', HasFilter: true }]);
|
||||
assert.deepEqual(await historySnapshot(pool), originalHistory);
|
||||
});
|
||||
|
||||
await t.test('physical deletion cannot cascade into loan, export, or disposal history', async () => {
|
||||
for (const assetId of [1, 2, 3]) {
|
||||
await assert.rejects(pool.request().input('id', sql.Int, assetId).query(`
|
||||
DELETE dbo.AssetInventory WHERE AssetId = @id;
|
||||
`), error => error.number === 547);
|
||||
}
|
||||
assert.deepEqual(await historySnapshot(pool), originalHistory);
|
||||
});
|
||||
|
||||
await t.test('returning an old loan updates only its archived asset ledger', async () => {
|
||||
const transaction = new sql.Transaction(pool);
|
||||
await transaction.begin();
|
||||
try {
|
||||
await new sql.Request(transaction).query(`
|
||||
UPDATE dbo.AssetInventory SET EndingBalance = EndingBalance + 2
|
||||
WHERE AssetId = (SELECT AssetId FROM dbo.AssetBorrowRequests WHERE BorrowId = 1);
|
||||
UPDATE dbo.AssetBorrowRequests SET ReturnedQuantity = ReturnedQuantity + 2 WHERE BorrowId = 1;
|
||||
INSERT dbo.AssetBorrowRequests
|
||||
(AssetId, RequestType, RequestStatus, BorrowerName, BorrowQuantity)
|
||||
VALUES (1, 'return', 'approved', N'Loan owner', 2);
|
||||
DECLARE @returnId INT = SCOPE_IDENTITY();
|
||||
INSERT dbo.AssetBorrowRequestLinks (BorrowId, ReturnId, Quantity) VALUES (1, @returnId, 2);
|
||||
`);
|
||||
await transaction.commit();
|
||||
} catch (error) {
|
||||
await transaction.rollback();
|
||||
throw error;
|
||||
}
|
||||
const result = await pool.request().query(`
|
||||
SELECT AssetName, EndingBalance FROM dbo.AssetInventory
|
||||
WHERE AssetCode = 'SHARED-CODE' ORDER BY IsArchived DESC;
|
||||
SELECT BorrowQuantity - ReturnedQuantity AS OutstandingQuantity
|
||||
FROM dbo.AssetBorrowRequests WHERE BorrowId = 1;
|
||||
SELECT SUM(Quantity) AS LinkedReturnedQuantity FROM dbo.AssetBorrowRequestLinks WHERE BorrowId = 1;
|
||||
`);
|
||||
assert.deepEqual(result.recordset, [
|
||||
{ AssetName: 'Original drill', EndingBalance: 8 },
|
||||
{ AssetName: 'Replacement drill', EndingBalance: 20 }
|
||||
]);
|
||||
assert.equal(result.recordsets[1][0].OutstandingQuantity, 2);
|
||||
assert.equal(result.recordsets[2][0].LinkedReturnedQuantity, 3);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('SQL Server archive migration rolls back partial DDL if active codes are already duplicated', integrationOptions, async () => {
|
||||
await withTestDatabase(async pool => {
|
||||
await pool.request().query(`
|
||||
CREATE TABLE dbo.AssetInventory (
|
||||
AssetId INT IDENTITY PRIMARY KEY,
|
||||
AssetCode NVARCHAR(100) NOT NULL
|
||||
);
|
||||
INSERT dbo.AssetInventory (AssetCode) VALUES ('DUPLICATE'), ('DUPLICATE');
|
||||
`);
|
||||
await assert.rejects(ensureAssetArchiveSchema(pool));
|
||||
const result = await pool.request().query(`
|
||||
SELECT COL_LENGTH('dbo.AssetInventory', 'IsArchived') AS ArchiveColumn,
|
||||
COL_LENGTH('dbo.AssetInventory', 'ArchivedDate') AS DateColumn;
|
||||
SELECT COUNT(*) AS AssetCount FROM dbo.AssetInventory;
|
||||
`);
|
||||
assert.deepEqual(result.recordset[0], { ArchiveColumn: null, DateColumn: null });
|
||||
assert.equal(result.recordsets[1][0].AssetCount, 2);
|
||||
});
|
||||
});
|
||||
@@ -1,214 +0,0 @@
|
||||
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 source = fs.readFileSync(path.join(__dirname, '../public/js/app.js'), 'utf8');
|
||||
|
||||
function fixture({ allowed = true, confirmed = true, responseSuccess = true } = {}) {
|
||||
const requests = [];
|
||||
const refreshed = [];
|
||||
const notifications = [];
|
||||
const button = { disabled: false };
|
||||
const archiveTableBody = { innerHTML: '' };
|
||||
const archiveCount = { textContent: '' };
|
||||
const fetch = async (url, options) => {
|
||||
requests.push({ url, options });
|
||||
return { ok: responseSuccess, json: async () => ({ success: responseSuccess, data: { archivedCount: 2 } }) };
|
||||
};
|
||||
const document = {
|
||||
addEventListener() {},
|
||||
getElementById: id => ({
|
||||
archiveAllAssetsBtn: button,
|
||||
archivedAssetBorrowsTableBody: archiveTableBody,
|
||||
archivedAssetBorrowsCount: archiveCount
|
||||
})[id] || null
|
||||
};
|
||||
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, {
|
||||
apiBase: '/api',
|
||||
assets: [{ AssetId: 1 }, { AssetId: 2 }],
|
||||
archivedAssets: [],
|
||||
assetBorrows: [],
|
||||
selectedAssetIds: new Set([1, 2]),
|
||||
canCurrentUserManageAssets: () => allowed,
|
||||
ensureAssetManagePermission: () => allowed,
|
||||
confirmBulkAssetDelete: async (count, all) => {
|
||||
assert.equal(count, 2);
|
||||
assert.equal(all, true);
|
||||
return confirmed;
|
||||
},
|
||||
refreshAssetsUI: async () => { refreshed.push('assets'); manager.assets = []; },
|
||||
refreshAssetBorrowsUI: async () => { refreshed.push('borrows'); },
|
||||
notifySuccess: message => notifications.push(message),
|
||||
notifyFailure: message => notifications.push(message),
|
||||
notifyWarning: message => notifications.push(message)
|
||||
});
|
||||
return { manager, requests, refreshed, notifications, button, archiveTableBody, archiveCount };
|
||||
}
|
||||
|
||||
function borrow(BorrowId, overrides = {}) {
|
||||
return {
|
||||
BorrowId, AssetId: BorrowId, AssetCode: 'SAME-CODE', AssetName: 'Máy đo',
|
||||
RequestType: 'borrow', RequestStatus: 'approved', BorrowQuantity: 5,
|
||||
ReturnedQuantity: 0, RemainingQuantity: 5, IsArchived: false,
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
test('all history retains completed loans and partial loans with related returns', () => {
|
||||
const { manager } = fixture();
|
||||
manager.assetBorrows = [
|
||||
borrow(1),
|
||||
borrow(2, { RelatedReturnCount: 1, ReturnedQuantity: 2, RemainingQuantity: 3 }),
|
||||
borrow(3, { RequestStatus: 'returned', ReturnedQuantity: 5, RemainingQuantity: 0, IsArchived: true }),
|
||||
borrow(4, { RequestType: 'return', IsArchived: true })
|
||||
];
|
||||
assert.deepEqual(Array.from(manager.getFilteredAssetBorrows(), row => row.BorrowId), [1, 2, 3, 4]);
|
||||
manager.assetBorrowCatalogFilter = 'archived';
|
||||
assert.deepEqual(Array.from(manager.getFilteredAssetBorrows(), row => row.BorrowId), [3, 4]);
|
||||
manager.assetBorrowSearchTerm = 'tài sản cũ';
|
||||
assert.deepEqual(Array.from(manager.getFilteredAssetBorrows(), row => row.BorrowId), [3, 4]);
|
||||
});
|
||||
|
||||
test('opening borrow and return page selects current catalog without changing an open page filter', () => {
|
||||
const { manager } = fixture();
|
||||
manager.currentPage = 'assets';
|
||||
manager.assetBorrowCatalogFilter = 'archived';
|
||||
manager.assetBorrowPage = 3;
|
||||
manager.renderView('asset-borrows');
|
||||
assert.equal(manager.assetBorrowCatalogFilter, 'current');
|
||||
assert.equal(manager.assetBorrowPage, 1);
|
||||
|
||||
manager.assetBorrowCatalogFilter = 'archived';
|
||||
manager.renderView('asset-borrows');
|
||||
assert.equal(manager.assetBorrowCatalogFilter, 'archived');
|
||||
});
|
||||
|
||||
test('outstanding loans include archived, partial, and pending-return loans, excluding other statuses', () => {
|
||||
const { manager } = fixture();
|
||||
manager.assetBorrowTypeFilter = 'outstanding';
|
||||
manager.assetBorrows = [
|
||||
borrow(1),
|
||||
borrow(2, { IsArchived: true, ReturnedQuantity: 2, RemainingQuantity: 3, RelatedReturnCount: 1 }),
|
||||
borrow(3, { IsArchived: 1, RelatedReturnCount: 1, AvailableReturnQuantity: 0 }),
|
||||
borrow(4, { RequestStatus: 'pending' }),
|
||||
borrow(5, { RequestStatus: 'rejected' }),
|
||||
borrow(6, { RequestStatus: 'returned' }),
|
||||
borrow(7, { RemainingQuantity: 0 }),
|
||||
borrow(8, { RequestType: 'return' })
|
||||
];
|
||||
assert.deepEqual(Array.from(manager.getFilteredAssetBorrows(), row => row.BorrowId), [1, 2, 3]);
|
||||
manager.assetBorrowCatalogFilter = 'archived';
|
||||
assert.deepEqual(Array.from(manager.getFilteredAssetBorrows(), row => row.BorrowId), [2, 3]);
|
||||
manager.assetBorrowCatalogFilter = 'current';
|
||||
assert.deepEqual(Array.from(manager.getFilteredAssetBorrows(), row => row.BorrowId), [1]);
|
||||
manager.assetBorrowSearchTerm = 'missing';
|
||||
assert.equal(manager.getFilteredAssetBorrows().length, 0);
|
||||
});
|
||||
|
||||
test('partial archived loans permit another return only for quantity not reserved by pending returns', () => {
|
||||
const { manager } = fixture();
|
||||
const partial = borrow(1, { IsArchived: true, RelatedReturnCount: 1, ReturnedQuantity: 2, RemainingQuantity: 3, AvailableReturnQuantity: 3 });
|
||||
assert.equal(manager.canCreateAssetReturnRequestFromBorrow(partial), true);
|
||||
assert.equal(manager.canCreateAssetReturnRequestFromBorrow({ ...partial, AvailableReturnQuantity: 0 }), false);
|
||||
assert.equal(manager.canCreateAssetReturnRequestFromBorrow({ ...partial, RequestStatus: 'pending' }), false);
|
||||
assert.match(manager.getArchivedAssetBadgeHtml(partial), /Tài sản cũ/);
|
||||
});
|
||||
|
||||
test('legacy borrower summaries remain visible without any borrow requests or current assets', () => {
|
||||
const { manager } = fixture();
|
||||
manager.assets = [];
|
||||
manager.archivedAssets = [
|
||||
{ AssetId: 1, AssetCode: 'REUSED', Borrower: [{ name: 'An', quantity: 2 }], ExportInPeriod: 2, IsArchived: true },
|
||||
{ AssetId: 2, AssetCode: 'REUSED', Borrower: '', ExportInPeriod: 3, IsArchived: true },
|
||||
{ AssetId: 3, AssetCode: 'DONE', Borrower: '', ExportInPeriod: 0, IsArchived: true }
|
||||
];
|
||||
assert.deepEqual(Array.from(manager.getArchivedOutstandingAssets(), row => row.AssetId), [1, 2]);
|
||||
manager.archivedAssetSearchTerm = 'An';
|
||||
assert.deepEqual(Array.from(manager.getArchivedOutstandingAssets(), row => row.AssetId), [1]);
|
||||
manager.getCurrentUserBorrowerNameKeys = () => ['an'];
|
||||
assert.deepEqual(Array.from(manager.getCurrentUserBorrowedAssets(), row => [row.AssetId, row.BorrowedQuantityByCurrentUser]), [[1, 2]]);
|
||||
});
|
||||
|
||||
test('old asset list includes every archived record, including assets with no outstanding borrower', () => {
|
||||
const { manager, archiveTableBody, archiveCount } = fixture();
|
||||
manager.archivedAssets = [
|
||||
{ AssetId: 1, AssetCode: 'BORROWED', AssetName: 'Máy đang mượn', Borrower: [{ name: 'An', quantity: 2 }], ExportInPeriod: 2, IsArchived: true },
|
||||
{ AssetId: 2, AssetCode: 'IN-STOCK', AssetName: 'Máy trong kho', Borrower: '', ExportInPeriod: 0, IsArchived: true },
|
||||
{ AssetId: 3, AssetCode: 'RETURNED', AssetName: 'Máy đã trả', Borrower: '', ExportInPeriod: 0, IsArchived: true }
|
||||
];
|
||||
assert.deepEqual(Array.from(manager.getFilteredArchivedAssets(), row => row.AssetId), [1, 2, 3]);
|
||||
manager.renderArchivedAssetBorrowsTable();
|
||||
assert.match(archiveTableBody.innerHTML, /BORROWED/);
|
||||
assert.match(archiveTableBody.innerHTML, /IN-STOCK/);
|
||||
assert.match(archiveTableBody.innerHTML, /RETURNED/);
|
||||
assert.match(archiveCount.textContent, /3/);
|
||||
manager.archivedAssetSearchTerm = 'trong kho';
|
||||
assert.deepEqual(Array.from(manager.getFilteredArchivedAssets(), row => row.AssetId), [2]);
|
||||
});
|
||||
|
||||
test('same-code current and archived assets remain separate in my borrowed assets', () => {
|
||||
const { manager } = fixture();
|
||||
manager.getCurrentUserBorrowerNameKeys = () => ['an'];
|
||||
manager.assets = [{ AssetId: 2, AssetCode: 'REUSED', Borrower: [{ name: 'An', quantity: 1 }] }];
|
||||
manager.archivedAssets = [{ AssetId: 1, AssetCode: 'REUSED', Borrower: [{ name: 'An', quantity: 3 }], IsArchived: true }];
|
||||
assert.deepEqual(Array.from(manager.getCurrentUserBorrowedAssets(), row => [row.AssetId, row.BorrowedQuantityByCurrentUser]), [[2, 1], [1, 3]]);
|
||||
});
|
||||
|
||||
test('archive all requires confirmation, calls archive endpoint once and refreshes both datasets', async () => {
|
||||
const { manager, requests, refreshed, button } = fixture();
|
||||
await manager.handleArchiveAllAssets();
|
||||
assert.equal(requests.length, 1);
|
||||
assert.equal(requests[0].url, '/api/assets/archive-all');
|
||||
assert.equal(requests[0].options.method, 'POST');
|
||||
assert.deepEqual(refreshed, ['assets', 'borrows']);
|
||||
assert.equal(manager.selectedAssetIds.size, 0);
|
||||
assert.equal(manager.assetPage, 1);
|
||||
assert.equal(manager.archivingAssets, false);
|
||||
assert.equal(button.disabled, true, 'Empty current catalog cannot be archived again');
|
||||
});
|
||||
|
||||
test('cancel or missing permission leaves the catalog untouched', async () => {
|
||||
for (const options of [{ confirmed: false }, { allowed: false }]) {
|
||||
const { manager, requests, refreshed } = fixture(options);
|
||||
await manager.handleArchiveAllAssets();
|
||||
assert.equal(requests.length, 0);
|
||||
assert.equal(refreshed.length, 0);
|
||||
assert.equal(manager.selectedAssetIds.size, 2);
|
||||
assert.equal(manager.assets.length, 2);
|
||||
}
|
||||
});
|
||||
|
||||
test('failed archive preserves current selection and supports retry', async () => {
|
||||
const { manager, requests, refreshed, notifications, button } = fixture({ responseSuccess: false });
|
||||
await manager.handleArchiveAllAssets();
|
||||
assert.equal(requests.length, 1);
|
||||
assert.equal(refreshed.length, 0);
|
||||
assert.equal(manager.selectedAssetIds.size, 2);
|
||||
assert.equal(manager.archivingAssets, false);
|
||||
assert.equal(button.disabled, false);
|
||||
assert.match(notifications[0], /thất bại/);
|
||||
});
|
||||
|
||||
test('archive double clicks issue one request while confirmation is pending', async () => {
|
||||
const { manager, requests } = fixture();
|
||||
let resolveConfirmation;
|
||||
manager.confirmBulkAssetDelete = () => new Promise(resolve => { resolveConfirmation = resolve; });
|
||||
const pending = manager.handleArchiveAllAssets();
|
||||
await manager.handleArchiveAllAssets();
|
||||
resolveConfirmation(true);
|
||||
await pending;
|
||||
assert.equal(requests.length, 1);
|
||||
});
|
||||
|
||||
test('archived pending borrows cannot be approved, while archived returns can', () => {
|
||||
const { manager } = fixture();
|
||||
const pending = borrow(1, { RequestStatus: 'pending', IsArchived: true });
|
||||
assert.doesNotMatch(manager.buildPendingAssetRequestCardHtml(pending), /asset-request-approve-btn/);
|
||||
assert.match(manager.buildPendingAssetRequestCardHtml(pending), /asset-request-reject-btn/);
|
||||
assert.match(manager.buildPendingAssetRequestCardHtml({ ...pending, RequestType: 'return' }), /asset-request-approve-btn/);
|
||||
});
|
||||
@@ -1,38 +0,0 @@
|
||||
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]]);
|
||||
});
|
||||
@@ -1,110 +0,0 @@
|
||||
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);
|
||||
});
|
||||
@@ -1,87 +0,0 @@
|
||||
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, /<Alpha>: <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);
|
||||
});
|
||||
@@ -1,101 +0,0 @@
|
||||
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: [] }), { workbookBuilder, userDisplayName = 'Borrower A' } = {}) {
|
||||
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) {
|
||||
if (name === 'mssql') return sql;
|
||||
if (name === 'dotenv') return { config() {} };
|
||||
if (name === './export-request-workbook' && workbookBuilder) {
|
||||
return { buildExportRequestWorkbook: workbookBuilder };
|
||||
}
|
||||
return 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() },
|
||||
testDisplayName: userDisplayName
|
||||
};
|
||||
vm.runInNewContext(`${serverSource}
|
||||
pool = testPool;
|
||||
getUserDisplayNameById = async () => testDisplayName;
|
||||
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,
|
||||
headers: {},
|
||||
setHeader(name, value) { this.headers[name] = value; return this; },
|
||||
type(value) { this.headers['Content-Type'] = value; return this; },
|
||||
attachment(value) { this.fileName = value; return this; },
|
||||
send(value) { this.body = value; return this; },
|
||||
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 };
|
||||
@@ -1,240 +0,0 @@
|
||||
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 appSource = fs.readFileSync(path.join(__dirname, '../public/js/app.js'), 'utf8');
|
||||
|
||||
// A small DOM fixture lets the actual event handler and cleanup methods run
|
||||
// without starting authentication, network requests, or the application itself.
|
||||
function createFixture() {
|
||||
const elements = [];
|
||||
const listeners = new Map();
|
||||
class Element {
|
||||
constructor({ id = '', classes = [], dataset = {}, parent = null } = {}) {
|
||||
this.id = id;
|
||||
this.dataset = dataset;
|
||||
this.parentElement = parent;
|
||||
this.children = [];
|
||||
this.value = '';
|
||||
this.isConnected = true;
|
||||
const names = new Set(classes);
|
||||
this.classList = {
|
||||
contains: name => names.has(name),
|
||||
add: (...added) => added.forEach(name => names.add(name)),
|
||||
remove: (...removed) => removed.forEach(name => names.delete(name))
|
||||
};
|
||||
if (parent) parent.children.push(this);
|
||||
elements.push(this);
|
||||
}
|
||||
matches(selector) {
|
||||
if (selector === '[data-close-modal]') return 'closeModal' in this.dataset;
|
||||
if (selector.startsWith('.')) {
|
||||
return selector.slice(1).split('.').every(name => this.classList.contains(name));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
closest(selector) {
|
||||
return this.matches(selector) ? this : this.parentElement?.closest(selector) || null;
|
||||
}
|
||||
getAttribute(name) {
|
||||
return name === 'data-close-modal' ? this.dataset.closeModal ?? null : null;
|
||||
}
|
||||
remove() {
|
||||
this.isConnected = false;
|
||||
this.children.forEach(child => child.remove());
|
||||
}
|
||||
set innerHTML(value) {
|
||||
assert.equal(value, '', 'The fixture only supports clearing an existing container');
|
||||
this.children.forEach(child => child.remove());
|
||||
this.children = [];
|
||||
}
|
||||
get innerHTML() {
|
||||
return this.children.length ? '<dialog />' : '';
|
||||
}
|
||||
}
|
||||
const document = {
|
||||
addEventListener(type, handler) {
|
||||
if (!listeners.has(type)) listeners.set(type, []);
|
||||
listeners.get(type).push(handler);
|
||||
},
|
||||
getElementById: id => elements.find(node => node.id === id && node.isConnected) || null,
|
||||
querySelectorAll: selector => elements.filter(node => node.isConnected && node.matches(selector)),
|
||||
contains: node => node.isConnected
|
||||
};
|
||||
const context = vm.createContext({
|
||||
document,
|
||||
Element,
|
||||
HTMLElement: Element,
|
||||
window: { fetch: async () => { throw new Error('Unexpected network request'); } },
|
||||
console
|
||||
});
|
||||
vm.runInContext(`${appSource}\napp = Object.create(AccountManager.prototype); globalThis.manager = app;`, context);
|
||||
const add = options => new Element(options);
|
||||
const modal = (id, parent) => add({ id, parent, classes: ['modal-backdrop', 'open'] });
|
||||
function dispatch(type, target, properties = {}) {
|
||||
const event = {
|
||||
target,
|
||||
defaultPrevented: false,
|
||||
preventDefault() { this.defaultPrevented = true; },
|
||||
stopPropagation() {},
|
||||
...properties
|
||||
};
|
||||
(listeners.get(type) || []).forEach(handler => handler(event));
|
||||
return event;
|
||||
}
|
||||
return { manager: context.manager, document, listeners, add, modal, dispatch };
|
||||
}
|
||||
|
||||
test('close buttons work after asynchronous modal insertion, including clicks on the icon', async () => {
|
||||
const fixture = createFixture();
|
||||
fixture.manager.setupModalCloseListeners();
|
||||
await Promise.resolve(); // modals.html is fetched after listeners are installed.
|
||||
const parent = fixture.modal('accountModal');
|
||||
const other = fixture.modal('assetModal');
|
||||
const button = fixture.add({ parent, dataset: { closeModal: 'accountModal' } });
|
||||
const icon = fixture.add({ parent: button });
|
||||
|
||||
const event = fixture.dispatch('click', icon);
|
||||
|
||||
assert.equal(parent.classList.contains('open'), false);
|
||||
assert.equal(other.classList.contains('open'), true);
|
||||
assert.equal(event.defaultPrevented, true);
|
||||
|
||||
parent.classList.add('open');
|
||||
fixture.dispatch('click', button);
|
||||
assert.equal(parent.classList.contains('open'), false);
|
||||
});
|
||||
|
||||
test('repeated setup installs one modal close handler', () => {
|
||||
const fixture = createFixture();
|
||||
fixture.manager.setupModalCloseListeners();
|
||||
fixture.manager.setupModalCloseListeners();
|
||||
const target = fixture.add({ dataset: { closeModal: 'accountModal' } });
|
||||
const closed = [];
|
||||
fixture.manager.closeModal = id => closed.push(id);
|
||||
|
||||
fixture.dispatch('click', target);
|
||||
|
||||
assert.deepEqual(closed, ['accountModal']);
|
||||
assert.equal(fixture.listeners.get('click').length, 1);
|
||||
});
|
||||
|
||||
test('backdrop clicks close their dialog, while clicks inside the form leave it open', () => {
|
||||
const fixture = createFixture();
|
||||
fixture.manager.setupModalCloseListeners();
|
||||
const modal = fixture.modal('assetModal');
|
||||
const other = fixture.modal('accountModal');
|
||||
const content = fixture.add({ parent: modal });
|
||||
const input = fixture.add({ parent: content });
|
||||
|
||||
fixture.dispatch('click', input);
|
||||
assert.equal(modal.classList.contains('open'), true);
|
||||
fixture.dispatch('click', modal);
|
||||
assert.equal(modal.classList.contains('open'), false);
|
||||
assert.equal(other.classList.contains('open'), true);
|
||||
});
|
||||
|
||||
test('canceling destructive confirmations resolves false exactly once', async () => {
|
||||
for (const [modalId, resolverField] of [
|
||||
['assetRequestDeleteConfirmModal', 'pendingAssetRequestDeleteConfirmResolver'],
|
||||
['bulkDeleteAssetsConfirmModal', 'pendingBulkAssetDeleteConfirmResolver']
|
||||
]) {
|
||||
const fixture = createFixture();
|
||||
fixture.manager.setupModalCloseListeners();
|
||||
const modal = fixture.modal(modalId);
|
||||
const button = fixture.add({ parent: modal, dataset: { closeModal: modalId } });
|
||||
const resolutions = [];
|
||||
const pending = new Promise(resolve => {
|
||||
fixture.manager[resolverField] = value => {
|
||||
resolutions.push(value);
|
||||
resolve(value);
|
||||
};
|
||||
});
|
||||
|
||||
fixture.dispatch('click', button);
|
||||
fixture.dispatch('click', button);
|
||||
|
||||
assert.equal(await pending, false);
|
||||
assert.deepEqual(resolutions, [false]);
|
||||
assert.equal(fixture.manager[resolverField], undefined);
|
||||
assert.equal(modal.classList.contains('open'), false);
|
||||
}
|
||||
});
|
||||
|
||||
test('closing consumable rejection and return dialogs clears pending input state', () => {
|
||||
const fixture = createFixture();
|
||||
const rejectModal = fixture.modal('consumableRequestRejectModal');
|
||||
const idInput = fixture.add({ id: 'consumableRequestRejectIdInput', parent: rejectModal });
|
||||
const reasonInput = fixture.add({ id: 'consumableRequestRejectReasonInput', parent: rejectModal });
|
||||
idInput.value = '42';
|
||||
reasonInput.value = 'Previous reason';
|
||||
fixture.manager.pendingConsumableRequestRejectId = 42;
|
||||
fixture.manager.closeModal(rejectModal.id);
|
||||
assert.equal(rejectModal.classList.contains('open'), false);
|
||||
assert.equal(idInput.value, '');
|
||||
assert.equal(reasonInput.value, '');
|
||||
assert.equal(fixture.manager.pendingConsumableRequestRejectId, undefined);
|
||||
|
||||
const returnModal = fixture.modal('consumableReturnModal');
|
||||
fixture.manager.pendingConsumableReturnHistoryId = 99;
|
||||
fixture.manager.closeModal(returnModal.id);
|
||||
assert.equal(returnModal.classList.contains('open'), false);
|
||||
assert.equal(fixture.manager.pendingConsumableReturnHistoryId, undefined);
|
||||
});
|
||||
|
||||
test('closing dynamic user, role, profile and detail dialogs clears their containers', () => {
|
||||
for (const modalId of ['userModal', 'roleModal', 'profileModal', 'userDetailsModal']) {
|
||||
const fixture = createFixture();
|
||||
fixture.manager.setupModalCloseListeners();
|
||||
const container = fixture.add({ id: `${modalId}Container` });
|
||||
const modal = fixture.modal(modalId, container);
|
||||
const button = fixture.add({ parent: modal, dataset: { closeModal: modalId } });
|
||||
|
||||
fixture.dispatch('click', button);
|
||||
|
||||
assert.equal(container.innerHTML, '', modalId);
|
||||
assert.equal(fixture.document.getElementById(modalId), null, modalId);
|
||||
}
|
||||
});
|
||||
|
||||
test('Escape closes dialogs through their cleanup handlers', () => {
|
||||
const fixture = createFixture();
|
||||
for (const method of [
|
||||
'updateAccountDisplay', 'setupAccountRowListeners', 'setupFilters',
|
||||
'setupResponsiveShell', 'closeMobileNav', 'closeNotificationPopover'
|
||||
]) fixture.manager[method] = () => {};
|
||||
fixture.manager.setupEventListeners();
|
||||
const confirmation = fixture.modal('bulkDeleteAssetsConfirmModal');
|
||||
let resolution;
|
||||
fixture.manager.pendingBulkAssetDeleteConfirmResolver = value => { resolution = value; };
|
||||
const container = fixture.add({ id: 'profileModalContainer' });
|
||||
fixture.modal('profileModal', container);
|
||||
const notification = fixture.modal('notificationComposerModal');
|
||||
|
||||
fixture.dispatch('keydown', null, { key: 'Escape' });
|
||||
|
||||
assert.equal(confirmation.classList.contains('open'), false);
|
||||
assert.equal(resolution, false);
|
||||
assert.equal(container.innerHTML, '');
|
||||
assert.equal(notification.isConnected, false);
|
||||
});
|
||||
|
||||
test('closing a missing modal is harmless', () => {
|
||||
const fixture = createFixture();
|
||||
assert.doesNotThrow(() => fixture.manager.closeModal('alreadyRemovedModal'));
|
||||
});
|
||||
|
||||
test('static and dynamic modal close controls avoid inline scripts and form submission', () => {
|
||||
for (const relativePath of ['public/modals.html', 'public/pages/index.html', 'public/js/app.js']) {
|
||||
const source = fs.readFileSync(path.join(__dirname, '..', relativePath), 'utf8');
|
||||
assert.doesNotMatch(source, /\bonclick\s*=\s*["'][^"']*\bclose\w*Modal\s*\(/i, relativePath);
|
||||
const closeButtons = [...source.matchAll(/<button\b[^>]*\bdata-close-modal\s*=\s*["'][^"']+["'][^>]*>/g)];
|
||||
if (relativePath !== 'public/pages/index.html') assert.ok(closeButtons.length > 0, relativePath);
|
||||
for (const [button] of closeButtons) {
|
||||
assert.match(button, /\btype\s*=\s*["']button["']/, `${relativePath}: ${button}`);
|
||||
assert.doesNotMatch(button, /\bonclick\s*=/, `${relativePath}: ${button}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1,162 +0,0 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
process.env.NODE_ENV = 'test';
|
||||
process.env.DATA_ENCRYPTION_SECRET = 'test-only-encryption-secret-with-more-than-32-characters';
|
||||
|
||||
const {
|
||||
app,
|
||||
encryptSensitiveValue,
|
||||
decryptSensitiveValue,
|
||||
hashSessionToken,
|
||||
normalizeOptionalHttpUrl,
|
||||
isPdfBuffer,
|
||||
sanitizeDocumentFileName,
|
||||
getDocumentContentDisposition,
|
||||
normalizeNotificationActionUrl,
|
||||
normalizeNotificationAudiences,
|
||||
normalizeNotificationSeverity
|
||||
} = require('../backend/server');
|
||||
|
||||
async function withTestServer(run) {
|
||||
const server = app.listen(0, '127.0.0.1');
|
||||
await new Promise((resolve, reject) => {
|
||||
server.once('listening', resolve);
|
||||
server.once('error', reject);
|
||||
});
|
||||
|
||||
try {
|
||||
const address = server.address();
|
||||
await run(`http://127.0.0.1:${address.port}`);
|
||||
} finally {
|
||||
await new Promise(resolve => server.close(resolve));
|
||||
}
|
||||
}
|
||||
|
||||
test('stored credentials use authenticated encryption and round-trip safely', () => {
|
||||
const plainText = 'example-password-value';
|
||||
const first = encryptSensitiveValue(plainText);
|
||||
const second = encryptSensitiveValue(plainText);
|
||||
|
||||
assert.match(first, /^enc:v2:/);
|
||||
assert.notEqual(first, second);
|
||||
assert.equal(first.includes(plainText), false);
|
||||
assert.equal(decryptSensitiveValue(first), plainText);
|
||||
assert.equal(decryptSensitiveValue(`${first}tampered`), null);
|
||||
});
|
||||
|
||||
test('session tokens are stored as deterministic SHA-256 hashes', () => {
|
||||
const token = 'a-private-random-session-token';
|
||||
const hash = hashSessionToken(token);
|
||||
|
||||
assert.match(hash, /^[a-f0-9]{64}$/);
|
||||
assert.equal(hash, hashSessionToken(token));
|
||||
assert.equal(hash.includes(token), false);
|
||||
});
|
||||
|
||||
test('application URLs accept only HTTP and HTTPS protocols', () => {
|
||||
assert.equal(normalizeOptionalHttpUrl(''), '');
|
||||
assert.equal(normalizeOptionalHttpUrl('javascript:alert(1)'), null);
|
||||
assert.equal(normalizeOptionalHttpUrl('file:///etc/passwd'), null);
|
||||
assert.match(normalizeOptionalHttpUrl('https://example.com/path'), /^https:\/\/example\.com\/path/);
|
||||
});
|
||||
|
||||
test('notification links stay inside the application', () => {
|
||||
assert.equal(normalizeNotificationActionUrl('#asset-borrows'), '#asset-borrows');
|
||||
assert.equal(normalizeNotificationActionUrl('/pages/index.html#notifications'), '/pages/index.html#notifications');
|
||||
assert.equal(normalizeNotificationActionUrl('https://attacker.example'), null);
|
||||
assert.equal(normalizeNotificationActionUrl('//attacker.example/path'), null);
|
||||
assert.equal(normalizeNotificationActionUrl('/\\attacker.example/path'), null);
|
||||
assert.equal(normalizeNotificationActionUrl('javascript:alert(1)'), null);
|
||||
});
|
||||
|
||||
test('notification audiences are normalized and deduplicated', () => {
|
||||
assert.deepEqual(normalizeNotificationAudiences([]), []);
|
||||
assert.deepEqual(normalizeNotificationAudiences([{ type: 'all' }]), [{ type: 'all', value: null }]);
|
||||
assert.deepEqual(normalizeNotificationAudiences([
|
||||
{ type: 'role', value: 'Admin' },
|
||||
{ type: 'role', value: 'admin' },
|
||||
{ type: 'user', value: '5' },
|
||||
{ type: 'user', value: 'invalid' }
|
||||
]), [
|
||||
{ type: 'role', value: 'admin' },
|
||||
{ type: 'user', value: '5' }
|
||||
]);
|
||||
assert.equal(normalizeNotificationSeverity('WARNING'), 'warning');
|
||||
assert.equal(normalizeNotificationSeverity('unknown'), 'info');
|
||||
});
|
||||
|
||||
test('PDF uploads require a PDF header and end-of-file marker', () => {
|
||||
assert.equal(isPdfBuffer(Buffer.from('%PDF-1.7\nbody\n%%EOF')), true);
|
||||
assert.equal(isPdfBuffer(Buffer.from('%PDF-1.7\nbody without trailer')), false);
|
||||
assert.equal(isPdfBuffer(Buffer.from('<html>not a pdf</html>')), false);
|
||||
});
|
||||
|
||||
test('document filenames and response headers cannot inject control characters', () => {
|
||||
const safeName = sanitizeDocumentFileName('bao/cao\r\nInjected: value');
|
||||
const longName = sanitizeDocumentFileName('a'.repeat(300));
|
||||
const disposition = getDocumentContentDisposition('Báo cáo tháng 8.pdf');
|
||||
|
||||
assert.equal(safeName, 'bao_caoInjected_ value.pdf');
|
||||
assert.equal(longName.length, 255);
|
||||
assert.match(longName, /\.pdf$/);
|
||||
assert.match(disposition, /^inline; filename="/);
|
||||
assert.match(disposition, /filename\*=UTF-8''/);
|
||||
assert.equal(disposition.includes('\r'), false);
|
||||
assert.equal(disposition.includes('\n'), false);
|
||||
});
|
||||
|
||||
test('forged legacy identity headers cannot bypass protected APIs', async () => {
|
||||
await withTestServer(async baseUrl => {
|
||||
const response = await fetch(`${baseUrl}/api/users`, {
|
||||
headers: {
|
||||
'x-user-id': '1',
|
||||
'x-user-role': 'admin'
|
||||
}
|
||||
});
|
||||
const body = await response.json();
|
||||
|
||||
assert.equal(response.status, 401);
|
||||
assert.equal(body.success, false);
|
||||
});
|
||||
});
|
||||
|
||||
test('saved export files, preview and batch exports require an authenticated session', async () => {
|
||||
await withTestServer(async baseUrl => {
|
||||
for (const [route, method] of [
|
||||
['/api/asset-export-documents/f13b142b-913b-44b8-b15c-d719bd45d197', 'GET'],
|
||||
['/api/asset-export-documents/f13b142b-913b-44b8-b15c-d719bd45d197/download', 'GET'],
|
||||
['/api/assets/export', 'POST']
|
||||
]) {
|
||||
const response = await fetch(baseUrl + route, { method, headers: { 'x-user-role': 'admin' } });
|
||||
assert.equal(response.status, 401);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test('security headers and no-store API caching are enabled', async () => {
|
||||
await withTestServer(async baseUrl => {
|
||||
const response = await fetch(`${baseUrl}/api/health`);
|
||||
|
||||
assert.equal(response.status, 200);
|
||||
assert.match(response.headers.get('content-security-policy') || '', /default-src 'self'/);
|
||||
assert.match(response.headers.get('content-security-policy') || '', /script-src-attr 'none'/);
|
||||
assert.equal(response.headers.get('x-powered-by'), null);
|
||||
assert.equal(response.headers.get('cache-control'), 'no-store');
|
||||
});
|
||||
});
|
||||
|
||||
test('state-changing requests from untrusted origins are rejected before route handling', async () => {
|
||||
await withTestServer(async baseUrl => {
|
||||
const response = await fetch(`${baseUrl}/api/auth/login`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Origin: 'https://attacker.example',
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({ username: 'test', password: 'not-a-real-password' })
|
||||
});
|
||||
|
||||
assert.equal(response.status, 403);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user