- 读 EHR 预支台账 → 按 ERP 付款申请单口径逐行建单,默认试算不写库 - 可选建单后自动提交、按套打样例生成 PDF 直连网络打印,打印完成钉钉提醒领取 - 含幂等查重与异常清单,业务口径与字段顺序按生产单核对 - 依赖 erpsdk / printkit / dingtalk_sdk(plugin.json requires.sdks 声明) - 需求单文档同步:开发/流程/评分/需求文档更新,新增交接文档
120 lines
5.3 KiB
Python
120 lines
5.3 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""流程编排:台账行 → 组装 → 查重 → 建单 →(提交)→ 套打 PDF →(打印)。
|
||
|
||
安全默认:`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
|
||
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, client=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 = '') -> dict:
|
||
"""执行整批,返回 {summary, detail, path}。"""
|
||
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)
|
||
|
||
detail, errors, printed, printed_items = [], [], [], []
|
||
for row in rows_data:
|
||
venue = _venue(row)
|
||
org_code = ledger.guess_org_code(row, org_map)
|
||
item = {'seq': row.get('seq'), 'staff': row['staff'], 'name': row['name'],
|
||
'amount': row['amount'], 'org': org_code, 'venue': venue, 'status': ''}
|
||
try:
|
||
model = payload.build_model(row, org_code=org_code, dept_code=dept_code,
|
||
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)
|
||
|
||
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)} 张")
|
||
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}
|