Files
puddy a2f4e756ae feat: 更新3个插件版本并优化XQ0006考勤异常处理逻辑
- XQ0036门店员工起调薪处理:版本升至0.1.6,优化纳税单位解析逻辑,优先使用接口返回值,新增金色印象、金色湖畔、后浪会馆的纳税单位兜底规则
- XQ0047微盟数据导出:版本升至1.0.5,新增等待生成上限配置项,优化轮询超时处理逻辑
- XQ0006 EHR系统周考勤异常处理:版本升至1.4.1,重构推送逻辑,支持组织架构范围选择,新增dws推送通道,优化自动确认范围为整月轻微异常,新增组织架构同步功能
2026-11-20 13:41:03 +08:00

355 lines
17 KiB
Python
Raw Permalink 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 -*-
"""XQ0006 EHR系统周考勤异常处理 插件入口。
流程编排(由影刀版 attendance_abnormal.py 移植,登录态改由底座注入):
1) 会话校验:底座注入 HR session → getCurUserInfo 校验(失效提示重新登录);
2) 拉取查询月份(默认 1 号查上月,否则当月)全部「未调整」考勤异常;
3) 导出 Excel 底稿(试算模式只做这一步);
4) 自动确认:整月轻微异常(迟到/早退 < 30 分钟,分批调用确认接口);
5) 钉钉推送(口径):仅推送上周「组织架构勾选节点(含下级)」的严重异常给当事人,
并把条数汇总推送到群。组织架构由界面「同步组织架构」拉取 HR 组织维护台账并固化为
JSON,勾选节点按组织全路径前缀匹配数据行;未勾选则不推送当事人。
优先用 dws(单聊 + 群、附 Excel);未装 dws 时当事人回退工作通知,
群汇总不发送(需要附件能力)。
"""
import json
import os
from dingtalk_sdk.config import resolve_dws_bin
from webhost.backend.plugins.base import ScenePlugin, PLUGINS
from . import config
from .data import hr_api, org_tree
from .data.hr_api import HRSessionExpiredError
from .logic import attendance_rules as rules
from .report import attendance_report
from .report import dingtalk_push
def detect_dws(path_hint: str = "") -> str:
"""检测 dws 是否可用,返回可执行路径(未安装返回空串)。
顺序:字段 dws_path > 环境变量 DINGTALK_DWS_BIN > 用户目录默认位置 > PATH。
"""
hint = str(path_hint or "").strip()
if hint and os.path.isdir(hint):
hint = os.path.join(hint, "dws.exe")
try:
return resolve_dws_bin(hint)
except Exception: # noqa: BLE001 - 检测失败按未安装
return ""
def _as_bool(value, default=False):
"""字段值转布尔(兼容 JSON 布尔与 "true"/"false" 字符串)。"""
if value is None or value == "":
return default
if isinstance(value, bool):
return value
return str(value).strip().lower() in ("1", "true", "yes", "on")
def _parse_scope_paths(value):
"""组织架构勾选结果 → 组织全路径列表(兼容 JSON 数组字符串 / 数组 / 换行文本)。"""
if isinstance(value, (list, tuple)):
return [str(v).strip() for v in value if str(v or "").strip()]
raw = str(value or "").strip()
if not raw:
return []
try:
data = json.loads(raw)
except ValueError:
data = None
if isinstance(data, list):
return [str(v).strip() for v in data if str(v or "").strip()]
return [s.strip() for s in raw.splitlines() if s.strip()]
class WeeklyAttendanceAbnormalPlugin(ScenePlugin):
"""EHR系统周考勤异常处理(需求 XQ0006)。"""
id = "xq0006"
name = "EHR系统周考勤异常处理"
version = "1.4.1"
description = ("拉取查询月份未调整考勤异常并导出 Excel,整月轻微异常自动确认;"
"上周「组织架构所选范围(含下级)」的严重异常按人合并推送,"
"组织架构支持一键同步最新并固化为 JSON;"
"优先用 dws 单聊+群(附 Excel),未装 dws 时当事人回退工作通知、群汇总不发送;"
"支持试算模式(只出表、不确认不推送)。")
platform = "hr"
uses_month = True
capabilities = ["xq0006"]
permissions = {"platforms": ["hr"]}
fields = {
"ref_month": {
"type": "string", "title": "执行月份",
"default": "",
"description": "留空=本月(1 号查上月);格式 YYYY-MM(如 2026-11)",
},
"save_dir": {
"type": "string", "title": "输出目录",
"default": config.DEFAULT_SAVE_DIR,
"description": "考勤异常 Excel 底稿存放目录",
},
"dry_run": {
"type": "boolean", "title": "试算模式", "default": False,
"description": "开启后只导出 Excel 并统计,不自动确认、不发送任何钉钉消息",
},
"auto_confirm": {
"type": "boolean", "title": "自动确认", "default": True,
"description": "开启后对整月轻微异常(迟到/早退 < 30 分钟,不分职能序列)调用确认接口(分批提交);"
"严重异常只推送不确认;试算模式下强制不确认",
},
"push_enabled": {
"type": "boolean", "title": "钉钉推送", "default": True,
"description": "开启后推送上周组织架构所选范围的严重异常给当事人,并推送条数汇总到钉钉群;试算模式下强制不推送",
},
"push_scope_paths": {
"type": "string", "title": "推送范围(组织架构)", "default": "",
"description": "界面组织树勾选的节点(组织全路径 JSON 数组,含全部下级);未勾选=不推送当事人",
},
"dws_path": {
"type": "string", "title": "dws 路径", "default": "",
"description": "留空自动检测(DINGTALK_DWS_BIN / 用户目录 / PATH);dws 负责当事人单聊与群汇总(附 Excel),"
"检测不到时当事人回退工作通知、群汇总不发送",
},
"push_group": {
"type": "string", "title": "汇总群名", "default": "",
"description": "dws 推送时的群全称(按群名精确匹配),留空用默认;并附带 Excel 底稿",
},
"push_at_all": {
"type": "boolean", "title": "汇总群 @所有人", "default": False,
"description": "需群里有 @所有人 权限(仅 dws 通道生效)",
},
}
def run(self, fields: dict, ctx):
fields = fields or {}
# ---- 仅检测 dws(UI「检测」按钮:probe_dws=true,不取数、不推送) ----
if _as_bool(fields.get("probe_dws"), False):
path = detect_dws(str(fields.get("dws_path") or ""))
if path:
ctx.log(f"[INFO] dws 检测通过:{path}")
else:
ctx.log("[WARN] 未检测到 dws:执行时将回退工作通知 + 群机器人", "WARNING")
return {
"ok": True, "probe": True,
"dws_available": bool(path), "dws_path": path,
"summary": (f"dws 可用:{path}" if path
else "未检测到 dws(执行时回退工作通知 + 群机器人)"),
}
# ---- 同步组织架构(UI「同步组织架构」按钮:action=sync_org,只拉组织、不取考勤) ----
if str(fields.get("action") or "").strip() == "sync_org":
try:
return self._sync_org(ctx)
except HRSessionExpiredError as e:
ctx.log(f"HR 登录态已失效,请重新登录后再同步组织架构:{e}", "ERROR")
raise RuntimeError("HR 登录态已失效,请重新登录 HR 后再同步组织架构") from e
# ---- 读取已固化的组织架构(界面缓存丢失时回填,不访问 HR) ----
if str(fields.get("action") or "").strip() == "load_org":
payload = org_tree.load()
if not payload:
return {"ok": True, "org_tree": [], "count": 0,
"summary": "本机还没有固化的组织架构,请点「同步组织架构」"}
return {
"ok": True,
"org_tree": payload["tree"],
"count": payload.get("count", 0),
"fetched_at": payload.get("fetched_at", ""),
"summary": f"已读取本机组织架构({payload.get('count', 0)} 个节点)",
}
try:
return self._run(fields, ctx)
except HRSessionExpiredError as e:
ctx.log(f"HR 登录态已失效,请重新登录后再执行:{e}", "ERROR")
raise RuntimeError("HR 登录态已失效,请重新登录 HR 后再执行") from e
def _sync_org(self, ctx):
"""拉取 HR 组织维护台账 → 固化组织架构 JSON → 回传树供界面渲染。"""
config.set_log(ctx.log)
config.set_progress(ctx.progress)
config.set_session(ctx.get_session("hr"))
session = config.require_session()
ctx.progress(5)
user_id, _treecode = hr_api.validate_session(session)
config.set_user_id(user_id)
ctx.progress(15)
payload = org_tree.sync(
session,
on_progress=lambda page, total: ctx.progress(15 + int(75 * page / max(total, 1))))
ctx.progress(100)
summary = (f"组织架构同步完成:{payload['count']} 个组织节点,"
f"已固化到 {config.ORG_TREE_FILE}")
ctx.log(summary, "INFO")
return {
"ok": True,
"sync_org": True,
"summary": summary,
"detail": {
"count": payload["count"],
"fetched_at": payload["fetched_at"],
"path": config.ORG_TREE_FILE,
},
"org_tree": payload["tree"],
"fetched_at": payload["fetched_at"],
"count": payload["count"],
}
def _run(self, fields: dict, ctx):
# ---- 注入运行上下文 ----
config.set_log(ctx.log)
config.set_progress(ctx.progress)
config.set_session(ctx.get_session("hr"))
session = config.require_session()
save_dir = (fields.get("save_dir") or "").strip() or config.DEFAULT_SAVE_DIR
auto_confirm = _as_bool(fields.get("auto_confirm"), True)
push_enabled = _as_bool(fields.get("push_enabled"), True)
dry_run = _as_bool(fields.get("dry_run"), config.DEFAULT_DRY_RUN)
if dry_run: # 试算:只导出,不产生任何写入/外发动作
auto_confirm, push_enabled = False, False
scope_paths = _parse_scope_paths(fields.get("push_scope_paths"))
if push_enabled:
if scope_paths:
ctx.log(f"推送范围:组织架构勾选 {len(scope_paths)} 个节点(含全部下级)", "INFO")
else:
ctx.log("推送范围:未勾选任何组织节点,本次不推送当事人"
"(如需推送请用「选择组织范围」勾选)", "WARN")
dws_path = detect_dws(str(fields.get("dws_path") or ""))
if dws_path:
ctx.log(f"dws 检测通过:{dws_path}(单聊 + 群推送,附 Excel)", "INFO")
elif push_enabled:
ctx.log("未检测到 dws:当事人回退企业内部应用工作通知;群汇总含 Excel 附件,不发送;"
"需要群推送请把 dws.exe 加入 PATH 或填写「dws 路径」", "WARN")
push_group = (fields.get("push_group") or "").strip() or config.DEFAULT_PUSH_GROUP
push_at_all = _as_bool(fields.get("push_at_all"), False)
try:
month = rules.resolve_month(fields.get("ref_month"))
except ValueError as e:
raise RuntimeError(str(e)) from e
begin, end = rules.month_range(month)
ctx.log(f"===== 周考勤异常处理启动:{month} 整月({begin} ~ {end}),"
f"试算模式={'是(只导出)' if dry_run else '否'},"
f"自动确认={'开(整月轻微)' if auto_confirm else '关'},"
f"钉钉推送={'开' if push_enabled else '关'} =====", "INFO")
# ---- 步骤1:会话校验 ----
ctx.progress(5)
user_id, treecode = hr_api.validate_session(session)
config.set_user_id(user_id)
ctx.progress(8)
# ---- 步骤2:拉取整月考勤异常 ----
data = hr_api.fetch_all_attendance_abnormal(session, user_id, treecode, begin, end)
ctx.log(f"考勤异常共获取 {len(data)} 条(调整状态:{config.IS_ADJUSTED or '所有'})", "INFO")
if not data:
ctx.log(f"{month} 无考勤异常数据,跳过导出与推送", "INFO")
ctx.progress(100)
return {
"summary": f"{month} 无考勤异常数据,未导出、未确认、未推送",
"detail": {"total": 0},
"path": "",
"save_dir": save_dir,
}
ctx.progress(30)
# ---- 步骤3:导出 Excel 底稿 ----
path = attendance_report.export_excel(data, save_dir, month, dry_run=dry_run)
ctx.progress(35)
# ---- 步骤4:自动确认(整月轻微异常) ----
split = rules.split_data(data, scope_paths)
auto_items = [it for it in data
if it.get("abnormal_id") and rules.is_mild_abnormal(it)]
auto_count = len(auto_items)
confirmed_count, failed_ids = 0, []
if auto_confirm:
ctx.log(f"自动确认(整月轻微异常){auto_count} 条 …", "INFO")
_, confirmed_count, failed_ids = hr_api.auto_confirm_all(
session, auto_items,
on_progress=lambda done, total: ctx.progress(
35 + int(35 * done / max(total, 1))))
else:
if dry_run:
ctx.log(f"试算模式:仅统计待确认轻微异常 {auto_count} 条,未执行确认", "INFO")
else:
ctx.log(f"自动确认未启用,仅统计待确认轻微异常 {auto_count} 条,未执行确认", "WARN")
ctx.progress(72)
# ---- 步骤5:钉钉推送(只通知,不改口径) ----
messages = rules.group_messages(split["func_list"])
group_message = rules.build_group_summary(
len(data), auto_count, confirmed_count, len(split["non_func_list"]),
len(split["func_list"]), len(messages), len(split["other_list"]),
month, begin, end)
push_result = {"sent": 0, "failed": [], "group_sent": False, "note": ""}
push_channel = "none"
if push_enabled:
if dws_path:
# 首选 dws:当事人单聊 + 汇总群(附 Excel 底稿)
push_channel = "dws"
push_result = dingtalk_push.push_by_dws(
messages, group_message, push_group, file_path=path,
record_dir=os.path.join(save_dir, config.RECORD_SUBDIR),
at_all=push_at_all, dws_path=dws_path,
on_progress=lambda done, total: ctx.progress(
72 + int(15 * done / max(total, 1))))
else:
# 回退:仅当事人工作通知;群汇总需 dws 附件,跳过
push_channel = "worknotice"
if messages:
push_result = dingtalk_push.push_person_messages(
messages,
on_progress=lambda done, total: ctx.progress(
72 + int(15 * done / max(total, 1))))
else:
ctx.log("无需推送的异常,跳过当事人钉钉通知", "INFO")
ctx.log("未检测到 dws:群汇总(含 Excel 附件)未发送", "WARN")
else:
if dry_run:
ctx.log("试算模式:未发送任何钉钉消息", "INFO")
else:
ctx.log("钉钉推送未启用,未发送任何钉钉消息", "INFO")
ctx.progress(90)
# ---- 步骤6:汇总日志 ----
ctx.log("=" * 60, "INFO")
ctx.log(group_message, "INFO")
ctx.log(f"导出文件:{path}", "INFO")
if failed_ids:
ctx.log(f"自动确认失败 {len(failed_ids)} 条:{','.join(str(i) for i in failed_ids[:20])}", "WARN")
if push_result["failed"]:
ctx.log(f"当事人推送失败 {len(push_result['failed'])} 人:"
f"{';'.join(push_result['failed'][:10])}", "WARN")
ctx.log("=" * 60, "INFO")
counts = {
"total": len(data),
"auto_confirm_total": auto_count,
"confirmed": confirmed_count,
"confirm_failed": len(failed_ids),
"func_lastweek": len(split["func_list"]),
"non_func_lastweek": len(split["non_func_list"]),
"other": len(split["other_list"]),
"push_people": len(messages),
"push_sent": push_result["sent"],
"push_failed": len(push_result["failed"]),
"push_channel": push_channel,
"group_pushed": bool(push_result.get("group_sent")),
}
summary = f"{month} 周考勤异常处理完成:共 {counts['total']} 条"
if dry_run:
summary += ",试算模式(仅导出,未确认、未推送)"
elif auto_confirm:
summary += f",自动确认 {confirmed_count}/{auto_count} 条"
else:
summary += ",自动确认已关闭"
if push_enabled:
summary += f",推送 {counts['push_people']} 人(成功 {counts['push_sent']})"
summary += f";导出:{path}"
ctx.progress(100)
return {"summary": summary, "detail": counts, "path": path, "save_dir": save_dir}
PLUGINS.append(WeeklyAttendanceAbnormalPlugin())