rescue: 断电事故后工作区全量备份
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr
|
||||
@Description: HR 系统相关业务模块
|
||||
"""
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr
|
||||
@Description: HR 系统相关业务模块
|
||||
"""
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,162 +1,162 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.attendance
|
||||
@FileName: attendance_stat_export.py
|
||||
@Description: 考勤统计报表逐日出勤导出:
|
||||
调用「考勤统计报表」接口分页抓取某月全集团数据(每人一行,含 v_1~v_最后一天),
|
||||
导出 Excel,列为「工号/姓名/部门/岗位 + 1日~最后一日」(默认上月,可按参数指定月份)。
|
||||
底层复用:hr_api.attendance_stat(报表抓取)、hr_session(会话管理)。
|
||||
@Version: 1.0.0
|
||||
|
||||
使用说明:
|
||||
1. 从项目根目录用模块方式运行(依赖打包为 app 包):
|
||||
python -m app.service.hrbp.ehr.attendance.attendance_stat_export
|
||||
2. 可选参数:<保存目录> <月份 YYYYMM>(默认上月)。
|
||||
3. 首次运行会自动完成 HR 登录并缓存 cookies,登录态过期自动重登。
|
||||
"""
|
||||
|
||||
import calendar
|
||||
import os
|
||||
import sys
|
||||
from datetime import date, datetime, timedelta
|
||||
from typing import Dict, List
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging
|
||||
from app.service.hrbp.ehr.common.hr_api.attendance_stat import fetch_all_attendance_stat
|
||||
from app.service.hrbp.ehr.common.hr_api.attendance import fetch_cur_user_info
|
||||
from app.service.hrbp.common.hr_session import build_hr_session, HRSessionExpiredError, refresh_hr_session
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ===================== 配置区(自行修改) =====================
|
||||
# 默认保存目录
|
||||
SAVE_DIR = r"D:\资料\人资\考勤统计"
|
||||
|
||||
# 身份信息列(对应报文 datas 里的字段)
|
||||
IDENTITY_COLS: List[Dict[str, str]] = [
|
||||
{"key": "base_code", "title": "工号"},
|
||||
{"key": "staff_name", "title": "姓名"},
|
||||
{"key": "dept_org_name", "title": "部门"},
|
||||
{"key": "post_name", "title": "岗位"},
|
||||
]
|
||||
|
||||
|
||||
def _clean(v) -> str:
|
||||
"""转字符串并去掉常见杂质(None、浮点 .0 尾缀)。"""
|
||||
if v is None:
|
||||
return ""
|
||||
s = str(v).strip()
|
||||
if s.endswith(".0"):
|
||||
s = s[:-2]
|
||||
return s
|
||||
|
||||
|
||||
def last_month_ym(today: date = None) -> str:
|
||||
"""返回上月月份 "YYYYMM"。"""
|
||||
today = today or date.today()
|
||||
this_first = today.replace(day=1)
|
||||
last_end = this_first - timedelta(days=1)
|
||||
return f"{last_end.year:04d}{last_end.month:02d}"
|
||||
|
||||
|
||||
def _build_rows(records: List[Dict], days_in_month: int) -> List[Dict]:
|
||||
"""把报表 datas 转成导出行:身份信息 + 1日~最终日(v_1~v_N),缺失留空。"""
|
||||
rows: List[Dict] = []
|
||||
for rec in records:
|
||||
row = {item["title"]: _clean(rec.get(item["key"])) for item in IDENTITY_COLS}
|
||||
for day in range(1, days_in_month + 1):
|
||||
row[f"{day}日"] = _clean(rec.get(f"v_{day}"))
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
|
||||
def export_month_attendance(save_dir: str = None, month: str = None) -> str:
|
||||
"""导出某月考勤统计逐日出勤 Excel,返回文件路径。
|
||||
|
||||
Args:
|
||||
save_dir: 保存目录,默认 SAVE_DIR
|
||||
month: 查询月份 "YYYYMM"(默认上月)
|
||||
|
||||
Returns:
|
||||
导出文件路径
|
||||
"""
|
||||
save_dir = save_dir or SAVE_DIR
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
|
||||
if not month:
|
||||
month = last_month_ym()
|
||||
year, mon = int(month[:4]), int(month[4:6])
|
||||
days_in_month = calendar.monthrange(year, mon)[1]
|
||||
logger.info("===== 考勤统计报表导出,月份:%s(%d 天) =====", month, days_in_month)
|
||||
|
||||
# 1. 会话校验 + 取当前用户 userId
|
||||
session = build_hr_session()
|
||||
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", "")
|
||||
if not user_id:
|
||||
raise RuntimeError(f"getCurUserInfo 未返回 userId:{info}")
|
||||
logger.info("cookies 校验通过,user_id=%s", user_id)
|
||||
|
||||
# 2. 分页抓取全集团考勤统计报表明细
|
||||
records = fetch_all_attendance_stat(session, user_id, month)
|
||||
logger.info("考勤统计报表共 %d 人", len(records))
|
||||
if not records:
|
||||
logger.error("考勤统计报表无数据,请检查月份或权限")
|
||||
return ""
|
||||
|
||||
# 3. 组装导出行并输出 Excel
|
||||
columns = [item["title"] for item in IDENTITY_COLS] + [f"{d}日" for d in range(1, days_in_month + 1)]
|
||||
rows = _build_rows(records, days_in_month)
|
||||
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
save_path = os.path.abspath(os.path.join(save_dir, f"考勤统计报表_{month}_{ts}.xlsx"))
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
raise RuntimeError("缺少 pandas 依赖,无法导出 Excel")
|
||||
|
||||
df = pd.DataFrame(rows, columns=columns)
|
||||
try:
|
||||
df.to_excel(save_path, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试"
|
||||
)
|
||||
|
||||
logger.info("导出明细:%d 人 × %d 列", len(rows), len(columns))
|
||||
logger.info("文件已保存:%s", save_path)
|
||||
logger.info("=" * 60)
|
||||
logger.info("【考勤统计报表汇总】")
|
||||
logger.info(" 月份:%s", month)
|
||||
logger.info(" 人数:%d 人", len(rows))
|
||||
logger.info(" 导出文件:%s", save_path)
|
||||
logger.info("=" * 60)
|
||||
return save_path
|
||||
|
||||
|
||||
def main() -> None:
|
||||
setup_logging()
|
||||
# 参数:<保存目录> <月份 YYYYMM>
|
||||
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 = export_month_attendance(save_dir, month)
|
||||
if out:
|
||||
logger.info("===== 考勤统计报表导出完成 =====")
|
||||
except Exception as e: # noqa: BLE001
|
||||
if "正被占用" in str(e):
|
||||
logger.error("=========== 提醒 ===========")
|
||||
logger.error(str(e))
|
||||
logger.error("请关闭该 Excel 文件后重新运行即可。")
|
||||
return
|
||||
logger.error("考勤统计报表导出失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.attendance
|
||||
@FileName: attendance_stat_export.py
|
||||
@Description: 考勤统计报表逐日出勤导出:
|
||||
调用「考勤统计报表」接口分页抓取某月全集团数据(每人一行,含 v_1~v_最后一天),
|
||||
导出 Excel,列为「工号/姓名/部门/岗位 + 1日~最后一日」(默认上月,可按参数指定月份)。
|
||||
底层复用:hr_api.attendance_stat(报表抓取)、hr_session(会话管理)。
|
||||
@Version: 1.0.0
|
||||
|
||||
使用说明:
|
||||
1. 从项目根目录用模块方式运行(依赖打包为 app 包):
|
||||
python -m app.service.hrbp.ehr.attendance.attendance_stat_export
|
||||
2. 可选参数:<保存目录> <月份 YYYYMM>(默认上月)。
|
||||
3. 首次运行会自动完成 HR 登录并缓存 cookies,登录态过期自动重登。
|
||||
"""
|
||||
|
||||
import calendar
|
||||
import os
|
||||
import sys
|
||||
from datetime import date, datetime, timedelta
|
||||
from typing import Dict, List
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging
|
||||
from app.service.hrbp.ehr.common.hr_api.attendance_stat import fetch_all_attendance_stat
|
||||
from app.service.hrbp.ehr.common.hr_api.attendance import fetch_cur_user_info
|
||||
from app.service.hrbp.common.hr_session import build_hr_session, HRSessionExpiredError, refresh_hr_session
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ===================== 配置区(自行修改) =====================
|
||||
# 默认保存目录
|
||||
SAVE_DIR = r"D:\资料\人资\考勤统计"
|
||||
|
||||
# 身份信息列(对应报文 datas 里的字段)
|
||||
IDENTITY_COLS: List[Dict[str, str]] = [
|
||||
{"key": "base_code", "title": "工号"},
|
||||
{"key": "staff_name", "title": "姓名"},
|
||||
{"key": "dept_org_name", "title": "部门"},
|
||||
{"key": "post_name", "title": "岗位"},
|
||||
]
|
||||
|
||||
|
||||
def _clean(v) -> str:
|
||||
"""转字符串并去掉常见杂质(None、浮点 .0 尾缀)。"""
|
||||
if v is None:
|
||||
return ""
|
||||
s = str(v).strip()
|
||||
if s.endswith(".0"):
|
||||
s = s[:-2]
|
||||
return s
|
||||
|
||||
|
||||
def last_month_ym(today: date = None) -> str:
|
||||
"""返回上月月份 "YYYYMM"。"""
|
||||
today = today or date.today()
|
||||
this_first = today.replace(day=1)
|
||||
last_end = this_first - timedelta(days=1)
|
||||
return f"{last_end.year:04d}{last_end.month:02d}"
|
||||
|
||||
|
||||
def _build_rows(records: List[Dict], days_in_month: int) -> List[Dict]:
|
||||
"""把报表 datas 转成导出行:身份信息 + 1日~最终日(v_1~v_N),缺失留空。"""
|
||||
rows: List[Dict] = []
|
||||
for rec in records:
|
||||
row = {item["title"]: _clean(rec.get(item["key"])) for item in IDENTITY_COLS}
|
||||
for day in range(1, days_in_month + 1):
|
||||
row[f"{day}日"] = _clean(rec.get(f"v_{day}"))
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
|
||||
def export_month_attendance(save_dir: str = None, month: str = None) -> str:
|
||||
"""导出某月考勤统计逐日出勤 Excel,返回文件路径。
|
||||
|
||||
Args:
|
||||
save_dir: 保存目录,默认 SAVE_DIR
|
||||
month: 查询月份 "YYYYMM"(默认上月)
|
||||
|
||||
Returns:
|
||||
导出文件路径
|
||||
"""
|
||||
save_dir = save_dir or SAVE_DIR
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
|
||||
if not month:
|
||||
month = last_month_ym()
|
||||
year, mon = int(month[:4]), int(month[4:6])
|
||||
days_in_month = calendar.monthrange(year, mon)[1]
|
||||
logger.info("===== 考勤统计报表导出,月份:%s(%d 天) =====", month, days_in_month)
|
||||
|
||||
# 1. 会话校验 + 取当前用户 userId
|
||||
session = build_hr_session()
|
||||
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", "")
|
||||
if not user_id:
|
||||
raise RuntimeError(f"getCurUserInfo 未返回 userId:{info}")
|
||||
logger.info("cookies 校验通过,user_id=%s", user_id)
|
||||
|
||||
# 2. 分页抓取全集团考勤统计报表明细
|
||||
records = fetch_all_attendance_stat(session, user_id, month)
|
||||
logger.info("考勤统计报表共 %d 人", len(records))
|
||||
if not records:
|
||||
logger.error("考勤统计报表无数据,请检查月份或权限")
|
||||
return ""
|
||||
|
||||
# 3. 组装导出行并输出 Excel
|
||||
columns = [item["title"] for item in IDENTITY_COLS] + [f"{d}日" for d in range(1, days_in_month + 1)]
|
||||
rows = _build_rows(records, days_in_month)
|
||||
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
save_path = os.path.abspath(os.path.join(save_dir, f"考勤统计报表_{month}_{ts}.xlsx"))
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
raise RuntimeError("缺少 pandas 依赖,无法导出 Excel")
|
||||
|
||||
df = pd.DataFrame(rows, columns=columns)
|
||||
try:
|
||||
df.to_excel(save_path, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试"
|
||||
)
|
||||
|
||||
logger.info("导出明细:%d 人 × %d 列", len(rows), len(columns))
|
||||
logger.info("文件已保存:%s", save_path)
|
||||
logger.info("=" * 60)
|
||||
logger.info("【考勤统计报表汇总】")
|
||||
logger.info(" 月份:%s", month)
|
||||
logger.info(" 人数:%d 人", len(rows))
|
||||
logger.info(" 导出文件:%s", save_path)
|
||||
logger.info("=" * 60)
|
||||
return save_path
|
||||
|
||||
|
||||
def main() -> None:
|
||||
setup_logging()
|
||||
# 参数:<保存目录> <月份 YYYYMM>
|
||||
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 = export_month_attendance(save_dir, month)
|
||||
if out:
|
||||
logger.info("===== 考勤统计报表导出完成 =====")
|
||||
except Exception as e: # noqa: BLE001
|
||||
if "正被占用" in str(e):
|
||||
logger.error("=========== 提醒 ===========")
|
||||
logger.error(str(e))
|
||||
logger.error("请关闭该 Excel 文件后重新运行即可。")
|
||||
return
|
||||
logger.error("考勤统计报表导出失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,5 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common
|
||||
@Description: HR 系统公共模块(登录、接口调用、会话管理、配置)
|
||||
"""
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common
|
||||
@Description: HR 系统公共模块(登录、接口调用、会话管理、配置)
|
||||
"""
|
||||
|
||||
@@ -1,130 +1,130 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common
|
||||
@FileName: config.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-08 10:40
|
||||
@Description: HR 系统配置,集中管理接口地址、分页大小等常量(供各业务模块复用)
|
||||
@Version: 1.1.0
|
||||
"""
|
||||
|
||||
from app.service.hrbp.ehr.common.common_query import build_condition, encode_common_query
|
||||
|
||||
# ---------- 银行卡(工资卡)信息查询接口 ----------
|
||||
# 分页查询工资卡信息(aa.md 提供),返回 JSON
|
||||
WAGE_CARD_URL = "https://hr.37du.co/RedseaPlatform/getPageAjax/HrStaffWageCard.mc"
|
||||
|
||||
# 单页最大抓取条数
|
||||
PAGE_MAX_SIZE = 500
|
||||
|
||||
# ---------- 银行字典接口 ----------
|
||||
BANK_DICT_URL = "https://hr.37du.co/RedseaPlatform/PtCodeTypeValue.mc?method=getCodeValueByCodes"
|
||||
BANK_DICT_CODE_TYPE = "WAGE.BANKTYPE"
|
||||
BANK_DICT_EXPIRE_SEC = 7 * 24 * 60 * 60 # 缓存7天过期,自动重新拉取
|
||||
|
||||
# ---------- 员工花名册(自定义导出)页面 ----------
|
||||
# 花名册自定义导出页面
|
||||
ROSTER_URL = "https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic#ajax&1&nworktoday-40175-24311-77128-52242&nworktoday-40175-24311|/RedseaPlatform/hrRoster/1116da64-b094-11ea-b588-14187743d052/getCustomCommonList.mc?clickFlag=true&treePermitType=permit&useSealTreeData=0&menuName=员工花名册"
|
||||
|
||||
# 待增减人员操作页面
|
||||
ADD_SUB_URL = "https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic#ajax&1&nworktoday-40175-13664-23874-98879&nworktoday-40175-13664|/RedseaPlatform/hrRoster/7984ae1a-16ec-11ed-bea9-822ff8ed5b28/getCustomCommonList.mc?menuName=待增减人员"
|
||||
|
||||
# 预入职台账(排班异常识别)自定义导出页面(aa.md 提供)
|
||||
PRE_ENTRY_ROSTER_URL = "https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic#ajax&1&nworktoday-40175-24311-01818-07406&nworktoday-40175-24311|/RedseaPlatform/hrRoster/10fe9cd6-b094-11ea-b588-14187743d052/getCustomCommonList.mc?_t=1787581570094&clickFlag=true&treePermitType=permit&useSealTreeData=0&menuName=预入职台账&_t=1787581570094"
|
||||
|
||||
# 调动台账(排班异常识别)自定义导出页面(aa.md 提供)
|
||||
TRANSFER_ROSTER_URL = "https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic#ajax&1&nworktoday-40175-24311-01818-39687&nworktoday-40175-24311|/RedseaPlatform/hrRoster/1123d951-b094-11ea-b588-14187743d052/getCustomCommonList.mc?clickFlag=true&treePermitType=permit&useSealTreeData=0&menuName=%E8%B0%83%E5%8A%A8%E5%8F%B0%E8%B4%A6"
|
||||
|
||||
# 花名册自定义导出模板(下拉框中全部模板,后续各业务场景可按需选用)
|
||||
ROSTER_TEMPLATE_NAME = "员工基础信息" # 默认模板
|
||||
ROSTER_TEMPLATE_CADRE_SELECT = "干部选拔信息" # 干部选拔
|
||||
ROSTER_TEMPLATE_INDIVIDUAL_TAX = "个税申报基础信息" # 个税申报
|
||||
ROSTER_TEMPLATE_EMPLOYER_INSURANCE = "雇主险增减员导出模板" # 雇主险增减员
|
||||
ROSTER_TEMPLATE_SHIFT_ABNORMAL = "排班异常识别导出" # 排班异常识别(预入职台账)
|
||||
|
||||
# ---------- 考勤异常查询接口 ----------
|
||||
# 获取当前用户信息(用于校验 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"
|
||||
|
||||
# 查询排班接口
|
||||
SHIFT_URL = "https://hr.37du.co/RedseaPlatform/redmagicapi/rf_p_kq_count_SelectBanci/getExecutePageResult.mc"
|
||||
|
||||
# 按部门查询排班集合接口(aa.md 提供):org_name=部门名,返回该部门全部排班
|
||||
# (data.list 记录含 work_date_name 排班名、org_name 部门名,逐条记录 = 一个排班)
|
||||
WORK_DATE_QUERY_URL = "https://hr.37du.co/RedseaPlatform/redmagicapi/rf_s_kq_work_date_query/redApiExec.mc"
|
||||
|
||||
# 查询请假记录接口
|
||||
LEAVE_URL = "https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc"
|
||||
|
||||
# 查询加班记录接口
|
||||
OVERTIME_URL = "https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc"
|
||||
|
||||
# 查询打卡记录接口
|
||||
KQ_DATA_URL = "https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc"
|
||||
|
||||
# ---------- 考勤统计报表(逐日出勤,aa.md 提供) ----------
|
||||
# 分页查询"考勤统计报表",每人一行含 v_1~v_最后一天(当月逐日出勤状态),返回 JSON
|
||||
MONTH_ATT_REPORT_URL = "https://hr.37du.co/RedseaPlatform/pt/report/excel/detail/getPageAjax.mc"
|
||||
MONTH_ATT_REPORT_ID = "f880c52a619446e0b74e3820b898d53b"
|
||||
# 集团根组织 struId(aa.md 中 struId / belongUnitStruId / ds1.struId / ds2.stru_id 共用)
|
||||
COMPANY_STRU_ID = "596bae33-50e9-11ec-b526-822ff8ed5b28"
|
||||
|
||||
# ---------- 组织维护(组织设置)查询接口(aa.md 提供) ----------
|
||||
# 组织维护台账实时数据查询,返回 JSON(count/datas/pageCount)
|
||||
ORG_QUERY_URL = "https://hr.37du.co/RedseaPlatform/hrRoster/110118b4-b094-11ea-b588-14187743d052/queryRealTimeData.mc"
|
||||
ORG_TABLE_ID = "assemble-pt_organzation"
|
||||
ORG_ROSTER_ID = "110118b4-b094-11ea-b588-14187743d052"
|
||||
|
||||
# 组织维护查询固定入参(从浏览器抓包提取;登录用户变更时需同步更新 currentUserId / currentStaffId 等)
|
||||
# commonQuery 由前端加密算法自构造(等价于抓包原始串,即 in_use in ('1') 条件),
|
||||
# 需要追加/修改查询条件时直接改 ORG_QUERY_CONDITIONS 后重新加密即可
|
||||
ORG_QUERY_CONDITIONS = [
|
||||
build_condition("`pt_organzation.IN_USE`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="select"),
|
||||
]
|
||||
|
||||
ORG_QUERY_BASE_PARAMS = {
|
||||
"menuName": "组织维护",
|
||||
"useSealTreeData": "0",
|
||||
"treePermitType": "permit",
|
||||
"cancelNodeClick": "1",
|
||||
"clickFlag": "true",
|
||||
"in_use": "1",
|
||||
"commonQuery": encode_common_query(ORG_QUERY_CONDITIONS),
|
||||
"newCondition": "",
|
||||
"urlConditions": "_t%3A1788589944798%23clickFlag%3Atrue%23cancelNodeClick%3A1%23treePermitType%3Apermit%23useSealTreeData%3A0%23menuName%3A%E7%BB%84%E7%BB%87%E7%BB%B4%E6%8A%A4%23_t%3A1788589944798%23",
|
||||
"exportConfig": "",
|
||||
"tableId": ORG_TABLE_ID,
|
||||
"rosterId": ORG_ROSTER_ID,
|
||||
"includeChildrenSetting": "",
|
||||
"struTreeCode": "cq37du",
|
||||
"djStruTreeCode": "",
|
||||
"djStruId": "",
|
||||
"djOrgName": "",
|
||||
"struId": COMPANY_STRU_ID,
|
||||
"belongUnitStruId": COMPANY_STRU_ID,
|
||||
"rootId": "cq37du",
|
||||
"isVirtual": "0",
|
||||
"currentUserRootId": "cq37du",
|
||||
"currentUserId": "178b0efa-8a65-11f1-a7d9-000c296f9469",
|
||||
"currentRoleIds": "POST_SYS_ADMIN,renshi",
|
||||
"currentStaffId": "1342173e-36cf-4160-8826-6b17d7d084a4",
|
||||
"baseHrefPath": "http://hr.37du.co:80RedseaPlatform",
|
||||
"qrCodeUrl": "jspresumepage-01.jsp",
|
||||
"orgName": "集团",
|
||||
"belongUnitOrgName": "集团",
|
||||
"throughParam": "",
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
}
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common
|
||||
@FileName: config.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-08 10:40
|
||||
@Description: HR 系统配置,集中管理接口地址、分页大小等常量(供各业务模块复用)
|
||||
@Version: 1.1.0
|
||||
"""
|
||||
|
||||
from app.service.hrbp.ehr.common.common_query import build_condition, encode_common_query
|
||||
|
||||
# ---------- 银行卡(工资卡)信息查询接口 ----------
|
||||
# 分页查询工资卡信息(aa.md 提供),返回 JSON
|
||||
WAGE_CARD_URL = "https://hr.37du.co/RedseaPlatform/getPageAjax/HrStaffWageCard.mc"
|
||||
|
||||
# 单页最大抓取条数
|
||||
PAGE_MAX_SIZE = 500
|
||||
|
||||
# ---------- 银行字典接口 ----------
|
||||
BANK_DICT_URL = "https://hr.37du.co/RedseaPlatform/PtCodeTypeValue.mc?method=getCodeValueByCodes"
|
||||
BANK_DICT_CODE_TYPE = "WAGE.BANKTYPE"
|
||||
BANK_DICT_EXPIRE_SEC = 7 * 24 * 60 * 60 # 缓存7天过期,自动重新拉取
|
||||
|
||||
# ---------- 员工花名册(自定义导出)页面 ----------
|
||||
# 花名册自定义导出页面
|
||||
ROSTER_URL = "https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic#ajax&1&nworktoday-40175-24311-77128-52242&nworktoday-40175-24311|/RedseaPlatform/hrRoster/1116da64-b094-11ea-b588-14187743d052/getCustomCommonList.mc?clickFlag=true&treePermitType=permit&useSealTreeData=0&menuName=员工花名册"
|
||||
|
||||
# 待增减人员操作页面
|
||||
ADD_SUB_URL = "https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic#ajax&1&nworktoday-40175-13664-23874-98879&nworktoday-40175-13664|/RedseaPlatform/hrRoster/7984ae1a-16ec-11ed-bea9-822ff8ed5b28/getCustomCommonList.mc?menuName=待增减人员"
|
||||
|
||||
# 预入职台账(排班异常识别)自定义导出页面(aa.md 提供)
|
||||
PRE_ENTRY_ROSTER_URL = "https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic#ajax&1&nworktoday-40175-24311-01818-07406&nworktoday-40175-24311|/RedseaPlatform/hrRoster/10fe9cd6-b094-11ea-b588-14187743d052/getCustomCommonList.mc?_t=1787581570094&clickFlag=true&treePermitType=permit&useSealTreeData=0&menuName=预入职台账&_t=1787581570094"
|
||||
|
||||
# 调动台账(排班异常识别)自定义导出页面(aa.md 提供)
|
||||
TRANSFER_ROSTER_URL = "https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic#ajax&1&nworktoday-40175-24311-01818-39687&nworktoday-40175-24311|/RedseaPlatform/hrRoster/1123d951-b094-11ea-b588-14187743d052/getCustomCommonList.mc?clickFlag=true&treePermitType=permit&useSealTreeData=0&menuName=%E8%B0%83%E5%8A%A8%E5%8F%B0%E8%B4%A6"
|
||||
|
||||
# 花名册自定义导出模板(下拉框中全部模板,后续各业务场景可按需选用)
|
||||
ROSTER_TEMPLATE_NAME = "员工基础信息" # 默认模板
|
||||
ROSTER_TEMPLATE_CADRE_SELECT = "干部选拔信息" # 干部选拔
|
||||
ROSTER_TEMPLATE_INDIVIDUAL_TAX = "个税申报基础信息" # 个税申报
|
||||
ROSTER_TEMPLATE_EMPLOYER_INSURANCE = "雇主险增减员导出模板" # 雇主险增减员
|
||||
ROSTER_TEMPLATE_SHIFT_ABNORMAL = "排班异常识别导出" # 排班异常识别(预入职台账)
|
||||
|
||||
# ---------- 考勤异常查询接口 ----------
|
||||
# 获取当前用户信息(用于校验 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"
|
||||
|
||||
# 查询排班接口
|
||||
SHIFT_URL = "https://hr.37du.co/RedseaPlatform/redmagicapi/rf_p_kq_count_SelectBanci/getExecutePageResult.mc"
|
||||
|
||||
# 按部门查询排班集合接口(aa.md 提供):org_name=部门名,返回该部门全部排班
|
||||
# (data.list 记录含 work_date_name 排班名、org_name 部门名,逐条记录 = 一个排班)
|
||||
WORK_DATE_QUERY_URL = "https://hr.37du.co/RedseaPlatform/redmagicapi/rf_s_kq_work_date_query/redApiExec.mc"
|
||||
|
||||
# 查询请假记录接口
|
||||
LEAVE_URL = "https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc"
|
||||
|
||||
# 查询加班记录接口
|
||||
OVERTIME_URL = "https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc"
|
||||
|
||||
# 查询打卡记录接口
|
||||
KQ_DATA_URL = "https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc"
|
||||
|
||||
# ---------- 考勤统计报表(逐日出勤,aa.md 提供) ----------
|
||||
# 分页查询"考勤统计报表",每人一行含 v_1~v_最后一天(当月逐日出勤状态),返回 JSON
|
||||
MONTH_ATT_REPORT_URL = "https://hr.37du.co/RedseaPlatform/pt/report/excel/detail/getPageAjax.mc"
|
||||
MONTH_ATT_REPORT_ID = "f880c52a619446e0b74e3820b898d53b"
|
||||
# 集团根组织 struId(aa.md 中 struId / belongUnitStruId / ds1.struId / ds2.stru_id 共用)
|
||||
COMPANY_STRU_ID = "596bae33-50e9-11ec-b526-822ff8ed5b28"
|
||||
|
||||
# ---------- 组织维护(组织设置)查询接口(aa.md 提供) ----------
|
||||
# 组织维护台账实时数据查询,返回 JSON(count/datas/pageCount)
|
||||
ORG_QUERY_URL = "https://hr.37du.co/RedseaPlatform/hrRoster/110118b4-b094-11ea-b588-14187743d052/queryRealTimeData.mc"
|
||||
ORG_TABLE_ID = "assemble-pt_organzation"
|
||||
ORG_ROSTER_ID = "110118b4-b094-11ea-b588-14187743d052"
|
||||
|
||||
# 组织维护查询固定入参(从浏览器抓包提取;登录用户变更时需同步更新 currentUserId / currentStaffId 等)
|
||||
# commonQuery 由前端加密算法自构造(等价于抓包原始串,即 in_use in ('1') 条件),
|
||||
# 需要追加/修改查询条件时直接改 ORG_QUERY_CONDITIONS 后重新加密即可
|
||||
ORG_QUERY_CONDITIONS = [
|
||||
build_condition("`pt_organzation.IN_USE`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="select"),
|
||||
]
|
||||
|
||||
ORG_QUERY_BASE_PARAMS = {
|
||||
"menuName": "组织维护",
|
||||
"useSealTreeData": "0",
|
||||
"treePermitType": "permit",
|
||||
"cancelNodeClick": "1",
|
||||
"clickFlag": "true",
|
||||
"in_use": "1",
|
||||
"commonQuery": encode_common_query(ORG_QUERY_CONDITIONS),
|
||||
"newCondition": "",
|
||||
"urlConditions": "_t%3A1788589944798%23clickFlag%3Atrue%23cancelNodeClick%3A1%23treePermitType%3Apermit%23useSealTreeData%3A0%23menuName%3A%E7%BB%84%E7%BB%87%E7%BB%B4%E6%8A%A4%23_t%3A1788589944798%23",
|
||||
"exportConfig": "",
|
||||
"tableId": ORG_TABLE_ID,
|
||||
"rosterId": ORG_ROSTER_ID,
|
||||
"includeChildrenSetting": "",
|
||||
"struTreeCode": "cq37du",
|
||||
"djStruTreeCode": "",
|
||||
"djStruId": "",
|
||||
"djOrgName": "",
|
||||
"struId": COMPANY_STRU_ID,
|
||||
"belongUnitStruId": COMPANY_STRU_ID,
|
||||
"rootId": "cq37du",
|
||||
"isVirtual": "0",
|
||||
"currentUserRootId": "cq37du",
|
||||
"currentUserId": "178b0efa-8a65-11f1-a7d9-000c296f9469",
|
||||
"currentRoleIds": "POST_SYS_ADMIN,renshi",
|
||||
"currentStaffId": "1342173e-36cf-4160-8826-6b17d7d084a4",
|
||||
"baseHrefPath": "http://hr.37du.co:80RedseaPlatform",
|
||||
"qrCodeUrl": "jspresumepage-01.jsp",
|
||||
"orgName": "集团",
|
||||
"belongUnitOrgName": "集团",
|
||||
"throughParam": "",
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
}
|
||||
|
||||
# ---------- 员工花名册(实时数据查询接口,纯 API 版) ----------
|
||||
# 花名册台账实时数据查询(与组织维护 queryRealTimeData 同模式),返回 JSON(count/datas/pageCount)
|
||||
ROSTER_QUERY_URL = "https://hr.37du.co/RedseaPlatform/hrRoster/1116da64-b094-11ea-b588-14187743d052/queryRealTimeData.mc"
|
||||
@@ -183,6 +183,6 @@ ROSTER_QUERY_BASE_PARAMS = {
|
||||
"hideCols": "",
|
||||
}
|
||||
|
||||
# 假期类型编码映射已上移到 HR 平台共享层 app/service/hrbp/common/config.py(VACATION_TYPE_MAP),
|
||||
# 由 ehr / oa 两系统统一引用,避免 oa 反向依赖 ehr。需要时从此处 import:
|
||||
# from app.service.hrbp.common.config import VACATION_TYPE_MAP
|
||||
# 假期类型编码映射已上移到 HR 平台共享层 app/service/hrbp/common/config.py(VACATION_TYPE_MAP),
|
||||
# 由 ehr / oa 两系统统一引用,避免 oa 反向依赖 ehr。需要时从此处 import:
|
||||
# from app.service.hrbp.common.config import VACATION_TYPE_MAP
|
||||
|
||||
@@ -1,88 +1,88 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common
|
||||
@FileName: hr_api/__init__.py
|
||||
@Description: HR 系统 API 包,按接口拆分到各子模块,此处统一导出(保持 from ...hr_api import X 兼容)
|
||||
@Version: 2.0.0
|
||||
"""
|
||||
|
||||
from app.service.hrbp.common.hr_session import HRSessionExpiredError, _is_expired, hr_request_json
|
||||
from app.service.hrbp.ehr.common.hr_api.wage_card import fetch_wage_card_page, fetch_all_wage_card
|
||||
from app.service.hrbp.ehr.common.hr_api.bank_dict import get_bank_dict, bank_type_to_name
|
||||
from app.service.hrbp.ehr.common.hr_api.attendance import (
|
||||
fetch_cur_user_info,
|
||||
fetch_attendance_abnormal_page,
|
||||
fetch_all_attendance_abnormal,
|
||||
adjust_abnormal,
|
||||
)
|
||||
from app.service.hrbp.ehr.common.hr_api.shift import fetch_shift_page, fetch_all_shift, fetch_work_date_page, fetch_all_work_date
|
||||
from app.service.hrbp.ehr.common.hr_api.leave import fetch_leave_page, fetch_all_leave
|
||||
from app.service.hrbp.ehr.common.hr_api.overtime import fetch_overtime_page, fetch_all_overtime
|
||||
from app.service.hrbp.ehr.common.hr_api.kq_data import fetch_kq_data_page, fetch_all_kq_data
|
||||
from app.service.hrbp.ehr.common.hr_api.attendance_stat import (
|
||||
fetch_attendance_stat_page,
|
||||
fetch_all_attendance_stat,
|
||||
)
|
||||
from app.service.hrbp.ehr.common.hr_api.org import fetch_org_page, fetch_all_orgs, to_org_rows
|
||||
from app.service.hrbp.ehr.common.hr_api.roster import (
|
||||
fetch_roster_page,
|
||||
fetch_all_rosters,
|
||||
to_roster_rows,
|
||||
build_leave_conditions,
|
||||
build_in_service_conditions,
|
||||
fetch_roster_code_dicts,
|
||||
)
|
||||
from app.service.hrbp.ehr.common.hr_api.code_dict import get_code_dicts, code_to_name
|
||||
from app.service.hrbp.ehr.common.hr_api.roster_export import export_common_list, export_roster_excel
|
||||
|
||||
__all__ = [
|
||||
# base
|
||||
"HRSessionExpiredError",
|
||||
"_is_expired",
|
||||
"hr_request_json",
|
||||
# wage_card
|
||||
"fetch_wage_card_page",
|
||||
"fetch_all_wage_card",
|
||||
# bank_dict
|
||||
"get_bank_dict",
|
||||
"bank_type_to_name",
|
||||
# attendance
|
||||
"fetch_cur_user_info",
|
||||
"fetch_attendance_abnormal_page",
|
||||
"fetch_all_attendance_abnormal",
|
||||
"adjust_abnormal",
|
||||
# shift
|
||||
"fetch_shift_page",
|
||||
"fetch_all_shift",
|
||||
"fetch_work_date_page",
|
||||
"fetch_all_work_date",
|
||||
# leave
|
||||
"fetch_leave_page",
|
||||
"fetch_all_leave",
|
||||
# overtime
|
||||
"fetch_overtime_page",
|
||||
"fetch_all_overtime",
|
||||
# kq_data
|
||||
"fetch_kq_data_page",
|
||||
"fetch_all_kq_data",
|
||||
# attendance_stat
|
||||
"fetch_attendance_stat_page",
|
||||
"fetch_all_attendance_stat",
|
||||
# org
|
||||
"fetch_org_page",
|
||||
"fetch_all_orgs",
|
||||
"to_org_rows",
|
||||
# roster
|
||||
"fetch_roster_page",
|
||||
"fetch_all_rosters",
|
||||
"to_roster_rows",
|
||||
"build_leave_conditions",
|
||||
"build_in_service_conditions",
|
||||
"fetch_roster_code_dicts",
|
||||
# code_dict
|
||||
"get_code_dicts",
|
||||
"code_to_name",
|
||||
# roster_export
|
||||
"export_common_list",
|
||||
"export_roster_excel",
|
||||
]
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common
|
||||
@FileName: hr_api/__init__.py
|
||||
@Description: HR 系统 API 包,按接口拆分到各子模块,此处统一导出(保持 from ...hr_api import X 兼容)
|
||||
@Version: 2.0.0
|
||||
"""
|
||||
|
||||
from app.service.hrbp.common.hr_session import HRSessionExpiredError, _is_expired, hr_request_json
|
||||
from app.service.hrbp.ehr.common.hr_api.wage_card import fetch_wage_card_page, fetch_all_wage_card
|
||||
from app.service.hrbp.ehr.common.hr_api.bank_dict import get_bank_dict, bank_type_to_name
|
||||
from app.service.hrbp.ehr.common.hr_api.attendance import (
|
||||
fetch_cur_user_info,
|
||||
fetch_attendance_abnormal_page,
|
||||
fetch_all_attendance_abnormal,
|
||||
adjust_abnormal,
|
||||
)
|
||||
from app.service.hrbp.ehr.common.hr_api.shift import fetch_shift_page, fetch_all_shift, fetch_work_date_page, fetch_all_work_date
|
||||
from app.service.hrbp.ehr.common.hr_api.leave import fetch_leave_page, fetch_all_leave
|
||||
from app.service.hrbp.ehr.common.hr_api.overtime import fetch_overtime_page, fetch_all_overtime
|
||||
from app.service.hrbp.ehr.common.hr_api.kq_data import fetch_kq_data_page, fetch_all_kq_data
|
||||
from app.service.hrbp.ehr.common.hr_api.attendance_stat import (
|
||||
fetch_attendance_stat_page,
|
||||
fetch_all_attendance_stat,
|
||||
)
|
||||
from app.service.hrbp.ehr.common.hr_api.org import fetch_org_page, fetch_all_orgs, to_org_rows
|
||||
from app.service.hrbp.ehr.common.hr_api.roster import (
|
||||
fetch_roster_page,
|
||||
fetch_all_rosters,
|
||||
to_roster_rows,
|
||||
build_leave_conditions,
|
||||
build_in_service_conditions,
|
||||
fetch_roster_code_dicts,
|
||||
)
|
||||
from app.service.hrbp.ehr.common.hr_api.code_dict import get_code_dicts, code_to_name
|
||||
from app.service.hrbp.ehr.common.hr_api.roster_export import export_common_list, export_roster_excel
|
||||
|
||||
__all__ = [
|
||||
# base
|
||||
"HRSessionExpiredError",
|
||||
"_is_expired",
|
||||
"hr_request_json",
|
||||
# wage_card
|
||||
"fetch_wage_card_page",
|
||||
"fetch_all_wage_card",
|
||||
# bank_dict
|
||||
"get_bank_dict",
|
||||
"bank_type_to_name",
|
||||
# attendance
|
||||
"fetch_cur_user_info",
|
||||
"fetch_attendance_abnormal_page",
|
||||
"fetch_all_attendance_abnormal",
|
||||
"adjust_abnormal",
|
||||
# shift
|
||||
"fetch_shift_page",
|
||||
"fetch_all_shift",
|
||||
"fetch_work_date_page",
|
||||
"fetch_all_work_date",
|
||||
# leave
|
||||
"fetch_leave_page",
|
||||
"fetch_all_leave",
|
||||
# overtime
|
||||
"fetch_overtime_page",
|
||||
"fetch_all_overtime",
|
||||
# kq_data
|
||||
"fetch_kq_data_page",
|
||||
"fetch_all_kq_data",
|
||||
# attendance_stat
|
||||
"fetch_attendance_stat_page",
|
||||
"fetch_all_attendance_stat",
|
||||
# org
|
||||
"fetch_org_page",
|
||||
"fetch_all_orgs",
|
||||
"to_org_rows",
|
||||
# roster
|
||||
"fetch_roster_page",
|
||||
"fetch_all_rosters",
|
||||
"to_roster_rows",
|
||||
"build_leave_conditions",
|
||||
"build_in_service_conditions",
|
||||
"fetch_roster_code_dicts",
|
||||
# code_dict
|
||||
"get_code_dicts",
|
||||
"code_to_name",
|
||||
# roster_export
|
||||
"export_common_list",
|
||||
"export_roster_excel",
|
||||
]
|
||||
|
||||
@@ -1,145 +1,145 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common.hr_api
|
||||
@FileName: attendance_stat.py
|
||||
@Description: 考勤统计报表(逐日出勤)查询接口:
|
||||
- fetch_attendance_stat_page:请求单页报表数据
|
||||
- fetch_all_attendance_stat:分页抓取某月全集团逐日出勤明细(每人一行,含 v_1~v_最后一天)
|
||||
- 登录态过期自动重登(复用 hr_session)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import time
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
from app.service.hrbp.ehr.common.config import (
|
||||
MONTH_ATT_REPORT_URL,
|
||||
MONTH_ATT_REPORT_ID,
|
||||
COMPANY_STRU_ID,
|
||||
)
|
||||
from app.service.hrbp.common.hr_session import HRSessionExpiredError, hr_request_json
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# 报表接口单页最大支持 1000 条(用户确认),全集团一次拉取即可减少翻页请求
|
||||
REPORT_PAGE_SIZE = 1000
|
||||
|
||||
|
||||
def fetch_attendance_stat_page(
|
||||
session,
|
||||
user_id: str,
|
||||
month: str,
|
||||
page_no: int = 1,
|
||||
page_size: int = REPORT_PAGE_SIZE,
|
||||
stru_id: str = COMPANY_STRU_ID,
|
||||
base_code: str = "",
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
请求单页"考勤统计报表"数据(aa.md 提供的接口入参)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
user_id: 由 getCurUserInfo 返回的 userId(当前登录用户)
|
||||
month: 查询月份 "YYYYMM"
|
||||
page_no: 页码(从 1 开始)
|
||||
page_size: 每页条数(单页最大 1000)
|
||||
stru_id: 集团根组织 struId,默认 COMPANY_STRU_ID
|
||||
base_code: 员工工号;非空时仅查该员工(用于跨月追溯单人查询)
|
||||
|
||||
Returns:
|
||||
接口返回的 JSON 字典(datas 为明细数组,pageCount 为总页数)
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
HRSessionExpiredError: 登录态过期(接口返回非 JSON)
|
||||
"""
|
||||
params = {
|
||||
"reportId": MONTH_ATT_REPORT_ID,
|
||||
"struId": stru_id,
|
||||
"start": (page_no - 1) * page_size,
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
"ds1.userId": user_id,
|
||||
"ds1.struId": stru_id,
|
||||
"ds1.month": month,
|
||||
"ds2.stru_id": stru_id,
|
||||
"ds3.month": "#ds1.month#",
|
||||
"orgTypeCode": "1",
|
||||
"rootId": "cq37du",
|
||||
"showSetField": "1",
|
||||
"menuName": "考勤统计报表",
|
||||
"treePermitType": "permit",
|
||||
"struTreeCode": "cq37du",
|
||||
"belongUnitStruId": stru_id,
|
||||
"isVirtual": "0",
|
||||
"isHistory": "undefined",
|
||||
"useSealTreeData": "0",
|
||||
"orgAlias": "集团",
|
||||
"commonQuery": "[]",
|
||||
"ds1.base_code": base_code,
|
||||
}
|
||||
url = f"{MONTH_ATT_REPORT_URL}?reportsId={MONTH_ATT_REPORT_ID}"
|
||||
return hr_request_json(session, "POST", url, params, "考勤统计报表")
|
||||
|
||||
|
||||
def fetch_all_attendance_stat(
|
||||
session,
|
||||
user_id: str,
|
||||
month: str,
|
||||
stru_id: str = COMPANY_STRU_ID,
|
||||
base_code: str = "",
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
分页抓取某月考勤统计报表明细(每人一行,含 v_1~v_最后一天)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
user_id: 由 getCurUserInfo 返回的 userId
|
||||
month: 查询月份 "YYYYMM"
|
||||
stru_id: 集团根组织 struId,默认 COMPANY_STRU_ID
|
||||
base_code: 员工工号;非空时仅查该员工(用于跨月追溯单人查询)
|
||||
|
||||
Returns:
|
||||
报表明细列表(接口 datas 字段内容)
|
||||
|
||||
Raises:
|
||||
HRSessionExpiredError: 登录态过期且重新登录后仍失败
|
||||
"""
|
||||
all_rows: List[Dict[str, Any]] = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_attendance_stat_page(session, user_id, month, page_no,
|
||||
REPORT_PAGE_SIZE, stru_id, base_code)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("考勤统计报表 HR 登录态过期,重新登录后续抓")
|
||||
from app.service.hrbp.common.hr_session import refresh_hr_session
|
||||
session = refresh_hr_session()
|
||||
# 重新登录后需重新获取当前用户 userId
|
||||
from app.service.hrbp.ehr.common.hr_api.attendance import fetch_cur_user_info
|
||||
user_id = fetch_cur_user_info(session).get("userId", "")
|
||||
data = fetch_attendance_stat_page(session, user_id, month, page_no,
|
||||
REPORT_PAGE_SIZE, stru_id, base_code)
|
||||
|
||||
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) # 轻微限速,避免触发风控
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common.hr_api
|
||||
@FileName: attendance_stat.py
|
||||
@Description: 考勤统计报表(逐日出勤)查询接口:
|
||||
- fetch_attendance_stat_page:请求单页报表数据
|
||||
- fetch_all_attendance_stat:分页抓取某月全集团逐日出勤明细(每人一行,含 v_1~v_最后一天)
|
||||
- 登录态过期自动重登(复用 hr_session)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import time
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
from app.service.hrbp.ehr.common.config import (
|
||||
MONTH_ATT_REPORT_URL,
|
||||
MONTH_ATT_REPORT_ID,
|
||||
COMPANY_STRU_ID,
|
||||
)
|
||||
from app.service.hrbp.common.hr_session import HRSessionExpiredError, hr_request_json
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# 报表接口单页最大支持 1000 条(用户确认),全集团一次拉取即可减少翻页请求
|
||||
REPORT_PAGE_SIZE = 1000
|
||||
|
||||
|
||||
def fetch_attendance_stat_page(
|
||||
session,
|
||||
user_id: str,
|
||||
month: str,
|
||||
page_no: int = 1,
|
||||
page_size: int = REPORT_PAGE_SIZE,
|
||||
stru_id: str = COMPANY_STRU_ID,
|
||||
base_code: str = "",
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
请求单页"考勤统计报表"数据(aa.md 提供的接口入参)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
user_id: 由 getCurUserInfo 返回的 userId(当前登录用户)
|
||||
month: 查询月份 "YYYYMM"
|
||||
page_no: 页码(从 1 开始)
|
||||
page_size: 每页条数(单页最大 1000)
|
||||
stru_id: 集团根组织 struId,默认 COMPANY_STRU_ID
|
||||
base_code: 员工工号;非空时仅查该员工(用于跨月追溯单人查询)
|
||||
|
||||
Returns:
|
||||
接口返回的 JSON 字典(datas 为明细数组,pageCount 为总页数)
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
HRSessionExpiredError: 登录态过期(接口返回非 JSON)
|
||||
"""
|
||||
params = {
|
||||
"reportId": MONTH_ATT_REPORT_ID,
|
||||
"struId": stru_id,
|
||||
"start": (page_no - 1) * page_size,
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
"ds1.userId": user_id,
|
||||
"ds1.struId": stru_id,
|
||||
"ds1.month": month,
|
||||
"ds2.stru_id": stru_id,
|
||||
"ds3.month": "#ds1.month#",
|
||||
"orgTypeCode": "1",
|
||||
"rootId": "cq37du",
|
||||
"showSetField": "1",
|
||||
"menuName": "考勤统计报表",
|
||||
"treePermitType": "permit",
|
||||
"struTreeCode": "cq37du",
|
||||
"belongUnitStruId": stru_id,
|
||||
"isVirtual": "0",
|
||||
"isHistory": "undefined",
|
||||
"useSealTreeData": "0",
|
||||
"orgAlias": "集团",
|
||||
"commonQuery": "[]",
|
||||
"ds1.base_code": base_code,
|
||||
}
|
||||
url = f"{MONTH_ATT_REPORT_URL}?reportsId={MONTH_ATT_REPORT_ID}"
|
||||
return hr_request_json(session, "POST", url, params, "考勤统计报表")
|
||||
|
||||
|
||||
def fetch_all_attendance_stat(
|
||||
session,
|
||||
user_id: str,
|
||||
month: str,
|
||||
stru_id: str = COMPANY_STRU_ID,
|
||||
base_code: str = "",
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
分页抓取某月考勤统计报表明细(每人一行,含 v_1~v_最后一天)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
user_id: 由 getCurUserInfo 返回的 userId
|
||||
month: 查询月份 "YYYYMM"
|
||||
stru_id: 集团根组织 struId,默认 COMPANY_STRU_ID
|
||||
base_code: 员工工号;非空时仅查该员工(用于跨月追溯单人查询)
|
||||
|
||||
Returns:
|
||||
报表明细列表(接口 datas 字段内容)
|
||||
|
||||
Raises:
|
||||
HRSessionExpiredError: 登录态过期且重新登录后仍失败
|
||||
"""
|
||||
all_rows: List[Dict[str, Any]] = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_attendance_stat_page(session, user_id, month, page_no,
|
||||
REPORT_PAGE_SIZE, stru_id, base_code)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("考勤统计报表 HR 登录态过期,重新登录后续抓")
|
||||
from app.service.hrbp.common.hr_session import refresh_hr_session
|
||||
session = refresh_hr_session()
|
||||
# 重新登录后需重新获取当前用户 userId
|
||||
from app.service.hrbp.ehr.common.hr_api.attendance import fetch_cur_user_info
|
||||
user_id = fetch_cur_user_info(session).get("userId", "")
|
||||
data = fetch_attendance_stat_page(session, user_id, month, page_no,
|
||||
REPORT_PAGE_SIZE, stru_id, base_code)
|
||||
|
||||
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
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,190 +1,190 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.employer_insurance.config
|
||||
@FileName: config.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-13
|
||||
@Description: 雇主险模块配置:集中管理文件路径、Sheet 名称、列名映射、校验常量等
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
from datetime import datetime
|
||||
|
||||
from app.service.hrbp.ehr.common.config import ROSTER_TEMPLATE_EMPLOYER_INSURANCE
|
||||
|
||||
# ---------- 文件路径 ----------
|
||||
BASE_DIR = r"D:\资料\人资\雇主险"
|
||||
DATE_STR = datetime.now().strftime("%Y.%m.%d")
|
||||
DATE_SHORT = datetime.now().strftime("%m.%d")
|
||||
TODAY_DATE = datetime.now().strftime("%Y-%m-%d")
|
||||
|
||||
# 输入/输出文件路径(三十七度默认,其余类别由 CATEGORIES 动态解析)
|
||||
OUTPUT_IN_PARAM = os.path.join(BASE_DIR, f"新在参名单-{DATE_STR}.xlsx")
|
||||
|
||||
# ---------- 四大类别(全流程按类别传参处理) ----------
|
||||
# 每类一个独立文件夹,目标文件为文件夹内最新的「*雇主险变更记录*.xlsx」。
|
||||
# include_dept: 仅保留的所属单位(空列表=不限制);exclude_dept: 需要排除的所属单位;
|
||||
# change_sheet_prefix: 步骤2调度时「变更清单」sheet 名称前缀(各类须统一该命名规则)。
|
||||
# scheme_suffix: 增员导入时「保险方案名称」追加的厂区后缀(HR 侧方案含后缀,
|
||||
# 如 人保-80万-秒创 / 人保-80万-湖畔 / 人保-80万-水庄;三十七度无后缀)。
|
||||
CATEGORIES = [
|
||||
{
|
||||
"name": "三十七度",
|
||||
"folder": os.path.join(BASE_DIR, "三十七度"),
|
||||
"include_dept": [],
|
||||
"exclude_dept": ["金色湖畔事业部", "秒创传媒事业部", "水庄大鹅事业部"],
|
||||
"change_sheet_prefix": "37度-雇员变更清单",
|
||||
"scheme_suffix": "",
|
||||
},
|
||||
{
|
||||
"name": "水庄餐饮",
|
||||
"folder": os.path.join(BASE_DIR, "水庄餐饮"),
|
||||
"include_dept": ["水庄大鹅事业部"],
|
||||
"exclude_dept": [],
|
||||
"change_sheet_prefix": "水庄-雇员变更清单",
|
||||
"scheme_suffix": "水庄",
|
||||
},
|
||||
{
|
||||
"name": "湖畔酒店",
|
||||
"folder": os.path.join(BASE_DIR, "湖畔酒店"),
|
||||
"include_dept": ["金色湖畔事业部"],
|
||||
"exclude_dept": [],
|
||||
"change_sheet_prefix": "湖畔-雇员变更清单",
|
||||
"scheme_suffix": "湖畔",
|
||||
},
|
||||
{
|
||||
"name": "秒创传媒",
|
||||
"folder": os.path.join(BASE_DIR, "秒创传媒"),
|
||||
"include_dept": ["秒创传媒事业部"],
|
||||
"exclude_dept": [],
|
||||
"change_sheet_prefix": "秒创-雇员变更清单",
|
||||
"scheme_suffix": "秒创",
|
||||
},
|
||||
]
|
||||
|
||||
# ---------- 类别辅助函数(全流程共用) ----------
|
||||
def get_category(name):
|
||||
"""按名称获取类别配置(支持精确名或唯一前缀,如「湖畔」/「湖畔酒店」)。
|
||||
|
||||
Args:
|
||||
name: 类别名
|
||||
|
||||
Returns:
|
||||
类别配置 dict
|
||||
|
||||
Raises:
|
||||
ValueError: 未知名或前缀不唯一
|
||||
"""
|
||||
name = (name or "").strip()
|
||||
for c in CATEGORIES:
|
||||
if c["name"] == name:
|
||||
return c
|
||||
matched = [c for c in CATEGORIES if c["name"].startswith(name)]
|
||||
if len(matched) == 1:
|
||||
return matched[0]
|
||||
raise ValueError(f"未知类别:{name},可选:{[c['name'] for c in CATEGORIES]}")
|
||||
|
||||
|
||||
def find_latest_target(folder):
|
||||
"""在类别文件夹中定位最新的「*雇主险变更记录*.xlsx」目标文件。
|
||||
|
||||
Args:
|
||||
folder: 类别文件夹路径
|
||||
|
||||
Returns:
|
||||
最新目标文件绝对路径
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 文件夹不存在或其中没有符合条件的雇主险变更记录文件
|
||||
"""
|
||||
if not os.path.isdir(folder):
|
||||
raise FileNotFoundError(f"类别文件夹不存在:{folder}")
|
||||
candidates = [
|
||||
os.path.join(folder, f)
|
||||
for f in os.listdir(folder)
|
||||
if f.lower().endswith(".xlsx") and "雇主险变更记录" in f
|
||||
]
|
||||
if not candidates:
|
||||
raise FileNotFoundError(
|
||||
f"文件夹 {folder} 下未找到「*雇主险变更记录*.xlsx」文件,请先准备今日的雇主险变更记录模板")
|
||||
return max(candidates, key=os.path.getmtime)
|
||||
|
||||
|
||||
def category_target_file(category):
|
||||
"""类别目标文件(各文件夹内最新的雇主险变更记录)。"""
|
||||
return find_latest_target(category["folder"])
|
||||
|
||||
|
||||
def category_output_backup(category):
|
||||
"""类别「新在参名单」备份路径(放在类别文件夹内)。"""
|
||||
return os.path.join(category["folder"], f"新在参名单-{DATE_STR}.xlsx")
|
||||
|
||||
|
||||
def category_change_sheet_workbook(category):
|
||||
"""类别「雇员变更清单」独立工作簿路径(放在类别文件夹内,调度后复制变更清单 sheet)。"""
|
||||
return os.path.join(category["folder"], f"{category['name']}-雇员变更清单-{DATE_STR}.xlsx")
|
||||
|
||||
|
||||
def category_change_sheet_name(category):
|
||||
"""类别「变更清单」sheet 名称。"""
|
||||
return f"{category['change_sheet_prefix']}-{DATE_SHORT}"
|
||||
|
||||
|
||||
def category_import_add_file(category):
|
||||
"""类别「增员导入」文件路径(放在类别文件夹内)。"""
|
||||
return os.path.join(category["folder"], "商业保险增员导入.xlsx")
|
||||
|
||||
|
||||
def category_import_sub_file(category):
|
||||
"""类别「减员导入」文件路径(放在类别文件夹内)。"""
|
||||
return os.path.join(category["folder"], "商业保险减员导入.xlsx")
|
||||
|
||||
# 增减员导入文件(步骤3:在 HR「待增减人员」页面上传,aa.md 提供)
|
||||
ADD_SUB_IMPORT_ADD_FILE = os.path.join(BASE_DIR, "商业保险增员导入.xlsx")
|
||||
ADD_SUB_IMPORT_SUB_FILE = os.path.join(BASE_DIR, "商业保险减员导入.xlsx")
|
||||
|
||||
# 增减员导入模板(官方模板:第1行标题/第2行表头/第3行示例说明,第4行起填数据)
|
||||
ADD_IMPORT_TEMPLATE = os.path.join(BASE_DIR, "商业保险增员导入模板.xlsx")
|
||||
SUB_IMPORT_TEMPLATE = os.path.join(BASE_DIR, "商业保险减员导入模板.xlsx")
|
||||
|
||||
# 固定 Sheet 名称
|
||||
SHEET_BIZ = "花名册导出-雇主险使用基础信息"
|
||||
SHEET_IN_PARAM = "手动维护-在参名单"
|
||||
CHANGE_SHEET_PREFIX = "37度-雇员变更清单"
|
||||
CHANGE_SHEET_NAME = f"{CHANGE_SHEET_PREFIX}-{DATE_SHORT}"
|
||||
|
||||
# ---------- 花名册列名映射(表头在第4行) ----------
|
||||
BIZ_COL_EMPLOYEE_ID = "证件号" # O列,员工唯一标识
|
||||
BIZ_COL_CATEGORY = "工种类别" # P列
|
||||
BIZ_COL_SCHEME = "投保方案" # Q列
|
||||
BIZ_COL_HANDLE = "方案处理" # W列,值: 增加投保 / 要替换 / /
|
||||
|
||||
# 数据起始行(第17行开始是数据区域,前16行是固定标题/兼职数据)
|
||||
DATA_START_ROW = 17
|
||||
|
||||
# ---------- 校验常量 ----------
|
||||
VALID_CATEGORIES = ["一类", "二类", "三类", "四类"]
|
||||
VALID_SCHEMES = ["人保-20万", "人保-50万", "人保-80万"]
|
||||
|
||||
|
||||
def scheme_with_suffix(category, scheme):
|
||||
"""增员导入「保险方案名称」追加厂区后缀(如 人保-80万 -> 人保-80万-秒创)。
|
||||
|
||||
源数据投保方案为无后缀的人保-X万;HR 侧方案列表含厂区后缀,
|
||||
生成增员导入文件时按类别追加。已带对应后缀或后缀为空时原样返回。
|
||||
"""
|
||||
suffix = str(category.get("scheme_suffix") or "").strip()
|
||||
scheme = str(scheme or "").strip()
|
||||
if suffix and scheme and not scheme.endswith("-" + suffix):
|
||||
return f"{scheme}-{suffix}"
|
||||
return scheme
|
||||
|
||||
# ---------- 功能开关 ----------
|
||||
ENABLE_VALIDATION = False # True: 启用数据校验, False: 跳过校验(测试模式)
|
||||
|
||||
# ---------- 本场景 HR 花名册导出模板(roster_export 动态传入,取自 ehr/common 统一配置) ----------
|
||||
ROSTER_TEMPLATE_NAME = ROSTER_TEMPLATE_EMPLOYER_INSURANCE
|
||||
|
||||
# 本场景需导出的在职状态(雇主险增减员只需在职人员,无需离职)
|
||||
ROSTER_EXPORT_STATUSES = ["在职"]
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.employer_insurance.config
|
||||
@FileName: config.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-13
|
||||
@Description: 雇主险模块配置:集中管理文件路径、Sheet 名称、列名映射、校验常量等
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
from datetime import datetime
|
||||
|
||||
from app.service.hrbp.ehr.common.config import ROSTER_TEMPLATE_EMPLOYER_INSURANCE
|
||||
|
||||
# ---------- 文件路径 ----------
|
||||
BASE_DIR = r"D:\资料\人资\雇主险"
|
||||
DATE_STR = datetime.now().strftime("%Y.%m.%d")
|
||||
DATE_SHORT = datetime.now().strftime("%m.%d")
|
||||
TODAY_DATE = datetime.now().strftime("%Y-%m-%d")
|
||||
|
||||
# 输入/输出文件路径(三十七度默认,其余类别由 CATEGORIES 动态解析)
|
||||
OUTPUT_IN_PARAM = os.path.join(BASE_DIR, f"新在参名单-{DATE_STR}.xlsx")
|
||||
|
||||
# ---------- 四大类别(全流程按类别传参处理) ----------
|
||||
# 每类一个独立文件夹,目标文件为文件夹内最新的「*雇主险变更记录*.xlsx」。
|
||||
# include_dept: 仅保留的所属单位(空列表=不限制);exclude_dept: 需要排除的所属单位;
|
||||
# change_sheet_prefix: 步骤2调度时「变更清单」sheet 名称前缀(各类须统一该命名规则)。
|
||||
# scheme_suffix: 增员导入时「保险方案名称」追加的厂区后缀(HR 侧方案含后缀,
|
||||
# 如 人保-80万-秒创 / 人保-80万-湖畔 / 人保-80万-水庄;三十七度无后缀)。
|
||||
CATEGORIES = [
|
||||
{
|
||||
"name": "三十七度",
|
||||
"folder": os.path.join(BASE_DIR, "三十七度"),
|
||||
"include_dept": [],
|
||||
"exclude_dept": ["金色湖畔事业部", "秒创传媒事业部", "水庄大鹅事业部"],
|
||||
"change_sheet_prefix": "37度-雇员变更清单",
|
||||
"scheme_suffix": "",
|
||||
},
|
||||
{
|
||||
"name": "水庄餐饮",
|
||||
"folder": os.path.join(BASE_DIR, "水庄餐饮"),
|
||||
"include_dept": ["水庄大鹅事业部"],
|
||||
"exclude_dept": [],
|
||||
"change_sheet_prefix": "水庄-雇员变更清单",
|
||||
"scheme_suffix": "水庄",
|
||||
},
|
||||
{
|
||||
"name": "湖畔酒店",
|
||||
"folder": os.path.join(BASE_DIR, "湖畔酒店"),
|
||||
"include_dept": ["金色湖畔事业部"],
|
||||
"exclude_dept": [],
|
||||
"change_sheet_prefix": "湖畔-雇员变更清单",
|
||||
"scheme_suffix": "湖畔",
|
||||
},
|
||||
{
|
||||
"name": "秒创传媒",
|
||||
"folder": os.path.join(BASE_DIR, "秒创传媒"),
|
||||
"include_dept": ["秒创传媒事业部"],
|
||||
"exclude_dept": [],
|
||||
"change_sheet_prefix": "秒创-雇员变更清单",
|
||||
"scheme_suffix": "秒创",
|
||||
},
|
||||
]
|
||||
|
||||
# ---------- 类别辅助函数(全流程共用) ----------
|
||||
def get_category(name):
|
||||
"""按名称获取类别配置(支持精确名或唯一前缀,如「湖畔」/「湖畔酒店」)。
|
||||
|
||||
Args:
|
||||
name: 类别名
|
||||
|
||||
Returns:
|
||||
类别配置 dict
|
||||
|
||||
Raises:
|
||||
ValueError: 未知名或前缀不唯一
|
||||
"""
|
||||
name = (name or "").strip()
|
||||
for c in CATEGORIES:
|
||||
if c["name"] == name:
|
||||
return c
|
||||
matched = [c for c in CATEGORIES if c["name"].startswith(name)]
|
||||
if len(matched) == 1:
|
||||
return matched[0]
|
||||
raise ValueError(f"未知类别:{name},可选:{[c['name'] for c in CATEGORIES]}")
|
||||
|
||||
|
||||
def find_latest_target(folder):
|
||||
"""在类别文件夹中定位最新的「*雇主险变更记录*.xlsx」目标文件。
|
||||
|
||||
Args:
|
||||
folder: 类别文件夹路径
|
||||
|
||||
Returns:
|
||||
最新目标文件绝对路径
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 文件夹不存在或其中没有符合条件的雇主险变更记录文件
|
||||
"""
|
||||
if not os.path.isdir(folder):
|
||||
raise FileNotFoundError(f"类别文件夹不存在:{folder}")
|
||||
candidates = [
|
||||
os.path.join(folder, f)
|
||||
for f in os.listdir(folder)
|
||||
if f.lower().endswith(".xlsx") and "雇主险变更记录" in f
|
||||
]
|
||||
if not candidates:
|
||||
raise FileNotFoundError(
|
||||
f"文件夹 {folder} 下未找到「*雇主险变更记录*.xlsx」文件,请先准备今日的雇主险变更记录模板")
|
||||
return max(candidates, key=os.path.getmtime)
|
||||
|
||||
|
||||
def category_target_file(category):
|
||||
"""类别目标文件(各文件夹内最新的雇主险变更记录)。"""
|
||||
return find_latest_target(category["folder"])
|
||||
|
||||
|
||||
def category_output_backup(category):
|
||||
"""类别「新在参名单」备份路径(放在类别文件夹内)。"""
|
||||
return os.path.join(category["folder"], f"新在参名单-{DATE_STR}.xlsx")
|
||||
|
||||
|
||||
def category_change_sheet_workbook(category):
|
||||
"""类别「雇员变更清单」独立工作簿路径(放在类别文件夹内,调度后复制变更清单 sheet)。"""
|
||||
return os.path.join(category["folder"], f"{category['name']}-雇员变更清单-{DATE_STR}.xlsx")
|
||||
|
||||
|
||||
def category_change_sheet_name(category):
|
||||
"""类别「变更清单」sheet 名称。"""
|
||||
return f"{category['change_sheet_prefix']}-{DATE_SHORT}"
|
||||
|
||||
|
||||
def category_import_add_file(category):
|
||||
"""类别「增员导入」文件路径(放在类别文件夹内)。"""
|
||||
return os.path.join(category["folder"], "商业保险增员导入.xlsx")
|
||||
|
||||
|
||||
def category_import_sub_file(category):
|
||||
"""类别「减员导入」文件路径(放在类别文件夹内)。"""
|
||||
return os.path.join(category["folder"], "商业保险减员导入.xlsx")
|
||||
|
||||
# 增减员导入文件(步骤3:在 HR「待增减人员」页面上传,aa.md 提供)
|
||||
ADD_SUB_IMPORT_ADD_FILE = os.path.join(BASE_DIR, "商业保险增员导入.xlsx")
|
||||
ADD_SUB_IMPORT_SUB_FILE = os.path.join(BASE_DIR, "商业保险减员导入.xlsx")
|
||||
|
||||
# 增减员导入模板(官方模板:第1行标题/第2行表头/第3行示例说明,第4行起填数据)
|
||||
ADD_IMPORT_TEMPLATE = os.path.join(BASE_DIR, "商业保险增员导入模板.xlsx")
|
||||
SUB_IMPORT_TEMPLATE = os.path.join(BASE_DIR, "商业保险减员导入模板.xlsx")
|
||||
|
||||
# 固定 Sheet 名称
|
||||
SHEET_BIZ = "花名册导出-雇主险使用基础信息"
|
||||
SHEET_IN_PARAM = "手动维护-在参名单"
|
||||
CHANGE_SHEET_PREFIX = "37度-雇员变更清单"
|
||||
CHANGE_SHEET_NAME = f"{CHANGE_SHEET_PREFIX}-{DATE_SHORT}"
|
||||
|
||||
# ---------- 花名册列名映射(表头在第4行) ----------
|
||||
BIZ_COL_EMPLOYEE_ID = "证件号" # O列,员工唯一标识
|
||||
BIZ_COL_CATEGORY = "工种类别" # P列
|
||||
BIZ_COL_SCHEME = "投保方案" # Q列
|
||||
BIZ_COL_HANDLE = "方案处理" # W列,值: 增加投保 / 要替换 / /
|
||||
|
||||
# 数据起始行(第17行开始是数据区域,前16行是固定标题/兼职数据)
|
||||
DATA_START_ROW = 17
|
||||
|
||||
# ---------- 校验常量 ----------
|
||||
VALID_CATEGORIES = ["一类", "二类", "三类", "四类"]
|
||||
VALID_SCHEMES = ["人保-20万", "人保-50万", "人保-80万"]
|
||||
|
||||
|
||||
def scheme_with_suffix(category, scheme):
|
||||
"""增员导入「保险方案名称」追加厂区后缀(如 人保-80万 -> 人保-80万-秒创)。
|
||||
|
||||
源数据投保方案为无后缀的人保-X万;HR 侧方案列表含厂区后缀,
|
||||
生成增员导入文件时按类别追加。已带对应后缀或后缀为空时原样返回。
|
||||
"""
|
||||
suffix = str(category.get("scheme_suffix") or "").strip()
|
||||
scheme = str(scheme or "").strip()
|
||||
if suffix and scheme and not scheme.endswith("-" + suffix):
|
||||
return f"{scheme}-{suffix}"
|
||||
return scheme
|
||||
|
||||
# ---------- 功能开关 ----------
|
||||
ENABLE_VALIDATION = False # True: 启用数据校验, False: 跳过校验(测试模式)
|
||||
|
||||
# ---------- 本场景 HR 花名册导出模板(roster_export 动态传入,取自 ehr/common 统一配置) ----------
|
||||
ROSTER_TEMPLATE_NAME = ROSTER_TEMPLATE_EMPLOYER_INSURANCE
|
||||
|
||||
# 本场景需导出的在职状态(雇主险增减员只需在职人员,无需离职)
|
||||
ROSTER_EXPORT_STATUSES = ["在职"]
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,135 +1,135 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.employer_insurance.export_change_sheet
|
||||
@FileName: export_change_sheet.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-26
|
||||
@Description: 雇主险名额调度系统(app 版)「步骤2.5:导出变更清单独立工作簿」
|
||||
前置:先运行 employer_insurance.py(步骤2:调度),并手动打开目标文件
|
||||
刷新公式计算结果(Ctrl+S 保存)后,再运行本步骤。
|
||||
将各类别目标文件中「变更清单」sheet 单独复制为独立工作簿:
|
||||
- 保留样式与格式(字体/边框/填充/数字格式/对齐/列宽/行高/合并单元格)
|
||||
- 单元格内容写为「值」而非公式(以 data_only 读取公式的缓存计算结果),
|
||||
避免独立成簿后公式引用其他 Sheet 产生 #REF! 等计算错误
|
||||
- 不改动原目标文件
|
||||
|
||||
【运行】python export_change_sheet.py [类别名]
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 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 copy import copy # noqa: E402
|
||||
from openpyxl import Workbook, load_workbook # noqa: E402
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
from app.service.hrbp.ehr.employer_insurance.config import ( # noqa: E402
|
||||
CATEGORIES,
|
||||
get_category,
|
||||
category_target_file,
|
||||
category_change_sheet_workbook,
|
||||
category_change_sheet_name,
|
||||
)
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def export_change_sheet_workbook(category):
|
||||
"""将类别目标文件中「变更清单」sheet 复制为独立工作簿(值 + 样式,无公式)。
|
||||
|
||||
以 data_only=True 加载目标文件:公式单元格直接取缓存计算结果(值),普通单元格
|
||||
取原值;样式 / 列宽 / 行高 / 合并单元格原样保留,不改动原目标文件。
|
||||
|
||||
Args:
|
||||
category: 类别配置 dict
|
||||
|
||||
Returns:
|
||||
bool: 是否成功生成(文件缺失 / sheet 不存在时返回 False)。
|
||||
"""
|
||||
category_name = category["name"]
|
||||
target_file = category_target_file(category)
|
||||
change_sheet_name = category_change_sheet_name(category)
|
||||
out_path = category_change_sheet_workbook(category)
|
||||
|
||||
if not os.path.isfile(target_file):
|
||||
logger.warning("类别[%s] 目标文件不存在,跳过:%s", category_name, target_file)
|
||||
return False
|
||||
|
||||
# data_only=True:公式单元格返回其缓存计算结果(值),而非公式字符串
|
||||
wb = load_workbook(target_file, data_only=True)
|
||||
if change_sheet_name not in wb.sheetnames:
|
||||
logger.warning("类别[%s] 工作簿中不存在变更清单 sheet [%s],跳过",
|
||||
category_name, change_sheet_name)
|
||||
return False
|
||||
src = wb[change_sheet_name]
|
||||
|
||||
out_wb = Workbook()
|
||||
out_ws = out_wb.active
|
||||
out_ws.title = change_sheet_name
|
||||
|
||||
# 复制单元格(值 + 样式)
|
||||
for row in src.iter_rows():
|
||||
for cell in row:
|
||||
dst = out_ws.cell(row=cell.row, column=cell.column, value=cell.value)
|
||||
if cell.has_style:
|
||||
dst.font = copy(cell.font)
|
||||
dst.border = copy(cell.border)
|
||||
dst.fill = copy(cell.fill)
|
||||
dst.number_format = cell.number_format
|
||||
dst.alignment = copy(cell.alignment)
|
||||
|
||||
# 复制列宽 / 行高
|
||||
for col_letter, dim in src.column_dimensions.items():
|
||||
if dim.width:
|
||||
out_ws.column_dimensions[col_letter].width = dim.width
|
||||
for row_idx, dim in src.row_dimensions.items():
|
||||
if dim.height:
|
||||
out_ws.row_dimensions[row_idx].height = dim.height
|
||||
# 复制合并单元格
|
||||
for mc in src.merged_cells.ranges:
|
||||
out_ws.merge_cells(str(mc))
|
||||
|
||||
out_wb.save(out_path)
|
||||
logger.info("类别[%s] 已导出变更清单独立工作簿:%s(sheet:%s,公式已转为值)",
|
||||
category_name, out_path, change_sheet_name)
|
||||
return True
|
||||
|
||||
|
||||
def main(category_name: str = None):
|
||||
"""步骤2.5:导出变更清单独立工作簿。
|
||||
|
||||
Args:
|
||||
category_name: 类别名(如「湖畔酒店」/「湖畔」),None 表示处理全部类别。
|
||||
|
||||
前置:先运行 employer_insurance.py(步骤2:调度),并手动打开目标文件
|
||||
刷新公式计算结果(Ctrl+S 保存)后,再运行本步骤。
|
||||
"""
|
||||
categories = [get_category(category_name)] if category_name else CATEGORIES
|
||||
for category in categories:
|
||||
try:
|
||||
export_change_sheet_workbook(category)
|
||||
except Exception:
|
||||
logger.exception("类别[%s] 导出变更清单工作簿失败", category["name"])
|
||||
logger.info("全部完成!")
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 程序入口
|
||||
# ============================================================
|
||||
if __name__ == "__main__":
|
||||
setup_logging()
|
||||
main()
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.employer_insurance.export_change_sheet
|
||||
@FileName: export_change_sheet.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-26
|
||||
@Description: 雇主险名额调度系统(app 版)「步骤2.5:导出变更清单独立工作簿」
|
||||
前置:先运行 employer_insurance.py(步骤2:调度),并手动打开目标文件
|
||||
刷新公式计算结果(Ctrl+S 保存)后,再运行本步骤。
|
||||
将各类别目标文件中「变更清单」sheet 单独复制为独立工作簿:
|
||||
- 保留样式与格式(字体/边框/填充/数字格式/对齐/列宽/行高/合并单元格)
|
||||
- 单元格内容写为「值」而非公式(以 data_only 读取公式的缓存计算结果),
|
||||
避免独立成簿后公式引用其他 Sheet 产生 #REF! 等计算错误
|
||||
- 不改动原目标文件
|
||||
|
||||
【运行】python export_change_sheet.py [类别名]
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 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 copy import copy # noqa: E402
|
||||
from openpyxl import Workbook, load_workbook # noqa: E402
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
from app.service.hrbp.ehr.employer_insurance.config import ( # noqa: E402
|
||||
CATEGORIES,
|
||||
get_category,
|
||||
category_target_file,
|
||||
category_change_sheet_workbook,
|
||||
category_change_sheet_name,
|
||||
)
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def export_change_sheet_workbook(category):
|
||||
"""将类别目标文件中「变更清单」sheet 复制为独立工作簿(值 + 样式,无公式)。
|
||||
|
||||
以 data_only=True 加载目标文件:公式单元格直接取缓存计算结果(值),普通单元格
|
||||
取原值;样式 / 列宽 / 行高 / 合并单元格原样保留,不改动原目标文件。
|
||||
|
||||
Args:
|
||||
category: 类别配置 dict
|
||||
|
||||
Returns:
|
||||
bool: 是否成功生成(文件缺失 / sheet 不存在时返回 False)。
|
||||
"""
|
||||
category_name = category["name"]
|
||||
target_file = category_target_file(category)
|
||||
change_sheet_name = category_change_sheet_name(category)
|
||||
out_path = category_change_sheet_workbook(category)
|
||||
|
||||
if not os.path.isfile(target_file):
|
||||
logger.warning("类别[%s] 目标文件不存在,跳过:%s", category_name, target_file)
|
||||
return False
|
||||
|
||||
# data_only=True:公式单元格返回其缓存计算结果(值),而非公式字符串
|
||||
wb = load_workbook(target_file, data_only=True)
|
||||
if change_sheet_name not in wb.sheetnames:
|
||||
logger.warning("类别[%s] 工作簿中不存在变更清单 sheet [%s],跳过",
|
||||
category_name, change_sheet_name)
|
||||
return False
|
||||
src = wb[change_sheet_name]
|
||||
|
||||
out_wb = Workbook()
|
||||
out_ws = out_wb.active
|
||||
out_ws.title = change_sheet_name
|
||||
|
||||
# 复制单元格(值 + 样式)
|
||||
for row in src.iter_rows():
|
||||
for cell in row:
|
||||
dst = out_ws.cell(row=cell.row, column=cell.column, value=cell.value)
|
||||
if cell.has_style:
|
||||
dst.font = copy(cell.font)
|
||||
dst.border = copy(cell.border)
|
||||
dst.fill = copy(cell.fill)
|
||||
dst.number_format = cell.number_format
|
||||
dst.alignment = copy(cell.alignment)
|
||||
|
||||
# 复制列宽 / 行高
|
||||
for col_letter, dim in src.column_dimensions.items():
|
||||
if dim.width:
|
||||
out_ws.column_dimensions[col_letter].width = dim.width
|
||||
for row_idx, dim in src.row_dimensions.items():
|
||||
if dim.height:
|
||||
out_ws.row_dimensions[row_idx].height = dim.height
|
||||
# 复制合并单元格
|
||||
for mc in src.merged_cells.ranges:
|
||||
out_ws.merge_cells(str(mc))
|
||||
|
||||
out_wb.save(out_path)
|
||||
logger.info("类别[%s] 已导出变更清单独立工作簿:%s(sheet:%s,公式已转为值)",
|
||||
category_name, out_path, change_sheet_name)
|
||||
return True
|
||||
|
||||
|
||||
def main(category_name: str = None):
|
||||
"""步骤2.5:导出变更清单独立工作簿。
|
||||
|
||||
Args:
|
||||
category_name: 类别名(如「湖畔酒店」/「湖畔」),None 表示处理全部类别。
|
||||
|
||||
前置:先运行 employer_insurance.py(步骤2:调度),并手动打开目标文件
|
||||
刷新公式计算结果(Ctrl+S 保存)后,再运行本步骤。
|
||||
"""
|
||||
categories = [get_category(category_name)] if category_name else CATEGORIES
|
||||
for category in categories:
|
||||
try:
|
||||
export_change_sheet_workbook(category)
|
||||
except Exception:
|
||||
logger.exception("类别[%s] 导出变更清单工作簿失败", category["name"])
|
||||
logger.info("全部完成!")
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 程序入口
|
||||
# ============================================================
|
||||
if __name__ == "__main__":
|
||||
setup_logging()
|
||||
main()
|
||||
|
||||
@@ -1,236 +1,236 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.employer_insurance.roster_filter
|
||||
@FileName: roster_filter.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-13
|
||||
@Description: 雇主险流程「步骤1:筛选复制」。从员工花名册按四大类别筛选数据,复制到各自类别的雇主险变更记录表
|
||||
(复刻 aa.md 的 WPS JS 宏,仅复制,不校验)
|
||||
- 源表:员工花名册.xlsx(统一格式:单 sheet、表头自动定位、业务列 B~O 14列)
|
||||
- 四大类别(config.CATEGORIES):三十七度 / 水庄餐饮 / 湖畔酒店 / 秒创传媒,各自独立文件夹
|
||||
- 过滤:按类别 include/exclude 所属单位(B列)+ 统一排除「虚拟大区」(C列/一级部门)
|
||||
- 目标:各文件夹内最新的「*雇主险变更记录*.xlsx」的「花名册导出-雇主险使用基础信息」sheet,表头第4行,数据第5行起(B~O 14列)
|
||||
- 源表缺失时自动调用 roster_export 从 HR 系统导出(输出位置由本场景指定)
|
||||
@Version: 2.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 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)
|
||||
|
||||
import pandas as pd # noqa: E402
|
||||
from openpyxl import load_workbook # noqa: E402
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
from app.service.hrbp.ehr.employer_insurance.config import ( # noqa: E402
|
||||
BASE_DIR,
|
||||
CATEGORIES,
|
||||
SHEET_BIZ,
|
||||
ROSTER_TEMPLATE_NAME,
|
||||
ROSTER_EXPORT_STATUSES,
|
||||
get_category,
|
||||
find_latest_target,
|
||||
)
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ---------- 源表配置(与 aa.md 宏保持一致) ----------
|
||||
EMPLOYEE_FILE = os.path.join(BASE_DIR, "员工花名册.xlsx")
|
||||
EXCLUDE_REGION = "虚拟大区" # 统一排除的一级部门(各类别均生效)
|
||||
EXCLUDE_NAME_KEYWORDS = ["人资", "测试"] # 姓名(N列)含这些关键字的行剔除(测试账号/人资账号等)
|
||||
|
||||
# N列 姓名在数据切片(B~O)内的 0-based 索引
|
||||
NAME_COL = 12
|
||||
|
||||
# 源表统一格式规范(roster_export._merge_roster_files 输出):
|
||||
# 单 sheet、只保留第2行表头(丢弃第1行标题)、「类型」列统一在最后一列
|
||||
# 读取时自动定位表头行(B 列 =「所属单位」),业务列 B~O 共14列不受「类型」列影响
|
||||
SOURCE_HEADER_MARK = "所属单位" # 表头定位标记(B列)
|
||||
TARGET_HEADER_ROW = 4 # 目标表表头在第4行(数据第5行起)
|
||||
DATA_COLUMNS = 14 # B~O 共14列(所属单位..证件号)
|
||||
|
||||
|
||||
def filter_and_copy_roster(category: dict, employee_file: str = None, target_file: str = None) -> int:
|
||||
"""
|
||||
从员工花名册按类别筛选数据,复制到该类别的雇主险变更记录表(仅复制,不校验)。
|
||||
|
||||
Args:
|
||||
category: 类别配置(config.CATEGORIES 中的一项),含 name/folder/include_dept/exclude_dept
|
||||
employee_file: 源表路径,默认 D:\\资料\\人资\\雇主险\\员工花名册.xlsx
|
||||
target_file: 目标表路径,默认取该类别文件夹内最新的「*雇主险变更记录*.xlsx」
|
||||
|
||||
Returns:
|
||||
复制的数据行数
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 源表或目标表不存在
|
||||
ValueError: 源表列数不足 或 目标表缺少指定 Sheet
|
||||
"""
|
||||
category_name = category["name"]
|
||||
employee_file = os.path.abspath(employee_file or EMPLOYEE_FILE)
|
||||
target_file = os.path.abspath(target_file or find_latest_target(category["folder"]))
|
||||
|
||||
if not os.path.exists(employee_file):
|
||||
raise FileNotFoundError(f"源表不存在:{employee_file}")
|
||||
if not os.path.exists(target_file):
|
||||
raise FileNotFoundError(f"目标表不存在:{target_file}")
|
||||
|
||||
# ---------- 1. 读取源表(统一规范:单 sheet,自动定位表头行,业务列 B~O) ----------
|
||||
# 先不设表头读取前几行,找到 B 列 =「所属单位」的表头行位置
|
||||
probe = pd.read_excel(employee_file, header=None, nrows=8)
|
||||
header_row = None
|
||||
for idx in range(len(probe)):
|
||||
if str(probe.iloc[idx, 1]).strip() == SOURCE_HEADER_MARK:
|
||||
header_row = idx
|
||||
break
|
||||
if header_row is None:
|
||||
raise ValueError(f"源表未找到表头行(B 列应为「{SOURCE_HEADER_MARK}」)")
|
||||
|
||||
df = pd.read_excel(employee_file, header=header_row)
|
||||
if df.shape[1] < DATA_COLUMNS + 1:
|
||||
raise ValueError(f"源表列数不足:{df.shape[1]}(需要 B~O 共{DATA_COLUMNS}列)")
|
||||
data = df.iloc[:, 1:DATA_COLUMNS + 1].copy() # B~O 14列(「类型」列在末尾,不受影响)
|
||||
|
||||
# 与宏一致:以 B 列(所属单位)最后非空行为数据边界
|
||||
data = data[data.iloc[:, 0].notna()]
|
||||
|
||||
# ---------- 2. 过滤:按类别 include/exclude 所属单位 + 统一排除「虚拟大区」 + 姓名关键字剔除 ----------
|
||||
dept = data.iloc[:, 0].astype(str).str.strip()
|
||||
region = data.iloc[:, 1].astype(str).str.strip()
|
||||
name = data.iloc[:, NAME_COL].astype(str).str.strip()
|
||||
include_dept = category.get("include_dept") or []
|
||||
exclude_dept = category.get("exclude_dept") or []
|
||||
mask = ~(region == EXCLUDE_REGION)
|
||||
if include_dept:
|
||||
mask &= dept.isin(include_dept)
|
||||
if exclude_dept:
|
||||
mask &= ~dept.isin(exclude_dept)
|
||||
for kw in EXCLUDE_NAME_KEYWORDS:
|
||||
mask &= ~name.str.contains(kw, na=False)
|
||||
filtered = data[mask]
|
||||
logger.info("类别[%s]:源表共 %d 行,过滤后 %d 行(保留 %s / 排除 %s,并排除「%s」,姓名剔除含 %s)",
|
||||
category_name, len(data), len(filtered),
|
||||
include_dept or "全部", exclude_dept or "无", EXCLUDE_REGION,
|
||||
" / ".join(EXCLUDE_NAME_KEYWORDS))
|
||||
if len(filtered) == 0:
|
||||
logger.warning("类别[%s] 筛选后没有数据!", category_name)
|
||||
|
||||
# ---------- 3. 写目标表(先覆盖写入,只清空超出新数据的旧行,避免大范围逐格清空) ----------
|
||||
wb = load_workbook(target_file)
|
||||
if SHEET_BIZ not in wb.sheetnames:
|
||||
raise ValueError(f"目标表缺少 Sheet:{SHEET_BIZ}")
|
||||
ws = wb[SHEET_BIZ]
|
||||
first_data_row = TARGET_HEADER_ROW + 1 # 第5行
|
||||
|
||||
# 找 B 列当前最后非空数据行(用于清空多余旧行)
|
||||
old_last = first_data_row - 1
|
||||
for r in range(first_data_row, ws.max_row + 1):
|
||||
if ws.cell(row=r, column=2).value is not None:
|
||||
old_last = r
|
||||
|
||||
# 写入 B~O(覆盖旧数据,本地化 cell 引用减少开销)
|
||||
rows = filtered.values.tolist()
|
||||
cell = ws.cell
|
||||
for i, row in enumerate(rows, start=first_data_row):
|
||||
for j, val in enumerate(row, start=2):
|
||||
cell(row=i, column=j).value = val
|
||||
|
||||
# 清空超出新数据的旧行
|
||||
new_last = first_data_row + len(rows) - 1
|
||||
if old_last > new_last:
|
||||
for r in range(new_last + 1, old_last + 1):
|
||||
for c in range(2, 2 + DATA_COLUMNS):
|
||||
cell(row=r, column=c).value = None
|
||||
|
||||
wb.save(target_file)
|
||||
logger.info("类别[%s] 已写入目标表 %s 第%d行起,共 %d 行", category_name, target_file, first_data_row, len(rows))
|
||||
return len(rows)
|
||||
|
||||
|
||||
def export_roster_for_employer_insurance(download_dir: str = None, ttl: int = None) -> str:
|
||||
"""按本场景模板「雇主险增减员导出模板」导出花名册(复用 roster_export,操作 HR 系统)。
|
||||
|
||||
输出位置由本场景指定:D:\\资料\\人资\\雇主险\\员工花名册.xlsx(与筛选复制的源表路径一致)。
|
||||
|
||||
Args:
|
||||
download_dir: 浏览器下载临时目录,默认使用 roster_export 的默认目录。
|
||||
ttl: 缓存有效期(秒),None 用 roster_export 默认(15 分钟);传 0 强制重新导出。
|
||||
|
||||
Returns:
|
||||
合并后的花名册文件路径。
|
||||
"""
|
||||
from app.service.hrbp.ehr.roster.roster_export import export_roster
|
||||
output_path = os.path.join(BASE_DIR, "员工花名册.xlsx")
|
||||
logger.info("按本场景模板 [%s] 导出花名册(在职状态:%s),输出:%s",
|
||||
ROSTER_TEMPLATE_NAME, ROSTER_EXPORT_STATUSES, output_path)
|
||||
return export_roster(download_dir=download_dir, template_name=ROSTER_TEMPLATE_NAME,
|
||||
output_path=output_path, statuses=ROSTER_EXPORT_STATUSES, ttl=ttl)
|
||||
|
||||
|
||||
def main(category_name: str = None) -> None:
|
||||
"""步骤1:就绪检查 + 导出(如需)+ 类别筛选复制。
|
||||
|
||||
Args:
|
||||
category_name: 类别名(如「湖畔酒店」/「湖畔」),None 表示处理全部类别。
|
||||
|
||||
说明:openpyxl 写入后公式列(P~W 工种类别/投保方案/方案处理)的缓存结果会丢失,
|
||||
需手动打开各目标文件刷新公式计算结果并保存,确认复制无误后再运行 schedule 步骤
|
||||
(employer_insurance.py)。
|
||||
"""
|
||||
setup_logging()
|
||||
args = sys.argv[1:]
|
||||
|
||||
# 命令行第一个非 -- 参数可作为类别名(如:python roster_filter.py 湖畔酒店)
|
||||
if not category_name:
|
||||
for a in args:
|
||||
if not a.startswith("--"):
|
||||
category_name = a
|
||||
break
|
||||
categories = [get_category(category_name)] if category_name else CATEGORIES
|
||||
|
||||
# 源表(员工花名册)缺失才自动导出;--export-roster 为显式强制导出(ttl=0 绕过缓存)
|
||||
force = "--export-roster" in args
|
||||
if force or not os.path.exists(EMPLOYEE_FILE):
|
||||
export_roster_for_employer_insurance(ttl=0 if force else None)
|
||||
else:
|
||||
logger.info("源表已存在:%s,跳过导出", EMPLOYEE_FILE)
|
||||
|
||||
# 逐类别筛选复制(目标文件=各文件夹内最新的雇主险变更记录)
|
||||
ok = 0
|
||||
for category in categories:
|
||||
try:
|
||||
target_file = find_latest_target(category["folder"])
|
||||
except FileNotFoundError as e:
|
||||
logger.error("跳过类别[%s]:%s", category["name"], e)
|
||||
continue
|
||||
logger.info("=" * 70)
|
||||
logger.info("处理类别[%s],目标文件:%s", category["name"], target_file)
|
||||
try:
|
||||
n = filter_and_copy_roster(category, target_file=target_file)
|
||||
ok += 1
|
||||
logger.info("类别[%s] 完成,写入 %d 行", category["name"], n)
|
||||
except Exception:
|
||||
logger.exception("类别[%s] 处理失败", category["name"])
|
||||
|
||||
logger.info("=" * 70)
|
||||
logger.info("筛选复制完成(成功 %d/%d 个类别)。请手动打开各目标文件刷新公式计算结果(Ctrl+S 保存),",
|
||||
ok, len(categories))
|
||||
logger.info("确认无误后运行:python employer_insurance.py schedule")
|
||||
logger.info("=" * 70)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.employer_insurance.roster_filter
|
||||
@FileName: roster_filter.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-13
|
||||
@Description: 雇主险流程「步骤1:筛选复制」。从员工花名册按四大类别筛选数据,复制到各自类别的雇主险变更记录表
|
||||
(复刻 aa.md 的 WPS JS 宏,仅复制,不校验)
|
||||
- 源表:员工花名册.xlsx(统一格式:单 sheet、表头自动定位、业务列 B~O 14列)
|
||||
- 四大类别(config.CATEGORIES):三十七度 / 水庄餐饮 / 湖畔酒店 / 秒创传媒,各自独立文件夹
|
||||
- 过滤:按类别 include/exclude 所属单位(B列)+ 统一排除「虚拟大区」(C列/一级部门)
|
||||
- 目标:各文件夹内最新的「*雇主险变更记录*.xlsx」的「花名册导出-雇主险使用基础信息」sheet,表头第4行,数据第5行起(B~O 14列)
|
||||
- 源表缺失时自动调用 roster_export 从 HR 系统导出(输出位置由本场景指定)
|
||||
@Version: 2.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 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)
|
||||
|
||||
import pandas as pd # noqa: E402
|
||||
from openpyxl import load_workbook # noqa: E402
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
from app.service.hrbp.ehr.employer_insurance.config import ( # noqa: E402
|
||||
BASE_DIR,
|
||||
CATEGORIES,
|
||||
SHEET_BIZ,
|
||||
ROSTER_TEMPLATE_NAME,
|
||||
ROSTER_EXPORT_STATUSES,
|
||||
get_category,
|
||||
find_latest_target,
|
||||
)
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ---------- 源表配置(与 aa.md 宏保持一致) ----------
|
||||
EMPLOYEE_FILE = os.path.join(BASE_DIR, "员工花名册.xlsx")
|
||||
EXCLUDE_REGION = "虚拟大区" # 统一排除的一级部门(各类别均生效)
|
||||
EXCLUDE_NAME_KEYWORDS = ["人资", "测试"] # 姓名(N列)含这些关键字的行剔除(测试账号/人资账号等)
|
||||
|
||||
# N列 姓名在数据切片(B~O)内的 0-based 索引
|
||||
NAME_COL = 12
|
||||
|
||||
# 源表统一格式规范(roster_export._merge_roster_files 输出):
|
||||
# 单 sheet、只保留第2行表头(丢弃第1行标题)、「类型」列统一在最后一列
|
||||
# 读取时自动定位表头行(B 列 =「所属单位」),业务列 B~O 共14列不受「类型」列影响
|
||||
SOURCE_HEADER_MARK = "所属单位" # 表头定位标记(B列)
|
||||
TARGET_HEADER_ROW = 4 # 目标表表头在第4行(数据第5行起)
|
||||
DATA_COLUMNS = 14 # B~O 共14列(所属单位..证件号)
|
||||
|
||||
|
||||
def filter_and_copy_roster(category: dict, employee_file: str = None, target_file: str = None) -> int:
|
||||
"""
|
||||
从员工花名册按类别筛选数据,复制到该类别的雇主险变更记录表(仅复制,不校验)。
|
||||
|
||||
Args:
|
||||
category: 类别配置(config.CATEGORIES 中的一项),含 name/folder/include_dept/exclude_dept
|
||||
employee_file: 源表路径,默认 D:\\资料\\人资\\雇主险\\员工花名册.xlsx
|
||||
target_file: 目标表路径,默认取该类别文件夹内最新的「*雇主险变更记录*.xlsx」
|
||||
|
||||
Returns:
|
||||
复制的数据行数
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 源表或目标表不存在
|
||||
ValueError: 源表列数不足 或 目标表缺少指定 Sheet
|
||||
"""
|
||||
category_name = category["name"]
|
||||
employee_file = os.path.abspath(employee_file or EMPLOYEE_FILE)
|
||||
target_file = os.path.abspath(target_file or find_latest_target(category["folder"]))
|
||||
|
||||
if not os.path.exists(employee_file):
|
||||
raise FileNotFoundError(f"源表不存在:{employee_file}")
|
||||
if not os.path.exists(target_file):
|
||||
raise FileNotFoundError(f"目标表不存在:{target_file}")
|
||||
|
||||
# ---------- 1. 读取源表(统一规范:单 sheet,自动定位表头行,业务列 B~O) ----------
|
||||
# 先不设表头读取前几行,找到 B 列 =「所属单位」的表头行位置
|
||||
probe = pd.read_excel(employee_file, header=None, nrows=8)
|
||||
header_row = None
|
||||
for idx in range(len(probe)):
|
||||
if str(probe.iloc[idx, 1]).strip() == SOURCE_HEADER_MARK:
|
||||
header_row = idx
|
||||
break
|
||||
if header_row is None:
|
||||
raise ValueError(f"源表未找到表头行(B 列应为「{SOURCE_HEADER_MARK}」)")
|
||||
|
||||
df = pd.read_excel(employee_file, header=header_row)
|
||||
if df.shape[1] < DATA_COLUMNS + 1:
|
||||
raise ValueError(f"源表列数不足:{df.shape[1]}(需要 B~O 共{DATA_COLUMNS}列)")
|
||||
data = df.iloc[:, 1:DATA_COLUMNS + 1].copy() # B~O 14列(「类型」列在末尾,不受影响)
|
||||
|
||||
# 与宏一致:以 B 列(所属单位)最后非空行为数据边界
|
||||
data = data[data.iloc[:, 0].notna()]
|
||||
|
||||
# ---------- 2. 过滤:按类别 include/exclude 所属单位 + 统一排除「虚拟大区」 + 姓名关键字剔除 ----------
|
||||
dept = data.iloc[:, 0].astype(str).str.strip()
|
||||
region = data.iloc[:, 1].astype(str).str.strip()
|
||||
name = data.iloc[:, NAME_COL].astype(str).str.strip()
|
||||
include_dept = category.get("include_dept") or []
|
||||
exclude_dept = category.get("exclude_dept") or []
|
||||
mask = ~(region == EXCLUDE_REGION)
|
||||
if include_dept:
|
||||
mask &= dept.isin(include_dept)
|
||||
if exclude_dept:
|
||||
mask &= ~dept.isin(exclude_dept)
|
||||
for kw in EXCLUDE_NAME_KEYWORDS:
|
||||
mask &= ~name.str.contains(kw, na=False)
|
||||
filtered = data[mask]
|
||||
logger.info("类别[%s]:源表共 %d 行,过滤后 %d 行(保留 %s / 排除 %s,并排除「%s」,姓名剔除含 %s)",
|
||||
category_name, len(data), len(filtered),
|
||||
include_dept or "全部", exclude_dept or "无", EXCLUDE_REGION,
|
||||
" / ".join(EXCLUDE_NAME_KEYWORDS))
|
||||
if len(filtered) == 0:
|
||||
logger.warning("类别[%s] 筛选后没有数据!", category_name)
|
||||
|
||||
# ---------- 3. 写目标表(先覆盖写入,只清空超出新数据的旧行,避免大范围逐格清空) ----------
|
||||
wb = load_workbook(target_file)
|
||||
if SHEET_BIZ not in wb.sheetnames:
|
||||
raise ValueError(f"目标表缺少 Sheet:{SHEET_BIZ}")
|
||||
ws = wb[SHEET_BIZ]
|
||||
first_data_row = TARGET_HEADER_ROW + 1 # 第5行
|
||||
|
||||
# 找 B 列当前最后非空数据行(用于清空多余旧行)
|
||||
old_last = first_data_row - 1
|
||||
for r in range(first_data_row, ws.max_row + 1):
|
||||
if ws.cell(row=r, column=2).value is not None:
|
||||
old_last = r
|
||||
|
||||
# 写入 B~O(覆盖旧数据,本地化 cell 引用减少开销)
|
||||
rows = filtered.values.tolist()
|
||||
cell = ws.cell
|
||||
for i, row in enumerate(rows, start=first_data_row):
|
||||
for j, val in enumerate(row, start=2):
|
||||
cell(row=i, column=j).value = val
|
||||
|
||||
# 清空超出新数据的旧行
|
||||
new_last = first_data_row + len(rows) - 1
|
||||
if old_last > new_last:
|
||||
for r in range(new_last + 1, old_last + 1):
|
||||
for c in range(2, 2 + DATA_COLUMNS):
|
||||
cell(row=r, column=c).value = None
|
||||
|
||||
wb.save(target_file)
|
||||
logger.info("类别[%s] 已写入目标表 %s 第%d行起,共 %d 行", category_name, target_file, first_data_row, len(rows))
|
||||
return len(rows)
|
||||
|
||||
|
||||
def export_roster_for_employer_insurance(download_dir: str = None, ttl: int = None) -> str:
|
||||
"""按本场景模板「雇主险增减员导出模板」导出花名册(复用 roster_export,操作 HR 系统)。
|
||||
|
||||
输出位置由本场景指定:D:\\资料\\人资\\雇主险\\员工花名册.xlsx(与筛选复制的源表路径一致)。
|
||||
|
||||
Args:
|
||||
download_dir: 浏览器下载临时目录,默认使用 roster_export 的默认目录。
|
||||
ttl: 缓存有效期(秒),None 用 roster_export 默认(15 分钟);传 0 强制重新导出。
|
||||
|
||||
Returns:
|
||||
合并后的花名册文件路径。
|
||||
"""
|
||||
from app.service.hrbp.ehr.roster.roster_export import export_roster
|
||||
output_path = os.path.join(BASE_DIR, "员工花名册.xlsx")
|
||||
logger.info("按本场景模板 [%s] 导出花名册(在职状态:%s),输出:%s",
|
||||
ROSTER_TEMPLATE_NAME, ROSTER_EXPORT_STATUSES, output_path)
|
||||
return export_roster(download_dir=download_dir, template_name=ROSTER_TEMPLATE_NAME,
|
||||
output_path=output_path, statuses=ROSTER_EXPORT_STATUSES, ttl=ttl)
|
||||
|
||||
|
||||
def main(category_name: str = None) -> None:
|
||||
"""步骤1:就绪检查 + 导出(如需)+ 类别筛选复制。
|
||||
|
||||
Args:
|
||||
category_name: 类别名(如「湖畔酒店」/「湖畔」),None 表示处理全部类别。
|
||||
|
||||
说明:openpyxl 写入后公式列(P~W 工种类别/投保方案/方案处理)的缓存结果会丢失,
|
||||
需手动打开各目标文件刷新公式计算结果并保存,确认复制无误后再运行 schedule 步骤
|
||||
(employer_insurance.py)。
|
||||
"""
|
||||
setup_logging()
|
||||
args = sys.argv[1:]
|
||||
|
||||
# 命令行第一个非 -- 参数可作为类别名(如:python roster_filter.py 湖畔酒店)
|
||||
if not category_name:
|
||||
for a in args:
|
||||
if not a.startswith("--"):
|
||||
category_name = a
|
||||
break
|
||||
categories = [get_category(category_name)] if category_name else CATEGORIES
|
||||
|
||||
# 源表(员工花名册)缺失才自动导出;--export-roster 为显式强制导出(ttl=0 绕过缓存)
|
||||
force = "--export-roster" in args
|
||||
if force or not os.path.exists(EMPLOYEE_FILE):
|
||||
export_roster_for_employer_insurance(ttl=0 if force else None)
|
||||
else:
|
||||
logger.info("源表已存在:%s,跳过导出", EMPLOYEE_FILE)
|
||||
|
||||
# 逐类别筛选复制(目标文件=各文件夹内最新的雇主险变更记录)
|
||||
ok = 0
|
||||
for category in categories:
|
||||
try:
|
||||
target_file = find_latest_target(category["folder"])
|
||||
except FileNotFoundError as e:
|
||||
logger.error("跳过类别[%s]:%s", category["name"], e)
|
||||
continue
|
||||
logger.info("=" * 70)
|
||||
logger.info("处理类别[%s],目标文件:%s", category["name"], target_file)
|
||||
try:
|
||||
n = filter_and_copy_roster(category, target_file=target_file)
|
||||
ok += 1
|
||||
logger.info("类别[%s] 完成,写入 %d 行", category["name"], n)
|
||||
except Exception:
|
||||
logger.exception("类别[%s] 处理失败", category["name"])
|
||||
|
||||
logger.info("=" * 70)
|
||||
logger.info("筛选复制完成(成功 %d/%d 个类别)。请手动打开各目标文件刷新公式计算结果(Ctrl+S 保存),",
|
||||
ok, len(categories))
|
||||
logger.info("确认无误后运行:python employer_insurance.py schedule")
|
||||
logger.info("=" * 70)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,317 +1,317 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.roster.roster_query
|
||||
@FileName: roster_query.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-26
|
||||
@Description: 花名册共享查询模块 —— 根据员工工号查询:
|
||||
1. 店长查询:返回其所在四级部门的店长工号与姓名(岗位含「店长」,多个取第一个);
|
||||
2. 人事查询:返回其所在经营中心(二级部门含「经营中心」)岗位含「人事」的全部名单;
|
||||
特殊分支:二级部门为「石桥铺会馆」时直接返回固定人事名单(梁敏/37001302),不查花名册。
|
||||
两类查询均支持批量(花名册只读一次)。供「告知书制作与下发」等业务流程复用。
|
||||
@Version: 1.2.0
|
||||
|
||||
使用方式(库函数,参数直接传):
|
||||
from app.service.hrbp.ehr.roster.roster_query import (
|
||||
find_store_manager, find_store_manager_batch,
|
||||
find_hr_personnel, find_hr_personnel_batch)
|
||||
- find_store_manager(工号, 花名册路径) -> {"success", "error", "manager_code", "manager_name"}
|
||||
- find_hr_personnel(工号, 花名册路径) -> {"success", "error", "dept", "personnel": [{"工号","姓名"}, ...]}
|
||||
- 批量:find_*_batch(工号列表, 花名册路径) -> {工号: 对应单查结果, ...}
|
||||
"""
|
||||
|
||||
import numbers
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 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)
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动。\n请先执行安装:\n pip install pandas openpyxl\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
from app.utils.logger import get_logger # noqa: E402
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置 ====================
|
||||
# 默认花名册路径(告知书制作与下发)
|
||||
DEFAULT_ROSTER_PATH = r"D:\资料\人资\告知书制作与下发\员工花名册.xlsx"
|
||||
|
||||
# 花名册字段列名(与 aa.md 字段一致)
|
||||
COL_NAME = "姓名" # 姓名
|
||||
COL_CODE = "工号" # 工号
|
||||
COL_DEPT2 = "二级部门" # 二级部门(经营中心)
|
||||
COL_DEPT4 = "四级部门" # 四级部门
|
||||
COL_POSITION = "岗位" # 岗位
|
||||
|
||||
# 岗位关键字(岗位字段包含对应关键字即视为该岗位)
|
||||
MANAGER_KEYWORD = "店长" # 店长岗位关键字
|
||||
HR_KEYWORD = "人事" # 人事岗位关键字
|
||||
DEPT2_MARK = "经营中心" # 二级部门需包含的经营中心标记
|
||||
|
||||
# 人事查询特殊分支:二级部门为「石桥铺会馆」时,不查花名册,直接返回固定人事名单
|
||||
DEPT2_HR_OVERRIDE = {
|
||||
"石桥铺会馆": [{"工号": "37001302", "姓名": "梁敏"}],
|
||||
}
|
||||
|
||||
|
||||
# ==================== 工具函数 ====================
|
||||
def _to_text(value):
|
||||
"""将工号等主键值统一转为文本,避免数字/文本混存导致匹配失败。
|
||||
|
||||
整型 float(如 37036835.0)去掉小数点后转 str,保证与文本工号("37036835")一致。
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
if pd.isna(value):
|
||||
return None
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if isinstance(value, numbers.Integral):
|
||||
return str(int(value))
|
||||
if isinstance(value, numbers.Real):
|
||||
f = float(value)
|
||||
if f.is_integer():
|
||||
return str(int(f))
|
||||
return str(value)
|
||||
|
||||
|
||||
def _read_roster(roster_path):
|
||||
"""读取花名册,自动定位表头行(含「工号」列的行),返回 DataFrame(列名为字段名)。
|
||||
|
||||
Args:
|
||||
roster_path: 花名册文件路径
|
||||
|
||||
Returns:
|
||||
pd.DataFrame
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 文件不存在
|
||||
ValueError: 未找到表头行或缺少必需列(工号/姓名/二级部门/四级部门/岗位)
|
||||
"""
|
||||
roster_path = os.path.abspath(roster_path)
|
||||
if not os.path.exists(roster_path):
|
||||
raise FileNotFoundError(f"花名册文件不存在:{roster_path}")
|
||||
|
||||
# 先不设表头读取前几行,定位含「工号」字段的表头行
|
||||
probe = pd.read_excel(roster_path, header=None, nrows=10)
|
||||
header_row = None
|
||||
for idx in range(len(probe)):
|
||||
if (probe.iloc[idx].astype(str).str.strip() == COL_CODE).any():
|
||||
header_row = idx
|
||||
break
|
||||
if header_row is None:
|
||||
raise ValueError(f"花名册未找到表头行(缺少「{COL_CODE}」字段):{roster_path}")
|
||||
|
||||
df = pd.read_excel(roster_path, header=header_row)
|
||||
required = (COL_CODE, COL_NAME, COL_DEPT2, COL_DEPT4, COL_POSITION)
|
||||
missing = [c for c in required if c not in df.columns]
|
||||
if missing:
|
||||
raise ValueError(f"花名册缺少必需列:{missing}({roster_path})")
|
||||
return df
|
||||
|
||||
|
||||
def _prepare_df(df):
|
||||
"""统一工号列文本格式并过滤空行,返回预处理后的 DataFrame(副本)。"""
|
||||
df = df.copy()
|
||||
df[COL_CODE] = df[COL_CODE].map(_to_text)
|
||||
return df[df[COL_CODE].notna()]
|
||||
|
||||
|
||||
# ==================== 核心查询 ====================
|
||||
def _find_store_manager_in_df(df, code):
|
||||
"""在已读取的花名册 DataFrame 中查询店长(不读文件)。"""
|
||||
# 1. 校验工号是否存在
|
||||
row = df[df[COL_CODE] == code]
|
||||
if row.empty:
|
||||
logger.warning("工号不存在:%s", code)
|
||||
return {"success": False, "error": f"工号不存在:{code}",
|
||||
"manager_code": None, "manager_name": None}
|
||||
|
||||
# 2. 根据工号查四级部门
|
||||
dept4 = _to_text(row.iloc[0][COL_DEPT4])
|
||||
|
||||
# 3. 无四级部门 -> 返回查询失败、空结果
|
||||
if not dept4:
|
||||
logger.warning("员工(工号 %s)无四级部门", code)
|
||||
return {"success": False, "error": f"员工(工号 {code})无四级部门",
|
||||
"manager_code": None, "manager_name": None}
|
||||
|
||||
# 4. 在该四级部门内找岗位包含「店长」的人
|
||||
candidates = df[
|
||||
(df[COL_DEPT4].map(_to_text) == dept4)
|
||||
& (df[COL_POSITION].astype(str).str.contains(MANAGER_KEYWORD, na=False))
|
||||
]
|
||||
if candidates.empty:
|
||||
logger.warning("四级部门「%s」内未找到店长(工号 %s)", dept4, code)
|
||||
return {"success": False, "error": f"四级部门「{dept4}」内未找到店长",
|
||||
"manager_code": None, "manager_name": None}
|
||||
|
||||
# 5. 命中多个时取第一个(按花名册行序)
|
||||
first = candidates.iloc[0]
|
||||
manager_code = _to_text(first[COL_CODE])
|
||||
manager_name = _to_text(first[COL_NAME]) or ""
|
||||
logger.info("工号 %s -> 四级部门「%s」-> 店长 %s(工号 %s)",
|
||||
code, dept4, manager_name, manager_code)
|
||||
return {"success": True, "error": None,
|
||||
"manager_code": manager_code, "manager_name": manager_name}
|
||||
|
||||
|
||||
def _find_hr_personnel_in_df(df, code):
|
||||
"""在已读取的花名册 DataFrame 中查询经营中心人事名单(不读文件)。"""
|
||||
# 1. 校验工号是否存在
|
||||
row = df[df[COL_CODE] == code]
|
||||
if row.empty:
|
||||
logger.warning("工号不存在:%s", code)
|
||||
return {"success": False, "error": f"工号不存在:{code}",
|
||||
"dept": None, "personnel": []}
|
||||
|
||||
# 2. 校验二级部门
|
||||
dept2 = _to_text(row.iloc[0][COL_DEPT2]) or ""
|
||||
|
||||
# 2.1 特殊分支:二级部门为「石桥铺会馆」时直接返回固定人事名单(不查花名册)
|
||||
if dept2 in DEPT2_HR_OVERRIDE:
|
||||
personnel = [dict(p) for p in DEPT2_HR_OVERRIDE[dept2]]
|
||||
logger.info("工号 %s -> 二级部门「%s」-> 固定人事 %d 人", code, dept2, len(personnel))
|
||||
return {"success": True, "error": None, "dept": dept2, "personnel": personnel}
|
||||
|
||||
if DEPT2_MARK not in dept2:
|
||||
logger.warning("员工(工号 %s)二级部门「%s」不包含「%s」", code, dept2, DEPT2_MARK)
|
||||
return {"success": False, "error": f"员工(工号 {code})二级部门不包含「{DEPT2_MARK}」",
|
||||
"dept": dept2 or None, "personnel": []}
|
||||
|
||||
# 3. 查询该经营中心下岗位包含「人事」的所有名单
|
||||
candidates = df[
|
||||
(df[COL_DEPT2].map(_to_text) == dept2)
|
||||
& (df[COL_POSITION].astype(str).str.contains(HR_KEYWORD, na=False))
|
||||
]
|
||||
personnel = [
|
||||
{"工号": _to_text(r[COL_CODE]), "姓名": _to_text(r[COL_NAME]) or ""}
|
||||
for _, r in candidates.iterrows()
|
||||
]
|
||||
logger.info("工号 %s -> 经营中心「%s」-> 人事 %d 人", code, dept2, len(personnel))
|
||||
return {"success": True, "error": None, "dept": dept2, "personnel": personnel}
|
||||
|
||||
|
||||
def _error_result(code, e):
|
||||
"""读取花名册失败时的统一错误结果(店长/人事两种结构)。"""
|
||||
return {
|
||||
"store": {"success": False, "error": str(e),
|
||||
"manager_code": None, "manager_name": None},
|
||||
"hr": {"success": False, "error": str(e), "dept": None, "personnel": []},
|
||||
}
|
||||
|
||||
|
||||
def find_store_manager(code, roster_path=None):
|
||||
"""根据员工工号,返回其所在四级部门的店长工号与姓名(单查)。
|
||||
|
||||
Args:
|
||||
code: 员工工号(str 或 int,如 "37036835" / 37036835)
|
||||
roster_path: 员工花名册路径,默认 DEFAULT_ROSTER_PATH
|
||||
|
||||
Returns:
|
||||
dict:
|
||||
success: bool 是否查询成功
|
||||
error: str|None 失败原因(工号不存在 / 无四级部门 / 部门内无店长 / 读取异常)
|
||||
manager_code: str|None 店长工号
|
||||
manager_name: str|None 店长姓名
|
||||
"""
|
||||
roster_path = roster_path or DEFAULT_ROSTER_PATH
|
||||
code = _to_text(code)
|
||||
if not code:
|
||||
return {"success": False, "error": f"工号为空:{code!r}",
|
||||
"manager_code": None, "manager_name": None}
|
||||
|
||||
try:
|
||||
df = _prepare_df(_read_roster(roster_path))
|
||||
except Exception as e:
|
||||
logger.error("读取花名册失败:%s", e)
|
||||
return _error_result(code, e)["store"]
|
||||
return _find_store_manager_in_df(df, code)
|
||||
|
||||
|
||||
def find_store_manager_batch(codes, roster_path=None):
|
||||
"""批量查询多个工号的店长(花名册只读一次)。
|
||||
|
||||
Args:
|
||||
codes: 工号列表(str/int)
|
||||
roster_path: 员工花名册路径,默认 DEFAULT_ROSTER_PATH
|
||||
|
||||
Returns:
|
||||
dict: {工号: find_store_manager 的返回结果, ...}
|
||||
"""
|
||||
roster_path = roster_path or DEFAULT_ROSTER_PATH
|
||||
try:
|
||||
df = _prepare_df(_read_roster(roster_path))
|
||||
except Exception as e:
|
||||
logger.error("读取花名册失败:%s", e)
|
||||
err = _error_result(None, e)["store"]
|
||||
return {_to_text(c): dict(err) for c in codes}
|
||||
return {_to_text(c): _find_store_manager_in_df(df, _to_text(c)) for c in codes}
|
||||
|
||||
|
||||
def find_hr_personnel(code, roster_path=None):
|
||||
"""根据员工工号,返回其所在经营中心(二级部门)岗位包含「人事」的全部名单(单查)。
|
||||
|
||||
Args:
|
||||
code: 员工工号(str 或 int)
|
||||
roster_path: 员工花名册路径,默认 DEFAULT_ROSTER_PATH
|
||||
|
||||
Returns:
|
||||
dict:
|
||||
success: bool 是否查询成功
|
||||
error: str|None 失败原因(工号不存在 / 二级部门不包含经营中心 / 读取异常)
|
||||
dept: str|None 二级部门(经营中心)
|
||||
personnel: list 人事名单 [{"工号": str, "姓名": str}, ...]
|
||||
"""
|
||||
roster_path = roster_path or DEFAULT_ROSTER_PATH
|
||||
code = _to_text(code)
|
||||
if not code:
|
||||
return {"success": False, "error": f"工号为空:{code!r}",
|
||||
"dept": None, "personnel": []}
|
||||
|
||||
try:
|
||||
df = _prepare_df(_read_roster(roster_path))
|
||||
except Exception as e:
|
||||
logger.error("读取花名册失败:%s", e)
|
||||
return _error_result(code, e)["hr"]
|
||||
return _find_hr_personnel_in_df(df, code)
|
||||
|
||||
|
||||
def find_hr_personnel_batch(codes, roster_path=None):
|
||||
"""批量查询多个工号所在经营中心的人事名单(花名册只读一次)。
|
||||
|
||||
Args:
|
||||
codes: 工号列表(str/int)
|
||||
roster_path: 员工花名册路径,默认 DEFAULT_ROSTER_PATH
|
||||
|
||||
Returns:
|
||||
dict: {工号: find_hr_personnel 的返回结果, ...}
|
||||
"""
|
||||
roster_path = roster_path or DEFAULT_ROSTER_PATH
|
||||
try:
|
||||
df = _prepare_df(_read_roster(roster_path))
|
||||
except Exception as e:
|
||||
logger.error("读取花名册失败:%s", e)
|
||||
err = _error_result(None, e)["hr"]
|
||||
return {_to_text(c): dict(err) for c in codes}
|
||||
return {_to_text(c): _find_hr_personnel_in_df(df, _to_text(c)) for c in codes}
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.roster.roster_query
|
||||
@FileName: roster_query.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-26
|
||||
@Description: 花名册共享查询模块 —— 根据员工工号查询:
|
||||
1. 店长查询:返回其所在四级部门的店长工号与姓名(岗位含「店长」,多个取第一个);
|
||||
2. 人事查询:返回其所在经营中心(二级部门含「经营中心」)岗位含「人事」的全部名单;
|
||||
特殊分支:二级部门为「石桥铺会馆」时直接返回固定人事名单(梁敏/37001302),不查花名册。
|
||||
两类查询均支持批量(花名册只读一次)。供「告知书制作与下发」等业务流程复用。
|
||||
@Version: 1.2.0
|
||||
|
||||
使用方式(库函数,参数直接传):
|
||||
from app.service.hrbp.ehr.roster.roster_query import (
|
||||
find_store_manager, find_store_manager_batch,
|
||||
find_hr_personnel, find_hr_personnel_batch)
|
||||
- find_store_manager(工号, 花名册路径) -> {"success", "error", "manager_code", "manager_name"}
|
||||
- find_hr_personnel(工号, 花名册路径) -> {"success", "error", "dept", "personnel": [{"工号","姓名"}, ...]}
|
||||
- 批量:find_*_batch(工号列表, 花名册路径) -> {工号: 对应单查结果, ...}
|
||||
"""
|
||||
|
||||
import numbers
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 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)
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动。\n请先执行安装:\n pip install pandas openpyxl\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
from app.utils.logger import get_logger # noqa: E402
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置 ====================
|
||||
# 默认花名册路径(告知书制作与下发)
|
||||
DEFAULT_ROSTER_PATH = r"D:\资料\人资\告知书制作与下发\员工花名册.xlsx"
|
||||
|
||||
# 花名册字段列名(与 aa.md 字段一致)
|
||||
COL_NAME = "姓名" # 姓名
|
||||
COL_CODE = "工号" # 工号
|
||||
COL_DEPT2 = "二级部门" # 二级部门(经营中心)
|
||||
COL_DEPT4 = "四级部门" # 四级部门
|
||||
COL_POSITION = "岗位" # 岗位
|
||||
|
||||
# 岗位关键字(岗位字段包含对应关键字即视为该岗位)
|
||||
MANAGER_KEYWORD = "店长" # 店长岗位关键字
|
||||
HR_KEYWORD = "人事" # 人事岗位关键字
|
||||
DEPT2_MARK = "经营中心" # 二级部门需包含的经营中心标记
|
||||
|
||||
# 人事查询特殊分支:二级部门为「石桥铺会馆」时,不查花名册,直接返回固定人事名单
|
||||
DEPT2_HR_OVERRIDE = {
|
||||
"石桥铺会馆": [{"工号": "37001302", "姓名": "梁敏"}],
|
||||
}
|
||||
|
||||
|
||||
# ==================== 工具函数 ====================
|
||||
def _to_text(value):
|
||||
"""将工号等主键值统一转为文本,避免数字/文本混存导致匹配失败。
|
||||
|
||||
整型 float(如 37036835.0)去掉小数点后转 str,保证与文本工号("37036835")一致。
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
if pd.isna(value):
|
||||
return None
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if isinstance(value, numbers.Integral):
|
||||
return str(int(value))
|
||||
if isinstance(value, numbers.Real):
|
||||
f = float(value)
|
||||
if f.is_integer():
|
||||
return str(int(f))
|
||||
return str(value)
|
||||
|
||||
|
||||
def _read_roster(roster_path):
|
||||
"""读取花名册,自动定位表头行(含「工号」列的行),返回 DataFrame(列名为字段名)。
|
||||
|
||||
Args:
|
||||
roster_path: 花名册文件路径
|
||||
|
||||
Returns:
|
||||
pd.DataFrame
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 文件不存在
|
||||
ValueError: 未找到表头行或缺少必需列(工号/姓名/二级部门/四级部门/岗位)
|
||||
"""
|
||||
roster_path = os.path.abspath(roster_path)
|
||||
if not os.path.exists(roster_path):
|
||||
raise FileNotFoundError(f"花名册文件不存在:{roster_path}")
|
||||
|
||||
# 先不设表头读取前几行,定位含「工号」字段的表头行
|
||||
probe = pd.read_excel(roster_path, header=None, nrows=10)
|
||||
header_row = None
|
||||
for idx in range(len(probe)):
|
||||
if (probe.iloc[idx].astype(str).str.strip() == COL_CODE).any():
|
||||
header_row = idx
|
||||
break
|
||||
if header_row is None:
|
||||
raise ValueError(f"花名册未找到表头行(缺少「{COL_CODE}」字段):{roster_path}")
|
||||
|
||||
df = pd.read_excel(roster_path, header=header_row)
|
||||
required = (COL_CODE, COL_NAME, COL_DEPT2, COL_DEPT4, COL_POSITION)
|
||||
missing = [c for c in required if c not in df.columns]
|
||||
if missing:
|
||||
raise ValueError(f"花名册缺少必需列:{missing}({roster_path})")
|
||||
return df
|
||||
|
||||
|
||||
def _prepare_df(df):
|
||||
"""统一工号列文本格式并过滤空行,返回预处理后的 DataFrame(副本)。"""
|
||||
df = df.copy()
|
||||
df[COL_CODE] = df[COL_CODE].map(_to_text)
|
||||
return df[df[COL_CODE].notna()]
|
||||
|
||||
|
||||
# ==================== 核心查询 ====================
|
||||
def _find_store_manager_in_df(df, code):
|
||||
"""在已读取的花名册 DataFrame 中查询店长(不读文件)。"""
|
||||
# 1. 校验工号是否存在
|
||||
row = df[df[COL_CODE] == code]
|
||||
if row.empty:
|
||||
logger.warning("工号不存在:%s", code)
|
||||
return {"success": False, "error": f"工号不存在:{code}",
|
||||
"manager_code": None, "manager_name": None}
|
||||
|
||||
# 2. 根据工号查四级部门
|
||||
dept4 = _to_text(row.iloc[0][COL_DEPT4])
|
||||
|
||||
# 3. 无四级部门 -> 返回查询失败、空结果
|
||||
if not dept4:
|
||||
logger.warning("员工(工号 %s)无四级部门", code)
|
||||
return {"success": False, "error": f"员工(工号 {code})无四级部门",
|
||||
"manager_code": None, "manager_name": None}
|
||||
|
||||
# 4. 在该四级部门内找岗位包含「店长」的人
|
||||
candidates = df[
|
||||
(df[COL_DEPT4].map(_to_text) == dept4)
|
||||
& (df[COL_POSITION].astype(str).str.contains(MANAGER_KEYWORD, na=False))
|
||||
]
|
||||
if candidates.empty:
|
||||
logger.warning("四级部门「%s」内未找到店长(工号 %s)", dept4, code)
|
||||
return {"success": False, "error": f"四级部门「{dept4}」内未找到店长",
|
||||
"manager_code": None, "manager_name": None}
|
||||
|
||||
# 5. 命中多个时取第一个(按花名册行序)
|
||||
first = candidates.iloc[0]
|
||||
manager_code = _to_text(first[COL_CODE])
|
||||
manager_name = _to_text(first[COL_NAME]) or ""
|
||||
logger.info("工号 %s -> 四级部门「%s」-> 店长 %s(工号 %s)",
|
||||
code, dept4, manager_name, manager_code)
|
||||
return {"success": True, "error": None,
|
||||
"manager_code": manager_code, "manager_name": manager_name}
|
||||
|
||||
|
||||
def _find_hr_personnel_in_df(df, code):
|
||||
"""在已读取的花名册 DataFrame 中查询经营中心人事名单(不读文件)。"""
|
||||
# 1. 校验工号是否存在
|
||||
row = df[df[COL_CODE] == code]
|
||||
if row.empty:
|
||||
logger.warning("工号不存在:%s", code)
|
||||
return {"success": False, "error": f"工号不存在:{code}",
|
||||
"dept": None, "personnel": []}
|
||||
|
||||
# 2. 校验二级部门
|
||||
dept2 = _to_text(row.iloc[0][COL_DEPT2]) or ""
|
||||
|
||||
# 2.1 特殊分支:二级部门为「石桥铺会馆」时直接返回固定人事名单(不查花名册)
|
||||
if dept2 in DEPT2_HR_OVERRIDE:
|
||||
personnel = [dict(p) for p in DEPT2_HR_OVERRIDE[dept2]]
|
||||
logger.info("工号 %s -> 二级部门「%s」-> 固定人事 %d 人", code, dept2, len(personnel))
|
||||
return {"success": True, "error": None, "dept": dept2, "personnel": personnel}
|
||||
|
||||
if DEPT2_MARK not in dept2:
|
||||
logger.warning("员工(工号 %s)二级部门「%s」不包含「%s」", code, dept2, DEPT2_MARK)
|
||||
return {"success": False, "error": f"员工(工号 {code})二级部门不包含「{DEPT2_MARK}」",
|
||||
"dept": dept2 or None, "personnel": []}
|
||||
|
||||
# 3. 查询该经营中心下岗位包含「人事」的所有名单
|
||||
candidates = df[
|
||||
(df[COL_DEPT2].map(_to_text) == dept2)
|
||||
& (df[COL_POSITION].astype(str).str.contains(HR_KEYWORD, na=False))
|
||||
]
|
||||
personnel = [
|
||||
{"工号": _to_text(r[COL_CODE]), "姓名": _to_text(r[COL_NAME]) or ""}
|
||||
for _, r in candidates.iterrows()
|
||||
]
|
||||
logger.info("工号 %s -> 经营中心「%s」-> 人事 %d 人", code, dept2, len(personnel))
|
||||
return {"success": True, "error": None, "dept": dept2, "personnel": personnel}
|
||||
|
||||
|
||||
def _error_result(code, e):
|
||||
"""读取花名册失败时的统一错误结果(店长/人事两种结构)。"""
|
||||
return {
|
||||
"store": {"success": False, "error": str(e),
|
||||
"manager_code": None, "manager_name": None},
|
||||
"hr": {"success": False, "error": str(e), "dept": None, "personnel": []},
|
||||
}
|
||||
|
||||
|
||||
def find_store_manager(code, roster_path=None):
|
||||
"""根据员工工号,返回其所在四级部门的店长工号与姓名(单查)。
|
||||
|
||||
Args:
|
||||
code: 员工工号(str 或 int,如 "37036835" / 37036835)
|
||||
roster_path: 员工花名册路径,默认 DEFAULT_ROSTER_PATH
|
||||
|
||||
Returns:
|
||||
dict:
|
||||
success: bool 是否查询成功
|
||||
error: str|None 失败原因(工号不存在 / 无四级部门 / 部门内无店长 / 读取异常)
|
||||
manager_code: str|None 店长工号
|
||||
manager_name: str|None 店长姓名
|
||||
"""
|
||||
roster_path = roster_path or DEFAULT_ROSTER_PATH
|
||||
code = _to_text(code)
|
||||
if not code:
|
||||
return {"success": False, "error": f"工号为空:{code!r}",
|
||||
"manager_code": None, "manager_name": None}
|
||||
|
||||
try:
|
||||
df = _prepare_df(_read_roster(roster_path))
|
||||
except Exception as e:
|
||||
logger.error("读取花名册失败:%s", e)
|
||||
return _error_result(code, e)["store"]
|
||||
return _find_store_manager_in_df(df, code)
|
||||
|
||||
|
||||
def find_store_manager_batch(codes, roster_path=None):
|
||||
"""批量查询多个工号的店长(花名册只读一次)。
|
||||
|
||||
Args:
|
||||
codes: 工号列表(str/int)
|
||||
roster_path: 员工花名册路径,默认 DEFAULT_ROSTER_PATH
|
||||
|
||||
Returns:
|
||||
dict: {工号: find_store_manager 的返回结果, ...}
|
||||
"""
|
||||
roster_path = roster_path or DEFAULT_ROSTER_PATH
|
||||
try:
|
||||
df = _prepare_df(_read_roster(roster_path))
|
||||
except Exception as e:
|
||||
logger.error("读取花名册失败:%s", e)
|
||||
err = _error_result(None, e)["store"]
|
||||
return {_to_text(c): dict(err) for c in codes}
|
||||
return {_to_text(c): _find_store_manager_in_df(df, _to_text(c)) for c in codes}
|
||||
|
||||
|
||||
def find_hr_personnel(code, roster_path=None):
|
||||
"""根据员工工号,返回其所在经营中心(二级部门)岗位包含「人事」的全部名单(单查)。
|
||||
|
||||
Args:
|
||||
code: 员工工号(str 或 int)
|
||||
roster_path: 员工花名册路径,默认 DEFAULT_ROSTER_PATH
|
||||
|
||||
Returns:
|
||||
dict:
|
||||
success: bool 是否查询成功
|
||||
error: str|None 失败原因(工号不存在 / 二级部门不包含经营中心 / 读取异常)
|
||||
dept: str|None 二级部门(经营中心)
|
||||
personnel: list 人事名单 [{"工号": str, "姓名": str}, ...]
|
||||
"""
|
||||
roster_path = roster_path or DEFAULT_ROSTER_PATH
|
||||
code = _to_text(code)
|
||||
if not code:
|
||||
return {"success": False, "error": f"工号为空:{code!r}",
|
||||
"dept": None, "personnel": []}
|
||||
|
||||
try:
|
||||
df = _prepare_df(_read_roster(roster_path))
|
||||
except Exception as e:
|
||||
logger.error("读取花名册失败:%s", e)
|
||||
return _error_result(code, e)["hr"]
|
||||
return _find_hr_personnel_in_df(df, code)
|
||||
|
||||
|
||||
def find_hr_personnel_batch(codes, roster_path=None):
|
||||
"""批量查询多个工号所在经营中心的人事名单(花名册只读一次)。
|
||||
|
||||
Args:
|
||||
codes: 工号列表(str/int)
|
||||
roster_path: 员工花名册路径,默认 DEFAULT_ROSTER_PATH
|
||||
|
||||
Returns:
|
||||
dict: {工号: find_hr_personnel 的返回结果, ...}
|
||||
"""
|
||||
roster_path = roster_path or DEFAULT_ROSTER_PATH
|
||||
try:
|
||||
df = _prepare_df(_read_roster(roster_path))
|
||||
except Exception as e:
|
||||
logger.error("读取花名册失败:%s", e)
|
||||
err = _error_result(None, e)["hr"]
|
||||
return {_to_text(c): dict(err) for c in codes}
|
||||
return {_to_text(c): _find_hr_personnel_in_df(df, _to_text(c)) for c in codes}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.shift_abnormal
|
||||
@FileName: __init__.py
|
||||
@Description: 排班异常识别模块包。
|
||||
包含预入职台账导出等子模块,供排班异常识别业务场景复用。
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.shift_abnormal
|
||||
@FileName: __init__.py
|
||||
@Description: 排班异常识别模块包。
|
||||
包含预入职台账导出等子模块,供排班异常识别业务场景复用。
|
||||
"""
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,411 +1,411 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.shift_abnormal
|
||||
@FileName: shift_abnormal_check.py
|
||||
@Author: 小布丁
|
||||
@Description: 排班异常识别(第三步):读取第二步导出的「调动台账 / 预入职台账」(表头在第 2 行),
|
||||
结合 HR 排班接口判断每人的排班是否异常,导出异常名单 Excel。
|
||||
判断口径:
|
||||
- 调动台账:按「调动时间」筛选近 9 天,对每人查询当日完整排班名
|
||||
({日期}_team_name,形如「印象-{上级部门}-技师岗」)。当「现职位序列」含「职能」
|
||||
时按「现单位」比对,其余按「现四级部门」比对;用 rf_s_kq_work_date_query
|
||||
接口按比对部门查出该部门全部排班集合,当日排班属于该集合才视为正常
|
||||
(接口查不到集合时兜底原「完整排班名包含部门名」判断),否则为排班异常
|
||||
(无排班 / 排班未更新);
|
||||
- 预入职台账:按「操作时间」筛选近 9 天,对每人查询「预入职日期」当日完整排班名,
|
||||
当日有完整排班信息即为正常,无排班信息则为排班异常。有排班信息即可,不校验部门。
|
||||
不纳入异常:现职位序列命中 经营系管理序列 / 职能系专业序列 / 门店技师序列 的剔除(调动+预入职均生效)。
|
||||
底层能力复用:hr_session(会话管理)、hr_api.shift(排班查询)、roster 导出。
|
||||
@Version: 1.0.0
|
||||
|
||||
说明:
|
||||
1. 输入为第二步导出的《调动台账.xlsx》《预入职台账.xlsx》,两表表头均在第 2 行(pandas header=1)。
|
||||
2. 完整排班名取 {日期}_team_name(含上级部门),而非 {日期}_bc_name(仅班次名,如「技师中班C」)。
|
||||
3. 首次运行会自动完成 HR 登录并缓存 cookies,登录态过期自动重登。
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from datetime import date, datetime, timedelta
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in __import__("pathlib").Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(__import__("pathlib").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.common.hr_session import build_hr_session # noqa: E402
|
||||
from app.service.hrbp.ehr.common.hr_api import fetch_cur_user_info # noqa: E402
|
||||
from app.service.hrbp.ehr.common.hr_api.shift import fetch_all_shift, fetch_all_work_date # noqa: E402
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
pd = None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ===================== 配置区(可自行修改) =====================
|
||||
# 默认输出目录(与第二步导出目录一致)
|
||||
SAVE_DIR = r"D:\资料\人资\排班异常识别"
|
||||
|
||||
# 第二步导出的台账文件名(表头在第 2 行)
|
||||
TRANSFER_FILE = os.path.join(SAVE_DIR, "调动台账.xlsx")
|
||||
PREENTRY_FILE = os.path.join(SAVE_DIR, "预入职台账.xlsx")
|
||||
|
||||
# 筛选窗口:近 N 天(含当天)
|
||||
DAYS = 9
|
||||
|
||||
# 每个员工是否重新校验会话(按人数控制频率,避免登录态过期后逐人触发重登)
|
||||
SESSION_REVALIDATE_EVERY = 30
|
||||
|
||||
# 名单输出列(调动台账 + 预入职台账合并为一张表,类别区分 调动/入职)
|
||||
COLUMNS: List[str] = [
|
||||
"序号", "姓名", "工号", "类别", "原单位", "原上级部门", "现单位", "现职位序列",
|
||||
"现上级部门", "现四级部门", "调动/入职时间", "操作时间", "当日排班", "异常原因",
|
||||
]
|
||||
|
||||
# 现职位序列命中以下序列的不纳入异常(不统计、不导出)
|
||||
EXCLUDE_SEQ_KEYWORDS = ("经营系管理序列", "职能系专业序列", "门店技师序列")
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 1. 通用工具
|
||||
# ----------------------------------------------
|
||||
def _clean(v) -> str:
|
||||
"""转字符串并去掉常见杂质:None、浮点 .0 尾缀、pandas 空占位(nan/native等)。"""
|
||||
if v is None:
|
||||
return ""
|
||||
s = str(v).strip()
|
||||
if s.lower() in ("nan", "none", "nat"):
|
||||
return ""
|
||||
if s.endswith(".0"):
|
||||
s = s[:-2]
|
||||
return s
|
||||
|
||||
|
||||
def _date_part(v) -> str:
|
||||
"""取日期字符串前 10 位(兼容 "YYYY-MM-DD HH:MM:SS")。"""
|
||||
return _clean(v)[:10]
|
||||
|
||||
|
||||
def _seq_excluded(seq: str) -> bool:
|
||||
"""现职位序列命中剔除序列(经营系管理序列/职能系专业序列/门店技师序列)返回 True。"""
|
||||
seq = _clean(seq)
|
||||
return any(kw in seq for kw in EXCLUDE_SEQ_KEYWORDS)
|
||||
|
||||
|
||||
def _shift_name(s: str) -> str:
|
||||
"""归一化排班名:兼容 {日期}_team_name 可能带 "YYYY-MM-DD_" 前缀,去掉前缀便于与接口 work_date_name 比对。"""
|
||||
s = _clean(s)
|
||||
if len(s) > 11 and s[4] == "-" and s[7] == "-" and s[10] == "_":
|
||||
return s[11:]
|
||||
return s
|
||||
|
||||
|
||||
def _parse_date(v) -> Optional[date]:
|
||||
"""解析日期字符串为 date,失败返回 None。"""
|
||||
s = _date_part(v)
|
||||
if not s:
|
||||
return None
|
||||
try:
|
||||
return datetime.strptime(s, "%Y-%m-%d").date()
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _recent_window(end: date = None, days: int = DAYS) -> Tuple[date, date]:
|
||||
"""返回近 N 天的 (开始日期, 结束日期),含当天。"""
|
||||
end = end or date.today()
|
||||
begin = end - timedelta(days=days - 1)
|
||||
return begin, end
|
||||
|
||||
|
||||
def _load_ledger(path: str) -> "pd.DataFrame":
|
||||
"""读取第二步导出的台账,表头在第 2 行(header=1)。"""
|
||||
if not os.path.exists(path):
|
||||
raise RuntimeError(
|
||||
f"未找到台账文件:{path}\n请先运行第二步导出(调动台账 / 预入职台账)后再执行本模块。"
|
||||
)
|
||||
df = pd.read_excel(path, header=1, dtype=str)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
logger.info("已读取台账:%s,共 %d 行", path, len(df))
|
||||
return df
|
||||
|
||||
|
||||
def _validate_session(session):
|
||||
"""校验 cookies 有效性,返回 (session, user_id);过期则重新登录并重建会话。"""
|
||||
session, user_id = _ensure_user_id(session, None)
|
||||
return session, user_id
|
||||
|
||||
|
||||
def _ensure_user_id(session, user_id: Optional[str]) -> Tuple[object, str]:
|
||||
"""获取有效 user_id 与会话。传入 None 时实时取;已有则直接复用。"""
|
||||
if user_id:
|
||||
return session, user_id
|
||||
info = fetch_cur_user_info(session)
|
||||
new_uid = _clean(info.get("userId"))
|
||||
if not new_uid:
|
||||
raise RuntimeError(f"员工基础信息接口未返回 userId:{info}")
|
||||
return session, new_uid
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 2. 按工号查询某日完整排班名({日期}_team_name)
|
||||
# ----------------------------------------------
|
||||
class _ShiftFetcher:
|
||||
"""带缓存的排班查询器:按 (工号, 日期) 缓存当日完整排班名,复用同一会话,定期校验登录态。"""
|
||||
|
||||
def __init__(self, session, user_id: str):
|
||||
self.session = session
|
||||
self.user_id = user_id
|
||||
self.cache: Dict[Tuple[str, date], str] = {}
|
||||
self.calls = 0
|
||||
|
||||
def fetch(self, code: str, day: date) -> str:
|
||||
"""返回某工号某日的完整排班名;无排班则返回空串。"""
|
||||
key = (code, day)
|
||||
if key not in self.cache:
|
||||
# 定期重新校验登录态,避免绑定过期会话
|
||||
self.calls += 1
|
||||
if self.calls % SESSION_REVALIDATE_EVERY == 1:
|
||||
self.session, uid = _ensure_user_id(self.session, None)
|
||||
self.user_id = uid
|
||||
val = self._query(code, day)
|
||||
self.cache[key] = val
|
||||
time.sleep(0.2)
|
||||
return self.cache[key]
|
||||
|
||||
def _query(self, code: str, day: date) -> str:
|
||||
day_str = day.strftime("%Y-%m-%d")
|
||||
rows = fetch_all_shift(self.session, self.user_id, code, day_str, day_str)
|
||||
for rec in rows:
|
||||
return _clean(rec.get(f"{day_str}_team_name"))
|
||||
return ""
|
||||
|
||||
|
||||
class _DeptShiftFetcher:
|
||||
"""按部门名缓存该部门的排班名集合(work_date_name),复用同一会话,定期校验登录态。
|
||||
|
||||
同一部门可能配置多个排班(技师岗/服务岗/管理岗…),通过 rf_s_kq_work_date_query
|
||||
接口按部门查出全部排班名,用于判断员工当日排班是否属于该部门。
|
||||
"""
|
||||
|
||||
def __init__(self, session):
|
||||
self.session = session
|
||||
self.cache: Dict[str, set] = {}
|
||||
self.calls = 0
|
||||
|
||||
def fetch(self, dept_name: str) -> set:
|
||||
"""返回某部门的排班名集合;部门名为空或查不到返回空集合。"""
|
||||
dept_name = _clean(dept_name)
|
||||
if not dept_name:
|
||||
return set()
|
||||
if dept_name not in self.cache:
|
||||
# 定期重新校验登录态,避免绑定过期会话
|
||||
self.calls += 1
|
||||
if self.calls % SESSION_REVALIDATE_EVERY == 1:
|
||||
self.session, _ = _ensure_user_id(self.session, None)
|
||||
self.cache[dept_name] = {_shift_name(n) for n in fetch_all_work_date(self.session, dept_name)}
|
||||
time.sleep(0.2)
|
||||
return self.cache[dept_name]
|
||||
|
||||
|
||||
def _shift_belongs(dept_fetcher: "_DeptShiftFetcher", dept_name: str, shift: str) -> bool:
|
||||
"""判断某排班是否属于某部门。
|
||||
|
||||
优先用新接口(rf_s_kq_work_date_query)按部门查出排班集合做成员判断;
|
||||
接口查不到集合(如「现单位」无直属排班)时兜底原「完整排班名包含部门名」判断。
|
||||
"""
|
||||
dept_name = _clean(dept_name)
|
||||
shift_norm = _shift_name(shift)
|
||||
if not dept_name or not shift_norm:
|
||||
return False
|
||||
dept_shifts = dept_fetcher.fetch(dept_name)
|
||||
if dept_shifts:
|
||||
return shift_norm in dept_shifts
|
||||
return dept_name in shift
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 3. 调动台账判定
|
||||
# ----------------------------------------------
|
||||
def _check_transfer_row(fetcher: "_ShiftFetcher", dept_fetcher: "_DeptShiftFetcher", r, begin: date, end: date):
|
||||
"""对单行调动记录判定,返回名单行 dict;属正常则返回 None。"""
|
||||
code = _clean(r.get("工号"))
|
||||
day = _parse_date(r.get("调动时间"))
|
||||
if not code or not day:
|
||||
return None
|
||||
if not (begin <= day <= end):
|
||||
return None
|
||||
|
||||
# 判断字段:现职位序列含「职能」按现单位判断,否则按现四级部门判断
|
||||
seq = _clean(r.get("现职位序列"))
|
||||
if _seq_excluded(seq):
|
||||
return None
|
||||
if "职能" in seq:
|
||||
target_field, target_name = "现单位", _clean(r.get("现单位"))
|
||||
else:
|
||||
target_field, target_name = "现四级部门", _clean(r.get("现四级部门"))
|
||||
|
||||
shift = fetcher.fetch(code, day) # 当日完整排班名(含上级部门),无排班为空串
|
||||
|
||||
if not shift:
|
||||
reason, present = "调动时间无排班", ""
|
||||
elif target_name and not _shift_belongs(dept_fetcher, target_name, shift):
|
||||
reason, present = f"排班未更新为{target_field}({target_name})", shift
|
||||
else:
|
||||
return None # 当日有排班且排班属于所需部门 → 正常
|
||||
|
||||
return {
|
||||
"序号": 0,
|
||||
"姓名": _clean(r.get("姓名")),
|
||||
"工号": code,
|
||||
"类别": "调动",
|
||||
"原单位": _clean(r.get("原单位")),
|
||||
"原上级部门": _clean(r.get("原上级部门")),
|
||||
"现单位": _clean(r.get("现单位")),
|
||||
"现职位序列": seq,
|
||||
"现上级部门": _clean(r.get("现上级部门")),
|
||||
"现四级部门": _clean(r.get("现四级部门")),
|
||||
"调动/入职时间": day.strftime("%Y-%m-%d"),
|
||||
"操作时间": _date_part(r.get("操作时间")),
|
||||
"当日排班": present,
|
||||
"异常原因": reason,
|
||||
}
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 4. 预入职台账判定
|
||||
# ----------------------------------------------
|
||||
def _check_preentry_row(fetcher: "_ShiftFetcher", dept_fetcher: "_DeptShiftFetcher", r, begin: date, end: date):
|
||||
"""对单行预入职记录判定,返回名单行 dict;有排班信息则返回 None。"""
|
||||
code = _clean(r.get("工号"))
|
||||
op_day = _parse_date(r.get("操作时间")) # 筛选字段:操作时间
|
||||
if not code or not op_day:
|
||||
return None
|
||||
if not (begin <= op_day <= end):
|
||||
return None
|
||||
if _seq_excluded(r.get("职位序列")):
|
||||
return None
|
||||
|
||||
# 排班检查日期:预入职日期(筛选按操作时间,查询排班按预入职日期)
|
||||
pj_day = _parse_date(r.get("预入职日期"))
|
||||
if not pj_day:
|
||||
return None
|
||||
|
||||
shift = fetcher.fetch(code, pj_day) # 当日完整排班名,无则空串
|
||||
if shift:
|
||||
return None # 有排班信息即可 → 正常
|
||||
|
||||
return {
|
||||
"序号": 0,
|
||||
"姓名": _clean(r.get("姓名")),
|
||||
"工号": code,
|
||||
"类别": "入职",
|
||||
"原单位": "",
|
||||
"原上级部门": "",
|
||||
"现单位": _clean(r.get("入职单位")),
|
||||
"现职位序列": _clean(r.get("职位序列")),
|
||||
"现上级部门": "",
|
||||
"现四级部门": "",
|
||||
"调动/入职时间": pj_day.strftime("%Y-%m-%d"),
|
||||
"操作时间": op_day.strftime("%Y-%m-%d"),
|
||||
"当日排班": "",
|
||||
"异常原因": "预入职日期无排班",
|
||||
}
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 5. 主流程
|
||||
# ----------------------------------------------
|
||||
def _collect_rows(ledger_path: str, check_row, fetcher: "_ShiftFetcher",
|
||||
dept_fetcher: "_DeptShiftFetcher", end: date) -> List[dict]:
|
||||
"""通用判定流程:读台账 → 逐行判定,返回异常行列表(未写文件)。"""
|
||||
df = _load_ledger(ledger_path)
|
||||
begin, end_date = _recent_window(end)
|
||||
logger.info("筛选范围:%s ~ %s(近 %d 天)", begin, end_date, DAYS)
|
||||
|
||||
rows: List[dict] = []
|
||||
for _, r in df.iterrows():
|
||||
row = check_row(fetcher, dept_fetcher, r, begin, end_date)
|
||||
if row:
|
||||
rows.append(row)
|
||||
logger.info("台账 %s 排班异常人数:%d", os.path.basename(ledger_path), len(rows))
|
||||
return rows
|
||||
|
||||
|
||||
def run_shift_abnormal_check(
|
||||
transfer_path: str = None,
|
||||
preentry_path: str = None,
|
||||
days: int = DAYS,
|
||||
) -> str:
|
||||
"""执行排班异常识别(调动台账 + 预入职台账),合并导出单张 Excel,返回文件路径。
|
||||
|
||||
Args:
|
||||
transfer_path: 调动台账 xlsx 路径,默认 TRANSFER_FILE
|
||||
preentry_path: 预入职台账 xlsx 路径,默认 PREENTRY_FILE
|
||||
days: 筛选近 N 天,默认 9
|
||||
"""
|
||||
global DAYS
|
||||
DAYS = days
|
||||
transfer_path = transfer_path or TRANSFER_FILE
|
||||
preentry_path = preentry_path or PREENTRY_FILE
|
||||
end = date.today()
|
||||
|
||||
session = build_hr_session()
|
||||
session, user_id = _validate_session(session)
|
||||
fetcher = _ShiftFetcher(session, user_id)
|
||||
dept_fetcher = _DeptShiftFetcher(session)
|
||||
|
||||
rows: List[dict] = []
|
||||
if os.path.exists(transfer_path):
|
||||
rows.extend(_collect_rows(transfer_path, _check_transfer_row, fetcher, dept_fetcher, end))
|
||||
else:
|
||||
logger.warning("跳过调动台账:文件不存在 %s", transfer_path)
|
||||
|
||||
if os.path.exists(preentry_path):
|
||||
rows.extend(_collect_rows(preentry_path, _check_preentry_row, fetcher, dept_fetcher, end))
|
||||
else:
|
||||
logger.warning("跳过预入职台账:文件不存在 %s", preentry_path)
|
||||
|
||||
if not rows:
|
||||
raise RuntimeError("未识别到排班异常,或台账文件均不存在(请先完成第二步导出)。")
|
||||
|
||||
# 合并排序并补序号
|
||||
rows.sort(key=lambda x: (x.get("类别", ""), x.get("姓名", ""), x.get("工号", "")))
|
||||
for idx, item in enumerate(rows, 1):
|
||||
item["序号"] = idx
|
||||
|
||||
os.makedirs(SAVE_DIR, exist_ok=True)
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
save_path = os.path.join(SAVE_DIR, f"排班异常名单_{ts}.xlsx")
|
||||
pd.DataFrame(rows, columns=COLUMNS).to_excel(save_path, index=False)
|
||||
logger.info("排班异常合并名单(共 %d 人)已保存:%s", len(rows), save_path)
|
||||
return save_path
|
||||
|
||||
|
||||
def main() -> None:
|
||||
setup_logging()
|
||||
try:
|
||||
path = run_shift_abnormal_check()
|
||||
logger.info("=" * 60)
|
||||
logger.info("【排班异常识别完成】")
|
||||
logger.info(" 导出名单:%s", path)
|
||||
logger.info("=" * 60)
|
||||
except Exception as e:
|
||||
logger.error("排班异常识别失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.shift_abnormal
|
||||
@FileName: shift_abnormal_check.py
|
||||
@Author: 小布丁
|
||||
@Description: 排班异常识别(第三步):读取第二步导出的「调动台账 / 预入职台账」(表头在第 2 行),
|
||||
结合 HR 排班接口判断每人的排班是否异常,导出异常名单 Excel。
|
||||
判断口径:
|
||||
- 调动台账:按「调动时间」筛选近 9 天,对每人查询当日完整排班名
|
||||
({日期}_team_name,形如「印象-{上级部门}-技师岗」)。当「现职位序列」含「职能」
|
||||
时按「现单位」比对,其余按「现四级部门」比对;用 rf_s_kq_work_date_query
|
||||
接口按比对部门查出该部门全部排班集合,当日排班属于该集合才视为正常
|
||||
(接口查不到集合时兜底原「完整排班名包含部门名」判断),否则为排班异常
|
||||
(无排班 / 排班未更新);
|
||||
- 预入职台账:按「操作时间」筛选近 9 天,对每人查询「预入职日期」当日完整排班名,
|
||||
当日有完整排班信息即为正常,无排班信息则为排班异常。有排班信息即可,不校验部门。
|
||||
不纳入异常:现职位序列命中 经营系管理序列 / 职能系专业序列 / 门店技师序列 的剔除(调动+预入职均生效)。
|
||||
底层能力复用:hr_session(会话管理)、hr_api.shift(排班查询)、roster 导出。
|
||||
@Version: 1.0.0
|
||||
|
||||
说明:
|
||||
1. 输入为第二步导出的《调动台账.xlsx》《预入职台账.xlsx》,两表表头均在第 2 行(pandas header=1)。
|
||||
2. 完整排班名取 {日期}_team_name(含上级部门),而非 {日期}_bc_name(仅班次名,如「技师中班C」)。
|
||||
3. 首次运行会自动完成 HR 登录并缓存 cookies,登录态过期自动重登。
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from datetime import date, datetime, timedelta
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in __import__("pathlib").Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(__import__("pathlib").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.common.hr_session import build_hr_session # noqa: E402
|
||||
from app.service.hrbp.ehr.common.hr_api import fetch_cur_user_info # noqa: E402
|
||||
from app.service.hrbp.ehr.common.hr_api.shift import fetch_all_shift, fetch_all_work_date # noqa: E402
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
pd = None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ===================== 配置区(可自行修改) =====================
|
||||
# 默认输出目录(与第二步导出目录一致)
|
||||
SAVE_DIR = r"D:\资料\人资\排班异常识别"
|
||||
|
||||
# 第二步导出的台账文件名(表头在第 2 行)
|
||||
TRANSFER_FILE = os.path.join(SAVE_DIR, "调动台账.xlsx")
|
||||
PREENTRY_FILE = os.path.join(SAVE_DIR, "预入职台账.xlsx")
|
||||
|
||||
# 筛选窗口:近 N 天(含当天)
|
||||
DAYS = 9
|
||||
|
||||
# 每个员工是否重新校验会话(按人数控制频率,避免登录态过期后逐人触发重登)
|
||||
SESSION_REVALIDATE_EVERY = 30
|
||||
|
||||
# 名单输出列(调动台账 + 预入职台账合并为一张表,类别区分 调动/入职)
|
||||
COLUMNS: List[str] = [
|
||||
"序号", "姓名", "工号", "类别", "原单位", "原上级部门", "现单位", "现职位序列",
|
||||
"现上级部门", "现四级部门", "调动/入职时间", "操作时间", "当日排班", "异常原因",
|
||||
]
|
||||
|
||||
# 现职位序列命中以下序列的不纳入异常(不统计、不导出)
|
||||
EXCLUDE_SEQ_KEYWORDS = ("经营系管理序列", "职能系专业序列", "门店技师序列")
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 1. 通用工具
|
||||
# ----------------------------------------------
|
||||
def _clean(v) -> str:
|
||||
"""转字符串并去掉常见杂质:None、浮点 .0 尾缀、pandas 空占位(nan/native等)。"""
|
||||
if v is None:
|
||||
return ""
|
||||
s = str(v).strip()
|
||||
if s.lower() in ("nan", "none", "nat"):
|
||||
return ""
|
||||
if s.endswith(".0"):
|
||||
s = s[:-2]
|
||||
return s
|
||||
|
||||
|
||||
def _date_part(v) -> str:
|
||||
"""取日期字符串前 10 位(兼容 "YYYY-MM-DD HH:MM:SS")。"""
|
||||
return _clean(v)[:10]
|
||||
|
||||
|
||||
def _seq_excluded(seq: str) -> bool:
|
||||
"""现职位序列命中剔除序列(经营系管理序列/职能系专业序列/门店技师序列)返回 True。"""
|
||||
seq = _clean(seq)
|
||||
return any(kw in seq for kw in EXCLUDE_SEQ_KEYWORDS)
|
||||
|
||||
|
||||
def _shift_name(s: str) -> str:
|
||||
"""归一化排班名:兼容 {日期}_team_name 可能带 "YYYY-MM-DD_" 前缀,去掉前缀便于与接口 work_date_name 比对。"""
|
||||
s = _clean(s)
|
||||
if len(s) > 11 and s[4] == "-" and s[7] == "-" and s[10] == "_":
|
||||
return s[11:]
|
||||
return s
|
||||
|
||||
|
||||
def _parse_date(v) -> Optional[date]:
|
||||
"""解析日期字符串为 date,失败返回 None。"""
|
||||
s = _date_part(v)
|
||||
if not s:
|
||||
return None
|
||||
try:
|
||||
return datetime.strptime(s, "%Y-%m-%d").date()
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _recent_window(end: date = None, days: int = DAYS) -> Tuple[date, date]:
|
||||
"""返回近 N 天的 (开始日期, 结束日期),含当天。"""
|
||||
end = end or date.today()
|
||||
begin = end - timedelta(days=days - 1)
|
||||
return begin, end
|
||||
|
||||
|
||||
def _load_ledger(path: str) -> "pd.DataFrame":
|
||||
"""读取第二步导出的台账,表头在第 2 行(header=1)。"""
|
||||
if not os.path.exists(path):
|
||||
raise RuntimeError(
|
||||
f"未找到台账文件:{path}\n请先运行第二步导出(调动台账 / 预入职台账)后再执行本模块。"
|
||||
)
|
||||
df = pd.read_excel(path, header=1, dtype=str)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
logger.info("已读取台账:%s,共 %d 行", path, len(df))
|
||||
return df
|
||||
|
||||
|
||||
def _validate_session(session):
|
||||
"""校验 cookies 有效性,返回 (session, user_id);过期则重新登录并重建会话。"""
|
||||
session, user_id = _ensure_user_id(session, None)
|
||||
return session, user_id
|
||||
|
||||
|
||||
def _ensure_user_id(session, user_id: Optional[str]) -> Tuple[object, str]:
|
||||
"""获取有效 user_id 与会话。传入 None 时实时取;已有则直接复用。"""
|
||||
if user_id:
|
||||
return session, user_id
|
||||
info = fetch_cur_user_info(session)
|
||||
new_uid = _clean(info.get("userId"))
|
||||
if not new_uid:
|
||||
raise RuntimeError(f"员工基础信息接口未返回 userId:{info}")
|
||||
return session, new_uid
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 2. 按工号查询某日完整排班名({日期}_team_name)
|
||||
# ----------------------------------------------
|
||||
class _ShiftFetcher:
|
||||
"""带缓存的排班查询器:按 (工号, 日期) 缓存当日完整排班名,复用同一会话,定期校验登录态。"""
|
||||
|
||||
def __init__(self, session, user_id: str):
|
||||
self.session = session
|
||||
self.user_id = user_id
|
||||
self.cache: Dict[Tuple[str, date], str] = {}
|
||||
self.calls = 0
|
||||
|
||||
def fetch(self, code: str, day: date) -> str:
|
||||
"""返回某工号某日的完整排班名;无排班则返回空串。"""
|
||||
key = (code, day)
|
||||
if key not in self.cache:
|
||||
# 定期重新校验登录态,避免绑定过期会话
|
||||
self.calls += 1
|
||||
if self.calls % SESSION_REVALIDATE_EVERY == 1:
|
||||
self.session, uid = _ensure_user_id(self.session, None)
|
||||
self.user_id = uid
|
||||
val = self._query(code, day)
|
||||
self.cache[key] = val
|
||||
time.sleep(0.2)
|
||||
return self.cache[key]
|
||||
|
||||
def _query(self, code: str, day: date) -> str:
|
||||
day_str = day.strftime("%Y-%m-%d")
|
||||
rows = fetch_all_shift(self.session, self.user_id, code, day_str, day_str)
|
||||
for rec in rows:
|
||||
return _clean(rec.get(f"{day_str}_team_name"))
|
||||
return ""
|
||||
|
||||
|
||||
class _DeptShiftFetcher:
|
||||
"""按部门名缓存该部门的排班名集合(work_date_name),复用同一会话,定期校验登录态。
|
||||
|
||||
同一部门可能配置多个排班(技师岗/服务岗/管理岗…),通过 rf_s_kq_work_date_query
|
||||
接口按部门查出全部排班名,用于判断员工当日排班是否属于该部门。
|
||||
"""
|
||||
|
||||
def __init__(self, session):
|
||||
self.session = session
|
||||
self.cache: Dict[str, set] = {}
|
||||
self.calls = 0
|
||||
|
||||
def fetch(self, dept_name: str) -> set:
|
||||
"""返回某部门的排班名集合;部门名为空或查不到返回空集合。"""
|
||||
dept_name = _clean(dept_name)
|
||||
if not dept_name:
|
||||
return set()
|
||||
if dept_name not in self.cache:
|
||||
# 定期重新校验登录态,避免绑定过期会话
|
||||
self.calls += 1
|
||||
if self.calls % SESSION_REVALIDATE_EVERY == 1:
|
||||
self.session, _ = _ensure_user_id(self.session, None)
|
||||
self.cache[dept_name] = {_shift_name(n) for n in fetch_all_work_date(self.session, dept_name)}
|
||||
time.sleep(0.2)
|
||||
return self.cache[dept_name]
|
||||
|
||||
|
||||
def _shift_belongs(dept_fetcher: "_DeptShiftFetcher", dept_name: str, shift: str) -> bool:
|
||||
"""判断某排班是否属于某部门。
|
||||
|
||||
优先用新接口(rf_s_kq_work_date_query)按部门查出排班集合做成员判断;
|
||||
接口查不到集合(如「现单位」无直属排班)时兜底原「完整排班名包含部门名」判断。
|
||||
"""
|
||||
dept_name = _clean(dept_name)
|
||||
shift_norm = _shift_name(shift)
|
||||
if not dept_name or not shift_norm:
|
||||
return False
|
||||
dept_shifts = dept_fetcher.fetch(dept_name)
|
||||
if dept_shifts:
|
||||
return shift_norm in dept_shifts
|
||||
return dept_name in shift
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 3. 调动台账判定
|
||||
# ----------------------------------------------
|
||||
def _check_transfer_row(fetcher: "_ShiftFetcher", dept_fetcher: "_DeptShiftFetcher", r, begin: date, end: date):
|
||||
"""对单行调动记录判定,返回名单行 dict;属正常则返回 None。"""
|
||||
code = _clean(r.get("工号"))
|
||||
day = _parse_date(r.get("调动时间"))
|
||||
if not code or not day:
|
||||
return None
|
||||
if not (begin <= day <= end):
|
||||
return None
|
||||
|
||||
# 判断字段:现职位序列含「职能」按现单位判断,否则按现四级部门判断
|
||||
seq = _clean(r.get("现职位序列"))
|
||||
if _seq_excluded(seq):
|
||||
return None
|
||||
if "职能" in seq:
|
||||
target_field, target_name = "现单位", _clean(r.get("现单位"))
|
||||
else:
|
||||
target_field, target_name = "现四级部门", _clean(r.get("现四级部门"))
|
||||
|
||||
shift = fetcher.fetch(code, day) # 当日完整排班名(含上级部门),无排班为空串
|
||||
|
||||
if not shift:
|
||||
reason, present = "调动时间无排班", ""
|
||||
elif target_name and not _shift_belongs(dept_fetcher, target_name, shift):
|
||||
reason, present = f"排班未更新为{target_field}({target_name})", shift
|
||||
else:
|
||||
return None # 当日有排班且排班属于所需部门 → 正常
|
||||
|
||||
return {
|
||||
"序号": 0,
|
||||
"姓名": _clean(r.get("姓名")),
|
||||
"工号": code,
|
||||
"类别": "调动",
|
||||
"原单位": _clean(r.get("原单位")),
|
||||
"原上级部门": _clean(r.get("原上级部门")),
|
||||
"现单位": _clean(r.get("现单位")),
|
||||
"现职位序列": seq,
|
||||
"现上级部门": _clean(r.get("现上级部门")),
|
||||
"现四级部门": _clean(r.get("现四级部门")),
|
||||
"调动/入职时间": day.strftime("%Y-%m-%d"),
|
||||
"操作时间": _date_part(r.get("操作时间")),
|
||||
"当日排班": present,
|
||||
"异常原因": reason,
|
||||
}
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 4. 预入职台账判定
|
||||
# ----------------------------------------------
|
||||
def _check_preentry_row(fetcher: "_ShiftFetcher", dept_fetcher: "_DeptShiftFetcher", r, begin: date, end: date):
|
||||
"""对单行预入职记录判定,返回名单行 dict;有排班信息则返回 None。"""
|
||||
code = _clean(r.get("工号"))
|
||||
op_day = _parse_date(r.get("操作时间")) # 筛选字段:操作时间
|
||||
if not code or not op_day:
|
||||
return None
|
||||
if not (begin <= op_day <= end):
|
||||
return None
|
||||
if _seq_excluded(r.get("职位序列")):
|
||||
return None
|
||||
|
||||
# 排班检查日期:预入职日期(筛选按操作时间,查询排班按预入职日期)
|
||||
pj_day = _parse_date(r.get("预入职日期"))
|
||||
if not pj_day:
|
||||
return None
|
||||
|
||||
shift = fetcher.fetch(code, pj_day) # 当日完整排班名,无则空串
|
||||
if shift:
|
||||
return None # 有排班信息即可 → 正常
|
||||
|
||||
return {
|
||||
"序号": 0,
|
||||
"姓名": _clean(r.get("姓名")),
|
||||
"工号": code,
|
||||
"类别": "入职",
|
||||
"原单位": "",
|
||||
"原上级部门": "",
|
||||
"现单位": _clean(r.get("入职单位")),
|
||||
"现职位序列": _clean(r.get("职位序列")),
|
||||
"现上级部门": "",
|
||||
"现四级部门": "",
|
||||
"调动/入职时间": pj_day.strftime("%Y-%m-%d"),
|
||||
"操作时间": op_day.strftime("%Y-%m-%d"),
|
||||
"当日排班": "",
|
||||
"异常原因": "预入职日期无排班",
|
||||
}
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 5. 主流程
|
||||
# ----------------------------------------------
|
||||
def _collect_rows(ledger_path: str, check_row, fetcher: "_ShiftFetcher",
|
||||
dept_fetcher: "_DeptShiftFetcher", end: date) -> List[dict]:
|
||||
"""通用判定流程:读台账 → 逐行判定,返回异常行列表(未写文件)。"""
|
||||
df = _load_ledger(ledger_path)
|
||||
begin, end_date = _recent_window(end)
|
||||
logger.info("筛选范围:%s ~ %s(近 %d 天)", begin, end_date, DAYS)
|
||||
|
||||
rows: List[dict] = []
|
||||
for _, r in df.iterrows():
|
||||
row = check_row(fetcher, dept_fetcher, r, begin, end_date)
|
||||
if row:
|
||||
rows.append(row)
|
||||
logger.info("台账 %s 排班异常人数:%d", os.path.basename(ledger_path), len(rows))
|
||||
return rows
|
||||
|
||||
|
||||
def run_shift_abnormal_check(
|
||||
transfer_path: str = None,
|
||||
preentry_path: str = None,
|
||||
days: int = DAYS,
|
||||
) -> str:
|
||||
"""执行排班异常识别(调动台账 + 预入职台账),合并导出单张 Excel,返回文件路径。
|
||||
|
||||
Args:
|
||||
transfer_path: 调动台账 xlsx 路径,默认 TRANSFER_FILE
|
||||
preentry_path: 预入职台账 xlsx 路径,默认 PREENTRY_FILE
|
||||
days: 筛选近 N 天,默认 9
|
||||
"""
|
||||
global DAYS
|
||||
DAYS = days
|
||||
transfer_path = transfer_path or TRANSFER_FILE
|
||||
preentry_path = preentry_path or PREENTRY_FILE
|
||||
end = date.today()
|
||||
|
||||
session = build_hr_session()
|
||||
session, user_id = _validate_session(session)
|
||||
fetcher = _ShiftFetcher(session, user_id)
|
||||
dept_fetcher = _DeptShiftFetcher(session)
|
||||
|
||||
rows: List[dict] = []
|
||||
if os.path.exists(transfer_path):
|
||||
rows.extend(_collect_rows(transfer_path, _check_transfer_row, fetcher, dept_fetcher, end))
|
||||
else:
|
||||
logger.warning("跳过调动台账:文件不存在 %s", transfer_path)
|
||||
|
||||
if os.path.exists(preentry_path):
|
||||
rows.extend(_collect_rows(preentry_path, _check_preentry_row, fetcher, dept_fetcher, end))
|
||||
else:
|
||||
logger.warning("跳过预入职台账:文件不存在 %s", preentry_path)
|
||||
|
||||
if not rows:
|
||||
raise RuntimeError("未识别到排班异常,或台账文件均不存在(请先完成第二步导出)。")
|
||||
|
||||
# 合并排序并补序号
|
||||
rows.sort(key=lambda x: (x.get("类别", ""), x.get("姓名", ""), x.get("工号", "")))
|
||||
for idx, item in enumerate(rows, 1):
|
||||
item["序号"] = idx
|
||||
|
||||
os.makedirs(SAVE_DIR, exist_ok=True)
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
save_path = os.path.join(SAVE_DIR, f"排班异常名单_{ts}.xlsx")
|
||||
pd.DataFrame(rows, columns=COLUMNS).to_excel(save_path, index=False)
|
||||
logger.info("排班异常合并名单(共 %d 人)已保存:%s", len(rows), save_path)
|
||||
return save_path
|
||||
|
||||
|
||||
def main() -> None:
|
||||
setup_logging()
|
||||
try:
|
||||
path = run_shift_abnormal_check()
|
||||
logger.info("=" * 60)
|
||||
logger.info("【排班异常识别完成】")
|
||||
logger.info(" 导出名单:%s", path)
|
||||
logger.info("=" * 60)
|
||||
except Exception as e:
|
||||
logger.error("排班异常识别失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.wage_card
|
||||
@Description: 银行卡(工资卡)信息下载与核对、员工花名册自定义导出模块
|
||||
"""
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.wage_card
|
||||
@Description: 银行卡(工资卡)信息下载与核对、员工花名册自定义导出模块
|
||||
"""
|
||||
|
||||
@@ -1,89 +1,89 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.wage_card
|
||||
@FileName: bank_card_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-08
|
||||
@Description: 银行卡检查:下载工资卡汇总表并核对数据(身份证/姓名/银行卡号)。
|
||||
员工花名册已独立为 roster_export 模块,不再包含在此流程中。
|
||||
数据保存到 D:\\资料\\人资\\银行卡检查\\
|
||||
@Version: 2.0.0
|
||||
|
||||
使用说明:
|
||||
直接运行本文件即可依次执行工资卡下载、工资卡核对。
|
||||
python bank_card_check.py
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import 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.wage_card.wage_card_download import download_wage_card # noqa: E402
|
||||
from app.service.hrbp.ehr.wage_card.wage_card_check import check_wage_card # noqa: E402
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def run_bank_card_check():
|
||||
"""银行卡检查主流程:工资卡下载 -> 工资卡核对。"""
|
||||
results = {}
|
||||
|
||||
# ---- 第一步:下载工资卡汇总表 ----
|
||||
logger.info("=" * 60)
|
||||
logger.info("【银行卡检查】第一步:下载工资卡汇总表")
|
||||
logger.info("=" * 60)
|
||||
wage_path = None
|
||||
try:
|
||||
wage_path = download_wage_card()
|
||||
results["工资卡"] = wage_path
|
||||
logger.info("工资卡下载完成:%s", wage_path)
|
||||
except Exception as e:
|
||||
logger.error("工资卡下载失败:%s", e)
|
||||
results["工资卡"] = f"失败:{e}"
|
||||
|
||||
# ---- 第二步:核对工资卡数据 ----
|
||||
logger.info("=" * 60)
|
||||
logger.info("【银行卡检查】第二步:核对工资卡数据")
|
||||
logger.info("=" * 60)
|
||||
if wage_path:
|
||||
try:
|
||||
check_path = check_wage_card(wage_path)
|
||||
results["核对结果"] = check_path
|
||||
logger.info("工资卡核对完成:%s", check_path)
|
||||
except Exception as e:
|
||||
logger.error("工资卡核对失败:%s", e)
|
||||
results["核对结果"] = f"失败:{e}"
|
||||
else:
|
||||
logger.warning("工资卡汇总表未生成,跳过核对")
|
||||
results["核对结果"] = "跳过(工资卡下载失败)"
|
||||
|
||||
# ---- 汇总 ----
|
||||
logger.info("=" * 60)
|
||||
logger.info("【银行卡检查】全部完成,结果汇总:")
|
||||
for name, path in results.items():
|
||||
logger.info(" %s:%s", name, path)
|
||||
logger.info("=" * 60)
|
||||
return results
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""命令行入口:python bank_card_check.py"""
|
||||
setup_logging()
|
||||
run_bank_card_check()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.wage_card
|
||||
@FileName: bank_card_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-08
|
||||
@Description: 银行卡检查:下载工资卡汇总表并核对数据(身份证/姓名/银行卡号)。
|
||||
员工花名册已独立为 roster_export 模块,不再包含在此流程中。
|
||||
数据保存到 D:\\资料\\人资\\银行卡检查\\
|
||||
@Version: 2.0.0
|
||||
|
||||
使用说明:
|
||||
直接运行本文件即可依次执行工资卡下载、工资卡核对。
|
||||
python bank_card_check.py
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import 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.wage_card.wage_card_download import download_wage_card # noqa: E402
|
||||
from app.service.hrbp.ehr.wage_card.wage_card_check import check_wage_card # noqa: E402
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def run_bank_card_check():
|
||||
"""银行卡检查主流程:工资卡下载 -> 工资卡核对。"""
|
||||
results = {}
|
||||
|
||||
# ---- 第一步:下载工资卡汇总表 ----
|
||||
logger.info("=" * 60)
|
||||
logger.info("【银行卡检查】第一步:下载工资卡汇总表")
|
||||
logger.info("=" * 60)
|
||||
wage_path = None
|
||||
try:
|
||||
wage_path = download_wage_card()
|
||||
results["工资卡"] = wage_path
|
||||
logger.info("工资卡下载完成:%s", wage_path)
|
||||
except Exception as e:
|
||||
logger.error("工资卡下载失败:%s", e)
|
||||
results["工资卡"] = f"失败:{e}"
|
||||
|
||||
# ---- 第二步:核对工资卡数据 ----
|
||||
logger.info("=" * 60)
|
||||
logger.info("【银行卡检查】第二步:核对工资卡数据")
|
||||
logger.info("=" * 60)
|
||||
if wage_path:
|
||||
try:
|
||||
check_path = check_wage_card(wage_path)
|
||||
results["核对结果"] = check_path
|
||||
logger.info("工资卡核对完成:%s", check_path)
|
||||
except Exception as e:
|
||||
logger.error("工资卡核对失败:%s", e)
|
||||
results["核对结果"] = f"失败:{e}"
|
||||
else:
|
||||
logger.warning("工资卡汇总表未生成,跳过核对")
|
||||
results["核对结果"] = "跳过(工资卡下载失败)"
|
||||
|
||||
# ---- 汇总 ----
|
||||
logger.info("=" * 60)
|
||||
logger.info("【银行卡检查】全部完成,结果汇总:")
|
||||
for name, path in results.items():
|
||||
logger.info(" %s:%s", name, path)
|
||||
logger.info("=" * 60)
|
||||
return results
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""命令行入口:python bank_card_check.py"""
|
||||
setup_logging()
|
||||
run_bank_card_check()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -1,311 +1,311 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.wage_card
|
||||
@FileName: wage_card_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-08
|
||||
@Description: 工资卡汇总表核对:身份证一致性、姓名一致性、空值标记、银行卡号校验。
|
||||
读取工资卡汇总表 Excel,添加核对结果列后保存。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import 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 get_bank_dict, bank_type_to_name # noqa: E402
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
pd = None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ===================== 银行卡校验规则 =====================
|
||||
# 固定通用规则,无需随表格修改
|
||||
# 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+$")
|
||||
|
||||
|
||||
def check_bank_card(card_raw) -> dict:
|
||||
"""校验银行卡号,返回 {card, status, reason}。"""
|
||||
# 处理 pandas 从 Excel 读取时将卡号转为 float 的问题
|
||||
if isinstance(card_raw, float):
|
||||
if card_raw != card_raw: # NaN
|
||||
card = ""
|
||||
else:
|
||||
card = str(int(card_raw))
|
||||
elif isinstance(card_raw, int):
|
||||
card = str(card_raw)
|
||||
else:
|
||||
card = str(card_raw).strip().replace(" ", "")
|
||||
|
||||
if not card:
|
||||
return {"card": card, "status": "无效", "reason": "空白,无卡号"}
|
||||
|
||||
if not NUM_REG.match(card):
|
||||
return {"card": card, "status": "无效", "reason": "非纯数字,属于文字备注/脏数据"}
|
||||
|
||||
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位银行卡"}
|
||||
|
||||
if bin6 in BIN_16:
|
||||
if card_len == 16:
|
||||
return {"card": card, "status": "正常", "reason": "合规16位银联卡"}
|
||||
else:
|
||||
return {"card": card, "status": "错误", "reason": f"BIN{bin6}标准16位,录入位数错误"}
|
||||
|
||||
if bin6 in BIN_18:
|
||||
if card_len == 18:
|
||||
return {"card": card, "status": "正常", "reason": "合规18位兴业储蓄卡"}
|
||||
else:
|
||||
return {"card": card, "status": "错误", "reason": f"BIN{bin6}标准18位,录入位数错误"}
|
||||
|
||||
if card_len == 19:
|
||||
return {"card": card, "status": "正常", "reason": "合规19位储蓄卡"}
|
||||
else:
|
||||
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 = "开户人身份证"
|
||||
COL_STAFF_NAME = "员工姓名"
|
||||
COL_CARD_NAME = "开户人姓名"
|
||||
COL_BANK_ACCOUNT = "银行卡号"
|
||||
COL_BANK_NAME = "开卡银行"
|
||||
|
||||
COL_BANK_STATUS = "银行卡状态"
|
||||
COL_BANK_REASON = "银行卡说明"
|
||||
COL_CHECK_RESULT = "核对结果"
|
||||
COL_CHECK_BASIS = "校验依据"
|
||||
|
||||
|
||||
def _is_empty(val) -> bool:
|
||||
"""判断值是否为空(None、空字符串、NaN)。"""
|
||||
if val is None:
|
||||
return True
|
||||
if isinstance(val, float) and val != val: # NaN
|
||||
return True
|
||||
s = str(val).strip()
|
||||
return s == "" or s.lower() == "nan"
|
||||
|
||||
|
||||
def _normalize_id(val) -> str:
|
||||
"""将身份证号/银行卡号统一转为字符串,处理 pandas 读取 Excel 时的 float 转换问题。"""
|
||||
if val is None:
|
||||
return ""
|
||||
if isinstance(val, float):
|
||||
if val != val: # NaN
|
||||
return ""
|
||||
return str(int(val))
|
||||
if isinstance(val, int):
|
||||
return str(val)
|
||||
return str(val).strip().replace(" ", "")
|
||||
|
||||
|
||||
def check_wage_card(input_path: str, output_path: str = None) -> str:
|
||||
"""读取工资卡汇总表,执行核对并保存结果。
|
||||
|
||||
输出文件:
|
||||
- {汇总表}_核对结果.xlsx:全量核对结果
|
||||
- 无银行卡表.xlsx:未提供银行卡号(银行卡空白)的人员
|
||||
- 工资卡异常名单.xlsx:除无银行卡外的其他异常人员(含身份证不一致)
|
||||
|
||||
Args:
|
||||
input_path: 工资卡汇总表 Excel 路径
|
||||
output_path: 核对结果保存路径,默认在输入文件同目录加 _核对结果
|
||||
|
||||
Returns:
|
||||
核对结果文件路径
|
||||
"""
|
||||
if pd is None:
|
||||
raise RuntimeError("缺少 pandas 依赖,无法处理 Excel")
|
||||
|
||||
df = pd.read_excel(input_path)
|
||||
logger.info("读取工资卡汇总表:%s(%d 行)", input_path, len(df))
|
||||
|
||||
# 汇总表未带开卡银行列时,按银行编码(BANK_TYPE)补充(aa.md 银行字典接口)
|
||||
if COL_BANK_NAME not in df.columns and "银行编码" in df.columns:
|
||||
_, bank_map = get_bank_dict()
|
||||
df[COL_BANK_NAME] = df["银行编码"].apply(lambda c: bank_type_to_name(c, bank_map))
|
||||
|
||||
no_bank_rows = []
|
||||
|
||||
for idx, row in df.iterrows():
|
||||
idcard = _normalize_id(row.get(COL_IDCARD, ""))
|
||||
card_idcard = _normalize_id(row.get(COL_CARD_IDCARD, ""))
|
||||
staff_name = str(row.get(COL_STAFF_NAME, "")).strip()
|
||||
card_name = str(row.get(COL_CARD_NAME, "")).strip()
|
||||
bank_account = row.get(COL_BANK_ACCOUNT, "")
|
||||
|
||||
issues, basis, _, bk = classify_card_issue(
|
||||
idcard, card_idcard, staff_name, card_name, bank_account,
|
||||
)
|
||||
if _is_empty(bank_account):
|
||||
no_bank_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"] 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()
|
||||
bank_issues = df[df[COL_BANK_STATUS] != "正常"][COL_BANK_STATUS].value_counts().to_dict()
|
||||
passed = len(df[df[COL_CHECK_RESULT] == "通过"])
|
||||
|
||||
logger.info("核对完成:通过 %d / 总计 %d", passed, len(df))
|
||||
if result_counts:
|
||||
logger.info("核对问题分布:%s", result_counts)
|
||||
if bank_issues:
|
||||
logger.info("银行卡问题:%s", bank_issues)
|
||||
|
||||
# 保存
|
||||
if output_path is None:
|
||||
base, ext = os.path.splitext(input_path)
|
||||
output_path = f"{base}_核对结果{ext}"
|
||||
|
||||
# 将核对结果列移到最前面
|
||||
check_cols = [COL_CHECK_RESULT, COL_CHECK_BASIS, COL_BANK_STATUS, COL_BANK_REASON]
|
||||
other_cols = [c for c in df.columns if c not in check_cols]
|
||||
df = df[check_cols + other_cols]
|
||||
|
||||
df.to_excel(output_path, index=False)
|
||||
logger.info("核对结果已保存:%s", output_path)
|
||||
|
||||
# 无银行卡人员单独存表(独立文件)
|
||||
if no_bank_rows:
|
||||
base, ext = os.path.splitext(output_path)
|
||||
no_bank_path = os.path.join(os.path.dirname(base), f"无银行卡表{ext}")
|
||||
df.loc[no_bank_rows].to_excel(no_bank_path, index=False)
|
||||
logger.info("无银行卡表已保存:%s(%d 条)", no_bank_path, len(no_bank_rows))
|
||||
else:
|
||||
logger.info("无银行卡空白记录,跳过无银行卡表生成")
|
||||
|
||||
# ---- 生成异常名单(含身份证不一致,排除已单独成表的无银行卡记录) ----
|
||||
mask = (df[COL_CHECK_RESULT] != "通过") & (~df.index.isin(no_bank_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}"
|
||||
abnormal.to_excel(abnormal_path, index=False)
|
||||
logger.info("异常名单已保存:%s(%d 条)", abnormal_path, len(abnormal))
|
||||
else:
|
||||
abnormal_path = None
|
||||
logger.info("无异常记录,跳过异常名单生成")
|
||||
|
||||
return output_path
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""命令行入口:python wage_card_check.py [输入文件] [输出文件]"""
|
||||
setup_logging()
|
||||
input_path = sys.argv[1] if len(sys.argv) > 1 else os.path.join(
|
||||
r"D:\资料\人资\银行卡检查", "工资卡汇总表.xlsx"
|
||||
)
|
||||
output_path = sys.argv[2] if len(sys.argv) > 2 else None
|
||||
try:
|
||||
out = check_wage_card(input_path, output_path)
|
||||
logger.info("===== 工资卡核对完成:%s =====", out)
|
||||
except Exception as e:
|
||||
logger.error("工资卡核对失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.wage_card
|
||||
@FileName: wage_card_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-08
|
||||
@Description: 工资卡汇总表核对:身份证一致性、姓名一致性、空值标记、银行卡号校验。
|
||||
读取工资卡汇总表 Excel,添加核对结果列后保存。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import 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 get_bank_dict, bank_type_to_name # noqa: E402
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
pd = None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ===================== 银行卡校验规则 =====================
|
||||
# 固定通用规则,无需随表格修改
|
||||
# 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+$")
|
||||
|
||||
|
||||
def check_bank_card(card_raw) -> dict:
|
||||
"""校验银行卡号,返回 {card, status, reason}。"""
|
||||
# 处理 pandas 从 Excel 读取时将卡号转为 float 的问题
|
||||
if isinstance(card_raw, float):
|
||||
if card_raw != card_raw: # NaN
|
||||
card = ""
|
||||
else:
|
||||
card = str(int(card_raw))
|
||||
elif isinstance(card_raw, int):
|
||||
card = str(card_raw)
|
||||
else:
|
||||
card = str(card_raw).strip().replace(" ", "")
|
||||
|
||||
if not card:
|
||||
return {"card": card, "status": "无效", "reason": "空白,无卡号"}
|
||||
|
||||
if not NUM_REG.match(card):
|
||||
return {"card": card, "status": "无效", "reason": "非纯数字,属于文字备注/脏数据"}
|
||||
|
||||
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位银行卡"}
|
||||
|
||||
if bin6 in BIN_16:
|
||||
if card_len == 16:
|
||||
return {"card": card, "status": "正常", "reason": "合规16位银联卡"}
|
||||
else:
|
||||
return {"card": card, "status": "错误", "reason": f"BIN{bin6}标准16位,录入位数错误"}
|
||||
|
||||
if bin6 in BIN_18:
|
||||
if card_len == 18:
|
||||
return {"card": card, "status": "正常", "reason": "合规18位兴业储蓄卡"}
|
||||
else:
|
||||
return {"card": card, "status": "错误", "reason": f"BIN{bin6}标准18位,录入位数错误"}
|
||||
|
||||
if card_len == 19:
|
||||
return {"card": card, "status": "正常", "reason": "合规19位储蓄卡"}
|
||||
else:
|
||||
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 = "开户人身份证"
|
||||
COL_STAFF_NAME = "员工姓名"
|
||||
COL_CARD_NAME = "开户人姓名"
|
||||
COL_BANK_ACCOUNT = "银行卡号"
|
||||
COL_BANK_NAME = "开卡银行"
|
||||
|
||||
COL_BANK_STATUS = "银行卡状态"
|
||||
COL_BANK_REASON = "银行卡说明"
|
||||
COL_CHECK_RESULT = "核对结果"
|
||||
COL_CHECK_BASIS = "校验依据"
|
||||
|
||||
|
||||
def _is_empty(val) -> bool:
|
||||
"""判断值是否为空(None、空字符串、NaN)。"""
|
||||
if val is None:
|
||||
return True
|
||||
if isinstance(val, float) and val != val: # NaN
|
||||
return True
|
||||
s = str(val).strip()
|
||||
return s == "" or s.lower() == "nan"
|
||||
|
||||
|
||||
def _normalize_id(val) -> str:
|
||||
"""将身份证号/银行卡号统一转为字符串,处理 pandas 读取 Excel 时的 float 转换问题。"""
|
||||
if val is None:
|
||||
return ""
|
||||
if isinstance(val, float):
|
||||
if val != val: # NaN
|
||||
return ""
|
||||
return str(int(val))
|
||||
if isinstance(val, int):
|
||||
return str(val)
|
||||
return str(val).strip().replace(" ", "")
|
||||
|
||||
|
||||
def check_wage_card(input_path: str, output_path: str = None) -> str:
|
||||
"""读取工资卡汇总表,执行核对并保存结果。
|
||||
|
||||
输出文件:
|
||||
- {汇总表}_核对结果.xlsx:全量核对结果
|
||||
- 无银行卡表.xlsx:未提供银行卡号(银行卡空白)的人员
|
||||
- 工资卡异常名单.xlsx:除无银行卡外的其他异常人员(含身份证不一致)
|
||||
|
||||
Args:
|
||||
input_path: 工资卡汇总表 Excel 路径
|
||||
output_path: 核对结果保存路径,默认在输入文件同目录加 _核对结果
|
||||
|
||||
Returns:
|
||||
核对结果文件路径
|
||||
"""
|
||||
if pd is None:
|
||||
raise RuntimeError("缺少 pandas 依赖,无法处理 Excel")
|
||||
|
||||
df = pd.read_excel(input_path)
|
||||
logger.info("读取工资卡汇总表:%s(%d 行)", input_path, len(df))
|
||||
|
||||
# 汇总表未带开卡银行列时,按银行编码(BANK_TYPE)补充(aa.md 银行字典接口)
|
||||
if COL_BANK_NAME not in df.columns and "银行编码" in df.columns:
|
||||
_, bank_map = get_bank_dict()
|
||||
df[COL_BANK_NAME] = df["银行编码"].apply(lambda c: bank_type_to_name(c, bank_map))
|
||||
|
||||
no_bank_rows = []
|
||||
|
||||
for idx, row in df.iterrows():
|
||||
idcard = _normalize_id(row.get(COL_IDCARD, ""))
|
||||
card_idcard = _normalize_id(row.get(COL_CARD_IDCARD, ""))
|
||||
staff_name = str(row.get(COL_STAFF_NAME, "")).strip()
|
||||
card_name = str(row.get(COL_CARD_NAME, "")).strip()
|
||||
bank_account = row.get(COL_BANK_ACCOUNT, "")
|
||||
|
||||
issues, basis, _, bk = classify_card_issue(
|
||||
idcard, card_idcard, staff_name, card_name, bank_account,
|
||||
)
|
||||
if _is_empty(bank_account):
|
||||
no_bank_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"] 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()
|
||||
bank_issues = df[df[COL_BANK_STATUS] != "正常"][COL_BANK_STATUS].value_counts().to_dict()
|
||||
passed = len(df[df[COL_CHECK_RESULT] == "通过"])
|
||||
|
||||
logger.info("核对完成:通过 %d / 总计 %d", passed, len(df))
|
||||
if result_counts:
|
||||
logger.info("核对问题分布:%s", result_counts)
|
||||
if bank_issues:
|
||||
logger.info("银行卡问题:%s", bank_issues)
|
||||
|
||||
# 保存
|
||||
if output_path is None:
|
||||
base, ext = os.path.splitext(input_path)
|
||||
output_path = f"{base}_核对结果{ext}"
|
||||
|
||||
# 将核对结果列移到最前面
|
||||
check_cols = [COL_CHECK_RESULT, COL_CHECK_BASIS, COL_BANK_STATUS, COL_BANK_REASON]
|
||||
other_cols = [c for c in df.columns if c not in check_cols]
|
||||
df = df[check_cols + other_cols]
|
||||
|
||||
df.to_excel(output_path, index=False)
|
||||
logger.info("核对结果已保存:%s", output_path)
|
||||
|
||||
# 无银行卡人员单独存表(独立文件)
|
||||
if no_bank_rows:
|
||||
base, ext = os.path.splitext(output_path)
|
||||
no_bank_path = os.path.join(os.path.dirname(base), f"无银行卡表{ext}")
|
||||
df.loc[no_bank_rows].to_excel(no_bank_path, index=False)
|
||||
logger.info("无银行卡表已保存:%s(%d 条)", no_bank_path, len(no_bank_rows))
|
||||
else:
|
||||
logger.info("无银行卡空白记录,跳过无银行卡表生成")
|
||||
|
||||
# ---- 生成异常名单(含身份证不一致,排除已单独成表的无银行卡记录) ----
|
||||
mask = (df[COL_CHECK_RESULT] != "通过") & (~df.index.isin(no_bank_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}"
|
||||
abnormal.to_excel(abnormal_path, index=False)
|
||||
logger.info("异常名单已保存:%s(%d 条)", abnormal_path, len(abnormal))
|
||||
else:
|
||||
abnormal_path = None
|
||||
logger.info("无异常记录,跳过异常名单生成")
|
||||
|
||||
return output_path
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""命令行入口:python wage_card_check.py [输入文件] [输出文件]"""
|
||||
setup_logging()
|
||||
input_path = sys.argv[1] if len(sys.argv) > 1 else os.path.join(
|
||||
r"D:\资料\人资\银行卡检查", "工资卡汇总表.xlsx"
|
||||
)
|
||||
output_path = sys.argv[2] if len(sys.argv) > 2 else None
|
||||
try:
|
||||
out = check_wage_card(input_path, output_path)
|
||||
logger.info("===== 工资卡核对完成:%s =====", out)
|
||||
except Exception as e:
|
||||
logger.error("工资卡核对失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -1,205 +1,205 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.wage_card
|
||||
@FileName: wage_card_download.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-08 10:20
|
||||
@Description: 银行卡(工资卡)信息下载与核对:抓取「在职 + 离职」人员工资卡数据,
|
||||
将英文字段映射为中文并导出 .xlsx 汇总表。
|
||||
底层能力复用:接口调用(hr_api.py)、会话管理(session_manager.py)、接口地址(config.py)。
|
||||
@Version: 1.3.0
|
||||
|
||||
使用说明:
|
||||
1. 首次运行会调用 HR 登录模块(login.py)完成登录并缓存 cookies 到 AppData\Local\37duAutomation\.sessions\hr_cookies.json;
|
||||
后续运行自动复用缓存,登录态过期会自动重新登录。
|
||||
2. 直接运行本文件即可下载在职/离职工资卡数据并生成汇总 Excel。
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from datetime import date, timedelta
|
||||
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_wage_card_page,
|
||||
fetch_all_wage_card,
|
||||
get_bank_dict,
|
||||
bank_type_to_name,
|
||||
HRSessionExpiredError,
|
||||
)
|
||||
from app.service.hrbp.common.hr_session import ( # noqa: E402
|
||||
build_hr_session,
|
||||
refresh_hr_session,
|
||||
)
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
pd = None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ===================== 配置区(自行修改) =====================
|
||||
# 接口地址、分页大小统一在 ehr/common/config.py 中维护
|
||||
# 导出文件名 & 默认保存目录
|
||||
SAVE_NAME = "工资卡汇总表.xlsx"
|
||||
SAVE_DIR = r"D:\资料\人资\银行卡检查"
|
||||
|
||||
# 英文字段 → 中文字段映射(aa.md 提供)
|
||||
COL_MAP: Dict[str, str] = {
|
||||
"STAFF_NAME": "员工姓名",
|
||||
"STAFF_ID": "员工ID",
|
||||
"IDCARD": "身份证号",
|
||||
"join_date": "入职日期",
|
||||
"leaveOffice_date": "离职日期",
|
||||
"BELONG_UNIT_ORG_NAME": "所属事业部",
|
||||
"DEPT_ORG_NAME": "小组部门",
|
||||
"ORG_FULL_PATH": "组织全路径",
|
||||
"IS_MAIN": "是否主卡",
|
||||
"BANK_TYPE": "银行编码",
|
||||
"BANK_ACCOUNT": "银行卡号",
|
||||
"CARD_ID": "卡片ID",
|
||||
"base_code": "基地编码",
|
||||
"BRANCH_BANK": "支行编码",
|
||||
"bank_province": "银行省份",
|
||||
"bank_city": "银行城市",
|
||||
"wage_card_type": "工资卡类型",
|
||||
"branch_bank_name": "支行名称",
|
||||
"bank_no": "银行行号",
|
||||
"CARD_NAME": "开户人姓名",
|
||||
"CARD_IDCARD": "开户人身份证",
|
||||
"ext_remark": "备注",
|
||||
"si_name": "参保地点",
|
||||
"operator_name": "操作人",
|
||||
"OPERATE_TIME": "操作时间",
|
||||
"BANK_NUM": "银行卡序号",
|
||||
}
|
||||
|
||||
# 自定义列展示顺序(核心字段放最前面)
|
||||
SHOW_ORDER = [
|
||||
"人员类型", "员工姓名", "员工ID", "身份证号", "入职日期", "离职日期",
|
||||
"所属事业部", "小组部门", "组织全路径", "是否主卡",
|
||||
"银行编码", "开卡银行", "银行卡号", "开户人姓名", "参保地点", "操作人", "操作时间",
|
||||
]
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 1. 离职筛选时间范围(按当前日期动态计算)
|
||||
# ----------------------------------------------
|
||||
def get_leave_range(today: date = None) -> tuple:
|
||||
"""根据当前日期计算离职筛选时间范围,返回 (开始日期, 结束日期)。
|
||||
|
||||
规则:每月 8 号及之前 → 上月 1 日 到 今天;
|
||||
每月 8 号之后 → 本月 1 日 到 今天。
|
||||
"""
|
||||
today = today or date.today()
|
||||
if today.day <= 8:
|
||||
# 上月 1 日
|
||||
first_this_month = today.replace(day=1)
|
||||
last_prev_month = first_this_month - timedelta(days=1)
|
||||
start = last_prev_month.replace(day=1)
|
||||
else:
|
||||
# 本月 1 日
|
||||
start = today.replace(day=1)
|
||||
end = today
|
||||
return start.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 2. 登录态预检
|
||||
# ----------------------------------------------
|
||||
def preflight(session):
|
||||
"""正式抓取前先探测一次接口,确认 HR 登录态有效;过期则重新登录并重建会话。"""
|
||||
try:
|
||||
fetch_wage_card_page(session, status=1, page_no=1, page_size=1)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("预检发现 HR 登录态已过期,正在重新登录")
|
||||
return refresh_hr_session()
|
||||
return session
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 3. 导出汇总 Excel
|
||||
# ----------------------------------------------
|
||||
def export_excel(data_on_job: List[dict], data_leave: List[dict], save_dir: str = ".") -> str:
|
||||
"""合并在职/离职数据,字段映射为中文、调整列顺序并导出 .xlsx。
|
||||
|
||||
用 pandas 做数据处理,如需后续设置单元格格式可在保存前用 openpyxl 对 ws 加工。
|
||||
"""
|
||||
if pd is None:
|
||||
raise RuntimeError("缺少 pandas 依赖,无法导出 Excel")
|
||||
if not (data_on_job or data_leave):
|
||||
raise ValueError("未查询到任何数据,无法导出")
|
||||
|
||||
total_all = data_on_job + data_leave
|
||||
df = pd.DataFrame(total_all)
|
||||
# 替换英文列为中文
|
||||
df.rename(columns=COL_MAP, inplace=True)
|
||||
# 补充开卡银行:按银行编码(BANK_TYPE)匹配字典 code
|
||||
if "开卡银行" not in df.columns and "银行编码" in df.columns:
|
||||
_, bank_map = get_bank_dict()
|
||||
df["开卡银行"] = df["银行编码"].apply(lambda c: bank_type_to_name(c, bank_map))
|
||||
# 过滤表中实际存在的列,再拼接剩余其他字段
|
||||
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]
|
||||
|
||||
save_path = os.path.abspath(os.path.join(save_dir, SAVE_NAME))
|
||||
df.to_excel(save_path, index=False)
|
||||
logger.info("在职数据:%d 条", len(data_on_job))
|
||||
logger.info("离职数据:%d 条", len(data_leave))
|
||||
logger.info("合计总数据:%d 条", len(total_all))
|
||||
logger.info("文件已保存:%s", save_path)
|
||||
return save_path
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 4. 对外便捷入口
|
||||
# ----------------------------------------------
|
||||
def download_wage_card(save_dir: str = None) -> str:
|
||||
"""下载在职 + 离职工资卡数据并导出汇总 Excel,返回导出文件路径。"""
|
||||
save_dir = save_dir or SAVE_DIR
|
||||
session = preflight(build_hr_session())
|
||||
|
||||
logger.info("===== 开始抓取在职人员工资卡数据 =====")
|
||||
data_on_job = fetch_all_wage_card(session, status=1, status_name="在职")
|
||||
|
||||
logger.info("\n===== 开始抓取离职人员工资卡数据 =====")
|
||||
leave_start, leave_end = get_leave_range()
|
||||
data_leave = fetch_all_wage_card(
|
||||
session, status=2, status_name="离职",
|
||||
leave_start=leave_start, leave_end=leave_end,
|
||||
)
|
||||
|
||||
return export_excel(data_on_job, data_leave, save_dir)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
setup_logging()
|
||||
save_dir = sys.argv[1] if len(sys.argv) > 1 else SAVE_DIR
|
||||
try:
|
||||
out = download_wage_card(save_dir)
|
||||
logger.info("===== 抓取完成,导出:%s =====", out)
|
||||
except Exception as e:
|
||||
logger.error("抓取失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.wage_card
|
||||
@FileName: wage_card_download.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-08 10:20
|
||||
@Description: 银行卡(工资卡)信息下载与核对:抓取「在职 + 离职」人员工资卡数据,
|
||||
将英文字段映射为中文并导出 .xlsx 汇总表。
|
||||
底层能力复用:接口调用(hr_api.py)、会话管理(session_manager.py)、接口地址(config.py)。
|
||||
@Version: 1.3.0
|
||||
|
||||
使用说明:
|
||||
1. 首次运行会调用 HR 登录模块(login.py)完成登录并缓存 cookies 到 AppData\Local\37duAutomation\.sessions\hr_cookies.json;
|
||||
后续运行自动复用缓存,登录态过期会自动重新登录。
|
||||
2. 直接运行本文件即可下载在职/离职工资卡数据并生成汇总 Excel。
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from datetime import date, timedelta
|
||||
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_wage_card_page,
|
||||
fetch_all_wage_card,
|
||||
get_bank_dict,
|
||||
bank_type_to_name,
|
||||
HRSessionExpiredError,
|
||||
)
|
||||
from app.service.hrbp.common.hr_session import ( # noqa: E402
|
||||
build_hr_session,
|
||||
refresh_hr_session,
|
||||
)
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
pd = None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ===================== 配置区(自行修改) =====================
|
||||
# 接口地址、分页大小统一在 ehr/common/config.py 中维护
|
||||
# 导出文件名 & 默认保存目录
|
||||
SAVE_NAME = "工资卡汇总表.xlsx"
|
||||
SAVE_DIR = r"D:\资料\人资\银行卡检查"
|
||||
|
||||
# 英文字段 → 中文字段映射(aa.md 提供)
|
||||
COL_MAP: Dict[str, str] = {
|
||||
"STAFF_NAME": "员工姓名",
|
||||
"STAFF_ID": "员工ID",
|
||||
"IDCARD": "身份证号",
|
||||
"join_date": "入职日期",
|
||||
"leaveOffice_date": "离职日期",
|
||||
"BELONG_UNIT_ORG_NAME": "所属事业部",
|
||||
"DEPT_ORG_NAME": "小组部门",
|
||||
"ORG_FULL_PATH": "组织全路径",
|
||||
"IS_MAIN": "是否主卡",
|
||||
"BANK_TYPE": "银行编码",
|
||||
"BANK_ACCOUNT": "银行卡号",
|
||||
"CARD_ID": "卡片ID",
|
||||
"base_code": "基地编码",
|
||||
"BRANCH_BANK": "支行编码",
|
||||
"bank_province": "银行省份",
|
||||
"bank_city": "银行城市",
|
||||
"wage_card_type": "工资卡类型",
|
||||
"branch_bank_name": "支行名称",
|
||||
"bank_no": "银行行号",
|
||||
"CARD_NAME": "开户人姓名",
|
||||
"CARD_IDCARD": "开户人身份证",
|
||||
"ext_remark": "备注",
|
||||
"si_name": "参保地点",
|
||||
"operator_name": "操作人",
|
||||
"OPERATE_TIME": "操作时间",
|
||||
"BANK_NUM": "银行卡序号",
|
||||
}
|
||||
|
||||
# 自定义列展示顺序(核心字段放最前面)
|
||||
SHOW_ORDER = [
|
||||
"人员类型", "员工姓名", "员工ID", "身份证号", "入职日期", "离职日期",
|
||||
"所属事业部", "小组部门", "组织全路径", "是否主卡",
|
||||
"银行编码", "开卡银行", "银行卡号", "开户人姓名", "参保地点", "操作人", "操作时间",
|
||||
]
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 1. 离职筛选时间范围(按当前日期动态计算)
|
||||
# ----------------------------------------------
|
||||
def get_leave_range(today: date = None) -> tuple:
|
||||
"""根据当前日期计算离职筛选时间范围,返回 (开始日期, 结束日期)。
|
||||
|
||||
规则:每月 8 号及之前 → 上月 1 日 到 今天;
|
||||
每月 8 号之后 → 本月 1 日 到 今天。
|
||||
"""
|
||||
today = today or date.today()
|
||||
if today.day <= 8:
|
||||
# 上月 1 日
|
||||
first_this_month = today.replace(day=1)
|
||||
last_prev_month = first_this_month - timedelta(days=1)
|
||||
start = last_prev_month.replace(day=1)
|
||||
else:
|
||||
# 本月 1 日
|
||||
start = today.replace(day=1)
|
||||
end = today
|
||||
return start.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 2. 登录态预检
|
||||
# ----------------------------------------------
|
||||
def preflight(session):
|
||||
"""正式抓取前先探测一次接口,确认 HR 登录态有效;过期则重新登录并重建会话。"""
|
||||
try:
|
||||
fetch_wage_card_page(session, status=1, page_no=1, page_size=1)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("预检发现 HR 登录态已过期,正在重新登录")
|
||||
return refresh_hr_session()
|
||||
return session
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 3. 导出汇总 Excel
|
||||
# ----------------------------------------------
|
||||
def export_excel(data_on_job: List[dict], data_leave: List[dict], save_dir: str = ".") -> str:
|
||||
"""合并在职/离职数据,字段映射为中文、调整列顺序并导出 .xlsx。
|
||||
|
||||
用 pandas 做数据处理,如需后续设置单元格格式可在保存前用 openpyxl 对 ws 加工。
|
||||
"""
|
||||
if pd is None:
|
||||
raise RuntimeError("缺少 pandas 依赖,无法导出 Excel")
|
||||
if not (data_on_job or data_leave):
|
||||
raise ValueError("未查询到任何数据,无法导出")
|
||||
|
||||
total_all = data_on_job + data_leave
|
||||
df = pd.DataFrame(total_all)
|
||||
# 替换英文列为中文
|
||||
df.rename(columns=COL_MAP, inplace=True)
|
||||
# 补充开卡银行:按银行编码(BANK_TYPE)匹配字典 code
|
||||
if "开卡银行" not in df.columns and "银行编码" in df.columns:
|
||||
_, bank_map = get_bank_dict()
|
||||
df["开卡银行"] = df["银行编码"].apply(lambda c: bank_type_to_name(c, bank_map))
|
||||
# 过滤表中实际存在的列,再拼接剩余其他字段
|
||||
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]
|
||||
|
||||
save_path = os.path.abspath(os.path.join(save_dir, SAVE_NAME))
|
||||
df.to_excel(save_path, index=False)
|
||||
logger.info("在职数据:%d 条", len(data_on_job))
|
||||
logger.info("离职数据:%d 条", len(data_leave))
|
||||
logger.info("合计总数据:%d 条", len(total_all))
|
||||
logger.info("文件已保存:%s", save_path)
|
||||
return save_path
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 4. 对外便捷入口
|
||||
# ----------------------------------------------
|
||||
def download_wage_card(save_dir: str = None) -> str:
|
||||
"""下载在职 + 离职工资卡数据并导出汇总 Excel,返回导出文件路径。"""
|
||||
save_dir = save_dir or SAVE_DIR
|
||||
session = preflight(build_hr_session())
|
||||
|
||||
logger.info("===== 开始抓取在职人员工资卡数据 =====")
|
||||
data_on_job = fetch_all_wage_card(session, status=1, status_name="在职")
|
||||
|
||||
logger.info("\n===== 开始抓取离职人员工资卡数据 =====")
|
||||
leave_start, leave_end = get_leave_range()
|
||||
data_leave = fetch_all_wage_card(
|
||||
session, status=2, status_name="离职",
|
||||
leave_start=leave_start, leave_end=leave_end,
|
||||
)
|
||||
|
||||
return export_excel(data_on_job, data_leave, save_dir)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
setup_logging()
|
||||
save_dir = sys.argv[1] if len(sys.argv) > 1 else SAVE_DIR
|
||||
try:
|
||||
out = download_wage_card(save_dir)
|
||||
logger.info("===== 抓取完成,导出:%s =====", out)
|
||||
except Exception as e:
|
||||
logger.error("抓取失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
Reference in New Issue
Block a user