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, '>');
}
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(`]*\\br="${address}"[^>]*?)(?:/>|>[\\s\\S]*?)`);
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 ``;
if (typeof value === 'number') {
if (!Number.isFinite(value)) throw new Error('Invalid export request number');
return `${value}`;
}
// Explicit inline strings also prevent names/notes starting with '='
// from being interpreted as Excel formulas.
return `${xmlText(value)}`;
});
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(`]*\\br="${row}"[^>]*)>`), (_tag, attrs) => (
``
));
}
function wrapStyle(stylesXml, sourceIndex) {
let styleIndex;
const xml = stylesXml.replace(/]*)>([\s\S]*?)<\/cellXfs>/, (_block, attrs, content) => {
const styles = content.match(/]*(?:\/>|>[\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, alignmentAttrs) => (
``
));
return `${content}${newStyle}`;
});
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(/]*\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(/]*\br="(\d+)"[^>]*)>([\s\S]*?)<\/row>/g, (rowXml, attrs, rowNumber, cells) => {
const row = Number(rowNumber);
if (row < 18) return rowXml;
return `${cells.replace(/\br="([A-Z]+)(\d+)"/g,
(_ref, col, number) => `r="${col}${Number(number) + extra}"`)}
`;
});
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(`]*\\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(//, (_tag, count) => (
``
));
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(/]*?)\/>/, (_tag, attrs) => (
``
));
let workbook = readPart('xl/workbook.xml');
const names = `'ycxvt'!$A$1:$H$${24 + extra}`
+ `'ycxvt'!$8:$8`;
workbook = workbook.includes('')
? workbook.replace('', names + '')
: workbook.replace('${names}|]/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 };