feat: 新增轻量会话校验能力,优化登录态失效处理流程
1. 新增TODO_COUNT_URL轻量接口用于快速校验会话有效性 2. 定义OALoginExpiredError统一标识登录态失效异常 3. 重构会话校验逻辑,使用轻量接口替代拉取待办页校验 4. 为重试装饰器添加不重试异常配置,登录失效直接上抛 5. 全流程增加登录态失效自动重登机制,最多重试2次 6. 新增通用钉钉机器人推送工具类
This commit is contained in:
@@ -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