209 lines
8.5 KiB
Python
209 lines
8.5 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""员工花名册接口(导出 + 在职/离职筛选)。
|
||
|
||
用法::
|
||
|
||
from hr_sdk import HrClient, roster
|
||
|
||
client = HrClient(ctx.get_session("hr"))
|
||
path = roster.export(client, statuses=["在职"], output=r"D:\\out\\花名册.xlsx")
|
||
|
||
说明:
|
||
- 导出文件由 HR 模板决定列(服务端翻译字典字段),SDK 不做列名映射;
|
||
- 多状态合并时追加「类型」列(项目既定输出规范,各读取端按此读);
|
||
- ``ttl`` 秒内复用同路径文件(默认 900s,传 0 强制重导)。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import os
|
||
import time
|
||
from datetime import date, timedelta
|
||
from typing import Callable, List, Optional, Sequence
|
||
|
||
import pandas as pd
|
||
|
||
from . import export as export_mod
|
||
from .config import REDSEA, app_data_dir, base_params
|
||
from .errors import ConfigError, HrError
|
||
from .query import condition
|
||
|
||
ROSTER_ID = "1116da64-b094-11ea-b588-14187743d052"
|
||
TABLE_ID = "assemble-hr_staff_base"
|
||
MENU_NAME = "员工花名册"
|
||
PAGE_URL = f"{REDSEA}/hrRoster/{ROSTER_ID}/getCustomCommonList.mc"
|
||
EXPORT_URL = f"{REDSEA}/hrRoster/{ROSTER_ID}/exportCommonListData.mc"
|
||
|
||
DEFAULT_TEMPLATE = "员工基础信息"
|
||
DEFAULT_STATUSES = ["在职", "离职"]
|
||
DEFAULT_TTL = 900 # 缓存有效期(秒)
|
||
|
||
LOGGER = Callable[[str], None]
|
||
|
||
|
||
# ==================== 条件 ====================
|
||
|
||
def in_service_conditions() -> List[dict]:
|
||
"""在职条件:主职 in (1) + 在职状态 in (1)(与页面默认筛选一致)。"""
|
||
return [
|
||
condition("`pt_staff_stru.POST_STRU_ID`", "in", "1", query_text="1",
|
||
left_bracket="(", right_bracket=")", input_type="select"),
|
||
condition("`hr_staff_base.person_status`", "in", "1", query_text="1",
|
||
left_bracket="(", right_bracket=")", input_type="multipleSelect"),
|
||
]
|
||
|
||
|
||
def leave_conditions(start: str, end: str) -> List[dict]:
|
||
"""离职条件:主职 in (1) + 在职状态 in (2) + 离职时间闭区间。"""
|
||
return [
|
||
condition("`pt_staff_stru.POST_STRU_ID`", "in", "1", query_text="1",
|
||
left_bracket="(", right_bracket=")", input_type="select"),
|
||
condition("`hr_staff_base.person_status`", "in", "2", query_text="2",
|
||
left_bracket="(", right_bracket=")", input_type="multipleSelect"),
|
||
condition("`hr_staff_base.leaveOffice_date`", ">=", start,
|
||
left_bracket="(", input_type="date"),
|
||
condition("`hr_staff_base.leaveOffice_date`", "<=", end,
|
||
right_bracket=")", input_type="date"),
|
||
]
|
||
|
||
|
||
def leave_range(today: Optional[date] = None) -> tuple:
|
||
"""离职时间默认范围:上月 1 日 ~ 今天。"""
|
||
today = today or date.today()
|
||
last_month_end = today.replace(day=1) - timedelta(days=1)
|
||
start = last_month_end.replace(day=1)
|
||
return start.strftime("%Y-%m-%d"), today.strftime("%Y-%m-%d")
|
||
|
||
|
||
def default_output() -> str:
|
||
"""默认输出路径(插件通常显式传 output)。"""
|
||
return os.path.join(app_data_dir(), "output", "花名册.xlsx")
|
||
|
||
|
||
def _download_dir(output: str) -> str:
|
||
return os.path.join(os.path.dirname(os.path.abspath(output)), "download")
|
||
|
||
|
||
def _base(user: Optional[dict] = None) -> dict:
|
||
return base_params(MENU_NAME, TABLE_ID, ROSTER_ID, user=user)
|
||
|
||
|
||
# ==================== 导出 ====================
|
||
|
||
def export_one(client, status: str, *, template: str = DEFAULT_TEMPLATE,
|
||
filters: str = "", leave_start: str = "", leave_end: str = "",
|
||
output: str = "", user: Optional[dict] = None,
|
||
timeout: Optional[int] = None) -> str:
|
||
"""导出单个在职状态(不合并),返回原始 xlsx 路径。"""
|
||
if status == "离职":
|
||
start, end = leave_start, leave_end
|
||
if not start or not end:
|
||
start, end = leave_range()
|
||
conditions = leave_conditions(start, end)
|
||
client.log(f"[INFO] 离职时间范围:{start} ~ {end}")
|
||
else:
|
||
conditions = in_service_conditions()
|
||
|
||
resolved = filters or export_mod.resolve_template(client, template, ROSTER_ID) or ""
|
||
params = export_mod.build_params(_base(user), conditions=conditions,
|
||
template=template, filters=resolved)
|
||
target = output or os.path.join(_download_dir(default_output()),
|
||
f"花名册_{status}_{int(time.time())}.xlsx")
|
||
return export_mod.export_table(client, page_url=PAGE_URL, export_url=EXPORT_URL,
|
||
params=params, output_path=target, timeout=timeout)
|
||
|
||
|
||
def export(client, *, statuses: Optional[Sequence[str]] = None,
|
||
template: str = DEFAULT_TEMPLATE, filters: str = "",
|
||
leave_start: str = "", leave_end: str = "", output: str = "",
|
||
download_dir: str = "", ttl: int = DEFAULT_TTL,
|
||
user: Optional[dict] = None, timeout: Optional[int] = None) -> str:
|
||
"""导出花名册并按状态合并为一个 Excel(追加「类型」列),返回文件路径。
|
||
|
||
Args:
|
||
client: :class:`hr_sdk.client.HrClient`
|
||
statuses: 需要导出的状态,如 ``["在职"]`` / ``["在职","离职"]``(默认两者)
|
||
template: 自定义导出模板名(列由 HR 模板决定)
|
||
filters: 覆盖模板字段串(一般留空,走动态解析)
|
||
leave_start/leave_end: 离职时间范围(``YYYY-MM-DD``,缺省上月 1 日~今天)
|
||
output: 合并后输出路径
|
||
download_dir: 单状态临时文件目录(默认输出目录下 ``download/``)
|
||
ttl: 缓存有效期(秒);同路径文件在此时间内直接复用,传 0 强制重导
|
||
user: 覆盖抓包默认身份 ``{"userId","staffId","roleIds"}``
|
||
timeout: 单次导出等待上限(秒)
|
||
"""
|
||
statuses = [str(s) for s in (statuses or DEFAULT_STATUSES)]
|
||
output = os.path.abspath(output or default_output())
|
||
tmp_dir = download_dir or _download_dir(output)
|
||
|
||
if ttl and ttl > 0 and os.path.exists(output) and os.path.getsize(output) > 0 \
|
||
and time.time() - os.path.getmtime(output) <= ttl:
|
||
client.log(f"[INFO] 命中 {ttl}s 缓存,直接复用:{output}")
|
||
return output
|
||
|
||
resolved = filters or export_mod.resolve_template(client, template, ROSTER_ID) or ""
|
||
if not resolved:
|
||
raise ConfigError(
|
||
f"未能解析模板「{template}」的导出列,请检查模板名或显式传 filters")
|
||
|
||
client.log(f"[INFO] ===== 花名册导出开始(模板:{template},状态:{statuses})=====")
|
||
files: List[tuple] = []
|
||
try:
|
||
for status in statuses:
|
||
if status == "离职":
|
||
start, end = leave_start, leave_end
|
||
if not start or not end:
|
||
start, end = leave_range()
|
||
conditions = leave_conditions(start, end)
|
||
client.log(f"[INFO] 离职时间范围:{start} ~ {end}")
|
||
else:
|
||
conditions = in_service_conditions()
|
||
params = export_mod.build_params(_base(user), conditions=conditions,
|
||
template=template, filters=resolved)
|
||
temp_path = os.path.join(tmp_dir, f"花名册_{status}_{int(time.time())}.xlsx")
|
||
files.append((status, export_mod.export_table(
|
||
client, page_url=PAGE_URL, export_url=EXPORT_URL,
|
||
params=params, output_path=temp_path, timeout=timeout)))
|
||
return _merge(files, output, client.log)
|
||
finally:
|
||
for _, path in files:
|
||
try:
|
||
os.remove(path)
|
||
except OSError:
|
||
pass
|
||
|
||
|
||
def _merge(files: Sequence[tuple], output: str, log: LOGGER) -> str:
|
||
"""合并多状态文件并追加「类型」列(表头在第 2 行 → 输出表头第 1 行)。"""
|
||
if not files:
|
||
raise HrError("没有可合并的花名册文件")
|
||
frames = []
|
||
for status, path in files:
|
||
frame = pd.read_excel(path, header=1)
|
||
frame["类型"] = status
|
||
frames.append(frame)
|
||
log(f"[INFO] 读取 {os.path.basename(path)}({status},{len(frame)} 行)")
|
||
merged = pd.concat(frames, ignore_index=True)
|
||
os.makedirs(os.path.dirname(os.path.abspath(output)), exist_ok=True)
|
||
merged.to_excel(output, index=False)
|
||
log(f"[INFO] 合并完成:{len(merged)} 行 → {output}")
|
||
return output
|
||
|
||
|
||
__all__ = [
|
||
"DEFAULT_STATUSES",
|
||
"DEFAULT_TEMPLATE",
|
||
"DEFAULT_TTL",
|
||
"EXPORT_URL",
|
||
"MENU_NAME",
|
||
"PAGE_URL",
|
||
"ROSTER_ID",
|
||
"TABLE_ID",
|
||
"default_output",
|
||
"export",
|
||
"export_one",
|
||
"in_service_conditions",
|
||
"leave_conditions",
|
||
"leave_range",
|
||
]
|