refactor(workflows): 统一替换 yingdao 目录引用为 workflows
1. 将所有文档、代码中对 `yingdao/` 目录的引用替换为 `workflows/`,统一影刀版代码的命名空间 2. 调整 workflows/share 模块内的路径引用与文档注释,确保一致性 3. 同步更新测试代码与配置文件中的旧目录引用
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 后端:场景插件宿主
|
||||
"""
|
||||
@@ -0,0 +1,115 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""平台登录态管理(webhost 宿主壳 · 复用 desktop/shared 单一真源)
|
||||
|
||||
- cookies 与 desktop/影刀版共用同一份共享文件(%LOCALAPPDATA%\37duAutomation\.sessions),
|
||||
任一端登录成功后,webhost 直接复用,无需重复登录
|
||||
- is_online():真实校验(轻量 API 校验 cookies 有效性),不是内存假状态
|
||||
- login():真实登录(cookies 有效则秒级复用;失效则浏览器自动化滑块登录)
|
||||
- build_session():从共享 cookies 构建 requests.Session,供插件直接调用 shared 数据模块
|
||||
|
||||
约定:webhost 只依赖 desktop/shared 的真源登录模块,不复制登录逻辑。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
import requests
|
||||
|
||||
from webhost.backend.shared import hr_login as _hr
|
||||
from webhost.backend.shared import oa_login as _oa
|
||||
from webhost.backend.shared import seal_data_export as _seal
|
||||
|
||||
_LABELS = {"hr": "HR 系统", "oa": "OA 系统"}
|
||||
|
||||
# 共享 cookies:与 desktop/shared 版本使用同一份文件,路径约定保持一致
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
|
||||
# 各平台 cookie 文件与域名(构建 session 时按域过滤)
|
||||
_COOKIE_DEFS = {
|
||||
"hr": {"file": "hr_cookies.json", "domain": "hr.37du.co"},
|
||||
"oa": {"file": "oa_cookies.json", "domain": "oa.37du.co"},
|
||||
}
|
||||
|
||||
# 登录模块(desktop/shared 真源)
|
||||
_LOGIN_MODS = {"hr": _hr, "oa": _oa}
|
||||
|
||||
|
||||
class PlatformAuthError(Exception):
|
||||
"""平台不存在 / 登录态不可用等宿主层错误。"""
|
||||
|
||||
|
||||
def platforms() -> list:
|
||||
return [{"id": pid, "label": label} for pid, label in _LABELS.items()]
|
||||
|
||||
|
||||
def is_online(pid: str) -> bool:
|
||||
"""真实校验平台登录态(发起轻量 API 校验,非内存假状态)。"""
|
||||
if pid == "hr":
|
||||
return _hr._is_hr_session_valid()
|
||||
if pid == "oa":
|
||||
return _oa._is_oa_session_valid()
|
||||
return False
|
||||
|
||||
|
||||
def login(pid: str) -> dict:
|
||||
"""真实登录:cookies 有效则复用(不弹浏览器),失效则浏览器自动化登录。
|
||||
|
||||
返回 {id, label, online, message}
|
||||
"""
|
||||
if pid not in _LOGIN_MODS:
|
||||
raise PlatformAuthError(f"未知平台: {pid}")
|
||||
result = _LOGIN_MODS[pid].ensure_login(force=False)
|
||||
ok = bool(result and result.get("success"))
|
||||
return {"id": pid, "label": _LABELS[pid], "online": ok,
|
||||
"message": (result or {}).get("message", "")}
|
||||
|
||||
|
||||
def build_session(pid: str) -> "requests.Session":
|
||||
"""从共享 cookies 构建已登录 requests.Session(供插件调用 shared 数据模块)。
|
||||
|
||||
若登录态缺失则抛 PlatformAuthError,提示先登录。
|
||||
"""
|
||||
if pid not in _COOKIE_DEFS:
|
||||
raise PlatformAuthError(f"未知平台: {pid}")
|
||||
path = os.path.join(_SESSIONS_DIR, _COOKIE_DEFS[pid]["file"])
|
||||
if not os.path.exists(path):
|
||||
raise PlatformAuthError(
|
||||
f"未找到 {_LABELS[pid]} 登录态({path}),请先在页面点击登录")
|
||||
with open(path, encoding="utf-8") as f:
|
||||
cookies = json.load(f)
|
||||
if not cookies:
|
||||
raise PlatformAuthError(f"{_LABELS[pid]} 登录态为空,请重新登录")
|
||||
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
domain = _COOKIE_DEFS[pid]["domain"]
|
||||
injected: set = set()
|
||||
for c in cookies:
|
||||
if c.get("domain") and domain in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"],
|
||||
domain=c["domain"], path=c.get("path", "/"))
|
||||
injected.add(c["name"])
|
||||
# 兜底:domain 未命中目标域名的 cookie(如别名域名),且 name 尚未注入时,
|
||||
# 按目标域名补注入,避免漏掉关键 cookie 导致接口鉴权失败。
|
||||
for c in cookies:
|
||||
name = c.get("name")
|
||||
if name and name not in injected:
|
||||
session.cookies.set(name, c.get("value", ""),
|
||||
domain=domain, path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
def get_user_id(pid: str) -> str:
|
||||
"""获取平台用户 ID(HR 数据接口大多需要 user_id 参数)。"""
|
||||
if pid == "hr":
|
||||
session = build_session("hr")
|
||||
info = _seal.fetch_cur_user_info(session)
|
||||
return str(info.get("userId") or "")
|
||||
raise PlatformAuthError(f"平台 {pid} 暂不支持取 user_id")
|
||||
@@ -0,0 +1,47 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""WebSocket 广播枢纽:把插件 run 线程产生的 日志/进度/完成 事件实时推给前端。
|
||||
run 在 worker 线程执行,publish 通过 run_coroutine_threadsafe 投递到主事件循环。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import threading
|
||||
from typing import Dict
|
||||
|
||||
|
||||
class Hub:
|
||||
def __init__(self):
|
||||
self._loop: asyncio.AbstractEventLoop | None = None
|
||||
self._clients: list = []
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def bind(self, loop: asyncio.AbstractEventLoop):
|
||||
self._loop = loop
|
||||
|
||||
async def connect(self, websocket) -> None:
|
||||
await websocket.accept()
|
||||
with self._lock:
|
||||
self._clients.append(websocket)
|
||||
try:
|
||||
await websocket.receive_text() # 挂起直到客户端断开
|
||||
finally:
|
||||
with self._lock:
|
||||
self._clients.remove(websocket)
|
||||
|
||||
def publish(self, event: Dict) -> None:
|
||||
if self._loop is None:
|
||||
return
|
||||
asyncio.run_coroutine_threadsafe(self._send(event), self._loop)
|
||||
|
||||
async def _send(self, event: Dict) -> None:
|
||||
with self._lock:
|
||||
clients = list(self._clients)
|
||||
for ws in clients:
|
||||
try:
|
||||
await ws.send_json(event)
|
||||
except Exception:
|
||||
with self._lock:
|
||||
self._clients.remove(ws)
|
||||
|
||||
|
||||
HUB = Hub()
|
||||
@@ -0,0 +1,138 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主:FastAPI 后端。
|
||||
|
||||
- 承载平台登录态(复用 desktop/shared 的共享登录态单一真源,真实登录/校验)
|
||||
- 场景插件注册表 + 表单 schema
|
||||
- 执行 run 到 worker 线程,经 /ws 广播 日志/进度/完成
|
||||
- 挂载前端构建产物(frontend/dist)实现单产物
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import socket
|
||||
import threading
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI, HTTPException, WebSocket
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from pydantic import BaseModel
|
||||
|
||||
from webhost.backend import auth as platform_auth
|
||||
from webhost.backend.hub import HUB
|
||||
from webhost.backend.plugins import PLUGINS # noqa: F401 触发注册
|
||||
from webhost.backend.plugins.base import RunContext
|
||||
|
||||
PORT = 8799
|
||||
DIST = Path(__file__).resolve().parents[1] / "frontend" / "dist"
|
||||
|
||||
# 平台登录态:标签/展示名来自 auth,在线状态实时校验(非内存假状态)
|
||||
PLATFORMS: dict = {p["id"]: {"id": p["id"], "label": p["label"]}
|
||||
for p in platform_auth.platforms()}
|
||||
|
||||
# 运行会话:run_id -> {status, result, error}
|
||||
RUNS: dict = {}
|
||||
RUN_LOCK = threading.Lock()
|
||||
MAX_RUNS = 50 # 运行历史上限,超出丢弃最旧记录,避免内存无限增长
|
||||
|
||||
|
||||
class RunReq(BaseModel):
|
||||
plugin_id: str
|
||||
fields: dict = {}
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
HUB.bind(asyncio.get_running_loop())
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(title="37du Web Host", lifespan=lifespan)
|
||||
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
|
||||
|
||||
|
||||
def _plugin_schema(p) -> dict:
|
||||
return {"id": p.id, "name": p.name, "version": p.version,
|
||||
"description": p.description, "uses_month": getattr(p, "uses_month", False),
|
||||
"fields": p.fields}
|
||||
|
||||
|
||||
@app.get("/api/meta")
|
||||
def meta() -> dict:
|
||||
plugins = [_plugin_schema(p) for p in PLUGINS]
|
||||
platforms = [{"id": pid, "label": m["label"], "online": platform_auth.is_online(pid)}
|
||||
for pid, m in PLATFORMS.items()]
|
||||
return {"appName": "37du 业务场景工具集", "platforms": platforms, "plugins": plugins}
|
||||
|
||||
|
||||
@app.post("/api/platforms/{pid}/login")
|
||||
def login(pid: str) -> dict:
|
||||
"""真实登录:复用有效 cookies 或浏览器自动化登录(滑块),秒级~分钟级阻塞。"""
|
||||
plat = PLATFORMS.get(pid)
|
||||
if not plat:
|
||||
raise HTTPException(404, "平台不存在")
|
||||
return platform_auth.login(pid)
|
||||
|
||||
|
||||
def _run_target(plugin, fields: dict, run_id: str) -> None:
|
||||
ctx = RunContext(HUB, run_id=run_id, plugin_id=plugin.id, auth=platform_auth)
|
||||
try:
|
||||
result = plugin.run(fields, ctx)
|
||||
with RUN_LOCK:
|
||||
RUNS[run_id] = {"status": "done", "result": result, "error": None}
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": True})
|
||||
except Exception as e: # noqa: BLE001 全局兜底,推送失败给前端
|
||||
with RUN_LOCK:
|
||||
RUNS[run_id] = {"status": "error", "result": None, "error": str(e)}
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": str(e)})
|
||||
|
||||
|
||||
@app.post("/api/runs", status_code=202)
|
||||
def start_run(req: RunReq) -> dict:
|
||||
try:
|
||||
plugin = PLUGINS.find(req.plugin_id)
|
||||
except KeyError:
|
||||
raise HTTPException(404, "插件不存在")
|
||||
run_id = uuid.uuid4().hex
|
||||
with RUN_LOCK:
|
||||
if len(RUNS) >= MAX_RUNS:
|
||||
RUNS.pop(next(iter(RUNS))) # dict 有序:弹出最老的记录
|
||||
RUNS[run_id] = {"status": "running", "result": None, "error": None}
|
||||
HUB.publish({"t": "run_start", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"at": datetime.now().strftime("%H:%M:%S")})
|
||||
threading.Thread(target=_run_target, args=(plugin, req.fields, run_id),
|
||||
daemon=True, name=f"run-{plugin.id}").start()
|
||||
return {"run_id": run_id}
|
||||
|
||||
|
||||
@app.get("/api/runs/{run_id}")
|
||||
def get_run(run_id: str) -> dict:
|
||||
with RUN_LOCK:
|
||||
run = RUNS.get(run_id)
|
||||
if not run:
|
||||
raise HTTPException(404, "运行不存在")
|
||||
return run
|
||||
|
||||
|
||||
@app.websocket("/ws")
|
||||
async def ws(websocket: WebSocket):
|
||||
await HUB.connect(websocket)
|
||||
|
||||
|
||||
if DIST.exists():
|
||||
app.mount("/", StaticFiles(directory=str(DIST), html=True), name="web")
|
||||
|
||||
|
||||
def _port_free(port: int) -> bool:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
return s.connect_ex(("127.0.0.1", port)) != 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
print(f"[webhost] port {PORT} free = {_port_free(PORT)}")
|
||||
uvicorn.run(app, host="127.0.0.1", port=PORT, log_level="info")
|
||||
@@ -0,0 +1,68 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""插件注册表——目录动态扫描加载。
|
||||
|
||||
加载约定(扫描协议):
|
||||
- 插件形态:plugins/ 下的**目录包**(含 __init__.py,在其中定义 ScenePlugin 子类并
|
||||
PLUGINS.append,如 seal_check/)。顶层单模块(*.py)仅用于兼容旧 demo/platform_check。
|
||||
- 私有辅助文件**必须用 `_` 前缀**(如 _utils.py、_common/),扫描时一律排除,
|
||||
避免被误当作插件 import。
|
||||
- 只有继承 ScenePlugin 并通过 PLUGINS.append 注册的才会进入注册表;_ 前缀约定
|
||||
确保辅助模块根本不会被 import,杜绝误注册与无用告警。
|
||||
- 同名冲突:目录优先于同名 .py(先收目录再收 py,同名仅保留目录)。
|
||||
- 单个插件加载失败记 ERROR 并保留堆栈首行后跳过,不拖垮整体启动。
|
||||
|
||||
阶段二(权限):把「有权限的插件名」传给 load_plugins(allowed) 即可,无权限不 import。
|
||||
届时触发点建议从「import 副作用」改为由 main.py 在应用启动时显式调用 load_plugins(),
|
||||
以便每次按登录账号动态决定允许集。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import logging
|
||||
import pathlib
|
||||
import traceback
|
||||
|
||||
from webhost.backend.plugins.base import PLUGINS # noqa: F401 由 base 构造空注册表
|
||||
|
||||
_PLUGINS_ROOT = pathlib.Path(__file__).resolve().parent
|
||||
_PKG_NAME = __name__
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _discover_modules() -> list:
|
||||
"""发现插件模块:目录优先,排除 base 与 `_` 前缀的私有文件。"""
|
||||
names: list = []
|
||||
seen: set = set()
|
||||
for d in sorted(_PLUGINS_ROOT.iterdir()):
|
||||
if not d.is_dir() or d.name.startswith("_") or d.name == "__pycache__":
|
||||
continue
|
||||
if (d / "__init__.py").exists():
|
||||
names.append(d.name)
|
||||
seen.add(d.name)
|
||||
for f in sorted(_PLUGINS_ROOT.glob("*.py")):
|
||||
if f.name in ("__init__.py", "base.py") or f.name.startswith("_"):
|
||||
continue
|
||||
if f.stem not in seen: # 已被同名目录占用则跳过
|
||||
names.append(f.stem)
|
||||
return names
|
||||
|
||||
|
||||
def load_plugins(allowed: set = None) -> None:
|
||||
"""动态加载插件。allowed 为空 = 全量;否则仅加载白名单内的插件。
|
||||
|
||||
单插件加载失败记 ERROR(含堆栈首行)后跳过,不拖垮整体启动。
|
||||
"""
|
||||
allowed = allowed if allowed is not None else set()
|
||||
for _mod in _discover_modules():
|
||||
if allowed and _mod not in allowed:
|
||||
_LOGGER.info("插件 %s 不在权限白名单,跳过加载", _mod)
|
||||
continue
|
||||
try:
|
||||
importlib.import_module(f"{_PKG_NAME}.{_mod}")
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.error("插件 %s 加载失败,已跳过\n%s", _mod,
|
||||
traceback.format_exc(limit=1))
|
||||
|
||||
|
||||
# 触发加载(阶段一:全量;阶段二改由 main.py 显式调用并传入权限白名单)
|
||||
load_plugins()
|
||||
@@ -0,0 +1,70 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""场景插件抽象:后端 `run` 承载真实逻辑(浏览器自动化/登录态等),
|
||||
前端按 `fields` 渲染通用表单,执行过程经 `RunContext.log/progress` 推送到 WebSocket。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import List
|
||||
|
||||
|
||||
class RunContext:
|
||||
"""传给插件 `run` 的执行上下文:把日志/进度实时推给前端,并提供共享登录态访问。"""
|
||||
|
||||
def __init__(self, hub, run_id: str, plugin_id: str, auth=None):
|
||||
self._hub = hub
|
||||
self._auth = auth # webhost.backend.auth 模块(宿主注入的共享登录态)
|
||||
self.run_id = run_id
|
||||
self.plugin_id = plugin_id
|
||||
|
||||
def log(self, msg: str, level: str = "INFO"):
|
||||
self._hub.publish({
|
||||
"t": "log", "run_id": self.run_id, "plugin_id": self.plugin_id,
|
||||
"level": level, "msg": msg,
|
||||
})
|
||||
|
||||
def progress(self, pct: int):
|
||||
self._hub.publish({
|
||||
"t": "progress", "run_id": self.run_id,
|
||||
"plugin_id": self.plugin_id, "pct": int(max(0, min(100, pct))),
|
||||
})
|
||||
|
||||
# ---------- 共享登录态 ----------
|
||||
def get_session(self, platform: str) -> "requests.Session":
|
||||
"""获取指定平台的共享登录 session,可直接传给 shared 数据模块。"""
|
||||
if not self._auth:
|
||||
raise RuntimeError("宿主未注入登录态服务,无法构建 session")
|
||||
return self._auth.build_session(platform)
|
||||
|
||||
def get_user_id(self, platform: str) -> str:
|
||||
"""获取指定平台的用户 ID(HR 数据接口大多需要 user_id 参数)。"""
|
||||
if not self._auth:
|
||||
raise RuntimeError("宿主未注入登录态服务,无法获取 user_id")
|
||||
return self._auth.get_user_id(platform)
|
||||
|
||||
|
||||
class ScenePlugin:
|
||||
"""场景插件基类。新增场景:子类填 id/name/fields/run 并注册到 plugins 列表。"""
|
||||
|
||||
id: str = ""
|
||||
name: str = ""
|
||||
version: str = "1.0.0"
|
||||
description: str = ""
|
||||
platform: str = "" # 所需平台登录态:hr / oa / ""(无需登录)
|
||||
uses_month: bool = False # 是否需要底座页眉的“执行月份”(前端据此注入 ref_month 字段)
|
||||
# 表单字段定义:[{key,label,type,default,options}]
|
||||
# type ∈ int | text | select
|
||||
fields: List[dict] = []
|
||||
|
||||
def run(self, fields: dict, ctx: RunContext) -> dict:
|
||||
raise NotImplementedError(f"插件 {self.id} 未实现 run")
|
||||
|
||||
|
||||
class _Registry(list):
|
||||
def find(self, pid: str) -> ScenePlugin:
|
||||
for p in self:
|
||||
if p.id == pid:
|
||||
return p
|
||||
raise KeyError(pid)
|
||||
|
||||
|
||||
PLUGINS: _Registry = _Registry()
|
||||
@@ -0,0 +1,39 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""示例场景插件:证明「后端 run + 前端通用表单 + 实时日志/进度」的插件化链路可用。
|
||||
后续真实场景(如考勤月报封存检查)按同样方式接入即可。
|
||||
"""
|
||||
import time
|
||||
|
||||
from webhost.backend.plugins.base import PLUGINS, RunContext, ScenePlugin
|
||||
|
||||
|
||||
class DemoPlugin(ScenePlugin):
|
||||
id = "demo"
|
||||
name = "示例检查"
|
||||
version = "1.0.0"
|
||||
description = "跑一个带进度与日志的假任务,用于验证插件链路。"
|
||||
fields = [
|
||||
{"key": "steps", "label": "步数", "type": "int", "default": 3},
|
||||
{"key": "mode", "label": "模式", "type": "select",
|
||||
"options": ["正常", "中途报错"], "default": "正常"},
|
||||
]
|
||||
|
||||
def run(self, fields: dict, ctx: RunContext) -> dict:
|
||||
steps = max(1, min(50, int(fields.get("steps", 3))))
|
||||
mode = fields.get("mode", "正常")
|
||||
ctx.log(f"开始示例检查:{steps} 步,模式={mode}")
|
||||
for i in range(1, steps + 1):
|
||||
time.sleep(0.6)
|
||||
ctx.progress(int(i / steps * 90))
|
||||
ctx.log(f"第 {i}/{steps} 步完成")
|
||||
if mode == "中途报错":
|
||||
raise RuntimeError("按模式设置的报错,用于演示失败处理")
|
||||
ctx.progress(100)
|
||||
ctx.log("示例检查完成")
|
||||
return {
|
||||
"summary": f"共执行 {steps} 步,全部正常",
|
||||
"rows": [[i, f"结果 {i}"] for i in range(1, steps + 1)],
|
||||
}
|
||||
|
||||
|
||||
PLUGINS.append(DemoPlugin())
|
||||
@@ -0,0 +1,59 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""登录态自检(共享登录态 + 共享模块验证)
|
||||
|
||||
- 校验 HR / OA 共享登录态(真实 API 校验,非内存假状态)
|
||||
- 若 HR 在线:实测共享数据模块(desktop/shared/seal_data_export)能否构建 session、
|
||||
取 userId 并拉取指定月份封存数据 —— 验证 webhost 复用共享模块的完整链路
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from webhost.backend.shared import seal_data_export as _seal
|
||||
from webhost.backend import auth as platform_auth
|
||||
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
||||
|
||||
|
||||
class PlatformCheck(ScenePlugin):
|
||||
id = "platform_check"
|
||||
name = "登录态自检"
|
||||
version = "1.0.0"
|
||||
description = "校验 HR/OA 共享登录态,并实测共享模块(封存数据拉取)可用性"
|
||||
platform = ""
|
||||
|
||||
def run(self, fields: dict, ctx) -> dict:
|
||||
report = {}
|
||||
for pid in ("hr", "oa"):
|
||||
online = platform_auth.is_online(pid)
|
||||
label = platform_auth._LABELS[pid]
|
||||
report[pid] = "已登录" if online else "未登录"
|
||||
ctx.log(f"[共享登录态] {label}:{'已登录' if online else '未登录'}")
|
||||
|
||||
seal_info = None
|
||||
if report.get("hr") == "已登录":
|
||||
ym = str(fields.get("_month") or datetime.now().strftime("%Y-%m"))
|
||||
try:
|
||||
ctx.log("开始实测共享模块 seal_data_export……")
|
||||
ctx.progress(40)
|
||||
session = ctx.get_session("hr")
|
||||
user_id = ctx.get_user_id("hr")
|
||||
ctx.log(f"构建 session 成功,HR userId = {user_id or '(空)'}")
|
||||
page = _seal.fetch_seal_page(
|
||||
session, user_id, ym, page_no=1, page_size=5)
|
||||
rows = page.get("datas") or []
|
||||
seal_info = f"{ym} 返回 {len(rows)} 条(state={page.get('state')})"
|
||||
ctx.log(f"[共享模块] 封存数据拉取成功:{seal_info}")
|
||||
ctx.progress(100)
|
||||
except Exception as e: # noqa: BLE001
|
||||
ctx.log(f"[共享模块] 调用失败:{e}", level="ERROR")
|
||||
seal_info = f"error: {e}"
|
||||
else:
|
||||
ctx.log("HR 未登录,跳过共享模块实测(请先点击顶部 HR 登录)")
|
||||
|
||||
summary = ";".join(f"{platform_auth._LABELS[k]}={v}" for k, v in report.items())
|
||||
if seal_info:
|
||||
summary += f";封存模块:{seal_info}"
|
||||
return {"summary": summary, "report": report, "seal": seal_info}
|
||||
|
||||
|
||||
PLUGINS.append(PlatformCheck())
|
||||
@@ -0,0 +1,115 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""考勤月报封存检查 - webhost 场景插件(XQ0011)
|
||||
|
||||
流程:填写检查月份与正休规则 → 一键执行(拉取数据 + 运行五项检查 + 自动导出多 Sheet Excel)。
|
||||
复用 desktop/shared 数据真源(由宿主共享登录态注入 session/user_id),不内置登录逻辑。
|
||||
"""
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from webhost.backend.plugins.base import PLUGINS, RunContext, ScenePlugin
|
||||
|
||||
from webhost.backend.plugins.seal_check import config
|
||||
from webhost.backend.plugins.seal_check.data import (
|
||||
fetch_compare_diffs, fetch_org_name_map, fetch_roster_data,
|
||||
fetch_seal_rows, fetch_shift_batch,
|
||||
)
|
||||
from webhost.backend.plugins.seal_check.logic import LeaveRuleEngine, run_all_checks
|
||||
from webhost.backend.plugins.seal_check.report import CHECK_TAB_TITLES, export_report
|
||||
|
||||
|
||||
def _default_month() -> str:
|
||||
last_end = datetime.now().replace(day=1) - timedelta(days=1)
|
||||
return f"{last_end.year:04d}-{last_end.month:02d}"
|
||||
|
||||
|
||||
class SealCheckPlugin(ScenePlugin):
|
||||
id = "seal_check"
|
||||
name = "考勤月报封存检查"
|
||||
version = "1.0.0"
|
||||
description = "填写每月正休规则,一键执行五项检查并导出多 Sheet Excel 报告"
|
||||
platform = "hr"
|
||||
uses_month = True # 月份由底座页眉统一提供(注入 ref_month),插件自身不再单列
|
||||
fields = [
|
||||
{"key": "fixed_rest_days", "label": "固休应休天数", "type": "int",
|
||||
"default": config.DEFAULT_RULES["fixed_rest_days"]},
|
||||
{"key": "size_rest_days", "label": "大小休应休天数", "type": "int",
|
||||
"default": config.DEFAULT_RULES["size_rest_days"]},
|
||||
{"key": "quota_rest_days", "label": "限额排休上限", "type": "int",
|
||||
"default": config.DEFAULT_RULES["quota_rest_days"]},
|
||||
]
|
||||
|
||||
def run(self, fields: dict, ctx: RunContext) -> dict:
|
||||
month_str = str(fields.get("ref_month") or _default_month()).strip()
|
||||
year, month = int(month_str[:4]), int(month_str[5:7].strip())
|
||||
yearmonth = f"{year:04d}{month:02d}"
|
||||
month_display = f"{year:04d}-{month:02d}"
|
||||
|
||||
engine = LeaveRuleEngine(
|
||||
size_rest_days=int(fields.get("size_rest_days") or config.DEFAULT_RULES["size_rest_days"]),
|
||||
fixed_rest_days=int(fields.get("fixed_rest_days") or config.DEFAULT_RULES["fixed_rest_days"]),
|
||||
quota_rest_days=int(fields.get("quota_rest_days") or config.DEFAULT_RULES["quota_rest_days"]),
|
||||
)
|
||||
|
||||
session = ctx.get_session("hr")
|
||||
user_id = ctx.get_user_id("hr")
|
||||
|
||||
ctx.log(f"开始考勤月报封存检查:{month_display}")
|
||||
ctx.progress(5)
|
||||
|
||||
ctx.log("拉取考勤封存数据……")
|
||||
seal_rows = fetch_seal_rows(session, user_id, yearmonth)
|
||||
ctx.progress(30)
|
||||
ctx.log(f"封存数据 {len(seal_rows)} 人")
|
||||
|
||||
ctx.log("拉取组织表……")
|
||||
org_name_map = fetch_org_name_map(session)
|
||||
ctx.progress(45)
|
||||
ctx.log(f"组织 {len(org_name_map)} 条")
|
||||
|
||||
ctx.log("导出花名册(获取职位序列)……")
|
||||
seq_map, in_service_records = fetch_roster_data(session)
|
||||
ctx.progress(60)
|
||||
ctx.log(f"花名册职位序列 {len(seq_map)} 人,在职 {len(in_service_records)} 人")
|
||||
|
||||
ctx.log("批量拉取排班(计算应出勤天数)……")
|
||||
shift_map = fetch_shift_batch(session, user_id, yearmonth)
|
||||
ctx.progress(80)
|
||||
ctx.log(f"排班应出勤 {len(shift_map)} 人")
|
||||
|
||||
diff_rows, diff_note = fetch_compare_diffs(session, user_id, yearmonth)
|
||||
ctx.progress(90)
|
||||
|
||||
notes = [diff_note] if diff_note else []
|
||||
ctx.log("运行全部检查……")
|
||||
result = run_all_checks(
|
||||
seal_rows=seal_rows,
|
||||
org_name_map=org_name_map,
|
||||
seq_map=seq_map,
|
||||
in_service_records=in_service_records,
|
||||
shift_map=shift_map,
|
||||
engine=engine,
|
||||
year=year, month=month,
|
||||
diff_rows=diff_rows, diff_fields=None, notes=notes,
|
||||
)
|
||||
ctx.progress(95)
|
||||
|
||||
path = export_report(result["rows"], month_display, result["notes"])
|
||||
ctx.progress(100)
|
||||
|
||||
for note in result["notes"]:
|
||||
ctx.log(f"[提示] {note}")
|
||||
summary = ";".join(
|
||||
f"{CHECK_TAB_TITLES[i]} {len(result['rows'].get(i, []))} 条"
|
||||
for i in range(1, 6))
|
||||
ctx.log(f"结果汇总:{summary}")
|
||||
ctx.log(f"===== 检查完成,报告已导出:{path} =====")
|
||||
|
||||
return {
|
||||
"summary": summary,
|
||||
"path": path,
|
||||
"rows": {str(k): v for k, v in result["rows"].items()},
|
||||
"notes": result["notes"],
|
||||
}
|
||||
|
||||
|
||||
PLUGINS.append(SealCheckPlugin())
|
||||
@@ -0,0 +1,35 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""考勤月报封存检查(webhost 场景插件)配置。
|
||||
|
||||
与 desktop/plugins/seal_check/config.py 保持同步(影刀/桌面版为单一真源)。
|
||||
"""
|
||||
import os
|
||||
|
||||
# ==================== 输出目录 ====================
|
||||
SAVE_DIR = os.getenv("monthly_seal_save_dir") or r"D:\资料\人资\考勤异常"
|
||||
|
||||
# 花名册导出(取职位序列,服务端已翻译中文)
|
||||
ROSTER_EXPORT_PATH = os.path.join(SAVE_DIR, "员工花名册_桌面版.xlsx")
|
||||
ROSTER_DOWNLOAD_DIR = os.path.join(SAVE_DIR, "花名册下载")
|
||||
|
||||
# ==================== 每月正休规则(默认值,界面可覆盖) ====================
|
||||
DEFAULT_RULES = {
|
||||
"size_rest_days": 6, # 大小休 应休天数
|
||||
"fixed_rest_days": 5, # 固休 应休天数
|
||||
"quota_rest_days": 8, # 天数限额排休 上限
|
||||
}
|
||||
|
||||
# 集团总部职能部门(大小休)
|
||||
GROUP_HEADQUARTER_UNITS = (
|
||||
"财务管理部",
|
||||
"集团管理中心",
|
||||
"集团营建中心",
|
||||
)
|
||||
|
||||
# ==================== 排班接口 ====================
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
SHIFT_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_p_kq_count_SelectBanci/getExecutePageResult.mc"
|
||||
PAGE_MAX_SIZE = 500
|
||||
|
||||
# 排班休息日判定:当日班次名({日期}_bc_name)等于该值视为休息
|
||||
REST_SHIFT_NAME = "休息"
|
||||
@@ -0,0 +1,160 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""考勤月报封存检查 - 数据拉取(webhost 场景插件)
|
||||
|
||||
数据真源复用 desktop/shared(与桌面/影刀版单一真源一致),传入宿主构建的
|
||||
requests.Session / user_id 即可,不内置任何登录逻辑。
|
||||
session 由 webhost 宿主的共享登录态提供(RunContext.get_session / get_user_id)。
|
||||
"""
|
||||
import calendar
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Dict, List, Tuple
|
||||
|
||||
from webhost.backend.shared import org_export, roster_export_api, seal_data_export
|
||||
|
||||
from webhost.backend.plugins.seal_check import config
|
||||
|
||||
# hr_request_json:统一做全局重试(3次) + 登录态失效判定(复用桌面 shared 真源)
|
||||
hr_request_json = seal_data_export.hr_request_json
|
||||
|
||||
|
||||
# ==================== 通用工具 ====================
|
||||
def _clean(v) -> str:
|
||||
if v is None:
|
||||
return ""
|
||||
s = str(v).strip()
|
||||
if s.lower() in ("nan", "none", "nat"):
|
||||
return ""
|
||||
if s.endswith(".0"):
|
||||
s = s[:-2]
|
||||
return s
|
||||
|
||||
|
||||
def _norm_path(p: str) -> str:
|
||||
p = _clean(p).replace("\\", "/").strip("/")
|
||||
if p.startswith("集团/"):
|
||||
p = p[len("集团/"):]
|
||||
elif p == "集团":
|
||||
p = ""
|
||||
return p.strip("/")
|
||||
|
||||
|
||||
def last_month_ym(today: datetime = None) -> str:
|
||||
today = today or datetime.now()
|
||||
last_end = today.replace(day=1) - timedelta(days=1)
|
||||
return f"{last_end.year:04d}{last_end.month:02d}"
|
||||
|
||||
|
||||
# ==================== 1. 封存数据 ====================
|
||||
def fetch_seal_rows(session, user_id: str, yearmonth: str) -> List[dict]:
|
||||
rows = seal_data_export.fetch_all_seal(session, user_id, yearmonth)
|
||||
return seal_data_export._filter_by_unit(rows)
|
||||
|
||||
|
||||
# ==================== 2. 组织表 ====================
|
||||
def fetch_org_name_map(session) -> Dict[str, str]:
|
||||
"""组织全路径 -> 组织名称(用于解析组织类型)。"""
|
||||
rows = org_export.fetch_all_orgs(session)
|
||||
name_map: Dict[str, str] = {}
|
||||
for rec in rows:
|
||||
path = _norm_path(rec.get("pt_structure.ORG_FULL_PATH"))
|
||||
name = _clean(rec.get("pt_organzation.ORG_NAME"))
|
||||
if path and name:
|
||||
name_map[path] = name
|
||||
return name_map
|
||||
|
||||
|
||||
# ==================== 3. 花名册(导出接口,职位序列已翻译) ====================
|
||||
def fetch_roster_data(session) -> Tuple[Dict[str, str], List[dict]]:
|
||||
"""导出花名册(在职+离职)。返回 (seq_map, in_service_records)。"""
|
||||
import pandas as pd
|
||||
|
||||
path = roster_export_api.export_roster(
|
||||
output_path=config.ROSTER_EXPORT_PATH,
|
||||
download_dir=config.ROSTER_DOWNLOAD_DIR,
|
||||
template_name="员工基础信息",
|
||||
statuses=["在职", "离职"],
|
||||
)
|
||||
df = pd.read_excel(path, dtype=str)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
|
||||
seq_map: Dict[str, str] = {}
|
||||
in_service_records: List[dict] = []
|
||||
for _, r in df.iterrows():
|
||||
code = _clean(r.get("工号"))
|
||||
seq = _clean(r.get("职位序列"))
|
||||
if code:
|
||||
seq_map[code] = seq
|
||||
if _clean(r.get("在职状态")) == "在职":
|
||||
in_service_records.append({
|
||||
"工号": code,
|
||||
"姓名": _clean(r.get("姓名")),
|
||||
"所属单位": _clean(r.get("所属单位")),
|
||||
"一级部门": _clean(r.get("一级部门")),
|
||||
"二级部门": _clean(r.get("二级部门")),
|
||||
"三级部门": _clean(r.get("三级部门")),
|
||||
"四级部门": _clean(r.get("四级部门")),
|
||||
"五级部门": _clean(r.get("五级部门")),
|
||||
})
|
||||
return seq_map, in_service_records
|
||||
|
||||
|
||||
# ==================== 4. 排班(批量导出) ====================
|
||||
def fetch_shift_batch(session, user_id: str, yearmonth: str) -> Dict[str, int]:
|
||||
"""批量拉取某月全集团排班,返回 {工号: 应出勤天数}。
|
||||
|
||||
base_code 留空 = 全集团批量;每条记录 = 一个员工整月排班,
|
||||
逐日列 key 为 "YYYY-MM-DD_bc_name",休息日判定 bc_name == config.REST_SHIFT_NAME。
|
||||
"""
|
||||
ym = str(yearmonth)
|
||||
year, month = int(ym[:4]), int(ym[4:6])
|
||||
days_in_month = calendar.monthrange(year, month)[1]
|
||||
begin = f"{year:04d}-{month:02d}-01"
|
||||
end = f"{year:04d}-{month:02d}-{days_in_month:02d}"
|
||||
|
||||
all_rows: List[dict] = []
|
||||
page_no = 1
|
||||
while True:
|
||||
params = {
|
||||
"treecode": "cq37du", "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": begin, "end": end, "bc_date": begin,
|
||||
"base_code": "", "staff_name": "",
|
||||
"start": str((page_no - 1) * config.PAGE_MAX_SIZE),
|
||||
"sortType": "", "sortName": "",
|
||||
"pageNo": page_no, "pageSize": config.PAGE_MAX_SIZE,
|
||||
}
|
||||
data = hr_request_json(session, "POST", config.SHIFT_URL, params, "排班批量")
|
||||
if data.get("state") != "1":
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
# 分页保护:pageCount 缺失/为 0 时不能提前 break,否则会静默截断数据
|
||||
page_count = data.get("pageCount") or 0
|
||||
if page_count and page_no >= page_count:
|
||||
break
|
||||
if len(page_list) < config.PAGE_MAX_SIZE:
|
||||
break
|
||||
page_no += 1
|
||||
|
||||
result: Dict[str, int] = {}
|
||||
for rec in all_rows:
|
||||
code = _clean(rec.get("base_code"))
|
||||
if not code:
|
||||
continue
|
||||
work_days = 0
|
||||
for d in range(1, days_in_month + 1):
|
||||
bc = _clean(rec.get(f"{year:04d}-{month:02d}-{d:02d}_bc_name"))
|
||||
if bc and bc != config.REST_SHIFT_NAME:
|
||||
work_days += 1
|
||||
result[code] = work_days
|
||||
return result
|
||||
|
||||
|
||||
# ==================== 5. 对比差异(检查3,接口待封装) ====================
|
||||
def fetch_compare_diffs(session, user_id: str, yearmonth: str) -> Tuple[List[dict], str]:
|
||||
"""考勤月报封存「对比」差异数据;接口未封装前返回空 + 提示。"""
|
||||
return [], "检查3「封存值是否最新」的对比接口尚未封装,本次跳过该检查,请在数据层补充接口后启用"
|
||||
@@ -0,0 +1,279 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""考勤月报封存检查 - 规则引擎与五项检查(webhost 场景插件)
|
||||
|
||||
与 desktop/plugins/seal_check/logic.py 保持同步(桌面版为单一真源)。
|
||||
|
||||
规则完全由运行人员每月在界面录入的天数值驱动:
|
||||
- 固休:应休 = fixed_rest_days
|
||||
- 大小休:应休 = size_rest_days(实际允许 size_rest_days ~ 8 天区间)
|
||||
- 天数限额排休:应休 <= quota_rest_days(上限)
|
||||
"""
|
||||
import calendar
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime
|
||||
from typing import Dict, List
|
||||
|
||||
from webhost.backend.plugins.seal_check import config
|
||||
|
||||
# ==================== 异常名单统一列 ====================
|
||||
OUTPUT_COLUMNS = [
|
||||
"37工号", "姓名", "月报检查月份", "异常类型", "所属单位",
|
||||
"一级部门", "二级部门", "三级部门", "四级部门", "五级部门",
|
||||
]
|
||||
|
||||
TYPE_1 = "当月在职天数有差缺排班"
|
||||
TYPE_3 = "考勤封存非最新值,请重新封存"
|
||||
TYPE_4 = "出勤天数大于当月应出勤天数"
|
||||
TYPE_5 = "考勤月报未封存,请处理"
|
||||
|
||||
|
||||
# ==================== 规则引擎 ====================
|
||||
@dataclass
|
||||
class RestRule:
|
||||
rule_type: str # 大小休 / 固休 / 限额 / 未知
|
||||
days: int = None # 应休天数(限额为 None)
|
||||
max_days: int = None # 限额上限
|
||||
desc: str = "" # 规则描述(异常类型)
|
||||
|
||||
def validate(self, rest_days: int) -> bool:
|
||||
if self.rule_type == "固休":
|
||||
return rest_days == self.days
|
||||
if self.rule_type == "大小休":
|
||||
return self.days <= rest_days <= 8
|
||||
if self.rule_type == "限额":
|
||||
return rest_days <= self.max_days
|
||||
return True
|
||||
|
||||
|
||||
def _normalize_rest_days(v) -> int:
|
||||
try:
|
||||
s = str(v).strip()
|
||||
if s in ("", "nan", "None"):
|
||||
return -1
|
||||
if s.endswith(".0"):
|
||||
s = s[:-2]
|
||||
return int(float(s))
|
||||
except (TypeError, ValueError):
|
||||
return -1
|
||||
|
||||
|
||||
class LeaveRuleEngine:
|
||||
def __init__(self, size_rest_days=6, fixed_rest_days=5, quota_rest_days=8):
|
||||
self.size_rest_days = int(size_rest_days)
|
||||
self.fixed_rest_days = int(fixed_rest_days)
|
||||
self.quota_rest_days = int(quota_rest_days)
|
||||
|
||||
def query(self, unit: str, org_label: str = "", sequence: str = "") -> RestRule:
|
||||
if "技师" in sequence:
|
||||
return RestRule("限额", max_days=self.quota_rest_days,
|
||||
desc=f"当月排休不满足<={self.quota_rest_days}天规则")
|
||||
if unit == "金色湖畔事业部":
|
||||
return RestRule("固休", days=self.fixed_rest_days,
|
||||
desc=f"当月排休不满足={self.fixed_rest_days}天规则")
|
||||
if unit in config.GROUP_HEADQUARTER_UNITS:
|
||||
return RestRule("大小休", days=self.size_rest_days,
|
||||
desc=f"当月排休不满足>={self.size_rest_days}天<=8天规则")
|
||||
if unit == "金色印象事业部":
|
||||
if "事业部" in org_label:
|
||||
return RestRule("大小休", days=self.size_rest_days,
|
||||
desc=f"当月排休不满足>={self.size_rest_days}天<=8天规则")
|
||||
return RestRule("固休", days=self.fixed_rest_days,
|
||||
desc=f"当月排休不满足={self.fixed_rest_days}天规则")
|
||||
return RestRule("未知")
|
||||
|
||||
def check(self, unit, org_label, sequence, rest_days):
|
||||
rule = self.query(unit, org_label, sequence)
|
||||
days = _normalize_rest_days(rest_days)
|
||||
if rule.rule_type == "未知" or days < 0:
|
||||
return False, rule, days
|
||||
return (not rule.validate(days)), rule, days
|
||||
|
||||
|
||||
# ==================== 检查工具 ====================
|
||||
def _clean(v) -> str:
|
||||
if v is None:
|
||||
return ""
|
||||
s = str(v).strip()
|
||||
if s.lower() in ("nan", "none", "nat"):
|
||||
return ""
|
||||
if s.endswith(".0"):
|
||||
s = s[:-2]
|
||||
return s
|
||||
|
||||
|
||||
def _to_int(v, default=0) -> int:
|
||||
s = _clean(v)
|
||||
if not s:
|
||||
return default
|
||||
try:
|
||||
return int(float(s))
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def _norm_path(p: str) -> str:
|
||||
p = _clean(p).replace("\\", "/").strip("/")
|
||||
if p.startswith("集团/"):
|
||||
p = p[len("集团/"):]
|
||||
elif p == "集团":
|
||||
p = ""
|
||||
return p.strip("/")
|
||||
|
||||
|
||||
def _parse_date(s):
|
||||
s = _clean(s)[:10]
|
||||
if not s:
|
||||
return None
|
||||
try:
|
||||
return datetime.strptime(s, "%Y-%m-%d").date()
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _row_from_seal(rec: dict, month_display: str, abnormal_type: str) -> dict:
|
||||
return {
|
||||
"37工号": _clean(rec.get("base_code")),
|
||||
"姓名": _clean(rec.get("staff_name")),
|
||||
"月报检查月份": month_display,
|
||||
"异常类型": abnormal_type,
|
||||
"所属单位": _clean(rec.get("BELONG_UNIT_ORG_NAME")),
|
||||
"一级部门": _clean(rec.get("DEPT_ORG_ONE")),
|
||||
"二级部门": _clean(rec.get("DEPT_ORG_TWO")),
|
||||
"三级部门": _clean(rec.get("DEPT_ORG_THREE")),
|
||||
"四级部门": _clean(rec.get("DEPT_ORG_FOUR")),
|
||||
"五级部门": _clean(rec.get("DEPT_ORG_FIVE")),
|
||||
}
|
||||
|
||||
|
||||
def _resolve_org_label(rec: dict, org_name_map: Dict[str, str]) -> str:
|
||||
"""解析员工组织类型标签:部门全路径匹配组织表组织全路径 → 组织名称。
|
||||
匹配失败回退取路径最后一个节点名。"""
|
||||
path = _norm_path(rec.get("ORG_FULL_PATH"))
|
||||
if path and path in org_name_map:
|
||||
return org_name_map[path]
|
||||
if path:
|
||||
return path.split("/")[-1]
|
||||
return ""
|
||||
|
||||
|
||||
# ==================== 检查1:在职天数是否均排班 ====================
|
||||
def _calc_working_days(rec: dict, year: int, month: int) -> int:
|
||||
"""按需求文档规则计算当月在职天数(基于入职/离职时间)。"""
|
||||
month_days = calendar.monthrange(year, month)[1]
|
||||
first = date(year, month, 1)
|
||||
last = date(year, month, month_days)
|
||||
join_d = _parse_date(rec.get("join_date"))
|
||||
leave_d = _parse_date(rec.get("leaveOffice_date"))
|
||||
|
||||
def in_service(d):
|
||||
if join_d and d < join_d:
|
||||
return False
|
||||
if leave_d and d > leave_d:
|
||||
return False
|
||||
return True
|
||||
|
||||
in_first, in_last = in_service(first), in_service(last)
|
||||
if in_first and in_last:
|
||||
# 1号和月末都在职 = 全月在职,在职天数即为当月自然天数
|
||||
return month_days
|
||||
if in_first and not in_last:
|
||||
return (leave_d - first).days if leave_d else 0
|
||||
if not in_first and in_last:
|
||||
return (last - join_d).days if join_d else 0
|
||||
# 首尾都不在职:仅当入职、离职日期都落在本月内时按差计算;否则返回 0
|
||||
if join_d and leave_d and first <= join_d <= last and first <= leave_d <= last:
|
||||
return (leave_d - join_d).days
|
||||
return 0
|
||||
|
||||
|
||||
def check1(seal_rows: List[dict], year: int, month: int) -> List[dict]:
|
||||
month_display = f"{year:04d}-{month:02d}"
|
||||
rows = []
|
||||
for rec in seal_rows:
|
||||
wd = _calc_working_days(rec, year, month)
|
||||
yq = _to_int(rec.get("kq_stat_month_yq_work_day_in")) # 在职应勤工作日
|
||||
rest = _to_int(rec.get("kq_stat_cal_ext9")) # 休息天
|
||||
if wd - (yq + rest) != 0:
|
||||
rows.append(_row_from_seal(rec, month_display, TYPE_1))
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 检查2:排休天数验证 ====================
|
||||
def check2(seal_rows, org_name_map, seq_map, engine, year, month) -> List[dict]:
|
||||
month_display = f"{year:04d}-{month:02d}"
|
||||
rows = []
|
||||
for rec in seal_rows:
|
||||
unit = _clean(rec.get("BELONG_UNIT_ORG_NAME"))
|
||||
org_label = _resolve_org_label(rec, org_name_map)
|
||||
seq = seq_map.get(_clean(rec.get("base_code")), "")
|
||||
abnormal, rule, _days = engine.check(unit, org_label, seq, rec.get("kq_stat_cal_ext9"))
|
||||
if abnormal:
|
||||
rows.append(_row_from_seal(rec, month_display, rule.desc))
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 检查3:封存值是否为最新值 ====================
|
||||
def check3(diff_rows, seal_rows, diff_fields, year, month) -> List[dict]:
|
||||
month_display = f"{year:04d}-{month:02d}"
|
||||
if not diff_rows:
|
||||
return []
|
||||
seal_by_code = {_clean(r.get("base_code")): r for r in seal_rows}
|
||||
rows = []
|
||||
for dr in diff_rows:
|
||||
code = _clean(dr.get("base_code")) or _clean(dr.get("工号"))
|
||||
if any(_clean(dr.get(f)) for f in diff_fields) and code in seal_by_code:
|
||||
rows.append(_row_from_seal(seal_by_code[code], month_display, TYPE_3))
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 检查4:出勤天数验证 ====================
|
||||
def check4(seal_rows, shift_map, year, month) -> List[dict]:
|
||||
month_display = f"{year:04d}-{month:02d}"
|
||||
rows = []
|
||||
for rec in seal_rows:
|
||||
code = _clean(rec.get("base_code"))
|
||||
expected = shift_map.get(code)
|
||||
if expected is None:
|
||||
continue
|
||||
attend = _to_int(rec.get("kq_stat_cal_ext19"), default=-1) # 实际出勤天日
|
||||
if attend >= 0 and attend > expected:
|
||||
rows.append(_row_from_seal(rec, month_display, TYPE_4))
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 检查5:未封存名单 ====================
|
||||
def check5(seal_rows, in_service_records, year, month) -> List[dict]:
|
||||
month_display = f"{year:04d}-{month:02d}"
|
||||
seal_codes = {_clean(r.get("base_code")) for r in seal_rows}
|
||||
rows = []
|
||||
for rec in in_service_records:
|
||||
code = _clean(rec.get("工号"))
|
||||
if code and code not in seal_codes:
|
||||
rows.append({
|
||||
"37工号": code, "姓名": _clean(rec.get("姓名")),
|
||||
"月报检查月份": month_display, "异常类型": TYPE_5,
|
||||
"所属单位": _clean(rec.get("所属单位")),
|
||||
"一级部门": _clean(rec.get("一级部门")),
|
||||
"二级部门": _clean(rec.get("二级部门")),
|
||||
"三级部门": _clean(rec.get("三级部门")),
|
||||
"四级部门": _clean(rec.get("四级部门")),
|
||||
"五级部门": _clean(rec.get("五级部门")),
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 汇总编排 ====================
|
||||
def run_all_checks(*, seal_rows, org_name_map, seq_map, in_service_records,
|
||||
shift_map, engine, year, month, diff_rows=None, diff_fields=None,
|
||||
notes=None) -> dict:
|
||||
notes = list(notes or [])
|
||||
results = {
|
||||
1: check1(seal_rows, year, month),
|
||||
2: check2(seal_rows, org_name_map, seq_map, engine, year, month),
|
||||
3: check3(diff_rows or [], seal_rows, diff_fields or [], year, month),
|
||||
4: check4(seal_rows, shift_map, year, month),
|
||||
5: check5(seal_rows, in_service_records, year, month),
|
||||
}
|
||||
if diff_rows is None:
|
||||
notes.append("检查3「封存值是否为最新值」:对比接口数据未提供,本次跳过该检查")
|
||||
return {"rows": results, "notes": notes}
|
||||
@@ -0,0 +1,63 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""考勤月报封存检查 - Excel 报告导出(webhost 场景插件)
|
||||
|
||||
与 desktop/plugins/seal_check/report.py 保持同步(桌面版为单一真源)。
|
||||
|
||||
输出:考勤月报封存检查_{月份}_{时间戳}.xlsx(汇总 + 检查1~5 Sheet,空 Sheet 保留表头)
|
||||
"""
|
||||
import os
|
||||
from datetime import datetime
|
||||
from typing import Dict, List
|
||||
|
||||
from webhost.backend.plugins.seal_check import config
|
||||
from webhost.backend.plugins.seal_check.logic import OUTPUT_COLUMNS, TYPE_1, TYPE_3, TYPE_4, TYPE_5
|
||||
|
||||
CHECK_TAB_TITLES = {
|
||||
1: "检查1_在职天数排班异常",
|
||||
2: "检查2_排休天数异常",
|
||||
3: "检查3_封存非最新值",
|
||||
4: "检查4_出勤天数异常",
|
||||
5: "检查5_未封存名单",
|
||||
}
|
||||
|
||||
CHECK_DESCRIPTIONS = {
|
||||
1: TYPE_1,
|
||||
2: "当月排休不满足……天规则(动态)",
|
||||
3: TYPE_3,
|
||||
4: TYPE_4,
|
||||
5: TYPE_5,
|
||||
}
|
||||
|
||||
|
||||
def export_report(rows_map: Dict[int, List[dict]], month: str, notes: List[str] = None,
|
||||
save_dir: str = None) -> str:
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
raise RuntimeError("缺少 pandas / openpyxl 依赖,无法导出 Excel")
|
||||
|
||||
save_dir = save_dir or config.SAVE_DIR
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
path = os.path.join(save_dir, f"考勤月报封存检查_{month}_{ts}.xlsx")
|
||||
|
||||
with pd.ExcelWriter(path, engine="openpyxl") as writer:
|
||||
summary = []
|
||||
for i in range(1, 6):
|
||||
n = len(rows_map.get(i, []))
|
||||
summary.append({
|
||||
"检查项": CHECK_TAB_TITLES[i],
|
||||
"命中条数": n,
|
||||
"异常类型": CHECK_DESCRIPTIONS[i],
|
||||
"说明": "详见对应 Sheet" if n else "无异常",
|
||||
})
|
||||
if notes:
|
||||
summary.append({"检查项": "备注", "命中条数": len(notes),
|
||||
"异常类型": "", "说明": ";".join(notes)})
|
||||
pd.DataFrame(summary).to_excel(writer, sheet_name="汇总", index=False)
|
||||
|
||||
for i in range(1, 6):
|
||||
df = pd.DataFrame(rows_map.get(i, []), columns=OUTPUT_COLUMNS)
|
||||
df.to_excel(writer, sheet_name=CHECK_TAB_TITLES[i], index=False)
|
||||
|
||||
return path
|
||||
@@ -0,0 +1,7 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost.backend.shared:webhost 共享模块(登录/导出/封存拉取)
|
||||
|
||||
原 desktop/shared 迁入,webhost 单一真源,完全自包含、不依赖其他目录。
|
||||
与 workflows/(影刀版)为**独立维护的两份副本**,修改时若需同步,
|
||||
请手动将 workflows 对应文件复制覆盖到本目录。
|
||||
"""
|
||||
@@ -0,0 +1,449 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: hr_login.py
|
||||
@Description: HR 登录自定义指令(影刀编码版 Python 模块源码)。
|
||||
作为「37duHR登录」影刀自定义指令的模块源码(单一真源),
|
||||
供所有 HR 系统影刀脚本复用,避免每个脚本各自内联滑块登录逻辑。
|
||||
|
||||
如何在影刀中创建指令:
|
||||
1. 影刀客户端 → 新建「PC自动化指令」→ 指令编码如 hr_login,添加 Python 模块;
|
||||
2. 把本文件内容粘贴进指令的 Python 模块(或直接以本文件作为模块源码);
|
||||
3. 增加流程参数 force(可选,布尔,是否强制重新登录);
|
||||
4. 保存并「发版」;在需要登录的应用中「获取指令」并安装;
|
||||
5. 在每个应用的流程开头拖入该指令,即可保证后续业务脚本能读到有效 cookies。
|
||||
|
||||
约定(与项目 app 版一致,见 app/common/app_paths.py):
|
||||
- 配置:统一读取固定路径共享 .env:%LOCALAPPDATA%\\37duAutomation\\.env
|
||||
(本地开发时也兼容当前工作目录下的 .env);
|
||||
- 登录态:统一写入 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json,
|
||||
各影刀业务脚本自行用这些 cookies 构建 requests.Session。
|
||||
|
||||
配置(已直接内置在模块源码中,无需 .env / 环境变量):
|
||||
LOGIN_URL=HR 登录页 URL
|
||||
SUCCESS_KEYWORD=HR 登录成功后 URL 关键字
|
||||
USERNAME=用户名
|
||||
PASSWORD=密码
|
||||
hr_validate_url=(可选,.env/系统变量)HR 会话校验接口 URL;默认使用 getCurUserInfo 接口
|
||||
hr_captcha_debug_dir=(可选)滑块调试图片输出目录;不设置则不落盘
|
||||
|
||||
全局变量(在影刀流程中创建,此指令负责写入):
|
||||
login_state 登录成功或缓存的 cookies 有效时写入 True,否则为 False
|
||||
|
||||
依赖(影刀「Python包管理」安装):
|
||||
pip install DrissionPage requests python-dotenv opencv-python numpy Pillow
|
||||
|
||||
入口:
|
||||
main(args) 影刀自定义指令调用入口,args 传 {"force": true|false},返回 JSON 安全 dict
|
||||
python hr_login.py 独立运行(等价于 main({"force": true}))
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import time
|
||||
import random
|
||||
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
# ================== 共享路径(与 app 版统一) ==================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
|
||||
|
||||
def _load_shared_env():
|
||||
"""统一加载配置:优先固定路径共享 .env,再兼容当前工作目录 .env 与系统变量。"""
|
||||
if os.path.exists(SHARED_ENV_FILE):
|
||||
load_dotenv(SHARED_ENV_FILE)
|
||||
load_dotenv()
|
||||
|
||||
|
||||
# ================== 配置 ==================
|
||||
# 账号密码只从共享 .env 读取(%LOCALAPPDATA%\37duAutomation\.env 或项目 .env),不内置明文,
|
||||
# 避免真实凭据写进源码/git 历史;缺失时登录会提示「登录配置缺失」。
|
||||
_load_shared_env()
|
||||
LOGIN_URL = 'https://hr.37du.co/RedseaPlatform/'
|
||||
SUCCESS_KEYWORD = 'https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic'
|
||||
USERNAME = os.getenv('hr_login_username', '')
|
||||
PASSWORD = os.getenv('hr_login_password', '')
|
||||
|
||||
# HR 会话校验接口:cookies 有效时返回 JSON,失效时返回登录页等非 JSON
|
||||
GET_CUR_USER_INFO_URL = "https://hr.37du.co/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
|
||||
LOGIN_BTN = "@id=login-btn"
|
||||
ACCOUNT_INPUT = "@id=j_username"
|
||||
PASSWORD_INPUT = "@id=j_password_2"
|
||||
CAPTCHA_CONTAINER = ".:comImageValidate"
|
||||
SLIDER_BTN = ".:v_rightBtn"
|
||||
BG_IMG = ".imgBg"
|
||||
SLIDER_IMG = "css:div.imgBg_3 > img"
|
||||
|
||||
RETRY_MAX = 5
|
||||
TIMEOUT = 10
|
||||
HEADLESS = False
|
||||
|
||||
|
||||
def ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
# ================== Cookies 持久化(登录成功后缓存,下次免登录复用) ==================
|
||||
def save_browser_cookies(page):
|
||||
cookies = page.cookies(all_domains=True)
|
||||
if not cookies:
|
||||
print("未获取到 Cookies,跳过保存")
|
||||
return
|
||||
ensure_dir(_SESSIONS_DIR)
|
||||
with open(COOKIE_FILE, 'w', encoding='utf-8') as f:
|
||||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||||
print(f"已保存 {len(cookies)} 个 Cookies 到 {COOKIE_FILE}")
|
||||
|
||||
|
||||
def load_cookies():
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
return None
|
||||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
# ================== 影刀全局变量 ==================
|
||||
def _set_login_state(value):
|
||||
"""写入影刀全局变量 login_state(影刀指令环境可用;独立运行/非影刀环境时静默跳过)。"""
|
||||
try:
|
||||
glv['login_state'] = value
|
||||
print(f"已写入影刀全局变量 login_state={value}")
|
||||
except Exception as e:
|
||||
print(f"写入影刀全局变量 login_state 失败(非影刀环境?):{e}")
|
||||
|
||||
|
||||
# ================== API 校验 cookies 有效性(无需打开浏览器) ==================
|
||||
def _is_hr_session_valid():
|
||||
"""API 轻量校验 HR cookies:请求 hr_validate_url(默认 getCurUserInfo 接口),
|
||||
返回 JSON 视为 cookies 有效;返回登录页等非 JSON 即视为失效。
|
||||
|
||||
与业务脚本(attendance_abnormal/bank_card_check 等)使用同一套构建方式:
|
||||
requests.Session + Chrome UA/Content-Type + 仅注入 37du.co 域 cookies。
|
||||
"""
|
||||
validate_url = os.getenv('hr_validate_url', '').strip() or GET_CUR_USER_INFO_URL
|
||||
try:
|
||||
cookies = load_cookies()
|
||||
if not cookies:
|
||||
return False
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
resp = session.post(validate_url, data={}, timeout=15)
|
||||
if resp.status_code != 200:
|
||||
print(f"API 校验 cookies 状态码异常:{resp.status_code}")
|
||||
return False
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception as e:
|
||||
print(f"API 校验 cookies 异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 滑块匹配(与已验证可用的 bank_card/roster 内联版一致) ==================
|
||||
def match_slider_dual(bg_bytes, slider_bytes):
|
||||
"""模板匹配滑块缺口,返回物理距离(px)。"""
|
||||
bg_img = cv2.imdecode(np.frombuffer(bg_bytes, np.uint8), cv2.IMREAD_COLOR)
|
||||
slider_color = cv2.imdecode(np.frombuffer(slider_bytes, np.uint8), cv2.IMREAD_UNCHANGED)
|
||||
if bg_img is None or slider_color is None:
|
||||
raise RuntimeError("无法解码验证码图片")
|
||||
|
||||
bg_h, bg_w = bg_img.shape[:2]
|
||||
x_offset, y_offset = 0, 0
|
||||
if len(slider_color.shape) == 3 and slider_color.shape[2] == 4:
|
||||
alpha = slider_color[:, :, 3]
|
||||
slider_rgb = slider_color[:, :, :3]
|
||||
ys, xs = np.where(alpha > 0)
|
||||
if len(ys) > 0:
|
||||
y_min, y_max = np.min(ys), np.max(ys)
|
||||
x_min, x_max = np.min(xs), np.max(xs)
|
||||
slider_rgb = slider_rgb[y_min:y_max + 1, x_min:x_max + 1]
|
||||
x_offset, y_offset = x_min, y_min
|
||||
else:
|
||||
slider_rgb = slider_color[:, :, :3] if len(slider_color.shape) == 3 else slider_color
|
||||
|
||||
s_h, s_w = slider_rgb.shape[:2]
|
||||
gray_bg = cv2.GaussianBlur(cv2.cvtColor(bg_img, cv2.COLOR_BGR2GRAY), (3, 3), 0)
|
||||
gray_slider = cv2.GaussianBlur(cv2.cvtColor(slider_rgb, cv2.COLOR_BGR2GRAY), (3, 3), 0)
|
||||
bg_edges = cv2.Canny(gray_bg, 50, 150)
|
||||
slider_edges = cv2.Canny(gray_slider, 50, 150)
|
||||
result = cv2.matchTemplate(bg_edges, slider_edges, cv2.TM_CCOEFF_NORMED)
|
||||
|
||||
candidates = []
|
||||
temp_result = result.copy()
|
||||
for _ in range(6):
|
||||
_, max_val, _, max_loc = cv2.minMaxLoc(temp_result)
|
||||
if max_val < 0.03:
|
||||
break
|
||||
candidates.append((max_val, max_loc))
|
||||
y0 = max(0, max_loc[1] - s_h // 2); y1 = min(temp_result.shape[0], max_loc[1] + s_h // 2)
|
||||
x0 = max(0, max_loc[0] - s_w // 2); x1 = min(temp_result.shape[1], max_loc[0] + s_w // 2)
|
||||
temp_result[y0:y1, x0:x1] = -2.0
|
||||
|
||||
if not candidates:
|
||||
raise RuntimeError("无有效滑块候选")
|
||||
|
||||
right_limit = bg_w - s_w - max(15, int(bg_w * 0.06))
|
||||
|
||||
def region_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 = []
|
||||
for val, loc in candidates:
|
||||
x, y = loc
|
||||
if x <= s_w or x > right_limit:
|
||||
continue
|
||||
scored.append((val + 0.5 * region_whiteness(x, y, s_w, s_h), val, loc))
|
||||
|
||||
if scored:
|
||||
scored.sort(key=lambda t: t[0], reverse=True)
|
||||
best_val, best_loc = scored[0][1], scored[0][2]
|
||||
else:
|
||||
best_val, best_loc = candidates[0]
|
||||
|
||||
distance = best_loc[0] - x_offset
|
||||
if distance < 0:
|
||||
distance = 0
|
||||
if distance + s_w > bg_w:
|
||||
distance = bg_w - s_w
|
||||
return distance
|
||||
|
||||
|
||||
# ================== 轨迹生成与滑动 ==================
|
||||
def generate_track(distance):
|
||||
overshoot = random.randint(2, 6) if random.random() < 0.75 else 0
|
||||
aim = distance + overshoot
|
||||
steps = []
|
||||
moved = 0
|
||||
y = 0
|
||||
while moved < aim:
|
||||
remain = aim - moved
|
||||
if remain > 80:
|
||||
dx = min(remain, random.randint(9, 15)); dt = random.uniform(0.010, 0.022)
|
||||
elif remain > 35:
|
||||
dx = min(remain, random.randint(5, 9)); dt = random.uniform(0.012, 0.028)
|
||||
elif remain > 12:
|
||||
dx = min(remain, random.randint(2, 5)); dt = random.uniform(0.016, 0.040)
|
||||
else:
|
||||
dx = min(remain, random.randint(1, 3)); dt = random.uniform(0.020, 0.060)
|
||||
if random.random() < 0.22:
|
||||
y = max(-2, min(2, y + random.choice([-1, 1])))
|
||||
else:
|
||||
y = int(round(y * 0.6))
|
||||
steps.append((dx, y, dt))
|
||||
moved += dx
|
||||
if overshoot > 0:
|
||||
back = overshoot
|
||||
while back > 0:
|
||||
dx = -min(back, random.randint(1, 3))
|
||||
steps.append((dx, random.choice([-1, 0, 1]), random.uniform(0.030, 0.080)))
|
||||
back += dx
|
||||
if random.random() < 0.65:
|
||||
steps.extend([(0, 0, random.uniform(0.060, 0.140)),
|
||||
(1, 0, random.uniform(0.020, 0.050)),
|
||||
(-1, 0, random.uniform(0.020, 0.050))])
|
||||
return steps
|
||||
|
||||
|
||||
def perform_slide(page, btn, distance_css):
|
||||
if distance_css <= 0:
|
||||
return False
|
||||
mid = btn.rect.midpoint
|
||||
steps = generate_track(distance_css)
|
||||
try:
|
||||
page.actions.move_to((mid[0] + random.uniform(-3, 3), mid[1] + random.uniform(-2, 2)),
|
||||
duration=random.uniform(0.25, 0.60))
|
||||
time.sleep(random.uniform(0.18, 0.45))
|
||||
page.actions.hold(on_ele=btn)
|
||||
time.sleep(random.uniform(0.12, 0.28))
|
||||
for dx, dy, dt in steps:
|
||||
if dx == 0 and dy == 0:
|
||||
time.sleep(dt)
|
||||
else:
|
||||
page.actions.move(offset_x=dx, offset_y=dy, duration=dt)
|
||||
time.sleep(random.uniform(0.10, 0.26))
|
||||
page.actions.release()
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"拖拽异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 验证码处理(与已验证可用的 bank_card/roster 内联版一致) ==================
|
||||
def handle_captcha(page):
|
||||
for retry in range(RETRY_MAX):
|
||||
print(f"\n--- 第 {retry + 1} 次尝试验证 ---")
|
||||
try:
|
||||
container = page.ele(CAPTCHA_CONTAINER, timeout=TIMEOUT)
|
||||
if not container:
|
||||
print("验证码容器未出现")
|
||||
continue
|
||||
bg_ele = container.ele(BG_IMG) or container.ele('div[style*="background-image"]')
|
||||
slider_ele = container.ele(SLIDER_IMG)
|
||||
if not bg_ele or not slider_ele:
|
||||
print("找不到背景图/滑块小图元素")
|
||||
continue
|
||||
if slider_ele.tag != 'img':
|
||||
inner = slider_ele.ele('tag:img')
|
||||
if inner:
|
||||
slider_ele = inner
|
||||
try:
|
||||
page.run_js('arguments[0].style.display = "none"', slider_ele)
|
||||
time.sleep(0.2)
|
||||
bg_screenshot = bg_ele.get_screenshot(as_bytes='png')
|
||||
page.run_js('arguments[0].style.display = ""', slider_ele)
|
||||
time.sleep(0.2)
|
||||
slider_screenshot = slider_ele.get_screenshot(as_bytes='png')
|
||||
except Exception:
|
||||
page.run_js('arguments[0].style.display = ""', slider_ele)
|
||||
continue
|
||||
|
||||
if not bg_screenshot or not slider_screenshot:
|
||||
print("截图数据为空")
|
||||
continue
|
||||
|
||||
distance_phys = match_slider_dual(bg_screenshot, slider_screenshot)
|
||||
dpr = page.run_js('return window.devicePixelRatio') or 1
|
||||
distance_css = distance_phys / dpr
|
||||
print(f" 匹配距离 {distance_phys}px -> CSS {distance_css:.1f}px")
|
||||
|
||||
btn = page.ele(SLIDER_BTN)
|
||||
if btn and perform_slide(page, btn, distance_css):
|
||||
time.sleep(2)
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
return True
|
||||
if not page.ele(CAPTCHA_CONTAINER, timeout=1):
|
||||
return True
|
||||
time.sleep(2)
|
||||
except Exception as e:
|
||||
print(f"异常:{e}")
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
# ================== 登录主流程 ==================
|
||||
def _do_login():
|
||||
"""打开浏览器完成登录(含滑块),成功保存 cookies。"""
|
||||
co = ChromiumOptions()
|
||||
if HEADLESS:
|
||||
co.headless()
|
||||
page = ChromiumPage(co)
|
||||
try:
|
||||
page.get(LOGIN_URL)
|
||||
time.sleep(2)
|
||||
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
print("已登录")
|
||||
save_browser_cookies(page)
|
||||
return True
|
||||
|
||||
account = page.ele(ACCOUNT_INPUT)
|
||||
if not account:
|
||||
print("找不到账号输入框")
|
||||
return False
|
||||
account.clear()
|
||||
account.input(USERNAME)
|
||||
time.sleep(0.5)
|
||||
|
||||
pwd = page.ele(PASSWORD_INPUT)
|
||||
if not pwd:
|
||||
print("找不到密码输入框")
|
||||
return False
|
||||
pwd.clear()
|
||||
pwd.input(PASSWORD)
|
||||
time.sleep(0.5)
|
||||
|
||||
login_btn = page.ele(LOGIN_BTN)
|
||||
if not login_btn:
|
||||
print("找不到登录按钮")
|
||||
return False
|
||||
login_btn.click()
|
||||
time.sleep(3)
|
||||
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
print("登录成功(无滑块)")
|
||||
save_browser_cookies(page)
|
||||
return True
|
||||
|
||||
if handle_captcha(page):
|
||||
print("登录成功(验证通过)")
|
||||
save_browser_cookies(page)
|
||||
return True
|
||||
print("登录失败")
|
||||
return False
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def ensure_login(force=False):
|
||||
"""
|
||||
确保存在有效的 HR 登录态并缓存 cookies。
|
||||
返回 JSON 安全 dict:{success, cookie_path, message, relogin}
|
||||
"""
|
||||
_load_shared_env()
|
||||
# 默认未登录;登录成功或复用有效 cookies 后再置 True
|
||||
_set_login_state(False)
|
||||
|
||||
if not (LOGIN_URL and SUCCESS_KEYWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录配置缺失(hr_login_url / hr_target_url_keyword 未配置且无内置默认值)", "relogin": False}
|
||||
if not (USERNAME and PASSWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录配置缺失(hr_login_username / hr_login_password 未配置且无内置默认值)", "relogin": False}
|
||||
|
||||
# 优先复用已保存的 cookies(通过 API 校验有效性,无需打开浏览器)
|
||||
if not force and _is_hr_session_valid():
|
||||
print("已通过缓存的 Cookies 复用 HR 登录态")
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE,
|
||||
"message": "复用缓存登录态", "relogin": False}
|
||||
|
||||
ok = _do_login()
|
||||
if ok:
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE, "message": "登录成功", "relogin": True}
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录失败(滑块验证未通过)", "relogin": False}
|
||||
|
||||
|
||||
# ================== 影刀自定义指令入口 ==================
|
||||
def main(args):
|
||||
"""
|
||||
影刀自定义指令「37duHR登录」调用入口。
|
||||
args: dict,可选字段 force(bool) 是否强制重新登录
|
||||
返回: dict {success, cookie_path, message, relogin}
|
||||
"""
|
||||
if not args:
|
||||
args = {}
|
||||
force = bool(args.get("force", False))
|
||||
try:
|
||||
return ensure_login(force=force)
|
||||
except Exception as e:
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": f"登录过程异常:{e}", "relogin": False}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
result = main({"force": False})
|
||||
print("最终结果:", result)
|
||||
@@ -0,0 +1,241 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: oa_login.py
|
||||
@Description: OA 登录自定义指令(影刀编码版 Python 模块源码)。
|
||||
作为「37duOA登录」影刀自定义指令的模块源码(单一真源),
|
||||
供所有 OA 系统影刀脚本(请假/加班/社保增减等)复用。
|
||||
|
||||
如何在影刀中创建指令:
|
||||
1. 影刀客户端 → 新建「PC自动化指令」→ 指令编码如 oa_login,添加 Python 模块;
|
||||
2. 把本文件内容粘贴进指令的 Python 模块(或直接以本文件作为模块源码);
|
||||
3. 增加流程参数 force(可选,布尔,是否强制重新登录);
|
||||
4. 保存并「发版」;在需要登录的应用中「获取指令」并安装;
|
||||
5. 在每个应用的流程开头拖入该指令,即可保证后续业务脚本能读到有效 cookies。
|
||||
|
||||
约定(与项目 app 版一致,见 app/common/app_paths.py):
|
||||
- 配置:统一读取固定路径共享 .env:%LOCALAPPDATA%\\37duAutomation\\.env
|
||||
(本地开发时也兼容当前工作目录下的 .env);
|
||||
- 登录态:统一写入 %LOCALAPPDATA%\\37duAutomation\\.sessions\\oa_cookies.json,
|
||||
各影刀业务脚本自行用这些 cookies 构建 SessionPage / requests.Session。
|
||||
|
||||
配置(已直接内置在模块源码中,无需 .env / 环境变量):
|
||||
LOGIN_URL=OA 登录页 URL
|
||||
SUCCESS_KEYWORD=OA 登录成功后 URL 关键字
|
||||
USERNAME=用户名
|
||||
PASSWORD=密码
|
||||
oa_validate_url=(可选,.env/系统变量)轻量会话校验接口 URL;默认使用 sumTodoCount 待办统计接口
|
||||
|
||||
全局变量(在影刀流程中创建,此指令负责写入):
|
||||
login_state 登录成功或缓存的 cookies 有效时写入 True,否则为 False
|
||||
|
||||
依赖(影刀「Python包管理」安装):
|
||||
pip install DrissionPage requests python-dotenv
|
||||
|
||||
入口:
|
||||
main(force=True) 影刀自定义指令调用入口,force 传 True/False(是否强制重新登录),返回 JSON 安全 dict
|
||||
python oa_login.py 独立运行(等价于 main(force=True))
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import time
|
||||
|
||||
from DrissionPage import ChromiumPage
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
|
||||
# ================== 共享路径(与 app 版统一) ==================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
|
||||
|
||||
def _load_shared_env():
|
||||
"""统一加载配置:优先固定路径共享 .env,再兼容当前工作目录 .env 与系统变量。"""
|
||||
if os.path.exists(SHARED_ENV_FILE):
|
||||
load_dotenv(SHARED_ENV_FILE)
|
||||
load_dotenv()
|
||||
|
||||
|
||||
# ================== 配置 ==================
|
||||
# 账号密码只从共享 .env 读取(%LOCALAPPDATA%\37duAutomation\.env 或项目 .env),不内置明文,
|
||||
# 避免真实凭据写进源码/git 历史;缺失时登录会提示「登录配置缺失」。
|
||||
_load_shared_env()
|
||||
LOGIN_URL = 'https://oa.37du.co/login.jsp'
|
||||
SUCCESS_KEYWORD = 'https://oa.37du.co/sys/portal/page.jsp'
|
||||
USERNAME = os.getenv('oa_login_username', '')
|
||||
PASSWORD = os.getenv('oa_login_password', '')
|
||||
|
||||
# OA 会话校验接口:cookies 有效时返回 JSON,失效时被重定向到登录页返回 HTML
|
||||
TODO_COUNT_URL = "https://oa.37du.co/sys/notify/sys_notify_todo/sysNotifyTodo.do"
|
||||
|
||||
USERNAME_INPUT = 'tag:input@name=j_username'
|
||||
PASSWORD_INPUT = 'tag:input@name=j_password'
|
||||
LOGIN_BTN = '.lui_login_button_div_c'
|
||||
|
||||
TIMEOUT = 10
|
||||
WAIT_AFTER_LOAD = 2
|
||||
|
||||
|
||||
def ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
# ================== Cookies 持久化 ==================
|
||||
def save_browser_cookies(page):
|
||||
cookies = page.cookies(all_domains=True)
|
||||
if not cookies:
|
||||
print("未获取到 Cookies,跳过保存")
|
||||
return
|
||||
ensure_dir(_SESSIONS_DIR)
|
||||
with open(COOKIE_FILE, 'w', encoding='utf-8') as f:
|
||||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||||
print(f"已保存 {len(cookies)} 个 Cookies 到 {COOKIE_FILE}")
|
||||
|
||||
|
||||
def load_cookies():
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
return None
|
||||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
# ================== 影刀全局变量 ==================
|
||||
def _set_login_state(value):
|
||||
"""写入影刀全局变量 login_state(影刀指令环境可用;独立运行/非影刀环境时静默跳过)。"""
|
||||
try:
|
||||
glv['login_state'] = value
|
||||
print(f"已写入影刀全局变量 login_state={value}")
|
||||
except Exception as e:
|
||||
print(f"写入影刀全局变量 login_state 失败(非影刀环境?):{e}")
|
||||
|
||||
|
||||
# ================== API 校验 cookies 有效性(无需打开浏览器) ==================
|
||||
def _is_oa_session_valid():
|
||||
"""API 轻量校验 OA cookies:请求 oa_validate_url(默认 sumTodoCount 待办统计接口),
|
||||
返回 JSON 视为 cookies 有效;被重定向到登录页返回 HTML 即视为失效。
|
||||
|
||||
与业务脚本(overtime_approval/leave_approval/social_change 等)使用同一套接口与校验逻辑:
|
||||
requests.Session + Chrome UA + 仅注入 37du.co 域 cookies,GET method=sumTodoCount。
|
||||
"""
|
||||
validate_url = os.getenv('oa_validate_url', '').strip() or TODO_COUNT_URL
|
||||
try:
|
||||
cookies = load_cookies()
|
||||
if not cookies:
|
||||
return False
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
resp = session.get(validate_url, params={"method": "sumTodoCount"}, timeout=15)
|
||||
if resp.status_code != 200:
|
||||
print(f"API 校验 cookies 状态码异常:{resp.status_code}")
|
||||
return False
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception as e:
|
||||
print(f"API 校验 cookies 异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 登录主流程 ==================
|
||||
def _do_login(timeout=TIMEOUT, wait_after_load=WAIT_AFTER_LOAD):
|
||||
"""打开浏览器完成 OA 账号密码登录,成功保存 cookies。"""
|
||||
page = ChromiumPage()
|
||||
try:
|
||||
page.get(LOGIN_URL)
|
||||
time.sleep(wait_after_load)
|
||||
|
||||
username_input = page.ele(USERNAME_INPUT)
|
||||
if not username_input:
|
||||
raise RuntimeError("未找到用户名输入框")
|
||||
username_input.input(USERNAME)
|
||||
page.wait(0.5)
|
||||
|
||||
password_input = page.ele(PASSWORD_INPUT)
|
||||
if not password_input:
|
||||
raise RuntimeError("未找到密码输入框")
|
||||
password_input.input(PASSWORD)
|
||||
page.wait(0.5)
|
||||
|
||||
login_button = page.ele(LOGIN_BTN)
|
||||
if not login_button:
|
||||
raise RuntimeError("未找到登录按钮")
|
||||
login_button.click()
|
||||
page.wait(0.5)
|
||||
|
||||
start = time.time()
|
||||
while time.time() - start < timeout:
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
print(f"登录成功!当前 URL: {page.url}")
|
||||
save_browser_cookies(page)
|
||||
return True
|
||||
time.sleep(0.5)
|
||||
|
||||
error_elem = page.ele('.error-msg') or page.ele('.alert-danger')
|
||||
if error_elem:
|
||||
print(f"登录失败,提示: {error_elem.text}")
|
||||
raise RuntimeError(f"登录超时,当前 URL: {page.url}")
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def ensure_login(force=False):
|
||||
"""
|
||||
确保存在有效的 OA 登录态并缓存 cookies。
|
||||
返回 JSON 安全 dict:{success, cookie_path, message, relogin}
|
||||
"""
|
||||
_load_shared_env()
|
||||
# 默认未登录;登录成功或复用有效 cookies 后再置 True
|
||||
_set_login_state(False)
|
||||
|
||||
if not (LOGIN_URL and SUCCESS_KEYWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录配置缺失(oa_login_url / oa_target_url_keyword 未配置且无内置默认值)", "relogin": False}
|
||||
if not (USERNAME and PASSWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录配置缺失(oa_login_username / oa_login_password 未配置且无内置默认值)", "relogin": False}
|
||||
|
||||
# 优先复用已保存的 cookies(通过 API 校验有效性,无需打开浏览器)
|
||||
if not force and _is_oa_session_valid():
|
||||
print("已通过缓存的 Cookies 复用 OA 登录态")
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE,
|
||||
"message": "复用缓存登录态", "relogin": False}
|
||||
|
||||
ok = _do_login()
|
||||
if ok:
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE, "message": "登录成功", "relogin": True}
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录失败", "relogin": False}
|
||||
|
||||
|
||||
# ================== 影刀自定义指令入口 ==================
|
||||
def main(force=True):
|
||||
"""
|
||||
影刀自定义指令「37duOA登录」调用入口。
|
||||
force: bool 是否强制重新登录(默认 True,便于本地独立运行直接刷新登录态)
|
||||
返回: dict {success, cookie_path, message, relogin}
|
||||
"""
|
||||
try:
|
||||
return ensure_login(force=force)
|
||||
except Exception as e:
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": f"登录过程异常:{e}", "relogin": False}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
result = main(force=True)
|
||||
print("最终结果:", result)
|
||||
@@ -0,0 +1,401 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: org_export.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-05
|
||||
@Description: 组织维护(组织设置)导出(影刀共享指令,单文件自包含)——从共享登录态读取
|
||||
HR cookies,调用组织维护台账实时查询接口(queryRealTimeData.mc)分页拉取
|
||||
全部组织数据,转换为页面 18 列格式后导出 Excel。纯接口实现,无需浏览器。
|
||||
@Version: 1.0.0
|
||||
|
||||
运行方式:
|
||||
1. 影刀:注册为自定义指令「37du组织维护导出」,main(...) 关键字传参(缺省用内置默认值,见 DEFAULT_* 常量)
|
||||
output_path Excel 保存路径(默认 D:\\资料\\人资\\组织维护\\组织维护.xlsx)
|
||||
2. 命令行:python org_export.py 直接运行(__main__ 中按示例传参)
|
||||
3. 业务脚本:懒加载本模块调用 export_orgs(...)
|
||||
|
||||
依赖安装(启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install requests pandas openpyxl
|
||||
|
||||
登录态:读取 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json(由「37duHR登录」指令写入);
|
||||
缺失/失效时不自动补登,抛出提示先重新执行「37duHR登录」指令。
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.parse
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
# ==================== 第三方库导入(启动校验:全部必须预先安装,不懒加载) ====================
|
||||
try:
|
||||
import requests
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(共享指令要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install requests pandas openpyxl\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging,正常 INFO 不输出大体积 JSON) ====================
|
||||
class _PrintLogger:
|
||||
def debug(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def info(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def warning(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def error(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== commonQuery 前端加密(自实现,与前端行为一致,已实测接口可用) ====================
|
||||
# 自定义 Base64 字符表(索引0~63,64为填充字符)
|
||||
_CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
|
||||
_PAD_CHAR = '7' # 填充字符(索引64)
|
||||
_SALT = "yyryrtweasdasd" # 固定盐值
|
||||
|
||||
|
||||
def _custom_base64_encode(data):
|
||||
"""使用自定义字符表进行 Base64 编码(data 为 UTF-8 字节序列)。"""
|
||||
result = []
|
||||
for i in range(0, len(data), 3):
|
||||
chunk = data[i:i + 3]
|
||||
b1 = chunk[0] if len(chunk) > 0 else 0
|
||||
b2 = chunk[1] if len(chunk) > 1 else 0
|
||||
b3 = chunk[2] if len(chunk) > 2 else 0
|
||||
|
||||
enc1 = (b1 >> 2) & 0x3F
|
||||
enc2 = ((b1 << 4) | (b2 >> 4)) & 0x3F
|
||||
enc3 = ((b2 << 2) | (b3 >> 6)) & 0x3F
|
||||
enc4 = b3 & 0x3F
|
||||
|
||||
if len(chunk) == 1:
|
||||
enc3 = 64
|
||||
enc4 = 64
|
||||
elif len(chunk) == 2:
|
||||
enc4 = 64
|
||||
|
||||
result.append(_CUSTOM_CHARS[enc1])
|
||||
result.append(_CUSTOM_CHARS[enc2])
|
||||
result.append(_CUSTOM_CHARS[enc3])
|
||||
result.append(_CUSTOM_CHARS[enc4])
|
||||
return ''.join(result)
|
||||
|
||||
|
||||
def build_condition(query_field, query_type, query_value, query_text="",
|
||||
left_bracket="", right_bracket="", logic="AND", input_type="text"):
|
||||
"""构造一个符合前端格式的单条查询条件字典。"""
|
||||
return {
|
||||
"queryField": query_field,
|
||||
"leftBracket": left_bracket,
|
||||
"queryType": query_type,
|
||||
"queryValue": query_value,
|
||||
"queryText": query_text,
|
||||
"rightBracket": right_bracket,
|
||||
"logic": logic,
|
||||
"inputType": input_type,
|
||||
}
|
||||
|
||||
|
||||
def encode_common_query(query_list):
|
||||
"""将查询条件列表加密为 commonQuery 字符串(encodeURIComponent + 自定义 Base64 + 盐值 + 首尾重排)。"""
|
||||
# 1. JSON(无空格,同 JSON.stringify) 2. URI 编码(不编码 ! ' ( ) * - . _ ~)
|
||||
json_str = json.dumps(query_list, ensure_ascii=False, separators=(',', ':'))
|
||||
uri_encoded = urllib.parse.quote(json_str, safe="-_.~!*'()")
|
||||
# 3. 自定义 Base64 + 盐值 4. 重排:前2位 + 后3位 + 中间部分
|
||||
en_str = _custom_base64_encode(uri_encoded.encode('utf-8')) + _SALT
|
||||
return en_str[:2] + en_str[-3:] + en_str[2:-3]
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置 ====================
|
||||
# 缓存统一放在 %LOCALAPPDATA%\37duAutomation(影刀版共享目录)
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation'
|
||||
)
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- 组织维护查询接口(与 app 版 ehr/common/config 一致) ----------
|
||||
ORG_QUERY_URL = "https://hr.37du.co/RedseaPlatform/hrRoster/110118b4-b094-11ea-b588-14187743d052/queryRealTimeData.mc"
|
||||
ORG_TABLE_ID = "assemble-pt_organzation"
|
||||
ORG_ROSTER_ID = "110118b4-b094-11ea-b588-14187743d052"
|
||||
PAGE_MAX_SIZE = 500 # 每页最大条数
|
||||
|
||||
# 组织维护查询固定入参(从浏览器抓包提取;登录用户变更时需同步更新 currentUserId / currentStaffId 等)
|
||||
# commonQuery 由自实现前端加密动态生成(等价抓包原始串,即 in_use in ('1') 条件);
|
||||
# 需要追加/修改查询条件时改 ORG_QUERY_CONDITIONS 后由 encode_common_query 重新加密
|
||||
ORG_QUERY_CONDITIONS = [
|
||||
build_condition("`pt_organzation.IN_USE`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="select"),
|
||||
]
|
||||
|
||||
ORG_QUERY_BASE_PARAMS = {
|
||||
"menuName": "组织维护",
|
||||
"useSealTreeData": "0",
|
||||
"treePermitType": "permit",
|
||||
"cancelNodeClick": "1",
|
||||
"clickFlag": "true",
|
||||
"in_use": "1",
|
||||
"commonQuery": encode_common_query(ORG_QUERY_CONDITIONS),
|
||||
"newCondition": "",
|
||||
"urlConditions": "_t%3A1788589944798%23clickFlag%3Atrue%23cancelNodeClick%3A1%23treePermitType%3Apermit%23useSealTreeData%3A0%23menuName%3A%E7%BB%84%E7%BB%87%E7%BB%B4%E6%8A%A4%23_t%3A1788589944798%23",
|
||||
"exportConfig": "",
|
||||
"tableId": ORG_TABLE_ID,
|
||||
"rosterId": ORG_ROSTER_ID,
|
||||
"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": "",
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
}
|
||||
|
||||
# ---------- 接口字段 -> 页面列名映射(「序号」接口不返回,转换时按行号生成;
|
||||
# 分管部门对应 pt_structure2.ORG_ALIAS,当前数据未使用但列位保留) ----------
|
||||
ORG_FIELD_MAP = [
|
||||
("pt_organzation.ORG_NAME", "组织名称"),
|
||||
("pt_organzation.ORG_CODE", "组织编号"),
|
||||
("pt_organzation.ORG_TYPE_CODE", "组织类型"),
|
||||
("pt_structure1.ORG_ALIAS", "上级组织"),
|
||||
("org_principal_staff_name_select.org_principal_staff_name", "组织负责人"),
|
||||
("pt_structure2.ORG_ALIAS", "分管部门"),
|
||||
("branch_leader_name_select.branch_leader_name", "分管领导"),
|
||||
("pt_organzation.BEGIN_DATE", "成立日期"),
|
||||
("pt_orgnization_extend.FOUND_DOC_NUM", "成立文号"),
|
||||
("pt_organzation.CANT_CODE", "所属地区"),
|
||||
("pt_organzation.office_address", "办公地址"),
|
||||
("pt_organzation.remarks", "备注"),
|
||||
("pt_orgnization_extend.FOUND_REASON", "成立原因"),
|
||||
("pt_structure.ORG_FULL_PATH", "组织全路径"),
|
||||
("pt_organzation.create_time", "创建时间"),
|
||||
("pt_organzation.IN_USE", "使用状态"),
|
||||
("pt_organzation_ext.ext_payday", "发薪日"),
|
||||
]
|
||||
|
||||
# 使用状态编码 -> 文字
|
||||
IN_USE_MAP = {"1": "在用", "0": "停用"}
|
||||
|
||||
# ---------- 默认导出参数(内置默认值,便于分发共享;如需覆盖请直接改这里或由 main(args) 传参) ----------
|
||||
DEFAULT_OUTPUT_PATH = r"D:\资料\人资\组织维护\组织维护.xlsx"
|
||||
|
||||
# ---------- 项目级重试次数(单页请求失败最大尝试次数,含首次) ----------
|
||||
MAX_ATTEMPTS = 3
|
||||
|
||||
|
||||
class LoginRequiredError(Exception):
|
||||
"""HR 登录态缺失或失效(接口返回登录页等非 JSON 内容)。"""
|
||||
|
||||
|
||||
# ==================== 登录态(共享 cookies 文件) ====================
|
||||
def _build_session():
|
||||
"""读取共享 HR cookies 构造 requests 会话(仅取 hr.37du.co 域)。
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: 共享 cookies 文件不存在
|
||||
"""
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
raise LoginRequiredError(
|
||||
"未找到 HR 登录态 cookies,请先调用「37duHR登录」指令完成登录后再重试。")
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies or []:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
def _is_expired(text) -> bool:
|
||||
"""接口正常返回 JSON;返回登录页/错误页等非 JSON 即视为登录态过期。"""
|
||||
return bool(text) and not text.lstrip().startswith(("{", "["))
|
||||
|
||||
|
||||
# ==================== 动态日期参数 ====================
|
||||
def get_date_params():
|
||||
"""生成组织维护查询所需的动态日期参数(当月 / 上月 / 当年首月)。"""
|
||||
now = datetime.now()
|
||||
year, month, day = now.year, now.month, now.day
|
||||
|
||||
# 上月(本月 1 号减一天即上月最后一天)
|
||||
last_month_date = datetime(year, month, 1) - timedelta(days=1)
|
||||
|
||||
return {
|
||||
"currentDate": f"{year}-{month:02d}-{day:02d}",
|
||||
"currentMonth": f"{year}{month:02d}",
|
||||
"currentMonthBar": f"{year}-{month:02d}",
|
||||
"lastMonth": f"{last_month_date.year}{last_month_date.month:02d}",
|
||||
"lastMonFirstDay": f"{last_month_date.year}-{last_month_date.month:02d}-01",
|
||||
"lastMonLastDay": last_month_date.strftime("%Y-%m-%d"),
|
||||
"curYearFirstMon": f"{year}01",
|
||||
"curYearFirstMonBar": f"{year}-01",
|
||||
}
|
||||
|
||||
|
||||
# ==================== 接口请求 ====================
|
||||
def _fetch_org_page_once(session, page_no, page_size):
|
||||
"""请求单页组织维护数据(单次请求,不含重试)。"""
|
||||
params = ORG_QUERY_BASE_PARAMS.copy()
|
||||
params.update(get_date_params())
|
||||
params.update({
|
||||
"pageNo": str(page_no),
|
||||
"pageSize": str(page_size),
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"_t": str(int(time.time() * 1000)),
|
||||
})
|
||||
resp = session.request("POST", ORG_QUERY_URL, params=params, timeout=30)
|
||||
if not resp or resp.status_code != 200:
|
||||
raise RuntimeError(f"组织维护接口状态码异常: {getattr(resp, 'status_code', '无响应')}")
|
||||
if _is_expired(resp.text):
|
||||
raise LoginRequiredError("HR 登录态已失效,请先重新调用「37duHR登录」指令完成登录后再重试。")
|
||||
return resp.json()
|
||||
|
||||
|
||||
def _fetch_org_page(session, page_no, page_size=PAGE_MAX_SIZE):
|
||||
"""请求单页组织维护数据(项目级重试:最大 3 次,登录态失效不重试直接抛出)。"""
|
||||
last_exc = None
|
||||
for attempt in range(1, MAX_ATTEMPTS + 1):
|
||||
try:
|
||||
return _fetch_org_page_once(session, page_no, page_size)
|
||||
except LoginRequiredError:
|
||||
raise # 确定性失败,不重试
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt >= MAX_ATTEMPTS:
|
||||
break
|
||||
delay = 2.0 * attempt
|
||||
logger.warning("组织维护第%d页请求第 %d 次失败:%s,%.1f 秒后重试", page_no, attempt, e, delay)
|
||||
time.sleep(delay)
|
||||
logger.error("组织维护第%d页连续 %d 次请求失败,放弃", page_no, MAX_ATTEMPTS)
|
||||
raise last_exc
|
||||
|
||||
|
||||
def fetch_all_orgs(session):
|
||||
"""分页抓取全部组织维护数据(在职组织,in_use=1),返回接口原始记录列表。"""
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
total_page = None
|
||||
while True:
|
||||
data = _fetch_org_page(session, page_no, PAGE_MAX_SIZE)
|
||||
if data.get("state") != "1":
|
||||
raise RuntimeError(f"组织维护第{page_no}页接口返回错误:{data.get('meg') or data.get('des')}")
|
||||
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("组织维护无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
|
||||
if total_page is None:
|
||||
logger.info("总记录数:%s,总页数:%s", data.get("count"), data.get("pageCount"))
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("组织维护已抓取 %d/%s 页,累计 %d/%s 条",
|
||||
page_no, total_page, len(all_rows), data.get("count"))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2) # 轻微限速,避免触发风控
|
||||
return all_rows
|
||||
|
||||
|
||||
# ==================== 字段转换 ====================
|
||||
def to_org_rows(datalist):
|
||||
"""将接口原始记录转换为页面列名顺序的字典列表(18 列,含序号)。"""
|
||||
rows = []
|
||||
for i, r in enumerate(datalist, 1):
|
||||
row = {"序号": i}
|
||||
for key, name in ORG_FIELD_MAP:
|
||||
value = r.get(key)
|
||||
if name == "使用状态":
|
||||
value = IN_USE_MAP.get(str(value), value)
|
||||
elif name == "成立日期" and value:
|
||||
value = str(value).split(" ")[0] # 去掉 00:00:00 时分秒
|
||||
row[name] = value
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 导出主流程 ====================
|
||||
def export_orgs(output_path=None):
|
||||
"""查询全部组织维护数据并导出 Excel(18 列,与页面列一致)。
|
||||
|
||||
Args:
|
||||
output_path: Excel 保存路径(默认 DEFAULT_OUTPUT_PATH)
|
||||
|
||||
Returns:
|
||||
(导出文件路径, 数据条数)
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: HR 登录态缺失或失效
|
||||
RuntimeError: 请求失败(重试耗尽)或接口返回异常
|
||||
"""
|
||||
output_path = output_path or DEFAULT_OUTPUT_PATH
|
||||
|
||||
logger.info("===== 开始组织维护导出,保存路径:%s =====", output_path)
|
||||
session = _build_session()
|
||||
datalist = fetch_all_orgs(session)
|
||||
if not datalist:
|
||||
raise RuntimeError("组织维护接口未查询到任何数据")
|
||||
|
||||
rows = to_org_rows(datalist)
|
||||
out_dir = os.path.dirname(output_path)
|
||||
if out_dir:
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
pd.DataFrame(rows).to_excel(output_path, index=False)
|
||||
logger.info("===== 组织维护导出完成:共 %d 条,已保存 %s =====", len(rows), output_path)
|
||||
return output_path, len(rows)
|
||||
|
||||
|
||||
def main(output_path=None):
|
||||
"""影刀自定义指令入口「37du组织维护导出」。
|
||||
|
||||
Args:
|
||||
output_path: Excel 保存路径(缺省用内置默认值 DEFAULT_OUTPUT_PATH)
|
||||
|
||||
Returns:
|
||||
{"success": bool, "save_path": str, "count": int}
|
||||
save_path 即导出的 Excel 文件路径。
|
||||
"""
|
||||
output_path = output_path or DEFAULT_OUTPUT_PATH
|
||||
try:
|
||||
save_path, count = export_orgs(output_path)
|
||||
return {"success": True, "save_path": save_path, "count": count}
|
||||
except Exception as e:
|
||||
logger.error("组织维护导出失败:%s", e)
|
||||
return {"success": False, "error": str(e), "save_path": output_path}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
output_path = r"D:\资料\人资\组织维护\组织维护.xlsx"
|
||||
main(output_path)
|
||||
@@ -0,0 +1,661 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: roster_export_api.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-05
|
||||
@Description: 员工花名册导出(影刀共享指令,单文件自包含)——纯接口版。
|
||||
与浏览器版 roster_export.py 的 main(...) 调用签名完全一致:
|
||||
main(statuses, leave_start, leave_end, template, output_path, download_dir)
|
||||
底层改为:访问台账页面绑定会话 -> ws/bridge 注册 -> WebSocket 订阅主题 ->
|
||||
POST exportCommonListData 异步导出(服务端生成 Excel 并翻译全部字典字段)->
|
||||
接收 "--end--|文件路径" 推送 -> 下载临时文件 -> 按状态合并(追加「类型」列)。
|
||||
无需 DrissionPage/浏览器,字典翻译(星级/参保类型/职衔/职级等)由服务端完成。
|
||||
@Version: 1.0.0
|
||||
|
||||
运行方式:
|
||||
1. 影刀:注册为自定义指令「37du花名册导出」,main(...) 关键字传参(缺省用内置默认值,见 DEFAULT_* 常量)
|
||||
statuses 在职状态,str "在职" / "在职,离职" 或 list(默认 在职+离职)
|
||||
leave_start 离职时间开始 "YYYY-MM-DD"(离职时需要;不传默认 上月1日到今天)
|
||||
leave_end 离职时间结束 "YYYY-MM-DD"(离职时需要;不传默认 上月1日到今天)
|
||||
template 自定义导出模板名(默认 员工基础信息)
|
||||
output_path 合并后 Excel 保存路径(默认 D:\\资料\\人资\\花名册\\花名册.xlsx)
|
||||
download_dir 单状态临时文件目录(默认 D:\\资料\\人资\\花名册\\download,合并后自动清理)
|
||||
2. 命令行:python roster_export_api.py 直接运行(__main__ 中按示例传参)
|
||||
3. 业务脚本:懒加载本模块调用 main(...) / export_roster(...)
|
||||
|
||||
依赖安装(启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install requests pandas openpyxl websocket-client
|
||||
|
||||
登录态:读取 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json(由「37duHR登录」指令写入);
|
||||
缺失/失效时不自动补登,抛出提示先重新执行「37duHR登录」指令。
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.parse
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
# ==================== 第三方库导入(启动校验:全部必须预先安装,不懒加载) ====================
|
||||
try:
|
||||
import requests
|
||||
import pandas as pd
|
||||
import websocket # websocket-client
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(共享指令要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install requests pandas openpyxl websocket-client\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging,正常 INFO 不输出大体积 JSON) ====================
|
||||
class _PrintLogger:
|
||||
def debug(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def info(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def warning(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def error(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== commonQuery 前端加密(自实现,与前端行为一致,已实测接口可用) ====================
|
||||
# 自定义 Base64 字符表(索引0~63,64为填充字符)
|
||||
_CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
|
||||
_PAD_CHAR = '7' # 填充字符(索引64)
|
||||
_SALT = "yyryrtweasdasd" # 固定盐值
|
||||
|
||||
|
||||
def _custom_base64_encode(data):
|
||||
"""使用自定义字符表进行 Base64 编码(data 为 UTF-8 字节序列)。"""
|
||||
result = []
|
||||
for i in range(0, len(data), 3):
|
||||
chunk = data[i:i + 3]
|
||||
b1 = chunk[0] if len(chunk) > 0 else 0
|
||||
b2 = chunk[1] if len(chunk) > 1 else 0
|
||||
b3 = chunk[2] if len(chunk) > 2 else 0
|
||||
|
||||
enc1 = (b1 >> 2) & 0x3F
|
||||
enc2 = ((b1 << 4) | (b2 >> 4)) & 0x3F
|
||||
enc3 = ((b2 << 2) | (b3 >> 6)) & 0x3F
|
||||
enc4 = b3 & 0x3F
|
||||
|
||||
if len(chunk) == 1:
|
||||
enc3 = 64
|
||||
enc4 = 64
|
||||
elif len(chunk) == 2:
|
||||
enc4 = 64
|
||||
|
||||
result.append(_CUSTOM_CHARS[enc1])
|
||||
result.append(_CUSTOM_CHARS[enc2])
|
||||
result.append(_CUSTOM_CHARS[enc3])
|
||||
result.append(_CUSTOM_CHARS[enc4])
|
||||
return ''.join(result)
|
||||
|
||||
|
||||
def build_condition(query_field, query_type, query_value, query_text="",
|
||||
left_bracket="", right_bracket="", logic="AND", input_type="text"):
|
||||
"""构造一个符合前端格式的单条查询条件字典。"""
|
||||
return {
|
||||
"queryField": query_field,
|
||||
"leftBracket": left_bracket,
|
||||
"queryType": query_type,
|
||||
"queryValue": query_value,
|
||||
"queryText": query_text,
|
||||
"rightBracket": right_bracket,
|
||||
"logic": logic,
|
||||
"inputType": input_type,
|
||||
}
|
||||
|
||||
|
||||
def encode_common_query(query_list):
|
||||
"""将查询条件列表加密为 commonQuery 字符串(encodeURIComponent + 自定义 Base64 + 盐值 + 首尾重排)。"""
|
||||
# 1. JSON(无空格,同 JSON.stringify) 2. URI 编码(不编码 ! ' ( ) * - . _ ~)
|
||||
json_str = json.dumps(query_list, ensure_ascii=False, separators=(',', ':'))
|
||||
uri_encoded = urllib.parse.quote(json_str, safe="-_.~!*'()")
|
||||
# 3. 自定义 Base64 + 盐值 4. 重排:前2位 + 后3位 + 中间部分
|
||||
en_str = _custom_base64_encode(uri_encoded.encode('utf-8')) + _SALT
|
||||
return en_str[:2] + en_str[-3:] + en_str[2:-3]
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置 ====================
|
||||
# 缓存统一放在 %LOCALAPPDATA%\37duAutomation(影刀版共享目录)
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation'
|
||||
)
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- 员工花名册查询/导出接口(与 app 版 ehr/common/hr_api 一致) ----------
|
||||
ROSTER_ID = "1116da64-b094-11ea-b588-14187743d052"
|
||||
ROSTER_PAGE_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{ROSTER_ID}/getCustomCommonList.mc"
|
||||
ROSTER_EXPORT_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{ROSTER_ID}/exportCommonListData.mc"
|
||||
BRIDGE_URL = "https://hr.37du.co/RedseaPlatform/ws/bridge"
|
||||
# 自定义导出模板定义(页面「自定义导出」弹窗同款接口:列表拿 id -> 详情拿 exportField)
|
||||
TEMPLATE_LIST_URL = ("https://hr.37du.co/RedseaPlatform/redmagicapi/"
|
||||
"rf_pt_users_export_define_select/getExecuteResult.mc")
|
||||
TEMPLATE_DETAIL_URL = "https://hr.37du.co/RedseaPlatform/ptUsersExportDefine/getPtusersexportdefine.mc"
|
||||
WS_EXPORT_THEME = "HR_DEFINED_HMC_EXPORT"
|
||||
WS_SERVICE_URL = "wss://hr.37du.co/RedseaPlatform/ws/service?theme=" + WS_EXPORT_THEME
|
||||
XHR_HEADERS = {"X-Requested-With": "XMLHttpRequest"}
|
||||
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36"
|
||||
|
||||
# 花名册查询固定入参(从浏览器抓包提取;登录用户变更时需同步更新 currentUserId / currentStaffId 等)
|
||||
# commonQuery 在导出时按「在职/离职」条件动态加密生成
|
||||
ROSTER_QUERY_BASE_PARAMS = {
|
||||
"menuName": "员工花名册",
|
||||
"useSealTreeData": "0",
|
||||
"treePermitType": "permit",
|
||||
"cancelNodeClick": "1",
|
||||
"clickFlag": "true",
|
||||
"in_use": "1",
|
||||
"commonQuery": "",
|
||||
"newCondition": "",
|
||||
"urlConditions": "",
|
||||
"exportConfig": "",
|
||||
"tableId": "assemble-hr_staff_base",
|
||||
"rosterId": ROSTER_ID,
|
||||
"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": "",
|
||||
}
|
||||
|
||||
# ---------- 自定义导出模板(exportFilters 字段串,顺序与页面导出模板列一致) ----------
|
||||
ROSTER_TEMPLATE_FILTERS = {
|
||||
# 「员工基础信息」模板(31 列,与页面抓包 exportFilters 一致)
|
||||
"员工基础信息": ",".join([
|
||||
"hr_staff_base.staff_name", # 姓名
|
||||
"hr_staff_base.base_code", # 工号
|
||||
"hr_staff_base.idCard", # 证件号
|
||||
"hr_staff_base.join_date", # 入职时间
|
||||
"hr_staff_base.leaveOffice_date", # 离职时间
|
||||
"pt_staff_stru.BELONG_UNIT_ORG_NAME", # 所属单位
|
||||
"pt_staff_stru.DEPT_ORG_NAME", # 所属部门
|
||||
"pt_staff_stru.DEPT_ORG_ONE", # 一级部门
|
||||
"pt_staff_stru.DEPT_ORG_TWO", # 二级部门
|
||||
"pt_staff_stru.DEPT_ORG_THREE", # 三级部门
|
||||
"pt_staff_stru.DEPT_ORG_FOUR", # 四级部门
|
||||
"pt_staff_stru.DEPT_ORG_FIVE", # 五级部门
|
||||
"pt_staff_stru.POST_ORG_NAME", # 岗位
|
||||
"hr_staff_base_ext.ext_technician_code", # 技师工号
|
||||
"hr_staff_base_ext.ext_star_level", # 星级
|
||||
"pt_staff_stru.first_type_id", # 职位序列
|
||||
"pt_staff_stru.POST_LEVEL_ID", # 职衔
|
||||
"pt_staff_stru.PT_POST_GRADE_ID", # 职级
|
||||
"pt_post_level.ext_grade_name", # 职等
|
||||
"hr_staff_base.mobile_phone", # 手机号码
|
||||
"hr_staff_base.person_status", # 在职状态
|
||||
"hr_staff_base_ext.ext_insurance_type", # 参保类型
|
||||
"pt_staff_stru.ORG_FULL_PATH", # 组织全路径
|
||||
"hr_staff_base.nation", # 民族
|
||||
"hr_staff_base.sex", # 性别
|
||||
"hr_staff_base.age", # 年龄
|
||||
"hr_staff_base.period", # 试用期限(月)
|
||||
"hr_staff_base.pre_correction_date", # 试用期结束日期
|
||||
"hr_staff_base_ext.ext_trans_type", # 上下班交通方式
|
||||
"hr_staff_base_ext.ext_recruit_way", # 招聘渠道
|
||||
"hr_staff_base.identity", # 用工类型
|
||||
]),
|
||||
# 「雇主险增减员导出模板」(14 列,无三级/五级部门,顺序按模板)
|
||||
"雇主险增减员导出模板": ",".join([
|
||||
"pt_staff_stru.BELONG_UNIT_ORG_NAME", # 所属单位
|
||||
"pt_staff_stru.DEPT_ORG_ONE", # 一级部门
|
||||
"pt_staff_stru.DEPT_ORG_TWO", # 二级部门
|
||||
"pt_staff_stru.DEPT_ORG_FOUR", # 四级部门
|
||||
"hr_staff_base.base_code", # 工号
|
||||
"hr_staff_base.age", # 年龄
|
||||
"hr_staff_base.sex", # 性别
|
||||
"pt_staff_stru.POST_ORG_NAME", # 岗位
|
||||
"pt_staff_stru.first_type_id", # 职位序列
|
||||
"hr_staff_base_ext.ext_insurance_type", # 参保类型
|
||||
"hr_staff_base_ext.ext_trans_type", # 上下班交通方式
|
||||
"hr_staff_base.join_date", # 入职时间
|
||||
"hr_staff_base.staff_name", # 姓名
|
||||
"hr_staff_base.idCard", # 证件号
|
||||
]),
|
||||
}
|
||||
|
||||
# ---------- 默认导出参数(与浏览器版 roster_export.py 保持一致) ----------
|
||||
DEFAULT_TEMPLATE = "员工基础信息"
|
||||
DEFAULT_STATUSES = ["在职", "离职"]
|
||||
DEFAULT_OUTPUT_PATH = r"D:\资料\人资\花名册\花名册.xlsx"
|
||||
DEFAULT_DOWNLOAD_DIR = r"D:\资料\人资\花名册\download"
|
||||
DEFAULT_TTL_SECONDS = 15 * 60 # 缓存有效期(秒)
|
||||
|
||||
# 异步导出等待超时(秒,服务端逐条生成 7000+ 条约需 10~20 秒,留足余量)
|
||||
EXPORT_TIMEOUT_SECONDS = 300
|
||||
|
||||
# ---------- 项目级重试次数(单状态导出失败最大尝试次数,含首次) ----------
|
||||
MAX_ATTEMPTS = 3
|
||||
|
||||
|
||||
class LoginRequiredError(Exception):
|
||||
"""HR 登录态缺失或失效(接口返回登录页等非 JSON 内容)。"""
|
||||
|
||||
|
||||
# ==================== 登录态(共享 cookies 文件) ====================
|
||||
def _build_session():
|
||||
"""读取共享 HR cookies 构造 requests 会话(仅取 37du.co 域)。
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: 共享 cookies 文件不存在
|
||||
"""
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
raise LoginRequiredError(
|
||||
"未找到 HR 登录态 cookies,请先调用「37duHR登录」指令完成登录后再重试。")
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": USER_AGENT,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies or []:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
def _is_expired(text) -> bool:
|
||||
"""接口正常返回 JSON;返回登录页/错误页等非 JSON 即视为登录态过期。"""
|
||||
return bool(text) and not text.lstrip().startswith(("{", "["))
|
||||
|
||||
|
||||
# ==================== 动态日期参数 ====================
|
||||
def get_date_params():
|
||||
"""生成花名册查询所需的动态日期参数(当月 / 上月 / 当年首月)。"""
|
||||
now = datetime.now()
|
||||
year, month, day = now.year, now.month, now.day
|
||||
|
||||
# 上月(本月 1 号减一天即上月最后一天)
|
||||
last_month_date = datetime(year, month, 1) - timedelta(days=1)
|
||||
|
||||
return {
|
||||
"currentDate": f"{year}-{month:02d}-{day:02d}",
|
||||
"currentMonth": f"{year}{month:02d}",
|
||||
"currentMonthBar": f"{year}-{month:02d}",
|
||||
"lastMonth": f"{last_month_date.year}{last_month_date.month:02d}",
|
||||
"lastMonFirstDay": f"{last_month_date.year}-{last_month_date.month:02d}-01",
|
||||
"lastMonLastDay": last_month_date.strftime("%Y-%m-%d"),
|
||||
"curYearFirstMon": f"{year}01",
|
||||
"curYearFirstMonBar": f"{year}-01",
|
||||
}
|
||||
|
||||
|
||||
def _get_leave_range(today=None):
|
||||
"""计算离职筛选时间范围:默认上月 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 _build_in_service_conditions():
|
||||
"""在职人员条件:主职 in (1) + 在职状态 in (1),等价页面默认抓包条件。"""
|
||||
return [
|
||||
build_condition("`pt_staff_stru.POST_STRU_ID`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="select"),
|
||||
build_condition("`hr_staff_base.person_status`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="multipleSelect"),
|
||||
]
|
||||
|
||||
|
||||
def _build_leave_conditions(leave_start, leave_end):
|
||||
"""离职人员条件:主职 in (1) + 在职状态 in (2) + 离职时间区间,等价页面离职筛选抓包串。"""
|
||||
return [
|
||||
build_condition("`pt_staff_stru.POST_STRU_ID`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="select"),
|
||||
build_condition("`hr_staff_base.person_status`", "in", "2",
|
||||
query_text="2", left_bracket="(", right_bracket=")",
|
||||
input_type="multipleSelect"),
|
||||
build_condition("`hr_staff_base.leaveOffice_date`", ">=", leave_start,
|
||||
left_bracket="(", input_type="date"),
|
||||
build_condition("`hr_staff_base.leaveOffice_date`", "<=", leave_end,
|
||||
right_bracket=")", input_type="date"),
|
||||
]
|
||||
|
||||
|
||||
# ==================== 自定义导出模板动态解析 ====================
|
||||
def resolve_template_filters(session, template_name, user_id=None):
|
||||
"""按模板名动态解析 exportFilters 字段串(与页面「自定义导出」弹窗逻辑一致)。
|
||||
|
||||
两步:模板列表(redmagicapi select,拿 id + ext1 名称)-> 模板详情
|
||||
(getPtusersexportdefine,拿 exportField JSON)-> 按 exportField 顺序拼接字段串。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
template_name: 模板名(对应模板列表的 ext1)
|
||||
user_id: 当前登录用户 id(缺省用 ROSTER_QUERY_BASE_PARAMS 里的 currentUserId)
|
||||
|
||||
Returns:
|
||||
exportFilters 字段串(逗号分隔,顺序与模板一致);解析失败返回 None(调用方回退内置模板)
|
||||
"""
|
||||
user_id = user_id or ROSTER_QUERY_BASE_PARAMS["currentUserId"]
|
||||
try:
|
||||
# 1. 模板列表 -> 按名称匹配拿 id
|
||||
r = session.post(TEMPLATE_LIST_URL, headers=XHR_HEADERS, timeout=15).json()
|
||||
templates = r.get("jsonList") or []
|
||||
target = next((t for t in templates if t.get("ext1") == template_name), None)
|
||||
if not target:
|
||||
logger.warning("模板列表中未找到「%s」(可选:%s),回退内置模板",
|
||||
template_name, [t.get("ext1") for t in templates])
|
||||
return None
|
||||
|
||||
# 2. 模板详情 -> exportField JSON -> 按顺序拼字段串
|
||||
r2 = session.post(TEMPLATE_DETAIL_URL, headers=XHR_HEADERS,
|
||||
data={"rosterId": ROSTER_ID, "id": target["id"]}, timeout=15).json()
|
||||
export_field = (r2.get("result") or {}).get("exportField") or ""
|
||||
fields = json.loads(export_field)
|
||||
if not fields:
|
||||
logger.warning("模板「%s」详情无 exportField,回退内置模板", template_name)
|
||||
return None
|
||||
filters = ",".join(f["tableCode"] for f in fields)
|
||||
logger.info("模板「%s」动态解析成功(%d 列)", template_name, len(fields))
|
||||
return filters
|
||||
except Exception as e:
|
||||
logger.warning("模板「%s」动态解析失败:%s,回退内置模板", template_name, e)
|
||||
return None
|
||||
|
||||
|
||||
# ==================== WebSocket 异步导出(单状态) ====================
|
||||
def _bind_session(session):
|
||||
"""绑定会话:先访问台账页面,再调用 ws/bridge 注册 HTTP 会话到 WS 容器。
|
||||
|
||||
服务端依赖页面访问后的会话状态,未绑定时 bridge 返回 "0"、WS 握手报 500(用户登录)。
|
||||
"""
|
||||
session.get(ROSTER_PAGE_URL, params={"clickFlag": "true", "treePermitType": "permit",
|
||||
"useSealTreeData": "0"}, timeout=30)
|
||||
r = session.post(BRIDGE_URL, data={}, headers=XHR_HEADERS, timeout=10)
|
||||
if "成功" not in r.text and r.text.strip() != "1":
|
||||
raise LoginRequiredError(
|
||||
f"ws/bridge 会话注册失败(登录态可能已失效):{r.text[:100]}。"
|
||||
"请先重新调用「37duHR登录」指令完成登录后再重试。")
|
||||
|
||||
|
||||
def _export_one_status_once(session, status, download_dir, template_name,
|
||||
leave_start=None, leave_end=None, export_filters=None):
|
||||
"""单个在职状态的异步导出(单次尝试):提交任务 -> WS 收 --end-- -> 下载临时文件。
|
||||
|
||||
Returns:
|
||||
临时 Excel 文件路径
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: 登录态失效
|
||||
RuntimeError: 提交失败 / 超时 / 下载失败
|
||||
"""
|
||||
# 1. 会话绑定(页面访问 + bridge 注册)
|
||||
_bind_session(session)
|
||||
|
||||
# 2. WebSocket 连接并订阅主题
|
||||
cookie_hdr = "; ".join(f"{c.name}={c.value}" for c in 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)
|
||||
try:
|
||||
ws.send(json.dumps({"theme": WS_EXPORT_THEME, "code": "SUBCRIBE_THEME"}))
|
||||
ack = json.loads(ws.recv())
|
||||
if ack.get("code") != "SUBCRIBE_THEME_ACK":
|
||||
raise RuntimeError(f"WS 订阅失败:{str(ack)[:100]}")
|
||||
logger.info("WS 订阅成功(%s)", WS_EXPORT_THEME)
|
||||
|
||||
# 3. 提交异步导出任务(按状态构造 commonQuery,服务端翻译全部字典字段)
|
||||
params = {k: str(v) for k, v in ROSTER_QUERY_BASE_PARAMS.items()}
|
||||
if status == "离职":
|
||||
ls = leave_start or ""
|
||||
le = leave_end or ""
|
||||
if not ls or not le:
|
||||
ls, le = _get_leave_range()
|
||||
params["commonQuery"] = encode_common_query(_build_leave_conditions(ls, le))
|
||||
logger.info("离职时间范围:%s ~ %s", ls, le)
|
||||
else:
|
||||
params["commonQuery"] = encode_common_query(_build_in_service_conditions())
|
||||
params.update(get_date_params())
|
||||
params["exportConfig"] = json.dumps(
|
||||
{"exportName": template_name,
|
||||
"exportFilters": export_filters or ROSTER_TEMPLATE_FILTERS.get(template_name, "")},
|
||||
ensure_ascii=False, separators=(",", ":"))
|
||||
params["_t"] = str(int(time.time() * 1000))
|
||||
|
||||
resp = session.post(ROSTER_EXPORT_URL, data=params, headers=XHR_HEADERS, timeout=30)
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"提交导出任务失败:HTTP {resp.status_code}")
|
||||
logger.info("导出任务已提交(状态:%s,模板:%s)", status, template_name)
|
||||
|
||||
# 4. 接收进度推送,直到 --end--|文件路径
|
||||
file_url = None
|
||||
deadline = time.time() + EXPORT_TIMEOUT_SECONDS
|
||||
ws.settimeout(EXPORT_TIMEOUT_SECONDS)
|
||||
while time.time() < deadline:
|
||||
msg = json.loads(ws.recv())
|
||||
txt, code = msg.get("txt", ""), msg.get("code", "")
|
||||
if code != "NORMAL_PUSH_TO":
|
||||
continue
|
||||
if txt.startswith("--end--"):
|
||||
file_url = txt.split("|", 1)[1].strip()
|
||||
break
|
||||
if txt.startswith(("开始下载", "正在生成")):
|
||||
logger.info(" 进度:%s", txt)
|
||||
if not file_url:
|
||||
raise RuntimeError(f"等待导出文件超时({EXPORT_TIMEOUT_SECONDS}s)")
|
||||
logger.info("导出完成,文件地址:%s", file_url)
|
||||
finally:
|
||||
ws.close()
|
||||
|
||||
# 5. 下载文件到临时目录
|
||||
dl_url = "https://hr.37du.co" + file_url if file_url.startswith("/") else file_url
|
||||
dl = session.get(dl_url, timeout=120)
|
||||
if dl.status_code != 200 or not dl.content:
|
||||
raise RuntimeError(f"下载导出文件失败:HTTP {dl.status_code},{len(dl.content)} 字节")
|
||||
os.makedirs(download_dir, exist_ok=True)
|
||||
temp_path = os.path.join(download_dir, f"花名册_{status}_{int(time.time())}.xlsx")
|
||||
with open(temp_path, "wb") as f:
|
||||
f.write(dl.content)
|
||||
logger.info("已下载临时文件:%s(%d 字节)", temp_path, len(dl.content))
|
||||
return temp_path
|
||||
|
||||
|
||||
def _export_one_status(session, status, download_dir, template_name,
|
||||
leave_start=None, leave_end=None, export_filters=None):
|
||||
"""导出单个在职状态的花名册(项目级重试:最大 3 次,登录态失效不重试直接抛出)。"""
|
||||
last_exc = None
|
||||
for attempt in range(1, MAX_ATTEMPTS + 1):
|
||||
try:
|
||||
return _export_one_status_once(session, status, download_dir, template_name,
|
||||
leave_start, leave_end, export_filters)
|
||||
except LoginRequiredError:
|
||||
raise # 确定性失败,不重试
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt >= MAX_ATTEMPTS:
|
||||
break
|
||||
delay = 2.0 * attempt
|
||||
logger.warning("导出在职状态「%s」第 %d 次失败:%s,%.1f 秒后重试",
|
||||
status, attempt, e, delay)
|
||||
time.sleep(delay)
|
||||
logger.error("导出在职状态「%s」连续 %d 次失败,放弃", status, MAX_ATTEMPTS)
|
||||
raise last_exc
|
||||
|
||||
|
||||
# ==================== 合并输出 ====================
|
||||
def _normalize_and_save(files_with_status, output_path):
|
||||
"""合并多个花名册 Excel 文件,添加「类型」列标识在职状态(与浏览器版输出规范一致)。
|
||||
|
||||
统一输出格式(各业务场景读取端按此规范读取):
|
||||
- 只保留第2行表头,丢弃第1行标题(源表第1行为模板名标题)
|
||||
- 「类型」列统一追加在最后一列,标识在职状态
|
||||
- 单 sheet,表头在第1行,数据第2行起
|
||||
"""
|
||||
dfs = []
|
||||
for status, path in files_with_status:
|
||||
df = pd.read_excel(path, header=1) # 取第2行作表头,丢弃第1行标题
|
||||
df["类型"] = status # 类型列统一追加到最后一列
|
||||
dfs.append(df)
|
||||
logger.info("读取花名册文件:%s(%s,%d 行)", path, status, len(df))
|
||||
merged = pd.concat(dfs, ignore_index=True)
|
||||
out_dir = os.path.dirname(output_path)
|
||||
if out_dir:
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
merged.to_excel(output_path, index=False)
|
||||
logger.info("合并完成,共 %d 行,已保存:%s", len(merged), output_path)
|
||||
|
||||
# 删除临时下载的单个文件
|
||||
for _, path in files_with_status:
|
||||
try:
|
||||
os.remove(path)
|
||||
except Exception:
|
||||
pass
|
||||
return output_path
|
||||
|
||||
|
||||
# ==================== 导出主流程 ====================
|
||||
def export_roster(download_dir=None, output_path=None, template_name=None,
|
||||
statuses=None, leave_start=None, leave_end=None, ttl=DEFAULT_TTL_SECONDS):
|
||||
"""执行员工花名册自定义导出(按需在职状态,各导一次),合并为一个 Excel 文件。
|
||||
|
||||
带 TTL 缓存:output_path 已有且距上次导出不超过 ttl 秒时直接复用(跳过接口导出),
|
||||
超时才重新导出。花名册版本由「模板 + 输出路径」共同隔离(各业务场景路径独立),
|
||||
不同模板导出到不同路径,不会互相复用。纯接口实现,无需浏览器。
|
||||
|
||||
Args:
|
||||
download_dir: 单状态临时文件目录(默认 DEFAULT_DOWNLOAD_DIR)
|
||||
output_path: 合并后保存路径(默认 DEFAULT_OUTPUT_PATH)
|
||||
template_name: 自定义导出模板名(默认 DEFAULT_TEMPLATE)
|
||||
statuses: 需导出的在职状态列表,如 ["在职"] / ["离职"] / ["在职","离职"]
|
||||
(默认 DEFAULT_STATUSES)
|
||||
leave_start / leave_end: 离职时间范围 "YYYY-MM-DD"(离职状态时生效;缺省自动计算)
|
||||
ttl: 缓存有效期(秒),默认 DEFAULT_TTL_SECONDS(15 分钟);传 0 表示总是重新导出
|
||||
|
||||
Returns:
|
||||
合并后的花名册文件路径
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: HR 登录态缺失或失效
|
||||
RuntimeError: 导出失败(重试耗尽)或接口返回异常
|
||||
"""
|
||||
download_dir = download_dir or DEFAULT_DOWNLOAD_DIR
|
||||
output_path = output_path or DEFAULT_OUTPUT_PATH
|
||||
template_name = template_name or DEFAULT_TEMPLATE
|
||||
statuses = list(statuses) if statuses else list(DEFAULT_STATUSES)
|
||||
if ttl is None: # None 使用默认缓存有效期
|
||||
ttl = DEFAULT_TTL_SECONDS
|
||||
|
||||
# TTL 缓存:输出路径已有、非空且距上次导出不超过 ttl 秒时直接复用,跳过接口导出
|
||||
if ttl > 0 and os.path.exists(output_path) \
|
||||
and os.path.getsize(output_path) > 0 \
|
||||
and time.time() - os.path.getmtime(output_path) <= ttl:
|
||||
logger.info("花名册缓存命中(%.0f 分钟内已导出,直接复用):%s", ttl / 60.0, output_path)
|
||||
return output_path
|
||||
|
||||
leave_desc = ""
|
||||
if "离职" in statuses:
|
||||
ls, le = leave_start or "", leave_end or ""
|
||||
if not ls or not le:
|
||||
ls, le = _get_leave_range()
|
||||
leave_desc = f",离职时间 {ls} ~ {le}"
|
||||
logger.info("===== 开始花名册导出(模板:%s,在职状态:%s%s),临时目录:%s =====",
|
||||
template_name, statuses, leave_desc, download_dir)
|
||||
|
||||
session = _build_session()
|
||||
# 模板动态解析(列表 -> 详情 -> exportField),失败回退内置模板字段串
|
||||
export_filters = resolve_template_filters(session, template_name)
|
||||
|
||||
files_with_status = []
|
||||
for status in statuses:
|
||||
logger.info("===== 开始导出在职状态:%s =====", status)
|
||||
path = _export_one_status(session, status, download_dir, template_name,
|
||||
leave_start, leave_end, export_filters)
|
||||
files_with_status.append((status, path))
|
||||
|
||||
# 合并所有花名册文件
|
||||
result = _normalize_and_save(files_with_status, output_path)
|
||||
logger.info("===== 花名册导出并合并完成:%s =====", result)
|
||||
return result
|
||||
|
||||
|
||||
def main(statuses=None, leave_start=None, leave_end=None,
|
||||
template=None, output_path=None, download_dir=None):
|
||||
"""影刀自定义指令入口「37du花名册导出」(与浏览器版 roster_export.py 签名一致)。
|
||||
|
||||
Args(缺省用内置默认值,见 DEFAULT_* 常量):
|
||||
statuses: 在职状态,str "在职" 或 "在职,离职",或 list ["在职","离职"]
|
||||
leave_start / leave_end: 离职时间范围 "YYYY-MM-DD"(离职时需要;不传默认 上月1日到今天)
|
||||
template: 自定义导出模板名
|
||||
output_path / download_dir: 保存路径与临时下载目录
|
||||
|
||||
Returns:
|
||||
{"success": bool, "save_path": str, "statuses": [...], "template": str}
|
||||
save_path 即调用方传入的 output_path(合并后的花名册文件路径)。
|
||||
"""
|
||||
# 在职状态:兼容 str / list / 逗号分隔
|
||||
if isinstance(statuses, str):
|
||||
statuses = [s.strip() for s in statuses.replace(",", ",").split(",") if s.strip()]
|
||||
elif statuses:
|
||||
statuses = [str(s) for s in statuses]
|
||||
else:
|
||||
statuses = list(DEFAULT_STATUSES)
|
||||
|
||||
template = template or DEFAULT_TEMPLATE
|
||||
output_path = output_path or DEFAULT_OUTPUT_PATH
|
||||
download_dir = download_dir or DEFAULT_DOWNLOAD_DIR
|
||||
|
||||
try:
|
||||
save_path = export_roster(
|
||||
download_dir=download_dir, output_path=output_path,
|
||||
template_name=template, statuses=statuses,
|
||||
leave_start=leave_start, leave_end=leave_end)
|
||||
return {"success": True, "save_path": save_path, "statuses": statuses, "template": template}
|
||||
except Exception as e:
|
||||
logger.error("花名册导出失败:%s", e)
|
||||
return {"success": False, "error": str(e), "statuses": statuses, "template": template}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
statuses = ["在职"]
|
||||
leave_start = ""
|
||||
leave_end = ""
|
||||
template = "员工基础信息"
|
||||
output_path = r"D:\资料\人资\排班异常识别\员工花名册.xlsx"
|
||||
main(statuses=statuses, leave_start=leave_start, leave_end=leave_end,
|
||||
template=template, output_path=output_path)
|
||||
@@ -0,0 +1,440 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: seal_data_export.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-07
|
||||
@UpdateTime: 2026-09-07
|
||||
@Description: 考勤月报封存检查 - 封存数据导出与预处理模块(影刀单文件,自包含)。
|
||||
统一负责:拉取当月全集团考勤封存数据 → 预处理筛选(所属单位仅保留白名单单位)→
|
||||
保存为预处理后的封存表(固定路径)。检查1/检查5 等各检查模块不再直连接口,
|
||||
一律通过本模块 load_seal_rows() 读取预处理封存表。
|
||||
|
||||
所属单位白名单(预处理口径,需调整时只改 SEAL_UNIT_WHITELIST 一处):
|
||||
财务管理部 / 集团管理中心 / 集团营建中心 / 金色印象事业部 / 金色湖畔事业部
|
||||
|
||||
数据来源(接口直取,对应 aa.md / aa.json):
|
||||
- 接口:POST https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc
|
||||
sqlId = kq_count_leave_wage_SelectV2,入参 yearmonth = YYYYMM,base_code 留空 = 全集团批量。
|
||||
- 每员工一条封存记录,所属单位字段 BELONG_UNIT_ORG_NAME(aa.md 列:所属单位)。
|
||||
|
||||
输出:
|
||||
考勤封存数据_{月份}.xlsx 预处理后的封存表(固定路径,覆盖式保存,仅含白名单单位员工,
|
||||
中文表头,供人工复核 & 各检查模块读取复用)。
|
||||
|
||||
依赖安装(启动校验:必须预先装齐):
|
||||
pip install requests pandas openpyxl python-dotenv
|
||||
|
||||
运行前置:需存在「37duHR登录」写入的共享登录态(hr_cookies.json)。
|
||||
|
||||
环境变量(可选):
|
||||
monthly_seal_save_dir 输出目录(默认 D:\\资料\\人资\\考勤异常)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
from datetime import date, datetime
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
# ==================== 第三方库(启动校验:全部装齐,不懒加载) ====================
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐)。\n"
|
||||
"请先执行安装:\n pip install requests pandas openpyxl python-dotenv\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging,保持单文件无外部依赖) ====================
|
||||
class _PrintLogger:
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[DEBUG] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[INFO] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[WARN] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[ERROR] {msg}")
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 共享路径 & 常量配置 ====================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
GET_CUR_USER_INFO_URL = f"{HR_BASE_URL}/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
SEAL_URL = "https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc"
|
||||
SEAL_SQL_ID = "kq_count_leave_wage_SelectV2"
|
||||
PAGE_MAX_SIZE = 500
|
||||
|
||||
SAVE_DIR = os.getenv("monthly_seal_save_dir") or r"D:\资料\人资\考勤异常"
|
||||
|
||||
# 所属单位白名单(预处理口径:封存表仅保留以下单位员工)
|
||||
SEAL_UNIT_FIELD = "BELONG_UNIT_ORG_NAME" # aa.md:所属单位
|
||||
SEAL_UNIT_WHITELIST: Tuple[str, ...] = (
|
||||
"财务管理部",
|
||||
"集团管理中心",
|
||||
"集团营建中心",
|
||||
"金色印象事业部",
|
||||
"金色湖畔事业部",
|
||||
)
|
||||
|
||||
# 封存记录工号字段
|
||||
SEAL_CODE_FIELDS = ("base_code", "seal_base_code")
|
||||
|
||||
# 中文导出列 → 接口字段(来源:aa.md 封存页列定义。保存封存数据时按此重命名表头,读取时反查还原)
|
||||
CN_FIELD_MAP: Dict[str, str] = {
|
||||
"姓名": "staff_name", "工号": "base_code", "岗位": "POST_ALIAS_NAME",
|
||||
"所属单位": "BELONG_UNIT_ORG_NAME", "一级部门": "DEPT_ORG_ONE",
|
||||
"二级部门": "DEPT_ORG_TWO", "三级部门": "DEPT_ORG_THREE",
|
||||
"四级部门": "DEPT_ORG_FOUR", "五级部门": "DEPT_ORG_FIVE", "部门全路径": "ORG_FULL_PATH",
|
||||
"封存月份": "yearmonth", "开始日期": "count_begin_date", "结束日期": "count_end_date",
|
||||
"实际出勤天日": "kq_stat_cal_ext19", "_在职应勤工作日": "kq_stat_month_yq_work_day_in",
|
||||
"休息天": "kq_stat_cal_ext9", "旷工天数": "kq_stat_cal_ext39", "漏打卡次数": "kq_stat_cal_ext8",
|
||||
"年假天": "kq_stat_leave_day_num1", "_病假天": "kq_stat_leave_day_num4",
|
||||
"_产假天": "kq_stat_leave_day_num5", "_事假天": "kq_stat_leave_day_num9",
|
||||
"_普通事假天": "kq_stat_leave_day_num16", "_特殊事假天": "kq_stat_leave_day_num17",
|
||||
"_小时特假小时": "kq_stat_leave_hour_num18", "_普通事假(晚/高峰)天": "kq_stat_leave_day_num19",
|
||||
"_普通事假(早/中)天": "kq_stat_leave_day_num20", "_特别福利假天": "kq_stat_leave_day_num23",
|
||||
"_年度福利假天": "kq_stat_leave_day_num24",
|
||||
"_工作日加班转补贴小时": "kq_stat_ps_bt_hour", "法定节假日加班转补贴天": "kq_stat_cal_ext69",
|
||||
"休息日加班转补贴天": "kq_stat_cal_ext44", "当月未休调休天": "kq_stat_cal_ext63",
|
||||
"迟到30分钟内次数": "kq_stat_cal_ext60", "迟到30到60分钟内次数": "kq_stat_cal_ext61",
|
||||
"迟到60到120分钟内次数": "kq_stat_cal_ext62",
|
||||
"早退30分钟内次数": "kq_stat_cal_ext51", "早退30到60分钟内次数": "kq_stat_cal_ext52",
|
||||
"早退60到120分钟内次数": "kq_stat_cal_ext53", "连班次数": "kq_stat_cal_ext40",
|
||||
"是否未休小时特假": "kq_stat_cal_ext42", "是否全勤": "kq_stat_cal_ext43",
|
||||
"离职时间": "leaveOffice_date", "入职日期": "join_date", "身份证": "idCard",
|
||||
"用工类型": "identity", "操作时间": "operate_time", "操作人": "operator_name",
|
||||
"考勤封存状态": "kq_data_state", "考勤封存操作人": "kq_data_operator_name",
|
||||
"员工状态": "staff_status", "在职状态": "person_status_name",
|
||||
}
|
||||
|
||||
|
||||
# ==================== HR 登录态(共享 cookies) ====================
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态失效(接口返回非 JSON,被重定向到登录页)。"""
|
||||
|
||||
|
||||
def _load_shared_hr_cookies():
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
return None
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
return json.load(f) or None
|
||||
|
||||
|
||||
def _ensure_hr_cookies():
|
||||
if _load_shared_hr_cookies():
|
||||
return True
|
||||
raise RuntimeError(
|
||||
"未找到 HR 登录态(hr_cookies.json)或已失效。\n"
|
||||
"请在影刀流程开头先调用「37duHR登录」指令,或本地先运行 python workflows/share/hr_login.py")
|
||||
|
||||
|
||||
def build_hr_session():
|
||||
_ensure_hr_cookies()
|
||||
cookies = _load_shared_hr_cookies()
|
||||
if not cookies:
|
||||
raise RuntimeError("无 hr cookies,请先完成 HR 登录")
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
def hr_request_json(session, method, url, params, label, timeout=20):
|
||||
"""POST/GET 请求并校验返回 JSON;登录态失效抛 HRSessionExpiredError。
|
||||
|
||||
按项目规范做全局重试(最大 3 次,指数退避),仅在网络/服务端异常时重试;
|
||||
登录态失效(HRSessionExpiredError)属确定性失败,直接抛出、不重试。
|
||||
"""
|
||||
last_exc = None
|
||||
for attempt in range(1, 4):
|
||||
try:
|
||||
resp = session.request(method.upper(), url, data=params, timeout=timeout)
|
||||
resp.raise_for_status()
|
||||
text = resp.text or ""
|
||||
if not text or not text.lstrip().startswith(("{", "[")):
|
||||
raise HRSessionExpiredError(f"{label}:登录态失效(返回非 JSON)")
|
||||
return resp.json()
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt < 3:
|
||||
time.sleep(1.0 * (2 ** (attempt - 1)))
|
||||
raise last_exc
|
||||
|
||||
|
||||
def fetch_cur_user_info(session):
|
||||
return hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
|
||||
|
||||
|
||||
def _relogin_get_user_id():
|
||||
"""登录态失效后:重建会话 → 重新获取 userId。"""
|
||||
_ensure_hr_cookies()
|
||||
session = build_hr_session()
|
||||
info = fetch_cur_user_info(session)
|
||||
return session, _clean(info.get("userId"))
|
||||
|
||||
|
||||
# ==================== 考勤封存接口(aa.md:getPageAjaxList.mc + leave_wage_SelectV2) ====================
|
||||
def fetch_seal_page(session, user_id, yearmonth, page_no=1, page_size=PAGE_MAX_SIZE):
|
||||
"""请求单页考勤封存数据。
|
||||
|
||||
base_code / staff_name 留空 = 不过滤,按组织树全集团批量返回当月封存记录。
|
||||
"""
|
||||
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) * page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", SEAL_URL, params, "考勤封存")
|
||||
|
||||
|
||||
def fetch_all_seal(session, user_id, yearmonth: str) -> List[dict]:
|
||||
"""分页抓取某月全集团完整封存数据(pageSize=500 分页拉取)。"""
|
||||
all_rows: List[dict] = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_seal_page(session, user_id, yearmonth, page_no, PAGE_MAX_SIZE)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("考勤封存登录态过期,自动补登录后续抓")
|
||||
session, user_id = _relogin_get_user_id()
|
||||
data = fetch_seal_page(session, user_id, yearmonth, page_no, PAGE_MAX_SIZE)
|
||||
if data.get("state") != "1":
|
||||
logger.error("考勤封存第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("考勤封存无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount") or 0
|
||||
logger.info("考勤封存已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
# 分页保护:pageCount 缺失/为 0 时不能提前 break,否则会静默截断数据;
|
||||
# 仅当 pageCount 存在且已到最后页,或返回行数不足一页时才结束分页。
|
||||
if total_page and page_no >= total_page:
|
||||
break
|
||||
if len(page_list) < PAGE_MAX_SIZE:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
# ==================== 通用工具 ====================
|
||||
def _clean(v) -> str:
|
||||
if v is None:
|
||||
return ""
|
||||
try:
|
||||
if pd.isna(v):
|
||||
return ""
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
s = str(v).strip()
|
||||
if s.lower() in ("nan", "none", "nat"):
|
||||
return ""
|
||||
if s.endswith(".0"):
|
||||
s = s[:-2]
|
||||
return s
|
||||
|
||||
|
||||
def _prev_month(year: int, month: int) -> Tuple[int, int]:
|
||||
if month == 1:
|
||||
return year - 1, 12
|
||||
return year, month - 1
|
||||
|
||||
|
||||
def _normalize_month(month) -> str:
|
||||
"""月份归一化:None → 上月;YYYYMM → YYYY-MM;其余原样。"""
|
||||
if not month:
|
||||
py, pm = _prev_month(date.today().year, date.today().month)
|
||||
return f"{py:04d}-{pm:02d}"
|
||||
s = str(month).strip()
|
||||
if len(s) == 6 and s.isdigit():
|
||||
return f"{s[:4]}-{s[4:]}"
|
||||
return s
|
||||
|
||||
|
||||
def _seal_path(ym: str) -> str:
|
||||
"""预处理封存表固定路径(按月覆盖式保存,供检查模块稳定读取)。"""
|
||||
return os.path.join(SAVE_DIR, f"考勤封存数据_{ym}.xlsx")
|
||||
|
||||
|
||||
def _rename_columns_cn(frame: "pd.DataFrame", cn_map: Dict[str, str]) -> "pd.DataFrame":
|
||||
"""把封存数据列名按 中文导出列→接口字段 映射替换为中文表头。
|
||||
|
||||
仅重命名 cn_map 中存在的列,未映射的列(如各类 kq_stat_* 扩展字段)保留原英文名,
|
||||
列顺序不变,保证保存的封存数据信息不丢失。
|
||||
"""
|
||||
rename = {en: cn for cn, en in cn_map.items() if en in frame.columns}
|
||||
return frame.rename(columns=rename)
|
||||
|
||||
|
||||
# ==================== 预处理:所属单位白名单筛选 ====================
|
||||
def _filter_by_unit(rows: List[dict]) -> List[dict]:
|
||||
"""封存数据预处理:仅保留所属单位在白名单内的记录。"""
|
||||
return [rec for rec in rows if _clean(rec.get(SEAL_UNIT_FIELD)) in SEAL_UNIT_WHITELIST]
|
||||
|
||||
|
||||
# ==================== 导出 / 读取 ====================
|
||||
def export_seal_data(month: str = None) -> List[dict]:
|
||||
"""拉取当月全集团考勤封存数据 → 所属单位白名单预处理 → 保存固定路径封存表。
|
||||
|
||||
Args:
|
||||
month: 检查月份 "YYYY-MM"(或 YYYYMM),默认上月。
|
||||
|
||||
Returns:
|
||||
预处理后的封存记录行列表(接口原始字段名)。
|
||||
"""
|
||||
ym = _normalize_month(month)
|
||||
yearmonth = ym.replace("-", "")
|
||||
logger.info("===== 封存数据导出与预处理,月份:%s =====", ym)
|
||||
|
||||
# 1. 拉取当月全集团封存数据(base_code 留空批量)
|
||||
session = build_hr_session()
|
||||
user_id = _clean(fetch_cur_user_info(session).get("userId"))
|
||||
if not user_id:
|
||||
raise RuntimeError("获取当前用户 userId 失败")
|
||||
seal_rows = fetch_all_seal(session, user_id, yearmonth)
|
||||
if not seal_rows:
|
||||
raise RuntimeError(f"当月「{ym}」未拉到考勤封存数据,请确认该月已封存。")
|
||||
logger.info("全集团封存记录共 %d 人:%s", len(seal_rows), ym)
|
||||
|
||||
# 2. 预处理:所属单位白名单筛选
|
||||
filtered = _filter_by_unit(seal_rows)
|
||||
logger.info("封存数据预处理:全集团 %d 人 → 白名单单位 %d 人", len(seal_rows), len(filtered))
|
||||
|
||||
# 3. 保存预处理封存表(固定路径,覆盖式)
|
||||
os.makedirs(SAVE_DIR, exist_ok=True)
|
||||
path = _seal_path(ym)
|
||||
try:
|
||||
_rename_columns_cn(pd.DataFrame(filtered), CN_FIELD_MAP).to_excel(path, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(path)}」后重试")
|
||||
logger.info("预处理封存表已保存:%s(%d 行)", path, len(filtered))
|
||||
return filtered
|
||||
|
||||
|
||||
def load_seal_rows(month: str = None) -> List[dict]:
|
||||
"""读取预处理封存表(固定路径),返回接口原始字段名的记录行列表,供各检查模块使用。
|
||||
|
||||
Args:
|
||||
month: 检查月份 "YYYY-MM"(或 YYYYMM),默认上月。
|
||||
|
||||
Returns:
|
||||
预处理后的封存记录行列表(中文表头已反查还原为接口字段名)。
|
||||
"""
|
||||
ym = _normalize_month(month)
|
||||
path = _seal_path(ym)
|
||||
if not os.path.exists(path):
|
||||
raise RuntimeError(
|
||||
f"未找到预处理封存表:{path}\n"
|
||||
"请先运行「seal_data_export.py」导出并预处理当月封存数据(所属单位白名单筛选),"
|
||||
"再运行各检查模块。")
|
||||
df = pd.read_excel(path, dtype=str)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
# CN_FIELD_MAP 为 中文导出列→接口字段,反查:中文表头 → 接口字段名
|
||||
reverse = {cn: en for cn, en in CN_FIELD_MAP.items()}
|
||||
df = df.rename(columns={c: reverse.get(c, c) for c in df.columns})
|
||||
rows: List[dict] = [dict(r) for r in df.to_dict(orient="records")]
|
||||
logger.info("已读取预处理封存表:%s(%d 行)", path, len(rows))
|
||||
return rows
|
||||
|
||||
|
||||
def main(args=None) -> dict:
|
||||
"""影刀「调用模块」入口;也可作为脚本直接运行。
|
||||
args: dict,可选字段:month("YYYY-MM",默认上月)。
|
||||
"""
|
||||
if args is None:
|
||||
args = {}
|
||||
month = args.get("month") or os.getenv("monthly_seal_month") or (sys_argv_if(2))
|
||||
try:
|
||||
rows = export_seal_data(month)
|
||||
logger.info("=" * 60)
|
||||
logger.info("【封存数据导出与预处理完成】")
|
||||
logger.info(" 月份:%s | 白名单单位封存人数:%d", _normalize_month(month), len(rows))
|
||||
logger.info(" 输出目录:%s", SAVE_DIR)
|
||||
logger.info("=" * 60)
|
||||
return {"success": True, "count": len(rows)}
|
||||
except Exception as e:
|
||||
if "正被占用" in str(e):
|
||||
logger.error("=========== 提醒 ===========")
|
||||
logger.error(str(e))
|
||||
return {"success": False, "message": str(e)}
|
||||
logger.error("封存数据导出失败:%s\n%s", e, traceback.format_exc())
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
|
||||
def sys_argv_if(idx):
|
||||
"""读取命令行第 idx 个参数(index from 1);不存在返回 None。"""
|
||||
return sys.argv[idx] if len(sys.argv) > idx else None
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,12 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>37du 业务场景工具集</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+1382
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"name": "37du-webhost-frontend",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"vue": "^3.5.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^5.2.1",
|
||||
"vite": "^6.0.3"
|
||||
},
|
||||
"allowScripts": {
|
||||
"esbuild@0.25.12": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
<template>
|
||||
<div class="__app">
|
||||
<!-- 顶部:品牌 + 平台登录态 + 进度 -->
|
||||
<header class="topbar panel">
|
||||
<div class="brand">
|
||||
<span class="logo">37</span>
|
||||
<div class="brand-meta">
|
||||
<strong>{{ store.appName }}</strong>
|
||||
<span>{{ wsText }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="divider"></div>
|
||||
|
||||
<div class="band">
|
||||
<span class="band-label">平台登录态</span>
|
||||
<button
|
||||
v-for="p in store.platforms"
|
||||
:key="p.id"
|
||||
class="chip"
|
||||
:class="{ online: p.online }"
|
||||
:disabled="busyLogin === p.id"
|
||||
@click="login(p.id)"
|
||||
:title="p.online ? '已登录,点击刷新' : '未登录,点击登录'"
|
||||
>
|
||||
<i class="dot"></i>
|
||||
<span>{{ busyLogin === p.id ? '登录中…' : p.label }}</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="spacer"></div>
|
||||
|
||||
<div class="run-state">
|
||||
<span v-if="store.running" class="run-label">{{ store.progress }}%</span>
|
||||
<div v-show="store.running" class="progress"><div :style="{ width: store.progress + '%' }"></div></div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- 主体:左场景 | 右插件页 + 日志 -->
|
||||
<div class="body">
|
||||
<aside class="panel side">
|
||||
<div class="side-head">
|
||||
<span class="sec-title">场景</span>
|
||||
<span class="count">{{ store.plugins.length }}</span>
|
||||
</div>
|
||||
<ul class="scene-list">
|
||||
<li
|
||||
v-for="(p, i) in store.plugins"
|
||||
:key="p.id"
|
||||
:class="{ active: p.id === store.selectedId }"
|
||||
@click="store.selectedId = p.id"
|
||||
>
|
||||
<span class="scene-icon" :style="{ background: PALETTE[i % PALETTE.length] }">
|
||||
{{ p.name.slice(0, 1) }}
|
||||
</span>
|
||||
<span class="scene-name">{{ p.name }}</span>
|
||||
<em>v{{ p.version }}</em>
|
||||
</li>
|
||||
</ul>
|
||||
<div class="side-foot">场景以插件方式接入</div>
|
||||
</aside>
|
||||
|
||||
<main class="main">
|
||||
<div class="page-scroll panel">
|
||||
<PluginPage />
|
||||
</div>
|
||||
<LogPanel />
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import PluginPage from './components/PluginPage.vue'
|
||||
import LogPanel from './components/LogPanel.vue'
|
||||
import { store, handleEvent, clearLogs } from './store'
|
||||
import { connectWS, fetchMeta, loginPlatform } from './api'
|
||||
|
||||
const PALETTE = ['#3b6cff', '#7c5cff', '#12a4d8', '#22b07a', '#e88a3a', '#e5484d']
|
||||
|
||||
const wsText = computed(() =>
|
||||
store.wsOn ? '服务已连接' : '连接中断,正在重连…')
|
||||
|
||||
onMounted(async () => {
|
||||
const meta = await fetchMeta()
|
||||
store.appName = meta.appName
|
||||
store.platforms = meta.platforms
|
||||
store.plugins = meta.plugins
|
||||
store.selectedId = meta.plugins[0]?.id || ''
|
||||
clearLogs()
|
||||
if (window.__ws) window.__ws.close()
|
||||
const ws = connectWS(handleEvent)
|
||||
window.__ws = ws
|
||||
ws.onopen = () => (store.wsOn = true)
|
||||
ws.onclose = () => { store.wsOn = false; setTimeout(() => (location.reload()), 2500) }
|
||||
})
|
||||
|
||||
const busyLogin = ref('')
|
||||
|
||||
async function login(id) {
|
||||
if (busyLogin.value) return
|
||||
busyLogin.value = id
|
||||
try {
|
||||
const r = await loginPlatform(id)
|
||||
const p = store.platforms.find((x) => x.id === id)
|
||||
if (p) p.online = !!r.online
|
||||
} catch (e) {
|
||||
alert('登录失败:' + (e.message || e))
|
||||
} finally {
|
||||
busyLogin.value = ''
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.topbar {
|
||||
display: flex; align-items: center; gap: 16px;
|
||||
padding: 12px 18px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.brand { display: flex; align-items: center; gap: 11px; }
|
||||
.logo {
|
||||
width: 36px; height: 36px; border-radius: 10px;
|
||||
display: grid; place-items: center;
|
||||
background: var(--primary-grad); color: #fff;
|
||||
font-size: 14px; font-weight: 800;
|
||||
box-shadow: 0 4px 12px -3px rgba(59,108,255,.6);
|
||||
}
|
||||
.brand-meta { display: flex; flex-direction: column; line-height: 1.2; }
|
||||
.brand-meta strong { font-size: 14px; }
|
||||
.brand-meta span { font-size: 11px; color: var(--text-faint); }
|
||||
|
||||
.divider { width: 1px; height: 26px; background: var(--border); }
|
||||
|
||||
.band { display: flex; align-items: center; gap: 6px; }
|
||||
.band-label { font-size: 12px; color: var(--text-faint); margin-right: 4px; }
|
||||
.chip {
|
||||
display: inline-flex; align-items: center; gap: 7px;
|
||||
border: 1px solid var(--border-strong); background: var(--surface);
|
||||
color: var(--text-sub); padding: 5px 12px; border-radius: 999px;
|
||||
cursor: pointer; font-size: 12.5px; transition: all .15s;
|
||||
}
|
||||
.chip .dot { width: 9px; height: 9px; border-radius: 50%; background: #c6ccdc; }
|
||||
.chip.online { border-color: transparent; background: var(--ok-weak); color: #1a8f63; }
|
||||
.chip.online .dot { background: var(--ok); box-shadow: 0 0 0 3px rgba(34,176,122,.18); }
|
||||
.chip:hover { border-color: var(--primary); color: var(--primary); }
|
||||
.chip:disabled { opacity: .55; cursor: not-allowed; }
|
||||
.chip:disabled:hover { border-color: var(--border-strong); color: var(--text-sub); }
|
||||
|
||||
.spacer { flex: 1; }
|
||||
.run-state { display: flex; align-items: center; gap: 10px; }
|
||||
.run-label { font-size: 12px; color: var(--primary); font-weight: 600; min-width: 38px; text-align: right; }
|
||||
|
||||
.body { flex: 1; display: flex; gap: 14px; min-height: 0; margin-top: 14px; }
|
||||
|
||||
.side { width: 232px; flex-shrink: 0; display: flex; flex-direction: column; padding: 14px 12px; }
|
||||
.side-head { display: flex; align-items: center; justify-content: space-between; padding: 0 6px 10px; }
|
||||
.count { font-size: 11px; color: var(--text-faint); background: var(--surface-2); border: 1px solid var(--border); border-radius: 999px; padding: 1px 8px; }
|
||||
.scene-list { list-style: none; margin: 0; padding: 0; flex: 1; overflow: auto; display: flex; flex-direction: column; gap: 2px; }
|
||||
.scene-list li {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
padding: 9px 10px; border-radius: var(--radius-sm); cursor: pointer;
|
||||
transition: background .13s;
|
||||
}
|
||||
.scene-list li:hover { background: var(--surface-2); }
|
||||
.scene-list li.active { background: var(--primary-weak); }
|
||||
.scene-list li.active .scene-name { color: var(--primary); font-weight: 600; }
|
||||
.scene-icon {
|
||||
width: 26px; height: 26px; border-radius: 8px; flex-shrink: 0;
|
||||
display: grid; place-items: center; color: #fff; font-size: 12px; font-weight: 700;
|
||||
}
|
||||
.scene-name { flex: 1; color: var(--text-sub); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.scene-list li.active .scene-name { color: var(--primary); }
|
||||
.scene-list em { font-style: normal; font-size: 10px; color: var(--text-faint); }
|
||||
.side-foot { font-size: 10px; color: var(--text-faint); text-align: center; padding-top: 10px; border-top: 1px dashed var(--border); margin-top: 8px; }
|
||||
|
||||
.main { flex: 1; display: flex; flex-direction: column; gap: 14px; min-width: 0; }
|
||||
.page-scroll { flex: 1; min-height: 0; padding: 20px 24px; overflow: auto; }
|
||||
</style>
|
||||
@@ -0,0 +1,40 @@
|
||||
// 与 FastAPI 后端交互 + WebSocket 实时流
|
||||
const WS_BASE = (location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host
|
||||
|
||||
async function j(url, opts) {
|
||||
const res = await fetch(url, opts)
|
||||
if (!res.ok) {
|
||||
let msg = `HTTP ${res.status}`
|
||||
try { msg = (await res.json()).detail || msg } catch (e) {}
|
||||
throw new Error(msg)
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
export async function fetchMeta() {
|
||||
return j('/api/meta')
|
||||
}
|
||||
|
||||
export async function loginPlatform(id) {
|
||||
return j(`/api/platforms/${id}/login`, { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function startRun(pluginId, fields) {
|
||||
return j('/api/runs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: pluginId, fields }),
|
||||
})
|
||||
}
|
||||
|
||||
export async function getRun(runId) {
|
||||
return j(`/api/runs/${runId}`)
|
||||
}
|
||||
|
||||
export function connectWS(onEvent) {
|
||||
const ws = new WebSocket(WS_BASE + '/ws')
|
||||
ws.onmessage = (e) => {
|
||||
try { onEvent(JSON.parse(e.data)) } catch (_) {}
|
||||
}
|
||||
return ws
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<template>
|
||||
<div class="panel log-wrap">
|
||||
<div class="log-head">
|
||||
<div class="log-title">
|
||||
<i class="status" :class="store.wsOn ? 'on' : 'off'"></i>
|
||||
<span>运行日志</span>
|
||||
<span v-if="store.running" class="live">●</span>
|
||||
</div>
|
||||
<button class="btn mini" @click="clear">清空</button>
|
||||
</div>
|
||||
<div ref="box" class="log-box">
|
||||
<div v-if="store.logs.length === 0" class="log-empty">暂无日志,点击「一键执行」开始</div>
|
||||
<div v-for="(l, i) in store.logs" :key="i" class="log-line">
|
||||
<span class="t">{{ l.time }}</span>
|
||||
<span class="lv" :class="'s-' + (l.level || 'INFO')">[{{ l.level || 'INFO' }}]</span>
|
||||
<span>{{ l.msg }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { nextTick, ref, watch } from 'vue'
|
||||
import { store, clearLogs } from '../store'
|
||||
|
||||
const box = ref(null)
|
||||
watch(
|
||||
() => store.logs.length,
|
||||
async () => {
|
||||
await nextTick()
|
||||
if (box.value) box.value.scrollTop = box.value.scrollHeight
|
||||
}
|
||||
)
|
||||
function clear() {
|
||||
clearLogs()
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.log-wrap { display: flex; flex-direction: column; height: 190px; flex-shrink: 0; overflow: hidden; position: relative; }
|
||||
.log-head {
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
padding: 9px 14px; border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.log-title { display: flex; align-items: center; gap: 8px; font-weight: 600; color: var(--text); }
|
||||
.status { width: 9px; height: 9px; border-radius: 50%; }
|
||||
.status.on { background: var(--ok); box-shadow: 0 0 0 3px var(--ok-weak); }
|
||||
.status.off { background: #c6ccdc; }
|
||||
.live { color: var(--ok); font-size: 10px; animation: blink 1s infinite; }
|
||||
@keyframes blink { 50% { opacity: .2; } }
|
||||
.log-empty { color: var(--text-faint); padding: 14px; font-family: var(--mono); font-size: 12px; }
|
||||
.btn.mini { padding: 4px 12px; font-size: 12px; }
|
||||
</style>
|
||||
@@ -0,0 +1,176 @@
|
||||
<template>
|
||||
<div v-if="plugin" class="plugin-page">
|
||||
<!-- 页头 -->
|
||||
<div class="head">
|
||||
<div class="ident">
|
||||
<span class="avatar" :style="{ background: avatarBg }">{{ plugin.name.slice(0, 1) }}</span>
|
||||
<div class="ident-meta">
|
||||
<h2>{{ plugin.name }}</h2>
|
||||
<p>{{ plugin.description }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="plugin?.uses_month" class="month">
|
||||
<span class="field-label">执行月份</span>
|
||||
<select v-model="month" class="input month-sel">
|
||||
<option v-for="m in months" :key="m" :value="m">{{ m }}</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 结果横幅 -->
|
||||
<transition name="fade">
|
||||
<div v-if="store.lastResult" class="banner" :class="store.lastResult.ok ? 'ok' : 'err'">
|
||||
<span class="b-ic">{{ store.lastResult.ok ? '✓' : '✕' }}</span>
|
||||
<span class="b-text">
|
||||
{{ store.lastResult.ok ? (store.lastSummary || '执行完成') : '执行失败:' + store.lastResult.error }}
|
||||
</span>
|
||||
<button class="b-close" @click="closeBanner">×</button>
|
||||
</div>
|
||||
</transition>
|
||||
|
||||
<!-- 参数 -->
|
||||
<div class="sec-title">参数配置</div>
|
||||
<div class="form-card">
|
||||
<div class="fields">
|
||||
<div v-for="f in plugin.fields" :key="f.key" class="fgroup">
|
||||
<label class="field-label">{{ f.label }}</label>
|
||||
<input
|
||||
v-if="f.type === 'int'"
|
||||
class="input"
|
||||
type="number"
|
||||
v-model.number="form[f.key]"
|
||||
:placeholder="String(f.default ?? 0)"
|
||||
/>
|
||||
<input
|
||||
v-else-if="f.type === 'text'"
|
||||
class="input"
|
||||
type="text"
|
||||
v-model="form[f.key]"
|
||||
:placeholder="f.default || ''"
|
||||
/>
|
||||
<select v-else class="input" v-model="form[f.key]">
|
||||
<option v-for="opt in f.options" :key="opt" :value="opt">{{ opt }}</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button class="btn primary run-btn" :disabled="store.running" @click="run">
|
||||
<span v-if="store.running" class="spin"></span>
|
||||
{{ store.running ? '执行中…' : '一键执行' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="hint">执行日志与进度实时显示在下方日志区,结果完成后自动汇总于此。</p>
|
||||
</div>
|
||||
|
||||
<div v-else class="empty">未选择场景</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { store } from '../store'
|
||||
import { startRun, getRun } from '../api'
|
||||
|
||||
const months = computed(() => {
|
||||
const now = new Date()
|
||||
const list = []
|
||||
for (let off = 1; off <= 6; off++) {
|
||||
const d = new Date(now.getFullYear(), now.getMonth() - off, 1)
|
||||
list.push(`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`)
|
||||
}
|
||||
return list
|
||||
})
|
||||
const month = ref(months.value[0])
|
||||
|
||||
const PALETTE = ['#3b6cff', '#7c5cff', '#12a4d8', '#22b07a', '#e88a3a', '#e5484d']
|
||||
const idx = computed(() => Math.max(0, store.plugins.findIndex((p) => p.id === store.selectedId)))
|
||||
const avatarBg = computed(() => PALETTE[idx.value % PALETTE.length])
|
||||
|
||||
const plugin = computed(() => store.plugins.find((p) => p.id === store.selectedId) || null)
|
||||
|
||||
const form = ref({})
|
||||
watch(
|
||||
() => plugin.value?.id,
|
||||
(id) => {
|
||||
form.value = {}
|
||||
const p = store.plugins.find((x) => x.id === id)
|
||||
if (p) p.fields.forEach((f) => (form.value[f.key] = f.default ?? (f.type === 'int' ? 0 : '')))
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
async function run() {
|
||||
if (!plugin.value || store.running) return
|
||||
store.running = true
|
||||
store.progress = 0
|
||||
store.currentRun = ''
|
||||
store.lastResult = null
|
||||
store.lastSummary = ''
|
||||
const payload = { ...form.value }
|
||||
if (plugin.value.uses_month) payload.ref_month = month.value // 仅月度插件注入月份
|
||||
const r = await startRun(plugin.value.id, payload)
|
||||
store.lastRunId = r.run_id
|
||||
}
|
||||
|
||||
// 完成时拉取后端摘要填充横幅
|
||||
watch(
|
||||
() => store.lastResult,
|
||||
async (res) => {
|
||||
if (res && res.ok && store.lastRunId) {
|
||||
try {
|
||||
const run = await getRun(store.lastRunId)
|
||||
store.lastSummary = run.result?.summary || ''
|
||||
} catch (e) {}
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
function closeBanner() {
|
||||
store.lastResult = null
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.plugin-page { display: flex; flex-direction: column; gap: 18px; min-height: 100%; }
|
||||
|
||||
.head { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; }
|
||||
.ident { display: flex; align-items: center; gap: 14px; }
|
||||
.avatar {
|
||||
width: 44px; height: 44px; border-radius: 13px; flex-shrink: 0;
|
||||
display: grid; place-items: center; color: #fff; font-size: 18px; font-weight: 700;
|
||||
box-shadow: var(--shadow-md);
|
||||
}
|
||||
.ident-meta { display: flex; flex-direction: column; gap: 2px; }
|
||||
.ident-meta h2 { margin: 0; font-size: 17px; }
|
||||
.ident-meta p { margin: 0; font-size: 12px; color: var(--text-sub); }
|
||||
.month { display: flex; align-items: center; gap: 8px; }
|
||||
.month-sel { min-width: 110px; }
|
||||
|
||||
.banner {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
padding: 11px 14px; border-radius: var(--radius-sm); font-size: 13px;
|
||||
}
|
||||
.banner.ok { background: var(--ok-weak); color: #156d4e; border: 1px solid #bfe8d5; }
|
||||
.banner.err { background: var(--err-weak); color: #a83a3e; border: 1px solid #f3c4c5; }
|
||||
.b-ic { font-weight: 800; font-size: 15px; }
|
||||
.b-text { flex: 1; }
|
||||
.b-close { border: none; background: transparent; font-size: 18px; line-height: 1; cursor: pointer; color: inherit; opacity: .5; }
|
||||
.b-close:hover { opacity: 1; }
|
||||
|
||||
.form-card {
|
||||
display: flex; flex-direction: column; gap: 16px;
|
||||
background: var(--surface-2); border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm); padding: 16px;
|
||||
}
|
||||
.fields { display: flex; gap: 24px; flex-wrap: wrap; }
|
||||
.fgroup { display: flex; flex-direction: column; gap: 6px; min-width: 120px; }
|
||||
.fgroup .input { width: 150px; }
|
||||
.actions { display: flex; justify-content: flex-end; }
|
||||
.run-btn { min-width: 128px; height: 38px; font-size: 14px; display: inline-flex; align-items: center; justify-content: center; gap: 8px; }
|
||||
.spin { width: 14px; height: 14px; border: 2px solid rgba(255,255,255,.4); border-top-color: #fff; border-radius: 50%; animation: spin 0.7s linear infinite; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
|
||||
.hint { font-size: 12px; color: var(--text-faint); margin: 0; padding-left: 2px; }
|
||||
.empty { color: var(--text-faint); padding: 40px; }
|
||||
</style>
|
||||
@@ -0,0 +1,5 @@
|
||||
import { createApp } from 'vue'
|
||||
import App from './App.vue'
|
||||
import './style.css'
|
||||
|
||||
createApp(App).mount('#app')
|
||||
@@ -0,0 +1,53 @@
|
||||
import { reactive } from 'vue'
|
||||
|
||||
export const store = reactive({
|
||||
appName: '',
|
||||
platforms: [],
|
||||
plugins: [],
|
||||
selectedId: '',
|
||||
logs: [], // {time, level, msg}
|
||||
progress: 0,
|
||||
running: false,
|
||||
currentRun: '', // 当前接收日志/进度的 run_id
|
||||
lastRunId: '', // 最近一次执行的 run_id
|
||||
lastResult: null, // {ok, error}
|
||||
lastSummary: '', // 完成时后端返回的摘要
|
||||
wsOn: false,
|
||||
})
|
||||
|
||||
export function clearLogs() {
|
||||
store.logs = []
|
||||
store.lastResult = null
|
||||
store.lastSummary = ''
|
||||
}
|
||||
|
||||
export function log(level, msg) {
|
||||
const time = new Date().toLocaleTimeString('zh-CN', { hour12: false })
|
||||
store.logs.push({ time, level, msg })
|
||||
if (store.logs.length > 500) store.logs.splice(0, store.logs.length - 500)
|
||||
}
|
||||
|
||||
export function handleEvent(ev) {
|
||||
switch (ev.t) {
|
||||
case 'run_start':
|
||||
store.currentRun = ev.run_id
|
||||
if (!store.running) { clearLogs() }
|
||||
break
|
||||
case 'log':
|
||||
if (ev.run_id === store.currentRun || !store.currentRun) {
|
||||
log(ev.level || 'INFO', ev.msg)
|
||||
}
|
||||
break
|
||||
case 'progress':
|
||||
if (ev.run_id === store.currentRun) store.progress = ev.pct
|
||||
break
|
||||
case 'run_done':
|
||||
store.running = false
|
||||
store.progress = 100
|
||||
store.lastResult = { ok: ev.ok, error: ev.error || '' }
|
||||
if (ev.ok) log('INFO', '===== 执行完成 =====')
|
||||
else log('ERROR', `执行失败:${ev.error}`)
|
||||
store.currentRun = ''
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
/* ============ 37du Web Host 设计系统(亮色) ============ */
|
||||
:root {
|
||||
--bg: #eef2f9;
|
||||
--bg-grad: linear-gradient(180deg, #f4f7fc 0%, #e9eef7 100%);
|
||||
--surface: #ffffff;
|
||||
--surface-2: #f7f9fd;
|
||||
--border: #e5eaf3;
|
||||
--border-strong: #cdd6e6;
|
||||
|
||||
--text: #1f2633;
|
||||
--text-sub: #5b6477;
|
||||
--text-faint: #98a0b3;
|
||||
|
||||
--primary: #3b6cff;
|
||||
--primary-2: #6f8dff;
|
||||
--primary-grad: linear-gradient(135deg, #4c79ff 0%, #3b6cff 100%);
|
||||
--primary-weak: #eef2ff;
|
||||
--primary-weak-2: #e2e9ff;
|
||||
|
||||
--ok: #22b07a;
|
||||
--ok-weak: #e6f7f0;
|
||||
--err: #e5484d;
|
||||
--err-weak: #fdecec;
|
||||
--warn: #d99a1b;
|
||||
|
||||
--shadow-sm: 0 1px 2px rgba(24, 39, 75, 0.05);
|
||||
--shadow-md: 0 6px 24px -8px rgba(24, 39, 75, 0.18);
|
||||
--radius: 14px;
|
||||
--radius-sm: 9px;
|
||||
--mono: "JetBrains Mono", "Consolas", "Courier New", monospace;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
html, body, #app { height: 100%; margin: 0; }
|
||||
|
||||
body {
|
||||
font-family: "Inter", "Microsoft YaHei UI", "PingFang SC", -apple-system, sans-serif;
|
||||
font-size: 13px;
|
||||
color: var(--text);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
.__app {
|
||||
height: 100%;
|
||||
background: var(--bg-grad);
|
||||
padding: 16px 18px 18px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
/* 滚动条 */
|
||||
::-webkit-scrollbar { width: 10px; height: 10px; }
|
||||
::-webkit-scrollbar-thumb { background: #d4dae8; border-radius: 6px; border: 2px solid transparent; background-clip: content-box; }
|
||||
::-webkit-scrollbar-thumb:hover { background: #c1c9dc; background-clip: content-box; border: 2px solid transparent; }
|
||||
::-webkit-scrollbar-track { background: transparent; }
|
||||
|
||||
/* 通用白卡 */
|
||||
.panel {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: var(--shadow-sm);
|
||||
}
|
||||
|
||||
/* 分节标题 */
|
||||
.sec-title {
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
color: var(--text-faint);
|
||||
}
|
||||
|
||||
/* 按钮 */
|
||||
.btn {
|
||||
border: 1px solid var(--border-strong);
|
||||
background: var(--surface);
|
||||
color: var(--text-sub);
|
||||
border-radius: 8px;
|
||||
padding: 7px 16px;
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
cursor: pointer;
|
||||
transition: all .15s ease;
|
||||
}
|
||||
.btn:hover { color: var(--text); border-color: #b9c3d8; background: var(--surface-2); }
|
||||
.btn:active { transform: translateY(1px); }
|
||||
.btn:disabled { color: #c0c6d4; border-color: var(--border); background: #f4f6fb; cursor: not-allowed; transform: none; }
|
||||
|
||||
.btn.primary {
|
||||
background: var(--primary-grad);
|
||||
color: #fff;
|
||||
border: 1px solid transparent;
|
||||
font-weight: 600;
|
||||
box-shadow: 0 4px 14px -4px rgba(59, 108, 255, 0.55);
|
||||
}
|
||||
.btn.primary:hover:not(:disabled) { box-shadow: 0 8px 20px -6px rgba(59, 108, 255, 0.65); color: #fff; }
|
||||
.btn.primary:disabled { background: #b9c6f0; box-shadow: none; }
|
||||
|
||||
/* 输入 / 选择 */
|
||||
.input {
|
||||
height: 34px;
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: 8px;
|
||||
background: var(--surface);
|
||||
color: var(--text);
|
||||
padding: 0 12px;
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
outline: none;
|
||||
transition: border-color .15s, box-shadow .15s;
|
||||
}
|
||||
.input:focus { border-color: var(--primary); box-shadow: 0 0 0 3px var(--primary-weak); }
|
||||
select.input { padding-right: 30px; appearance: none; cursor: pointer;
|
||||
background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%237b8497' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E");
|
||||
background-repeat: no-repeat; background-position: right 10px center; }
|
||||
.field-label { color: var(--text-sub); font-size: 13px; }
|
||||
|
||||
/* 进度条 */
|
||||
.progress { height: 8px; width: 180px; background: #e8ecf5; border-radius: 6px; overflow: hidden; }
|
||||
.progress > div { height: 100%; border-radius: 6px;
|
||||
background: var(--primary-grad);
|
||||
transition: width .25s ease;
|
||||
box-shadow: 0 0 6px rgba(59,108,255,.5); }
|
||||
|
||||
/* 日志 */
|
||||
.log-box {
|
||||
font-family: var(--mono);
|
||||
font-size: 12px;
|
||||
line-height: 1.75;
|
||||
color: var(--text);
|
||||
padding: 12px 14px;
|
||||
overflow: auto;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
}
|
||||
.log-line:hover { background: #f7f9fd; }
|
||||
.log-box .t { color: var(--text-faint); margin-right: 10px; user-select: none; }
|
||||
.log-box .lv { margin-right: 6px; font-weight: 700; }
|
||||
.log-box .s-INFO { color: var(--primary); }
|
||||
.log-box .s-ERROR { color: var(--err); }
|
||||
.log-box .s-WARN { color: var(--warn); }
|
||||
|
||||
/* 过渡 */
|
||||
.fade-enter-active, .fade-leave-active { transition: opacity .18s ease, transform .18s ease; }
|
||||
.fade-enter-from { opacity: 0; transform: translateY(4px); }
|
||||
.fade-leave-to { opacity: 0; }
|
||||
@@ -0,0 +1,19 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
// dev 时把 /api 与 /ws 代理到 FastAPI 后端,实现前后端分离开发
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
server: {
|
||||
port: 5173,
|
||||
strictPort: true,
|
||||
proxy: {
|
||||
'/api': { target: 'http://127.0.0.1:8799', changeOrigin: true },
|
||||
'/ws': { target: 'ws://127.0.0.1:8799', ws: true },
|
||||
},
|
||||
},
|
||||
build: {
|
||||
outDir: 'dist',
|
||||
emptyOutDir: true,
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,127 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""(win) webhost 启动器:杀掉旧实例 → 拉起 uvicorn → 用 PyWebView(WebView2) 打开原生应用窗口。
|
||||
|
||||
单用户本地工具。窗口关闭即停止服务并退出;端口被占用时判定旧实例并清理后重启。
|
||||
若 WebView2 不可用则回退到系统浏览器打开。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import webbrowser
|
||||
from pathlib import Path
|
||||
|
||||
import psutil
|
||||
|
||||
PORT = 8799
|
||||
URL = f"http://127.0.0.1:{PORT}"
|
||||
HERE = Path(__file__).resolve().parent
|
||||
PID_FILE = HERE / ".webhost.pid"
|
||||
|
||||
|
||||
def _port_pids() -> list[int]:
|
||||
return [c.pid for c in psutil.net_connections(kind="inet")
|
||||
if c.laddr.port == PORT and c.status in ("LISTEN", "LISTENING") and c.pid]
|
||||
|
||||
|
||||
def _kill_existing() -> None:
|
||||
"""杀掉旧实例:优先按端口监听进程,兜底按 PID 文件。"""
|
||||
targets = set(_port_pids())
|
||||
if PID_FILE.exists():
|
||||
try:
|
||||
targets.add(int(PID_FILE.read_text().strip()))
|
||||
except ValueError:
|
||||
pass
|
||||
for pid in targets:
|
||||
try:
|
||||
proc = psutil.Process(pid)
|
||||
if proc.name().lower().startswith(("python", "uvicorn")):
|
||||
proc.terminate()
|
||||
proc.wait(timeout=4)
|
||||
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.TimeoutExpired):
|
||||
continue
|
||||
for _ in range(40): # 等待端口释放
|
||||
if not _port_pids():
|
||||
break
|
||||
time.sleep(0.25)
|
||||
|
||||
|
||||
def _port_free() -> bool:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
return s.connect_ex(("127.0.0.1", PORT)) != 0
|
||||
|
||||
|
||||
def _start_server() -> subprocess.Popen:
|
||||
if not _port_free():
|
||||
_kill_existing()
|
||||
time.sleep(0.3)
|
||||
cmd = [sys.executable, "-m", "uvicorn", "webhost.backend.main:app",
|
||||
"--host", "127.0.0.1", "--port", str(PORT), "--log-level", "warning"]
|
||||
proc = subprocess.Popen(cmd, cwd=str(HERE.parent),
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
PID_FILE.write_text(str(proc.pid))
|
||||
for _ in range(60): # 等待就绪
|
||||
if not _port_free():
|
||||
return proc
|
||||
if proc.poll() is not None:
|
||||
break
|
||||
time.sleep(0.25)
|
||||
raise RuntimeError("服务启动失败")
|
||||
|
||||
|
||||
def _open_window(app_name: str) -> bool:
|
||||
"""尝试 PyWebView 原生窗口;失败返回显示不可用。"""
|
||||
try:
|
||||
import webview # noqa: WPS433
|
||||
|
||||
webview.create_window(app_name, URL,
|
||||
width=1200, height=780, min_size=(1000, 660),
|
||||
background_color="#eef2f9")
|
||||
webview.start(gui="edgechromium")
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _stop(proc: subprocess.Popen) -> None:
|
||||
try:
|
||||
proc.terminate()
|
||||
proc.wait(timeout=5)
|
||||
except Exception:
|
||||
try:
|
||||
proc.kill()
|
||||
except Exception:
|
||||
pass
|
||||
if PID_FILE.exists():
|
||||
try:
|
||||
PID_FILE.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def main() -> int:
|
||||
app_name = "37du 业务场景工具集"
|
||||
proc = _start_server()
|
||||
|
||||
if not _open_window(app_name):
|
||||
# 回退:系统浏览器
|
||||
webbrowser.open(URL)
|
||||
print(f"[webhost] 已用系统浏览器打开:{URL}")
|
||||
try:
|
||||
while True:
|
||||
time.sleep(1)
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
_stop(proc)
|
||||
return 0
|
||||
else:
|
||||
_stop(proc)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user