Files
37duAutomation/plugins/XQ0001-0100/XQ0004 EHR系统加班流程审核/__init__.py
T
puddy 14d72ee0b2 fix(plugin): XQ0004 1.2.1 延时加班推送只展示加班时段,不展示加班天数
- 延时加班按小时计,推送里去掉「加班天数」,改展示加班起止时段;
  休息日/法定假日仍按天计,展示逻辑不变
- 插件版(report/overtime_report.py)与影刀版(overtime_approval.py)同步
2026-11-16 11:27:52 +08:00

223 lines
11 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 -*-
"""XQ0004 EHR系统加班流程审核 插件入口。
流程编排(由影刀版 overtime_approval.py 移植,登录态改由底座注入):
1) 会话准备:底座注入 HR session/userId → getCurUserInfo 校验(失效抛错提示重新登录);
2) 拉取「加班」待办(纯接口,无待办不启动浏览器);
3) 逐单取表单并校验:按加班类型(延时/法定假日/休息日)校验加班日期、时长、排班
与打卡区间,延时加班另做提前到岗型与弹性到岗兑换校验;
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 .data.hr_api import HRSessionExpiredError
from .logic import overtime_rules
from .report import overtime_report
from .report import dingtalk_robot
class OvertimeApprovalPlugin(ScenePlugin):
"""EHR系统加班流程审核(需求 XQ0004)。"""
id = "xq0004"
name = "EHR系统加班流程审核"
version = "1.2.1"
description = ("自动审核 EHR 加班待办:拉取待办与加班表单,按加班类型(延时/法定假日/休息日)"
"校验加班日期、时长、排班与打卡区间及弹性到岗兑换;校验通过自动提交审批,"
"并生成审批报告与钉钉群推送。")
platform = "hr"
uses_month = False
capabilities = ["xq0004"]
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": "开启后把汇总与需人工处理明细推送到钉钉群机器人",
},
"push_env": {
"type": "string", "title": "推送环境", "default": "dev",
"description": "dev=内置测试群,prod=内置生产群;填写自定义 Webhook 时以自定义为准",
},
"dingtalk_webhook": {
"type": "string", "title": "钉钉 Webhook", "default": "",
"description": "留空使用内置默认机器人;需要发到其他群时填写完整 webhook 地址",
},
"dingtalk_secret": {
"type": "string", "title": "钉钉加签密钥", "default": "",
"description": "机器人启用加签安全设置时填写,留空表示不加签",
},
"debug_mode": {
"type": "boolean", "title": "调试日志", "default": False,
"description": "开启后输出接口返回等调试信息",
},
}
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))
push_env = (fields.get("push_env") or "dev").strip().lower() or "dev"
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 = []
skipped = []
try:
if docs:
for idx, doc in enumerate(docs, 1):
try:
detail = hr_api.fetch_doc_detail(doc)
result = overtime_rules.validate_doc(detail, session)
# 当天发起当天的加班:本次跳过不审核(不提交、不入报告/推送),后续再审核
if result.get("decision") == "跳过":
skipped.append(result)
ctx.log(f"已跳过 {idx}/{len(docs)}: {result.get('creator')} - "
f"{result.get('title')} -> {result.get('note')}", "INFO")
ctx.progress(15 + int(75 * idx / len(docs)))
continue
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 = overtime_report.generate_report(results)
report_path = overtime_report.save_report(report_text, save_dir)
ctx.progress(95)
# ---- 步骤4:钉钉推送 ----
push_message = ""
if push_enabled:
push_items = overtime_report.build_push_summary(results, subject)
if not push_items and skipped:
push_items = [{"text": f"本次跳过 {len(skipped)} 条当天加班单据(当天打卡未完成),"
f"待打卡完成后再次审核"}]
if not push_items:
push_items = [{"text": f"暂无待审批的{subject}单据"}]
push_res = dingtalk_robot.main(
push_items, title=f"【{subject}审批】汇总",
webhook=webhook, secret=secret, env=push_env)
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") == "人工复核"),
"overdue": 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") == "失败"),
"skipped": len(skipped),
}
if not docs:
summary = f"暂无待审批的{subject}单据;报告:{report_path}"
else:
summary = (f"{subject}审批完成,共 {counts['total']} 单:通过 {counts['passed']},"
f"校验不通过未处理 {counts['rejected']},人工复核 {counts['review']}")
if counts["skipped"]:
summary += f",当天加班跳过 {counts['skipped']}"
if counts["overdue"]:
summary += f",超期待人资处理 {counts['overdue']}"
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,
}
except HRSessionExpiredError as e:
# 与影刀版 run_flow 一致:中途 HR 会话失效时给出明确提示,而非原始异常冒泡
ctx.log(f"HR 登录态已失效,请重新登录后再执行: {e}", "ERROR")
raise RuntimeError("HR 登录态已失效,请重新登录 HR 后再执行") from e
finally:
if browser is not None:
try:
browser.quit()
except Exception:
pass
PLUGINS.append(OvertimeApprovalPlugin())