546 lines
31 KiB
Python
546 lines
31 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""XQ0033 门店管理及服务岗出勤积分更新 插件入口。
|
||
|
||
日期基准:积分日期 T-2 = 运行日 - 2;**所有「月」窗口(报表月份 / 月首 / 再入职台账区间 /
|
||
批次文件名)一律锚定 T-2 所在月**。月初 1、2 号运行时 T-2 落在上个月,本轮自动延续上月批次
|
||
接着跑(例:11-01 跑 10 月报表 → 生成 前缀1030.xlsx,补上 10-30 的积分;11-02 补 10-31),
|
||
既不因「本月报表没数据」直接失败,也不会漏掉月末两天的积分。
|
||
跨月首轮(T-2 已进入新月份)时上一月的「今日/前一日导出」快照与本月日列毫无对应关系,
|
||
两份快照一律清空重建(见 logic/workbook.reset_snapshots):前一日镜像恒为 0,
|
||
月首至 T-3 的差值 = 今日镜像 → 全部转为补导入,本月首轮自然补齐月头几天;
|
||
若照旧平移上月快照,差值会变成「本月 day N - 上月 day N」,既有漏补也有凭空删积分。
|
||
前一日快照来源:优先取「文件名积分日期段含 T-3」的上轮批次文件的今日导出(按日期取,
|
||
不是取本文件旧快照——旧文件被 WPS 另存后 mtime 会变、同一天重跑会把本文件快照改写,
|
||
都会让差值错位乃至丢行);找不到上轮文件时退化为文件内快照平滚。
|
||
|
||
两个开关各自独立,可组合执行:
|
||
第一步 do_update(更新工作簿):
|
||
1) HR 考勤统计报表分页抓取(T-2 所在月)+ 离职当月再入职台账 + 换工号历史工号;
|
||
2) 标记再入职人员「再入职日之前」的不操作段(不导入、不删除);选择目标批次文件
|
||
(优先 T-2 续用,否则复制新建);
|
||
3) 写「考勤统计报表」+ 快照滚动(前一日快照取 T-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 RejoinGuard
|
||
from .logic.state_store import load_state, save_state
|
||
from .logic.target_file import pick_latest_file, pick_prev_file, pick_target_file
|
||
from .logic.workbook import (copy_file_today_to_prev, copy_today_to_prev, ensure_sheets,
|
||
read_compare_results, read_report_month, reset_snapshots,
|
||
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(t2, covered_until):
|
||
"""上轮已处理积分日期与 T-2 之间漏处理的日期(限 T-2 所在月、早于 T-2)。
|
||
|
||
跳天运行(如隔几天才跑一次)时,中间日期的考勤数据大多已在上轮快照里,
|
||
按差值对比会因「差值=0」被漏掉,需按新增段口径全量补。
|
||
月份窗口取「T-2 所在月」:月初运行时 T-2 属上月,补漏也要在上月范围内找。
|
||
"""
|
||
if covered_until is None or covered_until >= t2 - timedelta(days=1):
|
||
return []
|
||
month_first = date(t2.year, t2.month, 1)
|
||
d = max(covered_until + timedelta(days=1), month_first)
|
||
days = []
|
||
while d < t2 and (d.year, d.month) == (t2.year, t2.month):
|
||
days.append(d)
|
||
d += timedelta(days=1)
|
||
return days
|
||
|
||
|
||
def _is_new_month(file_month, covered_until, t2):
|
||
"""目标文件里现存数据是否属于「上一个月」(跨月首轮 → 上一月快照作废)。
|
||
|
||
优先用「考勤统计报表」B2 标题里的月份(插件每轮都会写),标题缺失时退回
|
||
「来源文件名推断的上一轮积分日期」(自动选文件时才有),两者都拿不到时按
|
||
「未跨月」处理,保持原来的快照平滚行为,不做无依据的清空。
|
||
"""
|
||
target = (t2.year, t2.month)
|
||
if file_month:
|
||
return file_month != target
|
||
if covered_until:
|
||
return (covered_until.year, covered_until.month) != target
|
||
return False
|
||
|
||
|
||
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.19"
|
||
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, "report_month": "",
|
||
"selected": 0, "new": 0, "fix": 0, "del": 0, "gap": 0,
|
||
"rejoin_new": 0, "rejoin_total": 0, "rejoin_skip": 0,
|
||
"rejoin_skipped_rows": 0, "rejoin_skip_desc": []}
|
||
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. 积分日期 T-2 所在月的考勤统计报表(分页抓取,进度按页推进)
|
||
# 月初(1、2 号)运行时 T-2 落在上个月,必须拉上月报表 + 按上月窗口计算,
|
||
# 否则既拉不到当月数据(11-01 拉 11 月报表必然为空),上月最后两天的积分也会整段漏掉。
|
||
month_first = date(t2.year, t2.month, 1)
|
||
month = f"{t2.year}-{t2.month:02d}"
|
||
if (t2.year, t2.month) != (today.year, today.month):
|
||
ctx.log(f"积分日期 T-2={t2} 属上月:本轮延续 {month} 批次"
|
||
f"(报表月份 / 月首窗口 / 再入职台账均按 {month} 计算)", "INFO")
|
||
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} 无数据(积分日期 {t2} 所在月),"
|
||
"请检查月份或权限")
|
||
report_rows = [report_row_to_list(rec) for rec in raw_rows]
|
||
stats["report_rows"] = len(report_rows)
|
||
stats["report_month"] = month
|
||
ctx.progress(18)
|
||
ctx.log(f"考勤统计报表共 {len(report_rows)} 人", "INFO")
|
||
|
||
# 2. 离职当月再入职台账 + 换工号历史工号 → 标记「再入职日之前」的不操作段
|
||
# 台账窗口 = [T-2 所在月1日, 今天](月初补上月时也覆盖上月离职人员)
|
||
rejoin_rows = client.fetch_all_rejoin_ledger(today, month_first)
|
||
stats["rejoin_total"] = len(rejoin_rows)
|
||
ctx.progress(22)
|
||
ctx.log(f"离职当月再入职台账共 {len(rejoin_rows)} 人"
|
||
f"(离职日期 ∈ [{month_first}, {today}])", "INFO")
|
||
|
||
old_codes_map = client.build_rejoin_old_codes(rejoin_rows) if rejoin_rows else {}
|
||
ctx.progress(26)
|
||
guard = RejoinGuard(rejoin_rows, old_codes_map, t2)
|
||
stats["rejoin_skip_desc"] = guard.describe()
|
||
stats["rejoin_skip"] = len(stats["rejoin_skip_desc"])
|
||
if stats["rejoin_skip"]:
|
||
ctx.log("再入职人员「再入职日之前」的积分一律不操作(不导入、不删除):"
|
||
+ ";".join(stats["rejoin_skip_desc"]), "INFO")
|
||
|
||
# 3. 选择目标批次文件(同时据来源文件名推断上轮已处理的积分日期)
|
||
t3 = t2 - timedelta(days=1)
|
||
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(t2, covered_until)
|
||
# 上一轮批次文件(文件名积分日期段含 T-3)→ 本批「考勤-前一日导出」的数据来源。
|
||
# 按日期取而不是拿本文件旧快照:旧文件被 WPS 另存 / 同一天重跑都会让本文件快照错位。
|
||
prev_src = None
|
||
if not force_file:
|
||
prev_src = pick_prev_file(save_dir, t3)
|
||
if prev_src and os.path.abspath(prev_src) == os.path.abspath(target_path):
|
||
prev_src = None # 目标文件自身已含 T-3(跨日批次续跑)→ 文件内平滚即可
|
||
ctx.progress(30)
|
||
ctx.log(f"目标文件:{target_path}({'新批文件' if is_new_batch else '续用追加'})"
|
||
f",上轮积分日期:{covered_until or '未知'}", "INFO")
|
||
if prev_src:
|
||
ctx.log(f"上轮批次文件(含 T-3={t3}):{os.path.basename(prev_src)},"
|
||
"其「考勤--今日导出」作为本批前一日快照", "INFO")
|
||
elif not force_file:
|
||
ctx.log(f"未找到文件名含 T-3({t3:%m%d}) 的上轮文件,前一日快照退化为本文件内平滚", "WARN")
|
||
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)
|
||
# 快照滚动的月份判定必须在覆写报表前读(B2 标题 = 文件现存数据所属月)
|
||
file_month = read_report_month(wb)
|
||
write_report_sheet(wb, report_rows, t2.year, t2.month)
|
||
if _is_new_month(file_month, covered_until, t2):
|
||
old_txt = f"{file_month[0]}-{file_month[1]:02d}" if file_month else "上轮批次"
|
||
ctx.log(f"目标文件原数据属 {old_txt},本轮积分日期 {t2} 已跨月:"
|
||
"「考勤--今日导出」「考勤-前一日导出」清空重建——前一日快照只在本月内有效,"
|
||
"月首至 T-3 各天差值按今日镜像全量补导入(不与上月同日数据相减)", "INFO")
|
||
reset_snapshots(wb)
|
||
elif prev_src:
|
||
try:
|
||
copy_file_today_to_prev(wb, prev_src)
|
||
except Exception as e:
|
||
ctx.log(f"读取上轮文件快照失败({e}),退化为本文件内平滚", "WARN")
|
||
copy_today_to_prev(wb)
|
||
else:
|
||
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, t2, gap_days)
|
||
finally:
|
||
wv.close()
|
||
wv = None
|
||
gc.collect()
|
||
# 再入职人员「再入职日之前」的积分一律不操作:报表原样保留、旧导入行不动,
|
||
# 因此新增段 / 修正补 / 修正删三类行都要按同一口径过滤掉——既不重复导入,
|
||
# 也不生成删除行去扣掉其在职期间已生效的积分。
|
||
before = len(new_rows) + len(fix_rows) + len(del_rows)
|
||
new_rows = guard.allow(new_rows)
|
||
fix_rows = guard.allow(fix_rows)
|
||
del_rows = guard.allow(del_rows)
|
||
stats["rejoin_skipped_rows"] = before - (len(new_rows) + len(fix_rows) + len(del_rows))
|
||
stats["new"], stats["fix"], stats["del"] = len(new_rows), len(fix_rows), len(del_rows)
|
||
stats["gap"] = len(gap_days)
|
||
ctx.progress(62)
|
||
skip_txt = (f",再入职日之前已跳过 {stats['rejoin_skipped_rows']} 行(不导入、不删除)"
|
||
if stats["rejoin_skipped_rows"] else "")
|
||
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)} 行{skip_txt}", "INFO")
|
||
|
||
# 7. 写积分导入 / 积分删除(新增段保护 + 修正段全月刷新)→ COM 收尾重算
|
||
state_file = config.state_path(os.path.dirname(target_path))
|
||
state = load_state(state_file)
|
||
write_import_sheet(wb, t2, new_rows, fix_rows, state, file_key, is_new_batch)
|
||
write_delete_sheet(wb, 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)} 批依次上传("
|
||
+ "、".join(f"{d:%m-%d} {len(groups[d])} 人" for d in sorted(groups))
|
||
+ ")", "INFO")
|
||
parts, failed, retried, existed, verified = [], [], 0, 0, 0
|
||
for d in sorted(groups):
|
||
chunk = groups[d]
|
||
res = self._upload_once(client, ctx, f"积分导入_{d:%m-%d}", chunk, kind, d)
|
||
if res["success"]:
|
||
item = f"{d:%m-%d} {len(chunk)} 人"
|
||
if res.get("kind") == "verified":
|
||
verified += 1
|
||
item += (f"(系统没回执,已按工号核对确认写入,"
|
||
f"该日期共 {res.get('total', '?')} 条积分记录)")
|
||
elif res.get("kind") == "benign":
|
||
# 系统提示积分已存在:这批此前已导入过,本次没有重复加分
|
||
existed += 1
|
||
item += "(此前已导入,本次没有重复加分)"
|
||
elif res.get("first_error"):
|
||
retried += 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 verified:
|
||
msg += f";其中 {verified} 批系统没有回执,已按工号到「积分列表」核对确认写入"
|
||
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, day=None):
|
||
"""单批上传:上传前防重复加分,上传后按工号核对,未确认成功时最多再传一次。
|
||
|
||
OPM 的导入接口写入成功后只回 HTTP 200 空 body(日志里的「系统没有返回任何内容」
|
||
就是这样),客户端拿不到任何结论,所以只能自己核对:
|
||
- 上传前防重复:该积分日期今天已有记录时,先按工号看这批是不是已经导过。
|
||
全部已存在 → 不再上传;只有一部分不在 → 只补传缺的那部分人。
|
||
(实测平台对同一人同一天不去重,同一批传两次积分会加两遍)
|
||
- 上传后核对:拉「积分列表」明细,按工号确认本批每个人都能查到积分记录。
|
||
注意平台 1 人 1 天可能生成 2 条明细(有效出勤 + 遵章守纪),所以不能按条数,
|
||
只能按工号;全部查到 → 判成功,有人查不到 → 重传一次。
|
||
- 会话失效(拿到登录页 / 401)→ 重新登录后重传;
|
||
- 重传提示「已存在 / 未生成出勤积分」→ 说明第一次其实已生效,如实记录不报失败。
|
||
"""
|
||
url = client.import_url if kind == "import" else client.delete_url
|
||
payload = build_kaoqin_bytes(rows)
|
||
want = {str(r[0]).strip() for r in rows}
|
||
|
||
# 上传前:该积分日期今天已写入过记录时,先判断这批是否已经导过,避免重复加分
|
||
if day is not None:
|
||
base_total = client.count_points(day)
|
||
if base_total:
|
||
exist_total, exist_codes = client.fetch_day_point_codes(day)
|
||
if exist_codes:
|
||
missing = want - set(exist_codes)
|
||
if not missing:
|
||
return {"success": True, "kind": "benign", "total": exist_total,
|
||
"message": f"该积分日期此前已导入过(这 {len(want)} 人系统里都能查到"
|
||
f"积分记录,共 {exist_total} 条),为避免重复加分,本次没有上传"}
|
||
if len(missing) < len(want):
|
||
ctx.log(f"{label}:该积分日期此前已导入 {len(want) - len(missing)} 人,"
|
||
f"本次只补传剩下 {len(missing)} 人(已导入的人不会重复加分)", "INFO")
|
||
rows = [r for r in rows if str(r[0]).strip() in missing]
|
||
payload = build_kaoqin_bytes(rows)
|
||
want = missing
|
||
|
||
res = client.upload(url, payload, f"{label}.xlsx")
|
||
if res["success"]:
|
||
return res
|
||
|
||
# 上传后没回执:拉明细按工号核对,能确认就不必再把同一份文件传一遍
|
||
total, codes, missing = None, None, None
|
||
if day is not None and res.get("kind") == "unknown":
|
||
total, codes = client.fetch_day_point_codes(day)
|
||
if codes is not None:
|
||
missing = want - set(codes)
|
||
if not missing:
|
||
ctx.log(f"{label}:上传后系统没有返回结果,已到「积分列表」按工号逐个核对,"
|
||
f"本批 {len(want)} 人全部查到积分记录(该积分日期现有 {total} 条)", "INFO")
|
||
return {"success": True, "kind": "verified",
|
||
"gained": len(want), "total": total,
|
||
"message": f"系统没有返回结果,已按工号核对确认写入"
|
||
f"({len(want)} 人全部查到,该日期共 {total} 条积分记录)"}
|
||
|
||
need_relogin = res.get("kind") == "notfound" or not client.is_session_valid()
|
||
if missing is not None:
|
||
detail = f",核对后仍有 {len(missing)} 人查不到积分记录"
|
||
elif day is not None:
|
||
detail = ",暂时无法从「积分列表」核对"
|
||
else:
|
||
detail = ""
|
||
ctx.log(f"{label}:第 1 次上传后系统没有返回明确结果({res['message']}){detail};"
|
||
+ ("登录已失效,重新登录后再传一次" 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"第一次上传系统没有返回结果,重传时系统提示这些人的积分已存在,"
|
||
f"说明第一次其实已经写入,没有重复加分({res2['message']})")
|
||
res2["first_error"] = res["message"]
|
||
return res2
|
||
# 重传仍没回执:再按工号核对一次,能确认就判成功,避免把已写入的批次报成失败
|
||
if day is not None and res2.get("kind") == "unknown":
|
||
total2, codes2 = client.fetch_day_point_codes(day)
|
||
if codes2 is not None and not (want - set(codes2)):
|
||
ctx.log(f"{label}:重传后系统仍没有回执,已按工号核对确认 {len(want)} 人全部写入", "INFO")
|
||
return {"success": True, "kind": "verified",
|
||
"gained": len(want), "total": total2,
|
||
"message": f"两次上传系统都没有回执,已按工号核对确认写入"
|
||
f"({len(want)} 人全部查到,该日期共 {total2} 条积分记录)"}
|
||
return {"success": False,
|
||
"message": f"第一次上传:{res['message']};重传:{res2['message']}"}
|
||
|
||
|
||
PLUGINS.append(Xq0033Plugin())
|