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:
2026-08-18 12:00:53 +08:00
parent ce388951fc
commit 5422dc8e3f
53 changed files with 6119 additions and 1064 deletions
+466 -254
View File
@@ -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)