update export request

This commit is contained in:
2026-11-10 11:01:24 +07:00
parent 63866b14a1
commit 00122e5b4a
16 changed files with 1108 additions and 382 deletions

View File

@@ -13,9 +13,10 @@ 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');
const { parseAllocations, addProjectExports, releaseAllocations } = require('./asset-project-allocations');
const { buildExportRequestWorkbook } = require('./export-request-workbook');
const { ensureAssetExportDocumentSchema } = require('./asset-export-documents');
const { ensureAssetExportRequestSchema, createAssetExportWorkflow } = require('./asset-export-requests');
const { ensureRobotSchema, createRobotRouter } = require('./robots');
const { ensureRobotBomSchema, createRobotBomRouter } = require('./robot-bom');
const { createAnnouncementRouter } = require('./announcements');
@@ -3112,6 +3113,7 @@ async function createTables() {
// Fail startup if history preservation cannot be installed.
await ensureAssetArchiveSchema(pool);
await ensureAssetExportDocumentSchema(pool);
await ensureAssetExportRequestSchema(pool);
await ensureRobotSchema(pool);
await ensureRobotBomSchema(pool);
await pool.request().query(`
@@ -8589,11 +8591,12 @@ app.get('/api/assets/:id', async (req, res) => {
}
});
app.get('/api/asset-export-history', requireAssetOrAdmin, async (req, res) => {
app.get('/api/asset-export-history', async (req, res) => {
try {
const limit = Math.min(parsePositiveInteger(req.query.limit, 300), 2000);
const result = await pool.request()
.input('limit', sql.Int, limit)
.input('requesterId', sql.Int, getUserIdFromRequest(req) || -1)
.query(`
SELECT TOP (@limit)
h.ExportHistoryId, h.AssetId, h.AssetCode, h.AssetName,
@@ -8602,6 +8605,7 @@ app.get('/api/asset-export-history', requireAssetOrAdmin, async (req, res) => {
h.ExportDocumentId, d.FileName AS DocumentFileName
FROM AssetExportHistory h
LEFT JOIN AssetExportDocuments d ON d.ExportDocumentId = h.ExportDocumentId
${['admin', 'asset'].includes(getRequesterRole(req)) ? '' : 'WHERE h.CreatedBy = @requesterId'}
ORDER BY h.ExportedDate DESC, h.ExportHistoryId DESC
`);
@@ -8618,11 +8622,13 @@ function isExportDocumentId(value) {
return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(String(value || ''));
}
app.get('/api/asset-export-documents/:id', requireAssetOrAdmin, async (req, res) => {
app.get('/api/asset-export-documents/:id', async (req, res) => {
if (!isExportDocumentId(req.params.id)) return res.status(400).json({ success: false, message: 'Mã phiếu không hợp lệ.' });
try {
const result = await pool.request().input('documentId', sql.UniqueIdentifier, req.params.id).query(`
const result = await pool.request().input('documentId', sql.UniqueIdentifier, req.params.id)
.input('requesterId', sql.Int, getUserIdFromRequest(req) || -1).query(`
SELECT ExportDocumentId, FileName, SnapshotJson FROM AssetExportDocuments WHERE ExportDocumentId = @documentId
${['admin', 'asset'].includes(getRequesterRole(req)) ? '' : 'AND CreatedBy = @requesterId'}
`);
const document = result.recordset?.[0];
if (!document) return res.status(404).json({ success: false, message: 'Không tìm thấy phiếu xuất đã lưu.' });
@@ -8632,11 +8638,13 @@ app.get('/api/asset-export-documents/:id', requireAssetOrAdmin, async (req, res)
} catch (err) { sendInternalError(res, err); }
});
app.get('/api/asset-export-documents/:id/download', requireAssetOrAdmin, async (req, res) => {
app.get('/api/asset-export-documents/:id/download', async (req, res) => {
if (!isExportDocumentId(req.params.id)) return res.status(400).json({ success: false, message: 'Mã phiếu không hợp lệ.' });
try {
const result = await pool.request().input('documentId', sql.UniqueIdentifier, req.params.id).query(`
const result = await pool.request().input('documentId', sql.UniqueIdentifier, req.params.id)
.input('requesterId', sql.Int, getUserIdFromRequest(req) || -1).query(`
SELECT FileName, MimeType, FileContent FROM AssetExportDocuments WHERE ExportDocumentId = @documentId
${['admin', 'asset'].includes(getRequesterRole(req)) ? '' : 'AND CreatedBy = @requesterId'}
`);
const document = result.recordset?.[0];
if (!document) return res.status(404).json({ success: false, message: 'Không tìm thấy file Excel đã lưu.' });
@@ -8931,7 +8939,7 @@ app.post('/api/assets/:id/damage-disposal', requireAssetOrAdmin, async (req, res
}
});
function prepareAssetExport(asset, allocations, borrowerName, exportNote) {
function prepareAssetExport(asset, allocations, exportNote) {
const fail = message => { throw Object.assign(new Error(message), { statusCode: 400 }); };
const exportQuantity = allocations.reduce((sum, row) => sum + row.quantity, 0);
const quantity = parseNonNegativeInteger(asset.Quantity, 0);
@@ -8945,144 +8953,107 @@ function prepareAssetExport(asset, allocations, borrowerName, exportNote) {
const label = String(asset.AssetCode || asset.AssetName || asset.AssetId);
if (available <= 0) fail(`${label}: Tài sản đã hết tồn cuối kỳ, không thể xuất thêm.`);
if (exportQuantity > available) fail(`${label}: Số lượng xuất (${exportQuantity}) vượt quá tồn cuối kỳ (${available}).`);
const borrower = mergeBorrowerEntries(asset.Borrower, borrowerName, exportQuantity);
if (borrower && borrower.length > 255) fail('Danh sách người mượn quá dài, vui lòng rút gọn tên.');
const exportDelta = parseBorrowerEntries(borrower)
.reduce((sum, entry) => sum + parseNonNegativeInteger(entry?.quantity, 0), 0) - previousBorrowerExport;
// Permanent project exports never enter the returnable borrower ledger.
const exportDelta = exportQuantity;
const stock = normalizeAssetStockBuckets(available,
parseOptionalNonNegativeInteger(asset.NewQuantity) ?? available,
parseOptionalNonNegativeInteger(asset.UsedQuantity) ?? 0);
const borrowFromNew = Math.min(stock.newQuantity, exportDelta);
const exportFromNew = Math.min(stock.newQuantity, exportDelta);
const endingBalance = Math.max(available - exportDelta, 0);
const exportInPeriod = Math.max(baseExportInPeriod + exportDelta, 0);
const oldNotes = String(asset.Notes || '').trim();
return { asset, allocations, available, borrower, endingBalance, exportInPeriod,
newQuantity: Math.max(stock.newQuantity - borrowFromNew, 0),
usedQuantity: Math.max(stock.usedQuantity - Math.max(exportDelta - borrowFromNew, 0), 0),
return { asset, allocations, available, endingBalance, exportInPeriod,
newQuantity: Math.max(stock.newQuantity - exportFromNew, 0),
usedQuantity: Math.max(stock.usedQuantity - Math.max(exportDelta - exportFromNew, 0), 0),
status: resolveAssetStatusFromStock(endingBalance, exportInPeriod),
notes: exportNote ? (oldNotes ? `${oldNotes}\n${exportNote}` : exportNote) : (oldNotes || null) };
}
async function handleAssetExport(req, res, singleAssetId) {
let transaction;
try {
const rawItems = singleAssetId === undefined ? req.body?.items : [{ ...req.body, assetId: singleAssetId }];
let items;
try {
if (!Array.isArray(rawItems) || !rawItems.length || rawItems.length > 100) throw new Error('Vui lòng chọn từ 1 đến 100 tài sản.');
const seen = new Set();
items = rawItems.map(row => {
const assetId = Number(row?.assetId);
if (!Number.isSafeInteger(assetId) || assetId <= 0 || assetId > 2147483647) throw new Error('Mã tài sản không hợp lệ.');
if (seen.has(assetId)) throw new Error('Mỗi tài sản chỉ được xuất hiện một lần trong phiếu.');
seen.add(assetId);
return { assetId, allocations: normalizeExportAllocations(row) };
});
if (items.reduce((sum, item) => sum + item.allocations.length, 0) > 100) throw new Error('Một phiếu chỉ hỗ trợ tối đa 100 dòng tài sản / dự án.');
} catch (err) {
return res.status(400).json({ success: false, message: err.message });
}
const borrowerName = String(req.body?.borrowerName || req.body?.custodianName || '').trim();
const exportNote = String(req.body?.note || '').trim() || null;
if (!borrowerName || borrowerName.length > 100) return res.status(400).json({ success: false, message: 'Vui lòng chọn người mượn, tối đa 100 ký tự.' });
if (exportNote && exportNote.length > 1000) return res.status(400).json({ success: false, message: 'Ghi chú xuất tối đa 1000 ký tự.' });
const createdBy = getUserIdFromRequest(req);
const exportedByName = await getUserDisplayNameById(createdBy) || req.user?.FullName || req.user?.Username || 'Unknown';
const exportedDate = new Date();
transaction = new sql.Transaction(pool);
await transaction.begin();
const lockedAssets = new Map();
// Consistent lock order avoids deadlocks between overlapping batches.
for (const { assetId } of [...items].sort((a, b) => a.assetId - b.assetId)) {
const result = await new sql.Request(transaction).input('assetId', sql.Int, assetId).query(`
SELECT TOP 1 AssetId, AssetCode, AssetName, Quantity, ImportInPeriod, ExportInPeriod,
EndingBalance, NewQuantity, UsedQuantity, Custodian, Borrower, ProjectAllocations,
Model, SerialNumber, Unit, Department, Notes
FROM AssetInventory WITH (UPDLOCK, ROWLOCK)
WHERE AssetId = @assetId AND IsArchived = 0
`);
if (!result.recordset?.[0]) throw Object.assign(new Error(`Không tìm thấy tài sản ${assetId} trong danh mục hiện tại.`), { statusCode: 404 });
lockedAssets.set(assetId, result.recordset[0]);
}
// Validate every asset before creating the file or writing any inventory.
const plans = items.map(item => prepareAssetExport(lockedAssets.get(item.assetId), item.allocations, borrowerName, exportNote));
const workbookItems = plans.map(plan => ({ item: plan.asset, rows: plan.allocations, availableStock: plan.available }));
const document = await buildExportRequestWorkbook({
...(plans.length === 1 ? workbookItems[0] : { items: workbookItems }),
requesterName: borrowerName, recipientName: borrowerName, exportedByName, note: exportNote, exportedDate
});
const documentId = crypto.randomUUID();
const snapshot = { version: 1, exportedDate: exportedDate.toISOString(), borrowerName, exportedByName, note: exportNote,
items: plans.map(plan => ({ assetId: plan.asset.AssetId, assetCode: plan.asset.AssetCode,
assetName: plan.asset.AssetName, model: plan.asset.Model, serialNumber: plan.asset.SerialNumber,
unit: plan.asset.Unit, department: plan.asset.Department, availableStock: plan.available,
allocations: plan.allocations })) };
async function performAssetExport(transaction, plans, { createdBy, requesterName, exportedByName, exportNote }) {
const exportedDate = new Date();
const workbookItems = plans.map(plan => ({ item: plan.asset, rows: plan.allocations, availableStock: plan.available }));
const document = await buildExportRequestWorkbook({
...(plans.length === 1 ? workbookItems[0] : { items: workbookItems }),
requesterName, recipientName: requesterName, exportedByName, note: exportNote, exportedDate
});
const documentId = crypto.randomUUID();
const snapshot = { version: 1, exportedDate: exportedDate.toISOString(), borrowerName: requesterName, requesterName, exportedByName, note: exportNote,
items: plans.map(plan => ({ assetId: plan.asset.AssetId, assetCode: plan.asset.AssetCode,
assetName: plan.asset.AssetName, model: plan.asset.Model, serialNumber: plan.asset.SerialNumber,
unit: plan.asset.Unit, department: plan.asset.Department, availableStock: plan.available,
allocations: plan.allocations })) };
await new sql.Request(transaction)
.input('documentId', sql.UniqueIdentifier, documentId)
.input('fileName', sql.NVarChar(255), document.fileName)
.input('mimeType', sql.NVarChar(150), document.mimeType)
.input('fileContent', sql.VarBinary(sql.MAX), Buffer.from(document.contentBase64, 'base64'))
.input('snapshotJson', sql.NVarChar(sql.MAX), JSON.stringify(snapshot))
.input('createdBy', sql.Int, createdBy)
.input('exportedDate', sql.DateTime, exportedDate)
.query(`INSERT INTO AssetExportDocuments (ExportDocumentId, FileName, MimeType, FileContent, SnapshotJson, CreatedBy, ExportedDate)
VALUES (@documentId, @fileName, @mimeType, @fileContent, @snapshotJson, @createdBy, @exportedDate)`);
const histories = [];
for (const plan of plans) {
const { asset } = plan;
await new sql.Request(transaction)
.input('documentId', sql.UniqueIdentifier, documentId)
.input('fileName', sql.NVarChar(255), document.fileName)
.input('mimeType', sql.NVarChar(150), document.mimeType)
.input('fileContent', sql.VarBinary(sql.MAX), Buffer.from(document.contentBase64, 'base64'))
.input('snapshotJson', sql.NVarChar(sql.MAX), JSON.stringify(snapshot))
.input('createdBy', sql.Int, createdBy)
.input('exportedDate', sql.DateTime, exportedDate)
.query(`INSERT INTO AssetExportDocuments (ExportDocumentId, FileName, MimeType, FileContent, SnapshotJson, CreatedBy, ExportedDate)
VALUES (@documentId, @fileName, @mimeType, @fileContent, @snapshotJson, @createdBy, @exportedDate)`);
const histories = [];
for (const plan of plans) {
const { asset } = plan;
await new sql.Request(transaction)
.input('assetId', sql.Int, asset.AssetId)
// No borrower: returns can release loans while keeping these project exports.
.input('projectAllocations', sql.NVarChar(sql.MAX), JSON.stringify(addProjectExports(asset.ProjectAllocations, plan.allocations)))
.input('exportInPeriod', sql.Int, plan.exportInPeriod)
.input('endingBalance', sql.Int, plan.endingBalance)
.input('newQuantity', sql.Int, plan.newQuantity)
.input('usedQuantity', sql.Int, plan.usedQuantity)
.input('status', sql.NVarChar, plan.status)
.input('exportedBy', sql.NVarChar, exportedByName)
.input('notes', sql.NVarChar, plan.notes)
.query(`UPDATE AssetInventory SET ProjectAllocations = @projectAllocations,
ExportInPeriod = @exportInPeriod, EndingBalance = @endingBalance, NewQuantity = @newQuantity,
UsedQuantity = @usedQuantity, Status = @status, ExportedBy = @exportedBy, Notes = @notes,
UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME())
WHERE AssetId = @assetId AND IsArchived = 0`);
for (const allocation of plan.allocations) {
const result = await new sql.Request(transaction)
.input('assetId', sql.Int, asset.AssetId)
.input('projectAllocations', sql.NVarChar(sql.MAX), JSON.stringify(addAllocations(asset.ProjectAllocations, plan.allocations, borrowerName)))
.input('borrower', sql.NVarChar, plan.borrower)
.input('exportInPeriod', sql.Int, plan.exportInPeriod)
.input('endingBalance', sql.Int, plan.endingBalance)
.input('newQuantity', sql.Int, plan.newQuantity)
.input('usedQuantity', sql.Int, plan.usedQuantity)
.input('status', sql.NVarChar, plan.status)
.input('exportedBy', sql.NVarChar, exportedByName)
.input('notes', sql.NVarChar, plan.notes)
.query(`UPDATE AssetInventory SET ProjectAllocations = @projectAllocations, Borrower = @borrower,
ExportInPeriod = @exportInPeriod, EndingBalance = @endingBalance, NewQuantity = @newQuantity,
UsedQuantity = @usedQuantity, Status = @status, ExportedBy = @exportedBy, Notes = @notes,
UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME())
WHERE AssetId = @assetId AND IsArchived = 0`);
for (const allocation of plan.allocations) {
const result = await new sql.Request(transaction)
.input('assetId', sql.Int, asset.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, String(asset.Custodian || '').trim() || '-')
.input('exportedByName', sql.NVarChar, exportedByName)
.input('exportNote', sql.NVarChar, exportNote)
.input('createdBy', sql.Int, createdBy)
.input('exportedDate', sql.DateTime, exportedDate)
.input('documentId', sql.UniqueIdentifier, documentId)
.query(`INSERT INTO AssetExportHistory (AssetId, AssetCode, AssetName, ExportQuantity, ProjectName,
CustodianName, ExportedByName, ExportNote, CreatedBy, ExportedDate, ExportDocumentId)
OUTPUT INSERTED.*
VALUES (@assetId, @assetCode, @assetName, @exportQuantity, @projectName,
@custodianName, @exportedByName, @exportNote, @createdBy, @exportedDate, @documentId)`);
histories.push(result.recordset?.[0] || null);
}
.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, String(asset.Custodian || '').trim() || '-')
.input('exportedByName', sql.NVarChar, exportedByName)
.input('exportNote', sql.NVarChar, exportNote)
.input('createdBy', sql.Int, createdBy)
.input('exportedDate', sql.DateTime, exportedDate)
.input('documentId', sql.UniqueIdentifier, documentId)
.query(`INSERT INTO AssetExportHistory (AssetId, AssetCode, AssetName, ExportQuantity, ProjectName,
CustodianName, ExportedByName, ExportNote, CreatedBy, ExportedDate, ExportDocumentId)
OUTPUT INSERTED.*
VALUES (@assetId, @assetCode, @assetName, @exportQuantity, @projectName,
@custodianName, @exportedByName, @exportNote, @createdBy, @exportedDate, @documentId)`);
histories.push(result.recordset?.[0] || null);
}
await transaction.commit();
res.json({ success: true, message: 'Xuất tài sản thành công',
data: singleAssetId !== undefined && req.body.allocations === undefined ? histories[0] : histories,
document: { ...document, documentId } });
} catch (err) {
if (transaction) {
try { await transaction.rollback(); } catch (_rollbackErr) { /* Preserve the original error. */ }
}
if (err.statusCode) res.status(err.statusCode).json({ success: false, message: err.message });
else sendInternalError(res, err);
}
return { document: { ...document, documentId }, histories };
}
app.post('/api/assets/export', requireAssetOrAdmin, (req, res) => handleAssetExport(req, res));
app.post('/api/assets/:id/export', requireAssetOrAdmin, (req, res) => handleAssetExport(req, res, req.params.id));
const assetExportWorkflow = createAssetExportWorkflow({
getPool: () => pool, sql, requireManage: requireAssetOrAdmin, getRequesterRole, getUserIdFromRequest,
getUserDisplayNameById: id => getUserDisplayNameById(id), prepareAssetExport, performAssetExport, sendInternalError,
notifyCreated: target => safeCreateSystemNotification({
severity: 'info', title: 'Đơn xuất vào dự án mới',
message: `${target.RequesterName} đã gửi đơn xuất #${target.ExportRequestId}, chờ duyệt.`,
actionUrl: '#asset-exports', audiences: [{ type: 'role', value: 'admin' }, { type: 'role', value: 'asset' }]
}),
notifyProcessed: (target, action, rejectReason) => safeCreateSystemNotification({
severity: action === 'approved' ? 'success' : 'error',
title: action === 'approved' ? 'Đơn xuất dự án được duyệt' : 'Đơn xuất dự án bị từ chối',
message: `Đơn xuất #${target.ExportRequestId} đã ${action === 'approved' ? 'được duyệt và trừ kho' : `bị từ chối. Lý do: ${rejectReason}`}.`,
actionUrl: '#asset-exports', audiences: [{ type: 'user', value: Number(target.CreatedBy) }]
})
});
app.use('/api/asset-export-requests', assetExportWorkflow.router);
app.post('/api/assets/export', requireAssetOrAdmin, (req, res) => assetExportWorkflow.directExport(req, res));
app.post('/api/assets/:id/export', requireAssetOrAdmin, (req, res) => assetExportWorkflow.directExport(req, res, req.params.id));
app.post('/api/assets', requireAssetOrAdmin, async (req, res) => {
try {