feat(electron-shell): 新增插件目录选择接口并将版本升至 1.10.0
This commit is contained in:
@@ -27,7 +27,7 @@ class OvertimeApprovalPlugin(ScenePlugin):
|
||||
|
||||
id = "xq0004"
|
||||
name = "EHR系统加班流程审核"
|
||||
version = "1.0.0"
|
||||
version = "1.1.0"
|
||||
description = ("自动审核 EHR 加班待办:拉取待办与加班表单,按加班类型(延时/法定假日/休息日)"
|
||||
"校验加班日期、时长、排班与打卡区间及弹性到岗兑换;校验通过自动提交审批,"
|
||||
"并生成审批报告与钉钉群推送。")
|
||||
|
||||
@@ -39,6 +39,9 @@ OT_MIN_HOURS = 1
|
||||
CROSS_DAY_BEFORE_HOUR = 6
|
||||
# 加班审核周期:加班日期距今天不超过该天数才允许审核
|
||||
OT_REVIEW_DAYS = 8
|
||||
# 审核周期豁免岗位:岗位名包含该关键字的加班人员不受 OT_REVIEW_DAYS 限制(仍受月度截止约束)
|
||||
# 实际岗位名为「店长」「店长(裕见)」「街区店长(声艺大咖)」「大店长(水庄)」等,统一用「店长」匹配
|
||||
OT_REVIEW_EXEMPT_POST_KEYWORDS = ("店长",)
|
||||
# 月度截止:每月该日期 12:00 之后,不再审核上一个月的加班流程
|
||||
MONTH_CUTOFF_DAY = 2
|
||||
MONTH_CUTOFF_HOUR = 12
|
||||
|
||||
@@ -22,6 +22,7 @@ from ..config import (
|
||||
OT_MIN_HOURS,
|
||||
CROSS_DAY_BEFORE_HOUR,
|
||||
OT_REVIEW_DAYS,
|
||||
OT_REVIEW_EXEMPT_POST_KEYWORDS,
|
||||
MONTH_CUTOFF_DAY,
|
||||
MONTH_CUTOFF_HOUR,
|
||||
ZHINENG_HALF_MORNING_HOURS,
|
||||
@@ -519,12 +520,19 @@ def _validate_day_ot(info, punch, session, staff_id, require_holiday):
|
||||
return "通过", f"审批通过(申报{apply_days:g}天,打卡间隔{interval:.2f}小时)"
|
||||
|
||||
|
||||
def check_review_period(ot_date, today=None):
|
||||
def _is_review_period_exempt(post_name):
|
||||
"""岗位名包含豁免关键字(如「门店店长」)时不受审核周期天数限制。"""
|
||||
name = str(post_name or "").strip()
|
||||
return bool(name) and any(kw in name for kw in OT_REVIEW_EXEMPT_POST_KEYWORDS)
|
||||
|
||||
|
||||
def check_review_period(ot_date, post_name=None, today=None):
|
||||
"""
|
||||
加班日期有效性前置校验,返回 (是否可审核, 原因)。
|
||||
|
||||
规则:
|
||||
1. 审核周期 OT_REVIEW_DAYS 天:加班日期距今天超过该天数,不再审核;
|
||||
(岗位命中 OT_REVIEW_EXEMPT_POST_KEYWORDS,如门店店长,则不受该天数限制)
|
||||
2. 月度截止:每月 MONTH_CUTOFF_DAY 号 MONTH_CUTOFF_HOUR:00 之后,
|
||||
不再审核上一个月的加班流程。
|
||||
"""
|
||||
@@ -538,8 +546,9 @@ def check_review_period(ot_date, today=None):
|
||||
today = today or datetime.now()
|
||||
today_date = today.date()
|
||||
|
||||
# 规则1:8天审核周期
|
||||
if (today_date - ot_day.date()).days > OT_REVIEW_DAYS:
|
||||
# 规则1:8天审核周期(门店店长等豁免岗位不限制)
|
||||
if not _is_review_period_exempt(post_name) \
|
||||
and (today_date - ot_day.date()).days > OT_REVIEW_DAYS:
|
||||
return False, f"加班日期({ot_date})距今超过{OT_REVIEW_DAYS}天审核周期,不再审核"
|
||||
|
||||
# 规则2:每月2号12点之后不再审核上月加班
|
||||
@@ -556,7 +565,8 @@ def validate_doc(doc, session):
|
||||
overtime_info = parse_overtime_form(form_data)
|
||||
|
||||
# 前置校验:加班日期有效性(8天审核周期 + 每月2号12点后不再审核上月加班)
|
||||
valid, period_reason = check_review_period(overtime_info.get("加班日期"))
|
||||
# 门店店长岗位不受 8 天审核周期限制,仍受月度截止约束
|
||||
valid, period_reason = check_review_period(overtime_info.get("加班日期"), overtime_info.get("岗位"))
|
||||
if not valid:
|
||||
return {
|
||||
"title": doc.get("title", ""),
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0004",
|
||||
"name": "EHR系统加班流程审核",
|
||||
"version": "1.0.0",
|
||||
"version": "1.1.0",
|
||||
"description": "自动审核 EHR 加班待办:拉取待办与加班表单,按加班类型(延时/法定假日/休息日)校验加班日期、时长、排班与打卡区间及弹性到岗兑换;校验通过自动提交审批,并生成审批报告与钉钉群推送。",
|
||||
"category": "人事考勤",
|
||||
"icon": "",
|
||||
|
||||
@@ -10,7 +10,9 @@
|
||||
|
||||
- **第一步:更新工作簿**(`do_update`)
|
||||
1. HR 分页抓取当月考勤统计报表(`reportId=f880c52a...`,每页 1000)+ 离职当月再入职台账 + 换工号历史工号;
|
||||
2. 踢除再入职人员的离职前无效积分段;选择目标批次文件(优先文件名含 T-2 的批次,否则复制最新文件新建);
|
||||
2. 标记再入职人员「再入职日之前」的不操作段(含离职前那段,该段随离职结算已导入生效,
|
||||
既不重复导入、也不生成删除行;换工号再入职的历史工号整月不操作);
|
||||
选择目标批次文件(优先文件名含 T-2 的批次,否则复制最新文件新建);
|
||||
3. 写「考勤统计报表」→ 快照滚动 → 写「当月再入职名单」→ COM 全量重算(A 列圈人生效);
|
||||
4. 读 A 列「正确」行 → 写「考勤--今日导出」+「对比结果」值区 → COM 重算(差值/镜像生效);
|
||||
5. 读对比结果算新增段 / 修正删 / 修正补 → 写「积分导入」「积分删除」(`_xq0033_state.json` 保护历史新增段)
|
||||
@@ -39,7 +41,7 @@
|
||||
|
||||
- `config/` — 业务常量(HR 接口、台账 ID、工作表名、OPM 路径)与日志/会话钩子
|
||||
- `data/` — HR 客户端(报表/台账分页、补登)、台账自定义查询编码、OPM 客户端
|
||||
- `logic/` — 目标文件选择、工作簿写入、COM 重算、再入职踢段、状态文件
|
||||
- `logic/` — 目标文件选择、工作簿写入、COM 重算、再入职不操作段判定、状态文件
|
||||
- `report/` — 运行摘要(文案 + detail 结构化明细)
|
||||
- `ui/` — 前端**构建产物**(壳子托管于 `/pui/xq0033/`,勿手改)
|
||||
- `ui-src/` — 前端源码(Vue 3 + Element Plus + Vite)
|
||||
|
||||
@@ -4,11 +4,12 @@
|
||||
两个开关各自独立,可组合执行:
|
||||
第一步 do_update(更新工作簿):
|
||||
1) HR 考勤统计报表分页抓取(当月)+ 离职当月再入职台账 + 换工号历史工号;
|
||||
2) 踢除再入职人员无效积分段;选择目标批次文件(优先 T-2 续用,否则复制新建);
|
||||
2) 标记再入职人员「再入职日之前」的不操作段(不导入、不删除);选择目标批次文件
|
||||
(优先 T-2 续用,否则复制新建);
|
||||
3) 写「考勤统计报表」+ 快照滚动 + 「当月再入职名单」→ COM 全量重算(A 列圈人生效);
|
||||
4) 读 A 列"正确"行 → 写「考勤--今日导出」+「对比结果」值区 → COM 重算(差值/镜像生效);
|
||||
5) 读对比结果算新增段/修正段 → 写「积分导入」「积分删除」(含历史新增段保护)
|
||||
→ COM 收尾重算保存。
|
||||
5) 读对比结果算新增段/修正段(剔除再入职不操作段)→ 写「积分导入」「积分删除」
|
||||
(含历史新增段保护)→ COM 收尾重算保存。
|
||||
第二步 do_push(推送系统):
|
||||
读取工作簿积分导入/删除表 → OPM 登录 → 上传(地址固定,账号密码由界面配置)。
|
||||
|
||||
@@ -27,7 +28,7 @@ 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.rejoin_gap import RejoinGuard
|
||||
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,
|
||||
@@ -78,7 +79,7 @@ class Xq0033Plugin(ScenePlugin):
|
||||
|
||||
id = "xq0033"
|
||||
name = "门店管理及服务岗出勤积分更新"
|
||||
version = "1.0.9"
|
||||
version = "1.0.11"
|
||||
description = (
|
||||
"拉取 HR 当月考勤统计报表并按 A 列公式圈人,滚动今日/前一日快照做逐日差值,"
|
||||
"自动更新积分工作簿(考勤统计报表 / 当月再入职名单 / 积分导入 / 积分删除,"
|
||||
@@ -136,7 +137,8 @@ class Xq0033Plugin(ScenePlugin):
|
||||
|
||||
notes = []
|
||||
stats = {"update": do_update, "report_rows": 0, "selected": 0, "new": 0, "fix": 0,
|
||||
"del": 0, "rejoin_new": 0, "rejoin_total": 0, "cleared": 0}
|
||||
"del": 0, "rejoin_new": 0, "rejoin_total": 0, "rejoin_skip": 0,
|
||||
"rejoin_skipped_rows": 0, "rejoin_skip_desc": []}
|
||||
target_path = None
|
||||
push_results = None
|
||||
|
||||
@@ -194,7 +196,7 @@ class Xq0033Plugin(ScenePlugin):
|
||||
ctx.progress(18)
|
||||
ctx.log(f"考勤统计报表共 {len(report_rows)} 人", "INFO")
|
||||
|
||||
# 2. 离职当月再入职台账 + 换工号历史工号 → 踢除无效积分段
|
||||
# 2. 离职当月再入职台账 + 换工号历史工号 → 标记「再入职日之前」的不操作段
|
||||
rejoin_rows = client.fetch_all_rejoin_ledger(today)
|
||||
stats["rejoin_total"] = len(rejoin_rows)
|
||||
ctx.progress(22)
|
||||
@@ -202,9 +204,12 @@ class Xq0033Plugin(ScenePlugin):
|
||||
|
||||
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")
|
||||
guard = RejoinGuard(rejoin_rows, old_codes_map, today)
|
||||
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. 选择目标批次文件(同时据来源文件名推断上轮已处理的积分日期)
|
||||
target_path, is_new_batch, covered_until = pick_target_file(today, save_dir, force_file)
|
||||
@@ -266,12 +271,22 @@ class Xq0033Plugin(ScenePlugin):
|
||||
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)} 行", "INFO")
|
||||
f",修正补 {len(fix_rows)} 行,修正删 {len(del_rows)} 行{skip_txt}", "INFO")
|
||||
|
||||
# 7. 写积分导入 / 积分删除(新增段保护 + 修正段全月刷新)→ COM 收尾重算
|
||||
state_file = config.state_path(os.path.dirname(target_path))
|
||||
|
||||
@@ -1,11 +1,22 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0033 插件 - 离职当月再入职人员无效积分段踢除。"""
|
||||
"""XQ0033 插件 - 离职当月再入职人员「不操作段」判定(只跳过,不清空、不删除)。
|
||||
|
||||
业务口径(2026-10-29 业务确认,取代此前「再入职日之前全部踢除 + 生成删除行」方案):
|
||||
离职当月再入职人员的「再入职日之前」积分既不导入、也不删除——该段是其离职前在职期间应得的
|
||||
积分,离职结算时已随离职批次导入并生效,本轮再导入=重复给分,反向清段/生成删除行则会把
|
||||
已生效的积分扣掉。因此:
|
||||
- 台账工号(同工号再入职):[本月1日, 再入职日) 记为不操作段,报表原样保留、不补不删;
|
||||
- 历史工号(换工号再入职):该工号整月都属于离职前段 → 整月不操作;
|
||||
因工号可能被复用,要求「工号+姓名」同时匹配才跳过,避免误伤他人积分。
|
||||
判定由 RejoinGuard 统一提供:新增段 / 修正补 / 修正删行过滤共用同一口径。
|
||||
"""
|
||||
from datetime import date
|
||||
|
||||
from .. import config
|
||||
|
||||
_CODE = "hr_staff_base.base_code"
|
||||
_NAME = "hr_staff_base.staff_name"
|
||||
_WHOLE_MONTH = 32 # 上界 32 = 整月(1~31 日)都不操作
|
||||
|
||||
|
||||
def _clean(v):
|
||||
@@ -14,49 +25,83 @@ def _clean(v):
|
||||
return str(v).strip()
|
||||
|
||||
|
||||
def blank_rejoin_gap(report_rows, rejoin_rows, old_codes_map=None):
|
||||
"""就地清空再入职人员无效积分段,返回清空的考勤状态单元格数。
|
||||
def _parse_date(v):
|
||||
try:
|
||||
return date.fromisoformat(str(v).strip()[:10])
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
- 台账工号:清 [离职日, 再入职日) 中间段;
|
||||
- 历史工号(换工号再入职):清 [再入职日, 月末],但要求报告行工号+姓名同时匹配,
|
||||
避免工号被复用后误清他人积分。
|
||||
"""
|
||||
old_codes_map = old_codes_map or {}
|
||||
gaps = {} # 台账工号 -> (leave_day, join_day)
|
||||
old_gaps = {} # 历史工号 -> (join_day, 再入职人姓名)
|
||||
for r in rejoin_rows:
|
||||
code = _clean(r.get(_CODE))
|
||||
name = _clean(r.get(_NAME))
|
||||
ld = r.get(f"{config.REJOIN_FIELD_PREFIX}.leave_date")
|
||||
jd = r.get(f"{config.REJOIN_FIELD_PREFIX}.join_date")
|
||||
if not code or not ld or not jd:
|
||||
continue
|
||||
try:
|
||||
leave = date.fromisoformat(str(ld).strip()[:10])
|
||||
join = date.fromisoformat(str(jd).strip()[:10])
|
||||
except ValueError:
|
||||
continue
|
||||
gaps[code] = (leave.day, join.day)
|
||||
for old_code in old_codes_map.get(code, ()):
|
||||
old_gaps[old_code] = (join.day, name)
|
||||
if not gaps and not old_gaps:
|
||||
return 0
|
||||
|
||||
cleared = 0
|
||||
for row in report_rows:
|
||||
code, row_name = row[0], row[8]
|
||||
if code in gaps:
|
||||
leave_day, join_day = gaps[code]
|
||||
for d in range(leave_day, join_day):
|
||||
if 1 <= d <= 31 and row[8 + d] not in (None, ""):
|
||||
row[8 + d] = ""
|
||||
cleared += 1
|
||||
elif code in old_gaps:
|
||||
join_day, rejoin_name = old_gaps[code]
|
||||
if row_name != rejoin_name:
|
||||
class RejoinGuard:
|
||||
"""再入职人员「不操作段」判定(新增段/修正补/修正删行过滤共用)。"""
|
||||
|
||||
def __init__(self, rejoin_rows, old_codes_map=None, today=None):
|
||||
today = today or date.today()
|
||||
self.month_first = date(today.year, today.month, 1)
|
||||
self.gaps = {} # 台账工号 -> (不操作段上界(不含), 再入职日, 姓名)
|
||||
self.old_gaps = {} # 历史工号 -> (不操作段上界(不含), 再入职日, 姓名)
|
||||
for r in rejoin_rows or ():
|
||||
code = _clean(r.get(_CODE))
|
||||
name = _clean(r.get(_NAME))
|
||||
leave = _parse_date(r.get(f"{config.REJOIN_FIELD_PREFIX}.leave_date"))
|
||||
join = _parse_date(r.get(f"{config.REJOIN_FIELD_PREFIX}.join_date"))
|
||||
if not code or leave is None or join is None:
|
||||
continue
|
||||
for d in range(join_day, 32):
|
||||
if 1 <= d <= 31 and row[8 + d] not in (None, ""):
|
||||
row[8 + d] = ""
|
||||
cleared += 1
|
||||
return cleared
|
||||
until = self._until_day(join)
|
||||
self.gaps[code] = (until, join, name)
|
||||
for old_code in (old_codes_map or {}).get(code, ()):
|
||||
old_code = _clean(old_code)
|
||||
if old_code:
|
||||
self.old_gaps[old_code] = (_WHOLE_MONTH, join, name)
|
||||
|
||||
def _until_day(self, join):
|
||||
"""再入职日 → 本月不操作段上界(不含)。
|
||||
|
||||
本月再入职 → 再入职日;下月及以后再入职 → 整月(32);早于本月 → 无不操作段(1)。
|
||||
"""
|
||||
if (join.year, join.month) == (self.month_first.year, self.month_first.month):
|
||||
return join.day
|
||||
return _WHOLE_MONTH if join > self.month_first else 1
|
||||
|
||||
def __bool__(self):
|
||||
return bool(self.gaps or self.old_gaps)
|
||||
|
||||
def invalid_until(self, code, name):
|
||||
"""不操作段上界(不含):本月 1 日 ~ 该日之前均不导入、不删除;非再入职人员返回 None。"""
|
||||
code = _clean(code)
|
||||
hit = self.gaps.get(code)
|
||||
if hit is None:
|
||||
candidate = self.old_gaps.get(code)
|
||||
if candidate and _clean(name) == candidate[2]:
|
||||
hit = candidate
|
||||
return hit[0] if hit else None
|
||||
|
||||
def is_invalid(self, code, name, day):
|
||||
"""该员工某日(当月第几天)是否属于不操作段(不导入、不删除)。"""
|
||||
until = self.invalid_until(code, name)
|
||||
return until is not None and 1 <= int(day) < until
|
||||
|
||||
def allow(self, rows):
|
||||
"""过滤 [(员工信息9列, date), ...],剔除不操作段的行(不导入、不删除)。"""
|
||||
if not rows or not self:
|
||||
return rows
|
||||
return [x for x in rows if not self.is_invalid(x[0][0], x[0][8], x[1].day)]
|
||||
|
||||
def describe(self):
|
||||
"""人员/段位描述,用于日志与运行摘要(例:何蕾(37037921) 再入职 10-18 → 1~17 日不操作)。"""
|
||||
out = []
|
||||
for code, (until, join, name) in self.gaps.items():
|
||||
out.append(f"{name or '未知'}({code}) 再入职 {join:%m-%d} → "
|
||||
f"{self._seg_text(until)}不导入/不删除")
|
||||
for code, (until, join, name) in self.old_gaps.items():
|
||||
out.append(f"{name or '未知'}({code}) 换工号再入职({join:%m-%d})→ "
|
||||
f"{self._seg_text(until)}不导入/不删除")
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
def _seg_text(until):
|
||||
if until >= _WHOLE_MONTH:
|
||||
return "整月"
|
||||
if until <= 1:
|
||||
return "无(当月无需跳过)"
|
||||
return f"1~{until - 1} 日"
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0033",
|
||||
"name": "门店管理及服务岗出勤积分更新",
|
||||
"version": "1.0.9",
|
||||
"version": "1.0.11",
|
||||
"description": "拉取 HR 当月考勤统计报表并按 A 列公式圈人,滚动今日/前一日快照做逐日差值,自动更新积分工作簿(考勤统计报表 / 当月再入职名单 / 积分导入 / 积分删除,COM 全量重算),可选将积分导入与删除表推送至 OPM 平台。",
|
||||
"category": "考勤",
|
||||
"icon": "",
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
def build_summary(today, t2, target_path, stats, push_result=None):
|
||||
"""按执行结果拼装 {summary, detail}。
|
||||
|
||||
stats: report_rows/selected/new/fix/del/gap/rejoin_new/rejoin_total/cleared 计数;
|
||||
update=False 表示本轮仅推送(不展示更新计数)。
|
||||
stats: report_rows/selected/new/fix/del/gap/rejoin_new/rejoin_total/rejoin_skip/
|
||||
rejoin_skipped_rows 计数;update=False 表示本轮仅推送(不展示更新计数)。
|
||||
push_result: {label: {success, message}} 或 None(未执行推送)。
|
||||
"""
|
||||
if stats.get("update", True):
|
||||
@@ -22,7 +22,8 @@ def build_summary(today, t2, target_path, stats, push_result=None):
|
||||
"修正删积分行": stats.get("del", 0),
|
||||
"再入职新增行": stats.get("rejoin_new", 0),
|
||||
"再入职台账人数": stats.get("rejoin_total", 0),
|
||||
"踢除无效积分格": stats.get("cleared", 0),
|
||||
"再入职不操作段人数": stats.get("rejoin_skip", 0),
|
||||
"再入职段跳过行数": stats.get("rejoin_skipped_rows", 0),
|
||||
}
|
||||
lines = [
|
||||
f"XQ0033 完成(运行日 {today},积分日期 T-2={t2}):"
|
||||
@@ -31,8 +32,10 @@ def build_summary(today, t2, target_path, stats, push_result=None):
|
||||
f"积分删除 {stats.get('del', 0)} 行;当月再入职新增 {stats.get('rejoin_new', 0)} 行。",
|
||||
f"工作簿:{target_path}",
|
||||
]
|
||||
if stats.get("cleared"):
|
||||
lines.append(f"已踢除离职当月再入职人员无效积分段 {stats['cleared']} 个考勤状态。")
|
||||
if stats.get("rejoin_skip"):
|
||||
desc = ";".join(stats.get("rejoin_skip_desc") or []) or f"{stats['rejoin_skip']} 人"
|
||||
lines.append(f"离职当月再入职 {stats['rejoin_skip']} 人:再入职日之前的积分不操作"
|
||||
f"(不导入、不删除),本轮跳过 {stats.get('rejoin_skipped_rows', 0)} 行——{desc}。")
|
||||
if stats.get("gap"):
|
||||
lines.append(f"检测到漏处理日期 {stats['gap']} 天,已按新增段口径全量补齐。")
|
||||
else:
|
||||
|
||||
@@ -70,7 +70,7 @@ class _LogWriter:
|
||||
class Xq0037Plugin(ScenePlugin):
|
||||
id = "xq0037"
|
||||
name = "调动改签离职电子签"
|
||||
version = "1.1.8"
|
||||
version = "1.1.10"
|
||||
description = ("XQ0037 调动改签离职电子签:①调动台账导出 ②HR调动信息置位(已发起名单+群提醒) "
|
||||
"③待办完善信息提交 ④发起离职电子签 ⑤回写AI表格跟进(含已发补录) "
|
||||
"⑥签署完成核查回写 ⑦OA待办对账销办(逐人销历史残留),AI表格字段接力驱动、单步执行错峰定时")
|
||||
@@ -204,7 +204,8 @@ def summarize(step, stats):
|
||||
f"失败 {stats.get('error', 0)}")
|
||||
if step == STEP_AITABLE:
|
||||
return (f"AI表新增 {stats.get('added', 0)},已有跳过 {stats.get('skip_exists', 0)},"
|
||||
f"未发起/无流程 {stats.get('not_initiated', 0)},发起日期回填 {stats.get('backfill', 0)}")
|
||||
f"未发起/无流程 {stats.get('not_initiated', 0)},发起日期回填 {stats.get('backfill', 0)},"
|
||||
f"培训会馆不回写 {stats.get('skip_venue', 0)}")
|
||||
if step == STEP_RECONCILE:
|
||||
return (f"清空流程 {stats.get('flows', 0)},应销待办 {stats.get('tasks', 0)},"
|
||||
f"已销 {stats.get('deleted', 0)},保留在办 {stats.get('kept', 0)},"
|
||||
|
||||
@@ -18,7 +18,10 @@
|
||||
原岗位/原技师工号 + 是否已发起改签离职=是 + 发起时间=当天;
|
||||
5. 检测到已发起(AI 表已有本笔调动记录,或本次回写成功)-> 回填推送表
|
||||
「已发起名单」对应行「发起日期」列(AI/35,openpyxl 直写,试算模式不写);
|
||||
6. 回写完成(新增成功或 AI 表已有)-> 从待办工号列表移除,列表清空即链路收尾。
|
||||
6. 回写完成(新增成功或 AI 表已有)-> 从待办工号列表移除,列表清空即链路收尾;
|
||||
7. 调入「职业技术培训会馆」的人员不回写 AI 表:该会馆由 HR 批量发起、
|
||||
完善信息时不新签合同(step3 is_new_sign=0),不纳入跟进表;
|
||||
仅回填「已发起名单」发起日期并从待办列表移除,避免每次重跑反复核查。
|
||||
|
||||
字段映射注意:AI 表「现单位名称/原单位名称」是 singleSelect 且选项为会馆名
|
||||
(四级部门级),取名单表「现四级部门/原四级部门」列,不是「现单位/原单位」
|
||||
@@ -66,6 +69,9 @@ ROSTER_COLS = ("姓名", "工号", "调动时间",
|
||||
FIELD_INITIATED = "是否已发起改签离职"
|
||||
FIELD_INIT_TIME = "发起时间"
|
||||
|
||||
# 调入该会馆的人员不回写 AI 表(HR 批量发起、不新签合同,不纳入跟进)
|
||||
UNIT_TRAINING_VENUE = "职业技术培训会馆"
|
||||
|
||||
# 试算开关:True=试算(只打印,不写 AI 表);False=实跑写入
|
||||
DRY_RUN = False
|
||||
FIELD_INIT_DATE = "发起日期" # 「已发起名单」AI(35) 列(按表头名定位),已发起时回填
|
||||
@@ -170,6 +176,17 @@ def pick_unit(row, prefix, choices):
|
||||
return ""
|
||||
|
||||
|
||||
def is_training_venue(row):
|
||||
"""调入单位 = 职业技术培训会馆(看「现」二/三/四级部门,含会馆名即命中)。
|
||||
|
||||
培训会馆由 HR 批量发起、完善信息时是否新签合同=否(step3 is_new_sign=0),
|
||||
不纳入 AI 表跟进,回写阶段跳过新增;只按「调出」方向看的场景不适用。
|
||||
"""
|
||||
return any(UNIT_TRAINING_VENUE in row[k]
|
||||
for k in ("现单位", "现二级部门", "现三级部门", "现四级部门")
|
||||
if row.get(k))
|
||||
|
||||
|
||||
def load_roster_rows():
|
||||
"""名单表数据行 -> {工号(str): 回写字段 + _row(行号,发起日期回填用)};
|
||||
同工号多行取后一行。"""
|
||||
@@ -188,6 +205,9 @@ def load_roster_rows():
|
||||
"姓名": _s(ws.cell(r, header["姓名"]).value),
|
||||
"工号": code,
|
||||
"调动时间": ws.cell(r, header["调动时间"]).value,
|
||||
# 现单位(事业部级)可选列:仅用于培训会馆判定,缺列不影响回写
|
||||
"现单位": _s(ws.cell(r, header["现单位"]).value)
|
||||
if "现单位" in header else "",
|
||||
"现二级部门": _s(ws.cell(r, header["现二级部门"]).value),
|
||||
"现三级部门": _s(ws.cell(r, header["现三级部门"]).value),
|
||||
"现四级部门": _s(ws.cell(r, header["现四级部门"]).value),
|
||||
@@ -362,7 +382,7 @@ def main(dry_run=None):
|
||||
if not pending and not sent:
|
||||
_log("[待办] 待办工号列表为空,且「调动导出」无已发人员,无事可做")
|
||||
return {"added": 0, "skip_exists": 0, "skip_noroster": 0,
|
||||
"not_initiated": 0, "backfill": 0, "sent": 0}
|
||||
"not_initiated": 0, "backfill": 0, "sent": 0, "skip_venue": 0}
|
||||
if pending:
|
||||
_log("[待办] 本批待办 {} 人:{}".format(
|
||||
len(pending), "、".join(f"{c}{n}" for c, n in sorted(pending.items()))))
|
||||
@@ -370,7 +390,8 @@ def main(dry_run=None):
|
||||
existing = fetch_follow_records()
|
||||
|
||||
stats = {"added": 0, "skip_exists": 0, "skip_noroster": 0,
|
||||
"not_initiated": 0, "backfill": 0, "sent": len(sent)}
|
||||
"not_initiated": 0, "backfill": 0, "sent": len(sent),
|
||||
"skip_venue": 0}
|
||||
# 待办路径:发起成功以 HR 为准,未发起/无流程的保留待办,不回写不回填不移除
|
||||
initiated = {}
|
||||
if pending:
|
||||
@@ -393,15 +414,32 @@ def main(dry_run=None):
|
||||
_log(f"[汇总] HR已发起=0 未发起或无流程={stats['not_initiated']} "
|
||||
f"已发={len(sent_only)} 名单缺行={stats['skip_noroster']} "
|
||||
f"新增={stats['added']} 已有跳过={stats['skip_exists']} "
|
||||
f"发起日期回填={stats['backfill']}"
|
||||
f"发起日期回填={stats['backfill']} 培训会馆不回写={stats['skip_venue']}"
|
||||
f"{'(试算模式)' if dry_run else ''}")
|
||||
return stats
|
||||
|
||||
choices = fetch_field_choices()
|
||||
if not choices:
|
||||
raise RuntimeError("未能获取「现/原单位名称」字段选项集,终止回写以免单位名称写空")
|
||||
# 调入职业技术培训会馆:HR 批量发起、完善信息不新签合同(step3 is_new_sign=0),
|
||||
# 不纳入 AI 表跟进 —— 不新增行,仍回填发起日期并从待办列表移除(否则每次重跑反复核查)
|
||||
venue = {c: ms for c, ms in targets.items()
|
||||
if c in roster and is_training_venue(roster[c])}
|
||||
write_targets = {c: ms for c, ms in targets.items() if c not in venue}
|
||||
stats["skip_venue"] = len(venue)
|
||||
for code in sorted(venue):
|
||||
_log(f"[跳过·会馆] {code} {roster[code]['姓名']} | 调入{UNIT_TRAINING_VENUE},"
|
||||
f"不新签合同,不回写 AI 表格")
|
||||
|
||||
add_items, done_codes, init_items = [], [], []
|
||||
for code, init_ms in sorted(targets.items()):
|
||||
done_codes.extend(sorted(venue))
|
||||
init_items.extend(sorted(venue.items()))
|
||||
choices = set()
|
||||
if write_targets:
|
||||
choices = fetch_field_choices()
|
||||
if not choices:
|
||||
raise RuntimeError(
|
||||
"未能获取「现/原单位名称」字段选项集,终止回写以免单位名称写空")
|
||||
else:
|
||||
_log(f"[完成] 本轮无 AI 表新增({len(venue)} 人调入{UNIT_TRAINING_VENUE},不回写)")
|
||||
for code, init_ms in sorted(write_targets.items()):
|
||||
tag = "已发" if code in sent_only else "待办"
|
||||
row = roster.get(code)
|
||||
if row is None:
|
||||
@@ -442,10 +480,10 @@ def main(dry_run=None):
|
||||
|
||||
if done_codes and not dry_run:
|
||||
remove_pending(done_codes)
|
||||
_log("[待办] 回写完成,已从待办列表移除:{}".format("、".join(done_codes)))
|
||||
_log("[待办] 回写/收尾完成,已从待办列表移除:{}".format("、".join(done_codes)))
|
||||
_log(f"[汇总] 待办已发起={len(initiated)} 已发={len(sent_only)} "
|
||||
f"未发起或无流程={stats['not_initiated']} 名单缺行={stats['skip_noroster']} "
|
||||
f"新增={stats['added']} 已有跳过={stats['skip_exists']} "
|
||||
f"发起日期回填={stats['backfill']}"
|
||||
f"发起日期回填={stats['backfill']} 培训会馆不回写={stats['skip_venue']}"
|
||||
f"{'(试算模式)' if dry_run else ''}")
|
||||
return stats
|
||||
|
||||
@@ -5,9 +5,10 @@
|
||||
「是否完成新合同签署」任一为空(checkbox 未勾)的行,逐行到 HR 核查:
|
||||
|
||||
离职签署完成(解除旧合同的电子签三状态 is_initiate_sign/staff/org 全 "2"):
|
||||
1. 生效中合同 tab 出现起始日 > 调动日的新合同行 -> 旧合同已解除 -> 完成;
|
||||
1. 生效中合同 tab 出现起始日 >= 调动日的新合同行(含起始日恰为调动日当天,
|
||||
如调动 2026-10-19 / 新合同起始 2026-10-19)-> 旧合同已解除 -> 完成;
|
||||
2. 改签流程仍在运行中 -> 按流程 businessKey 查签署记录三状态全 "2" -> 完成;
|
||||
3. 流程查不到运行中 且 生效中 tab 无旧合同行(起始日 <= 调动日)-> 流程已
|
||||
3. 流程查不到运行中 且 生效中 tab 无旧合同行(起始日 < 调动日)-> 流程已
|
||||
办结且旧合同已解除 -> 完成(XQ0020 审核通过前提=三状态全已完成);
|
||||
其余(旧合同仍在生效中/流程查不到)-> 未完成,不回填,等下次运行。
|
||||
|
||||
@@ -159,6 +160,33 @@ def find_running_flow(session, code, name):
|
||||
return ""
|
||||
|
||||
|
||||
# ---------- 新旧合同切分 ----------
|
||||
def _start_ms(row):
|
||||
"""合同行起始日 -> 当天 0 点毫秒;缺失/格式不识别返回 None。"""
|
||||
return _ms_day(str(row.get("hr_staff_contract.contract_start_date") or ""))
|
||||
|
||||
|
||||
def _split_contracts(active, move_ms):
|
||||
"""生效中 tab 合同行按起始日与调动日切分 -> (旧合同, 新合同, 无法判定)。
|
||||
|
||||
口径(业务确认):起始日 >= 调动日 = 新合同(改签后新签,含起始日恰为调动日
|
||||
当天,如调动 2026-10-19 / 新合同起始 2026-10-19);起始日 < 调动日 = 旧合同
|
||||
(调动前在用)。起始日缺失/格式不识别/调动时间缺失 = 无法判定,不参与判定:
|
||||
原实现 `r not in old_rows` 会把所有解析失败或调动时间缺失的行退化成「新合同」,
|
||||
直接判定双完成造成误回填。
|
||||
"""
|
||||
old_rows, new_rows, unknown_rows = [], [], []
|
||||
for r in active:
|
||||
s = _start_ms(r)
|
||||
if s is None or not move_ms:
|
||||
unknown_rows.append(r)
|
||||
elif s >= move_ms:
|
||||
new_rows.append(r)
|
||||
else:
|
||||
old_rows.append(r)
|
||||
return old_rows, new_rows, unknown_rows
|
||||
|
||||
|
||||
# ---------- 单行核查 ----------
|
||||
def check_one(session, row):
|
||||
"""核查一行 -> {FIELD_LEAVE_DONE: bool|None, FIELD_NEW_DONE: bool|None}。
|
||||
@@ -169,15 +197,12 @@ def check_one(session, row):
|
||||
result = {FIELD_LEAVE_DONE: None, FIELD_NEW_DONE: None}
|
||||
notes = []
|
||||
|
||||
# 生效中合同 tab:区分旧合同(起始<=调动日)与新合同(起始>调动日)
|
||||
# 生效中合同 tab:起始日 < 调动日 = 旧合同;>= 调动日 = 新合同(含当天生效)
|
||||
active = _query_contract_tab(
|
||||
session, ROSTER_ID_ACTIVE_CONTRACT,
|
||||
f"{HR_BASE_URL}/RedseaPlatform/hrRoster/{ROSTER_ID_ACTIVE_CONTRACT}/queryRealTimeData.mc",
|
||||
code)
|
||||
old_rows = [r for r in active
|
||||
if move_ms and _ms_day(str(r.get("hr_staff_contract.contract_start_date") or "")) is not None
|
||||
and _ms_day(str(r.get("hr_staff_contract.contract_start_date"))) <= move_ms]
|
||||
new_active = [r for r in active if r not in old_rows]
|
||||
old_rows, new_active, unknown_rows = _split_contracts(active, move_ms)
|
||||
|
||||
if new_active:
|
||||
# 新合同已生效:签署完成才进生效中(HR 硬规则)-> 离职/新合同均完成
|
||||
@@ -201,6 +226,9 @@ def check_one(session, row):
|
||||
notes.append("离职电子签三状态均已完成(合同待流转生效)")
|
||||
else:
|
||||
notes.append("改签流程不在运行中且旧合同仍在生效中 -> 未完成,不回填")
|
||||
elif unknown_rows:
|
||||
# 起始日解析失败/调动时间缺失:无法区分新旧合同,本轮不判定(不误回填)
|
||||
notes.append("生效中Tab合同起始日无法解析(调动时间缺失或日期格式异常)-> 本轮不判定")
|
||||
else:
|
||||
# 生效中既无旧也无新:查待生效 tab(新合同签署中/签完未生效)
|
||||
notes.append("生效中Tab无合同行")
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0037",
|
||||
"name": "调动改签离职电子签",
|
||||
"version": "1.1.8",
|
||||
"version": "1.1.10",
|
||||
"description": "XQ0037 调动改签离职电子签:按步骤执行 ①调动台账导出(近三月台账 + 近3天筛选)②按公式判定已发/需要追加「已发起名单」+ HR置位+群提醒 ③待办完善信息提交 ④发起离职电子签 ⑤回写AI表格跟进(含已发补录) ⑥签署完成核查回写 ⑦OA待办对账销办(逐人销历史残留);钉钉AI表格字段接力驱动,HR/OA 会话由壳子注入",
|
||||
"category": "人事考勤",
|
||||
"icon": "",
|
||||
|
||||
@@ -68,10 +68,10 @@ def _resolve_action(fields):
|
||||
class Xq0041Plugin(ScenePlugin):
|
||||
id = 'xq0041'
|
||||
name = '新美大平台核对'
|
||||
version = '1.1.6'
|
||||
version = '1.1.7'
|
||||
description = ('美团经营宝账单自动下载与台账核对:按需下载打款记录、团购收益明细、'
|
||||
'预订收益明细,把新产生的收益按验券时间并入月份台账,'
|
||||
'并给核对统计表补当天的团购统计表链接')
|
||||
'并按日期把核对统计表整行同源取数公式(资金组取数)换成当天共享总表的链接')
|
||||
platform = '' # 插件自带登录(经营宝 SSO + 选商家),不用底座共享登录态
|
||||
uses_month = False
|
||||
capabilities = ['xq0041']
|
||||
|
||||
@@ -1,14 +1,19 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""「新美大核对统计」按日期补 V/W 列外部链接公式。
|
||||
"""「新美大核对统计」按日期补共享总表取数公式(自动扫描整行同源公式)。
|
||||
|
||||
业务口径(从台账既有 62 条链接反推):
|
||||
V = =[N]资金组取数!$B$5 (应收岗-团购统计表-昨日遗留)
|
||||
W = =[N]资金组取数!$B$6 (应收岗-团购统计表-本日遗留)
|
||||
业务口径:该 sheet 里所有形如 `[n]资金组取数!$B$xx` 的公式都属于「同源取数」,每行应按 A 列日期
|
||||
指向**当天那份**财务共享总表(当前实测 4 列 × 62 行 = 248 个):
|
||||
V = [n]资金组取数!$B$5 应收岗-团购统计表-昨日遗留
|
||||
W = [n]资金组取数!$B$6 应收岗-团购统计表-本日遗留
|
||||
Y = [n]资金组取数!$B$3
|
||||
Z = [n]资金组取数!$B$4
|
||||
外部文件:file:///\\\\caiwu01\\共享文件夹\\1111\\TG\\{YYYY}年{M}月\\{M}.{D}\\马敏团购总表{M}.{D}.xlsx
|
||||
|
||||
实现:能复用的链接按 target 匹配复用,缺的新增 externalLinkNN.xml + rels +
|
||||
workbook.xml 的 externalReferences + workbook.xml.rels + Content_Types 声明;
|
||||
目标 sheet 只改对应行的 V/W 单元格,其余部件原样拷贝。
|
||||
实现:**不写死列名**——扫描目标行里每个公式,凡含 `[n]资金组取数!` 就把其中的 [n] 换成该行日期
|
||||
对应的编号(前置负号、单元格地址、公式其它部分原样保留;引用别的工作簿的 [n] 不动)。
|
||||
已是目标编号的单元格原样保留(含缓存值),只改对不上的。缺的外部链接新增部件并五处同步。
|
||||
日期范围:不给区间就处理整表 A 列所有日期行(幂等),给了就只处理区间内。
|
||||
共享盘不可达不阻塞:公式照写,Excel 打开点「更新链接」即可取值。
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
@@ -20,6 +25,7 @@ from datetime import date, datetime, timedelta
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from .. import config
|
||||
from .zipio import open_zip
|
||||
|
||||
_EXTLINK_TPL = (
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
|
||||
@@ -35,12 +41,15 @@ _EXTLINK_RELS_TPL = (
|
||||
'relationships/externalLinkPath" Target="%s" TargetMode="External"/></Relationships>'
|
||||
)
|
||||
_CELL_RE = re.compile(r'<c r="([A-Z]+)(\d+)"([^>]*?)(?:/>|>(.*?)</c>)', re.S)
|
||||
_F_RE = re.compile(r'<f([^>]*?)(?:/>|>(.*?)</f>)', re.S)
|
||||
_ROW_RE = re.compile(r'<row r="(\d+)"[^>]*?(?:/>|>.*?</row>)', re.S)
|
||||
_EXT_REF = re.compile(r'\[(\d+)\]' + re.escape(config.LINK_SHEET) + r'!')
|
||||
|
||||
|
||||
def _pick_latest(pattern):
|
||||
def _pick_ledger():
|
||||
import glob
|
||||
files = [p for p in glob.glob(os.path.join(config.WORK_DIR, pattern))
|
||||
if '备份' not in os.path.basename(p)]
|
||||
files = [p for p in glob.glob(os.path.join(config.WORK_DIR, config.LEDGER_GLOB))
|
||||
if '备份' not in os.path.basename(p) and not p.endswith('.tmp')]
|
||||
if not files:
|
||||
return None
|
||||
files.sort(key=os.path.getmtime)
|
||||
@@ -57,6 +66,14 @@ def _file_uri(path):
|
||||
return 'file:///' + path
|
||||
|
||||
|
||||
def _norm_uri(uri):
|
||||
"""外部链接目标归一化:去掉 file:/// 前缀、双反斜杠归一、小写(否则每次都新增重复链接)。"""
|
||||
u = (uri or '').strip()
|
||||
if u.lower().startswith('file:///'):
|
||||
u = u[len('file:///'):]
|
||||
return u.replace('\\\\', '\\').lower()
|
||||
|
||||
|
||||
def _sheet_xml_path(zf, sheet_name):
|
||||
import xml.etree.ElementTree as ET
|
||||
main = '{http://schemas.openxmlformats.org/spreadsheetml/2006/main}'
|
||||
@@ -78,47 +95,8 @@ def _sheet_xml_path(zf, sheet_name):
|
||||
return None
|
||||
|
||||
|
||||
def _col_num(letters):
|
||||
n = 0
|
||||
for ch in letters:
|
||||
n = n * 26 + (ord(ch) - 64)
|
||||
return n
|
||||
|
||||
|
||||
def _set_row_cells(row_xml, row_no, cells):
|
||||
keep = []
|
||||
style_default = None
|
||||
for m in _CELL_RE.finditer(row_xml):
|
||||
col = m.group(1)
|
||||
sm = re.search(r'\bs="(\d+)"', m.group(3))
|
||||
if style_default is None and sm:
|
||||
style_default = sm.group(1)
|
||||
if col in cells:
|
||||
continue
|
||||
keep.append((_col_num(col), m.group(0)))
|
||||
for col, (formula, style) in cells.items():
|
||||
s = style or style_default
|
||||
s_attr = f' s="{s}"' if s else ''
|
||||
keep.append((_col_num(col), f'<c r="{col}{row_no}"{s_attr}><f>{formula}</f></c>'))
|
||||
keep.sort(key=lambda x: x[0])
|
||||
attrs = re.match(r'<row([^>]*)>', row_xml)
|
||||
head = f'<row{attrs.group(1)}>' if attrs else f'<row r="{row_no}">'
|
||||
return f'{head}{"".join(c for _, c in keep)}</row>'
|
||||
|
||||
|
||||
def _norm_uri(uri):
|
||||
"""外部链接目标归一化:`file:///\\\\caiwu01\\共享...` → `\\\\caiwu01\\共享...`(小写)。
|
||||
|
||||
比对方是本地路径,不带 file:/// 前缀;不归一会永远匹配不上,
|
||||
导致每次运行都新增一条重复的外部链接。
|
||||
"""
|
||||
u = (uri or '').strip()
|
||||
if u.lower().startswith('file:///'):
|
||||
u = u[len('file:///'):]
|
||||
return u.replace('\\\\', '\\').lower()
|
||||
|
||||
|
||||
def _parse_links(zf):
|
||||
"""既有外部链接:{归一化路径: 序号} + 最大序号。"""
|
||||
mapping, max_n = {}, 0
|
||||
for name in zf.namelist():
|
||||
m = re.match(r'xl/externalLinks/_rels/externalLink(\d+)\.xml\.rels$', name)
|
||||
@@ -129,108 +107,190 @@ def _parse_links(zf):
|
||||
txt = zf.read(name).decode('utf-8', 'replace')
|
||||
tm = re.search(r'Target="([^"]+)"', txt)
|
||||
if tm:
|
||||
mapping.setdefault(_norm_uri(tm.group(1)), n) # 同路径多条时保留最早那条
|
||||
mapping.setdefault(_norm_uri(tm.group(1)), n)
|
||||
return mapping, max_n
|
||||
|
||||
|
||||
def _col_num(letters):
|
||||
n = 0
|
||||
for ch in letters:
|
||||
n = n * 26 + (ord(ch) - 64)
|
||||
return n
|
||||
|
||||
|
||||
def _set_row_cells(row_xml, row_no, cells):
|
||||
"""用新单元格替换指定列(保留该列原有样式 s),行内其余单元格原样保留。"""
|
||||
keep, styles = [], {}
|
||||
for m in _CELL_RE.finditer(row_xml):
|
||||
col = m.group(1)
|
||||
sm = re.search(r'\bs="(\d+)"', m.group(3))
|
||||
if sm:
|
||||
styles.setdefault(col, sm.group(1))
|
||||
if col in cells:
|
||||
continue
|
||||
keep.append((_col_num(col), m.group(0)))
|
||||
for col, formula in cells.items():
|
||||
s = styles.get(col)
|
||||
s_attr = f' s="{s}"' if s else ''
|
||||
keep.append((_col_num(col), f'<c r="{col}{row_no}"{s_attr}><f>{formula}</f></c>'))
|
||||
keep.sort(key=lambda x: x[0])
|
||||
attrs = re.match(r'<row([^>]*)>', row_xml)
|
||||
head = f'<row{attrs.group(1)}>' if attrs else f'<row r="{row_no}">'
|
||||
return f'{head}{"".join(c for _, c in keep)}</row>'
|
||||
|
||||
|
||||
def _same_src_formulas(row_inner):
|
||||
"""该行里所有引用共享总表的公式 {列: 公式文本}(共享公式引用无文本的跳过)。"""
|
||||
out = {}
|
||||
for c in _CELL_RE.finditer(row_inner):
|
||||
body = c.group(4) or ''
|
||||
fm = _F_RE.search(body)
|
||||
if not fm:
|
||||
continue
|
||||
text = fm.group(2) or ''
|
||||
if text and _EXT_REF.search(text):
|
||||
out[c.group(1)] = text
|
||||
return out
|
||||
|
||||
|
||||
def _date_rows(ledger):
|
||||
"""读「新美大核对统计」A 列日期 → {date: 行号}。"""
|
||||
wb = load_workbook(ledger, read_only=True, data_only=False)
|
||||
try:
|
||||
if config.STAT_SHEET not in wb.sheetnames:
|
||||
raise RuntimeError(f'台账缺少 sheet「{config.STAT_SHEET}」')
|
||||
ws = wb[config.STAT_SHEET]
|
||||
out = {}
|
||||
for i, row in enumerate(ws.iter_rows(min_col=1, max_col=1, values_only=True), start=1):
|
||||
v = row[0]
|
||||
if isinstance(v, datetime):
|
||||
out[v.date()] = i
|
||||
elif isinstance(v, date):
|
||||
out[v] = i
|
||||
return out
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
|
||||
def run(d_from=None, d_to=None, dry_run=False):
|
||||
"""按日期区间补 V/W。d_from/d_to 为空则取最新「团购收益明细_YYYYMMDD_YYYYMMDD.xlsx」的日期。"""
|
||||
ledger = _pick_latest(config.LEDGER_GLOB)
|
||||
"""按 A 列日期给「新美大核对统计」整行同源取数公式换链接编号。
|
||||
|
||||
d_from/d_to 为空 → 处理整表所有日期行;给了区间 → 只处理区间内的日期行。
|
||||
"""
|
||||
ledger = _pick_ledger()
|
||||
if not ledger:
|
||||
return {'ok': False, 'message': f'未找到台账:{config.LEDGER_GLOB}'}
|
||||
config.log(f'台账:{os.path.basename(ledger)}')
|
||||
config.log(f'台账:{os.path.basename(ledger)}({config.STAT_SHEET})')
|
||||
|
||||
if not d_from:
|
||||
detail = _pick_latest(config.DETAIL_GLOB)
|
||||
if detail:
|
||||
m = re.search(r'(\d{8})_(\d{8})', os.path.basename(detail)) or \
|
||||
re.search(r'(\d{8})', os.path.basename(detail))
|
||||
if m:
|
||||
d_from = m.group(1)
|
||||
d_to = m.group(2) if m.lastindex and m.lastindex >= 2 else m.group(1)
|
||||
if not d_from:
|
||||
today = date.today()
|
||||
d_from = (today - timedelta(days=1)).isoformat()
|
||||
d_to = today.isoformat()
|
||||
try:
|
||||
rows_by_date = _date_rows(ledger)
|
||||
except RuntimeError as e:
|
||||
return {'ok': False, 'message': str(e)}
|
||||
if not rows_by_date:
|
||||
return {'ok': False, 'message': f'「{config.STAT_SHEET}」A 列没有日期行'}
|
||||
|
||||
d1 = datetime.strptime(d_from.replace('-', '')[:8], '%Y%m%d').date()
|
||||
d2 = datetime.strptime(str(d_to).replace('-', '')[:8], '%Y%m%d').date()
|
||||
config.log(f'日期区间:{d1} ~ {d2}')
|
||||
|
||||
wb = load_workbook(ledger, read_only=True, data_only=False)
|
||||
if config.STAT_SHEET not in wb.sheetnames:
|
||||
wb.close()
|
||||
return {'ok': False, 'message': f'台账缺少 sheet「{config.STAT_SHEET}」'}
|
||||
ws = wb[config.STAT_SHEET]
|
||||
date_rows = {}
|
||||
for i, row in enumerate(ws.iter_rows(min_col=1, max_col=1, values_only=True), start=1):
|
||||
v = row[0]
|
||||
if isinstance(v, datetime):
|
||||
date_rows[v.date()] = i
|
||||
elif isinstance(v, date):
|
||||
date_rows[v] = i
|
||||
wb.close()
|
||||
|
||||
days, day = [], d1
|
||||
while day <= d2:
|
||||
days.append(day)
|
||||
day += timedelta(days=1)
|
||||
skipped = [d for d in days if d not in date_rows]
|
||||
if skipped:
|
||||
config.log(f'核对统计表里没有这些日期行,跳过:{[str(d) for d in skipped]}', 'WARN')
|
||||
days = [d for d in days if d in date_rows]
|
||||
days = sorted(rows_by_date)
|
||||
if d_from or d_to:
|
||||
d1 = datetime.strptime(str(d_from).replace('-', '')[:8], '%Y%m%d').date() if d_from else days[0]
|
||||
d2 = datetime.strptime(str(d_to).replace('-', '')[:8], '%Y%m%d').date() if d_to else days[-1]
|
||||
if d2 < d1:
|
||||
d1, d2 = d2, d1
|
||||
skipped = [x for x in days if not (d1 <= x <= d2)]
|
||||
days = [x for x in days if d1 <= x <= d2]
|
||||
config.log(f'日期区间 {d1} ~ {d2}:命中 {len(days)} 行,跳过 {len(skipped)} 行')
|
||||
if not days:
|
||||
return {'ok': False, 'message': '没有可处理的日期行'}
|
||||
return {'ok': True, 'rows': [], 'new_links': 0, 'ledger': ledger,
|
||||
'message': f'区间内没有 {config.STAT_SHEET} 日期行'}
|
||||
config.log(f'核对表 {len(days)} 个日期行:{days[0]} ~ {days[-1]}')
|
||||
|
||||
zf = zipfile.ZipFile(ledger)
|
||||
link_map, max_link = _parse_links(zf)
|
||||
config.log(f'既有外部链接 {len(link_map)} 条,最大序号 {max_link}')
|
||||
zf = open_zip(ledger)
|
||||
try:
|
||||
link_map, max_link = _parse_links(zf)
|
||||
config.log(f'既有外部链接 {len(link_map)} 条,最大序号 {max_link}')
|
||||
sheet_path = _sheet_xml_path(zf, config.STAT_SHEET)
|
||||
if not sheet_path:
|
||||
return {'ok': False, 'message': f'找不到「{config.STAT_SHEET}」的 xml'}
|
||||
sheet_xml = zf.read(sheet_path).decode('utf-8')
|
||||
wb_xml = zf.read('xl/workbook.xml').decode('utf-8')
|
||||
wb_rels = zf.read('xl/_rels/workbook.xml.rels').decode('utf-8')
|
||||
ct_xml = zf.read('[Content_Types].xml').decode('utf-8')
|
||||
finally:
|
||||
zf.close()
|
||||
|
||||
plan, need_new = [], []
|
||||
row_spans = {}
|
||||
for m in _ROW_RE.finditer(sheet_xml):
|
||||
row_spans[int(m.group(1))] = m.group(0)
|
||||
|
||||
plan, need_new, skipped, no_formula = [], {}, 0, 0
|
||||
for d in days:
|
||||
path = _target_path(d)
|
||||
if _norm_uri(path) in link_map:
|
||||
plan.append((d, date_rows[d], link_map[_norm_uri(path)], path, '复用'))
|
||||
row_no = rows_by_date[d]
|
||||
row_xml = row_spans.get(row_no)
|
||||
if row_xml is None:
|
||||
config.log(f'{d} 第 {row_no} 行 XML 未找到,跳过', 'WARN')
|
||||
continue
|
||||
srcs = _same_src_formulas(row_xml)
|
||||
if not srcs:
|
||||
no_formula += 1
|
||||
continue
|
||||
key = _norm_uri(_target_path(d))
|
||||
have = link_map.get(key)
|
||||
if have is not None and all(set(_EXT_REF.findall(f)) == {str(have)}
|
||||
for f in srcs.values()):
|
||||
skipped += 1
|
||||
continue
|
||||
if have is not None:
|
||||
idx, mode = have, '复用'
|
||||
else:
|
||||
idx = max_link + len(need_new) + 1
|
||||
need_new.append((idx, path, _file_uri(path)))
|
||||
plan.append((d, date_rows[d], idx, path, '新增'))
|
||||
if key not in need_new:
|
||||
need_new[key] = (max_link + len(need_new) + 1, _target_path(d))
|
||||
idx, mode = need_new[key][0], '新增'
|
||||
todo = {}
|
||||
for col, fml in srcs.items():
|
||||
if set(_EXT_REF.findall(fml)) == {str(idx)}:
|
||||
continue
|
||||
todo[col] = _EXT_REF.sub(f'[{idx}]{config.LINK_SHEET}!', fml)
|
||||
if not todo:
|
||||
skipped += 1
|
||||
continue
|
||||
plan.append((d, row_no, idx, _target_path(d), mode, todo))
|
||||
|
||||
for d, row_no, idx, path, mode in plan:
|
||||
config.log(f' {d} → 第{row_no}行 [{idx}]({mode}){path}')
|
||||
config.log(f'需更新 {len(plan)} 行(已正确 {skipped} 行、无同源公式 {no_formula} 行),'
|
||||
f'新增外部链接 {len(need_new)} 条')
|
||||
for d, row_no, idx, path, mode, todo in plan:
|
||||
cols = ','.join(f'{c}({f})' for c, f in sorted(todo.items()))
|
||||
config.log(f' {d} 第{row_no}行 → [{idx}]({mode}){cols} {path}', 'DEBUG')
|
||||
|
||||
if not plan:
|
||||
return {'ok': True, 'rows': [], 'new_links': 0, 'ledger': ledger,
|
||||
'message': f'{config.STAT_SHEET} 同源取数公式已是最新,无需改动'}
|
||||
|
||||
if dry_run:
|
||||
zf.close()
|
||||
return {'ok': True, 'rows': [p[1] for p in plan],
|
||||
'message': f'[演练] {len(plan)} 行将更新 V/W,需新增 {len(need_new)} 条外部链接'}
|
||||
return {'ok': True, 'rows': [p[1] for p in plan], 'new_links': len(need_new),
|
||||
'ledger': ledger,
|
||||
'message': f'[演练] 将更新 {len(plan)} 行,需新增 {len(need_new)} 条外部链接'}
|
||||
|
||||
if not os.path.isdir(config.SHARE_ROOT):
|
||||
config.log(f'共享盘当前不可达({config.SHARE_ROOT}),公式照写,'
|
||||
f'恢复后打开 Excel 点「更新链接」即可取值', 'WARN')
|
||||
f'恢复到内网后打开 Excel 点「更新链接」即可取值', 'WARN')
|
||||
|
||||
sheet_path = _sheet_xml_path(zf, config.STAT_SHEET)
|
||||
if not sheet_path:
|
||||
zf.close()
|
||||
return {'ok': False, 'message': f'找不到「{config.STAT_SHEET}」的 xml'}
|
||||
sheet_xml = zf.read(sheet_path).decode('utf-8')
|
||||
wb_xml = zf.read('xl/workbook.xml').decode('utf-8')
|
||||
wb_rels = zf.read('xl/_rels/workbook.xml.rels').decode('utf-8')
|
||||
ct_xml = zf.read('[Content_Types].xml').decode('utf-8')
|
||||
lock = os.path.join(os.path.dirname(ledger), '~$' + os.path.basename(ledger))
|
||||
if os.path.exists(lock):
|
||||
return {'ok': False, 'message': '台账正在 Excel 中打开(检测到 ~$ 锁文件),请关闭后重跑'}
|
||||
backup = os.path.join(
|
||||
config.WORK_DIR,
|
||||
f'{os.path.splitext(os.path.basename(ledger))[0]}_核对备份'
|
||||
f'{time.strftime("%Y%m%d_%H%M%S")}.xlsx')
|
||||
shutil.copy2(ledger, backup)
|
||||
config.log(f'已备份 → {os.path.basename(backup)}')
|
||||
|
||||
for d, row_no, idx, path, mode in plan:
|
||||
m = re.search(r'<row r="' + str(row_no) + r'"[^>]*>.*?</row>', sheet_xml, re.S)
|
||||
if not m:
|
||||
config.log(f'第 {row_no} 行 XML 未找到,跳过', 'WARN')
|
||||
continue
|
||||
# 注意:XML 的 <f> 里放公式正文,不带 Excel 界面上的前导 '='
|
||||
new_row = _set_row_cells(m.group(0), row_no, {
|
||||
'V': (f'[{idx}]{config.LINK_SHEET}!$B$5', None),
|
||||
'W': (f'[{idx}]{config.LINK_SHEET}!$B$6', None),
|
||||
})
|
||||
sheet_xml = sheet_xml[:m.start()] + new_row + sheet_xml[m.end():]
|
||||
config.log(f'{d} 行已补上团购统计表取数链接')
|
||||
spans = {}
|
||||
for m in _ROW_RE.finditer(sheet_xml):
|
||||
spans[int(m.group(1))] = (m.start(), m.end())
|
||||
for d, row_no, idx, path, mode, todo in sorted(plan, key=lambda p: -p[1]):
|
||||
s, e = spans[row_no]
|
||||
sheet_xml = sheet_xml[:s] + _set_row_cells(sheet_xml[s:e], row_no, todo) + sheet_xml[e:]
|
||||
|
||||
for idx, path, uri in need_new:
|
||||
for key, (idx, path) in need_new.items():
|
||||
rid_num = max(int(x) for x in re.findall(r'Id="rId(\d+)"', wb_rels)) + 1
|
||||
rid = f'rId{rid_num}'
|
||||
wb_rels = wb_rels.replace(
|
||||
@@ -246,7 +306,7 @@ def run(d_from=None, d_to=None, dry_run=False):
|
||||
f'ContentType="application/vnd.openxmlformats-officedocument.'
|
||||
f'spreadsheetml.externalLink+xml"/></Types>')
|
||||
|
||||
tmp = ledger + '.rebuild.tmp'
|
||||
tmp = ledger + '.links.tmp'
|
||||
replace = {
|
||||
sheet_path: sheet_xml.encode('utf-8'),
|
||||
'xl/workbook.xml': wb_xml.encode('utf-8'),
|
||||
@@ -254,29 +314,34 @@ def run(d_from=None, d_to=None, dry_run=False):
|
||||
'[Content_Types].xml': ct_xml.encode('utf-8'),
|
||||
}
|
||||
new_files = {}
|
||||
for idx, path, uri in need_new:
|
||||
for key, (idx, path) in need_new.items():
|
||||
new_files[f'xl/externalLinks/externalLink{idx}.xml'] = \
|
||||
(_EXTLINK_TPL % config.LINK_SHEET).encode('utf-8')
|
||||
new_files[f'xl/externalLinks/_rels/externalLink{idx}.xml.rels'] = \
|
||||
(_EXTLINK_RELS_TPL % uri).encode('utf-8')
|
||||
(_EXTLINK_RELS_TPL % _file_uri(path)).encode('utf-8')
|
||||
|
||||
with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED, allowZip64=True) as dst:
|
||||
for info in zf.infolist():
|
||||
if info.is_dir():
|
||||
continue
|
||||
zi = zipfile.ZipInfo(info.filename, date_time=info.date_time)
|
||||
zi.compress_type = zipfile.ZIP_DEFLATED
|
||||
zi.external_attr = info.external_attr
|
||||
if info.filename in replace:
|
||||
dst.writestr(zi, replace.pop(info.filename))
|
||||
else:
|
||||
with zf.open(info) as fin, dst.open(zi, 'w', force_zip64=True) as fout:
|
||||
shutil.copyfileobj(fin, fout, 4 << 20)
|
||||
for name, data in list(replace.items()) + list(new_files.items()):
|
||||
dst.writestr(name, data)
|
||||
zf.close()
|
||||
zf = open_zip(ledger)
|
||||
try:
|
||||
with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED, allowZip64=True) as dst:
|
||||
for info in zf.infolist():
|
||||
if info.is_dir():
|
||||
continue
|
||||
zi = zipfile.ZipInfo(info.filename, date_time=info.date_time)
|
||||
zi.compress_type = zipfile.ZIP_DEFLATED
|
||||
zi.external_attr = info.external_attr
|
||||
if info.filename in replace:
|
||||
dst.writestr(zi, replace.pop(info.filename))
|
||||
else:
|
||||
with zf.open(info) as fin, dst.open(zi, 'w', force_zip64=True) as fout:
|
||||
shutil.copyfileobj(fin, fout, 4 << 20)
|
||||
for name, data in list(replace.items()) + list(new_files.items()):
|
||||
dst.writestr(name, data)
|
||||
finally:
|
||||
zf.close()
|
||||
os.replace(tmp, ledger)
|
||||
|
||||
config.log(f'完成:{len(plan)} 行更新 V/W,新增外部链接 {len(need_new)} 条')
|
||||
config.log(f'完成:{len(plan)} 行同源公式已更新,新增外部链接 {len(need_new)} 条')
|
||||
return {'ok': True, 'rows': [p[1] for p in plan], 'new_links': len(need_new),
|
||||
'message': f'核对统计 V/W 已更新 {len(plan)} 行'}
|
||||
'ledger': ledger,
|
||||
'message': f'{config.STAT_SHEET} 同源取数公式已更新 {len(plan)} 行'
|
||||
f'(新增外部链接 {len(need_new)} 条)'}
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xlsx(zip) 读写的兼容层。
|
||||
|
||||
背景:台账被 WPS 保存后,透视缓存的 `pivotCacheRecords*.xml` 会写成
|
||||
「local header 里 size=0xFFFFFFFF + ZIP64 extra 带真实大小、central directory 却缺 ZIP64 extra」。
|
||||
Python 3.11 的 zipfile 从 central 取到 0xFFFFFFFF,把条目当成 4GB,
|
||||
`ZipFile.open()` 直接抛 `BadZipFile: Overlapped entries ... (possible zip bomb)`。
|
||||
|
||||
这里在打开后把这类 ZipInfo 的 size 修成真实值(解析 local header 的 ZIP64 extra,
|
||||
取不到就用下一条目偏移反推),只改内存对象、不动文件;之后 `zf.open(info)` 可正常读。
|
||||
"""
|
||||
import struct
|
||||
import zipfile
|
||||
|
||||
|
||||
def _local_sizes(fp, info):
|
||||
"""从 local file header 的 ZIP64 extra 取 (usize, csize),取不到返回 (None, None)。"""
|
||||
fp.seek(info.header_offset)
|
||||
hdr = fp.read(30)
|
||||
if len(hdr) < 30 or hdr[:4] != b'PK\x03\x04':
|
||||
return None, None
|
||||
nlen, elen = struct.unpack('<HH', hdr[26:30])
|
||||
fp.read(nlen)
|
||||
extra = fp.read(elen)
|
||||
usize = csize = None
|
||||
i = 0
|
||||
while i + 4 <= len(extra):
|
||||
hid, hlen = struct.unpack('<HH', extra[i:i + 4])
|
||||
body = extra[i + 4:i + 4 + hlen]
|
||||
if hid == 0x0001: # ZIP64 extended information
|
||||
if len(body) >= 16:
|
||||
usize, csize = struct.unpack('<QQ', body[:16])
|
||||
elif len(body) >= 8:
|
||||
usize = struct.unpack('<Q', body[:8])[0]
|
||||
i += 4 + hlen
|
||||
return usize, csize
|
||||
|
||||
|
||||
def repair_sizes(zf):
|
||||
"""修 0xFFFFFFFF 的条目大小,返回修复条数。"""
|
||||
fixed = 0
|
||||
fp = getattr(zf, 'fp', None)
|
||||
if fp is None:
|
||||
return 0
|
||||
try:
|
||||
if not fp.seekable():
|
||||
return 0
|
||||
except Exception:
|
||||
return 0
|
||||
try:
|
||||
pos = fp.tell()
|
||||
except Exception:
|
||||
pos = None
|
||||
for info in zf.infolist():
|
||||
if info.compress_size != 0xFFFFFFFF and info.file_size != 0xFFFFFFFF:
|
||||
continue
|
||||
usize, csize = _local_sizes(fp, info)
|
||||
if csize is None:
|
||||
end = getattr(info, '_end_offset', None)
|
||||
if end:
|
||||
head = _peek(fp, info, 26, 4) or b'\x00\x00\x00\x00'
|
||||
nlen, elen = struct.unpack('<HH', head)
|
||||
csize = end - (info.header_offset + 30 + nlen + elen)
|
||||
if csize is None:
|
||||
continue
|
||||
info.compress_size = csize
|
||||
if usize:
|
||||
info.file_size = usize
|
||||
fixed += 1
|
||||
if pos is not None:
|
||||
try:
|
||||
fp.seek(pos)
|
||||
except Exception:
|
||||
pass
|
||||
return fixed
|
||||
|
||||
|
||||
def _peek(fp, info, offset, size):
|
||||
try:
|
||||
fp.seek(info.header_offset + offset)
|
||||
return fp.read(size)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def open_zip(path):
|
||||
"""open + 修复 WPS 写坏的 zip64 条目大小,返回可正常读取的 ZipFile。"""
|
||||
zf = zipfile.ZipFile(path)
|
||||
repair_sizes(zf)
|
||||
return zf
|
||||
@@ -2,8 +2,8 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0041",
|
||||
"name": "新美大平台核对",
|
||||
"version": "1.1.6",
|
||||
"description": "美团经营宝账单自动下载与台账核对:按需下载打款记录、团购收益明细、预订收益明细,把新产生的收益按验券时间并入月份台账,并给核对统计表补当天的团购统计表链接。登录一次后可长期复用。",
|
||||
"version": "1.1.7",
|
||||
"description": "美团经营宝账单自动下载与台账核对:按需下载打款记录、团购收益明细、预订收益明细,把新产生的收益按验券时间并入月份台账,并按日期把核对统计表整行同源取数公式([n]资金组取数!$B$xx,实测 V/W/Y/Z)换成当天共享总表的链接。登录一次后可长期复用。",
|
||||
"category": "财务",
|
||||
"icon": "",
|
||||
"platform": "",
|
||||
@@ -88,7 +88,7 @@
|
||||
"type": "boolean",
|
||||
"title": "更新核对统计",
|
||||
"default": true,
|
||||
"description": "给核对统计表对应日期的行补上当天团购统计表的取数链接"
|
||||
"description": "按核对统计 A 列日期,把整行同源取数公式([n]资金组取数!$B$xx,实测 V/W/Y/Z)换成当天那份马敏团购总表的链接;已是目标链接的单元格保留不动"
|
||||
},
|
||||
"dry_run": {
|
||||
"type": "boolean",
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0042 抖音平台核对 —— webhost 场景插件入口。
|
||||
|
||||
当前阶段:登录态获取 + 两类数据自动导出。
|
||||
打开抖音来客 → 人工登录(含验证码/滑块,浏览器里一次性完成,之后复用登录态)
|
||||
→ 按日期区间导出「核销明细」(履约管理订单列表)与「提现记录」(财务导出记录)
|
||||
→ 轮询生成状态 → 下载到本机目录(默认 D:\\资料\\财务\\抖音平台核对)。
|
||||
→ 轮询生成状态 → 下载到本机目录(默认 D:\\资料\\财务\\抖音平台核对)
|
||||
→ 核销明细增量并入台账「抖音到账统计YYYY.M月.xlsx」的「金色印象--抖音」sheet。
|
||||
→ 再按日期给「抖音到账核对」O/P 列补共享总表(资金组取数)外部取数公式。
|
||||
导出前查该类导出记录,超过保留阈值(界面可配,默认核销 60 / 提现 25)就删最早的。
|
||||
|
||||
接口签名(a_bogus / msToken)由页面 SDK 注入,插件只在页面上下文发请求,不逆向签名。
|
||||
|
||||
待补:并入台账 + 更新核对统计(口径确认后按 xq0041 的分层补齐)。
|
||||
台账写入只改目标 sheet 的 XML(保留透视表与外部链接),公式列 A、BT~CA 按模板行下拉。
|
||||
"""
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
@@ -17,6 +17,7 @@ from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
||||
|
||||
from . import config
|
||||
from .data import browser, douyin_export, douyin_login
|
||||
from .logic import merge_ledger, stat_links
|
||||
|
||||
|
||||
def _parse_day(s):
|
||||
@@ -55,9 +56,11 @@ def _limit(raw, default):
|
||||
class Xq0042Plugin(ScenePlugin):
|
||||
id = 'xq0042'
|
||||
name = '抖音平台核对'
|
||||
version = '0.6.2'
|
||||
version = '0.7.2'
|
||||
description = ('抖音来客数据自动导出:登录后按日期区间导出核销明细、提现记录,'
|
||||
'轮询生成完成后下载到本机目录;导出记录超阈值自动删最早的')
|
||||
'轮询生成完成后下载到本机目录,核销明细增量并入台账「金色印象--抖音」'
|
||||
'(公式列自动下拉),并按日期把「抖音到账核对」整行同源取数公式'
|
||||
'(资金组取数)换成当天共享总表的链接;导出记录超阈值自动删最早的')
|
||||
platform = '' # 插件自带登录(抖音来客 SSO),不用底座共享登录态
|
||||
uses_month = False
|
||||
capabilities = ['xq0042']
|
||||
@@ -73,6 +76,9 @@ class Xq0042Plugin(ScenePlugin):
|
||||
'default': config.RECORD_LIMIT_VERIFY},
|
||||
'record_limit_withdraw': {'type': 'integer', 'title': '提现记录-导出记录保留条数',
|
||||
'default': config.RECORD_LIMIT_WITHDRAW},
|
||||
'run_merge': {'type': 'boolean', 'title': '并入台账(金色印象--抖音)', 'default': True},
|
||||
'run_stat_links': {'type': 'boolean', 'title': '补核对表同源取数公式', 'default': True},
|
||||
'dry_run': {'type': 'boolean', 'title': '只统计不写入(演练)', 'default': False},
|
||||
'save_dir': {'type': 'string', 'title': '保存目录', 'default': ''},
|
||||
'force_login': {'type': 'boolean', 'title': '强制重新登录', 'default': False},
|
||||
'debug_mode': {'type': 'boolean', 'title': '调试日志', 'default': False},
|
||||
@@ -91,8 +97,13 @@ class Xq0042Plugin(ScenePlugin):
|
||||
force = bool(fields.get('force_login'))
|
||||
do_verify = fields.get('export_verify', True) is not False
|
||||
do_withdraw = fields.get('export_withdraw', True) is not False
|
||||
if not do_verify and not do_withdraw:
|
||||
raise RuntimeError('请至少勾选一项导出内容(核销明细 / 提现记录)')
|
||||
run_merge = fields.get('run_merge', True) is not False
|
||||
run_stat = fields.get('run_stat_links', True) is not False
|
||||
dry_run = bool(fields.get('dry_run'))
|
||||
do_download = do_verify or do_withdraw
|
||||
if not do_download and not run_merge and not run_stat:
|
||||
raise RuntimeError('请至少选择一项执行内容'
|
||||
'(导出核销明细 / 导出提现记录 / 并入台账 / 补核对表取数)')
|
||||
limit_verify = _limit(fields.get('record_limit_verify'), config.RECORD_LIMIT_VERIFY)
|
||||
limit_withdraw = _limit(fields.get('record_limit_withdraw'), config.RECORD_LIMIT_WITHDRAW)
|
||||
|
||||
@@ -102,44 +113,86 @@ class Xq0042Plugin(ScenePlugin):
|
||||
ranges.append(f'核销 {v_from} ~ {v_to}')
|
||||
if do_withdraw:
|
||||
ranges.append(f'提现 {w_from} ~ {w_to}')
|
||||
config.log(f'本次执行:导出{"、".join(kinds)}({";".join(ranges)})→ {save_dir}'
|
||||
+ ('(强制重新登录)' if force else ''))
|
||||
config.log(f'导出记录保留条数:核销明细 {limit_verify}、提现记录 {limit_withdraw}')
|
||||
plan = []
|
||||
if do_download:
|
||||
plan.append(f'导出{"、".join(kinds)}({";".join(ranges)})→ {save_dir}')
|
||||
if run_merge:
|
||||
plan.append(f'并入台账「{config.LEDGER_SHEET}」'
|
||||
+ ('(演练,不写文件)' if dry_run else ''))
|
||||
if run_stat:
|
||||
plan.append(f'补核对表「{config.STAT_SHEET}」同源取数公式'
|
||||
+ ('(演练,不写文件)' if dry_run else ''))
|
||||
config.log('本次执行:' + ' + '.join(plan) + ('(强制重新登录)' if force else ''))
|
||||
if do_download:
|
||||
config.log(f'导出记录保留条数:核销明细 {limit_verify}、提现记录 {limit_withdraw}')
|
||||
config.progress(5)
|
||||
|
||||
page = browser.open_page()
|
||||
results = {}
|
||||
try:
|
||||
ok, msg = douyin_login.ensure_login(page, force=force)
|
||||
config.log(msg)
|
||||
if not ok:
|
||||
raise RuntimeError(f'登录失败:{msg}')
|
||||
config.progress(30)
|
||||
login_msg = ''
|
||||
if do_download:
|
||||
page = browser.open_page()
|
||||
try:
|
||||
ok, msg = douyin_login.ensure_login(page, force=force)
|
||||
config.log(msg)
|
||||
if not ok:
|
||||
raise RuntimeError(f'登录失败:{msg}')
|
||||
login_msg = msg
|
||||
config.progress(30)
|
||||
|
||||
if do_verify:
|
||||
results['核销明细'] = douyin_export.run(page, v_from, v_to, save_dir,
|
||||
limit_verify)
|
||||
config.progress(65)
|
||||
if do_withdraw:
|
||||
results['提现记录'] = douyin_export.run_withdraw(page, w_from, w_to,
|
||||
save_dir, limit_withdraw)
|
||||
config.progress(95)
|
||||
finally:
|
||||
browser.close_page(page)
|
||||
if do_verify:
|
||||
results['核销明细'] = douyin_export.run(page, v_from, v_to, save_dir,
|
||||
limit_verify)
|
||||
config.progress(65)
|
||||
if do_withdraw:
|
||||
results['提现记录'] = douyin_export.run_withdraw(page, w_from, w_to,
|
||||
save_dir, limit_withdraw)
|
||||
config.progress(95)
|
||||
finally:
|
||||
browser.close_page(page)
|
||||
|
||||
failed = {k: v.get('message') for k, v in results.items() if not v.get('ok')}
|
||||
ok_parts = [v.get('message') for v in results.values() if v.get('ok')]
|
||||
path = next((v.get('path') for v in results.values() if v.get('ok')), '')
|
||||
if failed:
|
||||
detail = ';'.join(f'{k}失败:{m}' for k, m in failed.items())
|
||||
raise RuntimeError(('已完成:' + ';'.join(ok_parts) + '。' if ok_parts else '')
|
||||
+ detail)
|
||||
failed = {k: v.get('message') for k, v in results.items() if not v.get('ok')}
|
||||
ok_parts = [v.get('message') for v in results.values() if v.get('ok')]
|
||||
if failed:
|
||||
detail = ';'.join(f'{k}失败:{m}' for k, m in failed.items())
|
||||
raise RuntimeError(('已完成:' + ';'.join(ok_parts) + '。' if ok_parts else '')
|
||||
+ detail)
|
||||
|
||||
merge = None
|
||||
if run_merge:
|
||||
config.progress(96 if do_download else 20)
|
||||
merge = merge_ledger.run(dry_run=dry_run)
|
||||
if not merge.get('ok'):
|
||||
raise RuntimeError(f'并入台账失败:{merge.get("message")}')
|
||||
config.log(merge.get('message'))
|
||||
|
||||
links = None
|
||||
if run_stat:
|
||||
config.progress(98 if (do_download or run_merge) else 30)
|
||||
links = stat_links.run(dry_run=dry_run)
|
||||
if not links.get('ok'):
|
||||
raise RuntimeError(f'补核对表取数公式失败:{links.get("message")}')
|
||||
config.log(links.get('message'))
|
||||
config.progress(100)
|
||||
|
||||
parts = []
|
||||
if results:
|
||||
parts.append(f'{";".join(ranges)}:' + ';'.join(
|
||||
v.get('message') for v in results.values() if v.get('ok')))
|
||||
if merge is not None:
|
||||
parts.append(str(merge.get('message')))
|
||||
if links is not None:
|
||||
parts.append(str(links.get('message')))
|
||||
path = next((v.get('path') for v in results.values() if v.get('ok')), '')
|
||||
if not path and merge:
|
||||
path = merge.get('ledger') or ''
|
||||
if not path and links:
|
||||
path = links.get('ledger') or ''
|
||||
return {
|
||||
'summary': f'{";".join(ranges)}:' + ';'.join(ok_parts),
|
||||
'summary': ';'.join(p for p in parts if p) or '执行完成',
|
||||
'detail': {'date_from': v_from, 'date_to': v_to,
|
||||
'withdraw_from': w_from, 'withdraw_to': w_to,
|
||||
'login': msg, 'results': results},
|
||||
'login': login_msg, 'results': results,
|
||||
'merge': merge, 'stat_links': links, 'dry_run': dry_run},
|
||||
'path': path,
|
||||
}
|
||||
|
||||
|
||||
@@ -82,6 +82,37 @@ DELETE_MAX_PER_RUN = 20 # 单次运行最多删几条,超出部
|
||||
# ==================== 输出目录 ====================
|
||||
WORK_DIR = r'D:\资料\财务\抖音平台核对' # 核销明细 + 台账统一目录
|
||||
|
||||
# ==================== 台账合并(金色印象--抖音) ====================
|
||||
# 口径参考 xq0041 新美大:按台账「核销时间」列最大值增量追加明细,其余列按表头同名对齐。
|
||||
# 抖音台账结构(2026-09 版实测):
|
||||
# 表头第 1 行、数据第 2 行起,A~CC 共 81 列;
|
||||
# A 列 =`=M*1`(日期)、BT~CA = 核对公式(撮合标识 / 达人辅助 / 核对 / 核销时间 / 交班 / 0 点 / 0 点标识),
|
||||
# CC 列(XLOOKUP 返佣)业务不要求脚本补,故不写;
|
||||
# 尾部 76804~91697 是只剩公式的空行(max_row 被撑大,写入前要清掉)。
|
||||
LEDGER_GLOB = '抖音到账统计*.xlsx'
|
||||
LEDGER_SHEET = '金色印象--抖音'
|
||||
TIME_COL = '核销时间'
|
||||
DETAIL_GLOB = '核销明细*.xlsx'
|
||||
HEADER_ROW = 1
|
||||
DATA_START_ROW = 2
|
||||
FORMULA_SKIP_COLS = ('CC',) # 不随行下拉的公式列(业务口径:CC 不管)
|
||||
NUM_TYPE_SAMPLE = 30 # 判断某列写数值还是文本时参考的末行样本数
|
||||
|
||||
# ==================== 核对表取数链接(抖音到账核对) ====================
|
||||
# 「抖音到账核对」整行都是外部工作簿取数(与 xq0041 新美大核对统计同源,同一份共享总表):
|
||||
# O = [n]资金组取数!$B$24 应收岗-团购统计表-昨日遗留 (E)
|
||||
# P = -[n]资金组取数!$B$25 应收岗-团购统计表-本日遗留 (F)
|
||||
# R = [n]资金组取数!$B$22 充值
|
||||
# S = [n]资金组取数!$B$23
|
||||
# 外部文件 = \\caiwu01\共享文件夹\1111\TG\{YYYY}年{M}月\{M}.{D}\马敏团购总表{M}.{D}.xlsx
|
||||
# 口径:每行按 A 列日期指向「当天那份财务共享总表」;台账历史只把 9.27/9.28/9.29 三行改对,
|
||||
# 其余行仍是 [1](9.1 的文件),所以要按日期重写(已是目标链接的行原样保留,含缓存值)。
|
||||
# 列不写死:stat_links 扫整行所有 `[n]资金组取数!` 公式,把 [n] 换成该行日期的编号。
|
||||
STAT_SHEET = '抖音到账核对'
|
||||
SHARE_ROOT = r'\\caiwu01\共享文件夹\1111\TG'
|
||||
LINK_BOOK = '马敏团购总表'
|
||||
LINK_SHEET = '资金组取数'
|
||||
|
||||
# ==================== 运行参数 ====================
|
||||
LOGIN_WAIT = 600 # 等待人工登录(含验证码/滑块)超时
|
||||
BACKEND_STABLE = 15 # 后台页连续稳定秒数(登录后有短暂回跳登录页的现象)
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""逻辑层:核销明细增量并入「金色印象--抖音」台账。"""
|
||||
@@ -0,0 +1,626 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""台账增量合并:把「核销明细」里比台账更新的行追加到「金色印象--抖音」。
|
||||
|
||||
财务口径(2026-10 确认,参考 xq0041 新美大):
|
||||
1. 台账取同目录 `抖音到账统计YYYY.M月.xlsx` 里**月份最新**的一份(排除 `_备份*`);
|
||||
2. 取该 sheet「核销时间」列的**最大时间**;
|
||||
3. 核销明细(可一次多份,`核销明细-核销时间-起_止.xlsx`)里比该时间旧的行剔除,
|
||||
其余按**表头同名**对齐追加(明细比台账多的列忽略,台账独有的列留空);
|
||||
4. 写入起点 = **真实数据末行 + 1**(max_row 被尾部空公式行撑大,直接用会在中间留空行),
|
||||
尾部既有空公式行先清掉,避免与新数据交错;
|
||||
5. 公式列按模板行(真实末行)下拉:A 列 `=M*1`、BT~CA 核对区
|
||||
(内联公式按行号平移;共享公式 `<f t="shared" si="N"/>` 先按 si 找主定义再平移,
|
||||
效果等同手工双击右下角);**CC 列业务不管,不写**。
|
||||
|
||||
写入方式:只改目标 sheet 的 XML(清尾部空行、`</sheetData>` 前插行、更新 dimension),
|
||||
其余部件逐字节拷贝 —— 台账含 5 个透视表 + 4 个外部链接,openpyxl 全量 load→save 会丢
|
||||
透视表,且目标 sheet 解压后 314MB、网表尾部还有 1.4 万行空公式行。
|
||||
"""
|
||||
import glob
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import time
|
||||
import zipfile
|
||||
from datetime import date, datetime
|
||||
|
||||
from openpyxl import load_workbook
|
||||
from openpyxl.reader.strings import read_string_table
|
||||
|
||||
from .zipio import open_zip
|
||||
|
||||
from .. import config
|
||||
|
||||
_NS_MAIN = '{http://schemas.openxmlformats.org/spreadsheetml/2006/main}'
|
||||
_NS_REL = '{http://schemas.openxmlformats.org/officeDocument/2006/relationships}'
|
||||
_NS_PKGREL = '{http://schemas.openxmlformats.org/package/2006/relationships}'
|
||||
_MONTH_RE = re.compile(r'(\d{4})[.\-年](\d{1,2})\s*月')
|
||||
_ROW_RE = re.compile(rb'<row r="(\d+)"[^>]*?(?:/>|>(.*?)</row>)', re.S)
|
||||
_CELL_RE = re.compile(rb'<c r="([A-Z]{1,3})(\d+)"([^>]*?)(?:/>|>(.*?)</c>)', re.S)
|
||||
_V_RE = re.compile(rb'<v>([^<]*)</v>')
|
||||
_F_RE = re.compile(rb'<f([^>]*?)(?:/>|>(.*?)</f>)', re.S)
|
||||
_IS_T_RE = re.compile(rb'<t[^>]*>(.*?)</t>', re.S)
|
||||
_NUM_RE = re.compile(r'-?\d+(?:\.\d+)?')
|
||||
_SI_RE = re.compile(rb'si="(\d+)"')
|
||||
|
||||
|
||||
# ==================== 通用小工具 ====================
|
||||
def _to_dt(v):
|
||||
if v is None:
|
||||
return None
|
||||
if isinstance(v, datetime):
|
||||
return v
|
||||
if isinstance(v, date):
|
||||
return datetime(v.year, v.month, v.day)
|
||||
s = str(v).strip()
|
||||
if not s:
|
||||
return None
|
||||
for fmt in ('%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d',
|
||||
'%Y/%m/%d %H:%M:%S', '%Y/%m/%d'):
|
||||
try:
|
||||
return datetime.strptime(s, fmt)
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _month_key(path):
|
||||
m = _MONTH_RE.search(os.path.basename(path))
|
||||
return (int(m.group(1)), int(m.group(2))) if m else (0, 0)
|
||||
|
||||
|
||||
def _pick_latest(pattern, by_month=True):
|
||||
"""排除备份文件与临时文件(`_备份20261029_145157.xlsx` 同样匹配 glob)。"""
|
||||
files = [p for p in glob.glob(os.path.join(config.WORK_DIR, pattern))
|
||||
if '备份' not in os.path.basename(p) and not p.endswith('.rebuild.tmp')]
|
||||
if not files:
|
||||
return None
|
||||
if by_month:
|
||||
files.sort(key=lambda p: (_month_key(p), os.path.getmtime(p)))
|
||||
else:
|
||||
files.sort(key=os.path.getmtime)
|
||||
return files[-1]
|
||||
|
||||
|
||||
def _col_letter(n):
|
||||
s = ''
|
||||
while n > 0:
|
||||
n, r = divmod(n - 1, 26)
|
||||
s = chr(65 + r) + s
|
||||
return s
|
||||
|
||||
|
||||
def _col_num(letters):
|
||||
n = 0
|
||||
for ch in letters:
|
||||
n = n * 26 + (ord(ch) - 64)
|
||||
return n
|
||||
|
||||
|
||||
def _skip_cols():
|
||||
return {_col_num(c) for c in config.FORMULA_SKIP_COLS}
|
||||
|
||||
|
||||
def _xml_text(v):
|
||||
return (str(v).replace('&', '&').replace('<', '<')
|
||||
.replace('>', '>').replace('"', '"'))
|
||||
|
||||
|
||||
def _num_text(v):
|
||||
"""能当数字写就返回数字文本,否则 None(金额列写成数值,避免整列变文本)。"""
|
||||
if v is None or isinstance(v, bool):
|
||||
return None
|
||||
if isinstance(v, (int, float)):
|
||||
f = float(v)
|
||||
else:
|
||||
s = str(v).strip().replace(',', '')
|
||||
if not _NUM_RE.fullmatch(s):
|
||||
return None
|
||||
f = float(s)
|
||||
if f.is_integer() and abs(f) < 1e15:
|
||||
return str(int(f))
|
||||
return repr(round(f, 10))
|
||||
|
||||
|
||||
# ==================== 台账读取(流式,不整体加载) ====================
|
||||
def _sheet_xml_path(zf, sheet_name):
|
||||
import xml.etree.ElementTree as ET
|
||||
root = ET.fromstring(zf.read('xl/workbook.xml'))
|
||||
rid = None
|
||||
for s in root.iter(f'{_NS_MAIN}sheet'):
|
||||
if s.get('name') == sheet_name:
|
||||
rid = s.get(f'{_NS_REL}id')
|
||||
break
|
||||
if not rid:
|
||||
return None
|
||||
rels = ET.fromstring(zf.read('xl/_rels/workbook.xml.rels'))
|
||||
for rel in rels.iter(f'{_NS_PKGREL}Relationship'):
|
||||
if rel.get('Id') == rid:
|
||||
t = (rel.get('Target') or '').lstrip('/')
|
||||
return t if t.startswith('xl/') else 'xl/' + t
|
||||
return None
|
||||
|
||||
|
||||
def _cell_map(inner):
|
||||
out = {}
|
||||
for m in _CELL_RE.finditer(inner):
|
||||
out[m.group(1)] = (m.group(3), m.group(4) or b'')
|
||||
return out
|
||||
|
||||
|
||||
def _cell_text(attrs, body, strings):
|
||||
if b't="inlineStr"' in attrs:
|
||||
tm = _IS_T_RE.search(body)
|
||||
return tm.group(1).decode('utf-8', 'replace') if tm else None
|
||||
vm = _V_RE.search(body)
|
||||
if not vm:
|
||||
return None
|
||||
raw = vm.group(1)
|
||||
if b't="s"' in attrs:
|
||||
try:
|
||||
idx = int(raw)
|
||||
except ValueError:
|
||||
return None
|
||||
return strings[idx] if 0 <= idx < len(strings) else None
|
||||
return raw.decode('utf-8', 'replace')
|
||||
|
||||
|
||||
def _is_num(attrs, body):
|
||||
if b't=' in attrs:
|
||||
return False
|
||||
return b'<v>' in body
|
||||
|
||||
|
||||
def _scan_ledger(path, sheet_name):
|
||||
"""扫台账:表头、真实末行、时间列最大值、末行模板样式、分母/分子类型。"""
|
||||
zf = open_zip(path)
|
||||
try:
|
||||
sheet_path = _sheet_xml_path(zf, sheet_name)
|
||||
if not sheet_path:
|
||||
return {'ok': False, 'message': f'台账里找不到 sheet「{sheet_name}」'}
|
||||
try:
|
||||
strings = read_string_table(zf.open('xl/sharedStrings.xml'))
|
||||
except KeyError:
|
||||
strings = []
|
||||
|
||||
header, last_data_row = {}, config.HEADER_ROW
|
||||
max_dt, max_keys = None, set()
|
||||
tpl_cells, tpl_row_no = {}, 0
|
||||
type_rows, shared = [], {}
|
||||
|
||||
with zf.open(sheet_path) as f:
|
||||
buf = b''
|
||||
while True:
|
||||
chunk = f.read(4 << 20)
|
||||
if not chunk and not buf:
|
||||
break
|
||||
buf += chunk
|
||||
pos = 0
|
||||
while True:
|
||||
m = _ROW_RE.search(buf, pos)
|
||||
if not m:
|
||||
break
|
||||
pos = m.end()
|
||||
r = int(m.group(1))
|
||||
inner = m.group(2) or b''
|
||||
cells = _cell_map(inner)
|
||||
|
||||
# 共享公式主定义:只有主定义带公式文本,其余是自闭合引用
|
||||
if b't="shared"' in inner:
|
||||
for letter, (attrs, body) in cells.items():
|
||||
fm = _F_RE.search(body)
|
||||
if not fm or not fm.group(2) or b't="shared"' not in fm.group(1):
|
||||
continue
|
||||
sm = _SI_RE.search(fm.group(1))
|
||||
if sm:
|
||||
shared[sm.group(1).decode()] = (
|
||||
r, fm.group(2).decode('utf-8', 'replace'))
|
||||
|
||||
if r == config.HEADER_ROW:
|
||||
for letter, (attrs, body) in cells.items():
|
||||
name = _cell_text(attrs, body, strings)
|
||||
if name and str(name).strip():
|
||||
header.setdefault(str(name).strip(),
|
||||
_col_num(letter.decode()))
|
||||
continue
|
||||
if r < config.DATA_START_ROW:
|
||||
continue
|
||||
|
||||
keys = []
|
||||
for col in (b'B', b'F', b'M'):
|
||||
cell = cells.get(col)
|
||||
keys.append(_cell_text(cell[0], cell[1], strings) if cell else None)
|
||||
if not any(k for k in keys):
|
||||
continue # 尾部只剩公式的空行
|
||||
|
||||
last_data_row = r
|
||||
tpl_cells = _tpl_from_cells(cells)
|
||||
tpl_row_no = r
|
||||
types = {}
|
||||
for letter, (attrs, body) in cells.items():
|
||||
if b'<f' in body:
|
||||
continue
|
||||
types[letter] = 'num' if _is_num(attrs, body) else 'text'
|
||||
type_rows.append(types)
|
||||
if len(type_rows) > config.NUM_TYPE_SAMPLE:
|
||||
type_rows.pop(0)
|
||||
|
||||
dt = _to_dt(keys[2])
|
||||
if dt is not None:
|
||||
key = (keys[0] or '', keys[1] or '', keys[2] or '')
|
||||
if max_dt is None or dt > max_dt:
|
||||
max_dt, max_keys = dt, {key}
|
||||
elif dt == max_dt:
|
||||
max_keys.add(key)
|
||||
|
||||
buf = buf[pos:]
|
||||
if not chunk:
|
||||
break
|
||||
|
||||
# 数值列判定:末 N 行里数字出现次数多于文本才算(金额列写数值,其余照旧写文本)
|
||||
num_cols = set()
|
||||
counts = {}
|
||||
for row in type_rows:
|
||||
for letter, kind in row.items():
|
||||
c = counts.setdefault(letter, [0, 0])
|
||||
c[0 if kind == 'num' else 1] += 1
|
||||
for letter, (num_cnt, txt_cnt) in counts.items():
|
||||
if num_cnt > txt_cnt:
|
||||
num_cols.add(_col_num(letter.decode()))
|
||||
|
||||
return {'ok': True, 'header': header, 'last_data_row': last_data_row,
|
||||
'max_dt': max_dt, 'max_keys': max_keys, 'tpl': tpl_cells,
|
||||
'tpl_row': tpl_row_no, 'num_cols': num_cols, 'shared': shared,
|
||||
'max_row': _max_row(zf, sheet_path)}
|
||||
finally:
|
||||
zf.close()
|
||||
|
||||
|
||||
def _max_row(zf, sheet_path):
|
||||
"""dimension 里的最大行号(尾部空公式行也算)。"""
|
||||
head = zf.open(sheet_path).read(4096)
|
||||
m = re.search(rb'<dimension ref="[A-Z]+\d+:[A-Z]+(\d+)"', head)
|
||||
return int(m.group(1)) if m else 0
|
||||
|
||||
|
||||
def _check_formula_cols(info):
|
||||
"""模板行里引用了共享公式但找不到主定义的列(找不到就没法下拉,必须报出来)。"""
|
||||
bad = []
|
||||
for letter, cell in (info.get('tpl') or {}).items():
|
||||
if cell.get('f'):
|
||||
continue
|
||||
if cell.get('si') and cell['si'] not in (info.get('shared') or {}):
|
||||
bad.append(letter)
|
||||
return bad
|
||||
|
||||
|
||||
def _tpl_from_cells(cells):
|
||||
out = {}
|
||||
for letter, (attrs, body) in cells.items():
|
||||
sm = re.search(rb'\bs="(\d+)"', attrs)
|
||||
info = {'s': sm.group(1).decode() if sm else None, 'f': None, 'si': None}
|
||||
fm = _F_RE.search(body)
|
||||
if fm:
|
||||
info['f'] = fm.group(2).decode('utf-8', 'replace') if fm.group(2) else None
|
||||
if b't="shared"' in fm.group(1):
|
||||
si = _SI_RE.search(fm.group(1))
|
||||
info['si'] = si.group(1).decode() if si else None
|
||||
out[letter.decode()] = info
|
||||
return out
|
||||
|
||||
|
||||
# ==================== 公式平移 / 新行 XML ====================
|
||||
def _shift_formula(formula, from_row, to_row):
|
||||
"""把公式里的相对行号从 from_row 平移到 to_row($ 锁定的行号不动)。"""
|
||||
if not formula or from_row == to_row:
|
||||
return formula
|
||||
delta = to_row - from_row
|
||||
|
||||
def repl(m):
|
||||
col, lock, row = m.group(1), m.group(2), m.group(3)
|
||||
if lock == '$':
|
||||
return m.group(0)
|
||||
return f'{col}{int(row) + delta}'
|
||||
|
||||
return re.sub(r'(?<![A-Za-z0-9_])([A-Z]{1,3})(\$?)(\d+)', repl, formula)
|
||||
|
||||
|
||||
def _rows_xml(rows, start_row, col_map, tpl, tpl_row, shared, num_cols):
|
||||
"""新行 XML:值列写值(数值列写数值、其余写文本),公式列按模板行下拉。"""
|
||||
skip_cols = _skip_cols()
|
||||
val_cols = {lcol for _, lcol in col_map}
|
||||
parts = []
|
||||
for i, row in enumerate(rows):
|
||||
r = start_row + i
|
||||
cells = []
|
||||
for didx, lcol in col_map:
|
||||
info = tpl.get(_col_letter(lcol)) or {}
|
||||
s_attr = f' s="{info["s"]}"' if info.get('s') else ''
|
||||
raw = row[didx] if didx < len(row) else None
|
||||
if raw is None or (isinstance(raw, str) and raw == ''):
|
||||
continue
|
||||
letter = _col_letter(lcol)
|
||||
if lcol in num_cols:
|
||||
num = _num_text(raw)
|
||||
if num is not None:
|
||||
cells.append((lcol, f'<c r="{letter}{r}"{s_attr}><v>{num}</v></c>'))
|
||||
continue
|
||||
cells.append((lcol, f'<c r="{letter}{r}"{s_attr} t="inlineStr">'
|
||||
f'<is><t xml:space="preserve">{_xml_text(raw)}</t></is></c>'))
|
||||
|
||||
for letter, info in tpl.items():
|
||||
cnum = _col_num(letter)
|
||||
if cnum in val_cols or cnum in skip_cols:
|
||||
continue
|
||||
formula = None
|
||||
if info.get('f'):
|
||||
formula = _shift_formula(info['f'], tpl_row, r)
|
||||
elif info.get('si') and info['si'] in shared:
|
||||
def_row, text = shared[info['si']]
|
||||
formula = _shift_formula(text, def_row, r)
|
||||
if not formula:
|
||||
continue
|
||||
s_attr = f' s="{info["s"]}"' if info.get('s') else ''
|
||||
cells.append((cnum, f'<c r="{letter}{r}"{s_attr}><f>{formula}</f></c>'))
|
||||
|
||||
if not cells:
|
||||
continue
|
||||
cells.sort(key=lambda x: x[0])
|
||||
parts.append(f'<row r="{r}">{"".join(c for _, c in cells)}</row>')
|
||||
return ''.join(parts).encode('utf-8')
|
||||
|
||||
|
||||
# ==================== 原生 XML 写入 ====================
|
||||
def _append_rows_native(path, sheet_name, payload, new_max_row, skip_from_row):
|
||||
"""流式重写目标 sheet:更新 dimension → 丢弃尾部空公式行 → 插新行 → 其余部件原样拷贝。"""
|
||||
tmp = path + '.rebuild.tmp'
|
||||
marker = b'</sheetData>'
|
||||
skip_tag = f'<row r="{skip_from_row}"'.encode()
|
||||
inserted = False
|
||||
|
||||
src = open_zip(path)
|
||||
sheet_path = _sheet_xml_path(src, sheet_name)
|
||||
if not sheet_path:
|
||||
src.close()
|
||||
raise RuntimeError(f'workbook 里找不到 sheet「{sheet_name}」')
|
||||
with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED, allowZip64=True) as dst:
|
||||
for info in src.infolist():
|
||||
if info.is_dir():
|
||||
continue
|
||||
zi = zipfile.ZipInfo(info.filename, date_time=info.date_time)
|
||||
zi.compress_type = zipfile.ZIP_DEFLATED
|
||||
zi.external_attr = info.external_attr
|
||||
with src.open(info) as fin, dst.open(zi, 'w', force_zip64=True) as fout:
|
||||
if info.filename != sheet_path:
|
||||
shutil.copyfileobj(fin, fout, 4 << 20)
|
||||
continue
|
||||
|
||||
dim_done = False
|
||||
dropping = False
|
||||
buf = b''
|
||||
while True:
|
||||
chunk = fin.read(4 << 20)
|
||||
if not chunk:
|
||||
if buf and not inserted:
|
||||
fout.write(buf)
|
||||
break
|
||||
buf += chunk
|
||||
if not dim_done:
|
||||
buf = re.sub(
|
||||
rb'(<dimension ref="[A-Z]+\d+:[A-Z]+)\d+(")',
|
||||
lambda m: m.group(1) + str(new_max_row).encode() + m.group(2),
|
||||
buf, count=1)
|
||||
dim_done = True
|
||||
|
||||
if dropping:
|
||||
idx = buf.find(marker)
|
||||
if idx < 0:
|
||||
buf = buf[-(len(marker) - 1):]
|
||||
continue
|
||||
fout.write(payload)
|
||||
fout.write(buf[idx:])
|
||||
shutil.copyfileobj(fin, fout, 4 << 20)
|
||||
inserted = True
|
||||
break
|
||||
|
||||
i_skip = buf.find(skip_tag)
|
||||
i_mark = buf.find(marker)
|
||||
if i_mark >= 0 and (i_skip < 0 or i_mark < i_skip):
|
||||
fout.write(buf[:i_mark])
|
||||
fout.write(payload)
|
||||
fout.write(buf[i_mark:])
|
||||
shutil.copyfileobj(fin, fout, 4 << 20)
|
||||
inserted = True
|
||||
break
|
||||
if i_skip >= 0:
|
||||
fout.write(buf[:i_skip])
|
||||
buf = buf[i_skip:]
|
||||
dropping = True
|
||||
continue
|
||||
keep = max(len(skip_tag), len(marker), 512 * 1024)
|
||||
fout.write(buf[:-keep])
|
||||
buf = buf[-keep:]
|
||||
src.close() # Windows 下必须先放句柄,否则 os.replace 失败
|
||||
if not inserted:
|
||||
try:
|
||||
os.remove(tmp)
|
||||
except OSError:
|
||||
pass
|
||||
raise RuntimeError('sheet xml 里没找到 </sheetData>,未做任何修改')
|
||||
os.replace(tmp, path)
|
||||
return len(payload)
|
||||
|
||||
|
||||
# ==================== 明细读取 ====================
|
||||
def _header_index(header):
|
||||
out = {}
|
||||
for i, v in enumerate(header):
|
||||
if v is None:
|
||||
continue
|
||||
name = str(v).strip()
|
||||
if name and name not in out:
|
||||
out[name] = i
|
||||
return out
|
||||
|
||||
|
||||
def _read_details(files, ledger_max, max_keys):
|
||||
"""读全部核销明细,剔除比台账旧的行与台账边界已有的行。"""
|
||||
head, rows = None, []
|
||||
total = skip_old = skip_dup = skip_notime = 0
|
||||
seen = set()
|
||||
for path in files:
|
||||
# 平台导出的明细 dimension 常是 A1(read_only 只会读到第一列),文件不大,直接完整加载
|
||||
wb = load_workbook(path, data_only=True)
|
||||
try:
|
||||
ws = wb.worksheets[0]
|
||||
it = ws.iter_rows(values_only=True)
|
||||
first = next(it, None)
|
||||
if first is None:
|
||||
continue
|
||||
dhead = _header_index(first)
|
||||
if head is None:
|
||||
head = dhead
|
||||
for name in ('订单编号', config.TIME_COL):
|
||||
if name not in dhead:
|
||||
return {'ok': False,
|
||||
'message': f'明细「{os.path.basename(path)}」缺少列「{name}」'}
|
||||
ti = head[config.TIME_COL]
|
||||
oi = head.get('订单编号')
|
||||
ci = next((i for n, i in head.items() if n.startswith('券码')), None)
|
||||
for row in it:
|
||||
if row is None:
|
||||
continue
|
||||
total += 1
|
||||
raw_t = row[ti] if ti < len(row) else None
|
||||
dt = _to_dt(raw_t)
|
||||
if dt is None:
|
||||
skip_notime += 1
|
||||
continue
|
||||
if dt < ledger_max:
|
||||
skip_old += 1
|
||||
continue
|
||||
key = (str(row[oi] or '') if oi is not None and oi < len(row) else '',
|
||||
str(row[ci] or '') if ci is not None and ci < len(row) else '',
|
||||
str(raw_t or ''))
|
||||
if dt == ledger_max and key in max_keys:
|
||||
skip_dup += 1
|
||||
continue
|
||||
if key in seen:
|
||||
skip_dup += 1
|
||||
continue
|
||||
seen.add(key)
|
||||
rows.append((dt, row))
|
||||
finally:
|
||||
wb.close()
|
||||
# 多份明细按核销时间排序后追加,保持台账「时间递增」的历史形态
|
||||
rows.sort(key=lambda x: x[0])
|
||||
return {'ok': True, 'head': head or {}, 'rows': [r for _, r in rows],
|
||||
'total': total, 'skip_old': skip_old, 'skip_dup': skip_dup,
|
||||
'skip_notime': skip_notime}
|
||||
|
||||
|
||||
# ==================== 入口 ====================
|
||||
def run(dry_run=False):
|
||||
"""执行合并。返回 {ok, appended, start_row, end_row, ledger, message}。"""
|
||||
if not os.path.isdir(config.WORK_DIR):
|
||||
return {'ok': False, 'message': f'目录不存在:{config.WORK_DIR}'}
|
||||
ledger = _pick_latest(config.LEDGER_GLOB, by_month=True)
|
||||
if not ledger:
|
||||
return {'ok': False, 'message': f'未找到台账:{config.LEDGER_GLOB}'}
|
||||
config.log(f'台账:{os.path.basename(ledger)}({_month_key(ledger)[0]}年'
|
||||
f'{_month_key(ledger)[1]}月)')
|
||||
|
||||
details = [p for p in glob.glob(os.path.join(config.WORK_DIR, config.DETAIL_GLOB))
|
||||
if '备份' not in os.path.basename(p) and not p.endswith('.rebuild.tmp')
|
||||
and not os.path.basename(p).startswith('~$')]
|
||||
if not details:
|
||||
return {'ok': False, 'message': f'未找到核销明细:{config.DETAIL_GLOB}'}
|
||||
details.sort(key=os.path.getmtime)
|
||||
config.log(f'核销明细 {len(details)} 份:' +
|
||||
'、'.join(os.path.basename(p) for p in details))
|
||||
|
||||
t0 = time.time()
|
||||
info = _scan_ledger(ledger, config.LEDGER_SHEET)
|
||||
if not info.get('ok'):
|
||||
return {'ok': False, 'message': info.get('message')}
|
||||
if config.TIME_COL not in info['header']:
|
||||
return {'ok': False, 'message': f'台账表头缺少「{config.TIME_COL}」'}
|
||||
if info['max_dt'] is None:
|
||||
return {'ok': False, 'message': f'台账「{config.TIME_COL}」列没有有效时间'}
|
||||
last_data = info['last_data_row']
|
||||
tail = (info.get('max_row') or last_data) - last_data
|
||||
config.log(f'台账真实末行 {last_data},{config.TIME_COL}最大 {info["max_dt"]},'
|
||||
f'尾部 {tail} 行空公式行(dimension 到 {info.get("max_row")});'
|
||||
f'扫描耗时 {time.time() - t0:.1f}s')
|
||||
|
||||
bad_formula = _check_formula_cols(info)
|
||||
if bad_formula:
|
||||
msg = f'模板行 {info["tpl_row"]} 的公式列 {bad_formula} 找不到共享公式主定义'
|
||||
if 'A' in bad_formula:
|
||||
return {'ok': False, 'message': msg + '(A 列日期为公式,无法下拉)'}
|
||||
config.log(msg + ',这些列本次留空', 'WARN')
|
||||
fcols = [c for c, v in info['tpl'].items() if v.get('f') or v.get('si')]
|
||||
config.log(f'公式列(按模板行下拉):{fcols}', 'DEBUG')
|
||||
config.log(f'不写公式的列:{list(config.FORMULA_SKIP_COLS)}(业务口径:CC 不管)', 'DEBUG')
|
||||
|
||||
det = _read_details(details, info['max_dt'], info['max_keys'])
|
||||
if not det.get('ok'):
|
||||
return {'ok': False, 'message': det.get('message')}
|
||||
rows = det['rows']
|
||||
config.log(f'明细共 {det["total"]} 行:保留 {len(rows)},'
|
||||
f'早于台账 {det["skip_old"]},重复 {det["skip_dup"]},'
|
||||
f'无核销时间 {det["skip_notime"]}')
|
||||
if not rows:
|
||||
return {'ok': True, 'appended': 0, 'ledger': ledger,
|
||||
'message': '明细里没有比台账更新的记录'}
|
||||
|
||||
lhead = info['header']
|
||||
dhead = det['head']
|
||||
col_map = [(didx, lhead[name]) for name, didx in dhead.items()
|
||||
if name in lhead and lhead[name] != 1] # A 列日期是公式,不写值
|
||||
missing = [n for n in lhead if n not in dhead]
|
||||
ignored = [n for n in dhead if n not in lhead]
|
||||
config.log(f'列映射 {len(col_map)} 列;台账独有(留空):{missing or "无"};'
|
||||
f'明细独有(忽略):{ignored or "无"}', 'DEBUG')
|
||||
|
||||
start_row = last_data + 1
|
||||
new_max_row = start_row + len(rows) - 1
|
||||
config.log(f'并入范围:台账第 {start_row} ~ {new_max_row} 行')
|
||||
|
||||
if dry_run:
|
||||
return {'ok': True, 'appended': 0, 'start_row': start_row, 'end_row': new_max_row,
|
||||
'ledger': ledger, 'message': f'[演练] 将追加 {len(rows)} 行'}
|
||||
|
||||
lock = os.path.join(os.path.dirname(ledger), '~$' + os.path.basename(ledger))
|
||||
if os.path.exists(lock):
|
||||
return {'ok': False, 'message': '台账正在 Excel 中打开(检测到 ~$ 锁文件),'
|
||||
'请关闭后重跑'}
|
||||
try:
|
||||
with open(ledger, 'r+b'):
|
||||
pass
|
||||
except OSError as e:
|
||||
return {'ok': False, 'message': f'台账不可写(可能被 Excel 占用):{e}'}
|
||||
|
||||
bak = os.path.join(
|
||||
config.WORK_DIR,
|
||||
f'{os.path.splitext(os.path.basename(ledger))[0]}_备份'
|
||||
f'{time.strftime("%Y%m%d_%H%M%S")}.xlsx')
|
||||
shutil.copy2(ledger, bak)
|
||||
config.log(f'已备份 → {os.path.basename(bak)}')
|
||||
|
||||
payload = _rows_xml(rows, start_row, col_map, info['tpl'], info['tpl_row'],
|
||||
info['shared'], info['num_cols'])
|
||||
t1 = time.time()
|
||||
size = _append_rows_native(ledger, config.LEDGER_SHEET, payload, new_max_row,
|
||||
skip_from_row=start_row)
|
||||
config.log(f'并入完成:{len(rows)} 行,耗时 {time.time() - t1:.1f}s'
|
||||
f'(写入 {size / 1024:.0f} KB)')
|
||||
|
||||
verify = _scan_ledger(ledger, config.LEDGER_SHEET)
|
||||
if verify.get('ok'):
|
||||
config.log(f'校验:真实末行 {verify["last_data_row"]}(预期 {new_max_row}),'
|
||||
f'{config.TIME_COL}最大 {verify["max_dt"]}')
|
||||
|
||||
return {'ok': True, 'appended': len(rows), 'start_row': start_row,
|
||||
'end_row': new_max_row, 'ledger': ledger,
|
||||
'message': f'已并入 {len(rows)} 行到台账'}
|
||||
@@ -0,0 +1,335 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""「抖音到账核对」按日期补共享总表取数公式(自动扫描整行同源公式)。
|
||||
|
||||
业务口径:该 sheet 里所有形如 `[n]资金组取数!$B$xx` 的公式都属于「同源取数」,每行应按 A 列日期
|
||||
指向**当天那份**财务共享总表(当前实测 4 列 × 39 行 = 156 个):
|
||||
O = [n]资金组取数!$B$24 应收岗-团购统计表-昨日遗留 (E)
|
||||
P = -[n]资金组取数!$B$25 应收岗-团购统计表-本日遗留 (F)
|
||||
R = [n]资金组取数!$B$22 充值
|
||||
S = [n]资金组取数!$B$23
|
||||
外部文件:file:///\\\\caiwu01\\共享文件夹\\1111\\TG\\{YYYY}年{M}月\\{M}.{D}\\马敏团购总表{M}.{D}.xlsx
|
||||
|
||||
实现:**不写死列名**——扫描目标行里每个公式,凡含 `[n]资金组取数!` 就把其中的 [n] 换成该行日期
|
||||
对应的编号(前置负号、单元格地址、公式其它部分原样保留;引用别的工作簿的 [n] 不动)。
|
||||
已是目标编号的单元格原样保留(含缓存值),只改对不上的。缺的外部链接新增部件并五处同步。
|
||||
共享盘不可达不阻塞:公式照写,Excel 打开点「更新链接」即可取值。
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import time
|
||||
import zipfile
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from .. import config
|
||||
from .zipio import open_zip
|
||||
|
||||
_EXTLINK_TPL = (
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
|
||||
'<externalLink xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"'
|
||||
' xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">'
|
||||
'<externalBook r:id="rId1"><sheetNames><sheetName val="%s"/></sheetNames>'
|
||||
'<sheetDataSet><sheetData sheetId="0"/></sheetDataSet></externalBook></externalLink>'
|
||||
)
|
||||
_EXTLINK_RELS_TPL = (
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
|
||||
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
|
||||
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/'
|
||||
'relationships/externalLinkPath" Target="%s" TargetMode="External"/></Relationships>'
|
||||
)
|
||||
_CELL_RE = re.compile(r'<c r="([A-Z]+)(\d+)"([^>]*?)'
|
||||
r'(?:/>|>(.*?)</c>)', re.S)
|
||||
_F_RE = re.compile(r'<f([^>]*?)(?:/>|>(.*?)</f>)', re.S)
|
||||
_ROW_RE = re.compile(r'<row r="(\d+)"[^>]*?(?:/>|>.*?</row>)', re.S)
|
||||
# 同源引用:`[n]资金组取数!`(sheet 名不含空格,无需引号)
|
||||
_EXT_REF = re.compile(r'\[(\d+)\]' + re.escape(config.LINK_SHEET) + r'!')
|
||||
|
||||
|
||||
def _pick_ledger():
|
||||
import glob
|
||||
files = [p for p in glob.glob(os.path.join(config.WORK_DIR, config.LEDGER_GLOB))
|
||||
if '备份' not in os.path.basename(p) and not p.endswith('.tmp')]
|
||||
if not files:
|
||||
return None
|
||||
files.sort(key=os.path.getmtime)
|
||||
return files[-1]
|
||||
|
||||
|
||||
def _target_path(d):
|
||||
return os.path.join(config.SHARE_ROOT, f'{d.year}年{d.month}月', f'{d.month}.{d.day}',
|
||||
f'{config.LINK_BOOK}{d.month}.{d.day}.xlsx')
|
||||
|
||||
|
||||
def _file_uri(path):
|
||||
"""与既有 rels 一致:file:///\\\\caiwu01\\共享文件夹\\...(XML 属性里反斜杠不转义)。"""
|
||||
return 'file:///' + path
|
||||
|
||||
|
||||
def _norm_uri(uri):
|
||||
"""外部链接目标归一化:去掉 file:/// 前缀、双反斜杠归一、小写(否则每次都新增重复链接)。"""
|
||||
u = (uri or '').strip()
|
||||
if u.lower().startswith('file:///'):
|
||||
u = u[len('file:///'):]
|
||||
return u.replace('\\\\', '\\').lower()
|
||||
|
||||
|
||||
def _sheet_xml_path(zf, sheet_name):
|
||||
import xml.etree.ElementTree as ET
|
||||
main = '{http://schemas.openxmlformats.org/spreadsheetml/2006/main}'
|
||||
rel = '{http://schemas.openxmlformats.org/officeDocument/2006/relationships}'
|
||||
pkg = '{http://schemas.openxmlformats.org/package/2006/relationships}'
|
||||
root = ET.fromstring(zf.read('xl/workbook.xml'))
|
||||
rid = None
|
||||
for s in root.iter(f'{main}sheet'):
|
||||
if s.get('name') == sheet_name:
|
||||
rid = s.get(f'{rel}id')
|
||||
break
|
||||
if not rid:
|
||||
return None
|
||||
rels = ET.fromstring(zf.read('xl/_rels/workbook.xml.rels'))
|
||||
for r in rels.iter(f'{pkg}Relationship'):
|
||||
if r.get('Id') == rid:
|
||||
t = (r.get('Target') or '').lstrip('/')
|
||||
return t if t.startswith('xl/') else 'xl/' + t
|
||||
return None
|
||||
|
||||
|
||||
def _parse_links(zf):
|
||||
"""既有外部链接:{归一化路径: 序号} + 最大序号。"""
|
||||
mapping, max_n = {}, 0
|
||||
for name in zf.namelist():
|
||||
m = re.match(r'xl/externalLinks/_rels/externalLink(\d+)\.xml\.rels$', name)
|
||||
if not m:
|
||||
continue
|
||||
n = int(m.group(1))
|
||||
max_n = max(max_n, n)
|
||||
txt = zf.read(name).decode('utf-8', 'replace')
|
||||
tm = re.search(r'Target="([^"]+)"', txt)
|
||||
if tm:
|
||||
mapping.setdefault(_norm_uri(tm.group(1)), n)
|
||||
return mapping, max_n
|
||||
|
||||
|
||||
def _set_row_cells(row_xml, row_no, cells):
|
||||
"""用新单元格替换指定列(保留该列原有样式 s),行内其余单元格原样保留。"""
|
||||
keep, styles = [], {}
|
||||
for m in _CELL_RE.finditer(row_xml):
|
||||
col = m.group(1)
|
||||
sm = re.search(r'\bs="(\d+)"', m.group(3))
|
||||
if sm:
|
||||
styles.setdefault(col, sm.group(1))
|
||||
if col in cells:
|
||||
continue
|
||||
keep.append((_col_num(col), m.group(0)))
|
||||
for col, formula in cells.items():
|
||||
s = styles.get(col)
|
||||
s_attr = f' s="{s}"' if s else ''
|
||||
keep.append((_col_num(col), f'<c r="{col}{row_no}"{s_attr}><f>{formula}</f></c>'))
|
||||
keep.sort(key=lambda x: x[0])
|
||||
attrs = re.match(r'<row([^>]*)>', row_xml)
|
||||
head = f'<row{attrs.group(1)}>' if attrs else f'<row r="{row_no}">'
|
||||
return f'{head}{"".join(c for _, c in keep)}</row>'
|
||||
|
||||
|
||||
def _col_num(letters):
|
||||
n = 0
|
||||
for ch in letters:
|
||||
n = n * 26 + (ord(ch) - 64)
|
||||
return n
|
||||
|
||||
|
||||
def _same_src_formulas(row_inner):
|
||||
"""该行里所有引用共享总表的公式 {列: 公式文本}(共享公式引用无文本的跳过)。"""
|
||||
out = {}
|
||||
for c in _CELL_RE.finditer(row_inner):
|
||||
body = c.group(4) or ''
|
||||
fm = _F_RE.search(body)
|
||||
if not fm:
|
||||
continue
|
||||
text = fm.group(2) or ''
|
||||
if text and _EXT_REF.search(text):
|
||||
out[c.group(1)] = text
|
||||
return out
|
||||
|
||||
|
||||
def _date_rows(ledger):
|
||||
"""读「抖音到账核对」A 列日期 → {date: 行号}。"""
|
||||
wb = load_workbook(ledger, read_only=True, data_only=False)
|
||||
try:
|
||||
if config.STAT_SHEET not in wb.sheetnames:
|
||||
raise RuntimeError(f'台账缺少 sheet「{config.STAT_SHEET}」')
|
||||
ws = wb[config.STAT_SHEET]
|
||||
out = {}
|
||||
for i, row in enumerate(ws.iter_rows(min_col=1, max_col=1, values_only=True), start=1):
|
||||
v = row[0]
|
||||
if isinstance(v, datetime):
|
||||
out[v.date()] = i
|
||||
elif isinstance(v, date):
|
||||
out[v] = i
|
||||
return out
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
|
||||
def run(dry_run=False):
|
||||
"""按 A 列日期给「抖音到账核对」整行同源取数公式换链接编号。"""
|
||||
ledger = _pick_ledger()
|
||||
if not ledger:
|
||||
return {'ok': False, 'message': f'未找到台账:{config.LEDGER_GLOB}'}
|
||||
config.log(f'台账:{os.path.basename(ledger)}({config.STAT_SHEET})')
|
||||
|
||||
try:
|
||||
rows_by_date = _date_rows(ledger)
|
||||
except RuntimeError as e:
|
||||
return {'ok': False, 'message': str(e)}
|
||||
if not rows_by_date:
|
||||
return {'ok': False, 'message': f'「{config.STAT_SHEET}」A 列没有日期行'}
|
||||
days = sorted(rows_by_date)
|
||||
config.log(f'核对表 {len(days)} 个日期行:{days[0]} ~ {days[-1]}')
|
||||
|
||||
zf = open_zip(ledger)
|
||||
try:
|
||||
link_map, max_link = _parse_links(zf)
|
||||
config.log(f'既有外部链接 {len(link_map)} 条,最大序号 {max_link}')
|
||||
sheet_path = _sheet_xml_path(zf, config.STAT_SHEET)
|
||||
if not sheet_path:
|
||||
return {'ok': False, 'message': f'找不到「{config.STAT_SHEET}」的 xml'}
|
||||
sheet_xml = zf.read(sheet_path).decode('utf-8')
|
||||
wb_xml = zf.read('xl/workbook.xml').decode('utf-8')
|
||||
wb_rels = zf.read('xl/_rels/workbook.xml.rels').decode('utf-8')
|
||||
ct_xml = zf.read('[Content_Types].xml').decode('utf-8')
|
||||
finally:
|
||||
zf.close()
|
||||
|
||||
row_spans = {}
|
||||
for m in _ROW_RE.finditer(sheet_xml):
|
||||
row_spans[int(m.group(1))] = (m.start(), m.end(), m.group(0))
|
||||
|
||||
plan, need_new, skipped, no_formula = [], {}, 0, 0
|
||||
for d in days:
|
||||
row_no = rows_by_date[d]
|
||||
span = row_spans.get(row_no)
|
||||
if not span:
|
||||
config.log(f'{d} 第 {row_no} 行 XML 未找到,跳过', 'WARN')
|
||||
continue
|
||||
srcs = _same_src_formulas(span[2])
|
||||
if not srcs:
|
||||
no_formula += 1
|
||||
continue
|
||||
key = _norm_uri(_target_path(d))
|
||||
have = link_map.get(key)
|
||||
if have is not None and all(set(_EXT_REF.findall(f)) == {str(have)}
|
||||
for f in srcs.values()):
|
||||
skipped += 1
|
||||
continue
|
||||
if have is not None:
|
||||
idx, mode = have, '复用'
|
||||
else:
|
||||
if key not in need_new:
|
||||
need_new[key] = (max_link + len(need_new) + 1, _target_path(d))
|
||||
idx, mode = need_new[key][0], '新增'
|
||||
todo = {}
|
||||
for col, fml in srcs.items():
|
||||
if set(_EXT_REF.findall(fml)) == {str(idx)}:
|
||||
continue
|
||||
todo[col] = _EXT_REF.sub(f'[{idx}]{config.LINK_SHEET}!', fml)
|
||||
if not todo:
|
||||
skipped += 1
|
||||
continue
|
||||
plan.append((d, row_no, idx, _target_path(d), mode, todo))
|
||||
|
||||
config.log(f'需更新 {len(plan)} 行(已正确 {skipped} 行、无同源公式 {no_formula} 行),'
|
||||
f'新增外部链接 {len(need_new)} 条')
|
||||
for d, row_no, idx, path, mode, todo in plan:
|
||||
cols = ','.join(f'{c}({f})' for c, f in sorted(todo.items()))
|
||||
config.log(f' {d} 第{row_no}行 → [{idx}]({mode}){cols} {path}', 'DEBUG')
|
||||
|
||||
if not plan:
|
||||
return {'ok': True, 'rows': [], 'new_links': 0, 'ledger': ledger,
|
||||
'message': f'{config.STAT_SHEET} 同源取数公式已是最新,无需改动'}
|
||||
|
||||
if dry_run:
|
||||
return {'ok': True, 'rows': [p[1] for p in plan], 'new_links': len(need_new),
|
||||
'ledger': ledger,
|
||||
'message': f'[演练] 将更新 {len(plan)} 行,需新增 {len(need_new)} 条外部链接'}
|
||||
|
||||
if not os.path.isdir(config.SHARE_ROOT):
|
||||
config.log(f'共享盘当前不可达({config.SHARE_ROOT}),公式照写,'
|
||||
f'恢复到内网后打开 Excel 点「更新链接」即可取值', 'WARN')
|
||||
|
||||
lock = os.path.join(os.path.dirname(ledger), '~$' + os.path.basename(ledger))
|
||||
if os.path.exists(lock):
|
||||
return {'ok': False, 'message': '台账正在 Excel 中打开(检测到 ~$ 锁文件),请关闭后重跑'}
|
||||
backup = os.path.join(
|
||||
config.WORK_DIR,
|
||||
f'{os.path.splitext(os.path.basename(ledger))[0]}_核对备份'
|
||||
f'{time.strftime("%Y%m%d_%H%M%S")}.xlsx')
|
||||
shutil.copy2(ledger, backup)
|
||||
config.log(f'已备份 → {os.path.basename(backup)}')
|
||||
|
||||
# 按行号倒序替换,避免前面的偏移失效
|
||||
spans = {}
|
||||
for m in _ROW_RE.finditer(sheet_xml):
|
||||
spans[int(m.group(1))] = (m.start(), m.end())
|
||||
for d, row_no, idx, path, mode, todo in sorted(plan, key=lambda p: -p[1]):
|
||||
s, e = spans[row_no]
|
||||
row_xml = sheet_xml[s:e]
|
||||
sheet_xml = sheet_xml[:s] + _set_row_cells(row_xml, row_no, todo) + sheet_xml[e:]
|
||||
|
||||
for key, (idx, path) in need_new.items():
|
||||
rid_num = max(int(x) for x in re.findall(r'Id="rId(\d+)"', wb_rels)) + 1
|
||||
rid = f'rId{rid_num}'
|
||||
wb_rels = wb_rels.replace(
|
||||
'</Relationships>',
|
||||
f'<Relationship Id="{rid}" Type="http://schemas.openxmlformats.org/'
|
||||
f'officeDocument/2006/relationships/externalLink" '
|
||||
f'Target="externalLinks/externalLink{idx}.xml"/></Relationships>')
|
||||
wb_xml = wb_xml.replace('</externalReferences>',
|
||||
f'<externalReference r:id="{rid}"/></externalReferences>')
|
||||
ct_xml = ct_xml.replace(
|
||||
'</Types>',
|
||||
f'<Override PartName="/xl/externalLinks/externalLink{idx}.xml" '
|
||||
f'ContentType="application/vnd.openxmlformats-officedocument.'
|
||||
f'spreadsheetml.externalLink+xml"/></Types>')
|
||||
|
||||
tmp = ledger + '.links.tmp'
|
||||
replace = {
|
||||
sheet_path: sheet_xml.encode('utf-8'),
|
||||
'xl/workbook.xml': wb_xml.encode('utf-8'),
|
||||
'xl/_rels/workbook.xml.rels': wb_rels.encode('utf-8'),
|
||||
'[Content_Types].xml': ct_xml.encode('utf-8'),
|
||||
}
|
||||
new_files = {}
|
||||
for key, (idx, path) in need_new.items():
|
||||
new_files[f'xl/externalLinks/externalLink{idx}.xml'] = \
|
||||
(_EXTLINK_TPL % config.LINK_SHEET).encode('utf-8')
|
||||
new_files[f'xl/externalLinks/_rels/externalLink{idx}.xml.rels'] = \
|
||||
(_EXTLINK_RELS_TPL % _file_uri(path)).encode('utf-8')
|
||||
|
||||
zf = open_zip(ledger)
|
||||
try:
|
||||
with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED, allowZip64=True) as dst:
|
||||
for info in zf.infolist():
|
||||
if info.is_dir():
|
||||
continue
|
||||
zi = zipfile.ZipInfo(info.filename, date_time=info.date_time)
|
||||
zi.compress_type = zipfile.ZIP_DEFLATED
|
||||
zi.external_attr = info.external_attr
|
||||
if info.filename in replace:
|
||||
dst.writestr(zi, replace.pop(info.filename))
|
||||
else:
|
||||
with zf.open(info) as fin, dst.open(zi, 'w', force_zip64=True) as fout:
|
||||
shutil.copyfileobj(fin, fout, 4 << 20)
|
||||
for name, data in list(replace.items()) + list(new_files.items()):
|
||||
dst.writestr(name, data)
|
||||
finally:
|
||||
zf.close()
|
||||
os.replace(tmp, ledger)
|
||||
|
||||
config.log(f'完成:{len(plan)} 行同源公式已更新,新增外部链接 {len(need_new)} 条')
|
||||
return {'ok': True, 'rows': [p[1] for p in plan], 'new_links': len(need_new),
|
||||
'ledger': ledger,
|
||||
'message': f'{config.STAT_SHEET} 同源取数公式已更新 {len(plan)} 行'
|
||||
f'(新增外部链接 {len(need_new)} 条)'}
|
||||
@@ -0,0 +1,92 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xlsx(zip) 读写的兼容层。
|
||||
|
||||
背景:台账被 WPS 保存后,透视缓存的 `pivotCacheRecords*.xml` 会写成
|
||||
「local header 里 size=0xFFFFFFFF + ZIP64 extra 带真实大小、central directory 却缺 ZIP64 extra」。
|
||||
Python 3.11 的 zipfile 从 central 取到 0xFFFFFFFF,把条目当成 4GB,
|
||||
`ZipFile.open()` 直接抛 `BadZipFile: Overlapped entries ... (possible zip bomb)`。
|
||||
|
||||
这里在打开后把这类 ZipInfo 的 size 修成真实值(解析 local header 的 ZIP64 extra,
|
||||
取不到就用下一条目偏移反推),只改内存对象、不动文件;之后 `zf.open(info)` 可正常读。
|
||||
"""
|
||||
import struct
|
||||
import zipfile
|
||||
|
||||
_LFH = struct.Struct('<IHHHHHIIIHH')
|
||||
|
||||
|
||||
def _local_sizes(fp, info):
|
||||
"""从 local file header 的 ZIP64 extra 取 (usize, csize),取不到返回 (None, None)。"""
|
||||
fp.seek(info.header_offset)
|
||||
hdr = fp.read(30)
|
||||
if len(hdr) < 30 or hdr[:4] != b'PK\x03\x04':
|
||||
return None, None
|
||||
nlen, elen = struct.unpack('<HH', hdr[26:30])
|
||||
fp.read(nlen)
|
||||
extra = fp.read(elen)
|
||||
usize = csize = None
|
||||
i = 0
|
||||
while i + 4 <= len(extra):
|
||||
hid, hlen = struct.unpack('<HH', extra[i:i + 4])
|
||||
body = extra[i + 4:i + 4 + hlen]
|
||||
if hid == 0x0001: # ZIP64 extended information
|
||||
if len(body) >= 16:
|
||||
usize, csize = struct.unpack('<QQ', body[:16])
|
||||
elif len(body) >= 8:
|
||||
usize = struct.unpack('<Q', body[:8])[0]
|
||||
i += 4 + hlen
|
||||
return usize, csize
|
||||
|
||||
|
||||
def repair_sizes(zf):
|
||||
"""修 0xFFFFFFFF 的条目大小,返回修复条数。"""
|
||||
fixed = 0
|
||||
fp = getattr(zf, 'fp', None)
|
||||
if fp is None:
|
||||
return 0
|
||||
try:
|
||||
if not fp.seekable():
|
||||
return 0
|
||||
except Exception:
|
||||
return 0
|
||||
try:
|
||||
pos = fp.tell()
|
||||
except Exception:
|
||||
pos = None
|
||||
for info in zf.infolist():
|
||||
if info.compress_size != 0xFFFFFFFF and info.file_size != 0xFFFFFFFF:
|
||||
continue
|
||||
usize, csize = _local_sizes(fp, info)
|
||||
if csize is None:
|
||||
end = getattr(info, '_end_offset', None)
|
||||
if end:
|
||||
nlen = struct.unpack('<H', _peek(fp, info, 26, 2) or b'\x00\x00')[0]
|
||||
elen = struct.unpack('<H', _peek(fp, info, 28, 2) or b'\x00\x00')[0]
|
||||
csize = end - (info.header_offset + 30 + nlen + elen)
|
||||
if csize is None:
|
||||
continue
|
||||
info.compress_size = csize
|
||||
if usize:
|
||||
info.file_size = usize
|
||||
fixed += 1
|
||||
if pos is not None:
|
||||
try:
|
||||
fp.seek(pos)
|
||||
except Exception:
|
||||
pass
|
||||
return fixed
|
||||
|
||||
|
||||
def _peek(fp, info, offset, size):
|
||||
try:
|
||||
fp.seek(info.header_offset + offset)
|
||||
return fp.read(size)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def open_zip(path):
|
||||
"""open + 修复 WPS 写坏的 zip64 条目大小,返回可正常读取的 ZipFile。"""
|
||||
zf = zipfile.ZipFile(path)
|
||||
repair_sizes(zf)
|
||||
return zf
|
||||
@@ -2,8 +2,8 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0042",
|
||||
"name": "抖音平台核对",
|
||||
"version": "0.6.2",
|
||||
"description": "抖音来客(life.douyin.com)数据自动导出:打开官方页面人工登录(含验证码/滑块),按日期区间导出核销明细与提现记录,轮询生成完成后下载到本机目录;导出记录超过保留阈值自动删最早的(阈值可在界面改);并入台账与核对统计待补齐。",
|
||||
"version": "0.7.2",
|
||||
"description": "抖音来客(life.douyin.com)数据自动导出:打开官方页面人工登录(含验证码/滑块),按日期区间导出核销明细与提现记录,轮询生成完成后下载到本机目录;导出记录超过保留阈值自动删最早的(阈值可在界面改);核销明细按「核销时间」增量并入台账「抖音到账统计YYYY.M月.xlsx」的「金色印象--抖音」sheet,A 与 BT~CA 公式列自动下拉;并按 A 列日期把「抖音到账核对」整行同源取数公式([n]资金组取数!$B$xx,实测 O/P/R/S)的链接换成当天那份共享总表。",
|
||||
"category": "财务",
|
||||
"icon": "",
|
||||
"platform": "",
|
||||
@@ -71,6 +71,24 @@
|
||||
"default": "",
|
||||
"description": "留空=D:\\资料\\财务\\抖音平台核对"
|
||||
},
|
||||
"run_merge": {
|
||||
"type": "boolean",
|
||||
"title": "并入台账(金色印象--抖音)",
|
||||
"default": true,
|
||||
"description": "核销明细按「核销时间」增量并入台账金色印象--抖音 sheet,A 与 BT~CA 公式列自动下拉(CC 列不写)"
|
||||
},
|
||||
"run_stat_links": {
|
||||
"type": "boolean",
|
||||
"title": "补核对表同源取数公式",
|
||||
"default": true,
|
||||
"description": "扫「抖音到账核对」整行所有 [n]资金组取数!$B$xx 公式(实测 O/P/R/S),按 A 列日期把 [n] 换成当天那份共享总表(\\\\caiwu01\\...\\马敏团购总表M.D.xlsx);已是目标链接的单元格保留不动"
|
||||
},
|
||||
"dry_run": {
|
||||
"type": "boolean",
|
||||
"title": "只统计不写入(演练)",
|
||||
"default": false,
|
||||
"description": "只输出将追加的行数与起止行号,不修改台账文件"
|
||||
},
|
||||
"force_login": {
|
||||
"type": "boolean",
|
||||
"title": "强制重新登录",
|
||||
|
||||
@@ -115,6 +115,37 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 03 台账合并 -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">03</span>
|
||||
<span class="sec-name">台账合并与核对表</span>
|
||||
<span class="sec-line" />
|
||||
</div>
|
||||
<div class="grid grid-switch">
|
||||
<el-form-item label="并入台账(金色印象--抖音)">
|
||||
<el-switch v-model="form.run_merge" :disabled="running" />
|
||||
</el-form-item>
|
||||
<el-form-item label="补核对表同源取数公式">
|
||||
<el-switch v-model="form.run_stat_links" :disabled="running" />
|
||||
</el-form-item>
|
||||
<el-form-item label="只统计不写入(演练)">
|
||||
<el-switch v-model="form.dry_run"
|
||||
:disabled="running || (!form.run_merge && !form.run_stat_links)" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="tip">
|
||||
核销明细按<b>「核销时间」</b>增量并入保存目录里月份最新的
|
||||
<b>抖音到账统计YYYY.M月.xlsx</b> → sheet「金色印象--抖音」:比台账最大时间旧的行剔除,
|
||||
其余按表头同名追加;<b>A 列(=M*1)与 BT~CA 核对公式自动下拉,CC 列不写</b>。<br>
|
||||
<b>核对表取数</b>:扫「抖音到账核对」整行所有 <b>[n]资金组取数!$B$xx</b> 公式
|
||||
(实测 O/P/R/S = B24/B25/B22/B23),按 A 列日期把 [n] 换成当天那份共享总表
|
||||
\\caiwu01\共享文件夹\1111\TG\YYYY年M月\M.D\马敏团购总表M.D.xlsx,已是目标链接的单元格保留不动。<br>
|
||||
写入前自动备份(_备份 / _核对备份 + 时间戳),写入期间请关闭该台账;
|
||||
只勾这两项、不勾导出时可单独补账(不开浏览器);共享盘不可达时公式照写,回内网点「更新链接」取值。
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 操作 -->
|
||||
<div class="actions">
|
||||
<el-button type="primary" class="btn-run" :loading="running" @click="start">
|
||||
@@ -167,6 +198,9 @@ const DEFAULTS = () => {
|
||||
export_withdraw: true,
|
||||
record_limit_verify: 60,
|
||||
record_limit_withdraw: 25,
|
||||
run_merge: true,
|
||||
run_stat_links: true,
|
||||
dry_run: false,
|
||||
save_dir: '',
|
||||
force_login: false,
|
||||
debug_mode: false,
|
||||
@@ -181,8 +215,9 @@ const {
|
||||
} = usePluginUI({
|
||||
defaults: DEFAULTS,
|
||||
validate() {
|
||||
if (!form.export_verify && !form.export_withdraw) {
|
||||
ElMessage.warning('请至少勾选一项要导出的内容(核销明细 / 提现记录)')
|
||||
if (!form.export_verify && !form.export_withdraw && !form.run_merge
|
||||
&& !form.run_stat_links) {
|
||||
ElMessage.warning('请至少选择一项执行内容(核销明细 / 提现记录 / 并入台账 / 补核对表取数)')
|
||||
return false
|
||||
}
|
||||
const pairs = []
|
||||
@@ -213,6 +248,9 @@ const {
|
||||
export_withdraw: !!f.export_withdraw,
|
||||
record_limit_verify: n(f.record_limit_verify, 60),
|
||||
record_limit_withdraw: n(f.record_limit_withdraw, 25),
|
||||
run_merge: !!f.run_merge,
|
||||
run_stat_links: !!f.run_stat_links,
|
||||
dry_run: !!((f.run_merge || f.run_stat_links) && f.dry_run),
|
||||
save_dir: t(f.save_dir),
|
||||
force_login: !!f.force_login,
|
||||
debug_mode: !!f.debug_mode,
|
||||
|
||||
+19
-19
File diff suppressed because one or more lines are too long
@@ -4,7 +4,7 @@
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>抖音平台核对</title>
|
||||
<script type="module" crossorigin src="/pui/xq0042/assets/index-BUp-ZeAA.js"></script>
|
||||
<script type="module" crossorigin src="/pui/xq0042/assets/index-D8-abd5n.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0042/assets/index-D2-8mbvQ.css">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
1) 登录态预检(API 校验 %LOCALAPPDATA%\\37duAutomation\\.sessions\\crm_cookie_header.txt);
|
||||
有效则全程免扫码,失效则打开可见浏览器等钉钉扫码一次(同次运行最多弹一次);
|
||||
2) 打开「报表统计/储值卡余额」整页截图 → 储值卡余额-YYYYMMDD.png;
|
||||
3) requests 复用同一登录态,按日期规则导出 18 张报表 xlsx
|
||||
3) requests 复用同一登录态,按日期规则导出 22 张报表 xlsx
|
||||
(礼品卡订单因接口限制跨度 ≤31 天,近 3 个自然月按月拆分)。
|
||||
"""
|
||||
import os
|
||||
@@ -19,8 +19,8 @@ from .data import crm_export
|
||||
class CrmDataExportPlugin(ScenePlugin):
|
||||
id = "xq0048"
|
||||
name = "CRM数据导出"
|
||||
version = "1.1.6"
|
||||
description = ("37du CRM(crm.37du.co)数据导出:储值卡余额整页截图 + 18 张报表自动导出(导出内容可勾选),"
|
||||
version = "1.1.10"
|
||||
description = ("37du CRM(crm.37du.co)数据导出:储值卡余额整页截图 + 22 张报表自动导出(导出内容可勾选),"
|
||||
"登录态钉钉扫码一次后缓存复用(约 30 分钟内免扫码),"
|
||||
"按各报表日期规则自动计算区间,礼品卡订单按月拆分")
|
||||
platform = "" # CRM 为钉钉扫码登录,插件内自带登录流程,不使用底座共享登录态
|
||||
|
||||
@@ -114,15 +114,21 @@ UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
# ==================== 报表清单(名称, 导出接口, 日期规则, 附加参数, 日期参数字段) ====================
|
||||
# 规则:prev=前一天单日;prev_today=昨日~今日;month_to_today=本月1日~今日;
|
||||
# prev_prev=昨日~昨日;month1_to_prev=本月1日~前一天;last_month=上月完整;
|
||||
# last3_months=近 3 个自然月按月拆分(止日不超过前一天)
|
||||
# last3_months=近 3 个自然月按月拆分(止日不超过前一天);
|
||||
# today=当日快照(无日期筛选参数,仅用于文件命名)
|
||||
# 日期参数字段:报表统计类为 reportDate;淘宝订单为 createTimePeriod(页面「购买时间」);
|
||||
# 微盟核销为 validateDatePeriod;开卡订单/会员退卡为 period;
|
||||
# 礼品卡订单为 receiveTimePeriod(接口限制跨度 ≤31 天,故按月拆分)
|
||||
# 礼品卡订单为 receiveTimePeriod(接口限制跨度 ≤31 天,故按月拆分);
|
||||
# 储值余额为 None(页面只有手机号筛选,查询即全量导出)
|
||||
REPORTS = [
|
||||
('储值余额', 'report/debitCard/memberBalanceExport', 'today', None, None),
|
||||
('储值记录', 'report/debitCard/depositExport', 'month_to_today', {'depositType': 2}, 'reportDate'), # 储值类型=小程序储值
|
||||
('储值台账', 'report/debitCard/balanceAccountBookExport', 'month_to_today', {'depositType': 2}, 'reportDate'), # 储值类型=小程序储值
|
||||
('团购支付数据', 'report/groupPay/export', 'prev', None, 'reportDate'),
|
||||
('现金支付', 'report/cashPay/export', 'prev', None, 'reportDate'),
|
||||
('第三方支付(门店)', 'report/thirdPayShop/export', 'prev', None, 'reportDate'),
|
||||
('支付数据', 'report/unionPay/export', 'prev', None, 'reportDate'),
|
||||
('订单附加属性统计', 'report/orderSubjectAddition/export', 'prev', None, 'payFinishTimePeriod'),
|
||||
('团购数据', 'report/groupData/export', 'prev_today', None, 'reportDate'),
|
||||
('淘宝订单数据', 'report/taobaoTicket/export', 'prev_today', None, 'createTimePeriod'),
|
||||
('技师综合业绩', 'report/comprehensivePerformance/export', 'month_to_today', None, 'reportDate'),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0048 CRM 数据导出 - 储值卡余额截图 + 18 张报表导出。
|
||||
"""xq0048 CRM 数据导出 - 储值卡余额截图 + 22 张报表导出。
|
||||
|
||||
从影刀版 workflows/XQ0001-0100/XQ0048 CRM数据导出/crm_export_all.py 迁移,
|
||||
登录逻辑改为插件内 data/crm_login.py(自包含,不跨目录 import)。
|
||||
@@ -216,9 +216,11 @@ def _screenshot(save_dir, date_str):
|
||||
|
||||
# ==================== 报表导出 ====================
|
||||
def _date_window(rule):
|
||||
"""按规则返回 (起, 止) 日期。"""
|
||||
"""按规则返回 (起, 止) 日期。today 仅用于无日期筛选报表的文件命名。"""
|
||||
today = date.today()
|
||||
prev = today - timedelta(days=1)
|
||||
if rule == 'today':
|
||||
return today, today
|
||||
if rule == 'prev' or rule == 'prev_prev':
|
||||
return prev, prev
|
||||
if rule == 'prev_today':
|
||||
@@ -288,11 +290,15 @@ def _export_window(title, path, beg, end, extra, save_dir, date_key, idx, total)
|
||||
filename = _filename(title, beg, end)
|
||||
save_path = os.path.join(save_dir, filename)
|
||||
url = config.BASE + path
|
||||
date_val = f'{beg:%Y-%m-%d} {end:%Y-%m-%d}'
|
||||
if date_key == 'reportDate' and beg == end:
|
||||
date_val = f'{beg:%Y-%m-%d}'
|
||||
params = {'pageNum': 1, 'pageSize': config.PAGE_SIZE, date_key: date_val}
|
||||
date_desc = f'{date_key}={date_val}'
|
||||
params = {'pageNum': 1, 'pageSize': config.PAGE_SIZE}
|
||||
if date_key:
|
||||
date_val = f'{beg:%Y-%m-%d} {end:%Y-%m-%d}'
|
||||
if date_key == 'reportDate' and beg == end:
|
||||
date_val = f'{beg:%Y-%m-%d}'
|
||||
params[date_key] = date_val
|
||||
date_desc = f'{date_key}={date_val}'
|
||||
else:
|
||||
date_desc = '无日期筛选(全量)'
|
||||
if extra:
|
||||
params.update(extra)
|
||||
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0048",
|
||||
"name": "CRM数据导出",
|
||||
"version": "1.1.6",
|
||||
"description": "37du CRM(crm.37du.co)数据导出:储值卡余额整页截图 + 18 张报表自动导出(导出内容可勾选)。登录态钉钉扫码一次后缓存复用(约 30 分钟内免扫码),按各报表日期规则自动计算区间,礼品卡订单因接口限制跨度 ≤31 天按月拆分。",
|
||||
"version": "1.1.10",
|
||||
"description": "37du CRM(crm.37du.co)数据导出:储值卡余额整页截图 + 22 张报表自动导出(导出内容可勾选)。登录态钉钉扫码一次后缓存复用(约 30 分钟内免扫码),按各报表日期规则自动计算区间,礼品卡订单因接口限制跨度 ≤31 天按月拆分。",
|
||||
"category": "财务",
|
||||
"icon": "",
|
||||
"platform": "",
|
||||
|
||||
@@ -1,140 +1,133 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<!-- 未登录 / 结果横幅 -->
|
||||
<transition name="fade-slide">
|
||||
<el-alert v-if="needLogin" type="warning" :closable="false" show-icon title="未登录:请先在壳子(工作台)登录统一账户,再刷新本界面" />
|
||||
<el-alert v-else-if="banner" :type="banner.type" :closable="true" show-icon @close="banner = null">
|
||||
<template #title>{{ banner.text }}</template>
|
||||
</el-alert>
|
||||
</transition>
|
||||
<!-- 方案工具条:方案供「定时任务」按 config_id 引用,到点自动取方案最新参数 -->
|
||||
<div class="toolbar">
|
||||
<span class="spacer" />
|
||||
<span class="saved" :class="{ 'is-idle': !lastSavedAt }">
|
||||
<i />{{ lastSavedAt ? '已保存 ' + lastSavedAt : '尚未保存' }}
|
||||
</span>
|
||||
<el-select v-model="schemeSel" class="scheme-sel" size="small" :disabled="running"
|
||||
placeholder="当前配置(自动保存)" @change="onSchemeChange">
|
||||
<el-option v-for="o in schemeOptions" :key="o.value" :label="o.label" :value="o.value" />
|
||||
</el-select>
|
||||
<el-button size="small" :disabled="running" @click="saveSchemeAs">存为方案</el-button>
|
||||
<el-button size="small" text type="danger" :disabled="running || !schemeSel"
|
||||
@click="removeScheme">删除</el-button>
|
||||
</div>
|
||||
|
||||
<!-- 执行配置(头部含多配置方案:方案供「定时任务」引用,到点自动取方案最新参数) -->
|
||||
<el-card shadow="never" class="panel">
|
||||
<template #header>
|
||||
<div class="panel-head">
|
||||
<div class="panel-title">
|
||||
<span class="title-ico">
|
||||
<svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" stroke-width="2"
|
||||
stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
|
||||
<polyline points="7 10 12 15 17 10" />
|
||||
<line x1="12" y1="15" x2="12" y2="3" />
|
||||
</svg>
|
||||
</span>
|
||||
<div class="title-txts">
|
||||
<div class="title-txt">执行配置</div>
|
||||
<div class="title-sub">勾选导出内容,参数自动保存到本机,方案供定时任务到点引用</div>
|
||||
<!-- 内联提示 -->
|
||||
<div v-if="needLogin" class="notice is-warn">
|
||||
<span class="n-ico">!</span>
|
||||
<span>未登录:请先在壳子(工作台)登录统一账户,再刷新本界面</span>
|
||||
</div>
|
||||
<div v-else-if="notice" class="notice" :class="'is-' + notice.type">
|
||||
<span class="n-ico">{{ notice.type === 'ok' ? '✓' : (notice.type === 'error' ? '✕' : '·') }}</span>
|
||||
<span>{{ notice.text }}</span>
|
||||
</div>
|
||||
|
||||
<!-- 01 导出内容 -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">01</span>
|
||||
<span class="sec-name">导出内容</span>
|
||||
<span class="sec-line" />
|
||||
</div>
|
||||
<div class="sec-body">
|
||||
<div class="grp-tools">
|
||||
<span class="gt-count">已选 <b>{{ form.reports.length }}</b> / {{ ALL_KEYS.length }} 项</span>
|
||||
<span class="spacer" />
|
||||
<el-button size="small" :disabled="running" @click="selectAll">全选</el-button>
|
||||
<el-button size="small" text :disabled="running || !form.reports.length"
|
||||
@click="clearAll">清空</el-button>
|
||||
</div>
|
||||
<div class="groups">
|
||||
<div v-for="g in GROUPED" :key="g.name" class="grp">
|
||||
<div class="grp-head">
|
||||
<el-checkbox :model-value="g.all" :indeterminate="g.some" :disabled="running"
|
||||
@change="toggleGroup(g)">{{ g.name }}</el-checkbox>
|
||||
<span class="grp-count" :class="{ full: g.all }">{{ g.picked }}/{{ g.items.length }}</span>
|
||||
</div>
|
||||
<div class="grp-body">
|
||||
<el-checkbox v-for="it in g.items" :key="it.key" :model-value="form.reports.includes(it.key)"
|
||||
:disabled="running" class="rep-item" @change="toggleItem(it.key)">
|
||||
<span class="rep-name">{{ it.name }}</span>
|
||||
<el-tooltip :content="it.tag" placement="top" :show-after="150">
|
||||
<el-icon class="rep-info"><InfoFilled /></el-icon>
|
||||
</el-tooltip>
|
||||
</el-checkbox>
|
||||
</div>
|
||||
</div>
|
||||
<div class="head-tools">
|
||||
<span v-if="lastSavedAt" class="saved">
|
||||
<i class="dot" />已保存 {{ lastSavedAt }}
|
||||
</span>
|
||||
<el-select v-model="schemeSel" class="scheme-sel" size="small" :disabled="running" @change="onSchemeChange">
|
||||
<el-option v-for="o in schemeOptions" :key="o.value" :label="o.label" :value="o.value" />
|
||||
</el-select>
|
||||
<el-button size="small" :disabled="running" @click="saveSchemeAs">存为方案</el-button>
|
||||
<el-button size="small" text type="danger" :disabled="running || !schemeSel"
|
||||
@click="removeScheme">删除</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<div class="tip">
|
||||
勾选项由后端按各自规则自动计算日期区间并导出;<b>截图</b>=储值卡余额整页,<b>储值余额</b>=当天快照(无日期筛选)。
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<el-form label-position="top">
|
||||
<!-- 执行说明 -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">01</span>
|
||||
<span class="sec-name">执行说明</span>
|
||||
<span class="sec-line" />
|
||||
</div>
|
||||
<div class="flow-desc">
|
||||
<div class="flow-item"><span class="flow-no">1</span>登录态预检:约 30 分钟内免扫码;失效时自动打开浏览器,钉钉扫码一次后全程复用</div>
|
||||
<div class="flow-item"><span class="flow-no">2</span>「报表统计/储值卡余额」整页截图 → 储值卡余额-YYYYMMDD.png</div>
|
||||
<div class="flow-item"><span class="flow-no">3</span>按勾选的报表自动计算日期区间,逐张导出 xlsx(礼品卡订单因接口限制跨度 ≤31 天,按月拆分)</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 导出内容(按业务分组) -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">02</span>
|
||||
<span class="sec-name">导出内容</span>
|
||||
<span class="sec-line" />
|
||||
<span class="sec-count">已选 <b>{{ form.reports.length }}</b> / {{ ALL_KEYS.length }} 项</span>
|
||||
<el-button size="small" text type="primary" :disabled="running" @click="selectAll">全选</el-button>
|
||||
<el-button size="small" text :disabled="running || !form.reports.length" @click="clearAll">清空</el-button>
|
||||
</div>
|
||||
<div class="groups">
|
||||
<div v-for="g in GROUPED" :key="g.name" class="grp">
|
||||
<div class="grp-head">
|
||||
<el-checkbox :model-value="g.all" :indeterminate="g.some" :disabled="running"
|
||||
@change="toggleGroup(g)">{{ g.name }}</el-checkbox>
|
||||
<span class="grp-count" :class="{ full: g.all }">{{ g.picked }}/{{ g.items.length }}</span>
|
||||
</div>
|
||||
<div class="grp-body">
|
||||
<el-checkbox v-for="it in g.items" :key="it.key" :model-value="form.reports.includes(it.key)"
|
||||
:disabled="running" class="rep-item" @change="toggleItem(it.key)">
|
||||
<span class="rep-name">{{ it.name }}</span>
|
||||
<el-tooltip :content="it.tag" placement="top" :show-after="150">
|
||||
<el-icon class="rep-info"><InfoFilled /></el-icon>
|
||||
</el-tooltip>
|
||||
</el-checkbox>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tip">日期区间由各报表规则自动计算:截图=当天;前一天;昨日~今日;昨日;本月1日~今日;本月1日~昨日;上月完整;近3个自然月(礼品卡订单按月拆分)</div>
|
||||
</section>
|
||||
|
||||
<!-- 执行设置 -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">03</span>
|
||||
<span class="sec-name">执行设置</span>
|
||||
<span class="sec-line" />
|
||||
</div>
|
||||
<!-- 02 执行设置 -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">02</span>
|
||||
<span class="sec-name">执行设置</span>
|
||||
<span class="sec-line" />
|
||||
</div>
|
||||
<div class="sec-body">
|
||||
<el-form label-position="top">
|
||||
<div class="grid">
|
||||
<el-form-item label="保存目录">
|
||||
<el-input v-model="form.save_dir" :disabled="running" clearable
|
||||
placeholder="留空 = D:\资料\财务\CRM数据导出" />
|
||||
<div class="dir-ctrl">
|
||||
<el-input v-model="form.save_dir" class="dir-input" :disabled="running" clearable
|
||||
placeholder="D:\资料\财务\CRM数据导出" />
|
||||
<el-button class="dir-btn" :disabled="running || picking" :loading="picking"
|
||||
@click="pickDir">选择</el-button>
|
||||
</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="调试日志">
|
||||
<el-switch v-model="form.debug_mode" :disabled="running" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="tip">截图与全部 xlsx 统一输出到保存目录;「调试日志」开启后输出完整调试信息(默认关闭)</div>
|
||||
</section>
|
||||
|
||||
<!-- 操作 -->
|
||||
<div class="actions">
|
||||
<el-button type="primary" size="large" class="btn-run" :loading="running" @click="run">
|
||||
{{ running ? '执行中 ' + progress + '%' : '一键执行' }}
|
||||
</el-button>
|
||||
<el-button v-if="running" type="danger" size="large" plain :loading="stopping"
|
||||
@click="forceStop">强制停止</el-button>
|
||||
<span class="spacer" />
|
||||
<el-button size="large" :disabled="running" @click="saveNow(true)">保存配置</el-button>
|
||||
<el-button size="large" text :disabled="running" @click="resetDefaults">恢复默认</el-button>
|
||||
</div>
|
||||
</el-form>
|
||||
</el-card>
|
||||
|
||||
<!-- 运行状态 -->
|
||||
<transition name="fade-slide">
|
||||
<div v-if="running" class="status">
|
||||
<el-progress :percentage="progress" :stroke-width="10" :show-text="false" class="status-bar" />
|
||||
<div class="status-row">
|
||||
<span class="pulse" />
|
||||
<span class="status-txt">正在执行,日志与进度实时显示在工作台下方【运行日志】区</span>
|
||||
<span class="status-pct">{{ progress }}%</span>
|
||||
</div>
|
||||
<div class="tip">
|
||||
截图与全部 xlsx 统一输出到该目录(留空 = 默认目录);<b>调试日志</b>开启后输出完整调试信息,默认关闭。
|
||||
</div>
|
||||
</el-form>
|
||||
</div>
|
||||
</transition>
|
||||
</section>
|
||||
|
||||
<!-- 流程说明:大段说明收进折叠区 -->
|
||||
<details class="help">
|
||||
<summary><span>流程说明</span><span class="h-arrow">▾</span></summary>
|
||||
<div class="help-body">
|
||||
<div class="hb-line"><b>① 登录态预检</b>:约 30 分钟内免扫码;失效时自动打开浏览器,钉钉扫码一次后全程复用。</div>
|
||||
<div class="hb-line"><b>② 截图</b>:进入「报表统计 / 储值卡余额」整页截图 → <b>储值卡余额-YYYYMMDD.png</b>。</div>
|
||||
<div class="hb-line"><b>③ 报表导出</b>:按勾选项逐张导出 xlsx;礼品卡订单因接口限制跨度 ≤31 天,按月拆分。</div>
|
||||
<div class="hb-line"><b>日期规则</b>:当天快照(储值余额)/ 前一天 / 昨日~今日 / 昨日 / 本月1日~今日 / 本月1日~昨日 / 上月完整 / 近3个自然月。</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<!-- 操作区 -->
|
||||
<div class="actions">
|
||||
<el-button type="primary" class="btn-run" :loading="running" @click="run">
|
||||
{{ running ? '执行中 ' + progress + '%' : '一键执行' }}
|
||||
</el-button>
|
||||
<el-button v-if="running" type="danger" plain :loading="stopping"
|
||||
@click="forceStop">强制停止</el-button>
|
||||
<span class="spacer" />
|
||||
<el-button :disabled="running" @click="restoreLastFields">恢复上次参数</el-button>
|
||||
<el-button :disabled="running" @click="saveNow(true)">保存配置</el-button>
|
||||
<el-button text :disabled="running" @click="resetDefaults">恢复默认</el-button>
|
||||
</div>
|
||||
|
||||
<!-- 运行态:只留一行文字,进度与日志由壳子展示 -->
|
||||
<div v-if="running" class="runline">
|
||||
<span class="pulse" />
|
||||
<span>正在执行,日志与进度实时显示在工作台下方「运行日志」区</span>
|
||||
<span class="pct">{{ progress }}%</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed } from 'vue'
|
||||
import { computed, ref } from 'vue'
|
||||
import { usePluginUI } from './usePluginUI'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { InfoFilled } from '@element-plus/icons-vue'
|
||||
@@ -146,10 +139,14 @@ const ITEMS = [
|
||||
{ key: 'report/cashPay/export#prev', name: '现金支付', tag: '前一天', group: '支付数据' },
|
||||
{ key: 'report/thirdPayShop/export#prev', name: '第三方支付(门店)', tag: '前一天', group: '支付数据' },
|
||||
{ key: 'report/unionPay/export#prev', name: '支付数据', tag: '前一天', group: '支付数据' },
|
||||
{ key: 'report/orderSubjectAddition/export#prev', name: '订单附加属性统计', tag: '前一天', group: '支付数据' },
|
||||
{ key: 'report/groupData/export#prev_today', name: '团购数据', tag: '昨日~今日', group: '支付数据' },
|
||||
{ key: 'report/taobaoTicket/export#prev_today', name: '淘宝订单数据', tag: '昨日~今日', group: '支付数据' },
|
||||
{ key: 'report/comprehensivePerformance/export#month_to_today', name: '技师综合业绩', tag: '本月1日~今日', group: '业绩与核销' },
|
||||
{ key: 'report/weimeng/exportValidate#prev_prev', name: '微盟核销统计', tag: '昨日', group: '业绩与核销' },
|
||||
{ key: 'report/debitCard/memberBalanceExport#today', name: '储值余额', tag: '当天快照·无日期筛选', group: '储值卡与霸王餐' },
|
||||
{ key: 'report/debitCard/depositExport#month_to_today', name: '储值记录', tag: '本月1日~今日·小程序储值', group: '储值卡与霸王餐' },
|
||||
{ key: 'report/debitCard/balanceAccountBookExport#month_to_today', name: '储值台账', tag: '本月1日~今日·小程序储值', group: '储值卡与霸王餐' },
|
||||
{ key: 'report/debitCardConsume/export#month1_to_prev', name: '储值卡消费', tag: '本月1日~昨日', group: '储值卡与霸王餐' },
|
||||
{ key: 'report/depositData/export#month1_to_prev', name: '储值卡线上充值', tag: '本月1日~昨日·渠道=管理端', group: '储值卡与霸王餐' },
|
||||
{ key: 'report/overlordOrderDeposit/export#month1_to_prev', name: '霸王餐充值明细', tag: '本月1日~昨日', group: '储值卡与霸王餐' },
|
||||
@@ -164,15 +161,16 @@ const ITEMS = [
|
||||
const ALL_KEYS = ITEMS.map((i) => i.key)
|
||||
const GROUPS = [...new Set(ITEMS.map((i) => i.group))]
|
||||
|
||||
// DEFAULTS 与 plugin.json.fields 的 default 逐项一致
|
||||
const DEFAULTS = () => ({
|
||||
reports: [...ALL_KEYS],
|
||||
save_dir: '',
|
||||
save_dir: 'D:\\资料\\财务\\CRM数据导出',
|
||||
debug_mode: false,
|
||||
})
|
||||
|
||||
const {
|
||||
form, needLogin, banner, lastSavedAt, running, progress, stopping,
|
||||
saveNow, resetDefaults,
|
||||
form, needLogin, notice, lastSavedAt, running, progress, stopping,
|
||||
saveNow, resetDefaults, restoreLastFields,
|
||||
schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||
run, forceStop,
|
||||
} = usePluginUI({
|
||||
@@ -223,413 +221,108 @@ function selectAll() {
|
||||
function clearAll() {
|
||||
form.reports = []
|
||||
}
|
||||
|
||||
// 调用壳子本机接口打开原生「选择文件夹」对话框(壳子 /api/dialog/directory,仅返回路径)
|
||||
const picking = ref(false)
|
||||
async function pickDir() {
|
||||
picking.value = true
|
||||
try {
|
||||
const r = await fetch('/api/dialog/directory', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ title: '选择保存目录', current: form.save_dir || '' }),
|
||||
})
|
||||
const d = await r.json().catch(() => ({}))
|
||||
if (!r.ok) throw new Error(d.detail || d.error || ('HTTP ' + r.status))
|
||||
if (d.path) form.save_dir = d.path
|
||||
} catch (e) {
|
||||
ElMessage.warning('打开文件夹选择失败:' + e.message)
|
||||
} finally {
|
||||
picking.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* ---------- 页面骨架 ---------- */
|
||||
.page {
|
||||
width: 100%;
|
||||
padding: 6px 4px 28px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
}
|
||||
/* 插件差异样式:只用壳子 token,不写字面色值;左右内边距由壳子提供 */
|
||||
|
||||
.fade-slide-enter-active,
|
||||
.fade-slide-leave-active {
|
||||
transition: opacity 0.25s ease, transform 0.25s ease;
|
||||
}
|
||||
|
||||
.fade-slide-enter-from,
|
||||
.fade-slide-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateY(-6px);
|
||||
}
|
||||
|
||||
/* ---------- 主容器(无边框平铺:外层由壳子 iframe 的边框统一包裹) ---------- */
|
||||
.panel {
|
||||
background: transparent;
|
||||
border-radius: 0;
|
||||
border: none;
|
||||
box-shadow: none;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.panel :deep(.el-card__header) {
|
||||
padding: 6px 2px 16px;
|
||||
border-bottom: 1px solid var(--el-border-color-lighter);
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.panel :deep(.el-card__body) {
|
||||
padding: 16px 2px 2px;
|
||||
}
|
||||
|
||||
/* ---------- 卡片头部 ---------- */
|
||||
.panel-head {
|
||||
/* ---------- 导出内容:顶部计数 + 按钮 ---------- */
|
||||
.grp-tools {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
margin-bottom: var(--space-2-5);
|
||||
}
|
||||
.grp-tools .spacer { flex: 1; }
|
||||
.gt-count { font: 400 11.5px/1 var(--f-cn); color: var(--t3); }
|
||||
.gt-count b { font: 600 12px/1 var(--f-num); color: var(--brand-ink); font-variant-numeric: tabular-nums; }
|
||||
|
||||
.panel-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.title-ico {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 10px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--el-color-primary);
|
||||
background: linear-gradient(135deg, var(--el-color-primary-light-8), var(--el-color-primary-light-6));
|
||||
box-shadow: inset 0 0 0 1px var(--el-color-primary-light-5);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.title-txts {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.title-txt {
|
||||
font-weight: 700;
|
||||
font-size: 15px;
|
||||
line-height: 1.2;
|
||||
color: var(--el-text-color-primary);
|
||||
}
|
||||
|
||||
.title-sub {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.head-tools {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.scheme-sel {
|
||||
width: 200px;
|
||||
}
|
||||
|
||||
.saved {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
color: #2ea44f;
|
||||
background: rgba(46, 164, 79, 0.1);
|
||||
border: 1px solid rgba(46, 164, 79, 0.25);
|
||||
padding: 2px 10px;
|
||||
border-radius: 999px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.saved .dot {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 50%;
|
||||
background: #2ea44f;
|
||||
}
|
||||
|
||||
/* ---------- 表单分区 ---------- */
|
||||
.sec {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.sec:last-of-type {
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.sec-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.sec-badge {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: 7px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
color: var(--el-color-primary);
|
||||
background: var(--el-color-primary-light-9);
|
||||
border: 1px solid var(--el-color-primary-light-7);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.sec-name {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--el-text-color-primary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.sec-line {
|
||||
flex: 1;
|
||||
height: 1px;
|
||||
background: linear-gradient(90deg, var(--el-border-color-lighter), transparent);
|
||||
}
|
||||
|
||||
.sec-count {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.sec-count b {
|
||||
color: var(--el-color-primary);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
/* 执行说明 */
|
||||
.flow-desc {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.flow-item {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
font-size: 13px;
|
||||
color: var(--el-text-color-regular);
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.flow-no {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 6px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
color: var(--el-color-primary);
|
||||
background: var(--el-color-primary-light-9);
|
||||
border: 1px solid var(--el-color-primary-light-7);
|
||||
flex-shrink: 0;
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
/* ---------- 导出内容分组 ---------- */
|
||||
/* ---------- 分组块:浅灰底 + 描边,避免白卡叠白卡 ---------- */
|
||||
.groups {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(340px, 1fr));
|
||||
gap: 10px;
|
||||
grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
|
||||
gap: var(--space-2-5);
|
||||
}
|
||||
|
||||
.grp {
|
||||
border: 1px solid var(--el-border-color-lighter);
|
||||
border-radius: 10px;
|
||||
padding: 10px 14px 12px;
|
||||
background: var(--el-fill-color-blank);
|
||||
transition: border-color 0.2s;
|
||||
background: var(--subtle);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--r-field);
|
||||
padding: 8px 12px 10px;
|
||||
}
|
||||
|
||||
.grp:hover {
|
||||
border-color: var(--el-color-primary-light-5);
|
||||
}
|
||||
|
||||
.grp-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
gap: var(--space-2);
|
||||
padding-bottom: 6px;
|
||||
margin-bottom: 4px;
|
||||
border-bottom: 1px dashed var(--el-border-color-lighter);
|
||||
border-bottom: 1px solid var(--line-soft);
|
||||
}
|
||||
|
||||
.grp-head :deep(.el-checkbox__label) {
|
||||
font-weight: 600;
|
||||
font-size: 13px;
|
||||
font: 600 12.5px/18px var(--f-cn);
|
||||
color: var(--t1);
|
||||
}
|
||||
|
||||
.grp-count {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
font: 500 11px/1 var(--f-num);
|
||||
color: var(--t3);
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--r-pill);
|
||||
padding: 4px 8px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
background: var(--el-fill-color);
|
||||
border-radius: 999px;
|
||||
padding: 1px 8px;
|
||||
}
|
||||
|
||||
.grp-count.full {
|
||||
color: var(--el-color-success);
|
||||
background: rgba(46, 164, 79, 0.1);
|
||||
color: var(--good-ink);
|
||||
background: var(--good-soft);
|
||||
border-color: var(--good-line);
|
||||
}
|
||||
|
||||
.grp-body {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
|
||||
gap: 2px 8px;
|
||||
margin-top: 4px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.grp-body :deep(.el-checkbox) {
|
||||
margin-right: 0;
|
||||
height: 26px;
|
||||
height: 24px;
|
||||
}
|
||||
|
||||
.grp-body :deep(.el-checkbox__label) {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
font-size: 12.5px;
|
||||
color: var(--el-text-color-primary);
|
||||
padding-left: 4px;
|
||||
font: 400 12px/18px var(--f-cn);
|
||||
color: var(--t2);
|
||||
}
|
||||
|
||||
.rep-info {
|
||||
font-size: 13px;
|
||||
color: var(--el-text-color-placeholder);
|
||||
cursor: help;
|
||||
flex-shrink: 0;
|
||||
transition: color 0.2s;
|
||||
}
|
||||
|
||||
.rep-info:hover {
|
||||
color: var(--el-color-primary);
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(280px, 1fr) auto;
|
||||
gap: 0 18px;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.grid :deep(.el-form-item) {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.grid :deep(.el-form-item__label) {
|
||||
padding-bottom: 6px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.tip {
|
||||
width: 100%;
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
line-height: 1.6;
|
||||
margin-top: 6px;
|
||||
color: var(--t4);
|
||||
cursor: help;
|
||||
transition: color var(--dur);
|
||||
}
|
||||
.rep-info:hover { color: var(--brand); }
|
||||
|
||||
/* ---------- 操作区 ---------- */
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
border-top: 1px dashed var(--el-border-color);
|
||||
padding-top: 18px;
|
||||
margin-top: 18px;
|
||||
}
|
||||
|
||||
.spacer {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.btn-run {
|
||||
min-width: 150px;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
letter-spacing: 2px;
|
||||
background: linear-gradient(135deg, var(--el-color-primary), var(--el-color-primary-dark-2));
|
||||
box-shadow: 0 6px 16px var(--el-color-primary-light-6);
|
||||
transition: filter 0.2s, box-shadow 0.2s, transform 0.15s;
|
||||
}
|
||||
|
||||
.btn-run:hover {
|
||||
filter: brightness(1.06);
|
||||
box-shadow: 0 8px 20px var(--el-color-primary-light-5);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.btn-run:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.btn-run.is-loading {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* ---------- 运行状态 ---------- */
|
||||
.status {
|
||||
padding: 14px 16px;
|
||||
border-radius: 12px;
|
||||
background: linear-gradient(135deg, var(--el-color-primary-light-9), var(--el-color-primary-light-8));
|
||||
border: 1px solid var(--el-color-primary-light-6);
|
||||
box-shadow: 0 2px 10px var(--el-color-primary-light-7);
|
||||
}
|
||||
|
||||
.status-bar :deep(.el-progress-bar__outer) {
|
||||
background: rgba(64, 158, 255, 0.15);
|
||||
}
|
||||
|
||||
.status-bar :deep(.el-progress-bar__inner) {
|
||||
background: linear-gradient(90deg, var(--el-color-primary), var(--el-color-primary-dark-2));
|
||||
}
|
||||
|
||||
.status-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.pulse {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: var(--el-color-primary);
|
||||
animation: pulse 1.4s ease-out infinite;
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0% {
|
||||
box-shadow: 0 0 0 0 var(--el-color-primary-light-6);
|
||||
}
|
||||
|
||||
70% {
|
||||
box-shadow: 0 0 0 8px transparent;
|
||||
}
|
||||
|
||||
100% {
|
||||
box-shadow: 0 0 0 0 transparent;
|
||||
}
|
||||
}
|
||||
|
||||
.status-txt {
|
||||
flex: 1;
|
||||
font-size: 12.5px;
|
||||
color: var(--el-text-color-regular);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.status-pct {
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
color: var(--el-color-primary);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
/* ---------- 执行设置:目录输入框 + 选择按钮(同一行两列) ---------- */
|
||||
.dir-ctrl { display: flex; align-items: center; gap: var(--space-2); width: 100%; }
|
||||
.dir-ctrl .dir-input { flex: 1 1 auto; min-width: 0; }
|
||||
.dir-ctrl .dir-btn { flex: 0 0 auto; }
|
||||
</style>
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { createApp } from 'vue'
|
||||
import ElementPlus from 'element-plus'
|
||||
import 'element-plus/dist/index.css'
|
||||
import zhCn from 'element-plus/es/locale/lang/zh-cn'
|
||||
import App from './App.vue'
|
||||
|
||||
createApp(App).use(ElementPlus, { locale: zhCn }).mount('#app')
|
||||
import { createApp } from 'vue'
|
||||
import ElementPlus from 'element-plus'
|
||||
import 'element-plus/dist/index.css'
|
||||
// 注意顺序:style.css 必须在 element-plus 之后引入,才能覆盖 --el-* 变量映射到壳子 token
|
||||
import './style.css'
|
||||
import zhCn from 'element-plus/es/locale/lang/zh-cn'
|
||||
import App from './App.vue'
|
||||
|
||||
createApp(App).use(ElementPlus, { locale: zhCn }).mount('#app')
|
||||
|
||||
@@ -0,0 +1,341 @@
|
||||
/* ============================================================
|
||||
插件 UI 基础样式(规范 v3 · 对齐壳子「白底面板 + 描边卡」)
|
||||
- token 与壳子 frontend/src/style.css 同源(权威源 design-app/styles.css)
|
||||
- Element Plus 变量映射到壳子 token
|
||||
- 版式类:page / toolbar / notice / sec / grid / tip / actions / badge / table
|
||||
规则:插件内只用 var(--xxx),不写字面色值;左右内边距由壳子提供,不要重复加
|
||||
============================================================ */
|
||||
|
||||
:root {
|
||||
/* 底色与卡面 */
|
||||
--canvas: #F2F4F8;
|
||||
--surface: #FFFFFF;
|
||||
--field: #F5F6FA;
|
||||
--subtle: #F7F8FC;
|
||||
|
||||
/* 描边 */
|
||||
--line: #E8EAF1;
|
||||
--line-soft: #F0F2F7;
|
||||
--line-btn: #E3E6EF;
|
||||
|
||||
/* 文字五阶 */
|
||||
--t1: #12141B;
|
||||
--t2: #3C4250;
|
||||
--t3: #6E7686;
|
||||
--t4: #A3AAB8;
|
||||
--t5: #C6CBD6;
|
||||
|
||||
/* 主色(靛蓝) */
|
||||
--brand: #4F5AE8;
|
||||
--brand-ink: #3D47D4;
|
||||
--brand-soft: #EEF0FE;
|
||||
--brand-track: #DDE1F8;
|
||||
--brand-hover: #4550E0;
|
||||
|
||||
/* 语义色 */
|
||||
--good: #0E9F76; --good-ink: #0B8A66; --good-soft: #EBF7F2; --good-line: #D3EDE3;
|
||||
--warn: #D98218; --warn-ink: #B4700F; --warn-soft: #FDF3E4; --warn-line: rgba(217, 130, 24, .28);
|
||||
--danger: #E5484D; --danger-ink: #CC3B40; --danger-soft: #FDEDED; --danger-line: #F6D7D8;
|
||||
|
||||
/* 圆角 */
|
||||
--r-row: 8px;
|
||||
--r-field: 9px;
|
||||
--r-btn: 10px;
|
||||
--r-sub: 12px;
|
||||
--r-card: 14px;
|
||||
--r-pill: 999px;
|
||||
|
||||
/* 阴影(插件内基本不用,保持与壳子同值) */
|
||||
--sh-card: 0 2px 8px rgba(18, 20, 31, .05);
|
||||
--sh-float: 0 8px 24px rgba(18, 20, 31, .10);
|
||||
--sh-brand: 0 4px 12px rgba(79, 89, 232, .28);
|
||||
--sh-brand-sm: 0 2px 8px rgba(79, 89, 232, .24);
|
||||
|
||||
/* 字体 */
|
||||
--f-cn: "PingFang SC", "HarmonyOS Sans SC", "Microsoft YaHei", "Noto Sans SC", system-ui, -apple-system, sans-serif;
|
||||
--f-num: "Inter", "SF Pro Display", -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||
--f-mono: "JetBrains Mono", "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
|
||||
|
||||
/* 间距 */
|
||||
--space-1: 4px;
|
||||
--space-1-5: 6px;
|
||||
--space-2: 8px;
|
||||
--space-2-5: 10px;
|
||||
--space-3: 12px;
|
||||
--space-4: 16px;
|
||||
--space-5: 20px;
|
||||
--space-6: 28px;
|
||||
|
||||
--dur: .15s;
|
||||
--ease: cubic-bezier(.22, 1, .36, 1);
|
||||
}
|
||||
|
||||
/* ---------- Element Plus → 壳子 token ---------- */
|
||||
:root {
|
||||
--el-color-primary: var(--brand);
|
||||
--el-color-primary-light-3: #7A83EE;
|
||||
--el-color-primary-light-5: #A6ACF4;
|
||||
--el-color-primary-light-7: #C9CDF9;
|
||||
--el-color-primary-light-8: #DDE0FB;
|
||||
--el-color-primary-light-9: var(--brand-soft);
|
||||
--el-color-primary-dark-2: var(--brand-ink);
|
||||
|
||||
--el-color-success: var(--good);
|
||||
--el-color-success-light-9: var(--good-soft);
|
||||
--el-color-warning: var(--warn);
|
||||
--el-color-warning-light-9: var(--warn-soft);
|
||||
--el-color-danger: var(--danger);
|
||||
--el-color-danger-light-9: var(--danger-soft);
|
||||
--el-color-error: var(--danger);
|
||||
|
||||
--el-text-color-primary: var(--t1);
|
||||
--el-text-color-regular: var(--t2);
|
||||
--el-text-color-secondary: var(--t3);
|
||||
--el-text-color-placeholder: var(--t4);
|
||||
|
||||
--el-border-color: var(--line);
|
||||
--el-border-color-light: var(--line);
|
||||
--el-border-color-lighter: var(--line-soft);
|
||||
--el-border-color-extra-light: var(--line-soft);
|
||||
--el-fill-color-blank: var(--surface);
|
||||
--el-fill-color-light: var(--field);
|
||||
--el-bg-color: var(--surface);
|
||||
|
||||
--el-border-radius-base: var(--r-field);
|
||||
--el-border-radius-small: var(--r-field);
|
||||
--el-font-family: var(--f-cn);
|
||||
--el-font-size-base: 12.5px;
|
||||
--el-box-shadow-light: var(--sh-card);
|
||||
}
|
||||
|
||||
/* ---------- 基础重置 ---------- */
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
html, body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background: var(--surface);
|
||||
color: var(--t1);
|
||||
font-family: var(--f-cn);
|
||||
font-size: 12.5px;
|
||||
line-height: 1.5;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
#app { padding: 0; }
|
||||
|
||||
/* ---------- 页面:只排垂直节奏(左右 24px 由壳子给) ---------- */
|
||||
.page {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-4);
|
||||
padding: 2px 0 20px;
|
||||
}
|
||||
|
||||
/* ---------- 工具条:方案下拉 + 存为方案 + 删除 + 已保存胶囊 ---------- */
|
||||
.toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
flex-wrap: wrap;
|
||||
min-height: 32px;
|
||||
}
|
||||
.toolbar .spacer { flex: 1; }
|
||||
.scheme-sel { width: 200px; }
|
||||
|
||||
.saved {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
height: 22px;
|
||||
padding: 0 9px;
|
||||
border-radius: var(--r-pill);
|
||||
background: var(--good-soft);
|
||||
border: 1px solid var(--good-line);
|
||||
color: var(--good-ink);
|
||||
font: 500 11px/1 var(--f-cn);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.saved i { width: 5px; height: 5px; border-radius: 50%; background: var(--good); }
|
||||
.saved.is-idle { background: var(--field); border-color: var(--line); color: var(--t4); }
|
||||
.saved.is-idle i { background: var(--t5); }
|
||||
|
||||
/* ---------- 提示条(替代顶部大横幅) ---------- */
|
||||
.notice {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: var(--space-2);
|
||||
padding: 9px 12px;
|
||||
border-radius: var(--r-sub);
|
||||
border: 1px solid var(--line);
|
||||
background: var(--subtle);
|
||||
font: 400 12px/18px var(--f-cn);
|
||||
color: var(--t2);
|
||||
}
|
||||
.notice .n-ico { flex: 0 0 auto; font-weight: 700; }
|
||||
.notice.is-warn { background: var(--warn-soft); border-color: var(--warn-line); color: var(--warn-ink); }
|
||||
.notice.is-error { background: var(--danger-soft); border-color: var(--danger-line); color: var(--danger-ink); }
|
||||
.notice.is-ok { background: var(--good-soft); border-color: var(--good-line); color: var(--good-ink); }
|
||||
|
||||
/* ---------- 分区卡:与壳子列表卡/表格卡同一套 ---------- */
|
||||
.sec {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--r-sub);
|
||||
overflow: hidden;
|
||||
}
|
||||
.sec-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
padding: 10px 14px;
|
||||
background: var(--subtle);
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.sec-badge {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 6px;
|
||||
display: inline-grid;
|
||||
place-items: center;
|
||||
font: 600 10.5px/1 var(--f-num);
|
||||
color: var(--brand-ink);
|
||||
background: var(--brand-soft);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.sec-name { font: 600 13px/18px var(--f-cn); color: var(--t1); white-space: nowrap; }
|
||||
.sec-line { flex: 1; height: 1px; background: var(--line-soft); }
|
||||
.sec-body { padding: 14px 14px 6px; }
|
||||
|
||||
/* ---------- 栅格与表单 ---------- */
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
|
||||
gap: 0 16px;
|
||||
}
|
||||
.grid-switch { grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); }
|
||||
/* 日期行紧跟在开关行后,补一点呼吸 */
|
||||
.grid-date { margin-top: 4px; }
|
||||
.grid .el-form-item { margin-bottom: 12px; }
|
||||
.grid .el-form-item__label {
|
||||
padding-bottom: 6px !important;
|
||||
font-weight: 500;
|
||||
color: var(--t2);
|
||||
}
|
||||
.grid .el-input,
|
||||
.grid .el-select,
|
||||
.grid .el-date-editor,
|
||||
.grid .el-input-number { width: 100% !important; }
|
||||
|
||||
/* ---------- 说明文字 ---------- */
|
||||
.tip {
|
||||
margin-top: var(--space-2);
|
||||
font: 400 11.5px/1.65 var(--f-cn);
|
||||
color: var(--t3);
|
||||
}
|
||||
.tip b { color: var(--t2); font-weight: 600; }
|
||||
|
||||
/* ---------- 执行摘要(操作区上方一行低调说明) ---------- */
|
||||
.plan { display: flex; align-items: baseline; gap: var(--space-2); font-size: 11.5px; line-height: 1.6; color: var(--t3); }
|
||||
.plan .p-tag { flex: 0 0 auto; font-weight: 600; color: var(--brand-ink); }
|
||||
.plan .p-text { min-width: 0; }
|
||||
.plan.is-empty .p-text { color: var(--warn); }
|
||||
|
||||
/* ---------- 操作区 ---------- */
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
flex-wrap: wrap;
|
||||
padding-top: 14px;
|
||||
border-top: 1px solid var(--line-soft);
|
||||
}
|
||||
.actions .spacer { flex: 1; }
|
||||
.btn-run {
|
||||
min-width: 150px;
|
||||
height: 34px;
|
||||
border: none;
|
||||
border-radius: var(--r-btn);
|
||||
background: var(--brand);
|
||||
color: #fff;
|
||||
font: 600 12.5px/18px var(--f-cn);
|
||||
letter-spacing: 1px;
|
||||
box-shadow: var(--sh-brand);
|
||||
transition: background var(--dur), box-shadow var(--dur), transform .06s;
|
||||
}
|
||||
.btn-run:hover { background: var(--brand-hover); }
|
||||
.btn-run:active { transform: translateY(1px); box-shadow: var(--sh-brand-sm); }
|
||||
.btn-run.is-loading { pointer-events: none; }
|
||||
|
||||
/* ---------- 状态胶囊(与壳子表格状态列同款) ---------- */
|
||||
.badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
height: 22px;
|
||||
padding: 0 9px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 6px;
|
||||
font: 500 11px/1 var(--f-cn);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.badge i { width: 5px; height: 5px; border-radius: 50%; flex-shrink: 0; }
|
||||
.badge.ok { color: var(--good-ink); background: var(--good-soft); border-color: var(--good-line); }
|
||||
.badge.ok i { background: var(--good); }
|
||||
.badge.warn { color: var(--warn-ink); background: var(--warn-soft); border-color: var(--warn-line); }
|
||||
.badge.warn i { background: var(--warn); }
|
||||
.badge.bad { color: var(--danger-ink); background: var(--danger-soft); border-color: var(--danger-line); }
|
||||
.badge.bad i { background: var(--danger); }
|
||||
.badge.idle { color: var(--t3); background: var(--field); border-color: var(--line); }
|
||||
.badge.idle i { background: var(--t5); }
|
||||
|
||||
/* ---------- 表格(插件内需要列表时用;与壳子表格同口径) ---------- */
|
||||
.table-card {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--r-sub);
|
||||
overflow: hidden;
|
||||
}
|
||||
.table-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
padding: 12px 16px;
|
||||
background: var(--subtle);
|
||||
border-bottom: 1px solid var(--line);
|
||||
font: 600 13.5px/20px var(--f-cn);
|
||||
color: var(--t1);
|
||||
}
|
||||
.table { width: 100%; border-collapse: collapse; table-layout: fixed; }
|
||||
.table th {
|
||||
padding: 10px 16px;
|
||||
text-align: center;
|
||||
font: 500 11px/16px var(--f-cn);
|
||||
color: var(--t3);
|
||||
background: var(--surface);
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.table td {
|
||||
padding: 10px 16px;
|
||||
text-align: center;
|
||||
border-bottom: 1px solid var(--line-soft);
|
||||
font: 400 12px/18px var(--f-cn);
|
||||
color: var(--t2);
|
||||
}
|
||||
.table tr:last-child td { border-bottom: 0; }
|
||||
.table tbody tr { transition: background var(--dur); }
|
||||
.table tbody tr:hover { background: var(--field); }
|
||||
.table td.is-name { text-align: left; font-weight: 600; color: var(--t1); }
|
||||
.table th.is-name { text-align: left; }
|
||||
|
||||
/* ---------- 运行态一行文字(进度由壳子 RunIndicator 展示) ---------- */
|
||||
.runline { display: flex; align-items: center; gap: var(--space-2); font-size: 12px; color: var(--t3); }
|
||||
.runline .pct { font: 600 12px/1 var(--f-num); color: var(--brand-ink); font-variant-numeric: tabular-nums; }
|
||||
.pulse { width: 7px; height: 7px; border-radius: 50%; background: var(--brand); animation: pulse 1.4s ease-out infinite; }
|
||||
@keyframes pulse {
|
||||
0% { box-shadow: 0 0 0 0 var(--brand-soft); }
|
||||
70% { box-shadow: 0 0 0 7px transparent; }
|
||||
100% { box-shadow: 0 0 0 0 transparent; }
|
||||
}
|
||||
@@ -1,9 +1,14 @@
|
||||
// 插件 UI 公共 kit(vendored 进各插件 ui-src,构建期内联进产物,运行零外部依赖)。
|
||||
// 收敛三块通用逻辑,App.vue 只保留各插件差异部分(表单字段/校验/布局):
|
||||
// 1. 本机当前配置:加载、防抖自动保存、恢复默认(/api/plugin-config/<id>)
|
||||
// 2. 多配置方案:列表/应用/存为方案/删除(/api/plugin-configs,同名覆盖、密码明文保存;
|
||||
// 供壳子「定时任务」按 config_id 引用,到点自动取方案最新参数)
|
||||
// 3. 执行状态机:一键执行、强制停止、WS 实时进度 + 轮询兜底、未登录重试
|
||||
// 插件 UI 公共 kit v2(vendored 进各插件 ui-src,构建期内联,运行零外部依赖)。
|
||||
//
|
||||
// 与 v1 的差异(适配当前壳子):
|
||||
// 1. 新增 restoreLastFields():调 /api/plugins/<id>/last-fields 恢复上次执行参数(password 不落盘);
|
||||
// 2. 顶部大横幅 → 内联 notice:执行结果横幅、插件名/版本、运行 Indicator 已由壳子
|
||||
// (PageHead + 结果横幅 + RunIndicator)统一渲染,插件内不再重复;
|
||||
// 3. startRun 的 409 单独识别:壳子在 iframe fetch 上包了「入队确认」,用户取消会返回 409,
|
||||
// 不能再当成普通失败提示。
|
||||
//
|
||||
// 保留能力:本机当前配置(加载/防抖自动保存/恢复默认)、多配置方案(供定时任务按 config_id 引用)、
|
||||
// 执行状态机(执行/强停/WS 进度 + 轮询兜底/未登录重试)。
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { PLUGIN_ID } from './api'
|
||||
@@ -15,58 +20,37 @@ async function j(url, opts) {
|
||||
}
|
||||
if (!res.ok) {
|
||||
let msg = `HTTP ${res.status}`
|
||||
try { msg = (await res.json()).detail || msg } catch (_) { /* 保留默认 */ }
|
||||
throw new Error(msg)
|
||||
try {
|
||||
msg = (await res.json()).detail || msg
|
||||
} catch (_) { /* 保留默认 */ }
|
||||
throw Object.assign(new Error(msg), { code: res.status, status: res.status })
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
// ---- 后端 API(同源,统一账户会话 cookie 自动携带)----
|
||||
function loadConfig() {
|
||||
return j(`/api/plugin-config/${PLUGIN_ID}`)
|
||||
}
|
||||
|
||||
function saveConfig(data) {
|
||||
return j(`/api/plugin-config/${PLUGIN_ID}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
function listSchemes() {
|
||||
return j(`/api/plugin-configs?plugin_id=${encodeURIComponent(PLUGIN_ID)}`)
|
||||
}
|
||||
|
||||
function saveScheme(name, fields) {
|
||||
return j('/api/plugin-configs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, name, fields }),
|
||||
})
|
||||
}
|
||||
|
||||
function deleteScheme(cfgId) {
|
||||
return j(`/api/plugin-configs/${encodeURIComponent(PLUGIN_ID)}/${encodeURIComponent(cfgId)}`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
}
|
||||
|
||||
function startRun(fields) {
|
||||
return j('/api/runs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, fields }),
|
||||
})
|
||||
}
|
||||
|
||||
function getRun(runId) {
|
||||
return j(`/api/runs/${runId}`)
|
||||
}
|
||||
|
||||
function stopRun(runId) {
|
||||
return j(`/api/runs/${runId}/stop`, { method: 'POST' })
|
||||
}
|
||||
const loadConfig = () => j(`/api/plugin-config/${PLUGIN_ID}`)
|
||||
const saveConfig = (data) => j(`/api/plugin-config/${PLUGIN_ID}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
const loadLastFields = () => j(`/api/plugins/${PLUGIN_ID}/last-fields`)
|
||||
const listSchemes = () => j(`/api/plugin-configs?plugin_id=${encodeURIComponent(PLUGIN_ID)}`)
|
||||
const saveScheme = (name, fields) => j('/api/plugin-configs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, name, fields }),
|
||||
})
|
||||
const deleteScheme = (cfgId) =>
|
||||
j(`/api/plugin-configs/${encodeURIComponent(PLUGIN_ID)}/${encodeURIComponent(cfgId)}`, { method: 'DELETE' })
|
||||
const startRun = (fields) => j('/api/runs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, fields }),
|
||||
})
|
||||
const getRun = (runId) => j(`/api/runs/${runId}`)
|
||||
const stopRun = (runId) => j(`/api/runs/${runId}/stop`, { method: 'POST' })
|
||||
|
||||
function connectWS(onEvent) {
|
||||
const ws = new WebSocket((location.protocol === 'https:' ? 'wss://' : 'ws://')
|
||||
@@ -78,8 +62,18 @@ function connectWS(onEvent) {
|
||||
// ---- 工具 ----
|
||||
const clone = (o) => JSON.parse(JSON.stringify(o))
|
||||
|
||||
// 保存字段合并规则:标量空值(''/null/undefined)不覆盖;数组照原样应用——
|
||||
// 空数组可能是有意配置(如 xq0031 仓库留空 = 全部不筛选),必须还原
|
||||
// 本机配置的「上次保存时间」:后端只存字段、不返回时间戳,
|
||||
// 这里用 localStorage 记住,刷新后仍能显示(取不到时静默)。
|
||||
const SAVED_AT_KEY = `plugin:${PLUGIN_ID}:lastSavedAt`
|
||||
function readSavedAt() {
|
||||
try { return localStorage.getItem(SAVED_AT_KEY) || '' } catch (_) { return '' }
|
||||
}
|
||||
function writeSavedAt(v) {
|
||||
try { localStorage.setItem(SAVED_AT_KEY, v) } catch (_) { /* 存储不可用时只保留内存态 */ }
|
||||
}
|
||||
|
||||
// 保存字段合并规则:标量空值(''/null/undefined)不覆盖;数组照原样应用
|
||||
// (空数组可能是有意配置,如「留空=不筛选」)
|
||||
function mergeSaved(form, saved) {
|
||||
Object.keys(form).forEach((k) => {
|
||||
const v = saved ? saved[k] : undefined
|
||||
@@ -88,22 +82,14 @@ function mergeSaved(form, saved) {
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 插件 UI 公共状态机
|
||||
* @param {Object} opts
|
||||
* @param {Function} opts.defaults 默认表单工厂;恢复默认时传入当前表单作参考
|
||||
* (如 xq0031 按当前 erp_system 带出对应默认组织/仓库)
|
||||
* @param {Function} [opts.validate] 执行前校验,失败自行 ElMessage 提示并返回 false
|
||||
* @param {Function} [opts.buildPayload] 定制提交参数(缺省 = 表单全量深拷贝)
|
||||
*/
|
||||
export function usePluginUI(opts = {}) {
|
||||
const { defaults, validate, buildPayload } = opts
|
||||
|
||||
const form = reactive(defaults ? defaults() : {})
|
||||
const loaded = ref(false)
|
||||
const needLogin = ref(false)
|
||||
const banner = ref(null)
|
||||
const lastSavedAt = ref('')
|
||||
const notice = ref(null) // { type: 'warn'|'error'|'ok', text }
|
||||
const lastSavedAt = ref(readSavedAt())
|
||||
const running = ref(false)
|
||||
const progress = ref(0)
|
||||
const stopping = ref(false)
|
||||
@@ -113,20 +99,23 @@ export function usePluginUI(opts = {}) {
|
||||
let pollTimer = null
|
||||
let saveTimer = null
|
||||
|
||||
// 传空 type 视为清除横幅(不能留 {type:null},否则会渲染成只有"!"的空横幅)
|
||||
const notify = (type, text) => { notice.value = type ? { type, text } : null }
|
||||
|
||||
// ---------- 当前配置:加载 / 防抖自动保存 ----------
|
||||
// 登录由壳子统一处理(打开界面时会话必然就绪),这里读取失败一律静默回退默认值,
|
||||
// 不弹任何提示;真到执行时才发现会话问题,再明确告知。
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const saved = await loadConfig()
|
||||
mergeSaved(form, saved)
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.warning('读取本机配置失败,已用默认值:' + e.message)
|
||||
}
|
||||
loaded.value = true
|
||||
refreshSchemes() // 方案列表一并加载:重开界面/切插件回来(iframe 重挂载)后,下拉仍列出全部已存方案
|
||||
refreshSchemes()
|
||||
})
|
||||
|
||||
// 配置变更自动保存(防抖 800ms),执行中不保存
|
||||
watch(form, () => {
|
||||
if (!loaded.value || running.value) return
|
||||
clearTimeout(saveTimer)
|
||||
@@ -137,6 +126,7 @@ export function usePluginUI(opts = {}) {
|
||||
try {
|
||||
await saveConfig(clone(form))
|
||||
lastSavedAt.value = new Date().toLocaleTimeString('zh-CN', { hour12: false })
|
||||
writeSavedAt(lastSavedAt.value)
|
||||
if (explicit) ElMessage.success('配置已保存到本机')
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
@@ -146,12 +136,30 @@ export function usePluginUI(opts = {}) {
|
||||
|
||||
function resetDefaults() {
|
||||
Object.assign(form, defaults ? defaults(form) : {})
|
||||
notify(null)
|
||||
ElMessage.info('已恢复默认配置')
|
||||
}
|
||||
|
||||
// ---------- 多配置方案(定时任务引用的参数快照,在插件界面维护) ----------
|
||||
const schemes = ref([]) // [{id, name, fields, at}]
|
||||
const schemeSel = ref('') // '' = 当前配置(即表单本身)
|
||||
// 恢复上次执行参数(壳子记录,password 类字段不落盘)
|
||||
async function restoreLastFields() {
|
||||
try {
|
||||
const r = await loadLastFields()
|
||||
const fields = r.fields || {}
|
||||
if (!Object.keys(fields).length) {
|
||||
ElMessage.info('暂无上次执行参数')
|
||||
return
|
||||
}
|
||||
mergeSaved(form, fields)
|
||||
ElMessage.success('已恢复上次执行参数' + (r.at ? `(${r.at})` : ''))
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.error('恢复上次参数失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 多配置方案 ----------
|
||||
const schemes = ref([])
|
||||
const schemeSel = ref('')
|
||||
const schemeOptions = computed(() => [
|
||||
{ value: '', label: '当前配置(自动保存)' },
|
||||
...schemes.value.map((s) => ({ value: s.id, label: s.name })),
|
||||
@@ -161,15 +169,11 @@ export function usePluginUI(opts = {}) {
|
||||
try {
|
||||
const r = await listSchemes()
|
||||
schemes.value = r.configs || []
|
||||
} catch (_) {
|
||||
/* 方案是辅助能力,加载失败静默(下拉仅剩当前配置) */
|
||||
}
|
||||
} catch (_) { /* 方案是辅助能力,失败静默 */ }
|
||||
}
|
||||
|
||||
// 应用方案:载入方案字段(密码随方案明文保存)→ 防抖自动保存固化为当前配置;
|
||||
// 执行永远提交表单当前值,方案本身只作为定时任务的参数快照源
|
||||
function onSchemeChange(id) {
|
||||
if (!id) return // 切回「当前配置」:表单即当前配置,无需动作
|
||||
if (!id) return
|
||||
const s = schemes.value.find((x) => x.id === id)
|
||||
if (!s) return
|
||||
mergeSaved(form, s.fields)
|
||||
@@ -189,10 +193,10 @@ export function usePluginUI(opts = {}) {
|
||||
cancelButtonText: '取消',
|
||||
inputPattern: /\S/,
|
||||
inputErrorMessage: '请输入方案名称',
|
||||
}
|
||||
},
|
||||
))
|
||||
} catch (_) {
|
||||
return // 用户取消
|
||||
return
|
||||
}
|
||||
name = String(name).trim()
|
||||
if (!name) return
|
||||
@@ -202,10 +206,10 @@ export function usePluginUI(opts = {}) {
|
||||
await ElMessageBox.confirm(
|
||||
`已存在同名方案「${dup.name}」,保存将覆盖它的参数(多套不同配置请用不同名称)。`,
|
||||
'覆盖已有方案',
|
||||
{ type: 'warning', confirmButtonText: '覆盖保存', cancelButtonText: '取消' }
|
||||
{ type: 'warning', confirmButtonText: '覆盖保存', cancelButtonText: '取消' },
|
||||
)
|
||||
} catch (_) {
|
||||
return // 用户取消覆盖
|
||||
return
|
||||
}
|
||||
}
|
||||
try {
|
||||
@@ -226,7 +230,7 @@ export function usePluginUI(opts = {}) {
|
||||
await ElMessageBox.confirm(
|
||||
`删除配置方案「${s.name}」?引用它的定时任务到点会跳过触发并提示重选。`,
|
||||
'删除方案',
|
||||
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
|
||||
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' },
|
||||
)
|
||||
} catch (_) {
|
||||
return
|
||||
@@ -242,38 +246,45 @@ export function usePluginUI(opts = {}) {
|
||||
}
|
||||
|
||||
// ---------- 执行 ----------
|
||||
async function run() {
|
||||
// action: download(只下载)/ reconcile(只核对);不传则用 payload 里的 action
|
||||
async function run(action) {
|
||||
if (running.value) return
|
||||
// 未登录不再静默返回:先重试一次配置读取(会话可能在打开后已恢复),仍失败则明确提示
|
||||
if (needLogin.value) {
|
||||
try {
|
||||
await loadConfig()
|
||||
needLogin.value = false
|
||||
ElMessage.success('登录态已恢复,请再次点击执行')
|
||||
} catch (_) {
|
||||
notify('error', '登录态未就绪,请稍后重试')
|
||||
return
|
||||
} catch (_) { /* 仍未登录 */ }
|
||||
ElMessage.warning('未登录:请先在壳子登录统一账户,再打开本界面')
|
||||
return
|
||||
}
|
||||
}
|
||||
if (validate && !validate()) return
|
||||
if (validate && !validate(action)) return
|
||||
await saveNow(false)
|
||||
notify(null)
|
||||
running.value = true
|
||||
progress.value = 0
|
||||
banner.value = null
|
||||
try {
|
||||
const r = await startRun(buildPayload ? buildPayload(form) : clone(form))
|
||||
const payload = buildPayload ? buildPayload(form) : clone(form)
|
||||
if (action) payload.action = action
|
||||
const r = await startRun(payload)
|
||||
runId = r.run_id
|
||||
connect() // runId 就绪后再连 WS,避免早到的运行事件被过滤掉
|
||||
connect()
|
||||
startPolling()
|
||||
} catch (e) {
|
||||
running.value = false
|
||||
stopPolling()
|
||||
if (e.code === 401) needLogin.value = true
|
||||
banner.value = { type: 'error', text: '启动执行失败:' + e.message }
|
||||
if (e.code === 401) {
|
||||
needLogin.value = true
|
||||
notify('error', '登录态未就绪,本次没有启动,请稍后重试')
|
||||
} else if (e.code === 409) {
|
||||
// 壳子「入队确认」里用户点了取消
|
||||
notify('warn', '已取消加入执行队列,本次没有启动')
|
||||
} else {
|
||||
notify('error', '启动执行失败:' + e.message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 强制停止(整树强杀执行子进程,含浏览器)
|
||||
async function forceStop() {
|
||||
if (!runId || stopping.value) return
|
||||
stopping.value = true
|
||||
@@ -287,11 +298,10 @@ export function usePluginUI(opts = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
// 实时进度 + 完成(WS 只取进度/结束事件,日志由壳子下方日志区展示;断开后轮询兜底)
|
||||
function connect() {
|
||||
if (ws && ws.readyState <= 1) return
|
||||
ws = connectWS((ev) => {
|
||||
if (ev.run_id && ev.run_id !== runId) return // 只看本次运行
|
||||
if (ev.run_id && ev.run_id !== runId) return
|
||||
if (ev.t === 'progress') progress.value = Math.max(progress.value, ev.pct || 0)
|
||||
else if (ev.t === 'run_done') ev.ok ? finished() : failed(ev.error || '执行失败')
|
||||
})
|
||||
@@ -304,7 +314,7 @@ export function usePluginUI(opts = {}) {
|
||||
if (!runId) return
|
||||
try {
|
||||
const r = await getRun(runId)
|
||||
if (r.status === 'done') finished(r.result?.summary || '执行完成')
|
||||
if (r.status === 'done') finished(r.result?.summary)
|
||||
else if (r.status === 'error') failed(r.error || '执行失败')
|
||||
} catch (_) { /* 下轮再试 */ }
|
||||
}, 5000)
|
||||
@@ -318,23 +328,20 @@ export function usePluginUI(opts = {}) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
progress.value = 100
|
||||
banner.value = { type: 'success', text: summary || '执行完成' }
|
||||
// 结果横幅由壳子统一展示,插件内仅在需要时给一句简短结论
|
||||
if (summary) notify('ok', summary)
|
||||
}
|
||||
|
||||
function failed(err) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
banner.value = { type: 'error', text: '执行失败:' + err }
|
||||
notify('error', '执行失败:' + err)
|
||||
}
|
||||
|
||||
return {
|
||||
// 状态
|
||||
form, loaded, needLogin, banner, lastSavedAt, running, progress, stopping,
|
||||
// 当前配置
|
||||
saveNow, resetDefaults,
|
||||
// 多配置方案
|
||||
form, loaded, needLogin, notice, lastSavedAt, running, progress, stopping,
|
||||
saveNow, resetDefaults, restoreLastFields,
|
||||
schemes, schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||
// 执行
|
||||
run, forceStop,
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+23
-23
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -4,8 +4,8 @@
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>CRM数据导出</title>
|
||||
<script type="module" crossorigin src="/pui/xq0048/assets/index-DLXNU8di.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0048/assets/index-CLtlaiAs.css">
|
||||
<script type="module" crossorigin src="/pui/xq0048/assets/index-DDWdGAco.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0048/assets/index-B4OFoa9k.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
|
||||
@@ -1,221 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 雇主险增减操作 插件入口。
|
||||
|
||||
流程编排(替代影刀版 4 个脚本的人工串行,WPS COM 替代人工 Ctrl+S 刷新公式):
|
||||
1) 花名册确保:源表缺失或超过 TTL(15 分钟)时自动从 HR 接口导出,新鲜度内复用;
|
||||
2) 筛选复制:按类别 include/exclude 过滤花名册数据写入各目标表(F列工号强制文本);
|
||||
3) WPS/Excel 后台重算公式(替代人工打开文件 Ctrl+S,供调度读取公式缓存值);
|
||||
4) 三阶段名额调度:更新「手动维护-在参名单」+ 精细更新「变更清单」+ 备份;
|
||||
5) 再次重算公式(刷新变更清单/在参名单公式列缓存);
|
||||
6) 生成增员/减员导入文件 + 导出变更清单独立工作簿(公式转值);
|
||||
7) HR 自动导入(可选开关,默认开启):浏览器自动化把调度生成的导入文件导入
|
||||
HR「待增减人员」(先全部减员再全部增员,仅导入本次调度成功的类别);
|
||||
8) 钉钉群通知(可选开关,默认开启):汇总 + 增/减员导入异常名单推送到钉钉群
|
||||
(失败不影响主流程)。
|
||||
|
||||
运行上下文:底座注入 HR 会话与 userId(config 全局钩子),平台 = hr,uses_month = False。
|
||||
字段(fields)由 plugin.json 权威定义:base_dir / ref_date / categories / roster_path /
|
||||
enable_validation / wps_recalc / export_change_sheet / gen_import_files / import_to_hr /
|
||||
dingtalk_notify。
|
||||
"""
|
||||
import os
|
||||
|
||||
from webhost.backend.plugins.base import ScenePlugin, PLUGINS
|
||||
|
||||
from . import config
|
||||
from .logic import roster_filter, schedule, hr_import
|
||||
from .logic.wps_recalc import recalc_target, ComRecalcError
|
||||
from .report import notify, output
|
||||
|
||||
|
||||
class EmployerInsurancePlugin(ScenePlugin):
|
||||
"""雇主险名额调度(需求 XQ0002)。"""
|
||||
|
||||
id = "xq0002"
|
||||
name = "雇主险增减操作"
|
||||
version = "1.0.9"
|
||||
description = ("雇主险名额调度全流程:花名册导出→筛选复制→WPS/Excel 后台取消筛选并重算公式→"
|
||||
"三阶段名额调度→更新在参名单与变更清单→生成增员/减员导入文件"
|
||||
"(可选自动导入 HR 系统)→钉钉群推送汇总与导入异常名单,"
|
||||
"替代人工取消筛选与 Ctrl+S 刷新公式、人工上传导入环节")
|
||||
platform = "hr"
|
||||
uses_month = False
|
||||
capabilities = ["xq0002"]
|
||||
permissions = {"platforms": ["hr"]}
|
||||
|
||||
def run(self, fields: dict, ctx):
|
||||
# ---- 注入运行上下文:日志 / HR 会话 / userId ----
|
||||
config.set_log(ctx.log)
|
||||
config.set_user_id(ctx.get_user_id("hr"))
|
||||
session = None
|
||||
try:
|
||||
session = ctx.get_session("hr")
|
||||
except Exception as e:
|
||||
ctx.log(f"HR 会话获取失败(花名册自动导出将回退共享 cookies):{e}", "WARN")
|
||||
config.set_session(session)
|
||||
|
||||
# ---- 解析运行参数 ----
|
||||
base_dir = (fields.get("base_dir") or "").strip() or config.DEFAULT_BASE_DIR
|
||||
config.set_base_dir(base_dir)
|
||||
config.set_ref_date(fields.get("ref_date") or "")
|
||||
cat_names = fields.get("categories") or []
|
||||
categories = [config.get_category(n) for n in cat_names] if cat_names else list(config.CATEGORIES)
|
||||
roster_path = (fields.get("roster_path") or "").strip()
|
||||
enable_validation = bool(fields.get("enable_validation", True))
|
||||
wps_recalc = bool(fields.get("wps_recalc", True))
|
||||
export_change_sheet = bool(fields.get("export_change_sheet", True))
|
||||
gen_import_files = bool(fields.get("gen_import_files", True))
|
||||
import_to_hr = bool(fields.get("import_to_hr", True))
|
||||
dingtalk_notify = bool(fields.get("dingtalk_notify", True))
|
||||
import_on = import_to_hr and gen_import_files
|
||||
if import_to_hr and not gen_import_files:
|
||||
ctx.log("已开启「自动导入HR系统」但「生成导入文件」未开启,本次无可导入文件,导入步骤将跳过", "WARN")
|
||||
|
||||
if not categories:
|
||||
raise ValueError("未选择任何类别")
|
||||
|
||||
notes: list = []
|
||||
ctx.log(f"===== 雇主险增减操作启动:业务日期 {config.today_date()},根目录 {base_dir} =====", "INFO")
|
||||
|
||||
# ---- 步骤1:花名册确保(5% ~ 10%) ----
|
||||
ctx.progress(5)
|
||||
try:
|
||||
roster_path = roster_filter.ensure_employee_file(roster_path, session)
|
||||
ctx.log(f"源表就绪:{roster_path}", "INFO")
|
||||
except Exception as e:
|
||||
notes.append(f"花名册准备失败(筛选复制与调度将受影响):{e}")
|
||||
ctx.log(f"花名册准备失败:{e}", "WARN")
|
||||
ctx.progress(10)
|
||||
|
||||
# ---- 步骤2:筛选复制(10% ~ 45%) ----
|
||||
ok_categories = []
|
||||
n = len(categories)
|
||||
for i, category in enumerate(categories):
|
||||
ctx.progress(10 + int(35 * i / n))
|
||||
try:
|
||||
roster_filter.filter_and_copy_roster(category, employee_path=roster_path)
|
||||
ok_categories.append(category)
|
||||
except Exception as e:
|
||||
notes.append(f"类别[{category['name']}] 筛选复制失败:{e}")
|
||||
ctx.log(f"类别[{category['name']}] 筛选复制失败:{e}", "WARN")
|
||||
ctx.progress(45)
|
||||
|
||||
# ---- 步骤3:WPS/Excel 后台重算公式(45% ~ 60%,替代人工 Ctrl+S) ----
|
||||
recalc_ok = {}
|
||||
if wps_recalc:
|
||||
for i, category in enumerate(ok_categories):
|
||||
ctx.progress(45 + int(15 * i / max(n, 1)))
|
||||
try:
|
||||
recalc_target(config.category_target_file(category))
|
||||
recalc_ok[category["name"]] = True
|
||||
except ComRecalcError as e:
|
||||
notes.append(f"类别[{category['name']}] 公式重算失败(跳过该类别调度):{e}")
|
||||
ctx.log(f"类别[{category['name']}] 公式重算失败:{e}", "WARN")
|
||||
# 重算失败的类别不进入调度(公式缓存缺失会导致读取不到工种类别/投保方案/方案处理)
|
||||
to_schedule = [c for c in ok_categories if recalc_ok.get(c["name"])]
|
||||
else:
|
||||
ctx.log("已关闭 WPS/Excel 后台重算:请确认目标文件公式已人工刷新(打开保存过),"
|
||||
"否则调度将读取不到公式计算结果", "WARN")
|
||||
to_schedule = ok_categories
|
||||
ctx.progress(60)
|
||||
|
||||
# ---- 步骤4:三阶段名额调度 ----
|
||||
# 进度边界:开启 HR 导入时压缩为 60~80(步骤5/6/7 依次 80~84 / 84~90 / 90~100),
|
||||
# 关闭时沿用原 60~88 / 88~95 / 95~100
|
||||
s4_end, s4_span = (80, 20) if import_on else (88, 28)
|
||||
s5_end, s5_span = (84, 4) if import_on else (95, 7)
|
||||
s6_end, s6_span = (90, 6) if import_on else (100, 5)
|
||||
scheduled = []
|
||||
for i, category in enumerate(to_schedule):
|
||||
ctx.progress(60 + int(s4_span * i / max(len(to_schedule), 1)))
|
||||
try:
|
||||
schedule.schedule_category(category,
|
||||
enable_validation=enable_validation,
|
||||
gen_import_files=gen_import_files)
|
||||
scheduled.append(category)
|
||||
except schedule.DataValidationError:
|
||||
ctx.log("数据校验失败,已中断后续类别调度,请修正数据后重试", "ERROR")
|
||||
raise
|
||||
except Exception as e:
|
||||
notes.append(f"类别[{category['name']}] 调度失败:{e}")
|
||||
ctx.log(f"类别[{category['name']}] 调度失败:{e}", "WARN")
|
||||
ctx.progress(s4_end)
|
||||
|
||||
# ---- 步骤5:再次重算公式(刷新变更清单/在参名单公式列缓存) ----
|
||||
if wps_recalc:
|
||||
for i, category in enumerate(scheduled):
|
||||
ctx.progress(s5_end - s5_span + int(s5_span * i / max(len(scheduled), 1)))
|
||||
try:
|
||||
recalc_target(config.category_target_file(category))
|
||||
except ComRecalcError as e:
|
||||
notes.append(f"类别[{category['name']}] 调度后重算失败(变更清单独立工作簿将取不到公式值):{e}")
|
||||
ctx.log(f"类别[{category['name']}] 调度后重算失败:{e}", "WARN")
|
||||
ctx.progress(s5_end)
|
||||
|
||||
# ---- 步骤6:导出变更清单独立工作簿 ----
|
||||
if export_change_sheet:
|
||||
for i, category in enumerate(scheduled):
|
||||
ctx.progress(s6_end - s6_span + int(s6_span * i / max(len(scheduled), 1)))
|
||||
try:
|
||||
output.export_change_sheet_workbook(category)
|
||||
except Exception as e:
|
||||
notes.append(f"类别[{category['name']}] 导出变更清单工作簿失败:{e}")
|
||||
ctx.log(f"类别[{category['name']}] 导出变更清单工作簿失败:{e}", "WARN")
|
||||
ctx.progress(s6_end)
|
||||
|
||||
# ---- 步骤7:HR 自动导入(90% ~ 100%,仅本次调度成功的类别;先全部减员再全部增员) ----
|
||||
import_results = []
|
||||
if import_on:
|
||||
if not scheduled:
|
||||
ctx.log("无调度成功的类别,跳过 HR 自动导入", "WARN")
|
||||
else:
|
||||
def _on_import_progress(done, total):
|
||||
ctx.progress(90 + int(10 * done / max(total, 1)))
|
||||
|
||||
ctx.log(f"开始 HR 自动导入:先全部【减员】后【增员】,共 {len(scheduled) * 2} 个导入单元")
|
||||
try:
|
||||
import_results = hr_import.import_all(scheduled, on_progress=_on_import_progress)
|
||||
except hr_import.LoginRequiredError as e:
|
||||
notes.append(f"HR 自动导入未执行(登录态缺失):{e}")
|
||||
ctx.log(f"HR 自动导入未执行:{e}", "ERROR")
|
||||
except Exception as e:
|
||||
notes.append(f"HR 自动导入整体失败:{e}")
|
||||
ctx.log(f"HR 自动导入整体失败:{e}", "ERROR")
|
||||
ctx.progress(100)
|
||||
|
||||
# ---- 汇总 ----
|
||||
detail = {
|
||||
"处理类别": len(categories),
|
||||
"筛选复制成功": len(ok_categories),
|
||||
"调度成功": len(scheduled),
|
||||
}
|
||||
import_lines = hr_import.summarize_results(import_results) \
|
||||
if import_on and import_results else []
|
||||
if import_on:
|
||||
import_text = ";".join(import_lines) if import_lines else "无导入结果"
|
||||
tail = ("增/减员导入文件与变更清单独立工作簿已生成在各类别文件夹。"
|
||||
f"HR 导入结果:{import_text}。")
|
||||
else:
|
||||
tail = ("增/减员导入文件与变更清单独立工作簿已生成在各类别文件夹,"
|
||||
"请先执行【减员】导入再执行【增员】导入。")
|
||||
summary = ("雇主险增减操作完成({date}):处理 {total} 个类别,筛选复制 {filtered} 个、"
|
||||
"调度成功 {scheduled} 个。{tail}").format(
|
||||
date=config.today_date(), total=len(categories),
|
||||
filtered=len(ok_categories), scheduled=len(scheduled), tail=tail)
|
||||
if notes:
|
||||
summary += "\n注意事项:\n- " + "\n- ".join(notes)
|
||||
|
||||
# ---- 步骤8:钉钉群通知(汇总 + 导入异常名单;失败不影响主流程) ----
|
||||
if dingtalk_notify:
|
||||
notify.push_run_result(total=len(categories), filtered=len(ok_categories),
|
||||
scheduled=len(scheduled), import_on=import_on,
|
||||
import_lines=import_lines,
|
||||
import_results=import_results, notes=notes)
|
||||
else:
|
||||
ctx.log("钉钉群通知已关闭,跳过推送", "INFO")
|
||||
|
||||
return {"summary": summary, "notes": notes, "detail": detail,
|
||||
"path": base_dir, "date": config.today_date()}
|
||||
|
||||
|
||||
PLUGINS.append(EmployerInsurancePlugin())
|
||||
@@ -1,408 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 雇主险增减操作 插件 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:本包只依赖 Python 标准库 / 第三方库 / 底座注入的 RunContext。
|
||||
业务模块统一经 config.log()/logger 输出日志、config.get_session()/get_user_id() 取登录态;
|
||||
运行参数(根目录 / 业务日期)由 __init__.py 的 run() 解析 fields 后注入(set_base_dir/set_ref_date)。
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
from datetime import date, datetime
|
||||
|
||||
# ==================== 共享目录(登录态/缓存,与影刀版同路径) ====================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
CACHE_DIR = os.path.join(_APP_DATA_DIR, 'cache')
|
||||
|
||||
# ==================== 钉钉群通知(report/notify.py 使用) ====================
|
||||
# prod=生产群 / dev=测试群(机器人 webhook 配置见 report/dingtalk_robot.py ENV_CONFIGS)
|
||||
DINGTALK_ENV = "prod"
|
||||
|
||||
# ==================== 默认根目录与业务日期(run() 注入覆盖) ====================
|
||||
DEFAULT_BASE_DIR = r"D:\资料\人资\雇主险"
|
||||
|
||||
# ==================== 固定 Sheet 名称 ====================
|
||||
SHEET_BIZ = "花名册导出-雇主险使用基础信息"
|
||||
SHEET_IN_PARAM = "手动维护-在参名单"
|
||||
|
||||
# ==================== 四大类别(合并调度/筛选口径,与 app 版 config 一致) ====================
|
||||
# 每类一个独立文件夹;include_dept/exclude_dept 用于筛选复制;
|
||||
# change_sheet_prefix 为各类「变更清单」sheet 名称前缀;scheme_suffix 为增员导入方案后缀。
|
||||
CATEGORIES = [
|
||||
{
|
||||
"name": "三十七度",
|
||||
"folder": os.path.join(DEFAULT_BASE_DIR, "三十七度"),
|
||||
"include_dept": [],
|
||||
"exclude_dept": ["金色湖畔事业部", "秒创传媒事业部", "水庄大鹅事业部"],
|
||||
"change_sheet_prefix": "37度-雇员变更清单",
|
||||
"scheme_suffix": "",
|
||||
},
|
||||
{
|
||||
"name": "水庄餐饮",
|
||||
"folder": os.path.join(DEFAULT_BASE_DIR, "水庄餐饮"),
|
||||
"include_dept": ["水庄大鹅事业部"],
|
||||
"exclude_dept": [],
|
||||
"change_sheet_prefix": "水庄-雇员变更清单",
|
||||
"scheme_suffix": "水庄",
|
||||
},
|
||||
{
|
||||
"name": "湖畔酒店",
|
||||
"folder": os.path.join(DEFAULT_BASE_DIR, "湖畔酒店"),
|
||||
"include_dept": ["金色湖畔事业部"],
|
||||
"exclude_dept": [],
|
||||
"change_sheet_prefix": "湖畔-雇员变更清单",
|
||||
"scheme_suffix": "湖畔",
|
||||
},
|
||||
{
|
||||
"name": "秒创传媒",
|
||||
"folder": os.path.join(DEFAULT_BASE_DIR, "秒创传媒"),
|
||||
"include_dept": ["秒创传媒事业部"],
|
||||
"exclude_dept": [],
|
||||
"change_sheet_prefix": "秒创-雇员变更清单",
|
||||
"scheme_suffix": "秒创",
|
||||
},
|
||||
]
|
||||
|
||||
# 过滤规则(与 aa.md 宏一致)
|
||||
EXCLUDE_REGIONS = ["虚拟大区"] # 统一排除的一级部门(各类别均生效)
|
||||
EXCLUDE_NAME_KEYWORDS = ["虚拟", "人资", "测试"] # 姓名(N列)含这些关键字的行剔除
|
||||
|
||||
# 源表/目标表格式规范(共享「37du花名册导出」输出统一格式)
|
||||
SOURCE_HEADER_MARK = "所属单位" # 源表表头定位标记(B列)
|
||||
EXPORT_TEMPLATE = "雇主险增减员导出模板" # 雇主险源表使用的自定义导出模板
|
||||
EXPORT_STATUSES = ["在职"]
|
||||
TARGET_HEADER_ROW = 4 # 目标表表头在第4行(数据第5行起)
|
||||
DATA_COLUMNS = 14 # B~O 共14列(所属单位..证件号)
|
||||
|
||||
# 数据切片(B~O)内 0-based 列索引
|
||||
CODE_COL = 4 # F列 工号(必须文本格式)
|
||||
JOIN_DATE_COL = 11 # M列 入职时间
|
||||
NAME_COL = 12 # N列 姓名
|
||||
ID_COL = 13 # O列 证件号(18位身份证号超出浮点精度,必须文本格式)
|
||||
|
||||
# ==================== 花名册列名映射(表头在第4行) ====================
|
||||
BIZ_COL_EMPLOYEE_ID = "证件号" # O列,员工唯一标识
|
||||
BIZ_COL_CATEGORY = "工种类别" # P列
|
||||
BIZ_COL_SCHEME = "投保方案" # Q列
|
||||
BIZ_COL_HANDLE = "方案处理" # W列,值: 增加投保 / 要替换 / /
|
||||
|
||||
# 在参名单数据起始行(第17行开始是数据区域,前16行是固定标题/兼职数据)
|
||||
DATA_START_ROW = 17
|
||||
|
||||
# ==================== 校验常量 ====================
|
||||
VALID_CATEGORIES = ["一类", "二类", "三类", "四类"]
|
||||
VALID_SCHEMES = ["人保-20万", "人保-50万", "人保-80万"]
|
||||
|
||||
# ==================== 增减员导入模板(雇主险根目录下官方模板) ====================
|
||||
ADD_IMPORT_TEMPLATE = "商业保险增员导入模板.xlsx"
|
||||
SUB_IMPORT_TEMPLATE = "商业保险减员导入模板.xlsx"
|
||||
|
||||
|
||||
# ==================== 运行参数钩子(run() 注入) ====================
|
||||
_base_dir = DEFAULT_BASE_DIR
|
||||
_ref_date = None # datetime.date;None 表示今天
|
||||
_log = None
|
||||
_session = None
|
||||
_user_id = ""
|
||||
|
||||
|
||||
def set_base_dir(path):
|
||||
global _base_dir
|
||||
_base_dir = (path or "").strip().strip('"') or DEFAULT_BASE_DIR
|
||||
|
||||
|
||||
def get_base_dir():
|
||||
return _base_dir
|
||||
|
||||
|
||||
def parse_ref_date(value):
|
||||
"""把 fields.ref_date(YYYY-MM-DD / YYYY.M.D 等)解析为 date;空返回今天。"""
|
||||
if not value:
|
||||
return date.today()
|
||||
s = str(value).strip()
|
||||
m = re.match(r"(\d{4})[-./年](\d{1,2})[-./月](\d{1,2})", s)
|
||||
if m:
|
||||
try:
|
||||
return date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
||||
except ValueError:
|
||||
pass
|
||||
return date.today()
|
||||
|
||||
|
||||
def set_ref_date(value):
|
||||
global _ref_date
|
||||
_ref_date = parse_ref_date(value)
|
||||
|
||||
|
||||
def ref_date():
|
||||
"""业务日期(默认今天)。"""
|
||||
return _ref_date or date.today()
|
||||
|
||||
|
||||
def date_str():
|
||||
"""YYYY.M.D(目标表/备份文件名,如 2026.9.22)。"""
|
||||
return ref_date().strftime("%Y.%m.%d")
|
||||
|
||||
|
||||
def date_short():
|
||||
"""M.D(变更清单 sheet 后缀,不补前导零,如 9.22 / 9.1)。"""
|
||||
return f"{ref_date().month}.{ref_date().day}"
|
||||
|
||||
|
||||
def today_date():
|
||||
"""YYYY-MM-DD(批改日期/增员减员日期/投保日期)。"""
|
||||
return ref_date().strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ==================== 类别辅助函数 ====================
|
||||
def get_category(name):
|
||||
"""按名称获取类别配置(支持精确名或唯一前缀,如「湖畔」/「湖畔酒店」)。"""
|
||||
name = (name or "").strip()
|
||||
for c in CATEGORIES:
|
||||
if c["name"] == name:
|
||||
return c
|
||||
matched = [c for c in CATEGORIES if c["name"].startswith(name)]
|
||||
if len(matched) == 1:
|
||||
return matched[0]
|
||||
raise ValueError(f"未知类别:{name},可选:{[c['name'] for c in CATEGORIES]}")
|
||||
|
||||
|
||||
def _target_file_date(filename):
|
||||
"""从目标文件名解析业务日期(优先 YYYY.M.D,回退 M.D 当年)。"""
|
||||
m = re.search(r"(\d{4})\.(\d{1,2})\.(\d{1,2})", filename)
|
||||
if m:
|
||||
try:
|
||||
return date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
||||
except ValueError:
|
||||
return None
|
||||
m = re.search(r"(\d{1,2})\.(\d{1,2})", filename)
|
||||
if m:
|
||||
try:
|
||||
return date(ref_date().year, int(m.group(1)), int(m.group(2)))
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def find_latest_target(folder):
|
||||
"""在类别文件夹中定位最新的「*雇主险变更记录*.xlsx」目标文件。
|
||||
|
||||
按「文件名中的业务日期」选择最新(不依赖修改时间),避免昨日文件被改动/
|
||||
打开导致 mtime 更新而被误当成今日文件(曾因此把变更清单写进昨日文件)。
|
||||
"""
|
||||
if not os.path.isdir(folder):
|
||||
raise FileNotFoundError(f"类别文件夹不存在:{folder}")
|
||||
candidates = [
|
||||
os.path.join(folder, f)
|
||||
for f in os.listdir(folder)
|
||||
if f.lower().endswith(".xlsx") and "雇主险变更记录" in f
|
||||
]
|
||||
if not candidates:
|
||||
raise FileNotFoundError(
|
||||
f"文件夹 {folder} 下未找到「*雇主险变更记录*.xlsx」文件,请先准备今日的雇主险变更记录模板")
|
||||
# 排序键:业务日期优先,同日期内再按修改时间兜底
|
||||
def _sort_key(path):
|
||||
return (_target_file_date(os.path.basename(path)) or date.min,
|
||||
os.path.getmtime(path))
|
||||
return max(candidates, key=_sort_key)
|
||||
|
||||
|
||||
def _category_dir(category):
|
||||
"""类别文件夹(base_dir 运行时可能被覆盖,须实时拼接而非 import 时固化)。"""
|
||||
return os.path.join(get_base_dir(), category["name"])
|
||||
|
||||
|
||||
def category_folder(category):
|
||||
return _category_dir(category)
|
||||
|
||||
|
||||
def category_target_file(category):
|
||||
"""类别目标文件(各文件夹内最新的雇主险变更记录)。"""
|
||||
return find_latest_target(_category_dir(category))
|
||||
|
||||
|
||||
def category_output_backup(category):
|
||||
"""类别「新在参名单」备份路径(放在类别文件夹内)。"""
|
||||
return os.path.join(_category_dir(category), f"新在参名单-{date_str()}.xlsx")
|
||||
|
||||
|
||||
def category_change_sheet_workbook(category):
|
||||
"""类别「雇员变更清单」独立工作簿路径(放在类别文件夹内)。"""
|
||||
return os.path.join(_category_dir(category), f"{category['name']}-雇员变更清单-{date_str()}.xlsx")
|
||||
|
||||
|
||||
def category_change_sheet_name(category):
|
||||
"""类别「变更清单」sheet 名称(沿用历史模板命名:无横线、不补前导零)。"""
|
||||
return f"{category['change_sheet_prefix']}{date_short()}"
|
||||
|
||||
|
||||
def category_import_add_file(category):
|
||||
"""类别「增员导入」文件路径(放在类别文件夹内)。"""
|
||||
return os.path.join(_category_dir(category), "商业保险增员导入.xlsx")
|
||||
|
||||
|
||||
def category_import_sub_file(category):
|
||||
"""类别「减员导入」文件路径(放在类别文件夹内)。"""
|
||||
return os.path.join(_category_dir(category), "商业保险减员导入.xlsx")
|
||||
|
||||
|
||||
def add_import_template():
|
||||
return os.path.join(get_base_dir(), ADD_IMPORT_TEMPLATE)
|
||||
|
||||
|
||||
def sub_import_template():
|
||||
return os.path.join(get_base_dir(), SUB_IMPORT_TEMPLATE)
|
||||
|
||||
|
||||
def employee_file(path=""):
|
||||
"""花名册路径:传入优先,否则 {base_dir}\\员工花名册.xlsx。"""
|
||||
return (path or "").strip() or os.path.join(get_base_dir(), "员工花名册.xlsx")
|
||||
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
def set_log(fn):
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def log(msg, level="INFO"):
|
||||
if _log:
|
||||
_log(str(msg), level)
|
||||
else:
|
||||
print(f"[{level}] {msg}")
|
||||
|
||||
|
||||
class _ModuleLogger:
|
||||
"""模块级 logger 适配:保留影刀版 logger.info(...) 调用点,统一转发到 ctx.log。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "DEBUG")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "INFO")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "WARN")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "ERROR")
|
||||
|
||||
|
||||
logger = _ModuleLogger()
|
||||
|
||||
|
||||
def set_session(session):
|
||||
global _session
|
||||
_session = session
|
||||
|
||||
|
||||
def get_session():
|
||||
return _session
|
||||
|
||||
|
||||
def require_session():
|
||||
"""取插件运行期注入的 HR session(缺失抛错,提示先在插件界面登录 HR)。"""
|
||||
if _session is None:
|
||||
raise RuntimeError("未注入 HR 登录态,请先在插件界面完成 HR 登录")
|
||||
return _session
|
||||
|
||||
|
||||
def set_user_id(uid):
|
||||
global _user_id
|
||||
_user_id = str(uid or "")
|
||||
|
||||
|
||||
def get_user_id():
|
||||
return _user_id
|
||||
|
||||
|
||||
# ==================== 文本/日期辅助函数(logic/report 层共用) ====================
|
||||
def to_text(value):
|
||||
"""将工号等主键值统一转为文本,避免数字/文本混存导致 Excel 公式匹配失败。
|
||||
|
||||
整型 float(如 10086.0)去掉小数点后转 str,保证与文本工号(如"10086")一致。
|
||||
"""
|
||||
import numbers
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
if value != value: # NaN
|
||||
return None
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if isinstance(value, numbers.Integral):
|
||||
return str(int(value))
|
||||
if isinstance(value, numbers.Real):
|
||||
f = float(value)
|
||||
if f.is_integer():
|
||||
return str(int(f))
|
||||
return str(value)
|
||||
|
||||
|
||||
def clean_text(value):
|
||||
"""转可写文本;None/NaN/空白返回 None。"""
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
if value != value: # NaN
|
||||
return None
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
s = str(value).strip()
|
||||
return s or None
|
||||
|
||||
|
||||
def parse_join_date(value):
|
||||
"""解析入职时间为 date 对象(兼容 datetime/字符串「YYYY-MM-DD」「YYYY.M.D」等)。"""
|
||||
from datetime import datetime as _dt
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
if value != value: # NaN
|
||||
return None
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if isinstance(value, datetime):
|
||||
return value.date()
|
||||
s = str(value).strip()
|
||||
m = re.match(r"(\d{4})[.\-/年](\d{1,2})[.\-/月](\d{1,2})", s)
|
||||
if m:
|
||||
try:
|
||||
return _dt(int(m.group(1)), int(m.group(2)), int(m.group(3))).date()
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def to_date(value):
|
||||
"""将日期/日期字符串统一转为 date 对象;无法解析时返回 None。"""
|
||||
from datetime import datetime as _dt
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, datetime):
|
||||
return value.date()
|
||||
if isinstance(value, date):
|
||||
return value
|
||||
s = str(value).strip()
|
||||
if not s:
|
||||
return None
|
||||
for fmt in ("%Y-%m-%d", "%Y/%m/%d", "%Y.%m.%d"):
|
||||
try:
|
||||
return _dt.strptime(s, fmt).date()
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
@@ -1,2 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 data 层:花名册导出(接口版)。"""
|
||||
@@ -1,453 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - 员工花名册导出(接口版,由 xq0011 插件同模块内嵌移植)。
|
||||
|
||||
纯接口版(无需浏览器):访问台账页面绑定会话 -> ws/bridge 注册 -> WebSocket 订阅主题 ->
|
||||
POST exportCommonListData 异步导出(服务端生成 Excel 并翻译全部字典字段)-> 接收 "--end--|文件路径" 推送
|
||||
-> 下载临时文件 -> 按状态合并(追加「类型」列)。
|
||||
|
||||
插件化改造点:
|
||||
1. HR 会话优先用底座注入的 session(调用方传入),未传时兜底读共享 cookies 文件;
|
||||
2. 内置「雇主险增减员导出模板」(B~O 共 14 列:所属单位→证件号,与 app 版 roster_template 一致);
|
||||
3. 日志统一转发到 config.logger。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.parse
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
import requests
|
||||
import pandas as pd
|
||||
import websocket # websocket-client
|
||||
|
||||
from ..config import logger, SESSIONS_DIR, EXPORT_TEMPLATE, EXPORT_STATUSES
|
||||
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- 员工花名册查询/导出接口(与 app 版 ehr/common/hr_api 一致) ----------
|
||||
ROSTER_ID = "1116da64-b094-11ea-b588-14187743d052"
|
||||
ROSTER_PAGE_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{ROSTER_ID}/getCustomCommonList.mc"
|
||||
ROSTER_EXPORT_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{ROSTER_ID}/exportCommonListData.mc"
|
||||
BRIDGE_URL = "https://hr.37du.co/RedseaPlatform/ws/bridge"
|
||||
TEMPLATE_LIST_URL = ("https://hr.37du.co/RedseaPlatform/redmagicapi/"
|
||||
"rf_pt_users_export_define_select/getExecuteResult.mc")
|
||||
TEMPLATE_DETAIL_URL = "https://hr.37du.co/RedseaPlatform/ptUsersExportDefine/getPtusersexportdefine.mc"
|
||||
WS_EXPORT_THEME = "HR_DEFINED_HMC_EXPORT"
|
||||
WS_SERVICE_URL = "wss://hr.37du.co/RedseaPlatform/ws/service?theme=" + WS_EXPORT_THEME
|
||||
XHR_HEADERS = {"X-Requested-With": "XMLHttpRequest"}
|
||||
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36"
|
||||
|
||||
# 花名册查询固定入参(从浏览器抓包提取)
|
||||
ROSTER_QUERY_BASE_PARAMS = {
|
||||
"menuName": "员工花名册",
|
||||
"useSealTreeData": "0",
|
||||
"treePermitType": "permit",
|
||||
"cancelNodeClick": "1",
|
||||
"clickFlag": "true",
|
||||
"in_use": "1",
|
||||
"commonQuery": "",
|
||||
"newCondition": "",
|
||||
"urlConditions": "",
|
||||
"exportConfig": "",
|
||||
"tableId": "assemble-hr_staff_base",
|
||||
"rosterId": ROSTER_ID,
|
||||
"includeChildrenSetting": "",
|
||||
"struTreeCode": "cq37du",
|
||||
"djStruTreeCode": "",
|
||||
"djStruId": "",
|
||||
"djOrgName": "",
|
||||
"struId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"belongUnitStruId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"rootId": "cq37du",
|
||||
"isVirtual": "0",
|
||||
"currentUserRootId": "cq37du",
|
||||
"currentUserId": "178b0efa-8a65-11f1-a7d9-000c296f9469",
|
||||
"currentRoleIds": "POST_SYS_ADMIN,renshi",
|
||||
"currentStaffId": "1342173e-36cf-4160-8826-6b17d7d084a4",
|
||||
"baseHrefPath": "http:hr.37du.co:80RedseaPlatform",
|
||||
"qrCodeUrl": "jspresumepage-01.jsp",
|
||||
"orgName": "集团",
|
||||
"belongUnitOrgName": "集团",
|
||||
"throughParam": "",
|
||||
"start": "0",
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": "1",
|
||||
"pageSize": "15",
|
||||
"dataIds": "",
|
||||
"hideCols": "",
|
||||
}
|
||||
|
||||
# ---------- 自定义导出模板(exportFilters 字段串,顺序与页面导出模板列一致) ----------
|
||||
# 「雇主险增减员导出模板」(14 列 + 序号,B~O:所属单位→证件号,与 app 版 roster_template 一致)
|
||||
ROSTER_TEMPLATE_FILTERS_EMPLOYER = ",".join([
|
||||
"pt_staff_stru.BELONG_UNIT_ORG_NAME", # 所属单位
|
||||
"pt_staff_stru.DEPT_ORG_ONE", # 一级部门
|
||||
"pt_staff_stru.DEPT_ORG_TWO", # 二级部门
|
||||
"pt_staff_stru.DEPT_ORG_FOUR", # 四级部门
|
||||
"hr_staff_base.base_code", # 工号
|
||||
"hr_staff_base.age", # 年龄
|
||||
"hr_staff_base.sex", # 性别
|
||||
"pt_staff_stru.POST_ORG_NAME", # 岗位
|
||||
"pt_staff_stru.first_type_id", # 职位序列
|
||||
"hr_staff_base_ext.ext_insurance_type", # 参保类型
|
||||
"hr_staff_base_ext.ext_trans_type", # 上下班交通方式
|
||||
"hr_staff_base.join_date", # 入职时间
|
||||
"hr_staff_base.staff_name", # 姓名
|
||||
"hr_staff_base.idCard", # 证件号
|
||||
])
|
||||
|
||||
ROSTER_TEMPLATE_FILTERS = {
|
||||
"雇主险增减员导出模板": ROSTER_TEMPLATE_FILTERS_EMPLOYER,
|
||||
}
|
||||
|
||||
# ---------- 默认导出参数 ----------
|
||||
DEFAULT_TEMPLATE = EXPORT_TEMPLATE # 雇主险增减员导出模板
|
||||
DEFAULT_STATUSES = list(EXPORT_STATUSES) # ["在职"]
|
||||
DEFAULT_TTL_SECONDS = 15 * 60 # 缓存有效期(秒)
|
||||
EXPORT_TIMEOUT_SECONDS = 300 # 异步导出等待超时(秒)
|
||||
MAX_ATTEMPTS = 3 # 项目级重试次数
|
||||
|
||||
|
||||
class LoginRequiredError(Exception):
|
||||
"""HR 登录态缺失或失效(接口返回登录页等非 JSON 内容)。"""
|
||||
|
||||
|
||||
# ==================== commonQuery 前端加密(自实现,与前端行为一致,已实测接口可用) ====================
|
||||
_CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
|
||||
_SALT = "yyryrtweasdasd" # 固定盐值
|
||||
|
||||
|
||||
def _custom_base64_encode(data):
|
||||
"""使用自定义字符表进行 Base64 编码(data 为 UTF-8 字节序列)。"""
|
||||
result = []
|
||||
for i in range(0, len(data), 3):
|
||||
chunk = data[i:i + 3]
|
||||
b1 = chunk[0] if len(chunk) > 0 else 0
|
||||
b2 = chunk[1] if len(chunk) > 1 else 0
|
||||
b3 = chunk[2] if len(chunk) > 2 else 0
|
||||
|
||||
enc1 = (b1 >> 2) & 0x3F
|
||||
enc2 = ((b1 << 4) | (b2 >> 4)) & 0x3F
|
||||
enc3 = ((b2 << 2) | (b3 >> 6)) & 0x3F
|
||||
enc4 = b3 & 0x3F
|
||||
|
||||
if len(chunk) == 1:
|
||||
enc3 = 64
|
||||
enc4 = 64
|
||||
elif len(chunk) == 2:
|
||||
enc4 = 64
|
||||
|
||||
result.append(_CUSTOM_CHARS[enc1])
|
||||
result.append(_CUSTOM_CHARS[enc2])
|
||||
result.append(_CUSTOM_CHARS[enc3])
|
||||
result.append(_CUSTOM_CHARS[enc4])
|
||||
return ''.join(result)
|
||||
|
||||
|
||||
def build_condition(query_field, query_type, query_value, query_text="",
|
||||
left_bracket="", right_bracket="", logic="AND", input_type="text"):
|
||||
"""构造一个符合前端格式的单条查询条件字典。"""
|
||||
return {
|
||||
"queryField": query_field,
|
||||
"leftBracket": left_bracket,
|
||||
"queryType": query_type,
|
||||
"queryValue": query_value,
|
||||
"queryText": query_text,
|
||||
"rightBracket": right_bracket,
|
||||
"logic": logic,
|
||||
"inputType": input_type,
|
||||
}
|
||||
|
||||
|
||||
def encode_common_query(query_list):
|
||||
"""将查询条件列表加密为 commonQuery 字符串(encodeURIComponent + 自定义 Base64 + 盐值 + 首尾重排)。"""
|
||||
json_str = json.dumps(query_list, ensure_ascii=False, separators=(',', ':'))
|
||||
uri_encoded = urllib.parse.quote(json_str, safe="-_.~!*'()")
|
||||
en_str = _custom_base64_encode(uri_encoded.encode('utf-8')) + _SALT
|
||||
return en_str[:2] + en_str[-3:] + en_str[2:-3]
|
||||
|
||||
|
||||
# ==================== 登录态(底座注入优先,兜底共享 cookies) ====================
|
||||
def _build_session(session=None):
|
||||
"""取 HR 会话:优先用调用方(底座注入)传入的 session,否则读共享 cookies 构建。"""
|
||||
if session is not None:
|
||||
return session
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
raise LoginRequiredError(
|
||||
"未找到 HR 登录态 cookies,请先在插件界面完成 HR 登录后再重试。")
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": USER_AGENT,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies or []:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
# ==================== 动态日期参数 ====================
|
||||
def get_date_params():
|
||||
"""生成花名册查询所需的动态日期参数(当月 / 上月 / 当年首月)。"""
|
||||
now = datetime.now()
|
||||
year, month, day = now.year, now.month, now.day
|
||||
last_month_date = datetime(year, month, 1) - timedelta(days=1)
|
||||
return {
|
||||
"currentDate": f"{year}-{month:02d}-{day:02d}",
|
||||
"currentMonth": f"{year}{month:02d}",
|
||||
"currentMonthBar": f"{year}-{month:02d}",
|
||||
"lastMonth": f"{last_month_date.year}{last_month_date.month:02d}",
|
||||
"lastMonFirstDay": f"{last_month_date.year}-{last_month_date.month:02d}-01",
|
||||
"lastMonLastDay": last_month_date.strftime("%Y-%m-%d"),
|
||||
"curYearFirstMon": f"{year}01",
|
||||
"curYearFirstMonBar": f"{year}-01",
|
||||
}
|
||||
|
||||
|
||||
def _get_leave_range(today=None):
|
||||
"""计算离职筛选时间范围:默认上月 1 日到今天(离职时间不传时使用)。"""
|
||||
today = today or date.today()
|
||||
last_month_end = today.replace(day=1) - timedelta(days=1)
|
||||
start = last_month_end.replace(day=1)
|
||||
return start.strftime("%Y-%m-%d"), today.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ==================== 查询条件构造 ====================
|
||||
def _build_in_service_conditions():
|
||||
return [
|
||||
build_condition("`pt_staff_stru.POST_STRU_ID`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="select"),
|
||||
build_condition("`hr_staff_base.person_status`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="multipleSelect"),
|
||||
]
|
||||
|
||||
|
||||
def _build_leave_conditions(leave_start, leave_end):
|
||||
return [
|
||||
build_condition("`pt_staff_stru.POST_STRU_ID`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="select"),
|
||||
build_condition("`hr_staff_base.person_status`", "in", "2",
|
||||
query_text="2", left_bracket="(", right_bracket=")",
|
||||
input_type="multipleSelect"),
|
||||
build_condition("`hr_staff_base.leaveOffice_date`", ">=", leave_start,
|
||||
left_bracket="(", input_type="date"),
|
||||
build_condition("`hr_staff_base.leaveOffice_date`", "<=", leave_end,
|
||||
right_bracket=")", input_type="date"),
|
||||
]
|
||||
|
||||
|
||||
# ==================== 自定义导出模板动态解析 ====================
|
||||
def resolve_template_filters(session, template_name):
|
||||
"""按模板名动态解析 exportFilters 字段串(失败回退内置模板)。"""
|
||||
try:
|
||||
r = session.post(TEMPLATE_LIST_URL, headers=XHR_HEADERS, timeout=15).json()
|
||||
templates = r.get("jsonList") or []
|
||||
target = next((t for t in templates if t.get("ext1") == template_name), None)
|
||||
if not target:
|
||||
logger.warning("模板列表中未找到「%s」,回退内置模板", template_name)
|
||||
return None
|
||||
r2 = session.post(TEMPLATE_DETAIL_URL, headers=XHR_HEADERS,
|
||||
data={"rosterId": ROSTER_ID, "id": target["id"]}, timeout=15).json()
|
||||
export_field = (r2.get("result") or {}).get("exportField") or ""
|
||||
fields = json.loads(export_field)
|
||||
if not fields:
|
||||
logger.warning("模板「%s」详情无 exportField,回退内置模板", template_name)
|
||||
return None
|
||||
filters = ",".join(f["tableCode"] for f in fields)
|
||||
logger.info("模板「%s」动态解析成功(%d 列)", template_name, len(fields))
|
||||
return filters
|
||||
except Exception as e:
|
||||
logger.warning("模板「%s」动态解析失败:%s,回退内置模板", template_name, e)
|
||||
return None
|
||||
|
||||
|
||||
# ==================== WebSocket 异步导出(单状态) ====================
|
||||
def _bind_session(session):
|
||||
"""绑定会话:先访问台账页面,再调用 ws/bridge 注册 HTTP 会话到 WS 容器。"""
|
||||
session.get(ROSTER_PAGE_URL, params={"clickFlag": "true", "treePermitType": "permit",
|
||||
"useSealTreeData": "0"}, timeout=30)
|
||||
r = session.post(BRIDGE_URL, data={}, headers=XHR_HEADERS, timeout=10)
|
||||
if "成功" not in r.text and r.text.strip() != "1":
|
||||
raise LoginRequiredError(
|
||||
f"ws/bridge 会话注册失败(登录态可能已失效):{r.text[:100]}。"
|
||||
"请先在插件界面重新完成 HR 登录后再重试。")
|
||||
|
||||
|
||||
def _export_one_status_once(session, status, download_dir, template_name,
|
||||
leave_start=None, leave_end=None, export_filters=None):
|
||||
"""单个在职状态的异步导出(单次尝试):提交任务 -> WS 收 --end-- -> 下载临时文件。"""
|
||||
_bind_session(session)
|
||||
cookie_hdr = "; ".join(f"{c.name}={c.value}" for c in session.cookies
|
||||
if "hr.37du.co" in (c.domain or ""))
|
||||
ws = websocket.WebSocket()
|
||||
ws.connect(WS_SERVICE_URL, header=[
|
||||
f"Cookie: {cookie_hdr}",
|
||||
"Origin: https://hr.37du.co",
|
||||
f"User-Agent: {USER_AGENT}",
|
||||
], timeout=10)
|
||||
try:
|
||||
ws.send(json.dumps({"theme": WS_EXPORT_THEME, "code": "SUBCRIBE_THEME"}))
|
||||
ack = json.loads(ws.recv())
|
||||
if ack.get("code") != "SUBCRIBE_THEME_ACK":
|
||||
raise RuntimeError(f"WS 订阅失败:{str(ack)[:100]}")
|
||||
logger.info("WS 订阅成功(%s)", WS_EXPORT_THEME)
|
||||
|
||||
params = {k: str(v) for k, v in ROSTER_QUERY_BASE_PARAMS.items()}
|
||||
if status == "离职":
|
||||
ls = leave_start or ""
|
||||
le = leave_end or ""
|
||||
if not ls or not le:
|
||||
ls, le = _get_leave_range()
|
||||
params["commonQuery"] = encode_common_query(_build_leave_conditions(ls, le))
|
||||
logger.info("离职时间范围:%s ~ %s", ls, le)
|
||||
else:
|
||||
params["commonQuery"] = encode_common_query(_build_in_service_conditions())
|
||||
params.update(get_date_params())
|
||||
params["exportConfig"] = json.dumps(
|
||||
{"exportName": template_name,
|
||||
"exportFilters": export_filters or ROSTER_TEMPLATE_FILTERS.get(template_name, "")},
|
||||
ensure_ascii=False, separators=(",", ":"))
|
||||
params["_t"] = str(int(time.time() * 1000))
|
||||
|
||||
resp = session.post(ROSTER_EXPORT_URL, data=params, headers=XHR_HEADERS, timeout=30)
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"提交导出任务失败:HTTP {resp.status_code}")
|
||||
logger.info("导出任务已提交(状态:%s,模板:%s)", status, template_name)
|
||||
|
||||
file_url = None
|
||||
deadline = time.time() + EXPORT_TIMEOUT_SECONDS
|
||||
ws.settimeout(EXPORT_TIMEOUT_SECONDS)
|
||||
while time.time() < deadline:
|
||||
msg = json.loads(ws.recv())
|
||||
txt, code = msg.get("txt", ""), msg.get("code", "")
|
||||
if code != "NORMAL_PUSH_TO":
|
||||
continue
|
||||
if txt.startswith("--end--"):
|
||||
file_url = txt.split("|", 1)[1].strip()
|
||||
break
|
||||
if txt.startswith(("开始下载", "正在生成")):
|
||||
logger.info(" 进度:%s", txt)
|
||||
if not file_url:
|
||||
raise RuntimeError(f"等待导出文件超时({EXPORT_TIMEOUT_SECONDS}s)")
|
||||
logger.info("导出完成,文件地址:%s", file_url)
|
||||
finally:
|
||||
ws.close()
|
||||
|
||||
dl_url = "https://hr.37du.co" + file_url if file_url.startswith("/") else file_url
|
||||
dl = session.get(dl_url, timeout=120)
|
||||
if dl.status_code != 200 or not dl.content:
|
||||
raise RuntimeError(f"下载导出文件失败:HTTP {dl.status_code},{len(dl.content)} 字节")
|
||||
os.makedirs(download_dir, exist_ok=True)
|
||||
temp_path = os.path.join(download_dir, f"花名册_{status}_{int(time.time())}.xlsx")
|
||||
with open(temp_path, "wb") as f:
|
||||
f.write(dl.content)
|
||||
logger.info("已下载临时文件:%s(%d 字节)", temp_path, len(dl.content))
|
||||
return temp_path
|
||||
|
||||
|
||||
def _export_one_status(session, status, download_dir, template_name,
|
||||
leave_start=None, leave_end=None, export_filters=None):
|
||||
"""导出单个在职状态的花名册(项目级重试:最大 3 次,登录态失效不重试直接抛出)。"""
|
||||
last_exc = None
|
||||
for attempt in range(1, MAX_ATTEMPTS + 1):
|
||||
try:
|
||||
return _export_one_status_once(session, status, download_dir, template_name,
|
||||
leave_start, leave_end, export_filters)
|
||||
except LoginRequiredError:
|
||||
raise # 确定性失败,不重试
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt >= MAX_ATTEMPTS:
|
||||
break
|
||||
delay = 2.0 * attempt
|
||||
logger.warning("导出在职状态「%s」第 %d 次失败:%s,%.1f 秒后重试",
|
||||
status, attempt, e, delay)
|
||||
time.sleep(delay)
|
||||
logger.error("导出在职状态「%s」连续 %d 次失败,放弃", status, MAX_ATTEMPTS)
|
||||
raise last_exc
|
||||
|
||||
|
||||
# ==================== 合并输出 ====================
|
||||
def _normalize_and_save(files_with_status, output_path):
|
||||
"""合并多个花名册 Excel 文件,添加「类型」列标识在职状态。
|
||||
|
||||
统一输出格式:只保留第2行表头,丢弃第1行标题;「类型」列追加在最后一列;
|
||||
单 sheet,表头在第1行,数据第2行起。
|
||||
"""
|
||||
dfs = []
|
||||
for status, path in files_with_status:
|
||||
df = pd.read_excel(path, header=1) # 取第2行作表头,丢弃第1行标题
|
||||
df["类型"] = status
|
||||
dfs.append(df)
|
||||
logger.info("读取花名册文件:%s(%s,%d 行)", path, status, len(df))
|
||||
merged = pd.concat(dfs, ignore_index=True)
|
||||
out_dir = os.path.dirname(output_path)
|
||||
if out_dir:
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
merged.to_excel(output_path, index=False)
|
||||
logger.info("合并完成,共 %d 行,已保存:%s", len(merged), output_path)
|
||||
for _, path in files_with_status:
|
||||
try:
|
||||
os.remove(path)
|
||||
except Exception:
|
||||
pass
|
||||
return output_path
|
||||
|
||||
|
||||
# ==================== 导出主流程 ====================
|
||||
def export_roster(download_dir=None, output_path=None, template_name=None,
|
||||
statuses=None, leave_start=None, leave_end=None,
|
||||
ttl=DEFAULT_TTL_SECONDS, session=None):
|
||||
"""执行员工花名册自定义导出(按需在职状态,各导一次),合并为一个 Excel 文件。
|
||||
|
||||
带 TTL 缓存:output_path 已有且距上次导出不超过 ttl 秒时直接复用(跳过接口导出)。
|
||||
|
||||
Args:
|
||||
session: 底座注入的 HR 会话(优先);None 时兜底读共享 cookies。
|
||||
其余参数与影刀版 export_roster 一致。
|
||||
|
||||
Returns:
|
||||
合并后的花名册文件路径
|
||||
"""
|
||||
download_dir = download_dir or os.path.dirname(output_path or "") or "."
|
||||
output_path = output_path or "花名册.xlsx"
|
||||
template_name = template_name or DEFAULT_TEMPLATE
|
||||
statuses = list(statuses) if statuses else list(DEFAULT_STATUSES)
|
||||
if ttl is None:
|
||||
ttl = DEFAULT_TTL_SECONDS
|
||||
|
||||
# TTL 缓存:输出路径已有、非空且距上次导出不超过 ttl 秒时直接复用
|
||||
if ttl > 0 and os.path.exists(output_path) \
|
||||
and os.path.getsize(output_path) > 0 \
|
||||
and time.time() - os.path.getmtime(output_path) <= ttl:
|
||||
logger.info("花名册缓存命中(%.0f 分钟内已导出,直接复用):%s", ttl / 60.0, output_path)
|
||||
return output_path
|
||||
|
||||
leave_desc = ""
|
||||
if "离职" in statuses:
|
||||
ls, le = leave_start or "", leave_end or ""
|
||||
if not ls or not le:
|
||||
ls, le = _get_leave_range()
|
||||
leave_desc = f",离职时间 {ls} ~ {le}"
|
||||
logger.info("===== 开始花名册导出(模板:%s,在职状态:%s%s) =====",
|
||||
template_name, statuses, leave_desc)
|
||||
|
||||
session = _build_session(session)
|
||||
export_filters = resolve_template_filters(session, template_name)
|
||||
|
||||
files_with_status = []
|
||||
for status in statuses:
|
||||
logger.info("===== 开始导出在职状态:%s =====", status)
|
||||
path = _export_one_status(session, status, download_dir, template_name,
|
||||
leave_start, leave_end, export_filters)
|
||||
files_with_status.append((status, path))
|
||||
|
||||
result = _normalize_and_save(files_with_status, output_path)
|
||||
logger.info("===== 花名册导出并合并完成:%s =====", result)
|
||||
return result
|
||||
@@ -1,2 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 logic 层:筛选复制 + 三阶段名额调度 + WPS/Excel 重算。"""
|
||||
@@ -1,658 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - HR「待增减人员」增减员导入(浏览器自动化,移植影刀版 add_sub_import v1.8.0)。
|
||||
|
||||
流程:访问待增减人员页面 -> 更多操作 -> 减员/增员导入 -> 上传文件 -> 下一步(格式校验)
|
||||
-> 下一步(真正导入)-> 关闭;监听 getTmpDataPage.mc 捕获逐行导入结果。
|
||||
|
||||
插件化改造点(相对影刀版):
|
||||
1. 登录态:优先底座注入 session(config.get_session())的 cookies 注入浏览器,
|
||||
未注入/为空时兜底读共享 cookies 文件(hr_cookies.json);
|
||||
2. 导入文件路径经 config.category_import_add_file / category_import_sub_file 实时解析
|
||||
(base_dir 由 run() 注入,不依赖类别配置里的固化 folder);
|
||||
3. 一次运行共用一个浏览器:先全部类别【减员】再全部类别【增员】
|
||||
(替换/修改人员必须先撤旧方案再上新方案,先增员会方案冲突报错);
|
||||
4. 日志统一转发 config.logger;结果 dict 返回,由 __init__.py 汇总进 summary/notes。
|
||||
|
||||
关键语义(与影刀版一致,勿改):
|
||||
- getTmpDataPage.mc 仅在存在异常行时才返回逐行结果:全部成功时 HR 不调用结果接口,
|
||||
流程完整走完(两步「下一步」+「关闭」)且监听正常、未捕获异常行 -> 按文件条数推定全部成功;
|
||||
- 接口每页固定 15 条,弹窗只加载第一页:捕获首响应后按 pageNo 主动翻页拉全;
|
||||
- 需导入条数从导入文件 A 列最大序号统计(模板预格式化空白行不计);
|
||||
- 上传/校验/确认走 UI 控件(input[name=file] 设置路径跳过系统文件选择框)。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
|
||||
import requests
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from ..config import logger, SESSIONS_DIR, get_session
|
||||
|
||||
try:
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
_DRP_AVAILABLE = True
|
||||
_DRP_IMPORT_ERROR = None
|
||||
except ImportError as _e: # 模块可安全导入(开关关闭时不触发),使用时再报清晰错误
|
||||
_DRP_AVAILABLE = False
|
||||
_DRP_IMPORT_ERROR = _e
|
||||
|
||||
# ==================== 常量(与影刀版 add_sub_import 一致) ====================
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# HR 系统「待增减人员」页面
|
||||
ADD_SUB_URL = (
|
||||
"https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic"
|
||||
"#ajax&1&nworktoday-40175-13664-23874-98879&nworktoday-40175-13664"
|
||||
"|/RedseaPlatform/hrRoster/7984ae1a-16ec-11ed-bea9-822ff8ed5b28/"
|
||||
"getCustomCommonList.mc?menuName=待增减人员"
|
||||
)
|
||||
|
||||
BTN_MORE = "更多操作" # 「更多操作」下拉按钮
|
||||
MENU_ADD = "增员导入" # 下拉菜单:增员导入
|
||||
MENU_SUB = "减员导入" # 下拉菜单:减员导入
|
||||
BTN_NEXT = "下一步" # 导入弹窗「下一步」按钮(第 2/3 步)
|
||||
BTN_CLOSE = "关闭" # 导入完成弹窗「关闭」按钮
|
||||
|
||||
WAIT_SHORT = 0.6
|
||||
WAIT_MID = 2.0
|
||||
WAIT_LONG = 4.0
|
||||
|
||||
# 接口监听:第二步「下一步」导入内容结果(getTmpDataPage.mc)
|
||||
TMP_DATA_API_MARK = "getTmpDataPage.mc" # 导入内容结果接口(URL 子串过滤)
|
||||
TMP_DATA_STATE_OK = "1" # 接口 state 成功值
|
||||
TMP_DATA_WAIT = 8.0 # 等待导入结果接口响应的超时秒数
|
||||
|
||||
USER_AGENT = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"Chrome/120.0.0.0 Safari/537.36")
|
||||
|
||||
|
||||
class LoginRequiredError(Exception):
|
||||
"""HR 登录态缺失/失效(页面被重定向到登录页或无可用 cookies)。"""
|
||||
|
||||
|
||||
class ElementNotFoundError(Exception):
|
||||
"""页面元素/控件未找到(页面结构变化或加载超时)。"""
|
||||
|
||||
|
||||
# ==================== 登录态:底座注入 session 优先,兜底共享 cookies 文件 ====================
|
||||
def _cookies_from_requests_session(session):
|
||||
"""从底座注入的 requests.Session 提取 37du.co 域 cookies(DrissionPage 字典格式)。"""
|
||||
cookies = []
|
||||
try:
|
||||
jar_items = list(session.cookies)
|
||||
except Exception:
|
||||
return cookies
|
||||
for c in jar_items:
|
||||
domain = str(getattr(c, "domain", "") or "")
|
||||
if "37du.co" not in domain:
|
||||
continue
|
||||
cookies.append({
|
||||
"name": c.name, "value": c.value,
|
||||
"domain": domain, "path": getattr(c, "path", None) or "/",
|
||||
})
|
||||
return cookies
|
||||
|
||||
|
||||
def _cookies_from_shared_file():
|
||||
"""读取共享 HR cookies 文件(37du.co 域),缺失/为空返回空列表。"""
|
||||
if not os.path.isfile(SHARED_HR_COOKIE_FILE):
|
||||
return []
|
||||
try:
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding="utf-8") as f:
|
||||
cookies = json.load(f) or []
|
||||
except Exception as e:
|
||||
logger.warning("共享 HR cookies 文件读取失败 %s:%s", SHARED_HR_COOKIE_FILE, e)
|
||||
return []
|
||||
return [c for c in cookies if c.get("domain") and "37du.co" in str(c["domain"])]
|
||||
|
||||
|
||||
def _collect_browser_cookies():
|
||||
"""收集浏览器登录态 cookies:底座注入 session 优先,为空兜底共享 cookies 文件。"""
|
||||
cookies = []
|
||||
session = get_session()
|
||||
if session is not None:
|
||||
cookies = _cookies_from_requests_session(session)
|
||||
if cookies:
|
||||
logger.info("使用底座注入 HR 会话的 cookies:%d 个", len(cookies))
|
||||
if not cookies:
|
||||
cookies = _cookies_from_shared_file()
|
||||
if cookies:
|
||||
logger.info("使用共享 cookies 文件:%d 个(%s)", len(cookies), SHARED_HR_COOKIE_FILE)
|
||||
if not cookies:
|
||||
raise LoginRequiredError(
|
||||
"未找到可用 HR 登录态:底座未注入 HR 会话且共享 cookies 文件缺失/为空,"
|
||||
"请先在插件界面完成 HR 登录后再执行导入。")
|
||||
return cookies
|
||||
|
||||
|
||||
def _build_hr_session():
|
||||
"""构建可访问 HR 接口的 requests.Session(供结果接口翻页拉全)。
|
||||
|
||||
cookies 来源与浏览器一致(注入 session 优先,兜底共享文件);构建失败返回 None,
|
||||
调用方降级为仅统计监听到的第一页(与影刀版兜底语义一致)。
|
||||
"""
|
||||
cookies = []
|
||||
session = get_session()
|
||||
if session is not None:
|
||||
cookies = _cookies_from_requests_session(session)
|
||||
if not cookies:
|
||||
cookies = _cookies_from_shared_file()
|
||||
if not cookies:
|
||||
return None
|
||||
s = requests.Session()
|
||||
s.headers.update({
|
||||
"User-Agent": USER_AGENT,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
try:
|
||||
s.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
except Exception:
|
||||
continue
|
||||
return s
|
||||
|
||||
|
||||
# ==================== 元素定位辅助(DrissionPage) ====================
|
||||
def _create_page():
|
||||
"""创建 ChromiumPage(统一配置,非无头,与影刀版一致)。"""
|
||||
co = ChromiumOptions()
|
||||
return ChromiumPage(co)
|
||||
|
||||
|
||||
def _click_text(page, text, timeout=10):
|
||||
"""按元素文本精确匹配并点击,找不到则抛错。"""
|
||||
ele = page.ele(f'xpath://*[normalize-space(text())="{text}"]', timeout=timeout)
|
||||
if not ele:
|
||||
raise ElementNotFoundError(f"未找到元素:{text}")
|
||||
ele.click()
|
||||
logger.info("已点击:%s", text)
|
||||
|
||||
|
||||
def _click_text_in(page, container, text, timeout=5):
|
||||
"""在指定容器内按文本匹配并点击。"""
|
||||
ele = container.ele(f'xpath:.//*[normalize-space(text())="{text}"]', timeout=timeout)
|
||||
if not ele:
|
||||
raise ElementNotFoundError(f"容器内未找到元素:{text}")
|
||||
ele.click()
|
||||
logger.info("已点击:%s", text)
|
||||
|
||||
|
||||
def _is_displayed(ele):
|
||||
"""判断元素是否可见且具有尺寸;异常时返回 False(保守不误判)。"""
|
||||
if ele is None:
|
||||
return False
|
||||
try:
|
||||
if not ele.states.is_displayed:
|
||||
return False
|
||||
w, h = ele.rect.size
|
||||
return w > 0 and h > 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _ensure_logged_in(page):
|
||||
"""访问待增减人员页面;若被重定向到登录页,抛 LoginRequiredError。"""
|
||||
page.get(ADD_SUB_URL)
|
||||
time.sleep(WAIT_LONG)
|
||||
if page.ele('@id=j_username', timeout=2):
|
||||
raise LoginRequiredError(
|
||||
"HR 登录态已失效(页面被重定向到登录页),请先在插件界面重新登录 HR 再执行导入。")
|
||||
logger.info("已进入待增减人员页面:%s", page.url)
|
||||
|
||||
|
||||
# ==================== 增员/减员导入页面流程 ====================
|
||||
def _open_more_operations(page):
|
||||
"""点击「更多操作」按钮,展开下拉菜单(幂等,已展开则跳过)。"""
|
||||
menu = page.ele('css:#custom-btn-ul', timeout=2)
|
||||
if menu and _is_displayed(menu):
|
||||
logger.info("「更多操作」下拉已展开,跳过")
|
||||
time.sleep(WAIT_SHORT)
|
||||
return menu
|
||||
|
||||
more_btn = page.ele('css:#more-btns button.dropdown-toggle', timeout=15)
|
||||
if not more_btn:
|
||||
more_btn = page.ele('css:button.btn-success.dropdown-toggle', timeout=5)
|
||||
if not more_btn:
|
||||
_click_text(page, BTN_MORE)
|
||||
else:
|
||||
more_btn.click()
|
||||
logger.info("已点击「更多操作」")
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
menu = page.ele('css:#custom-btn-ul', timeout=5)
|
||||
if not menu:
|
||||
raise ElementNotFoundError("未找到「更多操作」下拉菜单(#custom-btn-ul)")
|
||||
logger.info("「更多操作」下拉已展开")
|
||||
return menu
|
||||
|
||||
|
||||
def _choose_import_menu(page, menu_label):
|
||||
"""在下拉菜单中选择「增员导入」或「减员导入」。"""
|
||||
menu = _open_more_operations(page)
|
||||
_click_text_in(page, menu, menu_label)
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _upload_file(page, file_path):
|
||||
"""在导入弹窗中上传指定文件(直接对 input[name=file] 设置路径,跳过系统文件选择框)。"""
|
||||
if not os.path.isfile(file_path):
|
||||
raise FileNotFoundError(f"导入文件不存在:{file_path}")
|
||||
file_input = page.ele('css:input[name="file"]', timeout=15)
|
||||
if not file_input:
|
||||
raise ElementNotFoundError("未找到文件上传控件(input[name=file])")
|
||||
file_input.input(file_path)
|
||||
logger.info("已选择导入文件:%s", file_path)
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
|
||||
def _click_next(page):
|
||||
"""点击导入弹窗中的「下一步」按钮(btn-success 且可见)。"""
|
||||
btn = page.ele(
|
||||
'xpath://div[contains(@class,"sub-btn")]//button[contains(@class,"btn-success")'
|
||||
' and normalize-space(.)="下一步"]',
|
||||
timeout=10,
|
||||
)
|
||||
if not btn or not _is_displayed(btn):
|
||||
raise ElementNotFoundError("未找到可见的「下一步」按钮")
|
||||
btn.click()
|
||||
logger.info("已点击「下一步」")
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _click_close(page):
|
||||
"""点击导入完成弹窗中的「关闭」按钮。"""
|
||||
btn = page.ele(
|
||||
'xpath://div[contains(@class,"sub-btn")]//button[contains(@class,"btn-default")'
|
||||
' and normalize-space(.)="关闭"]',
|
||||
timeout=10,
|
||||
)
|
||||
if not btn or not _is_displayed(btn):
|
||||
raise ElementNotFoundError("未找到可见的「关闭」按钮")
|
||||
btn.click()
|
||||
logger.info("已点击「关闭」")
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 接口监听:上传表格后解析结果(getTmpDataPage.mc),捕获返回的全部异常
|
||||
# ---------------------------------------------------------------
|
||||
def _extract_json_response(req):
|
||||
"""从监听到的请求中解析 JSON 响应;解析失败返回 None。"""
|
||||
try:
|
||||
return req.response.json()
|
||||
except Exception:
|
||||
body = getattr(req.response, "body", None)
|
||||
if isinstance(body, (dict, list)):
|
||||
return body
|
||||
if not body:
|
||||
return None
|
||||
try:
|
||||
return json.loads(body)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _merge_datas(result, resp):
|
||||
"""从一次接口响应(resp)中提取并累计统计:需导入总条数、成功数、异常明细。"""
|
||||
for item in resp.get("datas") or []:
|
||||
item = item or {}
|
||||
msg = str(item.get("imp_fixed_msg", "") or "").strip()
|
||||
if not msg:
|
||||
continue
|
||||
result["total_count"] += 1
|
||||
# 成功行返回「导入成功;」固定文案,只计数量不纳入异常
|
||||
if "导入成功" in msg:
|
||||
result["success_count"] += 1
|
||||
continue
|
||||
result["exceptions"].append({
|
||||
"staff_code": str(item.get("imp_assi_staff_code_ext_table_field_base_id", "") or ""),
|
||||
"staff_name": str(item.get("imp_assi_staff_name_ext_table_field_base_id", "") or ""),
|
||||
"insurance_name": str(item.get("ext_insurance_name", "") or ""),
|
||||
"message": msg,
|
||||
})
|
||||
|
||||
|
||||
def _fetch_remaining_pages(result, first_url, first_body, page_count, page_size=15):
|
||||
"""getTmpDataPage 每页固定返回 15 条,弹窗只加载第一页:按 pageNo 主动翻页拉全。
|
||||
|
||||
该接口为 POST,分页参数(importId/imp_fixed_businessid/start/pageNo/pageSize)
|
||||
在请求 body 中,必须复用首次请求 body 改页码后 POST(直接 GET URL 拿不到目标页)。
|
||||
"""
|
||||
if page_count <= 1:
|
||||
return
|
||||
session = _build_hr_session()
|
||||
if session is None:
|
||||
logger.warning("分页拉取失败(无法构建 HR 会话),仅统计弹窗第一页")
|
||||
return
|
||||
for page_no in range(2, page_count + 1):
|
||||
start = (page_no - 1) * page_size
|
||||
body = re.sub(r"pageNo=\d+", f"pageNo={page_no}", first_body or "")
|
||||
body = re.sub(r"start=\d+", f"start={start}", body)
|
||||
body = re.sub(r"pageSize=\d+", f"pageSize={page_size}", body)
|
||||
try:
|
||||
resp = session.post(first_url, data=body, timeout=15)
|
||||
data = resp.json()
|
||||
except Exception as e:
|
||||
logger.warning("分页第 %s/%s 页拉取失败:%s", page_no, page_count, e)
|
||||
continue
|
||||
if str(data.get("state", "")).strip() != TMP_DATA_STATE_OK:
|
||||
logger.warning("分页第 %s/%s 页返回 state=%s,跳过",
|
||||
page_no, page_count, data.get("state"))
|
||||
continue
|
||||
logger.info("分页第 %s/%s 页返回 %s 条",
|
||||
page_no, page_count, len(data.get("datas") or []))
|
||||
_merge_datas(result, data)
|
||||
|
||||
|
||||
def _capture_import_exceptions(page, timeout=TMP_DATA_WAIT):
|
||||
"""监听导入结果接口(getTmpDataPage.mc),捕获全部逐行结果(监听须已开启)。
|
||||
|
||||
第一步「下一步」(格式校验/预览)也可能请求该接口但行内 imp_fixed_msg 为空,跳过;
|
||||
仅处理携带导入结果说明的响应。捕获首响应后按 pageCount 主动翻页拉全。
|
||||
|
||||
Returns:
|
||||
dict: {captured, state, meg, listen_ok, success_count, total_count, exceptions}
|
||||
"""
|
||||
result = {"captured": False, "state": "", "meg": "", "exceptions": [],
|
||||
"listen_ok": True, "success_count": 0, "total_count": 0}
|
||||
first_url = None
|
||||
first_body = ""
|
||||
page_count = 1
|
||||
deadline = time.time() + timeout
|
||||
last_hit = time.time()
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
remain = max(0.0, deadline - time.time())
|
||||
req = page.listen.wait(timeout=min(0.5, remain))
|
||||
except Exception as e:
|
||||
logger.warning("监听 %s 接口异常:%s", TMP_DATA_API_MARK, e)
|
||||
break
|
||||
if not req:
|
||||
# 已捕获过解析响应时,再确认一个间隔后结束,合并多次返回的结果
|
||||
if result["captured"] and time.time() - last_hit >= 1.0:
|
||||
break
|
||||
continue
|
||||
if not hasattr(req, "url"):
|
||||
continue
|
||||
if TMP_DATA_API_MARK not in (req.url or ""):
|
||||
continue
|
||||
resp = _extract_json_response(req)
|
||||
if not isinstance(resp, dict):
|
||||
continue
|
||||
# 预览/校验响应行内 imp_fixed_msg 为空 -> 跳过,继续等待最终结果
|
||||
if not any(str((it or {}).get("imp_fixed_msg", "") or "").strip()
|
||||
for it in (resp.get("datas") or [])):
|
||||
continue
|
||||
result["captured"] = True
|
||||
last_hit = time.time()
|
||||
state = str(resp.get("state", "")).strip()
|
||||
if state:
|
||||
result["state"] = state
|
||||
meg = str(resp.get("meg", "") or "").strip()
|
||||
if meg:
|
||||
result["meg"] = meg
|
||||
if first_url is None:
|
||||
first_url = req.url
|
||||
first_body = req.request.postData or ""
|
||||
try:
|
||||
page_count = max(1, int(resp.get("pageCount") or 1))
|
||||
except Exception:
|
||||
page_count = 1
|
||||
_merge_datas(result, resp)
|
||||
if first_url and page_count > 1:
|
||||
_fetch_remaining_pages(result, first_url, first_body, page_count)
|
||||
break
|
||||
return result
|
||||
|
||||
|
||||
def _count_import_rows(file_path):
|
||||
"""统计导入文件需导入条数(A 列最大序号;第 1 行标题/第 2 行表头/第 3 行示例,第 4 行起数据)。
|
||||
|
||||
官方模板自带大量预格式化空白行(max_row 可达数千),不能直接用 max_row 统计。
|
||||
"""
|
||||
try:
|
||||
wb = load_workbook(file_path, read_only=True)
|
||||
try:
|
||||
ws = wb[wb.sheetnames[0]]
|
||||
max_seq = 0
|
||||
for seq in ws.iter_rows(min_row=4, max_row=ws.max_row,
|
||||
max_col=1, values_only=True):
|
||||
v = seq[0]
|
||||
if v is None or str(v).strip() == "":
|
||||
continue
|
||||
try:
|
||||
max_seq = max(max_seq, int(v))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
return max_seq
|
||||
finally:
|
||||
wb.close()
|
||||
except Exception as e:
|
||||
logger.warning("统计导入文件条数失败 %s:%s", file_path, e)
|
||||
return 0
|
||||
|
||||
|
||||
def _import_file_path(category, menu_label):
|
||||
"""按菜单解析类别导入文件路径(base_dir 运行时注入,实时拼接)。"""
|
||||
if menu_label == MENU_ADD:
|
||||
from ..config import category_import_add_file
|
||||
return category_import_add_file(category)
|
||||
from ..config import category_import_sub_file
|
||||
return category_import_sub_file(category)
|
||||
|
||||
|
||||
def _import_one(page, category, menu_label, expected_total=None):
|
||||
"""对单个类别执行一次导入(选菜单 -> 上传 -> 下一步 -> 下一步 -> 关闭)。
|
||||
|
||||
自第一个「下一步」之前即开启 getTmpDataPage.mc 监听(结果接口可能在格式校验或
|
||||
真正导入时触发,提前监听避免漏捕);异常仅记录上报,不中断导入流程。
|
||||
|
||||
Args:
|
||||
expected_total: 需导入条数(由 import_all 预检传入,避免重复读文件;None 时自行统计)。
|
||||
|
||||
Returns:
|
||||
dict: 导入结果(含 expected_total 需导入条数、exceptions 异常明细等)。
|
||||
"""
|
||||
file_path = _import_file_path(category, menu_label)
|
||||
if not os.path.isfile(file_path):
|
||||
raise FileNotFoundError(f"导入文件不存在:{file_path}")
|
||||
if expected_total is None:
|
||||
expected_total = _count_import_rows(file_path)
|
||||
|
||||
logger.info("===== 类别[%s] 开始%s,文件:%s(需导入 %d 条) =====",
|
||||
category["name"], menu_label, file_path, expected_total)
|
||||
_choose_import_menu(page, menu_label)
|
||||
_upload_file(page, file_path)
|
||||
|
||||
# 第一个「下一步」前开启监听,贯穿「格式校验/预览 + 真正导入」全过程;
|
||||
# 监听启动失败必须上报,否则未捕获异常会被误判为正常(假成功)
|
||||
listen_ok = True
|
||||
try:
|
||||
page.listen.start(TMP_DATA_API_MARK)
|
||||
except Exception as e:
|
||||
listen_ok = False
|
||||
logger.error("启动 %s 接口监听失败,无法捕获导入结果:%s", TMP_DATA_API_MARK, e)
|
||||
try:
|
||||
_click_next(page) # 第一步:格式校验/预览
|
||||
_click_next(page) # 第二步:真正导入内容(触发结果接口)
|
||||
import_result = _capture_import_exceptions(page)
|
||||
import_result["listen_ok"] = listen_ok
|
||||
import_result["expected_total"] = expected_total
|
||||
finally:
|
||||
try:
|
||||
page.listen.stop()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 全部成功时 HR 不调用结果接口:流程完整走完 + 监听正常 + 未捕获异常行 -> 按文件条数推定全部成功
|
||||
if (not import_result["captured"] and listen_ok and not import_result["exceptions"]):
|
||||
import_result["assumed_all_success"] = True
|
||||
import_result["success_count"] = expected_total
|
||||
import_result["total_count"] = expected_total
|
||||
|
||||
if import_result["exceptions"]:
|
||||
logger.error("类别[%s] %s:导入返回 %d 条异常:",
|
||||
category["name"], menu_label, len(import_result["exceptions"]))
|
||||
for exc in import_result["exceptions"]:
|
||||
logger.error(" - [%s/%s] 方案[%s]:%s",
|
||||
exc["staff_code"], exc["staff_name"],
|
||||
exc["insurance_name"], exc["message"])
|
||||
elif not listen_ok:
|
||||
logger.error("类别[%s] %s:接口监听启动失败,无法确认导入结果,请人工核对",
|
||||
category["name"], menu_label)
|
||||
elif import_result["captured"] and import_result["state"] != TMP_DATA_STATE_OK:
|
||||
logger.error("类别[%s] %s:导入接口 state=%s(meg=%s),导入可能失败",
|
||||
category["name"], menu_label, import_result["state"], import_result["meg"])
|
||||
elif import_result.get("assumed_all_success"):
|
||||
logger.info("类别[%s] %s:全部导入成功(HR 未返回结果接口,按文件 %d 条推定),无异常",
|
||||
category["name"], menu_label, expected_total)
|
||||
elif not import_result["captured"]:
|
||||
logger.warning("类别[%s] %s:未捕获到导入结果接口响应,无法确认导入结果",
|
||||
category["name"], menu_label)
|
||||
else:
|
||||
logger.info("类别[%s] %s:导入成功 %s 人,无异常",
|
||||
category["name"], menu_label, import_result.get("success_count", 0))
|
||||
|
||||
_click_close(page)
|
||||
logger.info("===== 类别[%s] %s完成 =====", category["name"], menu_label)
|
||||
return import_result
|
||||
|
||||
|
||||
# ==================== 对外入口:先减员后增员,全程共用一个浏览器 ====================
|
||||
def _skipped_result(category, menu, reason):
|
||||
"""构造「无待导入条目」的跳过单元结果(无 error,不计流程失败)。"""
|
||||
return {
|
||||
"category": category["name"], "menu": menu,
|
||||
"captured": False, "state": "", "meg": "", "exceptions": [],
|
||||
"listen_ok": True, "expected_total": 0,
|
||||
"success_count": 0, "total_count": 0,
|
||||
"skipped": True, "skip_reason": reason,
|
||||
}
|
||||
|
||||
|
||||
def import_all(categories, on_progress=None):
|
||||
"""对指定类别执行 HR 导入(★先全部类别【减员】再【增员】,顺序不可换)。
|
||||
|
||||
预检:仅「导入文件存在且实际有待导入条目」的单元才会启动浏览器执行导入;
|
||||
需导入 0 条(无增员/减员变动)的单元直接跳过——本就没有需要导入的内容,
|
||||
不启动浏览器、也不报"流程失败"。
|
||||
|
||||
Args:
|
||||
categories: 类别配置列表(config.CATEGORIES 项,须为本次调度成功的类别,
|
||||
只导入本次新生成的导入文件,避免误传历史文件)。
|
||||
on_progress: 可选回调 on_progress(done, total),每个实际执行导入的
|
||||
「类别×菜单」单元完成后调用,供 __init__.py 上报进度。
|
||||
|
||||
Returns:
|
||||
list[dict]: 每单元结果:{category, menu, captured, state, meg, exceptions,
|
||||
listen_ok, expected_total, success_count, total_count,
|
||||
assumed_all_success?, error?, error_type?, skipped?}
|
||||
skipped=True 表示该单元导入文件无待导入条目(需导入 0 条),未启动浏览器导入,
|
||||
不视为流程失败(无 error 字段)。
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: HR 登录态缺失/失效(整个导入未开始,无部分导入风险)。
|
||||
RuntimeError: DrissionPage 依赖缺失。
|
||||
"""
|
||||
if not _DRP_AVAILABLE:
|
||||
raise RuntimeError(f"缺少 DrissionPage 依赖(python-env 未内置),无法自动导入:{_DRP_IMPORT_ERROR}")
|
||||
if not categories:
|
||||
logger.info("无待导入类别,跳过 HR 导入")
|
||||
return []
|
||||
|
||||
# ---- 预检:按导入文件实际条数过滤出真正需要导入的单元(类别×菜单) ----
|
||||
results = []
|
||||
units = []
|
||||
for c in categories:
|
||||
for menu in (MENU_SUB, MENU_ADD):
|
||||
label = "减员" if menu == MENU_SUB else "增员"
|
||||
file_path = _import_file_path(c, menu)
|
||||
if not os.path.isfile(file_path):
|
||||
logger.warning("类别[%s] %s导入文件不存在,视为无需导入:%s",
|
||||
c["name"], label, file_path)
|
||||
results.append(_skipped_result(c, menu, "导入文件不存在"))
|
||||
continue
|
||||
expected_total = _count_import_rows(file_path)
|
||||
if expected_total <= 0:
|
||||
logger.info("类别[%s] %s导入文件无待导入条目,跳过导入:%s",
|
||||
c["name"], label, file_path)
|
||||
results.append(_skipped_result(c, menu, "无待导入条目"))
|
||||
continue
|
||||
units.append((c, menu, expected_total))
|
||||
|
||||
if not units:
|
||||
logger.info("各类别增/减员导入文件均无待导入条目,跳过 HR 自动导入(未启动浏览器)")
|
||||
return results
|
||||
|
||||
total_units = len(units)
|
||||
done = 0
|
||||
|
||||
page = _create_page()
|
||||
logger.info("浏览器已启动(导入全程共用)")
|
||||
try:
|
||||
cookies = _collect_browser_cookies()
|
||||
page.set.cookies(cookies)
|
||||
_ensure_logged_in(page)
|
||||
|
||||
for category, menu_label, expected_total in units:
|
||||
try:
|
||||
res = dict(_import_one(page, category, menu_label, expected_total=expected_total))
|
||||
res["category"] = category["name"]
|
||||
res["menu"] = menu_label
|
||||
results.append(res)
|
||||
except Exception as e:
|
||||
logger.error("类别[%s] %s失败:%s", category["name"], menu_label, e)
|
||||
results.append({
|
||||
"category": category["name"], "menu": menu_label,
|
||||
"captured": False, "state": "", "meg": "", "exceptions": [],
|
||||
"listen_ok": True, "expected_total": 0,
|
||||
"success_count": 0, "total_count": 0,
|
||||
"error": str(e), "error_type": type(e).__name__,
|
||||
})
|
||||
done += 1
|
||||
if on_progress:
|
||||
try:
|
||||
on_progress(done, total_units)
|
||||
except Exception:
|
||||
pass
|
||||
return results
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def summarize_results(results):
|
||||
"""把导入结果汇总为可读文本行列表(供插件 summary 拼接)。
|
||||
|
||||
口径与影刀版一致:需导入条数取自导入文件(expected_total,与接口是否捕获无关);
|
||||
成功/失败取接口返回的业务结果(全部成功时 HR 不返回接口,按文件条数推定成功);
|
||||
流程失败(登录/元素/文件缺失)的单元不纳入条数统计,仅报失败;
|
||||
跳过单元(skipped,无待导入条目)正常纳入统计(需导入 0 条),不报失败/待确认。
|
||||
"""
|
||||
lines = []
|
||||
for menu, label in ((MENU_SUB, "减员"), (MENU_ADD, "增员")):
|
||||
rs = [r for r in results if r.get("menu") == menu]
|
||||
if not rs:
|
||||
continue
|
||||
total = sum(r.get("expected_total") or 0 for r in rs if not r.get("error"))
|
||||
success = sum(r.get("success_count") or 0 for r in rs if not r.get("error"))
|
||||
fail = sum(len(r.get("exceptions") or []) for r in rs if not r.get("error"))
|
||||
flow_failed = [r["category"] for r in rs if r.get("error")]
|
||||
unconfirmed = [r["category"] for r in rs
|
||||
if not r.get("error") and not r.get("exceptions")
|
||||
and not r.get("assumed_all_success") and not r.get("skipped")
|
||||
and (not r.get("captured") or r.get("state") != TMP_DATA_STATE_OK)]
|
||||
line = f"{label}:需导入 {total} 条,成功 {success} 条,异常 {fail} 条"
|
||||
extras = []
|
||||
if unconfirmed:
|
||||
extras.append(f"{len(unconfirmed)} 个类别结果待人工确认({'、'.join(unconfirmed)})")
|
||||
if flow_failed:
|
||||
extras.append(f"流程失败({'、'.join(flow_failed)})")
|
||||
if extras:
|
||||
line += ";" + ";".join(extras)
|
||||
lines.append(line)
|
||||
return lines
|
||||
@@ -1,158 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - 筛选复制(由影刀版 roster_filter.py v2.0.0 移植)。
|
||||
|
||||
从员工花名册按类别 include/exclude 所属单位筛选数据,复制到各自类别目标表
|
||||
(各文件夹内最新的「*雇主险变更记录*.xlsx」),并剔除「入职时间 > 业务日期」的
|
||||
未来入职员工;F列工号强制文本格式(否则与在参名单 B列及表内公式匹配失败)。
|
||||
|
||||
源表缺失或超过 TTL(15 分钟)时调用 data.roster_export_api.export_roster 自动导出,
|
||||
替代影刀版对 share/roster_export.py 的懒加载;登录态经底座注入的 session。
|
||||
"""
|
||||
import os
|
||||
|
||||
import pandas as pd
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from ..config import (
|
||||
logger, SHEET_BIZ, SOURCE_HEADER_MARK, EXPORT_TEMPLATE, EXPORT_STATUSES,
|
||||
TARGET_HEADER_ROW, DATA_COLUMNS, CODE_COL, ID_COL, JOIN_DATE_COL, NAME_COL,
|
||||
EXCLUDE_REGIONS, EXCLUDE_NAME_KEYWORDS, category_folder, employee_file,
|
||||
find_latest_target, to_text, parse_join_date, ref_date, CACHE_DIR,
|
||||
)
|
||||
from ..data.roster_export_api import export_roster
|
||||
|
||||
|
||||
def _read_source(employee_path):
|
||||
"""读取源表(员工花名册):自动定位表头行(B 列=「所属单位」),返回 B~O 14 列切片。"""
|
||||
probe = pd.read_excel(employee_path, header=None, nrows=8)
|
||||
header_row = None
|
||||
for idx in range(len(probe)):
|
||||
if str(probe.iloc[idx, 1]).strip() == SOURCE_HEADER_MARK:
|
||||
header_row = idx
|
||||
break
|
||||
if header_row is None:
|
||||
raise ValueError(f"源表未找到表头行(B 列应为「{SOURCE_HEADER_MARK}」)")
|
||||
|
||||
df = pd.read_excel(employee_path, header=header_row)
|
||||
if df.shape[1] < DATA_COLUMNS + 1:
|
||||
raise ValueError(f"源表列数不足:{df.shape[1]}(需要 B~O 共{DATA_COLUMNS}列)")
|
||||
data = df.iloc[:, 1:DATA_COLUMNS + 1].copy() # B~O 14列(「类型」列在末尾,不受影响)
|
||||
# 与宏一致:以 B 列(所属单位)最后非空行为数据边界
|
||||
return data[data.iloc[:, 0].notna()]
|
||||
|
||||
|
||||
def filter_and_copy_roster(category, employee_path="", target_file=None):
|
||||
"""从员工花名册按类别筛选数据,复制到该类别的雇主险变更记录表(仅复制,不校验)。
|
||||
|
||||
Args:
|
||||
category: 类别配置(含 name/include_dept/exclude_dept)
|
||||
employee_path: 源表路径,默认 {base_dir}\\员工花名册.xlsx
|
||||
target_file: 目标表路径,默认取该类别文件夹内最新的「*雇主险变更记录*.xlsx」
|
||||
|
||||
Returns:
|
||||
复制的数据行数
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 源表或目标表不存在
|
||||
ValueError: 源表列数不足 或 目标表缺少指定 Sheet
|
||||
"""
|
||||
category_name = category["name"]
|
||||
employee_path = os.path.abspath(employee_path or employee_file())
|
||||
target_file = os.path.abspath(target_file or find_latest_target(category_folder(category)))
|
||||
|
||||
if not os.path.exists(employee_path):
|
||||
raise FileNotFoundError(f"源表不存在:{employee_path}")
|
||||
if not os.path.exists(target_file):
|
||||
raise FileNotFoundError(f"目标表不存在:{target_file}")
|
||||
|
||||
# ---------- 1. 读取源表并过滤 ----------
|
||||
data = _read_source(employee_path)
|
||||
dept = data.iloc[:, 0].astype(str).str.strip()
|
||||
region = data.iloc[:, 1].astype(str).str.strip()
|
||||
name = data.iloc[:, NAME_COL].astype(str).str.strip()
|
||||
include_dept = category.get("include_dept") or []
|
||||
exclude_dept = category.get("exclude_dept") or []
|
||||
mask = ~region.isin(EXCLUDE_REGIONS)
|
||||
if include_dept:
|
||||
mask &= dept.isin(include_dept)
|
||||
if exclude_dept:
|
||||
mask &= ~dept.isin(exclude_dept)
|
||||
for kw in EXCLUDE_NAME_KEYWORDS:
|
||||
mask &= ~name.str.contains(kw, na=False)
|
||||
|
||||
# 入职时间 > 业务日期 的行剔除(未来才入职的员工暂不纳入,留到当天再筛选出来)
|
||||
today = ref_date()
|
||||
join_dates = data.iloc[:, JOIN_DATE_COL].map(parse_join_date)
|
||||
future_mask = join_dates.map(lambda d: d is not None and d > today)
|
||||
n_future = int(future_mask.sum())
|
||||
mask &= ~future_mask
|
||||
filtered = data[mask]
|
||||
logger.info("类别[%s]:源表共 %d 行,过滤后 %d 行(保留 %s / 排除 %s,并排除 %s,姓名剔除含 %s,剔除未来入职 %d 人)",
|
||||
category_name, len(data), len(filtered),
|
||||
include_dept or "全部", exclude_dept or "无", " / ".join(EXCLUDE_REGIONS),
|
||||
" / ".join(EXCLUDE_NAME_KEYWORDS), n_future)
|
||||
if len(filtered) == 0:
|
||||
logger.warning("类别[%s] 筛选后没有数据!", category_name)
|
||||
|
||||
# ---------- 2. 写目标表(先覆盖写入,只清空超出新数据的旧行) ----------
|
||||
wb = load_workbook(target_file)
|
||||
if SHEET_BIZ not in wb.sheetnames:
|
||||
raise ValueError(f"目标表缺少 Sheet:{SHEET_BIZ}")
|
||||
ws = wb[SHEET_BIZ]
|
||||
first_data_row = TARGET_HEADER_ROW + 1 # 第5行
|
||||
|
||||
# 找 B 列当前最后非空数据行(用于清空多余旧行)
|
||||
old_last = first_data_row - 1
|
||||
for r in range(first_data_row, ws.max_row + 1):
|
||||
if ws.cell(row=r, column=2).value is not None:
|
||||
old_last = r
|
||||
|
||||
# 写入 B~O(覆盖旧数据;F列工号 / O列证件号 强制文本格式)
|
||||
rows = filtered.values.tolist()
|
||||
cell = ws.cell
|
||||
for i, row in enumerate(rows, start=first_data_row):
|
||||
for j, val in enumerate(row, start=2):
|
||||
c = cell(row=i, column=j)
|
||||
# 工号/证件号为主键:18位身份证号超出浮点精度,文本化避免截断,保证公式/映射匹配
|
||||
if j - 2 in (CODE_COL, ID_COL):
|
||||
c.value = to_text(val)
|
||||
c.number_format = "@"
|
||||
else:
|
||||
c.value = val
|
||||
|
||||
# 清空超出新数据的旧行
|
||||
new_last = first_data_row + len(rows) - 1
|
||||
if old_last > new_last:
|
||||
for r in range(new_last + 1, old_last + 1):
|
||||
for c in range(2, 2 + DATA_COLUMNS):
|
||||
cell(row=r, column=c).value = None
|
||||
|
||||
wb.save(target_file)
|
||||
logger.info("类别[%s] 已写入目标表 %s 第%d行起,共 %d 行", category_name, target_file, first_data_row, len(rows))
|
||||
return len(rows)
|
||||
|
||||
|
||||
def ensure_employee_file(employee_path="", session=None):
|
||||
"""确保花名册源表可用:缺失或超过 TTL(15 分钟)时自动重新从 HR 接口导出。
|
||||
|
||||
新鲜度评估交给 export_roster 的 TTL 缓存:源表存在、非空且距上次导出
|
||||
不超过 15 分钟时直接复用,否则重新导出覆盖(不用陈旧花名册做调度)。
|
||||
|
||||
Args:
|
||||
employee_path: 花名册路径(留空=默认根目录/员工花名册.xlsx)
|
||||
session: 底座注入的 HR 会话(导出时使用)
|
||||
|
||||
Returns:
|
||||
源表绝对路径
|
||||
"""
|
||||
path = os.path.abspath(employee_path or employee_file())
|
||||
export_roster(
|
||||
download_dir=os.path.join(CACHE_DIR, "roster_tmp"),
|
||||
output_path=path,
|
||||
template_name=EXPORT_TEMPLATE,
|
||||
statuses=EXPORT_STATUSES,
|
||||
session=session,
|
||||
)
|
||||
if not os.path.exists(path):
|
||||
raise FileNotFoundError(f"花名册导出完成但源表仍不存在:{path}")
|
||||
return path
|
||||
@@ -1,559 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - 三阶段名额调度(由影刀版 employer_insurance_schedule.py v1.3.0 移植)。
|
||||
|
||||
阶段0 初始化(空闲名额池 / 当前参保映射 / 待转入队列)→
|
||||
阶段1 处理业务(增加投保批量 / 要替换逐行)→
|
||||
阶段2 分配名额(复用空闲名额 / 全新新增);
|
||||
含姓名核对修正(J列)、特殊情况槽位追踪(离职/参保减少被复用后保留占位)、
|
||||
以及类别级编排 schedule_category(读取目标文件 → 各阶段 → 输出)。
|
||||
|
||||
文件路径/日期/常量统一来自 config 层;输出(在参名单/变更清单/备份/增减员导入)
|
||||
由 report.output 负责(本模块在编排处懒加载,避免与 report 相互 import 成环)。
|
||||
"""
|
||||
import os
|
||||
from collections import defaultdict
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from ..config import (
|
||||
logger, SHEET_BIZ, SHEET_IN_PARAM, DATA_START_ROW,
|
||||
BIZ_COL_EMPLOYEE_ID, BIZ_COL_CATEGORY, BIZ_COL_SCHEME, BIZ_COL_HANDLE,
|
||||
VALID_CATEGORIES, VALID_SCHEMES, category_target_file,
|
||||
category_output_backup, category_change_sheet_name,
|
||||
add_import_template, sub_import_template, to_text, today_date,
|
||||
)
|
||||
|
||||
|
||||
class DataValidationError(Exception):
|
||||
"""数据校验失败异常:直接中断调度,禁止继续往后跑。"""
|
||||
|
||||
|
||||
def scheme_with_suffix(category, scheme):
|
||||
"""增员导入「保险方案名称」追加厂区后缀(如 人保-80万 -> 人保-80万-秒创)。
|
||||
|
||||
源数据投保方案为无后缀的人保-X万;HR 侧方案列表含厂区后缀,
|
||||
生成增员导入文件时按类别追加。已带对应后缀或后缀为空时原样返回。
|
||||
"""
|
||||
suffix = str(category.get("scheme_suffix") or "").strip()
|
||||
scheme = str(scheme or "").strip()
|
||||
if suffix and scheme and not scheme.endswith("-" + suffix):
|
||||
return f"{scheme}-{suffix}"
|
||||
return scheme
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 一、数据校验
|
||||
# ============================================================
|
||||
def validate_biz_data(biz_df):
|
||||
"""校验花名册业务数据的合法性。
|
||||
|
||||
校验规则:
|
||||
1. 工种类别(P列)必须为:一类/二类/三类/四类
|
||||
2. 方案处理 = "增加投保" 时,投保方案(Q列)必须为:人保-20万 / 50万 / 80万
|
||||
|
||||
返回 errors 错误列表,每个错误含 行号/员工ID/错误类型/详情;为空表示校验通过。
|
||||
"""
|
||||
errors = []
|
||||
for idx, row in biz_df.iterrows():
|
||||
row_num = idx + 5 # 数据从第5行开始(第4行是表头)
|
||||
emp_id = row[BIZ_COL_EMPLOYEE_ID]
|
||||
category = row[BIZ_COL_CATEGORY]
|
||||
scheme = row[BIZ_COL_SCHEME]
|
||||
handle = row[BIZ_COL_HANDLE]
|
||||
|
||||
if pd.isna(category) or category not in VALID_CATEGORIES:
|
||||
errors.append({
|
||||
"行号": row_num,
|
||||
"员工ID": emp_id,
|
||||
"错误类型": "工种类别非法",
|
||||
"详情": f"工种类别为 '{category}',允许值:{VALID_CATEGORIES}",
|
||||
})
|
||||
|
||||
if str(handle).strip() == "增加投保":
|
||||
if pd.isna(scheme) or scheme not in VALID_SCHEMES:
|
||||
errors.append({
|
||||
"行号": row_num,
|
||||
"员工ID": emp_id,
|
||||
"错误类型": "投保方案非法",
|
||||
"详情": f"增加投保但投保方案为 '{scheme}',允许值:{VALID_SCHEMES}",
|
||||
})
|
||||
return errors
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 二、阶段0:初始化(从在参名单构建状态)
|
||||
# ============================================================
|
||||
def initialize(in_param_df):
|
||||
"""从「手动维护-在参名单」构建三个核心数据结构。
|
||||
|
||||
1. idle_pools: 空闲名额池 {方案名称: [{type, employee_id}, ...]}
|
||||
2. employee_map: 当前参保员工映射 {证件号: 投保方案}
|
||||
3. pending_queues: 待转入队列(初始为空){方案名称: [证件号, ...]}
|
||||
|
||||
列索引(0-based): K列(10)证件号 / M列(12)当前投保方案 / R列(17)方案处理
|
||||
"""
|
||||
idle_pools = defaultdict(list)
|
||||
employee_map = {}
|
||||
pending_queues = defaultdict(list)
|
||||
|
||||
IDX_EMP_ID = 10
|
||||
IDX_CUR_SCHEME = 12
|
||||
IDX_HANDLE = 17
|
||||
|
||||
for _, row in in_param_df.iterrows():
|
||||
emp_id = row.iloc[IDX_EMP_ID]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
|
||||
handle = str(row.iloc[IDX_HANDLE]).strip()
|
||||
scheme = row.iloc[IDX_CUR_SCHEME]
|
||||
|
||||
if handle in ["无需", "档次替换"]:
|
||||
# 正常参保或待替换,都视为当前已参保
|
||||
if not pd.isna(scheme) and scheme != "":
|
||||
employee_map[emp_id] = scheme
|
||||
elif handle == "离职减少":
|
||||
if not pd.isna(scheme) and scheme != "":
|
||||
idle_pools[scheme].append({"type": "离职减少", "employee_id": emp_id})
|
||||
elif handle == "参保减少":
|
||||
if not pd.isna(scheme) and scheme != "":
|
||||
idle_pools[scheme].append({"type": "参保减少", "employee_id": emp_id})
|
||||
# 其他值(如'/')忽略
|
||||
|
||||
# 按优先级排序(离职减少优先)
|
||||
for scheme in idle_pools:
|
||||
idle_pools[scheme].sort(key=lambda x: 1 if x["type"] == "离职减少" else 2)
|
||||
|
||||
return idle_pools, employee_map, pending_queues
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 二点五、姓名核对修正(在参名单 J列 与 花名册 姓名比对)
|
||||
# ============================================================
|
||||
def collect_name_corrections(in_param_df, biz_df):
|
||||
"""核对「手动维护-在参名单」J列姓名与花名册「姓名」是否一致,并就地修正。
|
||||
|
||||
以证件号(在参名单 K列 / 花名册 O列)为关联键:
|
||||
- 在参名单中证件号存在、且花名册中能查到该证件号(覆盖离职减少/参保减少等全部行)
|
||||
- 两者姓名不一致且花名册姓名非空 → 记录一条修正,并把 in_param_df J列改为花名册姓名,
|
||||
使后续「删除记录 / 在参名单输出 / 减员导入」统一使用修正后姓名。
|
||||
- 花名册查不到(如已离职)无法核对,跳过不处理。
|
||||
|
||||
Returns:
|
||||
corrections: 修正列表,每项 {emp_id, old_name, new_name, category, scheme}
|
||||
"""
|
||||
biz_dict = {}
|
||||
for _, row in biz_df.iterrows():
|
||||
emp_id = row[BIZ_COL_EMPLOYEE_ID]
|
||||
if pd.notna(emp_id):
|
||||
biz_dict[emp_id] = row
|
||||
|
||||
corrections = []
|
||||
for idx, row in in_param_df.iterrows():
|
||||
emp_id = row.iloc[10]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
biz_row = biz_dict.get(emp_id)
|
||||
if biz_row is None:
|
||||
continue # 花名册查不到,无法核对,跳过
|
||||
new_name = biz_row.get("姓名")
|
||||
if new_name is None or pd.isna(new_name) or str(new_name).strip() == "":
|
||||
continue
|
||||
new_name = str(new_name).strip()
|
||||
old_name = row.iloc[9]
|
||||
old_name_txt = "" if pd.isna(old_name) else str(old_name).strip()
|
||||
if old_name_txt == new_name:
|
||||
continue # 姓名一致,无需修正
|
||||
# 就地修正 in_param_df J列(姓名),供后续统一使用
|
||||
in_param_df.at[idx, in_param_df.columns[9]] = new_name
|
||||
corrections.append({
|
||||
"emp_id": emp_id,
|
||||
"old_name": old_name_txt or "未知",
|
||||
"new_name": new_name,
|
||||
"category": biz_row.get(BIZ_COL_CATEGORY),
|
||||
"scheme": biz_row.get(BIZ_COL_SCHEME),
|
||||
})
|
||||
|
||||
if corrections:
|
||||
logger.info("姓名核对修正:共 %d 条", len(corrections))
|
||||
for c in corrections:
|
||||
logger.info(" %s:%s → %s", c["emp_id"], c["old_name"], c["new_name"])
|
||||
else:
|
||||
logger.info("姓名核对完成:在参名单与花名册姓名全部一致")
|
||||
return corrections
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 三、阶段1:处理花名册业务
|
||||
# ============================================================
|
||||
def process_business(biz_df, idle_pools, employee_map, pending_queues):
|
||||
"""遍历花名册业务数据,产生待转入队列和额外空闲名额。
|
||||
|
||||
业务类型:
|
||||
1. 增加投保 → 批量加入待转入队列
|
||||
2. 要替换 → 逐行处理:产生"档次替换迁出"名额,员工置为未参保
|
||||
3. 其他 → 记录"非法事件跳过"
|
||||
|
||||
返回:idle_pools, employee_map, pending_queues, change_log
|
||||
"""
|
||||
change_log = []
|
||||
now = today_date()
|
||||
|
||||
# ---------- 1. 增加投保(批量处理) ----------
|
||||
df_add = biz_df[biz_df[BIZ_COL_HANDLE].astype(str).str.strip() == "增加投保"]
|
||||
if not df_add.empty:
|
||||
for scheme, group in df_add.groupby(BIZ_COL_SCHEME):
|
||||
if pd.isna(scheme) or scheme == "":
|
||||
for _, row in group.iterrows():
|
||||
change_log.append({
|
||||
"员工ID": row[BIZ_COL_EMPLOYEE_ID],
|
||||
"操作": "非法事件跳过",
|
||||
"详情": "投保方案为空,无法增加投保",
|
||||
"时间": now,
|
||||
})
|
||||
continue
|
||||
emp_ids = group[BIZ_COL_EMPLOYEE_ID].tolist()
|
||||
pending_queues[scheme].extend(emp_ids)
|
||||
for emp_id in emp_ids:
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "增加投保",
|
||||
"详情": f"加入 {scheme} 待转入队列",
|
||||
"时间": now,
|
||||
})
|
||||
|
||||
# ---------- 2. 要替换(逐行处理,涉及状态变更) ----------
|
||||
df_replace = biz_df[biz_df[BIZ_COL_HANDLE].astype(str).str.strip() == "要替换"]
|
||||
for _, row in df_replace.iterrows():
|
||||
emp_id = row[BIZ_COL_EMPLOYEE_ID]
|
||||
target_scheme = row[BIZ_COL_SCHEME]
|
||||
|
||||
# 校验:员工必须当前已参保
|
||||
origin_scheme = employee_map.get(emp_id)
|
||||
if origin_scheme is None:
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "非法事件跳过",
|
||||
"详情": "员工当前未参保,无法进行档次替换",
|
||||
"时间": now,
|
||||
})
|
||||
continue
|
||||
|
||||
if pd.isna(target_scheme) or target_scheme == "":
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "非法事件跳过",
|
||||
"详情": "目标方案为空",
|
||||
"时间": now,
|
||||
})
|
||||
continue
|
||||
|
||||
# 产生"档次替换迁出"名额
|
||||
idle_pools[origin_scheme].append({"type": "档次替换迁出", "employee_id": emp_id})
|
||||
# 重新排序(离职减少 > 参保减少 > 档次替换迁出)
|
||||
idle_pools[origin_scheme].sort(
|
||||
key=lambda x: 1 if x["type"] == "离职减少"
|
||||
else 2 if x["type"] == "参保减少"
|
||||
else 3)
|
||||
|
||||
# 员工置为未参保
|
||||
employee_map[emp_id] = None
|
||||
pending_queues[target_scheme].append(emp_id)
|
||||
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "档次替换迁出",
|
||||
"详情": f"从 {origin_scheme} 迁出,进入 {target_scheme} 待转入",
|
||||
"时间": now,
|
||||
})
|
||||
|
||||
# ---------- 3. 其他未知类型 ----------
|
||||
df_other = biz_df[~biz_df[BIZ_COL_HANDLE].astype(str).str.strip().isin(["增加投保", "要替换"])]
|
||||
for _, row in df_other.iterrows():
|
||||
change_log.append({
|
||||
"员工ID": row[BIZ_COL_EMPLOYEE_ID],
|
||||
"操作": "非法事件跳过",
|
||||
"详情": f"未知业务类型: {row[BIZ_COL_HANDLE]}",
|
||||
"时间": now,
|
||||
})
|
||||
|
||||
return idle_pools, employee_map, pending_queues, change_log
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 四、阶段2:分配名额
|
||||
# ============================================================
|
||||
def allocate_slots(idle_pools, employee_map, pending_queues, change_log):
|
||||
"""逐个方案处理待转入队列,分配空闲名额或创建新名额。
|
||||
|
||||
逻辑:
|
||||
1. 队列中的每个员工必须未参保
|
||||
2. 有空闲名额 → 复用(记录来源)
|
||||
3. 无空闲名额 → 全新新增
|
||||
|
||||
返回:final_records, change_log, reused_source_employees
|
||||
"""
|
||||
final_records = []
|
||||
reused_source_employees = []
|
||||
all_schemes = set(idle_pools.keys()) | set(pending_queues.keys())
|
||||
now = today_date()
|
||||
|
||||
for scheme in all_schemes:
|
||||
queue = pending_queues.get(scheme, [])
|
||||
pool = idle_pools.get(scheme, [])
|
||||
|
||||
for emp_id in queue:
|
||||
# 校验:员工必须未参保
|
||||
if employee_map.get(emp_id) is not None:
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "非法事件跳过",
|
||||
"详情": f"员工已参保 {employee_map[emp_id]},不能重复参保",
|
||||
"时间": now,
|
||||
})
|
||||
continue
|
||||
|
||||
if pool:
|
||||
# 复用空闲名额(取出优先级最高的)
|
||||
slot = pool.pop(0)
|
||||
reused_source_employees.append(slot["employee_id"])
|
||||
employee_map[emp_id] = scheme
|
||||
final_records.append({
|
||||
"证件号": emp_id,
|
||||
"投保方案": scheme,
|
||||
"参保状态": "正常参保",
|
||||
"名额来源": slot["type"],
|
||||
"来源员工ID": slot["employee_id"],
|
||||
})
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "复用空闲名额参保",
|
||||
"详情": f"复用 {slot['type']}(来源 {slot['employee_id']}),方案 {scheme}",
|
||||
"来源员工ID": slot["employee_id"],
|
||||
"时间": now,
|
||||
})
|
||||
else:
|
||||
# 全新新增
|
||||
employee_map[emp_id] = scheme
|
||||
final_records.append({
|
||||
"证件号": emp_id,
|
||||
"投保方案": scheme,
|
||||
"参保状态": "正常参保",
|
||||
"名额来源": "全新新增",
|
||||
})
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "全新新增名额参保",
|
||||
"详情": f"新增名额,方案 {scheme}",
|
||||
"时间": now,
|
||||
})
|
||||
|
||||
return final_records, change_log, reused_source_employees
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 四点半、特殊情况槽位追踪(report 层共用)
|
||||
# ============================================================
|
||||
def _find_special_slots(final_records, in_param_df):
|
||||
"""识别特殊情况:离职/参保减少名额被老员工复用,且该老员工释放的旧名额无人复用。
|
||||
|
||||
(例如 曹益娟参保减少20万→老员工胡兴复用,胡兴的X档旧名额没人用)。
|
||||
此时把源员工名额改为老员工旧方案(X档)保留在参名单,变更清单补一条"增加X档",
|
||||
既保证 增加>=删除 平衡,又把空闲名额放回池中供下次替换使用(避免同人两条名单)。
|
||||
|
||||
Returns:
|
||||
special_slots: [{source_id, source_name, source_category, new_scheme}, ...]
|
||||
"""
|
||||
# 初始参保映射:在参名单 M列(投保方案)非空视为"原已参保"
|
||||
initial_employee_map = {}
|
||||
for _, row in in_param_df.iterrows():
|
||||
emp_id = row.iloc[10]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
orig_scheme = row.iloc[12]
|
||||
if pd.notna(orig_scheme) and str(orig_scheme).strip() != "":
|
||||
initial_employee_map[emp_id] = True
|
||||
|
||||
final_emp_ids = set(rec["证件号"] for rec in final_records)
|
||||
# 槽位复用网络:来源员工ID -> 接收记录(用于链条追踪)
|
||||
slot_network = {}
|
||||
for _rec in final_records:
|
||||
_sid = _rec.get("来源员工ID")
|
||||
if _sid is not None and not pd.isna(_sid) and str(_sid).strip():
|
||||
slot_network[str(_sid).strip()] = _rec
|
||||
|
||||
# 链条追踪:离职/参保减少释放的名额被老员工复用后,沿"来源员工ID"网络一路追踪,
|
||||
# 老员工每次"删除自己旧方案"即释放一个旧名额,若该名额被下一人复用则继续,直到:
|
||||
# - 接收者是全新新员工(无旧方案可删)→ 链条自然结束,增删本就平衡;
|
||||
# - 末端老员工释放的旧名额无人复用 → 该旧名额即"空闲名额"(X档)。
|
||||
special_slots = []
|
||||
for rec in final_records:
|
||||
if rec.get("名额来源") not in ("离职减少", "参保减少"):
|
||||
continue
|
||||
source_id = rec.get("来源员工ID")
|
||||
# 源员工自身也参保则跳过,避免同一个人出现两条名单
|
||||
if source_id is None or pd.isna(source_id) or source_id in final_emp_ids:
|
||||
continue
|
||||
source_id = str(source_id).strip()
|
||||
# 沿链条追踪,找到末端"未被复用的旧方案"(空闲名额 X档)
|
||||
current_owner = source_id
|
||||
visited = set()
|
||||
loose_end_scheme = None
|
||||
while current_owner not in visited:
|
||||
visited.add(current_owner)
|
||||
next_rec = slot_network.get(current_owner)
|
||||
if next_rec is None:
|
||||
break # 链条断裂
|
||||
receiver_id = str(next_rec["证件号"]).strip()
|
||||
# 接收者不是原已参保老员工(全新新员工)-> 无旧方案可释放,链条自然结束
|
||||
if receiver_id not in initial_employee_map:
|
||||
break
|
||||
# 接收者是老员工:释放自己的旧方案(X档);若该旧名额无人复用则即为空闲名额
|
||||
if receiver_id not in slot_network:
|
||||
row_match = in_param_df[in_param_df.iloc[:, 10] == receiver_id]
|
||||
if not row_match.empty:
|
||||
loose_end_scheme = row_match.iloc[0].iloc[12]
|
||||
break
|
||||
current_owner = receiver_id # 旧名额被复用,继续追踪下一环
|
||||
if not loose_end_scheme:
|
||||
continue
|
||||
src_match = in_param_df[in_param_df.iloc[:, 10] == source_id]
|
||||
if src_match.empty:
|
||||
continue
|
||||
src_row = src_match.iloc[0]
|
||||
special_slots.append({
|
||||
"source_id": source_id,
|
||||
"source_name": src_row.iloc[9],
|
||||
"source_category": src_row.iloc[11],
|
||||
"new_scheme": loose_end_scheme,
|
||||
})
|
||||
return special_slots
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 五、类别级编排(读取目标文件 → 三阶段 → 输出)
|
||||
# ============================================================
|
||||
def _check_import_templates():
|
||||
"""前置校验增减员导入模板是否存在,任一缺失立即抛错。
|
||||
|
||||
模板在调度开始时校验(而非生成导入文件时才报),避免完整调度跑完后
|
||||
才发现模板缺失、需要重做的浪费。
|
||||
"""
|
||||
missing = [
|
||||
path for path in (add_import_template(), sub_import_template())
|
||||
if not os.path.isfile(path)
|
||||
]
|
||||
if missing:
|
||||
raise FileNotFoundError(
|
||||
"增减员导入模板缺失,请先补充模板后再调度:\n - " + "\n - ".join(missing))
|
||||
|
||||
|
||||
def schedule_category(category, enable_validation=True, gen_import_files=True):
|
||||
"""对单个类别执行调度全流程(读取已刷新公式的目标文件,输出结果)。
|
||||
|
||||
Args:
|
||||
category: 类别配置
|
||||
enable_validation: 是否启用数据校验(校验失败抛 DataValidationError 中断)
|
||||
gen_import_files: 是否生成增员/减员导入文件
|
||||
|
||||
前置:目标文件已完成筛选复制(roster_filter)并经 WPS/Excel 重算公式。
|
||||
"""
|
||||
category_name = category["name"]
|
||||
target_file = category_target_file(category)
|
||||
output_backup = category_output_backup(category)
|
||||
change_sheet_prefix = category["change_sheet_prefix"]
|
||||
change_sheet_name = category_change_sheet_name(category)
|
||||
logger.info("=" * 70)
|
||||
logger.info("类别[%s] 目标文件:%s", category_name, target_file)
|
||||
|
||||
if not os.path.exists(target_file):
|
||||
raise FileNotFoundError(f"目标表不存在:{target_file},请先完成筛选复制步骤")
|
||||
|
||||
# 检查必需 Sheet
|
||||
xl = pd.ExcelFile(target_file)
|
||||
for s in (SHEET_BIZ, SHEET_IN_PARAM):
|
||||
if s not in xl.sheet_names:
|
||||
raise ValueError(f"目标表缺少必需 Sheet:{s}")
|
||||
logger.info("文件结构检查通过。")
|
||||
|
||||
if gen_import_files:
|
||||
_check_import_templates()
|
||||
|
||||
# ---------- 读取并清洗花名册数据 ----------
|
||||
# O列(索引14)证件号强制 dtype=str:含空行的列会被 pandas 推断为 float64,
|
||||
# 18 位身份证号读取即截断(如 ...0009 -> ...0000),导致与在参名单匹配失败
|
||||
biz_df = pd.read_excel(target_file, sheet_name=SHEET_BIZ, header=3, dtype={14: str})
|
||||
logger.info("原始花名册数据:%d 行", len(biz_df))
|
||||
# 过滤:证件号为空 或 方案处理为 "/"
|
||||
biz_df = biz_df[
|
||||
biz_df[BIZ_COL_EMPLOYEE_ID].notna() &
|
||||
(biz_df[BIZ_COL_HANDLE].astype(str).str.strip() != "/")
|
||||
]
|
||||
logger.info("清洗后花名册数据:%d 行", len(biz_df))
|
||||
|
||||
# ---------- 读取在参名单 ----------
|
||||
# K列(索引10)证件号同样强制 dtype=str,避免 float64 截断 18 位身份证号
|
||||
in_param_df = pd.read_excel(target_file, sheet_name=SHEET_IN_PARAM, header=5,
|
||||
dtype={10: str})
|
||||
logger.info("在参名单:%d 行", len(in_param_df))
|
||||
|
||||
# 主键文本化:证件号统一转文本(pandas 会把纯数字证件号读为 int64,openpyxl 落盘时
|
||||
# 转浮点会截断 18 位身份证号;统一文本化后匹配/输出全部一致且不丢精度)
|
||||
# 用整列赋值(允许自动升级 dtype),避免 float64 列 iloc 赋值报 LossySetitemError
|
||||
biz_df = biz_df.copy()
|
||||
biz_df[BIZ_COL_EMPLOYEE_ID] = biz_df[BIZ_COL_EMPLOYEE_ID].map(to_text)
|
||||
in_param_df = in_param_df.copy()
|
||||
_id_col = in_param_df.columns[10]
|
||||
in_param_df[_id_col] = in_param_df[_id_col].map(to_text)
|
||||
column_names = in_param_df.columns.tolist()
|
||||
|
||||
# ---------- 姓名核对修正 ----------
|
||||
logger.info("核对在参名单与花名册姓名...")
|
||||
name_corrections = collect_name_corrections(in_param_df, biz_df)
|
||||
|
||||
# ---------- 数据校验 ----------
|
||||
if enable_validation:
|
||||
logger.info("正在校验数据...")
|
||||
errors = validate_biz_data(biz_df)
|
||||
if errors:
|
||||
for e in errors:
|
||||
logger.error(" 行%s 员工%s:%s - %s",
|
||||
e["行号"], e["员工ID"], e["错误类型"], e["详情"])
|
||||
raise DataValidationError(
|
||||
f"类别[{category_name}] 数据校验失败,共 {len(errors)} 个错误,已中断调度")
|
||||
logger.info("数据校验通过!")
|
||||
|
||||
# ---------- 阶段0:初始化 ----------
|
||||
logger.info("初始化状态...")
|
||||
idle_pools, employee_map, pending_queues = initialize(in_param_df)
|
||||
logger.info(" 空闲名额池:%d 个", sum(len(v) for v in idle_pools.values()))
|
||||
logger.info(" 当前参保员工:%d 人", len(employee_map))
|
||||
|
||||
# ---------- 阶段1:处理业务 ----------
|
||||
logger.info("处理花名册业务...")
|
||||
idle_pools, employee_map, pending_queues, change_log = process_business(
|
||||
biz_df, idle_pools, employee_map, pending_queues)
|
||||
logger.info(" 待转入总人数:%d 人", sum(len(v) for v in pending_queues.values()))
|
||||
logger.info(" 变更日志条数:%d", len(change_log))
|
||||
|
||||
# ---------- 阶段2:分配名额 ----------
|
||||
logger.info("分配名额...")
|
||||
final_records, change_log, reused_source_employees = allocate_slots(
|
||||
idle_pools, employee_map, pending_queues, change_log)
|
||||
logger.info(" 最终参保记录:%d 人", len(final_records))
|
||||
|
||||
# ---------- 阶段3+4:输出(懒加载 report,避免 import 成环) ----------
|
||||
from ..report.output import output_results, export_add_sub_import
|
||||
logger.info("输出结果...")
|
||||
output_results(
|
||||
final_records, change_log, reused_source_employees, biz_df,
|
||||
in_param_df, column_names, target_file, output_backup,
|
||||
change_sheet_name, change_sheet_prefix, SHEET_IN_PARAM,
|
||||
name_corrections)
|
||||
|
||||
if gen_import_files:
|
||||
logger.info("生成增员/减员导入文件...")
|
||||
export_add_sub_import(category, biz_df, in_param_df, final_records, reused_source_employees)
|
||||
|
||||
logger.info("类别[%s] 调度完成!", category_name)
|
||||
return final_records
|
||||
@@ -1,122 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - WPS/Excel COM 后台重算 + 取消筛选工具。
|
||||
|
||||
替代雇主险流程中「人工打开目标文件刷新公式(Ctrl+S 保存)」环节:
|
||||
openpyxl 写入数据后公式列的缓存结果会丢失,调度/导出变更清单前必须先重算落盘;
|
||||
同时移除所有 sheet 的 AutoFilter,保证每次处理结束文件以无筛选状态保存,
|
||||
后续人工「删除重新粘贴花名册」不再受筛选残留导致数据错位。
|
||||
底层用 WPS 表格 COM(Ket.Application,专业版/企业版)打开 → 取消筛选 →
|
||||
CalculateFullRebuild → Save;WPS 不可用时回退 MS Excel(Excel.Application)。
|
||||
目标文件若已被用户在 WPS/Excel 中打开则复用该工作簿,不打断用户会话。
|
||||
"""
|
||||
import os
|
||||
|
||||
from ..config import logger
|
||||
|
||||
|
||||
class ComRecalcError(RuntimeError):
|
||||
"""公式重算失败(文件被占用 / 本机无 WPS 专业版或 MS Excel / COM 异常)。"""
|
||||
|
||||
|
||||
def recalc_target(file_path):
|
||||
"""对单个 xlsx 执行「取消全部筛选 → 全量重算公式 → 保存」。
|
||||
|
||||
目标文件已在 WPS/Excel 中打开时复用该工作簿(不关闭,保留用户会话);
|
||||
由本函数自行打开的工作簿在保存后关闭;仅当实例已无其他工作簿时才退出 COM。
|
||||
|
||||
Args:
|
||||
file_path: 目标文件绝对路径。
|
||||
|
||||
Raises:
|
||||
ComRecalcError: 重算失败(含本机无可用 COM 引擎 / COM 异常等)。
|
||||
"""
|
||||
file_path = os.path.abspath(file_path)
|
||||
if not os.path.isfile(file_path):
|
||||
raise ComRecalcError(f"待重算文件不存在:{file_path}")
|
||||
|
||||
import pythoncom
|
||||
import win32com.client
|
||||
|
||||
pythoncom.CoInitialize()
|
||||
app = None
|
||||
engine = ""
|
||||
wb = None
|
||||
already_open = False
|
||||
try:
|
||||
# 优先 WPS 表格 COM(Ket.Application);失败回退 MS Excel
|
||||
try:
|
||||
app = win32com.client.Dispatch("Ket.Application")
|
||||
engine = "WPS"
|
||||
except Exception:
|
||||
try:
|
||||
app = win32com.client.Dispatch("Excel.Application")
|
||||
engine = "Excel"
|
||||
except Exception as e:
|
||||
raise ComRecalcError(
|
||||
"本机未检测到可用的 WPS 表格 COM / MS Excel COM,无法自动重算公式。\n"
|
||||
"请安装 WPS 专业版/企业版或 MS Excel 后重试,或关闭「WPS/Excel 后台重算公式」开关后人工打开文件 Ctrl+S 刷新公式。"
|
||||
) from e
|
||||
|
||||
# 不设置 Visible=False:Dispatch 可能附着到用户已打开的实例,隐藏其窗口
|
||||
app.DisplayAlerts = False # 关闭弹窗警告(finally 恢复)
|
||||
try:
|
||||
# 目标文件已在 WPS/Excel 中打开时复用该工作簿
|
||||
for w in app.Workbooks:
|
||||
try:
|
||||
if os.path.normcase(str(w.FullName or "")) == os.path.normcase(file_path):
|
||||
wb = w
|
||||
already_open = True
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
if wb is None:
|
||||
wb = app.Workbooks.Open(file_path, UpdateLinks=2)
|
||||
|
||||
# 1. 取消所有 sheet 的筛选(筛选只是隐藏行,但会干扰人工维护花名册)
|
||||
removed = 0
|
||||
for ws in wb.Worksheets:
|
||||
try:
|
||||
if ws.AutoFilterMode:
|
||||
ws.AutoFilterMode = False
|
||||
removed += 1
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 2. 强制完整重算全部公式(openpyxl 写入后公式列缓存丢失)
|
||||
wb.Application.CalculateFullRebuild()
|
||||
|
||||
# 3. 把计算结果缓存写入 xlsx 磁盘
|
||||
wb.Save()
|
||||
logger.info("公式重算完成(%s COM):取消 %d 个 sheet 筛选%s:%s",
|
||||
engine, removed,
|
||||
"(复用已打开的工作簿)" if already_open else "", file_path)
|
||||
finally:
|
||||
try:
|
||||
app.DisplayAlerts = True
|
||||
except Exception:
|
||||
pass
|
||||
if wb is not None and not already_open:
|
||||
try:
|
||||
wb.Close(SaveChanges=False)
|
||||
except Exception:
|
||||
pass
|
||||
except ComRecalcError:
|
||||
raise
|
||||
except Exception as e:
|
||||
# 打开失败通常仍是文件被占用/锁定,给出可操作提示
|
||||
raise ComRecalcError(
|
||||
f"公式重算失败({engine or 'COM'}):{e}\n"
|
||||
"请确认该目标文件未被 WPS/Excel 以受保护/只读视图打开(关闭后再试)。"
|
||||
) from e
|
||||
finally:
|
||||
if app is not None:
|
||||
# 仅当实例已无其他工作簿时才退出,避免关掉用户正在使用的 WPS/Excel
|
||||
try:
|
||||
if app.Workbooks.Count == 0:
|
||||
app.Quit()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
pythoncom.CoUninitialize()
|
||||
except Exception:
|
||||
pass
|
||||
@@ -1,86 +0,0 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0002",
|
||||
"name": "雇主险增减操作",
|
||||
"version": "1.0.10",
|
||||
"description": "雇主险名额调度全流程:花名册导出→筛选复制→WPS/Excel 后台取消筛选并重算公式→三阶段名额调度→更新在参名单与变更清单→生成增员/减员导入文件(可选自动导入 HR 系统)→钉钉群推送汇总与导入异常名单,替代人工取消筛选与 Ctrl+S 刷新公式、人工上传导入环节",
|
||||
"category": "人事",
|
||||
"icon": "",
|
||||
"platform": "hr",
|
||||
"uses_month": false,
|
||||
"ui": true,
|
||||
"capabilities": ["xq0002"],
|
||||
"permissions": {
|
||||
"platforms": ["hr"]
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"base_dir": {
|
||||
"type": "string",
|
||||
"title": "雇主险根目录",
|
||||
"default": "D:\\资料\\人资\\雇主险",
|
||||
"description": "四类各占一个子文件夹(三十七度/水庄餐饮/湖畔酒店/秒创传媒),增/减员导入模板放在根目录"
|
||||
},
|
||||
"ref_date": {
|
||||
"type": "string",
|
||||
"title": "业务日期",
|
||||
"default": "",
|
||||
"description": "留空=今天;影响变更清单/在参名单/导入文件中的日期与备份文件名"
|
||||
},
|
||||
"categories": {
|
||||
"type": "array",
|
||||
"title": "处理类别(可多选)",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"enum": ["三十七度", "水庄餐饮", "湖畔酒店", "秒创传媒"]
|
||||
},
|
||||
"default": ["三十七度", "水庄餐饮", "湖畔酒店", "秒创传媒"],
|
||||
"description": "留空=全部类别"
|
||||
},
|
||||
"roster_path": {
|
||||
"type": "string",
|
||||
"title": "花名册路径",
|
||||
"default": "",
|
||||
"description": "留空=根目录/员工花名册.xlsx(源表缺失或超过 15 分钟 TTL 时自动从 HR 导出)"
|
||||
},
|
||||
"enable_validation": {
|
||||
"type": "boolean",
|
||||
"title": "启用数据校验",
|
||||
"default": true,
|
||||
"description": "校验工种类别与投保方案合法性,校验失败终止调度"
|
||||
},
|
||||
"wps_recalc": {
|
||||
"type": "boolean",
|
||||
"title": "WPS/Excel 后台重算公式",
|
||||
"default": true,
|
||||
"description": "筛选复制后/调度后自动打开目标文件取消全部筛选并全量重算公式保存,替代人工取消筛选与 Ctrl+S 刷新公式;需本机安装 WPS 专业版/企业版或 MS Excel"
|
||||
},
|
||||
"export_change_sheet": {
|
||||
"type": "boolean",
|
||||
"title": "导出变更清单独立工作簿",
|
||||
"default": true,
|
||||
"description": "调度后将各类别变更清单 sheet 复制为独立工作簿(公式转值,保留样式)"
|
||||
},
|
||||
"gen_import_files": {
|
||||
"type": "boolean",
|
||||
"title": "生成增员/减员导入文件",
|
||||
"default": true,
|
||||
"description": "调度后生成商业保险增员/减员导入.xlsx(HR 待增减人员页面上传素材)"
|
||||
},
|
||||
"import_to_hr": {
|
||||
"type": "boolean",
|
||||
"title": "自动导入HR系统",
|
||||
"default": true,
|
||||
"description": "调度完成后自动把增/减员导入文件导入 HR「待增减人员」(浏览器自动化,先减员后增员,仅导入本次调度成功的类别);需本机 Chrome/Edge 且执行中会弹出浏览器窗口;须同时开启「生成增员/减员导入文件」"
|
||||
},
|
||||
"dingtalk_notify": {
|
||||
"type": "boolean",
|
||||
"title": "钉钉群通知",
|
||||
"default": true,
|
||||
"description": "执行完成后推送结果汇总与增/减员导入异常名单到钉钉群(推送失败不影响主流程)"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 report 层:在参名单更新/变更清单/备份/增减员导入输出。"""
|
||||
@@ -1,297 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - 钉钉群机器人推送(自 workflows/share/dingtalk_robot.py 移植,插件内单一真源)。
|
||||
|
||||
推送原理(HTTP Webhook,零第三方依赖,仅标准库,符合插件自包含约束):
|
||||
按钉钉加签规则(HMAC-SHA256 + Base64 + URL 编码)生成签名,
|
||||
向机器人 Webhook 推送 Markdown 消息,失败自动重试 3 次。
|
||||
|
||||
约定:
|
||||
- 执行机运行环境无 .env 读取,故推送地址/加签密钥/页脚署名直接内联在下方
|
||||
「默认配置」区(单一真源),改推送目标时改常量即可;
|
||||
- 页脚署名默认 "37du 任务调度平台":
|
||||
注意:钉钉机器人若配置了"自定义关键词"安全校验,
|
||||
页脚署名需包含该关键词(如 小芒)才会被接受;
|
||||
- env='dev' 走测试环境机器人,避免调试时误发生产群。
|
||||
|
||||
用法(业务层统一走 report/notify.py,也可直接调用):
|
||||
main("需要推送的通知文本") 即可,标题/颜色/环境等均可选;
|
||||
text 传「块格式分组」字典列表 [{title, blocks, status?}] 时由本模块自动分批逐条推送。
|
||||
返回: {"success": bool, "message": str}
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime
|
||||
|
||||
# ==================== 默认配置 ====================
|
||||
DEFAULT_WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=65dd3f38dea12d2419743aad62ed25f5544ae1ff2ff7d2f667682e0dc912ff6e'
|
||||
DEFAULT_SECRET = '' # 加签密钥(未配置则不加签)
|
||||
DEFAULT_SERVER_NAME = '37du 任务调度平台'
|
||||
|
||||
# 测试环境配置(env='dev' 时使用;默认使用 DEFAULT_WEBHOOK )
|
||||
DEV_WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=26613569642db03fae6fd19cc932a4b08d82fd09afd35ccfd3ddee5884b5cb66'
|
||||
DEV_SECRET = '' # 测试环境加签密钥(未配置则不加签)
|
||||
DEV_SERVER_NAME = '小芒 任务调度平台'
|
||||
|
||||
# 环境 → 机器人配置(main 的 env 参数选择;缺省/未知环境回退 prod)
|
||||
ENV_CONFIGS = {
|
||||
'prod': {'webhook': DEFAULT_WEBHOOK, 'secret': DEFAULT_SECRET, 'server_name': DEFAULT_SERVER_NAME},
|
||||
'dev': {'webhook': DEV_WEBHOOK, 'secret': DEV_SECRET, 'server_name': DEV_SERVER_NAME},
|
||||
}
|
||||
|
||||
DEFAULT_TIMEOUT = 10 # HTTP 请求超时秒数
|
||||
DEFAULT_RETRY_TIMES = 3 # 失败重试次数(含首次)
|
||||
|
||||
# 通知状态 → 标题颜色
|
||||
_STATUS_COLORS = {
|
||||
'info': '#0077ff', # 蓝色
|
||||
'success': '#00b300', # 绿色
|
||||
'warning': '#ff9900', # 橙色
|
||||
'error': '#ff0000', # 红色
|
||||
}
|
||||
|
||||
|
||||
def _build_sign(secret, timestamp_ms):
|
||||
"""按钉钉加签规则计算签名(HMAC-SHA256 + Base64 + URL 编码)。"""
|
||||
string_to_sign = f"{timestamp_ms}\n{secret}"
|
||||
hmac_code = hmac.new(
|
||||
secret.encode('utf-8'), string_to_sign.encode('utf-8'), digestmod=hashlib.sha256
|
||||
).digest()
|
||||
return urllib.parse.quote_plus(base64.b64encode(hmac_code))
|
||||
|
||||
|
||||
def _build_url(webhook, secret=''):
|
||||
"""拼接最终推送地址:配置了 secret 时追加 timestamp + sign 参数。"""
|
||||
if not secret:
|
||||
return webhook
|
||||
ts = int(round(time.time() * 1000))
|
||||
separator = '&' if '?' in webhook else '?'
|
||||
return f"{webhook}{separator}timestamp={ts}&sign={_build_sign(secret, ts)}"
|
||||
|
||||
|
||||
class DingTalkRobot:
|
||||
"""钉钉群机器人推送器。"""
|
||||
|
||||
def __init__(self, webhook='', secret='', server_name='', timeout=DEFAULT_TIMEOUT):
|
||||
self.webhook = (webhook or DEFAULT_WEBHOOK).strip()
|
||||
self.secret = (secret or DEFAULT_SECRET).strip()
|
||||
self.server_name = (server_name or DEFAULT_SERVER_NAME).strip()
|
||||
self.timeout = timeout
|
||||
if not self.webhook:
|
||||
raise ValueError('webhook 不能为空')
|
||||
|
||||
def _post(self, payload):
|
||||
"""推送 payload 到机器人,errcode != 0 视为失败;失败自动重试。"""
|
||||
last_err = None
|
||||
for attempt in range(DEFAULT_RETRY_TIMES):
|
||||
try:
|
||||
url = _build_url(self.webhook, self.secret)
|
||||
data = json.dumps(payload, ensure_ascii=False).encode('utf-8')
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=data,
|
||||
headers={'Content-Type': 'application/json; charset=utf-8'},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
||||
body = resp.read().decode('utf-8')
|
||||
resp_data = json.loads(body)
|
||||
if resp_data.get('errcode') != 0:
|
||||
raise RuntimeError(
|
||||
f"钉钉机器人返回错误 errcode={resp_data.get('errcode')}, "
|
||||
f"errmsg={resp_data.get('errmsg')}"
|
||||
)
|
||||
return
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
print(f"[WARN] 推送失败(第 {attempt + 1}/{DEFAULT_RETRY_TIMES} 次):{e}")
|
||||
time.sleep(1)
|
||||
raise RuntimeError(f"推送失败,重试 {DEFAULT_RETRY_TIMES} 次后仍出错:{last_err}")
|
||||
|
||||
def send(self, title, content, status='info', server_name=''):
|
||||
"""发送统一通知(Markdown:标题按状态着色,正文直接渲染,带页脚)。
|
||||
|
||||
Args:
|
||||
title: 消息标题
|
||||
content: 消息正文(Markdown,引用块/加粗/超链接/列表等语法会被钉钉渲染)
|
||||
status: info|success|warning|error,决定标题颜色(默认 info)
|
||||
server_name: 页脚署名
|
||||
"""
|
||||
color = _STATUS_COLORS.get(status, _STATUS_COLORS['info'])
|
||||
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
||||
display_name = (server_name or self.server_name).strip()
|
||||
footer = f"\n\n---\n\n###### {display_name} | {now}"
|
||||
|
||||
text = f"**<font color='{color}'>{title}</font>**\n\n"
|
||||
text += content.strip() + "\n"
|
||||
text += footer
|
||||
|
||||
payload = {'msgtype': 'markdown', 'markdown': {'title': title, 'text': text}}
|
||||
print(f"[INFO] 钉钉机器人推送通知 [{status}]: {title}")
|
||||
self._post(payload)
|
||||
|
||||
def send_in_batches(self, title, content, status='info', server_name='',
|
||||
max_chars=15000):
|
||||
"""分批发送长内容(按行智能拆分,避免切断单行数据)。
|
||||
|
||||
当钉钉消息内容超过 max_chars 字符时,自动按行拆成多批发送,
|
||||
每批带「第 N/M 批」标题前缀,便于接收方识别。
|
||||
|
||||
Args:
|
||||
title: 消息标题
|
||||
content: 消息正文(长文本)
|
||||
status: info|success|warning|error,决定标题颜色
|
||||
server_name: 页脚署名
|
||||
max_chars: 单批最大字符数(默认 15000,钉钉 Markdown 上限约 20000)
|
||||
"""
|
||||
lines = content.strip().split('\n')
|
||||
batches = []
|
||||
current_batch = []
|
||||
current_len = 0
|
||||
|
||||
for line in lines:
|
||||
line_len = len(line) + 1 # +1 for newline
|
||||
if current_len + line_len > max_chars and current_batch:
|
||||
batches.append('\n'.join(current_batch))
|
||||
current_batch = [line]
|
||||
current_len = line_len
|
||||
else:
|
||||
current_batch.append(line)
|
||||
current_len += line_len
|
||||
|
||||
if current_batch:
|
||||
batches.append('\n'.join(current_batch))
|
||||
|
||||
total = len(batches)
|
||||
for i, batch_content in enumerate(batches, 1):
|
||||
batch_title = f"{title}(第{i}/{total}批)" if total > 1 else title
|
||||
print(f"[INFO] 分批推送 {i}/{total}: {batch_title}")
|
||||
self.send(batch_title, batch_content, status=status,
|
||||
server_name=server_name)
|
||||
|
||||
|
||||
# ==================== 块格式工具:调用方把每条记录格式化为 block 字符串列表,
|
||||
# 这里统一负责分批、加头尾、生成最终待推送的消息文本列表 ====================
|
||||
|
||||
def compose_batch_messages(blocks, title_prefix, batch_size=10):
|
||||
"""把块格式 block 字符串列表按 batch_size 条一批,生成带批次标题的消息文本列表。
|
||||
|
||||
Args:
|
||||
blocks: 每条记录格式化后的 block 字符串列表(调用方负责格式化业务字段)
|
||||
title_prefix: 批次标题前缀,如 "【请假审批】通过"
|
||||
batch_size: 每批最大条数(默认 10)
|
||||
|
||||
Returns:
|
||||
字符串列表,每项是一条完整的待推送 Markdown 文本,可直接传给 main(text=...)
|
||||
配合 batch=True 发送。
|
||||
"""
|
||||
if not blocks:
|
||||
return []
|
||||
result = []
|
||||
total_batches = (len(blocks) + batch_size - 1) // batch_size
|
||||
for bi in range(total_batches):
|
||||
batch = blocks[bi * batch_size:(bi + 1) * batch_size]
|
||||
header = f"###### {title_prefix}(第{bi + 1}/{total_batches}批)\n\n"
|
||||
# 钉钉中引用块尾行后需空行(双换行)再进入新标题,否则会紧贴渲染
|
||||
footer = f"\n\n###### 本批共{len(batch)}条"
|
||||
content = header + '\n\n'.join(batch) + footer
|
||||
result.append(content)
|
||||
return result
|
||||
|
||||
|
||||
# ==================== 推送入口 ====================
|
||||
def main(text, title='消息通知', status='info', webhook='', secret='', server_name='',
|
||||
env='prod', batch=False, max_chars=15000):
|
||||
"""
|
||||
钉钉群机器人推送入口(与影刀版「37du钉钉群机器人推送」指令同一套签名/分批/页脚逻辑)。
|
||||
只需把要推送的通知文本传进来即可,例如:
|
||||
|
||||
main("订单同步失败,错误原因:接口超时")
|
||||
|
||||
支持逐条推送多条:text 传「文本列表」时按顺序逐条发送,列表项可为纯文本,
|
||||
也可为字典 {text, title?, status?, batch?} 自定义该条标题、颜色与格式。
|
||||
消息正文一律按 Markdown 渲染(引用块/加粗/超链接/列表等语法直接生效)。
|
||||
|
||||
块格式分组(推荐,调用方不关心分批):
|
||||
text 传字典列表,每项形如 {title, blocks, status?, batch_size?},
|
||||
blocks 为每条记录格式化好的 block 字符串列表。模块自动按 batch_size
|
||||
(默认 10)分批、每批带「第N/M批」标题并逐条推送。示例:
|
||||
main([
|
||||
{"title": "【增员导入】异常名单(2 条)",
|
||||
"blocks": ["**🔹 三十七度‑张三**\n> 工号:...", "..."],
|
||||
"status": "error"},
|
||||
])
|
||||
|
||||
可选参数:
|
||||
title: 消息标题(默认 消息通知)
|
||||
status: info|success|warning|error,决定标题颜色(默认 info)
|
||||
webhook: 机器人 webhook(缺省按 env 选择;显式传入则优先)
|
||||
secret: 加签密钥(缺省按 env 选择;显式传入则优先)
|
||||
server_name: 页脚署名(缺省按 env 选择;显式传入则优先)
|
||||
env: 环境 prod|dev,决定缺省 webhook/secret/server_name(默认 prod)
|
||||
batch: 是否启用分批发送(默认 False)。
|
||||
True: 当内容超长时自动按行拆成多批发送,每批标题带「第N/M批」;
|
||||
False: 单条发送(内容超长可能被钉钉截断或报错)。
|
||||
max_chars: 单批最大字符数(默认 15000,钉钉 Markdown 上限约 20000),
|
||||
仅在 batch=True 时生效。
|
||||
|
||||
返回: {"success": bool, "message": str}
|
||||
"""
|
||||
try:
|
||||
if text is None or (isinstance(text, str) and not str(text).strip()) \
|
||||
or (isinstance(text, list) and not text):
|
||||
return {'success': False, 'message': '通知文本不能为空'}
|
||||
env_key = (env or 'prod').strip().lower()
|
||||
if env_key not in ENV_CONFIGS:
|
||||
return {'success': False, 'message': f'未知环境 [{env_key}],可选:{" / ".join(ENV_CONFIGS)}'}
|
||||
cfg = ENV_CONFIGS[env_key]
|
||||
webhook = webhook or cfg['webhook']
|
||||
secret = secret or cfg['secret']
|
||||
server_name = server_name or cfg['server_name']
|
||||
if not webhook:
|
||||
return {'success': False, 'message': f'环境 [{env_key}] 的 webhook 未配置,请先在 dingtalk_robot.py 中填写'}
|
||||
robot = DingTalkRobot(webhook=webhook, secret=secret, server_name=server_name)
|
||||
|
||||
items = text if isinstance(text, list) else [text]
|
||||
sent = 0
|
||||
last_title, last_status = title, status
|
||||
for item in items:
|
||||
if isinstance(item, dict) and item.get('blocks') is not None:
|
||||
# 块格式分组:调用方只传格式化好的 block 列表 + 标题,
|
||||
# 分批、加批次标题、逐条推送全部由本模块负责(调用方不关心批次)
|
||||
ti = item.get('title', title)
|
||||
st = item.get('status', status)
|
||||
bs = int(item.get('batch_size', 10) or 10)
|
||||
for batch_content in compose_batch_messages(item['blocks'], ti, bs):
|
||||
robot.send(str(ti), str(batch_content), status=st,
|
||||
server_name=server_name)
|
||||
sent += 1
|
||||
last_title, last_status = ti, st
|
||||
continue
|
||||
if isinstance(item, dict):
|
||||
t = item.get('text')
|
||||
ti = item.get('title', title)
|
||||
st = item.get('status', status)
|
||||
bc = item.get('batch', batch)
|
||||
mc = item.get('max_chars', max_chars)
|
||||
else:
|
||||
t, ti, st, bc, mc = item, title, status, batch, max_chars
|
||||
if t is None or not str(t).strip():
|
||||
continue
|
||||
if bc:
|
||||
robot.send_in_batches(str(ti), str(t), status=st,
|
||||
server_name=server_name, max_chars=mc)
|
||||
else:
|
||||
robot.send(str(ti), str(t), status=st, server_name=server_name)
|
||||
sent += 1
|
||||
last_title, last_status = ti, st
|
||||
if sent == 0:
|
||||
return {'success': False, 'message': '通知文本为空'}
|
||||
if len(items) == 1:
|
||||
return {'success': True, 'message': f'已推送通知 [{env_key}/{last_status}]:{last_title}'}
|
||||
return {'success': True, 'message': f'已推送 {sent} 条通知 [{env_key}]'}
|
||||
except Exception as e:
|
||||
return {'success': False, 'message': str(e)}
|
||||
@@ -1,120 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - 钉钉群通知(业务消息构建 + 推送,口径与影刀版 add_sub_import 一致)。
|
||||
|
||||
推送内容:
|
||||
1. 汇总一条:调度/筛选结果统计 + HR 导入结果(或人工导入提示)+ 注意事项;
|
||||
2. 增员/减员导入异常名单各一条(接口返回的业务异常明细 + 流程失败单元),
|
||||
名单过长由 dingtalk_robot 按批自动分批(每批 10 条)。
|
||||
消息状态色:全部正常 success(绿);有异常/待确认/注意事项 warning(橙);调度全军覆没 error(红)。
|
||||
推送失败只记 WARN 日志,不影响插件主流程。
|
||||
"""
|
||||
from ..config import DINGTALK_ENV, log
|
||||
from . import dingtalk_robot
|
||||
|
||||
TITLE_SUMMARY = "雇主险增减操作完成"
|
||||
|
||||
|
||||
def _import_issues(import_results):
|
||||
"""从 HR 导入结果中提取异常/流程失败明细,按菜单(增员导入/减员导入)分组。
|
||||
|
||||
Returns:
|
||||
dict: {menu: [{"category", "staff_code", "staff_name",
|
||||
"insurance_name", "message"}, ...]}
|
||||
"""
|
||||
grouped = {}
|
||||
for r in import_results or []:
|
||||
menu = r.get("menu") or "导入"
|
||||
if r.get("error"):
|
||||
# 流程失败(登录/元素/文件缺失等):无业务结果,合并为一条异常上报
|
||||
grouped.setdefault(menu, []).append({
|
||||
"category": r.get("category", ""),
|
||||
"staff_code": "", "staff_name": "", "insurance_name": "",
|
||||
"message": f"流程失败({r.get('error_type', 'Exception')}):{r['error']}",
|
||||
})
|
||||
continue
|
||||
for exc in r.get("exceptions") or []:
|
||||
grouped.setdefault(menu, []).append({
|
||||
"category": r.get("category", ""),
|
||||
"staff_code": exc.get("staff_code", ""),
|
||||
"staff_name": exc.get("staff_name", ""),
|
||||
"insurance_name": exc.get("insurance_name", ""),
|
||||
"message": exc.get("message", ""),
|
||||
})
|
||||
return grouped
|
||||
|
||||
|
||||
def _build_messages(total, filtered, scheduled, import_on, import_lines,
|
||||
import_results, notes):
|
||||
"""构建待推送消息列表(汇总 + 异常名单),块格式交由 dingtalk_robot 分批发送。"""
|
||||
issues = _import_issues(import_results)
|
||||
issue_total = sum(len(v) for v in issues.values())
|
||||
|
||||
# ---- 1. 汇总消息 ----
|
||||
summary_lines = [
|
||||
"**处理类别 {} 个:筛选复制成功 {} 个、调度成功 {} 个**".format(
|
||||
total, filtered, scheduled),
|
||||
]
|
||||
if import_on:
|
||||
summary_lines.extend(import_lines or ["HR 导入未执行(登录态缺失或整体失败,详见注意事项与日志)"])
|
||||
else:
|
||||
summary_lines.append("HR 自动导入未开启:请取各类别文件夹内导入文件,先【减员】后【增员】人工导入")
|
||||
blocks = ["\n\n".join(summary_lines)]
|
||||
if notes:
|
||||
blocks.append("**⚠️ 注意事项({})**\n\n{}".format(
|
||||
len(notes), "\n\n".join("> - {}".format(n) for n in notes)))
|
||||
if scheduled == 0:
|
||||
status = "error"
|
||||
elif notes or issue_total:
|
||||
status = "warning"
|
||||
else:
|
||||
status = "success"
|
||||
messages = [{"title": TITLE_SUMMARY, "blocks": blocks, "status": status}]
|
||||
|
||||
# ---- 2. 增员/减员导入异常名单(各一条独立消息) ----
|
||||
for menu, excs in issues.items():
|
||||
if not excs:
|
||||
continue
|
||||
exc_blocks = []
|
||||
for exc in excs:
|
||||
exc_blocks.append(
|
||||
"**🔹 {} / {}**\n\n"
|
||||
"> 工号:{}\n\n"
|
||||
"> 姓名:{}\n\n"
|
||||
"> 方案:{}\n\n"
|
||||
"> 异常:{}".format(
|
||||
exc.get("category", "") or "-",
|
||||
exc.get("staff_name", "") or "-",
|
||||
exc.get("staff_code", "") or "-",
|
||||
exc.get("staff_name", "") or "-",
|
||||
exc.get("insurance_name", "") or "-",
|
||||
exc.get("message", ""),
|
||||
))
|
||||
messages.append({
|
||||
"title": "【{}】异常名单({} 条)".format(menu, len(excs)),
|
||||
"blocks": exc_blocks,
|
||||
"status": "error",
|
||||
})
|
||||
return messages
|
||||
|
||||
|
||||
def push_run_result(total, filtered, scheduled, import_on, import_lines,
|
||||
import_results, notes):
|
||||
"""把本次运行结果推送到钉钉群(环境取 config.DINGTALK_ENV),失败不影响主流程。
|
||||
|
||||
Args:
|
||||
total/filtered/scheduled: 处理/筛选复制/调度成功的类别数
|
||||
import_on: 是否执行了 HR 自动导入
|
||||
import_lines: hr_import.summarize_results 的可读文本行(未执行时传 [])
|
||||
import_results: hr_import.import_all 的逐单元结果(未执行时传 [])
|
||||
notes: 本次运行的注意事项列表
|
||||
"""
|
||||
try:
|
||||
messages = _build_messages(total, filtered, scheduled, import_on,
|
||||
import_lines, import_results, notes)
|
||||
result = dingtalk_robot.main(messages, env=DINGTALK_ENV)
|
||||
if result.get("success"):
|
||||
log(f"钉钉群通知已推送:{result.get('message', '')}", "INFO")
|
||||
else:
|
||||
log(f"钉钉群通知推送失败:{result.get('message', '')}", "WARN")
|
||||
except Exception as e:
|
||||
log(f"钉钉群通知推送失败(不影响主流程):{e}", "WARN")
|
||||
@@ -1,664 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - 结果输出层(由影刀版 employer_insurance_schedule.py 阶段3/五点五 与
|
||||
export_change_sheet.py 合并移植)。
|
||||
|
||||
包含:
|
||||
- output_results:更新「手动维护-在参名单」(第17行起B~N列)+ 精细更新「变更清单」
|
||||
(清空并重写 B/M/N/四级部门/P~S 列)+ 姓名修正记录 + 备份新在参名单;
|
||||
- export_add_sub_import:按「人+投保方案」记录级集合差生成 增员/减员 导入文件;
|
||||
- export_change_sheet_workbook:将类别目标文件「变更清单」sheet 复制为独立工作簿
|
||||
(值+样式,公式转缓存结果,避免 #REF!)。
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
from copy import copy
|
||||
|
||||
import pandas as pd
|
||||
from openpyxl import Workbook, load_workbook
|
||||
|
||||
from ..config import (
|
||||
logger, DATA_START_ROW, BIZ_COL_EMPLOYEE_ID, BIZ_COL_CATEGORY, BIZ_COL_SCHEME,
|
||||
category_import_add_file, category_import_sub_file, category_target_file,
|
||||
category_change_sheet_workbook, category_change_sheet_name,
|
||||
add_import_template, sub_import_template, today_date,
|
||||
to_text, clean_text, to_date,
|
||||
)
|
||||
from ..logic.schedule import _find_special_slots, scheme_with_suffix
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 一、输出结果(在参名单 + 变更清单 + 备份 + 姓名修正)
|
||||
# ============================================================
|
||||
def output_results(final_records, change_log, reused_source_employees, biz_df,
|
||||
in_param_df, column_names, target_file, output_backup,
|
||||
change_sheet_name, change_sheet_prefix, in_param_sheet,
|
||||
name_corrections=None):
|
||||
"""输出四部分内容:
|
||||
1. 更新"手动维护-在参名单"(第17行起B~N列)
|
||||
2. 精细更新"变更清单"(仅清空并重写B/M/N/P~S列数据)
|
||||
3. 备份新在参名单
|
||||
4. 姓名修正记录写入变更清单(批改标志=修改,备注写明「修正姓名,原xx修正为xx」)
|
||||
"""
|
||||
# ---------- 1. 构建需要清空的员工ID集合 ----------
|
||||
emp_ids_to_clear = set()
|
||||
for rec in final_records:
|
||||
emp_ids_to_clear.add(rec["证件号"])
|
||||
emp_ids_to_clear.update(reused_source_employees)
|
||||
|
||||
# 构建初始参保映射:在参名单中存在原投保方案(M列)的员工视为"原已参保"
|
||||
# (不依赖R列方案处理值,避免老员工R列为空/其它值时漏掉"删除原方案"记录)
|
||||
initial_employee_map = {}
|
||||
for _, row in in_param_df.iterrows():
|
||||
emp_id = row.iloc[10]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
orig_scheme = row.iloc[12]
|
||||
if pd.notna(orig_scheme) and str(orig_scheme).strip() != "":
|
||||
initial_employee_map[emp_id] = True
|
||||
|
||||
final_emp_ids = set(rec["证件号"] for rec in final_records)
|
||||
|
||||
# 特殊情况识别(公共函数):离职/参保减少名额被老员工复用,且老员工释放的旧名额无人复用
|
||||
special_slots = _find_special_slots(final_records, in_param_df)
|
||||
special_source_ids = set(s["source_id"] for s in special_slots)
|
||||
special_src_scheme = {s["source_id"]: s["new_scheme"] for s in special_slots}
|
||||
if special_slots:
|
||||
logger.info("特殊情况:离职/参保减少名额被老员工复用,链条末端空闲名额 %d 例(源员工改为空闲方案保留)",
|
||||
len(special_slots))
|
||||
for s in special_slots:
|
||||
logger.info(" 源 %s -> 改为方案 %s", s["source_id"], s["new_scheme"])
|
||||
|
||||
# ---------- 2. 保留的行 ----------
|
||||
handle_col = column_names[17]
|
||||
emp_id_col = column_names[10]
|
||||
keep_mask = (
|
||||
((in_param_df[handle_col] == "无需") & (~in_param_df[emp_id_col].isin(emp_ids_to_clear))) |
|
||||
((in_param_df[handle_col].isin(["离职减少", "参保减少"])) & (~in_param_df[emp_id_col].isin(reused_source_employees))) |
|
||||
(in_param_df[emp_id_col].isin(special_source_ids)) # 特殊情况源员工保留(改M列为老员工旧方案)
|
||||
)
|
||||
kept_df = in_param_df[keep_mask].copy()
|
||||
kept_emp_ids = set(kept_df[emp_id_col].tolist())
|
||||
|
||||
# ---------- 3. 构建员工信息字典 ----------
|
||||
biz_dict = {}
|
||||
for idx, row in biz_df.iterrows():
|
||||
emp_id = row[BIZ_COL_EMPLOYEE_ID]
|
||||
if pd.notna(emp_id):
|
||||
biz_dict[emp_id] = row
|
||||
|
||||
# ---------- 4. 构建新参保记录(B~N列) ----------
|
||||
new_records = []
|
||||
for rec in final_records:
|
||||
emp_id = rec["证件号"]
|
||||
if emp_id not in biz_dict:
|
||||
logger.warning("员工 %s 在花名册中找不到,跳过", emp_id)
|
||||
continue
|
||||
row_biz = biz_dict[emp_id]
|
||||
new_records.append({
|
||||
"B": to_text(row_biz.get("工号")), # B列工号必须为文本
|
||||
"C": row_biz.get("年龄"),
|
||||
"D": row_biz.get("性别"),
|
||||
"E": row_biz.get("岗位"),
|
||||
"F": row_biz.get("职位序列"),
|
||||
"G": row_biz.get("参保类型"),
|
||||
"H": row_biz.get("上下班交通方式"),
|
||||
"I": row_biz.get("入职时间"),
|
||||
"J": row_biz.get("姓名"),
|
||||
"K": row_biz.get("证件号"),
|
||||
"L": row_biz.get("工种类别"),
|
||||
"M": row_biz.get("投保方案"),
|
||||
"N": today_date(),
|
||||
})
|
||||
|
||||
# ---------- 5. 打开工作簿 ----------
|
||||
wb = load_workbook(target_file)
|
||||
ws = wb[in_param_sheet]
|
||||
max_row = ws.max_row
|
||||
|
||||
# ---------- 6. 读取现有数据 ----------
|
||||
existing_rows = []
|
||||
for row_idx in range(DATA_START_ROW, max_row + 1):
|
||||
row_data = []
|
||||
for col in range(1, 27):
|
||||
row_data.append(ws.cell(row=row_idx, column=col).value)
|
||||
existing_rows.append({
|
||||
"row_idx": row_idx,
|
||||
"data": row_data,
|
||||
"emp_id": ws.cell(row=row_idx, column=11).value, # K列
|
||||
})
|
||||
|
||||
# ---------- 7. 构建新数据列表 ----------
|
||||
new_rows = []
|
||||
|
||||
# 姓名修正映射(证件号 -> 新姓名),保留行 J列姓名统一改为花名册姓名
|
||||
corr_by_id = {c["emp_id"]: c["new_name"] for c in (name_corrections or [])}
|
||||
|
||||
# 7.1 保留行
|
||||
for row_info in existing_rows:
|
||||
emp_id = row_info["emp_id"]
|
||||
if emp_id in kept_emp_ids:
|
||||
row_data = row_info["data"]
|
||||
# 特殊情况源员工:M列改为老员工释放的旧方案(X档),N列投保日期更新为今天
|
||||
if emp_id in special_src_scheme:
|
||||
row_data[12] = special_src_scheme[emp_id]
|
||||
row_data[13] = today_date() # N列 投保日期
|
||||
# 姓名核对修正:J列姓名改为花名册姓名
|
||||
if emp_id in corr_by_id:
|
||||
row_data[9] = corr_by_id[emp_id]
|
||||
new_rows.append({
|
||||
"row_idx": row_info["row_idx"],
|
||||
"data": row_data,
|
||||
"emp_id": emp_id,
|
||||
"action": "keep",
|
||||
})
|
||||
|
||||
# 7.2 清空需要替换的行(仅清空B~N列,R/S列不动;特殊情况源员工已保留,此处不清空)
|
||||
for row_info in existing_rows:
|
||||
emp_id = row_info["emp_id"]
|
||||
if (emp_id in emp_ids_to_clear and emp_id not in special_source_ids) or emp_id is None:
|
||||
row_data = row_info["data"].copy()
|
||||
for i in range(1, 14):
|
||||
row_data[i] = None
|
||||
new_rows.append({
|
||||
"row_idx": row_info["row_idx"],
|
||||
"data": row_data,
|
||||
"emp_id": None,
|
||||
"action": "clear",
|
||||
})
|
||||
|
||||
# 7.3 填充新记录到空行
|
||||
empty_slots = [r for r in new_rows if r["action"] == "clear" and r["emp_id"] is None]
|
||||
empty_slots.sort(key=lambda x: x["row_idx"])
|
||||
|
||||
def _fill(row_data, rec):
|
||||
row_data[1] = rec["B"]
|
||||
row_data[2] = rec["C"]
|
||||
row_data[3] = rec["D"]
|
||||
row_data[4] = rec["E"]
|
||||
row_data[5] = rec["F"]
|
||||
row_data[6] = rec["G"]
|
||||
row_data[7] = rec["H"]
|
||||
row_data[8] = rec["I"]
|
||||
row_data[9] = rec["J"]
|
||||
row_data[10] = rec["K"]
|
||||
row_data[11] = rec["L"]
|
||||
row_data[12] = rec["M"]
|
||||
row_data[13] = rec["N"]
|
||||
|
||||
for rec in new_records:
|
||||
if empty_slots:
|
||||
slot = empty_slots.pop(0)
|
||||
row_data = slot["data"]
|
||||
_fill(row_data, rec)
|
||||
slot["emp_id"] = rec["K"]
|
||||
slot["action"] = "filled"
|
||||
else:
|
||||
# 追加新行(复制上一行样式)
|
||||
row_data = [None] * 26
|
||||
if existing_rows:
|
||||
src_row_idx = existing_rows[-1]["row_idx"]
|
||||
for col in range(1, 27):
|
||||
src_cell = ws.cell(row=src_row_idx, column=col)
|
||||
dst_cell = ws.cell(row=max_row + 1, column=col)
|
||||
if src_cell.has_style:
|
||||
dst_cell.font = copy(src_cell.font)
|
||||
dst_cell.border = copy(src_cell.border)
|
||||
dst_cell.fill = copy(src_cell.fill)
|
||||
dst_cell.number_format = src_cell.number_format
|
||||
dst_cell.alignment = copy(src_cell.alignment)
|
||||
last_row_data = existing_rows[-1]["data"]
|
||||
for i in range(14, 26):
|
||||
row_data[i] = last_row_data[i]
|
||||
_fill(row_data, rec)
|
||||
new_rows.append({
|
||||
"row_idx": None,
|
||||
"data": row_data,
|
||||
"emp_id": rec["K"],
|
||||
"action": "append",
|
||||
})
|
||||
|
||||
# ---------- 8. 更新现有行(B~N列,列号=索引+1;B列工号强制文本) ----------
|
||||
for row_info in new_rows:
|
||||
if row_info["row_idx"] is not None:
|
||||
row_idx = row_info["row_idx"]
|
||||
row_data = row_info["data"]
|
||||
for idx in range(1, 14):
|
||||
c = ws.cell(row=row_idx, column=idx + 1)
|
||||
if idx == 1:
|
||||
c.value = to_text(row_data[idx])
|
||||
c.number_format = "@"
|
||||
else:
|
||||
c.value = row_data[idx]
|
||||
|
||||
# ---------- 9. 追加新行 ----------
|
||||
current_row = max_row + 1
|
||||
for row_info in new_rows:
|
||||
if row_info["row_idx"] is None:
|
||||
row_idx = current_row
|
||||
row_data = row_info["data"]
|
||||
for col_idx, value in enumerate(row_data, start=1):
|
||||
c = ws.cell(row=row_idx, column=col_idx)
|
||||
if col_idx == 2:
|
||||
c.value = to_text(value)
|
||||
c.number_format = "@"
|
||||
else:
|
||||
c.value = value
|
||||
current_row += 1
|
||||
|
||||
# ---------- 9.5 紧凑化:消除中间空行(只搬移 B~O 数据列,公式列 R/S/T/U/V/W 不动) ----------
|
||||
data_values = []
|
||||
for row_idx in range(DATA_START_ROW, current_row):
|
||||
has_data = any(
|
||||
ws.cell(row=row_idx, column=c).value not in (None, "")
|
||||
for c in range(2, 16)
|
||||
)
|
||||
if has_data:
|
||||
data_values.append([ws.cell(row=row_idx, column=c).value for c in range(2, 16)])
|
||||
target_row = DATA_START_ROW
|
||||
for vals in data_values:
|
||||
for col, v in enumerate(vals, start=2):
|
||||
cell = ws.cell(row=target_row, column=col)
|
||||
if col == 2: # B列 工号 强制文本
|
||||
cell.value = to_text(v)
|
||||
cell.number_format = "@"
|
||||
elif col == 14: # N列 投保日期 -> 日期类型 + yyyy-mm-dd
|
||||
cell.value = to_date(v)
|
||||
if cell.value is not None:
|
||||
cell.number_format = "yyyy-mm-dd"
|
||||
else:
|
||||
cell.value = v
|
||||
target_row += 1
|
||||
# 清空多出部分的 B~O 列(公式列不动)
|
||||
for row_idx in range(target_row, current_row):
|
||||
for col in range(2, 16):
|
||||
ws.cell(row=row_idx, column=col).value = None
|
||||
|
||||
# ---------- 10. 重新编号A列 ----------
|
||||
seq = 1
|
||||
for row_idx in range(DATA_START_ROW, current_row):
|
||||
if ws.cell(row=row_idx, column=11).value is not None:
|
||||
ws.cell(row=row_idx, column=1).value = seq
|
||||
seq += 1
|
||||
else:
|
||||
ws.cell(row=row_idx, column=1).value = None
|
||||
|
||||
# ============================================================
|
||||
# ★★★ 11. 精细更新变更清单 ★★★
|
||||
# ============================================================
|
||||
if change_sheet_name not in wb.sheetnames:
|
||||
# 收集所有以类别变更清单前缀开头、且不是当前目标名的Sheet作为候选模板
|
||||
candidates = [
|
||||
name for name in wb.sheetnames
|
||||
if name.startswith(change_sheet_prefix) and name != change_sheet_name
|
||||
]
|
||||
|
||||
def _template_sort_key(name):
|
||||
m = re.search(r"(\d{1,2})\.(\d{1,2})", name)
|
||||
return (int(m.group(1)), int(m.group(2))) if m else (-1, -1)
|
||||
|
||||
template_name = max(candidates, key=_template_sort_key) if candidates else None
|
||||
|
||||
if template_name is not None:
|
||||
# 复制最近一次的历史模板Sheet(保留公式与样式)
|
||||
source = wb[template_name]
|
||||
target = wb.copy_worksheet(source)
|
||||
target.title = change_sheet_name
|
||||
logger.info("已从模板 [%s] 复制变更清单", template_name)
|
||||
else:
|
||||
# 没有任何历史模板,创建新Sheet(兜底)
|
||||
ws_change = wb.create_sheet(change_sheet_name)
|
||||
headers = ["序号", "批改标志*", "姓名", "证件类型", "证件号", "年龄",
|
||||
"员工职业类别", "每人责任限额", "方案组别编号", "是否有工伤保险",
|
||||
"工作单位", "", "备注", "批改日期", "新增费用会馆",
|
||||
"姓名", "证件号", "工种类别", "投保方案"]
|
||||
for col_idx, h in enumerate(headers, start=1):
|
||||
ws_change.cell(row=1, column=col_idx).value = h
|
||||
ws_change.cell(row=2, column=1).value = "公式"
|
||||
ws_change = wb[change_sheet_name]
|
||||
else:
|
||||
ws_change = wb[change_sheet_name]
|
||||
|
||||
# ---------- 定位 O列(费用会馆/四级部门列)----------
|
||||
# 表头名不固定(如「新增费用会馆\n(自留后续划成本用)」),按"包含「费用会馆」"模糊匹配
|
||||
DEPT_COL_MARK = "费用会馆"
|
||||
dept_col = 15
|
||||
for _col in range(1, 21):
|
||||
if any(DEPT_COL_MARK in str(ws_change.cell(row=_row, column=_col).value or "")
|
||||
for _row in (1, 2)):
|
||||
dept_col = _col
|
||||
break
|
||||
logger.info("变更清单四级部门列定位:%s(第%d列)", dept_col, dept_col)
|
||||
|
||||
# 花名册表四级部门列名(按"包含「四级部门」"模糊匹配表头,兜底固定名)
|
||||
biz_dept_col = next((c for c in biz_df.columns if "四级部门" in str(c)), "四级部门")
|
||||
|
||||
# 清空B列、M列备注、N列、四级部门列、P~S列 从第3行开始
|
||||
max_row_change = ws_change.max_row
|
||||
if max_row_change >= 3:
|
||||
for row in range(3, max_row_change + 1):
|
||||
ws_change.cell(row=row, column=2).value = None # B列
|
||||
ws_change.cell(row=row, column=13).value = None # M列 备注
|
||||
ws_change.cell(row=row, column=14).value = None # N列
|
||||
ws_change.cell(row=row, column=dept_col).value = None # 四级部门列
|
||||
for col in range(16, 20): # P~S列
|
||||
ws_change.cell(row=row, column=col).value = None
|
||||
|
||||
# 收集变更记录
|
||||
records = []
|
||||
|
||||
# 1. 删除记录(特殊情况源员工一并输出"增加老员工旧方案",保证增减平衡)
|
||||
for emp_id in emp_ids_to_clear:
|
||||
if emp_id in final_emp_ids:
|
||||
continue
|
||||
row_match = in_param_df[in_param_df.iloc[:, 10] == emp_id]
|
||||
if not row_match.empty:
|
||||
row = row_match.iloc[0]
|
||||
name = row.iloc[9]
|
||||
category = row.iloc[11]
|
||||
scheme = row.iloc[12]
|
||||
records.append({"op": "删除", "name": name, "emp_id": emp_id,
|
||||
"category": category, "scheme": scheme})
|
||||
# 特殊情况:源员工名额被老员工复用且老员工旧名额无人复用 -> 源员工改为该旧方案
|
||||
if emp_id in special_src_scheme:
|
||||
records.append({"op": "增加", "name": name, "emp_id": emp_id,
|
||||
"category": category, "scheme": special_src_scheme[emp_id]})
|
||||
else:
|
||||
records.append({"op": "删除", "name": "未知", "emp_id": emp_id,
|
||||
"category": "未知", "scheme": "未知"})
|
||||
|
||||
# 2. 增加记录。档次替换仅当「自己的名额档次替换、不涉及其他人」时合并为一条「修改」
|
||||
# 收集「自己的旧名额被他人复用」的员工集合(来源员工ID)
|
||||
reused_by_others = set()
|
||||
for _rec in final_records:
|
||||
_sid = _rec.get("来源员工ID")
|
||||
if _sid is not None and not pd.isna(_sid) and str(_sid).strip():
|
||||
reused_by_others.add(_sid)
|
||||
for rec in final_records:
|
||||
emp_id = rec["证件号"]
|
||||
if emp_id in biz_dict:
|
||||
row_biz = biz_dict[emp_id]
|
||||
name = row_biz.get("姓名")
|
||||
category = row_biz.get("工种类别")
|
||||
scheme = row_biz.get("投保方案")
|
||||
else:
|
||||
name = category = scheme = None
|
||||
if emp_id in initial_employee_map:
|
||||
# 原已参保(档次替换):仅"自己的名额档次替换、不涉及其他人"才合并为「修改」
|
||||
pure_self_replace = (
|
||||
rec.get("名额来源") == "全新新增" and
|
||||
emp_id not in reused_by_others
|
||||
)
|
||||
row_match = in_param_df[in_param_df.iloc[:, 10] == emp_id]
|
||||
old_scheme = None
|
||||
if not row_match.empty:
|
||||
old_scheme = row_match.iloc[0].iloc[12]
|
||||
if pure_self_replace:
|
||||
remark = None
|
||||
if old_scheme is not None and str(old_scheme).strip() != "" and \
|
||||
scheme is not None and str(scheme).strip() != "":
|
||||
remark = f"由{old_scheme}替换为{scheme}"
|
||||
records.append({"op": "修改", "name": name, "emp_id": emp_id,
|
||||
"category": category, "scheme": scheme, "remark": remark})
|
||||
else:
|
||||
# 涉及其他人的档次替换:正常两条(删除旧方案 + 增加新方案)
|
||||
records.append({"op": "删除", "name": name, "emp_id": emp_id,
|
||||
"category": category, "scheme": old_scheme})
|
||||
records.append({"op": "增加", "name": name, "emp_id": emp_id,
|
||||
"category": category, "scheme": scheme})
|
||||
else:
|
||||
# 新参保人员:仅「全新新增」名额(纯新增,当日名额净增加)在 O列 填四级部门
|
||||
new_rec = {"op": "增加", "name": name, "emp_id": emp_id,
|
||||
"category": category, "scheme": scheme}
|
||||
if rec.get("名额来源") == "全新新增":
|
||||
biz_row_dept = biz_dict.get(emp_id)
|
||||
dept = clean_text(biz_row_dept.get(biz_dept_col)) if biz_row_dept is not None else None
|
||||
if dept is None:
|
||||
# 四级部门为空:回退填所属单位,并记录日志供人工核对
|
||||
dept = clean_text(biz_row_dept.get("所属单位")) if biz_row_dept is not None else None
|
||||
logger.warning("员工 %s(%s) 花名册四级部门为空,O列回退填所属单位:%s",
|
||||
name, emp_id, dept)
|
||||
new_rec["dept"] = dept
|
||||
records.append(new_rec)
|
||||
|
||||
# 写入新记录
|
||||
current_row_change = 3
|
||||
for rec in records:
|
||||
op = rec.get("op")
|
||||
name = rec.get("name")
|
||||
emp_id = rec.get("emp_id")
|
||||
category = rec.get("category")
|
||||
scheme = rec.get("scheme")
|
||||
if name is None or emp_id is None or category is None or scheme is None:
|
||||
logger.warning("跳过变更记录:%s %s 信息不完整", op, emp_id)
|
||||
continue
|
||||
ws_change.cell(row=current_row_change, column=2).value = op # B列
|
||||
ws_change.cell(row=current_row_change, column=13).value = rec.get("remark") # M列 备注
|
||||
ws_change.cell(row=current_row_change, column=14).value = today_date() # N列
|
||||
# 四级部门列:仅纯新增名额(全新新增)的「增加」记录才填
|
||||
if op == "增加" and rec.get("dept") is not None:
|
||||
ws_change.cell(row=current_row_change, column=dept_col).value = rec.get("dept")
|
||||
ws_change.cell(row=current_row_change, column=16).value = name # P列
|
||||
ws_change.cell(row=current_row_change, column=17).value = emp_id # Q列
|
||||
ws_change.cell(row=current_row_change, column=18).value = category # R列
|
||||
ws_change.cell(row=current_row_change, column=19).value = scheme # S列
|
||||
current_row_change += 1
|
||||
|
||||
# 3. 姓名修正记录(批改标志=修改,备注写明「修正姓名,原xx修正为xx」)
|
||||
for corr in (name_corrections or []):
|
||||
ws_change.cell(row=current_row_change, column=2).value = "修改"
|
||||
ws_change.cell(row=current_row_change, column=13).value = \
|
||||
f"修正姓名,原{corr['old_name']}修正为{corr['new_name']}"
|
||||
ws_change.cell(row=current_row_change, column=14).value = today_date()
|
||||
ws_change.cell(row=current_row_change, column=16).value = corr["new_name"]
|
||||
ws_change.cell(row=current_row_change, column=17).value = corr["emp_id"]
|
||||
ws_change.cell(row=current_row_change, column=18).value = corr.get("category")
|
||||
ws_change.cell(row=current_row_change, column=19).value = corr.get("scheme")
|
||||
current_row_change += 1
|
||||
|
||||
# ---------- 12. 保存工作簿 ----------
|
||||
wb.save(target_file)
|
||||
|
||||
# ---------- 13. 备份新在参名单 ----------
|
||||
df_final = pd.DataFrame(final_records)
|
||||
df_final.to_excel(output_backup, index=False)
|
||||
|
||||
logger.info("手动维护-在参名单已更新(保留 %d 个原有员工,清空 %d 个旧员工行,新增 %d 条参保记录)",
|
||||
len(kept_emp_ids), len(emp_ids_to_clear), len(new_records))
|
||||
logger.info("变更清单已精细更新(共 %d 条变更记录,含 %d 条姓名修正)",
|
||||
len(records) + len(name_corrections or []), len(name_corrections or []))
|
||||
logger.info("备份新在参名单已保存:%s", output_backup)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 二、生成增员/减员导入文件(HR「待增减人员」页面上传素材)
|
||||
# ============================================================
|
||||
def _write_import_file(template_path, out_path, rows):
|
||||
"""加载模板(保留第1~3行标题/表头/示例说明),第4行起写数据,另存为 out_path。"""
|
||||
if not os.path.isfile(template_path):
|
||||
raise FileNotFoundError(f"导入模板不存在:{template_path},无法生成导入文件 {out_path}")
|
||||
wb = load_workbook(template_path)
|
||||
ws = wb[wb.sheetnames[0]]
|
||||
for i, row_vals in enumerate(rows):
|
||||
excel_row = 4 + i
|
||||
for col_idx, val in enumerate(row_vals, start=1):
|
||||
c = ws.cell(row=excel_row, column=col_idx)
|
||||
if col_idx == 2: # 工号/身份证列强制文本
|
||||
c.value = to_text(val)
|
||||
c.number_format = "@"
|
||||
else:
|
||||
c.value = val
|
||||
wb.save(out_path)
|
||||
logger.info("已生成导入文件:%s(%d 条)", out_path, len(rows))
|
||||
|
||||
|
||||
def export_add_sub_import(category, biz_df, in_param_df, final_records, reused_source_employees):
|
||||
"""生成各类别「商业保险增员导入.xlsx / 商业保险减员导入.xlsx」(HR 上传素材)。
|
||||
|
||||
集合差模型:按「人 + 投保方案」记录级做差:
|
||||
- 减员 = 原参保记录 − 新参保记录
|
||||
- 增员 = 新参保记录 − 原参保记录
|
||||
离职减少/参保减少名额未被使用 → 新旧记录都在 → 不减员,方便下次直接替换。
|
||||
特殊情况:离职/参保减少名额被老员工复用且老员工旧名额无人复用 -> 源员工保留在
|
||||
参名单并改为空闲方案,该源员工同样纳入增员(新增该方案),保证不漏人。
|
||||
|
||||
★执行顺序:请务必先执行【减员】导入,再执行【增员】导入!涉及替换/修改的人员
|
||||
若先增员会因人员方案冲突直接报错。
|
||||
"""
|
||||
# ---------- 1. 原参保记录集合 ----------
|
||||
orig_records = {} # to_text(证件号) -> 方案
|
||||
for _, row in in_param_df.iterrows():
|
||||
emp_id = row.iloc[10]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
scheme = row.iloc[12]
|
||||
if pd.isna(scheme) or str(scheme).strip() == "":
|
||||
continue
|
||||
orig_records[to_text(emp_id)] = scheme
|
||||
|
||||
# ---------- 2. 新参保记录集合(保留的原记录 + 新增记录 + 特殊情况保留源员工) ----------
|
||||
cleared_ids = set(to_text(e) for e in reused_source_employees)
|
||||
cleared_ids.update(to_text(rec["证件号"]) for rec in final_records)
|
||||
new_records_map = {
|
||||
emp_id: scheme for emp_id, scheme in orig_records.items()
|
||||
if emp_id not in cleared_ids
|
||||
}
|
||||
for rec in final_records:
|
||||
new_records_map[to_text(rec["证件号"])] = rec["投保方案"]
|
||||
# 特殊情况源员工(离职/参保减少名额被复用后保留在参名单,方案改为空闲方案):
|
||||
# 纳入"新参保记录"参与集合差,保证减员/增员对称、不漏人
|
||||
special_slots = _find_special_slots(final_records, in_param_df)
|
||||
for _s in special_slots:
|
||||
new_records_map[to_text(_s["source_id"])] = _s["new_scheme"]
|
||||
|
||||
# ---------- 3. 记录级集合差:减员名单 ----------
|
||||
sub_ids = [
|
||||
emp_id for emp_id, orig_scheme in orig_records.items()
|
||||
if emp_id not in new_records_map or new_records_map[emp_id] != orig_scheme
|
||||
]
|
||||
|
||||
# ---------- 4. 员工信息查询(biz_df 优先,其次 in_param_df) ----------
|
||||
emp_info = {} # to_text(证件号) -> {"工号": ..., "姓名": ...}
|
||||
for _, row in in_param_df.iterrows():
|
||||
emp_id = row.iloc[10]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
emp_info[to_text(emp_id)] = {"工号": to_text(row.iloc[1]), "姓名": row.iloc[9]}
|
||||
for _, row in biz_df.iterrows():
|
||||
emp_id = row[BIZ_COL_EMPLOYEE_ID]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
emp_info[to_text(emp_id)] = {"工号": to_text(row.get("工号")), "姓名": row.get("姓名")}
|
||||
|
||||
def _code(emp_id):
|
||||
"""工号/身份证列:优先工号,空则回退证件号。"""
|
||||
return clean_text(emp_info.get(emp_id, {}).get("工号")) or clean_text(emp_id)
|
||||
|
||||
def _name(emp_id):
|
||||
return clean_text(emp_info.get(emp_id, {}).get("姓名"))
|
||||
|
||||
# ---------- 5. 组装行数据 ----------
|
||||
sub_rows, skipped_sub = [], 0
|
||||
for i, emp_id in enumerate(sub_ids, start=1):
|
||||
name = _name(emp_id)
|
||||
if not name:
|
||||
skipped_sub += 1
|
||||
logger.warning("减员:员工 %s 缺少姓名,跳过", emp_id)
|
||||
continue
|
||||
sub_rows.append([i, _code(emp_id), name, today_date()])
|
||||
|
||||
add_rows, skipped_add, seq = [], 0, 0
|
||||
for rec in final_records:
|
||||
emp_id = to_text(rec["证件号"])
|
||||
name = _name(emp_id)
|
||||
if not name:
|
||||
skipped_add += 1
|
||||
logger.warning("增员:员工 %s 缺少姓名,跳过", emp_id)
|
||||
continue
|
||||
seq += 1
|
||||
add_rows.append([seq, _code(emp_id), name,
|
||||
scheme_with_suffix(category, rec["投保方案"]), today_date(),
|
||||
rec.get("名额来源") or "新增"])
|
||||
# 特殊情况源员工(保留在参名单,方案改为空闲方案)也需增员(新增该方案),不漏人
|
||||
for _s in special_slots:
|
||||
emp_id = to_text(_s["source_id"])
|
||||
new_scheme = _s["new_scheme"]
|
||||
# 方案未变(极少见边界)则无需增员
|
||||
if emp_id in orig_records and orig_records[emp_id] == new_scheme:
|
||||
continue
|
||||
name = _name(emp_id)
|
||||
if not name:
|
||||
skipped_add += 1
|
||||
logger.warning("增员:特殊情况源员工 %s 缺少姓名,跳过", emp_id)
|
||||
continue
|
||||
seq += 1
|
||||
add_rows.append([seq, _code(emp_id), name,
|
||||
scheme_with_suffix(category, new_scheme), today_date(),
|
||||
"特殊情况保留名额"])
|
||||
|
||||
# ---------- 6. 写入模板(保留第1~3行,第4行起填数据) ----------
|
||||
_write_import_file(sub_import_template(), category_import_sub_file(category), sub_rows)
|
||||
_write_import_file(add_import_template(), category_import_add_file(category), add_rows)
|
||||
|
||||
logger.info("类别[%s] 增员 %d 条 / 减员 %d 条(跳过:增员 %d / 减员 %d)",
|
||||
category["name"], len(add_rows), len(sub_rows), skipped_add, skipped_sub)
|
||||
logger.info("执行顺序提醒:请先执行【减员】导入,再执行【增员】导入(涉及替换/修改的人员先增员会因方案冲突报错)")
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 三、导出变更清单独立工作簿(值 + 样式,公式转缓存结果)
|
||||
# ============================================================
|
||||
def export_change_sheet_workbook(category):
|
||||
"""将类别目标文件中「变更清单」sheet 复制为独立工作簿(值 + 样式,无公式)。
|
||||
|
||||
以 data_only=True 加载目标文件:公式单元格直接取缓存计算结果(值),普通单元格
|
||||
取原值;样式 / 列宽 / 行高 / 合并单元格原样保留,不改动原目标文件。
|
||||
|
||||
Returns:
|
||||
bool: 是否成功生成(文件缺失 / sheet 不存在时返回 False)。
|
||||
"""
|
||||
category_name = category["name"]
|
||||
target_file = category_target_file(category)
|
||||
change_sheet_name = category_change_sheet_name(category)
|
||||
out_path = category_change_sheet_workbook(category)
|
||||
|
||||
if not os.path.isfile(target_file):
|
||||
logger.warning("类别[%s] 目标文件不存在,跳过:%s", category_name, target_file)
|
||||
return False
|
||||
|
||||
wb = load_workbook(target_file, data_only=True)
|
||||
if change_sheet_name not in wb.sheetnames:
|
||||
logger.warning("类别[%s] 工作簿中不存在变更清单 sheet [%s],跳过",
|
||||
category_name, change_sheet_name)
|
||||
return False
|
||||
src = wb[change_sheet_name]
|
||||
|
||||
out_wb = Workbook()
|
||||
out_ws = out_wb.active
|
||||
out_ws.title = change_sheet_name
|
||||
|
||||
# 复制单元格(值 + 样式)
|
||||
for row in src.iter_rows():
|
||||
for cell in row:
|
||||
dst = out_ws.cell(row=cell.row, column=cell.column, value=cell.value)
|
||||
if cell.has_style:
|
||||
dst.font = copy(cell.font)
|
||||
dst.border = copy(cell.border)
|
||||
dst.fill = copy(cell.fill)
|
||||
dst.number_format = cell.number_format
|
||||
dst.alignment = copy(cell.alignment)
|
||||
|
||||
# 复制列宽 / 行高
|
||||
for col_letter, dim in src.column_dimensions.items():
|
||||
if dim.width:
|
||||
out_ws.column_dimensions[col_letter].width = dim.width
|
||||
for row_idx, dim in src.row_dimensions.items():
|
||||
if dim.height:
|
||||
out_ws.row_dimensions[row_idx].height = dim.height
|
||||
# 复制合并单元格
|
||||
for mc in src.merged_cells.ranges:
|
||||
out_ws.merge_cells(str(mc))
|
||||
|
||||
out_wb.save(out_path)
|
||||
logger.info("类别[%s] 已导出变更清单独立工作簿:%s(sheet:%s,公式已转为值)",
|
||||
category_name, out_path, change_sheet_name)
|
||||
return True
|
||||
@@ -1,6 +0,0 @@
|
||||
requests
|
||||
pandas
|
||||
openpyxl
|
||||
websocket-client
|
||||
pywin32
|
||||
DrissionPage
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,13 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>雇主险增减操作</title>
|
||||
<script type="module" crossorigin src="/pui/xq0002/assets/index-CAJDpQI-.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0002/assets/index-klWce3Ko.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,195 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 EHR系统请假流程审核 插件入口。
|
||||
|
||||
流程编排(由影刀版 leave_approval.py 移植,登录态改由底座注入):
|
||||
1) 会话准备:底座注入 HR session/userId → getCurUserInfo 校验(失效抛错提示重新登录);
|
||||
2) 拉取「请假」待办(纯接口,无待办不启动浏览器);
|
||||
3) 逐单取表单并校验:Group1 仅比对排班上班天数与填报天数;Group2 另需附件
|
||||
(病假/结婚证/产检 OCR,特殊事假/产假/丧假仅需附件);小时特假校验请假时段
|
||||
是否落在排班班段内(含前一天跨天夜班)+ 已上传附件;
|
||||
4) 校验通过且开启自动审批时,浏览器注入 HR cookies 后点击同意并确认;
|
||||
5) 生成审批报告落盘 + 钉钉群机器人推送(汇总 + 需人工处理明细)。
|
||||
"""
|
||||
import time
|
||||
|
||||
from webhost.backend.plugins.base import ScenePlugin, PLUGINS
|
||||
|
||||
from . import config
|
||||
from .data import hr_api
|
||||
from .data import hr_browser
|
||||
from .logic import leave_rules
|
||||
from .report import leave_report
|
||||
from .report import dingtalk_robot
|
||||
|
||||
|
||||
class LeaveApprovalPlugin(ScenePlugin):
|
||||
"""EHR系统请假流程审核(需求 XQ0003)。"""
|
||||
|
||||
id = "xq0003"
|
||||
name = "EHR系统请假流程审核"
|
||||
version = "1.0.0"
|
||||
description = ("自动审核 EHR 请假待办:按假期类型校验排班上班天数与填报天数是否一致,"
|
||||
"病假/结婚证/产检按附件 OCR 关键词核验,小时特假校验请假时段是否落在排班班段内;"
|
||||
"校验通过自动提交审批,并生成审批报告与钉钉群推送。")
|
||||
platform = "hr"
|
||||
uses_month = False
|
||||
capabilities = ["xq0003"]
|
||||
permissions = {"platforms": ["hr"]}
|
||||
fields = {
|
||||
"save_dir": {
|
||||
"type": "string", "title": "输出目录",
|
||||
"default": config.DEFAULT_SAVE_DIR,
|
||||
"description": "审批报告与服务端附件(附件/ 子目录)统一存放目录",
|
||||
},
|
||||
"approve_enabled": {
|
||||
"type": "boolean", "title": "自动提交审批", "default": True,
|
||||
"description": "开启后,校验结论为「通过」的单据会在流程详情页自动点击同意;关闭则只校验不提交",
|
||||
},
|
||||
"push_enabled": {
|
||||
"type": "boolean", "title": "钉钉群推送", "default": True,
|
||||
"description": "开启后把汇总与需人工处理明细推送到钉钉群机器人",
|
||||
},
|
||||
"dingtalk_webhook": {
|
||||
"type": "string", "title": "钉钉 Webhook", "default": "",
|
||||
"description": "留空使用内置默认机器人;需要发到其他群时填写完整 webhook 地址",
|
||||
},
|
||||
"dingtalk_secret": {
|
||||
"type": "string", "title": "钉钉加签密钥", "default": "",
|
||||
"description": "机器人启用加签安全设置时填写,留空表示不加签",
|
||||
},
|
||||
"debug_mode": {
|
||||
"type": "boolean", "title": "调试日志", "default": False,
|
||||
"description": "开启后输出 OCR 识别明细等调试信息",
|
||||
},
|
||||
}
|
||||
|
||||
def run(self, fields: dict, ctx):
|
||||
# ---- 注入运行上下文:日志 / 进度 / HR 会话 / userId / 输出目录 ----
|
||||
config.set_log(ctx.log)
|
||||
config.set_progress(ctx.progress)
|
||||
config.set_session(ctx.get_session("hr"))
|
||||
config.set_user_id(ctx.get_user_id("hr"))
|
||||
save_dir = (fields.get("save_dir") or "").strip() or config.DEFAULT_SAVE_DIR
|
||||
config.set_save_dir(save_dir)
|
||||
config.set_debug(bool(fields.get("debug_mode")))
|
||||
approve_enabled = bool(fields.get("approve_enabled", True))
|
||||
push_enabled = bool(fields.get("push_enabled", True))
|
||||
webhook = (fields.get("dingtalk_webhook") or "").strip()
|
||||
secret = (fields.get("dingtalk_secret") or "").strip()
|
||||
|
||||
subject = config.DEFAULT_SUBJECT
|
||||
session = config.require_session()
|
||||
ctx.log(f"===== 请假审批启动:输出目录 {save_dir},自动审批={'开' if approve_enabled else '关'} =====",
|
||||
"INFO")
|
||||
|
||||
# ---- 步骤1:会话校验 ----
|
||||
ctx.progress(5)
|
||||
user_id = hr_api.validate_session(session)
|
||||
config.set_user_id(user_id)
|
||||
|
||||
# ---- 步骤2:拉取请假待办 ----
|
||||
ctx.progress(10)
|
||||
docs = hr_api.fetch_documents(session, subject)
|
||||
ctx.log(f"共获取{subject}待办 {len(docs)} 条", "INFO")
|
||||
ctx.progress(15)
|
||||
|
||||
browser = None
|
||||
results = []
|
||||
try:
|
||||
if docs:
|
||||
for idx, doc in enumerate(docs, 1):
|
||||
try:
|
||||
detail = hr_api.fetch_doc_detail(doc)
|
||||
result = leave_rules.validate_doc(detail, session)
|
||||
|
||||
if approve_enabled and result.get("decision") == "通过":
|
||||
if browser is None:
|
||||
browser = hr_browser.build_browser(session)
|
||||
browser.get(detail["detail_url"])
|
||||
time.sleep(1.5) # 等待详情页与审批按钮加载
|
||||
orig_decision = result.get("decision")
|
||||
submit = hr_browser.submit_approval(browser, orig_decision)
|
||||
result["审批动作"] = submit["action"]
|
||||
result["审批结果"] = submit["message"]
|
||||
# 提交失败兜底:单据状态未变,不能仍标为通过,归为「异常」交人工跟进
|
||||
if submit["ok"] == "false":
|
||||
result["decision"] = "异常"
|
||||
result["note"] = (
|
||||
f"机器结论[{orig_decision}]但审批提交失败:{submit['message']}"
|
||||
)
|
||||
ctx.log(f"审批提交: {submit['action']} {submit['message']}", "INFO")
|
||||
elif result.get("decision") != "通过":
|
||||
ctx.log(f"决策为{result.get('decision')},不自动提交审批(待人工处理)", "INFO")
|
||||
|
||||
results.append(result)
|
||||
ctx.log(f"已校验 {idx}/{len(docs)}: {result.get('creator')} - "
|
||||
f"{result.get('title')} -> {result.get('decision')}", "INFO")
|
||||
except Exception as e:
|
||||
ctx.log(f"处理单据失败: {doc.get('title')}, 错误: {e}", "ERROR")
|
||||
results.append({
|
||||
"creator": doc.get("creator", "未知"),
|
||||
"title": doc.get("title", "未知"),
|
||||
"detail_url": doc.get("detail_url", ""),
|
||||
"decision": "失败",
|
||||
"error": str(e),
|
||||
})
|
||||
ctx.progress(15 + int(75 * idx / len(docs)))
|
||||
else:
|
||||
ctx.log(f"{subject}无待审批单据,跳过浏览器操作", "INFO")
|
||||
|
||||
# ---- 步骤3:报告落盘 ----
|
||||
ctx.progress(92)
|
||||
report_text = leave_report.generate_report(results)
|
||||
report_path = leave_report.save_report(report_text, save_dir)
|
||||
ctx.progress(95)
|
||||
|
||||
# ---- 步骤4:钉钉推送 ----
|
||||
push_message = ""
|
||||
if push_enabled:
|
||||
push_items = leave_report.build_push_summary(results, subject)
|
||||
if not push_items:
|
||||
push_items = [{"text": f"暂无待审批的{subject}单据"}]
|
||||
push_res = dingtalk_robot.main(
|
||||
push_items, title=f"【{subject}审批】汇总",
|
||||
webhook=webhook, secret=secret)
|
||||
push_message = push_res.get("message", "")
|
||||
ctx.log(f"钉钉推送: {push_message}", "INFO")
|
||||
ctx.progress(100)
|
||||
|
||||
counts = {
|
||||
"total": len(results),
|
||||
"passed": sum(1 for r in results if r.get("decision") == "通过"),
|
||||
"rejected": sum(1 for r in results if r.get("decision") == "校验不通过未处理"),
|
||||
"review": sum(1 for r in results if r.get("decision") == "人工复核"),
|
||||
"abnormal": sum(1 for r in results if r.get("decision") == "异常"),
|
||||
"failed": sum(1 for r in results if r.get("decision") == "失败"),
|
||||
}
|
||||
if not docs:
|
||||
summary = f"暂无待审批的{subject}单据;报告:{report_path}"
|
||||
else:
|
||||
summary = (f"{subject}审批完成,共 {counts['total']} 单:通过 {counts['passed']},"
|
||||
f"校验不通过未处理 {counts['rejected']},人工复核 {counts['review']}")
|
||||
if counts["abnormal"]:
|
||||
summary += f",审批异常 {counts['abnormal']}"
|
||||
if counts["failed"]:
|
||||
summary += f",处理失败 {counts['failed']}"
|
||||
summary += f";报告:{report_path}"
|
||||
if push_message:
|
||||
summary += f";推送:{push_message}"
|
||||
|
||||
return {
|
||||
"summary": summary,
|
||||
"detail": counts,
|
||||
"path": report_path,
|
||||
"results": results,
|
||||
"save_dir": save_dir,
|
||||
}
|
||||
finally:
|
||||
if browser is not None:
|
||||
try:
|
||||
browser.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
PLUGINS.append(LeaveApprovalPlugin())
|
||||
@@ -1,203 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 EHR系统请假流程审核 插件 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:本包只依赖 Python 标准库 / 第三方库 / 底座注入的 RunContext。
|
||||
所有业务模块统一经 config.logger 输出日志、config.require_session()/require_user_id() 取登录态。
|
||||
登录态由底座注入(hr 平台),插件不自行读 cookies 文件、不做自动补登。
|
||||
"""
|
||||
import os
|
||||
import random
|
||||
import time
|
||||
from functools import wraps
|
||||
|
||||
# ==================== 输出配置 ====================
|
||||
DEFAULT_SAVE_DIR = r"D:\资料\人资\请假流程审批"
|
||||
ATTACHMENT_DIR_NAME = "附件"
|
||||
|
||||
# ==================== HR 系统接口 ====================
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
WE_PROCESS_QUERY_URL = f"{HR_BASE_URL}/RedseaPlatform/WeProcess.mc?method=getProcessAndData"
|
||||
WF_ACTIVITY_URL = f"{HR_BASE_URL}/RedseaPlatform/WfActivity.mc"
|
||||
WORKFORM_ENGINE_URL = f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc"
|
||||
GET_CUR_USER_INFO_URL = f"{HR_BASE_URL}/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
SHIFT_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_p_kq_count_SelectBanci/getExecutePageResult.mc"
|
||||
ATTACHMENT_URL = f"{HR_BASE_URL}/RedseaPlatform/corePlatformOutUser/fjkFileDownload.mob"
|
||||
|
||||
DEFAULT_PAGE_SIZE = 100
|
||||
PAGE_MAX_SIZE = 500
|
||||
DEFAULT_TREE_CODE = "cq37du"
|
||||
DEFAULT_SUBJECT = "请假"
|
||||
|
||||
# 审批按钮:决策 -> (选择器, 按钮文案);仅「通过」会自动提交
|
||||
APPROVE_BUTTONS = {"通过": ("#chooseSubmit", "同意")}
|
||||
|
||||
# ==================== 假期类型编码 → 名称 ====================
|
||||
VACATION_TYPE_MAP = {
|
||||
"04": "病假",
|
||||
"05": "产假",
|
||||
"09": "事假",
|
||||
"11": "调休假",
|
||||
"15": "普通事假",
|
||||
"17": "特殊事假",
|
||||
"18": "小时特假",
|
||||
"19": "普通事假(晚/高峰)",
|
||||
"20": "普通事假(早/中)",
|
||||
"22": "半天休(仅限人资专用)",
|
||||
"23": "特别福利假",
|
||||
"24": "年度福利假",
|
||||
}
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
_progress = None
|
||||
_session = None
|
||||
_user_id = ""
|
||||
_save_dir = DEFAULT_SAVE_DIR
|
||||
_debug = False
|
||||
|
||||
|
||||
def set_log(fn):
|
||||
"""注入 ctx.log(RunContext.log),各模块经 log()/logger 输出。"""
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def log(msg, level="INFO"):
|
||||
if _log:
|
||||
_log(str(msg), level)
|
||||
else:
|
||||
print(f"[{level}] {msg}")
|
||||
|
||||
|
||||
class _ModuleLogger:
|
||||
"""模块级 logger 适配:保留影刀版 logger.info(...) 调用点,统一转发到 ctx.log。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "DEBUG")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "INFO")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "WARN")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "ERROR")
|
||||
|
||||
|
||||
logger = _ModuleLogger()
|
||||
|
||||
|
||||
def set_progress(fn):
|
||||
"""注入 ctx.progress,业务层按阶段上报进度。"""
|
||||
global _progress
|
||||
_progress = fn
|
||||
|
||||
|
||||
def progress(pct):
|
||||
if _progress:
|
||||
try:
|
||||
_progress(int(pct))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def set_session(session):
|
||||
global _session
|
||||
_session = session
|
||||
|
||||
|
||||
def get_session():
|
||||
return _session
|
||||
|
||||
|
||||
def require_session():
|
||||
"""取插件运行期注入的 HR session(缺失抛错,提示先登录 HR)。"""
|
||||
if _session is None:
|
||||
raise RuntimeError("未注入 HR 登录态,请先在壳子(工作台)完成 HR 登录")
|
||||
return _session
|
||||
|
||||
|
||||
def set_user_id(uid):
|
||||
global _user_id
|
||||
_user_id = str(uid or "")
|
||||
|
||||
|
||||
def get_user_id():
|
||||
return _user_id
|
||||
|
||||
|
||||
def require_user_id():
|
||||
if not _user_id:
|
||||
raise RuntimeError("获取当前用户 userId 失败,请重新完成 HR 登录")
|
||||
return _user_id
|
||||
|
||||
|
||||
def set_save_dir(path):
|
||||
global _save_dir
|
||||
_save_dir = (path or "").strip() or DEFAULT_SAVE_DIR
|
||||
|
||||
|
||||
def get_save_dir():
|
||||
return _save_dir
|
||||
|
||||
|
||||
def get_attachment_dir():
|
||||
"""服务端附件本地保存目录:<save_dir>\\附件。"""
|
||||
return os.path.join(_save_dir, ATTACHMENT_DIR_NAME)
|
||||
|
||||
|
||||
def set_debug(flag):
|
||||
global _debug
|
||||
_debug = bool(flag)
|
||||
|
||||
|
||||
def is_debug():
|
||||
return _debug
|
||||
|
||||
|
||||
# ==================== 重试装饰器(全局最大 3 次) ====================
|
||||
class RetryExhaustedError(Exception):
|
||||
"""重试次数耗尽。"""
|
||||
|
||||
|
||||
def retry(max_attempts: int = 3, no_retry_on: tuple = ()):
|
||||
"""指数退避重试:首次失败后 1s、2s、4s(含抖动);连续失败记录错误并抛出。"""
|
||||
|
||||
def decorator(func):
|
||||
@wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
last_exc = None
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
except no_retry_on:
|
||||
raise
|
||||
except Exception as e: # noqa: BLE001 - 统一重试入口
|
||||
last_exc = e
|
||||
if attempt >= max_attempts:
|
||||
break
|
||||
delay = 1.0 * (2 ** (attempt - 1)) * random.uniform(0.5, 1.5)
|
||||
logger.warning("%s 第 %d 次失败,%.1fs 后重试: %s",
|
||||
func.__name__, attempt, delay, e)
|
||||
time.sleep(delay)
|
||||
logger.error("%s 连续 %d 次尝试失败,放弃并记录: %s",
|
||||
func.__name__, max_attempts, last_exc)
|
||||
raise RetryExhaustedError(
|
||||
f"{func.__name__} 连续 {max_attempts} 次失败: {last_exc}") from last_exc
|
||||
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
@@ -1,2 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 请假流程审核 插件 - 数据层。"""
|
||||
@@ -1,356 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 EHR系统请假流程审核 插件 - HR 接口层(由影刀版 leave_approval.py 接口部分移植)。
|
||||
|
||||
链路:
|
||||
1) WeProcess getProcessAndData 查请假流程待办(含 taskId/businessKey/formId)
|
||||
2) WfActivity getWfActivityByTaskId 取 formId(待办行缺失时兜底)
|
||||
3) WorkformEngine getBusinessDate 取请假表单数据
|
||||
4) rf_p_kq_count_SelectBanci 按工号+日期范围取排班(动态列 YYYY-MM-DD_bc_name/bc_time)
|
||||
5) fjkFileDownload.mob 下载表单附件
|
||||
|
||||
插件化改造点(与影刀版差异):
|
||||
1. 纯 requests 调用(底座注入的 requests.Session),不再用 DrissionPage SessionPage;
|
||||
2. 登录态失效统一抛 HRSessionExpiredError,由上层提示重新登录(不自动补登);
|
||||
3. 日志统一转发到 ctx.log(config.logger)。
|
||||
"""
|
||||
import os
|
||||
import time
|
||||
from urllib.parse import unquote
|
||||
|
||||
from ..config import (
|
||||
logger, retry, require_session,
|
||||
HR_BASE_URL, WE_PROCESS_QUERY_URL, WF_ACTIVITY_URL, WORKFORM_ENGINE_URL,
|
||||
GET_CUR_USER_INFO_URL, SHIFT_URL, ATTACHMENT_URL,
|
||||
DEFAULT_PAGE_SIZE, PAGE_MAX_SIZE, DEFAULT_TREE_CODE,
|
||||
)
|
||||
|
||||
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态失效(接口返回非 JSON,被重定向到登录页)。"""
|
||||
|
||||
|
||||
def hr_request_json(session, method, url, params, label, timeout=20):
|
||||
"""POST/GET 请求并校验返回 JSON;非 JSON 视为登录态失效。"""
|
||||
resp = session.request(method.upper(), url, data=params, timeout=timeout)
|
||||
resp.raise_for_status()
|
||||
text = resp.text or ""
|
||||
if not text or not text.lstrip().startswith(("{", "[")):
|
||||
raise HRSessionExpiredError(f"{label}:HR 登录态失效(返回非 JSON)")
|
||||
return resp.json()
|
||||
|
||||
|
||||
def fetch_cur_user_info(session):
|
||||
"""调用 getCurUserInfo,返回 userId / rootId(treecode)。"""
|
||||
return hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
|
||||
|
||||
|
||||
def validate_session(session):
|
||||
"""校验注入的 HR 登录态有效,返回 current userId。"""
|
||||
try:
|
||||
info = fetch_cur_user_info(session)
|
||||
except HRSessionExpiredError:
|
||||
raise RuntimeError("HR 登录态已失效,请重新登录 HR 后再执行") from None
|
||||
user_id = str(info.get("userId") or "") if isinstance(info, dict) else ""
|
||||
if not user_id:
|
||||
raise RuntimeError("HR 登录态无效(getCurUserInfo 未返回 userId),请重新登录 HR")
|
||||
return user_id
|
||||
|
||||
|
||||
# ==================== 请假流程待办 ====================
|
||||
def fetch_we_process_page(session, subject, page_no=1, page_size=DEFAULT_PAGE_SIZE):
|
||||
"""拉一页流程待办(title 按标题模糊匹配)。"""
|
||||
params = {
|
||||
"version": "", "PACKAGE_ID": "cq37du", "process_type": "", "defProcessType": "",
|
||||
"struId": "", "rootId": "cq37du", "taskIds": "", "title": subject,
|
||||
"state": "", "startTime": "", "endTime": "",
|
||||
"sortType": "desc", "sortName": "CREATE_TIME",
|
||||
"commonQuery": "[]", "start": str((page_no - 1) * page_size),
|
||||
"pageNo": str(page_no), "pageSize": str(page_size),
|
||||
}
|
||||
data = hr_request_json(session, "POST", WE_PROCESS_QUERY_URL, params, "WeProcess")
|
||||
if str(data.get("state")) != "1":
|
||||
if str(data.get("state")) == "Nosession" or "会话过期" in str(data.get("meg", "")):
|
||||
raise HRSessionExpiredError(f"WeProcess 返回会话过期: {data.get('meg')}")
|
||||
raise RuntimeError(f"WeProcess 接口返回失败: state={data.get('state')} meg={data.get('meg')}")
|
||||
return data
|
||||
|
||||
|
||||
def parse_we_process_list(data):
|
||||
"""解析待办行为单据字典;detail_url 用 reqType=WAIT(待办审批视图,页面才有审批按钮)。"""
|
||||
docs = []
|
||||
for row in data.get("jsonList") or data.get("datas") or []:
|
||||
title = str(row.get("title") or "").strip()
|
||||
task_id = str(row.get("taskId") or "")
|
||||
business_key = str(row.get("businessKey") or "")
|
||||
process_id = str(row.get("processId") or "")
|
||||
form_id = str(row.get("formId") or "")
|
||||
if not task_id or not business_key:
|
||||
logger.warning("跳过缺 taskId/businessKey 的待办行: %s", title)
|
||||
continue
|
||||
detail_url = (
|
||||
f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc?method=goToWorkFlow"
|
||||
f"&formId={form_id}&businessKey={business_key}&processId={process_id}"
|
||||
f"&taskId={task_id}&reqType=WAIT&headType=&systemId="
|
||||
)
|
||||
docs.append({
|
||||
"title": title,
|
||||
"creator": str(row.get("createUserName") or row.get("createUserNameCn") or "").strip(),
|
||||
"time": str(row.get("createTime") or "").strip(),
|
||||
"taskId": task_id,
|
||||
"businessKey": business_key,
|
||||
"processId": process_id,
|
||||
"formId": form_id,
|
||||
"detail_url": detail_url,
|
||||
})
|
||||
return docs
|
||||
|
||||
|
||||
def get_documents(session, subject, page_size=DEFAULT_PAGE_SIZE):
|
||||
"""分页拉取全部待办,按 taskId 去重。"""
|
||||
all_docs = []
|
||||
page_no = 1
|
||||
while page_no <= 20: # 防御性分页上限
|
||||
data = fetch_we_process_page(session, subject, page_no=page_no, page_size=page_size)
|
||||
docs = parse_we_process_list(data)
|
||||
all_docs.extend(docs)
|
||||
logger.info("第 %d 页获取 %d 条,累计 %d 条", page_no, len(docs), len(all_docs))
|
||||
if len(docs) < page_size:
|
||||
break
|
||||
page_no += 1
|
||||
|
||||
seen = set()
|
||||
unique_docs = []
|
||||
for doc in all_docs:
|
||||
key = doc.get("taskId") or doc.get("detail_url") or doc.get("title")
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
unique_docs.append(doc)
|
||||
|
||||
if len(unique_docs) != len(all_docs):
|
||||
logger.warning("去重前 %d 条,去重后 %d 条(已过滤 %d 条重复单据)",
|
||||
len(all_docs), len(unique_docs), len(all_docs) - len(unique_docs))
|
||||
return unique_docs
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||||
def fetch_documents(session, subject):
|
||||
return get_documents(session, subject=subject)
|
||||
|
||||
|
||||
# ==================== 表单详情 ====================
|
||||
def get_wf_activity_by_task_id(session, task_id):
|
||||
url = f"{WF_ACTIVITY_URL}?method=getWfActivityByTaskId"
|
||||
logger.info("获取 formId: taskId=%s", task_id)
|
||||
try:
|
||||
json_data = hr_request_json(session, "POST", url, {"taskId": task_id}, "WfActivity")
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"WfActivity 接口请求失败: {e}") from e
|
||||
logger.debug("WfActivity 返回: %s", json_data)
|
||||
return json_data
|
||||
|
||||
|
||||
def extract_form_id(wf_activity_data):
|
||||
form_id = (
|
||||
wf_activity_data.get("formId")
|
||||
or wf_activity_data.get("FormId")
|
||||
or wf_activity_data.get("form_id")
|
||||
)
|
||||
if not form_id:
|
||||
for key in ("data", "result"):
|
||||
data_obj = wf_activity_data.get(key, {})
|
||||
if isinstance(data_obj, dict):
|
||||
form_id = data_obj.get("formId") or data_obj.get("FormId") or data_obj.get("form_id")
|
||||
if form_id:
|
||||
break
|
||||
if not form_id:
|
||||
raise ValueError(f"无法从 WfActivity 返回数据中提取 formId: {wf_activity_data}")
|
||||
logger.info("提取到 formId: %s", form_id)
|
||||
return form_id
|
||||
|
||||
|
||||
def get_business_data(session, business_key, form_id):
|
||||
url = f"{WORKFORM_ENGINE_URL}?method=getBusinessDate"
|
||||
logger.info("获取请假表单: businessKey=%s, formId=%s", business_key, form_id)
|
||||
try:
|
||||
json_data = hr_request_json(
|
||||
session, "POST", url,
|
||||
{"businessKey": business_key, "formId": form_id}, "WorkformEngine")
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"WorkformEngine 接口请求失败: {e}") from e
|
||||
|
||||
result = json_data.get("result")
|
||||
if json_data.get("state") != "1" or not isinstance(result, dict):
|
||||
raise RuntimeError(f"WorkformEngine 接口返回失败: {json_data}")
|
||||
logger.info("WorkformEngine 返回成功")
|
||||
return result
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||||
def fetch_doc_detail(doc):
|
||||
"""纯接口取单据详情:taskId/businessKey 直接取自 WeProcess 行(免 SSO 解析)。"""
|
||||
session = require_session()
|
||||
task_id = doc.get("taskId")
|
||||
business_key = doc.get("businessKey")
|
||||
if not task_id or not business_key:
|
||||
raise RuntimeError(f"待办行缺 taskId/businessKey: {doc.get('title')}")
|
||||
|
||||
wf_activity_data = get_wf_activity_by_task_id(session, task_id)
|
||||
form_id = extract_form_id(wf_activity_data)
|
||||
form_data = get_business_data(session, business_key, form_id)
|
||||
return {**doc, "formId": form_id, "formData": form_data}
|
||||
|
||||
|
||||
# ==================== 排班查询 ====================
|
||||
def fetch_shift_page(session, user_id, base_code, begin_date, end_date,
|
||||
treecode=DEFAULT_TREE_CODE, page_no=1, page_size=PAGE_MAX_SIZE):
|
||||
"""请求单页排班数据(按工号 base_code 查询)。"""
|
||||
params = {
|
||||
"treecode": treecode,
|
||||
"user_id": user_id,
|
||||
"sqlId": "kq_count_SelectBanci",
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"staff_ids": "",
|
||||
"person_status": "1,4",
|
||||
"post_no": "",
|
||||
"post_type": "1",
|
||||
"post_level": "",
|
||||
"identity": "",
|
||||
"showType": "1",
|
||||
"dateType": "1",
|
||||
"begin": begin_date,
|
||||
"end": end_date,
|
||||
"bc_date": begin_date,
|
||||
"base_code": base_code,
|
||||
"staff_name": "",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", SHIFT_URL, params, "排班")
|
||||
|
||||
|
||||
def fetch_all_shift(session, user_id, base_code, begin_date, end_date,
|
||||
treecode=DEFAULT_TREE_CODE):
|
||||
"""分页抓取指定工号、日期范围内的全部排班记录。"""
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_shift_page(
|
||||
session, user_id, base_code, begin_date, end_date,
|
||||
treecode, page_no, PAGE_MAX_SIZE)
|
||||
except HRSessionExpiredError:
|
||||
raise RuntimeError("排班接口 HR 登录态失效,请重新登录 HR 后再执行") from None
|
||||
if data.get("state") != "1":
|
||||
logger.error("排班第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("排班无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("排班已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
def get_day_shift(shift_rows, date_str):
|
||||
"""从排班记录中提取指定日期的班次信息(动态列 YYYY-MM-DD_bc_name/bc_time)。"""
|
||||
info = {"bc_name": "", "bc_time": ""}
|
||||
for rec in shift_rows:
|
||||
name = rec.get(f"{date_str}_bc_name")
|
||||
time_ = rec.get(f"{date_str}_bc_time")
|
||||
if name or time_:
|
||||
info = {
|
||||
"bc_name": str(name if name is not None else ""),
|
||||
"bc_time": str(time_ if time_ is not None else ""),
|
||||
}
|
||||
break
|
||||
return info
|
||||
|
||||
|
||||
# ==================== 附件下载 ====================
|
||||
def download_attachment(session, file_id, save_dir):
|
||||
"""按附件 fileId 下载(兼容逗号分隔多附件),返回逗号拼接路径串;全失败返回 None。"""
|
||||
if not file_id:
|
||||
logger.warning("附件 fileId 为空,跳过下载")
|
||||
return None
|
||||
ids = [x.strip() for x in str(file_id).split(",") if x.strip()]
|
||||
saved = []
|
||||
for fid in ids:
|
||||
path = _download_one(session, fid, save_dir)
|
||||
if path:
|
||||
saved.append(path)
|
||||
if not saved:
|
||||
return None
|
||||
return ",".join(saved)
|
||||
|
||||
|
||||
def _download_one(session, file_id, save_dir):
|
||||
"""下载单个附件 fileId,返回本地保存路径;失败返回 None。"""
|
||||
if not file_id:
|
||||
return None
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
download_url = f"{ATTACHMENT_URL}?fileId={file_id}"
|
||||
try:
|
||||
resp = session.get(download_url, timeout=60)
|
||||
except Exception as e:
|
||||
logger.warning("附件请求失败(fileId=%s): %s", file_id, e)
|
||||
return None
|
||||
if resp is None or resp.status_code != 200:
|
||||
logger.warning("附件下载失败: HTTP %s (fileId=%s)",
|
||||
getattr(resp, "status_code", "?"), file_id)
|
||||
return None
|
||||
|
||||
# 从 Content-Disposition 解析真实文件名(可能带 UTF-8'' 编码)
|
||||
filename = None
|
||||
cd = resp.headers.get("Content-Disposition", "")
|
||||
if "filename=" in cd:
|
||||
raw = cd.split("filename=")[-1].strip().strip('"')
|
||||
if raw.startswith("UTF-8''"):
|
||||
raw = unquote(raw.split("UTF-8''", 1)[1])
|
||||
else:
|
||||
try:
|
||||
raw = raw.encode('latin-1').decode('utf-8')
|
||||
except (UnicodeDecodeError, UnicodeEncodeError):
|
||||
pass
|
||||
if raw:
|
||||
filename = raw
|
||||
|
||||
# 解析不到文件名时,用 fileId 兜底,并按 Content-Type 补扩展名
|
||||
if not filename:
|
||||
filename = file_id
|
||||
ct = (resp.headers.get("Content-Type") or "").split(";")[0].strip().lower()
|
||||
ext_map = {
|
||||
"image/png": ".png",
|
||||
"image/jpeg": ".jpg",
|
||||
"application/pdf": ".pdf",
|
||||
"application/octet-stream": ".bin",
|
||||
}
|
||||
filename += ext_map.get(ct, ".bin")
|
||||
|
||||
# 清理非法字符,防止路径注入
|
||||
filename = "".join(c for c in filename if c not in '\\/:*?"<>|')
|
||||
path = os.path.join(save_dir, filename)
|
||||
# 多附件可能出现同名文件导致覆盖:追加 fileId 短后缀区分
|
||||
counter = 1
|
||||
base, ext = os.path.splitext(filename)
|
||||
while os.path.exists(path):
|
||||
path = os.path.join(save_dir, f"{base}_{file_id[:8]}_{counter}{ext}")
|
||||
counter += 1
|
||||
with open(path, "wb") as f:
|
||||
f.write(resp.content)
|
||||
logger.info("附件已下载: %s", path)
|
||||
return path
|
||||
@@ -1,124 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 EHR系统请假流程审核 插件 - 浏览器审批层。
|
||||
|
||||
用途:表单数据全部走接口,仅在「通过」需要真实点击审批按钮时才启动浏览器。
|
||||
登录态来自底座注入的 requests.Session(hr 平台),插件不自行读 cookies 文件、不自动补登。
|
||||
"""
|
||||
import time
|
||||
|
||||
from ..config import logger, APPROVE_BUTTONS
|
||||
|
||||
|
||||
def _cookies_from_session(session):
|
||||
"""把注入 session 的 cookies 转成 DrissionPage 可用的 cookie 字典列表。"""
|
||||
cookies = []
|
||||
if session is None:
|
||||
return cookies
|
||||
try:
|
||||
jar = session.cookies
|
||||
except Exception:
|
||||
return cookies
|
||||
for c in jar:
|
||||
domain = str(c.domain or "")
|
||||
if domain and "37du.co" not in domain:
|
||||
continue
|
||||
cookies.append({
|
||||
"name": c.name,
|
||||
"value": c.value,
|
||||
"domain": domain or ".37du.co",
|
||||
"path": c.path or "/",
|
||||
})
|
||||
return cookies
|
||||
|
||||
|
||||
def build_browser(session):
|
||||
"""创建 ChromiumPage 并注入 HR 登录态;cookies 为空时抛错(提示先登录 HR)。"""
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
cookies = _cookies_from_session(session)
|
||||
if not cookies:
|
||||
raise RuntimeError("未获取到 HR 登录 cookies,请先在壳子(工作台)完成 HR 登录后再执行")
|
||||
page = ChromiumPage(ChromiumOptions())
|
||||
page.set.cookies(cookies)
|
||||
logger.info("浏览器已启动并注入 HR cookies:%d 个", len(cookies))
|
||||
return page
|
||||
|
||||
|
||||
def _find_button(page, selector, timeout=3.0):
|
||||
"""在详情页查找审批按钮:优先主文档,找不到则遍历 iframe。"""
|
||||
try:
|
||||
btn = page.ele(selector, timeout=timeout)
|
||||
if btn:
|
||||
return btn
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
frames = page.get_frames()
|
||||
except Exception:
|
||||
frames = []
|
||||
for frame in frames:
|
||||
try:
|
||||
btn = frame.ele(selector, timeout=1)
|
||||
if btn:
|
||||
return btn
|
||||
except Exception:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def submit_approval(page, decision):
|
||||
"""按校验结论执行真实审批提交。
|
||||
|
||||
Args:
|
||||
page: 停留在单据详情页的 ChromiumPage
|
||||
decision: 校验决策(仅「通过」会自动提交,其余不提交)
|
||||
|
||||
Returns:
|
||||
{"action": "同意"/"-", "ok": "true"/"false", "message": ...}
|
||||
"""
|
||||
if decision not in APPROVE_BUTTONS:
|
||||
return {"action": "-", "ok": "true", "message": "无需提交"}
|
||||
selector, label = APPROVE_BUTTONS[decision]
|
||||
try:
|
||||
btn = _find_button(page, selector)
|
||||
if btn is None:
|
||||
msg = f"未找到审批按钮 {selector}({label}),可能页面未加载完成或按钮在未识别的 iframe 中"
|
||||
logger.error(msg)
|
||||
return {"action": label, "ok": "false", "message": msg}
|
||||
logger.info("点击审批按钮: %s(%s)", selector, label)
|
||||
btn.click()
|
||||
|
||||
def _visible(el):
|
||||
try:
|
||||
return el.states.is_displayed
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
# 普通流程确认框 #custom-confirm-modal-ok 为主;选人弹窗 .wf-select-people 为特殊单据才触发
|
||||
confirm = None
|
||||
for _ in range(20):
|
||||
c1 = page.ele("#custom-confirm-modal-ok", timeout=0.2)
|
||||
if c1 is not None and _visible(c1):
|
||||
confirm = c1
|
||||
break
|
||||
people = page.ele(".wf-select-people", timeout=0.2)
|
||||
if people is not None and _visible(people):
|
||||
try:
|
||||
c2 = people.ele("css:.modal-footer button.btn.btn-primary", timeout=0.2)
|
||||
except Exception:
|
||||
c2 = None
|
||||
if c2 is not None and _visible(c2):
|
||||
confirm = c2
|
||||
break
|
||||
time.sleep(0.2)
|
||||
if confirm is None:
|
||||
msg = "未找到确认框确定按钮(#custom-confirm-modal-ok 或 .modal-footer .btn.btn-primary),审批未提交"
|
||||
logger.error(msg)
|
||||
return {"action": label, "ok": "false", "message": msg}
|
||||
confirm.click()
|
||||
logger.info("已点击确认框确定按钮")
|
||||
time.sleep(1.0)
|
||||
return {"action": label, "ok": "true", "message": f"已执行审批提交[{label}]"}
|
||||
except Exception as e:
|
||||
logger.error("审批提交失败[%s]: %s", label, str(e))
|
||||
return {"action": label, "ok": "false", "message": f"审批提交[{label}]失败: {e}"}
|
||||
@@ -1,2 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 请假流程审核 插件 - 业务规则层。"""
|
||||
@@ -1,375 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 EHR系统请假流程审核 插件 - 请假校验规则(由影刀版移植)。
|
||||
|
||||
校验分组:
|
||||
Group 1(事假/调休假等):排班上班天数与填报天数一致 -> 通过
|
||||
Group 2(病假/产假等):天数一致 + 附件(OCR/仅附件)-> 通过
|
||||
小时特假:请假时段须完整落在排班班段内(含前一天跨天夜班)+ 已上传附件
|
||||
"""
|
||||
import math
|
||||
import re
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from ..config import logger, require_session, require_user_id, get_attachment_dir, VACATION_TYPE_MAP
|
||||
from ..data.hr_api import fetch_all_shift, get_day_shift, download_attachment
|
||||
from .ocr import check_leave_attachment, check_leave_attachment_detail, marriage_within_one_year
|
||||
|
||||
# 按小时请假的假期类型:不比对天数,按请假时段判断是否落在排班班段内
|
||||
HOURLY_LEAVE_TYPES = {
|
||||
"小时特假",
|
||||
}
|
||||
|
||||
# Group 1:仅校验排班上班天数与填报天数一致
|
||||
LEAVE_TYPE_GROUP_1 = {
|
||||
"事假", "调休假", "半天休(仅限人资专用)",
|
||||
"普通事假", "普通事假(早/中)", "普通事假(晚/高峰)",
|
||||
"年度福利假",
|
||||
}
|
||||
|
||||
# Group 2:校验天数一致 + 需上传附件
|
||||
LEAVE_TYPE_GROUP_2 = {
|
||||
"病假", "特别福利假", "特殊事假", "产假",
|
||||
}
|
||||
|
||||
|
||||
# ==================== 表单解析 ====================
|
||||
def _first_non_null(result, *keys):
|
||||
"""返回第一个值非 None 的字段(不能用 or 链:0 / 0.0 / "" 是合法值但为 falsy)。"""
|
||||
for k in keys:
|
||||
v = result.get(k)
|
||||
if v is not None:
|
||||
return v
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_vacation_type(result):
|
||||
raw = _first_non_null(result, "vacation_type", "leave_type", "sub_type")
|
||||
raw = str(raw).strip() if raw is not None else ""
|
||||
if raw in VACATION_TYPE_MAP:
|
||||
return VACATION_TYPE_MAP[raw]
|
||||
return raw
|
||||
|
||||
|
||||
def parse_leave_form(result):
|
||||
"""把 WorkformEngine 表单数据解析为统一的中文键字典。"""
|
||||
return {
|
||||
"请假人员ID": result.get("staff_id"),
|
||||
"工号": result.get("staff_code"),
|
||||
"请假人员": result.get("staff_name"),
|
||||
"组织全路径": result.get("org_full_path"),
|
||||
"岗位": result.get("post_name"),
|
||||
"假期类型": _resolve_vacation_type(result),
|
||||
# 开始日期优先 start_date(跨天/夜班场景 begin_date 可能取成申请日导致起止倒挂)
|
||||
"开始日期": result.get("start_date") or result.get("begin_date"),
|
||||
"开始时间": result.get("start_time"),
|
||||
"开始段": result.get("begin_other_name"),
|
||||
"结束日期": result.get("end_date"),
|
||||
"结束时间": result.get("end_time"),
|
||||
"结束段": result.get("end_other_name"),
|
||||
"请假天数": _first_non_null(result, "leave_days", "leave_day", "leave_days_new", "ot_day"),
|
||||
"请假小时": _first_non_null(result, "leave_hours", "leave_hour", "ot_hour"),
|
||||
"请假原因": result.get("leave_reason"),
|
||||
"附件": result.get("file"),
|
||||
}
|
||||
|
||||
|
||||
def _get_hr_context():
|
||||
"""取注入的 HR 会话与 userId(失败抛错提示重新登录)。"""
|
||||
return require_session(), require_user_id()
|
||||
|
||||
|
||||
# ==================== 天数校验 ====================
|
||||
def _get_date_range(begin_date, end_date):
|
||||
start_date = begin_date[:10] if begin_date else None
|
||||
end_date = end_date[:10] if end_date else None
|
||||
return start_date, end_date
|
||||
|
||||
|
||||
def _get_work_days_count(start_date, end_date, staff_code):
|
||||
"""获取请假区间内实际上班天数(休息与否只以 bc_name 为准)。"""
|
||||
session, user_id = _get_hr_context()
|
||||
rows = fetch_all_shift(session, user_id, staff_code, start_date, end_date)
|
||||
if not rows:
|
||||
raise RuntimeError("未能获取到任何排班数据")
|
||||
|
||||
work_days = []
|
||||
current = datetime.strptime(start_date, "%Y-%m-%d")
|
||||
end_dt = datetime.strptime(end_date, "%Y-%m-%d")
|
||||
while current <= end_dt:
|
||||
day = current.strftime("%Y-%m-%d")
|
||||
info = get_day_shift(rows, day)
|
||||
bc_name = info["bc_name"]
|
||||
if bc_name and not bc_name.startswith("休息"):
|
||||
work_days.append(day)
|
||||
current += timedelta(days=1)
|
||||
|
||||
logger.info("请假区间 %s ~ %s,实际上班天数: %d", start_date, end_date, len(work_days))
|
||||
return len(work_days)
|
||||
|
||||
|
||||
# ==================== 小时假校验 ====================
|
||||
def _parse_leave_time(value):
|
||||
"""解析 "YYYY-MM-DD HH:MM[:SS]" -> (date, 当日分钟数);解析失败返回 None。"""
|
||||
if not value:
|
||||
return None
|
||||
m = re.search(r"(\d{4})-(\d{1,2})-(\d{1,2})[ T](\d{1,2}):(\d{2})", str(value))
|
||||
if not m:
|
||||
return None
|
||||
try:
|
||||
day = datetime(int(m.group(1)), int(m.group(2)), int(m.group(3))).date()
|
||||
except ValueError:
|
||||
return None
|
||||
return day, int(m.group(4)) * 60 + int(m.group(5))
|
||||
|
||||
|
||||
def _shift_min_range(bc_time):
|
||||
"""解析班段时间 "09:00 ~ 18:00" -> (开始分钟, 结束分钟);跨天夜班 end<start。"""
|
||||
if not bc_time:
|
||||
return None
|
||||
m = re.search(r"(\d{1,2}):(\d{2})\s*~\s*(\d{1,2}):(\d{2})", str(bc_time))
|
||||
if not m:
|
||||
return None
|
||||
return int(m.group(1)) * 60 + int(m.group(2)), int(m.group(3)) * 60 + int(m.group(4))
|
||||
|
||||
|
||||
def _fmt_min(m):
|
||||
return f"{m // 60:02d}:{m % 60:02d}"
|
||||
|
||||
|
||||
def _hourly_leave_within_shift(shift_rows, leave_date, leave_end_date, start_min, end_min):
|
||||
"""判断小时假请假时段是否完整落在某天排班班段内(含前一天跨天夜班)。
|
||||
|
||||
返回 (是否通过, 命中班段日期, 命中bc_time)。
|
||||
"""
|
||||
end_abs = end_min + (leave_end_date - leave_date).days * 1440
|
||||
if end_abs < start_min:
|
||||
end_abs += 1440 # 请假自身跨天兜底
|
||||
for delta in (0, -1):
|
||||
day = (leave_date + timedelta(days=delta)).strftime("%Y-%m-%d")
|
||||
info = get_day_shift(shift_rows, day)
|
||||
r = _shift_min_range(info["bc_time"])
|
||||
if r is None:
|
||||
continue
|
||||
s, e = r
|
||||
base = delta * 1440
|
||||
if s == 0 and e == 0:
|
||||
iv = (base, base + 1440) # 全天班(罕见)
|
||||
elif e < s:
|
||||
iv = (base + s, base + e + 1440) # 跨天夜班
|
||||
else:
|
||||
iv = (base + s, base + e) # 当日班段
|
||||
if iv[0] <= start_min and end_abs <= iv[1]:
|
||||
return True, day, info["bc_time"]
|
||||
return False, None, None
|
||||
|
||||
|
||||
def _validate_hourly_leave(result, session, leave_info, staff_code, attachment, vacation_type):
|
||||
"""小时特假校验:请假时段完整落在排班班段内(含前一天跨天夜班)+ 已上传附件。"""
|
||||
leave_hours = leave_info.get("请假小时")
|
||||
leave_start = _parse_leave_time(leave_info.get("开始时间"))
|
||||
leave_end = _parse_leave_time(leave_info.get("结束时间"))
|
||||
|
||||
if leave_start is None:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "无法解析请假开始时间"
|
||||
return result
|
||||
if leave_end is None:
|
||||
leave_end = leave_start
|
||||
|
||||
try:
|
||||
hr_session, user_id = _get_hr_context()
|
||||
query_start = (leave_start[0] - timedelta(days=1)).strftime("%Y-%m-%d")
|
||||
query_end = leave_end[0].strftime("%Y-%m-%d")
|
||||
shift_rows = fetch_all_shift(hr_session, user_id, staff_code, query_start, query_end)
|
||||
except Exception as e:
|
||||
logger.warning("小时假获取排班数据失败: %s", str(e))
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = f"获取排班数据失败: {e}"
|
||||
return result
|
||||
|
||||
ok, hit_day, hit_bc = _hourly_leave_within_shift(
|
||||
shift_rows, leave_start[0], leave_end[0], leave_start[1], leave_end[1])
|
||||
|
||||
if not ok:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = (
|
||||
f"请假时段 {_fmt_min(leave_start[1])}~{_fmt_min(leave_end[1])} "
|
||||
f"未落在请假当天({query_end})或前一天({query_start})的排班班段内"
|
||||
)
|
||||
return result
|
||||
|
||||
if not attachment:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "未上传附件"
|
||||
return result
|
||||
|
||||
result["decision"] = "通过"
|
||||
result["附件路径"] = download_attachment(session, attachment, get_attachment_dir())
|
||||
result["leave_info"]["排班班段"] = f"{hit_day} {hit_bc}"
|
||||
result["note"] = (
|
||||
f"审批通过(假期类型: {vacation_type},请假小时: {leave_hours},"
|
||||
f"请假时段 {_fmt_min(leave_start[1])}~{_fmt_min(leave_end[1])} 落在排班班段 "
|
||||
f"{hit_day} {hit_bc} 内,附件已上传)"
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
# ==================== 附件校验 ====================
|
||||
def _verify_attachment(session, vacation_type, reason, file_id):
|
||||
"""按假期类型校验附件内容,返回 (decision, note, attachment_path)。"""
|
||||
path = download_attachment(session, file_id, get_attachment_dir())
|
||||
if not path:
|
||||
return "人工复核", "附件下载失败,需人工核验", None
|
||||
|
||||
paths = [p for p in path.split(",") if p]
|
||||
if not paths:
|
||||
return "人工复核", "附件下载失败,需人工核验", None
|
||||
logger.info("附件校验开始: vacation_type=%s, 附件数=%d, 路径=%s", vacation_type, len(paths), paths)
|
||||
|
||||
def _first_hit(checker):
|
||||
return next((p for p in paths if checker(p)), None)
|
||||
|
||||
def _kw_hint(p, leave_type):
|
||||
"""返回该附件 OCR 命中的关键词列表(顿号拼接),用于备注便于人工判断。"""
|
||||
_, hits, _ = check_leave_attachment_detail(p, leave_type)
|
||||
return "、".join(hits) if hits else ""
|
||||
|
||||
if vacation_type == "病假":
|
||||
hit = _first_hit(lambda p: check_leave_attachment(p, "sick"))
|
||||
if hit:
|
||||
kw_desc = f"(命中关键词: {_kw_hint(hit, 'sick')})" if _kw_hint(hit, "sick") else ""
|
||||
return "通过", f"附件OCR检测通过(病假,共{len(paths)}份){kw_desc}", path
|
||||
return "人工复核", f"共{len(paths)}份附件OCR均未命中病假关键词,需人工核验", path
|
||||
|
||||
if vacation_type == "特别福利假":
|
||||
reason = reason or ""
|
||||
if "婚" in reason:
|
||||
hit = None
|
||||
reg_kw = ""
|
||||
for p in paths:
|
||||
ok, _, hits = check_leave_attachment_detail(p, "marriage")
|
||||
if ok:
|
||||
hit = p
|
||||
reg_kw = "、".join(hits)
|
||||
break
|
||||
if hit is None:
|
||||
return "人工复核", f"共{len(paths)}份附件OCR均未命中结婚证关键词,需人工核验", path
|
||||
ok, reg_date = marriage_within_one_year(hit)
|
||||
kw_desc = f"(命中关键词: {reg_kw})" if reg_kw else ""
|
||||
if ok:
|
||||
return "通过", f"结婚证OCR检测通过,登记日期{reg_date}在1年内{kw_desc}", path
|
||||
return "人工复核", f"结婚登记日期{reg_date if reg_date else '未识别'}不在1年内{kw_desc},需人工核验", path
|
||||
if "产" in reason or "孕" in reason:
|
||||
hit = _first_hit(lambda p: check_leave_attachment(p, "maternity"))
|
||||
if hit:
|
||||
kw_desc = f"(命中关键词: {_kw_hint(hit, 'maternity')})" if _kw_hint(hit, "maternity") else ""
|
||||
return "通过", f"产检附件OCR检测通过(共{len(paths)}份){kw_desc}", path
|
||||
return "人工复核", f"共{len(paths)}份附件OCR均未命中产检关键词,需人工核验", path
|
||||
if "丧" in reason:
|
||||
return "通过", f"丧假附件已上传({len(paths)}份)", path
|
||||
return "人工复核", f"特别福利假具体类型无法识别(理由: {reason}),需人工核验", path
|
||||
|
||||
# 特殊事假 / 产假:有附件即通过
|
||||
return "通过", f"附件已上传({len(paths)}份)", path
|
||||
|
||||
|
||||
# ==================== 单据校验入口 ====================
|
||||
def validate_doc(doc, session):
|
||||
"""校验单张请假单据,返回审批决策字典。"""
|
||||
form_data = doc.get("formData", {}) or {}
|
||||
leave_info = parse_leave_form(form_data)
|
||||
|
||||
staff_id = leave_info.get("请假人员ID")
|
||||
staff_code = leave_info.get("工号")
|
||||
vacation_type = leave_info.get("假期类型")
|
||||
begin_date = leave_info.get("开始日期")
|
||||
end_date = leave_info.get("结束日期")
|
||||
leave_days = leave_info.get("请假天数")
|
||||
attachment = leave_info.get("附件")
|
||||
is_hourly = vacation_type in HOURLY_LEAVE_TYPES
|
||||
|
||||
result = {
|
||||
"title": doc.get("title", ""),
|
||||
"creator": doc.get("creator", ""),
|
||||
"time": doc.get("time", ""),
|
||||
"detail_url": doc.get("detail_url", ""),
|
||||
"decision": "通过",
|
||||
"note": "",
|
||||
"leave_info": leave_info,
|
||||
}
|
||||
|
||||
if not vacation_type:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "无法识别假期类型"
|
||||
return result
|
||||
|
||||
if not staff_id:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "请假人员ID缺失"
|
||||
return result
|
||||
|
||||
if not staff_code:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "请假人工号缺失"
|
||||
return result
|
||||
|
||||
# 小时假(如小时特假)不走天数比对,提前按请假时段校验排班班段
|
||||
if is_hourly:
|
||||
return _validate_hourly_leave(result, session, leave_info, staff_code, attachment, vacation_type)
|
||||
|
||||
start_date, end_date = _get_date_range(begin_date, end_date)
|
||||
if not start_date or not end_date:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "请假起止日期缺失"
|
||||
return result
|
||||
|
||||
try:
|
||||
actual_work_days = _get_work_days_count(start_date, end_date, staff_code)
|
||||
except Exception as e:
|
||||
logger.warning("计算上班天数失败: %s", str(e))
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = f"获取排班数据失败: {e}"
|
||||
return result
|
||||
|
||||
try:
|
||||
fill_days = float(leave_days) if leave_days else 0
|
||||
except (TypeError, ValueError):
|
||||
fill_days = 0
|
||||
|
||||
leave_info["实际上班天数"] = actual_work_days
|
||||
leave_info["填报天数"] = fill_days
|
||||
|
||||
# 请半天假(0.5天)仍占用1个排班上班日,故用向上取整比对
|
||||
days_mismatch = actual_work_days != math.ceil(round(fill_days, 2))
|
||||
|
||||
if vacation_type in LEAVE_TYPE_GROUP_1:
|
||||
if days_mismatch:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = f"排班上班天数({actual_work_days}天)与填报天数({fill_days}天)不一致"
|
||||
else:
|
||||
result["decision"] = "通过"
|
||||
result["note"] = (
|
||||
f"审批通过(假期类型: {vacation_type},上班天数: {actual_work_days},"
|
||||
f"填报天数: {fill_days})"
|
||||
)
|
||||
|
||||
elif vacation_type in LEAVE_TYPE_GROUP_2:
|
||||
# 需附件的假期:天数一致 + 附件内容校验(OCR/仅附件);无法确认 -> 人工复核
|
||||
reasons = []
|
||||
if days_mismatch:
|
||||
reasons.append(f"排班上班天数({actual_work_days}天)与填报天数({fill_days}天)不一致")
|
||||
if not attachment:
|
||||
reasons.append("未上传附件")
|
||||
|
||||
if reasons:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = ";".join(reasons)
|
||||
else:
|
||||
result["decision"], result["note"], result["附件路径"] = _verify_attachment(
|
||||
session, vacation_type, leave_info.get("请假原因"), attachment
|
||||
)
|
||||
else:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = f"无法识别的假期类型: {vacation_type}"
|
||||
|
||||
return result
|
||||
@@ -1,265 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 EHR系统请假流程审核 插件 - 附件 OCR 校验(可选依赖,懒初始化)。
|
||||
|
||||
行为与影刀版一致:病假/婚假/产检假按关键词命中检测,结婚证按登记日期判断 1 年内。
|
||||
插件化差异:rapidocr/onnxruntime 属可选依赖,首次使用时才初始化引擎;
|
||||
缺库或初始化失败时优雅降级(返回 False / 空),由上层转为「人工复核」,不崩溃。
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
from datetime import datetime
|
||||
|
||||
from ..config import logger, is_debug
|
||||
|
||||
_OCR_LEAVE_KEYWORDS = {
|
||||
# 病假/医疗类:对应医院诊断证明、病历、检验单等
|
||||
"sick": {
|
||||
"医院", "门诊", "就诊", "诊断", "病历", "医嘱", "病假", "病情",
|
||||
"检查", "检验", "处方", "诊断证明", "疾病", "治疗", "医技报告单",
|
||||
},
|
||||
# 婚假类:对应结婚证、婚姻登记证明
|
||||
"marriage": {
|
||||
"结婚证", "婚姻登记", "结婚登记", "持证人", "婚姻登记机关",
|
||||
"婚姻证", "中华人民共和国结婚证",
|
||||
},
|
||||
# 产检假类:对应产检报告、B超单、妊娠诊断证明
|
||||
"maternity": {
|
||||
"医院", "门诊", "就诊", "诊断", "病历", "医嘱", "病假", "病情",
|
||||
"检查", "检验", "处方", "诊断证明", "疾病", "治疗", "医技报告单",
|
||||
"产检", "产前检查", "孕检", "妊娠", "怀孕", "孕周", "预产期",
|
||||
"超声检查", "B超", "胎儿", "产科", "孕期", "产前筛查", "胎心",
|
||||
},
|
||||
}
|
||||
_OCR_CONFIDENCE_THRESHOLD = 0.5
|
||||
_OCR_VALID_TYPES = set(_OCR_LEAVE_KEYWORDS.keys()) | {"all"}
|
||||
|
||||
_ocr_engine = None # 已初始化的引擎
|
||||
_ocr_init_failed = False # 初始化失败标记:避免每张附件重复尝试导入/初始化
|
||||
_ocr_legacy = False # True = rapidocr_onnxruntime(返回 (结果列表, 耗时) 元组)
|
||||
|
||||
|
||||
def ocr_available():
|
||||
"""OCR 是否可用(可触发懒初始化)。"""
|
||||
return _ensure_engine() is not None
|
||||
|
||||
|
||||
def _ensure_engine():
|
||||
"""懒初始化 OCR 引擎;缺库或失败返回 None(上层降级为人工复核)。
|
||||
|
||||
优先 rapidocr(>=3.x,影刀版同款,结果对象带 boxes/txts/scores),
|
||||
其次 rapidocr_onnxruntime(老包,返回 (结果列表, 耗时) 元组)。
|
||||
"""
|
||||
global _ocr_engine, _ocr_init_failed, _ocr_legacy
|
||||
if _ocr_engine is not None:
|
||||
return _ocr_engine
|
||||
if _ocr_init_failed:
|
||||
return None
|
||||
try:
|
||||
from rapidocr import RapidOCR
|
||||
_ocr_engine = RapidOCR()
|
||||
_ocr_legacy = False
|
||||
logger.info("OCR 引擎初始化成功(rapidocr)")
|
||||
return _ocr_engine
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
from rapidocr_onnxruntime import RapidOCR
|
||||
_ocr_engine = RapidOCR()
|
||||
_ocr_legacy = True
|
||||
logger.info("OCR 引擎初始化成功(rapidocr_onnxruntime)")
|
||||
except Exception as e:
|
||||
_ocr_init_failed = True
|
||||
_ocr_engine = None
|
||||
logger.warning("OCR 引擎不可用(附件转人工复核): %s", e)
|
||||
return _ocr_engine
|
||||
|
||||
|
||||
def _ocr_read_text(file_path, debug=False):
|
||||
"""OCR 识别图片,返回 (清洗后拼接文本, 原始拼接文本)。"""
|
||||
engine = _ensure_engine()
|
||||
if engine is None:
|
||||
logger.warning("OCR 引擎未初始化,跳过识别: %s", file_path)
|
||||
raise RuntimeError("OCR 引擎未初始化(rapidocr 缺失或初始化失败)")
|
||||
if not os.path.isfile(file_path):
|
||||
logger.warning("OCR 附件文件不存在,跳过识别: %s", file_path)
|
||||
raise FileNotFoundError(f"附件文件不存在: {file_path}")
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image, ImageEnhance, ImageOps
|
||||
|
||||
with Image.open(file_path) as img:
|
||||
# 应用 EXIF 方向信息,修正手机横拍导致的旋转
|
||||
img = ImageOps.exif_transpose(img)
|
||||
gray_img = img.convert("L")
|
||||
enhancer = ImageEnhance.Contrast(gray_img)
|
||||
enhanced_img = enhancer.enhance(2.0)
|
||||
img_array = np.array(enhanced_img)
|
||||
|
||||
result = engine(img_array)
|
||||
if _ocr_legacy or isinstance(result, tuple):
|
||||
# rapidocr_onnxruntime: ([ [box, text, score], ... ], 耗时)
|
||||
res_list = result[0] if isinstance(result, tuple) else result
|
||||
txts, scores = [], []
|
||||
for item in (res_list or []):
|
||||
try:
|
||||
txts.append(str(item[1]))
|
||||
scores.append(float(item[2]))
|
||||
except (IndexError, TypeError, ValueError):
|
||||
continue
|
||||
else:
|
||||
txts = getattr(result, "txts", None)
|
||||
scores = getattr(result, "scores", None)
|
||||
if txts is None:
|
||||
txts = ()
|
||||
if scores is None:
|
||||
scores = ()
|
||||
|
||||
logger.info("【OCR识别结果】文件: %s, 识别到 %d 个文本块", os.path.basename(file_path), len(txts))
|
||||
if debug or is_debug():
|
||||
for idx, (txt, score) in enumerate(zip(txts, scores)):
|
||||
logger.info(" [%02d] 置信度:%.3f | 文本: %s", idx, score, txt)
|
||||
|
||||
raw_text = ""
|
||||
full_text = ""
|
||||
for text, score in zip(txts, scores):
|
||||
if score < _OCR_CONFIDENCE_THRESHOLD:
|
||||
continue
|
||||
raw_text += text
|
||||
full_text += text.replace(" ", "").replace("\u3000", "")
|
||||
|
||||
# 过滤乱码特殊符号,保留常用字符
|
||||
clean_pattern = re.compile(r'[^\u4e00-\u9fa5a-zA-Z0-9,。!?;:、《》“”‘’()【】.,;:!?年月日]')
|
||||
full_text = clean_pattern.sub('', full_text)
|
||||
return full_text, raw_text
|
||||
|
||||
|
||||
def _target_keywords(leave_type):
|
||||
if leave_type == "all":
|
||||
target = set()
|
||||
for kw_set in _OCR_LEAVE_KEYWORDS.values():
|
||||
target.update(kw_set)
|
||||
return target
|
||||
return _OCR_LEAVE_KEYWORDS[leave_type]
|
||||
|
||||
|
||||
def check_leave_attachment(file_path, leave_type="sick", debug=False):
|
||||
"""检测附件图片是否包含对应假期关键词;文件异常/识别失败/未命中均返回 False。"""
|
||||
if leave_type not in _OCR_VALID_TYPES:
|
||||
return False
|
||||
if not os.path.isfile(file_path):
|
||||
return False
|
||||
if _ensure_engine() is None:
|
||||
logger.warning("OCR 不可用,附件转人工复核: %s", file_path)
|
||||
return False
|
||||
|
||||
try:
|
||||
full_text, _ = _ocr_read_text(file_path, debug=debug)
|
||||
except Exception as e:
|
||||
logger.warning("OCR 识别异常(leave_type=%s): %s", leave_type, e)
|
||||
return False
|
||||
|
||||
if debug:
|
||||
logger.info("【清洗后匹配文本】\n%s\n%s", full_text, "=" * 60)
|
||||
|
||||
hit_words = [kw for kw in _target_keywords(leave_type) if kw in full_text]
|
||||
if debug:
|
||||
logger.info("【命中关键词】: %s", hit_words)
|
||||
return len(hit_words) > 0
|
||||
|
||||
|
||||
def check_leave_attachment_detail(file_path, leave_type="sick", debug=False):
|
||||
"""检测附件是否命中关键词,返回 (是否命中, 命中关键词列表, OCR全文)。"""
|
||||
if leave_type not in _OCR_VALID_TYPES:
|
||||
return False, [], ""
|
||||
if not os.path.isfile(file_path):
|
||||
return False, [], ""
|
||||
if _ensure_engine() is None:
|
||||
logger.warning("OCR 不可用,附件转人工复核: %s", file_path)
|
||||
return False, [], ""
|
||||
|
||||
try:
|
||||
full_text, raw_text = _ocr_read_text(file_path, debug=debug)
|
||||
except Exception as e:
|
||||
logger.warning("OCR 识别异常(leave_type=%s): %s", leave_type, e)
|
||||
return False, [], ""
|
||||
|
||||
hit_words = [kw for kw in _target_keywords(leave_type) if kw in full_text]
|
||||
logger.info("【OCR关键词匹配】假期类型: %s, 命中: %s", leave_type, hit_words if hit_words else "无")
|
||||
return len(hit_words) > 0, hit_words, raw_text
|
||||
|
||||
|
||||
def _ocr_extract_dates(text):
|
||||
"""从文本中提取所有日期,支持 "20XX年X月X日"、"XXXX-XX-XX"、"XXXX/XX/XX" 等格式。"""
|
||||
dates = []
|
||||
patterns = [
|
||||
r'(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日?',
|
||||
r'(\d{4})\s*[-/.年]\s*(\d{1,2})\s*[-/.月]\s*(\d{1,2})\s*日?',
|
||||
]
|
||||
for pat in patterns:
|
||||
for m in re.finditer(pat, text):
|
||||
try:
|
||||
dates.append(datetime(int(m.group(1)), int(m.group(2)), int(m.group(3))).date())
|
||||
except ValueError:
|
||||
continue
|
||||
return dates
|
||||
|
||||
|
||||
def _ocr_extract_registration_date(text):
|
||||
"""从结婚证文本中提取"登记日期"字段对应的日期;找不到返回 None。"""
|
||||
reg_match = re.search(r'登记日期', text)
|
||||
if not reg_match:
|
||||
return None
|
||||
|
||||
text_after = text[reg_match.end():]
|
||||
date_patterns = [
|
||||
r'(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日?',
|
||||
r'(\d{4})\s*[-/.年]\s*(\d{1,2})\s*[-/.月]\s*(\d{1,2})\s*日?',
|
||||
]
|
||||
for pat in date_patterns:
|
||||
m = re.search(pat, text_after)
|
||||
if m:
|
||||
try:
|
||||
return datetime(int(m.group(1)), int(m.group(2)), int(m.group(3))).date()
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def marriage_within_one_year(file_path, today=None, debug=False):
|
||||
"""识别结婚证登记日期并判断是否在当前日期 1 年内。
|
||||
|
||||
优先查找"登记日期"关键词附近的日期,找不到则取识别到的最大日期兜底。
|
||||
返回 (是否1年内, 登记日期)。
|
||||
"""
|
||||
if today is None:
|
||||
today = datetime.now().date()
|
||||
if not os.path.isfile(file_path):
|
||||
return False, None
|
||||
if _ensure_engine() is None:
|
||||
logger.warning("OCR 不可用,结婚证登记日期转人工复核: %s", file_path)
|
||||
return False, None
|
||||
|
||||
try:
|
||||
full_text, _ = _ocr_read_text(file_path, debug=debug)
|
||||
except Exception as e:
|
||||
if debug:
|
||||
logger.warning("[识别异常] %s", e)
|
||||
return False, None
|
||||
|
||||
dates = _ocr_extract_dates(full_text)
|
||||
if not dates:
|
||||
if debug:
|
||||
logger.info("【未识别到任何日期】")
|
||||
return False, None
|
||||
|
||||
reg_date = _ocr_extract_registration_date(full_text)
|
||||
if reg_date is None:
|
||||
reg_date = max(dates)
|
||||
if debug:
|
||||
logger.info("【未找到登记日期关键词,使用最大日期兜底】")
|
||||
|
||||
ok = reg_date <= today and (today - reg_date).days <= 365
|
||||
if debug:
|
||||
logger.info("【识别日期】: %s", dates)
|
||||
logger.info("【登记日期】: %s,1年内: %s", reg_date, ok)
|
||||
return ok, reg_date
|
||||
@@ -1,58 +0,0 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0003",
|
||||
"name": "EHR系统请假流程审核",
|
||||
"version": "1.0.0",
|
||||
"description": "自动审核 EHR 请假待办:拉取待办与请假表单,按假期类型校验排班上班天数与填报天数是否一致,病假/产假等按附件 OCR 关键词核验(病假/结婚证/产检),小时特假校验请假时段是否落在排班班段内;校验通过自动提交审批,并生成审批报告与钉钉群推送。",
|
||||
"category": "人事考勤",
|
||||
"icon": "",
|
||||
"platform": "hr",
|
||||
"uses_month": false,
|
||||
"ui": true,
|
||||
"capabilities": ["xq0003"],
|
||||
"permissions": {
|
||||
"platforms": ["hr"]
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"save_dir": {
|
||||
"type": "string",
|
||||
"title": "输出目录",
|
||||
"default": "D:\\资料\\人资\\请假流程审批",
|
||||
"description": "审批报告与服务端附件(附件/ 子目录)统一存放目录"
|
||||
},
|
||||
"approve_enabled": {
|
||||
"type": "boolean",
|
||||
"title": "自动提交审批",
|
||||
"default": true,
|
||||
"description": "开启后,校验结论为「通过」的单据会在流程详情页自动点击同意;关闭则只校验不提交"
|
||||
},
|
||||
"push_enabled": {
|
||||
"type": "boolean",
|
||||
"title": "钉钉群推送",
|
||||
"default": true,
|
||||
"description": "开启后把汇总与需人工处理明细推送到钉钉群机器人"
|
||||
},
|
||||
"dingtalk_webhook": {
|
||||
"type": "string",
|
||||
"title": "钉钉 Webhook",
|
||||
"default": "",
|
||||
"description": "留空使用内置默认机器人;需要发到其他群时填写完整 webhook 地址"
|
||||
},
|
||||
"dingtalk_secret": {
|
||||
"type": "string",
|
||||
"title": "钉钉加签密钥",
|
||||
"default": "",
|
||||
"description": "机器人启用加签安全设置时填写,留空表示不加签"
|
||||
},
|
||||
"debug_mode": {
|
||||
"type": "boolean",
|
||||
"title": "调试日志",
|
||||
"default": false,
|
||||
"description": "开启后输出 OCR 识别明细等调试信息"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 请假流程审核 插件 - 报告与推送层。"""
|
||||
@@ -1,230 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 EHR系统请假流程审核 插件 - 钉钉群机器人推送(自 XQ0034 移植,插件内单一真源)。
|
||||
|
||||
推送原理(HTTP Webhook,零第三方依赖,仅标准库,符合插件自包含约束):
|
||||
按钉钉加签规则(HMAC-SHA256 + Base64 + URL 编码)生成签名,
|
||||
向机器人 Webhook 推送 Markdown 消息,失败自动重试 3 次。
|
||||
|
||||
约定:
|
||||
- 默认 webhook/加签密钥来自插件字段(UI 配置),字段为空时回退本文件默认配置;
|
||||
- env='dev' 走测试环境机器人,避免调试时误发生产群。
|
||||
|
||||
用法:
|
||||
main("需要推送的通知文本");
|
||||
text 传「块格式分组」字典列表 [{title, blocks, status?}] 时由本模块自动分批逐条推送。
|
||||
返回: {"success": bool, "message": str}
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime
|
||||
|
||||
from ..config import logger
|
||||
|
||||
# ==================== 默认配置 ====================
|
||||
DEFAULT_WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=65dd3f38dea12d2419743aad62ed25f5544ae1ff2ff7d2f667682e0dc912ff6e'
|
||||
DEFAULT_SECRET = '' # 加签密钥(未配置则不加签)
|
||||
DEFAULT_SERVER_NAME = '37du 任务调度平台'
|
||||
|
||||
# 测试环境配置(env='dev' 时使用;默认使用 DEFAULT_WEBHOOK)
|
||||
DEV_WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=26613569642db03fae6fd19cc932a4b08d82fd09afd35ccfd3ddee5884b5cb66'
|
||||
DEV_SECRET = ''
|
||||
DEV_SERVER_NAME = '37du 任务调度平台'
|
||||
|
||||
ENV_CONFIGS = {
|
||||
'prod': {'webhook': DEFAULT_WEBHOOK, 'secret': DEFAULT_SECRET, 'server_name': DEFAULT_SERVER_NAME},
|
||||
'dev': {'webhook': DEV_WEBHOOK, 'secret': DEV_SECRET, 'server_name': DEV_SERVER_NAME},
|
||||
}
|
||||
|
||||
DEFAULT_TIMEOUT = 10
|
||||
DEFAULT_RETRY_TIMES = 3
|
||||
|
||||
_STATUS_COLORS = {
|
||||
'info': '#0077ff',
|
||||
'success': '#00b300',
|
||||
'warning': '#ff9900',
|
||||
'error': '#ff0000',
|
||||
}
|
||||
|
||||
|
||||
def _build_sign(secret, timestamp_ms):
|
||||
"""按钉钉加签规则计算签名(HMAC-SHA256 + Base64 + URL 编码)。"""
|
||||
string_to_sign = f"{timestamp_ms}\n{secret}"
|
||||
hmac_code = hmac.new(
|
||||
secret.encode('utf-8'), string_to_sign.encode('utf-8'), digestmod=hashlib.sha256
|
||||
).digest()
|
||||
return urllib.parse.quote_plus(base64.b64encode(hmac_code))
|
||||
|
||||
|
||||
def _build_url(webhook, secret=''):
|
||||
"""拼接最终推送地址:配置了 secret 时追加 timestamp + sign 参数。"""
|
||||
if not secret:
|
||||
return webhook
|
||||
ts = int(round(time.time() * 1000))
|
||||
separator = '&' if '?' in webhook else '?'
|
||||
return f"{webhook}{separator}timestamp={ts}&sign={_build_sign(secret, ts)}"
|
||||
|
||||
|
||||
class DingTalkRobot:
|
||||
"""钉钉群机器人推送器。"""
|
||||
|
||||
def __init__(self, webhook='', secret='', server_name='', timeout=DEFAULT_TIMEOUT):
|
||||
self.webhook = (webhook or DEFAULT_WEBHOOK).strip()
|
||||
self.secret = (secret or DEFAULT_SECRET).strip()
|
||||
self.server_name = (server_name or DEFAULT_SERVER_NAME).strip()
|
||||
self.timeout = timeout
|
||||
if not self.webhook:
|
||||
raise ValueError('webhook 不能为空')
|
||||
|
||||
def _post(self, payload):
|
||||
"""推送 payload 到机器人,errcode != 0 视为失败;失败自动重试。"""
|
||||
last_err = None
|
||||
for attempt in range(DEFAULT_RETRY_TIMES):
|
||||
try:
|
||||
url = _build_url(self.webhook, self.secret)
|
||||
data = json.dumps(payload, ensure_ascii=False).encode('utf-8')
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=data,
|
||||
headers={'Content-Type': 'application/json; charset=utf-8'},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
||||
body = resp.read().decode('utf-8')
|
||||
resp_data = json.loads(body)
|
||||
if resp_data.get('errcode') != 0:
|
||||
raise RuntimeError(
|
||||
f"钉钉机器人返回错误 errcode={resp_data.get('errcode')}, "
|
||||
f"errmsg={resp_data.get('errmsg')}"
|
||||
)
|
||||
return
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
logger.warning("推送失败(第 %d/%d 次):%s", attempt + 1, DEFAULT_RETRY_TIMES, e)
|
||||
time.sleep(1)
|
||||
raise RuntimeError(f"推送失败,重试 {DEFAULT_RETRY_TIMES} 次后仍出错:{last_err}")
|
||||
|
||||
def send(self, title, content, status='info', server_name=''):
|
||||
"""发送统一通知(Markdown:标题按状态着色,正文直接渲染,带页脚)。"""
|
||||
color = _STATUS_COLORS.get(status, _STATUS_COLORS['info'])
|
||||
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
||||
display_name = (server_name or self.server_name).strip()
|
||||
footer = f"\n\n---\n\n###### {display_name} | {now}"
|
||||
|
||||
text = f"**<font color='{color}'>{title}</font>**\n\n"
|
||||
text += content.strip() + "\n"
|
||||
text += footer
|
||||
|
||||
payload = {'msgtype': 'markdown', 'markdown': {'title': title, 'text': text}}
|
||||
logger.info("钉钉机器人推送通知 [%s]: %s", status, title)
|
||||
self._post(payload)
|
||||
|
||||
def send_in_batches(self, title, content, status='info', server_name='',
|
||||
max_chars=15000):
|
||||
"""分批发送长内容(按行智能拆分,避免切断单行数据)。"""
|
||||
lines = content.strip().split('\n')
|
||||
batches = []
|
||||
current_batch = []
|
||||
current_len = 0
|
||||
|
||||
for line in lines:
|
||||
line_len = len(line) + 1
|
||||
if current_len + line_len > max_chars and current_batch:
|
||||
batches.append('\n'.join(current_batch))
|
||||
current_batch = [line]
|
||||
current_len = line_len
|
||||
else:
|
||||
current_batch.append(line)
|
||||
current_len += line_len
|
||||
|
||||
if current_batch:
|
||||
batches.append('\n'.join(current_batch))
|
||||
|
||||
total = len(batches)
|
||||
for i, batch_content in enumerate(batches, 1):
|
||||
batch_title = f"{title}(第{i}/{total}批)" if total > 1 else title
|
||||
logger.info("分批推送 %d/%d: %s", i, total, batch_title)
|
||||
self.send(batch_title, batch_content, status=status, server_name=server_name)
|
||||
|
||||
|
||||
def compose_batch_messages(blocks, title_prefix, batch_size=10):
|
||||
"""把块格式 block 列表按 batch_size 条一批,生成带批次标题的消息文本列表。"""
|
||||
if not blocks:
|
||||
return []
|
||||
result = []
|
||||
total_batches = (len(blocks) + batch_size - 1) // batch_size
|
||||
for bi in range(total_batches):
|
||||
batch = blocks[bi * batch_size:(bi + 1) * batch_size]
|
||||
header = f"###### {title_prefix}(第{bi + 1}/{total_batches}批)\n\n"
|
||||
footer = f"\n\n###### 本批共{len(batch)}条"
|
||||
content = header + '\n\n'.join(batch) + footer
|
||||
result.append(content)
|
||||
return result
|
||||
|
||||
|
||||
def main(text, title='消息通知', status='info', webhook='', secret='', server_name='',
|
||||
env='prod', batch=False, max_chars=15000):
|
||||
"""钉钉群机器人推送入口。
|
||||
|
||||
text 支持:
|
||||
- 纯文本:单条 Markdown 推送;
|
||||
- 字典列表 {title, blocks, status?, batch_size?}:块格式分组,自动分批逐条推送;
|
||||
- 文本列表:按顺序逐条发送。
|
||||
|
||||
返回: {"success": bool, "message": str}
|
||||
"""
|
||||
try:
|
||||
if text is None or (isinstance(text, str) and not str(text).strip()) \
|
||||
or (isinstance(text, list) and not text):
|
||||
return {'success': False, 'message': '通知文本不能为空'}
|
||||
env_key = (env or 'prod').strip().lower()
|
||||
if env_key not in ENV_CONFIGS:
|
||||
return {'success': False, 'message': f'未知环境 [{env_key}],可选:{" / ".join(ENV_CONFIGS)}'}
|
||||
cfg = ENV_CONFIGS[env_key]
|
||||
webhook = (webhook or '').strip() or cfg['webhook']
|
||||
secret = (secret or '').strip() or cfg['secret']
|
||||
server_name = server_name or cfg['server_name']
|
||||
if not webhook:
|
||||
return {'success': False, 'message': f'环境 [{env_key}] 的 webhook 未配置'}
|
||||
robot = DingTalkRobot(webhook=webhook, secret=secret, server_name=server_name)
|
||||
|
||||
items = text if isinstance(text, list) else [text]
|
||||
sent = 0
|
||||
last_title, last_status = title, status
|
||||
for item in items:
|
||||
if isinstance(item, dict) and item.get('blocks') is not None:
|
||||
ti = item.get('title', title)
|
||||
st = item.get('status', status)
|
||||
bs = int(item.get('batch_size', 10) or 10)
|
||||
for batch_content in compose_batch_messages(item['blocks'], ti, bs):
|
||||
robot.send(str(ti), str(batch_content), status=st, server_name=server_name)
|
||||
sent += 1
|
||||
last_title, last_status = ti, st
|
||||
continue
|
||||
if isinstance(item, dict):
|
||||
t = item.get('text')
|
||||
ti = item.get('title', title)
|
||||
st = item.get('status', status)
|
||||
bc = item.get('batch', batch)
|
||||
mc = item.get('max_chars', max_chars)
|
||||
else:
|
||||
t, ti, st, bc, mc = item, title, status, batch, max_chars
|
||||
if t is None or not str(t).strip():
|
||||
continue
|
||||
if bc:
|
||||
robot.send_in_batches(str(ti), str(t), status=st,
|
||||
server_name=server_name, max_chars=mc)
|
||||
else:
|
||||
robot.send(str(ti), str(t), status=st, server_name=server_name)
|
||||
sent += 1
|
||||
last_title, last_status = ti, st
|
||||
if sent == 0:
|
||||
return {'success': False, 'message': '通知文本为空'}
|
||||
if len(items) == 1:
|
||||
return {'success': True, 'message': f'已推送通知 [{env_key}/{last_status}]:{last_title}'}
|
||||
return {'success': True, 'message': f'已推送 {sent} 条通知 [{env_key}]'}
|
||||
except Exception as e:
|
||||
return {'success': False, 'message': str(e)}
|
||||
@@ -1,205 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 EHR系统请假流程审核 插件 - 报告生成与推送摘要(由影刀版移植)。"""
|
||||
import os
|
||||
from datetime import datetime
|
||||
|
||||
from ..config import logger
|
||||
|
||||
|
||||
def _name(r):
|
||||
info = r.get("leave_info", {}) or {}
|
||||
return info.get("请假人员") or r.get("creator") or "未知"
|
||||
|
||||
|
||||
def _vtype(r):
|
||||
info = r.get("leave_info", {}) or {}
|
||||
return info.get("假期类型") or "未知"
|
||||
|
||||
|
||||
def _format_detail(info):
|
||||
"""将 leave_info 字典格式化为易读的明细行。"""
|
||||
fields = [
|
||||
("请假人员", "请假人员"),
|
||||
("工号", "工号"),
|
||||
("岗位", "岗位"),
|
||||
("组织全路径", "组织全路径"),
|
||||
("假期类型", "假期类型"),
|
||||
("开始日期", "开始日期"),
|
||||
("开始段", "开始段"),
|
||||
("结束日期", "结束日期"),
|
||||
("结束段", "结束段"),
|
||||
("请假天数", "请假天数"),
|
||||
("请假小时", "请假小时"),
|
||||
("排班班段", "排班班段"),
|
||||
("实际上班天数", "实际上班天数"),
|
||||
("填报天数", "填报天数"),
|
||||
("附件", "附件"),
|
||||
]
|
||||
parts = []
|
||||
for key, label in fields:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
parts.append(f"{label}={val}")
|
||||
return " | ".join(parts)
|
||||
|
||||
|
||||
def generate_report(results):
|
||||
"""生成请假审批报告:汇总行 + 每条明细 + 校验不通过未处理清单 + 人工复核清单(+异常/失败)。"""
|
||||
passed = [r for r in results if r.get("decision") == "通过"]
|
||||
rejected = [r for r in results if r.get("decision") == "校验不通过未处理"]
|
||||
review = [r for r in results if r.get("decision") == "人工复核"]
|
||||
abnormal = [r for r in results if r.get("decision") == "异常"]
|
||||
failed = [r for r in results if r.get("decision") == "失败"]
|
||||
|
||||
summary = f"共 {len(results)} 单:通过 {len(passed)},校验不通过未处理 {len(rejected)},人工复核 {len(review)}"
|
||||
if abnormal:
|
||||
summary += f",审批异常 {len(abnormal)}"
|
||||
if failed:
|
||||
summary += f",处理失败 {len(failed)}"
|
||||
|
||||
lines = [
|
||||
"请假审批报告",
|
||||
"=" * 60,
|
||||
summary,
|
||||
"",
|
||||
]
|
||||
|
||||
lines.append("【审批明细】")
|
||||
for i, r in enumerate(results, 1):
|
||||
info = r.get("leave_info", {}) or {}
|
||||
decision = r.get("decision", "未知")
|
||||
note = r.get("note") or r.get("error") or ""
|
||||
lines.append(f" #{i} {_name(r)}({_vtype(r)})-> {decision}")
|
||||
detail = _format_detail(info)
|
||||
if detail:
|
||||
lines.append(f" {detail}")
|
||||
if note:
|
||||
lines.append(f" 备注: {note}")
|
||||
if r.get("审批动作"):
|
||||
lines.append(f" 审批动作: {r['审批动作']}({r.get('审批结果', '')})")
|
||||
lines.append("")
|
||||
|
||||
if rejected:
|
||||
lines.append("《请假审批校验不通过未处理人员明细清单》")
|
||||
for i, r in enumerate(rejected, 1):
|
||||
reason = r.get("note") or r.get("error") or ""
|
||||
url = r.get("detail_url") or "无"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 假期类型: {_vtype(r)} | 校验不通过原因: {reason} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
if review:
|
||||
lines.append("《附件人工复核待办清单》")
|
||||
for i, r in enumerate(review, 1):
|
||||
url = r.get("detail_url") or "无"
|
||||
path = r.get("附件路径") or "下载失败"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 假期类型: {_vtype(r)} | 详情页链接: {url} | 附件: {path}")
|
||||
lines.append("")
|
||||
|
||||
if abnormal:
|
||||
lines.append("《请假审批异常待人工确认清单》")
|
||||
for i, r in enumerate(abnormal, 1):
|
||||
url = r.get("detail_url") or "无"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 假期类型: {_vtype(r)} | 原因: {r.get('note') or r.get('error') or ''} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
if failed:
|
||||
lines.append("【处理失败】")
|
||||
for i, r in enumerate(failed, 1):
|
||||
lines.append(f"{i}. {_name(r)} | {r.get('title', '')} | 错误: {r.get('error', '')}")
|
||||
lines.append("")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _format_leave_block(r):
|
||||
"""将单条请假审批结果格式化为块格式 Markdown。"""
|
||||
info = r.get("leave_info", {}) or {}
|
||||
name = info.get("请假人员") or r.get("creator") or "未知"
|
||||
vtype = info.get("假期类型") or ""
|
||||
lines = [f"**🔹 {name}‑{vtype}**"]
|
||||
label_map = [
|
||||
("请假人员", "请假人员"),
|
||||
("工号", "工号"),
|
||||
("岗位", "岗位"),
|
||||
("组织全路径", "组织全路径"),
|
||||
("假期类型", "假期类型"),
|
||||
]
|
||||
for key, label in label_map:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
lines.append(f"> {label}:{val}")
|
||||
start = info.get("开始日期")
|
||||
start_seg = info.get("开始段")
|
||||
if start:
|
||||
if start_seg:
|
||||
lines.append(f"> 开始日期:{start}|开始段:{start_seg}")
|
||||
else:
|
||||
lines.append(f"> 开始日期:{start}")
|
||||
end = info.get("结束日期")
|
||||
end_seg = info.get("结束段")
|
||||
if end:
|
||||
if end_seg:
|
||||
lines.append(f"> 结束日期:{end}|结束段:{end_seg}")
|
||||
else:
|
||||
lines.append(f"> 结束日期:{end}")
|
||||
for key, label in [("请假天数", "请假天数"), ("请假小时", "请假小时"),
|
||||
("实际上班天数", "实际上班天数"), ("填报天数", "填报天数")]:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
lines.append(f"> {label}:{val}")
|
||||
note = r.get("note") or r.get("error") or ""
|
||||
if note:
|
||||
lines.append(f"> 备注:{note}")
|
||||
url = r.get("detail_url") or ""
|
||||
if url:
|
||||
lines.append(f"> 详情页:[查看详情]({url})")
|
||||
# 钉钉 Markdown 引用块内每行需用双换行分隔才会换行
|
||||
return '\n\n'.join(lines)
|
||||
|
||||
|
||||
def build_push_summary(results, subject=""):
|
||||
"""按结果类型生成块格式 Markdown 推送分组(通过的单据仅计数,不逐条推送)。"""
|
||||
if not results:
|
||||
return []
|
||||
passed = [r for r in results if r.get("decision") == "通过"]
|
||||
rejected = [r for r in results if r.get("decision") == "校验不通过未处理"]
|
||||
review = [r for r in results if r.get("decision") == "人工复核"]
|
||||
abnormal = [r for r in results if r.get("decision") == "异常"]
|
||||
failed = [r for r in results if r.get("decision") == "失败"]
|
||||
if not passed and not rejected and not review and not abnormal and not failed:
|
||||
return []
|
||||
|
||||
messages = []
|
||||
|
||||
def _push_group(title_prefix, records):
|
||||
if not records:
|
||||
return
|
||||
blocks = [_format_leave_block(r) for r in records]
|
||||
messages.append({"title": title_prefix, "blocks": blocks})
|
||||
|
||||
summary_lines = [f"本次共审批 **{len(results)}** 条:"]
|
||||
for label, cnt in [("通过", len(passed)),
|
||||
("校验不通过未处理", len(rejected)),
|
||||
("需人工复核", len(review)),
|
||||
("审批异常", len(abnormal)),
|
||||
("处理失败", len(failed))]:
|
||||
summary_lines.append(f"- {label}:{cnt} 条")
|
||||
messages.append({"title": f"【{subject}审批】汇总", "blocks": ["\n".join(summary_lines)]})
|
||||
|
||||
_push_group(f"【{subject}审批】校验不通过未处理", rejected)
|
||||
_push_group(f"【{subject}审批】需人工复核", review)
|
||||
_push_group(f"【{subject}审批】审批异常", abnormal)
|
||||
_push_group(f"【{subject}审批】处理失败", failed)
|
||||
|
||||
return messages
|
||||
|
||||
|
||||
def save_report(text, save_dir):
|
||||
"""把报告落盘为 <save_dir>/请假审批报告_YYYYMMDD_HHMMSS.txt,返回路径。"""
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
filename = f"请假审批报告_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
|
||||
path = os.path.join(save_dir, filename)
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write(text)
|
||||
logger.info("审批报告已保存: %s", path)
|
||||
return path
|
||||
@@ -1,6 +0,0 @@
|
||||
requests
|
||||
DrissionPage
|
||||
rapidocr
|
||||
onnxruntime
|
||||
Pillow
|
||||
numpy
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,13 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>EHR系统请假流程审核</title>
|
||||
<script type="module" crossorigin src="/pui/xq0003/assets/index-B2Ej4o3H.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0003/assets/index-Ka-PutnU.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,207 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 EHR系统加班流程审核 插件入口。
|
||||
|
||||
流程编排(由影刀版 overtime_approval.py 移植,登录态改由底座注入):
|
||||
1) 会话准备:底座注入 HR session/userId → getCurUserInfo 校验(失效抛错提示重新登录);
|
||||
2) 拉取「加班」待办(纯接口,无待办不启动浏览器);
|
||||
3) 逐单取表单并校验:按加班类型(延时/法定假日/休息日)校验加班日期、时长、排班
|
||||
与打卡区间,延时加班另做提前到岗型与弹性到岗兑换校验;
|
||||
4) 校验通过且开启自动审批时,浏览器注入 HR cookies 后点击同意并确认;
|
||||
5) 生成审批报告落盘 + 钉钉群机器人推送(汇总 + 需人工处理明细)。
|
||||
"""
|
||||
import time
|
||||
|
||||
from webhost.backend.plugins.base import ScenePlugin, PLUGINS
|
||||
|
||||
from . import config
|
||||
from .data import hr_api
|
||||
from .data import hr_browser
|
||||
from .data.hr_api import HRSessionExpiredError
|
||||
from .logic import overtime_rules
|
||||
from .report import overtime_report
|
||||
from .report import dingtalk_robot
|
||||
|
||||
|
||||
class OvertimeApprovalPlugin(ScenePlugin):
|
||||
"""EHR系统加班流程审核(需求 XQ0004)。"""
|
||||
|
||||
id = "xq0004"
|
||||
name = "EHR系统加班流程审核"
|
||||
version = "1.0.0"
|
||||
description = ("自动审核 EHR 加班待办:拉取待办与加班表单,按加班类型(延时/法定假日/休息日)"
|
||||
"校验加班日期、时长、排班与打卡区间及弹性到岗兑换;校验通过自动提交审批,"
|
||||
"并生成审批报告与钉钉群推送。")
|
||||
platform = "hr"
|
||||
uses_month = False
|
||||
capabilities = ["xq0004"]
|
||||
permissions = {"platforms": ["hr"]}
|
||||
fields = {
|
||||
"save_dir": {
|
||||
"type": "string", "title": "输出目录",
|
||||
"default": config.DEFAULT_SAVE_DIR,
|
||||
"description": "审批报告统一存放目录",
|
||||
},
|
||||
"approve_enabled": {
|
||||
"type": "boolean", "title": "自动提交审批", "default": True,
|
||||
"description": "开启后,校验结论为「通过」的单据会在流程详情页自动点击同意;关闭则只校验不提交",
|
||||
},
|
||||
"push_enabled": {
|
||||
"type": "boolean", "title": "钉钉群推送", "default": True,
|
||||
"description": "开启后把汇总与需人工处理明细推送到钉钉群机器人",
|
||||
},
|
||||
"push_env": {
|
||||
"type": "string", "title": "推送环境", "default": "dev",
|
||||
"description": "dev=内置测试群,prod=内置生产群;填写自定义 Webhook 时以自定义为准",
|
||||
},
|
||||
"dingtalk_webhook": {
|
||||
"type": "string", "title": "钉钉 Webhook", "default": "",
|
||||
"description": "留空使用内置默认机器人;需要发到其他群时填写完整 webhook 地址",
|
||||
},
|
||||
"dingtalk_secret": {
|
||||
"type": "string", "title": "钉钉加签密钥", "default": "",
|
||||
"description": "机器人启用加签安全设置时填写,留空表示不加签",
|
||||
},
|
||||
"debug_mode": {
|
||||
"type": "boolean", "title": "调试日志", "default": False,
|
||||
"description": "开启后输出接口返回等调试信息",
|
||||
},
|
||||
}
|
||||
|
||||
def run(self, fields: dict, ctx):
|
||||
# ---- 注入运行上下文:日志 / 进度 / HR 会话 / userId / 输出目录 ----
|
||||
config.set_log(ctx.log)
|
||||
config.set_progress(ctx.progress)
|
||||
config.set_session(ctx.get_session("hr"))
|
||||
config.set_user_id(ctx.get_user_id("hr"))
|
||||
save_dir = (fields.get("save_dir") or "").strip() or config.DEFAULT_SAVE_DIR
|
||||
config.set_save_dir(save_dir)
|
||||
config.set_debug(bool(fields.get("debug_mode")))
|
||||
approve_enabled = bool(fields.get("approve_enabled", True))
|
||||
push_enabled = bool(fields.get("push_enabled", True))
|
||||
push_env = (fields.get("push_env") or "dev").strip().lower() or "dev"
|
||||
webhook = (fields.get("dingtalk_webhook") or "").strip()
|
||||
secret = (fields.get("dingtalk_secret") or "").strip()
|
||||
|
||||
subject = config.DEFAULT_SUBJECT
|
||||
session = config.require_session()
|
||||
ctx.log(f"===== 加班审批启动:输出目录 {save_dir},自动审批={'开' if approve_enabled else '关'} =====",
|
||||
"INFO")
|
||||
|
||||
# ---- 步骤1:会话校验 ----
|
||||
ctx.progress(5)
|
||||
user_id = hr_api.validate_session(session)
|
||||
config.set_user_id(user_id)
|
||||
|
||||
# ---- 步骤2:拉取加班待办 ----
|
||||
ctx.progress(10)
|
||||
docs = hr_api.fetch_documents(session, subject)
|
||||
ctx.log(f"共获取{subject}待办 {len(docs)} 条", "INFO")
|
||||
ctx.progress(15)
|
||||
|
||||
browser = None
|
||||
results = []
|
||||
try:
|
||||
if docs:
|
||||
for idx, doc in enumerate(docs, 1):
|
||||
try:
|
||||
detail = hr_api.fetch_doc_detail(doc)
|
||||
result = overtime_rules.validate_doc(detail, session)
|
||||
|
||||
if approve_enabled and result.get("decision") == "通过":
|
||||
if browser is None:
|
||||
browser = hr_browser.build_browser(session)
|
||||
browser.get(detail["detail_url"])
|
||||
time.sleep(1.5) # 等待详情页与审批按钮加载
|
||||
orig_decision = result.get("decision")
|
||||
submit = hr_browser.submit_approval(browser, orig_decision)
|
||||
result["审批动作"] = submit["action"]
|
||||
result["审批结果"] = submit["message"]
|
||||
# 提交失败兜底:单据状态未变,不能仍标为通过,归为「异常」交人工跟进
|
||||
if submit["ok"] == "false":
|
||||
result["decision"] = "异常"
|
||||
result["note"] = (
|
||||
f"机器结论[{orig_decision}]但审批提交失败:{submit['message']}"
|
||||
)
|
||||
ctx.log(f"审批提交: {submit['action']} {submit['message']}", "INFO")
|
||||
elif result.get("decision") != "通过":
|
||||
ctx.log(f"决策为{result.get('decision')},不自动提交审批(待人工处理)", "INFO")
|
||||
|
||||
results.append(result)
|
||||
ctx.log(f"已校验 {idx}/{len(docs)}: {result.get('creator')} - "
|
||||
f"{result.get('title')} -> {result.get('decision')}", "INFO")
|
||||
except Exception as e:
|
||||
ctx.log(f"处理单据失败: {doc.get('title')}, 错误: {e}", "ERROR")
|
||||
results.append({
|
||||
"creator": doc.get("creator", "未知"),
|
||||
"title": doc.get("title", "未知"),
|
||||
"detail_url": doc.get("detail_url", ""),
|
||||
"decision": "失败",
|
||||
"error": str(e),
|
||||
})
|
||||
ctx.progress(15 + int(75 * idx / len(docs)))
|
||||
else:
|
||||
ctx.log(f"{subject}无待审批单据,跳过浏览器操作", "INFO")
|
||||
|
||||
# ---- 步骤3:报告落盘 ----
|
||||
ctx.progress(92)
|
||||
report_text = overtime_report.generate_report(results)
|
||||
report_path = overtime_report.save_report(report_text, save_dir)
|
||||
ctx.progress(95)
|
||||
|
||||
# ---- 步骤4:钉钉推送 ----
|
||||
push_message = ""
|
||||
if push_enabled:
|
||||
push_items = overtime_report.build_push_summary(results, subject)
|
||||
if not push_items:
|
||||
push_items = [{"text": f"暂无待审批的{subject}单据"}]
|
||||
push_res = dingtalk_robot.main(
|
||||
push_items, title=f"【{subject}审批】汇总",
|
||||
webhook=webhook, secret=secret, env=push_env)
|
||||
push_message = push_res.get("message", "")
|
||||
ctx.log(f"钉钉推送: {push_message}", "INFO")
|
||||
ctx.progress(100)
|
||||
|
||||
counts = {
|
||||
"total": len(results),
|
||||
"passed": sum(1 for r in results if r.get("decision") == "通过"),
|
||||
"rejected": sum(1 for r in results if r.get("decision") == "校验不通过未处理"),
|
||||
"review": sum(1 for r in results if r.get("decision") == "人工复核"),
|
||||
"overdue": sum(1 for r in results if r.get("decision") == "超期"),
|
||||
"abnormal": sum(1 for r in results if r.get("decision") == "异常"),
|
||||
"failed": sum(1 for r in results if r.get("decision") == "失败"),
|
||||
}
|
||||
if not docs:
|
||||
summary = f"暂无待审批的{subject}单据;报告:{report_path}"
|
||||
else:
|
||||
summary = (f"{subject}审批完成,共 {counts['total']} 单:通过 {counts['passed']},"
|
||||
f"校验不通过未处理 {counts['rejected']},人工复核 {counts['review']}")
|
||||
if counts["overdue"]:
|
||||
summary += f",超期待人资处理 {counts['overdue']}"
|
||||
if counts["abnormal"]:
|
||||
summary += f",审批异常 {counts['abnormal']}"
|
||||
if counts["failed"]:
|
||||
summary += f",处理失败 {counts['failed']}"
|
||||
summary += f";报告:{report_path}"
|
||||
if push_message:
|
||||
summary += f";推送:{push_message}"
|
||||
|
||||
return {
|
||||
"summary": summary,
|
||||
"detail": counts,
|
||||
"path": report_path,
|
||||
"results": results,
|
||||
"save_dir": save_dir,
|
||||
}
|
||||
except HRSessionExpiredError as e:
|
||||
# 与影刀版 run_flow 一致:中途 HR 会话失效时给出明确提示,而非原始异常冒泡
|
||||
ctx.log(f"HR 登录态已失效,请重新登录后再执行: {e}", "ERROR")
|
||||
raise RuntimeError("HR 登录态已失效,请重新登录 HR 后再执行") from e
|
||||
finally:
|
||||
if browser is not None:
|
||||
try:
|
||||
browser.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
PLUGINS.append(OvertimeApprovalPlugin())
|
||||
@@ -1,213 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 EHR系统加班流程审核 插件 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:本包只依赖 Python 标准库 / 第三方库 / 底座注入的 RunContext。
|
||||
所有业务模块统一经 config.logger 输出日志、config.require_session() 取登录态。
|
||||
登录态由底座注入(hr 平台),插件不自行读 cookies 文件、不做自动补登。
|
||||
"""
|
||||
import random
|
||||
import time
|
||||
from functools import wraps
|
||||
|
||||
# ==================== 输出配置 ====================
|
||||
DEFAULT_SAVE_DIR = r"D:\资料\人资\加班流程审批"
|
||||
|
||||
# ==================== HR 系统接口 ====================
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
WE_PROCESS_QUERY_URL = f"{HR_BASE_URL}/RedseaPlatform/WeProcess.mc?method=getProcessAndData"
|
||||
GET_CUR_USER_INFO_URL = f"{HR_BASE_URL}/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
WF_ACTIVITY_URL = f"{HR_BASE_URL}/RedseaPlatform/WfActivity.mc"
|
||||
WORKFORM_ENGINE_URL = f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc"
|
||||
ATTENDANCE_DAILY_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_count_leave_yc_day_all/redApiExec.mc"
|
||||
LEAVE_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_leave_record_SelectByStaffID/redApiExec.mc"
|
||||
PUNCH_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_data_queryByStaffId/redApiExec.mc"
|
||||
|
||||
DEFAULT_PAGE_SIZE = 100
|
||||
DEFAULT_TREE_CODE = "cq37du"
|
||||
DEFAULT_SUBJECT = "加班"
|
||||
|
||||
# ==================== 加班审批规则常量 ====================
|
||||
WORK_START_TIME = "09:00"
|
||||
WORK_END_TIME = "18:00"
|
||||
FLEX_TRIGGER_TIME = "23:00"
|
||||
# 次日弹性上班扣减:次日打卡晚于该时刻(13:00)视为跨过中午休息,扣除午餐时长 LUNCH_BREAK_HOURS
|
||||
FLEX_LATE_LUNCH_TRIGGER_TIME = "13:00"
|
||||
# 次日弹性上班扣减时扣除的中午休息时长(小时)
|
||||
LUNCH_BREAK_HOURS = 1
|
||||
OT_MIN_HOURS = 1
|
||||
# 跨天打卡判定:次日首条打卡时间早于该时刻(6点),视为归属加班当天的跨天有效打卡
|
||||
CROSS_DAY_BEFORE_HOUR = 6
|
||||
# 加班审核周期:加班日期距今天不超过该天数才允许审核
|
||||
OT_REVIEW_DAYS = 8
|
||||
# 月度截止:每月该日期 12:00 之后,不再审核上一个月的加班流程
|
||||
MONTH_CUTOFF_DAY = 2
|
||||
MONTH_CUTOFF_HOUR = 12
|
||||
# 职能排班半天加班时长:上午3.5小时、下午4.5小时(休息日/节假日加班整天仍为9小时)
|
||||
ZHINENG_HALF_MORNING_HOURS = 3.5
|
||||
ZHINENG_HALF_AFTERNOON_HOURS = 4.5
|
||||
# 职能排班上午/下午分界:申请加班开始时间早于该时刻(12点)视为上午半天
|
||||
ZHINENG_HALF_CUTOFF_HOUR = 12
|
||||
# 提前到岗型延时加班:加班开始时间早于当天正常上班时间(09:00)视为提前到岗型,
|
||||
# 常规"晚于规定下班时间18:00""当日有下班打卡"校验不适用,改以到岗打卡为区间合规证据。
|
||||
OT_PRE_SHIFT_ARRIVE_BEFORE_HOURS = 1
|
||||
OT_PRE_SHIFT_ARRIVE_AFTER_MINUTES = 0
|
||||
|
||||
# ==================== 审批提交 ====================
|
||||
# 仅自动提交"同意"(校验通过);校验不通过未处理一律不自动提交,保留待人工处理
|
||||
APPROVE_BUTTONS = {
|
||||
"通过": ("#chooseSubmit", "同意"),
|
||||
}
|
||||
|
||||
# ==================== 编码 → 名称 ====================
|
||||
OT_TYPE_MAP = {"1": "延时加班", "2": "法定假日加班", "3": "休息日加班"}
|
||||
SUBSIDY_TYPE_MAP = {"1": "转调休", "2": "转补贴"}
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
_progress = None
|
||||
_session = None
|
||||
_user_id = ""
|
||||
_save_dir = DEFAULT_SAVE_DIR
|
||||
_debug = False
|
||||
|
||||
|
||||
def set_log(fn):
|
||||
"""注入 ctx.log(RunContext.log),各模块经 log()/logger 输出。"""
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def log(msg, level="INFO"):
|
||||
if _log:
|
||||
_log(str(msg), level)
|
||||
else:
|
||||
print(f"[{level}] {msg}")
|
||||
|
||||
|
||||
class _ModuleLogger:
|
||||
"""模块级 logger 适配:保留影刀版 logger.info(...) 调用点,统一转发到 ctx.log。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "DEBUG")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "INFO")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "WARN")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "ERROR")
|
||||
|
||||
|
||||
logger = _ModuleLogger()
|
||||
|
||||
|
||||
def set_progress(fn):
|
||||
"""注入 ctx.progress,业务层按阶段上报进度。"""
|
||||
global _progress
|
||||
_progress = fn
|
||||
|
||||
|
||||
def progress(pct):
|
||||
if _progress:
|
||||
try:
|
||||
_progress(int(pct))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def set_session(session):
|
||||
global _session
|
||||
_session = session
|
||||
|
||||
|
||||
def get_session():
|
||||
return _session
|
||||
|
||||
|
||||
def require_session():
|
||||
"""取插件运行期注入的 HR session(缺失抛错,提示先登录 HR)。"""
|
||||
if _session is None:
|
||||
raise RuntimeError("未注入 HR 登录态,请先在壳子(工作台)完成 HR 登录")
|
||||
return _session
|
||||
|
||||
|
||||
def set_user_id(uid):
|
||||
global _user_id
|
||||
_user_id = str(uid or "")
|
||||
|
||||
|
||||
def get_user_id():
|
||||
return _user_id
|
||||
|
||||
|
||||
def require_user_id():
|
||||
if not _user_id:
|
||||
raise RuntimeError("获取当前用户 userId 失败,请重新完成 HR 登录")
|
||||
return _user_id
|
||||
|
||||
|
||||
def set_save_dir(path):
|
||||
global _save_dir
|
||||
_save_dir = (path or "").strip() or DEFAULT_SAVE_DIR
|
||||
|
||||
|
||||
def get_save_dir():
|
||||
return _save_dir
|
||||
|
||||
|
||||
def set_debug(flag):
|
||||
global _debug
|
||||
_debug = bool(flag)
|
||||
|
||||
|
||||
def is_debug():
|
||||
return _debug
|
||||
|
||||
|
||||
# ==================== 重试装饰器(全局最大 3 次) ====================
|
||||
class RetryExhaustedError(Exception):
|
||||
"""重试次数耗尽。"""
|
||||
|
||||
|
||||
def retry(max_attempts: int = 3, no_retry_on: tuple = ()):
|
||||
"""指数退避重试:首次失败后 1s、2s、4s(含抖动);连续失败记录错误并抛出。"""
|
||||
|
||||
def decorator(func):
|
||||
@wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
last_exc = None
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
except no_retry_on:
|
||||
raise
|
||||
except Exception as e: # noqa: BLE001 - 统一重试入口
|
||||
last_exc = e
|
||||
if attempt >= max_attempts:
|
||||
break
|
||||
delay = 1.0 * (2 ** (attempt - 1)) * random.uniform(0.5, 1.5)
|
||||
logger.warning("%s 第 %d 次失败,%.1fs 后重试: %s",
|
||||
func.__name__, attempt, delay, e)
|
||||
time.sleep(delay)
|
||||
logger.error("%s 连续 %d 次尝试失败,放弃并记录: %s",
|
||||
func.__name__, max_attempts, last_exc)
|
||||
raise RetryExhaustedError(
|
||||
f"{func.__name__} 连续 {max_attempts} 次失败: {last_exc}") from last_exc
|
||||
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
@@ -1,2 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 加班流程审核 插件 - 数据层。"""
|
||||
@@ -1,348 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 EHR系统加班流程审核 插件 - HR 接口层(由影刀版 overtime_approval.py 接口部分移植)。
|
||||
|
||||
链路:
|
||||
1) WeProcess getProcessAndData 查加班流程待办(含 taskId/businessKey/formId)
|
||||
2) WfActivity getWfActivityByTaskId 取 formId
|
||||
3) WorkformEngine getBusinessDate 取加班表单数据
|
||||
4) rf_s_kq_count_leave_yc_day_all 按员工+日期范围取每日考勤(班次名/班次起止)
|
||||
5) rf_s_kq_leave_record_SelectByStaffID 取请假记录(弹性兑换前置校验)
|
||||
6) rf_s_kq_data_queryByStaffId 取打卡明细(kq_time/bc_date/time_order)
|
||||
|
||||
插件化改造点(与影刀版差异):
|
||||
1. 纯 requests 调用(底座注入的 requests.Session),不再用 DrissionPage SessionPage;
|
||||
2. 登录态失效统一抛 HRSessionExpiredError,由上层提示重新登录(不自动补登);
|
||||
3. 日志统一转发到 ctx.log(config.logger)。
|
||||
"""
|
||||
from ..config import (
|
||||
logger, retry, require_session,
|
||||
HR_BASE_URL, WE_PROCESS_QUERY_URL, WF_ACTIVITY_URL, WORKFORM_ENGINE_URL,
|
||||
GET_CUR_USER_INFO_URL, ATTENDANCE_DAILY_URL, LEAVE_RECORD_URL, PUNCH_RECORD_URL,
|
||||
DEFAULT_PAGE_SIZE,
|
||||
)
|
||||
|
||||
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态失效(接口返回非 JSON 或 Nosession,被重定向到登录页)。"""
|
||||
|
||||
|
||||
def hr_request_json(session, method, url, params, label, timeout=20):
|
||||
"""POST/GET 请求并校验返回 JSON;非 JSON 视为登录态失效。"""
|
||||
resp = session.request(method.upper(), url, data=params, timeout=timeout)
|
||||
resp.raise_for_status()
|
||||
text = resp.text or ""
|
||||
if not text or not text.lstrip().startswith(("{", "[")):
|
||||
raise HRSessionExpiredError(f"{label}:HR 登录态失效(返回非 JSON)")
|
||||
return resp.json()
|
||||
|
||||
|
||||
def fetch_cur_user_info(session):
|
||||
"""调用 getCurUserInfo,返回 userId / rootId(treecode)。"""
|
||||
return hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
|
||||
|
||||
|
||||
def validate_session(session):
|
||||
"""校验注入的 HR 登录态有效,返回 current userId。"""
|
||||
try:
|
||||
info = fetch_cur_user_info(session)
|
||||
except HRSessionExpiredError:
|
||||
raise RuntimeError("HR 登录态已失效,请重新登录 HR 后再执行") from None
|
||||
user_id = str(info.get("userId") or "") if isinstance(info, dict) else ""
|
||||
if not user_id:
|
||||
raise RuntimeError("HR 登录态无效(getCurUserInfo 未返回 userId),请重新登录 HR")
|
||||
return user_id
|
||||
|
||||
|
||||
# ==================== 加班流程待办 ====================
|
||||
def fetch_we_process_page(session, subject, page_no=1, page_size=DEFAULT_PAGE_SIZE):
|
||||
"""拉一页流程待办(title 按标题模糊匹配)。"""
|
||||
params = {
|
||||
"version": "", "PACKAGE_ID": "cq37du", "process_type": "", "defProcessType": "",
|
||||
"struId": "", "rootId": "cq37du", "taskIds": "", "title": subject,
|
||||
"state": "", "startTime": "", "endTime": "",
|
||||
"sortType": "desc", "sortName": "CREATE_TIME",
|
||||
"commonQuery": "[]", "start": str((page_no - 1) * page_size),
|
||||
"pageNo": str(page_no), "pageSize": str(page_size),
|
||||
}
|
||||
data = hr_request_json(session, "POST", WE_PROCESS_QUERY_URL, params, "WeProcess")
|
||||
if str(data.get("state")) != "1":
|
||||
if str(data.get("state")) == "Nosession" or "会话过期" in str(data.get("meg", "")):
|
||||
raise HRSessionExpiredError(f"WeProcess 返回会话过期: {data.get('meg')}")
|
||||
raise RuntimeError(f"WeProcess 接口返回失败: state={data.get('state')} meg={data.get('meg')}")
|
||||
return data
|
||||
|
||||
|
||||
def parse_we_process_list(data):
|
||||
"""解析待办行为单据字典;detail_url 用 reqType=WAIT(待办审批视图,页面才有审批按钮)。"""
|
||||
docs = []
|
||||
for row in data.get("jsonList") or data.get("datas") or []:
|
||||
title = str(row.get("title") or "").strip()
|
||||
task_id = str(row.get("taskId") or "")
|
||||
business_key = str(row.get("businessKey") or "")
|
||||
process_id = str(row.get("processId") or "")
|
||||
form_id = str(row.get("formId") or "")
|
||||
if not task_id or not business_key:
|
||||
logger.warning("跳过缺 taskId/businessKey 的待办行: %s", title)
|
||||
continue
|
||||
detail_url = (
|
||||
f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc?method=goToWorkFlow"
|
||||
f"&formId={form_id}&businessKey={business_key}&processId={process_id}"
|
||||
f"&taskId={task_id}&reqType=WAIT&headType=&systemId="
|
||||
)
|
||||
docs.append({
|
||||
"title": title,
|
||||
"creator": str(row.get("createUserName") or row.get("createUserNameCn") or "").strip(),
|
||||
"time": str(row.get("createTime") or "").strip(),
|
||||
"taskId": task_id,
|
||||
"businessKey": business_key,
|
||||
"processId": process_id,
|
||||
"formId": form_id,
|
||||
"detail_url": detail_url,
|
||||
})
|
||||
return docs
|
||||
|
||||
|
||||
def get_documents(session, subject, page_size=DEFAULT_PAGE_SIZE):
|
||||
"""分页拉取全部待办,按 taskId 去重。"""
|
||||
all_docs = []
|
||||
page_no = 1
|
||||
while page_no <= 20: # 防御性分页上限
|
||||
data = fetch_we_process_page(session, subject, page_no=page_no, page_size=page_size)
|
||||
docs = parse_we_process_list(data)
|
||||
all_docs.extend(docs)
|
||||
logger.info("第 %d 页获取 %d 条,累计 %d 条", page_no, len(docs), len(all_docs))
|
||||
if len(docs) < page_size:
|
||||
break
|
||||
page_no += 1
|
||||
|
||||
seen = set()
|
||||
unique_docs = []
|
||||
for doc in all_docs:
|
||||
key = doc.get("taskId") or doc.get("detail_url") or doc.get("title")
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
unique_docs.append(doc)
|
||||
|
||||
if len(unique_docs) != len(all_docs):
|
||||
logger.warning("去重前 %d 条,去重后 %d 条(已过滤 %d 条重复单据)",
|
||||
len(all_docs), len(unique_docs), len(all_docs) - len(unique_docs))
|
||||
return unique_docs
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||||
def fetch_documents(session, subject):
|
||||
return get_documents(session, subject=subject)
|
||||
|
||||
|
||||
# ==================== 表单详情 ====================
|
||||
def get_wf_activity_by_task_id(session, task_id):
|
||||
url = f"{WF_ACTIVITY_URL}?method=getWfActivityByTaskId"
|
||||
logger.info("获取 formId: taskId=%s", task_id)
|
||||
try:
|
||||
json_data = hr_request_json(session, "POST", url, {"taskId": task_id}, "WfActivity")
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"WfActivity 接口请求失败: {e}") from e
|
||||
logger.debug("WfActivity 返回: %s", json_data)
|
||||
return json_data
|
||||
|
||||
|
||||
def extract_form_id(wf_activity_data):
|
||||
form_id = (
|
||||
wf_activity_data.get("formId")
|
||||
or wf_activity_data.get("FormId")
|
||||
or wf_activity_data.get("form_id")
|
||||
)
|
||||
if not form_id:
|
||||
for key in ("data", "result"):
|
||||
data_obj = wf_activity_data.get(key, {})
|
||||
if isinstance(data_obj, dict):
|
||||
form_id = data_obj.get("formId") or data_obj.get("FormId") or data_obj.get("form_id")
|
||||
if form_id:
|
||||
break
|
||||
if not form_id:
|
||||
raise ValueError(f"无法从 WfActivity 返回数据中提取 formId: {wf_activity_data}")
|
||||
logger.info("提取到 formId: %s", form_id)
|
||||
return form_id
|
||||
|
||||
|
||||
def get_business_data(session, business_key, form_id):
|
||||
url = f"{WORKFORM_ENGINE_URL}?method=getBusinessDate"
|
||||
logger.info("获取加班表单: businessKey=%s, formId=%s", business_key, form_id)
|
||||
try:
|
||||
json_data = hr_request_json(
|
||||
session, "POST", url,
|
||||
{"businessKey": business_key, "formId": form_id}, "WorkformEngine")
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"WorkformEngine 接口请求失败: {e}") from e
|
||||
|
||||
result = json_data.get("result")
|
||||
if json_data.get("state") != "1" or not isinstance(result, dict):
|
||||
raise RuntimeError(f"WorkformEngine 接口返回失败: {json_data}")
|
||||
logger.info("WorkformEngine 返回成功")
|
||||
return result
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||||
def fetch_doc_detail(doc):
|
||||
"""纯接口取单据详情:taskId/businessKey 直接取自 WeProcess 行(免 SSO 解析)。"""
|
||||
session = require_session()
|
||||
task_id = doc.get("taskId")
|
||||
business_key = doc.get("businessKey")
|
||||
if not task_id or not business_key:
|
||||
raise RuntimeError(f"待办行缺 taskId/businessKey: {doc.get('title')}")
|
||||
|
||||
wf_activity_data = get_wf_activity_by_task_id(session, task_id)
|
||||
form_id = extract_form_id(wf_activity_data)
|
||||
form_data = get_business_data(session, business_key, form_id)
|
||||
return {**doc, "formId": form_id, "formData": form_data}
|
||||
|
||||
|
||||
# ==================== 每日考勤(排班 + 班次时段) ====================
|
||||
def get_attendance_daily(session, staff_id, start_date, end_date):
|
||||
"""按员工+日期范围查询每日考勤(含班次起止时间与上下班打卡)。
|
||||
|
||||
kq_status_total 按考勤状态分类返回记录:0=休息日、1=正常班、9=未打卡、11=异常,
|
||||
需四种状态各查一次,再按 work_day 合并去重,才能同时拿到班次名/班次时段与休息日记录。
|
||||
"""
|
||||
by_day = {}
|
||||
for status in ("0", "1", "9", "11"):
|
||||
params = {
|
||||
"staff_id": staff_id,
|
||||
"begin_date": start_date,
|
||||
"end_date": end_date,
|
||||
"kq_status_total": status,
|
||||
}
|
||||
logger.info("获取考勤逐日(kq_status_total=%s): staff_id=%s, %s 至 %s",
|
||||
status, staff_id, start_date, end_date)
|
||||
try:
|
||||
json_data = hr_request_json(
|
||||
session, "POST", ATTENDANCE_DAILY_URL, params, "考勤逐日")
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"考勤逐日接口请求失败: {e}") from e
|
||||
|
||||
for r in json_data.get("data", []) or []:
|
||||
by_day.setdefault(str(r.get("work_day", "")), r)
|
||||
records = [by_day[k] for k in sorted(by_day)]
|
||||
logger.info("考勤逐日合并返回 %d 天", len(records))
|
||||
return records
|
||||
|
||||
|
||||
# ==================== 请假记录 ====================
|
||||
def fetch_leave_record_page(session, staff_id, begin_date, end_date,
|
||||
page_no=1, page_size=DEFAULT_PAGE_SIZE, sub_type="-1"):
|
||||
data = {
|
||||
"sub_type": sub_type,
|
||||
"staff_id": staff_id,
|
||||
"begin_date": begin_date,
|
||||
"end_date": end_date,
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"pageSize": str(page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": str(page_no),
|
||||
}
|
||||
logger.info("获取请假记录: staff_id=%s, %s 至 %s, 第%d页",
|
||||
staff_id, begin_date, end_date, page_no)
|
||||
try:
|
||||
json_data = hr_request_json(session, "POST", LEAVE_RECORD_URL, data, "请假记录")
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"请假记录接口请求失败: {e}") from e
|
||||
|
||||
if json_data.get("success") is not True or json_data.get("code") != 200:
|
||||
raise RuntimeError(f"请假记录接口返回失败: {json_data}")
|
||||
page_info = json_data.get("data")
|
||||
if not isinstance(page_info, dict):
|
||||
raise RuntimeError(f"请假记录接口未返回 data 字段: {json_data}")
|
||||
return page_info
|
||||
|
||||
|
||||
def get_leave_records(session, staff_id, begin_date, end_date,
|
||||
page_size=DEFAULT_PAGE_SIZE, sub_type="-1"):
|
||||
all_records = []
|
||||
page_info = fetch_leave_record_page(
|
||||
session, staff_id, begin_date, end_date,
|
||||
page_no=1, page_size=page_size, sub_type=sub_type)
|
||||
total = int(page_info.get("total", 0))
|
||||
page_total = int(page_info.get("pageCount", 1))
|
||||
records = page_info.get("list", []) or []
|
||||
all_records.extend(records)
|
||||
logger.info("请假记录总数: %d, 第1页获取 %d 条", total, len(records))
|
||||
|
||||
if page_total > 1:
|
||||
for p in range(2, page_total + 1):
|
||||
page_info = fetch_leave_record_page(
|
||||
session, staff_id, begin_date, end_date,
|
||||
page_no=p, page_size=page_size, sub_type=sub_type)
|
||||
records = page_info.get("list", []) or []
|
||||
all_records.extend(records)
|
||||
logger.info("第 %d 页获取 %d 条,累计 %d 条", p, len(records), len(all_records))
|
||||
return all_records
|
||||
|
||||
|
||||
# ==================== 打卡明细 ====================
|
||||
def fetch_punch_record_page(session, staff_id, begin_date, end_date,
|
||||
page_no=1, page_size=DEFAULT_PAGE_SIZE, sub_type="-1"):
|
||||
"""请求单页员工打卡明细(kq_time 真实打卡时间 / bc_date 考勤归属日 / time_order 1上2下)。"""
|
||||
data = {
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": str(page_no),
|
||||
"pageSize": str(page_size),
|
||||
"staff_id": staff_id,
|
||||
"rootId": "",
|
||||
"countId": "",
|
||||
"bc_date": begin_date,
|
||||
"bc_date_end": end_date,
|
||||
"begin": begin_date,
|
||||
"end": end_date,
|
||||
"sub_type": sub_type,
|
||||
}
|
||||
logger.info("获取打卡明细: staff_id=%s, %s 至 %s, 第%d页",
|
||||
staff_id, begin_date, end_date, page_no)
|
||||
try:
|
||||
json_data = hr_request_json(session, "POST", PUNCH_RECORD_URL, data, "打卡明细")
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"打卡明细接口请求失败: {e}") from e
|
||||
|
||||
if json_data.get("success") is not True or json_data.get("code") != 200:
|
||||
raise RuntimeError(f"打卡明细接口返回失败: {json_data}")
|
||||
page_info = json_data.get("data")
|
||||
if not isinstance(page_info, dict):
|
||||
raise RuntimeError(f"打卡明细接口未返回 data 字段: {json_data}")
|
||||
return page_info
|
||||
|
||||
|
||||
def get_punch_records(session, staff_id, begin_date, end_date,
|
||||
page_size=DEFAULT_PAGE_SIZE, sub_type="-1"):
|
||||
"""查询员工某时间段内的全部打卡明细(自动分页)。"""
|
||||
all_records = []
|
||||
page_info = fetch_punch_record_page(
|
||||
session, staff_id, begin_date, end_date,
|
||||
page_no=1, page_size=page_size, sub_type=sub_type)
|
||||
total = int(page_info.get("total", 0))
|
||||
page_total = int(page_info.get("pageCount", 1))
|
||||
records = page_info.get("list", []) or []
|
||||
all_records.extend(records)
|
||||
logger.info("打卡明细总数: %d, 第1页获取 %d 条", total, len(records))
|
||||
|
||||
if page_total > 1:
|
||||
for p in range(2, page_total + 1):
|
||||
page_info = fetch_punch_record_page(
|
||||
session, staff_id, begin_date, end_date,
|
||||
page_no=p, page_size=page_size, sub_type=sub_type)
|
||||
records = page_info.get("list", []) or []
|
||||
all_records.extend(records)
|
||||
logger.info("第 %d 页获取 %d 条,累计 %d 条", p, len(records), len(all_records))
|
||||
return all_records
|
||||
@@ -1,124 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 EHR系统加班流程审核 插件 - 浏览器审批层。
|
||||
|
||||
用途:表单数据全部走接口,仅在「通过」需要真实点击审批按钮时才启动浏览器。
|
||||
登录态来自底座注入的 requests.Session(hr 平台),插件不自行读 cookies 文件、不自动补登。
|
||||
"""
|
||||
import time
|
||||
|
||||
from ..config import logger, APPROVE_BUTTONS
|
||||
|
||||
|
||||
def _cookies_from_session(session):
|
||||
"""把注入 session 的 cookies 转成 DrissionPage 可用的 cookie 字典列表。"""
|
||||
cookies = []
|
||||
if session is None:
|
||||
return cookies
|
||||
try:
|
||||
jar = session.cookies
|
||||
except Exception:
|
||||
return cookies
|
||||
for c in jar:
|
||||
domain = str(c.domain or "")
|
||||
if domain and "37du.co" not in domain:
|
||||
continue
|
||||
cookies.append({
|
||||
"name": c.name,
|
||||
"value": c.value,
|
||||
"domain": domain or ".37du.co",
|
||||
"path": c.path or "/",
|
||||
})
|
||||
return cookies
|
||||
|
||||
|
||||
def build_browser(session):
|
||||
"""创建 ChromiumPage 并注入 HR 登录态;cookies 为空时抛错(提示先登录 HR)。"""
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
cookies = _cookies_from_session(session)
|
||||
if not cookies:
|
||||
raise RuntimeError("未获取到 HR 登录 cookies,请先在壳子(工作台)完成 HR 登录后再执行")
|
||||
page = ChromiumPage(ChromiumOptions())
|
||||
page.set.cookies(cookies)
|
||||
logger.info("浏览器已启动并注入 HR cookies:%d 个", len(cookies))
|
||||
return page
|
||||
|
||||
|
||||
def _find_button(page, selector, timeout=3.0):
|
||||
"""在详情页查找审批按钮:优先主文档,找不到则遍历 iframe。"""
|
||||
try:
|
||||
btn = page.ele(selector, timeout=timeout)
|
||||
if btn:
|
||||
return btn
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
frames = page.get_frames()
|
||||
except Exception:
|
||||
frames = []
|
||||
for frame in frames:
|
||||
try:
|
||||
btn = frame.ele(selector, timeout=1)
|
||||
if btn:
|
||||
return btn
|
||||
except Exception:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def submit_approval(page, decision):
|
||||
"""按校验结论执行真实审批提交。
|
||||
|
||||
Args:
|
||||
page: 停留在单据详情页的 ChromiumPage
|
||||
decision: 校验决策(仅「通过」会自动提交,其余不提交)
|
||||
|
||||
Returns:
|
||||
{"action": "同意"/"-", "ok": "true"/"false", "message": ...}
|
||||
"""
|
||||
if decision not in APPROVE_BUTTONS:
|
||||
return {"action": "-", "ok": "true", "message": "无需提交"}
|
||||
selector, label = APPROVE_BUTTONS[decision]
|
||||
try:
|
||||
btn = _find_button(page, selector)
|
||||
if btn is None:
|
||||
msg = f"未找到审批按钮 {selector}({label}),可能页面未加载完成或按钮在未识别的 iframe 中"
|
||||
logger.error(msg)
|
||||
return {"action": label, "ok": "false", "message": msg}
|
||||
logger.info("点击审批按钮: %s(%s)", selector, label)
|
||||
btn.click()
|
||||
|
||||
def _visible(el):
|
||||
try:
|
||||
return el.states.is_displayed
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
# 普通流程确认框 #custom-confirm-modal-ok 为主;选人弹窗 .wf-select-people 为特殊单据才触发
|
||||
confirm = None
|
||||
for _ in range(20):
|
||||
c1 = page.ele("#custom-confirm-modal-ok", timeout=0.2)
|
||||
if c1 is not None and _visible(c1):
|
||||
confirm = c1
|
||||
break
|
||||
people = page.ele(".wf-select-people", timeout=0.2)
|
||||
if people is not None and _visible(people):
|
||||
try:
|
||||
c2 = people.ele("css:.modal-footer button.btn.btn-primary", timeout=0.2)
|
||||
except Exception:
|
||||
c2 = None
|
||||
if c2 is not None and _visible(c2):
|
||||
confirm = c2
|
||||
break
|
||||
time.sleep(0.2)
|
||||
if confirm is None:
|
||||
msg = "未找到确认框确定按钮(#custom-confirm-modal-ok 或 .modal-footer .btn.btn-primary),审批未提交"
|
||||
logger.error(msg)
|
||||
return {"action": label, "ok": "false", "message": msg}
|
||||
confirm.click()
|
||||
logger.info("已点击确认框确定按钮")
|
||||
time.sleep(1.0)
|
||||
return {"action": label, "ok": "true", "message": f"已执行审批提交[{label}]"}
|
||||
except Exception as e:
|
||||
logger.error("审批提交失败[%s]: %s", label, str(e))
|
||||
return {"action": label, "ok": "false", "message": f"审批提交[{label}]失败: {e}"}
|
||||
@@ -1,2 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 加班流程审核 插件 - 业务规则层。"""
|
||||
@@ -1,598 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 EHR系统加班流程审核 插件 - 加班校验规则层。
|
||||
|
||||
迁移自 workflows/XQ0001-0100/XQ0004 EHR系统加班流程审核/overtime_approval.py:
|
||||
- 登录态改造:SessionPage → 底座注入 requests.Session(data.hr_api.get_* 接口)
|
||||
- 日志改造:print 输出与进程退出提示 → config.logger
|
||||
- 规则逻辑(时长取整/弹性兑换/休息日法定假日加班/审核周期)原样保留
|
||||
"""
|
||||
import calendar
|
||||
import math
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from chinese_calendar import get_holiday_detail, is_in_lieu
|
||||
|
||||
from ..config import (
|
||||
logger,
|
||||
WORK_START_TIME,
|
||||
WORK_END_TIME,
|
||||
FLEX_TRIGGER_TIME,
|
||||
FLEX_LATE_LUNCH_TRIGGER_TIME,
|
||||
LUNCH_BREAK_HOURS,
|
||||
OT_MIN_HOURS,
|
||||
CROSS_DAY_BEFORE_HOUR,
|
||||
OT_REVIEW_DAYS,
|
||||
MONTH_CUTOFF_DAY,
|
||||
MONTH_CUTOFF_HOUR,
|
||||
ZHINENG_HALF_MORNING_HOURS,
|
||||
ZHINENG_HALF_AFTERNOON_HOURS,
|
||||
ZHINENG_HALF_CUTOFF_HOUR,
|
||||
OT_PRE_SHIFT_ARRIVE_BEFORE_HOURS,
|
||||
OT_PRE_SHIFT_ARRIVE_AFTER_MINUTES,
|
||||
OT_TYPE_MAP,
|
||||
SUBSIDY_TYPE_MAP,
|
||||
)
|
||||
from ..data.hr_api import get_attendance_daily, get_leave_records, get_punch_records
|
||||
|
||||
|
||||
# ==================== 加班表单解析 ====================
|
||||
def parse_overtime_form(result):
|
||||
ot_type_code = result.get("ot_type")
|
||||
subsidy_type_code = result.get("subsidy_type")
|
||||
|
||||
overtime_info = {
|
||||
"加班人员ID": result.get("staff_id"),
|
||||
"加班人员": result.get("staff_name"),
|
||||
"组织全路径": result.get("org_full_path"),
|
||||
"岗位": result.get("post_name"),
|
||||
"加班类型": OT_TYPE_MAP.get(ot_type_code, ot_type_code),
|
||||
"补贴类型": SUBSIDY_TYPE_MAP.get(subsidy_type_code, subsidy_type_code),
|
||||
"加班日期": result.get("ot_date"),
|
||||
"加班开始时间": result.get("start_time"),
|
||||
"加班结束时间": result.get("end_time"),
|
||||
"加班时长(小时)": result.get("ot_hour") or result.get("expect_hour"),
|
||||
"加班天数(天)": result.get("ot_day"),
|
||||
"系统判断加班时长(小时)": result.get("judge_ot_hour"),
|
||||
"系统判断加班天数(天)": result.get("judge_ot_day"),
|
||||
"附件": result.get("file"),
|
||||
}
|
||||
|
||||
judge_start = result.get("judge_start_time")
|
||||
judge_end = result.get("judge_end_time")
|
||||
# 接口对未判定场景返回字符串"无数据",需过滤,避免拼出"10:00:00 至 无数据"
|
||||
if (judge_start and judge_end
|
||||
and "无" not in str(judge_start) and "无" not in str(judge_end)):
|
||||
overtime_info["系统判定加班时间"] = f"{judge_start} 至 {judge_end}"
|
||||
else:
|
||||
overtime_info["系统判定加班时间"] = None
|
||||
|
||||
return overtime_info
|
||||
|
||||
|
||||
# ==================== 加班校验规则 ====================
|
||||
def _parse_dt(value):
|
||||
if not value:
|
||||
return None
|
||||
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M"):
|
||||
try:
|
||||
return datetime.strptime(str(value), fmt)
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _calc_delayed_hours(start, end):
|
||||
total = (end - start).total_seconds() / 3600
|
||||
if total < 1:
|
||||
return 0.0
|
||||
return 1.0 + math.floor((total - 1) / 0.5) * 0.5
|
||||
|
||||
|
||||
def _calc_flex_d(actual_checkout, flex_trigger):
|
||||
return 1.0 + math.floor((actual_checkout - flex_trigger).total_seconds() / 1800) * 0.5
|
||||
|
||||
|
||||
def _calc_day_ot_threshold(days):
|
||||
return 8.0 * days + int(days)
|
||||
|
||||
|
||||
def _next_day(date_str):
|
||||
d = datetime.strptime(date_str, "%Y-%m-%d")
|
||||
return (d + timedelta(days=1)).strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def _is_within_arrival_window(punch_str, start_dt,
|
||||
before_hours=OT_PRE_SHIFT_ARRIVE_BEFORE_HOURS,
|
||||
after_minutes=OT_PRE_SHIFT_ARRIVE_AFTER_MINUTES):
|
||||
"""提前到岗型加班:判断打卡时间是否落在加班开始时间附近的到岗证据窗口内。"""
|
||||
p = _parse_dt(punch_str)
|
||||
if p is None:
|
||||
return False
|
||||
return (start_dt - timedelta(hours=before_hours)) <= p <= (start_dt + timedelta(minutes=after_minutes))
|
||||
|
||||
|
||||
def _is_spring_festival(date_str):
|
||||
try:
|
||||
date = datetime.strptime(date_str, "%Y-%m-%d").date()
|
||||
is_holiday, holiday_name = get_holiday_detail(date)
|
||||
return (is_holiday and holiday_name == 'Spring Festival'
|
||||
and not is_in_lieu(date) and date.weekday() < 5)
|
||||
except Exception as e:
|
||||
logger.warning("春节法定假日判定失败(%s): %s", date_str, str(e))
|
||||
return False
|
||||
|
||||
|
||||
def _get_shift(session, staff_id, date_str):
|
||||
if not date_str or not staff_id:
|
||||
return "未知"
|
||||
try:
|
||||
records = get_attendance_daily(session, staff_id, date_str, date_str)
|
||||
for r in records:
|
||||
if str(r.get("work_day", "")) == date_str:
|
||||
bc = r.get("bc_name")
|
||||
if bc:
|
||||
return str(bc)
|
||||
# 休息日记录 bc_name 为空,以异常状态标识判断(abnormal_name/kq_status_name1);
|
||||
# 用前缀"休息"匹配,兼容"休息"/"休息(调)"/"休息(补)"等变体
|
||||
if str(r.get("abnormal_name") or r.get("kq_status_name1") or "").startswith("休息"):
|
||||
return "休息"
|
||||
return "无排班"
|
||||
return "无排班"
|
||||
except Exception as e:
|
||||
logger.warning("获取排班失败(%s): %s", date_str, str(e))
|
||||
return "获取失败"
|
||||
|
||||
|
||||
def _is_zhineng_schedule(session, staff_id, date_str):
|
||||
"""
|
||||
判断员工是否为职能排班(休息日/节假日加班半天规则专用)。
|
||||
|
||||
不看加班当天(当天排班通常显示'休息'),而是查看当月每日考勤中的其他天:
|
||||
只要任一天班次包含'职能'(如 职能正班A),即按职能排班处理。
|
||||
排班获取失败时优雅降级返回 False,沿用默认半天4小时规则。
|
||||
"""
|
||||
if not date_str or not staff_id:
|
||||
return False
|
||||
try:
|
||||
year = int(date_str[:4])
|
||||
month = int(date_str[5:7])
|
||||
first_day = f"{year:04d}-{month:02d}-01"
|
||||
last_day = f"{year:04d}-{month:02d}-{calendar.monthrange(year, month)[1]:02d}"
|
||||
records = get_attendance_daily(session, staff_id, first_day, last_day)
|
||||
return any("职能" in (r.get("bc_name") or "") for r in records)
|
||||
except Exception as e:
|
||||
logger.warning("获取排班判断职能失败(%s): %s", date_str, str(e))
|
||||
return False
|
||||
|
||||
|
||||
def _check_attendance(session, staff_id, ot_date):
|
||||
return {"加班当天班次": _get_shift(session, staff_id, ot_date)}
|
||||
|
||||
|
||||
def _extract_shift_times(daily_records, date_str):
|
||||
"""从每日考勤记录中提取指定日期的班次起止时间("HH:MM"),无则返回 (None, None)。
|
||||
|
||||
数据源为 rf_s_kq_count_leave_yc_day_all 接口返回的每日记录
|
||||
(字段 work_day + bc_begin_time/bc_end_time),据此可拿到员工当天实际排班的
|
||||
下班时间(如维护早班 08:00-17:00),避免延时加班校验错误使用默认 18:00。
|
||||
"""
|
||||
for r in daily_records:
|
||||
if str(r.get("work_day", "")) != date_str:
|
||||
continue
|
||||
b = r.get("bc_begin_time")
|
||||
e = r.get("bc_end_time")
|
||||
return (str(b).strip()[:5] if b else None,
|
||||
str(e).strip()[:5] if e else None)
|
||||
return None, None
|
||||
|
||||
|
||||
def _check_punch_records(session, staff_id, ot_date):
|
||||
if not ot_date or not staff_id:
|
||||
return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None,
|
||||
"前一天最晚打卡": None, "班次开始时间": None, "班次结束时间": None,
|
||||
"次日班次开始时间": None, "打卡备注": "缺少加班日期或员工ID"}
|
||||
|
||||
start = datetime.strptime(ot_date, "%Y-%m-%d")
|
||||
prev_day = (start - timedelta(days=1)).strftime("%Y-%m-%d")
|
||||
next_day = (start + timedelta(days=1)).strftime("%Y-%m-%d")
|
||||
|
||||
try:
|
||||
# 打卡明细接口返回 kq_time=真实打卡时间 与 bc_date=考勤归属日,
|
||||
# 跨天打卡(次日0点~6点)由系统归入加班当天,无需人工拼接/修正日期;
|
||||
# 范围扩到前一天是为了兼容提前到岗型加班(开始<=6点)到岗打卡被归到前一天的情况。
|
||||
punches = get_punch_records(session, staff_id, prev_day, next_day)
|
||||
if not punches:
|
||||
return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None,
|
||||
"前一天最晚打卡": None, "班次开始时间": None, "班次结束时间": None,
|
||||
"次日班次开始时间": None, "打卡备注": "当天及次日无打卡记录"}
|
||||
# 按考勤归属日 bc_date 分组;time_order:1=上班打卡、2=下班打卡
|
||||
arrivals = {}
|
||||
checkouts = {}
|
||||
all_by_date = {}
|
||||
for r in punches:
|
||||
bd = str(r.get("bc_date", "")).strip()
|
||||
t = str(r.get("kq_time", "")).strip()
|
||||
if not bd or not t:
|
||||
continue
|
||||
all_by_date.setdefault(bd, []).append(t)
|
||||
if str(r.get("time_order", "")).strip() == "1":
|
||||
arrivals.setdefault(bd, []).append(t)
|
||||
elif str(r.get("time_order", "")).strip() == "2":
|
||||
checkouts.setdefault(bd, []).append(t)
|
||||
# 班次起止时间仍由考勤逐日接口提供;未获取到时由上层回退默认 09:00/18:00
|
||||
daily = get_attendance_daily(session, staff_id, prev_day, next_day)
|
||||
shift_begin, shift_end = _extract_shift_times(daily, ot_date)
|
||||
# 次日班次开始时间:弹性到岗兑换计算晚到时长时,次日上班时间优先取排班开始时间
|
||||
next_shift_begin, _ = _extract_shift_times(daily, next_day)
|
||||
|
||||
def _sorted(date_str):
|
||||
return sorted(all_by_date.get(date_str, []))
|
||||
|
||||
# 当日最早/最晚打卡:优先按上下班类型取,缺该类型时回退取当天全部打卡
|
||||
day_all = _sorted(ot_date)
|
||||
day_arrivals = sorted(arrivals.get(ot_date, []))
|
||||
day_checkouts = sorted(checkouts.get(ot_date, []))
|
||||
day_first = day_arrivals[0] if day_arrivals else (day_all[0] if day_all else None)
|
||||
day_last = day_checkouts[-1] if day_checkouts else (day_all[-1] if day_all else None)
|
||||
# 次日最早打卡(弹性兑换用)
|
||||
next_arrivals = sorted(arrivals.get(next_day, []))
|
||||
next_all = _sorted(next_day)
|
||||
next_first = next_arrivals[0] if next_arrivals else (next_all[0] if next_all else None)
|
||||
# 前一天最晚打卡(提前到岗型加班用)
|
||||
prev_all = _sorted(prev_day)
|
||||
prev_last = prev_all[-1] if prev_all else None
|
||||
return {
|
||||
"当日最早打卡": day_first,
|
||||
"当日最晚打卡": day_last,
|
||||
"次日最早打卡": next_first,
|
||||
"前一天最晚打卡": prev_last,
|
||||
"班次开始时间": shift_begin,
|
||||
"班次结束时间": shift_end,
|
||||
"次日班次开始时间": next_shift_begin,
|
||||
"打卡备注": "",
|
||||
}
|
||||
except Exception as e:
|
||||
logger.warning("获取打卡明细失败: %s", str(e))
|
||||
return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None,
|
||||
"前一天最晚打卡": None, "班次开始时间": None, "班次结束时间": None,
|
||||
"次日班次开始时间": None, "打卡备注": f"获取失败: {e}"}
|
||||
|
||||
|
||||
def _check_leave_covers_morning(session, staff_id, date_str):
|
||||
prev_day = (datetime.strptime(date_str, "%Y-%m-%d") - timedelta(days=1)).strftime("%Y-%m-%d")
|
||||
try:
|
||||
records = get_leave_records(session, staff_id, prev_day, date_str)
|
||||
except Exception as e:
|
||||
logger.warning("获取请假记录失败: %s", str(e))
|
||||
return False
|
||||
|
||||
# 上班时间优先取排班开始时间,未获取到排班时段时回退默认 09:00
|
||||
shift_begin = None
|
||||
try:
|
||||
daily = get_attendance_daily(session, staff_id, date_str, date_str)
|
||||
shift_begin, _ = _extract_shift_times(daily, date_str)
|
||||
except Exception as e:
|
||||
logger.warning("获取排班时段失败(%s): %s", date_str, str(e))
|
||||
morning_time = shift_begin or WORK_START_TIME
|
||||
morning = datetime.strptime(f"{date_str} {morning_time}", "%Y-%m-%d %H:%M")
|
||||
for r in records:
|
||||
start = _parse_dt(r.get("start_time"))
|
||||
end = _parse_dt(r.get("end_time"))
|
||||
if start and end and start <= morning <= end:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _validate_delayed(info, punch, session, staff_id):
|
||||
ot_date = info.get("加班日期")
|
||||
start = _parse_dt(info.get("加班开始时间"))
|
||||
end = _parse_dt(info.get("加班结束时间"))
|
||||
actual_checkout = _parse_dt(punch.get("当日最晚打卡"))
|
||||
reasons = []
|
||||
# 申请结束时间晚于实际下班打卡、但实际在岗时长(按系统取整)仍满足申请时长时,用于附加到通过备注
|
||||
end_checkout_note = ""
|
||||
|
||||
# 1. 日期校验:加班开始日期与申请加班日期不一致时直接校验不通过未处理,
|
||||
# 无需再校验后续的时长、区间合规等内容
|
||||
if start is None:
|
||||
reasons.append("加班开始时间缺失")
|
||||
elif start.strftime("%Y-%m-%d") != ot_date:
|
||||
reason = f"加班开始日期({start:%Y-%m-%d})与申请加班日期({ot_date})不一致"
|
||||
info["计算加班时长(小时)"] = None
|
||||
info["弹性扣减(小时)"] = 0
|
||||
info["有效加班时长(小时)"] = 0
|
||||
info["弹性额度D(小时)"] = 0
|
||||
return "校验不通过未处理", reason
|
||||
|
||||
# 2. 时长校验
|
||||
hours = None
|
||||
if end is None:
|
||||
reasons.append("加班结束时间缺失")
|
||||
elif start is not None:
|
||||
hours = _calc_delayed_hours(start, end)
|
||||
if hours < OT_MIN_HOURS:
|
||||
reasons.append(f"加班时长为{hours:g}小时,不足{OT_MIN_HOURS}小时")
|
||||
|
||||
# 3. 区间合规校验
|
||||
# 班次起止时间优先用打卡明细携带的班次时段(bc_begin_time/bc_end_time),
|
||||
# 未获取到时回退默认 09:00/18:00(常规班次),避免非18点下班班次被误判。
|
||||
shift_begin = punch.get("班次开始时间") or WORK_START_TIME
|
||||
shift_end = punch.get("班次结束时间") or WORK_END_TIME
|
||||
work_start = datetime.strptime(f"{ot_date} {shift_begin}", "%Y-%m-%d %H:%M")
|
||||
work_end = datetime.strptime(f"{ot_date} {shift_end}", "%Y-%m-%d %H:%M")
|
||||
# 提前到岗型延时加班:加班开始时间早于当天班次开始时间。
|
||||
# 常规"晚于规定下班时间""当日有下班打卡"校验不适用,改以加班开始时间附近的到岗打卡作为证据:
|
||||
# - 开始<=6点时,到岗打卡可能被系统归到前一天(跨天打卡),需回看前一天记录;
|
||||
# - 6点~9点开始的,到岗打卡归属当天,只看当天记录。
|
||||
is_pre_shift = start is not None and start < work_start
|
||||
if is_pre_shift:
|
||||
candidates = [punch.get("当日最早打卡")]
|
||||
cross_cutoff = start.replace(hour=CROSS_DAY_BEFORE_HOUR, minute=0, second=0, microsecond=0)
|
||||
if start <= cross_cutoff:
|
||||
candidates.append(punch.get("前一天最晚打卡"))
|
||||
arrival_punch = next(
|
||||
(c for c in candidates if _is_within_arrival_window(c, start)),
|
||||
None,
|
||||
)
|
||||
if arrival_punch is None:
|
||||
reasons.append(f"提前到岗型加班,未找到加班开始时间({start:%H:%M})附近的到岗打卡")
|
||||
else:
|
||||
info["到岗打卡"] = arrival_punch
|
||||
else:
|
||||
if start is not None and start < work_end:
|
||||
reasons.append(f"申请开始时间({start:%H:%M})早于规定下班时间({shift_end})")
|
||||
if end is not None:
|
||||
if actual_checkout is None:
|
||||
reasons.append("当日无下班打卡记录,无法校验区间合规")
|
||||
elif start is not None and hours is not None:
|
||||
# 核心原则:申请的加班时长必须与打卡可支撑的实际在岗时长相符。
|
||||
# 按系统取整规则(_calc_delayed_hours),用实际打卡区间(申请开始->实际下班打卡)
|
||||
# 计算实际在岗时长,>= 申请时长即通过(申请结束时间比打卡晚几分钟也属正常)。
|
||||
# 例:申请 18:00-23:05(取整5h),实际打卡23:00:45,实际在岗取整后也是5h,应通过
|
||||
actual_hours = _calc_delayed_hours(start, actual_checkout)
|
||||
if actual_hours >= hours:
|
||||
if end > actual_checkout:
|
||||
end_checkout_note = (
|
||||
f"申请结束时间({end:%H:%M})晚于实际下班打卡({actual_checkout:%H:%M:%S}),"
|
||||
f"实际在岗时长按系统取整为{actual_hours:g}小时,满足申请时长"
|
||||
)
|
||||
else:
|
||||
reasons.append(
|
||||
f"申请结束时间({end:%H:%M})晚于实际下班打卡时间({actual_checkout:%H:%M:%S}),"
|
||||
f"实际在岗时长按取整仅{actual_hours:g}小时,不足申请{hours:g}小时"
|
||||
)
|
||||
|
||||
info["计算加班时长(小时)"] = hours
|
||||
if reasons:
|
||||
info["弹性扣减(小时)"] = 0
|
||||
info["有效加班时长(小时)"] = hours
|
||||
info["弹性额度D(小时)"] = 0
|
||||
return "校验不通过未处理", ";".join(reasons)
|
||||
|
||||
# 4. 弹性到岗兑换
|
||||
deduction = 0.0
|
||||
flex_note = ""
|
||||
d_hours = 0.0
|
||||
flex_trigger = datetime.strptime(f"{ot_date} {FLEX_TRIGGER_TIME}", "%Y-%m-%d %H:%M")
|
||||
|
||||
if actual_checkout is not None and actual_checkout >= flex_trigger:
|
||||
d_hours = _calc_flex_d(actual_checkout, flex_trigger)
|
||||
next_day = _next_day(ot_date)
|
||||
next_shift = _get_shift(session, staff_id, next_day)
|
||||
|
||||
if next_shift in ("休息", "无排班"):
|
||||
flex_note = f"次日({next_day})为休息日,不触发弹性兑换"
|
||||
elif next_shift in ("获取失败", "未知"):
|
||||
flex_note = f"次日({next_day})排班获取失败,不触发弹性兑换"
|
||||
elif _check_leave_covers_morning(session, staff_id, next_day):
|
||||
flex_note = f"次日({next_day})请假覆盖早上上班时间,不触发弹性兑换"
|
||||
else:
|
||||
# 次日上班时间优先取排班开始时间,未获取到排班时段时回退默认 09:00
|
||||
next_shift_begin = punch.get("次日班次开始时间") or WORK_START_TIME
|
||||
work_start = datetime.strptime(f"{next_day} {next_shift_begin}", "%Y-%m-%d %H:%M")
|
||||
p = _parse_dt(punch.get("次日最早打卡"))
|
||||
|
||||
if p is None:
|
||||
flex_note = f"次日({next_day})无打卡记录,不触发弹性兑换"
|
||||
elif p <= work_start:
|
||||
flex_note = f"次日打卡({p:%H:%M})准时或提前,无需兑换"
|
||||
else:
|
||||
# 有晚到,校验:加班时长 + 晚到 <= 实际在岗时长(按系统取整)
|
||||
# 实际在岗时长 = 加班开始->实际下班打卡 按延时取整(1h起算0.5h累加)
|
||||
actual_work = _calc_delayed_hours(start, actual_checkout)
|
||||
lunch_trigger = datetime.strptime(
|
||||
f"{next_day} {FLEX_LATE_LUNCH_TRIGGER_TIME}", "%Y-%m-%d %H:%M"
|
||||
)
|
||||
|
||||
if p <= work_start + timedelta(hours=d_hours):
|
||||
# T < P <= T+D:晚到时长 = P-T,次日打卡超过13:00时
|
||||
# 再扣1小时午餐,按1小时起算向上取整(不足1小时不扣)
|
||||
late_raw = (p - work_start).total_seconds() / 3600
|
||||
if p > lunch_trigger:
|
||||
late_raw -= LUNCH_BREAK_HOURS
|
||||
late_hours = math.ceil(late_raw) if late_raw >= OT_MIN_HOURS else 0
|
||||
if late_hours < 1:
|
||||
flex_note = f"次日打卡({p:%H:%M})晚到不足1小时,不触发弹性兑换"
|
||||
else:
|
||||
if hours + late_hours > actual_work:
|
||||
info["弹性扣减(小时)"] = 0
|
||||
info["有效加班时长(小时)"] = hours
|
||||
info["弹性额度D(小时)"] = d_hours
|
||||
return "校验不通过未处理", (
|
||||
f"弹性兑换校验校验不通过未处理:申请加班{hours:g}h + 晚到{late_hours}h "
|
||||
f"> 实际在岗时长{actual_work:g}h"
|
||||
)
|
||||
deduction = float(late_hours)
|
||||
flex_note = f"次日打卡({p:%H:%M})晚到,兑换{late_hours}小时"
|
||||
else:
|
||||
if hours + d_hours > actual_work:
|
||||
info["弹性扣减(小时)"] = 0
|
||||
info["有效加班时长(小时)"] = hours
|
||||
info["弹性额度D(小时)"] = d_hours
|
||||
return "校验不通过未处理", (
|
||||
f"弹性兑换校验校验不通过未处理:申请加班{hours:g}h + 兑换额度{d_hours:g}h "
|
||||
f"> 实际在岗时长{actual_work:g}h"
|
||||
)
|
||||
deduction = float(d_hours)
|
||||
flex_note = (
|
||||
f"次日打卡({p:%H:%M})超出弹性区间(D={d_hours:g}h),"
|
||||
f"按D兑换,超出部分交考勤处理"
|
||||
)
|
||||
else:
|
||||
if actual_checkout is not None:
|
||||
flex_note = f"实际下班打卡({actual_checkout:%H:%M})早于{FLEX_TRIGGER_TIME},弹性额度D=0"
|
||||
|
||||
effective = max(0.0, float(hours) - deduction)
|
||||
info["弹性扣减(小时)"] = deduction
|
||||
info["有效加班时长(小时)"] = effective
|
||||
info["弹性额度D(小时)"] = d_hours
|
||||
note = f"审批通过,有效加班时长{effective:g}小时"
|
||||
extra_parts = [end_checkout_note, flex_note]
|
||||
extra = ";".join(p for p in extra_parts if p)
|
||||
if extra:
|
||||
note += f"({extra})"
|
||||
return "通过", note
|
||||
|
||||
|
||||
def _validate_day_ot(info, punch, session, staff_id, require_holiday):
|
||||
ot_date = info.get("加班日期")
|
||||
reasons = []
|
||||
|
||||
shift = info.get("加班当天班次", "")
|
||||
if shift not in ("休息", "获取失败", "未知", "无排班"):
|
||||
reasons.append(f"当天排班为'{shift}',非休息日")
|
||||
|
||||
if require_holiday and not _is_spring_festival(ot_date):
|
||||
reasons.append(f"{ot_date}不在春节法定节假日列表中")
|
||||
|
||||
# 加班时长 > 0:休息日加班按天计,表单 ot_hour 常为 0(aa.md 中 ot_hours=0.0、ot_days=1.00),
|
||||
# 此时用申报起止时间推算实际加班时长,避免误校验不通过未处理
|
||||
ot_hour = info.get("加班时长(小时)") or info.get("系统判断加班时长(小时)")
|
||||
try:
|
||||
ot_hour = float(ot_hour)
|
||||
except (TypeError, ValueError):
|
||||
ot_hour = 0.0
|
||||
if ot_hour <= 0:
|
||||
start = _parse_dt(info.get("加班开始时间"))
|
||||
end = _parse_dt(info.get("加班结束时间"))
|
||||
if start and end and end > start:
|
||||
ot_hour = (end - start).total_seconds() / 3600
|
||||
if ot_hour <= 0:
|
||||
reasons.append("加班时长为0或缺失")
|
||||
|
||||
first = _parse_dt(punch.get("当日最早打卡"))
|
||||
last = _parse_dt(punch.get("当日最晚打卡"))
|
||||
interval = None
|
||||
# 打卡明细接口已按考勤归属日 bc_date 分组,跨天打卡(次日0点~6点)归入加班当天,
|
||||
# 因此当日最早/最晚打卡已包含跨天下班打卡,无需再参考次日打卡补全。
|
||||
if first is None or last is None:
|
||||
reasons.append("当天缺少上班或下班打卡")
|
||||
else:
|
||||
interval = (last - first).total_seconds() / 3600
|
||||
|
||||
apply_days = info.get("加班天数(天)") or info.get("系统判断加班天数(天)")
|
||||
try:
|
||||
apply_days = float(apply_days)
|
||||
except (TypeError, ValueError):
|
||||
apply_days = 0.0
|
||||
if apply_days <= 0:
|
||||
reasons.append("申报天数缺失或为0")
|
||||
elif interval is not None:
|
||||
threshold = _calc_day_ot_threshold(apply_days)
|
||||
# 职能排班半天(0.5天)加班:上午3.5小时、下午4.5小时,不再统一按4小时半天处理;
|
||||
# 上/下午按申请加班开始时间判定(早于12:00视为上午半天)
|
||||
if abs(apply_days - 0.5) < 1e-9 and _is_zhineng_schedule(session, staff_id, ot_date):
|
||||
start = _parse_dt(info.get("加班开始时间"))
|
||||
if start is not None and start.hour < ZHINENG_HALF_CUTOFF_HOUR:
|
||||
threshold = ZHINENG_HALF_MORNING_HOURS
|
||||
else:
|
||||
threshold = ZHINENG_HALF_AFTERNOON_HOURS
|
||||
if interval < threshold:
|
||||
reasons.append(
|
||||
f"打卡间隔{interval:.2f}小时不足申报{apply_days:g}天所需的{threshold:g}小时"
|
||||
)
|
||||
|
||||
info["打卡时间间隔(小时)"] = interval
|
||||
info["申报天数(天)"] = apply_days
|
||||
if reasons:
|
||||
return "校验不通过未处理", ";".join(reasons)
|
||||
return "通过", f"审批通过(申报{apply_days:g}天,打卡间隔{interval:.2f}小时)"
|
||||
|
||||
|
||||
def check_review_period(ot_date, today=None):
|
||||
"""
|
||||
加班日期有效性前置校验,返回 (是否可审核, 原因)。
|
||||
|
||||
规则:
|
||||
1. 审核周期 OT_REVIEW_DAYS 天:加班日期距今天超过该天数,不再审核;
|
||||
2. 月度截止:每月 MONTH_CUTOFF_DAY 号 MONTH_CUTOFF_HOUR:00 之后,
|
||||
不再审核上一个月的加班流程。
|
||||
"""
|
||||
if not ot_date:
|
||||
return False, "加班日期缺失,无法校验审核周期"
|
||||
try:
|
||||
ot_day = datetime.strptime(ot_date, "%Y-%m-%d")
|
||||
except (TypeError, ValueError):
|
||||
return False, f"加班日期格式非法: {ot_date}"
|
||||
|
||||
today = today or datetime.now()
|
||||
today_date = today.date()
|
||||
|
||||
# 规则1:8天审核周期
|
||||
if (today_date - ot_day.date()).days > OT_REVIEW_DAYS:
|
||||
return False, f"加班日期({ot_date})距今超过{OT_REVIEW_DAYS}天审核周期,不再审核"
|
||||
|
||||
# 规则2:每月2号12点之后不再审核上月加班
|
||||
if ot_day.date() < today_date.replace(day=1):
|
||||
if today.day > MONTH_CUTOFF_DAY or (today.day == MONTH_CUTOFF_DAY and today.hour >= MONTH_CUTOFF_HOUR):
|
||||
return False, (f"加班日期({ot_date})属于上月或更早,已超过本月{MONTH_CUTOFF_DAY}号"
|
||||
f"{MONTH_CUTOFF_HOUR}点,不再审核上月加班流程")
|
||||
|
||||
return True, ""
|
||||
|
||||
|
||||
def validate_doc(doc, session):
|
||||
form_data = doc.get("formData", {}) or {}
|
||||
overtime_info = parse_overtime_form(form_data)
|
||||
|
||||
# 前置校验:加班日期有效性(8天审核周期 + 每月2号12点后不再审核上月加班)
|
||||
valid, period_reason = check_review_period(overtime_info.get("加班日期"))
|
||||
if not valid:
|
||||
return {
|
||||
"title": doc.get("title", ""),
|
||||
"creator": doc.get("creator", ""),
|
||||
"time": doc.get("time", ""),
|
||||
"detail_url": doc.get("detail_url", ""),
|
||||
"decision": "超期",
|
||||
"note": period_reason,
|
||||
"overtime_info": overtime_info,
|
||||
}
|
||||
|
||||
staff_id = overtime_info.get("加班人员ID")
|
||||
ot_date = overtime_info.get("加班日期")
|
||||
|
||||
attendance_info = _check_attendance(session, staff_id, ot_date)
|
||||
punch_info = _check_punch_records(session, staff_id, ot_date)
|
||||
overtime_info.update(attendance_info)
|
||||
overtime_info.update(punch_info)
|
||||
|
||||
ot_type_code = str(form_data.get("ot_type") or "")
|
||||
if ot_type_code == "1":
|
||||
decision, note = _validate_delayed(overtime_info, punch_info, session, staff_id)
|
||||
elif ot_type_code == "3":
|
||||
decision, note = _validate_day_ot(overtime_info, punch_info, session, staff_id, require_holiday=False)
|
||||
elif ot_type_code == "2":
|
||||
require_holiday = _is_spring_festival(ot_date)
|
||||
decision, note = _validate_day_ot(overtime_info, punch_info, session, staff_id, require_holiday=require_holiday)
|
||||
else:
|
||||
decision, note = "校验不通过未处理", f"无法识别加班类型: {ot_type_code}"
|
||||
|
||||
return {
|
||||
"title": doc.get("title", ""),
|
||||
"creator": doc.get("creator", ""),
|
||||
"time": doc.get("time", ""),
|
||||
"detail_url": doc.get("detail_url", ""),
|
||||
"decision": decision,
|
||||
"note": note,
|
||||
"overtime_info": overtime_info,
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0004",
|
||||
"name": "EHR系统加班流程审核",
|
||||
"version": "1.0.0",
|
||||
"description": "自动审核 EHR 加班待办:拉取待办与加班表单,按加班类型(延时/法定假日/休息日)校验加班日期、时长、排班与打卡区间及弹性到岗兑换;校验通过自动提交审批,并生成审批报告与钉钉群推送。",
|
||||
"category": "人事考勤",
|
||||
"icon": "",
|
||||
"platform": "hr",
|
||||
"uses_month": false,
|
||||
"ui": true,
|
||||
"capabilities": ["xq0004"],
|
||||
"permissions": {
|
||||
"platforms": ["hr"]
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"save_dir": {
|
||||
"type": "string",
|
||||
"title": "输出目录",
|
||||
"default": "D:\\资料\\人资\\加班流程审批",
|
||||
"description": "加班审批报告存放目录"
|
||||
},
|
||||
"approve_enabled": {
|
||||
"type": "boolean",
|
||||
"title": "自动提交审批",
|
||||
"default": true,
|
||||
"description": "开启后,校验结论为「通过」的单据会在流程详情页自动点击同意;关闭则只校验不提交"
|
||||
},
|
||||
"push_enabled": {
|
||||
"type": "boolean",
|
||||
"title": "钉钉群推送",
|
||||
"default": true,
|
||||
"description": "开启后把汇总与需人工处理明细推送到钉钉群机器人"
|
||||
},
|
||||
"push_env": {
|
||||
"type": "string",
|
||||
"title": "推送环境",
|
||||
"default": "dev",
|
||||
"description": "dev=内置测试群,prod=内置生产群;填写自定义 Webhook 时以自定义为准"
|
||||
},
|
||||
"dingtalk_webhook": {
|
||||
"type": "string",
|
||||
"title": "钉钉 Webhook",
|
||||
"default": "",
|
||||
"description": "留空使用内置默认机器人;需要发到其他群时填写完整 webhook 地址"
|
||||
},
|
||||
"dingtalk_secret": {
|
||||
"type": "string",
|
||||
"title": "钉钉加签密钥",
|
||||
"default": "",
|
||||
"description": "机器人启用加签安全设置时填写,留空表示不加签"
|
||||
},
|
||||
"debug_mode": {
|
||||
"type": "boolean",
|
||||
"title": "调试日志",
|
||||
"default": false,
|
||||
"description": "开启后输出接口返回等调试信息"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 加班流程审核 插件 - 报告与推送层。"""
|
||||
@@ -1,230 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 EHR系统加班流程审核 插件 - 钉钉群机器人推送(插件内单一真源)。
|
||||
|
||||
推送原理(HTTP Webhook,零第三方依赖,仅标准库,符合插件自包含约束):
|
||||
按钉钉加签规则(HMAC-SHA256 + Base64 + URL 编码)生成签名,
|
||||
向机器人 Webhook 推送 Markdown 消息,失败自动重试 3 次。
|
||||
|
||||
约定:
|
||||
- 默认 webhook/加签密钥来自插件字段(UI 配置),字段为空时回退本文件默认配置;
|
||||
- env='dev' 走测试环境机器人,避免调试时误发生产群。
|
||||
|
||||
用法:
|
||||
main("需要推送的通知文本");
|
||||
text 传「块格式分组」字典列表 [{title, blocks, status?}] 时由本模块自动分批逐条推送。
|
||||
返回: {"success": bool, "message": str}
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime
|
||||
|
||||
from ..config import logger
|
||||
|
||||
# ==================== 默认配置 ====================
|
||||
DEFAULT_WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=65dd3f38dea12d2419743aad62ed25f5544ae1ff2ff7d2f667682e0dc912ff6e'
|
||||
DEFAULT_SECRET = '' # 加签密钥(未配置则不加签)
|
||||
DEFAULT_SERVER_NAME = '37du 任务调度平台'
|
||||
|
||||
# 测试环境配置(env='dev' 时使用;默认使用 DEFAULT_WEBHOOK)
|
||||
DEV_WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=26613569642db03fae6fd19cc932a4b08d82fd09afd35ccfd3ddee5884b5cb66'
|
||||
DEV_SECRET = ''
|
||||
DEV_SERVER_NAME = '37du 任务调度平台'
|
||||
|
||||
ENV_CONFIGS = {
|
||||
'prod': {'webhook': DEFAULT_WEBHOOK, 'secret': DEFAULT_SECRET, 'server_name': DEFAULT_SERVER_NAME},
|
||||
'dev': {'webhook': DEV_WEBHOOK, 'secret': DEV_SECRET, 'server_name': DEV_SERVER_NAME},
|
||||
}
|
||||
|
||||
DEFAULT_TIMEOUT = 10
|
||||
DEFAULT_RETRY_TIMES = 3
|
||||
|
||||
_STATUS_COLORS = {
|
||||
'info': '#0077ff',
|
||||
'success': '#00b300',
|
||||
'warning': '#ff9900',
|
||||
'error': '#ff0000',
|
||||
}
|
||||
|
||||
|
||||
def _build_sign(secret, timestamp_ms):
|
||||
"""按钉钉加签规则计算签名(HMAC-SHA256 + Base64 + URL 编码)。"""
|
||||
string_to_sign = f"{timestamp_ms}\n{secret}"
|
||||
hmac_code = hmac.new(
|
||||
secret.encode('utf-8'), string_to_sign.encode('utf-8'), digestmod=hashlib.sha256
|
||||
).digest()
|
||||
return urllib.parse.quote_plus(base64.b64encode(hmac_code))
|
||||
|
||||
|
||||
def _build_url(webhook, secret=''):
|
||||
"""拼接最终推送地址:配置了 secret 时追加 timestamp + sign 参数。"""
|
||||
if not secret:
|
||||
return webhook
|
||||
ts = int(round(time.time() * 1000))
|
||||
separator = '&' if '?' in webhook else '?'
|
||||
return f"{webhook}{separator}timestamp={ts}&sign={_build_sign(secret, ts)}"
|
||||
|
||||
|
||||
class DingTalkRobot:
|
||||
"""钉钉群机器人推送器。"""
|
||||
|
||||
def __init__(self, webhook='', secret='', server_name='', timeout=DEFAULT_TIMEOUT):
|
||||
self.webhook = (webhook or DEFAULT_WEBHOOK).strip()
|
||||
self.secret = (secret or DEFAULT_SECRET).strip()
|
||||
self.server_name = (server_name or DEFAULT_SERVER_NAME).strip()
|
||||
self.timeout = timeout
|
||||
if not self.webhook:
|
||||
raise ValueError('webhook 不能为空')
|
||||
|
||||
def _post(self, payload):
|
||||
"""推送 payload 到机器人,errcode != 0 视为失败;失败自动重试。"""
|
||||
last_err = None
|
||||
for attempt in range(DEFAULT_RETRY_TIMES):
|
||||
try:
|
||||
url = _build_url(self.webhook, self.secret)
|
||||
data = json.dumps(payload, ensure_ascii=False).encode('utf-8')
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=data,
|
||||
headers={'Content-Type': 'application/json; charset=utf-8'},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
||||
body = resp.read().decode('utf-8')
|
||||
resp_data = json.loads(body)
|
||||
if resp_data.get('errcode') != 0:
|
||||
raise RuntimeError(
|
||||
f"钉钉机器人返回错误 errcode={resp_data.get('errcode')}, "
|
||||
f"errmsg={resp_data.get('errmsg')}"
|
||||
)
|
||||
return
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
logger.warning("推送失败(第 %d/%d 次):%s", attempt + 1, DEFAULT_RETRY_TIMES, e)
|
||||
time.sleep(1)
|
||||
raise RuntimeError(f"推送失败,重试 {DEFAULT_RETRY_TIMES} 次后仍出错:{last_err}")
|
||||
|
||||
def send(self, title, content, status='info', server_name=''):
|
||||
"""发送统一通知(Markdown:标题按状态着色,正文直接渲染,带页脚)。"""
|
||||
color = _STATUS_COLORS.get(status, _STATUS_COLORS['info'])
|
||||
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
||||
display_name = (server_name or self.server_name).strip()
|
||||
footer = f"\n\n---\n\n###### {display_name} | {now}"
|
||||
|
||||
text = f"**<font color='{color}'>{title}</font>**\n\n"
|
||||
text += content.strip() + "\n"
|
||||
text += footer
|
||||
|
||||
payload = {'msgtype': 'markdown', 'markdown': {'title': title, 'text': text}}
|
||||
logger.info("钉钉机器人推送通知 [%s]: %s", status, title)
|
||||
self._post(payload)
|
||||
|
||||
def send_in_batches(self, title, content, status='info', server_name='',
|
||||
max_chars=15000):
|
||||
"""分批发送长内容(按行智能拆分,避免切断单行数据)。"""
|
||||
lines = content.strip().split('\n')
|
||||
batches = []
|
||||
current_batch = []
|
||||
current_len = 0
|
||||
|
||||
for line in lines:
|
||||
line_len = len(line) + 1
|
||||
if current_len + line_len > max_chars and current_batch:
|
||||
batches.append('\n'.join(current_batch))
|
||||
current_batch = [line]
|
||||
current_len = line_len
|
||||
else:
|
||||
current_batch.append(line)
|
||||
current_len += line_len
|
||||
|
||||
if current_batch:
|
||||
batches.append('\n'.join(current_batch))
|
||||
|
||||
total = len(batches)
|
||||
for i, batch_content in enumerate(batches, 1):
|
||||
batch_title = f"{title}(第{i}/{total}批)" if total > 1 else title
|
||||
logger.info("分批推送 %d/%d: %s", i, total, batch_title)
|
||||
self.send(batch_title, batch_content, status=status, server_name=server_name)
|
||||
|
||||
|
||||
def compose_batch_messages(blocks, title_prefix, batch_size=10):
|
||||
"""把块格式 block 列表按 batch_size 条一批,生成带批次标题的消息文本列表。"""
|
||||
if not blocks:
|
||||
return []
|
||||
result = []
|
||||
total_batches = (len(blocks) + batch_size - 1) // batch_size
|
||||
for bi in range(total_batches):
|
||||
batch = blocks[bi * batch_size:(bi + 1) * batch_size]
|
||||
header = f"###### {title_prefix}(第{bi + 1}/{total_batches}批)\n\n"
|
||||
footer = f"\n\n###### 本批共{len(batch)}条"
|
||||
content = header + '\n\n'.join(batch) + footer
|
||||
result.append(content)
|
||||
return result
|
||||
|
||||
|
||||
def main(text, title='消息通知', status='info', webhook='', secret='', server_name='',
|
||||
env='prod', batch=False, max_chars=15000):
|
||||
"""钉钉群机器人推送入口。
|
||||
|
||||
text 支持:
|
||||
- 纯文本:单条 Markdown 推送;
|
||||
- 字典列表 {title, blocks, status?, batch_size?}:块格式分组,自动分批逐条推送;
|
||||
- 文本列表:按顺序逐条发送。
|
||||
|
||||
返回: {"success": bool, "message": str}
|
||||
"""
|
||||
try:
|
||||
if text is None or (isinstance(text, str) and not str(text).strip()) \
|
||||
or (isinstance(text, list) and not text):
|
||||
return {'success': False, 'message': '通知文本不能为空'}
|
||||
env_key = (env or 'prod').strip().lower()
|
||||
if env_key not in ENV_CONFIGS:
|
||||
return {'success': False, 'message': f'未知环境 [{env_key}],可选:{" / ".join(ENV_CONFIGS)}'}
|
||||
cfg = ENV_CONFIGS[env_key]
|
||||
webhook = (webhook or '').strip() or cfg['webhook']
|
||||
secret = (secret or '').strip() or cfg['secret']
|
||||
server_name = server_name or cfg['server_name']
|
||||
if not webhook:
|
||||
return {'success': False, 'message': f'环境 [{env_key}] 的 webhook 未配置'}
|
||||
robot = DingTalkRobot(webhook=webhook, secret=secret, server_name=server_name)
|
||||
|
||||
items = text if isinstance(text, list) else [text]
|
||||
sent = 0
|
||||
last_title, last_status = title, status
|
||||
for item in items:
|
||||
if isinstance(item, dict) and item.get('blocks') is not None:
|
||||
ti = item.get('title', title)
|
||||
st = item.get('status', status)
|
||||
bs = int(item.get('batch_size', 10) or 10)
|
||||
for batch_content in compose_batch_messages(item['blocks'], ti, bs):
|
||||
robot.send(str(ti), str(batch_content), status=st, server_name=server_name)
|
||||
sent += 1
|
||||
last_title, last_status = ti, st
|
||||
continue
|
||||
if isinstance(item, dict):
|
||||
t = item.get('text')
|
||||
ti = item.get('title', title)
|
||||
st = item.get('status', status)
|
||||
bc = item.get('batch', batch)
|
||||
mc = item.get('max_chars', max_chars)
|
||||
else:
|
||||
t, ti, st, bc, mc = item, title, status, batch, max_chars
|
||||
if t is None or not str(t).strip():
|
||||
continue
|
||||
if bc:
|
||||
robot.send_in_batches(str(ti), str(t), status=st,
|
||||
server_name=server_name, max_chars=mc)
|
||||
else:
|
||||
robot.send(str(ti), str(t), status=st, server_name=server_name)
|
||||
sent += 1
|
||||
last_title, last_status = ti, st
|
||||
if sent == 0:
|
||||
return {'success': False, 'message': '通知文本为空'}
|
||||
if len(items) == 1:
|
||||
return {'success': True, 'message': f'已推送通知 [{env_key}/{last_status}]:{last_title}'}
|
||||
return {'success': True, 'message': f'已推送 {sent} 条通知 [{env_key}]'}
|
||||
except Exception as e:
|
||||
return {'success': False, 'message': str(e)}
|
||||
@@ -1,249 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 EHR系统加班流程审核 插件 - 报告生成与推送摘要(由影刀版移植)。"""
|
||||
import os
|
||||
from datetime import datetime
|
||||
|
||||
from ..config import logger
|
||||
|
||||
|
||||
def _name(r):
|
||||
info = r.get("overtime_info", {}) or {}
|
||||
return info.get("加班人员") or r.get("creator") or "未知"
|
||||
|
||||
|
||||
def _otype(r):
|
||||
info = r.get("overtime_info", {}) or {}
|
||||
return info.get("加班类型") or "未知"
|
||||
|
||||
|
||||
def _format_detail(info):
|
||||
"""将 overtime_info 字典格式化为易读的明细行。"""
|
||||
fields = [
|
||||
("加班人员", "加班人员"),
|
||||
("组织全路径", "组织全路径"),
|
||||
("岗位", "岗位"),
|
||||
("加班类型", "加班类型"),
|
||||
("补贴类型", "补贴类型"),
|
||||
("加班日期", "加班日期"),
|
||||
("加班开始时间", "加班开始时间"),
|
||||
("加班结束时间", "加班结束时间"),
|
||||
("加班时长(小时)", "加班时长"),
|
||||
("加班天数(天)", "加班天数"),
|
||||
("系统判断加班时长(小时)", "系统判定时长"),
|
||||
("系统判断加班天数(天)", "系统判定天数"),
|
||||
("系统判定加班时间", "系统判定时间"),
|
||||
("加班当天班次", "当天班次"),
|
||||
("当日最早打卡", "最早打卡"),
|
||||
("当日最晚打卡", "最晚打卡"),
|
||||
("次日最早打卡", "次日最早打卡"),
|
||||
("前一天最晚打卡", "前一天最晚打卡"),
|
||||
("到岗打卡", "到岗打卡"),
|
||||
("计算加班时长(小时)", "计算时长"),
|
||||
("弹性扣减(小时)", "弹性扣减"),
|
||||
("有效加班时长(小时)", "有效时长"),
|
||||
("弹性额度D(小时)", "弹性额度D"),
|
||||
("打卡时间间隔(小时)", "打卡间隔"),
|
||||
("申报天数(天)", "申报天数"),
|
||||
("打卡备注", "打卡备注"),
|
||||
]
|
||||
parts = []
|
||||
for key, label in fields:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
parts.append(f"{label}={val}")
|
||||
return " | ".join(parts)
|
||||
|
||||
|
||||
def generate_report(results):
|
||||
"""
|
||||
生成加班审批报告:汇总行 + 每条明细 + 校验不通过未处理清单 + 人工复核清单(+处理失败)。
|
||||
|
||||
输出:
|
||||
- 每条审批的完整明细(含加班日期、时长、打卡、排班等)
|
||||
- 《加班审批校验不通过未处理人员明细清单》:员工姓名、加班类型、校验不通过原因
|
||||
- 《附件人工复核待办清单》:员工姓名、加班类型、详情页链接
|
||||
- 《超期加班待人资处理清单》:员工姓名、加班类型、处理原因、详情页链接(供人资人工处理)
|
||||
"""
|
||||
passed = [r for r in results if r.get("decision") == "通过"]
|
||||
rejected = [r for r in results if r.get("decision") == "校验不通过未处理"]
|
||||
review = [r for r in results if r.get("decision") == "人工复核"]
|
||||
overdue = [r for r in results if r.get("decision") == "超期"]
|
||||
abnormal = [r for r in results if r.get("decision") == "异常"]
|
||||
failed = [r for r in results if r.get("decision") == "失败"]
|
||||
|
||||
summary = f"共 {len(results)} 单:通过 {len(passed)},校验不通过未处理 {len(rejected)},人工复核 {len(review)}"
|
||||
if overdue:
|
||||
summary += f",超期待人资处理 {len(overdue)}"
|
||||
if abnormal:
|
||||
summary += f",审批异常 {len(abnormal)}"
|
||||
if failed:
|
||||
summary += f",处理失败 {len(failed)}"
|
||||
|
||||
lines = [
|
||||
"加班审批报告",
|
||||
"=" * 60,
|
||||
summary,
|
||||
"",
|
||||
]
|
||||
|
||||
# ----- 明细清单(所有审批单的完整数据) -----
|
||||
lines.append("【审批明细】")
|
||||
for i, r in enumerate(results, 1):
|
||||
info = r.get("overtime_info", {}) or {}
|
||||
decision = r.get("decision", "未知")
|
||||
note = r.get("note") or r.get("error") or ""
|
||||
lines.append(f" #{i} {_name(r)}({_otype(r)})-> {decision}")
|
||||
detail = _format_detail(info)
|
||||
if detail:
|
||||
lines.append(f" {detail}")
|
||||
if note:
|
||||
lines.append(f" 备注: {note}")
|
||||
if r.get("审批动作"):
|
||||
lines.append(f" 审批动作: {r['审批动作']}({r.get('审批结果', '')})")
|
||||
lines.append("")
|
||||
|
||||
# ----- 校验不通过未处理清单 -----
|
||||
if rejected:
|
||||
lines.append("《加班审批校验不通过未处理人员明细清单》")
|
||||
for i, r in enumerate(rejected, 1):
|
||||
reason = r.get("note") or r.get("error") or ""
|
||||
url = r.get("detail_url") or "无"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 校验不通过原因: {reason} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 人工复核清单 -----
|
||||
if review:
|
||||
lines.append("《附件人工复核待办清单》")
|
||||
for i, r in enumerate(review, 1):
|
||||
url = r.get("detail_url") or "无"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 超期待人资处理清单 -----
|
||||
if overdue:
|
||||
lines.append("《超期加班待人资处理清单》")
|
||||
lines.append("(已超出审核周期,需人资人工处理,对应员工及原因如下)")
|
||||
for i, r in enumerate(overdue, 1):
|
||||
reason = r.get("note") or r.get("error") or ""
|
||||
url = r.get("detail_url") or "无"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 处理原因: {reason} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 处理失败 -----
|
||||
if failed:
|
||||
lines.append("【处理失败】")
|
||||
for i, r in enumerate(failed, 1):
|
||||
lines.append(f"{i}. {_name(r)} | {r.get('title', '')} | 错误: {r.get('error', '')}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 审批异常(审批提交失败,需人工跟进) -----
|
||||
if abnormal:
|
||||
lines.append("《加班审批异常待人工确认清单》")
|
||||
lines.append("(机器已出结论但审批提交未成功,OA 中单据状态未变,需人工跟进)")
|
||||
for i, r in enumerate(abnormal, 1):
|
||||
reason = r.get("note") or r.get("error") or "未知"
|
||||
url = r.get("detail_url") or "无"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 原因: {reason} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _format_overtime_block(r):
|
||||
"""将单条加班审批结果格式化为块格式 Markdown。"""
|
||||
info = r.get("overtime_info", {}) or {}
|
||||
name = info.get("加班人员") or r.get("creator") or "未知"
|
||||
otype = info.get("加班类型") or ""
|
||||
lines = [f"**🔹 {name}‑{otype}**"]
|
||||
for key, label in [
|
||||
("加班人员", "加班人员"),
|
||||
("岗位", "岗位"),
|
||||
("组织全路径", "组织全路径"),
|
||||
("加班类型", "加班类型"),
|
||||
("补贴类型", "补贴类型"),
|
||||
]:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
lines.append(f"> {label}:{val}")
|
||||
date = info.get("加班日期")
|
||||
if date:
|
||||
lines.append(f"> 加班日期:{date}")
|
||||
start = info.get("加班开始时间")
|
||||
end = info.get("加班结束时间")
|
||||
if start or end:
|
||||
lines.append(f"> 加班时段:{start or ''} ~ {end or ''}")
|
||||
for key, label in [("加班时长(小时)", "加班时长"), ("加班天数(天)", "加班天数"),
|
||||
("系统判定加班时间", "系统判定时间"),
|
||||
("计算加班时长(小时)", "计算时长"),
|
||||
("有效加班时长(小时)", "有效时长"),
|
||||
("弹性扣减(小时)", "弹性扣减"),
|
||||
("申报天数(天)", "申报天数")]:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
lines.append(f"> {label}:{val}")
|
||||
note = r.get("note") or r.get("error") or ""
|
||||
if note:
|
||||
lines.append(f"> 备注:{note}")
|
||||
url = r.get("detail_url") or ""
|
||||
if url:
|
||||
lines.append(f"> 详情页:[查看详情]({url})")
|
||||
# 钉钉 Markdown 引用块内每行需用双换行(空行)分隔才会换行,单换行会被合并
|
||||
return '\n\n'.join(lines)
|
||||
|
||||
|
||||
def build_push_summary(results, subject=""):
|
||||
"""
|
||||
按结果类型生成块格式 Markdown 推送分组。
|
||||
|
||||
返回:字典列表,每项 {"title": 分组标题, "blocks": [每条记录格式化后的 block 字符串]},
|
||||
分批/推送由机器人推送模块内部完成(调用方不关心批次)。
|
||||
"""
|
||||
if not results:
|
||||
return []
|
||||
passed = [r for r in results if r.get("decision") == "通过"]
|
||||
rejected = [r for r in results if r.get("decision") == "校验不通过未处理"]
|
||||
review = [r for r in results if r.get("decision") == "人工复核"]
|
||||
overdue = [r for r in results if r.get("decision") == "超期"]
|
||||
abnormal = [r for r in results if r.get("decision") == "异常"]
|
||||
failed = [r for r in results if r.get("decision") == "失败"]
|
||||
if not passed and not rejected and not review and not overdue and not abnormal and not failed:
|
||||
return []
|
||||
|
||||
messages = []
|
||||
|
||||
def _push_group(title_prefix, records):
|
||||
if not records:
|
||||
return
|
||||
blocks = [_format_overtime_block(r) for r in records]
|
||||
messages.append({"title": title_prefix, "blocks": blocks})
|
||||
|
||||
# 汇总消息先发:本次审批各类别数量(一条,含 0 的类别)
|
||||
summary_lines = [f"本次共审批 **{len(results)}** 条:"]
|
||||
for label, cnt in [("通过", len(passed)),
|
||||
("校验不通过未处理", len(rejected)),
|
||||
("需人工复核", len(review)),
|
||||
("超期待人资处理", len(overdue)),
|
||||
("审批异常", len(abnormal)),
|
||||
("处理失败", len(failed))]:
|
||||
summary_lines.append(f"- {label}:{cnt} 条")
|
||||
messages.append({"title": f"【{subject}审批】汇总", "blocks": ["\n".join(summary_lines)]})
|
||||
|
||||
# 通过的单据数量太多,不再逐条推送明细,只保留汇总计数与需人工处理的明细
|
||||
_push_group(f"【{subject}审批】校验不通过未处理", rejected)
|
||||
_push_group(f"【{subject}审批】需人工复核", review)
|
||||
_push_group(f"【{subject}审批】超期待人资处理", overdue)
|
||||
_push_group(f"【{subject}审批】审批异常", abnormal)
|
||||
_push_group(f"【{subject}审批】处理失败", failed)
|
||||
|
||||
return messages
|
||||
|
||||
|
||||
def save_report(text, save_dir):
|
||||
"""把报告落盘为 <save_dir>/加班审批报告_YYYYMMDD_HHMMSS.txt,返回路径。"""
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
filename = f"加班审批报告_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
|
||||
path = os.path.join(save_dir, filename)
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write(text)
|
||||
logger.info("审批报告已保存: %s", path)
|
||||
return path
|
||||
@@ -1,3 +0,0 @@
|
||||
requests
|
||||
DrissionPage
|
||||
chinese_calendar
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,13 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>EHR系统加班流程审核</title>
|
||||
<script type="module" crossorigin src="/pui/xq0004/assets/index-Br4JMqLc.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0004/assets/index-DYuos9Vi.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,184 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0008 重庆社保增减员办理 插件入口。
|
||||
|
||||
需求 XQ0008(重庆社保增减员导入名单制作)为主体,合并 XQ0014(重庆社保系统增减员办理)
|
||||
+ XQ0015/XQ0016(参保成功/异常/社保转移告知书制作与下发),八个可选阶段按业务顺序
|
||||
串行(可自由勾选):
|
||||
|
||||
0) 目录预检:校验统一资料根目录(base_dir)是否满足各阶段需求(源名单/台账/模板/花名册/告知书模板)
|
||||
1) 增员名单制作:源表《参保名单》筛重庆+参保类型+办理状态空,按参保单位分组复制
|
||||
《增员模版.xls》生成《XX增员导入名单.xls》(转移参保-增员 / 新参保-增员 分目录)
|
||||
2) 减员名单制作:源表《停保名单》筛重庆+停保/转移停保+办理停保空,生成《XX减员导入名单.xls》
|
||||
3) 增员系统办理:逐参保单位读取台账账号,登录重庆人社政务平台(法人用户+图形验证码),
|
||||
「城保参保单位人员增加」上传导入 → 预申报提交 → 审核结论回写「办理状态」
|
||||
4) 减员系统办理:同上「城保参保单位人员减少」,回写「办理停保」
|
||||
5) 增员核查回盘:对「办理状态=待审核」单位核查(参保成功/参保失败/400回待办),
|
||||
下载回盘表核对五项参保状态追加个人编号
|
||||
6) 减员核查回盘:对「办理停保=待审核」单位核查(停保成功/停保失败),下载回盘表留档
|
||||
7) 告知书制作:生成 员工参与社会保险/参保异常/社保转移 三类告知书(Word+PDF),
|
||||
构造 OA 工作沟通推送数据落盘;可开关自动推 OA(需先在工作台登录 OA)
|
||||
|
||||
运行上下文:平台 = ""(社保系统办理按参保单位逐账号浏览器自动化登录;OA 推送仅在
|
||||
告知书阶段启用时懒取底座 oa 会话)。字段由 plugin.json 权威定义:base_dir / ledger_dir /
|
||||
phases / run_limit / debug_mode / notice_branch / notice_push_oa / notice_test_mode。
|
||||
"""
|
||||
from webhost.backend.plugins.base import ScenePlugin, PLUGINS
|
||||
|
||||
from . import config
|
||||
from .logic import dir_check, notice_gen, oa_push, roster_gen
|
||||
from .logic.web_import import ImportEngine
|
||||
from .logic.web_review import ReviewEngine
|
||||
|
||||
# 阶段定义(key, 名称);多选按序串行,留空=全部
|
||||
_PHASES = [
|
||||
("dir_check", "目录预检"),
|
||||
("add_list", "增员名单制作"),
|
||||
("stop_list", "减员名单制作"),
|
||||
("add_import", "增员系统办理"),
|
||||
("stop_import", "减员系统办理"),
|
||||
("add_review", "增员核查回盘"),
|
||||
("stop_review", "减员核查回盘"),
|
||||
("notice", "告知书制作"),
|
||||
]
|
||||
_PHASE_LABELS = {k: n for k, n in _PHASES}
|
||||
|
||||
|
||||
class ChongqingSocialChangePlugin(ScenePlugin):
|
||||
"""重庆社保增减员办理(需求 XQ0008 + XQ0014 + XQ0015/XQ0016)。"""
|
||||
|
||||
id = "xq0008"
|
||||
name = "重庆社保增减员办理"
|
||||
version = "1.0.5"
|
||||
description = ("重庆社保增减员全流程(XQ0008 名单制作 + XQ0014 系统办理/核查回盘 + "
|
||||
"XQ0015/XQ0016 告知书制作下发):目录预检、增/减员名单制作、增/减员系统办理、"
|
||||
"增/减员核查回盘、告知书制作与 OA 推送八阶段可选串行。逐参保单位读取台账账号"
|
||||
"登录重庆人社政务平台完成导入申报与审核核查,生成三类告知书并构造 OA 工作沟通推送")
|
||||
platform = ""
|
||||
uses_month = False
|
||||
capabilities = ["xq0008"]
|
||||
permissions = {"platforms": []}
|
||||
|
||||
def run(self, fields: dict, ctx):
|
||||
# ---- 注入运行上下文:日志 / 进度 / 目录 / 运行参数 ----
|
||||
config.set_log(ctx.log)
|
||||
config.set_progress(ctx.progress)
|
||||
base_dir = (fields.get("base_dir") or "").strip() or config.DEFAULT_BASE_DIR
|
||||
config.set_base_dir(base_dir)
|
||||
config.set_ledger_dir(fields.get("ledger_dir") or "")
|
||||
config.set_debug(bool(fields.get("debug_mode", False)))
|
||||
config.set_run_limit(fields.get("run_limit") or 0)
|
||||
config.set_notice_branch(fields.get("notice_branch") or "all")
|
||||
config.set_notice_test_mode(bool(fields.get("notice_test_mode", False)))
|
||||
config.set_notice_push_oa(bool(fields.get("notice_push_oa", False)))
|
||||
|
||||
# ---- 解析阶段选择 ----
|
||||
sel = [str(p).strip() for p in (fields.get("phases") or []) if str(p).strip()]
|
||||
keys = [k for k, _ in _PHASES if k in sel] or [k for k, _ in _PHASES]
|
||||
labels = [_PHASE_LABELS[k] for k in keys]
|
||||
ctx.log(f"===== 重庆社保增减员办理启动:资料根目录 {config.get_base_dir()} =====", "INFO")
|
||||
ctx.log(f"执行阶段:{' → '.join(labels)}", "INFO")
|
||||
if not keys:
|
||||
return {"summary": "未选择任何执行阶段", "detail": {}, "notes": [], "path": base_dir}
|
||||
|
||||
# ---- 各阶段进度区间(平均切分) ----
|
||||
n = len(keys)
|
||||
notes: list = []
|
||||
detail: dict = {}
|
||||
for i, key in enumerate(keys):
|
||||
span = (int(100 * i / n), int(100 * (i + 1) / n))
|
||||
label = _PHASE_LABELS[key]
|
||||
ctx.progress(span[0])
|
||||
try:
|
||||
result = self._run_phase(key, span, ctx)
|
||||
detail[key] = {"label": label, "result": result}
|
||||
ctx.log(f"【{label}】完成:{_safe_message(result)}", "INFO")
|
||||
except Exception as e:
|
||||
notes.append(f"【{label}】执行失败:{e}")
|
||||
detail[key] = {"label": label, "result": {"success": False, "message": str(e)}}
|
||||
ctx.log(f"【{label}】执行失败:{e}", "ERROR")
|
||||
finally:
|
||||
ctx.progress(span[1])
|
||||
ctx.progress(100)
|
||||
|
||||
# ---- 汇总 ----
|
||||
fail_phases = [k for k, v in detail.items()
|
||||
if not (v.get("result") or {}).get("success", True)]
|
||||
tail = ""
|
||||
if notes:
|
||||
tail = "\n注意事项:\n- " + "\n- ".join(notes)
|
||||
summary = ("重庆社保增减员办理完成:{done}。{fail}").format(
|
||||
done="、".join(labels),
|
||||
fail=f"失败阶段:{'、'.join(fail_phases)}" if fail_phases else "全部成功")
|
||||
summary += tail
|
||||
return {"summary": summary, "detail": detail, "notes": notes,
|
||||
"path": base_dir, "phases": labels}
|
||||
|
||||
def _run_phase(self, key, span, ctx):
|
||||
"""按阶段执行,返回 JSON 安全 dict。"""
|
||||
if key == "dir_check":
|
||||
report = dir_check.check_directory()
|
||||
for c in report["checks"]:
|
||||
ctx.log(f" [{'✓' if c['ok'] else '✗'}] {c['name']}:{c['detail']}")
|
||||
return {"success": report["ok"], "message": "目录预检完成", "checks": report["checks"]}
|
||||
if key == "add_list":
|
||||
total, detail_map = roster_gen.make_add_lists()
|
||||
return {"success": True, "message": f"增员名单制作完成,共 {total} 份",
|
||||
"detail": detail_map}
|
||||
if key == "stop_list":
|
||||
total, detail_map = roster_gen.make_stop_lists()
|
||||
return {"success": True, "message": f"减员名单制作完成,共 {total} 份",
|
||||
"detail": detail_map}
|
||||
if key == "add_import":
|
||||
return ImportEngine("add").run(progress_span=span)
|
||||
if key == "stop_import":
|
||||
return ImportEngine("stop").run(progress_span=span)
|
||||
if key == "add_review":
|
||||
return ReviewEngine("add").run(progress_span=span)
|
||||
if key == "stop_review":
|
||||
return ReviewEngine("stop").run(progress_span=span)
|
||||
if key == "notice":
|
||||
return self._run_notice(ctx)
|
||||
raise ValueError(f"未知阶段:{key}")
|
||||
|
||||
def _run_notice(self, ctx):
|
||||
"""告知书制作:生成三类告知书 + 构造 OA 推送数据;按开关自动推送。"""
|
||||
# 花名册优先走 HR 接口取数(需已登录 HR);未登录/失效时回退源表「附-在职花名册」/本地文件
|
||||
try:
|
||||
config.set_hr_session(ctx.get_session("hr"))
|
||||
except Exception as e:
|
||||
config.set_hr_session(None)
|
||||
ctx.log(f"HR 登录态不可用,花名册将回退源表/本地文件:{e}", "WARN")
|
||||
result = notice_gen.make_notices()
|
||||
summary_parts = [f"生成 {result['total']} 份告知书(docx+pdf)",
|
||||
f"构造 {result['messages_count']} 条 OA 推送数据"]
|
||||
# 自动推送(需先在工作台登录 OA)
|
||||
if config.get_notice_push_oa():
|
||||
if not result["messages"]:
|
||||
summary_parts.append("OA 推送跳过(无可推送数据)")
|
||||
else:
|
||||
try:
|
||||
config.set_oa_session(ctx.get_session("oa"))
|
||||
push = oa_push.push_messages(result["messages"])
|
||||
result["push"] = push
|
||||
summary_parts.append(f"OA 推送:{push['message']}")
|
||||
if not push["success"]:
|
||||
result["success"] = False
|
||||
except Exception as e:
|
||||
result["push"] = {"success": False, "message": str(e), "results": []}
|
||||
summary_parts.append(f"OA 推送未执行:{e}")
|
||||
ctx.log(f"OA 推送未执行(请先在工作台登录 OA):{e}", "WARN")
|
||||
else:
|
||||
summary_parts.append("未开启自动 OA 推送(推送数据已落盘 oa_messages.json)")
|
||||
result.setdefault("success", True)
|
||||
result["message"] = ";".join(summary_parts)
|
||||
return result
|
||||
|
||||
|
||||
def _safe_message(result):
|
||||
"""取结果 dict 的 message 字段做日志(结果可能为 None)。"""
|
||||
if isinstance(result, dict):
|
||||
return result.get("message", "")
|
||||
return str(result or "")
|
||||
|
||||
|
||||
PLUGINS.append(ChongqingSocialChangePlugin())
|
||||
@@ -1,581 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0008 重庆社保增减员办理 插件 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:本包只依赖 Python 标准库 / 第三方库 / 底座注入的 RunContext。
|
||||
业务模块统一经 config.log()/logger 输出日志、config.progress() 上报进度;
|
||||
运行参数(根目录 / 台账目录 / 调试开关 / 每次限制数)由 __init__.py 的 run()
|
||||
解析 fields 后注入(set_base_dir / set_ledger_dir / set_debug / set_run_limit)。
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
|
||||
# ==================== 共享目录(缓存/调试,与其它插件同路径约定) ====================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
CACHE_DIR = os.path.join(_APP_DATA_DIR, 'cache')
|
||||
# 本插件的崩溃恢复缓存 / 调试截图 / 验证码调试图目录
|
||||
CKPT_DIR = os.path.join(CACHE_DIR, 'xq0008')
|
||||
|
||||
# ==================== 默认根目录(run() 注入覆盖) ====================
|
||||
DEFAULT_BASE_DIR = r"D:\资料\人资\重庆社保增减员办理"
|
||||
|
||||
# ==================== 文件模式 ====================
|
||||
SOURCE_KEYWORD = "社保变更及增减名单" # 源名单文件名关键字(对齐原版精确匹配,防同名老文件误选)
|
||||
SOURCE_GLOB = f"*{SOURCE_KEYWORD}*.xlsx" # 源名单(年月动态,取最新)
|
||||
LEDGER_GLOB = "*社保户头管理台账*.xlsx" # 台账(可能加前后缀,取最新)
|
||||
TEMPLATE_ADD = "增员模版.xls"
|
||||
TEMPLATE_STOP = "减员模版.xls"
|
||||
OUTPUT_DIR_ADD_NEW = "新参保-增员" # 增员产出子目录(按参保类型分文件夹)
|
||||
OUTPUT_DIR_ADD_TRANS = "转移参保-增员"
|
||||
OUTPUT_DIR_STOP = "停保-减员" # 减员产出子目录
|
||||
|
||||
# ==================== 统一目录子结构(真实布局) ====================
|
||||
ROSTER_WORK_DIR = "社保增减名单制作" # 名单制作输出与模板目录(base_dir 下)
|
||||
ROSTER_TPL_DIR = "模板" # 增员/减员模版所在子目录
|
||||
REPLAY_ROOT = "回盘打印" # 回盘表目录(base_dir 下)
|
||||
NOTICE_DIR = "告知书下发" # 告知书根目录(base_dir 下)
|
||||
NOTICE_TPL_DIR = "模板" # 告知书模板子目录
|
||||
NOTICE_OUTPUT_NAME = "输出" # 告知书输出子目录
|
||||
|
||||
|
||||
def roster_output_dir(sub):
|
||||
"""名单制作输出目录:{base_dir}/社保增减名单制作/<sub>。"""
|
||||
return os.path.join(get_base_dir(), ROSTER_WORK_DIR, sub)
|
||||
|
||||
|
||||
def roster_template_dir():
|
||||
"""增员/减员模版目录:{base_dir}/社保增减名单制作/模板。"""
|
||||
return os.path.join(get_base_dir(), ROSTER_WORK_DIR, ROSTER_TPL_DIR)
|
||||
|
||||
|
||||
def notice_output_root():
|
||||
"""告知书输出根:{base_dir}/告知书下发/输出。"""
|
||||
return os.path.join(get_base_dir(), NOTICE_DIR, NOTICE_OUTPUT_NAME)
|
||||
|
||||
|
||||
def notice_template_dir():
|
||||
"""告知书模板目录:{base_dir}/告知书下发/模板。"""
|
||||
return os.path.join(get_base_dir(), NOTICE_DIR, NOTICE_TPL_DIR)
|
||||
|
||||
|
||||
def replay_dir(sub):
|
||||
"""回盘表目录:{base_dir}/回盘打印/<sub>。"""
|
||||
return os.path.join(get_base_dir(), REPLAY_ROOT, sub)
|
||||
|
||||
|
||||
REPLAY_PREFIX = "人员增减申请回盘表" # 回盘表文件名前缀
|
||||
|
||||
# ==================== 目标区域 / 参保类型 ====================
|
||||
TARGET_REGION = "重庆"
|
||||
ADD_TYPES = ("新参保", "转移参保") # 名单制作覆盖两种参保类型
|
||||
WEB_ADD_TYPES = ("新参保", "转移参保") # 增员系统办理/核查覆盖两种参保类型(与 import_add.py 一致)
|
||||
STOP_TYPES = ("停保", "转移停保") # 减员两类都办
|
||||
|
||||
# ==================== 台账「缴费比例」sheet 数据列(0-based,表头占 1-2 行已跳过) ====================
|
||||
LEDGER_COL = {"户头": 1, "城市": 3, "在用": 4, "信用代码": 8, "平台用户名": 10, "平台密码": 11}
|
||||
|
||||
# ==================== 源名单结构 ====================
|
||||
SOURCE_HEADER_ROW = 3 # 表头在第3行
|
||||
SHEET_KEY_ADD = "参保名单" # 增员 sheet 关键字(如 202609参保名单)
|
||||
SHEET_KEY_STOP = "停保名单" # 减员 sheet 关键字(如 202609停保名单)
|
||||
SHEET_KEY_LEDGER = "缴费比例" # 台账 sheet 关键字(如 2026年9月缴费比例)
|
||||
|
||||
# ==================== 增员名单制作(XQ0008 generate_add.py 移植) ====================
|
||||
# 源表列名 ↔ 模板列名映射(键为模板列含义,值为源表列名)
|
||||
COLUMN_MAP_ADD = {
|
||||
'姓名': '姓名',
|
||||
'证件号码': '身份证号码',
|
||||
'民族': '民族',
|
||||
'月基本工资额': '工资', # 月基本工资额取「工资申报」列
|
||||
'户口性质': '户口性质',
|
||||
'文化程度': '文化程度',
|
||||
'联系电话': '电话号码',
|
||||
'单位名称': '参保单位',
|
||||
'社保号': '社保号',
|
||||
'参保单位全称': '参保单位全称',
|
||||
'备注': '备注',
|
||||
}
|
||||
# 学历映射
|
||||
EDU_MAP = {
|
||||
'硕士研究生': '14.硕士研究生',
|
||||
'本科': '21.大学本科',
|
||||
'大专': '31.大学专科',
|
||||
'高中': '61.普通中学',
|
||||
'职高/中专/中技': '44.职业高中',
|
||||
'初中': '71.初级中学',
|
||||
'小学': '81.小学',
|
||||
}
|
||||
# 民族映射
|
||||
NATION_MAP = {
|
||||
'汉族': '01.汉族', '蒙古族': '02.蒙古族', '回族': '03.回族', '藏族': '04.藏族',
|
||||
'维吾尔族': '05.维吾尔族', '苗族': '06.苗族', '彝族': '07.彝族', '壮族': '08.壮族',
|
||||
'布依族': '09.布依族', '朝鲜族': '10.朝鲜族', '满族': '11.满族', '侗族': '12.侗族',
|
||||
'瑶族': '13.瑶族', '白族': '14.白族', '土家族': '15.土家族', '哈尼族': '16.哈尼族',
|
||||
'哈萨克族': '17.哈萨克族', '傣族': '18.傣族', '黎族': '19.黎族', '傈僳族': '20.傈僳族',
|
||||
'佤族': '21.佤族', '畲族': '22.畲族', '高山族': '23.高山族', '拉祜族': '24.拉祜族',
|
||||
'水族': '25.水族', '东乡族': '26.东乡族', '纳西族': '27.纳西族', '景颇族': '28.景颇族',
|
||||
'柯尔克孜族': '29.柯尔克孜族', '土族': '30.土族', '达斡尔族': '31.达斡尔族',
|
||||
'仫佬族': '32.仫佬族', '羌族': '33.羌族', '布朗族': '34.布朗族', '撒拉族': '35.撒拉族',
|
||||
'毛南族': '36.毛南族', '仡佬族': '37.仡佬族', '锡伯族': '38.锡伯族', '阿昌族': '39.阿昌族',
|
||||
'普米族': '40.普米族', '塔吉克族': '41.塔吉克族', '怒族': '42.怒族',
|
||||
'乌孜别克族': '43.乌孜别克族', '俄罗斯族': '44.俄罗斯族', '鄂温克族': '45.鄂温克族',
|
||||
'德昂族': '46.德昂族', '保安族': '47.保安族', '裕固族': '48.裕固族', '京族': '49.京族',
|
||||
'塔塔尔族': '50.塔塔尔族', '独龙族': '51.独龙族', '鄂伦春族': '52.鄂伦春族',
|
||||
'赫哲族': '53.赫哲族', '门巴族': '54.门巴族', '珞巴族': '55.珞巴族', '基诺族': '56.基诺族',
|
||||
'少数民族': '57.少数民族', '其他': '99.其他',
|
||||
}
|
||||
# 户籍类型映射
|
||||
RESIDENCE_MAP = {
|
||||
'本地城镇': '11.本市城镇',
|
||||
'本地农村': '21.本市农村',
|
||||
'外地城镇': '12.外市城镇',
|
||||
'外地农村': '22.外市农村',
|
||||
}
|
||||
# 增员固定默认值
|
||||
DEFAULT_VALUES_ADD = {
|
||||
'个人身份': '24.工人',
|
||||
'证件类型': '01.居民身份证(户口簿)',
|
||||
'国籍': 'CHN.中国',
|
||||
'专职技能': '499.未定职级',
|
||||
'技能等级': '无',
|
||||
'工种': '',
|
||||
'备注': '',
|
||||
}
|
||||
# 增员模板(表头 B2:U2,数据从第4行起)
|
||||
TPL_DATA_START_ROW = 4
|
||||
TPL_COLS_ADD = [
|
||||
'证件号码', '姓名', '民族', '首次参加工作日期', '月基本工资额', '工种', '个人身份',
|
||||
'户口性质', '联系电话', '文化程度', '养老保险参保时间', '失业保险参保时间',
|
||||
'医疗保险参保时间', '工伤保险参保时间', '生育保险参保时间', '证件类型', '国籍',
|
||||
'备注', '专职技能', '技能等级',
|
||||
]
|
||||
# 需按日期写入的模板列(工伤=当日,其余=本月1日)
|
||||
DATE_COLS_ADD = {
|
||||
'首次参加工作日期', '养老保险参保时间', '失业保险参保时间',
|
||||
'医疗保险参保时间', '工伤保险参保时间', '生育保险参保时间',
|
||||
}
|
||||
|
||||
# ==================== 减员名单制作(XQ0008 generate_stop.py 移植) ====================
|
||||
COLUMN_MAP_STOP = {
|
||||
'个人编号': '社保编号',
|
||||
'证件号码': '身份证号码',
|
||||
'姓名': '停保人姓名',
|
||||
'单位社保号': '单位社保号',
|
||||
'单位名称': '参保单位',
|
||||
'单位全称': '单位全称',
|
||||
}
|
||||
DEFAULT_VALUES_STOP = {
|
||||
'减少原因': '在职人员主动解除劳动合同',
|
||||
'养老保险减少标志': '1 减少',
|
||||
'失业保险减少标志': '1 减少',
|
||||
'医疗保险减少标志': '1 减少',
|
||||
'工伤保险减少标志': '1 减少',
|
||||
'生育保险减少标志': '1 减少',
|
||||
'失业原因': '3 劳动者自愿辞职',
|
||||
}
|
||||
# 减员模板(表头 B2:L2,数据从第4行起)
|
||||
TPL_COLS_STOP = [
|
||||
'个人编号', '证件号码', '姓名', '减少时间', '减少原因',
|
||||
'养老保险减少标志', '失业保险减少标志', '医疗保险减少标志',
|
||||
'工伤保险减少标志', '生育保险减少标志', '失业原因',
|
||||
]
|
||||
DATE_COLS_STOP = {'减少时间'}
|
||||
STOP_LEAVE_DATE_COL = "离职日期"
|
||||
STOP_PROCESSED_COL = "办理停保"
|
||||
|
||||
|
||||
# ==================== 核查回盘常量(check_review / check_review_stop) ====================
|
||||
CHECK_STATUS = "待审核"
|
||||
DONE_STATUS = "已办结"
|
||||
ERR_400_KEYWORD = "status 400"
|
||||
RUN_400_CLEAR = True # 400系统错误:True=运行结束后统一清空状态回待办(重新走名单制作+办理)
|
||||
MENU_QUERY = "已申报查询"
|
||||
API_KEYWORD = "queryYsbWs04orWs01"
|
||||
API_UNIT_INFO = ("https://ggfw.rlsbj.cq.gov.cn/onlinehall/declare/server/gourd/"
|
||||
"cloud/ggfw/declare/query/DwCx/dwyl/getAab001")
|
||||
MENU_PAGE_URL = ("https://ggfw.rlsbj.cq.gov.cn/onlinehall/nethall/pc/cqzhrs/"
|
||||
"onlineoffice/OdCommon")
|
||||
PAGE_SIZE = 10
|
||||
MAX_PAGES = 50
|
||||
INS_STATUSES = ["养老参保状态", "失业参保状态", "医疗参保状态",
|
||||
"工伤参保状态", "生育参保状态"]
|
||||
INS_OK = "参保缴费"
|
||||
|
||||
# ==================== 告知书制作(XQ0015/XQ0016 notice_mail_merge.py 移植) ====================
|
||||
# 统一目录:模板在 {base_dir}/告知书下发/模板,输出在 {base_dir}/告知书下发/输出/YYYYMM
|
||||
NOTICE_HEADER_ROW = 3 # 参保名单 sheet 表头行
|
||||
NOTICE_MAIN_COLS = 51 # 主表字段到「费用」列(AY)为止
|
||||
# 三类告知书模板(file=告知书下发/模板 下的文件名;folder=输出子目录;status/type=过滤条件)
|
||||
NOTICE_TEMPLATES = {
|
||||
"新参保": {
|
||||
"file": "员工参与社会保险告知书模板.docx",
|
||||
"folder": "员工参与社会保险告知书",
|
||||
"status": "已参",
|
||||
"type": "新参保",
|
||||
},
|
||||
"参保异常": {
|
||||
"file": "参保异常告知模板.docx",
|
||||
"folder": "参保异常告知书",
|
||||
"status": "参保失败",
|
||||
"type": "新参保",
|
||||
},
|
||||
"社保转移": {
|
||||
"file": "社保转移告知模板.docx",
|
||||
"folder": "社保转移告知书",
|
||||
"status": "已参",
|
||||
"type": "转移参保",
|
||||
},
|
||||
}
|
||||
NOTICE_BRANCHES = ("新参保", "转移参保") # 告知书执行分支(可分别/全部)
|
||||
# 社保转移数据源 sheet(转移参保数据已并入同文件「变更-职能及干部/变更-门店」sheet)
|
||||
TRANSFER_SHEET_GENERATE = ("变更-职能及干部", "变更-门店")
|
||||
TRANSFER_SHEET_PUSH = "变更-门店"
|
||||
TRANSFER_CHANGE_COL = "是否变更"
|
||||
TRANSFER_CHANGE_VALUE = "是"
|
||||
TRANSFER_COL_MAP = {"新区域": "区域", "个人费用": "费用"}
|
||||
# 旧占位符 → 新占位符(模板兼容旧写法)
|
||||
LEGACY_PLACEHOLDERS = {
|
||||
"{{当前月15日}}": "{{当月15日}}",
|
||||
"{{重庆}}": "{{区域}}",
|
||||
"{{当前月+1}}": "{{下月}}",
|
||||
"{{费用*2}}": "{{一次性扣款}}",
|
||||
}
|
||||
# 推送人映射:键可为「二级部门(经营中心)」或「二级部门为空时的所属单位回退值」(如 水庄大鹅事业部)。
|
||||
# 优先于花名册人事查找(覆盖映射不依赖员工是否在花名册)。
|
||||
DEPT2_PUSH_OVERRIDE = {
|
||||
"金色印象海口经营中心": ["37000700"],
|
||||
"金色印象昆明经营中心": ["37002511"],
|
||||
"金色印象南宁经营中心": ["37009626"],
|
||||
"金色印象深圳经营中心": ["37018211"],
|
||||
"金色印象郑州经营中心": ["37006992"],
|
||||
"水庄大鹅事业部": ["37036104"], # 所属单位回退值(非二级部门),直接推送 37036104 唐佳膑
|
||||
}
|
||||
DEPT2_HR_OVERRIDE = {"石桥铺会馆": ["37001302"]}
|
||||
CC_RECEIVER_NAME = "周卫"
|
||||
CC_RECEIVER_ID = "37001166"
|
||||
NOTICE_OA_TEST_RECEIVERS = ["37036361", "37001166"] # 测试模式接收人(夏一平 + 周卫)
|
||||
# OA 推送文案(subject/content 支持 {y}/{m}/{push_date} 动态替换)
|
||||
NOTICE_OA_MESSAGE_TEMPLATES = (
|
||||
{
|
||||
"key": "参保类",
|
||||
"rule_keys": ("新参保", "参保异常"),
|
||||
"subject": "{y}年{m}月员工参保结果告知书",
|
||||
"content": (
|
||||
"各位店长、人行伙伴:\n"
|
||||
"各区域门店{m}月新参保已完成,以下是各门店《参保成功告知书》/《参保异常告知书》,现需涉及的门店对员工本人进行传达告知(下载并签收);\n"
|
||||
"其中参保异常人员,重庆户籍的可以在渝快办APP上查询办理停保,"
|
||||
"如办理不成功,也可打12333咨询社保机构,异地区域拨打区号+12333;若员工处理完毕,请店长报备至人资周卫,以便下月再参;\n"
|
||||
"请门店在{m}月26日前完成签署并将《签收回执》传递人行,"
|
||||
"人行跟进本经营中心所有人员的告知书回收,{m}月28日前传递人资周卫。\n"
|
||||
"@@R人力资源部\n"
|
||||
"@@R{push_date}"
|
||||
),
|
||||
"category": "工作安排",
|
||||
},
|
||||
{
|
||||
"key": "社保转移",
|
||||
"rule_keys": ("社保转移",),
|
||||
"subject": "{y}年{m}月员工参保单位变更确认",
|
||||
"content": (
|
||||
"各位领导/同事:\n"
|
||||
"根据《社保执行细则》,本月人力资源部已输出“工作与参保单位不一致”的人员,"
|
||||
"现需要涉及门店/经营中心与员工本人进行转移确认(下载变更告知书、打印并与员工清晰讲解),"
|
||||
"在{m}月27日下班前完成签署并将《社保缴纳确认单》传递分部人行,"
|
||||
"在{m}月29日内传递人资周卫处。\n"
|
||||
"特别注意:员工若有住院就医计划,须及时反馈可暂不转移,待处理完毕后办理。"
|
||||
"员工若属于暂调(后续会回到原门店),也须及时反馈可暂不转移。\n"
|
||||
"@@R人力资源部\n"
|
||||
"@@R{push_date}"
|
||||
),
|
||||
"category": "工作安排",
|
||||
},
|
||||
)
|
||||
NOTICE_OA_HIGHLIGHTS = {
|
||||
"参保类": [
|
||||
("《参保成功告知书》", "#c0392b"),
|
||||
("《参保异常告知书》", "#c0392b"),
|
||||
("《签收回执》", "#c0392b"),
|
||||
("{m}月26日前", "#c0392b"),
|
||||
("{m}月28日前", "#c0392b"),
|
||||
],
|
||||
"社保转移": [
|
||||
("《社保缴纳确认单》", "#c0392b"),
|
||||
("{m}月25日下班前", "#c0392b"),
|
||||
("27日内", "#c0392b"),
|
||||
("特别注意:员工若有住院就医计划,须及时反馈可暂不转移,待处理完毕后办理。员工若属于暂调(后续会回到原门店),也须及时反馈可暂不转移。", "#c0392b"),
|
||||
],
|
||||
}
|
||||
|
||||
# ==================== OA 工作沟通推送(work_communication.py 移植) ====================
|
||||
OA_BASE_URL = "https://oa.37du.co"
|
||||
PERSON_SEARCH_URL = f"{OA_BASE_URL}/sys/common/dataxml.jsp"
|
||||
ATT_UPLOAD_URL = f"{OA_BASE_URL}/sys/attachment/sys_att_main/sysAttMain.do"
|
||||
ATT_UPLOADER_URL = f"{OA_BASE_URL}/sys/attachment/uploaderServlet"
|
||||
WORK_COMMUNICATION_ADD_URL = (f"{OA_BASE_URL}/km/collaborate/km_collaborate_main/"
|
||||
"kmCollaborateMain.do?method=add")
|
||||
KM_COLLABORATE_SAVE_URL = (f"{OA_BASE_URL}/km/collaborate/km_collaborate_main/"
|
||||
"kmCollaborateMain.do")
|
||||
TODO_COUNT_URL = f"{OA_BASE_URL}/sys/notify/sys_notify_todo/sysNotifyTodo.do"
|
||||
FD_CONTENT_PREFIX = b"\xe4\x99\x89\xe5\xa0\xa0\xe4\xb5\x85\xe4\x89\x81\xe5\x8d\x85\xe3\x98\xb4".decode("utf-8")
|
||||
FD_CATEGORY_MAP = {
|
||||
"工作交流": "15e4c970dd59cd559f096644cecadbc7",
|
||||
"信息传递": "15e4c980ff72365007fc1a741ceb0c7d",
|
||||
"工作安排": "17646e8283a07a43be3003d485492a4f",
|
||||
"项目沟通": "1767a1195ec34b0de7d53764c84812f1",
|
||||
"温馨提示": "17efb81557d1e74c532aa78407a95189",
|
||||
"其他": "15e4c985cd9a92cc54cb20c413d9b29e",
|
||||
}
|
||||
FD_CATEGORY_DEFAULT = FD_CATEGORY_MAP["工作安排"]
|
||||
KM_COLLABORATE_MODEL = "com.landray.kmss.km.collaborate.model.KmCollaborateMain"
|
||||
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
_progress = None
|
||||
_base_dir = DEFAULT_BASE_DIR
|
||||
_ledger_dir = ""
|
||||
_debug = False
|
||||
_run_limit = None
|
||||
|
||||
|
||||
def set_log(fn):
|
||||
"""注入 ctx.log(RunContext.log),各模块经 log()/logger 输出。"""
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def log(msg, level="INFO"):
|
||||
if _log:
|
||||
_log(str(msg), level)
|
||||
else:
|
||||
print(f"[{level}] {msg}")
|
||||
|
||||
|
||||
class _ModuleLogger:
|
||||
"""模块级 logger 适配:保留影刀版 logger.info(...) 调用点,统一转发到 ctx.log。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "DEBUG")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "INFO")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "WARN")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "ERROR")
|
||||
|
||||
|
||||
logger = _ModuleLogger()
|
||||
|
||||
|
||||
def set_progress(fn):
|
||||
"""注入 ctx.progress(RunContext.progress),各模块可上报细粒度进度。"""
|
||||
global _progress
|
||||
_progress = fn
|
||||
|
||||
|
||||
def progress(pct):
|
||||
if _progress:
|
||||
try:
|
||||
_progress(int(pct))
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
log(f"进度 {pct}%", "DEBUG")
|
||||
|
||||
|
||||
def set_base_dir(path):
|
||||
global _base_dir
|
||||
_base_dir = (path or "").strip().strip('"') or DEFAULT_BASE_DIR
|
||||
|
||||
|
||||
def get_base_dir():
|
||||
return _base_dir
|
||||
|
||||
|
||||
def set_ledger_dir(path):
|
||||
global _ledger_dir
|
||||
_ledger_dir = (path or "").strip().strip('"') or ""
|
||||
|
||||
|
||||
def get_ledger_dir():
|
||||
return _ledger_dir or _base_dir
|
||||
|
||||
|
||||
def set_debug(flag):
|
||||
global _debug
|
||||
_debug = bool(flag)
|
||||
|
||||
|
||||
def is_debug():
|
||||
return _debug
|
||||
|
||||
|
||||
def set_run_limit(value):
|
||||
global _run_limit
|
||||
v = value
|
||||
try:
|
||||
v = int(v)
|
||||
except (TypeError, ValueError):
|
||||
v = None
|
||||
_run_limit = v if v and v > 0 else None
|
||||
|
||||
|
||||
def get_run_limit():
|
||||
return _run_limit
|
||||
|
||||
|
||||
# ==================== 告知书 / OA 推送运行参数钩子(run() 注入) ====================
|
||||
_notice_branch = "all" # '新参保' | '转移参保' | 'all'
|
||||
_notice_test_mode = False # True=OA 推送接收人覆盖为测试接收人
|
||||
_notice_push_oa = False # True=生成告知书后自动推 OA 工作沟通
|
||||
_oa_session = None # 底座注入的 OA requests.Session(未登录时为 None)
|
||||
|
||||
|
||||
def set_notice_branch(value):
|
||||
global _notice_branch
|
||||
v = str(value or "all").strip()
|
||||
_notice_branch = v if v in ("新参保", "转移参保", "all") else "all"
|
||||
|
||||
|
||||
def get_notice_branch():
|
||||
return _notice_branch
|
||||
|
||||
|
||||
def set_notice_test_mode(flag):
|
||||
global _notice_test_mode
|
||||
_notice_test_mode = bool(flag)
|
||||
|
||||
|
||||
def get_notice_test_mode():
|
||||
return _notice_test_mode
|
||||
|
||||
|
||||
def set_notice_push_oa(flag):
|
||||
global _notice_push_oa
|
||||
_notice_push_oa = bool(flag)
|
||||
|
||||
|
||||
def get_notice_push_oa():
|
||||
return _notice_push_oa
|
||||
|
||||
|
||||
def set_oa_session(session):
|
||||
global _oa_session
|
||||
_oa_session = session
|
||||
|
||||
|
||||
def get_oa_session():
|
||||
return _oa_session
|
||||
|
||||
|
||||
# ==================== 花名册数据源钩子(run() 注入) ====================
|
||||
_hr_session = None # 底座注入的 HR requests.Session(花名册接口取数用,未登录为 None)
|
||||
|
||||
|
||||
def set_hr_session(session):
|
||||
global _hr_session
|
||||
_hr_session = session
|
||||
|
||||
|
||||
def get_hr_session():
|
||||
return _hr_session
|
||||
|
||||
|
||||
# ==================== 通用辅助 ====================
|
||||
def _to_text(value):
|
||||
"""转可写文本:证件号/电话等长数字统一为字符串,避免丢精度/科学计数。"""
|
||||
if value is None:
|
||||
return ''
|
||||
try:
|
||||
import math
|
||||
if isinstance(value, float) and math.isnan(value):
|
||||
return ''
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if isinstance(value, float) and value.is_integer():
|
||||
return str(int(value))
|
||||
return str(value).strip()
|
||||
|
||||
|
||||
def _clean_value(value):
|
||||
"""None/NaN 归一为 '',其余原样(用于写入单元格)。"""
|
||||
if value is None:
|
||||
return ''
|
||||
import math
|
||||
if isinstance(value, float) and math.isnan(value):
|
||||
return ''
|
||||
return value
|
||||
|
||||
|
||||
def _safe_name(value):
|
||||
"""单位名转安全文件名:None/NaN/空白 → '未知单位';只剥掉尾部一个「店」。"""
|
||||
if value is None:
|
||||
return '未知单位'
|
||||
try:
|
||||
import pandas as pd
|
||||
if pd.isna(value) or not str(value).strip():
|
||||
return '未知单位'
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
name = str(value).replace("/", "_").replace("\\", "_").replace(":", "_").strip()
|
||||
if name.endswith("店"):
|
||||
name = name[:-1]
|
||||
return name
|
||||
|
||||
|
||||
def _norm_id(v):
|
||||
"""身份证号规范化:去空格、转大写;数值型转整数字符串。"""
|
||||
if v is None:
|
||||
return ''
|
||||
if isinstance(v, float) and v.is_integer():
|
||||
v = int(v)
|
||||
return str(v).strip().upper()
|
||||
|
||||
|
||||
def _id_hit(cid, ref_ids):
|
||||
"""身份证匹配:规范化后精确匹配。"""
|
||||
return bool(cid) and cid in ref_ids
|
||||
|
||||
|
||||
def _latest_file(directory, pattern):
|
||||
"""目录内按模式取最新文件(排除 Excel 临时文件 ~$)。"""
|
||||
from glob import glob
|
||||
candidates = [p for p in glob(os.path.join(directory, pattern))
|
||||
if not os.path.basename(p).startswith("~$")]
|
||||
if not candidates:
|
||||
raise FileNotFoundError(f"在 {directory} 下未找到匹配 {pattern} 的文件")
|
||||
return max(candidates, key=os.path.getmtime)
|
||||
|
||||
|
||||
def _pick_sheet(xl, exact_name, keyword, pattern=None):
|
||||
"""优先精确 sheet 名,其次按关键字/正则匹配;正则匹配时取年月最新。"""
|
||||
names = [n.strip() for n in xl.sheet_names]
|
||||
if exact_name in names:
|
||||
return exact_name
|
||||
if pattern:
|
||||
hits = [(int(m.group(1)), int(m.group(2)), n)
|
||||
for n in names if (m := re.match(pattern, n))]
|
||||
if hits:
|
||||
return max(hits)[2]
|
||||
for n in names:
|
||||
if keyword in n:
|
||||
return n
|
||||
raise ValueError(f"未找到目标 sheet(精确={exact_name},关键字={keyword}),"
|
||||
f"实际 sheets:{xl.sheet_names}")
|
||||
@@ -1,2 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""数据层:源名单 / 台账读取、按业务口径筛选分组。"""
|
||||
@@ -1,183 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""数据层:源名单(参保名单/停保名单)与社保户头管理台账的读取、筛选、取号。
|
||||
|
||||
统一承载 XQ0008(名单制作)与 XQ0014(系统办理/核查)共用的数据读取逻辑:
|
||||
- load_records(kind, operation_type, status_filter):读源名单并按业务口径筛选
|
||||
- load_units / load_check_tasks:按参保单位分组(办理/核查任务)
|
||||
- load_accounts:从台账取各单位政务平台账号
|
||||
"""
|
||||
import os
|
||||
from datetime import datetime
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def read_source(kind):
|
||||
"""定位并解析源名单,返回 (source_file, sheet_name)。
|
||||
|
||||
kind: 'add' 参保名单 sheet / 'stop' 停保名单 sheet(sheet 名年月动态,取最新)。
|
||||
"""
|
||||
source_file = config._latest_file(config.get_base_dir(), config.SOURCE_GLOB)
|
||||
now = datetime.now()
|
||||
xl = __import__('pandas').ExcelFile(source_file)
|
||||
if kind == 'add':
|
||||
sheet_name = config._pick_sheet(xl, f"{now:%Y%m}{config.SHEET_KEY_ADD}",
|
||||
config.SHEET_KEY_ADD)
|
||||
else:
|
||||
sheet_name = config._pick_sheet(xl, f"{now:%Y%m}{config.SHEET_KEY_STOP}",
|
||||
config.SHEET_KEY_STOP,
|
||||
pattern=r"(20\d{2})(1[0-2]|[1-9])停保名单")
|
||||
return source_file, sheet_name
|
||||
|
||||
|
||||
def load_records(kind, operation_type=None, status_filter="empty", exclude_ids=frozenset()):
|
||||
"""读源名单并按业务口径筛选,返回 DataFrame(表头第3行)。
|
||||
|
||||
- kind: 'add'(参保名单)/ 'stop'(停保名单)
|
||||
- operation_type: 增员时的参保类型('新参保'/'转移参保');减员忽略(固定两类都办)
|
||||
- status_filter: 'empty' 办理状态/办理停保为空;'待审核' 等于该值
|
||||
- exclude_ids: 排除的身份证号集合(上次已回写人员,防重复申报/核查)
|
||||
"""
|
||||
import pandas as pd
|
||||
source_file, sheet_name = read_source(kind)
|
||||
print_source = os.path.basename(source_file)
|
||||
# 对齐原版 dtype 保护:add 只指定身份证/电话两列为文本(18 位身份证防 float 丢精度),
|
||||
# stop 全列文本;dtype 字典引用 sheet 不存在的列不会报错
|
||||
dtype = {"身份证号码": str, "电话号码": str} if kind == 'add' else str
|
||||
df = pd.read_excel(source_file, sheet_name=sheet_name,
|
||||
header=config.SOURCE_HEADER_ROW - 1, dtype=dtype)
|
||||
|
||||
if kind == 'add':
|
||||
status_col = "办理状态"
|
||||
# 增员可传单值或元组(如 config.WEB_ADD_TYPES 两类都办)
|
||||
op_types = operation_type if isinstance(operation_type, (tuple, list, set)) \
|
||||
else (operation_type,)
|
||||
mask = (df["区域"].astype(str).str.strip() == config.TARGET_REGION)
|
||||
mask &= (df["参保类型"].astype(str).str.strip().isin(op_types))
|
||||
else:
|
||||
status_col = config.STOP_PROCESSED_COL
|
||||
mask = (df["区域"].astype(str).str.strip() == config.TARGET_REGION)
|
||||
mask &= (df["类型"].astype(str).str.strip().isin(config.STOP_TYPES))
|
||||
|
||||
if status_filter == "empty":
|
||||
st_text = df[status_col].astype(str).str.strip().str.lower()
|
||||
mask &= (df[status_col].isna() | st_text.isin(['', 'nan', 'none', 'nat']))
|
||||
else:
|
||||
mask &= (df[status_col].astype(str).str.strip() == status_filter)
|
||||
|
||||
sub = df[mask].copy()
|
||||
if exclude_ids and '身份证号码' in sub.columns:
|
||||
before = len(sub)
|
||||
ref = [config._norm_id(x) for x in exclude_ids]
|
||||
sub = sub[~sub['身份证号码'].map(lambda v: config._id_hit(config._norm_id(v), ref))]
|
||||
dropped = before - len(sub)
|
||||
if dropped:
|
||||
config.log(f" 已排除 {dropped} 行上次运行已回写的人员(防重复申报/核查)")
|
||||
return sub, source_file, sheet_name, status_col
|
||||
|
||||
|
||||
def load_units(kind, operation_type=None, status_filter="empty", exclude_ids=frozenset()):
|
||||
"""读取名单并筛选,返回 [(参保类型, 参保单位, 人数), ...](按类型+单位分组,名称排序)。
|
||||
|
||||
减员(kind='stop')参保类型恒为 None(停保/转移停保合并按单位分组)。
|
||||
"""
|
||||
sub, source_file, sheet_name, status_col = load_records(
|
||||
kind, operation_type, status_filter, exclude_ids)
|
||||
print_source = os.path.basename(source_file)
|
||||
if kind == 'add':
|
||||
desc = f"{config.TARGET_REGION} ∩ 参保类型∈{'/'.join(config.WEB_ADD_TYPES)}"
|
||||
else:
|
||||
desc = f"{config.TARGET_REGION} ∩ 类型∈{'/'.join(config.STOP_TYPES)}"
|
||||
config.log(f"源名单:{print_source}(sheet: {sheet_name})")
|
||||
if sub.empty:
|
||||
config.log(f"没有筛选到数据({desc} ∩ {status_col}={'空' if status_filter == 'empty' else status_filter})")
|
||||
return [], source_file, sheet_name
|
||||
if kind == 'add':
|
||||
sub["_type"] = sub["参保类型"].astype(str).str.strip()
|
||||
sub["_unit"] = sub["参保单位"].astype(str).str.strip()
|
||||
grouped = sub.groupby(["_type", "_unit"]).size()
|
||||
units = [(t, u, int(n)) for (t, u), n in grouped.items()]
|
||||
units.sort(key=lambda x: (x[0], x[1]))
|
||||
unit_desc = "个(类型+单位)分组"
|
||||
else:
|
||||
grouped = sub.groupby(sub["参保单位"].astype(str).str.strip()).size()
|
||||
units = [(None, u, int(n)) for u, n in grouped.items()]
|
||||
units.sort(key=lambda x: x[1])
|
||||
unit_desc = "个参保单位"
|
||||
config.log(f"筛选结果:共 {sum(n for _, _, n in units)} 人 / {len(units)} {unit_desc}")
|
||||
return units, source_file, sheet_name
|
||||
|
||||
|
||||
def load_check_tasks(kind, status_filter=config.CHECK_STATUS, exclude_ids=frozenset()):
|
||||
"""读取名单筛选 办理状态/办理停保=待审核 的行,分组。
|
||||
|
||||
增员按参保类型+单位分组(回盘文件按类型分目录),减员按单位分组。
|
||||
返回 [{unit, type, count, cids(set)}],供核查流程使用。
|
||||
"""
|
||||
operation_type = config.WEB_ADD_TYPES if kind == 'add' else None
|
||||
sub, source_file, sheet_name, status_col = load_records(
|
||||
kind, operation_type, status_filter, exclude_ids)
|
||||
print_source = os.path.basename(source_file)
|
||||
config.log(f"源名单:{print_source}(sheet: {sheet_name})")
|
||||
if sub.empty:
|
||||
config.log(f"没有筛选到数据({status_col}={status_filter})")
|
||||
return [], source_file, sheet_name
|
||||
sub = sub.copy()
|
||||
sub["_unit"] = sub["参保单位"].astype(str).str.strip()
|
||||
tasks = []
|
||||
if kind == 'add':
|
||||
sub["_type"] = sub["参保类型"].astype(str).str.strip()
|
||||
for (unit, t), g in sub.groupby(["_unit", "_type"]):
|
||||
cids = {config._norm_id(v) for v in g['身份证号码']}
|
||||
cids.discard('')
|
||||
tasks.append({"unit": unit, "type": t, "count": len(cids), "cids": cids})
|
||||
tasks.sort(key=lambda x: (x['unit'], x['type']))
|
||||
unit_desc = "个(类型+单位)分组"
|
||||
else:
|
||||
for unit, g in sub.groupby("_unit"):
|
||||
cids = {config._norm_id(v) for v in g['身份证号码']}
|
||||
cids.discard('')
|
||||
tasks.append({"unit": unit, "type": None, "count": len(cids), "cids": cids})
|
||||
tasks.sort(key=lambda x: x['unit'])
|
||||
unit_desc = "个参保单位"
|
||||
config.log(f"核查范围:共 {sum(t['count'] for t in tasks)} 人 / "
|
||||
f"{len(tasks)} {unit_desc}({status_col}={status_filter})")
|
||||
return tasks, source_file, sheet_name
|
||||
|
||||
|
||||
def load_accounts(unit_names):
|
||||
"""从台账「YYYY年M月缴费比例」sheet 取各单位账号。
|
||||
|
||||
返回 {参保单位: {"username":..., "username_src": "信用代码|平台用户名", "password":...}},
|
||||
取不到的单位不在返回值中(由预检统一报错)。
|
||||
"""
|
||||
import pandas as pd
|
||||
ledger_file = config._latest_file(config.get_ledger_dir(), config.LEDGER_GLOB)
|
||||
now = datetime.now()
|
||||
xl = pd.ExcelFile(ledger_file)
|
||||
sheet_name = config._pick_sheet(xl, f"{now.year}年{now.month}月缴费比例",
|
||||
config.SHEET_KEY_LEDGER,
|
||||
pattern=r"(20\d{2})年(1[0-2]|[1-9])月缴费比例")
|
||||
config.log(f"台账:{os.path.basename(ledger_file)}(sheet: {sheet_name})")
|
||||
|
||||
# 表头为 1-2 行合并结构:跳过前 2 行,B列(户头)非空即数据行
|
||||
df = pd.read_excel(ledger_file, sheet_name=sheet_name, header=None, skiprows=2)
|
||||
df = df[df[config.LEDGER_COL["户头"]].notna()].copy()
|
||||
for c in config.LEDGER_COL.values():
|
||||
df[c] = df[c].map(config._to_text)
|
||||
|
||||
pool = df[(df[config.LEDGER_COL["城市"]] == config.TARGET_REGION)
|
||||
& (df[config.LEDGER_COL["在用"]] == "是")]
|
||||
accounts = {}
|
||||
for name in unit_names:
|
||||
hit = pool[pool[config.LEDGER_COL["户头"]] == name]
|
||||
if hit.empty:
|
||||
continue # 预检阶段统一报「台账未匹配」
|
||||
row = hit.iloc[0]
|
||||
credit, plat_user, plat_pwd = (
|
||||
row[config.LEDGER_COL["信用代码"]], row[config.LEDGER_COL["平台用户名"]],
|
||||
row[config.LEDGER_COL["平台密码"]])
|
||||
# 用户名规则:I列信用代码优先,空则回退 K列平台用户名
|
||||
username, src = (credit, "信用代码") if credit else (plat_user, "平台用户名")
|
||||
accounts[name] = {"username": username, "username_src": src, "password": plat_pwd}
|
||||
return accounts
|
||||
@@ -1,133 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""名单回写(JSON 缓存防崩溃,运行结束统一写 Excel 一次)。
|
||||
|
||||
原影刀版 import_add/import_stop/check_review/check_review_stop 各自维护一套
|
||||
「内存累积 + JSON 缓存 + 结束统一落盘」机制,此处收敛为 Writeback 类:
|
||||
|
||||
- 每个账号办完:回写内容只追加进内存 + 写轻量 JSON 缓存(防中途崩溃丢失,不碰 Excel)
|
||||
- 运行结束 flush() 统一写 Excel 一次,保存成功校验后删除缓存
|
||||
- 下次启动若发现残留缓存(上次崩溃)先恢复回写再办新单
|
||||
- kind 区分回写列:add → 办理状态;stop → 办理停保;缓存文件名也分开,增/减互不干扰
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
class Writeback:
|
||||
"""按 kind(add/stop)绑定的名单回写器。"""
|
||||
|
||||
def __init__(self, kind):
|
||||
self.kind = kind
|
||||
cache_name = ("writeback_pending.json" if kind == "add"
|
||||
else "writeback_pending_stop.json")
|
||||
self._cache_path = os.path.join(config.CKPT_DIR, cache_name)
|
||||
self._status_col = "办理状态" if kind == "add" else config.STOP_PROCESSED_COL
|
||||
self._pending_status = {}
|
||||
self._pending_remark = {}
|
||||
self._source_file = None
|
||||
self._source_sheet = None
|
||||
|
||||
# ---------------- 源名单绑定(flush 依赖) ----------------
|
||||
def bind_source(self, source_file, source_sheet):
|
||||
self._source_file = source_file
|
||||
self._source_sheet = source_sheet
|
||||
|
||||
def has_pending(self):
|
||||
return bool(self._pending_status or self._pending_remark)
|
||||
|
||||
# ---------------- JSON 缓存 ----------------
|
||||
def _save_ckpt(self):
|
||||
"""把累积的回写内容写 JSON 缓存(临时文件+替换,避免写一半损坏)。"""
|
||||
data = [{"id": cid, "status": self._pending_status.get(cid, ""),
|
||||
"remark": self._pending_remark.get(cid, "")}
|
||||
for cid in dict.fromkeys(list(self._pending_status)
|
||||
+ list(self._pending_remark))]
|
||||
os.makedirs(config.CKPT_DIR, exist_ok=True)
|
||||
tmp = self._cache_path + ".tmp"
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, ensure_ascii=False, indent=1)
|
||||
os.replace(tmp, self._cache_path)
|
||||
|
||||
def load_ckpt(self):
|
||||
"""启动时恢复上次未回写的累积内容(崩溃恢复)。返回已回写人员的身份证号集合。"""
|
||||
recovered = set()
|
||||
if not os.path.isfile(self._cache_path):
|
||||
return recovered
|
||||
try:
|
||||
with open(self._cache_path, "r", encoding="utf-8") as f:
|
||||
for it in json.load(f):
|
||||
cid = it.get("id")
|
||||
if it.get("status"):
|
||||
self._pending_status[cid] = it["status"]
|
||||
if it.get("remark"):
|
||||
self._pending_remark[cid] = it["remark"]
|
||||
if cid:
|
||||
recovered.add(cid)
|
||||
except Exception as e:
|
||||
config.log(f" 恢复回写缓存失败:{e}")
|
||||
return recovered
|
||||
|
||||
# ---------------- 累积 ----------------
|
||||
def writeback_source(self, status_map, remark_map):
|
||||
"""按身份证号码聚合回写内容(内存 + JSON 缓存,不碰 Excel)。"""
|
||||
self._pending_status.update(status_map or {})
|
||||
self._pending_remark.update(remark_map or {})
|
||||
try:
|
||||
self._save_ckpt()
|
||||
except Exception as e:
|
||||
config.log(f" 回写缓存写入失败(不影响办理,仅崩溃后需人工补状态):{e}")
|
||||
|
||||
# ---------------- 统一落盘 ----------------
|
||||
def flush(self):
|
||||
"""把累积的回写内容统一写回源名单 Excel(openpyxl 直改原文件),
|
||||
保存成功(校验)后删除 JSON 缓存。保存失败则缓存保留,下次启动自动恢复。"""
|
||||
if not self.has_pending():
|
||||
return 0
|
||||
if not self._source_file:
|
||||
raise RuntimeError("无源名单文件记录,无法回写")
|
||||
from openpyxl import load_workbook
|
||||
wb = load_workbook(self._source_file)
|
||||
ws = wb[self._source_sheet]
|
||||
# 表头第3行定位列号
|
||||
hdr = {}
|
||||
for c in ws[config.SOURCE_HEADER_ROW]:
|
||||
if c.value is not None:
|
||||
hdr[str(c.value).strip()] = c.column
|
||||
col_id = hdr.get('身份证号码')
|
||||
col_status = hdr.get(self._status_col)
|
||||
col_remark = hdr.get('备注')
|
||||
if not col_id or not col_status:
|
||||
raise RuntimeError(f"源名单缺少身份证号码/{self._status_col}列,无法回写")
|
||||
changed = 0
|
||||
pending_ids = set(self._pending_status) | set(self._pending_remark)
|
||||
ref = [config._norm_id(x) for x in pending_ids]
|
||||
for row in ws.iter_rows(min_row=config.SOURCE_HEADER_ROW + 1):
|
||||
cid = config._norm_id(row[col_id - 1].value)
|
||||
if cid and config._id_hit(cid, ref):
|
||||
r = row[0].row
|
||||
if cid in self._pending_status:
|
||||
ws.cell(row=r, column=col_status, value=self._pending_status[cid])
|
||||
if cid in self._pending_remark and col_remark:
|
||||
# 备注追加不覆盖:新备注换行追加(已存在则不重复追加)
|
||||
cell = ws.cell(row=r, column=col_remark)
|
||||
old = str(cell.value or '').strip()
|
||||
new = str(self._pending_remark[cid]).strip()
|
||||
if new not in old:
|
||||
cell.value = f"{old}\n{new}" if old else new
|
||||
changed += 1
|
||||
try:
|
||||
wb.save(self._source_file)
|
||||
except PermissionError:
|
||||
# 缓存保留,下次启动自动恢复回写
|
||||
raise RuntimeError(f"源名单文件被占用(请关闭 Excel 后重跑),回写未保存")
|
||||
self._pending_status.clear()
|
||||
self._pending_remark.clear()
|
||||
if os.path.isfile(self._cache_path):
|
||||
os.unlink(self._cache_path)
|
||||
config.log(f" 源名单回写完成:更新 {changed} 行 → "
|
||||
f"{os.path.basename(self._source_file)}(缓存已清除)")
|
||||
config.log(" 注意:openpyxl 保存会清掉公式缓存(如「区域」列 XLOOKUP),"
|
||||
"下次运行前请先用 Excel 打开并保存一次该名单以重算公式")
|
||||
return changed
|
||||
@@ -1,2 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""业务逻辑层(聚合子包)。"""
|
||||
@@ -1,133 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""目录预检:校验 base_dir(统一目录)是否满足插件各阶段需求。
|
||||
|
||||
用户设置资料根目录后,可先运行「目录预检」阶段确认目录结构齐备(真实布局):
|
||||
- 根目录:源名单《*社保变更及增减名单*.xlsx》、员工花名册.xlsx
|
||||
- 台账目录(默认根目录,可单独设置):社保户头管理台账*.xlsx(含缴费比例 sheet)
|
||||
- 社保增减名单制作/模板/:增员模版.xls、减员模版.xls
|
||||
- 告知书下发/模板/:三类告知书模板
|
||||
(名单制作输出/、回盘打印/、告知书下发/输出/ 由各阶段运行时自动创建,不预检)
|
||||
输出逐项 {名称, 是否就绪, 说明},未就绪项汇总列出,供用户补齐后重跑。
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
from datetime import datetime
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def _current_month_file(dir_path, pattern):
|
||||
"""目录内匹配 pattern 且文件名月份=当月的文件(告知书数据源要求当月)。"""
|
||||
if not os.path.isdir(dir_path):
|
||||
return None, "目录不存在"
|
||||
found = [n for n in os.listdir(dir_path)
|
||||
if n.lower().endswith(".xlsx") and not n.startswith("~$")
|
||||
and re.match(pattern.replace("*", ".*"), n)]
|
||||
if not found:
|
||||
return None, f"未找到匹配 {pattern} 的 xlsx"
|
||||
now = datetime.now()
|
||||
for name in found:
|
||||
m = re.search(r"(20\d{2})年(\d{1,2})月", name) or re.search(r"(20\d{2})(\d{2})", name)
|
||||
if m and (int(m.group(1)), int(m.group(2))) == (now.year, now.month):
|
||||
return os.path.join(dir_path, name), "当月文件"
|
||||
return None, f"均为历史月份:{sorted(found)[:5]}"
|
||||
|
||||
|
||||
def _check_sheets(excel_path, required):
|
||||
"""校验 xlsx 是否包含所有必需 sheet(关键字匹配)。返回 (ok, 缺失列表)。"""
|
||||
try:
|
||||
import pandas as pd
|
||||
xl = pd.ExcelFile(excel_path)
|
||||
names = [n.strip() for n in xl.sheet_names]
|
||||
missing = [kw for kw in required
|
||||
if not any(kw in n for n in names)]
|
||||
return (not missing), missing
|
||||
except Exception as e:
|
||||
return False, [f"读取失败:{e}"]
|
||||
|
||||
|
||||
def check_directory():
|
||||
"""执行目录预检。返回 dict {ok, missing, checks}。
|
||||
|
||||
checks: [{name, ok, detail}] 逐项清单(缺失/异常项 ok=False)。
|
||||
"""
|
||||
base = config.get_base_dir()
|
||||
ledger = config.get_ledger_dir()
|
||||
checks = []
|
||||
|
||||
def add(name, ok, detail):
|
||||
checks.append({"name": name, "ok": bool(ok), "detail": detail})
|
||||
|
||||
# ---- 0. 目录本身 ----
|
||||
base_ok = os.path.isdir(base)
|
||||
add("资料根目录", base_ok, base if base_ok else f"目录不存在:{base}")
|
||||
|
||||
# ---- 1. 名单制作 / 系统办理:源名单 ----
|
||||
src_file = None
|
||||
candidates = []
|
||||
if base_ok:
|
||||
candidates = [p for p in os.listdir(base)
|
||||
if p.lower().endswith(".xlsx") and not p.startswith("~$")
|
||||
and config.SOURCE_KEYWORD in p]
|
||||
add(f"源名单(*{config.SOURCE_KEYWORD}*.xlsx)", bool(candidates),
|
||||
"、".join(sorted(candidates)[:3]) or "未找到,请放入当月《社保变更及增减名单》")
|
||||
if candidates:
|
||||
src_file = os.path.join(base, max(
|
||||
candidates, key=lambda n: os.path.getmtime(os.path.join(base, n))))
|
||||
|
||||
# ---- 2. 告知书数据源:当月文件 ----
|
||||
if base_ok:
|
||||
cur, note = _current_month_file(base, f"*{config.SOURCE_KEYWORD}*")
|
||||
else:
|
||||
cur, note = None, "根目录不存在"
|
||||
add("源名单(当月文件,告知书用)", cur is not None, note)
|
||||
|
||||
# ---- 3. 源名单关键 sheet ----
|
||||
if src_file:
|
||||
ok, missing = _check_sheets(src_file, ["参保名单", "停保名单"])
|
||||
add("源名单关键 sheet(参保名单/停保名单)", ok, "缺失:" + "、".join(missing) if missing else "齐备")
|
||||
else:
|
||||
add("源名单关键 sheet(参保名单/停保名单)", False, "源名单缺失,跳过校验")
|
||||
|
||||
# ---- 4. 名单制作:模板 + 输出目录 ----
|
||||
tpl_dir = config.roster_template_dir()
|
||||
add_exact = os.path.join(tpl_dir, config.TEMPLATE_ADD)
|
||||
add_hit = (os.path.isfile(add_exact)
|
||||
or any("增员模版" in f for f in os.listdir(tpl_dir)) if os.path.isdir(tpl_dir) else False)
|
||||
add("增员模版(社保增减名单制作/模板/增员模版.xls)", add_hit,
|
||||
f"{tpl_dir}\\{config.TEMPLATE_ADD}" if base_ok else "根目录不存在")
|
||||
stop_exact = os.path.join(tpl_dir, config.TEMPLATE_STOP)
|
||||
stop_hit = (os.path.isfile(stop_exact)
|
||||
or any("减员模版" in f for f in os.listdir(tpl_dir)) if os.path.isdir(tpl_dir) else False)
|
||||
add("减员模版(社保增减名单制作/模板/减员模版.xls)", stop_hit,
|
||||
f"{tpl_dir}\\{config.TEMPLATE_STOP}" if base_ok else "根目录不存在")
|
||||
|
||||
# ---- 5. 台账(含缴费比例 sheet) ----
|
||||
ledger_ok = os.path.isdir(ledger)
|
||||
ledger_file = None
|
||||
if ledger_ok:
|
||||
cand = [p for p in os.listdir(ledger)
|
||||
if p.lower().endswith(".xlsx") and "社保户头管理台账" in p and not p.startswith("~$")]
|
||||
if cand:
|
||||
ledger_file = os.path.join(ledger, max(cand, key=lambda n: os.path.getmtime(os.path.join(ledger, n))))
|
||||
add("社保户头管理台账", ledger_file is not None,
|
||||
os.path.basename(ledger_file) if ledger_file else f"未找到(目录:{ledger})")
|
||||
if ledger_file:
|
||||
ok, missing = _check_sheets(ledger_file, ["缴费比例"])
|
||||
add("台账「缴费比例」sheet", ok, "缺失:" + "、".join(missing) if missing else "齐备")
|
||||
else:
|
||||
add("台账「缴费比例」sheet", False, "台账缺失,跳过校验")
|
||||
|
||||
# ---- 6. 告知书:花名册 + 三类模板 ----
|
||||
roster = os.path.join(base, "员工花名册.xlsx")
|
||||
add("员工花名册(告知书二级部门/接收人)", base_ok and os.path.isfile(roster),
|
||||
roster if base_ok else "根目录不存在")
|
||||
tpl_dir_notice = config.notice_template_dir()
|
||||
tpl_dir_ok = os.path.isdir(tpl_dir_notice)
|
||||
for key, tpl in config.NOTICE_TEMPLATES.items():
|
||||
p = os.path.join(tpl_dir_notice, tpl["file"])
|
||||
add(f"告知书模板[{key}](告知书下发/模板/{tpl['file']})", tpl_dir_ok and os.path.isfile(p),
|
||||
p if tpl_dir_ok else f"模板目录不存在:{tpl_dir_notice}")
|
||||
|
||||
missing = [c for c in checks if not c["ok"]]
|
||||
return {"ok": not missing, "missing": len(missing), "checks": checks}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,366 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""OA 工作沟通推送(work_communication.py 移植,适配插件底座)。
|
||||
|
||||
原影刀版用 DrissionPage SessionPage + 读共享 oa_cookies.json;插件版改为:
|
||||
- 登录态由底座注入(config.get_oa_session(),即 ctx.get_session("oa") 返回的
|
||||
requests.Session,已带 OA cookies),不读 cookie 文件
|
||||
- 请求直接用 requests.Session API(resp = session.get/post(...))
|
||||
|
||||
流程:解析接收人(工号/姓名 → 人员ID)→ 上传附件(getuserkey→二进制→submit绑定)→
|
||||
提交工作沟通(取新建页 fdId + 通知方式随机字段 → POST method=save 保存)。
|
||||
push_messages(messages) 逐条推送,返回 {success, message, doc_id, results}。
|
||||
"""
|
||||
import base64
|
||||
import mimetypes
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
# 附件二进制上传时的请求头(Referer 指向 OA 根地址,避免被服务端拦截)
|
||||
_DEFAULT_HEADERS = {
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"Chrome/120.0.0.0 Safari/537.36",
|
||||
"Referer": f"{config.OA_BASE_URL}/",
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
}
|
||||
|
||||
|
||||
class OALoginExpiredError(Exception):
|
||||
"""OA 登录态失效:接口返回登录页等非 JSON 内容。"""
|
||||
|
||||
|
||||
# ==================== 登录态(底座注入的 requests.Session) ====================
|
||||
def get_oa_session():
|
||||
"""取底座注入的 OA requests.Session;未登录时抛友好错误。"""
|
||||
session = config.get_oa_session()
|
||||
if session is None:
|
||||
raise RuntimeError("未注入 OA 登录态,请先在工作台(壳子)登录 OA 系统再运行本阶段")
|
||||
return session
|
||||
|
||||
|
||||
def is_session_valid(session):
|
||||
"""调轻量接口 sumTodoCount 判断 OA 会话是否有效。"""
|
||||
try:
|
||||
resp = session.get(config.TODO_COUNT_URL,
|
||||
params={"method": "sumTodoCount"}, timeout=10)
|
||||
if resp is None or resp.status_code != 200:
|
||||
return False
|
||||
text = resp.text or ""
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception as e:
|
||||
config.log(f"OA 会话校验异常:{e}", "WARN")
|
||||
return False
|
||||
|
||||
|
||||
# ==================== 通用响应校验 ====================
|
||||
def _check_response(resp, label):
|
||||
"""校验响应:存在性 / 状态码 / 登录态。返回 resp。"""
|
||||
if resp is None:
|
||||
raise RuntimeError(f"{label}请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"{label}接口状态码异常: {resp.status_code}")
|
||||
text = resp.text or ""
|
||||
if "login.jsp" in text or "j_username" in text:
|
||||
raise OALoginExpiredError(f"{label}接口返回登录页,OA 登录态已失效")
|
||||
return resp
|
||||
|
||||
|
||||
def oa_request_json(session, method, url, params, label, timeout=20, headers=None):
|
||||
"""通用「发送请求 + 校验响应」:发出请求 → 校验 → 返回 JSON。"""
|
||||
resp = (session.get(url, params=params, timeout=timeout, headers=headers)
|
||||
if method.upper() == "GET"
|
||||
else session.post(url, data=params, timeout=timeout, headers=headers))
|
||||
resp = _check_response(resp, label)
|
||||
text = resp.text or ""
|
||||
try:
|
||||
return resp.json()
|
||||
except Exception:
|
||||
raise RuntimeError(f"{label}接口返回非 JSON 数据(状态码 {resp.status_code}): {text[:200]}")
|
||||
|
||||
|
||||
# ==================== 人员搜索 ====================
|
||||
def search_person(session, keyword, org_type="15"):
|
||||
"""按工号或姓名搜索人员,返回 (person_id, person_name);未找到返回 None。"""
|
||||
params = {
|
||||
"s_bean": "organizationDialogSearch",
|
||||
"orgType": org_type,
|
||||
"deptLimit": "",
|
||||
"isExternal": "",
|
||||
"key": keyword,
|
||||
"s_ajax": "true",
|
||||
}
|
||||
resp = _check_response(session.get(config.PERSON_SEARCH_URL, params=params, timeout=20),
|
||||
"人员搜索")
|
||||
try:
|
||||
root = ET.fromstring(resp.text)
|
||||
except ET.ParseError as e:
|
||||
config.log(f"人员搜索[{keyword}]响应解析失败: {e}", "WARN")
|
||||
return None
|
||||
matches = []
|
||||
for node in root.iter("data"):
|
||||
pid = node.get("id")
|
||||
pname = node.get("name")
|
||||
if pid and pname:
|
||||
matches.append((pid, pname))
|
||||
if not matches:
|
||||
config.log(f"未搜索到人员: {keyword}", "WARN")
|
||||
return None
|
||||
for pid, pname in matches:
|
||||
if keyword in (pid, pname):
|
||||
config.log(f"搜索到人员: {pname} (ID: {pid})")
|
||||
return (pid, pname)
|
||||
if len(matches) > 1:
|
||||
config.log(f"关键字[{keyword}]模糊匹配到 {len(matches)} 人,默认取第一个: {matches[0]}", "WARN")
|
||||
pid, pname = matches[0]
|
||||
config.log(f"搜索到人员: {pname} (ID: {pid})")
|
||||
return (pid, pname)
|
||||
|
||||
|
||||
# ==================== 附件上传 ====================
|
||||
def upload_attachment(session, file_path):
|
||||
"""上传单个附件,返回最终附件 ID(attid)。getuserkey → 二进制上传 → submit 绑定。"""
|
||||
file_path = os.path.abspath(file_path)
|
||||
if not os.path.exists(file_path):
|
||||
raise FileNotFoundError(f"附件文件不存在: {file_path}")
|
||||
file_name = os.path.basename(file_path)
|
||||
file_size = str(os.path.getsize(file_path))
|
||||
file_type = mimetypes.guess_type(file_name)[0] or "application/octet-stream"
|
||||
last_modified = time.strftime(
|
||||
"%a %b %d %Y %H:%M:%S GMT+0800", time.localtime(os.path.getmtime(file_path)))
|
||||
fd_sign = base64.b64encode(file_name.encode("utf-8")).decode("utf-8")
|
||||
fd_sign = fd_sign.replace("+", "").replace("/", "").replace("=", "")
|
||||
|
||||
# 1) 获取 userkey
|
||||
resp1 = oa_request_json(session, "GET", config.ATT_UPLOAD_URL, {
|
||||
"method": "handleAttUpload", "gettype": "getuserkey", "format": "json",
|
||||
"filesize": file_size, "md5": "", "fileName": file_name,
|
||||
"isSupportDirect": "false", "s_ajax": "true",
|
||||
}, "附件上传-获取userkey", headers=_DEFAULT_HEADERS)
|
||||
userkey = resp1.get("token", {}).get("header", {}).get("userkey")
|
||||
if not userkey:
|
||||
raise RuntimeError(f"获取 userkey 失败: {resp1}")
|
||||
config.log(" 1. 获取 userkey 成功")
|
||||
|
||||
# 2) 上传二进制
|
||||
uploader_url = f"{config.ATT_UPLOADER_URL}?gettype=upload&format=json&userkey={userkey}"
|
||||
# 底座注入的共享会话默认带 Content-Type: application/x-www-form-urlencoded,
|
||||
# 会导致 requests 在 files 上传时不再自动生成 multipart/form-data 边界头,
|
||||
# 服务端(Apache Commons FileUpload)以 InvalidContentTypeException 拒绝。
|
||||
# 上传前临时清除该默认头,让 requests 生成正确的 multipart 请求,随后恢复。
|
||||
saved_ct = session.headers.pop("Content-Type", None)
|
||||
try:
|
||||
with open(file_path, "rb") as f:
|
||||
files = {"file": (file_name, f, file_type)}
|
||||
data2 = {"id": "WU_FILE_0", "name": file_name, "type": file_type,
|
||||
"lastModifiedDate": last_modified, "size": file_size}
|
||||
resp2 = _check_response(session.post(uploader_url, data=data2, files=files,
|
||||
timeout=60, headers=_DEFAULT_HEADERS),
|
||||
"附件上传-二进制")
|
||||
finally:
|
||||
if saved_ct is not None:
|
||||
session.headers["Content-Type"] = saved_ct
|
||||
try:
|
||||
filekey = resp2.json().get("filekey")
|
||||
except Exception:
|
||||
filekey = None
|
||||
if not filekey:
|
||||
raise RuntimeError(f"二进制上传失败: {resp2.text[:200]}")
|
||||
config.log(f" 2. 二进制上传成功, filekey: {filekey[:16]}...")
|
||||
|
||||
# 3) submit 绑定附件
|
||||
resp3 = oa_request_json(session, "GET", config.ATT_UPLOAD_URL, {
|
||||
"method": "handleAttUpload", "gettype": "submit", "format": "json",
|
||||
"filekey": filekey, "filename": file_name, "fdKey": "attachment",
|
||||
"fdModelName": config.KM_COLLABORATE_MODEL, "fdAttType": "byte",
|
||||
"width": "null", "height": "null", "proportion": "true",
|
||||
"fdSign": fd_sign, "s_ajax": "true",
|
||||
}, "附件上传-提交绑定", headers=_DEFAULT_HEADERS)
|
||||
attid = resp3.get("attid")
|
||||
if str(resp3.get("status")) != "1" or not attid:
|
||||
raise RuntimeError(f"提交绑定附件失败: {resp3}")
|
||||
config.log(f" 3. 提交绑定成功, attid: {attid}")
|
||||
return attid
|
||||
|
||||
|
||||
# ==================== 工作沟通提交 ====================
|
||||
def _encode_fd_content(content):
|
||||
"""把沟通内容编码为 OA 要求的 fdContent 格式:固定前缀 + {base64(HTML)}。"""
|
||||
return config.FD_CONTENT_PREFIX + "{" + \
|
||||
base64.b64encode(content.encode("utf-8")).decode("utf-8") + "}"
|
||||
|
||||
|
||||
def _get_add_page_fd_info(session):
|
||||
"""打开新建工作沟通页,解析出草稿 fdId、通知方式随机字段名、当前用户 ID。"""
|
||||
resp = _check_response(session.get(config.WORK_COMMUNICATION_ADD_URL, timeout=20),
|
||||
"新建工作沟通-取页面")
|
||||
html = resp.text or ""
|
||||
m = re.search(r'name="fdId"\s+value="([^"]*)"', html)
|
||||
fd_id = m.group(1) if m else ""
|
||||
m2 = re.search(r'name="(__notify_type_[a-f0-9]+)"', html)
|
||||
notify_field = m2.group(1) if m2 else ""
|
||||
m3 = re.search(r'name="docCreatorId"\s+value="([^"]*)"', html)
|
||||
creator_id = m3.group(1) if m3 else ""
|
||||
if not fd_id:
|
||||
raise RuntimeError("新建工作沟通页面解析失败:未找到 fdId")
|
||||
config.log(f"获取新建草稿 fdId: {fd_id}, 通知方式字段: {notify_field}, "
|
||||
f"页面当前用户ID: {creator_id or '无'}")
|
||||
return fd_id, notify_field, creator_id
|
||||
|
||||
|
||||
def submit_work_communication(session, receiver_ids, receiver_names, subject, content,
|
||||
attachment_ids=None, creator_id=None,
|
||||
category_id=config.FD_CATEGORY_DEFAULT):
|
||||
"""提交工作沟通(新建),成功返回沟通文档 ID(fdId)。多值分隔符用「;」。"""
|
||||
if category_id in config.FD_CATEGORY_MAP:
|
||||
category_id = config.FD_CATEGORY_MAP[category_id]
|
||||
elif not category_id:
|
||||
category_id = config.FD_CATEGORY_DEFAULT
|
||||
|
||||
receiver_ids_str = ";".join(receiver_ids) if isinstance(receiver_ids, list) else receiver_ids
|
||||
receiver_names_str = ";".join(receiver_names) if isinstance(receiver_names, list) else receiver_names
|
||||
if isinstance(attachment_ids, list):
|
||||
attachment_ids_str = ";".join(attachment_ids)
|
||||
else:
|
||||
attachment_ids_str = attachment_ids or ""
|
||||
|
||||
fd_id, notify_field, page_creator_id = _get_add_page_fd_info(session)
|
||||
creator_id = creator_id or page_creator_id
|
||||
if not creator_id:
|
||||
raise ValueError("docCreatorId(creator_id) 必填,且无法从新建页自动提取,请显式传入")
|
||||
|
||||
data = {
|
||||
"fdId": fd_id,
|
||||
"fdNumber": "",
|
||||
"participantIds": receiver_ids_str,
|
||||
"participantNames": receiver_names_str,
|
||||
"docSubject": subject,
|
||||
"fdIsPriority": "",
|
||||
"fdCategoryId": category_id,
|
||||
"fdContent": _encode_fd_content(content),
|
||||
"attachmentForms.attachment.fdModelId": "",
|
||||
"attachmentForms.attachment.extParam": "",
|
||||
"attachmentForms.attachment.fdModelName": config.KM_COLLABORATE_MODEL,
|
||||
"attachmentForms.attachment.fdKey": "attachment",
|
||||
"attachmentForms.attachment.fdAttType": "",
|
||||
"attachmentForms.attachment.fdMulti": "",
|
||||
"attachmentForms.attachment.deletedAttachmentIds": "",
|
||||
"attachmentForms.attachment.attachmentIds": attachment_ids_str,
|
||||
"__landray_fileattachment": "",
|
||||
"fdNotifyType": "todo",
|
||||
"__notify_type_placeholder": "todo",
|
||||
"_fdPartnerOperating": "true",
|
||||
"fdPartnerOperating": "true",
|
||||
"fdIsOnlyView": "false",
|
||||
"fdIsReminders": "false",
|
||||
"fdRemindersDay_hidden": "",
|
||||
"fdRemindersDay": "2",
|
||||
"docCreatorId": creator_id,
|
||||
}
|
||||
if notify_field:
|
||||
data[notify_field] = data.pop("__notify_type_placeholder")
|
||||
else:
|
||||
data.pop("__notify_type_placeholder", None)
|
||||
|
||||
resp = _check_response(session.post(config.KM_COLLABORATE_SAVE_URL,
|
||||
params={"method": "save", "s_seq": "1"},
|
||||
data=data, timeout=30),
|
||||
"工作沟通提交")
|
||||
text = resp.text or ""
|
||||
if "您的操作已成功" in text:
|
||||
config.log(f"工作沟通发送成功, 文档ID: {fd_id}")
|
||||
return fd_id
|
||||
raise RuntimeError(f"提交工作沟通失败: {text[:200]}")
|
||||
|
||||
|
||||
# ==================== 一键推送入口 ====================
|
||||
def _to_list(value):
|
||||
"""把单个字符串或列表统一成列表。"""
|
||||
if not value:
|
||||
return []
|
||||
return [value] if isinstance(value, str) else list(value)
|
||||
|
||||
|
||||
def send_work_communication(receiver_keywords, subject, content,
|
||||
attachment_paths=None, creator_id=None, category=None):
|
||||
"""发送单条工作沟通:解析接收人 → 上传附件 → 提交。返回沟通文档 ID。"""
|
||||
if not subject or not subject.strip():
|
||||
raise ValueError("subject(标题) 不能为空")
|
||||
if not content or not content.strip():
|
||||
raise ValueError("content(内容) 不能为空")
|
||||
session = get_oa_session()
|
||||
if not is_session_valid(session):
|
||||
raise OALoginExpiredError("OA 登录态已失效,请重新在工作台登录 OA")
|
||||
|
||||
# 1. 解析接收人
|
||||
receiver_ids, receiver_names, unresolved = [], [], []
|
||||
for kw in _to_list(receiver_keywords):
|
||||
kw = str(kw).strip()
|
||||
if not kw:
|
||||
continue
|
||||
result = search_person(session, kw)
|
||||
if result:
|
||||
pid, pname = result
|
||||
receiver_ids.append(pid)
|
||||
receiver_names.append(pname)
|
||||
config.log(f"接收人[{kw}] -> {pname} (ID: {pid})")
|
||||
else:
|
||||
unresolved.append(kw)
|
||||
if not receiver_ids:
|
||||
raise RuntimeError("未解析到任何接收人,请检查传入的工号/姓名")
|
||||
if unresolved:
|
||||
raise RuntimeError(f"以下接收人解析失败,已中止发送: {', '.join(unresolved)}")
|
||||
|
||||
# 2. 上传附件(任一失败即整体失败)
|
||||
attachment_ids = []
|
||||
for path in _to_list(attachment_paths):
|
||||
attid = upload_attachment(session, path)
|
||||
attachment_ids.append(attid)
|
||||
config.log(f"附件[{path}] -> attid: {attid}")
|
||||
|
||||
# 3. 提交沟通
|
||||
return submit_work_communication(
|
||||
session=session, receiver_ids=receiver_ids, receiver_names=receiver_names,
|
||||
subject=subject, content=content, attachment_ids=attachment_ids or None,
|
||||
creator_id=creator_id, category_id=category)
|
||||
|
||||
|
||||
def _send_wrapped(receiver_keywords, subject, content, attachment_paths="",
|
||||
creator_id="", category="工作安排"):
|
||||
"""单条工作沟通推送(捕获异常,返回 result dict)。"""
|
||||
try:
|
||||
doc_id = send_work_communication(
|
||||
receiver_keywords=receiver_keywords, subject=subject, content=content,
|
||||
attachment_paths=attachment_paths or None, creator_id=creator_id or None,
|
||||
category=category)
|
||||
return {"success": True, "message": f"工作沟通发送成功,文档ID: {doc_id}", "doc_id": doc_id}
|
||||
except Exception as e:
|
||||
config.log(f"工作沟通推送失败: {e}", "ERROR")
|
||||
return {"success": False, "message": f"工作沟通推送失败: {e}", "doc_id": ""}
|
||||
|
||||
|
||||
def push_messages(messages):
|
||||
"""逐条推送工作沟通(messages 结构同告知书模块产出的 OA 推送数据)。
|
||||
messages 每条含 {receivers, subject, content, attachment_paths, category}。
|
||||
返回 {success, message, doc_id, results}。"""
|
||||
results = []
|
||||
for i, msg in enumerate(messages or [], 1):
|
||||
r = _send_wrapped(
|
||||
receiver_keywords=msg.get("receivers", []),
|
||||
subject=msg.get("subject", ""),
|
||||
content=msg.get("content", ""),
|
||||
attachment_paths=msg.get("attachment_paths", ""),
|
||||
creator_id=msg.get("creator_id", ""),
|
||||
category=msg.get("category", "工作安排"))
|
||||
results.append(r)
|
||||
config.log(f"[{i}/{len(messages or [])}] {r.get('message')}")
|
||||
ok = sum(1 for r in results if r.get("success"))
|
||||
return {
|
||||
"success": ok == len(results),
|
||||
"message": f"共推送 {len(results)} 条,成功 {ok} 条",
|
||||
"doc_id": ",".join(r.get("doc_id", "") for r in results if r.get("doc_id")),
|
||||
"results": results,
|
||||
}
|
||||
@@ -1,285 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0008 重庆社保增减员导入名单制作(generate_add.py / generate_stop.py 移植)。
|
||||
|
||||
- make_add_lists():按参保类型(转移参保 / 新参保)分组生成《XX增员导入名单.xls》,
|
||||
分别输出到 转移参保-增员 / 新参保-增员 子目录(xlrd 读取 + xlutils 复制模板保留下拉字典);
|
||||
日期规则:首次参加工作日期=本月1号、个人身份=24.工人、工伤参保时间=当日、其余参保时间=本月1号。
|
||||
- make_stop_lists():按参保单位生成《XX减员导入名单.xls》到 停保-减员 子目录;
|
||||
减少时间=离职日期(当月)否则=当天、减少原因=在职人员主动解除劳动合同、
|
||||
五个险种减少标志=1 减少、失业原因=3 劳动者自愿辞职。
|
||||
"""
|
||||
import os
|
||||
from datetime import datetime
|
||||
|
||||
from .. import config
|
||||
from ..data import source_reader
|
||||
|
||||
|
||||
# ==================== 翻译映射 ====================
|
||||
def _translate_education(val):
|
||||
if val is None:
|
||||
return '90.其他'
|
||||
try:
|
||||
import pandas as pd
|
||||
if pd.isna(val):
|
||||
return '90.其他'
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return config.EDU_MAP.get(str(val).strip(), '90.其他')
|
||||
|
||||
|
||||
def _translate_nation(val):
|
||||
if val is None:
|
||||
return '99.其他'
|
||||
try:
|
||||
import pandas as pd
|
||||
if pd.isna(val):
|
||||
return '99.其他'
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return config.NATION_MAP.get(str(val).strip(), '99.其他')
|
||||
|
||||
|
||||
def _translate_residence(val):
|
||||
if val is None:
|
||||
return ''
|
||||
try:
|
||||
import pandas as pd
|
||||
if pd.isna(val):
|
||||
return ''
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return config.RESIDENCE_MAP.get(str(val).strip(), '')
|
||||
|
||||
|
||||
# ==================== 增员名单制作 ====================
|
||||
def _write_template_add(template_file, output_path, unit_no, unit_name, records):
|
||||
"""复制《增员模版.xls》写入 B1/D1 及 B4 起数据,另存为 output_path。
|
||||
|
||||
xlrd 读取(formatting_info 保留样式)+ xlutils.copy 复制,保留 Sheet2 下拉字典;
|
||||
B1=社保号,D1=参保单位全称;数据从模板第4行起,按 TPL_COLS_ADD 顺序写入 B~U 列;
|
||||
日期列以 yyyy/m/d 文本写入(工伤=当日,其余已填本月1日);多余示例行清空。
|
||||
"""
|
||||
import xlrd
|
||||
from xlutils.copy import copy as xl_copy
|
||||
rb = xlrd.open_workbook(template_file, formatting_info=True)
|
||||
orig_rows = rb.sheet_by_index(0).nrows
|
||||
wb = xl_copy(rb)
|
||||
ws = wb.get_sheet(0) # 批量导入
|
||||
ws.write(0, 1, unit_no) # B1 社保号
|
||||
ws.write(0, 3, unit_name) # D1 参保单位全称
|
||||
for i, rec in enumerate(records):
|
||||
r = config.TPL_DATA_START_ROW - 1 + i # 0-based:模板第4行 → index 3
|
||||
for c, col in enumerate(config.TPL_COLS_ADD):
|
||||
val = rec.get(col)
|
||||
if col in config.DATE_COLS_ADD and val is not None:
|
||||
ws.write(r, c + 1, f"{val.year}/{val.month}/{val.day}")
|
||||
else:
|
||||
ws.write(r, c + 1, config._clean_value(val))
|
||||
for r in range(config.TPL_DATA_START_ROW - 1 + len(records), orig_rows):
|
||||
for c in range(1, len(config.TPL_COLS_ADD) + 1):
|
||||
ws.write(r, c, "")
|
||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||
wb.save(output_path)
|
||||
|
||||
|
||||
def _find_template_add():
|
||||
"""定位《增员模版.xls》(社保增减名单制作/模板 下,优先精确名,其次按 *增员模版*.xls)。"""
|
||||
from glob import glob
|
||||
tpl_dir = config.roster_template_dir()
|
||||
exact = os.path.join(tpl_dir, config.TEMPLATE_ADD)
|
||||
if os.path.isfile(exact):
|
||||
return exact
|
||||
candidates = glob(os.path.join(tpl_dir, "*增员模版*.xls"))
|
||||
if not candidates:
|
||||
raise FileNotFoundError(
|
||||
f"在 {tpl_dir} 下未找到《{config.TEMPLATE_ADD}》,请先准备增员导入模板。")
|
||||
return max(candidates, key=os.path.getmtime)
|
||||
|
||||
|
||||
def _add_output_dir(operation_type):
|
||||
"""按参保类型取输出目录(社保增减名单制作/新参保-增员 或 转移参保-增员)。"""
|
||||
sub = {"新参保": config.OUTPUT_DIR_ADD_NEW,
|
||||
"转移参保": config.OUTPUT_DIR_ADD_TRANS}.get(operation_type)
|
||||
if not sub:
|
||||
raise ValueError(f"未知参保类型:{operation_type}(可选:{'/'.join(config.ADD_TYPES)})")
|
||||
out_dir = config.roster_output_dir(sub)
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
return out_dir
|
||||
|
||||
|
||||
def process_add_members(operation_type):
|
||||
"""生成增员导入名单(operation_type: '新参保' 或 '转移参保')。返回生成的份数。"""
|
||||
sub, source_file, _sheet, _ = source_reader.load_records(
|
||||
"add", operation_type=operation_type, status_filter="empty")
|
||||
config.log(f"源表:{os.path.basename(source_file)}")
|
||||
if sub.empty:
|
||||
config.log(f"没有找到【{operation_type}】的数据({config.TARGET_REGION}区域,办理状态为空)")
|
||||
return 0
|
||||
|
||||
today, first_day = datetime.now(), datetime.now().replace(day=1)
|
||||
config.log(f"今日日期:{today:%Y-%m-%d};本月1日:{first_day:%Y-%m-%d}"
|
||||
f"(首次参加/养老/失业/医疗/生育参保时间);工伤参保时间=当日")
|
||||
|
||||
template_file = _find_template_add()
|
||||
output_dir = _add_output_dir(operation_type)
|
||||
config.log(f"输出目录:{output_dir}")
|
||||
n_files = 0
|
||||
for store_name, group in sub.groupby(config.COLUMN_MAP_ADD['单位名称']):
|
||||
config.log(f" 正在处理:{store_name},共 {len(group)} 人")
|
||||
first_row = group.iloc[0]
|
||||
unit_no = first_row[config.COLUMN_MAP_ADD['社保号']]
|
||||
unit_full_name = first_row[config.COLUMN_MAP_ADD['参保单位全称']]
|
||||
records = []
|
||||
for _, row in group.iterrows():
|
||||
rec = {
|
||||
'证件号码': config._to_text(row[config.COLUMN_MAP_ADD['证件号码']]),
|
||||
'姓名': row[config.COLUMN_MAP_ADD['姓名']],
|
||||
'民族': _translate_nation(row[config.COLUMN_MAP_ADD['民族']]),
|
||||
'首次参加工作日期': first_day,
|
||||
'月基本工资额': config._clean_value(row[config.COLUMN_MAP_ADD['月基本工资额']]),
|
||||
'工种': config.DEFAULT_VALUES_ADD['工种'],
|
||||
'个人身份': config.DEFAULT_VALUES_ADD['个人身份'],
|
||||
'户口性质': _translate_residence(row[config.COLUMN_MAP_ADD['户口性质']]),
|
||||
'联系电话': config._to_text(row[config.COLUMN_MAP_ADD['联系电话']]),
|
||||
'文化程度': _translate_education(row[config.COLUMN_MAP_ADD['文化程度']]),
|
||||
'养老保险参保时间': first_day,
|
||||
'失业保险参保时间': first_day,
|
||||
'医疗保险参保时间': first_day,
|
||||
'工伤保险参保时间': today,
|
||||
'生育保险参保时间': first_day,
|
||||
'证件类型': config.DEFAULT_VALUES_ADD['证件类型'],
|
||||
'国籍': config.DEFAULT_VALUES_ADD['国籍'],
|
||||
'备注': config.DEFAULT_VALUES_ADD['备注'],
|
||||
'专职技能': config.DEFAULT_VALUES_ADD['专职技能'],
|
||||
'技能等级': config.DEFAULT_VALUES_ADD['技能等级'],
|
||||
}
|
||||
records.append(rec)
|
||||
output_path = os.path.join(output_dir,
|
||||
f"{config._safe_name(store_name)}增员导入名单.xls")
|
||||
_write_template_add(template_file, output_path, unit_no, unit_full_name, records)
|
||||
config.log(f" 已生成:{output_path}")
|
||||
n_files += 1
|
||||
config.log(f"所有【{operation_type}】导入名单生成完成!")
|
||||
return n_files
|
||||
|
||||
|
||||
def make_add_lists():
|
||||
"""增员名单制作:依次生成 转移参保 / 新参保 两类名单。返回 (总份数, 结果明细)。"""
|
||||
total, detail = 0, {}
|
||||
for op_type in config.ADD_TYPES:
|
||||
n = process_add_members(op_type)
|
||||
total += n
|
||||
detail[op_type] = n
|
||||
return total, detail
|
||||
|
||||
|
||||
# ==================== 减员名单制作 ====================
|
||||
def _write_template_stop(template_file, output_path, unit_no, unit_full_name, records):
|
||||
"""复制《减员模版.xls》写入 B1/D1 及 B4 起数据,另存为 output_path。"""
|
||||
import xlrd
|
||||
from xlutils.copy import copy as xl_copy
|
||||
rb = xlrd.open_workbook(template_file, formatting_info=True)
|
||||
orig_rows = rb.sheet_by_index(0).nrows
|
||||
wb = xl_copy(rb)
|
||||
ws = wb.get_sheet(0) # 批量导入
|
||||
ws.write(0, 1, unit_no) # B1 单位社保号
|
||||
ws.write(0, 3, unit_full_name) # D1 单位全称
|
||||
for i, rec in enumerate(records):
|
||||
r = config.TPL_DATA_START_ROW - 1 + i
|
||||
for c, col in enumerate(config.TPL_COLS_STOP):
|
||||
val = rec.get(col)
|
||||
if col in config.DATE_COLS_STOP and val is not None:
|
||||
ws.write(r, c + 1, f"{val.year}/{val.month}/{val.day}")
|
||||
else:
|
||||
ws.write(r, c + 1, config._clean_value(val))
|
||||
for r in range(config.TPL_DATA_START_ROW - 1 + len(records), orig_rows):
|
||||
for c in range(1, len(config.TPL_COLS_STOP) + 1):
|
||||
ws.write(r, c, "")
|
||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||
wb.save(output_path)
|
||||
|
||||
|
||||
def _find_template_stop():
|
||||
"""定位《减员模版.xls》(社保增减名单制作/模板 下,优先精确名,其次按 *减员模版*.xls)。"""
|
||||
from glob import glob
|
||||
tpl_dir = config.roster_template_dir()
|
||||
exact = os.path.join(tpl_dir, config.TEMPLATE_STOP)
|
||||
if os.path.isfile(exact):
|
||||
return exact
|
||||
candidates = glob(os.path.join(tpl_dir, "*减员模版*.xls"))
|
||||
if not candidates:
|
||||
raise FileNotFoundError(
|
||||
f"在 {tpl_dir} 下未找到《{config.TEMPLATE_STOP}》,请先准备停保导入模板。")
|
||||
return max(candidates, key=os.path.getmtime)
|
||||
|
||||
|
||||
def _resolve_reduce_time(raw, today):
|
||||
"""减少时间取值规则:离职日期为当月日期 → 减少时间=离职日期;否则=当天。"""
|
||||
try:
|
||||
import pandas as pd
|
||||
dt = pd.to_datetime(raw, errors='coerce')
|
||||
except (TypeError, ValueError):
|
||||
dt = None
|
||||
if dt is not None and getattr(dt, 'year', None) == today.year and dt.month == today.month:
|
||||
return dt, True
|
||||
return today, False
|
||||
|
||||
|
||||
def process_stop_members():
|
||||
"""生成停保导入名单。返回生成的份数。"""
|
||||
sub, source_file, _sheet, _ = source_reader.load_records(
|
||||
"stop", status_filter="empty")
|
||||
config.log(f"源表:{os.path.basename(source_file)}")
|
||||
if sub.empty:
|
||||
config.log(f"没有筛选到数据(类型 ∈ {'/'.join(config.STOP_TYPES)} ∩ "
|
||||
f"区域={config.TARGET_REGION} ∩ 办理停保为空)")
|
||||
return 0
|
||||
|
||||
today = datetime.now()
|
||||
config.log(f"制作日期:{today:%Y-%m-%d}")
|
||||
template_file = _find_template_stop()
|
||||
output_dir = config.roster_output_dir(config.OUTPUT_DIR_STOP)
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
config.log(f"输出目录:{output_dir}")
|
||||
n_files, n_leave_date = 0, 0
|
||||
for group_key, group in sub.groupby(config.COLUMN_MAP_STOP['单位名称']):
|
||||
config.log(f" 正在处理:单位【{group_key}】,共 {len(group)} 人")
|
||||
first_row = group.iloc[0]
|
||||
unit_no = first_row[config.COLUMN_MAP_STOP['单位社保号']]
|
||||
unit_full_name = first_row[config.COLUMN_MAP_STOP['单位全称']]
|
||||
records = []
|
||||
for _, row in group.iterrows():
|
||||
reduce_time, from_leave = _resolve_reduce_time(
|
||||
row[config.STOP_LEAVE_DATE_COL], today)
|
||||
if from_leave:
|
||||
n_leave_date += 1
|
||||
rec = {
|
||||
'个人编号': config._clean_value(row[config.COLUMN_MAP_STOP['个人编号']]),
|
||||
'证件号码': config._clean_value(row[config.COLUMN_MAP_STOP['证件号码']]),
|
||||
'姓名': config._clean_value(row[config.COLUMN_MAP_STOP['姓名']]),
|
||||
'减少时间': reduce_time,
|
||||
'减少原因': config.DEFAULT_VALUES_STOP['减少原因'],
|
||||
'养老保险减少标志': config.DEFAULT_VALUES_STOP['养老保险减少标志'],
|
||||
'失业保险减少标志': config.DEFAULT_VALUES_STOP['失业保险减少标志'],
|
||||
'医疗保险减少标志': config.DEFAULT_VALUES_STOP['医疗保险减少标志'],
|
||||
'工伤保险减少标志': config.DEFAULT_VALUES_STOP['工伤保险减少标志'],
|
||||
'生育保险减少标志': config.DEFAULT_VALUES_STOP['生育保险减少标志'],
|
||||
'失业原因': config.DEFAULT_VALUES_STOP['失业原因'],
|
||||
}
|
||||
records.append(rec)
|
||||
output_path = os.path.join(output_dir,
|
||||
f"{config._safe_name(group_key)}减员导入名单.xls")
|
||||
_write_template_stop(template_file, output_path, unit_no, unit_full_name, records)
|
||||
config.log(f" 已生成:{output_path}")
|
||||
n_files += 1
|
||||
config.log(f"所有停保导入名单生成完成!共 {len(sub[config.COLUMN_MAP_STOP['单位名称']].unique())} 个单位")
|
||||
config.log(f"减少时间取值:{n_leave_date} 人取离职日期,"
|
||||
f"{len(sub) - n_leave_date} 人取当天({today:%Y-%m-%d})")
|
||||
return n_files
|
||||
|
||||
|
||||
def make_stop_lists():
|
||||
"""减员名单制作。返回 (份数, 结果明细)。"""
|
||||
n = process_stop_members()
|
||||
return n, {"停保-减员": n}
|
||||
@@ -1,729 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""重庆社保系统增减员办理(增员/减员系统导入)—— import_add.py / import_stop.py 移植。
|
||||
|
||||
统一引擎 ImportEngine(kind):
|
||||
- kind='add':城保参保单位人员增加,消费《新参保-增员》/《转移参保-增员》目录
|
||||
《XX增员导入名单.xls》(按参保类型分目录),回写「办理状态」列(参保失败),
|
||||
审核结论回写「办理状态」
|
||||
- kind='stop':城保参保单位人员减少,消费《停保-减员》目录《XX减员导入名单.xls》,
|
||||
回写「办理停保」列(停保失败),审核结论回写「办理停保」
|
||||
|
||||
流程(每参保单位):
|
||||
登录(web_login,法人用户+图形验证码)→ 进业务页 → 上传导入 → 校验未通过回写 →
|
||||
预申报 → 去申报 → 全部提交 → 下一步 → 提交 → 去查看 → 明细审核结论回写 →
|
||||
下个单位前清 cookies 关浏览器。回写 JSON 缓存防崩溃,运行结束统一写 Excel。
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
from .. import config
|
||||
from ..data import source_reader
|
||||
from ..data.writeback import Writeback
|
||||
from . import web_login
|
||||
|
||||
|
||||
# ==================== 通用网页操作(增/减共用) ====================
|
||||
WEB_TIMEOUT = 20 # 网页元素等待超时(秒)
|
||||
|
||||
|
||||
def _shot(tab, name):
|
||||
"""调试截图:仅调试模式开启时保存页面截图并打印当前 URL。"""
|
||||
if not config.is_debug():
|
||||
return
|
||||
try:
|
||||
from pathlib import Path
|
||||
d = Path(config.CKPT_DIR) / "debug_shots"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
ts = datetime.now().strftime("%H%M%S")
|
||||
tab.get_screenshot(path=str(d), name=f"{ts}_{name}.png")
|
||||
config.log(f" [截图] {ts}_{name}.png url={str(tab.url)[:90]}")
|
||||
except Exception as e:
|
||||
config.log(f" [截图失败] {name}: {e}")
|
||||
|
||||
|
||||
def _click_any(tab, selectors, desc, timeout=WEB_TIMEOUT):
|
||||
"""按候选选择器顺序定位并点击第一个命中元素,全部未命中抛异常。"""
|
||||
last_err = None
|
||||
for sel in selectors:
|
||||
try:
|
||||
ele = tab.ele(sel, timeout=timeout)
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
continue
|
||||
if ele:
|
||||
ele.click()
|
||||
return ele
|
||||
raise RuntimeError(f"网页操作失败:找不到{desc}({last_err})")
|
||||
|
||||
|
||||
def _find_any(tab, selectors, desc, timeout=WEB_TIMEOUT):
|
||||
"""按候选选择器顺序查找元素,全部未命中抛异常。"""
|
||||
for sel in selectors:
|
||||
ele = tab.ele(sel, timeout=timeout)
|
||||
if ele:
|
||||
return ele
|
||||
raise RuntimeError(f"网页操作失败:找不到{desc}")
|
||||
|
||||
|
||||
def _wait_modal(tab, keyword, timeout=60):
|
||||
"""等待某 ant-modal 弹窗正文出现指定关键字,返回该弹窗元素;超时返回 None。"""
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
for m in tab.eles('css:.ant-modal-body'):
|
||||
if keyword in (m.text or ''):
|
||||
return m
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
return None
|
||||
|
||||
|
||||
def _dismiss_popups(tab, rounds=5):
|
||||
"""循环关闭常见提示弹窗(我已知晓/我知道了/确定/同意),直到没有可关的。"""
|
||||
texts = ["我已知晓", "我知道了", "知道了", "确 定", "确定", "同 意", "同意"]
|
||||
for _ in range(rounds):
|
||||
hit = False
|
||||
for t in texts:
|
||||
try:
|
||||
btn = tab.ele(f'tag:button@@text()={t}', timeout=0.5)
|
||||
except Exception:
|
||||
btn = None
|
||||
if btn:
|
||||
try:
|
||||
btn.click()
|
||||
config.log(f" 关闭弹窗:{t}")
|
||||
hit = True
|
||||
time.sleep(1.2)
|
||||
except Exception:
|
||||
pass
|
||||
if not hit:
|
||||
break
|
||||
|
||||
|
||||
def _open_business_page(page, work_tab, business_item):
|
||||
"""工作台 → 单位办事 → 业务「在线办理」。返回承载业务页的 tab。"""
|
||||
before = set(page.tab_ids)
|
||||
_click_any(work_tab, ['tag:button@@text()=单位办事'], '「单位办事」菜单')
|
||||
time.sleep(2.5)
|
||||
h4 = _find_any(work_tab, [f'tag:h4@@text()={business_item}'], f'业务入口「{business_item}」')
|
||||
li = h4
|
||||
for _ in range(6):
|
||||
li = li.parent()
|
||||
if li is None:
|
||||
break
|
||||
if li.tag == 'li':
|
||||
break
|
||||
act = li.ele('text=在线办理', timeout=3) if li is not None else None
|
||||
if act is None:
|
||||
raise RuntimeError("网页操作失败:找不到「在线办理」按钮")
|
||||
act.click()
|
||||
deadline = time.time() + 30
|
||||
while time.time() < deadline:
|
||||
time.sleep(1)
|
||||
cand_tids = [i for i in page.tab_ids if i not in before] + [work_tab.tab_id]
|
||||
for tid in cand_tids:
|
||||
try:
|
||||
t = page.get_tab(tid)
|
||||
if t.ele('#customized_form_controls_data', timeout=0.5):
|
||||
return t
|
||||
except Exception:
|
||||
continue
|
||||
raise RuntimeError("进入在线办理页失败(未出现文件上传控件)")
|
||||
|
||||
|
||||
# ==================== 减员特有:提示信息弹窗 ====================
|
||||
def _title_is_tip(m):
|
||||
"""弹窗标题是否含「提示信息」。"""
|
||||
try:
|
||||
t = m.ele('css:.ant-modal-title', timeout=0.2)
|
||||
return bool(t and '提示信息' in (t.text or ''))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _find_tip_modal_by_title(tab):
|
||||
"""按标题「提示信息」定位弹窗:一次查询所有标题元素再上溯到 .ant-modal。"""
|
||||
try:
|
||||
for t in tab.eles('css:.ant-modal-title'):
|
||||
if '提示信息' not in (t.text or ''):
|
||||
continue
|
||||
p = t
|
||||
for _ in range(4):
|
||||
p = p.parent()
|
||||
if p is None:
|
||||
break
|
||||
cls = p.attr('class') or ''
|
||||
if 'ant-modal' in cls and 'ant-modal-content' not in cls \
|
||||
and 'ant-modal-header' not in cls:
|
||||
return p
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def _remove_tip_modals(tab):
|
||||
"""把「提示信息」类弹窗残留节点连 wrap 一起从 DOM 移除。"""
|
||||
try:
|
||||
tab.run_js(
|
||||
"document.querySelectorAll('.ant-modal').forEach(function(m){"
|
||||
" var t = m.querySelector('.ant-modal-title');"
|
||||
" var onlyX = m.querySelector('button.ant-modal-close') &&"
|
||||
" m.querySelectorAll('button').length === 1;"
|
||||
" if ((t && t.textContent.indexOf('提示信息') !== -1) || onlyX) {"
|
||||
" var w = m.closest('.ant-modal-wrap') || m; w.remove();"
|
||||
" }"
|
||||
"});")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _close_tip_modal(tab):
|
||||
"""关闭「提示信息」弹窗(减员流程特有)。未弹出返回 False。"""
|
||||
m = _find_tip_modal_by_title(tab)
|
||||
if m is None:
|
||||
return False
|
||||
x = m.ele('css:button.ant-modal-close', timeout=1)
|
||||
if x:
|
||||
try:
|
||||
if x.states.has_rect:
|
||||
x.click()
|
||||
config.log(" 关闭「提示信息」弹窗")
|
||||
time.sleep(0.8)
|
||||
except Exception:
|
||||
pass
|
||||
_remove_tip_modals(tab)
|
||||
return True
|
||||
|
||||
|
||||
def _body_in_tip_modal(m):
|
||||
"""modal-body 是否属于标题为「提示信息」的说明弹窗。"""
|
||||
p = m
|
||||
for _ in range(3):
|
||||
try:
|
||||
p = p.parent()
|
||||
except Exception:
|
||||
return False
|
||||
if p is None:
|
||||
return False
|
||||
if _title_is_tip(p):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
# ==================== 导入与申报(增/减共用,少量分支) ====================
|
||||
def _wait_import_result(tab, timeout=90):
|
||||
"""导入结果探针:等待「导入完成」成功弹窗,或捕获失败提示。
|
||||
返回 ("ok", modal元素) / ("fail", 提示文本) / ("timeout", None)。"""
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
bodies = tab.eles('css:.ant-modal-body')
|
||||
# 第一遍只认「导入完成」成功标志(页面可能同时残留说明弹窗)
|
||||
for m in bodies:
|
||||
if '导入完成' in (m.text or ''):
|
||||
return "ok", m
|
||||
# 第二遍:其它任何非加载中、非「提示信息」说明弹窗的文本都视为失败提示
|
||||
for m in bodies:
|
||||
t = (m.text or '').strip()
|
||||
if t and not any(k in t for k in ('提交中', '导入中', '加载中')) \
|
||||
and not _body_in_tip_modal(m):
|
||||
return "fail", t
|
||||
for msg in tab.eles('css:.ant-message'):
|
||||
t = (msg.text or '').strip()
|
||||
if t:
|
||||
return "fail", t
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.4)
|
||||
return "timeout", None
|
||||
|
||||
|
||||
def _wait_unit_ready(tab, timeout=5):
|
||||
"""等参保单位信息真正显示出来(导入请求 aab001 部件的就绪信号)。"""
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
for sel in tab.eles('css:.ant-select-borderless'):
|
||||
for kind in ('css:.ant-select-selection-placeholder',
|
||||
'css:.ant-select-selection-item'):
|
||||
ele = sel.ele(kind, timeout=1)
|
||||
if ele and (ele.text or '').strip():
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
return False
|
||||
|
||||
|
||||
def _upload_import(tab, xls_path, close_tip, max_rounds=3):
|
||||
"""上传名单 xls 并点「导入」,带失败探针与重试。返回 (导入成功人数, 导入失败人数)。"""
|
||||
last_err = "导入超时无响应"
|
||||
for rnd in range(1, max_rounds + 1):
|
||||
inp = _find_any(tab, ['#customized_form_controls_data',
|
||||
'css:input[type="file"]'], '文件上传控件')
|
||||
inp.input(xls_path)
|
||||
if not _wait_unit_ready(tab, timeout=40):
|
||||
config.log(" 警告:40s 内单位信息未出现,本轮仍尝试导入")
|
||||
time.sleep(1.0)
|
||||
_shot(tab, "03_file_selected")
|
||||
if close_tip:
|
||||
_close_tip_modal(tab) # 点导入前再兜底清一次「提示信息」
|
||||
_click_any(tab, ['tag:button@@text()=导 入', 'tag:button@@text():导入'], '「导 入」按钮')
|
||||
state, payload = _wait_import_result(tab, timeout=90)
|
||||
if state == "ok":
|
||||
_shot(tab, "04_import_result")
|
||||
text = payload.text or ''
|
||||
m_ok = re.search(r'成功[::]\s*(\d+)\s*人', text)
|
||||
m_fail = re.search(r'失败[::]\s*(\d+)\s*人', text)
|
||||
total = int(m_ok.group(1)) if m_ok else 0
|
||||
failed = int(m_fail.group(1)) if m_fail else 0
|
||||
config.log(f" 导入完成:成功 {total} 人,失败 {failed} 人")
|
||||
if total == 0:
|
||||
# 全员未通过:不在此中止,交给上层读「校验未通过人员」回写参保失败并跳过申报
|
||||
# (若此处 raise,失败人员不会落账,下次运行会重复申报)
|
||||
config.log(f" 导入完成但成功人数为 0,提示:{text.strip()[:120]}")
|
||||
for t in ('确 定', '确定'):
|
||||
try:
|
||||
btn = tab.ele(f'tag:button@@text()={t}', timeout=2)
|
||||
except Exception:
|
||||
btn = None
|
||||
if btn:
|
||||
btn.click()
|
||||
break
|
||||
time.sleep(1.5)
|
||||
return total, failed
|
||||
last_err = payload if state == "fail" else "导入后未出现结果弹窗(超时)"
|
||||
config.log(f" 第 {rnd} 轮导入未成功:{str(last_err)[:120]}")
|
||||
time.sleep(2 + rnd)
|
||||
raise RuntimeError(f"导入重试 {max_rounds} 轮均失败,最后提示:{str(last_err)[:160]}")
|
||||
|
||||
|
||||
def _read_failed_rows(tab):
|
||||
"""切到「校验未通过人员」tab 读表格,返回 [(证件号码, 详细信息), ...]。"""
|
||||
try:
|
||||
tab_btn = tab.ele('tag:span@@text()=校验未通过人员', timeout=10)
|
||||
except Exception:
|
||||
tab_btn = None
|
||||
if not tab_btn:
|
||||
return []
|
||||
tab_btn.click()
|
||||
time.sleep(2)
|
||||
rows = []
|
||||
try:
|
||||
for tb in tab.eles('tag:table'):
|
||||
ths = [th.text.strip() for th in tb.eles('tag:th')]
|
||||
if '证件号码' in ths and '详细信息' in ths:
|
||||
i_id, i_detail = ths.index('证件号码'), ths.index('详细信息')
|
||||
for tr in tb.eles('css:tbody tr'):
|
||||
tds = [td.text.strip() for td in tr.eles('tag:td')]
|
||||
if len(tds) > max(i_id, i_detail) and len(tds[i_id]) >= 15:
|
||||
detail = tds[i_detail]
|
||||
for sep in (':', ':'):
|
||||
if sep in detail:
|
||||
detail = detail.split(sep, 1)[1].strip()
|
||||
break
|
||||
rows.append((tds[i_id], detail))
|
||||
break
|
||||
except Exception as e:
|
||||
config.log(f" 读取校验未通过表格异常:{e}")
|
||||
_shot(tab, "05_check_failed_tab")
|
||||
return rows
|
||||
|
||||
|
||||
def _wait_pdf_ready(tab, timeout=60):
|
||||
"""等 react-pdf canvas 出现且 2 秒不变,视为 PDF 绘制完成。超时仅告警不拦截。"""
|
||||
last, stable_since = None, None
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
canvases = tab.eles('css:.react-pdf__Page__canvas')
|
||||
sig = (len(canvases), canvases[0].attr('width') if canvases else None)
|
||||
except Exception:
|
||||
sig = None
|
||||
if sig and sig[0] > 0:
|
||||
if sig == last:
|
||||
if stable_since and time.time() - stable_since >= 2:
|
||||
return True
|
||||
else:
|
||||
stable_since = time.time()
|
||||
last = sig
|
||||
time.sleep(1)
|
||||
config.log(" 警告:等待 PDF 渲染超时,继续尝试提交", "WARN")
|
||||
return False
|
||||
|
||||
|
||||
def _goto_submit_page(tab, tries=3):
|
||||
"""点「下一步」进入提交页,验证「提 交」按钮出现;未出现则重试。"""
|
||||
for i in range(tries):
|
||||
_click_any(tab, ['tag:button@@text()=下一步'], '「下一步」按钮')
|
||||
deadline = time.time() + 12
|
||||
while time.time() < deadline:
|
||||
if tab.ele('tag:button@@text()=提 交', timeout=1):
|
||||
return True
|
||||
time.sleep(0.5)
|
||||
config.log(f" 下一步后未出现「提 交」按钮(第 {i + 1} 次),重试")
|
||||
time.sleep(1.5)
|
||||
return False
|
||||
|
||||
|
||||
def _click_submit_add(tab, tries=3):
|
||||
"""增员:点「提 交」,验证「已知晓」确认弹窗出现。"""
|
||||
for i in range(tries):
|
||||
btn = tab.ele('tag:button@@text()=提 交', timeout=5)
|
||||
if btn:
|
||||
try:
|
||||
btn.click()
|
||||
except Exception:
|
||||
pass
|
||||
deadline = time.time() + 10
|
||||
while time.time() < deadline:
|
||||
if tab.ele('tag:button@@text()=已知晓', timeout=1):
|
||||
return True
|
||||
try:
|
||||
for msg in tab.eles('css:.ant-message'):
|
||||
t = (msg.text or '').strip()
|
||||
if t:
|
||||
config.log(f" 提交提示:{t[:100]}")
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
config.log(f" 第 {i + 1} 次提交未出现「已知晓」确认弹窗,重试")
|
||||
time.sleep(1.5)
|
||||
return False
|
||||
|
||||
|
||||
def _confirm_submit_add(tab, tries=3):
|
||||
"""增员:点「已知晓」→ 等「您已成功提交」弹窗。"""
|
||||
for i in range(tries):
|
||||
btn = tab.ele('tag:button@@text()=已知晓', timeout=5)
|
||||
if btn:
|
||||
try:
|
||||
btn.click()
|
||||
except Exception:
|
||||
pass
|
||||
if _wait_modal(tab, '您已成功提交', timeout=60):
|
||||
return True
|
||||
config.log(f" 第 {i + 1} 次点击已知晓后未见成功弹窗,重试")
|
||||
return False
|
||||
|
||||
|
||||
def _click_submit_stop(tab, tries=3):
|
||||
"""减员:点「提 交」,成功弹窗自带「确 定/去查看」按钮(无「已知晓」确认环节)。"""
|
||||
for i in range(tries):
|
||||
btn = tab.ele('tag:button@@text()=提 交', timeout=5)
|
||||
if btn:
|
||||
try:
|
||||
btn.click()
|
||||
except Exception:
|
||||
pass
|
||||
if _wait_modal(tab, '您已成功提交', timeout=30):
|
||||
return True
|
||||
try:
|
||||
for msg in tab.eles('css:.ant-message'):
|
||||
t = (msg.text or '').strip()
|
||||
if t:
|
||||
config.log(f" 提交提示:{t[:100]}")
|
||||
except Exception:
|
||||
pass
|
||||
config.log(f" 第 {i + 1} 次提交未出现「您已成功提交」弹窗,重试")
|
||||
time.sleep(1.5)
|
||||
return False
|
||||
|
||||
|
||||
def _predeclare_and_submit(page, tab, kind):
|
||||
"""预申报 → 去申报 → 关弹窗 → 全部提交 → 等 PDF → 下一步 → 提交 → 等成功。
|
||||
kind='add' 走「已知晓」确认;kind='stop' 成功弹窗自带按钮。"""
|
||||
_click_any(tab, ['tag:button@@text()=预申报'], '「预申报」按钮')
|
||||
if _wait_modal(tab, '预申报成功', timeout=60) is None:
|
||||
raise RuntimeError("预申报后未出现成功弹窗")
|
||||
_click_any(tab, ['tag:button@@text()=去申报'], '「去申报」按钮')
|
||||
deadline = time.time() + 15
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
if tab.ele('tag:button@@text()=我已知晓', timeout=0.5) or \
|
||||
tab.ele('tag:button@@text()=我知道了', timeout=0.5) or \
|
||||
tab.ele('tag:button@@text()=全部提交', timeout=0.5):
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.3)
|
||||
_dismiss_popups(tab)
|
||||
_shot(tab, "06_declare_page")
|
||||
_click_any(tab, ['tag:button@@text()=全部提交'], '「全部提交」按钮')
|
||||
_wait_pdf_ready(tab)
|
||||
_shot(tab, "07_pdf_ready")
|
||||
if not _goto_submit_page(tab):
|
||||
_shot(tab, "08_no_submit_btn")
|
||||
raise RuntimeError("点击下一步后未出现「提 交」按钮")
|
||||
_shot(tab, "08_submit_page")
|
||||
if kind == 'add':
|
||||
if not _click_submit_add(tab):
|
||||
_shot(tab, "09_submit_no_confirm")
|
||||
raise RuntimeError("点击提交后未出现「已知晓」确认弹窗")
|
||||
if not _confirm_submit_add(tab):
|
||||
_shot(tab, "10_confirm_no_success")
|
||||
raise RuntimeError("点击已知晓后未出现「您已成功提交」弹窗(提交可能未完成)")
|
||||
else:
|
||||
if not _click_submit_stop(tab):
|
||||
_shot(tab, "09_submit_no_success")
|
||||
raise RuntimeError("点击提交后未出现「您已成功提交」弹窗(提交可能未完成)")
|
||||
_shot(tab, "11_submit_success")
|
||||
config.log(" 提交成功")
|
||||
|
||||
|
||||
def _collect_review_rows(tab):
|
||||
"""从明细表收集审核结论:{证件号码: (审核结论, 业务流水号)}。"""
|
||||
results = {}
|
||||
for tr in tab.eles('css:.ant-table-tbody tr.ant-table-row'):
|
||||
try:
|
||||
tds = [td.text.strip() for td in tr.eles('tag:td')]
|
||||
except Exception:
|
||||
continue
|
||||
cid = tds[3] if len(tds) > 3 else ''
|
||||
if len(cid) in (15, 18) and cid.rstrip('Xx').isdigit():
|
||||
results[cid] = (tds[4], tds[0])
|
||||
return results
|
||||
|
||||
|
||||
def _open_query_page(page, tab, timeout=25):
|
||||
"""点「去查看」进入申报查询列表(可能新开 tab),返回承载列表的 tab。"""
|
||||
before = set(page.tab_ids)
|
||||
_click_any(tab, ['tag:button@@text()=去查看'], '「去查看」按钮')
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
time.sleep(1)
|
||||
tids = [i for i in page.tab_ids if i not in before] + [tab.tab_id]
|
||||
for tid in tids:
|
||||
try:
|
||||
t = page.get_tab(tid)
|
||||
row = t.ele('css:.ant-table-tbody tr.ant-table-row', timeout=0.5)
|
||||
if row and row.ele('tag:a@@text()=查看', timeout=0.5):
|
||||
_shot(t, "12_query_list")
|
||||
return t
|
||||
except Exception:
|
||||
continue
|
||||
raise RuntimeError("点击去查看后未找到申报查询列表(含「查看」按钮的记录表)")
|
||||
|
||||
|
||||
def _query_review_results(page, tab, close_tip):
|
||||
"""进入申报查询列表 → (减员先关提示信息)→ 打开序号1记录「查看」→ 读审核结论。
|
||||
返回 {证件号码: (审核结论, 业务流水号)}。"""
|
||||
qtab = _open_query_page(page, tab)
|
||||
if close_tip:
|
||||
_close_tip_modal(qtab) # 去查看后会再弹一次「提示信息」,需先关闭
|
||||
for attempt in range(3):
|
||||
row = qtab.ele('css:.ant-table-tbody tr.ant-table-row', timeout=10)
|
||||
view = row.ele('tag:a@@text()=查看', timeout=3) if row else None
|
||||
if view:
|
||||
try:
|
||||
view.click()
|
||||
except Exception:
|
||||
pass
|
||||
deadline = time.time() + 12
|
||||
while time.time() < deadline:
|
||||
time.sleep(1)
|
||||
results = _collect_review_rows(qtab)
|
||||
if results:
|
||||
_shot(qtab, "13_review_detail")
|
||||
return results
|
||||
config.log(f" 第 {attempt + 1} 次查看未读到审核结论明细,重试")
|
||||
_shot(qtab, "13_review_detail_miss")
|
||||
time.sleep(1.5)
|
||||
raise RuntimeError("未读取到审核结论明细表")
|
||||
|
||||
|
||||
# ==================== 统一导入引擎 ====================
|
||||
class ImportEngine:
|
||||
"""按 kind(add/stop)配置的增/减员系统办理引擎。"""
|
||||
|
||||
def __init__(self, kind):
|
||||
self.kind = kind
|
||||
if kind == 'add':
|
||||
self.business_item = "城保参保单位人员增加"
|
||||
# 名单产出目录:按参保类型分文件夹(新参保-增员 / 转移参保-增员)
|
||||
self.import_dir_names = {
|
||||
"新参保": config.OUTPUT_DIR_ADD_NEW,
|
||||
"转移参保": config.OUTPUT_DIR_ADD_TRANS,
|
||||
}
|
||||
self.file_suffix = "增员导入名单.xls"
|
||||
self.fail_status = "参保失败"
|
||||
self.close_tip = False
|
||||
self.operation_type = config.WEB_ADD_TYPES
|
||||
else:
|
||||
self.business_item = "城保参保单位人员减少"
|
||||
self.import_dir_names = {}
|
||||
self.file_suffix = "减员导入名单.xls"
|
||||
self.fail_status = "停保失败"
|
||||
self.close_tip = True
|
||||
self.operation_type = None
|
||||
self.import_dir_name = config.OUTPUT_DIR_STOP if kind != 'add' else config.OUTPUT_DIR_ADD_NEW
|
||||
self.writeback = Writeback(kind)
|
||||
|
||||
def _import_dir(self, op_type):
|
||||
"""按参保类型取名单产出子目录(增员);减员固定「停保-减员」。"""
|
||||
if self.kind == 'add':
|
||||
return self.import_dir_names.get(op_type, config.OUTPUT_DIR_ADD_NEW)
|
||||
return self.import_dir_name
|
||||
|
||||
# ---------------- 预检 ----------------
|
||||
def precheck(self, units, accounts):
|
||||
"""预检:核对每个(类型+单位)的导入文件与账号。返回待办列表。"""
|
||||
tasks, errors = [], []
|
||||
config.log("\n========== 预检 ==========")
|
||||
for op_type, unit, count in units:
|
||||
import_dir = config.roster_output_dir(self._import_dir(op_type))
|
||||
file_path = os.path.join(import_dir, f"{config._safe_name(unit)}{self.file_suffix}")
|
||||
acc = accounts.get(unit)
|
||||
problems = []
|
||||
if not os.path.isfile(file_path):
|
||||
problems.append(f"缺导入文件({self._import_dir(op_type)}\\{os.path.basename(file_path)})")
|
||||
if acc is None:
|
||||
problems.append("台账未匹配(检查户头名/城市=重庆/是否在用=是)")
|
||||
else:
|
||||
if not acc["username"]:
|
||||
problems.append("账号缺失(I列信用代码与K列平台用户名均为空)")
|
||||
if not acc["password"]:
|
||||
problems.append("密码缺失(L列平台密码为空)")
|
||||
tag = f"{unit}({op_type or '停保'},{count}人)"
|
||||
if problems:
|
||||
errors.append(f"[{unit} {op_type or ''}] " + ";".join(problems))
|
||||
config.log(f" ✗ {tag}:{';'.join(problems)}")
|
||||
else:
|
||||
tasks.append({"type": op_type, "unit": unit, "count": count, "file": file_path,
|
||||
"username": acc["username"], "password": acc["password"]})
|
||||
config.log(f" ✓ {tag} 账号={acc['username']}"
|
||||
f"({acc['username_src']})文件={os.path.basename(file_path)}")
|
||||
if errors:
|
||||
config.log(f"\n预检未通过,共 {len(errors)} 个问题,请先修正后重跑:")
|
||||
for e in errors:
|
||||
config.log(f" - {e}")
|
||||
return None
|
||||
config.log(f"预检通过:{len(tasks)} 个待办理\n")
|
||||
return tasks
|
||||
|
||||
# ---------------- 单个单位网页办理 ----------------
|
||||
def do_web_import(self, task):
|
||||
"""登录后的完整业务流程:进业务页 → 上传导入 → 校验回写 → 预申报提交 → 查询回写。"""
|
||||
page = web_login.LAST_SESSION.get('page')
|
||||
work_tab = web_login.LAST_SESSION.get('tab')
|
||||
if page is None or work_tab is None:
|
||||
return {"success": False, "message": "无有效登录会话"}
|
||||
|
||||
res = {"success": False, "imported": 0, "failed": [], "review": {}}
|
||||
try:
|
||||
_shot(work_tab, "01_workbench")
|
||||
biz_tab = _open_business_page(page, work_tab, self.business_item)
|
||||
if self.close_tip:
|
||||
_close_tip_modal(biz_tab) # 减员:进业务页先关「提示信息」弹窗
|
||||
_shot(biz_tab, "02_biz_upload_page")
|
||||
|
||||
# 1) 上传导入
|
||||
total, _failed_cnt = _upload_import(biz_tab, task['file'], self.close_tip)
|
||||
res['imported'] = total
|
||||
|
||||
# 2) 校验未通过:回写 参保失败/停保失败 + 备注(详细信息)
|
||||
fail_rows = _read_failed_rows(biz_tab)
|
||||
res['failed'] = [{"id": cid, "detail": d} for cid, d in fail_rows]
|
||||
expected = task.get('count', 0)
|
||||
if expected and total + len(fail_rows) != expected:
|
||||
raise RuntimeError(
|
||||
f"人数不平账:导入成功{total} + 校验未通过{len(fail_rows)} ≠ 名单{expected}人,"
|
||||
f"中止该单位(防漏人/重复申报),请人工核对")
|
||||
if fail_rows:
|
||||
self.writeback.writeback_source(
|
||||
{cid: self.fail_status for cid, _ in fail_rows},
|
||||
{cid: d for cid, d in fail_rows})
|
||||
passed = total
|
||||
|
||||
# 3) 全员未通过 → 跳过申报
|
||||
if passed <= 0:
|
||||
config.log(" 校验通过人数为 0,跳过申报")
|
||||
res.update(success=True,
|
||||
message=f"导入{total}人,全部校验未通过,已回写未申报")
|
||||
return res
|
||||
|
||||
# 4) 预申报 → 正式提交 → 查询审核结论回写
|
||||
_predeclare_and_submit(page, biz_tab, self.kind)
|
||||
review = _query_review_results(page, biz_tab, self.close_tip)
|
||||
res['review'] = [{"id": cid, "conclusion": c, "sn": sn}
|
||||
for cid, (c, sn) in review.items()]
|
||||
if review:
|
||||
self.writeback.writeback_source(
|
||||
{cid: concl for cid, (concl, _) in review.items()}, {})
|
||||
res.update(success=True,
|
||||
message=f"导入{total}人,未通过{len(fail_rows)}人,提交{passed}人")
|
||||
return res
|
||||
except Exception as e:
|
||||
res["message"] = f"网页操作异常:{e}"
|
||||
return res
|
||||
|
||||
# ---------------- 逐单位登录 + 网页操作 ----------------
|
||||
def process_units(self, tasks, accounts, progress_span=(0, 100)):
|
||||
"""逐参保单位:登录 → 网页导入申报 → 回写。每账号办完清 cookies 关浏览器。"""
|
||||
span_start, span_end = progress_span
|
||||
results = []
|
||||
for i, task in enumerate(tasks, 1):
|
||||
config.log(f"\n========== [{i}/{len(tasks)}] {task['unit']}"
|
||||
f"({task.get('type') or '停保'},{task['count']}人)==========")
|
||||
config.log(f"导入文件:{task['file']}")
|
||||
if len(tasks) > 1:
|
||||
config.progress(span_start + int((span_end - span_start) * (i - 1) / len(tasks)))
|
||||
try:
|
||||
login_res = web_login.ensure_login(task["username"], task["password"])
|
||||
except Exception as e:
|
||||
login_res = {"success": False, "message": f"登录调用异常:{e}"}
|
||||
config.log(f"登录结果:{login_res.get('message')}")
|
||||
try:
|
||||
if login_res.get("success"):
|
||||
web_res = self.do_web_import(task)
|
||||
config.log(f"办理结果:{web_res.get('message')}")
|
||||
results.append({**task, **web_res})
|
||||
else:
|
||||
results.append({**task, "success": False,
|
||||
"message": login_res.get("message", "")})
|
||||
finally:
|
||||
web_login.close_session()
|
||||
config.progress(span_end)
|
||||
return results
|
||||
|
||||
# ---------------- 主流程 ----------------
|
||||
def run(self, progress_span=(0, 100)):
|
||||
"""主流程:恢复缓存 → 读名单(排除已回写人员)→ 取号 → 预检 → 逐单位登录(+导入)→ 统一回写。
|
||||
返回 JSON 安全 dict。"""
|
||||
recovered_ids = self.writeback.load_ckpt()
|
||||
units, source_file, source_sheet = source_reader.load_units(
|
||||
self.kind, operation_type=self.operation_type, status_filter="empty",
|
||||
exclude_ids=recovered_ids)
|
||||
self.writeback.bind_source(source_file, source_sheet)
|
||||
if recovered_ids:
|
||||
config.log("\n检测到上次未回写的内容,先统一回写:")
|
||||
try:
|
||||
self.writeback.flush()
|
||||
except Exception as e:
|
||||
config.log(f"恢复回写失败(缓存保留,下次启动重试):{e}")
|
||||
if not units:
|
||||
return {"success": True, "message": "无待办数据", "total": 0, "done": 0}
|
||||
|
||||
accounts = source_reader.load_accounts([u for _, u, _ in units])
|
||||
tasks = self.precheck(units, accounts)
|
||||
if tasks is None:
|
||||
return {"success": False, "message": "预检未通过,详见日志",
|
||||
"total": len(units), "done": 0}
|
||||
|
||||
limit = config.get_run_limit()
|
||||
results = self.process_units(tasks[:limit], accounts, progress_span)
|
||||
try:
|
||||
self.writeback.flush()
|
||||
except Exception as e:
|
||||
config.log(f"回写失败:{e}")
|
||||
ok = [r for r in results if r["success"]]
|
||||
fail = [r for r in results if not r["success"]]
|
||||
config.log(f"\n========== 汇总 ==========")
|
||||
config.log(f"成功 {len(ok)} 家,失败 {len(fail)} 家")
|
||||
for r in fail:
|
||||
config.log(f" ✗ {r['unit']}({r.get('type') or ''}):{r.get('message', '')}")
|
||||
return {"success": not fail, "message": f"成功{len(ok)}/失败{len(fail)}",
|
||||
"total": len(results), "done": len(ok)}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user