rescue: 断电事故后工作区全量备份
This commit is contained in:
@@ -1,390 +1,390 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.common.oa_api
|
||||
@FileName: flow.py
|
||||
@Description: OA 流程引擎/表单/附件接口:taskId 查 formId、businessKey 查表单数据、附件下载。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
from typing import Dict, Any, Optional
|
||||
from urllib.parse import unquote
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
try:
|
||||
from DrissionPage import SessionPage
|
||||
except ImportError:
|
||||
SessionPage = None
|
||||
|
||||
from app.service.hrbp.oa.common.config import (
|
||||
WF_ACTIVITY_URL,
|
||||
WORKFORM_ENGINE_URL,
|
||||
FILE_DOWNLOAD_URL,
|
||||
FJK_BY_IDS_URL,
|
||||
CONTRACT_SIGNATURE_SELECT_URL,
|
||||
ATTACHMENT_SAVE_DIR,
|
||||
)
|
||||
from app.service.hrbp.oa.common.oa_api.base import oa_request_json
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def get_wf_activity_by_task_id(
|
||||
session: SessionPage,
|
||||
task_id: str
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
通过 taskId 调用 WfActivity 接口获取 formId。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
task_id: SSO 解析得到的 taskId
|
||||
|
||||
Returns:
|
||||
接口返回的 JSON 字典,包含 formId 等信息
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
"""
|
||||
url = f"{WF_ACTIVITY_URL}?method=getWfActivityByTaskId"
|
||||
data = {"taskId": task_id}
|
||||
logger.info("获取 formId: taskId=%s", task_id)
|
||||
json_data = oa_request_json(session, "POST", url, data, "WfActivity")
|
||||
logger.debug("WfActivity 返回: %s", json_data)
|
||||
return json_data
|
||||
|
||||
|
||||
def extract_form_id(wf_activity_data: Dict[str, Any]) -> str:
|
||||
"""
|
||||
从 WfActivity 接口返回数据中提取 formId。
|
||||
|
||||
Args:
|
||||
wf_activity_data: get_wf_activity_by_task_id 返回的 JSON
|
||||
|
||||
Returns:
|
||||
formId 字符串
|
||||
|
||||
Raises:
|
||||
ValueError: 未找到 formId
|
||||
"""
|
||||
# 常见 formId 字段路径:顶层,以及 data / result 子对象
|
||||
form_id = (
|
||||
wf_activity_data.get("formId")
|
||||
or wf_activity_data.get("FormId")
|
||||
or wf_activity_data.get("form_id")
|
||||
)
|
||||
if not form_id:
|
||||
for key in ("data", "result"):
|
||||
data_obj = wf_activity_data.get(key, {})
|
||||
if isinstance(data_obj, dict):
|
||||
form_id = (
|
||||
data_obj.get("formId")
|
||||
or data_obj.get("FormId")
|
||||
or data_obj.get("form_id")
|
||||
)
|
||||
if form_id:
|
||||
break
|
||||
|
||||
if not form_id:
|
||||
raise ValueError(f"无法从 WfActivity 返回数据中提取 formId: {wf_activity_data}")
|
||||
|
||||
logger.info("提取到 formId: %s", form_id)
|
||||
return form_id
|
||||
|
||||
|
||||
def get_business_data(
|
||||
session: SessionPage,
|
||||
business_key: str,
|
||||
form_id: str
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
通过 businessKey 和 formId 调用 WorkformEngine 接口获取加班申请表单数据。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
business_key: SSO 解析得到的 businessKey
|
||||
form_id: 从 WfActivity 接口获取的 formId
|
||||
|
||||
Returns:
|
||||
表单详细数据字典(接口响应的 result 字段,如 ot_date/staff_name 等)
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
"""
|
||||
url = f"{WORKFORM_ENGINE_URL}?method=getBusinessDate"
|
||||
data = {
|
||||
"businessKey": business_key,
|
||||
"formId": form_id,
|
||||
}
|
||||
logger.info("获取加班表单: businessKey=%s, formId=%s", business_key, form_id)
|
||||
json_data = oa_request_json(session, "POST", url, data, "WorkformEngine")
|
||||
|
||||
# 表单详情在 result 字段中(如 ot_date / staff_name 等)
|
||||
result = json_data.get("result")
|
||||
if json_data.get("state") != "1" or not isinstance(result, dict):
|
||||
raise RuntimeError(f"WorkformEngine 接口返回失败: {json_data}")
|
||||
|
||||
logger.info("WorkformEngine 返回成功")
|
||||
return result
|
||||
|
||||
|
||||
# ==================== EHR 会话失效自愈 ====================
|
||||
# 关键坑:EHR 会话(hr.37du.co)可能中途失效(共享 cookies 过期/服务端踢下线),
|
||||
# 而待办接口在 oa.37du.co 上仍可用,导致 OA 侧会话校验检测不到——
|
||||
# 表现为附件清单/下载接口返回登录页 HTML 或"外部用户未登录,无法访问"。
|
||||
# 处置:检测到失效时用单据 SSO 详情链接(纯接口,sign 可重复使用)重建会话后重试一次。
|
||||
|
||||
|
||||
def _ehr_resp_is_login(resp) -> bool:
|
||||
"""判断响应体是否为登录页/错误 HTML(JSON/PDF/二进制流均判定为正常)。"""
|
||||
if resp is None:
|
||||
return True
|
||||
body = (resp.content or b"")[:512].lstrip().lower()
|
||||
return body.startswith(b"<!doctype") or body.startswith(b"<html")
|
||||
|
||||
|
||||
def _download_resp_is_file(resp) -> bool:
|
||||
"""判断下载响应是否为真实文件流(Content-Disposition 或 %PDF 头)。"""
|
||||
if resp is None or resp.status_code != 200:
|
||||
return False
|
||||
if resp.headers.get("Content-Disposition"):
|
||||
return True
|
||||
return (resp.content or b"")[:5] == b"%PDF-"
|
||||
|
||||
|
||||
def _rebuild_ehr_session(session, detail_url: str) -> bool:
|
||||
"""EHR 会话失效时访问单据 SSO 详情链接重建会话(纯接口即可,无需浏览器)。"""
|
||||
if not detail_url:
|
||||
return False
|
||||
logger.warning("EHR 会话失效,访问单据详情链接重建会话")
|
||||
try:
|
||||
session.get(detail_url)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.warning("重建 EHR 会话失败: %s", e)
|
||||
return False
|
||||
|
||||
|
||||
def get_fjk_file_list(
|
||||
session: SessionPage,
|
||||
file_ids: str,
|
||||
detail_url: str = None,
|
||||
) -> list:
|
||||
"""
|
||||
按 fileId 列表调用 getFjkByIds 查询附件清单。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象(已带登录 Cookie)
|
||||
file_ids: 逗号分隔的多个 fileId(如表单 result.contract_file 字段)
|
||||
detail_url: 单据 SSO 详情链接,用于 EHR 会话失效时重建会话重试
|
||||
|
||||
Returns:
|
||||
附件清单(jsonList),每项含 id/fileName/fileSuffix/herfUrl/fileSize 等;
|
||||
无有效 fileId 时返回空列表。
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
"""
|
||||
ids = [x.strip() for x in str(file_ids).split(",") if x.strip()]
|
||||
if not ids:
|
||||
return []
|
||||
data = {"ids": ",".join(ids)}
|
||||
logger.info("查询附件清单: ids=%s", ids)
|
||||
for attempt in (1, 2):
|
||||
session.post(FJK_BY_IDS_URL, data=data)
|
||||
resp = session.response
|
||||
if resp is not None and resp.status_code == 200 and not _ehr_resp_is_login(resp):
|
||||
json_data = resp.json()
|
||||
logger.debug("getFjkByIds 返回: %s", json_data)
|
||||
return json_data.get("jsonList") or []
|
||||
if attempt == 1 and _rebuild_ehr_session(session, detail_url):
|
||||
continue
|
||||
raise RuntimeError(
|
||||
f"getFjkByIds 接口响应异常: {resp.status_code if resp else '无响应'}"
|
||||
f"({((resp.text or '')[:80] if resp else '')})"
|
||||
)
|
||||
|
||||
|
||||
def download_attachment(
|
||||
session: SessionPage,
|
||||
file_id: str,
|
||||
save_dir: str = ATTACHMENT_SAVE_DIR,
|
||||
detail_url: str = None,
|
||||
) -> Optional[str]:
|
||||
"""
|
||||
根据附件 fileId 从 OA 下载请假单据附件,支持多附件(逗号分隔多个 fileId)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象(已带登录 Cookie)
|
||||
file_id: 附件 fileId 或逗号分隔的多个 fileId(表单 result.file 字段值)
|
||||
save_dir: 保存目录(默认 downloads)
|
||||
detail_url: 单据 SSO 详情链接,用于 EHR 会话失效时重建会话重试
|
||||
|
||||
Returns:
|
||||
成功保存的文件路径;多附件或下载失败时返回逗号拼接的相对路径列表
|
||||
(保持与历史单附件行为一致:单个成功仍返回单个路径字符串)。
|
||||
"""
|
||||
if not file_id:
|
||||
logger.warning("附件 fileId 为空,跳过下载")
|
||||
return None
|
||||
|
||||
# 兼容多附件:file 字段可能为逗号分隔的多个 fileId,逐个下载
|
||||
ids = [x.strip() for x in str(file_id).split(",") if x.strip()]
|
||||
saved = []
|
||||
for fid in ids:
|
||||
path = _download_one(session, fid, save_dir, detail_url=detail_url)
|
||||
if path:
|
||||
saved.append(path)
|
||||
if not saved:
|
||||
return None
|
||||
return ",".join(saved)
|
||||
|
||||
|
||||
def _download_one(
|
||||
session: SessionPage,
|
||||
file_id: str,
|
||||
save_dir: str,
|
||||
detail_url: str = None,
|
||||
) -> Optional[str]:
|
||||
"""
|
||||
下载单个附件 fileId,返回本地保存路径;失败返回 None。
|
||||
|
||||
会话失效(响应非文件流)时先经 detail_url 重建 EHR 会话再重试一次。
|
||||
"""
|
||||
if not file_id:
|
||||
return None
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
url = f"{FILE_DOWNLOAD_URL}?fileId={file_id}"
|
||||
logger.info("下载附件: fileId=%s", file_id)
|
||||
|
||||
resp = None
|
||||
for attempt in (1, 2):
|
||||
try:
|
||||
session.get(url)
|
||||
resp = session.response
|
||||
except Exception as e:
|
||||
logger.warning("附件请求失败(fileId=%s): %s", file_id, e)
|
||||
if _download_resp_is_file(resp):
|
||||
break
|
||||
logger.warning("附件响应异常(fileId=%s): HTTP %s, 内容: %s",
|
||||
file_id,
|
||||
resp.status_code if resp else "无响应",
|
||||
((resp.content or b"")[:60] if resp else b""))
|
||||
if attempt == 1 and _rebuild_ehr_session(session, detail_url):
|
||||
continue
|
||||
return None
|
||||
|
||||
# 从 Content-Disposition 解析真实文件名(可能带 UTF-8'' 编码)
|
||||
filename = None
|
||||
cd = resp.headers.get("Content-Disposition", "")
|
||||
if "filename=" in cd:
|
||||
raw = cd.split("filename=")[-1].strip().strip('"')
|
||||
if raw.startswith("UTF-8''"):
|
||||
raw = unquote(raw.split("UTF-8''", 1)[1])
|
||||
if raw:
|
||||
filename = raw
|
||||
|
||||
# 解析不到文件名时,用 fileId 兜底,并按 Content-Type 补扩展名
|
||||
if not filename:
|
||||
filename = file_id
|
||||
ct = (resp.headers.get("Content-Type") or "").split(";")[0].strip().lower()
|
||||
ext_map = {
|
||||
"image/png": ".png",
|
||||
"image/jpeg": ".jpg",
|
||||
"application/pdf": ".pdf",
|
||||
"application/octet-stream": ".bin",
|
||||
}
|
||||
filename += ext_map.get(ct, ".bin")
|
||||
|
||||
# 清理非法字符,防止路径注入
|
||||
filename = "".join(c for c in filename if c not in '\\/:*?"<>|')
|
||||
path = os.path.join(save_dir, filename)
|
||||
# 多附件可能出现同名文件导致覆盖:追加 fileId 短后缀区分
|
||||
counter = 1
|
||||
base, ext = os.path.splitext(filename)
|
||||
while os.path.exists(path):
|
||||
path = os.path.join(save_dir, f"{base}_{file_id[:8]}_{counter}{ext}")
|
||||
counter += 1
|
||||
with open(path, "wb") as f:
|
||||
f.write(resp.content)
|
||||
logger.info("附件已下载: %s", path)
|
||||
return path
|
||||
|
||||
|
||||
# ==================== 电子签真实签署状态查询 ====================
|
||||
# getBusinessDate 返回的 ext_is_initiate_sign / ext_staff_sign_status / ext_org_sign_status
|
||||
# 恒为空串,拿不到真实签署状态;需再调该查询接口(按 main_id 即合同业务主键)取真实状态
|
||||
|
||||
|
||||
def get_contract_sign_status(session: SessionPage, contract_id: str) -> Dict[str, Any]:
|
||||
"""
|
||||
查询电子签真实签署状态。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
contract_id: 合同业务主键(= getBusinessData 返回的 main_id / SSO businessKey)
|
||||
|
||||
Returns:
|
||||
{"is_initiate_sign": ..., "sign_status_yg": ..., "sign_status_qy": ...,
|
||||
"file": 签章附件 fileId 串(可能为 None/空)}
|
||||
查询失败抛 RuntimeError。
|
||||
"""
|
||||
session.post(CONTRACT_SIGNATURE_SELECT_URL, data={
|
||||
"contract_id": contract_id,
|
||||
"inParamFormId": "",
|
||||
"colCode": "main_id",
|
||||
})
|
||||
resp = session.response
|
||||
if not resp:
|
||||
raise RuntimeError("签署状态查询请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"签署状态查询接口状态码异常: {resp.status_code}")
|
||||
try:
|
||||
json_data = resp.json()
|
||||
except Exception:
|
||||
body = (resp.text or "")[:200]
|
||||
raise RuntimeError(f"签署状态查询接口返回非 JSON 数据(状态码 {resp.status_code}): {body}")
|
||||
|
||||
result = json_data.get("result")
|
||||
if json_data.get("state") != "1" or not isinstance(result, dict):
|
||||
# 业务层执行异常(如该合同无电子签记录,服务端存储过程报错):稳定可复现,
|
||||
# 重试无意义,按"查不到状态"处理——返回空状态,由校验归为"未完成"(不管)
|
||||
logger.warning("签署状态查询业务异常(按未完成处理): contract_id=%s, meg=%s",
|
||||
contract_id, json_data.get("meg"))
|
||||
return {
|
||||
"is_initiate_sign": None,
|
||||
"sign_status_yg": None,
|
||||
"sign_status_qy": None,
|
||||
"file": None,
|
||||
}
|
||||
|
||||
logger.info("签署状态查询成功: contract_id=%s", contract_id)
|
||||
return {
|
||||
"is_initiate_sign": result.get("is_initiate_sign"),
|
||||
"sign_status_yg": result.get("sign_status_yg"),
|
||||
"sign_status_qy": result.get("sign_status_qy"),
|
||||
"file": result.get("file"),
|
||||
}
|
||||
|
||||
|
||||
def enrich_form_sign_status(form_data: Dict[str, Any], session: SessionPage) -> Dict[str, Any]:
|
||||
"""
|
||||
把 getBusinessData 返回的表单数据中的电子签三状态字段补上真实值。
|
||||
|
||||
表单 result 里 ext_is_initiate_sign/ext_staff_sign_status/ext_org_sign_status 恒为空串,
|
||||
需按 main_id 再调签署状态查询接口,把真实状态写回这三个字段,供后续校验使用。
|
||||
接口变更:表单 contract_file 已恒为空串,签章附件 fileId 改从签署记录 file 字段获取
|
||||
(",id1,id2" 格式,get_fjk_file_list 按逗号拆分可容忍前导逗号)。
|
||||
"""
|
||||
contract_id = form_data.get("main_id")
|
||||
if not contract_id:
|
||||
raise RuntimeError("表单数据缺少 main_id,无法查询电子签签署状态")
|
||||
sign_status = get_contract_sign_status(session, contract_id)
|
||||
form_data["ext_is_initiate_sign"] = sign_status["is_initiate_sign"]
|
||||
form_data["ext_staff_sign_status"] = sign_status["sign_status_yg"]
|
||||
form_data["ext_org_sign_status"] = sign_status["sign_status_qy"]
|
||||
form_data["contract_file"] = (
|
||||
(sign_status.get("file") or "").strip()
|
||||
or (form_data.get("contract_file") or "").strip()
|
||||
)
|
||||
return form_data
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.common.oa_api
|
||||
@FileName: flow.py
|
||||
@Description: OA 流程引擎/表单/附件接口:taskId 查 formId、businessKey 查表单数据、附件下载。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
from typing import Dict, Any, Optional
|
||||
from urllib.parse import unquote
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
try:
|
||||
from DrissionPage import SessionPage
|
||||
except ImportError:
|
||||
SessionPage = None
|
||||
|
||||
from app.service.hrbp.oa.common.config import (
|
||||
WF_ACTIVITY_URL,
|
||||
WORKFORM_ENGINE_URL,
|
||||
FILE_DOWNLOAD_URL,
|
||||
FJK_BY_IDS_URL,
|
||||
CONTRACT_SIGNATURE_SELECT_URL,
|
||||
ATTACHMENT_SAVE_DIR,
|
||||
)
|
||||
from app.service.hrbp.oa.common.oa_api.base import oa_request_json
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def get_wf_activity_by_task_id(
|
||||
session: SessionPage,
|
||||
task_id: str
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
通过 taskId 调用 WfActivity 接口获取 formId。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
task_id: SSO 解析得到的 taskId
|
||||
|
||||
Returns:
|
||||
接口返回的 JSON 字典,包含 formId 等信息
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
"""
|
||||
url = f"{WF_ACTIVITY_URL}?method=getWfActivityByTaskId"
|
||||
data = {"taskId": task_id}
|
||||
logger.info("获取 formId: taskId=%s", task_id)
|
||||
json_data = oa_request_json(session, "POST", url, data, "WfActivity")
|
||||
logger.debug("WfActivity 返回: %s", json_data)
|
||||
return json_data
|
||||
|
||||
|
||||
def extract_form_id(wf_activity_data: Dict[str, Any]) -> str:
|
||||
"""
|
||||
从 WfActivity 接口返回数据中提取 formId。
|
||||
|
||||
Args:
|
||||
wf_activity_data: get_wf_activity_by_task_id 返回的 JSON
|
||||
|
||||
Returns:
|
||||
formId 字符串
|
||||
|
||||
Raises:
|
||||
ValueError: 未找到 formId
|
||||
"""
|
||||
# 常见 formId 字段路径:顶层,以及 data / result 子对象
|
||||
form_id = (
|
||||
wf_activity_data.get("formId")
|
||||
or wf_activity_data.get("FormId")
|
||||
or wf_activity_data.get("form_id")
|
||||
)
|
||||
if not form_id:
|
||||
for key in ("data", "result"):
|
||||
data_obj = wf_activity_data.get(key, {})
|
||||
if isinstance(data_obj, dict):
|
||||
form_id = (
|
||||
data_obj.get("formId")
|
||||
or data_obj.get("FormId")
|
||||
or data_obj.get("form_id")
|
||||
)
|
||||
if form_id:
|
||||
break
|
||||
|
||||
if not form_id:
|
||||
raise ValueError(f"无法从 WfActivity 返回数据中提取 formId: {wf_activity_data}")
|
||||
|
||||
logger.info("提取到 formId: %s", form_id)
|
||||
return form_id
|
||||
|
||||
|
||||
def get_business_data(
|
||||
session: SessionPage,
|
||||
business_key: str,
|
||||
form_id: str
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
通过 businessKey 和 formId 调用 WorkformEngine 接口获取加班申请表单数据。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
business_key: SSO 解析得到的 businessKey
|
||||
form_id: 从 WfActivity 接口获取的 formId
|
||||
|
||||
Returns:
|
||||
表单详细数据字典(接口响应的 result 字段,如 ot_date/staff_name 等)
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
"""
|
||||
url = f"{WORKFORM_ENGINE_URL}?method=getBusinessDate"
|
||||
data = {
|
||||
"businessKey": business_key,
|
||||
"formId": form_id,
|
||||
}
|
||||
logger.info("获取加班表单: businessKey=%s, formId=%s", business_key, form_id)
|
||||
json_data = oa_request_json(session, "POST", url, data, "WorkformEngine")
|
||||
|
||||
# 表单详情在 result 字段中(如 ot_date / staff_name 等)
|
||||
result = json_data.get("result")
|
||||
if json_data.get("state") != "1" or not isinstance(result, dict):
|
||||
raise RuntimeError(f"WorkformEngine 接口返回失败: {json_data}")
|
||||
|
||||
logger.info("WorkformEngine 返回成功")
|
||||
return result
|
||||
|
||||
|
||||
# ==================== EHR 会话失效自愈 ====================
|
||||
# 关键坑:EHR 会话(hr.37du.co)可能中途失效(共享 cookies 过期/服务端踢下线),
|
||||
# 而待办接口在 oa.37du.co 上仍可用,导致 OA 侧会话校验检测不到——
|
||||
# 表现为附件清单/下载接口返回登录页 HTML 或"外部用户未登录,无法访问"。
|
||||
# 处置:检测到失效时用单据 SSO 详情链接(纯接口,sign 可重复使用)重建会话后重试一次。
|
||||
|
||||
|
||||
def _ehr_resp_is_login(resp) -> bool:
|
||||
"""判断响应体是否为登录页/错误 HTML(JSON/PDF/二进制流均判定为正常)。"""
|
||||
if resp is None:
|
||||
return True
|
||||
body = (resp.content or b"")[:512].lstrip().lower()
|
||||
return body.startswith(b"<!doctype") or body.startswith(b"<html")
|
||||
|
||||
|
||||
def _download_resp_is_file(resp) -> bool:
|
||||
"""判断下载响应是否为真实文件流(Content-Disposition 或 %PDF 头)。"""
|
||||
if resp is None or resp.status_code != 200:
|
||||
return False
|
||||
if resp.headers.get("Content-Disposition"):
|
||||
return True
|
||||
return (resp.content or b"")[:5] == b"%PDF-"
|
||||
|
||||
|
||||
def _rebuild_ehr_session(session, detail_url: str) -> bool:
|
||||
"""EHR 会话失效时访问单据 SSO 详情链接重建会话(纯接口即可,无需浏览器)。"""
|
||||
if not detail_url:
|
||||
return False
|
||||
logger.warning("EHR 会话失效,访问单据详情链接重建会话")
|
||||
try:
|
||||
session.get(detail_url)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.warning("重建 EHR 会话失败: %s", e)
|
||||
return False
|
||||
|
||||
|
||||
def get_fjk_file_list(
|
||||
session: SessionPage,
|
||||
file_ids: str,
|
||||
detail_url: str = None,
|
||||
) -> list:
|
||||
"""
|
||||
按 fileId 列表调用 getFjkByIds 查询附件清单。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象(已带登录 Cookie)
|
||||
file_ids: 逗号分隔的多个 fileId(如表单 result.contract_file 字段)
|
||||
detail_url: 单据 SSO 详情链接,用于 EHR 会话失效时重建会话重试
|
||||
|
||||
Returns:
|
||||
附件清单(jsonList),每项含 id/fileName/fileSuffix/herfUrl/fileSize 等;
|
||||
无有效 fileId 时返回空列表。
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
"""
|
||||
ids = [x.strip() for x in str(file_ids).split(",") if x.strip()]
|
||||
if not ids:
|
||||
return []
|
||||
data = {"ids": ",".join(ids)}
|
||||
logger.info("查询附件清单: ids=%s", ids)
|
||||
for attempt in (1, 2):
|
||||
session.post(FJK_BY_IDS_URL, data=data)
|
||||
resp = session.response
|
||||
if resp is not None and resp.status_code == 200 and not _ehr_resp_is_login(resp):
|
||||
json_data = resp.json()
|
||||
logger.debug("getFjkByIds 返回: %s", json_data)
|
||||
return json_data.get("jsonList") or []
|
||||
if attempt == 1 and _rebuild_ehr_session(session, detail_url):
|
||||
continue
|
||||
raise RuntimeError(
|
||||
f"getFjkByIds 接口响应异常: {resp.status_code if resp else '无响应'}"
|
||||
f"({((resp.text or '')[:80] if resp else '')})"
|
||||
)
|
||||
|
||||
|
||||
def download_attachment(
|
||||
session: SessionPage,
|
||||
file_id: str,
|
||||
save_dir: str = ATTACHMENT_SAVE_DIR,
|
||||
detail_url: str = None,
|
||||
) -> Optional[str]:
|
||||
"""
|
||||
根据附件 fileId 从 OA 下载请假单据附件,支持多附件(逗号分隔多个 fileId)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象(已带登录 Cookie)
|
||||
file_id: 附件 fileId 或逗号分隔的多个 fileId(表单 result.file 字段值)
|
||||
save_dir: 保存目录(默认 downloads)
|
||||
detail_url: 单据 SSO 详情链接,用于 EHR 会话失效时重建会话重试
|
||||
|
||||
Returns:
|
||||
成功保存的文件路径;多附件或下载失败时返回逗号拼接的相对路径列表
|
||||
(保持与历史单附件行为一致:单个成功仍返回单个路径字符串)。
|
||||
"""
|
||||
if not file_id:
|
||||
logger.warning("附件 fileId 为空,跳过下载")
|
||||
return None
|
||||
|
||||
# 兼容多附件:file 字段可能为逗号分隔的多个 fileId,逐个下载
|
||||
ids = [x.strip() for x in str(file_id).split(",") if x.strip()]
|
||||
saved = []
|
||||
for fid in ids:
|
||||
path = _download_one(session, fid, save_dir, detail_url=detail_url)
|
||||
if path:
|
||||
saved.append(path)
|
||||
if not saved:
|
||||
return None
|
||||
return ",".join(saved)
|
||||
|
||||
|
||||
def _download_one(
|
||||
session: SessionPage,
|
||||
file_id: str,
|
||||
save_dir: str,
|
||||
detail_url: str = None,
|
||||
) -> Optional[str]:
|
||||
"""
|
||||
下载单个附件 fileId,返回本地保存路径;失败返回 None。
|
||||
|
||||
会话失效(响应非文件流)时先经 detail_url 重建 EHR 会话再重试一次。
|
||||
"""
|
||||
if not file_id:
|
||||
return None
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
url = f"{FILE_DOWNLOAD_URL}?fileId={file_id}"
|
||||
logger.info("下载附件: fileId=%s", file_id)
|
||||
|
||||
resp = None
|
||||
for attempt in (1, 2):
|
||||
try:
|
||||
session.get(url)
|
||||
resp = session.response
|
||||
except Exception as e:
|
||||
logger.warning("附件请求失败(fileId=%s): %s", file_id, e)
|
||||
if _download_resp_is_file(resp):
|
||||
break
|
||||
logger.warning("附件响应异常(fileId=%s): HTTP %s, 内容: %s",
|
||||
file_id,
|
||||
resp.status_code if resp else "无响应",
|
||||
((resp.content or b"")[:60] if resp else b""))
|
||||
if attempt == 1 and _rebuild_ehr_session(session, detail_url):
|
||||
continue
|
||||
return None
|
||||
|
||||
# 从 Content-Disposition 解析真实文件名(可能带 UTF-8'' 编码)
|
||||
filename = None
|
||||
cd = resp.headers.get("Content-Disposition", "")
|
||||
if "filename=" in cd:
|
||||
raw = cd.split("filename=")[-1].strip().strip('"')
|
||||
if raw.startswith("UTF-8''"):
|
||||
raw = unquote(raw.split("UTF-8''", 1)[1])
|
||||
if raw:
|
||||
filename = raw
|
||||
|
||||
# 解析不到文件名时,用 fileId 兜底,并按 Content-Type 补扩展名
|
||||
if not filename:
|
||||
filename = file_id
|
||||
ct = (resp.headers.get("Content-Type") or "").split(";")[0].strip().lower()
|
||||
ext_map = {
|
||||
"image/png": ".png",
|
||||
"image/jpeg": ".jpg",
|
||||
"application/pdf": ".pdf",
|
||||
"application/octet-stream": ".bin",
|
||||
}
|
||||
filename += ext_map.get(ct, ".bin")
|
||||
|
||||
# 清理非法字符,防止路径注入
|
||||
filename = "".join(c for c in filename if c not in '\\/:*?"<>|')
|
||||
path = os.path.join(save_dir, filename)
|
||||
# 多附件可能出现同名文件导致覆盖:追加 fileId 短后缀区分
|
||||
counter = 1
|
||||
base, ext = os.path.splitext(filename)
|
||||
while os.path.exists(path):
|
||||
path = os.path.join(save_dir, f"{base}_{file_id[:8]}_{counter}{ext}")
|
||||
counter += 1
|
||||
with open(path, "wb") as f:
|
||||
f.write(resp.content)
|
||||
logger.info("附件已下载: %s", path)
|
||||
return path
|
||||
|
||||
|
||||
# ==================== 电子签真实签署状态查询 ====================
|
||||
# getBusinessDate 返回的 ext_is_initiate_sign / ext_staff_sign_status / ext_org_sign_status
|
||||
# 恒为空串,拿不到真实签署状态;需再调该查询接口(按 main_id 即合同业务主键)取真实状态
|
||||
|
||||
|
||||
def get_contract_sign_status(session: SessionPage, contract_id: str) -> Dict[str, Any]:
|
||||
"""
|
||||
查询电子签真实签署状态。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
contract_id: 合同业务主键(= getBusinessData 返回的 main_id / SSO businessKey)
|
||||
|
||||
Returns:
|
||||
{"is_initiate_sign": ..., "sign_status_yg": ..., "sign_status_qy": ...,
|
||||
"file": 签章附件 fileId 串(可能为 None/空)}
|
||||
查询失败抛 RuntimeError。
|
||||
"""
|
||||
session.post(CONTRACT_SIGNATURE_SELECT_URL, data={
|
||||
"contract_id": contract_id,
|
||||
"inParamFormId": "",
|
||||
"colCode": "main_id",
|
||||
})
|
||||
resp = session.response
|
||||
if not resp:
|
||||
raise RuntimeError("签署状态查询请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"签署状态查询接口状态码异常: {resp.status_code}")
|
||||
try:
|
||||
json_data = resp.json()
|
||||
except Exception:
|
||||
body = (resp.text or "")[:200]
|
||||
raise RuntimeError(f"签署状态查询接口返回非 JSON 数据(状态码 {resp.status_code}): {body}")
|
||||
|
||||
result = json_data.get("result")
|
||||
if json_data.get("state") != "1" or not isinstance(result, dict):
|
||||
# 业务层执行异常(如该合同无电子签记录,服务端存储过程报错):稳定可复现,
|
||||
# 重试无意义,按"查不到状态"处理——返回空状态,由校验归为"未完成"(不管)
|
||||
logger.warning("签署状态查询业务异常(按未完成处理): contract_id=%s, meg=%s",
|
||||
contract_id, json_data.get("meg"))
|
||||
return {
|
||||
"is_initiate_sign": None,
|
||||
"sign_status_yg": None,
|
||||
"sign_status_qy": None,
|
||||
"file": None,
|
||||
}
|
||||
|
||||
logger.info("签署状态查询成功: contract_id=%s", contract_id)
|
||||
return {
|
||||
"is_initiate_sign": result.get("is_initiate_sign"),
|
||||
"sign_status_yg": result.get("sign_status_yg"),
|
||||
"sign_status_qy": result.get("sign_status_qy"),
|
||||
"file": result.get("file"),
|
||||
}
|
||||
|
||||
|
||||
def enrich_form_sign_status(form_data: Dict[str, Any], session: SessionPage) -> Dict[str, Any]:
|
||||
"""
|
||||
把 getBusinessData 返回的表单数据中的电子签三状态字段补上真实值。
|
||||
|
||||
表单 result 里 ext_is_initiate_sign/ext_staff_sign_status/ext_org_sign_status 恒为空串,
|
||||
需按 main_id 再调签署状态查询接口,把真实状态写回这三个字段,供后续校验使用。
|
||||
接口变更:表单 contract_file 已恒为空串,签章附件 fileId 改从签署记录 file 字段获取
|
||||
(",id1,id2" 格式,get_fjk_file_list 按逗号拆分可容忍前导逗号)。
|
||||
"""
|
||||
contract_id = form_data.get("main_id")
|
||||
if not contract_id:
|
||||
raise RuntimeError("表单数据缺少 main_id,无法查询电子签签署状态")
|
||||
sign_status = get_contract_sign_status(session, contract_id)
|
||||
form_data["ext_is_initiate_sign"] = sign_status["is_initiate_sign"]
|
||||
form_data["ext_staff_sign_status"] = sign_status["sign_status_yg"]
|
||||
form_data["ext_org_sign_status"] = sign_status["sign_status_qy"]
|
||||
form_data["contract_file"] = (
|
||||
(sign_status.get("file") or "").strip()
|
||||
or (form_data.get("contract_file") or "").strip()
|
||||
)
|
||||
return form_data
|
||||
|
||||
Reference in New Issue
Block a user