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

139 lines
5.7 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 -*-
"""发起前对账:台账待发起行 vs ERP 付款申请单,一对一匹配。
业务口径(2026-11 生产实测):预支台账里「付款状态」为空或「未付」的行,先看 ERP
是否已经有人发起过付款申请;有则把台账状态回填「已付」,这批行不再重复建单。
⚠️ ERP 付款申请单的申请人字段(``FBJ_SQR.FSTAFFNUMBER``)是 **代提人(HR/会馆负责人)**
的工号,不是被预支人的工号;真实受款人看 **收款单位** ``FCONTACTUNIT``(往来单位=员工),
其 ``FNumber`` 即员工工号、``FName`` 即姓名。匹配优先级:
1. 收款单位工号 == 台账工号 → 金额一致优先 → 取申请日期最接近的一张;
2. 收款单位姓名 == 台账姓名 → 金额一致 → 日期就近(收款单位工号缺失时的兼容);
3. 申请说明的 ``姓名(-)的预支/借支/借款`` 受款人格式(历史单据收款单位可能为空);
4. 申请人工号一致(本人自提场景)。
"""
from __future__ import annotations
import re
from datetime import date, datetime, timedelta
from .. import config
def _norm_staff(value) -> str:
"""工号归一:去空白与前导零(ERP 里可能存成 0000037000086)。"""
text = str(value or '').strip()
return text.lstrip('0') or text
def _same_amount(a, b) -> bool:
try:
return abs(float(a) - float(b)) <= 0.01
except (TypeError, ValueError):
return False
def _as_date(value):
text = str(value or '')[:10]
for fmt in ('%Y-%m-%d', '%Y/%m/%d', '%Y%m%d'):
try:
return datetime.strptime(text, fmt).date()
except ValueError:
continue
return None
def _day_gap(a, b) -> int:
da, db = _as_date(a), _as_date(b)
if not da or not db:
return 9999
return abs((da - db).days)
def _pick_nearest(row: dict, pool: list) -> dict:
return min(pool, key=lambda b: _day_gap(row.get('date'), b.get('date')))
def _prefer_amount(row: dict, pool: list) -> list:
"""金额一致的候选优先;没有则整个候选池按日期就近。"""
exact = [b for b in pool if _same_amount(row.get('amount'), b.get('amount'))]
return exact or pool
def _is_payee(remark: str, name: str) -> bool:
"""说明里该姓名是否为受款人(``姓名(-)的预支`` 格式)。
不能只判断姓名出现:「经过周鹏总批准予以发放」这种说明里也有姓名,但不是受款人。
"""
if not name:
return False
pattern = re.escape(name) + r'\s*[((][^))]{0,6}[))]\s*的\s*(预支|借支|借款)'
return re.search(pattern, str(remark or '')) is not None
def match(rows: list, bills: list) -> tuple:
"""台账行与 ERP 单据一对一匹配。
Args:
rows: ``ledger.read_rows`` 的行(工号/姓名/金额/年月/提报日期)
bills: ``erp.list_payapply`` 的单据(staff/amount/remark/date/status/...)
Returns:
``(matched, unmatched)``;matched 项为
``{"row": 台账行, "bill": ERP 单, "how": 匹配依据}``
"""
unused = list(bills or [])
matched, unmatched = [], []
for row in rows or []:
name = str(row.get('name') or '').strip()
staff = _norm_staff(row.get('staff'))
alive = [b for b in unused
if str(b.get('status') or '').upper() != config.ERP_VOID_STATUS]
pick, how = None, ''
# 1) 收款单位工号(FCONTACTUNIT.FNumber,生产实测即受款员工工号)
if staff:
pool = [b for b in alive if _norm_staff(b.get('payee_staff')) == staff]
if pool:
pick, how = _pick_nearest(row, _prefer_amount(row, pool)), '收款单位工号'
# 2) 收款单位姓名 + 金额(收款单位工号缺失时的兼容)
if pick is None and name:
pool = [b for b in alive if str(b.get('payee_name') or '').strip() == name]
exact = [b for b in pool if _same_amount(row.get('amount'), b.get('amount'))]
if exact:
pick, how = _pick_nearest(row, exact), '收款单位姓名+金额'
# 3) 说明受款人格式(历史单据收款单位可能为空)
if pick is None and name:
pool = [b for b in alive if _is_payee(b.get('remark'), name)]
exact = [b for b in pool if _same_amount(row.get('amount'), b.get('amount'))]
if exact:
pick, how = _pick_nearest(row, exact), '说明受款人+金额'
elif len(pool) == 1 and _day_gap(row.get('date'), pool[0].get('date')) <= 60:
pick, how = pool[0], '说明受款人'
# 4) 申请人工号(本人自提场景)
if pick is None:
pool = [b for b in alive if staff and _norm_staff(b.get('staff')) == staff]
if pool:
pick, how = _pick_nearest(row, _prefer_amount(row, pool)), '申请人工号'
if pick is None:
unmatched.append(row)
continue
unused.remove(pick)
matched.append({'row': row, 'bill': pick, 'how': how})
return matched, unmatched
def window(month: str, today: date | None = None) -> tuple:
"""台账月份 → ERP 查询窗口 ``(begin, end)``(月初前推 N 天 ~ 今天)。
预支台账的付款申请常在次月才发起,窗口前推避免漏判上月发起的单。
"""
digits = re.sub(r'\D', '', str(month or ''))
if len(digits) != 6:
raise ValueError(f'月份格式不对:{month!r}(应为 YYYYMM)')
first = date(int(digits[:4]), int(digits[4:]), 1)
end = today or datetime.now().date()
begin = first - timedelta(days=int(config.RECONCILE_LOOKBACK_DAYS))
return begin.isoformat(), end.isoformat()