/** * 送货单**图片**(小程序 canvas 出图)——开发者 2026-10-15 需求:分享出去的是**一张图片** * (参照「秒账」的微信分享卡片:卡片缩略图就是整张送货单)。 * * 与免登录 H5 送货单(`/d/`)**同字段、同口径**,避免客户看到两张不一样的单: * 编号、产品、单位、总数量、「单价(销售价,不是成本价)」、金额、备注、 * 「生产时间(本单**实际用掉的批次**的生产日期,跨批就多项,放最后一列)」,加合计与金额大写, * + 订货电话/地址 + 制单人/收货人(签字)。 * · 不显示「收款记录」(2026-10-15 开发者裁决:库里只有结算单级收款,不编数字) * · 商品名取**下单原文** `item_name`(口径甲,2026-10-15 裁决) * · 生产时间取自出库流水的批次(2026-10-20):未出库就没有流水 ⇒ 该格留空,**不猜批次** * · **保险**:后端没下发该字段(或整单没有任何生产日期)⇒ **整列不渲染**、退回原 7 列版式 * * 复用 `a4HistoryPrint` 的 canvas 取节点/导出套路(小程序原有先例)。 * 设计:docs/design/20261015-小程序送货单图片(canvas出图分享).md * docs/design/20261020-送货单图片增加生产时间列.md */ const { getCanvasNode } = require('./a4HistoryPrint'); const { amountInWords } = require('./amountInWords'); const W = 1000; const MARGIN = 40; const ROW_H = 44; const HEAD_H = 46; const LINE_H = 26; // 生产时间一格内多批次时的行距 const ROW_V_PAD = 14; // 多行格子的上下留白(行高 = 行数 * LINE_H + 该值) const FONT = '22px sans-serif'; const FONT_BOLD = 'bold 22px sans-serif'; /** 列宽:8 列(含生产时间)/ 7 列(保险:无生产时间数据时退回原版式),合计均为 W - 2*MARGIN = 920 */ function columns(showProduction) { const widths = showProduction ? [60, 220, 60, 90, 100, 110, 130, 150] : [70, 300, 70, 110, 110, 130, 130]; let x = MARGIN; return widths.map((w) => { const col = { x, w }; x += w; return col; }); } function ellipsize(ctx, text, maxWidth) { const value = String(text == null ? '' : 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 qtyText(value) { const num = Number(value) || 0; return Number.isInteger(num) ? String(num) : String(Number(num.toFixed(3))); } function money(value) { return (Number(value) || 0).toFixed(2); } /** 生产时间:一行商品可能跨多个批次(FIFO)⇒ 多个日期,逐行显示 */ function productionDateLines(item) { const raw = item && item.production_dates; const list = Array.isArray(raw) ? raw : []; return list.map((value) => String(value == null ? '' : value).trim()).filter(Boolean); } /** 该行实际高度:无生产时间或多批次时按行数撑高 */ function rowHeightFor(item) { const lines = productionDateLines(item).length; return Math.max(ROW_H, lines * LINE_H + ROW_V_PAD); } /** * 图片高度随行数增长(导出前要先确定画布尺寸)。 * 传 items 数组时按每行实际高度算(生产时间多批次会把行撑高);传数字时按默认行高(向后兼容)。 */ function deliveryNoteHeight(rowCountOrItems) { const items = Array.isArray(rowCountOrItems) ? rowCountOrItems : null; const bodyHeight = items ? (items.length ? items.reduce((sum, item) => sum + rowHeightFor(item), 0) : ROW_H) : ROW_H * Math.max(1, Number(rowCountOrItems) || 0); // 标题 + 单号/日期 + 客户 + 表头 + 行 + 合计行 + 汇总两行 + 底边距 return 120 + 42 + 40 + HEAD_H + ROW_H + bodyHeight + ROW_H + 40 + 40 + 40; } function sumBy(items, pick) { return (items || []).reduce((sum, item) => sum + (Number(pick(item)) || 0), 0); } /** * 在 canvas 2d 节点上绘制送货单。 * @param {*} canvas 2d canvas 节点 * @param {object} note { order_code, customer_name, sale_date, contact_phone, address, created_by_name, items:[{item_name,unit,quantity,price,amount,remark,production_dates}] } */ function drawDeliveryNote(canvas, note) { const items = (note && note.items) || []; const height = deliveryNoteHeight(items); canvas.width = W; canvas.height = height; const ctx = canvas.getContext('2d'); // 白底(相册/微信里直接是白纸观感) ctx.fillStyle = '#ffffff'; ctx.fillRect(0, 0, W, height); ctx.textBaseline = 'middle'; // ── 标题 + 单号 / 销售日期 + 客户 ── ctx.fillStyle = '#111111'; ctx.font = 'bold 40px sans-serif'; ctx.textAlign = 'center'; ctx.fillText('送货单', W / 2, 52); ctx.font = FONT; ctx.textAlign = 'left'; ctx.fillText('NO.' + String(note.order_code || ''), MARGIN, 104); ctx.textAlign = 'right'; ctx.fillText('销售日期:' + String(note.sale_date || ''), W - MARGIN, 104); ctx.textAlign = 'left'; ctx.font = FONT_BOLD; ctx.fillText('客户:' + String(note.customer_name || ''), MARGIN, 142); // ── 表格 ── // 保险(2026-10-20):后端没下发 `batch_production_dates`(老版服务端)或整单没有任何日期 // ⇒ **不渲染生产时间列**,退回原 7 列版式(不让客户看到一整列空白)。 const showProduction = items.some((item) => productionDateLines(item).length > 0); const cols = columns(showProduction); const tableRight = W - MARGIN; let y = 172; const drawRow = (cells, { bold = false, fill = null, rowH = ROW_H } = {}) => { if (fill) { ctx.fillStyle = fill; ctx.fillRect(MARGIN, y, tableRight - MARGIN, rowH); } ctx.fillStyle = '#111111'; ctx.font = bold ? FONT_BOLD : FONT; for (let i = 0; i < cols.length; i += 1) { const col = cols[i]; // 编号/产品/单位/生产时间/备注左对齐;总数量/单价/金额右对齐 const rightAligned = i === 3 || i === 4 || i === 5; ctx.textAlign = rightAligned ? 'right' : 'left'; const pad = 8; const maxWidth = col.w - pad * 2; const cx = rightAligned ? col.x + col.w - pad : col.x + pad; // 单元格可以是字符串,也可以是字符串数组(生产时间多批次 ⇒ 逐行绘制) const lines = Array.isArray(cells[i]) ? cells[i] : [cells[i] == null ? '' : String(cells[i])]; const blockHeight = lines.length * LINE_H; let ty = y + rowH / 2 - blockHeight / 2 + LINE_H / 2; for (const line of lines) { const value = line == null ? '' : String(line); ctx.fillText(ellipsize(ctx, value, maxWidth), cx, ty); ty += LINE_H; } } // 边框 ctx.strokeStyle = '#111111'; ctx.lineWidth = 1.5; ctx.strokeRect(MARGIN, y, tableRight - MARGIN, rowH); for (const col of cols) { ctx.beginPath(); ctx.moveTo(col.x, y); ctx.lineTo(col.x, y + rowH); ctx.stroke(); } ctx.beginPath(); ctx.moveTo(tableRight, y); ctx.lineTo(tableRight, y + rowH); ctx.stroke(); y += rowH; }; const header = ['编号', '产品', '单位', '总数量', '单价', '金额', '备注']; if (showProduction) header.push('生产时间'); drawRow(header, { bold: true, fill: '#f3f4f6' }); items.forEach((item, index) => { const cells = [ index + 1, item.item_name, item.unit, qtyText(item.quantity), money(item.price), money(item.amount), item.remark || '', ]; if (showProduction) cells.push(productionDateLines(item)); drawRow(cells, { rowH: rowHeightFor(item) }); }); const totalQty = sumBy(items, (item) => item.quantity); const totalAmount = sumBy(items, (item) => item.amount); const totalCells = ['', '合计', '', qtyText(totalQty), '', money(totalAmount), '']; if (showProduction) totalCells.push(''); drawRow(totalCells, { bold: true, fill: '#f3f4f6' }); // ── 汇总 + 金额大写 ── y += 34; ctx.font = FONT; ctx.fillStyle = '#111111'; ctx.textAlign = 'left'; ctx.fillText( `产品合计:${money(totalAmount)} 送货金额:${money(totalAmount)}`, MARGIN, y ); ctx.font = FONT_BOLD; ctx.textAlign = 'right'; ctx.fillText(`合计金额:${amountInWords(totalAmount)} ${money(totalAmount)}`, tableRight, y); // ── 电话 / 地址 / 制单人 / 收货人 ── y += 38; ctx.font = FONT; ctx.textAlign = 'left'; ctx.fillText('订货电话:' + (note.contact_phone || '-'), MARGIN, y); ctx.textAlign = 'right'; ctx.fillText('制单人:' + (note.created_by_name || '-'), tableRight, y); y += 34; ctx.textAlign = 'left'; ctx.fillText('订货地址:' + (note.address || '-'), MARGIN, y); ctx.textAlign = 'right'; ctx.fillText('收货人(签字):', tableRight, y); return height; } /** 取 canvas 节点 → 绘制 → 导出临时图片(返回 tempFilePath) */ async function exportDeliveryNoteImage(component, selector, note) { const canvas = await getCanvasNode(component, selector); drawDeliveryNote(canvas, note); return new Promise((resolve, reject) => { wx.canvasToTempFilePath( { canvas, fileType: 'png', destWidth: canvas.width, destHeight: canvas.height, success: (res) => resolve(res.tempFilePath), fail: (err) => reject(new Error((err && err.errMsg) || '生成送货单图片失败')), }, component ); }); } /** * 送货单图片的数据(与免登录 H5 送货单**同字段/同口径**): * · 商品名取下单原文 `item_name`(口径甲);单价取销售价 `price` * · 已退货行不打印(与 H5 一致);散客单客户名显示「散客录单」 * · 不打印「收款记录」(2026-10-15 开发者裁决) * * 2026-10-15 二次修改:入口从**订单详情页**移到**订单列表卡片**(开发者:「按钮别放到详情里面, * 放到订单列表的外面就行」)⇒ 本函数从详情页移到本工具,供列表直接复用。 */ function buildDeliveryNotePayload(order, items) { const rows = (items || []) .filter((item) => !item.is_returned) .map((item) => ({ item_name: item.item_name || item.sku_name || '', unit: item.unit || '', quantity: Number(item.quantity) || 0, price: Number(item.price) || 0, amount: Number(item.amount) || 0, remark: item.remark || '', // 本单**实际用掉的批次**的生产日期(服务端按出库流水聚合);未出库 ⇒ [] production_dates: Array.isArray(item.batch_production_dates) ? item.batch_production_dates.map((value) => String(value == null ? '' : value)).filter(Boolean) : [], })); const customerCode = String((order && order.customer_code) || ''); const saleDate = String((order && (order.delivery_date || order.created_at)) || '').slice(0, 10); return { order_code: String((order && order.order_code) || ''), customer_name: customerCode === '__RETAIL__' ? '散客录单' : String((order && (order.company_name || order.customer_code)) || ''), sale_date: saleDate, contact_phone: String((order && order.contact_phone) || ''), address: String((order && order.delivery_address) || ''), created_by_name: String((order && order.created_by_name) || ''), items: rows, }; } module.exports = { drawDeliveryNote, exportDeliveryNoteImage, deliveryNoteHeight, amountInWords, buildDeliveryNotePayload, };