Files
SupplierSystem/miniprogram/utils/a4HistoryPrint.js
T
Ubuntu deb3e72750
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库:jxc/ai-fresh-delivery
来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d
快照树:  09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件)

按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据
(生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、
deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

218 lines
6.3 KiB
JavaScript

const { buildJpegPdf, readFileBytes, writePdfFile } = require('./jpegPdf');
const A4_W = 1240;
const A4_H = 1754;
const MAX_PAGES = 12;
const MARGIN = 56;
const ROW_H = 36;
const HEADER_H = 148;
const FOOTER_H = 48;
function getCanvasNode(component, selector) {
const queryOnce = () =>
new Promise((resolve, reject) => {
component
.createSelectorQuery()
.select(selector)
.fields({ node: true, size: true })
.exec((res) => {
const node = res && res[0] && res[0].node;
if (!node) {
reject(new Error('打印画布不可用'));
return;
}
resolve(node);
});
});
return queryOnce().catch(() => new Promise((resolve, reject) => {
setTimeout(() => {
queryOnce().then(resolve).catch(reject);
}, 50);
}));
}
function canvasToJpeg(component, canvas) {
return new Promise((resolve, reject) => {
wx.canvasToTempFilePath(
{
canvas,
fileType: 'jpg',
quality: 0.82,
destWidth: canvas.width,
destHeight: canvas.height,
success: (res) => resolve(res.tempFilePath),
fail: (err) => reject(new Error(err.errMsg || '生成页面失败')),
},
component
);
});
}
function ellipsize(ctx, text, maxWidth) {
const value = String(text || '');
if (ctx.measureText(value).width <= maxWidth) return value;
let low = 0;
let high = value.length;
while (low < high) {
const mid = Math.ceil((low + high) / 2);
const next = `${value.slice(0, mid)}…`;
if (ctx.measureText(next).width <= maxWidth) low = mid;
else high = mid - 1;
}
return low <= 0 ? '…' : `${value.slice(0, low)}…`;
}
function sumAmounts(rows) {
let total = 0;
let count = 0;
for (const row of rows || []) {
const amount = Number(row[5]);
if (Number.isFinite(amount)) total += amount;
count += 1;
}
return { count, total: Math.round(total * 100) / 100 };
}
function colLayout() {
const inner = A4_W - MARGIN * 2;
const dateW = 150;
const qtyW = 110;
const unitW = 90;
const priceW = 120;
const totalW = 130;
const nameW = inner - dateW - qtyW - unitW - priceW - totalW;
let x = MARGIN;
const cols = [
{ key: 0, x, w: dateW, align: 'left' },
{ key: 1, x: (x += dateW), w: nameW, align: 'left' },
{ key: 2, x: (x += nameW), w: qtyW, align: 'right' },
{ key: 3, x: (x += qtyW), w: unitW, align: 'left' },
{ key: 4, x: (x += unitW), w: priceW, align: 'right' },
{ key: 5, x: (x += priceW), w: totalW, align: 'right' },
];
return cols;
}
function drawHeader(ctx, title, subtitle, pageIndex, pageCount) {
ctx.fillStyle = '#111';
ctx.font = 'bold 36px sans-serif';
ctx.textAlign = 'left';
ctx.textBaseline = 'top';
ctx.fillText(title, MARGIN, 40);
ctx.font = '22px sans-serif';
ctx.fillStyle = '#444';
ctx.fillText(subtitle || '', MARGIN, 88);
ctx.textAlign = 'right';
ctx.fillText(`${pageIndex + 1} / ${pageCount}`, A4_W - MARGIN, 88);
ctx.strokeStyle = '#111';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(MARGIN, 128);
ctx.lineTo(A4_W - MARGIN, 128);
ctx.stroke();
}
function drawTableHead(ctx, cols) {
const labels = ['日期', '商品名', '数量', '单位', '单价', '合计'];
ctx.font = 'bold 22px sans-serif';
ctx.fillStyle = '#111';
ctx.textBaseline = 'middle';
const y = HEADER_H - ROW_H / 2;
labels.forEach((label, i) => {
const col = cols[i];
ctx.textAlign = col.align === 'right' ? 'right' : 'left';
const tx = col.align === 'right' ? col.x + col.w - 8 : col.x + 8;
ctx.fillText(label, tx, y);
});
ctx.strokeStyle = '#ccc';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(MARGIN, HEADER_H);
ctx.lineTo(A4_W - MARGIN, HEADER_H);
ctx.stroke();
}
function drawRows(ctx, cols, pageRows) {
ctx.font = '22px sans-serif';
ctx.fillStyle = '#111';
ctx.textBaseline = 'middle';
pageRows.forEach((row, idx) => {
const y = HEADER_H + ROW_H * idx + ROW_H / 2;
if (idx % 2 === 1) {
ctx.fillStyle = '#f4f4f5';
ctx.fillRect(MARGIN, HEADER_H + ROW_H * idx, A4_W - MARGIN * 2, ROW_H);
ctx.fillStyle = '#111';
}
cols.forEach((col) => {
const raw = row[col.key];
const text = raw == null || raw === '' ? '' : String(raw);
ctx.textAlign = col.align === 'right' ? 'right' : 'left';
const tx = col.align === 'right' ? col.x + col.w - 8 : col.x + 8;
ctx.fillText(ellipsize(ctx, text, col.w - 16), tx, y);
});
});
}
function drawFooter(ctx, summary) {
ctx.strokeStyle = '#111';
ctx.lineWidth = 2;
const y = A4_H - FOOTER_H;
ctx.beginPath();
ctx.moveTo(MARGIN, y - 10);
ctx.lineTo(A4_W - MARGIN, y - 10);
ctx.stroke();
ctx.font = 'bold 22px sans-serif';
ctx.fillStyle = '#111';
ctx.textAlign = 'left';
ctx.textBaseline = 'top';
ctx.fillText(summary, MARGIN, y);
}
function rowsPerPage() {
return Math.floor((A4_H - HEADER_H - FOOTER_H) / ROW_H);
}
async function printA4FromRows(component, options) {
const rows = options.rows || [];
if (!rows.length) throw new Error(options.emptyText || '没有可打印的数据');
const perPage = rowsPerPage();
const pageCount = Math.ceil(rows.length / perPage);
if (pageCount > MAX_PAGES) {
throw new Error(`超过 ${MAX_PAGES} 页,请缩小日期范围后再打印`);
}
const canvas = await getCanvasNode(component, options.selector || '#printCanvas');
canvas.width = A4_W;
canvas.height = A4_H;
const ctx = canvas.getContext('2d');
const cols = colLayout();
const { count, total } = sumAmounts(rows);
const summary = `合计 ${count} 项 ¥${total}`;
const jpegPaths = [];
for (let i = 0; i < pageCount; i += 1) {
const slice = rows.slice(i * perPage, (i + 1) * perPage);
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, A4_W, A4_H);
drawHeader(ctx, options.title || '鲜配达', options.subtitle || '', i, pageCount);
drawTableHead(ctx, cols);
drawRows(ctx, cols, slice);
drawFooter(ctx, summary);
jpegPaths.push(await canvasToJpeg(component, canvas));
}
const jpegs = [];
for (const path of jpegPaths) {
jpegs.push(await readFileBytes(path));
}
const pdf = buildJpegPdf(jpegs);
const filePath = `${wx.env.USER_DATA_PATH}/${options.fileName || 'history-print.pdf'}`;
await writePdfFile(filePath, pdf);
return filePath;
}
module.exports = {
printA4FromRows,
getCanvasNode,
canvasToJpeg,
A4_W,
A4_H,
};