restore: 恢复 11-06~11-09 本地未提交改动
- libs: 新增 hr_sdk / hotel_report / dingtalk,更新 desktopauto - controlplane-next: SDK 管理模块(controller/entity/migrations)与前端视图 - electron-shell: 插件同步、注册表、runner 调整 - plugins: XQ0035/XQ0041/XQ0042/XQ0045_XQ0046/XQ0048/XQ0076/XQ0078 等版本更新 - tests/tools: 新增 SDK 兼容性检查与打包工具(sdk_pack.py、sdk_compat_check.py)
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
@@ -0,0 +1,141 @@
|
||||
# hr_sdk · HR 系统 SDK
|
||||
|
||||
把 HR(RedseaPlatform)的接口事实收拢成一个纯 Python 运行库:**SDK 出接口,插件出业务**。
|
||||
|
||||
- 包名 / `provides`:`hr_sdk`;SDK id:`hr_sdk`
|
||||
- 版本:见 `sdk.json`(与 `hr_sdk/__version__`、`pyproject.toml` 三处一致)
|
||||
- 依赖:`requests`、`pandas`、`openpyxl`、`websocket-client`(执行机环境包已预装)
|
||||
|
||||
## 边界
|
||||
|
||||
| 进 SDK(机制/接口事实) | 留插件(业务) |
|
||||
|---|---|
|
||||
| 域名/路径/bridge/WS 主题、公共查询入参 | 异常判定口径、店长分组、固定路由、默认处理人 |
|
||||
| `commonQuery` 加密(自定义 Base64 + 盐 + 重排) | 模板列定义(走 HR 模板动态解析,或插件传 `filters`) |
|
||||
| 异步导出(bridge 注册 + WS 订阅 + 下载) | 列名映射、单位过滤、表格版式、落盘命名策略 |
|
||||
| 分页拉全、重试、登录态失效识别 | 推送文案、群里 @ 谁、文件发到哪个群 |
|
||||
| 花名册/预入职/调动/组织接口 | 谁算「异常」、要不要发、发给谁 |
|
||||
|
||||
## 接口
|
||||
|
||||
```python
|
||||
from hr_sdk import HrClient, roster, ledger, org, workflow, attendance, shift, seal, attach, contract
|
||||
|
||||
client = HrClient(ctx.get_session("hr"), log=ctx.log) # 借来的会话,SDK 不 close
|
||||
|
||||
path = roster.export(client, statuses=["在职"], output=out / "花名册.xlsx")
|
||||
path = roster.export_one(client, "离职", leave_start="2026-10-01",
|
||||
leave_end="2026-11-09", output=out / "离职.xlsx")
|
||||
path = ledger.export_transfer(client, output=out / "调动台账.xlsx") # 默认近 30 天
|
||||
path = ledger.export_pre_entry(client, output=out / "预入职台账.xlsx")
|
||||
rows = org.rows(client) # 原始记录
|
||||
|
||||
docs = workflow.list_docs(client, subject="请假") # 待办单据
|
||||
form = workflow.form_data(client, docs[0]["businessKey"], docs[0]["formId"])
|
||||
days = attendance.daily(client, staff_id, "2026-10-01", "2026-10-31")
|
||||
leaves = attendance.leaves(client, staff_id, "2026-10-01", "2026-10-31")
|
||||
punches = attendance.punches(client, staff_id, "2026-10-01", "2026-10-31")
|
||||
|
||||
shifts = shift.person(client, user_id, base_code="37036361",
|
||||
start="2026-11-01", end="2026-11-09")
|
||||
today = shift.day_shift(shifts, "2026-11-09") # 当日完整排班名
|
||||
names = shift.department_names(client, "金色印象XX店") # 该部门全部排班名
|
||||
|
||||
seal_rows = seal.rows(client, month="2026-10") # 封存原始记录
|
||||
paths = attach.download(client, file_id, save_dir=out / "附件")
|
||||
contract.export(client, "生效中", template="合同台账导出", output=out / "合同.xlsx")
|
||||
```
|
||||
|
||||
`HrClient` 还有:`request_json`、`paginate`、`paginate_json`、`download`、`upload`。
|
||||
查询条件:
|
||||
|
||||
```python
|
||||
from hr_sdk import condition, date_range, encode
|
||||
|
||||
conds = date_range("`hr_staff_move_info.MOVE_DATE`", "2026-10-01", "2026-11-09")
|
||||
params["commonQuery"] = encode(conds)
|
||||
```
|
||||
|
||||
## 增/减员导入(`imports`,写操作)
|
||||
|
||||
```python
|
||||
from hr_sdk import imports
|
||||
|
||||
res = imports.upload(client, r"D:\out\增员导入.xlsx", "add") # 默认 dry_run:只校验
|
||||
res = imports.upload(client, r"D:\out\增员导入.xlsx", "add", apply=True) # 真导入(写库)
|
||||
|
||||
codes = imports.read_codes(path) # 文件里的工号(第 4 行起 B 列)
|
||||
rows = imports.operated_staff(client, started_at) # 入库核对数据(判定留插件)
|
||||
```
|
||||
|
||||
- 模板列(服务端 `fieldJson`,会随 HR 调整):**增员** `工号/身份证 · 姓名 · 保险方案名称 · 增员日期 · 备注`;
|
||||
**减员** `工号/身份证 · 姓名 · 减员日期`。文件格式:第 2 行列标题、第 4 行起数据。
|
||||
- `apply=False`(默认)只做「取模板配置 + 文件格式校验 + 表头匹配」,**不写库**。
|
||||
- `apply=True` 时:`businessId` 每次新生成;**提交请求不重试**(防重复导入);结果靠轮询
|
||||
(前端走 WebSocket,这里 2s 一次,默认 300s);失败自动拉「失败数据」明细并核对当天失败批次。
|
||||
- 登录态失效一律抛 `SessionExpiredError`(不吞、不重试)。
|
||||
|
||||
## 会话来源
|
||||
|
||||
- **插件里**:`ctx.get_session("hr")`(壳子按账号自动补登),插件 `platform = "hr"`;
|
||||
- **壳子登录子进程 / CLI / agent**:`hr_sdk.session.session_from_cookies(path)`,
|
||||
默认读 `%LOCALAPPDATA%\37duAutomation\.sessions\hr_cookies.json`
|
||||
(`PLATFORM_ACCOUNT` 存在时按账号隔离到 `.sessions/<账号>/`;`HR_COOKIES_FILE` 可整体覆盖)。
|
||||
|
||||
## 登录原语(`auth`)
|
||||
|
||||
**插件不要调**——登录由壳子按账号完成。只有壳子登录子进程 / CLI / agent 用:
|
||||
|
||||
```python
|
||||
from hr_sdk import auth
|
||||
|
||||
res = auth.ensure_login() # 优先复用 cookies,失效才登录
|
||||
# → {"success": bool, "cookie_path": str, "message": str, "relogin": bool}
|
||||
|
||||
auth.login("user", "pwd") # 强制登录并落盘,失败抛 AuthError
|
||||
auth.session_alive() # 只校验现有 cookies
|
||||
```
|
||||
|
||||
内含:密码 AES-128-ECB(前端硬编码 key)、滑块图 diff + 模板双算法互验、滑块校验、
|
||||
提交登录、cookie 落盘。依赖 `opencv-python-headless` / `numpy` / `pycryptodome`
|
||||
(**惰性导入**,不登录就不会加载)。
|
||||
|
||||
减员/增员导入(写接口)尚未进 SDK:`hr_import_api` 是 6 个接口的 multipart 写链路,
|
||||
需要单独一批 + 真机用测试文件验证,不做半成品。
|
||||
|
||||
## 与既有实现的差异
|
||||
|
||||
| 项 | 既有(`workflows/share/*`、`shared/*`、插件副本) | SDK |
|
||||
|---|---|---|
|
||||
| 公共入参 | 3 份 40 键 dict 各写一遍 | `config.base_params()` 一处 |
|
||||
| 加密协议 | 6 份副本 | `query` 一处(自测与旧实现 sha256 逐字节对齐) |
|
||||
| 异步导出 | 每份 100+ 行 | `export.export_table()` 一处 |
|
||||
| 模板列 | 硬编码字段串 + 失败静默回退 | 动态解析;失败**报错**(不静默导出空列) |
|
||||
| 错误 | `SystemExit` / 返回 dict 混用 | 统一异常 `HrError` 子类 |
|
||||
| 日志 | `print` | `log=` 回调 |
|
||||
| 会话 | 自己读 cookie 文件 | 借用调用方 session |
|
||||
|
||||
## 开发 / 自测 / 发版
|
||||
|
||||
```powershell
|
||||
cd libs\hr_sdk; ..\..\.venv\Scripts\python.exe -m hr_sdk._selftest; cd ..\..
|
||||
|
||||
.venv\Scripts\python.exe tools\sdk_pack.py --sdk libs\hr_sdk --install
|
||||
.venv\Scripts\python.exe tools\agent_cli.py --admin puddy --password 123456 `
|
||||
--base http://172.30.30.243:8800 sdk-publish dist-sdk\hr_sdk_v0.1.0.zip --baseline-sdk <上一版>
|
||||
```
|
||||
|
||||
插件侧声明依赖:
|
||||
|
||||
```json
|
||||
{ "requires": { "sdks": { "hr_sdk": { "compat": "^0.1" } } } }
|
||||
```
|
||||
|
||||
## 坑位
|
||||
|
||||
1. **`currentUserId` / `currentStaffId` / `currentRoleIds` 是抓包默认值**(与原实现一致)。
|
||||
换账号后导出失败优先怀疑这三个;可用 `user={"userId":..., "staffId":..., "roleIds":...}` 覆盖。
|
||||
2. **异步导出必须先 `ws/bridge` 注册**,否则 WS 握手 500;SDK 已封装,别绕过。
|
||||
3. **模板解析失败会直接报错**(不像旧实现静默回退内置字段串),需要旧行为请显式传 `filters=`。
|
||||
4. **花名册缓存 TTL 900s**:同路径 15 分钟内直接复用,要最新数据传 `ttl=0`。
|
||||
5. **`^0.x` caret 语义**:升 `0.2.0` 时消费插件要同批升 `compat`。
|
||||
@@ -0,0 +1,83 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""hr_sdk · HR(RedseaPlatform)接口 SDK(纯运行库,只能被调用)。
|
||||
|
||||
分工:**SDK 出接口,插件出业务**。这里封装登录态访问、查询条件加密、异步导出、
|
||||
分页拉全、模板解析等接口事实;异常判定、店长分组、文案、列名映射、落盘策略留在插件。
|
||||
|
||||
当前版本(0.1.0)覆盖:
|
||||
|
||||
========================== ==========================================================
|
||||
接口 入口
|
||||
========================== ==========================================================
|
||||
通用请求 / 分页 / 下载 :class:`client.HrClient`
|
||||
查询条件加密(commonQuery) :mod:`query`(``condition`` / ``date_range`` / ``encode``)
|
||||
异步导出机制 :mod:`export`(bridge 注册 + WS 订阅 + 下载)
|
||||
花名册(在职/离职) :mod:`roster`(``export`` / ``export_one``)
|
||||
预入职台账 / 调动台账 :mod:`ledger`(``export_pre_entry`` / ``export_transfer``)
|
||||
组织机构 :mod:`org`(``rows``)
|
||||
========================== ==========================================================
|
||||
|
||||
典型用法::
|
||||
|
||||
from hr_sdk import HrClient, roster, ledger
|
||||
|
||||
client = HrClient(ctx.get_session("hr"), log=ctx.log) # 借来的会话,不 close
|
||||
path = roster.export(client, statuses=["在职"], output=out / "花名册.xlsx")
|
||||
transfer = ledger.export_transfer(client, output=out / "调动台账.xlsx")
|
||||
|
||||
契约:不读命令行参数、不 ``sys.exit``、不 ``print``(用 ``log`` 回调)、
|
||||
不 ``close()`` 借来的 session;异常统一为 :class:`errors.HrError` 子类。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
__version__ = "0.1.3"
|
||||
|
||||
from . import (attach, attendance, auth, client, config, contract, errors, export, imports,
|
||||
ledger, org, query, roster, seal, session, shift, workflow)
|
||||
from .client import HrClient
|
||||
from .config import HR_BASE_URL, WS_EXPORT_THEME, base_params, cookies_file
|
||||
from .errors import (ApiError, AuthError, CancelledError, ConfigError, ExportTimeoutError,
|
||||
HrError, SessionExpiredError)
|
||||
from .query import condition, date_range, encode, encode_common_query
|
||||
from .session import SessionLike, looks_like_login_page, session_from_cookies
|
||||
|
||||
__all__ = [
|
||||
"ApiError",
|
||||
"AuthError",
|
||||
"CancelledError",
|
||||
"ConfigError",
|
||||
"ExportTimeoutError",
|
||||
"HR_BASE_URL",
|
||||
"HrClient",
|
||||
"HrError",
|
||||
"SessionExpiredError",
|
||||
"SessionLike",
|
||||
"WS_EXPORT_THEME",
|
||||
"attach",
|
||||
"attendance",
|
||||
"auth",
|
||||
"base_params",
|
||||
"client",
|
||||
"condition",
|
||||
"config",
|
||||
"contract",
|
||||
"cookies_file",
|
||||
"date_range",
|
||||
"encode",
|
||||
"encode_common_query",
|
||||
"errors",
|
||||
"export",
|
||||
"imports",
|
||||
"ledger",
|
||||
"looks_like_login_page",
|
||||
"org",
|
||||
"query",
|
||||
"roster",
|
||||
"seal",
|
||||
"session",
|
||||
"session_from_cookies",
|
||||
"shift",
|
||||
"workflow",
|
||||
"__version__",
|
||||
]
|
||||
@@ -0,0 +1,459 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""离线自测:不联网、不读生产 cookie、不启动浏览器/WS。
|
||||
|
||||
安装时由 ``sdk.json.selftest`` 声明,客户端冒烟会执行 ``main()``;
|
||||
开发态也可直接跑:``python -m hr_sdk._selftest``。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
from datetime import date
|
||||
|
||||
from . import attach, attendance, auth, contract, imports, seal, shift, workflow
|
||||
from . import client as client_mod
|
||||
from . import config, errors, export, ledger, org, query, roster, session
|
||||
|
||||
_CHECKS = 0
|
||||
|
||||
|
||||
def _ok(cond, message: str) -> None:
|
||||
global _CHECKS
|
||||
_CHECKS += 1
|
||||
if not cond:
|
||||
raise AssertionError(message)
|
||||
|
||||
|
||||
def _eq(actual, expected, message: str) -> None:
|
||||
_ok(actual == expected, f"{message}:期望 {expected!r},实际 {actual!r}")
|
||||
|
||||
|
||||
def _raises(exc_type, fn, message: str) -> None:
|
||||
try:
|
||||
fn()
|
||||
except exc_type:
|
||||
_ok(True, message)
|
||||
return
|
||||
except Exception as other: # noqa: BLE001
|
||||
raise AssertionError(f"{message}:期望 {exc_type.__name__},实际 {type(other).__name__}")
|
||||
raise AssertionError(f"{message}:未抛出 {exc_type.__name__}")
|
||||
|
||||
|
||||
# ==================== 查询条件加密 ====================
|
||||
|
||||
#: 与既有实现(workflows/share/roster_export_api.py)逐字节一致的回归锚点
|
||||
_EXPECT_LEN = 758
|
||||
_EXPECT_SHA = "eb63099b0c8e0c52a040553c20f1c6d069cd72b2e90816035fbfcf69a60f6842"
|
||||
|
||||
|
||||
def test_query() -> None:
|
||||
_eq(len(query.CUSTOM_CHARS), 65, "自定义字符表长度(64 字符 + 填充位)")
|
||||
encoded = query.encode(roster.in_service_conditions())
|
||||
_eq(len(encoded), _EXPECT_LEN, "在职条件加密串长度")
|
||||
_eq(hashlib.sha256(encoded.encode()).hexdigest(), _EXPECT_SHA,
|
||||
"在职条件加密串与既有实现一致")
|
||||
|
||||
conds = query.date_range("`x.y`", "2026-01-01", "2026-01-31")
|
||||
_eq(len(conds), 2, "日期区间条件条数")
|
||||
_eq(conds[0]["leftBracket"], "(", "日期区间左括号")
|
||||
_eq(conds[1]["rightBracket"], ")", "日期区间右括号")
|
||||
_eq(conds[0]["inputType"], "date", "日期区间 inputType")
|
||||
|
||||
single = query.condition("`a.b`", "in", "1", query_text="1", input_type="select")
|
||||
_eq(set(single), {"queryField", "leftBracket", "queryType", "queryValue",
|
||||
"queryText", "rightBracket", "logic", "inputType"}, "条件字段齐全")
|
||||
_eq(single["logic"], "AND", "默认逻辑 AND")
|
||||
|
||||
|
||||
# ==================== 公共入参 ====================
|
||||
|
||||
def test_config() -> None:
|
||||
params = config.base_params("员工花名册", "assemble-hr_staff_base", roster.ROSTER_ID)
|
||||
_ok(len(params) >= 35, "公共入参字段数")
|
||||
_eq(params["rosterId"], roster.ROSTER_ID, "rosterId 注入")
|
||||
_eq(params["tableId"], "assemble-hr_staff_base", "tableId 注入")
|
||||
_eq(params["menuName"], "员工花名册", "menuName 注入")
|
||||
_ok(all(isinstance(v, str) for v in params.values()), "入参值全部为字符串")
|
||||
|
||||
with_user = config.base_params("m", "t", "r", user={"userId": "u1", "staffId": "s1",
|
||||
"roleIds": "r1"})
|
||||
_eq((with_user["currentUserId"], with_user["currentStaffId"], with_user["currentRoleIds"]),
|
||||
("u1", "s1", "r1"), "身份覆盖生效")
|
||||
_eq(config.base_params("m", "t", "r", baseHrefPath="x")["baseHrefPath"], "x", "任意覆盖项")
|
||||
|
||||
_ok(config.cookies_file().endswith(".json"), "cookies 路径是文件")
|
||||
|
||||
|
||||
# ==================== 会话 ====================
|
||||
|
||||
def test_session() -> None:
|
||||
_ok(session.looks_like_login_page("<!DOCTYPE html><html>"), "HTML 判定为登录页")
|
||||
_ok(not session.looks_like_login_page('{"state":"1"}'), "JSON 判定为正常")
|
||||
_raises(errors.ConfigError,
|
||||
lambda: session.session_from_cookies(r"Z:\not-exist\hr_cookies.json"),
|
||||
"cookie 文件缺失抛 ConfigError")
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = os.path.join(tmp, "c.json")
|
||||
with open(path, "w", encoding="utf-8") as fp:
|
||||
json.dump([{"name": "a", "value": "1", "domain": ".37du.co", "path": "/"},
|
||||
{"name": "b", "value": "2", "domain": ".other.com", "path": "/"}], fp)
|
||||
sess = session.session_from_cookies(path)
|
||||
_eq(len(sess.cookies), 1, "仅保留目标域 cookies")
|
||||
|
||||
|
||||
# ==================== 客户端 ====================
|
||||
|
||||
class _Resp:
|
||||
def __init__(self, text: str, status: int = 200):
|
||||
self.text = text
|
||||
self.status_code = status
|
||||
self.content = text.encode("utf-8")
|
||||
|
||||
def json(self):
|
||||
return json.loads(self.text)
|
||||
|
||||
|
||||
class _FakeSession:
|
||||
cookies: list = []
|
||||
|
||||
def get(self, url, **kwargs): # noqa: D401
|
||||
return _Resp('{"state":"1"}')
|
||||
|
||||
def post(self, url, **kwargs):
|
||||
return _Resp('{"state":"1"}')
|
||||
|
||||
|
||||
def test_client() -> None:
|
||||
hr = client_mod.HrClient(_FakeSession(), log=lambda m: None)
|
||||
_eq(hr.as_json(_Resp('{"state": "1"}')), {"state": "1"}, "JSON 解析")
|
||||
_raises(errors.SessionExpiredError, lambda: hr.as_json(_Resp("<html>login</html>")),
|
||||
"HTML 响应抛登录态失效")
|
||||
_raises(errors.ApiError, lambda: hr.as_json(_Resp("{oops")), "坏 JSON 抛 ApiError")
|
||||
|
||||
pages = {1: ([{"a": 1}, {"a": 2}], True), 2: ([{"a": 3}], False)}
|
||||
rows = hr.paginate(lambda no, size: pages[no], page_size=2, sleep=0)
|
||||
_eq(len(rows), 3, "分页合并 3 行")
|
||||
_eq(rows[-1]["a"], 3, "分页顺序保持")
|
||||
|
||||
_eq(hr.check_state({"state": "1", "datas": []})["state"], "1", "state=1 通过")
|
||||
_raises(errors.SessionExpiredError,
|
||||
lambda: hr.check_state({"state": "0", "meg": "会话过期,请重新登录!"}),
|
||||
"服务端会话过期 → 登录态失效")
|
||||
_raises(errors.ApiError,
|
||||
lambda: hr.check_state({"state": "0", "meg": "参数错误"}),
|
||||
"业务错误 → ApiError")
|
||||
|
||||
_raises(errors.ConfigError, lambda: client_mod.HrClient(None), "空会话抛 ConfigError")
|
||||
|
||||
|
||||
# ==================== 导出机制 ====================
|
||||
|
||||
def test_export() -> None:
|
||||
base = config.base_params("m", "t", "r")
|
||||
with_cond = export.build_params(base, conditions=roster.in_service_conditions(),
|
||||
template="员工基础信息", filters="a.b,c.d")
|
||||
_eq(with_cond["exportConfig"],
|
||||
'{"exportName":"员工基础信息","exportFilters":"a.b,c.d"}', "导出配置 JSON")
|
||||
_ok(with_cond["commonQuery"].startswith("BH"), "条件加密注入 commonQuery")
|
||||
_ok(int(with_cond["_t"]) > 1_000_000_000_000, "时间戳为毫秒")
|
||||
|
||||
_raises(errors.ConfigError,
|
||||
lambda: export.build_params(base, template="t", filters=""),
|
||||
"有模板无字段串抛 ConfigError")
|
||||
_eq(export.build_params(base, conditions=None).get("commonQuery"), "",
|
||||
"无条件时 commonQuery 保持空串")
|
||||
|
||||
|
||||
# ==================== 业务接口(纯构造部分) ====================
|
||||
|
||||
class _DummyClient:
|
||||
def __init__(self):
|
||||
self.log = lambda msg: None
|
||||
|
||||
|
||||
def test_roster() -> None:
|
||||
_eq(len(roster.in_service_conditions()), 2, "在职条件 2 条")
|
||||
_eq(len(roster.leave_conditions("2026-09-01", "2026-10-31")), 4, "离职条件 4 条")
|
||||
_eq(roster.leave_range(date(2026, 11, 9)), ("2026-10-01", "2026-11-09"), "离职默认范围")
|
||||
|
||||
# TTL 缓存命中:不触碰网络(DummyClient 无 session)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = os.path.join(tmp, "花名册.xlsx")
|
||||
with open(path, "wb") as fp:
|
||||
fp.write(b"x")
|
||||
_eq(roster.export(_DummyClient(), output=path, ttl=900), os.path.abspath(path),
|
||||
"TTL 缓存命中直接复用")
|
||||
|
||||
|
||||
def test_ledger() -> None:
|
||||
_eq(ledger.recent_range(date(2026, 11, 9), 30), ("2026-10-11", "2026-11-09"),
|
||||
"近 30 天范围")
|
||||
_eq(ledger.recent_range(date(2026, 3, 1), 1), ("2026-03-01", "2026-03-01"), "单日范围")
|
||||
_ok(ledger.TRANSFER_ROSTER_ID != ledger.PRE_ENTRY_ROSTER_ID, "两个台账 rosterId 不同")
|
||||
_ok(ledger.TRANSFER_EXPORT_URL.endswith("exportCommonListData.mc"), "调动导出地址")
|
||||
_ok(ledger.PRE_ENTRY_EXPORT_URL.endswith("exportCommonListData.mc"), "预入职导出地址")
|
||||
|
||||
|
||||
def test_org() -> None:
|
||||
conds = org.conditions()
|
||||
_eq(len(conds), 1, "组织条件 1 条")
|
||||
_eq(conds[0]["queryType"], "in", "组织条件类型")
|
||||
_ok(org.ORG_QUERY_URL.endswith("queryRealTimeData.mc"), "组织查询地址")
|
||||
|
||||
|
||||
def test_workflow() -> None:
|
||||
data = {"jsonList": [
|
||||
{"title": "请假-张三", "taskId": "t1", "businessKey": "b1",
|
||||
"processId": "p1", "formId": "f1", "createTime": "2026-11-01"},
|
||||
{"title": "缺字段行"},
|
||||
]}
|
||||
docs = workflow.parse_docs(data)
|
||||
_eq(len(docs), 1, "缺 taskId/businessKey 的行被跳过")
|
||||
_eq(docs[0]["taskId"], "t1", "taskId 解析")
|
||||
_ok("reqType=WAIT" in docs[0]["detail_url"], "详情地址带待办视图参数")
|
||||
_ok(workflow.detail_url(task_id="t1").endswith("systemId="), "detail_url 拼接")
|
||||
_ok(workflow.WE_PROCESS_QUERY_URL.endswith("getProcessAndData"), "待办查询地址")
|
||||
|
||||
|
||||
def test_attendance() -> None:
|
||||
_eq(len(attendance.DAILY_STATUSES), 4, "逐日考勤四种状态")
|
||||
ok = attendance._check_success({"success": True, "code": 200, "data": {}}, "x")
|
||||
_eq(str(ok.get("code")), "200", "success/code 信封通过")
|
||||
_raises(errors.SessionExpiredError,
|
||||
lambda: attendance._check_success(
|
||||
{"success": False, "code": 500, "message": "会话过期"}, "x"),
|
||||
"会话过期 → 登录态失效")
|
||||
_raises(errors.ApiError,
|
||||
lambda: attendance._check_success(
|
||||
{"success": False, "code": 500, "message": "参数错误"}, "x"),
|
||||
"业务失败 → ApiError")
|
||||
|
||||
|
||||
def test_shift() -> None:
|
||||
_eq(shift.day_shift([{"2026-11-09_team_name": "早班"}], "2026-11-09"), "早班",
|
||||
"当日排班取值")
|
||||
_eq(shift.day_shift([{"2026-11-09_team_name": ""}], "2026-11-09"), "",
|
||||
"空排班返回空串")
|
||||
_eq(shift.day_shift([], "2026-11-09"), "", "无记录返回空串")
|
||||
_ok(shift.WORK_DATE_QUERY_URL.endswith("rf_s_kq_work_date_query/redApiExec.mc"),
|
||||
"部门排班地址")
|
||||
|
||||
|
||||
def test_seal() -> None:
|
||||
_eq(seal.normalize_month("202610"), "2026-10", "YYYYMM 归一")
|
||||
_eq(seal.normalize_month("2026-10"), "2026-10", "YYYY-MM 保持")
|
||||
_eq(len(seal.normalize_month()), 7, "缺省取上月(YYYY-MM)")
|
||||
_ok(seal.SEAL_URL.endswith("getPageAjaxList.mc"), "封存查询地址")
|
||||
|
||||
|
||||
def test_attach() -> None:
|
||||
headers = {"Content-Disposition": 'attachment; filename="合同.pdf"'}
|
||||
_eq(attach._filename_from_headers(headers, "x.bin"), "合同.pdf", "文件名解析")
|
||||
_eq(attach._filename_from_headers({}, "f.bin"), "f.bin", "无头信息用兜底名")
|
||||
_raises(errors.ConfigError, lambda: attach.download(_DummyClient(), "", "d"),
|
||||
"空 file_id 抛 ConfigError")
|
||||
|
||||
|
||||
def test_contract() -> None:
|
||||
_eq(len(contract.ROSTERS), 2, "两个合同台账")
|
||||
_raises(errors.ConfigError,
|
||||
lambda: contract.export(_DummyClient(), tag="不存在"),
|
||||
"未知合同台账抛 ConfigError")
|
||||
_raises(errors.ConfigError,
|
||||
lambda: contract.export(_DummyClient(), tag="生效中"),
|
||||
"模板与字段串都没给抛 ConfigError")
|
||||
|
||||
|
||||
def test_export_pipeline() -> None:
|
||||
"""桩掉 export_table,验证「参数构造 → 调用」链路(防模块名被同名函数遮蔽)。"""
|
||||
calls = {}
|
||||
original = export.export_table
|
||||
|
||||
def _stub(client, **kwargs):
|
||||
calls.clear()
|
||||
calls.update(kwargs)
|
||||
return kwargs["output_path"]
|
||||
|
||||
export.export_table = _stub
|
||||
try:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = roster.export_one(_DummyClient(), "在职", filters="a.b,c.d",
|
||||
output=os.path.join(tmp, "在职.xlsx"))
|
||||
_ok(path.endswith("在职.xlsx"), "花名册单状态导出链路")
|
||||
_ok("员工基础信息" in calls["params"]["exportConfig"], "导出参数带模板名")
|
||||
_ok(bool(calls["params"]["commonQuery"]), "导出参数带加密条件")
|
||||
|
||||
path = contract.export(_DummyClient(), "生效中", filters="a.b",
|
||||
output=os.path.join(tmp, "合同.xlsx"))
|
||||
_ok(path.endswith("合同.xlsx"), "合同台账导出链路")
|
||||
_eq(calls["params"]["rosterId"], contract.ROSTERS["生效中"], "合同 rosterId")
|
||||
finally:
|
||||
export.export_table = original
|
||||
|
||||
|
||||
class _ImportResp:
|
||||
def __init__(self, text: str):
|
||||
self.text = text
|
||||
self.status_code = 200
|
||||
self.content = text.encode("utf-8")
|
||||
|
||||
def json(self):
|
||||
return json.loads(self.text)
|
||||
|
||||
|
||||
class _ImportStubClient:
|
||||
"""导入链路用的假客户端:只回放固定配置与表头校验响应,不联网。"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.log = lambda msg: None
|
||||
|
||||
def get(self, url, headers=None, timeout=None):
|
||||
conf = {
|
||||
"id": "12eecb13-78b0-4fac-a865-10c3043a33e1",
|
||||
"title": "商业保险增员导入",
|
||||
"maxNum": 500,
|
||||
"fieldJson": json.dumps([{"columnName": "a", "columnDisplay": "姓名"},
|
||||
{"columnName": "b", "columnDisplay": "工号"}],
|
||||
ensure_ascii=False),
|
||||
}
|
||||
return _ImportResp("var hrModuleBaseImport = " + json.dumps(conf, ensure_ascii=False)
|
||||
+ ";")
|
||||
|
||||
def post_files(self, url, files=None, data=None, timeout=None):
|
||||
return _ImportResp(json.dumps({
|
||||
"state": "1",
|
||||
"result": [{"excelColName": "姓名", "excelColNum": 1},
|
||||
{"excelColName": "工号", "excelColNum": 2}],
|
||||
}, ensure_ascii=False))
|
||||
|
||||
def as_json(self, resp, label=""):
|
||||
return json.loads(resp.text)
|
||||
|
||||
def check_state(self, data, label=""):
|
||||
return data
|
||||
|
||||
|
||||
def test_imports() -> None:
|
||||
_eq(imports.menu_info("add")["label"], "增员导入", "增员菜单")
|
||||
_ok(imports.menu_info("SUB")["import_id"].startswith("22e"), "减员菜单(大小写不敏感)")
|
||||
_raises(errors.ConfigError, lambda: imports.menu_info("x"), "未知导入类型抛 ConfigError")
|
||||
|
||||
fields = [{"columnName": "a", "columnDisplay": "姓名"},
|
||||
{"columnName": "b", "columnDisplay": "工号"}]
|
||||
titles = [{"excelColName": "姓名", "excelColNum": 1},
|
||||
{"excelColName": "工号", "excelColNum": 2}]
|
||||
title_list, matched = imports.match_titles(fields, titles)
|
||||
_eq(matched, 2, "表头匹配列数")
|
||||
_eq(title_list[0]["excelColNum"], 1, "回填 excelColNum")
|
||||
_eq(len(imports.field_list({"fieldJson": '[{"columnName":"a"}]'})), 1, "fieldJson 解析")
|
||||
|
||||
text = '{"姓名":"张三","备注":"a&b=c"}'
|
||||
_eq(query.decode_raw(query.encode_raw(text)), text, "titleList 编码/解码互逆")
|
||||
|
||||
from openpyxl import Workbook
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = os.path.join(tmp, "import.xlsx")
|
||||
book = Workbook()
|
||||
sheet = book.active
|
||||
sheet.append(["商业保险增员导入"])
|
||||
sheet.append(["姓名", "工号"])
|
||||
sheet.append([])
|
||||
sheet.append([1, "37000001"])
|
||||
sheet.append([2, "37000002"])
|
||||
sheet.append(["", "37000003"]) # A 列空 → 不计入
|
||||
book.save(path)
|
||||
_eq(imports.read_codes(path), ["37000001", "37000002"], "读导入文件工号")
|
||||
|
||||
stub = _ImportStubClient()
|
||||
res = imports.upload(stub, path, "add")
|
||||
_eq(res["dry_run"], True, "默认 dry_run")
|
||||
_eq(res["applied"], False, "dry_run 不提交写库")
|
||||
_eq(res["ok"], True, "dry_run 校验通过")
|
||||
_eq(res["matched"], 2, "dry_run 匹配列数")
|
||||
_eq(res["fields"], 2, "模板字段数")
|
||||
|
||||
_raises(errors.ConfigError,
|
||||
lambda: imports.upload(stub, os.path.join(tmp, "none.xlsx")),
|
||||
"文件缺失抛 ConfigError")
|
||||
|
||||
|
||||
def test_auth() -> None:
|
||||
import base64 as _b64
|
||||
|
||||
raw = _b64.b64decode(auth.aes_encrypt_password("123456"))
|
||||
_eq(len(raw) % 16, 0, "AES 密文按 16 字节对齐")
|
||||
from Crypto.Cipher import AES
|
||||
plain = AES.new(auth.AES_KEY, AES.MODE_ECB).decrypt(raw)
|
||||
_ok(plain.startswith(b"123456"), "AES 回解得到原文")
|
||||
_ok(auth.CAPTCHA_GET_URL.endswith("image.mob"), "滑块图地址")
|
||||
_ok(auth.LOGIN_POST_URL.endswith("/PW"), "登录提交地址")
|
||||
_eq(auth.solve_distance({"shade": None, "origin": None, "cutout": None}),
|
||||
(None, "无法定位"), "缺图时无法定位缺口")
|
||||
|
||||
old_user = os.environ.pop("hr_login_username", None)
|
||||
old_pwd = os.environ.pop("hr_login_password", None)
|
||||
try:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
res = auth.ensure_login(cookie_path=os.path.join(tmp, "none.json"))
|
||||
_eq(res["success"], False, "无凭证时 ensure_login 失败")
|
||||
_eq(res["relogin"], False, "无凭证时不标记 relogin")
|
||||
_raises(errors.ConfigError, lambda: auth.login("", ""), "空账号抛 ConfigError")
|
||||
finally:
|
||||
if old_user is not None:
|
||||
os.environ["hr_login_username"] = old_user
|
||||
if old_pwd is not None:
|
||||
os.environ["hr_login_password"] = old_pwd
|
||||
|
||||
_eq(config.cookies_file(account="alice").split(os.sep)[-2], "alice",
|
||||
"cookie 按账号隔离目录")
|
||||
|
||||
|
||||
# ==================== 入口 ====================
|
||||
|
||||
def main() -> int:
|
||||
from . import __version__
|
||||
|
||||
tests = [
|
||||
("query", test_query),
|
||||
("config", test_config),
|
||||
("session", test_session),
|
||||
("client", test_client),
|
||||
("export", test_export),
|
||||
("roster", test_roster),
|
||||
("ledger", test_ledger),
|
||||
("org", test_org),
|
||||
("workflow", test_workflow),
|
||||
("attendance", test_attendance),
|
||||
("shift", test_shift),
|
||||
("seal", test_seal),
|
||||
("attach", test_attach),
|
||||
("contract", test_contract),
|
||||
("export_pipeline", test_export_pipeline),
|
||||
("imports", test_imports),
|
||||
("auth", test_auth),
|
||||
]
|
||||
failed = 0
|
||||
try:
|
||||
_eq(__version__, "0.1.3", "包版本与 sdk.json 一致")
|
||||
for name, fn in tests:
|
||||
try:
|
||||
fn()
|
||||
print(f"[ok] {name}")
|
||||
except AssertionError as exc:
|
||||
failed += 1
|
||||
print(f"[FAIL] {name}: {exc}")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
failed += 1
|
||||
print(f"[ERROR] {name}: {type(exc).__name__}: {exc}")
|
||||
finally:
|
||||
print(f"自测完成:{_CHECKS} 项断言,失败 {failed} 组")
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,86 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""附件下载(审批单附件等)。
|
||||
|
||||
用法::
|
||||
|
||||
from hr_sdk import HrClient, attach
|
||||
|
||||
client = HrClient(ctx.get_session("hr"))
|
||||
paths = attach.download(client, file_id, save_dir=r"D:\\out\\附件")
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import List, Sequence
|
||||
from urllib.parse import unquote
|
||||
|
||||
from .config import REDSEA, USER_AGENT
|
||||
from .errors import ConfigError
|
||||
|
||||
ATTACHMENT_URL = f"{REDSEA}/corePlatformOutUser/fjkFileDownload.mob"
|
||||
|
||||
|
||||
def _filename_from_headers(headers: dict, fallback: str) -> str:
|
||||
"""从 Content-Disposition 解析文件名(兼容 ``UTF-8''`` 与 latin-1 编码)。"""
|
||||
disposition = ""
|
||||
for key, value in (headers or {}).items():
|
||||
if key.lower() == "content-disposition":
|
||||
disposition = str(value)
|
||||
break
|
||||
if "filename=" not in disposition:
|
||||
return fallback
|
||||
raw = disposition.split("filename=")[-1].strip().strip('"')
|
||||
if raw.startswith("UTF-8''"):
|
||||
raw = unquote(raw.split("UTF-8''", 1)[1])
|
||||
else:
|
||||
try:
|
||||
raw = raw.encode("latin-1").decode("utf-8")
|
||||
except (UnicodeDecodeError, UnicodeEncodeError):
|
||||
pass
|
||||
return raw or fallback
|
||||
|
||||
|
||||
def download(client, file_id: str, save_dir: str) -> str:
|
||||
"""下载单个附件,返回本地路径。
|
||||
|
||||
``file_id`` 允许逗号分隔多个(与接口字段一致),此时只下第一个;批量用
|
||||
:func:`download_many`。
|
||||
|
||||
Raises:
|
||||
ConfigError: file_id / save_dir 为空
|
||||
HrError: HTTP 非 200 或内容为空
|
||||
"""
|
||||
ids = [x.strip() for x in str(file_id or "").split(",") if x.strip()]
|
||||
if not ids:
|
||||
raise ConfigError("file_id 为空")
|
||||
if not save_dir:
|
||||
raise ConfigError("save_dir 不能为空")
|
||||
|
||||
fid = ids[0]
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
resp = client.session.get(f"{ATTACHMENT_URL}?fileId={fid}",
|
||||
headers={"User-Agent": USER_AGENT}, timeout=60)
|
||||
if resp.status_code != 200 or not resp.content:
|
||||
from .errors import HrError
|
||||
raise HrError(f"附件下载失败:HTTP {resp.status_code}(fileId={fid})")
|
||||
name = _filename_from_headers(getattr(resp, "headers", {}) or {}, f"{fid}.bin")
|
||||
path = os.path.abspath(os.path.join(save_dir, name))
|
||||
with open(path, "wb") as fp:
|
||||
fp.write(resp.content)
|
||||
client.log(f"[INFO] 附件已下载:{path}({len(resp.content)} 字节)")
|
||||
return path
|
||||
|
||||
|
||||
def download_many(client, file_ids: Sequence[str], save_dir: str) -> List[str]:
|
||||
"""下载多个附件;单个失败不影响其它(失败记录 WARN 并跳过)。"""
|
||||
paths: List[str] = []
|
||||
for fid in file_ids or []:
|
||||
try:
|
||||
paths.append(download(client, fid, save_dir))
|
||||
except Exception as exc: # noqa: BLE001
|
||||
client.log(f"[WARN] 附件 {fid} 下载失败:{exc}")
|
||||
return paths
|
||||
|
||||
|
||||
__all__ = ["ATTACHMENT_URL", "download", "download_many"]
|
||||
@@ -0,0 +1,117 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""考勤接口:逐日考勤 / 请假记录 / 打卡明细。
|
||||
|
||||
用法::
|
||||
|
||||
from hr_sdk import HrClient, attendance
|
||||
|
||||
client = HrClient(ctx.get_session("hr"))
|
||||
days = attendance.daily(client, staff_id, "2026-10-01", "2026-10-31")
|
||||
leaves = attendance.leaves(client, staff_id, "2026-10-01", "2026-10-31")
|
||||
punches = attendance.punches(client, staff_id, "2026-10-01", "2026-10-31")
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Dict, List
|
||||
|
||||
from .config import MAX_PAGES, REDSEA
|
||||
from .errors import ApiError, SessionExpiredError
|
||||
|
||||
ATTENDANCE_DAILY_URL = f"{REDSEA}/redmagicapi/rf_s_kq_count_leave_yc_day_all/redApiExec.mc"
|
||||
LEAVE_RECORD_URL = f"{REDSEA}/redmagicapi/rf_s_kq_leave_record_SelectByStaffID/redApiExec.mc"
|
||||
PUNCH_RECORD_URL = f"{REDSEA}/redmagicapi/rf_s_kq_data_queryByStaffId/redApiExec.mc"
|
||||
|
||||
DEFAULT_PAGE_SIZE = 100
|
||||
#: 逐日考勤按考勤状态各查一次:0=休息日 1=正常班 9=未打卡 11=异常
|
||||
DAILY_STATUSES = ("0", "1", "9", "11")
|
||||
|
||||
|
||||
def _check_success(data: dict, label: str) -> dict:
|
||||
"""``redApiExec`` 用 ``success/code`` 信封(与 ``state`` 不同)。"""
|
||||
if data.get("success") is True and str(data.get("code")) == "200":
|
||||
return data
|
||||
message = str(data.get("message") or data.get("msg") or data)
|
||||
if any(hint in message for hint in ("会话", "登录")):
|
||||
raise SessionExpiredError(f"{label}登录态失效:{message}")
|
||||
raise ApiError(f"{label}返回失败:{message}", code=str(data.get("code") or ""),
|
||||
payload=data)
|
||||
|
||||
|
||||
def _page_records(client, url: str, payload: dict, label: str, *,
|
||||
page_size: int = DEFAULT_PAGE_SIZE, max_pages: int = MAX_PAGES,
|
||||
sleep: float = 0.2) -> List[dict]:
|
||||
"""``data{list,total,pageCount}`` 形态的自动分页。"""
|
||||
records: List[dict] = []
|
||||
page_count = 1
|
||||
for page_no in range(1, max_pages + 1):
|
||||
body = dict(payload)
|
||||
body.update({"start": str((page_no - 1) * page_size), "pageNo": str(page_no),
|
||||
"pageSize": str(page_size)})
|
||||
data = _check_success(client.request_json("POST", url, data=body, label=label),
|
||||
label)
|
||||
info = data.get("data") if isinstance(data.get("data"), dict) else {}
|
||||
page_rows = info.get("list") or []
|
||||
records.extend(page_rows)
|
||||
if page_no == 1:
|
||||
page_count = int(info.get("pageCount") or 1)
|
||||
client.log(f"[INFO] {label}共 {info.get('total')} 条 / {page_count} 页")
|
||||
if page_no >= page_count or not page_rows:
|
||||
break
|
||||
if sleep:
|
||||
time.sleep(sleep)
|
||||
return records
|
||||
|
||||
|
||||
# ==================== 逐日考勤 ====================
|
||||
|
||||
def daily(client, staff_id: str, start: str, end: str) -> List[dict]:
|
||||
"""按员工 + 日期范围查每日考勤(按 ``work_day`` 合并四种状态)。"""
|
||||
by_day: Dict[str, dict] = {}
|
||||
for status in DAILY_STATUSES:
|
||||
params = {"staff_id": staff_id, "begin_date": start, "end_date": end,
|
||||
"kq_status_total": status}
|
||||
data = client.request_json("POST", ATTENDANCE_DAILY_URL, data=params,
|
||||
label="考勤逐日")
|
||||
_check_success(data, "考勤逐日")
|
||||
for row in data.get("data") or []:
|
||||
by_day.setdefault(str(row.get("work_day", "")), row)
|
||||
records = [by_day[k] for k in sorted(by_day)]
|
||||
client.log(f"[INFO] 逐日考勤合并 {len(records)} 天({staff_id} {start}~{end})")
|
||||
return records
|
||||
|
||||
|
||||
# ==================== 请假 / 打卡 ====================
|
||||
|
||||
def leaves(client, staff_id: str, start: str, end: str, *,
|
||||
sub_type: str = "-1", page_size: int = DEFAULT_PAGE_SIZE) -> List[dict]:
|
||||
"""请假记录(自动分页)。"""
|
||||
payload = {"sub_type": sub_type, "staff_id": staff_id,
|
||||
"begin_date": start, "end_date": end,
|
||||
"sortType": "", "sortName": ""}
|
||||
return _page_records(client, LEAVE_RECORD_URL, payload, "请假记录",
|
||||
page_size=page_size)
|
||||
|
||||
|
||||
def punches(client, staff_id: str, start: str, end: str, *,
|
||||
sub_type: str = "-1", page_size: int = DEFAULT_PAGE_SIZE) -> List[dict]:
|
||||
"""打卡明细(自动分页;``kq_time`` 真实打卡时间 / ``bc_date`` 考勤归属日)。"""
|
||||
payload = {"staff_id": staff_id, "rootId": "", "countId": "",
|
||||
"bc_date": start, "bc_date_end": end,
|
||||
"begin": start, "end": end, "sub_type": sub_type,
|
||||
"sortType": "", "sortName": ""}
|
||||
return _page_records(client, PUNCH_RECORD_URL, payload, "打卡明细",
|
||||
page_size=page_size)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"ATTENDANCE_DAILY_URL",
|
||||
"DAILY_STATUSES",
|
||||
"DEFAULT_PAGE_SIZE",
|
||||
"LEAVE_RECORD_URL",
|
||||
"PUNCH_RECORD_URL",
|
||||
"daily",
|
||||
"leaves",
|
||||
"punches",
|
||||
]
|
||||
@@ -0,0 +1,418 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""HR 登录原语(纯接口,无浏览器):AES 密码、滑块定位、提交登录、cookie 落盘。
|
||||
|
||||
**插件不要调这里**——插件用宿主注入的会话(``ctx.get_session("hr")``),
|
||||
登录由壳子按账号完成。本模块只服务三类「没有宿主」的场景:
|
||||
|
||||
1. 壳子登录子进程(``platform-auth.js`` 拉起 python 调 ``ensure_login()``);
|
||||
2. CLI / agent / 一次性排查;
|
||||
3. 离线自测(不联网的那部分)。
|
||||
|
||||
登录链路(2026-10 实测):
|
||||
GET 登录页 → GET 滑块图(shade/origin/cutout + y)
|
||||
→ 定位缺口 x(diff 法 + 模板匹配互验) → POST 校验滑块
|
||||
→ POST j_red_security_check/PW(密码 AES-128-ECB)→ GET getCurUserInfo 校验 → 落盘 cookies。
|
||||
|
||||
依赖:``requests`` + ``opencv-python-headless``/``numpy`` + ``pycryptodome``(惰性导入,
|
||||
只用登录时才付这份代价)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import importlib
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import time
|
||||
from typing import Callable, Optional, Tuple
|
||||
|
||||
import requests
|
||||
|
||||
from .config import REDSEA, USER_AGENT, cookies_file
|
||||
from .errors import AuthError, ConfigError
|
||||
from .session import looks_like_login_page
|
||||
|
||||
LOGIN_URL = f"{REDSEA}/"
|
||||
CAPTCHA_GET_URL = f"{REDSEA}/captcha/get/verification/image.mob"
|
||||
CAPTCHA_CHECK_URL = f"{REDSEA}/captcha/check/verification/result.mob"
|
||||
LOGIN_POST_URL = f"{REDSEA}/j_red_security_check/PW"
|
||||
CUR_USER_URL = f"{REDSEA}/PtUsers.mc?method=getCurUserInfo"
|
||||
|
||||
#: 前端登录页硬编码的 AES 密钥与 CSRF 常量(接口事实,非我方密钥)
|
||||
AES_KEY = b"ps_uer_!@#BGYUJN"
|
||||
CSRF_TOKEN = "RP"
|
||||
|
||||
#: 浏览器可见窗口(登录页 .imgBg 340x171 固定、background 原尺寸绘制)
|
||||
VIEW_W = 340
|
||||
VIEW_H = 171
|
||||
|
||||
TIMEOUT = 15
|
||||
RETRY_MAX = 5 # 单轮滑块重试次数
|
||||
LOGIN_ROUND_MAX = 3 # 整轮登录最大重试(项目级 3 次)
|
||||
|
||||
LOGGER = Callable[[str], None]
|
||||
|
||||
|
||||
# ==================== 依赖惰性加载 ====================
|
||||
|
||||
def _require(module: str, hint: str):
|
||||
try:
|
||||
return importlib.import_module(module)
|
||||
except ImportError: # pragma: no cover - 环境缺依赖
|
||||
raise ConfigError(f"登录需要 {module}(执行机环境包应已预装):{hint}") from None
|
||||
|
||||
|
||||
def _cv2_np():
|
||||
return _require("cv2", "pip install opencv-python-headless"), _require("numpy", "pip install numpy")
|
||||
|
||||
|
||||
# ==================== 密码加密 ====================
|
||||
|
||||
def aes_encrypt_password(password: str) -> str:
|
||||
"""AES-128-ECB + PKCS7,key 为前端硬编码常量,输出 base64(等价 CryptoJS)。"""
|
||||
aes_mod = _require("Crypto.Cipher.AES", "pip install pycryptodome")
|
||||
pad_mod = _require("Crypto.Util.Padding", "pip install pycryptodome")
|
||||
cipher = aes_mod.new(AES_KEY, aes_mod.MODE_ECB)
|
||||
return base64.b64encode(cipher.encrypt(pad_mod.pad(password.encode("utf-8"), 16))
|
||||
).decode("ascii")
|
||||
|
||||
|
||||
# ==================== 会话与 cookie ====================
|
||||
|
||||
def new_session(timeout: float = TIMEOUT) -> requests.Session:
|
||||
"""建立会话并访问登录页拿基础 cookie(验证码与登录必须同一会话)。"""
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": USER_AGENT,
|
||||
"Referer": LOGIN_URL,
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
})
|
||||
session.get(LOGIN_URL, timeout=timeout)
|
||||
return session
|
||||
|
||||
|
||||
def save_cookies(session, path: str = "") -> str:
|
||||
"""把会话 cookie 落盘为 ``[{name,value,domain,path,expires}]``,返回文件路径。"""
|
||||
target = path or cookies_file()
|
||||
items = [{
|
||||
"name": c.name, "value": c.value, "domain": c.domain,
|
||||
"path": c.path or "/",
|
||||
"expires": int(c.expires) if c.expires else None,
|
||||
} for c in session.cookies]
|
||||
if not items:
|
||||
raise AuthError("未获取到 Cookies,无法保存登录态")
|
||||
os.makedirs(os.path.dirname(os.path.abspath(target)), exist_ok=True)
|
||||
with open(target, "w", encoding="utf-8") as fp:
|
||||
json.dump(items, fp, ensure_ascii=False, indent=2)
|
||||
return target
|
||||
|
||||
|
||||
def load_cookies(path: str = "") -> Optional[list]:
|
||||
"""读取 cookies 文件;不存在返回 ``None``。"""
|
||||
target = path or cookies_file()
|
||||
if not os.path.exists(target):
|
||||
return None
|
||||
try:
|
||||
with open(target, encoding="utf-8") as fp:
|
||||
data = json.load(fp)
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
items = data.get("cookies") if isinstance(data, dict) else data
|
||||
return items or None
|
||||
|
||||
|
||||
def session_alive(*, cookie_path: str = "", validate_url: str = "",
|
||||
timeout: float = TIMEOUT) -> bool:
|
||||
"""用 cookies 请求 ``getCurUserInfo``:返回 JSON 视为有效。"""
|
||||
from .session import session_from_cookies
|
||||
|
||||
try:
|
||||
session = session_from_cookies(cookie_path or cookies_file())
|
||||
except ConfigError:
|
||||
return False
|
||||
try:
|
||||
resp = session.post(validate_url or CUR_USER_URL, data={}, timeout=timeout)
|
||||
except requests.RequestException:
|
||||
return False
|
||||
if resp.status_code != 200:
|
||||
return False
|
||||
return not looks_like_login_page(resp.text or "")
|
||||
|
||||
|
||||
# ==================== 滑块 ====================
|
||||
|
||||
def _b64_to_img(b64str: str, flag: int):
|
||||
cv2, np = _cv2_np()
|
||||
if not b64str:
|
||||
return None
|
||||
try:
|
||||
buf = base64.b64decode(b64str)
|
||||
return cv2.imdecode(np.frombuffer(buf, np.uint8), flag)
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
|
||||
|
||||
def _crop_view(img):
|
||||
"""裁切到浏览器可见窗口(坐标与页面 1:1)。"""
|
||||
if img is None:
|
||||
return None
|
||||
height, width = img.shape[:2]
|
||||
return img[:min(height, VIEW_H), :min(width, VIEW_W)]
|
||||
|
||||
|
||||
def get_captcha(session, timeout: float = TIMEOUT) -> dict:
|
||||
"""取滑块图,返回 ``{shade, origin, cutout, y}``(y 为拼图块 top)。"""
|
||||
cv2, _ = _cv2_np()
|
||||
data = session.get(CAPTCHA_GET_URL, timeout=timeout).json()
|
||||
result = data.get("result") or {}
|
||||
return {
|
||||
"shade": _crop_view(_b64_to_img(result.get("shadeImage"), cv2.IMREAD_COLOR)),
|
||||
"origin": _crop_view(_b64_to_img(result.get("originImage"), cv2.IMREAD_COLOR)),
|
||||
"cutout": _b64_to_img(result.get("cutoutImage"), cv2.IMREAD_UNCHANGED),
|
||||
"y": int(result.get("y") or 0),
|
||||
}
|
||||
|
||||
|
||||
def locate_by_diff(shade, origin) -> Tuple[Optional[int], str]:
|
||||
"""diff 法:两图差异最大连通域的左边界 = 缺口 x。"""
|
||||
cv2, np = _cv2_np()
|
||||
if shade is None or origin is None or shade.shape != origin.shape:
|
||||
return None, "图片缺失或尺寸不一致"
|
||||
diff = cv2.absdiff(shade, origin).max(axis=2)
|
||||
mask = (diff > 30).astype(np.uint8) * 255
|
||||
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8))
|
||||
count, _, stats, _ = cv2.connectedComponentsWithStats(mask)
|
||||
if count <= 1:
|
||||
return None, "无差异区域"
|
||||
best = max(range(1, count), key=lambda i: stats[i, cv2.CC_STAT_AREA])
|
||||
area = int(stats[best, cv2.CC_STAT_AREA])
|
||||
x = int(stats[best, cv2.CC_STAT_LEFT])
|
||||
if area < 300 or area > 12000: # 缺口约 55x55(面积 ~3000)
|
||||
return None, f"差异区域面积异常({area})"
|
||||
return x, f"diff(area={area})"
|
||||
|
||||
|
||||
def match_slider_dual(bg_img, cutout) -> Optional[int]:
|
||||
"""模板匹配缺口(Canny + TM_CCOEFF_NORMED + 白区加权),返回水平距离 px。"""
|
||||
cv2, np = _cv2_np()
|
||||
if bg_img is None or cutout is None:
|
||||
return None
|
||||
bg_h, bg_w = bg_img.shape[:2]
|
||||
x_offset = 0
|
||||
if len(cutout.shape) == 3 and cutout.shape[2] == 4:
|
||||
alpha = cutout[:, :, 3]
|
||||
rgb = cutout[:, :, :3]
|
||||
ys, xs = np.where(alpha > 0)
|
||||
if len(ys) > 0:
|
||||
rgb = rgb[np.min(ys):np.max(ys) + 1, np.min(xs):np.max(xs) + 1]
|
||||
x_offset = np.min(xs)
|
||||
else:
|
||||
rgb = cutout[:, :, :3] if len(cutout.shape) == 3 else cutout
|
||||
|
||||
s_h, s_w = rgb.shape[:2]
|
||||
if s_h <= 0 or s_w <= 0 or s_w >= bg_w or s_h >= bg_h:
|
||||
return None
|
||||
gray_bg = cv2.GaussianBlur(cv2.cvtColor(bg_img, cv2.COLOR_BGR2GRAY), (3, 3), 0)
|
||||
gray_slider = cv2.GaussianBlur(cv2.cvtColor(rgb, cv2.COLOR_BGR2GRAY), (3, 3), 0)
|
||||
result = cv2.matchTemplate(cv2.Canny(gray_bg, 50, 150),
|
||||
cv2.Canny(gray_slider, 50, 150),
|
||||
cv2.TM_CCOEFF_NORMED)
|
||||
|
||||
candidates = []
|
||||
temp = result.copy()
|
||||
for _ in range(6):
|
||||
_, max_val, _, max_loc = cv2.minMaxLoc(temp)
|
||||
if max_val < 0.03:
|
||||
break
|
||||
candidates.append((max_val, max_loc))
|
||||
y0 = max(0, max_loc[1] - s_h // 2)
|
||||
y1 = min(temp.shape[0], max_loc[1] + s_h // 2)
|
||||
x0 = max(0, max_loc[0] - s_w // 2)
|
||||
x1 = min(temp.shape[1], max_loc[0] + s_w // 2)
|
||||
temp[y0:y1, x0:x1] = -2.0
|
||||
if not candidates:
|
||||
return None
|
||||
|
||||
right_limit = bg_w - s_w - max(15, int(bg_w * 0.06))
|
||||
|
||||
def _whiteness(x, y, w, h):
|
||||
roi = bg_img[y:y + h, x:x + w]
|
||||
if roi.size == 0:
|
||||
return 0.0
|
||||
return float(np.all(roi > 200, axis=2).mean())
|
||||
|
||||
scored = [(val + 0.5 * _whiteness(loc[0], loc[1], s_w, s_h), loc)
|
||||
for val, loc in candidates if s_w < loc[0] <= right_limit]
|
||||
best_loc = (max(scored, key=lambda t: t[0])[1] if scored else candidates[0][1])
|
||||
distance = max(0, best_loc[0] - x_offset)
|
||||
return min(distance, bg_w - s_w)
|
||||
|
||||
|
||||
def solve_distance(cap: dict) -> Tuple[Optional[int], str]:
|
||||
"""定位缺口并给出应提交的 x(diff 与模板互验,分歧大则换图)。"""
|
||||
cutout = cap.get("cutout")
|
||||
shade = cap.get("shade")
|
||||
s_w = cutout.shape[1] if cutout is not None else 55
|
||||
view_w = shade.shape[1] if shade is not None else VIEW_W
|
||||
x_diff, info = locate_by_diff(cap.get("shade"), cap.get("origin"))
|
||||
x_tpl = match_slider_dual(cap.get("shade"), cutout)
|
||||
|
||||
x, how = None, "无法定位"
|
||||
if x_diff is not None and x_tpl is not None and abs(x_diff - x_tpl) <= 12:
|
||||
x, how = x_diff, "diff+tpl 一致"
|
||||
elif x_diff is not None:
|
||||
x, how = x_diff, "仅 diff(与模板分歧)"
|
||||
elif x_tpl is not None:
|
||||
x, how = x_tpl, "仅模板"
|
||||
if x is None:
|
||||
return None, how
|
||||
if x <= s_w or x > view_w - s_w: # 贴边缺口不可信
|
||||
return None, f"缺口位置越界({x}, 图宽{view_w})"
|
||||
return x, how
|
||||
|
||||
|
||||
def check_slider(session, x: int, y: int, timeout: float = TIMEOUT) -> bool:
|
||||
"""提交滑块校验。"""
|
||||
resp = session.post(CAPTCHA_CHECK_URL,
|
||||
params={"x": int(round(x)), "y": int(y)}, timeout=timeout)
|
||||
try:
|
||||
return bool(resp.json())
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def submit_login(session, username: str, password: str, x: int, y: int,
|
||||
timeout: float = TIMEOUT) -> Tuple[bool, str]:
|
||||
"""提交登录,返回 ``(ok, message)``;``state == "0"`` 视为失败。"""
|
||||
form = {
|
||||
"MENU_TYPE": "classic",
|
||||
"sysCode": "RedseaP",
|
||||
"j_username": username,
|
||||
"j_password": aes_encrypt_password(password),
|
||||
"x": int(round(x)),
|
||||
"y": int(y),
|
||||
}
|
||||
resp = session.post(LOGIN_POST_URL, data=form,
|
||||
headers={"Csrf-Token": CSRF_TOKEN}, timeout=timeout)
|
||||
try:
|
||||
result = resp.json()
|
||||
except ValueError:
|
||||
return False, f"登录响应非 JSON(HTTP {resp.status_code})"
|
||||
if str(result.get("state")) == "0":
|
||||
return False, str(result.get("meg") or "登录失败")
|
||||
return True, "登录成功"
|
||||
|
||||
|
||||
# ==================== 对外入口 ====================
|
||||
|
||||
def login(username: str = "", password: str = "", *, cookie_path: str = "",
|
||||
save: bool = True, log: Optional[LOGGER] = None) -> str:
|
||||
"""完整接口登录,成功返回 cookies 文件路径。
|
||||
|
||||
Args:
|
||||
username/password: 缺省读 ``hr_login_username`` / ``hr_login_password``
|
||||
cookie_path: 落盘路径(默认 :func:`hr_sdk.config.cookies_file`)
|
||||
save: 是否落盘(``False`` 时只验证能登录)
|
||||
log: 日志回调
|
||||
|
||||
Raises:
|
||||
ConfigError: 账号密码缺失
|
||||
AuthError: 登录失败(账号密码错 / 滑块连续不过)
|
||||
"""
|
||||
username = (username or os.getenv("hr_login_username", "")).strip()
|
||||
password = password or os.getenv("hr_login_password", "")
|
||||
if not username or not password:
|
||||
raise ConfigError("缺少登录配置:hr_login_username / hr_login_password")
|
||||
log = log or (lambda msg: None)
|
||||
|
||||
for rnd in range(1, LOGIN_ROUND_MAX + 1):
|
||||
try:
|
||||
session = new_session()
|
||||
except requests.RequestException as exc:
|
||||
log(f"[WARN] 建立会话失败({rnd}/{LOGIN_ROUND_MAX}):{exc}")
|
||||
time.sleep(1)
|
||||
continue
|
||||
|
||||
for attempt in range(1, RETRY_MAX + 1):
|
||||
try:
|
||||
cap = get_captcha(session)
|
||||
except (requests.RequestException, ValueError) as exc:
|
||||
log(f"[WARN] 取滑块图失败:{exc}")
|
||||
time.sleep(1)
|
||||
continue
|
||||
shade, y = cap.get("shade"), cap.get("y", 0)
|
||||
if shade is None or not (0 <= y <= shade.shape[0] - 55):
|
||||
time.sleep(0.5)
|
||||
continue
|
||||
|
||||
x, how = solve_distance(cap)
|
||||
if x is None:
|
||||
log(f"[INFO] 缺口定位失败({how}),换图")
|
||||
time.sleep(random.uniform(0.3, 0.8))
|
||||
continue
|
||||
|
||||
if not check_slider(session, x, y):
|
||||
log(f"[INFO] 滑块校验未通过(x={x}, y={y}, {how}),换图")
|
||||
time.sleep(random.uniform(0.5, 1.2))
|
||||
continue
|
||||
|
||||
ok, message = submit_login(session, username, password, x, y)
|
||||
if not ok:
|
||||
raise AuthError(f"登录失败:{message}") # 账号密码类错误,重试无意义
|
||||
path = save_cookies(session, cookie_path) if save else (cookie_path
|
||||
or cookies_file())
|
||||
log(f"[INFO] HR 登录成功,cookies 已保存:{path}")
|
||||
return path
|
||||
time.sleep(1)
|
||||
raise AuthError(f"登录失败:{LOGIN_ROUND_MAX} 轮 × {RETRY_MAX} 次滑块均未通过")
|
||||
|
||||
|
||||
def ensure_login(username: str = "", password: str = "", *, force: bool = False,
|
||||
cookie_path: str = "", log: Optional[LOGGER] = None) -> dict:
|
||||
"""确保存在有效登录态(优先复用 cookies),返回外壳兼容的 dict。
|
||||
|
||||
Returns:
|
||||
``{"success": bool, "cookie_path": str, "message": str, "relogin": bool}``
|
||||
"""
|
||||
log = log or (lambda msg: None)
|
||||
path = cookie_path or cookies_file()
|
||||
if not force and session_alive(cookie_path=path):
|
||||
log("[INFO] 复用缓存登录态")
|
||||
return {"success": True, "cookie_path": path, "message": "复用缓存登录态",
|
||||
"relogin": False}
|
||||
try:
|
||||
saved = login(username, password, cookie_path=path, log=log)
|
||||
except (AuthError, ConfigError) as exc:
|
||||
return {"success": False, "cookie_path": path, "message": str(exc),
|
||||
"relogin": False}
|
||||
return {"success": True, "cookie_path": saved, "message": "登录成功", "relogin": True}
|
||||
|
||||
|
||||
__all__ = [
|
||||
"AES_KEY",
|
||||
"CAPTCHA_CHECK_URL",
|
||||
"CAPTCHA_GET_URL",
|
||||
"CSRF_TOKEN",
|
||||
"CUR_USER_URL",
|
||||
"LOGIN_POST_URL",
|
||||
"LOGIN_ROUND_MAX",
|
||||
"LOGIN_URL",
|
||||
"RETRY_MAX",
|
||||
"TIMEOUT",
|
||||
"VIEW_H",
|
||||
"VIEW_W",
|
||||
"aes_encrypt_password",
|
||||
"check_slider",
|
||||
"ensure_login",
|
||||
"get_captcha",
|
||||
"load_cookies",
|
||||
"locate_by_diff",
|
||||
"login",
|
||||
"match_slider_dual",
|
||||
"new_session",
|
||||
"save_cookies",
|
||||
"session_alive",
|
||||
"solve_distance",
|
||||
"submit_login",
|
||||
]
|
||||
@@ -0,0 +1,186 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""HR 接口通用客户端:请求、JSON 校验、分页、下载、上传。
|
||||
|
||||
只做「机制」:不内置任何业务 URL;各接口模块(roster/ledger/org/...)传参调用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Callable, Dict, List, Optional, Tuple
|
||||
|
||||
from .config import DEFAULT_TIMEOUT, DOWNLOAD_TIMEOUT, MAX_ATTEMPTS, MAX_PAGES, XHR_HEADERS
|
||||
from .errors import ApiError, ConfigError, HrError, SessionExpiredError
|
||||
from .session import SessionLike, looks_like_login_page
|
||||
|
||||
LOGGER = Callable[[str], None]
|
||||
|
||||
|
||||
class HrClient:
|
||||
"""借来的会话 + 通用请求能力。
|
||||
|
||||
Args:
|
||||
session: 宿主注入的会话(``ctx.get_session("hr")``)或 :func:`session_from_cookies` 的产物
|
||||
timeout: 普通请求超时(秒)
|
||||
retries: 重试次数(含首次,默认 3);登录态失效不重试
|
||||
log: 日志回调(默认静默)
|
||||
"""
|
||||
|
||||
def __init__(self, session: SessionLike, *, timeout: Optional[float] = None,
|
||||
retries: Optional[int] = None, log: Optional[LOGGER] = None) -> None:
|
||||
if session is None:
|
||||
raise ConfigError("会话不能为空:插件里请用 ctx.get_session('hr')")
|
||||
self.session = session
|
||||
self.timeout = float(timeout if timeout is not None else DEFAULT_TIMEOUT)
|
||||
self.retries = max(1, int(retries if retries is not None else MAX_ATTEMPTS))
|
||||
self.log: LOGGER = log or (lambda msg: None)
|
||||
|
||||
# ---------------- 底层 ----------------
|
||||
def get(self, url: str, *, params: Optional[dict] = None,
|
||||
timeout: Optional[float] = None, headers: Optional[dict] = None):
|
||||
return self.session.get(url, params=params, headers=headers or XHR_HEADERS,
|
||||
timeout=timeout or self.timeout)
|
||||
|
||||
def post(self, url: str, *, data: Optional[dict] = None, params: Optional[dict] = None,
|
||||
timeout: Optional[float] = None, headers: Optional[dict] = None):
|
||||
return self.session.post(url, data=data if data is not None else {}, params=params,
|
||||
headers=headers or XHR_HEADERS,
|
||||
timeout=timeout or self.timeout)
|
||||
|
||||
def post_files(self, url: str, *, files: dict, data: Optional[dict] = None,
|
||||
timeout: Optional[float] = None):
|
||||
"""multipart 上传。
|
||||
|
||||
宿主注入的会话通常带 ``Content-Type: application/x-www-form-urlencoded``,
|
||||
会让 requests 不再生成 multipart 边界、被服务端拒绝;上传前临时清除、随后恢复。
|
||||
"""
|
||||
saved_type = self.session.headers.pop("Content-Type", None) \
|
||||
if hasattr(self.session.headers, "pop") else None
|
||||
headers = {"X-Requested-With": "XMLHttpRequest"}
|
||||
try:
|
||||
return self.session.post(url, files=files, data=data or {}, headers=headers,
|
||||
timeout=timeout or self.timeout)
|
||||
finally:
|
||||
if saved_type is not None:
|
||||
self.session.headers["Content-Type"] = saved_type
|
||||
|
||||
@staticmethod
|
||||
def as_json(response, label: str = "") -> dict:
|
||||
"""响应 → dict;返回登录页/HTML 视为登录态失效。"""
|
||||
text = (response.text or "").strip()
|
||||
if looks_like_login_page(text):
|
||||
raise SessionExpiredError(
|
||||
f"{label or '接口'}返回非 JSON(登录态可能已失效):{text[:120]}")
|
||||
try:
|
||||
data = response.json()
|
||||
except ValueError:
|
||||
raise ApiError(f"{label or '接口'}响应不是 JSON:{text[:200]}") from None
|
||||
if not isinstance(data, dict):
|
||||
raise ApiError(f"{label or '接口'}响应结构异常:{text[:200]}")
|
||||
return data
|
||||
|
||||
def request_json(self, method: str, url: str, *, params: Optional[dict] = None,
|
||||
data: Optional[dict] = None, timeout: Optional[float] = None,
|
||||
label: str = "") -> dict:
|
||||
"""带重试的 JSON 请求;登录态失效/业务错误不重试。"""
|
||||
last: Optional[BaseException] = None
|
||||
for attempt in range(1, self.retries + 1):
|
||||
try:
|
||||
if method.upper() == "GET":
|
||||
resp = self.get(url, params=params, timeout=timeout)
|
||||
else:
|
||||
resp = self.post(url, data=data, params=params, timeout=timeout)
|
||||
if resp.status_code >= 500:
|
||||
raise HrError(f"{label or '接口'}服务端 {resp.status_code}")
|
||||
return self.as_json(resp, label)
|
||||
except (SessionExpiredError, ApiError, ConfigError):
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001 - 网络抖动重试
|
||||
last = exc
|
||||
if attempt >= self.retries:
|
||||
break
|
||||
delay = 2.0 * attempt
|
||||
self.log(f"[WARN] {label or '接口'}第 {attempt} 次失败:{exc};"
|
||||
f"{delay:.0f}s 后重试")
|
||||
time.sleep(delay)
|
||||
raise HrError(f"{label or '接口'}请求失败(重试 {self.retries} 次):{last}")
|
||||
|
||||
# ---------------- 业务信封 ----------------
|
||||
#: 服务端把「登录态失效」放在 state != 1 的 meg 里,需要单独识别
|
||||
SESSION_HINTS = ("会话过期", "重新登录", "登录超时", "未登录", "登录失效")
|
||||
#: state 本身就是会话失效的取值(HTTP 200 也会出现)
|
||||
SESSION_STATES = ("nosession", "no_session", "sessiontimeout", "session_timeout")
|
||||
|
||||
def check_state(self, data: dict, label: str = "") -> dict:
|
||||
"""校验 ``state == 1``(HR 老接口信封);会话类错误抛登录态失效。"""
|
||||
state = str(data.get("state") or "").strip()
|
||||
if state == "1":
|
||||
return data
|
||||
msg = str(data.get("meg") or data.get("des") or data)
|
||||
if state.lower() in self.SESSION_STATES \
|
||||
or any(hint in msg for hint in self.SESSION_HINTS):
|
||||
raise SessionExpiredError(f"{label or '接口'}登录态失效:{msg}")
|
||||
raise ApiError(f"{label or '接口'}返回错误:{msg}",
|
||||
code=state, payload=data)
|
||||
|
||||
# ---------------- 分页 ----------------
|
||||
def paginate(self, fetch_page: Callable[[int, int], Tuple[List[dict], bool]], *,
|
||||
page_size: int = 200, max_pages: int = MAX_PAGES,
|
||||
sleep: float = 0.2) -> List[dict]:
|
||||
"""通用分页:``fetch_page(page_no, page_size) -> (rows, has_more)``。"""
|
||||
rows: List[dict] = []
|
||||
for page_no in range(1, max_pages + 1):
|
||||
page_rows, has_more = fetch_page(page_no, page_size)
|
||||
rows.extend(page_rows or [])
|
||||
if not has_more or not page_rows:
|
||||
break
|
||||
if sleep:
|
||||
time.sleep(sleep)
|
||||
return rows
|
||||
|
||||
def paginate_json(self, url: str, *, data_builder: Callable[[int, int], dict],
|
||||
page_size: int = 200, page_key: str = "rows",
|
||||
total_key: str = "total", label: str = "") -> List[dict]:
|
||||
"""常见 HR 列表接口分页(``rows`` + ``total`` 形态)。"""
|
||||
|
||||
def _fetch(page_no: int, size: int):
|
||||
data = self.request_json("POST", url, data=data_builder(page_no, size),
|
||||
label=label)
|
||||
rows = data.get(page_key) or []
|
||||
total = int(data.get(total_key) or 0)
|
||||
return rows, bool(total and page_no * size < total)
|
||||
|
||||
return self.paginate(_fetch, page_size=page_size)
|
||||
|
||||
# ---------------- 文件 ----------------
|
||||
def download(self, url: str, *, save_dir: str = "", filename: str = "",
|
||||
timeout: Optional[float] = None) -> str:
|
||||
"""下载到本地;``filename`` 为空时用 URL 末段。返回绝对路径。"""
|
||||
resp = self.session.get(url, timeout=timeout or DOWNLOAD_TIMEOUT)
|
||||
if resp.status_code != 200 or not resp.content:
|
||||
raise HrError(f"下载失败:HTTP {resp.status_code},{len(resp.content or b'')} 字节")
|
||||
name = filename or os.path.basename(url.split("?", 1)[0]) or "download.bin"
|
||||
target_dir = save_dir or os.getcwd()
|
||||
os.makedirs(target_dir, exist_ok=True)
|
||||
path = os.path.abspath(os.path.join(target_dir, name))
|
||||
with open(path, "wb") as fp:
|
||||
fp.write(resp.content)
|
||||
self.log(f"[INFO] 已下载:{path}({len(resp.content)} 字节)")
|
||||
return path
|
||||
|
||||
def upload(self, url: str, *, file_path: str, field: str = "file",
|
||||
data: Optional[Dict[str, Any]] = None, label: str = "上传") -> dict:
|
||||
"""multipart 上传并返回 JSON(字段名默认 ``file``)。"""
|
||||
if not file_path or not os.path.exists(file_path):
|
||||
raise ConfigError(f"文件不存在:{file_path}")
|
||||
with open(file_path, "rb") as fp:
|
||||
content = fp.read()
|
||||
files = {field: (os.path.basename(file_path), content,
|
||||
"application/octet-stream")}
|
||||
resp = self.post_files(url, files=files, data={k: str(v) for k, v in
|
||||
(data or {}).items()})
|
||||
return self.as_json(resp, label)
|
||||
|
||||
|
||||
__all__ = ["HrClient"]
|
||||
@@ -0,0 +1,162 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""HR(RedseaPlatform)接口事实常量:域名、bridge、WS 主题、公共查询入参。
|
||||
|
||||
设计原则:**这里只放「服务端协议事实」**——域名/路径/主题/公共参数键;
|
||||
业务语义(模板列、异常判定、店长分组、文案)一律留在插件。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import Dict, Optional
|
||||
|
||||
# ==================== 域名与协议 ====================
|
||||
#: HR 站点根(可用环境变量 HR_BASE_URL 覆盖,便于换测试环境)
|
||||
HR_BASE_URL = (os.getenv("HR_BASE_URL") or "https://hr.37du.co").rstrip("/")
|
||||
REDSEA = f"{HR_BASE_URL}/RedseaPlatform"
|
||||
|
||||
#: 会话注册(未注册时 WS 握手 500)
|
||||
BRIDGE_URL = f"{REDSEA}/ws/bridge"
|
||||
#: 异步导出推送主题
|
||||
WS_EXPORT_THEME = "HR_DEFINED_HMC_EXPORT"
|
||||
WS_SERVICE_URL = f"wss://{HR_BASE_URL.split('//')[-1]}/RedseaPlatform/ws/service?theme={WS_EXPORT_THEME}"
|
||||
|
||||
#: 异步导出请求头(服务端按 XHR 处理)
|
||||
XHR_HEADERS = {"X-Requested-With": "XMLHttpRequest"}
|
||||
USER_AGENT = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
|
||||
|
||||
#: 自定义导出模板解析(页面「自定义导出」弹窗同款接口)
|
||||
TEMPLATE_LIST_URL = f"{REDSEA}/redmagicapi/rf_pt_users_export_define_select/getExecuteResult.mc"
|
||||
TEMPLATE_DETAIL_URL = f"{REDSEA}/ptUsersExportDefine/getPtusersexportdefine.mc"
|
||||
|
||||
# ==================== 默认值与重试 ====================
|
||||
DEFAULT_TIMEOUT = 30.0 # 普通请求超时(秒)
|
||||
DOWNLOAD_TIMEOUT = 120.0 # 文件下载超时(秒)
|
||||
EXPORT_TIMEOUT_SECONDS = 300 # 异步导出等待上限(秒)
|
||||
MAX_ATTEMPTS = 3 # 项目级重试次数(含首次)
|
||||
PAGE_MAX_SIZE = 500 # 分页单页上限(组织维护等接口)
|
||||
MAX_PAGES = 500 # 分页保护上限
|
||||
|
||||
# ==================== 会话文件 ====================
|
||||
#: 壳子/影刀登录后写入的 cookies(按账号隔离时由宿主注入 HR_COOKIES_FILE)
|
||||
COOKIES_FILE = (os.getenv("HR_COOKIES_FILE") or "").strip()
|
||||
|
||||
|
||||
def app_data_dir() -> str:
|
||||
"""运行数据根:``%LOCALAPPDATA%\\37duAutomation``。"""
|
||||
base = os.getenv("LOCALAPPDATA") or os.getenv("APPDATA") or os.path.expanduser("~")
|
||||
return os.path.join(base, "37duAutomation")
|
||||
|
||||
|
||||
def cookies_file(account: str = "") -> str:
|
||||
"""HR cookies 文件路径。
|
||||
|
||||
与壳子一致按账号隔离:``account`` 参数或环境变量 ``PLATFORM_ACCOUNT`` 存在时
|
||||
落到 ``.sessions/<账号>/hr_cookies.json``,否则 ``.sessions/hr_cookies.json``;
|
||||
``HR_COOKIES_FILE`` 显式指定时优先。
|
||||
"""
|
||||
if COOKIES_FILE:
|
||||
return COOKIES_FILE
|
||||
acc = str(account or os.getenv("PLATFORM_ACCOUNT", "") or "").strip()
|
||||
sessions = os.path.join(app_data_dir(), ".sessions")
|
||||
if acc:
|
||||
sessions = os.path.join(sessions, acc)
|
||||
return os.path.join(sessions, "hr_cookies.json")
|
||||
|
||||
|
||||
# ==================== 台账公共查询入参 ====================
|
||||
#: 抓包得到、所有台账/Roster 接口通用的入参(与页面默认行为一致)
|
||||
_COMMON_BASE_PARAMS: Dict[str, object] = {
|
||||
"useSealTreeData": "0",
|
||||
"treePermitType": "permit",
|
||||
"cancelNodeClick": "1",
|
||||
"clickFlag": "true",
|
||||
"in_use": "1",
|
||||
"commonQuery": "",
|
||||
"newCondition": "",
|
||||
"urlConditions": "",
|
||||
"exportConfig": "",
|
||||
"includeChildrenSetting": "",
|
||||
"struTreeCode": "cq37du",
|
||||
"djStruTreeCode": "",
|
||||
"djStruId": "",
|
||||
"djOrgName": "",
|
||||
"struId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"belongUnitStruId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"rootId": "cq37du",
|
||||
"isVirtual": "0",
|
||||
"currentUserRootId": "cq37du",
|
||||
"currentUserId": "178b0efa-8a65-11f1-a7d9-000c296f9469",
|
||||
"currentRoleIds": "POST_SYS_ADMIN,renshi",
|
||||
"currentStaffId": "1342173e-36cf-4160-8826-6b17d7d084a4",
|
||||
"baseHrefPath": "http:hr.37du.co:80RedseaPlatform",
|
||||
"qrCodeUrl": "jspresumepage-01.jsp",
|
||||
"orgName": "集团",
|
||||
"belongUnitOrgName": "集团",
|
||||
"throughParam": "",
|
||||
"start": "0",
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": "1",
|
||||
"pageSize": "15",
|
||||
"dataIds": "",
|
||||
"hideCols": "",
|
||||
}
|
||||
|
||||
|
||||
def base_params(menu_name: str, table_id: str, roster_id: str,
|
||||
user: Optional[Dict[str, str]] = None,
|
||||
**overrides) -> Dict[str, str]:
|
||||
"""构造台账接口的公共入参(各台账只差 menuName / tableId / rosterId)。
|
||||
|
||||
Args:
|
||||
menu_name: 页面菜单名,如 ``员工花名册``
|
||||
table_id: 表 id,如 ``assemble-hr_staff_base``
|
||||
roster_id: 台账 id(UUID)
|
||||
user: 可选,``{"userId": ..., "staffId": ..., "roleIds": ...}`` 覆盖抓包默认身份
|
||||
(换账号登录后若导出失败,优先怀疑这三个值)
|
||||
overrides: 其余覆盖项(如 ``baseHrefPath``)
|
||||
|
||||
Returns:
|
||||
全字符串入参 dict(可直接 POST)
|
||||
"""
|
||||
params: Dict[str, str] = {k: str(v) for k, v in _COMMON_BASE_PARAMS.items()}
|
||||
params.update({
|
||||
"menuName": str(menu_name),
|
||||
"tableId": str(table_id),
|
||||
"rosterId": str(roster_id),
|
||||
})
|
||||
if user:
|
||||
if user.get("userId"):
|
||||
params["currentUserId"] = str(user["userId"])
|
||||
if user.get("staffId"):
|
||||
params["currentStaffId"] = str(user["staffId"])
|
||||
if user.get("roleIds"):
|
||||
params["currentRoleIds"] = str(user["roleIds"])
|
||||
for key, value in overrides.items():
|
||||
params[key] = str(value)
|
||||
return params
|
||||
|
||||
|
||||
__all__ = [
|
||||
"BRIDGE_URL",
|
||||
"COOKIES_FILE",
|
||||
"DEFAULT_TIMEOUT",
|
||||
"DOWNLOAD_TIMEOUT",
|
||||
"EXPORT_TIMEOUT_SECONDS",
|
||||
"HR_BASE_URL",
|
||||
"MAX_ATTEMPTS",
|
||||
"MAX_PAGES",
|
||||
"PAGE_MAX_SIZE",
|
||||
"REDSEA",
|
||||
"TEMPLATE_DETAIL_URL",
|
||||
"TEMPLATE_LIST_URL",
|
||||
"USER_AGENT",
|
||||
"WS_EXPORT_THEME",
|
||||
"WS_SERVICE_URL",
|
||||
"XHR_HEADERS",
|
||||
"app_data_dir",
|
||||
"base_params",
|
||||
"cookies_file",
|
||||
]
|
||||
@@ -0,0 +1,81 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""合同台账接口(生效中 / 待生效 两个台账)。
|
||||
|
||||
用法::
|
||||
|
||||
from hr_sdk import HrClient, contract
|
||||
|
||||
client = HrClient(ctx.get_session("hr"))
|
||||
for tag in contract.ROSTERS:
|
||||
contract.export(client, tag, template="合同台账导出",
|
||||
output=out / f"合同台账_{tag}.xlsx")
|
||||
|
||||
合并两个台账、加「合同状态」列、字段清洗都属业务,留在插件。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import Optional
|
||||
|
||||
from . import export
|
||||
from .config import REDSEA, app_data_dir, base_params
|
||||
from .errors import ConfigError
|
||||
|
||||
CONTRACT_TABLE_ID = "assemble-hr_staff_contract"
|
||||
MENU_NAME = "合同台账"
|
||||
|
||||
#: 生效中 / 待生效 两个台账的 rosterId
|
||||
ROSTERS = {
|
||||
"生效中": "614ffe05-b4f1-11ea-b588-14187743d052",
|
||||
"待生效": "8910a95d-b484-11ea-b588-14187743d052",
|
||||
}
|
||||
|
||||
|
||||
def page_url(roster_id: str) -> str:
|
||||
return f"{REDSEA}/hrRoster/{roster_id}/getCustomCommonList.mc"
|
||||
|
||||
|
||||
def export_url(roster_id: str) -> str:
|
||||
return f"{REDSEA}/hrRoster/{roster_id}/exportCommonListData.mc"
|
||||
|
||||
|
||||
def export(client, tag: str = "生效中", *, template: str = "", filters: str = "",
|
||||
output: str = "", user: Optional[dict] = None,
|
||||
timeout: Optional[int] = None) -> str:
|
||||
"""导出指定合同台账,返回文件路径。
|
||||
|
||||
Args:
|
||||
tag: ``生效中`` / ``待生效``(见 :data:`ROSTERS`)
|
||||
template: 自定义导出模板名(走动态解析)
|
||||
filters: 直接给字段串(``template`` 留空时必填)
|
||||
output: 输出路径(默认 ``<数据根>/output/合同台账_<tag>.xlsx``)
|
||||
user: 覆盖抓包默认身份
|
||||
|
||||
Raises:
|
||||
ConfigError: 未知 tag / 模板与字段串都没给或解析失败
|
||||
"""
|
||||
roster_id = ROSTERS.get(tag)
|
||||
if not roster_id:
|
||||
raise ConfigError(f"未知合同台账「{tag}」,可选:{' / '.join(ROSTERS)}")
|
||||
|
||||
resolved = filters
|
||||
if not resolved:
|
||||
if not template:
|
||||
raise ConfigError("请传 template(模板名)或 filters(字段串)")
|
||||
resolved = export.resolve_template(client, template, roster_id) or ""
|
||||
if not resolved:
|
||||
raise ConfigError(f"未能解析模板「{template}」的导出列,请检查模板名或显式传 filters")
|
||||
|
||||
target = os.path.abspath(output or os.path.join(app_data_dir(), "output",
|
||||
f"合同台账_{tag}.xlsx"))
|
||||
params = export.build_params(base_params(MENU_NAME, CONTRACT_TABLE_ID, roster_id,
|
||||
user=user),
|
||||
template=template, filters=resolved)
|
||||
client.log(f"[INFO] 合同台账导出({tag})")
|
||||
return export.export_table(client, page_url=page_url(roster_id),
|
||||
export_url=export_url(roster_id),
|
||||
params=params, output_path=target, timeout=timeout)
|
||||
|
||||
|
||||
__all__ = ["CONTRACT_TABLE_ID", "MENU_NAME", "ROSTERS", "export", "export_url", "page_url"]
|
||||
@@ -0,0 +1,51 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""SDK 异常体系(契约见《SDK 挂载机制设计》§6.5)。
|
||||
|
||||
一律抛异常,不 ``sys.exit``、不 ``KeyboardInterrupt``;异常消息不含 cookie / 密码。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class HrError(Exception):
|
||||
"""SDK 所有异常的基类。"""
|
||||
|
||||
|
||||
class ConfigError(HrError):
|
||||
"""配置/入参非法(缺 cookie、路径为空、模板解析失败等)。"""
|
||||
|
||||
|
||||
class SessionExpiredError(HrError):
|
||||
"""登录态缺失或失效(接口返回登录页/HTML 而非 JSON,或 ws/bridge 注册失败)。"""
|
||||
|
||||
|
||||
class AuthError(HrError):
|
||||
"""登录流程失败(账号密码错误、验证码不过等)。"""
|
||||
|
||||
|
||||
class ApiError(HrError):
|
||||
"""HR 接口返回业务错误(state != 1 / 明确错误码)。"""
|
||||
|
||||
def __init__(self, message: str, code: str = "", payload=None) -> None:
|
||||
super().__init__(message)
|
||||
self.code = str(code or "")
|
||||
self.payload = payload
|
||||
|
||||
|
||||
class ExportTimeoutError(HrError):
|
||||
"""异步导出等待超时(服务端长时间不推送 --end--)。"""
|
||||
|
||||
|
||||
class CancelledError(HrError):
|
||||
"""调用方通过 ``should_cancel()`` 请求中止。"""
|
||||
|
||||
|
||||
__all__ = [
|
||||
"ApiError",
|
||||
"AuthError",
|
||||
"CancelledError",
|
||||
"ConfigError",
|
||||
"ExportTimeoutError",
|
||||
"HrError",
|
||||
"SessionExpiredError",
|
||||
]
|
||||
@@ -0,0 +1,219 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""台账「异步自定义导出」机制(服务端生成 Excel → WS 推送 → 下载)。
|
||||
|
||||
所有台账(花名册 / 合同 / 预入职 / 调动 …)共用这一套:
|
||||
1. 访问台账页 + ``ws/bridge`` 注册会话(未注册时 WS 握手 500);
|
||||
2. WS 订阅 ``HR_DEFINED_HMC_EXPORT``;
|
||||
3. POST ``exportCommonListData.mc`` 提交任务(``commonQuery`` 为加密筛选条件);
|
||||
4. 收 ``--end--|文件地址`` 后下载到本地。
|
||||
|
||||
业务模块只提供「台账 id + 模板 + 条件」,不重复实现本文件。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from typing import Callable, Dict, List, Optional, Sequence
|
||||
|
||||
import websocket
|
||||
|
||||
from .config import (BRIDGE_URL, EXPORT_TIMEOUT_SECONDS, MAX_ATTEMPTS, TEMPLATE_DETAIL_URL,
|
||||
TEMPLATE_LIST_URL, USER_AGENT, WS_EXPORT_THEME, WS_SERVICE_URL, XHR_HEADERS)
|
||||
from .errors import ApiError, ConfigError, ExportTimeoutError, HrError, SessionExpiredError
|
||||
from .query import encode
|
||||
|
||||
LOGGER = Callable[[str], None]
|
||||
|
||||
_PAGE_QUERY = {"clickFlag": "true", "treePermitType": "permit", "useSealTreeData": "0"}
|
||||
|
||||
|
||||
# ==================== 会话绑定 ====================
|
||||
|
||||
def bind_session(client, page_url: str) -> None:
|
||||
"""访问台账页并调用 ``ws/bridge`` 把 HTTP 会话注册到 WS 容器。
|
||||
|
||||
Raises:
|
||||
SessionExpiredError: 登录态失效(bridge 未返回成功)
|
||||
"""
|
||||
client.get(page_url, params=dict(_PAGE_QUERY), timeout=client.timeout)
|
||||
resp = client.post(BRIDGE_URL, data={}, timeout=10)
|
||||
text = (resp.text or "").strip()
|
||||
if "成功" not in text and text != "1":
|
||||
raise SessionExpiredError(
|
||||
f"ws/bridge 会话注册失败(登录态可能已失效):{text[:100]}")
|
||||
client.log("[INFO] ws/bridge 会话已注册")
|
||||
|
||||
|
||||
# ==================== 模板解析 ====================
|
||||
|
||||
def resolve_template(client, template_name: str, roster_id: str,
|
||||
user_id: str = "") -> Optional[str]:
|
||||
"""按模板名动态解析 ``exportFilters`` 字段串(列表 → 详情 → exportField)。
|
||||
|
||||
与页面「自定义导出」弹窗同款接口。解析失败返回 ``None``(调用方用自己的 filters)。
|
||||
"""
|
||||
if not template_name:
|
||||
return None
|
||||
try:
|
||||
resp = client.post(TEMPLATE_LIST_URL)
|
||||
data = client.as_json(resp, "导出模板列表")
|
||||
templates = data.get("jsonList") or []
|
||||
# 模板列表是全局的,同名模板可能有多条(分属不同台账 rosterId);
|
||||
# 逐个尝试,取第一条「本 rosterId 下有 exportField」的
|
||||
matches = [t for t in templates if t.get("ext1") == template_name]
|
||||
if not matches:
|
||||
names = sorted({str(t.get("ext1")) for t in templates if t.get("ext1")})
|
||||
client.log(f"[WARN] 模板列表中未找到「{template_name}」"
|
||||
f"(共 {len(names)} 个可选)")
|
||||
return None
|
||||
|
||||
for target in matches:
|
||||
detail: Dict[str, str] = {"rosterId": roster_id, "id": str(target["id"])}
|
||||
if user_id:
|
||||
detail["userId"] = user_id
|
||||
resp2 = client.post(TEMPLATE_DETAIL_URL, data=detail)
|
||||
data2 = client.as_json(resp2, "导出模板详情")
|
||||
export_field = (data2.get("result") or {}).get("exportField") or ""
|
||||
fields = json.loads(export_field) if export_field else []
|
||||
if not fields:
|
||||
continue
|
||||
filters = ",".join(str(f["tableCode"]) for f in fields)
|
||||
client.log(f"[INFO] 模板「{template_name}」解析成功({len(fields)} 列,"
|
||||
f"命中第 {matches.index(target) + 1}/{len(matches)} 条同名模板)")
|
||||
return filters
|
||||
client.log(f"[WARN] 「{template_name}」{len(matches)} 条同名模板在本台账下均无 exportField")
|
||||
return None
|
||||
except (SessionExpiredError, ApiError):
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001 - 解析失败走调用方兜底
|
||||
client.log(f"[WARN] 模板「{template_name}」解析失败:{exc}")
|
||||
return None
|
||||
|
||||
|
||||
# ==================== 参数构造 ====================
|
||||
|
||||
def build_params(base: Dict[str, str], *, conditions: Optional[Sequence[dict]] = None,
|
||||
template: str = "", filters: str = "") -> Dict[str, str]:
|
||||
"""在台账公共入参上叠加加密条件与导出配置(纯函数,便于离线自测)。"""
|
||||
params = {k: str(v) for k, v in base.items()}
|
||||
if conditions:
|
||||
params["commonQuery"] = encode(conditions)
|
||||
if template:
|
||||
if not filters:
|
||||
raise ConfigError(f"模板「{template}」没有可用字段串(filters);"
|
||||
"请先 resolve_template 或显式传 filters")
|
||||
params["exportConfig"] = json.dumps(
|
||||
{"exportName": template, "exportFilters": filters},
|
||||
ensure_ascii=False, separators=(",", ":"))
|
||||
params["_t"] = str(int(time.time() * 1000))
|
||||
return params
|
||||
|
||||
|
||||
# ==================== WS 导出 ====================
|
||||
|
||||
def _connect_ws(client):
|
||||
cookie_hdr = "; ".join(f"{c.name}={c.value}" for c in client.session.cookies
|
||||
if "hr.37du.co" in (c.domain or ""))
|
||||
ws = websocket.WebSocket()
|
||||
ws.connect(WS_SERVICE_URL, header=[
|
||||
f"Cookie: {cookie_hdr}",
|
||||
"Origin: https://hr.37du.co",
|
||||
f"User-Agent: {USER_AGENT}",
|
||||
], timeout=10)
|
||||
ws.send(json.dumps({"theme": WS_EXPORT_THEME, "code": "SUBCRIBE_THEME"}))
|
||||
ack = json.loads(ws.recv())
|
||||
if ack.get("code") != "SUBCRIBE_THEME_ACK":
|
||||
ws.close()
|
||||
raise HrError(f"WS 订阅失败:{str(ack)[:100]}")
|
||||
client.log(f"[INFO] WS 订阅成功({WS_EXPORT_THEME})")
|
||||
return ws
|
||||
|
||||
|
||||
def _wait_file_url(ws, timeout: int, log: LOGGER) -> str:
|
||||
deadline = time.time() + timeout
|
||||
ws.settimeout(timeout)
|
||||
while time.time() < deadline:
|
||||
msg = json.loads(ws.recv())
|
||||
if msg.get("code") != "NORMAL_PUSH_TO":
|
||||
continue
|
||||
text = msg.get("txt", "")
|
||||
if text.startswith("--end--"):
|
||||
return text.split("|", 1)[1].strip()
|
||||
if text.startswith(("开始下载", "正在生成")):
|
||||
log(f"[INFO] 进度:{text}")
|
||||
raise ExportTimeoutError(f"等待导出文件超时({timeout}s)")
|
||||
|
||||
|
||||
def export_table(client, *, page_url: str, export_url: str, params: Dict[str, str],
|
||||
output_path: str, filename: str = "", timeout: Optional[int] = None,
|
||||
retries: Optional[int] = None) -> str:
|
||||
"""执行一次异步导出并落盘,返回本地文件绝对路径。
|
||||
|
||||
Args:
|
||||
client: :class:`hr_sdk.client.HrClient`
|
||||
page_url: 台账页面地址(用于绑定会话)
|
||||
export_url: ``exportCommonListData.mc`` 地址
|
||||
params: 已构造好的导出入参(含 commonQuery/exportConfig)
|
||||
output_path: 目标文件路径(目录不存在会自动创建)
|
||||
filename: 覆盖文件名(默认取 output_path 末段)
|
||||
timeout: 等待推送上限(秒)
|
||||
retries: 重试次数(登录态失效不重试)
|
||||
|
||||
Raises:
|
||||
SessionExpiredError: 登录态失效
|
||||
ExportTimeoutError: 等待超时
|
||||
HrError: 提交失败/下载失败(重试耗尽)
|
||||
"""
|
||||
if not output_path:
|
||||
raise ConfigError("output_path 不能为空")
|
||||
wait = int(timeout if timeout is not None else EXPORT_TIMEOUT_SECONDS)
|
||||
attempts = max(1, int(retries if retries is not None else MAX_ATTEMPTS))
|
||||
last: Optional[BaseException] = None
|
||||
for attempt in range(1, attempts + 1):
|
||||
try:
|
||||
return _export_once(client, page_url=page_url, export_url=export_url,
|
||||
params=params, output_path=output_path,
|
||||
filename=filename, timeout=wait)
|
||||
except SessionExpiredError:
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001
|
||||
last = exc
|
||||
if attempt >= attempts:
|
||||
break
|
||||
delay = 2.0 * attempt
|
||||
client.log(f"[WARN] 导出第 {attempt}/{attempts} 次失败:{exc};{delay:.0f}s 后重试")
|
||||
time.sleep(delay)
|
||||
raise HrError(f"导出失败(重试 {attempts} 次):{last}")
|
||||
|
||||
|
||||
def _export_once(client, *, page_url: str, export_url: str, params: Dict[str, str],
|
||||
output_path: str, filename: str, timeout: int) -> str:
|
||||
bind_session(client, page_url)
|
||||
ws = _connect_ws(client)
|
||||
try:
|
||||
resp = client.post(export_url, data=params, timeout=30)
|
||||
if resp.status_code != 200:
|
||||
raise HrError(f"提交导出任务失败:HTTP {resp.status_code}")
|
||||
client.log(f"[INFO] 导出任务已提交({params.get('menuName', '')})")
|
||||
file_url = _wait_file_url(ws, timeout, client.log)
|
||||
finally:
|
||||
ws.close()
|
||||
|
||||
client.log(f"[INFO] 导出完成,文件地址:{file_url}")
|
||||
if file_url.startswith("/"):
|
||||
from .config import HR_BASE_URL
|
||||
file_url = f"{HR_BASE_URL}{file_url}"
|
||||
target_dir = os.path.dirname(os.path.abspath(output_path))
|
||||
name = filename or os.path.basename(output_path)
|
||||
os.makedirs(target_dir, exist_ok=True)
|
||||
return client.download(file_url, save_dir=target_dir, filename=name)
|
||||
|
||||
|
||||
def precheck(client, page_url: str) -> None:
|
||||
"""登录态预检:先注册会话,失效立刻抛错,避免跑到一半才发现。"""
|
||||
bind_session(client, page_url)
|
||||
|
||||
|
||||
__all__ = ["bind_session", "build_params", "export_table", "precheck", "resolve_template"]
|
||||
@@ -0,0 +1,588 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""增员 / 减员导入(HR「待增减人员 → 更多操作 → 增减员导入」的纯接口实现)。
|
||||
|
||||
**写操作**,默认 ``dry_run=True``:只做「取模板配置 + 文件格式校验 + 表头匹配」,
|
||||
不提交、不写库。必须显式 ``apply=True`` 才真正导入。
|
||||
|
||||
链路(与前端弹窗一致,全为 multipart):
|
||||
|
||||
1. ``GET /hr/module/base/import/do/<importId>/toImpPage.mc`` 取模板配置(fieldJson 表头映射)
|
||||
2. ``POST .../checkFileType.mc`` 文件格式校验(只读,返回 Excel 实际表头)
|
||||
3. 同名列回填 ``excelColNum``(等价前端 ``setDefaultMatchTitle``)
|
||||
4. ``POST .../uploadData.mc`` **唯一写库动作**(异步;不重试,防重复导入)
|
||||
5. ``POST .../getImportResult.mc`` 轮询结果(前端用 WebSocket,这里轮询等价)
|
||||
6. ``POST .../getFailPage.mc`` / ``getTmpDataPage.mc`` 失败明细分页
|
||||
7. ``getImportFailurePageAjax.mc`` 当天失败批次核对
|
||||
|
||||
入库核对(哪些人真的入库了)由插件事后调 :func:`operated_staff` 拿数据自行判定。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Dict, List, Optional
|
||||
from urllib.parse import quote
|
||||
|
||||
from .config import REDSEA, base_params
|
||||
from .errors import ApiError, ConfigError, SessionExpiredError
|
||||
from .query import encode, encode_raw
|
||||
|
||||
CONTEXT_PATH = "/RedseaPlatform"
|
||||
#: 注意:REDSEA 已含 ``/RedseaPlatform``,这里只放其后的路径段
|
||||
IMP_DO = "/hr/module/base/import/do"
|
||||
TO_IMP_PAGE_URL = (f"{REDSEA}{IMP_DO}/"
|
||||
"{import_id}/toImpPage.mc?pageType=1&importTitle={title}&struTreeCode=")
|
||||
CHECK_FILE_TYPE_URL = f"{REDSEA}{IMP_DO}/checkFileType.mc"
|
||||
UPLOAD_DATA_URL = f"{REDSEA}{IMP_DO}/uploadData.mc"
|
||||
GET_IMPORT_RESULT_URL = f"{REDSEA}{IMP_DO}/getImportResult.mc"
|
||||
GET_TMP_DATA_PAGE_URL = f"{REDSEA}{IMP_DO}/getTmpDataPage.mc"
|
||||
IMP_BASE = "/hr/module/base/import"
|
||||
GET_IMPORT_FAILURE_LIST_URL = f"{REDSEA}{IMP_BASE}/getImportFailurePageAjax.mc"
|
||||
GET_FAIL_PAGE_URL = f"{REDSEA}{IMP_BASE}/getFailPage.mc"
|
||||
|
||||
#: 「待增减人员」台账(入库核对用;成功导入的人会带本次 ext_operate_time 留在列表)
|
||||
PENDING_ROSTER_ID = "7984ae1a-16ec-11ed-bea9-822ff8ed5b28"
|
||||
PENDING_LIST_URL = f"{REDSEA}/hrRoster/{PENDING_ROSTER_ID}/queryRealTimeData.mc"
|
||||
PENDING_TABLE_ID = "assemble-hr_staff_base"
|
||||
PENDING_ORG_STRU_ID = "596bae33-50e9-11ec-b526-822ff8ed5b28"
|
||||
PENDING_ROLE_IDS = "POST_SYS_ADMIN,renshi"
|
||||
PENDING_PAGE_SIZE = 100
|
||||
PENDING_OPERATE_FIELD = "`si_add_cut_person_sp_cq37du.ext_operate_time`"
|
||||
|
||||
#: 两个导入模板的固定配置 id(取自「待增减人员」页按钮配置,勿改)
|
||||
IMPORT_MENUS = {
|
||||
"add": {"import_id": "12eecb13-78b0-4fac-a865-10c3043a33e1",
|
||||
"title": "商业保险增员导入", "label": "增员导入"},
|
||||
"sub": {"import_id": "22e180f9-476b-412d-b68b-bbed8393dba6",
|
||||
"title": "商业保险减员导入", "label": "减员导入"},
|
||||
}
|
||||
|
||||
#: 弹窗默认行号(列标题行 / 内容起始行)
|
||||
TITLE_ROW_NUM = "2"
|
||||
CONTENT_ROW_NUM = "4"
|
||||
|
||||
XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
TMP_PAGE_SIZE = 15 # getTmpDataPage/getFailPage 固定 15 条/页
|
||||
FAIL_LIST_PAGE_SIZE = 50 # 失败批次列表每页条数
|
||||
POLL_TIMEOUT_SECONDS = 300 # 导入结果轮询上限
|
||||
POLL_INTERVAL_SECONDS = 2.0
|
||||
|
||||
_CONF_CACHE: Dict[str, dict] = {}
|
||||
|
||||
|
||||
# ==================== 模板配置 ====================
|
||||
|
||||
def menu_info(menu: str) -> dict:
|
||||
"""取导入菜单信息(``add`` / ``sub``)。"""
|
||||
key = str(menu or "").strip().lower()
|
||||
if key not in IMPORT_MENUS:
|
||||
raise ConfigError(f"未知导入类型「{menu}」,可选:{' / '.join(IMPORT_MENUS)}")
|
||||
return IMPORT_MENUS[key]
|
||||
|
||||
|
||||
def load_conf(client, menu: str) -> dict:
|
||||
"""取导入模板配置 ``hrModuleBaseImport``(含 importId / fieldJson / maxNum)。"""
|
||||
menu_info(menu) # 校验 menu 合法
|
||||
key = str(menu).strip().lower()
|
||||
if key in _CONF_CACHE:
|
||||
return _CONF_CACHE[key]
|
||||
|
||||
info = IMPORT_MENUS[key]
|
||||
url = TO_IMP_PAGE_URL.format(import_id=info["import_id"],
|
||||
title=quote(info["title"], safe=""))
|
||||
resp = client.get(url, headers={"X-Requested-With": "XMLHttpRequest"}, timeout=30)
|
||||
html = (resp.content or b"").decode("utf-8", "ignore")
|
||||
if "j_username" in html[:5000] and "RedSea" not in html[:2000]:
|
||||
raise SessionExpiredError(f"{info['label']}弹窗页被重定向到登录页(HR 登录态失效)")
|
||||
|
||||
idx = html.find("var hrModuleBaseImport =")
|
||||
if idx < 0:
|
||||
raise ApiError(f"{info['label']}弹窗页未找到模板配置(页面结构可能已变化)")
|
||||
start = html.find("{", idx)
|
||||
try:
|
||||
conf, _ = json.JSONDecoder().raw_decode(html[start:])
|
||||
except ValueError as exc:
|
||||
raise ApiError(f"{info['label']}模板配置解析失败:{exc}") from None
|
||||
if str(conf.get("id") or "") != info["import_id"]:
|
||||
client.log(f"[WARN] {info['label']}页面 importId={conf.get('id')} 与预期不一致(沿用页面值)")
|
||||
client.log(f"[INFO] {info['label']}模板:{conf.get('title') or info['title']}"
|
||||
f"(最多 {conf.get('maxNum') or '-'} 行)")
|
||||
_CONF_CACHE[key] = conf
|
||||
return conf
|
||||
|
||||
|
||||
def field_list(conf: dict) -> List[dict]:
|
||||
"""解析 ``fieldJson`` → 表头映射数组(``columnName``/``columnDisplay``)。"""
|
||||
raw = conf.get("fieldJson") or "[]"
|
||||
try:
|
||||
data = json.loads(str(raw).replace("\n", "\\n").replace("\r", "\\r"))
|
||||
except ValueError:
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except ValueError:
|
||||
return []
|
||||
return data if isinstance(data, list) else []
|
||||
|
||||
|
||||
def match_titles(fields: List[dict], excel_titles: List[dict]):
|
||||
"""同名列回填 ``excelColNum``(等价前端 ``setDefaultMatchTitle``)。
|
||||
|
||||
Returns:
|
||||
``(title_list, matched)``:回填后的字段数组与匹配列数。
|
||||
"""
|
||||
by_name = {}
|
||||
for item in excel_titles or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
name = str(item.get("excelColName") or "").strip()
|
||||
if name:
|
||||
by_name[name] = item.get("excelColNum")
|
||||
title_list = [dict(f) for f in fields if isinstance(f, dict)]
|
||||
matched = 0
|
||||
for field in title_list:
|
||||
display = str(field.get("columnDisplay") or "").strip()
|
||||
if display in by_name and by_name[display] is not None:
|
||||
field["excelColNum"] = by_name[display]
|
||||
matched += 1
|
||||
return title_list, matched
|
||||
|
||||
|
||||
def _form_base(conf: dict, title_list: List[dict]) -> dict:
|
||||
"""弹窗表单公共字段(与前端 FormData 一致)。"""
|
||||
return {
|
||||
"importId": conf["id"],
|
||||
"titleRowNum": TITLE_ROW_NUM,
|
||||
"contentRowNum": CONTENT_ROW_NUM,
|
||||
"titleList": encode_raw(json.dumps(title_list, ensure_ascii=False,
|
||||
separators=(",", ":"))),
|
||||
"name": "test", # 前端为兼容 IE 固定附加,照传
|
||||
}
|
||||
|
||||
|
||||
# ==================== 校验(只读) ====================
|
||||
|
||||
def check_file(client, file_path: str, menu: str = "add", *,
|
||||
conf: Optional[dict] = None) -> dict:
|
||||
"""文件格式校验(**不写库**),返回 ``{conf, fields, title_list, matched, excel_titles}``。"""
|
||||
_require_file(file_path)
|
||||
menu_info(menu)
|
||||
conf = conf or load_conf(client, menu)
|
||||
fields = field_list(conf)
|
||||
|
||||
resp = client.post_files(
|
||||
CHECK_FILE_TYPE_URL,
|
||||
files={"file": (os.path.basename(file_path), _read_bytes(file_path), XLSX_MIME)},
|
||||
data=_form_base(conf, fields), timeout=180)
|
||||
data = client.as_json(resp, "文件格式校验")
|
||||
client.check_state(data, "文件格式校验")
|
||||
|
||||
titles = data.get("result") or []
|
||||
title_list, matched = match_titles(fields, titles)
|
||||
client.log(f"[INFO] 表头校验通过:Excel {len(titles)} 列,"
|
||||
f"匹配模板 {matched}/{len(fields)} 列")
|
||||
return {"conf": conf, "fields": fields, "title_list": title_list,
|
||||
"matched": matched, "excel_titles": titles}
|
||||
|
||||
|
||||
# ==================== 导入(写) ====================
|
||||
|
||||
def upload(client, file_path: str, menu: str = "add", *, apply: bool = False,
|
||||
poll_timeout: int = POLL_TIMEOUT_SECONDS,
|
||||
fetch_exceptions: bool = True) -> dict:
|
||||
"""校验(+ 可选)提交导入并回收结果。
|
||||
|
||||
Args:
|
||||
client: :class:`hr_sdk.client.HrClient`
|
||||
file_path: 导入 Excel(模板:列标题行=2、内容起始行=4)
|
||||
menu: ``add``(增员)/ ``sub``(减员)
|
||||
apply: **默认 False**,只校验不写库;True 才真正提交
|
||||
poll_timeout: 结果轮询上限(秒)
|
||||
fetch_exceptions: 失败时是否拉失败明细
|
||||
|
||||
Returns:
|
||||
dict:``{menu, label, file, dry_run, matched, fields, max_num, applied, ok,
|
||||
stage, business_id, is_success, success, check_fail, save_fail, other,
|
||||
message, exceptions, batch_found, batch_total}``
|
||||
|
||||
Raises:
|
||||
SessionExpiredError: 登录态失效(确定性失败,不重试、不建议继续提交)
|
||||
ConfigError: 文件缺失 / menu 非法
|
||||
"""
|
||||
info = menu_info(menu)
|
||||
key = str(menu).strip().lower()
|
||||
out = {"menu": key, "label": info["label"], "file": os.path.abspath(file_path),
|
||||
"dry_run": not apply, "matched": 0, "fields": 0, "max_num": 0,
|
||||
"applied": False, "ok": False, "stage": "", "business_id": "",
|
||||
"is_success": False, "success": 0, "check_fail": 0, "save_fail": 0,
|
||||
"other": 0, "message": "", "exceptions": [],
|
||||
"batch_found": False, "batch_total": 0}
|
||||
|
||||
checked = check_file(client, file_path, key)
|
||||
conf, title_list = checked["conf"], checked["title_list"]
|
||||
out.update({"matched": checked["matched"], "fields": len(checked["fields"]),
|
||||
"max_num": int(conf.get("maxNum") or 0)})
|
||||
if checked["matched"] <= 0:
|
||||
out.update(stage="check",
|
||||
message=f"导入文件表头与「{conf.get('title') or info['title']}」模板不匹配(0 列匹配)")
|
||||
return out
|
||||
if not apply:
|
||||
out.update(ok=True, message="仅校验(dry_run):未提交、未写库")
|
||||
return out
|
||||
|
||||
# ---- 以下为写操作 ----
|
||||
business_id = str(uuid.uuid4()) # 必须 36 位带连字符(HR 用该串关联任务与失败记录)
|
||||
out.update(business_id=business_id, applied=True)
|
||||
form = _form_base(conf, title_list)
|
||||
form["businessId"] = business_id
|
||||
try:
|
||||
resp = client.post_files(
|
||||
UPLOAD_DATA_URL,
|
||||
files={"file": (os.path.basename(file_path), _read_bytes(file_path), XLSX_MIME)},
|
||||
data=form, timeout=180)
|
||||
except Exception as exc: # noqa: BLE001 - 结果未知,转轮询判定
|
||||
out.update(stage="upload", message=f"提交异常(结果未知,转轮询):{exc}")
|
||||
client.log(f"[WARN] {info['label']}提交异常,转轮询判定:{exc}")
|
||||
else:
|
||||
try:
|
||||
payload = resp.json()
|
||||
except ValueError:
|
||||
payload = None
|
||||
if isinstance(payload, dict):
|
||||
client.check_state(payload, f"{info['label']}提交") # 会话失效直接抛
|
||||
if str(payload.get("state")) != "1":
|
||||
detail = decode_error(payload.get("des")) or decode_error(payload.get("meg"))
|
||||
out.update(stage="upload",
|
||||
message=f"提交未被受理:{(detail or payload)[:500]}")
|
||||
return out
|
||||
client.log(f"[INFO] {info['label']}已提交(businessId={business_id},"
|
||||
f"HTTP {resp.status_code})")
|
||||
|
||||
result = _poll_result(client, conf["id"], business_id, poll_timeout)
|
||||
if result is None:
|
||||
out.update(stage="result",
|
||||
message=f"结果轮询超时({poll_timeout}s),结果待人工确认")
|
||||
return out
|
||||
|
||||
out.update({
|
||||
"is_success": str(result.get("isSuccess")) == "1",
|
||||
"success": _int(result.get("success")),
|
||||
"check_fail": _int(result.get("checkFail")),
|
||||
"save_fail": _int(result.get("saveFail")),
|
||||
"other": _int(result.get("other")),
|
||||
"message": str(result.get("meg") or ""),
|
||||
})
|
||||
if fetch_exceptions and not out["is_success"]:
|
||||
out["exceptions"] = fetch_failures(client, conf["id"], business_id)
|
||||
_check_fail_batches(client, conf["id"], business_id, out, info["label"])
|
||||
out["ok"] = True
|
||||
return out
|
||||
|
||||
|
||||
def decode_error(value) -> str:
|
||||
"""解码服务端返回的加密文案(``des``/``meg``),失败返回原文。"""
|
||||
from .query import decode_raw
|
||||
|
||||
text = str(value or "").strip()
|
||||
return decode_raw(text) if text else ""
|
||||
|
||||
|
||||
def _int(value) -> int:
|
||||
try:
|
||||
return int(value or 0)
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
|
||||
|
||||
def _poll_result(client, import_id: str, business_id: str,
|
||||
timeout: int) -> Optional[dict]:
|
||||
"""轮询 ``getImportResult``:拿到含 isSuccess/success 的 result 即返回,超时 None。"""
|
||||
deadline = time.time() + max(1, int(timeout))
|
||||
waited = 0
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
resp = client.post_files(GET_IMPORT_RESULT_URL,
|
||||
files={},
|
||||
data={"importId": import_id,
|
||||
"businessId": business_id}, timeout=30)
|
||||
data = client.as_json(resp, "导入结果查询")
|
||||
client.check_state(data, "导入结果查询")
|
||||
res = data.get("result")
|
||||
if str(data.get("state")) == "1" and isinstance(res, dict) \
|
||||
and ("isSuccess" in res or "success" in res):
|
||||
return res
|
||||
meg = str(data.get("meg") or "").strip()
|
||||
if meg:
|
||||
waited += int(POLL_INTERVAL_SECONDS)
|
||||
if waited % 30 == 0:
|
||||
client.log(f"[INFO] 导入处理中:{meg}(已等待 {waited}s)")
|
||||
except SessionExpiredError:
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001 - 轮询期间容忍抖动
|
||||
client.log(f"[WARN] 导入结果查询失败(继续轮询):{exc}")
|
||||
time.sleep(POLL_INTERVAL_SECONDS)
|
||||
return None
|
||||
|
||||
|
||||
# ==================== 失败明细 / 批次 ====================
|
||||
|
||||
def _page_failures(client, url: str, data_builder, label: str) -> List[dict]:
|
||||
items: List[dict] = []
|
||||
page_count, page_no = 1, 1
|
||||
while page_no <= page_count:
|
||||
try:
|
||||
resp = client.post_files(url, files={}, data=data_builder(page_no), timeout=30)
|
||||
result = client.as_json(resp, label)
|
||||
client.check_state(result, label)
|
||||
except SessionExpiredError:
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001
|
||||
client.log(f"[WARN] {label}第 {page_no} 页失败:{exc}")
|
||||
break
|
||||
page_count = max(1, _int(result.get("pageCount") or 1))
|
||||
items.extend(_parse_failure_rows(result.get("datas") or []))
|
||||
page_no += 1
|
||||
return items
|
||||
|
||||
|
||||
def _parse_failure_rows(rows: List[dict]) -> List[dict]:
|
||||
out = []
|
||||
for item in rows or []:
|
||||
item = item or {}
|
||||
message = str(item.get("imp_fixed_msg", "") or "").strip()
|
||||
if not message or "导入成功" in message: # 成功行固定文案,不计入异常
|
||||
continue
|
||||
out.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": message,
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def fetch_failures(client, import_id: str, business_id: str) -> List[dict]:
|
||||
"""拉某批次失败明细(官方「失败数据」页优先,弹窗明细兜底)。"""
|
||||
items = _page_failures(
|
||||
client, GET_FAIL_PAGE_URL,
|
||||
lambda page_no: {
|
||||
"excelImpVersion": "2", "functionCode": import_id,
|
||||
"businessId": business_id,
|
||||
"start": str((page_no - 1) * TMP_PAGE_SIZE), "pageNo": str(page_no),
|
||||
"pageSize": str(TMP_PAGE_SIZE), "commonQuery": "[]",
|
||||
"sortType": "", "sortName": "",
|
||||
}, "失败数据")
|
||||
if items:
|
||||
return items
|
||||
return _page_failures(
|
||||
client, GET_TMP_DATA_PAGE_URL,
|
||||
lambda page_no: {
|
||||
"importId": import_id, "imp_fixed_businessid": business_id,
|
||||
"start": str((page_no - 1) * TMP_PAGE_SIZE), "pageNo": str(page_no),
|
||||
"pageSize": str(TMP_PAGE_SIZE), "sortType": "", "sortName": "",
|
||||
}, "导入明细")
|
||||
|
||||
|
||||
def fail_batches(client, import_id: str, date_begin: str = "",
|
||||
date_end: str = "") -> List[dict]:
|
||||
"""查某模板在指定时间段内的失败批次(只有存在失败数据才生成批次)。"""
|
||||
today = date_begin or time.strftime("%Y-%m-%d")
|
||||
resp = client.post_files(GET_IMPORT_FAILURE_LIST_URL, files={}, data={
|
||||
"root_id": "", "excelImpVersion": "2", "functionCode": import_id,
|
||||
"date_begin": today, "date_end": date_end or f"{today} 23:59:59",
|
||||
"start": "0", "sortType": "", "sortName": "", "pageNo": "1",
|
||||
"pageSize": str(FAIL_LIST_PAGE_SIZE),
|
||||
}, timeout=30)
|
||||
data = client.as_json(resp, "导入失败批次列表")
|
||||
if str(data.get("state")) != "1":
|
||||
client.check_state(data, "导入失败批次列表")
|
||||
return []
|
||||
out = []
|
||||
for item in data.get("datas") or []:
|
||||
item = item or {}
|
||||
bid = str(item.get("businessid") or "").strip()
|
||||
if not bid:
|
||||
continue
|
||||
out.append({"business_id": bid,
|
||||
"operator_time": str(item.get("operator_time") or ""),
|
||||
"total": _int(item.get("total"))})
|
||||
return out
|
||||
|
||||
|
||||
def _check_fail_batches(client, import_id: str, business_id: str, out: dict,
|
||||
label: str) -> None:
|
||||
"""当天失败批次核对(只补观测字段,不影响主流程)。"""
|
||||
try:
|
||||
batches = fail_batches(client, import_id)
|
||||
except SessionExpiredError:
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001
|
||||
client.log(f"[WARN] {label}失败批次核对跳过:{exc}")
|
||||
return
|
||||
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:
|
||||
client.log(f"[INFO] {label}失败批次已确认:{business_id}"
|
||||
f"({hit['operator_time']},失败 {hit['total']} 条)")
|
||||
if out["exceptions"] and len(out["exceptions"]) != hit["total"]:
|
||||
client.log(f"[WARN] {label}明细条数({len(out['exceptions'])})"
|
||||
f"与批次统计({hit['total']})不一致,请人工核对")
|
||||
elif not out["is_success"]:
|
||||
client.log(f"[WARN] {label}未在当天失败批次列表中找到本批次,请人工核对")
|
||||
|
||||
|
||||
# ==================== 入库核对数据(只读) ====================
|
||||
|
||||
def _date_params() -> dict:
|
||||
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 operated_staff(client, started_at: str, end_at: str = "",
|
||||
max_pages: int = 80) -> List[dict]:
|
||||
"""查「待增减人员」里商业保险操作时间 ∈ [started_at, end_at] 的人员。
|
||||
|
||||
返回 ``[{staff_code, staff_name, scheme, operate_time, add_date, cut_date}]``;
|
||||
与导入文件工号做交集即可判断「到底哪些人入库了」——判定逻辑留插件。
|
||||
"""
|
||||
if not started_at:
|
||||
raise ConfigError("started_at 不能为空(导入提交前的时间点,YYYY-MM-DD HH:MM:SS)")
|
||||
end_at = end_at or time.strftime("%Y-%m-%d %H:%M:%S")
|
||||
user = client.request_json("POST", f"{REDSEA}/PtUsers.mc?method=getCurUserInfo",
|
||||
data={}, label="当前用户信息")
|
||||
root = str(user.get("rootId") or "cq37du")
|
||||
params = base_params("待增减人员", PENDING_TABLE_ID, PENDING_ROSTER_ID,
|
||||
user={"userId": user.get("userId") or "",
|
||||
"staffId": user.get("staffId") or "",
|
||||
"roleIds": PENDING_ROLE_IDS})
|
||||
params.update({
|
||||
"_t": str(int(time.time() * 1000)),
|
||||
"struTreeCode": root,
|
||||
"struId": PENDING_ORG_STRU_ID,
|
||||
"belongUnitStruId": PENDING_ORG_STRU_ID,
|
||||
"rootId": root,
|
||||
"currentUserRootId": root,
|
||||
"pageSize": str(PENDING_PAGE_SIZE),
|
||||
"commonQuery": encode([
|
||||
{"queryField": PENDING_OPERATE_FIELD, "leftBracket": "(", "queryType": ">=",
|
||||
"queryValue": started_at, "queryText": started_at, "rightBracket": "",
|
||||
"logic": "AND", "inputType": "date"},
|
||||
{"queryField": PENDING_OPERATE_FIELD, "leftBracket": "", "queryType": "<=",
|
||||
"queryValue": end_at, "queryText": end_at, "rightBracket": ")",
|
||||
"logic": "AND", "inputType": "date"},
|
||||
]),
|
||||
})
|
||||
params.update(_date_params())
|
||||
|
||||
rows: List[dict] = []
|
||||
for page_no in range(1, max(1, max_pages) + 1):
|
||||
body = dict(params)
|
||||
body["pageNo"] = str(page_no)
|
||||
body["start"] = str((page_no - 1) * PENDING_PAGE_SIZE)
|
||||
data = client.request_json("POST", PENDING_LIST_URL, data=body,
|
||||
label=f"待增减人员第 {page_no} 页")
|
||||
client.check_state(data, f"待增减人员第 {page_no} 页")
|
||||
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 ""),
|
||||
})
|
||||
page_count = _int(data.get("pageCount") or 1) or 1
|
||||
if page_no >= page_count or not datas:
|
||||
break
|
||||
client.log(f"[INFO] 待增减人员操作记录:{len(rows)} 条({started_at} 之后)")
|
||||
return rows
|
||||
|
||||
|
||||
def read_codes(file_path: str) -> List[str]:
|
||||
"""读导入文件里的工号(第 4 行起、A 列序号非空视为有效行,取 B 列)。"""
|
||||
_require_file(file_path)
|
||||
from openpyxl import load_workbook
|
||||
|
||||
codes: List[str] = []
|
||||
try:
|
||||
wb = load_workbook(file_path, read_only=True, data_only=True)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
raise ConfigError(f"读取导入文件失败:{exc}") from None
|
||||
try:
|
||||
ws = wb[wb.sheetnames[0]]
|
||||
for row in ws.iter_rows(min_row=int(CONTENT_ROW_NUM), max_col=2,
|
||||
values_only=True):
|
||||
seq, code = (list(row) + [None, None])[:2]
|
||||
if seq in (None, "") or code in (None, ""):
|
||||
continue
|
||||
codes.append(str(code).strip())
|
||||
finally:
|
||||
wb.close()
|
||||
return codes
|
||||
|
||||
|
||||
# ==================== 内部工具 ====================
|
||||
|
||||
def _require_file(path: str) -> None:
|
||||
if not path or not os.path.isfile(path):
|
||||
raise ConfigError(f"导入文件不存在:{path}")
|
||||
|
||||
|
||||
def _read_bytes(path: str) -> bytes:
|
||||
with open(path, "rb") as fp:
|
||||
return fp.read() # 读成 bytes:重试/多次提交时可重发
|
||||
|
||||
|
||||
__all__ = [
|
||||
"CHECK_FILE_TYPE_URL",
|
||||
"CONTENT_ROW_NUM",
|
||||
"FAIL_LIST_PAGE_SIZE",
|
||||
"GET_FAIL_PAGE_URL",
|
||||
"GET_IMPORT_FAILURE_LIST_URL",
|
||||
"GET_IMPORT_RESULT_URL",
|
||||
"GET_TMP_DATA_PAGE_URL",
|
||||
"IMPORT_MENUS",
|
||||
"PENDING_LIST_URL",
|
||||
"PENDING_OPERATE_FIELD",
|
||||
"PENDING_ROSTER_ID",
|
||||
"POLL_INTERVAL_SECONDS",
|
||||
"POLL_TIMEOUT_SECONDS",
|
||||
"TITLE_ROW_NUM",
|
||||
"TMP_PAGE_SIZE",
|
||||
"UPLOAD_DATA_URL",
|
||||
"XLSX_MIME",
|
||||
"check_file",
|
||||
"decode_error",
|
||||
"fail_batches",
|
||||
"fetch_failures",
|
||||
"field_list",
|
||||
"load_conf",
|
||||
"match_titles",
|
||||
"menu_info",
|
||||
"operated_staff",
|
||||
"read_codes",
|
||||
"upload",
|
||||
]
|
||||
@@ -0,0 +1,127 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""台账导出:预入职台账 / 调动台账(纯接口,服务端生成 Excel)。
|
||||
|
||||
用法::
|
||||
|
||||
from hr_sdk import HrClient, ledger
|
||||
|
||||
client = HrClient(ctx.get_session("hr"))
|
||||
ledger.export_transfer(client, output=r"D:\\out\\调动台账.xlsx")
|
||||
ledger.export_pre_entry(client, output=r"D:\\out\\预入职台账.xlsx")
|
||||
|
||||
两个台账共用 :mod:`hr_sdk.export` 的异步导出机制,差别只在
|
||||
``rosterId`` / ``tableId`` / 日期字段 / 默认模板。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from datetime import date, timedelta
|
||||
from typing import Optional
|
||||
|
||||
from . import export
|
||||
from .config import REDSEA, app_data_dir, base_params
|
||||
from .errors import ConfigError
|
||||
from .query import date_range
|
||||
|
||||
# ==================== 调动台账 ====================
|
||||
#: 「调动已生效」tab 的台账 id(入口页 1123d951 是默认 tab,导出走 10feec75)
|
||||
TRANSFER_ROSTER_ID = "10feec75-b094-11ea-b588-14187743d052"
|
||||
TRANSFER_TABLE_ID = "assemble-hr_staff_move_info"
|
||||
TRANSFER_MENU_NAME = "调动台账"
|
||||
TRANSFER_PAGE_URL = f"{REDSEA}/hrRoster/{TRANSFER_ROSTER_ID}/getCustomCommonList.mc"
|
||||
TRANSFER_EXPORT_URL = f"{REDSEA}/hrRoster/{TRANSFER_ROSTER_ID}/exportCommonListData.mc"
|
||||
TRANSFER_DATE_FIELD = "`hr_staff_move_info.MOVE_DATE`"
|
||||
DEFAULT_TRANSFER_TEMPLATE = "排班异常识别导出"
|
||||
|
||||
# ==================== 预入职台账 ====================
|
||||
#: 「已入职」tab 的台账 id(入口页 10fe9cd6 是默认 tab,导出走 112adc5b)
|
||||
PRE_ENTRY_ROSTER_ID = "112adc5b-b094-11ea-b588-14187743d052"
|
||||
PRE_ENTRY_TABLE_ID = "assemble-hr_staff_base_offer"
|
||||
PRE_ENTRY_MENU_NAME = "预入职台账"
|
||||
PRE_ENTRY_PAGE_URL = f"{REDSEA}/hrRoster/{PRE_ENTRY_ROSTER_ID}/getCustomCommonList.mc"
|
||||
PRE_ENTRY_EXPORT_URL = f"{REDSEA}/hrRoster/{PRE_ENTRY_ROSTER_ID}/exportCommonListData.mc"
|
||||
PRE_ENTRY_DATE_FIELD = "`hr_staff_base_offer.join_date`"
|
||||
DEFAULT_PRE_ENTRY_TEMPLATE = "排班异常识别导出"
|
||||
|
||||
DEFAULT_DAYS = 30
|
||||
|
||||
|
||||
def recent_range(today: Optional[date] = None, days: int = DEFAULT_DAYS) -> tuple:
|
||||
"""近 N 天闭区间(含今天),返回 ``(start, end)``。"""
|
||||
today = today or date.today()
|
||||
start = today - timedelta(days=max(1, days) - 1)
|
||||
return start.strftime("%Y-%m-%d"), today.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def _default_output(filename: str) -> str:
|
||||
return os.path.join(app_data_dir(), "output", filename)
|
||||
|
||||
|
||||
def _run(client, *, page_url: str, export_url: str, menu: str, table_id: str,
|
||||
roster_id: str, date_field: str, start: str, end: str,
|
||||
template: str, filters: str, output: str,
|
||||
user: Optional[dict], timeout: Optional[int]) -> str:
|
||||
if not start or not end:
|
||||
start, end = recent_range(date.today(), DEFAULT_DAYS)
|
||||
resolved = filters or export.resolve_template(client, template, roster_id) or ""
|
||||
if not resolved:
|
||||
raise ConfigError(
|
||||
f"未能解析模板「{template}」的导出列,请检查模板名或显式传 filters")
|
||||
params = export.build_params(
|
||||
base_params(menu, table_id, roster_id, user=user),
|
||||
conditions=date_range(date_field, start, end),
|
||||
template=template, filters=resolved)
|
||||
client.log(f"[INFO] {menu}导出:{start} ~ {end}(模板:{template})")
|
||||
return export.export_table(client, page_url=page_url, export_url=export_url,
|
||||
params=params, output_path=output, timeout=timeout)
|
||||
|
||||
|
||||
def export_transfer(client, *, start: str = "", end: str = "",
|
||||
template: str = DEFAULT_TRANSFER_TEMPLATE, filters: str = "",
|
||||
output: str = "", user: Optional[dict] = None,
|
||||
timeout: Optional[int] = None) -> str:
|
||||
"""导出调动台账(「调动已生效」),默认近 30 天,返回文件路径。"""
|
||||
return _run(client,
|
||||
page_url=TRANSFER_PAGE_URL, export_url=TRANSFER_EXPORT_URL,
|
||||
menu=TRANSFER_MENU_NAME, table_id=TRANSFER_TABLE_ID,
|
||||
roster_id=TRANSFER_ROSTER_ID, date_field=TRANSFER_DATE_FIELD,
|
||||
start=start, end=end, template=template, filters=filters,
|
||||
output=os.path.abspath(output or _default_output("调动台账.xlsx")),
|
||||
user=user, timeout=timeout)
|
||||
|
||||
|
||||
def export_pre_entry(client, *, start: str = "", end: str = "",
|
||||
template: str = DEFAULT_PRE_ENTRY_TEMPLATE, filters: str = "",
|
||||
output: str = "", user: Optional[dict] = None,
|
||||
timeout: Optional[int] = None) -> str:
|
||||
"""导出预入职台账(「已入职」),默认近 30 天,返回文件路径。"""
|
||||
return _run(client,
|
||||
page_url=PRE_ENTRY_PAGE_URL, export_url=PRE_ENTRY_EXPORT_URL,
|
||||
menu=PRE_ENTRY_MENU_NAME, table_id=PRE_ENTRY_TABLE_ID,
|
||||
roster_id=PRE_ENTRY_ROSTER_ID, date_field=PRE_ENTRY_DATE_FIELD,
|
||||
start=start, end=end, template=template, filters=filters,
|
||||
output=os.path.abspath(output or _default_output("预入职台账.xlsx")),
|
||||
user=user, timeout=timeout)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"DEFAULT_DAYS",
|
||||
"DEFAULT_PRE_ENTRY_TEMPLATE",
|
||||
"DEFAULT_TRANSFER_TEMPLATE",
|
||||
"PRE_ENTRY_DATE_FIELD",
|
||||
"PRE_ENTRY_EXPORT_URL",
|
||||
"PRE_ENTRY_MENU_NAME",
|
||||
"PRE_ENTRY_PAGE_URL",
|
||||
"PRE_ENTRY_ROSTER_ID",
|
||||
"PRE_ENTRY_TABLE_ID",
|
||||
"TRANSFER_DATE_FIELD",
|
||||
"TRANSFER_EXPORT_URL",
|
||||
"TRANSFER_MENU_NAME",
|
||||
"TRANSFER_PAGE_URL",
|
||||
"TRANSFER_ROSTER_ID",
|
||||
"TRANSFER_TABLE_ID",
|
||||
"export_pre_entry",
|
||||
"export_transfer",
|
||||
"recent_range",
|
||||
]
|
||||
@@ -0,0 +1,62 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""组织机构(组织维护)接口:分页拉取在用组织。
|
||||
|
||||
用法::
|
||||
|
||||
from hr_sdk import HrClient, org
|
||||
|
||||
client = HrClient(ctx.get_session("hr"))
|
||||
records = org.rows(client) # 接口原始记录,列名映射/落盘由插件决定
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Callable, List, Optional
|
||||
|
||||
from .config import PAGE_MAX_SIZE, REDSEA, base_params
|
||||
from .query import condition
|
||||
|
||||
ORG_ROSTER_ID = "110118b4-b094-11ea-b588-14187743d052"
|
||||
ORG_TABLE_ID = "assemble-pt_organzation"
|
||||
ORG_MENU_NAME = "组织维护"
|
||||
ORG_QUERY_URL = f"{REDSEA}/hrRoster/{ORG_ROSTER_ID}/queryRealTimeData.mc"
|
||||
|
||||
LOGGER = Callable[[str], None]
|
||||
|
||||
|
||||
def conditions() -> List[dict]:
|
||||
"""组织维护默认条件:``in_use in ('1')``(在用)。"""
|
||||
return [condition("`pt_organzation.IN_USE`", "in", "1", query_text="1",
|
||||
left_bracket="(", right_bracket=")", input_type="select")]
|
||||
|
||||
|
||||
def rows(client, *, page_size: int = PAGE_MAX_SIZE,
|
||||
max_pages: int = 500) -> List[dict]:
|
||||
"""分页拉取全部在用组织,返回接口原始记录列表(``datas`` 元素)。
|
||||
|
||||
Raises:
|
||||
ApiError: 接口 ``state != 1``
|
||||
"""
|
||||
from .query import encode
|
||||
|
||||
base = base_params(ORG_MENU_NAME, ORG_TABLE_ID, ORG_ROSTER_ID)
|
||||
base["commonQuery"] = encode(conditions())
|
||||
base["baseHrefPath"] = f"http://hr.37du.co:80RedseaPlatform"
|
||||
|
||||
def _fetch(page_no: int, size: int):
|
||||
data = dict(base)
|
||||
data["pageNo"] = str(page_no)
|
||||
data["pageSize"] = str(size)
|
||||
result = client.request_json("POST", ORG_QUERY_URL, data=data, label="组织维护")
|
||||
client.check_state(result, f"组织维护第 {page_no} 页")
|
||||
page_rows = result.get("datas") or []
|
||||
total_page = int(result.get("pageCount") or 0)
|
||||
if page_no == 1:
|
||||
client.log(f"[INFO] 组织维护共 {result.get('count')} 条 / {total_page} 页")
|
||||
return page_rows, page_no < total_page
|
||||
|
||||
return client.paginate(_fetch, page_size=page_size, max_pages=max_pages)
|
||||
|
||||
|
||||
__all__ = ["ORG_MENU_NAME", "ORG_QUERY_URL", "ORG_ROSTER_ID", "ORG_TABLE_ID",
|
||||
"conditions", "rows"]
|
||||
@@ -0,0 +1,140 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""前端查询条件加密(``commonQuery``)——服务端协议,改动需与服务端同步。
|
||||
|
||||
算法(与前端行为一致,已实测):
|
||||
JSON(无空格)→ encodeURIComponent(不编码 ``! ' ( ) * - . _ ~``)
|
||||
→ 自定义字符表 Base64 → 追加盐 → 首 2 位 + 末 3 位 + 中间部分重排
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import urllib.parse
|
||||
from typing import Any, Dict, List, Sequence
|
||||
|
||||
#: 自定义 Base64 字符表(索引 0~63,64 为填充字符)
|
||||
CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
|
||||
PAD_CHAR = "7"
|
||||
SALT = "yyryrtweasdasd"
|
||||
|
||||
|
||||
def custom_base64_encode(data: bytes) -> str:
|
||||
"""用自定义字符表做 Base64 编码。"""
|
||||
out: List[str] = []
|
||||
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 = 64
|
||||
enc4 = 64
|
||||
elif len(chunk) == 2:
|
||||
enc4 = 64
|
||||
|
||||
out.append(CUSTOM_CHARS[enc1])
|
||||
out.append(CUSTOM_CHARS[enc2])
|
||||
out.append(CUSTOM_CHARS[enc3])
|
||||
out.append(CUSTOM_CHARS[enc4])
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def custom_base64_decode(enc_str: str) -> bytes:
|
||||
"""自定义字符表 Base64 解码(``'7'`` 为填充符),与 :func:`custom_base64_encode` 互逆。"""
|
||||
index = {c: i for i, c in enumerate(CUSTOM_CHARS)}
|
||||
pad = enc_str.count(PAD_CHAR)
|
||||
enc_str = enc_str.replace(PAD_CHAR, "")
|
||||
data = bytearray()
|
||||
for i in range(0, len(enc_str), 4):
|
||||
chunk = enc_str[i:i + 4].ljust(4, PAD_CHAR)
|
||||
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])
|
||||
return bytes(data[:-pad] if pad else data)
|
||||
|
||||
|
||||
def condition(query_field: str, query_type: str, query_value: Any, query_text: str = "",
|
||||
left_bracket: str = "", right_bracket: str = "", logic: str = "AND",
|
||||
input_type: str = "text") -> Dict[str, str]:
|
||||
"""构造一条符合前端格式的查询条件。"""
|
||||
return {
|
||||
"queryField": query_field,
|
||||
"leftBracket": left_bracket,
|
||||
"queryType": query_type,
|
||||
"queryValue": query_value,
|
||||
"queryText": query_text,
|
||||
"rightBracket": right_bracket,
|
||||
"logic": logic,
|
||||
"inputType": input_type,
|
||||
}
|
||||
|
||||
|
||||
#: 旧名兼容
|
||||
build_condition = condition
|
||||
|
||||
|
||||
def date_range(field: str, start: str, end: str, input_type: str = "date") -> List[dict]:
|
||||
"""构造闭区间日期条件(``>= start`` 与 ``<= end`` 用括号包成一组)。"""
|
||||
return [
|
||||
condition(field, ">=", start, left_bracket="(", input_type=input_type),
|
||||
condition(field, "<=", end, right_bracket=")", input_type=input_type),
|
||||
]
|
||||
|
||||
|
||||
def encode(conditions: Sequence[dict]) -> str:
|
||||
"""条件列表 → ``commonQuery`` 字符串。"""
|
||||
json_str = json.dumps(list(conditions), ensure_ascii=False, separators=(",", ":"))
|
||||
uri_encoded = urllib.parse.quote(json_str, safe="-_.~!*'()")
|
||||
en_str = custom_base64_encode(uri_encoded.encode("utf-8")) + SALT
|
||||
return en_str[:2] + en_str[-3:] + en_str[2:-3]
|
||||
|
||||
|
||||
#: 旧名兼容
|
||||
encode_common_query = encode
|
||||
|
||||
|
||||
def encode_raw(text: str) -> str:
|
||||
"""前端 ``Base64.tranCode.encode``:自定义 Base64 + 盐 + 首尾重排(不做 URI 编码)。
|
||||
|
||||
用于 ``titleList``(字段映射数组 JSON)等参数;编码错误会让服务端解不出映射、
|
||||
任务根本不入队。
|
||||
"""
|
||||
en_str = custom_base64_encode(str(text).encode("utf-8")) + SALT
|
||||
return en_str[:2] + en_str[-3:] + en_str[2:-3]
|
||||
|
||||
|
||||
def decode_raw(text: str) -> str:
|
||||
"""``encode_raw`` 的逆过程,用于解码服务端返回的加密错误文案。"""
|
||||
raw = str(text or "").strip()
|
||||
if len(raw) < 8:
|
||||
return raw
|
||||
try:
|
||||
en_str = raw[:2] + raw[5:] + raw[2:5]
|
||||
if en_str.endswith(SALT):
|
||||
en_str = en_str[:-len(SALT)]
|
||||
return urllib.parse.unquote(custom_base64_decode(en_str)
|
||||
.decode("utf-8", errors="replace"))
|
||||
except Exception: # noqa: BLE001 - 解码失败保留原文
|
||||
return raw
|
||||
|
||||
|
||||
__all__ = [
|
||||
"CUSTOM_CHARS",
|
||||
"PAD_CHAR",
|
||||
"SALT",
|
||||
"build_condition",
|
||||
"condition",
|
||||
"custom_base64_decode",
|
||||
"custom_base64_encode",
|
||||
"date_range",
|
||||
"decode_raw",
|
||||
"encode",
|
||||
"encode_common_query",
|
||||
"encode_raw",
|
||||
]
|
||||
@@ -0,0 +1,208 @@
|
||||
# -*- 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
|
||||
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.resolve_template(client, template, ROSTER_ID) or ""
|
||||
params = export.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.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.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.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.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",
|
||||
]
|
||||
@@ -0,0 +1,100 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""考勤封存数据接口(月度考勤封存表)。
|
||||
|
||||
用法::
|
||||
|
||||
from hr_sdk import HrClient, seal
|
||||
|
||||
client = HrClient(ctx.get_session("hr"))
|
||||
rows = seal.rows(client) # 默认上月,接口原始字段
|
||||
rows = seal.rows(client, month="2026-10")
|
||||
|
||||
只出「拉取」:单位过滤、中文列名、落盘命名都是业务,留在插件。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from typing import List, Optional
|
||||
|
||||
from .config import MAX_PAGES, PAGE_MAX_SIZE, REDSEA
|
||||
from .errors import ConfigError
|
||||
|
||||
GET_CUR_USER_INFO_URL = f"{REDSEA}/PtUsers.mc?method=getCurUserInfo"
|
||||
SEAL_URL = f"{REDSEA}/kqController/getPageAjaxList.mc"
|
||||
SEAL_SQL_ID = "kq_count_leave_wage_SelectV2"
|
||||
|
||||
|
||||
def normalize_month(month: Optional[str] = None) -> str:
|
||||
"""月份归一:``None`` → 上月;``YYYYMM`` → ``YYYY-MM``;其它原样。"""
|
||||
if not month:
|
||||
today = date.today()
|
||||
year, mon = (today.year - 1, 12) if today.month == 1 else (today.year,
|
||||
today.month - 1)
|
||||
return f"{year:04d}-{mon:02d}"
|
||||
text = str(month).strip()
|
||||
if len(text) == 6 and text.isdigit():
|
||||
return f"{text[:4]}-{text[4:]}"
|
||||
return text
|
||||
|
||||
|
||||
def current_user(client) -> dict:
|
||||
"""取当前登录用户信息(含 ``userId``)。"""
|
||||
return client.request_json("POST", GET_CUR_USER_INFO_URL, data={},
|
||||
label="获取当前用户信息")
|
||||
|
||||
|
||||
def rows(client, month: Optional[str] = None, user_id: str = "", *,
|
||||
page_size: int = PAGE_MAX_SIZE, max_pages: int = MAX_PAGES) -> List[dict]:
|
||||
"""按月份拉全集团封存记录(``base_code`` 留空 = 不过滤)。
|
||||
|
||||
Args:
|
||||
month: ``YYYY-MM`` 或 ``YYYYMM``,缺省上月
|
||||
user_id: 操作人 userId;留空自动取当前登录用户
|
||||
page_size/max_pages: 分页参数
|
||||
|
||||
Raises:
|
||||
ConfigError: 拿不到 userId
|
||||
"""
|
||||
if not user_id:
|
||||
user_id = str(current_user(client).get("userId") or "").strip()
|
||||
if not user_id:
|
||||
raise ConfigError("获取当前用户 userId 失败(无法查询封存数据)")
|
||||
|
||||
ym = normalize_month(month)
|
||||
yearmonth = ym.replace("-", "")
|
||||
client.log(f"[INFO] 封存数据月份:{ym}(userId={user_id})")
|
||||
|
||||
def _fetch(page_no: int, size: int):
|
||||
params = {
|
||||
"tree_code": "cq37du", "user_id": user_id, "sqlId": SEAL_SQL_ID,
|
||||
"commonQuery": "", "commonQueryStr": "", "dept_org_name": "",
|
||||
"confirm_state": "", "person_status": "", "identity": "",
|
||||
"staff_status": "", "orgAlias": "", "dept_ids": "", "post_type": "1",
|
||||
"custom_dept_ids": "", "custom_dept_names": "", "STAFF_ID": "",
|
||||
"sealOrgAlias": "", "seal_dept_stru_id": "", "kqDataOperatorName": "",
|
||||
"kqDataOperatorId": "", "base_code": "", "staff_name": "",
|
||||
"yearmonth": yearmonth, "kq_data_state": "",
|
||||
"start": str((page_no - 1) * size), "sortType": "", "sortName": "",
|
||||
"pageNo": page_no, "pageSize": size,
|
||||
}
|
||||
data = client.request_json("POST", SEAL_URL, data=params, label="考勤封存")
|
||||
client.check_state(data, "考勤封存")
|
||||
page_rows = data.get("datas") or []
|
||||
total_page = int(data.get("pageCount") or 0)
|
||||
if page_no == 1:
|
||||
client.log(f"[INFO] 封存共 {data.get('count')} 条 / {total_page} 页")
|
||||
# pageCount 缺失/为 0 时不能提前结束,否则会静默截断
|
||||
return page_rows, bool(total_page and page_no < total_page) or not total_page
|
||||
|
||||
return client.paginate(_fetch, page_size=page_size, max_pages=max_pages, sleep=0.2)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"GET_CUR_USER_INFO_URL",
|
||||
"SEAL_SQL_ID",
|
||||
"SEAL_URL",
|
||||
"current_user",
|
||||
"normalize_month",
|
||||
"rows",
|
||||
]
|
||||
@@ -0,0 +1,83 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""借用会话(SessionLike)与离线 cookie 构造。
|
||||
|
||||
**SDK 不负责按账号登录编排**:插件里一律用宿主注入的会话::
|
||||
|
||||
client = HrClient(ctx.get_session("hr"))
|
||||
|
||||
只有壳子的登录子进程 / CLI / agent 这类「没有宿主」的场景才用
|
||||
:func:`session_from_cookies`。SDK 从不 ``close()`` 借来的 session。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from typing import Any, Optional, Protocol, runtime_checkable
|
||||
|
||||
import requests
|
||||
|
||||
from .config import USER_AGENT, cookies_file
|
||||
from .errors import ConfigError
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class SessionLike(Protocol):
|
||||
"""借来的会话契约(requests.Session 天然满足)。"""
|
||||
|
||||
cookies: Any
|
||||
headers: Any
|
||||
|
||||
def get(self, url, **kwargs): ... # noqa: D401,E704
|
||||
|
||||
def post(self, url, **kwargs): ...
|
||||
|
||||
|
||||
def session_from_cookies(path: str = "", *, domain_filter: str = "37du.co",
|
||||
user_agent: str = USER_AGENT) -> requests.Session:
|
||||
"""从 cookies JSON 构造会话(仅取目标域 cookies)。
|
||||
|
||||
兼容两种文件格式:浏览器导出的 ``[{name,value,domain,path}, ...]`` 列表,
|
||||
以及 ``{"cookies": [...]}`` 包装形式。
|
||||
|
||||
Raises:
|
||||
ConfigError: 文件不存在或没有可用 cookie
|
||||
"""
|
||||
cookie_path = path or cookies_file()
|
||||
if not cookie_path or not os.path.exists(cookie_path):
|
||||
raise ConfigError(f"未找到 HR 登录态 cookies:{cookie_path}(请先登录 HR 平台)")
|
||||
try:
|
||||
with open(cookie_path, encoding="utf-8") as fp:
|
||||
raw = json.load(fp)
|
||||
except (OSError, ValueError) as exc:
|
||||
raise ConfigError(f"cookies 文件无法解析:{cookie_path}({exc})") from None
|
||||
items = raw.get("cookies") if isinstance(raw, dict) else raw
|
||||
if not isinstance(items, list) or not items:
|
||||
raise ConfigError(f"cookies 文件为空:{cookie_path}")
|
||||
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": user_agent,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
count = 0
|
||||
for c in items:
|
||||
if not isinstance(c, dict) or not c.get("name"):
|
||||
continue
|
||||
domain = c.get("domain") or ""
|
||||
if domain_filter and domain_filter not in domain:
|
||||
continue
|
||||
session.cookies.set(c["name"], c.get("value", ""),
|
||||
domain=domain or None, path=c.get("path", "/"))
|
||||
count += 1
|
||||
if not count:
|
||||
raise ConfigError(f"cookies 中没有 {domain_filter} 域的条目:{cookie_path}")
|
||||
return session
|
||||
|
||||
|
||||
def looks_like_login_page(text: Optional[str]) -> bool:
|
||||
"""接口正常返回 JSON;登录页/错误页 → 视为登录态过期。"""
|
||||
return bool(text) and not str(text).lstrip().startswith(("{", "["))
|
||||
|
||||
|
||||
__all__ = ["SessionLike", "looks_like_login_page", "session_from_cookies"]
|
||||
@@ -0,0 +1,115 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""排班接口:个人排班(按工号)/ 部门排班名集合。
|
||||
|
||||
用法::
|
||||
|
||||
from hr_sdk import HrClient, shift
|
||||
|
||||
client = HrClient(ctx.get_session("hr"))
|
||||
rows = shift.person(client, user_id, base_code="37036361",
|
||||
start="2026-11-01", end="2026-11-09")
|
||||
today = shift.day_shift(rows, "2026-11-09") # 当日完整排班名
|
||||
names = shift.department_names(client, "金色印象XX店") # 该部门全部排班名
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import List
|
||||
|
||||
from .config import REDSEA
|
||||
|
||||
#: 个人排班(页面「排班查询」同款)
|
||||
SHIFT_URL = f"{REDSEA}/redmagicapi/rf_p_kq_count_SelectBanci/getExecutePageResult.mc"
|
||||
#: 部门排班(按部门名查该部门全部排班名)
|
||||
WORK_DATE_QUERY_URL = f"{REDSEA}/redmagicapi/rf_s_kq_work_date_query/redApiExec.mc"
|
||||
|
||||
DEFAULT_TREE_CODE = "cq37du"
|
||||
COMPANY_STRU_ID = "596bae33-50e9-11ec-b526-822ff8ed5b28"
|
||||
PAGE_MAX_SIZE = 500
|
||||
WORK_DATE_PAGE_SIZE = 50
|
||||
|
||||
|
||||
def person(client, user_id: str, base_code: str, start: str, end: str, *,
|
||||
treecode: str = DEFAULT_TREE_CODE, page_size: int = PAGE_MAX_SIZE) -> List[dict]:
|
||||
"""按工号 + 日期范围拉全部个人排班记录(``datas`` 分页)。"""
|
||||
def _fetch(page_no: int, size: int):
|
||||
params = {
|
||||
"treecode": treecode, "user_id": user_id, "sqlId": "kq_count_SelectBanci",
|
||||
"commonQuery": "", "commonQueryStr": "", "staff_ids": "",
|
||||
"person_status": "1,4", "post_no": "", "post_type": "1", "post_level": "",
|
||||
"identity": "", "showType": "1", "dateType": "1",
|
||||
"begin": start, "end": end, "bc_date": start,
|
||||
"base_code": base_code, "staff_name": "",
|
||||
"start": str((page_no - 1) * size), "sortType": "", "sortName": "",
|
||||
"pageNo": page_no, "pageSize": size,
|
||||
}
|
||||
data = client.request_json("POST", SHIFT_URL, data=params, label="排班")
|
||||
client.check_state(data, "排班")
|
||||
page_rows = data.get("datas") or []
|
||||
total_page = int(data.get("pageCount") or 0)
|
||||
if page_no == 1:
|
||||
client.log(f"[INFO] 排班共 {data.get('count')} 条 / {total_page} 页")
|
||||
return page_rows, bool(total_page and page_no < total_page)
|
||||
|
||||
return client.paginate(_fetch, page_size=page_size, sleep=0.2)
|
||||
|
||||
|
||||
def day_shift(rows: List[dict], day: str) -> str:
|
||||
"""从排班记录里取某日的完整排班名(列名形如 ``2026-11-09_team_name``)。"""
|
||||
key = f"{day}_team_name"
|
||||
for row in rows or []:
|
||||
value = row.get(key)
|
||||
if value:
|
||||
return str(value).strip()
|
||||
return ""
|
||||
|
||||
|
||||
def department_names(client, org_name: str, *, page_size: int = WORK_DATE_PAGE_SIZE,
|
||||
max_pages: int = 200) -> List[str]:
|
||||
"""按部门名拉该部门全部排班名(``work_date_name``,去重保序)。
|
||||
|
||||
接口查不到集合时返回空列表——是否回退到其它判定由插件决定。
|
||||
"""
|
||||
names: List[str] = []
|
||||
seen = set()
|
||||
for page_no in range(1, max_pages + 1):
|
||||
params = {
|
||||
"stru_tree_code": DEFAULT_TREE_CODE, "struId": COMPANY_STRU_ID,
|
||||
"containLower": "", "work_date_name": "", "paiban_type": "",
|
||||
"holiday_plan_name": "", "org_name": org_name, "work_status": "1",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "desc", "sortName": "create_time",
|
||||
"pageNo": page_no, "pageSize": page_size,
|
||||
}
|
||||
data = client.request_json("POST", WORK_DATE_QUERY_URL, data=params,
|
||||
label="部门排班")
|
||||
if data.get("success") is not True:
|
||||
message = str(data.get("message") or data.get("meg") or data)
|
||||
from .errors import ApiError
|
||||
raise ApiError(f"部门排班返回失败:{message}", payload=data)
|
||||
block = data.get("data") if isinstance(data.get("data"), dict) else {}
|
||||
page_rows = block.get("list") or []
|
||||
if not page_rows:
|
||||
break
|
||||
for rec in page_rows:
|
||||
name = str(rec.get("work_date_name") or "").strip()
|
||||
if name and name not in seen:
|
||||
seen.add(name)
|
||||
names.append(name)
|
||||
if len(page_rows) < page_size:
|
||||
break
|
||||
client.log(f"[INFO] 部门「{org_name}」排班名 {len(names)} 个")
|
||||
return names
|
||||
|
||||
|
||||
__all__ = [
|
||||
"COMPANY_STRU_ID",
|
||||
"DEFAULT_TREE_CODE",
|
||||
"PAGE_MAX_SIZE",
|
||||
"SHIFT_URL",
|
||||
"WORK_DATE_PAGE_SIZE",
|
||||
"WORK_DATE_QUERY_URL",
|
||||
"day_shift",
|
||||
"department_names",
|
||||
"person",
|
||||
]
|
||||
@@ -0,0 +1,137 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""审批流程(待办单据)接口:列表 / 表单业务数据。
|
||||
|
||||
用法::
|
||||
|
||||
from hr_sdk import HrClient, workflow
|
||||
|
||||
client = HrClient(ctx.get_session("hr"))
|
||||
docs = workflow.list_docs(client, subject="请假") # 待办单据
|
||||
form = workflow.form_data(client, docs[0]["businessKey"], docs[0]["formId"])
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
from .config import HR_BASE_URL, REDSEA
|
||||
|
||||
WE_PROCESS_QUERY_URL = f"{REDSEA}/WeProcess.mc?method=getProcessAndData"
|
||||
WF_ACTIVITY_URL = f"{REDSEA}/WfActivity.mc"
|
||||
WORKFORM_ENGINE_URL = f"{REDSEA}/WorkformEngine.mc"
|
||||
DETAIL_URL_PREFIX = f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc?method=goToWorkFlow"
|
||||
|
||||
DEFAULT_PAGE_SIZE = 100
|
||||
MAX_PAGES = 20
|
||||
|
||||
|
||||
# ==================== 待办列表 ====================
|
||||
|
||||
def fetch_page(client, subject: str, *, page_no: int = 1,
|
||||
page_size: int = DEFAULT_PAGE_SIZE) -> dict:
|
||||
"""拉一页待办(title 按标题模糊匹配 ``subject``)。"""
|
||||
params = {
|
||||
"version": "", "PACKAGE_ID": "cq37du", "process_type": "", "defProcessType": "",
|
||||
"struId": "", "rootId": "cq37du", "taskIds": "", "title": subject,
|
||||
"state": "", "startTime": "", "endTime": "",
|
||||
"sortType": "desc", "sortName": "CREATE_TIME",
|
||||
"commonQuery": "[]", "start": str((page_no - 1) * page_size),
|
||||
"pageNo": str(page_no), "pageSize": str(page_size),
|
||||
}
|
||||
data = client.request_json("POST", WE_PROCESS_QUERY_URL, data=params, label="WeProcess")
|
||||
return client.check_state(data, "WeProcess")
|
||||
|
||||
|
||||
def parse_docs(data: dict) -> List[dict]:
|
||||
"""解析待办行为单据字典;``detail_url`` 用 ``reqType=WAIT``(待办审批视图)。"""
|
||||
docs = []
|
||||
for row in data.get("jsonList") or data.get("datas") or []:
|
||||
task_id = str(row.get("taskId") or "").strip()
|
||||
business_key = str(row.get("businessKey") or "").strip()
|
||||
if not task_id or not business_key:
|
||||
continue
|
||||
form_id = str(row.get("formId") or "")
|
||||
process_id = str(row.get("processId") or "")
|
||||
docs.append({
|
||||
"title": str(row.get("title") or "").strip(),
|
||||
"creator": str(row.get("createUserName") or row.get("createUserNameCn")
|
||||
or "").strip(),
|
||||
"time": str(row.get("createTime") or "").strip(),
|
||||
"taskId": task_id,
|
||||
"businessKey": business_key,
|
||||
"processId": process_id,
|
||||
"formId": form_id,
|
||||
"detail_url": (f"{DETAIL_URL_PREFIX}&formId={form_id}"
|
||||
f"&businessKey={business_key}&processId={process_id}"
|
||||
f"&taskId={task_id}&reqType=WAIT&headType=&systemId="),
|
||||
})
|
||||
return docs
|
||||
|
||||
|
||||
def list_docs(client, subject: str, *, page_size: int = DEFAULT_PAGE_SIZE,
|
||||
max_pages: int = MAX_PAGES) -> List[dict]:
|
||||
"""分页拉全部待办并按 ``taskId`` 去重。``subject`` 如 ``请假`` / ``加班``。"""
|
||||
all_docs: List[dict] = []
|
||||
for page_no in range(1, max_pages + 1):
|
||||
data = fetch_page(client, subject, page_no=page_no, page_size=page_size)
|
||||
page_docs = parse_docs(data)
|
||||
client.log(f"[INFO] 待办第 {page_no} 页 {len(page_docs)} 条")
|
||||
all_docs.extend(page_docs)
|
||||
if len(page_docs) < page_size:
|
||||
break
|
||||
|
||||
seen, unique = set(), []
|
||||
for doc in all_docs:
|
||||
key = doc.get("taskId") or doc.get("detail_url")
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
unique.append(doc)
|
||||
if len(unique) != len(all_docs):
|
||||
client.log(f"[WARN] 待办去重:{len(all_docs)} → {len(unique)}")
|
||||
return unique
|
||||
|
||||
|
||||
# ==================== 单据详情 ====================
|
||||
|
||||
def activity(client, task_id: str) -> dict:
|
||||
"""按 taskId 取流程活动信息(含 formId/businessKey)。"""
|
||||
data = client.request_json("POST", f"{WF_ACTIVITY_URL}?method=getWfActivityByTaskId",
|
||||
data={"taskId": task_id}, label="WfActivity")
|
||||
return client.check_state(data, "WfActivity")
|
||||
|
||||
|
||||
def form_data(client, business_key: str, form_id: str) -> Dict[str, object]:
|
||||
"""取表单业务数据(``result`` 字典)。"""
|
||||
data = client.request_json("POST", f"{WORKFORM_ENGINE_URL}?method=getBusinessDate",
|
||||
data={"businessKey": business_key, "formId": form_id},
|
||||
label="WorkformEngine")
|
||||
client.check_state(data, "WorkformEngine")
|
||||
result = data.get("result")
|
||||
if not isinstance(result, dict):
|
||||
from .errors import ApiError
|
||||
raise ApiError(f"WorkformEngine 未返回 result 字典:{str(data)[:200]}", payload=data)
|
||||
return result
|
||||
|
||||
|
||||
def detail_url(form_id: str = "", business_key: str = "", process_id: str = "",
|
||||
task_id: str = "") -> str:
|
||||
"""构造待办审批详情页地址(需要人工点击时用)。"""
|
||||
return (f"{DETAIL_URL_PREFIX}&formId={form_id}&businessKey={business_key}"
|
||||
f"&processId={process_id}&taskId={task_id}&reqType=WAIT&headType=&systemId=")
|
||||
|
||||
|
||||
__all__ = [
|
||||
"DEFAULT_PAGE_SIZE",
|
||||
"DETAIL_URL_PREFIX",
|
||||
"MAX_PAGES",
|
||||
"WE_PROCESS_QUERY_URL",
|
||||
"WF_ACTIVITY_URL",
|
||||
"WORKFORM_ENGINE_URL",
|
||||
"activity",
|
||||
"detail_url",
|
||||
"fetch_page",
|
||||
"form_data",
|
||||
"list_docs",
|
||||
"parse_docs",
|
||||
]
|
||||
@@ -0,0 +1,22 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=64"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "hr_sdk"
|
||||
version = "0.1.3"
|
||||
description = "HR(RedseaPlatform)接口 SDK:通用请求/分页/下载、commonQuery 加密、台账异步导出、花名册/预入职/调动/组织机构"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.9"
|
||||
dependencies = [
|
||||
"requests>=2.28",
|
||||
"pandas>=1.5",
|
||||
"openpyxl>=3.1",
|
||||
"websocket-client>=1.5",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
Repository = "https://github.com/37du/37duAutomation"
|
||||
|
||||
[tool.setuptools]
|
||||
packages = ["hr_sdk"]
|
||||
@@ -0,0 +1,4 @@
|
||||
requests>=2.28
|
||||
pandas>=1.5
|
||||
openpyxl>=3.1
|
||||
websocket-client>=1.5
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "hr_sdk",
|
||||
"name": "HR 系统 SDK",
|
||||
"version": "0.1.3",
|
||||
"description": "HR(RedseaPlatform)接口封装:通用请求/分页/下载、commonQuery 条件加密、台账异步导出(bridge+WS)、花名册/预入职/调动/合同台账/组织机构、审批流程、考勤与排班、封存数据、附件下载、增减员导入(默认 dry-run)、登录原语",
|
||||
"provides": [
|
||||
"hr_sdk"
|
||||
],
|
||||
"deps": [
|
||||
"requests",
|
||||
"pandas",
|
||||
"openpyxl",
|
||||
"websocket"
|
||||
],
|
||||
"python": ">=3.9",
|
||||
"minRuntimeVersion": "",
|
||||
"selftest": "hr_sdk._selftest:main",
|
||||
"api": "api.json"
|
||||
}
|
||||
Reference in New Issue
Block a user