feat: 新增银行卡检查插件及相关依赖与配置文件

This commit is contained in:
2026-10-29 14:21:30 +08:00
parent 259369953f
commit 526116af83
494 changed files with 66923 additions and 2714 deletions
@@ -0,0 +1,2 @@
# -*- coding: utf-8 -*-
"""XQ0005 插件 - 数据层:HR 工资卡 / 银行字典接口。"""
@@ -0,0 +1,105 @@
# -*- coding: utf-8 -*-
"""XQ0005 插件 - 银行字典接口(WAGE.BANKTYPE):银行编码 -> 开卡银行名称。
参考影刀版 bank_card_check.py:
- 优先读本机缓存(%LOCALAPPDATA%\\37duAutomation\\BankCardCheck\\bank_dict_*.json),
缓存 7 天过期后自动重新拉取;
- 拉取失败时降级使用旧缓存;无缓存返回空字典(开卡银行列留空,不影响其他核对)。
"""
import json
import os
import time
from ..config import (
BANK_DICT_CODE_TYPE, BANK_DICT_EXPIRE_SEC, BANK_DICT_LIST_FILE,
BANK_DICT_MAP_FILE, BANK_DICT_URL, MAX_REQUEST_RETRY, logger,
)
from ..config import _APP_DATA_DIR as DICT_CACHE_DIR
def _ensure_dir(path):
os.makedirs(path, exist_ok=True)
def fetch_bank_dict(session):
"""远程调用字典接口并写入本地缓存,返回 (list[dict], dict[code->name])。"""
payload = {
"codeType": BANK_DICT_CODE_TYPE,
"inUse": "0,1,2",
"platformMode": "redseaPlatform",
}
resp = session.post(BANK_DICT_URL, data=payload, timeout=30)
resp.raise_for_status()
resp_json = resp.json()
raw_list = resp_json.get(BANK_DICT_CODE_TYPE) or []
result_list = [{"code": str(item.get("code", "")), "name": item.get("name", "")}
for item in raw_list]
result_map = {item["code"]: item["name"] for item in result_list}
_ensure_dir(DICT_CACHE_DIR)
with open(BANK_DICT_LIST_FILE, "w", encoding="utf-8") as f:
json.dump(result_list, f, ensure_ascii=False, indent=2)
with open(BANK_DICT_MAP_FILE, "w", encoding="utf-8") as f:
json.dump(result_map, f, ensure_ascii=False, indent=2)
logger.info("银行字典远程拉取完成,共 %d 条", len(result_list))
return result_list, result_map
def load_bank_dict_cache():
"""读取本地银行字典缓存,失败返回 (None, None)。"""
try:
with open(BANK_DICT_LIST_FILE, "r", encoding="utf-8") as f:
lst = json.load(f)
with open(BANK_DICT_MAP_FILE, "r", encoding="utf-8") as f:
mp = json.load(f)
return lst, mp
except Exception as e:
logger.warning("银行字典本地缓存读取失败:%s", e)
return None, None
def get_bank_dict(session=None, force_refresh=False):
"""获取银行字典(优先本地缓存,过期/强制刷新才请求接口),返回 (list, map)。"""
need_refresh = force_refresh
if not (os.path.exists(BANK_DICT_LIST_FILE) and os.path.exists(BANK_DICT_MAP_FILE)):
need_refresh = True
else:
mtime = os.path.getmtime(BANK_DICT_LIST_FILE)
if time.time() - mtime > BANK_DICT_EXPIRE_SEC:
need_refresh = True
if need_refresh:
last_err = None
for attempt in range(1, MAX_REQUEST_RETRY + 1):
try:
return fetch_bank_dict(session)
except Exception as e:
last_err = e
logger.warning("银行字典远程拉取第 %d 次失败:%s", attempt, e)
time.sleep(1.0 * attempt)
logger.error("银行字典远程拉取失败:%s", last_err)
lst, mp = load_bank_dict_cache()
if lst is not None:
logger.warning("降级使用本地银行字典缓存,共 %d 条", len(lst))
return lst, mp
return [], {}
lst, mp = load_bank_dict_cache()
if lst is None:
return fetch_bank_dict(session)
logger.info("读取本地银行字典缓存,共 %d 条", len(lst))
return lst, mp
def bank_type_to_name(bank_type, bank_map):
"""按银行编码(BANK_TYPE)匹配字典 code,返回开卡银行;未命中返回空串。"""
if bank_type is None:
return ""
if isinstance(bank_type, float):
if bank_type != bank_type: # NaN
return ""
bank_type = str(int(bank_type))
elif isinstance(bank_type, int):
bank_type = str(bank_type)
else:
bank_type = str(bank_type).strip()
return (bank_map or {}).get(bank_type, "")
@@ -0,0 +1,136 @@
# -*- coding: utf-8 -*-
"""XQ0005 插件 - 工资卡接口(HrStaffWageCard)分页拉取。
接口:POST {HR}/RedseaPlatform/getPageAjax/HrStaffWageCard.mc
person_status=1 在职(离职日期不限);person_status=2 离职(按 leaveOffice_date 区间筛选)。
登录态由底座注入(config.require_session()),失效抛 RuntimeError 提示重新登录,不做自动补登。
"""
import time
from datetime import date, timedelta
from ..config import MAX_REQUEST_RETRY, PAGE_MAX_SIZE, WAGE_CARD_URL, logger
class HRSessionExpiredError(Exception):
"""HR 登录态失效(接口返回非 JSON,通常被重定向到登录页)。"""
LOGIN_EXPIRED_MSG = "HR 登录态已过期,请先在壳子(工作台)重新登录 HR 平台后重试"
def _request_page(session, status, page_no, page_size, leave_start=None, leave_end=None):
"""请求工资卡单页数据(不做重试,由调用方统一重试)。"""
params = {
"start": (page_no - 1) * page_size,
"pageNo": page_no,
"pageSize": page_size,
"ftl_list_STRU_TREE_CODE": "cq37du",
"sortName": "hr_staff_wage_card.STAFF_NAME",
"sortType": "asc",
"commonQuery": "[]",
"person_status": status,
}
if status == 1:
params["leaveOffice_date"] = ""
elif leave_start and leave_end:
params["leaveOffice_date[0]"] = leave_start
params["leaveOffice_date[1]"] = leave_end
params["leaveOffice_date_start"] = leave_start
params["leaveOffice_date_end"] = leave_end
resp = session.post(WAGE_CARD_URL, data=params, timeout=20)
if resp.status_code != 200:
raise RuntimeError(f"工资卡接口状态码异常: {resp.status_code}")
text = resp.text or ""
if text and not text.lstrip().startswith(("{", "[")):
raise HRSessionExpiredError(LOGIN_EXPIRED_MSG)
try:
return resp.json()
except Exception:
raise RuntimeError(f"工资卡接口返回非 JSON 数据(状态码 {resp.status_code}): {text[:200]}")
def fetch_wage_card_page(session, status, page_no=1, page_size=PAGE_MAX_SIZE,
leave_start=None, leave_end=None):
"""请求工资卡单页数据(项目级重试:最多 3 次,登录失效不重试直接抛出)。"""
last_err = None
for attempt in range(1, MAX_REQUEST_RETRY + 1):
try:
data = _request_page(session, status, page_no, page_size, leave_start, leave_end)
if not isinstance(data, dict):
raise RuntimeError(f"工资卡接口返回结构异常: {str(data)[:200]}")
return data
except HRSessionExpiredError:
raise
except Exception as e:
last_err = e
if attempt >= MAX_REQUEST_RETRY:
break
logger.warning("工资卡第 %d 页第 %d 次请求失败:%s", page_no, attempt, e)
time.sleep(1.0 * attempt)
raise RuntimeError(f"工资卡第 {page_no} 页连续 {MAX_REQUEST_RETRY} 次请求失败:{last_err}")
def fetch_all_wage_card(session, status, status_name, leave_start=None, leave_end=None):
"""分页抓取某人员状态(在职/离职)的工资卡全量数据,返回接口原始记录列表。"""
all_rows = []
page_no = 1
while True:
try:
data = fetch_wage_card_page(session, status, page_no, PAGE_MAX_SIZE,
leave_start, leave_end)
except HRSessionExpiredError:
raise RuntimeError(f"【{status_name}】{LOGIN_EXPIRED_MSG}")
if str(data.get("state")) != "1":
raise RuntimeError(f"【{status_name}】第 {page_no} 页数据请求失败:{data.get('meg')}")
page_list = data.get("datas", []) or []
if not page_list:
logger.info("【%s】无更多数据", status_name)
break
for item in page_list:
item["人员类型"] = status_name
all_rows.extend(page_list)
total = data.get("count", 0)
total_page = int(data.get("pageCount", 0) or 0)
logger.info("【%s】已抓取 %d/%d 页,累计 %d/%d 条",
status_name, page_no, total_page, len(all_rows), total)
if page_no >= total_page:
break
page_no += 1
time.sleep(0.2)
return all_rows
def precheck(session):
"""登录态预检:拉一条在职数据,登录失效直接抛错,避免跑完一半才发现。"""
try:
fetch_wage_card_page(session, status=1, page_no=1, page_size=1)
except HRSessionExpiredError:
raise RuntimeError(LOGIN_EXPIRED_MSG)
logger.info("HR 登录态校验通过")
def get_leave_range(today=None, start_override="", end_override=""):
"""计算离职日期筛选范围,返回 (开始日期, 结束日期) 字符串 YYYY-MM-DD。
自动规则(与影刀版一致):每月 8 号及之前 -> 上月 1 日 ~ 今天;8 号之后 -> 本月 1 日 ~ 今天。
两个覆盖值都填写时优先使用覆盖值(补跑历史月份用)。
"""
start_override = (start_override or "").strip()
end_override = (end_override or "").strip()
if start_override and end_override:
logger.info("离职日期范围使用手动指定:%s ~ %s", start_override, end_override)
return start_override, end_override
today = today or date.today()
if today.day <= 8:
first_this_month = today.replace(day=1)
last_prev_month = first_this_month - timedelta(days=1)
start = last_prev_month.replace(day=1)
else:
start = today.replace(day=1)
return start.strftime("%Y-%m-%d"), today.strftime("%Y-%m-%d")