refactor: 重构审批流程与依赖,新增社保异动模块
1. 新增社保增减名单模块,支持参保/停保名单导出 2. 重构钉钉推送逻辑,先推摘要再按需推送完整报告 3. 优化假期/加班校验的天数比对逻辑,适配半天请假场景 4. 重写排班HTML解析器,兼容新的页面结构并提取班次全称 5. 重构审批报告生成逻辑,新增全量明细展示 6. 重构影刀脚本的日志与依赖管理,新增UI自动化聚焦输入框 7. 更新依赖包,新增uiautomation库支持
This commit is contained in:
Binary file not shown.
Binary file not shown.
@@ -154,9 +154,14 @@ def run_flow(
|
||||
report = generate_report(results)
|
||||
print("\n" + report)
|
||||
|
||||
# 推送「通过项汇总」到钉钉(测试阶段,env 控制;无通过项或失败均不影响主流程)
|
||||
# 先推送摘要到钉钉
|
||||
push_report(build_push_summary(results, subject), subject)
|
||||
|
||||
# 有驳回/人工复核/失败时,再推送完整报告(含明细表格)
|
||||
has_detail = any(r.get("decision") != "通过" for r in results)
|
||||
if has_detail:
|
||||
push_report(report, subject)
|
||||
|
||||
# 保存最新 cookies(SSO 已刷新 hr 域会话,供下次运行免登录复用)
|
||||
save_browser_cookies(browser)
|
||||
|
||||
|
||||
@@ -23,29 +23,47 @@ def parse_attendance_html(html: str) -> Dict[str, str]:
|
||||
"""
|
||||
解析排班 HTML 表格,提取每个日期的班次名称。
|
||||
|
||||
示例 HTML 片段:
|
||||
<a class='cale_a' ... data-temp='2026-08-01' ...>正常</a>
|
||||
或 <a ...>休息</a>
|
||||
实际 HTML 结构(属性用单引号):
|
||||
<a class='cale_a' title='经营正班A' short_bc_name='经营A'
|
||||
data-temp='2026-08-03' finalState='' onclick="...">正常</a>
|
||||
|
||||
- data-temp: 日期
|
||||
- title: 班次全称(如 经营正班A、职能正班A、休息)
|
||||
- 文本内容: 考勤状态(如 正常、异常、休息)
|
||||
|
||||
Args:
|
||||
html: 排班接口返回的 HTML 字符串
|
||||
|
||||
Returns:
|
||||
字典:{日期字符串: 班次名称}
|
||||
例如:{"2026-08-01": "正常", "2026-08-02": "休息"}
|
||||
例如:{"2026-08-01": "休息", "2026-08-03": "经营正班A"}
|
||||
"""
|
||||
# 正则匹配 <a> 标签中的 data-temp 和文本内容
|
||||
# 注意:实际接口返回的 HTML 中 data-temp 用单引号(data-temp='2026-08-04'),
|
||||
# 需同时兼容单/双引号,否则会解析出 0 条
|
||||
pattern = r'<a[^>]*data-temp=["\']([^"\']+)["\'][^>]*>([^<]+)</a>'
|
||||
matches = re.findall(pattern, html)
|
||||
if not html:
|
||||
return {}
|
||||
|
||||
result = {}
|
||||
for date, shift in matches:
|
||||
# 去除可能的空格
|
||||
date_clean = date.strip()
|
||||
shift_clean = shift.strip()
|
||||
result[date_clean] = shift_clean
|
||||
# 匹配含 data-temp 属性的 <a> 标签,兼容单引号和双引号
|
||||
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
|
||||
|
||||
|
||||
|
||||
@@ -28,9 +28,31 @@ def _vtype(r: Dict[str, Any]) -> str:
|
||||
return info.get("假期类型") or "未知"
|
||||
|
||||
|
||||
def _format_detail(info: Dict[str, Any]) -> str:
|
||||
"""将 leave_info 字典格式化为易读的明细行。"""
|
||||
fields = [
|
||||
("请假人员", "请假人员"),
|
||||
("所属部门", "所属部门"),
|
||||
("假期类型", "假期类型"),
|
||||
("开始时间", "开始时间"),
|
||||
("结束时间", "结束时间"),
|
||||
("请假天数", "请假天数"),
|
||||
("请假小时", "请假小时"),
|
||||
("实际上班天数", "实际上班天数"),
|
||||
("填报天数", "填报天数"),
|
||||
("附件", "附件"),
|
||||
]
|
||||
parts = []
|
||||
for key, label in fields:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
parts.append(f"{label}={val}")
|
||||
return " | ".join(parts)
|
||||
|
||||
|
||||
def generate_report(results: List[Dict[str, Any]]) -> str:
|
||||
"""
|
||||
生成请假审批报告:汇总行 + 通过名单 + 驳回清单 + 人工复核清单(+处理失败)。
|
||||
生成请假审批报告:汇总行 + 每条明细 + 驳回清单 + 人工复核清单(+处理失败)。
|
||||
|
||||
Args:
|
||||
results: validate_doc 返回的校验结果列表,decision ∈ {通过/驳回/人工复核/失败}
|
||||
@@ -54,13 +76,21 @@ def generate_report(results: List[Dict[str, Any]]) -> str:
|
||||
"",
|
||||
]
|
||||
|
||||
# 通过名单(简短,详情见钉钉推送)
|
||||
if passed:
|
||||
names = "、".join(_name(r) for r in passed)
|
||||
lines.append(f"【通过】{len(passed)} 条:{names}")
|
||||
lines.append("")
|
||||
# ----- 明细清单(所有审批单的完整数据) -----
|
||||
lines.append("【审批明细】")
|
||||
for i, r in enumerate(results, 1):
|
||||
info = r.get("leave_info", {}) or {}
|
||||
decision = r.get("decision", "未知")
|
||||
note = r.get("note") or r.get("error") or ""
|
||||
lines.append(f" #{i} {_name(r)}({_vtype(r)})-> {decision}")
|
||||
detail = _format_detail(info)
|
||||
if detail:
|
||||
lines.append(f" {detail}")
|
||||
if note:
|
||||
lines.append(f" 备注: {note}")
|
||||
lines.append("")
|
||||
|
||||
# 清单一:自动驳回
|
||||
# ----- 驳回清单 -----
|
||||
if rejected:
|
||||
lines.append("《请假审批自动驳回人员明细清单》")
|
||||
for i, r in enumerate(rejected, 1):
|
||||
@@ -68,7 +98,7 @@ def generate_report(results: List[Dict[str, Any]]) -> str:
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 假期类型: {_vtype(r)} | 驳回原因: {reason}")
|
||||
lines.append("")
|
||||
|
||||
# 清单二:附件人工复核
|
||||
# ----- 人工复核清单 -----
|
||||
if review:
|
||||
lines.append("《附件人工复核待办清单》")
|
||||
for i, r in enumerate(review, 1):
|
||||
@@ -76,7 +106,7 @@ def generate_report(results: List[Dict[str, Any]]) -> str:
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 假期类型: {_vtype(r)} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
# 处理失败(异常,需人工介入;不属于上述三态)
|
||||
# ----- 处理失败 -----
|
||||
if failed:
|
||||
lines.append("【处理失败】")
|
||||
for i, r in enumerate(failed, 1):
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
import math
|
||||
from typing import Any, Dict, List, Tuple
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
@@ -174,7 +175,9 @@ def validate_doc(doc: Dict[str, Any], session: Any) -> Dict[str, Any]:
|
||||
leave_info["实际上班天数"] = actual_work_days
|
||||
leave_info["填报天数"] = fill_days
|
||||
|
||||
days_mismatch = abs(actual_work_days - fill_days) > 0.01
|
||||
# 请半天假(0.5天)仍占用1个排班上班日,故用向上取整比对:
|
||||
# 0.5天->1个工作日,1.0天->1个工作日,1.5天->2个工作日
|
||||
days_mismatch = actual_work_days != math.ceil(round(fill_days, 2))
|
||||
|
||||
# ========== 根据假期类型分支处理 ==========
|
||||
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.social_change
|
||||
@FileName: __init__.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-07 15:00
|
||||
@Description: 社保增减名单模块(导出员工异动名单)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
@@ -0,0 +1,442 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.social_change.employee_change_list
|
||||
@FileName: employee_change_list.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-07 14:55
|
||||
@Description: 社保增减名单模块:复用 OA 登录态,监听首页请求动态获取参数并导出员工异动名单(精简版)
|
||||
@Version: 2.3.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Dict, Optional, Tuple
|
||||
from urllib.parse import urljoin, urlparse, parse_qs
|
||||
|
||||
# ---- 单文件运行支持 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging
|
||||
from app.utils.intelligent_retry import retry
|
||||
from app.service.hrbp.oa.common.config import BASE_URL
|
||||
from app.service.hrbp.oa.common.login import oa_login
|
||||
from app.service.hrbp.oa.common.session_manager import (
|
||||
init_session_from_page,
|
||||
load_saved_session,
|
||||
save_browser_cookies,
|
||||
is_session_valid,
|
||||
load_cookies,
|
||||
COOKIE_FILE,
|
||||
)
|
||||
|
||||
try:
|
||||
from DrissionPage import ChromiumPage, SessionPage, ChromiumOptions
|
||||
except ImportError:
|
||||
ChromiumPage = None
|
||||
SessionPage = None
|
||||
ChromiumOptions = None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ---------- 常量 ----------
|
||||
HOME_URL = f"{BASE_URL}/sys/portal/page.jsp?portalId=1754a0f1c8b63479fb544514619903d5"
|
||||
LIST_URL = f"{BASE_URL}/km/review/km_review_main_list.jsp"
|
||||
SEARCH_URL = f"{BASE_URL}/sys/search/search.do"
|
||||
MENU_API_PATH = "/sys/portal/sys_portal_nav/sysPortalNav.do"
|
||||
|
||||
DEFAULT_FIXED_PARAMS = {
|
||||
"fdModelName": "com.landray.kmss.km.review.model.KmReviewMain",
|
||||
"canClose": "false",
|
||||
"isNew": "true",
|
||||
"j_aside": "false",
|
||||
"j_rIframe": "true",
|
||||
"j_iframe": "true",
|
||||
}
|
||||
|
||||
DEFAULT_EXPORT_COLUMNS = (
|
||||
"fd_38e9dd25e050e0;docCreator;fd_38d49cbc0ceeae;"
|
||||
"fd_390c6988e241ea;fd_390c639f265c78;fd_38e77e5cd6e9fe;"
|
||||
"fd_38d49cd67211e2;fd_38d49cd73eff02;fd_38deea220dc8c4;docStatus"
|
||||
)
|
||||
|
||||
# 员工停保申请台账的导出列(与参保表单字段不同)
|
||||
DEFAULT_EXPORT_COLUMNS_SUSPEND = (
|
||||
"fd_38d32213b2e9cc;fd_38d322164f42f2;fd_38e6887c2b3690;"
|
||||
"fd_3ec504d4c63e02;fd_38dad8035e33e4;fd_38e6887d6b0088;"
|
||||
"fd_38d32227f7a496;fd_38dee9ae569d6a;fd_38e687e91f4fc6;"
|
||||
"fd_38e687eb56dc4c;docStatus;docPublishTime"
|
||||
)
|
||||
|
||||
# 参保 / 停保 两个菜单名,对应的 searchId 不同,由 get_search_id_from_menu 动态获取
|
||||
MENU_NAME_PARTICIPATE = "员工参保申请"
|
||||
MENU_NAME_SUSPEND = "员工停保申请"
|
||||
|
||||
# 参保 / 停保 两个台账的查询筛选字段下标不同(参保为 2,停保为 3)
|
||||
FILTER_IDX_PARTICIPATE = "2"
|
||||
FILTER_IDX_SUSPEND = "3"
|
||||
|
||||
|
||||
def _resolve_query_date(query_date: Optional[str] = None) -> str:
|
||||
"""返回查询起始日期:手动传入则用传入值,否则用当前月份第一天。"""
|
||||
if query_date:
|
||||
return query_date
|
||||
return datetime.now().strftime("%Y-%m-01")
|
||||
|
||||
|
||||
def _build_filter_params(filter_idx: str, query_date: Optional[str] = None) -> Dict:
|
||||
"""构造查询筛选参数,如 {v0_2: gt, v1_2: 2026-08-01}。"""
|
||||
day = _resolve_query_date(query_date)
|
||||
return {f"v0_{filter_idx}": "gt", f"v1_{filter_idx}": day}
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 1. 会话获取与登录
|
||||
# ----------------------------------------------
|
||||
@retry(max_attempts=3)
|
||||
def _login():
|
||||
return oa_login()
|
||||
|
||||
|
||||
def get_session(subject: str = "社保") -> Tuple[Optional[ChromiumPage], SessionPage]:
|
||||
saved_session = load_saved_session()
|
||||
if saved_session is not None and is_session_valid(saved_session, subject):
|
||||
logger.info("复用已保存的登录会话,跳过登录(无需启动浏览器)")
|
||||
if hasattr(saved_session, 'session'):
|
||||
saved_session.session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
|
||||
"Referer": LIST_URL,
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
"Accept": "application/json, text/javascript, */*; q=0.01",
|
||||
})
|
||||
return None, saved_session
|
||||
|
||||
logger.info("无可用会话,执行完整登录")
|
||||
browser = _login()
|
||||
session = init_session_from_page(browser)
|
||||
save_browser_cookies(browser)
|
||||
if hasattr(session, 'session'):
|
||||
session.session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
||||
"Referer": LIST_URL,
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
"Accept": "application/json, text/javascript, */*; q=0.01",
|
||||
})
|
||||
return browser, session
|
||||
|
||||
|
||||
def _check_response(resp, action: str) -> None:
|
||||
if resp is None:
|
||||
raise RuntimeError(f"{action}失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"{action}失败,状态码: {resp.status_code}")
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 2. 动态提取 fdId(监听浏览器网络请求)
|
||||
# ----------------------------------------------
|
||||
def _get_cookies_with_domain(session: SessionPage) -> list:
|
||||
cookies = []
|
||||
try:
|
||||
raw = session.session.cookies
|
||||
for c in raw:
|
||||
cookies.append({
|
||||
"name": c.name,
|
||||
"value": c.value,
|
||||
"domain": c.domain,
|
||||
"path": c.path or "/",
|
||||
})
|
||||
except Exception as e:
|
||||
logger.debug("从底层会话提取 cookies 失败: %s", e)
|
||||
if not cookies:
|
||||
try:
|
||||
cookies = load_cookies(COOKIE_FILE) or []
|
||||
except Exception as e:
|
||||
logger.debug("从本地 cookie 文件读取失败: %s", e)
|
||||
return cookies
|
||||
|
||||
|
||||
def get_fd_id_by_listening(session: SessionPage) -> str:
|
||||
cookies = _get_cookies_with_domain(session)
|
||||
if not cookies:
|
||||
raise RuntimeError("Session 中没有 cookie,请先执行完整登录")
|
||||
|
||||
co = ChromiumOptions()
|
||||
# 如需 Edge 浏览器,请取消注释并设置路径
|
||||
# co.set_browser_path(r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe")
|
||||
browser = ChromiumPage(co)
|
||||
browser.set.cookies(cookies)
|
||||
|
||||
try:
|
||||
browser.listen.start()
|
||||
logger.info("正在访问 OA 首页:%s", HOME_URL)
|
||||
browser.get(HOME_URL)
|
||||
time.sleep(5)
|
||||
|
||||
deadline = time.time() + 10
|
||||
target_request = None
|
||||
while time.time() < deadline:
|
||||
req = browser.listen.wait(timeout=1)
|
||||
if req and 'sysPortalNav.do' in req.url:
|
||||
target_request = req
|
||||
break
|
||||
if target_request is None:
|
||||
raise RuntimeError("超时未监听到菜单请求,请检查网络或登录态")
|
||||
|
||||
url = target_request.url
|
||||
logger.debug("监听到菜单请求: %s", url)
|
||||
qs = parse_qs(urlparse(url).query)
|
||||
fd_id = qs.get('fdId', [None])[0]
|
||||
if not fd_id:
|
||||
raise RuntimeError("菜单请求中未包含 fdId")
|
||||
logger.info("动态获取到 fdId: %s", fd_id)
|
||||
return fd_id
|
||||
finally:
|
||||
browser.listen.stop()
|
||||
browser.quit()
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 3. 从菜单 JSON 获取 searchId
|
||||
# ----------------------------------------------
|
||||
def get_search_id_from_menu(session: SessionPage, fd_id: str,
|
||||
menu_name: str = MENU_NAME_PARTICIPATE) -> str:
|
||||
params = {
|
||||
"method": "portlet",
|
||||
"fdId": fd_id,
|
||||
"f_s": "sourcejs",
|
||||
"t": str(int(time.time() * 1000))
|
||||
}
|
||||
session.get(f"{BASE_URL}{MENU_API_PATH}", params=params)
|
||||
_check_response(session.response, "获取菜单")
|
||||
data = session.response.json()
|
||||
|
||||
def find_item(items):
|
||||
for item in items:
|
||||
if item.get("text") == menu_name:
|
||||
return item
|
||||
if "children" in item:
|
||||
found = find_item(item["children"])
|
||||
if found:
|
||||
return found
|
||||
return None
|
||||
|
||||
items = data if isinstance(data, list) else data.get("children", [])
|
||||
item = find_item(items)
|
||||
if not item:
|
||||
raise RuntimeError(f"菜单中未找到 '{menu_name}'")
|
||||
href = item["href"]
|
||||
full_url = urljoin(BASE_URL, href)
|
||||
qs = parse_qs(urlparse(full_url).query)
|
||||
search_id = qs.get("searchId", [None])[0]
|
||||
if not search_id:
|
||||
raise RuntimeError("菜单链接中未包含 searchId")
|
||||
logger.info("从菜单获取到 searchId: %s", search_id)
|
||||
return search_id
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 4. 获取总条数(通过 result 接口)
|
||||
# ----------------------------------------------
|
||||
def get_total_count(session: SessionPage, base_params: Dict, search_id: str, timestamp: str) -> int:
|
||||
"""
|
||||
请求 result 接口,从返回的 HTML 中提取总条数。
|
||||
支持多种格式:exportNum、"总记录数"、"共X条"
|
||||
"""
|
||||
params = {
|
||||
"method": "result",
|
||||
"searchId": search_id,
|
||||
"j_timestamp": timestamp,
|
||||
**base_params
|
||||
}
|
||||
session.get(SEARCH_URL, params=params, headers={"Referer": LIST_URL})
|
||||
_check_response(session.response, "查询总数")
|
||||
html = session.response.text
|
||||
|
||||
# 1. 优先从 exportNum 提取
|
||||
num_match = re.search(r'exportNum:\s*"(\d+)"', html)
|
||||
if num_match:
|
||||
total = int(num_match.group(1))
|
||||
logger.info("从 exportNum 获取到总记录数: %d", total)
|
||||
return total
|
||||
|
||||
# 2. 备选:从 "总记录数:数字" 提取
|
||||
total_match = re.search(r'总记录数[::]\s*(\d+)', html)
|
||||
if total_match:
|
||||
total = int(total_match.group(1))
|
||||
logger.info("从 '总记录数' 获取到总记录数: %d", total)
|
||||
return total
|
||||
|
||||
# 3. 再尝试从 "共 X 条" 提取(你贴出的HTML中正是这种格式)
|
||||
fallback_match = re.search(r'共\s*(\d+)\s*条', html)
|
||||
if fallback_match:
|
||||
total = int(fallback_match.group(1))
|
||||
logger.info("从 '共X条' 获取到总记录数: %d", total)
|
||||
return total
|
||||
|
||||
logger.warning("未找到总条数,默认为 0")
|
||||
return 0
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 5. 导出数据(直接 POST)
|
||||
# ----------------------------------------------
|
||||
def export_all_data(session: SessionPage, base_params: Dict, total: int, columns: str,
|
||||
search_id: str, timestamp: str) -> bytes:
|
||||
data = {
|
||||
"method": "exportResult",
|
||||
"searchId": search_id,
|
||||
"j_timestamp": timestamp,
|
||||
**base_params,
|
||||
"fdColumns": columns,
|
||||
"fdNum": str(total),
|
||||
"fdNumStart": "1",
|
||||
"fdNumEnd": str(total),
|
||||
"fdKeepRtfStyle": "true",
|
||||
"checkIdValues": "",
|
||||
}
|
||||
session.post(SEARCH_URL, data=data, headers={"Referer": LIST_URL})
|
||||
_check_response(session.response, "导出数据")
|
||||
return session.response.content
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 6. 主流程(精简版)
|
||||
# ----------------------------------------------
|
||||
def export_employee_change_list(
|
||||
filter_params: Optional[Dict] = None,
|
||||
columns: str = DEFAULT_EXPORT_COLUMNS,
|
||||
output_dir: str = ".",
|
||||
menu_name: str = MENU_NAME_PARTICIPATE,
|
||||
filter_idx: str = FILTER_IDX_PARTICIPATE,
|
||||
query_date: Optional[str] = None,
|
||||
) -> str:
|
||||
setup_logging()
|
||||
logger.info("社保增减名单导出流程开始(精简版),菜单:%s", menu_name)
|
||||
|
||||
if filter_params is None:
|
||||
filter_params = _build_filter_params(filter_idx, query_date)
|
||||
|
||||
base_params = {**DEFAULT_FIXED_PARAMS, **filter_params}
|
||||
|
||||
browser, session = get_session()
|
||||
|
||||
try:
|
||||
# 1. 动态获取 fdId
|
||||
fd_id = get_fd_id_by_listening(session)
|
||||
|
||||
# 2. 从菜单获取 searchId
|
||||
search_id = get_search_id_from_menu(session, fd_id, menu_name)
|
||||
|
||||
# 3. 生成一个固定的时间戳(毫秒)
|
||||
timestamp = str(int(time.time() * 1000))
|
||||
logger.info("使用时间戳: %s", timestamp)
|
||||
|
||||
# 4. 查询获取总条数
|
||||
total = get_total_count(session, base_params, search_id, timestamp)
|
||||
if total == 0:
|
||||
logger.warning("查询结果为 0 条,请检查筛选条件或无数据")
|
||||
return ""
|
||||
|
||||
# 5. 导出数据
|
||||
logger.info("开始导出 %d 条记录...", total)
|
||||
file_content = export_all_data(session, base_params, total, columns,
|
||||
search_id, timestamp)
|
||||
|
||||
output_filename = f"{time.strftime('%Y%m')}_{menu_name}表_{time.strftime('%H%M%S')}.xls"
|
||||
output_path = os.path.abspath(os.path.join(output_dir, output_filename))
|
||||
with open(output_path, "wb") as f:
|
||||
f.write(file_content)
|
||||
logger.info("导出完成,文件保存为:%s", output_path)
|
||||
|
||||
if browser is not None:
|
||||
save_browser_cookies(browser)
|
||||
return output_path
|
||||
|
||||
except Exception as e:
|
||||
logger.error("导出过程出错: %s", e, exc_info=True)
|
||||
if "登录" in str(e) or "cookie" in str(e).lower():
|
||||
try:
|
||||
if os.path.exists(COOKIE_FILE):
|
||||
os.remove(COOKIE_FILE)
|
||||
logger.info("已删除失效的 cookie 文件")
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
finally:
|
||||
if browser is not None:
|
||||
try:
|
||||
browser.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def export_participation(
|
||||
filter_params: Optional[Dict] = None,
|
||||
columns: str = DEFAULT_EXPORT_COLUMNS,
|
||||
output_dir: str = ".",
|
||||
query_date: Optional[str] = None,
|
||||
) -> str:
|
||||
"""导出员工参保申请名单。"""
|
||||
return export_employee_change_list(
|
||||
filter_params=filter_params,
|
||||
columns=columns,
|
||||
output_dir=output_dir,
|
||||
menu_name=MENU_NAME_PARTICIPATE,
|
||||
filter_idx=FILTER_IDX_PARTICIPATE,
|
||||
query_date=query_date,
|
||||
)
|
||||
|
||||
|
||||
def export_suspension(
|
||||
filter_params: Optional[Dict] = None,
|
||||
columns: str = DEFAULT_EXPORT_COLUMNS_SUSPEND,
|
||||
output_dir: str = ".",
|
||||
query_date: Optional[str] = None,
|
||||
) -> str:
|
||||
"""导出员工停保申请名单。"""
|
||||
return export_employee_change_list(
|
||||
filter_params=filter_params,
|
||||
columns=columns,
|
||||
output_dir=output_dir,
|
||||
menu_name=MENU_NAME_SUSPEND,
|
||||
filter_idx=FILTER_IDX_SUSPEND,
|
||||
query_date=query_date,
|
||||
)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = sys.argv[1:]
|
||||
change_type = "全部"
|
||||
query_date = None
|
||||
for a in args:
|
||||
if re.match(r"^\d{4}-\d{2}-\d{2}$", a):
|
||||
query_date = a
|
||||
elif a in ("参保", "participate", "participation"):
|
||||
change_type = "参保"
|
||||
elif a in ("停保", "suspend", "suspension"):
|
||||
change_type = "停保"
|
||||
|
||||
if change_type == "参保":
|
||||
export_participation(query_date=query_date)
|
||||
elif change_type == "停保":
|
||||
export_suspension(query_date=query_date)
|
||||
else:
|
||||
# 默认(含 "全部"/"都要"/无参数):参保 + 停保 都导出
|
||||
export_participation(query_date=query_date)
|
||||
export_suspension(query_date=query_date)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -28,9 +28,44 @@ def _otype(r: Dict[str, Any]) -> str:
|
||||
return info.get("加班类型") or "未知"
|
||||
|
||||
|
||||
def _format_detail(info: Dict[str, Any]) -> str:
|
||||
"""将 overtime_info 字典格式化为易读的明细行。"""
|
||||
fields = [
|
||||
("加班人员", "加班人员"),
|
||||
("所属部门", "所属部门"),
|
||||
("加班类型", "加班类型"),
|
||||
("补贴类型", "补贴类型"),
|
||||
("加班日期", "加班日期"),
|
||||
("加班开始时间", "加班开始时间"),
|
||||
("加班结束时间", "加班结束时间"),
|
||||
("加班时长(小时)", "加班时长"),
|
||||
("加班天数(天)", "加班天数"),
|
||||
("系统判断加班时长(小时)", "系统判定时长"),
|
||||
("系统判断加班天数(天)", "系统判定天数"),
|
||||
("系统判定加班时间", "系统判定时间"),
|
||||
("加班当天班次", "当天班次"),
|
||||
("当日最早打卡", "最早打卡"),
|
||||
("当日最晚打卡", "最晚打卡"),
|
||||
("次日最早打卡", "次日最早打卡"),
|
||||
("计算加班时长(小时)", "计算时长"),
|
||||
("弹性扣减(小时)", "弹性扣减"),
|
||||
("有效加班时长(小时)", "有效时长"),
|
||||
("弹性额度D(小时)", "弹性额度D"),
|
||||
("打卡时间间隔(小时)", "打卡间隔"),
|
||||
("申报天数(天)", "申报天数"),
|
||||
("打卡备注", "打卡备注"),
|
||||
]
|
||||
parts = []
|
||||
for key, label in fields:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
parts.append(f"{label}={val}")
|
||||
return " | ".join(parts)
|
||||
|
||||
|
||||
def generate_report(results: List[Dict[str, Any]]) -> str:
|
||||
"""
|
||||
生成加班审批报告:汇总行 + 通过名单 + 驳回清单 + 人工复核清单(+处理失败)。
|
||||
生成加班审批报告:汇总行 + 每条明细 + 驳回清单 + 人工复核清单(+处理失败)。
|
||||
|
||||
Args:
|
||||
results: validate_doc 返回的校验结果列表,decision ∈ {通过/驳回/人工复核/失败}
|
||||
@@ -54,11 +89,21 @@ def generate_report(results: List[Dict[str, Any]]) -> str:
|
||||
"",
|
||||
]
|
||||
|
||||
if passed:
|
||||
names = "、".join(_name(r) for r in passed)
|
||||
lines.append(f"【通过】{len(passed)} 条:{names}")
|
||||
lines.append("")
|
||||
# ----- 明细清单(所有审批单的完整数据) -----
|
||||
lines.append("【审批明细】")
|
||||
for i, r in enumerate(results, 1):
|
||||
info = r.get("overtime_info", {}) or {}
|
||||
decision = r.get("decision", "未知")
|
||||
note = r.get("note") or r.get("error") or ""
|
||||
lines.append(f" #{i} {_name(r)}({_otype(r)})-> {decision}")
|
||||
detail = _format_detail(info)
|
||||
if detail:
|
||||
lines.append(f" {detail}")
|
||||
if note:
|
||||
lines.append(f" 备注: {note}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 驳回清单 -----
|
||||
if rejected:
|
||||
lines.append("《加班审批自动驳回人员明细清单》")
|
||||
for i, r in enumerate(rejected, 1):
|
||||
@@ -66,6 +111,7 @@ def generate_report(results: List[Dict[str, Any]]) -> str:
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 驳回原因: {reason}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 人工复核清单 -----
|
||||
if review:
|
||||
lines.append("《附件人工复核待办清单》")
|
||||
for i, r in enumerate(review, 1):
|
||||
@@ -73,6 +119,7 @@ def generate_report(results: List[Dict[str, Any]]) -> str:
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 处理失败 -----
|
||||
if failed:
|
||||
lines.append("【处理失败】")
|
||||
for i, r in enumerate(failed, 1):
|
||||
|
||||
+124
-18
@@ -10,7 +10,7 @@
|
||||
@Version: 1.0.0
|
||||
|
||||
依赖安装:
|
||||
pip install pyautogui pywin32 pyperclip
|
||||
pip install pyautogui pywin32 pyperclip uiautomation
|
||||
|
||||
使用前提:
|
||||
1. Windows 系统
|
||||
@@ -59,6 +59,11 @@ try:
|
||||
except ImportError:
|
||||
pyperclip = None
|
||||
|
||||
try:
|
||||
import uiautomation as ua
|
||||
except ImportError:
|
||||
ua = None
|
||||
|
||||
|
||||
# ==================== 默认参数 ====================
|
||||
DEFAULT_ACTIVATE_METHOD = "auto" # auto | hotkey | win32
|
||||
@@ -147,29 +152,50 @@ def _is_dingtalk_foreground():
|
||||
|
||||
|
||||
def _activate(method=DEFAULT_ACTIVATE_METHOD):
|
||||
"""按指定方式激活钉钉窗口。auto = 先 Ctrl+D,失败回退 win32。
|
||||
"""激活钉钉窗口:先找窗口,托盘中则 Ctrl+D 唤起,win32 置前,点击确保焦点。
|
||||
|
||||
若钉钉已在前台则直接返回——Ctrl+D 是 toggle 热键,窗口已显示时再按会把它隐藏,
|
||||
若钉钉已在前台则直接返回--Ctrl+D 是 toggle 热键,窗口已显示时再按会把它隐藏,
|
||||
导致后续发送失败。连续发送时第二次起会命中此分支。
|
||||
"""
|
||||
if _is_dingtalk_foreground():
|
||||
logger.info("钉钉窗口已在前台,跳过激活")
|
||||
return
|
||||
|
||||
if method == "hotkey":
|
||||
_activate_by_hotkey()
|
||||
elif method == "win32":
|
||||
_activate_by_win32()
|
||||
elif method == "auto":
|
||||
# 先尝试找到已打开的钉钉窗口
|
||||
hwnd = None
|
||||
try:
|
||||
hwnd = _find_dingtalk_hwnd()
|
||||
except RuntimeError:
|
||||
pass
|
||||
|
||||
if hwnd is None:
|
||||
# 钉钉在系统托盘,用 Ctrl+D 全局热键唤起
|
||||
pyautogui.hotkey("ctrl", "d")
|
||||
time.sleep(1.5)
|
||||
try:
|
||||
_activate_by_hotkey()
|
||||
logger.info("通过 Ctrl+D 激活钉钉窗口")
|
||||
except Exception as e:
|
||||
logger.warning("Ctrl+D 激活失败(%s),回退到 win32 查窗口激活", e)
|
||||
_activate_by_win32()
|
||||
logger.info("通过 win32 激活钉钉窗口")
|
||||
hwnd = _find_dingtalk_hwnd()
|
||||
except RuntimeError:
|
||||
raise RuntimeError("Ctrl+D 未能唤起钉钉窗口,请确认钉钉已启动并配置了 Ctrl+D 热键")
|
||||
|
||||
# win32 置前台
|
||||
if win32gui.IsIconic(hwnd):
|
||||
win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
|
||||
time.sleep(0.3)
|
||||
pyautogui.press("alt")
|
||||
win32gui.SetForegroundWindow(hwnd)
|
||||
time.sleep(DEFAULT_WAIT_AFTER_ACTIVATE)
|
||||
|
||||
# 点击窗口中心确保键盘焦点落在钉钉上(SetForegroundWindow 只切前台,不保证键盘焦点)
|
||||
rect = win32gui.GetWindowRect(hwnd)
|
||||
cx = (rect[0] + rect[2]) // 2
|
||||
cy = (rect[1] + rect[3]) // 2
|
||||
pyautogui.click(cx, cy)
|
||||
time.sleep(0.5)
|
||||
|
||||
if _is_dingtalk_foreground():
|
||||
logger.info("钉钉窗口已激活")
|
||||
else:
|
||||
raise ValueError(f"不支持的 activate_method: {method!r},可选: auto/hotkey/win32")
|
||||
raise RuntimeError("无法激活钉钉窗口,请确认钉钉桌面端已启动并登录")
|
||||
|
||||
|
||||
# ==================== 剪贴板 ====================
|
||||
@@ -205,11 +231,90 @@ def _set_file_to_clipboard(file_path):
|
||||
|
||||
|
||||
# ==================== 搜索 & 发送 ====================
|
||||
def _find_editable_controls(control, result, depth=0, max_depth=15):
|
||||
"""递归遍历控件树,收集所有可编辑控件(Edit/Document)。"""
|
||||
if depth > max_depth or len(result) > 20:
|
||||
return
|
||||
try:
|
||||
ct = control.ControlType
|
||||
if ct in (ua.ControlType.EditControl, ua.ControlType.DocumentControl):
|
||||
result.append(control)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
for child in control.GetChildren():
|
||||
_find_editable_controls(child, result, depth + 1, max_depth)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _rect_area(rect):
|
||||
"""计算矩形面积,无效矩形返回 0。"""
|
||||
try:
|
||||
return max(0, rect.right - rect.left) * max(0, rect.bottom - rect.top)
|
||||
except Exception:
|
||||
return 0
|
||||
|
||||
|
||||
def _focus_message_input():
|
||||
"""聚焦消息输入框(分辨率无关)。
|
||||
|
||||
优先使用 UI Automation 遍历钉钉控件树,定位底部区域面积最大的可编辑控件
|
||||
(即消息输入框)并点击;若 uiautomation 不可用或未找到控件,回退到
|
||||
Escape 键关闭搜索面板,依赖钉钉将焦点自动移至消息输入框。
|
||||
"""
|
||||
if ua is not None:
|
||||
try:
|
||||
hwnd = _find_dingtalk_hwnd()
|
||||
window = ua.ControlFromHandle(hwnd)
|
||||
if window is not None:
|
||||
edits = []
|
||||
_find_editable_controls(window, edits)
|
||||
valid = [e for e in edits if e.BoundingRectangle and _rect_area(e.BoundingRectangle) > 0]
|
||||
if valid:
|
||||
wleft, wtop, wright, wbottom = win32gui.GetWindowRect(hwnd)
|
||||
wh = wbottom - wtop
|
||||
# 优先选择窗口底部 40% 区域的可编辑控件
|
||||
bottom_edits = [
|
||||
e for e in valid
|
||||
if e.BoundingRectangle.bottom > wtop + wh * 0.6
|
||||
]
|
||||
candidates = bottom_edits if bottom_edits else valid
|
||||
# 取面积最大的(消息输入框通常是最大的可编辑区域)
|
||||
target = max(candidates, key=lambda e: _rect_area(e.BoundingRectangle))
|
||||
rect = target.BoundingRectangle
|
||||
cx = (rect.left + rect.right) // 2
|
||||
cy = (rect.top + rect.bottom) // 2
|
||||
pyautogui.click(cx, cy)
|
||||
time.sleep(0.3)
|
||||
logger.debug("UI Automation 定位到消息输入框: (%d, %d)", cx, cy)
|
||||
return
|
||||
except Exception as e:
|
||||
logger.debug("UI Automation 聚焦失败: %s", e)
|
||||
|
||||
# 回退:钉钉可能失焦,重新确认前台并点击窗口底部消息输入框区域
|
||||
if not _is_dingtalk_foreground():
|
||||
_activate()
|
||||
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.3)
|
||||
logger.debug("回退方案:点击窗口底部聚焦消息输入框: (%d, %d)", cx, cy)
|
||||
except Exception:
|
||||
pyautogui.press("escape")
|
||||
time.sleep(0.3)
|
||||
logger.debug("最终回退:通过 Escape 键尝试聚焦")
|
||||
|
||||
|
||||
def _search_and_open(target, wait_search=DEFAULT_WAIT_SEARCH):
|
||||
"""Ctrl+Shift+F 打开搜索 → 粘贴目标名 → 回车进入会话。
|
||||
"""Ctrl+Shift+F 打开搜索 → 粘贴目标名 → 回车进入会话 → 点击输入框获取焦点。
|
||||
|
||||
时序很关键:搜索结果加载、会话跳转都需要时间,等待不足会把消息内容
|
||||
误贴到搜索框。这里分段等待,确保回车后会话已加载、焦点已落到消息输入框。
|
||||
误贴到搜索框。这里分段等待,确保回车后会话已加载;最后点击消息输入框
|
||||
确保焦点落到输入框,避免粘贴时内容进入搜索框或其他控件。
|
||||
"""
|
||||
pyautogui.hotkey("ctrl", "shift", "f")
|
||||
time.sleep(DEFAULT_WAIT_SEARCH_BOX) # 搜索框打开
|
||||
@@ -218,7 +323,8 @@ def _search_and_open(target, wait_search=DEFAULT_WAIT_SEARCH):
|
||||
time.sleep(DEFAULT_WAIT_SEARCH_RESULT) # 搜索结果加载
|
||||
pyautogui.press("enter")
|
||||
time.sleep(DEFAULT_WAIT_CONVERSATION_LOAD) # 会话开始加载
|
||||
time.sleep(wait_search) # 焦点稳定到消息输入框
|
||||
time.sleep(wait_search) # 会话加载完成
|
||||
_focus_message_input() # 聚焦消息输入框
|
||||
logger.info("已搜索并进入会话: %s", target)
|
||||
|
||||
|
||||
|
||||
+2
-1
@@ -3,4 +3,5 @@ python-dotenv
|
||||
chinese_calendar
|
||||
pyautogui
|
||||
pywin32
|
||||
pyperclip
|
||||
pyperclip
|
||||
uiautomation
|
||||
@@ -21,12 +21,10 @@
|
||||
# ==================== 标准库导入 ====================
|
||||
import functools
|
||||
import json
|
||||
import logging
|
||||
import logging.handlers
|
||||
import math
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from datetime import datetime, timedelta
|
||||
@@ -71,7 +69,6 @@ except ImportError:
|
||||
_APP_DATA_DIR = os.path.join(os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'), 'LeaveApproval')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||||
_LOG_DIR = os.path.join(_APP_DATA_DIR, 'logs')
|
||||
|
||||
# ---------- OA 系统 ----------
|
||||
BASE_URL = "https://oa.37du.co"
|
||||
@@ -88,67 +85,23 @@ LEAVE_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_leave_reco
|
||||
DEFAULT_PAGE_SIZE = 15
|
||||
|
||||
|
||||
# ==================== 日志配置 ====================
|
||||
_console_fmt = "%(asctime)s | %(levelname)-7s | %(name)s | %(message)s"
|
||||
_file_fmt = "%(asctime)s | %(levelname)-7s | %(name)s | %(filename)s:%(lineno)d | %(message)s"
|
||||
_date_fmt = "%Y-%m-%d %H:%M:%S"
|
||||
# ==================== 日志(影刀环境用 print 替代 logging) ====================
|
||||
class _PrintLogger:
|
||||
"""简易日志器,用 print 输出,兼容原有 logger.xxx(msg, *args) 调用。"""
|
||||
def debug(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
_initialized = False
|
||||
def info(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def warning(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def error(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
|
||||
class _ColoredFormatter(logging.Formatter):
|
||||
_colors = {
|
||||
logging.DEBUG: "\033[36m",
|
||||
logging.INFO: "\033[32m",
|
||||
logging.WARNING: "\033[33m",
|
||||
logging.ERROR: "\033[31m",
|
||||
logging.CRITICAL: "\033[35m",
|
||||
}
|
||||
_reset = "\033[0m"
|
||||
|
||||
def format(self, record: logging.LogRecord) -> str:
|
||||
color = self._colors.get(record.levelno, "")
|
||||
orig_levelname = record.levelname
|
||||
record.levelname = f"{color}{record.levelname}{self._reset}"
|
||||
result = super().format(record)
|
||||
record.levelname = orig_levelname
|
||||
return result
|
||||
|
||||
|
||||
def setup_logging(level: int = logging.INFO, log_dir: str = None, log_file: bool = True) -> None:
|
||||
global _initialized
|
||||
if _initialized:
|
||||
return
|
||||
|
||||
logger = logging.getLogger()
|
||||
logger.setLevel(level)
|
||||
logger.handlers.clear()
|
||||
|
||||
console_handler = logging.StreamHandler(sys.stdout)
|
||||
console_handler.setLevel(level)
|
||||
console_handler.setFormatter(_ColoredFormatter(_console_fmt, datefmt=_date_fmt))
|
||||
logger.addHandler(console_handler)
|
||||
|
||||
if log_file:
|
||||
if log_dir is None:
|
||||
log_dir = _LOG_DIR
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
log_path = os.path.join(log_dir, f"app_{datetime.now().strftime('%Y%m%d')}.log")
|
||||
file_handler = logging.handlers.RotatingFileHandler(
|
||||
log_path, maxBytes=5 * 1024 * 1024, backupCount=5, encoding="utf-8"
|
||||
)
|
||||
file_handler.setLevel(logging.DEBUG)
|
||||
file_handler.setFormatter(logging.Formatter(_file_fmt, datefmt=_date_fmt))
|
||||
logger.addHandler(file_handler)
|
||||
|
||||
_initialized = True
|
||||
|
||||
|
||||
def get_logger(name: str) -> logging.Logger:
|
||||
return logging.getLogger(name)
|
||||
|
||||
|
||||
logger = get_logger("leave_approval")
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 重试装饰器 ====================
|
||||
@@ -180,7 +133,9 @@ def retry(max_attempts: int = 3) -> Callable:
|
||||
logger.warning("%s 第 %d 次执行失败: %s,%.2f 秒后重试", func.__name__, attempt, e, delay)
|
||||
time.sleep(delay)
|
||||
|
||||
raise RetryExhaustedError(f"{func.__name__} failed after {max_attempts} attempts") from last_exc
|
||||
raise RetryExhaustedError(
|
||||
f"{func.__name__} failed after {max_attempts} attempts, last error: {last_exc}"
|
||||
) from last_exc
|
||||
return wrapper
|
||||
return decorator
|
||||
|
||||
@@ -444,12 +399,41 @@ def get_leave_records(session, staff_id, begin_date, end_date, page_size=DEFAULT
|
||||
|
||||
# ==================== 排班/打卡解析 ====================
|
||||
def parse_attendance_html(html):
|
||||
# 实际接口返回的 HTML 中 data-temp 用单引号(data-temp='2026-08-04'),需同时兼容单/双引号
|
||||
pattern = r'<a[^>]*data-temp=["\']([^"\']+)["\'][^>]*>([^<]+)</a>'
|
||||
matches = re.findall(pattern, 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 = {}
|
||||
for date, shift in matches:
|
||||
result[date.strip()] = shift.strip()
|
||||
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
|
||||
|
||||
|
||||
@@ -700,7 +684,14 @@ def resolve_sso_params(browser, sso_url, wait_timeout=20):
|
||||
|
||||
|
||||
# ==================== 审批引擎 ====================
|
||||
def _check_browser_deps():
|
||||
"""检查浏览器自动化依赖是否就绪,缺失时给出清晰提示。"""
|
||||
if ChromiumPage is None or SessionPage is None:
|
||||
raise RuntimeError("DrissionPage 未安装,请运行: pip install DrissionPage")
|
||||
|
||||
|
||||
def _get_browser_and_session(subject):
|
||||
_check_browser_deps()
|
||||
saved_session = load_saved_session()
|
||||
if saved_session is not None and is_session_valid(saved_session, subject):
|
||||
logger.info("复用已保存的登录会话,跳过登录")
|
||||
@@ -780,29 +771,50 @@ def _is_dingtalk_foreground():
|
||||
|
||||
|
||||
def _activate_dingtalk():
|
||||
"""激活钉钉窗口:Ctrl+D 优先,失败回退 win32。已在前台则跳过(Ctrl+D 是 toggle)。"""
|
||||
"""激活钉钉窗口:Ctrl+D 唤起托盘中的钉钉 -> win32 置前 -> 点击确保焦点。"""
|
||||
if _is_dingtalk_foreground():
|
||||
logger.info("钉钉窗口已在前台,跳过激活")
|
||||
return
|
||||
|
||||
# 先尝试找到已打开的钉钉窗口
|
||||
hwnd = None
|
||||
try:
|
||||
pyautogui.hotkey("ctrl", "d")
|
||||
time.sleep(1.0)
|
||||
if not _is_dingtalk_foreground():
|
||||
raise RuntimeError("Ctrl+D 未能激活")
|
||||
logger.info("通过 Ctrl+D 激活钉钉窗口")
|
||||
except Exception as e:
|
||||
logger.warning("Ctrl+D 激活失败(%s),回退到 win32 查窗口激活", e)
|
||||
hwnd = _find_dingtalk_hwnd()
|
||||
if win32gui.IsIconic(hwnd):
|
||||
win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
|
||||
time.sleep(0.3)
|
||||
pyautogui.press("alt")
|
||||
win32gui.SetForegroundWindow(hwnd)
|
||||
time.sleep(1.0)
|
||||
except RuntimeError:
|
||||
pass
|
||||
|
||||
if hwnd is None:
|
||||
# 钉钉在系统托盘,用 Ctrl+D 全局热键唤起
|
||||
pyautogui.hotkey("ctrl", "d")
|
||||
time.sleep(1.5)
|
||||
try:
|
||||
hwnd = _find_dingtalk_hwnd()
|
||||
except RuntimeError:
|
||||
raise RuntimeError("Ctrl+D 未能唤起钉钉窗口,请确认钉钉已启动并配置了 Ctrl+D 热键")
|
||||
|
||||
# win32 置前台
|
||||
if win32gui.IsIconic(hwnd):
|
||||
win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
|
||||
time.sleep(0.3)
|
||||
pyautogui.press("alt")
|
||||
win32gui.SetForegroundWindow(hwnd)
|
||||
time.sleep(1.0)
|
||||
|
||||
# 点击窗口中心确保键盘焦点落在钉钉上(SetForegroundWindow 只切前台,不保证键盘焦点)
|
||||
rect = win32gui.GetWindowRect(hwnd)
|
||||
cx = (rect[0] + rect[2]) // 2
|
||||
cy = (rect[1] + rect[3]) // 2
|
||||
pyautogui.click(cx, cy)
|
||||
time.sleep(0.5)
|
||||
|
||||
if _is_dingtalk_foreground():
|
||||
logger.info("钉钉窗口已激活")
|
||||
else:
|
||||
raise RuntimeError("无法激活钉钉窗口,请确认钉钉桌面端已启动并登录")
|
||||
|
||||
|
||||
def _send_dingtalk_text(target, text):
|
||||
"""搜索联系人并发送文本:激活 → Ctrl+Shift+F 搜索 → 回车进会话 → 粘贴 → 回车发送。"""
|
||||
"""搜索联系人并发送文本:激活 -> 搜索 -> 进会话 -> 点击输入框聚焦 -> 粘贴 -> 发送。"""
|
||||
_check_dingtalk_deps()
|
||||
_activate_dingtalk()
|
||||
# 搜索联系人
|
||||
@@ -812,9 +824,22 @@ def _send_dingtalk_text(target, text):
|
||||
pyautogui.hotkey("ctrl", "v")
|
||||
time.sleep(1.0)
|
||||
pyautogui.press("enter")
|
||||
time.sleep(1.0)
|
||||
time.sleep(2.5) # 焦点稳定到消息输入框
|
||||
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")
|
||||
@@ -897,7 +922,6 @@ def push_report(report, subject=""):
|
||||
|
||||
|
||||
def run_flow(subject, validate_doc, generate_report):
|
||||
setup_logging()
|
||||
logger.info("%s审批流程开始", subject)
|
||||
|
||||
browser, session, _ = _get_browser_and_session(subject)
|
||||
@@ -924,9 +948,14 @@ def run_flow(subject, validate_doc, generate_report):
|
||||
report = generate_report(results)
|
||||
print("\n" + report)
|
||||
|
||||
# 推送「通过项汇总」到钉钉(env 控制;无通过项或失败均不影响主流程)
|
||||
# 先推送摘要到钉钉
|
||||
push_report(build_push_summary(results, subject), subject)
|
||||
|
||||
# 有驳回/人工复核/失败时,再推送完整报告(含明细表格)
|
||||
has_detail = any(r.get("decision") != "通过" for r in results)
|
||||
if has_detail:
|
||||
push_report(report, subject)
|
||||
|
||||
save_browser_cookies(browser)
|
||||
logger.info("%s审批流程结束,共处理 %d 条", subject, len(results))
|
||||
return report
|
||||
@@ -1053,7 +1082,9 @@ def validate_doc(doc, session):
|
||||
leave_info["实际上班天数"] = actual_work_days
|
||||
leave_info["填报天数"] = fill_days
|
||||
|
||||
days_mismatch = abs(actual_work_days - fill_days) > 0.01
|
||||
# 请半天假(0.5天)仍占用1个排班上班日,故用向上取整比对:
|
||||
# 0.5天->1个工作日,1.0天->1个工作日,1.5天->2个工作日
|
||||
days_mismatch = actual_work_days != math.ceil(round(fill_days, 2))
|
||||
|
||||
if vacation_type in HOURLY_LEAVE_TYPES:
|
||||
# 按小时请假(如小时特假):不比对天数,只要请假当天落在排班上班日即可
|
||||
@@ -1114,8 +1145,30 @@ def _vtype(r):
|
||||
return info.get("假期类型") or "未知"
|
||||
|
||||
|
||||
def _format_detail(info):
|
||||
"""将 leave_info 字典格式化为易读的明细行。"""
|
||||
fields = [
|
||||
("请假人员", "请假人员"),
|
||||
("所属部门", "所属部门"),
|
||||
("假期类型", "假期类型"),
|
||||
("开始时间", "开始时间"),
|
||||
("结束时间", "结束时间"),
|
||||
("请假天数", "请假天数"),
|
||||
("请假小时", "请假小时"),
|
||||
("实际上班天数", "实际上班天数"),
|
||||
("填报天数", "填报天数"),
|
||||
("附件", "附件"),
|
||||
]
|
||||
parts = []
|
||||
for key, label in fields:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
parts.append(f"{label}={val}")
|
||||
return " | ".join(parts)
|
||||
|
||||
|
||||
def generate_report(results):
|
||||
"""生成请假审批报告:汇总行 + 通过名单 + 驳回清单 + 人工复核清单(+处理失败)。"""
|
||||
"""生成请假审批报告:汇总行 + 每条明细 + 驳回清单 + 人工复核清单(+处理失败)。"""
|
||||
passed = [r for r in results if r.get("decision") == "通过"]
|
||||
rejected = [r for r in results if r.get("decision") == "驳回"]
|
||||
review = [r for r in results if r.get("decision") == "人工复核"]
|
||||
@@ -1132,11 +1185,21 @@ def generate_report(results):
|
||||
"",
|
||||
]
|
||||
|
||||
if passed:
|
||||
names = "、".join(_name(r) for r in passed)
|
||||
lines.append(f"【通过】{len(passed)} 条:{names}")
|
||||
lines.append("")
|
||||
# ----- 明细清单(所有审批单的完整数据) -----
|
||||
lines.append("【审批明细】")
|
||||
for i, r in enumerate(results, 1):
|
||||
info = r.get("leave_info", {}) or {}
|
||||
decision = r.get("decision", "未知")
|
||||
note = r.get("note") or r.get("error") or ""
|
||||
lines.append(f" #{i} {_name(r)}({_vtype(r)})-> {decision}")
|
||||
detail = _format_detail(info)
|
||||
if detail:
|
||||
lines.append(f" {detail}")
|
||||
if note:
|
||||
lines.append(f" 备注: {note}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 驳回清单 -----
|
||||
if rejected:
|
||||
lines.append("《请假审批自动驳回人员明细清单》")
|
||||
for i, r in enumerate(rejected, 1):
|
||||
@@ -1144,6 +1207,7 @@ def generate_report(results):
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 假期类型: {_vtype(r)} | 驳回原因: {reason}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 人工复核清单 -----
|
||||
if review:
|
||||
lines.append("《附件人工复核待办清单》")
|
||||
for i, r in enumerate(review, 1):
|
||||
@@ -1151,6 +1215,7 @@ def generate_report(results):
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 假期类型: {_vtype(r)} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 处理失败 -----
|
||||
if failed:
|
||||
lines.append("【处理失败】")
|
||||
for i, r in enumerate(failed, 1):
|
||||
|
||||
@@ -21,13 +21,10 @@
|
||||
# ==================== 标准库导入 ====================
|
||||
import functools
|
||||
import json
|
||||
import logging
|
||||
import logging.handlers
|
||||
import math
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from datetime import datetime, timedelta
|
||||
@@ -72,7 +69,6 @@ except ImportError:
|
||||
_APP_DATA_DIR = os.path.join(os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'), 'OvertimeApproval')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||||
_LOG_DIR = os.path.join(_APP_DATA_DIR, 'logs')
|
||||
|
||||
# ---------- OA 系统 ----------
|
||||
BASE_URL = "https://oa.37du.co"
|
||||
@@ -95,67 +91,23 @@ OT_MIN_HOURS = 1
|
||||
DEFAULT_PAGE_SIZE = 15
|
||||
|
||||
|
||||
# ==================== 日志配置 ====================
|
||||
_console_fmt = "%(asctime)s | %(levelname)-7s | %(name)s | %(message)s"
|
||||
_file_fmt = "%(asctime)s | %(levelname)-7s | %(name)s | %(filename)s:%(lineno)d | %(message)s"
|
||||
_date_fmt = "%Y-%m-%d %H:%M:%S"
|
||||
# ==================== 日志(影刀环境用 print 替代 logging) ====================
|
||||
class _PrintLogger:
|
||||
"""简易日志器,用 print 输出,兼容原有 logger.xxx(msg, *args) 调用。"""
|
||||
def debug(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
_initialized = False
|
||||
def info(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def warning(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def error(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
|
||||
class _ColoredFormatter(logging.Formatter):
|
||||
_colors = {
|
||||
logging.DEBUG: "\033[36m",
|
||||
logging.INFO: "\033[32m",
|
||||
logging.WARNING: "\033[33m",
|
||||
logging.ERROR: "\033[31m",
|
||||
logging.CRITICAL: "\033[35m",
|
||||
}
|
||||
_reset = "\033[0m"
|
||||
|
||||
def format(self, record: logging.LogRecord) -> str:
|
||||
color = self._colors.get(record.levelno, "")
|
||||
orig_levelname = record.levelname
|
||||
record.levelname = f"{color}{record.levelname}{self._reset}"
|
||||
result = super().format(record)
|
||||
record.levelname = orig_levelname
|
||||
return result
|
||||
|
||||
|
||||
def setup_logging(level: int = logging.INFO, log_dir: str = None, log_file: bool = True) -> None:
|
||||
global _initialized
|
||||
if _initialized:
|
||||
return
|
||||
|
||||
logger = logging.getLogger()
|
||||
logger.setLevel(level)
|
||||
logger.handlers.clear()
|
||||
|
||||
console_handler = logging.StreamHandler(sys.stdout)
|
||||
console_handler.setLevel(level)
|
||||
console_handler.setFormatter(_ColoredFormatter(_console_fmt, datefmt=_date_fmt))
|
||||
logger.addHandler(console_handler)
|
||||
|
||||
if log_file:
|
||||
if log_dir is None:
|
||||
log_dir = _LOG_DIR
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
log_path = os.path.join(log_dir, f"app_{datetime.now().strftime('%Y%m%d')}.log")
|
||||
file_handler = logging.handlers.RotatingFileHandler(
|
||||
log_path, maxBytes=5 * 1024 * 1024, backupCount=5, encoding="utf-8"
|
||||
)
|
||||
file_handler.setLevel(logging.DEBUG)
|
||||
file_handler.setFormatter(logging.Formatter(_file_fmt, datefmt=_date_fmt))
|
||||
logger.addHandler(file_handler)
|
||||
|
||||
_initialized = True
|
||||
|
||||
|
||||
def get_logger(name: str) -> logging.Logger:
|
||||
return logging.getLogger(name)
|
||||
|
||||
|
||||
logger = get_logger("overtime_approval")
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 重试装饰器 ====================
|
||||
@@ -187,7 +139,9 @@ def retry(max_attempts: int = 3) -> Callable:
|
||||
logger.warning("%s 第 %d 次执行失败: %s,%.2f 秒后重试", func.__name__, attempt, e, delay)
|
||||
time.sleep(delay)
|
||||
|
||||
raise RetryExhaustedError(f"{func.__name__} failed after {max_attempts} attempts") from last_exc
|
||||
raise RetryExhaustedError(
|
||||
f"{func.__name__} failed after {max_attempts} attempts, last error: {last_exc}"
|
||||
) from last_exc
|
||||
return wrapper
|
||||
return decorator
|
||||
|
||||
@@ -451,11 +405,49 @@ def get_leave_records(session, staff_id, begin_date, end_date, page_size=DEFAULT
|
||||
|
||||
# ==================== 排班/打卡解析 ====================
|
||||
def parse_attendance_html(html):
|
||||
pattern = r'<a[^>]*data-temp="([^"]+)"[^>]*>([^<]+)</a>'
|
||||
matches = re.findall(pattern, 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:
|
||||
logger.warning("排班 HTML 为空")
|
||||
return {}
|
||||
|
||||
result = {}
|
||||
for date, shift in matches:
|
||||
result[date.strip()] = shift.strip()
|
||||
# 匹配含 data-temp 属性的 <a> 标签,兼容单引号和双引号
|
||||
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
|
||||
|
||||
if not result:
|
||||
logger.warning("排班 HTML 解析失败,未匹配到任何数据。HTML 片段(前500字符): %s", html[:500])
|
||||
else:
|
||||
logger.debug("排班解析: 共 %d 条", len(result))
|
||||
|
||||
return result
|
||||
|
||||
|
||||
@@ -692,7 +684,14 @@ def resolve_sso_params(browser, sso_url, wait_timeout=20):
|
||||
|
||||
|
||||
# ==================== 审批引擎 ====================
|
||||
def _check_browser_deps():
|
||||
"""检查浏览器自动化依赖是否就绪,缺失时给出清晰提示。"""
|
||||
if ChromiumPage is None or SessionPage is None:
|
||||
raise RuntimeError("DrissionPage 未安装,请运行: pip install DrissionPage")
|
||||
|
||||
|
||||
def _get_browser_and_session(subject):
|
||||
_check_browser_deps()
|
||||
saved_session = load_saved_session()
|
||||
if saved_session is not None and is_session_valid(saved_session, subject):
|
||||
logger.info("复用已保存的登录会话,跳过登录")
|
||||
@@ -772,29 +771,50 @@ def _is_dingtalk_foreground():
|
||||
|
||||
|
||||
def _activate_dingtalk():
|
||||
"""激活钉钉窗口:Ctrl+D 优先,失败回退 win32。已在前台则跳过(Ctrl+D 是 toggle)。"""
|
||||
"""激活钉钉窗口:Ctrl+D 唤起托盘中的钉钉 -> win32 置前 -> 点击确保焦点。"""
|
||||
if _is_dingtalk_foreground():
|
||||
logger.info("钉钉窗口已在前台,跳过激活")
|
||||
return
|
||||
|
||||
# 先尝试找到已打开的钉钉窗口
|
||||
hwnd = None
|
||||
try:
|
||||
pyautogui.hotkey("ctrl", "d")
|
||||
time.sleep(1.0)
|
||||
if not _is_dingtalk_foreground():
|
||||
raise RuntimeError("Ctrl+D 未能激活")
|
||||
logger.info("通过 Ctrl+D 激活钉钉窗口")
|
||||
except Exception as e:
|
||||
logger.warning("Ctrl+D 激活失败(%s),回退到 win32 查窗口激活", e)
|
||||
hwnd = _find_dingtalk_hwnd()
|
||||
if win32gui.IsIconic(hwnd):
|
||||
win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
|
||||
time.sleep(0.3)
|
||||
pyautogui.press("alt")
|
||||
win32gui.SetForegroundWindow(hwnd)
|
||||
time.sleep(1.0)
|
||||
except RuntimeError:
|
||||
pass
|
||||
|
||||
if hwnd is None:
|
||||
# 钉钉在系统托盘,用 Ctrl+D 全局热键唤起
|
||||
pyautogui.hotkey("ctrl", "d")
|
||||
time.sleep(1.5)
|
||||
try:
|
||||
hwnd = _find_dingtalk_hwnd()
|
||||
except RuntimeError:
|
||||
raise RuntimeError("Ctrl+D 未能唤起钉钉窗口,请确认钉钉已启动并配置了 Ctrl+D 热键")
|
||||
|
||||
# win32 置前台
|
||||
if win32gui.IsIconic(hwnd):
|
||||
win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
|
||||
time.sleep(0.3)
|
||||
pyautogui.press("alt")
|
||||
win32gui.SetForegroundWindow(hwnd)
|
||||
time.sleep(1.0)
|
||||
|
||||
# 点击窗口中心确保键盘焦点落在钉钉上(SetForegroundWindow 只切前台,不保证键盘焦点)
|
||||
rect = win32gui.GetWindowRect(hwnd)
|
||||
cx = (rect[0] + rect[2]) // 2
|
||||
cy = (rect[1] + rect[3]) // 2
|
||||
pyautogui.click(cx, cy)
|
||||
time.sleep(0.5)
|
||||
|
||||
if _is_dingtalk_foreground():
|
||||
logger.info("钉钉窗口已激活")
|
||||
else:
|
||||
raise RuntimeError("无法激活钉钉窗口,请确认钉钉桌面端已启动并登录")
|
||||
|
||||
|
||||
def _send_dingtalk_text(target, text):
|
||||
"""搜索联系人并发送文本:激活 → Ctrl+Shift+F 搜索 → 回车进会话 → 粘贴 → 回车发送。"""
|
||||
"""搜索联系人并发送文本:激活 -> 搜索 -> 进会话 -> 点击输入框聚焦 -> 粘贴 -> 发送。"""
|
||||
_check_dingtalk_deps()
|
||||
_activate_dingtalk()
|
||||
# 搜索联系人
|
||||
@@ -804,9 +824,22 @@ def _send_dingtalk_text(target, text):
|
||||
pyautogui.hotkey("ctrl", "v")
|
||||
time.sleep(1.0)
|
||||
pyautogui.press("enter")
|
||||
time.sleep(1.0)
|
||||
time.sleep(2.5) # 焦点稳定到消息输入框
|
||||
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")
|
||||
@@ -889,7 +922,6 @@ def push_report(report, subject=""):
|
||||
|
||||
|
||||
def run_flow(subject, validate_doc, generate_report):
|
||||
setup_logging()
|
||||
logger.info("%s审批流程开始", subject)
|
||||
|
||||
browser, session, _ = _get_browser_and_session(subject)
|
||||
@@ -916,9 +948,14 @@ def run_flow(subject, validate_doc, generate_report):
|
||||
report = generate_report(results)
|
||||
print("\n" + report)
|
||||
|
||||
# 推送「通过项汇总」到钉钉(env 控制;无通过项或失败均不影响主流程)
|
||||
# 先推送摘要到钉钉
|
||||
push_report(build_push_summary(results, subject), subject)
|
||||
|
||||
# 有驳回/人工复核/失败时,再推送完整报告(含明细表格)
|
||||
has_detail = any(r.get("decision") != "通过" for r in results)
|
||||
if has_detail:
|
||||
push_report(report, subject)
|
||||
|
||||
save_browser_cookies(browser)
|
||||
logger.info("%s审批流程结束,共处理 %d 条", subject, len(results))
|
||||
return report
|
||||
@@ -1231,13 +1268,49 @@ def _otype(r):
|
||||
return info.get("加班类型") or "未知"
|
||||
|
||||
|
||||
def _format_detail(info):
|
||||
"""将 overtime_info 字典格式化为易读的明细行。"""
|
||||
fields = [
|
||||
("加班人员", "加班人员"),
|
||||
("所属部门", "所属部门"),
|
||||
("加班类型", "加班类型"),
|
||||
("补贴类型", "补贴类型"),
|
||||
("加班日期", "加班日期"),
|
||||
("加班开始时间", "加班开始时间"),
|
||||
("加班结束时间", "加班结束时间"),
|
||||
("加班时长(小时)", "加班时长"),
|
||||
("加班天数(天)", "加班天数"),
|
||||
("系统判断加班时长(小时)", "系统判定时长"),
|
||||
("系统判断加班天数(天)", "系统判定天数"),
|
||||
("系统判定加班时间", "系统判定时间"),
|
||||
("加班当天班次", "当天班次"),
|
||||
("当日最早打卡", "最早打卡"),
|
||||
("当日最晚打卡", "最晚打卡"),
|
||||
("次日最早打卡", "次日最早打卡"),
|
||||
("计算加班时长(小时)", "计算时长"),
|
||||
("弹性扣减(小时)", "弹性扣减"),
|
||||
("有效加班时长(小时)", "有效时长"),
|
||||
("弹性额度D(小时)", "弹性额度D"),
|
||||
("打卡时间间隔(小时)", "打卡间隔"),
|
||||
("申报天数(天)", "申报天数"),
|
||||
("打卡备注", "打卡备注"),
|
||||
]
|
||||
parts = []
|
||||
for key, label in fields:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
parts.append(f"{label}={val}")
|
||||
return " | ".join(parts)
|
||||
|
||||
|
||||
def generate_report(results):
|
||||
"""
|
||||
生成加班审批报告:汇总行 + 通过名单 + 驳回清单 + 人工复核清单(+处理失败)。
|
||||
生成加班审批报告:汇总行 + 每条明细 + 驳回清单 + 人工复核清单(+处理失败)。
|
||||
|
||||
输出两份清单:
|
||||
《加班审批自动驳回人员明细清单》:员工姓名、加班类型、驳回原因
|
||||
《附件人工复核待办清单》:员工姓名、加班类型、详情页链接(供人工打开查看附件)
|
||||
输出:
|
||||
- 每条审批的完整明细(含加班日期、时长、打卡、排班等)
|
||||
- 《加班审批自动驳回人员明细清单》:员工姓名、加班类型、驳回原因
|
||||
- 《附件人工复核待办清单》:员工姓名、加班类型、详情页链接
|
||||
"""
|
||||
passed = [r for r in results if r.get("decision") == "通过"]
|
||||
rejected = [r for r in results if r.get("decision") == "驳回"]
|
||||
@@ -1255,11 +1328,21 @@ def generate_report(results):
|
||||
"",
|
||||
]
|
||||
|
||||
if passed:
|
||||
names = "、".join(_name(r) for r in passed)
|
||||
lines.append(f"【通过】{len(passed)} 条:{names}")
|
||||
lines.append("")
|
||||
# ----- 明细清单(所有审批单的完整数据) -----
|
||||
lines.append("【审批明细】")
|
||||
for i, r in enumerate(results, 1):
|
||||
info = r.get("overtime_info", {}) or {}
|
||||
decision = r.get("decision", "未知")
|
||||
note = r.get("note") or r.get("error") or ""
|
||||
lines.append(f" #{i} {_name(r)}({_otype(r)})-> {decision}")
|
||||
detail = _format_detail(info)
|
||||
if detail:
|
||||
lines.append(f" {detail}")
|
||||
if note:
|
||||
lines.append(f" 备注: {note}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 驳回清单 -----
|
||||
if rejected:
|
||||
lines.append("《加班审批自动驳回人员明细清单》")
|
||||
for i, r in enumerate(rejected, 1):
|
||||
@@ -1267,6 +1350,7 @@ def generate_report(results):
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 驳回原因: {reason}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 人工复核清单 -----
|
||||
if review:
|
||||
lines.append("《附件人工复核待办清单》")
|
||||
for i, r in enumerate(review, 1):
|
||||
@@ -1274,6 +1358,7 @@ def generate_report(results):
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 处理失败 -----
|
||||
if failed:
|
||||
lines.append("【处理失败】")
|
||||
for i, r in enumerate(failed, 1):
|
||||
|
||||
Reference in New Issue
Block a user