Files
37duAutomation/plugins/xq0011/logic/unsealed_check.py
T

198 lines
8.1 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 -*-
"""XQ0011 考勤月报封存检查 插件 - 检查5「未封存名单」(由影刀版移植)。
当月考勤封存完毕后执行,检查范围为「上月完整月份」。识别当月有在职记录的员工是否都有
考勤月报封存记录;有在职记录但无封存记录者输出异常名单。
判定口径:
- 花名册逐人取 入职时间 / 离职时间,判定其「在检查月是否在职」:
在职 =(入职时间 ≤ 月末)且(无离职时间 或 离职时间 ≥ 月初)。
- 仅统计所属单位在白名单内的员工;
- 有在职记录但工号不在当月封存记录集合里 → 异常。
数据来源:
1) 在职记录(花名册):由 roster_export_api.export_roster() 导出(模板=员工基础信息);
2) 考勤封存记录:由 seal_data_export.export_seal_data() 导出并预处理,本模块只读取。
插件化改造点:
1. 花名册由 run() 自动导出(TTL 缓存复用),roster_path 可显式指定;
2. 不单独落盘,仅返回异常名单行。
"""
import os
from datetime import date, datetime
from typing import List, Optional, Set, Tuple
import pandas as pd
from ..config import logger, DEFAULT_SAVE_DIR, get_roster_path
from ..data.seal_data_export import (
SEAL_UNIT_WHITELIST, enrich_dept_fields, load_excluded_codes, load_seal_rows,
_clean, _parse_date,
)
def _default_roster(save_dir: str) -> str:
return os.path.join(save_dir, "员工花名册.xlsx")
# 异常类型(对应需求文档检查5)
ABNORMAL_TYPE = "考勤月报未封存,请处理"
# 封存记录工号字段
SEAL_CODE_FIELDS = ("base_code", "seal_base_code")
# 花名册字段(与「员工基础信息」模板导出的列名一致)
ROSTER_CODE_COL = "工号"
ROSTER_NAME_COL = "姓名"
ROSTER_UNIT_COL = "所属单位"
ROSTER_JOIN_COL = "入职时间"
ROSTER_LEAVE_COL = "离职时间"
# 输出列(对应需求文档检查5输出字段)
OUTPUT_COLUMNS = [
"37工号", "姓名", "岗位", "入职时间", "离职时间", "月报检查月份", "异常类型",
"所属单位", "一级部门", "二级部门", "三级部门", "四级部门", "五级部门",
]
def _prev_month(year: int, month: int) -> Tuple[int, int]:
if month == 1:
return year - 1, 12
return year, month - 1
def _month_range(ym: str) -> Tuple[date, date]:
y, m = int(ym[:4]), int(ym[5:7])
if m == 2:
import calendar
total_days = calendar.monthrange(y, m)[1]
else:
total_days = 31 if m in (1, 3, 5, 7, 8, 10, 12) else 30
return date(y, m, 1), date(y, m, total_days)
def _seal_map(rows: List[dict]) -> Dict[str, dict]:
"""取当月封存记录映射(工号 → 封存记录行,一员工一条)。"""
mapping: Dict[str, dict] = {}
for rec in rows:
code = ""
for f in SEAL_CODE_FIELDS:
code = _clean(rec.get(f))
if code:
break
if code:
mapping.setdefault(code, rec)
return mapping
# ==================== 花名册在职判定 ====================
def _load_roster(roster_path: str) -> "pd.DataFrame":
"""读取花名册(「员工基础信息」模板导出,表头在第 1 行)。"""
if not os.path.exists(roster_path):
raise RuntimeError(
f"未找到花名册文件:{roster_path}\n"
"请先运行插件(花名册导出步骤,模板=员工基础信息,在职状态=在职+离职)导出花名册;"
"或通过 roster_path 字段指定已有花名册文件。")
df = pd.read_excel(roster_path, dtype=str)
df.columns = [str(c).strip() for c in df.columns]
logger.info("已读取花名册:%s,共 %d 行", roster_path, len(df))
return df
def _in_month(join: Optional[date], leave: Optional[date], first: date, last: date) -> bool:
"""判断员工检查月是否在职:入职 ≤ 月末 且(未离职 或 离职 ≥ 月初)。"""
if join is None or join > last:
return False
if leave is None or leave >= first:
return True
return False
# ==================== 主流程 ====================
def _build_unsealed_rows(df, seal_map: Dict[str, dict], ym: str, first: date, last: date,
roster_path: str = None) -> List[dict]:
"""遍历花名册,找出检查月在职、所属单位在白名单内但无封存记录的员工,返回名单行列表。
与封存预处理口径一致:一级部门 = 职业技术培训学校 的员工不参与本检查,直接剔除。
在册判定口径(离职时间统一以封存记录为准):存在离职后又复职的员工,其最新花名册
离职日期已被清空,若只看花名册会漏判其检查月曾离职;故对已封存(有封存记录)的
员工优先用封存记录的入职/离职时间判定检查月在册,花名册仅兜底无封存记录者。
"""
abnormal: List[dict] = []
seen: Set[str] = set()
excluded = load_excluded_codes(roster_path)
excluded_n = 0
for _, row in df.iterrows():
code = _clean(row.get(ROSTER_CODE_COL))
if not code or code in seen:
continue # 花名册在职/离职同一工号可能多行,取一行即可
seen.add(code)
unit = _clean(row.get(ROSTER_UNIT_COL))
if unit not in SEAL_UNIT_WHITELIST:
continue # 与封存表预处理口径一致:仅检查白名单单位员工
if code in excluded:
excluded_n += 1
continue # 一级部门 = 职业技术培训学校,不参与本检查
seal_rec = seal_map.get(code)
if seal_rec is not None:
join = _parse_date(seal_rec.get("join_date"))
leave = _parse_date(seal_rec.get("leaveOffice_date"))
else:
join = _parse_date(row.get(ROSTER_JOIN_COL))
leave = _parse_date(row.get(ROSTER_LEAVE_COL))
if not _in_month(join, leave, first, last):
continue # 检查月不在册(尚未入职或已离职早于月初)
if code in seal_map:
continue # 已有封存记录,正常
abnormal.append(enrich_dept_fields({
"37工号": code,
"姓名": _clean(row.get(ROSTER_NAME_COL)),
"月报检查月份": ym,
"异常类型": ABNORMAL_TYPE,
}, code, seal_rec, roster_path))
if excluded_n:
logger.info("检查5 剔除「职业技术培训学校」%d 人", excluded_n)
return abnormal
def run_unsealed_check(month: str = None, save_dir: str = None,
roster_path: str = None) -> List[dict]:
"""执行检查5「未封存名单」,返回异常名单行列表。
Args:
month: 检查月份 "YYYY-MM",默认上月。
save_dir: 输出目录(默认路径下读取封存表与花名册)。
roster_path: 花名册文件路径,默认 save_dir/员工花名册.xlsx。
Returns:
异常名单行列表(每行为 OUTPUT_COLUMNS 对应字段的 dict)。
"""
today = date.today()
if month:
try:
first, last = _month_range(month)
except (ValueError, IndexError, TypeError):
raise ValueError(f"月份格式应为 YYYY-MM,收到:{month}")
ym = month
else:
py, pm = _prev_month(today.year, today.month)
first, last = _month_range(f"{py:04d}-{pm:02d}")
ym = f"{py:04d}-{pm:02d}"
save_dir = save_dir or DEFAULT_SAVE_DIR
roster_path = roster_path or _default_roster(save_dir)
logger.info("===== 检查5「未封存名单」月份:%s(%s ~ %s) =====", ym, first, last)
# 1. 读花名册(在职记录)
df = _load_roster(roster_path)
# 2. 读取预处理封存表(已按所属单位白名单筛选并保存)
seal_rows = load_seal_rows(ym, save_dir)
seal_map = _seal_map(seal_rows)
logger.info("考勤封存记录共 %d 人:%s", len(seal_map), ym)
# 3. 找出在册未封存
abnormal = _build_unsealed_rows(df, seal_map, ym, first, last, roster_path)
logger.info("检查5命中异常 %d 人(在册未封存)", len(abnormal))
return abnormal