fix(label): 排不下或缺码时拒绝打印,绝不发半张
plan_label 标出 overflow;打印路径(TSPL/ZPL)遇到就返回失败不发数据; 二维码容量表补到 version 40,超长/非 GBK 容器码不再猜错尺寸。 新增 120 组随机长文本压力用例与拒打用例。
This commit is contained in:
+82
-35
@@ -203,13 +203,31 @@ def _wrap(text, font, max_w, max_lines=2):
|
||||
|
||||
|
||||
def _qr_modules(n_bytes):
|
||||
"""QR 版本 → 模块数(ECC=H 的保守估算表)"""
|
||||
"""QR 版本 → 模块数(ECC=H 的容量表,最多到 version 40)
|
||||
|
||||
以前 >154 字节一律返回 69,超长容器码会把码高估小,印出来可能
|
||||
超出保留区。现在按真实容量表取,最大 1273 字节 / 177 模块。
|
||||
"""
|
||||
for limit, mods in ((7, 21), (14, 25), (24, 29), (34, 33), (44, 37),
|
||||
(58, 41), (64, 45), (84, 49), (98, 53), (119, 57),
|
||||
(139, 61), (154, 65)):
|
||||
(137, 61), (155, 65), (177, 69), (194, 73),
|
||||
(220, 77), (250, 81), (280, 85), (310, 89),
|
||||
(338, 93), (382, 97), (403, 101), (439, 105),
|
||||
(461, 109), (511, 113), (535, 117), (593, 121),
|
||||
(625, 125), (658, 129), (698, 133), (742, 137),
|
||||
(790, 141), (842, 145), (898, 149), (958, 153),
|
||||
(983, 157), (1051, 161), (1093, 165), (1139, 169),
|
||||
(1219, 173), (1273, 177)):
|
||||
if n_bytes <= limit:
|
||||
return mods
|
||||
return 69
|
||||
return 177
|
||||
|
||||
|
||||
_QR_MAX_BYTES = 1273 # ECC=H、version 40 的字节上限
|
||||
|
||||
|
||||
class LabelOverflow(ValueError):
|
||||
"""版面排不下(或二维码数据打不出):宁可报错,也不打截断/缺码的标签"""
|
||||
|
||||
|
||||
def plan_label(cfg, title, fields, qr_data=''):
|
||||
@@ -234,8 +252,19 @@ def plan_label(cfg, title, fields, qr_data=''):
|
||||
qr = None
|
||||
qr_w = 0
|
||||
qr_gap = 0
|
||||
overflow = False
|
||||
if qr_data:
|
||||
mods = _qr_modules(len(str(qr_data).encode('gbk', 'ignore')))
|
||||
try:
|
||||
raw_qr = str(qr_data).encode('gbk')
|
||||
except UnicodeEncodeError:
|
||||
raw_qr = b''
|
||||
warn.append('容器码含打印机不支持的字符(非 GBK),本次不打印')
|
||||
overflow = True
|
||||
if len(raw_qr) > _QR_MAX_BYTES:
|
||||
warn.append('容器码过长(%d 字节),一张二维码最多 %d 字节;'
|
||||
'本次不打印' % (len(raw_qr), _QR_MAX_BYTES))
|
||||
overflow = True
|
||||
mods = _qr_modules(len(raw_qr))
|
||||
# 文字和二维码之间留 2mm(=二维码左侧 4 个模块静区,扫码不受干扰)
|
||||
qr_gap = int(round(2 * dpm))
|
||||
# 二维码随纸型动态放大/缩小:最大占纸高 42%、纸宽 34%,
|
||||
@@ -326,6 +355,7 @@ def plan_label(cfg, title, fields, qr_data=''):
|
||||
if len(rows) * font * ratio > avail_h + 1:
|
||||
warn.append('内容太长,这张标签排不下全部文字;'
|
||||
'请加大标签或缩短商品名/客户名')
|
||||
overflow = True
|
||||
else:
|
||||
warn.append('内容较长,已压缩行距排满整张标签')
|
||||
|
||||
@@ -358,7 +388,15 @@ def plan_label(cfg, title, fields, qr_data=''):
|
||||
'gap_dots': int(round(gap_mm * dpm)),
|
||||
'gap_mm': gap_mm,
|
||||
'font': font, 'n_lines': n,
|
||||
'text_w': int(text_w), 'warnings': warn}
|
||||
'text_w': int(text_w), 'warnings': warn, 'overflow': overflow}
|
||||
|
||||
|
||||
def _checked(p):
|
||||
"""打印路径专用:排不下/码打不出就抛异常,绝不把半张标签发出去"""
|
||||
if p.get('overflow'):
|
||||
msg = ';'.join(p.get('warnings') or []) or '标签排不下全部内容'
|
||||
raise LabelOverflow(msg)
|
||||
return p
|
||||
|
||||
|
||||
def _tspl_from_plan(p):
|
||||
@@ -389,23 +427,23 @@ def build_picking_label_tspl(cfg, customer, item_name, weight, unit, date_str,
|
||||
order_code=''):
|
||||
# 参数名保留 order_code 兼容旧调用;v1.0.64 起传的是服务端容器码
|
||||
# (container_code),二维码只能用这个,不能用订单号。
|
||||
p = plan_label(cfg, '分拣标签',
|
||||
['客户: %s' % customer,
|
||||
'品名: %s' % item_name,
|
||||
'%s: %.2f %s' % (qty_word(unit), weight, unit),
|
||||
'日期: %s' % date_str],
|
||||
qr_data=order_code or '')
|
||||
p = _checked(plan_label(cfg, '分拣标签',
|
||||
['客户: %s' % customer,
|
||||
'品名: %s' % item_name,
|
||||
'%s: %.2f %s' % (qty_word(unit), weight, unit),
|
||||
'日期: %s' % date_str],
|
||||
qr_data=order_code or ''))
|
||||
return _tspl_from_plan(p)
|
||||
|
||||
|
||||
def build_inspection_label_tspl(cfg, order_code, item_name, weight, unit,
|
||||
supplier, date_str):
|
||||
p = plan_label(cfg, '验收标签',
|
||||
['订单: %s' % order_code,
|
||||
'品名: %s' % item_name,
|
||||
'%s: %.2f %s' % (qty_word(unit), weight, unit),
|
||||
'供应商: %s' % supplier,
|
||||
'时间: %s' % date_str])
|
||||
p = _checked(plan_label(cfg, '验收标签',
|
||||
['订单: %s' % order_code,
|
||||
'品名: %s' % item_name,
|
||||
'%s: %.2f %s' % (qty_word(unit), weight, unit),
|
||||
'供应商: %s' % supplier,
|
||||
'时间: %s' % date_str]))
|
||||
return _tspl_from_plan(p)
|
||||
|
||||
|
||||
@@ -417,7 +455,7 @@ def build_zpl(cfg, title, fields, qr_data=None):
|
||||
现在复用 TSPL 的自适应结果(折行、原子串不拆、二维码位置),
|
||||
只把 TEXT/QRCODE 换成 ZPL 的 ^FO/^A0N/^BQN。
|
||||
"""
|
||||
p = plan_label(cfg, title, fields, qr_data or '')
|
||||
p = _checked(plan_label(cfg, title, fields, qr_data or ''))
|
||||
g = p['geom']
|
||||
out = ['^XA^CI28^PW%d^LL%d^LH0,0' % (g['w'], g['h'])]
|
||||
for ln in p['lines']:
|
||||
@@ -533,27 +571,36 @@ class LabelPrinter:
|
||||
def print_picking(self, customer, item_name, weight, unit, order_code=''):
|
||||
# order_code 为兼容旧调用保留的名字;调用方实际传容器码
|
||||
date_str = datetime.datetime.now().strftime('%m-%d %H:%M')
|
||||
if self.cfg.get('type') == 'zpl':
|
||||
data = build_zpl(self.cfg, '分拣标签',
|
||||
['客户: %s' % customer, '品名: %s' % item_name,
|
||||
'%s: %.2f %s' % (qty_word(unit), weight, unit),
|
||||
'日期: %s' % date_str], order_code)
|
||||
else:
|
||||
data = build_picking_label_tspl(self.cfg, customer, item_name,
|
||||
weight, unit, date_str, order_code)
|
||||
try:
|
||||
if self.cfg.get('type') == 'zpl':
|
||||
data = build_zpl(self.cfg, '分拣标签',
|
||||
['客户: %s' % customer, '品名: %s' % item_name,
|
||||
'%s: %.2f %s' % (qty_word(unit), weight, unit),
|
||||
'日期: %s' % date_str], order_code)
|
||||
else:
|
||||
data = build_picking_label_tspl(self.cfg, customer, item_name,
|
||||
weight, unit, date_str,
|
||||
order_code)
|
||||
except LabelOverflow as e:
|
||||
# 排不下/码打不出:宁可不发,也不打截断或缺码的标签
|
||||
return False, '本次未打印:%s' % e
|
||||
return self._send(data)
|
||||
|
||||
def print_inspection(self, order_code, item_name, weight, unit, supplier):
|
||||
date_str = datetime.datetime.now().strftime('%m-%d %H:%M')
|
||||
if self.cfg.get('type') == 'zpl':
|
||||
data = build_zpl(self.cfg, '验收标签',
|
||||
['订单: %s' % order_code, '品名: %s' % item_name,
|
||||
'%s: %.2f %s' % (qty_word(unit), weight, unit),
|
||||
'供应商: %s' % supplier, '时间: %s' % date_str])
|
||||
else:
|
||||
data = build_inspection_label_tspl(
|
||||
self.cfg, order_code, item_name, weight, unit, supplier,
|
||||
date_str)
|
||||
try:
|
||||
if self.cfg.get('type') == 'zpl':
|
||||
data = build_zpl(self.cfg, '验收标签',
|
||||
['订单: %s' % order_code, '品名: %s' % item_name,
|
||||
'%s: %.2f %s' % (qty_word(unit), weight, unit),
|
||||
'供应商: %s' % supplier,
|
||||
'时间: %s' % date_str])
|
||||
else:
|
||||
data = build_inspection_label_tspl(
|
||||
self.cfg, order_code, item_name, weight, unit, supplier,
|
||||
date_str)
|
||||
except LabelOverflow as e:
|
||||
return False, '本次未打印:%s' % e
|
||||
return self._send(data)
|
||||
|
||||
def send_raw(self, data, doc_name='标签'):
|
||||
|
||||
@@ -180,5 +180,92 @@ for (wmm, hmm) in ((50, 50), (60, 40)):
|
||||
x + mods * cell <= wmm * 8 and y + mods * cell <= hmm * 8,
|
||||
'x=%d y=%d size=%d' % (x, y, mods * cell))
|
||||
|
||||
print('总计:%d 通过,%d 失败' % (ok, fail))
|
||||
|
||||
# ---- 随机长文本压力:真实前缀 + 随机长度,4 种常用纸型 ----
|
||||
print('=== 随机长文本压力(不截断 / 不缺码) ===')
|
||||
import random
|
||||
|
||||
random.seed(20261123)
|
||||
POOL = ('红富士苹果蔬菜水果批发市场配送中心农夫山泉饮用天然水'
|
||||
'上海青小棠菜土豆白萝卜冬瓜南瓜青椒黄果柑蒜苗菠菜'
|
||||
'abcABC0123456789 -_/().:×·()')
|
||||
STRESS_SIZES = [(60, 40), (76, 60), (80, 60), (50, 50), (70, 50)]
|
||||
|
||||
|
||||
def _rand_txt(n):
|
||||
return ''.join(random.choice(POOL) for _ in range(n))
|
||||
|
||||
|
||||
for i in range(120):
|
||||
wmm, hmm = STRESS_SIZES[i % len(STRESS_SIZES)]
|
||||
cfg = {'width_mm': wmm, 'height_mm': hmm, 'dpi': 203, 'gap_mm': 2}
|
||||
title = '分拣标签'
|
||||
fields = ['客户: ' + _rand_txt(random.randint(4, 20)),
|
||||
'品名: ' + _rand_txt(random.randint(4, 24)),
|
||||
'数量: %.2f 桶' % (random.random() * 999),
|
||||
'日期: 11-23 12:29']
|
||||
qr = 'CT' + ''.join(random.choice('0123456789ABCDEF') for _ in range(18))
|
||||
p = L.plan_label(cfg, title, fields, qr_data=qr)
|
||||
src = L._safe_text(title) + ''.join(L._safe_text(f) for f in fields)
|
||||
got = ''.join(ln['text'] for ln in p['lines'])
|
||||
q = p['qr']
|
||||
g = p['geom']
|
||||
bad = []
|
||||
if p.get('overflow'):
|
||||
bad.append('overflow=%s' % (p['warnings'],))
|
||||
if got != src:
|
||||
bad.append('内容不完整')
|
||||
for ln in p['lines']:
|
||||
if ln['x'] + ln['w'] > g['w'] or ln['y'] + ln['font'] > g['h']:
|
||||
bad.append('行越纸')
|
||||
if q and ln['x'] + ln['w'] > q['x']:
|
||||
bad.append('文字压码')
|
||||
if not q:
|
||||
bad.append('缺码')
|
||||
elif (q['x'] < 0 or q['y'] < 0 or q['x'] + q['size'] > g['w']
|
||||
or q['y'] + q['size'] > g['h']):
|
||||
bad.append('码越纸')
|
||||
check('压力 #%d %dx%d' % (i, wmm, hmm), not bad,
|
||||
'%s | %r' % ('; '.join(sorted(set(bad))), fields))
|
||||
|
||||
# ---- 打不出来时坚决不发数据:排不下 / 容器码过长 ----
|
||||
print('=== 排不下就拒打(不发半张) ===')
|
||||
sent = []
|
||||
|
||||
|
||||
class _FakePrinter(L.LabelPrinter):
|
||||
def _send(self, data, doc_name='标签'):
|
||||
sent.append(data)
|
||||
return True, 'fake'
|
||||
|
||||
|
||||
pr = _FakePrinter({'printer': {'type': 'tspl', 'width_mm': 35, 'height_mm': 25,
|
||||
'gap_mm': 2, 'dpi': 203}})
|
||||
ok_bad, msg_bad = pr.print_picking('客' * 120, '品' * 120, 1.0, '斤', 'CT1')
|
||||
check('排不下时返回失败', ok_bad is False, str((ok_bad, msg_bad)))
|
||||
check('排不下时一个字节都不发', not sent, str(len(sent)))
|
||||
|
||||
pr2 = _FakePrinter({'printer': {'type': 'tspl', 'width_mm': 60,
|
||||
'height_mm': 40, 'gap_mm': 2, 'dpi': 203}})
|
||||
ok_ok, msg_ok = pr2.print_picking('王记饭店', '红富士苹果', 5.62, '斤',
|
||||
'CT-OK-1')
|
||||
check('正常数据能打', ok_ok is True and bool(sent), str((ok_ok, msg_ok)))
|
||||
if sent:
|
||||
_s = sent[-1].decode('gbk', errors='replace')
|
||||
check('正常数据带整块码',
|
||||
'QRCODE ' in _s and '"CT-OK-1"' in _s, _s[:160])
|
||||
|
||||
pr3 = _FakePrinter({'printer': {'type': 'tspl', 'width_mm': 60,
|
||||
'height_mm': 40, 'gap_mm': 2, 'dpi': 203}})
|
||||
sent[:] = []
|
||||
ok_long, msg_long = pr3.print_picking('王记饭店', '红富士苹果', 5.62, '斤',
|
||||
'C' * 1300)
|
||||
check('容器码超长时拒打', ok_long is False and not sent,
|
||||
str((ok_long, msg_long, len(sent))))
|
||||
|
||||
check('QR 容量表:1273 字节 = 177 模块',
|
||||
L._qr_modules(1273) == 177, str(L._qr_modules(1273)))
|
||||
|
||||
print('总计:%d 通过,%d 失败' % (ok, fail))
|
||||
sys.exit(1 if fail else 0)
|
||||
|
||||
@@ -44,6 +44,8 @@
|
||||
也不顶到码上。
|
||||
· 排版不再截断:排不下就折行、降字号、必要时压缩行距,每个字都会打出来;
|
||||
二维码永远整块打印(最小 1 点/模块),不会省略或缺角。
|
||||
· 真遇到标签太小 / 容器码过长 / 码内容打印机不支持:本次直接不打印并提示,
|
||||
不会发出半张或缺码的标签(宁可没打,也不打错)。
|
||||
· 如果标签实在太小、内容根本排不下,日志会提示加大标签,不会默默丢字。
|
||||
· ×、·、— 这类字符在 GBK 里是全角双字节,现在按全角算宽,不再低估。
|
||||
· 设置页预览改用像素字号:Windows 显示缩放 125%/150% 时,预览文字
|
||||
|
||||
Reference in New Issue
Block a user