restore: 恢复 11-06~11-09 本地未提交改动
- libs: 新增 hr_sdk / hotel_report / dingtalk,更新 desktopauto - controlplane-next: SDK 管理模块(controller/entity/migrations)与前端视图 - electron-shell: 插件同步、注册表、runner 调整 - plugins: XQ0035/XQ0041/XQ0042/XQ0045_XQ0046/XQ0048/XQ0076/XQ0078 等版本更新 - tests/tools: 新增 SDK 兼容性检查与打包工具(sdk_pack.py、sdk_compat_check.py)
This commit is contained in:
@@ -0,0 +1,219 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""台账「异步自定义导出」机制(服务端生成 Excel → WS 推送 → 下载)。
|
||||
|
||||
所有台账(花名册 / 合同 / 预入职 / 调动 …)共用这一套:
|
||||
1. 访问台账页 + ``ws/bridge`` 注册会话(未注册时 WS 握手 500);
|
||||
2. WS 订阅 ``HR_DEFINED_HMC_EXPORT``;
|
||||
3. POST ``exportCommonListData.mc`` 提交任务(``commonQuery`` 为加密筛选条件);
|
||||
4. 收 ``--end--|文件地址`` 后下载到本地。
|
||||
|
||||
业务模块只提供「台账 id + 模板 + 条件」,不重复实现本文件。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from typing import Callable, Dict, List, Optional, Sequence
|
||||
|
||||
import websocket
|
||||
|
||||
from .config import (BRIDGE_URL, EXPORT_TIMEOUT_SECONDS, MAX_ATTEMPTS, TEMPLATE_DETAIL_URL,
|
||||
TEMPLATE_LIST_URL, USER_AGENT, WS_EXPORT_THEME, WS_SERVICE_URL, XHR_HEADERS)
|
||||
from .errors import ApiError, ConfigError, ExportTimeoutError, HrError, SessionExpiredError
|
||||
from .query import encode
|
||||
|
||||
LOGGER = Callable[[str], None]
|
||||
|
||||
_PAGE_QUERY = {"clickFlag": "true", "treePermitType": "permit", "useSealTreeData": "0"}
|
||||
|
||||
|
||||
# ==================== 会话绑定 ====================
|
||||
|
||||
def bind_session(client, page_url: str) -> None:
|
||||
"""访问台账页并调用 ``ws/bridge`` 把 HTTP 会话注册到 WS 容器。
|
||||
|
||||
Raises:
|
||||
SessionExpiredError: 登录态失效(bridge 未返回成功)
|
||||
"""
|
||||
client.get(page_url, params=dict(_PAGE_QUERY), timeout=client.timeout)
|
||||
resp = client.post(BRIDGE_URL, data={}, timeout=10)
|
||||
text = (resp.text or "").strip()
|
||||
if "成功" not in text and text != "1":
|
||||
raise SessionExpiredError(
|
||||
f"ws/bridge 会话注册失败(登录态可能已失效):{text[:100]}")
|
||||
client.log("[INFO] ws/bridge 会话已注册")
|
||||
|
||||
|
||||
# ==================== 模板解析 ====================
|
||||
|
||||
def resolve_template(client, template_name: str, roster_id: str,
|
||||
user_id: str = "") -> Optional[str]:
|
||||
"""按模板名动态解析 ``exportFilters`` 字段串(列表 → 详情 → exportField)。
|
||||
|
||||
与页面「自定义导出」弹窗同款接口。解析失败返回 ``None``(调用方用自己的 filters)。
|
||||
"""
|
||||
if not template_name:
|
||||
return None
|
||||
try:
|
||||
resp = client.post(TEMPLATE_LIST_URL)
|
||||
data = client.as_json(resp, "导出模板列表")
|
||||
templates = data.get("jsonList") or []
|
||||
# 模板列表是全局的,同名模板可能有多条(分属不同台账 rosterId);
|
||||
# 逐个尝试,取第一条「本 rosterId 下有 exportField」的
|
||||
matches = [t for t in templates if t.get("ext1") == template_name]
|
||||
if not matches:
|
||||
names = sorted({str(t.get("ext1")) for t in templates if t.get("ext1")})
|
||||
client.log(f"[WARN] 模板列表中未找到「{template_name}」"
|
||||
f"(共 {len(names)} 个可选)")
|
||||
return None
|
||||
|
||||
for target in matches:
|
||||
detail: Dict[str, str] = {"rosterId": roster_id, "id": str(target["id"])}
|
||||
if user_id:
|
||||
detail["userId"] = user_id
|
||||
resp2 = client.post(TEMPLATE_DETAIL_URL, data=detail)
|
||||
data2 = client.as_json(resp2, "导出模板详情")
|
||||
export_field = (data2.get("result") or {}).get("exportField") or ""
|
||||
fields = json.loads(export_field) if export_field else []
|
||||
if not fields:
|
||||
continue
|
||||
filters = ",".join(str(f["tableCode"]) for f in fields)
|
||||
client.log(f"[INFO] 模板「{template_name}」解析成功({len(fields)} 列,"
|
||||
f"命中第 {matches.index(target) + 1}/{len(matches)} 条同名模板)")
|
||||
return filters
|
||||
client.log(f"[WARN] 「{template_name}」{len(matches)} 条同名模板在本台账下均无 exportField")
|
||||
return None
|
||||
except (SessionExpiredError, ApiError):
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001 - 解析失败走调用方兜底
|
||||
client.log(f"[WARN] 模板「{template_name}」解析失败:{exc}")
|
||||
return None
|
||||
|
||||
|
||||
# ==================== 参数构造 ====================
|
||||
|
||||
def build_params(base: Dict[str, str], *, conditions: Optional[Sequence[dict]] = None,
|
||||
template: str = "", filters: str = "") -> Dict[str, str]:
|
||||
"""在台账公共入参上叠加加密条件与导出配置(纯函数,便于离线自测)。"""
|
||||
params = {k: str(v) for k, v in base.items()}
|
||||
if conditions:
|
||||
params["commonQuery"] = encode(conditions)
|
||||
if template:
|
||||
if not filters:
|
||||
raise ConfigError(f"模板「{template}」没有可用字段串(filters);"
|
||||
"请先 resolve_template 或显式传 filters")
|
||||
params["exportConfig"] = json.dumps(
|
||||
{"exportName": template, "exportFilters": filters},
|
||||
ensure_ascii=False, separators=(",", ":"))
|
||||
params["_t"] = str(int(time.time() * 1000))
|
||||
return params
|
||||
|
||||
|
||||
# ==================== WS 导出 ====================
|
||||
|
||||
def _connect_ws(client):
|
||||
cookie_hdr = "; ".join(f"{c.name}={c.value}" for c in client.session.cookies
|
||||
if "hr.37du.co" in (c.domain or ""))
|
||||
ws = websocket.WebSocket()
|
||||
ws.connect(WS_SERVICE_URL, header=[
|
||||
f"Cookie: {cookie_hdr}",
|
||||
"Origin: https://hr.37du.co",
|
||||
f"User-Agent: {USER_AGENT}",
|
||||
], timeout=10)
|
||||
ws.send(json.dumps({"theme": WS_EXPORT_THEME, "code": "SUBCRIBE_THEME"}))
|
||||
ack = json.loads(ws.recv())
|
||||
if ack.get("code") != "SUBCRIBE_THEME_ACK":
|
||||
ws.close()
|
||||
raise HrError(f"WS 订阅失败:{str(ack)[:100]}")
|
||||
client.log(f"[INFO] WS 订阅成功({WS_EXPORT_THEME})")
|
||||
return ws
|
||||
|
||||
|
||||
def _wait_file_url(ws, timeout: int, log: LOGGER) -> str:
|
||||
deadline = time.time() + timeout
|
||||
ws.settimeout(timeout)
|
||||
while time.time() < deadline:
|
||||
msg = json.loads(ws.recv())
|
||||
if msg.get("code") != "NORMAL_PUSH_TO":
|
||||
continue
|
||||
text = msg.get("txt", "")
|
||||
if text.startswith("--end--"):
|
||||
return text.split("|", 1)[1].strip()
|
||||
if text.startswith(("开始下载", "正在生成")):
|
||||
log(f"[INFO] 进度:{text}")
|
||||
raise ExportTimeoutError(f"等待导出文件超时({timeout}s)")
|
||||
|
||||
|
||||
def export_table(client, *, page_url: str, export_url: str, params: Dict[str, str],
|
||||
output_path: str, filename: str = "", timeout: Optional[int] = None,
|
||||
retries: Optional[int] = None) -> str:
|
||||
"""执行一次异步导出并落盘,返回本地文件绝对路径。
|
||||
|
||||
Args:
|
||||
client: :class:`hr_sdk.client.HrClient`
|
||||
page_url: 台账页面地址(用于绑定会话)
|
||||
export_url: ``exportCommonListData.mc`` 地址
|
||||
params: 已构造好的导出入参(含 commonQuery/exportConfig)
|
||||
output_path: 目标文件路径(目录不存在会自动创建)
|
||||
filename: 覆盖文件名(默认取 output_path 末段)
|
||||
timeout: 等待推送上限(秒)
|
||||
retries: 重试次数(登录态失效不重试)
|
||||
|
||||
Raises:
|
||||
SessionExpiredError: 登录态失效
|
||||
ExportTimeoutError: 等待超时
|
||||
HrError: 提交失败/下载失败(重试耗尽)
|
||||
"""
|
||||
if not output_path:
|
||||
raise ConfigError("output_path 不能为空")
|
||||
wait = int(timeout if timeout is not None else EXPORT_TIMEOUT_SECONDS)
|
||||
attempts = max(1, int(retries if retries is not None else MAX_ATTEMPTS))
|
||||
last: Optional[BaseException] = None
|
||||
for attempt in range(1, attempts + 1):
|
||||
try:
|
||||
return _export_once(client, page_url=page_url, export_url=export_url,
|
||||
params=params, output_path=output_path,
|
||||
filename=filename, timeout=wait)
|
||||
except SessionExpiredError:
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001
|
||||
last = exc
|
||||
if attempt >= attempts:
|
||||
break
|
||||
delay = 2.0 * attempt
|
||||
client.log(f"[WARN] 导出第 {attempt}/{attempts} 次失败:{exc};{delay:.0f}s 后重试")
|
||||
time.sleep(delay)
|
||||
raise HrError(f"导出失败(重试 {attempts} 次):{last}")
|
||||
|
||||
|
||||
def _export_once(client, *, page_url: str, export_url: str, params: Dict[str, str],
|
||||
output_path: str, filename: str, timeout: int) -> str:
|
||||
bind_session(client, page_url)
|
||||
ws = _connect_ws(client)
|
||||
try:
|
||||
resp = client.post(export_url, data=params, timeout=30)
|
||||
if resp.status_code != 200:
|
||||
raise HrError(f"提交导出任务失败:HTTP {resp.status_code}")
|
||||
client.log(f"[INFO] 导出任务已提交({params.get('menuName', '')})")
|
||||
file_url = _wait_file_url(ws, timeout, client.log)
|
||||
finally:
|
||||
ws.close()
|
||||
|
||||
client.log(f"[INFO] 导出完成,文件地址:{file_url}")
|
||||
if file_url.startswith("/"):
|
||||
from .config import HR_BASE_URL
|
||||
file_url = f"{HR_BASE_URL}{file_url}"
|
||||
target_dir = os.path.dirname(os.path.abspath(output_path))
|
||||
name = filename or os.path.basename(output_path)
|
||||
os.makedirs(target_dir, exist_ok=True)
|
||||
return client.download(file_url, save_dir=target_dir, filename=name)
|
||||
|
||||
|
||||
def precheck(client, page_url: str) -> None:
|
||||
"""登录态预检:先注册会话,失效立刻抛错,避免跑到一半才发现。"""
|
||||
bind_session(client, page_url)
|
||||
|
||||
|
||||
__all__ = ["bind_session", "build_params", "export_table", "precheck", "resolve_template"]
|
||||
Reference in New Issue
Block a user