Files
T
puddy 4a5a1c2bd4 feat(plugin): XQ0012 预支付款申请 0.2.5(对账回填、新旧系统分流、两份打印、钉钉提醒模块)
台账按月接口导出并追加目标工作簿;整表刷新「预支办结流程」供单据头 XLOOKUP 取收款信息;发起前对账命中回填已付;按台账口径新旧系统分流;建单后套打 ERP 单据 + 单子传递打印;含离线自检与打包脚本。
2026-11-16 17:14:17 +08:00

300 lines
11 KiB
Python
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.
# -*- coding: utf-8 -*-
"""XQ0012 付款申请单套打(自绘 PDF)。
背景
----
金蝶 WebAPI 没有打印接口(2026-11-14 探测确认),ERP 客户端套打出来的版面
(`C:\\Users\\admin\\Downloads\\套打_付款申请单_2026111414513723.PDF`)已按坐标量过:
A4 竖版、SimSun、11pt 正文 / 15pt 标题、0.75pt 表格线,全部是矢量,可直接复刻。
本模块按同一套坐标重绘这张单,数据从 ERP `view()` 返回单据里取,
输出 PDF 后交 `printkit` 出纸(IPP 直连,不走驱动/队列)。
用法(由 logic/flow 调用,不接命令行参数):
pdf = render_payapply(erp_view_dict, out_path)
"""
from __future__ import annotations
import datetime as _dt
import os
import pymupdf as _mu
# ---------------- 版面常量(单位 pt,均实测自 ERP 套打样例) ----------------
PAGE_W, PAGE_H = 595.28, 841.89 # A4
LINE_W = 0.75
COLOR = (0, 0, 0)
FONT_SIZE, TITLE_SIZE = 11, 15
ASCENT = 0.859375 # SimSun 实测;baseline = y0 + ASCENT*size
LEFT, RIGHT = 6.8, 586.6 # 表格左右外框
# 顶部固定行(y 依次)
Y_TOP = 59.8
Y_R1, Y_R2, Y_R3, Y_R4, Y_R5 = 59.8, 92.1, 124.3, 156.6, 188.9
Y_ACC_TOP = 221.2 # 收款人账户明细表起始
ACC_HEAD_H, ACC_ROW_H = 32.3, 32.5
SIG_H, GAP_H = 32.9, 3.9 # 报销人签名行 / 间隔
FEE_TITLE_H, FEE_HEAD_H, FEE_ROW_H = 32.6, 32.5, 32.6
FONT_FILES = [r"C:\Windows\Fonts\simsun.ttc", r"C:\Windows\Fonts\simhei.ttf"]
def _pick_font() -> str | None:
for p in FONT_FILES:
if os.path.exists(p):
return p
return None
def _ml(v) -> str:
"""多语言文本 → 当前语言值(View 返回 [{'Key':2052,'Value':...}])。"""
if isinstance(v, list):
for it in v:
if isinstance(it, dict) and it.get("Key") == 2052:
return str(it.get("Value") or "")
return ""
if isinstance(v, dict):
return _ml(v.get("Name")) or str(v.get("Value") or "")
return "" if v is None else str(v)
def _name(ref: dict | None) -> str:
return _ml((ref or {}).get("Name"))
def _date_cn(iso: str) -> str:
"""2026-11-14T00:00:00 → 2026/11/14"""
s = str(iso or "")[:10]
return s.replace("-", "/") if s else ""
def _money(v) -> str:
try:
return f"{float(v):.2f}"
except (TypeError, ValueError):
return ""
def from_view(view: dict, bill_no: str | None = None) -> dict:
"""ERP `view()` 单据 → 套打数据(字段缺失时留空,不抛异常)。"""
head = (view or {}).get("Result") or view or {}
entries = head.get("FPAYAPPLYENTRY") or []
total = sum(float((e or {}).get("FAPPLYAMOUNTFOR") or 0) for e in entries)
return {
"bill_no": bill_no or head.get("FBillNo") or "",
"applicant": _name(head.get("FBJ_SQR")),
"applicant_no": (head.get("FBJ_SQR") or {}).get("FStaffNumber") or "",
"dept": _name(head.get("F_VTUY_Base_re5")),
"pay_org": _name(head.get("FPAYORGID")),
"cost_center": "", # 样例为空;需要时按部门全路径补
"apply_amount": _money(total),
"approve_amount": _money(total),
"create_date": _date_cn(head.get("FCREATEDATE") or head.get("FDATE")),
"print_time": _dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"currency": _name(head.get("FCURRENCYID")) or "人民币",
"entries": [{
"cost": _name((e or {}).get("FCOSTID")),
"account_name": _ml((e or {}).get("FEACHCCOUNTNAME")),
"bank": _ml((e or {}).get("FEACHBANKNAME")),
"account_no": str((e or {}).get("F_VTUY_Text_apv1") or ""),
"amount": _money((e or {}).get("FAPPLYAMOUNTFOR")),
"dept": _name((e or {}).get("F_VTUY_Base_re5_entry")) or "",
"remark": "",
} for e in entries],
}
class _Canvas:
"""一页 A4 + SimSun:画线、左对齐/居中文字。"""
def __init__(self, doc, page):
self.doc, self.page = doc, page
self.fontname = "sun"
ff = _pick_font()
if ff:
self.page.insert_font(fontname=self.fontname, fontfile=ff)
self.font = _mu.Font(fontfile=ff)
else: # 兜底:pymupdf 内置 CJK
self.fontname = "china-s"
self.font = _mu.Font("china-s")
def line(self, x0, y0, x1, y1):
self.page.draw_line(_mu.Point(x0, y0), _mu.Point(x1, y1),
color=COLOR, width=LINE_W)
def hline(self, y, x0=LEFT, x1=RIGHT):
self.line(x0, y, x1, y)
def vline(self, x, y0, y1):
self.line(x, y0, x, y1)
def width(self, txt, size):
return self.font.text_length(txt, fontsize=size)
def text(self, x, y0, txt, size=FONT_SIZE):
if not txt:
return
self.page.insert_text((x, y0 + ASCENT * size), str(txt),
fontname=self.fontname, fontsize=size)
def center(self, x0, x1, y0, txt, size=FONT_SIZE):
if not txt:
return
w = self.width(str(txt), size)
self.text((x0 + x1) / 2 - w / 2, y0, txt, size)
def cell(self, x0, x1, y0, txt, size=FONT_SIZE):
"""表格单元格:居中。"""
self.center(x0, x1, y0, txt, size)
def _header(c: _Canvas):
# 标题(页面居中)
c.center(0, PAGE_W, 25.4, "个人工资付款申请", TITLE_SIZE)
# 5 行固定表头网格 + 左右外框
for y in (Y_R1, Y_R2, Y_R3, Y_R4, Y_R5):
c.hline(y)
c.vline(LEFT, Y_R1, Y_ACC_TOP)
c.vline(RIGHT, Y_R1, Y_ACC_TOP)
for x, y0, y1 in (
(83.8, Y_R1, Y_R5), (284.3, Y_R1, Y_R2), (387.6, Y_R1, Y_R5),
(184.3, Y_R2, Y_R3), (284.8, Y_R2, Y_R4), (478.5, Y_R2, Y_R3),
(586.6, Y_R1, Y_R2), (586.6, Y_R3, Y_R4),
(184.3, Y_R4, Y_R5), (478.5, Y_R4, Y_R5),
):
c.vline(x, y0, y1)
def _header_text(c: _Canvas, d: dict):
y = Y_R1
c.text(7.9, y + 9.8, "标题")
c.text(84.9, y + 9.8, f"{d['applicant']}提报的付款申请")
c.text(286.0, y + 9.8, "单据编号")
c.text(388.7, y + 9.8, d["bill_no"])
y = Y_R2
c.text(7.9, y + 9.8, "报销人")
c.text(84.9, y + 9.8, d["applicant"])
c.text(185.4, y + 9.8, "报销人工号")
c.text(286.0, y + 9.8, d["applicant_no"])
c.text(388.7, y + 9.8, "报销人部门")
c.text(479.6, y + 9.8, d["dept"])
y = Y_R3
c.text(7.9, y + 9.9, "费用归属主体")
c.text(84.9, y + 9.9, d["pay_org"])
c.text(286.0, y + 9.9, "费用归属成本中心")
if d.get("cost_center"):
c.text(388.7, y + 9.9, d["cost_center"])
y = Y_R4
c.text(7.9, y + 3.6, "合计申请金")
c.text(84.9, y + 9.8, d["apply_amount"])
c.text(7.9, y + 16.1, "(RMB)")
c.text(185.4, y + 3.6, "合计核准金额")
c.text(286.0, y + 9.8, d["approve_amount"])
c.text(185.4, y + 16.1, "(RMB)")
c.text(388.7, y + 9.8, "创建时间")
c.text(479.6, y + 9.8, d["create_date"])
# 收款人账户明细 段标题
c.text(7.9, 198.7, "收款人账户明细")
def _account_table(c: _Canvas, d: dict, n: int) -> float:
"""收款人账户明细表(N 行),返回表底 y。"""
top = Y_ACC_TOP
db = d["entries"]
c.hline(top)
c.vline(LEFT, top, top + ACC_HEAD_H + n * ACC_ROW_H)
c.vline(RIGHT, top, top + ACC_HEAD_H + n * ACC_ROW_H)
bottom = top + ACC_HEAD_H + n * ACC_ROW_H
# 表头
hy = top
cols = [(LEFT, 83.8), (83.8, 184.3), (184.3, 284.8), (284.8, 478.8), (478.8, RIGHT)]
for x, _ in cols[1:]:
c.vline(x, top, bottom)
for (x0, x1), label in zip(cols, ("支付货币", "收款人账户名", "收款人开户行",
"收款人账号", "收款金额")):
c.cell(x0, x1, hy + 9.8, label)
c.hline(top + ACC_HEAD_H)
for i, e in enumerate(db[:n]):
y0 = top + ACC_HEAD_H + i * ACC_ROW_H
vals = (d["currency"], e["account_name"], e["bank"], e["account_no"], e["amount"])
for (x0, x1), v in zip(cols, vals):
c.cell(x0, x1, y0 + 9.9, v)
if i < n - 1:
c.hline(y0 + ACC_ROW_H)
c.hline(bottom)
return bottom
def _signature(c: _Canvas, d: dict, top: float) -> float:
c.vline(LEFT, top, top + SIG_H)
c.vline(RIGHT, top, top + SIG_H)
c.vline(387.6, top, top + SIG_H)
c.vline(83.8, top, top + SIG_H)
c.text(17.3, top + 10.1, "报销人签名")
c.text(314.2, top + 10.1, "打印日期")
c.text(434.9, top + 10.1, d["print_time"])
bottom = top + SIG_H
c.hline(bottom)
return bottom
def _fee_table(c: _Canvas, d: dict, top: float, n: int) -> float:
"""费用分摊明细表(N 行 + 合计行)。"""
c.vline(LEFT, top, top + FEE_TITLE_H + FEE_HEAD_H + n * FEE_ROW_H + FEE_ROW_H)
c.vline(RIGHT, top, top + FEE_TITLE_H + FEE_HEAD_H + n * FEE_ROW_H + FEE_ROW_H)
c.text(7.9, top + 10.0, "费用分摊明细")
head_top = top + FEE_TITLE_H
c.hline(head_top)
cols = [(LEFT, 184.3), (184.3, 284.8), (284.8, 387.6), (387.6, RIGHT)]
for x, _ in cols[1:]:
c.vline(x, head_top, head_top + FEE_HEAD_H + n * FEE_ROW_H + FEE_ROW_H)
for (x0, x1), label in zip(cols, ("费用项目", "分摊部门", "分摊金额", "备注")):
c.cell(x0, x1, head_top + 9.9, label)
c.hline(head_top + FEE_HEAD_H)
total = 0.0
for i, e in enumerate(d["entries"][:n]):
y0 = head_top + FEE_HEAD_H + i * FEE_ROW_H
vals = (e["cost"], e["dept"], e["amount"], e["remark"])
for (x0, x1), v in zip(cols, vals):
c.cell(x0, x1, y0 + 10.0, v)
try:
total += float(e["amount"])
except ValueError:
pass
c.hline(y0 + FEE_ROW_H)
# 合计行
y0 = head_top + FEE_HEAD_H + n * FEE_ROW_H
c.text(57.1, y0 + 10.0, "分摊表合计金额")
c.cell(284.8, 387.6, y0 + 10.0, _money(total))
bottom = y0 + FEE_ROW_H
c.hline(bottom)
return bottom
def render_payapply(data: dict, out_path: str) -> str:
"""按套打模板画一张付款申请单 → PDF 路径。"""
n = max(1, len(data.get("entries") or []))
doc = _mu.open()
page = doc.new_page(width=PAGE_W, height=PAGE_H)
c = _Canvas(doc, page)
_header(c)
_header_text(c, data)
bottom = _account_table(c, data, n)
bottom = _signature(c, data, bottom)
bottom += GAP_H # 3.9pt 间隔
c.hline(bottom) # 费用分摊段顶线
bottom = _fee_table(c, data, bottom, n)
doc.set_metadata({"title": f"付款申请单 {data.get('bill_no', '')}",
"creator": "37duAutomation/XQ0012"})
try:
doc.subset_fonts() # 嵌入字体子集化:9.5MB → ~50KB
except Exception: # noqa: BLE001
pass
os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True)
doc.save(out_path, deflate=True)
doc.close()
return out_path