xuất excel
This commit is contained in:
8
backend/asset-export-documents.js
Normal file
8
backend/asset-export-documents.js
Normal file
@@ -0,0 +1,8 @@
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
async function ensureAssetExportDocumentSchema(pool) {
|
||||
await pool.request().batch(fs.readFileSync(path.join(__dirname, 'asset-export-documents.sql'), 'utf8'));
|
||||
}
|
||||
|
||||
module.exports = { ensureAssetExportDocumentSchema };
|
||||
27
backend/asset-export-documents.sql
Normal file
27
backend/asset-export-documents.sql
Normal file
@@ -0,0 +1,27 @@
|
||||
SET XACT_ABORT ON;
|
||||
BEGIN TRY
|
||||
BEGIN TRANSACTION;
|
||||
IF OBJECT_ID('dbo.AssetExportDocuments', 'U') IS NULL
|
||||
BEGIN
|
||||
CREATE TABLE dbo.AssetExportDocuments (
|
||||
ExportDocumentId UNIQUEIDENTIFIER NOT NULL PRIMARY KEY,
|
||||
FileName NVARCHAR(255) NOT NULL,
|
||||
MimeType NVARCHAR(150) NOT NULL,
|
||||
FileContent VARBINARY(MAX) NOT NULL,
|
||||
SnapshotJson NVARCHAR(MAX) NOT NULL,
|
||||
CreatedBy INT NULL,
|
||||
ExportedDate DATETIME NOT NULL,
|
||||
CreatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME()))
|
||||
);
|
||||
END;
|
||||
IF COL_LENGTH('dbo.AssetExportHistory', 'ExportDocumentId') IS NULL
|
||||
ALTER TABLE dbo.AssetExportHistory ADD ExportDocumentId UNIQUEIDENTIFIER NULL;
|
||||
IF NOT EXISTS (SELECT 1 FROM sys.foreign_keys WHERE name = 'FK_AssetExportHistory_Document')
|
||||
EXEC(N'ALTER TABLE dbo.AssetExportHistory ADD CONSTRAINT FK_AssetExportHistory_Document
|
||||
FOREIGN KEY (ExportDocumentId) REFERENCES dbo.AssetExportDocuments(ExportDocumentId)');
|
||||
COMMIT TRANSACTION;
|
||||
END TRY
|
||||
BEGIN CATCH
|
||||
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
|
||||
THROW;
|
||||
END CATCH;
|
||||
180
backend/export-request-workbook.js
Normal file
180
backend/export-request-workbook.js
Normal file
@@ -0,0 +1,180 @@
|
||||
const fs = require('node:fs/promises');
|
||||
const path = require('node:path');
|
||||
const crypto = require('node:crypto');
|
||||
const { CFB } = require('xlsx');
|
||||
|
||||
const TEMPLATE_PATH = path.join(__dirname, 'templates', 'export-request.xlsx');
|
||||
const MIME_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
|
||||
|
||||
function xmlText(value) {
|
||||
return String(value ?? '').replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\ufffe\uffff]/g, '')
|
||||
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
}
|
||||
|
||||
function setAttribute(attributes, name, value) {
|
||||
const pattern = new RegExp(`\\s${name}="[^"]*"`);
|
||||
return attributes.replace(pattern, '') + ` ${name}="${value}"`;
|
||||
}
|
||||
|
||||
// Edit only the fixed template's XML parts. A read/write through the SheetJS
|
||||
// worksheet model would discard its logo, print settings and annotations.
|
||||
function writeCell(xml, address, value, style) {
|
||||
const pattern = new RegExp(`<c\\b([^>]*\\br="${address}"[^>]*?)(?:/>|>[\\s\\S]*?</c>)`);
|
||||
let found = false;
|
||||
const result = xml.replace(pattern, (_cell, originalAttributes) => {
|
||||
found = true;
|
||||
let attributes = originalAttributes.replace(/\s+t="[^"]*"/g, '');
|
||||
if (style !== undefined) attributes = setAttribute(attributes, 's', style);
|
||||
if (value === null || value === undefined || value === '') return `<c${attributes}/>`;
|
||||
if (typeof value === 'number') {
|
||||
if (!Number.isFinite(value)) throw new Error('Invalid export request number');
|
||||
return `<c${attributes}><v>${value}</v></c>`;
|
||||
}
|
||||
// Explicit inline strings also prevent names/notes starting with '='
|
||||
// from being interpreted as Excel formulas.
|
||||
return `<c${attributes} t="inlineStr"><is><t xml:space="preserve">${xmlText(value)}</t></is></c>`;
|
||||
});
|
||||
if (!found) throw new Error(`Export request template is missing cell ${address}`);
|
||||
return result;
|
||||
}
|
||||
|
||||
function setRowHeight(xml, row, height) {
|
||||
height = Math.min(height, 409.5); // Excel's maximum row height in points.
|
||||
return xml.replace(new RegExp(`<row\\b([^>]*\\br="${row}"[^>]*)>`), (_tag, attrs) => (
|
||||
`<row${setAttribute(setAttribute(attrs, 'ht', height), 'customHeight', 1)}>`
|
||||
));
|
||||
}
|
||||
|
||||
function wrapStyle(stylesXml, sourceIndex) {
|
||||
let styleIndex;
|
||||
const xml = stylesXml.replace(/<cellXfs\b([^>]*)>([\s\S]*?)<\/cellXfs>/, (_block, attrs, content) => {
|
||||
const styles = content.match(/<xf\b[^>]*(?:\/>|>[\s\S]*?<\/xf>)/g);
|
||||
if (!styles?.[sourceIndex]) throw new Error('Export request template styles are invalid');
|
||||
styleIndex = styles.length;
|
||||
const newStyle = styles[sourceIndex].replace(/<alignment\b([^>]*?)\/>/, (_alignment, alignmentAttrs) => (
|
||||
`<alignment${setAttribute(alignmentAttrs, 'wrapText', 1)}/>`
|
||||
));
|
||||
return `<cellXfs${setAttribute(attrs, 'count', styles.length + 1)}>${content}${newStyle}</cellXfs>`;
|
||||
});
|
||||
if (styleIndex === undefined) throw new Error('Export request template styles are missing');
|
||||
return { xml, index: styleIndex };
|
||||
}
|
||||
|
||||
function extendRows(xml, extra) {
|
||||
if (!extra) return xml;
|
||||
const templateRow = xml.match(/<row\b[^>]*\br="10"[^>]*>[\s\S]*?<\/row>/)?.[0];
|
||||
if (!templateRow) throw new Error('Export request template is missing its detail row');
|
||||
// Insert before the last detail row, retaining that row's bottom border.
|
||||
xml = xml.replace(/<row\b([^>]*\br="(\d+)"[^>]*)>([\s\S]*?)<\/row>/g, (rowXml, attrs, rowNumber, cells) => {
|
||||
const row = Number(rowNumber);
|
||||
if (row < 18) return rowXml;
|
||||
return `<row${setAttribute(attrs, 'r', row + extra)}>${cells.replace(/\br="([A-Z]+)(\d+)"/g,
|
||||
(_ref, col, number) => `r="${col}${Number(number) + extra}"`)}</row>`;
|
||||
});
|
||||
const added = Array.from({ length: extra }, (_, index) => templateRow
|
||||
.replace(/\br="10"/, `r="${18 + index}"`)
|
||||
.replace(/\br="([A-Z]+)10"/g, (_ref, col) => `r="${col}${18 + index}"`)).join('');
|
||||
xml = xml.replace(new RegExp(`<row\\b[^>]*\\br="${18 + extra}"[^>]*>`), match => added + match);
|
||||
return xml.replace(/\bref="([A-Z]+)(\d+):([A-Z]+)(\d+)"/g, (_ref, left, start, right, end) => (
|
||||
`ref="${left}${Number(start) >= 18 ? Number(start) + extra : start}:${right}${Number(end) >= 18 ? Number(end) + extra : end}"`
|
||||
));
|
||||
}
|
||||
|
||||
function wrappedLines(value, width) {
|
||||
return String(value || '').split('\n').reduce((total, line) => total + Math.max(1, Math.ceil(line.length / width)), 0);
|
||||
}
|
||||
|
||||
async function buildExportRequestWorkbook({ item, rows, availableStock, items, requesterName, recipientName,
|
||||
exportedByName, note = '', exportedDate = new Date(), kind = 'asset' }, { templatePath = TEMPLATE_PATH } = {}) {
|
||||
const entries = items ?? [{ item, rows, availableStock }];
|
||||
if (!Array.isArray(entries) || !entries.length || entries.length > 100) throw new Error('Invalid export request items');
|
||||
const detailRows = entries.flatMap(entry => {
|
||||
if (!entry.item || !Array.isArray(entry.rows) || !entry.rows.length) throw new Error('Invalid export request rows');
|
||||
if (!Number.isSafeInteger(entry.availableStock) || entry.availableStock < 0) throw new Error('Invalid export request stock');
|
||||
let remaining = entry.availableStock;
|
||||
return entry.rows.map(row => {
|
||||
if (!Number.isSafeInteger(row.quantity) || row.quantity <= 0 || row.quantity > remaining) throw new Error('Export request exceeds stock');
|
||||
const detail = { ...row, item: entry.item, availableStock: remaining };
|
||||
remaining -= row.quantity;
|
||||
return detail;
|
||||
});
|
||||
});
|
||||
if (detailRows.length > 100) throw new Error('Invalid export request rows');
|
||||
const department = [...new Set(entries.map(entry => String(entry.item.Department || '').trim()).filter(Boolean))].join(', ');
|
||||
|
||||
const container = CFB.read(await fs.readFile(templatePath), { type: 'buffer' });
|
||||
const readPart = name => {
|
||||
const part = CFB.find(container, `Root Entry/${name}`);
|
||||
if (!part) throw new Error(`Export request template is missing ${name}`);
|
||||
return Buffer.from(part.content).toString('utf8');
|
||||
};
|
||||
const writePart = (name, value) => CFB.utils.cfb_add(container, `Root Entry/${name}`, Buffer.from(value, 'utf8'));
|
||||
|
||||
let sheet = readPart('xl/worksheets/sheet1.xml');
|
||||
let styles = readPart('xl/styles.xml');
|
||||
const headerStyle = wrapStyle(styles, 37);
|
||||
const contentStyle = wrapStyle(headerStyle.xml, 4);
|
||||
styles = contentStyle.xml;
|
||||
const extra = Math.max(0, detailRows.length - 10);
|
||||
sheet = extendRows(sheet, extra);
|
||||
|
||||
const dateParts = new Intl.DateTimeFormat('en-GB', { timeZone: 'Asia/Ho_Chi_Minh',
|
||||
year: 'numeric', month: '2-digit', day: '2-digit' }).formatToParts(new Date(exportedDate));
|
||||
const datePart = type => dateParts.find(part => part.type === type).value;
|
||||
const date = `${datePart('day')}/${datePart('month')}/${datePart('year')}`;
|
||||
sheet = writeCell(sheet, 'G5', `Ngày đề nghị: ${date}`, headerStyle.index);
|
||||
sheet = writeCell(sheet, 'G6', `Người đề nghị: ${requesterName || ''}`, headerStyle.index);
|
||||
sheet = writeCell(sheet, 'G7', `Bộ phận sử dụng: ${department}`, headerStyle.index);
|
||||
const content = [`Nội dung: Xuất ${kind === 'consumable' ? 'vật tư' : 'tài sản'}${recipientName ? ` cho ${recipientName}` : ''}.`,
|
||||
exportedByName ? `Người xuất: ${exportedByName}.` : '', note].filter(Boolean).join(' ');
|
||||
sheet = writeCell(sheet, 'A7', content, contentStyle.index);
|
||||
sheet = sheet.replace(/<mergeCells count="(\d+)">/, (_tag, count) => (
|
||||
`<mergeCells count="${Number(count) + 1}"><mergeCell ref="A7:F7"/>`
|
||||
));
|
||||
sheet = setRowHeight(sheet, 5, 30);
|
||||
sheet = setRowHeight(sheet, 6, Math.max(30, wrappedLines(`Người đề nghị: ${requesterName || ''}`, 42) * 16 + 8));
|
||||
sheet = setRowHeight(sheet, 7, Math.max(32, wrappedLines(content, 92) * 16 + 8,
|
||||
wrappedLines(`Bộ phận sử dụng: ${department}`, 42) * 16 + 8));
|
||||
|
||||
const code = entries.length === 1
|
||||
? String(entries[0].item.AssetCode || entries[0].item.ConsumableCode || '').trim()
|
||||
: 'NHIEU-TAI-SAN';
|
||||
detailRows.forEach((row, index) => {
|
||||
const item = row.item;
|
||||
const itemCode = String(item.AssetCode || item.ConsumableCode || '').trim();
|
||||
const description = [item.AssetName || item.ConsumableName || '', itemCode ? `Mã: ${itemCode}` : '',
|
||||
item.Model ? `Model: ${item.Model}` : '', item.SerialNumber ? `Serial: ${item.SerialNumber}` : ''].filter(Boolean).join('\n');
|
||||
const number = index + 9;
|
||||
const purpose = String(row.projectName || recipientName || '').trim();
|
||||
const values = [index + 1, description, item.Unit || '', row.quantity, row.availableStock, row.quantity, null, purpose];
|
||||
values.forEach((value, column) => {
|
||||
sheet = writeCell(sheet, `${String.fromCharCode(65 + column)}${number}`, value,
|
||||
column === 1 ? 13 : column === 7 ? 12 : undefined);
|
||||
});
|
||||
sheet = setRowHeight(sheet, number, Math.max(32, wrappedLines(description, 24) * 16 + 8,
|
||||
wrappedLines(purpose, 31) * 16 + 8, wrappedLines(item.Unit, 14) * 16 + 8));
|
||||
});
|
||||
// Retain all signature labels and placeholders. No signatory names/dates
|
||||
// are populated. The optional import sheet and drawing parts stay intact.
|
||||
sheet = sheet.replace(/<pageSetup\b([^>]*?)\/>/, (_tag, attrs) => (
|
||||
`<pageSetup${setAttribute(setAttribute(attrs.replace(/\s+scale="[^"]*"/, ''), 'fitToWidth', 1), 'fitToHeight', extra ? 0 : 1)}/>`
|
||||
));
|
||||
let workbook = readPart('xl/workbook.xml');
|
||||
const names = `<definedName name="_xlnm.Print_Area" localSheetId="0">'ycxvt'!$A$1:$H$${24 + extra}</definedName>`
|
||||
+ `<definedName name="_xlnm.Print_Titles" localSheetId="0">'ycxvt'!$8:$8</definedName>`;
|
||||
workbook = workbook.includes('</definedNames>')
|
||||
? workbook.replace('</definedNames>', names + '</definedNames>')
|
||||
: workbook.replace('<calcPr', `<definedNames>${names}</definedNames><calcPr`);
|
||||
writePart('xl/worksheets/sheet1.xml', sheet);
|
||||
writePart('xl/styles.xml', styles);
|
||||
writePart('xl/workbook.xml', workbook);
|
||||
const buffer = CFB.write(container, { type: 'buffer', fileType: 'zip', compression: true });
|
||||
const safeCode = code.replace(/[\u0000-\u001f\u007f\\/:*?"<>|]/g, '_').slice(0, 80) || 'vat-tu';
|
||||
return {
|
||||
fileName: `DE-NGHI-XUAT-${safeCode}-${datePart('year')}${datePart('month')}${datePart('day')}-${crypto.randomUUID().slice(0, 8)}.xlsx`,
|
||||
mimeType: MIME_TYPE,
|
||||
contentBase64: Buffer.from(buffer).toString('base64')
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { buildExportRequestWorkbook, TEMPLATE_PATH, MIME_TYPE };
|
||||
@@ -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 {
|
||||
|
||||
BIN
backend/templates/export-request.xlsx
Normal file
BIN
backend/templates/export-request.xlsx
Normal file
Binary file not shown.
Reference in New Issue
Block a user