- XQ0036门店员工起调薪处理:版本升至0.1.6,优化纳税单位解析逻辑,优先使用接口返回值,新增金色印象、金色湖畔、后浪会馆的纳税单位兜底规则 - XQ0047微盟数据导出:版本升至1.0.5,新增等待生成上限配置项,优化轮询超时处理逻辑 - XQ0006 EHR系统周考勤异常处理:版本升至1.4.1,重构推送逻辑,支持组织架构范围选择,新增dws推送通道,优化自动确认范围为整月轻微异常,新增组织架构同步功能
278 lines
9.9 KiB
Python
278 lines
9.9 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""XQ0006 数据层:HR 组织架构(组织维护台账)拉取、树化与本地固化。
|
||
|
||
数据源:组织维护台账实时查询接口(与 workflows/share/org_export.py 同款、已在生产使用),
|
||
返回全部「在用」组织,字段含组织名称 / 组织编号 / 组织类型 / 组织全路径(集团-A-B-C)。
|
||
树按组织全路径的 "-" 层级切分构建,节点 id 即全路径,正好与考勤异常行的
|
||
ORG_FULL_PATH 同口径,界面勾选的节点可直接按路径前缀匹配数据行。
|
||
|
||
固化位置:%LOCALAPPDATA%\\37duAutomation\\plugin_data\\xq0006\\org_tree.json;
|
||
界面「同步组织架构」按钮触发 sync(),只写这一个文件,不随插件升级丢失。
|
||
"""
|
||
import json
|
||
import os
|
||
import time
|
||
import urllib.parse
|
||
|
||
from .. import config
|
||
from .hr_api import HRSessionExpiredError
|
||
|
||
# ==================== 接口与固定入参 ====================
|
||
ORG_QUERY_URL = config.ORG_QUERY_URL
|
||
ORG_PAGE_SIZE = config.ORG_PAGE_SIZE
|
||
MAX_ATTEMPTS = 3
|
||
RETRY_WAIT = 1.5
|
||
|
||
# commonQuery 前端加密(等价浏览器行为,已实测接口可用)
|
||
_CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
|
||
_SALT = "yyryrtweasdasd"
|
||
|
||
|
||
def _custom_base64_encode(data):
|
||
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, 64
|
||
elif len(chunk) == 2:
|
||
enc4 = 64
|
||
result += [_CUSTOM_CHARS[enc1], _CUSTOM_CHARS[enc2],
|
||
_CUSTOM_CHARS[enc3], _CUSTOM_CHARS[enc4]]
|
||
return "".join(result)
|
||
|
||
|
||
def _encode_common_query(conditions):
|
||
"""查询条件列表 → commonQuery 串(URI 编码 + 自定义 Base64 + 盐 + 首尾重排)。"""
|
||
raw = json.dumps(conditions, ensure_ascii=False, separators=(",", ":"))
|
||
uri = urllib.parse.quote(raw, safe="-_.~!*'()")
|
||
en = _custom_base64_encode(uri.encode("utf-8")) + _SALT
|
||
return en[:2] + en[-3:] + en[2:-3]
|
||
|
||
|
||
_COMMON_QUERY = _encode_common_query([{
|
||
"queryField": "`pt_organzation.IN_USE`", "leftBracket": "(", "queryType": "in",
|
||
"queryValue": "1", "queryText": "1", "rightBracket": ")", "logic": "AND",
|
||
"inputType": "select",
|
||
}])
|
||
|
||
_BASE_PARAMS = {
|
||
"menuName": "组织维护",
|
||
"useSealTreeData": "0",
|
||
"treePermitType": "permit",
|
||
"cancelNodeClick": "1",
|
||
"clickFlag": "true",
|
||
"in_use": "1",
|
||
"commonQuery": _COMMON_QUERY,
|
||
"newCondition": "",
|
||
"urlConditions": ("_t%3A1788589944798%23clickFlag%3Atrue%23cancelNodeClick%3A1%23"
|
||
"treePermitType%3Apermit%23useSealTreeData%3A0%23menuName%3A"
|
||
"%E7%BB%84%E7%BB%87%E7%BB%B4%E6%8A%A4%23_t%3A1788589944798%23"),
|
||
"exportConfig": "",
|
||
"tableId": config.ORG_TABLE_ID,
|
||
"rosterId": config.ORG_ROSTER_ID,
|
||
"includeChildrenSetting": "",
|
||
"struTreeCode": config.HR_TREE_CODE,
|
||
"djStruTreeCode": "",
|
||
"djStruId": "",
|
||
"djOrgName": "",
|
||
"struId": config.GROUP_ROOT_STRU_ID,
|
||
"belongUnitStruId": config.GROUP_ROOT_STRU_ID,
|
||
"rootId": config.HR_TREE_CODE,
|
||
"isVirtual": "0",
|
||
"baseHrefPath": "http://hr.37du.co:80RedseaPlatform",
|
||
"qrCodeUrl": "jspresumepage-01.jsp",
|
||
"orgName": "集团",
|
||
"belongUnitOrgName": "集团",
|
||
"throughParam": "",
|
||
"sortType": "",
|
||
"sortName": "",
|
||
}
|
||
|
||
# 接口字段:组织名称 / 编号 / 类型 / 组织全路径(上级组织仅作兜底参考)
|
||
F_NAME = "pt_organzation.ORG_NAME"
|
||
F_CODE = "pt_organzation.ORG_CODE"
|
||
F_TYPE = "pt_organzation.ORG_TYPE_CODE"
|
||
F_PATH = "pt_structure.ORG_FULL_PATH"
|
||
F_PARENT = "pt_structure1.ORG_ALIAS"
|
||
|
||
|
||
def _date_params():
|
||
"""组织维护查询固定带的日期参数(接口校验用,取当前时刻)。"""
|
||
now = time.localtime()
|
||
return {
|
||
"currentDate": time.strftime("%Y-%m-%d", now),
|
||
"currentMonth": time.strftime("%Y%m", now),
|
||
"currentMonthBar": time.strftime("%Y-%m", now),
|
||
"lastMonth": time.strftime("%Y%m", now),
|
||
"lastMonFirstDay": time.strftime("%Y-%m", now) + "-01",
|
||
"lastMonLastDay": time.strftime("%Y-%m-%d", now),
|
||
"curYearFirstMon": time.strftime("%Y", now) + "01",
|
||
"curYearFirstMonBar": time.strftime("%Y", now) + "-01",
|
||
}
|
||
|
||
|
||
def _fetch_page_once(session, page_no, page_size):
|
||
params = dict(_BASE_PARAMS)
|
||
params.update(_date_params())
|
||
params.update({
|
||
"currentUserRootId": config.HR_TREE_CODE,
|
||
"currentUserId": config.ORG_DEFAULT_USER_ID,
|
||
"currentRoleIds": config.ORG_CURRENT_ROLE_IDS,
|
||
"currentStaffId": config.ORG_DEFAULT_STAFF_ID,
|
||
"pageNo": str(page_no),
|
||
"pageSize": str(page_size),
|
||
"start": str((page_no - 1) * page_size),
|
||
"_t": str(int(time.time() * 1000)),
|
||
})
|
||
resp = session.request("POST", ORG_QUERY_URL, params=params,
|
||
timeout=config.HTTP_TIMEOUT * 3)
|
||
resp.raise_for_status()
|
||
text = resp.text or ""
|
||
if not text.lstrip().startswith(("{", "[")):
|
||
raise HRSessionExpiredError("组织架构:HR 登录态失效(返回非 JSON),请重新登录 HR 后重试")
|
||
return resp.json()
|
||
|
||
|
||
def _fetch_page(session, page_no):
|
||
last_err = None
|
||
for attempt in range(1, MAX_ATTEMPTS + 1):
|
||
try:
|
||
return _fetch_page_once(session, page_no, ORG_PAGE_SIZE)
|
||
except HRSessionExpiredError:
|
||
raise
|
||
except Exception as e: # noqa: BLE001 - 网络/接口异常按项目规范重试 3 次
|
||
last_err = e
|
||
config.logger.warning("组织架构第 %d 页第 %d/%d 次失败:%s",
|
||
page_no, attempt, MAX_ATTEMPTS, e)
|
||
if attempt < MAX_ATTEMPTS:
|
||
time.sleep(RETRY_WAIT * attempt)
|
||
raise RuntimeError(f"组织架构第 {page_no} 页拉取失败:{last_err}")
|
||
|
||
|
||
def fetch_all_orgs(session, on_progress=None):
|
||
"""分页拉取全部在用组织记录(接口原始行)。"""
|
||
rows = []
|
||
page_no = 1
|
||
while True:
|
||
data = _fetch_page(session, page_no)
|
||
if str(data.get("state")) != "1":
|
||
raise RuntimeError(f"组织架构第 {page_no} 页接口返回失败:{data.get('meg')}")
|
||
page_list = data.get("datas") or []
|
||
if not page_list:
|
||
break
|
||
rows.extend(page_list)
|
||
total_page = int(data.get("pageCount", 0) or 0)
|
||
config.logger.info("组织架构已抓取 %d/%d 页,累计 %d 条",
|
||
page_no, total_page, len(rows))
|
||
if on_progress:
|
||
on_progress(page_no, total_page)
|
||
if total_page and page_no >= total_page:
|
||
break
|
||
page_no += 1
|
||
time.sleep(0.2)
|
||
return rows
|
||
|
||
|
||
def build_tree(records):
|
||
"""组织记录 → 树(节点 id/child 关系均由组织全路径的 '-' 层级推导)。
|
||
|
||
Returns:
|
||
(树节点列表, 跳过条数)
|
||
"""
|
||
nodes = {}
|
||
skipped = 0
|
||
for r in records:
|
||
path = str(r.get(F_PATH) or "").strip()
|
||
if not path:
|
||
skipped += 1
|
||
continue
|
||
name = str(r.get(F_NAME) or "").strip()
|
||
segs = [s for s in path.split("-") if s]
|
||
if not segs:
|
||
skipped += 1
|
||
continue
|
||
acc = []
|
||
for seg in segs:
|
||
acc.append(seg)
|
||
p = "-".join(acc)
|
||
node = nodes.get(p)
|
||
if node is None:
|
||
node = {"path": p, "name": seg, "code": "", "type": "", "children": []}
|
||
nodes[p] = node
|
||
leaf = nodes[path]
|
||
leaf["name"] = name or segs[-1]
|
||
leaf["code"] = str(r.get(F_CODE) or "")
|
||
leaf["type"] = str(r.get(F_TYPE) or "")
|
||
|
||
roots = []
|
||
for p, node in nodes.items():
|
||
parent_path = p.rsplit("-", 1)[0] if "-" in p else ""
|
||
parent = nodes.get(parent_path)
|
||
if parent is not None:
|
||
parent["children"].append(node)
|
||
else:
|
||
roots.append(node)
|
||
return roots, skipped
|
||
|
||
|
||
def _count_nodes(tree):
|
||
total = 0
|
||
stack = list(tree)
|
||
while stack:
|
||
node = stack.pop()
|
||
total += 1
|
||
stack.extend(node.get("children") or [])
|
||
return total
|
||
|
||
|
||
def save(tree, count):
|
||
"""把树固化到 plugin_data/xq0006/org_tree.json(先写临时文件再替换)。"""
|
||
payload = {
|
||
"schema": 1,
|
||
"fetched_at": time.strftime("%Y-%m-%d %H:%M:%S"),
|
||
"count": count,
|
||
"tree": tree,
|
||
}
|
||
os.makedirs(os.path.dirname(config.ORG_TREE_FILE), exist_ok=True)
|
||
tmp = config.ORG_TREE_FILE + ".tmp"
|
||
with open(tmp, "w", encoding="utf-8") as f:
|
||
json.dump(payload, f, ensure_ascii=False, separators=(",", ":"))
|
||
os.replace(tmp, config.ORG_TREE_FILE)
|
||
return payload
|
||
|
||
|
||
def load():
|
||
"""读取本地固化的组织架构;不存在/损坏返回 None。"""
|
||
try:
|
||
with open(config.ORG_TREE_FILE, encoding="utf-8") as f:
|
||
data = json.load(f)
|
||
except FileNotFoundError:
|
||
return None
|
||
except (OSError, ValueError) as e:
|
||
config.logger.warning("组织架构本地文件读取失败:%s", e)
|
||
return None
|
||
if not isinstance(data, dict) or not isinstance(data.get("tree"), list):
|
||
return None
|
||
return data
|
||
|
||
|
||
def sync(session, on_progress=None):
|
||
"""拉取最新组织架构 → 建树 → 固化 → 返回 payload(含 tree)。"""
|
||
records = fetch_all_orgs(session, on_progress=on_progress)
|
||
if not records:
|
||
raise RuntimeError("组织架构接口未返回任何组织数据(请确认账号有组织维护查询权限)")
|
||
tree, skipped = build_tree(records)
|
||
if skipped:
|
||
config.logger.warning("组织架构有 %d 条记录缺少组织全路径,已跳过", skipped)
|
||
count = _count_nodes(tree)
|
||
payload = save(tree, count)
|
||
config.logger.info("组织架构同步完成:%d 个节点,已固化到 %s", count, config.ORG_TREE_FILE)
|
||
return payload
|