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)