feat: 新增定性评价推送插件 v1.1.1
This commit is contained in:
@@ -25,11 +25,13 @@
|
||||
全部排班集合,当日排班({日期}_team_name)属于该集合才正常(接口查不到集合时兜底
|
||||
原「完整排班名包含部门名」判断),否则为排班异常(无排班 / 排班未更新);
|
||||
- 预入职台账:按「操作时间」近 {DAYS} 天;查询「预入职日期」当日完整排班名,有即正常,否则异常。
|
||||
预入职台账导出模板无四级部门列,入职类异常的「现四级部门」按工号查花名册回填(查不到保持为空)。
|
||||
|
||||
生物识别登记核查(考勤平台 BioData,2026-09-22 新增,逻辑内联本文件满足影刀单文件自包含):
|
||||
对最终异常名单每个工号调用考勤平台 BioData 接口(q=工号)核查是否已登记
|
||||
生物识别(指纹/人脸),records==0 判定未登记;未登记人员在店长单聊提醒中
|
||||
单独追加一段「尚未登记生物识别(指纹/人脸)」明细,与排班异常分开标注;
|
||||
名单 Excel 同步增设「生物识别」列(未登记/空)便于留档核查;
|
||||
平台存在账号互踢,每次核查重新登录、不缓存 cookies;查询失败(登录/网络异常)时
|
||||
降级跳过该核查,不阻断排班异常主流程。
|
||||
考勤平台登录 URL / 账号 / 密码均内置默认值(自包含,可用 attendance_* 环境变量覆盖)。
|
||||
@@ -41,7 +43,9 @@
|
||||
店长解析(花名册):
|
||||
- 所有异常行已通过「离职过滤」保证工号在花名册内(未入册者已被剔除,含预入职);
|
||||
- 按异常人员「工号」查其「四级部门」,再找该部门内岗位含「店长」的人;
|
||||
- 仍解析不到的异常,若配置 shift_abnormal_default_manager 则归入默认处理人,否则仅记录不推送。
|
||||
- 仍解析不到的异常,若配置 shift_abnormal_default_manager 则归入默认处理人,否则仅记录不推送;
|
||||
- 名单 Excel 增设「店长/处理人」「推送状态」列:每行标注归属店长与是否纳入单聊推送,
|
||||
未解析且无默认处理人的行显示「未解析到店长 / 未推送-无处理人」,便于人工跟进。
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install requests pandas openpyxl python-dotenv cryptography
|
||||
@@ -174,6 +178,7 @@ DEFAULT_PUSH_GROUP = "数字人沟通群" # 默认汇总推送群(与 XQ0009
|
||||
COLUMNS = [
|
||||
"序号", "姓名", "工号", "类别", "原单位", "原上级部门", "现单位", "现职位序列",
|
||||
"现上级部门", "现四级部门", "调动/入职时间", "操作时间", "当日排班", "异常原因",
|
||||
"生物识别", "店长/处理人", "推送状态",
|
||||
]
|
||||
|
||||
|
||||
@@ -667,6 +672,20 @@ def _find_manager_by_dept(df, dept_name, label=""):
|
||||
return _to_text(first[COL_CODE]), _to_text(first[COL_NAME]) or ""
|
||||
|
||||
|
||||
def _lookup_dept4_by_code(roster_df, code) -> str:
|
||||
"""按工号在花名册查询其四级部门,查不到返回空串。
|
||||
|
||||
预入职台账导出模板无四级部门列,入职类异常的「现四级部门」由此回填。
|
||||
"""
|
||||
code = _to_text(code)
|
||||
if not code:
|
||||
return ""
|
||||
row = roster_df[roster_df[COL_CODE].map(_to_text) == code]
|
||||
if row.empty:
|
||||
return ""
|
||||
return _to_text(row.iloc[0][COL_DEPT4])
|
||||
|
||||
|
||||
def resolve_manager(roster_df, row: dict) -> Tuple[str, str]:
|
||||
"""解析某条异常名单行对应的店长:工号已保证在花名册(离职过滤已剔除未入册者),
|
||||
直接按工号查其四级部门 → 部门内岗位含「店长」的人;找不到返回 (None, None)。"""
|
||||
@@ -938,10 +957,10 @@ def fetch_bio_data(pins) -> Dict[str, List[dict]]:
|
||||
|
||||
# ==================== 生物识别登记核查(考勤平台 BioData) ====================
|
||||
def _annotate_bio_status(rows: List[dict]) -> None:
|
||||
"""对异常名单每行核查考勤平台生物识别登记,标记行内 bio_status。
|
||||
"""对异常名单每行核查考勤平台生物识别登记,标记行内「生物识别」字段(随名单 Excel 导出)。
|
||||
|
||||
判定口径:BioData 接口(q=工号)返回 records==0(无任何指纹/人脸记录)即未登记。
|
||||
考勤平台查询失败(登录/网络异常)时降级为不标注(bio_status=""),
|
||||
考勤平台查询失败(登录/网络异常)时降级为不标注(「生物识别」=""),
|
||||
仅推送排班异常、不追加生物识别提醒,不阻断排班异常主流程。
|
||||
"""
|
||||
pins = [r.get("工号", "") for r in rows if r.get("工号")]
|
||||
@@ -954,8 +973,15 @@ def _annotate_bio_status(rows: List[dict]) -> None:
|
||||
bio_map = {}
|
||||
for r in rows:
|
||||
code = r.get("工号", "")
|
||||
# 只有查询成功且确无记录才标「未登记」;查询失败/已登记均不触发生物识别提醒
|
||||
r["bio_status"] = "未登记" if (bio_map and code and not bio_map.get(code)) else ""
|
||||
# 只有查询成功且确无记录才标「未登记」;查询失败/已登记均为空
|
||||
r["生物识别"] = "未登记" if (bio_map and code and not bio_map.get(code)) else ""
|
||||
|
||||
|
||||
def _manager_label(mc: str, mn: str) -> str:
|
||||
"""店长/处理人显示标签:姓名/工号(缺一则只显示另一个)。"""
|
||||
if mc and mn:
|
||||
return f"{mn}/{mc}"
|
||||
return mc or mn
|
||||
|
||||
|
||||
def build_messages(rows: List[dict], roster_df) -> List[tuple]:
|
||||
@@ -965,7 +991,12 @@ def build_messages(rows: List[dict], roster_df) -> List[tuple]:
|
||||
无法解析店长的异常,若配置 DEFAULT_MANAGER 则归入默认处理人(多个用英文逗号分隔,
|
||||
轮流分配),否则仅日志记录、不推送。
|
||||
|
||||
生物识别核查(2026-09-22 新增):行内 bio_status=="未登记" 的人员,
|
||||
行标注(随名单 Excel 导出,2026-10-07 新增):
|
||||
- 「店长/处理人」:该行归属的店长(姓名/工号);归默认处理人显示默认处理人;
|
||||
未解析且无默认处理人显示「未解析到店长」;
|
||||
- 「推送状态」:已推送(纳入单聊推送)/ 未推送-无处理人(未解析且无默认处理人)。
|
||||
|
||||
生物识别核查(2026-09-22 新增):行内「生物识别」=="未登记" 的人员,
|
||||
在消息尾部单独追加一段「尚未登记生物识别(指纹/人脸)」明细,与排班异常分开标注。
|
||||
"""
|
||||
messages: List[tuple] = []
|
||||
@@ -976,6 +1007,8 @@ def build_messages(rows: List[dict], roster_df) -> List[tuple]:
|
||||
for row in rows:
|
||||
mc, mn = resolve_manager(roster_df, row)
|
||||
if mc or mn:
|
||||
row["店长/处理人"] = _manager_label(mc, mn)
|
||||
row["推送状态"] = "已推送"
|
||||
groups.setdefault((mc or "", mn or ""), []).append(row)
|
||||
else:
|
||||
unresolved.append(row)
|
||||
@@ -989,7 +1022,14 @@ def build_messages(rows: List[dict], roster_df) -> List[tuple]:
|
||||
for i, row in enumerate(unresolved):
|
||||
mgr = default_managers[i % len(default_managers)]
|
||||
key = _resolve_manager_identity(roster_df, mgr)
|
||||
row["店长/处理人"] = _manager_label(*key)
|
||||
row["推送状态"] = "已推送"
|
||||
groups.setdefault(key, []).append(row)
|
||||
else:
|
||||
# 未解析且无默认处理人:表格单独标注,不纳入单聊推送(仅群附件可见)
|
||||
for row in unresolved:
|
||||
row["店长/处理人"] = "未解析到店长"
|
||||
row["推送状态"] = "未推送-无处理人"
|
||||
|
||||
for (mc, mn), items in groups.items():
|
||||
dept = _find_dept4_by_manager(roster_df, mc, mn) # 门店名以花名册店长四级部门为准
|
||||
@@ -1001,7 +1041,7 @@ def build_messages(rows: List[dict], roster_df) -> List[tuple]:
|
||||
f"{line_items}"
|
||||
)
|
||||
# 生物识别未登记人员单独追加一段(考勤平台 BioData 查无记录),与排班异常分开标注
|
||||
no_bio = [r for r in items if r.get("bio_status") == "未登记"]
|
||||
no_bio = [r for r in items if r.get("生物识别") == "未登记"]
|
||||
if no_bio:
|
||||
bio_lines = "<br>".join(
|
||||
f"{r.get('姓名', '')}({r.get('工号', '')}){r.get('调动/入职时间', '')}" for r in no_bio)
|
||||
@@ -1115,6 +1155,11 @@ def run_shift_abnormal_check(
|
||||
len(resigned), [f"{r.get('姓名')}/{r.get('工号')}" for r in resigned])
|
||||
rows = [r for r in rows if _to_text(r.get("工号")) in roster_codes]
|
||||
|
||||
# 预入职异常回填「现四级部门」:台账模板无该列,按工号查花名册补齐(查不到保持为空)
|
||||
for r in rows:
|
||||
if r.get("类别") == "入职" and not _clean(r.get("现四级部门")):
|
||||
r["现四级部门"] = _lookup_dept4_by_code(roster_df, r.get("工号"))
|
||||
|
||||
if not rows:
|
||||
logger.info("未识别到排班异常,无需推送。")
|
||||
messages = []
|
||||
@@ -1126,16 +1171,16 @@ def run_shift_abnormal_check(
|
||||
rows.sort(key=lambda x: (x.get("类别", ""), x.get("姓名", ""), x.get("工号", "")))
|
||||
for idx, item in enumerate(rows, 1):
|
||||
item["序号"] = idx
|
||||
# 导出名单留档
|
||||
# 解析店长并构造单聊推送消息(同时为每行标注「店长/处理人」「推送状态」)
|
||||
messages = build_messages(rows, roster_df)
|
||||
|
||||
# 导出名单留档(含 店长/处理人、推送状态、生物识别)
|
||||
os.makedirs(SAVE_DIR, exist_ok=True)
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
save_path = os.path.join(SAVE_DIR, f"排班异常名单_{ts}.xlsx")
|
||||
pd.DataFrame(rows, columns=COLUMNS).to_excel(save_path, index=False)
|
||||
logger.info("排班异常名单(共 %d 人)已保存:%s", len(rows), save_path)
|
||||
|
||||
# 解析店长并构造单聊推送消息
|
||||
messages = build_messages(rows, roster_df)
|
||||
|
||||
# 汇总群聊推送:汇总文案 + 名单表格附件(dict 含 group 键,共享指令自动识别为群聊)
|
||||
group_msg = _build_group_push_message(save_path, begin, end_window)
|
||||
if group_msg:
|
||||
|
||||
@@ -4,7 +4,11 @@
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-13
|
||||
@Description: 雇主险名额调度系统「步骤2:调度」
|
||||
@Version: 1.3.0
|
||||
@Version: 1.4.0
|
||||
- v1.4.0:调度前自动前置处理——经 WPS/Excel COM 打开目标文件,取消所有 sheet 的
|
||||
筛选(AutoFilterMode=False,杜绝筛选状态下人工删贴数据错位、筛选残留),
|
||||
全量重算公式(CalculateFullRebuild,替代人工打开 Ctrl+S 刷新)后保存关闭。
|
||||
新增依赖 pywin32;目标文件若已在 WPS/Excel 中打开则复用当前工作簿保存。
|
||||
- v1.3.0:变更清单「费用会馆」列(表头含"费用会馆"即可,如 O列 新增费用会馆)
|
||||
自动填充四级部门——按证件号关联「花名册导出-雇主险使用基础信息」中
|
||||
表头含"四级部门"的列,仅「纯新增名额」(全新新增)的 增加 记录填写;
|
||||
@@ -21,7 +25,7 @@
|
||||
三十七度无后缀),与 HR 侧带后缀方案列表对齐。
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install pandas openpyxl
|
||||
pip install pandas openpyxl pywin32
|
||||
|
||||
环境变量(.env 文件或系统变量,可选):
|
||||
employer_insurance_base_dir = 文件目录(默认 D:\\资料\\人资\\雇主险)
|
||||
@@ -44,11 +48,13 @@ from datetime import datetime, date
|
||||
try:
|
||||
import pandas as pd
|
||||
from openpyxl import Workbook, load_workbook
|
||||
import pythoncom
|
||||
import win32com.client
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install pandas openpyxl\n"
|
||||
" pip install pandas openpyxl pywin32\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
@@ -1371,6 +1377,111 @@ def export_add_sub_import(category, biz_df, in_param_df, final_records, reused_s
|
||||
logger.info("执行顺序提醒:请先执行【减员】导入,再执行【增员】导入(涉及替换/修改的人员先增员会因方案冲突报错)")
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 五点六、前置处理:取消筛选 + WPS COM 刷新公式并保存
|
||||
# ============================================================
|
||||
# WPS/Excel 表格组件 ProgID 依次尝试:WPS 表格 → 旧版 WPS(ET) → MS Excel
|
||||
COM_PROG_IDS = ("Ket.Application", "et.Application", "Excel.Application")
|
||||
|
||||
|
||||
def refresh_and_unfilter_via_com(target_file):
|
||||
"""处理前经 WPS/Excel COM 打开目标文件:取消全部筛选 → 全量重算公式 → 保存关闭。
|
||||
|
||||
背景:
|
||||
1) 筛选状态下人工删除/粘贴花名册会导致数据错位,且残留筛选会一直留在文件里,
|
||||
后续在筛选状态下维护数据仍会出错——处理前统一 AutoFilterMode=False 彻底移除;
|
||||
2) roster_filter.py 经 openpyxl 覆盖写入后 P~W 公式列缓存丢失,必须全量重算并保存,
|
||||
pandas 才能读到公式计算结果(替代原「手动打开 Ctrl+S 刷新」步骤)。
|
||||
|
||||
ProgID 依次尝试 Ket.Application(WPS 表格)/ et.Application(旧版 WPS)/ Excel.Application;
|
||||
目标文件若已在 WPS/Excel 中打开,则直接复用当前工作簿(保存即用户当前所见内容),
|
||||
此时不会关闭该工作簿、也不会退出程序,避免影响用户正在使用的会话。
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 目标文件不存在。
|
||||
RuntimeError: 本机 WPS/Excel COM 均不可用(需安装 WPS 或 MS Excel,及 pip install pywin32)。
|
||||
"""
|
||||
abspath = os.path.abspath(target_file)
|
||||
if not os.path.isfile(abspath):
|
||||
raise FileNotFoundError(f"目标文件不存在:{abspath}")
|
||||
|
||||
pythoncom.CoInitialize()
|
||||
try:
|
||||
app = None
|
||||
last_err = None
|
||||
for prog_id in COM_PROG_IDS:
|
||||
try:
|
||||
app = win32com.client.Dispatch(prog_id)
|
||||
break
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
if app is None:
|
||||
raise RuntimeError(
|
||||
"无法启动 WPS/Excel COM(依次尝试 "
|
||||
+ " / ".join(COM_PROG_IDS)
|
||||
+ f" 均失败):{last_err}。\n"
|
||||
"请确认本机已安装 WPS 或 MS Excel,且已安装依赖:pip install pywin32")
|
||||
|
||||
wb = None
|
||||
already_open = False
|
||||
try:
|
||||
app.DisplayAlerts = False
|
||||
# 目标文件已在 WPS/Excel 中打开时复用该工作簿(保存即用户当前所见内容)
|
||||
for w in app.Workbooks:
|
||||
try:
|
||||
if os.path.normcase(str(w.FullName or "")) == os.path.normcase(abspath):
|
||||
wb = w
|
||||
already_open = True
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
if wb is None:
|
||||
wb = app.Workbooks.Open(abspath)
|
||||
|
||||
# 1. 取消所有 sheet 的筛选(彻底移除 AutoFilter,被隐藏的行全部恢复显示)
|
||||
removed = 0
|
||||
for ws in wb.Worksheets:
|
||||
try:
|
||||
if ws.AutoFilterMode:
|
||||
ws.AutoFilterMode = False
|
||||
removed += 1
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 2. 全量重算公式(重建公式依赖,确保公式缓存全部刷新)
|
||||
try:
|
||||
app.CalculateFullRebuild()
|
||||
except Exception:
|
||||
try:
|
||||
app.CalculateFull()
|
||||
except Exception:
|
||||
app.Calculate()
|
||||
|
||||
# 3. 保存(计算结果写入文件缓存,后续 pandas 才能读到)
|
||||
wb.Save()
|
||||
logger.info("前置处理完成:取消 %d 个 sheet 的筛选,公式全量重算并保存%s",
|
||||
removed, "(复用 WPS 中已打开的工作簿)" if already_open else "")
|
||||
finally:
|
||||
try:
|
||||
app.DisplayAlerts = True
|
||||
except Exception:
|
||||
pass
|
||||
# 新开的工作簿用完关闭;用户会话中已打开的不动,避免打断用户操作
|
||||
if wb is not None and not already_open:
|
||||
try:
|
||||
wb.Close(SaveChanges=False)
|
||||
except Exception:
|
||||
pass
|
||||
# 仅当无其他工作簿打开时退出程序,避免误关用户正在使用的 WPS/Excel
|
||||
try:
|
||||
if app.Workbooks.Count == 0:
|
||||
app.Quit()
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
pythoncom.CoUninitialize()
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 六、入口(步骤2:调度)
|
||||
# ============================================================
|
||||
@@ -1392,8 +1503,8 @@ def _check_import_templates():
|
||||
def schedule_category(category):
|
||||
"""对单个类别执行调度全流程(读取已刷新公式的目标文件,输出结果)。
|
||||
|
||||
前置:先运行 roster_filter.py(筛选复制),并手动打开目标文件
|
||||
刷新公式计算结果(Ctrl+S 保存)后,再运行本步骤。
|
||||
前置:先运行 roster_filter.py(筛选复制)。本步骤开始时自动经 WPS/Excel COM
|
||||
取消筛选、全量重算公式并保存,无需再手动打开目标文件刷新。
|
||||
"""
|
||||
category_name = category["name"]
|
||||
target_file = category_target_file(category)
|
||||
@@ -1408,6 +1519,9 @@ def schedule_category(category):
|
||||
logger.error("目标表不存在:%s,请先运行 roster_filter.py 步骤生成。", target_file)
|
||||
return
|
||||
|
||||
# ★ 前置处理:取消筛选 + WPS/Excel COM 全量重算公式并保存(替代人工打开刷新步骤)
|
||||
refresh_and_unfilter_via_com(target_file)
|
||||
|
||||
# 检查必需Sheet
|
||||
xl = pd.ExcelFile(target_file)
|
||||
required_sheets = [SHEET_BIZ, SHEET_IN_PARAM]
|
||||
@@ -1512,15 +1626,15 @@ def main(category_names: list[str] = None):
|
||||
category_names: 类别名列表(如 ["三十七度", "湖畔酒店"]),
|
||||
空列表 / None 表示处理全部类别。
|
||||
|
||||
前置:先运行 roster_filter.py(筛选复制),并手动打开目标文件
|
||||
刷新公式计算结果(Ctrl+S 保存)后,再运行本步骤。
|
||||
前置:先运行 roster_filter.py(筛选复制)。本步骤开始时自动经 WPS/Excel COM
|
||||
取消筛选、全量重算公式并保存,无需再手动打开目标文件刷新。
|
||||
"""
|
||||
categories = [get_category(n) for n in category_names] if category_names else CATEGORIES
|
||||
for category in categories:
|
||||
try:
|
||||
schedule_category(category)
|
||||
except DataValidationError:
|
||||
# 数据校验失败:整批中断,不再处理后续类别
|
||||
except (DataValidationError, RuntimeError):
|
||||
# 数据校验失败 / COM 前置处理失败(如本机无 WPS/Excel):整批中断,不再处理后续类别
|
||||
raise
|
||||
except Exception:
|
||||
logger.exception("类别[%s] 调度失败", category["name"])
|
||||
|
||||
@@ -0,0 +1,607 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0038 定性评价推送:OA 绩效评价单批量推送(蓝凌 EKP kmReviewMain)
|
||||
|
||||
功能:
|
||||
读取《定性评价导入明细.xlsx》的「加工辅助表」,按 定性发起标记(序号-部门-序列)
|
||||
+ 部门负责人工号 分组,每组推送一张绩效评价单:
|
||||
- 明细表多行 = 组内成员(按 Excel 行序),A-N 列数据原样填入
|
||||
- 人员类别 = 标记末段序列映射(管理→管理序列、专业→专业序列)
|
||||
- 被评价人(单选)= 第一顺序部门负责人
|
||||
- 绩效复核人(多选)= 全部部门负责人(按工号列顺序)
|
||||
默认仅暂存(草稿箱可见、不发起流程、零通知);确认无误后改 SEND_MODE=True 走真实发送。
|
||||
每组提交成功后自动回验 edit 页(明细工号、复核人是否落库)。
|
||||
|
||||
导出模式(RUN_MODE='export'):按门户查询方案(管理/专业序列定性评价,searchId 固化),
|
||||
以 创建时间=EXPORT_DATE(空=当天)为条件,走 search.do 结构化导出接口:
|
||||
1) dataxml.jsp?s_bean=sysSearchResultExportDictService 取字段字典(两方案模板独立、fd 不同,各自解析)
|
||||
2) GET search.do?method=result 建查询上下文并提取 exportNum 总数
|
||||
3) POST search.do?method=exportResult 直接返回 xls 字节流,落盘到数据源同目录并打印摘要
|
||||
无需解析 HTML;两方案当天实测 90/290 条全部拉全。
|
||||
导出后自动核对:取门户页内嵌登录信息(var userName/loginName)得到登录账号,
|
||||
「当前处理人」含登录账号姓名的行判为异常,生成 *_核对.xlsx(末列「异常标记」)。
|
||||
|
||||
数据源(DATA_FILE / DATA_SHEET,表头行=DATA_HEADER_ROW,首行为提示语):
|
||||
- A-N 列为 OA 明细数据,原样推送(定性得分/定性系数/定性占比/绩效系数/绩效等级留空,
|
||||
由负责人在 OA 端填写定性得分后页面联动计算)
|
||||
- P 列 定性发起标记:格式 序号-部门-序列,末段 管理/专业 决定人员类别
|
||||
- 「部门负责人工号」列:支持多个(、,,;;分隔),按顺序全部解析为绩效复核人
|
||||
|
||||
运行:项目根目录执行 .venv\\Scripts\\python.exe "workflows\\XQ0001-0100\\XQ0038 定性评价推送\\oa_review_push.py"
|
||||
依赖:requests、openpyxl(推送)/ xlrd(导出,仅导出模式用);登录态来自 oa_cookies.json,失效请先更新。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
from collections import OrderedDict
|
||||
|
||||
import requests
|
||||
|
||||
# ============ 配置区(按需修改) ============
|
||||
RUN_MODE = 'push' # 'push'=推送定性评价单;'export'=导出已提交单据数据(见下方导出配置)
|
||||
TEMPLATE_FD_ID = '1994af414ec11b46ca19109447fb6fb6' # 绩效评价单模板
|
||||
BASE_URL = 'https://oa.37du.co'
|
||||
COOKIE_FILE = os.path.join(os.getenv('LOCALAPPDATA'), '37duAutomation',
|
||||
'.sessions', 'oa_cookies.json')
|
||||
DATA_FILE = r'D:\资料\人资\定性评价推送\定性评价导入明细.xlsx'
|
||||
DATA_SHEET = '加工辅助表'
|
||||
DATA_HEADER_ROW = 2 # 表头所在行(首行为提示语)
|
||||
SEND_MODE = True # False=仅暂存草稿;True=真实发送(发起流程、通知复核人,不可逆)
|
||||
TEST_MODE = True # True=测试模式:明细「评价说明」末尾附加【测试】标志,便于负责人识别
|
||||
MAX_RETRY = 3 # 单组失败重试次数
|
||||
DEBUG = False # True 时输出调试信息
|
||||
|
||||
# ---- 导出模式配置(RUN_MODE='export' 时生效) ----
|
||||
MODEL_NAME = 'com.landray.kmss.km.review.model.KmReviewMain'
|
||||
SEARCH_PLANS = OrderedDict([ # 门户查询方案(管理/专业序列定性评价)
|
||||
('管理序列(新)', '199bd93c6d6998ef08fc293409cbc6a7'),
|
||||
('专业序列(新)', '199bd9679aebbf36aab8e224cd698d2b'),
|
||||
])
|
||||
EXPORT_DATE = '' # 创建时间条件(等于);空=运行当天
|
||||
EXPORT_KEYWORDS = ( # 导出列:按字段字典中文名「包含」匹配,两方案各自命中(如专业序列无「定性得分」)
|
||||
'KPI考核得分', 'KPI系数', '被评价人', '部门', '创建时间', '定性得分',
|
||||
'定性考评系数', '定性考评占比', '考核月份', '文档状态',
|
||||
'员工工号', '员工姓名显示值', '最终绩效等级', '最终绩效系数',
|
||||
)
|
||||
# ==========================================
|
||||
|
||||
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"Chrome/120.0.0.0 Safari/537.36")
|
||||
ADD_URL = (BASE_URL + '/km/review/km_review_main/kmReviewMain.do?method=add&fdTemplateId='
|
||||
+ TEMPLATE_FD_ID)
|
||||
EDIT_URL = BASE_URL + '/km/review/km_review_main/kmReviewMain.do?method=edit&fdId='
|
||||
VIEW_URL = BASE_URL + '/km/review/km_review_main/kmReviewMain.do?method=view&fdId='
|
||||
POST_URL = BASE_URL + '/km/review/km_review_main/kmReviewMain.do'
|
||||
SEARCH_URL = BASE_URL + '/sys/search/search.do'
|
||||
DATAXML_URL = BASE_URL + '/sys/common/dataxml.jsp'
|
||||
PORTAL_URL = (BASE_URL + '/sys/portal/page.jsp'
|
||||
'?portalId=174c4a7ebfac0e2a320e0474539b1251')
|
||||
|
||||
# 单头字段
|
||||
FD_REPORTER = 'fd_3b07f5cf6764ec' # 提报人(new_address,页面 JS 自动填当前用户)
|
||||
FD_CATEGORY = 'fd_3b07f60887a0e0' # 人员类别(单选)
|
||||
FD_EVAL_USER = 'fd_3b3ed9a88d549a' # 被评价人(relation_choose 单选)
|
||||
FD_MONTH = 'fd_3e7d96f3848888' # 考核月份
|
||||
FD_REVIEWER = 'fd_3e798512bd3dd8' # 绩效复核人(address 多选)
|
||||
|
||||
# 明细表(模板 fd_3b07f63c1975a2.<行号>.<fd>)字段 → 加工辅助表 A-N 列名
|
||||
DET_PREFIX = 'fd_3b07f63c1975a2'
|
||||
DET_USER_FD = 'fd_3e92ac2eabd704' # 明细行被评价人(address)
|
||||
DET_FIELDS = OrderedDict([
|
||||
('月份', 'fd_3b07f66df3dddc'),
|
||||
('工号', 'fd_3b07f66b2fd146'),
|
||||
('部门1', 'fd_3b07f6961e2d74'),
|
||||
('是否参与强制分布', 'fd_3e859de2c946a4'),
|
||||
('定性得分', 'fd_3e74f39c387020'),
|
||||
('定性系数', 'fd_3e74f39f1d12bc'),
|
||||
('定性占比', 'fd_3e74f3a1ee9b0e'),
|
||||
('KPI系数', 'fd_3b1bced70cac6e'),
|
||||
('KPI得分', 'fd_3b07f65f9c0cba'),
|
||||
('KPI占比', 'fd_3b07f65cbc2212'),
|
||||
('绩效系数', 'fd_3e74f39dcd3e78'),
|
||||
('绩效等级', 'fd_3e74f3a729b0b2'),
|
||||
('评价说明', 'fd_3e7b401a25c082'),
|
||||
])
|
||||
|
||||
SERIES_MAP = {'管理': '管理序列', '专业': '专业序列'}
|
||||
|
||||
TAG_RE = re.compile(r'<input\b[^>]*>|<textarea\b[^>]*>.*?</textarea>', re.S | re.I)
|
||||
ATTR_RE = re.compile(r'''(name|value|type|checked|selected)\s*=\s*("([^"]*)"|'([^']*)')''', re.I)
|
||||
|
||||
|
||||
def log(msg):
|
||||
print(time.strftime('[%H:%M:%S] ') + str(msg), flush=True)
|
||||
|
||||
|
||||
def build_session():
|
||||
s = requests.Session()
|
||||
s.headers.update({"User-Agent": UA,
|
||||
"Referer": BASE_URL + "/km/review/km_review_main/kmReviewMain.do",
|
||||
"Origin": BASE_URL})
|
||||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||||
for c in json.load(f):
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
s.cookies.set(c["name"], c["value"], domain=c["domain"],
|
||||
path=c.get("path", "/"))
|
||||
return s
|
||||
|
||||
|
||||
def get_attrs(tag):
|
||||
out = {}
|
||||
for m in ATTR_RE.finditer(tag):
|
||||
val = m.group(3) if m.group(3) is not None else m.group(4)
|
||||
out[m.group(1).lower()] = val
|
||||
for flag in ('checked', 'selected'):
|
||||
if re.search(r'\b%s\b' % flag, tag, re.I) and flag not in out:
|
||||
out[flag] = flag
|
||||
return out
|
||||
|
||||
|
||||
def parse_fields(page):
|
||||
"""解析 add 页全部 input/textarea 为 (name, value) 保序列表(模拟浏览器整表提交)。"""
|
||||
fields = []
|
||||
for tag in TAG_RE.findall(page):
|
||||
low = tag.lower()
|
||||
if low.startswith('<textarea'):
|
||||
m = re.search(r'name\s*=\s*("([^"]*)"|\'([^\']*)\')', tag, re.I)
|
||||
if not m:
|
||||
continue
|
||||
name = m.group(2) if m.group(2) is not None else m.group(3)
|
||||
body = re.match(r'<textarea\b[^>]*>(.*?)</textarea>', tag, re.S | re.I)
|
||||
fields.append((name, body.group(1) if body else ''))
|
||||
continue
|
||||
a = get_attrs(tag)
|
||||
name = a.get('name')
|
||||
if name is None:
|
||||
continue
|
||||
itype = (a.get('type') or 'text').lower()
|
||||
if itype in ('submit', 'button', 'image', 'file', 'reset'):
|
||||
continue
|
||||
if itype in ('checkbox', 'radio') and 'checked' not in a:
|
||||
continue
|
||||
fields.append((name, a.get('value', '')))
|
||||
return fields
|
||||
|
||||
|
||||
def org_search(s, key):
|
||||
"""通讯录查询(orgType=8 人员):key 支持工号精确/姓名模糊,返回 (id, name)。"""
|
||||
resp = s.post(BASE_URL + '/sys/common/dataxml.jsp',
|
||||
data={"s_bean": "organizationDialogSearch", "key": key,
|
||||
"startWith": "", "orgType": "8", "times": "2"}, timeout=20)
|
||||
m = re.search(r'<data\b[^>]*>', resp.text)
|
||||
if not m:
|
||||
return None, None
|
||||
tag = m.group(0)
|
||||
i = re.search(r'''\bid="([^"]+)"''', tag)
|
||||
n = re.search(r'''\bname="([^"]+)"''', tag)
|
||||
return (i.group(1) if i else None, n.group(1) if n else None)
|
||||
|
||||
|
||||
# ---------- 导出模式(search.do 结构化导出) ----------
|
||||
|
||||
def get_export_columns(s, search_id):
|
||||
"""查询方案字段字典,返回 [(fd, 中文名), ...]。"""
|
||||
resp = s.get(DATAXML_URL, params={"s_bean": "sysSearchResultExportDictService",
|
||||
"fdModelName": MODEL_NAME, "searchId": search_id,
|
||||
"type": "opt"}, timeout=20)
|
||||
return re.findall(r'<data\s+key0="([^"]+)"\s+key1="([^"]*)"', resp.text)
|
||||
|
||||
|
||||
def export_plan_once(s, search_id, day, out_path):
|
||||
"""单次导出一个查询方案,返回 (行数, 错误信息);错误信息为空即成功。"""
|
||||
ts = str(int(time.time() * 1000))
|
||||
# 条件槽位与门户抓包一致:v0_2=eq & v1_2=创建时间(当天)
|
||||
base = {"method": "result", "fdModelName": MODEL_NAME, "searchId": search_id,
|
||||
"canClose": "false", "isNew": "true", "j_aside": "false",
|
||||
"j_rIframe": "true", "j_iframe": "true",
|
||||
"v0_2": "eq", "v1_2": day, "j_timestamp": ts}
|
||||
resp = s.get(SEARCH_URL, params=base, timeout=30, headers={"Referer": SEARCH_URL})
|
||||
m = re.search(r'exportNum:\s*"(\d+)"', resp.text)
|
||||
if not m:
|
||||
return None, '结果页未取得 exportNum(登录态可能失效,请更新 oa_cookies.json)'
|
||||
total = int(m.group(1))
|
||||
if total == 0:
|
||||
return 0, ''
|
||||
cols = [fd for fd, name in get_export_columns(s, search_id)
|
||||
if any(kw in name for kw in EXPORT_KEYWORDS)]
|
||||
if not cols:
|
||||
return None, '字段字典未匹配到导出列'
|
||||
data = dict(base)
|
||||
data["method"] = "exportResult"
|
||||
data.update({"fdColumns": ';'.join(cols), "fdNum": str(total),
|
||||
"fdNumStart": "1", "fdNumEnd": str(total),
|
||||
"fdKeepRtfStyle": "true", "checkIdValues": ""})
|
||||
resp = s.post(SEARCH_URL, data=data, timeout=120, headers={"Referer": SEARCH_URL})
|
||||
ctype = resp.headers.get('Content-Type', '')
|
||||
if 'application/vnd.ms-excel' not in ctype:
|
||||
text = re.sub(r'\s+', ' ', re.sub(r'<[^>]+>', ' ', resp.text))
|
||||
return None, '导出返回非 xls(%s):%s' % (ctype, text[:150])
|
||||
with open(out_path, 'wb') as f:
|
||||
f.write(resp.content)
|
||||
return total, ''
|
||||
|
||||
|
||||
def get_login_user(s):
|
||||
"""门户页内嵌登录信息,返回 (姓名 userName, 登录名/工号 loginName)。"""
|
||||
resp = s.get(PORTAL_URL, timeout=30)
|
||||
name = re.search(r"var\s+userName\s*=\s*'([^']*)'", resp.text)
|
||||
no = re.search(r"var\s+loginName\s*=\s*'([^']*)'", resp.text)
|
||||
return (name.group(1) if name else '', no.group(1) if no else '')
|
||||
|
||||
|
||||
def audit_xls(path, user_name):
|
||||
"""核对导出 xls:「当前处理人」含登录账号姓名 -> 异常,生成 *_核对.xlsx。
|
||||
|
||||
返回异常行数(user_name 为空时跳过核对返回 -1)。
|
||||
导出表只有姓名文本、无处理人工号列(字段字典无此字段),故按姓名匹配。
|
||||
"""
|
||||
import openpyxl
|
||||
import xlrd
|
||||
wb = xlrd.open_workbook(path)
|
||||
sh = wb.sheet_by_index(0)
|
||||
head = [str(sh.cell_value(0, c)) for c in range(sh.ncols)]
|
||||
if '当前处理人' not in head:
|
||||
log(' 核对跳过:导出表无「当前处理人」列')
|
||||
return -1
|
||||
proc_idx = head.index('当前处理人')
|
||||
key_idx = {n: (head.index(n) if n in head else -1)
|
||||
for n in ('员工工号', '被评价人', '当前环节')}
|
||||
rows_out, bad = [], []
|
||||
for r in range(sh.nrows):
|
||||
vals = []
|
||||
for c in range(sh.ncols):
|
||||
v = sh.cell_value(r, c)
|
||||
if isinstance(v, float) and '时间' in head[c]:
|
||||
try:
|
||||
v = xlrd.xldate.xldate_as_datetime(v, wb.datemode).strftime(
|
||||
'%Y-%m-%d %H:%M')
|
||||
except Exception:
|
||||
pass
|
||||
vals.append('' if v is None else str(v))
|
||||
if r == 0:
|
||||
vals.append('异常标记')
|
||||
else:
|
||||
handlers = [x.strip() for x in re.split(r'[;;,,]', vals[proc_idx])
|
||||
if x.strip()]
|
||||
mark = '异常:当前处理人含登录账号' if user_name and user_name in handlers else ''
|
||||
if mark:
|
||||
bad.append(vals)
|
||||
vals.append(mark)
|
||||
rows_out.append(vals)
|
||||
out_path = re.sub(r'\.xls$', '_核对.xlsx', path)
|
||||
owb = openpyxl.Workbook()
|
||||
osh = owb.active
|
||||
osh.title = '核对结果'
|
||||
for vals in rows_out:
|
||||
osh.append(vals)
|
||||
owb.save(out_path)
|
||||
log(' sheet=%s 行=%d(含表头) 列=%d -> %s'
|
||||
% (sh.name, sh.nrows, sh.ncols, os.path.basename(out_path)))
|
||||
log(' 异常 %d 行(当前处理人=%s)' % (len(bad), user_name or '未知,未核对'))
|
||||
for vals in bad[:20]:
|
||||
log(' %s | %s | %s | 处理人=%s' % (
|
||||
vals[key_idx['员工工号']], vals[key_idx['被评价人']],
|
||||
vals[key_idx['当前环节']], vals[proc_idx]))
|
||||
return len(bad)
|
||||
|
||||
|
||||
def run_export():
|
||||
day = EXPORT_DATE or time.strftime('%Y-%m-%d')
|
||||
out_dir = os.path.dirname(DATA_FILE)
|
||||
s = build_session()
|
||||
log('导出模式:创建时间=%s,方案 %d 个' % (day, len(SEARCH_PLANS)))
|
||||
user_name, login_no = get_login_user(s)
|
||||
if user_name:
|
||||
log('登录账号:%s(%s),将核对当前处理人' % (user_name, login_no))
|
||||
else:
|
||||
log('警告:未取得门户登录账号,跳过当前处理人核对')
|
||||
fail = []
|
||||
for name, sid in SEARCH_PLANS.items():
|
||||
label = name.split('(')[0]
|
||||
out_path = os.path.join(out_dir, '定性评价结果_%s_%s.xls'
|
||||
% (label, day.replace('-', '')))
|
||||
last_err = ''
|
||||
for attempt in range(1, MAX_RETRY + 1):
|
||||
try:
|
||||
total, err = export_plan_once(s, sid, day, out_path)
|
||||
except Exception:
|
||||
total, err = None, '异常: ' + traceback.format_exc(limit=1).replace('\n', ' ')
|
||||
if not err:
|
||||
log('%s -> %d 条 -> %s' % (name, total, out_path))
|
||||
if total:
|
||||
audit_xls(out_path, user_name)
|
||||
break
|
||||
last_err = err
|
||||
log('%s -> 第%d次失败:%s' % (name, attempt, err))
|
||||
time.sleep(1)
|
||||
else:
|
||||
fail.append((name, last_err))
|
||||
log('==== 导出完成:成功 %d / 失败 %d ====' % (len(SEARCH_PLANS) - len(fail), len(fail)))
|
||||
for name, err in fail:
|
||||
log('失败 %s:%s' % (name, err))
|
||||
return 0 if not fail else 1
|
||||
|
||||
|
||||
# ---------- 数据读取与分组 ----------
|
||||
|
||||
def clean_header(h):
|
||||
"""列名清洗:去掉 (*) 与尾部中文括号注记,如 月份(*)→月份、定性得分(仅修改此项)→定性得分。"""
|
||||
h = re.sub(r'\(\*\)\s*$', '', h.strip())
|
||||
h = re.sub(r'([^)]*)\s*$', '', h)
|
||||
return h.strip()
|
||||
|
||||
|
||||
def read_groups():
|
||||
"""读取加工辅助表并按(标记序号, 序列, 部门负责人工号串)分组。
|
||||
|
||||
返回 (总行数, OrderedDict{key: [行记录,...]}),组内行序=Excel 行序。
|
||||
行记录 = {明细列名: 值}(A-N 原样)。
|
||||
"""
|
||||
import openpyxl
|
||||
wb = openpyxl.load_workbook(DATA_FILE, read_only=True, data_only=True)
|
||||
if DATA_SHEET not in wb.sheetnames:
|
||||
raise ValueError('数据文件缺少 sheet:%s(现有:%s)'
|
||||
% (DATA_SHEET, '/'.join(wb.sheetnames)))
|
||||
ws = wb[DATA_SHEET]
|
||||
it = ws.iter_rows(values_only=True)
|
||||
for _ in range(DATA_HEADER_ROW - 1):
|
||||
next(it, None)
|
||||
header = [clean_header('' if h is None else str(h)) for h in next(it)]
|
||||
col = {}
|
||||
for i, h in enumerate(header):
|
||||
if h and h not in col:
|
||||
col[h] = i
|
||||
need = list(DET_FIELDS.keys()) + ['定性发起标记', '部门负责人工号']
|
||||
miss = [c for c in need if c not in col]
|
||||
if miss:
|
||||
raise ValueError('加工辅助表缺少列:%s' % '、'.join(miss))
|
||||
|
||||
rows = []
|
||||
for vals in it:
|
||||
if vals is None or all(v is None or str(v).strip() == '' for v in vals):
|
||||
continue
|
||||
r = {}
|
||||
for c in need:
|
||||
i = col[c]
|
||||
v = vals[i] if i < len(vals) else None
|
||||
r[c] = '' if v is None else str(v).strip()
|
||||
if not r['工号'] or not r['定性发起标记']:
|
||||
continue
|
||||
rows.append(r)
|
||||
wb.close()
|
||||
|
||||
groups = OrderedDict()
|
||||
for r in rows:
|
||||
parts = [p.strip() for p in r['定性发起标记'].split('-')]
|
||||
if len(parts) < 3:
|
||||
raise ValueError('定性发起标记格式异常:%s(工号 %s)'
|
||||
% (r['定性发起标记'], r['工号']))
|
||||
series = parts[-1]
|
||||
if series not in SERIES_MAP:
|
||||
raise ValueError('未知序列:%s(标记 %s,工号 %s)'
|
||||
% (series, r['定性发起标记'], r['工号']))
|
||||
owner_nos = tuple(n for n in re.split(r'[、,,;;\s]+', r['部门负责人工号']) if n)
|
||||
if not owner_nos:
|
||||
raise ValueError('部门负责人工号为空(工号 %s)' % r['工号'])
|
||||
key = (parts[0], series, owner_nos)
|
||||
groups.setdefault(key, []).append(r)
|
||||
return len(rows), groups
|
||||
|
||||
|
||||
# ---------- 单据创建 ----------
|
||||
|
||||
def fill_and_post(s, group):
|
||||
"""推送一组(一张单,明细多行),返回 (fdId, 是否成功, 说明)。失败由调用方重试。"""
|
||||
seq_no, series, owner_nos = group['key']
|
||||
rows = group['rows']
|
||||
|
||||
# 1) 解析部门负责人(多选,按工号列顺序)
|
||||
owners = []
|
||||
for no in owner_nos:
|
||||
o_id, o_name = org_search(s, no)
|
||||
if not o_id:
|
||||
return '', False, '通讯录未查到部门负责人工号 %s' % no
|
||||
owners.append((o_id, o_name))
|
||||
|
||||
# 2) 解析组内成员(按 Excel 行序,同工号复用)
|
||||
members = OrderedDict()
|
||||
for r in rows:
|
||||
no = r['工号']
|
||||
if no in members:
|
||||
continue
|
||||
m_id, m_name = org_search(s, no)
|
||||
if not m_id:
|
||||
return '', False, '通讯录未查到工号 %s' % no
|
||||
members[no] = (m_id, m_name)
|
||||
|
||||
# 3) 取 add 页(每次独立,fdId 服务端预生成)
|
||||
resp = s.get(ADD_URL, timeout=30)
|
||||
page = resp.text
|
||||
if 'kmReviewMainForm' not in page:
|
||||
return '', False, 'add 页加载异常(登录态可能失效,请更新 oa_cookies.json)'
|
||||
data = dict(parse_fields(page))
|
||||
fd_id = data.get('fdId', '')
|
||||
|
||||
# 4) 单头
|
||||
data['method'] = 'saveDraft' if not SEND_MODE else 'save'
|
||||
data['docStatus'] = '10'
|
||||
if not SEND_MODE:
|
||||
# 暂存开关(浏览器"暂存"按钮行为):服务端走仅保存分支、不启动流程
|
||||
data['sysWfBusinessForm.canStartProcess'] = 'false'
|
||||
data['extendDataFormInfo.value(%s)' % FD_CATEGORY] = SERIES_MAP[series]
|
||||
# 被评价人(人员类别2,relationChoose 关联工号串):实测手动发起的成功单据该字段为空,
|
||||
# 子流程(N7 启动子流程)数据映射依赖它;若填入"工号字符串"会使子流程被评价人解析失效,
|
||||
# 报"启动子流程失败,存在处理人为空或失效"。故留空(与手动发起一致)。
|
||||
for suffix in ('', '_text', '_dataFdId', '_dataSourceId', '_dataModelName',
|
||||
'_selectedDatas'):
|
||||
data['extendDataFormInfo.value(%s%s)' % (FD_EVAL_USER, suffix)] = ''
|
||||
# 考核月份(取组内首行月份,与明细一致)
|
||||
data['extendDataFormInfo.value(%s)' % FD_MONTH] = rows[0]['月份']
|
||||
# 绩效复核人(多选地址本,分号分隔、按工号列顺序)
|
||||
data['extendDataFormInfo.value(%s.id)' % FD_REVIEWER] = ';'.join(o[0] for o in owners)
|
||||
data['extendDataFormInfo.value(%s.name)' % FD_REVIEWER] = ';'.join(o[1] for o in owners)
|
||||
|
||||
# 5) 明细多行(A-N 列原样,行序=Excel 行序)
|
||||
det_prefix = 'extendDataFormInfo.value(%s.' % DET_PREFIX
|
||||
data = {k: v for k, v in data.items() if not k.startswith(det_prefix)}
|
||||
row_pairs = []
|
||||
for i, r in enumerate(rows):
|
||||
m_id, m_name = members[r['工号']]
|
||||
row_pairs.append(('%s%d.fdId)' % (det_prefix, i), ''))
|
||||
for col_name, fd in DET_FIELDS.items():
|
||||
val = r.get(col_name, '')
|
||||
if col_name == '评价说明' and TEST_MODE:
|
||||
val = val + '【测试】' if val else '【测试】'
|
||||
row_pairs.append(('%s%d.%s)' % (det_prefix, i, fd), val))
|
||||
row_pairs.append(('%s%d.%s.id)' % (det_prefix, i, DET_USER_FD), m_id))
|
||||
row_pairs.append(('%s%d.%s.name)' % (det_prefix, i, DET_USER_FD), m_name))
|
||||
|
||||
# 6) 流程参数(严格还原 add 页 /sys/lbpmservice/include/syslbpmprocess_submit.js
|
||||
# 中 lbpm.globals.setParameterOnSubmit() + 起草提交操作 operation_drafter_submit.js
|
||||
# 的 setOperationParam() 的组装结果):
|
||||
# taskId = lbpm.nowProcessorInfoObj.id → fdCurNodeXML 中 draftWorkitem 任务 id
|
||||
# processId = $("input[name='sysWfBusinessForm.fdProcessId']").val()
|
||||
# activityType = lbpm.nowProcessorInfoObj.type → "draftWorkitem"
|
||||
# operationType= lbpm.currentOperationType → 选中 oprGroup=drafter_submit:提交文档
|
||||
# param.operationName = 当前操作名(提交文档)
|
||||
# param.identityId = rolesSelectObj 选中值 → 提交人身份(fdIdentityId/fdDefaultIdentity)
|
||||
# 注意 activityType 必须是 draftWorkitem:若误传 draftNode,引擎会在 draftNode
|
||||
# 活动里按 taskId 找不到工作项,抛 TaskRefExecutionIsNullException(页面提示
|
||||
# "当前处理的流程已被其他人抢先一步提交")。
|
||||
# 提交人身份/操作(浏览器真实提交参数,经 agent-browser 抓包验证):
|
||||
# 表单字段 oprGroup=drafter_submit:提交文档、rolesSelectObj=<身份id>、
|
||||
# sysWfBusinessForm.fdSystemNotifyType={}、提报人 extendDataFormInfo.value(fd_xxx.id)
|
||||
# param 内 identityId、operationName。这些缺一不可:引擎读 oprGroup/身份来确定
|
||||
# "提交人/启动人",漏传会导致子流程启动节点解析启动人身份为空/失效,
|
||||
# 报"启动子流程失败,存在处理人为空或失效"(对应启动人策略③提示错误)。
|
||||
param_json = {
|
||||
"taskId": "", "processId": fd_id, "activityType": "draftWorkitem",
|
||||
"param": {"notifyType": "{}",
|
||||
"notifyLevel": data.get('sysWfBusinessForm.fdNotifyLevel', '3'),
|
||||
"notifyOnFinish": True, "notifyForFollow": False,
|
||||
"auditNote": "",
|
||||
"auditNoteFdId": data.get('sysWfBusinessForm.fdAuditNoteFdId', ''),
|
||||
"dayOfNotifyDrafter": "0", "hourOfNotifyDrafter": "0",
|
||||
"minuteOfNotifyDrafter": "0"},
|
||||
}
|
||||
if SEND_MODE:
|
||||
# 真实发起:taskId 必须指向 fdCurNodeXML 中注册了 drafter_submit 操作的
|
||||
# draftWorkitem 任务(taskId 为空会默认落到 draftNode 任务,而该任务只注册
|
||||
# drafter_abandon 操作,报"drafter_submit操作未授权")。该隐藏域 value 在
|
||||
# HTML 中整体转义(< " 等),需先反转义再解析。
|
||||
m_xml = re.search(
|
||||
r'name="sysWfBusinessForm\.fdCurNodeXML"[^>]*value="([^"]*)"', page)
|
||||
raw = m_xml.group(1) if m_xml else ''
|
||||
raw = raw.replace('"', '"').replace('<', '<').replace('>', '>')
|
||||
m_task = re.search(r'<task type="draftWorkitem"[^>]*id="([^"]+)"', raw)
|
||||
param_json["taskId"] = m_task.group(1) if m_task else ''
|
||||
param_json["operationType"] = "drafter_submit"
|
||||
param_json["processId"] = data.get('sysWfBusinessForm.fdProcessId', '') or fd_id
|
||||
# 提交人身份(弹窗选中值=rolesSelectObj;页面默认 fdIdentityId/fdDefaultIdentity)
|
||||
identity_id = (data.get('sysWfBusinessForm.fdIdentityId', '')
|
||||
or data.get('sysWfBusinessForm.fdDefaultIdentity', '') or '')
|
||||
param_json["param"]["identityId"] = identity_id
|
||||
param_json["param"]["operationName"] = "提交文档"
|
||||
# 浏览器真实提交的流程相关表单字段(引擎据 oprGroup/rolesSelectObj 确定操作人与身份)
|
||||
data['oprGroup'] = 'drafter_submit:提交文档'
|
||||
data['rolesSelectObj'] = identity_id
|
||||
data['handlerIds[0]'] = ''
|
||||
data['handlerNames[0]'] = ''
|
||||
data['commonUsages'] = ''
|
||||
data['fdCanCircularize'] = 'true'
|
||||
data['sysWfBusinessForm.fdSystemNotifyType'] = '{}'
|
||||
if identity_id:
|
||||
data['extendDataFormInfo.value(%s.id)' % FD_REPORTER] = identity_id
|
||||
log('[DEBUG] 发起参数 fdId=%s taskId=%s processId=%s identityId=%s'
|
||||
% (fd_id, param_json['taskId'], param_json['processId'], identity_id))
|
||||
data['sysWfBusinessForm.fdParameterJson'] = json.dumps(
|
||||
param_json, separators=(',', ':'), ensure_ascii=False)
|
||||
|
||||
payload = list(data.items()) + row_pairs
|
||||
if DEBUG:
|
||||
log('[DEBUG] payload 字段数=%d fdId=%s 明细行数=%d 复核人=%s'
|
||||
% (len(payload), fd_id, len(rows), [o[1] for o in owners]))
|
||||
|
||||
# 7) 提交
|
||||
post = s.post(POST_URL, data=payload, timeout=30, allow_redirects=True)
|
||||
body = post.text
|
||||
if SEND_MODE:
|
||||
# 成功会返回 edit 页(含 ResourceStringCache 等内联 JS,其中可能有
|
||||
# "Exception"字样,不能用它判断失败);服务端错误页固定含"很抱歉,
|
||||
# 操作失败"。提交是否真正落库交由下方 edit 页回验兜底。
|
||||
ok = (post.status_code == 200 and '很抱歉,操作失败' not in body)
|
||||
else:
|
||||
ok = ('您的操作已成功' in body) or ('method=edit&fdId=' in body)
|
||||
if ok:
|
||||
# 8) edit 页回验:明细每人工号、复核人姓名是否落库
|
||||
miss = verify_draft(s, fd_id, rows, owners)
|
||||
if miss:
|
||||
return fd_id, False, '已提交但回验缺失:%s' % '、'.join(miss)
|
||||
return fd_id, True, ('发送成功' if SEND_MODE else '草稿成功')
|
||||
text = re.sub(r'<[^>]+>', ' ', body)
|
||||
text = re.sub(r'\s+', ' ', text)
|
||||
m = re.search(r'(很抱歉,操作失败.*?)(?:</|$)', text)
|
||||
return fd_id, False, (m.group(1)[:200] if m else text[:200])
|
||||
|
||||
|
||||
def verify_draft(s, fd_id, rows, owners):
|
||||
"""回验落库,返回缺失项列表(空=通过)。
|
||||
|
||||
暂存走 edit 页(起草人可编辑);真实发送后单据已进入复核人待办、起草人失去
|
||||
编辑权(edit 返回 403),须改走 view 页(提交后仍可只读查看)。
|
||||
"""
|
||||
resp = s.get((VIEW_URL if SEND_MODE else EDIT_URL) + fd_id, timeout=30)
|
||||
body = resp.text
|
||||
miss = [r['工号'] for r in rows if r['工号'] not in body]
|
||||
miss += ['复核人' + o[1] for o in owners if o[1] and o[1] not in body]
|
||||
return miss
|
||||
|
||||
|
||||
def process_one(s, group, seq):
|
||||
"""单组处理,含全局重试。"""
|
||||
seq_no, series, owner_nos = group['key']
|
||||
label = '组%d %s-%s 负责人[%s] %d人' % (
|
||||
seq, seq_no, series, '/'.join(owner_nos), len(group['rows']))
|
||||
last_err = ''
|
||||
for attempt in range(1, MAX_RETRY + 1):
|
||||
try:
|
||||
fd_id, ok, msg = fill_and_post(s, group)
|
||||
except Exception:
|
||||
last_err = '异常: ' + traceback.format_exc(limit=1).replace('\n', ' ')
|
||||
fd_id, ok, msg = '', False, last_err
|
||||
if ok:
|
||||
log('%s -> %s fdId=%s' % (label, msg, fd_id))
|
||||
return True, fd_id
|
||||
last_err = msg
|
||||
log('%s -> 第%d次失败:%s' % (label, attempt, msg))
|
||||
time.sleep(1)
|
||||
log('%s -> 已重试%d次仍失败' % (label, MAX_RETRY))
|
||||
return False, last_err
|
||||
|
||||
|
||||
def main():
|
||||
if RUN_MODE == 'export':
|
||||
return run_export()
|
||||
row_cnt, groups = read_groups()
|
||||
log('读取 %d 行,分 %d 组(%s | 模式=%s)' % (
|
||||
row_cnt, len(groups), os.path.basename(DATA_FILE),
|
||||
'真实发送' if SEND_MODE else '仅暂存'))
|
||||
s = build_session()
|
||||
ok_cnt, fail_list = 0, []
|
||||
for seq, (key, grp_rows) in enumerate(groups.items(), 1):
|
||||
ok, info = process_one(s, {'key': key, 'rows': grp_rows}, seq)
|
||||
if ok:
|
||||
ok_cnt += 1
|
||||
else:
|
||||
fail_list.append((seq, key, len(grp_rows), info))
|
||||
log('==== 完成:成功 %d 组 / 失败 %d 组 ====' % (ok_cnt, len(fail_list)))
|
||||
for seq, key, cnt, err in fail_list:
|
||||
log('失败 组%d %s-%s 负责人[%s] %d人:%s'
|
||||
% (seq, key[0], key[1], '/'.join(key[2]), cnt, err))
|
||||
return 0 if not fail_list else 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -1,314 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""探针(只读):验证「HR WeProcess.mc?method=getProcessAndData」能否替代 OA 待办接口 + SSO 解析。
|
||||
背景:XQ0003 请假 / XQ0004 加班 / XQ0020 改签离职电子签流程 三个审核流程目前链路为
|
||||
OA 待办(sysNotifyMainIndex.do, fdType=13) -> 详情链接 SSO 跳转解析(taskId/businessKey)
|
||||
-> WfActivity 取 formId -> WorkformEngine 取表单(SSO 后落地均在 hr.37du.co)。
|
||||
本探针验证:
|
||||
1) 仅用 hr_cookies.json 调 WeProcess 按标题关键字拉待办(不依赖 OA 登录态);
|
||||
2) 与 OA 待办接口同关键字结果做数量/标题一致性比对(验证 OA 与 HR 数据一致);
|
||||
3) 免 SSO 链路:WeProcess 返回的 taskId -> WfActivity 取 formId -> WorkformEngine
|
||||
getBusinessDate 取表单数据(全程纯 HR 接口),证明无需浏览器 SSO 解析。
|
||||
注意事项(实测结论):
|
||||
- WeProcess 响应结构为 {state, meg, total, isRecord, result, jsonList},数据在 jsonList;
|
||||
- 会话过期时 state=Nosession、meg=会话过期,需先运行 hr_login_api.py 刷新登录态。
|
||||
只读探针:不发审批、不写任何业务文件,仅控制台输出。
|
||||
运行:.venv\\Scripts\\python.exe workflows/share/_probe_we_process_todo.py
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
from datetime import datetime
|
||||
from urllib.parse import urlencode
|
||||
|
||||
import requests
|
||||
|
||||
_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')
|
||||
HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
OA_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||||
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
OA_BASE_URL = "https://oa.37du.co"
|
||||
WE_PROCESS_URL = f"{HR_BASE_URL}/RedseaPlatform/WeProcess.mc?method=getProcessAndData"
|
||||
OA_TODO_URL = f"{OA_BASE_URL}/sys/notify/sys_notify_todo/sysNotifyMainIndex.do"
|
||||
WF_ACTIVITY_URL = f"{HR_BASE_URL}/RedseaPlatform/WfActivity.mc"
|
||||
WORKFORM_ENGINE_URL = f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc"
|
||||
|
||||
# 三个审核流程的待办主题关键字(与各自 main() 中 run_flow(subject=...) 完全一致)
|
||||
SUBJECTS = ["请假", "加班", "改签离职电子签流程"]
|
||||
|
||||
PAGE_SIZE = 100
|
||||
USER_AGENT = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"Chrome/120.0.0.0 Safari/537.36")
|
||||
|
||||
|
||||
def _mtime(path):
|
||||
try:
|
||||
return datetime.fromtimestamp(os.path.getmtime(path)).strftime("%Y-%m-%d %H:%M:%S")
|
||||
except OSError:
|
||||
return "不存在"
|
||||
|
||||
|
||||
def load_cookies(path):
|
||||
if not os.path.exists(path):
|
||||
return None
|
||||
with open(path, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
def build_session(cookies, domain_keyword=None):
|
||||
session = requests.Session()
|
||||
session.headers.update({"User-Agent": USER_AGENT,
|
||||
"X-Requested-With": "XMLHttpRequest"})
|
||||
for c in cookies or []:
|
||||
domain = c.get("domain") or ""
|
||||
if domain_keyword and domain_keyword not in domain:
|
||||
continue
|
||||
if domain:
|
||||
session.cookies.set(c["name"], c["value"], domain=domain, path=c.get("path", "/"))
|
||||
else:
|
||||
session.cookies.set(c["name"], c["value"])
|
||||
return session
|
||||
|
||||
|
||||
def _is_login_page(text):
|
||||
return bool(text) and ("login.jsp" in text or "j_username" in text)
|
||||
|
||||
|
||||
def _is_json(text):
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
|
||||
|
||||
def _row(row, *names):
|
||||
"""行字段多候选取值(兼容 jsonList 驼峰/下划线字段名)。"""
|
||||
for n in names:
|
||||
v = row.get(n)
|
||||
if v not in (None, ""):
|
||||
return v
|
||||
return ""
|
||||
|
||||
|
||||
# ==================== OA 侧:待办列表(现状链路) ====================
|
||||
def oa_todo_page(session, subject, page_no=1, page_size=PAGE_SIZE):
|
||||
params = {
|
||||
"method": "list", "dataType": "todo", "fdType": "13", "fdCateId": "",
|
||||
"q.s_raq": str(random.random()), "q.fdSubject": subject,
|
||||
"pageno": page_no, "rowsize": page_size, "pagingtype": "default",
|
||||
"orderby": "fdCreateTime", "ordertype": "down",
|
||||
}
|
||||
resp = session.get(f"{OA_TODO_URL}?{urlencode(params)}", timeout=20)
|
||||
text = resp.text or ""
|
||||
if _is_login_page(text):
|
||||
raise RuntimeError("OA 登录态失效(返回登录页)")
|
||||
if not _is_json(text):
|
||||
raise RuntimeError(f"OA 待办接口返回非 JSON(前 80 字符):{text[:80]}")
|
||||
return resp.json()
|
||||
|
||||
|
||||
def oa_parse_rows(data):
|
||||
"""复刻 XQ0003 parse_todo_list:解析标题/发起人/时间/详情链接,跳过协作类待办。"""
|
||||
docs, skipped = [], 0
|
||||
for row in data.get("datas") or []:
|
||||
cells = {c.get("col"): (c.get("value") or "") for c in row if isinstance(c, dict)}
|
||||
title_raw = cells.get("todo.subject4View", "")
|
||||
match = re.search(r'<span class="subjecthead"[^>]*>(.*?)</span>', title_raw, re.DOTALL)
|
||||
title = match.group(1).strip() if match else re.sub(r'<[^>]+>', '', title_raw).strip()
|
||||
detail_url = cells.get("tr_href", "")
|
||||
if detail_url and not detail_url.startswith(("http://", "https://")):
|
||||
detail_url = OA_BASE_URL + detail_url
|
||||
if "kmCollaborateMain.do" in detail_url:
|
||||
skipped += 1
|
||||
continue
|
||||
docs.append({"title": title, "creator": cells.get("docCreatorName", ""),
|
||||
"time": cells.get("fdCreateTime", ""), "detail_url": detail_url})
|
||||
return docs, skipped
|
||||
|
||||
|
||||
def oa_fetch_all(session, subject):
|
||||
data = oa_todo_page(session, subject, page_no=1)
|
||||
total = int((data.get("page") or {}).get("totalSize") or 0)
|
||||
docs, skipped = oa_parse_rows(data)
|
||||
pages = (total + PAGE_SIZE - 1) // PAGE_SIZE if total else 1
|
||||
for p in range(2, min(pages, 20) + 1):
|
||||
data = oa_todo_page(session, subject, page_no=p)
|
||||
more, skip = oa_parse_rows(data)
|
||||
docs.extend(more)
|
||||
skipped += skip
|
||||
# 按详情链接去重(与现有 get_documents 口径一致)
|
||||
seen, unique = set(), []
|
||||
for d in docs:
|
||||
key = d.get("detail_url") or d.get("title")
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
unique.append(d)
|
||||
return unique, total, skipped
|
||||
|
||||
|
||||
# ==================== HR 侧:WeProcess 流程待办(候选新链路) ====================
|
||||
def hr_we_process_page(session, title, page_no=1, page_size=PAGE_SIZE):
|
||||
params = {
|
||||
"version": "", "PACKAGE_ID": "cq37du", "process_type": "", "defProcessType": "",
|
||||
"struId": "", "rootId": "cq37du", "taskIds": "", "title": title,
|
||||
"state": "", "startTime": "", "endTime": "",
|
||||
"sortType": "desc", "sortName": "CREATE_TIME",
|
||||
"commonQuery": "[]", "start": "0", "pageNo": str(page_no), "pageSize": str(page_size),
|
||||
}
|
||||
resp = session.post(WE_PROCESS_URL, data=params, timeout=20)
|
||||
text = resp.text or ""
|
||||
if not _is_json(text):
|
||||
raise RuntimeError(f"WeProcess 返回非 JSON(HR 登录态可能失效,前 80 字符):{text[:80]}")
|
||||
d = resp.json()
|
||||
if str(d.get("state")) != "1":
|
||||
raise RuntimeError(f"WeProcess 返回失败 state={d.get('state')} meg={d.get('meg')}")
|
||||
return d
|
||||
|
||||
|
||||
def hr_fetch_all(session, title):
|
||||
rows, d, page_no = [], None, 1
|
||||
while page_no <= 20:
|
||||
d = hr_we_process_page(session, title, page_no=page_no)
|
||||
datas = d.get("jsonList") or d.get("datas") or []
|
||||
rows.extend(datas)
|
||||
if len(datas) < PAGE_SIZE:
|
||||
break
|
||||
page_no += 1
|
||||
total = d.get("total") if isinstance(d, dict) else None
|
||||
return rows, total
|
||||
|
||||
|
||||
# ==================== 免 SSO 链路验证:taskId -> formId -> 表单数据 ====================
|
||||
def wf_activity_form_id(session, task_id):
|
||||
resp = session.post(f"{WF_ACTIVITY_URL}?method=getWfActivityByTaskId",
|
||||
data={"taskId": task_id}, timeout=20)
|
||||
d = resp.json()
|
||||
if str(d.get("state")) != "1" and not d.get("formId"):
|
||||
raise RuntimeError(f"WfActivity 返回失败:{json.dumps(d, ensure_ascii=False)[:120]}")
|
||||
for src in [d] + [d.get(k) for k in ("data", "result") if isinstance(d.get(k), dict)]:
|
||||
for key in ("formId", "FormId", "form_id"):
|
||||
if src.get(key):
|
||||
return str(src[key])
|
||||
raise RuntimeError(f"WfActivity 未能提取 formId:{json.dumps(d, ensure_ascii=False)[:120]}")
|
||||
|
||||
|
||||
def business_data(session, business_key, form_id):
|
||||
resp = session.post(f"{WORKFORM_ENGINE_URL}?method=getBusinessDate",
|
||||
data={"businessKey": business_key, "formId": form_id}, timeout=20)
|
||||
d = resp.json()
|
||||
if str(d.get("state")) != "1" or not isinstance(d.get("result"), dict):
|
||||
raise RuntimeError(f"getBusinessDate 返回失败:{json.dumps(d, ensure_ascii=False)[:120]}")
|
||||
return d["result"]
|
||||
|
||||
|
||||
def _norm_title(s):
|
||||
return re.sub(r"\s+", "", str(s or ""))
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def main():
|
||||
print("=" * 72)
|
||||
print("探针:OA 待办 vs HR WeProcess 一致性 + 免 SSO 链路验证(只读)")
|
||||
print(f"hr_cookies.json 修改时间: {_mtime(HR_COOKIE_FILE)}")
|
||||
print(f"oa_cookies.json 修改时间: {_mtime(OA_COOKIE_FILE)}")
|
||||
|
||||
hr_cookies = load_cookies(HR_COOKIE_FILE)
|
||||
oa_cookies = load_cookies(OA_COOKIE_FILE)
|
||||
if not hr_cookies:
|
||||
print("[终止] 未找到 hr_cookies.json,请先运行「37duHR登录」")
|
||||
return 1
|
||||
hr = build_session(hr_cookies, domain_keyword="37du.co")
|
||||
oa = build_session(oa_cookies) if oa_cookies else None
|
||||
if oa is None:
|
||||
print("[提示] 未找到 oa_cookies.json,将只测 HR 侧,无法做 OA 一致性比对")
|
||||
|
||||
all_subjects_ok = True
|
||||
for idx, subject in enumerate(SUBJECTS, 1):
|
||||
print("=" * 72)
|
||||
print(f"[{idx}/{len(SUBJECTS)}] 主题关键字: {subject}")
|
||||
|
||||
# ---- OA 侧 ----
|
||||
oa_docs, oa_total, oa_skipped = [], None, 0
|
||||
if oa is not None:
|
||||
try:
|
||||
oa_docs, oa_total, oa_skipped = oa_fetch_all(oa, subject)
|
||||
print(f"OA 待办: 接口 total={oa_total},解析去重 {len(oa_docs)} 条"
|
||||
f"(跳过协作类 {oa_skipped} 条)")
|
||||
except RuntimeError as e:
|
||||
print(f"OA 待办拉取失败: {e}")
|
||||
|
||||
# ---- HR 侧 ----
|
||||
try:
|
||||
hr_rows, hr_total = hr_fetch_all(hr, subject)
|
||||
except RuntimeError as e:
|
||||
print(f"[HR失败] {e}")
|
||||
all_subjects_ok = False
|
||||
continue
|
||||
print(f"HR WeProcess: jsonList={len(hr_rows)} 条, total={hr_total}")
|
||||
|
||||
if not hr_rows:
|
||||
print(" (HR 返回空,无法比对)")
|
||||
all_subjects_ok = False
|
||||
continue
|
||||
|
||||
# 首行字段发现 + 状态类字段
|
||||
keys = sorted(hr_rows[0].keys())
|
||||
print(f"HR 行字段({len(keys)}): {','.join(keys)}")
|
||||
for k in ("state", "processState", "taskState", "currentState", "flowState"):
|
||||
vals = sorted({str(r.get(k)) for r in hr_rows if r.get(k) is not None})
|
||||
if vals:
|
||||
print(f" 字段 {k} 取值: {vals}")
|
||||
|
||||
# ---- 一致性比对 ----
|
||||
if oa_docs is not None and oa_total is not None:
|
||||
oa_map = {_norm_title(_row(d, "title")): d for d in oa_docs}
|
||||
hr_map = {}
|
||||
for r in hr_rows:
|
||||
t = _norm_title(_row(r, "title", "processTitle", "docSubject", "businessName"))
|
||||
if t:
|
||||
hr_map.setdefault(t, r)
|
||||
matched = set(oa_map) & set(hr_map)
|
||||
oa_only, hr_only = set(oa_map) - set(hr_map), set(hr_map) - set(oa_map)
|
||||
print(f"标题比对: OA {len(oa_map)} 条 vs HR {len(hr_map)} 条,"
|
||||
f"完全匹配 {len(matched)} 条;OA 独有 {len(oa_only)} 条,HR 独有 {len(hr_only)} 条")
|
||||
for t in list(oa_only)[:5]:
|
||||
print(f" [OA独有] {oa_map[t]['title']}(发起人 {oa_map[t]['creator']})")
|
||||
for t in list(hr_only)[:5]:
|
||||
r = hr_map[t]
|
||||
print(f" [HR独有] {_row(r, 'title')}(发起人 {_row(r, 'createUserName', 'createUserNameCn')})")
|
||||
if oa_only or hr_only:
|
||||
all_subjects_ok = False
|
||||
|
||||
# ---- 免 SSO 链路验证(最多 3 条)----
|
||||
chain_ok = chain_fail = 0
|
||||
for r in hr_rows[:3]:
|
||||
task_id = str(_row(r, "taskId", "task_id"))
|
||||
bk = str(_row(r, "businessKey", "business_key"))
|
||||
try:
|
||||
if not task_id:
|
||||
raise RuntimeError("行内无 taskId")
|
||||
form_id = wf_activity_form_id(hr, task_id)
|
||||
row_form = str(_row(r, "formId", "form_id"))
|
||||
result = business_data(hr, bk, form_id)
|
||||
chain_ok += 1
|
||||
agree = ("一致" if (not row_form or row_form == form_id)
|
||||
else f"与行内formId({row_form})不一致")
|
||||
print(f" [链路OK] {_row(r, 'title')} | taskId={task_id} -> formId={form_id}"
|
||||
f"({agree}) | 表单字段数={len(result)}")
|
||||
except Exception as e:
|
||||
chain_fail += 1
|
||||
print(f" [链路FAIL] {_row(r, 'title')} | taskId={task_id} businessKey={bk} | {e}")
|
||||
print(f"免SSO链路验证: 成功 {chain_ok} 条,失败 {chain_fail} 条")
|
||||
if chain_fail:
|
||||
all_subjects_ok = False
|
||||
|
||||
print("=" * 72)
|
||||
verdict = "三个主题均一致,免 SSO 链路可用" if all_subjects_ok else "存在差异/失败,见上方明细"
|
||||
print(f"探针结束。结论: {verdict}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user