feat(plugin): XQ0012 预支付款申请 0.2.5(对账回填、新旧系统分流、两份打印、钉钉提醒模块)
台账按月接口导出并追加目标工作簿;整表刷新「预支办结流程」供单据头 XLOOKUP 取收款信息;发起前对账命中回填已付;按台账口径新旧系统分流;建单后套打 ERP 单据 + 单子传递打印;含离线自检与打包脚本。
This commit is contained in:
@@ -24,7 +24,7 @@
|
||||
| `erp_system` / `erp_username` / `erp_password` | ERP 新版/旧版与账密(仅存本机) |
|
||||
| `dry_run` | **默认开**:只组装 + 查重 + 输出,不写 ERP |
|
||||
| `submit` | 建单后自动提交(默认关) |
|
||||
| `print_enabled` / `printer` / `copies` | 套打打印、打印机(人力资源部双面 / 网络信息部单面)、份数 |
|
||||
| `print_enabled` / `printer` / `copies` | 套打打印、打印机(人力资源部双面 / 信息技术部单面)、份数 |
|
||||
| `dingtalk_enabled` / `dingtalk_users` | 打印后钉钉提醒(默认开)、接收人「姓名/工号」(多个用「、」分隔,留空=不提醒) |
|
||||
|
||||
## 依赖
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0012 EHR 预支及支付报酬 → ERP 付款申请单(webhost 场景插件)。
|
||||
|
||||
流程:读 EHR 预支台账(xlsx)→ 逐行组装 Save Model →(幂等查重)→ 建单 →
|
||||
(可选提交)→ 自绘套打 PDF →(可选)printkit 出纸。
|
||||
流程:按月份从 EHR 接口导出预支报酬台账(默认当月)→ 读有效行 → 逐行组装 Save Model
|
||||
→(幂等查重)→ 建单 →(可选提交)→ 自绘套打 PDF →(可选)printkit 出纸。
|
||||
|
||||
默认 **试算模式**(dry_run=True):不写 ERP,只输出将要提交的报文与校验结果;
|
||||
业务口径确认后关掉试算、按需打开「提交」「打印」。
|
||||
@@ -15,7 +15,7 @@ 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
|
||||
from .logic import flow, reconcile, route
|
||||
|
||||
|
||||
def _parse_date(s: str):
|
||||
@@ -41,21 +41,31 @@ class PrepayPayApplyPlugin(ScenePlugin):
|
||||
|
||||
id = 'xq0012'
|
||||
name = 'EHR预支及支付报酬自动发起ERP付款申请'
|
||||
version = '0.1.0'
|
||||
description = ('读 EHR 预支台账 → 自动在 ERP 建付款申请单(默认试算不写库),'
|
||||
'可选提交、自动套打打印;含幂等查重与异常清单')
|
||||
platform = '' # 走 ERP WebAPI 账密登录,不用底座共享登录态
|
||||
version = '0.2.5'
|
||||
description = ('按月份从 EHR 接口导出预支报酬台账(默认当月)→ 按月扫描已办结预支流程刷新'
|
||||
'「预支办结流程」→ Excel 重算并校验单据头必录信息(含银行卡)→ 自动在 ERP '
|
||||
'建付款申请单(默认试算不写库),可选提交、打印两份(ERP 单据套打 + 单子传递单);'
|
||||
'含幂等查重与异常清单')
|
||||
platform = 'hr' # 数据源走底座共享的 HR 登录态;ERP 仍用账密登录
|
||||
uses_month = False
|
||||
capabilities = ['xq0012']
|
||||
permissions = {'platforms': []}
|
||||
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': '预支台账 xlsx 所在目录;留空=默认目录,自动取最新一个',
|
||||
'description': '导出临时文件/独立台账落盘目录;留空=默认目录',
|
||||
},
|
||||
'ledger_workbook': {
|
||||
'type': 'string', 'title': '目标工作簿', 'default': config.LEDGER_WORKBOOK_DEFAULT,
|
||||
'description': '导出数据追加到该工作簿的「预支报酬台账」sheet(按表头对齐、自动去重);留空=只导出独立文件',
|
||||
},
|
||||
'ledger_file': {
|
||||
'type': 'string', 'title': '台账文件(可选)', 'default': '',
|
||||
'description': '指定具体 xlsx 路径;留空=按目录取最新',
|
||||
'description': '指定现成 xlsx(跳过导出与追加);留空=按台账月份自动导出/追加',
|
||||
},
|
||||
'apply_date': {
|
||||
'type': 'string', 'title': '申请日期', 'default': '',
|
||||
@@ -82,12 +92,23 @@ class PrepayPayApplyPlugin(ScenePlugin):
|
||||
'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': '建单后套打打印', 'default': False,
|
||||
'type': 'boolean', 'title': '建单后打印(ERP 单据 + 传递单)', 'default': False,
|
||||
'description': '打开后打两份:①每张 ERP 付款申请单套打一份;'
|
||||
'②「单子传递打印」里本批建单对应的行汇总一份',
|
||||
},
|
||||
'printer': {
|
||||
'type': 'string', 'title': '打印机', 'default': config.PRINTER_DEFAULT,
|
||||
@@ -122,32 +143,168 @@ class PrepayPayApplyPlugin(ScenePlugin):
|
||||
|
||||
work_dir = str(fields.get('ledger_dir') or '').strip() or config.LEDGER_DIR_DEFAULT
|
||||
ledger_file = str(fields.get('ledger_file') or '').strip()
|
||||
path = ledger_file or ledger.find_latest_ledger(work_dir)
|
||||
log(f'[台账] {path}')
|
||||
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)
|
||||
log(f'[台账] 有效数据 {len(rows)} 行')
|
||||
rows = ledger.read_rows(path, month, pending_only=True)
|
||||
log(f'[台账] {month} 待发起(付款状态为空/未付){len(rows)} 行')
|
||||
if not rows:
|
||||
return {'summary': '台账无有效数据(检查工号/金额是否为空或含 #N/A)', 'detail': [], 'path': ''}
|
||||
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()
|
||||
|
||||
dry_run = bool(fields.get('dry_run', True))
|
||||
client = None
|
||||
if not dry_run:
|
||||
user = str(fields.get('erp_username') or '').strip()
|
||||
pwd = str(fields.get('erp_password') or '')
|
||||
if not (user and pwd):
|
||||
return {'summary': '未填 ERP 账号密码(试算模式不需要)', 'detail': [], 'path': ''}
|
||||
erp = 'old' if str(fields.get('erp_system') or '新版').strip() == '旧版' else 'new'
|
||||
client = erp_mod.login(user, pwd, erp=erp)
|
||||
# 回填金蝶引入模板: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, client=client,
|
||||
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)),
|
||||
@@ -155,8 +312,10 @@ class PrepayPayApplyPlugin(ScenePlugin):
|
||||
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
|
||||
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ _pkg.__path__ = [str(HERE)]
|
||||
sys.modules["xq0012"] = _pkg
|
||||
|
||||
from xq0012 import config # noqa: E402
|
||||
from xq0012.logic import payload, flow # noqa: E402
|
||||
from xq0012.logic import payload, flow, reconcile, route # noqa: E402
|
||||
from xq0012.report import payapply_pdf, notify # noqa: E402
|
||||
|
||||
FAILED = []
|
||||
@@ -58,18 +58,25 @@ def t_payload_order():
|
||||
|
||||
|
||||
def t_ledger_read():
|
||||
p = config.LEDGER_DIR_DEFAULT
|
||||
import os
|
||||
if not os.path.isdir(p):
|
||||
print(' (台账目录不存在,跳过)')
|
||||
return
|
||||
sys.path.insert(0, str(HERE))
|
||||
from xq0012.data import ledger
|
||||
f = ledger.find_latest_ledger(p)
|
||||
assert ledger.normalize_month('2026-11') == '202611', '月份归一'
|
||||
f = config.LEDGER_WORKBOOK_DEFAULT # 默认:追加目标工作簿
|
||||
if not os.path.exists(f):
|
||||
p = config.LEDGER_DIR_DEFAULT
|
||||
cands = [os.path.join(p, n) for n in os.listdir(p)
|
||||
if n.startswith('预支报酬台账_') and n.endswith('.xlsx')] if os.path.isdir(p) else []
|
||||
if not cands:
|
||||
print(' (既没有目标工作簿,也没有接口导出的 预支报酬台账_YYYYMM.xlsx,跳过)')
|
||||
return
|
||||
f = max(cands, key=os.path.getmtime)
|
||||
rows = ledger.read_rows(f)
|
||||
assert rows and rows[0]['staff'], '台账应至少有一条有效行'
|
||||
month_rows = ledger.read_rows(f, '202611')
|
||||
org = ledger.load_org_map(f)
|
||||
print(f' {Path(f).name}: {len(rows)} 行,组织映射 {len(org)} 条')
|
||||
print(f' {Path(f).name}: 全部 {len(rows)} 行、202611 {len(month_rows)} 行,'
|
||||
f'组织映射 {len(org)} 条')
|
||||
|
||||
|
||||
def t_render_pdf():
|
||||
@@ -94,8 +101,8 @@ def t_notify_message():
|
||||
body = notify.build_message(
|
||||
[{'bill_no': 'FKSQ20261100001', 'name': '何广飞', 'amount': 2000.0},
|
||||
{'bill_no': 'FKSQ20261100002', 'name': '唐雪非', 'amount': 1500.5}],
|
||||
'网络信息部', failed=1)
|
||||
assert '网络信息部' in body and '打印机处领取' in body
|
||||
'信息技术部', failed=1)
|
||||
assert '信息技术部' in body and '打印机处领取' in body
|
||||
assert 'FKSQ20261100001' in body and '1500.50' in body
|
||||
assert '合计 3500.50 元' in body
|
||||
assert '打印失败' in body
|
||||
@@ -107,12 +114,261 @@ def t_notify_recipients():
|
||||
assert got[2] == ('李四', '')
|
||||
|
||||
|
||||
def t_reconcile_match():
|
||||
from datetime import date as _date
|
||||
# 真实场景:ERP 单的申请人工号是代提人(HR),受款人只在申请说明里
|
||||
rows = [
|
||||
{'staff': '37000365', 'name': '何广飞', 'amount': 2000.0, 'month': '202610',
|
||||
'date': '2026-10-27', 'pay_status': ''},
|
||||
{'staff': '37000086', 'name': '周鹏', 'amount': 20000.0, 'month': '202611',
|
||||
'date': '2026-11-01', 'pay_status': '未付'},
|
||||
{'staff': '37000999', 'name': '张三', 'amount': 500.0, 'month': '202611',
|
||||
'date': '2026-11-03', 'pay_status': '未付'},
|
||||
]
|
||||
bills = [
|
||||
{'bill_no': 'FKSQ20261001405', 'staff': '37001090', 'amount': 2000.0, 'status': 'C',
|
||||
'date': '2026-10-30', 'payee_staff': '37000365', 'payee_name': '何广飞',
|
||||
'remark': '2026-10-30 水晶郦城CEO会馆-何广飞(-)的预支,原因:缴纳弟弟生活费;'},
|
||||
{'bill_no': 'FKSQ20260901369', 'staff': '37001090', 'amount': 2000.0, 'status': 'C',
|
||||
'date': '2026-09-22', 'payee_staff': '37000365', 'payee_name': '何广飞',
|
||||
'remark': '2026-09-22 水晶郦城CEO会馆-何广飞(-)的预支,原因:支付妹妹大学生活费;'},
|
||||
{'bill_no': 'FKSQ20261100003', 'staff': '37000999', 'amount': 500.0, 'status': 'Z',
|
||||
'date': '2026-11-03', 'payee_staff': '37000999', 'payee_name': '张三',
|
||||
'remark': '2026-11-03 某会馆-张三(-)的预支'},
|
||||
# 生产真实干扰项:「经过周鹏总批准」不是周鹏本人的预支单,收款人也不是周鹏
|
||||
{'bill_no': 'FKSQ20261000965', 'staff': '37001090', 'amount': 600.0, 'status': 'C',
|
||||
'date': '2026-10-17', 'payee_staff': '37001234', 'payee_name': '其他员工',
|
||||
'remark': '该员工与门店存在劳资纠纷,经过周鹏总批准予以发放。(国贸LIFE主题会馆);'},
|
||||
]
|
||||
matched, unmatched = reconcile.match(rows, bills)
|
||||
assert len(matched) == 1, f'应命中 1 行,实际 {len(matched)}'
|
||||
assert matched[0]['bill']['bill_no'] == 'FKSQ20261001405', '应取日期最接近的 10-30 单'
|
||||
assert matched[0]['how'] == '收款单位工号', '应优先按收款单位命中'
|
||||
assert {u['name'] for u in unmatched} == {'周鹏', '张三'}, '周鹏无单、张三单作废,均未命中'
|
||||
assert not reconcile._is_payee('经过周鹏总批准予以发放', '周鹏'), '姓名出现≠受款人'
|
||||
assert reconcile._is_payee('水晶郦城CEO会馆-何广飞(-)的预支', '何广飞')
|
||||
assert reconcile.window('202611', today=_date(2026, 11, 16)) == ('2026-09-17', '2026-11-16')
|
||||
|
||||
|
||||
def t_pending_filter():
|
||||
import os
|
||||
sys.path.insert(0, str(HERE))
|
||||
from xq0012.data import ledger
|
||||
assert ledger.is_pending({'pay_status': ''})
|
||||
assert ledger.is_pending({'pay_status': '未付'})
|
||||
assert not ledger.is_pending({'pay_status': '已付'})
|
||||
f = config.LEDGER_WORKBOOK_DEFAULT
|
||||
if os.path.exists(f):
|
||||
all_rows = ledger.read_rows(f, '202611')
|
||||
pending = ledger.read_rows(f, '202611', pending_only=True)
|
||||
assert len(pending) <= len(all_rows), '待发起行数不应超过全部行数'
|
||||
print(f' 202611 全部 {len(all_rows)} 行、待发起 {len(pending)} 行')
|
||||
|
||||
|
||||
def t_route_pick():
|
||||
std = {'解放碑CBD行政会馆': '是', '新光天地行政会馆': '是'}
|
||||
store = {'job_seq': config.JOB_SEQ_STORE, 'dept4': '水晶郦城CEO会馆'}
|
||||
assert route.pick(store, std) == config.SYSTEM_OLD, '门店服务序列 + 非标准化 → 旧系统'
|
||||
assert route.pick({'job_seq': config.JOB_SEQ_STORE, 'dept4': '解放碑CBD行政会馆'},
|
||||
std) == config.SYSTEM_NEW, '标准化门店 → 新系统'
|
||||
assert route.pick({'job_seq': '经营系管理序列', 'dept4': '水晶郦城CEO会馆'},
|
||||
std) == config.SYSTEM_NEW, '非门店服务序列 AR 恒为「-」→ 新系统'
|
||||
assert route.pick(store, {}) == config.SYSTEM_OLD, '无标准化名单时按查不到=「否」'
|
||||
assert route.dept_for(config.SYSTEM_OLD, 'BM000477') == config.DEPT_OLD_SYSTEM
|
||||
assert route.dept_for(config.SYSTEM_NEW, 'BM000477') == 'BM000477'
|
||||
|
||||
import os
|
||||
sys.path.insert(0, str(HERE))
|
||||
from xq0012.data import ledger
|
||||
f = config.LEDGER_WORKBOOK_DEFAULT
|
||||
if os.path.exists(f):
|
||||
stores = ledger.load_std_stores(f)
|
||||
assert stores.get('解放碑CBD行政会馆') == '是', '辅助0 sheet 读取应含标准化门店'
|
||||
rows = ledger.read_rows(f)
|
||||
picked = {route.label(route.pick(r, stores)) for r in rows}
|
||||
print(f' 标准化门店 {len(stores)} 家;台账 {len(rows)} 行判定:{picked or "-"}')
|
||||
|
||||
|
||||
def t_flow_dry_run():
|
||||
rows = [{'seq': '1', 'staff': '37000365', 'name': '何广飞', 'date': '2026-10-30',
|
||||
'amount': 2000.0, 'reason': '测试', 'org_path': '集团-水晶郦城CEO会馆', 'dept': '接待组'}]
|
||||
'amount': 2000.0, 'reason': '测试', 'org_path': '集团-水晶郦城CEO会馆',
|
||||
'dept': '接待组', 'system': config.SYSTEM_NEW}]
|
||||
out = flow.run_flow(rows_data=rows, org_map={'水晶郦城CEO会馆': '99.01.06.01.02.01.05'},
|
||||
dry_run=True, apply_date=date(2026, 10, 30))
|
||||
assert '试算' in out['summary'] and len(out['detail']) == 1
|
||||
assert out['detail'][0]['system'] == '新系统'
|
||||
|
||||
|
||||
def t_flow_site_error():
|
||||
rows = [{'seq': '1', 'staff': '37000365', 'name': '何广飞', 'date': '2026-10-30',
|
||||
'amount': 2000.0, 'reason': '测试', 'org_path': '集团-水晶郦城CEO会馆',
|
||||
'dept': '接待组', 'system': config.SYSTEM_OLD}]
|
||||
out = flow.run_flow(rows_data=rows, org_map={}, dry_run=False,
|
||||
site_errors={config.SYSTEM_OLD: '密码错误'})
|
||||
assert out['detail'][0]['status'].startswith('旧系统登录失败'), out['detail'][0]['status']
|
||||
assert out['detail'][0]['dept'] == config.DEPT_OLD_SYSTEM
|
||||
|
||||
|
||||
def t_billhead_fill():
|
||||
"""FBillHead 三列回填:日期=传入日期、发起人=默认值、越界行跳过。"""
|
||||
import tempfile
|
||||
|
||||
import openpyxl
|
||||
from xq0012.data import ledger
|
||||
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = config.BILLHEAD_SHEET
|
||||
for col, name in ((4, '*' + config.BH_COL_DATE), (5, config.BH_COL_APPLICANT_NO),
|
||||
(6, config.BH_COL_APPLICANT_NAME)):
|
||||
ws.cell(row=2, column=col).value = name # 真实模板的日期列带必录星号 *
|
||||
ws.cell(row=3, column=8).value = '37000365'
|
||||
path = str(Path(tempfile.gettempdir()) / 'xq0012_billhead_selftest.xlsx')
|
||||
wb.save(path)
|
||||
|
||||
n = ledger.fill_billhead(path, [{'row': 3}, {'row': 99}],
|
||||
date(2026, 11, 16), '37001090', '刘纤')
|
||||
assert n == 1, f'只应回填 1 行,实际 {n}'
|
||||
wb2 = openpyxl.load_workbook(path, data_only=True)
|
||||
got = [wb2[config.BILLHEAD_SHEET].cell(row=3, column=c).value for c in (4, 5, 6)]
|
||||
wb2.close()
|
||||
assert got[0].date() == date(2026, 11, 16), got
|
||||
assert got[1] == '37001090' and got[2] == '刘纤', got
|
||||
|
||||
|
||||
def t_flow_sheet():
|
||||
"""预支办结流程:整表覆盖(清旧行/按表头写/标记重算)+ 月份区间 + 缺 sheet 直接返回。"""
|
||||
import tempfile
|
||||
|
||||
import openpyxl
|
||||
from xq0012.data import ledger
|
||||
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = config.FLOW_SHEET
|
||||
header = ['流水号', '工号', '姓名', '收款银行', '收款账号']
|
||||
for i, name in enumerate(header, start=1):
|
||||
ws.cell(row=2, column=i).value = name
|
||||
ws.cell(row=3, column=2).value = 'OLD' # 旧数据应被清空
|
||||
path = str(Path(tempfile.gettempdir()) / 'xq0012_flow_selftest.xlsx')
|
||||
wb.save(path)
|
||||
|
||||
data = [{'工号': '37000365', '姓名': '何广飞', '收款银行': '中国银行', '收款账号': '6217****1'},
|
||||
{'工号': '37000366', '姓名': '周鹏', '收款银行': '建设银行', '收款账号': '6217****2'}]
|
||||
n = ledger.write_flow_sheet(path, header, data)
|
||||
assert n == 2, n
|
||||
wb2 = openpyxl.load_workbook(path, data_only=True)
|
||||
got = [[c.value for c in r] for r in wb2[config.FLOW_SHEET].iter_rows(
|
||||
min_row=3, max_row=5, max_col=5)]
|
||||
assert got[0][1] == '37000365' and got[1][1] == '37000366', got
|
||||
assert got[2] == [None] * 5, f'第 3 行旧数据未清空:{got[2]}'
|
||||
assert wb2.calculation.fullCalcOnLoad, '未标记打开时重算'
|
||||
wb2.close()
|
||||
|
||||
# 月份区间(流程监控按月扫描)
|
||||
assert ledger.month_range('2026-11') == ('2026-11-01', '2026-11-30')
|
||||
assert ledger.month_range('202602') == ('2026-02-01', '2026-02-28')
|
||||
assert ledger.month_range('2024-02') == ('2024-02-01', '2024-02-29')
|
||||
|
||||
# 工作簿缺「预支办结流程」→ 直接返回原因,不发起任何请求
|
||||
wb3 = openpyxl.Workbook()
|
||||
wb3.active.title = '别的sheet'
|
||||
path3 = str(Path(tempfile.gettempdir()) / 'xq0012_flow_nosheet.xlsx')
|
||||
wb3.save(path3)
|
||||
res = ledger.refresh_flow_sheet(object(), path3, '202611')
|
||||
assert res['written'] == 0 and '缺少' in res['reason'], res
|
||||
|
||||
|
||||
def t_billhead_check():
|
||||
"""单据头完整性校验:必录 9 列、缺失行列出短名、可降级为只校验 D/E/F。"""
|
||||
import tempfile
|
||||
|
||||
import openpyxl
|
||||
from xq0012.data import ledger
|
||||
|
||||
cols = [(4, '*' + config.BH_COL_DATE), (5, config.BH_COL_APPLICANT_NO),
|
||||
(6, config.BH_COL_APPLICANT_NAME), (16, config.BH_COL_PAY_ORG),
|
||||
(18, config.BH_COL_SETTLE_ORG), (24, config.BH_COL_DEPT_NAME),
|
||||
(39, config.BH_COL_ACCOUNT_NAME), (40, config.BH_COL_BANK),
|
||||
(41, config.BH_COL_ACCOUNT_NO)]
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = config.BILLHEAD_SHEET
|
||||
for col, name in cols:
|
||||
ws.cell(row=2, column=col).value = name
|
||||
for r in (3, 4):
|
||||
ws.cell(row=r, column=4).value = date(2026, 11, 16)
|
||||
ws.cell(row=r, column=5).value = '37001090'
|
||||
ws.cell(row=r, column=6).value = '刘纤'
|
||||
ws.cell(row=r, column=16).value = '重庆三十七度健康管理有限公司'
|
||||
ws.cell(row=r, column=18).value = '重庆三十七度健康管理有限公司'
|
||||
ws.cell(row=r, column=24).value = '人力资源部'
|
||||
ws.cell(row=r, column=39).value = '何广飞'
|
||||
ws.cell(row=r, column=40).value = '招商银行'
|
||||
ws.cell(row=3, column=41).value = '6222****0000' # 只有第 3 行银行卡齐全
|
||||
path = str(Path(tempfile.gettempdir()) / 'xq0012_billhead_check.xlsx')
|
||||
wb.save(path)
|
||||
|
||||
rows = [{'row': 3, 'staff': '37000365', 'name': '何广飞'},
|
||||
{'row': 4, 'staff': '37000366', 'name': '周鹏'},
|
||||
{'row': 99, 'staff': '37000367', 'name': '越界'}]
|
||||
got = ledger.check_billhead(path, rows)
|
||||
assert got['checked'] == 3 and len(got['ok']) == 1, got
|
||||
assert got['ok'][0]['row'] == 3
|
||||
missing = {m['row']: m['fields'] for m in got['missing']}
|
||||
assert missing[4] == ['对方银行账号'], missing
|
||||
assert missing[99] == ['超出模板预置行'], missing
|
||||
|
||||
part = ledger.check_billhead(path, rows, formula_cols=False)
|
||||
assert len(part['ok']) == 2, '不重算时只校验 D/E/F,第 4 行也应通过'
|
||||
|
||||
|
||||
def t_sheet_print():
|
||||
"""单子传递打印:只打本批行、两行表头、读值渲染、页脚行数正确。"""
|
||||
import tempfile
|
||||
|
||||
import openpyxl
|
||||
import pymupdf as fitz
|
||||
from xq0012.report import sheet_pdf
|
||||
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = config.SHEET_PRINT_SHEET
|
||||
head = ['FSEQNO', 'FPAYDATE', 'FPAYUNITNAME', 'FPAYORGNAME', 'FEXPENSEITEMNAME',
|
||||
'FAPPLYAMOUNT']
|
||||
cn = ['序号', '日期', '收款单位', '付款组织', '费用项目', '申请付款金额']
|
||||
for c, v in enumerate(head, 1):
|
||||
ws.cell(row=1, column=c).value = v
|
||||
for c, v in enumerate(cn, 1):
|
||||
ws.cell(row=2, column=c).value = v
|
||||
data = [(3, '1', '2026-10-30', '何广飞', '水晶郦城CEO会馆', '预支工资', 2000),
|
||||
(4, '2', '2026-10-30', '不打印的行', '-', '-', 999),
|
||||
(5, '3', '2026-10-30', '周鹏', '总部', '预支工资', 3000)]
|
||||
for r, seq, d, name, org, item, amt in data:
|
||||
for c, v in enumerate([seq, d, name, org, item, amt], 1):
|
||||
ws.cell(row=r, column=c).value = v
|
||||
path = str(Path(tempfile.gettempdir()) / 'xq0012_sheet_print.xlsx')
|
||||
wb.save(path)
|
||||
|
||||
out = str(Path(tempfile.gettempdir()) / 'xq0012_sheet_print.pdf')
|
||||
pdf, n = sheet_pdf.render_sheet_pdf(path, config.SHEET_PRINT_SHEET, [3, 5], out)
|
||||
assert n == 2, n
|
||||
doc = fitz.open(pdf)
|
||||
try:
|
||||
text = ''.join(p.get_text() for p in doc)
|
||||
flat = ''.join(text.split()) # 字体子集化后空格可能不是 U+0020
|
||||
assert '共2行' in flat, text[:200]
|
||||
assert '何广飞' in flat and '周鹏' in flat
|
||||
assert '不打印的行' not in flat
|
||||
assert '收款单位' in flat and '申请付款金额' in flat
|
||||
finally:
|
||||
doc.close()
|
||||
|
||||
try:
|
||||
sheet_pdf.render_sheet_pdf(path, '不存在的sheet', [3], out)
|
||||
raise AssertionError('缺 sheet 应报错')
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
@@ -122,7 +378,15 @@ if __name__ == '__main__':
|
||||
check('套打 PDF', t_render_pdf)
|
||||
check('钉钉提醒文案', t_notify_message)
|
||||
check('钉钉接收人解析', t_notify_recipients)
|
||||
check('对账匹配', t_reconcile_match)
|
||||
check('待发起过滤', t_pending_filter)
|
||||
check('新旧系统分流', t_route_pick)
|
||||
check('流程试算', t_flow_dry_run)
|
||||
check('分流登录失败', t_flow_site_error)
|
||||
check('单据头三列回填', t_billhead_fill)
|
||||
check('预支办结流程刷新', t_flow_sheet)
|
||||
check('单据头完整性校验', t_billhead_check)
|
||||
check('单子传递打印', t_sheet_print)
|
||||
print('=' * 50)
|
||||
if FAILED:
|
||||
print(f'失败 {len(FAILED)} 项')
|
||||
|
||||
@@ -42,15 +42,50 @@ DINGTALK_USER_GET_URL = 'https://oapi.dingtalk.com/user/get'
|
||||
DINGTALK_WORK_SEND_URL = 'https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2'
|
||||
|
||||
# ==================== 打印 ====================
|
||||
PRINTER_DEFAULT = '人力资源部' # l6570,支持双面;测试机用「网络信息部」l565
|
||||
PRINTER_OPTIONS = ['人力资源部', '网络信息部']
|
||||
PRINTER_DEFAULT = '人力资源部' # l6570,支持双面;测试机用「信息技术部」l565
|
||||
PRINTER_OPTIONS = ['人力资源部', '信息技术部']
|
||||
PRINT_COPIES_DEFAULT = 1
|
||||
|
||||
# ---- 第二份打印:「单子传递打印」sheet → 自绘矢量 PDF ----
|
||||
# 直接读单元格值(公式已重算落盘)、按本批已建单的行排版,不依赖 Excel/WPS 导出,
|
||||
# 交 printkit 出纸(与 ERP 单据同一台打印机),跟在「建单后套打打印」开关后面。
|
||||
SHEET_PRINT_SHEET = '单子传递打印'
|
||||
SHEET_PRINT_TPL = '单子传递打印_{n}行.pdf'
|
||||
SHEET_PRINT_TITLE = '' # 页头标题,留空不印
|
||||
|
||||
# ==================== 数据源 ====================
|
||||
LEDGER_DIR_DEFAULT = r'D:\资料\人资\预支' # 预支台账 xlsx 所在目录(取最新)
|
||||
LEDGER_KEYWORDS = ('预支', '工资预付') # 文件名关键词
|
||||
LEDGER_SHEET = '预支报酬台账'
|
||||
ORG_SHEET = '辅助2-ERP组织机构' # 同工作簿内的组织编码→名称表
|
||||
LEDGER_DIR_DEFAULT = r'D:\资料\人资\预支' # 导出临时文件/独立台账落盘目录
|
||||
LEDGER_WORKBOOK_DEFAULT = (r'D:\资料\人资\预支\1030工资预支付款申请--已付.xlsx')
|
||||
# 目标工作簿:导出数据追加到其「预支报酬台账」sheet
|
||||
LEDGER_SHEET = '预支报酬台账' # 接口导出 sheet 名(= 导出名)
|
||||
ORG_SHEET = '辅助2-ERP组织机构' # 目标工作簿内的组织编码→名称表(追加模式下可正常取映射)
|
||||
BILLHEAD_SHEET = '付款申请单#单据头(FBillHead)' # 金蝶引入模板 sheet,与台账逐行镜像(H{r}=台账!C{r})
|
||||
|
||||
# FBillHead 需按批次动态改写的三列(金蝶引入前必须填当天/默认发起人)
|
||||
BH_COL_DATE = '(单据头)申请日期'
|
||||
BH_COL_APPLICANT_NO = '(单据头)申请人#编码'
|
||||
BH_COL_APPLICANT_NAME = '(单据头)申请人#名称'
|
||||
DEFAULT_APPLICANT_STAFF = '37001090' # 默认发起人工号(HR 代提人)
|
||||
DEFAULT_APPLICANT_NAME = '刘纤'
|
||||
|
||||
# ==================== 流程详细数据(银行卡信息来源) ====================
|
||||
# FBillHead 的 AM/AN/AO = XLOOKUP(工号, 预支办结流程!O:O, V/AC/AD)
|
||||
# → 收款人 / 收款银行 / 收款账号;所以「预支办结流程」必须先整表刷新。
|
||||
FLOW_SHEET = '预支办结流程' # 目标 sheet(第 2 行表头、第 3 行起数据)
|
||||
FLOW_EXPORT_NAME = '全部流程详细数据' # HR「任务流程 → 导出全部流程详细数据」
|
||||
FLOW_TITLE = '预支' # 流程监控按标题模糊匹配
|
||||
COL_PROCESS_ID = '流程id' # 台账 AR:processId → 查 taskId
|
||||
COL_FORM_ID = '表单id' # 台账 AS:formId(= 导出 wfworkFormId)
|
||||
COL_MAIN_ID = '流程主键' # 台账 AQ:预生成主键(= 导出 main_id)
|
||||
|
||||
# ==================== 单据头完整性校验(发起前) ====================
|
||||
# D/E/F 由插件直接写入;P/R/X 与 AM/AN/AO 是公式列,必须 Excel 重算后才有值
|
||||
BH_COL_PAY_ORG = '(单据头)付款组织#名称'
|
||||
BH_COL_SETTLE_ORG = '(单据头)结算组织#名称'
|
||||
BH_COL_DEPT_NAME = '(单据头)申请部门#名称'
|
||||
BH_COL_ACCOUNT_NAME = '(付款申请单明细)对方账户名称#中文(简体)'
|
||||
BH_COL_BANK = '(付款申请单明细)对方开户行#中文(简体)'
|
||||
BH_COL_ACCOUNT_NO = '(付款申请单明细)对方银行账号(编辑)'
|
||||
|
||||
# 台账列名(第 2 行表头,数据从第 3 行起)
|
||||
COL_SEQ = '序号'
|
||||
@@ -62,8 +97,35 @@ COL_AMOUNT = '预支金额'
|
||||
COL_REASON = '预支原因'
|
||||
COL_ORG_PATH = '预支组织全路径'
|
||||
COL_DEPT_PATH = '预支五级部门'
|
||||
COL_DEPT4 = '预支四级部门' # 会馆名(FBillHead P 列取数源)
|
||||
COL_JOB_SEQ = '预支职位序列' # 用于新旧系统分流
|
||||
COL_PAY_STATUS = '付款状态'
|
||||
|
||||
# ==================== 新旧系统分流(目标工作簿 FBillHead 的 AS 列) ====================
|
||||
# AS = IF(AND(AR<>"-", AQ="否"), "旧系统", "新系统")
|
||||
# AR「服务岗参保情况」= 预支报酬台账!AW = IF(职位序列<>"门店服务序列","-",…)
|
||||
# AQ「是否标准化门店」= XLOOKUP(会馆, '辅助0-标准化门店收款账号'!B:B, F:F, "否")
|
||||
# ⇒ 旧系统 = 职位序列是「门店服务序列」且会馆不在标准化门店名单;其余新系统。
|
||||
SYSTEM_AUTO = '自动'
|
||||
SYSTEM_NEW = 'new'
|
||||
SYSTEM_OLD = 'old'
|
||||
JOB_SEQ_STORE = '门店服务序列'
|
||||
STD_STORE_SHEET = '辅助0-标准化门店收款账号' # B 列=门店名,F 列=是否标准化
|
||||
STD_STORE_MISS = '否' # XLOOKUP 查不到的默认值
|
||||
DEPT_OLD_SYSTEM = 'BM000881' # 模板 W 列:IF(AS="新系统","BM000477","BM000881")
|
||||
|
||||
# ==================== 发起前对账(ERP 已有流程 → 台账回填「已付」) ====================
|
||||
PAY_STATUS_DONE = '已付' # 对账命中后写入的状态值
|
||||
PAY_STATUS_PENDING = ('', '未付') # 待发起口径:付款状态为空 或「未付」
|
||||
ERP_VOID_STATUS = 'Z' # 作废单据不算已发起流程
|
||||
# ExecuteBillQuery 字段键(2026-11 生产实测):
|
||||
# FBJ_SQR.* 是代提人(HR/会馆负责人);FCONTACTUNIT.* 才是收款人(往来单位=员工)
|
||||
# 分录金额/收款人字段在 ExecuteBillQuery 里不可用,金额取表头 FAPPLYAMOUNTFOR_H
|
||||
ERP_QUERY_FIELDS = ('FBillNo,FDocumentStatus,FDATE,'
|
||||
'FBJ_SQR.FSTAFFNUMBER,F_VTUY_Remarks_qtr,FAPPLYAMOUNTFOR_H,'
|
||||
'FCONTACTUNIT.FNumber,FCONTACTUNIT.FName')
|
||||
RECONCILE_LOOKBACK_DAYS = 45 # 查询窗口:台账月份首日前推 45 天 → 今天
|
||||
|
||||
# ==================== 运行参数 ====================
|
||||
RETRY_MAX = 3 # 项目规范:全局重试 3 次
|
||||
TIMEOUT = 60
|
||||
|
||||
@@ -60,3 +60,46 @@ def status(client: ErpClient, number: str) -> str | None:
|
||||
rows = client.bill_query(config.FORM_ID, 'FBillNo,FDocumentStatus',
|
||||
filter_string=f"FBillNo='{number}'", limit=5)
|
||||
return rows[0][1] if rows else None
|
||||
|
||||
|
||||
def list_payapply(client: ErpClient, begin: str, end: str = '') -> list:
|
||||
"""查 FDATE 区间内的付款申请单(用于发起前对账),排除作废单。
|
||||
|
||||
Args:
|
||||
begin/end: ``YYYY-MM-DD``;end 留空=不限上界。
|
||||
|
||||
Returns:
|
||||
[{"bill_no", "status", "date", "staff", "name", "remark", "amount",
|
||||
"payee_staff", "payee_name"}]
|
||||
``staff`` 是申请人(代提人),``payee_*`` 是收款单位(真实受款员工)。
|
||||
"""
|
||||
cond = f"FDATE>='{begin}'"
|
||||
if end:
|
||||
cond += f" and FDATE<='{end}'"
|
||||
try:
|
||||
rows = client.bill_query_all(config.FORM_ID, config.ERP_QUERY_FIELDS,
|
||||
filter_string=cond, order_string='FID DESC',
|
||||
page_size=500, max_rows=5000) or []
|
||||
except ErpError as e:
|
||||
config.log(f'{TAG} 付款申请单查询失败:{e}', 'WARN')
|
||||
return []
|
||||
out = []
|
||||
for r in rows:
|
||||
if not r:
|
||||
continue
|
||||
vals = list(r) + [None] * 8
|
||||
state = str(vals[1] or '').strip().upper()
|
||||
if state == config.ERP_VOID_STATUS:
|
||||
continue
|
||||
out.append({
|
||||
'bill_no': str(vals[0] or '').strip(),
|
||||
'status': state,
|
||||
'date': str(vals[2] or '')[:10],
|
||||
'staff': str(vals[3] or '').strip(),
|
||||
'remark': str(vals[4] or '').strip(),
|
||||
'amount': float(vals[5] or 0),
|
||||
'payee_staff': str(vals[6] or '').strip(),
|
||||
'payee_name': str(vals[7] or '').strip(),
|
||||
})
|
||||
config.log(f'{TAG} {begin}~{end or "今天"} 付款申请单 {len(out)} 张(已排除作废)')
|
||||
return out
|
||||
|
||||
@@ -1,16 +1,23 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""台账数据层:读 EHR 导出的「预支台账」工作簿。
|
||||
"""台账数据层:按月份从 EHR 接口导出「预支报酬台账」,再按口径读有效行。
|
||||
|
||||
口径(2026-11-14 实测于 1030工资预支付款申请--已付.xlsx):
|
||||
- sheet「预支报酬台账」:第 2 行是表头,第 3 行起是数据,后面大量空行/公式残留;
|
||||
口径(2026-11 实测):
|
||||
- 接口导出:``hr_sdk.ledger.export_advance_pay``(预支工资/报薪台账,月份筛选
|
||||
``ext_yuzhi_month``,留空=当月),服务端生成 xlsx,sheet = 「预支报酬台账」;
|
||||
- sheet 第 2 行是表头,第 3 行起是数据(第 1 行是导出名标题);
|
||||
- 有效行:工号非空、预支金额 > 0、整行无 #N/A 类错误值;
|
||||
- 同工作簿的「辅助2-ERP组织机构」sheet(FNumber/FName)用来做 组织名称 → 编码 映射。
|
||||
- 组织编码:接口导出不含手工工作簿的「辅助2-ERP组织机构」sheet,当前统一回落
|
||||
申请组织 ``config.APPLY_ORG_ID``(后续要按会馆映射时再加映射源)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
from datetime import datetime
|
||||
import tempfile
|
||||
import zipfile
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
import openpyxl
|
||||
|
||||
@@ -35,19 +42,34 @@ def _num(v):
|
||||
return 0.0
|
||||
|
||||
|
||||
def find_latest_ledger(work_dir: str = '') -> str:
|
||||
"""取目录下最新的预支台账 xlsx(文件名含关键词,忽略临时文件)。"""
|
||||
work_dir = work_dir or config.LEDGER_DIR_DEFAULT
|
||||
cands = []
|
||||
for name in os.listdir(work_dir):
|
||||
if not name.lower().endswith(('.xlsx', '.xlsm')) or name.startswith('~$'):
|
||||
continue
|
||||
if any(k in name for k in config.LEDGER_KEYWORDS):
|
||||
cands.append(os.path.join(work_dir, name))
|
||||
if not cands:
|
||||
raise FileNotFoundError(f'{work_dir} 下没有找到预支台账 xlsx(关键词:{config.LEDGER_KEYWORDS})')
|
||||
cands.sort(key=lambda p: os.path.getmtime(p), reverse=True)
|
||||
return cands[0]
|
||||
def normalize_month(month: str = '') -> str:
|
||||
"""台账月份归一为 YYYYMM;留空=当月。"""
|
||||
text = re.sub(r'\D', '', str(month or ''))
|
||||
if not text:
|
||||
return datetime.now().strftime('%Y%m')
|
||||
if len(text) != 6:
|
||||
raise ValueError(f'月份格式不对:{month!r}(应为 YYYYMM 或 YYYY-MM)')
|
||||
return text
|
||||
|
||||
|
||||
def export_month(session, work_dir: str = '', month: str = '', timeout: int = 300) -> str:
|
||||
"""按月份从 EHR 接口导出预支台账,返回落盘路径(同月份文件覆盖重导)。
|
||||
|
||||
Args:
|
||||
session: 底座注入的 HR 登录态(``ctx.get_session("hr")``)
|
||||
work_dir: 落盘目录;留空=``config.LEDGER_DIR_DEFAULT``
|
||||
month: YYYYMM / YYYY-MM;留空=当月
|
||||
timeout: 等待服务端生成文件的上限(秒)
|
||||
"""
|
||||
from hr_sdk import HrClient, ledger as hr_ledger # SDK 下发,插件内懒加载
|
||||
|
||||
ym = normalize_month(month)
|
||||
out_dir = work_dir or config.LEDGER_DIR_DEFAULT
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
target = os.path.join(out_dir, f'预支报酬台账_{ym}.xlsx')
|
||||
hr_ledger.export_advance_pay(HrClient(session, log=config.log, timeout=config.TIMEOUT),
|
||||
month=ym, output=target, timeout=timeout)
|
||||
return target
|
||||
|
||||
|
||||
def load_org_map(path: str) -> dict:
|
||||
@@ -67,8 +89,243 @@ def load_org_map(path: str) -> dict:
|
||||
wb.close()
|
||||
|
||||
|
||||
def read_rows(path: str) -> list:
|
||||
"""读台账有效数据行,返回行字典列表(键见 config.COL_*)。"""
|
||||
def load_std_stores(path: str) -> dict:
|
||||
"""会馆名 → 是否标准化门店(辅助0 表:B 列门店名、F 列是否标准化)。
|
||||
|
||||
口径对齐 FBillHead 的 ``XLOOKUP(会馆, B:B, F:F, "否")``:查不到即按「否」。
|
||||
"""
|
||||
wb = openpyxl.load_workbook(path, data_only=True, read_only=True)
|
||||
try:
|
||||
if config.STD_STORE_SHEET not in wb.sheetnames:
|
||||
return {}
|
||||
ws = wb[config.STD_STORE_SHEET]
|
||||
out = {}
|
||||
for row in ws.iter_rows(min_row=2, values_only=True):
|
||||
name = _s(row[1] if len(row) > 1 else '')
|
||||
if name:
|
||||
out[name] = _s(row[5] if len(row) > 5 else '')
|
||||
return out
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
|
||||
def _header_map(ws) -> dict:
|
||||
"""第 2 行表头 → 0 基列号。"""
|
||||
out = {}
|
||||
for idx, cell in enumerate(next(ws.iter_rows(min_row=2, max_row=2, values_only=True)), 1):
|
||||
name = _s(cell)
|
||||
if name:
|
||||
out[name] = idx - 1
|
||||
return out
|
||||
|
||||
|
||||
def _row_key(staff, month, amount, when) -> tuple:
|
||||
"""查重键:工号 + 预支报酬年月 + 金额 + 提报日期。"""
|
||||
return (_s(staff), _s(month), _num(amount), _s(when))
|
||||
|
||||
|
||||
_CELL_RE = re.compile(r'<c r="([A-Z]+[0-9]+)"[^>]*(?<!/)>.*?</c>', re.S)
|
||||
|
||||
|
||||
def _sheet_parts(path: str) -> dict:
|
||||
"""sheet 名 → xlsx 内部 worksheet xml 路径。"""
|
||||
with zipfile.ZipFile(path) as z:
|
||||
wb = z.read("xl/workbook.xml").decode("utf-8")
|
||||
rels = z.read("xl/_rels/workbook.xml.rels").decode("utf-8")
|
||||
targets = {}
|
||||
for tag in re.findall(r"<Relationship [^>]*/>", rels):
|
||||
rid = re.search(r'Id="([^"]+)"', tag)
|
||||
tgt = re.search(r'Target="([^"]+)"', tag)
|
||||
if rid and tgt:
|
||||
targets[rid.group(1)] = tgt.group(1)
|
||||
out = {}
|
||||
for tag in re.findall(r"<sheet [^>]*/>", wb):
|
||||
name = re.search(r'name="([^"]+)"', tag).group(1)
|
||||
rid = re.search(r'r:id="(rId\d+)"', tag).group(1)
|
||||
target = targets[rid]
|
||||
out[name] = target.lstrip("/") if target.startswith("/") else "xl/" + target
|
||||
return out
|
||||
|
||||
|
||||
def _formula_cached_values(path: str) -> dict:
|
||||
"""提取公式单元格的缓存值(openpyxl 另存会丢,需要原样搬回)。"""
|
||||
cached = {}
|
||||
with zipfile.ZipFile(path) as z:
|
||||
for part in _sheet_parts(path).values():
|
||||
xml = z.read(part).decode("utf-8")
|
||||
hits = {}
|
||||
for m in _CELL_RE.finditer(xml):
|
||||
body = m.group(0)
|
||||
if "<f>" not in body:
|
||||
continue
|
||||
v = re.search(r"<v(?P<attr>[^>]*)>(?P<val>[^<]*)</v>", body)
|
||||
if v and v.group("val"):
|
||||
hits[m.group(1)] = body
|
||||
if hits:
|
||||
cached[part] = hits
|
||||
return cached
|
||||
|
||||
|
||||
def _norm_formula(text: str) -> str:
|
||||
"""公式归一(解实体、去空白),用于判断另存前后公式是否一致。"""
|
||||
return re.sub(r'\s+', '', html.unescape(text))
|
||||
|
||||
|
||||
def _restore_cached_values(cached: dict, path: str) -> None:
|
||||
"""把原工作簿公式缓存值写回另存后的文件(公式不变时整格替换)。"""
|
||||
with zipfile.ZipFile(path) as z:
|
||||
parts = {n: z.read(n) for n in z.namelist()}
|
||||
changed = False
|
||||
for part, hits in cached.items():
|
||||
if part not in parts:
|
||||
continue
|
||||
xml = parts[part].decode("utf-8")
|
||||
|
||||
def repl(m):
|
||||
old = hits.get(m.group(1))
|
||||
body = m.group(0)
|
||||
if not old or re.search(r"<v[^>]*>[^<]+</v>", body):
|
||||
return body
|
||||
f_new = re.search(r"<f>(.*?)</f>", body, re.S)
|
||||
f_old = re.search(r"<f>(.*?)</f>", old, re.S)
|
||||
same = (f_new and f_old
|
||||
and _norm_formula(f_new.group(1)) == _norm_formula(f_old.group(1)))
|
||||
return old if same else body
|
||||
|
||||
new_xml = _CELL_RE.sub(repl, xml)
|
||||
if new_xml != xml:
|
||||
parts[part] = new_xml.encode("utf-8")
|
||||
changed = True
|
||||
if not changed:
|
||||
return
|
||||
tmp = path + ".restore"
|
||||
with zipfile.ZipFile(tmp, "w", zipfile.ZIP_DEFLATED) as zout:
|
||||
for name, data in parts.items():
|
||||
zout.writestr(name, data)
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def _save_workbook(wb, path: str) -> None:
|
||||
"""同目录临时文件 + 原子替换保存,并搬回公式缓存值(openpyxl 另存会丢)。"""
|
||||
tmp = path + '.tmp'
|
||||
cached = _formula_cached_values(path)
|
||||
try:
|
||||
wb.save(tmp)
|
||||
_restore_cached_values(cached, tmp)
|
||||
os.replace(tmp, path)
|
||||
except PermissionError as e:
|
||||
wb.close()
|
||||
if os.path.exists(tmp):
|
||||
os.remove(tmp)
|
||||
raise ValueError(f'工作簿被占用(请先关闭 Excel/WPS):{path}') from e
|
||||
except Exception:
|
||||
wb.close()
|
||||
if os.path.exists(tmp):
|
||||
os.remove(tmp)
|
||||
raise
|
||||
|
||||
|
||||
def append_month(session, workbook_path: str, month: str = '', export_dir: str = '',
|
||||
timeout: int = 300) -> dict:
|
||||
"""导出指定月份(默认当月)台账,追加到目标工作簿「预支报酬台账」sheet。
|
||||
|
||||
- 按第 2 行表头名称逐列对齐写入,模板里 A 序号与 AT~AW 等公式列原样保留;
|
||||
- 已有同键(工号+年月+金额+提报日期)的行自动跳过,可反复执行;
|
||||
- 写回采用「同目录临时文件 + 原子替换」,避免半截文件;工作簿被 Excel/WPS 占用时明确报错。
|
||||
|
||||
Returns:
|
||||
{"path": 工作簿路径, "month": YYYYMM, "added": 新增行数,
|
||||
"skipped": 重复跳过行数, "exported": 导出文件路径}
|
||||
"""
|
||||
ym = normalize_month(month)
|
||||
export_dir = export_dir or os.path.join(tempfile.gettempdir(), '37du_xq0012')
|
||||
exported = export_month(session, export_dir, ym, timeout=timeout)
|
||||
|
||||
src_wb = openpyxl.load_workbook(exported, data_only=True)
|
||||
src_ws = src_wb[config.LEDGER_SHEET]
|
||||
src_hdr = _header_map(src_ws)
|
||||
src_rows = []
|
||||
staff_idx = src_hdr.get(config.COL_STAFF)
|
||||
if staff_idx is None:
|
||||
raise ValueError(f'导出文件缺少列「{config.COL_STAFF}」')
|
||||
for raw in src_ws.iter_rows(min_row=3, values_only=True):
|
||||
if not raw or not _s(raw[staff_idx]):
|
||||
continue
|
||||
if any(ERR_RE.match(_s(v)) for v in raw):
|
||||
continue
|
||||
vals = {name: raw[i] for name, i in src_hdr.items() if i < len(raw)}
|
||||
if _num(vals.get(config.COL_AMOUNT)) <= 0:
|
||||
continue
|
||||
src_rows.append(vals)
|
||||
src_wb.close()
|
||||
|
||||
wb = openpyxl.load_workbook(workbook_path, data_only=False)
|
||||
if config.LEDGER_SHEET not in wb.sheetnames:
|
||||
raise ValueError(f'{workbook_path} 缺少 sheet「{config.LEDGER_SHEET}」')
|
||||
ws = wb[config.LEDGER_SHEET]
|
||||
tgt_hdr = _header_map(ws)
|
||||
for need in (config.COL_STAFF, config.COL_MONTH, config.COL_AMOUNT, config.COL_DATE):
|
||||
if need not in tgt_hdr:
|
||||
raise ValueError(f'「{config.LEDGER_SHEET}」第 2 行缺少列「{need}」')
|
||||
|
||||
def cell_get(r, name):
|
||||
i = tgt_hdr.get(name)
|
||||
return ws.cell(row=r, column=i + 1).value if i is not None else None
|
||||
|
||||
existing = set()
|
||||
next_row = None
|
||||
last_seq = 0
|
||||
for r in range(3, ws.max_row + 1):
|
||||
staff = cell_get(r, config.COL_STAFF)
|
||||
if staff not in (None, ''):
|
||||
existing.add(_row_key(staff, cell_get(r, config.COL_MONTH),
|
||||
cell_get(r, config.COL_AMOUNT), cell_get(r, config.COL_DATE)))
|
||||
seq = _num(cell_get(r, config.COL_SEQ))
|
||||
last_seq = max(last_seq, int(seq))
|
||||
elif next_row is None:
|
||||
next_row = r # 模板里第一条空行(序号/公式已预置)
|
||||
if next_row is None:
|
||||
next_row = ws.max_row + 1
|
||||
|
||||
added = skipped = 0
|
||||
overflow = 0
|
||||
for vals in src_rows:
|
||||
key = _row_key(vals.get(config.COL_STAFF), vals.get(config.COL_MONTH),
|
||||
vals.get(config.COL_AMOUNT), vals.get(config.COL_DATE))
|
||||
if key in existing:
|
||||
skipped += 1
|
||||
continue
|
||||
if next_row > ws.max_row:
|
||||
overflow += 1 # 超出模板预置行:照常写入,公式列需人工补
|
||||
for name, i in tgt_hdr.items():
|
||||
if name == config.COL_SEQ: # 模板已预置序号,保留原编号
|
||||
continue
|
||||
if name in vals:
|
||||
ws.cell(row=next_row, column=i + 1).value = vals[name]
|
||||
if ws.cell(row=next_row, column=tgt_hdr[config.COL_SEQ] + 1).value in (None, ''):
|
||||
last_seq += 1
|
||||
ws.cell(row=next_row, column=tgt_hdr[config.COL_SEQ] + 1).value = str(last_seq)
|
||||
existing.add(key)
|
||||
added += 1
|
||||
next_row += 1
|
||||
|
||||
_save_workbook(wb, workbook_path)
|
||||
wb.close()
|
||||
return {'path': workbook_path, 'month': ym, 'added': added,
|
||||
'skipped': skipped, 'overflow': overflow, 'exported': exported}
|
||||
|
||||
|
||||
def is_pending(row: dict) -> bool:
|
||||
"""待发起口径:付款状态为空 或「未付」。"""
|
||||
return _s(row.get('pay_status')) in config.PAY_STATUS_PENDING
|
||||
|
||||
|
||||
def read_rows(path: str, month: str = '', pending_only: bool = False) -> list:
|
||||
"""读台账有效数据行,返回行字典列表(键见 config.COL_*)。
|
||||
|
||||
``month`` 非空时只看该月;``pending_only=True`` 时只返回付款状态为空/「未付」的行。
|
||||
"""
|
||||
ym = re.sub(r'\D', '', str(month or ''))
|
||||
wb = openpyxl.load_workbook(path, data_only=True)
|
||||
if config.LEDGER_SHEET not in wb.sheetnames:
|
||||
raise ValueError(f'{path} 缺少 sheet「{config.LEDGER_SHEET}」')
|
||||
@@ -79,7 +336,7 @@ def read_rows(path: str) -> list:
|
||||
if name:
|
||||
header[name] = idx - 1
|
||||
rows = []
|
||||
for raw in ws.iter_rows(min_row=3, values_only=True):
|
||||
for r, raw in enumerate(ws.iter_rows(min_row=3, values_only=True), start=3):
|
||||
if not raw:
|
||||
continue
|
||||
def get(col):
|
||||
@@ -90,7 +347,8 @@ def read_rows(path: str) -> list:
|
||||
continue
|
||||
if any(ERR_RE.match(_s(v)) for v in raw):
|
||||
continue
|
||||
rows.append({
|
||||
row = {
|
||||
'row': r,
|
||||
'seq': _s(get(config.COL_SEQ)),
|
||||
'month': _s(get(config.COL_MONTH)),
|
||||
'staff': staff,
|
||||
@@ -100,12 +358,116 @@ def read_rows(path: str) -> list:
|
||||
'reason': _s(get(config.COL_REASON)),
|
||||
'org_path': _s(get(config.COL_ORG_PATH)),
|
||||
'dept': _s(get(config.COL_DEPT_PATH)),
|
||||
'dept4': _s(get(config.COL_DEPT4)),
|
||||
'job_seq': _s(get(config.COL_JOB_SEQ)),
|
||||
'pay_status': _s(get(config.COL_PAY_STATUS)),
|
||||
})
|
||||
'process_id': _s(get(config.COL_PROCESS_ID)),
|
||||
'form_id': _s(get(config.COL_FORM_ID)),
|
||||
'main_id': _s(get(config.COL_MAIN_ID)),
|
||||
}
|
||||
if ym and row['month'] != ym:
|
||||
continue
|
||||
if pending_only and not is_pending(row):
|
||||
continue
|
||||
rows.append(row)
|
||||
wb.close()
|
||||
return rows
|
||||
|
||||
|
||||
def update_pay_status(path: str, marks: list) -> int:
|
||||
"""把台账中与 marks 匹配的行付款状态改为「已付」,返回实际更新行数。
|
||||
|
||||
marks 项:``{"staff", "month", "amount", "date", "bill_no"}``;按
|
||||
工号+预支年月+金额+提报日期 定位,同键多行一对一消费(只标最早一条未标行),
|
||||
已标「已付」的行跳过,可反复执行。
|
||||
"""
|
||||
if not marks:
|
||||
return 0
|
||||
wb = openpyxl.load_workbook(path, data_only=False)
|
||||
if config.LEDGER_SHEET not in wb.sheetnames:
|
||||
wb.close()
|
||||
raise ValueError(f'{path} 缺少 sheet「{config.LEDGER_SHEET}」')
|
||||
ws = wb[config.LEDGER_SHEET]
|
||||
header = _header_map(ws)
|
||||
status_idx = header.get(config.COL_PAY_STATUS)
|
||||
if status_idx is None:
|
||||
wb.close()
|
||||
raise ValueError(f'「{config.LEDGER_SHEET}」缺少列「{config.COL_PAY_STATUS}」')
|
||||
|
||||
def cell_get(r, name):
|
||||
i = header.get(name)
|
||||
return ws.cell(row=r, column=i + 1).value if i is not None else None
|
||||
|
||||
buckets = {}
|
||||
for r in range(3, ws.max_row + 1):
|
||||
if cell_get(r, config.COL_STAFF) in (None, ''):
|
||||
continue
|
||||
if _s(ws.cell(row=r, column=status_idx + 1).value) == config.PAY_STATUS_DONE:
|
||||
continue
|
||||
key = _row_key(cell_get(r, config.COL_STAFF), cell_get(r, config.COL_MONTH),
|
||||
cell_get(r, config.COL_AMOUNT), cell_get(r, config.COL_DATE))
|
||||
buckets.setdefault(key, []).append(r)
|
||||
|
||||
changed = 0
|
||||
for m in marks:
|
||||
key = _row_key(m.get('staff'), m.get('month'), m.get('amount'), m.get('date'))
|
||||
pending_rows = buckets.get(key)
|
||||
if not pending_rows:
|
||||
continue
|
||||
r = pending_rows.pop(0)
|
||||
ws.cell(row=r, column=status_idx + 1).value = config.PAY_STATUS_DONE
|
||||
changed += 1
|
||||
if changed:
|
||||
_save_workbook(wb, path)
|
||||
wb.close()
|
||||
return changed
|
||||
|
||||
|
||||
def fill_billhead(path: str, rows: list, apply_date, staff: str, name: str) -> int:
|
||||
"""把待发起行回填到 FBillHead 的三列(申请日期 / 申请人#编码 / 申请人#名称)。
|
||||
|
||||
FBillHead 与台账逐行镜像(``H{r} = 预支报酬台账!C{r}``),所以按台账物理行号写同一行;
|
||||
超出模板预置行(或工作簿缺该 sheet)直接跳过,返回实际写入行数。
|
||||
"""
|
||||
if not rows:
|
||||
return 0
|
||||
wb = openpyxl.load_workbook(path, data_only=False)
|
||||
try:
|
||||
if config.BILLHEAD_SHEET not in wb.sheetnames:
|
||||
wb.close()
|
||||
return 0
|
||||
ws = wb[config.BILLHEAD_SHEET]
|
||||
header = _header_map(ws)
|
||||
|
||||
def col_of(name: str) -> int:
|
||||
if name in header: # 表头可能带必录星号「*(单据头)申请日期」
|
||||
return header[name] + 1
|
||||
for key, idx in header.items():
|
||||
if str(key).lstrip('*').strip() == name:
|
||||
return idx + 1
|
||||
raise ValueError(f'「{config.BILLHEAD_SHEET}」第 2 行缺少列「{name}」')
|
||||
|
||||
cols = {key: col_of(key) for key in (
|
||||
config.BH_COL_DATE, config.BH_COL_APPLICANT_NO, config.BH_COL_APPLICANT_NAME)}
|
||||
when = datetime.combine(apply_date, datetime.min.time())
|
||||
changed = 0
|
||||
for row in rows:
|
||||
r = int(row.get('row') or 0)
|
||||
if r < 3 or r > ws.max_row:
|
||||
continue
|
||||
ws.cell(row=r, column=cols[config.BH_COL_DATE]).value = when
|
||||
ws.cell(row=r, column=cols[config.BH_COL_APPLICANT_NO]).value = staff
|
||||
ws.cell(row=r, column=cols[config.BH_COL_APPLICANT_NAME]).value = name
|
||||
changed += 1
|
||||
if changed:
|
||||
_save_workbook(wb, path)
|
||||
wb.close()
|
||||
return changed
|
||||
except Exception:
|
||||
wb.close()
|
||||
raise
|
||||
|
||||
|
||||
def guess_org_code(row: dict, org_map: dict) -> str:
|
||||
"""从「预支组织全路径」推断付款组织编码(会馆级优先,其次公司级)。"""
|
||||
path = str(row.get('org_path') or '')
|
||||
@@ -115,3 +477,234 @@ def guess_org_code(row: dict, org_map: dict) -> str:
|
||||
if p and p in org_map:
|
||||
return org_map[p]
|
||||
return config.APPLY_ORG_ID
|
||||
|
||||
|
||||
# ==================== 预支办结流程(全部流程详细数据) ====================
|
||||
|
||||
def _read_export(path: str):
|
||||
"""读导出文件 → (表头列表, 行字典列表)。服务端实际是 xlsx(扩展名给 .xls)。"""
|
||||
with open(path, 'rb') as fp:
|
||||
wb = openpyxl.load_workbook(io.BytesIO(fp.read()), data_only=True)
|
||||
try:
|
||||
ws = wb[wb.sheetnames[0]]
|
||||
header = [_s(c) for c in next(ws.iter_rows(min_row=2, max_row=2, values_only=True))]
|
||||
rows = []
|
||||
for raw in ws.iter_rows(min_row=3, values_only=True):
|
||||
if not raw or not any(_s(v) for v in raw):
|
||||
continue
|
||||
rows.append({name: raw[i] for i, name in enumerate(header)
|
||||
if name and i < len(raw)})
|
||||
return header, rows
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
|
||||
def write_flow_sheet(path: str, header: list, data_rows: list) -> int:
|
||||
"""整表覆盖「预支办结流程」:清空第 3 行起旧数据,按表头名写入导出结果。
|
||||
|
||||
Returns: 写入行数;工作簿缺该 sheet 时返回 0。
|
||||
"""
|
||||
wb = openpyxl.load_workbook(path, data_only=False)
|
||||
try:
|
||||
if config.FLOW_SHEET not in wb.sheetnames:
|
||||
return 0
|
||||
ws = wb[config.FLOW_SHEET]
|
||||
tgt = _header_map(ws)
|
||||
cols = {name: tgt[name] + 1 for name in header if name in tgt}
|
||||
if not cols:
|
||||
raise ValueError(f'「{config.FLOW_SHEET}」第 2 行表头与导出列不匹配')
|
||||
max_col = ws.max_column
|
||||
for r in range(3, ws.max_row + 1):
|
||||
for c in range(1, max_col + 1):
|
||||
ws.cell(row=r, column=c).value = None
|
||||
r = 3
|
||||
for vals in data_rows:
|
||||
for name, col in cols.items():
|
||||
if name in vals:
|
||||
ws.cell(row=r, column=col).value = vals[name]
|
||||
r += 1
|
||||
# Excel 打开时强制重算(AM/AN/AO 的 XLOOKUP 才会刷新银行卡)
|
||||
wb.calculation.fullCalcOnLoad = True
|
||||
_save_workbook(wb, path)
|
||||
return len(data_rows)
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
|
||||
def month_range(month: str = '') -> tuple:
|
||||
"""YYYYMM / YYYY-MM → (当月首日, 当月末日),ISO 字符串。"""
|
||||
ym = normalize_month(month)
|
||||
first = date(int(ym[:4]), int(ym[4:]), 1)
|
||||
nxt = date(first.year + (first.month == 12), first.month % 12 + 1, 1)
|
||||
return first.isoformat(), (nxt - timedelta(days=1)).isoformat()
|
||||
|
||||
|
||||
#: 单次导出的 taskId 上限(按表单批量导,过多容易触发服务端超时)
|
||||
FLOW_EXPORT_BATCH = 50
|
||||
|
||||
|
||||
def refresh_flow_sheet(session, workbook_path: str, month: str = '', work_dir: str = '',
|
||||
timeout: int = 180) -> dict:
|
||||
"""按月份扫描「流程监控 → 全部流程(已办结)」,整表覆盖「预支办结流程」。
|
||||
|
||||
链路:supervise 接口按月+标题取 processId → ``workflow.task_ids`` 取首条 taskId
|
||||
(表单数据是进程级,取一条即可)→ 按 formId 分组 ``workflow.export_detail`` 异步导出
|
||||
→ 按表头名从第 3 行起覆盖写入。
|
||||
|
||||
与台账行无关:只要本月有已办结预支流程就整表重刷,覆盖后已付行也查得到收款信息。
|
||||
|
||||
Returns:
|
||||
``{"written": 写入行数, "flows": 已办结流程数, "skipped": [无 taskId 的流程],
|
||||
"exported": [文件路径], "reason": 未刷新原因}``
|
||||
"""
|
||||
wb = openpyxl.load_workbook(workbook_path, read_only=True)
|
||||
try:
|
||||
if config.FLOW_SHEET not in wb.sheetnames:
|
||||
return {'written': 0, 'flows': 0, 'skipped': [], 'exported': [],
|
||||
'reason': f'工作簿缺少 sheet「{config.FLOW_SHEET}」'}
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
from hr_sdk import HrClient, workflow # SDK 下发,插件内懒加载
|
||||
|
||||
client = HrClient(session, log=config.log, timeout=config.TIMEOUT)
|
||||
begin, end = month_range(month)
|
||||
flows = workflow.list_supervised(client, title=config.FLOW_TITLE, begin_date=begin,
|
||||
end_date=end, current_state='COMPLETED')
|
||||
if not flows:
|
||||
return {'written': 0, 'flows': 0, 'skipped': [], 'exported': [],
|
||||
'reason': f'{begin}~{end} 无已办结的「{config.FLOW_TITLE}」流程(保留原表)'}
|
||||
config.log(f'[流程] {begin}~{end} 已办结「{config.FLOW_TITLE}」流程 {len(flows)} 条', 'DEBUG')
|
||||
|
||||
out_dir = work_dir or os.path.join(tempfile.gettempdir(), '37du_xq0012')
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
|
||||
groups, skipped = {}, [] # 表单id → [taskId]
|
||||
for flow in flows:
|
||||
fid = _s(flow.get('formId'))
|
||||
got = workflow.task_ids(client, flow.get('processId')) if fid else []
|
||||
if not got:
|
||||
skipped.append(flow)
|
||||
continue
|
||||
groups.setdefault(fid, []).append(got[0])
|
||||
|
||||
header, data_rows, exported = [], [], []
|
||||
for fid, tids in groups.items():
|
||||
info = workflow.form_info(client, fid)
|
||||
for i in range(0, len(tids), FLOW_EXPORT_BATCH):
|
||||
chunk = tids[i:i + FLOW_EXPORT_BATCH]
|
||||
target = os.path.join(
|
||||
out_dir, f'{config.FLOW_EXPORT_NAME}_{fid[:8]}_{i // FLOW_EXPORT_BATCH + 1}.xls')
|
||||
exported.append(workflow.export_detail(
|
||||
client, task_ids=chunk, table=info['table'], wfwork_form_id=fid,
|
||||
pk=info['pk'], output_path=target, title_name=config.FLOW_EXPORT_NAME,
|
||||
timeout=timeout))
|
||||
head, got_rows = _read_export(target)
|
||||
header = header or head
|
||||
data_rows.extend(got_rows)
|
||||
config.log(f'[流程] 表单「{info["name"] or fid}」导出 {len(tids)} 条任务', 'DEBUG')
|
||||
|
||||
if not data_rows:
|
||||
return {'written': 0, 'flows': len(flows), 'skipped': skipped,
|
||||
'exported': exported, 'reason': '导出结果为空(保留原表)'}
|
||||
written = write_flow_sheet(workbook_path, header, data_rows)
|
||||
return {'written': written, 'flows': len(flows), 'skipped': skipped,
|
||||
'exported': exported, 'reason': ''}
|
||||
|
||||
|
||||
def recalc_with_excel(path: str) -> bool:
|
||||
"""用本机 Excel 全量重算并保存(把公式结果落成缓存值),失败返回 False。
|
||||
|
||||
openpyxl 写回的公式没有缓存值;不重算则 ``data_only=True`` 读到 None,
|
||||
AM/AN/AO 的银行卡与 P/R/X 的组织名都会误判为缺失。
|
||||
"""
|
||||
try:
|
||||
import win32com.client as win32 # pywin32,执行机未必装
|
||||
except ImportError:
|
||||
config.log('[重算] 未安装 pywin32,跳过 Excel 重算(打开工作簿时仍会自动重算)', 'WARN')
|
||||
return False
|
||||
excel = book = None
|
||||
try:
|
||||
excel = win32.DispatchEx('Excel.Application')
|
||||
excel.Visible = False
|
||||
excel.DisplayAlerts = False
|
||||
book = excel.Workbooks.Open(os.path.abspath(path), UpdateLinks=0)
|
||||
excel.CalculateFullRebuild()
|
||||
book.Save()
|
||||
return True
|
||||
except Exception as e: # noqa: BLE001
|
||||
config.log(f'[重算] Excel 重算失败(不影响建单):{e}', 'WARN')
|
||||
return False
|
||||
finally:
|
||||
if book is not None:
|
||||
try:
|
||||
book.Close(SaveChanges=False)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
if excel is not None:
|
||||
try:
|
||||
excel.Quit()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
|
||||
#: 发起前必录校验:(表头名, 报告用短名, 是否公式列)
|
||||
_BILLHEAD_REQUIRED = (
|
||||
(config.BH_COL_DATE, '申请日期', False),
|
||||
(config.BH_COL_APPLICANT_NO, '申请人编码', False),
|
||||
(config.BH_COL_APPLICANT_NAME, '申请人名称', False),
|
||||
(config.BH_COL_PAY_ORG, '付款组织', True),
|
||||
(config.BH_COL_SETTLE_ORG, '结算组织', True),
|
||||
(config.BH_COL_DEPT_NAME, '申请部门', True),
|
||||
(config.BH_COL_ACCOUNT_NAME, '对方账户名称', True),
|
||||
(config.BH_COL_BANK, '对方开户行', True),
|
||||
(config.BH_COL_ACCOUNT_NO, '对方银行账号', True),
|
||||
)
|
||||
|
||||
|
||||
def check_billhead(path: str, rows: list, formula_cols: bool = True) -> dict:
|
||||
"""校验 FBillHead 待发起行的必录信息(含银行卡)是否齐全。
|
||||
|
||||
``formula_cols=False`` 时只校验插件直接写入的 D/E/F —— 没做 Excel 重算时
|
||||
公式列缓存值不可信,不能据此丢行。
|
||||
|
||||
Returns:
|
||||
``{"checked": 校验行数, "ok": [通过行],
|
||||
"missing": [{"row","seq","staff","name","fields": [缺失列短名]}]}``
|
||||
"""
|
||||
wb = openpyxl.load_workbook(path, data_only=True)
|
||||
try:
|
||||
if config.BILLHEAD_SHEET not in wb.sheetnames:
|
||||
raise ValueError(f'{path} 缺少 sheet「{config.BILLHEAD_SHEET}」')
|
||||
ws = wb[config.BILLHEAD_SHEET]
|
||||
header = _header_map(ws)
|
||||
cols = {}
|
||||
for name, label, need_formula in _BILLHEAD_REQUIRED:
|
||||
if need_formula and not formula_cols:
|
||||
continue
|
||||
idx = header.get(name)
|
||||
if idx is None:
|
||||
for key, i in header.items():
|
||||
if str(key).lstrip('*').strip() == name:
|
||||
idx = i
|
||||
break
|
||||
if idx is None:
|
||||
raise ValueError(f'「{config.BILLHEAD_SHEET}」第 2 行缺少列「{name}」')
|
||||
cols[label] = idx + 1
|
||||
|
||||
ok_rows, missing = [], []
|
||||
for row in rows:
|
||||
r = int(row.get('row') or 0)
|
||||
if r < 3 or r > ws.max_row:
|
||||
bad = ['超出模板预置行']
|
||||
else:
|
||||
bad = [label for label, col in cols.items()
|
||||
if not _s(ws.cell(row=r, column=col).value)]
|
||||
if bad:
|
||||
missing.append({'row': r, 'seq': row.get('seq'), 'staff': row.get('staff'),
|
||||
'name': row.get('name'), 'fields': bad})
|
||||
else:
|
||||
ok_rows.append(row)
|
||||
return {'checked': len(rows), 'ok': ok_rows, 'missing': missing}
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""流程编排:台账行 → 组装 → 查重 → 建单 →(提交)→ 套打 PDF →(打印)。
|
||||
"""流程编排:台账行 → 组装 → 查重 → 建单 →(提交)→ 套打 PDF →(打印)→ 传递单。
|
||||
|
||||
打印有两份(共用「建单后打印(ERP 单据 + 传递单)」一个开关):
|
||||
1. ERP 单据:逐张 ``client.view()`` → 自绘套打 PDF → printkit 出纸;
|
||||
2. Excel「单子传递打印」:本批已建单的行直接读值 → 自绘矢量 PDF → printkit 出纸。
|
||||
|
||||
安全默认:`dry_run=True` 时**不写 ERP**,只把将要提交的 Model 与校验结果打出来;
|
||||
`submit=False` 时只建草稿(A 状态),由 HR 在 ERP 里确认后再提交。
|
||||
@@ -12,7 +16,7 @@ from datetime import date, datetime
|
||||
from .. import config
|
||||
from ..data import erp as erp_mod
|
||||
from ..data import ledger
|
||||
from . import payload
|
||||
from . import payload, route
|
||||
from ..report import payapply_pdf
|
||||
|
||||
|
||||
@@ -22,27 +26,46 @@ def _venue(row: dict) -> str:
|
||||
return parts[-1].strip() if parts else ''
|
||||
|
||||
|
||||
def run_flow(*, rows_data: list, org_map: dict, client=None,
|
||||
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 = '') -> dict:
|
||||
"""执行整批,返回 {summary, detail, path}。"""
|
||||
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)
|
||||
item = {'seq': row.get('seq'), 'staff': row['staff'], 'name': row['name'],
|
||||
'amount': row['amount'], 'org': org_code, 'venue': venue, 'status': ''}
|
||||
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_code,
|
||||
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
|
||||
@@ -109,11 +132,33 @@ def run_flow(*, rows_data: list, org_map: dict, client=None,
|
||||
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}
|
||||
'printed': printed_items, 'print_failed': print_failed, 'printer': printer,
|
||||
'sheet_print': sheet_print}
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
# -*- 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()
|
||||
@@ -0,0 +1,35 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""新旧系统分流:按目标工作簿 FBillHead sheet 的 AS 列口径判定走哪个 ERP。
|
||||
|
||||
AS(行 3 起同构):
|
||||
|
||||
=IF(AND(AR3<>"-", AQ3="否"), "旧系统", "新系统")
|
||||
AR「服务岗参保情况」= 预支报酬台账!AW
|
||||
= IF(职位序列<>"门店服务序列","-", IF(参保…,"服务岗未参保"/"服务岗已参保"))
|
||||
⇒ 职位序列不是「门店服务序列」时恒为 "-"
|
||||
AQ「是否标准化门店」= XLOOKUP(会馆, '辅助0-标准化门店收款账号'!B:B, F:F, "否")
|
||||
|
||||
⇒ **旧系统** = 职位序列为「门店服务序列」且会馆不是标准化门店;其余一律新系统。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def pick(row: dict, std_stores: dict) -> str:
|
||||
"""判定该行走哪个 ERP,返回 ``config.SYSTEM_NEW`` / ``config.SYSTEM_OLD``。"""
|
||||
if str(row.get('job_seq') or '').strip() != config.JOB_SEQ_STORE:
|
||||
return config.SYSTEM_NEW # AR = "-"
|
||||
venue = str(row.get('dept4') or '').strip()
|
||||
flag = str((std_stores or {}).get(venue, config.STD_STORE_MISS)).strip()
|
||||
return config.SYSTEM_OLD if flag == config.STD_STORE_MISS else config.SYSTEM_NEW
|
||||
|
||||
|
||||
def label(site: str) -> str:
|
||||
"""站点键 → 中文标签(日志/结果展示用)。"""
|
||||
return '旧系统' if site == config.SYSTEM_OLD else '新系统'
|
||||
|
||||
|
||||
def dept_for(site: str, new_dept: str) -> str:
|
||||
"""申请部门跟系统走:旧系统 BM000881,新系统用传入的部门(默认 BM000477)。"""
|
||||
return config.DEPT_OLD_SYSTEM if site == config.SYSTEM_OLD else new_dept
|
||||
@@ -2,15 +2,18 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0012",
|
||||
"name": "付款申请单自动发起",
|
||||
"version": "0.1.0",
|
||||
"description": "读 EHR 预支台账 → 按 ERP 付款申请单口径逐行建单(默认试算不写库),可选提交、自动套打打印;含幂等查重与异常清单;打印完成后钉钉提醒去领取",
|
||||
"version": "0.2.5",
|
||||
"description": "按月份从 EHR 接口导出预支报酬台账(默认当月)→ 按月扫描「流程监控-已办结」预支流程刷新「预支办结流程」(全部流程详细数据,供 XLOOKUP 取收款银行/账号)→ 写入单据头申请日期/发起人 → Excel 重算并校验必录信息(含银行卡,缺失行跳过)→ 与 ERP 付款申请单对账回填「已付」→ 剩余未付行按台账「新旧系统」口径自动分流建单(默认试算不写库),可选提交,打印两份(每张 ERP 单据套打 + 「单子传递打印」本批行汇总);含幂等查重与异常清单;打印完成后钉钉提醒去领取",
|
||||
"category": "人资",
|
||||
"icon": "",
|
||||
"platform": "",
|
||||
"platform": "hr",
|
||||
"uses_month": false,
|
||||
"ui": true,
|
||||
"requires": {
|
||||
"sdks": {
|
||||
"hr_sdk": {
|
||||
"compat": "^0.2"
|
||||
},
|
||||
"erpsdk": {
|
||||
"compat": "^0.1"
|
||||
},
|
||||
@@ -26,22 +29,36 @@
|
||||
"xq0012"
|
||||
],
|
||||
"permissions": {
|
||||
"platforms": []
|
||||
"platforms": [
|
||||
"hr"
|
||||
]
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ref_month": {
|
||||
"type": "string",
|
||||
"title": "台账月份",
|
||||
"default": "",
|
||||
"description": "YYYY-MM 或 YYYYMM;留空=当月。当月无预支记录时直接提示,不自动回退上月"
|
||||
},
|
||||
"ledger_dir": {
|
||||
"type": "string",
|
||||
"title": "台账目录",
|
||||
"default": "D:\\资料\\人资\\预支",
|
||||
"description": "预支台账 xlsx 所在目录;留空=默认目录,自动取最新一个"
|
||||
"description": "导出临时文件/独立台账落盘目录;留空=默认目录"
|
||||
},
|
||||
"ledger_workbook": {
|
||||
"type": "string",
|
||||
"title": "目标工作簿",
|
||||
"default": "D:\\资料\\人资\\预支\\1030工资预支付款申请--已付.xlsx",
|
||||
"description": "导出数据追加到该工作簿的「预支报酬台账」sheet(按表头对齐、自动去重);留空=只导出独立文件"
|
||||
},
|
||||
"ledger_file": {
|
||||
"type": "string",
|
||||
"title": "台账文件(可选)",
|
||||
"default": "",
|
||||
"description": "指定具体 xlsx 路径;留空=按目录取最新"
|
||||
"description": "指定现成 xlsx(跳过导出与追加);留空=按台账月份自动导出/追加"
|
||||
},
|
||||
"apply_date": {
|
||||
"type": "string",
|
||||
@@ -66,6 +83,18 @@
|
||||
"default": "BM000477",
|
||||
"description": "默认 BM000477 人力资源部(生产真实单口径)"
|
||||
},
|
||||
"default_applicant_staff": {
|
||||
"type": "string",
|
||||
"title": "默认发起人工号",
|
||||
"default": "37001090",
|
||||
"description": "回填「付款申请单#单据头(FBillHead)」的申请人#编码(与申请日期=当天同时写入)"
|
||||
},
|
||||
"default_applicant_name": {
|
||||
"type": "string",
|
||||
"title": "默认发起人姓名",
|
||||
"default": "刘纤",
|
||||
"description": "回填「付款申请单#单据头(FBillHead)」的申请人#名称"
|
||||
},
|
||||
"expect_days": {
|
||||
"type": "number",
|
||||
"title": "期望付款日=申请日+N 天",
|
||||
@@ -74,11 +103,13 @@
|
||||
"erp_system": {
|
||||
"type": "string",
|
||||
"title": "ERP系统",
|
||||
"default": "新版",
|
||||
"default": "自动",
|
||||
"enum": [
|
||||
"自动",
|
||||
"新版",
|
||||
"旧版"
|
||||
]
|
||||
],
|
||||
"description": "自动=按台账「新旧系统」口径分流(门店服务序列且非标准化门店走旧版,部门随系统 BM000477/BM000881);新版/旧版=强制全部走一个系统"
|
||||
},
|
||||
"erp_username": {
|
||||
"type": "string",
|
||||
@@ -97,6 +128,18 @@
|
||||
"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": "建单后自动提交",
|
||||
@@ -105,8 +148,9 @@
|
||||
},
|
||||
"print_enabled": {
|
||||
"type": "boolean",
|
||||
"title": "建单后套打打印",
|
||||
"default": false
|
||||
"title": "建单后打印(ERP 单据 + 传递单)",
|
||||
"default": false,
|
||||
"description": "打开后打两份:①每张 ERP 付款申请单套打一份;②「单子传递打印」里本批建单对应的行汇总一份"
|
||||
},
|
||||
"printer": {
|
||||
"type": "string",
|
||||
@@ -114,7 +158,7 @@
|
||||
"default": "人力资源部",
|
||||
"enum": [
|
||||
"人力资源部",
|
||||
"网络信息部"
|
||||
"信息技术部"
|
||||
]
|
||||
},
|
||||
"copies": {
|
||||
|
||||
@@ -289,6 +289,10 @@ def render_payapply(data: dict, out_path: str) -> str:
|
||||
bottom = _fee_table(c, data, bottom, n)
|
||||
doc.set_metadata({"title": f"付款申请单 {data.get('bill_no', '')}",
|
||||
"creator": "37duAutomation/XQ0012"})
|
||||
try:
|
||||
doc.subset_fonts() # 嵌入字体子集化:9.5MB → ~50KB
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True)
|
||||
doc.save(out_path, deflate=True)
|
||||
doc.close()
|
||||
|
||||
@@ -2,27 +2,42 @@
|
||||
"""打印层:套打 PDF → printkit 网络打印机出纸。
|
||||
|
||||
printkit 走 IPP over TLS,不装驱动、不弹框、不走 Windows 队列;
|
||||
l6570(人力资源部)支持双面,l565(网络信息部)仅单面(printkit 会自动降级)。
|
||||
l6570(人力资源部)支持双面,l565(信息技术部)仅单面(printkit 会自动降级)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
from printkit import Printer
|
||||
|
||||
from .. import config
|
||||
|
||||
TAG = '[打印]'
|
||||
#: 打印机忙着处理上一份时会回 0x0507(server-error-busy),退避重试
|
||||
RETRIES = 3
|
||||
RETRY_WAIT = 6
|
||||
|
||||
|
||||
def print_pdf(pdf_path: str, printer: str = '', copies: int = 1, dry_run: bool = False) -> list:
|
||||
"""打印 PDF,返回每次结果(copies>1 时逐份提交)。"""
|
||||
"""打印 PDF,返回每次结果(copies>1 时逐份提交,单份最多重试 ``RETRIES`` 次)。"""
|
||||
name = printer or config.PRINTER_DEFAULT
|
||||
results = []
|
||||
for i in range(max(1, int(copies or 1))):
|
||||
try:
|
||||
r = Printer(name).print(pdf_path, dry_run=dry_run)
|
||||
results.append({'copies': i + 1, 'ok': bool(r.get('ok')), 'pages': len(r.get('pages') or [])})
|
||||
config.log(f'{TAG} 第 {i + 1} 份 → {name} ok={bool(r.get("ok"))}')
|
||||
except Exception as e: # noqa: BLE001
|
||||
config.log(f'{TAG} 第 {i + 1} 份失败({name}):{e}', 'ERROR')
|
||||
results.append({'copies': i + 1, 'ok': False, 'error': str(e)[:200]})
|
||||
for attempt in range(1, RETRIES + 1):
|
||||
try:
|
||||
r = Printer(name).print(pdf_path, dry_run=dry_run)
|
||||
results.append({'copies': i + 1, 'ok': bool(r.get('ok')),
|
||||
'pages': len(r.get('pages') or []), 'attempts': attempt})
|
||||
config.log(f'{TAG} 第 {i + 1} 份 → {name} ok={bool(r.get("ok"))}'
|
||||
+ (f'(第 {attempt} 次)' if attempt > 1 else ''))
|
||||
break
|
||||
except Exception as e: # noqa: BLE001
|
||||
if attempt < RETRIES:
|
||||
config.log(f'{TAG} 第 {i + 1} 份失败({name}):{e},{RETRY_WAIT}s 后重试',
|
||||
'WARN')
|
||||
time.sleep(RETRY_WAIT)
|
||||
continue
|
||||
config.log(f'{TAG} 第 {i + 1} 份失败({name}):{e}', 'ERROR')
|
||||
results.append({'copies': i + 1, 'ok': False, 'attempts': attempt,
|
||||
'error': str(e)[:200]})
|
||||
return results
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""「单子传递打印」sheet → 矢量 PDF(Excel 那份打印)。
|
||||
|
||||
排版直接复用 ``printkit.sheet``(同一个 SDK,插件已在 ``requires.sdks`` 里声明):
|
||||
``TablePDF`` 负责两行表头、中文禁则折行、数字右对齐、跨页重复表头、页脚页码;
|
||||
这里只做「按 FBillHead 行号挑出本批已建单的行」这件插件自己的事。
|
||||
|
||||
为什么不调 ``printkit.sheet.build_pdf``:``read_rows`` 只能从表头下一行整表读,
|
||||
无法只取本批行(行号与单据头逐行镜像,批内可能是不连续行)。
|
||||
|
||||
用法(由 ``logic.flow`` 调用):::
|
||||
|
||||
pdf, n = render_sheet_pdf(workbook_path, '单子传递打印', [3, 5], out_pdf)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from printkit.sheet import TablePDF, fmt_value
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def render_sheet_pdf(src: str, sheet: str, row_numbers, out_path: str,
|
||||
title: str = '', header_rows=(1, 2), fontsize: float = 9.0) -> tuple:
|
||||
"""把 ``sheet`` 中指定行(FBillHead 行号)渲染成 PDF,返回 ``(路径, 行数)``。
|
||||
|
||||
Args:
|
||||
src: 工作簿路径(已重算,公式有缓存值)
|
||||
sheet: sheet 名,如 ``config.SHEET_PRINT_SHEET``
|
||||
row_numbers: 要打印的行号集合(本批已建单的行)
|
||||
out_path: 输出 PDF
|
||||
title: 页头标题,留空不印
|
||||
header_rows: 表头行(第 1 行英文字段、第 2 行中文标题)
|
||||
|
||||
Raises:
|
||||
ValueError: 缺 sheet,或本批行没有可打印内容
|
||||
"""
|
||||
import openpyxl
|
||||
|
||||
wb = openpyxl.load_workbook(src, data_only=True)
|
||||
try:
|
||||
if sheet not in wb.sheetnames:
|
||||
raise ValueError(f'工作簿缺少 sheet「{sheet}」')
|
||||
ws = wb[sheet]
|
||||
ncol = min(ws.max_column or 1, 12)
|
||||
headers = []
|
||||
for r in header_rows:
|
||||
headers.append([fmt_value(ws.cell(row=r, column=c).value) or f'列{c}'
|
||||
for c in range(1, ncol + 1)])
|
||||
|
||||
rows = []
|
||||
for r in sorted({int(x) for x in row_numbers if x}):
|
||||
if r < max(header_rows) + 1 or r > ws.max_row:
|
||||
config.log(f'[传递单] 跳过第 {r} 行(超出 sheet 有效范围)', 'WARN')
|
||||
continue
|
||||
vals = [fmt_value(ws.cell(row=r, column=c).value) for c in range(1, ncol + 1)]
|
||||
if not any(v.strip() for v in vals):
|
||||
config.log(f'[传递单] 第 {r} 行全空,跳过', 'WARN')
|
||||
continue
|
||||
rows.append(vals)
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
if not rows:
|
||||
raise ValueError(f'「{sheet}」本批对应行没有可打印内容')
|
||||
|
||||
pdf = TablePDF(title=title, fontsize=fontsize)
|
||||
pdf.table(headers, rows)
|
||||
pdf.footer(f'共 {len(rows)} 行 · 第 {{page}} / {{total}} 页')
|
||||
data = pdf.to_bytes()
|
||||
|
||||
p = Path(out_path)
|
||||
p.parent.mkdir(parents=True, exist_ok=True)
|
||||
p.write_bytes(data)
|
||||
return str(p), len(rows)
|
||||
@@ -31,7 +31,11 @@
|
||||
</div>
|
||||
<div class="sec-body">
|
||||
<el-form label-position="top">
|
||||
<el-form-item label="台账目录(自动取最新)">
|
||||
<el-form-item label="台账月份(留空=当月,空月直接提示)">
|
||||
<el-input v-model="form.ref_month" :disabled="running" clearable
|
||||
placeholder="2026-11 或 202611" />
|
||||
</el-form-item>
|
||||
<el-form-item label="台账目录(接口导出落盘)">
|
||||
<div class="dir-ctrl">
|
||||
<el-input v-model="form.ledger_dir" class="dir-input" :disabled="running" clearable
|
||||
placeholder="D:\资料\人资\预支" />
|
||||
@@ -39,13 +43,18 @@
|
||||
@click="pickDir">选择</el-button>
|
||||
</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="台账文件(可选,留空=按目录取最新)">
|
||||
<el-form-item label="目标工作簿(追加到「预支报酬台账」sheet,留空=只导出)">
|
||||
<el-input v-model="form.ledger_workbook" :disabled="running" clearable
|
||||
placeholder="D:\资料\人资\预支\1030工资预支付款申请--已付.xlsx" />
|
||||
</el-form-item>
|
||||
<el-form-item label="台账文件(可选,留空=自动导出/追加)">
|
||||
<el-input v-model="form.ledger_file" :disabled="running" clearable
|
||||
placeholder="D:\资料\人资\预支\xxx.xlsx" />
|
||||
placeholder="留空即可" />
|
||||
</el-form-item>
|
||||
<div class="tip">
|
||||
读 sheet <b>预支报酬台账</b>:工号非空、金额 > 0、不含 #N/A 的行才算有效;
|
||||
组织名→编码取同工作簿 <b>辅助2-ERP组织机构</b> 表。
|
||||
按「预支报酬年月」调 EHR 接口导出(默认当月),按表头名称追加到目标工作簿的
|
||||
<b>预支报酬台账</b> sheet:自动跳过已存在的同键行,保留序号与 AT~AW 公式列。
|
||||
有效行口径:工号非空、金额 > 0、不含 #N/A。
|
||||
</div>
|
||||
</el-form>
|
||||
</div>
|
||||
@@ -79,7 +88,19 @@
|
||||
<el-form-item label="申请部门编码">
|
||||
<el-input v-model="form.apply_dept" :disabled="running" placeholder="BM000477" />
|
||||
</el-form-item>
|
||||
<div class="inline-row">
|
||||
<el-form-item label="默认发起人工号">
|
||||
<el-input v-model="form.default_applicant_staff" :disabled="running"
|
||||
placeholder="37001090" />
|
||||
</el-form-item>
|
||||
<el-form-item label="默认发起人姓名">
|
||||
<el-input v-model="form.default_applicant_name" :disabled="running"
|
||||
placeholder="刘纤" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="tip">
|
||||
每批执行会把「付款申请单#单据头(FBillHead)」对应行的
|
||||
<b>申请日期</b>写成当天、<b>申请人#编码/名称</b>写成上面的默认发起人(可直接用于金蝶「引入」)。
|
||||
付款用途业务口径未定:人工导入模板是 <b>个人借款</b>,生产真实单是 <b>工资预提</b>,按当月批次选。
|
||||
申请部门默认 <b>BM000477 人力资源部</b>(生产真实单口径)。
|
||||
</div>
|
||||
@@ -98,6 +119,7 @@
|
||||
<div class="inline-row">
|
||||
<el-form-item label="ERP系统">
|
||||
<el-select v-model="form.erp_system" :disabled="running" style="width: 100%">
|
||||
<el-option label="自动(按台账新旧系统)" value="自动" />
|
||||
<el-option label="新版" value="新版" />
|
||||
<el-option label="旧版" value="旧版" />
|
||||
</el-select>
|
||||
@@ -111,13 +133,19 @@
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="inline-row">
|
||||
<el-form-item class="switch-item" label="发起前对账回填(已有 ERP 单标已付)">
|
||||
<el-switch v-model="form.reconcile" :disabled="running" />
|
||||
</el-form-item>
|
||||
<el-form-item class="switch-item" label="刷新「预支办结流程」(收款银行/账号)">
|
||||
<el-switch v-model="form.refresh_flow" :disabled="running" />
|
||||
</el-form-item>
|
||||
<el-form-item class="switch-item" label="试算模式(不写 ERP)">
|
||||
<el-switch v-model="form.dry_run" :disabled="running" />
|
||||
</el-form-item>
|
||||
<el-form-item class="switch-item" label="建单后自动提交">
|
||||
<el-switch v-model="form.submit" :disabled="running" />
|
||||
</el-form-item>
|
||||
<el-form-item class="switch-item" label="建单后套打打印">
|
||||
<el-form-item class="switch-item" label="建单后打印(单据+传递单)">
|
||||
<el-switch v-model="form.print_enabled" :disabled="running" />
|
||||
</el-form-item>
|
||||
<el-form-item class="switch-item" label="调试日志">
|
||||
@@ -128,7 +156,7 @@
|
||||
<el-form-item label="打印机">
|
||||
<el-select v-model="form.printer" :disabled="running" style="width: 100%">
|
||||
<el-option label="人力资源部(双面)" value="人力资源部" />
|
||||
<el-option label="网络信息部(单面)" value="网络信息部" />
|
||||
<el-option label="信息技术部(单面)" value="信息技术部" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="打印份数">
|
||||
@@ -146,6 +174,9 @@
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="tip">
|
||||
<b>自动分流</b>按台账「新旧系统」口径:职位序列是「门店服务序列」且会馆不在标准化门店名单 → 旧版,其余新版;
|
||||
申请部门随系统走(新版 BM000477 / 旧版 BM000881)。
|
||||
<b>对账回填</b>先按台账月份查 ERP 已有付款申请单,命中的台账行写「付款状态=已付」并不再发起(需填 ERP 账号)。
|
||||
<b>试算模式</b>只组装 + 查重 + 输出结果,不写 ERP;关掉试算才会建单。
|
||||
「自动提交」关闭时只建草稿(A 状态),由 HR 在 ERP 里核对后再提交(提交后进入审批流)。
|
||||
打印走 printkit 直连网络打印机,不弹窗。
|
||||
@@ -163,7 +194,7 @@
|
||||
<div class="hb-line"><b>顺序</b>:Model 里「部门」必须排在「申请人」之后,且分录最后(否则报申请人/部门必录)。</div>
|
||||
<div class="hb-line"><b>保存</b>:IsAutoAdjustField 必须 false。</div>
|
||||
<div class="hb-line"><b>分录</b>:费用项目 0111001 预支工资 / 结算方式 JSFS04_SYS 转账 / 币别 PRE001。</div>
|
||||
<div class="hb-line"><b>套打</b>:自绘 PDF(A4、SimSun、与 ERP 套打样例一致),不走 ERP 打印接口。</div>
|
||||
<div class="hb-line"><b>打印</b>:两份——①每张 ERP 单据套打一份(自绘 PDF,A4/SimSun);②「单子传递打印」本批对应行汇总一份(读单元格值自绘 PDF)。</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
@@ -194,16 +225,22 @@ import { ElMessage } from 'element-plus'
|
||||
|
||||
// DEFAULTS 与 plugin.json.fields 的 default 逐项一致
|
||||
const DEFAULTS = () => ({
|
||||
ref_month: '',
|
||||
ledger_dir: 'D:\\资料\\人资\\预支',
|
||||
ledger_workbook: 'D:\\资料\\人资\\预支\\1030工资预支付款申请--已付.xlsx',
|
||||
ledger_file: '',
|
||||
apply_date: '',
|
||||
pay_purpose: '个人借款',
|
||||
apply_dept: 'BM000477',
|
||||
default_applicant_staff: '37001090',
|
||||
default_applicant_name: '刘纤',
|
||||
expect_days: 1,
|
||||
erp_system: '新版',
|
||||
erp_system: '自动',
|
||||
erp_username: '',
|
||||
erp_password: '',
|
||||
dry_run: true,
|
||||
reconcile: true,
|
||||
refresh_flow: true,
|
||||
submit: false,
|
||||
print_enabled: false,
|
||||
printer: '人力资源部',
|
||||
|
||||
+20
-20
File diff suppressed because one or more lines are too long
@@ -4,7 +4,7 @@
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>付款申请单自动发起</title>
|
||||
<script type="module" crossorigin src="/pui/xq0012/assets/index-Drjevmlm.js"></script>
|
||||
<script type="module" crossorigin src="/pui/xq0012/assets/index-DrneYZ41.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0012/assets/index-Dy0-BAQJ.css">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
Reference in New Issue
Block a user