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-06 | -37035868 | -孙乐梅 | -保健师 | -612323199312248329 | -15191640557 | -外地农村 | -结束 | -- 结束节点 - | -- - - | -
| - | 2 | -车站南路CEO会馆_技师组 - | -刘树勇 | -2026-08-06 | -37034578 | -王来 | -保健师 | -430121198712095241 | -15073151371 | -外地农村 | -结束 | -- 结束节点 - | -- - - | -
| - | 3 | -金鹰LIFE主题会馆_技师组 - | -蒋德静 | -2026-08-05 | -37035680 | -杨圣平 | -保健师 | -53233120041224382X | -15812119041 | -本地农村 | -结束 | -- 结束节点 - | -- - - | -
| - | 4 | -鸳鸯行政会馆_技师组 - | -马茂杨 | -2026-08-05 | -37010344 | -陈万丽 | -归真技师 | -522122199206227429 | -18166998334 | -外地城镇 | -结束 | -- 结束节点 - | -- - - | -
| - | 5 | -鸳鸯行政会馆_技师组 - | -马茂杨 | -2026-08-05 | -37010344 | -陈万丽 | -归真技师 | -522122199206227429 | -18166998334 | -外地城镇 | -废弃 | -- 结束节点 - | -- - - | -
| - | 6 | -洋河北路CEO会馆_技师组 - | -陈志祥 | -2026-08-05 | -37020789 | -蔡运婷 | -归真技师 | -50010619850902942X | -13752871644 | -本地城镇 | -结束 | -- 结束节点 - | -- - - | -
| - | 7 | -国贸LIFE主题会馆_技师组 - | -隆城 | -2026-08-04 | -37036109 | -蒲荣 | -保健师 | -511304198906157223 | -18102794578 | -外地农村 | -结束 | -- 结束节点 - | -- - - | -
| - | 8 | -春晖路CEO会馆_接待组 - | -徐利 | -2026-08-04 | -37006639 | -徐利 | -接待组负责人,营运主管 - | -510521199203087426 | -18148474240 | -外地农村 | -结束 | -- 结束节点 - | -- - - | -
| - | 9 | -新光天地行政会馆_技师组 - | -黄甜 | -2026-08-04 | -37034232 | -马忠莉 | -保健师 | -511025198410163940 | -13698309146 | -本地城镇 | -结束 | -- 结束节点 - | -- - - | -
| - | 10 | -女宾部_女宾服务组 | -梁敏 | -2026-08-04 | -37025027 | -吴长春 | -水区服务顾问(女) - | -51290219790311446X | -18090507933 | -外地城镇 | -结束 | -- 结束节点 - | -- - - | -
| - | 11 | -国贸LIFE主题会馆_技师组 - | -隆城 | -2026-08-03 | -37035876 | -符小妹 | -保健师 | -46002720020901852X | -15508954368 | -本地农村 | -结束 | -- 结束节点 - | -- - - | -
| - | 12 | -国贸LIFE主题会馆_技师组 - | -隆城 | -2026-08-03 | -37035873 | -符式月 | -保健师 | -460025199802111823 | -18889124407 | -本地农村 | -结束 | -- 结束节点 - | -- - - | -
| - | 13 | -南门行政会馆_餐饮组 - | -谢利超 | -2026-08-03 | -37032935 | -陈润 | -吧员 | -612429199007240738 | -15929963446 | -本地农村 | -结束 | -- 结束节点 - | -- - - | -
| - | 14 | -河西麓谷行政会馆_技师组 - | -沙丁 | -2026-08-03 | -37017808 | -刘美兰 | -归真技师 | -432524199008278324 | -18216457320 | -本地农村 | -结束 | -- 结束节点 - | -- - - | -
| - | 15 | -观音桥步行街行政会馆_技师组 - | -王林洪 | -2026-08-03 | -37033899 | -张春琴 | -保健师 | -522401198502088224 | -15730249899 | -外地农村 | -结束 | -- 结束节点 - | -- - - | -