feat: 新增银行卡检查插件及相关依赖与配置文件

This commit is contained in:
2026-10-29 14:21:30 +08:00
parent 0a32518060
commit c77a26cd99
494 changed files with 66923 additions and 2714 deletions
+394
View File
@@ -0,0 +1,394 @@
# -*- 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 _gap_days(today, t2, covered_until):
"""上轮已处理积分日期与 T-2 之间漏处理的日期(限本月、早于 T-2)。
跳天运行(如隔几天才跑一次)时,中间日期的考勤数据大多已在上轮快照里,
按差值对比会因「差值=0」被漏掉,需按新增段口径全量补。
"""
if covered_until is None or covered_until >= t2 - timedelta(days=1):
return []
month_first = date(today.year, today.month, 1)
d = max(covered_until + timedelta(days=1), month_first)
days = []
while d < t2 and d.month == today.month:
days.append(d)
d += timedelta(days=1)
return days
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.9"
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, covered_until = pick_target_file(today, save_dir, force_file)
file_key = os.path.basename(target_path)
gap_days = _gap_days(today, t2, covered_until)
ctx.progress(30)
ctx.log(f"目标文件:{target_path}({'新批文件' if is_new_batch else '续用追加'})"
f",上轮积分日期:{covered_until or '未知'}", "INFO")
if gap_days:
ctx.log(f"检测到 {covered_until} 之后、T-2={t2} 之前漏处理日期:"
f"{'、'.join(d.strftime('%m-%d') for d in gap_days)},"
"本轮按新增段口径全量补齐", "WARN")
# 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, gap_days)
finally:
wv.close()
wv = None
gc.collect()
stats["new"], stats["fix"], stats["del"] = len(new_rows), len(fix_rows), len(del_rows)
stats["gap"] = len(gap_days)
ctx.progress(62)
ctx.log(f"积分计算结果:新增段 {len(new_rows)} 行(T-2={t2}"
f"{',含补漏 ' + '、'.join(d.strftime('%m-%d') for d in gap_days) if gap_days else ''})"
f",修正补 {len(fix_rows)} 行,修正删 {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:
if kind == "import":
# 跳天补漏后单次可能上万行,OPM 逐行处理易超时 → 按积分日期分批(每批约单日量)
groups = {}
for r in rows:
groups.setdefault(r[2].date(), []).append(r)
if len(groups) > 1:
ctx.log(f"{label} 共 {len(rows)} 行,按积分日期分 {len(groups)} 批上传", "INFO")
parts, failed, retried, existed = [], [], 0, 0
for d in sorted(groups):
chunk = groups[d]
res = self._upload_once(client, ctx, f"积分导入_{d:%m-%d}", chunk, kind)
if res["success"]:
item = f"{d:%m-%d} {len(chunk)} 行"
if res.get("first_error"):
retried += 1
item += "(重试后确认)"
elif res.get("kind") == "benign":
# 服务端提示已存在/无需处理:这批此前已导入过,不是本次新写入
existed += 1
item += "(已存在)"
parts.append(item)
else:
failed.append(f"{d:%m-%d}({res['message']})")
msg = ("分批成功:" + "、".join(parts)) if not failed \
else "失败批次:" + ";".join(failed)
if not failed and retried:
msg += f";其中 {retried} 批首传响应异常,已由重传结果确认"
if not failed and existed:
msg += f";其中 {existed} 批服务端提示已存在(此前已导入,本次未新增)"
results[label] = {"success": not failed, "message": msg}
else:
results[label] = self._upload_once(client, ctx, label, rows, kind)
res = results[label]
ctx.log(f"{label} 推送:{'成功' if res['success'] else '失败'}({res['message']})",
"INFO" if res["success"] else "ERROR")
return results
@staticmethod
def _upload_once(client, ctx, label, rows, kind):
"""单批上传,失败最多重传一次。
OPM 偶发返回非 JSON(HTML 登录页 / 空响应),此时无法确认是否已写入:
- 会话仍有效 → 原会话直接重传,不白做一次重登;
- 会话失效(拿到登录页 / 401) → 重登后重传;
- 重传若提示「已存在/未生成出勤积分」→ 判定首传其实已生效,如实记录而不是报失败。
"""
url = client.import_url if kind == "import" else client.delete_url
payload = build_kaoqin_bytes(rows)
res = client.upload(url, payload, f"{label}.xlsx")
if res["success"]:
return res
need_relogin = res.get("kind") == "notfound" or not client.is_session_valid()
ctx.log(f"{label} 第 1 次上传未确认成功:{res['message']}"
f"(会话{'已失效,重登后重试' if need_relogin else '仍有效,直接重试'})", "WARN")
if need_relogin:
try:
client.session = None
client.ensure_session()
except Exception as e:
return {"success": False, "message": f"{res['message']};重登失败:{e}"}
res2 = client.upload(url, payload, f"{label}.xlsx")
if res2["success"]:
if res2.get("kind") == "benign":
res2["message"] = (f"首传响应异常({res['message']}),重传提示已存在 → "
f"判定首传已生效:{res2['message']}")
res2["first_error"] = res["message"]
return res2
return {"success": False, "message": f"首传:{res['message']};重传:{res2['message']}"}
PLUGINS.append(Xq0033Plugin())