台账按月接口导出并追加目标工作簿;整表刷新「预支办结流程」供单据头 XLOOKUP 取收款信息;发起前对账命中回填已付;按台账口径新旧系统分流;建单后套打 ERP 单据 + 单子传递打印;含离线自检与打包脚本。
711 lines
28 KiB
Python
711 lines
28 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""台账数据层:按月份从 EHR 接口导出「预支报酬台账」,再按口径读有效行。
|
||
|
||
口径(2026-11 实测):
|
||
- 接口导出:``hr_sdk.ledger.export_advance_pay``(预支工资/报薪台账,月份筛选
|
||
``ext_yuzhi_month``,留空=当月),服务端生成 xlsx,sheet = 「预支报酬台账」;
|
||
- sheet 第 2 行是表头,第 3 行起是数据(第 1 行是导出名标题);
|
||
- 有效行:工号非空、预支金额 > 0、整行无 #N/A 类错误值;
|
||
- 组织编码:接口导出不含手工工作簿的「辅助2-ERP组织机构」sheet,当前统一回落
|
||
申请组织 ``config.APPLY_ORG_ID``(后续要按会馆映射时再加映射源)。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import html
|
||
import io
|
||
import os
|
||
import re
|
||
import tempfile
|
||
import zipfile
|
||
from datetime import date, datetime, timedelta
|
||
|
||
import openpyxl
|
||
|
||
from .. import config
|
||
|
||
ERR_RE = re.compile(r'^#(N/A|REF!|VALUE!|DIV/0!|NAME\?|NULL!|NUM!|GETTING_DATA)$', re.I)
|
||
|
||
|
||
def _s(v) -> str:
|
||
if v is None:
|
||
return ''
|
||
if isinstance(v, datetime):
|
||
return v.strftime('%Y-%m-%d')
|
||
s = str(v).strip()
|
||
return '' if ERR_RE.match(s) else s
|
||
|
||
|
||
def _num(v):
|
||
try:
|
||
return float(str(v).replace(',', ''))
|
||
except (TypeError, ValueError):
|
||
return 0.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:
|
||
"""组织名称 → 编码(辅助2-ERP组织机构:FNumber / FName#2052)。"""
|
||
wb = openpyxl.load_workbook(path, data_only=True, read_only=True)
|
||
try:
|
||
if config.ORG_SHEET not in wb.sheetnames:
|
||
return {}
|
||
ws = wb[config.ORG_SHEET]
|
||
out = {}
|
||
for row in ws.iter_rows(min_row=3, values_only=True):
|
||
code, name = _s(row[0] if row else ''), _s(row[1] if len(row) > 1 else '')
|
||
if code and name:
|
||
out[name] = code
|
||
return out
|
||
finally:
|
||
wb.close()
|
||
|
||
|
||
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}」')
|
||
ws = wb[config.LEDGER_SHEET]
|
||
header = {}
|
||
for idx, cell in enumerate(next(ws.iter_rows(min_row=2, max_row=2, values_only=True)), 1):
|
||
name = _s(cell)
|
||
if name:
|
||
header[name] = idx - 1
|
||
rows = []
|
||
for r, raw in enumerate(ws.iter_rows(min_row=3, values_only=True), start=3):
|
||
if not raw:
|
||
continue
|
||
def get(col):
|
||
i = header.get(col)
|
||
return raw[i] if i is not None and i < len(raw) else None
|
||
staff, amount = _s(get(config.COL_STAFF)), _num(get(config.COL_AMOUNT))
|
||
if not staff or amount <= 0:
|
||
continue
|
||
if any(ERR_RE.match(_s(v)) for v in raw):
|
||
continue
|
||
row = {
|
||
'row': r,
|
||
'seq': _s(get(config.COL_SEQ)),
|
||
'month': _s(get(config.COL_MONTH)),
|
||
'staff': staff,
|
||
'name': _s(get(config.COL_NAME)),
|
||
'date': _s(get(config.COL_DATE)),
|
||
'amount': amount,
|
||
'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 '')
|
||
parts = [p for p in re.split(r'[-/→>]', path) if p]
|
||
for p in reversed(parts): # 从末级向上找:会馆名优先
|
||
p = p.strip()
|
||
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()
|