docs: 更新 AGENTS/README 平台架构说明与月度总结,运行日志视图支持已取消状态

This commit is contained in:
2026-10-31 17:55:25 +08:00
parent e1b4097573
commit b976b80d9d
201 changed files with 11049 additions and 7398 deletions
@@ -18,16 +18,18 @@
关键事实(决定了不需要抓包、也没有一次性 token 门槛):
- importId 是导入模板的固定配置 id,写死在弹窗页 hidden input 中;
- businessId 由前端 guid() 生成、每次导入唯一,接口版自行 uuid4();
- titleList 是字段映射数组 JSON 的 base64,无签名;
- businessId 由前端 guid() 生成(36 位带连字符)、每次导入唯一,接口版用 uuid4();
- titleList 是字段映射数组 JSON 经「前端 Base64.tranCode.encode」编码的结果:自定义字符表
Base64 + 固定盐 + 首尾重排(非标准 base64;编码错会让服务端 uploadDataSax 抛空指针、
任务根本不入队,后续只能查到全 0 的结果);
- 写库只发生在 uploadData,checkFileType 纯校验(读文件比对表头)。
"""
import base64
import json
import os
import time
import uuid
from urllib.parse import quote
from datetime import datetime, timedelta
from urllib.parse import quote, unquote
import requests
@@ -42,6 +44,19 @@ CHECK_FILE_TYPE_URL = BASE_URL + IMP_DO + "/checkFileType.mc"
UPLOAD_DATA_URL = BASE_URL + IMP_DO + "/uploadData.mc"
GET_IMPORT_RESULT_URL = BASE_URL + IMP_DO + "/getImportResult.mc"
GET_TMP_DATA_PAGE_URL = BASE_URL + IMP_DO + "/getTmpDataPage.mc"
# 失败数据页(注意:这两个不在 /do 下,是导入模块的列表/明细接口)
IMP_BASE = CONTEXT_PATH + "/hr/module/base/import"
GET_IMPORT_FAILURE_LIST_URL = BASE_URL + IMP_BASE + "/getImportFailurePageAjax.mc"
GET_FAIL_PAGE_URL = BASE_URL + IMP_BASE + "/getFailPage.mc"
# 「待增减人员」列表(核对本次入库用:导入成功的人会带当天 ext_operate_time 留在列表里)
PENDING_ROSTER_ID = "7984ae1a-16ec-11ed-bea9-822ff8ed5b28"
PENDING_LIST_URL = (BASE_URL + CONTEXT_PATH + "/hrRoster/"
+ PENDING_ROSTER_ID + "/queryRealTimeData.mc")
GET_CUR_USER_INFO_URL = BASE_URL + CONTEXT_PATH + "/PtUsers.mc?method=getCurUserInfo"
PENDING_ORG_STRU_ID = "596bae33-50e9-11ec-b526-822ff8ed5b28" # 集团节点(页面固定值)
PENDING_ROLE_IDS = "POST_SYS_ADMIN,renshi" # 与花名册查询口径一致
PENDING_PAGE_SIZE = 100
# 两个导入模板的固定配置 id(取自「待增减人员」页按钮配置,勿改)
IMPORT_MENUS = {
@@ -63,6 +78,7 @@ XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
RETRY_TIMES = 3 # 只读接口重试次数(项目级规范)
RETRY_INTERVAL = 1.0
PAGE_SIZE = 15 # getTmpDataPage 固定 15 条/页
FAIL_LIST_PAGE_SIZE = 50 # 导入失败批次列表每页条数(同一天可能有多个批次)
POLL_TIMEOUT_SECONDS = 300 # 导入结果轮询上限(与前端"排队等候"提示口径一致)
POLL_INTERVAL_SECONDS = 2.0
@@ -111,16 +127,39 @@ def build_session():
# ==================== HTTP 基础 ====================
# HR 会话失效有两种表现:① 页面被重定向到登录页(HTML);② 接口返回 HTTP 200 +
# JSON {"state":"Nosession","meg":"会话过期,请重新登录!"}。后者不是 HTTP 错误,
# 不识别就会被当成"导入处理中/无结果"一直轮询到 POLL_TIMEOUT,最终误报"待人工确认"。
SESSION_EXPIRED_STATES = ("nosession", "no_session", "sessiontimeout", "session_timeout")
SESSION_EXPIRED_KEYWORDS = ("会话过期", "会话已失效", "重新登录", "登录已超时", "登录超时")
def _raise_if_session_expired(data, desc):
"""识别「会话失效」类响应并抛 LoginRequiredError(HTTP 200 也会出现,必须按业务字段判定)。"""
if not isinstance(data, dict):
return
state = str(data.get("state") or "").strip()
meg = str(data.get("meg") or "").strip()
expired = state.lower() in SESSION_EXPIRED_STATES \
or any(k in meg for k in SESSION_EXPIRED_KEYWORDS)
if expired:
raise LoginRequiredError(
f"{desc} 提示会话失效(state={state or '-'},meg={meg or '-'}),"
"HR 登录态已失效,请在插件界面重新登录 HR 后重试。")
def _parse_json(resp, desc):
"""解析接口响应;返回登录页等非 JSON 内容时判定登录态失效。"""
"""解析接口响应;登录页 HTML 或会话失效 JSON 均判定为登录态失效。"""
text = resp.text or ""
try:
return resp.json()
data = resp.json()
except Exception:
if "j_username" in text or "login" in text.lower()[:2000]:
raise LoginRequiredError(
f"{desc} 返回登录页,HR 登录态已失效,请在插件界面重新登录 HR。")
raise RuntimeError(f"{desc} 响应非 JSON(HTTP {resp.status_code}):{text[:200]}")
_raise_if_session_expired(data, desc)
return data
def _multipart_post(session, url, data, file_path=None, timeout=120):
@@ -185,9 +224,75 @@ def _post_json(session, url, data, desc, file_path=None, timeout=120):
raise RuntimeError(f"{desc} 请求失败(已重试 {RETRY_TIMES} 次):{last}")
# titleList 提交前要用前端 Base64.tranCode.encode 编码:自定义字符表 Base64 + 固定盐 +
# 首尾重排(与 commonQuery 同源,仅少一步 URI 编码)。用标准 base64 会导致服务端解不出
# 字段映射(titleList 为 null),uploadDataSax 直接抛 NullPointerException、任务不入队。
_CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
_TITLE_SALT = "yyryrtweasdasd"
def _custom_base64_encode(data):
"""使用自定义字符表进行 Base64 编码(data 为 UTF-8 字节序列,'7' 对应填充位)。"""
result = []
for i in range(0, len(data), 3):
chunk = data[i:i + 3]
b1 = chunk[0] if len(chunk) > 0 else 0
b2 = chunk[1] if len(chunk) > 1 else 0
b3 = chunk[2] if len(chunk) > 2 else 0
enc1 = (b1 >> 2) & 0x3F
enc2 = ((b1 << 4) | (b2 >> 4)) & 0x3F
enc3 = ((b2 << 2) | (b3 >> 6)) & 0x3F
enc4 = b3 & 0x3F
if len(chunk) == 1:
enc3 = enc4 = 64
elif len(chunk) == 2:
enc4 = 64
result.append(_CUSTOM_CHARS[enc1])
result.append(_CUSTOM_CHARS[enc2])
result.append(_CUSTOM_CHARS[enc3])
result.append(_CUSTOM_CHARS[enc4])
return "".join(result)
def _custom_base64_decode(enc_str):
"""自定义字符表 Base64 解码('7' 为填充符),与 _custom_base64_encode 互逆。"""
index = {c: i for i, c in enumerate(_CUSTOM_CHARS)}
pad = enc_str.count("7")
enc_str = enc_str.replace("7", "")
data = bytearray()
for i in range(0, len(enc_str), 4):
chunk = enc_str[i:i + 4].ljust(4, "7")
n = ((index[chunk[0]] << 18) | (index[chunk[1]] << 12)
| (index[chunk[2]] << 6) | index[chunk[3]])
data.extend([(n >> 16) & 0xFF, (n >> 8) & 0xFF, n & 0xFF])
if pad:
data = data[:-pad]
return bytes(data)
def _b64(value):
"""与前端 Base64.tranCode.encode 等价(标准 base64,UTF-8)。"""
return base64.b64encode(str(value).encode("utf-8")).decode("ascii")
"""等价前端 Base64.tranCode.encode:自定义 Base64 + 盐值 + 首尾重排(titleList 专用)。"""
raw = str(value).encode("utf-8")
en_str = _custom_base64_encode(raw) + _TITLE_SALT
return en_str[:2] + en_str[-3:] + en_str[2:-3]
def _decode_hr_text(value):
"""解码 HR 接口返回的加密文案(uploadData 的 des / meg),失败返回原文。
入参/文件异常时 uploadData 返回 {"state":"0","meg":null,"des":"<加密串>"},
解密后才是真正的错误(如服务端异常堆栈),不解码只能看到一串乱码。
"""
text = str(value or "").strip()
if len(text) < 8:
return text
try:
en_str = text[:2] + text[5:] + text[2:5]
if en_str.endswith(_TITLE_SALT):
en_str = en_str[:-len(_TITLE_SALT)]
return unquote(_custom_base64_decode(en_str).decode("utf-8", errors="replace"))
except Exception:
return text
# ==================== 1. 弹窗配置 ====================
@@ -286,11 +391,25 @@ def submit_upload(session, conf, file_path, title_list, business_id):
data["businessId"] = business_id
try:
resp = _multipart_post(session, UPLOAD_DATA_URL, data, file_path=file_path, timeout=180)
logger.info("导入请求已提交(businessId=%s,HTTP %s)", business_id, resp.status_code)
return True
except Exception as e:
logger.warning("导入请求提交异常(结果未知,转轮询判定):%s", e)
return False
logger.info("导入请求已提交(businessId=%s,HTTP %s)", business_id, resp.status_code)
# 会话失效时上传同样返回 HTTP 200 + state=Nosession(任务并未受理):
# 这里立即判定登录态,避免"其实没受理"却继续轮询到超时、误报待人工确认
try:
payload = resp.json()
except Exception:
payload = None
_raise_if_session_expired(payload, f"{conf.get('title') or ''}导入提交")
if isinstance(payload, dict) and str(payload.get("state")) != "1":
# 服务端受理失败(多为入参/文件让它抛异常):des/meg 是加密文案,解码后写日志,
# 否则后续只会轮询到全 0 结果、报"待人工确认",真正原因看不到
detail = _decode_hr_text(payload.get("des")) or _decode_hr_text(payload.get("meg"))
logger.error("导入提交未被受理(state=%s):%s", payload.get("state"),
detail.replace("\n", " ")[:500] if detail else "-")
return False
return True
def get_import_result(session, import_id, business_id):
@@ -343,6 +462,8 @@ def fetch_exceptions(session, import_id, business_id):
try:
result = _post_json(session, GET_TMP_DATA_PAGE_URL, data,
f"导入明细第 {page_no} 页", timeout=30)
except LoginRequiredError:
raise # 登录态失效必须上报,不能当成"无异常行"吞掉
except Exception as e:
logger.warning("导入明细第 %s 页拉取失败:%s", page_no, e)
break
@@ -372,6 +493,247 @@ def fetch_exceptions(session, import_id, business_id):
return exceptions
def query_fail_batches(session, import_id, date_begin=None, date_end=None):
"""查某模板在指定时间段内的导入失败批次(「导入失败记录」列表接口)。
业务语义:导入提交后系统自动把校验通过的数据入库、把失败的返回明细;
只有存在失败数据时才会在此列表里生成批次(全成功的批次不会出现)。
Returns:
list[dict]:{business_id, operator_time, total}(total 为该批次失败条数);无记录返回 []。
"""
today = date_begin or time.strftime("%Y-%m-%d")
data = {
"root_id": "",
"excelImpVersion": "2",
"functionCode": import_id,
"date_begin": today,
"date_end": date_end or (today + " 23:59:59"),
"start": "0",
"sortType": "",
"sortName": "",
"pageNo": "1",
"pageSize": str(FAIL_LIST_PAGE_SIZE),
}
result = _post_json(session, GET_IMPORT_FAILURE_LIST_URL, data,
"导入失败批次列表", timeout=30)
if str(result.get("state")) != "1":
logger.info("导入失败批次列表无结果(state=%s)", result.get("state"))
return []
batches = []
for item in result.get("datas") or []:
item = item or {}
bid = str(item.get("businessid") or "").strip()
if not bid:
continue
try:
total = int(item.get("total") or 0)
except (TypeError, ValueError):
total = 0
batches.append({"business_id": bid,
"operator_time": str(item.get("operator_time") or ""),
"total": total})
return batches
def fetch_fail_page(session, import_id, business_id):
"""分页拉取某批次的失败明细(官方「失败数据」页接口 getFailPage.mc)。
字段口径与 getTmpDataPage 一致(imp_fixed_msg / 工号 / 姓名 / 方案),
「导入成功」行不计入异常。
"""
exceptions = []
page_no = 1
page_count = 1
while page_no <= page_count:
data = {
"excelImpVersion": "2",
"functionCode": import_id,
"businessId": business_id,
"start": str((page_no - 1) * PAGE_SIZE),
"pageNo": str(page_no),
"pageSize": str(PAGE_SIZE),
"commonQuery": "[]",
"sortType": "",
"sortName": "",
}
try:
result = _post_json(session, GET_FAIL_PAGE_URL, data,
f"失败数据第 {page_no} 页", timeout=30)
except LoginRequiredError:
raise
except Exception as e:
logger.warning("失败数据第 %s 页拉取失败:%s", page_no, e)
break
if str(result.get("state")) != "1":
break
try:
page_count = max(1, int(result.get("pageCount") or 1))
except (TypeError, ValueError):
page_count = 1
for item in result.get("datas") or []:
item = item or {}
msg = str(item.get("imp_fixed_msg", "") or "").strip()
if not msg or "导入成功" in msg:
continue
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 item.get("sicut_o_rel_ext_insurance_name") or ""),
"message": msg,
})
page_no += 1
return exceptions
# ==================== 8. 入库核对(待增减人员列表 · 操作时间) ====================
def _date_params():
"""列表查询需要的动态日期参数(当月/上月/当年首月),与花名册查询口径一致。"""
now = datetime.now()
last = now.replace(day=1) - timedelta(days=1)
return {
"currentDate": now.strftime("%Y-%m-%d"),
"currentMonth": now.strftime("%Y%m"),
"currentMonthBar": now.strftime("%Y-%m"),
"lastMonth": last.strftime("%Y%m"),
"lastMonFirstDay": last.strftime("%Y-%m-01"),
"lastMonLastDay": last.strftime("%Y-%m-%d"),
"curYearFirstMon": f"{now.year}01",
"curYearFirstMonBar": f"{now.year}-01",
}
def _encode_common_query(conditions):
"""查询条件列表 -> commonQuery(JSON -> URI 编码 -> 自定义 Base64 + 盐 -> 首尾重排)。"""
json_str = json.dumps(conditions, ensure_ascii=False, separators=(",", ":"))
en_str = _custom_base64_encode(quote(json_str, safe="-_.~!*'()").encode("utf-8")) + _TITLE_SALT
return en_str[:2] + en_str[-3:] + en_str[2:-3]
def _current_user_id(session):
"""取当前登录用户 userId/staffId(列表查询参数用),失败返回空 dict。"""
try:
data = _post_json(session, GET_CUR_USER_INFO_URL, {}, "当前用户信息", timeout=30)
except LoginRequiredError:
raise
except Exception as e:
logger.warning("取当前用户信息失败(沿用内置参数):%s", e)
return {}
return data if isinstance(data, dict) else {}
def query_operated_staff(session, started_at, end_at=None, max_pages=80):
"""查「待增减人员」列表里商业保险操作时间落在 [started_at, end_at] 的人员。
业务含义:导入提交后系统自动把成功数据入库,这些人会带着本次的
si_add_cut_person_sp_cq37du.ext_operate_time 留在列表中;失败的人不会带上本次操作时间。
据此可与导入文件工号比对,确认"本次到底入库了哪些人"。
Args:
started_at: "YYYY-MM-DD HH:MM:SS"(导入提交前的时间点)
end_at: 结束时间,默认现在
Returns:
list[dict]:{staff_code, staff_name, scheme, operate_time, add_date, cut_date}
"""
end_at = end_at or time.strftime("%Y-%m-%d %H:%M:%S")
field = "`si_add_cut_person_sp_cq37du.ext_operate_time`"
conditions = [
{"queryField": field, "leftBracket": "(", "queryType": ">=", "queryValue": started_at,
"queryText": started_at, "rightBracket": "", "logic": "AND", "inputType": "date"},
{"queryField": field, "leftBracket": "", "queryType": "<=", "queryValue": end_at,
"queryText": end_at, "rightBracket": ")", "logic": "AND", "inputType": "date"},
]
info = _current_user_id(session)
root = info.get("rootId") or "cq37du"
params = {
"menuName": "待增减人员",
"_t": str(int(time.time() * 1000)),
"in_use": "1",
"commonQuery": _encode_common_query(conditions),
"newCondition": "",
"urlConditions": "",
"exportConfig": "",
"tableId": "assemble-hr_staff_base",
"rosterId": PENDING_ROSTER_ID,
"includeChildrenSetting": "",
"struTreeCode": root,
"djStruTreeCode": "", "djStruId": "", "djOrgName": "",
"struId": PENDING_ORG_STRU_ID,
"belongUnitStruId": PENDING_ORG_STRU_ID,
"rootId": root,
"isVirtual": "0",
"currentUserRootId": root,
"currentUserId": info.get("userId") or "",
"currentRoleIds": PENDING_ROLE_IDS,
"currentStaffId": info.get("staffId") or "",
"baseHrefPath": "http:hr.37du.co:80RedseaPlatform",
"qrCodeUrl": "jspresumepage-01.jsp",
"orgName": "集团", "belongUnitOrgName": "集团",
"throughParam": "",
"start": "0", "sortType": "", "sortName": "",
"pageNo": "1", "pageSize": str(PENDING_PAGE_SIZE),
}
params.update(_date_params())
rows = []
page_no = 1
while page_no <= max_pages:
params["pageNo"] = str(page_no)
params["start"] = str((page_no - 1) * PENDING_PAGE_SIZE)
data = _post_json(session, PENDING_LIST_URL, params,
f"待增减人员操作记录第 {page_no} 页", timeout=60)
if str(data.get("state")) != "1":
logger.info("待增减人员列表无结果(state=%s)", data.get("state"))
break
datas = data.get("datas") or []
for item in datas:
item = item or {}
code = str(item.get("a_sp_cq37du.base_code") or "").strip()
if not code:
continue
rows.append({
"staff_code": code,
"staff_name": str(item.get("hr_staff_base.staff_name") or ""),
"scheme": str(item.get("si_add_cut_person_sp_cq37du.ext_insurance_name") or ""),
"operate_time": str(item.get("si_add_cut_person_sp_cq37du.ext_operate_time") or ""),
"add_date": str(item.get("si_add_cut_person_sp_cq37du.ext_add_per_date") or ""),
"cut_date": str(item.get("si_add_cut_person_sp_cq37du.ext_cut_per_date") or ""),
})
try:
page_count = int(data.get("pageCount") or 1)
except (TypeError, ValueError):
page_count = 1
if page_no >= page_count or not datas:
break
page_no += 1
return rows
def _read_import_codes(file_path):
"""读导入文件里的工号集合(第 4 行起 A 列序号非空视为有效数据行,取 B 列)。"""
from openpyxl import load_workbook
codes = set()
try:
wb = load_workbook(file_path, read_only=True, data_only=True)
except Exception as e:
logger.warning("读取导入文件失败(跳过入库核对):%s", e)
return codes
try:
ws = wb[wb.sheetnames[0]]
for row in ws.iter_rows(min_row=4, max_col=2, values_only=True):
if not row:
continue
seq, code = (list(row) + [None, None])[:2]
if seq in (None, "") or code in (None, ""):
continue
codes.add(str(code).strip())
finally:
wb.close()
return codes
def import_one_file(session, menu, file_path):
"""对单个导入文件执行完整接口导入(校验 -> 导入 -> 结果 -> 明细)。
@@ -416,8 +778,11 @@ def import_one_file(session, menu, file_path):
logger.info("%s表头匹配 %d/%d 列", label, matched, len(title_list))
# 4) 提交导入(唯一写操作,businessId 每次唯一)
business_id = uuid.uuid4().hex
# 必须与前端 guid() 同格式(36 位带连字符):HR 的失败记录/ws 消息 key 都按该字符串关联,
# 用 uuid4().hex(32 位无连字符)会导致服务端任务与查询对不上号
business_id = str(uuid.uuid4())
out["business_id"] = business_id
started_at = time.strftime("%Y-%m-%d %H:%M:%S") # 入库核对的时间起点(提交前)
submit_upload(session, conf, file_path, title_list, business_id)
# 5) 轮询结果
@@ -440,8 +805,71 @@ def import_one_file(session, menu, file_path):
out["other"] = _int("other")
out["meg"] = str(result.get("meg") or "")
# 6) 失败明细
# 6) 失败明细:官方「失败数据」页接口优先,弹窗明细接口兜底
if not out["is_success"]:
out["exceptions"] = fetch_exceptions(session, conf["id"], business_id)
out["exceptions"] = fetch_fail_page(session, conf["id"], business_id)
if not out["exceptions"]:
out["exceptions"] = fetch_exceptions(session, conf["id"], business_id)
# 7) 当天失败批次核对:列表里能看到本批次的失败条数(全成功的批次不会出现在这里),
# 既验证"这批确实被受理并处理过",也能和明细条数互校
try:
batches = query_fail_batches(session, conf["id"])
hit = next((b for b in batches if b["business_id"] == business_id), None)
out["batch_found"] = bool(hit)
out["batch_total"] = hit["total"] if hit else 0
if hit:
logger.info("%s当天失败批次已确认:%s(操作时间 %s,失败 %s 条)",
label, business_id, hit["operator_time"], hit["total"])
if out["exceptions"] and len(out["exceptions"]) != hit["total"]:
logger.warning("%s失败明细条数(%d)与批次统计(%d)不一致,请人工核对",
label, len(out["exceptions"]), hit["total"])
elif out["is_success"]:
logger.info("%s全部成功,当天失败批次列表无本批次记录(符合预期)", label)
else:
logger.warning("%s未在当天失败批次列表中找到本批次(%s),结果请人工核对",
label, business_id)
except LoginRequiredError:
raise
except Exception as e:
logger.warning("%s当天失败批次核对失败(不影响主流程):%s", label, e)
# 8) 入库核对:本次成功入库的人会带本次操作时间出现在「待增减人员」列表,
# 用导入文件工号做交集,确认"到底哪些人入库了"(失败的人不会带本次操作时间)
try:
codes = _read_import_codes(file_path)
if codes:
operated = query_operated_staff(session, started_at)
op_codes = {o["staff_code"] for o in operated}
if menu == "sub":
# 减员成功表现为"人员从待增减列表移除",因此仍在列表的人才是需要核对的;
# 例外:同一人也在本批增员文件里(换方案替换)→ 增员后会重新出现在列表,属正常
still = codes & op_codes
out["operated_count"] = len(codes) - len(still)
out["operated_missing"] = sorted(still)
logger.info("%s减员核对:文件 %d 人,已从待增减列表移除 %d 人(操作时间 ≥ %s)",
label, len(codes), len(codes) - len(still), started_at)
if still:
logger.info("%s仍在待增减列表 %d 人(同时在本批增员文件中的属正常替换,余者请核对):%s",
label, len(still), "、".join(sorted(still)[:20]))
else:
# 增员成功表现为"带本次操作时间出现在待增减列表"
hit = codes & op_codes
out["operated_count"] = len(hit)
out["operated_missing"] = sorted(codes - hit)
logger.info("%s入库核对:文件 %d 人,列表命中 %d 人(操作时间 ≥ %s)",
label, len(codes), len(hit), started_at)
if out["operated_missing"]:
logger.warning("%s未在列表命中 %d 人:%s", label,
len(out["operated_missing"]),
"、".join(out["operated_missing"][:20]))
if out["is_success"] and len(hit) < len(codes):
logger.warning("%s接口返回全部成功,但列表只命中 %d/%d 人,请人工核对",
label, len(hit), len(codes))
except LoginRequiredError:
raise
except Exception as e:
logger.warning("%s入库核对失败(不影响主流程):%s", label, e)
out["ok"] = True
return out