Files
37duAutomation/plugins/XQ0001-0100/XQ0001 排班异常识别/__init__.py
T
puddy 4941e8b6c0 feat(plugin): 新增 XQ0006 周考勤异常处理、XQ0083 调动流程生效确认;其余插件累积改动
XQ0001 排班异常识别 / XQ0002 雇主险增减操作 / XQ0012 ERP 付款申请 / XQ0013 社保费用申报 / XQ0042 抖音平台核对 / XQ0084 银行卡更新:逻辑与界面 bundle 更新(含各自版本号变更)
2026-11-18 18:55:59 +08:00

318 lines
14 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 -*-
"""XQ0001 排班异常识别(插件版)。
流程:
1) 预检:dws 是否可用、HR 登录态是否可用、输出目录是否可写;
2) 取数:按需用 SDK 现导「员工花名册(在职)」「调动台账」「预入职台账」;
3) 判定:近 N 天新入职/调入人员的当日排班是否属于应有门店(口径见 README);
4) 核查:考勤平台 BioData 生物识别登记(本插件自带,不进 SDK);
5) 留档:排班异常名单 xlsx(含店长/处理人、推送状态、生物识别);
6) 推送:店长单聊 + 汇总群(`dingtalk_sdk.dws`),未装 dws 则跳过推送只出名单。
运行上下文:``platform = "hr"``(壳子按账号自动补登),不使用执行月份。
"""
from __future__ import annotations
import os
from datetime import date
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
from dingtalk_sdk import Dws
from dingtalk_sdk.config import resolve_dws_bin
from hr_sdk import HrClient
from hr_sdk import ledger as hr_ledger
from hr_sdk import roster as hr_roster
from hr_sdk import seal as hr_seal
from hr_sdk.errors import SessionExpiredError
from . import config
from .data import biometrics
from .logic import manager as manager_mod
from .logic import messages as messages_mod
from .logic import rules
from .report.excel import export_list
LOGIN_HINT = "HR 登录态失效,请先在壳子右上角重新登录 HR 后重试"
def detect_dws(path_hint: str = "") -> str:
"""检测 dws 是否可用,返回可执行路径(未安装返回空串)。
顺序:字段 dws_path > 环境变量 DINGTALK_DWS_BIN > 用户目录默认位置 > PATH。
"""
try:
return resolve_dws_bin(path_hint or "")
except Exception: # noqa: BLE001 - 检测失败按未安装
return ""
class ShiftAbnormalPlugin(ScenePlugin):
"""排班异常识别(需求 XQ0001)。"""
id = "xq0001"
name = "排班异常识别"
version = "1.0.3"
description = ("核查近 N 天新入职/调入人员的当日排班是否属于应有门店,输出异常名单并按店长"
"单聊 + 汇总群推送(依赖 hr_sdk / dingtalk_sdk;未装 dws 时只出名单不推送)。")
platform = "hr"
uses_month = False
capabilities = ["xq0001"]
permissions = {"platforms": ["hr"]}
fields = {
"save_dir": {
"type": "string", "title": "输出目录",
"default": config.DEFAULT_SAVE_DIR,
"description": "名单、台账、推送记录都写在这里(台账/推送记录各自子目录)",
},
"days": {
"type": "int", "title": "核查窗口(天)", "default": config.DAYS_DEFAULT,
"description": "近 N 天(含当天)内新入职/调动的人员",
},
"roster_cache": {
"type": "boolean", "title": "花名册 30 分钟内复用", "default": True,
"description": "开启后同一份在职花名册 30 分钟内直接复用;关闭则每次重新导出",
},
"push": {
"type": "boolean", "title": "推送钉钉", "default": True,
"description": "关闭则只出名单;本机未安装 dws 时会自动跳过推送并提示",
},
"push_group": {
"type": "string", "title": "汇总群名", "default": config.DEFAULT_PUSH_GROUP,
"description": "群全称(按群名精确匹配),留空用默认",
},
"push_at_all": {
"type": "boolean", "title": "汇总群 @所有人", "default": False,
"description": "需群里有 @所有人 权限",
},
"default_manager": {
"type": "string", "title": "默认处理人",
"default": "",
"description": "解析不到店长的异常归入此人(工号或姓名;多个用英文逗号分隔,轮流分配);留空则只留档不推送",
},
"check_biometrics": {
"type": "boolean", "title": "核查生物识别登记", "default": True,
"description": "调考勤平台 BioData 核查是否已录指纹/人脸;平台异常时自动降级跳过",
},
"bio_username": {
"type": "string", "title": "考勤平台账号", "default": "",
"description": "留空用内置默认;也可用 attendance_login_username 环境变量",
},
"bio_password": {
"type": "string", "format": "password", "title": "考勤平台密码", "default": "",
"description": "留空用内置默认;也可用 attendance_login_password 环境变量",
},
"dws_path": {
"type": "string", "title": "dws 路径", "default": "",
"description": "留空自动检测(DINGTALK_DWS_BIN / 用户目录 / PATH);检测不到会跳过推送",
},
}
# ---------------- 入口 ----------------
def run(self, fields: dict, ctx) -> dict: # noqa: C901 - 流程线性,分支都是必要预检
fields = fields or {}
def log(msg: str, level: str = "INFO") -> None:
ctx.log(msg, level)
# ---- 0. 仅检测 dws(UI「检测」按钮:probe_dws=true,不取数、不推送) ----
if bool(fields.get("probe_dws", False)):
path = detect_dws(str(fields.get("dws_path") or ""))
if path:
log(f"[INFO] dws 检测通过:{path}")
else:
log("[WARN] 未检测到 dws:执行时将只出名单、不推送", "WARNING")
return {
"ok": True, "probe": True,
"dws_available": bool(path), "dws_path": path,
"summary": (f"dws 可用:{path}" if path
else "未检测到 dws(执行时只出名单、不推送)"),
}
save_dir = config.save_dir(fields)
os.makedirs(save_dir, exist_ok=True)
# ---- 1. 预检:dws ----
dws_path = detect_dws(str(fields.get("dws_path") or ""))
if dws_path:
log(f"[INFO] dws 检测通过:{dws_path}")
else:
log("[WARN] 未检测到 dws(钉钉命令行),本次只出名单、不推送;"
"需要推送请把 dws.exe 加入 PATH 或填写「dws 路径」字段", "WARNING")
ctx.progress(5)
# ---- 2. 会话与客户端 ----
try:
session = ctx.get_session("hr")
except Exception as exc: # noqa: BLE001
raise RuntimeError(f"未获取到 HR 登录态:{exc};请先在壳子登录 HR") from exc
def hr_log(msg: str) -> None:
level = ("WARNING" if "[WARN]" in msg
else "ERROR" if "[ERROR]" in msg else "INFO")
log(msg, level)
client = HrClient(session, log=hr_log)
try:
return self._run(client, fields, save_dir, dws_path, log, ctx)
except SessionExpiredError as exc:
raise RuntimeError(f"{LOGIN_HINT}({exc})") from exc
# ---------------- 主体 ----------------
def _run(self, client, fields: dict, save_dir: str, dws_path: str,
log, ctx) -> dict:
days = config.days(fields)
ledger_dir = os.path.join(save_dir, config.LEDGER_SUBDIR)
os.makedirs(ledger_dir, exist_ok=True)
# ---- 3. 取数:台账与花名册一律现导到「输出目录/台账/」 ----
roster_path = os.path.join(ledger_dir, config.ROSTER_FILENAME)
roster_ttl = config.ROSTER_TTL_CACHE if bool(fields.get("roster_cache", True)) else 0
log("[INFO] 导出员工花名册(在职)…")
roster_path = hr_roster.export(
client, statuses=["在职"], output=roster_path, ttl=roster_ttl)
ctx.progress(30)
transfer_path = os.path.join(ledger_dir, config.TRANSFER_FILENAME)
log("[INFO] 导出调动台账…")
transfer_path = hr_ledger.export_transfer(client, output=transfer_path)
preentry_path = os.path.join(ledger_dir, config.PREENTRY_FILENAME)
log("[INFO] 导出预入职台账…")
preentry_path = hr_ledger.export_pre_entry(client, output=preentry_path)
ctx.progress(45)
# ---- 4. 判定 ----
user_id = str(hr_seal.current_user(client).get("userId") or "").strip()
if not user_id:
raise RuntimeError("未取到 HR userId,无法查询排班")
roster_df = manager_mod.read_roster(roster_path, log)
roster_codes = {rules.to_text(c) for c in roster_df[config.COL_CODE]}
fetcher = rules.ShiftFetcher(client, user_id, log)
dept_fetcher = rules.DeptShiftFetcher(client, log)
end = date.today()
begin, end_window = rules.recent_window(end, days)
rows = rules.collect_rows(transfer_path, rules.check_transfer_row,
fetcher, dept_fetcher, end, days, log)
rows += rules.collect_rows(preentry_path, rules.check_preentry_row,
fetcher, dept_fetcher, end, days, log)
ctx.progress(65)
# 离职过滤:花名册查不到工号 → 按离职剔除(调动/入职都生效)
if rows:
resigned = [r for r in rows if rules.to_text(r.get("工号")) not in roster_codes]
if resigned:
names = [f"{r.get('姓名')}/{r.get('工号')}" for r in resigned]
log(f"[WARN] 花名册查不到工号,按离职剔除 {len(resigned)} 人:{names}",
"WARNING")
rows = [r for r in rows if rules.to_text(r.get("工号")) in roster_codes]
# 后勤组织过滤:花名册「一级部门」含「后勤」的(如后勤(C))不纳入异常
if rows:
dept1_by_code = manager_mod.dept1_map(roster_df)
if not dept1_by_code:
log(f"[WARN] 花名册缺少「{config.COL_DEPT1}」列,后勤组织剔除未生效",
"WARNING")
else:
excluded = [r for r in rows
if manager_mod.dept1_excluded(
dept1_by_code.get(rules.to_text(r.get("工号")), ""))]
if excluded:
names = [f"{r.get('姓名')}/{r.get('工号')}" for r in excluded]
log(f"[WARN] 一级部门含后勤,剔除 {len(excluded)} 人:{names}",
"WARNING")
rows = [r for r in rows if r not in excluded]
# 预入职台账无四级部门列 → 按工号回填
for row in rows:
if row.get("类别") == "入职" and not rules.clean(row.get("现四级部门")):
row["现四级部门"] = manager_mod.lookup_dept4_by_code(roster_df,
row.get("工号"))
summary = {
"ok": True, "total": len(rows), "messages": 0, "pushed": False,
"dws_available": bool(dws_path), "dws_path": dws_path,
"save_dir": save_dir, "list_path": "", "roster_path": roster_path,
"transfer_path": transfer_path, "preentry_path": preentry_path,
"group": config.push_group(fields), "note": "",
}
if not rows:
log("[INFO] 未识别到排班异常,无需推送")
summary["note"] = "无异常"
summary["summary"] = "未识别到排班异常"
ctx.progress(100)
return summary
# ---- 5. 生物识别核查(降级不阻断) ----
if bool(fields.get("check_biometrics", True)):
biometrics.annotate(rows,
str(fields.get("bio_username") or ""),
str(fields.get("bio_password") or ""), log)
ctx.progress(75)
rows.sort(key=lambda x: (x.get("类别", ""), x.get("姓名", ""), x.get("工号", "")))
for index, item in enumerate(rows, 1):
item["序号"] = index
# ---- 6. 消息构造 → 留档(先构造,才能把「店长/处理人」「推送状态」写进名单) ----
chat_messages = messages_mod.build_messages(
rows, roster_df, config.default_manager(fields), log)
list_path = export_list(rows, save_dir, log)
summary["list_path"] = list_path
group_message = messages_mod.build_group_message(
list_path, begin, end_window, config.push_group(fields),
bool(fields.get("push_at_all", False)), log)
payload = list(chat_messages) + ([group_message] if group_message else [])
summary["messages"] = len(payload)
ctx.progress(85)
# ---- 7. 推送 ----
if not bool(fields.get("push", True)):
summary["note"] = "已关闭推送(只出名单)"
log("[INFO] 推送开关关闭,只出名单")
elif not dws_path:
summary["note"] = "未安装 dws,已跳过推送"
log("[WARN] 未安装 dws,跳过推送(名单已留档)", "WARNING")
else:
summary.update(self._push(payload, dws_path, save_dir, log))
summary["summary"] = (
f"异常 {summary['total']} 人 · 消息 {summary['messages']} 条 · "
f"{'已推送' if summary.get('pushed') else (summary.get('note') or '未推送')}")
ctx.progress(100)
return summary
# ---------------- 工具 ----------------
@staticmethod
def _push(payload, dws_path: str, save_dir: str, log) -> dict:
"""执行推送(单聊 + 汇总群),返回摘要字段。"""
record_dir = os.path.join(save_dir, config.RECORD_SUBDIR)
def dws_log(msg: str) -> None:
level = "WARNING" if "[WARN]" in msg else "INFO"
log(msg, level)
try:
client = Dws(bin=dws_path, record_dir=record_dir, log=dws_log)
result = client.push(payload)
except Exception as exc: # noqa: BLE001 - 推送失败不影响名单
log(f"[WARN] 推送失败:{exc}(名单已留档)", "WARNING")
return {"pushed": False, "note": f"推送失败:{exc}"}
ok = bool(result.get("success"))
message = str(result.get("message") or "")
if not ok:
failed = [r for r in (result.get("results") or []) if not r.get("success")]
detail = ";".join(str(r.get("message") or "")[:80] for r in failed[:3])
log(f"[WARN] 部分推送失败:{message}({detail})", "WARNING")
else:
log(f"[INFO] 推送完成:{message}")
return {"pushed": ok, "note": message}
PLUGINS.append(ShiftAbnormalPlugin())