feat: 新增考勤异常模块、银行卡校验、OCR附件检测等功能
1. 新增考勤异常查询与导出模块,支持当月异常拉取、Excel导出、钉钉推送提醒 2. 完善请假/加班流程解析与校验,新增附件下载、OCR核验能力 3. 新增银行卡信息校验模块,支持在职/离职员工工资卡数据核对与异常导出 4. 新增通用OCR工具模块,支持病假/婚假/产检假附件关键词检测与日期提取 5. 新增门店请休假异常名单、银行卡检查等需求文档 6. 重构部分现有模块代码,优化配置与接口调用逻辑 7. 新增测试文件与工具类,完善项目基础能力
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.attendance
|
||||
@Description: 考勤异常查询与导出模块
|
||||
"""
|
||||
@@ -0,0 +1,323 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.attendance
|
||||
@FileName: attendance_abnormal.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-10
|
||||
@Description: 考勤异常查询与导出:通过员工基础信息接口(getCurUserInfo)校验 cookies 有效性,
|
||||
再调用考勤异常接口分页拉取【当月】全部考勤异常数据,导出为 Excel;
|
||||
并按规则(迟到/早退 >=30 分钟,或其他类型异常)向对应员工姓名推送钉钉核实通知。
|
||||
底层能力复用:接口调用(hr_api.py)、会话管理(session_manager.py)、接口地址(config.py)。
|
||||
@Version: 2.0.0
|
||||
|
||||
使用说明:
|
||||
1. 首次运行会调用 HR 登录模块(login.py)完成登录并缓存 cookies 到 .sessions/hr_cookies.json;
|
||||
后续运行自动复用缓存,登录态过期会自动重新登录。
|
||||
2. 直接运行本文件即可查询当月考勤异常并导出 Excel。
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
from typing import Dict, List
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
|
||||
# 底层复用:接口调用 / 会话管理
|
||||
from app.service.hrbp.ehr.common.hr_api import ( # noqa: E402
|
||||
fetch_cur_user_info,
|
||||
fetch_all_attendance_abnormal,
|
||||
# adjust_abnormal, # 自动确认异常能力暂未启用,需要时取消注释
|
||||
HRSessionExpiredError,
|
||||
)
|
||||
from app.service.hrbp.ehr.common.session_manager import ( # noqa: E402
|
||||
build_hr_session,
|
||||
refresh_hr_session,
|
||||
)
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
pd = None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ===================== 配置区(自行修改) =====================
|
||||
# 默认保存目录
|
||||
SAVE_DIR = r"D:\资料\人资\考勤异常"
|
||||
|
||||
# 英文字段 → 中文字段映射(aa.md 提供的考勤异常字段,其余字段保留原样)
|
||||
COL_MAP: Dict[str, str] = {
|
||||
"abnormal_id": "异常ID",
|
||||
"STAFF_NAME": "员工姓名",
|
||||
"base_code": "工号",
|
||||
"work_day": "考勤日期",
|
||||
"bc_name": "班次",
|
||||
"abnormal": "异常类型",
|
||||
"abnormal_minute": "异常时长(分钟)",
|
||||
}
|
||||
|
||||
# 自定义列展示顺序(核心字段放最前面,其余字段自动排在后面)
|
||||
SHOW_ORDER = [
|
||||
"异常ID", "员工姓名", "工号", "考勤日期", "班次", "异常类型", "异常时长(分钟)",
|
||||
]
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 1. 当月查询范围(每次默认查询当月)
|
||||
# ----------------------------------------------
|
||||
def current_month_range(today: date = None) -> tuple:
|
||||
"""返回当月的查询日期范围,返回 (开始日期, 结束日期)。
|
||||
开始日期 = 当月 1 日,结束日期 = 今天。
|
||||
"""
|
||||
today = today or date.today()
|
||||
begin = today.replace(day=1)
|
||||
return begin.strftime("%Y-%m-%d"), today.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 2. cookies 有效性校验(员工基础信息接口)
|
||||
# ----------------------------------------------
|
||||
def _validate_session(session):
|
||||
"""调用 getCurUserInfo 校验 cookies 有效性,并返回 (session, user_id, treecode)。
|
||||
若登录态过期则重新登录并重建会话后重试。
|
||||
"""
|
||||
try:
|
||||
info = fetch_cur_user_info(session)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("cookies 已失效,正在重新登录")
|
||||
session = refresh_hr_session()
|
||||
info = fetch_cur_user_info(session)
|
||||
user_id = info.get("userId", "")
|
||||
treecode = info.get("rootId", "")
|
||||
if not user_id or not treecode:
|
||||
raise RuntimeError(f"员工基础信息接口未返回 userId/rootId:{info}")
|
||||
logger.info("cookies 校验通过,user_id=%s,treecode=%s", user_id, treecode)
|
||||
return session, user_id, treecode
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 3. 导出当月考勤异常 Excel
|
||||
# ----------------------------------------------
|
||||
def export_excel(data: List[dict], save_dir: str, month_str: str) -> str:
|
||||
"""将考勤异常数据映射为中文、调整列顺序并导出 .xlsx。"""
|
||||
if pd is None:
|
||||
raise RuntimeError("缺少 pandas 依赖,无法导出 Excel")
|
||||
if not data:
|
||||
raise ValueError("未查询到任何考勤异常数据,无法导出")
|
||||
|
||||
df = pd.DataFrame(data)
|
||||
# 替换英文列为中文
|
||||
df.rename(columns=COL_MAP, inplace=True)
|
||||
# 过滤表中实际存在的列,再拼接剩余其他字段
|
||||
exist_cols = [col for col in SHOW_ORDER if col in df.columns]
|
||||
other_cols = [col for col in df.columns if col not in exist_cols]
|
||||
df = df[exist_cols + other_cols]
|
||||
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
save_path = os.path.abspath(os.path.join(save_dir, f"考勤异常_{month_str}.xlsx"))
|
||||
df.to_excel(save_path, index=False)
|
||||
logger.info("考勤异常数据:%d 条", len(data))
|
||||
logger.info("文件已保存:%s", save_path)
|
||||
return save_path
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 4. 筛选 + 钉钉推送(按姓名)
|
||||
# ----------------------------------------------
|
||||
def classify_abnormal(item: dict) -> bool:
|
||||
"""判断该条异常是否需要钉钉推送。
|
||||
|
||||
规则(需求):
|
||||
- 迟到/早退 且 异常时长 < 30 分钟 → 不推送(轻微异常);
|
||||
- 迟到/早退 且 异常时长 >= 30 分钟 → 推送;
|
||||
- 其他类型异常(旷工/工时不足/漏打卡等)→ 推送。
|
||||
"""
|
||||
abnormal = str(item.get("abnormal", ""))
|
||||
try:
|
||||
minute = int(item.get("abnormal_minute", 0) or 0)
|
||||
except (TypeError, ValueError):
|
||||
minute = 0
|
||||
if ("迟到" in abnormal or "早退" in abnormal) and minute < 30:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def build_notify_text(item: dict) -> str:
|
||||
"""按需求格式拼接钉钉通知文本。
|
||||
|
||||
确认行按实际异常类型动态生成:查出什么类型就写什么类型;
|
||||
迟到/早退会在确认项前附上分钟数。
|
||||
"""
|
||||
abnormal = str(item.get("abnormal", "") or "").strip() or "考勤异常"
|
||||
minute = item.get("abnormal_minute")
|
||||
# 迟到/早退 附上分钟数
|
||||
if ("迟到" in abnormal or "早退" in abnormal) and minute not in ("", None):
|
||||
confirm_item = f"{abnormal}{minute}分钟"
|
||||
else:
|
||||
confirm_item = abnormal
|
||||
return (
|
||||
"【考勤异常核实通知】\n"
|
||||
f"姓名:{item.get('STAFF_NAME', '')}\n"
|
||||
f"工号:{item.get('base_code', '')}\n"
|
||||
f"考勤日期:{item.get('work_day', '')}\n"
|
||||
f"班次:{item.get('bc_name', '')}\n"
|
||||
f"异常类型:{abnormal}\n"
|
||||
f"异常时长:{minute}分钟\n"
|
||||
f"请确认本次{confirm_item}真实情况:{abnormal}/漏打卡/外出/其他"
|
||||
)
|
||||
|
||||
|
||||
def push_abnormal(items: List[dict]) -> None:
|
||||
"""逐条生成钉钉通知文本(暂不实际发送,先供人工确认)。
|
||||
|
||||
当前仅打印通知文本;确认无误后,取消下方 send_to_person 的注释即可启用推送。
|
||||
"""
|
||||
from app.utils.dingtalk_sender import send_to_person # noqa: F401
|
||||
|
||||
for it in items:
|
||||
name = it.get("STAFF_NAME", "") or ""
|
||||
if not name:
|
||||
logger.warning("异常记录缺少姓名,跳过:%s", it)
|
||||
continue
|
||||
text = build_notify_text(it)
|
||||
# 先注释掉实际推送,仅输出文本供确认
|
||||
logger.info("【待推送通知】\n%s", text)
|
||||
# send_to_person(name, text=text)
|
||||
# logger.info("已向 %s 推送考勤异常通知", name)
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 5. 内部抓取(供下载/处理共用)
|
||||
# ----------------------------------------------
|
||||
def _fetch_abnormal_data(month: str = None) -> tuple:
|
||||
"""校验会话、计算查询范围、拉取当月考勤异常数据。
|
||||
|
||||
Returns:
|
||||
(data, month_str):data 为异常明细列表,month_str 为查询月份 "YYYY-MM"
|
||||
"""
|
||||
session = build_hr_session()
|
||||
# 校验 cookies 有效性,并获取查询所需 user_id / treecode
|
||||
session, user_id, treecode = _validate_session(session)
|
||||
|
||||
# 计算查询范围:默认当月
|
||||
if month:
|
||||
begin = f"{month}-01"
|
||||
end = f"{month}-31"
|
||||
month_str = month
|
||||
else:
|
||||
begin, end = current_month_range()
|
||||
month_str = date.today().strftime("%Y-%m")
|
||||
logger.info("===== 查询考勤异常日期范围:%s ~ %s =====", begin, end)
|
||||
|
||||
data = fetch_all_attendance_abnormal(session, user_id, treecode, begin, end)
|
||||
return data, month_str
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 6. 对外便捷入口
|
||||
# ----------------------------------------------
|
||||
# ---- 自动确认异常能力暂未启用,需要时取消以下注释 ----
|
||||
# def confirm_abnormal(abnormal_ids, type_code: int = 1, session=None):
|
||||
# """确认/调整考勤异常单据(按 abnormal_id 唯一编号)。
|
||||
#
|
||||
# Args:
|
||||
# abnormal_ids: 异常单据 id,可为单个 id 或 id 列表
|
||||
# type_code: 处理类型,1=自动确认异常(默认)
|
||||
# session: 已登录会话;为空时自动构建并校验
|
||||
#
|
||||
# Returns:
|
||||
# 接口返回的 JSON 字典(state=1 表示处理成功)
|
||||
# """
|
||||
# if session is None:
|
||||
# session = build_hr_session()
|
||||
# session, _, _ = _validate_session(session)
|
||||
# return adjust_abnormal(session, abnormal_ids, type_code)
|
||||
|
||||
|
||||
def download_attendance_abnormal(save_dir: str = None, month: str = None) -> str:
|
||||
"""查询当月考勤异常并导出 Excel,返回导出文件路径。
|
||||
|
||||
Args:
|
||||
save_dir: 保存目录,默认 SAVE_DIR
|
||||
month: 查询月份 "YYYY-MM"(默认当月)。传该参数时查询整个月,
|
||||
不传则按「当月 1 日 至 今天」查询。
|
||||
"""
|
||||
save_dir = save_dir or SAVE_DIR
|
||||
data, month_str = _fetch_abnormal_data(month)
|
||||
if not data:
|
||||
logger.info("当月无考勤异常数据")
|
||||
return None
|
||||
return export_excel(data, save_dir, month_str)
|
||||
|
||||
|
||||
def handle_attendance_abnormal(save_dir: str = None, month: str = None) -> str:
|
||||
"""查询当月考勤异常,导出 Excel,并按要求向钉钉推送需核实的异常。
|
||||
|
||||
推送规则见 classify_abnormal:迟到/早退 >= 30 分钟,或其他类型异常,按姓名推送。
|
||||
|
||||
Args:
|
||||
save_dir: 保存目录,默认 SAVE_DIR
|
||||
month: 查询月份 "YYYY-MM"(默认当月)
|
||||
|
||||
Returns:
|
||||
导出文件路径(无数据时返回 None)
|
||||
"""
|
||||
save_dir = save_dir or SAVE_DIR
|
||||
data, month_str = _fetch_abnormal_data(month)
|
||||
if not data:
|
||||
logger.info("当月无考勤异常数据,跳过导出与推送")
|
||||
return None
|
||||
|
||||
path = export_excel(data, save_dir, month_str)
|
||||
|
||||
push_list = [it for it in data if classify_abnormal(it)]
|
||||
handled_count = len(data) - len(push_list)
|
||||
logger.info("考勤异常共 %d 条:需推送 %d 条,轻微异常(迟到/早退<30分钟,直接处理) %d 条",
|
||||
len(data), len(push_list), handled_count)
|
||||
if push_list:
|
||||
push_abnormal(push_list)
|
||||
else:
|
||||
logger.info("无需推送的异常,跳过钉钉通知")
|
||||
|
||||
# ---- 最终统计汇总 ----
|
||||
logger.info("=" * 60)
|
||||
logger.info("【考勤异常处理汇总】")
|
||||
logger.info(" 考勤异常总数:%d 条", len(data))
|
||||
logger.info(" 直接处理(轻微,无需通知):%d 条", handled_count)
|
||||
logger.info(" 待通知(需核实推送):%d 条", len(push_list))
|
||||
logger.info(" 导出文件:%s", path)
|
||||
logger.info("=" * 60)
|
||||
return path
|
||||
|
||||
|
||||
def main() -> None:
|
||||
setup_logging()
|
||||
save_dir = sys.argv[1] if len(sys.argv) > 1 else SAVE_DIR
|
||||
month = sys.argv[2] if len(sys.argv) > 2 else None
|
||||
try:
|
||||
out = handle_attendance_abnormal(save_dir, month)
|
||||
if out:
|
||||
logger.info("===== 考勤异常处理完成,导出:%s =====", out)
|
||||
else:
|
||||
logger.info("===== 考勤异常处理完成:当月无数据 =====")
|
||||
except Exception as e:
|
||||
logger.error("考勤异常处理失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 142 KiB After Width: | Height: | Size: 72 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 166 KiB After Width: | Height: | Size: 83 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 9.7 KiB After Width: | Height: | Size: 4.3 KiB |
@@ -21,3 +21,22 @@ ROSTER_URL = "https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic#ajax&
|
||||
|
||||
# 花名册默认导出的自定义模板名称
|
||||
ROSTER_TEMPLATE_NAME = "员工基础信息"
|
||||
|
||||
# ---------- 考勤异常查询接口 ----------
|
||||
# 获取当前用户信息(用于校验 cookies 有效性,并取得查询考勤异常所需的 userId / rootId(treecode))
|
||||
GET_CUR_USER_INFO_URL = "https://hr.37du.co/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
|
||||
# 分页查询考勤异常(aa.md 提供)
|
||||
ATTENDANCE_ABNORMAL_URL = "https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc"
|
||||
|
||||
# 考勤异常确认/调整接口(abnormalIds=异常单据id,type=1 表示自动确认)
|
||||
ATTENDANCE_ADJUST_URL = "https://hr.37du.co/RedseaPlatform/abnormalAdjust/KqCountAbnormal.mc"
|
||||
|
||||
# 查询排班接口(aa.md 提供,用于过滤虚假异常)
|
||||
SHIFT_URL = "https://hr.37du.co/RedseaPlatform/redmagicapi/rf_p_kq_count_SelectBanci/getExecutePageResult.mc"
|
||||
|
||||
# 查询请假记录接口(aa.md 提供,用于过滤虚假异常)
|
||||
LEAVE_URL = "https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc"
|
||||
|
||||
# 查询加班记录接口(aa.md 提供,用于过滤虚假异常)
|
||||
OVERTIME_URL = "https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc"
|
||||
|
||||
@@ -12,7 +12,16 @@ import time
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
from app.service.hrbp.ehr.common.config import WAGE_CARD_URL, PAGE_MAX_SIZE
|
||||
from app.service.hrbp.ehr.common.config import (
|
||||
WAGE_CARD_URL,
|
||||
PAGE_MAX_SIZE,
|
||||
GET_CUR_USER_INFO_URL,
|
||||
ATTENDANCE_ABNORMAL_URL,
|
||||
ATTENDANCE_ADJUST_URL,
|
||||
SHIFT_URL,
|
||||
LEAVE_URL,
|
||||
OVERTIME_URL,
|
||||
)
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
@@ -138,3 +147,558 @@ def fetch_all_wage_card(
|
||||
page_no += 1
|
||||
time.sleep(0.2) # 轻微限速,避免触发风控
|
||||
return all_rows
|
||||
|
||||
|
||||
def adjust_abnormal(
|
||||
session,
|
||||
abnormal_ids,
|
||||
type_code: int = 1,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
确认/调整考勤异常单据。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
abnormal_ids: 异常单据唯一编号 abnormal_id,可为单个 id 或 id 列表
|
||||
type_code: 处理类型,1=自动确认异常(按接口约定)
|
||||
|
||||
Returns:
|
||||
接口返回的 JSON 字典(state=1 表示处理成功)
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
HRSessionExpiredError: 登录态过期(接口返回非 JSON)
|
||||
"""
|
||||
if isinstance(abnormal_ids, (list, tuple)):
|
||||
ids = ",".join(str(i) for i in abnormal_ids)
|
||||
else:
|
||||
ids = str(abnormal_ids)
|
||||
|
||||
params = {"abnormalIds": ids, "type": type_code}
|
||||
resp = session.post(ATTENDANCE_ADJUST_URL, data=params, timeout=20)
|
||||
if not resp:
|
||||
raise RuntimeError("考勤异常确认请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"考勤异常确认接口状态码异常: {resp.status_code}")
|
||||
if _is_expired(resp.text):
|
||||
raise HRSessionExpiredError("HR 登录态已过期,考勤异常确认接口返回非 JSON 内容")
|
||||
try:
|
||||
return resp.json()
|
||||
except Exception:
|
||||
body = (resp.text or "")[:200]
|
||||
raise RuntimeError(f"考勤异常确认接口返回非 JSON 数据(状态码 {resp.status_code}): {body}")
|
||||
|
||||
|
||||
# ---------- 考勤异常查询接口 ----------
|
||||
def fetch_cur_user_info(session) -> Dict[str, Any]:
|
||||
"""
|
||||
调用 getCurUserInfo 校验 cookies 有效性,并返回当前登录用户信息。
|
||||
|
||||
该接口同时返回查询考勤异常所需的 userId 与 rootId(treecode):
|
||||
- 正常返回 JSON(含 userId / rootId),说明 cookies 有效;
|
||||
- 返回登录页等非 JSON 内容,说明登录态过期。
|
||||
|
||||
Returns:
|
||||
接口返回的 JSON 字典(含 userId / rootId 等字段)
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
HRSessionExpiredError: 登录态过期(接口返回非 JSON)
|
||||
"""
|
||||
resp = session.post(GET_CUR_USER_INFO_URL, timeout=20)
|
||||
if not resp:
|
||||
raise RuntimeError("获取当前用户信息失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"获取当前用户信息状态码异常: {resp.status_code}")
|
||||
if _is_expired(resp.text):
|
||||
raise HRSessionExpiredError("HR 登录态已过期,getCurUserInfo 接口返回非 JSON 内容")
|
||||
try:
|
||||
return resp.json()
|
||||
except Exception:
|
||||
body = (resp.text or "")[:200]
|
||||
raise RuntimeError(f"获取当前用户信息返回非 JSON 数据(状态码 {resp.status_code}): {body}")
|
||||
|
||||
|
||||
def fetch_attendance_abnormal_page(
|
||||
session,
|
||||
user_id: str,
|
||||
treecode: str,
|
||||
begin_date: str,
|
||||
end_date: str,
|
||||
page_no: int = 1,
|
||||
page_size: int = PAGE_MAX_SIZE,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
请求单页考勤异常数据(aa.md 提供的接口入参)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
user_id / treecode: 由 getCurUserInfo 返回的 userId / rootId
|
||||
begin_date / end_date: 查询日期范围 "YYYY-MM-DD"(当月)
|
||||
page_no: 页码(从 1 开始)
|
||||
page_size: 每页条数
|
||||
|
||||
Returns:
|
||||
接口返回的 JSON 字典(datas 为明细数组,pageCount 为总页数)
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
HRSessionExpiredError: 登录态过期(接口返回非 JSON)
|
||||
"""
|
||||
params = {
|
||||
"treecode": treecode,
|
||||
"user_id": user_id,
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"sqlId": "kq_count_abnormal_Select",
|
||||
"redapiId": "rf_p_kq_count_abnormal_Select",
|
||||
"treeCodeList": "",
|
||||
"abnormal_type": "",
|
||||
"base_code": "",
|
||||
"join_date": "",
|
||||
"join_date_end": end_date,
|
||||
"person_status": "",
|
||||
"staff_id": "",
|
||||
"post_no": "",
|
||||
"post_type": "1",
|
||||
"period_order": "",
|
||||
"identity_test": "",
|
||||
"identity": "",
|
||||
"sex": "",
|
||||
"age": "",
|
||||
"age_end": "",
|
||||
"start_operat_time": "",
|
||||
"end_operat_time": "",
|
||||
"operator_username": "",
|
||||
"operator_userid": "",
|
||||
"is_adjusted": "",
|
||||
"begin_date": begin_date,
|
||||
"end_date": end_date,
|
||||
"STAFF_NAME": "",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "desc",
|
||||
"sortName": "work_day",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
resp = session.post(ATTENDANCE_ABNORMAL_URL, data=params, timeout=20)
|
||||
if not resp:
|
||||
raise RuntimeError("考勤异常请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"考勤异常接口状态码异常: {resp.status_code}")
|
||||
if _is_expired(resp.text):
|
||||
raise HRSessionExpiredError("HR 登录态已过期,考勤异常接口返回非 JSON 内容")
|
||||
try:
|
||||
return resp.json()
|
||||
except Exception:
|
||||
body = (resp.text or "")[:200]
|
||||
raise RuntimeError(f"考勤异常接口返回非 JSON 数据(状态码 {resp.status_code}): {body}")
|
||||
|
||||
|
||||
def fetch_all_attendance_abnormal(
|
||||
session,
|
||||
user_id: str,
|
||||
treecode: str,
|
||||
begin_date: str,
|
||||
end_date: str,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
分页抓取指定日期范围内的全部考勤异常数据。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
user_id / treecode: 由 getCurUserInfo 返回的 userId / rootId
|
||||
begin_date / end_date: 查询日期范围 "YYYY-MM-DD"
|
||||
|
||||
Returns:
|
||||
异常明细列表(接口 datas 字段内容)
|
||||
|
||||
Raises:
|
||||
HRSessionExpiredError: 登录态过期且重新登录后仍失败
|
||||
"""
|
||||
all_rows: List[Dict[str, Any]] = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_attendance_abnormal_page(
|
||||
session, user_id, treecode, begin_date, end_date, page_no, PAGE_MAX_SIZE
|
||||
)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("考勤异常 HR 登录态过期,重新登录后续抓")
|
||||
from app.service.hrbp.ehr.common.session_manager import refresh_hr_session
|
||||
session = refresh_hr_session()
|
||||
# 重新登录后需重新获取 user_id / treecode
|
||||
info = fetch_cur_user_info(session)
|
||||
user_id = info.get("userId", "")
|
||||
treecode = info.get("rootId", "")
|
||||
data = fetch_attendance_abnormal_page(
|
||||
session, user_id, treecode, begin_date, end_date, page_no, PAGE_MAX_SIZE
|
||||
)
|
||||
|
||||
if data.get("state") != "1":
|
||||
logger.error("考勤异常第%d页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("考勤异常无更多数据")
|
||||
break
|
||||
|
||||
all_rows.extend(page_list)
|
||||
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("考勤异常已抓取 %d/%d 页,累计 %d 条",
|
||||
page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2) # 轻微限速,避免触发风控
|
||||
return all_rows
|
||||
|
||||
|
||||
# ---------- 查询排班接口(用于过滤虚假异常,暂未在主流程调用) ----------
|
||||
def fetch_shift_page(
|
||||
session,
|
||||
user_id: str,
|
||||
base_code: str,
|
||||
begin_date: str,
|
||||
end_date: str,
|
||||
treecode: str = "cq37du",
|
||||
page_no: int = 1,
|
||||
page_size: int = PAGE_MAX_SIZE,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
请求单页排班数据(aa.md 提供的接口入参)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
user_id: 由 getCurUserInfo 返回的 userId
|
||||
base_code: 员工工号
|
||||
begin_date / end_date: 查询日期范围 "YYYY-MM-DD"
|
||||
treecode: 组织树编码,默认 cq37du
|
||||
page_no / page_size: 分页参数
|
||||
|
||||
Returns:
|
||||
接口返回的 JSON 字典(datas 为排班明细数组)
|
||||
"""
|
||||
params = {
|
||||
"treecode": treecode,
|
||||
"user_id": user_id,
|
||||
"sqlId": "kq_count_SelectBanci",
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"staff_ids": "",
|
||||
"person_status": "1,4",
|
||||
"post_no": "",
|
||||
"post_type": "1",
|
||||
"post_level": "",
|
||||
"identity": "",
|
||||
"showType": "1",
|
||||
"dateType": "2",
|
||||
"begin": begin_date,
|
||||
"end": end_date,
|
||||
"bc_date": begin_date,
|
||||
"base_code": base_code,
|
||||
"staff_name": "",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
resp = session.post(SHIFT_URL, data=params, timeout=20)
|
||||
if not resp:
|
||||
raise RuntimeError("排班请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"排班接口状态码异常: {resp.status_code}")
|
||||
if _is_expired(resp.text):
|
||||
raise HRSessionExpiredError("HR 登录态已过期,排班接口返回非 JSON 内容")
|
||||
try:
|
||||
return resp.json()
|
||||
except Exception:
|
||||
body = (resp.text or "")[:200]
|
||||
raise RuntimeError(f"排班接口返回非 JSON 数据(状态码 {resp.status_code}): {body}")
|
||||
|
||||
|
||||
def fetch_all_shift(
|
||||
session,
|
||||
user_id: str,
|
||||
base_code: str,
|
||||
begin_date: str,
|
||||
end_date: str,
|
||||
treecode: str = "cq37du",
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""分页抓取指定工号、日期范围内的全部排班数据。"""
|
||||
all_rows: List[Dict[str, Any]] = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_shift_page(
|
||||
session, user_id, base_code, begin_date, end_date,
|
||||
treecode, page_no, PAGE_MAX_SIZE,
|
||||
)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("排班 HR 登录态过期,重新登录后续抓")
|
||||
from app.service.hrbp.ehr.common.session_manager import refresh_hr_session
|
||||
session = refresh_hr_session()
|
||||
info = fetch_cur_user_info(session)
|
||||
user_id = info.get("userId", "")
|
||||
data = fetch_shift_page(
|
||||
session, user_id, base_code, begin_date, end_date,
|
||||
treecode, page_no, PAGE_MAX_SIZE,
|
||||
)
|
||||
|
||||
if data.get("state") != "1":
|
||||
logger.error("排班第%d页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("排班无更多数据")
|
||||
break
|
||||
|
||||
all_rows.extend(page_list)
|
||||
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("排班已抓取 %d/%d 页,累计 %d 条",
|
||||
page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
# ---------- 查询请假记录接口(用于过滤虚假异常,暂未在主流程调用) ----------
|
||||
def fetch_leave_page(
|
||||
session,
|
||||
user_id: str,
|
||||
base_code: str,
|
||||
start_time: str,
|
||||
end_time: str,
|
||||
treecode: str = "cq37du",
|
||||
page_no: int = 1,
|
||||
page_size: int = PAGE_MAX_SIZE,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
请求单页请假记录数据(aa.md 提供的接口入参)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
user_id: 由 getCurUserInfo 返回的 userId
|
||||
base_code: 员工工号
|
||||
start_time / end_time: 查询日期范围 "YYYY-MM-DD"
|
||||
treecode: 组织树编码,默认 cq37du
|
||||
page_no / page_size: 分页参数
|
||||
|
||||
Returns:
|
||||
接口返回的 JSON 字典(datas 为请假记录数组)
|
||||
"""
|
||||
params = {
|
||||
"STRU_TREE_CODE": treecode,
|
||||
"user_id": user_id,
|
||||
"begin_date": "",
|
||||
"end_date": "",
|
||||
"sqlId": "select_kqLeave_record",
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"post_no": "",
|
||||
"source": "",
|
||||
"person_status": "",
|
||||
"staff_id": "",
|
||||
"staffNames": "",
|
||||
"post_type": "1",
|
||||
"processing_reason": "",
|
||||
"processing_date": "",
|
||||
"start_operat_time": "",
|
||||
"end_operat_time": "",
|
||||
"orgAlias": "",
|
||||
"dept_ids": "",
|
||||
"base_code": base_code,
|
||||
"staff_name": "",
|
||||
"start_time": start_time,
|
||||
"end_time": end_time,
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "desc",
|
||||
"sortName": "operat_time",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
resp = session.post(LEAVE_URL, data=params, timeout=20)
|
||||
if not resp:
|
||||
raise RuntimeError("请假查询请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"请假查询接口状态码异常: {resp.status_code}")
|
||||
if _is_expired(resp.text):
|
||||
raise HRSessionExpiredError("HR 登录态已过期,请假查询接口返回非 JSON 内容")
|
||||
try:
|
||||
return resp.json()
|
||||
except Exception:
|
||||
body = (resp.text or "")[:200]
|
||||
raise RuntimeError(f"请假查询接口返回非 JSON 数据(状态码 {resp.status_code}): {body}")
|
||||
|
||||
|
||||
def fetch_all_leave(
|
||||
session,
|
||||
user_id: str,
|
||||
base_code: str,
|
||||
start_time: str,
|
||||
end_time: str,
|
||||
treecode: str = "cq37du",
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""分页抓取指定工号、日期范围内的全部请假记录。"""
|
||||
all_rows: List[Dict[str, Any]] = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_leave_page(
|
||||
session, user_id, base_code, start_time, end_time,
|
||||
treecode, page_no, PAGE_MAX_SIZE,
|
||||
)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("请假查询 HR 登录态过期,重新登录后续抓")
|
||||
from app.service.hrbp.ehr.common.session_manager import refresh_hr_session
|
||||
session = refresh_hr_session()
|
||||
info = fetch_cur_user_info(session)
|
||||
user_id = info.get("userId", "")
|
||||
data = fetch_leave_page(
|
||||
session, user_id, base_code, start_time, end_time,
|
||||
treecode, page_no, PAGE_MAX_SIZE,
|
||||
)
|
||||
|
||||
if data.get("state") != "1":
|
||||
logger.error("请假查询第%d页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("请假查询无更多数据")
|
||||
break
|
||||
|
||||
all_rows.extend(page_list)
|
||||
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("请假查询已抓取 %d/%d 页,累计 %d 条",
|
||||
page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
# ---------- 查询加班记录接口(用于过滤虚假异常,暂未在主流程调用) ----------
|
||||
def fetch_overtime_page(
|
||||
session,
|
||||
user_id: str,
|
||||
base_code: str,
|
||||
start_time: str,
|
||||
end_time: str,
|
||||
treecode: str = "cq37du",
|
||||
page_no: int = 1,
|
||||
page_size: int = PAGE_MAX_SIZE,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
请求单页加班记录数据(aa.md 提供的接口入参)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
user_id: 由 getCurUserInfo 返回的 userId
|
||||
base_code: 员工工号
|
||||
start_time / end_time: 查询日期范围 "YYYY-MM-DD"
|
||||
treecode: 组织树编码,默认 cq37du
|
||||
page_no / page_size: 分页参数
|
||||
|
||||
Returns:
|
||||
接口返回的 JSON 字典(datas 为加班记录数组)
|
||||
"""
|
||||
params = {
|
||||
"STRU_TREE_CODE": treecode,
|
||||
"user_id": user_id,
|
||||
"sqlId": "kq_overtime_detail_select",
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"BPM_STATUS": "",
|
||||
"post_no": "",
|
||||
"postName": "",
|
||||
"source": "",
|
||||
"IS_SUBSIDY": "",
|
||||
"person_status": "",
|
||||
"staff_id": "",
|
||||
"staffNames": "",
|
||||
"post_type": "1",
|
||||
"processing_reason": "",
|
||||
"start_operat_time": "",
|
||||
"end_operat_time": "",
|
||||
"base_code": base_code,
|
||||
"staff_name": "",
|
||||
"WORK_OVERTIME_TYPE": "",
|
||||
"start_time": start_time,
|
||||
"end_time": end_time,
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "desc",
|
||||
"sortName": "OPERATE_TIME",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
resp = session.post(OVERTIME_URL, data=params, timeout=20)
|
||||
if not resp:
|
||||
raise RuntimeError("加班查询请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"加班查询接口状态码异常: {resp.status_code}")
|
||||
if _is_expired(resp.text):
|
||||
raise HRSessionExpiredError("HR 登录态已过期,加班查询接口返回非 JSON 内容")
|
||||
try:
|
||||
return resp.json()
|
||||
except Exception:
|
||||
body = (resp.text or "")[:200]
|
||||
raise RuntimeError(f"加班查询接口返回非 JSON 数据(状态码 {resp.status_code}): {body}")
|
||||
|
||||
|
||||
def fetch_all_overtime(
|
||||
session,
|
||||
user_id: str,
|
||||
base_code: str,
|
||||
start_time: str,
|
||||
end_time: str,
|
||||
treecode: str = "cq37du",
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""分页抓取指定工号、日期范围内的全部加班记录。"""
|
||||
all_rows: List[Dict[str, Any]] = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_overtime_page(
|
||||
session, user_id, base_code, start_time, end_time,
|
||||
treecode, page_no, PAGE_MAX_SIZE,
|
||||
)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("加班查询 HR 登录态过期,重新登录后续抓")
|
||||
from app.service.hrbp.ehr.common.session_manager import refresh_hr_session
|
||||
session = refresh_hr_session()
|
||||
info = fetch_cur_user_info(session)
|
||||
user_id = info.get("userId", "")
|
||||
data = fetch_overtime_page(
|
||||
session, user_id, base_code, start_time, end_time,
|
||||
treecode, page_no, PAGE_MAX_SIZE,
|
||||
)
|
||||
|
||||
if data.get("state") != "1":
|
||||
logger.error("加班查询第%d页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("加班查询无更多数据")
|
||||
break
|
||||
|
||||
all_rows.extend(page_list)
|
||||
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("加班查询已抓取 %d/%d 页,累计 %d 条",
|
||||
page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
@@ -37,10 +37,31 @@ logger = get_logger(__name__)
|
||||
|
||||
# ===================== 银行卡校验规则 =====================
|
||||
# 固定通用规则,无需随表格修改
|
||||
# 必须16位的BIN
|
||||
BIN_16 = {"621483", "622622", "621691", "622619", "622620"}
|
||||
# 必须18位的BIN
|
||||
BIN_18 = {"622908"}
|
||||
# 16 位银联卡 BIN(按银行归类,经实际工资卡数据比对核验)
|
||||
BIN_16 = {
|
||||
# 招商银行
|
||||
"621483", "621485", "621486", "622588", "622609",
|
||||
# 民生银行
|
||||
"621691", "622615", "622617", "622619", "622620", "622622",
|
||||
# 民生银行信用卡(16 位贷记卡)
|
||||
"622601",
|
||||
# 重庆农村商业银行
|
||||
"621258", "621465", "621528", "622867",
|
||||
# 浦东发展银行
|
||||
"621792", "621793", "622521",
|
||||
# 其他银行
|
||||
"621499", # 建设银行理财金卡
|
||||
"621755", # 重庆三峡银行
|
||||
"623020", # 华夏银行
|
||||
}
|
||||
# 18 位银联储蓄卡 BIN
|
||||
BIN_18 = {"622908"} # 兴业银行
|
||||
# 非 62 开头但合法的老版储蓄卡 BIN(历史卡仍在使用,标准均为 19 位)
|
||||
NON62_BIN = {
|
||||
"436742", # 建设银行龙卡储蓄卡
|
||||
"601382", # 中国银行长城电子借记卡
|
||||
"955882", # 工商银行牡丹灵通卡
|
||||
}
|
||||
# 正则:匹配全数字
|
||||
NUM_REG = re.compile(r"^\d+$")
|
||||
|
||||
@@ -64,18 +85,17 @@ def check_bank_card(card_raw) -> dict:
|
||||
if not NUM_REG.match(card):
|
||||
return {"card": card, "status": "无效", "reason": "非纯数字,属于文字备注/脏数据"}
|
||||
|
||||
if not card.startswith("62"):
|
||||
bin6 = card[:6]
|
||||
if not (card.startswith("62") or bin6 in NON62_BIN):
|
||||
return {"card": card, "status": "无效", "reason": "非62开头,非标准银联储蓄卡"}
|
||||
|
||||
card_len = len(card)
|
||||
if card_len not in (16, 18, 19):
|
||||
return {"card": card, "status": "错误", "reason": f"位数异常{card_len}位,仅支持16/18/19位银行卡"}
|
||||
|
||||
bin6 = card[:6]
|
||||
|
||||
if bin6 in BIN_16:
|
||||
if card_len == 16:
|
||||
return {"card": card, "status": "正常", "reason": "合规16位储蓄卡"}
|
||||
return {"card": card, "status": "正常", "reason": "合规16位银联卡"}
|
||||
else:
|
||||
return {"card": card, "status": "错误", "reason": f"BIN{bin6}标准16位,录入位数错误"}
|
||||
|
||||
@@ -91,6 +111,55 @@ def check_bank_card(card_raw) -> dict:
|
||||
return {"card": card, "status": "错误", "reason": f"BIN{bin6}标准19位,录入位数错误,需人工核对"}
|
||||
|
||||
|
||||
# ===================== 核对分类 =====================
|
||||
def classify_card_issue(idcard, card_idcard, staff_name, card_name, bank_account):
|
||||
"""按 4 类异常对单条工资卡记录分类。
|
||||
|
||||
返回 (issues, basis, id_inconsistent, bank_info)
|
||||
issues: 4 类异常标签(写入核对结果)
|
||||
basis : 详细校验依据(写入校验依据)
|
||||
1. 开户人信息或银行卡空白
|
||||
2. 员工身份证与开户人身份证不一致
|
||||
3. 员工姓名与开户人姓名不一致(仅身份证一致时比对)
|
||||
4. 银行卡信息异常(银行卡非空但格式/位数错误)
|
||||
"""
|
||||
issues = []
|
||||
basis = []
|
||||
bank_info = None
|
||||
|
||||
# ---- 1. 开户人信息或银行卡空白 ----
|
||||
if _is_empty(card_idcard):
|
||||
issues.append("开户人身份证空白")
|
||||
basis.append("开户人身份证空白")
|
||||
if _is_empty(card_name):
|
||||
issues.append("开户人姓名空白")
|
||||
basis.append("开户人姓名空白")
|
||||
if _is_empty(bank_account):
|
||||
issues.append("银行卡空白")
|
||||
basis.append("银行卡空白")
|
||||
|
||||
# ---- 2. 身份证不一致(开户人身份证非空且与员工不一致) ----
|
||||
id_inconsistent = (not _is_empty(card_idcard)) and idcard != card_idcard
|
||||
if id_inconsistent:
|
||||
issues.append("员工身份证与开户人身份证不一致")
|
||||
basis.append(f"身份证不一致(员工:{idcard} vs 开户人:{card_idcard})")
|
||||
|
||||
# ---- 3. 姓名不一致(仅身份证一致时比对) ----
|
||||
if (not id_inconsistent and not _is_empty(card_idcard)
|
||||
and not _is_empty(card_name) and staff_name != card_name):
|
||||
issues.append("员工姓名与开户人姓名不一致")
|
||||
basis.append(f"姓名不一致(员工:{staff_name} vs 开户人:{card_name})")
|
||||
|
||||
# ---- 4. 银行卡信息异常(银行卡非空但格式/位数错误) ----
|
||||
if not _is_empty(bank_account):
|
||||
bank_info = check_bank_card(bank_account)
|
||||
if bank_info["status"] != "正常":
|
||||
issues.append("银行卡信息异常")
|
||||
basis.append(f"银行卡信息异常({bank_info['reason']})")
|
||||
|
||||
return issues, basis, id_inconsistent, bank_info
|
||||
|
||||
|
||||
# ===================== 列名常量 =====================
|
||||
COL_IDCARD = "身份证号"
|
||||
COL_CARD_IDCARD = "开户人身份证"
|
||||
@@ -130,12 +199,11 @@ def _normalize_id(val) -> str:
|
||||
def check_wage_card(input_path: str, output_path: str = None) -> str:
|
||||
"""读取工资卡汇总表,执行核对并保存结果。
|
||||
|
||||
核对逻辑:
|
||||
1. 开户人身份证为空 -> 标记
|
||||
2. 身份证号 vs 开户人身份证 不一致 -> 标记
|
||||
3. (身份证一致时)开户人姓名为空 -> 标记
|
||||
4. (身份证一致时)员工姓名 vs 开户人姓名 不一致 -> 标记
|
||||
5. 银行卡号校验(check_bank_card)
|
||||
核对逻辑(按 4 类异常分类):
|
||||
1. 开户人信息或银行卡空白
|
||||
2. 员工身份证与开户人身份证不一致(单独存『身份证不一致表』)
|
||||
3. 员工姓名与开户人姓名不一致(仅身份证一致时比对)
|
||||
4. 银行卡信息异常(银行卡非空但格式/位数错误)
|
||||
|
||||
Args:
|
||||
input_path: 工资卡汇总表 Excel 路径
|
||||
@@ -150,6 +218,8 @@ def check_wage_card(input_path: str, output_path: str = None) -> str:
|
||||
df = pd.read_excel(input_path)
|
||||
logger.info("读取工资卡汇总表:%s(%d 行)", input_path, len(df))
|
||||
|
||||
id_mismatch_rows = []
|
||||
|
||||
for idx, row in df.iterrows():
|
||||
idcard = _normalize_id(row.get(COL_IDCARD, ""))
|
||||
card_idcard = _normalize_id(row.get(COL_CARD_IDCARD, ""))
|
||||
@@ -157,30 +227,16 @@ def check_wage_card(input_path: str, output_path: str = None) -> str:
|
||||
card_name = str(row.get(COL_CARD_NAME, "")).strip()
|
||||
bank_account = row.get(COL_BANK_ACCOUNT, "")
|
||||
|
||||
issues = [] # 问题类型(简短)
|
||||
basis = [] # 校验依据(详细对比信息)
|
||||
|
||||
# ---- 身份证核对 ----
|
||||
if _is_empty(card_idcard):
|
||||
issues.append("开户人身份证为空")
|
||||
elif idcard != card_idcard:
|
||||
issues.append("身份证不一致")
|
||||
basis.append(f"身份证不一致(员工:{idcard} vs 开户人:{card_idcard})")
|
||||
else:
|
||||
# ---- 姓名核对(仅身份证一致时) ----
|
||||
if _is_empty(card_name):
|
||||
issues.append("开户人姓名为空")
|
||||
elif staff_name != card_name:
|
||||
issues.append("姓名不一致")
|
||||
basis.append(f"姓名不一致(员工:{staff_name} vs 开户人:{card_name})")
|
||||
|
||||
# ---- 银行卡校验 ----
|
||||
bk = check_bank_card(bank_account)
|
||||
issues, basis, id_inconsistent, bk = classify_card_issue(
|
||||
idcard, card_idcard, staff_name, card_name, bank_account,
|
||||
)
|
||||
if id_inconsistent:
|
||||
id_mismatch_rows.append(idx)
|
||||
|
||||
df.at[idx, COL_CHECK_RESULT] = "、".join(issues) if issues else "通过"
|
||||
df.at[idx, COL_CHECK_BASIS] = ";".join(basis) if basis else ""
|
||||
df.at[idx, COL_BANK_STATUS] = bk["status"]
|
||||
df.at[idx, COL_BANK_REASON] = bk["reason"]
|
||||
df.at[idx, COL_BANK_STATUS] = bk["status"] if bk else ""
|
||||
df.at[idx, COL_BANK_REASON] = bk["reason"] if bk else ""
|
||||
|
||||
# 统计
|
||||
result_counts = df[df[COL_CHECK_RESULT] != "通过"][COL_CHECK_RESULT].value_counts().to_dict()
|
||||
@@ -206,8 +262,18 @@ def check_wage_card(input_path: str, output_path: str = None) -> str:
|
||||
df.to_excel(output_path, index=False)
|
||||
logger.info("核对结果已保存:%s", output_path)
|
||||
|
||||
# ---- 生成异常名单(仅含核对不通过的行) ----
|
||||
abnormal = df[df[COL_CHECK_RESULT] != "通过"]
|
||||
# 身份证不一致单独存表(独立文件,供人工校验)
|
||||
if id_mismatch_rows:
|
||||
base, ext = os.path.splitext(output_path)
|
||||
id_path = os.path.join(os.path.dirname(base), f"身份证不一致表{ext}")
|
||||
df.loc[id_mismatch_rows].to_excel(id_path, index=False)
|
||||
logger.info("身份证不一致表已保存:%s(%d 条)", id_path, len(id_mismatch_rows))
|
||||
else:
|
||||
logger.info("无身份证不一致记录")
|
||||
|
||||
# ---- 生成异常名单(排除已单独成表的身份证不一致记录) ----
|
||||
mask = (df[COL_CHECK_RESULT] != "通过") & (~df.index.isin(id_mismatch_rows))
|
||||
abnormal = df[mask]
|
||||
if len(abnormal) > 0:
|
||||
base, ext = os.path.splitext(output_path)
|
||||
abnormal_path = f"{os.path.dirname(base)}{os.sep}工资卡异常名单{ext}"
|
||||
|
||||
Reference in New Issue
Block a user