xuất excel

This commit is contained in:
2026-10-14 09:10:37 +07:00
parent dff0d32912
commit 533923076c
19 changed files with 1655 additions and 236 deletions

View File

@@ -14,6 +14,8 @@ 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 { buildExportRequestWorkbook } = require('./export-request-workbook');
const { ensureAssetExportDocumentSchema } = require('./asset-export-documents');
dotenv.config();
@@ -3126,6 +3128,7 @@ async function createTables() {
// Fail startup if history preservation cannot be installed.
await ensureAssetArchiveSchema(pool);
await ensureAssetExportDocumentSchema(pool);
await pool.request().query(`
IF COL_LENGTH('dbo.AssetInventory', 'ProjectAllocations') IS NULL
ALTER TABLE dbo.AssetInventory ADD ProjectAllocations NVARCHAR(MAX) NULL;
@@ -8114,6 +8117,7 @@ app.post('/api/consumables/:id/export', requireAssetOrAdmin, async (req, res) =>
ConsumableId,
ConsumableCode,
ConsumableName,
Model,
Unit,
OpeningBalance,
ImportInPeriod,
@@ -8153,6 +8157,15 @@ app.post('/api/consumables/:id/export', requireAssetOrAdmin, async (req, res) =>
const nextExportInPeriod = previousExportInPeriod + exportQuantity;
const nextEndingBalance = Math.max(previousEndingBalance - exportQuantity, 0);
const document = await buildExportRequestWorkbook({
kind: 'consumable', item: consumable,
rows: [{ projectName: targetType === 'project' ? projectName : '', quantity: exportQuantity }],
availableStock: previousEndingBalance,
requesterName: targetType === 'user' ? recipientName : exportedByName,
recipientName: targetType === 'user' ? recipientName : '',
exportedByName, note: exportNote, exportedDate
});
await new sql.Request(transaction)
.input('consumableId', sql.Int, consumableId)
.input('exportInPeriod', sql.Int, nextExportInPeriod)
@@ -8246,7 +8259,8 @@ app.post('/api/consumables/:id/export', requireAssetOrAdmin, async (req, res) =>
res.json({
success: true,
message: 'Xuat vat tu tieu hao thanh cong',
data: historyResult.recordset?.[0] || null
data: historyResult.recordset?.[0] || null,
document
});
} catch (err) {
if (transaction) {
@@ -8589,21 +8603,13 @@ app.get('/api/asset-export-history', requireAssetOrAdmin, async (req, res) => {
.input('limit', sql.Int, limit)
.query(`
SELECT TOP (@limit)
ExportHistoryId,
AssetId,
AssetCode,
AssetName,
ExportQuantity,
ProjectName,
CustodianName,
ExportedByName,
ExportNote,
CreatedBy,
ExportedDate,
CreatedDate,
UpdatedDate
FROM AssetExportHistory
ORDER BY ExportedDate DESC, ExportHistoryId DESC
h.ExportHistoryId, h.AssetId, h.AssetCode, h.AssetName,
h.ExportQuantity, h.ProjectName, h.CustodianName, h.ExportedByName,
h.ExportNote, h.CreatedBy, h.ExportedDate, h.CreatedDate, h.UpdatedDate,
h.ExportDocumentId, d.FileName AS DocumentFileName
FROM AssetExportHistory h
LEFT JOIN AssetExportDocuments d ON d.ExportDocumentId = h.ExportDocumentId
ORDER BY h.ExportedDate DESC, h.ExportHistoryId DESC
`);
res.json({
@@ -8615,6 +8621,37 @@ app.get('/api/asset-export-history', requireAssetOrAdmin, async (req, res) => {
}
});
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) => {
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(`
SELECT ExportDocumentId, FileName, SnapshotJson FROM AssetExportDocuments WHERE ExportDocumentId = @documentId
`);
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.' });
res.setHeader('Cache-Control', 'private, no-store');
res.json({ success: true, data: { documentId: document.ExportDocumentId, fileName: document.FileName,
snapshot: JSON.parse(document.SnapshotJson) } });
} catch (err) { sendInternalError(res, err); }
});
app.get('/api/asset-export-documents/:id/download', requireAssetOrAdmin, 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(`
SELECT FileName, MimeType, FileContent FROM AssetExportDocuments WHERE ExportDocumentId = @documentId
`);
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.' });
res.setHeader('Cache-Control', 'private, no-store');
res.type(document.MimeType).attachment(document.FileName).send(Buffer.from(document.FileContent));
} catch (err) { sendInternalError(res, err); }
});
app.get('/api/asset-damage-disposal-history', requireAssetOrAdmin, async (req, res) => {
try {
const limit = Math.min(parsePositiveInteger(req.query.limit, 300), 2000);
@@ -8901,217 +8938,158 @@ app.post('/api/assets/:id/damage-disposal', requireAssetOrAdmin, async (req, res
}
});
app.post('/api/assets/:id/export', requireAssetOrAdmin, async (req, res) => {
function prepareAssetExport(asset, allocations, borrowerName, 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);
const importInPeriod = parseNonNegativeInteger(asset.ImportInPeriod, 0);
const previousBorrowerExport = parseBorrowerEntries(asset.Borrower)
.reduce((sum, entry) => sum + parseNonNegativeInteger(entry?.quantity, 0), 0);
const allocatedQuantity = parseAllocations(asset.ProjectAllocations).reduce((sum, row) => sum + row.quantity, 0);
const baseExportInPeriod = Math.max(parseOptionalNonNegativeInteger(asset.ExportInPeriod) || 0, previousBorrowerExport, allocatedQuantity);
const totalAvailable = Math.max(quantity + importInPeriod - baseExportInPeriod, 0);
const available = Math.min(parseOptionalNonNegativeInteger(asset.EndingBalance) ?? totalAvailable, totalAvailable);
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;
const stock = normalizeAssetStockBuckets(available,
parseOptionalNonNegativeInteger(asset.NewQuantity) ?? available,
parseOptionalNonNegativeInteger(asset.UsedQuantity) ?? 0);
const borrowFromNew = 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),
status: resolveAssetStatusFromStock(endingBalance, exportInPeriod),
notes: exportNote ? (oldNotes ? `${oldNotes}\n${exportNote}` : exportNote) : (oldNotes || null) };
}
async function handleAssetExport(req, res, singleAssetId) {
let transaction;
try {
const assetId = Number(req.params.id);
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 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();
if (!Number.isInteger(assetId) || assetId <= 0) {
return res.status(400).json({ success: false, message: 'Asset id is invalid' });
}
if (exportQuantity <= 0) {
return res.status(400).json({ success: false, message: 'So luong xuat phai lon hon 0' });
}
if (!borrowerName) {
return res.status(400).json({ success: false, message: 'Nguoi muon la bat buoc' });
}
transaction = new sql.Transaction(pool);
await transaction.begin();
const assetResult = 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,
Notes
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
`);
const asset = assetResult.recordset?.[0];
if (!asset) {
await transaction.rollback();
return res.status(404).json({ success: false, message: 'Asset not found' });
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]);
}
const quantity = parseNonNegativeInteger(asset.Quantity, 0);
const importInPeriod = parseNonNegativeInteger(asset.ImportInPeriod, 0);
const existingBorrowerEntries = parseBorrowerEntries(asset.Borrower);
const previousBorrowerExport = existingBorrowerEntries.reduce((sum, entry) => (
sum + parseNonNegativeInteger(entry?.quantity, 0)
), 0);
const storedExportInPeriod = parseOptionalNonNegativeInteger(asset.ExportInPeriod);
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 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(
baseEndingBalance,
baseNewQuantity !== null ? baseNewQuantity : baseEndingBalance,
baseUsedQuantity !== null ? baseUsedQuantity : 0
);
if (baseEndingBalance <= 0) {
await transaction.rollback();
return res.status(400).json({ success: false, message: 'Tai san da het ton cuoi ky, khong the xuat them' });
}
if (exportQuantity > baseEndingBalance) {
await transaction.rollback();
return res.status(400).json({
success: false,
message: `So luong xuat (${exportQuantity}) vuot qua ton cuoi ky (${baseEndingBalance})`
});
}
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)
), 0);
const exportDelta = nextBorrowerExport - previousBorrowerExport;
const nextExportInPeriod = Math.max(baseExportInPeriod + exportDelta, 0);
const nextEndingBalance = Math.max(baseEndingBalance - exportDelta, 0);
const borrowFromNew = Math.min(stockBuckets.newQuantity, exportDelta);
const borrowFromUsed = Math.max(exportDelta - borrowFromNew, 0);
const nextNewQuantity = Math.max(stockBuckets.newQuantity - borrowFromNew, 0);
const nextUsedQuantity = Math.max(stockBuckets.usedQuantity - borrowFromUsed, 0);
const nextStatus = resolveAssetStatusFromStock(nextEndingBalance, nextExportInPeriod);
const existingAssetNotes = String(asset.Notes || '').trim();
const cleanExportNote = String(exportNote || '').trim();
const nextAssetNotes = cleanExportNote
? (existingAssetNotes ? `${existingAssetNotes}\n${cleanExportNote}` : cleanExportNote)
: (existingAssetNotes || null);
await new sql.Request(transaction)
.input('assetId', sql.Int, assetId)
.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)
.input('newQuantity', sql.Int, nextNewQuantity)
.input('usedQuantity', sql.Int, nextUsedQuantity)
.input('status', sql.NVarChar, nextStatus)
.input('exportedBy', sql.NVarChar, exportedByName)
.input('notes', sql.NVarChar, nextAssetNotes)
.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
`);
const historyCustodianName = String(asset.Custodian || '').trim() || '-';
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: req.body.allocations === undefined ? histories[0] : histories
// 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
});
} catch (err) {
if (transaction) {
try {
await transaction.rollback();
} catch (_rollbackErr) {
// Ignore rollback error, respond original error below.
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 })) };
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)
.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);
}
}
sendInternalError(res, err);
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);
}
});
}
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));
app.post('/api/assets', requireAssetOrAdmin, async (req, res) => {
try {