291 lines
15 KiB
JavaScript
291 lines
15 KiB
JavaScript
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);
|
|
});
|
|
});
|