refactor: 替换排班/打卡接口为考勤逐日接口,清理旧依赖
1. 重构考勤相关接口:将get_attendance_html、get_attendance_records替换为get_attendance_daily,使用新的ATTENDANCE_DAILY_URL接口替代旧接口 2. 更新请假校验逻辑:使用考勤逐日接口统计上班天数,替换原跨月排班HTML请求逻辑 3. 升级测试用例:同步更新test_03_attendance.py和test_06_leave_online.py适配新接口 4. 新增/完善文档:新增多份流程与需求文档,删除旧版冗余文档,整理docs目录结构 5. 清理废弃文件:删除原周考勤异常、门店请休假异常相关旧需求文档 6. 配置更新:更新config.py中的考勤相关URL常量,补充注释说明 7. 待办优化:更新aa.md内容,同步加班审批规则说明
This commit is contained in:
@@ -0,0 +1,584 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: attendance_abnormal_yingdao.py
|
||||
@Description: 周考勤异常处理(影刀单文件版)- 独立自 app/service/hrbp/ehr/attendance/attendance_abnormal.py,
|
||||
业务逻辑完全一致:HR 登录态(共享登录)→ 分页拉取当月未调整考勤异常 → 导出 Excel 底稿
|
||||
→ 分级分类(轻微直接处理 / 其余钉钉核实)→ 按「姓名-工号」合并推送当事人
|
||||
→ 生成处理汇总报表 → 推送给 人资专用号 留痕。
|
||||
@Version: 1.1.0
|
||||
|
||||
登录(共享登录,不内联滑块算法):
|
||||
- 登录态统一由「37duHR登录」影刀自定义指令写入共享 cookies:
|
||||
%LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json
|
||||
- 本脚本直接复用该 cookies;缺失/失效时,若当前目录存在 yingdao/instructions/hr_login.py
|
||||
则自动调用共享登录模块补登(便于本地 python 独立运行调试);
|
||||
影刀定时任务中请在流程开头先拖入「37duHR登录」指令。
|
||||
|
||||
钉钉推送(共享指令,不内联 OCR 视觉发送代码):
|
||||
- 实际发送统一由「37du钉钉推送」影刀自定义指令承担(单一真源:
|
||||
yingdao/instructions/dingtalk_sender.py),本脚本通过 import 调用其
|
||||
main({"messages": [...]}) 批量发送(messages 为字典列表,逐条发送并汇总结果);
|
||||
- 影刀流程中也可直接拖入「37du钉钉推送」指令,把 messages(字典列表)
|
||||
或 target/text 传入即可完成发送,等价于本脚本内部调用;
|
||||
- 本脚本运行后会同步把待推送的 messages(字典列表)写入影刀全局变量
|
||||
glv['messages'](无数据时置为空列表),供流程后续步骤读取复用;
|
||||
- 钉钉 OCR 视觉发送所需依赖(pyautogui/pywin32/pyperclip/psutil/Pillow/numpy/
|
||||
rapidocr-onnxruntime)由共享指令内自校验,本脚本不再重复安装。
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install requests python-dotenv pandas openpyxl
|
||||
|
||||
环境变量(.env 或系统变量,固定路径共享 .env 见 yingdao/instructions/hr_login.py):
|
||||
dingtalk_push_enabled=true|false(默认 false,是否启用钉钉推送,总开关)
|
||||
dingtalk_notify_target=人资专用号钉钉联系人姓名(处理汇总报表推送对象,如 夏一平)
|
||||
attendance_save_dir=(可选)Excel 导出目录,默认 D:\\资料\\人资\\考勤异常
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
import time
|
||||
from datetime import date, datetime
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install requests python-dotenv pandas openpyxl\n"
|
||||
"(钉钉推送相关依赖 pyautogui/pywin32/pyperclip/psutil/Pillow/numpy/"
|
||||
"rapidocr-onnxruntime 由共享指令 dingtalk_sender.py 校验,见其文档头)\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
load_dotenv()
|
||||
|
||||
# ==================== 日志(print) ====================
|
||||
class _PrintLogger:
|
||||
"""影刀版无 logging 依赖,直接用 print 输出,行为与项目 logger 对齐。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[DEBUG] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[INFO] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[WARN] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[ERROR] {msg}")
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
# ==================== 影刀全局变量(glv) ====================
|
||||
def _set_glv(name, value):
|
||||
"""写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
|
||||
try:
|
||||
glv[name] = value
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ==================== 共享路径 & 常量配置(与 app 版统一,见 app/common/app_paths.py) ====================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
# HR 登录态:由「37duHR登录」共享指令写入
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- HR 系统 ----------
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
GET_CUR_USER_INFO_URL = f"{HR_BASE_URL}/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
ATTENDANCE_ABNORMAL_URL = f"{HR_BASE_URL}/RedseaPlatform/kqController/getPageAjaxList.mc"
|
||||
PAGE_MAX_SIZE = 500
|
||||
|
||||
# 默认保存目录(可用环境变量覆盖)
|
||||
SAVE_DIR = os.getenv("attendance_save_dir") or r"D:\资料\人资\考勤异常"
|
||||
|
||||
# 英文字段 → 中文字段映射(aa.md 提供的考勤异常字段,其余字段保留原样)
|
||||
COL_MAP = {
|
||||
"abnormal_id": "异常ID",
|
||||
"STAFF_NAME": "员工姓名",
|
||||
"base_code": "工号",
|
||||
"first_type_name": "职位序列",
|
||||
"work_day": "考勤日期",
|
||||
"bc_name": "班次",
|
||||
"abnormal": "异常类型",
|
||||
"abnormal_minute": "异常时长(分钟)",
|
||||
}
|
||||
|
||||
SHOW_ORDER = [
|
||||
"异常ID", "员工姓名", "工号", "职位序列", "考勤日期", "班次", "异常类型", "异常时长(分钟)",
|
||||
]
|
||||
|
||||
# 考勤异常调整状态过滤(本次只查询「未调整」);0=未调整、1=补签调整、2=确认异常、3=正常调整、空=所有
|
||||
IS_ADJUSTED = "0"
|
||||
# 钉钉推送总开关(默认关闭仅生成报表打印)
|
||||
DINGTALK_PUSH_ENABLED = "true"
|
||||
# 人资专用号:处理汇总报表推送对象;未配置则跳过汇总推送
|
||||
DINGTALK_NOTIFY_TARGET = "夏一平"
|
||||
|
||||
|
||||
# ==================== 共享登录集成 ====================
|
||||
# 脚本位于 yingdao/ 下,共享登录模块位于 yingdao/instructions/ 下,可直接 import(本地独立运行);
|
||||
# 影刀部署时若未携带该目录则退化为「仅复用共享 cookies」。
|
||||
_INSTRUCTION_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "instructions")
|
||||
if _INSTRUCTION_DIR not in sys.path:
|
||||
sys.path.insert(0, _INSTRUCTION_DIR)
|
||||
|
||||
try:
|
||||
import hr_login as _hr_login_shared # noqa: E402
|
||||
if os.path.exists(SHARED_ENV_FILE):
|
||||
from dotenv import load_dotenv as _reload_dotenv
|
||||
_reload_dotenv(SHARED_ENV_FILE)
|
||||
_hr_login_shared._load_shared_env()
|
||||
except ImportError:
|
||||
_hr_login_shared = None
|
||||
|
||||
try:
|
||||
import dingtalk_sender as _dt_sender_shared # noqa: E402
|
||||
except ImportError:
|
||||
_dt_sender_shared = None
|
||||
|
||||
|
||||
def _send_dingtalk_text(target, text):
|
||||
"""钉钉 OCR 视觉推送(共享指令):调用 dingtalk_sender.send_dingtalk_text(单条)。
|
||||
本地运行时要求 yingdao/instructions/dingtalk_sender.py 存在;影刀流程中
|
||||
也可直接拖入「37du钉钉推送」指令发送,二者等价。
|
||||
"""
|
||||
if _dt_sender_shared is not None:
|
||||
return _dt_sender_shared.send_dingtalk_text(target, text)
|
||||
raise RuntimeError(
|
||||
"未加载共享钉钉推送模块(yingdao/instructions/dingtalk_sender.py)。\n"
|
||||
"请在影刀流程中拖入「37du钉钉推送」指令发送,或本地放置该共享模块文件。")
|
||||
|
||||
|
||||
def _send_dingtalk_messages(messages):
|
||||
"""批量钉钉推送(共享指令):调用 dingtalk_sender.main({"messages": [...]})。
|
||||
messages 为字典列表,逐条发送并汇总;返回 (成功数, 失败数),单条失败不中断整体。
|
||||
"""
|
||||
if _dt_sender_shared is None:
|
||||
raise RuntimeError(
|
||||
"未加载共享钉钉推送模块(yingdao/instructions/dingtalk_sender.py)。\n"
|
||||
"请在影刀流程中拖入「37du钉钉推送」指令发送,或本地放置该共享模块文件。")
|
||||
result = _dt_sender_shared.main({"messages": messages})
|
||||
return result.get("sent", 0), result.get("failed", 0)
|
||||
|
||||
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态失效(接口返回非 JSON,被重定向到登录页)。"""
|
||||
|
||||
|
||||
def hr_request_json(session, method, url, params, label, timeout=20):
|
||||
"""POST/GET 请求并校验返回 JSON;失效抛 HRSessionExpiredError。"""
|
||||
resp = session.request(method.upper(), url, data=params, timeout=timeout)
|
||||
resp.raise_for_status()
|
||||
text = resp.text
|
||||
if not text or not text.lstrip().startswith(("{", "[")):
|
||||
raise HRSessionExpiredError(f"{label}:HR 登录态失效(返回非 JSON)")
|
||||
return resp.json()
|
||||
|
||||
|
||||
def _load_shared_hr_cookies():
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
return None
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
def _ensure_hr_cookies():
|
||||
"""确保存在 HR 登录态文件;缺失时优先调用共享登录模块补登。"""
|
||||
if _load_shared_hr_cookies():
|
||||
return True
|
||||
if _hr_login_shared is not None:
|
||||
logger.info("无 HR cookies,调用共享 HR 登录模块自动登录")
|
||||
result = _hr_login_shared.ensure_login(force=False)
|
||||
if result.get("success"):
|
||||
return True
|
||||
raise RuntimeError(f"HR 自动登录失败:{result.get('message')}")
|
||||
raise RuntimeError(
|
||||
"未找到 HR 登录态(hr_cookies.json)且无法加载共享登录模块。\n"
|
||||
"请在影刀流程开头先调用「37duHR登录」指令,或本地先运行 python yingdao/instructions/hr_login.py")
|
||||
|
||||
|
||||
def build_hr_session():
|
||||
"""用共享 hr_cookies.json 构建 requests.Session(过滤 hr.37du.co 域)。"""
|
||||
_ensure_hr_cookies()
|
||||
cookies = _load_shared_hr_cookies()
|
||||
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 "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
def _relogin_get_user_info():
|
||||
"""登录态失效后:补登 → 重建会话 → 重新获取 userId/rootId。"""
|
||||
_ensure_hr_cookies()
|
||||
session = build_hr_session()
|
||||
info = fetch_cur_user_info(session)
|
||||
return session, info.get("userId", ""), info.get("rootId", "")
|
||||
|
||||
|
||||
# ==================== HR 接口 ====================
|
||||
def fetch_cur_user_info(session):
|
||||
return hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
|
||||
|
||||
|
||||
def fetch_attendance_abnormal_page(session, user_id, treecode, begin_date, end_date,
|
||||
page_no=1, page_size=PAGE_MAX_SIZE,
|
||||
is_adjusted=IS_ADJUSTED, abnormal_type=""):
|
||||
params = {
|
||||
"treecode": treecode,
|
||||
"user_id": user_id,
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"sqlId": "kq_count_abnormal_Select",
|
||||
"redapiId": "rf_p_kq_count_abnormal_Select",
|
||||
"treeCodeList": "",
|
||||
"abnormal_type": abnormal_type,
|
||||
"base_code": "",
|
||||
"join_date": "",
|
||||
"join_date_end": end_date,
|
||||
"person_status": "",
|
||||
"staff_id": "",
|
||||
"post_no": "",
|
||||
"post_type": "1",
|
||||
"period_order": "",
|
||||
"identity_test": "",
|
||||
"identity": "",
|
||||
"sex": "",
|
||||
"age": "",
|
||||
"age_end": "",
|
||||
"start_operat_time": "",
|
||||
"end_operat_time": "",
|
||||
"operator_username": "",
|
||||
"operator_userid": "",
|
||||
"is_adjusted": is_adjusted,
|
||||
"begin_date": begin_date,
|
||||
"end_date": end_date,
|
||||
"STAFF_NAME": "",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "desc",
|
||||
"sortName": "work_day",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", ATTENDANCE_ABNORMAL_URL, params, "考勤异常")
|
||||
|
||||
|
||||
def fetch_all_attendance_abnormal(session, user_id, treecode, begin_date, end_date,
|
||||
is_adjusted=IS_ADJUSTED, abnormal_type=""):
|
||||
"""分页拉取全部考勤异常;中途登录态失效自动补登后续抓。"""
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_attendance_abnormal_page(
|
||||
session, user_id, treecode, begin_date, end_date,
|
||||
page_no, PAGE_MAX_SIZE, is_adjusted, abnormal_type)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("考勤异常 HR 登录态过期,自动补登后续抓")
|
||||
session, user_id, treecode = _relogin_get_user_info()
|
||||
data = fetch_attendance_abnormal_page(
|
||||
session, user_id, treecode, begin_date, end_date,
|
||||
page_no, PAGE_MAX_SIZE, is_adjusted, abnormal_type)
|
||||
if data.get("state") != "1":
|
||||
logger.error("考勤异常第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("考勤异常无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("考勤异常已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
# ==================== 业务规则(与 app 版一致) ====================
|
||||
def current_month_range(today=None):
|
||||
"""返回当月查询范围:(当月1日, 今天)。"""
|
||||
today = today or date.today()
|
||||
begin = today.replace(day=1)
|
||||
return begin.strftime("%Y-%m-%d"), today.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def classify_abnormal(item):
|
||||
"""判断该条异常是否需要钉钉推送。
|
||||
迟到/早退 且 异常时长 < 30 分钟 → 不推送(轻微异常,直接处理);
|
||||
迟到/早退 >= 30 分钟 或 其他类型(旷工/工时不足/漏打卡等)→ 推送。
|
||||
"""
|
||||
abnormal = str(item.get("abnormal", ""))
|
||||
try:
|
||||
minute = int(item.get("abnormal_minute", 0) or 0)
|
||||
except (TypeError, ValueError):
|
||||
minute = 0
|
||||
if ("迟到" in abnormal or "早退" in abnormal) and minute < 30:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def is_func_staff(item):
|
||||
"""判断该员工是否属于职能序列(first_type_name 含「职能」才推送)。"""
|
||||
return "职能" in str(item.get("first_type_name", "") or "")
|
||||
|
||||
|
||||
def build_notify_text(items):
|
||||
"""按人员合并拼接钉钉通知文本(一人一条,含该人全部异常)。"""
|
||||
first = items[0]
|
||||
lines = [
|
||||
"【考勤异常核实通知】",
|
||||
f"姓名:{first.get('STAFF_NAME', '')}",
|
||||
f"工号:{first.get('base_code', '')}",
|
||||
f"共 {len(items)} 条考勤异常,请逐条确认:",
|
||||
]
|
||||
for idx, item in enumerate(items, 1):
|
||||
abnormal = str(item.get("abnormal", "") or "").strip() or "考勤异常"
|
||||
minute = item.get("abnormal_minute")
|
||||
if ("迟到" in abnormal or "早退" in abnormal) and minute not in ("", None):
|
||||
confirm_item = f"{abnormal}{minute}分钟"
|
||||
else:
|
||||
confirm_item = abnormal
|
||||
lines.append(
|
||||
f"{idx}. 考勤日期:{item.get('work_day', '')}|班次:{item.get('bc_name', '')}"
|
||||
f"|异常类型:{abnormal}|异常时长:{minute}分钟"
|
||||
)
|
||||
lines.append(f" 请确认本次{confirm_item}真实情况:{abnormal}/漏打卡/外出/其他")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
# ==================== 导出 Excel ====================
|
||||
def export_excel(data, save_dir, month_str):
|
||||
if not data:
|
||||
raise ValueError("未查询到任何考勤异常数据,无法导出")
|
||||
|
||||
df = pd.DataFrame(data)
|
||||
df.rename(columns=COL_MAP, inplace=True)
|
||||
exist_cols = [col for col in SHOW_ORDER if col in df.columns]
|
||||
other_cols = [col for col in df.columns if col not in exist_cols]
|
||||
df = df[exist_cols + other_cols]
|
||||
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
save_path = os.path.abspath(os.path.join(save_dir, f"考勤异常_{month_str}_{ts}.xlsx"))
|
||||
try:
|
||||
df.to_excel(save_path, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试"
|
||||
)
|
||||
logger.info("考勤异常数据:%d 条", len(data))
|
||||
logger.info("文件已保存:%s", save_path)
|
||||
return save_path
|
||||
|
||||
|
||||
# ==================== 钉钉推送(总开关控制) ====================
|
||||
def push_abnormal(items):
|
||||
"""按「工号-姓名」分组,合并为 messages 字典列表后一次性批量推送给当事人。
|
||||
推送目标(target)使用工号作为钉钉搜索关键字,避免同名人员误发;
|
||||
会话标题校验名(display_name)传姓名(钉钉标题显示姓名而非工号)。
|
||||
返回 (成功数, 失败数);单条失败不中断整体(共享指令内部逐条 try/except 汇总)。
|
||||
"""
|
||||
groups = {}
|
||||
for it in items:
|
||||
name = it.get("STAFF_NAME", "") or ""
|
||||
if not name:
|
||||
logger.warning("异常记录缺少姓名,跳过:%s", it)
|
||||
continue
|
||||
key = (it.get("base_code", "") or "", name)
|
||||
groups.setdefault(key, []).append(it)
|
||||
|
||||
messages = [
|
||||
{"target": _code or _name, "display_name": _name, "text": build_notify_text(group)}
|
||||
for (_code, _name), group in groups.items()
|
||||
]
|
||||
# 同步写入影刀全局变量,供流程后续步骤/「37du钉钉推送」指令读取(无数据也置空,避免 NameError)
|
||||
_set_glv('messages', messages)
|
||||
if not messages:
|
||||
return 0, 0
|
||||
|
||||
push_count, fail_count = _send_dingtalk_messages(messages)
|
||||
logger.info("当事人批量推送完成:成功 %d 条,失败 %d 条(共 %d 人)",
|
||||
push_count, fail_count, len(messages))
|
||||
return push_count, fail_count
|
||||
|
||||
|
||||
def push_report(report):
|
||||
"""推送处理汇总报表到 人资专用号(未配置则跳过,失败不影响主流程)。"""
|
||||
if not DINGTALK_NOTIFY_TARGET:
|
||||
logger.warning("未配置 dingtalk_notify_target,跳过汇总报表推送")
|
||||
return False
|
||||
try:
|
||||
_send_dingtalk_text(DINGTALK_NOTIFY_TARGET, report)
|
||||
logger.info("汇总报表已推送至人资专用号:%s", DINGTALK_NOTIFY_TARGET)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.warning("汇总报表推送失败:%s", e)
|
||||
return False
|
||||
|
||||
|
||||
# ==================== 处理汇总报表(推送前生成最终结果) ====================
|
||||
def generate_report(data, handled_list, func_list, non_func_list, save_path, begin, end):
|
||||
lines = []
|
||||
lines.append("=" * 60)
|
||||
lines.append("周考勤异常处理报表")
|
||||
lines.append("=" * 60)
|
||||
lines.append(f"查询范围:{begin} ~ {end}")
|
||||
lines.append(f"考勤异常总数:{len(data)} 条")
|
||||
lines.append(f"直接处理(轻微,迟到/早退<30分钟):{len(handled_list)} 条")
|
||||
lines.append(f"非职能人员(不推送):{len(non_func_list)} 条")
|
||||
lines.append(f"待通知(职能人员):{len(func_list)} 条")
|
||||
lines.append(f"导出文件:{save_path}")
|
||||
lines.append(f"钉钉推送:{'已启用' if DINGTALK_PUSH_ENABLED else '未启用'}")
|
||||
lines.append("-" * 60)
|
||||
lines.append("【待通知明细(职能人员,需钉钉核实)】")
|
||||
if func_list:
|
||||
for i, it in enumerate(func_list, 1):
|
||||
lines.append(
|
||||
f"{i}. {it.get('STAFF_NAME','')}({it.get('base_code','')})"
|
||||
f" | {it.get('work_day','')} | 班次:{it.get('bc_name','')}"
|
||||
f" | 异常:{it.get('abnormal','')} | {it.get('abnormal_minute','')}分钟")
|
||||
else:
|
||||
lines.append(" 无")
|
||||
lines.append("【直接处理明细(轻微异常)】")
|
||||
if handled_list:
|
||||
for i, it in enumerate(handled_list, 1):
|
||||
lines.append(
|
||||
f"{i}. {it.get('STAFF_NAME','')}({it.get('base_code','')})"
|
||||
f" | {it.get('work_day','')} | 异常:{it.get('abnormal','')}"
|
||||
f" | {it.get('abnormal_minute','')}分钟")
|
||||
else:
|
||||
lines.append(" 无")
|
||||
lines.append("=" * 60)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def handle_attendance_abnormal(save_dir=None, month=None):
|
||||
save_dir = save_dir or SAVE_DIR
|
||||
|
||||
# 1. 会话:复用共享登录态,必要时补登
|
||||
session = build_hr_session()
|
||||
try:
|
||||
info = fetch_cur_user_info(session)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("cookies 已失效,自动补登")
|
||||
session, user_id, treecode = _relogin_get_user_info()
|
||||
info = {"userId": user_id, "rootId": treecode}
|
||||
user_id = info.get("userId", "")
|
||||
treecode = info.get("rootId", "")
|
||||
if not user_id or not treecode:
|
||||
raise RuntimeError(f"员工基础信息接口未返回 userId/rootId:{info}")
|
||||
logger.info("cookies 校验通过,user_id=%s,treecode=%s", user_id, treecode)
|
||||
|
||||
# 2. 查询范围:默认当月
|
||||
if month:
|
||||
begin = f"{month}-01"
|
||||
end = f"{month}-31"
|
||||
else:
|
||||
begin, end = current_month_range()
|
||||
logger.info("===== 查询考勤异常日期范围:%s ~ %s,调整状态:%s =====", begin, end, IS_ADJUSTED or "所有")
|
||||
|
||||
# 3. 拉取数据
|
||||
data = fetch_all_attendance_abnormal(session, user_id, treecode, begin, end, IS_ADJUSTED)
|
||||
if not data:
|
||||
logger.info("当月无考勤异常数据,跳过导出与推送")
|
||||
return None
|
||||
|
||||
# 4. 导出 Excel 底稿
|
||||
month_str = month or date.today().strftime("%Y-%m")
|
||||
path = export_excel(data, save_dir, month_str)
|
||||
|
||||
# 5. 分级分类
|
||||
push_list = [it for it in data if classify_abnormal(it)]
|
||||
handled_list = [it for it in data if not classify_abnormal(it)]
|
||||
func_list = [it for it in push_list if is_func_staff(it)]
|
||||
non_func_list = [it for it in push_list if not is_func_staff(it)]
|
||||
|
||||
# 6. 生成处理汇总报表(最终结果,推送前形成)
|
||||
report = generate_report(data, handled_list, func_list, non_func_list, path, begin, end)
|
||||
print("\n" + report + "\n")
|
||||
|
||||
# 7. 钉钉推送(总开关控制)
|
||||
push_count, fail_count = 0, 0
|
||||
if DINGTALK_PUSH_ENABLED:
|
||||
if func_list:
|
||||
push_count, fail_count = push_abnormal(func_list)
|
||||
else:
|
||||
logger.info("无需推送的异常,跳过当事人钉钉通知")
|
||||
logger.info("当事人推送完成:成功 %d 条,失败 %d 条", push_count, fail_count)
|
||||
push_report(report)
|
||||
else:
|
||||
logger.info("钉钉推送未启用(dingtalk_push_enabled!=true),仅生成报表,未发送任何钉钉消息")
|
||||
|
||||
# 8. 汇总日志
|
||||
logger.info("=" * 60)
|
||||
logger.info("【考勤异常处理汇总】")
|
||||
logger.info(" 考勤异常总数:%d 条", len(data))
|
||||
logger.info(" 直接处理(轻微,无需通知):%d 条", len(handled_list))
|
||||
logger.info(" 非职能人员(不推送):%d 条", len(non_func_list))
|
||||
logger.info(" 待通知(职能人员):%d 条,合并为 %d 条推送", len(func_list), push_count)
|
||||
logger.info(" 导出文件:%s", path)
|
||||
logger.info("=" * 60)
|
||||
return path
|
||||
|
||||
|
||||
def main(args=None):
|
||||
"""影刀「调用模块」入口;也可作为脚本直接运行。
|
||||
args: dict,可选字段 save_dir(导出目录)、month("YYYY-MM",默认当月)
|
||||
"""
|
||||
if args is None:
|
||||
args = {}
|
||||
# 始终定义影刀全局变量 messages(默认空列表),避免后续流程步骤引用时 NameError
|
||||
_set_glv('messages', [])
|
||||
save_dir = args.get("save_dir") or (sys.argv[1] if len(sys.argv) > 1 else None)
|
||||
month = args.get("month") or (sys.argv[2] if len(sys.argv) > 2 else None)
|
||||
try:
|
||||
out = handle_attendance_abnormal(save_dir, month)
|
||||
if out:
|
||||
logger.info("===== 考勤异常处理完成,导出:%s =====", out)
|
||||
else:
|
||||
logger.info("===== 考勤异常处理完成:当月无数据 =====")
|
||||
return {"success": True, "save_path": out}
|
||||
except Exception as e:
|
||||
if "正被占用" in str(e):
|
||||
logger.error("=========== 提醒 ===========")
|
||||
logger.error(str(e))
|
||||
logger.error("请关闭该 Excel 文件后重新运行即可,无需重查数据。")
|
||||
return {"success": False, "message": str(e)}
|
||||
logger.error("考勤异常处理失败:%s", e)
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,567 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: dingtalk_sender.py
|
||||
@Description: 钉钉推送自定义指令(影刀编码版 Python 模块源码,单一真源)。
|
||||
作为「37du钉钉推送」影刀自定义指令的模块源码,
|
||||
供所有需要钉钉推送的影刀脚本/流程复用(周考勤、请假审批、加班审批、人事变动等),
|
||||
避免每个脚本各自内联 OCR 视觉发送逻辑。
|
||||
|
||||
如何在影刀中创建指令:
|
||||
1. 影刀客户端 → 新建「PC自动化指令」→ 指令编码如 dingtalk_sender,添加 Python 模块;
|
||||
2. 把本文件内容粘贴进指令的 Python 模块(或直接以本文件作为模块源码);
|
||||
3. 增加流程参数 params(字典类型,dict),或分别增加 target/text/chat_type 三个参数;
|
||||
4. 保存并「发版」;在需要钉钉推送的应用中「获取指令」并安装;
|
||||
5. 在流程中拖入该指令,把业务脚本输出的参数传入(两种方式任选):
|
||||
方式A(推荐):流程中先拼一个字典变量(如 {"target": "张三", "text": "..."}),
|
||||
作为 params 整体传入;
|
||||
方式B:分别传 target、text 变量(chat_type 可选),指令内部自动拼成字典;
|
||||
指令返回 JSON:{"success": bool, "message": str},可在后续流程中判断是否重试。
|
||||
|
||||
推送原理(OCR 视觉方案,与 app/utils/dingtalk_sender.py 一致):
|
||||
查找钉钉窗口 → 多策略激活到前台 → Ctrl+Shift+F 搜索会话 → OCR 定位输入框
|
||||
→ 粘贴文本 → 回车发送。
|
||||
|
||||
依赖(影刀「Python包管理」安装;启动校验不懒加载):
|
||||
pip install pyautogui pywin32 pyperclip psutil
|
||||
pip install Pillow numpy rapidocr-onnxruntime
|
||||
|
||||
入口:
|
||||
main(args) 影刀自定义指令调用入口
|
||||
args = {
|
||||
"target": "联系人搜索关键字(支持工号,避免同名误选)",
|
||||
"text": "要发送的文本内容",
|
||||
"chat_type": "联系人|群组(可选,默认 联系人)",
|
||||
"display_name": "会话标题校验名(可选;钉钉标题显示姓名,target 用工号时传姓名校验)",
|
||||
}
|
||||
通过流程参数传入(支持整字典 params 或分别传 target/text/chat_type)
|
||||
返回 JSON 安全 dict:{"success": bool, "message": str}
|
||||
|
||||
python dingtalk_sender.py 目标 文本 独立运行(等价于 main({"target": ..., "text": ...}))
|
||||
"""
|
||||
import sys
|
||||
import time
|
||||
|
||||
# ==================== 第三方库导入(启动校验:全部必须预先安装,不懒加载) ====================
|
||||
try:
|
||||
import pyautogui
|
||||
import win32gui
|
||||
import win32con
|
||||
import win32api
|
||||
import win32process
|
||||
import pyperclip
|
||||
import psutil
|
||||
from PIL import Image, ImageGrab
|
||||
import numpy as np
|
||||
from rapidocr_onnxruntime import RapidOCR
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(钉钉推送指令要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install pyautogui pywin32 pyperclip psutil\n"
|
||||
" pip install Pillow numpy rapidocr-onnxruntime\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
|
||||
# ==================== 日志(print) ====================
|
||||
class _PrintLogger:
|
||||
"""影刀版无 logging 依赖,直接用 print 输出,行为与项目 logger 对齐。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[DEBUG] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[INFO] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[WARN] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[ERROR] {msg}")
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
# ==================== 钉钉 OCR 视觉推送(单一真源,与 app/utils/dingtalk_sender.py 一致) ====================
|
||||
_DT_TIMEOUT = 8
|
||||
_DT_SEARCH_RETRY = 3
|
||||
_DT_RETRY_TIMES = 3
|
||||
_DT_TOP_HEIGHT_RATIO = 0.18
|
||||
|
||||
|
||||
def _dt_get_ocr():
|
||||
"""获取 RapidOCR 实例(单例)。
|
||||
实例挂在函数自身属性上,避免依赖模块级可变全局变量:影刀指令运行环境对
|
||||
「模块级 global 变量」的作用域处理与标准 Python 不同(曾报
|
||||
name '_dt_ocr' is not defined),函数属性存放在函数对象自身,任何环境都可靠。
|
||||
"""
|
||||
inst = getattr(_dt_get_ocr, "_instance", None)
|
||||
if inst is None:
|
||||
inst = RapidOCR()
|
||||
_dt_get_ocr._instance = inst
|
||||
return inst
|
||||
|
||||
|
||||
def _dt_get_process_name_by_pid(pid):
|
||||
try:
|
||||
return psutil.Process(pid).name()
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _dt_find_dingtalk_window(include_hidden=True):
|
||||
"""查找钉钉主窗口句柄(排除 0 尺寸阴影/辅助窗口,只认 DingTalk 进程或主标题)。"""
|
||||
def has_valid_rect(hwnd):
|
||||
try:
|
||||
left, top, right, bottom = win32gui.GetWindowRect(hwnd)
|
||||
return (right - left) > 0 and (bottom - top) > 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def is_main_title(hwnd):
|
||||
return win32gui.GetWindowText(hwnd) in ('钉钉', 'DingTalk')
|
||||
|
||||
candidates = []
|
||||
|
||||
def enum_callback(hwnd, _):
|
||||
if not include_hidden and not win32gui.IsWindowVisible(hwnd):
|
||||
return True
|
||||
title = win32gui.GetWindowText(hwnd)
|
||||
if title == '钉钉' or title == 'DingTalk':
|
||||
candidates.append(hwnd)
|
||||
return True
|
||||
try:
|
||||
_, pid = win32process.GetWindowThreadProcessId(hwnd)
|
||||
proc_name = _dt_get_process_name_by_pid(pid)
|
||||
if proc_name and proc_name.lower() == 'dingtalk.exe':
|
||||
candidates.append(hwnd)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
|
||||
win32gui.EnumWindows(enum_callback, None)
|
||||
|
||||
valid = [h for h in candidates if has_valid_rect(h)]
|
||||
if not valid:
|
||||
return None
|
||||
for h in valid:
|
||||
if is_main_title(h) and win32gui.IsWindowVisible(h):
|
||||
return h
|
||||
for h in valid:
|
||||
if is_main_title(h):
|
||||
return h
|
||||
for h in valid:
|
||||
if win32gui.IsWindowVisible(h):
|
||||
return h
|
||||
return valid[0]
|
||||
|
||||
|
||||
def _dt_activate_window(hwnd):
|
||||
"""强制激活窗口(最小化、隐藏、托盘均可恢复)。"""
|
||||
if win32gui.IsIconic(hwnd):
|
||||
win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
|
||||
time.sleep(0.3)
|
||||
if not win32gui.IsWindowVisible(hwnd):
|
||||
win32gui.ShowWindow(hwnd, win32con.SW_SHOW)
|
||||
time.sleep(0.3)
|
||||
win32gui.SetForegroundWindow(hwnd)
|
||||
win32api.keybd_event(win32con.VK_MENU, 0, win32con.KEYEVENTF_KEYUP, 0)
|
||||
time.sleep(0.3)
|
||||
|
||||
|
||||
def _dt_get_window_rect(hwnd):
|
||||
return win32gui.GetWindowRect(hwnd)
|
||||
|
||||
|
||||
def _dt_is_dingtalk_main_visible():
|
||||
hwnd = _dt_find_dingtalk_window(include_hidden=True)
|
||||
return bool(hwnd) and win32gui.IsWindowVisible(hwnd)
|
||||
|
||||
|
||||
def _dt_is_dingtalk_foreground():
|
||||
fg = win32gui.GetForegroundWindow()
|
||||
if not fg:
|
||||
return False
|
||||
title = win32gui.GetWindowText(fg) or ""
|
||||
return '钉钉' in title or 'DingTalk' in title
|
||||
|
||||
|
||||
def _dt_capture_region(x, y, w, h):
|
||||
if w <= 0 or h <= 0:
|
||||
logger.warning("截图区域无效: (%s, %s, %s, %s),跳过", x, y, w, h)
|
||||
return None
|
||||
img = ImageGrab.grab(bbox=(x, y, x + w, y + h))
|
||||
if img is None or img.size[0] == 0 or img.size[1] == 0:
|
||||
logger.warning("抓取图像为空")
|
||||
return None
|
||||
return img
|
||||
|
||||
|
||||
def _dt_ocr_image(img):
|
||||
if img is None:
|
||||
return []
|
||||
img_np = np.array(img)
|
||||
result, _ = _dt_get_ocr()(img_np)
|
||||
ocr_data = []
|
||||
if result is not None:
|
||||
for box, text, score in result:
|
||||
xs = [p[0] for p in box]
|
||||
ys = [p[1] for p in box]
|
||||
x1, y1 = min(xs), min(ys)
|
||||
x2, y2 = max(xs), max(ys)
|
||||
ocr_data.append((text, (x1, y1, x2, y2)))
|
||||
return ocr_data
|
||||
|
||||
|
||||
def _dt_find_text_center(ocr_data, target_text):
|
||||
for text, (x1, y1, x2, y2) in ocr_data:
|
||||
if target_text in text:
|
||||
return (x1 + x2) // 2, (y1 + y2) // 2
|
||||
return None
|
||||
|
||||
|
||||
def _dt_wait_for_tab(hwnd, expected_tab, timeout=_DT_TIMEOUT):
|
||||
left, top, right, bottom = _dt_get_window_rect(hwnd)
|
||||
width = right - left
|
||||
height = bottom - top
|
||||
top_height = max(40, int(height * _DT_TOP_HEIGHT_RATIO))
|
||||
start = time.time()
|
||||
while time.time() - start < timeout:
|
||||
img = _dt_capture_region(left, top, width, top_height)
|
||||
ocr_data = _dt_ocr_image(img)
|
||||
if _dt_find_text_center(ocr_data, expected_tab):
|
||||
logger.info("检测到'%s'标签", expected_tab)
|
||||
return True
|
||||
time.sleep(0.5)
|
||||
logger.warning("未检测到'%s'标签", expected_tab)
|
||||
return False
|
||||
|
||||
|
||||
def _dt_is_chat_opened(hwnd, target_name):
|
||||
left, top, right, bottom = _dt_get_window_rect(hwnd)
|
||||
width = right - left
|
||||
height = bottom - top
|
||||
top_height = max(40, int(height * _DT_TOP_HEIGHT_RATIO))
|
||||
img = _dt_capture_region(left, top, width, top_height)
|
||||
ocr_data = _dt_ocr_image(img)
|
||||
for text, _ in ocr_data:
|
||||
if target_name in text:
|
||||
logger.debug("标题识别到: '%s'", text)
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _dt_search_and_open(hwnd, target_name, chat_type="联系人", verify_name=None):
|
||||
"""搜索并打开指定的联系人或群组会话。
|
||||
|
||||
target_name 为搜索关键字(支持工号,避免同名人员误选,如搜索 10086);
|
||||
verify_name 为打开会话后校验标题用的名称(钉钉会话标题显示的是联系人姓名
|
||||
而非工号,故同名人场景需传姓名用于校验;不传则回退为 target_name)。
|
||||
"""
|
||||
_dt_activate_window(hwnd)
|
||||
for attempt in range(_DT_SEARCH_RETRY):
|
||||
pyautogui.hotkey('ctrl', 'shift', 'f')
|
||||
time.sleep(0.8)
|
||||
pyautogui.hotkey('ctrl', 'a')
|
||||
pyautogui.press('delete')
|
||||
pyperclip.copy(target_name)
|
||||
pyautogui.hotkey('ctrl', 'v')
|
||||
time.sleep(0.5)
|
||||
pyautogui.press('enter')
|
||||
logger.info("搜索 '%s' (尝试 %d)", target_name, attempt + 1)
|
||||
time.sleep(0.8)
|
||||
if _dt_wait_for_tab(hwnd, chat_type, timeout=3):
|
||||
break
|
||||
else:
|
||||
pyautogui.press('esc')
|
||||
time.sleep(0.5)
|
||||
else:
|
||||
logger.error("搜索框未正常打开")
|
||||
return False
|
||||
|
||||
left, top, right, bottom = _dt_get_window_rect(hwnd)
|
||||
width = right - left
|
||||
height = bottom - top
|
||||
top_height = max(40, int(height * _DT_TOP_HEIGHT_RATIO))
|
||||
img = _dt_capture_region(left, top, width, top_height)
|
||||
ocr_data = _dt_ocr_image(img)
|
||||
pos = _dt_find_text_center(ocr_data, chat_type)
|
||||
if pos:
|
||||
cx, cy = pos
|
||||
pyautogui.click(left + cx, top + cy)
|
||||
logger.info("点击'%s'标签", chat_type)
|
||||
else:
|
||||
logger.warning("未识别'%s'标签", chat_type)
|
||||
time.sleep(0.5)
|
||||
|
||||
pyautogui.press('enter')
|
||||
logger.info("打开第一个匹配项")
|
||||
time.sleep(1.5)
|
||||
|
||||
start = time.time()
|
||||
while time.time() - start < _DT_TIMEOUT:
|
||||
if _dt_is_chat_opened(hwnd, verify_name or target_name):
|
||||
logger.info("成功进入会话 '%s'", verify_name or target_name)
|
||||
return True
|
||||
_dt_activate_window(hwnd)
|
||||
time.sleep(0.5)
|
||||
logger.warning("未检测到会话名 '%s'", verify_name or target_name)
|
||||
return False
|
||||
|
||||
|
||||
def _dt_find_input_box_by_ocr(hwnd):
|
||||
left, top, right, bottom = _dt_get_window_rect(hwnd)
|
||||
width = right - left
|
||||
height = bottom - top
|
||||
bottom_region_top = top + int(height * 0.6)
|
||||
bottom_region_height = int(height * 0.4)
|
||||
img = _dt_capture_region(left, bottom_region_top, width, bottom_region_height)
|
||||
ocr_data = _dt_ocr_image(img)
|
||||
keywords = ["请输入消息", "发送消息", "输入消息", "说点什么"]
|
||||
for keyword in keywords:
|
||||
pos = _dt_find_text_center(ocr_data, keyword)
|
||||
if pos:
|
||||
cx, cy = pos
|
||||
screen_x = left + cx
|
||||
screen_y = bottom_region_top + cy
|
||||
logger.info("定位输入框: '%s' 坐标 (%s, %s)", keyword, screen_x, screen_y)
|
||||
return screen_x, screen_y
|
||||
logger.warning("未识别到输入框提示")
|
||||
return None
|
||||
|
||||
|
||||
def _dt_focus_input_box(hwnd):
|
||||
input_pos = _dt_find_input_box_by_ocr(hwnd)
|
||||
if input_pos:
|
||||
pyautogui.click(input_pos[0], input_pos[1])
|
||||
return True
|
||||
left, top, right, bottom = _dt_get_window_rect(hwnd)
|
||||
width = right - left
|
||||
height = bottom - top
|
||||
pyautogui.click(left + width // 2, top + height - 60)
|
||||
logger.warning("使用固定坐标点击输入框")
|
||||
return False
|
||||
|
||||
|
||||
def _dt_send_hotkey_to_activate():
|
||||
logger.info("尝试快捷键 Ctrl+Alt+D 激活")
|
||||
pyautogui.hotkey('ctrl', 'alt', 'd')
|
||||
time.sleep(0.8)
|
||||
|
||||
|
||||
def _dt_is_dingtalk_activated(hwnd, target_name=None):
|
||||
try:
|
||||
left, top, right, bottom = _dt_get_window_rect(hwnd)
|
||||
width = right - left
|
||||
height = bottom - top
|
||||
if width <= 0 or height <= 0:
|
||||
return False
|
||||
top_height = max(50, int(height * 0.18))
|
||||
img = _dt_capture_region(left, top, width, top_height)
|
||||
if img is None:
|
||||
return False
|
||||
ocr_data = _dt_ocr_image(img)
|
||||
if target_name:
|
||||
for text, _ in ocr_data:
|
||||
if target_name in text:
|
||||
return True
|
||||
main_keywords = ["搜索或提问", "消息", "未读", "搜索", "提问"]
|
||||
for kw in main_keywords:
|
||||
for text, _ in ocr_data:
|
||||
if kw in text:
|
||||
return True
|
||||
return False
|
||||
except Exception as e:
|
||||
logger.warning("激活检测异常: %s", e)
|
||||
return False
|
||||
|
||||
|
||||
def _dt_ensure_activate_dingtalk(hwnd, target_name=None, timeout=10):
|
||||
"""多策略确保钉钉窗口激活到前台(快捷键→Win32 API→组合)。"""
|
||||
def wait_for_valid_rect(hwnd, max_wait=1.5):
|
||||
end = time.time() + max_wait
|
||||
while time.time() < end:
|
||||
left, top, right, bottom = _dt_get_window_rect(hwnd)
|
||||
if (right - left) > 0 and (bottom - top) > 0:
|
||||
return True
|
||||
time.sleep(0.2)
|
||||
return False
|
||||
|
||||
def find_current():
|
||||
return _dt_find_dingtalk_window(include_hidden=True) or hwnd
|
||||
|
||||
def verify(hwnd):
|
||||
start = time.time()
|
||||
while time.time() - start < timeout:
|
||||
if _dt_is_dingtalk_activated(hwnd, target_name=None):
|
||||
return True
|
||||
time.sleep(0.5)
|
||||
return False
|
||||
|
||||
if _dt_is_dingtalk_foreground():
|
||||
logger.info("钉钉已在最前,跳过激活")
|
||||
return True
|
||||
|
||||
if not _dt_is_dingtalk_main_visible():
|
||||
_dt_send_hotkey_to_activate()
|
||||
cur = find_current()
|
||||
if cur and wait_for_valid_rect(cur) and verify(cur):
|
||||
logger.info("快捷键激活成功")
|
||||
win32gui.SetForegroundWindow(cur)
|
||||
return True
|
||||
logger.warning("快捷键后窗口尺寸无效")
|
||||
else:
|
||||
logger.info("窗口已可见,跳过切换快捷键(避免将其隐藏)")
|
||||
|
||||
logger.info("尝试 Win32 API 激活")
|
||||
cur = find_current()
|
||||
if cur:
|
||||
_dt_activate_window(cur)
|
||||
if wait_for_valid_rect(cur) and verify(cur):
|
||||
logger.info("API激活成功")
|
||||
return True
|
||||
logger.warning("API后窗口尺寸无效")
|
||||
|
||||
logger.info("组合激活")
|
||||
if not _dt_is_dingtalk_main_visible():
|
||||
_dt_send_hotkey_to_activate()
|
||||
time.sleep(0.5)
|
||||
cur = find_current()
|
||||
if cur:
|
||||
_dt_activate_window(cur)
|
||||
time.sleep(1)
|
||||
if wait_for_valid_rect(cur) and verify(cur):
|
||||
logger.info("组合激活成功")
|
||||
return True
|
||||
|
||||
raise RuntimeError("所有激活策略失败")
|
||||
|
||||
|
||||
def _dt_find_hwnd_or_raise():
|
||||
hwnd = _dt_find_dingtalk_window(include_hidden=True)
|
||||
if not hwnd:
|
||||
dingtalk_running = any(p.name().lower() == 'dingtalk.exe' for p in psutil.process_iter())
|
||||
if not dingtalk_running:
|
||||
raise RuntimeError("钉钉进程未运行,请手动启动并登录")
|
||||
else:
|
||||
raise RuntimeError("找到进程但无窗口,请手动激活")
|
||||
return hwnd
|
||||
|
||||
|
||||
def _dt_send_text_to_person(name, text, chat_type="联系人", display_name=None):
|
||||
"""向指定联系人/群发送文本(OCR 视觉方案):查找窗口→多策略激活→搜索打开会话→定位输入框→粘贴发送。
|
||||
name 为搜索关键字(支持工号);display_name 为会话标题校验名(钉钉标题显示姓名,
|
||||
同名人时传姓名用于校验;不传则用 name 校验),二者分离避免同名误选。
|
||||
"""
|
||||
if not text or not text.strip():
|
||||
raise ValueError("text 不能为空")
|
||||
|
||||
for attempt in range(_DT_RETRY_TIMES):
|
||||
try:
|
||||
hwnd = _dt_find_hwnd_or_raise()
|
||||
_dt_ensure_activate_dingtalk(hwnd, target_name=None, timeout=10)
|
||||
hwnd = _dt_find_dingtalk_window(include_hidden=True) or hwnd
|
||||
|
||||
if not _dt_search_and_open(hwnd, name, chat_type, display_name):
|
||||
raise RuntimeError("打开%s会话失败" % chat_type)
|
||||
|
||||
_dt_focus_input_box(hwnd)
|
||||
time.sleep(0.3)
|
||||
|
||||
pyperclip.copy(text)
|
||||
pyautogui.hotkey('ctrl', 'v')
|
||||
time.sleep(0.2)
|
||||
pyautogui.press('enter')
|
||||
logger.info("发送成功:%s...", text[:30])
|
||||
return True
|
||||
|
||||
except RuntimeError as e:
|
||||
logger.error(str(e))
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error("第%d次尝试失败:%s", attempt + 1, e)
|
||||
time.sleep(2)
|
||||
|
||||
raise RuntimeError("重试 %d 次后失败" % _DT_RETRY_TIMES)
|
||||
|
||||
|
||||
def send_dingtalk_text(target, text, chat_type="联系人", display_name=None):
|
||||
"""推送文本到钉钉联系人/群(OCR 视觉方案)。供业务脚本 import 调用。
|
||||
target 为搜索关键字(支持工号);display_name 为会话标题校验名(可选,同名人传姓名)。
|
||||
"""
|
||||
return _dt_send_text_to_person(target, text, chat_type, display_name)
|
||||
|
||||
|
||||
# ==================== 影刀自定义指令入口 ====================
|
||||
def _send_one(msg):
|
||||
"""发送单条消息,返回 {success: bool, message: str}。msg 为 {target, text, chat_type?, display_name?} 字典。"""
|
||||
target = str((msg or {}).get("target", "") or "").strip()
|
||||
text = str((msg or {}).get("text", "") or "")
|
||||
chat_type = str((msg or {}).get("chat_type", "") or "联系人").strip() or "联系人"
|
||||
display_name = str((msg or {}).get("display_name", "") or "").strip() or None
|
||||
if not target:
|
||||
return {"success": False, "message": "参数 target 不能为空"}
|
||||
if not text.strip():
|
||||
return {"success": False, "message": "参数 text 不能为空"}
|
||||
try:
|
||||
send_dingtalk_text(target, text, chat_type, display_name)
|
||||
return {"success": True, "message": f"已向 {target} 发送成功"}
|
||||
except Exception as e:
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
|
||||
def main(args):
|
||||
"""
|
||||
影刀自定义指令「37du钉钉推送」调用入口。
|
||||
args: dict,通过流程变量传入(影刀变量支持传字典/列表):
|
||||
方式A(批量,推荐):args = {"messages": [{target, text, chat_type?}, ...]}
|
||||
messages 为「字典列表」,逐条发送并返回汇总结果;
|
||||
方式B(单条):args = {"params": {target, text, chat_type?}} 或
|
||||
{"target":..., "text":...};
|
||||
返回: dict
|
||||
单条: {success: bool, message: str}
|
||||
批量: {success: bool, message: str, sent: int, failed: int, results: [...]}
|
||||
"""
|
||||
if not args:
|
||||
args = {}
|
||||
# 兼容「整个字典作为 params 传入」的用法
|
||||
if isinstance(args.get("params"), dict):
|
||||
merged = dict(args)
|
||||
merged.update(args["params"])
|
||||
args = merged
|
||||
|
||||
# 批量:messages 为字典列表,逐条发送
|
||||
if isinstance(args.get("messages"), list):
|
||||
results = [_send_one(m) for m in args["messages"]]
|
||||
ok = sum(1 for r in results if r.get("success"))
|
||||
return {
|
||||
"success": ok == len(results),
|
||||
"message": f"共 {len(results)} 条,成功 {ok},失败 {len(results) - ok}",
|
||||
"sent": ok,
|
||||
"failed": len(results) - ok,
|
||||
"results": results,
|
||||
}
|
||||
|
||||
# 单条发送
|
||||
return _send_one(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 仅本地自测连通性。影刀中会直接调用 main(args) 并通过流程变量传参,不会走这里。
|
||||
# 批量测试:流程变量 messages = 字典列表,每条含 target/text,main 逐条发送并汇总。
|
||||
_messages = [{"target": "夏一平", "text": "【37du钉钉推送·测试1】你好,这是一条连通性测试消息。"},{"target": "夏一平", "text": "【37du钉钉推送·测试2】你好,这是第二条测试消息。"}]
|
||||
result = main({"messages": _messages})
|
||||
print("最终结果:", result)
|
||||
@@ -0,0 +1,448 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: hr_login.py
|
||||
@Description: HR 登录自定义指令(影刀编码版 Python 模块源码)。
|
||||
作为「37duHR登录」影刀自定义指令的模块源码(单一真源),
|
||||
供所有 HR 系统影刀脚本复用,避免每个脚本各自内联滑块登录逻辑。
|
||||
|
||||
如何在影刀中创建指令:
|
||||
1. 影刀客户端 → 新建「PC自动化指令」→ 指令编码如 hr_login,添加 Python 模块;
|
||||
2. 把本文件内容粘贴进指令的 Python 模块(或直接以本文件作为模块源码);
|
||||
3. 增加流程参数 force(可选,布尔,是否强制重新登录);
|
||||
4. 保存并「发版」;在需要登录的应用中「获取指令」并安装;
|
||||
5. 在每个应用的流程开头拖入该指令,即可保证后续业务脚本能读到有效 cookies。
|
||||
|
||||
约定(与项目 app 版一致,见 app/common/app_paths.py):
|
||||
- 配置:统一读取固定路径共享 .env:%LOCALAPPDATA%\\37duAutomation\\.env
|
||||
(本地开发时也兼容当前工作目录下的 .env);
|
||||
- 登录态:统一写入 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json,
|
||||
各影刀业务脚本自行用这些 cookies 构建 requests.Session。
|
||||
|
||||
环境变量(.env 或系统变量):
|
||||
hr_login_url=HR 登录页 URL
|
||||
hr_target_url_keyword=HR 登录成功后 URL 关键字
|
||||
hr_login_username=用户名
|
||||
hr_login_password=密码
|
||||
hr_validate_url=(可选)HR 会话校验接口 URL;默认使用 getCurUserInfo 接口
|
||||
hr_captcha_debug_dir=(可选)滑块调试图片输出目录;不设置则不落盘
|
||||
|
||||
全局变量(在影刀流程中创建,此指令负责写入):
|
||||
login_state 登录成功或缓存的 cookies 有效时写入 True,否则为 False
|
||||
|
||||
依赖(影刀「Python包管理」安装):
|
||||
pip install DrissionPage requests python-dotenv opencv-python numpy Pillow
|
||||
|
||||
入口:
|
||||
main(args) 影刀自定义指令调用入口,args 传 {"force": true|false},返回 JSON 安全 dict
|
||||
python hr_login.py 独立运行(等价于 main({"force": true}))
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import time
|
||||
import random
|
||||
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
# ================== 共享路径(与 app 版统一) ==================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
|
||||
|
||||
def _load_shared_env():
|
||||
"""统一加载配置:优先固定路径共享 .env,再兼容当前工作目录 .env 与系统变量。"""
|
||||
if os.path.exists(SHARED_ENV_FILE):
|
||||
load_dotenv(SHARED_ENV_FILE)
|
||||
load_dotenv()
|
||||
|
||||
|
||||
# ================== 配置 ==================
|
||||
# 注意:必须在读取环境变量前先加载 .env,否则 import 时这些值会被捕获为 None
|
||||
_load_shared_env()
|
||||
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')
|
||||
|
||||
# HR 会话校验接口:cookies 有效时返回 JSON,失效时返回登录页等非 JSON
|
||||
GET_CUR_USER_INFO_URL = "https://hr.37du.co/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
|
||||
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"
|
||||
|
||||
RETRY_MAX = 5
|
||||
TIMEOUT = 10
|
||||
HEADLESS = False
|
||||
|
||||
|
||||
def ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
# ================== Cookies 持久化(登录成功后缓存,下次免登录复用) ==================
|
||||
def save_browser_cookies(page):
|
||||
cookies = page.cookies(all_domains=True)
|
||||
if not cookies:
|
||||
print("未获取到 Cookies,跳过保存")
|
||||
return
|
||||
ensure_dir(_SESSIONS_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():
|
||||
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 _set_login_state(value):
|
||||
"""写入影刀全局变量 login_state(影刀指令环境可用;独立运行/非影刀环境时静默跳过)。"""
|
||||
try:
|
||||
glv['login_state'] = value
|
||||
print(f"已写入影刀全局变量 login_state={value}")
|
||||
except Exception as e:
|
||||
print(f"写入影刀全局变量 login_state 失败(非影刀环境?):{e}")
|
||||
|
||||
|
||||
# ================== API 校验 cookies 有效性(无需打开浏览器) ==================
|
||||
def _is_hr_session_valid():
|
||||
"""API 轻量校验 HR cookies:请求 hr_validate_url(默认 getCurUserInfo 接口),
|
||||
返回 JSON 视为 cookies 有效;返回登录页等非 JSON 即视为失效。
|
||||
|
||||
与业务脚本(attendance_abnormal/bank_card_check 等)使用同一套构建方式:
|
||||
requests.Session + Chrome UA/Content-Type + 仅注入 37du.co 域 cookies。
|
||||
"""
|
||||
validate_url = os.getenv('hr_validate_url', '').strip() or GET_CUR_USER_INFO_URL
|
||||
try:
|
||||
cookies = load_cookies()
|
||||
if not cookies:
|
||||
return False
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
resp = session.post(validate_url, data={}, timeout=15)
|
||||
if resp.status_code != 200:
|
||||
print(f"API 校验 cookies 状态码异常:{resp.status_code}")
|
||||
return False
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception as e:
|
||||
print(f"API 校验 cookies 异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 滑块匹配(与已验证可用的 bank_card/roster 内联版一致) ==================
|
||||
def match_slider_dual(bg_bytes, slider_bytes):
|
||||
"""模板匹配滑块缺口,返回物理距离(px)。"""
|
||||
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:
|
||||
print(f"拖拽异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 验证码处理(与已验证可用的 bank_card/roster 内联版一致) ==================
|
||||
def handle_captcha(page):
|
||||
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) or container.ele('div[style*="background-image"]')
|
||||
slider_ele = container.ele(SLIDER_IMG)
|
||||
if not bg_ele or not slider_ele:
|
||||
print("找不到背景图/滑块小图元素")
|
||||
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
|
||||
|
||||
if not bg_screenshot or not slider_screenshot:
|
||||
print("截图数据为空")
|
||||
continue
|
||||
|
||||
distance_phys = match_slider_dual(bg_screenshot, slider_screenshot)
|
||||
dpr = page.run_js('return window.devicePixelRatio') or 1
|
||||
distance_css = distance_phys / dpr
|
||||
print(f" 匹配距离 {distance_phys}px -> CSS {distance_css:.1f}px")
|
||||
|
||||
btn = page.ele(SLIDER_BTN)
|
||||
if btn and 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
|
||||
time.sleep(2)
|
||||
except Exception as e:
|
||||
print(f"异常:{e}")
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
# ================== 登录主流程 ==================
|
||||
def _do_login():
|
||||
"""打开浏览器完成登录(含滑块),成功保存 cookies。"""
|
||||
co = ChromiumOptions()
|
||||
if HEADLESS:
|
||||
co.headless()
|
||||
page = ChromiumPage(co)
|
||||
try:
|
||||
page.get(LOGIN_URL)
|
||||
time.sleep(2)
|
||||
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
print("已登录")
|
||||
save_browser_cookies(page)
|
||||
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
|
||||
print("登录失败")
|
||||
return False
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def ensure_login(force=False):
|
||||
"""
|
||||
确保存在有效的 HR 登录态并缓存 cookies。
|
||||
返回 JSON 安全 dict:{success, cookie_path, message, relogin}
|
||||
"""
|
||||
_load_shared_env()
|
||||
# 默认未登录;登录成功或复用有效 cookies 后再置 True
|
||||
_set_login_state(False)
|
||||
|
||||
if not (LOGIN_URL and SUCCESS_KEYWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "未配置 hr_login_url / hr_target_url_keyword 环境变量", "relogin": False}
|
||||
if not (USERNAME and PASSWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "未配置 hr_login_username / hr_login_password 环境变量", "relogin": False}
|
||||
|
||||
# 优先复用已保存的 cookies(通过 API 校验有效性,无需打开浏览器)
|
||||
if not force and _is_hr_session_valid():
|
||||
print("已通过缓存的 Cookies 复用 HR 登录态")
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE,
|
||||
"message": "复用缓存登录态", "relogin": False}
|
||||
|
||||
ok = _do_login()
|
||||
if ok:
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE, "message": "登录成功", "relogin": True}
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录失败(滑块验证未通过)", "relogin": False}
|
||||
|
||||
|
||||
# ================== 影刀自定义指令入口 ==================
|
||||
def main(args):
|
||||
"""
|
||||
影刀自定义指令「37duHR登录」调用入口。
|
||||
args: dict,可选字段 force(bool) 是否强制重新登录
|
||||
返回: dict {success, cookie_path, message, relogin}
|
||||
"""
|
||||
if not args:
|
||||
args = {}
|
||||
force = bool(args.get("force", False))
|
||||
try:
|
||||
return ensure_login(force=force)
|
||||
except Exception as e:
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": f"登录过程异常:{e}", "relogin": False}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
result = main({"force": False})
|
||||
print("最终结果:", result)
|
||||
@@ -0,0 +1,196 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: oa_login.py
|
||||
@Description: OA 登录自定义指令(影刀编码版 Python 模块源码)。
|
||||
作为「37duOA登录」影刀自定义指令的模块源码(单一真源),
|
||||
供所有 OA 系统影刀脚本(请假/加班/社保增减等)复用。
|
||||
|
||||
如何在影刀中创建指令:
|
||||
1. 影刀客户端 → 新建「PC自动化指令」→ 指令编码如 oa_login,添加 Python 模块;
|
||||
2. 把本文件内容粘贴进指令的 Python 模块(或直接以本文件作为模块源码);
|
||||
3. 增加流程参数 force(可选,布尔,是否强制重新登录);
|
||||
4. 保存并「发版」;在需要登录的应用中「获取指令」并安装;
|
||||
5. 在每个应用的流程开头拖入该指令,即可保证后续业务脚本能读到有效 cookies。
|
||||
|
||||
约定(与项目 app 版一致,见 app/common/app_paths.py):
|
||||
- 配置:统一读取固定路径共享 .env:%LOCALAPPDATA%\\37duAutomation\\.env
|
||||
(本地开发时也兼容当前工作目录下的 .env);
|
||||
- 登录态:统一写入 %LOCALAPPDATA%\\37duAutomation\\.sessions\\oa_cookies.json,
|
||||
各影刀业务脚本自行用这些 cookies 构建 SessionPage / requests.Session。
|
||||
|
||||
环境变量(.env 或系统变量):
|
||||
oa_login_url=OA 登录页 URL
|
||||
oa_target_url_keyword=OA 登录成功后 URL 关键字
|
||||
oa_login_username=用户名
|
||||
oa_login_password=密码
|
||||
oa_validate_url=(可选)轻量会话校验接口 URL;不配置则仅以 cookies 存在作为复用依据
|
||||
|
||||
依赖(影刀「Python包管理」安装):
|
||||
pip install DrissionPage python-dotenv
|
||||
|
||||
入口:
|
||||
main(args) 影刀自定义指令调用入口,args 传 {"force": true|false},返回 JSON 安全 dict
|
||||
python oa_login.py 独立运行(等价于 main({"force": true}))
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import time
|
||||
|
||||
from DrissionPage import ChromiumPage, SessionPage
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# ================== 共享路径(与 app 版统一) ==================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
|
||||
|
||||
def _load_shared_env():
|
||||
"""统一加载配置:优先固定路径共享 .env,再兼容当前工作目录 .env 与系统变量。"""
|
||||
if os.path.exists(SHARED_ENV_FILE):
|
||||
load_dotenv(SHARED_ENV_FILE)
|
||||
load_dotenv()
|
||||
|
||||
|
||||
# ================== Cookies 持久化 ==================
|
||||
def save_browser_cookies(page):
|
||||
cookies = page.cookies(all_domains=True)
|
||||
if not cookies:
|
||||
print("未获取到 Cookies,跳过保存")
|
||||
return
|
||||
os.makedirs(_SESSIONS_DIR, exist_ok=True)
|
||||
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():
|
||||
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 _is_oa_session_valid():
|
||||
"""轻量校验 OA 会话:请求 oa_validate_url,返回 JSON 视为有效。未配置则默认有效。"""
|
||||
validate_url = os.getenv('oa_validate_url', '').strip()
|
||||
if not validate_url:
|
||||
return True
|
||||
try:
|
||||
session = SessionPage()
|
||||
cookies = load_cookies()
|
||||
if cookies:
|
||||
session.set.cookies(cookies)
|
||||
session.set.timeout(10)
|
||||
session.get(validate_url)
|
||||
resp = session.response
|
||||
if resp is None or resp.status_code != 200:
|
||||
return False
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
# ================== 登录主流程 ==================
|
||||
def _do_login(username=None, password=None, timeout=10, wait_after_load=2):
|
||||
"""打开浏览器完成 OA 账号密码登录,成功保存 cookies。"""
|
||||
login_url = os.getenv('oa_login_url')
|
||||
if not login_url:
|
||||
raise RuntimeError("环境变量 oa_login_url 未设置")
|
||||
target_url_keyword = os.getenv('oa_target_url_keyword')
|
||||
if not target_url_keyword:
|
||||
raise RuntimeError("环境变量 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:
|
||||
print(f"登录成功!当前 URL: {page.url}")
|
||||
save_browser_cookies(page)
|
||||
return True
|
||||
time.sleep(0.5)
|
||||
|
||||
error_elem = page.ele('.error-msg') or page.ele('.alert-danger')
|
||||
if error_elem:
|
||||
print(f"登录失败,提示: {error_elem.text}")
|
||||
raise RuntimeError(f"登录超时,当前 URL: {page.url}")
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def ensure_login(force=False, username=None, password=None):
|
||||
"""
|
||||
确保存在有效的 OA 登录态并缓存 cookies。
|
||||
返回 JSON 安全 dict:{success, cookie_path, message, relogin}
|
||||
"""
|
||||
_load_shared_env()
|
||||
|
||||
if not os.getenv('oa_login_url'):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "未配置 oa_login_url 环境变量", "relogin": False}
|
||||
|
||||
if not force:
|
||||
if load_cookies() and _is_oa_session_valid():
|
||||
print("已通过缓存的 Cookies 复用 OA 登录态")
|
||||
return {"success": True, "cookie_path": COOKIE_FILE,
|
||||
"message": "复用缓存登录态", "relogin": False}
|
||||
|
||||
try:
|
||||
_do_login(username=username, password=password)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE, "message": "登录成功", "relogin": True}
|
||||
except Exception as e:
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": f"登录失败:{e}", "relogin": False}
|
||||
|
||||
|
||||
# ================== 影刀自定义指令入口 ==================
|
||||
def main(args):
|
||||
"""
|
||||
影刀自定义指令「37duOA登录」调用入口。
|
||||
args: dict,可选字段 force(bool) 是否强制重新登录
|
||||
返回: dict {success, cookie_path, message, relogin}
|
||||
"""
|
||||
if not args:
|
||||
args = {}
|
||||
force = bool(args.get("force", False))
|
||||
return ensure_login(force=force)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
result = main({"force": True})
|
||||
print("最终结果:", result)
|
||||
+466
-254
@@ -7,7 +7,7 @@
|
||||
@Version: 2.0.0
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install DrissionPage python-dotenv pyautogui pywin32 pyperclip Pillow numpy rapidocr-onnxruntime
|
||||
pip install DrissionPage python-dotenv pyautogui pywin32 pyperclip Pillow numpy rapidocr-onnxruntime psutil
|
||||
|
||||
环境变量(.env 文件或系统变量):
|
||||
oa_login_url=登录页URL
|
||||
@@ -26,9 +26,8 @@ import os
|
||||
import random
|
||||
import re
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any, Callable, Dict, List, Tuple
|
||||
from typing import Callable
|
||||
from urllib.parse import urlencode, urlparse, parse_qs
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||
@@ -40,8 +39,11 @@ try:
|
||||
import win32gui
|
||||
import win32con
|
||||
import win32clipboard
|
||||
import win32process
|
||||
import win32api
|
||||
import pyperclip
|
||||
from PIL import Image, ImageEnhance
|
||||
import psutil
|
||||
from PIL import Image, ImageEnhance, ImageGrab
|
||||
import numpy as np
|
||||
from rapidocr_onnxruntime import RapidOCR
|
||||
except ImportError as _import_err:
|
||||
@@ -49,7 +51,7 @@ except ImportError as _import_err:
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install DrissionPage python-dotenv pyautogui pywin32 pyperclip "
|
||||
"Pillow numpy rapidocr-onnxruntime\n"
|
||||
"Pillow numpy rapidocr-onnxruntime psutil\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
@@ -73,8 +75,9 @@ TODO_COUNT_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyTodo.do"
|
||||
FD_TYPE = "13"
|
||||
WF_ACTIVITY_URL = f"{HR_BASE_URL}/RedseaPlatform/WfActivity.mc"
|
||||
WORKFORM_ENGINE_URL = f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc"
|
||||
PAIBAN_URL = f"{HR_BASE_URL}/RedseaPlatform/KqCount.mc"
|
||||
KQ_DATA_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_data_queryByStaffId_all/getExecuteResult.mc"
|
||||
# 考勤逐日接口(按员工+日期范围返回每日班次名/班次起止/上下班打卡,data 数组)
|
||||
# 请假/加班校验统一使用该接口获取排班信息,替代原排班日历接口与打卡流水接口
|
||||
ATTENDANCE_DAILY_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_count_leave_yc_day_all/redApiExec.mc"
|
||||
LEAVE_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_leave_record_SelectByStaffID/redApiExec.mc"
|
||||
|
||||
# ---------- 分页 ----------
|
||||
@@ -342,6 +345,13 @@ def parse_todo_list(data):
|
||||
if detail_url and not detail_url.startswith(("http://", "https://")):
|
||||
detail_url = BASE_URL + detail_url
|
||||
|
||||
# 跳过"工作沟通/协作"类待办(如"请回复…与您的工作沟通:请假申请"):
|
||||
# 链接指向协作模块 kmCollaborateMain.do,非审批工作流,SSO 后仅到
|
||||
# unifyWorkFlow.jsp?fkId=… 拿不到 businessKey,永远无法解析,直接跳过避免无谓重试
|
||||
if "kmCollaborateMain.do" in detail_url:
|
||||
logger.warning("跳过非审批待办(工作沟通/协作): %s", title)
|
||||
continue
|
||||
|
||||
docs.append({"title": title, "creator": creator, "time": time_str, "detail_url": detail_url})
|
||||
return docs
|
||||
|
||||
@@ -450,59 +460,43 @@ def get_business_data(session, business_key, form_id):
|
||||
return result
|
||||
|
||||
|
||||
def get_attendance_html(session, staff_id, year, month):
|
||||
url = f"{PAIBAN_URL}?method=geRenPaibanByMonth"
|
||||
data = {"type": "2", "staffId": staff_id, "year": str(year), "month": str(month)}
|
||||
logger.info("获取排班: %s %d-%02d", staff_id, year, month)
|
||||
def get_attendance_daily(session, staff_id, start_date, end_date):
|
||||
"""按员工+日期范围查询每日考勤(含班次名/班次起止时间/上下班打卡)。
|
||||
|
||||
session.post(url, data=data)
|
||||
resp = session.response
|
||||
if not resp:
|
||||
raise RuntimeError("排班请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"排班接口状态码异常: {resp.status_code}")
|
||||
接口: rf_s_kq_count_leave_yc_day_all/redApiExec.mc
|
||||
kq_status_total 按考勤状态分类返回记录(来源为前端 JS 扒取的请求构造):
|
||||
- 0=休息日、1=正常班、9=未打卡、11=异常(如上班漏打卡)
|
||||
因此需按这四种状态各查一次,再按 work_day 合并去重,才能同时拿到
|
||||
班次名/班次时段与休息日、异常班当天的上下班打卡。
|
||||
"""
|
||||
by_day = {}
|
||||
for status in ("0", "1", "9", "11"):
|
||||
params = {
|
||||
"staff_id": staff_id,
|
||||
"begin_date": start_date,
|
||||
"end_date": end_date,
|
||||
"kq_status_total": status,
|
||||
}
|
||||
logger.info("获取考勤逐日(kq_status_total=%s): staff_id=%s, %s 至 %s",
|
||||
status, staff_id, start_date, end_date)
|
||||
|
||||
try:
|
||||
json_data = resp.json()
|
||||
except Exception:
|
||||
raise RuntimeError("排班接口返回非 JSON 数据")
|
||||
session.post(ATTENDANCE_DAILY_URL, data=params)
|
||||
resp = session.response
|
||||
if not resp:
|
||||
raise RuntimeError("考勤逐日请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"考勤逐日接口状态码异常: {resp.status_code}")
|
||||
|
||||
if json_data.get("success") != "true":
|
||||
raise RuntimeError(f"排班接口返回失败: {json_data}")
|
||||
try:
|
||||
json_data = resp.json()
|
||||
except Exception:
|
||||
body = (resp.text or "")[:200]
|
||||
raise RuntimeError(f"考勤逐日接口返回非 JSON 数据: {body}")
|
||||
|
||||
html = json_data.get("caleHtml")
|
||||
if not html:
|
||||
raise RuntimeError("排班接口未返回 caleHtml 字段")
|
||||
return html
|
||||
|
||||
|
||||
def get_attendance_records(session, staff_id, start_date, end_date):
|
||||
params = {
|
||||
"staff_id": staff_id,
|
||||
"rootId": "",
|
||||
"countId": "",
|
||||
"bc_date": start_date,
|
||||
"bc_date_end": end_date,
|
||||
"begin": start_date,
|
||||
"end": end_date,
|
||||
}
|
||||
logger.info("获取打卡明细: staff_id=%s, %s 至 %s", staff_id, start_date, end_date)
|
||||
|
||||
session.get(KQ_DATA_URL, params=params)
|
||||
resp = session.response
|
||||
if not resp:
|
||||
raise RuntimeError("考勤打卡请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"考勤打卡接口状态码异常: {resp.status_code}")
|
||||
|
||||
try:
|
||||
json_data = resp.json()
|
||||
except Exception:
|
||||
body = (resp.text or "")[:200]
|
||||
raise RuntimeError(f"考勤打卡接口返回非 JSON 数据: {body}")
|
||||
|
||||
records = json_data.get("jsonList", [])
|
||||
logger.info("打卡明细返回 %d 条", len(records))
|
||||
for r in json_data.get("data", []) or []:
|
||||
by_day.setdefault(str(r.get("work_day", "")), r)
|
||||
records = [by_day[k] for k in sorted(by_day)]
|
||||
logger.info("考勤逐日合并返回 %d 天", len(records))
|
||||
return records
|
||||
|
||||
|
||||
@@ -561,92 +555,6 @@ def get_leave_records(session, staff_id, begin_date, end_date, page_size=DEFAULT
|
||||
return all_records
|
||||
|
||||
|
||||
# ==================== 排班/打卡解析 ====================
|
||||
def parse_attendance_html(html):
|
||||
"""
|
||||
解析排班日历 HTML,返回 {日期: 班次} 字典。
|
||||
|
||||
实际 HTML 结构(属性用单引号):
|
||||
<a class='cale_a' title='经营正班A' short_bc_name='经营A'
|
||||
data-temp='2026-08-03' finalState='' onclick="...">正常</a>
|
||||
|
||||
- data-temp: 日期
|
||||
- title: 班次全称(如 经营正班A、职能正班A、休息)
|
||||
- 文本内容: 考勤状态(如 正常、异常、休息)
|
||||
"""
|
||||
if not html:
|
||||
return {}
|
||||
|
||||
result = {}
|
||||
a_tag_pattern = r"""<a\b[^>]*\bdata-temp=['"]([^'"]+)['"][^>]*>([^<]*)</a>"""
|
||||
|
||||
for match in re.finditer(a_tag_pattern, html, re.DOTALL):
|
||||
date_str = match.group(1).strip()
|
||||
text_content = match.group(2).strip()
|
||||
|
||||
# 从完整标签中提取 title 属性(班次名称),兼容单/双引号
|
||||
full_tag = match.group(0)
|
||||
title_match = re.search(r"""\btitle=['"]([^'"]*)['"]""", full_tag)
|
||||
shift_name = title_match.group(1).strip() if title_match else ""
|
||||
|
||||
# 优先使用 title(班次名称),休息日 title='休息'
|
||||
if shift_name:
|
||||
if text_content and text_content == "异常":
|
||||
result[date_str] = f"{shift_name}(异常)"
|
||||
else:
|
||||
result[date_str] = shift_name
|
||||
else:
|
||||
result[date_str] = text_content
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def get_work_days_in_range(attendance_dict, start_date, end_date):
|
||||
start = datetime.strptime(start_date, "%Y-%m-%d")
|
||||
end = datetime.strptime(end_date, "%Y-%m-%d")
|
||||
work_days = []
|
||||
current = start
|
||||
while current <= end:
|
||||
date_str = current.strftime("%Y-%m-%d")
|
||||
shift = attendance_dict.get(date_str, "")
|
||||
if shift != "休息" and shift != "":
|
||||
work_days.append(date_str)
|
||||
current += timedelta(days=1)
|
||||
return work_days
|
||||
|
||||
|
||||
def summarize_attendance_records(records):
|
||||
time_format = "%Y-%m-%d %H:%M:%S"
|
||||
group_map = defaultdict(list)
|
||||
|
||||
for item in records:
|
||||
staff_id = item.get("staff_id", "")
|
||||
bc_day = item.get("bc_date", "")
|
||||
if not staff_id or not bc_day:
|
||||
continue
|
||||
try:
|
||||
kq_dt = datetime.strptime(item["kq_time"], time_format)
|
||||
except (KeyError, ValueError):
|
||||
continue
|
||||
group_map[(staff_id, bc_day)].append({**item, "_dt": kq_dt})
|
||||
|
||||
summary = []
|
||||
for (sid, day), items in group_map.items():
|
||||
items.sort(key=lambda x: x["_dt"])
|
||||
base = items[0]
|
||||
row = {
|
||||
"staff_id": sid,
|
||||
"staff_name": base.get("staff_name", ""),
|
||||
"dept_name": base.get("DEPT_ORG_NAME", ""),
|
||||
"post_name": base.get("POST_ALIAS_NAME", ""),
|
||||
"attend_date": day,
|
||||
"first_check_in": items[0]["kq_time"],
|
||||
"last_check_out": items[-1]["kq_time"] if len(items) > 1 else None,
|
||||
}
|
||||
summary.append(row)
|
||||
return summary
|
||||
|
||||
|
||||
# ==================== 请假表单解析 ====================
|
||||
VACATION_TYPE_MAP = {
|
||||
"04": "病假",
|
||||
@@ -1027,109 +935,419 @@ def show_rpa_result_popup(page: ChromiumPage,
|
||||
|
||||
|
||||
|
||||
# ==================== 钉钉推送(内联精简版,保持单文件自包含) ====================
|
||||
DINGTALK_WINDOW_KEYWORD = "钉钉"
|
||||
# ==================== 钉钉推送(OCR 视觉方案内联,保持单文件自包含) ====================
|
||||
# 内联自 app/utils/dingtalk_sender.py(视觉方案),相比旧固定坐标模拟大幅提升稳定性:
|
||||
# 窗口查找排除 0 尺寸阴影/辅助窗口,只认主窗口;多策略激活(快捷键→Win32 API→组合);
|
||||
# 搜索框/标签/输入框全部通过 OCR 校验后再操作。
|
||||
_DT_TIMEOUT = 8
|
||||
_DT_SEARCH_RETRY = 3
|
||||
_DT_RETRY_TIMES = 3
|
||||
_DT_TOP_HEIGHT_RATIO = 0.18
|
||||
|
||||
_dt_ocr = None
|
||||
|
||||
|
||||
def _find_dingtalk_hwnd():
|
||||
"""用 win32gui.EnumWindows 按标题查找钉钉主窗口句柄。"""
|
||||
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 _dt_get_ocr():
|
||||
"""获取 RapidOCR 实例(单例;若模块已初始化 _ocr_engine 则复用,避免重复加载模型)。"""
|
||||
global _dt_ocr
|
||||
# 用 globals().get 而非直接读 _dt_ocr:避免个别运行环境/旧 pyc 下模块级 _dt_ocr 未定义时抛 NameError
|
||||
_dt_ocr = globals().get("_dt_ocr")
|
||||
if _dt_ocr is None:
|
||||
_dt_ocr = globals().get("_ocr_engine") or RapidOCR()
|
||||
return _dt_ocr
|
||||
|
||||
|
||||
def _is_dingtalk_foreground():
|
||||
title = win32gui.GetWindowText(win32gui.GetForegroundWindow())
|
||||
return DINGTALK_WINDOW_KEYWORD in title
|
||||
|
||||
|
||||
def _activate_dingtalk():
|
||||
"""激活钉钉窗口:Ctrl+D 唤起托盘中的钉钉 -> win32 置前 -> 点击确保焦点。"""
|
||||
if _is_dingtalk_foreground():
|
||||
logger.info("钉钉窗口已在前台,跳过激活")
|
||||
return
|
||||
|
||||
# 先尝试找到已打开的钉钉窗口
|
||||
hwnd = None
|
||||
def _dt_get_process_name_by_pid(pid):
|
||||
"""根据进程 ID 获取进程名称,失败返回 None"""
|
||||
try:
|
||||
hwnd = _find_dingtalk_hwnd()
|
||||
except RuntimeError:
|
||||
pass
|
||||
return psutil.Process(pid).name()
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
if hwnd is None:
|
||||
# 钉钉在系统托盘,用 Ctrl+D 全局热键唤起
|
||||
pyautogui.hotkey("ctrl", "d")
|
||||
time.sleep(1.5)
|
||||
|
||||
def _dt_find_dingtalk_window(include_hidden=True):
|
||||
"""查找钉钉“主窗口”句柄(排除 0 尺寸阴影/辅助窗口,只认 DingTalk 进程或主标题)。"""
|
||||
def has_valid_rect(hwnd):
|
||||
try:
|
||||
hwnd = _find_dingtalk_hwnd()
|
||||
except RuntimeError:
|
||||
raise RuntimeError("Ctrl+D 未能唤起钉钉窗口,请确认钉钉已启动并配置了 Ctrl+D 热键")
|
||||
left, top, right, bottom = win32gui.GetWindowRect(hwnd)
|
||||
return (right - left) > 0 and (bottom - top) > 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
# win32 置前台
|
||||
def is_main_title(hwnd):
|
||||
return win32gui.GetWindowText(hwnd) in ('钉钉', 'DingTalk')
|
||||
|
||||
candidates = []
|
||||
def enum_callback(hwnd, _):
|
||||
if not include_hidden and not win32gui.IsWindowVisible(hwnd):
|
||||
return True
|
||||
title = win32gui.GetWindowText(hwnd)
|
||||
if title == '钉钉' or title == 'DingTalk':
|
||||
candidates.append(hwnd)
|
||||
return True
|
||||
try:
|
||||
_, pid = win32process.GetWindowThreadProcessId(hwnd)
|
||||
proc_name = _dt_get_process_name_by_pid(pid)
|
||||
if proc_name and proc_name.lower() == 'dingtalk.exe':
|
||||
candidates.append(hwnd)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
win32gui.EnumWindows(enum_callback, None)
|
||||
|
||||
valid = [h for h in candidates if has_valid_rect(h)]
|
||||
if not valid:
|
||||
return None
|
||||
for h in valid:
|
||||
if is_main_title(h) and win32gui.IsWindowVisible(h):
|
||||
return h
|
||||
for h in valid:
|
||||
if is_main_title(h):
|
||||
return h
|
||||
for h in valid:
|
||||
if win32gui.IsWindowVisible(h):
|
||||
return h
|
||||
return valid[0]
|
||||
|
||||
|
||||
def _dt_activate_window(hwnd):
|
||||
"""强制激活窗口(最小化、隐藏、托盘均可恢复)"""
|
||||
if win32gui.IsIconic(hwnd):
|
||||
win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
|
||||
time.sleep(0.3)
|
||||
pyautogui.press("alt")
|
||||
if not win32gui.IsWindowVisible(hwnd):
|
||||
win32gui.ShowWindow(hwnd, win32con.SW_SHOW)
|
||||
time.sleep(0.3)
|
||||
win32gui.SetForegroundWindow(hwnd)
|
||||
time.sleep(1.0)
|
||||
win32api.keybd_event(win32con.VK_MENU, 0, win32con.KEYEVENTF_KEYUP, 0)
|
||||
time.sleep(0.3)
|
||||
|
||||
# 点击窗口中心确保键盘焦点落在钉钉上(SetForegroundWindow 只切前台,不保证键盘焦点)
|
||||
rect = win32gui.GetWindowRect(hwnd)
|
||||
cx = (rect[0] + rect[2]) // 2
|
||||
cy = (rect[1] + rect[3]) // 2
|
||||
pyautogui.click(cx, cy)
|
||||
|
||||
def _dt_get_window_rect(hwnd):
|
||||
"""获取窗口矩形 (left, top, right, bottom)"""
|
||||
return win32gui.GetWindowRect(hwnd)
|
||||
|
||||
|
||||
def _dt_is_dingtalk_main_visible():
|
||||
"""钉钉主窗口当前是否可见"""
|
||||
hwnd = _dt_find_dingtalk_window(include_hidden=True)
|
||||
return bool(hwnd) and win32gui.IsWindowVisible(hwnd)
|
||||
|
||||
|
||||
def _dt_is_dingtalk_foreground():
|
||||
"""钉钉主窗口是否已处于最前"""
|
||||
fg = win32gui.GetForegroundWindow()
|
||||
if not fg:
|
||||
return False
|
||||
title = win32gui.GetWindowText(fg) or ""
|
||||
return '钉钉' in title or 'DingTalk' in title
|
||||
|
||||
|
||||
def _dt_capture_region(x, y, w, h):
|
||||
"""截取屏幕指定区域,若区域无效则返回 None"""
|
||||
if w <= 0 or h <= 0:
|
||||
logger.warning("截图区域无效: (%s, %s, %s, %s),跳过", x, y, w, h)
|
||||
return None
|
||||
img = ImageGrab.grab(bbox=(x, y, x + w, y + h))
|
||||
if img is None or img.size[0] == 0 or img.size[1] == 0:
|
||||
logger.warning("抓取图像为空")
|
||||
return None
|
||||
return img
|
||||
|
||||
|
||||
def _dt_ocr_image(img):
|
||||
"""对图像进行 OCR 识别,返回 (text, (x1,y1,x2,y2)) 列表"""
|
||||
if img is None:
|
||||
return []
|
||||
img_np = np.array(img)
|
||||
result, _ = _dt_get_ocr()(img_np)
|
||||
ocr_data = []
|
||||
if result is not None:
|
||||
for box, text, score in result:
|
||||
xs = [p[0] for p in box]
|
||||
ys = [p[1] for p in box]
|
||||
x1, y1 = min(xs), min(ys)
|
||||
x2, y2 = max(xs), max(ys)
|
||||
ocr_data.append((text, (x1, y1, x2, y2)))
|
||||
return ocr_data
|
||||
|
||||
|
||||
def _dt_find_text_center(ocr_data, target_text):
|
||||
"""在 OCR 结果中查找包含 target_text 的文本框,返回中心坐标 (x, y)"""
|
||||
for text, (x1, y1, x2, y2) in ocr_data:
|
||||
if target_text in text:
|
||||
return (x1 + x2) // 2, (y1 + y2) // 2
|
||||
return None
|
||||
|
||||
|
||||
def _dt_wait_for_tab(hwnd, expected_tab, timeout=_DT_TIMEOUT):
|
||||
"""循环检测窗口顶部是否出现 expected_tab 标签(如“联系人”或“群组”)。"""
|
||||
left, top, right, bottom = _dt_get_window_rect(hwnd)
|
||||
width = right - left
|
||||
height = bottom - top
|
||||
top_height = max(40, int(height * _DT_TOP_HEIGHT_RATIO))
|
||||
start = time.time()
|
||||
while time.time() - start < timeout:
|
||||
img = _dt_capture_region(left, top, width, top_height)
|
||||
ocr_data = _dt_ocr_image(img)
|
||||
if _dt_find_text_center(ocr_data, expected_tab):
|
||||
logger.info("检测到'%s'标签", expected_tab)
|
||||
return True
|
||||
time.sleep(0.5)
|
||||
logger.warning("未检测到'%s'标签", expected_tab)
|
||||
return False
|
||||
|
||||
|
||||
def _dt_is_chat_opened(hwnd, target_name):
|
||||
"""截取窗口顶部区域,OCR识别是否有目标名称"""
|
||||
left, top, right, bottom = _dt_get_window_rect(hwnd)
|
||||
width = right - left
|
||||
height = bottom - top
|
||||
top_height = max(40, int(height * _DT_TOP_HEIGHT_RATIO))
|
||||
img = _dt_capture_region(left, top, width, top_height)
|
||||
ocr_data = _dt_ocr_image(img)
|
||||
for text, _ in ocr_data:
|
||||
if target_name in text:
|
||||
logger.debug("标题识别到: '%s'", text)
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _dt_search_and_open(hwnd, target_name, chat_type="联系人"):
|
||||
"""搜索并打开指定的联系人或群组会话。"""
|
||||
_dt_activate_window(hwnd)
|
||||
for attempt in range(_DT_SEARCH_RETRY):
|
||||
pyautogui.hotkey('ctrl', 'shift', 'f')
|
||||
time.sleep(0.8)
|
||||
pyautogui.hotkey('ctrl', 'a')
|
||||
pyautogui.press('delete')
|
||||
pyperclip.copy(target_name)
|
||||
pyautogui.hotkey('ctrl', 'v')
|
||||
time.sleep(0.5)
|
||||
pyautogui.press('enter')
|
||||
logger.info("搜索 '%s' (尝试 %d)", target_name, attempt + 1)
|
||||
time.sleep(0.8)
|
||||
if _dt_wait_for_tab(hwnd, chat_type, timeout=3):
|
||||
break
|
||||
else:
|
||||
pyautogui.press('esc')
|
||||
time.sleep(0.5)
|
||||
else:
|
||||
logger.error("搜索框未正常打开")
|
||||
return False
|
||||
|
||||
left, top, right, bottom = _dt_get_window_rect(hwnd)
|
||||
width = right - left
|
||||
height = bottom - top
|
||||
top_height = max(40, int(height * _DT_TOP_HEIGHT_RATIO))
|
||||
img = _dt_capture_region(left, top, width, top_height)
|
||||
ocr_data = _dt_ocr_image(img)
|
||||
pos = _dt_find_text_center(ocr_data, chat_type)
|
||||
if pos:
|
||||
cx, cy = pos
|
||||
pyautogui.click(left + cx, top + cy)
|
||||
logger.info("点击'%s'标签", chat_type)
|
||||
else:
|
||||
logger.warning("未识别'%s'标签", chat_type)
|
||||
time.sleep(0.5)
|
||||
|
||||
if _is_dingtalk_foreground():
|
||||
logger.info("钉钉窗口已激活")
|
||||
pyautogui.press('enter')
|
||||
logger.info("打开第一个匹配项")
|
||||
time.sleep(1.5)
|
||||
|
||||
start = time.time()
|
||||
while time.time() - start < _DT_TIMEOUT:
|
||||
if _dt_is_chat_opened(hwnd, target_name):
|
||||
logger.info("成功进入会话 '%s'", target_name)
|
||||
return True
|
||||
_dt_activate_window(hwnd)
|
||||
time.sleep(0.5)
|
||||
logger.warning("未检测到会话名 '%s'", target_name)
|
||||
return False
|
||||
|
||||
|
||||
def _dt_find_input_box_by_ocr(hwnd):
|
||||
"""通过OCR识别“请输入消息”等提示文字,返回屏幕坐标"""
|
||||
left, top, right, bottom = _dt_get_window_rect(hwnd)
|
||||
width = right - left
|
||||
height = bottom - top
|
||||
bottom_region_top = top + int(height * 0.6)
|
||||
bottom_region_height = int(height * 0.4)
|
||||
img = _dt_capture_region(left, bottom_region_top, width, bottom_region_height)
|
||||
ocr_data = _dt_ocr_image(img)
|
||||
keywords = ["请输入消息", "发送消息", "输入消息", "说点什么"]
|
||||
for keyword in keywords:
|
||||
pos = _dt_find_text_center(ocr_data, keyword)
|
||||
if pos:
|
||||
cx, cy = pos
|
||||
screen_x = left + cx
|
||||
screen_y = bottom_region_top + cy
|
||||
logger.info("定位输入框: '%s' 坐标 (%s, %s)", keyword, screen_x, screen_y)
|
||||
return screen_x, screen_y
|
||||
logger.warning("未识别到输入框提示")
|
||||
return None
|
||||
|
||||
|
||||
def _dt_focus_input_box(hwnd):
|
||||
"""定位并点击输入框,使其获得焦点"""
|
||||
input_pos = _dt_find_input_box_by_ocr(hwnd)
|
||||
if input_pos:
|
||||
pyautogui.click(input_pos[0], input_pos[1])
|
||||
return True
|
||||
left, top, right, bottom = _dt_get_window_rect(hwnd)
|
||||
width = right - left
|
||||
height = bottom - top
|
||||
pyautogui.click(left + width // 2, top + height - 60)
|
||||
logger.warning("使用固定坐标点击输入框")
|
||||
return False
|
||||
|
||||
|
||||
def _dt_send_hotkey_to_activate():
|
||||
"""模拟按下全局快捷键 Ctrl+Alt+D 以激活钉钉窗口"""
|
||||
logger.info("尝试快捷键 Ctrl+Alt+D 激活")
|
||||
pyautogui.hotkey('ctrl', 'alt', 'd')
|
||||
time.sleep(0.8)
|
||||
|
||||
|
||||
def _dt_is_dingtalk_activated(hwnd, target_name=None):
|
||||
"""通过 OCR 检测钉钉窗口是否已激活到前台(主界面可见)。"""
|
||||
try:
|
||||
left, top, right, bottom = _dt_get_window_rect(hwnd)
|
||||
width = right - left
|
||||
height = bottom - top
|
||||
if width <= 0 or height <= 0:
|
||||
return False
|
||||
top_height = max(50, int(height * 0.18))
|
||||
img = _dt_capture_region(left, top, width, top_height)
|
||||
if img is None:
|
||||
return False
|
||||
ocr_data = _dt_ocr_image(img)
|
||||
if target_name:
|
||||
for text, _ in ocr_data:
|
||||
if target_name in text:
|
||||
return True
|
||||
main_keywords = ["搜索或提问", "消息", "未读", "搜索", "提问"]
|
||||
for kw in main_keywords:
|
||||
for text, _ in ocr_data:
|
||||
if kw in text:
|
||||
return True
|
||||
return False
|
||||
except Exception as e:
|
||||
logger.warning("激活检测异常: %s", e)
|
||||
return False
|
||||
|
||||
|
||||
def _dt_ensure_activate_dingtalk(hwnd, target_name=None, timeout=10):
|
||||
"""多策略确保钉钉窗口激活到前台(快捷键→Win32 API→组合)。"""
|
||||
def wait_for_valid_rect(hwnd, max_wait=1.5):
|
||||
end = time.time() + max_wait
|
||||
while time.time() < end:
|
||||
left, top, right, bottom = _dt_get_window_rect(hwnd)
|
||||
if (right - left) > 0 and (bottom - top) > 0:
|
||||
return True
|
||||
time.sleep(0.2)
|
||||
return False
|
||||
|
||||
def find_current():
|
||||
return _dt_find_dingtalk_window(include_hidden=True) or hwnd
|
||||
|
||||
def verify(hwnd):
|
||||
start = time.time()
|
||||
while time.time() - start < timeout:
|
||||
if _dt_is_dingtalk_activated(hwnd, target_name=None):
|
||||
return True
|
||||
time.sleep(0.5)
|
||||
return False
|
||||
|
||||
if _dt_is_dingtalk_foreground():
|
||||
logger.info("钉钉已在最前,跳过激活")
|
||||
return True
|
||||
|
||||
if not _dt_is_dingtalk_main_visible():
|
||||
_dt_send_hotkey_to_activate()
|
||||
cur = find_current()
|
||||
if cur and wait_for_valid_rect(cur) and verify(cur):
|
||||
logger.info("快捷键激活成功")
|
||||
win32gui.SetForegroundWindow(cur)
|
||||
return True
|
||||
logger.warning("快捷键后窗口尺寸无效")
|
||||
else:
|
||||
raise RuntimeError("无法激活钉钉窗口,请确认钉钉桌面端已启动并登录")
|
||||
logger.info("窗口已可见,跳过切换快捷键(避免将其隐藏)")
|
||||
|
||||
logger.info("尝试 Win32 API 激活")
|
||||
cur = find_current()
|
||||
if cur:
|
||||
_dt_activate_window(cur)
|
||||
if wait_for_valid_rect(cur) and verify(cur):
|
||||
logger.info("API激活成功")
|
||||
return True
|
||||
logger.warning("API后窗口尺寸无效")
|
||||
|
||||
logger.info("组合激活")
|
||||
if not _dt_is_dingtalk_main_visible():
|
||||
_dt_send_hotkey_to_activate()
|
||||
time.sleep(0.5)
|
||||
cur = find_current()
|
||||
if cur:
|
||||
_dt_activate_window(cur)
|
||||
time.sleep(1)
|
||||
if wait_for_valid_rect(cur) and verify(cur):
|
||||
logger.info("组合激活成功")
|
||||
return True
|
||||
|
||||
raise RuntimeError("所有激活策略失败")
|
||||
|
||||
|
||||
def _dt_find_hwnd_or_raise():
|
||||
"""查找钉钉窗口,失败时给出可读的错误信息。"""
|
||||
hwnd = _dt_find_dingtalk_window(include_hidden=True)
|
||||
if not hwnd:
|
||||
dingtalk_running = any(p.name().lower() == 'dingtalk.exe' for p in psutil.process_iter())
|
||||
if not dingtalk_running:
|
||||
raise RuntimeError("钉钉进程未运行,请手动启动并登录")
|
||||
else:
|
||||
raise RuntimeError("找到进程但无窗口,请手动激活")
|
||||
return hwnd
|
||||
|
||||
|
||||
def _dt_send_text_to_person(name, text):
|
||||
"""向指定联系人发送文本(OCR 视觉方案):查找窗口→多策略激活→搜索打开会话→定位输入框→粘贴发送。"""
|
||||
if not text or not text.strip():
|
||||
raise ValueError("text 不能为空")
|
||||
|
||||
for attempt in range(_DT_RETRY_TIMES):
|
||||
try:
|
||||
hwnd = _dt_find_hwnd_or_raise()
|
||||
_dt_ensure_activate_dingtalk(hwnd, target_name=None, timeout=10)
|
||||
hwnd = _dt_find_dingtalk_window(include_hidden=True) or hwnd
|
||||
|
||||
if not _dt_search_and_open(hwnd, name, "联系人"):
|
||||
raise RuntimeError("打开联系人会话失败")
|
||||
|
||||
_dt_focus_input_box(hwnd)
|
||||
time.sleep(0.3)
|
||||
|
||||
pyperclip.copy(text)
|
||||
pyautogui.hotkey('ctrl', 'v')
|
||||
time.sleep(0.2)
|
||||
pyautogui.press('enter')
|
||||
logger.info("发送成功:%s...", text[:30])
|
||||
return True
|
||||
|
||||
except RuntimeError as e:
|
||||
logger.error(str(e))
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error("第%d次尝试失败:%s", attempt + 1, e)
|
||||
time.sleep(2)
|
||||
|
||||
raise RuntimeError(f"重试 {_DT_RETRY_TIMES} 次后失败")
|
||||
|
||||
|
||||
def _send_dingtalk_text(target, text):
|
||||
"""搜索联系人并发送文本:激活 -> 搜索 -> 进会话 -> 点击输入框聚焦 -> 粘贴 -> 发送。"""
|
||||
_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) # 等待会话加载完成
|
||||
logger.info("已搜索并进入会话: %s", target)
|
||||
|
||||
# 进入会话后钉钉可能失焦,重新确认前台并点击消息输入框区域
|
||||
if not _is_dingtalk_foreground():
|
||||
_activate_dingtalk()
|
||||
try:
|
||||
hwnd = _find_dingtalk_hwnd()
|
||||
rect = win32gui.GetWindowRect(hwnd)
|
||||
cx = (rect[0] + rect[2]) // 2
|
||||
cy = rect[1] + int((rect[3] - rect[1]) * 0.85) # 窗口底部 15%,消息输入框区域
|
||||
pyautogui.click(cx, 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 ""))
|
||||
"""推送文本到钉钉联系人(OCR 视觉方案,与 app/utils/dingtalk_sender.py 行为一致)。"""
|
||||
_dt_send_text_to_person(target, text)
|
||||
|
||||
|
||||
def build_push_summary(results, subject=""):
|
||||
@@ -1384,38 +1602,32 @@ def _get_date_range(start_time, end_time):
|
||||
return start_date, end_date
|
||||
|
||||
|
||||
def _get_months_in_range(start_date, end_date):
|
||||
"""获取日期范围内所有 (year, month) 元组列表,跨月按月份分段"""
|
||||
start = datetime.strptime(start_date, "%Y-%m-%d")
|
||||
end = datetime.strptime(end_date, "%Y-%m-%d")
|
||||
months = []
|
||||
current = start.replace(day=1)
|
||||
while current <= end:
|
||||
months.append((current.year, current.month))
|
||||
if current.month == 12:
|
||||
current = current.replace(year=current.year + 1, month=1)
|
||||
else:
|
||||
current = current.replace(month=current.month + 1)
|
||||
return months
|
||||
|
||||
|
||||
def _get_work_days_count(session, staff_id, start_date, end_date):
|
||||
"""获取请假区间内实际上班天数(非休息日),跨月按月份分段请求"""
|
||||
months = _get_months_in_range(start_date, end_date)
|
||||
attendance = {}
|
||||
for year, month in months:
|
||||
try:
|
||||
html = get_attendance_html(session, staff_id, year, month)
|
||||
monthly = parse_attendance_html(html)
|
||||
attendance.update(monthly)
|
||||
logger.info("排班数据已获取: %d-%02d, 共 %d 天", year, month, len(monthly))
|
||||
except Exception as e:
|
||||
logger.warning("获取排班失败(%d-%02d): %s", year, month, str(e))
|
||||
"""获取请假区间内实际上班天数(非休息日)。
|
||||
|
||||
if not attendance:
|
||||
数据源为考勤逐日接口,按日期范围一次查询,返回区间内每天的班次名
|
||||
(bc_name,休息日为"休息"),据此统计非休息的天数。
|
||||
"""
|
||||
try:
|
||||
records = get_attendance_daily(session, staff_id, start_date, end_date)
|
||||
logger.info("排班数据已获取: %s ~ %s, 共 %d 天", start_date, end_date, len(records))
|
||||
except Exception as e:
|
||||
logger.warning("获取排班失败(%s~%s): %s", start_date, end_date, str(e))
|
||||
records = []
|
||||
|
||||
if not records:
|
||||
raise RuntimeError("未能获取到任何排班数据")
|
||||
|
||||
work_days = get_work_days_in_range(attendance, start_date, end_date)
|
||||
attendance = {str(r.get("work_day", "")): r.get("bc_name", "") for r in records}
|
||||
work_days = []
|
||||
current = datetime.strptime(start_date, "%Y-%m-%d")
|
||||
end_dt = datetime.strptime(end_date, "%Y-%m-%d")
|
||||
while current <= end_dt:
|
||||
day = current.strftime("%Y-%m-%d")
|
||||
if attendance.get(day) not in (None, "", "休息"):
|
||||
work_days.append(day)
|
||||
current += timedelta(days=1)
|
||||
|
||||
logger.info("请假区间 %s ~ %s,实际上班天数: %d", start_date, end_date, len(work_days))
|
||||
return len(work_days)
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user