diff --git a/aa.md b/aa.md index f18aad7..368f8a8 100644 --- a/aa.md +++ b/aa.md @@ -1,121 +1,163 @@ -// ============================================================ -// 功能:从员工花名册筛选数据,复制到雇主险变更记录表(仅复制,不校验) -// 适用:WPS 表格 (JS宏 / JSA) -// 说明:自动根据当前日期生成目标文件名,无需手动选择 -// ============================================================ +员工排班 -function 筛选复制花名册() { - // ============================================================ - // 第一步:配置常量 - // ============================================================ - const EMPLOYEE_FILE = "D:\\资料\\人资\\雇主险\\员工花名册.xlsx"; - const SOURCE_SHEET = "雇主险增减员导出模板"; - const TARGET_SHEET = "花名册导出-雇主险使用基础信息"; - const EXCLUDE_DEPT = ["金色湖畔事业部", "秒创传媒事业部", "水庄大鹅事业部"]; +Request URL - // ============================================================ - // 第二步:自动生成当天目标文件路径 - // ============================================================ - var today = new Date(); - var year = today.getFullYear(); - var month = today.getMonth() + 1; // 月份从0开始,需+1 - var day = today.getDate(); - var dateStr = year + "." + month + "." + day; // 例如 "2026.8.12" +https://hr.37du.co/RedseaPlatform/redmagicapi/rf_p_kq_count_SelectBanci/getExecutePageResult.mc - var INSURANCE_FILE = "D:\\资料\\人资\\雇主险\\三十七度-雇主险变更记录-" + dateStr + ".xlsx"; +Request Method - // 可选:检查文件是否存在(WPS JSA 中没有直接的文件存在判断函数,可尝试打开,但此处交给后续 Open 处理) +POST - // ============================================================ - // 第三步:关闭刷新和事件,提升速度 - // ============================================================ - Application.ScreenUpdating = false; - Application.EnableEvents = false; - var startTime = new Date(); +treecode=cq37du&user_id=07b83185-6243-42bc-b79f-b81b4cffb471&sqlId=kq_count_SelectBanci&commonQuery=&commonQueryStr=&staff_ids=&person_status=1%2C4&post_no=&post_type=1&post_level=&identity=&showType=1&dateType=1&begin=2026-08-10&end=2026-08-16&bc_date=2026-08-14&base_code=37031376&staff_name=&start=0&sortType=&sortName=&pageNo=1&pageSize=15 - try { - // ============================================================ - // 第四步:打开文件 - // ============================================================ - var wbEmployee = Workbooks.Open(EMPLOYEE_FILE); - var wbInsurance = Workbooks.Open(INSURANCE_FILE); - var wsSource = wbEmployee.Sheets(SOURCE_SHEET); - var wsTarget = wbInsurance.Sheets(TARGET_SHEET); - - // ============================================================ - // 第五步:读取源数据(从第3行开始,跳过表头) - // ============================================================ - var lastRow = wsSource.Cells(wsSource.Rows.Count, 2).End(-4162).Row; - if (lastRow < 3) { - alert("源表没有数据!"); - wbEmployee.Close(false); - wbInsurance.Close(false); - return; +{ + "attributeMap": null, + "count": 1, + "datas": [ + { + "staff_id": "70023bb2-a362-438c-ba46-2f165c502351", + "work_day": "2026-08-10", + "paiban_type": "-2", + "priority": "0", + "team_id": "355945ef0e894881a21980b79b7dfbf1", + "bc_id": "de1daf426e7f4fa6916f3012434e8973", + "sb_type": 0, + "xb_type": 0, + "begin_time": "09:00", + "end_time": "18:00", + "yq_total_min": 480, + "change_value_day": 1.0, + "remark": "", + "team_name": "集团本部职能", + "STAFF_ID": "70023bb2-a362-438c-ba46-2f165c502351", + "STAFF_NAME": "郑荣斌", + "base_code": "37031376", + "join_date": "2025-10-15", + "leaveOffice_date": null, + "Regular_Time": "2026-01-15", + "person_status": "1", + "staff_status": "1", + "identity": "1", + "idCard": "500242********3177", + "STRU_ID": "bfaf2462-a96f-11f0-a0a5-000c296f9469", + "dept_one": null, + "dept_two": null, + "POST_LEVEL_ID": "8fdd4d7d-648d-11ec-b526-822ff8ed5b28", + "POST_LEVEL_NAME": "总监", + "DEPT_ORG_ONE": null, + "DEPT_ORG_TWO": null, + "DEPT_ORG_THREE": null, + "DEPT_ORG_FOUR": null, + "DEPT_ORG_FIVE": null, + "POST_ALIAS": "财务总监", + "POST_ORG_NAME": "财务总监", + "BELONG_UNIT_STRU_ID": "e451622b-8be5-11f1-a7d9-000c296f9469", + "BELONG_UNIT_ORG_NAME": "财务管理部", + "DEPT_STRU_ID": "e451622b-8be5-11f1-a7d9-000c296f9469", + "DEPT_ORG_NAME": "财务管理部", + "POST_NO": "231", + "POST_ALIAS_NAME": "财务总监", + "ORG_FULL_PATH": "集团-财务管理部", + "hrext_hsb_ext_speciality": null, + "hrext_ext_technician_code": null, + "hrext_ext_cal_person2": "", + "hrext_ext_call_phone2": "", + "hrext_ext_star_level": "正式", + "hrext_ext_rehiring_reason_type": "", + "hrext_ext_staff_type": "职能高层管理", + "hrext_ext_insurance_type": "社会保险", + "hrext_ext_recruit_way": "BOSS直聘", + "hrext_ext_call_relationship2": "", + "hrext_ext_is_CRBT_open": "", + "hrext_ext_dept_principal": "", + "hrext_ext_yb_pay_year": "", + "hrext_ext_Have_worked": "", + "hrext_ext_family_join": "否", + "hrext_ext_criminal_record": "否", + "hrext_ext_infectious_disease": "否", + "hrext_ext_References": "", + "hrext_ext_References_phone": "", + "hrext_ext_References_outside": "", + "hrext_ext_outside_References_phone": "", + "hrext_ext_is_dormitory": "否", + "hrext_ext_process_approval_status": "", + "hrext_ext_trans_type": "其他", + "bc_name": "职能正班A", + "2026-08-10_bc_id": "de1daf426e7f4fa6916f3012434e8973", + "2026-08-10_bc_name": "职能正班A", + "2026-08-10_bc_time": "09:00 ~ 18:00", + "2026-08-10_paiban_type": "-2", + "2026-08-10_remark": "", + "2026-08-10_team_name": "集团本部职能", + "2026-08-10_team_id": "355945ef0e894881a21980b79b7dfbf1", + "2026-08-10_sb_type": 0, + "2026-08-10_xb_type": 0, + "2026-08-11_bc_id": "de1daf426e7f4fa6916f3012434e8973", + "2026-08-11_bc_name": "职能正班A", + "2026-08-11_bc_time": "09:00 ~ 18:00", + "2026-08-11_paiban_type": "-2", + "2026-08-11_remark": "", + "2026-08-11_team_name": "集团本部职能", + "2026-08-11_team_id": "355945ef0e894881a21980b79b7dfbf1", + "2026-08-11_sb_type": 0, + "2026-08-11_xb_type": 0, + "2026-08-12_bc_id": "de1daf426e7f4fa6916f3012434e8973", + "2026-08-12_bc_name": "职能正班A", + "2026-08-12_bc_time": "09:00 ~ 18:00", + "2026-08-12_paiban_type": "-2", + "2026-08-12_remark": "", + "2026-08-12_team_name": "集团本部职能", + "2026-08-12_team_id": "355945ef0e894881a21980b79b7dfbf1", + "2026-08-12_sb_type": 0, + "2026-08-12_xb_type": 0, + "2026-08-13_bc_id": "de1daf426e7f4fa6916f3012434e8973", + "2026-08-13_bc_name": "职能正班A", + "2026-08-13_bc_time": "09:00 ~ 18:00", + "2026-08-13_paiban_type": "-2", + "2026-08-13_remark": "", + "2026-08-13_team_name": "集团本部职能", + "2026-08-13_team_id": "355945ef0e894881a21980b79b7dfbf1", + "2026-08-13_sb_type": 0, + "2026-08-13_xb_type": 0, + "2026-08-14_bc_id": "de1daf426e7f4fa6916f3012434e8973", + "2026-08-14_bc_name": "职能正班A", + "2026-08-14_bc_time": "09:00 ~ 18:00", + "2026-08-14_paiban_type": "-2", + "2026-08-14_remark": "", + "2026-08-14_team_name": "集团本部职能", + "2026-08-14_team_id": "355945ef0e894881a21980b79b7dfbf1", + "2026-08-14_sb_type": 0, + "2026-08-14_xb_type": 0, + "2026-08-15_bc_id": "4", + "2026-08-15_bc_name": "休息", + "2026-08-15_bc_time": "", + "2026-08-15_paiban_type": "0", + "2026-08-15_remark": "", + "2026-08-15_team_name": "集团本部职能", + "2026-08-15_team_id": "355945ef0e894881a21980b79b7dfbf1", + "2026-08-15_sb_type": "", + "2026-08-15_xb_type": "", + "2026-08-16_bc_id": "4", + "2026-08-16_bc_name": "休息", + "2026-08-16_bc_time": "", + "2026-08-16_paiban_type": "0", + "2026-08-16_remark": "", + "2026-08-16_team_name": "集团本部职能", + "2026-08-16_team_id": "355945ef0e894881a21980b79b7dfbf1", + "2026-08-16_sb_type": "", + "2026-08-16_xb_type": "", + "total_hours": 40.0, + "total_day": 5 } - var dataRange = wsSource.Range("B3:O" + lastRow); - var dataArray = dataRange.Value2; - - // ============================================================ - // 第六步:过滤数据 - // ============================================================ - var resultArray = []; - for (var i = 0; i < dataArray.length; i++) { - var row = dataArray[i]; - var dept = row[0]; // B列 - var region = row[1]; // C列 - var excludeDept = false; - for (var j = 0; j < EXCLUDE_DEPT.length; j++) { - if (dept === EXCLUDE_DEPT[j]) { excludeDept = true; break; } - } - if (!excludeDept && region !== "虚拟大区") { - resultArray.push(row); - } - } - - if (resultArray.length === 0) { - alert("筛选后没有数据!"); - wbEmployee.Close(false); - wbInsurance.Close(false); - return; - } - - // ============================================================ - // 第七步:清空目标区域(B5:O 至最后非空行) - // ============================================================ - var targetLastRow = wsTarget.Cells(wsTarget.Rows.Count, 2).End(-4162).Row; - if (targetLastRow >= 5) { - wsTarget.Range("B5:O" + targetLastRow).ClearContents(); - } - - // ============================================================ - // 第八步:写入数据 - // ============================================================ - var writeRange = wsTarget.Range( - wsTarget.Cells(5, 2), - wsTarget.Cells(5 + resultArray.length - 1, 15) - ); - writeRange.Value2 = resultArray; - - // ============================================================ - // 第九步:保存并关闭 - // ============================================================ - wbInsurance.Save(); - wbEmployee.Close(false); - wbInsurance.Close(false); - - var elapsed = (new Date() - startTime) / 1000; - Application.ScreenUpdating = true; - Application.EnableEvents = true; - alert("复制完成!\n共复制 " + resultArray.length + " 行数据\n耗时 " + elapsed.toFixed(2) + " 秒"); - - } catch (e) { - Application.ScreenUpdating = true; - Application.EnableEvents = true; - // 如果文件不存在,Workbooks.Open 会抛出错误,捕获并提示 - if (e.message.indexOf("找不到") !== -1 || e.message.indexOf("不存在") !== -1) { - alert("错误:未找到今日的目标文件(" + INSURANCE_FILE + "),请确认文件是否存在。"); - } else { - alert("复制出错:" + e.message); - } - } + ], + "pageSize": 15, + "start": 0, + "pageNo": 1, + "pageCount": 1, + "allDatas": null, + "url": null, + "state": "1", + "meg": "", + "des": "", + "viewMapper": null } diff --git a/app/service/hrbp/common/__init__.py b/app/service/hrbp/common/__init__.py new file mode 100644 index 0000000..bb031a7 --- /dev/null +++ b/app/service/hrbp/common/__init__.py @@ -0,0 +1,9 @@ +# -*- coding: utf-8 -*- +""" +@Module: hrbp.common +@FileName: __init__.py +@Description: HR 平台共享层:供 ehr / oa 两个系统模块复用。 + HR(hr.37du.co) 是两套系统共用的底座(OA 的流程引擎/排班/打卡等接口也在 HR 域), + 因此把 HR 平台的登录、会话、请求封装与共享常量上移到此层,避免 oa 反向依赖 ehr。 +@Version: 1.0.0 +""" diff --git a/app/service/hrbp/common/config.py b/app/service/hrbp/common/config.py new file mode 100644 index 0000000..531ba8a --- /dev/null +++ b/app/service/hrbp/common/config.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- +""" +@Module: hrbp.common +@FileName: config.py +@Description: HR 平台共享配置:供 ehr / oa 两个系统模块复用 +@Version: 1.0.0 +""" + +# HR 平台根域名(ehr / oa 大量后台接口均位于该域) +HR_BASE_URL = "https://hr.37du.co" + +# ---------- 假期类型编码 -> 名称映射(请假接口 leave_type 过滤 / 请假表单解析共用) ---------- +# 来源:OA 请假表单解析模块原 VACATION_TYPE_MAP,统一收口到 HR 平台共享层供各模块复用 +VACATION_TYPE_MAP = { + "04": "病假", + "05": "产假", + "09": "事假", + "11": "调休假", + "15": "普通事假", + "17": "特殊事假", + "18": "小时特假", + "19": "普通事假(晚/高峰)", + "20": "普通事假(早/中)", + "22": "半天休(仅限人资专用)", + "23": "特别福利假", + "24": "年度福利假", +} diff --git a/app/service/hrbp/common/hr_session.py b/app/service/hrbp/common/hr_session.py new file mode 100644 index 0000000..3aac249 --- /dev/null +++ b/app/service/hrbp/common/hr_session.py @@ -0,0 +1,110 @@ +# -*- coding: utf-8 -*- +""" +@Module: hrbp.common +@FileName: hr_session.py +@Description: HR 平台 requests 会话与请求封装(共享层): + - build_hr_session / refresh_hr_session:构建 HR requests 会话,登录态过期自动重登 + - HRSessionExpiredError / _is_expired / hr_request_json:HR 接口请求通用封装 + 供 ehr / oa 所有访问 hr.37du.co 接口的模块复用。 +@Version: 1.0.0 +""" + +import os +import json + +from app.common.app_paths import get_sessions_dir +from app.utils.logger import get_logger + +try: + import requests +except ImportError: + requests = None + +logger = get_logger(__name__) + +# HR 登录 cookies 持久化目录(统一放在 AppData\Local\37duAutomation,login.py 登录成功后保存) +_SESSIONS_DIR = get_sessions_dir() +HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json') + + +class HRSessionExpiredError(Exception): + """HR 登录态过期:接口返回登录页等非 JSON 内容。""" + + +def _is_expired(text) -> bool: + """接口正常情况下返回 JSON;返回登录页/错误页等非 JSON 即视为登录态过期。""" + return bool(text) and not text.lstrip().startswith(("{", "[")) + + +def build_hr_session(auto_login: bool = True) -> "requests.Session": + """用本地缓存的 HR cookies 构造 requests 会话(仅取 hr.37du.co 域)。 + + Args: + auto_login: 无 cookies 缓存时是否自动执行 HR 登录。 + True=自动登录(ehr 各模块默认);False=直接抛错提示先登录(OA 侧批处理默认) + """ + if requests is None: + raise RuntimeError("缺少 requests 依赖,请先安装") + if not os.path.exists(HR_COOKIE_FILE): + if not auto_login: + raise RuntimeError(f"未找到 HR cookies 缓存文件:{HR_COOKIE_FILE},请先执行 HR 登录") + logger.info("未找到 HR cookies 缓存,先执行 HR 登录") + refresh_hr_session() + if not os.path.exists(HR_COOKIE_FILE): + raise RuntimeError(f"HR 登录后仍未生成 cookies 文件:{HR_COOKIE_FILE}") + + with open(HR_COOKIE_FILE, encoding='utf-8') as f: + cookies = json.load(f) + + session = requests.Session() + session.headers.update({ + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36", + "Content-Type": "application/x-www-form-urlencoded", + }) + for c in cookies or []: + if c.get("domain") and "37du.co" in c["domain"]: + session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/")) + return session + + +def refresh_hr_session() -> "requests.Session": + """HR 登录态过期后重新执行 HR 登录刷新 cookies,并重建会话。""" + from app.service.hrbp.common.login import login as hr_login + if not hr_login(): + raise RuntimeError("HR 登录态过期后重新登录失败") + return build_hr_session() + + +def hr_request_json(session, method: str, url: str, params: dict, label: str, timeout: int = 20): + """通用「发送请求 + 校验响应」:发出请求 → 校验状态码/登录态 → 返回解析后的 JSON。 + + Args: + session: 已登录的 requests.Session 对象 + method: "POST" / "GET" + url: 接口地址 + params: 表单参数(POST 用 data,GET 用 params) + label: 接口中文名(用于报错信息) + timeout: 请求超时秒数,默认 20 + + Returns: + 解析后的 JSON 字典 + + Raises: + RuntimeError: 请求失败或响应异常 + HRSessionExpiredError: 登录态过期(接口返回非 JSON) + """ + if method.upper() == "GET": + resp = session.request(method, url, params=params, timeout=timeout) + else: + resp = session.request(method, url, data=params, timeout=timeout) + if not resp: + raise RuntimeError(f"{label}请求失败,未获取到响应") + if resp.status_code != 200: + raise RuntimeError(f"{label}接口状态码异常: {resp.status_code}") + if _is_expired(resp.text): + raise HRSessionExpiredError(f"HR 登录态已过期,{label}接口返回非 JSON 内容") + try: + return resp.json() + except Exception: + body = (resp.text or "")[:200] + raise RuntimeError(f"{label}接口返回非 JSON 数据(状态码 {resp.status_code}): {body}") diff --git a/app/service/hrbp/ehr/common/login.py b/app/service/hrbp/common/login.py similarity index 98% rename from app/service/hrbp/ehr/common/login.py rename to app/service/hrbp/common/login.py index 24d1495..7be2252 100644 --- a/app/service/hrbp/ehr/common/login.py +++ b/app/service/hrbp/common/login.py @@ -1,10 +1,9 @@ # -*- coding: utf-8 -*- """ -@Module: hrbp.ehr.common +@Module: hrbp.common @FileName: login.py -@Author: 小布丁 -@CreateTime: 2026-08-05 23:52 -@Description: HR 登录 + 滑块验证(改进版:双候选 + 低置信度容忍) +@Description: HR 登录 + 滑块验证(改进版:双候选 + 低置信度容忍)。 + HR 平台登录能力(原位于 ehr/common/login.py),上移到共享层供 ehr / oa 复用 @Version: 1.1.0 """ import os @@ -487,4 +486,4 @@ def login(): if __name__ == "__main__": success = login() - print("最终结果:", "成功" if success else "失败") \ No newline at end of file + print("最终结果:", "成功" if success else "失败") diff --git a/app/service/hrbp/ehr/absence/__init__.py b/app/service/hrbp/ehr/absence/__init__.py new file mode 100644 index 0000000..ebdd993 --- /dev/null +++ b/app/service/hrbp/ehr/absence/__init__.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +""" +@Module: hrbp.ehr.absence +@Description: 请休假异常分析包:门店上月请休假异常人员名单梳理。 +@Version: 1.0.0 +""" + +from app.service.hrbp.ehr.absence.absence_analysis import export_absence_list + +__all__ = ["export_absence_list"] diff --git a/app/service/hrbp/ehr/absence/absence_analysis.py b/app/service/hrbp/ehr/absence/absence_analysis.py new file mode 100644 index 0000000..e481215 --- /dev/null +++ b/app/service/hrbp/ehr/absence/absence_analysis.py @@ -0,0 +1,426 @@ +# -*- coding: utf-8 -*- +""" +@Module: hrbp.ehr.absence +@FileName: absence_analysis.py +@Author: 小布丁 +@CreateTime: 2026-08-14 +@Description: 门店上月请休假异常人员名单梳理: + 花名册(员工基础信息模板)+ 上月旷工类考勤异常(abnormal_type=2)+ 请假记录, + 计算每人上月内最长连续未出勤段,连续 >= 5 天者纳入名单,导出 Excel。 + 底层能力复用:roster_export(花名册导出)、hr_api(abnormal / leave)、hr_session(会话管理)。 +@Version: 1.0.0 + +使用说明: + 1. 首次运行会调用 HR 登录模块(login.py)完成登录并缓存 cookies,后续自动复用; + 登录态过期会自动重新登录。 + 2. 默认统计上月,可按需传入查询月份。 + 3. 花名册默认通过浏览器自动化导出最新数据(会弹出浏览器窗口,请勿关闭); + 如已存在花名册文件,可直接通过参数指定,跳过浏览器导出。 +""" + +import calendar +import os +import sys +from datetime import date, datetime, timedelta +from pathlib import Path +from typing import Dict, List, Optional, Tuple + +# ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ---- +def _find_project_root() -> str: + for parent in Path(__file__).resolve().parents: + if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file(): + return str(parent) + return str(Path(__file__).resolve().parents[5]) + + +_root = _find_project_root() +if _root not in sys.path: + sys.path.insert(0, _root) + +from app.utils.logger import get_logger, setup_logging # noqa: E402 + +# 底层复用:接口调用 / 会话管理 / 花名册导出 +from app.service.hrbp.ehr.common.hr_api import ( # noqa: E402 + fetch_cur_user_info, + fetch_all_attendance_abnormal, + fetch_all_leave, + HRSessionExpiredError, +) +from app.service.hrbp.common.hr_session import ( # noqa: E402 + build_hr_session, + refresh_hr_session, +) +from app.service.hrbp.ehr.common.config import ROSTER_TEMPLATE_NAME # noqa: E402 + +try: + import pandas as pd +except ImportError: + pd = None + +logger = get_logger(__name__) + +# ===================== 配置区(自行修改) ===================== +# 默认保存目录 +SAVE_DIR = r"D:\资料\人资\请休假异常" + +# 连续未出勤天数阈值:>= 该天数纳入名单 +MIN_CONSECUTIVE_DAYS = 5 + +# 名单输出列(需求文档第 4 节) +COLUMNS: List[str] = [ + "序号", "经营中心", "片区", "门店", "37工号", "姓名", "联系电话", "岗位", + "技师工号", "参保类型", "入职时间", "请休假起始日期", "请休假结束日期", "请休假天数", +] + +# 花名册模板字段 -> 名单字段映射(Q9 已确认「员工基础信息」模板包含所需字段) +ROSTER_COL_MAP: Dict[str, str] = { + "二级部门": "经营中心", + "三级部门": "片区", + "四级部门": "门店", + "工号": "37工号", + "姓名": "姓名", + "手机号码": "联系电话", + "岗位": "岗位", + "技师工号": "技师工号", + "参保类型": "参保类型", + "入职时间": "入职时间", +} + +# 未归岗占位文案(情况 A 且无任何请假流程) +NOT_BACK_TEXT = "未归岗,事件待定" + + +# ---------------------------------------------- +# 1. 日期范围:默认上月完整月份 +# ---------------------------------------------- +def last_month_range(today: date = None) -> Tuple[date, date]: + """返回上月完整月份的 (开始日期, 结束日期)。""" + today = today or date.today() + this_first = today.replace(day=1) + last_end = this_first - timedelta(days=1) + last_begin = last_end.replace(day=1) + return last_begin, last_end + + +def _month_range(month: str) -> Tuple[date, date]: + """按 "YYYY-MM" 返回该月完整范围的 (开始日期, 结束日期)。""" + year, mon = map(int, month.split("-")) + last_day = calendar.monthrange(year, mon)[1] + return date(year, mon, 1), date(year, mon, last_day) + + +# ---------------------------------------------- +# 2. 单元格清洗 +# ---------------------------------------------- +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 _date_part(v) -> str: + """取日期字符串前 10 位(兼容 "YYYY-MM-DD HH:MM:SS")。""" + return _clean(v)[:10] + + +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 + + +# ---------------------------------------------- +# 3. cookies 有效性校验(复用考勤模块逻辑) +# ---------------------------------------------- +def _validate_session(session): + """调用 getCurUserInfo 校验 cookies 有效性,并返回 (session, user_id, treecode)。 + 若登录态过期则重新登录并重建会话后重试。 + """ + try: + info = fetch_cur_user_info(session) + except HRSessionExpiredError: + logger.warning("cookies 已失效,正在重新登录") + session = refresh_hr_session() + info = fetch_cur_user_info(session) + user_id = info.get("userId", "") + treecode = info.get("rootId", "") + if not user_id or not treecode: + raise RuntimeError(f"员工基础信息接口未返回 userId/rootId:{info}") + logger.info("cookies 校验通过,user_id=%s,treecode=%s", user_id, treecode) + return session, user_id, treecode + + +# ---------------------------------------------- +# 4. 花名册读取(优先用已有文件,否则浏览器导出) +# ---------------------------------------------- +def _load_roster(roster_path: str = None, save_dir: str = None) -> "pd.DataFrame": + """读取花名册数据(合并后的「员工基础信息」Excel,表头在第 1 行)。 + + Args: + roster_path: 已有花名册文件路径;为空则调用 export_roster 导出最新数据。 + save_dir: 导出时的下载/输出目录,默认 SAVE_DIR。 + + Returns: + 花名册 DataFrame(列名已去除首尾空格,全部按字符串读取)。 + """ + if roster_path and not os.path.exists(roster_path): + raise RuntimeError(f"指定的花名册文件不存在:{roster_path}") + + if not roster_path: + from app.service.hrbp.ehr.roster.roster_export import export_roster + target = os.path.abspath(save_dir or SAVE_DIR) + os.makedirs(target, exist_ok=True) + download_dir = os.path.join(target, "roster_download") + os.makedirs(download_dir, exist_ok=True) + ts = datetime.now().strftime("%Y%m%d_%H%M%S") + out_path = os.path.join(target, f"花名册_{ts}.xlsx") + logger.info("===== 未指定花名册文件,开始浏览器导出 =====") + roster_path = export_roster( + download_dir=download_dir, + template_name=ROSTER_TEMPLATE_NAME, + output_path=out_path, + statuses=["在职", "离职"], + ) + + df = pd.read_excel(roster_path, dtype=str) + df.columns = [str(c).strip() for c in df.columns] + logger.info("已读取花名册:%s,共 %d 行", roster_path, len(df)) + return df + + +def _build_emp_map(df: "pd.DataFrame") -> Dict[str, "pd.Series"]: + """按工号建员工信息映射;同一工号多条时优先「在职」记录。""" + emp: Dict[str, "pd.Series"] = {} + for _, row in df.iterrows(): + code = _clean(row.get("工号")) + if not code: + continue + if code in emp and _clean(row.get("类型")) != "在职": + continue # 已有在职记录,跳过离职/其他 + emp[code] = row + logger.info("花名册有效员工:%d 人", len(emp)) + return emp + + +# ---------------------------------------------- +# 5. 连续未出勤段计算 +# ---------------------------------------------- +def _longest_consecutive(days: set) -> Optional[Tuple[date, date]]: + """返回日期集合中最长连续段的 (start, end);空集返回 None。""" + if not days: + return None + ds = sorted(days) + best_len, best_start, best_end = 1, ds[0], ds[0] + cur_len, cur_start, prev = 1, ds[0], ds[0] + for d in ds[1:]: + if (d - prev).days == 1: + cur_len += 1 + else: + if cur_len > best_len: + best_len, best_start, best_end = cur_len, cur_start, prev + cur_start, cur_len = d, 1 + prev = d + if cur_len > best_len: + best_len, best_start, best_end = cur_len, cur_start, prev + return best_start, best_end + + +# ---------------------------------------------- +# 6. 请假截止日期(情况 A:该段之后无出勤) +# ---------------------------------------------- +def _latest_leave_end(session, user_id: str, code: str, begin: date, end: date) -> Optional[str]: + """查询该员工上月请假记录,返回最新请假流程的截止日期 "YYYY-MM-DD";无请假返回 None。""" + leaves = fetch_all_leave( + session, user_id, code, begin.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d") + ) + ends = [_parse_date(r.get("end_time")) for r in leaves] + ends = [d for d in ends if d] + if not ends: + return None + return max(ends).strftime("%Y-%m-%d") + + +# ---------------------------------------------- +# 7. 名单梳理主流程 +# ---------------------------------------------- +def _analyze(emp: Dict[str, "pd.Series"], absent_by_code: Dict[str, set], + session, user_id: str, begin: date, end: date) -> List[dict]: + """按工号计算最长连续未出勤段,组装名单行。 + + Returns: + 名单行字典列表(列见 COLUMNS),未命中时为空列表。 + """ + all_days = [begin + timedelta(days=i) for i in range((end - begin).days + 1)] + hits: List[Tuple[str, date, date]] = [] # (工号, 段起始, 段结束) + + for code, absent in absent_by_code.items(): + seg = _longest_consecutive(absent) + if not seg: + continue + seg_start, seg_end = seg + if (seg_end - seg_start).days + 1 < MIN_CONSECUTIVE_DAYS: + continue + hits.append((code, seg_start, seg_end)) + logger.info("连续未出勤 >= %d 天的员工:%d 人", MIN_CONSECUTIVE_DAYS, len(hits)) + + # 组装输出行(按 经营中心/片区/门店/工号 排序) + def _sort_key(item): + r = emp.get(item[0]) + return (_clean(r.get("二级部门")) if r is not None else "", + _clean(r.get("三级部门")) if r is not None else "", + _clean(r.get("四级部门")) if r is not None else "", item[0]) + + rows: List[dict] = [] + for idx, (code, seg_start, seg_end) in enumerate(sorted(hits, key=_sort_key), 1): + r = emp.get(code) + # 结束日期:段后是否已有出勤(上月内) + later = [d for d in all_days if d > seg_end and d not in absent_by_code[code]] + if later: + first_later = min(later) + end_str = (first_later - timedelta(days=1)).strftime("%Y-%m-%d") + days_str = str((date.fromisoformat(end_str) - seg_start).days + 1) + else: + # 情况 A:仍无出勤,取最新请假截止;无请假则标记未归岗 + leave_end = _latest_leave_end(session, user_id, code, begin, end) + if leave_end: + end_str = leave_end + days_str = str((date.fromisoformat(leave_end) - seg_start).days + 1) + else: + end_str = NOT_BACK_TEXT + days_str = "" + rows.append({ + "序号": idx, + "经营中心": _clean(r.get("二级部门")) if r is not None else "", + "片区": _clean(r.get("三级部门")) if r is not None else "", + "门店": _clean(r.get("四级部门")) if r is not None else "", + "37工号": code, + "姓名": _clean(r.get("姓名")) if r is not None else "", + "联系电话": _clean(r.get("手机号码")) if r is not None else "", + "岗位": _clean(r.get("岗位")) if r is not None else "", + "技师工号": _clean(r.get("技师工号")) if r is not None else "", + "参保类型": _clean(r.get("参保类型")) if r is not None else "", + "入职时间": _date_part(r.get("入职时间")) if r is not None else "", + "请休假起始日期": seg_start.strftime("%Y-%m-%d"), + "请休假结束日期": end_str, + "请休假天数": days_str, + }) + return rows + + +# ---------------------------------------------- +# 8. 导出名单 Excel +# ---------------------------------------------- +def export_excel(rows: List[dict], save_dir: str, month_str: str) -> str: + """将名单行导出为 .xlsx(无数据时也保留表头,便于对照)。""" + if pd is None: + raise RuntimeError("缺少 pandas 依赖,无法导出 Excel") + os.makedirs(save_dir, exist_ok=True) + df = pd.DataFrame(rows, columns=COLUMNS) + ts = datetime.now().strftime("%Y%m%d_%H%M%S") + save_path = os.path.abspath(os.path.join(save_dir, f"门店上月请休假异常名单_{month_str}_{ts}.xlsx")) + try: + df.to_excel(save_path, index=False) + except PermissionError: + raise RuntimeError( + f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试" + ) + logger.info("名单数据:%d 条", len(rows)) + logger.info("文件已保存:%s", save_path) + return save_path + + +# ---------------------------------------------- +# 9. 对外入口 +# ---------------------------------------------- +def export_absence_list(save_dir: str = None, roster_path: str = None, month: str = None) -> str: + """梳理上月请休假异常名单并导出 Excel,返回导出文件路径。 + + Args: + save_dir: 保存目录,默认 SAVE_DIR + roster_path: 已有花名册文件路径;为空则浏览器导出最新花名册 + month: 查询月份 "YYYY-MM"(默认上月) + + Returns: + 导出文件路径 + """ + save_dir = save_dir or SAVE_DIR + os.makedirs(save_dir, exist_ok=True) + + # 统计范围:默认上月完整月份 + if month: + begin, end = _month_range(month) + else: + begin, end = last_month_range() + month_str = f"{begin:%Y%m}" + logger.info("===== 请休假异常名单梳理,统计范围:%s ~ %s =====", + begin.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d")) + + # 1. 花名册 + df = _load_roster(roster_path, save_dir) + emp = _build_emp_map(df) + + # 2. 会话校验 + session = build_hr_session() + session, user_id, treecode = _validate_session(session) + + # 3. 上月旷工类考勤异常(abnormal_type=2,所有调整状态) + abnormals = fetch_all_attendance_abnormal( + session, user_id, treecode, + begin.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d"), + is_adjusted="", abnormal_type="2", + ) + logger.info("上月旷工类异常共 %d 条", len(abnormals)) + + # 4. 按工号聚合未出勤日期 + absent_by_code: Dict[str, set] = {} + for rec in abnormals: + code = _clean(rec.get("base_code")) + d = _parse_date(rec.get("work_day")) + if code and d: + absent_by_code.setdefault(code, set()).add(d) + logger.info("涉及员工:%d 人", len(absent_by_code)) + + # 5. 计算连续未出勤段,组装名单 + rows = _analyze(emp, absent_by_code, session, user_id, begin, end) + + # 6. 导出 + path = export_excel(rows, save_dir, month_str) + logger.info("=" * 60) + logger.info("【请休假异常名单汇总】") + logger.info(" 统计范围:%s ~ %s", begin, end) + logger.info(" 连续未出勤 >= %d 天:%d 人", MIN_CONSECUTIVE_DAYS, len(rows)) + logger.info(" 导出文件:%s", path) + logger.info("=" * 60) + return path + + +def main() -> None: + setup_logging() + save_dir = sys.argv[1] if len(sys.argv) > 1 else SAVE_DIR + roster_path = sys.argv[2] if len(sys.argv) > 2 else None + month = sys.argv[3] if len(sys.argv) > 3 else None + try: + out = export_absence_list(save_dir, roster_path, month) + logger.info("===== 请休假异常名单梳理完成,导出:%s =====", out) + except Exception as e: + if "正被占用" in str(e): + # 文件被 Excel 占用:只提醒关闭后重试,不抛堆栈 + logger.error("=========== 提醒 ===========") + logger.error(str(e)) + logger.error("请关闭该 Excel 文件后重新运行即可,无需重查数据。") + return + logger.error("请休假异常名单梳理失败:%s", e) + raise + + +if __name__ == "__main__": + main() diff --git a/app/service/hrbp/ehr/attendance/abnormal_check.py b/app/service/hrbp/ehr/attendance/abnormal_check.py new file mode 100644 index 0000000..9f618b1 --- /dev/null +++ b/app/service/hrbp/ehr/attendance/abnormal_check.py @@ -0,0 +1,605 @@ +# -*- coding: utf-8 -*- +""" +@Module: hrbp.ehr.attendance +@FileName: abnormal_check.py +@Author: 小布丁 +@CreateTime: 2026-08-14 +@Description: 月考勤异常三重复核:结合考勤异常 / 请假 / 加班 / 打卡四类接口, + 对当月数据做三项检查并输出多 Sheet Excel 报告(独立于周考勤异常处理流程): + + 检查1:已确认异常(is_adjusted=2)的日期,是否存在请假流程? + —— 可能存在「提前确认后请假」导致仍为考勤异常的情况; + 检查2:休息日加班(类型3)且加班天数为 0.5 天,当日打卡是否按考勤班段正常打卡(无漏打卡)? + 检查3:员工整日请假(leave_days>=1)当日,仍存在其他考勤异常(未调整/已确认)处于确认 + —— 弹出提示「该员工XX日考勤状态存在异常」。 + +底层复用:接口调用(app.service.hrbp.ehr.common.hr_api)、会话管理(app.service.hrbp.common.hr_session)。 +@Version: 1.0.0 + +使用说明: + 1. 首次运行会调用 HR 登录模块(login.py)完成登录并缓存 cookies 到 + AppData\\Local\\37duAutomation\\.sessions\\hr_cookies.json; + 后续运行自动复用缓存,登录态过期会自动重新登录。 + 2. 直接运行本文件即可对当月做三查并导出 Excel 报告。 + 3. 加班/请假接口按「空工号=查询全部」调用,返回的记录自带工号,无需额外员工列表接口。 +""" + +import os +import sys +from datetime import date, datetime, timedelta +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple + +# ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ---- +def _find_project_root() -> str: + for parent in Path(__file__).resolve().parents: + if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file(): + return str(parent) + return str(Path(__file__).resolve().parents[5]) + + +_root = _find_project_root() +if _root not in sys.path: + sys.path.insert(0, _root) + +from app.utils.logger import get_logger, setup_logging # noqa: E402 + +# 底层复用:接口调用 / 会话管理 +from app.service.hrbp.ehr.common.hr_api import ( # noqa: E402 + fetch_cur_user_info, + fetch_all_attendance_abnormal, + fetch_all_leave, + fetch_all_overtime, + fetch_all_kq_data, + fetch_all_shift, + HRSessionExpiredError, +) +from app.service.hrbp.common.hr_session import ( # noqa: E402 + build_hr_session, + refresh_hr_session, +) +from app.service.hrbp.common.config import VACATION_TYPE_MAP # noqa: E402 + +try: + import pandas as pd +except ImportError: + pd = None + +logger = get_logger(__name__) + +# ===================== 配置区(自行修改) ===================== +# 默认保存目录(与周考勤异常导出目录保持一致) +SAVE_DIR = r"D:\资料\人资\考勤异常" + +# 考勤异常调整状态过滤:0=未调整、1=补签调整、2=确认异常、3=正常调整、空=所有状态 +IS_ADJUSTED_CONFIRMED = "2" # 已确认异常(检查1) +IS_ADJUSTED_OPEN = "0" # 未调整异常(检查3并集之一) +IS_ADJUSTED_ALL = "" # 全部状态 + +# 加班类型:空=全部、1=延时加班、2=法定假日加班、3=休息日加班 +WORK_OVERTIME_TYPE_REST = "3" + +# 休息日半天加班判定阈值(ot_days / sys_ot_days / plan_ot_days ≈ 0.5) +HALF_DAY = 0.5 +EPS = 1e-6 + +# 打卡与班段边界匹配容差(分钟):上班打卡在班段开始前后、下班打卡在班段结束前后 +# 该时间内有打卡即视为「按班段正常打卡」,用于排除晚到/早走导致的漏打卡误报 +PUNCH_TOLERANCE_MIN = 60 + + +# ---------------------------------------------- +# 1. 工具函数 +# ---------------------------------------------- +def current_month_range(today: date = None) -> Tuple[str, str]: + """返回当月的查询日期范围 (开始日期, 结束日期)。开始=当月1日,结束=今天。""" + today = today or date.today() + begin = today.replace(day=1) + return begin.strftime("%Y-%m-%d"), today.strftime("%Y-%m-%d") + + +def _get(rec: Dict[str, Any], *keys: str, default: Any = "") -> Any: + """从记录中取第一个存在的键的值(兼容字段大小写差异)。""" + for k in keys: + if rec.get(k) is not None and rec.get(k) != "": + return rec[k] + return default + + +def _to_date_str(value: Any) -> str: + """将接口返回的日期/时间值归一化为 'YYYY-MM-DD'(取前10位)。""" + if value is None: + return "" + s = str(value).strip() + return s[:10] if len(s) >= 10 else s + + +def _float(value: Any, default: float = 0.0) -> float: + try: + return float(value) + except (TypeError, ValueError): + return default + + +def _is_half_day_ot(rec: Dict[str, Any]) -> bool: + """判断加班记录是否为休息日半天(0.5 天)。 + + 依次取 ot_days / sys_ot_days / plan_ot_days,任一 ≈ 0.5 即判定半天。 + """ + for key in ("ot_days", "sys_ot_days", "plan_ot_days"): + val = rec.get(key) + if val is not None and val != "": + if abs(_float(val) - HALF_DAY) <= EPS: + return True + return False + + +def _leave_type_name(rec: Dict[str, Any]) -> str: + """从请假记录中提取假期类型名称(兼容编码与名称两种输入)。""" + raw = _get(rec, "leave_type", "vacation_type", "sub_type", "LEAVE_TYPE") + raw = str(raw).strip() + if raw in VACATION_TYPE_MAP: + return VACATION_TYPE_MAP[raw] + return raw + + +def _staff_name(rec: Dict[str, Any]) -> str: + """兼容取员工姓名字段(不同接口命名不同)。""" + return str(_get(rec, "STAFF_NAME", "staff_name", "staffName", default="")) + + +def _punch_analysis(records: List[Dict[str, Any]]) -> Dict[str, Any]: + """对某日打卡流水做统计。 + + 打卡记录无法可靠区分上下班(time_order 多为空),按时间最早=上班、最晚=下班汇总。 + + Returns: + {count, first, last}:count 打卡次数,first/last 最早/最晚打卡时间(含时分) + """ + times = [] + for rec in records: + t = _get(rec, "kq_time", "kqTime", "punch_time") + if t: + times.append(str(t)) + times.sort() + if not times: + return {"count": 0, "first": "", "last": ""} + return {"count": len(times), "first": times[0], "last": times[-1]} + + +def _to_minutes(value: Any) -> Optional[int]: + """将 "HH:MM[:SS]" 时间串转为当日分钟数;解析失败返回 None。""" + if value is None: + return None + s = str(value).strip() + if not s: + return None + # 兼容 "09:00" / "09:00:00" / "2026-08-03 09:00:00"(取最后的时间段) + import re + m = re.search(r"(\d{1,2}):(\d{2})(?::(\d{2}))?$", s) + if not m: + return None + return int(m.group(1)) * 60 + int(m.group(2)) + + +def _parse_shift_time(bc_time: str) -> Tuple[Optional[int], Optional[int]]: + """解析班段时间 "09:00 ~ 18:00" -> (开始分钟, 结束分钟);无班段返回 (None, None)。""" + if not bc_time: + return None, None + import re + m = re.search(r"(\d{1,2}):(\d{2})\s*~\s*(\d{1,2}):(\d{2})", str(bc_time)) + if not m: + return None, None + start = int(m.group(1)) * 60 + int(m.group(2)) + end = int(m.group(3)) * 60 + int(m.group(4)) + return start, end + + +def _extract_day_shift(shift_rows: List[Dict[str, Any]], date_str: str) -> Dict[str, Any]: + """从某员工排班记录中提取指定日期的班段信息。 + + 排班接口 datas 为动态列(key 为 "YYYY-MM-DD_bc_name/bc_time/paiban_type"): + - bc_time:班段时间,如 "09:00 ~ 18:00"(休息日为空串) + - paiban_type:-2=上班、0=休息 + + Returns: + {"bc_name": 班次名, "bc_time": 班段时间, "paiban_type": 排班类型} + """ + info = {"bc_name": "", "bc_time": "", "paiban_type": ""} + for rec in shift_rows: + name = _get(rec, f"{date_str}_bc_name", default="") + time_ = _get(rec, f"{date_str}_bc_time", default="") + paiban = _get(rec, f"{date_str}_paiban_type", default="") + if name or time_ or paiban: + info = {"bc_name": str(name), "bc_time": str(time_), "paiban_type": str(paiban)} + break + return info + + +def _judge_punch_by_shift(p: Dict[str, Any], shift_info: Dict[str, Any]) -> str: + """结合班段时间判断当日打卡是否正常。 + + 规则: + - 排班有班段时间(如 "09:00 ~ 12:00"):最早打卡应覆盖班段开始(前后容差内), + 最晚打卡应覆盖班段结束,且打卡次数 >= 2 → 正常; + - 排班为休息日(无班段时间):退化为打卡次数判断(>=2 正常)。 + """ + start_min, end_min = _parse_shift_time(shift_info.get("bc_time", "")) + count = p["count"] + tol = PUNCH_TOLERANCE_MIN + + # 无班段(休息日排班):按打卡次数判断 + if start_min is None or end_min is None: + if count >= 2: + return "正常(有上班+下班打卡)" + if count == 1: + return "漏打卡(当日仅 1 次打卡,缺一次)" + return "漏打卡(当日无打卡记录)" + + # 有班段:最早打卡覆盖班段开始、最晚打卡覆盖班段结束 + first_min = _to_minutes(p["first"]) + last_min = _to_minutes(p["last"]) + first_ok = first_min is not None and first_min <= start_min + tol + last_ok = last_min is not None and last_min >= end_min - tol + if count >= 2 and first_ok and last_ok: + return "正常(按班段上班/下班打卡齐全)" + if count == 0: + return "漏打卡(当日无打卡记录)" + if count == 1: + return "漏打卡(当日仅 1 次打卡,缺一次)" + return "漏打卡(打卡未按班段覆盖上下班)" + + +# ---------------------------------------------- +# 2. cookies 有效性校验(员工基础信息接口) +# ---------------------------------------------- +def _validate_session(session): + """调用 getCurUserInfo 校验 cookies 有效性,并返回 (session, user_id, treecode)。 + 若登录态过期则重新登录并重建会话后重试。 + """ + try: + info = fetch_cur_user_info(session) + except HRSessionExpiredError: + logger.warning("cookies 已失效,正在重新登录") + session = refresh_hr_session() + info = fetch_cur_user_info(session) + user_id = info.get("userId", "") + treecode = info.get("rootId", "") + if not user_id or not treecode: + raise RuntimeError(f"员工基础信息接口未返回 userId/rootId:{info}") + logger.info("cookies 校验通过,user_id=%s,treecode=%s", user_id, treecode) + return session, user_id, treecode + + +# ---------------------------------------------- +# 3. 数据获取(全量拉取,返回记录自带工号) +# ---------------------------------------------- +def _fetch_all_data(session, user_id: str, treecode: str, begin: str, end: str) -> Dict[str, list]: + """一次性拉取三项检查所需的基础数据。 + + - abnormal_confirmed: 已确认异常(is_adjusted=2) + - abnormal_open: 未调整异常(is_adjusted=0) + - leaves: 全部请假记录(空工号=全量,检查1/检查3共用) + - rest_overtime: 全部休息日加班(类型3,空工号=全量,检查2用) + + Returns: + 以名称为键的列表字典 + """ + logger.info("===== 月考勤异常三查,日期范围:%s ~ %s =====", begin, end) + + abnormal_confirmed = fetch_all_attendance_abnormal( + session, user_id, treecode, begin, end, IS_ADJUSTED_CONFIRMED + ) + abnormal_open = fetch_all_attendance_abnormal( + session, user_id, treecode, begin, end, IS_ADJUSTED_OPEN + ) + logger.info("已确认异常 %d 条,未调整异常 %d 条", len(abnormal_confirmed), len(abnormal_open)) + + # 请假:空工号 = 查询全部员工(返回记录自带 base_code) + leaves = fetch_all_leave(session, user_id, "", begin, end) + logger.info("请假记录(全部员工)%d 条", len(leaves)) + + # 休息日加班:空工号 = 查询全部员工 + rest_overtime = fetch_all_overtime( + session, user_id, "", begin, end, WORK_OVERTIME_TYPE_REST + ) + logger.info("休息日加班记录(全部员工)%d 条", len(rest_overtime)) + + return { + "abnormal_confirmed": abnormal_confirmed, + "abnormal_open": abnormal_open, + "leaves": leaves, + "rest_overtime": rest_overtime, + } + + +def _build_leave_set(leaves: List[Dict[str, Any]], need_full_day: bool = False) -> Dict[Tuple[str, str], Dict]: + """把请假记录索引化为 {(base_code, 'YYYY-MM-DD'): leave_rec}。 + + need_full_day=True 时只保留整日请假(leave_days>=1)的每一天; + 否则保留请假范围内的每一天(供检查1判断「日期是否有请假流程」)。 + """ + index: Dict[Tuple[str, str], Dict] = {} + for rec in leaves: + code = str(_get(rec, "base_code")).strip() + start = _to_date_str(_get(rec, "start_time", "begin_date")) + end = _to_date_str(_get(rec, "end_time", "end_date")) + leave_days = _float(rec.get("leave_days")) + if not code or not start or not end: + continue + if need_full_day and leave_days < 1: + continue + try: + cur = datetime.strptime(start, "%Y-%m-%d").date() + end_d = datetime.strptime(end, "%Y-%m-%d").date() + except ValueError: + continue + if end_d < cur: + continue + step = timedelta(days=1) + while cur <= end_d: + index[(code, cur.strftime("%Y-%m-%d"))] = rec + cur += step + return index + + +# ---------------------------------------------- +# 4. 检查1:已确认异常日期 × 请假流程 +# ---------------------------------------------- +def check_leave_after_confirm(abnormal_confirmed: List[Dict[str, Any]], + leave_index: Dict[Tuple[str, str], Dict]) -> List[Dict[str, Any]]: + """已确认异常(is_adjusted=2)的日期,是否同时存在请假流程。 + + 若存在,说明可能是「提前确认后请假」导致仍为考勤异常,需人工复核。 + """ + rows: List[Dict[str, Any]] = [] + for ab in abnormal_confirmed: + code = str(_get(ab, "base_code")).strip() + work_day = _to_date_str(_get(ab, "work_day")) + if not code or not work_day: + continue + leave_rec = leave_index.get((code, work_day)) + if not leave_rec: + continue + rows.append({ + "员工姓名": _staff_name(ab), + "工号": code, + "考勤日期": work_day, + "异常类型": _get(ab, "abnormal"), + "请假类型": _leave_type_name(leave_rec), + "请假起止": f"{_to_date_str(_get(leave_rec, 'start_time', 'begin_date'))} ~ " + f"{_to_date_str(_get(leave_rec, 'end_time', 'end_date'))}", + "问题说明": "该日期已确认考勤异常,但同时存在请假流程,可能为「提前确认后请假」仍为异常", + }) + return rows + + +# ---------------------------------------------- +# 5. 检查2:休息日半天加班 × 打卡校验(结合排班班段) +# ---------------------------------------------- +def check_rest_day_half_day_punch(session, user_id: str, treecode: str, + rest_overtime: List[Dict[str, Any]], + begin: str, end: str) -> List[Dict[str, Any]]: + """休息日加班(类型3)且加班天数为 0.5 天时,校验当日打卡是否按考勤班段正常打卡。 + + 步骤: + 1. 按工号拉取排班(fetch_all_shift),取加班日期的班段时间(bc_time); + 2. 拉取该员工当日打卡流水(fetch_all_kq_data); + 3. 结合班段判定:最早打卡覆盖班段开始、最晚打卡覆盖班段结束且次数>=2 → 正常, + 否则漏打卡;休息日排班(无班段)则退化为按打卡次数判断。 + """ + rows: List[Dict[str, Any]] = [] + half_ots = [ot for ot in rest_overtime if _is_half_day_ot(ot)] + logger.info("休息日半天加班 %d 条,逐一校验打卡(结合排班班段)", len(half_ots)) + + # 按工号缓存排班记录,避免重复请求 + shift_cache: Dict[str, List[Dict[str, Any]]] = {} + + for ot in half_ots: + code = str(_get(ot, "base_code")).strip() + ot_date = _to_date_str(_get(ot, "OT_DATE", "ot_date")) + if not code or not ot_date: + continue + try: + kq = fetch_all_kq_data(session, user_id, code, ot_date, ot_date, treecode) + except HRSessionExpiredError: + # fetch_all_kq_data 内部已处理重登;此处兜底 + raise + + # 拉取该员工排班(缓存),取加班日的班段 + if code not in shift_cache: + shift_cache[code] = fetch_all_shift(session, user_id, code, begin, end, treecode) + shift_info = _extract_day_shift(shift_cache.get(code, []), ot_date) + + p = _punch_analysis(kq) + judge = _judge_punch_by_shift(p, shift_info) + rows.append({ + "员工姓名": _staff_name(ot), + "工号": code, + "加班日期": ot_date, + "加班天数": _get(ot, "ot_days", "sys_ot_days", "plan_ot_days", default="0.5"), + "排班班次": shift_info["bc_name"], + "排班班段时间": shift_info["bc_time"], + "计划时段": f"{_get(ot, 'PLAN_START_TIME') or _get(ot, 'FINAL_START_TIME')} ~ " + f"{_get(ot, 'PLAN_END_TIME') or _get(ot, 'FINAL_END_TIME')}", + "上班打卡": p["first"], + "下班打卡": p["last"], + "打卡次数": p["count"], + "判定": judge, + }) + return rows + + +# ---------------------------------------------- +# 6. 检查3:整日请假 × 考勤异常 → 提示 +# ---------------------------------------------- +def check_full_day_leave_abnormal(abnormal_confirmed: List[Dict[str, Any]], + abnormal_open: List[Dict[str, Any]], + leaves: List[Dict[str, Any]]) -> List[Dict[str, Any]]: + """员工整日请假(leave_days>=1)当日,仍存在其他考勤异常(未调整/已确认)→ 提示。 + + 异常并集 = 未调整(is_adjusted=0) + 已确认(is_adjusted=2)。 + """ + rows: List[Dict[str, Any]] = [] + + # 整日请假日期索引 {(code, date): leave_rec} + full_day_leave = _build_leave_set(leaves, need_full_day=True) + if not full_day_leave: + logger.info("无整日请假记录,检查3跳过") + return rows + + # 异常并集(同一员工同一日期可能同时有未调整/已确认,各自输出一条便于核查) + for ab in list(abnormal_open) + list(abnormal_confirmed): + code = str(_get(ab, "base_code")).strip() + work_day = _to_date_str(_get(ab, "work_day")) + if not code or not work_day: + continue + leave_rec = full_day_leave.get((code, work_day)) + if not leave_rec: + continue + is_adjusted = str(ab.get("is_adjusted", "")) + status = "确认异常" if is_adjusted == "2" else ("未调整" if is_adjusted == "0" else "异常") + hint = f"该员工{work_day}考勤状态存在异常" + rows.append({ + "员工姓名": _staff_name(ab), + "工号": code, + "请假日期": work_day, + "请假类型": _leave_type_name(leave_rec), + "请假天数": _get(leave_rec, "leave_days"), + "异常类型": _get(ab, "abnormal"), + "异常状态": status, + "提示": hint, + }) + return rows + + +# ---------------------------------------------- +# 7. 导出多 Sheet Excel 报告 +# ---------------------------------------------- +def export_report(results: Dict[str, List[Dict[str, Any]]], save_dir: str, month_str: str) -> str: + """将三项检查结果导出为多 Sheet Excel 报告。 + + Sheet 顺序:汇总 -> 检查1 -> 检查2 -> 检查3(无数据的 Sheet 也保留表头便于对照)。 + """ + if pd is None: + raise RuntimeError("缺少 pandas 依赖,无法导出 Excel") + + os.makedirs(save_dir, exist_ok=True) + ts = datetime.now().strftime("%Y%m%d_%H%M%S") + save_path = os.path.abspath(os.path.join(save_dir, f"月考勤异常三查_{month_str}_{ts}.xlsx")) + + sheet_cfg = [ + ("检查1_确认异常有请假", "check1", [ + "员工姓名", "工号", "考勤日期", "异常类型", "请假类型", "请假起止", "问题说明"]), + ("检查2_休息日半天打卡", "check2", [ + "员工姓名", "工号", "加班日期", "加班天数", "排班班次", "排班班段时间", "计划时段", + "上班打卡", "下班打卡", "打卡次数", "判定"]), + ("检查3_整日请假有异常", "check3", [ + "员工姓名", "工号", "请假日期", "请假类型", "请假天数", "异常类型", "异常状态", "提示"]), + ] + + c1 = results.get("check1", []) + c2 = results.get("check2", []) + c3 = results.get("check3", []) + + # 汇总行 + summary = [ + {"检查项": "检查1:确认异常日期存在请假流程", "条数": len(c1)}, + {"检查项": "检查2:休息日半天加班打卡校验", "条数": len(c2)}, + {"检查项": "检查3:整日请假当日仍有考勤异常", "条数": len(c3)}, + ] + summary[1]["备注"] = "「判定」列中 漏打卡 需人工复核" + summary[0]["备注"] = "可能为「提前确认后请假」仍为异常" + + try: + with pd.ExcelWriter(save_path, engine="openpyxl") as writer: + pd.DataFrame(summary).to_excel(writer, sheet_name="汇总", index=False) + for sheet_name, key, cols in sheet_cfg: + data = results.get(key, []) + df = pd.DataFrame(data, columns=cols) + df.to_excel(writer, sheet_name=sheet_name, index=False) + except PermissionError: + raise RuntimeError( + f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试" + ) + logger.info("月考勤异常三查完成:检查1=%d 条,检查2=%d 条,检查3=%d 条", + len(c1), len(c2), len(c3)) + logger.info("文件已保存:%s", save_path) + return save_path + + +# ---------------------------------------------- +# 8. 对外便捷入口 +# ---------------------------------------------- +def handle_abnormal_check(save_dir: str = None, month: str = None) -> str: + """执行月考勤异常三项检查并导出 Excel 报告,返回导出文件路径。 + + Args: + save_dir: 保存目录,默认 SAVE_DIR + month: 查询月份 "YYYY-MM"(默认当月)。传该参数时查询整个月, + 不传则按「当月 1 日 至 今天」查询。 + """ + save_dir = save_dir or SAVE_DIR + session = build_hr_session() + session, user_id, treecode = _validate_session(session) + + if month: + begin = f"{month}-01" + end = f"{month}-31" + month_str = month + else: + begin, end = current_month_range() + month_str = date.today().strftime("%Y-%m") + + data = _fetch_all_data(session, user_id, treecode, begin, end) + + # 请假索引(全部请假,供检查1判断日期是否有请假流程) + leave_index = _build_leave_set(data["leaves"], need_full_day=False) + + # 检查1 + c1 = check_leave_after_confirm(data["abnormal_confirmed"], leave_index) + logger.info("检查1(确认异常有请假):命中 %d 条", len(c1)) + for r in c1: + logger.warning("【检查1】%s %s 考勤日期 %s,异常:%s,请假:%s", + r["员工姓名"], r["工号"], r["考勤日期"], r["异常类型"], r["请假类型"]) + + # 检查2 + c2 = check_rest_day_half_day_punch(session, user_id, treecode, + data["rest_overtime"], begin, end) + logger.info("检查2(休息日半天打卡):校验 %d 条", len(c2)) + for r in c2: + if "漏打卡" in r["判定"]: + logger.warning("【检查2】%s %s %s 加班半天,%s", + r["员工姓名"], r["工号"], r["加班日期"], r["判定"]) + + # 检查3 + c3 = check_full_day_leave_abnormal( + data["abnormal_confirmed"], data["abnormal_open"], data["leaves"]) + logger.info("检查3(整日请假有异常):命中 %d 条", len(c3)) + for r in c3: + logger.warning("【检查3】%s %s %s:%s(异常:%s / %s)", + r["员工姓名"], r["工号"], r["请假日期"], r["提示"], + r["异常类型"], r["异常状态"]) + + return export_report({"check1": c1, "check2": c2, "check3": c3}, save_dir, month_str) + + +def main() -> None: + setup_logging() + save_dir = sys.argv[1] if len(sys.argv) > 1 else SAVE_DIR + month = sys.argv[2] if len(sys.argv) > 2 else None + try: + out = handle_abnormal_check(save_dir, month) + logger.info("===== 月考勤异常三查完成,导出:%s =====", out) + except Exception as e: + if "正被占用" in str(e): + logger.error("=========== 提醒 ===========") + logger.error(str(e)) + logger.error("请关闭该 Excel 文件后重新运行即可,无需重查数据。") + return + logger.error("月考勤异常三查失败:%s", e) + raise + + +if __name__ == "__main__": + main() diff --git a/app/service/hrbp/ehr/attendance/attendance_abnormal.py b/app/service/hrbp/ehr/attendance/attendance_abnormal.py index 378b9cd..7fdb86f 100644 --- a/app/service/hrbp/ehr/attendance/attendance_abnormal.py +++ b/app/service/hrbp/ehr/attendance/attendance_abnormal.py @@ -18,7 +18,7 @@ import os import sys -from datetime import date +from datetime import date, datetime from pathlib import Path from typing import Dict, List @@ -43,7 +43,7 @@ from app.service.hrbp.ehr.common.hr_api import ( # noqa: E402 # adjust_abnormal, # 自动确认异常能力暂未启用,需要时取消注释 HRSessionExpiredError, ) -from app.service.hrbp.ehr.common.session_manager import ( # noqa: E402 +from app.service.hrbp.common.hr_session import ( # noqa: E402 build_hr_session, refresh_hr_session, ) @@ -75,6 +75,10 @@ SHOW_ORDER = [ "异常ID", "员工姓名", "工号", "考勤日期", "班次", "异常类型", "异常时长(分钟)", ] +# 考勤异常调整状态过滤(本次只查询「未调整」) +# 0=未调整、1=补签调整、2=确认异常、3=正常调整、空=所有状态 +IS_ADJUSTED = "0" + # ---------------------------------------------- # 1. 当月查询范围(每次默认查询当月) @@ -128,8 +132,15 @@ def export_excel(data: List[dict], save_dir: str, month_str: str) -> str: df = df[exist_cols + other_cols] os.makedirs(save_dir, exist_ok=True) - save_path = os.path.abspath(os.path.join(save_dir, f"考勤异常_{month_str}.xlsx")) - df.to_excel(save_path, index=False) + # 文件名加时间戳,避免同名文件被占用导致 PermissionError + ts = datetime.now().strftime("%Y%m%d_%H%M%S") + save_path = os.path.abspath(os.path.join(save_dir, f"考勤异常_{month_str}_{ts}.xlsx")) + try: + df.to_excel(save_path, index=False) + except PermissionError: + raise RuntimeError( + f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试" + ) logger.info("考勤异常数据:%d 条", len(data)) logger.info("文件已保存:%s", save_path) return save_path @@ -221,9 +232,12 @@ def _fetch_abnormal_data(month: str = None) -> tuple: else: begin, end = current_month_range() month_str = date.today().strftime("%Y-%m") - logger.info("===== 查询考勤异常日期范围:%s ~ %s =====", begin, end) + logger.info("===== 查询考勤异常日期范围:%s ~ %s,调整状态:%s =====", + begin, end, IS_ADJUSTED or "所有") - data = fetch_all_attendance_abnormal(session, user_id, treecode, begin, end) + data = fetch_all_attendance_abnormal( + session, user_id, treecode, begin, end, IS_ADJUSTED + ) return data, month_str @@ -315,6 +329,12 @@ def main() -> None: else: logger.info("===== 考勤异常处理完成:当月无数据 =====") except Exception as e: + if "正被占用" in str(e): + # 文件被 Excel 占用:只提醒关闭后重试,不抛堆栈 + logger.error("=========== 提醒 ===========") + logger.error(str(e)) + logger.error("请关闭该 Excel 文件后重新运行即可,无需重查数据。") + return logger.error("考勤异常处理失败:%s", e) raise diff --git a/app/service/hrbp/ehr/common/captcha_debug/bg_clean_0.png b/app/service/hrbp/ehr/common/captcha_debug/bg_clean_0.png deleted file mode 100644 index 9088376..0000000 Binary files a/app/service/hrbp/ehr/common/captcha_debug/bg_clean_0.png and /dev/null differ diff --git a/app/service/hrbp/ehr/common/captcha_debug/bg_clean_0_marked.png b/app/service/hrbp/ehr/common/captcha_debug/bg_clean_0_marked.png deleted file mode 100644 index 9c80fad..0000000 Binary files a/app/service/hrbp/ehr/common/captcha_debug/bg_clean_0_marked.png and /dev/null differ diff --git a/app/service/hrbp/ehr/common/captcha_debug/bg_clean_1.png b/app/service/hrbp/ehr/common/captcha_debug/bg_clean_1.png deleted file mode 100644 index 0bc63a1..0000000 Binary files a/app/service/hrbp/ehr/common/captcha_debug/bg_clean_1.png and /dev/null differ diff --git a/app/service/hrbp/ehr/common/captcha_debug/bg_clean_1_marked.png b/app/service/hrbp/ehr/common/captcha_debug/bg_clean_1_marked.png deleted file mode 100644 index c5b1055..0000000 Binary files a/app/service/hrbp/ehr/common/captcha_debug/bg_clean_1_marked.png and /dev/null differ diff --git a/app/service/hrbp/ehr/common/captcha_debug/bg_clean_2.png b/app/service/hrbp/ehr/common/captcha_debug/bg_clean_2.png deleted file mode 100644 index d024256..0000000 Binary files a/app/service/hrbp/ehr/common/captcha_debug/bg_clean_2.png and /dev/null differ diff --git a/app/service/hrbp/ehr/common/captcha_debug/bg_clean_2_marked.png b/app/service/hrbp/ehr/common/captcha_debug/bg_clean_2_marked.png deleted file mode 100644 index 475d8a3..0000000 Binary files a/app/service/hrbp/ehr/common/captcha_debug/bg_clean_2_marked.png and /dev/null differ diff --git a/app/service/hrbp/ehr/common/captcha_debug/bg_clean_3.png b/app/service/hrbp/ehr/common/captcha_debug/bg_clean_3.png deleted file mode 100644 index 92f8dce..0000000 Binary files a/app/service/hrbp/ehr/common/captcha_debug/bg_clean_3.png and /dev/null differ diff --git a/app/service/hrbp/ehr/common/captcha_debug/bg_clean_3_marked.png b/app/service/hrbp/ehr/common/captcha_debug/bg_clean_3_marked.png deleted file mode 100644 index bb1785b..0000000 Binary files a/app/service/hrbp/ehr/common/captcha_debug/bg_clean_3_marked.png and /dev/null differ diff --git a/app/service/hrbp/ehr/common/captcha_debug/slider_0.png b/app/service/hrbp/ehr/common/captcha_debug/slider_0.png deleted file mode 100644 index d5d159b..0000000 Binary files a/app/service/hrbp/ehr/common/captcha_debug/slider_0.png and /dev/null differ diff --git a/app/service/hrbp/ehr/common/captcha_debug/slider_1.png b/app/service/hrbp/ehr/common/captcha_debug/slider_1.png deleted file mode 100644 index d0d0b29..0000000 Binary files a/app/service/hrbp/ehr/common/captcha_debug/slider_1.png and /dev/null differ diff --git a/app/service/hrbp/ehr/common/captcha_debug/slider_2.png b/app/service/hrbp/ehr/common/captcha_debug/slider_2.png deleted file mode 100644 index 88c30aa..0000000 Binary files a/app/service/hrbp/ehr/common/captcha_debug/slider_2.png and /dev/null differ diff --git a/app/service/hrbp/ehr/common/captcha_debug/slider_3.png b/app/service/hrbp/ehr/common/captcha_debug/slider_3.png deleted file mode 100644 index 770959c..0000000 Binary files a/app/service/hrbp/ehr/common/captcha_debug/slider_3.png and /dev/null differ diff --git a/app/service/hrbp/ehr/common/config.py b/app/service/hrbp/ehr/common/config.py index ab31315..e1809ae 100644 --- a/app/service/hrbp/ehr/common/config.py +++ b/app/service/hrbp/ehr/common/config.py @@ -48,3 +48,10 @@ LEAVE_URL = "https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc" # 查询加班记录接口(aa.md 提供,用于过滤虚假异常) OVERTIME_URL = "https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc" + +# 查询打卡记录接口(aa.md 提供,sqlId=kq_data_query,按 base_code 工号查原始打卡流水) +KQ_DATA_URL = "https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc" + +# 假期类型编码映射已上移到 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 diff --git a/app/service/hrbp/ehr/common/hr_api.py b/app/service/hrbp/ehr/common/hr_api.py deleted file mode 100644 index e521ac8..0000000 --- a/app/service/hrbp/ehr/common/hr_api.py +++ /dev/null @@ -1,818 +0,0 @@ -# -*- coding: utf-8 -*- -""" -@Module: hrbp.ehr.common -@FileName: hr_api.py -@Author: 小布丁 -@CreateTime: 2026-08-05 23:52 -@Description: HR 系统 API 模块,负责调用系统接口(工资卡等),供各业务模块复用 -@Version: 2.0.0 -""" - -import json -import os -import time -from typing import Any, Dict, List - -from app.common.app_paths import get_sessions_dir -from app.utils.logger import get_logger -from app.service.hrbp.ehr.common.config import ( - WAGE_CARD_URL, - PAGE_MAX_SIZE, - GET_CUR_USER_INFO_URL, - ATTENDANCE_ABNORMAL_URL, - ATTENDANCE_ADJUST_URL, - SHIFT_URL, - LEAVE_URL, - OVERTIME_URL, - BANK_DICT_URL, - BANK_DICT_CODE_TYPE, - BANK_DICT_EXPIRE_SEC, -) -from app.service.hrbp.ehr.common.session_manager import build_hr_session - -logger = get_logger(__name__) - - -class HRSessionExpiredError(Exception): - """HR 登录态过期:接口返回登录页等非 JSON 内容。""" - - -def _is_expired(text) -> bool: - """接口正常情况下返回 JSON;返回登录页/错误页等非 JSON 即视为登录态过期。""" - return bool(text) and not text.lstrip().startswith(("{", "[")) - - -# ---------- 银行卡(工资卡)信息查询接口 ---------- -def fetch_wage_card_page( - session, - status: int, - page_no: int = 1, - page_size: int = PAGE_MAX_SIZE, - leave_start: str = None, - leave_end: str = None, -) -> Dict[str, Any]: - """ - 请求单页工资卡数据。 - - Args: - session: 已登录的 requests.Session 对象 - status: 人员状态,1=在职 / 2=离职 - page_no: 页码(从 1 开始) - page_size: 每页条数 - leave_start / leave_end: 离职筛选时间范围 "YYYY-MM-DD"(status=2 时必填) - - Returns: - 接口返回的 JSON 字典 - - Raises: - RuntimeError: 请求失败或响应异常 - HRSessionExpiredError: 登录态过期(接口返回非 JSON) - """ - params = { - "start": (page_no - 1) * page_size, - "pageNo": page_no, - "pageSize": page_size, - "ftl_list_STRU_TREE_CODE": "cq37du", - "sortName": "hr_staff_wage_card.STAFF_NAME", - "sortType": "asc", - "commonQuery": "[]", - "person_status": status, - } - # 在职、离职参数区分 - if status == 1: - params["leaveOffice_date"] = "" - elif leave_start and leave_end: - params["leaveOffice_date[0]"] = leave_start - params["leaveOffice_date[1]"] = leave_end - params["leaveOffice_date_start"] = leave_start - params["leaveOffice_date_end"] = leave_end - - resp = session.post(WAGE_CARD_URL, data=params, timeout=20) - if not resp: - raise RuntimeError("工资卡请求失败,未获取到响应") - if resp.status_code != 200: - raise RuntimeError(f"工资卡接口状态码异常: {resp.status_code}") - if _is_expired(resp.text): - raise HRSessionExpiredError("HR 登录态已过期,接口返回非 JSON 内容") - try: - return resp.json() - except Exception: - body = (resp.text or "")[:200] - raise RuntimeError(f"工资卡接口返回非 JSON 数据(状态码 {resp.status_code}): {body}") - - -def fetch_all_wage_card( - session, - status: int, - status_name: str, - leave_start: str = None, - leave_end: str = None, -) -> List[Dict[str, Any]]: - """ - 分页抓取指定人员类型(在职/离职)的全部工资卡数据。 - - Args: - session: 已登录的 requests.Session 对象 - status: 人员状态,1=在职 / 2=离职 - status_name: 人员类型文字(用于日志与数据标记) - leave_start / leave_end: 离职筛选时间范围(status=2 时必填) - - Returns: - 数据行列表(每条已附加「人员类型」字段) - """ - all_rows: List[Dict[str, Any]] = [] - page_no = 1 - while True: - try: - data = fetch_wage_card_page(session, status, page_no, PAGE_MAX_SIZE, leave_start, leave_end) - except HRSessionExpiredError: - logger.warning("【%s】HR 登录态过期,重新登录后续抓", status_name) - from app.service.hrbp.ehr.common.session_manager import refresh_hr_session - session = refresh_hr_session() - data = fetch_wage_card_page(session, status, page_no, PAGE_MAX_SIZE, leave_start, leave_end) - - if data.get("state") != "1": - logger.error("【%s】第%d页请求失败:%s", status_name, page_no, data.get("meg")) - break - - page_list = data.get("datas", []) or [] - if not page_list: - logger.info("【%s】无更多数据", status_name) - break - - # 给每条数据增加人员类型标识 - for item in page_list: - item["人员类型"] = status_name - all_rows.extend(page_list) - - total = data.get("count", 0) - total_page = data.get("pageCount", 0) - logger.info("【%s】已抓取 %d/%d 页,累计 %d/%d 条", - status_name, page_no, total_page, len(all_rows), total) - if page_no >= total_page: - break - page_no += 1 - time.sleep(0.2) # 轻微限速,避免触发风控 - return all_rows - - -# ---------- 银行字典接口(aa.md 提供,按 BANK_TYPE 匹配 code -> 开卡银行) ---------- -# 缓存文件统一放在 AppData\Local\37duAutomation\.sessions 目录 -_BANK_DICT_CACHE_DIR = get_sessions_dir() -BANK_DICT_LIST_FILE = os.path.join(_BANK_DICT_CACHE_DIR, "bank_dict_list.json") -BANK_DICT_MAP_FILE = os.path.join(_BANK_DICT_CACHE_DIR, "bank_dict_map.json") - - -def _fetch_bank_dict(session=None): - """远程调用接口获取银行字典,并写入本地缓存。 - - Returns: - (list[dict], dict[code->name]) - """ - if session is None: - session = build_hr_session() - payload = { - "codeType": BANK_DICT_CODE_TYPE, - "inUse": "0,1,2", - "platformMode": "redseaPlatform", - } - resp = session.post(BANK_DICT_URL, data=payload, timeout=30) - if not resp: - raise RuntimeError("银行字典请求失败,未获取到响应") - if resp.status_code != 200: - raise RuntimeError(f"银行字典接口状态码异常: {resp.status_code}") - if _is_expired(resp.text): - raise HRSessionExpiredError("HR 登录态已过期,银行字典接口返回非 JSON 内容") - resp_json = resp.json() - raw_list = resp_json.get(BANK_DICT_CODE_TYPE) or [] - result_list = [{"code": str(item.get("code", "")), "name": item.get("name", "")} - for item in raw_list] - result_map = {item["code"]: item["name"] for item in result_list} - - os.makedirs(_BANK_DICT_CACHE_DIR, exist_ok=True) - with open(BANK_DICT_LIST_FILE, "w", encoding="utf-8") as f: - json.dump(result_list, f, ensure_ascii=False, indent=2) - with open(BANK_DICT_MAP_FILE, "w", encoding="utf-8") as f: - json.dump(result_map, f, ensure_ascii=False, indent=2) - logger.info("银行字典远程拉取完成,共 %d 条", len(result_list)) - return result_list, result_map - - -def _load_bank_dict_cache(): - """读取本地银行字典缓存,失败返回 (None, None)。""" - try: - with open(BANK_DICT_LIST_FILE, "r", encoding="utf-8") as f: - lst = json.load(f) - with open(BANK_DICT_MAP_FILE, "r", encoding="utf-8") as f: - mp = json.load(f) - return lst, mp - except Exception as e: - logger.warning("银行字典本地缓存读取失败:%s", e) - return None, None - - -def get_bank_dict(session=None, force_refresh: bool = False): - """获取银行字典(优先本地缓存,过期/强制刷新才请求接口)。 - - Args: - session: 可选的已登录 requests.Session;未提供时自动构建 - force_refresh: True 强制重新调用接口 - - Returns: - (list版本, dict[code->name]版本) - """ - need_refresh = force_refresh - if not (os.path.exists(BANK_DICT_LIST_FILE) and os.path.exists(BANK_DICT_MAP_FILE)): - need_refresh = True - else: - mtime = os.path.getmtime(BANK_DICT_LIST_FILE) - if time.time() - mtime > BANK_DICT_EXPIRE_SEC: - need_refresh = True - - if need_refresh: - try: - return _fetch_bank_dict(session) - except Exception as e: - logger.error("银行字典远程拉取失败:%s", e) - lst, mp = _load_bank_dict_cache() - if lst is not None: - logger.warning("降级使用本地银行字典缓存,共 %d 条", len(lst)) - return lst, mp - return [], {} - - lst, mp = _load_bank_dict_cache() - if lst is None: - # 缓存异常时重新拉取 - return _fetch_bank_dict(session) - logger.info("读取本地银行字典缓存,共 %d 条", len(lst)) - return lst, mp - - -def bank_type_to_name(bank_type, bank_map) -> str: - """按银行编码(BANK_TYPE)匹配字典 code,返回开卡银行;未命中返回空串。""" - if bank_type is None: - return "" - if isinstance(bank_type, float): - if bank_type != bank_type: # NaN - return "" - bank_type = str(int(bank_type)) - elif isinstance(bank_type, int): - bank_type = str(bank_type) - else: - bank_type = str(bank_type).strip() - return bank_map.get(bank_type, "") - - -def adjust_abnormal( - session, - abnormal_ids, - type_code: int = 1, -) -> Dict[str, Any]: - """ - 确认/调整考勤异常单据。 - - Args: - session: 已登录的 requests.Session 对象 - abnormal_ids: 异常单据唯一编号 abnormal_id,可为单个 id 或 id 列表 - type_code: 处理类型,1=自动确认异常(按接口约定) - - Returns: - 接口返回的 JSON 字典(state=1 表示处理成功) - - Raises: - RuntimeError: 请求失败或响应异常 - HRSessionExpiredError: 登录态过期(接口返回非 JSON) - """ - if isinstance(abnormal_ids, (list, tuple)): - ids = ",".join(str(i) for i in abnormal_ids) - else: - ids = str(abnormal_ids) - - params = {"abnormalIds": ids, "type": type_code} - resp = session.post(ATTENDANCE_ADJUST_URL, data=params, timeout=20) - if not resp: - raise RuntimeError("考勤异常确认请求失败,未获取到响应") - if resp.status_code != 200: - raise RuntimeError(f"考勤异常确认接口状态码异常: {resp.status_code}") - if _is_expired(resp.text): - raise HRSessionExpiredError("HR 登录态已过期,考勤异常确认接口返回非 JSON 内容") - try: - return resp.json() - except Exception: - body = (resp.text or "")[:200] - raise RuntimeError(f"考勤异常确认接口返回非 JSON 数据(状态码 {resp.status_code}): {body}") - - -# ---------- 考勤异常查询接口 ---------- -def fetch_cur_user_info(session) -> Dict[str, Any]: - """ - 调用 getCurUserInfo 校验 cookies 有效性,并返回当前登录用户信息。 - - 该接口同时返回查询考勤异常所需的 userId 与 rootId(treecode): - - 正常返回 JSON(含 userId / rootId),说明 cookies 有效; - - 返回登录页等非 JSON 内容,说明登录态过期。 - - Returns: - 接口返回的 JSON 字典(含 userId / rootId 等字段) - - Raises: - RuntimeError: 请求失败或响应异常 - HRSessionExpiredError: 登录态过期(接口返回非 JSON) - """ - resp = session.post(GET_CUR_USER_INFO_URL, timeout=20) - if not resp: - raise RuntimeError("获取当前用户信息失败,未获取到响应") - if resp.status_code != 200: - raise RuntimeError(f"获取当前用户信息状态码异常: {resp.status_code}") - if _is_expired(resp.text): - raise HRSessionExpiredError("HR 登录态已过期,getCurUserInfo 接口返回非 JSON 内容") - try: - return resp.json() - except Exception: - body = (resp.text or "")[:200] - raise RuntimeError(f"获取当前用户信息返回非 JSON 数据(状态码 {resp.status_code}): {body}") - - -def fetch_attendance_abnormal_page( - session, - user_id: str, - treecode: str, - begin_date: str, - end_date: str, - page_no: int = 1, - page_size: int = PAGE_MAX_SIZE, -) -> Dict[str, Any]: - """ - 请求单页考勤异常数据(aa.md 提供的接口入参)。 - - Args: - session: 已登录的 requests.Session 对象 - user_id / treecode: 由 getCurUserInfo 返回的 userId / rootId - begin_date / end_date: 查询日期范围 "YYYY-MM-DD"(当月) - page_no: 页码(从 1 开始) - page_size: 每页条数 - - Returns: - 接口返回的 JSON 字典(datas 为明细数组,pageCount 为总页数) - - Raises: - RuntimeError: 请求失败或响应异常 - HRSessionExpiredError: 登录态过期(接口返回非 JSON) - """ - params = { - "treecode": treecode, - "user_id": user_id, - "commonQuery": "", - "commonQueryStr": "", - "sqlId": "kq_count_abnormal_Select", - "redapiId": "rf_p_kq_count_abnormal_Select", - "treeCodeList": "", - "abnormal_type": "", - "base_code": "", - "join_date": "", - "join_date_end": end_date, - "person_status": "", - "staff_id": "", - "post_no": "", - "post_type": "1", - "period_order": "", - "identity_test": "", - "identity": "", - "sex": "", - "age": "", - "age_end": "", - "start_operat_time": "", - "end_operat_time": "", - "operator_username": "", - "operator_userid": "", - "is_adjusted": "", - "begin_date": begin_date, - "end_date": end_date, - "STAFF_NAME": "", - "start": str((page_no - 1) * page_size), - "sortType": "desc", - "sortName": "work_day", - "pageNo": page_no, - "pageSize": page_size, - } - resp = session.post(ATTENDANCE_ABNORMAL_URL, data=params, timeout=20) - if not resp: - raise RuntimeError("考勤异常请求失败,未获取到响应") - if resp.status_code != 200: - raise RuntimeError(f"考勤异常接口状态码异常: {resp.status_code}") - if _is_expired(resp.text): - raise HRSessionExpiredError("HR 登录态已过期,考勤异常接口返回非 JSON 内容") - try: - return resp.json() - except Exception: - body = (resp.text or "")[:200] - raise RuntimeError(f"考勤异常接口返回非 JSON 数据(状态码 {resp.status_code}): {body}") - - -def fetch_all_attendance_abnormal( - session, - user_id: str, - treecode: str, - begin_date: str, - end_date: str, -) -> List[Dict[str, Any]]: - """ - 分页抓取指定日期范围内的全部考勤异常数据。 - - Args: - session: 已登录的 requests.Session 对象 - user_id / treecode: 由 getCurUserInfo 返回的 userId / rootId - begin_date / end_date: 查询日期范围 "YYYY-MM-DD" - - Returns: - 异常明细列表(接口 datas 字段内容) - - Raises: - HRSessionExpiredError: 登录态过期且重新登录后仍失败 - """ - all_rows: List[Dict[str, Any]] = [] - page_no = 1 - while True: - try: - data = fetch_attendance_abnormal_page( - session, user_id, treecode, begin_date, end_date, page_no, PAGE_MAX_SIZE - ) - except HRSessionExpiredError: - logger.warning("考勤异常 HR 登录态过期,重新登录后续抓") - from app.service.hrbp.ehr.common.session_manager import refresh_hr_session - session = refresh_hr_session() - # 重新登录后需重新获取 user_id / treecode - info = fetch_cur_user_info(session) - user_id = info.get("userId", "") - treecode = info.get("rootId", "") - data = fetch_attendance_abnormal_page( - session, user_id, treecode, begin_date, end_date, page_no, PAGE_MAX_SIZE - ) - - if data.get("state") != "1": - logger.error("考勤异常第%d页请求失败:%s", page_no, data.get("meg")) - break - - page_list = data.get("datas", []) or [] - if not page_list: - logger.info("考勤异常无更多数据") - break - - all_rows.extend(page_list) - - total_page = data.get("pageCount", 0) - logger.info("考勤异常已抓取 %d/%d 页,累计 %d 条", - page_no, total_page, len(all_rows)) - if page_no >= total_page: - break - page_no += 1 - time.sleep(0.2) # 轻微限速,避免触发风控 - return all_rows - - -# ---------- 查询排班接口(用于过滤虚假异常,暂未在主流程调用) ---------- -def fetch_shift_page( - session, - user_id: str, - base_code: str, - begin_date: str, - end_date: str, - treecode: str = "cq37du", - page_no: int = 1, - page_size: int = PAGE_MAX_SIZE, -) -> Dict[str, Any]: - """ - 请求单页排班数据(aa.md 提供的接口入参)。 - - Args: - session: 已登录的 requests.Session 对象 - user_id: 由 getCurUserInfo 返回的 userId - base_code: 员工工号 - begin_date / end_date: 查询日期范围 "YYYY-MM-DD" - treecode: 组织树编码,默认 cq37du - page_no / page_size: 分页参数 - - Returns: - 接口返回的 JSON 字典(datas 为排班明细数组) - """ - params = { - "treecode": treecode, - "user_id": user_id, - "sqlId": "kq_count_SelectBanci", - "commonQuery": "", - "commonQueryStr": "", - "staff_ids": "", - "person_status": "1,4", - "post_no": "", - "post_type": "1", - "post_level": "", - "identity": "", - "showType": "1", - "dateType": "2", - "begin": begin_date, - "end": end_date, - "bc_date": begin_date, - "base_code": base_code, - "staff_name": "", - "start": str((page_no - 1) * page_size), - "sortType": "", - "sortName": "", - "pageNo": page_no, - "pageSize": page_size, - } - resp = session.post(SHIFT_URL, data=params, timeout=20) - if not resp: - raise RuntimeError("排班请求失败,未获取到响应") - if resp.status_code != 200: - raise RuntimeError(f"排班接口状态码异常: {resp.status_code}") - if _is_expired(resp.text): - raise HRSessionExpiredError("HR 登录态已过期,排班接口返回非 JSON 内容") - try: - return resp.json() - except Exception: - body = (resp.text or "")[:200] - raise RuntimeError(f"排班接口返回非 JSON 数据(状态码 {resp.status_code}): {body}") - - -def fetch_all_shift( - session, - user_id: str, - base_code: str, - begin_date: str, - end_date: str, - treecode: str = "cq37du", -) -> List[Dict[str, Any]]: - """分页抓取指定工号、日期范围内的全部排班数据。""" - all_rows: List[Dict[str, Any]] = [] - page_no = 1 - while True: - try: - data = fetch_shift_page( - session, user_id, base_code, begin_date, end_date, - treecode, page_no, PAGE_MAX_SIZE, - ) - except HRSessionExpiredError: - logger.warning("排班 HR 登录态过期,重新登录后续抓") - from app.service.hrbp.ehr.common.session_manager import refresh_hr_session - session = refresh_hr_session() - info = fetch_cur_user_info(session) - user_id = info.get("userId", "") - data = fetch_shift_page( - session, user_id, base_code, begin_date, end_date, - treecode, page_no, PAGE_MAX_SIZE, - ) - - if data.get("state") != "1": - logger.error("排班第%d页请求失败:%s", page_no, data.get("meg")) - break - - page_list = data.get("datas", []) or [] - if not page_list: - logger.info("排班无更多数据") - break - - all_rows.extend(page_list) - - total_page = data.get("pageCount", 0) - logger.info("排班已抓取 %d/%d 页,累计 %d 条", - page_no, total_page, len(all_rows)) - if page_no >= total_page: - break - page_no += 1 - time.sleep(0.2) - return all_rows - - -# ---------- 查询请假记录接口(用于过滤虚假异常,暂未在主流程调用) ---------- -def fetch_leave_page( - session, - user_id: str, - base_code: str, - start_time: str, - end_time: str, - treecode: str = "cq37du", - page_no: int = 1, - page_size: int = PAGE_MAX_SIZE, -) -> Dict[str, Any]: - """ - 请求单页请假记录数据(aa.md 提供的接口入参)。 - - Args: - session: 已登录的 requests.Session 对象 - user_id: 由 getCurUserInfo 返回的 userId - base_code: 员工工号 - start_time / end_time: 查询日期范围 "YYYY-MM-DD" - treecode: 组织树编码,默认 cq37du - page_no / page_size: 分页参数 - - Returns: - 接口返回的 JSON 字典(datas 为请假记录数组) - """ - params = { - "STRU_TREE_CODE": treecode, - "user_id": user_id, - "begin_date": "", - "end_date": "", - "sqlId": "select_kqLeave_record", - "commonQuery": "", - "commonQueryStr": "", - "post_no": "", - "source": "", - "person_status": "", - "staff_id": "", - "staffNames": "", - "post_type": "1", - "processing_reason": "", - "processing_date": "", - "start_operat_time": "", - "end_operat_time": "", - "orgAlias": "", - "dept_ids": "", - "base_code": base_code, - "staff_name": "", - "start_time": start_time, - "end_time": end_time, - "start": str((page_no - 1) * page_size), - "sortType": "desc", - "sortName": "operat_time", - "pageNo": page_no, - "pageSize": page_size, - } - resp = session.post(LEAVE_URL, data=params, timeout=20) - if not resp: - raise RuntimeError("请假查询请求失败,未获取到响应") - if resp.status_code != 200: - raise RuntimeError(f"请假查询接口状态码异常: {resp.status_code}") - if _is_expired(resp.text): - raise HRSessionExpiredError("HR 登录态已过期,请假查询接口返回非 JSON 内容") - try: - return resp.json() - except Exception: - body = (resp.text or "")[:200] - raise RuntimeError(f"请假查询接口返回非 JSON 数据(状态码 {resp.status_code}): {body}") - - -def fetch_all_leave( - session, - user_id: str, - base_code: str, - start_time: str, - end_time: str, - treecode: str = "cq37du", -) -> List[Dict[str, Any]]: - """分页抓取指定工号、日期范围内的全部请假记录。""" - all_rows: List[Dict[str, Any]] = [] - page_no = 1 - while True: - try: - data = fetch_leave_page( - session, user_id, base_code, start_time, end_time, - treecode, page_no, PAGE_MAX_SIZE, - ) - except HRSessionExpiredError: - logger.warning("请假查询 HR 登录态过期,重新登录后续抓") - from app.service.hrbp.ehr.common.session_manager import refresh_hr_session - session = refresh_hr_session() - info = fetch_cur_user_info(session) - user_id = info.get("userId", "") - data = fetch_leave_page( - session, user_id, base_code, start_time, end_time, - treecode, page_no, PAGE_MAX_SIZE, - ) - - if data.get("state") != "1": - logger.error("请假查询第%d页请求失败:%s", page_no, data.get("meg")) - break - - page_list = data.get("datas", []) or [] - if not page_list: - logger.info("请假查询无更多数据") - break - - all_rows.extend(page_list) - - total_page = data.get("pageCount", 0) - logger.info("请假查询已抓取 %d/%d 页,累计 %d 条", - page_no, total_page, len(all_rows)) - if page_no >= total_page: - break - page_no += 1 - time.sleep(0.2) - return all_rows - - -# ---------- 查询加班记录接口(用于过滤虚假异常,暂未在主流程调用) ---------- -def fetch_overtime_page( - session, - user_id: str, - base_code: str, - start_time: str, - end_time: str, - treecode: str = "cq37du", - page_no: int = 1, - page_size: int = PAGE_MAX_SIZE, -) -> Dict[str, Any]: - """ - 请求单页加班记录数据(aa.md 提供的接口入参)。 - - Args: - session: 已登录的 requests.Session 对象 - user_id: 由 getCurUserInfo 返回的 userId - base_code: 员工工号 - start_time / end_time: 查询日期范围 "YYYY-MM-DD" - treecode: 组织树编码,默认 cq37du - page_no / page_size: 分页参数 - - Returns: - 接口返回的 JSON 字典(datas 为加班记录数组) - """ - params = { - "STRU_TREE_CODE": treecode, - "user_id": user_id, - "sqlId": "kq_overtime_detail_select", - "commonQuery": "", - "commonQueryStr": "", - "BPM_STATUS": "", - "post_no": "", - "postName": "", - "source": "", - "IS_SUBSIDY": "", - "person_status": "", - "staff_id": "", - "staffNames": "", - "post_type": "1", - "processing_reason": "", - "start_operat_time": "", - "end_operat_time": "", - "base_code": base_code, - "staff_name": "", - "WORK_OVERTIME_TYPE": "", - "start_time": start_time, - "end_time": end_time, - "start": str((page_no - 1) * page_size), - "sortType": "desc", - "sortName": "OPERATE_TIME", - "pageNo": page_no, - "pageSize": page_size, - } - resp = session.post(OVERTIME_URL, data=params, timeout=20) - if not resp: - raise RuntimeError("加班查询请求失败,未获取到响应") - if resp.status_code != 200: - raise RuntimeError(f"加班查询接口状态码异常: {resp.status_code}") - if _is_expired(resp.text): - raise HRSessionExpiredError("HR 登录态已过期,加班查询接口返回非 JSON 内容") - try: - return resp.json() - except Exception: - body = (resp.text or "")[:200] - raise RuntimeError(f"加班查询接口返回非 JSON 数据(状态码 {resp.status_code}): {body}") - - -def fetch_all_overtime( - session, - user_id: str, - base_code: str, - start_time: str, - end_time: str, - treecode: str = "cq37du", -) -> List[Dict[str, Any]]: - """分页抓取指定工号、日期范围内的全部加班记录。""" - all_rows: List[Dict[str, Any]] = [] - page_no = 1 - while True: - try: - data = fetch_overtime_page( - session, user_id, base_code, start_time, end_time, - treecode, page_no, PAGE_MAX_SIZE, - ) - except HRSessionExpiredError: - logger.warning("加班查询 HR 登录态过期,重新登录后续抓") - from app.service.hrbp.ehr.common.session_manager import refresh_hr_session - session = refresh_hr_session() - info = fetch_cur_user_info(session) - user_id = info.get("userId", "") - data = fetch_overtime_page( - session, user_id, base_code, start_time, end_time, - treecode, page_no, PAGE_MAX_SIZE, - ) - - if data.get("state") != "1": - logger.error("加班查询第%d页请求失败:%s", page_no, data.get("meg")) - break - - page_list = data.get("datas", []) or [] - if not page_list: - logger.info("加班查询无更多数据") - break - - all_rows.extend(page_list) - - total_page = data.get("pageCount", 0) - logger.info("加班查询已抓取 %d/%d 页,累计 %d 条", - page_no, total_page, len(all_rows)) - if page_no >= total_page: - break - page_no += 1 - time.sleep(0.2) - return all_rows diff --git a/app/service/hrbp/ehr/common/hr_api/__init__.py b/app/service/hrbp/ehr/common/hr_api/__init__.py new file mode 100644 index 0000000..0cc7a4e --- /dev/null +++ b/app/service/hrbp/ehr/common/hr_api/__init__.py @@ -0,0 +1,51 @@ +# -*- 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 +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 + +__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", + # leave + "fetch_leave_page", + "fetch_all_leave", + # overtime + "fetch_overtime_page", + "fetch_all_overtime", + # kq_data + "fetch_kq_data_page", + "fetch_all_kq_data", +] diff --git a/app/service/hrbp/ehr/common/hr_api/attendance.py b/app/service/hrbp/ehr/common/hr_api/attendance.py new file mode 100644 index 0000000..0680fb0 --- /dev/null +++ b/app/service/hrbp/ehr/common/hr_api/attendance.py @@ -0,0 +1,202 @@ +# -*- coding: utf-8 -*- +""" +@Module: hrbp.ehr.common.hr_api +@FileName: attendance.py +@Description: 当前用户信息 + 考勤异常查询/确认接口 +@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 ( + GET_CUR_USER_INFO_URL, + ATTENDANCE_ABNORMAL_URL, + ATTENDANCE_ADJUST_URL, + PAGE_MAX_SIZE, +) +from app.service.hrbp.common.hr_session import HRSessionExpiredError, hr_request_json + +logger = get_logger(__name__) + + +def fetch_cur_user_info(session) -> Dict[str, Any]: + """ + 调用 getCurUserInfo 校验 cookies 有效性,并返回当前登录用户信息。 + + 该接口同时返回查询考勤异常所需的 userId 与 rootId(treecode): + - 正常返回 JSON(含 userId / rootId),说明 cookies 有效; + - 返回登录页等非 JSON 内容,说明登录态过期。 + + Returns: + 接口返回的 JSON 字典(含 userId / rootId 等字段) + + Raises: + RuntimeError: 请求失败或响应异常 + HRSessionExpiredError: 登录态过期(接口返回非 JSON) + """ + return hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息") + + +def adjust_abnormal( + session, + abnormal_ids, + type_code: int = 1, +) -> Dict[str, Any]: + """ + 确认/调整考勤异常单据。 + + Args: + session: 已登录的 requests.Session 对象 + abnormal_ids: 异常单据唯一编号 abnormal_id,可为单个 id 或 id 列表 + type_code: 处理类型,1=自动确认异常(按接口约定) + + Returns: + 接口返回的 JSON 字典(state=1 表示处理成功) + + Raises: + RuntimeError: 请求失败或响应异常 + HRSessionExpiredError: 登录态过期(接口返回非 JSON) + """ + if isinstance(abnormal_ids, (list, tuple)): + ids = ",".join(str(i) for i in abnormal_ids) + else: + ids = str(abnormal_ids) + + params = {"abnormalIds": ids, "type": type_code} + return hr_request_json(session, "POST", ATTENDANCE_ADJUST_URL, params, "考勤异常确认") + + +def fetch_attendance_abnormal_page( + session, + user_id: str, + treecode: str, + begin_date: str, + end_date: str, + page_no: int = 1, + page_size: int = PAGE_MAX_SIZE, + is_adjusted: str = "0", + abnormal_type: str = "", +) -> Dict[str, Any]: + """ + 请求单页考勤异常数据(aa.md 提供的接口入参)。 + + Args: + session: 已登录的 requests.Session 对象 + user_id / treecode: 由 getCurUserInfo 返回的 userId / rootId + begin_date / end_date: 查询日期范围 "YYYY-MM-DD"(当月) + page_no: 页码(从 1 开始) + page_size: 每页条数 + is_adjusted: 调整状态过滤,0=未调整、1=补签调整、2=确认异常、3=正常调整、空=所有状态 + abnormal_type: 异常类型过滤,2=旷工类(旷工/上班旷工/下班旷工),空=全部 + + Returns: + 接口返回的 JSON 字典(datas 为明细数组,pageCount 为总页数) + + Raises: + RuntimeError: 请求失败或响应异常 + HRSessionExpiredError: 登录态过期(接口返回非 JSON) + """ + params = { + "treecode": treecode, + "user_id": user_id, + "commonQuery": "", + "commonQueryStr": "", + "sqlId": "kq_count_abnormal_Select", + "redapiId": "rf_p_kq_count_abnormal_Select", + "treeCodeList": "", + "abnormal_type": abnormal_type, + "base_code": "", + "join_date": "", + "join_date_end": end_date, + "person_status": "", + "staff_id": "", + "post_no": "", + "post_type": "1", + "period_order": "", + "identity_test": "", + "identity": "", + "sex": "", + "age": "", + "age_end": "", + "start_operat_time": "", + "end_operat_time": "", + "operator_username": "", + "operator_userid": "", + "is_adjusted": is_adjusted, + "begin_date": begin_date, + "end_date": end_date, + "STAFF_NAME": "", + "start": str((page_no - 1) * page_size), + "sortType": "desc", + "sortName": "work_day", + "pageNo": page_no, + "pageSize": page_size, + } + return hr_request_json(session, "POST", ATTENDANCE_ABNORMAL_URL, params, "考勤异常") + + +def fetch_all_attendance_abnormal( + session, + user_id: str, + treecode: str, + begin_date: str, + end_date: str, + is_adjusted: str = "0", + abnormal_type: str = "", +) -> List[Dict[str, Any]]: + """ + 分页抓取指定日期范围内的全部考勤异常数据。 + + Args: + session: 已登录的 requests.Session 对象 + user_id / treecode: 由 getCurUserInfo 返回的 userId / rootId + begin_date / end_date: 查询日期范围 "YYYY-MM-DD" + is_adjusted: 调整状态过滤,0=未调整、1=补签调整、2=确认异常、3=正常调整、空=所有状态 + abnormal_type: 异常类型过滤,2=旷工类(旷工/上班旷工/下班旷工),空=全部 + + Returns: + 异常明细列表(接口 datas 字段内容) + + Raises: + HRSessionExpiredError: 登录态过期且重新登录后仍失败 + """ + all_rows: List[Dict[str, Any]] = [] + page_no = 1 + while True: + try: + data = fetch_attendance_abnormal_page( + session, user_id, treecode, begin_date, end_date, page_no, PAGE_MAX_SIZE, is_adjusted, abnormal_type + ) + except HRSessionExpiredError: + logger.warning("考勤异常 HR 登录态过期,重新登录后续抓") + from app.service.hrbp.common.hr_session import refresh_hr_session + session = refresh_hr_session() + # 重新登录后需重新获取 user_id / treecode + info = fetch_cur_user_info(session) + user_id = info.get("userId", "") + treecode = info.get("rootId", "") + data = fetch_attendance_abnormal_page( + session, user_id, treecode, begin_date, end_date, page_no, PAGE_MAX_SIZE, is_adjusted, abnormal_type + ) + + 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 diff --git a/app/service/hrbp/ehr/common/hr_api/bank_dict.py b/app/service/hrbp/ehr/common/hr_api/bank_dict.py new file mode 100644 index 0000000..f540553 --- /dev/null +++ b/app/service/hrbp/ehr/common/hr_api/bank_dict.py @@ -0,0 +1,121 @@ +# -*- coding: utf-8 -*- +""" +@Module: hrbp.ehr.common.hr_api +@FileName: bank_dict.py +@Description: 银行字典接口(缓存 code -> 开卡银行 映射) +@Version: 1.0.0 +""" + +import json +import os +import time + +from app.common.app_paths import get_sessions_dir +from app.utils.logger import get_logger +from app.service.hrbp.ehr.common.config import ( + BANK_DICT_URL, + BANK_DICT_CODE_TYPE, + BANK_DICT_EXPIRE_SEC, +) +from app.service.hrbp.common.hr_session import HRSessionExpiredError, hr_request_json +from app.service.hrbp.common.hr_session import build_hr_session + +logger = get_logger(__name__) + +# 缓存文件统一放在 AppData\Local\37duAutomation\.sessions 目录 +_BANK_DICT_CACHE_DIR = get_sessions_dir() +BANK_DICT_LIST_FILE = os.path.join(_BANK_DICT_CACHE_DIR, "bank_dict_list.json") +BANK_DICT_MAP_FILE = os.path.join(_BANK_DICT_CACHE_DIR, "bank_dict_map.json") + + +def _fetch_bank_dict(session=None): + """远程调用接口获取银行字典,并写入本地缓存。 + + Returns: + (list[dict], dict[code->name]) + """ + if session is None: + session = build_hr_session() + payload = { + "codeType": BANK_DICT_CODE_TYPE, + "inUse": "0,1,2", + "platformMode": "redseaPlatform", + } + resp_json = hr_request_json(session, "POST", BANK_DICT_URL, payload, "银行字典", timeout=30) + raw_list = resp_json.get(BANK_DICT_CODE_TYPE) or [] + result_list = [{"code": str(item.get("code", "")), "name": item.get("name", "")} + for item in raw_list] + result_map = {item["code"]: item["name"] for item in result_list} + + os.makedirs(_BANK_DICT_CACHE_DIR, exist_ok=True) + with open(BANK_DICT_LIST_FILE, "w", encoding="utf-8") as f: + json.dump(result_list, f, ensure_ascii=False, indent=2) + with open(BANK_DICT_MAP_FILE, "w", encoding="utf-8") as f: + json.dump(result_map, f, ensure_ascii=False, indent=2) + logger.info("银行字典远程拉取完成,共 %d 条", len(result_list)) + return result_list, result_map + + +def _load_bank_dict_cache(): + """读取本地银行字典缓存,失败返回 (None, None)。""" + try: + with open(BANK_DICT_LIST_FILE, "r", encoding="utf-8") as f: + lst = json.load(f) + with open(BANK_DICT_MAP_FILE, "r", encoding="utf-8") as f: + mp = json.load(f) + return lst, mp + except Exception as e: + logger.warning("银行字典本地缓存读取失败:%s", e) + return None, None + + +def get_bank_dict(session=None, force_refresh: bool = False): + """获取银行字典(优先本地缓存,过期/强制刷新才请求接口)。 + + Args: + session: 可选的已登录 requests.Session;未提供时自动构建 + force_refresh: True 强制重新调用接口 + + Returns: + (list版本, dict[code->name]版本) + """ + need_refresh = force_refresh + if not (os.path.exists(BANK_DICT_LIST_FILE) and os.path.exists(BANK_DICT_MAP_FILE)): + need_refresh = True + else: + mtime = os.path.getmtime(BANK_DICT_LIST_FILE) + if time.time() - mtime > BANK_DICT_EXPIRE_SEC: + need_refresh = True + + if need_refresh: + try: + return _fetch_bank_dict(session) + except Exception as e: + logger.error("银行字典远程拉取失败:%s", e) + lst, mp = _load_bank_dict_cache() + if lst is not None: + logger.warning("降级使用本地银行字典缓存,共 %d 条", len(lst)) + return lst, mp + return [], {} + + lst, mp = _load_bank_dict_cache() + if lst is None: + # 缓存异常时重新拉取 + return _fetch_bank_dict(session) + logger.info("读取本地银行字典缓存,共 %d 条", len(lst)) + return lst, mp + + +def bank_type_to_name(bank_type, bank_map) -> str: + """按银行编码(BANK_TYPE)匹配字典 code,返回开卡银行;未命中返回空串。""" + if bank_type is None: + return "" + if isinstance(bank_type, float): + if bank_type != bank_type: # NaN + return "" + bank_type = str(int(bank_type)) + elif isinstance(bank_type, int): + bank_type = str(bank_type) + else: + bank_type = str(bank_type).strip() + return bank_map.get(bank_type, "") diff --git a/app/service/hrbp/ehr/common/hr_api/kq_data.py b/app/service/hrbp/ehr/common/hr_api/kq_data.py new file mode 100644 index 0000000..98c8522 --- /dev/null +++ b/app/service/hrbp/ehr/common/hr_api/kq_data.py @@ -0,0 +1,137 @@ +# -*- coding: utf-8 -*- +""" +@Module: hrbp.ehr.common.hr_api +@FileName: kq_data.py +@Description: 查询打卡记录接口(用于校验休息日半天上班是否按班段打卡) +@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 KQ_DATA_URL, PAGE_MAX_SIZE +from app.service.hrbp.common.hr_session import HRSessionExpiredError, hr_request_json +from app.service.hrbp.ehr.common.hr_api.attendance import fetch_cur_user_info + +logger = get_logger(__name__) + + +def fetch_kq_data_page( + session, + user_id: str, + base_code: str, + start_time: str, + end_time: str, + treecode: str = "cq37du", + page_no: int = 1, + page_size: int = PAGE_MAX_SIZE, +) -> Dict[str, Any]: + """ + 请求单页打卡记录数据(aa.md 提供的接口入参)。 + + Args: + session: 已登录的 requests.Session 对象 + user_id: 由 getCurUserInfo 返回的 userId + base_code: 员工工号 + start_time / end_time: 查询日期范围 "YYYY-MM-DD" + treecode: 组织树编码,默认 cq37du + page_no / page_size: 分页参数 + + Returns: + 接口返回的 JSON 字典(datas 为打卡流水数组,关键字段见下) + """ + params = { + "user_id": user_id, + "sqlId": "kq_data_query", + # datas 记录关键字段(aa.md 提供的返回样例): + # base_code 工号、staff_id、staff_name、 + # kq_time 打卡时间("YYYY-MM-DD HH:MM:SS")、kq_type 打卡类型(如 9)、 + # status 打卡状态、addr_status 地址状态、time_order 上/下班顺序、 + # bc_date 班次日期、kq_bc_id 考勤班次id、pb_id 排班id、address 打卡地点、 + # time_zone_min 时区分钟、varchar1 扩展标记 + "commonQuery": "", + "commonQueryStr": "", + "kqStaffIds": "", + "staff_id": "", + "staff_name": "", + "orgAlias": "", + "dept_ids": "", + "kq_type": "", + "post_type": "", + "person_status": "", + "dkstatus": "", + "addr_status": " ", + "struTreeCode": treecode, + "belongUnitStruId": "", + "work_day_begin": start_time, + "work_day_end": end_time, + "base_code": base_code, + "STAFF_NAME": "", + "start": str((page_no - 1) * page_size), + "sortType": "", + "sortName": "", + "pageNo": page_no, + "pageSize": page_size, + } + return hr_request_json(session, "POST", KQ_DATA_URL, params, "打卡查询") + + +def fetch_all_kq_data( + session, + user_id: str, + base_code: str, + start_time: str, + end_time: str, + treecode: str = "cq37du", +) -> List[Dict[str, Any]]: + """分页抓取指定工号、日期范围内的全部打卡记录。 + + Args: + session: 已登录的 requests.Session 对象 + user_id: 由 getCurUserInfo 返回的 userId + base_code: 员工工号 + start_time / end_time: 查询日期范围 "YYYY-MM-DD" + treecode: 组织树编码,默认 cq37du + + Returns: + 打卡记录列表(接口 datas 字段内容) + """ + all_rows: List[Dict[str, Any]] = [] + page_no = 1 + while True: + try: + data = fetch_kq_data_page( + session, user_id, base_code, start_time, end_time, + treecode, page_no, PAGE_MAX_SIZE, + ) + except HRSessionExpiredError: + logger.warning("打卡查询 HR 登录态过期,重新登录后续抓") + from app.service.hrbp.common.hr_session import refresh_hr_session + session = refresh_hr_session() + info = fetch_cur_user_info(session) + user_id = info.get("userId", "") + data = fetch_kq_data_page( + session, user_id, base_code, start_time, end_time, + treecode, page_no, PAGE_MAX_SIZE, + ) + + if data.get("state") != "1": + logger.error("打卡查询第%d页请求失败:%s", page_no, data.get("meg")) + break + + page_list = data.get("datas", []) or [] + if not page_list: + logger.info("打卡查询无更多数据") + break + + all_rows.extend(page_list) + + total_page = data.get("pageCount", 0) + logger.info("打卡查询已抓取 %d/%d 页,累计 %d 条", + page_no, total_page, len(all_rows)) + if page_no >= total_page: + break + page_no += 1 + time.sleep(0.2) + return all_rows diff --git a/app/service/hrbp/ehr/common/hr_api/leave.py b/app/service/hrbp/ehr/common/hr_api/leave.py new file mode 100644 index 0000000..5b9a852 --- /dev/null +++ b/app/service/hrbp/ehr/common/hr_api/leave.py @@ -0,0 +1,147 @@ +# -*- coding: utf-8 -*- +""" +@Module: hrbp.ehr.common.hr_api +@FileName: leave.py +@Description: 查询请假记录接口(用于过滤虚假异常,暂未在主流程调用) +@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 LEAVE_URL, PAGE_MAX_SIZE +from app.service.hrbp.common.hr_session import HRSessionExpiredError, hr_request_json +from app.service.hrbp.ehr.common.hr_api.attendance import fetch_cur_user_info + +logger = get_logger(__name__) + + +def fetch_leave_page( + session, + user_id: str, + base_code: str, + start_time: str, + end_time: str, + leave_type=None, + treecode: str = "cq37du", + page_no: int = 1, + page_size: int = PAGE_MAX_SIZE, +) -> Dict[str, Any]: + """ + 请求单页请假记录数据(aa.md 提供的接口入参)。 + + Args: + session: 已登录的 requests.Session 对象 + user_id: 由 getCurUserInfo 返回的 userId + base_code: 员工工号 + start_time / end_time: 查询日期范围 "YYYY-MM-DD" + leave_type: 请假类型编码(leave_type),可为单个值或列表,如 "22" / ["09", "22"]; + 不传(None)表示全部类型 + treecode: 组织树编码,默认 cq37du + page_no / page_size: 分页参数 + + Returns: + 接口返回的 JSON 字典(datas 为请假记录数组,字段含 start_time/end_time/leave_days/ + begin_date_other_name/end_date_other_name/base_code/staff_id 等) + """ + params = { + "STRU_TREE_CODE": treecode, + "user_id": user_id, + "begin_date": "", + "end_date": "", + "sqlId": "select_kqLeave_record", + "commonQuery": "", + "commonQueryStr": "", + "post_no": "", + "source": "", + "person_status": "", + "staff_id": "", + "staffNames": "", + "post_type": "1", + "processing_reason": "", + "processing_date": "", + "start_operat_time": "", + "end_operat_time": "", + "orgAlias": "", + "dept_ids": "", + "base_code": base_code, + "staff_name": "", + "start_time": start_time, + "end_time": end_time, + "start": str((page_no - 1) * page_size), + "sortType": "desc", + "sortName": "operat_time", + "pageNo": page_no, + "pageSize": page_size, + } + # leave_type 可多值(如 22&09&24...),requests 会把列表序列化为重复键;不传表示全部类型 + if leave_type: + if isinstance(leave_type, (list, tuple)): + params["leave_type"] = [str(t) for t in leave_type] + else: + params["leave_type"] = str(leave_type) + return hr_request_json(session, "POST", LEAVE_URL, params, "请假查询") + + +def fetch_all_leave( + session, + user_id: str, + base_code: str, + start_time: str, + end_time: str, + leave_type=None, + treecode: str = "cq37du", +) -> List[Dict[str, Any]]: + """分页抓取指定工号、日期范围内的全部请假记录。 + + Args: + session: 已登录的 requests.Session 对象 + user_id: 由 getCurUserInfo 返回的 userId + base_code: 员工工号 + start_time / end_time: 查询日期范围 "YYYY-MM-DD" + leave_type: 请假类型编码(leave_type),可为单个值或列表,如 "22" / ["09", "22"]; + 不传(None)表示全部类型 + treecode: 组织树编码,默认 cq37du + + Returns: + 请假记录列表(接口 datas 字段内容,含 start_time/end_time/leave_days 等) + """ + all_rows: List[Dict[str, Any]] = [] + page_no = 1 + while True: + try: + data = fetch_leave_page( + session, user_id, base_code, start_time, end_time, + leave_type, treecode, page_no, PAGE_MAX_SIZE, + ) + except HRSessionExpiredError: + logger.warning("请假查询 HR 登录态过期,重新登录后续抓") + from app.service.hrbp.common.hr_session import refresh_hr_session + session = refresh_hr_session() + info = fetch_cur_user_info(session) + user_id = info.get("userId", "") + data = fetch_leave_page( + session, user_id, base_code, start_time, end_time, + leave_type, treecode, page_no, PAGE_MAX_SIZE, + ) + + if data.get("state") != "1": + logger.error("请假查询第%d页请求失败:%s", page_no, data.get("meg")) + break + + page_list = data.get("datas", []) or [] + if not page_list: + logger.info("请假查询无更多数据") + break + + all_rows.extend(page_list) + + total_page = data.get("pageCount", 0) + logger.info("请假查询已抓取 %d/%d 页,累计 %d 条", + page_no, total_page, len(all_rows)) + if page_no >= total_page: + break + page_no += 1 + time.sleep(0.2) + return all_rows diff --git a/app/service/hrbp/ehr/common/hr_api/overtime.py b/app/service/hrbp/ehr/common/hr_api/overtime.py new file mode 100644 index 0000000..945ddf8 --- /dev/null +++ b/app/service/hrbp/ehr/common/hr_api/overtime.py @@ -0,0 +1,143 @@ +# -*- coding: utf-8 -*- +""" +@Module: hrbp.ehr.common.hr_api +@FileName: overtime.py +@Description: 查询加班记录接口(用于过滤虚假异常,暂未在主流程调用) +@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 OVERTIME_URL, PAGE_MAX_SIZE +from app.service.hrbp.common.hr_session import HRSessionExpiredError, hr_request_json +from app.service.hrbp.ehr.common.hr_api.attendance import fetch_cur_user_info + +logger = get_logger(__name__) + + +def fetch_overtime_page( + session, + user_id: str, + base_code: str, + start_time: str, + end_time: str, + work_overtime_type: str = "", + treecode: str = "cq37du", + page_no: int = 1, + page_size: int = PAGE_MAX_SIZE, +) -> Dict[str, Any]: + """ + 请求单页加班记录数据(aa.md 提供的接口入参)。 + + Args: + session: 已登录的 requests.Session 对象 + user_id: 由 getCurUserInfo 返回的 userId + base_code: 员工工号 + start_time / end_time: 查询日期范围 "YYYY-MM-DD" + work_overtime_type: 加班类型 WORK_OVERTIME_TYPE,空=全部、1=延时加班、2=法定假日加班、3=休息日加班 + treecode: 组织树编码,默认 cq37du + page_no / page_size: 分页参数 + + Returns: + 接口返回的 JSON 字典(datas 为加班记录数组,关键字段见下) + """ + params = { + "STRU_TREE_CODE": treecode, + "user_id": user_id, + "sqlId": "kq_overtime_detail_select", + # datas 记录关键字段(aa.md 提供的返回样例): + # base_code 工号、STAFF_ID、WORK_OVERTIME_TYPE 加班类型(1延时/2法定/3休息日)、 + # OT_DATE 加班日期、ot_days / sys_ot_days / plan_ot_days 加班天数(筛 0.5 天用)、 + # ot_hours / FINAL_HOURS 加班小时、 + # PLAN_START_TIME/PLAN_END_TIME、ACTUAL_START_TIME/ACTUAL_END_TIME、FINAL_START_TIME/FINAL_END_TIME 时间段、 + # SB_DA_RANGE / XB_DA_RANGE 上下班打卡分钟范围、SB_TIME_MORE/LESS、XB_TIME_MORE/LESS、OT_SB_TYPE/OT_XB_TYPE + "commonQuery": "", + "commonQueryStr": "", + "BPM_STATUS": "", + "post_no": "", + "postName": "", + "source": "", + "IS_SUBSIDY": "", + "person_status": "", + "staff_id": "", + "staffNames": "", + "post_type": "1", + "processing_reason": "", + "start_operat_time": "", + "end_operat_time": "", + "base_code": base_code, + "staff_name": "", + "WORK_OVERTIME_TYPE": work_overtime_type, + "start_time": start_time, + "end_time": end_time, + "start": str((page_no - 1) * page_size), + "sortType": "desc", + "sortName": "OPERATE_TIME", + "pageNo": page_no, + "pageSize": page_size, + } + return hr_request_json(session, "POST", OVERTIME_URL, params, "加班查询") + + +def fetch_all_overtime( + session, + user_id: str, + base_code: str, + start_time: str, + end_time: str, + work_overtime_type: str = "", + treecode: str = "cq37du", +) -> List[Dict[str, Any]]: + """分页抓取指定工号、日期范围内的全部加班记录。 + + Args: + session: 已登录的 requests.Session 对象 + user_id: 由 getCurUserInfo 返回的 userId + base_code: 员工工号 + start_time / end_time: 查询日期范围 "YYYY-MM-DD" + work_overtime_type: 加班类型 WORK_OVERTIME_TYPE,空=全部、1=延时加班、2=法定假日加班、3=休息日加班 + treecode: 组织树编码,默认 cq37du + + Returns: + 加班记录列表(接口 datas 字段内容) + """ + all_rows: List[Dict[str, Any]] = [] + page_no = 1 + while True: + try: + data = fetch_overtime_page( + session, user_id, base_code, start_time, end_time, + work_overtime_type, treecode, page_no, PAGE_MAX_SIZE, + ) + except HRSessionExpiredError: + logger.warning("加班查询 HR 登录态过期,重新登录后续抓") + from app.service.hrbp.common.hr_session import refresh_hr_session + session = refresh_hr_session() + info = fetch_cur_user_info(session) + user_id = info.get("userId", "") + data = fetch_overtime_page( + session, user_id, base_code, start_time, end_time, + work_overtime_type, treecode, page_no, PAGE_MAX_SIZE, + ) + + if data.get("state") != "1": + logger.error("加班查询第%d页请求失败:%s", page_no, data.get("meg")) + break + + page_list = data.get("datas", []) or [] + if not page_list: + logger.info("加班查询无更多数据") + break + + all_rows.extend(page_list) + + total_page = data.get("pageCount", 0) + logger.info("加班查询已抓取 %d/%d 页,累计 %d 条", + page_no, total_page, len(all_rows)) + if page_no >= total_page: + break + page_no += 1 + time.sleep(0.2) + return all_rows diff --git a/app/service/hrbp/ehr/common/hr_api/shift.py b/app/service/hrbp/ehr/common/hr_api/shift.py new file mode 100644 index 0000000..e92f4c1 --- /dev/null +++ b/app/service/hrbp/ehr/common/hr_api/shift.py @@ -0,0 +1,123 @@ +# -*- coding: utf-8 -*- +""" +@Module: hrbp.ehr.common.hr_api +@FileName: shift.py +@Description: 查询排班接口(用于过滤虚假异常,暂未在主流程调用) +@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 SHIFT_URL, PAGE_MAX_SIZE +from app.service.hrbp.common.hr_session import HRSessionExpiredError, hr_request_json +from app.service.hrbp.ehr.common.hr_api.attendance import fetch_cur_user_info + +logger = get_logger(__name__) + + +def fetch_shift_page( + session, + user_id: str, + base_code: str, + begin_date: str, + end_date: str, + treecode: str = "cq37du", + page_no: int = 1, + page_size: int = PAGE_MAX_SIZE, +) -> Dict[str, Any]: + """ + 请求单页排班数据(aa.md 提供的接口入参)。 + + Args: + session: 已登录的 requests.Session 对象 + user_id: 由 getCurUserInfo 返回的 userId + base_code: 员工工号 + begin_date / end_date: 查询日期范围 "YYYY-MM-DD" + treecode: 组织树编码,默认 cq37du + page_no / page_size: 分页参数 + + Returns: + 接口返回的 JSON 字典(datas 为排班明细数组,关键字段见下) + """ + params = { + "treecode": treecode, + "user_id": user_id, + "sqlId": "kq_count_SelectBanci", + # datas 记录关键字段(aa.md 提供的返回样例,一条记录 = 一个员工在查询范围内的排班): + # base_code 工号、staff_id、staff_name、work_day 首日、total_day / total_hours 汇总、 + # 基础班次:bc_name 班次名、bc_time 班段时间(如 "09:00 ~ 18:00",即班端)、begin_time / end_time、yq_total_min、 + # 逐日班次(动态列,key 为 "YYYY-MM-DD_bc_id/bc_name/bc_time/paiban_type/sb_type/xb_type"), + # paiban_type:-2=上班班次、0=休息;bc_time 为空串表示休息 + "commonQuery": "", + "commonQueryStr": "", + "staff_ids": "", + "person_status": "1,4", + "post_no": "", + "post_type": "1", + "post_level": "", + "identity": "", + "showType": "1", + "dateType": "1", + "begin": begin_date, + "end": end_date, + "bc_date": begin_date, + "base_code": base_code, + "staff_name": "", + "start": str((page_no - 1) * page_size), + "sortType": "", + "sortName": "", + "pageNo": page_no, + "pageSize": page_size, + } + return hr_request_json(session, "POST", SHIFT_URL, params, "排班") + + +def fetch_all_shift( + session, + user_id: str, + base_code: str, + begin_date: str, + end_date: str, + treecode: str = "cq37du", +) -> List[Dict[str, Any]]: + """分页抓取指定工号、日期范围内的全部排班数据。""" + all_rows: List[Dict[str, Any]] = [] + page_no = 1 + while True: + try: + data = fetch_shift_page( + session, user_id, base_code, begin_date, end_date, + treecode, page_no, PAGE_MAX_SIZE, + ) + except HRSessionExpiredError: + logger.warning("排班 HR 登录态过期,重新登录后续抓") + from app.service.hrbp.common.hr_session import refresh_hr_session + session = refresh_hr_session() + info = fetch_cur_user_info(session) + user_id = info.get("userId", "") + data = fetch_shift_page( + session, user_id, base_code, begin_date, end_date, + treecode, page_no, PAGE_MAX_SIZE, + ) + + if data.get("state") != "1": + logger.error("排班第%d页请求失败:%s", page_no, data.get("meg")) + break + + page_list = data.get("datas", []) or [] + if not page_list: + logger.info("排班无更多数据") + break + + all_rows.extend(page_list) + + total_page = data.get("pageCount", 0) + logger.info("排班已抓取 %d/%d 页,累计 %d 条", + page_no, total_page, len(all_rows)) + if page_no >= total_page: + break + page_no += 1 + time.sleep(0.2) + return all_rows diff --git a/app/service/hrbp/ehr/common/hr_api/wage_card.py b/app/service/hrbp/ehr/common/hr_api/wage_card.py new file mode 100644 index 0000000..3300546 --- /dev/null +++ b/app/service/hrbp/ehr/common/hr_api/wage_card.py @@ -0,0 +1,118 @@ +# -*- coding: utf-8 -*- +""" +@Module: hrbp.ehr.common.hr_api +@FileName: wage_card.py +@Description: 银行卡(工资卡)信息查询接口 +@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 WAGE_CARD_URL, PAGE_MAX_SIZE +from app.service.hrbp.common.hr_session import HRSessionExpiredError, hr_request_json + +logger = get_logger(__name__) + + +def fetch_wage_card_page( + session, + status: int, + page_no: int = 1, + page_size: int = PAGE_MAX_SIZE, + leave_start: str = None, + leave_end: str = None, +) -> Dict[str, Any]: + """ + 请求单页工资卡数据。 + + Args: + session: 已登录的 requests.Session 对象 + status: 人员状态,1=在职 / 2=离职 + page_no: 页码(从 1 开始) + page_size: 每页条数 + leave_start / leave_end: 离职筛选时间范围 "YYYY-MM-DD"(status=2 时必填) + + Returns: + 接口返回的 JSON 字典 + + Raises: + RuntimeError: 请求失败或响应异常 + HRSessionExpiredError: 登录态过期(接口返回非 JSON) + """ + params = { + "start": (page_no - 1) * page_size, + "pageNo": page_no, + "pageSize": page_size, + "ftl_list_STRU_TREE_CODE": "cq37du", + "sortName": "hr_staff_wage_card.STAFF_NAME", + "sortType": "asc", + "commonQuery": "[]", + "person_status": status, + } + # 在职、离职参数区分 + if status == 1: + params["leaveOffice_date"] = "" + elif leave_start and leave_end: + params["leaveOffice_date[0]"] = leave_start + params["leaveOffice_date[1]"] = leave_end + params["leaveOffice_date_start"] = leave_start + params["leaveOffice_date_end"] = leave_end + + return hr_request_json(session, "POST", WAGE_CARD_URL, params, "工资卡") + + +def fetch_all_wage_card( + session, + status: int, + status_name: str, + leave_start: str = None, + leave_end: str = None, +) -> List[Dict[str, Any]]: + """ + 分页抓取指定人员类型(在职/离职)的全部工资卡数据。 + + Args: + session: 已登录的 requests.Session 对象 + status: 人员状态,1=在职 / 2=离职 + status_name: 人员类型文字(用于日志与数据标记) + leave_start / leave_end: 离职筛选时间范围(status=2 时必填) + + Returns: + 数据行列表(每条已附加「人员类型」字段) + """ + all_rows: List[Dict[str, Any]] = [] + page_no = 1 + while True: + try: + data = fetch_wage_card_page(session, status, page_no, PAGE_MAX_SIZE, leave_start, leave_end) + except HRSessionExpiredError: + logger.warning("【%s】HR 登录态过期,重新登录后续抓", status_name) + from app.service.hrbp.common.hr_session import refresh_hr_session + session = refresh_hr_session() + data = fetch_wage_card_page(session, status, page_no, PAGE_MAX_SIZE, leave_start, leave_end) + + if data.get("state") != "1": + logger.error("【%s】第%d页请求失败:%s", status_name, page_no, data.get("meg")) + break + + page_list = data.get("datas", []) or [] + if not page_list: + logger.info("【%s】无更多数据", status_name) + break + + # 给每条数据增加人员类型标识 + for item in page_list: + item["人员类型"] = status_name + all_rows.extend(page_list) + + total = data.get("count", 0) + total_page = data.get("pageCount", 0) + logger.info("【%s】已抓取 %d/%d 页,累计 %d/%d 条", + status_name, page_no, total_page, len(all_rows), total) + if page_no >= total_page: + break + page_no += 1 + time.sleep(0.2) # 轻微限速,避免触发风控 + return all_rows diff --git a/app/service/hrbp/ehr/common/session_manager.py b/app/service/hrbp/ehr/common/session_manager.py deleted file mode 100644 index 0eef3d9..0000000 --- a/app/service/hrbp/ehr/common/session_manager.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -""" -@Module: hrbp.ehr.common -@FileName: session_manager.py -@Author: 小布丁 -@CreateTime: 2026-08-08 10:45 -@Description: 从 login.py 持久化的 HR cookies 构建 requests 会话;支持会话过期重新登录刷新(供各 HR 业务模块复用) -@Version: 1.0.0 -""" - -import os -import json - -from app.common.app_paths import get_sessions_dir -from app.utils.logger import get_logger - -try: - import requests -except ImportError: - requests = None - -logger = get_logger(__name__) - -# HR 登录 cookies 持久化目录(统一放在 AppData\Local\37duAutomation,login.py 登录成功后保存) -_SESSIONS_DIR = get_sessions_dir() -HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json') - - -def build_hr_session() -> "requests.Session": - """用本地缓存的 HR cookies 构造 requests 会话(仅取 hr.37du.co 域)。""" - if requests is None: - raise RuntimeError("缺少 requests 依赖,请先安装") - if not os.path.exists(HR_COOKIE_FILE): - logger.info("未找到 HR cookies 缓存,先执行 HR 登录") - refresh_hr_session() - if not os.path.exists(HR_COOKIE_FILE): - raise RuntimeError(f"HR 登录后仍未生成 cookies 文件:{HR_COOKIE_FILE}") - - with open(HR_COOKIE_FILE, encoding='utf-8') as f: - cookies = json.load(f) - - session = requests.Session() - session.headers.update({ - "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36", - "Content-Type": "application/x-www-form-urlencoded", - }) - for c in cookies or []: - if c.get("domain") and "37du.co" in c["domain"]: - session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/")) - return session - - -def refresh_hr_session() -> "requests.Session": - """HR 登录态过期后重新执行 HR 登录刷新 cookies,并重建会话。""" - from app.service.hrbp.ehr.common.login import login as hr_login - if not hr_login(): - raise RuntimeError("HR 登录态过期后重新登录失败") - return build_hr_session() diff --git a/app/service/hrbp/ehr/roster/roster_export.py b/app/service/hrbp/ehr/roster/roster_export.py index 7eee0a0..69f953d 100644 --- a/app/service/hrbp/ehr/roster/roster_export.py +++ b/app/service/hrbp/ehr/roster/roster_export.py @@ -16,7 +16,7 @@ 3. 下载目录默认取环境变量 roster_output_dir,否则使用项目根目录。 底层复用: - - HR 登录 & cookies:app.service.hrbp.ehr.common.login(load_cookies / login) + - HR 登录 & cookies:app.service.hrbp.common.login(load_cookies / login) - 页面地址 & 模板名:app.service.hrbp.ehr.common.config(ROSTER_URL / ROSTER_TEMPLATE_NAME) """ @@ -53,7 +53,7 @@ except ImportError: # 底层复用:HR 登录 / cookies / 配置 / 重试 / 离职时间范围 from app.service.hrbp.ehr.common.config import ROSTER_URL, ROSTER_TEMPLATE_NAME # noqa: E402 -from app.service.hrbp.ehr.common.login import load_cookies # noqa: E402 +from app.service.hrbp.common.login import load_cookies # noqa: E402 from app.service.hrbp.ehr.wage_card.wage_card_download import get_leave_range # noqa: E402 from app.utils.intelligent_retry import retry # noqa: E402 @@ -275,7 +275,7 @@ def _ensure_logged_in(page): # 登录页特征:存在用户名输入框 if page.ele('@id=j_username', timeout=2): logger.info("HR 登录态已失效,执行重新登录") - from app.service.hrbp.ehr.common.login import login as hr_login + from app.service.hrbp.common.login import login as hr_login if not hr_login(): raise RuntimeError("HR 重新登录失败") cookies = load_cookies() diff --git a/app/service/hrbp/ehr/wage_card/wage_card_download.py b/app/service/hrbp/ehr/wage_card/wage_card_download.py index 129492e..6939521 100644 --- a/app/service/hrbp/ehr/wage_card/wage_card_download.py +++ b/app/service/hrbp/ehr/wage_card/wage_card_download.py @@ -43,7 +43,7 @@ from app.service.hrbp.ehr.common.hr_api import ( # noqa: E402 bank_type_to_name, HRSessionExpiredError, ) -from app.service.hrbp.ehr.common.session_manager import ( # noqa: E402 +from app.service.hrbp.common.hr_session import ( # noqa: E402 build_hr_session, refresh_hr_session, ) diff --git a/app/service/hrbp/oa/common/config.py b/app/service/hrbp/oa/common/config.py index a1c6d88..fa1f36b 100644 --- a/app/service/hrbp/oa/common/config.py +++ b/app/service/hrbp/oa/common/config.py @@ -10,8 +10,9 @@ # ---------- OA 系统 ---------- # 待办列表等后台接口在 oa 域名;流程引擎/表单/考勤等 RedseaPlatform 接口在 hr 域名 +from app.service.hrbp.common.config import HR_BASE_URL # noqa: E402 + BASE_URL = "https://oa.37du.co" -HR_BASE_URL = "https://hr.37du.co" # 待办列表接口(oa 域名):按标题关键字查询当前账号的待办单据,用于抓取请假/加班等待审批流程 TODO_LIST_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyMainIndex.do" # 待办类型编码:"13" 对应需人工处理的审批类待办 diff --git a/app/service/hrbp/oa/common/oa_api.py b/app/service/hrbp/oa/common/oa_api.py deleted file mode 100644 index 15c30aa..0000000 --- a/app/service/hrbp/oa/common/oa_api.py +++ /dev/null @@ -1,606 +0,0 @@ -# -*- coding: utf-8 -*- -""" -@Module: hrbp.oa.oa_api -@FileName: oa_api.py -@Author: 小布丁 -@CreateTime: 2026-08-05 17:10 -@Description: OA/HR 系统 API 模块,负责调用系统接口(待办列表、流程引擎、表单、排班等) -@Version: 1.4.0 -""" - -import time -import re -import os -from typing import List, Dict, Any, Optional -from urllib.parse import urlencode, unquote - -from app.utils.logger import get_logger -try: - from DrissionPage import SessionPage -except ImportError: - SessionPage = None - -from app.service.hrbp.oa.common.config import BASE_URL, HR_BASE_URL, TODO_LIST_URL, DEFAULT_PAGE_SIZE, FD_TYPE, WF_ACTIVITY_URL, WORKFORM_ENGINE_URL, KQ_DATA_URL, LEAVE_RECORD_URL, PAIBAN_URL, FILE_DOWNLOAD_URL, ATTACHMENT_SAVE_DIR - -logger = get_logger(__name__) - - -def download_attachment( - session: SessionPage, - file_id: str, - save_dir: str = ATTACHMENT_SAVE_DIR, -) -> Optional[str]: - """ - 根据附件 fileId 从 OA 下载请假单据附件。 - - Args: - session: 已登录的 SessionPage 对象(已带登录 Cookie) - file_id: 附件 fileId(表单 result.file 字段值,即下载链接里的 fileId) - save_dir: 保存目录(默认 downloads) - - Returns: - 保存的完整文件路径;失败返回 None - """ - if not file_id: - logger.warning("附件 fileId 为空,跳过下载") - return None - - os.makedirs(save_dir, exist_ok=True) - url = f"{FILE_DOWNLOAD_URL}?fileId={file_id}" - logger.info("下载附件: fileId=%s", file_id) - - try: - session.get(url) - resp = session.response - except Exception as e: - logger.warning("附件请求失败(fileId=%s): %s", file_id, e) - return None - - if not resp or resp.status_code != 200: - logger.warning("附件下载失败: HTTP %s (fileId=%s)", resp.status_code, file_id) - return None - - # 从 Content-Disposition 解析真实文件名(可能带 UTF-8'' 编码) - filename = None - cd = resp.headers.get("Content-Disposition", "") - if "filename=" in cd: - raw = cd.split("filename=")[-1].strip().strip('"') - if raw.startswith("UTF-8''"): - raw = unquote(raw.split("UTF-8''", 1)[1]) - if raw: - filename = raw - - # 解析不到文件名时,用 fileId 兜底,并按 Content-Type 补扩展名 - if not filename: - filename = file_id - ct = (resp.headers.get("Content-Type") or "").split(";")[0].strip().lower() - ext_map = { - "image/png": ".png", - "image/jpeg": ".jpg", - "application/pdf": ".pdf", - "application/octet-stream": ".bin", - } - filename += ext_map.get(ct, ".bin") - - # 清理非法字符,防止路径注入 - filename = "".join(c for c in filename if c not in '\\/:*?"<>|') - path = os.path.join(save_dir, filename) - with open(path, "wb") as f: - f.write(resp.content) - logger.info("附件已下载: %s", path) - return path - - -# ---------- 获取待处理单据列表 ---------- -def fetch_todo_page( - session: SessionPage, - subject: str, - page_no: int = 1, - page_size: int = DEFAULT_PAGE_SIZE -) -> Dict[str, Any]: - """ - 请求单页待办列表数据。 - - Args: - session: 已登录的 SessionPage 对象 - subject: 待办标题关键字,如 "请假" / "加班" - page_no: 页码(从1开始) - page_size: 每页条数 - - Returns: - 接口返回的 JSON 字典 - - Raises: - RuntimeError: 请求失败或状态码异常 - """ - params = { - "method": "list", - "dataType": "todo", - "fdType": FD_TYPE, # 待办类型(请假/加班) - "fdCateId": "", - "q.fdSubject": subject, # 按标题关键字过滤(请假/加班) - "orderby": "fdCreateTime", - "ordertype": "down", - "page.pageNo": page_no, - "page.pageSize": page_size, - "__seq": int(time.time() * 1000), # 防缓存 - } - url = f"{TODO_LIST_URL}?{urlencode(params)}" - logger.debug("请求第 %d 页: %s", page_no, url) - - session.get(url) - resp = session.response - if not resp: - raise RuntimeError("请求失败,未获取到响应") - if resp.status_code != 200: - raise RuntimeError(f"接口请求失败,状态码: {resp.status_code}") - try: - return resp.json() - except Exception: - raise RuntimeError("接口返回非 JSON 数据,请检查参数或登录状态") - - -def parse_todo_list(data: Dict[str, Any]) -> List[Dict[str, Any]]: - """ - 解析接口返回的 JSON,提取每张单据的关键信息。 - - Args: - data: 接口返回的 JSON - - Returns: - 单据列表,每项包含: - - title: 标题(去除 HTML 标签) - - creator: 发起人 - - time: 接收时间(字符串) - - detail_url: SSO 跳转链接(完整 URL) - """ - datas = data.get("datas", []) - if not datas: - return [] - - docs = [] - for row in datas: - # 1. 标题 - title_cell = next((c for c in row if c["col"] == "todo.subject4View"), {}) - title_raw = title_cell.get("value", "") - # 移除 标签,仅保留内容 - match = re.search(r']*>(.*?)', title_raw, re.DOTALL) - title = match.group(1).strip() if match else re.sub(r'<[^>]+>', '', title_raw).strip() - - # 2. 发起人 - creator_cell = next((c for c in row if c["col"] == "docCreatorName"), {}) - creator = creator_cell.get("value", "") - - # 3. 接收时间 - time_cell = next((c for c in row if c["col"] == "fdCreateTime"), {}) - time_str = time_cell.get("value", "") - - # 4. SSO 跳转链接(补全为完整 URL) - href_cell = next((c for c in row if c["col"] == "tr_href"), {}) - detail_url = href_cell.get("value", "") - if detail_url and not detail_url.startswith(("http://", "https://")): - detail_url = BASE_URL + detail_url - - docs.append({ - "title": title, - "creator": creator, - "time": time_str, - "detail_url": detail_url, - }) - return docs - - -def get_documents( - session: SessionPage, - subject: str, - page_size: int = DEFAULT_PAGE_SIZE -) -> List[Dict[str, Any]]: - """ - 主入口:获取所有待处理单据(自动分页)。 - - 请假与加班流程逻辑一致,仅通过 subject 关键字区分。 - - Args: - session: 已登录的 SessionPage 对象(已设置 cookies) - subject: 待办标题关键字,如 "请假" / "加班" - page_size: 每页条数(默认15) - - Returns: - 所有单据的列表 - """ - all_docs = [] - - # 请求第一页,获取总条数 - data = fetch_todo_page(session, subject, page_no=1, page_size=page_size) - total = int(data.get("page", {}).get("totalSize", 0)) - logger.info("总待办[%s]条数: %d", subject, total) - - # 解析第一页 - docs = parse_todo_list(data) - all_docs.extend(docs) - logger.info("第 1 页获取 %d 条", len(docs)) - - # 若总条数超过单页,继续翻页 - if total > page_size: - total_pages = (total + page_size - 1) // page_size - for p in range(2, total_pages + 1): - data = fetch_todo_page(session, subject, page_no=p, page_size=page_size) - docs = parse_todo_list(data) - all_docs.extend(docs) - logger.info("第 %d 页获取 %d 条,累计 %d 条", p, len(docs), len(all_docs)) - - # 去重:OA 待办接口分页可能返回重复单据(同一条在多次/多页重复出现), - # 以详情链接 detail_url(含唯一 taskId)为键去重,避免同一单重复审批、重复推送 - seen = set() - unique_docs = [] - for doc in all_docs: - key = doc.get("detail_url") or doc.get("title") - if key in seen: - continue - seen.add(key) - unique_docs.append(doc) - - if len(unique_docs) != len(all_docs): - logger.warning("去重前 %d 条,去重后 %d 条(已过滤 %d 条重复单据)", - len(all_docs), len(unique_docs), len(all_docs) - len(unique_docs)) - return unique_docs - - -# ---------- WfActivity 接口:通过 taskId 获取 formId ---------- -def get_wf_activity_by_task_id( - session: SessionPage, - task_id: str -) -> Dict[str, Any]: - """ - 通过 taskId 调用 WfActivity 接口获取 formId。 - - Args: - session: 已登录的 SessionPage 对象 - task_id: SSO 解析得到的 taskId - - Returns: - 接口返回的 JSON 字典,包含 formId 等信息 - - Raises: - RuntimeError: 请求失败或响应异常 - """ - url = f"{WF_ACTIVITY_URL}?method=getWfActivityByTaskId" - data = {"taskId": task_id} - logger.info("获取 formId: taskId=%s", task_id) - - session.post(url, data=data) - resp = session.response - if not resp: - raise RuntimeError("WfActivity 请求失败,未获取到响应") - if resp.status_code != 200: - raise RuntimeError(f"WfActivity 接口状态码异常: {resp.status_code}") - - try: - json_data = resp.json() - except Exception: - body = (resp.text or "")[:200] - raise RuntimeError( - f"WfActivity 接口返回非 JSON 数据(状态码 {resp.status_code}): {body}" - ) - - logger.debug("WfActivity 返回: %s", json_data) - return json_data - - -def extract_form_id(wf_activity_data: Dict[str, Any]) -> str: - """ - 从 WfActivity 接口返回数据中提取 formId。 - - Args: - wf_activity_data: get_wf_activity_by_task_id 返回的 JSON - - Returns: - formId 字符串 - - Raises: - ValueError: 未找到 formId - """ - # 常见 formId 字段路径:顶层,以及 data / result 子对象 - form_id = ( - wf_activity_data.get("formId") - or wf_activity_data.get("FormId") - or wf_activity_data.get("form_id") - ) - if not form_id: - for key in ("data", "result"): - data_obj = wf_activity_data.get(key, {}) - if isinstance(data_obj, dict): - form_id = ( - data_obj.get("formId") - or data_obj.get("FormId") - or data_obj.get("form_id") - ) - if form_id: - break - - if not form_id: - raise ValueError(f"无法从 WfActivity 返回数据中提取 formId: {wf_activity_data}") - - logger.info("提取到 formId: %s", form_id) - return form_id - - -# ---------- WorkformEngine 接口:获取加班申请表单数据 ---------- -def get_business_data( - session: SessionPage, - business_key: str, - form_id: str -) -> Dict[str, Any]: - """ - 通过 businessKey 和 formId 调用 WorkformEngine 接口获取加班申请表单数据。 - - Args: - session: 已登录的 SessionPage 对象 - business_key: SSO 解析得到的 businessKey - form_id: 从 WfActivity 接口获取的 formId - - Returns: - 表单详细数据字典(接口响应的 result 字段,如 ot_date/staff_name 等) - - Raises: - RuntimeError: 请求失败或响应异常 - """ - url = f"{WORKFORM_ENGINE_URL}?method=getBusinessDate" - data = { - "businessKey": business_key, - "formId": form_id, - } - logger.info("获取加班表单: businessKey=%s, formId=%s", business_key, form_id) - - session.post(url, data=data) - resp = session.response - if not resp: - raise RuntimeError("WorkformEngine 请求失败,未获取到响应") - if resp.status_code != 200: - raise RuntimeError(f"WorkformEngine 接口状态码异常: {resp.status_code}") - - try: - json_data = resp.json() - except Exception: - body = (resp.text or "")[:200] - raise RuntimeError( - f"WorkformEngine 接口返回非 JSON 数据(状态码 {resp.status_code}): {body}" - ) - - # 表单详情在 result 字段中(如 ot_date / staff_name 等) - result = json_data.get("result") - if json_data.get("state") != "1" or not isinstance(result, dict): - raise RuntimeError(f"WorkformEngine 接口返回失败: {json_data}") - - logger.info("WorkformEngine 返回成功") - return result - - -# ---------- 排班接口 ---------- -def get_attendance_html( - session: SessionPage, - staff_id: str, - year: int, - month: int -) -> str: - """ - 获取指定员工某月的排班 HTML。 - - Args: - session: 已登录的 SessionPage 对象 - staff_id: 员工 UUID - year: 年份(如 2026) - month: 月份(1-12) - - Returns: - 排班表格的 HTML 字符串(从返回 JSON 的 caleHtml 字段提取) - - Raises: - RuntimeError: 请求失败或响应异常 - """ - url = f"{PAIBAN_URL}?method=geRenPaibanByMonth" - data = { - "type": "2", - "staffId": staff_id, - "year": str(year), - "month": str(month) - } - logger.info("获取排班: %s %d-%02d", staff_id, year, month) - - session.post(url, data=data) - resp = session.response - if not resp: - raise RuntimeError("排班请求失败,未获取到响应") - if resp.status_code != 200: - raise RuntimeError(f"排班接口状态码异常: {resp.status_code}") - - try: - json_data = resp.json() - except Exception: - raise RuntimeError("排班接口返回非 JSON 数据") - - if json_data.get("success") != "true": - raise RuntimeError(f"排班接口返回失败: {json_data}") - - html = json_data.get("caleHtml") - if not html: - raise RuntimeError("排班接口未返回 caleHtml 字段") - return html - - -# ---------- 考勤打卡明细接口 ---------- -def get_attendance_records( - session: SessionPage, - staff_id: str, - start_date: str, - end_date: str -) -> List[Dict[str, Any]]: - """ - 查询员工某时间段的原始打卡明细。 - - Args: - session: 已登录的 SessionPage 对象 - staff_id: 员工 UUID - start_date: 查询起始日期 "YYYY-MM-DD" - end_date: 查询结束日期 "YYYY-MM-DD" - - Returns: - 打卡记录列表(接口返回的 jsonList,每条含 kq_time / status / time_order 等) - - status: "1"=上班打卡, "5"=下班打卡, "6"=重复打卡 - - time_order: "1"=上班时段, "2"=下班时段 - - Raises: - RuntimeError: 请求失败或响应异常 - """ - params = { - "staff_id": staff_id, - "rootId": "", - "countId": "", - "bc_date": start_date, - "bc_date_end": end_date, - "begin": start_date, - "end": end_date, - } - logger.info("获取打卡明细: staff_id=%s, %s 至 %s", staff_id, start_date, end_date) - - session.get(KQ_DATA_URL, params=params) - resp = session.response - if not resp: - raise RuntimeError("考勤打卡请求失败,未获取到响应") - if resp.status_code != 200: - raise RuntimeError(f"考勤打卡接口状态码异常: {resp.status_code}") - - try: - json_data = resp.json() - except Exception: - body = (resp.text or "")[:200] - raise RuntimeError(f"考勤打卡接口返回非 JSON 数据: {body}") - - records = json_data.get("jsonList", []) - logger.info("打卡明细返回 %d 条", len(records)) - return records - - -# ---------- 请假记录接口 ---------- -def fetch_leave_record_page( - session: SessionPage, - staff_id: str, - begin_date: str, - end_date: str, - page_no: int = 1, - page_size: int = DEFAULT_PAGE_SIZE, - sub_type: str = "-1" -) -> Dict[str, Any]: - """ - 请求单页员工请假记录。 - - Args: - session: 已登录的 SessionPage 对象 - staff_id: 员工 UUID - begin_date: 查询起始日期 "YYYY-MM-DD" - end_date: 查询结束日期 "YYYY-MM-DD" - page_no: 页码(从1开始) - page_size: 每页条数 - sub_type: 假期类型编码,默认 "-1" 表示全部 - - Returns: - 接口返回的 data 字段字典,包含 total / pageCount / list - - Raises: - RuntimeError: 请求失败或响应异常 - """ - data = { - "sub_type": sub_type, - "staff_id": staff_id, - "begin_date": begin_date, - "end_date": end_date, - "start": str((page_no - 1) * page_size), - "pageSize": str(page_size), - "sortType": "", - "sortName": "", - "pageNo": str(page_no), - } - logger.info("获取请假记录: staff_id=%s, %s 至 %s, 第%d页", staff_id, begin_date, end_date, page_no) - - session.post(LEAVE_RECORD_URL, data=data) - resp = session.response - if not resp: - raise RuntimeError("请假记录请求失败,未获取到响应") - if resp.status_code != 200: - raise RuntimeError(f"请假记录接口状态码异常: {resp.status_code}") - - try: - json_data = resp.json() - except Exception: - body = (resp.text or "")[:200] - raise RuntimeError(f"请假记录接口返回非 JSON 数据: {body}") - - if json_data.get("success") is not True or json_data.get("code") != 200: - raise RuntimeError(f"请假记录接口返回失败: {json_data}") - - page_info = json_data.get("data") - if not isinstance(page_info, dict): - raise RuntimeError(f"请假记录接口未返回 data 字段: {json_data}") - return page_info - - -def get_leave_records( - session: SessionPage, - staff_id: str, - begin_date: str, - end_date: str, - page_size: int = DEFAULT_PAGE_SIZE, - sub_type: str = "-1" -) -> List[Dict[str, Any]]: - """ - 查询员工某时间段内的全部请假记录(自动分页)。 - - Args: - session: 已登录的 SessionPage 对象 - staff_id: 员工 UUID - begin_date: 查询起始日期 "YYYY-MM-DD" - end_date: 查询结束日期 "YYYY-MM-DD" - page_size: 每页条数 - sub_type: 假期类型编码,默认 "-1" 表示全部 - - Returns: - 请假记录列表,每条包含: - - staff_id: 员工ID - - staff_name: 员工姓名 - - leave_businessKey: 审批单号 - - sub_type: 假期类型编码 - - vacation_type_name: 假期名称 - - leave_reason: 请假原因 - - leave_days: 请假天数 - - leave_hours: 请假小时 - - start_time: 开始时间 - - end_time: 结束时间 - - Raises: - RuntimeError: 请求失败或响应异常 - """ - all_records: List[Dict[str, Any]] = [] - - # 请求第一页,获取总条数与总页数 - page_info = fetch_leave_record_page( - session, staff_id, begin_date, end_date, - page_no=1, page_size=page_size, sub_type=sub_type - ) - total = int(page_info.get("total", 0)) - page_total = int(page_info.get("pageCount", 1)) - records = page_info.get("list", []) or [] - all_records.extend(records) - logger.info("请假记录总数: %d, 第1页获取 %d 条", total, len(records)) - - # 若存在多页,继续翻页 - if page_total > 1: - for p in range(2, page_total + 1): - page_info = fetch_leave_record_page( - session, staff_id, begin_date, end_date, - page_no=p, page_size=page_size, sub_type=sub_type - ) - records = page_info.get("list", []) or [] - all_records.extend(records) - logger.info("第 %d 页获取 %d 条,累计 %d 条", p, len(records), len(all_records)) - - return all_records diff --git a/app/service/hrbp/oa/common/oa_api/__init__.py b/app/service/hrbp/oa/common/oa_api/__init__.py new file mode 100644 index 0000000..ba1a610 --- /dev/null +++ b/app/service/hrbp/oa/common/oa_api/__init__.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +""" +@Module: hrbp.oa.common.oa_api +@FileName: __init__.py +@Description: OA/HR 系统 API 模块:按功能拆分为 todo / flow / attendance / leave 子模块, + 本文件统一 re-export 公开接口,保持对调用方 import 路径不变。 + 通用请求封装见 base.py(oa_request_json)。 +@Version: 2.0.0 +""" + +from app.service.hrbp.oa.common.oa_api.base import oa_request_json, _handle_response +from app.service.hrbp.oa.common.oa_api.todo import ( + fetch_todo_page, + parse_todo_list, + get_documents, +) +from app.service.hrbp.oa.common.oa_api.flow import ( + get_wf_activity_by_task_id, + extract_form_id, + get_business_data, + download_attachment, +) +from app.service.hrbp.oa.common.oa_api.attendance import ( + get_attendance_html, + get_attendance_records, +) +from app.service.hrbp.oa.common.oa_api.leave import ( + fetch_leave_record_page, + get_leave_records, +) + +__all__ = [ + "oa_request_json", + "_handle_response", + "fetch_todo_page", + "parse_todo_list", + "get_documents", + "get_wf_activity_by_task_id", + "extract_form_id", + "get_business_data", + "download_attachment", + "get_attendance_html", + "get_attendance_records", + "fetch_leave_record_page", + "get_leave_records", +] diff --git a/app/service/hrbp/oa/common/oa_api/attendance.py b/app/service/hrbp/oa/common/oa_api/attendance.py new file mode 100644 index 0000000..6cf5bce --- /dev/null +++ b/app/service/hrbp/oa/common/oa_api/attendance.py @@ -0,0 +1,100 @@ +# -*- coding: utf-8 -*- +""" +@Module: hrbp.oa.common.oa_api +@FileName: attendance.py +@Description: 排班 HTML 与考勤打卡明细接口。 +@Version: 1.0.0 +""" + +from typing import List, Dict, Any + +from app.utils.logger import get_logger +try: + from DrissionPage import SessionPage +except ImportError: + SessionPage = None + +from app.service.hrbp.oa.common.config import PAIBAN_URL, KQ_DATA_URL +from app.service.hrbp.oa.common.oa_api.base import oa_request_json + +logger = get_logger(__name__) + + +def get_attendance_html( + session: SessionPage, + staff_id: str, + year: int, + month: int +) -> str: + """ + 获取指定员工某月的排班 HTML。 + + Args: + session: 已登录的 SessionPage 对象 + staff_id: 员工 UUID + year: 年份(如 2026) + month: 月份(1-12) + + Returns: + 排班表格的 HTML 字符串(从返回 JSON 的 caleHtml 字段提取) + + Raises: + RuntimeError: 请求失败或响应异常 + """ + url = f"{PAIBAN_URL}?method=geRenPaibanByMonth" + data = { + "type": "2", + "staffId": staff_id, + "year": str(year), + "month": str(month) + } + logger.info("获取排班: %s %d-%02d", staff_id, year, month) + json_data = oa_request_json(session, "POST", url, data, "排班") + + if json_data.get("success") != "true": + raise RuntimeError(f"排班接口返回失败: {json_data}") + + html = json_data.get("caleHtml") + if not html: + raise RuntimeError("排班接口未返回 caleHtml 字段") + return html + + +def get_attendance_records( + session: SessionPage, + staff_id: str, + start_date: str, + end_date: str +) -> List[Dict[str, Any]]: + """ + 查询员工某时间段的原始打卡明细。 + + Args: + session: 已登录的 SessionPage 对象 + staff_id: 员工 UUID + start_date: 查询起始日期 "YYYY-MM-DD" + end_date: 查询结束日期 "YYYY-MM-DD" + + Returns: + 打卡记录列表(接口返回的 jsonList,每条含 kq_time / status / time_order 等) + - status: "1"=上班打卡, "5"=下班打卡, "6"=重复打卡 + - time_order: "1"=上班时段, "2"=下班时段 + + Raises: + RuntimeError: 请求失败或响应异常 + """ + params = { + "staff_id": staff_id, + "rootId": "", + "countId": "", + "bc_date": start_date, + "bc_date_end": end_date, + "begin": start_date, + "end": end_date, + } + logger.info("获取打卡明细: staff_id=%s, %s 至 %s", staff_id, start_date, end_date) + json_data = oa_request_json(session, "GET", KQ_DATA_URL, params, "考勤打卡") + + records = json_data.get("jsonList", []) + logger.info("打卡明细返回 %d 条", len(records)) + return records diff --git a/app/service/hrbp/oa/common/oa_api/base.py b/app/service/hrbp/oa/common/oa_api/base.py new file mode 100644 index 0000000..7f2ec2c --- /dev/null +++ b/app/service/hrbp/oa/common/oa_api/base.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +""" +@Module: hrbp.oa.common.oa_api +@FileName: base.py +@Description: OA API 通用请求封装(发送 + 校验):只封装「发送 + 状态码 + JSON 解析」, + 业务级成功判定(state / success / code)保留在各接口自身。 + 对应 docs/通用接口请求封装规划.md。 +@Version: 1.0.0 +""" + +from app.utils.logger import get_logger + +try: + from DrissionPage import SessionPage +except ImportError: + SessionPage = None + +logger = get_logger(__name__) + + +def _handle_response(resp, label): + """统一校验响应:存在性 / 状态码 / JSON 可解析性,返回解析后的 JSON。""" + if not resp: + raise RuntimeError(f"{label}请求失败,未获取到响应") + if resp.status_code != 200: + raise RuntimeError(f"{label}接口状态码异常: {resp.status_code}") + try: + return resp.json() + except Exception: + body = (resp.text or "")[:200] + raise RuntimeError(f"{label}接口返回非 JSON 数据(状态码 {resp.status_code}): {body}") + + +def oa_request_json( + session: SessionPage, + method: str, + url: str, + params: dict, + label: str, + timeout: int = 20, +): + """通用「发送请求 + 校验响应」:发出请求 → 校验状态码/JSON → 返回解析后的 JSON。 + + Args: + session: 已登录的 DrissionPage SessionPage 对象(已带登录 Cookie) + method: "GET" / "POST"(GET 用 params 传参,POST 用 data 传参) + url: 接口地址 + params: 请求参数 + label: 接口中文名(用于报错信息) + timeout: 请求超时秒数,默认 20 + + Returns: + 解析后的 JSON 字典 + + Raises: + RuntimeError: 请求失败或响应异常 + """ + if method.upper() == "GET": + session.get(url, params=params, timeout=timeout) + else: + session.post(url, data=params, timeout=timeout) + return _handle_response(session.response, label) diff --git a/app/service/hrbp/oa/common/oa_api/flow.py b/app/service/hrbp/oa/common/oa_api/flow.py new file mode 100644 index 0000000..d57ecc0 --- /dev/null +++ b/app/service/hrbp/oa/common/oa_api/flow.py @@ -0,0 +1,192 @@ +# -*- coding: utf-8 -*- +""" +@Module: hrbp.oa.common.oa_api +@FileName: flow.py +@Description: OA 流程引擎/表单/附件接口:taskId 查 formId、businessKey 查表单数据、附件下载。 +@Version: 1.0.0 +""" + +import os +from typing import Dict, Any, Optional +from urllib.parse import unquote + +from app.utils.logger import get_logger +try: + from DrissionPage import SessionPage +except ImportError: + SessionPage = None + +from app.service.hrbp.oa.common.config import ( + WF_ACTIVITY_URL, + WORKFORM_ENGINE_URL, + FILE_DOWNLOAD_URL, + ATTACHMENT_SAVE_DIR, +) +from app.service.hrbp.oa.common.oa_api.base import oa_request_json + +logger = get_logger(__name__) + + +def get_wf_activity_by_task_id( + session: SessionPage, + task_id: str +) -> Dict[str, Any]: + """ + 通过 taskId 调用 WfActivity 接口获取 formId。 + + Args: + session: 已登录的 SessionPage 对象 + task_id: SSO 解析得到的 taskId + + Returns: + 接口返回的 JSON 字典,包含 formId 等信息 + + Raises: + RuntimeError: 请求失败或响应异常 + """ + url = f"{WF_ACTIVITY_URL}?method=getWfActivityByTaskId" + data = {"taskId": task_id} + logger.info("获取 formId: taskId=%s", task_id) + json_data = oa_request_json(session, "POST", url, data, "WfActivity") + logger.debug("WfActivity 返回: %s", json_data) + return json_data + + +def extract_form_id(wf_activity_data: Dict[str, Any]) -> str: + """ + 从 WfActivity 接口返回数据中提取 formId。 + + Args: + wf_activity_data: get_wf_activity_by_task_id 返回的 JSON + + Returns: + formId 字符串 + + Raises: + ValueError: 未找到 formId + """ + # 常见 formId 字段路径:顶层,以及 data / result 子对象 + form_id = ( + wf_activity_data.get("formId") + or wf_activity_data.get("FormId") + or wf_activity_data.get("form_id") + ) + if not form_id: + for key in ("data", "result"): + data_obj = wf_activity_data.get(key, {}) + if isinstance(data_obj, dict): + form_id = ( + data_obj.get("formId") + or data_obj.get("FormId") + or data_obj.get("form_id") + ) + if form_id: + break + + if not form_id: + raise ValueError(f"无法从 WfActivity 返回数据中提取 formId: {wf_activity_data}") + + logger.info("提取到 formId: %s", form_id) + return form_id + + +def get_business_data( + session: SessionPage, + business_key: str, + form_id: str +) -> Dict[str, Any]: + """ + 通过 businessKey 和 formId 调用 WorkformEngine 接口获取加班申请表单数据。 + + Args: + session: 已登录的 SessionPage 对象 + business_key: SSO 解析得到的 businessKey + form_id: 从 WfActivity 接口获取的 formId + + Returns: + 表单详细数据字典(接口响应的 result 字段,如 ot_date/staff_name 等) + + Raises: + RuntimeError: 请求失败或响应异常 + """ + url = f"{WORKFORM_ENGINE_URL}?method=getBusinessDate" + data = { + "businessKey": business_key, + "formId": form_id, + } + logger.info("获取加班表单: businessKey=%s, formId=%s", business_key, form_id) + json_data = oa_request_json(session, "POST", url, data, "WorkformEngine") + + # 表单详情在 result 字段中(如 ot_date / staff_name 等) + result = json_data.get("result") + if json_data.get("state") != "1" or not isinstance(result, dict): + raise RuntimeError(f"WorkformEngine 接口返回失败: {json_data}") + + logger.info("WorkformEngine 返回成功") + return result + + +def download_attachment( + session: SessionPage, + file_id: str, + save_dir: str = ATTACHMENT_SAVE_DIR, +) -> Optional[str]: + """ + 根据附件 fileId 从 OA 下载请假单据附件。 + + Args: + session: 已登录的 SessionPage 对象(已带登录 Cookie) + file_id: 附件 fileId(表单 result.file 字段值,即下载链接里的 fileId) + save_dir: 保存目录(默认 downloads) + + Returns: + 保存的完整文件路径;失败返回 None + """ + if not file_id: + logger.warning("附件 fileId 为空,跳过下载") + return None + + os.makedirs(save_dir, exist_ok=True) + url = f"{FILE_DOWNLOAD_URL}?fileId={file_id}" + logger.info("下载附件: fileId=%s", file_id) + + try: + session.get(url) + resp = session.response + except Exception as e: + logger.warning("附件请求失败(fileId=%s): %s", file_id, e) + return None + + if not resp or resp.status_code != 200: + logger.warning("附件下载失败: HTTP %s (fileId=%s)", resp.status_code, file_id) + return None + + # 从 Content-Disposition 解析真实文件名(可能带 UTF-8'' 编码) + filename = None + cd = resp.headers.get("Content-Disposition", "") + if "filename=" in cd: + raw = cd.split("filename=")[-1].strip().strip('"') + if raw.startswith("UTF-8''"): + raw = unquote(raw.split("UTF-8''", 1)[1]) + if raw: + filename = raw + + # 解析不到文件名时,用 fileId 兜底,并按 Content-Type 补扩展名 + if not filename: + filename = file_id + ct = (resp.headers.get("Content-Type") or "").split(";")[0].strip().lower() + ext_map = { + "image/png": ".png", + "image/jpeg": ".jpg", + "application/pdf": ".pdf", + "application/octet-stream": ".bin", + } + filename += ext_map.get(ct, ".bin") + + # 清理非法字符,防止路径注入 + filename = "".join(c for c in filename if c not in '\\/:*?"<>|') + path = os.path.join(save_dir, filename) + with open(path, "wb") as f: + f.write(resp.content) + logger.info("附件已下载: %s", path) + return path diff --git a/app/service/hrbp/oa/common/oa_api/leave.py b/app/service/hrbp/oa/common/oa_api/leave.py new file mode 100644 index 0000000..92e0570 --- /dev/null +++ b/app/service/hrbp/oa/common/oa_api/leave.py @@ -0,0 +1,132 @@ +# -*- coding: utf-8 -*- +""" +@Module: hrbp.oa.common.oa_api +@FileName: leave.py +@Description: 员工请假记录接口:单页查询与自动分页。 +@Version: 1.0.0 +""" + +from typing import List, Dict, Any + +from app.utils.logger import get_logger +try: + from DrissionPage import SessionPage +except ImportError: + SessionPage = None + +from app.service.hrbp.oa.common.config import LEAVE_RECORD_URL, DEFAULT_PAGE_SIZE +from app.service.hrbp.oa.common.oa_api.base import oa_request_json + +logger = get_logger(__name__) + + +def fetch_leave_record_page( + session: SessionPage, + staff_id: str, + begin_date: str, + end_date: str, + page_no: int = 1, + page_size: int = DEFAULT_PAGE_SIZE, + sub_type: str = "-1" +) -> Dict[str, Any]: + """ + 请求单页员工请假记录。 + + Args: + session: 已登录的 SessionPage 对象 + staff_id: 员工 UUID + begin_date: 查询起始日期 "YYYY-MM-DD" + end_date: 查询结束日期 "YYYY-MM-DD" + page_no: 页码(从1开始) + page_size: 每页条数 + sub_type: 假期类型编码,默认 "-1" 表示全部 + + Returns: + 接口返回的 data 字段字典,包含 total / pageCount / list + + Raises: + RuntimeError: 请求失败或响应异常 + """ + data = { + "sub_type": sub_type, + "staff_id": staff_id, + "begin_date": begin_date, + "end_date": end_date, + "start": str((page_no - 1) * page_size), + "pageSize": str(page_size), + "sortType": "", + "sortName": "", + "pageNo": str(page_no), + } + logger.info("获取请假记录: staff_id=%s, %s 至 %s, 第%d页", staff_id, begin_date, end_date, page_no) + json_data = oa_request_json(session, "POST", LEAVE_RECORD_URL, data, "请假记录") + + if json_data.get("success") is not True or json_data.get("code") != 200: + raise RuntimeError(f"请假记录接口返回失败: {json_data}") + + page_info = json_data.get("data") + if not isinstance(page_info, dict): + raise RuntimeError(f"请假记录接口未返回 data 字段: {json_data}") + return page_info + + +def get_leave_records( + session: SessionPage, + staff_id: str, + begin_date: str, + end_date: str, + page_size: int = DEFAULT_PAGE_SIZE, + sub_type: str = "-1" +) -> List[Dict[str, Any]]: + """ + 查询员工某时间段内的全部请假记录(自动分页)。 + + Args: + session: 已登录的 SessionPage 对象 + staff_id: 员工 UUID + begin_date: 查询起始日期 "YYYY-MM-DD" + end_date: 查询结束日期 "YYYY-MM-DD" + page_size: 每页条数 + sub_type: 假期类型编码,默认 "-1" 表示全部 + + Returns: + 请假记录列表,每条包含: + - staff_id: 员工ID + - staff_name: 员工姓名 + - leave_businessKey: 审批单号 + - sub_type: 假期类型编码 + - vacation_type_name: 假期名称 + - leave_reason: 请假原因 + - leave_days: 请假天数 + - leave_hours: 请假小时 + - start_time: 开始时间 + - end_time: 结束时间 + + Raises: + RuntimeError: 请求失败或响应异常 + """ + all_records: List[Dict[str, Any]] = [] + + # 请求第一页,获取总条数与总页数 + page_info = fetch_leave_record_page( + session, staff_id, begin_date, end_date, + page_no=1, page_size=page_size, sub_type=sub_type + ) + total = int(page_info.get("total", 0)) + page_total = int(page_info.get("pageCount", 1)) + records = page_info.get("list", []) or [] + all_records.extend(records) + logger.info("请假记录总数: %d, 第1页获取 %d 条", total, len(records)) + + # 若存在多页,继续翻页 + if page_total > 1: + for p in range(2, page_total + 1): + page_info = fetch_leave_record_page( + session, staff_id, begin_date, end_date, + page_no=p, page_size=page_size, sub_type=sub_type + ) + records = page_info.get("list", []) or [] + all_records.extend(records) + logger.info("第 %d 页获取 %d 条,累计 %d 条", p, len(records), len(all_records)) + + return all_records diff --git a/app/service/hrbp/oa/common/oa_api/todo.py b/app/service/hrbp/oa/common/oa_api/todo.py new file mode 100644 index 0000000..f20f7b1 --- /dev/null +++ b/app/service/hrbp/oa/common/oa_api/todo.py @@ -0,0 +1,165 @@ +# -*- coding: utf-8 -*- +""" +@Module: hrbp.oa.common.oa_api +@FileName: todo.py +@Description: OA 待办列表接口:分页查询待办单据、解析、去重。 +@Version: 1.0.0 +""" + +import time +import re +from typing import List, Dict, Any + +from app.utils.logger import get_logger +try: + from DrissionPage import SessionPage +except ImportError: + SessionPage = None + +from app.service.hrbp.oa.common.config import BASE_URL, TODO_LIST_URL, DEFAULT_PAGE_SIZE, FD_TYPE +from app.service.hrbp.oa.common.oa_api.base import oa_request_json + +logger = get_logger(__name__) + + +def fetch_todo_page( + session: SessionPage, + subject: str, + page_no: int = 1, + page_size: int = DEFAULT_PAGE_SIZE +) -> Dict[str, Any]: + """ + 请求单页待办列表数据。 + + Args: + session: 已登录的 SessionPage 对象 + subject: 待办标题关键字,如 "请假" / "加班" + page_no: 页码(从1开始) + page_size: 每页条数 + + Returns: + 接口返回的 JSON 字典 + + Raises: + RuntimeError: 请求失败或状态码异常 + """ + params = { + "method": "list", + "dataType": "todo", + "fdType": FD_TYPE, # 待办类型(请假/加班) + "fdCateId": "", + "q.fdSubject": subject, # 按标题关键字过滤(请假/加班) + "orderby": "fdCreateTime", + "ordertype": "down", + "page.pageNo": page_no, + "page.pageSize": page_size, + "__seq": int(time.time() * 1000), # 防缓存 + } + logger.debug("请求第 %d 页待办[%s]", page_no, subject) + return oa_request_json(session, "GET", TODO_LIST_URL, params, "待办列表") + + +def parse_todo_list(data: Dict[str, Any]) -> List[Dict[str, Any]]: + """ + 解析接口返回的 JSON,提取每张单据的关键信息。 + + Args: + data: 接口返回的 JSON + + Returns: + 单据列表,每项包含: + - title: 标题(去除 HTML 标签) + - creator: 发起人 + - time: 接收时间(字符串) + - detail_url: SSO 跳转链接(完整 URL) + """ + datas = data.get("datas", []) + if not datas: + return [] + + docs = [] + for row in datas: + # 1. 标题 + title_cell = next((c for c in row if c["col"] == "todo.subject4View"), {}) + title_raw = title_cell.get("value", "") + # 移除 标签,仅保留内容 + match = re.search(r']*>(.*?)', title_raw, re.DOTALL) + title = match.group(1).strip() if match else re.sub(r'<[^>]+>', '', title_raw).strip() + + # 2. 发起人 + creator_cell = next((c for c in row if c["col"] == "docCreatorName"), {}) + creator = creator_cell.get("value", "") + + # 3. 接收时间 + time_cell = next((c for c in row if c["col"] == "fdCreateTime"), {}) + time_str = time_cell.get("value", "") + + # 4. SSO 跳转链接(补全为完整 URL) + href_cell = next((c for c in row if c["col"] == "tr_href"), {}) + detail_url = href_cell.get("value", "") + if detail_url and not detail_url.startswith(("http://", "https://")): + detail_url = BASE_URL + detail_url + + docs.append({ + "title": title, + "creator": creator, + "time": time_str, + "detail_url": detail_url, + }) + return docs + + +def get_documents( + session: SessionPage, + subject: str, + page_size: int = DEFAULT_PAGE_SIZE +) -> List[Dict[str, Any]]: + """ + 主入口:获取所有待处理单据(自动分页)。 + + 请假与加班流程逻辑一致,仅通过 subject 关键字区分。 + + Args: + session: 已登录的 SessionPage 对象(已设置 cookies) + subject: 待办标题关键字,如 "请假" / "加班" + page_size: 每页条数(默认15) + + Returns: + 所有单据的列表 + """ + all_docs = [] + + # 请求第一页,获取总条数 + data = fetch_todo_page(session, subject, page_no=1, page_size=page_size) + total = int(data.get("page", {}).get("totalSize", 0)) + logger.info("总待办[%s]条数: %d", subject, total) + + # 解析第一页 + docs = parse_todo_list(data) + all_docs.extend(docs) + logger.info("第 1 页获取 %d 条", len(docs)) + + # 若总条数超过单页,继续翻页 + if total > page_size: + total_pages = (total + page_size - 1) // page_size + for p in range(2, total_pages + 1): + data = fetch_todo_page(session, subject, page_no=p, page_size=page_size) + docs = parse_todo_list(data) + all_docs.extend(docs) + logger.info("第 %d 页获取 %d 条,累计 %d 条", p, len(docs), len(all_docs)) + + # 去重:OA 待办接口分页可能返回重复单据(同一条在多次/多页重复出现), + # 以详情链接 detail_url(含唯一 taskId)为键去重,避免同一单重复审批、重复推送 + seen = set() + unique_docs = [] + for doc in all_docs: + key = doc.get("detail_url") or doc.get("title") + if key in seen: + continue + seen.add(key) + unique_docs.append(doc) + + if len(unique_docs) != len(all_docs): + logger.warning("去重前 %d 条,去重后 %d 条(已过滤 %d 条重复单据)", + len(all_docs), len(unique_docs), len(all_docs) - len(unique_docs)) + return unique_docs diff --git a/app/service/hrbp/oa/leave/parser.py b/app/service/hrbp/oa/leave/parser.py index 1fa633f..3ac4e06 100644 --- a/app/service/hrbp/oa/leave/parser.py +++ b/app/service/hrbp/oa/leave/parser.py @@ -11,26 +11,13 @@ from typing import Any, Dict from app.utils.logger import get_logger +from app.service.hrbp.common.config import VACATION_TYPE_MAP logger = get_logger(__name__) # ---------- 假期类型编码 -> 名称映射 ---------- - -VACATION_TYPE_MAP: Dict[str, str] = { - "04": "病假", - "05": "产假", - "09": "事假", - "11": "调休假", - "15": "普通事假", - "17": "特殊事假", - "18": "小时特假", - "19": "普通事假(晚/高峰)", - "20": "普通事假(早/中)", - "22": "半天休(仅限人资专用)", - "23": "特别福利假", - "24": "年度福利假", -} +# 已统一收口到 HR 平台共享层(hrbp/common/config.py),此处直接复用,不再重复定义 # ---------- 请假表单解析 ---------- diff --git a/app/service/hrbp/oa/social_change/employee_change_list.py b/app/service/hrbp/oa/social_change/employee_change_list.py index c70451d..c3a6cf9 100644 --- a/app/service/hrbp/oa/social_change/employee_change_list.py +++ b/app/service/hrbp/oa/social_change/employee_change_list.py @@ -28,9 +28,15 @@ _root = _find_project_root() if _root not in sys.path: sys.path.insert(0, _root) -from app.common.app_paths import get_sessions_dir from app.utils.logger import get_logger, setup_logging from app.utils.intelligent_retry import retry +# HR 平台会话/请求封装(共享层,避免反向依赖 ehr) +from app.service.hrbp.common.hr_session import ( + build_hr_session, + refresh_hr_session, + HRSessionExpiredError, + hr_request_json, +) from app.service.hrbp.oa.common.config import BASE_URL from app.service.hrbp.oa.common.login import oa_login from app.service.hrbp.oa.common.session_manager import ( @@ -54,11 +60,6 @@ try: except ImportError: xlrd = None -try: - import requests -except ImportError: - requests = None - try: from openpyxl import Workbook as _XlsxWorkbook from openpyxl.styles import PatternFill, Font, Alignment @@ -111,8 +112,7 @@ FILTER_IDX_SUSPEND = "3" # ---------- HR 参保记录核对(si_main 接口,对应 aa.md) ---------- SI_QUERY_URL = "https://hr.37du.co/RedseaPlatform/getPageAjax/si_main_SelectByTreeCode/CoreRequest.mc" -# HR cookies 持久化文件(ehr/common/login.py 保存,统一放在 AppData\Local\37duAutomation) -HR_COOKIE_FILE = os.path.join(get_sessions_dir(), 'hr_cookies.json') +# HR cookies 由 hrbp/common 共享层管理(login.py 保存、build_hr_session 读取) SI_BASE_PARAMS = { "start": "0", "pageNo": "1", "pageSize": "15", "USER_ID": "07b83185-6243-42bc-b79f-b81b4cffb471", @@ -479,55 +479,12 @@ def clean_employee_change_file(xls_path: str, output_dir: str = ".") -> str: # ---------------------------------------------- # 5.6 HR 参保记录核对(调用 si_main 接口,追加结果列) # ---------------------------------------------- -def _build_hr_session(): - """用本地缓存的 HR cookies 构造 requests 会话(仅取 hr.37du.co 域)。""" - if requests is None: - raise RuntimeError("缺少 requests 依赖,请先安装") - if not os.path.exists(HR_COOKIE_FILE): - raise RuntimeError(f"未找到 HR cookies 缓存文件:{HR_COOKIE_FILE},请先执行 HR 登录") - - import json - with open(HR_COOKIE_FILE, encoding='utf-8') as f: - cookies = json.load(f) - - session = requests.Session() - session.headers.update({ - "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", - "Content-Type": "application/x-www-form-urlencoded", - }) - for c in cookies or []: - if c.get("domain") and "37du.co" in c["domain"]: - session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/")) - return session - - -class HRSessionExpiredError(Exception): - """HR 登录态过期:接口返回登录页等非 JSON 内容。""" - - -def _si_is_expired(text) -> bool: - """接口正常情况下返回 JSON;返回登录页/错误页等非 JSON 即视为登录态过期。""" - return bool(text) and not text.lstrip().startswith(("{", "[")) - - -def _si_refresh_hr_session(): - """HR 登录态过期后重新执行 HR 登录刷新 cookies,并重建会话。""" - from app.service.hrbp.ehr.common.login import login as hr_login - if not hr_login(): - raise RuntimeError("HR 登录态过期后重新登录失败") - return _build_hr_session() - - @retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,)) def _si_query_batch(session, codes_batch): """查询一批工号(≤15个),返回响应 JSON。""" params = SI_BASE_PARAMS.copy() params["base_codes"] = ",".join(codes_batch) - resp = session.post(SI_QUERY_URL, data=params, timeout=15) - resp.raise_for_status() - if _si_is_expired(resp.text): - raise HRSessionExpiredError("HR 登录态已过期,接口返回非 JSON 内容") - return resp.json() + return hr_request_json(session, "POST", SI_QUERY_URL, params, "社保参保记录", timeout=15) def _si_found_codes(response_json): @@ -553,7 +510,7 @@ def _si_preflight(session): _si_query_batch(session, ["0"]) except HRSessionExpiredError: logger.warning("预检发现 HR 登录态已过期,正在重新登录") - return _si_refresh_hr_session() + return refresh_hr_session() return session @@ -570,7 +527,7 @@ def _write_annotated(headers, rows, emp_col, mode, base_name, output_dir=".") -> seen.add(code) unique_codes.append(code) - session = _si_preflight(_build_hr_session()) + session = _si_preflight(build_hr_session(auto_login=False)) found = set() for i in range(0, len(unique_codes), SI_BATCH_SIZE): batch = unique_codes[i:i + SI_BATCH_SIZE] @@ -579,7 +536,7 @@ def _write_annotated(headers, rows, emp_col, mode, base_name, output_dir=".") -> except HRSessionExpiredError: logger.warning("HR 登录态过期,正在重新登录并续跑(第 %d/%d 批)", min(i + SI_BATCH_SIZE, len(unique_codes)), len(unique_codes)) - session = _si_refresh_hr_session() + session = refresh_hr_session() found |= _si_check_batch(session, batch) logger.info("参保记录核对 %d/%d 个工号", min(i + SI_BATCH_SIZE, len(unique_codes)), len(unique_codes)) time.sleep(0.3) diff --git a/app/service/hrbp/oa/social_change/si_insurance_check.py b/app/service/hrbp/oa/social_change/si_insurance_check.py index 76e2d3d..2349d16 100644 --- a/app/service/hrbp/oa/social_change/si_insurance_check.py +++ b/app/service/hrbp/oa/social_change/si_insurance_check.py @@ -30,14 +30,15 @@ _root = _find_project_root() if _root not in sys.path: sys.path.insert(0, _root) -from app.common.app_paths import get_sessions_dir from app.utils.logger import get_logger, setup_logging from app.utils.intelligent_retry import retry - -try: - import requests -except ImportError: - requests = None +# HR 平台会话/请求封装(共享层,避免反向依赖 ehr) +from app.service.hrbp.common.hr_session import ( + build_hr_session, + refresh_hr_session, + HRSessionExpiredError, + hr_request_json, +) try: import xlrd @@ -57,9 +58,6 @@ logger = get_logger(__name__) # HR 参保记录查询接口(aa.md 提供的 si_main 接口) SI_QUERY_URL = "https://hr.37du.co/RedseaPlatform/getPageAjax/si_main_SelectByTreeCode/CoreRequest.mc" -# HR cookies 持久化文件(login.py 保存,统一放在 AppData\Local\37duAutomation) -HR_COOKIE_FILE = os.path.join(get_sessions_dir(), 'hr_cookies.json') - # 接口基础参数(aa.md 基础参数模板,base_codes 动态替换) SI_BASE_PARAMS = { "start": "0", "pageNo": "1", "pageSize": "15", @@ -86,61 +84,15 @@ RESULT_COL = "社保记录查询结果" BATCH_SIZE = 15 -class HRSessionExpiredError(Exception): - """HR 登录态过期:接口返回登录页等非 JSON 内容。""" - - -def _is_expired(text) -> bool: - """接口正常情况下返回 JSON;返回登录页/错误页等非 JSON 即视为登录态过期。""" - return bool(text) and not text.lstrip().startswith(("{", "[")) - - -def _refresh_hr_session() -> "requests.Session": - """HR 登录态过期后重新执行 HR 登录刷新 cookies,并重建会话。""" - from app.service.hrbp.ehr.common.login import login as hr_login - if not hr_login(): - raise RuntimeError("HR 登录态过期后重新登录失败") - return build_hr_session() - - # ---------------------------------------------- -# 1. HR 会话(复用登录缓存 cookies) -# ---------------------------------------------- -def build_hr_session() -> "requests.Session": - """用本地缓存的 HR cookies 构造 requests 会话(仅取 hr.37du.co 域)。""" - if requests is None: - raise RuntimeError("缺少 requests 依赖,请先安装") - if not os.path.exists(HR_COOKIE_FILE): - raise RuntimeError(f"未找到 HR cookies 缓存文件:{HR_COOKIE_FILE},请先执行 HR 登录") - - import json - with open(HR_COOKIE_FILE, encoding='utf-8') as f: - cookies = json.load(f) - - session = requests.Session() - session.headers.update({ - "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", - "Content-Type": "application/x-www-form-urlencoded", - }) - for c in cookies or []: - if c.get("domain") and "37du.co" in c["domain"]: - session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/")) - return session - - -# ---------------------------------------------- -# 2. 查询参保记录接口 +# 1. 查询参保记录接口 # ---------------------------------------------- @retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,)) def query_batch(session, codes_batch: List[str]): """查询一批工号(≤15个),返回响应 JSON。""" params = SI_BASE_PARAMS.copy() params["base_codes"] = ",".join(codes_batch) - resp = session.post(SI_QUERY_URL, data=params, timeout=15) - resp.raise_for_status() - if _is_expired(resp.text): - raise HRSessionExpiredError("HR 登录态已过期,接口返回非 JSON 内容") - return resp.json() + return hr_request_json(session, "POST", SI_QUERY_URL, params, "社保参保记录", timeout=15) def extract_found_codes(response_json) -> set: @@ -166,7 +118,7 @@ def preflight(session) -> "requests.Session": query_batch(session, ["0"]) except HRSessionExpiredError: logger.warning("预检发现 HR 登录态已过期,正在重新登录") - return _refresh_hr_session() + return refresh_hr_session() return session @@ -219,7 +171,7 @@ def check_and_annotate(table_path: str, mode: str, output_dir: str = ".") -> str seen.add(code) unique_codes.append(code) - session = preflight(build_hr_session()) + session = preflight(build_hr_session(auto_login=False)) found = set() for i in range(0, len(unique_codes), BATCH_SIZE): batch = unique_codes[i:i + BATCH_SIZE] @@ -228,7 +180,7 @@ def check_and_annotate(table_path: str, mode: str, output_dir: str = ".") -> str except HRSessionExpiredError: logger.warning("HR 登录态过期,正在重新登录并续跑(第 %d/%d 批)", min(i + BATCH_SIZE, len(unique_codes)), len(unique_codes)) - session = _refresh_hr_session() + session = refresh_hr_session() found |= check_codes(session, batch) logger.info("已查询 %d/%d 个工号", min(i + BATCH_SIZE, len(unique_codes)), len(unique_codes)) time.sleep(0.3) # 轻微限速,避免触发风控 diff --git a/docs/周考勤异常处理开发文档.md b/docs/周考勤异常处理开发文档.md new file mode 100644 index 0000000..97e114a --- /dev/null +++ b/docs/周考勤异常处理开发文档.md @@ -0,0 +1,155 @@ +# EHR 系统周考勤异常处理 — 开发文档 + +> 版本:v2.0.0 +> 对应文件:`app/service/hrbp/ehr/attendance/attendance_abnormal.py` +> 更新日期:2026-08-14 + +## 1. 概述 + +考勤异常查询、导出与分级推送工具。链路: + +``` +HR 会话(getCurUserInfo 校验)→ 分页拉取当月未调整考勤异常 +→ 导出 Excel 底稿 → 分级分类(轻微直接处理 / 其余钉钉核实)→ 推送通知 +``` + +> 对应需求文档:`docs/周考勤异常处理需求文档.md`。 + +## 2. 底层复用 + +| 组件 | 用途 | +|------|------| +| `hr_api.fetch_cur_user_info` | 校验 cookies,返回 userId / rootId(treecode) | +| `hr_api.fetch_all_attendance_abnormal` | 分页拉取考勤异常(支持 is_adjusted 过滤) | +| `hr_api.adjust_abnormal` | 考勤异常确认/调整接口封装(默认未启用) | +| `hr_session.build_hr_session / refresh_hr_session` | 会话构建与过期重登 | +| `utils.dingtalk_sender.send_to_person` | 钉钉按姓名推送(默认未启用) | +| `common.config` | 接口地址常量(`ATTENDANCE_ABNORMAL_URL`、`ATTENDANCE_ADJUST_URL`) | + +## 3. 配置区 + +| 常量 | 值 | 说明 | +|------|----|------| +| `SAVE_DIR` | `D:\资料\人资\考勤异常` | 导出目录 | +| `COL_MAP` | 异常ID/员工姓名/工号/考勤日期/班次/异常类型/异常时长(分钟) | 英文字段→中文字段 | +| `SHOW_ORDER` | 核心字段顺序 | 展示列顺序(其余字段自动排后) | +| `IS_ADJUSTED` | `"0"` | 只查询未调整异常(0=未调整) | + +## 4. 代码结构 + +| 函数 | 职责 | +|------|------| +| `current_month_range` | 当月 1 日至今天的日期范围 | +| `_validate_session` | cookies 校验(`getCurUserInfo`),过期自动重登并返回 (session, user_id, treecode) | +| `export_excel` | 字段中文化、列排序、导出 xlsx(文件名带时间戳,处理文件占用) | +| `classify_abnormal` | 分级判定:迟到/早退 < 30 分钟 → 不推送;其余 → 推送 | +| `build_notify_text` | 按需求格式拼接钉钉通知文本 | +| `push_abnormal` | 逐条生成通知文本(当前仅打印,`send_to_person` 注释待启用) | +| `_fetch_abnormal_data` | 会话校验 + 计算查询范围 + 拉取当月异常数据 | +| `download_attendance_abnormal` | 仅导出 Excel(无数据返回 None) | +| `handle_attendance_abnormal` | 导出 Excel + 分级 + 推送 + 统计汇总 | +| `main` | 命令行入口(参数:save_dir、month) | + +## 5. 核心逻辑说明 + +### 5.1 会话与数据获取 + +- 先 `build_hr_session()`,再 `getCurUserInfo` 校验;`HRSessionExpiredError` 时 `refresh_hr_session()` 重登后重试。 +- 查询范围:默认「当月 1 日至今天」;传 `month="YYYY-MM"` 则查整月(`begin=YYYY-MM-01`,`end=YYYY-MM-31`)。 +- 仅查询 `is_adjusted=0`(未调整)异常,避免重复处理已确认/已调整记录。 + +### 5.2 分级规则 `classify_abnormal` + +```python +if ("迟到" in abnormal or "早退" in abnormal) and minute < 30: + return False # 轻微异常,直接处理 +return True # 需推送核实 +``` + +- 判定基于 `abnormal`(异常类型)与 `abnormal_minute`(异常时长)。 +- 类型含「迟到/早退」且时长 < 30 分钟 → 轻微,直接处理; +- 迟到/早退 ≥ 30 分钟,或漏打卡/旷工/工时不足等其他类型 → 推送。 + +### 5.3 通知文本 `build_notify_text` + +``` +【考勤异常核实通知】 +姓名:{STAFF_NAME} +工号:{base_code} +考勤日期:{work_day} +班次:{bc_name} +异常类型:{abnormal} +异常时长:{minute}分钟 +请确认本次{异常类型}{时长}分钟真实情况:{异常类型}/漏打卡/外出/其他 +``` + +- 迟到/早退类异常会在确认项前附上时长(如「迟到35分钟」);其他类型直接写类型名。 +- 异常类型缺失时兜底为「考勤异常」。 + +### 5.4 推送 `push_abnormal` + +- 遍历待推送记录,按姓名(`STAFF_NAME`)生成通知文本。 +- 姓名缺失时记录告警并跳过。 +- **当前默认关闭实际发送**:仅 `logger.info` 输出「待推送通知」文本供人工确认;确认无误后取消 `send_to_person(name, text=text)` 注释即可启用。 + +### 5.5 汇总统计 + +`handle_attendance_abnormal` 输出:异常总数 / 直接处理数(轻微)/ 待通知数 / 导出文件路径。 + +## 6. 数据流 + +``` +build_hr_session → _validate_session(getCurUserInfo) + ↓ +_fetch_abnormal_data → fetch_all_attendance_abnormal(is_adjusted=0, 当月) + ↓ +export_excel → 考勤异常_{月份}_{时间戳}.xlsx + ↓ +classify_abnormal 分级 + ├─ 轻微(迟到/早退<30)→ 直接处理(统计记录) + └─ 待通知 → push_abnormal(生成文本 → 钉钉推送) +``` + +## 7. 异常与重试策略 + +| 场景 | 策略 | +|------|------| +| 登录态过期 | 捕获 `HRSessionExpiredError` → `refresh_hr_session` 重登 → 重新获取 userId/treecode 后续抓 | +| 接口异常 | `hr_request_json` 层处理,携带中文错误说明 | +| 导出文件被占用 | 捕获 `PermissionError` → 提示关闭 Excel 后重试,不抛堆栈 | +| 无数据 | 不导出空 Excel,返回 None 并跳过导出/推送 | +| 依赖缺失(pandas) | 抛明确中文错误 | + +## 8. 运行方式 + +```bash +# 直接运行(默认当月,默认目录) +python attendance_abnormal.py + +# 指定保存目录 + 查询月份 +python attendance_abnormal.py "D:\资料\人资\考勤异常" 2026-08 +``` + +> **影刀调度(已确认)**:每周三 15:00 后触发。默认查询「当月 1 日至今」,无需额外参数;如需要可在影刀任务中传入 save_dir。 + +```python +# 作为模块调用 +from app.service.hrbp.ehr.attendance.attendance_abnormal import handle_attendance_abnormal +path = handle_attendance_abnormal() # 默认当月 +path = handle_attendance_abnormal(month="2026-08") # 指定整月 +``` + +## 9. 待启用能力(按需求逐步开放) + +| 能力 | 现状 | 启用方式 | +|------|------|----------| +| 钉钉实际推送 | 仅打印通知文本 | 取消 `push_abnormal` 中 `send_to_person` 注释 | +| 考勤页面自动确认异常 | 接口已封装,调用点注释 | 取消 `confirm_abnormal` 注释并按需求接入调用链 | +| 异常截图传递当事人 | 未实现 | 需新增截图能力(如页面截图接口)后接入推送 | + +## 10. 维护注意事项 + +- **接口变更**:地址集中在 `ehr/common/config.py`(`ATTENDANCE_ABNORMAL_URL` 等)。 +- **分级阈值**:`classify_abnormal` 中 `30` 分钟为硬编码,需调整时改此处。 +- **通知模板**:`build_notify_text` 集中维护,改动不影响其他逻辑。 +- **只查未调整**:`IS_ADJUSTED="0"`,如需求改为包含其他状态,改此处即可。 diff --git a/docs/周考勤异常处理需求文档.md b/docs/周考勤异常处理需求文档.md new file mode 100644 index 0000000..30af119 --- /dev/null +++ b/docs/周考勤异常处理需求文档.md @@ -0,0 +1,102 @@ +# EHR 系统周考勤异常处理 — 需求文档 + +> 版本:v1.1(草案) +> 状态:待评审 +> 所属模块:`app/service/hrbp/ehr/attendance/attendance_abnormal.py`(考勤异常查询、导出、分级推送) +> 创建时间:2026-08-14 + +> **调度时间:每周三下午 15:00 后自动执行**(影刀定时任务触发)。 +> **查询范围(已确认):当月 1 日至今。** + +## 1. 背景 + +HR 每周需处理 EHR 系统的考勤异常(迟到、早退、漏打卡、旷工、工时不足等)。不同严重程度的异常处理方式不同:轻微异常可直接在考勤页面确认,严重异常需通过钉钉与当事人核实后再处理。目前依赖人工逐条下载、判断、推送,工作量大且易遗漏,需要自动化完成「拉取异常 → 分级分类 → 导出 → 钉钉核实 → 确认异常 → 结果记录」全流程。 + +## 2. 目标 + +- 自动拉取当月(可指定月份)**未调整**的考勤异常明细并导出 Excel,作为处理底稿。 +- 按规则自动分级:轻微异常(迟到/早退 < 30 分钟)→ 直接在考勤页面确认异常;其余异常 → 推送当事人核实。 +- 依据当事人回复执行后续处理:确认迟到 → 考勤页面确认异常;回复其他情形 → 指引当事人对接查询监控核实,核实后转人资。 +- 核实与处理结果通过人资专用号钉钉反馈或文档记录,供专人定期查看处理。 + +## 3. 分级处理规则 + +| 异常情形 | 处理方式 | +|----------|----------| +| 迟到 / 早退,异常时长 < 30 分钟 | 直接在考勤页面确认异常(轻微异常,无需通知) | +| 迟到 / 早退,异常时长 ≥ 30 分钟 | 按姓名推送钉钉通知,请当事人核实 | +| 漏打卡、旷工、工时不足等其他异常 | 按姓名推送钉钉通知,请当事人核实 | + +> 分级判定以「异常类型」与「异常时长(分钟)」两个字段为依据:类型含「迟到/早退」且时长 < 30 分钟视为轻微异常;其余一律进入钉钉核实流程。 + +## 4. 钉钉核实流程 + +1. **推送通知**:按异常人员姓名发送钉钉消息,内容包含姓名、工号、考勤日期、班次、异常类型、异常时长,并要求当事人确认本次异常的真实情形(如:迟到 N 分钟 / 漏打卡 / 外出 / 其他)。 +2. **当事人回复「确认迟到」** → 直接在考勤页面确认异常。 +3. **当事人回复其他情形** → 告知当事人请对接查询监控核实;核实结果传递人资(XXX)。 +4. **结果留痕**:处理截图反馈至人资专用号钉钉,或文档记录输出,专人定期查看处理。 + +> 说明: +> - 「截图传递当事人确认」指将异常明细(可含截图)通过钉钉发给当事人本人确认; +> - 「反馈截图给人资专用号」为流程留痕要求,与文档记录互为备份,二者至少执行其一。 + +## 5. 数据来源 + +| 数据 | 来源 | 用途 | +|------|------|------| +| 登录态 | hr.37du.co 登录(cookies 缓存,过期自动重登) | 保证考勤接口可访问 | +| 当前用户信息 | `getCurUserInfo` | 校验 cookies 有效性,获取查询所需的 userId / rootId(treecode) | +| 考勤异常明细 | 考勤异常分页接口(`is_adjusted=0` 未调整) | 当月待处理异常数据 | +| 钉钉会话 | 钉钉桌面客户端(模拟搜索+粘贴发送) | 向当事人/人资号发送核实通知 | + +## 6. 输出 + +- `考勤异常_{月份}_{时间戳}.xlsx`:当月未调整考勤异常明细,展示列见下: + +| 列 | 说明 | +|----|------| +| 异常ID | abnormal_id | +| 员工姓名 | STAFF_NAME | +| 工号 | base_code | +| 考勤日期 | work_day | +| 班次 | bc_name | +| 异常类型 | abnormal | +| 异常时长(分钟) | abnormal_minute | + +- 钉钉核实通知:按需发送给当事人(待启用推送后生效)。 + +## 7. 处理流程 + +1. **会话准备**:构建 HR 会话,调用 `getCurUserInfo` 校验登录态(过期则自动重登)。 +2. **拉取数据**:分页拉取当月(默认当月 1 日至今天)`is_adjusted=0`(未调整)考勤异常。 +3. **导出底稿**:字段中文化、调整列顺序后导出 Excel。 +4. **分级**:逐条按规则判定 —— 轻微异常归「直接处理」,其余归「待通知」。 +5. **推送核实**:对待通知的异常按姓名生成钉钉通知文本并推送当事人。 +6. **结果确认与留痕**:根据当事人回复在考勤页面确认异常或转交人资;处理结果截图/文档留痕。 + +## 8. 边界与约束 + +- 仅处理「未调整(is_adjusted=0)」异常,已确认/已调整的记录不重复处理。 +- 「考勤页面确认异常」对应考勤异常确认接口(`adjust_abnormal`),该能力当前已封装但默认未启用(需确认后开启)。 +- 钉钉实际推送默认关闭(仅打印通知文本供人工确认),启用前需人工复核通知模板。 +- 推送按姓名匹配钉钉联系人,姓名缺失或无法匹配的联系人跳过并记录告警。 +- 网络/接口异常使用重试机制;登录态过期自动重新登录后续抓。 +- 无异常数据时不导出空 Excel,直接跳过导出与推送。 + +## 9. 实现决策(已确认,以代码实现为准) + +| 事项 | 代码实现方式 | +|------|-------------| +| 自动确认 | 考勤异常确认接口(`adjust_abnormal`)已封装,但默认**不启用自动确认**;「在考勤页面确认异常」由人工执行 | +| 通知形式 | 按姓名推送**文本通知**(`build_notify_text`),程序不自动截图;截图/留痕由人工处理 | +| 结果留痕 | 以导出 Excel 文档记录输出(`考勤异常_{月份}_{时间戳}.xlsx`),专人定期查看;钉钉实际推送默认关闭(仅打印通知文本) | + +## 10. 交付物 + +- `app/service/hrbp/ehr/attendance/attendance_abnormal.py`:查询导出 + 分级 + 推送主流程。 +- 复用:`hr_api.fetch_all_attendance_abnormal`、`hr_api.adjust_abnormal`、`hr_session`、`utils.dingtalk_sender`。 +- 输出:`D:\资料\人资\考勤异常\考勤异常_{月份}_{时间戳}.xlsx`。 + +--- + +*本需求为草案,实现决策以代码实现为准,后续需求变化再行调整。* diff --git a/docs/月考勤异常处理开发文档.md b/docs/月考勤异常处理开发文档.md new file mode 100644 index 0000000..f44619c --- /dev/null +++ b/docs/月考勤异常处理开发文档.md @@ -0,0 +1,159 @@ +# EHR 系统月考勤异常处理 — 开发文档 + +> 版本:v1.0.0 +> 对应文件:`app/service/hrbp/ehr/attendance/abnormal_check.py` +> 更新日期:2026-08-14 + +## 1. 概述 + +月考勤异常三重复核工具,结合考勤异常 / 请假 / 加班 / 打卡 / 排班五类接口数据,对当月数据执行三项检查并输出多 Sheet Excel 报告。独立于周考勤异常处理流程。 + +``` +拉取当月数据(异常/请假/加班/打卡/排班) +→ 检查1:已确认异常 × 请假流程 +→ 检查2:休息日半天加班 × 班段打卡校验 +→ 检查3:整日请假 × 残留考勤异常 +→ 导出多 Sheet 报告 +``` + +> 对应需求文档:`docs/月考勤异常处理需求文档.md`。 + +## 2. 底层复用 + +| 组件 | 用途 | +|------|------| +| `hr_api.fetch_cur_user_info` | cookies 校验,返回 userId / rootId(treecode) | +| `hr_api.fetch_all_attendance_abnormal` | 分页拉取考勤异常(`is_adjusted` 过滤) | +| `hr_api.fetch_all_leave` | 全部请假记录(空工号=全量) | +| `hr_api.fetch_all_overtime` | 加班记录(类型过滤,空工号=全量) | +| `hr_api.fetch_all_kq_data` | 某员工某日打卡流水 | +| `hr_api.fetch_all_shift` | 某员工排班(动态列,按日期取班段) | +| `hr_session.build_hr_session / refresh_hr_session` | 会话构建与过期重登 | +| `common.config.VACATION_TYPE_MAP` | 假期类型编码 → 名称 | + +## 3. 配置区 + +| 常量 | 值 | 说明 | +|------|----|------| +| `SAVE_DIR` | `D:\资料\人资\考勤异常` | 导出目录 | +| `IS_ADJUSTED_CONFIRMED` | `"2"` | 已确认异常(检查1、检查3 并集之一) | +| `IS_ADJUSTED_OPEN` | `"0"` | 未调整异常(检查3 并集之一) | +| `WORK_OVERTIME_TYPE_REST` | `"3"` | 休息日加班(检查2) | +| `HALF_DAY` / `EPS` | `0.5` / `1e-6` | 半天加班判定阈值 | +| `PUNCH_TOLERANCE_MIN` | `60` | 打卡与班段边界匹配容差(分钟) | + +## 4. 代码结构 + +| 函数 | 职责 | +|------|------| +| `current_month_range` | 当月 1 日至今天的日期范围 | +| `_get` / `_to_date_str` / `_float` | 字段兼容取值、日期归一化、数值转换 | +| `_is_half_day_ot` | 判定加班是否为休息日半天(ot_days / sys_ot_days / plan_ot_days ≈ 0.5) | +| `_leave_type_name` | 请假类型编码 → 名称 | +| `_punch_analysis` | 打卡流水统计(按最早=上班、最晚=下班) | +| `_to_minutes` / `_parse_shift_time` | 时间串→分钟;班段 "HH:MM ~ HH:MM" 解析 | +| `_extract_day_shift` | 从排班记录提取指定日期班段(bc_time / paiban_type) | +| `_judge_punch_by_shift` | 结合班段判定打卡是否正常 | +| `_validate_session` | cookies 校验,过期重登 | +| `_fetch_all_data` | 一次性拉取三项检查所需基础数据 | +| `_build_leave_set` | 请假记录索引化 {(code, 日期): rec},支持整日过滤 | +| `check_leave_after_confirm` | 检查1 | +| `check_rest_day_half_day_punch` | 检查2 | +| `check_full_day_leave_abnormal` | 检查3 | +| `export_report` | 多 Sheet Excel 导出 | +| `handle_abnormal_check` / `main` | 对外入口 / 命令行入口 | + +## 5. 核心逻辑说明 + +### 5.1 数据获取 `_fetch_all_data` + +- `abnormal_confirmed`:`is_adjusted=2`(已确认异常)→ 检查1; +- `abnormal_open`:`is_adjusted=0`(未调整异常)→ 检查3 并集之一; +- `leaves`:全部请假(空工号)→ 检查1/检查3 共用; +- `rest_overtime`:休息日加班(类型=3,空工号)→ 检查2。 + +### 5.2 检查1:已确认异常 × 请假流程 + +- `_build_leave_set(leaves, need_full_day=False)` 建立「请假日期索引」(请假日期的每一天均计入)。 +- 逐条遍历已确认异常:`(base_code, work_day)` 命中请假索引 → 命中。 +- 输出「问题说明」提示可能为「提前确认后请假」仍为异常。 + +### 5.3 检查2:休息日半天加班 × 班段打卡校验 + +- 筛出休息日加班中 `_is_half_day_ot`(ot_days ≈ 0.5)的记录。 +- 按工号缓存排班(避免重复请求),`_extract_day_shift` 取加班日期的班段时间(动态列 `{date}_bc_time`)。 +- 拉取该员工当日打卡流水,`_punch_analysis` 统计最早/最晚打卡与次数。 +- `_judge_punch_by_shift` 判定: + - 有班段:最早打卡 ≤ 班段开始+容差 且 最晚打卡 ≥ 班段结束-容差 且 次数 ≥ 2 → 正常; + - 无班段(休息日排班):退化为按次数判断(≥2 正常,1/0 次漏打卡); + - 其余 → 漏打卡(未按班段覆盖上下班)。 + +### 5.4 检查3:整日请假 × 残留考勤异常 + +- `_build_leave_set(leaves, need_full_day=True)`:只保留整日请假(leave_days ≥ 1)的每一天。 +- 未调整 + 已确认异常取并集,逐条比对 (base_code, work_day)。 +- 命中输出「提示」列:`该员工{work_day}考勤状态存在异常`,并附异常类型与状态(未调整/确认异常)。 + +### 5.5 报告导出 `export_report` + +- 文件名:`月考勤异常三查_{月份}_{时间戳}.xlsx`(月份如 `2026-08`)。 +- Sheet 顺序:汇总 → 检查1_确认异常有请假 → 检查2_休息日半天打卡 → 检查3_整日请假有异常。 +- 无数据的 Sheet 也保留表头;汇总 Sheet 附带人工复核备注。 +- `PermissionError`(文件被占用)时给出明确中文提示。 + +## 6. 数据流 + +``` +build_hr_session → _validate_session(getCurUserInfo) + ↓ +_fetch_all_data(当月范围) + ├─ abnormal_confirmed(is_adjusted=2) ┐ + ├─ abnormal_open(is_adjusted=0) ├→ 检查1/检查3 + ├─ leaves(全部请假) ┘ + └─ rest_overtime(休息日加班类型3) ───→ 检查2(+ 按工号打卡/排班) + ↓ +export_report → 月考勤异常三查_{月份}_{时间戳}.xlsx +``` + +## 7. 异常与重试策略 + +| 场景 | 策略 | +|------|------| +| 登录态过期 | `getCurUserInfo` / 各接口捕获 `HRSessionExpiredError` → 重登后续抓 | +| 排班/打卡接口异常 | `fetch_all_*` 内部分页容错,重登兜底 | +| 导出文件被占用 | 捕获 `PermissionError` → 提示关闭 Excel 后重试 | +| 无数据 | 对应检查跳过,报告保留空 Sheet 表头 | +| 依赖缺失(pandas) | 抛明确中文错误 | + +## 8. 运行方式 + +```bash +# 直接运行(默认当月,默认目录) +python abnormal_check.py + +# 指定保存目录 + 查询整月 +python abnormal_check.py "D:\资料\人资\考勤异常" 2026-08 +``` + +> **影刀调度(已确认)**:每月 1 号 14:00-17:00 触发,需传**上月**月份参数,例如 9 月 1 日运行时传 `2026-08`。 + +```python +# 作为模块调用 +from app.service.hrbp.ehr.attendance.abnormal_check import handle_abnormal_check +path = handle_abnormal_check() # 默认当月(1日至今天) +path = handle_abnormal_check(month="2026-08") # 指定整月 +``` + +## 9. 输出文件 + +| 文件 | 内容 | +|------|------| +| `月考勤异常三查_{月份}_{时间戳}.xlsx` | 汇总 + 三个检查 Sheet(命中明细,空 Sheet 保留表头) | + +## 10. 维护注意事项 + +- **接口变更**:地址集中在 `ehr/common/config.py`(考勤/请假/加班/打卡/排班 URL)。 +- **半天判定阈值**:`HALF_DAY=0.5`,如加班天数口径变化调整此处。 +- **打卡容差**:`PUNCH_TOLERANCE_MIN=60` 分钟,按需调整以减少误报/漏报。 +- **班段解析**:`_parse_shift_time` 依赖 `"HH:MM ~ HH:MM"` 格式,班段时间格式变化需同步更新。 +- **仅检查不改数据**:本模块只输出报告,不调用确认/调整接口。 diff --git a/docs/月考勤异常处理需求文档.md b/docs/月考勤异常处理需求文档.md new file mode 100644 index 0000000..942c190 --- /dev/null +++ b/docs/月考勤异常处理需求文档.md @@ -0,0 +1,111 @@ +# EHR 系统月考勤异常处理 — 需求文档 + +> 版本:v1.1(草案) +> 状态:待评审 +> 所属模块:`app/service/hrbp/ehr/attendance/abnormal_check.py`(月考勤异常三重复核) +> 创建时间:2026-08-14 + +> **调度时间:每月 1 号 14:00-17:00 自动执行**(影刀定时任务触发)。 +> **查询范围(已确认):上月完整月份**(调度入参 `month=上月 YYYY-MM`)。 + +## 1. 背景 + +月考勤异常确认后,仍可能存在「误确认 / 漏处理」的情形。HR 需在每月 1 号(14:00-17:00)对上月考勤异常做一次三重复核,重点排查三类情况: + +1. 异常日期是否同时存在请假流程(可能存在「提前确认后请假」导致仍为考勤异常); +2. 休息日上班半天时,当日打卡是否按考勤班段正常打卡(是否存在漏打卡); +3. 员工整日请假当日,是否仍残留其他考勤异常处于确认状态。 + +自动化排查可避免人工逐人核对,确保考勤数据准确性。 + +## 2. 目标 + +- 自动拉取上月考勤异常、请假、休息日加班、打卡流水、排班数据。 +- 执行三项检查并输出多 Sheet Excel 报告,逐条给出问题说明与判定。 +- 检查结果供 HR 复核:确认是否误处理、是否需人工跟进。 + +## 3. 三项检查规则 + +### 检查1:已确认异常日期 × 请假流程 + +- 规则:`is_adjusted=2`(已确认异常)的日期,若同时存在请假流程(请假范围覆盖该日)→ 命中。 +- 原因:可能是「提前确认后请假」导致仍为考勤异常,需人工复核是否撤销/修正。 +- 输出:员工姓名、工号、考勤日期、异常类型、请假类型、请假起止、问题说明。 + +### 检查2:休息日半天加班 × 打卡校验(结合排班班段) + +- 规则:休息日加班(加班类型=3)且加班天数为 **0.5 天**的日期,校验当日打卡是否按考勤班段正常打卡。 +- 判定: + - 排班有班段时间(如 `09:00 ~ 18:00`):最早打卡覆盖班段开始、最晚打卡覆盖班段结束、且打卡次数 ≥ 2 → 正常;否则漏打卡。 + - 排班为休息日(无班段时间):按打卡次数判断(≥2 正常,1 次/0 次漏打卡)。 +- 容差:上班/下班打卡与班段边界的匹配容差默认 60 分钟,用于排除「晚到/早走导致的漏打卡误报」。 +- 输出:员工姓名、工号、加班日期、加班天数、排班班次、排班班段时间、计划时段、上班打卡、下班打卡、打卡次数、判定。 + +### 检查3:整日请假当日 × 残留考勤异常 + +- 规则:员工整日请假(`leave_days >= 1`)当日,仍存在其他考勤异常(未调整 `is_adjusted=0` 或已确认 `is_adjusted=2`)→ 命中。 +- 输出:提示「该员工 XX 日考勤状态存在异常」,并附异常类型与异常状态。 + +## 4. 数据来源 + +| 数据 | 来源 | 用途 | +|------|------|------| +| 登录态 | hr.37du.co 登录(cookies 缓存,过期自动重登) | 保证考勤接口可访问 | +| 当前用户信息 | `getCurUserInfo` | 校验 cookies,获取 userId / rootId(treecode) | +| 已确认异常 | 考勤异常接口(`is_adjusted=2`) | 检查1 | +| 未调整异常 | 考勤异常接口(`is_adjusted=0`) | 检查3 并集之一 | +| 请假记录 | 请假接口(空工号=全部员工) | 检查1 / 检查3 | +| 休息日加班 | 加班接口(类型=3,空工号=全部员工) | 检查2 | +| 打卡流水 | 打卡记录接口(按工号) | 检查2 | +| 排班 | 排班接口(按工号,取当日班段) | 检查2 | + +## 5. 输出报告 + +多 Sheet Excel:`月考勤异常三查_{月份}_{时间戳}.xlsx`,Sheet 顺序: + +| Sheet | 内容 | +|-------|------| +| 汇总 | 三项检查命中条数及备注 | +| 检查1_确认异常有请假 | 检查1 命中明细 | +| 检查2_休息日半天打卡 | 检查2 校验明细(「判定」列中「漏打卡」需人工复核) | +| 检查3_整日请假有异常 | 检查3 命中明细(含「该员工XX日考勤状态存在异常」提示) | + +> 无数据的 Sheet 也保留表头,便于对照。 + +## 6. 处理流程 + +1. **会话准备**:构建 HR 会话,`getCurUserInfo` 校验登录态。 +2. **拉取数据**:一次拉取上月已确认异常、未调整异常、全部请假、休息日加班。 +3. **检查1**:建立「请假日期索引」,逐条比对已确认异常的日期是否命中请假。 +4. **检查2**:筛出休息日半天加班,按工号拉取打卡与排班,结合班段判定是否漏打卡。 +5. **检查3**:建立「整日请假日期索引」,与未调整/已确认异常取并集比对。 +6. **导出报告**:多 Sheet Excel,输出命中明细与汇总。 +7. **复核跟进**:HR 对命中记录人工复核处理。 + +## 7. 边界与约束 + +- 调度(每月 1 号)时查询范围为**上月完整月份**(传 `month="上月 YYYY-MM"`);手动运行默认查「当月 1 日至今天」。 +- 仅做检查与输出,不自动修改/确认任何考勤异常(需人工复核)。 +- 打卡流水无法可靠区分上下班(`time_order` 多为空),按时间最早=上班、最晚=下班汇总统计。 +- 排班为休息日(无班段时间)时退化为打卡次数判断。 +- 登录态过期自动重登并续抓;导出文件被占用时提示关闭后重试。 +- 无数据时相应检查跳过并输出空 Sheet(保留表头)。 + +## 8. 实现决策(已确认,以代码实现为准) + +| 事项 | 代码实现方式 | +|------|-------------| +| 检查2识别口径 | 「休息日上班半天」以「休息日加班(加班类型=3)且加班天数=0.5 天」识别 | +| 打卡容差 | 打卡与班段边界匹配容差 60 分钟(`PUNCH_TOLERANCE_MIN`),用于排除晚到/早走导致的漏打卡误报 | +| 检查3提示方式 | 「弹出提示」实现为报告中的「提示」列,不做运行时弹窗/钉钉提醒 | +| 复核闭环 | 当前仅做检查与输出,不自动修改/确认考勤异常;命中记录由 HR 人工复核处理 | + +## 9. 交付物 + +- `app/service/hrbp/ehr/attendance/abnormal_check.py`:月考勤异常三查主流程。 +- 复用:`hr_api`(abnormal / leave / overtime / kq_data / shift)、`hr_session`、`common.config.VACATION_TYPE_MAP`。 +- 输出:`D:\资料\人资\考勤异常\月考勤异常三查_{月份}_{时间戳}.xlsx`。 + +--- + +*本需求为草案,实现决策以代码实现为准,后续需求变化再行调整。* diff --git a/docs/通用接口请求封装规划.md b/docs/通用接口请求封装规划.md deleted file mode 100644 index 92ae8dd..0000000 --- a/docs/通用接口请求封装规划.md +++ /dev/null @@ -1,109 +0,0 @@ -# 通用接口请求封装规划(待实现) - -> 状态:**规划中,尚未实现**。仅描述方案与范围,供评审后实施。 - -## 1. 背景与问题 - -当前项目中多个 API 模块存在**高度重复的「发送请求 + 校验响应」样板代码**,涉及: - -- `app/service/hrbp/ehr/common/hr_api.py` —— 基于 `requests.Session` -- `app/service/hrbp/oa/common/oa_api.py` —— 基于 DrissionPage `SessionPage` - -**重复的响应处理模板**(每个接口函数都要写一遍): - -``` -1. 判断响应是否存在 → 不存在则抛错 -2. 判断 HTTP 状态码 → 非 200 抛错 -3. 判断是否为 JSON 登录页 → 是则判登录态过期(仅 JSON 类接口) -4. 解析响应 JSON → 解析失败抛错 -``` - -这类样板在 `hr_api.py` 中已有 8 个 `fetch_*_page` / 接口函数,`oa_api.py` 中也有 6 个接口函数,均各自重复上述逻辑,维护成本高、易漏改。 - -## 2. 目标 - -- 抽取**发送/校验阶段**为项目通用能力,各接口只保留「拼参数 + 取用返回 JSON 字段」。 -- 保持各接口的**入参与返回字段解析相互独立**,互不耦合。 -- 覆盖 HR(requests)与 OA(SessionPage)两套 HTTP 客户端。 - -## 3. 方案设计 - -### 3.1 思路:只封装「发送 + 校验」,不封装业务解析 - -推荐做法(评审中):通用函数只负责「POST/GET 发出请求 → 校验状态码/登录态 → 返回解析后的 JSON」,**返回的 JSON 由各接口自行解析字段**。 - -> 依据:各接口的分页字段(`datas`、`pageCount`、`jsonList`、`data.list` 等)与成功标志(`state`、`success`、`code`)并不统一,硬抽成通用分页器反而增加耦合与判断分支;只抽「发送 + 校验」风险最低、收益最明显。 - -### 3.2 响应校验核心(两套客户端共用) - -由于 HR 与 OA 的响应对象都具备 `status_code`、`.json()`、`.text`,可抽一个**共用的响应校验函数**: - -```python -def _handle_response(resp, label): - """统一校验响应:存在性 / 状态码 / JSON 可解析性,返回解析后的 JSON。""" - if not resp: - raise RuntimeError(f"{label}请求失败,未获取到响应") - if resp.status_code != 200: - raise RuntimeError(f"{label}接口状态码异常: {resp.status_code}") - # 仅对「正常应返回 JSON」的接口做登录态过期判断(text 不以 { 或 [ 开头) - text = getattr(resp, "text", "") or "" - if text and not text.lstrip().startswith(("{", "[")): - raise SessionExpiredError(f"登录态已过期,{label}接口返回非 JSON 内容") - try: - return resp.json() - except Exception: - body = text[:200] - raise RuntimeError(f"{label}接口返回非 JSON 数据(状态码 {resp.status_code}): {body}") -``` - -### 3.3 两套客户端的薄适配层 - -请求发送方式不同,故在共用校验基础上提供两个薄发送函数(同放一个项目通用位置): - -```python -# ---- HR:requests.Session ---- -def hr_request_json(session, method, url, params, label): - resp = session.request(method, url, data=params, timeout=20) # 直接返回响应 - return _handle_response(resp, label) - -# ---- OA:DrissionPage SessionPage ---- -def oa_request_json(session, method, url, params, label): - # SessionPage 通过 session.get/post 发送,响应需从 session.response 取 - if method.upper() == "GET": - session.get(url, params=params) - else: - session.post(url, data=params) - return _handle_response(session.response, label) -``` - -> 说明:OA 某些接口用 GET+query、某些用 POST+form;HR 目前全为 POST+form。适配层暴露 `method` 以兼容两者。`_handle_response` 保持单一,避免两套各自维护。 - -### 3.4 落点 - -- 通用校验 `_handle_response` 与两个适配函数建议放:`app/service/hrbp/common/http.py`(新建)或 `app/utils/http_client.py`。 -- 若暂不新增目录,也可先放 `app/service/hrbp/oa/common/oa_api.py` 的兄弟位置,统一归口后再迁移。 - -### 3.5 改造范围(实施时) - -| 模块 | 涉及函数 | 说明 | -|------|---------|------| -| ehr/hr_api.py | `fetch_wage_card_page`、`fetch_attendance_abnormal_page`、`adjust_abnormal`、`fetch_shift_page`、`fetch_leave_page`、`fetch_cur_user_info` | 均改为 `hr_request_json(...)`,删除重复样板 | -| oa/oa_api.py | `fetch_todo_page`、`get_wf_activity_by_task_id`、`get_business_data`、`get_attendance_html`、`get_attendance_records`、`fetch_leave_record_page` | 均改为 `oa_request_json(...)`,删除重复样板 | - -> 注意:部分接口(如 `get_business_data`、`get_attendance_html`、`get_leave_records` 相关)除了校验 JSON 外,还有各自的业务成功判定(`state != "1"`、`success != "true"`、`code != 200` 等)。这些**业务级校验不并入通用函数**,保留在各接口自身,避免通用层过度耦合。 - -## 4. 不做的事(边界) - -- **不**封装通用分页器:各接口分页字段/成功标志不一,暂保持各自实现。 -- **不**改动各接口的入参与返回结构,保证对调用方(工资卡、考勤、OA 审批等流程)透明无感。 -- **不**引入新的第三方依赖。 - -## 5. 实施步骤(待评审后执行) - -1. 新建通用模块,写入 `_handle_response`、`hr_request_json`、`oa_request_json`。 -2. 依次改造 `hr_api.py`、`oa_api.py` 中各接口函数为薄调用,删除重复样板。 -3. 跑通现有测试(`tests/`)与关键流程(工资卡、考勤异常、OA 请假/加班审批)回归验证。 -4. 确认无行为差异后收尾。 - ---- -*文档状态:规划草案,待确认方案(是否只封装发送阶段、通用模块落点)后实施。* diff --git a/docs/银行卡检查开发文档.md b/docs/银行卡检查开发文档.md index 48dae4b..11676f6 100644 --- a/docs/银行卡检查开发文档.md +++ b/docs/银行卡检查开发文档.md @@ -1,8 +1,8 @@ # 银行卡检查(影刀版)— 开发文档 -> 版本:v1.0.0 +> 版本:v1.1.0 > 对应文件:`yingdao/bank_card_check_yingdao.py` -> 创建时间:2026-08-08 +> 更新日期:2026-08-14 ## 1. 概述 @@ -10,7 +10,7 @@ ``` HR 登录(滑块验证码) → 调用工资卡接口下载在职+离职工资卡数据 -→ 核对身份证/姓名/银行卡号 → 导出核对结果 + 异常名单 +→ 银行字典补充开卡银行 → 核对身份证/姓名/银行卡号 → 导出核对结果 + 无银行卡表 + 异常名单 ``` ## 2. 环境依赖 @@ -23,7 +23,7 @@ pip install DrissionPage python-dotenv requests pandas openpyxl opencv-python nu |------|------|-----------| | DrissionPage | 浏览器控制(登录、滑块验证码) | `hr_login` 抛明确错误 | | python-dotenv | 读取 `.env` 环境变量 | 静默跳过 | -| requests | 调用工资卡 HTTP 接口 | 抛明确错误 | +| requests | 调用工资卡 / 银行字典 HTTP 接口 | 抛明确错误 | | pandas / openpyxl | Excel 读写 | 抛明确错误 | | opencv-python / numpy | 滑块缺口识别 | 抛明确错误 | | Pillow | 验证码图片处理辅助 | — | @@ -36,8 +36,8 @@ pip install DrissionPage python-dotenv requests pandas openpyxl opencv-python nu |------|------|------| | `hr_login_username` | 是 | HR 登录账号 | | `hr_login_password` | 是 | HR 登录密码 | -| `hr_login_url` | 否(预留) | HR 登录页地址 | -| `hr_target_url_keyword` | 否(预留) | 登录成功 URL 关键字 | +| `hr_login_url` | 否(预留) | 文档声明预留,代码暂未读取(登录页为常量 `HR_LOGIN_URL`) | +| `hr_target_url_keyword` | 否(预留) | 文档声明预留,代码暂未读取(成功关键字为常量 `HR_SUCCESS_KEYWORD`) | | `wage_card_output_dir` | 否 | 输出目录,默认 `D:\资料\人资\银行卡检查` | 可通过 `.env` 文件(脚本目录)或系统环境变量注入,入口 `main()` 先执行 `load_dotenv()`。 @@ -48,15 +48,17 @@ pip install DrissionPage python-dotenv requests pandas openpyxl opencv-python nu |------|---------|------| | 导入与依赖降级 | — | 标准库/第三方库,缺失置 None | | 日志 | `_PrintLogger` / `logger` | 用 print 输出,替代 logging(影刀环境日志可见性) | -| 常量配置 | `_APP_DATA_DIR`、`COOKIE_FILE_HR`、`COL_MAP`、`SHOW_ORDER`、`BIN_16`、`BIN_18`、`NON62_BIN` 等 | 路径、接口地址、字段映射、校验 BIN 集合 | +| 常量配置 | `_APP_DATA_DIR`、`COOKIE_FILE_HR`、`BANK_DICT_*`、`COL_MAP`、`SHOW_ORDER`、`BIN_16`、`BIN_18`、`NON62_BIN` 等 | 路径、接口地址、字段映射、校验 BIN 集合 | | 重试装饰器 | `retry(max_attempts=3)` | 指数退避重试(2 的幂 × 随机系数),失败日志 | | Cookies 持久化 | `save_browser_cookies` / `load_cookies` / `_ensure_dir` | 保存/读取浏览器 cookies(JSON) | | HR 登录 | `hr_login` / `get_hr_session` / `_build_hr_session` / `handle_hr_captcha` / `match_slider_dual` / `generate_track` / `perform_slide` | 登录态管理 + 滑块验证码识别与拖动 | | 工资卡接口 | `fetch_wage_card_page` / `fetch_all_wage_card` / `HRSessionExpiredError` | 分页抓取工资卡数据,会话过期自动重登续抓 | +| 银行字典接口 | `_fetch_bank_dict` / `_load_bank_dict_cache` / `get_bank_dict` / `_bank_type_to_name` | BANK_TYPE 编码 → 开卡银行名称,远程拉取 + 本地缓存 | | 离职时间范围 | `get_leave_range` | 计算离职筛选日期范围 | -| Excel 导出 | `export_excel` | 在职+离职合并导出汇总表 | +| Excel 导出 | `export_excel` | 在职+离职合并导出汇总表,补充开卡银行 | | 银行卡校验 | `check_bank_card` | 单卡号校验 | -| 核对主逻辑 | `check_wage_card` | 逐行核对并输出结果 + 异常名单 | +| 核对辅助 | `_is_empty` / `_normalize_id` / `classify_card_issue` | 空值/身份证清洗、单条记录 4 类问题分类 | +| 核对主逻辑 | `check_wage_card` | 逐行核对并输出结果 + 无银行卡表 + 异常名单 | | 主流程 | `download_wage_card` / `run_bank_card_check` / `main` | 编排下载→核对→汇总 | ## 5. 核心逻辑说明 @@ -83,7 +85,16 @@ pip install DrissionPage python-dotenv requests pandas openpyxl opencv-python nu - 翻页终止条件:`page_no >= pageCount` 或返回空 `datas`。 - 每页抓取标记 `人员类型`(在职/离职),供合并展示。 -### 5.3 银行卡校验 `check_bank_card` +### 5.3 银行字典与开卡银行 + +- 接口:`POST https://hr.37du.co/RedseaPlatform/PtCodeTypeValue.mc?method=getCodeValueByCodes` +- 参数:`codeType=WAGE.BANKTYPE`、`inUse=0,1,2`、`platformMode=redseaPlatform`;响应按 `codeType` 取 `[{code, name}]`。 +- 缓存:`%LOCALAPPDATA%\37duAutomation\BankCardCheck\` 下 `bank_dict_list.json`(list)与 `bank_dict_map.json`(code→name 映射),7 天过期自动重拉。 +- 降级策略:远程拉取失败 → 读本地缓存;无缓存则返回空,`开卡银行` 置空,不阻断主流程。 +- `_bank_type_to_name`:对 `BANK_TYPE` 做 float/int/str 归一化(float 型如 `621483.0` 转 `621483`,NaN 返回空串),再查映射表。 +- 在 `export_excel` 与 `check_wage_card` 两处,汇总表缺「开卡银行」列且有「银行编码」列时自动补充。 + +### 5.4 银行卡校验 `check_bank_card` 按序判定:空白 → 非纯数字 → 62 开头或白名单 → 位数(16/18/19)→ BIN 匹配: @@ -96,15 +107,16 @@ BIN 集合来源于实际工资卡数据导出比对核验(chakahao.com 银行 返回 `{card, status, reason}` 三元组,其中 status ∈ 正常 / 无效 / 错误。 -### 5.4 核对主逻辑 `check_wage_card` +### 5.5 核对主逻辑 `check_wage_card` -- 读入汇总表,逐行取「身份证号、开户人身份证、员工姓名、开户人姓名、银行卡号」。 -- 身份证/姓名不一致时在「校验依据」列写入比对明细,仅当身份证不一致成立才比较姓名(身份证不一致则姓名不再比较)。 -- 银行卡校验独立于身份核对,状态写入「银行卡状态/银行卡说明」。 -- 「核对结果」非「通过」即判定异常,导出异常名单(`工资卡异常名单.xlsx`),无异常则不生成。 +- 读入汇总表,逐行取「身份证号、开户人身份证、员工姓名、开户人姓名、银行卡号」调用 `classify_card_issue` 分类。 +- `classify_card_issue` 按 4 类问题产出:① 开户人信息/银行卡空白;② 身份证不一致(开户人身份证非空且 ≠ 员工);③ 姓名不一致(仅身份证一致时比较);④ 银行卡信息异常(卡号非空但校验非「正常」)。 +- 「核对结果」列 = 问题拼接(`、`)或「通过」;「校验依据」列 = 明细拼接(`;`)。 +- 卡号空白(`_is_empty`)的记录单独收集到 `no_bank_rows`,导出 `无银行卡表.xlsx`(无记录则跳过)。 +- 异常名单 = 核对结果非「通过」且不在 `no_bank_rows` 中的记录,导出 `工资卡异常名单.xlsx`(无记录则跳过)。 - 核对结果输出路径默认 `{汇总表名}_核对结果.xlsx`。 -### 5.5 数据清洗 +### 5.6 数据清洗 - `_normalize_id`:float/int 转整数字符串(去除 NaN),去空格,用于身份证比对。 - `_is_empty`:识别 None / NaN / 空白串,用于空值判定。 @@ -122,9 +134,13 @@ get_hr_session → hr_cookies.json 存在? 预检(pageSize=1)→ 过期则 hr_login 重建 ↓ fetch_all_wage_card(status=1, 在职) ┐ -fetch_all_wage_card(status=2, 离职) ┴→ export_excel → 工资卡汇总表.xlsx +fetch_all_wage_card(status=2, 离职) ┴→ get_bank_dict(远程/缓存)→ 补充开卡银行 ↓ -check_wage_card → 核对结果.xlsx + 工资卡异常名单.xlsx +export_excel → 工资卡汇总表.xlsx + ↓ +check_wage_card → 工资卡汇总表_核对结果.xlsx + ├─ 无银行卡表.xlsx(有卡号空白记录时) + └─ 工资卡异常名单.xlsx(有其他异常记录时) ``` ## 7. 异常与重试策略 @@ -134,6 +150,7 @@ check_wage_card → 核对结果.xlsx + 工资卡异常名单.xlsx | 网络/接口异常 | `retry` 装饰器指数退避重试 3 次(`1s × 2^(n-1) × U(0.5,1.5)`) | | HR 会话过期 | 捕获 `HRSessionExpiredError` → 重新登录 → 重建 session → 从当前页续抓 | | 滑块验证失败 | 最多 5 次,成功后跳转或验证码容器消失即通过 | +| 银行字典拉取失败 | 降级读本地缓存;无缓存则返回空,开卡银行置空 | | 依赖缺失 | 在对应函数抛中文错误,含安装命令提示 | | 无数据 | 不导出空 Excel,抛 `ValueError` | @@ -154,14 +171,16 @@ results = run_bank_card_check() | 文件 | 内容 | |------|------| -| `工资卡汇总表.xlsx` | 在职+离职全部工资卡数据(中文字段) | +| `工资卡汇总表.xlsx` | 在职+离职全部工资卡数据(中文字段 + 开卡银行) | | `工资卡汇总表_核对结果.xlsx` | 汇总表 + 核对结果/校验依据/银行卡状态/银行卡说明 | -| `工资卡异常名单.xlsx` | 核对结果非「通过」的记录(无异常不生成) | +| `无银行卡表.xlsx` | 卡号空白的人员(有空白记录才生成) | +| `工资卡异常名单.xlsx` | 其余核对结果非「通过」的记录(含身份证不一致,无记录不生成) | ## 10. 扩展与维护注意事项 - **保持单文件自包含**:新增逻辑请勿引入项目包依赖,便于影刀与 App 共用。 - **登录选择器变更**:`LOGIN_BTN` / `ACCOUNT_INPUT_HR` 等常量集中于常量区,HR 系统改版时只需调整此处。 - **银行卡 BIN 规则更新**:改 `BIN_16` / `BIN_18` / `NON62_BIN` 集合即可,判定逻辑无需变动。 +- **银行字典缓存**:`BANK_DICT_EXPIRE_SEC` 控制缓存有效期;`get_bank_dict(force_refresh=True)` 可强制刷新。 - **字段映射变更**:改 `COL_MAP`(接口字段→中文)与 `SHOW_ORDER`(展示顺序)。 - **日志约定**:正常运行时仅输出 INFO 级关键节点,避免刷屏;滑块识别等细节属调试信息按需开启。 diff --git a/docs/银行卡检查需求文档.md b/docs/银行卡检查需求文档.md index d421d21..5d168de 100644 --- a/docs/银行卡检查需求文档.md +++ b/docs/银行卡检查需求文档.md @@ -1,13 +1,13 @@ # 银行卡检查(影刀版)— 需求文档 -> 版本:v1.0 +> 版本:v1.1 > 状态:待评审 > 所属模块:`yingdao/bank_card_check_yingdao.py`(单文件版,app 与影刀共用) -> 创建时间:2026-08-08 +> 更新日期:2026-08-14 ## 1. 背景 -HR 需要定期核对员工的工资卡信息(身份证号、姓名、银行卡号),以确保工资发放的准确性与合规性。目前该核对依赖人工从 HR 系统逐条下载、比对,工作量大且易出错,需要自动化完成「登录 → 下载 → 核对 → 输出」全流程。 +HR 需要定期核对员工的工资卡信息(身份证号、姓名、银行卡号),以确保工资发放的准确性与合规性。目前该核对依赖人工从 HR 系统逐条下载、比对,工作量大且易出错,需要自动化完成「登录 → 下载 → 补充开卡银行 → 核对 → 输出」全流程。 本模块面向影刀(RPA)环境,以单文件自包含方式实现,同时可被 App 项目目录直接调用,避免维护两套版本。 @@ -15,8 +15,9 @@ HR 需要定期核对员工的工资卡信息(身份证号、姓名、银行 - 自动登录 HR 系统(hr.37du.co),支持滑块验证码识别,并持久化登录态(cookies)。 - 自动调用工资卡接口,下载**在职 + 离职**人员的工资卡数据。 +- 自动通过银行字典接口,将**银行编码(BANK_TYPE)**补充为**开卡银行**名称。 - 自动核对每条记录的**身份证号、姓名、银行卡号**,输出核对结果与异常原因。 -- 导出三份 Excel:工资卡汇总表、核对结果表、异常名单。 +- 导出四份 Excel:工资卡汇总表、核对结果表、无银行卡表、异常名单(后两份仅在有对应记录时生成)。 ## 3. 数据来源 @@ -25,8 +26,11 @@ HR 需要定期核对员工的工资卡信息(身份证号、姓名、银行 | HR 登录态 | hr.37du.co 登录(滑块验证码)或本地缓存的 cookies | 保证工资卡查询接口可访问 | | 在职工资卡数据 | `POST https://hr.37du.co/RedseaPlatform/getPageAjax/HrStaffWageCard.mc`(status=1) | 在职人员工资卡明细 | | 离职工资卡数据 | 同上接口(status=2),按离职时间范围筛选 | 离职人员工资卡明细 | +| 银行字典 | `POST https://hr.37du.co/RedseaPlatform/PtCodeTypeValue.mc?method=getCodeValueByCodes`(codeType=`WAGE.BANKTYPE`) | 银行编码(BANK_TYPE)→ 开卡银行名称 | -> 登录态 cookies 持久化路径:`%LOCALAPPDATA%\37duAutomation\BankCardCheck\.sessions\hr_cookies.json`。 +> 缓存文件统一存放于 `%LOCALAPPDATA%\37duAutomation\BankCardCheck\`: +> - `.sessions\hr_cookies.json`:HR 登录态 cookies +> - `bank_dict_list.json` / `bank_dict_map.json`:银行字典缓存(7 天过期,自动重新拉取) ## 4. 输出字段 @@ -45,6 +49,7 @@ HR 需要定期核对员工的工资卡信息(身份证号、姓名、银行 | 组织全路径 | ORG_FULL_PATH | | 是否主卡 | IS_MAIN | | 银行编码 | BANK_TYPE | +| 开卡银行 | BANK_TYPE 经银行字典映射的银行名称(未命中为空) | | 银行卡号 | BANK_ACCOUNT | | 开户人姓名 | CARD_NAME | | 参保地点 | si_name | @@ -56,7 +61,7 @@ HR 需要定期核对员工的工资卡信息(身份证号、姓名、银行 | 字段 | 说明 | |------|------| | 核对结果 | 通过 / 具体问题(多问题以「、」分隔) | -| 校验依据 | 不一致时的比对明细(员工值 vs 开户人值) | +| 校验依据 | 问题明细(不一致时的比对值等,以「;」分隔) | | 银行卡状态 | 正常 / 无效 / 错误 | | 银行卡说明 | 银行卡校验的判定原因 | @@ -64,13 +69,13 @@ HR 需要定期核对员工的工资卡信息(身份证号、姓名、银行 ### 5.1 身份证核对 -- 开户人身份证为空 → 问题「开户人身份证为空」。 -- 员工身份证 ≠ 开户人身份证 → 问题「身份证不一致」,校验依据记录 `员工:{员工身份证} vs 开户人:{开户人身份证}`。 +- 开户人身份证为空 → 问题「开户人身份证空白」。 +- 员工身份证 ≠ 开户人身份证 → 问题「员工身份证与开户人身份证不一致」,校验依据记录 `身份证不一致(员工:{员工身份证} vs 开户人:{开户人身份证})`。 -### 5.2 姓名核对(仅在身份证一致时执行) +### 5.2 姓名核对(仅在身份证一致且开户人信息非空时执行) -- 开户人姓名为空 → 问题「开户人姓名为空」。 -- 员工姓名 ≠ 开户人姓名 → 问题「姓名不一致」,校验依据记录 `员工:{员工姓名} vs 开户人:{开户人姓名}`。 +- 开户人姓名为空 → 问题「开户人姓名空白」。 +- 员工姓名 ≠ 开户人姓名 → 问题「员工姓名与开户人姓名不一致」,校验依据记录 `姓名不一致(员工:{员工姓名} vs 开户人:{开户人姓名})`。 ### 5.3 银行卡校验 @@ -86,22 +91,29 @@ HR 需要定期核对员工的工资卡信息(身份证号、姓名、银行 | 其余 BIN 且非 19 位 | 错误 | BIN{N}标准19位,录入位数错误,需人工核对 | > 16 位/18 位 BIN 名单按实际工资卡数据导出比对核验(结合 chakahao.com 银行 BIN 库),以代码中 `BIN_16` / `BIN_18` / `NON62_BIN` 集合为准。 +> 银行卡非空但校验非「正常」时,额外产生问题「银行卡信息异常」,校验依据记录 `银行卡信息异常({判定原因})`。 -### 5.4 结果判定 +### 5.4 结果判定与分类输出 -- 核对结果 = 全部问题拼接(`、` 分隔);无问题则为「通过」。 -- 银行卡状态与说明独立判定,不参与「通过/异常」判定(「通过」仅看身份证/姓名问题)。 +- **核对结果** = 全部问题拼接(`、` 分隔);无问题则为「通过」。 +- 可能产生的问题包括:开户人身份证空白、开户人姓名空白、银行卡空白、身份证不一致、姓名不一致、银行卡信息异常。其中银行卡问题同样影响「通过」判定。 +- **银行卡状态 / 银行卡说明** 是银行卡格式校验的独立结果列,供人工复核参考。 +- 分类输出: + - **银行卡空白**(卡号空白)的记录 → 单独导出 `无银行卡表.xlsx`。 + - 其余核对结果非「通过」的记录(含身份证不一致、姓名不一致、银行卡信息异常等)→ 导出 `工资卡异常名单.xlsx`(不包含已入无银行卡表的记录)。 + - 两类文件均只有存在对应记录时才生成。 ## 6. 处理流程 -1. **登录**:优先复用本地缓存的 HR cookies;不存在或失效时执行 HR 登录(账号密码 + 滑块验证码识别)。 +1. **登录**:优先复用本地缓存的 HR cookies;不存在或失效时执行 HR 登录(账号密码 + 滑块验证码识别,最多尝试 5 次)。 2. **预检**:请求 1 条在职工资卡数据,验证登录态;过期则重新登录。 3. **抓取在职**:分页拉取在职人员工资卡数据(每页 500 条)。 4. **抓取离职**:按离职时间范围分页拉取离职工资卡数据。 -5. **导出汇总表**:合并在职 + 离职数据,字段中文化后导出 `工资卡汇总表.xlsx`。 +5. **导出汇总表**:合并在职 + 离职数据,字段中文化,并补充「开卡银行」列,导出 `工资卡汇总表.xlsx`。 6. **核对**:逐行执行身份证/姓名/银行卡校验,写入核对结果、校验依据、银行卡状态、银行卡说明。 -7. **导出核对结果**:`{汇总表}_核对结果.xlsx`。 -8. **导出异常名单**:核对结果非「通过」的记录导出为 `工资卡异常名单.xlsx`(无异常则跳过)。 +7. **导出核对结果**:`工资卡汇总表_核对结果.xlsx`。 +8. **导出无银行卡表**:卡号空白的记录导出 `无银行卡表.xlsx`(无空白记录则跳过)。 +9. **导出异常名单**:其余核对结果非「通过」的记录导出 `工资卡异常名单.xlsx`(无异常则跳过)。 ## 7. 离职筛选时间范围 @@ -115,6 +127,7 @@ HR 需要定期核对员工的工资卡信息(身份证号、姓名、银行 - 单文件自包含,可放任意目录直接运行(含 App 项目目录或影刀环境),不依赖项目包结构。 - 登录态过期时自动重新登录并续抓,不中断主流程。 - 网络/接口类操作使用指数退避重试(最多 3 次),记录告警日志。 +- 银行字典远程拉取失败时降级使用本地缓存;无缓存则「开卡银行」置空,不阻断流程。 - 依赖缺失(DrissionPage / opencv / pandas 等)时抛出明确的中文错误提示,不静默失败。 - 未查询到任何数据时不生成空 Excel。 - 滑块验证最多尝试 5 次,全部失败则登录报错。 @@ -122,11 +135,12 @@ HR 需要定期核对员工的工资卡信息(身份证号、姓名、银行 ## 9. 交付物 -- `yingdao/bank_card_check_yingdao.py`:完整主流程(登录、下载、核对、导出)。 -- 输出文件(目录可配置): +- `yingdao/bank_card_check_yingdao.py`:完整主流程(登录、下载、补充开卡银行、核对、导出)。 +- 输出文件(目录可配置,默认 `D:\资料\人资\银行卡检查`): - `工资卡汇总表.xlsx` - `工资卡汇总表_核对结果.xlsx` - - `工资卡异常名单.xlsx` + - `无银行卡表.xlsx`(存在卡号空白记录时生成) + - `工资卡异常名单.xlsx`(存在其他异常记录时生成) --- diff --git a/docs/门店上月请休假异常名单需求.md b/docs/门店上月请休假异常名单需求.md index 3bd91f7..8dc2541 100644 --- a/docs/门店上月请休假异常名单需求.md +++ b/docs/门店上月请休假异常名单需求.md @@ -103,13 +103,14 @@ HR 需要按月梳理门店人员「请休假异常」名单:从**上月最后 | Q6 在职/离职范围 | 包含所有人员 | | Q7 跨月连续未出勤 | 不涉及(数据只取上月) | | Q8 多段未出勤 | 不关心出勤段,取最长连续未出勤段 | +| Q9 花名册字段 | 「员工基础信息」模板已确认包含名单所需全部字段:二级部门(经营中心)、三级部门(片区)、四级部门(门店)、工号、姓名、手机号码、岗位、技师工号、参保类型、入职时间 | > 结论均已确认,可进入实现。 ## 9. 交付物 - `absence/absence_analysis.py` 主流程:花名册 + 出勤 + 请假 → 名单 Excel。 -- 复用:roster_export、hr_api(leave)、oa_api(attendance)、session_manager。 +- 复用:roster_export、hr_api(abnormal / leave)、hr_session。 - 输出:`D:\资料\人资\请休假异常\门店上月请休假异常名单_YYYYMM.xlsx`(待定)。 --- diff --git a/docs/雇主险名额调度开发文档.md b/docs/雇主险名额调度开发文档.md new file mode 100644 index 0000000..dde0844 --- /dev/null +++ b/docs/雇主险名额调度开发文档.md @@ -0,0 +1,226 @@ +# 雇主险名额调度系统 — 开发文档 + +> 版本:v2.0.0 +> 对应文件: +> - app 版:`app/service/hrbp/ehr/employer_insurance/`(config.py / roster_filter.py / employer_insurance.py) +> - 影刀版:`yingdao/employer_insurance/`(roster_export_yingdao.py / roster_filter_yingdao.py / employer_insurance_schedule_yingdao.py) +> 更新日期:2026-08-14 + +## 1. 概述 + +雇主险名额调度系统用于每月自动完成雇主责任险的增减员名额调度。整体为「三步走」流程: + +``` +步骤1 导出花名册(源表缺失时)→ 步骤2 筛选复制 →(人工刷新公式)→ 步骤3 调度 +``` + +系统分 **app 版** 与 **影刀版** 两套实现,业务逻辑完全一致;app 版依赖项目包结构(公共日志、公共配置),影刀版为单文件自包含(print 日志、懒加载依赖、环境变量可配),便于 RPA 环境直接运行。 + +## 2. 环境依赖 + +### 2.1 app 版 + +依赖项目 `requirements.txt`,关键库: + +| 依赖 | 用途 | +|------|------| +| pandas | 读取花名册 / 在参名单业务数据 | +| openpyxl | 原地更新目标文件、复制样式、精细更新变更清单 | +| app.utils.logger | 日志(INFO 级关键节点) | + +### 2.2 影刀版 + +```bash +pip install pandas openpyxl # 筛选复制 / 调度 +pip install DrissionPage python-dotenv requests opencv-python numpy Pillow # 仅导出步骤需要 +``` + +第三方库采用「try-import 懒加载」:缺失时不导入崩溃,在真正用到的函数处抛出中文错误提示。 + +### 2.3 影刀版环境变量 + +| 变量 | 必填 | 说明 | +|------|------|------| +| `hr_login_username` / `hr_login_password` | 导出步骤必须 | HR 登录账号密码(滑块验证码自动识别) | +| `employer_insurance_base_dir` | 否 | 文件目录,默认 `D:\资料\人资\雇主险` | +| `roster_template` | 否 | 导出模板名,默认「雇主险增减员导出模板」 | +| `roster_statuses` | 否 | 在职状态,默认「在职」 | +| `roster_output_path` | 否 | 合并后源表保存路径,默认 `D:\资料\人资\雇主险\员工花名册.xlsx` | +| `roster_download_dir` | 否 | 浏览器下载临时目录 | +| `roster_filter_export_on_missing` | 否 | 源表缺失时是否自动导出(默认 true) | + +## 3. 代码结构 + +### 3.1 app 版 + +| 文件 | 职责 | +|------|------| +| `config.py` | 集中管理:文件路径(BASE_DIR / TARGET_FILE / OUTPUT_IN_PARAM)、Sheet 名称、花名册列名映射、数据起始行、校验常量、功能开关(ENABLE_VALIDATION)、导出模板常量 | +| `roster_filter.py` | 步骤2 筛选复制:`filter_and_copy_roster()`(读取源表→过滤→写入目标表)、`export_roster_for_employer_insurance()`(按需复用 roster_export 导出) | +| `employer_insurance.py` | 步骤3 调度:`validate_biz_data()` / `initialize()` / `process_business()` / `allocate_slots()` / `output_results()` / `main()` | + +### 3.2 影刀版(单文件自包含) + +| 文件 | 职责 | +|------|------| +| `roster_export_yingdao.py` | 步骤1 导出:HR 登录(滑块验证码)→ 花名册自定义导出「雇主险增减员导出模板」→ 合并下载文件为统一格式源表 | +| `roster_filter_yingdao.py` | 步骤2 筛选复制:与 app 版 `roster_filter.py` 逻辑一致 | +| `employer_insurance_schedule_yingdao.py` | 步骤3 调度:与 app 版 `employer_insurance.py` 逻辑一致 | + +## 4. 核心逻辑说明 + +### 4.1 步骤2 筛选复制(roster_filter) + +- **源表定位表头**:先 `read_excel(header=None, nrows=8)` 探测,找到 B 列=「所属单位」的行作为表头行(兼容源表第一行标题)。 +- **数据边界**:以 B 列(所属单位)最后非空行为边界;取 B~O 共 14 列业务列(「类型」列在末尾不影响)。 +- **过滤规则**:排除 `金色湖畔事业部 / 秒创传媒事业部 / 水庄大鹅事业部`,且排除一级部门「虚拟大区」。 +- **写目标表**:Sheet「花名册导出-雇主险使用基础信息」表头第 4 行、数据第 5 行起 B~O 覆盖写入;仅清空「超出新数据」的旧行(先找旧最后非空行),避免大范围逐格清空。 +- **导出触发**:`--export-roster` 参数或源表缺失时,调用 `export_roster`(复用 roster_export,模板与在职状态取自公共配置)输出到本场景目录。 + +### 4.2 步骤3 调度(employer_insurance) + +#### 4.2.1 数据读取与清洗(main) + +- `biz_df = read_excel(..., header=3)`:表头第 4 行; +- 清洗:过滤证件号为空、方案处理为「/」的行; +- `in_param_df = read_excel(..., header=5)`:在参名单表头第 6 行; +- 文件与必需 Sheet(花名册、在参名单)缺失时终止。 + +#### 4.2.2 数据校验 validate_biz_data + +逐行校验(错误行号 = idx + 5): + +1. 工种类别 ∈ {一类, 二类, 三类, 四类}; +2. 方案处理=「增加投保」时,投保方案 ∈ {人保-20万, 人保-50万, 人保-80万}。 + +错误收集为 `{行号, 员工ID, 错误类型, 详情}` 列表,非空即终止流程。由 `ENABLE_VALIDATION` 开关控制(默认 False)。 + +#### 4.2.3 阶段0 初始化 initialize + +从在参名单构建三个数据结构(列索引 0-based:K=10 证件号 / M=12 当前投保方案 / R=17 方案处理): + +| 结构 | 构建规则 | +|------|----------| +| `idle_pools` | 方案处理=「离职减少」/「参保减少」且方案非空 → 按方案入池,记来源类型 | +| `employee_map` | 方案处理 ∈ {无需, 档次替换} 且方案非空 → 证件号→投保方案 | +| `pending_queues` | 初始为空 | + +空闲池按来源优先级排序:离职减少(1) > 参保减少(2)。 + +#### 4.2.4 阶段1 处理业务 process_business + +- **增加投保**:`groupby(投保方案)` 批量入队;方案为空 → 逐条「非法事件跳过」。 +- **要替换**:逐行处理,前提校验(已参保、目标方案非空)失败则「非法事件跳过」;成功则:原方案池追加「档次替换迁出」名额 → 重新排序(离职减少>参保减少>档次替换迁出)→ 员工置 `employee_map[emp]=None` → 进入目标方案队列。 +- **其他**:未知业务类型逐条「非法事件跳过」。 + +所有处理写入 `change_log`(员工ID / 操作 / 详情 / 时间)。 + +#### 4.2.5 阶段2 分配名额 allocate_slots + +对 `idle_pools ∪ pending_queues` 的全部方案,逐个处理队列: + +- 已参保员工 → 「非法事件跳过」(防重复参保); +- 有空闲名额 → `pool.pop(0)` 复用,记录来源员工到 `reused_source_employees`; +- 无空闲名额 → 全新新增。 + +产出 `final_records`(证件号 / 投保方案 / 参保状态=正常参保 / 名额来源 / 来源员工ID)与 `change_log`。 + +#### 4.2.6 阶段3 输出 output_results + +**在参名单(Sheet「手动维护-在参名单」,第 17 行起 B~N 列):** + +1. 构建需清空集合:`final_records` 证件号 ∪ `reused_source_employees`; +2. 保留行:「无需」且不在清空集合;「离职减少/参保减少」且未被复用; +3. 读现有行(1~26 列)→ 打标 keep / clear(仅清空 B~N 索引 1~13,R/S 不动); +4. 新参保记录优先填充 clear 空行,不足则复制末行样式追加新行(O~Z 列沿用上一条); +5. 更新现有行 B~N(列号 = 索引+1)、追加新行、重排 A 列序号。 + +**变更清单(Sheet「37度-雇员变更清单-月.日」,第 3 行起 B/N/P~S 列):** + +- Sheet 缺失时复制最近历史模板(前缀 `CHANGE_SHEET_PREFIX`,正则解析「月.日」后缀取最近),无模板则建兜底表头; +- 清空 B(2)、N(14)、P~S(16~19) 列后重写: + - **删除记录**:清空集合中不在最终参保名单的员工(曾参保标记来自在参名单初始「无需/档次替换」); + - **修改/增加记录**:`op = "修改" if 曾参保 else "增加"`,从花名册取姓名/证件号/工种类别/投保方案; + - 信息不完整(姓名/证件号/类别/方案任一为空)则跳过并告警。 + +**备份:** `final_records` 导出 `新在参名单-YYYY.MM.DD.xlsx`。 + +### 4.3 步骤1 导出(影刀版 roster_export_yingdao) + +复用影刀版登录与花名册导出通用能力(滑块验证码识别、cookies 复用、自定义导出模板操作),输出统一规范源表:单 sheet、保留第 2 行表头、业务列 B~O、「类型」列在末尾,与 app 版 roster_export 合并输出一致。 + +## 5. 数据流 + +``` +(源表缺失时)roster_export 导出 → 员工花名册.xlsx + ↓ +步骤2 roster_filter:定位表头 → 过滤事业部/虚拟大区 → 写入目标表 B~O(第5行起) + ↓ +人工打开目标文件刷新公式(Ctrl+S)保存 + ↓ +步骤3 employer_insurance(main) + ├─ 文件/Sheet 检查 → 读取 biz_df / in_param_df + ├─ 校验 validate_biz_data(开关) + ├─ 阶段0 initialize → idle_pools / employee_map / pending_queues + ├─ 阶段1 process_business → pending_queues 填充 / 名额池扩充 / change_log + ├─ 阶段2 allocate_slots → final_records / reused_source_employees + └─ 阶段3 output_results + ├─ 更新在参名单(B~N,第17行起) + ├─ 精细更新变更清单(B/N/P~S,第3行起) + └─ 备份新在参名单-YYYY.MM.DD.xlsx +``` + +## 6. 运行方式 + +### 6.1 app 版 + +```bash +# 步骤2:筛选复制(源表缺失时自动导出) +python app/service/hrbp/ehr/employer_insurance/roster_filter.py + +# 步骤3:调度(先手动刷新目标文件公式) +python app/service/hrbp/ehr/employer_insurance/employer_insurance.py +``` + +### 6.2 影刀版 + +```bash +python roster_export_yingdao.py # 步骤1:导出花名册(源表缺失时) +python roster_filter_yingdao.py # 步骤2:筛选复制 +python employer_insurance_schedule_yingdao.py # 步骤3:调度 +``` + +均为直接执行即可,无需命令行参数。 + +## 7. 输出文件 + +| 文件 | 内容 | +|------|------| +| `三十七度-雇主险变更记录-YYYY.MM.DD.xlsx`(原地更新) | 花名册数据 + 更新后的在参名单 + 重写后的变更清单 | +| `新在参名单-YYYY.MM.DD.xlsx` | 本次调度最终参保记录(证件号/投保方案/参保状态/名额来源/来源员工ID) | +| `员工花名册.xlsx` | 步骤1 导出 / 步骤2 读取的源表(本场景目录) | + +## 8. 异常与边界处理 + +| 场景 | 策略 | +|------|------| +| 目标文件不存在 / 缺必需 Sheet | 终止流程,ERROR 日志提示先准备文件 | +| 源表不存在 | 步骤2 自动触发导出;导出失败抛 `FileNotFoundError` | +| 源表无表头行(B列≠「所属单位」)| 抛 `ValueError` | +| 源表列数不足 | 抛 `ValueError`(需 B~O 14 列) | +| 数据校验失败 | 终止流程,逐条输出错误(行号/员工ID/错误类型/详情) | +| 员工在花名册中找不到 | 跳过该条参保记录并告警 | +| 变更记录信息不完整 | 跳过该条并告警 | +| 已参保员工重复参保 / 未参保员工要替换 / 方案为空 | 记录「非法事件跳过」,不影响整体 | +| 变更清单无历史模板 | 创建兜底表头(含「公式」占位) | +| 影刀版依赖缺失 | 在对应函数抛中文错误并提示安装命令 | + +## 9. 扩展与维护注意事项 + +- **路径/Sheet/列名集中管理**:app 版改 `config.py`,影刀版改文件顶部常量区即可,业务逻辑无需变动。 +- **校验开关**:`ENABLE_VALIDATION` 控制数据校验是否启用;默认关闭为测试模式,上线建议开启。 +- **两套版本同步**:app 版与影刀版调度/筛选逻辑保持一致,改动需同步两处(影刀版为单文件自包含,可整体复制粘贴)。 +- **导出模板变更**:改 `ehr/common/config.py` 的 `ROSTER_TEMPLATE_EMPLOYER_INSURANCE`,或影刀版 `roster_template` 环境变量。 +- **排除事业部变更**:改 `roster_filter.py` / 影刀版源表配置区的 `EXCLUDE_DEPT` / `EXCLUDE_REGION`。 +- **公式刷新依赖**:openpyxl 写入会丢失公式缓存结果,调度步骤必须前置人工刷新公式(Ctrl+S)。 +- **日志约定**:正常运行时仅输出 INFO 级关键节点;变更日志(change_log)为内存数据结构,仅供调试扩展,不落盘。 diff --git a/docs/雇主险名额调度需求文档.md b/docs/雇主险名额调度需求文档.md new file mode 100644 index 0000000..a483275 --- /dev/null +++ b/docs/雇主险名额调度需求文档.md @@ -0,0 +1,161 @@ +# 雇主险名额调度系统 — 需求文档 + +> 版本:v2.0.0 +> 状态:待评审 +> 所属模块:`app/service/hrbp/ehr/employer_insurance/`(app 版)+ `yingdao/employer_insurance/`(影刀版) +> 更新日期:2026-08-14 + +## 1. 背景 + +公司为员工购买雇主责任险,名额(承保额度档位)是有限资源,按「人保-20万 / 人保-50万 / 人保-80万」三档投保。每月需要根据花名册中的增减员信息,在既有参保员工(在参名单)基础上进行名额调度: + +- 新员工入职 → **增加投保**(复用已离职/减员释放的名额,或新增名额); +- 员工升档/降档 → **要替换**(档次替换迁出原名额,再迁入新档位); +- 员工离职 → **离职减少**(释放名额); +- 主动减保 → **参保减少**(释放名额)。 + +目前该流程依赖人工在 Excel 中逐条比对、挪动名额并维护「雇员变更清单」,工作量大、易出错。需要自动化完成「导出花名册 → 筛选复制 → 名额调度 → 更新在参名单与变更清单」的全流程。 + +本模块同时提供 **app 版**(依赖项目包结构)与 **影刀版**(单文件自包含,供 RPA 环境使用)两套实现,业务逻辑完全一致。 + +## 2. 目标 + +- 自动从 HR 系统导出花名册(仅在职人员),并筛选复制到雇主险变更记录表。 +- 读取花名册业务数据(增加投保 / 要替换)与在参名单(当前参保状态、空闲名额)。 +- 自动完成三阶段名额调度:**初始化 → 处理业务 → 分配名额**。 +- 自动更新「手动维护-在参名单」与「37度-雇员变更清单」,并备份新在参名单。 +- 结果与原业务人员人工维护口径一致,可复核、可回溯。 + +## 3. 数据来源 + +| 数据 | 来源 | 用途 | +|------|------|------| +| 员工花名册 | HR 系统「雇主险增减员导出模板」导出(源表缺失时自动导出) | 筛选复制的源数据 | +| 雇主险变更记录表 | 用户每日准备的目标文件 `三十七度-雇主险变更记录-YYYY.MM.DD.xlsx` | 承载花名册业务数据、在参名单、变更清单 | + +### 3.1 输入文件结构(目标文件) + +| Sheet | 表头行 | 数据起始行 | 说明 | +|-------|--------|------------|------| +| 花名册导出-雇主险使用基础信息 | 第 4 行 | 第 5 行 | 花名册业务数据(B~O 共 14 列业务列 + P/W 等公式列) | +| 手动维护-在参名单 | 第 6 行 | 第 17 行 | 当前参保名单与空闲名额标记 | +| 37度-雇员变更清单-月.日 | 2 行 | 第 3 行 | 上报给保险公司的变更清单(含公式) | + +### 3.2 关键字段(花名册业务数据) + +| 字段 | 列 | 说明 | +|------|----|------| +| 证件号 | O 列 | 员工唯一标识 | +| 工种类别 | P 列 | 一类 / 二类 / 三类 / 四类 | +| 投保方案 | Q 列 | 人保-20万 / 人保-50万 / 人保-80万 | +| 方案处理 | W 列 | 增加投保 / 要替换 / / | + +### 3.3 在参名单「方案处理」取值(R 列,第 17 行起) + +| 取值 | 含义 | +|------|------| +| 无需 | 正常参保,名额占用中 | +| 档次替换 | 待替换,仍视为当前已参保 | +| 离职减少 | 名额释放(离职) | +| 参保减少 | 名额释放(主动减保) | +| / 或空 | 忽略 | + +## 4. 业务规则 + +### 4.1 名额池与状态 + +调度前从在参名单构建三组核心状态: + +1. **空闲名额池**:按投保方案分组,来源为「离职减少」与「参保减少」的员工; +2. **当前参保映射**:证件号 → 投保方案(「无需」与「档次替换」均视为已参保); +3. **待转入队列**:初始为空,按投保方案分组。 + +### 4.2 业务处理 + +- **增加投保**(批量):按投保方案分组加入待转入队列;投保方案为空则记录「非法事件跳过」。 +- **要替换**(逐行): + - 员工必须当前已参保,否则「非法事件跳过」; + - 目标方案为空则「非法事件跳过」; + - 原方案产生「档次替换迁出」名额,员工置为未参保,进入目标方案待转入队列。 +- **其他未知类型**:记录「非法事件跳过」。 + +### 4.3 名额分配 + +逐个方案处理待转入队列: + +1. 队列中员工必须未参保,否则「非法事件跳过」(防重复参保); +2. **有空闲名额 → 复用**(记录名额来源与来源员工); +3. **无空闲名额 → 全新新增**。 + +### 4.4 名额复用优先级 + +同一方案下的空闲名额按来源排序:**离职减少 > 参保减少 > 档次替换迁出**。 + +### 4.5 数据校验(可开关) + +| 校验项 | 规则 | +|--------|------| +| 工种类别 | 必须为:一类 / 二类 / 三类 / 四类 | +| 投保方案 | 「增加投保」时投保方案必须为:人保-20万 / 人保-50万 / 人保-80万 | + +> 校验失败时终止流程并逐条输出错误(行号 / 员工ID / 错误类型 / 详情)。由开关 `ENABLE_VALIDATION` 控制,默认关闭(测试模式)。 + +## 5. 处理流程 + +1. **步骤1-导出**(源表缺失时):HR 登录 → 花名册页 → 组织机构(集团)→ 在职状态=在职 → 自定义导出「雇主险增减员导出模板」→ 下载保存为 `员工花名册.xlsx`。 +2. **步骤2-筛选复制**:读取源表(自动定位表头行)→ 排除指定事业部与「虚拟大区」→ 复制 B~O 列到目标表「花名册导出-雇主险使用基础信息」(覆盖写入,清空超出新数据的旧行)。 +3. **人工刷新公式**:手动打开目标文件,刷新公式计算结果(Ctrl+S 保存),确认无误。 +4. **步骤3-调度**: + - 校验文件与必需 Sheet 存在; + - 读取并清洗花名册数据(过滤证件号为空 / 方案处理为「/」); + - 数据校验(开关控制); + - 阶段0 初始化 → 阶段1 处理业务 → 阶段2 分配名额; + - 阶段3 输出:更新在参名单、精细更新变更清单、备份新在参名单。 + +## 6. 输出 + +| 输出 | 说明 | +|------|------| +| 目标文件原地更新 | ①「手动维护-在参名单」第 17 行起 B~N 列更新;②「37度-雇员变更清单-月.日」仅清空并重写 B/N/P~S 列数据 | +| `新在参名单-YYYY.MM.DD.xlsx` | 备份本次调度最终参保记录(证件号 / 投保方案 / 参保状态 / 名额来源 / 来源员工ID) | + +### 6.1 在参名单更新规则 + +- **保留**:「无需」且未发生变更的员工;「离职减少 / 参保减少」但名额未被复用的员工; +- **清空**:参与本次参保(复用或新增)的员工、被复用名额的来源员工、空行 —— 清空 B~N 列,R/S 列不动; +- **填充**:新参保记录填充到清空行(优先),不足则复制末行样式追加新行; +- 重新编号 A 列序号。 + +### 6.2 变更清单更新规则 + +- Sheet 不存在时,优先复制最近一次历史模板(名称前缀「37度-雇员变更清单」,按「月.日」后缀取最近),无模板则创建兜底表头; +- 清空 B 列、N 列、P~S 列(第 3 行起)后重写: + - **删除记录**:被清空且不在最终参保名单中的员工; + - **修改/增加记录**:最终参保名单中的员工(曾参保→「修改」,新参保→「增加」); + - B 列写批改标志,N 列写批改日期(当日),P~S 列写姓名 / 证件号 / 工种类别 / 投保方案。 + +## 7. 边界与约束 + +- 目标文件必须由用户每日准备,命名 `三十七度-雇主险变更记录-YYYY.MM.DD.xlsx`,缺文件或缺必需 Sheet 时流程终止并提示。 +- 源表(员工花名册)统一格式:单 sheet、自动定位表头行(B 列=「所属单位」)、业务列 B~O 共 14 列。 +- 筛选排除的固定事业部:金色湖畔事业部、秒创传媒事业部、水庄大鹅事业部;排除一级部门「虚拟大区」。 +- openpyxl 写入后公式列缓存结果会丢失,必须在调度前人工刷新公式(Ctrl+S)。 +- 员工在花名册中找不到时跳过该条参保记录并告警;变更记录信息不完整时跳过并告警。 +- 数据校验失败时终止调度,需人工修正后重跑。 +- 影刀版单文件自包含,不依赖项目包结构;app 版依赖项目路径与公共日志/配置模块。 + +## 8. 交付物 + +- app 版:`app/service/hrbp/ehr/employer_insurance/` + - `config.py`:路径、Sheet 名、列名映射、校验常量、功能开关 + - `roster_filter.py`:步骤2 筛选复制(含按需导出) + - `employer_insurance.py`:步骤3 调度(校验/初始化/业务处理/分配/输出) +- 影刀版:`yingdao/employer_insurance/` + - `roster_export_yingdao.py`:步骤1 导出花名册 + - `roster_filter_yingdao.py`:步骤2 筛选复制 + - `employer_insurance_schedule_yingdao.py`:步骤3 调度 +- 输出文件:目标文件原地更新 + `新在参名单-YYYY.MM.DD.xlsx` 备份。 + +--- + +*本需求为草案,规则细节以实际运行验证为准。* diff --git a/yingdao/leave_approval_yingdao.py b/yingdao/leave_approval_yingdao.py index d57f8a6..6ac4e74 100644 --- a/yingdao/leave_approval_yingdao.py +++ b/yingdao/leave_approval_yingdao.py @@ -1083,6 +1083,81 @@ def push_report(report, subject=""): return False +# ==================== 真实审批提交 ==================== +# 影刀环境无 .env 文件,开关直接写死在代码中;如需临时关闭自动审批改为 False +APPROVE_ENABLED = True +# 审批按钮:通过->同意(#chooseSubmit),驳回->退回申请人(#backApplySubmit) +_APPROVE_BUTTONS = { + "通过": ("#chooseSubmit", "同意"), + "驳回": ("#backApplySubmit", "退回申请人"), +} + + +def _find_button(page, selector, timeout=3.0): + """在详情页查找审批按钮:优先主文档,找不到则遍历 iframe(部分详情页按钮在 iframe 内)。""" + try: + btn = page.ele(selector, timeout=timeout) + if btn: + return btn + except Exception: + pass + try: + frames = page.get_frames() + except Exception: + frames = [] + for frame in frames: + try: + btn = frame.ele(selector, timeout=1) + if btn: + return btn + except Exception: + continue + return None + + +def submit_approval(page, decision): + """ + 按校验结论在流程详情页执行真实审批提交。 + + Args: + page: 停留在详情页的 ChromiumPage + decision: 校验决策(通过/驳回;其余决策不提交) + + Returns: + {"action": "同意"/"退回申请人"/"-", "ok": "true"/"false", "message": ...} + """ + if decision not in _APPROVE_BUTTONS: + return {"action": "-", "ok": "true", "message": "无需提交"} + selector, label = _APPROVE_BUTTONS[decision] + try: + btn = _find_button(page, selector) + if btn is None: + msg = f"未找到审批按钮 {selector}({label}),可能页面未加载完成或按钮在未识别的 iframe 中" + logger.error(msg) + return {"action": label, "ok": "false", "message": msg} + logger.info("点击审批按钮: %s(%s)", selector, label) + btn.click() + # 点击弹出的确认框"确定"按钮(同意/驳回共用同一确认框,仅标题不同)。 + # 确认框由 rsMessageBox.confirm 点击后动态生成(modal 渐入动画),轮询等待其出现 + confirm = None + for _ in range(10): + confirm = _find_button(page, "#custom-confirm-modal-ok", timeout=1) + if confirm: + break + time.sleep(0.5) + if confirm is None: + msg = "未找到确认框确定按钮 #custom-confirm-modal-ok,审批未提交" + logger.error(msg) + return {"action": label, "ok": "false", "message": msg} + confirm.click() + logger.info("已点击确认框确定按钮") + time.sleep(1.0) + return {"action": label, "ok": "true", "message": f"已执行审批提交[{label}]"} + except Exception as e: + logger.error("审批提交失败[%s]: %s", label, str(e)) + return {"action": label, "ok": "false", "message": f"审批提交[{label}]失败: {e}"} + + def run_flow(subject, validate_doc, generate_report): logger.info("%s审批流程开始", subject) @@ -1096,9 +1171,20 @@ def run_flow(subject, validate_doc, generate_report): try: doc_detail = _fetch_doc_detail(browser, session, doc) result = validate_doc(doc_detail, session) + # 真实审批提交:仅当 APPROVE_ENABLED=True 时执行(默认关闭) + # 与加班共用同一开关(公共审批引擎亦如此),驳回暂不自动处理(保留待人工复核),仅对"通过"提交真实审批 + if APPROVE_ENABLED: + if result.get("decision") == "通过": + submit = submit_approval(browser, result.get("decision")) + result["审批动作"] = submit["action"] + result["审批结果"] = f"{'成功' if submit['ok'] == 'true' else '失败'},{submit['message']}" + logger.info("审批提交: %s %s", submit["action"], result["审批结果"]) + else: + logger.info("决策为%s,暂不自动提交审批(待人工处理)", result.get("decision")) results.append(result) logger.info("已校验: %s - %s -> %s", result["creator"], result["title"], result["decision"]) # 弹出结果提示:通过=绿勾,其余(驳回/人工复核/失败)=红叉,停留便于演示 + # 必须放在审批提交之后:全屏弹窗会遮挡审批按钮,导致真实点击被拦截 try: show_rpa_result_popup( browser, @@ -1414,6 +1500,8 @@ def generate_report(results): lines.append(f" {detail}") if note: lines.append(f" 备注: {note}") + if r.get("审批动作"): + lines.append(f" 审批动作: {r['审批动作']}({r.get('审批结果', '')})") lines.append("") # ----- 驳回清单 ----- diff --git a/yingdao/overtime_approval_yingdao.py b/yingdao/overtime_approval_yingdao.py index 3087599..635df07 100644 --- a/yingdao/overtime_approval_yingdao.py +++ b/yingdao/overtime_approval_yingdao.py @@ -43,6 +43,9 @@ try: except ImportError: load_dotenv = lambda *args, **kwargs: None +# 模块加载时即读取 .env,避免复用已保存会话(跳过 oa_login)时环境变量未加载 +load_dotenv() + # 钉钉推送依赖(懒加载,缺失时给出清晰提示) try: import pyautogui @@ -1034,7 +1037,9 @@ def push_report(report, subject=""): return False -# ==================== 真实审批提交(默认关闭) ==================== +# ==================== 真实审批提交 ==================== +# 影刀环境无 .env 文件,开关直接写死在代码中;如需临时关闭自动审批改为 False +APPROVE_ENABLED = True # 审批按钮:通过->同意(#chooseSubmit),驳回->退回申请人(#backApplySubmit) _APPROVE_BUTTONS = { "通过": ("#chooseSubmit", "同意"), @@ -1086,8 +1091,14 @@ def submit_approval(page, decision): return {"action": label, "ok": "false", "message": msg} logger.info("点击审批按钮: %s(%s)", selector, label) btn.click() - # 点击弹出的确认框"确定"按钮(同意/驳回共用同一确认框,仅标题不同) - confirm = _find_button(page, "#custom-confirm-modal-ok", timeout=3) + # 点击弹出的确认框"确定"按钮(同意/驳回共用同一确认框,仅标题不同)。 + # 确认框由 rsMessageBox.confirm 点击后动态生成(modal 渐入动画),轮询等待其出现 + confirm = None + for _ in range(10): + confirm = _find_button(page, "#custom-confirm-modal-ok", timeout=1) + if confirm: + break + time.sleep(0.5) if confirm is None: msg = "未找到确认框确定按钮 #custom-confirm-modal-ok,审批未提交" logger.error(msg) @@ -1114,7 +1125,18 @@ def run_flow(subject, validate_doc, generate_report): try: doc_detail = _fetch_doc_detail(browser, session, doc) result = validate_doc(doc_detail, session) + # 真实审批提交:仅当 APPROVE_ENABLED=True 时执行(默认关闭) + if APPROVE_ENABLED: + # 驳回暂不自动处理(保留待人工复核),仅对"通过"提交真实审批 + if result.get("decision") == "通过": + submit = submit_approval(browser, result.get("decision")) + result["审批动作"] = submit["action"] + result["审批结果"] = f"{'成功' if submit['ok'] == 'true' else '失败'},{submit['message']}" + logger.info("审批提交: %s %s", submit["action"], result["审批结果"]) + else: + logger.info("决策为%s,暂不自动提交审批(待人工处理)", result.get("decision")) # 弹出结果提示:通过=绿勾,其余(驳回/人工复核/失败)=红叉,停留便于演示 + # 必须放在审批提交之后:全屏弹窗会遮挡审批按钮,导致真实点击被拦截 try: show_rpa_result_popup( browser, @@ -1123,12 +1145,6 @@ def run_flow(subject, validate_doc, generate_report): ) except Exception: pass - # 真实审批提交:仅当 overtime_approve_enabled=true 时执行(默认关闭) - if os.getenv("overtime_approve_enabled", "false").lower() == "true": - submit = submit_approval(browser, result.get("decision")) - result["审批动作"] = submit["action"] - result["审批结果"] = f"{'成功' if submit['ok'] == 'true' else '失败'},{submit['message']}" - logger.info("审批提交: %s %s", submit["action"], result["审批结果"]) results.append(result) logger.info("已校验: %s - %s -> %s", result["creator"], result["title"], result["decision"]) except Exception as e: @@ -1304,6 +1320,8 @@ def _validate_delayed(info, punch, session, staff_id): end = _parse_dt(info.get("加班结束时间")) actual_checkout = _parse_dt(punch.get("当日最晚打卡")) reasons = [] + # 申请结束时间晚于实际下班打卡、但实际在岗时长(按系统取整)仍满足申请时长时,用于附加到通过备注 + end_checkout_note = "" # 1. 日期校验:加班开始日期与申请加班日期不一致时直接驳回, # 无需再校验后续的时长、区间合规等内容 @@ -1353,8 +1371,23 @@ def _validate_delayed(info, punch, session, staff_id): if end is not None: if actual_checkout is None: reasons.append("当日无下班打卡记录,无法校验区间合规") - elif end > actual_checkout: - reasons.append(f"申请结束时间({end:%H:%M})晚于实际下班打卡时间({actual_checkout:%H:%M:%S})") + elif start is not None and hours is not None: + # 核心原则:申请的加班时长必须与打卡可支撑的实际在岗时长相符。 + # 按系统取整规则(_calc_delayed_hours),用实际打卡区间(申请开始->实际下班打卡) + # 计算实际在岗时长,>= 申请时长即通过(申请结束时间比打卡晚几分钟也属正常)。 + # 例:申请 18:00-23:05(取整5h),实际打卡23:00:45,实际在岗取整后也是5h,应通过 + actual_hours = _calc_delayed_hours(start, actual_checkout) + if actual_hours >= hours: + if end > actual_checkout: + end_checkout_note = ( + f"申请结束时间({end:%H:%M})晚于实际下班打卡({actual_checkout:%H:%M:%S})," + f"实际在岗时长按系统取整为{actual_hours:g}小时,满足申请时长" + ) + else: + reasons.append( + f"申请结束时间({end:%H:%M})晚于实际下班打卡时间({actual_checkout:%H:%M:%S})," + f"实际在岗时长按取整仅{actual_hours:g}小时,不足申请{hours:g}小时" + ) info["计算加班时长(小时)"] = hours if reasons: @@ -1426,8 +1459,10 @@ def _validate_delayed(info, punch, session, staff_id): info["有效加班时长(小时)"] = effective info["弹性额度D(小时)"] = d_hours note = f"审批通过,有效加班时长{effective:g}小时" - if flex_note: - note += f"({flex_note})" + extra_parts = [end_checkout_note, flex_note] + extra = ";".join(p for p in extra_parts if p) + if extra: + note += f"({extra})" return "通过", note