diff --git a/.trae/documents/dingtalk-message-sender.md b/.trae/documents/dingtalk-message-sender.md deleted file mode 100644 index 8f8a790..0000000 --- a/.trae/documents/dingtalk-message-sender.md +++ /dev/null @@ -1,119 +0,0 @@ -# 钉钉消息推送工具 实现计划 - -## Context(背景) - -项目目前只有基于 DrissionPage 的 **浏览器** 自动化(OA 审批),通用工具统一放在 `app/utils/`(见 [logger.py](file:///d:/work/code/Process-Automation/app/utils/logger.py)、[intelligent_retry.py](file:///d:/work/code/Process-Automation/app/utils/intelligent_retry.py))。 - -新需求:写一个 **钉钉桌面客户端** 消息推送工具——通过模拟键盘快捷键 + 剪贴板,向指定 **群名/人名** 发送 **文本和文档**。钉钉是桌面客户端(非浏览器),走不了 DrissionPage,需要引入桌面自动化依赖。 - -用户描述的操作链路:`Ctrl+D 激活钉钉 → Ctrl+Shift+F 搜索 → 回车确认 → 粘贴文本/文档 → 回车发送`。 - -## 已确认的决策 - -1. **窗口激活**:两者都支持,默认发 `Ctrl+D` 全局热键;失败自动回退到 win32 按标题查窗口置前。 -2. **文本+文件**:钉钉无法一条消息同时贴文本和文件 → 先发文本、再发文件(两条消息)。 - -## 依赖 - -新增到 [requirements.txt](file:///d:/work/code/Process-Automation/requirements.txt) 和 [pyproject.toml](file:///d:/work/code/Process-Automation/pyproject.toml): - -- `pyautogui` —— 发送键盘快捷键(`hotkey` / `press`) -- `pywin32` —— 窗口查找激活(`win32gui`)+ 文件剪贴板(`win32clipboard` 的 `CF_HDROP`) -- `pyperclip` —— 文本剪贴板(`pyautogui` 会自动带上,显式声明便于理解) - -## 文件改动 - -### 1. 新增 `app/utils/dingtalk_sender.py`(核心) - -遵循项目风格:文件头注释块(`@Module/@FileName/@Author/@CreateTime/@Description/@Version`)、复用 [get_logger](file:///d:/work/code/Process-Automation/app/utils/logger.py) 做日志、复用 [retry](file:///d:/work/code/Process-Automation/app/utils/intelligent_retry.py) 装饰关键步骤。 - -**模块结构**: - -``` -日志 & 常量 -├─ logger = get_logger(__name__) -├─ 默认等待时间常量(搜索结果、发送、激活) - -窗口激活 -├─ _find_dingtalk_hwnd() # win32gui.EnumWindows 按标题"钉钉"查找 -├─ _activate_by_win32() # ShowWindow(SW_RESTORE) + SetForegroundWindow(含 Alt trick 绕过前台锁) -└─ _activate_by_hotkey() # pyautogui.hotkey('ctrl','d') - -剪贴板 -├─ _set_text_to_clipboard(text) # pyperclip.copy -└─ _set_file_to_clipboard(path) # win32clipboard + struct 打包 DROPFILES(CF_HDROP, fWide=1, utf-16-le) - -搜索定位 -└─ _search_and_open(target) # Ctrl+Shift+F → 粘贴 target → 回车 → 等待 - -发送 -├─ _send_text(text) # 剪贴板文本 → Ctrl+V → 回车 -└─ _send_file(path) # 剪贴板文件 → Ctrl+V → 等待预览框 → 回车 - -高层 API -├─ class DingTalkSender # 封装可调参数(各步骤等待时间、激活方式) -│ └─ send(target, text, file_path, is_group) -├─ send_dingtalk_message(target, text, file_path, is_group, ...) # 一次性便捷函数 -├─ send_to_group(group_name, text, file_path) # 群消息快捷封装 -└─ send_to_person(name, text, file_path) # 个人消息快捷封装 -``` - -**主流程 `DingTalkSender.send`**: - -1. 激活钉钉窗口(默认 Ctrl+D,失败回退 win32) -2. `Ctrl+Shift+F` 打开搜索 → 粘贴 `target` → 回车 → 等待 `wait_search` 秒 -3. 若有 `text`:粘贴文本 → 回车发送 → 等待 `wait_send` 秒 -4. 若有 `file_path`:文件入剪贴板 → `Ctrl+V` → 等待 `wait_file_preview` 秒(预览框) → 回车发送 -5. 全程 logger.info 记录每步,失败抛 RuntimeError 含清晰提示 - -**关键实现细节**: - -- **中文输入**:一律走剪贴板 `Ctrl+V`,不用 `pyautogui.write`(不支持中文且受输入法干扰)。 -- **文件剪贴板**:`DROPFILES` 结构(20 字节:`pFiles=20, pt=(0,0), fNC=0, fWide=1`)+ 文件绝对路径 `utf-16-le` 编码 + 双 `\0` 结尾,用 `win32clipboard.SetClipboardData(CF_HDROP, data)`。路径必须 `os.path.abspath` 转绝对路径。 -- **窗口置前 trick**:`SetForegroundWindow` 会被 Windows 前台锁拦截,先 `pyautogui.press('alt')` 或 `win32gui.SendMessage(shell_hwnd, WM_SYSCOMMAND, SC_RESTORE, 0)` 再置前。 -- **搜索回车**:钉钉搜索框回车默认选中第一条结果并进入会话,焦点自动转到消息输入框。 -- **参数校验**:`target` 必填;`text` 和 `file_path` 至少传一个;`file_path` 不存在则提前报错。 -- **`@retry` 包裹**:激活、搜索两个易受环境影响的关键步骤用 `@retry(max_attempts=2)`,发送步骤不重试(避免重复发消息)。 - -**对外 API 签名**: - -```python -def send_dingtalk_message( - target: str, - text: str = "", - file_path: str = "", - is_group: bool = False, - activate_method: str = "auto", # "auto"(默认Ctrl+D回退win32) | "hotkey" | "win32" - wait_search: float = 1.5, - wait_send: float = 1.0, - wait_file_preview: float = 1.5, -) -> None: ... -``` - -### 2. 更新 `requirements.txt` - -追加三行:`pyautogui`、`pywin32`、`pyperclip`。 - -### 3. 更新 `pyproject.toml` `[project].dependencies` - -同步追加同样三项。 - -## 不改动的部分 - -- 不动 `app/utils/__init__.py`(现有内容只是注释头,保持原样,符合项目不集中导出的习惯)。 -- 不动任何 OA 业务模块(钉钉工具独立,暂不接入审批流程回调)。 - -## 验证方式 - -1. **依赖安装**:`.venv\Scripts\python.exe -m pip install pyautogui pywin32 pyperclip` -2. **导入自检**:`.venv\Scripts\python.exe -c "from app.utils.dingtalk_sender import send_to_group, send_to_person"` -3. **剪贴板单测(不发消息)**:调用 `_set_file_to_clipboard(r"C:\test.txt")` 后在资源管理器 `Ctrl+V` 验证能粘贴出文件。 -4. **端到端实测**(需钉钉已登录): - ```python - from app.utils.dingtalk_sender import send_to_person - send_to_person("张三", text="测试消息") # 文本 - send_to_person("张三", file_path=r"C:\report\月报.xlsx") # 文件 - send_to_person("张三", text="请查收", file_path=r"C:\report\月报.xlsx") # 先文本后文件 - ``` - 观察钉钉窗口是否被激活、搜索是否命中目标、消息是否发出。 -5. **日志检查**:`app/logs/app_YYYYMMDD.log` 应有完整步骤记录。 diff --git a/202608_员工停保申请表_193736.xls b/202608_员工停保申请表_193736.xls deleted file mode 100644 index 6718604..0000000 Binary files a/202608_员工停保申请表_193736.xls and /dev/null differ diff --git a/202608_员工停保申请表_230155_参保核对.xlsx b/202608_员工停保申请表_230155_参保核对.xlsx new file mode 100644 index 0000000..2e5428a Binary files /dev/null and b/202608_员工停保申请表_230155_参保核对.xlsx differ diff --git a/202608_员工参保申请表_193728.xls b/202608_员工参保申请表_193728.xls deleted file mode 100644 index 38f116c..0000000 Binary files a/202608_员工参保申请表_193728.xls and /dev/null differ diff --git a/202608_员工参保申请表_230145_参保核对.xlsx b/202608_员工参保申请表_230145_参保核对.xlsx new file mode 100644 index 0000000..21ad728 Binary files /dev/null and b/202608_员工参保申请表_230145_参保核对.xlsx differ diff --git a/aa.md b/aa.md index 0965f6b..21ead47 100644 --- a/aa.md +++ b/aa.md @@ -1,150 +1,123 @@ - \ No newline at end of file +# 你的 Cookie 字符串(从浏览器复制完整) + +COOKIE_STR = "你的完整Cookie" + +# 基础参数模板(和之前一样) + +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": "", +} + +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() + +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 + +# ---------- 使用示例 ---------- + +# 假设你有一个大的工号列表 + +all_codes = [ + "37028192", "37030557", "37035022", "其他工号..." +] + +# 将大列表按15个一组拆分 + +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 = [] # 用于存所有有数据的完整行,方便后续导出 + +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)} 条") 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 new file mode 100644 index 0000000..6224d39 Binary files /dev/null and b/app/service/hrbp/ehr/common/captcha_debug/bg_clean_0.png 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 new file mode 100644 index 0000000..583ab5b Binary files /dev/null and b/app/service/hrbp/ehr/common/captcha_debug/bg_clean_0_marked.png differ diff --git a/app/service/hrbp/ehr/common/captcha_debug/bg_clean_r1_0.png b/app/service/hrbp/ehr/common/captcha_debug/bg_clean_r1_0.png new file mode 100644 index 0000000..d3b6ba8 Binary files /dev/null and b/app/service/hrbp/ehr/common/captcha_debug/bg_clean_r1_0.png differ diff --git a/app/service/hrbp/ehr/common/captcha_debug/bg_clean_r1_0_marked.png b/app/service/hrbp/ehr/common/captcha_debug/bg_clean_r1_0_marked.png new file mode 100644 index 0000000..929896a Binary files /dev/null and b/app/service/hrbp/ehr/common/captcha_debug/bg_clean_r1_0_marked.png differ diff --git a/app/service/hrbp/ehr/common/captcha_debug/bg_clean_r1_1.png b/app/service/hrbp/ehr/common/captcha_debug/bg_clean_r1_1.png new file mode 100644 index 0000000..570e759 Binary files /dev/null and b/app/service/hrbp/ehr/common/captcha_debug/bg_clean_r1_1.png differ diff --git a/app/service/hrbp/ehr/common/captcha_debug/bg_clean_r1_1_marked.png b/app/service/hrbp/ehr/common/captcha_debug/bg_clean_r1_1_marked.png new file mode 100644 index 0000000..3dead84 Binary files /dev/null and b/app/service/hrbp/ehr/common/captcha_debug/bg_clean_r1_1_marked.png differ diff --git a/app/service/hrbp/ehr/common/captcha_debug/bg_clean_r1_2.png b/app/service/hrbp/ehr/common/captcha_debug/bg_clean_r1_2.png new file mode 100644 index 0000000..9fc0e9f Binary files /dev/null and b/app/service/hrbp/ehr/common/captcha_debug/bg_clean_r1_2.png differ diff --git a/app/service/hrbp/ehr/common/captcha_debug/bg_clean_r1_2_marked.png b/app/service/hrbp/ehr/common/captcha_debug/bg_clean_r1_2_marked.png new file mode 100644 index 0000000..d8a462b Binary files /dev/null and b/app/service/hrbp/ehr/common/captcha_debug/bg_clean_r1_2_marked.png differ diff --git a/app/service/hrbp/ehr/common/captcha_debug/bg_clean_r1_3.png b/app/service/hrbp/ehr/common/captcha_debug/bg_clean_r1_3.png new file mode 100644 index 0000000..dec05e2 Binary files /dev/null and b/app/service/hrbp/ehr/common/captcha_debug/bg_clean_r1_3.png differ diff --git a/app/service/hrbp/ehr/common/captcha_debug/bg_clean_r1_3_marked.png b/app/service/hrbp/ehr/common/captcha_debug/bg_clean_r1_3_marked.png new file mode 100644 index 0000000..82fda36 Binary files /dev/null and b/app/service/hrbp/ehr/common/captcha_debug/bg_clean_r1_3_marked.png differ diff --git a/app/service/hrbp/ehr/common/captcha_debug/bg_clean_r1_4.png b/app/service/hrbp/ehr/common/captcha_debug/bg_clean_r1_4.png new file mode 100644 index 0000000..1c64a97 Binary files /dev/null and b/app/service/hrbp/ehr/common/captcha_debug/bg_clean_r1_4.png differ diff --git a/app/service/hrbp/ehr/common/captcha_debug/bg_clean_r1_4_marked.png b/app/service/hrbp/ehr/common/captcha_debug/bg_clean_r1_4_marked.png new file mode 100644 index 0000000..371b2bf Binary files /dev/null and b/app/service/hrbp/ehr/common/captcha_debug/bg_clean_r1_4_marked.png 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 new file mode 100644 index 0000000..bedbf01 Binary files /dev/null and b/app/service/hrbp/ehr/common/captcha_debug/slider_0.png differ diff --git a/app/service/hrbp/ehr/common/captcha_debug/slider_r1_0.png b/app/service/hrbp/ehr/common/captcha_debug/slider_r1_0.png new file mode 100644 index 0000000..7dd7375 Binary files /dev/null and b/app/service/hrbp/ehr/common/captcha_debug/slider_r1_0.png differ diff --git a/app/service/hrbp/ehr/common/captcha_debug/slider_r1_1.png b/app/service/hrbp/ehr/common/captcha_debug/slider_r1_1.png new file mode 100644 index 0000000..dd20047 Binary files /dev/null and b/app/service/hrbp/ehr/common/captcha_debug/slider_r1_1.png differ diff --git a/app/service/hrbp/ehr/common/captcha_debug/slider_r1_2.png b/app/service/hrbp/ehr/common/captcha_debug/slider_r1_2.png new file mode 100644 index 0000000..a68b515 Binary files /dev/null and b/app/service/hrbp/ehr/common/captcha_debug/slider_r1_2.png differ diff --git a/app/service/hrbp/ehr/common/captcha_debug/slider_r1_3.png b/app/service/hrbp/ehr/common/captcha_debug/slider_r1_3.png new file mode 100644 index 0000000..1435e5e Binary files /dev/null and b/app/service/hrbp/ehr/common/captcha_debug/slider_r1_3.png differ diff --git a/app/service/hrbp/ehr/common/captcha_debug/slider_r1_4.png b/app/service/hrbp/ehr/common/captcha_debug/slider_r1_4.png new file mode 100644 index 0000000..0b0c73a Binary files /dev/null and b/app/service/hrbp/ehr/common/captcha_debug/slider_r1_4.png differ diff --git a/app/service/hrbp/ehr/common/hr_api.py b/app/service/hrbp/ehr/common/hr_api.py new file mode 100644 index 0000000..9348bd9 --- /dev/null +++ b/app/service/hrbp/ehr/common/hr_api.py @@ -0,0 +1,8 @@ +""" +@Module: hrbp.ehr.common +@FileName: hr_api.py +@Author: 小布丁 +@CreateTime: 2026-08-05 23:52 +@Description: HR 系统 API 接口,集中管理流程引擎、排单、考勤等接口地址 +@Version: 1.2.0 +""" \ No newline at end of file diff --git a/app/service/hrbp/ehr/common/login.py b/app/service/hrbp/ehr/common/login.py new file mode 100644 index 0000000..de537fb --- /dev/null +++ b/app/service/hrbp/ehr/common/login.py @@ -0,0 +1,489 @@ +# -*- coding: utf-8 -*- +""" +@Module: hrbp.ehr.common +@FileName: login.py +@Author: 小布丁 +@CreateTime: 2026-08-05 23:52 +@Description: HR 登录 + 滑块验证(改进版:双候选 + 低置信度容忍) +@Version: 1.1.0 +""" +import os +import re +import json +import time +import random +from PIL import Image, ImageDraw +from DrissionPage import ChromiumPage, ChromiumOptions +import cv2 +import numpy as np +import io +from dotenv import load_dotenv +load_dotenv() + +# ================== 配置 ================== +LOGIN_URL = os.getenv('hr_login_url') +SUCCESS_KEYWORD = os.getenv('hr_target_url_keyword') +USERNAME = os.getenv('hr_login_username') +PASSWORD = os.getenv('hr_login_password') + +LOGIN_BTN = "@id=login-btn" +ACCOUNT_INPUT = "@id=j_username" +PASSWORD_INPUT = "@id=j_password_2" +CAPTCHA_CONTAINER = ".:comImageValidate" +SLIDER_BTN = ".:v_rightBtn" +BG_IMG = ".imgBg" +SLIDER_IMG = "css:div.imgBg_3 > img" +# 注意:不再使用 REFRESH_BTN + +RETRY_MAX = 5 +TIMEOUT = 10 +HEADLESS = False +DEBUG_DIR = os.path.join(os.path.dirname(__file__), 'captcha_debug') + +# 登录 cookies 持久化目录(与 OA 系统一致,服务层统一管理各平台会话文件) +_COOKIE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', '..', '.sessions') +COOKIE_FILE = os.path.join(_COOKIE_DIR, 'hr_cookies.json') + +def ensure_dir(path): + os.makedirs(path, exist_ok=True) + +# ================== Cookies 持久化(登录成功后缓存,下次免登录复用) ================== +def save_browser_cookies(page): + """把浏览器全域名 cookies 保存到本地文件,下次运行可免登录复用。""" + cookies = page.cookies(all_domains=True) + if not cookies: + print("未获取到 Cookies,跳过保存") + return + ensure_dir(_COOKIE_DIR) + with open(COOKIE_FILE, 'w', encoding='utf-8') as f: + json.dump(cookies, f, ensure_ascii=False, indent=2) + print(f"已保存 {len(cookies)} 个 Cookies 到 {COOKIE_FILE}") + +def load_cookies(): + """从本地文件加载 cookies 列表;文件不存在或为空时返回 None。""" + if not os.path.exists(COOKIE_FILE): + return None + with open(COOKIE_FILE, encoding='utf-8') as f: + cookies = json.load(f) + return cookies or None + +# ================== 改进的匹配函数(双候选 + 低置信度容忍) ================== +def match_slider_dual(bg_bytes, slider_bytes, debug_prefix=""): + """ + 双候选匹配,返回最佳候选和次佳候选(即使置信度低) + 返回: (best_distance, best_conf, best_loc, candidates_list, x_offset, y_offset, slider_w, slider_h) + 其中 candidates_list 为 [(x, y, conf), ...] 用于绘制标记 + """ + 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: + print(f" [{debug_prefix}匹配错误] 无法解码图片") + return None, 0, None, [], 0, 0, 0, 0 + + bg_h, bg_w = bg_img.shape[:2] + s_h, s_w = slider_color.shape[:2] + print(f" [{debug_prefix}图片尺寸] 背景: {bg_w}x{bg_h}, 滑块原始: {s_w}x{s_h}") + + # ---- 提取滑块有效区域 ---- + x_offset = 0 + y_offset = 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 and len(xs) > 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 = x_min + y_offset = y_min + print(f" [{debug_prefix}滑块裁剪] 有效区域: x=[{x_min},{x_max}], y=[{y_min},{y_max}], 裁剪后尺寸: {slider_rgb.shape[1]}x{slider_rgb.shape[0]}") + else: + print(f" [{debug_prefix}滑块裁剪] 未找到非透明区域,使用完整图") + slider_rgb = slider_color[:, :, :3] + else: + if len(slider_color.shape) == 3: + slider_rgb = slider_color + else: + slider_rgb = cv2.cvtColor(slider_color, cv2.COLOR_GRAY2BGR) + x_offset = 0 + y_offset = 0 + + s_h, s_w = slider_rgb.shape[:2] + + # ---- 预处理:灰度 + 高斯模糊 + Canny ---- + gray_bg = cv2.cvtColor(bg_img, cv2.COLOR_BGR2GRAY) + gray_slider = cv2.cvtColor(slider_rgb, cv2.COLOR_BGR2GRAY) + gray_bg = cv2.GaussianBlur(gray_bg, (3, 3), 0) + gray_slider = cv2.GaussianBlur(gray_slider, (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) + + # 收集多个候选(前 6 个),避免真实缺口被最右侧干扰或滑块区假候选挤掉 + candidates = [] + temp_result = result.copy() + for i 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: + print(f" [{debug_prefix}] 无有效候选") + return None, 0, None, [], x_offset, y_offset, s_w, s_h + + # 最右侧判定为干扰项:真实缺口不会紧贴背景图最右端 + right_margin = max(15, int(bg_w * 0.06)) + right_limit = bg_w - s_w - right_margin + + # 真实缺口常为半透明白色矩形,白度是强判别信号(区域近白像素占比) + 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()) + + # 在有效区间 [s_w, right_limit] 内按「置信度 + 白度」综合评分选择 + scored = [] + for val, loc in candidates: + x, y = loc + if x <= s_w or x > right_limit: # 排除左端滑块区与最右侧干扰 + continue + wn = region_whiteness(x, y, s_w, s_h) + score = val + 0.5 * wn + scored.append((score, val, loc)) + print(f" [{debug_prefix}] 有效候选 loc={loc} conf={val:.4f} 白度={wn:.2f} 综合={score:.4f}") + + if not scored: + best_val, best_loc = candidates[0] # 全部落在无效区,回退全局最高 + print(f" [{debug_prefix}] 无有效区候选,回退最高置信度: loc={best_loc}, val={best_val:.4f}") + else: + scored.sort(key=lambda t: t[0], reverse=True) + best_val, best_loc = scored[0][1], scored[0][2] + print(f" [{debug_prefix}] 选择综合最优候选: loc={best_loc}, conf={best_val:.4f}") + distance_phys = best_loc[0] - x_offset + if distance_phys < 0: + distance_phys = 0 + if distance_phys + s_w > bg_w: + distance_phys = bg_w - s_w + + # ---- 若置信度极低,尝试 ORB 辅助 ---- + if best_val < 0.25 and len(candidates) > 0: + orb = cv2.ORB_create(nfeatures=500) + kp1, des1 = orb.detectAndCompute(slider_edges, None) + kp2, des2 = orb.detectAndCompute(bg_edges, None) + if des1 is not None and des2 is not None and len(kp1) > 5 and len(kp2) > 5: + bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True) + matches = bf.match(des1, des2) + matches = sorted(matches, key=lambda x: x.distance) + if len(matches) > 10: + good = [m for m in matches[:30] if m.distance < np.mean([m.distance for m in matches[:15]]) * 0.7] + if len(good) > 5: + src_pts = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1,1,2) + dst_pts = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1,1,2) + offsets = dst_pts - src_pts + median_offset = np.median(offsets, axis=0)[0] + orb_x = int(median_offset[0]) - x_offset + if 0 < orb_x < bg_w - s_w: + print(f" [{debug_prefix}] ORB辅助偏移: {orb_x}px (原模板置信度{best_val:.3f})") + distance_phys = orb_x + best_val = 0.5 # 提升置信度用于显示 + + # ---- 构建候选列表(用于绘图) ---- + candidate_points = [] + for val, loc in candidates: + candidate_points.append((loc[0], loc[1], val)) + + print(f" [{debug_prefix}最终物理距离] distance={distance_phys}px (置信度 {best_val:.4f})") + return distance_phys, best_val, best_loc, candidate_points, x_offset, y_offset, s_w, s_h + +def draw_match_debug_multi(bg_bytes, slider_bytes, candidate_points, best_loc, x_offset, y_offset, slider_w, slider_h, distance_phys, distance_css, save_path): + """在背景图上绘制所有候选矩形和最佳匹配""" + try: + bg_img = Image.open(io.BytesIO(bg_bytes)).convert("RGBA") + draw = ImageDraw.Draw(bg_img) + + # 绘制所有候选(灰色虚线框) + for i, (cx, cy, conf) in enumerate(candidate_points): + if (cx, cy) == (best_loc[0], best_loc[1]): + continue # 最佳单独绘制 + rect = [cx, cy, cx + slider_w, cy + slider_h] + draw.rectangle(rect, outline="gray", width=1) + draw.text((cx + 5, cy - 10), f"conf={conf:.2f}", fill="gray") + + # 绘制最佳匹配(红色实线) + if best_loc: + rect = [best_loc[0], best_loc[1], best_loc[0] + slider_w, best_loc[1] + slider_h] + draw.rectangle(rect, outline="red", width=3) + text = f"best phys={distance_phys} css={distance_css}" + draw.text((best_loc[0] + 5, best_loc[1] - 20), text, fill="red") + + bg_img.save(save_path) + print(f" [匹配标记] 已保存: {save_path}") + except Exception as e: + print(f" [匹配标记] 绘制失败: {e}") + +# ================== 轨迹生成与滑动(与原相同) ================== +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)) + dt = random.uniform(0.030, 0.080) + if random.random() < 0.35: + y = random.choice([-1, 0, 1]) + steps.append((dx, y, dt)) + 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) + if random.random() < 0.08: + time.sleep(random.uniform(0.010, 0.035)) + time.sleep(random.uniform(0.10, 0.26)) + page.actions.release() + return True + except Exception as e: + print(f"拖拽异常:{e}") + return False + +# ================== 验证码处理(移除刷新按钮,容忍低置信度) ================== +def handle_captcha(page): + ensure_dir(DEBUG_DIR) + dpr = page.run_js('return window.devicePixelRatio') + print(f"设备像素比(DPR): {dpr}") + + for retry in range(RETRY_MAX): + print(f"\n--- 第 {retry+1} 次尝试验证 ---") + try: + container = page.ele(CAPTCHA_CONTAINER, timeout=TIMEOUT) + if not container: + print("验证码容器未出现") + continue + + bg_ele = container.ele(BG_IMG) + if not bg_ele: + bg_ele = container.ele('div[style*="background-image"]') + if not bg_ele: + print("找不到背景图元素") + continue + + slider_ele = container.ele(SLIDER_IMG) + if not slider_ele: + print("找不到滑块小图元素") + continue + if slider_ele.tag != 'img': + img_inner = slider_ele.ele('tag:img') + if img_inner: + slider_ele = img_inner + + # 隐藏滑块 -> 截取背景 -> 恢复 -> 截取滑块 + bg_screenshot = None + slider_screenshot = None + 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 as e: + print(f"隐藏/截图过程出错:{e}") + try: + page.run_js('arguments[0].style.display = ""', slider_ele) + except: + pass + continue + + if not bg_screenshot or not slider_screenshot: + print("截图数据为空") + continue + + # 保存原始截图 + bg_path = os.path.join(DEBUG_DIR, f"bg_clean_{retry}.png") + slider_path = os.path.join(DEBUG_DIR, f"slider_{retry}.png") + with open(bg_path, 'wb') as f: + f.write(bg_screenshot) + with open(slider_path, 'wb') as f: + f.write(slider_screenshot) + print(f" [调试截图] 背景: {bg_path}") + print(f" [调试截图] 滑块: {slider_path}") + + # 调用改进的匹配函数 + ret = match_slider_dual(bg_screenshot, slider_screenshot, debug_prefix=f"retry{retry}") + if ret[0] is None: + print("匹配失败,无候选,尝试随机拖动触发刷新") + # 随机拖动一段距离(比如100-300px)尝试触发刷新 + random_css = random.uniform(100, 300) / dpr + btn = page.ele(SLIDER_BTN) + if btn: + perform_slide(page, btn, random_css) + time.sleep(2) + continue + + distance_phys, conf, best_loc, candidate_points, x_offset, y_offset, slider_w, slider_h = ret + + # 转换为 CSS 距离 + distance_css = distance_phys / dpr + print(f" [置信度] {conf:.4f},物理距离: {distance_phys}px,CSS距离: {distance_css:.1f}px") + + # 生成标记图(绘制所有候选) + marked_path = os.path.join(DEBUG_DIR, f"bg_clean_{retry}_marked.png") + draw_match_debug_multi(bg_screenshot, slider_screenshot, candidate_points, best_loc, + x_offset, y_offset, slider_w, slider_h, + distance_phys, distance_css, marked_path) + + if distance_css <= 0: + print(" CSS距离无效,尝试随机拖动") + random_css = random.uniform(100, 300) / dpr + btn = page.ele(SLIDER_BTN) + if btn: + perform_slide(page, btn, random_css) + time.sleep(2) + continue + + btn = page.ele(SLIDER_BTN) + if not btn: + print("找不到滑块按钮") + continue + + # 执行滑动 + perform_slide(page, btn, distance_css) + time.sleep(2) # 等待验证结果 + + # 检查是否登录成功 + if SUCCESS_KEYWORD in page.url: + return True + # 若验证码容器消失,则认为验证通过 + if not page.ele(CAPTCHA_CONTAINER, timeout=1): + return True + else: + print("验证未通过,等待自动刷新...") + # 不点击刷新按钮,等待网站自行更新验证码 + time.sleep(2) + + except Exception as e: + print(f"异常:{e}") + time.sleep(1) + return False + +# ================== 登录主流程(不变) ================== +def login(): + co = ChromiumOptions() + if HEADLESS: + co.headless() + page = ChromiumPage(co) + + # 尝试复用已保存的 cookies,免重复登录 + saved = load_cookies() + if saved: + try: + page.set.cookies(saved) + page.get(LOGIN_URL) + time.sleep(2) + if SUCCESS_KEYWORD in page.url: + print("已通过缓存的 Cookies 登录") + return True + print("缓存的 Cookies 已失效,重新登录") + except Exception as e: + print(f"复用 Cookies 失败:{e}") + else: + page.get(LOGIN_URL) + time.sleep(2) + + if SUCCESS_KEYWORD in page.url: + print("已登录") + return True + + account = page.ele(ACCOUNT_INPUT) + if not account: + print("找不到账号输入框") + return False + account.clear() + account.input(USERNAME) + time.sleep(0.5) + + pwd = page.ele(PASSWORD_INPUT) + if not pwd: + print("找不到密码输入框") + return False + pwd.clear() + pwd.input(PASSWORD) + time.sleep(0.5) + + login_btn = page.ele(LOGIN_BTN) + if not login_btn: + print("找不到登录按钮") + return False + login_btn.click() + time.sleep(3) + + if SUCCESS_KEYWORD in page.url: + print("登录成功(无滑块)") + save_browser_cookies(page) + return True + + if handle_captcha(page): + print("登录成功(验证通过)") + save_browser_cookies(page) + return True + else: + print("登录失败") + return False + +if __name__ == "__main__": + success = login() + print("最终结果:", "成功" if success else "失败") \ No newline at end of file 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 271b51a..1b444f9 100644 --- a/app/service/hrbp/oa/social_change/employee_change_list.py +++ b/app/service/hrbp/oa/social_change/employee_change_list.py @@ -48,6 +48,27 @@ except ImportError: SessionPage = None ChromiumOptions = None +try: + import xlrd +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 + from openpyxl.utils import get_column_letter +except ImportError: + _XlsxWorkbook = None + PatternFill = None + Font = None + Alignment = None + get_column_letter = None + logger = get_logger(__name__) # ---------- 常量 ---------- @@ -87,6 +108,35 @@ MENU_NAME_SUSPEND = "员工停保申请" FILTER_IDX_PARTICIPATE = "2" 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 保存) +HR_COOKIE_FILE = os.path.abspath( + os.path.join(os.path.dirname(__file__), '..', '..', '..', '.sessions', 'hr_cookies.json') +) +SI_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": "", +} +SI_RESULT_COL = "社保记录查询结果" +SI_BATCH_SIZE = 15 + def _resolve_query_date(query_date: Optional[str] = None) -> str: """返回查询起始日期:手动传入则用传入值,否则用当前月份第一天。""" @@ -167,16 +217,19 @@ def _get_cookies_with_domain(session: SessionPage) -> list: return cookies -def get_fd_id_by_listening(session: SessionPage) -> str: - cookies = _get_cookies_with_domain(session) - if not cookies: - raise RuntimeError("Session 中没有 cookie,请先执行完整登录") +def get_fd_id_by_listening(session: SessionPage, browser: Optional[ChromiumPage] = None) -> str: + # 优先复用外部传入的浏览器;仅在没有可用浏览器时才自行创建(如复用已保存会话的场景) + own_browser = browser is None + if own_browser: + cookies = _get_cookies_with_domain(session) + if not cookies: + raise RuntimeError("Session 中没有 cookie,请先执行完整登录") - co = ChromiumOptions() - # 如需 Edge 浏览器,请取消注释并设置路径 - # co.set_browser_path(r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe") - browser = ChromiumPage(co) - browser.set.cookies(cookies) + co = ChromiumOptions() + # 如需 Edge 浏览器,请取消注释并设置路径 + # co.set_browser_path(r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe") + browser = ChromiumPage(co) + browser.set.cookies(cookies) try: browser.listen.start() @@ -204,7 +257,8 @@ def get_fd_id_by_listening(session: SessionPage) -> str: return fd_id finally: browser.listen.stop() - browser.quit() + if own_browser: + browser.quit() # ---------------------------------------------- @@ -311,6 +365,248 @@ def export_all_data(session: SessionPage, base_params: Dict, total: int, columns return session.response.content +# ---------------------------------------------- +# 5.5 按工号去重清洗(去掉『废弃』,每工号保留最新申请日期) +# ---------------------------------------------- +def _normalize_date_key(value) -> float: + """将『申请日期』单元格归一化为可比较的数值键(Excel 序列号或日期天数)。""" + if value is None: + return 0.0 + if isinstance(value, (int, float)): + return float(value) + if isinstance(value, str): + m = re.match(r"(\d{4})[-/年](\d{1,2})[-/月](\d{1,2})", value.strip()) + if m: + y, mo, d = int(m.group(1)), int(m.group(2)), int(m.group(3)) + try: + return (datetime(y, mo, d) - datetime(1899, 12, 30)).days + except ValueError: + return 0.0 + return 0.0 + return 0.0 + + +def _date_display(value, wb): + """把 Excel 日期序列号转成可读字符串:整天只显示日期,带时间则显示到秒。""" + if isinstance(value, (int, float)): + try: + dt = xlrd.xldate_as_datetime(float(value), wb.datemode) + except Exception: + return value + if float(value).is_integer(): + return dt.strftime("%Y-%m-%d") + return dt.strftime("%Y-%m-%d %H:%M:%S") + return value + + +def _read_and_clean(xls_path: str): + """读取 .xls:去掉『废弃』,按工号去重(每工号保留最新申请日期)。 + + 返回 (headers, rows, emp_col),rows 中工号已统一为字符串、申请日期已格式化为文本。 + """ + if xlrd is None: + raise RuntimeError("缺少 xlrd 依赖,无法读取 .xls") + + wb = xlrd.open_workbook(xls_path) + sh = wb.sheet_by_index(0) + headers = [str(sh.cell_value(0, c)).strip() for c in range(sh.ncols)] + + def find_col(keyword): + for i, h in enumerate(headers): + if keyword in h: + return i + return None + + emp_col = find_col("工号") + date_col = find_col("申请日期") + status_col = find_col("文档状态") + if emp_col is None: + raise ValueError(f"未找到『工号』列,表头: {headers}") + + # 1) 过滤:去掉『废弃』,且工号非空;所有日期列统一转成可读文本 + rows = [] + for r in range(1, sh.nrows): + row = [] + for c in range(sh.ncols): + v = sh.cell_value(r, c) + if sh.cell_type(r, c) == xlrd.XL_CELL_DATE: + v = _date_display(v, wb) + row.append(v) + emp = str(row[emp_col]).strip() + if not emp: + continue + if status_col is not None and str(row[status_col]).strip() == "废弃": + continue + row[emp_col] = emp + rows.append(row) + + # 2) 去重:按工号保留申请日期最新的一条,保持首次出现顺序 + latest = {} + for row in rows: + emp = row[emp_col] + key = _normalize_date_key(row[date_col]) if date_col is not None else 0.0 + if emp not in latest or key > latest[emp][0]: + latest[emp] = (key, row) + + ordered = [] + seen = set() + for row in rows: + emp = row[emp_col] + if emp not in seen: + seen.add(emp) + ordered.append(latest[emp][1]) + + logger.info("清洗完成:去掉废弃后 %d 条,去重后 %d 条", len(rows), len(ordered)) + return headers, ordered, emp_col + + +def clean_employee_change_file(xls_path: str, output_dir: str = ".") -> str: + """按工号去重清洗导出的名单,写出清洗后的 .xlsx(兼容旧入口)。""" + if _XlsxWorkbook is None: + raise RuntimeError("缺少 openpyxl 依赖,无法执行去重清洗,请先安装") + headers, rows, _ = _read_and_clean(xls_path) + out_name = f"{os.path.splitext(os.path.basename(xls_path))[0]}_去重.xlsx" + out_path = os.path.abspath(os.path.join(output_dir, out_name)) + out_wb = _XlsxWorkbook() + ws = out_wb.active + ws.append(headers) + for row in rows: + ws.append(row) + out_wb.save(out_path) + logger.info("清洗结果保存为:%s", out_path) + return out_path + + +# ---------------------------------------------- +# 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 + + +@retry(max_attempts=3) +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() + return resp.json() + + +def _si_found_codes(response_json): + """从返回 JSON 中提取所有 base_Code 工号。""" + datas = response_json.get("datas") or [] + return {str(item.get("base_Code")).strip() for item in datas if item.get("base_Code")} + + +def _si_check_batch(session, codes_batch) -> set: + """返回这一批中『能查到参保记录』的工号集合;请求失败返回空集合并告警。""" + try: + return _si_found_codes(_si_query_batch(session, codes_batch)) + except Exception as e: + logger.warning("参保记录批量查询失败 %s:%s", codes_batch, e) + return set() + + +def _write_annotated(headers, rows, emp_col, mode, base_name, output_dir=".") -> str: + """逐批查 HR 参保记录,追加『社保记录查询结果』列,写出最终 .xlsx。""" + if _XlsxWorkbook is None: + raise RuntimeError("缺少 openpyxl 依赖,无法导出 .xlsx") + + # 按工号去重(保持首次出现顺序),再逐批查询 + unique_codes, seen = [], set() + for row in rows: + code = str(row[emp_col]).strip() + if code and code not in seen: + seen.add(code) + unique_codes.append(code) + + session = _build_hr_session() + found = set() + for i in range(0, len(unique_codes), SI_BATCH_SIZE): + found |= _si_check_batch(session, unique_codes[i:i + SI_BATCH_SIZE]) + logger.info("参保记录核对 %d/%d 个工号", min(i + SI_BATCH_SIZE, len(unique_codes)), len(unique_codes)) + time.sleep(0.3) + + is_participate = (mode == "participation") + new_rows = [] + for row in rows: + code = str(row[emp_col]).strip() + has_record = code in found + if is_participate: + val = "异常:已参保(系统有该工号记录)" if has_record else "正常:系统无该工号记录" + else: + val = "异常:已停保(系统无该工号记录)" if not has_record else "正常:系统有该工号记录" + new_rows.append(row + [val]) + + out_path = os.path.abspath(os.path.join( + output_dir, f"{base_name}_参保核对.xlsx")) + out_wb = _XlsxWorkbook() + + # 异常行标红 + 结果列加粗红字(便于数据多时一眼定位) + red_fill = PatternFill(start_color="FFC7CE", end_color="FFC7CE", fill_type="solid") if PatternFill else None + red_font = Font(color="9C0006", bold=True) if Font else None + head_fill = PatternFill(start_color="DDEBF7", end_color="DDEBF7", fill_type="solid") if PatternFill else None + + out_ws = out_wb.active + out_ws.title = "核对明细" + out_ws.append(headers + [SI_RESULT_COL]) + for c in range(1, len(headers) + 2): + cell = out_ws.cell(1, c) + cell.fill = head_fill + cell.font = Font(bold=True) if Font else None + cell.alignment = Alignment(horizontal="center") if Alignment else None + for idx, row in enumerate(new_rows, start=2): + out_ws.append(row) + if str(row[-1]).startswith("异常"): + for c in range(1, len(row) + 1): + cell = out_ws.cell(idx, c) + cell.fill = red_fill + if c == len(row): + cell.font = red_font + out_ws.freeze_panes = "A2" + out_ws.auto_filter.ref = out_ws.dimensions + if get_column_letter: + for c in range(1, len(headers) + 2): + out_ws.column_dimensions[get_column_letter(c)].width = 20 + + out_wb.save(out_path) + + abnormal = [r for r in new_rows if r[-1].startswith("异常")] + logger.info("参保核对完成:共 %d 个工号,查询到参保记录 %d 个,异常 %d 条,导出 %s", + len(unique_codes), len(found), len(abnormal), out_path) + return out_path + + +def annotate_si_result(xls_path: str, mode: str, output_dir: str = ".") -> str: + """读取原始 .xls → 清洗去重 → 查 HR 参保记录 → 追加结果列,导出一份最终文件(无中间表)。 + + mode: "participation"(参保,有记录=异常)/ "suspension"(停保,无记录=异常) + """ + headers, rows, emp_col = _read_and_clean(xls_path) + return _write_annotated(headers, rows, emp_col, mode, + os.path.splitext(os.path.basename(xls_path))[0], output_dir) + + # ---------------------------------------------- # 6. 主流程(精简版) # ---------------------------------------------- @@ -333,8 +629,8 @@ def export_employee_change_list( browser, session = get_session() try: - # 1. 动态获取 fdId - fd_id = get_fd_id_by_listening(session) + # 1. 动态获取 fdId(复用登录浏览器,避免重复创建导致浏览器被提前关闭) + fd_id = get_fd_id_by_listening(session, browser) # 2. 从菜单获取 searchId search_id = get_search_id_from_menu(session, fd_id, menu_name) @@ -360,9 +656,25 @@ def export_employee_change_list( f.write(file_content) logger.info("导出完成,文件保存为:%s", output_path) + # 6. 读取原始表并内存清洗(去『废弃』+按工号去重),不落中间表 + headers, rows, emp_col = _read_and_clean(output_path) + + # 7. 调用 HR 参保记录接口核对,追加『社保记录查询结果』列(一次性完成) + mode = "suspension" if menu_name == MENU_NAME_SUSPEND else "participation" + final_path = _write_annotated( + headers, rows, emp_col, mode, + os.path.splitext(os.path.basename(output_path))[0], output_dir) + + # 8. 清理中间原始导出文件,只保留最终标注表 + try: + os.remove(output_path) + logger.info("已清理中间原始导出文件:%s", output_path) + except Exception: + pass + if browser is not None: save_browser_cookies(browser) - return output_path + return final_path except Exception as e: logger.error("导出过程出错: %s", e, exc_info=True) diff --git a/app/service/hrbp/oa/social_change/si_insurance_check.py b/app/service/hrbp/oa/social_change/si_insurance_check.py new file mode 100644 index 0000000..86b97de --- /dev/null +++ b/app/service/hrbp/oa/social_change/si_insurance_check.py @@ -0,0 +1,276 @@ +# -*- coding: utf-8 -*- +""" +@Module: hrbp.oa.social_change.si_insurance_check +@FileName: si_insurance_check.py +@Author: 小布丁 +@CreateTime: 2026-08-07 15:20 +@Description: 社保参保状态核对:读取清洗后的社保增减名单(参保/停保),按工号逐批调用 HR 参保记录接口, + 判断每个工号是否有参保记录,追加一列标注结果并导出 .xlsx。 +@Version: 2.0.0 + +业务判定(对应 aa.md): + - 参保申请表:某工号在 HR 参保记录中「有返回数据」→ 已参保,属异常; + - 停保申请表:某工号在 HR 参保记录中「无返回数据」→ 已停保,属异常。 +""" + +import os +import sys +import time +from pathlib import Path +from typing import List, Tuple + +# ---- 单文件运行支持 ---- +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 +from app.utils.intelligent_retry import retry + +try: + import requests +except ImportError: + requests = None + +try: + import xlrd +except ImportError: + xlrd = None + +try: + from openpyxl import load_workbook as _load_workbook + from openpyxl import Workbook as _XlsxWorkbook +except ImportError: + _load_workbook = None + _XlsxWorkbook = None + +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 保存) +HR_COOKIE_FILE = os.path.abspath( + os.path.join(os.path.dirname(__file__), '..', '..', '..', '.sessions', 'hr_cookies.json') +) + +# 接口基础参数(aa.md 基础参数模板,base_codes 动态替换) +SI_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": "", +} + +RESULT_COL = "社保记录查询结果" +BATCH_SIZE = 15 + + +# ---------------------------------------------- +# 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. 查询参保记录接口 +# ---------------------------------------------- +@retry(max_attempts=3) +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() + return resp.json() + + +def extract_found_codes(response_json) -> set: + """从返回 JSON 中提取所有 base_Code 工号。""" + datas = response_json.get("datas") or [] + return {str(item.get("base_Code")).strip() for item in datas if item.get("base_Code")} + + +def check_codes(session, codes_batch: List[str]) -> set: + """返回这一批中『能查到参保记录』的工号集合;请求失败时返回空集合并告警。""" + try: + return extract_found_codes(query_batch(session, codes_batch)) + except Exception as e: + logger.warning("批量查询失败 %s:%s", codes_batch, e) + return set() + + +# ---------------------------------------------- +# 3. 读取表格(支持 .xlsx / .xls) +# ---------------------------------------------- +def read_table(path: str) -> Tuple[List[str], List[list]]: + """读取表格,返回 (表头, 数据行)。""" + ext = os.path.splitext(path)[1].lower() + if ext == ".xlsx": + if _load_workbook is None: + raise RuntimeError("缺少 openpyxl 依赖,无法读取 .xlsx") + ws = _load_workbook(path).active + rows = list(ws.iter_rows(values_only=True)) + headers = [str(h) if h is not None else "" for h in rows[0]] + data = [list(r) for r in rows[1:]] + elif ext == ".xls": + if xlrd is None: + raise RuntimeError("缺少 xlrd 依赖,无法读取 .xls") + sh = xlrd.open_workbook(path).sheet_by_index(0) + headers = [str(sh.cell_value(0, c)).strip() for c in range(sh.ncols)] + data = [[sh.cell_value(r, c) for c in range(sh.ncols)] for r in range(1, sh.nrows)] + else: + raise ValueError(f"不支持的文件格式:{ext},请提供 .xlsx 或 .xls") + return headers, data + + +# ---------------------------------------------- +# 4. 核对并追加结果列 +# ---------------------------------------------- +def check_and_annotate(table_path: str, mode: str, output_dir: str = ".") -> str: + """读表 → 按工号去重 → 逐批查接口 → 追加结果列 → 导出 .xlsx。 + + mode: "participation"(参保,有记录=异常)/ "suspension"(停保,无记录=异常) + """ + if _XlsxWorkbook is None: + raise RuntimeError("缺少 openpyxl 依赖,无法导出 .xlsx") + + headers, data = read_table(table_path) + emp_col = next((i for i, h in enumerate(headers) if "工号" in h), None) + if emp_col is None: + raise ValueError(f"未找到『工号』列,表头: {headers}") + + # 按工号去重(保持首次出现顺序),再逐批查询 + unique_codes = [] + seen = set() + for row in data: + code = str(row[emp_col]).strip() + if code and code not in seen: + seen.add(code) + unique_codes.append(code) + + session = build_hr_session() + found = set() + for i in range(0, len(unique_codes), BATCH_SIZE): + found |= check_codes(session, unique_codes[i:i + BATCH_SIZE]) + logger.info("已查询 %d/%d 个工号", min(i + BATCH_SIZE, len(unique_codes)), len(unique_codes)) + time.sleep(0.3) # 轻微限速,避免触发风控 + + is_participate = (mode == "participation") + new_rows = [] + for row in data: + code = str(row[emp_col]).strip() + has_record = code in found + if is_participate: + val = "异常:已参保(系统有该工号记录)" if has_record else "正常:系统无该工号记录" + else: + val = "异常:已停保(系统无该工号记录)" if not has_record else "正常:系统有该工号记录" + new_rows.append(row + [val]) + + out_path = os.path.abspath(os.path.join( + output_dir, + f"{os.path.splitext(os.path.basename(table_path))[0]}_参保核对.xlsx", + )) + out_wb = _XlsxWorkbook() + ws = out_wb.active + ws.append(headers + [RESULT_COL]) + for row in new_rows: + ws.append(row) + out_wb.save(out_path) + + abnormal = [r for r in new_rows if r[-1].startswith("异常")] + logger.info("完成:共 %d 个工号,查询到参保记录 %d 个,异常 %d 条,导出 %s", + len(unique_codes), len(found), len(abnormal), out_path) + return out_path + + +# ---------------------------------------------- +# 5. 对外便捷入口 +# ---------------------------------------------- +def check_participation(table_path: str, output_dir: str = ".") -> str: + return check_and_annotate(table_path, "participation", output_dir) + + +def check_suspension(table_path: str, output_dir: str = ".") -> str: + return check_and_annotate(table_path, "suspension", output_dir) + + +def _latest_cleaned(project: str, keyword: str) -> str: + """在项目目录里找最新(按修改时间)的、文件名含关键字且以 _去重.xlsx 结尾的表。""" + matches = [ + p for p in Path(project).glob("*.xlsx") + if keyword in p.name and p.name.endswith("_去重.xlsx") + ] + if not matches: + return "" + return str(max(matches, key=lambda p: p.stat().st_mtime)) + + +def main() -> None: + setup_logging() + args = sys.argv[1:] + project = _root + + def pick(keyword): + # 优先命令行显式指定,否则自动找最新清洗表 + for a in args: + if keyword in Path(a).name: + return a + return _latest_cleaned(project, keyword) + + participate = pick("参保") + suspend = pick("停保") + + if participate and os.path.exists(participate): + check_participation(participate, project) + else: + logger.warning("未找到参保清洗表(*参保*_去重.xlsx)") + + if suspend and os.path.exists(suspend): + check_suspension(suspend, project) + else: + logger.warning("未找到停保清洗表(*停保*_去重.xlsx)") + + +if __name__ == "__main__": + main() diff --git a/pyproject.toml b/pyproject.toml index b5481a9..03c8023 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -14,6 +14,8 @@ dependencies = [ "pyautogui", "pywin32", "pyperclip", + "xlrd", + "openpyxl", ] [tool.setuptools.packages.find] diff --git a/requirements.txt b/requirements.txt index 8008555..44dac69 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,4 +4,9 @@ chinese_calendar pyautogui pywin32 pyperclip -uiautomation \ No newline at end of file +uiautomation +xlrd +openpyxl +Pillow +opencv-python +numpy diff --git a/test.html b/test.html deleted file mode 100644 index 3c42abd..0000000 --- a/test.html +++ /dev/null @@ -1,1057 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - 参保申请单台账 - - - - - - - - - -
-
-
- - - - - - -
-
-
-
- - - - -
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- 所在单位 -
序号 - 所在单位 -
- 申请人
-
- 申请日期 - 工号 - 参保人 - 任职岗位 - 身份证号码 - 电话号码 - 户口性质 -
- 文档状态
-
当前环节当前处理人
1新光天地行政会馆_技师组 - 黄甜2026-08-0637035868孙乐梅保健师61232319931224832915191640557外地农村结束 - 结束节点 - - - -
2车站南路CEO会馆_技师组 - 刘树勇2026-08-0637034578王来保健师43012119871209524115073151371外地农村结束 - 结束节点 - - - -
3金鹰LIFE主题会馆_技师组 - 蒋德静2026-08-0537035680杨圣平保健师53233120041224382X15812119041本地农村结束 - 结束节点 - - - -
4鸳鸯行政会馆_技师组 - 马茂杨2026-08-0537010344陈万丽归真技师52212219920622742918166998334外地城镇结束 - 结束节点 - - - -
5鸳鸯行政会馆_技师组 - 马茂杨2026-08-0537010344陈万丽归真技师52212219920622742918166998334外地城镇废弃 - 结束节点 - - - -
6洋河北路CEO会馆_技师组 - 陈志祥2026-08-0537020789蔡运婷归真技师50010619850902942X13752871644本地城镇结束 - 结束节点 - - - -
7国贸LIFE主题会馆_技师组 - 隆城2026-08-0437036109蒲荣保健师51130419890615722318102794578外地农村结束 - 结束节点 - - - -
8春晖路CEO会馆_接待组 - 徐利2026-08-0437006639徐利接待组负责人,营运主管 - 51052119920308742618148474240外地农村结束 - 结束节点 - - - -
9新光天地行政会馆_技师组 - 黄甜2026-08-0437034232马忠莉保健师51102519841016394013698309146本地城镇结束 - 结束节点 - - - -
10女宾部_女宾服务组梁敏2026-08-0437025027吴长春水区服务顾问(女) - 51290219790311446X18090507933外地城镇结束 - 结束节点 - - - -
11国贸LIFE主题会馆_技师组 - 隆城2026-08-0337035876符小妹保健师46002720020901852X15508954368本地农村结束 - 结束节点 - - - -
12国贸LIFE主题会馆_技师组 - 隆城2026-08-0337035873符式月保健师46002519980211182318889124407本地农村结束 - 结束节点 - - - -
13南门行政会馆_餐饮组 - 谢利超2026-08-0337032935陈润吧员61242919900724073815929963446本地农村结束 - 结束节点 - - - -
14河西麓谷行政会馆_技师组 - 沙丁2026-08-0337017808刘美兰归真技师43252419900827832418216457320本地农村结束 - 结束节点 - - - -
15观音桥步行街行政会馆_技师组 - 王林洪2026-08-0337033899张春琴保健师52240119850208822415730249899外地农村结束 - 结束节点 - - - -
-
- -
- - - - - - -
- - - - - \ No newline at end of file diff --git a/yingdao/social_change_yingdao.py b/yingdao/social_change_yingdao.py new file mode 100644 index 0000000..6ecaac2 --- /dev/null +++ b/yingdao/social_change_yingdao.py @@ -0,0 +1,1166 @@ +# -*- coding: utf-8 -*- +""" +@FileName: social_change_yingdao.py +@Author: 小布丁 +@CreateTime: 2026-08-07 +@Description: 社保增减名单核对(统一单文件版,app 与影刀共用)——OA 登录导出参保/停保名单 -> 清洗去重 -> HR 登录(滑块验证码)调用 si_main 参保记录接口核对 -> 追加结果列 -> 钉钉推送两张表 +@Version: 2.0.0 + +设计说明(避免维护 app/影刀两套版本): + - 单文件自包含,可放任意目录直接运行(含 App 项目目录或影刀环境)。 + - 内含 HR 登录(滑块验证码识别),保证 si_main 查询所需的 hr.37du.co 登录态。 + - 社保模块无 SSO(SSO 仅用于加班/请假等单据解析),本脚本不含 SSO 逻辑。 + +业务判定: + - 参保申请表:某工号在 HR 参保记录中「有返回数据」→ 已参保,属异常; + - 停保申请表:某工号在 HR 参保记录中「无返回数据」→ 已停保,属异常。 + +依赖安装: + pip install DrissionPage python-dotenv requests xlrd openpyxl opencv-python numpy Pillow pyautogui pywin32 pyperclip + +环境变量(.env 文件或系统变量): + OA 登录:oa_login_url / oa_target_url_keyword / oa_login_username / oa_login_password + HR 登录:hr_login_url / hr_target_url_keyword / hr_login_username / hr_login_password + 钉钉推送:dingtalk_notify_enabled=true|false(默认false) / dingtalk_notify_target=联系人姓名 + 可选:social_change_query_date=查询起始日期(如 2026-08-01,默认当月1号) + social_change_output_dir=结果输出目录(默认当前目录) +""" + +# ==================== 标准库导入 ==================== +import functools +import json +import os +import random +import re +import sys +import time +from datetime import datetime +from urllib.parse import urljoin, urlparse, parse_qs + +# ==================== 第三方库导入 ==================== +try: + from DrissionPage import ChromiumPage, SessionPage, ChromiumOptions +except ImportError: + ChromiumPage = None + SessionPage = 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 xlrd +except ImportError: + xlrd = None + +try: + from openpyxl import load_workbook as _load_workbook + from openpyxl import Workbook as _XlsxWorkbook + from openpyxl.styles import PatternFill, Font, Alignment + from openpyxl.utils import get_column_letter +except ImportError: + _load_workbook = None + _XlsxWorkbook = None + PatternFill = None + Font = None + Alignment = None + get_column_letter = None + +# 滑块验证码识别依赖(懒加载) +try: + import cv2 + import numpy as np +except ImportError: + cv2 = None + np = None + +# 钉钉推送依赖(懒加载) +try: + import pyautogui +except ImportError: + pyautogui = None +try: + import win32gui + import win32con +except ImportError: + win32gui = None + win32con = None +try: + import pyperclip +except ImportError: + pyperclip = None + + +# ==================== 路径 & 常量配置 ==================== +_APP_DATA_DIR = os.path.join( + os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'), + 'SocialChange' +) +_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions') +COOKIE_FILE_OA = os.path.join(_SESSIONS_DIR, 'oa_cookies.json') +COOKIE_FILE_HR = os.path.join(_SESSIONS_DIR, 'hr_cookies.json') + +# ---------- OA 系统 ---------- +BASE_URL = "https://oa.37du.co" +HR_BASE_URL = "https://hr.37du.co" +HOME_URL = f"{BASE_URL}/sys/portal/page.jsp?portalId=1754a0f1c8b63479fb544514619903d5" +LIST_URL = f"{BASE_URL}/km/review/km_review_main_list.jsp" +SEARCH_URL = f"{BASE_URL}/sys/search/search.do" +MENU_API_PATH = "/sys/portal/sys_portal_nav/sysPortalNav.do" + +DEFAULT_FIXED_PARAMS = { + "fdModelName": "com.landray.kmss.km.review.model.KmReviewMain", + "canClose": "false", "isNew": "true", + "j_aside": "false", "j_rIframe": "true", "j_iframe": "true", +} +DEFAULT_EXPORT_COLUMNS = ( + "fd_38e9dd25e050e0;docCreator;fd_38d49cbc0ceeae;" + "fd_390c6988e241ea;fd_390c639f265c78;fd_38e77e5cd6e9fe;" + "fd_38d49cd67211e2;fd_38d49cd73eff02;fd_38deea220dc8c4;docStatus" +) +DEFAULT_EXPORT_COLUMNS_SUSPEND = ( + "fd_38d32213b2e9cc;fd_38d322164f42f2;fd_38e6887c2b3690;" + "fd_3ec504d4c63e02;fd_38dad8035e33e4;fd_38e6887d6b0088;" + "fd_38d32227f7a496;fd_38dee9ae569d6a;fd_38e687e91f4fc6;" + "fd_38e687eb56dc4c;docStatus;docPublishTime" +) +MENU_NAME_PARTICIPATE = "员工参保申请" +MENU_NAME_SUSPEND = "员工停保申请" +FILTER_IDX_PARTICIPATE = "2" +FILTER_IDX_SUSPEND = "3" + +# ---------- HR 参保记录核对(si_main 接口) ---------- +SI_QUERY_URL = f"{HR_BASE_URL}/RedseaPlatform/getPageAjax/si_main_SelectByTreeCode/CoreRequest.mc" +SI_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": "", +} +SI_RESULT_COL = "社保记录查询结果" +SI_BATCH_SIZE = 15 + +# ---------- 钉钉 ---------- +DINGTALK_WINDOW_KEYWORD = "钉钉" + + +# ==================== 日志(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() + + +# ==================== 重试装饰器 ==================== +class RetryExhaustedError(Exception): + pass + + +def retry(max_attempts: int = 3): + if max_attempts < 1: + raise ValueError("max_attempts must be >= 1") + + 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 RetryExhaustedError( + f"{func.__name__} failed after {max_attempts} attempts, last error: {last_exc}" + ) from 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 + + +# ==================== OA 登录 + 会话 ==================== +def init_session_from_page(browser_page, copy_headers=True): + session = SessionPage() + cookies_dict = browser_page.cookies(all_domains=True) + if cookies_dict: + session.set.cookies(cookies_dict) + logger.info("已复制 %d 个 Cookies 到 SessionPage", len(cookies_dict)) + else: + logger.warning("未获取到 Cookies,请确认浏览器已登录") + if copy_headers: + headers = {"User-Agent": browser_page.run_js("return navigator.userAgent;")} + session.set.headers(headers) + session.set.timeout(10) + if hasattr(session, 'session'): + session.session.headers.update({ + "Referer": LIST_URL, + "X-Requested-With": "XMLHttpRequest", + "Accept": "application/json, text/javascript, */*; q=0.01", + }) + return session + + +def load_saved_session(path): + cookies = load_cookies(path) + if not cookies: + return None + session = SessionPage() + session.set.cookies(cookies) + session.set.timeout(10) + if hasattr(session, 'session'): + session.session.headers.update({ + "Referer": LIST_URL, + "X-Requested-With": "XMLHttpRequest", + "Accept": "application/json, text/javascript, */*; q=0.01", + }) + return session + + +def create_browser_with_saved_cookies(path): + browser = ChromiumPage() + cookies = load_cookies(path) + if cookies: + browser.set.cookies(cookies) + return browser + + +def is_oa_session_valid(session): + try: + session.get(HOME_URL) + resp = session.response + return resp is not None and resp.status_code == 200 + except Exception as e: + logger.info("OA 会话已失效: %s", e) + return False + + +@retry(max_attempts=3) +def oa_login(username=None, password=None, timeout=15, wait_after_load=2): + load_dotenv() + login_url = os.getenv('oa_login_url') + target_url_keyword = os.getenv('oa_target_url_keyword') + if not login_url or not target_url_keyword: + raise RuntimeError("环境变量 oa_login_url / oa_target_url_keyword 未设置") + + final_username = username or os.getenv('oa_login_username') + final_password = password or os.getenv('oa_login_password') + if not final_username or not final_password: + raise RuntimeError("用户名或密码未提供,请设置环境变量或传入参数") + + page = ChromiumPage() + try: + page.get(login_url) + time.sleep(wait_after_load) + username_input = page.ele('tag:input@name=j_username') + if not username_input: + raise RuntimeError("未找到用户名输入框") + username_input.input(final_username) + page.wait(0.5) + password_input = page.ele('tag:input@name=j_password') + if not password_input: + raise RuntimeError("未找到密码输入框") + password_input.input(final_password) + page.wait(0.5) + login_button = page.ele('.lui_login_button_div_c') + if not login_button: + raise RuntimeError("未找到登录按钮") + login_button.click() + page.wait(0.5) + start = time.time() + while time.time() - start < timeout: + if target_url_keyword in page.url: + logger.info("OA 登录成功!当前 URL: %s", page.url) + return page + time.sleep(0.5) + raise RuntimeError(f"OA 登录超时,当前 URL: {page.url}") + except Exception as e: + page.quit() + raise RuntimeError(f"OA 登录过程出错: {e}") + + +def get_oa_session(): + saved = load_saved_session(COOKIE_FILE_OA) + if saved is not None and is_oa_session_valid(saved): + logger.info("复用已保存的 OA 登录会话,跳过登录") + return create_browser_with_saved_cookies(COOKIE_FILE_OA), saved + logger.info("无可用 OA 会话,执行完整登录") + browser = oa_login() + session = init_session_from_page(browser) + save_browser_cookies(browser, COOKIE_FILE_OA) + return browser, session + + +# ==================== HR 登录(滑块验证码) ==================== +HR_LOGIN_URL = None +HR_SUCCESS_KEYWORD = None +HR_USERNAME = None +HR_PASSWORD = None +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 + + +def _load_hr_env(): + global HR_LOGIN_URL, HR_SUCCESS_KEYWORD, HR_USERNAME, HR_PASSWORD + load_dotenv() + HR_LOGIN_URL = os.getenv('hr_login_url') + HR_SUCCESS_KEYWORD = os.getenv('hr_target_url_keyword') + HR_USERNAME = os.getenv('hr_login_username') + HR_PASSWORD = os.getenv('hr_login_password') + + +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_hr_env() + if not (HR_LOGIN_URL and HR_SUCCESS_KEYWORD): + raise RuntimeError("环境变量 hr_login_url / hr_target_url_keyword 未设置") + final_username = username or HR_USERNAME + final_password = password or HR_PASSWORD + if not final_username or not final_password: + raise RuntimeError("HR 用户名或密码未提供,请设置环境变量或传入参数") + + 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 + + +# ==================== 导出(fdId / searchId / 总数 / 导出) ==================== +def _check_response(resp, action): + if resp is None: + raise RuntimeError(f"{action}失败,未获取到响应") + if resp.status_code != 200: + raise RuntimeError(f"{action}失败,状态码: {resp.status_code}") + + +def _resolve_query_date(query_date=None): + return query_date or datetime.now().strftime("%Y-%m-01") + + +def _build_filter_params(filter_idx, query_date=None): + day = _resolve_query_date(query_date) + return {f"v0_{filter_idx}": "gt", f"v1_{filter_idx}": day} + + +def _get_cookies_with_domain(session): + cookies = [] + try: + raw = session.session.cookies + for c in raw: + cookies.append({"name": c.name, "value": c.value, "domain": c.domain, "path": c.path or "/"}) + except Exception: + cookies = load_cookies(COOKIE_FILE_OA) or [] + return cookies + + +def get_fd_id_by_listening(session, browser=None): + own_browser = browser is None + if own_browser: + cookies = _get_cookies_with_domain(session) + if not cookies: + raise RuntimeError("Session 中没有 cookie,请先执行完整登录") + browser = ChromiumPage(ChromiumOptions()) + browser.set.cookies(cookies) + try: + browser.listen.start() + logger.info("正在访问 OA 首页:%s", HOME_URL) + browser.get(HOME_URL) + time.sleep(5) + deadline = time.time() + 10 + target = None + while time.time() < deadline: + req = browser.listen.wait(timeout=1) + if req and 'sysPortalNav.do' in req.url: + target = req + break + if target is None: + raise RuntimeError("超时未监听到菜单请求,请检查网络或登录态") + qs = parse_qs(urlparse(target.url).query) + fd_id = qs.get('fdId', [None])[0] + if not fd_id: + raise RuntimeError("菜单请求中未包含 fdId") + logger.info("动态获取到 fdId: %s", fd_id) + return fd_id + finally: + browser.listen.stop() + if own_browser: + browser.quit() + + +def get_search_id_from_menu(session, fd_id, menu_name=MENU_NAME_PARTICIPATE): + params = {"method": "portlet", "fdId": fd_id, "f_s": "sourcejs", "t": str(int(time.time() * 1000))} + session.get(f"{BASE_URL}{MENU_API_PATH}", params=params) + _check_response(session.response, "获取菜单") + data = session.response.json() + + def find_item(items): + for item in items: + if item.get("text") == menu_name: + return item + if "children" in item: + found = find_item(item["children"]) + if found: + return found + return None + + items = data if isinstance(data, list) else data.get("children", []) + item = find_item(items) + if not item: + raise RuntimeError(f"菜单中未找到 '{menu_name}'") + qs = parse_qs(urlparse(urljoin(BASE_URL, item["href"])).query) + search_id = qs.get("searchId", [None])[0] + if not search_id: + raise RuntimeError("菜单链接中未包含 searchId") + logger.info("从菜单获取到 searchId: %s", search_id) + return search_id + + +def get_total_count(session, base_params, search_id, timestamp): + params = {"method": "result", "searchId": search_id, "j_timestamp": timestamp, **base_params} + session.get(SEARCH_URL, params=params, headers={"Referer": LIST_URL}) + _check_response(session.response, "查询总数") + html = session.response.text + for pat in (r'exportNum:\s*"(\d+)"', r'总记录数[::]\s*(\d+)', r'共\s*(\d+)\s*条'): + m = re.search(pat, html) + if m: + total = int(m.group(1)) + logger.info("获取到总记录数: %d", total) + return total + logger.warning("未找到总条数,默认为 0") + return 0 + + +def export_all_data(session, base_params, total, columns, search_id, timestamp): + data = { + "method": "exportResult", "searchId": search_id, "j_timestamp": timestamp, **base_params, + "fdColumns": columns, "fdNum": str(total), "fdNumStart": "1", "fdNumEnd": str(total), + "fdKeepRtfStyle": "true", "checkIdValues": "", + } + session.post(SEARCH_URL, data=data, headers={"Referer": LIST_URL}) + _check_response(session.response, "导出数据") + return session.response.content + + +# ==================== 读取 + 清洗去重 ==================== +def _normalize_date_key(value): + if value is None: + return 0.0 + if isinstance(value, (int, float)): + return float(value) + if isinstance(value, str): + m = re.match(r"(\d{4})[-/年](\d{1,2})[-/月](\d{1,2})", value.strip()) + if m: + try: + y, mo, d = int(m.group(1)), int(m.group(2)), int(m.group(3)) + return (datetime(y, mo, d) - datetime(1899, 12, 30)).days + except ValueError: + return 0.0 + return 0.0 + + +def _date_display(value, wb): + if isinstance(value, (int, float)): + try: + dt = xlrd.xldate_as_datetime(float(value), wb.datemode) + except Exception: + return value + if float(value).is_integer(): + return dt.strftime("%Y-%m-%d") + return dt.strftime("%Y-%m-%d %H:%M:%S") + return value + + +def _read_and_clean(xls_path): + if xlrd is None: + raise RuntimeError("缺少 xlrd 依赖,无法读取 .xls") + wb = xlrd.open_workbook(xls_path) + sh = wb.sheet_by_index(0) + headers = [str(sh.cell_value(0, c)).strip() for c in range(sh.ncols)] + + def find_col(keyword): + for i, h in enumerate(headers): + if keyword in h: + return i + return None + + emp_col = find_col("工号") + date_col = find_col("申请日期") + status_col = find_col("文档状态") + if emp_col is None: + raise ValueError(f"未找到『工号』列,表头: {headers}") + + rows = [] + for r in range(1, sh.nrows): + row = [] + for c in range(sh.ncols): + v = sh.cell_value(r, c) + if sh.cell_type(r, c) == xlrd.XL_CELL_DATE: + v = _date_display(v, wb) + row.append(v) + emp = str(row[emp_col]).strip() + if not emp: + continue + if status_col is not None and str(row[status_col]).strip() == "废弃": + continue + row[emp_col] = emp + rows.append(row) + + latest = {} + for row in rows: + emp = row[emp_col] + key = _normalize_date_key(row[date_col]) if date_col is not None else 0.0 + if emp not in latest or key > latest[emp][0]: + latest[emp] = (key, row) + + ordered, seen = [], set() + for row in rows: + emp = row[emp_col] + if emp not in seen: + seen.add(emp) + ordered.append(latest[emp][1]) + + logger.info("清洗完成:去掉废弃后 %d 条,去重后 %d 条", len(rows), len(ordered)) + return headers, ordered, emp_col + + +# ==================== HR 参保记录核对 ==================== +@retry(max_attempts=3) +def _si_query_batch(session, codes_batch): + 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() + return resp.json() + + +def _si_found_codes(response_json): + datas = response_json.get("datas") or [] + return {str(item.get("base_Code")).strip() for item in datas if item.get("base_Code")} + + +def _si_check_batch(session, codes_batch): + try: + return _si_found_codes(_si_query_batch(session, codes_batch)) + except Exception as e: + logger.warning("参保记录批量查询失败 %s:%s", codes_batch, e) + return set() + + +def _write_annotated(headers, rows, emp_col, mode, base_name, output_dir="."): + if _XlsxWorkbook is None: + raise RuntimeError("缺少 openpyxl 依赖,无法导出 .xlsx") + + unique_codes, seen = [], set() + for row in rows: + code = str(row[emp_col]).strip() + if code and code not in seen: + seen.add(code) + unique_codes.append(code) + + session = get_hr_session() + found = set() + for i in range(0, len(unique_codes), SI_BATCH_SIZE): + found |= _si_check_batch(session, unique_codes[i:i + SI_BATCH_SIZE]) + logger.info("参保记录核对 %d/%d 个工号", min(i + SI_BATCH_SIZE, len(unique_codes)), len(unique_codes)) + time.sleep(0.3) + + is_participate = (mode == "participation") + new_rows = [] + for row in rows: + code = str(row[emp_col]).strip() + has_record = code in found + if is_participate: + val = "异常:已参保(系统有该工号记录)" if has_record else "正常:系统无该工号记录" + else: + val = "异常:已停保(系统无该工号记录)" if not has_record else "正常:系统有该工号记录" + new_rows.append(row + [val]) + + out_path = os.path.abspath(os.path.join(output_dir, f"{base_name}_参保核对.xlsx")) + out_wb = _XlsxWorkbook() + + # 样式:异常行标红 + 结果列加粗红字(仅当样式可用) + red_fill = PatternFill(start_color="FFC7CE", end_color="FFC7CE", fill_type="solid") if PatternFill else None + red_font = Font(color="9C0006", bold=True) if Font else None + head_fill = PatternFill(start_color="DDEBF7", end_color="DDEBF7", fill_type="solid") if PatternFill else None + + ws = out_wb.active + ws.title = "核对明细" + ws.append(headers + [SI_RESULT_COL]) + for c in range(1, len(headers) + 2): + cell = ws.cell(1, c) + cell.fill = head_fill + cell.font = Font(bold=True) if Font else None + cell.alignment = Alignment(horizontal="center") if Alignment else None + for idx, row in enumerate(new_rows, start=2): + ws.append(row) + if str(row[-1]).startswith("异常"): + for c in range(1, len(row) + 1): + cell = ws.cell(idx, c) + cell.fill = red_fill + if c == len(row): + cell.font = red_font + ws.freeze_panes = "A2" + ws.auto_filter.ref = ws.dimensions + if get_column_letter: + for c in range(1, len(headers) + 2): + ws.column_dimensions[get_column_letter(c)].width = 20 + + out_wb.save(out_path) + + abnormal = [r for r in new_rows if r[-1].startswith("异常")] + logger.info("参保核对完成:共 %d 个工号,查询到参保记录 %d 个,异常 %d 条,导出 %s", + len(unique_codes), len(found), len(abnormal), out_path) + return out_path + + +# ==================== 导出 + 核对一条龙 ==================== +def export_employee_change_list(menu_name, filter_idx, columns, output_dir, query_date=None): + logger.info("社保增减名单核对流程开始,菜单:%s", menu_name) + base_params = {**DEFAULT_FIXED_PARAMS, **_build_filter_params(filter_idx, query_date)} + browser, session = get_oa_session() + + try: + fd_id = get_fd_id_by_listening(session, browser) + search_id = get_search_id_from_menu(session, fd_id, menu_name) + timestamp = str(int(time.time() * 1000)) + total = get_total_count(session, base_params, search_id, timestamp) + if total == 0: + logger.warning("查询结果为 0 条,请检查筛选条件或无数据") + return "" + + logger.info("开始导出 %d 条记录...", total) + content = export_all_data(session, base_params, total, columns, search_id, timestamp) + output_path = os.path.abspath(os.path.join( + output_dir, f"{time.strftime('%Y%m')}_{menu_name}表_{time.strftime('%H%M%S')}.xls")) + with open(output_path, "wb") as f: + f.write(content) + logger.info("导出完成,文件保存为:%s", output_path) + + headers, rows, emp_col = _read_and_clean(output_path) + mode = "suspension" if menu_name == MENU_NAME_SUSPEND else "participation" + final_path = _write_annotated( + headers, rows, emp_col, mode, + os.path.splitext(os.path.basename(output_path))[0], output_dir) + try: + os.remove(output_path) + logger.info("已清理中间原始导出文件:%s", output_path) + except Exception: + pass + return final_path + finally: + if browser is not None: + try: + browser.quit() + except Exception: + pass + + +def export_participation(output_dir=".", query_date=None): + return export_employee_change_list( + MENU_NAME_PARTICIPATE, FILTER_IDX_PARTICIPATE, DEFAULT_EXPORT_COLUMNS, output_dir, query_date) + + +def export_suspension(output_dir=".", query_date=None): + return export_employee_change_list( + MENU_NAME_SUSPEND, FILTER_IDX_SUSPEND, DEFAULT_EXPORT_COLUMNS_SUSPEND, output_dir, query_date) + + +# ==================== 钉钉推送 ==================== +def _check_dingtalk_deps(): + missing = [] + if pyautogui is None: + missing.append("pyautogui") + if win32gui is None: + missing.append("pywin32") + if pyperclip is None: + missing.append("pyperclip") + if missing: + raise RuntimeError(f"缺少依赖: {', '.join(missing)},请运行: pip install {' '.join(missing)}") + + +def _find_dingtalk_hwnd(): + matches = [] + + def _enum(hwnd, _): + if not win32gui.IsWindowVisible(hwnd): + return + title = win32gui.GetWindowText(hwnd) + if title and DINGTALK_WINDOW_KEYWORD in title: + matches.append((hwnd, title)) + + win32gui.EnumWindows(_enum, None) + if not matches: + raise RuntimeError("未找到标题包含「钉钉」的可见窗口,请确认钉钉桌面端已启动并登录") + matches.sort(key=lambda x: len(x[1])) + return matches[0][0] + + +def _is_dingtalk_foreground(): + return DINGTALK_WINDOW_KEYWORD in win32gui.GetWindowText(win32gui.GetForegroundWindow()) + + +def _activate_dingtalk(): + if _is_dingtalk_foreground(): + return + hwnd = None + try: + hwnd = _find_dingtalk_hwnd() + except RuntimeError: + pass + if hwnd is None: + pyautogui.hotkey("ctrl", "d") + time.sleep(1.5) + hwnd = _find_dingtalk_hwnd() + if win32gui.IsIconic(hwnd): + win32gui.ShowWindow(hwnd, win32con.SW_RESTORE) + time.sleep(0.3) + pyautogui.press("alt") + win32gui.SetForegroundWindow(hwnd) + time.sleep(1.0) + rect = win32gui.GetWindowRect(hwnd) + pyautogui.click((rect[0] + rect[2]) // 2, (rect[1] + rect[3]) // 2) + time.sleep(0.5) + + +def _send_dingtalk_text(target, text): + _check_dingtalk_deps() + _activate_dingtalk() + pyautogui.hotkey("ctrl", "shift", "f") + time.sleep(0.5) + pyperclip.copy(target) + pyautogui.hotkey("ctrl", "v") + time.sleep(1.0) + pyautogui.press("enter") + time.sleep(3.5) + if not _is_dingtalk_foreground(): + _activate_dingtalk() + try: + hwnd = _find_dingtalk_hwnd() + rect = win32gui.GetWindowRect(hwnd) + cy = rect[1] + int((rect[3] - rect[1]) * 0.85) + pyautogui.click((rect[0] + rect[2]) // 2, cy) + time.sleep(0.5) + except Exception: + pass + pyperclip.copy(text) + pyautogui.hotkey("ctrl", "v") + time.sleep(0.3) + pyautogui.press("enter") + time.sleep(1.0) + logger.info("钉钉文本已发送: %s", text[:50] + ("..." if len(text) > 50 else "")) + + +def _read_abnormal(xlsx_path, label): + """读取标注表,返回 (总条数, 异常行列表)。异常行形如 [工号, 申请人/姓名, 结果] 说明文本。""" + if _load_workbook is None or not os.path.exists(xlsx_path): + return 0, [] + ws = _load_workbook(xlsx_path).active + rows = list(ws.iter_rows(values_only=True)) + headers = [str(h) if h is not None else "" for h in rows[0]] + emp_col = next((i for i, h in enumerate(headers) if "工号" in h), None) + res_col = headers.index(SI_RESULT_COL) + name_col = next((i for i, h in enumerate(headers) if h in ("申请人", "停保人姓名")), None) + abnormal = [] + for r in rows[1:]: + val = r[res_col] if res_col < len(r) else "" + if val and str(val).startswith("异常"): + emp = str(r[emp_col]) if emp_col is not None and emp_col < len(r) else "" + name = str(r[name_col]) if name_col is not None and name_col < len(r) else "" + abnormal.append(f" · 工号{emp} {name} —— {val}") + return len(rows) - 1, abnormal + + +def build_push_text(part_path, susp_path): + p_total, p_abn = _read_abnormal(part_path, "参保") + s_total, s_abn = _read_abnormal(susp_path, "停保") + lines = ["【社保增减名单核对结果】"] + lines.append(f"参保表:共 {p_total} 条,异常 {len(p_abn)} 条") + if p_abn: + lines.extend(p_abn) + else: + lines.append(" 无异常") + lines.append("") + lines.append(f"停保表:共 {s_total} 条,异常 {len(s_abn)} 条") + if s_abn: + lines.extend(s_abn) + else: + lines.append(" 无异常") + return "\n".join(lines) + + +def push_report(text): + """推送核对结果到钉钉(env 控制,失败不影响主流程)。""" + if not text or not text.strip(): + return False + load_dotenv() + if os.getenv("dingtalk_notify_enabled", "false").lower() != "true": + logger.info("钉钉推送未开启(dingtalk_notify_enabled!=true),跳过") + return False + target = os.getenv("dingtalk_notify_target", "").strip() + if not target: + logger.warning("未配置 dingtalk_notify_target,跳过钉钉推送") + return False + try: + _send_dingtalk_text(target, text) + logger.info("核对结果已推送至钉钉: %s", target) + return True + except Exception as e: + logger.warning("钉钉推送失败: %s", e) + return False + + +# ==================== 主入口 ==================== +def main(): + load_dotenv() + args = sys.argv[1:] + output_dir = os.getenv("social_change_output_dir") or os.getcwd() + query_date = None + change_type = "全部" + for a in args: + if re.match(r"^\d{4}-\d{2}-\d{2}$", a): + query_date = a + elif a in ("参保", "participate"): + change_type = "参保" + elif a in ("停保", "suspend"): + change_type = "停保" + + if query_date is None: + query_date = os.getenv("social_change_query_date") or None + + part_path = "" + susp_path = "" + if change_type in ("参保", "全部"): + part_path = export_participation(output_dir=output_dir, query_date=query_date) + if change_type in ("停保", "全部"): + susp_path = export_suspension(output_dir=output_dir, query_date=query_date) + + # 推送两张表汇总(当两者都跑了或至少跑了一个) + if part_path or susp_path: + push_report(build_push_text(part_path, susp_path)) + + +if __name__ == "__main__": + main()