292 lines
13 KiB
Python
292 lines
13 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""XQ0084 闭环层:核对通过记录导入 HR 工资卡,成功后回写 AI 表格。
|
||
|
||
导入前先查 HR「工资卡管理」台账:该员工在 HR 已有同一张卡(卡号一致)说明之前
|
||
已经更新过,不再重复导入,直接回写 AI 表格「是否更新HR系统=是」;卡号不一致
|
||
(有新卡待换)才走导入。
|
||
|
||
调用链:``hr_sdk`` 工资卡台账(在职分页)→ 建身份证/工号索引 →
|
||
``build_wage_rows``(跳过已一致)→ ``hr_sdk.wage_import.import_cards``(浏览器上下文 +
|
||
WS 读结果)→ 按服务端 ``errorList.line`` 回填每条记录的导入结果 →
|
||
对已导入/已一致的记录把 AI 表格「是否更新HR系统」回写为「是」。
|
||
|
||
SDK 懒加载:hr_sdk 由执行机按 plugin.json.requires.sdks 挂载,不在模块顶层 import。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
|
||
from .. import config
|
||
|
||
|
||
def _log(msg, level="INFO"):
|
||
config.log(msg, level)
|
||
|
||
|
||
def _norm_card(value):
|
||
"""卡号归一:只留数字(表格里可能带空格/横线)。"""
|
||
return re.sub(r"\D", "", str(value or ""))
|
||
|
||
|
||
def _norm_id(value):
|
||
"""身份证归一:去空格/横线并转大写(尾位 x)。"""
|
||
return re.sub(r"[\s\-]", "", str(value or "")).upper()
|
||
|
||
|
||
def _norm_code(value):
|
||
"""工号归一:去空白。"""
|
||
return re.sub(r"\s", "", str(value or ""))
|
||
|
||
|
||
def _is_main(value):
|
||
return str(value or "").strip() in ("1", "主卡", "是", "true", "True")
|
||
|
||
|
||
def _append(before, text):
|
||
"""拼说明:已有备注在前,避免覆盖「HR 现有卡号…将更新为…」等上下文。"""
|
||
return f"{before};{text}" if before else text
|
||
|
||
|
||
def build_card_index(cards):
|
||
"""HR 工资卡台账 → 按身份证(员工/开户人)与工号检索的索引。
|
||
|
||
Args:
|
||
cards: 台账原始行(``BANK_ACCOUNT`` / ``CARD_IDCARD`` / ``IDCARD`` /
|
||
``base_code`` / ``IS_MAIN`` / ``branch_bank_name``)。
|
||
|
||
Returns:
|
||
``{"by_id": {身份证: [card]}, "by_code": {工号: [card]}}``,
|
||
``card = {card, main, branch, name}``(卡号为空的行忽略)。
|
||
"""
|
||
by_id, by_code = {}, {}
|
||
for item in cards or []:
|
||
card_no = _norm_card(item.get("BANK_ACCOUNT"))
|
||
if not card_no:
|
||
continue
|
||
card = {
|
||
"card": card_no,
|
||
"main": _is_main(item.get("IS_MAIN")),
|
||
"branch": str(item.get("branch_bank_name") or "").strip(),
|
||
"name": str(item.get("CARD_NAME") or "").strip(),
|
||
}
|
||
for key in {_norm_id(item.get("CARD_IDCARD")), _norm_id(item.get("IDCARD"))}:
|
||
if key:
|
||
by_id.setdefault(key, []).append(card)
|
||
code = _norm_code(item.get("base_code"))
|
||
if code:
|
||
by_code.setdefault(code, []).append(card)
|
||
return {"by_id": by_id, "by_code": by_code}
|
||
|
||
|
||
def match_existing(index, table_id, emp_no):
|
||
"""按身份证(优先)或工号取该员工在 HR 的工资卡;未命中返回空列表。"""
|
||
if not index:
|
||
return []
|
||
hit = index.get("by_id", {}).get(_norm_id(table_id))
|
||
if hit:
|
||
return hit
|
||
return index.get("by_code", {}).get(_norm_code(emp_no)) or []
|
||
|
||
|
||
def fetch_existing_cards(session):
|
||
"""拉 HR「工资卡管理」在职工资卡台账,返回 :func:`build_card_index` 的索引。
|
||
|
||
拉取失败(登录态/接口异常)返回 ``None``:降级为不查重、按原逻辑直接导入,
|
||
不阻断本次闭环。
|
||
"""
|
||
try:
|
||
from hr_sdk import HrClient # SDK 下发,懒加载
|
||
from hr_sdk.config import REDSEA
|
||
except Exception as e: # noqa: BLE001
|
||
_log(f"[HR查重] hr_sdk 不可用,跳过已更新检查:{e}", "WARNING")
|
||
return None
|
||
|
||
url = f"{REDSEA}{config.WAGE_CARD_LIST_PATH}"
|
||
client = HrClient(session)
|
||
cards = []
|
||
try:
|
||
for page_no in range(1, config.WAGE_CARD_MAX_PAGES + 1):
|
||
params = {
|
||
"start": (page_no - 1) * config.WAGE_CARD_PAGE_SIZE,
|
||
"pageNo": page_no,
|
||
"pageSize": config.WAGE_CARD_PAGE_SIZE,
|
||
"ftl_list_STRU_TREE_CODE": "cq37du",
|
||
"sortName": "hr_staff_wage_card.STAFF_NAME",
|
||
"sortType": "asc",
|
||
"commonQuery": "[]",
|
||
"person_status": 1, # 1=在职(换卡员工都在职)
|
||
"leaveOffice_date": "",
|
||
}
|
||
data = client.request_json("POST", url, data=params, label="工资卡台账")
|
||
state = str(data.get("state") or "").strip()
|
||
if state not in ("", "1"):
|
||
_log(f"[HR查重] 工资卡台账返回 state={state}:{data.get('meg')}", "WARNING")
|
||
return None
|
||
page_rows = data.get("datas") or []
|
||
cards.extend(page_rows)
|
||
total_page = int(data.get("pageCount") or 0)
|
||
if not page_rows or (total_page and page_no >= total_page):
|
||
break
|
||
except Exception as e: # noqa: BLE001 查重失败不阻断导入
|
||
_log(f"[HR查重] 工资卡台账拉取失败,跳过已更新检查:{e}", "WARNING")
|
||
return None
|
||
|
||
index = build_card_index(cards)
|
||
index["count"] = len(cards)
|
||
_log(f"[HR查重] HR 在职工资卡 {len(cards)} 条,"
|
||
f"身份证索引 {len(index['by_id'])}、工号索引 {len(index['by_code'])}")
|
||
return index
|
||
|
||
|
||
def build_wage_rows(rows, existing=None):
|
||
"""挑出可自动导入的记录并生成模板数据行。
|
||
|
||
Args:
|
||
rows: 核对结果行。
|
||
existing: :func:`fetch_existing_cards` 的索引(``None``=不查重)。
|
||
|
||
Returns:
|
||
(targets, data_rows):targets 与 data_rows 一一对应;
|
||
不可自动导入的记录(委托发放/缺字段)与 HR 已一致的记录已就地写入
|
||
hr_status/hr_note。
|
||
"""
|
||
targets, data_rows = [], []
|
||
for r in rows:
|
||
if r.get("conclusion") != "通过":
|
||
continue
|
||
if r.get("trust") == config.HR_TRUST_YES:
|
||
r["hr_status"] = "跳过"
|
||
r["hr_note"] = "委托发放,工资卡开户人与员工不一致,需人工在 HR 维护"
|
||
continue
|
||
if not (r.get("table_bank") and r.get("table_card") and r.get("table_id")):
|
||
r["hr_status"] = "跳过"
|
||
r["hr_note"] = "缺开户银行/银行卡号/身份证号,无法自动导入"
|
||
continue
|
||
|
||
table_card = _norm_card(r.get("table_card"))
|
||
hr_cards = match_existing(existing, r.get("table_id"), r.get("emp_no"))
|
||
if any(c.get("card") == table_card for c in hr_cards):
|
||
main = next(c for c in hr_cards if c.get("card") == table_card).get("main")
|
||
r["hr_status"] = config.HR_STATUS_EXISTING
|
||
r["hr_note"] = (f"HR 工资卡已是该卡号({table_card}"
|
||
f"{',主卡' if main else ''}),无需重复导入,直接回写台账")
|
||
continue
|
||
if hr_cards:
|
||
r["hr_note"] = (f"HR 现有卡号 {'、'.join(c['card'] for c in hr_cards[:2])},"
|
||
f"将更新为 {table_card}")
|
||
|
||
data_rows.append([
|
||
r.get("emp_name") or r.get("holder"), # *姓名(员工)
|
||
r.get("table_id"), # *身份证号
|
||
r.get("holder"), # *开户人姓名
|
||
config.WAGE_IS_MAIN, # *是否主卡
|
||
r.get("table_id"), # *开户人身份证号
|
||
config.WAGE_CARD_TYPE, # 银行卡类型
|
||
r.get("table_bank"), # *开卡银行
|
||
r.get("table_branch") or "", # 开户支行
|
||
r.get("table_card"), # *银行卡号
|
||
config.WAGE_REMARK, # 备注
|
||
])
|
||
targets.append(r)
|
||
return targets, data_rows
|
||
|
||
|
||
def import_passed(rows, session, progress=None):
|
||
"""把核对通过记录导入 HR 工资卡,结果逐条写回 ``rows`` 的 hr_status/hr_note。
|
||
|
||
HR 已有同一张卡的记录标记「已一致」,不进导入清单,但仍回写台账。
|
||
"""
|
||
p = progress or (lambda _pct: None)
|
||
# 没有核对通过的行就不必拉台账(省几页请求)
|
||
has_candidate = any(r.get("conclusion") == "通过" for r in rows)
|
||
existing = (fetch_existing_cards(session)
|
||
if config.CHECK_EXISTING_CARD and has_candidate else None)
|
||
targets, data_rows = build_wage_rows(rows, existing)
|
||
stats = {"imported": 0, "failed": 0, "skipped": 0, "existing": 0,
|
||
"written": 0, "message": ""}
|
||
stats["skipped"] = sum(1 for r in rows if r.get("hr_status") == "跳过")
|
||
stats["existing"] = sum(1 for r in rows
|
||
if r.get("hr_status") == config.HR_STATUS_EXISTING)
|
||
if not targets:
|
||
stats["message"] = (f"无待更新工资卡,跳过 HR 导入"
|
||
f"(HR 已一致 {stats['existing']} 条)")
|
||
_log("[HR导入] " + stats["message"], "WARNING")
|
||
stats["written"] = write_back(rows) # 已一致的记录也要回写「是」
|
||
return stats
|
||
|
||
_log(f"[HR导入] 开始导入 {len(targets)} 条工资卡(按身份证匹配;"
|
||
f"HR 已一致跳过 {stats['existing']} 条)")
|
||
try:
|
||
from hr_sdk import wage_import # SDK 下发,懒加载
|
||
res = wage_import.import_cards(
|
||
data_rows, session=session, fit_type=config.WAGE_FIT_TYPE,
|
||
timeout=config.WAGE_IMPORT_TIMEOUT, log=lambda m: _log(f"[HR导入] {m}"))
|
||
except Exception as e: # noqa: BLE001 导入失败不中断出表
|
||
_log(f"[HR导入] 导入失败:{e}", "ERROR")
|
||
for r in targets:
|
||
r["hr_status"] = "导入失败"
|
||
r["hr_note"] = f"HR 导入失败:{e}"
|
||
stats["failed"] = len(targets)
|
||
stats["message"] = f"HR 导入失败:{e}"
|
||
return stats
|
||
p(94)
|
||
|
||
errors = {}
|
||
for item in res.get("errorList") or []:
|
||
try:
|
||
errors[int(item.get("line") or 0)] = str(item.get("meg") or item.get("msg") or "")
|
||
except (TypeError, ValueError):
|
||
continue
|
||
for idx, r in enumerate(targets):
|
||
line = idx + 2 # 模板第 1 行为表头
|
||
if not errors and res.get("result") == 1:
|
||
r["hr_status"] = "已导入"
|
||
r["hr_note"] = _append(r.get("hr_note"), "HR 工资卡导入成功")
|
||
elif line in errors:
|
||
r["hr_status"] = "导入失败"
|
||
r["hr_note"] = _append(r.get("hr_note"), errors[line] or "HR 返回导入失败")
|
||
elif errors:
|
||
# 服务端有失败行但未命中本行:按成功处理,仍需人工复核导入结果
|
||
r["hr_status"] = "已导入"
|
||
r["hr_note"] = _append(r.get("hr_note"), "未在错误列表命中,请复核 HR 工资卡")
|
||
else:
|
||
r["hr_status"] = "导入失败"
|
||
r["hr_note"] = _append(r.get("hr_note"),
|
||
f"HR 返回 result={res.get('result')},未成功")
|
||
stats["imported"] = sum(1 for r in targets if r["hr_status"] == "已导入")
|
||
stats["failed"] = len(targets) - stats["imported"]
|
||
_log(f"[HR导入] 完成:成功 {stats['imported']}、失败 {stats['failed']}、"
|
||
f"跳过 {stats['skipped']}、HR 已一致 {stats['existing']}(服务端 "
|
||
f"total={res.get('total')} successNum={res.get('successNum')} "
|
||
f"errorNum={res.get('errorNum')})")
|
||
|
||
stats["written"] = write_back(rows)
|
||
return stats
|
||
|
||
|
||
def write_back(rows):
|
||
"""把已导入/HR 已一致的记录回写 AI 表格「是否更新HR系统=是」。"""
|
||
done = 0
|
||
pending = [r for r in rows
|
||
if r.get("hr_status") in ("已导入", config.HR_STATUS_EXISTING)
|
||
and r.get("record_id")]
|
||
if not pending:
|
||
return 0
|
||
from ..data.ai_table import open_client # 复用数据层凭证与客户端
|
||
try:
|
||
with open_client() as cli:
|
||
for r in pending:
|
||
try:
|
||
cli.update_fields(config.AI_BASE, config.AI_SHEET, r["record_id"],
|
||
{config.F_DONE: "是"})
|
||
r["hr_note"] = f"{r['hr_note']};台账已标记已更新HR系统"
|
||
done += 1
|
||
except Exception as e: # noqa: BLE001 单条失败不影响其它
|
||
r["hr_note"] = f"{r['hr_note']};台账回写失败:{e}"
|
||
_log(f"[回写] {r.get('emp_no')} {r.get('holder')} 回写失败:{e}", "ERROR")
|
||
except Exception as e: # noqa: BLE001
|
||
_log(f"[回写] 打开 AI 表格失败:{e}", "ERROR")
|
||
return 0
|
||
_log(f"[回写] 已回写 {done}/{len(pending)} 条「{config.F_DONE}=是」")
|
||
return done
|