update quản lí dự án

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

View File

@@ -0,0 +1,56 @@
// Current allocations are separate from the immutable export history and the
// legacy Project metadata. Never guess a project for old, unattributed loans.
function parseAllocations(value) {
const rows = typeof value === 'string' ? JSON.parse(value || '[]') : (value || []);
if (!Array.isArray(rows)) throw new Error('Invalid asset project allocations');
return rows.map(row => ({
projectName: String(row.projectName || '').trim(),
borrowerName: String(row.borrowerName || '').trim(),
quantity: Number(row.quantity)
})).filter(row => row.projectName && Number.isSafeInteger(row.quantity) && row.quantity > 0);
}
function normalizeExportAllocations(body = {}) {
const rows = body.allocations === undefined
? [{ projectName: body.projectName, quantity: body.quantity }]
: body.allocations;
if (!Array.isArray(rows) || !rows.length || rows.length > 100) {
throw new Error('Vui lòng chọn từ 1 đến 100 dòng dự án.');
}
const result = [];
for (const row of rows) {
const projectName = String(row?.projectName || '').trim();
const quantity = Number(row?.quantity);
if (!projectName || projectName.length > 150) throw new Error('Tên dự án là bắt buộc, tối đa 150 ký tự.');
if (!['number', 'string'].includes(typeof row?.quantity) || !Number.isSafeInteger(quantity) || quantity <= 0 || quantity > 2147483647) {
throw new Error('Số lượng xuất cho mỗi dự án phải là số nguyên dương.');
}
const existing = result.find(item => item.projectName.toLowerCase() === projectName.toLowerCase());
if (existing) existing.quantity += quantity;
else result.push({ projectName, quantity });
}
if (result.reduce((sum, row) => sum + row.quantity, 0) > 2147483647) throw new Error('Tổng số lượng xuất quá lớn.');
return result;
}
function addAllocations(current, rows, borrowerName) {
// Keep export order so unlinked returns can consume the oldest export first.
return [...parseAllocations(current), ...rows.map(row => ({ ...row, borrowerName }))];
}
function releaseAllocations(current, borrowerName, returnedQuantity, borrowerOutstanding) {
const rows = parseAllocations(current);
const matches = row => row.borrowerName.toLowerCase() === borrowerName.toLowerCase();
const attributed = rows.filter(matches).reduce((sum, row) => sum + row.quantity, 0);
// Older loans without a project (including request-based loans) are consumed first.
let remaining = Math.max(returnedQuantity - Math.max(borrowerOutstanding - attributed, 0), 0);
for (const row of rows) {
if (!matches(row)) continue;
const taken = Math.min(row.quantity, remaining);
row.quantity -= taken;
remaining -= taken;
}
return rows.filter(row => row.quantity > 0);
}
module.exports = { parseAllocations, normalizeExportAllocations, addAllocations, releaseAllocations };

View File

@@ -13,6 +13,7 @@ const dotenv = require('dotenv');
const helmet = require('helmet');
const { rateLimit } = require('express-rate-limit');
const { ensureAssetArchiveSchema } = require('./asset-archive-schema');
const { parseAllocations, normalizeExportAllocations, addAllocations, releaseAllocations } = require('./asset-project-allocations');
dotenv.config();
@@ -3125,6 +3126,10 @@ async function createTables() {
// Fail startup if history preservation cannot be installed.
await ensureAssetArchiveSchema(pool);
await pool.request().query(`
IF COL_LENGTH('dbo.AssetInventory', 'ProjectAllocations') IS NULL
ALTER TABLE dbo.AssetInventory ADD ProjectAllocations NVARCHAR(MAX) NULL;
`);
// Ensure notification indexes exist for audience lookup and unread counts.
try {
@@ -6510,6 +6515,7 @@ app.post('/api/asset-borrows/:id/process', requireAssetOrAdmin, async (req, res)
ai.UsedQuantity,
ai.Status,
ai.Borrower,
ai.ProjectAllocations,
ai.Unit AS AssetUnit
FROM AssetBorrowRequests br WITH (UPDLOCK, HOLDLOCK)
INNER JOIN AssetInventory ai WITH (UPDLOCK, HOLDLOCK) ON ai.AssetId = br.AssetId
@@ -6549,7 +6555,9 @@ app.post('/api/asset-borrows/:id/process', requireAssetOrAdmin, async (req, res)
0
);
const baseEndingBalance = parseOptionalNonNegativeInteger(targetRequest.EndingBalance);
const endingBalance = baseEndingBalance !== null ? baseEndingBalance : derivedEndingBalance;
const currentExport = Math.max(currentBorrowed, parseNonNegativeInteger(targetRequest.ExportInPeriod, 0));
const availableFromTotal = Math.max(parseNonNegativeInteger(targetRequest.Quantity, 0) + parseNonNegativeInteger(targetRequest.ImportInPeriod, 0) - currentExport, 0);
const endingBalance = Math.min(baseEndingBalance ?? derivedEndingBalance, availableFromTotal);
const baseNewQuantity = parseOptionalNonNegativeInteger(targetRequest.NewQuantity);
const baseUsedQuantity = parseOptionalNonNegativeInteger(targetRequest.UsedQuantity);
const stockBuckets = normalizeAssetStockBuckets(
@@ -6585,7 +6593,7 @@ app.post('/api/asset-borrows/:id/process', requireAssetOrAdmin, async (req, res)
const nextEndingBalance = Math.max(endingBalance - requestQuantity, 0);
const nextNewQuantity = Math.max(stockBuckets.newQuantity - borrowFromNew, 0);
const nextUsedQuantity = Math.max(stockBuckets.usedQuantity - borrowFromUsed, 0);
const nextBorrowingQuantity = currentBorrowed + requestQuantity;
const nextBorrowingQuantity = currentExport + requestQuantity;
const nextStatus = resolveAssetStatusFromStock(nextEndingBalance, nextBorrowingQuantity);
await new sql.Request(transaction)
@@ -6624,10 +6632,16 @@ app.post('/api/asset-borrows/:id/process', requireAssetOrAdmin, async (req, res)
});
}
const borrowerOutstanding = parseBorrowerEntries(targetRequest.Borrower)
.filter(row => row.name.toLowerCase() === borrowerName.toLowerCase())
.reduce((sum, row) => sum + row.quantity, 0);
const projectAllocations = releaseAllocations(targetRequest.ProjectAllocations, borrowerName, requestQuantity, borrowerOutstanding);
const borrowerSummary = decreased.summary || null;
const remainingBorrowed = decreased.entries.reduce((sum, entry) => (
sum + parseNonNegativeInteger(entry?.quantity, 0)
), 0);
const remainingBorrowed = Math.max(
decreased.entries.reduce((sum, entry) => sum + parseNonNegativeInteger(entry?.quantity, 0), 0),
parseNonNegativeInteger(targetRequest.ExportInPeriod, 0) - requestQuantity,
projectAllocations.reduce((sum, row) => sum + row.quantity, 0)
);
const quantity = parseNonNegativeInteger(targetRequest.Quantity, 0);
const importInPeriod = parseNonNegativeInteger(targetRequest.ImportInPeriod, 0);
const derivedEndingBalance = Math.max(quantity + importInPeriod - parseNonNegativeInteger(targetRequest.ExportInPeriod, 0), 0);
@@ -6650,6 +6664,7 @@ app.post('/api/asset-borrows/:id/process', requireAssetOrAdmin, async (req, res)
await new sql.Request(transaction)
.input('assetId', sql.Int, targetRequest.AssetId)
.input('borrower', sql.NVarChar, borrowerSummary)
.input('projectAllocations', sql.NVarChar(sql.MAX), JSON.stringify(projectAllocations))
.input('exportInPeriod', sql.Int, remainingBorrowed)
.input('endingBalance', sql.Int, nextEndingBalance)
.input('newQuantity', sql.Int, nextBuckets.newQuantity)
@@ -6659,6 +6674,7 @@ app.post('/api/asset-borrows/:id/process', requireAssetOrAdmin, async (req, res)
.query(`
UPDATE AssetInventory
SET Borrower = @borrower,
ProjectAllocations = @projectAllocations,
ExportInPeriod = @exportInPeriod,
EndingBalance = @endingBalance,
NewQuantity = @newQuantity,
@@ -8435,7 +8451,7 @@ app.get('/api/assets', async (req, res) => {
SELECT AssetId, IsArchived, ArchivedDate, AssetCode, AssetName, Model, SerialNumber,
Quantity, ImportInPeriod, ExportInPeriod, EndingBalance,
NewQuantity, UsedQuantity,
Unit, Department, Project, Location, Custodian, Borrower, ExportedBy,
Unit, Department, Project, ProjectAllocations, Location, Custodian, Borrower, ExportedBy,
PurchaseDate, PurchasePrice,
CASE
WHEN ISNULL(EndingBalance, 0) <= 0 THEN 'exported'
@@ -8544,7 +8560,7 @@ app.get('/api/assets/:id', async (req, res) => {
SELECT AssetId, AssetCode, AssetName, Model, SerialNumber,
Quantity, ImportInPeriod, ExportInPeriod, EndingBalance,
NewQuantity, UsedQuantity,
Unit, Department, Project, Location, Custodian, Borrower, ExportedBy,
Unit, Department, Project, ProjectAllocations, Location, Custodian, Borrower, ExportedBy,
PurchaseDate, PurchasePrice,
CASE
WHEN ISNULL(EndingBalance, 0) <= 0 THEN 'exported'
@@ -8889,9 +8905,11 @@ app.post('/api/assets/:id/export', requireAssetOrAdmin, async (req, res) => {
let transaction;
try {
const assetId = Number(req.params.id);
const exportQuantity = parseNonNegativeInteger(req.body?.quantity, 0);
let allocations;
try { allocations = normalizeExportAllocations(req.body); }
catch (err) { return res.status(400).json({ success: false, message: err.message }); }
const exportQuantity = allocations.reduce((sum, row) => sum + row.quantity, 0);
const borrowerName = String(req.body?.borrowerName || req.body?.custodianName || '').trim();
const projectName = String(req.body?.projectName || '').trim() || null;
const exportNote = String(req.body?.note || '').trim() || null;
const createdBy = getUserIdFromRequest(req);
const exportedByName = await getUserDisplayNameById(createdBy) || req.user?.FullName || req.user?.Username || 'Unknown';
@@ -8906,9 +8924,6 @@ app.post('/api/assets/:id/export', requireAssetOrAdmin, async (req, res) => {
if (!borrowerName) {
return res.status(400).json({ success: false, message: 'Nguoi muon la bat buoc' });
}
if (!projectName) {
return res.status(400).json({ success: false, message: 'Du an xuat la bat buoc' });
}
transaction = new sql.Transaction(pool);
await transaction.begin();
@@ -8928,6 +8943,7 @@ app.post('/api/assets/:id/export', requireAssetOrAdmin, async (req, res) => {
UsedQuantity,
Custodian,
Borrower,
ProjectAllocations,
Notes
FROM AssetInventory WITH (UPDLOCK, ROWLOCK)
WHERE AssetId = @assetId AND IsArchived = 0
@@ -8947,11 +8963,11 @@ app.post('/api/assets/:id/export', requireAssetOrAdmin, async (req, res) => {
), 0);
const storedExportInPeriod = parseOptionalNonNegativeInteger(asset.ExportInPeriod);
const baseExportInPeriod = storedExportInPeriod !== null ? storedExportInPeriod : previousBorrowerExport;
const allocatedQuantity = parseAllocations(asset.ProjectAllocations).reduce((sum, row) => sum + row.quantity, 0);
const baseExportInPeriod = Math.max(storedExportInPeriod || 0, previousBorrowerExport, allocatedQuantity);
const storedEndingBalance = parseOptionalNonNegativeInteger(asset.EndingBalance);
const baseEndingBalance = storedEndingBalance !== null
? storedEndingBalance
: Math.max(quantity + importInPeriod - baseExportInPeriod, 0);
const totalAvailable = Math.max(quantity + importInPeriod - baseExportInPeriod, 0);
const baseEndingBalance = Math.min(storedEndingBalance ?? totalAvailable, totalAvailable);
const baseNewQuantity = parseOptionalNonNegativeInteger(asset.NewQuantity);
const baseUsedQuantity = parseOptionalNonNegativeInteger(asset.UsedQuantity);
const stockBuckets = normalizeAssetStockBuckets(
@@ -8973,6 +8989,10 @@ app.post('/api/assets/:id/export', requireAssetOrAdmin, async (req, res) => {
}
const borrowerSummary = mergeBorrowerEntries(asset.Borrower, borrowerName, exportQuantity);
if (borrowerSummary && borrowerSummary.length > 255) {
await transaction.rollback();
return res.status(400).json({ success: false, message: 'Danh sách người mượn quá dài, vui lòng rút gọn tên.' });
}
const nextBorrowerEntries = parseBorrowerEntries(borrowerSummary);
const nextBorrowerExport = nextBorrowerEntries.reduce((sum, entry) => (
sum + parseNonNegativeInteger(entry?.quantity, 0)
@@ -8993,7 +9013,7 @@ app.post('/api/assets/:id/export', requireAssetOrAdmin, async (req, res) => {
await new sql.Request(transaction)
.input('assetId', sql.Int, assetId)
.input('project', sql.NVarChar, projectName)
.input('projectAllocations', sql.NVarChar(sql.MAX), JSON.stringify(addAllocations(asset.ProjectAllocations, allocations, borrowerName)))
.input('borrower', sql.NVarChar, borrowerSummary)
.input('exportInPeriod', sql.Int, nextExportInPeriod)
.input('endingBalance', sql.Int, nextEndingBalance)
@@ -9004,7 +9024,7 @@ app.post('/api/assets/:id/export', requireAssetOrAdmin, async (req, res) => {
.input('notes', sql.NVarChar, nextAssetNotes)
.query(`
UPDATE AssetInventory
SET Project = @project,
SET ProjectAllocations = @projectAllocations,
Borrower = @borrower,
ExportInPeriod = @exportInPeriod,
EndingBalance = @endingBalance,
@@ -9019,63 +9039,67 @@ app.post('/api/assets/:id/export', requireAssetOrAdmin, async (req, res) => {
const historyCustodianName = String(asset.Custodian || '').trim() || '-';
const historyResult = await new sql.Request(transaction)
.input('assetId', sql.Int, assetId)
.input('assetCode', sql.NVarChar, String(asset.AssetCode || '').trim())
.input('assetName', sql.NVarChar, String(asset.AssetName || '').trim())
.input('exportQuantity', sql.Int, exportQuantity)
.input('projectName', sql.NVarChar, projectName)
.input('custodianName', sql.NVarChar, historyCustodianName)
.input('exportedByName', sql.NVarChar, exportedByName)
.input('exportNote', sql.NVarChar, exportNote)
.input('createdBy', sql.Int, createdBy)
.input('exportedDate', sql.DateTime, exportedDate)
.query(`
INSERT INTO AssetExportHistory (
AssetId,
AssetCode,
AssetName,
ExportQuantity,
ProjectName,
CustodianName,
ExportedByName,
ExportNote,
CreatedBy,
ExportedDate
)
OUTPUT
INSERTED.ExportHistoryId,
INSERTED.AssetId,
INSERTED.AssetCode,
INSERTED.AssetName,
INSERTED.ExportQuantity,
INSERTED.ProjectName,
INSERTED.CustodianName,
INSERTED.ExportedByName,
INSERTED.ExportNote,
INSERTED.CreatedBy,
INSERTED.ExportedDate,
INSERTED.CreatedDate,
INSERTED.UpdatedDate
VALUES (
@assetId,
@assetCode,
@assetName,
@exportQuantity,
@projectName,
@custodianName,
@exportedByName,
@exportNote,
@createdBy,
@exportedDate
)
`);
const histories = [];
for (const allocation of allocations) {
const historyResult = await new sql.Request(transaction)
.input('assetId', sql.Int, assetId)
.input('assetCode', sql.NVarChar, String(asset.AssetCode || '').trim())
.input('assetName', sql.NVarChar, String(asset.AssetName || '').trim())
.input('exportQuantity', sql.Int, allocation.quantity)
.input('projectName', sql.NVarChar, allocation.projectName)
.input('custodianName', sql.NVarChar, historyCustodianName)
.input('exportedByName', sql.NVarChar, exportedByName)
.input('exportNote', sql.NVarChar, exportNote)
.input('createdBy', sql.Int, createdBy)
.input('exportedDate', sql.DateTime, exportedDate)
.query(`
INSERT INTO AssetExportHistory (
AssetId,
AssetCode,
AssetName,
ExportQuantity,
ProjectName,
CustodianName,
ExportedByName,
ExportNote,
CreatedBy,
ExportedDate
)
OUTPUT
INSERTED.ExportHistoryId,
INSERTED.AssetId,
INSERTED.AssetCode,
INSERTED.AssetName,
INSERTED.ExportQuantity,
INSERTED.ProjectName,
INSERTED.CustodianName,
INSERTED.ExportedByName,
INSERTED.ExportNote,
INSERTED.CreatedBy,
INSERTED.ExportedDate,
INSERTED.CreatedDate,
INSERTED.UpdatedDate
VALUES (
@assetId,
@assetCode,
@assetName,
@exportQuantity,
@projectName,
@custodianName,
@exportedByName,
@exportNote,
@createdBy,
@exportedDate
)
`);
histories.push(historyResult.recordset?.[0] || null);
}
await transaction.commit();
res.json({
success: true,
message: 'Xuat tai san thanh cong',
data: historyResult.recordset?.[0] || null
data: req.body.allocations === undefined ? histories[0] : histories
});
} catch (err) {
if (transaction) {
@@ -9154,6 +9178,7 @@ app.post('/api/assets', requireAssetOrAdmin, async (req, res) => {
});
app.put('/api/assets/:id', requireAssetOrAdmin, async (req, res) => {
const transaction = new sql.Transaction(pool);
try {
const payload = normalizeAssetPayload(req.body);
const updatedBy = getUserIdFromRequest(req);
@@ -9169,7 +9194,30 @@ app.put('/api/assets/:id', requireAssetOrAdmin, async (req, res) => {
await ensureDepartmentExists(payload.department);
const updateResult = await pool.request()
await transaction.begin();
const currentResult = await new sql.Request(transaction)
.input('assetId', sql.Int, req.params.id)
.query('SELECT * FROM AssetInventory WITH (UPDLOCK, HOLDLOCK) WHERE AssetId = @assetId AND IsArchived = 0');
const current = currentResult.recordset?.[0];
if (!current) {
await transaction.rollback();
return res.status(404).json({ success: false, message: 'Asset not found or archived' });
}
// The form may have been opened before another export. Keep the locked ledger.
payload.exportInPeriod = Math.max(parseNonNegativeInteger(current.ExportInPeriod, 0),
parseBorrowerEntries(current.Borrower).reduce((sum, row) => sum + row.quantity, 0),
parseAllocations(current.ProjectAllocations).reduce((sum, row) => sum + row.quantity, 0));
if (payload.quantity + payload.importInPeriod < payload.exportInPeriod) {
await transaction.rollback();
return res.status(400).json({ success: false, message: 'Tổng tài sản không được nhỏ hơn số lượng đang xuất.' });
}
payload.borrower = current.Borrower || null;
payload.endingBalance = payload.quantity + payload.importInPeriod - payload.exportInPeriod;
const buckets = normalizeAssetStockBuckets(payload.endingBalance, Math.max(payload.endingBalance - (current.UsedQuantity || 0), 0), current.UsedQuantity || 0);
payload.newQuantity = buckets.newQuantity;
payload.usedQuantity = buckets.usedQuantity;
payload.status = resolveAssetStatusFromStock(payload.endingBalance, payload.exportInPeriod);
const updateResult = await new sql.Request(transaction)
.input('assetId', sql.Int, req.params.id)
.input('assetCode', sql.NVarChar, payload.assetCode)
.input('assetName', sql.NVarChar, payload.assetName)
@@ -9221,11 +9269,14 @@ app.put('/api/assets/:id', requireAssetOrAdmin, async (req, res) => {
`);
if (!updateResult.recordset?.length) {
await transaction.rollback();
return res.status(404).json({ success: false, message: 'Asset not found or archived' });
}
await transaction.commit();
res.json({ success: true, message: 'Asset updated' });
} catch (err) {
try { await transaction.rollback(); } catch {}
if (String(err.message || '').includes('UNIQUE')) {
return res.status(409).json({ success: false, message: 'Asset code already exists' });
}
@@ -9414,6 +9465,16 @@ app.post('/api/assets/import', requireAssetOrAdmin, upload.single('file'), async
continue;
}
const allocatedAsset = await new sql.Request(transaction)
.input('assetCode', sql.NVarChar, row.assetCode)
.query(`SELECT AssetId FROM AssetInventory WITH (UPDLOCK, HOLDLOCK)
WHERE AssetCode = @assetCode AND IsArchived = 0
AND ProjectAllocations IS NOT NULL AND ProjectAllocations <> '[]'`);
if (allocatedAsset.recordset?.length) {
await transaction.rollback();
return res.status(409).json({ success: false, message: `Tài sản ${row.assetCode} đang xuất cho dự án. Vui lòng cập nhật bằng biểu mẫu tài sản để giữ số lượng đã phân bổ.` });
}
const mergeResult = await new sql.Request(transaction)
.input('assetCode', sql.NVarChar, row.assetCode)
.input('assetName', sql.NVarChar, row.assetName)

View File

@@ -0,0 +1,15 @@
# Xuất tài sản cho nhiều dự án
Chọn một tài sản → **Xuất tài sản** → chọn người mượn, dự án và số lượng. Dùng **Thêm dự án** để thêm các dòng trong cùng phiếu xuất. Tên dự án trùng nhau được cộng dồn; tất cả các dòng được lưu trong một giao dịch cùng cập nhật kho và lịch sử xuất.
- Tổng tài sản = tồn đầu kỳ (`Quantity`) + nhập trong kỳ (`ImportInPeriod`).
- Tổng xuất mới không vượt số lượng còn có thể xuất: giá trị nhỏ hơn giữa tồn kho đã lưu và tổng tài sản trừ lượng đang xuất.
- Bảng tài sản, tìm kiếm, chi tiết, giao diện điện thoại và file Excel hiển thị lượng đang xuất theo từng dự án.
- `AssetInventory.Project` vẫn là thông tin dự án mặc định. Phân bổ hiện tại nằm trong `ProjectAllocations`; trường này do máy chủ quản lý.
- Dữ liệu xuất cũ chưa có phân bổ được ghi là **Chưa xác định dự án**. Không dùng dự án cuối cùng hoặc lịch sử xuất cộng dồn để suy đoán lượng hiện tại.
- Luồng trả hiện tại không chọn dự án. Khi duyệt trả, hệ thống giảm phần chưa gắn dự án của người mượn trước, sau đó giảm các lần xuất cho dự án theo thứ tự xuất trước trả trước. Người mượn khác không bị ảnh hưởng.
- Biểu mẫu sửa giữ số lượng đang xuất mới nhất và không cho giảm tổng dưới lượng đó. Import Excel không ghi đè tài sản đang có phân bổ dự án; dùng biểu mẫu sửa cho các tài sản này.
Khởi động lại backend để tự thêm cột `ProjectAllocations` nếu chưa tồn tại. Không cần chỉnh `.env`. Migration giữ nguyên dữ liệu cũ, kể cả tài sản đã lưu trữ.
Kiểm tra: `npm test`, `node --check backend/server.js`, `node --check public/js/app.js`. Các kiểm thử tuyến API dùng SQL pool giả lập, không ghi vào cơ sở dữ liệu thật.

File diff suppressed because one or more lines are too long

View File

@@ -2462,6 +2462,7 @@ class AccountManager {
asset.UsedQuantity,
asset.Department,
asset.Project,
this.formatAssetProjectsText(asset),
asset.Location,
asset.Custodian,
asset.Borrower,
@@ -6633,6 +6634,44 @@ class AccountManager {
this.setupConsumableExportHistoryPagerListeners();
}
getAssetProjectAllocations(asset) {
let rows = asset?.ProjectAllocations || [];
if (typeof rows === 'string') {
try { rows = JSON.parse(rows); } catch { rows = []; }
}
const projects = new Map();
for (const row of Array.isArray(rows) ? rows : []) {
const name = String(row.projectName || '').trim();
const quantity = Number(row.quantity);
if (!name || !Number.isSafeInteger(quantity) || quantity <= 0) continue;
const key = name.toLowerCase();
const existing = projects.get(key) || { projectName: name, quantity: 0 };
existing.quantity += quantity;
projects.set(key, existing);
}
const result = [...projects.values()];
const allocated = result.reduce((sum, row) => sum + row.quantity, 0);
const unattributed = Math.max(this.buildAssetQuantityMetrics(asset).exportInPeriod - allocated, 0);
if (unattributed) result.push({ projectName: 'Chưa xác định dự án', quantity: unattributed });
return result;
}
formatAssetProjectsText(asset) {
return this.getAssetProjectAllocations(asset)
.map(row => `${row.projectName}: ${row.quantity}${asset?.Unit ? ` ${asset.Unit}` : ''}`).join('\n');
}
formatAssetProjectsHtml(asset) {
const rows = this.getAssetProjectAllocations(asset);
return rows.length ? rows.map(row => `<div class="whitespace-nowrap">${this.escapeHtml(row.projectName)}: <strong>${row.quantity}</strong> ${this.escapeHtml(asset?.Unit || '')}</div>`).join('') : '-';
}
getAssetAvailableForExport(asset) {
const metrics = this.buildAssetQuantityMetrics(asset);
const allocated = this.getAssetProjectAllocations(asset).reduce((sum, row) => sum + row.quantity, 0);
return Math.min(metrics.endingBalance, Math.max(metrics.quantity + metrics.importInPeriod - Math.max(metrics.exportInPeriod, metrics.borrowerExportInPeriod, allocated), 0));
}
getAssetMobileCardHtml(asset, rowNumber, canManageAssets) {
const statusMeta = this.getAssetStatusMeta(asset?.Status);
const assetId = Number(asset?.AssetId);
@@ -6659,10 +6698,11 @@ class AccountManager {
<div class="mt-3 grid grid-cols-2 gap-x-3 gap-y-2 border-t border-slate-100 pt-3 text-xs">
<div><span class="block text-[10px] font-bold uppercase text-slate-400">Model</span><span class="text-slate-700">${safe(asset?.Model)}</span></div>
<div><span class="block text-[10px] font-bold uppercase text-slate-400">Serial</span><span class="text-slate-700">${safe(asset?.SerialNumber)}</span></div>
<div><span class="block text-[10px] font-bold uppercase text-slate-400">Tổng tài sản</span><span class="font-bold text-slate-800">${this.buildAssetQuantityMetrics(asset).quantity + this.buildAssetQuantityMetrics(asset).importInPeriod}</span></div>
<div><span class="block text-[10px] font-bold uppercase text-slate-400">Tồn cuối kỳ</span><span class="font-bold text-slate-800">${endingBalance}${unit ? ` ${safe(unit)}` : ''}</span></div>
<div><span class="block text-[10px] font-bold uppercase text-slate-400">Đang mượn</span><span class="font-bold text-slate-800">${borrowedQuantity}${unit ? ` ${safe(unit)}` : ''}</span></div>
<div><span class="block text-[10px] font-bold uppercase text-slate-400">Phòng ban</span><span class="text-slate-700">${safe(asset?.Department)}</span></div>
<div><span class="block text-[10px] font-bold uppercase text-slate-400">Dự án</span><span class="text-slate-700">${safe(asset?.Project)}</span></div>
<div><span class="block text-[10px] font-bold uppercase text-slate-400">Dự án</span><div class="text-slate-700">${this.formatAssetProjectsHtml(asset)}</div></div>
<div><span class="block text-[10px] font-bold uppercase text-slate-400">Vị trí</span><span class="text-slate-700">${safe(asset?.Location)}</span></div>
<div><span class="block text-[10px] font-bold uppercase text-slate-400">Phụ trách</span><span class="text-slate-700">${safe(asset?.Custodian)}</span></div>
</div>
@@ -6788,12 +6828,13 @@ class AccountManager {
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Model</th>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Serial</th>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Số lượng (Tồn đầu kỳ)</th>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Tổng tài sản</th>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Nhập trong kỳ</th>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Xuất trong kỳ</th>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Tồn cuối kỳ</th>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Đơn vị</th>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Phòng ban</th>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Dự án</th>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Dự án đang xuất / SL</th>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Người phụ trách</th>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500" style="width: 132px; min-width: 132px; white-space: nowrap;">Trạng thái</th>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">SL hàng mới</th>
@@ -6825,12 +6866,13 @@ class AccountManager {
<td class="px-4 py-3 text-sm text-slate-600">${asset.Model || '-'}</td>
<td class="px-4 py-3 text-sm text-slate-600">${asset.SerialNumber || '-'}</td>
<td class="px-4 py-3 text-sm text-slate-600">${asset.Quantity || 0}</td>
<td class="px-4 py-3 text-sm font-semibold text-slate-700">${this.buildAssetQuantityMetrics(asset).quantity + this.buildAssetQuantityMetrics(asset).importInPeriod}</td>
<td class="px-4 py-3 text-sm text-slate-600">${asset.ImportInPeriod ?? 0}</td>
<td class="px-4 py-3 text-sm text-slate-600">${asset.ExportInPeriod ?? 0}</td>
<td class="px-4 py-3 text-sm text-slate-600">${asset.EndingBalance ?? 0}</td>
<td class="px-4 py-3 text-sm text-slate-600">${asset.Unit || '-'}</td>
<td class="px-4 py-3 text-sm text-slate-600">${asset.Department || '-'}</td>
<td class="px-4 py-3 text-sm text-slate-600">${asset.Project || '-'}</td>
<td class="px-4 py-3 text-sm text-slate-600">${this.formatAssetProjectsHtml(asset)}</td>
<td class="px-4 py-3 text-sm text-slate-600">${asset.Custodian || '-'}</td>
<td class="px-4 py-3 text-sm" style="width: 132px; min-width: 132px; white-space: nowrap;">
<span class="inline-block px-2 py-1 rounded text-xs font-semibold ${statusMeta.className}" style="display: inline-block; white-space: nowrap; word-break: keep-all; overflow-wrap: normal;">${statusMeta.label}</span>
@@ -6915,12 +6957,13 @@ class AccountManager {
<td class="px-4 py-3 text-sm text-slate-600">${asset.Model || '-'}</td>
<td class="px-4 py-3 text-sm text-slate-600">${asset.SerialNumber || '-'}</td>
<td class="px-4 py-3 text-sm text-slate-600">${asset.Quantity || 0}</td>
<td class="px-4 py-3 text-sm font-semibold text-slate-700">${this.buildAssetQuantityMetrics(asset).quantity + this.buildAssetQuantityMetrics(asset).importInPeriod}</td>
<td class="px-4 py-3 text-sm text-slate-600">${asset.ImportInPeriod ?? 0}</td>
<td class="px-4 py-3 text-sm text-slate-600">${asset.ExportInPeriod ?? 0}</td>
<td class="px-4 py-3 text-sm text-slate-600">${asset.EndingBalance ?? 0}</td>
<td class="px-4 py-3 text-sm text-slate-600">${asset.Unit || '-'}</td>
<td class="px-4 py-3 text-sm text-slate-600">${asset.Department || '-'}</td>
<td class="px-4 py-3 text-sm text-slate-600">${asset.Project || '-'}</td>
<td class="px-4 py-3 text-sm text-slate-600">${this.formatAssetProjectsHtml(asset)}</td>
<td class="px-4 py-3 text-sm text-slate-600">${asset.Custodian || '-'}</td>
<td class="px-4 py-3 text-sm" style="width: 132px; min-width: 132px; white-space: nowrap;">
<span class="inline-block px-2 py-1 rounded text-xs font-semibold ${statusMeta.className}" style="display: inline-block; white-space: nowrap; word-break: keep-all; overflow-wrap: normal;">${statusMeta.label}</span>
@@ -7299,6 +7342,7 @@ class AccountManager {
['Model', asset?.Model],
['Sd serial', asset?.SerialNumber],
['Số lượng (Tồn đầu kỳ)', `${asset?.Quantity || 0} ${asset?.Unit || ''}`.trim()],
['Tổng tài sản', this.buildAssetQuantityMetrics(asset).quantity + this.buildAssetQuantityMetrics(asset).importInPeriod],
['Nhập trong kỳ', asset?.ImportInPeriod ?? 0],
['Xuất trong kỳ', asset?.ExportInPeriod ?? 0],
['Tồn cuối kỳ', asset?.EndingBalance ?? 0],
@@ -7306,7 +7350,7 @@ class AccountManager {
['SL đã qua sử dụng', asset?.UsedQuantity ?? 0],
['SL đang mượn', asset?.ExportInPeriod ?? 0],
['Phòng ban', asset?.Department],
['Dự án', asset?.Project],
['Dự án đang xuất / Số lượng', this.formatAssetProjectsHtml(asset)],
['Vị trí', asset?.Location],
['Người phụ trách', asset?.Custodian],
['Ngày mua', this.formatDateOnly(asset?.PurchaseDate)],
@@ -7809,6 +7853,49 @@ class AccountManager {
}
}
collectBorrowProjectAllocations() {
const rows = [{
projectName: String(document.getElementById('borrowAssetProjectInput')?.value || '').trim(),
quantity: Number(document.getElementById('borrowQuantityInput')?.value)
}];
document.querySelectorAll('#borrowAdditionalProjects .borrow-project-row').forEach(row => {
rows.push({ projectName: row.querySelector('select').value.trim(), quantity: Number(row.querySelector('input').value) });
});
return rows;
}
updateBorrowAllocationSummary() {
const total = this.collectBorrowProjectAllocations().reduce((sum, row) => sum + (Number.isFinite(row.quantity) ? row.quantity : 0), 0);
const available = Number(document.getElementById('borrowCurrentEndingInput')?.value) || 0;
const summary = document.getElementById('borrowAllocationSummary');
if (summary) {
summary.textContent = `Tổng xuất: ${total} / ${available} có thể xuất · Còn lại: ${Math.max(available - total, 0)}${total > available ? ' — Vượt số lượng cho phép' : ''}`;
summary.classList.toggle('text-red-600', total > available);
}
}
addBorrowProjectRow() {
const container = document.getElementById('borrowAdditionalProjects');
if (!container || container.children.length >= 99) return;
const row = document.createElement('div');
row.className = 'borrow-project-row flex items-end gap-2';
row.innerHTML = `
<label class="flex-1 text-xs text-slate-600">Dự án
<select class="w-full border border-slate-200 rounded-lg text-sm py-2 px-3" required>
<option value="">-- Chọn dự án --</option>
${this.getUniqueAssetProjectNames().map(name => `<option value="${this.escapeHtml(name)}">${this.escapeHtml(name)}</option>`).join('')}
</select>
</label>
<label class="text-xs text-slate-600" style="width: 100px;">Số lượng
<input type="number" min="1" step="1" value="1" class="w-full border border-slate-200 rounded-lg text-sm py-2 px-3" required>
</label>
<button type="button" class="px-2 py-2 text-sm text-red-600" aria-label="Xóa dòng dự án">Xóa</button>`;
row.querySelector('input').max = document.getElementById('borrowCurrentEndingInput').value;
row.querySelector('button').addEventListener('click', () => { row.remove(); this.updateBorrowAllocationSummary(); });
container.appendChild(row);
this.updateBorrowAllocationSummary();
}
async openBorrowAssetModal() {
if (!this.ensureAssetManagePermission('xuat tai san')) {
return;
@@ -7827,7 +7914,8 @@ class AccountManager {
}
const metrics = this.buildAssetQuantityMetrics(asset);
if (metrics.endingBalance <= 0) {
const available = this.getAssetAvailableForExport(asset);
if (available <= 0) {
this.notifyWarning('Tài sản đã hết tồn cuối kỳ, không thể xuất thêm.');
return;
}
@@ -7853,14 +7941,20 @@ class AccountManager {
}
assetNameInput.value = `${asset.AssetCode || ''} - ${asset.AssetName || ''}`.trim();
endingInput.value = String(metrics.endingBalance);
endingInput.value = String(available);
quantityInput.value = '1';
quantityInput.min = '1';
quantityInput.max = String(metrics.endingBalance);
quantityInput.max = String(available);
this.refreshBorrowAssetUserOptions('');
this.refreshBorrowAssetProjectOptions(String(asset?.Project || '').trim());
noteInput.value = '';
document.getElementById('borrowAdditionalProjects').innerHTML = '';
document.getElementById('borrowAssetStockSummary').textContent =
`Tổng tài sản: ${metrics.quantity + metrics.importInPeriod} · Đang xuất: ${metrics.exportInPeriod} · Có thể xuất: ${available}`;
document.getElementById('addBorrowProjectBtn').onclick = () => this.addBorrowProjectRow();
document.getElementById('borrowAssetForm').oninput = () => this.updateBorrowAllocationSummary();
this.updateBorrowAllocationSummary();
if (borrowByInput) {
borrowByInput.value = this.getCurrentUserDisplayName();
@@ -7882,8 +7976,6 @@ class AccountManager {
const assetIdInput = document.getElementById('borrowAssetIdInput');
const borrowerInput = document.getElementById('borrowAssetUserInput');
const projectInput = document.getElementById('borrowAssetProjectInput');
const quantityInput = document.getElementById('borrowQuantityInput');
const noteInput = document.getElementById('borrowAssetNoteInput');
const selectedAssetId = Number(assetIdInput?.value || this.pendingBorrowAssetId);
@@ -7904,30 +7996,33 @@ class AccountManager {
return;
}
const projectName = String(projectInput?.value || '').trim();
if (!projectName) {
this.notifyWarning('Vui lòng chọn dự án cần xuất.');
const allocations = this.collectBorrowProjectAllocations();
if (allocations.some(row => !row.projectName)) {
this.notifyWarning('Vui lòng chọn dự án cho tất cả các dòng.');
return;
}
const borrowQuantity = this.parseNonNegativeInteger(quantityInput?.value ?? 0, 0);
if (borrowQuantity <= 0) {
this.notifyWarning('Số lượng xuất phải lớn hơn 0.');
if (allocations.some(row => !Number.isSafeInteger(row.quantity) || row.quantity <= 0)) {
this.notifyWarning('Số lượng của mỗi dự án phải là số nguyên dương.');
return;
}
const borrowQuantity = allocations.reduce((sum, row) => sum + row.quantity, 0);
const exportNote = String(noteInput?.value || '').trim();
const currentMetrics = this.buildAssetQuantityMetrics(asset);
if (currentMetrics.endingBalance <= 0) {
const available = this.getAssetAvailableForExport(asset);
if (available <= 0) {
this.notifyWarning('Tài sản đã hết tồn cuối kỳ, không thể xuất thêm.');
return;
}
if (borrowQuantity > currentMetrics.endingBalance) {
this.notifyWarning(`Số lượng xuất (${borrowQuantity}) vượt quá tồn cuối kỳ (${currentMetrics.endingBalance}).`);
if (borrowQuantity > available) {
this.notifyWarning(`Số lượng xuất (${borrowQuantity}) vượt quá tồn cuối kỳ (${available}).`);
return;
}
if (this.assetExportSubmitting) return;
this.assetExportSubmitting = true;
const submitButton = document.querySelector('#borrowAssetForm button[type="submit"]');
if (submitButton) submitButton.disabled = true;
try {
const response = await fetch(`${this.apiBase}/assets/${selectedAssetId}/export`, {
method: 'POST',
@@ -7936,7 +8031,7 @@ class AccountManager {
quantity: borrowQuantity,
borrowerName,
custodianName: borrowerName,
projectName,
allocations,
note: exportNote
})
});
@@ -7959,6 +8054,9 @@ class AccountManager {
} catch (err) {
console.error(err);
this.notifyFailure('Xuất tài sản thất bại');
} finally {
this.assetExportSubmitting = false;
if (submitButton) submitButton.disabled = false;
}
}
@@ -10128,12 +10226,14 @@ class AccountManager {
'Model': asset.Model || '',
'Serial Number': asset.SerialNumber || '',
'Quantity': asset.Quantity || 0,
'Tổng tài sản': this.buildAssetQuantityMetrics(asset).quantity + this.buildAssetQuantityMetrics(asset).importInPeriod,
'Import In Period': asset.ImportInPeriod ?? 0,
'Export In Period': asset.ExportInPeriod ?? 0,
'Ending Balance': asset.EndingBalance ?? 0,
'Unit': asset.Unit || '',
'Department': asset.Department || '',
'Project': asset.Project || '',
'Dự án đang xuất / Số lượng': this.formatAssetProjectsText(asset),
'Location': asset.Location || '',
'Custodian': asset.Custodian || '',
'Borrower': asset.Borrower || '',

View File

@@ -260,7 +260,7 @@
</select>
</div>
<div>
<label class="text-[10px] font-bold uppercase text-slate-500 tracking-widest block mb-1">Dự án</label>
<label class="text-[10px] font-bold uppercase text-slate-500 tracking-widest block mb-1">Dự án mặc định</label>
<select id="assetProjectInput" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3">
<option value="">-- Chọn dự án --</option>
</select>
@@ -688,43 +688,49 @@
<span class="material-symbols-outlined">close</span>
</button>
</div>
<form id="borrowAssetForm" class="p-6 space-y-4">
<form id="borrowAssetForm" class="p-6 space-y-4 overflow-y-auto" style="max-height: 80vh;">
<input type="hidden" id="borrowAssetIdInput">
<p id="borrowAssetStockSummary" class="text-sm font-semibold text-slate-700"></p>
<div>
<label class="text-[10px] font-bold uppercase text-slate-500 tracking-widest block mb-1">Tài sản</label>
<input type="text" id="borrowAssetNameInput" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3 bg-slate-50" readonly>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label class="text-[10px] font-bold uppercase text-slate-500 tracking-widest block mb-1">Tồn cuối kỳ hiện tại</label>
<label for="borrowCurrentEndingInput" class="text-xs font-bold text-slate-500 block mb-1">Còn có thể xuất</label>
<input type="number" id="borrowCurrentEndingInput" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3 bg-slate-50" readonly>
</div>
<div>
<label class="text-[10px] font-bold uppercase text-slate-500 tracking-widest block mb-1">Số lượng xuất</label>
<input type="number" id="borrowQuantityInput" min="1" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3" value="1" required>
</div>
<div>
<label class="text-[10px] font-bold uppercase text-slate-500 tracking-widest block mb-1">Người mượn</label>
<label for="borrowAssetUserInput" class="text-xs font-bold text-slate-500 block mb-1">Người mượn</label>
<select id="borrowAssetUserInput" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3" required>
<option value="">-- Chọn người mượn --</option>
</select>
</div>
<div>
<label class="text-[10px] font-bold uppercase text-slate-500 tracking-widest block mb-1">Xuất cho dự án</label>
<select id="borrowAssetProjectInput" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3" required>
<option value="">-- Chọn dự án --</option>
</select>
<div class="md:col-span-2 space-y-3">
<div class="flex items-end gap-2">
<label for="borrowAssetProjectInput" class="flex-1 text-xs text-slate-600">Dự án
<select id="borrowAssetProjectInput" class="w-full border border-slate-200 rounded-lg text-sm py-2 px-3" required>
<option value="">-- Chọn dự án --</option>
</select>
</label>
<label for="borrowQuantityInput" class="text-xs text-slate-600" style="width: 100px;">Số lượng
<input type="number" id="borrowQuantityInput" min="1" step="1" class="w-full border border-slate-200 rounded-lg text-sm py-2 px-3" value="1" required>
</label>
</div>
<div id="borrowAdditionalProjects" class="space-y-3"></div>
<button type="button" id="addBorrowProjectBtn" class="mt-2 px-3 py-2 text-xs font-bold text-primary border border-slate-200 rounded-lg">+ Thêm dự án</button>
<p id="borrowAllocationSummary" class="mt-2 text-sm font-semibold" aria-live="polite"></p>
</div>
<div>
<label class="text-[10px] font-bold uppercase text-slate-500 tracking-widest block mb-1">Người xuất</label>
<label for="borrowByInput" class="text-xs font-bold text-slate-500 block mb-1">Người xuất</label>
<input type="text" id="borrowByInput" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3 bg-slate-50" readonly>
</div>
<div class="md:col-span-2">
<label class="text-[10px] font-bold uppercase text-slate-500 tracking-widest block mb-1">Role người thao tác</label>
<div>
<label for="borrowRoleInput" class="text-xs font-bold text-slate-500 block mb-1">Role người thao tác</label>
<input type="text" id="borrowRoleInput" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3 bg-slate-50" readonly>
</div>
<div class="md:col-span-2">
<label class="text-[10px] font-bold uppercase text-slate-500 tracking-widest block mb-1">Ghi chú xuất</label>
<label for="borrowAssetNoteInput" class="text-xs font-bold text-slate-500 block mb-1">Ghi chú xuất</label>
<textarea id="borrowAssetNoteInput" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3 h-20 resize-none" placeholder="Nhập ghi chú (nếu có)"></textarea>
</div>
</div>

View File

@@ -1,90 +1,6 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const { createRequire } = require('node:module');
const serverPath = path.resolve(__dirname, '../backend/server.js');
const serverSource = fs.readFileSync(serverPath, 'utf8');
const serverRequire = createRequire(serverPath);
// Run the real route handlers with an isolated pool so these regressions do not
// need credentials or alter a developer's inventory.
function createFixture(answer = () => ({ recordset: [] })) {
const queries = [];
const transactions = [];
class Request {
constructor(transaction) {
this.transaction = transaction;
this.inputs = {};
}
input(name, _type, value) {
this.inputs[name] = value;
return this;
}
async query(query) {
const call = { query, inputs: this.inputs, transaction: this.transaction };
queries.push(call);
return answer(call);
}
}
class Transaction {
constructor() { transactions.push(this); }
async begin() { this.begun = true; }
async commit() { this.committed = true; }
async rollback() { this.rolledBack = true; }
}
const sql = { ...serverRequire('mssql'), Request, Transaction };
const module = { exports: {} };
const context = {
require(name) { return name === 'mssql' ? sql : serverRequire(name); },
module,
exports: module.exports,
__dirname: path.dirname(serverPath),
__filename: serverPath,
Buffer,
URL,
console,
process: {
env: {
...process.env,
NODE_ENV: 'test',
DATA_ENCRYPTION_SECRET: 'test-only-archive-key-with-more-than-32-characters'
},
on() {}
},
testPool: { request: () => new Request() }
};
vm.runInNewContext(`${serverSource}
pool = testPool;
getUserDisplayNameById = async () => 'Borrower A';
safeCreateSystemNotification = async () => {};
ensureDepartmentExists = async () => {};
syncAssetDepartmentsFromInventory = async () => {};
syncAssetProjectsFromInventory = async () => {};
`, context, { filename: serverPath });
async function invoke(method, routePath, overrides = {}) {
const route = module.exports.app.router.stack.find(layer => (
layer.route?.path === routePath && layer.route.methods[method]
)).route;
const handler = route.stack.at(-1).handle;
const req = {
params: {}, query: {}, body: {},
user: { UserId: 1, Role: 'asset', FullName: 'Borrower A' },
...overrides
};
const response = {
statusCode: 200,
status(value) { this.statusCode = value; return this; },
json(value) { this.body = value; return this; }
};
await handler(req, response);
return response;
}
return { invoke, queries, transactions };
}
const { createFixture } = require('./helpers/asset-route-fixture');
test('deleting an asset archives it without deleting any history or links', async () => {
const fixture = createFixture(() => ({ recordset: [{ AssetId: 17 }] }));
@@ -210,7 +126,7 @@ test('approving an archived return updates only its original inventory and borro
});
test('import matches the active version of a reused asset code only', async () => {
const fixture = createFixture(() => ({ recordset: [{ MergeAction: 'INSERT' }] }));
const fixture = createFixture(({ query }) => ({ recordset: query.includes('MERGE AssetInventory') ? [{ MergeAction: 'INSERT' }] : [] }));
const response = await fixture.invoke('post', '/api/assets/import', {
body: { rows: [{ assetCode: 'SAME-CODE', assetName: 'Replacement drill', model: 'D2', quantity: 5 }] }
});

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,88 @@
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const { createRequire } = require('node:module');
const serverPath = path.resolve(__dirname, '../../backend/server.js');
const serverSource = fs.readFileSync(serverPath, 'utf8');
const serverRequire = createRequire(serverPath);
// Run the real route handlers with an isolated pool so these regressions do not
// need credentials or alter a developer's inventory.
function createFixture(answer = () => ({ recordset: [] })) {
const queries = [];
const transactions = [];
class Request {
constructor(transaction) {
this.transaction = transaction;
this.inputs = {};
}
input(name, _type, value) {
this.inputs[name] = value;
return this;
}
async query(query) {
const call = { query, inputs: this.inputs, transaction: this.transaction };
queries.push(call);
return answer(call);
}
}
class Transaction {
constructor() { transactions.push(this); }
async begin() { this.begun = true; }
async commit() { this.committed = true; }
async rollback() { this.rolledBack = true; }
}
const sql = { ...serverRequire('mssql'), Request, Transaction };
const module = { exports: {} };
const context = {
require(name) { return name === 'mssql' ? sql : serverRequire(name); },
module,
exports: module.exports,
__dirname: path.dirname(serverPath),
__filename: serverPath,
Buffer,
URL,
console,
process: {
env: {
...process.env,
NODE_ENV: 'test',
DATA_ENCRYPTION_SECRET: 'test-only-archive-key-with-more-than-32-characters'
},
on() {}
},
testPool: { request: () => new Request() }
};
vm.runInNewContext(`${serverSource}
pool = testPool;
getUserDisplayNameById = async () => 'Borrower A';
safeCreateSystemNotification = async () => {};
ensureDepartmentExists = async () => {};
syncAssetDepartmentsFromInventory = async () => {};
syncAssetProjectsFromInventory = async () => {};
`, context, { filename: serverPath });
async function invoke(method, routePath, overrides = {}) {
const route = module.exports.app.router.stack.find(layer => (
layer.route?.path === routePath && layer.route.methods[method]
)).route;
const handler = route.stack.at(-1).handle;
const req = {
params: {}, query: {}, body: {},
user: { UserId: 1, Role: 'asset', FullName: 'Borrower A' },
...overrides
};
const response = {
statusCode: 200,
status(value) { this.statusCode = value; return this; },
json(value) { this.body = value; return this; }
};
await handler(req, response);
return response;
}
return { invoke, queries, transactions };
}
module.exports = { createFixture };