diff --git a/aa.json b/aa.json index ff3612a..33f6656 100644 --- a/aa.json +++ b/aa.json @@ -1,278 +1,48 @@ { - "attributeMap" : { - "cellStyleConfig" : { }, - "hasBr" : false, - "theadList" : [ { - "id" : null, - "title" : "2026年07月考勤统计报表", - "field" : "cfbfb1aa3bcc4eb6bbbc6467a079dfe3", - "oriField" : null, - "isDynamicCol" : null, - "colDrillingVal" : null, - "fieldNameShow" : null, - "colGroup" : null, - "colOrderNum" : 0, - "fieldType" : null, - "numberFmt" : null, - "dictType" : null, - "dictCode" : "", - "dateFmt" : null, - "url" : null, - "target" : null, - "separator" : null, - "isMergeRow" : null, - "mergeUnions" : null, - "isFooting" : null, - "freeze" : null, - "fixed" : null, - "align" : "center", - "sortable" : false, - "minWidth" : "", - "width" : "", - "type" : "html", - "show" : true, - "needFooting" : null, - "needMerge" : null, - "otherConfig" : null, - "otherConfigMap" : null - } ] - }, - "count" : 1, - "datas" : [ { - "stru_id" : "02440002-d5f1-11ee-b449-000c296f9469", - "GLOBAL_ORDER" : "1101101102", - "base_code" : "37033852", - "org_full_path" : "集团-财务管理部-财务-投融发展组", - "belong_unit_org_name" : "财务管理部", - "dept_org_name" : "投融发展组", - "dept_one" : "财务", - "dept_four" : null, - "post_name" : "投融资经理", - "staff_name" : "崔延", - "staff_id" : "17206f42-b874-41eb-a1f6-3651f3d2a1fd", - "ext_technician_code" : "", - "v_1" : "正常", - "v_2" : "正常", - "v_3" : "正常", - "v_4" : "休息", - "v_5" : "休息", - "v_6" : "正常", - "v_7" : "正常", - "v_8" : "正常", - "v_9" : "正常", - "v_10" : "正常", - "v_11" : "正常", - "v_12" : "休息", - "v_13" : "正常", - "v_14" : "正常", - "v_15" : "正常", - "v_16" : "正常", - "v_17" : "正常", - "v_18" : "休息", - "v_19" : "休息", - "v_20" : "正常", - "v_21" : "正常", - "v_22" : "迟到", - "v_23" : "正常", - "v_24" : "正常", - "v_25" : "正常", - "v_26" : "休息", - "v_27" : "正常", - "v_28" : "正常", - "v_29" : "正常", - "v_30" : "正常", - "v_31" : "正常", - "cd_0_30" : "1", - "cd_30_60" : "0", - "cd_60_120" : "0", - "zt_0_30" : "0", - "zt_30_60" : "0", - "zt_60_120" : "0", - "kg_day" : "0", - "lb_day" : "0", - "work_day_bt" : "0", - "xx_day_bt" : "0", - "sj_day" : "25.0", - "seal_month" : "202607", - "lk_day" : "0", - "systemSortNum" : "1", - "staff_name_export_suffix" : "崔延", - "org_full_path_export_suffix" : "集团-财务管理部-财务-投融发展组", - "v_29_export_suffix" : "正常", - "lk_day_export_suffix" : "0.0", - "GLOBAL_ORDER_export_suffix" : "1101101102", - "sj_day_export_suffix" : "25.0", - "stru_id_export_suffix" : "02440002-d5f1-11ee-b449-000c296f9469", - "lb_day_export_suffix" : "0.0", - "v_20_export_suffix" : "正常", - "dept_one_export_suffix" : "财务", - "post_name_export_suffix" : "投融资经理", - "cd_0_30_export_suffix" : "1", - "staff_id_export_suffix" : "17206f42-b874-41eb-a1f6-3651f3d2a1fd", - "v_28_export_suffix" : "正常", - "dept_org_name_export_suffix" : "投融发展组", - "v_27_export_suffix" : "正常", - "v_26_export_suffix" : "休息", - "cd_60_120_export_suffix" : "0", - "v_25_export_suffix" : "正常", - "v_24_export_suffix" : "正常", - "v_23_export_suffix" : "正常", - "v_22_export_suffix" : "迟到", - "v_21_export_suffix" : "正常", - "work_day_bt_export_suffix" : "0.0", - "v_19_export_suffix" : "休息", - "v_18_export_suffix" : "休息", - "base_code_export_suffix" : "37033852", - "v_2_export_suffix" : "正常", - "v_1_export_suffix" : "正常", - "v_4_export_suffix" : "休息", - "v_3_export_suffix" : "正常", - "v_6_export_suffix" : "正常", - "v_5_export_suffix" : "休息", - "v_8_export_suffix" : "正常", - "v_7_export_suffix" : "正常", - "v_9_export_suffix" : "正常", - "xx_day_bt_export_suffix" : "0.0", - "zt_30_60_export_suffix" : "0", - "v_17_export_suffix" : "正常", - "v_16_export_suffix" : "正常", - "v_15_export_suffix" : "正常", - "v_14_export_suffix" : "正常", - "v_13_export_suffix" : "正常", - "v_12_export_suffix" : "休息", - "v_11_export_suffix" : "正常", - "v_10_export_suffix" : "正常", - "zt_60_120_export_suffix" : "0", - "belong_unit_org_name_export_suffix" : "财务管理部", - "zt_0_30_export_suffix" : "0", - "kg_day_export_suffix" : "0.0", - "v_31_export_suffix" : "正常", - "v_30_export_suffix" : "正常", - "cd_30_60_export_suffix" : "0", - "seal_month_export_suffix" : "202607" - } ], - "pageSize" : 25, - "start" : 0, - "pageNo" : 1, - "pageCount" : 1, - "allDatas" : { - "#result-set-1" : [ { - "stru_id" : "02440002-d5f1-11ee-b449-000c296f9469", - "GLOBAL_ORDER" : "1101101102", - "base_code" : "37033852", - "org_full_path" : "集团-财务管理部-财务-投融发展组", - "belong_unit_org_name" : "财务管理部", - "dept_org_name" : "投融发展组", - "dept_one" : "财务", - "dept_four" : null, - "post_name" : "投融资经理", - "staff_name" : "崔延", - "staff_id" : "17206f42-b874-41eb-a1f6-3651f3d2a1fd", - "ext_technician_code" : "", - "v_1" : "正常", - "v_2" : "正常", - "v_3" : "正常", - "v_4" : "休息", - "v_5" : "休息", - "v_6" : "正常", - "v_7" : "正常", - "v_8" : "正常", - "v_9" : "正常", - "v_10" : "正常", - "v_11" : "正常", - "v_12" : "休息", - "v_13" : "正常", - "v_14" : "正常", - "v_15" : "正常", - "v_16" : "正常", - "v_17" : "正常", - "v_18" : "休息", - "v_19" : "休息", - "v_20" : "正常", - "v_21" : "正常", - "v_22" : "迟到", - "v_23" : "正常", - "v_24" : "正常", - "v_25" : "正常", - "v_26" : "休息", - "v_27" : "正常", - "v_28" : "正常", - "v_29" : "正常", - "v_30" : "正常", - "v_31" : "正常", - "cd_0_30" : "1", - "cd_30_60" : "0", - "cd_60_120" : "0", - "zt_0_30" : "0", - "zt_30_60" : "0", - "zt_60_120" : "0", - "kg_day" : "0", - "lb_day" : "0", - "work_day_bt" : "0", - "xx_day_bt" : "0", - "sj_day" : "25.0", - "seal_month" : "202607", - "lk_day" : "0", - "systemSortNum" : "1", - "staff_name_export_suffix" : "崔延", - "org_full_path_export_suffix" : "集团-财务管理部-财务-投融发展组", - "v_29_export_suffix" : "正常", - "lk_day_export_suffix" : "0.0", - "GLOBAL_ORDER_export_suffix" : "1101101102", - "sj_day_export_suffix" : "25.0", - "stru_id_export_suffix" : "02440002-d5f1-11ee-b449-000c296f9469", - "lb_day_export_suffix" : "0.0", - "v_20_export_suffix" : "正常", - "dept_one_export_suffix" : "财务", - "post_name_export_suffix" : "投融资经理", - "cd_0_30_export_suffix" : "1", - "staff_id_export_suffix" : "17206f42-b874-41eb-a1f6-3651f3d2a1fd", - "v_28_export_suffix" : "正常", - "dept_org_name_export_suffix" : "投融发展组", - "v_27_export_suffix" : "正常", - "v_26_export_suffix" : "休息", - "cd_60_120_export_suffix" : "0", - "v_25_export_suffix" : "正常", - "v_24_export_suffix" : "正常", - "v_23_export_suffix" : "正常", - "v_22_export_suffix" : "迟到", - "v_21_export_suffix" : "正常", - "work_day_bt_export_suffix" : "0.0", - "v_19_export_suffix" : "休息", - "v_18_export_suffix" : "休息", - "base_code_export_suffix" : "37033852", - "v_2_export_suffix" : "正常", - "v_1_export_suffix" : "正常", - "v_4_export_suffix" : "休息", - "v_3_export_suffix" : "正常", - "v_6_export_suffix" : "正常", - "v_5_export_suffix" : "休息", - "v_8_export_suffix" : "正常", - "v_7_export_suffix" : "正常", - "v_9_export_suffix" : "正常", - "xx_day_bt_export_suffix" : "0.0", - "zt_30_60_export_suffix" : "0", - "v_17_export_suffix" : "正常", - "v_16_export_suffix" : "正常", - "v_15_export_suffix" : "正常", - "v_14_export_suffix" : "正常", - "v_13_export_suffix" : "正常", - "v_12_export_suffix" : "休息", - "v_11_export_suffix" : "正常", - "v_10_export_suffix" : "正常", - "zt_60_120_export_suffix" : "0", - "belong_unit_org_name_export_suffix" : "财务管理部", - "zt_0_30_export_suffix" : "0", - "kg_day_export_suffix" : "0.0", - "v_31_export_suffix" : "正常", - "v_30_export_suffix" : "正常", - "cd_30_60_export_suffix" : "0", - "seal_month_export_suffix" : "202607" - } ] - }, - "url" : null, "state" : "1", - "meg" : "", + "meg" : "处理成功", "des" : "", - "viewMapper" : null + "result" : { + "base_code" : "37009184", + "belong_unit_org_name" : "事业部", + "belong_unit_stru_id" : "0bcdedeb-e592-11ee-b449-000c296f9469", + "contract_deadline" : "12", + "contract_end_date" : "2027-07-31", + "contract_file" : ",91728ef0aa974875a3fdbea7758a6f45,cd949564f68a4a7e9df0c61669011b84", + "contract_start_date" : "2026-08-01", + "contract_type" : "0", + "contract_type_template" : "041395a4-4d49-4a3e-a5bd-03128bf4faea,09657eb9-2855-4d6c-ae4a-4f83045845ab", + "current_contract_id" : "f4b51242-87dc-11f0-a0a5-000c296f9469", + "end_date2" : "2026-08-01", + "end_time" : "2027-08-01", + "ext_is_initiate_sign" : "2", + "ext_leave_template" : "95af4df0-d679-4f00-9503-3469c6cb4684,078df1ce-ad35-44cf-849c-dcbab32af4bc", + "ext_org_sign_status" : "2", + "ext_push_time" : "2026-08-20", + "ext_staff_sign_status" : "2", + "ext_technician_code" : "", + "file" : "", + "first_type_id" : "9d73c973-919a-4a26-a692-664bcb8fef02", + "idcard" : "512322197005235844", + "identity" : "6", + "is_new_sign" : "1", + "leaveoffice_time" : "2026-07-31", + "leaveoffice_type" : "ext_8", + "main_id" : "bpmc3a80a8e30ed44d0aeee479e114eb4b7", + "mobile_phone" : "15213746426", + "move_id" : "", + "org_full_path" : "集团-餐饮组", + "post_name" : "小吃厨师", + "post_no" : "279", + "post_org_name" : "小吃厨师", + "si_area" : "e5e14ddb-9a0e-11f1-a7d9-000c296f9469", + "staff_id" : "2b4ed7b4-7aa4-11ec-b449-000c296f9469", + "staff_name" : "陈永秀", + "treaty_type" : "5", + "trigger_type" : "2" + }, + "total" : "", + "jsonList" : null, + "viewMapper" : null, + "record" : false } \ No newline at end of file diff --git a/aa.md b/aa.md index 8438ed0..abc56e4 100644 --- a/aa.md +++ b/aa.md @@ -1,6 +1,51 @@ -202608变更-职能及干部 -申请停保 上月已停保 EHR参保单位 序号 所属单位 一级部门 二级部门 合同单位 应签署合同 37工号 姓名 岗位 社保编号 证件号码 电话号码 户口性质 职级 生日 年龄 性别 现区域 参保月份 申报工资 当前参保单位 参保单位全称 合同=参保 "转移参保单位 -(自动)" 全称 新区域 个人费用 变更后=参保 是否变更 是否有残疾证 变更后参保单位 变更原因/其他说明 备注 收集员工意见 -202608变更-门店 -湖畔是否变更 印象是否变更 申请停保 上月已停保 EHR参保单位 筹建暂调门店 筹建门店 退休办理 问题 序号 人员类别 所属单位 一级部门 二级部门 四级部门 合同单位 四级=合同 37工号 姓名 岗位 社保编号 证件号码 电话号码 户口性质 生日 年龄 性别 现区域 参保月份 申报工资 当前参保单位 参保单位全称 工作=参保 "转移参保单位 -(自动)" 参保单位全称 新区域 个人费用 变更后=参保 是否变更 是否有残疾证 变更后参保单位 变更原因/其他说明 备注 收集员工意见 +请求 URL +https://hr.37du.co/RedseaPlatform/PtFjk.mc?method=getFjkByIds +请求方法 +POST +ids=%2C91728ef0aa974875a3fdbea7758a6f45%2Ccd949564f68a4a7e9df0c61669011b84 +{ + "state" : "1", + "meg" : "处理成功", + "des" : "", + "result" : null, + "total" : "", + "jsonList" : [ { + "id" : "91728ef0aa974875a3fdbea7758a6f45", + "wid" : null, + "fileName" : "解除确认书2026082711135530519.pdf", + "fileSuffix" : ".pdf", + "fileSize" : 91972, + "savePath" : "/usr/local/uploadfile/authfolder/cq37du/third/api/2026/08/27/ff6395f7e0fb4e7087bef093db32c6b9.pdf", + "herfUrl" : "/authfolder/cq37du/third/api/2026/08/27/ff6395f7e0fb4e7087bef093db32c6b9.pdf", + "ywType" : null, + "description" : null, + "operator" : null, + "operatTime" : "2026-08-27 18:23:17", + "inUse" : "1", + "char1" : null, + "num1" : null, + "auth" : null, + "authCode" : null, + "serectSecurityLevel" : "10" + }, { + "id" : "cd949564f68a4a7e9df0c61669011b84", + "wid" : null, + "fileName" : "报酬支付确认2026082711135388183.pdf", + "fileSuffix" : ".pdf", + "fileSize" : 89285, + "savePath" : "/usr/local/uploadfile/authfolder/cq37du/third/api/2026/08/27/93bcf3ee5a1e4bcb81f90ffcead9a74e.pdf", + "herfUrl" : "/authfolder/cq37du/third/api/2026/08/27/93bcf3ee5a1e4bcb81f90ffcead9a74e.pdf", + "ywType" : null, + "description" : null, + "operator" : null, + "operatTime" : "2026-08-27 18:23:17", + "inUse" : "1", + "char1" : null, + "num1" : null, + "auth" : null, + "authCode" : null, + "serectSecurityLevel" : "10" + } ], + "viewMapper" : null, + "record" : false +} \ No newline at end of file diff --git a/app/service/hrbp/oa/common/config.py b/app/service/hrbp/oa/common/config.py index 98058d1..d13d1a5 100644 --- a/app/service/hrbp/oa/common/config.py +++ b/app/service/hrbp/oa/common/config.py @@ -82,6 +82,12 @@ FILE_DOWNLOAD_URL = f"{HR_BASE_URL}/RedseaPlatform/corePlatformOutUser/fjkFileDo # 附件默认保存目录 ATTACHMENT_SAVE_DIR = r"D:\资料\人资\请假流程审批\附件" +# 附件清单查询接口(hr 域名,见 aa.md):按 ids(逗号分隔 fileId)查询附件元信息 +# (fileName/fileSuffix/herfUrl 等),用于离职电子签签章附件(解除确认书/报酬支付确认)下载 +FJK_BY_IDS_URL = f"{HR_BASE_URL}/RedseaPlatform/PtFjk.mc?method=getFjkByIds" +# 离职电子签签章附件默认保存目录 +RESIGN_ATTACHMENT_SAVE_DIR = r"D:\资料\人资\离职电子签流程审核\附件" + # ---------- 加班审批规则常量 ---------- # 正常上班时间 T 兜底值:所有用到上班时间的地方(区间合规的加班开始时间、弹性到岗 # 兑换的次日上班时间、请假覆盖判断的早上上班时间等)都优先取排班开始时间 diff --git a/app/service/hrbp/oa/common/oa_api/flow.py b/app/service/hrbp/oa/common/oa_api/flow.py index d20df3d..62d6282 100644 --- a/app/service/hrbp/oa/common/oa_api/flow.py +++ b/app/service/hrbp/oa/common/oa_api/flow.py @@ -20,6 +20,7 @@ from app.service.hrbp.oa.common.config import ( WF_ACTIVITY_URL, WORKFORM_ENGINE_URL, FILE_DOWNLOAD_URL, + FJK_BY_IDS_URL, ATTACHMENT_SAVE_DIR, ) from app.service.hrbp.oa.common.oa_api.base import oa_request_json @@ -126,6 +127,34 @@ def get_business_data( return result +def get_fjk_file_list( + session: SessionPage, + file_ids: str, +) -> list: + """ + 按 fileId 列表调用 getFjkByIds 查询附件清单(接口见 aa.md)。 + + Args: + session: 已登录的 SessionPage 对象(已带登录 Cookie) + file_ids: 逗号分隔的多个 fileId(如表单 result.contract_file 字段) + + 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) + json_data = oa_request_json(session, "POST", FJK_BY_IDS_URL, data, "getFjkByIds") + logger.debug("getFjkByIds 返回: %s", json_data) + return json_data.get("jsonList") or [] + + def download_attachment( session: SessionPage, file_id: str, diff --git a/app/service/hrbp/oa/leave/attachment_check.py b/app/service/hrbp/oa/leave/attachment_check.py new file mode 100644 index 0000000..1a482a1 --- /dev/null +++ b/app/service/hrbp/oa/leave/attachment_check.py @@ -0,0 +1,221 @@ +# -*- coding: utf-8 -*- +""" +@Module: app.service.hrbp.oa.leave.attachment_check +@FileName: attachment_check.py +@Author: 小布丁 +@Description: 请假附件内容检测(业务层)。 + 基于通用图像 OCR(app.utils.ocr.recognize_text / recognize_text_raw): + 1. 按假期类型做关键词命中检测(病假/婚假/产检假) + 2. 结婚证登记日期识别 + 1 年内判断 +@Version: 1.0.0 +""" + +import os +import re +from datetime import date +from typing import List, Optional, Tuple + +from app.utils.ocr import recognize_text, recognize_text_raw + +# 按假期类型分类的关键词库 +LEAVE_KEYWORDS = { + # 病假/医疗类:对应医院诊断证明、病历、检验单等 + "sick": { + "医院", "门诊", "就诊", "诊断", "病历", "医嘱", "病假", "病情", + "检查", "检验", "处方", "诊断证明", "疾病", "治疗", "医技报告单", + }, + # 婚假类:对应结婚证、婚姻登记证明 + "marriage": { + "结婚证", "婚姻登记", "结婚登记", "持证人", "婚姻登记机关", + "婚姻证", "中华人民共和国结婚证", + }, + # 产检假类:对应产检报告、B超单、妊娠诊断证明 + "maternity": { + "产检", "产前检查", "孕检", "妊娠", "怀孕", "孕周", "预产期", + "超声检查", "B超", "胎儿", "产科", "孕期", "产前筛查", "胎心", + }, +} +VALID_TYPES = set(LEAVE_KEYWORDS.keys()) | {"all"} + + +def _ocr_read(file_path: str, debug: bool = False) -> Tuple[str, str]: + """识别附件图片,返回 (清洗后文本, 原始文本);文件异常/识别失败返回 ("", "")。""" + if not os.path.isfile(file_path): + return "", "" + try: + return recognize_text(file_path, debug=debug), recognize_text_raw(file_path, debug=debug) + except Exception as e: + if debug: + print(f"[识别异常] {e}") + return "", "" + + +def _hit_keywords(full_text: str, leave_type: str) -> List[str]: + """返回文本命中的关键词列表(leave_type 支持 all 汇总全部关键词)。""" + if leave_type not in VALID_TYPES: + return [] + if leave_type == "all": + target_keywords = set() + for kw_set in LEAVE_KEYWORDS.values(): + target_keywords.update(kw_set) + else: + target_keywords = LEAVE_KEYWORDS[leave_type] + return [kw for kw in target_keywords if kw in full_text] + + +def check_leave_attachment(file_path: str, leave_type: str = "sick", debug: bool = False) -> bool: + """ + 检测请假附件图片是否包含对应假期的关键词。 + + Args: + file_path: 图片文件路径(png/jpg/jpeg/bmp 等) + leave_type: sick / marriage / maternity / all + debug: 是否打印调试信息 + + Returns: + 命中关键词返回 True;未命中 / 文件异常 / 识别失败返回 False + """ + full_text, _ = _ocr_read(file_path, debug=debug) + if not full_text: + return False + + if debug: + print("【清洗后匹配文本】") + print(full_text) + print("=" * 60 + "\n") + + hit_words = _hit_keywords(full_text, leave_type) + if debug: + print(f"【命中关键词】: {hit_words}") + return len(hit_words) > 0 + + +def check_leave_attachment_detail( + file_path: str, leave_type: str = "sick", debug: bool = False +) -> Tuple[bool, List[str], str]: + """ + 检测请假附件图片是否包含对应假期的关键词,并返回命中的具体关键词列表与 OCR 原文。 + + Args: + file_path: 图片文件路径(png/jpg/jpeg/bmp 等) + leave_type: sick / marriage / maternity / all + debug: 是否打印调试信息 + + Returns: + (是否命中, 命中的关键词列表, OCR 识别原文);文件异常/识别失败返回 (False, [], "") + """ + full_text, raw_text = _ocr_read(file_path, debug=debug) + if not full_text: + return False, [], "" + + hit_words = _hit_keywords(full_text, leave_type) + return len(hit_words) > 0, hit_words, raw_text + + +def extract_dates(text: str) -> List[date]: + """ + 从文本中提取所有日期,支持 "20XX年X月X日"、"XXXX-XX-XX"、"XXXX/XX/XX" 等格式。 + + Args: + text: OCR 拼接后的文本 + + Returns: + 有效日期列表(datetime.date) + """ + dates: List[date] = [] + patterns = [ + r'(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日?', + r'(\d{4})\s*[-/.年]\s*(\d{1,2})\s*[-/.月]\s*(\d{1,2})\s*日?', + ] + for pat in patterns: + for m in re.finditer(pat, text): + try: + dates.append(date(int(m.group(1)), int(m.group(2)), int(m.group(3)))) + except ValueError: + continue + return dates + + +def _extract_registration_date(text: str) -> Optional[date]: + """ + 从结婚证文本中提取"登记日期"字段对应的日期。 + + 优先查找"登记日期"关键词后面紧跟的日期,如果找不到则返回 None。 + + Args: + text: OCR 识别的全文 + + Returns: + 登记日期(如果找到),否则返回 None + """ + # 查找"登记日期"关键词 + reg_match = re.search(r'登记日期', text) + if not reg_match: + return None + + # 从"登记日期"位置开始,提取后面紧跟的日期 + text_after = text[reg_match.end():] + date_patterns = [ + r'(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日?', + r'(\d{4})\s*[-/.年]\s*(\d{1,2})\s*[-/.月]\s*(\d{1,2})\s*日?', + ] + for pat in date_patterns: + m = re.search(pat, text_after) + if m: + try: + return date(int(m.group(1)), int(m.group(2)), int(m.group(3))) + except ValueError: + continue + return None + + +def marriage_within_one_year( + file_path: str, + today: Optional[date] = None, + debug: bool = False, +) -> Tuple[bool, Optional[date]]: + """ + 识别结婚证上的登记日期并判断是否在当前日期 1 年内。 + + 优先查找"登记日期"关键词附近的日期,如果找不到则取识别到的最大日期作为兜底。 + + Args: + file_path: 结婚证图片路径 + today: 基准日期(默认当天) + debug: 是否打印调试信息 + + Returns: + (是否 1 年内, 识别到的登记日期);识别失败/无日期返回 (False, None) + """ + if today is None: + today = date.today() + + full_text, _ = _ocr_read(file_path, debug=debug) + if not full_text: + return False, None + + dates = extract_dates(full_text) + if not dates: + if debug: + print("【未识别到任何日期】") + return False, None + + # 优先查找"登记日期"关键词附近的日期 + reg_date = _extract_registration_date(full_text) + if reg_date is None: + # 找不到"登记日期"关键词,fallback 到最大日期 + reg_date = max(dates) + if debug: + print("【未找到登记日期关键词,使用最大日期兜底】") + + ok = reg_date <= today and (today - reg_date).days <= 365 + if debug: + print(f"【识别日期】: {dates}") + print(f"【登记日期】: {reg_date},1年内: {ok}") + return ok, reg_date + + +if __name__ == "__main__": + # 简单自测入口 + path = r"D:\downloads\ocr_test_01.png" + print("病假关键词:", check_leave_attachment(path, "sick", debug=True)) diff --git a/app/service/hrbp/oa/leave/validator.py b/app/service/hrbp/oa/leave/validator.py index 1c8a508..b0367e6 100644 --- a/app/service/hrbp/oa/leave/validator.py +++ b/app/service/hrbp/oa/leave/validator.py @@ -25,7 +25,7 @@ from app.service.hrbp.oa.common.oa_api import download_attachment from app.service.hrbp.common.hr_session import build_hr_session, HRSessionExpiredError from app.service.hrbp.ehr.common.hr_api.attendance import fetch_cur_user_info from app.service.hrbp.ehr.common.hr_api.shift import fetch_all_shift -from app.utils.ocr import ( +from app.service.hrbp.oa.leave.attachment_check import ( check_leave_attachment, check_leave_attachment_detail, marriage_within_one_year, diff --git a/app/service/hrbp/oa/resign_e_sign/downloads.py b/app/service/hrbp/oa/resign_e_sign/downloads.py new file mode 100644 index 0000000..b5d8b1c --- /dev/null +++ b/app/service/hrbp/oa/resign_e_sign/downloads.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +""" +@Module: hrbp.oa.resign_e_sign.downloads +@FileName: downloads.py +@Author: 小布丁 +@CreateTime: 2026-08-31 +@Description: 离职电子签签章附件下载。 + 电子签全部完成后,按 getBusinessData 的 contract_file(逗号分隔 fileId) + 调 getFjkByIds 获取附件清单(解除确认书/报酬支付确认等), + 再逐个经 fjkFileDownload.mob 下载到本地,供后续解析校验/归档。 +@Version: 1.0.0 +""" + +from typing import Dict + +from app.utils.logger import get_logger +from app.service.hrbp.oa.common.config import RESIGN_ATTACHMENT_SAVE_DIR +from app.service.hrbp.oa.common.oa_api.flow import ( + get_fjk_file_list, + download_attachment, +) + +logger = get_logger(__name__) + + +def download_contract_files( + session, + contract_file: str, + save_dir: str = RESIGN_ATTACHMENT_SAVE_DIR, +) -> Dict[str, str]: + """ + 下载离职电子签签章附件(解除确认书/报酬支付确认)。 + + Args: + session: 已登录的 SessionPage 对象(已带登录 Cookie) + contract_file: getBusinessData 返回的 contract_file 字段(逗号分隔多个 fileId) + save_dir: 保存目录(默认离职电子签签章附件目录) + + Returns: + {文件名: 本地路径};无附件或全部失败返回空 dict(不抛异常)。 + """ + files = get_fjk_file_list(session, contract_file) + saved: Dict[str, str] = {} + for f in files: + fid = (f.get("id") or "").strip() + if not fid: + continue + path = download_attachment(session, fid, save_dir) + if path: + saved[f.get("fileName") or fid] = path + if not saved: + logger.warning("签章附件下载为空: contract_file=%s", contract_file) + return saved diff --git a/app/service/hrbp/oa/resign_e_sign/parser.py b/app/service/hrbp/oa/resign_e_sign/parser.py index 9d73159..75644ba 100644 --- a/app/service/hrbp/oa/resign_e_sign/parser.py +++ b/app/service/hrbp/oa/resign_e_sign/parser.py @@ -37,6 +37,38 @@ SIGN_STATE_MAP = { # 电子签三状态均须等于该编码(已完成)才同意 SIGN_DONE_CODE = "2" +# 离职类型字典(hr_staff_contract.leaveoffice_type 编码 -> 展示文本) +LEAVEOFFICE_TYPE_MAP = { + "": "请选择", + "0": "辞职", + "1": "辞退", + "4": "合同期内辞职", + "9": "其他", + "2": "进修学习", + "3": "参军", + "5": "除名", + "6": "开除", + "7": "死亡", + "8": "失踪", + "11": "协商一致解除", + "12": "主动离职", + "13": "非主动离职", + "14": "自动离职(未办理离职手续)", + "15": "开除人员", + "16": "调出", + "17": "合同到期未续签", + "18": "解除合同", + "ext_8": "个人申请辞职", + "ext_1": "主动辞职", + "ext_2": "到期个人不愿续签", + "ext_3": "单位不续签", + "ext_4": "劝退无证明", + "ext_5": "劝退有证明", + "ext_6": "自动离职", + "ext_7": "双方协商一致解除", + "10": "退休", +} + def _sign_name(mapping: Dict[str, str], code: Any) -> str: """将状态编码转换为名称;空值返回空串,未知编码原样返回。""" @@ -67,6 +99,8 @@ def parse_resign_e_sign_form(result: Dict[str, Any]) -> Dict[str, Any]: "组织架构": result.get("org_full_path"), "岗位": result.get("post_name"), "离职日期": result.get("leaveoffice_time"), + "离职类型编码": result.get("leaveoffice_type"), + "离职类型": _sign_name(LEAVEOFFICE_TYPE_MAP, result.get("leaveoffice_type")), "手机号": result.get("mobile_phone"), "合同类型": result.get("contract_type"), "合同开始日期": result.get("contract_start_date"), @@ -94,6 +128,7 @@ if __name__ == "__main__": "ext_staff_sign_status": "2", "idcard": "511623200311056533", "leaveoffice_time": "2026-07-31", + "leaveoffice_type": "ext_8", "mobile_phone": "19950986716", "org_full_path": "集团-金色印象事业部-第一大区-金色印象重庆第一经营中心-第四片区-石油路PLUS会馆-接待组", "post_name": "接待员", diff --git a/app/service/hrbp/oa/resign_e_sign/reporter.py b/app/service/hrbp/oa/resign_e_sign/reporter.py index 06591f9..c8b72bf 100644 --- a/app/service/hrbp/oa/resign_e_sign/reporter.py +++ b/app/service/hrbp/oa/resign_e_sign/reporter.py @@ -30,6 +30,7 @@ def _format_detail(info: Dict[str, Any]) -> str: ("组织架构", "组织架构"), ("岗位", "岗位"), ("离职日期", "离职日期"), + ("离职类型", "离职类型"), ("合同类型", "合同类型"), ("合同开始日期", "合同开始日期"), ("合同结束日期", "合同结束日期"), @@ -45,6 +46,20 @@ def _format_detail(info: Dict[str, Any]) -> str: return " | ".join(parts) +def _format_verify(verify: Dict[str, Any]) -> str: + """将文书核验结果格式化为易读摘要行。""" + if not verify: + return "" + parts = [f"文书核验: {'通过' if verify.get('is_pass') else '不通过'}"] + if verify.get("msg"): + parts.append(str(verify["msg"])) + for key in ("离职日期(表单)", "报酬支付确认日期", "解除确认书日期", "文书离职原因", "文书命中离职类型"): + val = verify.get(key) + if val: + parts.append(f"{key}={val}") + return " | ".join(parts) + + def generate_report(results: List[Dict[str, Any]]) -> str: """ 生成离职电子签审批报告:汇总行 + 每条明细 + 未完成待跟进清单(+处理失败/异常)。 @@ -85,6 +100,10 @@ def generate_report(results: List[Dict[str, Any]]) -> str: lines.append(f" {detail}") if note: lines.append(f" 备注: {note}") + if r.get("签章附件"): + lines.append(f" 签章附件: {r['签章附件']}") + if r.get("文书核验"): + lines.append(f" {_format_verify(r['文书核验'])}") if r.get("审批动作"): lines.append(f" 审批动作: {r['审批动作']}({r.get('审批结果', '')})") lines.append("") @@ -92,7 +111,7 @@ def generate_report(results: List[Dict[str, Any]]) -> str: # ----- 未完成(不管)待跟进清单 ----- if pending: lines.append("《离职电子签未完成待跟进清单》") - lines.append("(电子签未全部完成,机器不处理,待后续流转/人工跟进)") + lines.append("(电子签未全部完成,或文书核验未通过,机器不处理,待后续流转/人工复核)") for i, r in enumerate(pending, 1): info = r.get("resign_info", {}) or {} note = r.get("note") or "" diff --git a/app/service/hrbp/oa/resign_e_sign/validator.py b/app/service/hrbp/oa/resign_e_sign/validator.py index 5bc6220..4b14703 100644 --- a/app/service/hrbp/oa/resign_e_sign/validator.py +++ b/app/service/hrbp/oa/resign_e_sign/validator.py @@ -5,8 +5,9 @@ @Author: 小布丁 @CreateTime: 2026-08-20 @Description: 离职电子签流程校验模块(审批决策两态:通过 / 未完成)。 - 规则(见 aa.md):进入详情取三个电子签状态字段,三者均为"已完成"才同意, - 否则不处理("不管"),留给后续待办继续流转。 + 规则(见 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) @@ -20,6 +21,8 @@ from app.service.hrbp.oa.resign_e_sign.parser import ( parse_resign_e_sign_form, SIGN_DONE_CODE, ) +from app.service.hrbp.oa.resign_e_sign.downloads import download_contract_files +from app.service.hrbp.oa.resign_e_sign.verify_docs import verify_resign_docs logger = get_logger(__name__) @@ -35,12 +38,13 @@ def validate_doc(doc: Dict[str, Any], session: Any) -> Dict[str, Any]: 流程: 1. 解析表单数据,提取电子签三状态与员工信息 - 2. 三者均已完成 -> 通过(同意);否则 -> 未完成(不管) + 2. 三者均已完成 -> 通过(同意),并下载签章附件(解除确认书/报酬支付确认) + 3. 否则 -> 未完成(不管) Args: doc: 单据信息,含基本信息(title/creator/time/detail_url) 和审批引擎已获取的 taskId/businessKey/formId/formData(表单详情) - session: 已登录的 SessionPage 对象(本流程无需额外接口,保留参数以适配公共引擎签名) + session: 已登录的 SessionPage 对象(通过时用于下载签章附件) Returns: 校验结果,包含审批决策及详细信息 @@ -67,10 +71,47 @@ def validate_doc(doc: Dict[str, Any], session: Any) -> Dict[str, Any]: 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"] = ( - "审批通过(是否已发起电子签/员工签署状态/企业签署状态均为已完成)" - ) + # 三状态均已完成:下载签章附件并核验文书。 + # 审批决策须「电子签三状态 + 文书核验」全部满足才通过;任一不满足均不审批。 + verify_result = None + try: + files = download_contract_files(session, form_data.get("contract_file")) + if files: + result["签章附件"] = " | ".join(f"{name}->{path}" for name, path in files.items()) + # 文书核验:解析 PDF,比对日期/离职原因与表单字段 + try: + verify_result = verify_resign_docs(files, resign_info) + except Exception as e: + logger.warning("核验离职电子签文书失败[%s]: %s", doc.get("title", ""), e) + verify_result = {"is_pass": False, "msg": f"文书核验失败: {e}"} + result["文书核验"] = verify_result + else: + result["签章附件"] = "无(未查询到签章附件)" + verify_result = {"is_pass": False, "msg": "未查询到签章附件,无法核验文书"} + result["文书核验"] = verify_result + except Exception as e: + logger.warning("下载离职电子签签章附件失败[%s]: %s", doc.get("title", ""), e) + result["签章附件"] = f"下载失败: {e}" + verify_result = {"is_pass": False, "msg": f"签章附件下载失败: {e}"} + result["文书核验"] = verify_result + + if verify_result is not None and verify_result.get("is_pass"): + result["decision"] = "通过" + result["note"] = ( + "审批通过(电子签三状态均为已完成,且文书核验通过:" + "报酬支付确认/解除确认书日期与离职原因均与表单一致)" + ) + else: + result["decision"] = "未完成" + result["note"] = ( + "电子签三状态均已完成,但文书核验未通过,暂不审批待人工复核:" + f"{verify_result.get('msg', '') if verify_result else '核验结果缺失'}" + ) + logger.info( + "核验不通过单据[%s] %s: %s", + doc.get("title", ""), resign_info.get("员工姓名", ""), + verify_result.get("msg", "") if verify_result else "核验结果缺失", + ) else: result["decision"] = "未完成" result["note"] = ( diff --git a/app/service/hrbp/oa/resign_e_sign/verify_docs.py b/app/service/hrbp/oa/resign_e_sign/verify_docs.py new file mode 100644 index 0000000..e8c2568 --- /dev/null +++ b/app/service/hrbp/oa/resign_e_sign/verify_docs.py @@ -0,0 +1,202 @@ +# -*- coding: utf-8 -*- +""" +@Module: hrbp.oa.resign_e_sign.verify_docs +@FileName: verify_docs.py +@Author: 小布丁 +@CreateTime: 2026-08-31 +@Description: 离职电子签签章文书核验(下载 PDF 之后)。 + 1. 日期核验:报酬支付确认 / 解除确认书中的日期 == 表单实际离职日期(leaveoffice_time) + 2. 原因核验:解除确认书"因Xxx已于"中的离职原因 == 表单离职类型(leaveoffice_type 中文) + 核验结论仅用于报告展示与人工复核,不影响审批决策。 +@Version: 1.0.0 +""" + +import re +from datetime import date +from typing import Dict, List, Optional + +from app.utils.logger import get_logger +from app.utils.pdf import parse_pdf +from app.service.hrbp.oa.resign_e_sign.parser import LEAVEOFFICE_TYPE_MAP + +logger = get_logger(__name__) + +def _norm_zh(s: str) -> str: + """只保留汉字(用于归一化匹配,兼容 OCR 各种标点/空格)。""" + return re.sub(r"[^\u4e00-\u9fff]", "", s or "") + + +# 离职类型展示文本(LEAVEOFFICE_TYPE_MAP 的值,排除空/请选择), +# 存 (归一化汉字, 原展示文本) 二元组,按归一化长度降序做最长匹配 +_LEAVE_TEXT_SORTED = sorted( + ((_norm_zh(v), v) for v in LEAVEOFFICE_TYPE_MAP.values() if v and v != "请选择"), + key=lambda pair: len(pair[0]), + reverse=True, +) + + +def extract_doc_reason(text: str) -> Optional[str]: + """提取"因...已于"中间的离职原因,过滤非汉字(兼容 OCR 各种标点)。""" + clean_text = re.sub(r"\s+", "", text) + match = re.search(r"因(.*?)已于", clean_text) + if not match: + return None + raw_content = match.group(1) + reason = re.sub(r"[^\u4e00-\u9fff]", "", raw_content) + return reason.strip() or None + + +def longest_match_leave_type(doc_reason: str) -> Optional[str]: + """在离职类型展示文本列表做最长关键词匹配,返回命中的展示文本;无命中返回 None。""" + if not doc_reason: + return None + norm = _norm_zh(doc_reason) + for norm_opt, display in _LEAVE_TEXT_SORTED: + if norm_opt and norm_opt in norm: + return display + return None + + +def _extract_dates(text: str) -> List[date]: + """提取文本中所有日期,支持 XXXX年X月X日 / XXXX-XX-XX / XXXX/XX/XX 等格式。""" + dates: List[date] = [] + patterns = [ + r'(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日?', + r'(\d{4})\s*[-/.年]\s*(\d{1,2})\s*[-/.月]\s*(\d{1,2})\s*日?', + ] + for pat in patterns: + for m in re.finditer(pat, text): + try: + d = date(int(m.group(1)), int(m.group(2)), int(m.group(3))) + except ValueError: + continue + if d not in dates: + dates.append(d) + return dates + + +def _parse_form_date(value: str) -> Optional[date]: + """把表单里的离职日期字符串(YYYY-MM-DD)解析为 date。""" + if not value: + return None + m = re.match(r'(\d{4})\s*[-/.年]\s*(\d{1,2})\s*[-/.月]\s*(\d{1,2})\s*日?', str(value).strip()) + if not m: + return None + try: + return date(int(m.group(1)), int(m.group(2)), int(m.group(3))) + except ValueError: + return None + + +def _find_by_name(pdf_paths: Dict[str, str], keyword: str) -> Optional[str]: + """按文件名关键字从 {文件名: 路径} 中找对应的本地路径。""" + for name, path in pdf_paths.items(): + if keyword in name: + return path + return None + + +def verify_resign_docs(pdf_paths: Dict[str, str], resign_info: Dict) -> Dict: + """ + 核验下载的签章文书(解除确认书 / 报酬支付确认)与表单字段是否一致。 + + Args: + pdf_paths: {文件名: 本地路径},download_contract_files 的返回 + resign_info: parse_resign_e_sign_form 结果(含离职日期/离职类型) + + Returns: + { + "离职日期(表单)": str | None, + "离职类型(表单)": str | None, + "报酬支付确认日期": str | None, # 识别到的日期(ISO 逗号拼接) + "解除确认书日期": str | None, + "文书离职原因": str | None, + "文书命中离职类型": str | None, + "日期是否一致": True | False | None, + "原因是否一致": True | False | None, + "is_pass": bool, # 日期与原因均比对存在且一致 + "msg": str, # 可读的核验结论 + } + """ + form_date = _parse_form_date(resign_info.get("离职日期")) + form_type = resign_info.get("离职类型") + + result = { + "离职日期(表单)": resign_info.get("离职日期"), + "离职类型(表单)": form_type, + "报酬支付确认日期": None, + "解除确认书日期": None, + "文书离职原因": None, + "文书命中离职类型": None, + "日期是否一致": None, + "原因是否一致": None, + "is_pass": False, + "msg": "", + } + issues: List[str] = [] + + # ---- 日期核验:报酬支付确认 + 解除确认书 ---- + doc_dates: Dict[str, List[date]] = {} + for keyword in ("报酬支付确认", "解除确认书"): + path = _find_by_name(pdf_paths, keyword) + if not path: + issues.append(f"{keyword}文书缺失") + continue + try: + dates = _extract_dates(parse_pdf(path)) + except Exception as e: + logger.warning("解析%s失败: %s", keyword, e) + issues.append(f"{keyword}解析失败({e})") + continue + result[f"{keyword}日期"] = ",".join(d.isoformat() for d in dates) or None + doc_dates[keyword] = dates + + if doc_dates: + if form_date is not None: + all_ok = True + for keyword, dates in doc_dates.items(): + if form_date not in dates: + all_ok = False + issues.append( + f"{keyword}日期[{result[f'{keyword}日期']}]≠表单离职日期[{form_date.isoformat()}]" + ) + result["日期是否一致"] = all_ok + else: + issues.append("表单无离职日期,无法核验日期") + else: + issues.append("未获取到任何文书日期,无法核验日期") + + # ---- 原因核验:解除确认书 ---- + relieve_path = _find_by_name(pdf_paths, "解除确认书") + if relieve_path: + try: + reason = extract_doc_reason(parse_pdf(relieve_path)) + except Exception as e: + logger.warning("解析解除确认书失败: %s", e) + reason = None + issues.append(f"解除确认书解析失败({e})") + hit = longest_match_leave_type(reason) + result["文书离职原因"] = reason + result["文书命中离职类型"] = hit + if hit and form_type: + result["原因是否一致"] = (hit == form_type) + if hit != form_type: + issues.append(f"解除确认书原因[{hit}]≠表单离职类型[{form_type}]") + elif not form_type: + issues.append("表单无离职类型,无法核验原因") + else: + issues.append(f"解除确认书未命中任何离职类型(原因[{reason}])") + + result["is_pass"] = result["日期是否一致"] is True and result["原因是否一致"] is True + result["msg"] = ";".join(issues) if issues else "核验通过(日期与原因均与表单一致)" + return result + + +if __name__ == "__main__": + # 简单自测入口 + demo_paths = { + "解除确认书2026082711135530519.pdf": r"D:\资料\人资\离职电子签流程审核\附件\解除确认书.pdf", + "报酬支付确认2026082711135388183.pdf": r"D:\资料\人资\离职电子签流程审核\附件\报酬支付确认.pdf", + } + demo_info = {"离职日期": "2026-07-31", "离职类型": "个人申请辞职"} + print(verify_resign_docs(demo_paths, demo_info)) diff --git a/app/utils/ocr.py b/app/utils/ocr.py index 1355a7d..eac615f 100644 --- a/app/utils/ocr.py +++ b/app/utils/ocr.py @@ -3,16 +3,15 @@ @Module: app.utils.ocr @FileName: ocr.py @Author: 小布丁 -@Description: 请假附件 OCR 内容检测模块。 - 1. 按假期类型做关键词命中检测(病假/婚假/产检假) - 2. 结婚证登记日期识别 + 1 年内判断 -@Version: 1.0.0 +@Description: 通用图像文字识别模块(RapidOCR)。 + 只做「传图片 -> 返回识别文本」,不含任何业务判断; + 业务判断由各业务脚本负责(如请假附件关键词检测见 + app/service/hrbp/oa/leave/attachment_check.py)。 +@Version: 2.0.0 """ -import os import re -from datetime import date, timedelta -from typing import Any, Dict, List, Optional, Tuple +from typing import Tuple from PIL import Image, ImageEnhance, ImageOps import numpy as np @@ -22,57 +21,34 @@ try: except ImportError: RapidOCR = None -# ==================== 配置 ==================== -# 按假期类型分类的关键词库 -LEAVE_KEYWORDS: Dict[str, set] = { - # 病假/医疗类:对应医院诊断证明、病历、检验单等 - "sick": { - "医院", "门诊", "就诊", "诊断", "病历", "医嘱", "病假", "病情", - "检查", "检验", "处方", "诊断证明", "疾病", "治疗", "医技报告单", - }, - # 婚假类:对应结婚证、婚姻登记证明 - "marriage": { - "结婚证", "婚姻登记", "结婚登记", "持证人", "婚姻登记机关", - "婚姻证", "中华人民共和国结婚证", - }, - # 产检假类:对应产检报告、B超单、妊娠诊断证明 - "maternity": { - "产检", "产前检查", "孕检", "妊娠", "怀孕", "孕周", "预产期", - "超声检查", "B超", "胎儿", "产科", "孕期", "产前筛查", "胎心", - }, -} - # 置信度阈值:低于该分数的识别片段会被丢弃 -CONFIDENCE_THRESHOLD = 0.5 -VALID_TYPES = set(LEAVE_KEYWORDS.keys()) | {"all"} +_CONFIDENCE_THRESHOLD = 0.5 # 全局初始化 OCR 引擎,首次运行自动下载模型 _ocr_engine = RapidOCR() if RapidOCR is not None else None -# ============================================= -def _read_text(file_path: str, debug: bool = False) -> Tuple[str, str]: +def _preprocess_image(img) -> np.ndarray: + """预处理图像:EXIF 转正(修正手机横拍)+ 转灰度 + 提升对比度,返回可喂给 OCR 的图像数组。""" + img = ImageOps.exif_transpose(img) + gray_img = img.convert("L") + enhancer = ImageEnhance.Contrast(gray_img) + enhanced_img = enhancer.enhance(2.0) + return np.array(enhanced_img) + + +def _run_ocr(img_array: np.ndarray, debug: bool = False) -> Tuple[str, str]: """ - OCR 识别图片,返回 (清洗后拼接文本 full_text, 原始拼接文本 raw_text)。 + 对预处理后的图像数组执行 OCR,返回 (清洗后拼接文本, 原始拼接文本)。 - - 转灰度 + 提升对比度优化拍照单据识别 - 过滤低置信度片段 - - 去空格与特殊符号,便于关键词匹配 + - 清洗:去空格与特殊符号,便于关键词匹配 """ - with Image.open(file_path) as img: - # 应用 EXIF 方向信息,修正手机横拍导致的旋转 - img = ImageOps.exif_transpose(img) - gray_img = img.convert("L") - enhancer = ImageEnhance.Contrast(gray_img) - enhanced_img = enhancer.enhance(2.0) - img_array = np.array(enhanced_img) - if _ocr_engine is None: raise RuntimeError("RapidOCR 未安装,请执行: pip install rapidocr onnxruntime") result = _ocr_engine(img_array) - boxes = result.boxes if result and result.boxes is not None else [] txts = result.txts if result and result.txts is not None else () scores = result.scores if result and result.scores is not None else () @@ -86,7 +62,7 @@ def _read_text(file_path: str, debug: bool = False) -> Tuple[str, str]: raw_text = "" full_text = "" for text, score in zip(txts, scores): - if score < CONFIDENCE_THRESHOLD: + if score < _CONFIDENCE_THRESHOLD: continue raw_text += text clean_text = text.replace(" ", "").replace("\u3000", "") @@ -99,195 +75,56 @@ def _read_text(file_path: str, debug: bool = False) -> Tuple[str, str]: return full_text, raw_text -def check_leave_attachment(file_path: str, leave_type: str = "sick", debug: bool = False) -> bool: +def _read_image(img, debug: bool = False) -> Tuple[str, str]: + """对 PIL.Image 做预处理并 OCR,返回 (清洗后拼接文本, 原始拼接文本)。""" + img_array = _preprocess_image(img) + return _run_ocr(img_array, debug=debug) + + +def _read_text(file_path: str, debug: bool = False) -> Tuple[str, str]: + """OCR 识别图片文件,返回 (清洗后拼接文本, 原始拼接文本)。""" + with Image.open(file_path) as img: + return _read_image(img, debug=debug) + + +def recognize_image(img, debug: bool = False) -> str: """ - 检测请假附件图片是否包含对应假期的关键词。 + 通用图像 OCR(图像输入):传入 PIL.Image 或 numpy 数组,返回识别出的清洗后文本。 + + 供 PDF 扫描页渲染等内存图像场景复用;图片文件场景请使用 recognize_text()。 + """ + if isinstance(img, np.ndarray): + img = Image.fromarray(img) + full_text, _ = _read_image(img, debug=debug) + return full_text + + +def recognize_text(file_path: str, debug: bool = False) -> str: + """ + 通用图像 OCR(文件输入):传入图片路径,返回识别出的清洗后文本。 Args: file_path: 图片文件路径(png/jpg/jpeg/bmp 等) - leave_type: sick / marriage / maternity / all debug: 是否打印调试信息 Returns: - 命中关键词返回 True;未命中 / 文件异常 / 识别失败返回 False + 识别出的文本(已去空格、过滤特殊符号,便于关键词匹配);文件异常/识别失败抛异常 """ - if leave_type not in VALID_TYPES: - return False - if not os.path.isfile(file_path): - return False - - try: - full_text, raw_text = _read_text(file_path, debug=debug) - except Exception as e: - if debug: - print(f"[识别异常] {e}") - return False - - if debug: - print("【清洗后匹配文本】") - print(full_text) - print("=" * 60 + "\n") - - if leave_type == "all": - target_keywords = set() - for kw_set in LEAVE_KEYWORDS.values(): - target_keywords.update(kw_set) - else: - target_keywords = LEAVE_KEYWORDS[leave_type] - - hit_words = [kw for kw in target_keywords if kw in full_text] - if debug: - print(f"【命中关键词】: {hit_words}") - - return len(hit_words) > 0 + full_text, _ = _read_text(file_path, debug=debug) + return full_text -def check_leave_attachment_detail( - file_path: str, leave_type: str = "sick", debug: bool = False -) -> Tuple[bool, List[str], str]: +def recognize_text_raw(file_path: str, debug: bool = False) -> str: """ - 检测请假附件图片是否包含对应假期的关键词,并返回命中的具体关键词列表与 OCR 全文。 + 通用图像 OCR(文件输入):返回原始拼接文本(保留识别片段原样,含空格/符号)。 - Args: - file_path: 图片文件路径(png/jpg/jpeg/bmp 等) - leave_type: sick / marriage / maternity / all - debug: 是否打印调试信息 - - Returns: - (是否命中, 命中的关键词列表, OCR 识别全文);文件异常/识别失败返回 (False, [], "") + 需要展示识别原文时使用;默认请用 recognize_text()。 """ - if leave_type not in VALID_TYPES: - return False, [], "" - if not os.path.isfile(file_path): - return False, [], "" - - try: - full_text, raw_text = _read_text(file_path, debug=debug) - except Exception as e: - if debug: - print(f"[识别异常] {e}") - return False, [], "" - - if leave_type == "all": - target_keywords: set = set() - for kw_set in LEAVE_KEYWORDS.values(): - target_keywords.update(kw_set) - else: - target_keywords = LEAVE_KEYWORDS[leave_type] - - hit_words = [kw for kw in target_keywords if kw in full_text] - return len(hit_words) > 0, hit_words, raw_text - - -def extract_dates(text: str) -> List[date]: - """ - 从文本中提取所有日期,支持 "20XX年X月X日"、"XXXX-XX-XX"、"XXXX/XX/XX" 等格式。 - - Args: - text: OCR 拼接后的文本 - - Returns: - 有效日期列表(datetime.date) - """ - dates: List[date] = [] - patterns = [ - r'(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日?', - r'(\d{4})\s*[-/.年]\s*(\d{1,2})\s*[-/.月]\s*(\d{1,2})\s*日?', - ] - for pat in patterns: - for m in re.finditer(pat, text): - try: - dates.append(date(int(m.group(1)), int(m.group(2)), int(m.group(3)))) - except ValueError: - continue - return dates - - -def _extract_registration_date(text: str) -> Optional[date]: - """ - 从结婚证文本中提取"登记日期"字段对应的日期。 - - 优先查找"登记日期"关键词后面紧跟的日期,如果找不到则返回 None。 - - Args: - text: OCR 识别的全文 - - Returns: - 登记日期(如果找到),否则返回 None - """ - # 查找"登记日期"关键词 - reg_match = re.search(r'登记日期', text) - if not reg_match: - return None - - # 从"登记日期"位置开始,提取后面紧跟的日期 - text_after = text[reg_match.end():] - date_patterns = [ - r'(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日?', - r'(\d{4})\s*[-/.年]\s*(\d{1,2})\s*[-/.月]\s*(\d{1,2})\s*日?', - ] - for pat in date_patterns: - m = re.search(pat, text_after) - if m: - try: - return date(int(m.group(1)), int(m.group(2)), int(m.group(3))) - except ValueError: - continue - return None - - -def marriage_within_one_year( - file_path: str, - today: Optional[date] = None, - debug: bool = False, -) -> Tuple[bool, Optional[date]]: - """ - 识别结婚证上的登记日期并判断是否在当前日期 1 年内。 - - 优先查找"登记日期"关键词附近的日期,如果找不到则取识别到的最大日期作为兜底。 - - Args: - file_path: 结婚证图片路径 - today: 基准日期(默认当天) - debug: 是否打印调试信息 - - Returns: - (是否 1 年内, 识别到的登记日期);识别失败/无日期返回 (False, None) - """ - if today is None: - today = date.today() - if not os.path.isfile(file_path): - return False, None - - try: - full_text, raw_text = _read_text(file_path, debug=debug) - except Exception as e: - if debug: - print(f"[识别异常] {e}") - return False, None - - dates = extract_dates(full_text) - if not dates: - if debug: - print("【未识别到任何日期】") - return False, None - - # 优先查找"登记日期"关键词附近的日期 - reg_date = _extract_registration_date(full_text) - if reg_date is None: - # 找不到"登记日期"关键词,fallback 到最大日期 - reg_date = max(dates) - if debug: - print("【未找到登记日期关键词,使用最大日期兜底】") - - ok = reg_date <= today and (today - reg_date).days <= 365 - if debug: - print(f"【识别日期】: {dates}") - print(f"【登记日期】: {reg_date},1年内: {ok}") - return ok, reg_date + _, raw_text = _read_text(file_path, debug=debug) + return raw_text if __name__ == "__main__": # 简单自测入口 path = r"D:\downloads\ocr_test_01.png" - print("病假关键词:", check_leave_attachment(path, "sick", debug=True)) + print(recognize_text(path, debug=True)) diff --git a/app/utils/pdf.py b/app/utils/pdf.py new file mode 100644 index 0000000..dbe005f --- /dev/null +++ b/app/utils/pdf.py @@ -0,0 +1,70 @@ +# -*- coding: utf-8 -*- +""" +@Module: app.utils.pdf +@FileName: pdf.py +@Author: 小布丁 +@Description: PDF 内容解析模块(PyMuPDF)。 + 1. 文本型 PDF:PyMuPDF 直接提取每页文本 + 2. 扫描型 PDF:PyMuPDF 逐页渲染为图像,复用 app.utils.ocr.recognize_image 做 OCR +@Version: 1.0.0 +""" + +import os + +from PIL import Image + +try: + import fitz # PyMuPDF +except ImportError: + fitz = None + +from app.utils.ocr import recognize_image + +# 扫描页渲染分辨率(dpi):越高识别越准但越耗时 +SCAN_PAGE_DPI = 200 + + +def parse_pdf(file_path: str, debug: bool = False) -> str: + """解析 PDF 并返回全文。 + + 逐页解析: + - 页面含可提取文本层 -> 直接取文本(文本型 PDF); + - 页面无可提取文本(扫描件/图片型)-> 渲染为图像后复用通用图像 OCR recognize_image。 + + Args: + file_path: PDF 文件路径 + debug: 是否打印调试信息 + + Returns: + 全文文本(各页用换行拼接);文件异常/解析失败抛异常 + """ + if fitz is None: + raise RuntimeError("PyMuPDF 未安装,请执行: pip install pymupdf") + if not os.path.isfile(file_path): + raise FileNotFoundError(f"PDF 文件不存在: {file_path}") + + doc = fitz.open(file_path) + try: + parts = [] + for page_no, page in enumerate(doc, 1): + text = (page.get_text("text") or "").strip() + if text: + parts.append(text) + continue + # 扫描页:渲染为图像走通用 OCR + if debug: + print(f"【PDF】第 {page_no} 页无文本层,渲染为图像做 OCR ...") + pix = page.get_pixmap(dpi=SCAN_PAGE_DPI) + img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples) + page_text = recognize_image(img, debug=debug) + if page_text: + parts.append(page_text) + return "\n".join(parts) + finally: + doc.close() + + +if __name__ == "__main__": + # 简单自测入口 + _path = r"D:\downloads\pdf_test_01.pdf" + print(parse_pdf(_path, debug=True)) diff --git a/requirements.txt b/requirements.txt index e16f7c6..db27ae5 100644 --- a/requirements.txt +++ b/requirements.txt @@ -12,5 +12,6 @@ numpy opencv-python onnxruntime rapidocr +PyMuPDF pandas requests \ No newline at end of file diff --git a/tests/ocr.py b/tests/ocr.py index 328fff8..550ac87 100644 --- a/tests/ocr.py +++ b/tests/ocr.py @@ -1,7 +1,8 @@ # -*- coding: utf-8 -*- """ OCR 附件检测测试入口。 -实际逻辑已迁移至 app/utils/ocr.py,本文件仅做导入与自测。 +通用图像识别见 app/utils/ocr.py,请假附件业务检测见 +app/service/hrbp/oa/leave/attachment_check.py,本文件仅做导入与自测。 """ import os @@ -12,7 +13,11 @@ _PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if _PROJECT_ROOT not in sys.path: sys.path.insert(0, _PROJECT_ROOT) -from app.utils.ocr import check_leave_attachment, marriage_within_one_year, extract_dates +from app.service.hrbp.oa.leave.attachment_check import ( + check_leave_attachment, + marriage_within_one_year, + extract_dates, +) if __name__ == "__main__": diff --git a/tests/test.py b/tests/test.py index 3c16a07..4b9280a 100644 --- a/tests/test.py +++ b/tests/test.py @@ -1,180 +1,128 @@ -import os -import time -import pandas as pd -from docxtpl import DocxTemplate -from datetime import datetime -import pythoncom -import win32com.client +import re +from bs4 import BeautifulSoup -# ========================== 配置区域 ========================== -SUCCESS_TEMPLATE = r"D:\资料\人资\参保状态告知\参保成功告知书模板.docx" -FAILURE_TEMPLATE = r"D:\资料\人资\参保状态告知\参保异常告知书模板.docx" -EXCEL_PATH = r"D:\资料\人资\参保状态告知\data.xlsx" -OUTPUT_DIR = r"D:\资料\人资\参保状态告知\output" -COLUMN_MAPPING = { - "姓名": "name", - "身份证号": "id_card", - "状态": "status", - "保单号": "policy_number", - "生效日期": "effective_date", - "异常原因": "reason", -} +# ========== 网页表单全部可选离职类型(直接复制select里的option文本) ========== +WEB_OPTION_LIST = [ + "请选择", + "辞职", + "辞退", + "合同期内辞职", + "其他", + "进修学习", + "参军", + "除名", + "开除", + "死亡", + "失踪", + "协商一致解除", + "主动离职", + "非主动离职", + "自动离职(未办理离职手续)", + "开除人员", + "调出", + "合同到期未续签", + "解除合同", + "个人申请辞职", + "主动辞职", + "到期个人不愿续签", + "单位不续签", + "劝退无证明", + "劝退有证明", + "自动离职", + "双方协商一致解除", + "退休" +] +# 按字符串长度降序,实现最长匹配,长词优先 +WEB_OPTION_SORTED = sorted(WEB_OPTION_LIST, key=lambda x: len(x), reverse=True) -DATE_FORMAT = "%Y年%m月%d日" -# ===================== WPS 转 PDF(增强版:带重试) ===================== -def wps_docx_to_pdf(docx_file: str, pdf_file: str, retries=3, delay=2): +def extract_doc_reason(text: str) -> str | None: """ - 使用 WPS 将 docx 导出为 PDF,带重试机制 + 提取因...已于中间内容,过滤掉非汉字,兼容OCR各种标点 """ - for attempt in range(retries): - # 如果 PDF 已存在且有效,直接成功(避免重复转换) - if os.path.exists(pdf_file) and os.path.getsize(pdf_file) > 0: - return True + clean_text = re.sub(r"\s+", "", text) + match = re.search(r"因(.*?)已于", clean_text) + if not match: + return None + raw_content = match.group(1) + # 只保留汉字 + reason = re.sub(r"[^\u4e00-\u9fff]", "", raw_content) + return reason.strip() - pythoncom.CoInitialize() - wps = None - try: - # WPS 文字的 ProgID:kwps.application - wps = win32com.client.Dispatch("kwps.application") - wps.Visible = False - wps.DisplayAlerts = 0 # 不弹窗 - doc = wps.Documents.Open(os.path.abspath(docx_file)) - # 17 = wdFormatPDF (PDF 格式) - doc.ExportAsFixedFormat(os.path.abspath(pdf_file), 17) - doc.Close() +def longest_match_web_option(doc_reason: str) -> str | None: + """ + 在网页选项列表做最长关键词匹配 + 返回命中的网页选项文本;无命中返回None + """ + if not doc_reason: + return None + for opt in WEB_OPTION_SORTED: + if opt in doc_reason: + return opt + return None - # 检查是否真正生成 - if os.path.exists(pdf_file) and os.path.getsize(pdf_file) > 0: - return True - except Exception as e: - if attempt < retries - 1: - print(f" 🔄 WPS 转换重试 {attempt+2}/{retries}...") - time.sleep(delay) # 等待 WPS 资源释放 - continue - else: - print(f" ❌ WPS 转换失败(已重试 {retries} 次): {e}") - return False - finally: - try: - if wps is not None: - wps.Quit() - except: - pass - try: - pythoncom.CoUninitialize() - except: - pass +def check_verify(doc_reason: str, web_selected_text: str) -> tuple[bool, str]: + """ + 校验:文书提取的原因,最长匹配到的网页选项,是否等于网页实际选中值 + """ + hit_opt = longest_match_web_option(doc_reason) + if hit_opt is None: + return False, f"文书【{doc_reason}】没有匹配到网页表单任何离职类型,请人工复核" - return False + if hit_opt == web_selected_text: + return True, f"匹配成功:文书命中网页选项【{hit_opt}】,网页实际选中【{web_selected_text}】" + else: + return False, f"不匹配:文书命中网页选项【{hit_opt}】,网页实际选中【{web_selected_text}】" -# ========================== 辅助函数 ========================== -def safe_mkdir(path): - if not os.path.exists(path): - os.makedirs(path) -def format_value(value, var_name): - if pd.isna(value): - return "" - if var_name == "effective_date": - if isinstance(value, datetime): - return value.strftime(DATE_FORMAT) - try: - return pd.to_datetime(value).strftime(DATE_FORMAT) - except: - return str(value) - return str(value) +def extract_html_leave_type(html: str) -> tuple[str | None, str | None]: + """解析select,返回(编码,选中展示文本)""" + soup = BeautifulSoup(html, "html.parser") + select_elem = soup.find("select", name="leaveoffice_type") + if not select_elem: + return None, None + selected_opt = select_elem.find("option", selected=True) + if not selected_opt: + return None, None + code = selected_opt.get("value") + text_val = selected_opt.get_text(strip=True) + return code, text_val -# ========================== 主流程 ========================== -def main(): - # 检查文件 - if not os.path.exists(SUCCESS_TEMPLATE): - print(f"❌ 找不到成功模板:{SUCCESS_TEMPLATE}") - return - if not os.path.exists(FAILURE_TEMPLATE): - print(f"❌ 找不到异常模板:{FAILURE_TEMPLATE}") - return - if not os.path.exists(EXCEL_PATH): - print(f"❌ 找不到 Excel 数据:{EXCEL_PATH}") - return - safe_mkdir(OUTPUT_DIR) +def verify_resign(doc_text: str, html_snippet: str) -> dict: + """统一校验入口""" + doc_reason = extract_doc_reason(doc_text) + web_code, web_text = extract_html_leave_type(html_snippet) - try: - df = pd.read_excel(EXCEL_PATH, engine="openpyxl") - print(f"📊 共读取 {len(df)} 条参保记录") - except Exception as e: - print(f"❌ 读取 Excel 失败:{e}") - return + if doc_reason is None: + return { + "doc_extract_reason": None, + "web_leave_code": web_code, + "web_leave_text": web_text, + "is_pass": False, + "msg": "未能从文书提取离职原因,模板不匹配,需要人工复核" + } - success_count = 0 - fail_count = 0 - skip_count = 0 + is_ok, msg = check_verify(doc_reason, web_text) + return { + "doc_extract_reason": doc_reason, + "web_leave_code": web_code, + "web_leave_text": web_text, + "is_pass": is_ok, + "msg": msg + } - for idx, row in df.iterrows(): - try: - context = {} - for excel_col, var_name in COLUMN_MAPPING.items(): - raw_value = row.get(excel_col) - context[var_name] = format_value(raw_value, var_name) - - context["current_date"] = datetime.now().strftime(DATE_FORMAT) - - status = context.get("status", "").strip() - if status == "成功": - template_path = SUCCESS_TEMPLATE - prefix = "成功" - elif status == "异常": - template_path = FAILURE_TEMPLATE - prefix = "异常" - else: - print(f"⚠️ 第 {idx+1} 行状态未知('{status}'),已跳过") - skip_count += 1 - continue - - # 生成 Word - doc = DocxTemplate(template_path) - doc.render(context) - - name = context.get("name", f"row_{idx+1}") - safe_name = "".join(c for c in str(name) if c.isalnum() or c in "._- ") - base_filename = f"{safe_name}_{prefix}_{idx+1:03d}" - - docx_path = os.path.join(OUTPUT_DIR, f"{base_filename}.docx") - doc.save(docx_path) - print(f"✅ Word 已生成:{os.path.basename(docx_path)}") - - # 转换 PDF(带重试) - pdf_path = os.path.join(OUTPUT_DIR, f"{base_filename}.pdf") - ok = wps_docx_to_pdf(docx_path, pdf_path, retries=3, delay=2) - if ok: - print(f"✅ PDF 已生成:{os.path.basename(pdf_path)}") - if status == "成功": - success_count += 1 - else: - fail_count += 1 - else: - print(f"❌ PDF 生成失败:{base_filename},Word 文件已保留") - # 仍计入统计(状态已知,但 PDF 缺失) - if status == "成功": - success_count += 1 - else: - fail_count += 1 - - except Exception as e: - print(f"❌ 第 {idx+1} 行处理异常:{e}") - continue - - print("\n" + "=" * 50) - print(f"🎉 处理完成!") - print(f" ✅ 参保成功:{success_count} 份") - print(f" ❌ 参保异常:{fail_count} 份") - print(f" ⏭️ 跳过记录:{skip_count} 份") - print(f" 📁 文件保存在:{OUTPUT_DIR}") - print("=" * 50) if __name__ == "__main__": - main() \ No newline at end of file + # 测试样例 + doc_text_example = """曾入职渝中区金指故事足浴馆(个体工商户)担任小吃厨师职务,因个人申请辞职,已于2026年07月 31 日办理完离职相关手续,正式与公司解除用工关系""" + + html_example = '''''' + + result = verify_resign(doc_text_example, html_example) + print("=====校验结果=====") + for k, v in result.items(): + print(f"{k}: {v}") diff --git a/yingdao/XQ0020 EHR系统离职电子签流程审核/resign_e_sign_approval.py b/yingdao/XQ0020 EHR系统离职电子签流程审核/resign_e_sign_approval.py index 1d254ed..caf574c 100644 --- a/yingdao/XQ0020 EHR系统离职电子签流程审核/resign_e_sign_approval.py +++ b/yingdao/XQ0020 EHR系统离职电子签流程审核/resign_e_sign_approval.py @@ -8,7 +8,7 @@ @Version: 1.0.0 依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载): - pip install DrissionPage python-dotenv + pip install DrissionPage python-dotenv pymupdf 登录(共享登录态,本脚本仅读取 cookies 文件,不 import 任何共享模块): 「37duOA登录」指令写入 %LOCALAPPDATA%\37duAutomation\.sessions\oa_cookies.json; @@ -25,6 +25,8 @@ import os import random import re import time +import traceback +from datetime import date from typing import Callable from urllib.parse import urlencode, urlparse, parse_qs @@ -41,6 +43,18 @@ except ImportError as _import_err: f"缺失依赖详情: {_import_err}" ) +# ==================== PDF 解析依赖(影刀版启动校验:全部必须预先安装,不懒加载) ==================== +# 用于签章文书(解除确认书/报酬支付确认)PDF 解析;签章文书均为文字型 PDF,直接提取文本,不引入 OCR +try: + import fitz # PyMuPDF +except ImportError as _import_err: + raise RuntimeError( + "缺少 PDF 解析依赖,无法启动(签章文书核验需要)。\n" + "请先执行安装:\n" + " pip install pymupdf\n" + f"缺失依赖详情: {_import_err}" + ) + # ==================== 路径 & 常量配置 ==================== # 数据目录固定放在 AppData\Local\37duAutomation,不依赖脚本位置,每台电脑都有; # 登录态与共享 .env 统一由「37duOA登录」影刀自定义指令写入(见 yingdao/share/oa_login.py) @@ -58,6 +72,12 @@ 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" +# 附件清单查询接口(见 aa.md):按 ids(逗号分隔 fileId)查附件元信息(fileName/herfUrl 等) +FJK_BY_IDS_URL = f"{HR_BASE_URL}/RedseaPlatform/PtFjk.mc?method=getFjkByIds" +# 附件下载接口:按 fileId 下载 +FILE_DOWNLOAD_URL = f"{HR_BASE_URL}/RedseaPlatform/corePlatformOutUser/fjkFileDownload.mob" +# 离职电子签签章附件(解除确认书/报酬支付确认)默认保存目录 +CONTRACT_SAVE_DIR = r"D:\资料\人资\离职电子签流程审核\附件" # 审批提交接口:点击"同意"确认后前端会调用 sendWeTask(method=sendWeTask), # 监听其响应以区分提交成功/失败:state="1" 成功,state="0" 失败(失败时页面不关闭) SEND_WE_TASK_URL = f"{HR_BASE_URL}/RedseaPlatform/WeTask.mc" @@ -418,6 +438,38 @@ SIGN_STATE_MAP = { # 电子签三状态均须等于该编码(已完成)才同意 SIGN_DONE_CODE = "2" +# 离职类型字典(hr_staff_contract.leaveoffice_type 编码 -> 展示文本) +LEAVEOFFICE_TYPE_MAP = { + "": "请选择", + "0": "辞职", + "1": "辞退", + "4": "合同期内辞职", + "9": "其他", + "2": "进修学习", + "3": "参军", + "5": "除名", + "6": "开除", + "7": "死亡", + "8": "失踪", + "11": "协商一致解除", + "12": "主动离职", + "13": "非主动离职", + "14": "自动离职(未办理离职手续)", + "15": "开除人员", + "16": "调出", + "17": "合同到期未续签", + "18": "解除合同", + "ext_8": "个人申请辞职", + "ext_1": "主动辞职", + "ext_2": "到期个人不愿续签", + "ext_3": "单位不续签", + "ext_4": "劝退无证明", + "ext_5": "劝退有证明", + "ext_6": "自动离职", + "ext_7": "双方协商一致解除", + "10": "退休", +} + def _sign_name(mapping, code): """将状态编码转换为名称;空值返回空串,未知编码原样返回。""" @@ -439,6 +491,8 @@ def parse_resign_e_sign_form(result): "组织全路径": result.get("org_full_path"), "岗位": result.get("post_name"), "离职日期": result.get("leaveoffice_time"), + "离职类型编码": result.get("leaveoffice_type"), + "离职类型": _sign_name(LEAVEOFFICE_TYPE_MAP, result.get("leaveoffice_type")), "手机号": result.get("mobile_phone"), "合同类型": result.get("contract_type"), "合同开始日期": result.get("contract_start_date"), @@ -916,95 +970,378 @@ def run_flow(subject, validate_doc, generate_report): """ 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)) + # 先用纯接口 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}单据"]) - 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"] - result["审批结果"] = f"{submit['message']}" - # 审批结论与提交动作分离:提交失败不改审批结论(仍为"通过"), - # 仅记录 submit_ok 供推送/报告单列提醒;OA 中状态未变,需人工跟进 - result["submit_ok"] = submit["ok"] - if submit["ok"] == "false": - result["note"] = ( - f"审批通过但自动提交失败(OA 中未生效,需人工跟进):{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) - - logger.info("%s审批流程结束,共处理 %d 条", subject, len(results)) + # 无待办单据:不开浏览器,直接生成提示消息返回 + if not docs: + logger.info("%s无待审批单据,跳过浏览器操作", subject) + push_messages = _build_push_messages([f"暂无待审批的{subject}单据"]) + logger.info("%s审批流程结束,共处理 0 条(无单据)", subject) 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: + + # 有单据才启动浏览器: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"] + result["审批结果"] = f"{submit['message']}" + # 审批结论与提交动作分离:提交失败不改审批结论(仍为"通过"), + # 仅记录 submit_ok 供推送/报告单列提醒;OA 中状态未变,需人工跟进 + result["submit_ok"] = submit["ok"] + if submit["ok"] == "false": + result["note"] = ( + f"审批通过但自动提交失败(OA 中未生效,需人工跟进):{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: - browser.quit() + 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) + + 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 + + +# ==================== 签章附件下载 ==================== +# 电子签全部完成后,按 getBusinessData 的 contract_file(逗号分隔 fileId)调 getFjkByIds +# 获取附件清单(解除确认书/报酬支付确认等),再逐个经 fjkFileDownload.mob 下载到本地。 +def get_contract_files(session, contract_file): + """按 contract_file(逗号分隔 fileId)调 getFjkByIds 查询签章附件清单(见 aa.md)。""" + ids = [x.strip() for x in str(contract_file).split(",") if x.strip()] + if not ids: + return [] + session.post(FJK_BY_IDS_URL, data={"ids": ",".join(ids)}) + resp = session.response + if not resp or resp.status_code != 200: + raise RuntimeError( + f"getFjkByIds 接口状态码异常: {resp.status_code if resp else '无响应'}" + ) + json_data = resp.json() + return json_data.get("jsonList") or [] + + +def _download_contract_file(session, file_id, save_dir): + """下载单个签章附件 fileId(fjkFileDownload.mob),返回本地路径;失败返回 None。""" + from urllib.parse import unquote + if not file_id: + return None + os.makedirs(save_dir, exist_ok=True) + download_url = f"{FILE_DOWNLOAD_URL}?fileId={file_id}" + logger.info("下载签章附件: fileId=%s", file_id) + try: + session.get(download_url) + resp = session.response + except Exception as e: + logger.warning("签章附件请求失败(fileId=%s): %s", file_id, e) + return None + + if not resp or resp.status_code != 200: + logger.warning("签章附件下载失败: HTTP %s (fileId=%s)", resp.status_code, file_id) + 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]) + else: + try: + raw = raw.encode('latin-1').decode('utf-8') + except (UnicodeDecodeError, UnicodeEncodeError): + pass + 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 + + +def download_contract_files(session, contract_file, save_dir=CONTRACT_SAVE_DIR): + """签完成后下载解除确认书/报酬支付确认,返回 {文件名: 本地路径};失败返回空 dict。""" + files = get_contract_files(session, contract_file) + saved = {} + for f in files: + fid = (f.get("id") or "").strip() + if not fid: + continue + path = _download_contract_file(session, fid, save_dir) + if path: + saved[f.get("fileName") or fid] = path + if not saved: + logger.warning("签章附件下载为空: contract_file=%s", contract_file) + return saved + + +# ==================== PDF 解析(文字型,直接提取文本) ==================== +# 签章文书(解除确认书/报酬支付确认)均为文字型 PDF,直接用 PyMuPDF 逐页提取文本; +# 不引入 OCR;若出现无文本层的扫描件,解析为空串 -> 核验不通过,留待人工复核 +def parse_pdf(file_path): + """解析 PDF 并返回全文(文字型:逐页提取文本,无文本层则返回空串)。""" + doc = fitz.open(file_path) + try: + parts = [] + for page in doc: + text = (page.get_text("text") or "").strip() + if text: + parts.append(text) + return "\n".join(parts) + finally: + doc.close() + + +# ==================== 签章文书核验(下载 PDF 后比对表单字段) ==================== +# 1. 日期核验:报酬支付确认 / 解除确认书的识别日期 是否包含 表单实际离职日期(leaveoffice_time) +# 2. 原因核验:解除确认书"因Xxx已于"提取的离职原因 最长匹配 离职类型 是否等于表单离职类型 +# 核验结论仅用于报告展示与人工复核,不影响审批决策。 + + +def _norm_zh(s): + """只保留汉字(归一化匹配,兼容 OCR 各种标点/空格)。""" + return re.sub(r"[^\u4e00-\u9fff]", "", s or "") + + +# 离职类型展示文本(排除空/请选择),存 (归一化汉字, 原展示文本),按归一化长度降序做最长匹配 +_LEAVE_TEXT_SORTED = sorted( + ((_norm_zh(v), v) for v in LEAVEOFFICE_TYPE_MAP.values() if v and v != "请选择"), + key=lambda pair: len(pair[0]), + reverse=True, +) + + +def extract_doc_reason(text): + """提取"因...已于"中间的离职原因,过滤非汉字(兼容 OCR 各种标点)。""" + clean_text = re.sub(r"\s+", "", text) + match = re.search(r"因(.*?)已于", clean_text) + if not match: + return None + return _norm_zh(match.group(1)) or None + + +def longest_match_leave_type(doc_reason): + """在离职类型展示文本列表做最长关键词匹配,返回命中的展示文本;无命中返回 None。""" + if not doc_reason: + return None + norm = _norm_zh(doc_reason) + for norm_opt, display in _LEAVE_TEXT_SORTED: + if norm_opt and norm_opt in norm: + return display + return None + + +def _extract_dates(text): + """提取文本中所有日期,支持 XXXX年X月X日 / XXXX-XX-XX / XXXX/XX/XX 等格式。""" + dates = [] + patterns = [ + r'(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日?', + r'(\d{4})\s*[-/.年]\s*(\d{1,2})\s*[-/.月]\s*(\d{1,2})\s*日?', + ] + for pat in patterns: + for m in re.finditer(pat, text): + try: + d = date(int(m.group(1)), int(m.group(2)), int(m.group(3))) + except ValueError: + continue + if d not in dates: + dates.append(d) + return dates + + +def _parse_form_date(value): + """把表单离职日期字符串(YYYY-MM-DD)解析为 date。""" + if not value: + return None + m = re.match(r'(\d{4})\s*[-/.年]\s*(\d{1,2})\s*[-/.月]\s*(\d{1,2})\s*日?', str(value).strip()) + if not m: + return None + try: + return date(int(m.group(1)), int(m.group(2)), int(m.group(3))) + except ValueError: + return None + + +def _find_by_name(pdf_paths, keyword): + """按文件名关键字从 {文件名: 路径} 中找对应的本地路径。""" + for name, path in pdf_paths.items(): + if keyword in name: + return path + return None + + +def verify_resign_docs(pdf_paths, resign_info): + """ + 核验下载的签章文书(解除确认书 / 报酬支付确认)与表单字段是否一致。 + + Args: + pdf_paths: {文件名: 本地路径},download_contract_files 的返回 + resign_info: parse_resign_e_sign_form 结果(含离职日期/离职类型) + + Returns: + { + "离职日期(表单)": str | None, + "离职类型(表单)": str | None, + "报酬支付确认日期": str | None, # 识别到的日期(ISO 逗号拼接) + "解除确认书日期": str | None, + "文书离职原因": str | None, + "文书命中离职类型": str | None, + "日期是否一致": True | False | None, + "原因是否一致": True | False | None, + "is_pass": bool, # 日期与原因均比对存在且一致 + "msg": str, # 可读的核验结论 + } + """ + form_date = _parse_form_date(resign_info.get("离职日期")) + form_type = resign_info.get("离职类型") + + result = { + "离职日期(表单)": resign_info.get("离职日期"), + "离职类型(表单)": form_type, + "报酬支付确认日期": None, + "解除确认书日期": None, + "文书离职原因": None, + "文书命中离职类型": None, + "日期是否一致": None, + "原因是否一致": None, + "is_pass": False, + "msg": "", + } + issues = [] + + # ---- 日期核验:报酬支付确认 + 解除确认书 ---- + doc_dates = {} + for keyword in ("报酬支付确认", "解除确认书"): + path = _find_by_name(pdf_paths, keyword) + if not path: + issues.append(f"{keyword}文书缺失") + continue + try: + dates = _extract_dates(parse_pdf(path)) + except Exception as e: + logger.warning("解析%s失败: %s", keyword, e) + issues.append(f"{keyword}解析失败({e})") + continue + result[f"{keyword}日期"] = ",".join(d.isoformat() for d in dates) or None + doc_dates[keyword] = dates + + if doc_dates: + if form_date is not None: + all_ok = True + for keyword, dates in doc_dates.items(): + if form_date not in dates: + all_ok = False + issues.append( + f"{keyword}日期[{result[f'{keyword}日期']}]≠表单离职日期[{form_date.isoformat()}]" + ) + result["日期是否一致"] = all_ok + else: + issues.append("表单无离职日期,无法核验日期") + else: + issues.append("未获取到任何文书日期,无法核验日期") + + # ---- 原因核验:解除确认书 ---- + relieve_path = _find_by_name(pdf_paths, "解除确认书") + if relieve_path: + try: + reason = extract_doc_reason(parse_pdf(relieve_path)) + except Exception as e: + logger.warning("解析解除确认书失败: %s", e) + reason = None + issues.append(f"解除确认书解析失败({e})") + hit = longest_match_leave_type(reason) + result["文书离职原因"] = reason + result["文书命中离职类型"] = hit + if hit and form_type: + result["原因是否一致"] = (hit == form_type) + if hit != form_type: + issues.append(f"解除确认书原因[{hit}]≠表单离职类型[{form_type}]") + elif not form_type: + issues.append("表单无离职类型,无法核验原因") + else: + issues.append(f"解除确认书未命中任何离职类型(原因[{reason}])") + + result["is_pass"] = result["日期是否一致"] is True and result["原因是否一致"] is True + result["msg"] = ";".join(issues) if issues else "核验通过(日期与原因均与表单一致)" + return result # ==================== 离职电子签校验规则 ==================== @@ -1042,8 +1379,45 @@ def validate_doc(doc, session): 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"] = "审批通过(是否已发起电子签/员工签署状态/企业签署状态均为已完成)" + # 三状态均已完成:下载签章附件并核验文书。 + # 审批决策须「电子签三状态 + 文书核验」全部满足才通过;任一不满足均不审批。 + verify_result = None + try: + files = download_contract_files(session, form_data.get("contract_file")) + if files: + result["签章附件"] = " | ".join(f"{name}->{path}" for name, path in files.items()) + # 文书核验:解析 PDF,比对日期/离职原因与表单字段 + try: + verify_result = verify_resign_docs(files, resign_info) + except Exception as e: + logger.warning("核验离职电子签文书失败[%s]: %s", doc.get("title", ""), e) + verify_result = {"is_pass": False, "msg": f"文书核验失败: {e}"} + result["文书核验"] = verify_result + else: + result["签章附件"] = "无(未查询到签章附件)" + verify_result = {"is_pass": False, "msg": "未查询到签章附件,无法核验文书"} + result["文书核验"] = verify_result + except Exception as e: + logger.warning("下载离职电子签签章附件失败[%s]: %s", doc.get("title", ""), e) + result["签章附件"] = f"下载失败: {e}" + verify_result = {"is_pass": False, "msg": f"签章附件下载失败: {e}"} + result["文书核验"] = verify_result + + if verify_result is not None and verify_result.get("is_pass"): + result["decision"] = "通过" + result["note"] = ( + "审批通过(电子签三状态均为已完成,且文书核验通过:" + "报酬支付确认/解除确认书日期与离职原因均与表单一致)" + ) + else: + result["decision"] = "未完成" + result["note"] = ( + "电子签三状态均已完成,但文书核验未通过,暂不审批待人工复核:" + f"{verify_result.get('msg', '') if verify_result else '核验结果缺失'}" + ) + logger.info("核验不通过单据[%s] %s: %s", + doc.get("title", ""), resign_info.get("员工姓名", ""), + verify_result.get("msg", "") if verify_result else "核验结果缺失") else: result["decision"] = "未完成" result["note"] = ( @@ -1074,6 +1448,7 @@ def _format_detail(info): ("组织全路径", "组织全路径"), ("岗位", "岗位"), ("离职日期", "离职日期"), + ("离职类型", "离职类型"), ("合同类型", "合同类型"), ("合同开始日期", "合同开始日期"), ("合同结束日期", "合同结束日期"), @@ -1089,6 +1464,20 @@ def _format_detail(info): return " | ".join(parts) +def _format_verify(verify): + """将文书核验结果格式化为易读摘要行。""" + if not verify: + return "" + parts = [f"文书核验: {'通过' if verify.get('is_pass') else '不通过'}"] + if verify.get("msg"): + parts.append(str(verify["msg"])) + for key in ("离职日期(表单)", "报酬支付确认日期", "解除确认书日期", "文书离职原因", "文书命中离职类型"): + val = verify.get(key) + if val: + parts.append(f"{key}={val}") + return " | ".join(parts) + + def generate_report(results): """ 生成离职电子签审批报告:汇总行 + 每条明细 + 未完成待跟进清单(+提交失败/处理失败)。 @@ -1123,6 +1512,10 @@ def generate_report(results): lines.append(f" {detail}") if note: lines.append(f" 备注: {note}") + if r.get("签章附件"): + lines.append(f" 签章附件: {r['签章附件']}") + if r.get("文书核验"): + lines.append(f" {_format_verify(r['文书核验'])}") if r.get("审批动作"): lines.append(f" 审批动作: {r['审批动作']}({r.get('审批结果', '')})") lines.append("") @@ -1130,7 +1523,7 @@ def generate_report(results): # ----- 未完成(不管)待跟进清单 ----- if pending: lines.append("《离职电子签未完成待跟进清单》") - lines.append("(电子签未全部完成,机器不处理,待后续流转/人工跟进)") + lines.append("(电子签未全部完成,或文书核验未通过,机器不处理,待后续流转/人工复核)") for i, r in enumerate(pending, 1): info = r.get("resign_info", {}) or {} note = r.get("note") or "" @@ -1172,19 +1565,27 @@ def main(): 本脚本不发送任何消息:仅生成待推送消息(返回列表并写入影刀全局变量 messages), 由「37du钉钉群机器人推送」指令消费;仅生成群消息。 """ - push_messages = run_flow( - subject="改签离职电子签流程", - validate_doc=validate_doc, - generate_report=generate_report, - ) - # 写入影刀全局变量 messages(块格式分组列表:{title, blocks}), - # 供「37du钉钉群机器人推送」指令读取后整体传入 main(),由模块内部分批逐条发送; - # 本地独立运行时静默跳过 - _set_glv("messages", [ - m for m in push_messages - if str(m.get("text", "") or m.get("blocks", "") or "").strip() - ]) - return push_messages + try: + push_messages = run_flow( + subject="改签离职电子签流程", + validate_doc=validate_doc, + generate_report=generate_report, + ) + # 写入影刀全局变量 messages(块格式分组列表:{title, blocks}), + # 供「37du钉钉群机器人推送」指令读取后整体传入 main(),由模块内部分批逐条发送; + # 本地独立运行时静默跳过 + _set_glv("messages", [ + m for m in push_messages + if str(m.get("text", "") or m.get("blocks", "") or "").strip() + ]) + return push_messages + except SystemExit: + # 登录态缺失/失效等前置条件问题:已是友好提示(无堆栈),原样上抛给影刀展示 + raise + except Exception as e: + # 非预期异常兜底:先打印完整堆栈便于排查,再抛精简友好信息,避免整屏堆栈 + traceback.print_exc() + raise RuntimeError(f"离职电子签流程执行异常,请查看上方运行日志后重试: {e}") from e if __name__ == "__main__":