194 lines
9.4 KiB
Python
194 lines
9.4 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""XQ0065 插件 - 报告编排层:导出花名册/合同台账 → 10 条规则 → 单工作簿多 sheet → 可选钉钉摘要。"""
|
||
import os
|
||
from datetime import datetime
|
||
|
||
import pandas as pd
|
||
from openpyxl.styles import Alignment, Font, PatternFill
|
||
from openpyxl.utils import get_column_letter
|
||
|
||
from .. import config
|
||
from ..config import (
|
||
DEFAULT_SAVE_DIR, RESULT_NAME, SHEET_ABNORMAL, SHEET_CONTRACT, SHEET_CONTRACT_RAW,
|
||
SHEET_ROSTER_RAW, SHEET_SUMMARY, logger, require_session,
|
||
)
|
||
from ..data import hr_export
|
||
from ..logic.rules import clean_frames, run_all_rules
|
||
from .dingtalk_robot import send_markdown
|
||
|
||
|
||
def _rule_notes():
|
||
"""汇总 sheet 的规则口径说明(HR 自查依据),数值取本次生效配置。"""
|
||
setting = config.settings()
|
||
legal = "/".join(setting["legal_contract_types"])
|
||
whitelist = "/".join(setting["part_time_whitelist"]) or "无"
|
||
ages = f"女≥{setting['retire_age_female']}/男≥{setting['retire_age_male']}"
|
||
term_36, term_12 = setting["term_months_36"], setting["term_months_12"]
|
||
return {
|
||
"1 合同类型/用工类型": f"合法枚举仅 {legal};劳务协议、用工协议一律报出待 HR 确认;"
|
||
"全日制用工↔劳动合同、退休返聘人员↔超龄用工协议、实习生↔实习协议;"
|
||
f"兼职人员仅白名单({whitelist})放行",
|
||
"2 员工状态与星级": "试用期星级应为见习/代理;正式工星级不应为见习",
|
||
"3 手机号码": "手机号须为 11 位数字,且不得与紧急联系人电话(1/2)相同",
|
||
"4 紧急联系人": "联系人1 或 联系人2 至少一个完整:姓名/电话/关系非空、关系≠其他、联系人≠本人",
|
||
"5 地址完整性": "现居地址、身份证地址不得为空;身份证地址未含村/组/号/栋/室等门牌信息记「疑似」",
|
||
"6 身份证有效期": "有效期年限应为 "
|
||
+ "/".join(str(y) for y in setting["id_valid_years"])
|
||
+ " 年或长期(止期 9999-12-31)",
|
||
"7 身高体重": f"身高≥{setting['height_limit_cm']}cm 或 体重≥{setting['weight_limit_kg']}kg "
|
||
"即异常(满足其一)",
|
||
"8 技师工号": "门店技师序列的员工必须填写技师工号",
|
||
"9 所属部门": "所属部门应等于组织全路径最后一级",
|
||
"10 合同期限/达龄": f"达龄按合同起始日计龄({ages}):达龄应签 {term_12} 个月,"
|
||
"非 12 个月标记「疑似补足期限」;"
|
||
f"未达龄按序列(职能/经营={term_36} 个月,服务/技师={term_12} 个月);"
|
||
"无固定期跳过;入职当月合同起始应等于入职日期;合同起止/期限不得为空",
|
||
}
|
||
|
||
|
||
def _autofit(writer, sheet_name, df, max_width=46, min_width=8):
|
||
"""表头加粗 + 冻结首行 + 筛选 + 列宽自适应。"""
|
||
ws = writer.sheets[sheet_name]
|
||
ws.freeze_panes = "A2"
|
||
if len(df.columns):
|
||
ws.auto_filter.ref = ws.dimensions
|
||
header_fill = PatternFill("solid", fgColor="DDEBF7")
|
||
for col_idx, column in enumerate(df.columns, start=1):
|
||
cell = ws.cell(row=1, column=col_idx)
|
||
cell.font = Font(bold=True)
|
||
cell.fill = header_fill
|
||
cell.alignment = Alignment(horizontal="center", vertical="center")
|
||
width = len(str(column)) * 2 + 2
|
||
if len(df):
|
||
sample = df[column].astype(str).head(200)
|
||
width = max(width, int(sample.str.len().max() * 1.2) + 2)
|
||
ws.column_dimensions[get_column_letter(col_idx)].width = max(
|
||
min_width, min(max_width, width))
|
||
|
||
|
||
def save_workbook(summary_df, abnormal_df, contract_view, roster_df, contract_df,
|
||
output_path):
|
||
"""单工作簿多 sheet 输出,返回绝对路径。"""
|
||
os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True)
|
||
try:
|
||
with pd.ExcelWriter(output_path, engine="openpyxl") as writer:
|
||
summary_df.to_excel(writer, sheet_name=SHEET_SUMMARY, index=False)
|
||
abnormal_df.to_excel(writer, sheet_name=SHEET_ABNORMAL, index=False)
|
||
contract_view.to_excel(writer, sheet_name=SHEET_CONTRACT, index=False)
|
||
roster_df.to_excel(writer, sheet_name=SHEET_ROSTER_RAW, index=False)
|
||
contract_df.to_excel(writer, sheet_name=SHEET_CONTRACT_RAW, index=False)
|
||
for sheet, df in ((SHEET_SUMMARY, summary_df), (SHEET_ABNORMAL, abnormal_df),
|
||
(SHEET_CONTRACT, contract_view), (SHEET_ROSTER_RAW, roster_df),
|
||
(SHEET_CONTRACT_RAW, contract_df)):
|
||
_autofit(writer, sheet, df)
|
||
except PermissionError:
|
||
raise RuntimeError(
|
||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(output_path)}」后重试。"
|
||
f"无需重查数据。")
|
||
except OSError as e:
|
||
raise RuntimeError(f"导出失败:无法写入文件「{output_path}」({e}),请检查磁盘空间或目录权限")
|
||
|
||
logger.info("检查结果已保存:%s", output_path)
|
||
return os.path.abspath(output_path)
|
||
|
||
|
||
def build_push_text(summary_df, abnormal_count, person_count, path):
|
||
"""构造群机器人推送文案(Markdown)。"""
|
||
lines = ["### EHR系统花名册检查完成",
|
||
f"- 异常 **{abnormal_count}** 条,涉及 **{person_count}** 人",
|
||
f"- 结果文件:`{path}`"]
|
||
top = summary_df[summary_df["异常条数"] > 0]
|
||
if len(top):
|
||
lines.append("- 各检查项命中:" + ";".join(
|
||
f"{r['检查项']} {r['异常条数']} 条" for _, r in top.iterrows()))
|
||
lines.append("- 附件请到上述路径自取(群机器人不支持发文件)")
|
||
return "\n".join(lines)
|
||
|
||
|
||
def run_roster_check(save_dir=None, push_webhook="", push_secret="", progress=None):
|
||
"""执行花名册检查主流程(10 条规则)。
|
||
|
||
Returns:
|
||
dict: {path, stats, abnormal_count, person_count, excluded, roster_count,
|
||
contract_count, push}
|
||
"""
|
||
def _step(pct):
|
||
if progress:
|
||
try:
|
||
progress(pct)
|
||
except Exception:
|
||
pass
|
||
|
||
save_dir = (save_dir or "").strip() or DEFAULT_SAVE_DIR
|
||
download_dir = os.path.join(save_dir, "download")
|
||
output_path = os.path.join(save_dir, RESULT_NAME)
|
||
today = datetime.now().date()
|
||
|
||
# ---- 1. 登录态预检 ----
|
||
_step(5)
|
||
session = require_session()
|
||
hr_export.precheck(session)
|
||
_step(10)
|
||
|
||
# ---- 2. 导出在职花名册 + 合同台账(生效中/待生效) ----
|
||
roster_df = hr_export.export_roster(session, download_dir)
|
||
_step(55)
|
||
contract_df = hr_export.export_contracts(session, download_dir)
|
||
_step(70)
|
||
|
||
# ---- 3. 清洗 + 规则检查 ----
|
||
roster, contract, excluded = clean_frames(roster_df, contract_df)
|
||
findings_df, contract_view, stats_df = run_all_rules(roster, contract, today=today)
|
||
_step(85)
|
||
|
||
# ---- 4. 汇总 + 导出 ----
|
||
setting = config.settings()
|
||
stats_df["口径说明"] = stats_df["检查项"].map(_rule_notes()).fillna("")
|
||
disabled = [label for key, label in config.CHECK_ITEMS if key not in setting["checks"]]
|
||
scope = (f"统计日期 {today};花名册在职 {len(roster)} 人、合同台账 {len(contract)} 条"
|
||
f"(已剔除姓名含 {'/'.join(setting['exclude_name_keywords'])} 的账号 {excluded} 人)")
|
||
if disabled:
|
||
scope += f";未启用检查项:{'、'.join(disabled)}"
|
||
total_row = pd.DataFrame([{
|
||
"检查项": "合计",
|
||
"异常条数": len(findings_df),
|
||
"涉及员工数": findings_df["工号"].nunique(),
|
||
"疑似条数": int((findings_df["是否疑似"] == "是").sum()),
|
||
"口径说明": scope,
|
||
}])
|
||
summary_df = pd.concat([stats_df, total_row], ignore_index=True)
|
||
path = save_workbook(summary_df, findings_df, contract_view, roster, contract, output_path)
|
||
_step(95)
|
||
|
||
# ---- 5. 群机器人摘要推送(可选) ----
|
||
push_result = {"success": False, "message": "未配置 Webhook,跳过推送"}
|
||
if (push_webhook or "").strip():
|
||
text = build_push_text(summary_df, len(findings_df),
|
||
findings_df["工号"].nunique(), path)
|
||
push_result = send_markdown(push_webhook, push_secret, "花名册检查完成", text)
|
||
if not push_result.get("success"):
|
||
logger.warning("结果摘要推送失败(不影响导出):%s", push_result.get("message"))
|
||
_step(100)
|
||
|
||
logger.info("=" * 60)
|
||
logger.info("【EHR系统花名册检查完成】")
|
||
logger.info(" 花名册在职 %d 人;合同台账 %d 条", len(roster), len(contract))
|
||
logger.info(" 异常 %d 条,涉及 %d 人", len(findings_df), findings_df["工号"].nunique())
|
||
for _, r in stats_df.iterrows():
|
||
if r["异常条数"]:
|
||
logger.info(" %s:%d 条(%d 人,疑似 %d)", r["检查项"], r["异常条数"],
|
||
r["涉及员工数"], r["疑似条数"])
|
||
logger.info(" 结果文件:%s", path)
|
||
logger.info("=" * 60)
|
||
|
||
return {
|
||
"path": path,
|
||
"stats": stats_df,
|
||
"abnormal_count": len(findings_df),
|
||
"person_count": int(findings_df["工号"].nunique()),
|
||
"excluded": excluded,
|
||
"roster_count": len(roster),
|
||
"contract_count": len(contract),
|
||
"push": push_result,
|
||
}
|