refactor: 完成项目目录重构与代码迁移
本次提交完成了整体项目的目录梳理与代码迁移: 1. 将根级controlplane、webhost等目录的代码迁移至desktop/对应子目录,统一桌面端架构 2. 移动并整理了插件目录结构,将插件统一放入根级plugins/ 3. 调整了前端项目的路径与配置,统一前后端开发构建流程 4. 清理了废弃的旧版app/目录与冗余的构建中间文件 5. 更新了.gitignore与README.md,适配新的项目结构
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""示例场景插件:证明「后端 run + 前端通用表单 + 实时日志/进度」的插件化链路可用。
|
||||
后续真实场景(如考勤月报封存检查)按同样方式接入即可。
|
||||
"""
|
||||
import time
|
||||
|
||||
from webhost.backend.plugins.base import PLUGINS, RunContext, ScenePlugin
|
||||
|
||||
|
||||
class DemoPlugin(ScenePlugin):
|
||||
id = "demo"
|
||||
name = "示例检查"
|
||||
version = "1.0.0"
|
||||
description = "跑一个带进度与日志的假任务,用于验证插件链路。"
|
||||
fields = [
|
||||
{"key": "steps", "label": "步数", "type": "int", "default": 3},
|
||||
{"key": "mode", "label": "模式", "type": "select",
|
||||
"options": ["正常", "中途报错"], "default": "正常"},
|
||||
]
|
||||
|
||||
def run(self, fields: dict, ctx: RunContext) -> dict:
|
||||
steps = max(1, min(50, int(fields.get("steps", 3))))
|
||||
mode = fields.get("mode", "正常")
|
||||
ctx.log(f"开始示例检查:{steps} 步,模式={mode}")
|
||||
for i in range(1, steps + 1):
|
||||
time.sleep(0.6)
|
||||
ctx.progress(int(i / steps * 90))
|
||||
ctx.log(f"第 {i}/{steps} 步完成")
|
||||
if mode == "中途报错":
|
||||
raise RuntimeError("按模式设置的报错,用于演示失败处理")
|
||||
ctx.progress(100)
|
||||
ctx.log("示例检查完成")
|
||||
return {
|
||||
"summary": f"共执行 {steps} 步,全部正常",
|
||||
"rows": [[i, f"结果 {i}"] for i in range(1, steps + 1)],
|
||||
}
|
||||
|
||||
|
||||
PLUGINS.append(DemoPlugin())
|
||||
@@ -0,0 +1,59 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""登录态自检(共享登录态 + 共享模块验证)
|
||||
|
||||
- 校验 HR / OA 共享登录态(真实 API 校验,非内存假状态)
|
||||
- 若 HR 在线:实测共享数据模块(desktop/shared/seal_data_export)能否构建 session、
|
||||
取 userId 并拉取指定月份封存数据 —— 验证 webhost 复用共享模块的完整链路
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from webhost.backend.shared import seal_data_export as _seal
|
||||
from webhost.backend import auth as platform_auth
|
||||
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
||||
|
||||
|
||||
class PlatformCheck(ScenePlugin):
|
||||
id = "platform_check"
|
||||
name = "登录态自检"
|
||||
version = "1.0.0"
|
||||
description = "校验 HR/OA 共享登录态,并实测共享模块(封存数据拉取)可用性"
|
||||
platform = ""
|
||||
|
||||
def run(self, fields: dict, ctx) -> dict:
|
||||
report = {}
|
||||
for pid in ("hr", "oa"):
|
||||
online = platform_auth.is_online(pid)
|
||||
label = platform_auth._LABELS[pid]
|
||||
report[pid] = "已登录" if online else "未登录"
|
||||
ctx.log(f"[共享登录态] {label}:{'已登录' if online else '未登录'}")
|
||||
|
||||
seal_info = None
|
||||
if report.get("hr") == "已登录":
|
||||
ym = str(fields.get("_month") or datetime.now().strftime("%Y-%m"))
|
||||
try:
|
||||
ctx.log("开始实测共享模块 seal_data_export……")
|
||||
ctx.progress(40)
|
||||
session = ctx.get_session("hr")
|
||||
user_id = ctx.get_user_id("hr")
|
||||
ctx.log(f"构建 session 成功,HR userId = {user_id or '(空)'}")
|
||||
page = _seal.fetch_seal_page(
|
||||
session, user_id, ym, page_no=1, page_size=5)
|
||||
rows = page.get("datas") or []
|
||||
seal_info = f"{ym} 返回 {len(rows)} 条(state={page.get('state')})"
|
||||
ctx.log(f"[共享模块] 封存数据拉取成功:{seal_info}")
|
||||
ctx.progress(100)
|
||||
except Exception as e: # noqa: BLE001
|
||||
ctx.log(f"[共享模块] 调用失败:{e}", level="ERROR")
|
||||
seal_info = f"error: {e}"
|
||||
else:
|
||||
ctx.log("HR 未登录,跳过共享模块实测(请先点击顶部 HR 登录)")
|
||||
|
||||
summary = ";".join(f"{platform_auth._LABELS[k]}={v}" for k, v in report.items())
|
||||
if seal_info:
|
||||
summary += f";封存模块:{seal_info}"
|
||||
return {"summary": summary, "report": report, "seal": seal_info}
|
||||
|
||||
|
||||
PLUGINS.append(PlatformCheck())
|
||||
@@ -0,0 +1,109 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""社保系统增减员办理 - webhost 场景插件(XQ0008 + XQ0014 合并版)
|
||||
|
||||
四个执行模式 + 预检,覆盖重庆社保增减员业务闭环:
|
||||
增员名单制作 / 减员名单制作(XQ0008,纯 Excel 离线生成)
|
||||
增员办理 / 核查回盘(XQ0014,DrissionPage 登录政务平台逐单位办理)
|
||||
预检(只读源表 + 台账取号校验,不开浏览器)
|
||||
执行分批:增员办理/核查回盘按 limit 字段控制单次处理的单位数(0=不限)。
|
||||
登录与凭证:按参保单位从「社保户头管理台账」取号,浏览器现场真登录(无 cookies 缓存)。
|
||||
"""
|
||||
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
||||
|
||||
from . import config
|
||||
from . import source
|
||||
|
||||
|
||||
class SbPersonChangePlugin(ScenePlugin):
|
||||
id = "sb_person_change"
|
||||
name = "社保系统增减员办理"
|
||||
version = "1.0.0"
|
||||
description = "重庆社保增减员全流程:增员/减员名单制作 → 平台增员办理 → 核查回盘(含预检)"
|
||||
platform = "" # 政务网自登录(台账取号 + 浏览器现场登录),不使用底座共享登录态
|
||||
uses_month = False # 源表按最新 *社保*.xlsx 自动定位,无需月份参数
|
||||
fields = [
|
||||
{"key": "mode", "label": "执行模式", "type": "select",
|
||||
"options": ["增员名单制作", "减员名单制作", "增员办理", "核查回盘", "预检"],
|
||||
"default": "增员名单制作"},
|
||||
{"key": "limit", "label": "分批条数(0=不限)", "type": "int", "default": 0},
|
||||
{"key": "debug_mode", "label": "调试模式", "type": "select",
|
||||
"options": ["关闭", "开启"], "default": "关闭"},
|
||||
]
|
||||
|
||||
def run(self, fields: dict, ctx) -> dict:
|
||||
fields = fields or {}
|
||||
# 注入日志与调试开关(插件内全部模块经 config.log 输出)
|
||||
config.set_log(ctx.log)
|
||||
config.set_debug(str(fields.get("debug_mode") or "关闭") == "开启")
|
||||
mode = str(fields.get("mode") or "增员名单制作").strip()
|
||||
try:
|
||||
limit = max(0, int(fields.get("limit") or 0))
|
||||
except (TypeError, ValueError):
|
||||
limit = 0
|
||||
|
||||
ctx.log(f"开始执行:{mode}" + (f"(分批 {limit})" if limit else ""))
|
||||
|
||||
if mode == "预检":
|
||||
return self._run_precheck(ctx)
|
||||
if mode == "增员名单制作":
|
||||
from . import mode_make_add
|
||||
return mode_make_add.run(ctx)
|
||||
if mode == "减员名单制作":
|
||||
from . import mode_make_stop
|
||||
return mode_make_stop.run(ctx)
|
||||
if mode == "增员办理":
|
||||
from . import mode_do_add
|
||||
return mode_do_add.run(ctx, limit=limit)
|
||||
if mode == "核查回盘":
|
||||
from . import mode_check
|
||||
return mode_check.run(ctx, limit=limit)
|
||||
raise ValueError(f"未知执行模式:{mode}")
|
||||
|
||||
# ---------- 预检(不开浏览器,验证数据链路) ----------
|
||||
def _run_precheck(self, ctx) -> dict:
|
||||
from . import mode_do_add
|
||||
from datetime import datetime
|
||||
|
||||
ctx.progress(5)
|
||||
notes, problems = [], []
|
||||
|
||||
# 1) 增员办理预检:待办单位 + 导入文件 + 台账取号
|
||||
units = source.load_add_units()
|
||||
if units:
|
||||
ctx.progress(30)
|
||||
accounts = source.load_accounts([u for u, _ in units])
|
||||
tasks = mode_do_add.precheck(units, accounts)
|
||||
if tasks is None:
|
||||
problems.append("增员办理预检未通过(缺导入文件/台账账号,详见日志)")
|
||||
else:
|
||||
notes.append(f"增员办理:{len(tasks)} 个单位可办(共 {sum(t['count'] for t in tasks)} 人)")
|
||||
else:
|
||||
notes.append("增员办理:无待办数据(办理状态为空的新参保-增员)")
|
||||
ctx.progress(55)
|
||||
|
||||
# 2) 核查回盘预检:待审核单位 + 台账取号
|
||||
tasks_chk = source.load_check_tasks()
|
||||
if tasks_chk:
|
||||
ctx.progress(75)
|
||||
accounts_chk = source.load_accounts([t['unit'] for t in tasks_chk])
|
||||
errs = []
|
||||
for t in tasks_chk:
|
||||
acc = accounts_chk.get(t['unit'])
|
||||
if acc is None:
|
||||
errs.append(f"[{t['unit']}] 台账未匹配")
|
||||
elif not acc['username'] or not acc['password']:
|
||||
errs.append(f"[{t['unit']}] 账号或密码缺失")
|
||||
if errs:
|
||||
problems.append("核查回盘预检未通过:" + ";".join(errs))
|
||||
else:
|
||||
notes.append(f"核查回盘:{len(tasks_chk)} 个单位可核查"
|
||||
f"(共 {sum(t['count'] for t in tasks_chk)} 人待审核)")
|
||||
else:
|
||||
notes.append("核查回盘:无待核查数据(办理状态=待审核)")
|
||||
ctx.progress(100)
|
||||
|
||||
summary = f"预检完成 {datetime.now():%H:%M:%S}:" + (";".join(notes) if notes else "无待办")
|
||||
return {"summary": summary, "rows": [], "notes": notes + problems}
|
||||
|
||||
|
||||
PLUGINS.append(SbPersonChangePlugin())
|
||||
@@ -0,0 +1,256 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""社保系统增减员办理(sb_person_change)插件配置。
|
||||
|
||||
合并 XQ0008(名单制作)+ XQ0014(增员办理/核查回盘)的固化配置,
|
||||
与 workflows 影刀版各源文件的常量保持同源(四方向零依赖,各自演进)。
|
||||
"""
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
from glob import glob
|
||||
from pathlib import Path
|
||||
|
||||
# ==================== 插件内目录 ====================
|
||||
_HERE = Path(__file__).resolve().parent
|
||||
DEBUG_DIR = _HERE / "debug" # 截图/验证码/回写缓存落盘目录(debug 开启或崩溃恢复用)
|
||||
CKPT_FILE = DEBUG_DIR / "writeback_pending.json"
|
||||
|
||||
# ==================== 1. 文件路径配置 ====================
|
||||
SOURCE_DIR = os.getenv("cq_social_change_dir") or r"D:\资料\人资\重庆社保增减员导入名单制作"
|
||||
LEDGER_DIR = os.getenv("cq_social_ledger_dir") or r"D:\资料\人资\社保系统增减员办理"
|
||||
SOURCE_GLOB = "*社保*.xlsx" # 源名单文件(年月动态,取最新)
|
||||
LEDGER_GLOB = "*社保户头管理台账*.xlsx" # 台账文件(可能加前后缀,取最新)
|
||||
IMPORT_DIR_NAME = "新参保-增员" # 增员导入名单产出目录(按参保类型分文件夹)
|
||||
HUIPAN_DIR = r"D:\资料\人资\社保系统增减员办理\回盘打印\新参保-增员" # 回盘文件保存目录
|
||||
|
||||
# ==================== 2. 源表结构配置 ====================
|
||||
REGION = "重庆" # 区域筛选值
|
||||
OPERATION_TYPE = "新参保" # 参保类型筛选值
|
||||
TYPE_COL, REGION_COL, STATUS_COL, UNIT_COL = "参保类型", "区域", "办理状态", "参保单位"
|
||||
SOURCE_HEADER_ROW = 3 # 源表表头在第3行
|
||||
|
||||
# 台账「缴费比例」sheet 数据列(0-based,表头占 1-2 行已跳过)
|
||||
LEDGER_COL = {"户头": 1, "城市": 3, "在用": 4, "信用代码": 8, "平台用户名": 10, "平台密码": 11}
|
||||
|
||||
# ==================== 3. 增员名单模板映射(generate_add 同源) ====================
|
||||
ADD_SHEET_KEY = "参保名单"
|
||||
ADD_TEMPLATE_FILE = "增员模版.xls"
|
||||
OUTPUT_DIR_NAME = {"新参保": "新参保-增员", "转移参保": "转移参保-增员"}
|
||||
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.未定职级',
|
||||
'技能等级': '无',
|
||||
'工种': '',
|
||||
'备注': '',
|
||||
}
|
||||
TPL_DATA_START_ROW = 4
|
||||
TPL_COLS_ADD = [
|
||||
'证件号码', '姓名', '民族', '首次参加工作日期', '月基本工资额', '工种', '个人身份',
|
||||
'户口性质', '联系电话', '文化程度', '养老保险参保时间', '失业保险参保时间',
|
||||
'医疗保险参保时间', '工伤保险参保时间', '生育保险参保时间', '证件类型', '国籍',
|
||||
'备注', '专职技能', '技能等级',
|
||||
]
|
||||
DATE_COLS_ADD = {
|
||||
'首次参加工作日期', '养老保险参保时间', '失业保险参保时间',
|
||||
'医疗保险参保时间', '工伤保险参保时间', '生育保险参保时间',
|
||||
}
|
||||
|
||||
# ==================== 4. 减员名单模板映射(generate_stop 同源) ====================
|
||||
STOP_SHEET_KEY = "停保名单"
|
||||
STOP_TEMPLATE_FILE = "减员模版.xls"
|
||||
STOP_OUTPUT_DIR_NAME = "停保-减员"
|
||||
GROUP_COL_STOP = "参保单位"
|
||||
COLUMN_MAP_STOP = {
|
||||
'个人编号': '社保编号',
|
||||
'证件号码': '身份证号码',
|
||||
'姓名': '停保人姓名',
|
||||
'单位社保号': '单位社保号',
|
||||
'单位名称': '参保单位',
|
||||
}
|
||||
DEFAULT_VALUES_STOP = {
|
||||
'减少原因': '在职人员主动解除劳动合同',
|
||||
'养老保险减少标志': '1 减少',
|
||||
'失业保险减少标志': '1 减少',
|
||||
'医疗保险减少标志': '1 减少',
|
||||
'工伤保险减少标志': '1 减少',
|
||||
'生育保险减少标志': '1 减少',
|
||||
'失业原因': '3 劳动者自愿辞职',
|
||||
}
|
||||
TPL_COLS_STOP = [
|
||||
'个人编号', '证件号码', '姓名', '减少时间', '减少原因',
|
||||
'养老保险减少标志', '失业保险减少标志', '医疗保险减少标志',
|
||||
'工伤保险减少标志', '生育保险减少标志', '失业原因',
|
||||
]
|
||||
DATE_COLS_STOP = {'减少时间'}
|
||||
|
||||
# ==================== 5. 增员办理 / 核查回盘配置(import_add/check_review 同源) ====================
|
||||
CHECK_STATUS = "待审核" # 核查范围:办理状态为该值的人员
|
||||
DONE_STATUS = "已办结" # 已申报查询里第一条的该状态才继续查看
|
||||
PASS_STATUS = "参保成功" # 审核通过 → 办理状态
|
||||
FAIL_STATUS = "参保失败" # 审核不通过(非系统错误)→ 办理状态
|
||||
ERR_400_KEYWORD = "status 400" # aae111 含该关键字 = 系统错误,需重新增员
|
||||
RUN_400_CLEAR = True # 400系统错误:运行结束后统一清空办理状态回待办
|
||||
REPLAY_PREFIX = "人员增减申请回盘表" # 回盘保存文件名:前缀_单位_日期.xlsx
|
||||
INS_STATUSES = ["养老参保状态", "失业参保状态", "医疗参保状态",
|
||||
"工伤参保状态", "生育参保状态"]
|
||||
INS_OK = "参保缴费"
|
||||
|
||||
# ==================== 6. 运行开关(由 fields 注入,不在文件内固化 limit/debug) ====================
|
||||
DEBUG_MODE = False
|
||||
|
||||
|
||||
def set_debug(on) -> None:
|
||||
global DEBUG_MODE
|
||||
DEBUG_MODE = bool(on)
|
||||
|
||||
|
||||
# ==================== 7. 日志钩子(print → ctx.log) ====================
|
||||
_log_fn = print
|
||||
|
||||
|
||||
def set_log(fn) -> None:
|
||||
"""插件 run() 启动时把 ctx.log 注入进来,全部模块经 log() 输出。"""
|
||||
global _log_fn
|
||||
_log_fn = fn if fn else print
|
||||
|
||||
|
||||
def log(msg: str) -> None:
|
||||
try:
|
||||
_log_fn(msg)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ==================== 8. 共享文本/文件辅助 ====================
|
||||
def _safe_name(value):
|
||||
"""单位名转安全文件名(与影刀版规则一致,保证产出文件名可复现)。"""
|
||||
if value is None or not str(value).strip():
|
||||
return "未知单位"
|
||||
try:
|
||||
if value != value: # NaN
|
||||
return "未知单位"
|
||||
except Exception:
|
||||
pass
|
||||
name = str(value).replace("/", "_").replace("\\", "_").replace(":", "_").strip()
|
||||
if name.endswith("店"):
|
||||
name = name[:-1]
|
||||
return name
|
||||
|
||||
|
||||
def _to_text(value):
|
||||
"""None/NaN → '',其余转去空白字符串(台账号/密码列用)。"""
|
||||
if value is None:
|
||||
return ""
|
||||
try:
|
||||
if value != value: # NaN
|
||||
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 ''
|
||||
if isinstance(value, float) and math.isnan(value):
|
||||
return ''
|
||||
return value
|
||||
|
||||
|
||||
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 临时文件 ~$)。"""
|
||||
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 名,其次按关键字/正则匹配;正则匹配时取年月最新。"""
|
||||
if hasattr(xl, "sheet_names"):
|
||||
names = [n.strip() for n in xl.sheet_names]
|
||||
else: # openpyxl workbook
|
||||
names = [n.strip() for n in xl.sheetnames]
|
||||
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:{names}")
|
||||
|
||||
|
||||
def check_not_locked(path):
|
||||
"""文件占用预检:被 Excel 独占打开时抛出友好错误,提示先关闭再运行。"""
|
||||
if not path or not os.path.isfile(path):
|
||||
return
|
||||
try:
|
||||
with open(path, "r+b"):
|
||||
pass
|
||||
except PermissionError:
|
||||
raise RuntimeError(f"文件被占用(请先关闭 Excel 再运行):{path}")
|
||||
@@ -0,0 +1,209 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Excel 读写层(sb_person_change 插件)。
|
||||
|
||||
- 模板生成:xlrd 读取 + xlutils 复制《增员模版.xls》/《减员模版.xls》,
|
||||
保留 Sheet2 下拉字典与数据有效性(generate_add/generate_stop 同源);
|
||||
- 源名单回写:JSON 缓存防崩溃,运行结束统一 openpyxl 回写一次
|
||||
(import_add/check_review 同源机制,缓存文件落在插件 debug/ 目录)。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
from datetime import datetime
|
||||
from glob import glob
|
||||
|
||||
import xlrd
|
||||
from xlutils.copy import copy as xl_copy
|
||||
|
||||
from . import config
|
||||
|
||||
|
||||
def _log(msg):
|
||||
config.log(msg)
|
||||
|
||||
|
||||
# ==================== 模板写入(增员/减员共用) ====================
|
||||
def write_template(template_file, output_path, unit_no, unit_name, records, tpl_cols, date_cols):
|
||||
"""复制模板写入 B1/D1 及第4行起数据,另存为 output_path。
|
||||
|
||||
- xlrd 读取(formatting_info 保留样式)+ xlutils.copy 复制,保留下拉字典;
|
||||
- B1=社保号(或单位社保号),D1=单位全称;数据从模板第4行起,按 tpl_cols 顺序写入;
|
||||
- 日期列以 yyyy/m/d 文本写入(不补零,如 2026/9/1);
|
||||
- 模板原数据区中未被覆盖的多余示例行清空。
|
||||
"""
|
||||
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 参保单位全称
|
||||
start = config.TPL_DATA_START_ROW - 1 # 0-based:模板第4行 → index 3
|
||||
for i, rec in enumerate(records):
|
||||
r = start + i
|
||||
for c, col in enumerate(tpl_cols):
|
||||
val = rec.get(col)
|
||||
if col in date_cols 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(start + len(records), orig_rows):
|
||||
for c in range(1, len(tpl_cols) + 1):
|
||||
ws.write(r, c, "")
|
||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||
wb.save(output_path)
|
||||
|
||||
|
||||
def find_template_file(name):
|
||||
"""定位模板(优先精确名,其次按 *<名>*.xls 匹配,取最新)。name 如「增员模版.xls」。"""
|
||||
exact = os.path.join(config.SOURCE_DIR, name)
|
||||
if os.path.isfile(exact):
|
||||
return exact
|
||||
keyword = name.rsplit(".", 1)[0]
|
||||
candidates = glob(os.path.join(config.SOURCE_DIR, f"*{keyword}*.xls"))
|
||||
if not candidates:
|
||||
raise FileNotFoundError(
|
||||
f"在 {config.SOURCE_DIR} 下未找到《{name}》,请先准备导入模板。")
|
||||
return max(candidates, key=os.path.getmtime)
|
||||
|
||||
|
||||
def get_output_dir_add(operation_type):
|
||||
"""增员输出目录(SOURCE_DIR/新参保-增员 或 转移参保-增员),不存在则自动创建。"""
|
||||
sub = config.OUTPUT_DIR_NAME.get(operation_type)
|
||||
if not sub:
|
||||
raise ValueError(f"未知参保类型:{operation_type}(可选:{'/'.join(config.OUTPUT_DIR_NAME)})")
|
||||
out_dir = os.path.join(config.SOURCE_DIR, sub)
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
return out_dir
|
||||
|
||||
|
||||
def get_output_dir_stop():
|
||||
"""减员输出目录(SOURCE_DIR/停保-减员),不存在则自动创建。"""
|
||||
out_dir = os.path.join(config.SOURCE_DIR, config.STOP_OUTPUT_DIR_NAME)
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
return out_dir
|
||||
|
||||
|
||||
# ==================== 源名单回写(JSON 缓存防崩溃 + 结束统一回写) ====================
|
||||
# 回写内容只追加进内存 + 写轻量 JSON 缓存(防中途崩溃丢失,不碰 Excel);
|
||||
# 运行结束时 flush_writeback 统一写 Excel 一次,保存成功校验后删除缓存;
|
||||
# 下次启动若发现残留缓存(上次崩溃)先恢复回写再办新单。
|
||||
_PENDING_STATUS, _PENDING_REMARK = {}, {}
|
||||
_SOURCE_FILE_USED, _SOURCE_SHEET_USED = None, None
|
||||
|
||||
|
||||
def set_writeback_target(source_file, sheet_name):
|
||||
"""登记本次使用的源名单(供回写与文件占用预检)。"""
|
||||
global _SOURCE_FILE_USED, _SOURCE_SHEET_USED
|
||||
_SOURCE_FILE_USED, _SOURCE_SHEET_USED = source_file, sheet_name
|
||||
|
||||
|
||||
def get_writeback_target():
|
||||
return _SOURCE_FILE_USED, _SOURCE_SHEET_USED
|
||||
|
||||
|
||||
def _save_ckpt():
|
||||
"""把累积的回写内容写 JSON 缓存(临时文件+替换,避免写一半损坏)。"""
|
||||
data = [{"id": cid, "status": _PENDING_STATUS.get(cid, ""),
|
||||
"remark": _PENDING_REMARK.get(cid, "")}
|
||||
for cid in dict.fromkeys(list(_PENDING_STATUS) + list(_PENDING_REMARK))]
|
||||
config.DEBUG_DIR.mkdir(parents=True, exist_ok=True)
|
||||
tmp = config.CKPT_FILE.with_suffix(".tmp")
|
||||
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
tmp.replace(config.CKPT_FILE)
|
||||
|
||||
|
||||
def load_ckpt():
|
||||
"""启动时恢复上次未回写的累积内容(崩溃恢复)。返回已回写人员的身份证号集合。"""
|
||||
recovered = set()
|
||||
if not config.CKPT_FILE.exists():
|
||||
return recovered
|
||||
try:
|
||||
for it in json.loads(config.CKPT_FILE.read_text(encoding="utf-8")):
|
||||
cid = it.get("id")
|
||||
if it.get("status"):
|
||||
_PENDING_STATUS[cid] = it["status"]
|
||||
if it.get("remark"):
|
||||
_PENDING_REMARK[cid] = it["remark"]
|
||||
if cid:
|
||||
recovered.add(cid)
|
||||
return recovered
|
||||
except Exception as e:
|
||||
_log(f" 恢复回写缓存失败:{e}")
|
||||
return recovered
|
||||
|
||||
|
||||
def writeback_source(status_map, remark_map):
|
||||
"""按身份证号码聚合回写内容(内存 + JSON 缓存,不碰 Excel):
|
||||
status_map {身份证: 办理状态};remark_map {身份证: 备注}。"""
|
||||
_PENDING_STATUS.update(status_map or {})
|
||||
_PENDING_REMARK.update(remark_map or {})
|
||||
try:
|
||||
_save_ckpt()
|
||||
except Exception as e:
|
||||
_log(f" 回写缓存写入失败(不影响办理,仅崩溃后需人工补状态):{e}")
|
||||
|
||||
|
||||
def flush_writeback():
|
||||
"""把累积的回写内容统一写回源名单 Excel(openpyxl 直改原文件),
|
||||
保存成功(校验)后删除 JSON 缓存。保存失败则缓存保留,下次启动自动恢复。"""
|
||||
if not (_PENDING_STATUS or _PENDING_REMARK):
|
||||
return
|
||||
if not _SOURCE_FILE_USED:
|
||||
raise RuntimeError("无源名单文件记录,无法回写")
|
||||
from openpyxl import load_workbook
|
||||
wb = load_workbook(_SOURCE_FILE_USED)
|
||||
ws = wb[_SOURCE_SHEET_USED]
|
||||
# 表头第3行定位列号
|
||||
hdr = {}
|
||||
for c in ws[3]:
|
||||
if c.value is not None:
|
||||
hdr[str(c.value).strip()] = c.column
|
||||
col_id = hdr.get('身份证号码')
|
||||
col_status = hdr.get('办理状态')
|
||||
col_remark = hdr.get('备注')
|
||||
if not col_id or not col_status:
|
||||
raise RuntimeError("源名单缺少身份证号码/办理状态列,无法回写")
|
||||
changed = 0
|
||||
pending_ids = set(_PENDING_STATUS) | set(_PENDING_REMARK)
|
||||
ref = [config._norm_id(x) for x in pending_ids]
|
||||
for row in ws.iter_rows(min_row=4):
|
||||
cid = config._norm_id(row[col_id - 1].value)
|
||||
if cid and config._id_hit(cid, ref):
|
||||
r = row[0].row
|
||||
if cid in _PENDING_STATUS:
|
||||
ws.cell(row=r, column=col_status, value=_PENDING_STATUS[cid])
|
||||
if cid in _PENDING_REMARK and col_remark:
|
||||
# 备注追加不覆盖:新备注换行追加在后面(已存在则不重复追加)
|
||||
cell = ws.cell(row=r, column=col_remark)
|
||||
old = str(cell.value or '').strip()
|
||||
new = str(_PENDING_REMARK[cid]).strip()
|
||||
if new not in old: # 重查场景:备注已写过则跳过防重复
|
||||
cell.value = f"{old}\n{new}" if old else new
|
||||
changed += 1
|
||||
try:
|
||||
wb.save(_SOURCE_FILE_USED)
|
||||
except PermissionError:
|
||||
# 缓存保留,下次启动自动恢复回写
|
||||
raise RuntimeError("源名单文件被占用(请关闭 Excel 后重跑),回写未保存")
|
||||
_PENDING_STATUS.clear()
|
||||
_PENDING_REMARK.clear()
|
||||
if config.CKPT_FILE.exists():
|
||||
config.CKPT_FILE.unlink()
|
||||
_log(f" 源名单回写完成:更新 {changed} 行 → {os.path.basename(_SOURCE_FILE_USED)}(缓存已清除)")
|
||||
_log(" 注意:openpyxl 保存会清掉公式缓存(如「区域」列 XLOOKUP),"
|
||||
"下次运行前请先用 Excel 打开并保存一次该名单以重算公式")
|
||||
|
||||
|
||||
# ==================== 调试截图 ====================
|
||||
def shot(tab, name):
|
||||
"""调试截图:仅 DEBUG_MODE 开启时保存页面截图并记录当前 URL。"""
|
||||
if not config.DEBUG_MODE:
|
||||
return
|
||||
try:
|
||||
shot_dir = config.DEBUG_DIR / "shots"
|
||||
shot_dir.mkdir(parents=True, exist_ok=True)
|
||||
ts = datetime.now().strftime("%H%M%S")
|
||||
tab.get_screenshot(path=str(shot_dir), name=f"{ts}_{name}.png")
|
||||
_log(f" [截图] {ts}_{name}.png url={str(tab.url)[:90]}")
|
||||
except Exception as e:
|
||||
_log(f" [截图失败] {name}: {e}")
|
||||
@@ -0,0 +1,513 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""重庆人社网上服务大厅(政务平台)法人登录模块(sb_person_change 插件)。
|
||||
|
||||
自 workflows/XQ0014 sb_login.py 迁移:
|
||||
- 每个参保单位一套账号(统一社会信用代码/用户名 + 密码),登录一次办一家的业务;
|
||||
- 不做 cookies 缓存(政务平台 cookies 极易失效),统一每次现场真登录;
|
||||
- SSO 完整流程 + ddddocr 识别图形验证码(验证码 5 次/轮 × 流程 3 轮)。
|
||||
|
||||
改造点:print → config.log;验证码调试落盘受 config.DEBUG_MODE 控制;
|
||||
去掉影刀 glv/main 入口。默认账号兜底读共享 .env(%LOCALAPPDATA%\37duAutomation\.env)。
|
||||
"""
|
||||
import base64
|
||||
import os
|
||||
import random
|
||||
import time
|
||||
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
from dotenv import load_dotenv
|
||||
|
||||
from . import config
|
||||
|
||||
# 默认账号只从共享 .env 读取,不内置明文;主流程按参保单位从台账取号传入,这里仅作兜底。
|
||||
if os.path.exists(os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation', '.env')):
|
||||
load_dotenv(os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation', '.env'))
|
||||
load_dotenv()
|
||||
|
||||
APPLY_URL = 'https://ggfw.rlsbj.cq.gov.cn/onlinehall/nethall/pc/cqzhrs/arrondi/ApplyOnline'
|
||||
SSO_KEYWORD = 'authcq.cqdcg.com:1443/sso/login'
|
||||
HOME_KEYWORD = 'ggfw.rlsbj.cq.gov.cn'
|
||||
WORK_KEYWORD = 'onlineoffice/index' # 登录成功后新开的工作台 tab
|
||||
|
||||
RETRY_MAX = 5 # 验证码最大重试次数(每轮)
|
||||
FLOW_RETRY = 3 # 整个登录流程最大轮数
|
||||
TIMEOUT = 10 # 元素等待超时(秒)
|
||||
HEADLESS = False
|
||||
HUMAN_DELAY = (0.4, 1.2) # 操作间随机延时区间(秒),模拟人工降低脚本特征
|
||||
|
||||
|
||||
def _recognize_captcha(img_bytes):
|
||||
"""ddddocr 识别图形验证码,返回文本。懒加载避免无关场景的导入开销。"""
|
||||
import ddddocr
|
||||
ocr = ddddocr.DdddOcr(show_ad=False)
|
||||
return ocr.classification(img_bytes).strip()
|
||||
|
||||
|
||||
def _dump_debug_captcha(img_bytes, text):
|
||||
"""可选:落盘验证码调试图片(仅 config.DEBUG_MODE 开启时),便于分析识别失败样本。"""
|
||||
if not config.DEBUG_MODE:
|
||||
return
|
||||
try:
|
||||
cfg_dir = config.DEBUG_DIR / "captcha"
|
||||
cfg_dir.mkdir(parents=True, exist_ok=True)
|
||||
path = cfg_dir / f"captcha_{int(time.time() * 1000)}_{text or 'unknown'}.png"
|
||||
with open(path, 'wb') as f:
|
||||
f.write(img_bytes)
|
||||
except Exception as e:
|
||||
config.log(f"保存调试图片失败:{e}")
|
||||
|
||||
|
||||
def _find_input(tab, selectors):
|
||||
"""按候选选择器顺序查找输入框。"""
|
||||
for sel in selectors:
|
||||
ele = tab.ele(sel, timeout=2)
|
||||
if ele:
|
||||
return ele
|
||||
return None
|
||||
|
||||
|
||||
def _find_captcha(tab):
|
||||
"""定位验证码图片 + 输入框。
|
||||
|
||||
从验证码输入框的容器往上找(DOM 结构:div.normalCode > span包input + img.code),
|
||||
避免命中页面其它 base64 图标(img[src^=data:image] 会抓到 icon)。
|
||||
"""
|
||||
code_input = tab.ele('css:input[placeholder*="图形验证码"]', timeout=TIMEOUT)
|
||||
img = None
|
||||
if code_input:
|
||||
holder = code_input.parent(2) # div.normalCode 容器
|
||||
if holder:
|
||||
img = holder.ele('tag:img', timeout=1)
|
||||
if img is None:
|
||||
# 兜底:激活面板内第一个 base64 图
|
||||
img = tab.ele('css:.ant-tabs-tabpane-active img[src^="data:image"]', timeout=2)
|
||||
return img, code_input
|
||||
|
||||
|
||||
def _read_img_bytes(img):
|
||||
"""验证码图转 bytes:优先直接解码 base64 src(像素无损、无 DPR 缩放),失败退回元素截图。"""
|
||||
try:
|
||||
src = img.attr('src') or ''
|
||||
if 'base64,' in src:
|
||||
return base64.b64decode(src.split('base64,', 1)[1])
|
||||
except Exception:
|
||||
pass
|
||||
return img.get_screenshot(as_bytes='png')
|
||||
|
||||
|
||||
# ================== 登录主流程 ==================
|
||||
def _human_pause(a=None, b=None):
|
||||
"""操作间随机延时,模拟人工节奏。"""
|
||||
lo, hi = HUMAN_DELAY if (a is None or b is None) else (a, b)
|
||||
time.sleep(random.uniform(lo, hi))
|
||||
|
||||
|
||||
def _dismiss_notice(page):
|
||||
"""关闭首页/工作台弹窗(「温馨提示」我知道了、授权提示同意等),避免遮挡操作。"""
|
||||
candidates = [
|
||||
'tag:button@@text()=我知道了',
|
||||
'tag:button@@text()=知道了',
|
||||
'tag:button@@text()=同意',
|
||||
'tag:button@@text()=确定',
|
||||
]
|
||||
for _ in range(3):
|
||||
btn = None
|
||||
for sel in candidates:
|
||||
try:
|
||||
btn = page.ele(sel, timeout=1)
|
||||
except Exception:
|
||||
btn = None
|
||||
if btn:
|
||||
break
|
||||
if not btn:
|
||||
return
|
||||
try:
|
||||
btn.click()
|
||||
config.log(f"已关闭弹窗(点击:{btn.text.strip()})")
|
||||
time.sleep(0.5)
|
||||
except Exception:
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def _sso_form_ready(t):
|
||||
"""判断某 tab 是否已是渲染完成的 SSO 登录页:URL 在 SSO 且「法人用户」tab 已出现。
|
||||
注意用 text()= 精确匹配——text(): 模糊匹配会命中包含该文字的外层容器 div(如 #user-sso-pc)。"""
|
||||
try:
|
||||
if SSO_KEYWORD not in t.url:
|
||||
return False
|
||||
return bool(t.ele('tag:div@@text()=法人用户', timeout=0.5))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _is_work_tab(t):
|
||||
"""是否登录完成的工作台页(onlineoffice/index)。
|
||||
必须 origin 前缀匹配 + 路径含 onlineoffice/index——跳转链中间页(zwykb 授权页、
|
||||
ggfw 回调页)的 redirectUrl 查询参数里也含 ggfw/onlinehall 字样,用包含匹配会误判。"""
|
||||
try:
|
||||
u = (t.url or '').strip()
|
||||
except Exception:
|
||||
return False
|
||||
return u.startswith('https://' + HOME_KEYWORD) and WORK_KEYWORD in u
|
||||
|
||||
|
||||
def _open_sso_tab(page):
|
||||
"""点击首页「登录」,等待新 tab 打开、跳转链结束且登录表单渲染完成后返回。
|
||||
返回 (tab, already_logged):
|
||||
already_logged=False → SSO 登录页(需填表)
|
||||
already_logged=True → SSO 会话有效直接跳回大厅(登录成功,无需填表)"""
|
||||
_dismiss_notice(page)
|
||||
# 登录入口:loginBox 内的第一个 <a>(「登录」,无 href)
|
||||
login_link = page.ele('css:[class*="loginBox"] a', timeout=TIMEOUT)
|
||||
if not login_link:
|
||||
login_link = page.ele('tag:a@@text():登录', timeout=TIMEOUT)
|
||||
if not login_link:
|
||||
# 可能残留上一账号登录态(首页已免登录):清除 cookies 后刷新重试一次
|
||||
config.log("未找到登录入口(可能残留上一账号登录态),清除 cookies 后重试")
|
||||
try:
|
||||
page.clear_cache(cookies=True)
|
||||
except Exception:
|
||||
try:
|
||||
page.run_js("document.cookie.split(';').forEach(c=>{"
|
||||
"document.cookie=c.trim().split('=')[0]+"
|
||||
"'=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/'});")
|
||||
except Exception:
|
||||
pass
|
||||
page.get(APPLY_URL)
|
||||
time.sleep(2)
|
||||
login_link = page.ele('css:[class*="loginBox"] a', timeout=TIMEOUT) \
|
||||
or page.ele('tag:a@@text():登录', timeout=TIMEOUT)
|
||||
if not login_link:
|
||||
# 首页已是登录态(无登录入口):提示需清登录态,由调用方处理
|
||||
config.log("找不到登录入口(首页可能已是登录态)")
|
||||
return None, False
|
||||
before_ids = set(page.tab_ids)
|
||||
login_link.click()
|
||||
# 点击「登录」后是中转跳转链:轮询所有新开 tab,直到某个 tab 的 URL 稳定停在
|
||||
# SSO 且「法人用户」登录表单真实渲染出来(避免拿到闪现中的中转页就操作);
|
||||
# 若 SSO 会话仍有效(同账号二次登录),新 tab 会直接跳回大厅页 → 视为已登录
|
||||
tab = None
|
||||
for _ in range(90): # 最多等 45 秒
|
||||
time.sleep(0.5)
|
||||
for tid in [i for i in page.tab_ids if i not in before_ids]:
|
||||
try:
|
||||
t = page.get_tab(tid)
|
||||
except Exception:
|
||||
continue
|
||||
if _is_work_tab(t):
|
||||
config.log(f"SSO 会话有效,已直接登录:{t.url}")
|
||||
_close_extra_tabs(page, before_ids, t)
|
||||
_dismiss_notice(t)
|
||||
return t, True
|
||||
if _sso_form_ready(t):
|
||||
tab = t
|
||||
break
|
||||
if tab:
|
||||
break
|
||||
if tab is None:
|
||||
# 部分场景可能不新开 tab 而是当前页跳转
|
||||
if _sso_form_ready(page):
|
||||
return page, False
|
||||
config.log("点击登录后未检测到就绪的 SSO 登录页")
|
||||
return None, False
|
||||
_close_extra_tabs(page, before_ids, tab)
|
||||
return tab, False
|
||||
|
||||
|
||||
def _close_extra_tabs(page, before_ids, keep_tab):
|
||||
"""关掉一次「点登录」产生的多余新开 tab(中转页等),保持会话干净。"""
|
||||
for tid in [i for i in page.tab_ids if i not in before_ids and i != keep_tab.tab_id]:
|
||||
try:
|
||||
page.get_tab(tid).close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _wait_sso_ready(tab):
|
||||
"""等 SSO 登录页彻底稳定(URL 不再跳变 + 表单已渲染),再开始操作,
|
||||
避免跳转/React 重渲染过程中拿到元素随即失效(元素对象已失效)。"""
|
||||
last_url = None
|
||||
for _ in range(60): # 最多等 30 秒
|
||||
try:
|
||||
url = tab.url
|
||||
except Exception:
|
||||
return False
|
||||
stable = (url == last_url)
|
||||
last_url = url
|
||||
if _sso_form_ready(tab) and stable:
|
||||
break
|
||||
time.sleep(0.5)
|
||||
time.sleep(1.5) # 再缓冲,确保 React 渲染完成
|
||||
return True
|
||||
|
||||
|
||||
def _try_login_once(tab, page, username, password, retry_index):
|
||||
"""在 SSO tab 内完成一次填表 + 验证码 + 提交。返回 True 表示登录成功。
|
||||
所有动作间加随机延时,模拟人工节奏,降低脚本特征。"""
|
||||
_wait_sso_ready(tab)
|
||||
# 法人用户 tab:精确文本匹配(text(): 模糊会命中包含文字的外层容器,如 #user-sso-pc)
|
||||
legal_tab = tab.ele('tag:div@@text()=法人用户', timeout=TIMEOUT)
|
||||
if legal_tab:
|
||||
legal_tab.click()
|
||||
_human_pause(0.3, 0.8)
|
||||
# 校验确实切到法人用户面板(没点上会把账号填进个人用户表单)
|
||||
for _ in range(3):
|
||||
active = tab.ele('css:.ant-tabs-tab-active .ant-tabs-tab-btn', timeout=2)
|
||||
if active and active.text.strip() == '法人用户':
|
||||
break
|
||||
if legal_tab:
|
||||
try:
|
||||
legal_tab.click()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
|
||||
# 账号(统一社会信用代码)+ 密码
|
||||
# SSO 法人用户表单真实结构(2026-09 探针实测):
|
||||
# 账号框 id=identifier placeholder「请输入统一社会信用代码」
|
||||
user_input = _find_input(tab, [
|
||||
'css:input[placeholder*="统一社会信用代码"]',
|
||||
'css:input[placeholder*="社会信用代码"]',
|
||||
'css:#identifier',
|
||||
])
|
||||
if not user_input:
|
||||
config.log("找不到账号输入框")
|
||||
return False
|
||||
user_input.clear()
|
||||
user_input.input(username)
|
||||
_human_pause()
|
||||
|
||||
pwd_input = _find_input(tab, ['css:#password', 'css:input[type="password"]'])
|
||||
if not pwd_input:
|
||||
config.log("找不到密码输入框")
|
||||
return False
|
||||
pwd_input.clear()
|
||||
pwd_input.input(password)
|
||||
_human_pause()
|
||||
|
||||
# 图形验证码:base64 内嵌图(从验证码输入框容器定位,避免抓到页面其它图标)
|
||||
for attempt in range(RETRY_MAX):
|
||||
config.log(f"--- 第 {retry_index}-{attempt + 1} 次验证码识别 ---")
|
||||
img, code_input = _find_captcha(tab)
|
||||
if not img or not code_input:
|
||||
config.log("找不到验证码图片或输入框")
|
||||
return False
|
||||
img_bytes = _read_img_bytes(img)
|
||||
if not img_bytes:
|
||||
config.log("验证码图数据为空")
|
||||
time.sleep(1)
|
||||
continue
|
||||
try:
|
||||
code = _recognize_captcha(img_bytes)
|
||||
except Exception as e:
|
||||
config.log(f"ddddocr 识别异常:{e}")
|
||||
return False
|
||||
config.log(f" 识别结果:{code!r}")
|
||||
if not code:
|
||||
_refresh_captcha(tab, img)
|
||||
continue
|
||||
code = code.upper() # 页面显示为大写,按大写提交
|
||||
_dump_debug_captcha(img_bytes, code)
|
||||
code_input.clear()
|
||||
code_input.input(code)
|
||||
_human_pause(0.3, 0.9)
|
||||
|
||||
# 提交:登录按钮(button[type=submit],文案「登 录」)
|
||||
btn = tab.ele('css:button[type="submit"]', timeout=TIMEOUT) \
|
||||
or tab.ele('tag:button@@text():登录', timeout=TIMEOUT)
|
||||
if not btn:
|
||||
config.log("找不到登录提交按钮")
|
||||
return False
|
||||
_human_pause(0.2, 0.6) # 点提交前再停顿一下
|
||||
btn.click()
|
||||
|
||||
# 等待结果:SSO tab 跳回大厅 / 新开 onlineoffice 工作台 tab = 成功;错误提示 = 刷新重试
|
||||
ok, work_tab = _wait_login_result(tab, page)
|
||||
if ok:
|
||||
_try_login_once.work_tab = work_tab # 供 _do_login 保存会话
|
||||
return True
|
||||
_refresh_captcha(tab, img)
|
||||
return False
|
||||
|
||||
|
||||
def _wait_login_result(tab, page):
|
||||
"""提交后轮询判定登录结果。返回 (ok, work_tab)。"""
|
||||
before_ids = set(page.tab_ids)
|
||||
for _ in range(30): # 最多等 15 秒
|
||||
time.sleep(0.5)
|
||||
# 成功标志 1:登录后新开的 onlineoffice 工作台 tab
|
||||
for tid in [i for i in page.tab_ids if i not in before_ids]:
|
||||
try:
|
||||
t = page.get_tab(tid)
|
||||
except Exception:
|
||||
continue
|
||||
if _is_work_tab(t):
|
||||
config.log(f"登录成功(新开工作台 tab):{t.url}")
|
||||
_close_extra_tabs(page, before_ids, t)
|
||||
_dismiss_notice(t) # 工作台可能闪现授权/提示弹窗
|
||||
return True, t
|
||||
# 成功标志 2:SSO tab 自身跳到工作台页(origin 前缀匹配,防 redirectUrl 参数误判)
|
||||
try:
|
||||
url = (tab.url or '').strip()
|
||||
except Exception:
|
||||
url = ''
|
||||
if url.startswith('https://' + HOME_KEYWORD) and SSO_KEYWORD not in url and WORK_KEYWORD in url:
|
||||
config.log(f"登录成功,已跳转:{url}")
|
||||
_dismiss_notice(tab)
|
||||
return True, tab
|
||||
# ant-message 错误提示(验证码错误/账号密码错误等)
|
||||
try:
|
||||
err = tab.ele('css:.ant-message-error', timeout=0.5)
|
||||
if err:
|
||||
config.log(f"登录失败提示:{err.text}")
|
||||
return False, None
|
||||
except Exception:
|
||||
pass
|
||||
config.log("等待登录结果超时")
|
||||
return False, None
|
||||
|
||||
|
||||
def _refresh_captcha(tab, img):
|
||||
"""点击验证码图片刷新,校验 base64 src 是否真的变化(连续点 2 次)。"""
|
||||
try:
|
||||
old = img.attr('src') or ''
|
||||
except Exception:
|
||||
old = ''
|
||||
for _ in range(2):
|
||||
try:
|
||||
img.click()
|
||||
except Exception:
|
||||
try:
|
||||
img.click(by_js=True)
|
||||
except Exception:
|
||||
pass
|
||||
# 刷新是异步的:轮询 src 变化(最多 3 秒)
|
||||
for _p in range(10):
|
||||
time.sleep(0.3)
|
||||
try:
|
||||
new = img.attr('src') or ''
|
||||
except Exception:
|
||||
new = old
|
||||
if new and new != old:
|
||||
return True
|
||||
# src 还没变,再点一次
|
||||
config.log("警告:验证码图片刷新后未变化")
|
||||
return False
|
||||
|
||||
|
||||
LAST_SESSION = {'page': None, 'tab': None} # 登录成功后保留的浏览器会话(供后续网页操作使用)
|
||||
|
||||
|
||||
def _teardown(page):
|
||||
"""清 cookies/本地存储后关浏览器(账号切换彻底隔离,避免残留登录态)。"""
|
||||
if page is None:
|
||||
return
|
||||
try:
|
||||
page.clear_cache(cookies=True, local_storage=True, session_storage=True)
|
||||
except Exception:
|
||||
try:
|
||||
page.clear_cache()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def close_session():
|
||||
"""清 cookies 并关闭当前保留的登录会话(每个账号业务办完后必须调用)。"""
|
||||
_teardown(LAST_SESSION['page'])
|
||||
LAST_SESSION['page'] = None
|
||||
LAST_SESSION['tab'] = None
|
||||
|
||||
|
||||
def _do_login(username, password):
|
||||
"""打开浏览器现场完成登录(含图形验证码)。不做任何 cookies 缓存。
|
||||
成功保留浏览器会话(工作台 tab 供后续导入操作),失败关闭浏览器。
|
||||
返回 (ok, work_tab)。"""
|
||||
# 账号切换隔离:先关掉上一账号的浏览器会话(auto_port 临时目录本就不互通,双保险)
|
||||
close_session()
|
||||
co = ChromiumOptions()
|
||||
if HEADLESS:
|
||||
co.headless()
|
||||
# auto_port:每次启动独立端口+独立临时用户目录,账号间 cookies 天然隔离
|
||||
co.auto_port(True)
|
||||
co.set_argument('--start-maximized') # 浏览器启动即全屏(最大化),避免小窗口下元素被折叠/遮挡
|
||||
page = ChromiumPage(co)
|
||||
work_tab_holder = {'tab': None}
|
||||
|
||||
def _finish(ok):
|
||||
if ok:
|
||||
LAST_SESSION['page'] = page
|
||||
LAST_SESSION['tab'] = work_tab_holder['tab']
|
||||
return True, work_tab_holder['tab']
|
||||
_teardown(page)
|
||||
return False, None
|
||||
|
||||
try:
|
||||
page.get(APPLY_URL)
|
||||
_human_pause(1.0, 2.5)
|
||||
|
||||
tab = None
|
||||
for retry in range(FLOW_RETRY):
|
||||
try:
|
||||
_dismiss_notice(page)
|
||||
# 登录 tab 跨轮次复用:只在丢失/失效时才重新点「登录」,
|
||||
# 避免每轮重开浏览器 tab 越积越多(手动只点一次,代码不能反复点)
|
||||
if tab is not None:
|
||||
try:
|
||||
if SSO_KEYWORD not in tab.url:
|
||||
tab = None # 已跳走(登录成功或会话变化),需重新进入
|
||||
except Exception:
|
||||
tab = None # tab 已关闭/失效
|
||||
if tab is None:
|
||||
tab, already = _open_sso_tab(page)
|
||||
if tab is None:
|
||||
config.log(f"进入 SSO 登录页失败(第 {retry + 1}/{FLOW_RETRY} 轮)")
|
||||
time.sleep(2)
|
||||
continue
|
||||
if already:
|
||||
# 同账号 SSO 会话仍有效:免验证码直接登录成功
|
||||
work_tab_holder['tab'] = tab
|
||||
return _finish(True)
|
||||
if _try_login_once(tab, page, username, password, retry + 1):
|
||||
work_tab_holder['tab'] = getattr(_try_login_once, 'work_tab', None) or tab
|
||||
return _finish(True)
|
||||
# 登录失败:复用同一 tab 刷新重来,不再重复点「登录」
|
||||
try:
|
||||
tab.refresh()
|
||||
time.sleep(2)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
# 元素失效/页面刷新等异常:不中断整体流程,进入下一轮
|
||||
config.log(f"第 {retry + 1}/{FLOW_RETRY} 轮流程异常(将重试):{e}")
|
||||
time.sleep(1)
|
||||
config.log("登录失败(验证码识别未通过或流程异常)")
|
||||
return _finish(False)
|
||||
except Exception:
|
||||
# 整体异常也要保证清理(失败场景不留会话)
|
||||
_teardown(page)
|
||||
raise
|
||||
|
||||
|
||||
def ensure_login(username=None, password=None):
|
||||
"""以指定账号现场登录政务平台(无缓存,每次真登录)。
|
||||
返回 dict:{success, username, message}"""
|
||||
# 未传账号时回落到 .env 默认账号(兜底场景)
|
||||
username = (username or os.getenv('sb_login_username', '') or '').strip()
|
||||
password = (password or os.getenv('sb_login_password', '') or '').strip()
|
||||
if not (username and password):
|
||||
return {"success": False, "username": username,
|
||||
"message": "登录账号/密码缺失(台账未取到且 .env 未配置 sb_login_username / sb_login_password)"}
|
||||
|
||||
ok, _work_tab = _do_login(username, password)
|
||||
if ok:
|
||||
return {"success": True, "username": username, "message": "登录成功"}
|
||||
return {"success": False, "username": username,
|
||||
"message": "登录失败(验证码识别未通过或流程异常)"}
|
||||
@@ -0,0 +1,7 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""中心机插件包入口 shim(zip 包根必含 main.py)。
|
||||
|
||||
包以目录形式安装到 plugins/<id>/(webhost 宿主按账号权限自下载解压处)时由包扫描加载 __init__.py;
|
||||
以 zip 分发/存储时中心机校验要求包根含 main.py。导入本模块即触发插件注册。
|
||||
"""
|
||||
from . import SbPersonChangePlugin, PLUGINS # noqa: F401
|
||||
@@ -0,0 +1,218 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""核查回盘模式(sb_person_change 插件)。
|
||||
|
||||
自 workflows/XQ0014 check_review.py 主流程迁移:恢复缓存 → 读待审核名单 → 取号 →
|
||||
预检 → 逐单位登录核查审核结论 + 回盘打印下载核对 → 400系统错误统一清状态 → 统一回写。
|
||||
print → config.log。
|
||||
"""
|
||||
from . import config
|
||||
from . import excelio
|
||||
from . import login
|
||||
from . import source
|
||||
from . import webops
|
||||
|
||||
|
||||
def _log(msg):
|
||||
config.log(msg)
|
||||
|
||||
|
||||
def build_writeback(results, task_cids, unit_name):
|
||||
"""按回写规则处理明细,返回 (status_map, remark_map, redo400_list, log_lines)。
|
||||
只处理本单位「待审核」人员(证件号码精确匹配),其余仅记录日志。
|
||||
400系统错误不立即清状态:先记录,运行结束后统一清空办理状态回待办再新增。"""
|
||||
status_map, remark_map, redo400, logs = {}, {}, [], []
|
||||
for r in results:
|
||||
if not r['cid'] or r['cid'] not in task_cids:
|
||||
continue
|
||||
concl, opinion = r['conclusion'], r['opinion']
|
||||
line = f" {r['name']}({r['cid']}):{concl}"
|
||||
if concl == '审核通过':
|
||||
status_map[r['cid']] = config.PASS_STATUS
|
||||
line += f" → 办理状态={config.PASS_STATUS}"
|
||||
elif concl == '不通过':
|
||||
if config.ERR_400_KEYWORD in opinion:
|
||||
# 系统错误:仅记录,运行结束后统一清空办理状态回待办重新增员
|
||||
if config.RUN_400_CLEAR:
|
||||
redo400.append({"cid": r['cid'], "name": r['name'], "unit": unit_name})
|
||||
line += " → 400系统错误,已记录(结束后统一清状态回待办重新增员)"
|
||||
else:
|
||||
status_map[r['cid']] = config.FAIL_STATUS
|
||||
remark_map[r['cid']] = opinion or '审核不通过'
|
||||
line += f" → 办理状态={config.FAIL_STATUS},备注追加:{opinion[:60]}"
|
||||
else:
|
||||
line += " → 非终态结论,跳过"
|
||||
logs.append(line)
|
||||
return status_map, remark_map, redo400, logs
|
||||
|
||||
|
||||
def do_unit_check(task):
|
||||
"""登录后的完整核查流程。返回结果 dict(JSON 安全)。"""
|
||||
page = login.LAST_SESSION.get('page')
|
||||
work_tab = login.LAST_SESSION.get('tab')
|
||||
if page is None or work_tab is None:
|
||||
return {"success": False, "message": "无有效登录会话"}
|
||||
|
||||
res = {"success": False, "checked": 0, "passed": 0, "failed": 0,
|
||||
"redo400": [], "skipped": False}
|
||||
try:
|
||||
excelfio.shot(work_tab, "c1_workbench")
|
||||
biz_tab = webops.open_business_page(page, work_tab)
|
||||
webops._dismiss_popups(biz_tab)
|
||||
# 关键:必须等单位信息接口(getAab001)返回本单位,否则后续查询全部拿不到数据
|
||||
unit_info = webops.wait_unit_loaded(biz_tab, task['unit'])
|
||||
if unit_info is None:
|
||||
# 页面没加载出单位:重开一次业务页再等
|
||||
_log(" 单位信息未加载,重开业务页重试...")
|
||||
biz_tab = webops.open_business_page(page, work_tab)
|
||||
webops._dismiss_popups(biz_tab)
|
||||
unit_info = webops.wait_unit_loaded(biz_tab, task['unit'])
|
||||
if unit_info is None:
|
||||
res.update(success=True, skipped=True,
|
||||
message="单位信息未加载(getAab001无数据),跳过")
|
||||
return res
|
||||
unit_full = str(unit_info.get('aab004') or '').strip() # 平台单位全称,用于回盘命名
|
||||
fail_cids = set() # 审核不通过(参保失败)人员:平台无回盘记录,回盘阶段跳过其未查询备注
|
||||
excelfio.shot(biz_tab, "c2_biz_page")
|
||||
|
||||
table = webops.open_query_menu(biz_tab)
|
||||
excelfio.shot(biz_tab, "c3_query_list")
|
||||
status, view = webops.read_first_row(table)
|
||||
if not status:
|
||||
res.update(success=True, skipped=True, message="已申报查询无记录,跳过")
|
||||
elif status != config.DONE_STATUS:
|
||||
res.update(success=True, skipped=True,
|
||||
message=f"第一条状态「{status}」非{config.DONE_STATUS},跳过")
|
||||
else:
|
||||
_log(f" 第一条状态:{status},点击查看读取审核结论")
|
||||
url = webops._capture_query_url(page, biz_tab, view)
|
||||
results, detail_full = webops.replay_query_all(biz_tab, url)
|
||||
unit_full = unit_full or detail_full
|
||||
excelfio.shot(biz_tab, "c4_detail_fetched")
|
||||
if not results:
|
||||
res.update(success=True, message="明细接口返回 0 条,跳过")
|
||||
else:
|
||||
status_map, remark_map, redo400, logs = build_writeback(
|
||||
results, task['cids'], task['unit'])
|
||||
fail_cids = {cid for cid, st in status_map.items() if st == config.FAIL_STATUS}
|
||||
for line in logs:
|
||||
_log(line)
|
||||
if status_map or remark_map:
|
||||
excelfio.writeback_source(status_map, remark_map)
|
||||
n_match = len([r for r in results if r['cid'] in task['cids']])
|
||||
n_pass = len([v for v in status_map.values() if v == config.PASS_STATUS])
|
||||
n_fail = len([v for v in status_map.values() if v == config.FAIL_STATUS])
|
||||
res.update(
|
||||
success=True,
|
||||
checked=n_match,
|
||||
passed=n_pass,
|
||||
failed=n_fail,
|
||||
redo400=redo400,
|
||||
message=(f"核查{n_match}条,通过{n_pass} 失败{n_fail} "
|
||||
f"400系统错误{len(redo400)}(结束后统一清状态)"))
|
||||
|
||||
# 回盘打印:每个账号核查完都要下载回盘记录并核对参保状态(无论是否已办结)
|
||||
try:
|
||||
webops.do_huipan(page, biz_tab, task, res, unit_full, fail_cids)
|
||||
except Exception as e:
|
||||
res["huipan"] = f"回盘打印失败:{e}"
|
||||
_log(f" 回盘打印失败:{e}")
|
||||
return res
|
||||
except Exception as e:
|
||||
res["message"] = f"核查异常:{e}"
|
||||
return res
|
||||
|
||||
|
||||
def process_units(tasks, accounts, ctx):
|
||||
"""逐参保单位:登录 → 已申报查询核查 → 回写。每账号办完清 cookies 关浏览器。"""
|
||||
results = []
|
||||
n = len(tasks)
|
||||
for i, task in enumerate(tasks, 1):
|
||||
_log(f"\n========== [{i}/{n}] {task['unit']}({task['count']}人待审核)==========")
|
||||
ctx.progress(20 + int(70 * (i - 1) / max(n, 1)))
|
||||
acc = accounts.get(task['unit'])
|
||||
try:
|
||||
login_res = login.ensure_login(acc["username"], acc["password"])
|
||||
except Exception as e:
|
||||
login_res = {"success": False, "message": f"登录调用异常:{e}"}
|
||||
_log(f"登录结果:{login_res.get('message')}")
|
||||
try:
|
||||
if login_res.get("success"):
|
||||
web_res = do_unit_check(task)
|
||||
_log(f"核查结果:{web_res.get('message')}")
|
||||
results.append({**task, **web_res})
|
||||
else:
|
||||
results.append({**task, "success": False, "message": login_res.get("message", "")})
|
||||
finally:
|
||||
login.close_session()
|
||||
return results
|
||||
|
||||
|
||||
def run(ctx, limit=0):
|
||||
"""主流程:恢复缓存 → 读待审核名单 → 取号 → 预检 → 逐单位登录核查 → 统一回写。"""
|
||||
ctx.progress(5)
|
||||
recovered_ids = excelfio.load_ckpt()
|
||||
tasks = source.load_check_tasks(exclude_ids=recovered_ids)
|
||||
if recovered_ids:
|
||||
_log("\n检测到上次未回写的内容,先统一回写:")
|
||||
try:
|
||||
excelfio.flush_writeback()
|
||||
except Exception as e:
|
||||
_log(f"恢复回写失败(缓存保留,下次启动重试):{e}")
|
||||
if not tasks:
|
||||
ctx.progress(100)
|
||||
return {"summary": "无待核查数据", "rows": [], "notes": []}
|
||||
|
||||
ctx.progress(15)
|
||||
# 文件占用预检:源名单被 Excel 打开会卡回写,提前报错
|
||||
source_file, _ = excelfio.get_writeback_target()
|
||||
config.check_not_locked(source_file)
|
||||
|
||||
accounts = source.load_accounts([t['unit'] for t in tasks])
|
||||
# 预检:账号齐备才继续(与增员一致的严格预检)
|
||||
errors = []
|
||||
for t in tasks:
|
||||
acc = accounts.get(t['unit'])
|
||||
if acc is None:
|
||||
errors.append(f"[{t['unit']}] 台账未匹配")
|
||||
elif not acc['username'] or not acc['password']:
|
||||
errors.append(f"[{t['unit']}] 账号或密码缺失")
|
||||
if errors:
|
||||
_log("\n预检未通过:")
|
||||
for e in errors:
|
||||
_log(f" - {e}")
|
||||
raise RuntimeError("预检未通过,详见日志(台账未匹配/账号密码缺失),修正后重跑")
|
||||
|
||||
todo = tasks[:limit] if limit > 0 else tasks
|
||||
if limit > 0:
|
||||
_log(f"分批运行:本次仅核查前 {limit} 个单位")
|
||||
ctx.progress(20)
|
||||
results = process_units(todo, accounts, ctx)
|
||||
ctx.progress(92)
|
||||
# 400系统错误:核查时只记录,全部单位核查完后统一清空办理状态回待办(重新走名单制作+增员)
|
||||
redo_all = [p for r in results for p in (r.get("redo400") or [])]
|
||||
notes = []
|
||||
if redo_all:
|
||||
excelfio.writeback_source({p['cid']: "" for p in redo_all}, {})
|
||||
_log(f"\n400系统错误共 {len(redo_all)} 人,已统一清空办理状态回待办,"
|
||||
f"请重新执行名单制作后增员:")
|
||||
for p in redo_all:
|
||||
_log(f" - {p['name']}({p['cid']}){p['unit']}")
|
||||
notes.append(f"400系统错误:{p['name']}({p['cid']}){p['unit']} 已清状态回待办")
|
||||
try:
|
||||
excelfio.flush_writeback()
|
||||
except Exception as e:
|
||||
_log(f"回写失败:{e}")
|
||||
ok = [r for r in results if r["success"]]
|
||||
fail = [r for r in results if not r["success"]]
|
||||
skip = [r for r in ok if r.get("skipped")]
|
||||
_log(f"\n========== 汇总 ==========")
|
||||
_log(f"核查完成 {len(ok) - len(skip)} 家,跳过(未办结/无记录){len(skip)} 家,失败 {len(fail)} 家")
|
||||
for r in fail:
|
||||
_log(f" ✗ {r['unit']}:{r.get('message', '')}")
|
||||
notes.append(f"{r['unit']}:{r.get('message', '')}")
|
||||
ctx.progress(100)
|
||||
return {"summary": f"核查回盘 完成{len(ok) - len(skip)}/跳过{len(skip)}/失败{len(fail)}",
|
||||
"rows": [{k: r.get(k) for k in ('unit', 'count', 'checked', 'passed', 'failed',
|
||||
'huipan', 'message')}
|
||||
for r in results],
|
||||
"notes": notes}
|
||||
@@ -0,0 +1,187 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""增员办理模式(sb_person_change 插件)。
|
||||
|
||||
自 workflows/XQ0014 import_add.py 主流程迁移:恢复缓存 → 读名单(排除已回写人员)
|
||||
→ 取号 → 预检 → 逐单位登录政务平台导入申报 → 统一回写。print → config.log。
|
||||
"""
|
||||
from . import config
|
||||
from . import excelio
|
||||
from . import login
|
||||
from . import source
|
||||
from . import webops
|
||||
|
||||
|
||||
def _log(msg):
|
||||
config.log(msg)
|
||||
|
||||
|
||||
def precheck(units, accounts):
|
||||
"""预检:核对每个单位的导入文件与账号。返回待办列表 [{unit, count, file, username, password}]。"""
|
||||
import os
|
||||
import_dir = os.path.join(config.SOURCE_DIR, config.IMPORT_DIR_NAME)
|
||||
tasks, errors = [], []
|
||||
_log("\n========== 预检 ==========")
|
||||
for unit, count in units:
|
||||
file_path = os.path.join(import_dir, f"{config._safe_name(unit)}增员导入名单.xls")
|
||||
acc = accounts.get(unit)
|
||||
problems = []
|
||||
if not os.path.isfile(file_path):
|
||||
problems.append(f"缺导入文件({config.IMPORT_DIR_NAME}\\{os.path.basename(file_path)})")
|
||||
if acc is None:
|
||||
problems.append("台账未匹配(检查户头名/城市=重庆/是否在用=是)")
|
||||
else:
|
||||
if not acc["username"]:
|
||||
problems.append("账号缺失(信用代码与平台用户名均为空)")
|
||||
if not acc["password"]:
|
||||
problems.append("密码缺失(平台密码为空)")
|
||||
if problems:
|
||||
errors.append(f"[{unit}] " + ";".join(problems))
|
||||
_log(f" ✗ {unit}({count}人):{';'.join(problems)}")
|
||||
else:
|
||||
tasks.append({"unit": unit, "count": count, "file": file_path,
|
||||
"username": acc["username"], "password": acc["password"]})
|
||||
_log(f" ✓ {unit}({count}人)账号={acc['username']}"
|
||||
f"({acc['username_src']})文件={os.path.basename(file_path)}")
|
||||
if errors:
|
||||
_log(f"\n预检未通过,共 {len(errors)} 个问题,请先修正后重跑:")
|
||||
for e in errors:
|
||||
_log(f" - {e}")
|
||||
return None
|
||||
_log(f"预检通过:{len(tasks)} 个单位待办理\n")
|
||||
return tasks
|
||||
|
||||
|
||||
def do_web_import(task):
|
||||
"""登录后的完整业务流程:进业务页 → 上传导入 → 校验回写 → 预申报提交 → 查询回写。
|
||||
返回结果 dict(JSON 安全)。"""
|
||||
page = login.LAST_SESSION.get('page')
|
||||
work_tab = 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:
|
||||
excelfio.shot(work_tab, "01_workbench")
|
||||
biz_tab = webops.open_business_page(page, work_tab)
|
||||
excelfio.shot(biz_tab, "02_biz_upload_page")
|
||||
|
||||
# 1) 上传导入
|
||||
total, _failed_cnt = webops.upload_import(biz_tab, task['file'])
|
||||
res['imported'] = total
|
||||
|
||||
# 2) 校验未通过:回写 参保失败 + 备注(详细信息)
|
||||
# 平账规则:弹窗「成功N人」+「校验未通过人员」= 名单人数,不平账中止防止漏人导致下次重复申报
|
||||
fail_rows = webops.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:
|
||||
excelfio.writeback_source({cid: "参保失败" for cid, _ in fail_rows},
|
||||
{cid: d for cid, d in fail_rows})
|
||||
passed = total
|
||||
|
||||
# 3) 全员未通过 → 跳过申报
|
||||
if passed <= 0:
|
||||
_log(" 校验通过人数为 0,跳过申报")
|
||||
res.update(success=True, message=f"导入{total}人,全部校验未通过,已回写未申报")
|
||||
return res
|
||||
|
||||
# 4) 预申报 → 正式提交 → 查询审核结论回写
|
||||
webops.predeclare_and_submit(page, biz_tab)
|
||||
review = webops.query_review_results(page, biz_tab)
|
||||
res['review'] = [{"id": cid, "conclusion": c, "sn": sn}
|
||||
for cid, (c, sn) in review.items()]
|
||||
if review:
|
||||
excelfio.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(tasks, ctx):
|
||||
"""逐参保单位:登录政务平台 → 完整网页导入申报 → 回写。
|
||||
每个账号办完(无论成败)都清 cookies 关浏览器,下个账号全新开始。
|
||||
回写策略:单位内累积到内存并写 JSON 缓存(防崩溃),运行结束统一回写 Excel 一次。"""
|
||||
results = []
|
||||
n = len(tasks)
|
||||
for i, task in enumerate(tasks, 1):
|
||||
_log(f"\n========== [{i}/{n}] {task['unit']}({task['count']}人)==========")
|
||||
_log(f"导入文件:{task['file']}")
|
||||
ctx.progress(20 + int(70 * (i - 1) / max(n, 1)))
|
||||
try:
|
||||
login_res = login.ensure_login(task["username"], task["password"])
|
||||
except Exception as e:
|
||||
login_res = {"success": False, "message": f"登录调用异常:{e}"}
|
||||
_log(f"登录结果:{login_res.get('message')}")
|
||||
try:
|
||||
if login_res.get("success"):
|
||||
web_res = do_web_import(task)
|
||||
_log(f"办理结果:{web_res.get('message')}")
|
||||
results.append({**task, **web_res})
|
||||
else:
|
||||
results.append({**task, "success": False,
|
||||
"message": login_res.get("message", "")})
|
||||
finally:
|
||||
# 账号隔离:清 cookies + 关浏览器,再进入下一单位
|
||||
login.close_session()
|
||||
return results
|
||||
|
||||
|
||||
def run(ctx, limit=0):
|
||||
"""主流程:恢复缓存 → 读名单(排除已回写人员)→ 取号 → 预检 → 逐单位登录导入 → 统一回写。
|
||||
返回 JSON 安全 dict。"""
|
||||
ctx.progress(5)
|
||||
recovered_ids = excelfio.load_ckpt()
|
||||
units = source.load_add_units(exclude_ids=recovered_ids)
|
||||
# 崩溃恢复:上次运行残留的回写缓存统一落盘(排除逻辑已在 load_add_units 中生效,
|
||||
# 即使下面回写失败,这些人也不会被当成待办重复申报)
|
||||
if recovered_ids:
|
||||
_log("\n检测到上次未回写的内容,先统一回写:")
|
||||
try:
|
||||
excelfio.flush_writeback()
|
||||
except Exception as e:
|
||||
_log(f"恢复回写失败(缓存保留,下次启动重试):{e}")
|
||||
if not units:
|
||||
return {"summary": "无待办数据", "rows": [], "notes": []}
|
||||
|
||||
ctx.progress(15)
|
||||
# 文件占用预检:源名单被 Excel 打开会卡回写,提前报错
|
||||
source_file, _ = excelfio.get_writeback_target()
|
||||
config.check_not_locked(source_file)
|
||||
|
||||
accounts = source.load_accounts([u for u, _ in units])
|
||||
tasks = precheck(units, accounts)
|
||||
if tasks is None:
|
||||
raise RuntimeError("预检未通过,详见日志(缺导入文件/台账账号),修正后重跑")
|
||||
|
||||
if limit > 0:
|
||||
tasks = tasks[:limit]
|
||||
_log(f"分批运行:本次仅办理前 {limit} 个单位")
|
||||
|
||||
ctx.progress(20)
|
||||
results = process_units(tasks, ctx)
|
||||
ctx.progress(92)
|
||||
# 运行结束:本次累积的回写内容统一写 Excel 一次(失败则 JSON 缓存保留,下次启动恢复)
|
||||
try:
|
||||
excelfio.flush_writeback()
|
||||
except Exception as e:
|
||||
_log(f"回写失败:{e}")
|
||||
ok = [r for r in results if r["success"]]
|
||||
fail = [r for r in results if not r["success"]]
|
||||
_log(f"\n========== 汇总 ==========")
|
||||
_log(f"成功 {len(ok)} 家,失败 {len(fail)} 家")
|
||||
notes = []
|
||||
for r in fail:
|
||||
_log(f" ✗ {r['unit']}:{r.get('message', '')}")
|
||||
notes.append(f"{r['unit']}:{r.get('message', '')}")
|
||||
ctx.progress(100)
|
||||
return {"summary": f"增员办理 成功{len(ok)}/失败{len(fail)}",
|
||||
"rows": [{k: r.get(k) for k in ('unit', 'count', 'imported', 'message')}
|
||||
for r in results],
|
||||
"notes": notes}
|
||||
@@ -0,0 +1,108 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""增员名单制作模式(sb_person_change 插件)。
|
||||
|
||||
自 workflows/XQ0008 generate_add.py 迁移:读取【参保名单】sheet,筛选 区域=重庆 ∩
|
||||
参保类型=指定类型 ∩ 办理状态为空,按参保单位分组复制《增员模版.xls》(保留下拉字典),
|
||||
逐店生成《XX增员导入名单.xls》。日期规则与影刀版一致:先「转移参保」后「新参保」,
|
||||
工伤参保时间=当日,其余参保时间=本月1日。
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
from . import config
|
||||
from . import excelio
|
||||
from . import source
|
||||
|
||||
|
||||
def _log(msg):
|
||||
config.log(msg)
|
||||
|
||||
|
||||
def _translate_education(val):
|
||||
if val is None or config._to_text(val) == '':
|
||||
return '90.其他'
|
||||
return config.EDU_MAP.get(str(val).strip(), '90.其他')
|
||||
|
||||
|
||||
def _translate_nation(val):
|
||||
if val is None or config._to_text(val) == '':
|
||||
return '99.其他'
|
||||
return config.NATION_MAP.get(str(val).strip(), '99.其他')
|
||||
|
||||
|
||||
def _translate_residence(val):
|
||||
if val is None or config._to_text(val) == '':
|
||||
return ''
|
||||
return config.RESIDENCE_MAP.get(str(val).strip(), '')
|
||||
|
||||
|
||||
def _process_add_members(operation_type):
|
||||
"""生成指定参保类型的增员导入名单。"""
|
||||
cm = config.COLUMN_MAP_ADD
|
||||
source_file, df_filtered = source.load_add_rows(operation_type)
|
||||
if df_filtered.empty:
|
||||
return []
|
||||
config.check_not_locked(source_file)
|
||||
|
||||
today = datetime.now()
|
||||
first_day = today.replace(day=1)
|
||||
_log(f"今日日期:{today.strftime('%Y-%m-%d')}")
|
||||
_log(f"本月1日:{first_day.strftime('%Y-%m-%d')}(首次参加/养老/失业/医疗/生育参保时间)")
|
||||
_log(f"工伤参保时间:{today.strftime('%Y-%m-%d')}(当日)")
|
||||
|
||||
template_file = excelio.find_template_file(config.ADD_TEMPLATE_FILE)
|
||||
output_dir = excelio.get_output_dir_add(operation_type)
|
||||
_log(f"输出目录:{output_dir}")
|
||||
produced = []
|
||||
for store_name, group in df_filtered.groupby(cm['单位名称']):
|
||||
_log(f" 正在处理:{store_name},共 {len(group)} 人")
|
||||
first_row = group.iloc[0]
|
||||
unit_no = first_row[cm['社保号']]
|
||||
unit_full_name = first_row[cm['参保单位全称']]
|
||||
|
||||
# 逐行生成数据(键 = 模板列名)
|
||||
records = []
|
||||
for _, row in group.iterrows():
|
||||
records.append({
|
||||
'证件号码': config._to_text(row[cm['证件号码']]),
|
||||
'姓名': row[cm['姓名']],
|
||||
'民族': _translate_nation(row[cm['民族']]),
|
||||
'首次参加工作日期': first_day,
|
||||
'月基本工资额': config._clean_value(row[cm['月基本工资额']]),
|
||||
'工种': config.DEFAULT_VALUES_ADD['工种'],
|
||||
'个人身份': config.DEFAULT_VALUES_ADD['个人身份'],
|
||||
'户口性质': _translate_residence(row[cm['户口性质']]),
|
||||
'联系电话': config._to_text(row[cm['联系电话']]),
|
||||
'文化程度': _translate_education(row[cm['文化程度']]),
|
||||
'养老保险参保时间': 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['技能等级'],
|
||||
})
|
||||
|
||||
output_path = f"{output_dir}\\{config._safe_name(store_name)}增员导入名单.xls"
|
||||
excelio.write_template(template_file, output_path, unit_no, unit_full_name,
|
||||
records, config.TPL_COLS_ADD, config.DATE_COLS_ADD)
|
||||
_log(f" 已生成:{output_path}")
|
||||
produced.append({"unit": str(store_name), "count": len(group), "path": output_path})
|
||||
|
||||
_log(f"所有【{operation_type}】导入名单生成完成!")
|
||||
return produced
|
||||
|
||||
|
||||
def run(ctx):
|
||||
"""主入口(与影刀版一致):依次生成「转移参保」和「新参保」两类名单。"""
|
||||
ctx.progress(5)
|
||||
produced = []
|
||||
produced += _process_add_members('转移参保')
|
||||
ctx.progress(40)
|
||||
produced += _process_add_members('新参保')
|
||||
ctx.progress(100)
|
||||
total = sum(p["count"] for p in produced)
|
||||
return {"summary": f"增员名单制作:{len(produced)} 个单位 / {total} 人",
|
||||
"rows": produced, "notes": []}
|
||||
@@ -0,0 +1,66 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""减员名单制作模式(sb_person_change 插件)。
|
||||
|
||||
自 workflows/XQ0008 generate_stop.py 迁移:读取【停保名单】sheet,筛选 区域=重庆,
|
||||
按参保单位分组复制《减员模版.xls》(保留下拉字典),逐单位生成《XX减员导入名单.xls》。
|
||||
填写标准:减少时间=当天、减少原因=在职人员主动解除劳动合同、
|
||||
五个险种减少标志=1 减少、失业原因=3 劳动者自愿辞职。
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
from . import config
|
||||
from . import excelio
|
||||
from . import source
|
||||
|
||||
|
||||
def _log(msg):
|
||||
config.log(msg)
|
||||
|
||||
|
||||
def run(ctx):
|
||||
"""主流程:读【停保名单】→ 筛选重庆 → 按单位生成减员导入名单。"""
|
||||
ctx.progress(5)
|
||||
source_file, df_filtered = source.load_stop_rows()
|
||||
if df_filtered.empty:
|
||||
ctx.progress(100)
|
||||
return {"summary": f"无【{config.REGION}】区域停保数据", "rows": [], "notes": []}
|
||||
config.check_not_locked(source_file)
|
||||
_log(f"共找到 {len(df_filtered)} 条 {config.REGION} 区域停保记录")
|
||||
|
||||
today = datetime.now()
|
||||
_log(f"制作日期:{today.strftime('%Y-%m-%d')}(减少时间 = 当天)")
|
||||
|
||||
cm = config.COLUMN_MAP_STOP
|
||||
template_file = excelio.find_template_file(config.STOP_TEMPLATE_FILE)
|
||||
output_dir = excelio.get_output_dir_stop()
|
||||
_log(f"输出目录:{output_dir}")
|
||||
produced = []
|
||||
for group_key, group in df_filtered.groupby(config.GROUP_COL_STOP):
|
||||
_log(f" 正在处理:单位【{group_key}】,共 {len(group)} 人")
|
||||
first_row = group.iloc[0]
|
||||
unit_no = first_row[cm['单位社保号']] # 单位社保号 → B1
|
||||
unit_name = first_row[cm['单位名称']] # 参保单位 → D1
|
||||
|
||||
records = []
|
||||
for _, row in group.iterrows():
|
||||
rec = {'减少时间': today}
|
||||
for tpl_col in config.TPL_COLS_STOP:
|
||||
if tpl_col == '减少时间':
|
||||
continue
|
||||
if tpl_col in cm:
|
||||
rec[tpl_col] = config._clean_value(row[cm[tpl_col]])
|
||||
else:
|
||||
rec[tpl_col] = config.DEFAULT_VALUES_STOP[tpl_col]
|
||||
records.append(rec)
|
||||
|
||||
output_path = f"{output_dir}\\{config._safe_name(group_key)}减员导入名单.xls"
|
||||
excelio.write_template(template_file, output_path, unit_no, unit_name,
|
||||
records, config.TPL_COLS_STOP, config.DATE_COLS_STOP)
|
||||
_log(f" 已生成:{output_path}")
|
||||
produced.append({"unit": str(group_key), "count": len(group), "path": output_path})
|
||||
|
||||
_log(f"所有停保导入名单生成完成!共 {len(produced)} 个单位")
|
||||
ctx.progress(100)
|
||||
total = sum(p["count"] for p in produced)
|
||||
return {"summary": f"减员名单制作:{len(produced)} 个单位 / {total} 人",
|
||||
"rows": produced, "notes": []}
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "sb_person_change",
|
||||
"name": "社保系统增减员办理",
|
||||
"version": "1.0.0",
|
||||
"description": "重庆社保增减员全流程:增员/减员名单制作 → 平台增员办理 → 核查回盘(含预检)",
|
||||
"category": "社保",
|
||||
"icon": "",
|
||||
"platform": "",
|
||||
"uses_month": false,
|
||||
"capabilities": ["sb_person_change"],
|
||||
"permissions": {
|
||||
"platforms": []
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"mode": {
|
||||
"type": "string",
|
||||
"title": "执行模式",
|
||||
"default": "增员名单制作",
|
||||
"enum": ["增员名单制作", "减员名单制作", "增员办理", "核查回盘", "预检"],
|
||||
"description": "预检=只读源表与台账校验,不开浏览器"
|
||||
},
|
||||
"limit": {
|
||||
"type": "integer",
|
||||
"title": "分批条数",
|
||||
"default": 0,
|
||||
"description": "增员办理/核查回盘每次最多处理的单位数,0=不限"
|
||||
},
|
||||
"debug_mode": {
|
||||
"type": "string",
|
||||
"title": "调试模式",
|
||||
"default": "关闭",
|
||||
"enum": ["关闭", "开启"],
|
||||
"description": "开启后保存页面截图与验证码调试图(插件 debug/ 目录)"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
DrissionPage>=4.1
|
||||
ddddocr>=1.5
|
||||
python-dotenv>=1.0
|
||||
openpyxl>=3.1
|
||||
pandas>=2.0
|
||||
xlrd>=2.0
|
||||
xlwt>=1.3
|
||||
xlutils>=2.0
|
||||
@@ -0,0 +1,182 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""源名单/台账数据层(sb_person_change 插件)。
|
||||
|
||||
自 workflows/XQ0014 import_add.py(名单读取、台账取号)与 check_review.py(核查任务)
|
||||
迁移;名单制作模式的源表读取也在此(与 generate_add/generate_stop 同源)。
|
||||
print → config.log。
|
||||
"""
|
||||
import os
|
||||
from datetime import datetime
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from . import config
|
||||
from . import excelio
|
||||
|
||||
|
||||
def _log(msg):
|
||||
config.log(msg)
|
||||
|
||||
|
||||
# ==================== 源名单读取(增员办理) ====================
|
||||
def load_add_units(exclude_ids=frozenset()):
|
||||
"""读取源名单并筛选,返回 [(参保单位, 人数), ...](按单位分组)。
|
||||
|
||||
筛选:区域=重庆 ∩ 参保类型=新参保 ∩ 办理状态为空/NULL
|
||||
(待审核=已提交社保局、参保失败=已在其它流程处理,均不再办理)。
|
||||
exclude_ids:需排除的身份证号集合(上次运行已回写办理状态的人员,防重复申报)。
|
||||
"""
|
||||
source_file = config._latest_file(config.SOURCE_DIR, config.SOURCE_GLOB)
|
||||
now = datetime.now()
|
||||
xl = pd.ExcelFile(source_file)
|
||||
sheet_name = config._pick_sheet(xl, f"{now:%Y%m}参保名单", config.ADD_SHEET_KEY)
|
||||
_log(f"源名单:{os.path.basename(source_file)}(sheet: {sheet_name})")
|
||||
# 增员办理/核查的回写都落在该源名单上
|
||||
excelio.set_writeback_target(source_file, sheet_name)
|
||||
|
||||
df = pd.read_excel(source_file, sheet_name=sheet_name, header=config.SOURCE_HEADER_ROW - 1)
|
||||
status_text = df[config.STATUS_COL].astype(str).str.strip().str.lower()
|
||||
mask = (
|
||||
(df[config.REGION_COL].astype(str).str.strip() == config.REGION)
|
||||
& (df[config.TYPE_COL].astype(str).str.strip() == config.OPERATION_TYPE)
|
||||
& (df[config.STATUS_COL].isna() | status_text.isin(['', 'nan', 'none', 'nat']))
|
||||
)
|
||||
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:
|
||||
_log(f" 已排除 {dropped} 行上次运行已回写的人员(防重复申报)")
|
||||
if sub.empty:
|
||||
_log(f"没有筛选到数据({config.REGION} ∩ {config.OPERATION_TYPE} ∩ 办理状态为空)")
|
||||
return []
|
||||
grouped = sub.groupby(sub[config.UNIT_COL].astype(str).str.strip()).size()
|
||||
units = sorted(grouped.items(), key=lambda t: t[0])
|
||||
_log(f"筛选结果:共 {sum(n for _, n in units)} 人 / {len(units)} 个参保单位")
|
||||
return units
|
||||
|
||||
|
||||
# ==================== 源名单读取(核查回盘) ====================
|
||||
def load_check_tasks(exclude_ids=frozenset()):
|
||||
"""读取源名单,筛选 办理状态=待审核 的行,按参保单位分组。
|
||||
|
||||
返回 [{unit, count, cids(set)}]。
|
||||
exclude_ids:上次运行已回写的人员身份证号(防重复核查)。
|
||||
"""
|
||||
source_file = config._latest_file(config.SOURCE_DIR, config.SOURCE_GLOB)
|
||||
now = datetime.now()
|
||||
xl = pd.ExcelFile(source_file)
|
||||
sheet_name = config._pick_sheet(xl, f"{now:%Y%m}参保名单", config.ADD_SHEET_KEY)
|
||||
_log(f"源名单:{os.path.basename(source_file)}(sheet: {sheet_name})")
|
||||
excelio.set_writeback_target(source_file, sheet_name)
|
||||
|
||||
df = pd.read_excel(source_file, sheet_name=sheet_name, header=config.SOURCE_HEADER_ROW - 1)
|
||||
status = df[config.STATUS_COL].astype(str).str.strip()
|
||||
mask = (
|
||||
(df[config.REGION_COL].astype(str).str.strip() == config.REGION)
|
||||
& (df[config.TYPE_COL].astype(str).str.strip() == config.OPERATION_TYPE)
|
||||
& (status == config.CHECK_STATUS)
|
||||
)
|
||||
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:
|
||||
_log(f" 已排除 {dropped} 行上次运行已回写的人员(防重复核查)")
|
||||
if sub.empty:
|
||||
_log(f"没有筛选到数据({config.REGION} ∩ {config.OPERATION_TYPE} ∩ "
|
||||
f"办理状态={config.CHECK_STATUS})")
|
||||
return []
|
||||
|
||||
tasks = []
|
||||
for unit, g in sub.groupby(sub[config.UNIT_COL].astype(str).str.strip()):
|
||||
cids = {config._norm_id(v) for v in g['身份证号码']}
|
||||
cids.discard('')
|
||||
tasks.append({"unit": unit, "count": len(cids), "cids": cids})
|
||||
tasks.sort(key=lambda t: t['unit'])
|
||||
_log(f"核查范围:共 {sum(t['count'] for t in tasks)} 人 / {len(tasks)} 个参保单位"
|
||||
f"(办理状态={config.CHECK_STATUS})")
|
||||
return tasks
|
||||
|
||||
|
||||
# ==================== 源名单读取(名单制作) ====================
|
||||
def load_add_rows(operation_type):
|
||||
"""读取【参保名单】sheet,筛选 区域=重庆 ∩ 参保类型=指定类型 ∩ 办理状态为空。
|
||||
|
||||
返回 (source_file, df_filtered)。身份证/电话按文本读,防 18 位丢精度。
|
||||
"""
|
||||
source_file = config._latest_file(config.SOURCE_DIR, config.SOURCE_GLOB)
|
||||
xl = pd.ExcelFile(source_file)
|
||||
sheet_name = config._pick_sheet(xl, "", config.ADD_SHEET_KEY)
|
||||
_log(f"源表:{os.path.basename(source_file)}(sheet: {sheet_name})")
|
||||
df_source = pd.read_excel(
|
||||
source_file, sheet_name=sheet_name, header=config.SOURCE_HEADER_ROW - 1,
|
||||
dtype={'身份证号码': str, '电话号码': str})
|
||||
status_text = df_source[config.STATUS_COL].astype(str).str.strip().str.lower()
|
||||
mask = (
|
||||
(df_source[config.REGION_COL] == config.REGION)
|
||||
& (df_source[config.TYPE_COL] == operation_type)
|
||||
& (df_source[config.STATUS_COL].isna() | status_text.isin(['', 'nan', 'none', 'nat']))
|
||||
)
|
||||
df_filtered = df_source[mask].copy()
|
||||
if df_filtered.empty:
|
||||
_log(f"没有找到【{operation_type}】的数据({config.REGION}区域,办理状态为空)")
|
||||
return source_file, df_filtered
|
||||
|
||||
|
||||
def load_stop_rows():
|
||||
"""读取【停保名单】sheet,筛选 区域=重庆。全列按文本读,保住身份证/社保编号完整值。
|
||||
|
||||
返回 (source_file, df_filtered)。
|
||||
"""
|
||||
source_file = config._latest_file(config.SOURCE_DIR, config.SOURCE_GLOB)
|
||||
xl = pd.ExcelFile(source_file)
|
||||
sheet_name = config._pick_sheet(xl, "", config.STOP_SHEET_KEY)
|
||||
_log(f"源表:{os.path.basename(source_file)}(sheet: {sheet_name})")
|
||||
df_source = pd.read_excel(
|
||||
source_file, sheet_name=sheet_name, header=config.SOURCE_HEADER_ROW - 1, dtype=str)
|
||||
df_filtered = df_source[df_source[config.REGION_COL] == config.REGION].copy()
|
||||
if df_filtered.empty:
|
||||
_log(f"没有找到【{config.REGION}】区域的停保数据")
|
||||
return source_file, df_filtered
|
||||
|
||||
|
||||
# ==================== 台账取号 ====================
|
||||
def load_accounts(unit_names):
|
||||
"""从台账「YYYY年M月缴费比例」sheet 取各单位账号。
|
||||
|
||||
返回 {参保单位: {"username":..., "username_src": "信用代码|平台用户名", "password":...}},
|
||||
取不到的单位不在返回值中(由预检统一报错)。
|
||||
"""
|
||||
ledger_file = config._latest_file(config.LEDGER_DIR, config.LEDGER_GLOB)
|
||||
now = datetime.now()
|
||||
xl = pd.ExcelFile(ledger_file)
|
||||
sheet_name = config._pick_sheet(xl, f"{now.year}年{now.month}月缴费比例", "缴费比例",
|
||||
pattern=r"(20\d{2})年(1[0-2]|[1-9])月缴费比例")
|
||||
_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.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["平台密码"]])
|
||||
# 用户名规则:信用代码优先,空则回退平台用户名
|
||||
username, src = (credit, "信用代码") if credit else (plat_user, "平台用户名")
|
||||
accounts[name] = {"username": username, "username_src": src, "password": plat_pwd}
|
||||
return accounts
|
||||
@@ -0,0 +1,742 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""政务平台网页操作层(sb_person_change 插件)。
|
||||
|
||||
自 workflows/XQ0014 import_add.py(增员导入申报)与 check_review.py(已申报查询核查、
|
||||
回盘打印下载核对)迁移。全部 print → config.log,截图统一走 excelio.shot。
|
||||
依赖登录会话:login.LAST_SESSION(每个单位登录一次,办完 close_session)。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse, parse_qsl, urlencode
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from . import config
|
||||
from . import excelio
|
||||
from . import login
|
||||
|
||||
BUSINESS_ITEM = "城保参保单位人员增加" # 单位办事列表里的业务名称
|
||||
WEB_TIMEOUT = 20 # 网页元素等待超时(秒)
|
||||
|
||||
# 核查回盘相关(check_review 同源)
|
||||
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 # 重放翻页上限(防死循环)
|
||||
|
||||
|
||||
def _log(msg):
|
||||
config.log(msg)
|
||||
|
||||
|
||||
def _shot(tab, name):
|
||||
excelio.shot(tab, name)
|
||||
|
||||
|
||||
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()
|
||||
_log(f" 关闭弹窗:{t}")
|
||||
hit = True
|
||||
time.sleep(1.2)
|
||||
except Exception:
|
||||
pass
|
||||
if not hit:
|
||||
break
|
||||
|
||||
|
||||
# ==================== 增员导入:业务页与上传 ====================
|
||||
def open_business_page(page, work_tab):
|
||||
"""工作台 → 单位办事 → 「城保参保单位人员增加」在线办理。返回承载业务页的 tab。"""
|
||||
before = set(page.tab_ids)
|
||||
_click_any(work_tab, ['tag:button@@text()=单位办事'], '「单位办事」菜单')
|
||||
time.sleep(2.5)
|
||||
# 列表项:h4 标题定位 → 上溯到 li.ant-list-item → 点其「在线办理」
|
||||
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()
|
||||
# 业务页可能新开 tab 或当前页跳转:轮询识别出现上传控件(input[type=file])的页面
|
||||
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 _wait_import_result(tab, timeout=90):
|
||||
"""导入结果探针:等待「导入完成」成功弹窗,或捕获失败提示(modal/toast)。
|
||||
返回 ("ok", modal元素) / ("fail", 提示文本) / ("timeout", None)。"""
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
for m in tab.eles('css:.ant-modal-body'):
|
||||
t = (m.text or '').strip()
|
||||
if '导入完成' in t:
|
||||
return "ok", m
|
||||
if t and not any(k in t for k in ('提交中', '导入中', '加载中')):
|
||||
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 部件的就绪信号)。
|
||||
|
||||
单位信息由上传文件解析而来,显示在 borderless 下拉框里:
|
||||
可能先以 placeholder 形式出现,也可能直接是选中值。
|
||||
必须等文本内容真正渲染出来(非空)才算就绪,仅元素挂载不算。"""
|
||||
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, 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) # DrissionPage 对 file input 直接写路径即上传
|
||||
# 等单位信息出现(placeholder 或选中值),未就绪点导入会报 aab001 缺失
|
||||
if not _wait_unit_ready(tab, timeout=40):
|
||||
_log(" 警告:40s 内单位信息未出现,本轮仍尝试导入")
|
||||
time.sleep(1.0) # 就绪后再留缓冲,避免点太快
|
||||
_shot(tab, "03_file_selected")
|
||||
_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
|
||||
_log(f" 导入完成:成功 {total} 人,失败 {failed} 人")
|
||||
if total == 0:
|
||||
raise RuntimeError(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 "导入后未出现结果弹窗(超时)"
|
||||
_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 读表格,返回 [(证件号码, 详细信息), ...]。
|
||||
按表头(含「证件号码」+「详细信息」列)定位表格,避免抓到左侧导航等其它 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:
|
||||
_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)
|
||||
_log(" 警告:等待 PDF 渲染超时,继续尝试提交")
|
||||
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)
|
||||
_log(f" 下一步后未出现「提 交」按钮(第 {i + 1} 次),重试")
|
||||
time.sleep(1.5)
|
||||
return False
|
||||
|
||||
|
||||
def _click_submit(tab, tries=3):
|
||||
"""点「提 交」,验证「已知晓」确认弹窗出现;第一次可能因按钮未就绪失效,重试。
|
||||
期间打印页面 toast 提示,便于诊断失败原因。"""
|
||||
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:
|
||||
_log(f" 提交提示:{t[:100]}")
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
_log(f" 第 {i + 1} 次提交未出现「已知晓」确认弹窗,重试")
|
||||
time.sleep(1.5)
|
||||
return False
|
||||
|
||||
|
||||
def _confirm_submit(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
|
||||
_log(f" 第 {i + 1} 次点击已知晓后未见成功弹窗,重试")
|
||||
return False
|
||||
|
||||
|
||||
def predeclare_and_submit(page, tab):
|
||||
"""预申报 → 去申报 → 关弹窗 → 全部提交 → 等 PDF → 下一步 → 提交(带重试)→ 已知晓 → 等成功。"""
|
||||
_click_any(tab, ['tag:button@@text()=预申报'], '「预申报」按钮')
|
||||
if _wait_modal(tab, '预申报成功', timeout=60) is None:
|
||||
raise RuntimeError("预申报后未出现成功弹窗")
|
||||
_click_any(tab, ['tag:button@@text()=去申报'], '「去申报」按钮')
|
||||
# 等申报页就绪:提示弹窗或「全部提交」按钮任一出现即继续(替代固定 sleep,省 ~8s 空等)
|
||||
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 not _click_submit(tab):
|
||||
_shot(tab, "09_submit_no_confirm")
|
||||
raise RuntimeError("点击提交后未出现「已知晓」确认弹窗")
|
||||
if not _confirm_submit(tab):
|
||||
_shot(tab, "10_confirm_no_success")
|
||||
raise RuntimeError("点击已知晓后未出现「您已成功提交」弹窗(提交可能未完成)")
|
||||
_shot(tab, "11_submit_success")
|
||||
_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
|
||||
# 明细表结构:业务流水号/业务类型/姓名/证件号码/审核结论/审核意见/操作
|
||||
# 证件号码可能是 15/18 位,尾号可为 X,不能只 isdigit
|
||||
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):
|
||||
"""进入申报查询列表 → 打开序号1记录的「查看」→ 读明细表审核结论。
|
||||
返回 {证件号码: (审核结论, 业务流水号)}。"""
|
||||
qtab = _open_query_page(page, tab)
|
||||
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
|
||||
# 等明细表出现(含 18 位证件号码的行)
|
||||
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
|
||||
_log(f" 第 {attempt + 1} 次查看未读到审核结论明细,重试")
|
||||
_shot(qtab, "13_review_detail_miss")
|
||||
time.sleep(1.5)
|
||||
raise RuntimeError("未读取到审核结论明细表")
|
||||
|
||||
|
||||
# ==================== 核查回盘:已申报查询 + 接口重放 ====================
|
||||
def open_query_menu(tab):
|
||||
"""业务页左侧菜单点「已申报查询」,等记录表(表头含 当前状态/操作)出现。"""
|
||||
_click_any(tab, [f'tag:li@@text()={MENU_QUERY}', f'text={MENU_QUERY}'],
|
||||
f'左侧菜单「{MENU_QUERY}」')
|
||||
_dismiss_popups(tab)
|
||||
deadline = time.time() + 15
|
||||
while time.time() < deadline:
|
||||
for tb in tab.eles('tag:table'):
|
||||
try:
|
||||
ths = [th.text.strip() for th in tb.eles('tag:th')]
|
||||
except Exception:
|
||||
continue
|
||||
if '当前状态' in ths and '操作' in ths:
|
||||
return tb
|
||||
time.sleep(0.5)
|
||||
raise RuntimeError(f"点击「{MENU_QUERY}」后未出现申报记录表")
|
||||
|
||||
|
||||
def read_first_row(table):
|
||||
"""读申报记录表第一条:返回 (当前状态, 查看按钮元素)。无记录返回 (None, None)。"""
|
||||
row = table.ele('css:tbody tr.ant-table-row', timeout=3) \
|
||||
or table.ele('css:tbody tr', timeout=1)
|
||||
if row is None:
|
||||
return None, None
|
||||
ths = [th.text.strip() for th in table.eles('tag:th')]
|
||||
i_status = ths.index('当前状态')
|
||||
tds = [td.text.strip() for td in row.eles('tag:td')]
|
||||
status = tds[i_status] if len(tds) > i_status else ''
|
||||
view = None
|
||||
for sel in ('tag:a@@text()=查看', 'tag:span@@text()=查看', 'text=查看'):
|
||||
try:
|
||||
view = row.ele(sel, timeout=1)
|
||||
except Exception:
|
||||
view = None
|
||||
if view:
|
||||
break
|
||||
return status, view
|
||||
|
||||
|
||||
def _capture_query_url(page, tab, view):
|
||||
"""点「查看」并监听明细查询接口,返回请求 URL。
|
||||
明细可能在当前 tab 打开也可能新开 tab:两个方向都轮询监听。"""
|
||||
before = set(page.tab_ids)
|
||||
tab.listen.start(API_KEYWORD)
|
||||
new_tabs = []
|
||||
packet = None
|
||||
try:
|
||||
try:
|
||||
view.click()
|
||||
except Exception:
|
||||
view.click(by_js=True)
|
||||
deadline = time.time() + 25
|
||||
while time.time() < deadline and packet is None:
|
||||
# 新开 tab 也挂上监听(明细页可能新 tab 加载接口)
|
||||
for tid in [i for i in page.tab_ids if i not in before and i not in new_tabs]:
|
||||
new_tabs.append(tid)
|
||||
try:
|
||||
page.get_tab(tid).listen.start(API_KEYWORD)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
packet = tab.listen.wait(count=1, timeout=2)
|
||||
except Exception:
|
||||
packet = None
|
||||
if packet is None:
|
||||
for tid in new_tabs:
|
||||
try:
|
||||
packet = page.get_tab(tid).listen.wait(count=1, timeout=0.5)
|
||||
except Exception:
|
||||
packet = None
|
||||
if packet:
|
||||
break
|
||||
finally:
|
||||
for t in [tab] + [page.get_tab(tid) for tid in new_tabs if tid in page.tab_ids]:
|
||||
try:
|
||||
t.listen.stop()
|
||||
except Exception:
|
||||
pass
|
||||
if not packet:
|
||||
raise RuntimeError("点击查看后未监听到明细查询接口(queryYsbWs04orWs01)")
|
||||
url = packet.request.url
|
||||
_log(f" 已捕获明细接口:{url[:100]}...")
|
||||
return url
|
||||
|
||||
|
||||
def _fetch_via_xhr(tab, url):
|
||||
"""页内同步 XHR GET(自带登录态 cookies),返回响应文本。"""
|
||||
js = ("const xhr=new XMLHttpRequest();"
|
||||
"xhr.open('GET',arguments[0],false);"
|
||||
"xhr.setRequestHeader('Accept','application/json, text/javascript');"
|
||||
"xhr.send();return xhr.responseText;")
|
||||
return tab.run_js(js, url)
|
||||
|
||||
|
||||
def wait_unit_loaded(tab, unit_name, timeout=40):
|
||||
"""等业务页单位信息加载完成:轮询 getAab001 接口直到返回本单位数据。
|
||||
该接口没返回时页面没加载出单位,后续已申报查询/回盘打印都拿不到数据。
|
||||
接口轮询失败但页面已出现单位名时也视为加载成功(可能错过响应窗口)。
|
||||
返回 data[0](含 aab001、aab004 平台单位全称),页面已加载但接口拿不到时返回 {},超时返回 None。"""
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
raw = _fetch_via_xhr(tab, API_UNIT_INFO)
|
||||
data = (json.loads(raw).get('data') or [None])[0]
|
||||
if data and data.get('aab001'):
|
||||
_log(f" 单位信息已加载:{data.get('aab004')}(aab001={data.get('aab001')})")
|
||||
return data
|
||||
except Exception:
|
||||
pass
|
||||
# 接口没拿到但页面已经出现单位名 → 页面其实加载完了,不必再等
|
||||
try:
|
||||
if tab.ele(f'text:{unit_name}', timeout=0.5):
|
||||
_log(f" 页面已显示单位「{unit_name}」,视为加载完成(接口轮询未取到全称)")
|
||||
return {}
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
return None
|
||||
|
||||
|
||||
def replay_query_all(tab, captured_url):
|
||||
"""用捕获的请求参数重放接口翻页,取全量明细行。
|
||||
返回 ([{name, cid, conclusion, opinion}, ...], unit_full)。
|
||||
字段取 aac003/aac002/aae110s/aae111/aab004。"""
|
||||
parsed = urlparse(captured_url)
|
||||
base_params = [(k, v) for k, v in parse_qsl(parsed.query, keep_blank_values=True)
|
||||
if k != 'pageIndex']
|
||||
root = f"{parsed.scheme}://{parsed.netloc}{parsed.path}"
|
||||
rows, total = [], None
|
||||
for idx in range(MAX_PAGES):
|
||||
params = base_params + [('pageIndex', json.dumps(
|
||||
{"pageIndex": idx, "pageSize": PAGE_SIZE}, separators=(',', ':')))]
|
||||
full = f"{root}?{urlencode(params)}"
|
||||
raw = _fetch_via_xhr(tab, full)
|
||||
if not raw:
|
||||
raise RuntimeError(f"接口重放第 {idx + 1} 页返回空")
|
||||
payload = json.loads(raw)
|
||||
data = payload.get('data') or {}
|
||||
items = data.get('data') or []
|
||||
if total is None:
|
||||
total = data.get('total')
|
||||
rows.extend(items)
|
||||
_log(f" 接口重放第 {idx + 1} 页:取到 {len(items)} 条(累计 {len(rows)}/{total})")
|
||||
if not items or (total is not None and len(rows) >= total):
|
||||
break
|
||||
results = []
|
||||
for it in rows:
|
||||
results.append({
|
||||
"name": str(it.get('aac003') or '').strip(),
|
||||
"cid": config._norm_id(it.get('aac002')),
|
||||
"conclusion": str(it.get('aae110s') or '').strip(),
|
||||
"opinion": str(it.get('aae111') or '').strip(),
|
||||
})
|
||||
# 平台登记的参保单位全称(aab004),用于回盘文件命名
|
||||
unit_full = ""
|
||||
for it in rows:
|
||||
v = str(it.get('aab004') or '').strip()
|
||||
if v:
|
||||
unit_full = v
|
||||
break
|
||||
return results, unit_full
|
||||
|
||||
|
||||
# ==================== 核查回盘:回盘打印下载与核对 ====================
|
||||
def _clean_cell(v):
|
||||
"""单元格值转干净字符串:浮点整数去掉 .0,其余去首尾空白。"""
|
||||
if v is None:
|
||||
return ""
|
||||
if isinstance(v, float) and v.is_integer():
|
||||
return str(int(v))
|
||||
return str(v).strip()
|
||||
|
||||
|
||||
def download_huipan(page, biz_tab, unit):
|
||||
"""左侧菜单「回盘打印」→ 页内「回盘打印」按钮,等下载完成后重命名为规范文件名。
|
||||
返回保存的文件 Path。"""
|
||||
save_dir = Path(config.HUIPAN_DIR)
|
||||
save_dir.mkdir(parents=True, exist_ok=True)
|
||||
target = save_dir / f"{config.REPLAY_PREFIX}_{unit}_{datetime.now():%Y%m%d}.xlsx"
|
||||
menu_sel = ['tag:li@@text()=回盘打印', 'text=回盘打印']
|
||||
try:
|
||||
_click_any(biz_tab, menu_sel, '左侧菜单「回盘打印」')
|
||||
except Exception:
|
||||
# 点「查看」后会跳到明细详情页,左侧菜单不可见:直跳 OdCommon 菜单页即可
|
||||
try:
|
||||
_log(" 当前页看不到左侧菜单,直跳菜单页...")
|
||||
biz_tab.get(MENU_PAGE_URL)
|
||||
time.sleep(2)
|
||||
_click_any(biz_tab, menu_sel, '左侧菜单「回盘打印」(菜单页)')
|
||||
except Exception:
|
||||
# 直跳也不行:重开业务页再点(最后兜底)
|
||||
biz_tab = open_business_page(page, login.LAST_SESSION['tab'])
|
||||
_dismiss_popups(biz_tab)
|
||||
_click_any(biz_tab, menu_sel, '左侧菜单「回盘打印」(重开业务页)')
|
||||
_dismiss_popups(biz_tab)
|
||||
|
||||
# 页内「回盘打印」按钮(menu li 已处理,这里只找按钮/链接/文本)
|
||||
btn = None
|
||||
for sel in ('tag:button@@text()=回盘打印', 'tag:a@@text()=回盘打印',
|
||||
'tag:span@@text()=回盘打印'):
|
||||
try:
|
||||
btn = biz_tab.ele(sel, timeout=2)
|
||||
except Exception:
|
||||
btn = None
|
||||
if btn:
|
||||
break
|
||||
if btn is None:
|
||||
raise RuntimeError("未找到页内「回盘打印」按钮")
|
||||
|
||||
biz_tab.set.download_path(str(save_dir))
|
||||
before = {f.name for f in save_dir.iterdir() if f.is_file()}
|
||||
try:
|
||||
btn.click()
|
||||
except Exception:
|
||||
btn.click(by_js=True)
|
||||
|
||||
# 轮询等下载:新文件出现且大小连续2秒稳定(最多90秒)
|
||||
new_file, last_size, stable = None, -1, 0
|
||||
deadline = time.time() + 90
|
||||
while time.time() < deadline:
|
||||
time.sleep(1)
|
||||
files = [f for f in save_dir.iterdir() if f.is_file() and f.name not in before
|
||||
and f.suffix.lower() not in ('.crdownload', '.tmp')]
|
||||
if not files:
|
||||
stable, last_size = 0, -1
|
||||
continue
|
||||
f = max(files, key=lambda x: x.stat().st_mtime)
|
||||
size = f.stat().st_size
|
||||
if size > 0 and size == last_size:
|
||||
stable += 1
|
||||
if stable >= 2:
|
||||
new_file = f
|
||||
break
|
||||
else:
|
||||
stable = 0
|
||||
last_size = size
|
||||
if new_file is None:
|
||||
raise RuntimeError("点击回盘打印后90秒内未检测到新下载文件")
|
||||
os.replace(new_file, target) # 同名覆盖,保证文件名=回盘表_单位_日期.xlsx
|
||||
return target
|
||||
|
||||
|
||||
def verify_huipan(filepath, task_cids):
|
||||
"""读回盘表(表头在第2行),按身份证号核对五项参保状态,生成备注回写内容。
|
||||
同人多条记录:取参保缴费数量最多的那条(并列取先出现的)。
|
||||
返回 (remark_map, logs)。"""
|
||||
df = pd.read_excel(filepath, header=1)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
need = ['个人编号', '身份证号'] + config.INS_STATUSES
|
||||
missing = [c for c in need if c not in df.columns]
|
||||
if missing:
|
||||
raise RuntimeError(f"回盘表缺少列:{missing}")
|
||||
remarks, logs = {}, []
|
||||
for cid in task_cids:
|
||||
rows = df[df['身份证号'].map(
|
||||
lambda v: config._id_hit(config._norm_id(_clean_cell(v)), [cid]))]
|
||||
if rows.empty:
|
||||
remarks[cid] = "未查询到回盘记录"
|
||||
logs.append(f" 证件{cid}:回盘表中未找到记录 → 备注追加「未查询到回盘记录」")
|
||||
continue
|
||||
# 同人多条记录:取参保缴费数量最多的那条(并列取先出现的)
|
||||
best_row, best_ok = None, -1
|
||||
for _, row in rows.iterrows():
|
||||
ok = sum(1 for c in config.INS_STATUSES if _clean_cell(row[c]) == config.INS_OK)
|
||||
if ok > best_ok:
|
||||
best_row, best_ok = row, ok
|
||||
target = best_row
|
||||
bh = _clean_cell(target['个人编号'])
|
||||
if best_ok == len(config.INS_STATUSES):
|
||||
# 五项全参保缴费 = 正常,备注只追加个人编号
|
||||
remarks[cid] = f"个人编号:{bh}"
|
||||
logs.append(f" 证件{cid}:五项均参保缴费,个人编号 {bh} → 备注追加")
|
||||
else:
|
||||
# 有不是参保缴费的:记录个人编号 + 异常字段名和对应内容
|
||||
bad = [f"{c}:{_clean_cell(target[c])}"
|
||||
for c in config.INS_STATUSES if _clean_cell(target[c]) != config.INS_OK]
|
||||
remarks[cid] = f"个人编号:{bh};" + "、".join(bad)
|
||||
logs.append(f" 证件{cid}:参保状态异常 → {';'.join(bad)}(个人编号 {bh})→ 备注追加")
|
||||
return remarks, logs
|
||||
|
||||
|
||||
def do_huipan(page, biz_tab, task, res, unit_full="", fail_cids=()):
|
||||
"""每个账号核查完都执行:下载回盘记录 + 核对参保状态 + 备注追加(含与核查备注合并)。
|
||||
文件名单位优先用平台 aab004 全称,未取到(未办结跳过等)退回源名单参保单位名。
|
||||
fail_cids:审核不通过(参保失败)人员,平台无其回盘记录,跳过「未查询到回盘记录」回写。"""
|
||||
name_for_file = (unit_full or task['unit']).strip()
|
||||
if unit_full and unit_full != task['unit']:
|
||||
_log(f" 使用平台单位全称命名:{unit_full}")
|
||||
_log(" 开始回盘打印下载...")
|
||||
hp_file = download_huipan(page, biz_tab, name_for_file)
|
||||
_log(f" 回盘文件已保存:{hp_file}")
|
||||
hp_remarks, hp_logs = verify_huipan(hp_file, task['cids'])
|
||||
for line in hp_logs:
|
||||
_log(line)
|
||||
for cid in fail_cids:
|
||||
if hp_remarks.get(cid, "").strip() == "未查询到回盘记录":
|
||||
hp_remarks.pop(cid)
|
||||
_log(f" 证件{cid}:审核不通过无回盘记录,跳过未查询备注")
|
||||
# 与核查阶段已生成的备注合并(writeback_source 按证件号覆盖,需手动拼接)
|
||||
pending_remark = excelio._PENDING_REMARK
|
||||
for cid in list(hp_remarks):
|
||||
old = pending_remark.get(cid)
|
||||
if old:
|
||||
hp_remarks[cid] = f"{old}\n{hp_remarks[cid]}"
|
||||
if hp_remarks:
|
||||
excelio.writeback_source({}, hp_remarks)
|
||||
res["huipan"] = f"回盘已下载,核对回写 {len(hp_remarks)} 人"
|
||||
@@ -0,0 +1,115 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""考勤月报封存检查 - webhost 场景插件(XQ0011)
|
||||
|
||||
流程:填写检查月份与正休规则 → 一键执行(拉取数据 + 运行五项检查 + 自动导出多 Sheet Excel)。
|
||||
复用 desktop/shared 数据真源(由宿主共享登录态注入 session/user_id),不内置登录逻辑。
|
||||
"""
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from webhost.backend.plugins.base import PLUGINS, RunContext, ScenePlugin
|
||||
|
||||
from webhost.backend.plugins.seal_check import config
|
||||
from webhost.backend.plugins.seal_check.data import (
|
||||
fetch_compare_diffs, fetch_org_name_map, fetch_roster_data,
|
||||
fetch_seal_rows, fetch_shift_batch,
|
||||
)
|
||||
from webhost.backend.plugins.seal_check.logic import LeaveRuleEngine, run_all_checks
|
||||
from webhost.backend.plugins.seal_check.report import CHECK_TAB_TITLES, export_report
|
||||
|
||||
|
||||
def _default_month() -> str:
|
||||
last_end = datetime.now().replace(day=1) - timedelta(days=1)
|
||||
return f"{last_end.year:04d}-{last_end.month:02d}"
|
||||
|
||||
|
||||
class SealCheckPlugin(ScenePlugin):
|
||||
id = "seal_check"
|
||||
name = "考勤月报封存检查"
|
||||
version = "1.0.0"
|
||||
description = "填写每月正休规则,一键执行五项检查并导出多 Sheet Excel 报告"
|
||||
platform = "hr"
|
||||
uses_month = True # 月份由底座页眉统一提供(注入 ref_month),插件自身不再单列
|
||||
fields = [
|
||||
{"key": "fixed_rest_days", "label": "固休应休天数", "type": "int",
|
||||
"default": config.DEFAULT_RULES["fixed_rest_days"]},
|
||||
{"key": "size_rest_days", "label": "大小休应休天数", "type": "int",
|
||||
"default": config.DEFAULT_RULES["size_rest_days"]},
|
||||
{"key": "quota_rest_days", "label": "限额排休上限", "type": "int",
|
||||
"default": config.DEFAULT_RULES["quota_rest_days"]},
|
||||
]
|
||||
|
||||
def run(self, fields: dict, ctx: RunContext) -> dict:
|
||||
month_str = str(fields.get("ref_month") or _default_month()).strip()
|
||||
year, month = int(month_str[:4]), int(month_str[5:7].strip())
|
||||
yearmonth = f"{year:04d}{month:02d}"
|
||||
month_display = f"{year:04d}-{month:02d}"
|
||||
|
||||
engine = LeaveRuleEngine(
|
||||
size_rest_days=int(fields.get("size_rest_days") or config.DEFAULT_RULES["size_rest_days"]),
|
||||
fixed_rest_days=int(fields.get("fixed_rest_days") or config.DEFAULT_RULES["fixed_rest_days"]),
|
||||
quota_rest_days=int(fields.get("quota_rest_days") or config.DEFAULT_RULES["quota_rest_days"]),
|
||||
)
|
||||
|
||||
session = ctx.get_session("hr")
|
||||
user_id = ctx.get_user_id("hr")
|
||||
|
||||
ctx.log(f"开始考勤月报封存检查:{month_display}")
|
||||
ctx.progress(5)
|
||||
|
||||
ctx.log("拉取考勤封存数据……")
|
||||
seal_rows = fetch_seal_rows(session, user_id, yearmonth)
|
||||
ctx.progress(30)
|
||||
ctx.log(f"封存数据 {len(seal_rows)} 人")
|
||||
|
||||
ctx.log("拉取组织表……")
|
||||
org_name_map = fetch_org_name_map(session)
|
||||
ctx.progress(45)
|
||||
ctx.log(f"组织 {len(org_name_map)} 条")
|
||||
|
||||
ctx.log("导出花名册(获取职位序列)……")
|
||||
seq_map, in_service_records = fetch_roster_data(session)
|
||||
ctx.progress(60)
|
||||
ctx.log(f"花名册职位序列 {len(seq_map)} 人,在职 {len(in_service_records)} 人")
|
||||
|
||||
ctx.log("批量拉取排班(计算应出勤天数)……")
|
||||
shift_map = fetch_shift_batch(session, user_id, yearmonth)
|
||||
ctx.progress(80)
|
||||
ctx.log(f"排班应出勤 {len(shift_map)} 人")
|
||||
|
||||
diff_rows, diff_note = fetch_compare_diffs(session, user_id, yearmonth)
|
||||
ctx.progress(90)
|
||||
|
||||
notes = [diff_note] if diff_note else []
|
||||
ctx.log("运行全部检查……")
|
||||
result = run_all_checks(
|
||||
seal_rows=seal_rows,
|
||||
org_name_map=org_name_map,
|
||||
seq_map=seq_map,
|
||||
in_service_records=in_service_records,
|
||||
shift_map=shift_map,
|
||||
engine=engine,
|
||||
year=year, month=month,
|
||||
diff_rows=diff_rows, diff_fields=None, notes=notes,
|
||||
)
|
||||
ctx.progress(95)
|
||||
|
||||
path = export_report(result["rows"], month_display, result["notes"])
|
||||
ctx.progress(100)
|
||||
|
||||
for note in result["notes"]:
|
||||
ctx.log(f"[提示] {note}")
|
||||
summary = ";".join(
|
||||
f"{CHECK_TAB_TITLES[i]} {len(result['rows'].get(i, []))} 条"
|
||||
for i in range(1, 6))
|
||||
ctx.log(f"结果汇总:{summary}")
|
||||
ctx.log(f"===== 检查完成,报告已导出:{path} =====")
|
||||
|
||||
return {
|
||||
"summary": summary,
|
||||
"path": path,
|
||||
"rows": {str(k): v for k, v in result["rows"].items()},
|
||||
"notes": result["notes"],
|
||||
}
|
||||
|
||||
|
||||
PLUGINS.append(SealCheckPlugin())
|
||||
@@ -0,0 +1,35 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""考勤月报封存检查(webhost 场景插件)配置。
|
||||
|
||||
与 plugins/seal_check/config.py 保持同步(根级 plugins/ 为单一真源)。
|
||||
"""
|
||||
import os
|
||||
|
||||
# ==================== 输出目录 ====================
|
||||
SAVE_DIR = os.getenv("monthly_seal_save_dir") or r"D:\资料\人资\考勤异常"
|
||||
|
||||
# 花名册导出(取职位序列,服务端已翻译中文)
|
||||
ROSTER_EXPORT_PATH = os.path.join(SAVE_DIR, "员工花名册_桌面版.xlsx")
|
||||
ROSTER_DOWNLOAD_DIR = os.path.join(SAVE_DIR, "花名册下载")
|
||||
|
||||
# ==================== 每月正休规则(默认值,界面可覆盖) ====================
|
||||
DEFAULT_RULES = {
|
||||
"size_rest_days": 6, # 大小休 应休天数
|
||||
"fixed_rest_days": 5, # 固休 应休天数
|
||||
"quota_rest_days": 8, # 天数限额排休 上限
|
||||
}
|
||||
|
||||
# 集团总部职能部门(大小休)
|
||||
GROUP_HEADQUARTER_UNITS = (
|
||||
"财务管理部",
|
||||
"集团管理中心",
|
||||
"集团营建中心",
|
||||
)
|
||||
|
||||
# ==================== 排班接口 ====================
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
SHIFT_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_p_kq_count_SelectBanci/getExecutePageResult.mc"
|
||||
PAGE_MAX_SIZE = 500
|
||||
|
||||
# 排班休息日判定:当日班次名({日期}_bc_name)等于该值视为休息
|
||||
REST_SHIFT_NAME = "休息"
|
||||
@@ -0,0 +1,160 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""考勤月报封存检查 - 数据拉取(webhost 场景插件)
|
||||
|
||||
数据真源复用 desktop/shared(与桌面/影刀版单一真源一致),传入宿主构建的
|
||||
requests.Session / user_id 即可,不内置任何登录逻辑。
|
||||
session 由 webhost 宿主的共享登录态提供(RunContext.get_session / get_user_id)。
|
||||
"""
|
||||
import calendar
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Dict, List, Tuple
|
||||
|
||||
from webhost.backend.shared import org_export, roster_export_api, seal_data_export
|
||||
|
||||
from webhost.backend.plugins.seal_check import config
|
||||
|
||||
# hr_request_json:统一做全局重试(3次) + 登录态失效判定(复用桌面 shared 真源)
|
||||
hr_request_json = seal_data_export.hr_request_json
|
||||
|
||||
|
||||
# ==================== 通用工具 ====================
|
||||
def _clean(v) -> str:
|
||||
if v is None:
|
||||
return ""
|
||||
s = str(v).strip()
|
||||
if s.lower() in ("nan", "none", "nat"):
|
||||
return ""
|
||||
if s.endswith(".0"):
|
||||
s = s[:-2]
|
||||
return s
|
||||
|
||||
|
||||
def _norm_path(p: str) -> str:
|
||||
p = _clean(p).replace("\\", "/").strip("/")
|
||||
if p.startswith("集团/"):
|
||||
p = p[len("集团/"):]
|
||||
elif p == "集团":
|
||||
p = ""
|
||||
return p.strip("/")
|
||||
|
||||
|
||||
def last_month_ym(today: datetime = None) -> str:
|
||||
today = today or datetime.now()
|
||||
last_end = today.replace(day=1) - timedelta(days=1)
|
||||
return f"{last_end.year:04d}{last_end.month:02d}"
|
||||
|
||||
|
||||
# ==================== 1. 封存数据 ====================
|
||||
def fetch_seal_rows(session, user_id: str, yearmonth: str) -> List[dict]:
|
||||
rows = seal_data_export.fetch_all_seal(session, user_id, yearmonth)
|
||||
return seal_data_export._filter_by_unit(rows)
|
||||
|
||||
|
||||
# ==================== 2. 组织表 ====================
|
||||
def fetch_org_name_map(session) -> Dict[str, str]:
|
||||
"""组织全路径 -> 组织名称(用于解析组织类型)。"""
|
||||
rows = org_export.fetch_all_orgs(session)
|
||||
name_map: Dict[str, str] = {}
|
||||
for rec in rows:
|
||||
path = _norm_path(rec.get("pt_structure.ORG_FULL_PATH"))
|
||||
name = _clean(rec.get("pt_organzation.ORG_NAME"))
|
||||
if path and name:
|
||||
name_map[path] = name
|
||||
return name_map
|
||||
|
||||
|
||||
# ==================== 3. 花名册(导出接口,职位序列已翻译) ====================
|
||||
def fetch_roster_data(session) -> Tuple[Dict[str, str], List[dict]]:
|
||||
"""导出花名册(在职+离职)。返回 (seq_map, in_service_records)。"""
|
||||
import pandas as pd
|
||||
|
||||
path = roster_export_api.export_roster(
|
||||
output_path=config.ROSTER_EXPORT_PATH,
|
||||
download_dir=config.ROSTER_DOWNLOAD_DIR,
|
||||
template_name="员工基础信息",
|
||||
statuses=["在职", "离职"],
|
||||
)
|
||||
df = pd.read_excel(path, dtype=str)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
|
||||
seq_map: Dict[str, str] = {}
|
||||
in_service_records: List[dict] = []
|
||||
for _, r in df.iterrows():
|
||||
code = _clean(r.get("工号"))
|
||||
seq = _clean(r.get("职位序列"))
|
||||
if code:
|
||||
seq_map[code] = seq
|
||||
if _clean(r.get("在职状态")) == "在职":
|
||||
in_service_records.append({
|
||||
"工号": code,
|
||||
"姓名": _clean(r.get("姓名")),
|
||||
"所属单位": _clean(r.get("所属单位")),
|
||||
"一级部门": _clean(r.get("一级部门")),
|
||||
"二级部门": _clean(r.get("二级部门")),
|
||||
"三级部门": _clean(r.get("三级部门")),
|
||||
"四级部门": _clean(r.get("四级部门")),
|
||||
"五级部门": _clean(r.get("五级部门")),
|
||||
})
|
||||
return seq_map, in_service_records
|
||||
|
||||
|
||||
# ==================== 4. 排班(批量导出) ====================
|
||||
def fetch_shift_batch(session, user_id: str, yearmonth: str) -> Dict[str, int]:
|
||||
"""批量拉取某月全集团排班,返回 {工号: 应出勤天数}。
|
||||
|
||||
base_code 留空 = 全集团批量;每条记录 = 一个员工整月排班,
|
||||
逐日列 key 为 "YYYY-MM-DD_bc_name",休息日判定 bc_name == config.REST_SHIFT_NAME。
|
||||
"""
|
||||
ym = str(yearmonth)
|
||||
year, month = int(ym[:4]), int(ym[4:6])
|
||||
days_in_month = calendar.monthrange(year, month)[1]
|
||||
begin = f"{year:04d}-{month:02d}-01"
|
||||
end = f"{year:04d}-{month:02d}-{days_in_month:02d}"
|
||||
|
||||
all_rows: List[dict] = []
|
||||
page_no = 1
|
||||
while True:
|
||||
params = {
|
||||
"treecode": "cq37du", "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, "end": end, "bc_date": begin,
|
||||
"base_code": "", "staff_name": "",
|
||||
"start": str((page_no - 1) * config.PAGE_MAX_SIZE),
|
||||
"sortType": "", "sortName": "",
|
||||
"pageNo": page_no, "pageSize": config.PAGE_MAX_SIZE,
|
||||
}
|
||||
data = hr_request_json(session, "POST", config.SHIFT_URL, params, "排班批量")
|
||||
if data.get("state") != "1":
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
# 分页保护:pageCount 缺失/为 0 时不能提前 break,否则会静默截断数据
|
||||
page_count = data.get("pageCount") or 0
|
||||
if page_count and page_no >= page_count:
|
||||
break
|
||||
if len(page_list) < config.PAGE_MAX_SIZE:
|
||||
break
|
||||
page_no += 1
|
||||
|
||||
result: Dict[str, int] = {}
|
||||
for rec in all_rows:
|
||||
code = _clean(rec.get("base_code"))
|
||||
if not code:
|
||||
continue
|
||||
work_days = 0
|
||||
for d in range(1, days_in_month + 1):
|
||||
bc = _clean(rec.get(f"{year:04d}-{month:02d}-{d:02d}_bc_name"))
|
||||
if bc and bc != config.REST_SHIFT_NAME:
|
||||
work_days += 1
|
||||
result[code] = work_days
|
||||
return result
|
||||
|
||||
|
||||
# ==================== 5. 对比差异(检查3,接口待封装) ====================
|
||||
def fetch_compare_diffs(session, user_id: str, yearmonth: str) -> Tuple[List[dict], str]:
|
||||
"""考勤月报封存「对比」差异数据;接口未封装前返回空 + 提示。"""
|
||||
return [], "检查3「封存值是否最新」的对比接口尚未封装,本次跳过该检查,请在数据层补充接口后启用"
|
||||
@@ -0,0 +1,279 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""考勤月报封存检查 - 规则引擎与五项检查(webhost 场景插件)
|
||||
|
||||
与 plugins/seal_check/logic.py 保持同步(根级 plugins/ 为单一真源)。
|
||||
|
||||
规则完全由运行人员每月在界面录入的天数值驱动:
|
||||
- 固休:应休 = fixed_rest_days
|
||||
- 大小休:应休 = size_rest_days(实际允许 size_rest_days ~ 8 天区间)
|
||||
- 天数限额排休:应休 <= quota_rest_days(上限)
|
||||
"""
|
||||
import calendar
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime
|
||||
from typing import Dict, List
|
||||
|
||||
from webhost.backend.plugins.seal_check import config
|
||||
|
||||
# ==================== 异常名单统一列 ====================
|
||||
OUTPUT_COLUMNS = [
|
||||
"37工号", "姓名", "月报检查月份", "异常类型", "所属单位",
|
||||
"一级部门", "二级部门", "三级部门", "四级部门", "五级部门",
|
||||
]
|
||||
|
||||
TYPE_1 = "当月在职天数有差缺排班"
|
||||
TYPE_3 = "考勤封存非最新值,请重新封存"
|
||||
TYPE_4 = "出勤天数大于当月应出勤天数"
|
||||
TYPE_5 = "考勤月报未封存,请处理"
|
||||
|
||||
|
||||
# ==================== 规则引擎 ====================
|
||||
@dataclass
|
||||
class RestRule:
|
||||
rule_type: str # 大小休 / 固休 / 限额 / 未知
|
||||
days: int = None # 应休天数(限额为 None)
|
||||
max_days: int = None # 限额上限
|
||||
desc: str = "" # 规则描述(异常类型)
|
||||
|
||||
def validate(self, rest_days: int) -> bool:
|
||||
if self.rule_type == "固休":
|
||||
return rest_days == self.days
|
||||
if self.rule_type == "大小休":
|
||||
return self.days <= rest_days <= 8
|
||||
if self.rule_type == "限额":
|
||||
return rest_days <= self.max_days
|
||||
return True
|
||||
|
||||
|
||||
def _normalize_rest_days(v) -> int:
|
||||
try:
|
||||
s = str(v).strip()
|
||||
if s in ("", "nan", "None"):
|
||||
return -1
|
||||
if s.endswith(".0"):
|
||||
s = s[:-2]
|
||||
return int(float(s))
|
||||
except (TypeError, ValueError):
|
||||
return -1
|
||||
|
||||
|
||||
class LeaveRuleEngine:
|
||||
def __init__(self, size_rest_days=6, fixed_rest_days=5, quota_rest_days=8):
|
||||
self.size_rest_days = int(size_rest_days)
|
||||
self.fixed_rest_days = int(fixed_rest_days)
|
||||
self.quota_rest_days = int(quota_rest_days)
|
||||
|
||||
def query(self, unit: str, org_label: str = "", sequence: str = "") -> RestRule:
|
||||
if "技师" in sequence:
|
||||
return RestRule("限额", max_days=self.quota_rest_days,
|
||||
desc=f"当月排休不满足<={self.quota_rest_days}天规则")
|
||||
if unit == "金色湖畔事业部":
|
||||
return RestRule("固休", days=self.fixed_rest_days,
|
||||
desc=f"当月排休不满足={self.fixed_rest_days}天规则")
|
||||
if unit in config.GROUP_HEADQUARTER_UNITS:
|
||||
return RestRule("大小休", days=self.size_rest_days,
|
||||
desc=f"当月排休不满足>={self.size_rest_days}天<=8天规则")
|
||||
if unit == "金色印象事业部":
|
||||
if "事业部" in org_label:
|
||||
return RestRule("大小休", days=self.size_rest_days,
|
||||
desc=f"当月排休不满足>={self.size_rest_days}天<=8天规则")
|
||||
return RestRule("固休", days=self.fixed_rest_days,
|
||||
desc=f"当月排休不满足={self.fixed_rest_days}天规则")
|
||||
return RestRule("未知")
|
||||
|
||||
def check(self, unit, org_label, sequence, rest_days):
|
||||
rule = self.query(unit, org_label, sequence)
|
||||
days = _normalize_rest_days(rest_days)
|
||||
if rule.rule_type == "未知" or days < 0:
|
||||
return False, rule, days
|
||||
return (not rule.validate(days)), rule, days
|
||||
|
||||
|
||||
# ==================== 检查工具 ====================
|
||||
def _clean(v) -> str:
|
||||
if v is None:
|
||||
return ""
|
||||
s = str(v).strip()
|
||||
if s.lower() in ("nan", "none", "nat"):
|
||||
return ""
|
||||
if s.endswith(".0"):
|
||||
s = s[:-2]
|
||||
return s
|
||||
|
||||
|
||||
def _to_int(v, default=0) -> int:
|
||||
s = _clean(v)
|
||||
if not s:
|
||||
return default
|
||||
try:
|
||||
return int(float(s))
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def _norm_path(p: str) -> str:
|
||||
p = _clean(p).replace("\\", "/").strip("/")
|
||||
if p.startswith("集团/"):
|
||||
p = p[len("集团/"):]
|
||||
elif p == "集团":
|
||||
p = ""
|
||||
return p.strip("/")
|
||||
|
||||
|
||||
def _parse_date(s):
|
||||
s = _clean(s)[:10]
|
||||
if not s:
|
||||
return None
|
||||
try:
|
||||
return datetime.strptime(s, "%Y-%m-%d").date()
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _row_from_seal(rec: dict, month_display: str, abnormal_type: str) -> dict:
|
||||
return {
|
||||
"37工号": _clean(rec.get("base_code")),
|
||||
"姓名": _clean(rec.get("staff_name")),
|
||||
"月报检查月份": month_display,
|
||||
"异常类型": abnormal_type,
|
||||
"所属单位": _clean(rec.get("BELONG_UNIT_ORG_NAME")),
|
||||
"一级部门": _clean(rec.get("DEPT_ORG_ONE")),
|
||||
"二级部门": _clean(rec.get("DEPT_ORG_TWO")),
|
||||
"三级部门": _clean(rec.get("DEPT_ORG_THREE")),
|
||||
"四级部门": _clean(rec.get("DEPT_ORG_FOUR")),
|
||||
"五级部门": _clean(rec.get("DEPT_ORG_FIVE")),
|
||||
}
|
||||
|
||||
|
||||
def _resolve_org_label(rec: dict, org_name_map: Dict[str, str]) -> str:
|
||||
"""解析员工组织类型标签:部门全路径匹配组织表组织全路径 → 组织名称。
|
||||
匹配失败回退取路径最后一个节点名。"""
|
||||
path = _norm_path(rec.get("ORG_FULL_PATH"))
|
||||
if path and path in org_name_map:
|
||||
return org_name_map[path]
|
||||
if path:
|
||||
return path.split("/")[-1]
|
||||
return ""
|
||||
|
||||
|
||||
# ==================== 检查1:在职天数是否均排班 ====================
|
||||
def _calc_working_days(rec: dict, year: int, month: int) -> int:
|
||||
"""按需求文档规则计算当月在职天数(基于入职/离职时间)。"""
|
||||
month_days = calendar.monthrange(year, month)[1]
|
||||
first = date(year, month, 1)
|
||||
last = date(year, month, month_days)
|
||||
join_d = _parse_date(rec.get("join_date"))
|
||||
leave_d = _parse_date(rec.get("leaveOffice_date"))
|
||||
|
||||
def in_service(d):
|
||||
if join_d and d < join_d:
|
||||
return False
|
||||
if leave_d and d > leave_d:
|
||||
return False
|
||||
return True
|
||||
|
||||
in_first, in_last = in_service(first), in_service(last)
|
||||
if in_first and in_last:
|
||||
# 1号和月末都在职 = 全月在职,在职天数即为当月自然天数
|
||||
return month_days
|
||||
if in_first and not in_last:
|
||||
return (leave_d - first).days if leave_d else 0
|
||||
if not in_first and in_last:
|
||||
return (last - join_d).days if join_d else 0
|
||||
# 首尾都不在职:仅当入职、离职日期都落在本月内时按差计算;否则返回 0
|
||||
if join_d and leave_d and first <= join_d <= last and first <= leave_d <= last:
|
||||
return (leave_d - join_d).days
|
||||
return 0
|
||||
|
||||
|
||||
def check1(seal_rows: List[dict], year: int, month: int) -> List[dict]:
|
||||
month_display = f"{year:04d}-{month:02d}"
|
||||
rows = []
|
||||
for rec in seal_rows:
|
||||
wd = _calc_working_days(rec, year, month)
|
||||
yq = _to_int(rec.get("kq_stat_month_yq_work_day_in")) # 在职应勤工作日
|
||||
rest = _to_int(rec.get("kq_stat_cal_ext9")) # 休息天
|
||||
if wd - (yq + rest) != 0:
|
||||
rows.append(_row_from_seal(rec, month_display, TYPE_1))
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 检查2:排休天数验证 ====================
|
||||
def check2(seal_rows, org_name_map, seq_map, engine, year, month) -> List[dict]:
|
||||
month_display = f"{year:04d}-{month:02d}"
|
||||
rows = []
|
||||
for rec in seal_rows:
|
||||
unit = _clean(rec.get("BELONG_UNIT_ORG_NAME"))
|
||||
org_label = _resolve_org_label(rec, org_name_map)
|
||||
seq = seq_map.get(_clean(rec.get("base_code")), "")
|
||||
abnormal, rule, _days = engine.check(unit, org_label, seq, rec.get("kq_stat_cal_ext9"))
|
||||
if abnormal:
|
||||
rows.append(_row_from_seal(rec, month_display, rule.desc))
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 检查3:封存值是否为最新值 ====================
|
||||
def check3(diff_rows, seal_rows, diff_fields, year, month) -> List[dict]:
|
||||
month_display = f"{year:04d}-{month:02d}"
|
||||
if not diff_rows:
|
||||
return []
|
||||
seal_by_code = {_clean(r.get("base_code")): r for r in seal_rows}
|
||||
rows = []
|
||||
for dr in diff_rows:
|
||||
code = _clean(dr.get("base_code")) or _clean(dr.get("工号"))
|
||||
if any(_clean(dr.get(f)) for f in diff_fields) and code in seal_by_code:
|
||||
rows.append(_row_from_seal(seal_by_code[code], month_display, TYPE_3))
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 检查4:出勤天数验证 ====================
|
||||
def check4(seal_rows, shift_map, year, month) -> List[dict]:
|
||||
month_display = f"{year:04d}-{month:02d}"
|
||||
rows = []
|
||||
for rec in seal_rows:
|
||||
code = _clean(rec.get("base_code"))
|
||||
expected = shift_map.get(code)
|
||||
if expected is None:
|
||||
continue
|
||||
attend = _to_int(rec.get("kq_stat_cal_ext19"), default=-1) # 实际出勤天日
|
||||
if attend >= 0 and attend > expected:
|
||||
rows.append(_row_from_seal(rec, month_display, TYPE_4))
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 检查5:未封存名单 ====================
|
||||
def check5(seal_rows, in_service_records, year, month) -> List[dict]:
|
||||
month_display = f"{year:04d}-{month:02d}"
|
||||
seal_codes = {_clean(r.get("base_code")) for r in seal_rows}
|
||||
rows = []
|
||||
for rec in in_service_records:
|
||||
code = _clean(rec.get("工号"))
|
||||
if code and code not in seal_codes:
|
||||
rows.append({
|
||||
"37工号": code, "姓名": _clean(rec.get("姓名")),
|
||||
"月报检查月份": month_display, "异常类型": TYPE_5,
|
||||
"所属单位": _clean(rec.get("所属单位")),
|
||||
"一级部门": _clean(rec.get("一级部门")),
|
||||
"二级部门": _clean(rec.get("二级部门")),
|
||||
"三级部门": _clean(rec.get("三级部门")),
|
||||
"四级部门": _clean(rec.get("四级部门")),
|
||||
"五级部门": _clean(rec.get("五级部门")),
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 汇总编排 ====================
|
||||
def run_all_checks(*, seal_rows, org_name_map, seq_map, in_service_records,
|
||||
shift_map, engine, year, month, diff_rows=None, diff_fields=None,
|
||||
notes=None) -> dict:
|
||||
notes = list(notes or [])
|
||||
results = {
|
||||
1: check1(seal_rows, year, month),
|
||||
2: check2(seal_rows, org_name_map, seq_map, engine, year, month),
|
||||
3: check3(diff_rows or [], seal_rows, diff_fields or [], year, month),
|
||||
4: check4(seal_rows, shift_map, year, month),
|
||||
5: check5(seal_rows, in_service_records, year, month),
|
||||
}
|
||||
if diff_rows is None:
|
||||
notes.append("检查3「封存值是否为最新值」:对比接口数据未提供,本次跳过该检查")
|
||||
return {"rows": results, "notes": notes}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "seal_check",
|
||||
"name": "考勤月报封存检查",
|
||||
"version": "1.0.0",
|
||||
"description": "填写每月正休规则,一键执行五项检查并导出多 Sheet Excel 报告",
|
||||
"category": "考勤",
|
||||
"icon": "",
|
||||
"platform": "hr",
|
||||
"uses_month": true,
|
||||
"capabilities": ["seal_check", "hr.seal_check"],
|
||||
"permissions": {
|
||||
"platforms": ["hr"]
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"fixed_rest_days": { "type": "integer", "title": "固休应休天数", "default": 5, "description": "" },
|
||||
"size_rest_days": { "type": "integer", "title": "大小休应休天数", "default": 6, "description": "" },
|
||||
"quota_rest_days": { "type": "integer", "title": "限额排休上限", "default": 8, "description": "" }
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""考勤月报封存检查 - Excel 报告导出(webhost 场景插件)
|
||||
|
||||
与 plugins/seal_check/report.py 保持同步(根级 plugins/ 为单一真源)。
|
||||
|
||||
输出:考勤月报封存检查_{月份}_{时间戳}.xlsx(汇总 + 检查1~5 Sheet,空 Sheet 保留表头)
|
||||
"""
|
||||
import os
|
||||
from datetime import datetime
|
||||
from typing import Dict, List
|
||||
|
||||
from webhost.backend.plugins.seal_check import config
|
||||
from webhost.backend.plugins.seal_check.logic import OUTPUT_COLUMNS, TYPE_1, TYPE_3, TYPE_4, TYPE_5
|
||||
|
||||
CHECK_TAB_TITLES = {
|
||||
1: "检查1_在职天数排班异常",
|
||||
2: "检查2_排休天数异常",
|
||||
3: "检查3_封存非最新值",
|
||||
4: "检查4_出勤天数异常",
|
||||
5: "检查5_未封存名单",
|
||||
}
|
||||
|
||||
CHECK_DESCRIPTIONS = {
|
||||
1: TYPE_1,
|
||||
2: "当月排休不满足……天规则(动态)",
|
||||
3: TYPE_3,
|
||||
4: TYPE_4,
|
||||
5: TYPE_5,
|
||||
}
|
||||
|
||||
|
||||
def export_report(rows_map: Dict[int, List[dict]], month: str, notes: List[str] = None,
|
||||
save_dir: str = None) -> str:
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
raise RuntimeError("缺少 pandas / openpyxl 依赖,无法导出 Excel")
|
||||
|
||||
save_dir = save_dir or config.SAVE_DIR
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
path = os.path.join(save_dir, f"考勤月报封存检查_{month}_{ts}.xlsx")
|
||||
|
||||
with pd.ExcelWriter(path, engine="openpyxl") as writer:
|
||||
summary = []
|
||||
for i in range(1, 6):
|
||||
n = len(rows_map.get(i, []))
|
||||
summary.append({
|
||||
"检查项": CHECK_TAB_TITLES[i],
|
||||
"命中条数": n,
|
||||
"异常类型": CHECK_DESCRIPTIONS[i],
|
||||
"说明": "详见对应 Sheet" if n else "无异常",
|
||||
})
|
||||
if notes:
|
||||
summary.append({"检查项": "备注", "命中条数": len(notes),
|
||||
"异常类型": "", "说明": ";".join(notes)})
|
||||
pd.DataFrame(summary).to_excel(writer, sheet_name="汇总", index=False)
|
||||
|
||||
for i in range(1, 6):
|
||||
df = pd.DataFrame(rows_map.get(i, []), columns=OUTPUT_COLUMNS)
|
||||
df.to_excel(writer, sheet_name=CHECK_TAB_TITLES[i], index=False)
|
||||
|
||||
return path
|
||||
Reference in New Issue
Block a user