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

395 lines
18 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 -*-
"""插件自检(不联网:不登录 ERP、不出纸)。
会被壳子/SDK 分发流程当作自检入口(见 sdk.json 约定),也可手动跑:
.venv\\Scripts\\python.exe "plugins\\XQ0001-0100\\XQ0012 EHR预支及支付报酬自动发起ERP付款申请\\_selftest.py"
覆盖:配置常量 → payload 字段顺序 → 台账读取 → 套打 PDF 生成 → 流程试算。
"""
import sys
import types
from datetime import date
from pathlib import Path
HERE = Path(__file__).resolve().parent
# 以「包」的方式加载(跳过 __init__.py 的 webhost 依赖)
_pkg = types.ModuleType("xq0012")
_pkg.__path__ = [str(HERE)]
sys.modules["xq0012"] = _pkg
from xq0012 import config # noqa: E402
from xq0012.logic import payload, flow, reconcile, route # noqa: E402
from xq0012.report import payapply_pdf, notify # noqa: E402
FAILED = []
def check(name, fn):
try:
fn()
print(f"[ok] {name}")
except Exception as e: # noqa: BLE001
FAILED.append((name, e))
print(f"[FAIL] {name}: {e}")
def t_config():
assert config.FORM_ID == 'CN_PAYAPPLY'
assert config.BILL_TYPE_ID == 'FKSQ006.0YS'
assert config.SAVE_OPTIONS['is_auto_adjust_field'] is False, 'IsAutoAdjustField 必须关'
def t_payload_order():
row = {'seq': '1', 'month': '202610', 'staff': '37000365', 'name': '何广飞',
'date': '2026-10-30', 'amount': 2000.0, 'reason': '缴纳弟弟生活费',
'org_path': '集团-金色印象事业部-第一大区-水晶郦城CEO会馆', 'dept': '接待组'}
m = payload.build_model(row, org_code='99.01.06.01.02.01.05', dept_code='BM000477',
purpose_id='SFKYT11_SYS', apply_date=date(2026, 10, 30), expect_days=1,
venue='水晶郦城CEO会馆')
keys = list(m)
assert keys[-1] == 'FPAYAPPLYENTRY', '分录必须最后'
assert keys.index('FBJ_SQR') < keys.index('F_VTUY_Base_re5'), '部门必须在申请人之后'
assert m['FBJ_SQR'] == {'FSTAFFNUMBER': '37000365'}
assert m['FCONTACTUNIT'] == {'FNumber': '37000365'}, '往来单位用工号键 FNumber'
assert m['FPAYAPPLYENTRY'][0]['FAPPLYAMOUNTFOR'] == 2000.0
assert m['FPAYAPPLYENTRY'][0]['FEXPECTPAYDATE'] == '2026-10-31'
assert '何广飞' in m['F_VTUY_Remarks_qtr']
def t_ledger_read():
import os
sys.path.insert(0, str(HERE))
from xq0012.data import ledger
assert ledger.normalize_month('2026-11') == '202611', '月份归一'
f = config.LEDGER_WORKBOOK_DEFAULT # 默认:追加目标工作簿
if not os.path.exists(f):
p = config.LEDGER_DIR_DEFAULT
cands = [os.path.join(p, n) for n in os.listdir(p)
if n.startswith('预支报酬台账_') and n.endswith('.xlsx')] if os.path.isdir(p) else []
if not cands:
print(' (既没有目标工作簿,也没有接口导出的 预支报酬台账_YYYYMM.xlsx,跳过)')
return
f = max(cands, key=os.path.getmtime)
rows = ledger.read_rows(f)
assert rows and rows[0]['staff'], '台账应至少有一条有效行'
month_rows = ledger.read_rows(f, '202611')
org = ledger.load_org_map(f)
print(f' {Path(f).name}: 全部 {len(rows)} 行、202611 {len(month_rows)} 行,'
f'组织映射 {len(org)} 条')
def t_render_pdf():
data = payapply_pdf.from_view({}, 'SELFTEST-0001')
data.update({'applicant': '何广飞', 'applicant_no': '37000365', 'dept': '人力资源部',
'pay_org': '重庆三十七度健康管理有限公司', 'apply_amount': '2000.00',
'approve_amount': '2000.00', 'create_date': '2026/11/14', 'currency': '人民币'})
data['entries'] = [{'cost': '预支工资', 'account_name': '何广飞', 'bank': '招商银行',
'account_no': '6222***0000', 'amount': '2000.00', 'dept': '', 'remark': ''}]
out = str(HERE.parents[2] / 'out' / '_selftest_payapply.pdf')
payapply_pdf.render_payapply(data, out)
import pymupdf
doc = pymupdf.open(out)
assert doc.page_count == 1
text = doc[0].get_text('text')
assert 'SELFTEST-0001' in text and '2000.00' in text
assert len([d for d in doc[0].get_drawings()]) >= 30, '表格线数量异常'
doc.close()
def t_notify_message():
body = notify.build_message(
[{'bill_no': 'FKSQ20261100001', 'name': '何广飞', 'amount': 2000.0},
{'bill_no': 'FKSQ20261100002', 'name': '唐雪非', 'amount': 1500.5}],
'信息技术部', failed=1)
assert '信息技术部' in body and '打印机处领取' in body
assert 'FKSQ20261100001' in body and '1500.50' in body
assert '合计 3500.50 元' in body
assert '打印失败' in body
def t_notify_recipients():
got = notify.parse_recipients('陈莲/37001090、张三(37000236); 李四')
assert got[0] == ('陈莲', '37001090') and got[1] == ('张三', '37000236')
assert got[2] == ('李四', '')
def t_reconcile_match():
from datetime import date as _date
# 真实场景:ERP 单的申请人工号是代提人(HR),受款人只在申请说明里
rows = [
{'staff': '37000365', 'name': '何广飞', 'amount': 2000.0, 'month': '202610',
'date': '2026-10-27', 'pay_status': ''},
{'staff': '37000086', 'name': '周鹏', 'amount': 20000.0, 'month': '202611',
'date': '2026-11-01', 'pay_status': '未付'},
{'staff': '37000999', 'name': '张三', 'amount': 500.0, 'month': '202611',
'date': '2026-11-03', 'pay_status': '未付'},
]
bills = [
{'bill_no': 'FKSQ20261001405', 'staff': '37001090', 'amount': 2000.0, 'status': 'C',
'date': '2026-10-30', 'payee_staff': '37000365', 'payee_name': '何广飞',
'remark': '2026-10-30 水晶郦城CEO会馆-何广飞(-)的预支,原因:缴纳弟弟生活费;'},
{'bill_no': 'FKSQ20260901369', 'staff': '37001090', 'amount': 2000.0, 'status': 'C',
'date': '2026-09-22', 'payee_staff': '37000365', 'payee_name': '何广飞',
'remark': '2026-09-22 水晶郦城CEO会馆-何广飞(-)的预支,原因:支付妹妹大学生活费;'},
{'bill_no': 'FKSQ20261100003', 'staff': '37000999', 'amount': 500.0, 'status': 'Z',
'date': '2026-11-03', 'payee_staff': '37000999', 'payee_name': '张三',
'remark': '2026-11-03 某会馆-张三(-)的预支'},
# 生产真实干扰项:「经过周鹏总批准」不是周鹏本人的预支单,收款人也不是周鹏
{'bill_no': 'FKSQ20261000965', 'staff': '37001090', 'amount': 600.0, 'status': 'C',
'date': '2026-10-17', 'payee_staff': '37001234', 'payee_name': '其他员工',
'remark': '该员工与门店存在劳资纠纷,经过周鹏总批准予以发放。(国贸LIFE主题会馆);'},
]
matched, unmatched = reconcile.match(rows, bills)
assert len(matched) == 1, f'应命中 1 行,实际 {len(matched)}'
assert matched[0]['bill']['bill_no'] == 'FKSQ20261001405', '应取日期最接近的 10-30 单'
assert matched[0]['how'] == '收款单位工号', '应优先按收款单位命中'
assert {u['name'] for u in unmatched} == {'周鹏', '张三'}, '周鹏无单、张三单作废,均未命中'
assert not reconcile._is_payee('经过周鹏总批准予以发放', '周鹏'), '姓名出现≠受款人'
assert reconcile._is_payee('水晶郦城CEO会馆-何广飞(-)的预支', '何广飞')
assert reconcile.window('202611', today=_date(2026, 11, 16)) == ('2026-09-17', '2026-11-16')
def t_pending_filter():
import os
sys.path.insert(0, str(HERE))
from xq0012.data import ledger
assert ledger.is_pending({'pay_status': ''})
assert ledger.is_pending({'pay_status': '未付'})
assert not ledger.is_pending({'pay_status': '已付'})
f = config.LEDGER_WORKBOOK_DEFAULT
if os.path.exists(f):
all_rows = ledger.read_rows(f, '202611')
pending = ledger.read_rows(f, '202611', pending_only=True)
assert len(pending) <= len(all_rows), '待发起行数不应超过全部行数'
print(f' 202611 全部 {len(all_rows)} 行、待发起 {len(pending)} 行')
def t_route_pick():
std = {'解放碑CBD行政会馆': '是', '新光天地行政会馆': '是'}
store = {'job_seq': config.JOB_SEQ_STORE, 'dept4': '水晶郦城CEO会馆'}
assert route.pick(store, std) == config.SYSTEM_OLD, '门店服务序列 + 非标准化 → 旧系统'
assert route.pick({'job_seq': config.JOB_SEQ_STORE, 'dept4': '解放碑CBD行政会馆'},
std) == config.SYSTEM_NEW, '标准化门店 → 新系统'
assert route.pick({'job_seq': '经营系管理序列', 'dept4': '水晶郦城CEO会馆'},
std) == config.SYSTEM_NEW, '非门店服务序列 AR 恒为「-」→ 新系统'
assert route.pick(store, {}) == config.SYSTEM_OLD, '无标准化名单时按查不到=「否」'
assert route.dept_for(config.SYSTEM_OLD, 'BM000477') == config.DEPT_OLD_SYSTEM
assert route.dept_for(config.SYSTEM_NEW, 'BM000477') == 'BM000477'
import os
sys.path.insert(0, str(HERE))
from xq0012.data import ledger
f = config.LEDGER_WORKBOOK_DEFAULT
if os.path.exists(f):
stores = ledger.load_std_stores(f)
assert stores.get('解放碑CBD行政会馆') == '是', '辅助0 sheet 读取应含标准化门店'
rows = ledger.read_rows(f)
picked = {route.label(route.pick(r, stores)) for r in rows}
print(f' 标准化门店 {len(stores)} 家;台账 {len(rows)} 行判定:{picked or "-"}')
def t_flow_dry_run():
rows = [{'seq': '1', 'staff': '37000365', 'name': '何广飞', 'date': '2026-10-30',
'amount': 2000.0, 'reason': '测试', 'org_path': '集团-水晶郦城CEO会馆',
'dept': '接待组', 'system': config.SYSTEM_NEW}]
out = flow.run_flow(rows_data=rows, org_map={'水晶郦城CEO会馆': '99.01.06.01.02.01.05'},
dry_run=True, apply_date=date(2026, 10, 30))
assert '试算' in out['summary'] and len(out['detail']) == 1
assert out['detail'][0]['system'] == '新系统'
def t_flow_site_error():
rows = [{'seq': '1', 'staff': '37000365', 'name': '何广飞', 'date': '2026-10-30',
'amount': 2000.0, 'reason': '测试', 'org_path': '集团-水晶郦城CEO会馆',
'dept': '接待组', 'system': config.SYSTEM_OLD}]
out = flow.run_flow(rows_data=rows, org_map={}, dry_run=False,
site_errors={config.SYSTEM_OLD: '密码错误'})
assert out['detail'][0]['status'].startswith('旧系统登录失败'), out['detail'][0]['status']
assert out['detail'][0]['dept'] == config.DEPT_OLD_SYSTEM
def t_billhead_fill():
"""FBillHead 三列回填:日期=传入日期、发起人=默认值、越界行跳过。"""
import tempfile
import openpyxl
from xq0012.data import ledger
wb = openpyxl.Workbook()
ws = wb.active
ws.title = config.BILLHEAD_SHEET
for col, name in ((4, '*' + config.BH_COL_DATE), (5, config.BH_COL_APPLICANT_NO),
(6, config.BH_COL_APPLICANT_NAME)):
ws.cell(row=2, column=col).value = name # 真实模板的日期列带必录星号 *
ws.cell(row=3, column=8).value = '37000365'
path = str(Path(tempfile.gettempdir()) / 'xq0012_billhead_selftest.xlsx')
wb.save(path)
n = ledger.fill_billhead(path, [{'row': 3}, {'row': 99}],
date(2026, 11, 16), '37001090', '刘纤')
assert n == 1, f'只应回填 1 行,实际 {n}'
wb2 = openpyxl.load_workbook(path, data_only=True)
got = [wb2[config.BILLHEAD_SHEET].cell(row=3, column=c).value for c in (4, 5, 6)]
wb2.close()
assert got[0].date() == date(2026, 11, 16), got
assert got[1] == '37001090' and got[2] == '刘纤', got
def t_flow_sheet():
"""预支办结流程:整表覆盖(清旧行/按表头写/标记重算)+ 月份区间 + 缺 sheet 直接返回。"""
import tempfile
import openpyxl
from xq0012.data import ledger
wb = openpyxl.Workbook()
ws = wb.active
ws.title = config.FLOW_SHEET
header = ['流水号', '工号', '姓名', '收款银行', '收款账号']
for i, name in enumerate(header, start=1):
ws.cell(row=2, column=i).value = name
ws.cell(row=3, column=2).value = 'OLD' # 旧数据应被清空
path = str(Path(tempfile.gettempdir()) / 'xq0012_flow_selftest.xlsx')
wb.save(path)
data = [{'工号': '37000365', '姓名': '何广飞', '收款银行': '中国银行', '收款账号': '6217****1'},
{'工号': '37000366', '姓名': '周鹏', '收款银行': '建设银行', '收款账号': '6217****2'}]
n = ledger.write_flow_sheet(path, header, data)
assert n == 2, n
wb2 = openpyxl.load_workbook(path, data_only=True)
got = [[c.value for c in r] for r in wb2[config.FLOW_SHEET].iter_rows(
min_row=3, max_row=5, max_col=5)]
assert got[0][1] == '37000365' and got[1][1] == '37000366', got
assert got[2] == [None] * 5, f'第 3 行旧数据未清空:{got[2]}'
assert wb2.calculation.fullCalcOnLoad, '未标记打开时重算'
wb2.close()
# 月份区间(流程监控按月扫描)
assert ledger.month_range('2026-11') == ('2026-11-01', '2026-11-30')
assert ledger.month_range('202602') == ('2026-02-01', '2026-02-28')
assert ledger.month_range('2024-02') == ('2024-02-01', '2024-02-29')
# 工作簿缺「预支办结流程」→ 直接返回原因,不发起任何请求
wb3 = openpyxl.Workbook()
wb3.active.title = '别的sheet'
path3 = str(Path(tempfile.gettempdir()) / 'xq0012_flow_nosheet.xlsx')
wb3.save(path3)
res = ledger.refresh_flow_sheet(object(), path3, '202611')
assert res['written'] == 0 and '缺少' in res['reason'], res
def t_billhead_check():
"""单据头完整性校验:必录 9 列、缺失行列出短名、可降级为只校验 D/E/F。"""
import tempfile
import openpyxl
from xq0012.data import ledger
cols = [(4, '*' + config.BH_COL_DATE), (5, config.BH_COL_APPLICANT_NO),
(6, config.BH_COL_APPLICANT_NAME), (16, config.BH_COL_PAY_ORG),
(18, config.BH_COL_SETTLE_ORG), (24, config.BH_COL_DEPT_NAME),
(39, config.BH_COL_ACCOUNT_NAME), (40, config.BH_COL_BANK),
(41, config.BH_COL_ACCOUNT_NO)]
wb = openpyxl.Workbook()
ws = wb.active
ws.title = config.BILLHEAD_SHEET
for col, name in cols:
ws.cell(row=2, column=col).value = name
for r in (3, 4):
ws.cell(row=r, column=4).value = date(2026, 11, 16)
ws.cell(row=r, column=5).value = '37001090'
ws.cell(row=r, column=6).value = '刘纤'
ws.cell(row=r, column=16).value = '重庆三十七度健康管理有限公司'
ws.cell(row=r, column=18).value = '重庆三十七度健康管理有限公司'
ws.cell(row=r, column=24).value = '人力资源部'
ws.cell(row=r, column=39).value = '何广飞'
ws.cell(row=r, column=40).value = '招商银行'
ws.cell(row=3, column=41).value = '6222****0000' # 只有第 3 行银行卡齐全
path = str(Path(tempfile.gettempdir()) / 'xq0012_billhead_check.xlsx')
wb.save(path)
rows = [{'row': 3, 'staff': '37000365', 'name': '何广飞'},
{'row': 4, 'staff': '37000366', 'name': '周鹏'},
{'row': 99, 'staff': '37000367', 'name': '越界'}]
got = ledger.check_billhead(path, rows)
assert got['checked'] == 3 and len(got['ok']) == 1, got
assert got['ok'][0]['row'] == 3
missing = {m['row']: m['fields'] for m in got['missing']}
assert missing[4] == ['对方银行账号'], missing
assert missing[99] == ['超出模板预置行'], missing
part = ledger.check_billhead(path, rows, formula_cols=False)
assert len(part['ok']) == 2, '不重算时只校验 D/E/F,第 4 行也应通过'
def t_sheet_print():
"""单子传递打印:只打本批行、两行表头、读值渲染、页脚行数正确。"""
import tempfile
import openpyxl
import pymupdf as fitz
from xq0012.report import sheet_pdf
wb = openpyxl.Workbook()
ws = wb.active
ws.title = config.SHEET_PRINT_SHEET
head = ['FSEQNO', 'FPAYDATE', 'FPAYUNITNAME', 'FPAYORGNAME', 'FEXPENSEITEMNAME',
'FAPPLYAMOUNT']
cn = ['序号', '日期', '收款单位', '付款组织', '费用项目', '申请付款金额']
for c, v in enumerate(head, 1):
ws.cell(row=1, column=c).value = v
for c, v in enumerate(cn, 1):
ws.cell(row=2, column=c).value = v
data = [(3, '1', '2026-10-30', '何广飞', '水晶郦城CEO会馆', '预支工资', 2000),
(4, '2', '2026-10-30', '不打印的行', '-', '-', 999),
(5, '3', '2026-10-30', '周鹏', '总部', '预支工资', 3000)]
for r, seq, d, name, org, item, amt in data:
for c, v in enumerate([seq, d, name, org, item, amt], 1):
ws.cell(row=r, column=c).value = v
path = str(Path(tempfile.gettempdir()) / 'xq0012_sheet_print.xlsx')
wb.save(path)
out = str(Path(tempfile.gettempdir()) / 'xq0012_sheet_print.pdf')
pdf, n = sheet_pdf.render_sheet_pdf(path, config.SHEET_PRINT_SHEET, [3, 5], out)
assert n == 2, n
doc = fitz.open(pdf)
try:
text = ''.join(p.get_text() for p in doc)
flat = ''.join(text.split()) # 字体子集化后空格可能不是 U+0020
assert '共2行' in flat, text[:200]
assert '何广飞' in flat and '周鹏' in flat
assert '不打印的行' not in flat
assert '收款单位' in flat and '申请付款金额' in flat
finally:
doc.close()
try:
sheet_pdf.render_sheet_pdf(path, '不存在的sheet', [3], out)
raise AssertionError('缺 sheet 应报错')
except ValueError:
pass
if __name__ == '__main__':
check('配置常量', t_config)
check('payload 字段顺序', t_payload_order)
check('台账读取', t_ledger_read)
check('套打 PDF', t_render_pdf)
check('钉钉提醒文案', t_notify_message)
check('钉钉接收人解析', t_notify_recipients)
check('对账匹配', t_reconcile_match)
check('待发起过滤', t_pending_filter)
check('新旧系统分流', t_route_pick)
check('流程试算', t_flow_dry_run)
check('分流登录失败', t_flow_site_error)
check('单据头三列回填', t_billhead_fill)
check('预支办结流程刷新', t_flow_sheet)
check('单据头完整性校验', t_billhead_check)
check('单子传递打印', t_sheet_print)
print('=' * 50)
if FAILED:
print(f'失败 {len(FAILED)} 项')
sys.exit(1)
print('全部通过')