refactor: 重构影刀脚本目录结构,按需求单归档并清理冗余文件
- 将影刀脚本从按系统分组的oa/hr/employer_insurance等目录迁移到XQ00xx命名的需求单目录,与docs/需求单一一对应 - 删除原employer_insurance目录下冗余的export_change_sheet.py,将其迁移到XQ0002目录 - 清理已废弃的XQ0020标准化门店手续相关文档与XQ0021离职电子签重复文档 - 更新需求单总索引、README文档与影刀脚本目录说明,修正路径引用 - 修复雇主险导入模板校验逻辑与增员导入异常捕获逻辑
This commit is contained in:
@@ -61,6 +61,15 @@ from app.service.hrbp.ehr.employer_insurance.config import ( # noqa: E402
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ===================== 领域异常定义 =====================
|
||||
class ElementNotFoundError(Exception):
|
||||
"""页面元素/控件未找到(页面结构变化或加载超时)。
|
||||
|
||||
用于区分「UI 状态类失败」(页面没加载出来、元素定位器失效)与其它运行时错误,
|
||||
便于调用方针对性地重试或提示人工介入。
|
||||
"""
|
||||
|
||||
|
||||
# ===================== 流程步骤所用文案常量(aa.md 提供) =====================
|
||||
BTN_MORE = "更多操作" # 「更多操作」下拉按钮
|
||||
MENU_ADD = "增员导入" # 下拉菜单:增员导入
|
||||
@@ -75,9 +84,10 @@ WAIT_LONG = 4.0
|
||||
|
||||
# ---------- 接口监听:第二步「下一步」导入内容结果(getTmpDataPage.mc) ----------
|
||||
# 第一个「下一步」为格式校验(不做处理);点击第二个「下一步」(真正导入内容)后,
|
||||
# HR 系统会 POST getTmpDataPage.mc 返回导入结果,其中 datas[].imp_fixed_msg 为逐行异常信息
|
||||
# (如「存在已参保的人员,不允许重复增员!」)。
|
||||
# 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 # 等待导入结果接口响应的超时秒数
|
||||
|
||||
|
||||
@@ -88,7 +98,7 @@ def _click_text(page, text, timeout=10):
|
||||
"""按元素文本精确匹配并点击,找不到则抛错。"""
|
||||
ele = page.ele(f'xpath://*[normalize-space(text())="{text}"]', timeout=timeout)
|
||||
if not ele:
|
||||
raise RuntimeError(f"未找到元素:{text}")
|
||||
raise ElementNotFoundError(f"未找到元素:{text}")
|
||||
ele.click()
|
||||
logger.info("已点击:%s", text)
|
||||
|
||||
@@ -97,7 +107,7 @@ def _click_text_in(page, container, text, timeout=5):
|
||||
"""在指定容器内按文本匹配并点击。"""
|
||||
ele = container.ele(f'xpath:.//*[normalize-space(text())="{text}"]', timeout=timeout)
|
||||
if not ele:
|
||||
raise RuntimeError(f"容器内未找到元素:{text}")
|
||||
raise ElementNotFoundError(f"容器内未找到元素:{text}")
|
||||
ele.click()
|
||||
logger.info("已点击:%s", text)
|
||||
|
||||
@@ -164,7 +174,7 @@ def _open_more_operations(page):
|
||||
|
||||
menu = page.ele('css:#custom-btn-ul', timeout=5)
|
||||
if not menu:
|
||||
raise RuntimeError("未找到「更多操作」下拉菜单(#custom-btn-ul)")
|
||||
raise ElementNotFoundError("未找到「更多操作」下拉菜单(#custom-btn-ul)")
|
||||
logger.info("「更多操作」下拉已展开")
|
||||
return menu
|
||||
|
||||
@@ -189,7 +199,7 @@ def _upload_file(page, file_path):
|
||||
|
||||
file_input = page.ele('css:input[name="file"]', timeout=15)
|
||||
if not file_input:
|
||||
raise RuntimeError("未找到文件上传控件(input[name=file])")
|
||||
raise ElementNotFoundError("未找到文件上传控件(input[name=file])")
|
||||
file_input.input(file_path)
|
||||
logger.info("已选择导入文件:%s", file_path)
|
||||
time.sleep(WAIT_SHORT)
|
||||
@@ -203,7 +213,7 @@ def _click_next(page):
|
||||
timeout=10,
|
||||
)
|
||||
if not btn or not _is_displayed(btn):
|
||||
raise RuntimeError("未找到可见的「下一步」按钮")
|
||||
raise ElementNotFoundError("未找到可见的「下一步」按钮")
|
||||
btn.click()
|
||||
logger.info("已点击「下一步」")
|
||||
time.sleep(WAIT_MID)
|
||||
@@ -217,7 +227,7 @@ def _click_close(page):
|
||||
timeout=10,
|
||||
)
|
||||
if not btn or not _is_displayed(btn):
|
||||
raise RuntimeError("未找到可见的「关闭」按钮")
|
||||
raise ElementNotFoundError("未找到可见的「关闭」按钮")
|
||||
btn.click()
|
||||
logger.info("已点击「关闭」")
|
||||
time.sleep(WAIT_SHORT)
|
||||
@@ -248,20 +258,25 @@ def _capture_import_exceptions(page, timeout=TMP_DATA_WAIT):
|
||||
第一个「下一步」为格式校验(不监听);点击第二个「下一步」真正导入内容后,
|
||||
HR 系统会 POST getTmpDataPage.mc 返回导入结果:
|
||||
- state="1" 表示接口正常;meg 为全局提示;
|
||||
- datas[].imp_fixed_msg 非空表示该行存在异常(如「存在已参保的人员,不允许重复增员!」)。
|
||||
本函数合并该接口全部(含分页/多次)响应中的异常(不逐行单独处理),供流程统一上报。
|
||||
- datas[].imp_fixed_msg 为逐行导入结果说明:异常行如「存在已参保的人员,不允许重复增员!」,
|
||||
成功行返回「导入成功;」(成功行不纳入异常上报)。
|
||||
本函数合并该接口全部(含分页/多次)响应中的异常(不逐行单独处理),供流程统一上报;
|
||||
成功行(「导入成功」)只统计成功行数,不纳入异常。
|
||||
|
||||
Returns:
|
||||
dict: {
|
||||
"captured": bool, # 是否捕获到解析接口响应
|
||||
"state": str, # 接口 state(未捕获到为空串)
|
||||
"meg": str, # 全局提示
|
||||
"listen_ok": bool, # 接口监听是否成功启动(False=未监听,结果不可信)
|
||||
"success_count": int, # 接口返回的导入成功行数
|
||||
"exceptions": [ # 全部异常明细
|
||||
{"staff_code":..., "staff_name":..., "insurance_name":..., "message":...}, ...
|
||||
],
|
||||
}
|
||||
"""
|
||||
result = {"captured": False, "state": "", "meg": "", "exceptions": []}
|
||||
result = {"captured": False, "state": "", "meg": "", "exceptions": [],
|
||||
"listen_ok": True, "success_count": 0}
|
||||
deadline = time.time() + timeout
|
||||
last_hit = time.time()
|
||||
while time.time() < deadline:
|
||||
@@ -294,13 +309,19 @@ def _capture_import_exceptions(page, timeout=TMP_DATA_WAIT):
|
||||
for item in resp.get("datas") or []:
|
||||
item = item or {}
|
||||
msg = str(item.get("imp_fixed_msg", "") or "").strip()
|
||||
if msg:
|
||||
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,
|
||||
})
|
||||
if not msg:
|
||||
continue
|
||||
# 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
|
||||
|
||||
|
||||
@@ -347,13 +368,17 @@ def _import_one(page, category, menu_label, file_path=None):
|
||||
_click_next(page) # 第一步:下一步(格式校验,不做处理)
|
||||
|
||||
# 第二步:点击「下一步」真正导入内容;同时监听 getTmpDataPage.mc 接口,捕获导入返回的全部异常
|
||||
# 监听启动失败必须上报:若静默继续,未捕获到异常会被误报为「正常」,产生假成功
|
||||
listen_ok = True
|
||||
try:
|
||||
page.listen.start(TMP_DATA_API_MARK)
|
||||
except Exception as e:
|
||||
logger.warning("启动 %s 接口监听失败:%s", TMP_DATA_API_MARK, 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()
|
||||
@@ -367,11 +392,18 @@ def _import_one(page, category, menu_label, file_path=None):
|
||||
for exc in import_result["exceptions"]:
|
||||
logger.error(" - [%s/%s] 方案[%s]:%s",
|
||||
exc["staff_code"], exc["staff_name"], exc["insurance_name"], exc["message"])
|
||||
elif import_result["captured"] and import_result["state"] != "1":
|
||||
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:导入正常,无异常", category["name"], menu_label)
|
||||
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)
|
||||
@@ -393,17 +425,18 @@ def import_employee_change(import_type="增员", category_names=None, file_path=
|
||||
"success": bool, # 全部类别流程是否均完成
|
||||
"import_type": str, # 菜单文案(增员导入/减员导入)
|
||||
"categories": [str], # 类别名列表
|
||||
"results": [dict], # 每类别的解析捕获结果(见 _capture_import_exceptions)
|
||||
"results": [dict], # 每类别的解析捕获结果(见 _capture_import_exceptions);
|
||||
# 类别流程失败时含 error(错误信息)/error_type(异常类型)字段
|
||||
"exception_count": int, # 上传表格返回的异常总条数
|
||||
}
|
||||
|
||||
Raises:
|
||||
ValueError: import_type 非法。
|
||||
RuntimeError: 缺少 DrissionPage 依赖。
|
||||
ImportError: 缺少 DrissionPage 依赖。
|
||||
"""
|
||||
setup_logging()
|
||||
if ChromiumPage is None:
|
||||
raise RuntimeError("缺少 DrissionPage 依赖,请先安装: pip install DrissionPage")
|
||||
raise ImportError("缺少 DrissionPage 依赖,请先安装: pip install DrissionPage")
|
||||
|
||||
if import_type not in _IMPORT_TYPE_MAP:
|
||||
raise ValueError(f"不支持的导入类型:{import_type}(应为「增员」或「减员」)")
|
||||
@@ -433,6 +466,8 @@ def import_employee_change(import_type="增员", category_names=None, file_path=
|
||||
for category in categories:
|
||||
try:
|
||||
res = _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:
|
||||
@@ -441,6 +476,7 @@ def import_employee_change(import_type="增员", category_names=None, file_path=
|
||||
"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 条) =====",
|
||||
@@ -470,7 +506,7 @@ def main(category_names=None):
|
||||
"success": bool, # 增员+减员全部类别是否均完成
|
||||
"categories": [str],
|
||||
"details": {"增员导入": bool, "减员导入": bool},
|
||||
"exceptions": [dict], # 上传表格返回的全部异常明细(合并增/减员)
|
||||
"exceptions": [dict], # 全部异常明细(上传表格返回的异常 + 类别流程失败,合并增/减员)
|
||||
"exception_count": int, # 异常总条数
|
||||
}
|
||||
"""
|
||||
@@ -484,10 +520,21 @@ def main(category_names=None):
|
||||
details[_IMPORT_TYPE_MAP[import_type]] = result["success"]
|
||||
ok_all = ok_all and result["success"]
|
||||
for r in result["results"]:
|
||||
r = r or {}
|
||||
category = r.get("category") or ""
|
||||
menu = r.get("menu") or ""
|
||||
# 类别流程本身失败(元素找不到/登录失败/文件缺失等):合并为一条异常上报,避免被漏报
|
||||
if r.get("error"):
|
||||
exceptions.append({
|
||||
"category": category,
|
||||
"menu": 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["category"],
|
||||
"menu": r["menu"],
|
||||
"category": category,
|
||||
"menu": menu,
|
||||
"staff_code": exc["staff_code"],
|
||||
"staff_name": exc["staff_name"],
|
||||
"insurance_name": exc["insurance_name"],
|
||||
|
||||
@@ -946,10 +946,12 @@ def _write_import_file(template_path, out_path, rows):
|
||||
template_path: 官方导入模板路径。
|
||||
out_path: 生成的目标文件路径(类别文件夹内)。
|
||||
rows: 数据行列表,每行为 [序号, 工号/身份证, ...]。
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 导入模板不存在(导入文件为硬前提,缺失必须报错而非静默跳过)。
|
||||
"""
|
||||
if not os.path.isfile(template_path):
|
||||
logger.warning("导入模板不存在:%s,跳过生成 %s", template_path, out_path)
|
||||
return
|
||||
raise FileNotFoundError(f"导入模板不存在:{template_path},无法生成导入文件 {out_path}")
|
||||
wb = load_workbook(template_path)
|
||||
ws = wb[wb.sheetnames[0]]
|
||||
for i, row_vals in enumerate(rows):
|
||||
@@ -1058,6 +1060,21 @@ def export_add_sub_import(category, biz_df, in_param_df, final_records, reused_s
|
||||
# ============================================================
|
||||
# 六、入口(步骤2:调度)
|
||||
# ============================================================
|
||||
def _check_import_templates():
|
||||
"""前置校验增减员导入模板是否存在,任一缺失立即抛错。
|
||||
|
||||
模板在调度开始时校验(而非生成导入文件时才报),避免完整调度跑完后
|
||||
才发现模板缺失、需要重做的浪费。_write_import_file 内的检查作为兜底保留。
|
||||
"""
|
||||
missing = [
|
||||
path for path in (ADD_IMPORT_TEMPLATE, SUB_IMPORT_TEMPLATE)
|
||||
if not os.path.isfile(path)
|
||||
]
|
||||
if missing:
|
||||
raise FileNotFoundError(
|
||||
"增减员导入模板缺失,请先补充模板后再调度:\n - " + "\n - ".join(missing))
|
||||
|
||||
|
||||
def schedule_category(category):
|
||||
"""对单个类别执行调度全流程(读取已刷新公式的目标文件,输出结果)。
|
||||
|
||||
@@ -1086,6 +1103,9 @@ def schedule_category(category):
|
||||
return
|
||||
logger.info("文件结构检查通过。")
|
||||
|
||||
# 前置校验:增减员导入模板必须存在,避免调度全部完成后才发现模板缺失、需重做
|
||||
_check_import_templates()
|
||||
|
||||
# ---------- 读取并清洗花名册数据 ----------
|
||||
biz_df = pd.read_excel(target_file, sheet_name=SHEET_BIZ, header=3)
|
||||
logger.info("原始花名册数据:%d 行", len(biz_df))
|
||||
|
||||
Reference in New Issue
Block a user