1. 新增考勤异常查询与导出模块,支持当月异常拉取、Excel导出、钉钉推送提醒 2. 完善请假/加班流程解析与校验,新增附件下载、OCR核验能力 3. 新增银行卡信息校验模块,支持在职/离职员工工资卡数据核对与异常导出 4. 新增通用OCR工具模块,支持病假/婚假/产检假附件关键词检测与日期提取 5. 新增门店请休假异常名单、银行卡检查等需求文档 6. 重构部分现有模块代码,优化配置与接口调用逻辑 7. 新增测试文件与工具类,完善项目基础能力
1192 lines
43 KiB
Python
1192 lines
43 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
@FileName: social_change_yingdao.py
|
||
@Author: 小布丁
|
||
@CreateTime: 2026-08-07
|
||
@Description: 社保增减名单核对(统一单文件版,app 与影刀共用)——OA 登录导出参保/停保名单 -> 清洗去重 -> HR 登录(滑块验证码)调用 si_main 参保记录接口核对 -> 追加结果列 -> 钉钉推送两张表
|
||
@Version: 2.1.0
|
||
|
||
设计说明(避免维护 app/影刀两套版本):
|
||
- 单文件自包含,可放任意目录直接运行(含 App 项目目录或影刀环境)。
|
||
- 内含 HR 登录(滑块验证码识别),保证 si_main 查询所需的 hr.37du.co 登录态。
|
||
|
||
业务判定:
|
||
- 参保申请表:某工号在 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=结果输出目录(默认 D:\资料\人资\员工社保增减名单)
|
||
"""
|
||
|
||
# ==================== 标准库导入 ====================
|
||
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, no_retry_on: tuple = ()):
|
||
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 no_retry_on:
|
||
raise
|
||
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 = "https://hr.37du.co/RedseaPlatform/"
|
||
HR_SUCCESS_KEYWORD = "https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic"
|
||
HR_USERNAME = "Test01"
|
||
HR_PASSWORD = "37du@1234"
|
||
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 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):
|
||
if not (HR_LOGIN_URL and HR_SUCCESS_KEYWORD):
|
||
raise RuntimeError("HR 登录配置未设置")
|
||
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 参保记录核对 ====================
|
||
class HRSessionExpiredError(Exception):
|
||
"""HR 登录态过期:接口返回登录页等非 JSON 内容。"""
|
||
|
||
|
||
def _si_is_expired(text):
|
||
"""接口正常情况下返回 JSON;返回登录页/错误页等非 JSON 即视为登录态过期。"""
|
||
return bool(text) and not text.lstrip().startswith(("{", "["))
|
||
|
||
|
||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||
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()
|
||
if _si_is_expired(resp.text):
|
||
raise HRSessionExpiredError("HR 登录态已过期,接口返回非 JSON 内容")
|
||
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 HRSessionExpiredError:
|
||
raise
|
||
except Exception as e:
|
||
logger.warning("参保记录批量查询失败 %s:%s", codes_batch, e)
|
||
return set()
|
||
|
||
|
||
def _si_preflight(session):
|
||
"""正式核对前先探测一次接口,确认 HR 登录态有效;过期则重新登录并重建 session。"""
|
||
try:
|
||
_si_query_batch(session, ["0"])
|
||
except HRSessionExpiredError:
|
||
logger.warning("预检发现 HR 登录态已过期,正在重新登录")
|
||
hr_login()
|
||
return _build_hr_session()
|
||
return session
|
||
|
||
|
||
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 = _si_preflight(get_hr_session())
|
||
found = set()
|
||
for i in range(0, len(unique_codes), SI_BATCH_SIZE):
|
||
batch = unique_codes[i:i + SI_BATCH_SIZE]
|
||
try:
|
||
found |= _si_check_batch(session, batch)
|
||
except HRSessionExpiredError:
|
||
logger.warning("HR 登录态过期,正在重新登录并续跑(第 %d/%d 批)",
|
||
min(i + SI_BATCH_SIZE, len(unique_codes)), len(unique_codes))
|
||
hr_login()
|
||
session = _build_hr_session()
|
||
found |= _si_check_batch(session, batch)
|
||
logger.info("参保记录核对 %d/%d 个工号", min(i + SI_BATCH_SIZE, len(unique_codes)), len(unique_codes))
|
||
time.sleep(0.3)
|
||
|
||
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_candidates = ("参保人",) if label == "参保" else ("停保人姓名",)
|
||
name_col = next((i for i, h in enumerate(headers) if h in name_candidates), 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 r"D:\资料\人资\员工社保增减名单"
|
||
os.makedirs(output_dir, exist_ok=True)
|
||
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()
|