Files
order-notification-automation/src/exporter.cjs
T

96 lines
6.4 KiB
JavaScript

const fs = require('node:fs/promises');
const path = require('node:path');
const { loadPlaywright, browserOptions } = require('./runtime.cjs');
const fields = { order: '订单号', project: '项目编号', model: '产品型号', serial: '通知书编号' };
function buildFilename(metadata = {}) {
const parts = Object.entries(fields).map(([key, label]) => {
if (typeof metadata[key] !== 'string' || !metadata[key].trim()) throw new Error(`缺少${label},请在订单页检查。`);
const value = metadata[key].trim().replace(/[<>:"/\\|?*\x00-\x1f\x7f]/g, '_').replace(/[. ]+$/g, '').slice(0, 45);
if (!value || !/[^._ ]/.test(value)) throw new Error(`${label}不能用于文件名。`);
return value;
});
return parts.join('_') + '.pdf';
}
function validateSnapshot(snapshot) {
if (!snapshot || typeof snapshot.html !== 'string' || !snapshot.html.trim() || snapshot.html.length > 12_000_000) throw new Error('页面内容为空或超过大小限制。');
buildFilename(snapshot.metadata);
if (snapshot.bpmOrder != null && (
typeof snapshot.bpmOrder !== 'object' || Array.isArray(snapshot.bpmOrder) ||
!/^OFR_(?:LSCP|BS|KD|WY)_Applicant\.OrderNum$/.test(snapshot.bpmOrder.field) ||
typeof snapshot.bpmOrder.value !== 'string' || snapshot.bpmOrder.value !== snapshot.metadata.order
)) throw new Error('BPM 订单号字段与导出订单号不一致,请重新采集。');
if (snapshot.styles !== undefined && (!Array.isArray(snapshot.styles) || snapshot.styles.some(s => typeof s !== 'string'))) throw new Error('页面样式格式不正确。');
if (snapshot.images !== undefined && (!Array.isArray(snapshot.images) || snapshot.images.length > 200)) throw new Error('页面图片格式不正确。');
}
async function reserveFile(outputDir, filename) {
await fs.mkdir(outputDir, { recursive: true });
for (let index = 1; index <= 9999; index++) {
const suffix = index === 1 ? '' : ` (${index})`;
const target = path.join(outputDir, filename.slice(0, -4) + suffix + '.pdf');
try { const handle = await fs.open(target, 'wx'); return { target, handle }; }
catch (error) { if (error.code !== 'EEXIST') throw error; }
}
throw new Error('同名文件过多,请更换输出目录。');
}
async function renderSnapshot(snapshot, options = {}) {
validateSnapshot(snapshot);
const filename = buildFilename(snapshot.metadata);
const outputDir = path.resolve(options.outputDir || path.join(__dirname, '../output/pdf'));
const scale = options.scale ?? 0.59;
if (typeof scale !== 'number' || scale < 0.1 || scale > 2) throw new Error('scale 必须在 0.1 到 2 之间。');
const browser = await loadPlaywright().chromium.launch(browserOptions());
let reservation;
try {
const context = await browser.newContext({ javaScriptEnabled: false, serviceWorkers: 'block', viewport: { width: 1280, height: 1000 } });
await context.route('**/*', route => route.abort());
const page = await context.newPage();
await page.goto('about:blank');
// Only static markup enters the document. Network and page scripts stay disabled.
const content = await page.evaluate(({ html, styles, images, width }) => {
const doc = new DOMParser().parseFromString(html, 'text/html');
doc.querySelectorAll('script,iframe,object,embed,link,base,meta,input,button,textarea,select,[printout="false"],#taskCommentForm').forEach(el => el.remove());
doc.querySelectorAll('*').forEach(el => {
for (const attribute of [...el.attributes]) {
if (/^on/i.test(attribute.name) || ['action','srcdoc','srcset','formaction','href','poster','background'].includes(attribute.name.toLowerCase())) el.removeAttribute(attribute.name);
}
if (el.hidden || /display\s*:\s*none/i.test(el.getAttribute('style') || '')) el.remove();
});
const supplied = new Map((images || []).filter(image => image && typeof image.url === 'string' && /^data:image\/(png|jpeg|gif|webp);base64,[a-z0-9+/=\r\n]+$/i.test(image.data || '')).map(image => [image.url, image.data]));
doc.querySelectorAll('img').forEach(el => {
const value = supplied.get(el.getAttribute('src')) || el.getAttribute('src') || '';
if (/^data:image\/(png|jpeg|gif|webp);base64,[a-z0-9+/=\r\n]+$/i.test(value)) el.setAttribute('src', value); else el.remove();
});
const cleanCSS = css => css.replace(/@import\s+[^;]+;/gi, '').replace(/url\([^)]*\)/gi, 'none').replace(/<\/style/gi, '');
const css = (styles || []).map(cleanCSS).join('\n');
doc.querySelectorAll('style').forEach(el => el.remove());
const style = doc.createElement('style');
const pageWidth = Math.min(1264, Math.max(800, Number(width) || 1264));
style.textContent = css + `\nhtml,body{margin:0;padding:0;background:white}body,form{width:${pageWidth}px;font-family:Arial,"Microsoft YaHei",sans-serif}table{max-width:100%}tr{break-inside:avoid;page-break-inside:avoid}td{overflow-wrap:anywhere}a{color:inherit;text-decoration:none}span.TextBox,span.TextBoxPink{height:auto!important;min-height:16px}@media print{html,body{-webkit-print-color-adjust:exact;print-color-adjust:exact}}`;
doc.head.append(style);
doc.querySelectorAll('.yz-inp-cnt').forEach(el => {
const match = (el.getAttribute('style') || '').match(/width\s*:\s*([\d.]+)px/);
const text = el.textContent.trim();
if (match && Number(match[1]) <= 50 && text) el.style.width = Math.max(50, Math.min(120, text.length * 8)) + 'px';
});
return '<!doctype html>' + doc.documentElement.outerHTML;
}, snapshot);
await page.setContent(content, { waitUntil: 'load', timeout: 30000 });
await page.evaluate(() => document.fonts.ready);
const pdf = await page.pdf({ format: 'A4', scale, printBackground: true, displayHeaderFooter: false, margin: { top: '8mm', right: '6mm', bottom: '8mm', left: '6mm' } });
if (pdf.subarray(0, 5).toString() !== '%PDF-') throw new Error('PDF 生成失败。');
reservation = await reserveFile(outputDir, filename);
await reservation.handle.writeFile(pdf);
await reservation.handle.close();
return { path: reservation.target, filename: path.basename(reservation.target), bytes: pdf.length, warnings: snapshot.warnings || [] };
} catch (error) {
if (reservation) { await reservation.handle.close().catch(() => {}); await fs.unlink(reservation.target).catch(() => {}); }
throw error;
} finally { await browser.close(); }
}
module.exports = { buildFilename, validateSnapshot, renderSnapshot };