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

165 lines
7.6 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 -*-
"""流程编排:台账行 → 组装 → 查重 → 建单 →(提交)→ 套打 PDF →(打印)→ 传递单。
打印有两份(共用「建单后打印(ERP 单据 + 传递单)」一个开关):
1. ERP 单据:逐张 ``client.view()`` → 自绘套打 PDF → printkit 出纸;
2. Excel「单子传递打印」:本批已建单的行直接读值 → 自绘矢量 PDF → printkit 出纸。
安全默认:`dry_run=True` 时**不写 ERP**,只把将要提交的 Model 与校验结果打出来;
`submit=False` 时只建草稿(A 状态),由 HR 在 ERP 里确认后再提交。
"""
from __future__ import annotations
import os
from datetime import date, datetime
from .. import config
from ..data import erp as erp_mod
from ..data import ledger
from . import payload, route
from ..report import payapply_pdf
def _venue(row: dict) -> str:
path = str(row.get('org_path') or '')
parts = [p for p in path.replace('/', '-').split('-') if p.strip()]
return parts[-1].strip() if parts else ''
def run_flow(*, rows_data: list, org_map: dict, clients: dict | None = None,
site_errors: dict | None = None,
apply_date: date | None = None, purpose_id: str = '',
dept_code: str = '', expect_days: int = 1,
submit: bool = False, print_enabled: bool = False,
printer: str = '', copies: int = 1,
dry_run: bool = True, out_dir: str = '',
workbook_path: str = '') -> dict:
"""执行整批,返回 {summary, detail, path}。
每行按 ``row['system']``(``new``/``old``,由 ``logic.route.pick`` 预先写入)选对应
ERP 客户端与申请部门;``clients`` 是站点键 → 已登录客户端,登录失败的站点放
``site_errors``,其行直接记异常不建单。
"""
apply_date = apply_date or date.today()
purpose_id = purpose_id or config.PAY_PURPOSE_ID
dept_code = dept_code or config.APPLY_DEPT_ID
out_dir = out_dir or os.path.join(os.getcwd(), 'out')
os.makedirs(out_dir, exist_ok=True)
clients = clients or {}
site_errors = site_errors or {}
detail, errors, printed, printed_items = [], [], [], []
for row in rows_data:
venue = _venue(row)
org_code = ledger.guess_org_code(row, org_map)
site = str(row.get('system') or config.SYSTEM_NEW)
client = clients.get(site)
dept = route.dept_for(site, dept_code)
item = {'seq': row.get('seq'), 'row': row.get('row'), 'staff': row['staff'],
'name': row['name'], 'amount': row['amount'], 'org': org_code,
'venue': venue, 'system': route.label(site), 'dept': dept, 'status': ''}
if site in site_errors:
item['status'] = f'{route.label(site)}登录失败:{site_errors[site]}'
errors.append(item)
detail.append(item)
continue
try:
model = payload.build_model(row, org_code=org_code, dept_code=dept,
purpose_id=purpose_id, apply_date=apply_date,
expect_days=expect_days, venue=venue)
except Exception as e: # noqa: BLE001
item['status'] = f'组装失败:{e}'
errors.append(item)
detail.append(item)
continue
if dry_run or client is None:
item['status'] = '试算(未写 ERP)'
detail.append(item)
continue
# 幂等查重(同日期 + 同会馆 + 同姓名)
dup = erp_mod.find_duplicate(client, f"{row.get('date') or payload.fmt_date(apply_date)} {venue}-{row['name']}")
if dup:
item['status'] = f"已存在,跳过({dup[0][0]})"
detail.append(item)
continue
# 重试建单(项目规范:最多 3 次)
last = None
for attempt in range(1, config.RETRY_MAX + 1):
try:
bill_id, number = erp_mod.create(client, model)
item.update({'bill_id': bill_id, 'bill_no': number})
break
except Exception as e: # noqa: BLE001
last = e
config.log(f"[建单] {row['staff']} 第 {attempt} 次失败:{e}", 'ERROR')
if not item.get('bill_no'):
item['status'] = f'建单失败:{last}'
errors.append(item)
detail.append(item)
continue
# 提交
if submit:
try:
erp_mod.submit(client, item['bill_no'])
item['status'] = '已提交(B)'
except Exception as e: # noqa: BLE001
item['status'] = f'已建单,提交失败:{e}'
errors.append(item)
else:
item['status'] = '已建草稿(A)'
# 套打 + 打印
if print_enabled:
try:
doc = client.view(config.FORM_ID, number=item['bill_no'])
pdf = os.path.join(out_dir, config.PDF_NAME_TPL.format(bill_no=item['bill_no']))
payapply_pdf.render_payapply(payapply_pdf.from_view(doc, item['bill_no']), pdf)
item['pdf'] = pdf
from ..report import print as print_mod
pr = print_mod.print_pdf(pdf, printer, copies, dry_run=False)
item['print'] = pr
printed.append(pdf)
if any(x.get('ok') for x in pr):
printed_items.append({'bill_no': item['bill_no'], 'name': row['name'],
'amount': row['amount']})
except Exception as e: # noqa: BLE001
item['pdf_error'] = str(e)[:200]
config.log(f"[套打] {item['bill_no']} 失败:{e}", 'ERROR')
detail.append(item)
# 第二份打印:Excel「单子传递打印」本批对应行 → 矢量 PDF → printkit(汇总一份)
sheet_print = {}
if print_enabled and workbook_path:
row_nos = [d.get('row') for d in detail if d.get('bill_no') and d.get('row')]
if row_nos:
try:
from ..report import sheet_pdf
from ..report import print as print_mod
pdf = os.path.join(out_dir, config.SHEET_PRINT_TPL.format(n=len(row_nos)))
pdf, n = sheet_pdf.render_sheet_pdf(
workbook_path, config.SHEET_PRINT_SHEET, row_nos, pdf,
title=config.SHEET_PRINT_TITLE)
pr = print_mod.print_pdf(pdf, printer, 1, dry_run=False)
sheet_print = {'pdf': pdf, 'rows': n, 'print': pr}
config.log(f'[传递单] 已按 {n} 行生成并提交打印:{pdf}')
except Exception as e: # noqa: BLE001
sheet_print = {'error': str(e)[:200]}
config.log(f'[传递单] 生成/打印失败:{e}', 'ERROR')
total = sum(float(r['amount']) for r in rows_data)
summary = (f"台账 {len(rows_data)} 行,合计 {total:.2f} 元;"
f"{'试算' if dry_run else '建单'} {len([d for d in detail if d.get('bill_no')])} 张,"
f"异常 {len(errors)} 条,打印 {len(printed)} 张")
if sheet_print.get('rows'):
summary += f",传递单 {sheet_print['rows']} 行"
print_failed = len([d for d in detail if d.get('print') and not any(x.get('ok') for x in d['print'])])
return {'summary': summary, 'detail': detail, 'errors': errors,
'path': printed[0] if printed else '',
'printed': printed_items, 'print_failed': print_failed, 'printer': printer,
'sheet_print': sheet_print}