feat(plugin): 新增 XQ0006 周考勤异常处理、XQ0083 调动流程生效确认;其余插件累积改动
XQ0001 排班异常识别 / XQ0002 雇主险增减操作 / XQ0012 ERP 付款申请 / XQ0013 社保费用申报 / XQ0042 抖音平台核对 / XQ0084 银行卡更新:逻辑与界面 bundle 更新(含各自版本号变更)
This commit is contained in:
@@ -0,0 +1,278 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0083 插件 - 调动流程生效确认 主流程。
|
||||
|
||||
流程:
|
||||
1) 登录态预检;
|
||||
2) 拉取调动台账待处理记录(未生效 + 在用 + 主职);
|
||||
3) 来源=流程的记录只有流程已完成(002)才处理,申请中/已取消静默跳过;
|
||||
4) 对基础校验通过的员工统计「当月已生效调动次数」,执行 R3(超过上限转异常);
|
||||
5) dry_run=true(试算模式):不提交确认,明细表逐条给出「校验结论 + 校验原因」;
|
||||
dry_run=false 时:IfExist 预检 → 批量确认 → 回查 EXC_STATUS 校验是否生效;
|
||||
6) 输出 Excel(处理汇总 / 异常名单 / 已确认记录 / 跳过 / 全部明细,文件名带时间戳留档);
|
||||
7) 配置了钉钉 Webhook 时推送摘要。
|
||||
"""
|
||||
from datetime import date
|
||||
|
||||
from hr_sdk.errors import ApiError, HrError, SessionExpiredError
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
|
||||
from openpyxl.utils import get_column_letter
|
||||
|
||||
from .. import config
|
||||
from ..config import logger
|
||||
from ..data.move_api import MoveApi, month_bounds
|
||||
from ..logic import rules
|
||||
from .dingtalk_robot import send_markdown
|
||||
|
||||
_HEADER_FILL = PatternFill("solid", fgColor="1F4E79")
|
||||
_HEADER_FONT = Font(color="FFFFFF", bold=True)
|
||||
_TITLE_FONT = Font(bold=True, size=14)
|
||||
_THIN = Side(style="thin", color="BFBFBF")
|
||||
_BORDER = Border(left=_THIN, right=_THIN, top=_THIN, bottom=_THIN)
|
||||
_WRAP = Alignment(wrap_text=True, vertical="top")
|
||||
|
||||
_DETAIL_HEADERS = [
|
||||
("序号", 6), ("姓名", 11), ("工号", 12), ("调动生效日期", 13), ("调出单位", 22),
|
||||
("调出岗位", 16), ("现所属单位", 22), ("现岗位", 16), ("现职位序列", 16),
|
||||
("现技师工号", 12), ("来源", 9), ("流程状态", 11), ("状态", 9),
|
||||
("校验结论", 11), ("校验原因", 46), ("处理结果", 20),
|
||||
]
|
||||
|
||||
|
||||
def _item_row(item, index):
|
||||
return [
|
||||
index, item["staff_name"], item["base_code"], item["move_date"],
|
||||
item["pre_org"], item["pre_post"], item["org"], item["post"],
|
||||
item["sequence"], item["tech_code"], item["data_source"],
|
||||
item["process_status"], item["status"], rules.verdict(item),
|
||||
rules.verdict_reason(item), item["result"],
|
||||
]
|
||||
|
||||
|
||||
def _write_table(ws, headers, rows, widths=None, start_row=1):
|
||||
"""写入表头 + 数据(表头深蓝底白字、冻结首行、自动筛选、边框)。"""
|
||||
for col, name in enumerate(headers, 1):
|
||||
cell = ws.cell(row=start_row, column=col, value=name)
|
||||
cell.fill = _HEADER_FILL
|
||||
cell.font = _HEADER_FONT
|
||||
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||
cell.border = _BORDER
|
||||
width = widths[col - 1] if widths and col - 1 < len(widths) else None
|
||||
if width:
|
||||
ws.column_dimensions[get_column_letter(col)].width = width
|
||||
for r, row in enumerate(rows, start_row + 1):
|
||||
for c, value in enumerate(row, 1):
|
||||
cell = ws.cell(row=r, column=c, value=value)
|
||||
cell.border = _BORDER
|
||||
cell.alignment = _WRAP
|
||||
ws.freeze_panes = ws.cell(row=start_row + 1, column=1)
|
||||
if rows:
|
||||
ws.auto_filter.ref = f"A{start_row}:{get_column_letter(len(headers))}{start_row + len(rows)}"
|
||||
|
||||
|
||||
def _detail_sheet(ws, items):
|
||||
_write_table(ws, [h for h, _ in _DETAIL_HEADERS],
|
||||
[_item_row(item, i) for i, item in enumerate(items, 1)],
|
||||
[w for _, w in _DETAIL_HEADERS])
|
||||
|
||||
|
||||
def _write_summary(ws, stats, setting, today):
|
||||
ws["A1"] = "调动流程生效确认 · 处理汇总"
|
||||
ws["A1"].font = _TITLE_FONT
|
||||
ws.merge_cells("A1:B1")
|
||||
rows = [
|
||||
("执行日期", today.strftime("%Y-%m-%d")),
|
||||
("执行模式", "试算(只校验不确认)" if stats.get("dry_run") else "校验并确认"),
|
||||
("待处理记录", stats["total"]),
|
||||
("跳过(流程未完成/已取消)", stats["skipped"]),
|
||||
("提交确认", stats["submitted"]),
|
||||
("确认成功(已生效)", stats["confirmed"]),
|
||||
("异常(转入异常名单)", stats["abnormal"]),
|
||||
("待确认(仅校验未提交)", stats["pending"]),
|
||||
("当月已生效次数上限", f"{setting['max_moves_per_month']} 次/人"),
|
||||
("早于当月校验起始日", f"每月 {setting['early_month_day']} 号起"),
|
||||
("未来日期容差", f"今天 + {setting['future_days']} 天"),
|
||||
("品牌单位", "、".join(setting["brand_units"])),
|
||||
("免校验岗位单位", "、".join(setting["skip_unit_keywords"])),
|
||||
]
|
||||
_write_table(ws, ["指标", "数值"], rows, [26, 60], start_row=3)
|
||||
|
||||
|
||||
def _push_text(stats, path, dry_run):
|
||||
lines = [
|
||||
"### 调动流程生效确认",
|
||||
f"- 执行日期:{stats['today']}",
|
||||
f"- 待处理:**{stats['total']}** 条,跳过(流程未完成/已取消):{stats['skipped']} 条",
|
||||
f"- 已提交确认:**{stats['submitted']}** 条,确认生效:{stats['confirmed']} 条",
|
||||
f"- 仅校验未提交:{stats['pending']} 条" if dry_run else None,
|
||||
f"- 异常:**{stats['abnormal']}** 条",
|
||||
]
|
||||
if stats["abnormal"]:
|
||||
lines.append("")
|
||||
lines.append("**异常名单(前 10 条)**")
|
||||
for item in stats["abnormal_items"][:10]:
|
||||
reason = ";".join(item["reasons"])
|
||||
lines.append(f"- {item['staff_name']}({item['base_code'] or '-'})"
|
||||
f" {item['move_date']}:{reason}")
|
||||
if len(stats["abnormal_items"]) > 10:
|
||||
lines.append(f"- ……其余 {len(stats['abnormal_items']) - 10} 条见附件表")
|
||||
lines.append("")
|
||||
lines.append(f"结果文件:{path}")
|
||||
return "\n".join(line for line in lines if line is not None)
|
||||
|
||||
|
||||
def run_confirm(save_dir, push_webhook="", push_secret="", dry_run=False,
|
||||
progress=None, keep_files=config.DEFAULT_KEEP_FILES):
|
||||
"""执行一次调动流程生效确认(dry_run=True 为试算模式:只校验不确认),返回结果字典。"""
|
||||
progress = progress or (lambda pct: None)
|
||||
setting = config.settings()
|
||||
today = date.today()
|
||||
session = config.require_session()
|
||||
api = MoveApi(session)
|
||||
|
||||
progress(5)
|
||||
api.precheck()
|
||||
|
||||
progress(10)
|
||||
rows = api.fetch_pending()
|
||||
if setting["limit_rows"]:
|
||||
rows = rows[:setting["limit_rows"]]
|
||||
logger.info("按界面配置限制处理前 %d 条", setting["limit_rows"])
|
||||
|
||||
progress(20)
|
||||
seq_names = api.fetch_sequence_names()
|
||||
items = [rules.build_item(row, seq_names, today, setting) for row in rows]
|
||||
|
||||
# ---- R3:当月已生效次数(只对基础校验通过的员工查,减少请求) ----
|
||||
candidates = [it for it in items if it["status"] == rules.STATUS_PENDING]
|
||||
codes = sorted({it["base_code"] for it in candidates if it["base_code"]})
|
||||
month_first, month_last = month_bounds(today)
|
||||
effective_counts = {}
|
||||
for i, code in enumerate(codes, 1):
|
||||
effective_counts[code] = api.fetch_effective_count(code, month_first, month_last)
|
||||
progress(20 + int(40 * i / max(len(codes), 1)))
|
||||
blocked = rules.apply_month_limit(items, effective_counts, setting["max_moves_per_month"])
|
||||
if blocked:
|
||||
logger.warning("R3 当月调动超限 %d 条(转异常名单)", blocked)
|
||||
|
||||
# ---- 确认 / 试算 ----
|
||||
to_confirm = [it for it in items if it["status"] == rules.STATUS_PENDING]
|
||||
if dry_run:
|
||||
for item in to_confirm:
|
||||
item["result"] = "仅校验(未提交)"
|
||||
submitted = 0
|
||||
else:
|
||||
submitted = _do_confirm(api, to_confirm, progress)
|
||||
|
||||
progress(78)
|
||||
stats = _build_stats(items, today, submitted, dry_run)
|
||||
path = config.build_result_path(save_dir)
|
||||
_write_workbook(path, items, stats, setting, today)
|
||||
logger.info("结果已输出:%s", path)
|
||||
progress(90)
|
||||
|
||||
if (push_webhook or "").strip():
|
||||
push = send_markdown(push_webhook, push_secret,
|
||||
"调动流程生效确认结果",
|
||||
_push_text(stats, path, dry_run))
|
||||
else:
|
||||
push = {"success": False, "message": "未配置 Webhook"}
|
||||
|
||||
cleaned = config.cleanup_old_results(save_dir, keep_files, protect=path)
|
||||
progress(100)
|
||||
return {
|
||||
"total": stats["total"], "skipped": stats["skipped"], "submitted": submitted,
|
||||
"confirmed": stats["confirmed"], "abnormal": stats["abnormal"],
|
||||
"pending": stats["pending"], "path": path, "push": push, "cleaned": cleaned,
|
||||
"dry_run": dry_run,
|
||||
}
|
||||
|
||||
|
||||
def _do_confirm(api, to_confirm, progress):
|
||||
"""IfExist 预检 → 批量确认 → 回查 EXC_STATUS。返回提交条数。"""
|
||||
if not to_confirm:
|
||||
logger.info("没有需要提交确认的记录")
|
||||
return 0
|
||||
|
||||
power, ptype = api.fetch_prepare_power()
|
||||
ok, staff = api.if_exist([it["stru_id"] for it in to_confirm])
|
||||
if not ok:
|
||||
msg = f"预检拦截:{staff or '(未知)'} 存在未生效调动数据,本批放弃确认"
|
||||
for item in to_confirm:
|
||||
item["status"] = rules.STATUS_ABNORMAL
|
||||
item["reasons"].append(msg)
|
||||
logger.warning(msg)
|
||||
return 0
|
||||
|
||||
progress(64)
|
||||
move_ids = [it["move_id"] for it in to_confirm if it["move_id"]]
|
||||
try:
|
||||
api.confirm(move_ids, power, ptype)
|
||||
except SessionExpiredError:
|
||||
raise
|
||||
except (HrError, ApiError) as exc:
|
||||
msg = f"批量确认失败:{exc}"
|
||||
logger.error(msg)
|
||||
for item in to_confirm:
|
||||
item["status"] = rules.STATUS_ABNORMAL
|
||||
item["reasons"].append(msg)
|
||||
item["result"] = "确认失败"
|
||||
return 0
|
||||
logger.info("已提交批量确认 %d 条,回查生效状态……", len(move_ids))
|
||||
|
||||
progress(72)
|
||||
status_map = {}
|
||||
try:
|
||||
for row in api.fetch_by_ids(move_ids):
|
||||
status_map[str(row.get(config.F_MOVE_ID) or "").strip()] = \
|
||||
str(row.get(config.F_EXC_STATUS) or "").strip()
|
||||
except Exception as exc: # 回查失败不影响已提交事实
|
||||
logger.warning("确认后回查失败:%s", exc)
|
||||
|
||||
for item in to_confirm:
|
||||
exc_status = status_map.get(item["move_id"])
|
||||
if exc_status == config.EXC_STATUS_EFFECTIVE:
|
||||
item["status"] = "已确认"
|
||||
item["result"] = "已生效"
|
||||
elif exc_status is None:
|
||||
item["result"] = "已提交(未回查到状态,请平台复核)"
|
||||
logger.warning("%s(%s)确认后未回查到状态", item["staff_name"], item["base_code"])
|
||||
else:
|
||||
item["status"] = rules.STATUS_ABNORMAL
|
||||
item["reasons"].append(f"确认后未生效(EXC_STATUS={exc_status or '空'})")
|
||||
item["result"] = "确认失败"
|
||||
return len(move_ids)
|
||||
|
||||
|
||||
def _build_stats(items, today, submitted, dry_run):
|
||||
abnormal_items = [it for it in items if it["status"] == rules.STATUS_ABNORMAL]
|
||||
return {
|
||||
"today": today.strftime("%Y-%m-%d"),
|
||||
"dry_run": bool(dry_run),
|
||||
"total": len(items),
|
||||
"skipped": sum(1 for it in items if it["status"] == rules.STATUS_SKIP),
|
||||
"submitted": submitted,
|
||||
"confirmed": sum(1 for it in items if it["status"] == "已确认"),
|
||||
"abnormal": len(abnormal_items),
|
||||
"abnormal_items": abnormal_items,
|
||||
"pending": sum(1 for it in items if it["status"] == rules.STATUS_PENDING),
|
||||
}
|
||||
|
||||
|
||||
def _write_workbook(path, items, stats, setting, today):
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = config.SHEET_SUMMARY
|
||||
_write_summary(ws, stats, setting, today)
|
||||
|
||||
_detail_sheet(wb.create_sheet(config.SHEET_ABNORMAL),
|
||||
[it for it in items if it["status"] == rules.STATUS_ABNORMAL])
|
||||
_detail_sheet(wb.create_sheet(config.SHEET_CONFIRMED),
|
||||
[it for it in items if it["status"] == "已确认"])
|
||||
_detail_sheet(wb.create_sheet(config.SHEET_SKIPPED),
|
||||
[it for it in items if it["status"] == rules.STATUS_SKIP])
|
||||
_detail_sheet(wb.create_sheet(config.SHEET_ALL), items)
|
||||
|
||||
import os
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
wb.save(path)
|
||||
Reference in New Issue
Block a user