Files
37duAutomation/plugins/xq0003/__init__.py
T

196 lines
9.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""XQ0003 EHR系统请假流程审核 插件入口。
流程编排(由影刀版 leave_approval.py 移植,登录态改由底座注入):
1) 会话准备:底座注入 HR session/userId → getCurUserInfo 校验(失效抛错提示重新登录);
2) 拉取「请假」待办(纯接口,无待办不启动浏览器);
3) 逐单取表单并校验:Group1 仅比对排班上班天数与填报天数;Group2 另需附件
(病假/结婚证/产检 OCR,特殊事假/产假/丧假仅需附件);小时特假校验请假时段
是否落在排班班段内(含前一天跨天夜班)+ 已上传附件;
4) 校验通过且开启自动审批时,浏览器注入 HR cookies 后点击同意并确认;
5) 生成审批报告落盘 + 钉钉群机器人推送(汇总 + 需人工处理明细)。
"""
import time
from webhost.backend.plugins.base import ScenePlugin, PLUGINS
from . import config
from .data import hr_api
from .data import hr_browser
from .logic import leave_rules
from .report import leave_report
from .report import dingtalk_robot
class LeaveApprovalPlugin(ScenePlugin):
"""EHR系统请假流程审核(需求 XQ0003)。"""
id = "xq0003"
name = "EHR系统请假流程审核"
version = "1.0.0"
description = ("自动审核 EHR 请假待办:按假期类型校验排班上班天数与填报天数是否一致,"
"病假/结婚证/产检按附件 OCR 关键词核验,小时特假校验请假时段是否落在排班班段内;"
"校验通过自动提交审批,并生成审批报告与钉钉群推送。")
platform = "hr"
uses_month = False
capabilities = ["xq0003"]
permissions = {"platforms": ["hr"]}
fields = {
"save_dir": {
"type": "string", "title": "输出目录",
"default": config.DEFAULT_SAVE_DIR,
"description": "审批报告与服务端附件(附件/ 子目录)统一存放目录",
},
"approve_enabled": {
"type": "boolean", "title": "自动提交审批", "default": True,
"description": "开启后,校验结论为「通过」的单据会在流程详情页自动点击同意;关闭则只校验不提交",
},
"push_enabled": {
"type": "boolean", "title": "钉钉群推送", "default": True,
"description": "开启后把汇总与需人工处理明细推送到钉钉群机器人",
},
"dingtalk_webhook": {
"type": "string", "title": "钉钉 Webhook", "default": "",
"description": "留空使用内置默认机器人;需要发到其他群时填写完整 webhook 地址",
},
"dingtalk_secret": {
"type": "string", "title": "钉钉加签密钥", "default": "",
"description": "机器人启用加签安全设置时填写,留空表示不加签",
},
"debug_mode": {
"type": "boolean", "title": "调试日志", "default": False,
"description": "开启后输出 OCR 识别明细等调试信息",
},
}
def run(self, fields: dict, ctx):
# ---- 注入运行上下文:日志 / 进度 / HR 会话 / userId / 输出目录 ----
config.set_log(ctx.log)
config.set_progress(ctx.progress)
config.set_session(ctx.get_session("hr"))
config.set_user_id(ctx.get_user_id("hr"))
save_dir = (fields.get("save_dir") or "").strip() or config.DEFAULT_SAVE_DIR
config.set_save_dir(save_dir)
config.set_debug(bool(fields.get("debug_mode")))
approve_enabled = bool(fields.get("approve_enabled", True))
push_enabled = bool(fields.get("push_enabled", True))
webhook = (fields.get("dingtalk_webhook") or "").strip()
secret = (fields.get("dingtalk_secret") or "").strip()
subject = config.DEFAULT_SUBJECT
session = config.require_session()
ctx.log(f"===== 请假审批启动:输出目录 {save_dir},自动审批={'开' if approve_enabled else '关'} =====",
"INFO")
# ---- 步骤1:会话校验 ----
ctx.progress(5)
user_id = hr_api.validate_session(session)
config.set_user_id(user_id)
# ---- 步骤2:拉取请假待办 ----
ctx.progress(10)
docs = hr_api.fetch_documents(session, subject)
ctx.log(f"共获取{subject}待办 {len(docs)} 条", "INFO")
ctx.progress(15)
browser = None
results = []
try:
if docs:
for idx, doc in enumerate(docs, 1):
try:
detail = hr_api.fetch_doc_detail(doc)
result = leave_rules.validate_doc(detail, session)
if approve_enabled and result.get("decision") == "通过":
if browser is None:
browser = hr_browser.build_browser(session)
browser.get(detail["detail_url"])
time.sleep(1.5) # 等待详情页与审批按钮加载
orig_decision = result.get("decision")
submit = hr_browser.submit_approval(browser, orig_decision)
result["审批动作"] = submit["action"]
result["审批结果"] = submit["message"]
# 提交失败兜底:单据状态未变,不能仍标为通过,归为「异常」交人工跟进
if submit["ok"] == "false":
result["decision"] = "异常"
result["note"] = (
f"机器结论[{orig_decision}]但审批提交失败:{submit['message']}"
)
ctx.log(f"审批提交: {submit['action']} {submit['message']}", "INFO")
elif result.get("decision") != "通过":
ctx.log(f"决策为{result.get('decision')},不自动提交审批(待人工处理)", "INFO")
results.append(result)
ctx.log(f"已校验 {idx}/{len(docs)}: {result.get('creator')} - "
f"{result.get('title')} -> {result.get('decision')}", "INFO")
except Exception as e:
ctx.log(f"处理单据失败: {doc.get('title')}, 错误: {e}", "ERROR")
results.append({
"creator": doc.get("creator", "未知"),
"title": doc.get("title", "未知"),
"detail_url": doc.get("detail_url", ""),
"decision": "失败",
"error": str(e),
})
ctx.progress(15 + int(75 * idx / len(docs)))
else:
ctx.log(f"{subject}无待审批单据,跳过浏览器操作", "INFO")
# ---- 步骤3:报告落盘 ----
ctx.progress(92)
report_text = leave_report.generate_report(results)
report_path = leave_report.save_report(report_text, save_dir)
ctx.progress(95)
# ---- 步骤4:钉钉推送 ----
push_message = ""
if push_enabled:
push_items = leave_report.build_push_summary(results, subject)
if not push_items:
push_items = [{"text": f"暂无待审批的{subject}单据"}]
push_res = dingtalk_robot.main(
push_items, title=f"【{subject}审批】汇总",
webhook=webhook, secret=secret)
push_message = push_res.get("message", "")
ctx.log(f"钉钉推送: {push_message}", "INFO")
ctx.progress(100)
counts = {
"total": len(results),
"passed": sum(1 for r in results if r.get("decision") == "通过"),
"rejected": sum(1 for r in results if r.get("decision") == "校验不通过未处理"),
"review": sum(1 for r in results if r.get("decision") == "人工复核"),
"abnormal": sum(1 for r in results if r.get("decision") == "异常"),
"failed": sum(1 for r in results if r.get("decision") == "失败"),
}
if not docs:
summary = f"暂无待审批的{subject}单据;报告:{report_path}"
else:
summary = (f"{subject}审批完成,共 {counts['total']} 单:通过 {counts['passed']},"
f"校验不通过未处理 {counts['rejected']},人工复核 {counts['review']}")
if counts["abnormal"]:
summary += f",审批异常 {counts['abnormal']}"
if counts["failed"]:
summary += f",处理失败 {counts['failed']}"
summary += f";报告:{report_path}"
if push_message:
summary += f";推送:{push_message}"
return {
"summary": summary,
"detail": counts,
"path": report_path,
"results": results,
"save_dir": save_dir,
}
finally:
if browser is not None:
try:
browser.quit()
except Exception:
pass
PLUGINS.append(LeaveApprovalPlugin())