feat: 新增轻量会话校验能力,优化登录态失效处理流程
1. 新增TODO_COUNT_URL轻量接口用于快速校验会话有效性 2. 定义OALoginExpiredError统一标识登录态失效异常 3. 重构会话校验逻辑,使用轻量接口替代拉取待办页校验 4. 为重试装饰器添加不重试异常配置,登录失效直接上抛 5. 全流程增加登录态失效自动重登机制,最多重试2次 6. 新增通用钉钉机器人推送工具类
This commit is contained in:
@@ -1,163 +1,44 @@
|
||||
员工排班
|
||||
|
||||
Request URL
|
||||
【加班审批】本次共审批 15 条加班申请。
|
||||
|
||||
https://hr.37du.co/RedseaPlatform/redmagicapi/rf_p_kq_count_SelectBanci/getExecutePageResult.mc
|
||||
通过 12 条,分别是:
|
||||
|
||||
Request Method
|
||||
集团管理中心李泽燕发起李泽燕的加班申请-延时加班
|
||||
|
||||
POST
|
||||
集团管理中心张晶晶发起张晶晶的加班申请-延时加班
|
||||
|
||||
treecode=cq37du&user_id=07b83185-6243-42bc-b79f-b81b4cffb471&sqlId=kq_count_SelectBanci&commonQuery=&commonQueryStr=&staff_ids=&person_status=1%2C4&post_no=&post_type=1&post_level=&identity=&showType=1&dateType=1&begin=2026-08-10&end=2026-08-16&bc_date=2026-08-14&base_code=37031376&staff_name=&start=0&sortType=&sortName=&pageNo=1&pageSize=15
|
||||
财务管理部张艳发起张艳的加班申请-延时加班
|
||||
|
||||
{
|
||||
"attributeMap": null,
|
||||
"count": 1,
|
||||
"datas": [
|
||||
{
|
||||
"staff_id": "70023bb2-a362-438c-ba46-2f165c502351",
|
||||
"work_day": "2026-08-10",
|
||||
"paiban_type": "-2",
|
||||
"priority": "0",
|
||||
"team_id": "355945ef0e894881a21980b79b7dfbf1",
|
||||
"bc_id": "de1daf426e7f4fa6916f3012434e8973",
|
||||
"sb_type": 0,
|
||||
"xb_type": 0,
|
||||
"begin_time": "09:00",
|
||||
"end_time": "18:00",
|
||||
"yq_total_min": 480,
|
||||
"change_value_day": 1.0,
|
||||
"remark": "",
|
||||
"team_name": "集团本部职能",
|
||||
"STAFF_ID": "70023bb2-a362-438c-ba46-2f165c502351",
|
||||
"STAFF_NAME": "郑荣斌",
|
||||
"base_code": "37031376",
|
||||
"join_date": "2025-10-15",
|
||||
"leaveOffice_date": null,
|
||||
"Regular_Time": "2026-01-15",
|
||||
"person_status": "1",
|
||||
"staff_status": "1",
|
||||
"identity": "1",
|
||||
"idCard": "500242********3177",
|
||||
"STRU_ID": "bfaf2462-a96f-11f0-a0a5-000c296f9469",
|
||||
"dept_one": null,
|
||||
"dept_two": null,
|
||||
"POST_LEVEL_ID": "8fdd4d7d-648d-11ec-b526-822ff8ed5b28",
|
||||
"POST_LEVEL_NAME": "总监",
|
||||
"DEPT_ORG_ONE": null,
|
||||
"DEPT_ORG_TWO": null,
|
||||
"DEPT_ORG_THREE": null,
|
||||
"DEPT_ORG_FOUR": null,
|
||||
"DEPT_ORG_FIVE": null,
|
||||
"POST_ALIAS": "财务总监",
|
||||
"POST_ORG_NAME": "财务总监",
|
||||
"BELONG_UNIT_STRU_ID": "e451622b-8be5-11f1-a7d9-000c296f9469",
|
||||
"BELONG_UNIT_ORG_NAME": "财务管理部",
|
||||
"DEPT_STRU_ID": "e451622b-8be5-11f1-a7d9-000c296f9469",
|
||||
"DEPT_ORG_NAME": "财务管理部",
|
||||
"POST_NO": "231",
|
||||
"POST_ALIAS_NAME": "财务总监",
|
||||
"ORG_FULL_PATH": "集团-财务管理部",
|
||||
"hrext_hsb_ext_speciality": null,
|
||||
"hrext_ext_technician_code": null,
|
||||
"hrext_ext_cal_person2": "",
|
||||
"hrext_ext_call_phone2": "",
|
||||
"hrext_ext_star_level": "正式",
|
||||
"hrext_ext_rehiring_reason_type": "",
|
||||
"hrext_ext_staff_type": "职能高层管理",
|
||||
"hrext_ext_insurance_type": "社会保险",
|
||||
"hrext_ext_recruit_way": "BOSS直聘",
|
||||
"hrext_ext_call_relationship2": "",
|
||||
"hrext_ext_is_CRBT_open": "",
|
||||
"hrext_ext_dept_principal": "",
|
||||
"hrext_ext_yb_pay_year": "",
|
||||
"hrext_ext_Have_worked": "",
|
||||
"hrext_ext_family_join": "否",
|
||||
"hrext_ext_criminal_record": "否",
|
||||
"hrext_ext_infectious_disease": "否",
|
||||
"hrext_ext_References": "",
|
||||
"hrext_ext_References_phone": "",
|
||||
"hrext_ext_References_outside": "",
|
||||
"hrext_ext_outside_References_phone": "",
|
||||
"hrext_ext_is_dormitory": "否",
|
||||
"hrext_ext_process_approval_status": "",
|
||||
"hrext_ext_trans_type": "其他",
|
||||
"bc_name": "职能正班A",
|
||||
"2026-08-10_bc_id": "de1daf426e7f4fa6916f3012434e8973",
|
||||
"2026-08-10_bc_name": "职能正班A",
|
||||
"2026-08-10_bc_time": "09:00 ~ 18:00",
|
||||
"2026-08-10_paiban_type": "-2",
|
||||
"2026-08-10_remark": "",
|
||||
"2026-08-10_team_name": "集团本部职能",
|
||||
"2026-08-10_team_id": "355945ef0e894881a21980b79b7dfbf1",
|
||||
"2026-08-10_sb_type": 0,
|
||||
"2026-08-10_xb_type": 0,
|
||||
"2026-08-11_bc_id": "de1daf426e7f4fa6916f3012434e8973",
|
||||
"2026-08-11_bc_name": "职能正班A",
|
||||
"2026-08-11_bc_time": "09:00 ~ 18:00",
|
||||
"2026-08-11_paiban_type": "-2",
|
||||
"2026-08-11_remark": "",
|
||||
"2026-08-11_team_name": "集团本部职能",
|
||||
"2026-08-11_team_id": "355945ef0e894881a21980b79b7dfbf1",
|
||||
"2026-08-11_sb_type": 0,
|
||||
"2026-08-11_xb_type": 0,
|
||||
"2026-08-12_bc_id": "de1daf426e7f4fa6916f3012434e8973",
|
||||
"2026-08-12_bc_name": "职能正班A",
|
||||
"2026-08-12_bc_time": "09:00 ~ 18:00",
|
||||
"2026-08-12_paiban_type": "-2",
|
||||
"2026-08-12_remark": "",
|
||||
"2026-08-12_team_name": "集团本部职能",
|
||||
"2026-08-12_team_id": "355945ef0e894881a21980b79b7dfbf1",
|
||||
"2026-08-12_sb_type": 0,
|
||||
"2026-08-12_xb_type": 0,
|
||||
"2026-08-13_bc_id": "de1daf426e7f4fa6916f3012434e8973",
|
||||
"2026-08-13_bc_name": "职能正班A",
|
||||
"2026-08-13_bc_time": "09:00 ~ 18:00",
|
||||
"2026-08-13_paiban_type": "-2",
|
||||
"2026-08-13_remark": "",
|
||||
"2026-08-13_team_name": "集团本部职能",
|
||||
"2026-08-13_team_id": "355945ef0e894881a21980b79b7dfbf1",
|
||||
"2026-08-13_sb_type": 0,
|
||||
"2026-08-13_xb_type": 0,
|
||||
"2026-08-14_bc_id": "de1daf426e7f4fa6916f3012434e8973",
|
||||
"2026-08-14_bc_name": "职能正班A",
|
||||
"2026-08-14_bc_time": "09:00 ~ 18:00",
|
||||
"2026-08-14_paiban_type": "-2",
|
||||
"2026-08-14_remark": "",
|
||||
"2026-08-14_team_name": "集团本部职能",
|
||||
"2026-08-14_team_id": "355945ef0e894881a21980b79b7dfbf1",
|
||||
"2026-08-14_sb_type": 0,
|
||||
"2026-08-14_xb_type": 0,
|
||||
"2026-08-15_bc_id": "4",
|
||||
"2026-08-15_bc_name": "休息",
|
||||
"2026-08-15_bc_time": "",
|
||||
"2026-08-15_paiban_type": "0",
|
||||
"2026-08-15_remark": "",
|
||||
"2026-08-15_team_name": "集团本部职能",
|
||||
"2026-08-15_team_id": "355945ef0e894881a21980b79b7dfbf1",
|
||||
"2026-08-15_sb_type": "",
|
||||
"2026-08-15_xb_type": "",
|
||||
"2026-08-16_bc_id": "4",
|
||||
"2026-08-16_bc_name": "休息",
|
||||
"2026-08-16_bc_time": "",
|
||||
"2026-08-16_paiban_type": "0",
|
||||
"2026-08-16_remark": "",
|
||||
"2026-08-16_team_name": "集团本部职能",
|
||||
"2026-08-16_team_id": "355945ef0e894881a21980b79b7dfbf1",
|
||||
"2026-08-16_sb_type": "",
|
||||
"2026-08-16_xb_type": "",
|
||||
"total_hours": 40.0,
|
||||
"total_day": 5
|
||||
}
|
||||
],
|
||||
"pageSize": 15,
|
||||
"start": 0,
|
||||
"pageNo": 1,
|
||||
"pageCount": 1,
|
||||
"allDatas": null,
|
||||
"url": null,
|
||||
"state": "1",
|
||||
"meg": "",
|
||||
"des": "",
|
||||
"viewMapper": null
|
||||
}
|
||||
财务管理部向英发起向英的加班申请-休息日加班
|
||||
|
||||
财务管理部李阳发起李阳的加班申请-延时加班
|
||||
|
||||
财务管理部梁鲜香发起梁鲜香的加班申请-休息日加班
|
||||
|
||||
集团营建中心任毅发起任毅的加班申请-休息日加班
|
||||
|
||||
集团营建中心任川发起任川的加班申请-延时加班
|
||||
|
||||
集团管理中心周平发起周平的加班申请-延时加班
|
||||
|
||||
财务管理部黎小念发起黎小念的加班申请-休息日加班
|
||||
|
||||
集团营建中心夏彬晶发起夏彬晶的加班申请-延时加班
|
||||
|
||||
集团营建中心罗莉萍发起罗莉萍的加班申请-延时加班
|
||||
|
||||
自动驳回 1 条,分别是:
|
||||
|
||||
财务管理部张艳发起张艳的加班申请-延时加班
|
||||
|
||||
驳回原因:加班开始日期(2026-08-05)与申请加班日期(2026-08-04)不一致;申请结束时间(21:30)晚于实际下班打卡时间(20:12:33)
|
||||
|
||||
超期待人资处理 2 条,分别是:
|
||||
|
||||
财务管理部张艳发起张艳的加班申请-休息日加班
|
||||
|
||||
处理原因:加班日期(2026-08-02)距今超过8天审核周期,不再审核
|
||||
|
||||
财务管理部张艳发起张艳的加班申请-延时加班
|
||||
|
||||
处理原因:加班日期(2026-08-03)距今超过8天审核周期,不再审核
|
||||
|
||||
@@ -24,8 +24,10 @@ from app.service.hrbp.oa.common.session_manager import (
|
||||
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,
|
||||
@@ -141,13 +143,13 @@ def _get_browser_and_session(subject: str):
|
||||
return browser, session, True
|
||||
|
||||
|
||||
@retry(max_attempts=3)
|
||||
@retry(max_attempts=3, no_retry_on=(OALoginExpiredError,))
|
||||
def _fetch_documents(session, subject: str) -> List[Dict[str, Any]]:
|
||||
"""按主题拉取待办单据(失败自动重试,最多 3 次)"""
|
||||
"""按主题拉取待办单据(失败自动重试,最多 3 次;登录失效直接上抛交给上层重登)"""
|
||||
return get_documents(session, subject=subject)
|
||||
|
||||
|
||||
@retry(max_attempts=3)
|
||||
@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 取表单数据。
|
||||
@@ -208,49 +210,68 @@ def run_flow(
|
||||
setup_logging()
|
||||
logger.info("%s审批流程开始", subject)
|
||||
|
||||
browser, session, _ = _get_browser_and_session(subject)
|
||||
|
||||
docs = _fetch_documents(session, subject)
|
||||
logger.info("共获取%s待办 %d 条", subject, len(docs))
|
||||
|
||||
results = []
|
||||
for doc in docs:
|
||||
# 运行中遇 OA 登录态失效(待办/表单接口返回登录页):删除 cookie、自动重新登录并重跑一遍(最多 2 轮)
|
||||
for login_attempt in range(2):
|
||||
browser, session, _ = _get_browser_and_session(subject)
|
||||
try:
|
||||
doc_detail = _fetch_doc_detail(browser, session, doc)
|
||||
result = validate_doc(doc_detail, session)
|
||||
# 真实审批提交:仅当 overtime_approve_enabled=true 时执行(默认关闭)
|
||||
if _approve_enabled():
|
||||
submit = submit_approval(browser, result.get("decision"))
|
||||
result["审批动作"] = submit["action"]
|
||||
result["审批结果"] = f"{'成功' if submit['ok'] == 'true' else '失败'},{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),
|
||||
})
|
||||
docs = _fetch_documents(session, subject)
|
||||
logger.info("共获取%s待办 %d 条", subject, len(docs))
|
||||
|
||||
report = generate_report(results)
|
||||
print("\n" + report)
|
||||
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():
|
||||
submit = submit_approval(browser, result.get("decision"))
|
||||
result["审批动作"] = submit["action"]
|
||||
result["审批结果"] = f"{'成功' if submit['ok'] == 'true' else '失败'},{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),
|
||||
})
|
||||
|
||||
# 先推送摘要到钉钉
|
||||
push_report(build_push_summary(results, subject), subject)
|
||||
report = generate_report(results)
|
||||
print("\n" + report)
|
||||
|
||||
# 有驳回/人工复核/失败时,再推送完整报告(含明细表格)
|
||||
has_detail = any(r.get("decision") != "通过" for r in results)
|
||||
if has_detail:
|
||||
push_report(report, subject)
|
||||
# 先推送摘要到钉钉
|
||||
push_report(build_push_summary(results, subject), subject)
|
||||
|
||||
# 保存最新 cookies(SSO 已刷新 hr 域会话,供下次运行免登录复用)
|
||||
save_browser_cookies(browser)
|
||||
# 有驳回/人工复核/失败时,再推送完整报告(含明细表格)
|
||||
has_detail = any(r.get("decision") != "通过" for r in results)
|
||||
if has_detail:
|
||||
push_report(report, subject)
|
||||
|
||||
logger.info("%s审批流程结束,共处理 %d 条", subject, len(results))
|
||||
return report
|
||||
# 保存最新 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
|
||||
|
||||
@@ -15,6 +15,8 @@ from app.service.hrbp.common.config import HR_BASE_URL # noqa: E402
|
||||
BASE_URL = "https://oa.37du.co"
|
||||
# 待办列表接口(oa 域名):按标题关键字查询当前账号的待办单据,用于抓取请假/加班等待审批流程
|
||||
TODO_LIST_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyMainIndex.do"
|
||||
# 轻量会话校验接口:method=sumTodoCount 返回待办数统计 JSON,会话失效会被重定向到登录页
|
||||
TODO_COUNT_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyTodo.do"
|
||||
# 待办类型编码:"13" 对应需人工处理的审批类待办
|
||||
FD_TYPE = "13"
|
||||
|
||||
|
||||
@@ -8,7 +8,11 @@
|
||||
@Version: 2.0.0
|
||||
"""
|
||||
|
||||
from app.service.hrbp.oa.common.oa_api.base import oa_request_json, _handle_response
|
||||
from app.service.hrbp.oa.common.oa_api.base import (
|
||||
oa_request_json,
|
||||
_handle_response,
|
||||
OALoginExpiredError,
|
||||
)
|
||||
from app.service.hrbp.oa.common.oa_api.todo import (
|
||||
fetch_todo_page,
|
||||
parse_todo_list,
|
||||
@@ -32,6 +36,7 @@ from app.service.hrbp.oa.common.oa_api.leave import (
|
||||
__all__ = [
|
||||
"oa_request_json",
|
||||
"_handle_response",
|
||||
"OALoginExpiredError",
|
||||
"fetch_todo_page",
|
||||
"parse_todo_list",
|
||||
"get_documents",
|
||||
|
||||
@@ -18,17 +18,24 @@ except ImportError:
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class OALoginExpiredError(Exception):
|
||||
"""OA 登录态失效:接口返回登录页等非 JSON 内容。"""
|
||||
|
||||
|
||||
def _handle_response(resp, label):
|
||||
"""统一校验响应:存在性 / 状态码 / JSON 可解析性,返回解析后的 JSON。"""
|
||||
if not resp:
|
||||
raise RuntimeError(f"{label}请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"{label}接口状态码异常: {resp.status_code}")
|
||||
text = resp.text or ""
|
||||
try:
|
||||
return resp.json()
|
||||
except Exception:
|
||||
body = (resp.text or "")[:200]
|
||||
raise RuntimeError(f"{label}接口返回非 JSON 数据(状态码 {resp.status_code}): {body}")
|
||||
# OA 会话失效时接口会被重定向到登录页返回 HTML,据此判定登录失效
|
||||
if "login.jsp" in text or "j_username" in text:
|
||||
raise OALoginExpiredError(f"{label}接口返回登录页,OA 登录态已失效")
|
||||
raise RuntimeError(f"{label}接口返回非 JSON 数据(状态码 {resp.status_code}): {text[:200]}")
|
||||
|
||||
|
||||
def oa_request_json(
|
||||
|
||||
@@ -128,11 +128,19 @@ def create_browser_with_saved_cookies(path: str = COOKIE_FILE) -> ChromiumPage:
|
||||
|
||||
|
||||
def is_session_valid(session: SessionPage, subject: str = "加班") -> bool:
|
||||
"""通过拉取待办第一页判断会话是否有效(无效则需重新登录)。"""
|
||||
from app.service.hrbp.oa.common.oa_api import fetch_todo_page
|
||||
"""通过轻量接口 sumTodoCount 判断会话是否有效(无效则需重新登录)。
|
||||
|
||||
会话有效时接口返回待办数统计 JSON(如 {"type_2":"39","type_1":"8"});
|
||||
会话失效会被重定向到登录页返回 HTML,据此判定失效。
|
||||
"""
|
||||
from app.service.hrbp.oa.common.config import TODO_COUNT_URL
|
||||
try:
|
||||
fetch_todo_page(session, subject=subject, page_no=1, page_size=1)
|
||||
return True
|
||||
session.get(TODO_COUNT_URL, params={"method": "sumTodoCount"}, timeout=10)
|
||||
resp = session.response
|
||||
if resp is None or resp.status_code != 200:
|
||||
return False
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception as e:
|
||||
logger.info("会话已失效,需重新登录: %s", e)
|
||||
return False
|
||||
|
||||
@@ -217,7 +217,8 @@ def _get_cookies_with_domain(session: SessionPage) -> list:
|
||||
|
||||
|
||||
def get_fd_id_by_listening(session: SessionPage, browser: Optional[ChromiumPage] = None) -> str:
|
||||
# 优先复用外部传入的浏览器;仅在没有可用浏览器时才自行创建(如复用已保存会话的场景)
|
||||
# 优先复用外部传入的浏览器;仅在没有可用浏览器时才自行创建(如复用已保存会话的场景)。
|
||||
# 复用场景下 get_session 已用轻量接口 is_session_valid 校验过会话,无需在此重复校验
|
||||
own_browser = browser is None
|
||||
if own_browser:
|
||||
cookies = _get_cookies_with_domain(session)
|
||||
@@ -236,6 +237,10 @@ def get_fd_id_by_listening(session: SessionPage, browser: Optional[ChromiumPage]
|
||||
browser.get(HOME_URL)
|
||||
time.sleep(5)
|
||||
|
||||
# 兜底:轻量接口校验通过后,若新浏览器 cookies 提取不全仍可能停在登录页,快速失败避免空等
|
||||
if "login.jsp" in browser.url or browser.ele('tag:input@name=j_username', timeout=2):
|
||||
raise RuntimeError("登录态已失效,页面停留在登录页,请重新登录")
|
||||
|
||||
deadline = time.time() + 10
|
||||
target_request = None
|
||||
while time.time() < deadline:
|
||||
@@ -620,73 +625,77 @@ def export_employee_change_list(
|
||||
|
||||
base_params = {**DEFAULT_FIXED_PARAMS, **filter_params}
|
||||
|
||||
browser, session = get_session()
|
||||
# 登录态失效时自动删除 cookie、重新登录并重跑一遍(最多 2 轮)
|
||||
for login_attempt in range(2):
|
||||
browser, session = get_session()
|
||||
|
||||
try:
|
||||
# 1. 动态获取 fdId(复用登录浏览器,避免重复创建导致浏览器被提前关闭)
|
||||
fd_id = get_fd_id_by_listening(session, browser)
|
||||
|
||||
# 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)
|
||||
|
||||
# 6. 读取原始表并内存清洗(去『废弃』+按工号去重),不落中间表
|
||||
headers, rows, emp_col = _read_and_clean(output_path)
|
||||
|
||||
# 7. 调用 HR 参保记录接口核对,追加『社保记录查询结果』列(一次性完成)
|
||||
mode = "suspension" if menu_name == MENU_NAME_SUSPEND else "participation"
|
||||
final_path = _write_annotated(
|
||||
headers, rows, emp_col, mode,
|
||||
os.path.splitext(os.path.basename(output_path))[0], output_dir)
|
||||
|
||||
# 8. 清理中间原始导出文件,只保留最终标注表
|
||||
try:
|
||||
os.remove(output_path)
|
||||
logger.info("已清理中间原始导出文件:%s", output_path)
|
||||
except Exception:
|
||||
pass
|
||||
# 1. 动态获取 fdId(复用登录浏览器,避免重复创建导致浏览器被提前关闭)
|
||||
fd_id = get_fd_id_by_listening(session, browser)
|
||||
|
||||
if browser is not None:
|
||||
save_browser_cookies(browser)
|
||||
return final_path
|
||||
# 2. 从菜单获取 searchId
|
||||
search_id = get_search_id_from_menu(session, fd_id, menu_name)
|
||||
|
||||
except Exception as e:
|
||||
logger.error("导出过程出错: %s", e, exc_info=True)
|
||||
if "登录" in str(e) or "cookie" in str(e).lower():
|
||||
# 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)
|
||||
|
||||
# 6. 读取原始表并内存清洗(去『废弃』+按工号去重),不落中间表
|
||||
headers, rows, emp_col = _read_and_clean(output_path)
|
||||
|
||||
# 7. 调用 HR 参保记录接口核对,追加『社保记录查询结果』列(一次性完成)
|
||||
mode = "suspension" if menu_name == MENU_NAME_SUSPEND else "participation"
|
||||
final_path = _write_annotated(
|
||||
headers, rows, emp_col, mode,
|
||||
os.path.splitext(os.path.basename(output_path))[0], output_dir)
|
||||
|
||||
# 8. 清理中间原始导出文件,只保留最终标注表
|
||||
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()
|
||||
os.remove(output_path)
|
||||
logger.info("已清理中间原始导出文件:%s", output_path)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if browser is not None:
|
||||
save_browser_cookies(browser)
|
||||
return final_path
|
||||
|
||||
except Exception as e:
|
||||
logger.error("导出过程出错: %s", e, exc_info=True)
|
||||
is_login_fail = "登录" in str(e) or "cookie" in str(e).lower()
|
||||
if is_login_fail and 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
|
||||
|
||||
|
||||
def export_participation(
|
||||
filter_params: Optional[Dict] = None,
|
||||
|
||||
@@ -0,0 +1,456 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: utils.dingtalk_robot
|
||||
@FileName: dingtalk_robot.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-14
|
||||
@Description: 钉钉群机器人消息推送模块(自定义机器人 Webhook 方式)——项目级通用推送能力,
|
||||
供请假/加班/考勤/雇主险等所有业务模块复用,不绑定任何具体业务。
|
||||
提供统一通知方法 send_notification(标题按状态着色 + 内容引用块 + 页脚署名带时间),
|
||||
样式参照小芒任务调度平台的 DingTalkBot.send_notification。
|
||||
与 dingtalk_sender(桌面客户端模拟)不同,本模块走 HTTP 推送,无需登录钉钉桌面端。
|
||||
推送地址、加签密钥、页脚平台署名可通过环境变量配置:
|
||||
DINGTALK_ROBOT_WEBHOOK = https://oapi.dingtalk.com/robot/send?access_token=xxx
|
||||
DINGTALK_ROBOT_SECRET = 加签密钥(未配置则不加签)
|
||||
DINGTALK_ROBOT_NAME = 页脚平台署名,默认 "小芒 任务调度平台"
|
||||
注意:钉钉机器人若配置了"自定义关键词"安全校验,
|
||||
页脚署名需包含该关键词(如 小芒)才会被接受。
|
||||
失败自动重试 3 次,成功/失败均有日志;响应细节仅 DEBUG 级别输出,避免大 JSON 刷屏。
|
||||
@Version: 2.0.0
|
||||
|
||||
使用示例:
|
||||
from app.utils.dingtalk_robot import DingTalkRobot, send_robot_notification
|
||||
|
||||
# 统一通知(推荐):标题按 status 着色,内容多行自动转引用块,自动追加页脚署名+时间
|
||||
robot = DingTalkRobot()
|
||||
robot.send_notification(
|
||||
"任务执行失败",
|
||||
"订单同步失败\n错误原因:接口超时",
|
||||
status="error",
|
||||
)
|
||||
|
||||
# 底部带按钮的 ActionCard(如报表下载)
|
||||
robot.send_action_card(
|
||||
"报表已生成",
|
||||
"7 月考勤报表已生成,点击下方按钮下载",
|
||||
single_title="点击下载报表",
|
||||
single_url="https://xxx/download",
|
||||
)
|
||||
|
||||
# 纯文本
|
||||
robot.send_text("测试消息")
|
||||
"""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
|
||||
from app.utils.intelligent_retry import retry
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ==================== 环境变量加载 ====================
|
||||
def _load_env_file():
|
||||
"""
|
||||
从项目根目录的 .env 加载环境变量(不覆盖已存在的环境变量)。
|
||||
|
||||
优先使用 python-dotenv;缺失时手动解析 key=value 行,保证模块零第三方依赖可用。
|
||||
"""
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
load_dotenv()
|
||||
return
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
# 项目根目录:app/utils/dingtalk_robot.py 向上三级
|
||||
env_path = os.path.join(
|
||||
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
|
||||
".env",
|
||||
)
|
||||
if not os.path.exists(env_path):
|
||||
return
|
||||
with open(env_path, encoding="utf-8") as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#") or "=" not in line:
|
||||
continue
|
||||
key, _, value = line.partition("=")
|
||||
key = key.strip()
|
||||
value = value.strip().strip("\"'")
|
||||
if key and key not in os.environ:
|
||||
os.environ[key] = value
|
||||
|
||||
|
||||
_load_env_file()
|
||||
|
||||
# ==================== 默认参数 ====================
|
||||
DEFAULT_WEBHOOK = os.getenv("DINGTALK_ROBOT_WEBHOOK", "").strip()
|
||||
DEFAULT_SECRET = os.getenv("DINGTALK_ROBOT_SECRET", "").strip()
|
||||
DEFAULT_SERVER_NAME = os.getenv("DINGTALK_ROBOT_NAME", "").strip() or "小芒 任务调度平台"
|
||||
DEFAULT_TIMEOUT = 10 # HTTP 请求超时秒数
|
||||
DEFAULT_RETRY_TIMES = 3 # 失败重试次数(含首次)
|
||||
DINGTALK_ROBOT_ENDPOINT = "https://oapi.dingtalk.com/robot/send"
|
||||
|
||||
# 通知状态 → 标题颜色(与 aa.md 中 DingTalkBot.send_notification 色板一致)
|
||||
_STATUS_COLORS = {
|
||||
"info": "#0077ff", # 蓝色
|
||||
"success": "#00b300", # 绿色
|
||||
"warning": "#ff9900", # 橙色
|
||||
"error": "#ff0000", # 红色
|
||||
}
|
||||
|
||||
|
||||
def _build_sign(secret: str, timestamp_ms: int) -> str:
|
||||
"""按钉钉加签规则计算签名(HMAC-SHA256 + Base64 + URL 编码)。"""
|
||||
string_to_sign = f"{timestamp_ms}\n{secret}"
|
||||
hmac_code = hmac.new(
|
||||
secret.encode("utf-8"), string_to_sign.encode("utf-8"), digestmod=hashlib.sha256
|
||||
).digest()
|
||||
return urllib.parse.quote_plus(base64.b64encode(hmac_code))
|
||||
|
||||
|
||||
def _build_url(webhook: str, secret: str = "") -> str:
|
||||
"""拼接最终推送地址:配置了 secret 时追加 timestamp + sign 参数。"""
|
||||
if not secret:
|
||||
return webhook
|
||||
ts = int(round(time.time() * 1000))
|
||||
separator = "&" if "?" in webhook else "?"
|
||||
return f"{webhook}{separator}timestamp={ts}&sign={_build_sign(secret, ts)}"
|
||||
|
||||
|
||||
def _at_payload(
|
||||
at_mobiles: Optional[List[str]] = None,
|
||||
at_user_ids: Optional[List[str]] = None,
|
||||
is_at_all: bool = False,
|
||||
) -> dict:
|
||||
"""构造 @ 参数。三种 @ 方式可组合,都不指定时返回空 dict。"""
|
||||
at = {}
|
||||
if at_mobiles:
|
||||
at["atMobiles"] = list(at_mobiles)
|
||||
if at_user_ids:
|
||||
at["atUserIds"] = list(at_user_ids)
|
||||
if is_at_all:
|
||||
at["isAtAll"] = True
|
||||
return at
|
||||
|
||||
|
||||
class DingTalkRobot:
|
||||
"""
|
||||
钉钉群机器人推送器。
|
||||
|
||||
Args:
|
||||
webhook: 机器人 webhook 地址;缺省时读取环境变量 DINGTALK_ROBOT_WEBHOOK
|
||||
secret: 加签密钥;缺省时读取环境变量 DINGTALK_ROBOT_SECRET
|
||||
server_name: 页脚平台署名;缺省时读取环境变量 DINGTALK_ROBOT_NAME,
|
||||
默认 "小芒 任务调度平台"(含关键词"小芒",可满足机器人自定义关键词校验)
|
||||
timeout: HTTP 请求超时秒数
|
||||
|
||||
Raises:
|
||||
ValueError: webhook 为空
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
webhook: str = "",
|
||||
secret: str = "",
|
||||
server_name: str = "",
|
||||
timeout: int = DEFAULT_TIMEOUT,
|
||||
):
|
||||
self.webhook = (webhook or DEFAULT_WEBHOOK).strip()
|
||||
self.secret = (secret or DEFAULT_SECRET).strip()
|
||||
self.server_name = (server_name or DEFAULT_SERVER_NAME).strip()
|
||||
self.timeout = timeout
|
||||
if not self.webhook:
|
||||
raise ValueError(
|
||||
"webhook 不能为空,请通过参数传入或配置环境变量 DINGTALK_ROBOT_WEBHOOK"
|
||||
)
|
||||
|
||||
@retry(max_attempts=DEFAULT_RETRY_TIMES)
|
||||
def _post(self, payload: dict):
|
||||
"""推送 payload 到机器人,errcode != 0 视为失败(重试由装饰器负责)。"""
|
||||
url = _build_url(self.webhook, self.secret)
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=data,
|
||||
headers={"Content-Type": "application/json; charset=utf-8"},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
||||
body = resp.read().decode("utf-8")
|
||||
data = json.loads(body)
|
||||
if data.get("errcode") != 0:
|
||||
raise RuntimeError(
|
||||
f"钉钉机器人返回错误 errcode={data.get('errcode')}, "
|
||||
f"errmsg={data.get('errmsg')}"
|
||||
)
|
||||
logger.debug("钉钉机器人推送成功,响应: %s", data)
|
||||
|
||||
def _build_footer(self, server_name: str = "") -> str:
|
||||
"""构建页脚:###### {署名} | {当前时间}。署名缺省取实例的 server_name。"""
|
||||
display_name = (server_name or self.server_name).strip()
|
||||
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
return f"###### {display_name} | {current_time}"
|
||||
|
||||
def send_text(
|
||||
self,
|
||||
content: str,
|
||||
at_mobiles: Optional[List[str]] = None,
|
||||
at_user_ids: Optional[List[str]] = None,
|
||||
is_at_all: bool = False,
|
||||
) -> bool:
|
||||
"""
|
||||
发送文本消息。
|
||||
|
||||
Args:
|
||||
content: 文本内容
|
||||
at_mobiles: 需要 @ 的手机号列表
|
||||
at_user_ids: 需要 @ 的用户 userid 列表
|
||||
is_at_all: 是否 @所有人
|
||||
|
||||
Returns:
|
||||
是否推送成功
|
||||
|
||||
Raises:
|
||||
ValueError: content 为空
|
||||
"""
|
||||
if not content or not content.strip():
|
||||
raise ValueError("content 不能为空")
|
||||
|
||||
payload = {"msgtype": "text", "text": {"content": content}}
|
||||
at = _at_payload(at_mobiles, at_user_ids, is_at_all)
|
||||
if at:
|
||||
payload["at"] = at
|
||||
|
||||
logger.info("钉钉机器人推送文本: %s", content[:50] + ("..." if len(content) > 50 else ""))
|
||||
self._post(payload)
|
||||
return True
|
||||
|
||||
def send_markdown(
|
||||
self,
|
||||
title: str,
|
||||
text: str,
|
||||
at_mobiles: Optional[List[str]] = None,
|
||||
at_user_ids: Optional[List[str]] = None,
|
||||
is_at_all: bool = False,
|
||||
) -> bool:
|
||||
"""
|
||||
发送 Markdown 消息(底层通用方法,内容完全由调用方控制)。
|
||||
|
||||
Args:
|
||||
title: 消息标题(显示在会话中)
|
||||
text: Markdown 正文
|
||||
at_mobiles: 需要 @ 的手机号列表
|
||||
at_user_ids: 需要 @ 的用户 userid 列表
|
||||
is_at_all: 是否 @所有人
|
||||
|
||||
Returns:
|
||||
是否推送成功
|
||||
|
||||
Raises:
|
||||
ValueError: title 或 text 为空
|
||||
"""
|
||||
if not title or not title.strip():
|
||||
raise ValueError("title 不能为空")
|
||||
if not text or not text.strip():
|
||||
raise ValueError("text 不能为空")
|
||||
|
||||
payload = {"msgtype": "markdown", "markdown": {"title": title, "text": text}}
|
||||
at = _at_payload(at_mobiles, at_user_ids, is_at_all)
|
||||
if at:
|
||||
payload["at"] = at
|
||||
|
||||
logger.info("钉钉机器人推送 Markdown: %s", title)
|
||||
self._post(payload)
|
||||
return True
|
||||
|
||||
def send_notification(
|
||||
self,
|
||||
title: str,
|
||||
content: str,
|
||||
status: str = "info",
|
||||
at_mobiles: Optional[List[str]] = None,
|
||||
at_user_ids: Optional[List[str]] = None,
|
||||
is_at_all: bool = False,
|
||||
server_name: str = "",
|
||||
append_footer: bool = True,
|
||||
) -> bool:
|
||||
"""
|
||||
统一通知方法(推荐业务方使用),样式与 aa.md 中 DingTalkBot.send_notification 一致:
|
||||
|
||||
**<font color='#ff0000'>任务执行失败</font>** ← 标题按 status 着色
|
||||
|
||||
内容详情:
|
||||
> 订单同步失败 ← 内容多行自动转引用块
|
||||
> 错误原因:接口超时
|
||||
|
||||
---
|
||||
|
||||
###### 小芒 任务调度平台 | 2026-08-14 14:30:00 ← 页脚:署名 + 当前时间
|
||||
|
||||
Args:
|
||||
title: 消息标题
|
||||
content: 消息主体内容,支持多行(自动按行转引用块)
|
||||
status: 状态类型,决定标题颜色: info(蓝) | success(绿) | warning(橙) | error(红)
|
||||
at_mobiles: 需要 @ 的手机号列表
|
||||
at_user_ids: 需要 @ 的用户 userid 列表
|
||||
is_at_all: 是否 @所有人
|
||||
server_name: 页脚署名,缺省用实例的 server_name
|
||||
append_footer: 是否自动追加页脚(署名 + 时间),默认 True
|
||||
|
||||
Returns:
|
||||
是否推送成功
|
||||
|
||||
Raises:
|
||||
ValueError: title 或 content 为空
|
||||
"""
|
||||
if not title or not title.strip():
|
||||
raise ValueError("title 不能为空")
|
||||
if not content or not content.strip():
|
||||
raise ValueError("content 不能为空")
|
||||
|
||||
color = _STATUS_COLORS.get(status, _STATUS_COLORS["info"])
|
||||
|
||||
text = f"**<font color='{color}'>{title}</font>**\n\n"
|
||||
text += "内容详情:\n"
|
||||
for line in content.strip().splitlines():
|
||||
line = line.strip()
|
||||
if line:
|
||||
# 行尾两个空格 + 换行:钉钉 markdown 单个 \n 不换行,必须用硬换行才分行显示
|
||||
text += f"> {line} \n"
|
||||
if append_footer:
|
||||
text += f"\n\n---\n\n{self._build_footer(server_name)}"
|
||||
|
||||
payload = {"msgtype": "markdown", "markdown": {"title": title, "text": text}}
|
||||
at = _at_payload(at_mobiles, at_user_ids, is_at_all)
|
||||
if at:
|
||||
payload["at"] = at
|
||||
|
||||
logger.info("钉钉机器人推送通知 [%s]: %s", status, title)
|
||||
self._post(payload)
|
||||
return True
|
||||
|
||||
def send_action_card(
|
||||
self,
|
||||
title: str,
|
||||
content: str,
|
||||
single_title: str,
|
||||
single_url: str,
|
||||
at_mobiles: Optional[List[str]] = None,
|
||||
at_user_ids: Optional[List[str]] = None,
|
||||
is_at_all: bool = False,
|
||||
server_name: str = "",
|
||||
) -> bool:
|
||||
"""
|
||||
发送 ActionCard 消息(底部带按钮,如"点击下载报表")。
|
||||
|
||||
Args:
|
||||
title: 消息标题
|
||||
content: 卡片正文(支持多行)
|
||||
single_title: 按钮文字
|
||||
single_url: 按钮跳转链接
|
||||
at_mobiles: 需要 @ 的手机号列表
|
||||
at_user_ids: 需要 @ 的用户 userid 列表
|
||||
is_at_all: 是否 @所有人
|
||||
server_name: 页脚署名,缺省用实例的 server_name
|
||||
|
||||
Returns:
|
||||
是否推送成功
|
||||
|
||||
Raises:
|
||||
ValueError: title / content / single_title / single_url 任一为空
|
||||
"""
|
||||
if not title or not title.strip():
|
||||
raise ValueError("title 不能为空")
|
||||
if not content or not content.strip():
|
||||
raise ValueError("content 不能为空")
|
||||
if not single_title or not single_title.strip():
|
||||
raise ValueError("single_title 不能为空")
|
||||
if not single_url or not single_url.strip():
|
||||
raise ValueError("single_url 不能为空")
|
||||
|
||||
text = f"**{title}**\n\n{content}\n\n---\n\n{self._build_footer(server_name)}"
|
||||
payload = {
|
||||
"msgtype": "actionCard",
|
||||
"actionCard": {
|
||||
"title": title,
|
||||
"text": text,
|
||||
"singleTitle": single_title,
|
||||
"singleURL": single_url,
|
||||
},
|
||||
}
|
||||
at = _at_payload(at_mobiles, at_user_ids, is_at_all)
|
||||
if at:
|
||||
payload["at"] = at
|
||||
|
||||
logger.info("钉钉机器人推送 ActionCard: %s -> %s", title, single_url)
|
||||
self._post(payload)
|
||||
return True
|
||||
|
||||
|
||||
# ==================== 一次性便捷函数 ====================
|
||||
def send_robot_text(
|
||||
content: str,
|
||||
webhook: str = "",
|
||||
secret: str = "",
|
||||
at_mobiles: Optional[List[str]] = None,
|
||||
at_user_ids: Optional[List[str]] = None,
|
||||
is_at_all: bool = False,
|
||||
) -> bool:
|
||||
"""一键发送文本到群机器人(webhook 缺省取环境变量 DINGTALK_ROBOT_WEBHOOK)。"""
|
||||
robot = DingTalkRobot(webhook=webhook, secret=secret)
|
||||
return robot.send_text(content, at_mobiles=at_mobiles, at_user_ids=at_user_ids, is_at_all=is_at_all)
|
||||
|
||||
|
||||
def send_robot_notification(
|
||||
title: str,
|
||||
content: str,
|
||||
status: str = "info",
|
||||
webhook: str = "",
|
||||
secret: str = "",
|
||||
at_mobiles: Optional[List[str]] = None,
|
||||
at_user_ids: Optional[List[str]] = None,
|
||||
is_at_all: bool = False,
|
||||
server_name: str = "",
|
||||
) -> bool:
|
||||
"""一键发送统一通知(样式与 send_notification 一致)。"""
|
||||
robot = DingTalkRobot(webhook=webhook, secret=secret)
|
||||
return robot.send_notification(
|
||||
title, content, status=status,
|
||||
at_mobiles=at_mobiles, at_user_ids=at_user_ids, is_at_all=is_at_all,
|
||||
server_name=server_name,
|
||||
)
|
||||
|
||||
|
||||
# ==================== 命令行入口(便于手动测试) ====================
|
||||
def main():
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser(description="钉钉群机器人消息推送工具")
|
||||
parser.add_argument("content", help="消息内容(多行可用换行分隔)")
|
||||
parser.add_argument("-t", "--title", default="消息通知", help="消息标题")
|
||||
parser.add_argument("--status", default="info",
|
||||
choices=["info", "success", "warning", "error"], help="通知状态(决定标题颜色)")
|
||||
parser.add_argument("-w", "--webhook", default="", help="机器人 webhook,缺省取环境变量")
|
||||
parser.add_argument("-s", "--secret", default="", help="加签密钥,缺省取环境变量")
|
||||
parser.add_argument("--name", default="", help="页脚平台署名,缺省取环境变量")
|
||||
parser.add_argument("--all", action="store_true", help="@所有人")
|
||||
args = parser.parse_args()
|
||||
|
||||
send_robot_notification(
|
||||
args.title, args.content, status=args.status,
|
||||
webhook=args.webhook, secret=args.secret,
|
||||
server_name=args.name, is_at_all=args.all,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -68,6 +68,8 @@ COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||||
BASE_URL = "https://oa.37du.co"
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
TODO_LIST_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyMainIndex.do"
|
||||
# 轻量会话校验接口:method=sumTodoCount 返回待办数统计 JSON,会话失效会被重定向到登录页
|
||||
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"
|
||||
@@ -248,7 +250,11 @@ class RetryExhaustedError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def retry(max_attempts: int = 3) -> Callable:
|
||||
class OALoginExpiredError(Exception):
|
||||
"""OA 登录态失效:接口返回登录页等非 JSON 内容。"""
|
||||
|
||||
|
||||
def retry(max_attempts: int = 3, no_retry_on: tuple = ()) -> Callable:
|
||||
if max_attempts < 1:
|
||||
raise ValueError("max_attempts must be >= 1")
|
||||
|
||||
@@ -262,6 +268,8 @@ def retry(max_attempts: int = 3) -> Callable:
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
except no_retry_on:
|
||||
raise
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt >= max_attempts:
|
||||
@@ -305,6 +313,9 @@ def fetch_todo_page(session, subject, page_no=1, page_size=DEFAULT_PAGE_SIZE):
|
||||
try:
|
||||
return resp.json()
|
||||
except Exception:
|
||||
# OA 会话失效时接口会被重定向到登录页返回 HTML,据此判定登录失效
|
||||
if "login.jsp" in (resp.text or "") or "j_username" in (resp.text or ""):
|
||||
raise OALoginExpiredError("待办接口返回登录页,OA 登录态已失效")
|
||||
raise RuntimeError("接口返回非 JSON 数据,请检查参数或登录状态")
|
||||
|
||||
|
||||
@@ -813,9 +824,15 @@ def create_browser_with_saved_cookies(path=COOKIE_FILE):
|
||||
|
||||
|
||||
def is_session_valid(session, subject="请假"):
|
||||
"""调轻量接口 sumTodoCount 判断 OA 会话是否有效(无需拉待办)。"""
|
||||
try:
|
||||
fetch_todo_page(session, subject=subject, page_no=1, page_size=1)
|
||||
return True
|
||||
session.get(TODO_COUNT_URL, params={"method": "sumTodoCount"}, timeout=10)
|
||||
resp = session.response
|
||||
if resp is None or resp.status_code != 200:
|
||||
return False
|
||||
# 会话有效时返回待办数统计 JSON;失效会被重定向到登录页返回 HTML
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception as e:
|
||||
logger.info("会话已失效,需重新登录: %s", e)
|
||||
return False
|
||||
@@ -912,12 +929,12 @@ def _get_browser_and_session(subject):
|
||||
return browser, session, True
|
||||
|
||||
|
||||
@retry(max_attempts=3)
|
||||
@retry(max_attempts=3, no_retry_on=(OALoginExpiredError,))
|
||||
def _fetch_documents(session, subject):
|
||||
return get_documents(session, subject=subject)
|
||||
|
||||
|
||||
@retry(max_attempts=3)
|
||||
@retry(max_attempts=3, no_retry_on=(OALoginExpiredError,))
|
||||
def _fetch_doc_detail(browser, session, doc):
|
||||
detail_url = doc.get("detail_url", "")
|
||||
if not detail_url:
|
||||
@@ -1265,61 +1282,80 @@ def submit_approval(page, decision):
|
||||
def run_flow(subject, validate_doc, generate_report):
|
||||
logger.info("%s审批流程开始", subject)
|
||||
|
||||
browser, session, _ = _get_browser_and_session(subject)
|
||||
|
||||
docs = _fetch_documents(session, subject)
|
||||
logger.info("共获取%s待办 %d 条", subject, len(docs))
|
||||
|
||||
results = []
|
||||
for doc in docs:
|
||||
# 运行中遇 OA 登录态失效(待办/表单接口返回登录页):删除 cookie、自动重新登录并重跑一遍(最多 2 轮)
|
||||
for login_attempt in range(2):
|
||||
browser, session, _ = _get_browser_and_session(subject)
|
||||
try:
|
||||
doc_detail = _fetch_doc_detail(browser, session, doc)
|
||||
result = validate_doc(doc_detail, session)
|
||||
# 真实审批提交:仅当 APPROVE_ENABLED=True 时执行(默认关闭)
|
||||
# 与加班共用同一开关(公共审批引擎亦如此),驳回暂不自动处理(保留待人工复核),仅对"通过"提交真实审批
|
||||
if APPROVE_ENABLED:
|
||||
if result.get("decision") == "通过":
|
||||
submit = submit_approval(browser, result.get("decision"))
|
||||
result["审批动作"] = submit["action"]
|
||||
result["审批结果"] = f"{'成功' if submit['ok'] == 'true' else '失败'},{submit['message']}"
|
||||
logger.info("审批提交: %s %s", submit["action"], result["审批结果"])
|
||||
else:
|
||||
logger.info("决策为%s,暂不自动提交审批(待人工处理)", result.get("decision"))
|
||||
results.append(result)
|
||||
logger.info("已校验: %s - %s -> %s", result["creator"], result["title"], result["decision"])
|
||||
# 弹出结果提示:通过=绿勾,其余(驳回/人工复核/失败)=红叉,停留便于演示
|
||||
# 必须放在审批提交之后:全屏弹窗会遮挡审批按钮,导致真实点击被拦截
|
||||
try:
|
||||
show_rpa_result_popup(
|
||||
browser,
|
||||
"success" if result.get("decision") == "通过" else "error",
|
||||
2.5,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
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),
|
||||
})
|
||||
docs = _fetch_documents(session, subject)
|
||||
logger.info("共获取%s待办 %d 条", subject, len(docs))
|
||||
|
||||
report = generate_report(results)
|
||||
print("\n" + report)
|
||||
results = []
|
||||
for doc in docs:
|
||||
try:
|
||||
doc_detail = _fetch_doc_detail(browser, session, doc)
|
||||
result = validate_doc(doc_detail, session)
|
||||
# 真实审批提交:仅当 APPROVE_ENABLED=True 时执行(默认关闭)
|
||||
# 与加班共用同一开关(公共审批引擎亦如此),驳回暂不自动处理(保留待人工复核),仅对"通过"提交真实审批
|
||||
if APPROVE_ENABLED:
|
||||
if result.get("decision") == "通过":
|
||||
submit = submit_approval(browser, result.get("decision"))
|
||||
result["审批动作"] = submit["action"]
|
||||
result["审批结果"] = f"{'成功' if submit['ok'] == 'true' else '失败'},{submit['message']}"
|
||||
logger.info("审批提交: %s %s", submit["action"], result["审批结果"])
|
||||
else:
|
||||
logger.info("决策为%s,暂不自动提交审批(待人工处理)", result.get("decision"))
|
||||
results.append(result)
|
||||
logger.info("已校验: %s - %s -> %s", result["creator"], result["title"], result["decision"])
|
||||
# 弹出结果提示:通过=绿勾,其余(驳回/人工复核/失败)=红叉,停留便于演示
|
||||
# 必须放在审批提交之后:全屏弹窗会遮挡审批按钮,导致真实点击被拦截
|
||||
try:
|
||||
show_rpa_result_popup(
|
||||
browser,
|
||||
"success" if result.get("decision") == "通过" else "error",
|
||||
2.5,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
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),
|
||||
})
|
||||
|
||||
# 先推送摘要到钉钉
|
||||
push_report(build_push_summary(results, subject), subject)
|
||||
report = generate_report(results)
|
||||
print("\n" + report)
|
||||
|
||||
# 有驳回/人工复核/失败时,再推送完整报告(含明细表格)
|
||||
has_detail = any(r.get("decision") != "通过" for r in results)
|
||||
if has_detail:
|
||||
push_report(report, subject)
|
||||
# 先推送摘要到钉钉
|
||||
push_report(build_push_summary(results, subject), subject)
|
||||
|
||||
save_browser_cookies(browser)
|
||||
logger.info("%s审批流程结束,共处理 %d 条", subject, len(results))
|
||||
return report
|
||||
# 有驳回/人工复核/失败时,再推送完整报告(含明细表格)
|
||||
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
|
||||
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
|
||||
|
||||
|
||||
# ==================== 请假校验规则 ====================
|
||||
|
||||
@@ -64,6 +64,8 @@ COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||||
BASE_URL = "https://oa.37du.co"
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
TODO_LIST_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyMainIndex.do"
|
||||
# 轻量会话校验接口:method=sumTodoCount 返回待办数统计 JSON,会话失效会被重定向到登录页
|
||||
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"
|
||||
@@ -124,7 +126,11 @@ class RetryExhaustedError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def retry(max_attempts: int = 3) -> Callable:
|
||||
class OALoginExpiredError(Exception):
|
||||
"""OA 登录态失效:接口返回登录页等非 JSON 内容。"""
|
||||
|
||||
|
||||
def retry(max_attempts: int = 3, no_retry_on: tuple = ()) -> Callable:
|
||||
if max_attempts < 1:
|
||||
raise ValueError("max_attempts must be >= 1")
|
||||
|
||||
@@ -138,6 +144,8 @@ def retry(max_attempts: int = 3) -> Callable:
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
except no_retry_on:
|
||||
raise
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt >= max_attempts:
|
||||
@@ -181,6 +189,9 @@ def fetch_todo_page(session, subject, page_no=1, page_size=DEFAULT_PAGE_SIZE):
|
||||
try:
|
||||
return resp.json()
|
||||
except Exception:
|
||||
# OA 会话失效时接口会被重定向到登录页返回 HTML,据此判定登录失效
|
||||
if "login.jsp" in (resp.text or "") or "j_username" in (resp.text or ""):
|
||||
raise OALoginExpiredError("待办接口返回登录页,OA 登录态已失效")
|
||||
raise RuntimeError("接口返回非 JSON 数据,请检查参数或登录状态")
|
||||
|
||||
|
||||
@@ -623,9 +634,15 @@ def create_browser_with_saved_cookies(path=COOKIE_FILE):
|
||||
|
||||
|
||||
def is_session_valid(session, subject="加班"):
|
||||
"""调轻量接口 sumTodoCount 判断 OA 会话是否有效(无需拉待办)。"""
|
||||
try:
|
||||
fetch_todo_page(session, subject=subject, page_no=1, page_size=1)
|
||||
return True
|
||||
session.get(TODO_COUNT_URL, params={"method": "sumTodoCount"}, timeout=10)
|
||||
resp = session.response
|
||||
if resp is None or resp.status_code != 200:
|
||||
return False
|
||||
# 会话有效时返回待办数统计 JSON;失效会被重定向到登录页返回 HTML
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception as e:
|
||||
logger.info("会话已失效,需重新登录: %s", e)
|
||||
return False
|
||||
@@ -722,12 +739,12 @@ def _get_browser_and_session(subject):
|
||||
return browser, session, True
|
||||
|
||||
|
||||
@retry(max_attempts=3)
|
||||
@retry(max_attempts=3, no_retry_on=(OALoginExpiredError,))
|
||||
def _fetch_documents(session, subject):
|
||||
return get_documents(session, subject=subject)
|
||||
|
||||
|
||||
@retry(max_attempts=3)
|
||||
@retry(max_attempts=3, no_retry_on=(OALoginExpiredError,))
|
||||
def _fetch_doc_detail(browser, session, doc):
|
||||
detail_url = doc.get("detail_url", "")
|
||||
if not detail_url:
|
||||
@@ -1081,61 +1098,80 @@ def submit_approval(page, decision):
|
||||
def run_flow(subject, validate_doc, generate_report):
|
||||
logger.info("%s审批流程开始", subject)
|
||||
|
||||
browser, session, _ = _get_browser_and_session(subject)
|
||||
|
||||
docs = _fetch_documents(session, subject)
|
||||
logger.info("共获取%s待办 %d 条", subject, len(docs))
|
||||
|
||||
results = []
|
||||
for doc in docs:
|
||||
# 运行中遇 OA 登录态失效(待办/表单接口返回登录页):删除 cookie、自动重新登录并重跑一遍(最多 2 轮)
|
||||
for login_attempt in range(2):
|
||||
browser, session, _ = _get_browser_and_session(subject)
|
||||
try:
|
||||
doc_detail = _fetch_doc_detail(browser, session, doc)
|
||||
result = validate_doc(doc_detail, session)
|
||||
# 真实审批提交:仅当 APPROVE_ENABLED=True 时执行(默认关闭)
|
||||
if APPROVE_ENABLED:
|
||||
# 驳回暂不自动处理(保留待人工复核),仅对"通过"提交真实审批
|
||||
if result.get("decision") == "通过":
|
||||
submit = submit_approval(browser, result.get("decision"))
|
||||
result["审批动作"] = submit["action"]
|
||||
result["审批结果"] = f"{'成功' if submit['ok'] == 'true' else '失败'},{submit['message']}"
|
||||
logger.info("审批提交: %s %s", submit["action"], result["审批结果"])
|
||||
else:
|
||||
logger.info("决策为%s,暂不自动提交审批(待人工处理)", result.get("decision"))
|
||||
# 弹出结果提示:通过=绿勾,其余(驳回/人工复核/失败)=红叉,停留便于演示
|
||||
# 必须放在审批提交之后:全屏弹窗会遮挡审批按钮,导致真实点击被拦截
|
||||
try:
|
||||
show_rpa_result_popup(
|
||||
browser,
|
||||
"success" if result.get("decision") == "通过" else "error",
|
||||
2.5,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
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),
|
||||
})
|
||||
docs = _fetch_documents(session, subject)
|
||||
logger.info("共获取%s待办 %d 条", subject, len(docs))
|
||||
|
||||
report = generate_report(results)
|
||||
print("\n" + report)
|
||||
results = []
|
||||
for doc in docs:
|
||||
try:
|
||||
doc_detail = _fetch_doc_detail(browser, session, doc)
|
||||
result = validate_doc(doc_detail, session)
|
||||
# 真实审批提交:仅当 APPROVE_ENABLED=True 时执行(默认关闭)
|
||||
if APPROVE_ENABLED:
|
||||
# 驳回暂不自动处理(保留待人工复核),仅对"通过"提交真实审批
|
||||
if result.get("decision") == "通过":
|
||||
submit = submit_approval(browser, result.get("decision"))
|
||||
result["审批动作"] = submit["action"]
|
||||
result["审批结果"] = f"{'成功' if submit['ok'] == 'true' else '失败'},{submit['message']}"
|
||||
logger.info("审批提交: %s %s", submit["action"], result["审批结果"])
|
||||
else:
|
||||
logger.info("决策为%s,暂不自动提交审批(待人工处理)", result.get("decision"))
|
||||
# 弹出结果提示:通过=绿勾,其余(驳回/人工复核/失败)=红叉,停留便于演示
|
||||
# 必须放在审批提交之后:全屏弹窗会遮挡审批按钮,导致真实点击被拦截
|
||||
try:
|
||||
show_rpa_result_popup(
|
||||
browser,
|
||||
"success" if result.get("decision") == "通过" else "error",
|
||||
2.5,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
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),
|
||||
})
|
||||
|
||||
# 先推送摘要到钉钉
|
||||
push_report(build_push_summary(results, subject), subject)
|
||||
report = generate_report(results)
|
||||
print("\n" + report)
|
||||
|
||||
# 有驳回/人工复核/失败时,再推送完整报告(含明细表格)
|
||||
has_detail = any(r.get("decision") != "通过" for r in results)
|
||||
if has_detail:
|
||||
push_report(report, subject)
|
||||
# 先推送摘要到钉钉
|
||||
push_report(build_push_summary(results, subject), subject)
|
||||
|
||||
save_browser_cookies(browser)
|
||||
logger.info("%s审批流程结束,共处理 %d 条", subject, len(results))
|
||||
return report
|
||||
# 有驳回/人工复核/失败时,再推送完整报告(含明细表格)
|
||||
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
|
||||
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
|
||||
|
||||
|
||||
# ==================== 加班校验规则 ====================
|
||||
|
||||
@@ -80,6 +80,8 @@ HOME_URL = f"{BASE_URL}/sys/portal/page.jsp?portalId=1754a0f1c8b63479fb544514619
|
||||
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"
|
||||
# 轻量会话校验接口:method=sumTodoCount 返回待办数统计 JSON,会话失效会被重定向到登录页
|
||||
TODO_COUNT_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyTodo.do"
|
||||
|
||||
DEFAULT_FIXED_PARAMS = {
|
||||
"fdModelName": "com.landray.kmss.km.review.model.KmReviewMain",
|
||||
@@ -253,10 +255,15 @@ def create_browser_with_saved_cookies(path):
|
||||
|
||||
|
||||
def is_oa_session_valid(session):
|
||||
"""调轻量接口 sumTodoCount 判断 OA 会话是否有效(无需启动浏览器)。"""
|
||||
try:
|
||||
session.get(HOME_URL)
|
||||
session.get(TODO_COUNT_URL, params={"method": "sumTodoCount"}, timeout=10)
|
||||
resp = session.response
|
||||
return resp is not None and resp.status_code == 200
|
||||
if resp is None or resp.status_code != 200:
|
||||
return False
|
||||
# 会话有效时返回待办数统计 JSON(如 {"type_2":"39","type_1":"8"});失效会被重定向到登录页返回 HTML
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception as e:
|
||||
logger.info("OA 会话已失效: %s", e)
|
||||
return False
|
||||
@@ -642,6 +649,9 @@ def get_fd_id_by_listening(session, browser=None):
|
||||
logger.info("正在访问 OA 首页:%s", HOME_URL)
|
||||
browser.get(HOME_URL)
|
||||
time.sleep(5)
|
||||
# 兜底:若浏览器 cookies 失效会停在登录页,快速失败避免空等,且异常含『登录』可触发主流程自动重登
|
||||
if "login.jsp" in browser.url or browser.ele('tag:input@name=j_username', timeout=2):
|
||||
raise RuntimeError("登录态已失效,页面停留在登录页,请重新登录")
|
||||
deadline = time.time() + 10
|
||||
target = None
|
||||
while time.time() < deadline:
|
||||
@@ -920,42 +930,56 @@ def _write_annotated(headers, rows, emp_col, mode, base_name, output_dir="."):
|
||||
def export_employee_change_list(menu_name, filter_idx, columns, output_dir, query_date=None):
|
||||
logger.info("社保增减名单核对流程开始,菜单:%s", menu_name)
|
||||
base_params = {**DEFAULT_FIXED_PARAMS, **_build_filter_params(filter_idx, query_date)}
|
||||
browser, session = get_oa_session()
|
||||
|
||||
try:
|
||||
fd_id = get_fd_id_by_listening(session, browser)
|
||||
search_id = get_search_id_from_menu(session, fd_id, menu_name)
|
||||
timestamp = str(int(time.time() * 1000))
|
||||
total = get_total_count(session, base_params, search_id, timestamp)
|
||||
if total == 0:
|
||||
logger.warning("查询结果为 0 条,请检查筛选条件或无数据")
|
||||
return ""
|
||||
|
||||
logger.info("开始导出 %d 条记录...", total)
|
||||
content = export_all_data(session, base_params, total, columns, search_id, timestamp)
|
||||
output_path = os.path.abspath(os.path.join(
|
||||
output_dir, f"{time.strftime('%Y%m')}_{menu_name}表_{time.strftime('%H%M%S')}.xls"))
|
||||
with open(output_path, "wb") as f:
|
||||
f.write(content)
|
||||
logger.info("导出完成,文件保存为:%s", output_path)
|
||||
|
||||
headers, rows, emp_col = _read_and_clean(output_path)
|
||||
mode = "suspension" if menu_name == MENU_NAME_SUSPEND else "participation"
|
||||
final_path = _write_annotated(
|
||||
headers, rows, emp_col, mode,
|
||||
os.path.splitext(os.path.basename(output_path))[0], output_dir)
|
||||
# 登录态失效时自动删除 cookie、重新登录并重跑一遍(最多 2 轮)
|
||||
for login_attempt in range(2):
|
||||
browser, session = get_oa_session()
|
||||
try:
|
||||
os.remove(output_path)
|
||||
logger.info("已清理中间原始导出文件:%s", output_path)
|
||||
except Exception:
|
||||
pass
|
||||
return final_path
|
||||
finally:
|
||||
if browser is not None:
|
||||
fd_id = get_fd_id_by_listening(session, browser)
|
||||
search_id = get_search_id_from_menu(session, fd_id, menu_name)
|
||||
timestamp = str(int(time.time() * 1000))
|
||||
total = get_total_count(session, base_params, search_id, timestamp)
|
||||
if total == 0:
|
||||
logger.warning("查询结果为 0 条,请检查筛选条件或无数据")
|
||||
return ""
|
||||
|
||||
logger.info("开始导出 %d 条记录...", total)
|
||||
content = export_all_data(session, base_params, total, columns, search_id, timestamp)
|
||||
output_path = os.path.abspath(os.path.join(
|
||||
output_dir, f"{time.strftime('%Y%m')}_{menu_name}表_{time.strftime('%H%M%S')}.xls"))
|
||||
with open(output_path, "wb") as f:
|
||||
f.write(content)
|
||||
logger.info("导出完成,文件保存为:%s", output_path)
|
||||
|
||||
headers, rows, emp_col = _read_and_clean(output_path)
|
||||
mode = "suspension" if menu_name == MENU_NAME_SUSPEND else "participation"
|
||||
final_path = _write_annotated(
|
||||
headers, rows, emp_col, mode,
|
||||
os.path.splitext(os.path.basename(output_path))[0], output_dir)
|
||||
try:
|
||||
browser.quit()
|
||||
os.remove(output_path)
|
||||
logger.info("已清理中间原始导出文件:%s", output_path)
|
||||
except Exception:
|
||||
pass
|
||||
return final_path
|
||||
except Exception as e:
|
||||
logger.error("导出过程出错: %s", e)
|
||||
is_login_fail = "登录" in str(e) or "cookie" in str(e).lower()
|
||||
if is_login_fail and login_attempt == 0:
|
||||
try:
|
||||
if os.path.exists(COOKIE_FILE_OA):
|
||||
os.remove(COOKIE_FILE_OA)
|
||||
logger.info("检测到 OA 登录态失效,已删除 cookie,自动重新登录后重跑")
|
||||
except Exception:
|
||||
pass
|
||||
continue
|
||||
raise
|
||||
finally:
|
||||
if browser is not None:
|
||||
try:
|
||||
browser.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def export_participation(output_dir=".", query_date=None):
|
||||
|
||||
Reference in New Issue
Block a user