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

323 lines
17 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 EHR 预支及支付报酬 → ERP 付款申请单(webhost 场景插件)。
流程:按月份从 EHR 接口导出预支报酬台账(默认当月)→ 读有效行 → 逐行组装 Save Model
→(幂等查重)→ 建单 →(可选提交)→ 自绘套打 PDF →(可选)printkit 出纸。
默认 **试算模式**(dry_run=True):不写 ERP,只输出将要提交的报文与校验结果;
业务口径确认后关掉试算、按需打开「提交」「打印」。
"""
import os
from datetime import date
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
from . import config
from .data import erp as erp_mod
from .data import ledger
from .logic import flow, reconcile, route
def _parse_date(s: str):
s = (s or '').strip()
if not s:
return None
for fmt in ('%Y-%m-%d', '%Y/%m/%d', '%Y%m%d'):
try:
return date(*[int(x) for x in _split(s, fmt)])
except Exception: # noqa: BLE001
continue
return None
def _split(s: str, fmt: str):
import re
nums = [int(x) for x in re.findall(r'\d+', s)]
return nums[:3]
class PrepayPayApplyPlugin(ScenePlugin):
"""EHR 预支 → ERP 付款申请单(需求 XQ0012)。"""
id = 'xq0012'
name = 'EHR预支及支付报酬自动发起ERP付款申请'
version = '0.2.5'
description = ('按月份从 EHR 接口导出预支报酬台账(默认当月)→ 按月扫描已办结预支流程刷新'
'「预支办结流程」→ Excel 重算并校验单据头必录信息(含银行卡)→ 自动在 ERP '
'建付款申请单(默认试算不写库),可选提交、打印两份(ERP 单据套打 + 单子传递单);'
'含幂等查重与异常清单')
platform = 'hr' # 数据源走底座共享的 HR 登录态;ERP 仍用账密登录
uses_month = False
capabilities = ['xq0012']
permissions = {'platforms': ['hr']}
fields = {
'ref_month': {
'type': 'string', 'title': '台账月份', 'default': '',
'description': 'YYYY-MM 或 YYYYMM;留空=当月。当月无预支记录时直接提示,不自动回退上月',
},
'ledger_dir': {
'type': 'string', 'title': '台账目录', 'default': config.LEDGER_DIR_DEFAULT,
'description': '导出临时文件/独立台账落盘目录;留空=默认目录',
},
'ledger_workbook': {
'type': 'string', 'title': '目标工作簿', 'default': config.LEDGER_WORKBOOK_DEFAULT,
'description': '导出数据追加到该工作簿的「预支报酬台账」sheet(按表头对齐、自动去重);留空=只导出独立文件',
},
'ledger_file': {
'type': 'string', 'title': '台账文件(可选)', 'default': '',
'description': '指定现成 xlsx(跳过导出与追加);留空=按台账月份自动导出/追加',
},
'apply_date': {
'type': 'string', 'title': '申请日期', 'default': '',
'description': 'YYYY-MM-DD;留空=今天',
},
'pay_purpose': {
'type': 'string', 'title': '付款用途', 'default': '个人借款',
'enum': ['个人借款', '工资预提', '工资发放'],
'description': '⚠️ 业务待确认:人工模板=个人借款,生产真实单=工资预提',
},
'apply_dept': {
'type': 'string', 'title': '申请部门编码', 'default': config.APPLY_DEPT_ID,
'description': '默认 BM000477 人力资源部(生产真实单口径)',
},
'expect_days': {
'type': 'number', 'title': '期望付款日=申请日+N 天', 'default': config.DEFAULT_EXPECT_DAYS,
},
'erp_system': {
'type': 'string', 'title': 'ERP系统', 'default': '新版', 'enum': ['新版', '旧版'],
},
'erp_username': {'type': 'string', 'title': 'ERP登录账号', 'default': ''},
'erp_password': {'type': 'string', 'title': 'ERP登录密码', 'default': '', 'format': 'password'},
'dry_run': {
'type': 'boolean', 'title': '试算模式(不写 ERP)', 'default': True,
'description': '开启后只组装+查重+输出结果,不建单;验证通过后再关',
},
'reconcile': {
'type': 'boolean', 'title': '发起前对账回填', 'default': True,
'description': '先查 ERP 已有付款申请单,命中的台账行写「已付」且不再发起(需要 ERP 账号密码)',
},
'refresh_flow': {
'type': 'boolean', 'title': '刷新「预支办结流程」', 'default': True,
'description': '按月扫描「流程监控-全部流程(已办结)」的预支流程,导出「全部流程详细数据」'
'整表覆盖该 sheet,让单据头 XLOOKUP 取到最新收款人/银行/账号(需要 HR 登录态)',
},
'submit': {
'type': 'boolean', 'title': '建单后自动提交', 'default': False,
'description': '关闭时只建草稿(A),由 HR 在 ERP 确认后手动提交',
},
'print_enabled': {
'type': 'boolean', 'title': '建单后打印(ERP 单据 + 传递单)', 'default': False,
'description': '打开后打两份:①每张 ERP 付款申请单套打一份;'
'②「单子传递打印」里本批建单对应的行汇总一份',
},
'printer': {
'type': 'string', 'title': '打印机', 'default': config.PRINTER_DEFAULT,
'enum': config.PRINTER_OPTIONS,
},
'copies': {'type': 'number', 'title': '打印份数', 'default': config.PRINT_COPIES_DEFAULT},
'dingtalk_enabled': {
'type': 'boolean', 'title': '打印后钉钉提醒领取',
'default': config.DINGTALK_ENABLED_DEFAULT,
'description': '打印成功后推送一条群提醒(单号/收款人/金额/打印机),提醒去领取签字',
},
'dingtalk_users': {
'type': 'string', 'title': '钉钉接收人(姓名/工号)',
'default': config.DINGTALK_USERS_DEFAULT,
'description': '多个用「、」「,」「;」或换行分隔;重名必须带工号;留空=不提醒',
},
'debug_mode': {'type': 'boolean', 'title': '调试日志', 'default': False},
}
def run(self, fields: dict, ctx) -> dict:
fields = fields or {}
debug = bool(fields.get('debug_mode', False))
def log(msg: str, level: str = 'INFO') -> None:
if level == 'DEBUG' and not debug:
return
try:
ctx.log(msg, level)
except TypeError:
ctx.log(msg)
config.set_log(log)
work_dir = str(fields.get('ledger_dir') or '').strip() or config.LEDGER_DIR_DEFAULT
ledger_file = str(fields.get('ledger_file') or '').strip()
ledger_workbook = str(fields.get('ledger_workbook') or '').strip()
month = ledger.normalize_month(str(fields.get('ref_month') or ''))
if ledger_file:
path = ledger_file
log(f'[台账] 使用指定文件:{path}')
elif ledger_workbook:
log(f'[台账] 导出 {month} 台账并追加到工作簿:{ledger_workbook}')
res = ledger.append_month(ctx.get_session('hr'), ledger_workbook, month)
path = res['path']
log(f'[台账] 追加完成:新增 {res["added"]} 行,跳过重复 {res["skipped"]} 条'
+ (f',超出模板预置行 {res["overflow"]} 条(公式列需人工补)' if res['overflow'] else ''))
else:
log(f'[台账] 从 EHR 导出 {month} 预支报酬台账(目录:{work_dir})')
path = ledger.export_month(ctx.get_session('hr'), work_dir, month)
log(f'[台账] 已导出:{path}')
rows = ledger.read_rows(path, month, pending_only=True)
log(f'[台账] {month} 待发起(付款状态为空/未付){len(rows)} 行')
if not rows:
return {'summary': f'{month} 无待发起的预支记录(可能均已在 ERP 发起或台账未提报)',
'detail': [], 'path': path}
# 刷新「预支办结流程」:单据头 AM/AN/AO 靠它 XLOOKUP 出收款人/银行/账号
# 按月扫描「流程监控-已办结」整表覆盖,与台账行无关(已付行也要查得到收款信息)
if bool(fields.get('refresh_flow', True)):
try:
res_flow = ledger.refresh_flow_sheet(ctx.get_session('hr'), path, month,
work_dir=work_dir)
if res_flow['written']:
log(f'[流程] 已覆盖「{config.FLOW_SHEET}」{res_flow["written"]} 行'
f'({res_flow["flows"]} 条已办结流程、导出 {len(res_flow["exported"])} 个文件)')
else:
log(f'[流程] 未刷新:{res_flow["reason"]}', 'WARN')
if res_flow['skipped']:
names = '、'.join(str(r.get('title') or r.get('processId'))
for r in res_flow['skipped'][:5])
log(f'[流程] {len(res_flow["skipped"])} 条流程取不到 taskId,未导出:{names}',
'WARN')
except Exception as e: # noqa: BLE001
log(f'[流程] 刷新「{config.FLOW_SHEET}」失败(不影响建单):{e}', 'WARN')
dry_run = bool(fields.get('dry_run', True))
# 新旧系统分流:口径见 logic/route.py(FBillHead AS 列)
system_opt = str(fields.get('erp_system') or config.SYSTEM_AUTO).strip()
auto_route = system_opt in ('', config.SYSTEM_AUTO, '自动分流')
forced = '' if auto_route else (
config.SYSTEM_OLD if '旧' in system_opt else config.SYSTEM_NEW)
std_stores = ledger.load_std_stores(path)
if auto_route and not std_stores:
log(f'[分流] 工作簿无「{config.STD_STORE_SHEET}」sheet,会馆一律按非标准化处理'
f'({config.JOB_SEQ_STORE}员工将走旧系统)', 'WARN')
for r in rows:
r['system'] = forced or route.pick(r, std_stores)
if auto_route:
stat = {}
for r in rows:
stat[route.label(r['system'])] = stat.get(route.label(r['system']), 0) + 1
log('[分流] 按台账 AS 列判定:' + ','.join(f'{k} {v} 行' for k, v in stat.items()))
user = str(fields.get('erp_username') or '').strip()
pwd = str(fields.get('erp_password') or '')
clients, site_errors = {}, {}
if user and pwd:
for site in sorted({r['system'] for r in rows}):
try:
clients[site] = erp_mod.login(user, pwd, erp=site)
except Exception as e: # noqa: BLE001
site_errors[site] = str(e)[:200]
log(f'[ERP] {route.label(site)}登录失败:{e}', 'ERROR')
elif not dry_run:
return {'summary': '未填 ERP 账号密码(试算模式不需要)', 'detail': [], 'path': '',
'reconciled': 0}
# 发起前对账:ERP 已有流程的行回填「已付」并从本批剔除,避免重复发起
reconciled = 0
if bool(fields.get('reconcile', True)) and rows:
if not clients:
log('[对账] 未填 ERP 账号密码,跳过与 ERP 对账(仅按台账付款状态过滤)', 'WARN')
else:
begin, end = reconcile.window(month)
matched = []
for site, client in clients.items():
site_rows = [r for r in rows if r['system'] == site]
if not site_rows:
continue
bills = erp_mod.list_payapply(client, begin, end)
hit, _ = reconcile.match(site_rows, bills)
for m in hit:
m['site'] = site
matched.extend(hit)
log(f'[对账] {route.label(site)}:待发起 {len(site_rows)} 行、'
f'已有单据 {len(bills)} 张、命中 {len(hit)} 行', 'DEBUG')
if matched:
marks = [{'staff': m['row'].get('staff'), 'month': m['row'].get('month'),
'amount': m['row'].get('amount'), 'date': m['row'].get('date'),
'bill_no': m['bill'].get('bill_no')} for m in matched]
try:
reconciled = ledger.update_pay_status(path, marks)
log(f'[对账] {len(matched)} 行命中 ERP 已有付款申请,'
f'台账回填「{config.PAY_STATUS_DONE}」{reconciled} 行')
except ValueError as e:
log(f'[对账] 回填台账失败(仍在本批跳过重复):{e}', 'WARN')
done = {id(m['row']) for m in matched}
rows = [r for r in rows if id(r) not in done]
for m in matched[:10]:
log(f" [{route.label(m['site'])}] {m['row'].get('staff')} "
f"{m['row'].get('name')} → {m['bill'].get('bill_no')}({m['how']})",
'DEBUG')
if not rows:
return {'summary': f'{month} 待发起记录均已在 ERP 发起(对账命中 {len(matched)} 行),无需重复建单',
'detail': [], 'path': path, 'reconciled': reconciled}
org_map = ledger.load_org_map(path)
if not org_map:
log(f'[台账] 无组织机构辅助表,付款组织统一回落 {config.APPLY_ORG_ID}', 'WARN')
purpose = config.PAY_PURPOSE_OPTIONS.get(
str(fields.get('pay_purpose') or '个人借款').strip(), config.PAY_PURPOSE_ID)
dept_code = str(fields.get('apply_dept') or '').strip() or config.APPLY_DEPT_ID
apply_date = _parse_date(str(fields.get('apply_date') or ''))
effective_date = apply_date or date.today()
# 回填金蝶引入模板:FBillHead 的 申请日期 / 申请人编码 / 申请人名称(日期=当天)
bh_staff = (str(fields.get('default_applicant_staff') or '').strip()
or config.DEFAULT_APPLICANT_STAFF)
bh_name = (str(fields.get('default_applicant_name') or '').strip()
or config.DEFAULT_APPLICANT_NAME)
try:
filled = ledger.fill_billhead(path, rows, effective_date, bh_staff, bh_name)
if filled:
log(f'[单据头] 已回填 {filled} 行的申请日期({effective_date})'
f'与发起人({bh_staff}/{bh_name})')
elif rows:
log(f'[单据头] 未回填:缺少「{config.BILLHEAD_SHEET}」sheet 或行号超出模板预置范围', 'WARN')
except ValueError as e:
log(f'[单据头] 回填失败(不影响建单):{e}', 'WARN')
# 公式重算 → 校验单据头必录信息(含银行卡 AM/AN/AO),缺失行跳过不发起
recalc_ok = ledger.recalc_with_excel(path)
if recalc_ok:
log('[重算] 已用本机 Excel 全量重算并保存(公式结果已落盘)')
try:
got = ledger.check_billhead(path, rows, formula_cols=recalc_ok)
if got['missing']:
for m in got['missing'][:10]:
log(f'[校验] 跳过第 {m["row"]} 行 {m["staff"]}/{m["name"]}:'
f'缺 {"、".join(m["fields"])}', 'WARN')
log(f'[校验] {len(got["missing"])} 行单据头信息不完整,已跳过不发起'
f'(补齐台账/预支办结流程后可重跑)', 'WARN')
rows = got['ok']
if not rows:
return {'summary': '待发起行的单据头信息均不完整,本批无可发起记录',
'detail': [], 'path': path, 'reconciled': reconciled}
else:
log(f'[校验] {got["checked"]} 行单据头必录信息完整'
+ ('(含收款人/开户行/账号)' if recalc_ok
else '(未重算,仅校验日期/申请人)'))
except ValueError as e:
log(f'[校验] 单据头校验失败(不影响建单):{e}', 'WARN')
out = flow.run_flow(
rows_data=rows, org_map=org_map, clients=clients, site_errors=site_errors,
apply_date=apply_date, purpose_id=purpose, dept_code=dept_code,
expect_days=int(fields.get('expect_days') or config.DEFAULT_EXPECT_DAYS),
submit=bool(fields.get('submit', False)),
print_enabled=bool(fields.get('print_enabled', False)),
printer=str(fields.get('printer') or config.PRINTER_DEFAULT),
copies=int(fields.get('copies') or 1),
dry_run=dry_run,
workbook_path=path, # 第二份打印读「单子传递打印」本批对应行
)
log(f'[完成] {out["summary"]}')
out['reconciled'] = reconciled
return out
PLUGINS.append(PrepayPayApplyPlugin())