refactor(workflows): 统一替换 yingdao 目录引用为 workflows
1. 将所有文档、代码中对 `yingdao/` 目录的引用替换为 `workflows/`,统一影刀版代码的命名空间 2. 调整 workflows/share 模块内的路径引用与文档注释,确保一致性 3. 同步更新测试代码与配置文件中的旧目录引用
This commit is contained in:
@@ -0,0 +1,115 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""考勤月报封存检查 - webhost 场景插件(XQ0011)
|
||||
|
||||
流程:填写检查月份与正休规则 → 一键执行(拉取数据 + 运行五项检查 + 自动导出多 Sheet Excel)。
|
||||
复用 desktop/shared 数据真源(由宿主共享登录态注入 session/user_id),不内置登录逻辑。
|
||||
"""
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from webhost.backend.plugins.base import PLUGINS, RunContext, ScenePlugin
|
||||
|
||||
from webhost.backend.plugins.seal_check import config
|
||||
from webhost.backend.plugins.seal_check.data import (
|
||||
fetch_compare_diffs, fetch_org_name_map, fetch_roster_data,
|
||||
fetch_seal_rows, fetch_shift_batch,
|
||||
)
|
||||
from webhost.backend.plugins.seal_check.logic import LeaveRuleEngine, run_all_checks
|
||||
from webhost.backend.plugins.seal_check.report import CHECK_TAB_TITLES, export_report
|
||||
|
||||
|
||||
def _default_month() -> str:
|
||||
last_end = datetime.now().replace(day=1) - timedelta(days=1)
|
||||
return f"{last_end.year:04d}-{last_end.month:02d}"
|
||||
|
||||
|
||||
class SealCheckPlugin(ScenePlugin):
|
||||
id = "seal_check"
|
||||
name = "考勤月报封存检查"
|
||||
version = "1.0.0"
|
||||
description = "填写每月正休规则,一键执行五项检查并导出多 Sheet Excel 报告"
|
||||
platform = "hr"
|
||||
uses_month = True # 月份由底座页眉统一提供(注入 ref_month),插件自身不再单列
|
||||
fields = [
|
||||
{"key": "fixed_rest_days", "label": "固休应休天数", "type": "int",
|
||||
"default": config.DEFAULT_RULES["fixed_rest_days"]},
|
||||
{"key": "size_rest_days", "label": "大小休应休天数", "type": "int",
|
||||
"default": config.DEFAULT_RULES["size_rest_days"]},
|
||||
{"key": "quota_rest_days", "label": "限额排休上限", "type": "int",
|
||||
"default": config.DEFAULT_RULES["quota_rest_days"]},
|
||||
]
|
||||
|
||||
def run(self, fields: dict, ctx: RunContext) -> dict:
|
||||
month_str = str(fields.get("ref_month") or _default_month()).strip()
|
||||
year, month = int(month_str[:4]), int(month_str[5:7].strip())
|
||||
yearmonth = f"{year:04d}{month:02d}"
|
||||
month_display = f"{year:04d}-{month:02d}"
|
||||
|
||||
engine = LeaveRuleEngine(
|
||||
size_rest_days=int(fields.get("size_rest_days") or config.DEFAULT_RULES["size_rest_days"]),
|
||||
fixed_rest_days=int(fields.get("fixed_rest_days") or config.DEFAULT_RULES["fixed_rest_days"]),
|
||||
quota_rest_days=int(fields.get("quota_rest_days") or config.DEFAULT_RULES["quota_rest_days"]),
|
||||
)
|
||||
|
||||
session = ctx.get_session("hr")
|
||||
user_id = ctx.get_user_id("hr")
|
||||
|
||||
ctx.log(f"开始考勤月报封存检查:{month_display}")
|
||||
ctx.progress(5)
|
||||
|
||||
ctx.log("拉取考勤封存数据……")
|
||||
seal_rows = fetch_seal_rows(session, user_id, yearmonth)
|
||||
ctx.progress(30)
|
||||
ctx.log(f"封存数据 {len(seal_rows)} 人")
|
||||
|
||||
ctx.log("拉取组织表……")
|
||||
org_name_map = fetch_org_name_map(session)
|
||||
ctx.progress(45)
|
||||
ctx.log(f"组织 {len(org_name_map)} 条")
|
||||
|
||||
ctx.log("导出花名册(获取职位序列)……")
|
||||
seq_map, in_service_records = fetch_roster_data(session)
|
||||
ctx.progress(60)
|
||||
ctx.log(f"花名册职位序列 {len(seq_map)} 人,在职 {len(in_service_records)} 人")
|
||||
|
||||
ctx.log("批量拉取排班(计算应出勤天数)……")
|
||||
shift_map = fetch_shift_batch(session, user_id, yearmonth)
|
||||
ctx.progress(80)
|
||||
ctx.log(f"排班应出勤 {len(shift_map)} 人")
|
||||
|
||||
diff_rows, diff_note = fetch_compare_diffs(session, user_id, yearmonth)
|
||||
ctx.progress(90)
|
||||
|
||||
notes = [diff_note] if diff_note else []
|
||||
ctx.log("运行全部检查……")
|
||||
result = run_all_checks(
|
||||
seal_rows=seal_rows,
|
||||
org_name_map=org_name_map,
|
||||
seq_map=seq_map,
|
||||
in_service_records=in_service_records,
|
||||
shift_map=shift_map,
|
||||
engine=engine,
|
||||
year=year, month=month,
|
||||
diff_rows=diff_rows, diff_fields=None, notes=notes,
|
||||
)
|
||||
ctx.progress(95)
|
||||
|
||||
path = export_report(result["rows"], month_display, result["notes"])
|
||||
ctx.progress(100)
|
||||
|
||||
for note in result["notes"]:
|
||||
ctx.log(f"[提示] {note}")
|
||||
summary = ";".join(
|
||||
f"{CHECK_TAB_TITLES[i]} {len(result['rows'].get(i, []))} 条"
|
||||
for i in range(1, 6))
|
||||
ctx.log(f"结果汇总:{summary}")
|
||||
ctx.log(f"===== 检查完成,报告已导出:{path} =====")
|
||||
|
||||
return {
|
||||
"summary": summary,
|
||||
"path": path,
|
||||
"rows": {str(k): v for k, v in result["rows"].items()},
|
||||
"notes": result["notes"],
|
||||
}
|
||||
|
||||
|
||||
PLUGINS.append(SealCheckPlugin())
|
||||
@@ -0,0 +1,35 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""考勤月报封存检查(webhost 场景插件)配置。
|
||||
|
||||
与 desktop/plugins/seal_check/config.py 保持同步(影刀/桌面版为单一真源)。
|
||||
"""
|
||||
import os
|
||||
|
||||
# ==================== 输出目录 ====================
|
||||
SAVE_DIR = os.getenv("monthly_seal_save_dir") or r"D:\资料\人资\考勤异常"
|
||||
|
||||
# 花名册导出(取职位序列,服务端已翻译中文)
|
||||
ROSTER_EXPORT_PATH = os.path.join(SAVE_DIR, "员工花名册_桌面版.xlsx")
|
||||
ROSTER_DOWNLOAD_DIR = os.path.join(SAVE_DIR, "花名册下载")
|
||||
|
||||
# ==================== 每月正休规则(默认值,界面可覆盖) ====================
|
||||
DEFAULT_RULES = {
|
||||
"size_rest_days": 6, # 大小休 应休天数
|
||||
"fixed_rest_days": 5, # 固休 应休天数
|
||||
"quota_rest_days": 8, # 天数限额排休 上限
|
||||
}
|
||||
|
||||
# 集团总部职能部门(大小休)
|
||||
GROUP_HEADQUARTER_UNITS = (
|
||||
"财务管理部",
|
||||
"集团管理中心",
|
||||
"集团营建中心",
|
||||
)
|
||||
|
||||
# ==================== 排班接口 ====================
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
SHIFT_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_p_kq_count_SelectBanci/getExecutePageResult.mc"
|
||||
PAGE_MAX_SIZE = 500
|
||||
|
||||
# 排班休息日判定:当日班次名({日期}_bc_name)等于该值视为休息
|
||||
REST_SHIFT_NAME = "休息"
|
||||
@@ -0,0 +1,160 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""考勤月报封存检查 - 数据拉取(webhost 场景插件)
|
||||
|
||||
数据真源复用 desktop/shared(与桌面/影刀版单一真源一致),传入宿主构建的
|
||||
requests.Session / user_id 即可,不内置任何登录逻辑。
|
||||
session 由 webhost 宿主的共享登录态提供(RunContext.get_session / get_user_id)。
|
||||
"""
|
||||
import calendar
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Dict, List, Tuple
|
||||
|
||||
from webhost.backend.shared import org_export, roster_export_api, seal_data_export
|
||||
|
||||
from webhost.backend.plugins.seal_check import config
|
||||
|
||||
# hr_request_json:统一做全局重试(3次) + 登录态失效判定(复用桌面 shared 真源)
|
||||
hr_request_json = seal_data_export.hr_request_json
|
||||
|
||||
|
||||
# ==================== 通用工具 ====================
|
||||
def _clean(v) -> str:
|
||||
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 _norm_path(p: str) -> str:
|
||||
p = _clean(p).replace("\\", "/").strip("/")
|
||||
if p.startswith("集团/"):
|
||||
p = p[len("集团/"):]
|
||||
elif p == "集团":
|
||||
p = ""
|
||||
return p.strip("/")
|
||||
|
||||
|
||||
def last_month_ym(today: datetime = None) -> str:
|
||||
today = today or datetime.now()
|
||||
last_end = today.replace(day=1) - timedelta(days=1)
|
||||
return f"{last_end.year:04d}{last_end.month:02d}"
|
||||
|
||||
|
||||
# ==================== 1. 封存数据 ====================
|
||||
def fetch_seal_rows(session, user_id: str, yearmonth: str) -> List[dict]:
|
||||
rows = seal_data_export.fetch_all_seal(session, user_id, yearmonth)
|
||||
return seal_data_export._filter_by_unit(rows)
|
||||
|
||||
|
||||
# ==================== 2. 组织表 ====================
|
||||
def fetch_org_name_map(session) -> Dict[str, str]:
|
||||
"""组织全路径 -> 组织名称(用于解析组织类型)。"""
|
||||
rows = org_export.fetch_all_orgs(session)
|
||||
name_map: Dict[str, str] = {}
|
||||
for rec in rows:
|
||||
path = _norm_path(rec.get("pt_structure.ORG_FULL_PATH"))
|
||||
name = _clean(rec.get("pt_organzation.ORG_NAME"))
|
||||
if path and name:
|
||||
name_map[path] = name
|
||||
return name_map
|
||||
|
||||
|
||||
# ==================== 3. 花名册(导出接口,职位序列已翻译) ====================
|
||||
def fetch_roster_data(session) -> Tuple[Dict[str, str], List[dict]]:
|
||||
"""导出花名册(在职+离职)。返回 (seq_map, in_service_records)。"""
|
||||
import pandas as pd
|
||||
|
||||
path = roster_export_api.export_roster(
|
||||
output_path=config.ROSTER_EXPORT_PATH,
|
||||
download_dir=config.ROSTER_DOWNLOAD_DIR,
|
||||
template_name="员工基础信息",
|
||||
statuses=["在职", "离职"],
|
||||
)
|
||||
df = pd.read_excel(path, dtype=str)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
|
||||
seq_map: Dict[str, str] = {}
|
||||
in_service_records: List[dict] = []
|
||||
for _, r in df.iterrows():
|
||||
code = _clean(r.get("工号"))
|
||||
seq = _clean(r.get("职位序列"))
|
||||
if code:
|
||||
seq_map[code] = seq
|
||||
if _clean(r.get("在职状态")) == "在职":
|
||||
in_service_records.append({
|
||||
"工号": code,
|
||||
"姓名": _clean(r.get("姓名")),
|
||||
"所属单位": _clean(r.get("所属单位")),
|
||||
"一级部门": _clean(r.get("一级部门")),
|
||||
"二级部门": _clean(r.get("二级部门")),
|
||||
"三级部门": _clean(r.get("三级部门")),
|
||||
"四级部门": _clean(r.get("四级部门")),
|
||||
"五级部门": _clean(r.get("五级部门")),
|
||||
})
|
||||
return seq_map, in_service_records
|
||||
|
||||
|
||||
# ==================== 4. 排班(批量导出) ====================
|
||||
def fetch_shift_batch(session, user_id: str, yearmonth: str) -> Dict[str, int]:
|
||||
"""批量拉取某月全集团排班,返回 {工号: 应出勤天数}。
|
||||
|
||||
base_code 留空 = 全集团批量;每条记录 = 一个员工整月排班,
|
||||
逐日列 key 为 "YYYY-MM-DD_bc_name",休息日判定 bc_name == config.REST_SHIFT_NAME。
|
||||
"""
|
||||
ym = str(yearmonth)
|
||||
year, month = int(ym[:4]), int(ym[4:6])
|
||||
days_in_month = calendar.monthrange(year, month)[1]
|
||||
begin = f"{year:04d}-{month:02d}-01"
|
||||
end = f"{year:04d}-{month:02d}-{days_in_month:02d}"
|
||||
|
||||
all_rows: List[dict] = []
|
||||
page_no = 1
|
||||
while True:
|
||||
params = {
|
||||
"treecode": "cq37du", "user_id": user_id, "sqlId": "kq_count_SelectBanci",
|
||||
"commonQuery": "", "commonQueryStr": "", "staff_ids": "",
|
||||
"person_status": "1,4", "post_no": "", "post_type": "1", "post_level": "",
|
||||
"identity": "", "showType": "1", "dateType": "1",
|
||||
"begin": begin, "end": end, "bc_date": begin,
|
||||
"base_code": "", "staff_name": "",
|
||||
"start": str((page_no - 1) * config.PAGE_MAX_SIZE),
|
||||
"sortType": "", "sortName": "",
|
||||
"pageNo": page_no, "pageSize": config.PAGE_MAX_SIZE,
|
||||
}
|
||||
data = hr_request_json(session, "POST", config.SHIFT_URL, params, "排班批量")
|
||||
if data.get("state") != "1":
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
# 分页保护:pageCount 缺失/为 0 时不能提前 break,否则会静默截断数据
|
||||
page_count = data.get("pageCount") or 0
|
||||
if page_count and page_no >= page_count:
|
||||
break
|
||||
if len(page_list) < config.PAGE_MAX_SIZE:
|
||||
break
|
||||
page_no += 1
|
||||
|
||||
result: Dict[str, int] = {}
|
||||
for rec in all_rows:
|
||||
code = _clean(rec.get("base_code"))
|
||||
if not code:
|
||||
continue
|
||||
work_days = 0
|
||||
for d in range(1, days_in_month + 1):
|
||||
bc = _clean(rec.get(f"{year:04d}-{month:02d}-{d:02d}_bc_name"))
|
||||
if bc and bc != config.REST_SHIFT_NAME:
|
||||
work_days += 1
|
||||
result[code] = work_days
|
||||
return result
|
||||
|
||||
|
||||
# ==================== 5. 对比差异(检查3,接口待封装) ====================
|
||||
def fetch_compare_diffs(session, user_id: str, yearmonth: str) -> Tuple[List[dict], str]:
|
||||
"""考勤月报封存「对比」差异数据;接口未封装前返回空 + 提示。"""
|
||||
return [], "检查3「封存值是否最新」的对比接口尚未封装,本次跳过该检查,请在数据层补充接口后启用"
|
||||
@@ -0,0 +1,279 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""考勤月报封存检查 - 规则引擎与五项检查(webhost 场景插件)
|
||||
|
||||
与 desktop/plugins/seal_check/logic.py 保持同步(桌面版为单一真源)。
|
||||
|
||||
规则完全由运行人员每月在界面录入的天数值驱动:
|
||||
- 固休:应休 = fixed_rest_days
|
||||
- 大小休:应休 = size_rest_days(实际允许 size_rest_days ~ 8 天区间)
|
||||
- 天数限额排休:应休 <= quota_rest_days(上限)
|
||||
"""
|
||||
import calendar
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime
|
||||
from typing import Dict, List
|
||||
|
||||
from webhost.backend.plugins.seal_check import config
|
||||
|
||||
# ==================== 异常名单统一列 ====================
|
||||
OUTPUT_COLUMNS = [
|
||||
"37工号", "姓名", "月报检查月份", "异常类型", "所属单位",
|
||||
"一级部门", "二级部门", "三级部门", "四级部门", "五级部门",
|
||||
]
|
||||
|
||||
TYPE_1 = "当月在职天数有差缺排班"
|
||||
TYPE_3 = "考勤封存非最新值,请重新封存"
|
||||
TYPE_4 = "出勤天数大于当月应出勤天数"
|
||||
TYPE_5 = "考勤月报未封存,请处理"
|
||||
|
||||
|
||||
# ==================== 规则引擎 ====================
|
||||
@dataclass
|
||||
class RestRule:
|
||||
rule_type: str # 大小休 / 固休 / 限额 / 未知
|
||||
days: int = None # 应休天数(限额为 None)
|
||||
max_days: int = None # 限额上限
|
||||
desc: str = "" # 规则描述(异常类型)
|
||||
|
||||
def validate(self, rest_days: int) -> bool:
|
||||
if self.rule_type == "固休":
|
||||
return rest_days == self.days
|
||||
if self.rule_type == "大小休":
|
||||
return self.days <= rest_days <= 8
|
||||
if self.rule_type == "限额":
|
||||
return rest_days <= self.max_days
|
||||
return True
|
||||
|
||||
|
||||
def _normalize_rest_days(v) -> int:
|
||||
try:
|
||||
s = str(v).strip()
|
||||
if s in ("", "nan", "None"):
|
||||
return -1
|
||||
if s.endswith(".0"):
|
||||
s = s[:-2]
|
||||
return int(float(s))
|
||||
except (TypeError, ValueError):
|
||||
return -1
|
||||
|
||||
|
||||
class LeaveRuleEngine:
|
||||
def __init__(self, size_rest_days=6, fixed_rest_days=5, quota_rest_days=8):
|
||||
self.size_rest_days = int(size_rest_days)
|
||||
self.fixed_rest_days = int(fixed_rest_days)
|
||||
self.quota_rest_days = int(quota_rest_days)
|
||||
|
||||
def query(self, unit: str, org_label: str = "", sequence: str = "") -> RestRule:
|
||||
if "技师" in sequence:
|
||||
return RestRule("限额", max_days=self.quota_rest_days,
|
||||
desc=f"当月排休不满足<={self.quota_rest_days}天规则")
|
||||
if unit == "金色湖畔事业部":
|
||||
return RestRule("固休", days=self.fixed_rest_days,
|
||||
desc=f"当月排休不满足={self.fixed_rest_days}天规则")
|
||||
if unit in config.GROUP_HEADQUARTER_UNITS:
|
||||
return RestRule("大小休", days=self.size_rest_days,
|
||||
desc=f"当月排休不满足>={self.size_rest_days}天<=8天规则")
|
||||
if unit == "金色印象事业部":
|
||||
if "事业部" in org_label:
|
||||
return RestRule("大小休", days=self.size_rest_days,
|
||||
desc=f"当月排休不满足>={self.size_rest_days}天<=8天规则")
|
||||
return RestRule("固休", days=self.fixed_rest_days,
|
||||
desc=f"当月排休不满足={self.fixed_rest_days}天规则")
|
||||
return RestRule("未知")
|
||||
|
||||
def check(self, unit, org_label, sequence, rest_days):
|
||||
rule = self.query(unit, org_label, sequence)
|
||||
days = _normalize_rest_days(rest_days)
|
||||
if rule.rule_type == "未知" or days < 0:
|
||||
return False, rule, days
|
||||
return (not rule.validate(days)), rule, days
|
||||
|
||||
|
||||
# ==================== 检查工具 ====================
|
||||
def _clean(v) -> str:
|
||||
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 _to_int(v, default=0) -> int:
|
||||
s = _clean(v)
|
||||
if not s:
|
||||
return default
|
||||
try:
|
||||
return int(float(s))
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def _norm_path(p: str) -> str:
|
||||
p = _clean(p).replace("\\", "/").strip("/")
|
||||
if p.startswith("集团/"):
|
||||
p = p[len("集团/"):]
|
||||
elif p == "集团":
|
||||
p = ""
|
||||
return p.strip("/")
|
||||
|
||||
|
||||
def _parse_date(s):
|
||||
s = _clean(s)[:10]
|
||||
if not s:
|
||||
return None
|
||||
try:
|
||||
return datetime.strptime(s, "%Y-%m-%d").date()
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _row_from_seal(rec: dict, month_display: str, abnormal_type: str) -> dict:
|
||||
return {
|
||||
"37工号": _clean(rec.get("base_code")),
|
||||
"姓名": _clean(rec.get("staff_name")),
|
||||
"月报检查月份": month_display,
|
||||
"异常类型": abnormal_type,
|
||||
"所属单位": _clean(rec.get("BELONG_UNIT_ORG_NAME")),
|
||||
"一级部门": _clean(rec.get("DEPT_ORG_ONE")),
|
||||
"二级部门": _clean(rec.get("DEPT_ORG_TWO")),
|
||||
"三级部门": _clean(rec.get("DEPT_ORG_THREE")),
|
||||
"四级部门": _clean(rec.get("DEPT_ORG_FOUR")),
|
||||
"五级部门": _clean(rec.get("DEPT_ORG_FIVE")),
|
||||
}
|
||||
|
||||
|
||||
def _resolve_org_label(rec: dict, org_name_map: Dict[str, str]) -> str:
|
||||
"""解析员工组织类型标签:部门全路径匹配组织表组织全路径 → 组织名称。
|
||||
匹配失败回退取路径最后一个节点名。"""
|
||||
path = _norm_path(rec.get("ORG_FULL_PATH"))
|
||||
if path and path in org_name_map:
|
||||
return org_name_map[path]
|
||||
if path:
|
||||
return path.split("/")[-1]
|
||||
return ""
|
||||
|
||||
|
||||
# ==================== 检查1:在职天数是否均排班 ====================
|
||||
def _calc_working_days(rec: dict, year: int, month: int) -> int:
|
||||
"""按需求文档规则计算当月在职天数(基于入职/离职时间)。"""
|
||||
month_days = calendar.monthrange(year, month)[1]
|
||||
first = date(year, month, 1)
|
||||
last = date(year, month, month_days)
|
||||
join_d = _parse_date(rec.get("join_date"))
|
||||
leave_d = _parse_date(rec.get("leaveOffice_date"))
|
||||
|
||||
def in_service(d):
|
||||
if join_d and d < join_d:
|
||||
return False
|
||||
if leave_d and d > leave_d:
|
||||
return False
|
||||
return True
|
||||
|
||||
in_first, in_last = in_service(first), in_service(last)
|
||||
if in_first and in_last:
|
||||
# 1号和月末都在职 = 全月在职,在职天数即为当月自然天数
|
||||
return month_days
|
||||
if in_first and not in_last:
|
||||
return (leave_d - first).days if leave_d else 0
|
||||
if not in_first and in_last:
|
||||
return (last - join_d).days if join_d else 0
|
||||
# 首尾都不在职:仅当入职、离职日期都落在本月内时按差计算;否则返回 0
|
||||
if join_d and leave_d and first <= join_d <= last and first <= leave_d <= last:
|
||||
return (leave_d - join_d).days
|
||||
return 0
|
||||
|
||||
|
||||
def check1(seal_rows: List[dict], year: int, month: int) -> List[dict]:
|
||||
month_display = f"{year:04d}-{month:02d}"
|
||||
rows = []
|
||||
for rec in seal_rows:
|
||||
wd = _calc_working_days(rec, year, month)
|
||||
yq = _to_int(rec.get("kq_stat_month_yq_work_day_in")) # 在职应勤工作日
|
||||
rest = _to_int(rec.get("kq_stat_cal_ext9")) # 休息天
|
||||
if wd - (yq + rest) != 0:
|
||||
rows.append(_row_from_seal(rec, month_display, TYPE_1))
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 检查2:排休天数验证 ====================
|
||||
def check2(seal_rows, org_name_map, seq_map, engine, year, month) -> List[dict]:
|
||||
month_display = f"{year:04d}-{month:02d}"
|
||||
rows = []
|
||||
for rec in seal_rows:
|
||||
unit = _clean(rec.get("BELONG_UNIT_ORG_NAME"))
|
||||
org_label = _resolve_org_label(rec, org_name_map)
|
||||
seq = seq_map.get(_clean(rec.get("base_code")), "")
|
||||
abnormal, rule, _days = engine.check(unit, org_label, seq, rec.get("kq_stat_cal_ext9"))
|
||||
if abnormal:
|
||||
rows.append(_row_from_seal(rec, month_display, rule.desc))
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 检查3:封存值是否为最新值 ====================
|
||||
def check3(diff_rows, seal_rows, diff_fields, year, month) -> List[dict]:
|
||||
month_display = f"{year:04d}-{month:02d}"
|
||||
if not diff_rows:
|
||||
return []
|
||||
seal_by_code = {_clean(r.get("base_code")): r for r in seal_rows}
|
||||
rows = []
|
||||
for dr in diff_rows:
|
||||
code = _clean(dr.get("base_code")) or _clean(dr.get("工号"))
|
||||
if any(_clean(dr.get(f)) for f in diff_fields) and code in seal_by_code:
|
||||
rows.append(_row_from_seal(seal_by_code[code], month_display, TYPE_3))
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 检查4:出勤天数验证 ====================
|
||||
def check4(seal_rows, shift_map, year, month) -> List[dict]:
|
||||
month_display = f"{year:04d}-{month:02d}"
|
||||
rows = []
|
||||
for rec in seal_rows:
|
||||
code = _clean(rec.get("base_code"))
|
||||
expected = shift_map.get(code)
|
||||
if expected is None:
|
||||
continue
|
||||
attend = _to_int(rec.get("kq_stat_cal_ext19"), default=-1) # 实际出勤天日
|
||||
if attend >= 0 and attend > expected:
|
||||
rows.append(_row_from_seal(rec, month_display, TYPE_4))
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 检查5:未封存名单 ====================
|
||||
def check5(seal_rows, in_service_records, year, month) -> List[dict]:
|
||||
month_display = f"{year:04d}-{month:02d}"
|
||||
seal_codes = {_clean(r.get("base_code")) for r in seal_rows}
|
||||
rows = []
|
||||
for rec in in_service_records:
|
||||
code = _clean(rec.get("工号"))
|
||||
if code and code not in seal_codes:
|
||||
rows.append({
|
||||
"37工号": code, "姓名": _clean(rec.get("姓名")),
|
||||
"月报检查月份": month_display, "异常类型": TYPE_5,
|
||||
"所属单位": _clean(rec.get("所属单位")),
|
||||
"一级部门": _clean(rec.get("一级部门")),
|
||||
"二级部门": _clean(rec.get("二级部门")),
|
||||
"三级部门": _clean(rec.get("三级部门")),
|
||||
"四级部门": _clean(rec.get("四级部门")),
|
||||
"五级部门": _clean(rec.get("五级部门")),
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 汇总编排 ====================
|
||||
def run_all_checks(*, seal_rows, org_name_map, seq_map, in_service_records,
|
||||
shift_map, engine, year, month, diff_rows=None, diff_fields=None,
|
||||
notes=None) -> dict:
|
||||
notes = list(notes or [])
|
||||
results = {
|
||||
1: check1(seal_rows, year, month),
|
||||
2: check2(seal_rows, org_name_map, seq_map, engine, year, month),
|
||||
3: check3(diff_rows or [], seal_rows, diff_fields or [], year, month),
|
||||
4: check4(seal_rows, shift_map, year, month),
|
||||
5: check5(seal_rows, in_service_records, year, month),
|
||||
}
|
||||
if diff_rows is None:
|
||||
notes.append("检查3「封存值是否为最新值」:对比接口数据未提供,本次跳过该检查")
|
||||
return {"rows": results, "notes": notes}
|
||||
@@ -0,0 +1,63 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""考勤月报封存检查 - Excel 报告导出(webhost 场景插件)
|
||||
|
||||
与 desktop/plugins/seal_check/report.py 保持同步(桌面版为单一真源)。
|
||||
|
||||
输出:考勤月报封存检查_{月份}_{时间戳}.xlsx(汇总 + 检查1~5 Sheet,空 Sheet 保留表头)
|
||||
"""
|
||||
import os
|
||||
from datetime import datetime
|
||||
from typing import Dict, List
|
||||
|
||||
from webhost.backend.plugins.seal_check import config
|
||||
from webhost.backend.plugins.seal_check.logic import OUTPUT_COLUMNS, TYPE_1, TYPE_3, TYPE_4, TYPE_5
|
||||
|
||||
CHECK_TAB_TITLES = {
|
||||
1: "检查1_在职天数排班异常",
|
||||
2: "检查2_排休天数异常",
|
||||
3: "检查3_封存非最新值",
|
||||
4: "检查4_出勤天数异常",
|
||||
5: "检查5_未封存名单",
|
||||
}
|
||||
|
||||
CHECK_DESCRIPTIONS = {
|
||||
1: TYPE_1,
|
||||
2: "当月排休不满足……天规则(动态)",
|
||||
3: TYPE_3,
|
||||
4: TYPE_4,
|
||||
5: TYPE_5,
|
||||
}
|
||||
|
||||
|
||||
def export_report(rows_map: Dict[int, List[dict]], month: str, notes: List[str] = None,
|
||||
save_dir: str = None) -> str:
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
raise RuntimeError("缺少 pandas / openpyxl 依赖,无法导出 Excel")
|
||||
|
||||
save_dir = save_dir or config.SAVE_DIR
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
path = os.path.join(save_dir, f"考勤月报封存检查_{month}_{ts}.xlsx")
|
||||
|
||||
with pd.ExcelWriter(path, engine="openpyxl") as writer:
|
||||
summary = []
|
||||
for i in range(1, 6):
|
||||
n = len(rows_map.get(i, []))
|
||||
summary.append({
|
||||
"检查项": CHECK_TAB_TITLES[i],
|
||||
"命中条数": n,
|
||||
"异常类型": CHECK_DESCRIPTIONS[i],
|
||||
"说明": "详见对应 Sheet" if n else "无异常",
|
||||
})
|
||||
if notes:
|
||||
summary.append({"检查项": "备注", "命中条数": len(notes),
|
||||
"异常类型": "", "说明": ";".join(notes)})
|
||||
pd.DataFrame(summary).to_excel(writer, sheet_name="汇总", index=False)
|
||||
|
||||
for i in range(1, 6):
|
||||
df = pd.DataFrame(rows_map.get(i, []), columns=OUTPUT_COLUMNS)
|
||||
df.to_excel(writer, sheet_name=CHECK_TAB_TITLES[i], index=False)
|
||||
|
||||
return path
|
||||
Reference in New Issue
Block a user