feat(hrbp-ehr): 新增HR薪资卡与花名册自动化模块
1. 新增hrbp.ehr业务模块目录结构与基础配置 2. 新增工资卡数据抓取、核对功能,支持在职/离职员工数据导出 3. 新增员工花名册自定义导出自动化流程 4. 添加pandas依赖到requirements.txt 5. 清理调试用的验证码图片文件
@@ -1,123 +1,59 @@
|
||||
import requests
|
||||
import csv
|
||||
import os
|
||||
访问[hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic#ajax#ajax&&1&&nworktoday-40175-24311-77128-52242&&nworktoday-40175-24311|/RedseaPlatform/hrRoster/1116da64-b094-11ea-b588-14187743d052/getCustomCommonList.mc?_t=1786190208277&&clickFlag=true&&treePermitType=permit&&useSealTreeData=0&&menuName=%E5%91%98%E5%B7%A5%E8%8A%B1%E5%90%8D%E5%86%8C](https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic#ajax&1&nworktoday-40175-24311-77128-52242&nworktoday-40175-24311|/RedseaPlatform/hrRoster/1116da64-b094-11ea-b588-14187743d052/getCustomCommonList.mc?_t=1786190208277&clickFlag=true&treePermitType=permit&useSealTreeData=0&menuName=%E5%91%98%E5%B7%A5%E8%8A%B1%E5%90%8D%E5%86%8C&_t=1786190208277)
|
||||
|
||||
# 你的 Cookie 字符串(从浏览器复制完整)
|
||||
点击组织机构
|
||||
|
||||
COOKIE_STR = "你的完整Cookie"
|
||||
```
|
||||
<div class="hrm-bd-left-title" title="切换列表/树" data-i18n-attr="{'COMMON_TITLE':['title']}">
|
||||
<span class="iconfont icon-tree"></span>
|
||||
<span class="hrm-bd-left-title-name" data-i18n="COMMON_MENU">员工管理</span>
|
||||
<span class="hrm-bd-left-title-org tabActive" data-i18n="COMMON_TITLE">组织机构</span>
|
||||
</div>
|
||||
```
|
||||
|
||||
# 基础参数模板(和之前一样)
|
||||
点击集团
|
||||
|
||||
BASE_PARAMS = {
|
||||
"start": "0",
|
||||
"pageNo": "1",
|
||||
"pageSize": "15",
|
||||
"USER_ID": "07b83185-6243-42bc-b79f-b81b4cffb471",
|
||||
"STRU_ID": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"STRU_TREE_CODE": "cq37du",
|
||||
"queryTempPersonType": "queryForList",
|
||||
"belongUnitStruId": "f1a6c12a-cef4-11ee-b449-000c296f9469",
|
||||
"fastMode": "0",
|
||||
"rootId": "cq37du",
|
||||
"_noTrans_": "noTrans",
|
||||
"defineColumnType": "5",
|
||||
"PERSON_STATUS": "",
|
||||
"SI_STATE": "98",
|
||||
"staff_names": "",
|
||||
"base_codes": "", # 这个会被动态替换
|
||||
"includeSubUnit": "1",
|
||||
"postStruId": "1",
|
||||
"regist_property": "",
|
||||
"identity": "",
|
||||
"idcards": "",
|
||||
"if_sb": "",
|
||||
"payOrgId": "",
|
||||
"payUnitId": "",
|
||||
"siName": "",
|
||||
"belongUnitId": "",
|
||||
"belongUnitName": "",
|
||||
"DEPT_NAME": "",
|
||||
"inputDeptName": "",
|
||||
"selectType": "1",
|
||||
"operator": "",
|
||||
"joinDate_begin": "", "joinDate_end": "",
|
||||
"leaveDate_begin": "", "leaveDate_end": "",
|
||||
"siBeginDate_begin": "", "siBeginDate_end": "",
|
||||
"siEndDate_begin": "", "siEndDate_end": "",
|
||||
}
|
||||
```
|
||||
<a id="indexTree_1_a" class="level0 curSelectedNode" treenode_a="" onclick="" target="_blank" style="" title="集团"><span id="indexTree_1_ico" title="" treenode_ico="" class="button ico_open" style="background:url(/RedseaPlatform/skins/images/redsea-icon-bumenguanli.png) 0 0 no-repeat;"></span><span id="indexTree_1_span">集团</span></a>
|
||||
```
|
||||
|
||||
HEADERS = {
|
||||
"Cookie": COOKIE_STR,
|
||||
"User-Agent": "Mozilla/5.0",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
}
|
||||
然后清空输入框
|
||||
|
||||
def query_batch(codes_batch):
|
||||
"""查询一批工号(≤15个),返回响应 JSON"""
|
||||
params = BASE_PARAMS.copy()
|
||||
params["base_codes"] = ",".join(codes_batch)
|
||||
resp = requests.post(
|
||||
"https://hr.37du.co/RedseaPlatform/getPageAjax/si_main_SelectByTreeCode/CoreRequest.mc",
|
||||
data=params,
|
||||
headers=HEADERS,
|
||||
timeout=15
|
||||
)
|
||||
resp.raise_for_status() # 如果不是200会抛出异常
|
||||
return resp.json()
|
||||
```
|
||||
<p>访问<a href="https://hr.37du.co/RedseaPlatform/hrRoster/1116da64-b094-11ea-b588-14187743d052/getCustomCommonList.mc">hr.37du.co/RedseaPlatform/hrRoster/1116da64-b094-11ea-b588-14187743d052/getCustomCommonList.mc</a><br />
|
||||
清空输入框</p>
|
||||
<div component-div="commonSearchVue_1116da64-b094-11ea-b588-14187743d052_hr_staff_base.person_status"><div data-v-717358fc="" class="form-select el-input-group el-input-group--prepend" style="--textSize: 13px;"><div data-v-717358fc="" class="el-input-group__prepend">在职状态</div><div data-v-717358fc="" class="el-select el-select--small" labelkey="label"><div class="el-select__tags" style="width: 100%; max-width: 113px;"><span><span class="el-tag el-tag--info el-tag--mini el-tag--light"><span class="el-select__tags-text">在职</span><i class="el-tag__close el-icon-close"></i></span></span><input type="text" autocomplete="off" class="el-select__input is-small" style="flex-grow: 1; width: 0.176991%; max-width: 103px;"></div><div class="el-input el-input--small el-input--suffix"><input tabindex="-1" type="text" readonly="readonly" autocomplete="off" placeholder="" class="el-input__inner" style="height: 32px;"><span class="el-input__suffix"><span class="el-input__suffix-inner"><i class="el-select__caret el-input__icon el-icon-arrow-up" style=""></i></span></span></div></div><input data-v-717358fc="" style="position: absolute; z-index: -999; width: 0px; height: 0px; border-width: medium; border-style: none; border-color: currentcolor; border-image: none; padding: 0px; opacity: 0;"></div></div>
|
||||
```
|
||||
|
||||
def extract_found_codes(response_json):
|
||||
"""从返回的JSON里提取所有出现的工号(base_Code)"""
|
||||
datas = response_json.get("datas", [])
|
||||
return [item["base_Code"] for item in datas if "base_Code" in item]
|
||||
然后选择在职
|
||||
点击更多操作
|
||||
|
||||
def check_batch(codes_batch):
|
||||
"""比较查询结果与输入工号,返回找到的、未找到的列表"""
|
||||
try:
|
||||
data = query_batch(codes_batch)
|
||||
found = extract_found_codes(data)
|
||||
missing = [c for c in codes_batch if c not in found]
|
||||
return found, missing, data
|
||||
except Exception as e:
|
||||
print(f"请求失败:{e}")
|
||||
return [], codes_batch, None
|
||||
```
|
||||
<button type="button" class="btn btn-success btn-sm dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><i18n key="COMMON_BTN">更多操作</i18n>
|
||||
<span style="font-size: 14px;margin-left:5px;float: none;" class="icon icon-angle-down"></span>
|
||||
<span class="sr-only">Toggle Dropdown</span>
|
||||
</button>
|
||||
```
|
||||
|
||||
# ---------- 使用示例 ----------
|
||||
点击自定义导出
|
||||
|
||||
# 假设你有一个大的工号列表
|
||||
```
|
||||
<ul class="dropdown-menu" id="custom-btn-ul"><li trans-id="" btn-property-page-id="undefined" class=""><a>导出</a></li><li trans-id="" btn-property-page-id="undefined" class=""><a>自定义导出</a></li><li trans-id="109a1e49-b094-11ea-b588-14187743d052" btn-property-page-id="null" class=""><a>简历导出</a></li><li trans-id="109a0c98-b094-11ea-b588-14187743d052" btn-property-page-id="null" class=""><a>在职证明打印</a></li><li trans-id="109a81db-b094-11ea-b588-14187743d052" btn-property-page-id="null" class=""><a>离职证明打印</a></li><li trans-id="109bb704-b094-11ea-b588-14187743d052" btn-property-page-id="null" class=""><a>导入更新</a></li><li trans-id="1099c220-b094-11ea-b588-14187743d052" btn-property-page-id="null" class=""><a>批量上传头像</a></li><li trans-id="976c8025-11a7-443e-9853-93eb05fd5bf1" btn-property-page-id="null" class=""><a>批量下载头像</a></li><li trans-id="c7de15e0-c947-4e6c-88cf-311aa8fcb497" btn-property-page-id="c6255cdd51f0446783a9b0f2ad112b87" class=""><a>修改用工状态</a></li></ul>
|
||||
```
|
||||
|
||||
all_codes = [
|
||||
"37028192", "37030557", "37035022", "其他工号..."
|
||||
]
|
||||
点击选择模板
|
||||
|
||||
# 将大列表按15个一组拆分
|
||||
```
|
||||
<div data-v-717358fc="" class="form-select el-input-group el-input-group--prepend" data-v-252bd840="" style="--textSize: 13px;"><div data-v-717358fc="" class="el-input-group__prepend">模板</div><div data-v-717358fc="" class="el-select el-select--small" labelkey="label"><!----><div class="el-input el-input--small el-input--suffix"><!----><input type="text" readonly="readonly" autocomplete="off" placeholder="请选择模板" class="el-input__inner"><!----><span class="el-input__suffix"><span class="el-input__suffix-inner"><i class="el-select__caret el-input__icon el-icon-arrow-up"></i><!----><!----><!----><!----><!----></span><!----></span><!----><!----></div><div class="el-select-dropdown el-popper" style="display: none; min-width: 193.333px;"><div class="el-scrollbar" style=""><div class="el-select-dropdown__wrap el-scrollbar__wrap" style="margin-bottom: -15px; margin-right: -15px;"><ul class="el-scrollbar__view el-select-dropdown__list"><!----><div class="rs-option" label="干部选拔信息" value="548c2a43-7c45-459d-abb7-9b1622a188c5"><li class="el-select-dropdown__item" size="small"><div style="display: flex; justify-content: space-between; align-items: center;"><div>干部选拔信息</div> <div class="icon redsea-icon-error" style="display: none;"></div></div></li></div><div class="rs-option" label="员工基础信息" value="990effb5-f694-48ab-8820-6997edef50b5"><li class="el-select-dropdown__item" size="small"><div style="display: flex; justify-content: space-between; align-items: center;"><div>员工基础信息</div> <div class="icon redsea-icon-error" style="display: none;"></div></div></li></div><div class="rs-option" label="个税申报基础信息" value="e3e04246-9b9a-4de8-98b2-d0af999e252c"><li class="el-select-dropdown__item" size="small"><div style="display: flex; justify-content: space-between; align-items: center;"><div>个税申报基础信息</div> <div class="icon redsea-icon-error" style="display: none;"></div></div></li></div><div class="rs-option" label="雇主险增减员导出模板" value="fbe86100-a1b0-493d-ad6e-4a6ca0e6f7e1"><li class="el-select-dropdown__item" size="small"><div style="display: flex; justify-content: space-between; align-items: center;"><div>雇主险增减员导出模板</div> <div class="icon redsea-icon-error" style="display: none;"></div></div></li></div></ul></div><div class="el-scrollbar__bar is-horizontal"><div class="el-scrollbar__thumb" style="transform: translateX(0%);"></div></div><div class="el-scrollbar__bar is-vertical"><div class="el-scrollbar__thumb" style="transform: translateY(0%);"></div></div></div><!----></div></div><input data-v-717358fc="" style="position: absolute; z-index: -999; width: 0px; height: 0px; border-width: medium; border-style: none; border-color: currentcolor; border-image: none; padding: 0px; opacity: 0;"><!----><!----><!----></div>
|
||||
```
|
||||
|
||||
batch_size = 15
|
||||
batches = [all_codes[i:i+batch_size] for i in range(0, len(all_codes), batch_size)]
|
||||
点击员工基础信息
|
||||
|
||||
all_found = []
|
||||
all_missing = []
|
||||
output_rows = [] # 用于存所有有数据的完整行,方便后续导出
|
||||
```
|
||||
<div class="el-select-dropdown__wrap el-scrollbar__wrap" style="margin-bottom: -15px; margin-right: -15px;"><ul class="el-scrollbar__view el-select-dropdown__list"><!----><div class="rs-option" label="干部选拔信息" value="548c2a43-7c45-459d-abb7-9b1622a188c5"><li class="el-select-dropdown__item" size="small"><div style="display: flex; justify-content: space-between; align-items: center;"><div>干部选拔信息</div> <div class="icon redsea-icon-error" style="display: none;"></div></div></li></div><div class="rs-option" label="员工基础信息" value="990effb5-f694-48ab-8820-6997edef50b5"><li class="el-select-dropdown__item hover" size="small"><div style="display: flex; justify-content: space-between; align-items: center;"><div>员工基础信息</div> <div class="icon redsea-icon-error" style="display: none;"></div></div></li></div><div class="rs-option" label="个税申报基础信息" value="e3e04246-9b9a-4de8-98b2-d0af999e252c"><li class="el-select-dropdown__item" size="small"><div style="display: flex; justify-content: space-between; align-items: center;"><div>个税申报基础信息</div> <div class="icon redsea-icon-error" style="display: none;"></div></div></li></div><div class="rs-option" label="雇主险增减员导出模板" value="fbe86100-a1b0-493d-ad6e-4a6ca0e6f7e1"><li class="el-select-dropdown__item" size="small"><div style="display: flex; justify-content: space-between; align-items: center;"><div>雇主险增减员导出模板</div> <div class="icon redsea-icon-error" style="display: none;"></div></div></li></div></ul></div>
|
||||
```
|
||||
|
||||
for batch in batches:
|
||||
found, missing, resp_json = check_batch(batch)
|
||||
all_found.extend(found)
|
||||
all_missing.extend(missing)
|
||||
点击确认导出
|
||||
|
||||
# 如果找到数据,可以把这一批的完整行记录下来
|
||||
if resp_json and resp_json.get("datas"):
|
||||
output_rows.extend(resp_json["datas"])
|
||||
print(f"查询 {batch} → 找到 {found},未找到 {missing}")
|
||||
|
||||
print("\n=== 总结 ===")
|
||||
print(f"总计找到 {len(all_found)} 个工号:{all_found}")
|
||||
print(f"未找到 {len(all_missing)} 个工号:{all_missing}")
|
||||
|
||||
# 把有数据的记录保存为CSV(字段已全量输出)
|
||||
|
||||
if output_rows:
|
||||
keys = output_rows[0].keys()
|
||||
with open("found_si_data.csv", "w", newline="", encoding="utf-8-sig") as f:
|
||||
writer = csv.DictWriter(f, fieldnames=keys)
|
||||
writer.writeheader()
|
||||
writer.writerows(output_rows)
|
||||
print(f"有数据的记录已保存到 found_si_data.csv,共 {len(output_rows)} 条")
|
||||
```
|
||||
<button type="button" class="el-button el-button--primary el-button--small"><!----><!----><span>确认导出</span></button>
|
||||
```
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr
|
||||
@Description: HR 系统相关业务模块
|
||||
"""
|
||||
@@ -0,0 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common
|
||||
@Description: HR 系统公共模块(登录、接口调用、会话管理、配置)
|
||||
"""
|
||||
|
Before Width: | Height: | Size: 95 KiB After Width: | Height: | Size: 142 KiB |
|
Before Width: | Height: | Size: 109 KiB After Width: | Height: | Size: 166 KiB |
|
Before Width: | Height: | Size: 193 KiB |
|
Before Width: | Height: | Size: 224 KiB |
|
Before Width: | Height: | Size: 134 KiB |
|
Before Width: | Height: | Size: 155 KiB |
|
Before Width: | Height: | Size: 106 KiB |
|
Before Width: | Height: | Size: 123 KiB |
|
Before Width: | Height: | Size: 176 KiB |
|
Before Width: | Height: | Size: 202 KiB |
|
Before Width: | Height: | Size: 184 KiB |
|
Before Width: | Height: | Size: 212 KiB |
|
Before Width: | Height: | Size: 5.9 KiB After Width: | Height: | Size: 9.7 KiB |
|
Before Width: | Height: | Size: 12 KiB |
|
Before Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 9.5 KiB |
|
Before Width: | Height: | Size: 12 KiB |
|
Before Width: | Height: | Size: 11 KiB |
@@ -0,0 +1,23 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common
|
||||
@FileName: config.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-08 10:40
|
||||
@Description: HR 系统配置,集中管理接口地址、分页大小等常量(供各业务模块复用)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
# ---------- 银行卡(工资卡)信息查询接口 ----------
|
||||
# 分页查询工资卡信息(aa.md 提供),返回 JSON
|
||||
WAGE_CARD_URL = "https://hr.37du.co/RedseaPlatform/getPageAjax/HrStaffWageCard.mc"
|
||||
|
||||
# 单页最大抓取条数
|
||||
PAGE_MAX_SIZE = 500
|
||||
|
||||
# ---------- 员工花名册(自定义导出)页面 ----------
|
||||
# 花名册自定义导出页面(aa.md 提供),基于 DrissionPage 浏览器自动化操作
|
||||
ROSTER_URL = "https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic#ajax&1&nworktoday-40175-24311-77128-52242&nworktoday-40175-24311|/RedseaPlatform/hrRoster/1116da64-b094-11ea-b588-14187743d052/getCustomCommonList.mc?clickFlag=true&treePermitType=permit&useSealTreeData=0&menuName=%E5%91%98%E5%B7%A5%E8%8A%B1%E5%90%8D%E5%86%8C"
|
||||
|
||||
# 花名册默认导出的自定义模板名称
|
||||
ROSTER_TEMPLATE_NAME = "员工基础信息"
|
||||
@@ -1,8 +1,140 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common
|
||||
@FileName: hr_api.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 23:52
|
||||
@Description: HR 系统 API 接口,集中管理流程引擎、排单、考勤等接口地址
|
||||
@Version: 1.2.0
|
||||
"""
|
||||
@Description: HR 系统 API 模块,负责调用系统接口(工资卡等),供各业务模块复用
|
||||
@Version: 2.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
|
||||
|
||||
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
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
# -*- 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.utils.logger import get_logger
|
||||
|
||||
try:
|
||||
import requests
|
||||
except ImportError:
|
||||
requests = None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# HR 登录 cookies 持久化目录(login.py 登录成功后保存)
|
||||
_SESSIONS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', '..', '.sessions')
|
||||
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()
|
||||
@@ -0,0 +1,602 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.wage_card
|
||||
@FileName: roster_export.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-08
|
||||
@Description: 员工花名册自定义导出。复用 HR 系统登录及缓存 cookies,通过 DrissionPage 浏览器自动化
|
||||
按 aa.md 流程操作:进入花名册页 -> 组织机构(集团) -> 在职状态=在职 -> 更多操作 -> 自定义导出
|
||||
-> 选择模板「员工基础信息」-> 确认导出,并接收浏览器下载的文件到指定目录。
|
||||
@Version: 1.0.0
|
||||
|
||||
使用说明:
|
||||
1. 首次运行会调用 HR 登录模块(login.py)完成登录并缓存 cookies 到 .sessions/hr_cookies.json;
|
||||
后续运行自动复用缓存,登录态过期会自动重新登录。
|
||||
2. 直接运行本文件即可触发花名册导出(会弹出浏览器窗口,请勿关闭)。
|
||||
3. 下载目录默认取环境变量 roster_output_dir,否则使用项目根目录。
|
||||
|
||||
底层复用:
|
||||
- HR 登录 & cookies:app.service.hrbp.ehr.common.login(load_cookies / login)
|
||||
- 页面地址 & 模板名:app.service.hrbp.ehr.common.config(ROSTER_URL / ROSTER_TEMPLATE_NAME)
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from app.utils.logger import get_logger # noqa: E402
|
||||
from app.utils.logger import setup_logging # noqa: E402
|
||||
|
||||
try:
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
except ImportError:
|
||||
ChromiumPage = None
|
||||
ChromiumOptions = None
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
pd = None
|
||||
|
||||
# 底层复用: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.ehr.wage_card.wage_card_download import get_leave_range # noqa: E402
|
||||
from app.utils.intelligent_retry import retry # noqa: E402
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ===================== 流程步骤所用文案常量(aa.md 提供) =====================
|
||||
TAB_ORG = "组织机构" # 左侧「组织机构」tab,切换为组织树
|
||||
TREE_GROUP = "集团" # 组织树根节点
|
||||
PERSON_STATUSES = ["在职", "离职"] # 需导出的在职状态(按顺序逐次导出)
|
||||
BTN_MORE = "更多操作" # 更多操作按钮
|
||||
MENU_CUSTOM_EXPORT = "自定义导出"
|
||||
TEMPLATE_PLACEHOLDER = "请选择模板"
|
||||
BTN_CONFIRM = "确认导出"
|
||||
BTN_MORE_SEARCH = "更多搜索" # 展开更多筛选条件(离职时间等)
|
||||
LEAVE_RANGE_PLACEHOLDER = "请选择离职时间"
|
||||
FILTER_XPATH = 'xpath://button[contains(@class,"el-button--primary") and normalize-space(.)="筛选"]'
|
||||
|
||||
# 通用等待秒数
|
||||
WAIT_SHORT = 0.6
|
||||
WAIT_MID = 2.0
|
||||
WAIT_LONG = 4.0
|
||||
DOWNLOAD_BEGIN_TIMEOUT = 60 # 等待下载开始
|
||||
DOWNLOAD_FINISH_TIMEOUT = 300 # 等待下载完成
|
||||
|
||||
# 输出目录 & 合并文件名
|
||||
OUTPUT_DIR = r"D:\资料\人资\员工花名册"
|
||||
MERGED_NAME = "员工花名册.xlsx"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 1. 元素定位辅助(DrissionPage)
|
||||
# ---------------------------------------------------------------
|
||||
def _click_text(page, text, timeout=10):
|
||||
"""按元素文本精确匹配并点击,找不到则抛错。"""
|
||||
ele = page.ele(f'xpath://*[normalize-space(text())="{text}"]', timeout=timeout)
|
||||
if not ele:
|
||||
raise RuntimeError(f"未找到元素:{text}")
|
||||
ele.click()
|
||||
logger.info("已点击:%s", text)
|
||||
|
||||
|
||||
def _click_text_in(page, container, text, timeout=5):
|
||||
"""在指定容器内按文本匹配并点击。"""
|
||||
ele = container.ele(f'xpath:.//*[normalize-space(text())="{text}"]', timeout=timeout)
|
||||
if not ele:
|
||||
raise RuntimeError(f"容器内未找到元素:{text}")
|
||||
ele.click()
|
||||
logger.info("已点击:%s", text)
|
||||
|
||||
|
||||
def _ensure_person_status(page, status="在职"):
|
||||
"""将「在职状态」筛选设置为仅选中指定状态(在职/离职)。
|
||||
|
||||
注意:该筛选为多选下拉(在职/离职/退休/返聘),需要取消其它已选项,
|
||||
仅保留目标状态,避免导出时把多个状态混在一起。
|
||||
"""
|
||||
container = page.ele('css:div[component-div*="person_status"]', timeout=15)
|
||||
if not container:
|
||||
raise RuntimeError("未找到「在职状态」筛选控件")
|
||||
select = container.ele('css:.el-select', timeout=5)
|
||||
if not select:
|
||||
raise RuntimeError("未找到「在职状态」下拉框")
|
||||
|
||||
# 打开下拉,等待可见面板出现(下拉关闭时选项仍在 DOM 但不可见,必须取可见面板内的选项)
|
||||
select.click()
|
||||
time.sleep(WAIT_SHORT)
|
||||
panel = page.ele('css:.el-select-dropdown:not([style*="display: none"])', timeout=5)
|
||||
if not panel:
|
||||
select.click()
|
||||
time.sleep(WAIT_SHORT)
|
||||
panel = page.ele('css:.el-select-dropdown:not([style*="display: none"])', timeout=5)
|
||||
if not panel:
|
||||
raise RuntimeError("在职状态下拉面板未能展开")
|
||||
|
||||
items = panel.eles('css:li.el-select-dropdown__item')
|
||||
if not items:
|
||||
raise RuntimeError("在职状态下拉中没有选项")
|
||||
|
||||
# 文本 -> 选项元素
|
||||
opt_map = {}
|
||||
for it in items:
|
||||
txt = (it.text or "").strip()
|
||||
if txt:
|
||||
opt_map[txt] = it
|
||||
if status not in opt_map:
|
||||
raise RuntimeError(f"在职状态下拉中不存在选项:{status}")
|
||||
|
||||
# 仅保留目标状态选中,其余取消选中
|
||||
for txt, it in opt_map.items():
|
||||
is_selected = "selected" in (it.attr('class') or "")
|
||||
need = (txt == status)
|
||||
if is_selected != need:
|
||||
logger.info("在职状态选项「%s」%s", txt, "选中" if need else "取消选中")
|
||||
it.click()
|
||||
time.sleep(0.2)
|
||||
|
||||
# 关闭下拉(再次点击外壳切换收起)
|
||||
try:
|
||||
select.click()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(WAIT_SHORT)
|
||||
logger.info("在职状态已设为仅「%s」", status)
|
||||
|
||||
|
||||
def _is_displayed(ele):
|
||||
"""判断元素是否可见且具有尺寸(可点击);异常时返回 False(保守不误判)。"""
|
||||
if ele is None:
|
||||
return False
|
||||
try:
|
||||
if not ele.states.is_displayed:
|
||||
return False
|
||||
w, h = ele.rect.size
|
||||
return w > 0 and h > 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _open_more_search(page):
|
||||
"""确保「更多搜索」popover 已展开,返回是否成功。
|
||||
|
||||
通过按钮的 aria-describedby 属性找到 popover 内容元素,检查其是否可见来判断展开状态。
|
||||
按钮特征:class 含 search-more-condition-btn / el-popover__reference,外层容器 demo-search-more。
|
||||
"""
|
||||
# 定位「更多搜索」按钮
|
||||
btn = page.ele('css:button.search-more-condition-btn', timeout=3)
|
||||
if not btn:
|
||||
btn = page.ele('css:.demo-search-more .el-popover__reference', timeout=2)
|
||||
if not btn:
|
||||
btn = page.ele('xpath://button[.//span[contains(normalize-space(.),"更多搜索")]]', timeout=2)
|
||||
if not btn:
|
||||
logger.warning("未找到「更多搜索」按钮")
|
||||
return False
|
||||
|
||||
for _ in range(3):
|
||||
# 通过 aria-describedby 找到 popover 元素,检查是否可见
|
||||
popover_id = btn.attr('aria-describedby')
|
||||
if popover_id:
|
||||
popover = page.ele(f'css:#{popover_id}', timeout=2)
|
||||
if popover and _is_displayed(popover):
|
||||
logger.info("更多搜索已展开(popover #%s 可见)", popover_id)
|
||||
return True
|
||||
# 兜底:检查是否有可见的「筛选」按钮
|
||||
fb = page.ele(FILTER_XPATH, timeout=2)
|
||||
if fb and _is_displayed(fb):
|
||||
logger.info("更多搜索已展开(检测到可见的「筛选」按钮)")
|
||||
return True
|
||||
# 用 JS 直接 click() 触发 Element UI popover(纯选择器,避免传参问题)
|
||||
page.run_js(
|
||||
'var b=document.querySelector("button.search-more-condition-btn");'
|
||||
'if(b){b.click();}'
|
||||
)
|
||||
time.sleep(WAIT_MID)
|
||||
logger.warning("「更多搜索」未能展开")
|
||||
return False
|
||||
|
||||
|
||||
def _click_filter(page):
|
||||
"""点击更多搜索弹层底部的「筛选」按钮,应用离职时间等筛选条件。
|
||||
|
||||
全部在 JS 中完成:定位 popover -> 在 popover 内部找文本为「筛选」的按钮 -> 直接 .click()。
|
||||
之前全页面搜索可能找到错误的「筛选」按钮,现在限定在 popover 容器内查找。
|
||||
"""
|
||||
result = page.run_js(
|
||||
'var b=document.querySelector("button.search-more-condition-btn");'
|
||||
'if(!b){return "no_btn_more";}'
|
||||
'var id=b.getAttribute("aria-describedby");'
|
||||
'if(!id){return "no_id";}'
|
||||
'var pop=document.getElementById(id);'
|
||||
'if(!pop){return "no_popover:"+id;}'
|
||||
'var btns=pop.querySelectorAll("button");'
|
||||
'for(var i=0;i<btns.length;i++){'
|
||||
' var t=(btns[i].textContent||"").replace(/\\s/g,"");'
|
||||
' if(t==="筛选"){btns[i].click();return "clicked";}'
|
||||
'}'
|
||||
'return "no_filter_btn:"+id;'
|
||||
)
|
||||
if result != "clicked":
|
||||
raise RuntimeError(f"点击「筛选」失败:{result}")
|
||||
logger.info("已点击「筛选」(JS click)")
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _set_leave_date_range(page, leave_start=None, leave_end=None):
|
||||
"""设置「离职时间」筛选范围并应用,时间规则与工资卡离职导出一致(get_leave_range)。"""
|
||||
if not leave_start or not leave_end:
|
||||
leave_start, leave_end = get_leave_range()
|
||||
|
||||
if not _open_more_search(page):
|
||||
raise RuntimeError("「更多搜索」未能展开,无法设置离职时间")
|
||||
logger.info("设置离职时间范围:%s ~ %s", leave_start, leave_end)
|
||||
rng = page.ele(f'css:div.split-datetime-range[placeholder="{LEAVE_RANGE_PLACEHOLDER}"]', timeout=10)
|
||||
if not rng or not _is_displayed(rng):
|
||||
raise RuntimeError("未找到可见的「离职时间」选择器")
|
||||
start_input = rng.ele('css:input[placeholder="开始时间"]', timeout=5)
|
||||
end_input = rng.ele('css:input[placeholder="结束时间"]', timeout=5)
|
||||
if not start_input or not end_input:
|
||||
raise RuntimeError("未找到离职时间起止输入框")
|
||||
# 填入日期后按回车确认(input() 无 enter 参数,用 Actions 补回车)
|
||||
start_input.input(leave_start, clear=True)
|
||||
page.actions.key_down('enter').key_up('enter')
|
||||
time.sleep(WAIT_SHORT)
|
||||
end_input.input(leave_end, clear=True)
|
||||
page.actions.key_down('enter').key_up('enter')
|
||||
time.sleep(WAIT_SHORT)
|
||||
logger.info("离职时间已设置:%s ~ %s", leave_start, leave_end)
|
||||
|
||||
_click_filter(page)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 2. 打开花名册页并确保登录态(复用缓存 cookies)
|
||||
# ---------------------------------------------------------------
|
||||
def _ensure_logged_in(page):
|
||||
"""访问花名册页面;若被重定向到登录页,则复用/重登 HR 登录态。"""
|
||||
page.get(ROSTER_URL)
|
||||
time.sleep(WAIT_LONG)
|
||||
|
||||
# 登录页特征:存在用户名输入框
|
||||
if page.ele('@id=j_username', timeout=2):
|
||||
logger.info("HR 登录态已失效,执行重新登录")
|
||||
from app.service.hrbp.ehr.common.login import login as hr_login
|
||||
if not hr_login():
|
||||
raise RuntimeError("HR 重新登录失败")
|
||||
cookies = load_cookies()
|
||||
if cookies:
|
||||
page.set.cookies(cookies)
|
||||
page.get(ROSTER_URL)
|
||||
time.sleep(WAIT_LONG)
|
||||
if page.ele('@id=j_username', timeout=2):
|
||||
raise RuntimeError("HR 重新登录后仍停留在登录页")
|
||||
logger.info("已进入花名册页面:%s", page.url)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 3. 花名册导出主流程(aa.md 步骤)
|
||||
# ---------------------------------------------------------------
|
||||
def _select_org_tree(page):
|
||||
"""切换到组织树并选中「集团」。"""
|
||||
# 步骤1:点击左侧「组织机构」,切换为组织树
|
||||
org_tab = page.ele('css:.hrm-bd-left-title-org', timeout=15)
|
||||
if org_tab:
|
||||
org_tab.click()
|
||||
logger.info("已点击左侧「组织机构」")
|
||||
time.sleep(WAIT_MID)
|
||||
else:
|
||||
logger.warning("未找到「组织机构」tab,尝试直接按文本点击")
|
||||
_click_text(page, TAB_ORG)
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
# 步骤2:点击组织树根节点「集团」
|
||||
group = page.ele('css:a[title="集团"]', timeout=15)
|
||||
if not group:
|
||||
group = page.ele(f'xpath://*[normalize-space(text())="集团"]', timeout=5)
|
||||
if not group:
|
||||
raise RuntimeError("组织树中未找到「集团」节点")
|
||||
group.click()
|
||||
logger.info("已点击组织树根节点「集团」")
|
||||
time.sleep(WAIT_LONG)
|
||||
|
||||
|
||||
def _open_custom_export_dialog(page):
|
||||
"""点击「更多操作」->「自定义导出」,打开导出弹窗(幂等,已打开则跳过)。"""
|
||||
# 若导出弹窗已打开(存在「模板」下拉),直接返回
|
||||
tpl_label = page.ele(
|
||||
'xpath://div[contains(@class,"el-input-group__prepend") and normalize-space(.)="模板"]', timeout=2)
|
||||
if tpl_label and _is_displayed(tpl_label):
|
||||
logger.info("导出弹窗已打开,跳过「更多操作」")
|
||||
time.sleep(WAIT_MID)
|
||||
return
|
||||
|
||||
# 步骤3:点击「更多操作」按钮
|
||||
more_btn = page.ele('css:button.btn-success.dropdown-toggle', timeout=15)
|
||||
if more_btn:
|
||||
more_btn.click()
|
||||
else:
|
||||
_click_text(page, BTN_MORE)
|
||||
logger.info("已点击「更多操作」")
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
# 步骤4:点击「自定义导出」
|
||||
menu = page.ele('css:#custom-btn-ul', timeout=5)
|
||||
if menu:
|
||||
_click_text_in(page, menu, MENU_CUSTOM_EXPORT)
|
||||
else:
|
||||
_click_text(page, MENU_CUSTOM_EXPORT)
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _select_template(page, template_name=ROSTER_TEMPLATE_NAME):
|
||||
"""在导出弹窗中选择自定义导出模板。"""
|
||||
# 步骤5:定位「模板」下拉框容器(含「模板」前置标签的 el-select)
|
||||
tpl = page.ele(
|
||||
'xpath://div[contains(@class,"el-input-group__prepend") and normalize-space(.)="模板"]'
|
||||
'/following-sibling::div[contains(@class,"el-select")]',
|
||||
timeout=15,
|
||||
)
|
||||
if not tpl:
|
||||
raise RuntimeError("未找到「模板」下拉框")
|
||||
|
||||
# 确保下拉面板已展开(下拉面板会 teleport 到 body,需在页面级查找可见面板)
|
||||
panel = None
|
||||
for _ in range(3):
|
||||
panel = page.ele('css:.el-select-dropdown:not([style*="display: none"])', timeout=2)
|
||||
if panel and _is_displayed(panel):
|
||||
break
|
||||
tpl.click()
|
||||
time.sleep(WAIT_SHORT)
|
||||
if not panel:
|
||||
raise RuntimeError("模板下拉面板未能展开")
|
||||
|
||||
# 步骤6:在可见面板中选择模板(如「员工基础信息」)
|
||||
opt = panel.ele(
|
||||
f'xpath:.//li[contains(@class,"el-select-dropdown__item") and normalize-space(.)="{template_name}"]',
|
||||
timeout=5,
|
||||
)
|
||||
if not opt:
|
||||
raise RuntimeError(f"模板下拉中未找到:{template_name}")
|
||||
opt.click()
|
||||
logger.info("已选择模板:%s", template_name)
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
|
||||
def _click_confirm_export(page):
|
||||
"""点击「确认导出」,触发下载。"""
|
||||
btn = page.ele(f'xpath://button[contains(@class,"el-button--primary") and normalize-space(.)="{BTN_CONFIRM}"]',
|
||||
timeout=10)
|
||||
if not btn:
|
||||
raise RuntimeError(f"未找到「{BTN_CONFIRM}」按钮")
|
||||
btn.click()
|
||||
logger.info("已点击「确认导出」")
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 4. 下载等待
|
||||
# ---------------------------------------------------------------
|
||||
def _wait_download(page, download_dir, timeout=DOWNLOAD_FINISH_TIMEOUT):
|
||||
"""等待下载文件生成并大小稳定,返回下载文件路径。
|
||||
|
||||
采用文件系统轮询:统计下载目录中新增的、非临时文件,当其大小两次采样一致
|
||||
视为下载完成。避免依赖 DrissionPage 下载任务状态(可能卡在 100% 不结束)。
|
||||
"""
|
||||
logger.info("等待下载文件生成(最多 %ds)...", timeout)
|
||||
before = set(os.listdir(download_dir))
|
||||
deadline = time.time() + timeout
|
||||
last_sizes = {}
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
files = os.listdir(download_dir)
|
||||
except Exception:
|
||||
files = []
|
||||
for f in files:
|
||||
if f in before or f.endswith(('.crdownload', '.tmp', '.part', '.download')):
|
||||
continue
|
||||
p = os.path.join(download_dir, f)
|
||||
if not os.path.isfile(p):
|
||||
continue
|
||||
try:
|
||||
size = os.path.getsize(p)
|
||||
except Exception:
|
||||
continue
|
||||
if size <= 0:
|
||||
continue
|
||||
if last_sizes.get(p) == size:
|
||||
logger.info("花名册导出文件已下载:%s(%.2f KB)", p, size / 1024.0)
|
||||
return p
|
||||
last_sizes[p] = size
|
||||
time.sleep(1.0)
|
||||
raise RuntimeError(f"等待下载文件超时({timeout}s 内未检测到稳定文件)")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 5. 合并多个花名册 Excel 为一个,添加「类型」列
|
||||
# ---------------------------------------------------------------
|
||||
def _merge_roster_files(files_with_status, output_path):
|
||||
"""合并多个花名册 Excel 文件,添加「类型」列标识在职状态。
|
||||
|
||||
Args:
|
||||
files_with_status: [(status, file_path), ...] 列表
|
||||
output_path: 合并后文件保存路径
|
||||
|
||||
Returns:
|
||||
合并后文件路径
|
||||
"""
|
||||
if pd is None:
|
||||
raise RuntimeError("缺少 pandas 依赖,无法合并 Excel")
|
||||
dfs = []
|
||||
for status, path in files_with_status:
|
||||
df = pd.read_excel(path, header=1)
|
||||
df.insert(0, "类型", status)
|
||||
dfs.append(df)
|
||||
logger.info("读取花名册文件:%s(%s,%d 行)", path, status, len(df))
|
||||
merged = pd.concat(dfs, ignore_index=True)
|
||||
merged.to_excel(output_path, index=False)
|
||||
logger.info("合并完成,共 %d 行,已保存:%s", len(merged), output_path)
|
||||
|
||||
# 删除临时下载的单个文件
|
||||
for _, path in files_with_status:
|
||||
try:
|
||||
os.remove(path)
|
||||
except Exception:
|
||||
pass
|
||||
return output_path
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 6. 对外入口
|
||||
# ---------------------------------------------------------------
|
||||
@retry(max_attempts=3)
|
||||
def _export_one_status(page, status, download_dir):
|
||||
"""导出单个在职状态的花名册(设置筛选 -> 自定义导出 -> 下载),失败自动重试。"""
|
||||
logger.info(">>> 开始导出在职状态:%s", status)
|
||||
try:
|
||||
_ensure_person_status(page, status)
|
||||
if status == "离职":
|
||||
_set_leave_date_range(page)
|
||||
_open_custom_export_dialog(page)
|
||||
_select_template(page)
|
||||
_click_confirm_export(page)
|
||||
logger.info(">>> 等待在职状态「%s」的导出文件下载", status)
|
||||
path = _wait_download(page, download_dir)
|
||||
logger.info(">>> 在职状态「%s」导出完成", status)
|
||||
return path
|
||||
except Exception:
|
||||
logger.exception("导出在职状态「%s」失败,详细堆栈如下:", status)
|
||||
raise
|
||||
|
||||
|
||||
def export_roster(download_dir: str = None) -> str:
|
||||
"""执行员工花名册自定义导出(在职 + 离职各一次),合并为一个 Excel 文件。
|
||||
|
||||
Args:
|
||||
download_dir: 浏览器下载临时目录,默认使用 OUTPUT_DIR。
|
||||
|
||||
Returns:
|
||||
合并后的花名册文件路径。
|
||||
|
||||
Raises:
|
||||
RuntimeError: 任何流程步骤失败或下载未检测到时抛出。
|
||||
"""
|
||||
if ChromiumPage is None:
|
||||
raise RuntimeError("缺少 DrissionPage 依赖,请先安装: pip install DrissionPage")
|
||||
|
||||
download_dir = os.path.abspath(download_dir or OUTPUT_DIR)
|
||||
os.makedirs(download_dir, exist_ok=True)
|
||||
logger.info("===== 开始花名册导出,下载目录:%s =====", download_dir)
|
||||
|
||||
co = ChromiumOptions()
|
||||
page = ChromiumPage(co)
|
||||
logger.info("浏览器已启动")
|
||||
try:
|
||||
# 注入缓存 cookies,再访问页面
|
||||
cookies = load_cookies()
|
||||
logger.info("加载缓存 cookies:%d 个", len(cookies or []))
|
||||
if cookies:
|
||||
try:
|
||||
page.set.cookies(cookies)
|
||||
except Exception as e:
|
||||
logger.warning("注入缓存 cookies 失败:%s", e)
|
||||
|
||||
_ensure_logged_in(page)
|
||||
_select_org_tree(page)
|
||||
|
||||
# 下载目录设置需在触发下载前完成
|
||||
page.set.download_path(download_dir)
|
||||
logger.info("浏览器下载目录已设置:%s", download_dir)
|
||||
|
||||
files_with_status = []
|
||||
for status in PERSON_STATUSES:
|
||||
logger.info("===== 开始导出在职状态:%s =====", status)
|
||||
path = _export_one_status(page, status, download_dir)
|
||||
files_with_status.append((status, path))
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
# 合并所有花名册文件
|
||||
merged_path = os.path.join(OUTPUT_DIR, MERGED_NAME)
|
||||
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
||||
result = _merge_roster_files(files_with_status, merged_path)
|
||||
logger.info("===== 花名册导出并合并完成:%s =====", result)
|
||||
return result
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def debug_filter_only():
|
||||
"""调试模式:只执行到筛选结束,不导出,浏览器保持打开供检查。"""
|
||||
if ChromiumPage is None:
|
||||
raise RuntimeError("缺少 DrissionPage 依赖,请先安装: pip install DrissionPage")
|
||||
|
||||
logger.info("===== 调试模式:仅执行到筛选结束 =====")
|
||||
co = ChromiumOptions()
|
||||
page = ChromiumPage(co)
|
||||
logger.info("浏览器已启动")
|
||||
try:
|
||||
cookies = load_cookies()
|
||||
logger.info("加载缓存 cookies:%d 个", len(cookies or []))
|
||||
if cookies:
|
||||
try:
|
||||
page.set.cookies(cookies)
|
||||
except Exception as e:
|
||||
logger.warning("注入缓存 cookies 失败:%s", e)
|
||||
|
||||
_ensure_logged_in(page)
|
||||
_select_org_tree(page)
|
||||
|
||||
_ensure_person_status(page, "离职")
|
||||
_set_leave_date_range(page)
|
||||
|
||||
logger.info("===== 筛选已执行完毕,浏览器保持打开,按回车关闭 =====")
|
||||
input("按回车键关闭浏览器...")
|
||||
except Exception as e:
|
||||
logger.error("调试失败:%s", e)
|
||||
raise
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""命令行入口:python roster_export.py [下载目录]"""
|
||||
setup_logging()
|
||||
|
||||
# 调试模式:仅执行到筛选结束
|
||||
if len(sys.argv) > 1 and sys.argv[1] == "debug":
|
||||
debug_filter_only()
|
||||
return
|
||||
|
||||
download_dir = os.getenv("roster_output_dir")
|
||||
if not download_dir and len(sys.argv) > 1 and sys.argv[1] != "debug":
|
||||
download_dir = sys.argv[1]
|
||||
try:
|
||||
out = export_roster(download_dir)
|
||||
logger.info("===== 花名册导出完成:%s =====", out)
|
||||
except Exception as e:
|
||||
logger.error("花名册导出失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.wage_card
|
||||
@Description: 银行卡(工资卡)信息下载与核对、员工花名册自定义导出模块
|
||||
"""
|
||||
@@ -0,0 +1,89 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.wage_card
|
||||
@FileName: bank_card_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-08
|
||||
@Description: 银行卡检查:下载工资卡汇总表并核对数据(身份证/姓名/银行卡号)。
|
||||
员工花名册已独立为 roster_export 模块,不再包含在此流程中。
|
||||
数据保存到 D:\\资料\\人资\\银行卡检查\\
|
||||
@Version: 2.0.0
|
||||
|
||||
使用说明:
|
||||
直接运行本文件即可依次执行工资卡下载、工资卡核对。
|
||||
python bank_card_check.py
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
# ---- 单文件运行支持 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
from app.service.hrbp.ehr.wage_card.wage_card_download import download_wage_card # noqa: E402
|
||||
from app.service.hrbp.ehr.wage_card.wage_card_check import check_wage_card # noqa: E402
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def run_bank_card_check():
|
||||
"""银行卡检查主流程:工资卡下载 -> 工资卡核对。"""
|
||||
results = {}
|
||||
|
||||
# ---- 第一步:下载工资卡汇总表 ----
|
||||
logger.info("=" * 60)
|
||||
logger.info("【银行卡检查】第一步:下载工资卡汇总表")
|
||||
logger.info("=" * 60)
|
||||
wage_path = None
|
||||
try:
|
||||
wage_path = download_wage_card()
|
||||
results["工资卡"] = wage_path
|
||||
logger.info("工资卡下载完成:%s", wage_path)
|
||||
except Exception as e:
|
||||
logger.error("工资卡下载失败:%s", e)
|
||||
results["工资卡"] = f"失败:{e}"
|
||||
|
||||
# ---- 第二步:核对工资卡数据 ----
|
||||
logger.info("=" * 60)
|
||||
logger.info("【银行卡检查】第二步:核对工资卡数据")
|
||||
logger.info("=" * 60)
|
||||
if wage_path:
|
||||
try:
|
||||
check_path = check_wage_card(wage_path)
|
||||
results["核对结果"] = check_path
|
||||
logger.info("工资卡核对完成:%s", check_path)
|
||||
except Exception as e:
|
||||
logger.error("工资卡核对失败:%s", e)
|
||||
results["核对结果"] = f"失败:{e}"
|
||||
else:
|
||||
logger.warning("工资卡汇总表未生成,跳过核对")
|
||||
results["核对结果"] = "跳过(工资卡下载失败)"
|
||||
|
||||
# ---- 汇总 ----
|
||||
logger.info("=" * 60)
|
||||
logger.info("【银行卡检查】全部完成,结果汇总:")
|
||||
for name, path in results.items():
|
||||
logger.info(" %s:%s", name, path)
|
||||
logger.info("=" * 60)
|
||||
return results
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""命令行入口:python bank_card_check.py"""
|
||||
setup_logging()
|
||||
run_bank_card_check()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,239 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.wage_card
|
||||
@FileName: wage_card_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-08
|
||||
@Description: 工资卡汇总表核对:身份证一致性、姓名一致性、空值标记、银行卡号校验。
|
||||
读取工资卡汇总表 Excel,添加核对结果列后保存。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# ---- 单文件运行支持 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
pd = None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ===================== 银行卡校验规则 =====================
|
||||
# 固定通用规则,无需随表格修改
|
||||
# 必须16位的BIN
|
||||
BIN_16 = {"621483", "622622", "621691", "622619", "622620"}
|
||||
# 必须18位的BIN
|
||||
BIN_18 = {"622908"}
|
||||
# 正则:匹配全数字
|
||||
NUM_REG = re.compile(r"^\d+$")
|
||||
|
||||
|
||||
def check_bank_card(card_raw) -> dict:
|
||||
"""校验银行卡号,返回 {card, status, reason}。"""
|
||||
# 处理 pandas 从 Excel 读取时将卡号转为 float 的问题
|
||||
if isinstance(card_raw, float):
|
||||
if card_raw != card_raw: # NaN
|
||||
card = ""
|
||||
else:
|
||||
card = str(int(card_raw))
|
||||
elif isinstance(card_raw, int):
|
||||
card = str(card_raw)
|
||||
else:
|
||||
card = str(card_raw).strip().replace(" ", "")
|
||||
|
||||
if not card:
|
||||
return {"card": card, "status": "无效", "reason": "空白,无卡号"}
|
||||
|
||||
if not NUM_REG.match(card):
|
||||
return {"card": card, "status": "无效", "reason": "非纯数字,属于文字备注/脏数据"}
|
||||
|
||||
if not card.startswith("62"):
|
||||
return {"card": card, "status": "无效", "reason": "非62开头,非标准银联储蓄卡"}
|
||||
|
||||
card_len = len(card)
|
||||
if card_len not in (16, 18, 19):
|
||||
return {"card": card, "status": "错误", "reason": f"位数异常{card_len}位,仅支持16/18/19位银行卡"}
|
||||
|
||||
bin6 = card[:6]
|
||||
|
||||
if bin6 in BIN_16:
|
||||
if card_len == 16:
|
||||
return {"card": card, "status": "正常", "reason": "合规16位储蓄卡"}
|
||||
else:
|
||||
return {"card": card, "status": "错误", "reason": f"BIN{bin6}标准16位,录入位数错误"}
|
||||
|
||||
if bin6 in BIN_18:
|
||||
if card_len == 18:
|
||||
return {"card": card, "status": "正常", "reason": "合规18位兴业储蓄卡"}
|
||||
else:
|
||||
return {"card": card, "status": "错误", "reason": f"BIN{bin6}标准18位,录入位数错误"}
|
||||
|
||||
if card_len == 19:
|
||||
return {"card": card, "status": "正常", "reason": "合规19位储蓄卡"}
|
||||
else:
|
||||
return {"card": card, "status": "错误", "reason": f"BIN{bin6}标准19位,录入位数错误,需人工核对"}
|
||||
|
||||
|
||||
# ===================== 列名常量 =====================
|
||||
COL_IDCARD = "身份证号"
|
||||
COL_CARD_IDCARD = "开户人身份证"
|
||||
COL_STAFF_NAME = "员工姓名"
|
||||
COL_CARD_NAME = "开户人姓名"
|
||||
COL_BANK_ACCOUNT = "银行卡号"
|
||||
|
||||
COL_BANK_STATUS = "银行卡状态"
|
||||
COL_BANK_REASON = "银行卡说明"
|
||||
COL_CHECK_RESULT = "核对结果"
|
||||
COL_CHECK_BASIS = "校验依据"
|
||||
|
||||
|
||||
def _is_empty(val) -> bool:
|
||||
"""判断值是否为空(None、空字符串、NaN)。"""
|
||||
if val is None:
|
||||
return True
|
||||
if isinstance(val, float) and val != val: # NaN
|
||||
return True
|
||||
s = str(val).strip()
|
||||
return s == "" or s.lower() == "nan"
|
||||
|
||||
|
||||
def _normalize_id(val) -> str:
|
||||
"""将身份证号/银行卡号统一转为字符串,处理 pandas 读取 Excel 时的 float 转换问题。"""
|
||||
if val is None:
|
||||
return ""
|
||||
if isinstance(val, float):
|
||||
if val != val: # NaN
|
||||
return ""
|
||||
return str(int(val))
|
||||
if isinstance(val, int):
|
||||
return str(val)
|
||||
return str(val).strip().replace(" ", "")
|
||||
|
||||
|
||||
def check_wage_card(input_path: str, output_path: str = None) -> str:
|
||||
"""读取工资卡汇总表,执行核对并保存结果。
|
||||
|
||||
核对逻辑:
|
||||
1. 开户人身份证为空 -> 标记
|
||||
2. 身份证号 vs 开户人身份证 不一致 -> 标记
|
||||
3. (身份证一致时)开户人姓名为空 -> 标记
|
||||
4. (身份证一致时)员工姓名 vs 开户人姓名 不一致 -> 标记
|
||||
5. 银行卡号校验(check_bank_card)
|
||||
|
||||
Args:
|
||||
input_path: 工资卡汇总表 Excel 路径
|
||||
output_path: 核对结果保存路径,默认在输入文件同目录加 _核对结果
|
||||
|
||||
Returns:
|
||||
核对结果文件路径
|
||||
"""
|
||||
if pd is None:
|
||||
raise RuntimeError("缺少 pandas 依赖,无法处理 Excel")
|
||||
|
||||
df = pd.read_excel(input_path)
|
||||
logger.info("读取工资卡汇总表:%s(%d 行)", input_path, len(df))
|
||||
|
||||
for idx, row in df.iterrows():
|
||||
idcard = _normalize_id(row.get(COL_IDCARD, ""))
|
||||
card_idcard = _normalize_id(row.get(COL_CARD_IDCARD, ""))
|
||||
staff_name = str(row.get(COL_STAFF_NAME, "")).strip()
|
||||
card_name = str(row.get(COL_CARD_NAME, "")).strip()
|
||||
bank_account = row.get(COL_BANK_ACCOUNT, "")
|
||||
|
||||
issues = [] # 问题类型(简短)
|
||||
basis = [] # 校验依据(详细对比信息)
|
||||
|
||||
# ---- 身份证核对 ----
|
||||
if _is_empty(card_idcard):
|
||||
issues.append("开户人身份证为空")
|
||||
elif idcard != card_idcard:
|
||||
issues.append("身份证不一致")
|
||||
basis.append(f"身份证不一致(员工:{idcard} vs 开户人:{card_idcard})")
|
||||
else:
|
||||
# ---- 姓名核对(仅身份证一致时) ----
|
||||
if _is_empty(card_name):
|
||||
issues.append("开户人姓名为空")
|
||||
elif staff_name != card_name:
|
||||
issues.append("姓名不一致")
|
||||
basis.append(f"姓名不一致(员工:{staff_name} vs 开户人:{card_name})")
|
||||
|
||||
# ---- 银行卡校验 ----
|
||||
bk = check_bank_card(bank_account)
|
||||
|
||||
df.at[idx, COL_CHECK_RESULT] = "、".join(issues) if issues else "通过"
|
||||
df.at[idx, COL_CHECK_BASIS] = ";".join(basis) if basis else ""
|
||||
df.at[idx, COL_BANK_STATUS] = bk["status"]
|
||||
df.at[idx, COL_BANK_REASON] = bk["reason"]
|
||||
|
||||
# 统计
|
||||
result_counts = df[df[COL_CHECK_RESULT] != "通过"][COL_CHECK_RESULT].value_counts().to_dict()
|
||||
bank_issues = df[df[COL_BANK_STATUS] != "正常"][COL_BANK_STATUS].value_counts().to_dict()
|
||||
passed = len(df[df[COL_CHECK_RESULT] == "通过"])
|
||||
|
||||
logger.info("核对完成:通过 %d / 总计 %d", passed, len(df))
|
||||
if result_counts:
|
||||
logger.info("核对问题分布:%s", result_counts)
|
||||
if bank_issues:
|
||||
logger.info("银行卡问题:%s", bank_issues)
|
||||
|
||||
# 保存
|
||||
if output_path is None:
|
||||
base, ext = os.path.splitext(input_path)
|
||||
output_path = f"{base}_核对结果{ext}"
|
||||
|
||||
# 将核对结果列移到最前面
|
||||
check_cols = [COL_CHECK_RESULT, COL_CHECK_BASIS, COL_BANK_STATUS, COL_BANK_REASON]
|
||||
other_cols = [c for c in df.columns if c not in check_cols]
|
||||
df = df[check_cols + other_cols]
|
||||
|
||||
df.to_excel(output_path, index=False)
|
||||
logger.info("核对结果已保存:%s", output_path)
|
||||
|
||||
# ---- 生成异常名单(仅含核对不通过的行) ----
|
||||
abnormal = df[df[COL_CHECK_RESULT] != "通过"]
|
||||
if len(abnormal) > 0:
|
||||
base, ext = os.path.splitext(output_path)
|
||||
abnormal_path = f"{os.path.dirname(base)}{os.sep}工资卡异常名单{ext}"
|
||||
abnormal.to_excel(abnormal_path, index=False)
|
||||
logger.info("异常名单已保存:%s(%d 条)", abnormal_path, len(abnormal))
|
||||
else:
|
||||
abnormal_path = None
|
||||
logger.info("无异常记录,跳过异常名单生成")
|
||||
|
||||
return output_path
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""命令行入口:python wage_card_check.py [输入文件] [输出文件]"""
|
||||
setup_logging()
|
||||
input_path = sys.argv[1] if len(sys.argv) > 1 else os.path.join(
|
||||
r"D:\资料\人资\银行卡检查", "工资卡汇总表.xlsx"
|
||||
)
|
||||
output_path = sys.argv[2] if len(sys.argv) > 2 else None
|
||||
try:
|
||||
out = check_wage_card(input_path, output_path)
|
||||
logger.info("===== 工资卡核对完成:%s =====", out)
|
||||
except Exception as e:
|
||||
logger.error("工资卡核对失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,199 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.wage_card
|
||||
@FileName: wage_card_download.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-08 10:20
|
||||
@Description: 银行卡(工资卡)信息下载与核对:抓取「在职 + 离职」人员工资卡数据,
|
||||
将英文字段映射为中文并导出 .xlsx 汇总表。
|
||||
底层能力复用:接口调用(hr_api.py)、会话管理(session_manager.py)、接口地址(config.py)。
|
||||
@Version: 1.3.0
|
||||
|
||||
使用说明:
|
||||
1. 首次运行会调用 HR 登录模块(login.py)完成登录并缓存 cookies 到 .sessions/hr_cookies.json;
|
||||
后续运行自动复用缓存,登录态过期会自动重新登录。
|
||||
2. 直接运行本文件即可下载在职/离职工资卡数据并生成汇总 Excel。
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from datetime import date, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Dict, List
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
|
||||
# 底层复用:接口调用 / 会话管理
|
||||
from app.service.hrbp.ehr.common.hr_api import ( # noqa: E402
|
||||
fetch_wage_card_page,
|
||||
fetch_all_wage_card,
|
||||
HRSessionExpiredError,
|
||||
)
|
||||
from app.service.hrbp.ehr.common.session_manager import ( # noqa: E402
|
||||
build_hr_session,
|
||||
refresh_hr_session,
|
||||
)
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
pd = None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ===================== 配置区(自行修改) =====================
|
||||
# 接口地址、分页大小统一在 ehr/common/config.py 中维护
|
||||
# 导出文件名 & 默认保存目录
|
||||
SAVE_NAME = "工资卡汇总表.xlsx"
|
||||
SAVE_DIR = r"D:\资料\人资\银行卡检查"
|
||||
|
||||
# 英文字段 → 中文字段映射(aa.md 提供)
|
||||
COL_MAP: Dict[str, str] = {
|
||||
"STAFF_NAME": "员工姓名",
|
||||
"STAFF_ID": "员工ID",
|
||||
"IDCARD": "身份证号",
|
||||
"join_date": "入职日期",
|
||||
"leaveOffice_date": "离职日期",
|
||||
"BELONG_UNIT_ORG_NAME": "所属事业部",
|
||||
"DEPT_ORG_NAME": "小组部门",
|
||||
"ORG_FULL_PATH": "组织全路径",
|
||||
"IS_MAIN": "是否主卡",
|
||||
"BANK_TYPE": "银行编码",
|
||||
"BANK_ACCOUNT": "银行卡号",
|
||||
"CARD_ID": "卡片ID",
|
||||
"base_code": "基地编码",
|
||||
"BRANCH_BANK": "支行编码",
|
||||
"bank_province": "银行省份",
|
||||
"bank_city": "银行城市",
|
||||
"wage_card_type": "工资卡类型",
|
||||
"branch_bank_name": "支行名称",
|
||||
"bank_no": "银行行号",
|
||||
"CARD_NAME": "开户人姓名",
|
||||
"CARD_IDCARD": "开户人身份证",
|
||||
"ext_remark": "备注",
|
||||
"si_name": "参保地点",
|
||||
"operator_name": "操作人",
|
||||
"OPERATE_TIME": "操作时间",
|
||||
"BANK_NUM": "银行卡序号",
|
||||
}
|
||||
|
||||
# 自定义列展示顺序(核心字段放最前面)
|
||||
SHOW_ORDER = [
|
||||
"人员类型", "员工姓名", "员工ID", "身份证号", "入职日期", "离职日期",
|
||||
"所属事业部", "小组部门", "组织全路径", "是否主卡",
|
||||
"银行编码", "银行卡号", "开户人姓名", "参保地点", "操作人", "操作时间",
|
||||
]
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 1. 离职筛选时间范围(按当前日期动态计算)
|
||||
# ----------------------------------------------
|
||||
def get_leave_range(today: date = None) -> tuple:
|
||||
"""根据当前日期计算离职筛选时间范围,返回 (开始日期, 结束日期)。
|
||||
|
||||
规则:每月 8 号及之前 → 上月 1 日 到 今天;
|
||||
每月 8 号之后 → 本月 1 日 到 今天。
|
||||
"""
|
||||
today = today or date.today()
|
||||
if today.day <= 8:
|
||||
# 上月 1 日
|
||||
first_this_month = today.replace(day=1)
|
||||
last_prev_month = first_this_month - timedelta(days=1)
|
||||
start = last_prev_month.replace(day=1)
|
||||
else:
|
||||
# 本月 1 日
|
||||
start = today.replace(day=1)
|
||||
end = today
|
||||
return start.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 2. 登录态预检
|
||||
# ----------------------------------------------
|
||||
def preflight(session):
|
||||
"""正式抓取前先探测一次接口,确认 HR 登录态有效;过期则重新登录并重建会话。"""
|
||||
try:
|
||||
fetch_wage_card_page(session, status=1, page_no=1, page_size=1)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("预检发现 HR 登录态已过期,正在重新登录")
|
||||
return refresh_hr_session()
|
||||
return session
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 3. 导出汇总 Excel
|
||||
# ----------------------------------------------
|
||||
def export_excel(data_on_job: List[dict], data_leave: List[dict], save_dir: str = ".") -> str:
|
||||
"""合并在职/离职数据,字段映射为中文、调整列顺序并导出 .xlsx。
|
||||
|
||||
用 pandas 做数据处理,如需后续设置单元格格式可在保存前用 openpyxl 对 ws 加工。
|
||||
"""
|
||||
if pd is None:
|
||||
raise RuntimeError("缺少 pandas 依赖,无法导出 Excel")
|
||||
if not (data_on_job or data_leave):
|
||||
raise ValueError("未查询到任何数据,无法导出")
|
||||
|
||||
total_all = data_on_job + data_leave
|
||||
df = pd.DataFrame(total_all)
|
||||
# 替换英文列为中文
|
||||
df.rename(columns=COL_MAP, inplace=True)
|
||||
# 过滤表中实际存在的列,再拼接剩余其他字段
|
||||
exist_cols = [col for col in SHOW_ORDER if col in df.columns]
|
||||
other_cols = [col for col in df.columns if col not in exist_cols]
|
||||
df = df[exist_cols + other_cols]
|
||||
|
||||
save_path = os.path.abspath(os.path.join(save_dir, SAVE_NAME))
|
||||
df.to_excel(save_path, index=False)
|
||||
logger.info("在职数据:%d 条", len(data_on_job))
|
||||
logger.info("离职数据:%d 条", len(data_leave))
|
||||
logger.info("合计总数据:%d 条", len(total_all))
|
||||
logger.info("文件已保存:%s", save_path)
|
||||
return save_path
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 4. 对外便捷入口
|
||||
# ----------------------------------------------
|
||||
def download_wage_card(save_dir: str = None) -> str:
|
||||
"""下载在职 + 离职工资卡数据并导出汇总 Excel,返回导出文件路径。"""
|
||||
save_dir = save_dir or SAVE_DIR
|
||||
session = preflight(build_hr_session())
|
||||
|
||||
logger.info("===== 开始抓取在职人员工资卡数据 =====")
|
||||
data_on_job = fetch_all_wage_card(session, status=1, status_name="在职")
|
||||
|
||||
logger.info("\n===== 开始抓取离职人员工资卡数据 =====")
|
||||
leave_start, leave_end = get_leave_range()
|
||||
data_leave = fetch_all_wage_card(
|
||||
session, status=2, status_name="离职",
|
||||
leave_start=leave_start, leave_end=leave_end,
|
||||
)
|
||||
|
||||
return export_excel(data_on_job, data_leave, save_dir)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
setup_logging()
|
||||
save_dir = sys.argv[1] if len(sys.argv) > 1 else SAVE_DIR
|
||||
try:
|
||||
out = download_wage_card(save_dir)
|
||||
logger.info("===== 抓取完成,导出:%s =====", out)
|
||||
except Exception as e:
|
||||
logger.error("抓取失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -10,3 +10,4 @@ openpyxl
|
||||
Pillow
|
||||
opencv-python
|
||||
numpy
|
||||
pandas
|
||||
@@ -0,0 +1,820 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: bank_card_check_yingdao.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-08
|
||||
@Description: 银行卡检查(单文件版,app 与影刀共用)——HR 登录(滑块验证码)
|
||||
-> 调用工资卡接口下载在职+离职工资卡数据 -> 核对身份证/姓名/银行卡号
|
||||
-> 导出核对结果 + 异常名单到 D:\\资料\\人资\\银行卡检查\\
|
||||
@Version: 1.0.0
|
||||
|
||||
设计说明(避免维护 app/影刀两套版本):
|
||||
- 单文件自包含,可放任意目录直接运行(含 App 项目目录或影刀环境)。
|
||||
- 内含 HR 登录(滑块验证码识别),保证工资卡查询所需的 hr.37du.co 登录态。
|
||||
|
||||
依赖安装:
|
||||
pip install DrissionPage python-dotenv requests pandas openpyxl opencv-python numpy Pillow
|
||||
|
||||
环境变量(.env 文件或系统变量):
|
||||
HR 登录:hr_login_url / hr_target_url_keyword / hr_login_username / hr_login_password
|
||||
可选:wage_card_output_dir=结果输出目录(默认 D:\\资料\\人资\\银行卡检查)
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import functools
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from datetime import date, timedelta
|
||||
|
||||
# ==================== 第三方库导入 ====================
|
||||
try:
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
except ImportError:
|
||||
ChromiumPage = None
|
||||
ChromiumOptions = None
|
||||
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
except ImportError:
|
||||
load_dotenv = lambda *args, **kwargs: None
|
||||
|
||||
try:
|
||||
import requests
|
||||
except ImportError:
|
||||
requests = None
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
pd = None
|
||||
|
||||
try:
|
||||
import cv2
|
||||
import numpy as np
|
||||
except ImportError:
|
||||
cv2 = None
|
||||
np = None
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging) ====================
|
||||
class _PrintLogger:
|
||||
def debug(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def info(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def warning(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def error(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置 ====================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'BankCardCheck'
|
||||
)
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
COOKIE_FILE_HR = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- HR 系统 ----------
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
HR_LOGIN_URL = f"{HR_BASE_URL}/RedseaPlatform/"
|
||||
HR_SUCCESS_KEYWORD = f"{HR_BASE_URL}/RedseaPlatform/PtPortal.mc?method=classic"
|
||||
|
||||
# ---------- 工资卡接口 ----------
|
||||
WAGE_CARD_URL = f"{HR_BASE_URL}/RedseaPlatform/getPageAjax/HrStaffWageCard.mc"
|
||||
PAGE_MAX_SIZE = 500
|
||||
|
||||
# ---------- 输出 ----------
|
||||
OUTPUT_DIR = os.getenv("wage_card_output_dir") or r"D:\资料\人资\银行卡检查"
|
||||
SAVE_NAME = "工资卡汇总表.xlsx"
|
||||
|
||||
# ---------- HR 登录配置 ----------
|
||||
LOGIN_BTN = "@id=login-btn"
|
||||
ACCOUNT_INPUT_HR = "@id=j_username"
|
||||
PASSWORD_INPUT_HR = "@id=j_password_2"
|
||||
CAPTCHA_CONTAINER = ".:comImageValidate"
|
||||
SLIDER_BTN = ".:v_rightBtn"
|
||||
BG_IMG = ".imgBg"
|
||||
SLIDER_IMG = "css:div.imgBg_3 > img"
|
||||
HR_RETRY_MAX = 5
|
||||
HR_TIMEOUT = 10
|
||||
HR_HEADLESS = False
|
||||
|
||||
# ---------- 工资卡字段映射 ----------
|
||||
COL_MAP = {
|
||||
"STAFF_NAME": "员工姓名",
|
||||
"STAFF_ID": "员工ID",
|
||||
"IDCARD": "身份证号",
|
||||
"join_date": "入职日期",
|
||||
"leaveOffice_date": "离职日期",
|
||||
"BELONG_UNIT_ORG_NAME": "所属事业部",
|
||||
"DEPT_ORG_NAME": "小组部门",
|
||||
"ORG_FULL_PATH": "组织全路径",
|
||||
"IS_MAIN": "是否主卡",
|
||||
"BANK_TYPE": "银行编码",
|
||||
"BANK_ACCOUNT": "银行卡号",
|
||||
"CARD_ID": "卡片ID",
|
||||
"base_code": "基地编码",
|
||||
"BRANCH_BANK": "支行编码",
|
||||
"bank_province": "银行省份",
|
||||
"bank_city": "银行城市",
|
||||
"wage_card_type": "工资卡类型",
|
||||
"branch_bank_name": "支行名称",
|
||||
"bank_no": "银行行号",
|
||||
"CARD_NAME": "开户人姓名",
|
||||
"CARD_IDCARD": "开户人身份证",
|
||||
"ext_remark": "备注",
|
||||
"si_name": "参保地点",
|
||||
"operator_name": "操作人",
|
||||
"OPERATE_TIME": "操作时间",
|
||||
"BANK_NUM": "银行卡序号",
|
||||
}
|
||||
SHOW_ORDER = [
|
||||
"人员类型", "员工姓名", "员工ID", "身份证号", "入职日期", "离职日期",
|
||||
"所属事业部", "小组部门", "组织全路径", "是否主卡",
|
||||
"银行编码", "银行卡号", "开户人姓名", "参保地点", "操作人", "操作时间",
|
||||
]
|
||||
|
||||
# ---------- 核对相关列名 ----------
|
||||
COL_IDCARD = "身份证号"
|
||||
COL_CARD_IDCARD = "开户人身份证"
|
||||
COL_STAFF_NAME = "员工姓名"
|
||||
COL_CARD_NAME = "开户人姓名"
|
||||
COL_BANK_ACCOUNT = "银行卡号"
|
||||
COL_BANK_STATUS = "银行卡状态"
|
||||
COL_BANK_REASON = "银行卡说明"
|
||||
COL_CHECK_RESULT = "核对结果"
|
||||
COL_CHECK_BASIS = "校验依据"
|
||||
|
||||
# ---------- 银行卡校验规则 ----------
|
||||
BIN_16 = {"621483", "622622", "621691", "622619", "622620"}
|
||||
BIN_18 = {"622908"}
|
||||
NUM_REG = re.compile(r"^\d+$")
|
||||
|
||||
|
||||
# ==================== 重试装饰器 ====================
|
||||
def retry(max_attempts=3):
|
||||
def decorator(func):
|
||||
@functools.wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
last_exc = None
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt >= max_attempts:
|
||||
logger.error("%s 连续 %d 次失败: %s", func.__name__, max_attempts, e)
|
||||
break
|
||||
delay = 1.0 * (2.0 ** (attempt - 1)) * random.uniform(0.5, 1.5)
|
||||
logger.warning("%s 第 %d 次失败: %s,%.2f 秒后重试", func.__name__, attempt, e, delay)
|
||||
time.sleep(delay)
|
||||
raise last_exc
|
||||
return wrapper
|
||||
return decorator
|
||||
|
||||
|
||||
# ==================== Cookies 持久化 ====================
|
||||
def _ensure_dir(path):
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
def save_browser_cookies(browser_page, path):
|
||||
cookies = browser_page.cookies(all_domains=True)
|
||||
if not cookies:
|
||||
logger.warning("未获取到 Cookies,跳过保存")
|
||||
return
|
||||
_ensure_dir(os.path.dirname(path))
|
||||
with open(path, 'w', encoding='utf-8') as f:
|
||||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||||
logger.info("已保存 %d 个 Cookies 到 %s", len(cookies), path)
|
||||
|
||||
|
||||
def load_cookies(path):
|
||||
if not os.path.exists(path):
|
||||
return None
|
||||
with open(path, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
# ==================== HR 登录(滑块验证码) ====================
|
||||
def match_slider_dual(bg_bytes, slider_bytes):
|
||||
"""模板匹配滑块缺口,返回物理距离(px)。缺 opencv 时抛清晰错误。"""
|
||||
if cv2 is None or np is None:
|
||||
raise RuntimeError("缺少滑块识别依赖,请安装: pip install opencv-python numpy Pillow")
|
||||
|
||||
bg_img = cv2.imdecode(np.frombuffer(bg_bytes, np.uint8), cv2.IMREAD_COLOR)
|
||||
slider_color = cv2.imdecode(np.frombuffer(slider_bytes, np.uint8), cv2.IMREAD_UNCHANGED)
|
||||
if bg_img is None or slider_color is None:
|
||||
raise RuntimeError("无法解码验证码图片")
|
||||
|
||||
bg_h, bg_w = bg_img.shape[:2]
|
||||
x_offset, y_offset = 0, 0
|
||||
if len(slider_color.shape) == 3 and slider_color.shape[2] == 4:
|
||||
alpha = slider_color[:, :, 3]
|
||||
slider_rgb = slider_color[:, :, :3]
|
||||
ys, xs = np.where(alpha > 0)
|
||||
if len(ys) > 0:
|
||||
y_min, y_max = np.min(ys), np.max(ys)
|
||||
x_min, x_max = np.min(xs), np.max(xs)
|
||||
slider_rgb = slider_rgb[y_min:y_max + 1, x_min:x_max + 1]
|
||||
x_offset, y_offset = x_min, y_min
|
||||
else:
|
||||
slider_rgb = slider_color[:, :, :3] if len(slider_color.shape) == 3 else slider_color
|
||||
|
||||
s_h, s_w = slider_rgb.shape[:2]
|
||||
gray_bg = cv2.GaussianBlur(cv2.cvtColor(bg_img, cv2.COLOR_BGR2GRAY), (3, 3), 0)
|
||||
gray_slider = cv2.GaussianBlur(cv2.cvtColor(slider_rgb, cv2.COLOR_BGR2GRAY), (3, 3), 0)
|
||||
bg_edges = cv2.Canny(gray_bg, 50, 150)
|
||||
slider_edges = cv2.Canny(gray_slider, 50, 150)
|
||||
result = cv2.matchTemplate(bg_edges, slider_edges, cv2.TM_CCOEFF_NORMED)
|
||||
|
||||
candidates = []
|
||||
temp_result = result.copy()
|
||||
for _ in range(6):
|
||||
_, max_val, _, max_loc = cv2.minMaxLoc(temp_result)
|
||||
if max_val < 0.03:
|
||||
break
|
||||
candidates.append((max_val, max_loc))
|
||||
y0 = max(0, max_loc[1] - s_h // 2); y1 = min(temp_result.shape[0], max_loc[1] + s_h // 2)
|
||||
x0 = max(0, max_loc[0] - s_w // 2); x1 = min(temp_result.shape[1], max_loc[0] + s_w // 2)
|
||||
temp_result[y0:y1, x0:x1] = -2.0
|
||||
|
||||
if not candidates:
|
||||
raise RuntimeError("无有效滑块候选")
|
||||
|
||||
right_limit = bg_w - s_w - max(15, int(bg_w * 0.06))
|
||||
|
||||
def region_whiteness(x, y, w, h):
|
||||
roi = bg_img[y:y + h, x:x + w]
|
||||
if roi.size == 0:
|
||||
return 0.0
|
||||
return float(np.all(roi > 200, axis=2).mean())
|
||||
|
||||
scored = []
|
||||
for val, loc in candidates:
|
||||
x, y = loc
|
||||
if x <= s_w or x > right_limit:
|
||||
continue
|
||||
scored.append((val + 0.5 * region_whiteness(x, y, s_w, s_h), val, loc))
|
||||
|
||||
if scored:
|
||||
scored.sort(key=lambda t: t[0], reverse=True)
|
||||
best_val, best_loc = scored[0][1], scored[0][2]
|
||||
else:
|
||||
best_val, best_loc = candidates[0]
|
||||
|
||||
distance = best_loc[0] - x_offset
|
||||
if distance < 0:
|
||||
distance = 0
|
||||
if distance + s_w > bg_w:
|
||||
distance = bg_w - s_w
|
||||
return distance
|
||||
|
||||
|
||||
def generate_track(distance):
|
||||
overshoot = random.randint(2, 6) if random.random() < 0.75 else 0
|
||||
aim = distance + overshoot
|
||||
steps = []
|
||||
moved = 0
|
||||
y = 0
|
||||
while moved < aim:
|
||||
remain = aim - moved
|
||||
if remain > 80:
|
||||
dx = min(remain, random.randint(9, 15)); dt = random.uniform(0.010, 0.022)
|
||||
elif remain > 35:
|
||||
dx = min(remain, random.randint(5, 9)); dt = random.uniform(0.012, 0.028)
|
||||
elif remain > 12:
|
||||
dx = min(remain, random.randint(2, 5)); dt = random.uniform(0.016, 0.040)
|
||||
else:
|
||||
dx = min(remain, random.randint(1, 3)); dt = random.uniform(0.020, 0.060)
|
||||
if random.random() < 0.22:
|
||||
y = max(-2, min(2, y + random.choice([-1, 1])))
|
||||
else:
|
||||
y = int(round(y * 0.6))
|
||||
steps.append((dx, y, dt))
|
||||
moved += dx
|
||||
if overshoot > 0:
|
||||
back = overshoot
|
||||
while back > 0:
|
||||
dx = -min(back, random.randint(1, 3))
|
||||
steps.append((dx, random.choice([-1, 0, 1]), random.uniform(0.030, 0.080)))
|
||||
back += dx
|
||||
if random.random() < 0.65:
|
||||
steps.extend([(0, 0, random.uniform(0.060, 0.140)),
|
||||
(1, 0, random.uniform(0.020, 0.050)),
|
||||
(-1, 0, random.uniform(0.020, 0.050))])
|
||||
return steps
|
||||
|
||||
|
||||
def perform_slide(page, btn, distance_css):
|
||||
if distance_css <= 0:
|
||||
return False
|
||||
mid = btn.rect.midpoint
|
||||
steps = generate_track(distance_css)
|
||||
try:
|
||||
page.actions.move_to((mid[0] + random.uniform(-3, 3), mid[1] + random.uniform(-2, 2)),
|
||||
duration=random.uniform(0.25, 0.60))
|
||||
time.sleep(random.uniform(0.18, 0.45))
|
||||
page.actions.hold(on_ele=btn)
|
||||
time.sleep(random.uniform(0.12, 0.28))
|
||||
for dx, dy, dt in steps:
|
||||
if dx == 0 and dy == 0:
|
||||
time.sleep(dt)
|
||||
else:
|
||||
page.actions.move(offset_x=dx, offset_y=dy, duration=dt)
|
||||
time.sleep(random.uniform(0.10, 0.26))
|
||||
page.actions.release()
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.warning("拖拽异常:%s", e)
|
||||
return False
|
||||
|
||||
|
||||
def handle_hr_captcha(page):
|
||||
for retry_no in range(HR_RETRY_MAX):
|
||||
logger.info("--- HR 第 %d 次尝试验证 ---", retry_no + 1)
|
||||
try:
|
||||
container = page.ele(CAPTCHA_CONTAINER, timeout=HR_TIMEOUT)
|
||||
if not container:
|
||||
continue
|
||||
bg_ele = container.ele(BG_IMG) or container.ele('div[style*="background-image"]')
|
||||
slider_ele = container.ele(SLIDER_IMG)
|
||||
if not bg_ele or not slider_ele:
|
||||
continue
|
||||
if slider_ele.tag != 'img':
|
||||
inner = slider_ele.ele('tag:img')
|
||||
if inner:
|
||||
slider_ele = inner
|
||||
try:
|
||||
page.run_js('arguments[0].style.display = "none"', slider_ele)
|
||||
time.sleep(0.2)
|
||||
bg_screenshot = bg_ele.get_screenshot(as_bytes='png')
|
||||
page.run_js('arguments[0].style.display = ""', slider_ele)
|
||||
time.sleep(0.2)
|
||||
slider_screenshot = slider_ele.get_screenshot(as_bytes='png')
|
||||
except Exception:
|
||||
page.run_js('arguments[0].style.display = ""', slider_ele)
|
||||
continue
|
||||
|
||||
distance_phys = match_slider_dual(bg_screenshot, slider_screenshot)
|
||||
dpr = page.run_js('return window.devicePixelRatio') or 1
|
||||
distance_css = distance_phys / dpr
|
||||
logger.info("匹配距离 %dpx -> CSS %.1fpx", distance_phys, distance_css)
|
||||
|
||||
btn = page.ele(SLIDER_BTN)
|
||||
if btn and perform_slide(page, btn, distance_css):
|
||||
time.sleep(2)
|
||||
if HR_SUCCESS_KEYWORD in page.url:
|
||||
return True
|
||||
if not page.ele(CAPTCHA_CONTAINER, timeout=1):
|
||||
return True
|
||||
time.sleep(2)
|
||||
except Exception as e:
|
||||
logger.warning("验证异常:%s", e)
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
def hr_login(username=None, password=None):
|
||||
load_dotenv()
|
||||
final_username = username or os.getenv('hr_login_username')
|
||||
final_password = password or os.getenv('hr_login_password')
|
||||
if not final_username or not final_password:
|
||||
raise RuntimeError("HR 用户名或密码未提供,请设置环境变量 hr_login_username / hr_login_password")
|
||||
|
||||
if ChromiumPage is None:
|
||||
raise RuntimeError("缺少 DrissionPage 依赖,请先安装: pip install DrissionPage")
|
||||
|
||||
co = ChromiumOptions()
|
||||
if HR_HEADLESS:
|
||||
co.headless()
|
||||
page = ChromiumPage(co)
|
||||
|
||||
saved = load_cookies(COOKIE_FILE_HR)
|
||||
if saved:
|
||||
try:
|
||||
page.set.cookies(saved)
|
||||
page.get(HR_LOGIN_URL)
|
||||
time.sleep(2)
|
||||
if HR_SUCCESS_KEYWORD in page.url:
|
||||
logger.info("已通过缓存的 HR Cookies 登录")
|
||||
save_browser_cookies(page, COOKIE_FILE_HR)
|
||||
page.quit()
|
||||
return
|
||||
except Exception as e:
|
||||
logger.warning("复用 HR Cookies 失败:%s", e)
|
||||
else:
|
||||
page.get(HR_LOGIN_URL)
|
||||
time.sleep(2)
|
||||
|
||||
if HR_SUCCESS_KEYWORD in page.url:
|
||||
logger.info("HR 已登录")
|
||||
save_browser_cookies(page, COOKIE_FILE_HR)
|
||||
page.quit()
|
||||
return
|
||||
|
||||
try:
|
||||
account = page.ele(ACCOUNT_INPUT_HR)
|
||||
if not account:
|
||||
raise RuntimeError("找不到 HR 账号输入框")
|
||||
account.clear(); account.input(final_username); time.sleep(0.5)
|
||||
pwd = page.ele(PASSWORD_INPUT_HR)
|
||||
if not pwd:
|
||||
raise RuntimeError("找不到 HR 密码输入框")
|
||||
pwd.clear(); pwd.input(final_password); time.sleep(0.5)
|
||||
login_btn = page.ele(LOGIN_BTN)
|
||||
if not login_btn:
|
||||
raise RuntimeError("找不到登录按钮")
|
||||
login_btn.click(); time.sleep(3)
|
||||
|
||||
if HR_SUCCESS_KEYWORD in page.url:
|
||||
logger.info("HR 登录成功(无滑块)")
|
||||
elif handle_hr_captcha(page):
|
||||
logger.info("HR 登录成功(验证通过)")
|
||||
else:
|
||||
raise RuntimeError("HR 登录失败(滑块验证未通过)")
|
||||
save_browser_cookies(page, COOKIE_FILE_HR)
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def get_hr_session():
|
||||
"""确保存在有效的 hr.37du.co cookies;必要时触发 HR 登录。"""
|
||||
hr_cookies = load_cookies(COOKIE_FILE_HR)
|
||||
has_hr = any(c.get("domain") and c["domain"].endswith("hr.37du.co") for c in (hr_cookies or []))
|
||||
if not has_hr:
|
||||
logger.info("无 hr.37du.co 登录态,执行 HR 登录")
|
||||
hr_login()
|
||||
else:
|
||||
logger.info("复用已保存的 HR 登录态(hr.37du.co)")
|
||||
return _build_hr_session()
|
||||
|
||||
|
||||
def _build_hr_session():
|
||||
if requests is None:
|
||||
raise RuntimeError("缺少 requests 依赖,请先安装")
|
||||
cookies = load_cookies(COOKIE_FILE_HR)
|
||||
if not cookies:
|
||||
raise RuntimeError("无 hr cookies,请先完成 HR 登录")
|
||||
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:
|
||||
if c.get("domain") and c["domain"].endswith("hr.37du.co"):
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
# ==================== 工资卡接口 ====================
|
||||
class HRSessionExpiredError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def fetch_wage_card_page(session, status, page_no=1, page_size=PAGE_MAX_SIZE,
|
||||
leave_start=None, leave_end=None):
|
||||
params = {
|
||||
"start": (page_no - 1) * page_size,
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
"ftl_list_STRU_TREE_CODE": "cq37du",
|
||||
"sortName": "hr_staff_wage_card.STAFF_NAME",
|
||||
"sortType": "asc",
|
||||
"commonQuery": "[]",
|
||||
"person_status": status,
|
||||
}
|
||||
if status == 1:
|
||||
params["leaveOffice_date"] = ""
|
||||
elif leave_start and leave_end:
|
||||
params["leaveOffice_date[0]"] = leave_start
|
||||
params["leaveOffice_date[1]"] = leave_end
|
||||
params["leaveOffice_date_start"] = leave_start
|
||||
params["leaveOffice_date_end"] = leave_end
|
||||
|
||||
resp = session.post(WAGE_CARD_URL, data=params, timeout=20)
|
||||
if not resp:
|
||||
raise RuntimeError("工资卡请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"工资卡接口状态码异常: {resp.status_code}")
|
||||
text = resp.text or ""
|
||||
if text and not text.lstrip().startswith(("{", "[")):
|
||||
raise HRSessionExpiredError("HR 登录态已过期,接口返回非 JSON 内容")
|
||||
try:
|
||||
return resp.json()
|
||||
except Exception:
|
||||
body = text[:200]
|
||||
raise RuntimeError(f"工资卡接口返回非 JSON 数据(状态码 {resp.status_code}): {body}")
|
||||
|
||||
|
||||
def fetch_all_wage_card(session, status, status_name, leave_start=None, leave_end=None):
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_wage_card_page(session, status, page_no, PAGE_MAX_SIZE, leave_start, leave_end)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("【%s】HR 登录态过期,重新登录后续抓", status_name)
|
||||
hr_login()
|
||||
session = _build_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
|
||||
|
||||
|
||||
# ==================== 离职时间范围 ====================
|
||||
def get_leave_range(today=None):
|
||||
"""根据当前日期计算离职筛选时间范围,返回 (开始日期, 结束日期)。
|
||||
|
||||
规则:每月 8 号及之前 → 上月 1 日 到 今天;
|
||||
每月 8 号之后 → 本月 1 日 到 今天。
|
||||
"""
|
||||
today = today or date.today()
|
||||
if today.day <= 8:
|
||||
first_this_month = today.replace(day=1)
|
||||
last_prev_month = first_this_month - timedelta(days=1)
|
||||
start = last_prev_month.replace(day=1)
|
||||
else:
|
||||
start = today.replace(day=1)
|
||||
end = today
|
||||
return start.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ==================== 工资卡导出 Excel ====================
|
||||
def export_excel(data_on_job, data_leave, save_dir):
|
||||
if pd is None:
|
||||
raise RuntimeError("缺少 pandas 依赖,无法导出 Excel")
|
||||
if not (data_on_job or data_leave):
|
||||
raise ValueError("未查询到任何数据,无法导出")
|
||||
|
||||
total_all = data_on_job + data_leave
|
||||
df = pd.DataFrame(total_all)
|
||||
df.rename(columns=COL_MAP, inplace=True)
|
||||
exist_cols = [col for col in SHOW_ORDER if col in df.columns]
|
||||
other_cols = [col for col in df.columns if col not in exist_cols]
|
||||
df = df[exist_cols + other_cols]
|
||||
|
||||
_ensure_dir(save_dir)
|
||||
save_path = os.path.join(save_dir, SAVE_NAME)
|
||||
df.to_excel(save_path, index=False)
|
||||
logger.info("在职数据:%d 条", len(data_on_job))
|
||||
logger.info("离职数据:%d 条", len(data_leave))
|
||||
logger.info("合计总数据:%d 条", len(total_all))
|
||||
logger.info("文件已保存:%s", save_path)
|
||||
return save_path
|
||||
|
||||
|
||||
# ==================== 银行卡校验 ====================
|
||||
def check_bank_card(card_raw):
|
||||
card = str(card_raw).strip()
|
||||
if isinstance(card_raw, float):
|
||||
if card_raw != card_raw:
|
||||
card = ""
|
||||
else:
|
||||
card = str(int(card_raw))
|
||||
elif isinstance(card_raw, int):
|
||||
card = str(card_raw)
|
||||
else:
|
||||
card = str(card_raw).strip().replace(" ", "")
|
||||
|
||||
if not card:
|
||||
return {"card": card, "status": "无效", "reason": "空白,无卡号"}
|
||||
if not NUM_REG.match(card):
|
||||
return {"card": card, "status": "无效", "reason": "非纯数字,属于文字备注/脏数据"}
|
||||
if not card.startswith("62"):
|
||||
return {"card": card, "status": "无效", "reason": "非62开头,非标准银联储蓄卡"}
|
||||
|
||||
card_len = len(card)
|
||||
if card_len not in (16, 18, 19):
|
||||
return {"card": card, "status": "错误", "reason": f"位数异常{card_len}位,仅支持16/18/19位银行卡"}
|
||||
|
||||
bin6 = card[:6]
|
||||
if bin6 in BIN_16:
|
||||
if card_len == 16:
|
||||
return {"card": card, "status": "正常", "reason": "合规16位储蓄卡"}
|
||||
else:
|
||||
return {"card": card, "status": "错误", "reason": f"BIN{bin6}标准16位,录入位数错误"}
|
||||
if bin6 in BIN_18:
|
||||
if card_len == 18:
|
||||
return {"card": card, "status": "正常", "reason": "合规18位兴业储蓄卡"}
|
||||
else:
|
||||
return {"card": card, "status": "错误", "reason": f"BIN{bin6}标准18位,录入位数错误"}
|
||||
if card_len == 19:
|
||||
return {"card": card, "status": "正常", "reason": "合规19位储蓄卡"}
|
||||
else:
|
||||
return {"card": card, "status": "错误", "reason": f"BIN{bin6}标准19位,录入位数错误,需人工核对"}
|
||||
|
||||
|
||||
# ==================== 核对辅助 ====================
|
||||
def _is_empty(val):
|
||||
if val is None:
|
||||
return True
|
||||
if isinstance(val, float) and val != val:
|
||||
return True
|
||||
s = str(val).strip()
|
||||
return s == "" or s.lower() == "nan"
|
||||
|
||||
|
||||
def _normalize_id(val):
|
||||
if val is None:
|
||||
return ""
|
||||
if isinstance(val, float):
|
||||
if val != val:
|
||||
return ""
|
||||
return str(int(val))
|
||||
if isinstance(val, int):
|
||||
return str(val)
|
||||
return str(val).strip().replace(" ", "")
|
||||
|
||||
|
||||
# ==================== 核对主逻辑 ====================
|
||||
def check_wage_card(input_path, output_path=None):
|
||||
"""读取工资卡汇总表,执行核对并保存结果 + 异常名单。"""
|
||||
if pd is None:
|
||||
raise RuntimeError("缺少 pandas 依赖,无法处理 Excel")
|
||||
|
||||
df = pd.read_excel(input_path)
|
||||
logger.info("读取工资卡汇总表:%s(%d 行)", input_path, len(df))
|
||||
|
||||
for idx, row in df.iterrows():
|
||||
idcard = _normalize_id(row.get(COL_IDCARD, ""))
|
||||
card_idcard = _normalize_id(row.get(COL_CARD_IDCARD, ""))
|
||||
staff_name = str(row.get(COL_STAFF_NAME, "")).strip()
|
||||
card_name = str(row.get(COL_CARD_NAME, "")).strip()
|
||||
bank_account = row.get(COL_BANK_ACCOUNT, "")
|
||||
|
||||
issues = []
|
||||
basis = []
|
||||
|
||||
# ---- 身份证核对 ----
|
||||
if _is_empty(card_idcard):
|
||||
issues.append("开户人身份证为空")
|
||||
elif idcard != card_idcard:
|
||||
issues.append("身份证不一致")
|
||||
basis.append(f"身份证不一致(员工:{idcard} vs 开户人:{card_idcard})")
|
||||
else:
|
||||
# ---- 姓名核对(仅身份证一致时) ----
|
||||
if _is_empty(card_name):
|
||||
issues.append("开户人姓名为空")
|
||||
elif staff_name != card_name:
|
||||
issues.append("姓名不一致")
|
||||
basis.append(f"姓名不一致(员工:{staff_name} vs 开户人:{card_name})")
|
||||
|
||||
# ---- 银行卡校验 ----
|
||||
bk = check_bank_card(bank_account)
|
||||
|
||||
df.at[idx, COL_CHECK_RESULT] = "、".join(issues) if issues else "通过"
|
||||
df.at[idx, COL_CHECK_BASIS] = ";".join(basis) if basis else ""
|
||||
df.at[idx, COL_BANK_STATUS] = bk["status"]
|
||||
df.at[idx, COL_BANK_REASON] = bk["reason"]
|
||||
|
||||
# 统计
|
||||
result_counts = df[df[COL_CHECK_RESULT] != "通过"][COL_CHECK_RESULT].value_counts().to_dict()
|
||||
bank_issues = df[df[COL_BANK_STATUS] != "正常"][COL_BANK_STATUS].value_counts().to_dict()
|
||||
passed = len(df[df[COL_CHECK_RESULT] == "通过"])
|
||||
|
||||
logger.info("核对完成:通过 %d / 总计 %d", passed, len(df))
|
||||
if result_counts:
|
||||
logger.info("核对问题分布:%s", result_counts)
|
||||
if bank_issues:
|
||||
logger.info("银行卡问题:%s", bank_issues)
|
||||
|
||||
# 保存核对结果
|
||||
if output_path is None:
|
||||
base, ext = os.path.splitext(input_path)
|
||||
output_path = f"{base}_核对结果{ext}"
|
||||
|
||||
check_cols = [COL_CHECK_RESULT, COL_CHECK_BASIS, COL_BANK_STATUS, COL_BANK_REASON]
|
||||
other_cols = [c for c in df.columns if c not in check_cols]
|
||||
df = df[check_cols + other_cols]
|
||||
df.to_excel(output_path, index=False)
|
||||
logger.info("核对结果已保存:%s", output_path)
|
||||
|
||||
# 生成异常名单
|
||||
abnormal = df[df[COL_CHECK_RESULT] != "通过"]
|
||||
if len(abnormal) > 0:
|
||||
base, ext = os.path.splitext(output_path)
|
||||
abnormal_path = os.path.join(os.path.dirname(base), f"工资卡异常名单{ext}")
|
||||
abnormal.to_excel(abnormal_path, index=False)
|
||||
logger.info("异常名单已保存:%s(%d 条)", abnormal_path, len(abnormal))
|
||||
else:
|
||||
logger.info("无异常记录,跳过异常名单生成")
|
||||
|
||||
return output_path
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def download_wage_card(save_dir=None):
|
||||
"""下载在职 + 离职工资卡数据并导出汇总 Excel。"""
|
||||
save_dir = save_dir or OUTPUT_DIR
|
||||
# get_hr_session 会检查 cookies,不存在时自动触发 HR 登录
|
||||
session = get_hr_session()
|
||||
|
||||
# 预检登录态
|
||||
try:
|
||||
fetch_wage_card_page(session, status=1, page_no=1, page_size=1)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("预检发现 HR 登录态已过期,正在重新登录")
|
||||
hr_login()
|
||||
session = _build_hr_session()
|
||||
|
||||
logger.info("===== 开始抓取在职人员工资卡数据 =====")
|
||||
data_on_job = fetch_all_wage_card(session, status=1, status_name="在职")
|
||||
|
||||
logger.info("===== 开始抓取离职人员工资卡数据 =====")
|
||||
leave_start, leave_end = get_leave_range()
|
||||
data_leave = fetch_all_wage_card(
|
||||
session, status=2, status_name="离职",
|
||||
leave_start=leave_start, leave_end=leave_end,
|
||||
)
|
||||
|
||||
return export_excel(data_on_job, data_leave, save_dir)
|
||||
|
||||
|
||||
def run_bank_card_check():
|
||||
"""银行卡检查主流程:工资卡下载 -> 工资卡核对。"""
|
||||
results = {}
|
||||
|
||||
# ---- 第一步:下载工资卡汇总表 ----
|
||||
logger.info("=" * 60)
|
||||
logger.info("【银行卡检查】第一步:下载工资卡汇总表")
|
||||
logger.info("=" * 60)
|
||||
wage_path = None
|
||||
try:
|
||||
wage_path = download_wage_card()
|
||||
results["工资卡"] = wage_path
|
||||
logger.info("工资卡下载完成:%s", wage_path)
|
||||
except Exception as e:
|
||||
logger.error("工资卡下载失败:%s", e)
|
||||
results["工资卡"] = f"失败:{e}"
|
||||
|
||||
# ---- 第二步:核对工资卡数据 ----
|
||||
logger.info("=" * 60)
|
||||
logger.info("【银行卡检查】第二步:核对工资卡数据")
|
||||
logger.info("=" * 60)
|
||||
if wage_path:
|
||||
try:
|
||||
check_path = check_wage_card(wage_path)
|
||||
results["核对结果"] = check_path
|
||||
logger.info("工资卡核对完成:%s", check_path)
|
||||
except Exception as e:
|
||||
logger.error("工资卡核对失败:%s", e)
|
||||
results["核对结果"] = f"失败:{e}"
|
||||
else:
|
||||
logger.warning("工资卡汇总表未生成,跳过核对")
|
||||
results["核对结果"] = "跳过(工资卡下载失败)"
|
||||
|
||||
# ---- 汇总 ----
|
||||
logger.info("=" * 60)
|
||||
logger.info("【银行卡检查】全部完成,结果汇总:")
|
||||
for name, path in results.items():
|
||||
logger.info(" %s:%s", name, path)
|
||||
logger.info("=" * 60)
|
||||
return results
|
||||
|
||||
|
||||
# ==================== 主入口 ====================
|
||||
def main():
|
||||
load_dotenv()
|
||||
run_bank_card_check()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||