Files
puddy 50fb138e1b feat(plugin): 新增 XQ0006 周考勤异常处理、XQ0083 调动流程生效确认;其余插件累积改动
XQ0001 排班异常识别 / XQ0002 雇主险增减操作 / XQ0012 ERP 付款申请 / XQ0013 社保费用申报 / XQ0042 抖音平台核对 / XQ0084 银行卡更新:逻辑与界面 bundle 更新(含各自版本号变更)
2026-11-18 18:55:59 +08:00

390 lines
23 KiB
Python
Raw Permalink 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):不建单/不提交/不打印、不回填「付款状态」与单据头,
只输出将要提交的报文与校验结果(台账导出追加、办结流程刷新仍会写工作簿,日志会明说);
业务口径确认后关掉试算、按需打开「提交」「打印」。
资金安全约束(2026-11 加固):
- 对账/查重查询失败即**阻断**(对账失败中止整批、单行查重失败跳过该行),绝不 fail-open;
- 对账命中要求**受款人工号/姓名 + 金额一致**,金额不同视为另一笔付款;
- 幂等键 = 申请日期 + 会馆(预支四级部门)+ 姓名 + 金额。
单据口径(申请日期/付款用途/期望付款日/申请部门)**以工作簿「FBillHead」该行为准**,
界面不再暴露这四项;新旧系统各用一套 ERP 账密(旧版留空时沿用新版)。
"""
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, runmode
from .logic.dates import parse_int
class PrepayPayApplyPlugin(ScenePlugin):
"""EHR 预支 → ERP 付款申请单(需求 XQ0012)。"""
id = 'xq0012'
name = 'EHR预支及支付报酬自动发起ERP付款申请'
version = '0.3.4'
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(跳过导出与追加);留空=按台账月份自动导出/追加',
},
'default_applicant_staff': {
'type': 'string', 'title': '默认发起人工号', 'default': config.DEFAULT_APPLICANT_STAFF,
'description': '即单据头 E 列「申请人#编码」,同时作为 ERP 建单报文的申请人'
'(代提人,不是受款员工)',
},
'default_applicant_name': {
'type': 'string', 'title': '默认发起人姓名', 'default': config.DEFAULT_APPLICANT_NAME,
'description': '单据头 F 列「申请人#名称」;建单报文按编码带出姓名,此值只写工作簿',
},
'erp_system': {
'type': 'string', 'title': 'ERP系统', 'default': config.SYSTEM_AUTO,
'enum': ['自动', '新版', '旧版'],
'description': '自动=按台账「新旧系统」口径逐行分流;新版/旧版=强制全部走一个系统',
},
'erp_username': {'type': 'string', 'title': '新版ERP账号', 'default': ''},
'erp_password': {'type': 'string', 'title': '新版ERP密码', 'default': '',
'format': 'password'},
'erp_username_old': {'type': 'string', 'title': '旧版ERP账号', 'default': '',
'description': '旧系统账号与新版不同;留空=沿用新版账号'},
'erp_password_old': {'type': 'string', 'title': '旧版ERP密码', 'default': '',
'format': 'password',
'description': '旧系统密码与新版不同;留空=沿用新版密码'},
'run_mode': {
'type': 'string', 'title': '执行方式', 'default': runmode.MODE_DRY,
'enum': [m['value'] for m in runmode.MODES],
'description': '试算=dry_run(不写 ERP)|draft=只建草稿(A,人工核对后提交)|'
'submit=建单并提交(B,进审批流)',
},
'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': '打印成功后用工作通知提醒默认发起人(单号/收款人/金额/打印机),提醒去领取签字',
},
'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)
# 执行方式三选一:dry_run / draft(只建草稿 A)/ submit(建单并提交 B)
mode, dry_run, submit = runmode.resolve(fields)
if mode not in [m['value'] for m in runmode.MODES]:
log(f'[执行] 未知执行方式「{mode}」,按试算处理', 'WARN')
log(f'[执行] 执行方式:{runmode.label(mode)}'
+ ('(不写 ERP)' if dry_run else
('(只建草稿,人工核对后提交)' if not submit else '(建单后立即提交)')))
if dry_run:
log('[试算] 不建单/不提交/不打印、不回填「付款状态」与单据头;'
'台账导出追加、「预支办结流程」刷新仍会写工作簿', 'WARN')
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 出收款人/银行/账号
# 按月扫描「流程监控-已办结」整表覆盖,与台账行无关(已付行也要查得到收款信息)
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')
# 新旧系统分流:口径见 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 '')
user_old = str(fields.get('erp_username_old') or '').strip() or user
pwd_old = str(fields.get('erp_password_old') or '') or pwd
creds = {config.SYSTEM_NEW: (user, pwd), config.SYSTEM_OLD: (user_old, pwd_old)}
clients, site_errors = {}, {}
if user and pwd:
for site in sorted({r['system'] for r in rows}):
site_user, site_pwd = creds.get(site, (user, pwd))
if not (site_user and site_pwd):
site_errors[site] = '未填该系统的 ERP 账号/密码'
log(f'[ERP] {route.label(site)}未填账号密码,该系统下的行将跳过', 'ERROR')
continue
try:
clients[site] = erp_mod.login(site_user, site_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 已有流程的行回填「已付」并从本批剔除,避免重复发起。
# ⚠️ 对账查询失败**必须中止本批**(正式执行):查不到已有单据就当"没有重复",
# 会把 ERP 里已发起的单再发一遍。试算模式只告警,结果不剔除。
reconciled = 0
reconcile_error = ''
matched = []
if rows:
if not clients:
log('[对账] 未填 ERP 账号密码,跳过与 ERP 对账(仅按台账付款状态过滤)', 'WARN')
else:
begin, end = reconcile.window(month)
for site, client in clients.items():
site_rows = [r for r in rows if r['system'] == site]
if not site_rows:
continue
try:
bills = erp_mod.list_payapply(client, begin, end)
except Exception as e: # noqa: BLE001
reconcile_error = f'{route.label(site)}:{str(e)[:160]}'
log(f'[对账] {route.label(site)} 查询 ERP 付款申请单失败:{e}', 'ERROR')
break
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 reconcile_error and not dry_run:
raise RuntimeError(f'与 ERP 对账失败,本批已中止(避免重复发起付款):'
f'{reconcile_error}')
if reconcile_error:
log('[对账] 试算模式:对账失败,结果未剔除 ERP 已有单据;'
'正式执行会直接中止,请先修好查询', 'ERROR')
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]
if dry_run:
log(f'[对账] 试算模式:{len(matched)} 行命中 ERP 已有付款申请,'
f'本轮按"已发起"剔除(不回填台账「{config.PAY_STATUS_DONE}」)', 'WARN')
else:
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,
'reconcile_error': reconcile_error}
org_map = ledger.load_org_map(path)
if not org_map:
log(f'[台账] 无组织机构辅助表,付款组织统一回落 {config.APPLY_ORG_ID}', 'WARN')
# 单据口径以工作簿模板该行为准(界面不再问):AH 付款用途 / AK 期望付款日 / W 申请部门
purpose = config.PAY_PURPOSE_ID
dept_code = config.APPLY_DEPT_ID
effective_date = date.today()
copies = parse_int(fields.get('copies'), 1, '打印份数', 1, 5)
# 回填金蝶引入模板: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)
if dry_run:
log('[单据头] 试算模式:不回填申请日期/发起人(正式执行才写)')
else:
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')
# 收款账户(报文 AM/AN/AO):与单据头 XLOOKUP 同源 —— 预支办结流程 O/V/AC/AD
banks = ledger.load_flow_banks(path)
if banks:
hit = sum(1 for r in rows if str(r.get('staff') or '').strip() in banks)
log(f'[收款] 「{config.FLOW_SHEET}」收款信息 {len(banks)} 个工号,'
f'本批命中 {hit}/{len(rows)} 行(未命中的报文收款字段留空)')
else:
log(f'[收款] 「{config.FLOW_SHEET}」无收款信息(或列不全),报文收款字段留空', 'WARN')
# 单据口径(申请日期/付款用途/期望付款日/申请部门):直接读模板该行,界面不再问
terms = ledger.load_billhead_terms(path, rows)
if terms:
sample = next(iter(terms.values()))
log(f'[口径] 已读模板单据口径 {len(terms)} 行;示例:'
f'申请日期 {sample.get("apply_date") or "(空,用当天)"}、'
f'付款用途 {sample.get("purpose") or "(空,用默认)"}、'
f'期望付款日 {sample.get("expect_date") or "(空,用申请日+N)"}、'
f'申请部门 {sample.get("dept") or "(空,随新旧系统)"}')
else:
log(f'[口径] 未读到「{config.BILLHEAD_SHEET}」单据口径(缺 sheet/超模板行),'
f'按默认:申请日期=当天、付款用途={config.PAY_PURPOSE_ID}、'
f'期望付款日=+{config.DEFAULT_EXPECT_DAYS} 天、申请部门随系统', 'WARN')
out = flow.run_flow(
rows_data=rows, org_map=org_map, clients=clients, site_errors=site_errors,
apply_date=effective_date, purpose_id=purpose, dept_code=dept_code,
applicant_staff=bh_staff, # 申请人=界面默认发起人(FBillHead E/F 列)
expect_days=config.DEFAULT_EXPECT_DAYS,
submit=submit,
print_enabled=bool(fields.get('print_enabled', False)),
printer=str(fields.get('printer') or config.PRINTER_DEFAULT),
copies=copies,
dry_run=dry_run,
banks=banks,
terms=terms,
workbook_path=path, # 第二份打印读「单子传递打印」本批对应行
)
log(f'[完成] {out["summary"]}')
out['reconciled'] = reconciled
if reconcile_error:
out['reconcile_error'] = reconcile_error
# 打印完成 → 钉钉工作通知提醒领取(失败只记日志,不影响单据与打印)
if out.get('printed'):
if not bool(fields.get('dingtalk_enabled', config.DINGTALK_ENABLED_DEFAULT)):
log('[钉钉] 「打印后钉钉提醒」已关闭,跳过提醒')
else:
try:
from .report import notify
recipient = f'{bh_name}/{bh_staff}' if bh_name else bh_staff
out['notify'] = notify.notify_printed(
out['printed'],
out.get('printer') or str(fields.get('printer') or ''),
out.get('print_failed', 0),
users_text=recipient,
dry_run=dry_run)
if out['notify'].get('ok'):
log(f'[钉钉] 已提醒发起人「{recipient}」领取')
else:
log(f'[钉钉] 提醒未发出:'
f'{out["notify"].get("error") or out["notify"].get("skipped")}', 'WARN')
except Exception as e: # noqa: BLE001
out['notify'] = {'ok': False, 'error': str(e)[:200]}
log(f'[钉钉] 提醒失败(不影响单据):{e}', 'WARN')
return out
PLUGINS.append(PrepayPayApplyPlugin())