rescue: 断电事故后工作区全量备份
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.shift_abnormal
|
||||
@FileName: __init__.py
|
||||
@Description: 排班异常识别模块包。
|
||||
包含预入职台账导出等子模块,供排班异常识别业务场景复用。
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.shift_abnormal
|
||||
@FileName: __init__.py
|
||||
@Description: 排班异常识别模块包。
|
||||
包含预入职台账导出等子模块,供排班异常识别业务场景复用。
|
||||
"""
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,411 +1,411 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.shift_abnormal
|
||||
@FileName: shift_abnormal_check.py
|
||||
@Author: 小布丁
|
||||
@Description: 排班异常识别(第三步):读取第二步导出的「调动台账 / 预入职台账」(表头在第 2 行),
|
||||
结合 HR 排班接口判断每人的排班是否异常,导出异常名单 Excel。
|
||||
判断口径:
|
||||
- 调动台账:按「调动时间」筛选近 9 天,对每人查询当日完整排班名
|
||||
({日期}_team_name,形如「印象-{上级部门}-技师岗」)。当「现职位序列」含「职能」
|
||||
时按「现单位」比对,其余按「现四级部门」比对;用 rf_s_kq_work_date_query
|
||||
接口按比对部门查出该部门全部排班集合,当日排班属于该集合才视为正常
|
||||
(接口查不到集合时兜底原「完整排班名包含部门名」判断),否则为排班异常
|
||||
(无排班 / 排班未更新);
|
||||
- 预入职台账:按「操作时间」筛选近 9 天,对每人查询「预入职日期」当日完整排班名,
|
||||
当日有完整排班信息即为正常,无排班信息则为排班异常。有排班信息即可,不校验部门。
|
||||
不纳入异常:现职位序列命中 经营系管理序列 / 职能系专业序列 / 门店技师序列 的剔除(调动+预入职均生效)。
|
||||
底层能力复用:hr_session(会话管理)、hr_api.shift(排班查询)、roster 导出。
|
||||
@Version: 1.0.0
|
||||
|
||||
说明:
|
||||
1. 输入为第二步导出的《调动台账.xlsx》《预入职台账.xlsx》,两表表头均在第 2 行(pandas header=1)。
|
||||
2. 完整排班名取 {日期}_team_name(含上级部门),而非 {日期}_bc_name(仅班次名,如「技师中班C」)。
|
||||
3. 首次运行会自动完成 HR 登录并缓存 cookies,登录态过期自动重登。
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from datetime import date, datetime, timedelta
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in __import__("pathlib").Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(__import__("pathlib").Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
from app.service.hrbp.common.hr_session import build_hr_session # noqa: E402
|
||||
from app.service.hrbp.ehr.common.hr_api import fetch_cur_user_info # noqa: E402
|
||||
from app.service.hrbp.ehr.common.hr_api.shift import fetch_all_shift, fetch_all_work_date # noqa: E402
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
pd = None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ===================== 配置区(可自行修改) =====================
|
||||
# 默认输出目录(与第二步导出目录一致)
|
||||
SAVE_DIR = r"D:\资料\人资\排班异常识别"
|
||||
|
||||
# 第二步导出的台账文件名(表头在第 2 行)
|
||||
TRANSFER_FILE = os.path.join(SAVE_DIR, "调动台账.xlsx")
|
||||
PREENTRY_FILE = os.path.join(SAVE_DIR, "预入职台账.xlsx")
|
||||
|
||||
# 筛选窗口:近 N 天(含当天)
|
||||
DAYS = 9
|
||||
|
||||
# 每个员工是否重新校验会话(按人数控制频率,避免登录态过期后逐人触发重登)
|
||||
SESSION_REVALIDATE_EVERY = 30
|
||||
|
||||
# 名单输出列(调动台账 + 预入职台账合并为一张表,类别区分 调动/入职)
|
||||
COLUMNS: List[str] = [
|
||||
"序号", "姓名", "工号", "类别", "原单位", "原上级部门", "现单位", "现职位序列",
|
||||
"现上级部门", "现四级部门", "调动/入职时间", "操作时间", "当日排班", "异常原因",
|
||||
]
|
||||
|
||||
# 现职位序列命中以下序列的不纳入异常(不统计、不导出)
|
||||
EXCLUDE_SEQ_KEYWORDS = ("经营系管理序列", "职能系专业序列", "门店技师序列")
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 1. 通用工具
|
||||
# ----------------------------------------------
|
||||
def _clean(v) -> str:
|
||||
"""转字符串并去掉常见杂质:None、浮点 .0 尾缀、pandas 空占位(nan/native等)。"""
|
||||
if v is None:
|
||||
return ""
|
||||
s = str(v).strip()
|
||||
if s.lower() in ("nan", "none", "nat"):
|
||||
return ""
|
||||
if s.endswith(".0"):
|
||||
s = s[:-2]
|
||||
return s
|
||||
|
||||
|
||||
def _date_part(v) -> str:
|
||||
"""取日期字符串前 10 位(兼容 "YYYY-MM-DD HH:MM:SS")。"""
|
||||
return _clean(v)[:10]
|
||||
|
||||
|
||||
def _seq_excluded(seq: str) -> bool:
|
||||
"""现职位序列命中剔除序列(经营系管理序列/职能系专业序列/门店技师序列)返回 True。"""
|
||||
seq = _clean(seq)
|
||||
return any(kw in seq for kw in EXCLUDE_SEQ_KEYWORDS)
|
||||
|
||||
|
||||
def _shift_name(s: str) -> str:
|
||||
"""归一化排班名:兼容 {日期}_team_name 可能带 "YYYY-MM-DD_" 前缀,去掉前缀便于与接口 work_date_name 比对。"""
|
||||
s = _clean(s)
|
||||
if len(s) > 11 and s[4] == "-" and s[7] == "-" and s[10] == "_":
|
||||
return s[11:]
|
||||
return s
|
||||
|
||||
|
||||
def _parse_date(v) -> Optional[date]:
|
||||
"""解析日期字符串为 date,失败返回 None。"""
|
||||
s = _date_part(v)
|
||||
if not s:
|
||||
return None
|
||||
try:
|
||||
return datetime.strptime(s, "%Y-%m-%d").date()
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _recent_window(end: date = None, days: int = DAYS) -> Tuple[date, date]:
|
||||
"""返回近 N 天的 (开始日期, 结束日期),含当天。"""
|
||||
end = end or date.today()
|
||||
begin = end - timedelta(days=days - 1)
|
||||
return begin, end
|
||||
|
||||
|
||||
def _load_ledger(path: str) -> "pd.DataFrame":
|
||||
"""读取第二步导出的台账,表头在第 2 行(header=1)。"""
|
||||
if not os.path.exists(path):
|
||||
raise RuntimeError(
|
||||
f"未找到台账文件:{path}\n请先运行第二步导出(调动台账 / 预入职台账)后再执行本模块。"
|
||||
)
|
||||
df = pd.read_excel(path, header=1, dtype=str)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
logger.info("已读取台账:%s,共 %d 行", path, len(df))
|
||||
return df
|
||||
|
||||
|
||||
def _validate_session(session):
|
||||
"""校验 cookies 有效性,返回 (session, user_id);过期则重新登录并重建会话。"""
|
||||
session, user_id = _ensure_user_id(session, None)
|
||||
return session, user_id
|
||||
|
||||
|
||||
def _ensure_user_id(session, user_id: Optional[str]) -> Tuple[object, str]:
|
||||
"""获取有效 user_id 与会话。传入 None 时实时取;已有则直接复用。"""
|
||||
if user_id:
|
||||
return session, user_id
|
||||
info = fetch_cur_user_info(session)
|
||||
new_uid = _clean(info.get("userId"))
|
||||
if not new_uid:
|
||||
raise RuntimeError(f"员工基础信息接口未返回 userId:{info}")
|
||||
return session, new_uid
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 2. 按工号查询某日完整排班名({日期}_team_name)
|
||||
# ----------------------------------------------
|
||||
class _ShiftFetcher:
|
||||
"""带缓存的排班查询器:按 (工号, 日期) 缓存当日完整排班名,复用同一会话,定期校验登录态。"""
|
||||
|
||||
def __init__(self, session, user_id: str):
|
||||
self.session = session
|
||||
self.user_id = user_id
|
||||
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 % SESSION_REVALIDATE_EVERY == 1:
|
||||
self.session, uid = _ensure_user_id(self.session, None)
|
||||
self.user_id = uid
|
||||
val = self._query(code, day)
|
||||
self.cache[key] = val
|
||||
time.sleep(0.2)
|
||||
return self.cache[key]
|
||||
|
||||
def _query(self, code: str, day: date) -> str:
|
||||
day_str = day.strftime("%Y-%m-%d")
|
||||
rows = fetch_all_shift(self.session, self.user_id, code, day_str, day_str)
|
||||
for rec in rows:
|
||||
return _clean(rec.get(f"{day_str}_team_name"))
|
||||
return ""
|
||||
|
||||
|
||||
class _DeptShiftFetcher:
|
||||
"""按部门名缓存该部门的排班名集合(work_date_name),复用同一会话,定期校验登录态。
|
||||
|
||||
同一部门可能配置多个排班(技师岗/服务岗/管理岗…),通过 rf_s_kq_work_date_query
|
||||
接口按部门查出全部排班名,用于判断员工当日排班是否属于该部门。
|
||||
"""
|
||||
|
||||
def __init__(self, session):
|
||||
self.session = session
|
||||
self.cache: Dict[str, set] = {}
|
||||
self.calls = 0
|
||||
|
||||
def fetch(self, dept_name: str) -> set:
|
||||
"""返回某部门的排班名集合;部门名为空或查不到返回空集合。"""
|
||||
dept_name = _clean(dept_name)
|
||||
if not dept_name:
|
||||
return set()
|
||||
if dept_name not in self.cache:
|
||||
# 定期重新校验登录态,避免绑定过期会话
|
||||
self.calls += 1
|
||||
if self.calls % SESSION_REVALIDATE_EVERY == 1:
|
||||
self.session, _ = _ensure_user_id(self.session, None)
|
||||
self.cache[dept_name] = {_shift_name(n) for n in fetch_all_work_date(self.session, dept_name)}
|
||||
time.sleep(0.2)
|
||||
return self.cache[dept_name]
|
||||
|
||||
|
||||
def _shift_belongs(dept_fetcher: "_DeptShiftFetcher", dept_name: str, shift: str) -> bool:
|
||||
"""判断某排班是否属于某部门。
|
||||
|
||||
优先用新接口(rf_s_kq_work_date_query)按部门查出排班集合做成员判断;
|
||||
接口查不到集合(如「现单位」无直属排班)时兜底原「完整排班名包含部门名」判断。
|
||||
"""
|
||||
dept_name = _clean(dept_name)
|
||||
shift_norm = _shift_name(shift)
|
||||
if not dept_name or not shift_norm:
|
||||
return False
|
||||
dept_shifts = dept_fetcher.fetch(dept_name)
|
||||
if dept_shifts:
|
||||
return shift_norm in dept_shifts
|
||||
return dept_name in shift
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 3. 调动台账判定
|
||||
# ----------------------------------------------
|
||||
def _check_transfer_row(fetcher: "_ShiftFetcher", dept_fetcher: "_DeptShiftFetcher", r, begin: date, end: date):
|
||||
"""对单行调动记录判定,返回名单行 dict;属正常则返回 None。"""
|
||||
code = _clean(r.get("工号"))
|
||||
day = _parse_date(r.get("调动时间"))
|
||||
if not code or not day:
|
||||
return None
|
||||
if not (begin <= day <= end):
|
||||
return None
|
||||
|
||||
# 判断字段:现职位序列含「职能」按现单位判断,否则按现四级部门判断
|
||||
seq = _clean(r.get("现职位序列"))
|
||||
if _seq_excluded(seq):
|
||||
return None
|
||||
if "职能" in seq:
|
||||
target_field, target_name = "现单位", _clean(r.get("现单位"))
|
||||
else:
|
||||
target_field, target_name = "现四级部门", _clean(r.get("现四级部门"))
|
||||
|
||||
shift = fetcher.fetch(code, day) # 当日完整排班名(含上级部门),无排班为空串
|
||||
|
||||
if not shift:
|
||||
reason, present = "调动时间无排班", ""
|
||||
elif target_name and not _shift_belongs(dept_fetcher, target_name, shift):
|
||||
reason, present = f"排班未更新为{target_field}({target_name})", shift
|
||||
else:
|
||||
return None # 当日有排班且排班属于所需部门 → 正常
|
||||
|
||||
return {
|
||||
"序号": 0,
|
||||
"姓名": _clean(r.get("姓名")),
|
||||
"工号": code,
|
||||
"类别": "调动",
|
||||
"原单位": _clean(r.get("原单位")),
|
||||
"原上级部门": _clean(r.get("原上级部门")),
|
||||
"现单位": _clean(r.get("现单位")),
|
||||
"现职位序列": seq,
|
||||
"现上级部门": _clean(r.get("现上级部门")),
|
||||
"现四级部门": _clean(r.get("现四级部门")),
|
||||
"调动/入职时间": day.strftime("%Y-%m-%d"),
|
||||
"操作时间": _date_part(r.get("操作时间")),
|
||||
"当日排班": present,
|
||||
"异常原因": reason,
|
||||
}
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 4. 预入职台账判定
|
||||
# ----------------------------------------------
|
||||
def _check_preentry_row(fetcher: "_ShiftFetcher", dept_fetcher: "_DeptShiftFetcher", r, begin: date, end: date):
|
||||
"""对单行预入职记录判定,返回名单行 dict;有排班信息则返回 None。"""
|
||||
code = _clean(r.get("工号"))
|
||||
op_day = _parse_date(r.get("操作时间")) # 筛选字段:操作时间
|
||||
if not code or not op_day:
|
||||
return None
|
||||
if not (begin <= op_day <= end):
|
||||
return None
|
||||
if _seq_excluded(r.get("职位序列")):
|
||||
return None
|
||||
|
||||
# 排班检查日期:预入职日期(筛选按操作时间,查询排班按预入职日期)
|
||||
pj_day = _parse_date(r.get("预入职日期"))
|
||||
if not pj_day:
|
||||
return None
|
||||
|
||||
shift = fetcher.fetch(code, pj_day) # 当日完整排班名,无则空串
|
||||
if shift:
|
||||
return None # 有排班信息即可 → 正常
|
||||
|
||||
return {
|
||||
"序号": 0,
|
||||
"姓名": _clean(r.get("姓名")),
|
||||
"工号": code,
|
||||
"类别": "入职",
|
||||
"原单位": "",
|
||||
"原上级部门": "",
|
||||
"现单位": _clean(r.get("入职单位")),
|
||||
"现职位序列": _clean(r.get("职位序列")),
|
||||
"现上级部门": "",
|
||||
"现四级部门": "",
|
||||
"调动/入职时间": pj_day.strftime("%Y-%m-%d"),
|
||||
"操作时间": op_day.strftime("%Y-%m-%d"),
|
||||
"当日排班": "",
|
||||
"异常原因": "预入职日期无排班",
|
||||
}
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 5. 主流程
|
||||
# ----------------------------------------------
|
||||
def _collect_rows(ledger_path: str, check_row, fetcher: "_ShiftFetcher",
|
||||
dept_fetcher: "_DeptShiftFetcher", end: date) -> List[dict]:
|
||||
"""通用判定流程:读台账 → 逐行判定,返回异常行列表(未写文件)。"""
|
||||
df = _load_ledger(ledger_path)
|
||||
begin, end_date = _recent_window(end)
|
||||
logger.info("筛选范围:%s ~ %s(近 %d 天)", begin, end_date, DAYS)
|
||||
|
||||
rows: List[dict] = []
|
||||
for _, r in df.iterrows():
|
||||
row = check_row(fetcher, dept_fetcher, r, begin, end_date)
|
||||
if row:
|
||||
rows.append(row)
|
||||
logger.info("台账 %s 排班异常人数:%d", os.path.basename(ledger_path), len(rows))
|
||||
return rows
|
||||
|
||||
|
||||
def run_shift_abnormal_check(
|
||||
transfer_path: str = None,
|
||||
preentry_path: str = None,
|
||||
days: int = DAYS,
|
||||
) -> str:
|
||||
"""执行排班异常识别(调动台账 + 预入职台账),合并导出单张 Excel,返回文件路径。
|
||||
|
||||
Args:
|
||||
transfer_path: 调动台账 xlsx 路径,默认 TRANSFER_FILE
|
||||
preentry_path: 预入职台账 xlsx 路径,默认 PREENTRY_FILE
|
||||
days: 筛选近 N 天,默认 9
|
||||
"""
|
||||
global DAYS
|
||||
DAYS = days
|
||||
transfer_path = transfer_path or TRANSFER_FILE
|
||||
preentry_path = preentry_path or PREENTRY_FILE
|
||||
end = date.today()
|
||||
|
||||
session = build_hr_session()
|
||||
session, user_id = _validate_session(session)
|
||||
fetcher = _ShiftFetcher(session, user_id)
|
||||
dept_fetcher = _DeptShiftFetcher(session)
|
||||
|
||||
rows: List[dict] = []
|
||||
if os.path.exists(transfer_path):
|
||||
rows.extend(_collect_rows(transfer_path, _check_transfer_row, fetcher, dept_fetcher, end))
|
||||
else:
|
||||
logger.warning("跳过调动台账:文件不存在 %s", transfer_path)
|
||||
|
||||
if os.path.exists(preentry_path):
|
||||
rows.extend(_collect_rows(preentry_path, _check_preentry_row, fetcher, dept_fetcher, end))
|
||||
else:
|
||||
logger.warning("跳过预入职台账:文件不存在 %s", preentry_path)
|
||||
|
||||
if not rows:
|
||||
raise RuntimeError("未识别到排班异常,或台账文件均不存在(请先完成第二步导出)。")
|
||||
|
||||
# 合并排序并补序号
|
||||
rows.sort(key=lambda x: (x.get("类别", ""), x.get("姓名", ""), x.get("工号", "")))
|
||||
for idx, item in enumerate(rows, 1):
|
||||
item["序号"] = idx
|
||||
|
||||
os.makedirs(SAVE_DIR, exist_ok=True)
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
save_path = os.path.join(SAVE_DIR, f"排班异常名单_{ts}.xlsx")
|
||||
pd.DataFrame(rows, columns=COLUMNS).to_excel(save_path, index=False)
|
||||
logger.info("排班异常合并名单(共 %d 人)已保存:%s", len(rows), save_path)
|
||||
return save_path
|
||||
|
||||
|
||||
def main() -> None:
|
||||
setup_logging()
|
||||
try:
|
||||
path = run_shift_abnormal_check()
|
||||
logger.info("=" * 60)
|
||||
logger.info("【排班异常识别完成】")
|
||||
logger.info(" 导出名单:%s", path)
|
||||
logger.info("=" * 60)
|
||||
except Exception as e:
|
||||
logger.error("排班异常识别失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.shift_abnormal
|
||||
@FileName: shift_abnormal_check.py
|
||||
@Author: 小布丁
|
||||
@Description: 排班异常识别(第三步):读取第二步导出的「调动台账 / 预入职台账」(表头在第 2 行),
|
||||
结合 HR 排班接口判断每人的排班是否异常,导出异常名单 Excel。
|
||||
判断口径:
|
||||
- 调动台账:按「调动时间」筛选近 9 天,对每人查询当日完整排班名
|
||||
({日期}_team_name,形如「印象-{上级部门}-技师岗」)。当「现职位序列」含「职能」
|
||||
时按「现单位」比对,其余按「现四级部门」比对;用 rf_s_kq_work_date_query
|
||||
接口按比对部门查出该部门全部排班集合,当日排班属于该集合才视为正常
|
||||
(接口查不到集合时兜底原「完整排班名包含部门名」判断),否则为排班异常
|
||||
(无排班 / 排班未更新);
|
||||
- 预入职台账:按「操作时间」筛选近 9 天,对每人查询「预入职日期」当日完整排班名,
|
||||
当日有完整排班信息即为正常,无排班信息则为排班异常。有排班信息即可,不校验部门。
|
||||
不纳入异常:现职位序列命中 经营系管理序列 / 职能系专业序列 / 门店技师序列 的剔除(调动+预入职均生效)。
|
||||
底层能力复用:hr_session(会话管理)、hr_api.shift(排班查询)、roster 导出。
|
||||
@Version: 1.0.0
|
||||
|
||||
说明:
|
||||
1. 输入为第二步导出的《调动台账.xlsx》《预入职台账.xlsx》,两表表头均在第 2 行(pandas header=1)。
|
||||
2. 完整排班名取 {日期}_team_name(含上级部门),而非 {日期}_bc_name(仅班次名,如「技师中班C」)。
|
||||
3. 首次运行会自动完成 HR 登录并缓存 cookies,登录态过期自动重登。
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from datetime import date, datetime, timedelta
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in __import__("pathlib").Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(__import__("pathlib").Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
from app.service.hrbp.common.hr_session import build_hr_session # noqa: E402
|
||||
from app.service.hrbp.ehr.common.hr_api import fetch_cur_user_info # noqa: E402
|
||||
from app.service.hrbp.ehr.common.hr_api.shift import fetch_all_shift, fetch_all_work_date # noqa: E402
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
pd = None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ===================== 配置区(可自行修改) =====================
|
||||
# 默认输出目录(与第二步导出目录一致)
|
||||
SAVE_DIR = r"D:\资料\人资\排班异常识别"
|
||||
|
||||
# 第二步导出的台账文件名(表头在第 2 行)
|
||||
TRANSFER_FILE = os.path.join(SAVE_DIR, "调动台账.xlsx")
|
||||
PREENTRY_FILE = os.path.join(SAVE_DIR, "预入职台账.xlsx")
|
||||
|
||||
# 筛选窗口:近 N 天(含当天)
|
||||
DAYS = 9
|
||||
|
||||
# 每个员工是否重新校验会话(按人数控制频率,避免登录态过期后逐人触发重登)
|
||||
SESSION_REVALIDATE_EVERY = 30
|
||||
|
||||
# 名单输出列(调动台账 + 预入职台账合并为一张表,类别区分 调动/入职)
|
||||
COLUMNS: List[str] = [
|
||||
"序号", "姓名", "工号", "类别", "原单位", "原上级部门", "现单位", "现职位序列",
|
||||
"现上级部门", "现四级部门", "调动/入职时间", "操作时间", "当日排班", "异常原因",
|
||||
]
|
||||
|
||||
# 现职位序列命中以下序列的不纳入异常(不统计、不导出)
|
||||
EXCLUDE_SEQ_KEYWORDS = ("经营系管理序列", "职能系专业序列", "门店技师序列")
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 1. 通用工具
|
||||
# ----------------------------------------------
|
||||
def _clean(v) -> str:
|
||||
"""转字符串并去掉常见杂质:None、浮点 .0 尾缀、pandas 空占位(nan/native等)。"""
|
||||
if v is None:
|
||||
return ""
|
||||
s = str(v).strip()
|
||||
if s.lower() in ("nan", "none", "nat"):
|
||||
return ""
|
||||
if s.endswith(".0"):
|
||||
s = s[:-2]
|
||||
return s
|
||||
|
||||
|
||||
def _date_part(v) -> str:
|
||||
"""取日期字符串前 10 位(兼容 "YYYY-MM-DD HH:MM:SS")。"""
|
||||
return _clean(v)[:10]
|
||||
|
||||
|
||||
def _seq_excluded(seq: str) -> bool:
|
||||
"""现职位序列命中剔除序列(经营系管理序列/职能系专业序列/门店技师序列)返回 True。"""
|
||||
seq = _clean(seq)
|
||||
return any(kw in seq for kw in EXCLUDE_SEQ_KEYWORDS)
|
||||
|
||||
|
||||
def _shift_name(s: str) -> str:
|
||||
"""归一化排班名:兼容 {日期}_team_name 可能带 "YYYY-MM-DD_" 前缀,去掉前缀便于与接口 work_date_name 比对。"""
|
||||
s = _clean(s)
|
||||
if len(s) > 11 and s[4] == "-" and s[7] == "-" and s[10] == "_":
|
||||
return s[11:]
|
||||
return s
|
||||
|
||||
|
||||
def _parse_date(v) -> Optional[date]:
|
||||
"""解析日期字符串为 date,失败返回 None。"""
|
||||
s = _date_part(v)
|
||||
if not s:
|
||||
return None
|
||||
try:
|
||||
return datetime.strptime(s, "%Y-%m-%d").date()
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _recent_window(end: date = None, days: int = DAYS) -> Tuple[date, date]:
|
||||
"""返回近 N 天的 (开始日期, 结束日期),含当天。"""
|
||||
end = end or date.today()
|
||||
begin = end - timedelta(days=days - 1)
|
||||
return begin, end
|
||||
|
||||
|
||||
def _load_ledger(path: str) -> "pd.DataFrame":
|
||||
"""读取第二步导出的台账,表头在第 2 行(header=1)。"""
|
||||
if not os.path.exists(path):
|
||||
raise RuntimeError(
|
||||
f"未找到台账文件:{path}\n请先运行第二步导出(调动台账 / 预入职台账)后再执行本模块。"
|
||||
)
|
||||
df = pd.read_excel(path, header=1, dtype=str)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
logger.info("已读取台账:%s,共 %d 行", path, len(df))
|
||||
return df
|
||||
|
||||
|
||||
def _validate_session(session):
|
||||
"""校验 cookies 有效性,返回 (session, user_id);过期则重新登录并重建会话。"""
|
||||
session, user_id = _ensure_user_id(session, None)
|
||||
return session, user_id
|
||||
|
||||
|
||||
def _ensure_user_id(session, user_id: Optional[str]) -> Tuple[object, str]:
|
||||
"""获取有效 user_id 与会话。传入 None 时实时取;已有则直接复用。"""
|
||||
if user_id:
|
||||
return session, user_id
|
||||
info = fetch_cur_user_info(session)
|
||||
new_uid = _clean(info.get("userId"))
|
||||
if not new_uid:
|
||||
raise RuntimeError(f"员工基础信息接口未返回 userId:{info}")
|
||||
return session, new_uid
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 2. 按工号查询某日完整排班名({日期}_team_name)
|
||||
# ----------------------------------------------
|
||||
class _ShiftFetcher:
|
||||
"""带缓存的排班查询器:按 (工号, 日期) 缓存当日完整排班名,复用同一会话,定期校验登录态。"""
|
||||
|
||||
def __init__(self, session, user_id: str):
|
||||
self.session = session
|
||||
self.user_id = user_id
|
||||
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 % SESSION_REVALIDATE_EVERY == 1:
|
||||
self.session, uid = _ensure_user_id(self.session, None)
|
||||
self.user_id = uid
|
||||
val = self._query(code, day)
|
||||
self.cache[key] = val
|
||||
time.sleep(0.2)
|
||||
return self.cache[key]
|
||||
|
||||
def _query(self, code: str, day: date) -> str:
|
||||
day_str = day.strftime("%Y-%m-%d")
|
||||
rows = fetch_all_shift(self.session, self.user_id, code, day_str, day_str)
|
||||
for rec in rows:
|
||||
return _clean(rec.get(f"{day_str}_team_name"))
|
||||
return ""
|
||||
|
||||
|
||||
class _DeptShiftFetcher:
|
||||
"""按部门名缓存该部门的排班名集合(work_date_name),复用同一会话,定期校验登录态。
|
||||
|
||||
同一部门可能配置多个排班(技师岗/服务岗/管理岗…),通过 rf_s_kq_work_date_query
|
||||
接口按部门查出全部排班名,用于判断员工当日排班是否属于该部门。
|
||||
"""
|
||||
|
||||
def __init__(self, session):
|
||||
self.session = session
|
||||
self.cache: Dict[str, set] = {}
|
||||
self.calls = 0
|
||||
|
||||
def fetch(self, dept_name: str) -> set:
|
||||
"""返回某部门的排班名集合;部门名为空或查不到返回空集合。"""
|
||||
dept_name = _clean(dept_name)
|
||||
if not dept_name:
|
||||
return set()
|
||||
if dept_name not in self.cache:
|
||||
# 定期重新校验登录态,避免绑定过期会话
|
||||
self.calls += 1
|
||||
if self.calls % SESSION_REVALIDATE_EVERY == 1:
|
||||
self.session, _ = _ensure_user_id(self.session, None)
|
||||
self.cache[dept_name] = {_shift_name(n) for n in fetch_all_work_date(self.session, dept_name)}
|
||||
time.sleep(0.2)
|
||||
return self.cache[dept_name]
|
||||
|
||||
|
||||
def _shift_belongs(dept_fetcher: "_DeptShiftFetcher", dept_name: str, shift: str) -> bool:
|
||||
"""判断某排班是否属于某部门。
|
||||
|
||||
优先用新接口(rf_s_kq_work_date_query)按部门查出排班集合做成员判断;
|
||||
接口查不到集合(如「现单位」无直属排班)时兜底原「完整排班名包含部门名」判断。
|
||||
"""
|
||||
dept_name = _clean(dept_name)
|
||||
shift_norm = _shift_name(shift)
|
||||
if not dept_name or not shift_norm:
|
||||
return False
|
||||
dept_shifts = dept_fetcher.fetch(dept_name)
|
||||
if dept_shifts:
|
||||
return shift_norm in dept_shifts
|
||||
return dept_name in shift
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 3. 调动台账判定
|
||||
# ----------------------------------------------
|
||||
def _check_transfer_row(fetcher: "_ShiftFetcher", dept_fetcher: "_DeptShiftFetcher", r, begin: date, end: date):
|
||||
"""对单行调动记录判定,返回名单行 dict;属正常则返回 None。"""
|
||||
code = _clean(r.get("工号"))
|
||||
day = _parse_date(r.get("调动时间"))
|
||||
if not code or not day:
|
||||
return None
|
||||
if not (begin <= day <= end):
|
||||
return None
|
||||
|
||||
# 判断字段:现职位序列含「职能」按现单位判断,否则按现四级部门判断
|
||||
seq = _clean(r.get("现职位序列"))
|
||||
if _seq_excluded(seq):
|
||||
return None
|
||||
if "职能" in seq:
|
||||
target_field, target_name = "现单位", _clean(r.get("现单位"))
|
||||
else:
|
||||
target_field, target_name = "现四级部门", _clean(r.get("现四级部门"))
|
||||
|
||||
shift = fetcher.fetch(code, day) # 当日完整排班名(含上级部门),无排班为空串
|
||||
|
||||
if not shift:
|
||||
reason, present = "调动时间无排班", ""
|
||||
elif target_name and not _shift_belongs(dept_fetcher, target_name, shift):
|
||||
reason, present = f"排班未更新为{target_field}({target_name})", shift
|
||||
else:
|
||||
return None # 当日有排班且排班属于所需部门 → 正常
|
||||
|
||||
return {
|
||||
"序号": 0,
|
||||
"姓名": _clean(r.get("姓名")),
|
||||
"工号": code,
|
||||
"类别": "调动",
|
||||
"原单位": _clean(r.get("原单位")),
|
||||
"原上级部门": _clean(r.get("原上级部门")),
|
||||
"现单位": _clean(r.get("现单位")),
|
||||
"现职位序列": seq,
|
||||
"现上级部门": _clean(r.get("现上级部门")),
|
||||
"现四级部门": _clean(r.get("现四级部门")),
|
||||
"调动/入职时间": day.strftime("%Y-%m-%d"),
|
||||
"操作时间": _date_part(r.get("操作时间")),
|
||||
"当日排班": present,
|
||||
"异常原因": reason,
|
||||
}
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 4. 预入职台账判定
|
||||
# ----------------------------------------------
|
||||
def _check_preentry_row(fetcher: "_ShiftFetcher", dept_fetcher: "_DeptShiftFetcher", r, begin: date, end: date):
|
||||
"""对单行预入职记录判定,返回名单行 dict;有排班信息则返回 None。"""
|
||||
code = _clean(r.get("工号"))
|
||||
op_day = _parse_date(r.get("操作时间")) # 筛选字段:操作时间
|
||||
if not code or not op_day:
|
||||
return None
|
||||
if not (begin <= op_day <= end):
|
||||
return None
|
||||
if _seq_excluded(r.get("职位序列")):
|
||||
return None
|
||||
|
||||
# 排班检查日期:预入职日期(筛选按操作时间,查询排班按预入职日期)
|
||||
pj_day = _parse_date(r.get("预入职日期"))
|
||||
if not pj_day:
|
||||
return None
|
||||
|
||||
shift = fetcher.fetch(code, pj_day) # 当日完整排班名,无则空串
|
||||
if shift:
|
||||
return None # 有排班信息即可 → 正常
|
||||
|
||||
return {
|
||||
"序号": 0,
|
||||
"姓名": _clean(r.get("姓名")),
|
||||
"工号": code,
|
||||
"类别": "入职",
|
||||
"原单位": "",
|
||||
"原上级部门": "",
|
||||
"现单位": _clean(r.get("入职单位")),
|
||||
"现职位序列": _clean(r.get("职位序列")),
|
||||
"现上级部门": "",
|
||||
"现四级部门": "",
|
||||
"调动/入职时间": pj_day.strftime("%Y-%m-%d"),
|
||||
"操作时间": op_day.strftime("%Y-%m-%d"),
|
||||
"当日排班": "",
|
||||
"异常原因": "预入职日期无排班",
|
||||
}
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 5. 主流程
|
||||
# ----------------------------------------------
|
||||
def _collect_rows(ledger_path: str, check_row, fetcher: "_ShiftFetcher",
|
||||
dept_fetcher: "_DeptShiftFetcher", end: date) -> List[dict]:
|
||||
"""通用判定流程:读台账 → 逐行判定,返回异常行列表(未写文件)。"""
|
||||
df = _load_ledger(ledger_path)
|
||||
begin, end_date = _recent_window(end)
|
||||
logger.info("筛选范围:%s ~ %s(近 %d 天)", begin, end_date, DAYS)
|
||||
|
||||
rows: List[dict] = []
|
||||
for _, r in df.iterrows():
|
||||
row = check_row(fetcher, dept_fetcher, r, begin, end_date)
|
||||
if row:
|
||||
rows.append(row)
|
||||
logger.info("台账 %s 排班异常人数:%d", os.path.basename(ledger_path), len(rows))
|
||||
return rows
|
||||
|
||||
|
||||
def run_shift_abnormal_check(
|
||||
transfer_path: str = None,
|
||||
preentry_path: str = None,
|
||||
days: int = DAYS,
|
||||
) -> str:
|
||||
"""执行排班异常识别(调动台账 + 预入职台账),合并导出单张 Excel,返回文件路径。
|
||||
|
||||
Args:
|
||||
transfer_path: 调动台账 xlsx 路径,默认 TRANSFER_FILE
|
||||
preentry_path: 预入职台账 xlsx 路径,默认 PREENTRY_FILE
|
||||
days: 筛选近 N 天,默认 9
|
||||
"""
|
||||
global DAYS
|
||||
DAYS = days
|
||||
transfer_path = transfer_path or TRANSFER_FILE
|
||||
preentry_path = preentry_path or PREENTRY_FILE
|
||||
end = date.today()
|
||||
|
||||
session = build_hr_session()
|
||||
session, user_id = _validate_session(session)
|
||||
fetcher = _ShiftFetcher(session, user_id)
|
||||
dept_fetcher = _DeptShiftFetcher(session)
|
||||
|
||||
rows: List[dict] = []
|
||||
if os.path.exists(transfer_path):
|
||||
rows.extend(_collect_rows(transfer_path, _check_transfer_row, fetcher, dept_fetcher, end))
|
||||
else:
|
||||
logger.warning("跳过调动台账:文件不存在 %s", transfer_path)
|
||||
|
||||
if os.path.exists(preentry_path):
|
||||
rows.extend(_collect_rows(preentry_path, _check_preentry_row, fetcher, dept_fetcher, end))
|
||||
else:
|
||||
logger.warning("跳过预入职台账:文件不存在 %s", preentry_path)
|
||||
|
||||
if not rows:
|
||||
raise RuntimeError("未识别到排班异常,或台账文件均不存在(请先完成第二步导出)。")
|
||||
|
||||
# 合并排序并补序号
|
||||
rows.sort(key=lambda x: (x.get("类别", ""), x.get("姓名", ""), x.get("工号", "")))
|
||||
for idx, item in enumerate(rows, 1):
|
||||
item["序号"] = idx
|
||||
|
||||
os.makedirs(SAVE_DIR, exist_ok=True)
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
save_path = os.path.join(SAVE_DIR, f"排班异常名单_{ts}.xlsx")
|
||||
pd.DataFrame(rows, columns=COLUMNS).to_excel(save_path, index=False)
|
||||
logger.info("排班异常合并名单(共 %d 人)已保存:%s", len(rows), save_path)
|
||||
return save_path
|
||||
|
||||
|
||||
def main() -> None:
|
||||
setup_logging()
|
||||
try:
|
||||
path = run_shift_abnormal_check()
|
||||
logger.info("=" * 60)
|
||||
logger.info("【排班异常识别完成】")
|
||||
logger.info(" 导出名单:%s", path)
|
||||
logger.info("=" * 60)
|
||||
except Exception as e:
|
||||
logger.error("排班异常识别失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user