- 职位序列改取 pt_staff_stru.first_type_id,按 rf_s_Core_Post_pt_post_type_Select_v3_1 字典转名称 - 星级改按 star_level_sp_cq37du 字典解析(ext_1=见习/ext_2=正式/ext_13=代理),实时结果不全时回退全量导出 - 调薪但无起薪记录:与平台同口径「该员工没起薪,无需调薪」,记跳过而非待人工 - 入职/再次入职当天又借调:借调待办调 insertHrWageBaseStaffChange.mc(changeIds[])设置忽略,试算只标记待忽略 - 花名册实时查询补专用角色集、按页拉全
305 lines
13 KiB
Python
305 lines
13 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""花名册查询:职位序列(决定是否处理与工资账套)与星级(标准表匹配用)。
|
||
|
||
按待办工号实时查询在职/返聘人员(queryRealTimeData.mc,登录一次只取这批人,逐个补查时限流),
|
||
取不到职位序列才回退全量导出在职花名册。
|
||
|
||
字段口径(与 xq0034 / xq0035 / xq0083 同源,实测):
|
||
- 工号 ``hr_staff_base.base_code``
|
||
- 星级 ``hr_staff_base_ext.ext_star_level`` —— 实时查询返回的是字典 code
|
||
(``ext_1``=见习、``ext_2``=正式、``ext_13``=代理 …),须查字典
|
||
``star_level_sp_cq37du``(PtCodeTypeValue.mc)转成中文名;导出花名册里已是中文。
|
||
- 职位序列 ``pt_staff_stru.first_type_id`` —— **实时查询返回的是序列 ID(UUID),
|
||
不是名称**;服务端只对导出模板做字典翻译,实时查询行是「表名.字段名」原始值,
|
||
所以必须再查职位序列字典(rf_s_Core_Post_pt_post_type_Select_v3_1)转成
|
||
「门店服务序列 / 门店技师序列 / 经营系管理序列」等名称。
|
||
- 导出花名册(模板「员工基础信息」)里两列都已被服务端翻译成中文列名。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import os
|
||
import time
|
||
from typing import List, Optional
|
||
|
||
import pandas as pd
|
||
|
||
from hr_sdk.config import REDSEA
|
||
|
||
from .. import config
|
||
|
||
COL_CODE = ("工号", "base_code")
|
||
COL_STAR = ("星级", "ext_star_level")
|
||
COL_SEQ = ("职位序列", "first_type_id")
|
||
DEFAULT_TTL = 1800
|
||
|
||
ROSTER_ID = "1116da64-b094-11ea-b588-14187743d052"
|
||
ROSTER_TABLE_ID = "assemble-hr_staff_base"
|
||
ROSTER_MENU_NAME = "员工花名册"
|
||
ROSTER_QUERY_URL = f"{REDSEA}/hrRoster/{ROSTER_ID}/queryRealTimeData.mc"
|
||
PAGE_SIZE = 500
|
||
MAX_PAGES = 20
|
||
THROTTLE_SECONDS = 0.5
|
||
|
||
#: 职位序列字典(code=序列ID,name=序列名称)
|
||
SEQUENCE_DICT_URL = (f"{REDSEA}/redmagicapi/"
|
||
"rf_s_Core_Post_pt_post_type_Select_v3_1/getExecuteResult.mc")
|
||
#: 星级字典(花名册列配置 enumValue=star_level_sp_cq37du,inputType=select2)
|
||
STAR_DICT_URL = f"{REDSEA}/PtCodeTypeValue.mc?method=getCodeValueByCodes"
|
||
STAR_CODE_TYPE = "star_level_sp_cq37du"
|
||
#: 员工花名册专用角色集:缺这几项服务端按无权限返回空数据(与 xq0034/xq0035 同源)
|
||
ROSTER_ROLE_IDS = ("62367974-3904-409c-849a-2c3b0edcaf44,"
|
||
"f30200a0-2154-4692-8e58-7d2758d9bb82,"
|
||
"POST_SYS_ADMIN,renshi")
|
||
|
||
#: 字典缓存(进程内各查一次)
|
||
_SEQUENCE_NAMES: dict = {}
|
||
_STAR_NAMES: dict = {}
|
||
|
||
|
||
def _cell(row: dict, key: str) -> str:
|
||
"""兼容实时查询返回的裸键与 hr_staff_base / hr_staff_base_ext 前缀键。"""
|
||
return config.text(row.get(key)
|
||
or row.get(f"hr_staff_base.{key}")
|
||
or row.get(f"hr_staff_base_ext.{key}"))
|
||
|
||
|
||
def _field(row: dict, suffix: str) -> str:
|
||
"""行内以 suffix 结尾的键名(兼容 ``pt_staff_stru.first_type_id`` / 裸键 / 大小写)。
|
||
|
||
实时查询行的键是「表名.字段名」,不同台账带的前缀不同,按后缀匹配最稳。
|
||
"""
|
||
target = suffix.lower()
|
||
for key in row:
|
||
low = str(key).lower()
|
||
if low == target or low.endswith("." + target):
|
||
return str(key)
|
||
return ""
|
||
|
||
|
||
def _col(columns, aliases) -> str:
|
||
for alias in aliases:
|
||
if alias in columns:
|
||
return alias
|
||
return ""
|
||
|
||
|
||
def load(path: str, log=None) -> dict:
|
||
"""读取花名册导出文件 → {工号: {"star": 星级, "sequence": 职位序列}}。"""
|
||
path = config.text(path)
|
||
if not path or not os.path.exists(path):
|
||
return {}
|
||
frame = pd.read_excel(path, dtype=str)
|
||
if not _col(frame.columns, COL_CODE):
|
||
frame = pd.read_excel(path, dtype=str, header=1)
|
||
col_code = _col(frame.columns, COL_CODE)
|
||
col_star = _col(frame.columns, COL_STAR)
|
||
col_seq = _col(frame.columns, COL_SEQ)
|
||
if not col_code:
|
||
if log:
|
||
log(f"[WARN] 花名册缺少「工号」列:{list(frame.columns)}", "WARNING")
|
||
return {}
|
||
result = {}
|
||
for _, row in frame.iterrows():
|
||
code = config.text(row.get(col_code))
|
||
if not code:
|
||
continue
|
||
result[code] = {
|
||
"star": config.text(row.get(col_star)) if col_star else "",
|
||
"sequence": config.text(row.get(col_seq)) if col_seq else "",
|
||
}
|
||
if log:
|
||
log(f"[INFO] 花名册载入 {len(result)} 人(职位序列/星级):{os.path.basename(path)}")
|
||
return result
|
||
|
||
|
||
# ==================== 职位序列字典(ID → 名称) ====================
|
||
|
||
def sequence_names(client, log=None) -> dict:
|
||
"""职位序列字典 {序列ID: 序列名称},进程内缓存;失败返回空 dict(不阻断)。"""
|
||
if _SEQUENCE_NAMES:
|
||
return _SEQUENCE_NAMES
|
||
try:
|
||
data = client.request_json("POST", SEQUENCE_DICT_URL, data={},
|
||
label="职位序列字典")
|
||
items = data.get("jsonList") or data.get("datas") or []
|
||
names = {config.text(it.get("code")): config.text(it.get("name"))
|
||
for it in items if config.text(it.get("code"))}
|
||
_SEQUENCE_NAMES.update(names)
|
||
if log:
|
||
log(f"[INFO] 职位序列字典 {len(names)} 项")
|
||
except Exception as exc: # noqa: BLE001 - 字典失败不阻断
|
||
if log:
|
||
log(f"[WARN] 职位序列字典获取失败(职位序列将缺失):{exc}", "WARNING")
|
||
return _SEQUENCE_NAMES
|
||
|
||
|
||
def star_names(client, log=None) -> dict:
|
||
"""星级字典 {code: 名称}(ext_1=见习、ext_2=正式、ext_13=代理 …),进程内缓存。"""
|
||
if _STAR_NAMES:
|
||
return _STAR_NAMES
|
||
try:
|
||
data = client.request_json("POST", STAR_DICT_URL,
|
||
data={"codeType": STAR_CODE_TYPE}, label="星级字典")
|
||
groups = data.get(STAR_CODE_TYPE) or data.get("jsonList") or []
|
||
names = {config.text(it.get("code")): config.text(it.get("name"))
|
||
for it in groups if config.text(it.get("code"))}
|
||
_STAR_NAMES.update(names)
|
||
if log:
|
||
log(f"[INFO] 星级字典 {len(names)} 项")
|
||
except Exception as exc: # noqa: BLE001 - 字典失败不阻断
|
||
if log:
|
||
log(f"[WARN] 星级字典获取失败(星级将保留 code):{exc}", "WARNING")
|
||
return _STAR_NAMES
|
||
|
||
|
||
def _sequence(row: dict, names: Optional[dict] = None) -> str:
|
||
"""行内职位序列:优先已有的名称字段,否则用 first_type_id 查字典转名称。"""
|
||
names = names or {}
|
||
for suffix in ("first_type_name", "sequence_name", "type_name"):
|
||
key = _field(row, suffix)
|
||
if key:
|
||
name = config.text(row.get(key))
|
||
if name:
|
||
return name
|
||
for suffix in ("first_type_id", "sequence_id"):
|
||
key = _field(row, suffix)
|
||
seq_id = config.text(row.get(key)) if key else ""
|
||
if seq_id:
|
||
return names.get(seq_id, "")
|
||
return ""
|
||
|
||
|
||
def _star(row: dict, names: Optional[dict] = None) -> str:
|
||
"""行内星级:字典 code 转中文名;已是中文(导出)时原样返回。"""
|
||
names = names or {}
|
||
key = _field(row, "ext_star_level")
|
||
raw = config.text(row.get(key)) if key else ""
|
||
if not raw:
|
||
return ""
|
||
return names.get(raw, raw)
|
||
|
||
|
||
# ==================== 实时查询 ====================
|
||
|
||
def _index(rows: List[dict], names: Optional[dict] = None,
|
||
stars: Optional[dict] = None) -> dict:
|
||
result = {}
|
||
for row in rows:
|
||
code = _cell(row, "base_code")
|
||
if not code or code in result:
|
||
continue
|
||
result[code] = {
|
||
"star": _star(row, stars),
|
||
"sequence": _sequence(row, names),
|
||
}
|
||
return result
|
||
|
||
|
||
def _status_conditions() -> List[dict]:
|
||
"""在职+返聘(与花名册页面口径一致)。"""
|
||
from hr_sdk.query import condition
|
||
return [condition("`hr_staff_base.person_status`", "in", "1,4", query_text="1,4",
|
||
left_bracket="(", right_bracket=")", input_type="multipleSelect")]
|
||
|
||
|
||
def _query_page(client, conditions: List[dict], page_no: int = 1) -> List[dict]:
|
||
from hr_sdk.config import base_params
|
||
from hr_sdk.query import encode
|
||
|
||
params = base_params(ROSTER_MENU_NAME, ROSTER_TABLE_ID, ROSTER_ID)
|
||
params["commonQuery"] = encode(conditions)
|
||
params["baseHrefPath"] = "http://hr.37du.co:80RedseaPlatform"
|
||
# 花名册必须带专用角色集(缺角色服务端返回空数据);组织树 cq37du 由 base_params 提供
|
||
params["currentRoleIds"] = ROSTER_ROLE_IDS
|
||
params["pageNo"] = str(page_no)
|
||
params["pageSize"] = str(PAGE_SIZE)
|
||
data = client.request_json("POST", ROSTER_QUERY_URL, data=params, label=ROSTER_MENU_NAME)
|
||
client.check_state(data, ROSTER_MENU_NAME)
|
||
return data.get("datas") or []
|
||
|
||
|
||
def _query(client, conditions: List[dict], max_pages: int = MAX_PAGES) -> List[dict]:
|
||
"""按页拉实时查询结果:本页不足一页、或与上一页完全相同(服务端忽略 pageNo)即停。"""
|
||
rows: List[dict] = []
|
||
prev = None
|
||
for page_no in range(1, max_pages + 1):
|
||
page_rows = _query_page(client, conditions, page_no)
|
||
signature = tuple(_cell(row, "base_code") for row in page_rows)
|
||
rows.extend(page_rows)
|
||
if len(page_rows) < PAGE_SIZE or signature == prev:
|
||
break
|
||
prev = signature
|
||
return rows
|
||
|
||
|
||
def query_by_codes(client, codes: List[str], log=None) -> dict:
|
||
"""按工号批量实时查询花名册(只取这批人的职位序列/星级)。"""
|
||
from hr_sdk.query import condition
|
||
|
||
codes = [code for code in dict.fromkeys(codes) if code]
|
||
if not codes:
|
||
return {}
|
||
batch = _status_conditions() + [condition(
|
||
"`hr_staff_base.base_code`", "in", ",".join(codes), query_text=",".join(codes),
|
||
left_bracket="(", right_bracket=")", input_type="text")]
|
||
# 分页上限按本批人数估算,避免漏人
|
||
max_pages = min(MAX_PAGES, len(codes) // PAGE_SIZE + 2)
|
||
names = sequence_names(client, log)
|
||
stars = star_names(client, log)
|
||
result = _index(_query(client, batch, max_pages), names, stars)
|
||
if log:
|
||
log(f"[INFO] 花名册按工号实时查询 {len(codes)} 人,命中 {len(result)} 人")
|
||
missing = [code for code in codes if code not in result]
|
||
if missing:
|
||
# 批量 in 未覆盖时逐个 like 补查;逐个请求限流,避免连续打 HR 接口
|
||
for code in missing:
|
||
time.sleep(THROTTLE_SECONDS)
|
||
single = _status_conditions() + [condition(
|
||
"`hr_staff_base.base_code`", "like", code, query_text=code)]
|
||
result.update(_index(_query(client, single, max_pages=1), names, stars))
|
||
if log:
|
||
log(f"[INFO] 花名册逐个补查 {len(missing)} 人(限流 {THROTTLE_SECONDS}s/次),"
|
||
f"累计命中 {len(result)} 人")
|
||
return result
|
||
|
||
|
||
def _usable(index: dict) -> bool:
|
||
"""实时查询结果是否可用:有职位序列,且星级不是未翻译的字典 code。"""
|
||
if not index:
|
||
return False
|
||
if not any(item.get("sequence") for item in index.values()):
|
||
return False
|
||
return not any(config.text(item.get("star")).startswith("ext_")
|
||
for item in index.values())
|
||
|
||
|
||
def ensure(client, save_dir: str, log=None, base_codes: List[str] = None) -> dict:
|
||
"""返回花名册索引:按待办工号实时查询;字段取不全再回退全量导出。"""
|
||
realtime: dict = {}
|
||
if base_codes:
|
||
try:
|
||
realtime = query_by_codes(client, base_codes, log)
|
||
if _usable(realtime):
|
||
return realtime
|
||
if log:
|
||
log("[WARN] 花名册实时查询字段不全(无职位序列/星级仍是 code),"
|
||
"回退全量导出花名册", "WARNING")
|
||
except Exception as exc: # noqa: BLE001 - 查询失败不阻断
|
||
if log:
|
||
log(f"[WARN] 花名册实时查询失败,回退全量导出:{exc}", "WARNING")
|
||
try:
|
||
from hr_sdk import roster as roster_sdk
|
||
target = os.path.join(save_dir, "花名册_在职.xlsx")
|
||
path = roster_sdk.export(client, statuses=["在职"], output=target, ttl=DEFAULT_TTL)
|
||
exported = load(path, log)
|
||
if exported:
|
||
return exported
|
||
if log:
|
||
log("[WARN] 导出花名册为空,沿用实时查询结果(职位序列可能缺失)", "WARNING")
|
||
return realtime
|
||
except Exception as exc: # noqa: BLE001 - 查询失败不阻断,后续按待核对
|
||
if log:
|
||
log(f"[WARN] 自动导出花名册失败,职位序列/星级将缺失:{exc}", "WARNING")
|
||
return realtime
|