restore: 恢复 11-06~11-09 本地未提交改动

- libs: 新增 hr_sdk / hotel_report / dingtalk,更新 desktopauto
- controlplane-next: SDK 管理模块(controller/entity/migrations)与前端视图
- electron-shell: 插件同步、注册表、runner 调整
- plugins: XQ0035/XQ0041/XQ0042/XQ0045_XQ0046/XQ0048/XQ0076/XQ0078 等版本更新
- tests/tools: 新增 SDK 兼容性检查与打包工具(sdk_pack.py、sdk_compat_check.py)
This commit is contained in:
2026-11-09 17:27:10 +08:00
parent e4539db9f8
commit 9873eb1963
327 changed files with 29670 additions and 718 deletions
@@ -0,0 +1,261 @@
# -*- coding: utf-8 -*-
"""排班异常判定:台账读取、排班查询(带缓存)、逐行口径。
口径来源见 README「判定规则」;本模块只做判定,不发消息、不写文件。
排班接口由 ``hr_sdk.shift`` 提供,本插件不拼 URL。
"""
from __future__ import annotations
import os
import time
from datetime import date, datetime, timedelta
from typing import Dict, List, Optional, Tuple
import pandas as pd
from hr_sdk import shift
from .. import config
# ==================== 文本清洗 / 日期 ====================
def clean(value) -> str:
"""转字符串并去掉杂质:None、浮点 .0 尾缀、pandas 空占位(nan/nat)。"""
if value is None:
return ""
text = str(value).strip()
if text.lower() in ("nan", "none", "nat"):
return ""
if text.endswith(".0"):
text = text[:-2]
return text
def to_text(value) -> str:
"""工号等主键统一转文本(浮点/整型转 str),避免文本/数字混存匹配失败。"""
if value is None:
return ""
try:
if pd.isna(value):
return ""
except (TypeError, ValueError):
pass
return clean(value)
def shift_name(value) -> str:
"""归一化排班名:去掉 ``YYYY-MM-DD_`` 前缀,便于与接口 ``work_date_name`` 比对。"""
text = clean(value)
if len(text) > 11 and text[4] == "-" and text[7] == "-" and text[10] == "_":
return text[11:]
return text
def date_part(value) -> str:
return clean(value)[:10]
def parse_date(value) -> Optional[date]:
text = date_part(value)
if not text:
return None
try:
return datetime.strptime(text, "%Y-%m-%d").date()
except (TypeError, ValueError):
return None
def recent_window(end: Optional[date] = None, days: int = config.DAYS_DEFAULT
) -> Tuple[date, date]:
"""近 N 天闭区间(含当天)。"""
end = end or date.today()
return end - timedelta(days=max(1, days) - 1), end
# ==================== 台账 ====================
def load_ledger(path: str, log=print) -> pd.DataFrame:
"""读台账(表头在第 2 行)。"""
if not os.path.exists(path):
raise RuntimeError(f"未找到台账文件:{path}(请先用 SDK 导出或指定路径)")
frame = pd.read_excel(path, header=1, dtype=str)
frame.columns = [str(c).strip() for c in frame.columns]
log(f"[INFO] 已读取台账:{os.path.basename(path)}({len(frame)} 行)")
return frame
# ==================== 排班查询器 ====================
class ShiftFetcher:
"""按 (工号, 日期) 缓存当日完整排班名(接口调用带限速与定期登录态校验)。"""
def __init__(self, client, user_id: str, log=print):
self.client = client
self.user_id = user_id
self.log = log
self.cache: Dict[Tuple[str, date], str] = {}
self.calls = 0
def fetch(self, code: str, day: date) -> str:
key = (code, day)
if key not in self.cache:
self.calls += 1
if self.calls % config.SESSION_REVALIDATE_EVERY == 1:
self._refresh_user_id()
self.cache[key] = self._query(code, day)
time.sleep(0.2)
return self.cache[key]
def _refresh_user_id(self) -> None:
from hr_sdk import seal
try:
uid = str(seal.current_user(self.client).get("userId") or "").strip()
if uid:
self.user_id = uid
except Exception as exc: # noqa: BLE001 - 校验失败按原会话继续
self.log(f"[WARN] 登录态校验失败(沿用原会话):{exc}")
def _query(self, code: str, day: date) -> str:
day_str = day.strftime("%Y-%m-%d")
rows = shift.person(self.client, self.user_id, code, day_str, day_str)
return shift.day_shift(rows, day_str)
class DeptShiftFetcher:
"""按部门名缓存该部门的排班名集合(一个部门可能有技师/服务/管理多个排班)。"""
def __init__(self, client, log=print):
self.client = client
self.log = log
self.cache: Dict[str, set] = {}
self.calls = 0
def fetch(self, dept_name: str) -> set:
name = clean(dept_name)
if not name:
return set()
if name not in self.cache:
self.calls += 1
self.cache[name] = {shift_name(n)
for n in shift.department_names(self.client, name)}
time.sleep(0.2)
return self.cache[name]
def shift_belongs(dept_fetcher: DeptShiftFetcher, dept_name: str, shift_text: str) -> bool:
"""排班是否属于该部门:优先按部门排班集合判断,接口查不到时兜底「排班名包含部门名」。"""
name = clean(dept_name)
normalized = shift_name(shift_text)
if not name or not normalized:
return False
dept_shifts = dept_fetcher.fetch(name)
if dept_shifts:
return normalized in dept_shifts
return name in str(shift_text)
# ==================== 逐行判定 ====================
def seq_excluded(seq: str) -> bool:
"""现职位序列命中剔除序列 → True(不纳入异常)。"""
text = clean(seq)
return any(keyword in text for keyword in config.EXCLUDE_SEQ_KEYWORDS)
def check_transfer_row(fetcher: ShiftFetcher, dept_fetcher: DeptShiftFetcher,
row, begin: date, end: date) -> Optional[dict]:
"""调动台账单行判定:正常返回 None,异常返回名单行。"""
code = clean(row.get("工号"))
day = parse_date(row.get("调动时间"))
if not code or not day or not (begin <= day <= end):
return None
seq = clean(row.get("现职位序列"))
if seq_excluded(seq):
return None
if any(kw in seq for kw in config.FUNC_SEQ_UNIT_UNCHANGED_KEYWORDS):
old_unit, new_unit = clean(row.get("原单位")), clean(row.get("现单位"))
if old_unit and new_unit and old_unit == new_unit:
return None
if "职能" in seq:
target_field, target_name = "现单位", clean(row.get("现单位"))
else:
target_field, target_name = "现四级部门", clean(row.get("现四级部门"))
shift_text = fetcher.fetch(code, day)
if not shift_text:
reason, present = "调动时间无排班", ""
elif target_name and not shift_belongs(dept_fetcher, target_name, shift_text):
reason, present = f"排班未更新为{target_field}({target_name})", shift_text
else:
return None
return {
"序号": 0,
"姓名": clean(row.get("姓名")),
"工号": code,
"类别": "调动",
"原单位": clean(row.get("原单位")),
"原上级部门": clean(row.get("原上级部门")),
"现单位": clean(row.get("现单位")),
"现职位序列": seq,
"现上级部门": clean(row.get("现上级部门")),
"现四级部门": clean(row.get("现四级部门")),
"调动/入职时间": day.strftime("%Y-%m-%d"),
"操作时间": date_part(row.get("操作时间")),
"当日排班": present,
"异常原因": reason,
}
def check_preentry_row(fetcher: ShiftFetcher, dept_fetcher: DeptShiftFetcher,
row, begin: date, end: date) -> Optional[dict]:
"""预入职台账单行判定:预入职日期当天有排班即正常。"""
code = clean(row.get("工号"))
op_day = parse_date(row.get("操作时间")) # 筛选字段
if not code or not op_day or not (begin <= op_day <= end):
return None
if seq_excluded(row.get("职位序列")):
return None
pj_day = parse_date(row.get("预入职日期")) # 排班检查日期
if not pj_day:
return None
if fetcher.fetch(code, pj_day):
return None
return {
"序号": 0,
"姓名": clean(row.get("姓名")),
"工号": code,
"类别": "入职",
"原单位": "",
"原上级部门": "",
"现单位": clean(row.get("入职单位")),
"现职位序列": clean(row.get("职位序列")),
"现上级部门": "",
"现四级部门": "",
"调动/入职时间": pj_day.strftime("%Y-%m-%d"),
"操作时间": op_day.strftime("%Y-%m-%d"),
"当日排班": "",
"异常原因": "预入职日期无排班",
}
def collect_rows(ledger_path: str, check_row, fetcher: ShiftFetcher,
dept_fetcher: DeptShiftFetcher, end: date, days: int,
log=print) -> List[dict]:
"""读台账 → 逐行判定 → 异常行列表。"""
frame = load_ledger(ledger_path, log)
begin, end_date = recent_window(end, days)
log(f"[INFO] 筛选范围:{begin} ~ {end_date}(近 {days} 天)")
rows = []
for _, raw in frame.iterrows():
row = check_row(fetcher, dept_fetcher, raw, begin, end_date)
if row:
rows.append(row)
log(f"[INFO] {os.path.basename(ledger_path)} 排班异常 {len(rows)} 人")
return rows