update file tài sản

This commit is contained in:
2026-09-21 10:06:27 +07:00
parent 2015c6fc16
commit a215b503c6
10 changed files with 1274 additions and 68 deletions

View File

@@ -0,0 +1,222 @@
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('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/);
});

View File

@@ -0,0 +1,258 @@
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');
// 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 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);
});
});

View File

@@ -0,0 +1,173 @@
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 fetch = async (url, options) => {
requests.push({ url, options });
return { ok: responseSuccess, json: async () => ({ success: responseSuccess, data: { archivedCount: 2 } }) };
};
const document = {
addEventListener() {},
getElementById: id => id === 'archiveAllAssetsBtn' ? button : 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 };
}
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 }),
borrow(4, { RequestType: 'return' })
];
assert.deepEqual(Array.from(manager.getFilteredAssetBorrows(), row => row.BorrowId), [1, 2, 3, 4]);
});
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('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/);
});