rescue: 断电事故后工作区全量备份
This commit is contained in:
@@ -1,302 +1,302 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.approval_flow
|
||||
@FileName: approval_flow.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 23:52
|
||||
@Description: 公共审批引擎:登录(复用登录态)-> 查待办 -> 解析 SSO -> 获取表单 -> 校验 -> 生成报告
|
||||
加班/请假共用,业务差异通过 subject + validate_doc + generate_report 注入
|
||||
@Version: 1.2.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Callable, Dict, List
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging
|
||||
from app.utils.intelligent_retry import retry
|
||||
|
||||
from app.service.hrbp.oa.common.login import oa_login
|
||||
from app.service.hrbp.oa.common.session_manager import (
|
||||
init_session_from_page,
|
||||
refresh_session_cookies,
|
||||
load_saved_session,
|
||||
save_browser_cookies,
|
||||
create_browser_with_saved_cookies,
|
||||
is_session_valid,
|
||||
COOKIE_FILE,
|
||||
)
|
||||
from app.service.hrbp.oa.common.oa_api import (
|
||||
OALoginExpiredError,
|
||||
get_documents,
|
||||
get_wf_activity_by_task_id,
|
||||
extract_form_id,
|
||||
get_business_data,
|
||||
)
|
||||
from app.service.hrbp.oa.common.sso import resolve_sso_params
|
||||
from app.service.hrbp.oa.common.notify import push_report, build_push_summary
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
# ==================== 真实审批提交(默认关闭) ====================
|
||||
# 仅自动提交"同意"(校验通过):驳回/校验不通过未处理一律不自动提交,保留待人工处理
|
||||
_APPROVE_BUTTONS = {
|
||||
"通过": ("#chooseSubmit", "同意"),
|
||||
}
|
||||
|
||||
|
||||
def _approve_enabled() -> bool:
|
||||
"""是否启用真实审批提交(同意/退回申请人)。默认关闭。
|
||||
开关:.env 中 overtime_approve_enabled=true/false。
|
||||
未确认校验准确性前保持关闭,确认后再启用。"""
|
||||
from app.common.env import load_app_env
|
||||
load_app_env()
|
||||
return os.getenv("overtime_approve_enabled", "false").lower() == "true"
|
||||
|
||||
|
||||
def _find_button(browser, selector: str, timeout: float = 3.0):
|
||||
"""在详情页查找审批按钮:优先主文档,找不到则遍历 iframe(部分详情页按钮在 iframe 内)。"""
|
||||
try:
|
||||
btn = browser.ele(selector, timeout=timeout)
|
||||
if btn:
|
||||
return btn
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
frames = browser.get_frames()
|
||||
except Exception:
|
||||
frames = []
|
||||
for frame in frames:
|
||||
try:
|
||||
btn = frame.ele(selector, timeout=1)
|
||||
if btn:
|
||||
return btn
|
||||
except Exception:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def submit_approval(browser, decision: str) -> Dict[str, str]:
|
||||
"""
|
||||
按校验结论在流程详情页执行真实审批提交。
|
||||
|
||||
Args:
|
||||
browser: 停留在详情页的 ChromiumPage
|
||||
decision: 校验决策(通过/校验不通过未处理;其余决策不提交)
|
||||
|
||||
Returns:
|
||||
{"action": "同意"/"退回申请人"/"-", "ok": "true"/"false", "message": ...}
|
||||
"""
|
||||
if decision not in _APPROVE_BUTTONS:
|
||||
return {"action": "-", "ok": "true", "message": "无需提交"}
|
||||
selector, label = _APPROVE_BUTTONS[decision]
|
||||
try:
|
||||
btn = _find_button(browser, selector)
|
||||
if btn is None:
|
||||
msg = f"未找到审批按钮 {selector}({label}),可能页面未加载完成或按钮在未识别的 iframe 中"
|
||||
logger.error(msg)
|
||||
return {"action": label, "ok": "false", "message": msg}
|
||||
logger.info("点击审批按钮: %s(%s)", selector, label)
|
||||
btn.click()
|
||||
# 确认按钮为唯一 id,主文档直接用 ele() 高频等待其动态出现,避免 _find_button 的 iframe 遍历开销
|
||||
# 普通流程确认框 #custom-confirm-modal-ok 为主;选人弹窗 .wf-select-people 为特殊单据才触发
|
||||
def _visible(el):
|
||||
try:
|
||||
return el.states.is_displayed
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
confirm = None
|
||||
for _ in range(20):
|
||||
c1 = browser.ele("#custom-confirm-modal-ok", timeout=0.2)
|
||||
if c1 is not None and _visible(c1):
|
||||
confirm = c1
|
||||
break
|
||||
# 选人弹窗(容器常驻但默认隐藏,仅弹出时才可见)兜底
|
||||
people = browser.ele(".wf-select-people", timeout=0.2)
|
||||
if people is not None and _visible(people):
|
||||
try:
|
||||
c2 = people.ele("css:.modal-footer button.btn.btn-primary", timeout=0.2)
|
||||
except Exception:
|
||||
c2 = None
|
||||
if c2 is not None and _visible(c2):
|
||||
confirm = c2
|
||||
break
|
||||
time.sleep(0.2)
|
||||
if confirm is None:
|
||||
msg = "未找到确认框确定按钮(#custom-confirm-modal-ok 或 .modal-footer .btn.btn-primary),审批未提交"
|
||||
logger.error(msg)
|
||||
return {"action": label, "ok": "false", "message": msg}
|
||||
confirm.click()
|
||||
logger.info("已点击确认框确定按钮")
|
||||
time.sleep(1.0)
|
||||
return {"action": label, "ok": "true", "message": f"已执行审批提交[{label}]"}
|
||||
except Exception as e:
|
||||
logger.error("审批提交失败[%s]: %s", label, str(e))
|
||||
return {"action": label, "ok": "false", "message": f"审批提交[{label}]失败: {e}"}
|
||||
|
||||
|
||||
@retry(max_attempts=3)
|
||||
def _login():
|
||||
"""完整登录 OA(失败自动重试,最多 3 次)"""
|
||||
return oa_login()
|
||||
|
||||
|
||||
def _get_browser_and_session(subject: str):
|
||||
"""
|
||||
获取浏览器和会话:优先复用已保存的登录 cookies,无效或不存在时才完整登录。
|
||||
|
||||
Returns:
|
||||
(browser, session, is_fresh_login)
|
||||
"""
|
||||
saved_session = load_saved_session()
|
||||
if saved_session is not None and is_session_valid(saved_session, subject):
|
||||
logger.info("复用已保存的登录会话,跳过登录")
|
||||
browser = create_browser_with_saved_cookies()
|
||||
return browser, saved_session, False
|
||||
|
||||
browser = _login()
|
||||
session = init_session_from_page(browser)
|
||||
save_browser_cookies(browser)
|
||||
return browser, session, True
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(OALoginExpiredError,))
|
||||
def _fetch_documents(session, subject: str) -> List[Dict[str, Any]]:
|
||||
"""按主题拉取待办单据(失败自动重试,最多 3 次;登录失效直接上抛交给上层重登)"""
|
||||
return get_documents(session, subject=subject)
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(OALoginExpiredError,))
|
||||
def _fetch_doc_detail(browser, session, doc: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
解析单据详情:SSO 取 taskId/businessKey -> WfActivity 取 formId -> WorkformEngine 取表单数据。
|
||||
|
||||
Args:
|
||||
browser: 已登录的 ChromiumPage 对象(用于执行 SSO 的 JS 跳转)
|
||||
session: 已登录的 SessionPage 对象(用于后台 API 请求)
|
||||
doc: 单据信息(包含 detail_url)
|
||||
|
||||
Returns:
|
||||
单据信息 + taskId/businessKey/formId/formData
|
||||
"""
|
||||
detail_url = doc.get("detail_url", "")
|
||||
if not detail_url:
|
||||
raise RuntimeError(f"单据无详情链接: {doc.get('title')}")
|
||||
|
||||
# Step 1: 浏览器打开 SSO 链接,从重定向后的 URL 提取 taskId 和 businessKey
|
||||
sso_params = resolve_sso_params(browser, detail_url)
|
||||
task_id = sso_params["taskId"]
|
||||
business_key = sso_params["businessKey"]
|
||||
logger.info("SSO 解析完成: taskId=%s, businessKey=%s", task_id, business_key)
|
||||
|
||||
# SSO 的 linkLogin 在 hr 域产生了新的会话 cookie,先同步回 SessionPage
|
||||
refresh_session_cookies(session, browser)
|
||||
|
||||
# Step 2: 通过 taskId 获取 formId
|
||||
wf_activity_data = get_wf_activity_by_task_id(session, task_id)
|
||||
form_id = extract_form_id(wf_activity_data)
|
||||
|
||||
# Step 3: 通过 businessKey + formId 获取表单数据
|
||||
form_data = get_business_data(session, business_key, form_id)
|
||||
|
||||
return {
|
||||
**doc,
|
||||
"taskId": task_id,
|
||||
"businessKey": business_key,
|
||||
"formId": form_id,
|
||||
"formData": form_data,
|
||||
}
|
||||
|
||||
|
||||
def run_flow(
|
||||
subject: str,
|
||||
validate_doc: Callable[[Dict[str, Any], Any], Dict[str, Any]],
|
||||
generate_report: Callable[[List[Dict[str, Any]]], str],
|
||||
) -> str:
|
||||
"""
|
||||
公共审批流程:登录(优先复用已保存会话)-> 查待办 -> 逐单解析详情并校验 -> 生成报告。
|
||||
|
||||
Args:
|
||||
subject: 待办标题关键字,如 "加班" / "请假"
|
||||
validate_doc: 单张单据的校验函数,签名为 (doc, session) -> result
|
||||
generate_report: 校验结果报告生成函数
|
||||
|
||||
Returns:
|
||||
报告文本
|
||||
"""
|
||||
setup_logging()
|
||||
logger.info("%s审批流程开始", subject)
|
||||
|
||||
# 运行中遇 OA 登录态失效(待办/表单接口返回登录页):删除 cookie、自动重新登录并重跑一遍(最多 2 轮)
|
||||
for login_attempt in range(2):
|
||||
browser, session, _ = _get_browser_and_session(subject)
|
||||
try:
|
||||
docs = _fetch_documents(session, subject)
|
||||
logger.info("共获取%s待办 %d 条", subject, len(docs))
|
||||
|
||||
results = []
|
||||
for doc in docs:
|
||||
try:
|
||||
doc_detail = _fetch_doc_detail(browser, session, doc)
|
||||
result = validate_doc(doc_detail, session)
|
||||
# 真实审批提交:仅当 overtime_approve_enabled=true 时执行(默认关闭)
|
||||
if _approve_enabled():
|
||||
orig_decision = result.get("decision")
|
||||
submit = submit_approval(browser, orig_decision)
|
||||
result["审批动作"] = submit["action"]
|
||||
# 提交失败兜底:单据在 OA 中状态未变,不能仍标为通过/校验不通过未处理,
|
||||
# 归为「异常」并附机器结论,交由人工跟进
|
||||
if submit["ok"] == "false":
|
||||
result["decision"] = "异常"
|
||||
result["note"] = (
|
||||
f"机器结论[{orig_decision}]但审批提交失败:{submit['message']}"
|
||||
)
|
||||
result["审批结果"] = f"{submit['message']}"
|
||||
logger.info("审批提交: %s %s", submit["action"], result["审批结果"])
|
||||
results.append(result)
|
||||
logger.info(
|
||||
"已校验: %s - %s -> %s",
|
||||
result["creator"], result["title"], result["decision"],
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error("处理单据失败: %s, 错误: %s", doc.get("title"), str(e))
|
||||
results.append({
|
||||
"creator": doc.get("creator", "未知"),
|
||||
"title": doc.get("title", "未知"),
|
||||
"decision": "失败",
|
||||
"error": str(e),
|
||||
})
|
||||
|
||||
report = generate_report(results)
|
||||
print("\n" + report)
|
||||
|
||||
# 先推送摘要到钉钉
|
||||
push_report(build_push_summary(results, subject), subject)
|
||||
|
||||
# 再推送完整报告(含审批明细),保证请假/加班通知都展示具体审批明细
|
||||
push_report(report, subject)
|
||||
|
||||
# 保存最新 cookies(SSO 已刷新 hr 域会话,供下次运行免登录复用)
|
||||
save_browser_cookies(browser)
|
||||
|
||||
logger.info("%s审批流程结束,共处理 %d 条", subject, len(results))
|
||||
return report
|
||||
except OALoginExpiredError as e:
|
||||
logger.warning("OA 登录态失效: %s", e)
|
||||
if login_attempt == 0:
|
||||
try:
|
||||
if os.path.exists(COOKIE_FILE):
|
||||
os.remove(COOKIE_FILE)
|
||||
logger.info("已删除失效 cookie,自动重新登录后重跑")
|
||||
except Exception:
|
||||
pass
|
||||
continue
|
||||
raise
|
||||
finally:
|
||||
if browser is not None:
|
||||
try:
|
||||
browser.quit()
|
||||
except Exception:
|
||||
pass
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.approval_flow
|
||||
@FileName: approval_flow.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 23:52
|
||||
@Description: 公共审批引擎:登录(复用登录态)-> 查待办 -> 解析 SSO -> 获取表单 -> 校验 -> 生成报告
|
||||
加班/请假共用,业务差异通过 subject + validate_doc + generate_report 注入
|
||||
@Version: 1.2.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Callable, Dict, List
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging
|
||||
from app.utils.intelligent_retry import retry
|
||||
|
||||
from app.service.hrbp.oa.common.login import oa_login
|
||||
from app.service.hrbp.oa.common.session_manager import (
|
||||
init_session_from_page,
|
||||
refresh_session_cookies,
|
||||
load_saved_session,
|
||||
save_browser_cookies,
|
||||
create_browser_with_saved_cookies,
|
||||
is_session_valid,
|
||||
COOKIE_FILE,
|
||||
)
|
||||
from app.service.hrbp.oa.common.oa_api import (
|
||||
OALoginExpiredError,
|
||||
get_documents,
|
||||
get_wf_activity_by_task_id,
|
||||
extract_form_id,
|
||||
get_business_data,
|
||||
)
|
||||
from app.service.hrbp.oa.common.sso import resolve_sso_params
|
||||
from app.service.hrbp.oa.common.notify import push_report, build_push_summary
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
# ==================== 真实审批提交(默认关闭) ====================
|
||||
# 仅自动提交"同意"(校验通过):驳回/校验不通过未处理一律不自动提交,保留待人工处理
|
||||
_APPROVE_BUTTONS = {
|
||||
"通过": ("#chooseSubmit", "同意"),
|
||||
}
|
||||
|
||||
|
||||
def _approve_enabled() -> bool:
|
||||
"""是否启用真实审批提交(同意/退回申请人)。默认关闭。
|
||||
开关:.env 中 overtime_approve_enabled=true/false。
|
||||
未确认校验准确性前保持关闭,确认后再启用。"""
|
||||
from app.common.env import load_app_env
|
||||
load_app_env()
|
||||
return os.getenv("overtime_approve_enabled", "false").lower() == "true"
|
||||
|
||||
|
||||
def _find_button(browser, selector: str, timeout: float = 3.0):
|
||||
"""在详情页查找审批按钮:优先主文档,找不到则遍历 iframe(部分详情页按钮在 iframe 内)。"""
|
||||
try:
|
||||
btn = browser.ele(selector, timeout=timeout)
|
||||
if btn:
|
||||
return btn
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
frames = browser.get_frames()
|
||||
except Exception:
|
||||
frames = []
|
||||
for frame in frames:
|
||||
try:
|
||||
btn = frame.ele(selector, timeout=1)
|
||||
if btn:
|
||||
return btn
|
||||
except Exception:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def submit_approval(browser, decision: str) -> Dict[str, str]:
|
||||
"""
|
||||
按校验结论在流程详情页执行真实审批提交。
|
||||
|
||||
Args:
|
||||
browser: 停留在详情页的 ChromiumPage
|
||||
decision: 校验决策(通过/校验不通过未处理;其余决策不提交)
|
||||
|
||||
Returns:
|
||||
{"action": "同意"/"退回申请人"/"-", "ok": "true"/"false", "message": ...}
|
||||
"""
|
||||
if decision not in _APPROVE_BUTTONS:
|
||||
return {"action": "-", "ok": "true", "message": "无需提交"}
|
||||
selector, label = _APPROVE_BUTTONS[decision]
|
||||
try:
|
||||
btn = _find_button(browser, selector)
|
||||
if btn is None:
|
||||
msg = f"未找到审批按钮 {selector}({label}),可能页面未加载完成或按钮在未识别的 iframe 中"
|
||||
logger.error(msg)
|
||||
return {"action": label, "ok": "false", "message": msg}
|
||||
logger.info("点击审批按钮: %s(%s)", selector, label)
|
||||
btn.click()
|
||||
# 确认按钮为唯一 id,主文档直接用 ele() 高频等待其动态出现,避免 _find_button 的 iframe 遍历开销
|
||||
# 普通流程确认框 #custom-confirm-modal-ok 为主;选人弹窗 .wf-select-people 为特殊单据才触发
|
||||
def _visible(el):
|
||||
try:
|
||||
return el.states.is_displayed
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
confirm = None
|
||||
for _ in range(20):
|
||||
c1 = browser.ele("#custom-confirm-modal-ok", timeout=0.2)
|
||||
if c1 is not None and _visible(c1):
|
||||
confirm = c1
|
||||
break
|
||||
# 选人弹窗(容器常驻但默认隐藏,仅弹出时才可见)兜底
|
||||
people = browser.ele(".wf-select-people", timeout=0.2)
|
||||
if people is not None and _visible(people):
|
||||
try:
|
||||
c2 = people.ele("css:.modal-footer button.btn.btn-primary", timeout=0.2)
|
||||
except Exception:
|
||||
c2 = None
|
||||
if c2 is not None and _visible(c2):
|
||||
confirm = c2
|
||||
break
|
||||
time.sleep(0.2)
|
||||
if confirm is None:
|
||||
msg = "未找到确认框确定按钮(#custom-confirm-modal-ok 或 .modal-footer .btn.btn-primary),审批未提交"
|
||||
logger.error(msg)
|
||||
return {"action": label, "ok": "false", "message": msg}
|
||||
confirm.click()
|
||||
logger.info("已点击确认框确定按钮")
|
||||
time.sleep(1.0)
|
||||
return {"action": label, "ok": "true", "message": f"已执行审批提交[{label}]"}
|
||||
except Exception as e:
|
||||
logger.error("审批提交失败[%s]: %s", label, str(e))
|
||||
return {"action": label, "ok": "false", "message": f"审批提交[{label}]失败: {e}"}
|
||||
|
||||
|
||||
@retry(max_attempts=3)
|
||||
def _login():
|
||||
"""完整登录 OA(失败自动重试,最多 3 次)"""
|
||||
return oa_login()
|
||||
|
||||
|
||||
def _get_browser_and_session(subject: str):
|
||||
"""
|
||||
获取浏览器和会话:优先复用已保存的登录 cookies,无效或不存在时才完整登录。
|
||||
|
||||
Returns:
|
||||
(browser, session, is_fresh_login)
|
||||
"""
|
||||
saved_session = load_saved_session()
|
||||
if saved_session is not None and is_session_valid(saved_session, subject):
|
||||
logger.info("复用已保存的登录会话,跳过登录")
|
||||
browser = create_browser_with_saved_cookies()
|
||||
return browser, saved_session, False
|
||||
|
||||
browser = _login()
|
||||
session = init_session_from_page(browser)
|
||||
save_browser_cookies(browser)
|
||||
return browser, session, True
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(OALoginExpiredError,))
|
||||
def _fetch_documents(session, subject: str) -> List[Dict[str, Any]]:
|
||||
"""按主题拉取待办单据(失败自动重试,最多 3 次;登录失效直接上抛交给上层重登)"""
|
||||
return get_documents(session, subject=subject)
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(OALoginExpiredError,))
|
||||
def _fetch_doc_detail(browser, session, doc: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
解析单据详情:SSO 取 taskId/businessKey -> WfActivity 取 formId -> WorkformEngine 取表单数据。
|
||||
|
||||
Args:
|
||||
browser: 已登录的 ChromiumPage 对象(用于执行 SSO 的 JS 跳转)
|
||||
session: 已登录的 SessionPage 对象(用于后台 API 请求)
|
||||
doc: 单据信息(包含 detail_url)
|
||||
|
||||
Returns:
|
||||
单据信息 + taskId/businessKey/formId/formData
|
||||
"""
|
||||
detail_url = doc.get("detail_url", "")
|
||||
if not detail_url:
|
||||
raise RuntimeError(f"单据无详情链接: {doc.get('title')}")
|
||||
|
||||
# Step 1: 浏览器打开 SSO 链接,从重定向后的 URL 提取 taskId 和 businessKey
|
||||
sso_params = resolve_sso_params(browser, detail_url)
|
||||
task_id = sso_params["taskId"]
|
||||
business_key = sso_params["businessKey"]
|
||||
logger.info("SSO 解析完成: taskId=%s, businessKey=%s", task_id, business_key)
|
||||
|
||||
# SSO 的 linkLogin 在 hr 域产生了新的会话 cookie,先同步回 SessionPage
|
||||
refresh_session_cookies(session, browser)
|
||||
|
||||
# Step 2: 通过 taskId 获取 formId
|
||||
wf_activity_data = get_wf_activity_by_task_id(session, task_id)
|
||||
form_id = extract_form_id(wf_activity_data)
|
||||
|
||||
# Step 3: 通过 businessKey + formId 获取表单数据
|
||||
form_data = get_business_data(session, business_key, form_id)
|
||||
|
||||
return {
|
||||
**doc,
|
||||
"taskId": task_id,
|
||||
"businessKey": business_key,
|
||||
"formId": form_id,
|
||||
"formData": form_data,
|
||||
}
|
||||
|
||||
|
||||
def run_flow(
|
||||
subject: str,
|
||||
validate_doc: Callable[[Dict[str, Any], Any], Dict[str, Any]],
|
||||
generate_report: Callable[[List[Dict[str, Any]]], str],
|
||||
) -> str:
|
||||
"""
|
||||
公共审批流程:登录(优先复用已保存会话)-> 查待办 -> 逐单解析详情并校验 -> 生成报告。
|
||||
|
||||
Args:
|
||||
subject: 待办标题关键字,如 "加班" / "请假"
|
||||
validate_doc: 单张单据的校验函数,签名为 (doc, session) -> result
|
||||
generate_report: 校验结果报告生成函数
|
||||
|
||||
Returns:
|
||||
报告文本
|
||||
"""
|
||||
setup_logging()
|
||||
logger.info("%s审批流程开始", subject)
|
||||
|
||||
# 运行中遇 OA 登录态失效(待办/表单接口返回登录页):删除 cookie、自动重新登录并重跑一遍(最多 2 轮)
|
||||
for login_attempt in range(2):
|
||||
browser, session, _ = _get_browser_and_session(subject)
|
||||
try:
|
||||
docs = _fetch_documents(session, subject)
|
||||
logger.info("共获取%s待办 %d 条", subject, len(docs))
|
||||
|
||||
results = []
|
||||
for doc in docs:
|
||||
try:
|
||||
doc_detail = _fetch_doc_detail(browser, session, doc)
|
||||
result = validate_doc(doc_detail, session)
|
||||
# 真实审批提交:仅当 overtime_approve_enabled=true 时执行(默认关闭)
|
||||
if _approve_enabled():
|
||||
orig_decision = result.get("decision")
|
||||
submit = submit_approval(browser, orig_decision)
|
||||
result["审批动作"] = submit["action"]
|
||||
# 提交失败兜底:单据在 OA 中状态未变,不能仍标为通过/校验不通过未处理,
|
||||
# 归为「异常」并附机器结论,交由人工跟进
|
||||
if submit["ok"] == "false":
|
||||
result["decision"] = "异常"
|
||||
result["note"] = (
|
||||
f"机器结论[{orig_decision}]但审批提交失败:{submit['message']}"
|
||||
)
|
||||
result["审批结果"] = f"{submit['message']}"
|
||||
logger.info("审批提交: %s %s", submit["action"], result["审批结果"])
|
||||
results.append(result)
|
||||
logger.info(
|
||||
"已校验: %s - %s -> %s",
|
||||
result["creator"], result["title"], result["decision"],
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error("处理单据失败: %s, 错误: %s", doc.get("title"), str(e))
|
||||
results.append({
|
||||
"creator": doc.get("creator", "未知"),
|
||||
"title": doc.get("title", "未知"),
|
||||
"decision": "失败",
|
||||
"error": str(e),
|
||||
})
|
||||
|
||||
report = generate_report(results)
|
||||
print("\n" + report)
|
||||
|
||||
# 先推送摘要到钉钉
|
||||
push_report(build_push_summary(results, subject), subject)
|
||||
|
||||
# 再推送完整报告(含审批明细),保证请假/加班通知都展示具体审批明细
|
||||
push_report(report, subject)
|
||||
|
||||
# 保存最新 cookies(SSO 已刷新 hr 域会话,供下次运行免登录复用)
|
||||
save_browser_cookies(browser)
|
||||
|
||||
logger.info("%s审批流程结束,共处理 %d 条", subject, len(results))
|
||||
return report
|
||||
except OALoginExpiredError as e:
|
||||
logger.warning("OA 登录态失效: %s", e)
|
||||
if login_attempt == 0:
|
||||
try:
|
||||
if os.path.exists(COOKIE_FILE):
|
||||
os.remove(COOKIE_FILE)
|
||||
logger.info("已删除失效 cookie,自动重新登录后重跑")
|
||||
except Exception:
|
||||
pass
|
||||
continue
|
||||
raise
|
||||
finally:
|
||||
if browser is not None:
|
||||
try:
|
||||
browser.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
Reference in New Issue
Block a user