diff --git a/aa.md b/aa.md
index 77bafea..0b44274 100644
--- a/aa.md
+++ b/aa.md
@@ -1,2 +1,288 @@
-
-
+ 请求 URL
+https://hr.37du.co/RedseaPlatform/WorkformEngine.mc?method=getBusinessDate
+请求方法
+POST
+businessKey=bpmf69a3651bd624894b0527d52323d2577&formId=10a0b2ce-1b42-4576-97fa-974df67bad39
+{
+ "state" : "1",
+ "meg" : "处理成功",
+ "des" : "",
+ "result" : {
+ "base_code" : "37022119",
+ "belong_unit_org_name" : "金色印象事业部",
+ "belong_unit_stru_id" : "0bcdedeb-e592-11ee-b449-000c296f9469",
+ "contract_deadline" : "12",
+ "contract_end_date" : "2027-07-31",
+ "contract_file" : "",
+ "contract_start_date" : "2026-08-01",
+ "contract_type" : "0",
+ "contract_type_template" : "3cd64878-0261-4ebc-ae03-e2d68bfca8cc,95d5c603-a9e3-4ae4-b48c-927aeeed6128,b269d6d6-51ff-4da9-bb0a-8a615890385d",
+ "current_contract_id" : "d7ec411d-cb5c-11f0-a7d9-000c296f9469",
+ "end_date2" : "2026-08-01",
+ "end_time" : "2027-08-01",
+ "ext_is_initiate_sign" : "",
+ "ext_leave_template" : "a2a41822-32ae-4007-84f7-e95aecdcb081,078df1ce-ad35-44cf-849c-dcbab32af4bc",
+ "ext_org_sign_status" : "",
+ "ext_push_time" : "2026-08-20",
+ "ext_staff_sign_status" : "",
+ "ext_technician_code" : "",
+ "file" : "",
+ "first_type_id" : "9d73c973-919a-4a26-a692-664bcb8fef02",
+ "idcard" : "511623200311056533",
+ "identity" : "1",
+ "is_new_sign" : "1",
+ "leaveoffice_time" : "2026-07-31",
+ "leaveoffice_type" : "ext_8",
+ "main_id" : "bpmf69a3651bd624894b0527d52323d2577",
+ "mobile_phone" : "19950986716",
+ "move_id" : "",
+ "org_full_path" : "集团-金色印象事业部-第一大区-金色印象重庆第一经营中心-第四片区-石油路PLUS会馆-接待组",
+ "post_name" : "接待员",
+ "post_no" : "232",
+ "post_org_name" : "接待员",
+ "si_area" : "e5e14ddb-9a0e-11f1-a7d9-000c296f9469",
+ "staff_id" : "0f8a5181-e812-4bf9-b082-ac06343f1f1d",
+ "staff_name" : "夏礼广",
+ "treaty_type" : "1",
+ "trigger_type" : "2"
+ },
+ "total" : "",
+ "jsonList" : null,
+ "viewMapper" : null,
+ "record" : false
+}
+是否已发起电子签字典
+"hr_staff_contract.is_initiate_sign" : [ {
+ "code" : "1",
+ "name" : "已发起",
+ "codeType" : "hr_staff_contract.is_initiate_sign",
+ "parentCode" : "",
+ "description" : "",
+ "operator" : "张宝塔",
+ "operatTime" : "2026-08-18 17:56:07",
+ "inUse" : "1",
+ "char1" : "",
+ "char2" : "",
+ "num1" : 1,
+ "num2" : 0.0,
+ "operatorName" : null,
+ "groupName" : null,
+ "codeTypeName" : null,
+ "groupId" : null,
+ "fullPathCode" : null,
+ "fullPathName" : null,
+ "createTime" : null,
+ "oldCode" : null
+ }, {
+ "code" : "0",
+ "name" : "未发起",
+ "codeType" : "hr_staff_contract.is_initiate_sign",
+ "parentCode" : "",
+ "description" : "",
+ "operator" : "张宝塔",
+ "operatTime" : "2026-08-18 17:56:07",
+ "inUse" : "1",
+ "char1" : "",
+ "char2" : "",
+ "num1" : 2,
+ "num2" : 0.0,
+ "operatorName" : null,
+ "groupName" : null,
+ "codeTypeName" : null,
+ "groupId" : null,
+ "fullPathCode" : null,
+ "fullPathName" : null,
+ "createTime" : null,
+ "oldCode" : null
+ }, {
+ "code" : "2",
+ "name" : "已完成",
+ "codeType" : "hr_staff_contract.is_initiate_sign",
+ "parentCode" : "",
+ "description" : "",
+ "operator" : "张宝塔",
+ "operatTime" : "2026-08-18 17:56:07",
+ "inUse" : "1",
+ "char1" : "",
+ "char2" : "",
+ "num1" : 3,
+ "num2" : 1.0,
+ "operatorName" : null,
+ "groupName" : null,
+ "codeTypeName" : null,
+ "groupId" : null,
+ "fullPathCode" : null,
+ "fullPathName" : null,
+ "createTime" : null,
+ "oldCode" : null
+ }, {
+ "code" : "3",
+ "name" : "已撤销",
+ "codeType" : "hr_staff_contract.is_initiate_sign",
+ "parentCode" : "",
+ "description" : "",
+ "operator" : "张宝塔",
+ "operatTime" : "2026-08-18 17:56:07",
+ "inUse" : "1",
+ "char1" : "",
+ "char2" : "",
+ "num1" : 4,
+ "num2" : 1.0,
+ "operatorName" : null,
+ "groupName" : null,
+ "codeTypeName" : null,
+ "groupId" : null,
+ "fullPathCode" : null,
+ "fullPathName" : null,
+ "createTime" : null,
+ "oldCode" : null
+ }, {
+ "code" : "5",
+ "name" : "已过期",
+ "codeType" : "hr_staff_contract.is_initiate_sign",
+ "parentCode" : "",
+ "description" : "",
+ "operator" : "张宝塔",
+ "operatTime" : "2026-08-18 17:56:07",
+ "inUse" : "1",
+ "char1" : "",
+ "char2" : "",
+ "num1" : 5,
+ "num2" : 1.0,
+ "operatorName" : null,
+ "groupName" : null,
+ "codeTypeName" : null,
+ "groupId" : null,
+ "fullPathCode" : null,
+ "fullPathName" : null,
+ "createTime" : null,
+ "oldCode" : null
+ }, {
+ "code" : "7",
+ "name" : "已拒签",
+ "codeType" : "hr_staff_contract.is_initiate_sign",
+ "parentCode" : "",
+ "description" : "",
+ "operator" : "张宝塔",
+ "operatTime" : "2026-08-18 17:56:07",
+ "inUse" : "1",
+ "char1" : "",
+ "char2" : "",
+ "num1" : 6,
+ "num2" : 1.0,
+ "operatorName" : null,
+ "groupName" : null,
+ "codeTypeName" : null,
+ "groupId" : null,
+ "fullPathCode" : null,
+ "fullPathName" : null,
+ "createTime" : null,
+ "oldCode" : null
+ }, {
+ "code" : "8",
+ "name" : "已作废",
+ "codeType" : "hr_staff_contract.is_initiate_sign",
+ "parentCode" : "",
+ "description" : "",
+ "operator" : "张宝塔",
+ "operatTime" : "2026-08-18 17:56:07",
+ "inUse" : "1",
+ "char1" : "",
+ "char2" : "",
+ "num1" : 7,
+ "num2" : 0.0,
+ "operatorName" : null,
+ "groupName" : null,
+ "codeTypeName" : null,
+ "groupId" : null,
+ "fullPathCode" : null,
+ "fullPathName" : null,
+ "createTime" : null,
+ "oldCode" : null
+ }
+ 员工签署状态/企业签署状态字典
+ "esign_sigin_state" : [ {
+ "code" : "1",
+ "name" : "签署中",
+ "codeType" : "esign_sigin_state",
+ "parentCode" : "",
+ "description" : "",
+ "operator" : "张宝塔",
+ "operatTime" : "2026-08-18 17:56:07",
+ "inUse" : "1",
+ "char1" : "",
+ "char2" : "",
+ "num1" : 1,
+ "num2" : 0,
+ "operatorName" : null,
+ "groupName" : null,
+ "codeTypeName" : null,
+ "groupId" : null,
+ "fullPathCode" : null,
+ "fullPathName" : null,
+ "createTime" : null,
+ "oldCode" : null
+ }, {
+ "code" : "2",
+ "name" : "已完成",
+ "codeType" : "esign_sigin_state",
+ "parentCode" : "",
+ "description" : "",
+ "operator" : "张宝塔",
+ "operatTime" : "2026-08-18 17:56:07",
+ "inUse" : "1",
+ "char1" : "",
+ "char2" : "",
+ "num1" : 2,
+ "num2" : 0,
+ "operatorName" : null,
+ "groupName" : null,
+ "codeTypeName" : null,
+ "groupId" : null,
+ "fullPathCode" : null,
+ "fullPathName" : null,
+ "createTime" : null,
+ "oldCode" : null
+ }, {
+ "code" : "3",
+ "name" : "未完成",
+ "codeType" : "esign_sigin_state",
+ "parentCode" : "",
+ "description" : "",
+ "operator" : "张宝塔",
+ "operatTime" : "2026-08-18 17:56:07",
+ "inUse" : "1",
+ "char1" : "",
+ "char2" : "",
+ "num1" : 3,
+ "num2" : 0,
+ "operatorName" : null,
+ "groupName" : null,
+ "codeTypeName" : null,
+ "groupId" : null,
+ "fullPathCode" : null,
+ "fullPathName" : null,
+ "createTime" : null,
+ "oldCode" : null
+ }, {
+ "code" : "4",
+ "name" : "已作废",
+ "codeType" : "esign_sigin_state",
+ "parentCode" : "",
+ "description" : "",
+ "operator" : "张宝塔",
+ "operatTime" : "2026-08-18 17:56:07",
+ "inUse" : "1",
+ "char1" : "",
+ "char2" : "",
+ "num1" : 4,
+ "num2" : 0,
+ "operatorName" : null,
+ "groupName" : null,
+ "codeTypeName" : null,
+ "groupId" : null,
+ "fullPathCode" : null,
+ "fullPathName" : null,
+ "createTime" : null,
+ "oldCode" : null
+ } ]
\ No newline at end of file
diff --git a/app/service/hrbp/oa/common/notify.py b/app/service/hrbp/oa/common/notify.py
index 4127f5e..e7b47e6 100644
--- a/app/service/hrbp/oa/common/notify.py
+++ b/app/service/hrbp/oa/common/notify.py
@@ -102,20 +102,21 @@ def build_push_summary(results: list, subject: str = "") -> str:
rejected = [r for r in results if r.get("decision") == "校验不通过未处理"]
review = [r for r in results if r.get("decision") == "人工复核"]
overdue = [r for r in results if r.get("decision") == "超期"]
+ pending = [r for r in results if r.get("decision") == "未完成"]
abnormal = [r for r in results if r.get("decision") == "异常"]
failed = [r for r in results if r.get("decision") == "失败"]
- if not passed and not rejected and not review and not overdue and not abnormal:
+ if not passed and not rejected and not review and not overdue and not pending and not abnormal:
return ""
def _item(r):
- # 兼容请假(leave_info/假期类型)与加班(overtime_info/加班类型)
- info = r.get("leave_info") or r.get("overtime_info") or {}
- title = r.get("title", "") or info.get("请假人员") or info.get("加班人员") or "未知"
+ # 兼容请假(leave_info/假期类型)、加班(overtime_info/加班类型)与离职电子签(resign_info/员工姓名)
+ info = r.get("leave_info") or r.get("overtime_info") or r.get("resign_info") or {}
+ title = r.get("title", "") or info.get("请假人员") or info.get("加班人员") or info.get("员工姓名") or "未知"
vtype = info.get("假期类型") or info.get("加班类型") or ""
return f"{title}-{vtype}" if vtype else title
- all_pass = (not rejected and not review and not overdue and not abnormal and not failed)
+ all_pass = (not rejected and not review and not overdue and not pending and not abnormal and not failed)
lines = []
if all_pass:
@@ -148,6 +149,11 @@ def build_push_summary(results: list, subject: str = "") -> str:
for r in overdue:
lines.append(_item(r))
lines.append(f"处理原因:{r.get('note') or r.get('error') or '未知'}")
+ if pending:
+ lines.append(f"未完成待跟进 {len(pending)} 条,分别是:")
+ for r in pending:
+ lines.append(_item(r))
+ lines.append(f"原因:{r.get('note') or r.get('error') or '未知'}")
if abnormal:
lines.append(f"审批异常 {len(abnormal)} 条,分别是:")
for r in abnormal:
diff --git a/app/service/hrbp/oa/resign_e_sign/__init__.py b/app/service/hrbp/oa/resign_e_sign/__init__.py
new file mode 100644
index 0000000..e6cf9d6
--- /dev/null
+++ b/app/service/hrbp/oa/resign_e_sign/__init__.py
@@ -0,0 +1,9 @@
+# -*- coding: utf-8 -*-
+"""
+@Module: hrbp.oa.resign_e_sign
+@FileName: __init__.py
+@Author: 小布丁
+@CreateTime: 2026-08-20
+@Description: 离职电子签流程审核模块:解析 -> 校验(三态均已完成才同意)-> 报告
+@Version: 1.0.0
+"""
diff --git a/app/service/hrbp/oa/resign_e_sign/parser.py b/app/service/hrbp/oa/resign_e_sign/parser.py
new file mode 100644
index 0000000..9d73159
--- /dev/null
+++ b/app/service/hrbp/oa/resign_e_sign/parser.py
@@ -0,0 +1,106 @@
+# -*- coding: utf-8 -*-
+"""
+@Module: hrbp.oa.resign_e_sign.parser
+@FileName: parser.py
+@Author: 小布丁
+@CreateTime: 2026-08-20
+@Description: 离职电子签流程表单解析模块(解析 WorkformEngine 返回的 result,提取电子签三状态及员工信息)
+@Version: 1.0.0
+"""
+
+from typing import Any, Dict
+
+from app.utils.logger import get_logger
+
+logger = get_logger(__name__)
+
+
+# 是否已发起电子签字典(hr_staff_contract.is_initiate_sign)
+INITIATE_SIGN_MAP = {
+ "0": "未发起",
+ "1": "已发起",
+ "2": "已完成",
+ "3": "已撤销",
+ "5": "已过期",
+ "7": "已拒签",
+ "8": "已作废",
+}
+
+# 员工/企业签署状态字典(esign_sigin_state)
+SIGN_STATE_MAP = {
+ "1": "签署中",
+ "2": "已完成",
+ "3": "未完成",
+ "4": "已作废",
+}
+
+# 电子签三状态均须等于该编码(已完成)才同意
+SIGN_DONE_CODE = "2"
+
+
+def _sign_name(mapping: Dict[str, str], code: Any) -> str:
+ """将状态编码转换为名称;空值返回空串,未知编码原样返回。"""
+ if code is None or str(code).strip() == "":
+ return ""
+ return mapping.get(str(code).strip(), str(code))
+
+
+def parse_resign_e_sign_form(result: Dict[str, Any]) -> Dict[str, Any]:
+ """
+ 解析离职电子签表单数据,提取关键字段。
+
+ Args:
+ result: WorkformEngine 返回的 result 字典(即 doc['formData'])
+
+ Returns:
+ 包含离职电子签关键字段的字典(中文键名),三个电子签状态同时保留编码与名称
+ """
+ is_initiate = result.get("ext_is_initiate_sign")
+ staff_state = result.get("ext_staff_sign_status")
+ org_state = result.get("ext_org_sign_status")
+
+ return {
+ "员工姓名": result.get("staff_name"),
+ "工号": result.get("base_code"),
+ "身份证号": result.get("idcard"),
+ "所属事业部": result.get("belong_unit_org_name"),
+ "组织架构": result.get("org_full_path"),
+ "岗位": result.get("post_name"),
+ "离职日期": result.get("leaveoffice_time"),
+ "手机号": result.get("mobile_phone"),
+ "合同类型": result.get("contract_type"),
+ "合同开始日期": result.get("contract_start_date"),
+ "合同结束日期": result.get("contract_end_date"),
+ "是否已发起电子签编码": is_initiate,
+ "是否已发起电子签": _sign_name(INITIATE_SIGN_MAP, is_initiate),
+ "员工签署状态编码": staff_state,
+ "员工签署状态": _sign_name(SIGN_STATE_MAP, staff_state),
+ "企业签署状态编码": org_state,
+ "企业签署状态": _sign_name(SIGN_STATE_MAP, org_state),
+ }
+
+
+# ---------- 使用示例(测试用) ----------
+if __name__ == "__main__":
+ from app.utils.logger import setup_logging
+ setup_logging()
+
+ # 示例 result(WorkformEngine 返回的 result 字段,见 aa.md)
+ sample_result = {
+ "base_code": "37022119",
+ "belong_unit_org_name": "金色印象事业部",
+ "ext_is_initiate_sign": "2",
+ "ext_org_sign_status": "2",
+ "ext_staff_sign_status": "2",
+ "idcard": "511623200311056533",
+ "leaveoffice_time": "2026-07-31",
+ "mobile_phone": "19950986716",
+ "org_full_path": "集团-金色印象事业部-第一大区-金色印象重庆第一经营中心-第四片区-石油路PLUS会馆-接待组",
+ "post_name": "接待员",
+ "staff_name": "夏礼广",
+ }
+
+ parsed = parse_resign_e_sign_form(sample_result)
+ logger.info("===== 离职电子签信息解析结果 =====")
+ for key, value in parsed.items():
+ logger.info("%s: %s", key, value)
diff --git a/app/service/hrbp/oa/resign_e_sign/reporter.py b/app/service/hrbp/oa/resign_e_sign/reporter.py
new file mode 100644
index 0000000..06591f9
--- /dev/null
+++ b/app/service/hrbp/oa/resign_e_sign/reporter.py
@@ -0,0 +1,127 @@
+# -*- coding: utf-8 -*-
+"""
+@Module: hrbp.oa.resign_e_sign.reporter
+@FileName: reporter.py
+@Author: 小布丁
+@CreateTime: 2026-08-20
+@Description: 离职电子签流程报告模块。
+ 校验结果分两组:通过(已同意)/ 未完成(不管,待后续流转)。
+ 输出清单:
+ 《离职电子签未完成待跟进清单》:员工姓名、电子签三状态、详情页链接
+ 通过名单的简短汇总由 common.notify.build_push_summary 生成并推送钉钉。
+@Version: 1.0.0
+"""
+
+from typing import Any, Dict, List
+
+
+def _name(r: Dict[str, Any]) -> str:
+ """员工姓名:优先取表单里的员工姓名,缺失时回退到发起人。"""
+ info = r.get("resign_info", {}) or {}
+ return info.get("员工姓名") or r.get("creator") or "未知"
+
+
+def _format_detail(info: Dict[str, Any]) -> str:
+ """将 resign_info 字典格式化为易读的明细行。"""
+ fields = [
+ ("员工姓名", "员工姓名"),
+ ("工号", "工号"),
+ ("所属事业部", "所属事业部"),
+ ("组织架构", "组织架构"),
+ ("岗位", "岗位"),
+ ("离职日期", "离职日期"),
+ ("合同类型", "合同类型"),
+ ("合同开始日期", "合同开始日期"),
+ ("合同结束日期", "合同结束日期"),
+ ("是否已发起电子签", "是否已发起电子签"),
+ ("员工签署状态", "员工签署状态"),
+ ("企业签署状态", "企业签署状态"),
+ ]
+ parts = []
+ for key, label in fields:
+ val = info.get(key)
+ if val is not None and val != "" and val != "无":
+ parts.append(f"{label}={val}")
+ return " | ".join(parts)
+
+
+def generate_report(results: List[Dict[str, Any]]) -> str:
+ """
+ 生成离职电子签审批报告:汇总行 + 每条明细 + 未完成待跟进清单(+处理失败/异常)。
+
+ Args:
+ results: validate_doc 返回的校验结果列表,decision ∈ {通过/未完成/失败/异常}
+
+ Returns:
+ 报告文本
+ """
+ passed = [r for r in results if r.get("decision") == "通过"]
+ pending = [r for r in results if r.get("decision") == "未完成"]
+ abnormal = [r for r in results if r.get("decision") == "异常"]
+ failed = [r for r in results if r.get("decision") == "失败"]
+
+ summary = f"共 {len(results)} 单:通过 {len(passed)},未完成待跟进 {len(pending)}"
+ if abnormal:
+ summary += f",审批异常 {len(abnormal)}"
+ if failed:
+ summary += f",处理失败 {len(failed)}"
+
+ lines = [
+ "离职电子签审批报告",
+ "=" * 60,
+ summary,
+ "",
+ ]
+
+ # ----- 明细清单(所有审批单的完整数据) -----
+ lines.append("【审批明细】")
+ for i, r in enumerate(results, 1):
+ info = r.get("resign_info", {}) or {}
+ decision = r.get("decision", "未知")
+ note = r.get("note") or r.get("error") or ""
+ lines.append(f" #{i} {_name(r)}({info.get('工号', '')})-> {decision}")
+ detail = _format_detail(info)
+ if detail:
+ lines.append(f" {detail}")
+ if note:
+ lines.append(f" 备注: {note}")
+ if r.get("审批动作"):
+ lines.append(f" 审批动作: {r['审批动作']}({r.get('审批结果', '')})")
+ lines.append("")
+
+ # ----- 未完成(不管)待跟进清单 -----
+ if pending:
+ lines.append("《离职电子签未完成待跟进清单》")
+ lines.append("(电子签未全部完成,机器不处理,待后续流转/人工跟进)")
+ for i, r in enumerate(pending, 1):
+ info = r.get("resign_info", {}) or {}
+ note = r.get("note") or ""
+ url = r.get("detail_url") or "无"
+ lines.append(
+ f"{i}. 员工姓名: {_name(r)} | "
+ f"发起: {info.get('是否已发起电子签', '未知')} | "
+ f"员工: {info.get('员工签署状态', '未知')} | "
+ f"企业: {info.get('企业签署状态', '未知')} | "
+ f"原因: {note} | 详情页链接: {url}"
+ )
+ lines.append("")
+
+ # ----- 处理失败 -----
+ if failed:
+ lines.append("【处理失败】")
+ for i, r in enumerate(failed, 1):
+ lines.append(f"{i}. {_name(r)} | {r.get('title', '')} | 错误: {r.get('error', '')}")
+ lines.append("")
+
+ # ----- 审批异常(审批提交失败,需人工跟进) -----
+ if abnormal:
+ lines.append("《离职电子签审批异常待人工确认清单》")
+ lines.append("(机器已出结论但审批提交未成功,OA 中状态未变,待人工跟进处理)")
+ for i, r in enumerate(abnormal, 1):
+ reason = r.get("note") or r.get("error") or ""
+ url = r.get("detail_url") or "无"
+ action = r.get("审批动作") or "-"
+ lines.append(f"{i}. 员工姓名: {_name(r)} | 审批动作: {action} | 原因: {reason} | 详情页链接: {url}")
+ lines.append("")
+
+ return "\n".join(lines)
diff --git a/app/service/hrbp/oa/resign_e_sign/resign_e_sign_approval.py b/app/service/hrbp/oa/resign_e_sign/resign_e_sign_approval.py
new file mode 100644
index 0000000..7450e1a
--- /dev/null
+++ b/app/service/hrbp/oa/resign_e_sign/resign_e_sign_approval.py
@@ -0,0 +1,22 @@
+# -*- coding: utf-8 -*-
+"""
+@Module: hrbp.oa.resign_e_sign.resign_e_sign_approval
+@FileName: resign_e_sign_approval.py
+@Author: 小布丁
+@CreateTime: 2026-08-20
+@Description: 离职电子签流程审核入口(审批引擎见 common/approval_flow.py,校验规则见 validator.py,报告见 reporter.py)
+@Version: 1.0.0
+"""
+
+from app.service.hrbp.oa.common.approval_flow import run_flow
+from app.service.hrbp.oa.resign_e_sign.validator import validate_doc
+from app.service.hrbp.oa.resign_e_sign.reporter import generate_report
+
+
+def main() -> None:
+ """离职电子签流程审核:登录 -> 查待办 -> 解析SSO -> 获取表单 -> 校验 -> 报告"""
+ run_flow(subject="离职电子签流程", validate_doc=validate_doc, generate_report=generate_report)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/app/service/hrbp/oa/resign_e_sign/validator.py b/app/service/hrbp/oa/resign_e_sign/validator.py
new file mode 100644
index 0000000..5bc6220
--- /dev/null
+++ b/app/service/hrbp/oa/resign_e_sign/validator.py
@@ -0,0 +1,87 @@
+# -*- coding: utf-8 -*-
+"""
+@Module: hrbp.oa.resign_e_sign.validator
+@FileName: validator.py
+@Author: 小布丁
+@CreateTime: 2026-08-20
+@Description: 离职电子签流程校验模块(审批决策两态:通过 / 未完成)。
+ 规则(见 aa.md):进入详情取三个电子签状态字段,三者均为"已完成"才同意,
+ 否则不处理("不管"),留给后续待办继续流转。
+ - 是否已发起电子签 ext_is_initiate_sign(hr_staff_contract.is_initiate_sign)
+ - 员工签署状态 ext_staff_sign_status(esign_sigin_state)
+ - 企业签署状态 ext_org_sign_status(esign_sigin_state)
+@Version: 1.0.0
+"""
+
+from typing import Any, Dict
+
+from app.utils.logger import get_logger
+from app.service.hrbp.oa.resign_e_sign.parser import (
+ parse_resign_e_sign_form,
+ SIGN_DONE_CODE,
+)
+
+logger = get_logger(__name__)
+
+
+def _is_done(value: Any) -> bool:
+ """判断电子签状态编码是否为已完成(编码为字符串 "2")。"""
+ return value is not None and str(value).strip() == SIGN_DONE_CODE
+
+
+def validate_doc(doc: Dict[str, Any], session: Any) -> Dict[str, Any]:
+ """
+ 校验单张离职电子签单据,返回审批决策。
+
+ 流程:
+ 1. 解析表单数据,提取电子签三状态与员工信息
+ 2. 三者均已完成 -> 通过(同意);否则 -> 未完成(不管)
+
+ Args:
+ doc: 单据信息,含基本信息(title/creator/time/detail_url)
+ 和审批引擎已获取的 taskId/businessKey/formId/formData(表单详情)
+ session: 已登录的 SessionPage 对象(本流程无需额外接口,保留参数以适配公共引擎签名)
+
+ Returns:
+ 校验结果,包含审批决策及详细信息
+ """
+ form_data = doc.get("formData", {}) or {}
+ resign_info = parse_resign_e_sign_form(form_data)
+
+ is_initiate = form_data.get("ext_is_initiate_sign")
+ staff_state = form_data.get("ext_staff_sign_status")
+ org_state = form_data.get("ext_org_sign_status")
+
+ result: Dict[str, Any] = {
+ "title": doc.get("title", ""),
+ "creator": doc.get("creator", ""),
+ "time": doc.get("time", ""),
+ "detail_url": doc.get("detail_url", ""),
+ "decision": "未完成",
+ "note": "",
+ "resign_info": resign_info,
+ }
+
+ def _label(value: Any, mapping_name: str) -> str:
+ """取状态名称,缺失时回退为原始值/未知,便于人工判断。"""
+ return resign_info.get(mapping_name) or (str(value).strip() if value is not None else "未知")
+
+ if all(_is_done(v) for v in (is_initiate, staff_state, org_state)):
+ result["decision"] = "通过"
+ result["note"] = (
+ "审批通过(是否已发起电子签/员工签署状态/企业签署状态均为已完成)"
+ )
+ else:
+ result["decision"] = "未完成"
+ result["note"] = (
+ f"电子签未全部完成,暂不处理(是否已发起电子签: {_label(is_initiate, '是否已发起电子签')},"
+ f"员工签署状态: {_label(staff_state, '员工签署状态')},"
+ f"企业签署状态: {_label(org_state, '企业签署状态')})"
+ )
+ logger.info(
+ "未完成单据[%s] %s: 发起=%s, 员工=%s, 企业=%s",
+ doc.get("title", ""), resign_info.get("员工姓名", ""),
+ is_initiate, staff_state, org_state,
+ )
+
+ return result
diff --git a/yingdao/oa/resign_e_sign_approval.py b/yingdao/oa/resign_e_sign_approval.py
new file mode 100644
index 0000000..26321c2
--- /dev/null
+++ b/yingdao/oa/resign_e_sign_approval.py
@@ -0,0 +1,1048 @@
+# -*- coding: utf-8 -*-
+"""
+@FileName: resign_e_sign_approval.py
+@Author: 小布丁
+@CreateTime: 2026-08-20
+@Description: 离职电子签流程审核(影刀单文件版)- 业务逻辑与 App 版
+ app/service/hrbp/oa/resign_e_sign/ 完全一致
+@Version: 1.0.0
+
+依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
+ pip install DrissionPage python-dotenv
+
+登录(共享登录态,本脚本为单文件自包含):
+ - 登录态统一由「37duOA登录」影刀自定义指令写入共享 cookies:
+ %LOCALAPPDATA%\37duAutomation\.sessions\oa_cookies.json
+ - 本脚本仅读取该 cookies 文件,不 import 任何共享模块;缺失/失效时
+ 报错提示先运行登录指令(影刀流程开头请先拖入「37duOA登录」指令)。
+
+审批规则(见 aa.md):
+ - 进入详情取三个电子签状态字段,三者均为"已完成"才同意:
+ 是否已发起电子签 ext_is_initiate_sign(hr_staff_contract.is_initiate_sign,已完成=2)
+ 员工签署状态 ext_staff_sign_status(esign_sigin_state,已完成=2)
+ 企业签署状态 ext_org_sign_status(esign_sigin_state,已完成=2)
+ - 三者均已完成 -> 同意;否则不处理("不管",留给待办继续流转)。
+
+推送消息(本脚本不发送任何消息,只负责生成文本):
+ - 本脚本不内联任何消息推送逻辑;仅生成待推送的文本消息,经 main() 写入影刀全局变量
+ messages(列表,每项一条消息,按结果类型分组:通过/未完成/失败 各一条),
+ 由「37du钉钉群机器人推送」指令读取后逐条发送;本地独立运行时静默跳过写全局变量;
+ - main(push_type, target):
+ push_type="group"(默认)群消息:全局变量 messages 为文本列表,逐条交钉钉群机器人 webhook 推送;
+ push_type="person" 单聊:main 返回值仍为 {target, text} 列表,可交给「37du钉钉推送」指令走 OCR 单聊。
+"""
+
+# ==================== 标准库导入 ====================
+import functools
+import json
+import os
+import random
+import re
+import time
+from typing import Callable
+from urllib.parse import urlencode, urlparse, parse_qs
+
+# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
+# 任一依赖缺失会立即报错退出,避免运行到中途才发现缺库
+try:
+ from DrissionPage import ChromiumPage, SessionPage
+ from dotenv import load_dotenv
+except ImportError as _import_err:
+ raise RuntimeError(
+ "缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
+ "请先执行安装:\n"
+ " pip install DrissionPage python-dotenv\n"
+ f"缺失依赖详情: {_import_err}"
+ )
+
+# ==================== 路径 & 常量配置 ====================
+# 数据目录固定放在 AppData\Local\37duAutomation,不依赖脚本位置,每台电脑都有;
+# 登录态与共享 .env 统一由「37duOA登录」影刀自定义指令写入(见 yingdao/share/oa_login.py)
+_APP_DATA_DIR = os.path.join(os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'), '37duAutomation')
+_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
+COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
+SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
+
+# ---------- OA 系统 ----------
+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"
+
+# ---------- 分页 ----------
+# 待办接口分页参数名正确应为 pageno/rowsize/pagingtype(fetch_todo_page 已修正);
+# 每页调大至 100 作为兜底:即便个别场景分页仍异常,一次请求也能尽量拉全,避免丢单
+DEFAULT_PAGE_SIZE = 100
+
+
+# ==================== 日志(影刀环境用 print 替代 logging) ====================
+class _PrintLogger:
+ """简易日志器,用 print 输出,兼容原有 logger.xxx(msg, *args) 调用。"""
+ def debug(self, msg, *args, **kwargs):
+ print(msg % args if args else msg)
+
+ def info(self, msg, *args, **kwargs):
+ print(msg % args if args else msg)
+
+ def warning(self, msg, *args, **kwargs):
+ print(msg % args if args else msg)
+
+ def error(self, msg, *args, **kwargs):
+ print(msg % args if args else msg)
+
+
+logger = _PrintLogger()
+
+
+def _set_glv(name, value):
+ """写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
+ try:
+ glv[name] = value
+ except Exception:
+ pass
+
+
+# ==================== 重试装饰器 ====================
+class RetryExhaustedError(Exception):
+ pass
+
+
+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")
+
+ def decorator(func: Callable) -> Callable:
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ last_exc = None
+ base_delay = 1.0
+ backoff = 2.0
+
+ 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:
+ logger.error("%s 连续 %d 次尝试失败,放弃并记录: %s", func.__name__, max_attempts, e)
+ break
+ delay = base_delay * (backoff ** (attempt - 1))
+ delay *= random.uniform(0.5, 1.5)
+ logger.warning("%s 第 %d 次执行失败: %s,%.2f 秒后重试", func.__name__, attempt, e, delay)
+ time.sleep(delay)
+
+ raise RetryExhaustedError(
+ f"{func.__name__} failed after {max_attempts} attempts, last error: {last_exc}"
+ ) from last_exc
+ return wrapper
+ return decorator
+
+
+# ==================== OA/HR API 接口 ====================
+def fetch_todo_page(session, subject, page_no=1, page_size=DEFAULT_PAGE_SIZE):
+ params = {
+ "method": "list",
+ "dataType": "todo",
+ "fdType": FD_TYPE,
+ "fdCateId": "",
+ # 防缓存随机数:前端请求带 q.s_raq=<随机小数>,每次刷新
+ "q.s_raq": str(random.random()),
+ "q.fdSubject": subject,
+ # 分页参数必须用 pageno/rowsize/pagingtype:
+ # 用 page.pageNo/page.pageSize 会被服务端忽略,翻页返回重复数据
+ "pageno": page_no,
+ "rowsize": page_size,
+ "pagingtype": "default",
+ "orderby": "fdCreateTime",
+ "ordertype": "down",
+ }
+ url = f"{TODO_LIST_URL}?{urlencode(params)}"
+ logger.debug("请求第 %d 页: %s", page_no, url)
+
+ session.get(url)
+ resp = session.response
+ if not resp:
+ raise RuntimeError("请求失败,未获取到响应")
+ if resp.status_code != 200:
+ raise RuntimeError(f"接口请求失败,状态码: {resp.status_code}")
+ 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 数据,请检查参数或登录状态")
+
+
+def parse_todo_list(data):
+ datas = data.get("datas", [])
+ if not datas:
+ return []
+
+ docs = []
+ for row in datas:
+ title_cell = next((c for c in row if c["col"] == "todo.subject4View"), {})
+ title_raw = title_cell.get("value", "")
+ match = re.search(r']*>(.*?)', title_raw, re.DOTALL)
+ title = match.group(1).strip() if match else re.sub(r'<[^>]+>', '', title_raw).strip()
+
+ creator_cell = next((c for c in row if c["col"] == "docCreatorName"), {})
+ creator = creator_cell.get("value", "")
+
+ time_cell = next((c for c in row if c["col"] == "fdCreateTime"), {})
+ time_str = time_cell.get("value", "")
+
+ href_cell = next((c for c in row if c["col"] == "tr_href"), {})
+ detail_url = href_cell.get("value", "")
+ if detail_url and not detail_url.startswith(("http://", "https://")):
+ detail_url = BASE_URL + detail_url
+
+ # 跳过"工作沟通/协作"类待办(如"请回复…与您的工作沟通:离职电子签流程"):
+ # 链接指向协作模块 kmCollaborateMain.do,非审批工作流,SSO 后仅到
+ # unifyWorkFlow.jsp?fkId=… 拿不到 businessKey,永远无法解析,直接跳过避免无谓重试
+ if "kmCollaborateMain.do" in detail_url:
+ logger.warning("跳过非审批待办(工作沟通/协作): %s", title)
+ continue
+
+ docs.append({"title": title, "creator": creator, "time": time_str, "detail_url": detail_url})
+ return docs
+
+
+def get_documents(session, subject, page_size=DEFAULT_PAGE_SIZE):
+ all_docs = []
+ data = fetch_todo_page(session, subject, page_no=1, page_size=page_size)
+ total = int(data.get("page", {}).get("totalSize", 0))
+ logger.info("总待办[%s]条数: %d", subject, total)
+
+ docs = parse_todo_list(data)
+ all_docs.extend(docs)
+ logger.info("第 1 页获取 %d 条", len(docs))
+
+ if total > page_size:
+ total_pages = (total + page_size - 1) // page_size
+ for p in range(2, total_pages + 1):
+ data = fetch_todo_page(session, subject, page_no=p, page_size=page_size)
+ docs = parse_todo_list(data)
+ all_docs.extend(docs)
+ logger.info("第 %d 页获取 %d 条,累计 %d 条", p, len(docs), len(all_docs))
+
+ # 去重:OA 待办接口分页可能返回重复单据(同一条在多次/多页重复出现),
+ # 以详情链接 detail_url(含唯一 taskId)为键去重,避免同一单重复审批、重复推送
+ seen = set()
+ unique_docs = []
+ for doc in all_docs:
+ key = doc.get("detail_url") or doc.get("title")
+ if key in seen:
+ continue
+ seen.add(key)
+ unique_docs.append(doc)
+
+ if len(unique_docs) != len(all_docs):
+ logger.warning("去重前 %d 条,去重后 %d 条(已过滤 %d 条重复单据)",
+ len(all_docs), len(unique_docs), len(all_docs) - len(unique_docs))
+ return unique_docs
+
+
+def get_wf_activity_by_task_id(session, task_id):
+ url = f"{WF_ACTIVITY_URL}?method=getWfActivityByTaskId"
+ data = {"taskId": task_id}
+ logger.info("获取 formId: taskId=%s", task_id)
+
+ session.post(url, data=data)
+ resp = session.response
+ if not resp:
+ raise RuntimeError("WfActivity 请求失败,未获取到响应")
+ if resp.status_code != 200:
+ raise RuntimeError(f"WfActivity 接口状态码异常: {resp.status_code}")
+
+ try:
+ json_data = resp.json()
+ except Exception:
+ body = (resp.text or "")[:200]
+ raise RuntimeError(f"WfActivity 接口返回非 JSON 数据(状态码 {resp.status_code}): {body}")
+
+ logger.debug("WfActivity 返回: %s", json_data)
+ return json_data
+
+
+def extract_form_id(wf_activity_data):
+ 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, business_key, form_id):
+ url = f"{WORKFORM_ENGINE_URL}?method=getBusinessDate"
+ data = {"businessKey": business_key, "formId": form_id}
+ logger.info("获取离职电子签表单: businessKey=%s, formId=%s", business_key, form_id)
+
+ session.post(url, data=data)
+ resp = session.response
+ if not resp:
+ raise RuntimeError("WorkformEngine 请求失败,未获取到响应")
+ if resp.status_code != 200:
+ raise RuntimeError(f"WorkformEngine 接口状态码异常: {resp.status_code}")
+
+ try:
+ json_data = resp.json()
+ except Exception:
+ body = (resp.text or "")[:200]
+ raise RuntimeError(f"WorkformEngine 接口返回非 JSON 数据(状态码 {resp.status_code}): {body}")
+
+ 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
+
+
+# ==================== 离职电子签表单解析 ====================
+# 是否已发起电子签字典(hr_staff_contract.is_initiate_sign)
+INITIATE_SIGN_MAP = {
+ "0": "未发起",
+ "1": "已发起",
+ "2": "已完成",
+ "3": "已撤销",
+ "5": "已过期",
+ "7": "已拒签",
+ "8": "已作废",
+}
+
+# 员工/企业签署状态字典(esign_sigin_state)
+SIGN_STATE_MAP = {
+ "1": "签署中",
+ "2": "已完成",
+ "3": "未完成",
+ "4": "已作废",
+}
+
+# 电子签三状态均须等于该编码(已完成)才同意
+SIGN_DONE_CODE = "2"
+
+
+def _sign_name(mapping, code):
+ """将状态编码转换为名称;空值返回空串,未知编码原样返回。"""
+ if code is None or str(code).strip() == "":
+ return ""
+ return mapping.get(str(code).strip(), str(code))
+
+
+def parse_resign_e_sign_form(result):
+ is_initiate = result.get("ext_is_initiate_sign")
+ staff_state = result.get("ext_staff_sign_status")
+ org_state = result.get("ext_org_sign_status")
+
+ return {
+ "员工姓名": result.get("staff_name"),
+ "工号": result.get("base_code"),
+ "身份证号": result.get("idcard"),
+ "所属事业部": result.get("belong_unit_org_name"),
+ "组织架构": result.get("org_full_path"),
+ "岗位": result.get("post_name"),
+ "离职日期": result.get("leaveoffice_time"),
+ "手机号": result.get("mobile_phone"),
+ "合同类型": result.get("contract_type"),
+ "合同开始日期": result.get("contract_start_date"),
+ "合同结束日期": result.get("contract_end_date"),
+ "是否已发起电子签编码": is_initiate,
+ "是否已发起电子签": _sign_name(INITIATE_SIGN_MAP, is_initiate),
+ "员工签署状态编码": staff_state,
+ "员工签署状态": _sign_name(SIGN_STATE_MAP, staff_state),
+ "企业签署状态编码": org_state,
+ "企业签署状态": _sign_name(SIGN_STATE_MAP, org_state),
+ }
+
+
+# ==================== 登录态(共享 cookies 文件) ====================
+# 登录态统一由「37duOA登录」影刀自定义指令维护(见 yingdao/share/oa_login.py),
+# 本脚本为单文件自包含:仅读取共享 cookies 文件,不 import 任何共享模块。
+# cookies 缺失/失效时提示先运行登录指令,不再内联调用共享登录模块。
+
+
+def _load_shared_oa_cookies():
+ """读取共享 OA 登录 cookies(由「37duOA登录」影刀自定义指令写入)。"""
+ if not os.path.exists(COOKIE_FILE):
+ return None
+ with open(COOKIE_FILE, encoding='utf-8') as f:
+ cookies = json.load(f)
+ return cookies or None
+
+
+def _ensure_oa_cookies(force=False):
+ """确保存在有效的 OA 登录态文件(由「37duOA登录」指令写入)。
+
+ 本脚本为单文件自包含、不 import 共享登录模块,因此不做自动重登;
+ 登录态缺失或失效时抛友好的 SystemExit 提示(无堆栈),直接提醒先运行登录流程。
+ """
+ if not force and _load_shared_oa_cookies():
+ return True
+ if not os.path.exists(COOKIE_FILE):
+ raise SystemExit(
+ "未找到 OA 登录态文件(oa_cookies.json)。\n"
+ "请先在影刀流程开头拖入「37duOA登录」指令完成登录,"
+ "或本地运行: python yingdao/share/oa_login.py\n"
+ "登录完成后再运行本流程。")
+ raise SystemExit(
+ "OA 登录态已失效(oa_cookies.json 已过期)。\n"
+ "请先重新运行「37duOA登录」指令完成登录,"
+ "或本地运行: python yingdao/share/oa_login.py\n"
+ "重新登录后再运行本流程。")
+
+
+def is_session_valid(session, subject="离职电子签流程"):
+ """调轻量接口 sumTodoCount 判断 OA 会话是否有效(无需拉待办)。"""
+ try:
+ 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
+
+
+def refresh_session_cookies(session, browser_page):
+ cookies = browser_page.cookies(all_domains=True)
+ if cookies:
+ session.set.cookies(cookies)
+ logger.info("已同步 %d 个 Cookies 到 SessionPage(含 SSO 会话)", len(cookies))
+ else:
+ logger.warning("未获取到 Cookies,请确认浏览器登录态")
+
+
+def build_session(subject):
+ """仅构建 SessionPage(不启动浏览器),从共享 cookies 填充登录态。
+
+ 用于查待办、拉表单等纯接口操作;登录态失效时抛友好提示(SystemExit,无堆栈),
+ 提醒先运行「37duOA登录」指令重新登录,而不是中途崩溃。
+ """
+ _ensure_oa_cookies()
+ session = SessionPage()
+ session.set.timeout(10)
+ cookies = _load_shared_oa_cookies()
+ if cookies:
+ session.set.cookies(cookies)
+ if is_session_valid(session, subject):
+ return session
+ # 登录态已失效:单文件自包含、不做自动重登,直接友好提示先运行登录流程
+ _ensure_oa_cookies(force=True) # 恒抛 SystemExit 友好提示
+
+
+def build_browser(subject):
+ """有单据时才启动浏览器(SSO 跳转解析 / 真实审批点击 / 结果弹窗用),并填充共享 cookies。"""
+ _ensure_oa_cookies()
+ browser = ChromiumPage()
+ cookies = _load_shared_oa_cookies()
+ if cookies:
+ browser.set.cookies(cookies)
+ return browser
+
+
+# ==================== 登录(共享) ====================
+# 登录态统一由「37duOA登录」影刀自定义指令维护(见 yingdao/share/oa_login.py),
+# 本脚本通过 build_session()/build_browser() 复用共享 cookies,不再内联账号密码登录代码;
+# 无待办单据时不启动浏览器(build_session 纯接口即可),仅在确有单据时才开浏览器。
+
+
+# ==================== SSO 解析 ====================
+def resolve_sso_params(browser, sso_url, wait_timeout=20):
+ logger.info("解析 SSO 重定向: %s", sso_url)
+
+ browser.get(sso_url)
+ browser.wait.url_change(sso_url, exclude=True, timeout=wait_timeout, raise_err=False)
+ logger.info("重定向最终 URL: %s", browser.url)
+
+ params = parse_qs(urlparse(browser.url).query)
+ task_id = params.get("taskId", [None])[0] or params.get("fkId", [None])[0]
+ business_key = params.get("businessKey", [None])[0]
+
+ if not task_id or not business_key:
+ raise RuntimeError(f"无法从重定向 URL 提取 taskId 或 businessKey: {browser.url}")
+
+ logger.info("SSO 解析成功: taskId=%s, businessKey=%s", task_id, business_key)
+ return {"taskId": task_id, "businessKey": business_key}
+
+
+# ==================== 审批引擎 ====================
+@retry(max_attempts=3, no_retry_on=(OALoginExpiredError,))
+def _fetch_documents(session, subject):
+ return get_documents(session, subject=subject)
+
+
+@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:
+ raise RuntimeError(f"单据无详情链接: {doc.get('title')}")
+
+ sso_params = resolve_sso_params(browser, detail_url)
+ task_id = sso_params["taskId"]
+ business_key = sso_params["businessKey"]
+ logger.info("SSO 解析完成: taskId=%s, businessKey=%s", task_id, business_key)
+
+ refresh_session_cookies(session, browser)
+
+ wf_activity_data = get_wf_activity_by_task_id(session, task_id)
+ form_id = extract_form_id(wf_activity_data)
+
+ form_data = get_business_data(session, business_key, form_id)
+
+ return {**doc, "taskId": task_id, "businessKey": business_key, "formId": form_id, "formData": form_data}
+
+
+def show_rpa_result_popup(page: ChromiumPage,
+ type_: str = "success",
+ stay_seconds: float = 2.5):
+ """
+ 纯图标弹窗(无背景卡片),图标放大居中
+ :param page: DrissionPage 页面对象
+ :param type_: success / error
+ :param stay_seconds: 显示秒数(阻塞等待,保证弹窗完整展示后再继续)
+ """
+ # ========== 把两个 SVG 代码粘贴到下面的变量里 ==========
+ svg_success = '''''' # 审批通过 / 成功图标
+ svg_error = '''''' # 审批校验不通过未处理 / 失败图标
+ # ==================================================
+
+ svg_icon = svg_success if type_ == "success" else svg_error
+ accent_color = "#13C463" if type_ == "success" else "#F5222D"
+
+ js_script = f'''
+ (function() {{
+ const old = document.getElementById("rpa_apple_pop");
+ if (old) old.remove();
+
+ const mask = document.createElement('div');
+ mask.id = "rpa_apple_pop";
+ mask.style.cssText = `
+ position: fixed; inset: 0;
+ z-index: 999999;
+ display: flex; align-items: center; justify-content: center;
+ opacity: 0;
+ transition: opacity 0.25s ease;
+ `;
+
+ // 放大图标容器,无背景
+ const iconWrap = document.createElement('div');
+ iconWrap.style.cssText = `
+ position: relative;
+ width: 180px; height: 180px;
+ display: flex; align-items: center; justify-content: center;
+ transform: scale(0);
+ transition: transform 0.6s cubic-bezier(0.17, 0.89, 0.32, 1.27);
+ `;
+
+ iconWrap.innerHTML = `{svg_icon}`;
+ const svg = iconWrap.querySelector('svg');
+ if (svg) {{
+ svg.style.width = '100%';
+ svg.style.height = '100%';
+ }}
+
+ mask.appendChild(iconWrap);
+ document.body.appendChild(mask);
+
+ // 直接应用样式(不依赖 requestAnimationFrame,后台/未激活标签页也能正常显示)
+ mask.style.opacity = '1';
+ iconWrap.style.transform = 'scale(1)';
+
+ setTimeout(() => {{
+ mask.style.opacity = '0';
+ iconWrap.style.transform = 'scale(0.8)';
+ setTimeout(() => mask.remove(), 300);
+ }}, {int(stay_seconds * 1000)});
+ }})();
+ '''
+
+ page.run_js(js_script)
+
+ # 阻塞等待弹窗展示完成:弹窗稍后会被下一步打开单据的页面跳转清除,
+ # 若不等待,弹窗会"一闪而过"看不清审批结果
+ time.sleep(stay_seconds)
+
+
+# ==================== 推送消息生成(不发送,交由推送指令) ====================
+# 本脚本不发送任何消息:仅把审批结果按类型拼成多条文本消息(默认群消息,只含 text;
+# 传 push_type="person" 时生成含 target 的单聊消息),经 main() 把列表写入影刀全局变量 messages。
+
+
+# ==================== 推送消息生成(不发送,交由推送指令) ====================
+# 本脚本不发送任何消息:仅把审批结果按类型拼成多条文本消息(默认群消息,只含 text;
+# 传 push_type="person" 时生成含 target 的单聊消息),经 main() 把列表写入影刀全局变量 messages。
+
+
+def _build_push_messages(texts, push_type="group", target=None):
+ """把文本列表转成推送消息列表(字典列表)。
+
+ push_type 推送类型:"group" 群消息(仅 text,钉钉群机器人 webhook 推送);
+ "person" 单聊(含 target,钉钉联系人 OCR 推送)。
+ """
+ messages = []
+ for text in texts:
+ msg = {"text": text}
+ if push_type == "person":
+ msg["target"] = target
+ messages.append(msg)
+ return messages
+
+
+def build_push_summary(results, subject=""):
+ """
+ 按结果类型生成多条推送消息文本(每条一类,含该类的单笔明细)。
+ 返回:字符串列表,每项是一条独立完整消息,供推送指令逐条发送
+ (通过 / 未完成 / 处理失败 各一条)。无业务结果时返回空列表。
+ """
+ if not results:
+ return []
+ passed = [r for r in results if r.get("decision") == "通过"]
+ pending = [r for r in results if r.get("decision") == "未完成"]
+ abnormal = [r for r in results if r.get("decision") == "异常"]
+ failed = [r for r in results if r.get("decision") == "失败"]
+ if not passed and not pending and not abnormal and not failed:
+ return []
+
+ def _detail(r):
+ info = r.get("resign_info", {}) or {}
+ name = info.get("员工姓名") or r.get("title") or "未知"
+ code = info.get("工号") or ""
+ head = f"{name}({code})" if code else name
+ return head
+
+ messages = []
+ if passed:
+ lines = [f"【{subject}审批】通过 {len(passed)} 条:"]
+ lines += [f" {_detail(r)}" for r in passed]
+ lines.append(f"以上 {len(passed)} 条{subject}申请已审批同意")
+ messages.append("\n".join(lines))
+ if pending:
+ lines = [f"【{subject}审批】未完成待跟进 {len(pending)} 条:"]
+ for r in pending:
+ lines.append(f" {_detail(r)}")
+ lines.append(f" 原因:{r.get('note') or r.get('error') or '未知'}")
+ lines.append(f" 详情页:{r.get('detail_url') or '无'}")
+ messages.append("\n".join(lines))
+ if abnormal:
+ lines = [f"【{subject}审批】审批异常 {len(abnormal)} 条(机器已出结论但审批提交未成功,OA 中状态未变,待人工跟进):"]
+ for r in abnormal:
+ lines.append(f" {_detail(r)}")
+ lines.append(f" 详情页:{r.get('detail_url') or '无'}")
+ messages.append("\n".join(lines))
+ if failed:
+ lines = [f"【{subject}审批】处理失败 {len(failed)} 条:"]
+ for r in failed:
+ lines.append(f" {r.get('title') or '未知'}:{r.get('error') or '未知'}")
+ messages.append("\n".join(lines))
+ return messages
+
+
+# ==================== 真实审批提交 ====================
+# 影刀环境无 .env 文件,开关直接写死在代码中;如需临时关闭自动审批改为 False
+APPROVE_ENABLED = False
+# 审批按钮:仅自动提交"同意"(校验通过);未完成一律不自动提交("不管"),保留待后续流转
+_APPROVE_BUTTONS = {
+ "通过": ("#chooseSubmit", "同意"),
+}
+
+
+def _find_button(page, selector, timeout=3.0):
+ """在详情页查找审批按钮:优先主文档,找不到则遍历 iframe(部分详情页按钮在 iframe 内)。"""
+ try:
+ btn = page.ele(selector, timeout=timeout)
+ if btn:
+ return btn
+ except Exception:
+ pass
+ try:
+ frames = page.get_frames()
+ except Exception:
+ frames = []
+ for frame in frames:
+ try:
+ btn = frame.ele(selector, timeout=1)
+ if btn:
+ return btn
+ except Exception:
+ continue
+ return None
+
+
+def submit_approval(page, decision):
+ """
+ 按校验结论在流程详情页执行真实审批提交。
+
+ Args:
+ page: 停留在详情页的 ChromiumPage
+ decision: 校验决策(通过;其余决策不提交)
+
+ Returns:
+ {"action": "同意"/"-", "ok": "true"/"false", "message": ...}
+ """
+ if decision not in _APPROVE_BUTTONS:
+ return {"action": "-", "ok": "true", "message": "无需提交"}
+ selector, label = _APPROVE_BUTTONS[decision]
+ try:
+ btn = _find_button(page, selector)
+ if btn is None:
+ msg = f"未找到审批按钮 {selector}({label}),可能页面未加载完成或按钮在未识别的 iframe 中"
+ logger.error(msg)
+ return {"action": label, "ok": "false", "message": msg}
+ logger.info("点击审批按钮: %s(%s)", selector, label)
+ btn.click()
+ # 确认按钮为唯一 id,主文档直接用 ele() 高频等待其动态出现,避免 _find_button 的 iframe 遍历开销
+ # 普通流程确认框 #custom-confirm-modal-ok 为主;选人弹窗 .wf-select-people 为特殊单据才触发
+ def _visible(el):
+ try:
+ return el.states.is_displayed
+ except Exception:
+ return False
+
+ confirm = None
+ for _ in range(20):
+ c1 = page.ele("#custom-confirm-modal-ok", timeout=0.2)
+ if c1 is not None and _visible(c1):
+ confirm = c1
+ break
+ # 选人弹窗(容器常驻但默认隐藏,仅弹出时才可见)兜底
+ people = page.ele(".wf-select-people", timeout=0.2)
+ if people is not None and _visible(people):
+ try:
+ c2 = people.ele("css:.modal-footer button.btn.btn-primary", timeout=0.2)
+ except Exception:
+ c2 = None
+ if c2 is not None and _visible(c2):
+ confirm = c2
+ break
+ time.sleep(0.2)
+ if confirm is None:
+ msg = "未找到确认框确定按钮(#custom-confirm-modal-ok 或 .modal-footer .btn.btn-primary),审批未提交"
+ logger.error(msg)
+ return {"action": label, "ok": "false", "message": msg}
+ confirm.click()
+ logger.info("已点击确认框确定按钮")
+ time.sleep(1.0)
+ return {"action": label, "ok": "true", "message": f"已执行审批提交[{label}]"}
+ except Exception as e:
+ logger.error("审批提交失败[%s]: %s", label, str(e))
+ return {"action": label, "ok": "false", "message": f"审批提交[{label}]失败: {e}"}
+
+
+def run_flow(subject, validate_doc, generate_report, push_type="group", target=None):
+ """离职电子签审批主流程;返回生成的推送消息列表(字典列表,本脚本不发送)。
+
+ push_type 推送类型:"group" 群消息(钉钉群机器人 webhook);"person" 单聊(钉钉联系人 OCR 推送)。
+ target 单聊推送目标(联系人),仅 push_type="person" 时使用。
+ """
+ logger.info("%s审批流程开始", subject)
+
+ # 登录态失效(待办/表单接口返回登录页)时本脚本不做自动重登(单文件自包含),
+ # 直接抛友好提示(SystemExit 无堆栈)提醒先运行「37duOA登录」指令
+ for login_attempt in range(2):
+ # 先用纯接口 SessionPage(不开浏览器)拉待办;无单据则全程不启动浏览器
+ session = build_session(subject)
+ browser = None
+ try:
+ docs = _fetch_documents(session, subject)
+ logger.info("共获取%s待办 %d 条", subject, len(docs))
+
+ # 无待办单据:不开浏览器,直接生成提示消息返回
+ if not docs:
+ logger.info("%s无待审批单据,跳过浏览器操作", subject)
+ push_messages = _build_push_messages([f"暂无待审批的{subject}单据"], push_type, target)
+ logger.info("%s审批流程结束,共处理 0 条(无单据)", subject)
+ return push_messages
+
+ # 有单据才启动浏览器:SSO 跳转解析 / 真实审批提交 / 结果弹窗
+ browser = build_browser(subject)
+ refresh_session_cookies(session, browser)
+
+ 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") == "通过":
+ orig_decision = result.get("decision")
+ submit = submit_approval(browser, orig_decision)
+ result["审批动作"] = submit["action"]
+ # 提交失败兜底:单据在 OA 中状态未变,不能仍标为通过,
+ # 归为「异常」并附机器结论,交由人工跟进
+ if submit["ok"] == "false":
+ result["decision"] = "异常"
+ result["note"] = (
+ f"机器结论[{orig_decision}]但审批提交失败:{submit['message']}"
+ )
+ result["审批结果"] = f"{submit['message']}"
+ logger.info("审批提交: %s %s", submit["action"], result["审批结果"])
+ 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),
+ })
+
+ report = generate_report(results)
+ print("\n" + report)
+
+ # 生成推送消息文本(本脚本不发送,交由流程/推送指令):
+ # 按结果类型分多条(通过/未完成/失败 各一条,含单笔明细)
+ texts = build_push_summary(results, subject)
+ # 无任何待办/结果时也生成一条提示消息,避免静默不推送
+ if not texts:
+ texts.append(f"暂无待审批的{subject}单据")
+ push_messages = _build_push_messages(texts, push_type, target)
+
+ logger.info("%s审批流程结束,共处理 %d 条", subject, len(results))
+ return push_messages
+ except OALoginExpiredError as e:
+ logger.warning("OA 登录态失效: %s", e)
+ # 本脚本为单文件自包含、不自动重登:直接抛友好提示(SystemExit 无堆栈),
+ # 提醒先运行「37duOA登录」指令重新登录后再跑本流程
+ _ensure_oa_cookies(force=True)
+ finally:
+ if browser is not None:
+ try:
+ browser.quit()
+ except Exception:
+ pass
+
+
+# ==================== 离职电子签校验规则 ====================
+def _is_done(value):
+ """判断电子签状态编码是否为已完成(编码为字符串 "2")。"""
+ return value is not None and str(value).strip() == SIGN_DONE_CODE
+
+
+def validate_doc(doc, session):
+ """
+ 校验单张离职电子签单据,返回审批决策(通过 / 未完成)。
+
+ 三者(是否已发起电子签/员工签署状态/企业签署状态)均已完成 -> 通过(同意);
+ 否则 -> 未完成(不管,留给待办继续流转)。
+ """
+ form_data = doc.get("formData", {}) or {}
+ resign_info = parse_resign_e_sign_form(form_data)
+
+ is_initiate = form_data.get("ext_is_initiate_sign")
+ staff_state = form_data.get("ext_staff_sign_status")
+ org_state = form_data.get("ext_org_sign_status")
+
+ result = {
+ "title": doc.get("title", ""),
+ "creator": doc.get("creator", ""),
+ "time": doc.get("time", ""),
+ "detail_url": doc.get("detail_url", ""),
+ "decision": "未完成",
+ "note": "",
+ "resign_info": resign_info,
+ }
+
+ def _label(value, mapping_name):
+ """取状态名称,缺失时回退为原始值/未知,便于人工判断。"""
+ return resign_info.get(mapping_name) or (str(value).strip() if value is not None else "未知")
+
+ if all(_is_done(v) for v in (is_initiate, staff_state, org_state)):
+ result["decision"] = "通过"
+ result["note"] = "审批通过(是否已发起电子签/员工签署状态/企业签署状态均为已完成)"
+ else:
+ result["decision"] = "未完成"
+ result["note"] = (
+ f"电子签未全部完成,暂不处理(是否已发起电子签: {_label(is_initiate, '是否已发起电子签')},"
+ f"员工签署状态: {_label(staff_state, '员工签署状态')},"
+ f"企业签署状态: {_label(org_state, '企业签署状态')})"
+ )
+ logger.info("未完成单据[%s] %s: 发起=%s, 员工=%s, 企业=%s",
+ doc.get("title", ""), resign_info.get("员工姓名", ""),
+ is_initiate, staff_state, org_state)
+
+ return result
+
+
+# ==================== 报告生成 ====================
+def _name(r):
+ """员工姓名:优先取表单里的员工姓名,缺失时回退到发起人。"""
+ info = r.get("resign_info", {}) or {}
+ return info.get("员工姓名") or r.get("creator") or "未知"
+
+
+def _format_detail(info):
+ """将 resign_info 字典格式化为易读的明细行。"""
+ fields = [
+ ("员工姓名", "员工姓名"),
+ ("工号", "工号"),
+ ("所属事业部", "所属事业部"),
+ ("组织架构", "组织架构"),
+ ("岗位", "岗位"),
+ ("离职日期", "离职日期"),
+ ("合同类型", "合同类型"),
+ ("合同开始日期", "合同开始日期"),
+ ("合同结束日期", "合同结束日期"),
+ ("是否已发起电子签", "是否已发起电子签"),
+ ("员工签署状态", "员工签署状态"),
+ ("企业签署状态", "企业签署状态"),
+ ]
+ parts = []
+ for key, label in fields:
+ val = info.get(key)
+ if val is not None and val != "" and val != "无":
+ parts.append(f"{label}={val}")
+ return " | ".join(parts)
+
+
+def generate_report(results):
+ """
+ 生成离职电子签审批报告:汇总行 + 每条明细 + 未完成待跟进清单(+处理失败/异常)。
+ """
+ passed = [r for r in results if r.get("decision") == "通过"]
+ pending = [r for r in results if r.get("decision") == "未完成"]
+ abnormal = [r for r in results if r.get("decision") == "异常"]
+ failed = [r for r in results if r.get("decision") == "失败"]
+
+ summary = f"共 {len(results)} 单:通过 {len(passed)},未完成待跟进 {len(pending)}"
+ if abnormal:
+ summary += f",审批异常 {len(abnormal)}"
+ if failed:
+ summary += f",处理失败 {len(failed)}"
+
+ lines = [
+ "离职电子签审批报告",
+ "=" * 60,
+ summary,
+ "",
+ ]
+
+ # ----- 明细清单(所有审批单的完整数据) -----
+ lines.append("【审批明细】")
+ for i, r in enumerate(results, 1):
+ info = r.get("resign_info", {}) or {}
+ decision = r.get("decision", "未知")
+ note = r.get("note") or r.get("error") or ""
+ lines.append(f" #{i} {_name(r)}({info.get('工号', '')})-> {decision}")
+ detail = _format_detail(info)
+ if detail:
+ lines.append(f" {detail}")
+ if note:
+ lines.append(f" 备注: {note}")
+ if r.get("审批动作"):
+ lines.append(f" 审批动作: {r['审批动作']}({r.get('审批结果', '')})")
+ lines.append("")
+
+ # ----- 未完成(不管)待跟进清单 -----
+ if pending:
+ lines.append("《离职电子签未完成待跟进清单》")
+ lines.append("(电子签未全部完成,机器不处理,待后续流转/人工跟进)")
+ for i, r in enumerate(pending, 1):
+ info = r.get("resign_info", {}) or {}
+ note = r.get("note") or ""
+ url = r.get("detail_url") or "无"
+ lines.append(
+ f"{i}. 员工姓名: {_name(r)} | "
+ f"发起: {info.get('是否已发起电子签', '未知')} | "
+ f"员工: {info.get('员工签署状态', '未知')} | "
+ f"企业: {info.get('企业签署状态', '未知')} | "
+ f"原因: {note} | 详情页链接: {url}"
+ )
+ lines.append("")
+
+ # ----- 处理失败 -----
+ if failed:
+ lines.append("【处理失败】")
+ for i, r in enumerate(failed, 1):
+ lines.append(f"{i}. {_name(r)} | {r.get('title', '')} | 错误: {r.get('error', '')}")
+ lines.append("")
+
+ # ----- 审批异常(审批提交失败,需人工跟进) -----
+ if abnormal:
+ lines.append("《离职电子签审批异常待人工确认清单》")
+ lines.append("(机器已出结论但审批提交未成功,OA 中状态未变,待人工跟进处理)")
+ for i, r in enumerate(abnormal, 1):
+ reason = r.get("note") or r.get("error") or ""
+ url = r.get("detail_url") or "无"
+ action = r.get("审批动作") or "-"
+ lines.append(f"{i}. 员工姓名: {_name(r)} | 审批动作: {action} | 原因: {reason} | 详情页链接: {url}")
+ lines.append("")
+
+ return "\n".join(lines)
+
+
+# ==================== 主入口 ====================
+def main(push_type="group", target=None):
+ """离职电子签流程审核:查待办 -> 解析SSO -> 获取表单 -> 校验 -> 报告 -> 生成推送消息。
+
+ 本脚本不发送任何消息:仅生成待推送消息(返回列表并写入影刀全局变量 messages),
+ 由「37du钉钉群机器人推送」/「37du钉钉推送」指令消费。
+
+ Args:
+ push_type: 推送类型 "group"(默认,群消息,全局变量 messages 为纯文本直接发送)
+ / "person"(单聊,返回列表含 target,交由 OCR 单聊推送指令)
+ target: 单聊推送目标(联系人),仅 push_type="person" 时使用
+ """
+ push_type = str(push_type or "group").lower()
+ if push_type == "person" and not target:
+ logger.warning("push_type=person 但未提供 target,已按群消息(group)处理")
+ push_type = "group"
+ push_messages = run_flow(
+ subject="离职电子签流程",
+ validate_doc=validate_doc,
+ generate_report=generate_report,
+ push_type=push_type,
+ target=target,
+ )
+ # 写入影刀全局变量 messages(列表,每项一条消息,按结果类型分组),
+ # 供「37du钉钉群机器人推送」指令读取后逐条发送;本地独立运行时静默跳过
+ _set_glv("messages", [
+ str(m.get("text", "") or "").strip()
+ for m in push_messages if str(m.get("text", "") or "").strip()
+ ])
+ return push_messages
+
+
+if __name__ == "__main__":
+ main()