refactor: 重构影刀脚本目录结构,按需求单归档并清理冗余文件
- 将影刀脚本从按系统分组的oa/hr/employer_insurance等目录迁移到XQ00xx命名的需求单目录,与docs/需求单一一对应 - 删除原employer_insurance目录下冗余的export_change_sheet.py,将其迁移到XQ0002目录 - 清理已废弃的XQ0020标准化门店手续相关文档与XQ0021离职电子签重复文档 - 更新需求单总索引、README文档与影刀脚本目录说明,修正路径引用 - 修复雇主险导入模板校验逻辑与增员导入异常捕获逻辑
This commit is contained in:
@@ -0,0 +1,753 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: add_sub_import.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-23
|
||||
@Description: 雇主险流程「步骤3:增减员导入」(影刀版,单文件自包含)——在 HR「待增减人员」页面
|
||||
执行增员/减员导入(复刻 aa.md 与 app 版 add_sub_import 的操作流程):
|
||||
访问页面 -> 更多操作 -> 增员导入/减员导入 -> 上传文件 -> 下一步 -> 下一步 -> 关闭。
|
||||
登录态复用「37duHR登录」写入的共享 hr_cookies.json(只读不补登)。
|
||||
@Version: 1.4.0
|
||||
- v1.4.0:钉钉推送改为汇总 + 异常名单拆分多条消息(汇总一条,增员/减员异常名单各一条,
|
||||
名单过长自动分批),仅推接口返回的业务结果。
|
||||
- v1.3.0:导入异常消息写入影刀全局变量 messages(块格式分组列表),供「37du钉钉群机器人推送」指令直接推送;无异常时写入完成提示。
|
||||
- v1.2.0:监听第二个「下一步」(真正导入内容)触发的 getTmpDataPage.mc,捕获并上报导入返回的全部异常;第一个「下一步」为格式校验,不做处理。
|
||||
- v1.1.0:上传表格后监听 getTmpDataPage.mc 解析接口,捕获并上报返回的全部异常(如重复参保),不中断流程。
|
||||
|
||||
设计说明(与 yingdao 下其它单文件版一致):
|
||||
- 单文件自包含,可放任意目录直接运行(含 App 项目目录或影刀环境)。
|
||||
- 登录态复用共享 hr_cookies.json(缺失/失效引导先运行「37duHR登录」指令,不自动补登)。
|
||||
- 按类别传参(category_names 列表,空/None=全部类别),导入文件取各类别文件夹内的
|
||||
商业保险增员导入.xlsx / 商业保险减员导入.xlsx(由 schedule 步骤生成)。
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install DrissionPage
|
||||
|
||||
环境变量(.env 文件或系统变量,可选):
|
||||
employer_insurance_base_dir = 雇主险文件目录(默认 D:\\资料\\人资\\雇主险)
|
||||
|
||||
运行:直接执行本文件,按 __main__ 中的示例传参(增员/减员 + 类别列表)调用 main()
|
||||
main(category_names=['三十七度']) 或 import_employee_change(import_type, category_names)
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import traceback
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||
# 任一依赖缺失会立即报错退出,避免运行到中途才发现缺库
|
||||
try:
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
from dotenv import load_dotenv
|
||||
except ImportError as _import_err:
|
||||
raise ImportError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install DrissionPage\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
) from _import_err
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging) ====================
|
||||
class _PrintLogger:
|
||||
def debug(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def info(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def warning(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def error(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def exception(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 影刀全局变量(消息/结果写 glv,生成与发送解耦) ====================
|
||||
# 约定见 yingdao/README.md 5.2:业务脚本只生成消息文本写全局变量,
|
||||
# 发送一律由「37du钉钉群机器人推送」指令(yingdao/share/dingtalk_robot.py)完成。
|
||||
def _set_glv(name, value):
|
||||
"""写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
|
||||
try:
|
||||
glv[name] = value
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置(与 app 版 config 一致) ====================
|
||||
BASE_DIR = os.getenv("employer_insurance_base_dir") or r"D:\资料\人资\雇主险"
|
||||
|
||||
# 共享 HR 登录态:由「37duHR登录」指令(yingdao/share/hr_login.py)写入
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation'
|
||||
)
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- HR 系统「待增减人员」页面(与 app 版 ehr/common/config 一致) ----------
|
||||
ADD_SUB_URL = (
|
||||
"https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic"
|
||||
"#ajax&1&nworktoday-40175-13664-23874-98879&nworktoday-40175-13664"
|
||||
"|/RedseaPlatform/hrRoster/7984ae1a-16ec-11ed-bea9-822ff8ed5b28/"
|
||||
"getCustomCommonList.mc?menuName=待增减人员"
|
||||
)
|
||||
|
||||
# ---------- 四大类别(全流程按类别传参处理,与 app 版 config.CATEGORIES 一致) ----------
|
||||
CATEGORIES = [
|
||||
{"name": "三十七度", "folder": os.path.join(BASE_DIR, "三十七度")},
|
||||
{"name": "水庄餐饮", "folder": os.path.join(BASE_DIR, "水庄餐饮")},
|
||||
{"name": "湖畔酒店", "folder": os.path.join(BASE_DIR, "湖畔酒店")},
|
||||
{"name": "秒创传媒", "folder": os.path.join(BASE_DIR, "秒创传媒")},
|
||||
]
|
||||
|
||||
|
||||
# ---------- 类别辅助函数(全流程共用,与 app 版 config 一致) ----------
|
||||
def get_category(name):
|
||||
"""按名称获取类别配置(支持精确名或唯一前缀,如「湖畔」/「湖畔酒店」)。
|
||||
|
||||
Args:
|
||||
name: 类别名
|
||||
|
||||
Returns:
|
||||
类别配置 dict
|
||||
|
||||
Raises:
|
||||
ValueError: 未知名或前缀不唯一
|
||||
"""
|
||||
name = (name or "").strip()
|
||||
for c in CATEGORIES:
|
||||
if c["name"] == name:
|
||||
return c
|
||||
matched = [c for c in CATEGORIES if c["name"].startswith(name)]
|
||||
if len(matched) == 1:
|
||||
return matched[0]
|
||||
raise ValueError(f"未知类别:{name},可选:{[c['name'] for c in CATEGORIES]}")
|
||||
|
||||
|
||||
def category_import_add_file(category):
|
||||
"""类别「增员导入」文件路径(放在类别文件夹内,由 schedule 步骤生成)。"""
|
||||
return os.path.join(category["folder"], "商业保险增员导入.xlsx")
|
||||
|
||||
|
||||
def category_import_sub_file(category):
|
||||
"""类别「减员导入」文件路径(放在类别文件夹内,由 schedule 步骤生成)。"""
|
||||
return os.path.join(category["folder"], "商业保险减员导入.xlsx")
|
||||
|
||||
|
||||
# ---------- 流程步骤文案常量(与 app 版 add_sub_import 一致) ----------
|
||||
BTN_MORE = "更多操作" # 「更多操作」下拉按钮
|
||||
MENU_ADD = "增员导入" # 下拉菜单:增员导入
|
||||
MENU_SUB = "减员导入" # 下拉菜单:减员导入
|
||||
BTN_NEXT = "下一步" # 导入弹窗「下一步」按钮(第 2/3 步)
|
||||
BTN_CLOSE = "关闭" # 导入完成弹窗「关闭」按钮
|
||||
|
||||
# 通用等待秒数
|
||||
WAIT_SHORT = 0.6
|
||||
WAIT_MID = 2.0
|
||||
WAIT_LONG = 4.0
|
||||
|
||||
# ---------- 接口监听:第二步「下一步」导入内容结果(getTmpDataPage.mc) ----------
|
||||
# 第一个「下一步」为格式校验(不做处理);点击第二个「下一步」(真正导入内容)后,
|
||||
# HR 系统会 POST getTmpDataPage.mc 返回导入结果,其中 datas[].imp_fixed_msg 为逐行导入结果说明:
|
||||
# 异常行如「存在已参保的人员,不允许重复增员!」;成功行返回「导入成功;」(不纳入异常上报)。
|
||||
TMP_DATA_API_MARK = "getTmpDataPage.mc" # 导入内容结果接口(URL 子串过滤)
|
||||
TMP_DATA_STATE_OK = "1" # 导入内容结果接口 state 成功值
|
||||
TMP_DATA_WAIT = 8.0 # 等待导入结果接口响应的超时秒数
|
||||
|
||||
|
||||
class LoginRequiredError(Exception):
|
||||
"""打开页面被重定向到登录页(cookies 缺失或失效)。"""
|
||||
|
||||
|
||||
class ElementNotFoundError(Exception):
|
||||
"""页面元素/控件未找到(页面结构变化或加载超时)。
|
||||
|
||||
用于区分「UI 状态类失败」(页面没加载出来、元素定位器失效)与其它运行时错误,
|
||||
便于调用方针对性地重试或提示人工介入。
|
||||
"""
|
||||
|
||||
|
||||
# ==================== 登录态(共享 cookies 文件) ====================
|
||||
def _load_shared_hr_cookies():
|
||||
"""读取共享 HR cookies 文件(由「37duHR登录」指令写入)。"""
|
||||
if os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
return None
|
||||
|
||||
|
||||
# ==================== 元素定位辅助(DrissionPage) ====================
|
||||
def _create_page():
|
||||
"""创建新的 ChromiumPage(统一配置,非无头)。"""
|
||||
co = ChromiumOptions()
|
||||
return ChromiumPage(co)
|
||||
|
||||
|
||||
def _click_text(page, text, timeout=10):
|
||||
"""按元素文本精确匹配并点击,找不到则抛错。"""
|
||||
ele = page.ele(f'xpath://*[normalize-space(text())="{text}"]', timeout=timeout)
|
||||
if not ele:
|
||||
raise ElementNotFoundError(f"未找到元素:{text}")
|
||||
ele.click()
|
||||
logger.info("已点击:%s", text)
|
||||
|
||||
|
||||
def _click_text_in(page, container, text, timeout=5):
|
||||
"""在指定容器内按文本匹配并点击。"""
|
||||
ele = container.ele(f'xpath:.//*[normalize-space(text())="{text}"]', timeout=timeout)
|
||||
if not ele:
|
||||
raise ElementNotFoundError(f"容器内未找到元素:{text}")
|
||||
ele.click()
|
||||
logger.info("已点击:%s", text)
|
||||
|
||||
|
||||
def _is_displayed(ele):
|
||||
"""判断元素是否可见且具有尺寸;异常时返回 False(保守不误判)。"""
|
||||
if ele is None:
|
||||
return False
|
||||
try:
|
||||
if not ele.states.is_displayed:
|
||||
return False
|
||||
w, h = ele.rect.size
|
||||
return w > 0 and h > 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
# ==================== 打开待增减人员页面并确保登录态 ====================
|
||||
def _ensure_logged_in(page):
|
||||
"""访问待增减人员页面;若被重定向到登录页,提示先运行「37duHR登录」指令。"""
|
||||
page.get(ADD_SUB_URL)
|
||||
time.sleep(WAIT_LONG)
|
||||
|
||||
# 登录页特征:存在用户名输入框
|
||||
if page.ele('@id=j_username', timeout=2):
|
||||
raise LoginRequiredError(
|
||||
"HR 登录态已失效/缺失。请先在影刀流程开头调用「37duHR登录」指令完成登录,"
|
||||
"或本地运行: python yingdao/share/hr_login.py")
|
||||
logger.info("已进入待增减人员页面:%s", page.url)
|
||||
|
||||
|
||||
# ==================== 增员/减员导入主流程(aa.md 步骤) ====================
|
||||
def _open_more_operations(page):
|
||||
"""点击「更多操作」按钮,展开下拉菜单(幂等,已展开则跳过)。"""
|
||||
# 若下拉菜单已可见,直接返回
|
||||
menu = page.ele('css:#custom-btn-ul', timeout=2)
|
||||
if menu and _is_displayed(menu):
|
||||
logger.info("「更多操作」下拉已展开,跳过")
|
||||
time.sleep(WAIT_SHORT)
|
||||
return menu
|
||||
|
||||
# 定位「更多操作」按钮(#more-btns 容器内的 btn-success dropdown-toggle)
|
||||
more_btn = page.ele('css:#more-btns button.dropdown-toggle', timeout=15)
|
||||
if not more_btn:
|
||||
more_btn = page.ele('css:button.btn-success.dropdown-toggle', timeout=5)
|
||||
if not more_btn:
|
||||
_click_text(page, BTN_MORE)
|
||||
else:
|
||||
more_btn.click()
|
||||
logger.info("已点击「更多操作」")
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
menu = page.ele('css:#custom-btn-ul', timeout=5)
|
||||
if not menu:
|
||||
raise ElementNotFoundError("未找到「更多操作」下拉菜单(#custom-btn-ul)")
|
||||
logger.info("「更多操作」下拉已展开")
|
||||
return menu
|
||||
|
||||
|
||||
def _choose_import_menu(page, menu_label):
|
||||
"""在下拉菜单中选择「增员导入」或「减员导入」。"""
|
||||
menu = _open_more_operations(page)
|
||||
_click_text_in(page, menu, menu_label)
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _upload_file(page, file_path):
|
||||
"""在导入弹窗中上传指定文件。
|
||||
|
||||
aa.md:选择文件夹按钮(glyphicon glyphicon-folder-open)会弹出文件选择器;
|
||||
这里直接用 DrissionPage 对 <input type="file"> 设置文件路径,跳过系统文件选择框。
|
||||
"""
|
||||
if not os.path.isfile(file_path):
|
||||
raise FileNotFoundError(f"导入文件不存在:{file_path}")
|
||||
|
||||
file_input = page.ele('css:input[name="file"]', timeout=15)
|
||||
if not file_input:
|
||||
raise ElementNotFoundError("未找到文件上传控件(input[name=file])")
|
||||
file_input.input(file_path)
|
||||
logger.info("已选择导入文件:%s", file_path)
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
|
||||
def _click_next(page):
|
||||
"""点击导入弹窗中的「下一步」按钮(btn-success 且可见)。"""
|
||||
btn = page.ele(
|
||||
'xpath://div[contains(@class,"sub-btn")]//button[contains(@class,"btn-success")'
|
||||
' and normalize-space(.)="下一步"]',
|
||||
timeout=10,
|
||||
)
|
||||
if not btn or not _is_displayed(btn):
|
||||
raise ElementNotFoundError("未找到可见的「下一步」按钮")
|
||||
btn.click()
|
||||
logger.info("已点击「下一步」")
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _click_close(page):
|
||||
"""点击导入完成弹窗中的「关闭」按钮。"""
|
||||
btn = page.ele(
|
||||
'xpath://div[contains(@class,"sub-btn")]//button[contains(@class,"btn-default")'
|
||||
' and normalize-space(.)="关闭"]',
|
||||
timeout=10,
|
||||
)
|
||||
if not btn or not _is_displayed(btn):
|
||||
raise ElementNotFoundError("未找到可见的「关闭」按钮")
|
||||
btn.click()
|
||||
logger.info("已点击「关闭」")
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 接口监听:上传表格后解析结果(getTmpDataPage.mc),捕获返回的全部异常
|
||||
# ---------------------------------------------------------------
|
||||
def _extract_json_response(req):
|
||||
"""从监听到的请求中解析 JSON 响应;解析失败返回 None。"""
|
||||
try:
|
||||
return req.response.json()
|
||||
except Exception:
|
||||
body = getattr(req.response, "body", None)
|
||||
if isinstance(body, (dict, list)):
|
||||
return body
|
||||
if not body:
|
||||
return None
|
||||
try:
|
||||
return json.loads(body)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _capture_import_exceptions(page, timeout=TMP_DATA_WAIT):
|
||||
"""监听「第二个下一步:真正导入内容」结果接口(getTmpDataPage.mc),捕获返回的全部异常。
|
||||
|
||||
第一个「下一步」为格式校验(不监听);点击第二个「下一步」真正导入内容后,
|
||||
HR 系统会 POST getTmpDataPage.mc 返回导入结果:
|
||||
- state="1" 表示接口正常;meg 为全局提示;
|
||||
- datas[].imp_fixed_msg 为逐行导入结果说明:异常行如「存在已参保的人员,不允许重复增员!」,
|
||||
成功行返回「导入成功;」(成功行不纳入异常上报)。
|
||||
本函数合并该接口全部(含分页/多次)响应中的异常(不逐行单独处理),供流程统一上报;
|
||||
成功行(「导入成功」)只统计成功行数,不纳入异常。
|
||||
|
||||
Returns:
|
||||
dict: {
|
||||
"captured": bool, # 是否捕获到解析接口响应
|
||||
"state": str, # 接口 state(未捕获到为空串)
|
||||
"meg": str, # 全局提示
|
||||
"listen_ok": bool, # 接口监听是否成功启动(False=未监听,结果不可信)
|
||||
"success_count": int, # 接口返回的导入成功行数
|
||||
"total_count": int, # 接口返回的需导入总行数(成功+异常,即本次需导入条数)
|
||||
"exceptions": [ # 全部异常明细
|
||||
{"staff_code":..., "staff_name":..., "insurance_name":..., "message":...}, ...
|
||||
],
|
||||
}
|
||||
"""
|
||||
result = {"captured": False, "state": "", "meg": "", "exceptions": [],
|
||||
"listen_ok": True, "success_count": 0, "total_count": 0}
|
||||
deadline = time.time() + timeout
|
||||
last_hit = time.time()
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
remain = max(0.0, deadline - time.time())
|
||||
req = page.listen.wait(timeout=min(0.5, remain))
|
||||
except Exception as e:
|
||||
logger.warning("监听 %s 接口异常:%s", TMP_DATA_API_MARK, e)
|
||||
break
|
||||
if req is None:
|
||||
# 0.5s 无新响应:若已捕获过解析响应,再确认一个间隔后结束,合并所有分页/多次返回的异常
|
||||
if result["captured"] and time.time() - last_hit >= 1.0:
|
||||
break
|
||||
continue
|
||||
if not hasattr(req, "url"):
|
||||
continue
|
||||
if TMP_DATA_API_MARK not in (req.url or ""):
|
||||
continue
|
||||
resp = _extract_json_response(req)
|
||||
if not isinstance(resp, dict):
|
||||
continue
|
||||
result["captured"] = True
|
||||
last_hit = time.time()
|
||||
state = str(resp.get("state", "")).strip()
|
||||
if state:
|
||||
result["state"] = state
|
||||
meg = str(resp.get("meg", "") or "").strip()
|
||||
if meg:
|
||||
result["meg"] = meg
|
||||
for item in resp.get("datas") or []:
|
||||
item = item or {}
|
||||
msg = str(item.get("imp_fixed_msg", "") or "").strip()
|
||||
if not msg:
|
||||
continue
|
||||
# 接口返回的每一行即本次调度的一条需导入记录,全部计入需导入总条数
|
||||
result["total_count"] += 1
|
||||
# HR 对导入成功的行同样返回「导入成功;」等固定文案,成功行只统计数量,
|
||||
# 不纳入异常(否则会被误报为异常,如「异常:导入成功;」)
|
||||
if "导入成功" in msg:
|
||||
result["success_count"] += 1
|
||||
continue
|
||||
result["exceptions"].append({
|
||||
"staff_code": str(item.get("imp_assi_staff_code_ext_table_field_base_id", "") or ""),
|
||||
"staff_name": str(item.get("imp_assi_staff_name_ext_table_field_base_id", "") or ""),
|
||||
"insurance_name": str(item.get("ext_insurance_name", "") or ""),
|
||||
"message": msg,
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
def _import_one(page, category, menu_label, file_path=None):
|
||||
"""对单个类别执行一次导入(更多操作 -> 选菜单 -> 上传 -> 下一步 -> 下一步 -> 关闭)。
|
||||
|
||||
第一个「下一步」为格式校验(不做处理);第二个「下一步」真正导入内容时会请求
|
||||
getTmpDataPage.mc,监听该接口捕获导入返回的全部异常;异常仅记录并上报,不中断导入流程。
|
||||
|
||||
Returns:
|
||||
dict: 导入结果接口捕获结果(含 exceptions 全部异常明细),见 _capture_import_exceptions。
|
||||
"""
|
||||
file_path = file_path or (
|
||||
category_import_add_file(category) if menu_label == MENU_ADD
|
||||
else category_import_sub_file(category))
|
||||
if not os.path.isfile(file_path):
|
||||
raise FileNotFoundError(f"导入文件不存在:{file_path}")
|
||||
|
||||
logger.info("===== 类别[%s] 开始%s,文件:%s =====", category["name"], menu_label, file_path)
|
||||
_choose_import_menu(page, menu_label)
|
||||
_upload_file(page, file_path)
|
||||
|
||||
_click_next(page) # 第一步:下一步(格式校验,不做处理)
|
||||
|
||||
# 第二步:点击「下一步」真正导入内容;同时监听 getTmpDataPage.mc 接口,捕获导入返回的全部异常
|
||||
# 监听启动失败必须上报:若静默继续,未捕获到异常会被误报为「正常」,产生假成功
|
||||
listen_ok = True
|
||||
try:
|
||||
page.listen.start(TMP_DATA_API_MARK)
|
||||
except Exception as e:
|
||||
listen_ok = False
|
||||
logger.error("启动 %s 接口监听失败,无法捕获导入结果:%s", TMP_DATA_API_MARK, e)
|
||||
try:
|
||||
_click_next(page)
|
||||
import_result = _capture_import_exceptions(page)
|
||||
import_result["listen_ok"] = listen_ok
|
||||
finally:
|
||||
try:
|
||||
page.listen.stop()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 上报:全部异常逐条打日志
|
||||
if import_result["exceptions"]:
|
||||
logger.error("类别[%s] %s:导入返回 %d 条异常:",
|
||||
category["name"], menu_label, len(import_result["exceptions"]))
|
||||
for exc in import_result["exceptions"]:
|
||||
logger.error(" - [%s/%s] 方案[%s]:%s",
|
||||
exc["staff_code"], exc["staff_name"], exc["insurance_name"], exc["message"])
|
||||
elif not import_result.get("listen_ok", True):
|
||||
logger.error("类别[%s] %s:接口监听启动失败,无法确认导入结果,请人工核对",
|
||||
category["name"], menu_label)
|
||||
elif import_result["captured"] and import_result["state"] != TMP_DATA_STATE_OK:
|
||||
logger.error("类别[%s] %s:导入接口 state=%s(meg=%s),导入可能失败",
|
||||
category["name"], menu_label, import_result["state"], import_result["meg"])
|
||||
elif not import_result["captured"]:
|
||||
logger.warning("类别[%s] %s:未捕获到导入结果接口响应,无法确认导入结果",
|
||||
category["name"], menu_label)
|
||||
else:
|
||||
logger.info("类别[%s] %s:导入成功 %s 人,无异常",
|
||||
category["name"], menu_label, import_result.get("success_count", 0))
|
||||
|
||||
_click_close(page) # 第三步:关闭
|
||||
logger.info("===== 类别[%s] %s完成 =====", category["name"], menu_label)
|
||||
return import_result
|
||||
|
||||
|
||||
# ==================== 钉钉群消息生成(写入全局变量,由「37du钉钉群机器人推送」指令发送) ====================
|
||||
def _build_group_messages(import_type, categories, results, exception_count):
|
||||
"""构建钉钉群机器人推送消息(块格式分组列表 [{title, blocks, status}])。
|
||||
|
||||
拆分为多条独立消息推送(避免异常名单过多时单条消息过长):
|
||||
1. 汇总:标题「雇主险增减员操作完成」,正文为需增员/减员条数、导入成功/失败条数;
|
||||
2. 增员导入异常名单(接口返回的业务异常明细);
|
||||
3. 减员导入异常名单。
|
||||
某操作无异常则不发对应异常名单消息(全部成功时只有 1 条汇总);
|
||||
单条异常名单内异常再多,也会由「37du钉钉群机器人推送」指令按批自动分批发送。
|
||||
仅推送接口返回的业务结果(成功/异常);代码/流程异常(error)、或接口未返回结果
|
||||
(captured=False / state!=1)的类别不推送、也不计入汇总,只报错进日志;
|
||||
全部类别均无业务结果 → 返回空列表,不推送。
|
||||
results 每项可带 "menu" 字段(增员导入/减员导入),main() 合并增/减员时使用。
|
||||
"""
|
||||
# 按菜单(增员导入/减员导入)分组统计接口返回的业务结果,仅统计接口确认成功的类别
|
||||
group_stats = {} # menu -> {"total":, "success":, "fail":, "excs": [(category, exc), ...]}
|
||||
for r in results:
|
||||
if r.get("error") or not r.get("captured") or r.get("state") != TMP_DATA_STATE_OK:
|
||||
continue
|
||||
menu = r.get("menu") or import_type
|
||||
stat = group_stats.setdefault(
|
||||
menu, {"total": 0, "success": 0, "fail": 0, "excs": []})
|
||||
excs = r.get("exceptions") or []
|
||||
category = r.get("category") or ""
|
||||
stat["total"] += r.get("total_count") or (len(excs) + (r.get("success_count") or 0))
|
||||
stat["success"] += r.get("success_count") or 0
|
||||
stat["fail"] += len(excs)
|
||||
stat["excs"].extend((category, exc) for exc in excs)
|
||||
|
||||
if not group_stats:
|
||||
# 全部类别均为代码异常或接口未返回结果:不推送,报错交给日志
|
||||
return []
|
||||
|
||||
add_stat = group_stats.get(MENU_ADD, {"total": 0, "success": 0, "fail": 0, "excs": []})
|
||||
sub_stat = group_stats.get(MENU_SUB, {"total": 0, "success": 0, "fail": 0, "excs": []})
|
||||
|
||||
# 标题:按实际分组自动带操作名(增+减合并为「增减员」,单类型为「增员/减员」)
|
||||
ops = []
|
||||
if add_stat["total"] or add_stat["excs"]:
|
||||
ops.append("增员")
|
||||
if sub_stat["total"] or sub_stat["excs"]:
|
||||
ops.append("减员")
|
||||
title = "雇主险{}操作完成".format("".join(ops) if ops else import_type)
|
||||
|
||||
# 汇总块(本次调度需导入条数 / 导入成功 / 失败条数,均取接口返回的业务结果)
|
||||
summary = (
|
||||
"**本次调度需增员 {} 条,减员 {} 条**\n\n"
|
||||
"其中增员导入成功 {} 条,失败 {} 条\n\n"
|
||||
"其中减员导入成功 {} 条,失败 {} 条".format(
|
||||
add_stat["total"], sub_stat["total"],
|
||||
add_stat["success"], add_stat["fail"],
|
||||
sub_stat["success"], sub_stat["fail"],
|
||||
)
|
||||
)
|
||||
messages = [{
|
||||
"title": title,
|
||||
"blocks": [summary],
|
||||
# 有业务异常 → 橙色 warning(提醒查看下方异常名单);全部成功 → 绿色 success
|
||||
"status": "warning" if (add_stat["fail"] or sub_stat["fail"]) else "success",
|
||||
}]
|
||||
|
||||
# 增员/减员异常名单各拆一条独立消息(名单再长由推送指令按批自动分批发送)
|
||||
for menu, stat in ((MENU_ADD, add_stat), (MENU_SUB, sub_stat)):
|
||||
if not stat["excs"]:
|
||||
continue
|
||||
exc_blocks = []
|
||||
for category, exc in stat["excs"]:
|
||||
exc_blocks.append(
|
||||
"**🔹 {} / {}**\n\n"
|
||||
"> 工号:{}\n\n"
|
||||
"> 姓名:{}\n\n"
|
||||
"> 方案:{}\n\n"
|
||||
"> 异常:{}".format(
|
||||
category,
|
||||
exc.get("staff_name", ""),
|
||||
exc.get("staff_code", ""),
|
||||
exc.get("staff_name", ""),
|
||||
exc.get("insurance_name", "") or "-",
|
||||
exc.get("message", ""),
|
||||
)
|
||||
)
|
||||
messages.append({
|
||||
"title": "【{}】异常名单({} 条)".format(menu, stat["fail"]),
|
||||
"blocks": exc_blocks,
|
||||
"status": "error",
|
||||
})
|
||||
return messages
|
||||
|
||||
|
||||
def _write_group_messages_glv(import_type, categories, results, exception_count):
|
||||
"""把增/减员导入结果写入影刀全局变量 messages,供「37du钉钉群机器人推送」指令读取推送。
|
||||
|
||||
仅推送接口返回的业务结果(成功/异常);代码/流程异常或接口未返回结果只报错进日志,不推送业务群。
|
||||
全部类别均无业务结果时 messages 为空列表,推送指令不会真正发送。
|
||||
"""
|
||||
messages = _build_group_messages(import_type, categories, results, exception_count)
|
||||
_set_glv("messages", messages)
|
||||
biz_exceptions = sum(len(r.get("exceptions") or []) for r in results)
|
||||
# 未确认结果:代码/流程异常、或接口未返回成功(captured=False/state!=1),均只报错不推送
|
||||
unconfirmed = sum(1 for r in results
|
||||
if not r.get("exceptions")
|
||||
and (r.get("error") or not r.get("captured")
|
||||
or r.get("state") != TMP_DATA_STATE_OK))
|
||||
if biz_exceptions:
|
||||
logger.error("汇总消息已写入全局变量 messages:共 %d 条业务异常(由「37du钉钉群机器人推送」指令发送)",
|
||||
biz_exceptions)
|
||||
if unconfirmed:
|
||||
logger.error("另有 %d 个类别未确认导入结果(代码/流程异常或接口未返回),已报错、不推送业务群,"
|
||||
"请查看控制台/日志处理", unconfirmed)
|
||||
if not biz_exceptions and not unconfirmed:
|
||||
logger.info("完成汇总消息已写入全局变量 messages(由「37du钉钉群机器人推送」指令发送)")
|
||||
|
||||
|
||||
# ==================== 对外入口(函数传参调用,支持多类别) ====================
|
||||
# 参数兼容「增员/减员」短名 与「增员导入/减员导入」菜单全名
|
||||
_IMPORT_TYPE_MAP = {
|
||||
"增员": MENU_ADD,
|
||||
"减员": MENU_SUB,
|
||||
MENU_ADD: MENU_ADD,
|
||||
MENU_SUB: MENU_SUB,
|
||||
}
|
||||
|
||||
|
||||
def import_employee_change(import_type="增员", category_names=None, file_path=None):
|
||||
"""执行增员/减员导入(可一次传入一个或多个类别,复用同一浏览器)。
|
||||
|
||||
Args:
|
||||
import_type: "增员" 或 "减员"(也兼容 "增员导入"/"减员导入"),默认增员。
|
||||
category_names: 类别名列表(如 ["三十七度", "湖畔酒店"]),
|
||||
空列表 / None 表示处理全部类别。
|
||||
file_path: 要上传的文件路径;若传入则对每个类别使用同一文件(覆盖类别解析);
|
||||
不传则按类别文件夹取 schedule 步骤生成的 商业保险增员/减员导入.xlsx。
|
||||
|
||||
Returns:
|
||||
dict: {
|
||||
"success": bool, # 全部类别流程是否均完成
|
||||
"import_type": str, # 菜单文案(增员导入/减员导入)
|
||||
"categories": [str], # 类别名列表
|
||||
"results": [dict], # 每类别的解析捕获结果(见 _capture_import_exceptions);
|
||||
# 类别流程失败时含 error(错误信息)/error_type(异常类型)字段
|
||||
"exception_count": int, # 上传表格返回的异常总条数
|
||||
}
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: 共享 HR 登录态缺失/失效,需先运行「37duHR登录」指令。
|
||||
ValueError: import_type 非法。
|
||||
"""
|
||||
if import_type not in _IMPORT_TYPE_MAP:
|
||||
raise ValueError(f"不支持的导入类型:{import_type}(应为「增员」或「减员」)")
|
||||
menu_label = _IMPORT_TYPE_MAP[import_type]
|
||||
|
||||
categories = [get_category(n) for n in category_names] if category_names else CATEGORIES
|
||||
|
||||
logger.info("===== 开始%s,类别:%s =====", menu_label,
|
||||
[c["name"] for c in categories])
|
||||
page = _create_page()
|
||||
logger.info("浏览器已启动")
|
||||
try:
|
||||
cookies = _load_shared_hr_cookies()
|
||||
if not cookies:
|
||||
raise LoginRequiredError(
|
||||
"未找到 HR 登录态 cookies,请先调用「37duHR登录」指令完成登录后再重试。")
|
||||
logger.info("加载缓存 cookies:%d 个", len(cookies))
|
||||
page.set.cookies(cookies)
|
||||
_ensure_logged_in(page)
|
||||
|
||||
ok = 0
|
||||
results = []
|
||||
for category in categories:
|
||||
try:
|
||||
res = dict(_import_one(page, category, menu_label, file_path))
|
||||
res["category"] = category["name"]
|
||||
res["menu"] = menu_label
|
||||
results.append(res)
|
||||
ok += 1
|
||||
except Exception as e:
|
||||
logger.exception("类别[%s] %s失败:", category["name"], menu_label)
|
||||
results.append({
|
||||
"category": category["name"], "menu": menu_label,
|
||||
"captured": False, "state": "", "meg": "", "exceptions": [],
|
||||
"error": str(e),
|
||||
"error_type": type(e).__name__,
|
||||
})
|
||||
exception_count = sum(len(r.get("exceptions") or []) for r in results)
|
||||
logger.info("===== %s 全部完成(成功 %d/%d,异常 %d 条) =====",
|
||||
menu_label, ok, len(categories), exception_count)
|
||||
# 异常/完成消息写入影刀全局变量 messages(供「37du钉钉群机器人推送」指令读取推送)
|
||||
_write_group_messages_glv(
|
||||
menu_label,
|
||||
[c["name"] for c in categories],
|
||||
results,
|
||||
exception_count,
|
||||
)
|
||||
return {
|
||||
"success": ok == len(categories),
|
||||
"import_type": menu_label,
|
||||
"categories": [c["name"] for c in categories],
|
||||
"results": results,
|
||||
"exception_count": exception_count,
|
||||
}
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def main(category_names=None):
|
||||
"""影刀自定义指令入口「37du增减员导入」:对指定/全部类别一次性完成增员+减员导入。
|
||||
|
||||
Args:
|
||||
category_names: 类别名列表,空/None=全部类别。
|
||||
|
||||
Returns:
|
||||
dict: {
|
||||
"success": bool, # 增员+减员全部类别是否均完成
|
||||
"categories": [str],
|
||||
"details": {"增员导入": bool, "减员导入": bool},
|
||||
"exceptions": [dict], # 全部异常明细(上传表格返回的异常 + 类别流程失败,合并增/减员)
|
||||
"exception_count": int, # 异常总条数
|
||||
}
|
||||
"""
|
||||
load_dotenv()
|
||||
categories = [get_category(n)["name"] for n in category_names] if category_names \
|
||||
else [c["name"] for c in CATEGORIES]
|
||||
details = {}
|
||||
exceptions = []
|
||||
all_results = []
|
||||
ok_all = True
|
||||
for import_type in ("增员", "减员"):
|
||||
result = import_employee_change(import_type, category_names)
|
||||
details[_IMPORT_TYPE_MAP[import_type]] = result["success"]
|
||||
ok_all = ok_all and result["success"]
|
||||
for r in result["results"]:
|
||||
r["menu"] = r.get("menu") or _IMPORT_TYPE_MAP[import_type]
|
||||
all_results.append(r)
|
||||
# 类别流程本身失败(元素找不到/登录失败/文件缺失等):合并为一条异常上报,避免在推送中漏报
|
||||
if r.get("error"):
|
||||
exceptions.append({
|
||||
"category": r.get("category", ""),
|
||||
"menu": r.get("menu", ""),
|
||||
"staff_code": "", "staff_name": "", "insurance_name": "",
|
||||
"message": f"流程失败({r.get('error_type', 'Exception')}):{r['error']}",
|
||||
})
|
||||
for exc in r.get("exceptions") or []:
|
||||
exceptions.append({
|
||||
"category": r.get("category", ""),
|
||||
"menu": r.get("menu", ""),
|
||||
"staff_code": exc["staff_code"],
|
||||
"staff_name": exc["staff_name"],
|
||||
"insurance_name": exc["insurance_name"],
|
||||
"message": exc["message"],
|
||||
})
|
||||
if exceptions:
|
||||
logger.error("===== 增/减员导入共返回 %d 条异常,明细如下 =====", len(exceptions))
|
||||
for exc in exceptions:
|
||||
logger.error(" - [%s/%s] %s:方案[%s] 异常:%s",
|
||||
exc["category"], exc["staff_code"], exc["staff_name"],
|
||||
exc["insurance_name"], exc["message"])
|
||||
# 合并增/减员结果,覆盖写入影刀全局变量 messages(供「37du钉钉群机器人推送」指令读取推送)
|
||||
_write_group_messages_glv("增员/减员", categories, all_results, len(exceptions))
|
||||
return {
|
||||
"success": ok_all,
|
||||
"categories": categories,
|
||||
"details": details,
|
||||
"exceptions": exceptions,
|
||||
"exception_count": len(exceptions),
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(category_names=["三十七度"])
|
||||
Reference in New Issue
Block a user