659 lines
29 KiB
Python
659 lines
29 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""XQ0002 插件 - HR「待增减人员」增减员导入(浏览器自动化,移植影刀版 add_sub_import v1.8.0)。
|
||
|
||
流程:访问待增减人员页面 -> 更多操作 -> 减员/增员导入 -> 上传文件 -> 下一步(格式校验)
|
||
-> 下一步(真正导入)-> 关闭;监听 getTmpDataPage.mc 捕获逐行导入结果。
|
||
|
||
插件化改造点(相对影刀版):
|
||
1. 登录态:优先底座注入 session(config.get_session())的 cookies 注入浏览器,
|
||
未注入/为空时兜底读共享 cookies 文件(hr_cookies.json);
|
||
2. 导入文件路径经 config.category_import_add_file / category_import_sub_file 实时解析
|
||
(base_dir 由 run() 注入,不依赖类别配置里的固化 folder);
|
||
3. 一次运行共用一个浏览器:先全部类别【减员】再全部类别【增员】
|
||
(替换/修改人员必须先撤旧方案再上新方案,先增员会方案冲突报错);
|
||
4. 日志统一转发 config.logger;结果 dict 返回,由 __init__.py 汇总进 summary/notes。
|
||
|
||
关键语义(与影刀版一致,勿改):
|
||
- getTmpDataPage.mc 仅在存在异常行时才返回逐行结果:全部成功时 HR 不调用结果接口,
|
||
流程完整走完(两步「下一步」+「关闭」)且监听正常、未捕获异常行 -> 按文件条数推定全部成功;
|
||
- 接口每页固定 15 条,弹窗只加载第一页:捕获首响应后按 pageNo 主动翻页拉全;
|
||
- 需导入条数从导入文件 A 列最大序号统计(模板预格式化空白行不计);
|
||
- 上传/校验/确认走 UI 控件(input[name=file] 设置路径跳过系统文件选择框)。
|
||
"""
|
||
import json
|
||
import os
|
||
import re
|
||
import time
|
||
|
||
import requests
|
||
from openpyxl import load_workbook
|
||
|
||
from ..config import logger, SESSIONS_DIR, get_session
|
||
|
||
try:
|
||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||
_DRP_AVAILABLE = True
|
||
_DRP_IMPORT_ERROR = None
|
||
except ImportError as _e: # 模块可安全导入(开关关闭时不触发),使用时再报清晰错误
|
||
_DRP_AVAILABLE = False
|
||
_DRP_IMPORT_ERROR = _e
|
||
|
||
# ==================== 常量(与影刀版 add_sub_import 一致) ====================
|
||
SHARED_HR_COOKIE_FILE = os.path.join(SESSIONS_DIR, 'hr_cookies.json')
|
||
|
||
# HR 系统「待增减人员」页面
|
||
ADD_SUB_URL = (
|
||
"https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic"
|
||
"#ajax&1&nworktoday-40175-13664-23874-98879&nworktoday-40175-13664"
|
||
"|/RedseaPlatform/hrRoster/7984ae1a-16ec-11ed-bea9-822ff8ed5b28/"
|
||
"getCustomCommonList.mc?menuName=待增减人员"
|
||
)
|
||
|
||
BTN_MORE = "更多操作" # 「更多操作」下拉按钮
|
||
MENU_ADD = "增员导入" # 下拉菜单:增员导入
|
||
MENU_SUB = "减员导入" # 下拉菜单:减员导入
|
||
BTN_NEXT = "下一步" # 导入弹窗「下一步」按钮(第 2/3 步)
|
||
BTN_CLOSE = "关闭" # 导入完成弹窗「关闭」按钮
|
||
|
||
WAIT_SHORT = 0.6
|
||
WAIT_MID = 2.0
|
||
WAIT_LONG = 4.0
|
||
|
||
# 接口监听:第二步「下一步」导入内容结果(getTmpDataPage.mc)
|
||
TMP_DATA_API_MARK = "getTmpDataPage.mc" # 导入内容结果接口(URL 子串过滤)
|
||
TMP_DATA_STATE_OK = "1" # 接口 state 成功值
|
||
TMP_DATA_WAIT = 8.0 # 等待导入结果接口响应的超时秒数
|
||
|
||
USER_AGENT = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||
"Chrome/120.0.0.0 Safari/537.36")
|
||
|
||
|
||
class LoginRequiredError(Exception):
|
||
"""HR 登录态缺失/失效(页面被重定向到登录页或无可用 cookies)。"""
|
||
|
||
|
||
class ElementNotFoundError(Exception):
|
||
"""页面元素/控件未找到(页面结构变化或加载超时)。"""
|
||
|
||
|
||
# ==================== 登录态:底座注入 session 优先,兜底共享 cookies 文件 ====================
|
||
def _cookies_from_requests_session(session):
|
||
"""从底座注入的 requests.Session 提取 37du.co 域 cookies(DrissionPage 字典格式)。"""
|
||
cookies = []
|
||
try:
|
||
jar_items = list(session.cookies)
|
||
except Exception:
|
||
return cookies
|
||
for c in jar_items:
|
||
domain = str(getattr(c, "domain", "") or "")
|
||
if "37du.co" not in domain:
|
||
continue
|
||
cookies.append({
|
||
"name": c.name, "value": c.value,
|
||
"domain": domain, "path": getattr(c, "path", None) or "/",
|
||
})
|
||
return cookies
|
||
|
||
|
||
def _cookies_from_shared_file():
|
||
"""读取共享 HR cookies 文件(37du.co 域),缺失/为空返回空列表。"""
|
||
if not os.path.isfile(SHARED_HR_COOKIE_FILE):
|
||
return []
|
||
try:
|
||
with open(SHARED_HR_COOKIE_FILE, encoding="utf-8") as f:
|
||
cookies = json.load(f) or []
|
||
except Exception as e:
|
||
logger.warning("共享 HR cookies 文件读取失败 %s:%s", SHARED_HR_COOKIE_FILE, e)
|
||
return []
|
||
return [c for c in cookies if c.get("domain") and "37du.co" in str(c["domain"])]
|
||
|
||
|
||
def _collect_browser_cookies():
|
||
"""收集浏览器登录态 cookies:底座注入 session 优先,为空兜底共享 cookies 文件。"""
|
||
cookies = []
|
||
session = get_session()
|
||
if session is not None:
|
||
cookies = _cookies_from_requests_session(session)
|
||
if cookies:
|
||
logger.info("使用底座注入 HR 会话的 cookies:%d 个", len(cookies))
|
||
if not cookies:
|
||
cookies = _cookies_from_shared_file()
|
||
if cookies:
|
||
logger.info("使用共享 cookies 文件:%d 个(%s)", len(cookies), SHARED_HR_COOKIE_FILE)
|
||
if not cookies:
|
||
raise LoginRequiredError(
|
||
"未找到可用 HR 登录态:底座未注入 HR 会话且共享 cookies 文件缺失/为空,"
|
||
"请先在插件界面完成 HR 登录后再执行导入。")
|
||
return cookies
|
||
|
||
|
||
def _build_hr_session():
|
||
"""构建可访问 HR 接口的 requests.Session(供结果接口翻页拉全)。
|
||
|
||
cookies 来源与浏览器一致(注入 session 优先,兜底共享文件);构建失败返回 None,
|
||
调用方降级为仅统计监听到的第一页(与影刀版兜底语义一致)。
|
||
"""
|
||
cookies = []
|
||
session = get_session()
|
||
if session is not None:
|
||
cookies = _cookies_from_requests_session(session)
|
||
if not cookies:
|
||
cookies = _cookies_from_shared_file()
|
||
if not cookies:
|
||
return None
|
||
s = requests.Session()
|
||
s.headers.update({
|
||
"User-Agent": USER_AGENT,
|
||
"Content-Type": "application/x-www-form-urlencoded",
|
||
})
|
||
for c in cookies:
|
||
try:
|
||
s.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||
except Exception:
|
||
continue
|
||
return s
|
||
|
||
|
||
# ==================== 元素定位辅助(DrissionPage) ====================
|
||
def _create_page():
|
||
"""创建 ChromiumPage(统一配置,非无头,与影刀版一致)。"""
|
||
co = ChromiumOptions()
|
||
return ChromiumPage(co)
|
||
|
||
|
||
def _click_text(page, text, timeout=10):
|
||
"""按元素文本精确匹配并点击,找不到则抛错。"""
|
||
ele = page.ele(f'xpath://*[normalize-space(text())="{text}"]', timeout=timeout)
|
||
if not ele:
|
||
raise ElementNotFoundError(f"未找到元素:{text}")
|
||
ele.click()
|
||
logger.info("已点击:%s", text)
|
||
|
||
|
||
def _click_text_in(page, container, text, timeout=5):
|
||
"""在指定容器内按文本匹配并点击。"""
|
||
ele = container.ele(f'xpath:.//*[normalize-space(text())="{text}"]', timeout=timeout)
|
||
if not ele:
|
||
raise ElementNotFoundError(f"容器内未找到元素:{text}")
|
||
ele.click()
|
||
logger.info("已点击:%s", text)
|
||
|
||
|
||
def _is_displayed(ele):
|
||
"""判断元素是否可见且具有尺寸;异常时返回 False(保守不误判)。"""
|
||
if ele is None:
|
||
return False
|
||
try:
|
||
if not ele.states.is_displayed:
|
||
return False
|
||
w, h = ele.rect.size
|
||
return w > 0 and h > 0
|
||
except Exception:
|
||
return False
|
||
|
||
|
||
def _ensure_logged_in(page):
|
||
"""访问待增减人员页面;若被重定向到登录页,抛 LoginRequiredError。"""
|
||
page.get(ADD_SUB_URL)
|
||
time.sleep(WAIT_LONG)
|
||
if page.ele('@id=j_username', timeout=2):
|
||
raise LoginRequiredError(
|
||
"HR 登录态已失效(页面被重定向到登录页),请先在插件界面重新登录 HR 再执行导入。")
|
||
logger.info("已进入待增减人员页面:%s", page.url)
|
||
|
||
|
||
# ==================== 增员/减员导入页面流程 ====================
|
||
def _open_more_operations(page):
|
||
"""点击「更多操作」按钮,展开下拉菜单(幂等,已展开则跳过)。"""
|
||
menu = page.ele('css:#custom-btn-ul', timeout=2)
|
||
if menu and _is_displayed(menu):
|
||
logger.info("「更多操作」下拉已展开,跳过")
|
||
time.sleep(WAIT_SHORT)
|
||
return menu
|
||
|
||
more_btn = page.ele('css:#more-btns button.dropdown-toggle', timeout=15)
|
||
if not more_btn:
|
||
more_btn = page.ele('css:button.btn-success.dropdown-toggle', timeout=5)
|
||
if not more_btn:
|
||
_click_text(page, BTN_MORE)
|
||
else:
|
||
more_btn.click()
|
||
logger.info("已点击「更多操作」")
|
||
time.sleep(WAIT_SHORT)
|
||
|
||
menu = page.ele('css:#custom-btn-ul', timeout=5)
|
||
if not menu:
|
||
raise ElementNotFoundError("未找到「更多操作」下拉菜单(#custom-btn-ul)")
|
||
logger.info("「更多操作」下拉已展开")
|
||
return menu
|
||
|
||
|
||
def _choose_import_menu(page, menu_label):
|
||
"""在下拉菜单中选择「增员导入」或「减员导入」。"""
|
||
menu = _open_more_operations(page)
|
||
_click_text_in(page, menu, menu_label)
|
||
time.sleep(WAIT_MID)
|
||
|
||
|
||
def _upload_file(page, file_path):
|
||
"""在导入弹窗中上传指定文件(直接对 input[name=file] 设置路径,跳过系统文件选择框)。"""
|
||
if not os.path.isfile(file_path):
|
||
raise FileNotFoundError(f"导入文件不存在:{file_path}")
|
||
file_input = page.ele('css:input[name="file"]', timeout=15)
|
||
if not file_input:
|
||
raise ElementNotFoundError("未找到文件上传控件(input[name=file])")
|
||
file_input.input(file_path)
|
||
logger.info("已选择导入文件:%s", file_path)
|
||
time.sleep(WAIT_SHORT)
|
||
|
||
|
||
def _click_next(page):
|
||
"""点击导入弹窗中的「下一步」按钮(btn-success 且可见)。"""
|
||
btn = page.ele(
|
||
'xpath://div[contains(@class,"sub-btn")]//button[contains(@class,"btn-success")'
|
||
' and normalize-space(.)="下一步"]',
|
||
timeout=10,
|
||
)
|
||
if not btn or not _is_displayed(btn):
|
||
raise ElementNotFoundError("未找到可见的「下一步」按钮")
|
||
btn.click()
|
||
logger.info("已点击「下一步」")
|
||
time.sleep(WAIT_MID)
|
||
|
||
|
||
def _click_close(page):
|
||
"""点击导入完成弹窗中的「关闭」按钮。"""
|
||
btn = page.ele(
|
||
'xpath://div[contains(@class,"sub-btn")]//button[contains(@class,"btn-default")'
|
||
' and normalize-space(.)="关闭"]',
|
||
timeout=10,
|
||
)
|
||
if not btn or not _is_displayed(btn):
|
||
raise ElementNotFoundError("未找到可见的「关闭」按钮")
|
||
btn.click()
|
||
logger.info("已点击「关闭」")
|
||
time.sleep(WAIT_SHORT)
|
||
|
||
|
||
# ---------------------------------------------------------------
|
||
# 接口监听:上传表格后解析结果(getTmpDataPage.mc),捕获返回的全部异常
|
||
# ---------------------------------------------------------------
|
||
def _extract_json_response(req):
|
||
"""从监听到的请求中解析 JSON 响应;解析失败返回 None。"""
|
||
try:
|
||
return req.response.json()
|
||
except Exception:
|
||
body = getattr(req.response, "body", None)
|
||
if isinstance(body, (dict, list)):
|
||
return body
|
||
if not body:
|
||
return None
|
||
try:
|
||
return json.loads(body)
|
||
except Exception:
|
||
return None
|
||
|
||
|
||
def _merge_datas(result, resp):
|
||
"""从一次接口响应(resp)中提取并累计统计:需导入总条数、成功数、异常明细。"""
|
||
for item in resp.get("datas") or []:
|
||
item = item or {}
|
||
msg = str(item.get("imp_fixed_msg", "") or "").strip()
|
||
if not msg:
|
||
continue
|
||
result["total_count"] += 1
|
||
# 成功行返回「导入成功;」固定文案,只计数量不纳入异常
|
||
if "导入成功" in msg:
|
||
result["success_count"] += 1
|
||
continue
|
||
result["exceptions"].append({
|
||
"staff_code": str(item.get("imp_assi_staff_code_ext_table_field_base_id", "") or ""),
|
||
"staff_name": str(item.get("imp_assi_staff_name_ext_table_field_base_id", "") or ""),
|
||
"insurance_name": str(item.get("ext_insurance_name", "") or ""),
|
||
"message": msg,
|
||
})
|
||
|
||
|
||
def _fetch_remaining_pages(result, first_url, first_body, page_count, page_size=15):
|
||
"""getTmpDataPage 每页固定返回 15 条,弹窗只加载第一页:按 pageNo 主动翻页拉全。
|
||
|
||
该接口为 POST,分页参数(importId/imp_fixed_businessid/start/pageNo/pageSize)
|
||
在请求 body 中,必须复用首次请求 body 改页码后 POST(直接 GET URL 拿不到目标页)。
|
||
"""
|
||
if page_count <= 1:
|
||
return
|
||
session = _build_hr_session()
|
||
if session is None:
|
||
logger.warning("分页拉取失败(无法构建 HR 会话),仅统计弹窗第一页")
|
||
return
|
||
for page_no in range(2, page_count + 1):
|
||
start = (page_no - 1) * page_size
|
||
body = re.sub(r"pageNo=\d+", f"pageNo={page_no}", first_body or "")
|
||
body = re.sub(r"start=\d+", f"start={start}", body)
|
||
body = re.sub(r"pageSize=\d+", f"pageSize={page_size}", body)
|
||
try:
|
||
resp = session.post(first_url, data=body, timeout=15)
|
||
data = resp.json()
|
||
except Exception as e:
|
||
logger.warning("分页第 %s/%s 页拉取失败:%s", page_no, page_count, e)
|
||
continue
|
||
if str(data.get("state", "")).strip() != TMP_DATA_STATE_OK:
|
||
logger.warning("分页第 %s/%s 页返回 state=%s,跳过",
|
||
page_no, page_count, data.get("state"))
|
||
continue
|
||
logger.info("分页第 %s/%s 页返回 %s 条",
|
||
page_no, page_count, len(data.get("datas") or []))
|
||
_merge_datas(result, data)
|
||
|
||
|
||
def _capture_import_exceptions(page, timeout=TMP_DATA_WAIT):
|
||
"""监听导入结果接口(getTmpDataPage.mc),捕获全部逐行结果(监听须已开启)。
|
||
|
||
第一步「下一步」(格式校验/预览)也可能请求该接口但行内 imp_fixed_msg 为空,跳过;
|
||
仅处理携带导入结果说明的响应。捕获首响应后按 pageCount 主动翻页拉全。
|
||
|
||
Returns:
|
||
dict: {captured, state, meg, listen_ok, success_count, total_count, exceptions}
|
||
"""
|
||
result = {"captured": False, "state": "", "meg": "", "exceptions": [],
|
||
"listen_ok": True, "success_count": 0, "total_count": 0}
|
||
first_url = None
|
||
first_body = ""
|
||
page_count = 1
|
||
deadline = time.time() + timeout
|
||
last_hit = time.time()
|
||
while time.time() < deadline:
|
||
try:
|
||
remain = max(0.0, deadline - time.time())
|
||
req = page.listen.wait(timeout=min(0.5, remain))
|
||
except Exception as e:
|
||
logger.warning("监听 %s 接口异常:%s", TMP_DATA_API_MARK, e)
|
||
break
|
||
if not req:
|
||
# 已捕获过解析响应时,再确认一个间隔后结束,合并多次返回的结果
|
||
if result["captured"] and time.time() - last_hit >= 1.0:
|
||
break
|
||
continue
|
||
if not hasattr(req, "url"):
|
||
continue
|
||
if TMP_DATA_API_MARK not in (req.url or ""):
|
||
continue
|
||
resp = _extract_json_response(req)
|
||
if not isinstance(resp, dict):
|
||
continue
|
||
# 预览/校验响应行内 imp_fixed_msg 为空 -> 跳过,继续等待最终结果
|
||
if not any(str((it or {}).get("imp_fixed_msg", "") or "").strip()
|
||
for it in (resp.get("datas") or [])):
|
||
continue
|
||
result["captured"] = True
|
||
last_hit = time.time()
|
||
state = str(resp.get("state", "")).strip()
|
||
if state:
|
||
result["state"] = state
|
||
meg = str(resp.get("meg", "") or "").strip()
|
||
if meg:
|
||
result["meg"] = meg
|
||
if first_url is None:
|
||
first_url = req.url
|
||
first_body = req.request.postData or ""
|
||
try:
|
||
page_count = max(1, int(resp.get("pageCount") or 1))
|
||
except Exception:
|
||
page_count = 1
|
||
_merge_datas(result, resp)
|
||
if first_url and page_count > 1:
|
||
_fetch_remaining_pages(result, first_url, first_body, page_count)
|
||
break
|
||
return result
|
||
|
||
|
||
def _count_import_rows(file_path):
|
||
"""统计导入文件需导入条数(A 列最大序号;第 1 行标题/第 2 行表头/第 3 行示例,第 4 行起数据)。
|
||
|
||
官方模板自带大量预格式化空白行(max_row 可达数千),不能直接用 max_row 统计。
|
||
"""
|
||
try:
|
||
wb = load_workbook(file_path, read_only=True)
|
||
try:
|
||
ws = wb[wb.sheetnames[0]]
|
||
max_seq = 0
|
||
for seq in ws.iter_rows(min_row=4, max_row=ws.max_row,
|
||
max_col=1, values_only=True):
|
||
v = seq[0]
|
||
if v is None or str(v).strip() == "":
|
||
continue
|
||
try:
|
||
max_seq = max(max_seq, int(v))
|
||
except (TypeError, ValueError):
|
||
continue
|
||
return max_seq
|
||
finally:
|
||
wb.close()
|
||
except Exception as e:
|
||
logger.warning("统计导入文件条数失败 %s:%s", file_path, e)
|
||
return 0
|
||
|
||
|
||
def _import_file_path(category, menu_label):
|
||
"""按菜单解析类别导入文件路径(base_dir 运行时注入,实时拼接)。"""
|
||
if menu_label == MENU_ADD:
|
||
from ..config import category_import_add_file
|
||
return category_import_add_file(category)
|
||
from ..config import category_import_sub_file
|
||
return category_import_sub_file(category)
|
||
|
||
|
||
def _import_one(page, category, menu_label, expected_total=None):
|
||
"""对单个类别执行一次导入(选菜单 -> 上传 -> 下一步 -> 下一步 -> 关闭)。
|
||
|
||
自第一个「下一步」之前即开启 getTmpDataPage.mc 监听(结果接口可能在格式校验或
|
||
真正导入时触发,提前监听避免漏捕);异常仅记录上报,不中断导入流程。
|
||
|
||
Args:
|
||
expected_total: 需导入条数(由 import_all 预检传入,避免重复读文件;None 时自行统计)。
|
||
|
||
Returns:
|
||
dict: 导入结果(含 expected_total 需导入条数、exceptions 异常明细等)。
|
||
"""
|
||
file_path = _import_file_path(category, menu_label)
|
||
if not os.path.isfile(file_path):
|
||
raise FileNotFoundError(f"导入文件不存在:{file_path}")
|
||
if expected_total is None:
|
||
expected_total = _count_import_rows(file_path)
|
||
|
||
logger.info("===== 类别[%s] 开始%s,文件:%s(需导入 %d 条) =====",
|
||
category["name"], menu_label, file_path, expected_total)
|
||
_choose_import_menu(page, menu_label)
|
||
_upload_file(page, file_path)
|
||
|
||
# 第一个「下一步」前开启监听,贯穿「格式校验/预览 + 真正导入」全过程;
|
||
# 监听启动失败必须上报,否则未捕获异常会被误判为正常(假成功)
|
||
listen_ok = True
|
||
try:
|
||
page.listen.start(TMP_DATA_API_MARK)
|
||
except Exception as e:
|
||
listen_ok = False
|
||
logger.error("启动 %s 接口监听失败,无法捕获导入结果:%s", TMP_DATA_API_MARK, e)
|
||
try:
|
||
_click_next(page) # 第一步:格式校验/预览
|
||
_click_next(page) # 第二步:真正导入内容(触发结果接口)
|
||
import_result = _capture_import_exceptions(page)
|
||
import_result["listen_ok"] = listen_ok
|
||
import_result["expected_total"] = expected_total
|
||
finally:
|
||
try:
|
||
page.listen.stop()
|
||
except Exception:
|
||
pass
|
||
|
||
# 全部成功时 HR 不调用结果接口:流程完整走完 + 监听正常 + 未捕获异常行 -> 按文件条数推定全部成功
|
||
if (not import_result["captured"] and listen_ok and not import_result["exceptions"]):
|
||
import_result["assumed_all_success"] = True
|
||
import_result["success_count"] = expected_total
|
||
import_result["total_count"] = expected_total
|
||
|
||
if import_result["exceptions"]:
|
||
logger.error("类别[%s] %s:导入返回 %d 条异常:",
|
||
category["name"], menu_label, len(import_result["exceptions"]))
|
||
for exc in import_result["exceptions"]:
|
||
logger.error(" - [%s/%s] 方案[%s]:%s",
|
||
exc["staff_code"], exc["staff_name"],
|
||
exc["insurance_name"], exc["message"])
|
||
elif not listen_ok:
|
||
logger.error("类别[%s] %s:接口监听启动失败,无法确认导入结果,请人工核对",
|
||
category["name"], menu_label)
|
||
elif import_result["captured"] and import_result["state"] != TMP_DATA_STATE_OK:
|
||
logger.error("类别[%s] %s:导入接口 state=%s(meg=%s),导入可能失败",
|
||
category["name"], menu_label, import_result["state"], import_result["meg"])
|
||
elif import_result.get("assumed_all_success"):
|
||
logger.info("类别[%s] %s:全部导入成功(HR 未返回结果接口,按文件 %d 条推定),无异常",
|
||
category["name"], menu_label, expected_total)
|
||
elif not import_result["captured"]:
|
||
logger.warning("类别[%s] %s:未捕获到导入结果接口响应,无法确认导入结果",
|
||
category["name"], menu_label)
|
||
else:
|
||
logger.info("类别[%s] %s:导入成功 %s 人,无异常",
|
||
category["name"], menu_label, import_result.get("success_count", 0))
|
||
|
||
_click_close(page)
|
||
logger.info("===== 类别[%s] %s完成 =====", category["name"], menu_label)
|
||
return import_result
|
||
|
||
|
||
# ==================== 对外入口:先减员后增员,全程共用一个浏览器 ====================
|
||
def _skipped_result(category, menu, reason):
|
||
"""构造「无待导入条目」的跳过单元结果(无 error,不计流程失败)。"""
|
||
return {
|
||
"category": category["name"], "menu": menu,
|
||
"captured": False, "state": "", "meg": "", "exceptions": [],
|
||
"listen_ok": True, "expected_total": 0,
|
||
"success_count": 0, "total_count": 0,
|
||
"skipped": True, "skip_reason": reason,
|
||
}
|
||
|
||
|
||
def import_all(categories, on_progress=None):
|
||
"""对指定类别执行 HR 导入(★先全部类别【减员】再【增员】,顺序不可换)。
|
||
|
||
预检:仅「导入文件存在且实际有待导入条目」的单元才会启动浏览器执行导入;
|
||
需导入 0 条(无增员/减员变动)的单元直接跳过——本就没有需要导入的内容,
|
||
不启动浏览器、也不报"流程失败"。
|
||
|
||
Args:
|
||
categories: 类别配置列表(config.CATEGORIES 项,须为本次调度成功的类别,
|
||
只导入本次新生成的导入文件,避免误传历史文件)。
|
||
on_progress: 可选回调 on_progress(done, total),每个实际执行导入的
|
||
「类别×菜单」单元完成后调用,供 __init__.py 上报进度。
|
||
|
||
Returns:
|
||
list[dict]: 每单元结果:{category, menu, captured, state, meg, exceptions,
|
||
listen_ok, expected_total, success_count, total_count,
|
||
assumed_all_success?, error?, error_type?, skipped?}
|
||
skipped=True 表示该单元导入文件无待导入条目(需导入 0 条),未启动浏览器导入,
|
||
不视为流程失败(无 error 字段)。
|
||
|
||
Raises:
|
||
LoginRequiredError: HR 登录态缺失/失效(整个导入未开始,无部分导入风险)。
|
||
RuntimeError: DrissionPage 依赖缺失。
|
||
"""
|
||
if not _DRP_AVAILABLE:
|
||
raise RuntimeError(f"缺少 DrissionPage 依赖(python-env 未内置),无法自动导入:{_DRP_IMPORT_ERROR}")
|
||
if not categories:
|
||
logger.info("无待导入类别,跳过 HR 导入")
|
||
return []
|
||
|
||
# ---- 预检:按导入文件实际条数过滤出真正需要导入的单元(类别×菜单) ----
|
||
results = []
|
||
units = []
|
||
for c in categories:
|
||
for menu in (MENU_SUB, MENU_ADD):
|
||
label = "减员" if menu == MENU_SUB else "增员"
|
||
file_path = _import_file_path(c, menu)
|
||
if not os.path.isfile(file_path):
|
||
logger.warning("类别[%s] %s导入文件不存在,视为无需导入:%s",
|
||
c["name"], label, file_path)
|
||
results.append(_skipped_result(c, menu, "导入文件不存在"))
|
||
continue
|
||
expected_total = _count_import_rows(file_path)
|
||
if expected_total <= 0:
|
||
logger.info("类别[%s] %s导入文件无待导入条目,跳过导入:%s",
|
||
c["name"], label, file_path)
|
||
results.append(_skipped_result(c, menu, "无待导入条目"))
|
||
continue
|
||
units.append((c, menu, expected_total))
|
||
|
||
if not units:
|
||
logger.info("各类别增/减员导入文件均无待导入条目,跳过 HR 自动导入(未启动浏览器)")
|
||
return results
|
||
|
||
total_units = len(units)
|
||
done = 0
|
||
|
||
page = _create_page()
|
||
logger.info("浏览器已启动(导入全程共用)")
|
||
try:
|
||
cookies = _collect_browser_cookies()
|
||
page.set.cookies(cookies)
|
||
_ensure_logged_in(page)
|
||
|
||
for category, menu_label, expected_total in units:
|
||
try:
|
||
res = dict(_import_one(page, category, menu_label, expected_total=expected_total))
|
||
res["category"] = category["name"]
|
||
res["menu"] = menu_label
|
||
results.append(res)
|
||
except Exception as e:
|
||
logger.error("类别[%s] %s失败:%s", category["name"], menu_label, e)
|
||
results.append({
|
||
"category": category["name"], "menu": menu_label,
|
||
"captured": False, "state": "", "meg": "", "exceptions": [],
|
||
"listen_ok": True, "expected_total": 0,
|
||
"success_count": 0, "total_count": 0,
|
||
"error": str(e), "error_type": type(e).__name__,
|
||
})
|
||
done += 1
|
||
if on_progress:
|
||
try:
|
||
on_progress(done, total_units)
|
||
except Exception:
|
||
pass
|
||
return results
|
||
finally:
|
||
try:
|
||
page.quit()
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def summarize_results(results):
|
||
"""把导入结果汇总为可读文本行列表(供插件 summary 拼接)。
|
||
|
||
口径与影刀版一致:需导入条数取自导入文件(expected_total,与接口是否捕获无关);
|
||
成功/失败取接口返回的业务结果(全部成功时 HR 不返回接口,按文件条数推定成功);
|
||
流程失败(登录/元素/文件缺失)的单元不纳入条数统计,仅报失败;
|
||
跳过单元(skipped,无待导入条目)正常纳入统计(需导入 0 条),不报失败/待确认。
|
||
"""
|
||
lines = []
|
||
for menu, label in ((MENU_SUB, "减员"), (MENU_ADD, "增员")):
|
||
rs = [r for r in results if r.get("menu") == menu]
|
||
if not rs:
|
||
continue
|
||
total = sum(r.get("expected_total") or 0 for r in rs if not r.get("error"))
|
||
success = sum(r.get("success_count") or 0 for r in rs if not r.get("error"))
|
||
fail = sum(len(r.get("exceptions") or []) for r in rs if not r.get("error"))
|
||
flow_failed = [r["category"] for r in rs if r.get("error")]
|
||
unconfirmed = [r["category"] for r in rs
|
||
if not r.get("error") and not r.get("exceptions")
|
||
and not r.get("assumed_all_success") and not r.get("skipped")
|
||
and (not r.get("captured") or r.get("state") != TMP_DATA_STATE_OK)]
|
||
line = f"{label}:需导入 {total} 条,成功 {success} 条,异常 {fail} 条"
|
||
extras = []
|
||
if unconfirmed:
|
||
extras.append(f"{len(unconfirmed)} 个类别结果待人工确认({'、'.join(unconfirmed)})")
|
||
if flow_failed:
|
||
extras.append(f"流程失败({'、'.join(flow_failed)})")
|
||
if extras:
|
||
line += ";" + ";".join(extras)
|
||
lines.append(line)
|
||
return lines
|