Files
SupplierSystem/miniprogram/utils/deliveryNoteImage.js
T
Ubuntu bb16130549
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
feat(小程序): 送货单**图片**(canvas 出图 → 预览/存相册/分享给好友)
开发者需求(2026-10-15):「分享有点类似于这种效果,分享出的是一个图片」——参照「秒账」的
微信分享卡片:分享出去的主体是**一张送货单图片**(卡片下方那行应用名由微信按发出方显示,
不由我们自定义)。这与当天上午做的「分享**链接**(免登录 H5 /d/<token>)」是两件事,两者并存。

实现(小程序侧 canvas,复用既有 a4HistoryPrint 的取节点/导出套路):
- 新增 miniprogram/utils/deliveryNoteImage.js:按送货单版式绘制并 wx.canvasToTempFilePath 导出
  (标题/NO./销售日期/客户 + 编号·产品·单位·总数量·单价·金额·备注 + 合计 + 金额大写
   + 订货电话/地址 + 制单人/收货人(签字);长商品名 ellipsize 截断;高度随行数增长)
- 新增 miniprogram/utils/amountInWords.js:金额大写小程序副本(与服务端同算法)
- 订单详情页:隐藏 canvas + 「送货单图片」按钮 → 预览 / 保存到相册(无权限引导去设置)/
  分享给好友(不支持 showShareImageMenu 时降级为预览 + 长按保存转发)
- 后端只加两个返回字段(不改查询语义):移动端订单详情的 contact_phone、created_by_name

口径(与 H5 送货单一致,避免客户看到两张不一样的单):
- 单价取 order_items.price(销售价),**不打印成本价**;商品名取**下单原文** item_name(口径甲)
- **不打印收款记录**(2026-10-15 裁决);已退货行不打印;散客单客户名显示「散客录单」
- **独立进货单不给「送货单图片」入口**(不是给客户的货,与 /share-link 拒绝同口径)

验证:
- 新增契约测试 12/12 通过,含**小程序金额大写与服务端逐字对拍**(同一批边界值两侧输出完全相同)
- 后端 npx tsc --noEmit 0 错误;3 个新增/改动小程序 JS node --check 均 OK
- 后端全量 vitest 26 文件/33 用例失败 = 与基线一致,失败文件名无新增
- 设计门禁 run-all.sh --verify:通过 8 / 未通过 1(check-ai-cost 既有红)/ 未执行 1 = 基线

⚠️ 生效条件:① 小程序需用**微信开发者工具重新上传**一版;② 后端两个字段需**部署** server/dist 并重启。
⚠️ 本次**未**做服务端出图(开发者选了小程序端;生产机无中文字体,那条路要做时再装字体)。

设计:docs/design/20261015-小程序送货单图片(canvas出图分享).md
2026-10-15 13:41:19 +08:00

220 lines
7.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 送货单**图片**(小程序 canvas 出图)——开发者 2026-10-15 需求:分享出去的是**一张图片**
* (参照「秒账」的微信分享卡片:卡片缩略图就是整张送货单)。
*
* 与免登录 H5 送货单(`/d/<token>`)**同字段、同口径**,避免客户看到两张不一样的单:
* 编号、产品、单位、总数量、「单价(销售价,不是成本价)」、金额、备注,加合计与金额大写,
* + 订货电话/地址 + 制单人/收货人(签字)。
* · 不显示「收款记录」(2026-10-15 开发者裁决:库里只有结算单级收款,不编数字)
* · 商品名取**下单原文** `item_name`(口径甲,2026-10-15 裁决)
*
* 复用 `a4HistoryPrint` 的 canvas 取节点/导出套路(小程序原有先例)。
* 设计:docs/design/20261015-小程序送货单图片(canvas出图分享).md
*/
const { getCanvasNode } = require('./a4HistoryPrint');
const { amountInWords } = require('./amountInWords');
const W = 1000;
const MARGIN = 40;
const ROW_H = 44;
const HEAD_H = 46;
const FONT = '22px sans-serif';
const FONT_BOLD = 'bold 22px sans-serif';
/** 列宽:编号/产品/单位/总数量/单价/金额/备注(合计 = W - 2*MARGIN) */
function columns() {
const widths = [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);
}
/** 图片高度随行数增长(导出前要先确定画布尺寸) */
function deliveryNoteHeight(rowCount) {
const rows = Math.max(1, Number(rowCount) || 0);
// 标题 + 单号/日期 + 客户 + 表头 + 行 + 合计行 + 汇总两行 + 底边距
return 120 + 42 + 40 + HEAD_H + ROW_H * (rows + 1) + 44 + 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}] }
*/
function drawDeliveryNote(canvas, note) {
const items = (note && note.items) || [];
const height = deliveryNoteHeight(items.length);
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);
// ── 表格 ──
const cols = columns();
const tableRight = W - MARGIN;
let y = 172;
const drawRow = (cells, { bold = false, fill = null } = {}) => {
if (fill) {
ctx.fillStyle = fill;
ctx.fillRect(MARGIN, y, tableRight - MARGIN, ROW_H);
}
ctx.fillStyle = '#111111';
ctx.font = bold ? FONT_BOLD : FONT;
for (let i = 0; i < cols.length; i += 1) {
const col = cols[i];
const cell = cells[i] == null ? '' : String(cells[i]);
// 编号/产品/备注/单位左对齐;总数量/单价/金额右对齐
const rightAligned = i === 3 || i === 4 || i === 5;
ctx.textAlign = rightAligned ? 'right' : 'left';
const pad = 8;
const maxWidth = col.w - pad * 2;
const text = ellipsize(ctx, cell, maxWidth);
const cx = rightAligned ? col.x + col.w - pad : col.x + pad;
ctx.fillText(text, cx, y + ROW_H / 2);
}
// 边框
ctx.strokeStyle = '#111111';
ctx.lineWidth = 1.5;
ctx.strokeRect(MARGIN, y, tableRight - MARGIN, ROW_H);
for (const col of cols) {
ctx.beginPath();
ctx.moveTo(col.x, y);
ctx.lineTo(col.x, y + ROW_H);
ctx.stroke();
}
ctx.beginPath();
ctx.moveTo(tableRight, y);
ctx.lineTo(tableRight, y + ROW_H);
ctx.stroke();
y += ROW_H;
};
drawRow(['编号', '产品', '单位', '总数量', '单价', '金额', '备注'], { bold: true, fill: '#f3f4f6' });
items.forEach((item, index) => {
drawRow([
index + 1,
item.item_name,
item.unit,
qtyText(item.quantity),
money(item.price),
money(item.amount),
item.remark || '',
]);
});
const totalQty = sumBy(items, (item) => item.quantity);
const totalAmount = sumBy(items, (item) => item.amount);
drawRow(['', '合计', '', qtyText(totalQty), '', money(totalAmount), ''], {
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
);
});
}
module.exports = {
drawDeliveryNote,
exportDeliveryNoteImage,
deliveryNoteHeight,
amountInWords,
};