Files
37duAutomation/plugins/XQ0001-0100/XQ0033 门店管理及服务岗出勤积分更新/__init__.py
T

306 lines
14 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 -*-
"""XQ0033 门店管理及服务岗出勤积分更新 插件入口。
两个开关各自独立,可组合执行:
第一步 do_update(更新工作簿):
1) HR 考勤统计报表分页抓取(当月)+ 离职当月再入职台账 + 换工号历史工号;
2) 踢除再入职人员无效积分段;选择目标批次文件(优先 T-2 续用,否则复制新建);
3) 写「考勤统计报表」+ 快照滚动 + 「当月再入职名单」→ COM 全量重算(A 列圈人生效);
4) 读 A 列"正确"行 → 写「考勤--今日导出」+「对比结果」值区 → COM 重算(差值/镜像生效);
5) 读对比结果算新增段/修正段 → 写「积分导入」「积分删除」(含历史新增段保护)
→ COM 收尾重算保存。
第二步 do_push(推送系统):
读取工作簿积分导入/删除表 → OPM 登录 → 上传(地址固定,账号密码由界面配置)。
登录态:platform = hr(更新步骤必需);OPM 为插件内自包含登录(账号密码由界面配置)。
"""
import gc
import os
import time
from datetime import date, timedelta
import openpyxl
from webhost.backend.plugins.base import ScenePlugin, PLUGINS
from . import config
from .data.hr_client import HRClient, report_row_to_list
from .data.opm_client import OPMClient, build_kaoqin_bytes, read_point_sheet
from .logic.recalc import recalc_target
from .logic.rejoin_gap import blank_rejoin_gap
from .logic.state_store import load_state, save_state
from .logic.target_file import pick_latest_file, pick_target_file
from .logic.workbook import (copy_today_to_prev, ensure_sheets, read_compare_results,
select_report_rows, write_compare_values, write_delete_sheet,
write_import_sheet, write_rejoin_sheet, write_report_sheet,
write_today_export)
from .report.summary import build_summary
def _log_workbook_shape(ctx, path, wb):
"""输出工作簿规模诊断:openpyxl 内存占用与「已存在单元格数」成正比。"""
try:
size_mb = os.path.getsize(path) / 1024 / 1024
except OSError:
size_mb = 0.0
parts, total, bloated = [], 0, []
for ws in wb.worksheets:
cells = len(getattr(ws, "_cells", None) or {})
total += cells
parts.append(f"{ws.title} {ws.max_row}行×{ws.max_column}列")
if ws.max_row > 50000:
bloated.append(f"{ws.title}({ws.max_row}行)")
ctx.log(f"工作簿 {size_mb:.1f}MB,已存在单元格 {total} 个:" + ",".join(parts), "INFO")
if bloated:
ctx.log("模板 used range 异常膨胀:" + "、".join(bloated) +
",建议在 WPS 中删除多余空白行并清除整列格式后另存,可显著降低内存占用", "WARN")
class Xq0033Plugin(ScenePlugin):
"""门店管理及服务岗出勤积分更新(需求 XQ0033)。"""
id = "xq0033"
name = "门店管理及服务岗出勤积分更新"
version = "1.0.4"
description = (
"拉取 HR 当月考勤统计报表并按 A 列公式圈人,滚动今日/前一日快照做逐日差值,"
"自动更新积分工作簿(考勤统计报表 / 当月再入职名单 / 积分导入 / 积分删除,"
"COM 全量重算),可选将积分导入与删除表推送至 OPM 平台。")
platform = "hr"
uses_month = False
capabilities = ["xq0033"]
permissions = {"platforms": ["hr"]}
fields = {
"save_dir": {
"type": "string", "title": "工作簿目录",
"default": config.DEFAULT_SAVE_DIR,
"description": "积分工作簿(员工出勤及遵章积分导入*.xlsx)所在目录",
},
"target_file": {
"type": "string", "title": "指定工作簿", "default": "",
"description": "留空 = 自动选择(优先文件名含 T-2 的批次,否则复制最新文件新建批次)",
},
"do_update": {
"type": "boolean", "title": "第一步:更新工作簿", "default": True,
"description": "拉取 HR 报表并写入工作簿(积分导入/积分删除/当月再入职名单)",
},
"do_push": {
"type": "boolean", "title": "第二步:推送系统", "default": False,
"description": "读取工作簿积分导入/积分删除表上传到 OPM 平台(正式写入生产积分数据);"
"只看名单请只开第一步",
},
"opm_username": {
"type": "string", "title": "OPM 账号", "default": "",
"description": "OPM 平台登录账号(仅保存在本机)",
},
"opm_password": {
"type": "string", "title": "OPM 密码", "format": "password", "default": "",
"description": "OPM 平台登录密码(仅保存在本机,明文存储)",
},
}
# ==================== 入口 ====================
def run(self, fields: dict, ctx):
config.set_log(ctx.log)
started = time.time()
today = date.today()
t2 = today - timedelta(days=2)
save_dir = (fields.get("save_dir") or "").strip() or config.DEFAULT_SAVE_DIR
force_file = (fields.get("target_file") or "").strip() or None
do_update = bool(fields.get("do_update", True))
do_push = bool(fields.get("do_push", False))
if not do_update and not do_push:
raise RuntimeError("未选择执行步骤:请至少勾选「第一步:更新工作簿」或「第二步:推送系统」")
ctx.log(f"===== 门店管理及服务岗出勤积分更新启动:运行日 {today},积分日期 T-2={t2},"
f"更新工作簿={'是' if do_update else '否'},推送系统={'是' if do_push else '否'} =====",
"INFO")
notes = []
stats = {"update": do_update, "report_rows": 0, "selected": 0, "new": 0, "fix": 0,
"del": 0, "rejoin_new": 0, "rejoin_total": 0, "cleared": 0}
target_path = None
push_results = None
if do_update:
target_path = self._update(fields, ctx, today, t2, save_dir, force_file, stats)
if do_push:
base_pct = 80 if do_update else 20
try:
if not target_path:
ctx.progress(base_pct)
target_path = pick_latest_file(save_dir, force_file)
ctx.log(f"推送文件:{target_path}", "INFO")
push_results = self._push(target_path, fields, ctx, base_pct)
except Exception as e:
if not do_update:
raise
push_results = {"上传": {"success": False, "message": str(e)}}
notes.append(f"OPM 推送未完成(工作簿已更新):{e}")
ctx.log(f"OPM 推送失败(工作簿已更新):{e}", "ERROR")
ctx.progress(100)
summary, detail = build_summary(today, t2, target_path, stats, push_results)
if notes:
summary += "\n注意事项:\n- " + "\n- ".join(notes)
ctx.log(f"===== 完成,总耗时 {time.time() - started:.1f} 秒 =====", "INFO")
return {"summary": summary, "notes": notes, "detail": detail, "path": target_path}
# ==================== 第一步:更新工作簿 ====================
def _update(self, fields, ctx, today, t2, save_dir, force_file, stats):
ctx.progress(5)
try:
config.set_session(ctx.get_session("hr"))
config.set_user_id(ctx.get_user_id("hr"))
except Exception as e:
raise RuntimeError("未获取到 HR 登录态,请先在宿主完成 HR 登录后重试") from e
config.set_refresh(lambda: (ctx.get_session("hr"), ctx.get_user_id("hr")))
client = HRClient(config.get_session(), config.get_user_id(), config.refresh_session)
client.ensure_user()
# 1. 当月考勤统计报表(分页抓取,进度按页推进)
month = f"{today.year}-{today.month:02d}"
ctx.log(f"拉取 {month} 考勤统计报表……", "INFO")
def on_page(page_no, total_page):
total = max(1, int(total_page or 1))
ctx.progress(min(18, 8 + int(10 * page_no / total)))
raw_rows = client.fetch_all_attendance(month, on_page=on_page)
if not raw_rows:
raise RuntimeError(f"考勤统计报表 {month} 无数据,请检查月份或权限")
report_rows = [report_row_to_list(rec) for rec in raw_rows]
stats["report_rows"] = len(report_rows)
ctx.progress(18)
ctx.log(f"考勤统计报表共 {len(report_rows)} 人", "INFO")
# 2. 离职当月再入职台账 + 换工号历史工号 → 踢除无效积分段
rejoin_rows = client.fetch_all_rejoin_ledger(today)
stats["rejoin_total"] = len(rejoin_rows)
ctx.progress(22)
ctx.log(f"离职当月再入职台账共 {len(rejoin_rows)} 人", "INFO")
old_codes_map = client.build_rejoin_old_codes(rejoin_rows) if rejoin_rows else {}
ctx.progress(26)
stats["cleared"] = blank_rejoin_gap(report_rows, rejoin_rows, old_codes_map)
if stats["cleared"]:
ctx.log(f"已踢除离职当月再入职人员无效积分段 {stats['cleared']} 个考勤状态", "INFO")
# 3. 选择目标批次文件
target_path, is_new_batch = pick_target_file(today, save_dir, force_file)
file_key = os.path.basename(target_path)
ctx.progress(30)
ctx.log(f"目标文件:{target_path}({'新批文件' if is_new_batch else '续用追加'})", "INFO")
# 4. 全程只加载一次工作簿(大体积模板多次全量加载会触发 MemoryError),
# 写操作复用同一 wb;需要公式缓存值时另开 read_only 轻量读取。
wb = openpyxl.load_workbook(target_path, data_only=False)
_log_workbook_shape(ctx, target_path, wb)
try:
ensure_sheets(wb)
write_report_sheet(wb, report_rows, today.year, today.month)
copy_today_to_prev(wb)
stats["rejoin_new"] = write_rejoin_sheet(wb, rejoin_rows)
wb.save(target_path)
ctx.progress(34)
# COM 重算(A 列圈人生效)
recalc_target(target_path)
ctx.progress(40)
# 5. 圈人:read_only 读 A 列="正确" 的行
wv = openpyxl.load_workbook(target_path, data_only=True, read_only=True)
try:
sel_rows = select_report_rows(wv)
finally:
wv.close()
wv = None
gc.collect()
if not sel_rows:
raise RuntimeError("考勤统计报表 A 列无「正确」行,圈人公式判定异常,请检查模板")
stats["selected"] = len(sel_rows)
ctx.progress(46)
ctx.log(f"圈人公式命中 {len(sel_rows)} 人(已排除岗位:"
f"{'、'.join(sorted(config.EXCLUDE_POSTS))})", "INFO")
# 写今日导出 + 对比结果值区 → COM 重算(差值/镜像生效)
write_today_export(wb, sel_rows)
write_compare_values(wb, sel_rows)
wb.save(target_path)
ctx.progress(50)
recalc_target(target_path)
ctx.progress(56)
# 6. 读对比结果 → 新增段 / 修正补 / 修正删
wv = openpyxl.load_workbook(target_path, data_only=True, read_only=True)
try:
new_rows, fix_rows, del_rows = read_compare_results(wv, today, t2)
finally:
wv.close()
wv = None
gc.collect()
stats["new"], stats["fix"], stats["del"] = len(new_rows), len(fix_rows), len(del_rows)
ctx.progress(62)
ctx.log(f"积分计算结果:新增段 {len(new_rows)} 行({t2}),修正补 {len(fix_rows)} 行,"
f"修正删 {len(del_rows)} 行", "INFO")
# 7. 写积分导入 / 积分删除(新增段保护 + 修正段全月刷新)→ COM 收尾重算
state_file = config.state_path(os.path.dirname(target_path))
state = load_state(state_file)
write_import_sheet(wb, today, t2, new_rows, fix_rows, state, file_key, is_new_batch)
write_delete_sheet(wb, today, t2, del_rows)
save_state(state_file, state)
wb.save(target_path)
ctx.progress(68)
recalc_target(target_path)
ctx.progress(78)
finally:
wb.close()
wb = None
gc.collect()
return target_path
# ==================== 第二步:推送 OPM ====================
def _push(self, path, fields, ctx, base):
ctx.log(f"读取推送清单:{path}", "INFO")
import_rows = read_point_sheet(path, config.SHEET_IMPORT)
del_rows = read_point_sheet(path, config.SHEET_DELETE)
ctx.progress(min(96, base + 4))
ctx.log(f"积分导入 {len(import_rows)} 行,积分删除 {len(del_rows)} 行", "INFO")
tasks = (("积分导入", import_rows, "import"), ("积分删除", del_rows, "delete"))
results, valid = {}, []
for label, rows, kind in tasks:
if rows:
valid.append((label, rows, kind))
else:
results[label] = {"success": None, "message": "无数据,跳过"}
if not valid:
ctx.log("两表均无有效数据,无可推送", "WARN")
return results
username = (fields.get("opm_username") or "").strip()
password = (fields.get("opm_password") or "").strip()
if not username or not password:
raise RuntimeError("未配置 OPM 账号或密码,请在插件界面填写后重试")
client = OPMClient(config.DEFAULT_OPM_URL, username, password)
client.ensure_session()
ctx.progress(min(96, base + 8))
for label, rows, kind in valid:
url = client.import_url if kind == "import" else client.delete_url
res = client.upload(url, build_kaoqin_bytes(rows), f"{label}.xlsx")
results[label] = res
ctx.log(f"{label} 推送:{'成功' if res['success'] else '失败'}({res['message']})",
"INFO" if res["success"] else "ERROR")
return results
PLUGINS.append(Xq0033Plugin())