feat: 新增xq0031_xq0032 ERP报表导出插件,完成功能与基建更新
1. 新增xq0031_xq0032插件:包含前后端源码、打包脚本、配置文件与插件元数据 2. 新增内网文件服务器组件:exe、启停脚本、打包脚本与配置 3. 新增敏感凭证RSA加密下发能力与存储结构 4. 新增大文件源管理表与相关API 5. 优化登录流程与会话管理,新增Chrome自动化安装工具链 6. 清理废弃插件与示例代码 7. 更新版本号至1.1.3,完善安装包与.gitignore配置
This commit is contained in:
@@ -15,6 +15,7 @@ wheels/
|
||||
*.spec
|
||||
# 前端依赖与构建产物(desktop 桌面端)
|
||||
desktop/*/frontend/node_modules
|
||||
plugins/*/ui-src/node_modules
|
||||
desktop/*/frontend/dist/
|
||||
|
||||
# 桌面版打包产物(PyInstaller 中间/输出、安装包、插件构建包,不入库)
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
# 控制面管理台多页面化重构计划
|
||||
|
||||
## Context
|
||||
当前控制面管理台(controlplane/frontend)把「上传插件 / 插件列表 / 账号管理 / 插件授权 / 平台授权 / 修改密码」全部挤在单个 ManagementView.vue(~270 行)里,一屏堆叠、滚动查看困难,CRUD 操作没有独立入口。用户要求拆成多页面版本,每个 CRUD 独立成页,清晰可管理。
|
||||
|
||||
现状关键事实:
|
||||
- `package.json` 仅有 vue 依赖,**无 vue-router**;app 由 FastAPI `StaticFiles(html=True)` 挂载,history 路由刷新会 404 → 采用 **hash 路由**(`#/plugins`),刷新安全且零后端改动。
|
||||
- 数据面 `adminOverview()` 一次返回 plugins(含 versions/accounts) + accounts(含 plugins/platforms) + admins,各页面按需复用。
|
||||
- api.js 已有全部 CRUD 封装(adminUpload/adminGrant/adminPlatformGrant/adminAccount*/adminPluginDelete/adminPassword),**后端零改动**。
|
||||
|
||||
## 方案
|
||||
|
||||
### 1. 轻量 hash 路由(不新增依赖)
|
||||
`App.vue` 内实现 ~20 行路由:`route = ref(location.hash || '#/overview')`,监听 `hashchange`;顶栏下改为 **左侧扁平导航 + 右侧页面区** 布局(导航项:概览 / 插件管理 / 账号管理 / 权限授权,激活态用主色文字+左侧竖条,不用盒子边框)。
|
||||
|
||||
### 2. 页面拆分(components/views/,迁移 ManagementView.vue 现有逻辑,逐块对应)
|
||||
| 新页面 | 迁移自 ManagementView | 内容 |
|
||||
|---|---|---|
|
||||
| `OverviewView.vue` | 无(新增,轻量) | 统计数字(插件数/账号数/版本总数/最近上传)+ 使用说明一行 |
|
||||
| `PluginManageView.vue` | 上传插件包 + 插件列表 section | 上传表单一行 + 插件表格(版本历史/授权账号/删除) |
|
||||
| `AccountManageView.vue` | 账号管理 section | 建号行 + 账号表格(部门行内编辑/管理员切换/重置密码/删除) |
|
||||
| `GrantManageView.vue` | 授权账号 + 授权平台 section | **改为下拉选账号自动载入**(替代手输账号+点载入),插件勾选区与平台勾选区上下分节(扁平标题+分隔线) |
|
||||
| `PasswordDialog.vue` | 修改密码 section | 顶栏「改密码」按钮弹出的小弹层 |
|
||||
|
||||
`ManagementView.vue` 整体删除,不留死代码。
|
||||
|
||||
### 3. 共享状态与样式
|
||||
- `store.js` 增加 `overview = ref(null)` 与 `loadOverview(force)`:各页面 mounted 时调用(有缓存不重复拉),每页右上保留「刷新」按钮强刷。
|
||||
- ManagementView 中被多页面复用的 scoped 样式(table/th/td、.row、.ck、.link、.toast-note、input/button)提升到全局 `style.css`(沿用现有 CSS 变量 --border/--primary 等),页面内只留布局样式。
|
||||
- 沿用用户偏好:亮色、扁平、分区用「小标题 + 底部分隔线」,不用带边框的盒子。
|
||||
|
||||
### 4. 涉及文件
|
||||
- 改:`src/App.vue`(路由 + 侧导航 + 改密弹层入口)、`src/store.js`(overview 缓存)、`src/style.css`(公共表格/表单样式)
|
||||
- 增:`src/views/OverviewView.vue`、`PluginManageView.vue`、`AccountManageView.vue`、`GrantManageView.vue`、`src/components/PasswordDialog.vue`
|
||||
- 删:`src/components/ManagementView.vue`
|
||||
- 后端 `controlplane/app.py`:**不改**
|
||||
|
||||
### 5. 验证
|
||||
1. `cd controlplane/frontend && npm run build` 成功
|
||||
2. 源码起 controlplane(.venv\Scripts\python.exe controlplane\app.py),浏览器逐页验证:
|
||||
- 登录 → 默认落 `#/overview`;刷新页面保持当前 hash 页
|
||||
- 插件页上传/删除;账号页建号/改部门/切管理员/重置密码/删号;授权页下拉选账号后勾选保存(对比 overview 数据回显)
|
||||
- 顶栏「改密码」弹层改密后用新密码重登
|
||||
3. 通过后重打 `37du-center.exe`(pyinstaller 37du-center.spec → dist-exe)供中心机部署
|
||||
@@ -1,60 +0,0 @@
|
||||
# 中心机 Vue 管理前端搭建 + 底座管理 UI 剥离
|
||||
|
||||
## Context(为什么做)
|
||||
|
||||
优先级已定:**先把中心机(控制面 controlplane)完整搭起来,包括管理前端**,部署机才好用接口、配权限、做插件分发。
|
||||
|
||||
当前现状:
|
||||
- 控制面(`controlplane/`,8800)是纯 FastAPI API,**没有任何前端页面**、未挂载静态目录;目前没有 `/api/admin/password`(改自己密码)接口。
|
||||
- 管理界面目前是**借底座(`webhost/`)前端**(ManagementView.vue)通过 `webhost` 后端的 `/api/admin/*` 代理展示,普通用户能碰到管理入口——正是要消除的暴露风险。
|
||||
|
||||
目标:
|
||||
- 新建**控制面自己的 Vue 管理前端**(`controlplane/frontend`),挂在控制面 8800。
|
||||
- **同一轮**把底座 `webhost` 的管理界面/管理代理**一并拆掉**(用户已拍板),普通用户接触不到管理入口。
|
||||
- 保持**四方向零依赖**:控制面前端为独立 Vite+Vue 工程(从 webhost 组件移植,而非 import),控制面后端仍只依赖 fastapi/标准库。
|
||||
|
||||
## 边界(哪些必须保留)
|
||||
|
||||
底座用户执行插件仍走统一登录:`webhost` 后端 `/api/runs` 有 `_require_login` + 会话 cookie。因此底座后端的**身份/个人接口必须保留**,只拆**管理操作类**:
|
||||
|
||||
- **保留**(webhost 后端):`/api/admin/me`、`/api/admin/login`、`/api/admin/logout`、`/api/admin/password`
|
||||
- **删除**(webhost 后端管理操作代理):`overview`、`admins`、`accounts`、`account`、`account/update`、`account/reset_pwd`、`account/delete`、`plugin/delete`、`account_plugins`、`pkg`
|
||||
- 对应 `webhost/frontend`:保留 LoginPage + 顶部账号/登出 + `adminMe/adminLogin/adminLogout/adminPassword`;删除「控制面管理」入口与 ManagementView 渲染、删除 `adminOverview/adminUpload/adminGrant/adminAccounts/adminAccount*/adminPluginDelete`。
|
||||
|
||||
## 方案
|
||||
|
||||
### A. 控制面后端 `controlplane/app.py`
|
||||
1. 新增 `CORSMiddleware`(`allow_origins=["*"]`),便于 dev 跨域(与控制面前端同源也就可浏览)。
|
||||
2. 新增 **`POST /api/admin/password`**:入参 `{account, old_password, new_password}`,校验 `x_admin_user==account`(本人),`_verify_password` 旧密正确后 `_hash_password` 更新入库。复用已有 `_hash_password/_verify_password/_db`。
|
||||
3. **挂载控制面前端产物**:文件末尾 `app.mount("/", StaticFiles(directory=<dist>, html=True), name="web")`;`dist` 路径兼容 **frozen**:源码取 `APP_DIR/frontend/dist`,exe 取 `sys._MEIPASS/frontend/dist`(与 DB 路径的 frozen 逻辑一致)。mount 放 app 定义之后,避免遮蔽 `/api/*`。
|
||||
|
||||
### B. 控制面前端(新工程)`controlplane/frontend/`
|
||||
Vite + Vue3,独立工程,技术栈/样式**移植**自 `webhost/frontend`(亮色主题、CSS 变量),但不 import 它:
|
||||
- 脚手架:`package.json`、`vite.config.js`(dev 代理 `/api`→`http://127.0.0.1:8800`,`outDir:'dist'`)、`index.html`、`src/main.js`、`src/style.css`(沿用 webhost 的 CSS 变量与亮色规范)。
|
||||
- `src/store.js`:`{ current, isAdmin }`(登录态,sessionStorage 持久化)。
|
||||
- `src/api.js`:**直连控制面**,登录用 `POST /api/admin/auth`;管理请求统一带 `X-Admin-User` header;封装:
|
||||
`adminAuth/adminMe/adminOverview/adminAccounts/adminAccountCreate/Update/Reset/Delete/adminGrant/adminUpload(FormData → /api/admin/pkg)/adminPluginDelete/adminPassword/me`。
|
||||
- `src/components/LoginPage.vue`:改调 `adminAuth`,成功后写 store.current/isAdmin。
|
||||
- `src/components/ManagementView.vue`:**移植裁剪**自 webhost 同名组件——插件上传/列表/删除、账号增改/切管理员/重置密码/删除(禁自删/自撤管理)、按账号勾选授权、修改密码;数据统一经 `adminOverview`。
|
||||
- `src/App.vue`:登录门 → 顶栏(品牌 + 当前账号 + 管理员徽标 + 退出)+ 管理主体。
|
||||
- 构建:`cd controlplane/frontend && npm install && npm run build`,产物落在 `controlplane/frontend/dist`,由 A3 挂载。
|
||||
|
||||
### C. 底座 `webhost/` 剥离管理
|
||||
- `backend/main.py`:删除 A 中列出的 10 个管理操作代理;保留身份/个人 4 个;编译校验。
|
||||
- `frontend/src`:App.vue 移除「控制面管理」入口与 mgmt 视图渲染;删除 `components/ManagementView.vue`;api.js 删除管理操作函数(保留 me/login/logout/password);`npm run build` 重新产出 dist 以同步部署素材。
|
||||
|
||||
### D.(收尾/可选)重打中心机 exe
|
||||
用 PyInstaller 把 `controlplane/frontend/dist` 作为 `datas` 打进 `37du-center.exe`,使中心机 exe 自带管理 UI(打开 8800 即见)。首版可先用源码形态起控制面,exe 重打作为下一步。
|
||||
|
||||
## 关键文件
|
||||
- `controlplane/app.py`(+CORS、+password、+静态挂载)
|
||||
- `controlplane/frontend/**`(新 Vue 工程)
|
||||
- `webhost/backend/main.py`(删除管理代理)
|
||||
- `webhost/frontend/src/App.vue`、`api.js`、`components/ManagementView.vue`(剥离)
|
||||
- 复用:`controlplane/app.py` 的 `_hash_password/_verify_password/_db`;webhost `ManagementView.vue/LoginPage.vue/api.js/store.js` 的 UI 与交互逻辑(移植)。
|
||||
|
||||
## 验证
|
||||
1. **控制面**:源码起 8800;`GET /health`、`GET /`(返回 SPA index)、`POST /api/admin/password`(改密并校验)、`GET /api/admin/overview`(X-Admin-User=puddy)均通。
|
||||
2. **控制面前端 dev**:`npm run dev` → 登录 `puddy/123456` → 建号/改部门/切管理员/上传 zip/按账号授权/删除 全链路 CRUD 通过;删当前账号/撤自己管理被拦截。
|
||||
3. **底座剥离**:`/api/meta` 正常;`/api/admin/overview` 返回 404(已删);`/api/admin/login`+`/api/admin/me` 仍可用(需控制面在);前端 `npm run build` 后访问 `/` 无「控制面管理」入口。
|
||||
4. **四方向零依赖**:`controlplane/app.py` 仍只 import fastapi/标准库;`controlplane/frontend` 只引用自身;确认无新增跨目录 import。
|
||||
@@ -1,195 +0,0 @@
|
||||
# 中心机 Vue 管理前端搭建与底座管理 UI 剥离实施计划
|
||||
|
||||
## 概要
|
||||
|
||||
按照决策:**管理 UI 放到中心机自身,底座(webhost)不再带管理界面**。本计划完成:
|
||||
|
||||
1. 控制面后端补充 CORS、挂载前端静态产物
|
||||
2. 新建 `controlplane/frontend/` Vue 工程,实现完整管理界面(登录 + 账号CRUD + 插件管理 + 上传)
|
||||
3. 底座 `webhost/` 剥离管理相关代码,删除前端管理入口和界面
|
||||
4. 确保四方向零依赖:控制面前端独立,不与 webhost/frontend 耦合
|
||||
|
||||
---
|
||||
|
||||
## 当前状态分析
|
||||
|
||||
| 项 | 状态 | 说明 |
|
||||
|----|------|------|
|
||||
| `controlplane/app.py` 后端 API | ✅ 已完成 | 账号CRUD、插件上传删除、授权、密码修改全齐 |
|
||||
| `controlplane/app.py` CORS | ❌ 缺失 | 需要添加 CORSMiddleware |
|
||||
| `controlplane/app.py` 挂载前端 | ❌ 缺失 | 需要在末尾挂载 StaticFiles |
|
||||
| `controlplane/frontend/` 工程 | ❌ 不存在 | 需要从零新建 |
|
||||
| 前端功能:登录页 | ❌ 缺失 | 需要移植适配 |
|
||||
| 前端功能:管理台(插件/账号) | ❌ 缺失 | 需要移植并适配控制面直连 |
|
||||
| `webhost/` 管理代码剥离 | ❌ 未做 | 需要删除 ManagementView、移除侧边栏入口 |
|
||||
| PyInstaller 打包 | ⚠️ 已存在 | 需要确保 frontend/dist 打进 exe |
|
||||
|
||||
---
|
||||
|
||||
## 实施步骤
|
||||
|
||||
### A. 控制面后端 `controlplane/app.py`
|
||||
|
||||
1. **新增 `CORSMiddleware`**:
|
||||
- 在 `app = FastAPI(...)` 之后添加:
|
||||
```python
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
app.add_middleware(CORSMiddleware, allow_origins=["*"],
|
||||
allow_methods=["*"], allow_headers=["*"])
|
||||
```
|
||||
- 便于开发跨域,生产同域也不影响。
|
||||
|
||||
2. **验证 `POST /api/admin/password`**:
|
||||
- 检查发现已存在(行 311-332),功能正确:校验本人、旧密码、更新入库。无需修改。
|
||||
|
||||
3. **挂载控制面前端产物**:
|
||||
- 文件末尾(`if __name__ == "__main__":` 之前)添加:
|
||||
```python
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
# 挂载前端:源码模式 => controlplane/frontend/dist;exe模式 => sys._MEIPASS/frontend/dist
|
||||
if getattr(sys, "frozen", False):
|
||||
DIST = Path(sys._MEIPASS) / "frontend" / "dist"
|
||||
else:
|
||||
DIST = APP_DIR / "frontend" / "dist"
|
||||
|
||||
if DIST.exists():
|
||||
app.mount("/", StaticFiles(directory=str(DIST), html=True), name="web")
|
||||
```
|
||||
- APP_DIR 已有定义,直接复用。mount 放 `if __name__` 之前,避免遮蔽 `/api/*`。
|
||||
|
||||
---
|
||||
|
||||
### B. 新建控制面前端工程 `controlplane/frontend/`
|
||||
|
||||
复制 `webhost/frontend` 骨架,精简为纯管理台(不需要场景插件、平台登录这些底座功能):
|
||||
|
||||
#### B.1 基础配置
|
||||
|
||||
| 文件 | 操作 | 说明 |
|
||||
|------|------|------|
|
||||
| `package.json` | 新建 | 与 webhose 保持一致:Vue3 + Vite |
|
||||
| `vite.config.js` | 新建 | proxy `/api` 到 `http://127.0.0.1:8800` |
|
||||
| `index.html` | 新建 | 根入口,`<div id="app"></div>` |
|
||||
| `src/main.js` | 新建 | createApp 挂载 |
|
||||
| `src/style.css` | 复制 | 复用 webhost 的样式变量(亮色主题) |
|
||||
|
||||
#### B.2 源码结构
|
||||
|
||||
```
|
||||
controlplane/frontend/
|
||||
├─ package.json
|
||||
├─ vite.config.js
|
||||
├─ index.html
|
||||
└─ src/
|
||||
├─ main.js
|
||||
├─ style.css
|
||||
├─ api.js # API 封装:直连控制面 /api/*,不代理
|
||||
├─ store.js # 状态:current/isAdmin等
|
||||
├─ App.vue # 主布局:登录页 + 管理台
|
||||
└─ components/
|
||||
├─ LoginPage.vue # 登录页
|
||||
└─ ManagementView.vue # 管理主页(插件/账号/上传)
|
||||
```
|
||||
|
||||
#### B.3 各文件内容要点
|
||||
|
||||
- **`api.js`**:全部 API 直连 `'/api/xxx'`,去掉底座代理相关。包含:
|
||||
- `adminMe`, `adminLogin`, `adminLogout`, `adminPassword`
|
||||
- `adminOverview`, `adminAccounts`, `adminAccountCreate`, `adminAccountUpdate`, `adminAccountReset`, `adminAccountDelete`
|
||||
- `adminGrant`, `adminPluginDelete`, `adminUpload`
|
||||
|
||||
- **`store.js`**:只保留管理需要的状态(去掉 plugin/platform/log 相关):
|
||||
```javascript
|
||||
import { reactive } from 'vue'
|
||||
export const store = reactive({
|
||||
appName: '37du 插件管理平台',
|
||||
isAdmin: false,
|
||||
current: (() => {
|
||||
try { return localStorage.getItem('cp_account') || '' } catch (_) { return '' }
|
||||
})(),
|
||||
})
|
||||
```
|
||||
|
||||
- **`App.vue`**:
|
||||
- 未登录 → 显示 `LoginPage`
|
||||
- 已登录 → 顶部品牌 + 当前账号/登出 + 主体 `ManagementView`
|
||||
- 精简布局(不需要左场景栏、右日志区),纯管理台。
|
||||
|
||||
- **`LoginPage.vue`**:复用 webhost 逻辑,认证成功跳管理台。
|
||||
|
||||
- **`ManagementView.vue`**:
|
||||
- 复用 webhost 的完整功能:上传插件、插件列表、账号管理、授权、修改密码
|
||||
- API 直连控制面,不需要底座代理。
|
||||
|
||||
---
|
||||
|
||||
### C. 底座 `webhost/` 剥离管理 UI
|
||||
|
||||
按照决策"本轮一并拆底座管理UI":
|
||||
|
||||
1. **`webhost/frontend/src/App.vue`**:
|
||||
- 删除 `<ManagementView v-else-if="store.view === 'admin'" />`
|
||||
- 删除侧边栏中"控制面管理"入口(`admin-entry` li)
|
||||
- 删除 `import ManagementView from './components/ManagementView.vue'`
|
||||
|
||||
2. **删除文件**:
|
||||
- `webhost/frontend/src/components/ManagementView.vue`
|
||||
|
||||
3. **`webhost/frontend/src/api.js`**:
|
||||
- 删除管理操作 API:`adminOverview`, `adminGrant`, `adminAccounts`, `adminAccountCreate`, `adminAccountUpdate`, `adminAccountReset`, `adminAccountDelete`, `adminPluginDelete`, `adminUpload`。
|
||||
- **保留** 登录/会话 API:`adminMe`、`adminLogin`、`adminLogout`、`adminPassword`(App.vue 的 checkSession/logout 与统一登录仍需要)。
|
||||
- 只保留业务插件执行相关 API 再加上述认证 API。
|
||||
|
||||
4. **`webhost/backend/main.py`**:
|
||||
- 删除管理操作代理端点:`admin_overview`、`admin_accounts`、`admin_account_create`、`admin_account_update`、`admin_account_reset`、`admin_account_delete`、`admin_plugin_delete`、`admin_grant`、`admin_upload`。
|
||||
- **保留** 认证相关:`admin_me`(App.vue 的 checkSession 判断 is_admin)、`admin_login`、`admin_logout`、`admin_password`(底座用户改自己密码)。
|
||||
|
||||
---
|
||||
|
||||
### D. 构建与打包
|
||||
|
||||
1. **安装前端依赖**:
|
||||
```bash
|
||||
cd controlplane/frontend
|
||||
npm install
|
||||
```
|
||||
|
||||
2. **构建生产产物**:
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
- 输出到 `controlplane/frontend/dist/`
|
||||
|
||||
3. **重新打包 exe**(如果需要):
|
||||
- PyInstaller 需要把 `controlplane/frontend/dist` 整个打包进 exe
|
||||
- 确保 `center_run.py` .spec 中包含该数据目录
|
||||
|
||||
---
|
||||
|
||||
## 验收标准
|
||||
|
||||
1. 启动控制面 `python controlplane/app.py` 后:
|
||||
- 访问 `http://127.0.0.1:8800` 能看到登录页
|
||||
- 用 `puddy / 123456` 能登录
|
||||
- 登录后能看到管理台,显示插件列表、账号列表
|
||||
- 能新建账号、改部门、切换管理员、重置密码、删除账号
|
||||
- 能给账号授权插件
|
||||
- 能上传新插件包
|
||||
- 能删除插件
|
||||
|
||||
2. 底座访问验证(配置 `CONTROLPLANE_URL=http://172.30.28.131:8800`):
|
||||
- 底座登录页正常跳转(经由底座后端代理到控制面认证)
|
||||
- 底座侧没有管理入口,符合安全预期
|
||||
|
||||
3. 四方向零依赖验证:
|
||||
- `controlplane/` 不 `import` `webhost/` 任何模块
|
||||
- `controlplane/frontend/` 独立构建,不引用 `webhost/frontend` 源码
|
||||
|
||||
---
|
||||
|
||||
## 风险与注意事项
|
||||
|
||||
- 路径兼容性:exe 模式下前端 dist 路径必须是 `sys._MEIPASS/frontend/dist`,确保打包正确
|
||||
- CORS:开发时需要,生产同域不需要但开着也不影响
|
||||
- 样式:复用 webhost 的 `style.css`,保持亮色主题一致
|
||||
@@ -0,0 +1,147 @@
|
||||
# 内网大文件服务器实施方案
|
||||
|
||||
## Context(背景)
|
||||
|
||||
现状:所有文件(壳子更新包、Chrome 安装包、插件)都经中心机 `117.72.191.188:8800` 中转下载。
|
||||
壳子走 `/api/shell/pkg`(`shell_updater.py`),插件走 download-ticket。大文件经中心机转发,
|
||||
中心机磁盘与带宽都紧张。
|
||||
|
||||
目标:
|
||||
- 大型文件(壳子安装包、Chrome 安装包等)改走**内网文件服务器**直连下载;
|
||||
- 中心机**只存转发链接**(MySQL `file_sources` 表),不存大包;
|
||||
- 小文件(插件)维持走中心机;
|
||||
- 发布动作全由 `agent_cli` 完成(上传到文件服务器 + 登记链接到中心机库),客户端拿到链接直连下载,不新增前端页面。
|
||||
|
||||
已确认的决策:
|
||||
1. 文件服务器 = **独立 new 模块** `desktop/fileserver/`,完全解耦,独立 `.env`,独立端口 `8802`,放内网机器。
|
||||
2. 发布流程:`agent_cli` 上传到文件服务器 → 得到内网 URL → 调用中心机 `/api/admin/*` 把 URL 写进 `file_sources` 表。
|
||||
3. 存储:新增统一大文件源表 `file_sources`(废弃 `chrome_releases` 的用法,不删表仅不再使用)。
|
||||
4. 鉴权:文件服务器上传/删除/列表需 token(`FILESERVER_TOKEN`),下载开放(内网直连)。
|
||||
5. 只做 CLI + API,不新增控制面前端页面。
|
||||
|
||||
---
|
||||
|
||||
## 一、新建内网文件服务器 `desktop/fileserver/`
|
||||
|
||||
独立 FastAPI 模块,模块搜索根 = `desktop/`,运行以 `desktop/` 为 cwd,不 import 任何其他模块。
|
||||
|
||||
### 文件结构
|
||||
```
|
||||
desktop/fileserver/
|
||||
main.py # FastAPI 入口(rfile,call_app: app)
|
||||
core/config.py # 读 fileserver/.env
|
||||
.env # 配置(新建)
|
||||
requirements.txt # fastapi uvicorn python-multipart(可选,供宝塔装依赖)
|
||||
data/ # 文件落盘目录(运行时生成,/www/wwwroot/fileserver/data 之类)
|
||||
```
|
||||
|
||||
### 配置 `desktop/fileserver/.env`
|
||||
```
|
||||
FILESERVER_PORT=8802
|
||||
FILESERVER_TOKEN=<强随机串> # 上传/删除/列表鉴权
|
||||
FILESERVER_DATA_DIR=</www/wwwroot/fileserver/data> # 落盘目录;本机开发可相对路径
|
||||
FILESERVER_BASE_URL=http://<内网IP>:8802 # 对外下载根(生成 url 用,需内网机器可访问)
|
||||
```
|
||||
|
||||
### 接口(`main.py`)
|
||||
| 方法 | 路径 | 鉴权 | 说明 |
|
||||
|---|---|---|---|
|
||||
| POST | `/api/upload` | token | multipart 上传,存 `DATA_DIR`,返回 `{id, filename, sha256, size, url}` |
|
||||
| GET | `/api/files` | token | 列表已上传文件 |
|
||||
| DELETE | `/api/files/{id}` | token | 删除文件 |
|
||||
| GET | `/{id}`或`/files/{id}` | 开放 | 下载,`FileResponse`,断点续传 |
|
||||
|
||||
- ID 用上传时间+随机,文件名保留原始名(防止覆盖,落盘用唯一 id,响应带原始 filename)。
|
||||
- 下载 URL 拼 `FILESERVER_BASE_URL/{id}?dl={filename}` 样式,`dl` 作为 attachment 文件名。
|
||||
- 上传计算 sha256 返回,供登记校验。
|
||||
|
||||
---
|
||||
|
||||
## 二、中心机改动 `desktop/controlplane/`
|
||||
|
||||
### 1. `core/db.py` 新增 `file_sources` 表
|
||||
在 `_INIT_STATEMENTS` 追加:
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS file_sources (
|
||||
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '自增ID',
|
||||
category VARCHAR(32) NOT NULL DEFAULT '' COMMENT '分类:shell/chrome/browser 等',
|
||||
version VARCHAR(32) NOT NULL DEFAULT '' COMMENT '版本号(对比/展示用,可选)',
|
||||
filename VARCHAR(255) NOT NULL DEFAULT '' COMMENT '原文件名',
|
||||
url TEXT NOT NULL COMMENT '内网文件服务器直链',
|
||||
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT 'sha256 校验值(可选,有则校验)',
|
||||
notes VARCHAR(512) NOT NULL DEFAULT '' COMMENT '说明',
|
||||
enabled TINYINT(1) NOT NULL DEFAULT 1 COMMENT '1=启用 0=停用',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_category (category)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='大文件源(内网直链,走内网文件服务器)'
|
||||
```
|
||||
同步更新 `tools/schema_mysql.sql`(追加同 SQL)。
|
||||
|
||||
### 2. 新增 `apis/file_sources.py` 管理 API(管理员)
|
||||
- `GET /api/admin/file-sources`:按 category 列出(分组+启停)。
|
||||
- `POST /api/admin/file-sources`:登记/更新一条 `{category, version, filename, url, sha256, notes}`(同一 category 按 version 去重,重复则覆盖 url/notes/enabled)。
|
||||
- `PATCH /api/admin/file-sources/{id}`:启停 `enabled` 或改 notes(可选)。
|
||||
- `DELETE /api/admin/file-sources/{id}`:删除。
|
||||
- 全部走 `_require_admin(x_admin_token, x_api_token)`,沿用现有鉴权,`app.py` 里 `include_router`。
|
||||
|
||||
### 3. 壳子版本接口接入内网直链(`apis/plugins.py`)
|
||||
`/api/shell/version` 响应新增 `url` 字段:
|
||||
- 优先从 `file_sources` 表取 `category='shell'` 的启用记录(取最新一条)拼 URL;
|
||||
- 取不到则回退现有 `version.json` 逻辑(兼容,`surl` 为空)。
|
||||
- 返回加 `{"url": ...}`;客户端拿不到 URL 时仍回退中心机 `/api/shell/pkg`。
|
||||
|
||||
---
|
||||
|
||||
## 三、`agent_cli` 新增大文件发布命令 `desktop/controlplane/tools/agent_cli.py`
|
||||
|
||||
新增子命令,实现「上传到文件服务器 + 登记到中心机」两步一步完成:
|
||||
```
|
||||
python -m controlplane.tools.agent_cli file push <本地文件> --category shell --version 1.2.0 --notes "..."
|
||||
python -m controlplane.tools.agent_cli file list [--category shell]
|
||||
python -m controlplane.tools.agent_cli file rm <id>
|
||||
```
|
||||
- `file push`:① 用 `FILESERVER_BASE_URL` + `FILESERVER_TOKEN` POST 到 `http://<内网>:8802/api/upload`,拿 `url`+`sha256`;② 调中心机 `POST /api/admin/file-sources` 登记。
|
||||
- 文件服务器地址/token 复用 `controlplane/.env` 新增键:
|
||||
```
|
||||
FILESERVER_BASE_URL=http://<内网IP>:8802
|
||||
FILESERVER_TOKEN=<与文件服务器.env一致的token>
|
||||
```
|
||||
- 已省略 `shell-release` 直接上传中心机的用法吗?保留现状兼容:壳子仍可用新 `file push --category shell`,中心机 version 接口会取 file_sources→url;同时保留 `shell-release` 写 version.json 作为兜底,二者互不冲突。
|
||||
|
||||
---
|
||||
|
||||
## 四、客户端直连内网下载 `desktop/webhost/backend/core/shell_updater.py`
|
||||
|
||||
- `fetch_cloud_version()` 已取到 `info`(含 version/sha256/notes,现新增 url)。
|
||||
- `_download_locked()`:下载 url 优先取 `info.get("url")`(内网直链),为空回退 `f"{config.CONTROLPLANE_URL}/api/shell/pkg"`。
|
||||
- 下载鉴权:内网直链无鉴权;回退中心机路径仍带 `_headers()`。
|
||||
- sha256 校验逻辑不变。
|
||||
|
||||
Chrome:本次仅经 `file_sources(category='chrome')` 统一登记备查;客户端暂无 Chrome 下载触发逻辑,不动。
|
||||
|
||||
---
|
||||
|
||||
## 五、依赖与部署备注
|
||||
|
||||
- `fileserver` 新增依赖 `python-multipart`(宝塔 venv 需装)。
|
||||
- 命令行解析沿用 `argparse`,`Client.call` / `upload_pkg` 模式复用。
|
||||
- 遵循项目约束:各模块独立 `.env`、互不 import、错误重试 ≤3、INFO 屏蔽大 JSON。
|
||||
|
||||
---
|
||||
|
||||
**关键改动文件清单**
|
||||
- 新增:`desktop/fileserver/main.py`、`desktop/fileserver/core/config.py`、`desktop/fileserver/.env`、`desktop/fileserver/requirements.txt`
|
||||
- 中心机:`core/db.py`、`tools/schema_mysql.sql`、`apis/file_sources.py`(新)、`apis/plugins.py`、`app.py`、`.env`(增键)、`tools/agent_cli.py`
|
||||
- 客户端:`desktop/webhost/backend/core/shell_updater.py`
|
||||
|
||||
---
|
||||
|
||||
## Verification(验证)
|
||||
|
||||
1. 本机语法校验所有改动 py。
|
||||
2. `desktop/` 下启动文件服务器:`.venv\Scripts\python.exe -m fileserver.main`,curl 上传/列表/下载 3 个接口回环验证(上传后 sha256 一致、下载内容一致,下载无需 token)。
|
||||
3. 本地调 `agent_cli file push` 全链路(文件服务器上传 + 中心机登记),`file list` 能看到记录。
|
||||
4. 中心机 `/api/shell/version` 返回含 `url`;`file_sources` 表有 shell 记录。
|
||||
5. 客户端 `shell_updater` 单测:`info` 带 url 时从 url 下载、不带时回退 `/api/shell/pkg`(mock requests 验证)。
|
||||
6. 部署:文件服务器用宝塔 Python 项目(gunicorn 8802)独立部署,`fileserver/.env` 配置内网地址;中心机改动按既有 SOP 上传重启。
|
||||
@@ -0,0 +1,122 @@
|
||||
# 平台登录账号(HR/OA)本地加密存储 · 实施方案
|
||||
|
||||
> 状态:待实施。本方案已获用户确认,实施时直接按此执行。
|
||||
|
||||
## 一、目标与边界
|
||||
|
||||
把客户端(webhost/执行机)的 HR/OA 平台登录账号从「服务端下发」改为「客户端本地加密存储 + 前端多账号管理与切换」:
|
||||
|
||||
- **HR/OA 平台登录账号**(- `hr_login_username/password`、`oa_login_username/password`):**不走服务端下发**,改为客户端本地加密保存,前端点击"平台账号"按钮弹出输入框管理,首次输入即保存,支持多账号切换。
|
||||
- **钉钉开放平台凭证**(`DINGTALK_APPSECRET/CORP_ID/AGENT_ID/APPKEY`):仍走服务端 RSA 下发(维持此前批准的方案,不在本次改动范围)。
|
||||
|
||||
用户偏好约束:亮色 UI、扁平简洁;接受"本机存密钥/私钥"的加密权衡(已有 `plugin_configs` 存密码先例)。
|
||||
|
||||
## 二、已完成 / 不需要再改
|
||||
|
||||
- 服务端 `_ALLOWED_KEYS` 已移除 `hr_login_*`、`oa_login_*`(只留 DINGTALK_*),`config_push.py` 已编辑。**下次需 py_compile 校验。**
|
||||
|
||||
## 三、数据模型(每平台多账号)
|
||||
|
||||
保存在客户端本地:`%LOCALAPPDATA%\37duAutomation\platform_accounts.json`(与 `plugin_configs` 同级目录)。
|
||||
|
||||
```
|
||||
{
|
||||
"hr": [
|
||||
{"id": "uuid1", "name": "张三(人资)", "username": "37036273",
|
||||
"password": "<Fernet 密文>", "selected": true}
|
||||
],
|
||||
"oa": [
|
||||
{"id": "uuid2", "name": "行政-李四", "username": "40020001",
|
||||
"password": "<Fernet 密文>", "selected": false}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
要点:
|
||||
- `id` 用于前端 key 与切换,稳定不随名称变化。
|
||||
- `name` 为可读别名(便于区分不同使用者)。
|
||||
- `username` 明文存储(平台登录号非高度敏感)。
|
||||
- `password` 只用 Fernet 加密密文,不存明文。
|
||||
- 每平台至多一个 `selected=true`;首次输入无选中项时自动设为选中。
|
||||
- 影刀版与 webhost 共用此文件(读当前选中账号),后续可打通影刀自定义指令读取。
|
||||
|
||||
## 四、加密方案
|
||||
|
||||
- 用 `cryptography` 的 **Fernet**(对称,单密钥,适合本地)。
|
||||
- 项目已依赖 `cryptography`(`licensing.py` 已 import 其 hazmat),新增 Fernet 复用同一依赖,无新增 pip 要求。
|
||||
- 密钥文件:`%LOCALAPPDATA%\37duAutomation\.platform_secret.key`(Fernet 密钥,生成一次持久化)。
|
||||
- 兼容性:密钥丢失 → 无法解密,需重新录入账号(可接受,本地单机场景)。
|
||||
- 文件权限:Windows 下此目录按用户隔离(`%LOCALAPPDATA%`),满足"方便不同使用者切账号"的同时隔离各异账号。
|
||||
|
||||
## 五、webhost 后端改动(新增模块 + 路由)
|
||||
|
||||
### 5.1 新增 `backend/core/platform_accounts.py`(加密存储单一真源)
|
||||
- 常量:`ACCOUNTS_FILE = %LOCALAPPDATA%\37duAutomation\platform_accounts.json`,`SECRET_FILE = ...\.platform_secret.key`。
|
||||
- `_load_key()`:若密钥文件不存在则 `Fernet.generate_key()` 生成并落盘;读取缓存校验。
|
||||
- `load_all() / save_all(data)`:整文件原子读写(tmp + replace,仿 `plugin_configs`)。
|
||||
- 业务函数:
|
||||
- `get_credentials(platform: str) -> (username, password) | None`:取该平台 `selected` 账号并**解密**,供 hr/oa 登录模块调用。若无任何账号返回 `None`。
|
||||
- `list_accounts(platform) -> [{id,name,username,selected}]`:**不回传密码**(明/密都不回传)。
|
||||
- `save_account(platform, name, username, password, id=None, selected=None)`:新增或更新;密码加密后写入。
|
||||
- `delete_account(platform, id)`。
|
||||
- `select_account(platform, id)`:置该平台 `selected`,其余置 false。
|
||||
- 重新导出当前选中账号到 env:`apply_selected_to_env(platform)` → `os.environ[platform_login_username/password] = 选中账号明文`,供登录模块使用(见 5.3)。
|
||||
|
||||
### 5.2 新增 `backend/apis/platform_acct.py` 路由(鉴权:内部账户 cookie,仿 admin/plugin_ui)
|
||||
- `GET /api/platform-accts/{pid}` → 返回 `{list: [{id,name,username,selected}], selected: {...}}`。
|
||||
- `POST /api/platform-accts/{pid}`(body: `{name, username, password, id?}`)→ 新增或更新;返回新列表。
|
||||
- `POST /api/platform-accts/{pid}/select`(body: `{id}`)→ 切换选中;返回新列表。
|
||||
- `DELETE /api/platform-accts/{pid}/{id}` → 删除。
|
||||
- 全部 `_require_login`;`pid` 白名单 `{"hr","oa"}`。
|
||||
- 在 `backend/main.py` 注册 `api_platform_acct.router`(新 import + include_router)。
|
||||
|
||||
### 5.3 `backend/shared/hr_login.py` & `oa_login.py` 改造(读取点收敛)
|
||||
- 目前二者在 **模块 import 时** `USERNAME = os.getenv('hr_login_username','')` 固化。
|
||||
- 改造:把读取改为「登录时/被调用时」从 `platform_accounts.get_credentials(...)` 取当前选中账号,注入 `USERNAME/PASSWORD`。
|
||||
- 推荐最小改动:在 `_load_shared_env()` 后 / `ensure_login()` 内新增:
|
||||
```python
|
||||
_creds = platform_accounts.get_credentials('hr') # 或 'oa'
|
||||
if _creds:
|
||||
USERNAME, PASSWORD = _creds
|
||||
```
|
||||
(`USERNAME/PASSWORD` 由模块级常量改为全局函数内可覆盖,或在 `_do_login`/`ensure_login` 里局部读取。)确保未配置账号时仍走原有报缺逻辑。
|
||||
- 注意:`auth.py`(webhost 宿主)import `_hr`/`_oa` 并调 `_hr._is_hr_session_valid()`、`.ensure_login()`——因此读取点要放进登录入口内而非 import 时,才能拿到最新选中账号。
|
||||
|
||||
## 六、前端改动(App.vue / 新增组件)
|
||||
|
||||
- 顶部「平台登录态」旁新增「平台账号」按钮(图标+文字,亮色圆角 chip,样式对齐现有 `chip`)。
|
||||
- 点击弹出对话框(新增 `PlatformAccountDialog.vue` 或直接在 App.vue 内 el-dialog):
|
||||
- 顶部平台 tab(HR/OA)或选择器。
|
||||
- 已存账号列表:单选切换(radio 表示 selected)、显示 name+username、鼠标悬停出「编辑/删除」。
|
||||
- 底部表单:name(别名,可空)、username、password,+「保存本账号」按钮;「删除」二次确认(ElMessageBox)。
|
||||
- 保存后调 `POST /api/platform-accts/{pid}`;切换调 `select`;删除调 `DELETE`。每次操作后刷新列表 + `refreshMeta()`(平台态不依赖账号,可不刷新)。
|
||||
- API 封装在 `src/api.js`(新增 `listPlatformAccounts/savePlatformAccount/selectPlatformAccount/deletePlatformAccount`)。
|
||||
- 关闭时提示:切换账号后需重新登录对应平台才生效(登录态 cookies 按账号隔离在`.sessions`)。
|
||||
|
||||
## 七、webhost/.env 清理
|
||||
|
||||
- [.env L31-L38](file:///d:/work/code/37duAutomation/desktop/webhost/.env) 移除明文:
|
||||
```
|
||||
hr_login_username / hr_login_password / oa_login_username / oa_login_password
|
||||
```
|
||||
- 保留 `hr_login_url`、`oa_login_url`(非敏感,登录页 URL,也可固化进模块源码——但保留 .env 更灵活,本次可暂留)。
|
||||
- 更新 L31 注释说明:HR/OA 账号移入本地加密存储 `platform_accounts.json`,不再从 .env 读。
|
||||
|
||||
## 八、实施顺序
|
||||
|
||||
1. 中心机:`py_compile` 校验 `controlplane/apis/config_push.py`(本轮已改白名单)。
|
||||
2. webhost:写 `backend/core/platform_accounts.py`(加密存储核心)。
|
||||
3. webhost:写 `backend/apis/platform_acct.py` 并在 `main.py` 注册。
|
||||
4. 改造 `hr_login.py` / `oa_login.py` 读取当前选中账号。
|
||||
5. 前端:`api.js` + 新增「平台账号」按钮与弹窗。
|
||||
6. 清理 `.env` 明文。
|
||||
7. `py_compile` 全部改动 + 前端 `npm run build`。
|
||||
8. 手动自测:录入→切换→删除;登录 HR/OA 用当前选中账号。
|
||||
|
||||
## 九、验证与风险
|
||||
|
||||
- 自测路径:webhost 源码态启动(`desktop/webhost/.venv`),登录壳子 → 平台账号弹窗 → 录入 HR/OA 各一账号 + 第二个 HR 账号做切换 → 点平台登录,观察用选中账号成功。
|
||||
- 风险:
|
||||
- `plugin_configs` 目录已在用,`platform_accounts.json` 与 `.platform_secret.key` 放同目录需避免同名冲突(已用独立文件名规避)。
|
||||
- Fernet 密钥丢失不可找回 → 提示"重新录入"。密钥文件应纳入执行机备份(可选)。
|
||||
- 平台登录仍走浏览器自动化(滑块),账号切换不影响登录流程本身,只影响填入的账号密码。
|
||||
@@ -0,0 +1,105 @@
|
||||
# 敏感凭证中心化下发方案(webhost 去明文)
|
||||
|
||||
> 措辞约定:本文「服务端」= 原「中心机/controlplane」,「客户端」= 原「执行机/webhost」。
|
||||
|
||||
## Context(背景与目标)
|
||||
|
||||
当前客户端 [webhost/.env](file:///d:/work/code/37duAutomation/desktop/webhost/.env) 明文存放钉钉开放平台凭证(`DINGTALK_APPKEY/APPSECRET/AGENT_ID/CORP_ID`)。客户端落盘明文,存在泄露风险。
|
||||
|
||||
目标:敏感凭证改为存服务端控制面,客户端启动时用 **云令牌(Bearer) + RSA** 加密下发;服务端用客户端上报的公钥加密、客户端私钥解密;首次拉取后**加密落盘缓存**,服务端宕机时离线可解密复用。
|
||||
|
||||
非敏感配置(`CONTROLPLANE_URL`、`RUN_TIMEOUT`、`PLUGIN_SOURCE`、`CONTROLPLANE_ACCOUNT`、`CONTROLPLANE_TOKEN`)保留本地 `.env` 不下发。
|
||||
|
||||
## 敏感项范围(本次下发)
|
||||
|
||||
来自 webhost/.env 的敏感键:
|
||||
- `DINGTALK_APPKEY`、`DINGTALK_APPSECRET`、`DINGTALK_AGENT_ID`、`DINGTALK_CORP_ID`
|
||||
|
||||
说明:
|
||||
- `DINGTALK_APPSECRET` 客户端本体其实不需用(扫码回调走服务端),但为保持配置源唯一、且按用户要求"钉钉开放平台的都下发",一并纳入。若某键服务端侧本就有值(如钉钉),以服务端 DB 为唯一可信源。
|
||||
- **HR/OA 平台登录账号**(`hr_login_username/password`、`oa_login_username/password`)**不在本方案下发范围内**,已改为客户端本地加密存储(见《平台账号本地加密存储方案.md》),服务端不下发。
|
||||
|
||||
## 架构与链路
|
||||
|
||||
```
|
||||
[客户端 webhost]
|
||||
启动 → 生成/读取 RSA 私钥(本地) → 持有公钥
|
||||
→ 有云令牌且服务端可达:
|
||||
1. POST /register 上报公钥(admin 或云令牌关联账号, 一次性)
|
||||
2. GET /creds (Bearer 云令牌) → 服务端用该公钥加密各敏感值 → base64
|
||||
3. 解密 → 覆盖 config.* 敏感项
|
||||
4. 加密落盘缓存(离线用)
|
||||
→ 服务端不可达: 读缓存 → 私钥解密 → 覆盖 config.*
|
||||
[服务端 controlplane]
|
||||
MySQL 表 client_creds 存 {account, 公钥, 敏感值密文}
|
||||
/admin/creds/seed (管理员) 录入各敏感项明文 → 存 DB (本期: 人工从中控/命令行录入)
|
||||
```
|
||||
|
||||
## 服务端改动
|
||||
|
||||
### 1. 新增建表 `client_creds`
|
||||
在 [db.py](file:///d:/work/code/37duAutomation/desktop/controlplane/core/db.py#L24-L183) 与 [schema_mysql.sql](file:///d:/work/code/37duAutomation/desktop/controlplane/tools/schema_mysql.sql) 同步新增:
|
||||
```sql
|
||||
CREATE TABLE client_creds (
|
||||
account VARCHAR(64) NOT NULL, -- 客户端账号
|
||||
pubkey_pem TEXT NOT NULL, -- 该账号上报的 RSA 公钥
|
||||
creds MEDIUMTEXT NOT NULL, -- {key: base64(RSA 密文)} JSON, 每个值用该公钥加密
|
||||
updated_at DATETIME,
|
||||
PRIMARY KEY (account)
|
||||
);
|
||||
```
|
||||
数据访问沿用 db.py 现有 MySQL helper 风格(如 `_conn`/`_query` 等现有函数)。
|
||||
|
||||
### 2. RSA 能力
|
||||
在 [crypto.py](file:///d:/work/code/37duAutomation/desktop/controlplane/core/crypto.py) 复用 `cryptography` 新增:
|
||||
- `rsa_encrypt(pubkey_pem, bytes) -> bytes`(服务端加密敏感值)
|
||||
(私钥解密/生成在客户端侧实现)
|
||||
|
||||
### 3. 新路由 `apis/config_push.py`(在 [app.py](file:///d:/work/code/37duAutomation/desktop/controlplane/app.py#L44-L52) 注册)
|
||||
- `POST /api/admin/register`(管理员 `_require_admin`):入参 `{account, pubkey_pem}`,upsert 该账号公钥。
|
||||
- `GET /api/admin/creds`(可被客户端访问,鉴权 `_cloud_account(Bearer)`,同 [auth.py](file:///d:/work/code/37duAutomation/desktop/controlplane/apis/auth.py#L38-L44) `admin_me` 的解析方式):按 account 查表,取公钥,把 DB 明文敏感值逐个 RSA 加密返回 `{key: base64}`;同时更新 `updated_at`。
|
||||
- `POST /api/admin/creds/seed`(管理员):入参 `{account, values:{key:plaintext}}`,用于把 webhost/.env 现有明文一次性迁入服务端 DB(本期种子来源)。
|
||||
|
||||
## 客户端改动 (webhost)
|
||||
|
||||
### 4. RSA 密钥对管理 `backend/core/creds_store.py`
|
||||
- 首启若无私钥则 `cryptography` 生成 RSA-2048,私钥持久化到 `%LOCALAPPDATA%\37duAutomation\shell\creds\id_rsa.pem`(公钥由私钥导出)。
|
||||
- 说明:私钥必须在客户端本机可解,故本机明文存私钥是必要权衡(与现有 `%LOCALAPPDATA%\37duAutomation\.env` 同级保护);如后续需要可加 DPAPI,本期不做。
|
||||
|
||||
### 5. 下发与缓存 `backend/core/creds_sync.py`
|
||||
- `sync()`:有云令牌(`_ACCT_CLOUD_TOKEN`)可复用时,按当前账号:(a)若服务端无该账号公钥则先 `POST /register`;(b) `GET /creds` → 逐项 RSA 私钥解密 → 返回 `dict[key]=plaintext`;(c) 把拉到的**密文 JSON 原样**写缓存 `%LOCALAPPDATA%\37duAutomation\shell\creds\cache.json`(落盘的是密文,叠加服务端加密层)。
|
||||
- `load() -> dict`:服务端可达走 `sync()`;不可达则读 `cache.json` 用私钥解密。
|
||||
- 复用现有 Bearer 调法(参考 [meta.py](file:///d:/work/code/37duAutomation/desktop/webhost/backend/core/meta.py) 调 `/api/plugins` 的 `_ACCT_CLOUD_TOKEN` + 请求封装)与现有落盘目录写法(参考 plugin_sync.py / shell_updater.py)。
|
||||
|
||||
### 6. 启动注入 + 配置读取收口
|
||||
- 在 [main.py](file:///d:/work/code/37duAutomation/desktop/webhost/backend/main.py) 启动早段(`_sync_licensing` 之前)调用 `creds_sync.load()`,把解密结果写入一个进程级覆盖 dict。
|
||||
- 配置读取:webhost 的 config 加载器对敏感键优先取覆盖 dict(远程值),否则回退本地 `.env`(过渡期兼容未配服务端的机器)。
|
||||
- 从 [webhost/.env](file:///d:/work/code/37duAutomation/desktop/webhost/.env) 删除/注释敏感明文值,改为注释说明"由服务端下发"。
|
||||
|
||||
## 复用清单(不新造)
|
||||
|
||||
| 能力 | 复用点 |
|
||||
|---|---|
|
||||
| 云令牌鉴权 | [controlplane/core/auth.py](file:///d:/work/code/37duAutomation/desktop/controlplane/core/auth.py#L119-L167) `_cloud_account`;webhost `_ACCT_CLOUD_TOKEN` + 登录返回 `cloud_token` |
|
||||
| RSA/密码库 | `cryptography`(服务端 [crypto.py](file:///d:/work/code/37duAutomation/desktop/controlplane/core/crypto.py) 已依赖;客户端同样依赖) |
|
||||
| MySQL 数据层 | [controlplane/core/db.py](file:///d:/work/code/37duAutomation/desktop/controlplane/core/db.py) |
|
||||
| Bearer 调服务端 | [webhost/backend/core/meta.py](file:///d:/work/code/37duAutomation/desktop/webhost/backend/core/meta.py) |
|
||||
| 落盘目录 | `%LOCALAPPDATA%\37duAutomation\shell\`(plugin_sync/shell_updater) |
|
||||
|
||||
## 关键权衡(需知悉)
|
||||
- **客户端私钥本机明文存**:RSA 公钥加密只能防传输抓包/越权读服务端,本地私钥仍需本机保护。真正的"防本地泄露"需系统级 DPI/TPM,本期不引入。
|
||||
- **服务端 DB 与 webhost 原 .env 的值一致性**:seed 后以服务端为唯一源;旧 webhost/.env 值将失效并被删除。
|
||||
- **云令牌内存态**:服务端重启会丢已有云令牌(现有行为),届时客户端需重新登录后才再次拉取/刷新。缓存密文不受影响。
|
||||
|
||||
## 执行顺序
|
||||
1. 服务端:建表(db.py + schema_mysql.sql) → rsa_encrypt → config_push 路由 → app.py 注册。
|
||||
2. 客户端:creds_store(密钥对) → creds_sync(拉取+缓存+解密) → config 覆盖 + main.py 启动注入 → .env 去明文。
|
||||
3. 发布:服务端按 SOP 部署(含建表);webhost 重新打包发版。
|
||||
4. 迁移:管理员用 `creds/seed` 把现网 webhost/.env 的明文值录入服务端 DB。
|
||||
|
||||
## 验证 (端到端)
|
||||
1. 本地起服务端:确认 `client_creds` 表创建成功;`crypto.rsa_encrypt` 单测通过。
|
||||
2. 本地起 webhost 指针回本地服务端:首启生成私钥→register→拉取→解密后 `config.DINGTALK_APPSECRET` 等等于服务端 seed 值。
|
||||
3. 断网/停服务端:删本地 .env 敏感行后重启,确认 `creds_sync.load()` 用缓存密文解密出同一值(离线可用)。
|
||||
4. 服务端日志:`/creds` 命中、`updated_at` 更新、无异常。
|
||||
5. 发布到 117.72.191.188,客户端实测扫码/插件登录凭证取用正常。
|
||||
@@ -37,7 +37,7 @@ AI 智能体开发约束 & 项目执行规范
|
||||
- 变量配置规范:禁止使用命令行传入变量的方式实现参数配置,所有参数、变量、配置项均在代码/配置文件内部定义、固化或读取本地配置,保证运行无外部参数依赖。
|
||||
5. 发版与自动更新操作规范
|
||||
- 自动更新:插件由执行机按账号权限自下载(plugin_sync.py);壳子由执行机自动下载安装包 + 用户点击升级重启(shell_updater.py)。版本源都在中心机控制面。
|
||||
- 发版统一走 agent CLI(在 desktop/ 目录下执行:.venv\Scripts\python.exe -m controlplane.tools.agent_cli,中心机本机 + 管理密钥,即控制面 /api/admin/pkg 与 shell 源):
|
||||
- 发版统一走 agent CLI(在 desktop/ 目录下执行:.venv\Scripts\python.exe -m controlplane.tools.agent_cli,即控制面 /api/admin/pkg 与 shell 源)。鉴权两种方式:① 密码登录(推荐,任意机器可用):`--admin <管理员> --password <密码>`(或环境变量 AGENT_ADMIN_PASSWORD / AGENT_ADMIN_ACCOUNT),远程机器再加 `--base http://<中心机地址>:8800`;② 本机密钥自签(中心机本机):复用 controlplane/.env 与 .admin_secret。
|
||||
- 壳子发版:改 desktop/webhost/tools/shell.version 与 install.iss 的 MyAppVersion → desktop/webhost/frontend 执行 npm run build → PyInstaller 依次打 desktop/webhost/tools/37du-host.spec、37du-host-runner.spec、37du-host-console.spec → ISCC.exe desktop/webhost/tools/install.iss 出安装包;然后 agent_cli shell-release <安装包> --version <新版本> [--notes "说明"]。
|
||||
- 插件发版:根级 plugins/<id>/ 目录打成 zip(根目录含 plugin.json)后 agent_cli publish <插件.zip> --id <id> --version <v>;权限用 agent_cli grant / revoke 管理。
|
||||
- 中心机发版:控制面为源码部署(宝塔 gunicorn 8800,不打包 exe)。改后端代码后按 .trae/documents/控制面前后端部署SOP.md「后端部署流程」上传文件 + 重启项目;改前端后按同一文档「前端部署流程」构建并发布到静态站 8090。
|
||||
|
||||
@@ -6,16 +6,12 @@
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException
|
||||
|
||||
from controlplane import config, schemas
|
||||
from controlplane.core.auth import (
|
||||
_AUTH_FAILS, _auth_account_lookup, _auth_fail, _auth_gate, _check_token,
|
||||
_resolve_login, _require_admin, _sign_admin_token,
|
||||
_cloud_account, _issue_cloud_token, _resolve_login, _require_admin, _sign_admin_token,
|
||||
)
|
||||
from controlplane.core.crypto import _hash_password, _verify_password
|
||||
from controlplane.core.db import _db
|
||||
@@ -30,14 +26,21 @@ _CONTROLPLANE_PLATFORMS = [
|
||||
|
||||
|
||||
@router.get("/api/admin/me")
|
||||
def admin_me(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
def admin_me(authorization: str = Header(default="", alias="Authorization"),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
|
||||
"""查询当前账号信息:管理员标识 + 部门 + 昵称。"""
|
||||
try:
|
||||
account = _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
account = ""
|
||||
"""查询当前账号信息:管理员标识 + 部门 + 昵称 + 头像。
|
||||
|
||||
身份来源依次:登录时签发的用户云令牌(Bearer) → 签名票据(X-Admin-Token) →
|
||||
底座注入的 X-Admin-User(仅当配了 CONTROLPLANE_TOKEN 时可信)。
|
||||
"""
|
||||
account = _cloud_account(authorization)
|
||||
if not account:
|
||||
try:
|
||||
account = _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
account = ""
|
||||
if not account:
|
||||
return {"account": "", "is_admin": False, "dept": "", "nickname": "", "avatar": ""}
|
||||
with _db() as conn:
|
||||
@@ -65,8 +68,8 @@ def admin_platforms(x_admin_token: str = Header(default="", alias="X-Admin-Token
|
||||
@router.post("/api/admin/auth")
|
||||
def admin_auth(a: schemas.AuthIn,
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""统一账户登录:所有账号均可登录(需密码正确);是否管理员由 is_admin 决定。"""
|
||||
_check_token(x_api_token)
|
||||
"""统一账户登录:所有账号均可登录(需密码正确);是否管理员由 is_admin 决定。
|
||||
登录接口为公开入口,不要求 X-API-Token(否则未登录无法着装鉴权)。"""
|
||||
account = a.account.strip()
|
||||
if not account:
|
||||
raise HTTPException(400, "account 不能为空")
|
||||
@@ -82,23 +85,28 @@ def admin_auth(a: schemas.AuthIn,
|
||||
if not row["status"]:
|
||||
raise HTTPException(403, "账号已停用,请联系管理员")
|
||||
_AUTH_FAILS.pop(account, None)
|
||||
_nickname = (row["nickname"] or "")
|
||||
return {"ok": True, "account": account, "is_admin": bool(row["is_admin"]),
|
||||
"dept": (row["dept"] or ""), "nickname": (row["nickname"] or ""),
|
||||
"dept": (row["dept"] or ""), "nickname": _nickname,
|
||||
"avatar": (row["avatar"] or ""),
|
||||
"must_change_pwd": bool(row["must_change_pwd"]),
|
||||
"token": _sign_admin_token(account)}
|
||||
"token": _sign_admin_token(account),
|
||||
"cloud_token": _issue_cloud_token(account, _nickname)}
|
||||
|
||||
|
||||
@router.post("/api/admin/password")
|
||||
def admin_password(p: schemas.PwdIn,
|
||||
authorization: str = Header(default="", alias="Authorization"),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
|
||||
"""自助修改密码:任何统一账号可改自己的密码(需旧密码校验通过)。"""
|
||||
try:
|
||||
login = _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||||
login = _cloud_account(authorization)
|
||||
if not login:
|
||||
try:
|
||||
login = _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||||
if not p.account.strip() or not p.new_password:
|
||||
raise HTTPException(400, "account 与新密码不能为空")
|
||||
if p.account != login:
|
||||
@@ -123,10 +131,8 @@ def admin_password(p: schemas.PwdIn,
|
||||
|
||||
# ==================== 员工端登录 /auth/exchange(v3 最简方案,壳本机直连接 code) ====================
|
||||
# 壳 login 云端的唯一接口:壳把浏览器带回的钉钉 code POST 到此,用 AppSecret 换身份 → 只验证不建号
|
||||
# → 签发云端会话 token(供壳调 /api/plugins 鉴权,见 apis/plugins §2.2)。
|
||||
_CLOUD_TOKEN_TTL = 7 * 24 * 3600
|
||||
_cloud_tokens: dict = {}
|
||||
_cloud_lock = threading.Lock()
|
||||
# → 签发云端会话 token(供壳调 /api/plugins 鉴权,见 apis/plugins §2.2)。token 存储统一在
|
||||
# core.auth._cloud_tokens(_issue_cloud_token 签发、_cloud_account 解析),此处不再重复声明。
|
||||
|
||||
|
||||
@router.post("/auth/exchange")
|
||||
@@ -142,14 +148,8 @@ def auth_exchange(d: schemas.AuthExchangeIn) -> dict:
|
||||
if not account:
|
||||
raise HTTPException(401, "扫码未解析到有效账号,请重新扫码")
|
||||
acct = _auth_account_lookup(account)
|
||||
token = secrets.token_urlsafe(32)
|
||||
now = time.time()
|
||||
with _cloud_lock:
|
||||
# 惰性清理过期云端会话,防内存无限增长
|
||||
for k in [k for k, v in _cloud_tokens.items() if v["exp"] < now]:
|
||||
_cloud_tokens.pop(k, None)
|
||||
_cloud_tokens[token] = {"exp": now + _CLOUD_TOKEN_TTL, "account": account,
|
||||
"nickname": acct["nickname"] or (info.get("nickname") or "")}
|
||||
nickname = acct["nickname"] or (info.get("nickname") or "")
|
||||
token = _issue_cloud_token(account, nickname)
|
||||
return {"token": token,
|
||||
"account": account, "nickname": acct["nickname"] or (info.get("nickname") or ""),
|
||||
"account": account, "nickname": nickname,
|
||||
"exists": bool(acct["exists"]), "is_admin": False}
|
||||
@@ -0,0 +1,154 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""客户端敏感凭证中心化拉取(服务端侧):公钥登记 / 敏感凭证加密拉取 / 明文源管理。
|
||||
|
||||
- 凭证明文源存服务端 MySQL `client_creds.creds`(JSON: {key: plaintext}),
|
||||
明文源只由管理员经「敏感凭证」页面(/creds/manage 查看 + /creds/seed 保存)录入;
|
||||
register 仅登记执行机 RSA 公钥,不自动填充默认值。
|
||||
- 拉取 GET /api/admin/creds:**仅管理员可拉**(解析身份后校验 is_admin),服务端用该账号
|
||||
上报的 RSA 公钥把每个明文值 OAEP 加密为 base64 返回;客户端本机私钥解密。
|
||||
- 钉钉扫码 URL 已改由控制面代理构造(/api/dingtalk/login-url),执行机不再消费下发的钉钉值,
|
||||
链路保留供未来每账号敏感值下发能力使用。
|
||||
- 仅含钉钉开放平台凭证;HR/OA 平台登录账号由客户端本地加密存储(platform_accounts),不经服务端。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException
|
||||
|
||||
from controlplane import schemas
|
||||
from controlplane.core.auth import _cloud_account, _resolve_login, _require_admin
|
||||
from controlplane.core.crypto import rsa_encrypt
|
||||
from controlplane.core.db import _db, _now
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# 与 webhost/backend/core/creds_sync.py 的敏感键白名单保持一致(双重保障:下发限定范围)。
|
||||
# 仅下发钉钉开放平台凭证;HR/OA 平台登录账号改由执行机本地加密存储(platform_accounts),不经中心机。
|
||||
_ALLOWED_KEYS = (
|
||||
"DINGTALK_APPKEY", "DINGTALK_APPSECRET", "DINGTALK_AGENT_ID", "DINGTALK_CORP_ID",
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/admin/creds/register")
|
||||
def creds_register(b: schemas.CredsRegisterIn,
|
||||
authorization: str = Header(default="", alias="Authorization"),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""登记/更新某账号的 RSA 公钥(明文源不变)。
|
||||
|
||||
鉴权双轨(对齐方案"admin 或云令牌关联账号"):
|
||||
- 管理员(X-Admin-Token)可为任意账号登记;
|
||||
- 登录云令牌(Bearer)账号只能登记本人公钥(公钥本身公开,本人登记安全)。
|
||||
"""
|
||||
try:
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
except HTTPException:
|
||||
_self = _cloud_account(authorization)
|
||||
if not _self or _self != b.account.strip():
|
||||
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||||
account = b.account.strip()
|
||||
pem = b.pubkey_pem.strip()
|
||||
if not account or not pem:
|
||||
raise HTTPException(400, "account 与 pubkey_pem 不能为空")
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT creds FROM client_creds WHERE account = %s", (account,)).fetchone()
|
||||
# 明文源只由管理员 seed 创建/更新:register 仅登记公钥,保留现有明文源(无则空)
|
||||
existing = (row["creds"] if row else None) or "{}"
|
||||
conn.execute(
|
||||
"INSERT INTO client_creds(account, pubkey_pem, creds, updated_at) VALUES (%s, %s, %s, %s) "
|
||||
"ON DUPLICATE KEY UPDATE pubkey_pem = VALUES(pubkey_pem), "
|
||||
"creds = VALUES(creds), updated_at = VALUES(updated_at)",
|
||||
(account, pem, existing, _now()))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account}
|
||||
|
||||
|
||||
@router.post("/api/admin/creds/seed")
|
||||
def creds_seed(b: schemas.CredsSeedIn,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""录入/更新某账号的敏感凭证明文源(管理员,只允许白名单内键)。
|
||||
|
||||
仅当 pubkey_pem 非空时才需要用现有公钥给新增值加密留档;这里统一存明文源,
|
||||
/creds 下发时实时用该账号公钥加密,故无需在此预加密。
|
||||
"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
account = b.account.strip()
|
||||
if not account:
|
||||
raise HTTPException(400, "account 不能为空")
|
||||
allowed = {k: v for k, v in b.values.items() if k in _ALLOWED_KEYS}
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT pubkey_pem FROM client_creds WHERE account = %s", (account,)).fetchone()
|
||||
if row:
|
||||
conn.execute(
|
||||
"UPDATE client_creds SET creds = %s, updated_at = %s WHERE account = %s",
|
||||
(json.dumps(allowed, ensure_ascii=False), _now(), account))
|
||||
else:
|
||||
conn.execute(
|
||||
"INSERT INTO client_creds(account, pubkey_pem, creds, updated_at) VALUES (%s, '', %s, %s)",
|
||||
(account, json.dumps(allowed, ensure_ascii=False), _now()))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account, "seeded_keys": sorted(allowed)}
|
||||
|
||||
|
||||
@router.get("/api/admin/creds/manage")
|
||||
def creds_manage(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""管理台:列出已注册账号及其敏感凭证明文源(管理员回显,供页面编辑;值仅管理台可见)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
with _db() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT account, pubkey_pem, creds, updated_at FROM client_creds ORDER BY account").fetchall()
|
||||
return {
|
||||
"accounts": [{
|
||||
"account": r["account"],
|
||||
"has_pubkey": bool(r["pubkey_pem"]),
|
||||
"creds": json.loads(r["creds"] or "{}"),
|
||||
"updated_at": str(r["updated_at"] or ""),
|
||||
} for r in rows],
|
||||
"allowed_keys": list(_ALLOWED_KEYS),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/api/admin/creds")
|
||||
def creds_fetch(authorization: str = Header(default="", alias="Authorization"),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
|
||||
"""下发敏感凭证(**仅管理员可拉**)。鉴权:登录云令牌(Bearer) → 签名票据 → X-Admin-User。
|
||||
|
||||
解析出账号后校验 is_admin=1,非管理员一律 403(员工无法拉取,堵住越权窃取口子)。
|
||||
用账号上报的 RSA 公钥把每个明文值 OAEP 加密为 base64;无公钥或无明文源返回空。
|
||||
"""
|
||||
account = _cloud_account(authorization)
|
||||
if not account:
|
||||
try:
|
||||
account = _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
account = ""
|
||||
if not account:
|
||||
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||||
with _db() as conn:
|
||||
admin = conn.execute(
|
||||
"SELECT is_admin FROM accounts WHERE account = %s", (account,)).fetchone()
|
||||
if not admin or not admin["is_admin"]:
|
||||
raise HTTPException(403, "仅管理员可拉取敏感凭证")
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT pubkey_pem, creds FROM client_creds WHERE account = %s", (account,)).fetchone()
|
||||
if not row or not row["pubkey_pem"]:
|
||||
return {"account": account, "creds": {}}
|
||||
try:
|
||||
source = json.loads(row["creds"] or "{}")
|
||||
encrypted = {k: rsa_encrypt(row["pubkey_pem"], v)
|
||||
for k, v in source.items() if v is not None}
|
||||
except Exception as e: # noqa: BLE001
|
||||
raise HTTPException(500, f"凭证加密失败: {e}") from e
|
||||
with _db() as conn:
|
||||
conn.execute("UPDATE client_creds SET updated_at = %s WHERE account = %s",
|
||||
(_now(), account))
|
||||
conn.commit()
|
||||
return {"account": account, "creds": encrypted}
|
||||
@@ -126,4 +126,28 @@ def dingtalk_inline_qr(back: str = Query(default="", description="(兼容保留
|
||||
"&response_type=code&scope=snsapi_login&state=%s&redirect_uri=%s") % (
|
||||
config.DINGTALK_APP_KEY, secrets.token_hex(8),
|
||||
quote(f"{config.DINGTALK_CALLBACK}/api/admin/dingtalk/cb"))
|
||||
return {"goto": quote(auth_url)}
|
||||
return {"goto": quote(auth_url)}
|
||||
|
||||
|
||||
@router.get("/api/dingtalk/login-url")
|
||||
def dingtalk_login_url(back: str = Query(...),
|
||||
state: str = Query(default=""),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""构造钉钉扫码授权 URL(执行机代理调用):执行机无需自带钉钉应用凭证。
|
||||
|
||||
back 为执行机本机回跳地址(如 http://localhost:8799/auth/done),state 由执行机生成防回跳伪造;
|
||||
扫码后钉钉跳回 back,执行机再拿 code 走 /auth/exchange 换身份。
|
||||
"""
|
||||
_check_token(x_api_token)
|
||||
if not config.DINGTALK_APP_KEY or not config.DINGTALK_APP_SECRET:
|
||||
raise HTTPException(503, "控制面未配置钉钉开放平台应用(DINGTALK_APP_KEY / DINGTALK_APP_SECRET)")
|
||||
if not (back.startswith("http://") or back.startswith("https://")):
|
||||
raise HTTPException(400, "回跳地址非法(防止开放重定向)")
|
||||
login_url = "https://login.dingtalk.com/oauth2/challenge.htm?" + urlencode({
|
||||
"redirect_uri": back,
|
||||
"response_type": "code",
|
||||
"client_id": config.DINGTALK_APP_KEY,
|
||||
"scope": "openid",
|
||||
"prompt": "consent",
|
||||
"state": state or back})
|
||||
return {"url": login_url}
|
||||
@@ -0,0 +1,156 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""大文件源管理 API(管理员):登记/更新内网直链、列表、启停、删除。
|
||||
|
||||
大文件(壳子安装包、Chrome 安装包等)走内网文件服务器,中心机只存其直链。
|
||||
发布动作由 agent_cli 完成:先传文件服务器拿 url,再经本接口登记。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from controlplane.core.auth import _check_token, _require_admin
|
||||
from controlplane.core.db import _db, _now
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class FileSourceIn(BaseModel):
|
||||
"""登记/更新一条大文件源。同一 category+version 重复提交则覆盖 url/notes/sha256/enabled。"""
|
||||
category: str = Field(default="", max_length=32)
|
||||
version: str = Field(default="", max_length=32)
|
||||
filename: str = Field(default="", max_length=255)
|
||||
url: str = Field(default="", max_length=2000)
|
||||
sha256: str = Field(default="", max_length=64)
|
||||
notes: str = Field(default="", max_length=512)
|
||||
enabled: bool = True
|
||||
|
||||
|
||||
class FileSourcePatch(BaseModel):
|
||||
"""启停 / 改说明。"""
|
||||
enabled: Optional[bool] = None
|
||||
notes: Optional[str] = None
|
||||
|
||||
|
||||
def _rows_to_dicts(rows) -> list[dict]:
|
||||
out = []
|
||||
for r in rows:
|
||||
out.append({"id": r["id"], "category": r["category"], "version": r["version"],
|
||||
"filename": r["filename"], "url": r["url"], "sha256": r["sha256"],
|
||||
"notes": r["notes"], "enabled": bool(r["enabled"]),
|
||||
"updated_at": str(r["updated_at"] or "")})
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/api/admin/file-sources")
|
||||
def file_sources_list(category: str = "",
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""按 category 列出大文件源(可按 category 过滤,分组也可由 category 字段区分)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
with _db() as conn:
|
||||
if category.strip():
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM file_sources WHERE category = %s ORDER BY version, id",
|
||||
(category.strip(),)).fetchall()
|
||||
else:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM file_sources ORDER BY category, version, id").fetchall()
|
||||
return {"category": category, "files": _rows_to_dicts(rows)}
|
||||
|
||||
|
||||
@router.post("/api/admin/file-sources")
|
||||
def file_sources_upsert(b: FileSourceIn,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""登记/覆盖一条大文件源(同一 category+version 去重)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
category, version = b.category.strip(), b.version.strip()
|
||||
url = b.url.strip()
|
||||
if not category:
|
||||
raise HTTPException(400, "category 不能为空")
|
||||
if not url:
|
||||
raise HTTPException(400, "url 不能为空")
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT id FROM file_sources WHERE category = %s AND version = %s",
|
||||
(category, version)).fetchone()
|
||||
if row:
|
||||
conn.execute(
|
||||
"UPDATE file_sources SET filename=%s, url=%s, sha256=%s, notes=%s, "
|
||||
"enabled=%s, updated_at=%s WHERE id=%s",
|
||||
(b.filename.strip(), url, b.sha256.strip(), b.notes.strip(),
|
||||
int(b.enabled), _now(), row["id"]))
|
||||
fid = row["id"]
|
||||
else:
|
||||
cur = conn.execute(
|
||||
"INSERT INTO file_sources(category, version, filename, url, sha256, notes, "
|
||||
"enabled, updated_at) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)",
|
||||
(category, version, b.filename.strip(), url, b.sha256.strip(),
|
||||
b.notes.strip(), int(b.enabled), _now()))
|
||||
fid = cur.lastrowid
|
||||
conn.commit()
|
||||
return {"ok": True, "id": fid, "category": category, "version": version}
|
||||
|
||||
|
||||
@router.patch("/api/admin/file-sources/{fid}")
|
||||
def file_sources_patch(fid: int, b: FileSourcePatch,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""启停 / 改说明。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
fields, vals = [], []
|
||||
if b.enabled is not None:
|
||||
fields.append("enabled = %s"); vals.append(int(b.enabled))
|
||||
if b.notes is not None:
|
||||
fields.append("notes = %s"); vals.append(b.notes.strip())
|
||||
if not fields:
|
||||
raise HTTPException(400, "无更新字段")
|
||||
fields.append("updated_at = %s"); vals.append(_now())
|
||||
with _db() as conn:
|
||||
cur = conn.execute(f"UPDATE file_sources SET {', '.join(fields)} WHERE id=%s",
|
||||
(*vals, fid))
|
||||
conn.commit()
|
||||
if cur.rowcount == 0:
|
||||
raise HTTPException(404, "记录不存在")
|
||||
return {"ok": True, "id": fid}
|
||||
|
||||
|
||||
@router.delete("/api/admin/file-sources/{fid}")
|
||||
def file_sources_delete(fid: int,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""删除一条大文件源(仅删中心机登记,不动内网服务器文件)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
with _db() as conn:
|
||||
cur = conn.execute("DELETE FROM file_sources WHERE id = %s", (fid,))
|
||||
conn.commit()
|
||||
if cur.rowcount == 0:
|
||||
raise HTTPException(404, "记录不存在")
|
||||
return {"ok": True, "id": fid}
|
||||
|
||||
|
||||
@router.get("/api/file-sources/{category}")
|
||||
def file_sources_public_latest(category: str,
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""客户端只读取某 category 最新启用的一条大文件源(带 X-API-Token 即可,无需 admin 票据)。
|
||||
|
||||
供执行机消费内网大文件直链(如 Chrome 安装包)。返回最近 version 的一条;无则 available=False。
|
||||
"""
|
||||
_check_token(x_api_token)
|
||||
with _db() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT id, category, version, filename, url, sha256, notes FROM file_sources "
|
||||
"WHERE category = %s AND enabled = 1 ORDER BY version DESC, id DESC LIMIT 1",
|
||||
(category.strip(),)).fetchall()
|
||||
if not rows:
|
||||
return {"available": False, "category": category.strip()}
|
||||
r = rows[0]
|
||||
return {
|
||||
"available": True,
|
||||
"category": r["category"], "version": r["version"],
|
||||
"filename": r["filename"], "url": r["url"], "sha256": r["sha256"],
|
||||
"notes": r["notes"] or "",
|
||||
}
|
||||
@@ -7,6 +7,7 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import secrets
|
||||
import time
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException, Query
|
||||
from fastapi.responses import FileResponse
|
||||
@@ -14,7 +15,6 @@ from fastapi.responses import FileResponse
|
||||
from controlplane import config, crypto, schemas
|
||||
from controlplane.core.auth import _check_token, _cloud_account
|
||||
from controlplane.core.db import _audit, _db, _now
|
||||
from controlplane.core.pkgutil import _load_manifest
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -78,52 +78,6 @@ def platforms_allowed(account: str = Query(default="", description="账号(旧
|
||||
return {"account": acct, "allowed": [dict(r)["platform_id"] for r in rows]}
|
||||
|
||||
|
||||
@router.get("/api/manifest")
|
||||
def manifest(x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""全量插件版本清单:客户端据此比对是否需要拉新包。"""
|
||||
_check_token(x_api_token)
|
||||
with _db() as conn:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT p.id, p.name, p.latest_version AS version, pv.uploaded_at,
|
||||
p.status, p.category, pv.sha256 AS pkg_sha256, p.manifest
|
||||
FROM plugins p
|
||||
LEFT JOIN plugin_versions pv ON pv.plugin_id = p.id AND pv.version = p.latest_version
|
||||
ORDER BY p.id
|
||||
"""
|
||||
).fetchall()
|
||||
out = []
|
||||
for r in rows:
|
||||
item = dict(r)
|
||||
m = _load_manifest(item.pop("manifest"))
|
||||
item["manifest"] = m
|
||||
item["capabilities"] = m.get("capabilities") or []
|
||||
item["permissions"] = m.get("permissions") or {}
|
||||
props = (m.get("fields") or {}).get("properties") or {}
|
||||
item["field_count"] = len(props)
|
||||
out.append(item)
|
||||
return {"plugins": out, "generated_at": _now()}
|
||||
|
||||
|
||||
@router.get("/api/pkg/{plugin_id}/{version}")
|
||||
def pkg(plugin_id: str, version: str,
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")):
|
||||
"""下载指定版本插件包。包文件存磁盘,DB 记 filename 索引。"""
|
||||
_check_token(x_api_token)
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT filename FROM plugin_versions WHERE plugin_id = %s AND version = %s",
|
||||
(plugin_id, version),
|
||||
).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, f"未找到插件包 {plugin_id}@{version}")
|
||||
path = config.PKG_DIR / row["filename"]
|
||||
if not path.exists():
|
||||
raise HTTPException(404, f"包文件缺失:{row['filename']}")
|
||||
_audit("", "download", f"{plugin_id}@{version}")
|
||||
return FileResponse(path, filename=row["filename"], media_type="application/octet-stream")
|
||||
|
||||
|
||||
# ==================== 产品化:客户端(部署端)拉取接口 ====================
|
||||
@router.get("/api/me/pubkey")
|
||||
def me_pubkey() -> dict:
|
||||
@@ -136,7 +90,8 @@ def me_license(account: str = Query(...), device: str = Query(default=""),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""签发离线授权票据:基于当前账号的插件级授权(can_run)快照,Ed25519 签名。
|
||||
|
||||
票据无硬过期——部署端离线时凭缓存副本持续可用(符合"不联网一直能用")。
|
||||
票据含 expiresAt(issuedAt + LICENSE_TTL_DAYS 天):执行机最多离线该天数,
|
||||
超时须联网刷新票据后才可继续使用(每次刷新重置窗口)。
|
||||
"""
|
||||
_check_token(x_api_token)
|
||||
if not account.strip():
|
||||
@@ -157,14 +112,19 @@ def me_license(account: str = Query(...), device: str = Query(default=""),
|
||||
"canDownload": bool(r["can_download"]), "canRun": bool(r["can_run"]),
|
||||
"status": r["status"], "latestVersion": r["latest_version"]}
|
||||
for r in rows]
|
||||
issued_at = _now()
|
||||
expires_at = int(time.time()) + config.LICENSE_TTL_DAYS * 24 * 3600
|
||||
blob = crypto._sign_blob({"userId": account.strip(), "deviceId": device or "",
|
||||
"issuedAt": _now(), "plugins": plugins})
|
||||
return {"ticket": blob, "plugins": plugins, "issuedAt": _now()}
|
||||
"issuedAt": issued_at, "expiresAt": expires_at, "plugins": plugins})
|
||||
return {"ticket": blob, "plugins": plugins, "issuedAt": issued_at, "expiresAt": expires_at}
|
||||
|
||||
|
||||
@router.get("/api/me/control-list")
|
||||
def me_control_list(x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""签发管控清单:下架(revoke)/禁用(disable)/强制更新(force-update)聚合,Ed25519 签名。"""
|
||||
"""签发管控清单:下架(revoke)/禁用(disable)/强制更新(force-update)聚合,Ed25519 签名。
|
||||
|
||||
与授权票据同窗口携带 expiresAt:执行机刷新票据时一并刷新管控清单。
|
||||
"""
|
||||
_check_token(x_api_token)
|
||||
revoked = []
|
||||
disabled = []
|
||||
@@ -181,7 +141,8 @@ def me_control_list(x_api_token: str = Header(default="", alias="X-API-Token"))
|
||||
forced.append({"pluginId": pid, "minVersion": r["force_min_version"],
|
||||
"deadline": r["force_deadline"]})
|
||||
payload = {"revokedPlugins": revoked, "disabledPlugins": disabled,
|
||||
"forcedUpdates": forced, "updatedAt": _now()}
|
||||
"forcedUpdates": forced, "updatedAt": _now(),
|
||||
"expiresAt": int(time.time()) + config.LICENSE_TTL_DAYS * 24 * 3600}
|
||||
return {"ticket": crypto._sign_blob(payload), "control": payload}
|
||||
|
||||
|
||||
@@ -296,16 +257,44 @@ def _shell_meta() -> dict:
|
||||
return {}
|
||||
|
||||
|
||||
def _shell_source_url() -> dict:
|
||||
"""优先取 file_sources 表 category='shell' 的启用记录(最新一条),返回含 url 的字典;
|
||||
无记录返回空 dict。大文件走内网文件服务器时,客户端据此直连下载。"""
|
||||
try:
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT version, filename, url, sha256, notes FROM file_sources "
|
||||
"WHERE category = 'shell' AND enabled = 1 ORDER BY id DESC LIMIT 1").fetchone()
|
||||
except Exception: # noqa: BLE001 DB 未就绪等,回退 version.json
|
||||
return {}
|
||||
if not row or not row.get("url"):
|
||||
return {}
|
||||
return {"version": row.get("version") or "", "filename": row.get("filename") or "",
|
||||
"url": row["url"], "sha256": row.get("sha256") or "",
|
||||
"notes": row.get("notes") or ""}
|
||||
|
||||
|
||||
@router.get("/api/shell/version")
|
||||
def shell_version(x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""壳子版本清单:执行端启动时比对,判断是否需要自动下载升级包。"""
|
||||
"""壳子版本清单:执行端启动时比对,判断是否需要自动下载升级包。
|
||||
|
||||
优先用 file_sources(category=shell) 的内网直链;未登记时回退 version.json。
|
||||
响应含 url:客户端据此直连内网文件服务器下载大包;url 为空则回退中心机 /api/shell/pkg。
|
||||
"""
|
||||
_check_token(x_api_token)
|
||||
m = _shell_meta()
|
||||
source = _shell_source_url()
|
||||
meta = _shell_meta()
|
||||
if source.get("url"):
|
||||
return {"available": True, "version": source.get("version") or meta.get("version", ""),
|
||||
"filename": source.get("filename") or meta.get("filename", ""),
|
||||
"url": source["url"], "sha256": source.get("sha256") or meta.get("sha256", ""),
|
||||
"notes": source.get("notes") or meta.get("notes", "")}
|
||||
m = meta
|
||||
if not m.get("version"):
|
||||
return {"available": False, "version": ""}
|
||||
return {"available": True, "version": str(m["version"]),
|
||||
"filename": m.get("filename", ""), "sha256": m.get("sha256", ""),
|
||||
"notes": m.get("notes", "")}
|
||||
"notes": m.get("notes", ""), "url": ""}
|
||||
|
||||
|
||||
@router.get("/api/shell/pkg")
|
||||
|
||||
@@ -29,7 +29,9 @@ from controlplane import config
|
||||
from controlplane.core.db import _init_db, _seed
|
||||
from controlplane.apis import admin as api_admin
|
||||
from controlplane.apis import auth as api_auth
|
||||
from controlplane.apis import config_push as api_config_push
|
||||
from controlplane.apis import dingtalk as api_dingtalk
|
||||
from controlplane.apis import file_sources as api_file_sources
|
||||
from controlplane.apis import meta as api_meta
|
||||
from controlplane.apis import plugins as api_plugins
|
||||
|
||||
@@ -48,6 +50,8 @@ app.add_middleware(CORSMiddleware, allow_origins=["*"],
|
||||
app.include_router(api_meta.router)
|
||||
app.include_router(api_plugins.router)
|
||||
app.include_router(api_auth.router)
|
||||
app.include_router(api_config_push.router)
|
||||
app.include_router(api_file_sources.router)
|
||||
app.include_router(api_dingtalk.router)
|
||||
app.include_router(api_admin.router)
|
||||
|
||||
|
||||
@@ -58,8 +58,7 @@ def _verify_admin_token(tok: str) -> str:
|
||||
|
||||
|
||||
def _require_admin(x_admin_token: str = "", x_api_token: str = "") -> str:
|
||||
"""管理操作:校验内部凭证(X-API-Token) + 登录票据(X-Admin-Token)对应账号 is_admin=1。返回账号。"""
|
||||
_check_token(x_api_token)
|
||||
"""管理操作:仅校验登录票据(X-Admin-Token)对应账号 is_admin=1(浏览器管理面免 X-API-Token)。返回账号。"""
|
||||
try:
|
||||
account = _verify_admin_token(x_admin_token)
|
||||
except Exception:
|
||||
@@ -78,11 +77,10 @@ def _resolve_login(x_admin_token: str = "", x_api_token: str = "",
|
||||
x_admin_user: str = "") -> str:
|
||||
"""解析请求身份(用户自助操作用,管理写操作仍走 _require_admin)。
|
||||
|
||||
1. 优先验签名票据 X-Admin-Token(控制台直连场景);
|
||||
1. 优先验签名票据 X-Admin-Token(控制台/浏览器直连场景,免 X-API-Token);
|
||||
2. 兜底接受底座正向代理注入的 X-Admin-User,但仅当 CONTROLPLANE_TOKEN 非空且
|
||||
请求携带匹配的 X-API-Token 时成立(防伪造;TOKEN 为空时拒绝,fail-closed)。
|
||||
"""
|
||||
_check_token(x_api_token)
|
||||
try:
|
||||
account = _verify_admin_token(x_admin_token)
|
||||
if account:
|
||||
@@ -149,4 +147,19 @@ def _cloud_account(bearer: str) -> str:
|
||||
return rec["account"]
|
||||
if rec: # 过期顺手清理,防内存无限增长
|
||||
_cloud_tokens.pop(token, None)
|
||||
return ""
|
||||
return ""
|
||||
|
||||
|
||||
def _issue_cloud_token(account: str, nickname: str) -> str:
|
||||
"""签发云端会话 token 并写入共享存储(与 _cloud_account 同源,供 apis/auth /auth/exchange 调用)。
|
||||
|
||||
之前 apis/auth 里另建了一份同名 dict,写读不通导致 Bearer 永远解不出账号;这里统一出口。
|
||||
"""
|
||||
token = secrets.token_urlsafe(32)
|
||||
now = time.time()
|
||||
with _cloud_lock:
|
||||
for k in [k for k, v in _cloud_tokens.items() if v["exp"] < now]:
|
||||
_cloud_tokens.pop(k, None)
|
||||
_cloud_tokens[token] = {"exp": now + _CLOUD_TOKEN_TTL, "account": account,
|
||||
"nickname": nickname}
|
||||
return token
|
||||
@@ -53,6 +53,8 @@ _load_dotenv()
|
||||
# 内部凭证(底座→统一后端的调用凭证)。为空则不强制(内网可信场景)。
|
||||
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
CONTROLPLANE_PORT = int(os.getenv("CONTROLPLANE_PORT", "8800"))
|
||||
# 离线授权票据有效期(天):执行机最多离线该天数,超时须联网刷新票据后才可继续使用。
|
||||
LICENSE_TTL_DAYS = 7
|
||||
# MySQL 数据层(控制面唯一存储,无 SQLite 回退)。连接参数在 controlplane/.env 配置。
|
||||
MYSQL_HOST = os.getenv("MYSQL_HOST", "")
|
||||
MYSQL_PORT = int(os.getenv("MYSQL_PORT", "3306"))
|
||||
@@ -70,6 +72,16 @@ DINGTALK_APP_SECRET = os.getenv("DINGTALK_APP_SECRET", "")
|
||||
# 只要与用户实际访问地址、钉钉后台登记的回调域名一致即可。留空禁用扫码。
|
||||
DINGTALK_CALLBACK = os.getenv("DINGTALK_CALLBACK", "").rstrip("/")
|
||||
|
||||
# 客户端敏感凭证默认值参考(webhost 不再明文落盘,中心机 .env 为唯一可信明文源)。
|
||||
# 明文源只由管理员经 /api/admin/creds/seed 录入;客户端 register 不再自动填充本默认值
|
||||
# (防任何登录账号借 register 自证拿到全局密钥),本配置保留供管理台 seed 时参考/未来使用。
|
||||
# 键名 = 下发白名单键(去掉 CREDS_ 前缀),留空则该键不下发,需管理员用 /api/admin/creds/seed 录入。
|
||||
CREDS_DEFAULT = {
|
||||
_k.removeprefix("CREDS_"): os.getenv(_k, "").strip()
|
||||
for _k in ("CREDS_DINGTALK_APPKEY", "CREDS_DINGTALK_APPSECRET",
|
||||
"CREDS_DINGTALK_AGENT_ID", "CREDS_DINGTALK_CORP_ID")
|
||||
}
|
||||
|
||||
# 管理台会话票据签名密钥:CONTROLPLANE_ADMIN_SECRET > CONTROLPLANE_TOKEN > 首次随机生成并
|
||||
# 持久化到 .admin_secret(保证重启不回退,杜绝凭用户名 X-Admin-User 直接伪造身份)。
|
||||
_ADMIN_SECRET_CANDIDATE = os.getenv("CONTROLPLANE_ADMIN_SECRET") or os.getenv("CONTROLPLANE_TOKEN") or ""
|
||||
|
||||
@@ -13,7 +13,10 @@ import json
|
||||
import secrets
|
||||
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import padding
|
||||
from cryptography.hazmat.primitives.asymmetric import rsa
|
||||
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
|
||||
from cryptography.hazmat.primitives import hashes
|
||||
|
||||
from controlplane.core import config
|
||||
|
||||
@@ -86,4 +89,22 @@ def _verify_blob(blob: str, pub: Ed25519PublicKey) -> dict:
|
||||
if len(sig) != 64:
|
||||
raise ValueError("bad signature len")
|
||||
pub.verify(sig, canon)
|
||||
return json.loads(canon)
|
||||
return json.loads(canon)
|
||||
|
||||
|
||||
# ==================== 执行机敏感凭证下发:RSA 加密 ====================
|
||||
def rsa_encrypt(pubkey_pem: str | bytes, plaintext: str) -> str:
|
||||
"""用执行机上报的 RSA 公钥加密敏感明文,返回 base64 密文串。
|
||||
|
||||
凭证值均为短串(口令/密钥),OAEP+SHA256 上限 ~190B(RSA-2048),已足够。
|
||||
供中心机下发 `/api/admin/creds` 时对每个敏感值加密使用。
|
||||
"""
|
||||
pem = pubkey_pem.encode() if isinstance(pubkey_pem, str) else pubkey_pem
|
||||
pub = serialization.load_pem_public_key(pem)
|
||||
if not isinstance(pub, rsa.RSAPublicKey):
|
||||
raise ValueError("pubkey 必须是 RSA 公钥")
|
||||
ct = pub.encrypt(
|
||||
plaintext.encode("utf-8"),
|
||||
padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
|
||||
algorithm=hashes.SHA256(), label=None))
|
||||
return base64.b64encode(ct).decode()
|
||||
@@ -19,7 +19,7 @@ from controlplane.core import config
|
||||
from controlplane.core.crypto import _hash_password
|
||||
|
||||
# 初始迁移版本:全量 DDL 建齐后登记;后续增量 DDL 在此追加新版本并配套迁移逻辑
|
||||
_SCHEMA_VERSION = "20260916_001"
|
||||
_SCHEMA_VERSION = "20260917_001"
|
||||
|
||||
# 全量 DDL(11 张表,MySQL 5.7 兼容;与 tools/schema_mysql.sql 逐条一致)
|
||||
_DDL_TABLES = (
|
||||
@@ -180,6 +180,30 @@ _DDL_TABLES = (
|
||||
PRIMARY KEY (`key`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='系统级键值配置'
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS client_creds (
|
||||
account VARCHAR(64) NOT NULL COMMENT '执行机账号(工号)',
|
||||
pubkey_pem TEXT NOT NULL COMMENT '该账号上报的 RSA 公钥(PEM)',
|
||||
creds MEDIUMTEXT NOT NULL COMMENT '敏感凭证密文 JSON:{key: base64(RSA 密文)},各值用 pubkey_pem 加密',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (account)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='执行机敏感凭证(中心机下发,RSA 加密)'
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS file_sources (
|
||||
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '自增ID',
|
||||
category VARCHAR(32) NOT NULL DEFAULT '' COMMENT '分类:shell/chrome/browser 等',
|
||||
version VARCHAR(32) NOT NULL DEFAULT '' COMMENT '版本号(对比/展示用,可选)',
|
||||
filename VARCHAR(255) NOT NULL DEFAULT '' COMMENT '原文件名',
|
||||
url TEXT NOT NULL COMMENT '内网文件服务器直链',
|
||||
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT 'sha256 校验值(可选,有则校验)',
|
||||
notes VARCHAR(512) NOT NULL DEFAULT '' COMMENT '说明',
|
||||
enabled TINYINT(1) NOT NULL DEFAULT 1 COMMENT '1=启用 0=停用',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_category (category)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='大文件源(内网直链,走内网文件服务器)'
|
||||
""",
|
||||
)
|
||||
|
||||
|
||||
@@ -260,9 +284,10 @@ def _init_db() -> None:
|
||||
with _db() as conn:
|
||||
for ddl in _DDL_TABLES:
|
||||
conn.execute(ddl)
|
||||
conn.execute(
|
||||
"INSERT IGNORE INTO schema_migrations(version) VALUES (%s)",
|
||||
(_SCHEMA_VERSION,))
|
||||
for _ver in ("20260916_001", _SCHEMA_VERSION):
|
||||
conn.execute(
|
||||
"INSERT IGNORE INTO schema_migrations(version) VALUES (%s)",
|
||||
(_ver,))
|
||||
conn.commit()
|
||||
|
||||
|
||||
|
||||
@@ -39,6 +39,18 @@ class AuthIn(BaseModel):
|
||||
password: str
|
||||
|
||||
|
||||
class CredsRegisterIn(BaseModel):
|
||||
"""执行机上报 RSA 公钥(一次注册后中心机用其加密敏感凭证下发)。"""
|
||||
account: str
|
||||
pubkey_pem: str
|
||||
|
||||
|
||||
class CredsSeedIn(BaseModel):
|
||||
"""管理员录入/更新某执行机账号的敏感凭证明文源(集中存中心机 DB)。"""
|
||||
account: str
|
||||
values: dict[str, str]
|
||||
|
||||
|
||||
class DingTalkIn(BaseModel):
|
||||
account: str # 工号(作为统一账号)
|
||||
nickname: str = ""
|
||||
|
||||
Binary file not shown.
@@ -30,7 +30,7 @@
|
||||
<aside class="aside">
|
||||
<div class="aside-inner">
|
||||
<el-menu :default-active="activeKey" @select="onMenu">
|
||||
<el-menu-item v-for="m in menuOptions" :key="m.key" :index="m.key">
|
||||
<el-menu-item v-for="m in menu" :key="m.key" :index="m.key">
|
||||
<el-icon><component :is="m.icon" /></el-icon>
|
||||
<span>{{ m.label }}</span>
|
||||
</el-menu-item>
|
||||
@@ -49,7 +49,7 @@
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { ArrowDown, Lock, SwitchButton, Odometer, TrendCharts, Box, User, Key, Document } from '@element-plus/icons-vue'
|
||||
import { ArrowDown, Lock, SwitchButton, Odometer, TrendCharts, Box, User, Key, Document, Files } from '@element-plus/icons-vue'
|
||||
import { ElMessage as message } from 'element-plus'
|
||||
import LoginPage from './components/LoginPage.vue'
|
||||
import PasswordDialog from './components/PasswordDialog.vue'
|
||||
@@ -59,6 +59,8 @@ import AccountManageView from './views/AccountManageView.vue'
|
||||
import GrantManageView from './views/GrantManageView.vue'
|
||||
import StatsView from './views/StatsView.vue'
|
||||
import AuditView from './views/AuditView.vue'
|
||||
import CredsManageView from './views/CredsManageView.vue'
|
||||
import FileSourceManageView from './views/FileSourceManageView.vue'
|
||||
import { store, clearSession } from './store'
|
||||
import { adminMe } from './api'
|
||||
|
||||
@@ -68,8 +70,11 @@ const menuOptions = [
|
||||
{ label: '插件管理', key: 'plugins', icon: Box },
|
||||
{ label: '账号管理', key: 'accounts', icon: User },
|
||||
{ label: '权限授权', key: 'grants', icon: Key },
|
||||
{ label: '敏感凭证', key: 'creds', icon: Lock, admin: true },
|
||||
{ label: '大文件源', key: 'files', icon: Files, admin: true },
|
||||
{ label: '审计报表', key: 'audit', icon: Document },
|
||||
]
|
||||
const menu = computed(() => menuOptions.filter(m => !m.admin || store.isAdmin))
|
||||
|
||||
// 轻量 hash 路由:静态站刷新安全,零后端改动
|
||||
const KEY = {
|
||||
@@ -78,6 +83,8 @@ const KEY = {
|
||||
'#/plugins': 'plugins',
|
||||
'#/accounts': 'accounts',
|
||||
'#/grants': 'grants',
|
||||
'#/creds': 'creds',
|
||||
'#/files': 'files',
|
||||
'#/audit': 'audit',
|
||||
}
|
||||
const VIEWS = {
|
||||
@@ -86,6 +93,8 @@ const VIEWS = {
|
||||
'#/plugins': PluginManageView,
|
||||
'#/accounts': AccountManageView,
|
||||
'#/grants': GrantManageView,
|
||||
'#/creds': CredsManageView,
|
||||
'#/files': FileSourceManageView,
|
||||
'#/audit': AuditView,
|
||||
}
|
||||
const route = ref(VIEWS[location.hash] ? location.hash : '#/overview')
|
||||
|
||||
@@ -5,7 +5,17 @@ async function req(url, opts) {
|
||||
const res = await fetch(url, opts)
|
||||
if (!res.ok) {
|
||||
let msg = `HTTP ${res.status}`
|
||||
try { msg = (await res.json()).detail || msg } catch (_) {}
|
||||
try {
|
||||
const detail = (await res.json()).detail
|
||||
// FastAPI 422 的 detail 是 [{loc,msg,type},…] 数组;普通错误是字符串/含 msg 的对象
|
||||
if (typeof detail === 'string') msg = detail
|
||||
else if (Array.isArray(detail)) {
|
||||
msg = detail.map((d) => {
|
||||
const where = Array.isArray(d.loc) ? d.loc.filter((p) => p !== 'body').join('.') : ''
|
||||
return where ? `${where}: ${d.msg}` : (d.msg || JSON.stringify(d))
|
||||
}).join(';')
|
||||
} else if (detail && typeof detail === 'object') msg = detail.msg || JSON.stringify(detail)
|
||||
} catch (_) { /* 非 JSON 响应,保留 HTTP 状态码提示 */ }
|
||||
throw new Error(msg)
|
||||
}
|
||||
return res.json()
|
||||
@@ -114,6 +124,40 @@ export async function adminReports(limit = 300) {
|
||||
export async function adminStats() {
|
||||
return req('/api/admin/stats', { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminCredsList() {
|
||||
return req('/api/admin/creds/manage', { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminCredsSeed(body) {
|
||||
return req('/api/admin/creds/seed', {
|
||||
method: 'POST',
|
||||
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify(body)
|
||||
})
|
||||
}
|
||||
export async function adminFileSources(category = '') {
|
||||
const qs = category ? '?category=' + encodeURIComponent(category) : ''
|
||||
return req('/api/admin/file-sources' + qs, { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminFileSourceCreate(body) {
|
||||
return req('/api/admin/file-sources', {
|
||||
method: 'POST',
|
||||
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify(body)
|
||||
})
|
||||
}
|
||||
export async function adminFileSourcePatch(id, body) {
|
||||
return req(`/api/admin/file-sources/${id}`, {
|
||||
method: 'PATCH',
|
||||
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify(body)
|
||||
})
|
||||
}
|
||||
export async function adminFileSourceDelete(id) {
|
||||
return req(`/api/admin/file-sources/${id}`, {
|
||||
method: 'DELETE',
|
||||
headers: adminHeaders({ 'Content-Type': 'application/json' })
|
||||
})
|
||||
}
|
||||
export async function adminUpload(pluginId, name, version, file) {
|
||||
const fd = new FormData()
|
||||
fd.append('upload', file)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createApp } from 'vue'
|
||||
import ElementPlus from 'element-plus'
|
||||
import 'element-plus/dist/index.css'
|
||||
import zhCn from 'element-plus/es/locale/lang/zh-cn'
|
||||
// 图标沿用 @element-plus/icons-vue(纯 SVG 组件)
|
||||
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
|
||||
import App from './App.vue'
|
||||
@@ -11,4 +12,5 @@ const app = createApp(App)
|
||||
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
|
||||
app.component(key, component)
|
||||
}
|
||||
app.use(ElementPlus).mount('#app')
|
||||
// 中文语言包:日期选择器等组件的月份/按钮文案默认是英文,必须显式指定 locale
|
||||
app.use(ElementPlus, { locale: zhCn }).mount('#app')
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<div class="page-head cp-rise">
|
||||
<div>
|
||||
<h3>敏感凭证 <span class="badge">Creds</span></h3>
|
||||
<p>执行机敏感凭证的明文源(钉钉开放平台)。保存后客户端下次启动用 RSA 私钥解密拉取;留空 = 该键不下发</p>
|
||||
</div>
|
||||
<el-button :loading="busy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
</div>
|
||||
|
||||
<div class="cp-card panel cp-rise">
|
||||
<el-table :data="rows" v-loading="busy" size="default" style="width: 100%">
|
||||
<el-table-column prop="account" label="执行机账号" width="150">
|
||||
<template #default="{ row }">
|
||||
<span class="mono">{{ row.account }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="公钥" width="90">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="row.has_pubkey ? 'success' : 'info'" size="small" effect="light">
|
||||
{{ row.has_pubkey ? '已上报' : '未上报' }}
|
||||
</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column v-for="k in keyCols" :key="k.key" :label="k.label" min-width="170" show-overflow-tooltip>
|
||||
<template #default="{ row }">
|
||||
<span class="mono dim" :class="{ empty: !row.creds[k.key] }">{{ row.creds[k.key] || '(未配置)' }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="updated_at" label="更新时间" width="170" />
|
||||
<el-table-column label="操作" width="90" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<el-button link type="primary" :icon="EditPen" @click="openEdit(row)">编辑</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<template #empty>
|
||||
<el-empty description="暂无账号,客户端启动注册后自动出现" :image-size="80" />
|
||||
</template>
|
||||
</el-table>
|
||||
</div>
|
||||
|
||||
<el-dialog v-model="dlg" :title="`编辑凭证 · ${editing?.account || ''}`" width="540px">
|
||||
<div class="form">
|
||||
<div class="fitem" v-for="k in keyCols" :key="k.key">
|
||||
<label>{{ k.label }} <span class="dim mono">({{ k.key }})</span></label>
|
||||
<el-input v-model="form[k.key]" :type="k.key.includes('SECRET') ? 'password' : 'text'"
|
||||
:show-password="k.key.includes('SECRET')" placeholder="留空 = 不下发该键" />
|
||||
</div>
|
||||
<p class="tip">值仅管理台可见;保存后客户端下次启动拉取更新(离线用本地加密缓存)。</p>
|
||||
</div>
|
||||
<template #footer>
|
||||
<el-button @click="dlg = false">取消</el-button>
|
||||
<el-button type="primary" :loading="saving" @click="save">保存</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { Refresh, EditPen } from '@element-plus/icons-vue'
|
||||
import { ElMessage as message } from 'element-plus'
|
||||
import { adminCredsList, adminCredsSeed } from '../api'
|
||||
|
||||
const KEY_COLS = [
|
||||
{ key: 'DINGTALK_APPKEY', label: 'AppKey' },
|
||||
{ key: 'DINGTALK_APPSECRET', label: 'AppSecret' },
|
||||
{ key: 'DINGTALK_AGENT_ID', label: 'AgentId' },
|
||||
{ key: 'DINGTALK_CORP_ID', label: 'CorpId' },
|
||||
]
|
||||
|
||||
const keyCols = KEY_COLS
|
||||
const busy = ref(false)
|
||||
const rows = ref([])
|
||||
const dlg = ref(false)
|
||||
const saving = ref(false)
|
||||
const editing = ref(null)
|
||||
const form = ref({})
|
||||
|
||||
async function refresh() {
|
||||
busy.value = true
|
||||
try {
|
||||
const r = await adminCredsList()
|
||||
rows.value = r.accounts || []
|
||||
} catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
finally { busy.value = false }
|
||||
}
|
||||
|
||||
function openEdit(row) {
|
||||
editing.value = row
|
||||
form.value = {}
|
||||
keyCols.forEach(c => { form.value[c.key] = row.creds?.[c.key] || '' })
|
||||
dlg.value = true
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (!editing.value) return
|
||||
saving.value = true
|
||||
try {
|
||||
const values = {}
|
||||
keyCols.forEach(c => { if (form.value[c.key]) values[c.key] = String(form.value[c.key]).trim() })
|
||||
const r = await adminCredsSeed({ account: editing.value.account, values })
|
||||
message.success(`已保存 ${r.seeded_keys.length} 个键(留空键已清除)`)
|
||||
dlg.value = false
|
||||
await refresh()
|
||||
} catch (e) { message.error('保存失败:' + (e.message || e)) }
|
||||
finally { saving.value = false }
|
||||
}
|
||||
|
||||
onMounted(refresh)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.panel { padding: 22px 24px 26px; }
|
||||
.form { display: flex; flex-direction: column; gap: 16px; }
|
||||
.fitem { display: flex; flex-direction: column; gap: 7px; }
|
||||
.fitem label { font-size: 13px; font-weight: 700; color: var(--cp-ink-1); }
|
||||
.fitem .dim { font-weight: 500; font-size: 12px; }
|
||||
.empty { color: var(--cp-ink-3); }
|
||||
.tip { font-size: 12px; color: var(--cp-ink-3); margin: 2px 0 0; }
|
||||
</style>
|
||||
@@ -0,0 +1,186 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<div class="page-head cp-rise">
|
||||
<div>
|
||||
<h3>大文件源 <span class="badge">File Sources</span></h3>
|
||||
<p>内网大文件(壳子/Chrome 等)直链登记。中心机只存链接,文件本身走内网文件服务器</p>
|
||||
</div>
|
||||
<div class="head-actions">
|
||||
<el-select v-model="filter" placeholder="按分类过滤" style="width: 150px" clearable @change="refresh">
|
||||
<el-option v-for="c in categories" :key="c" :label="c" :value="c" />
|
||||
</el-select>
|
||||
<el-button :loading="busy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
<el-button type="primary" :icon="Plus" @click="openCreate">登记链接</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="cp-card panel cp-rise">
|
||||
<el-table :data="rows" v-loading="busy" size="default" style="width: 100%">
|
||||
<el-table-column prop="category" label="分类" width="110">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="catType(row.category)" size="small" effect="light">{{ row.category }}</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="version" label="版本" width="90">
|
||||
<template #default="{ row }"><span class="mono">{{ row.version }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="filename" label="文件" min-width="150" show-overflow-tooltip />
|
||||
<el-table-column label="内网直链" min-width="260" show-overflow-tooltip>
|
||||
<template #default="{ row }">
|
||||
<span class="mono dim url">{{ row.url }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="SHA256" width="120">
|
||||
<template #default="{ row }">
|
||||
<el-button v-if="row.sha256" link type="primary" @click="copy(row.sha256, 'SHA256')">
|
||||
{{ row.sha256.slice(0, 8) }}…
|
||||
</el-button>
|
||||
<span v-else class="dim">—</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="说明" min-width="140" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ row.notes || '—' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="updated_at" label="更新时间" width="160" />
|
||||
<el-table-column label="启用" width="70" align="center">
|
||||
<template #default="{ row }">
|
||||
<el-switch :model-value="!!row.enabled" :loading="row._tog" @change="(v) => toggle(row, v)" />
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="130" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<el-button link type="primary" @click="copy(row.url, '链接')">复制</el-button>
|
||||
<el-button link type="danger" :icon="Delete" @click="remove(row)">删除</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<template #empty>
|
||||
<el-empty description="暂无登记的大文件源" :image-size="80" />
|
||||
</template>
|
||||
</el-table>
|
||||
</div>
|
||||
|
||||
<el-dialog v-model="dlg" title="登记内网直链" width="560px">
|
||||
<div class="form">
|
||||
<div class="fitem">
|
||||
<label>分类 <span class="dim">(shell / chrome / …)</span></label>
|
||||
<el-input v-model="form.category" placeholder="如 chrome" />
|
||||
</div>
|
||||
<div class="fitem">
|
||||
<label>版本</label>
|
||||
<el-input v-model="form.version" placeholder="如 1.0.0" />
|
||||
</div>
|
||||
<div class="fitem">
|
||||
<label>文件名</label>
|
||||
<el-input v-model="form.filename" placeholder="如 ChromeStandaloneSetup64.exe" />
|
||||
</div>
|
||||
<div class="fitem">
|
||||
<label>内网直链 url</label>
|
||||
<el-input v-model="form.url" placeholder="http://内网IP:8802/files/..." />
|
||||
</div>
|
||||
<div class="fitem">
|
||||
<label>SHA256 <span class="dim">(可选)</span></label>
|
||||
<el-input v-model="form.sha256" placeholder="文件校验值,客户端下载后校验" />
|
||||
</div>
|
||||
<div class="fitem">
|
||||
<label>说明 <span class="dim">(可选)</span></label>
|
||||
<el-input v-model="form.notes" type="textarea" :rows="2" placeholder="备注" />
|
||||
</div>
|
||||
<p class="tip">同一 分类+版本 会覆盖旧记录;删除仅移除中心机登记,不影响内网文件服务器上的文件。</p>
|
||||
</div>
|
||||
<template #footer>
|
||||
<el-button @click="dlg = false">取消</el-button>
|
||||
<el-button type="primary" :loading="saving" @click="save">保存</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { Refresh, Plus, Delete } from '@element-plus/icons-vue'
|
||||
import { ElMessage as message, ElMessageBox } from 'element-plus'
|
||||
import { adminFileSources, adminFileSourceCreate, adminFileSourcePatch, adminFileSourceDelete } from '../api'
|
||||
|
||||
const CATS = ['shell', 'chrome']
|
||||
const categories = CATS
|
||||
const busy = ref(false)
|
||||
const rows = ref([])
|
||||
const filter = ref('')
|
||||
const dlg = ref(false)
|
||||
const saving = ref(false)
|
||||
const form = ref({})
|
||||
|
||||
async function refresh() {
|
||||
busy.value = true
|
||||
try {
|
||||
const r = await adminFileSources(filter.value || '')
|
||||
rows.value = r.files || []
|
||||
const seen = new Set(CATS)
|
||||
;(r.files || []).forEach((f) => seen.add(f.category))
|
||||
categories.length = 0
|
||||
;[...seen].sort().forEach((c) => categories.push(c))
|
||||
} catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
finally { busy.value = false }
|
||||
}
|
||||
|
||||
function catType(c) {
|
||||
return { shell: 'success', chrome: 'warning' }[c] || 'info'
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
form.value = { category: '', version: '', filename: '', url: '', sha256: '', notes: '', enabled: true }
|
||||
dlg.value = true
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (!form.value.category || !form.value.category.trim()) return message.error('分类不能为空')
|
||||
if (!form.value.url || !form.value.url.trim()) return message.error('内网直链不能为空')
|
||||
saving.value = true
|
||||
try {
|
||||
const { enabled, ...rest } = form.value
|
||||
const body = { ...rest, category: form.value.category.trim(), url: form.value.url.trim(), enabled: true }
|
||||
await adminFileSourceCreate(body)
|
||||
message.success('已登记')
|
||||
dlg.value = false
|
||||
await refresh()
|
||||
} catch (e) { message.error('保存失败:' + (e.message || e)) }
|
||||
finally { saving.value = false }
|
||||
}
|
||||
|
||||
async function toggle(row, v) {
|
||||
row._tog = true
|
||||
try { await adminFileSourcePatch(row.id, { enabled: v }); row.enabled = v; message.success(v ? '已启用' : '已停用') }
|
||||
catch (e) { message.error('操作失败:' + (e.message || e)) }
|
||||
finally { row._tog = false }
|
||||
}
|
||||
|
||||
async function remove(row) {
|
||||
try {
|
||||
await ElMessageBox.confirm(`删除「${row.category} ${row.version}」的登记?此操作仅移除中心机登记,不影响内网文件。`, '确认删除', { type: 'warning' })
|
||||
} catch (_) { return }
|
||||
try {
|
||||
await adminFileSourceDelete(row.id)
|
||||
message.success('已删除')
|
||||
await refresh()
|
||||
} catch (e) { message.error('删除失败:' + (e.message || e)) }
|
||||
}
|
||||
|
||||
async function copy(text, what) {
|
||||
try { await navigator.clipboard.writeText(text); message.success(what + '已复制') }
|
||||
catch (_) { message.error('复制失败,请手动选择') }
|
||||
}
|
||||
|
||||
onMounted(refresh)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.panel { padding: 22px 24px 26px; }
|
||||
.head-actions { display: flex; gap: 10px; align-items: center; }
|
||||
.form { display: flex; flex-direction: column; gap: 14px; }
|
||||
.fitem { display: flex; flex-direction: column; gap: 6px; }
|
||||
.fitem label { font-size: 13px; font-weight: 700; color: var(--cp-ink-1); }
|
||||
.fitem .dim { font-weight: 500; font-size: 12px; }
|
||||
.dim { color: var(--cp-ink-3); }
|
||||
.url { font-size: 12px; }
|
||||
.tip { font-size: 12px; color: var(--cp-ink-3); margin: 0; }
|
||||
</style>
|
||||
@@ -73,88 +73,136 @@
|
||||
</div>
|
||||
|
||||
<!-- 编辑插件 -->
|
||||
<el-dialog v-model="editShow" :title="`编辑插件 · ${edit.pid}`" width="560px" align-center destroy-on-close>
|
||||
<el-form label-position="top">
|
||||
<el-form-item label="名称">
|
||||
<el-input v-model="edit.name" placeholder="插件显示名" />
|
||||
</el-form-item>
|
||||
<el-form-item label="分类">
|
||||
<el-input v-model="edit.category" placeholder="如 薪酬 / 考勤 / 社保" />
|
||||
</el-form-item>
|
||||
<el-form-item label="描述">
|
||||
<el-input v-model="edit.description" type="textarea" :rows="2" placeholder="插件用途说明" />
|
||||
</el-form-item>
|
||||
<el-form-item label="状态">
|
||||
<el-radio-group v-model="edit.status">
|
||||
<el-radio-button value="published">正常发布</el-radio-button>
|
||||
<el-radio-button value="disabled">禁用(停止分发)</el-radio-button>
|
||||
<el-radio-button value="revoked">下架(禁止运行)</el-radio-button>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
<el-form-item label="强制更新(留空表示不强制)">
|
||||
<div class="force-row">
|
||||
<div class="force-line">
|
||||
<el-input v-model="edit.force_min" placeholder="最低版本,如 1.2.0" style="width: 180px" class="mono" />
|
||||
<el-input v-model="edit.force_dl" type="datetime-local" placeholder="截止时间" style="width: 200px" class="mono" />
|
||||
</div>
|
||||
<span class="hint">到达截止时间后,未升级到该版本的部署机会被禁止启动</span>
|
||||
<el-dialog v-model="editShow" width="720px" align-center destroy-on-close>
|
||||
<template #header>
|
||||
<div class="ed-head">
|
||||
<span class="ed-avatar">{{ (edit.name || edit.pid || '?').slice(0, 1) }}</span>
|
||||
<div class="ed-headmeta">
|
||||
<div class="ed-title mono">{{ edit.pid }}</div>
|
||||
<div class="ed-sub">修改基础信息、发布状态与强制更新策略</div>
|
||||
</div>
|
||||
</el-form-item>
|
||||
</div>
|
||||
</template>
|
||||
<el-form label-position="top" class="ed-form">
|
||||
<div class="ed-sec">
|
||||
<div class="ed-sec-title">基本信息</div>
|
||||
<div class="form-2col">
|
||||
<el-form-item label="插件名称">
|
||||
<el-input v-model="edit.name" placeholder="插件显示名" />
|
||||
</el-form-item>
|
||||
<el-form-item label="分类">
|
||||
<el-input v-model="edit.category" placeholder="如 薪酬 / 考勤 / 社保" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
</div>
|
||||
<div class="ed-sec">
|
||||
<div class="ed-sec-title">插件描述</div>
|
||||
<el-form-item>
|
||||
<el-input v-model="edit.description" type="textarea" :autosize="{ minRows: 5, maxRows: 12 }"
|
||||
maxlength="500" show-word-limit placeholder="插件用途说明(支持换行,执行端与详情页均会展示)" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="ed-sec">
|
||||
<div class="ed-sec-title">发布状态</div>
|
||||
<el-form-item>
|
||||
<el-radio-group v-model="edit.status">
|
||||
<el-radio-button value="published">正常发布</el-radio-button>
|
||||
<el-radio-button value="disabled">禁用(停止分发)</el-radio-button>
|
||||
<el-radio-button value="revoked">下架(禁止运行)</el-radio-button>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="ed-sec">
|
||||
<div class="ed-sec-title">强制更新 <span class="ed-opt">可选 · 两项都填才会生效</span></div>
|
||||
<div class="force-box">
|
||||
<div class="force-line">
|
||||
<el-input v-model="edit.force_min" placeholder="最低版本,如 1.2.0" style="width: 190px" class="mono" />
|
||||
<el-date-picker v-model="edit.force_dl" type="datetime" value-format="YYYY-MM-DD[T]HH:mm"
|
||||
format="YYYY-MM-DD HH:mm" placeholder="截止时间" style="width: 220px" class="mono" />
|
||||
</div>
|
||||
<div class="hint">到达截止时间后,未升级到该版本的部署机会被禁止启动;留空表示不强制</div>
|
||||
</div>
|
||||
</div>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<div class="modal-foot">
|
||||
<el-button @click="editShow = false">取消</el-button>
|
||||
<el-button type="primary" :loading="saving" @click="saveEdit">保存</el-button>
|
||||
<el-button type="primary" :loading="saving" @click="saveEdit">保存修改</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<!-- 插件详情 -->
|
||||
<el-dialog v-model="detailShow" :title="`插件详情 · ${detail?.id || ''}`" width="640px" align-center destroy-on-close>
|
||||
<el-dialog v-model="detailShow" width="780px" align-center destroy-on-close>
|
||||
<template #header>
|
||||
<div class="dt-head" v-if="detail">
|
||||
<span class="dt-avatar">{{ (detail.name || detail.id || '?').slice(0, 1) }}</span>
|
||||
<div class="dt-headmeta">
|
||||
<div class="dt-title-row">
|
||||
<span class="dt-id mono">{{ detail.id }}</span>
|
||||
<el-tag size="small" round effect="light" :type="statusMeta[detail.status]?.type || 'info'">
|
||||
{{ statusMeta[detail.status]?.label || detail.status || '—' }}
|
||||
</el-tag>
|
||||
<el-tag v-if="detail.category" size="small" round effect="plain" type="info">{{ detail.category }}</el-tag>
|
||||
</div>
|
||||
<div class="dt-name">{{ detail.name || '未命名插件' }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<div v-if="detail" class="plg-detail">
|
||||
<div class="d-head">
|
||||
<span class="d-id mono">{{ detail.id }}</span>
|
||||
<span class="d-name">{{ detail.name }}</span>
|
||||
<el-tag size="small" round effect="light" :type="statusMeta[detail.status]?.type || 'info'">
|
||||
{{ statusMeta[detail.status]?.label || detail.status || '—' }}
|
||||
</el-tag>
|
||||
<div class="dt-grid">
|
||||
<div class="dt-item">
|
||||
<el-icon class="dt-ic"><Box /></el-icon>
|
||||
<div><label>最新版本</label><span class="mono">{{ detail.latest_version || '—' }}</span></div>
|
||||
</div>
|
||||
<div class="dt-item">
|
||||
<el-icon class="dt-ic"><Files /></el-icon>
|
||||
<div><label>表单字段</label><span class="mono">{{ detail.field_count || 0 }} 项</span></div>
|
||||
</div>
|
||||
<div class="dt-item">
|
||||
<el-icon class="dt-ic"><User /></el-icon>
|
||||
<div><label>授权账号</label><span class="mono">{{ detail.accounts?.length || 0 }} 个</span></div>
|
||||
</div>
|
||||
<div class="dt-item">
|
||||
<el-icon class="dt-ic" :class="{ 'dt-ic-on': detail.force_min_version && detail.force_deadline }"><Clock /></el-icon>
|
||||
<div><label>强制更新</label><span>{{ forceText(detail) }}</span></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="d-grid">
|
||||
<div class="d-item"><label>分类</label><span>{{ detail.category || '—' }}</span></div>
|
||||
<div class="d-item"><label>最新版本</label><span class="mono">{{ detail.latest_version || '—' }}</span></div>
|
||||
<div class="d-item"><label>表单字段</label><span class="mono">{{ detail.field_count || 0 }}</span></div>
|
||||
<div class="d-item"><label>强制更新</label><span>{{ forceText(detail) }}</span></div>
|
||||
<div class="dt-sec">
|
||||
<div class="ed-sec-title">插件描述</div>
|
||||
<p class="dt-desc">{{ detail.description || '暂无描述' }}</p>
|
||||
</div>
|
||||
|
||||
<div class="d-sec"><label>描述</label><p class="d-desc">{{ detail.description || '—' }}</p></div>
|
||||
|
||||
<div class="d-sec">
|
||||
<label>能力</label>
|
||||
<div class="dt-sec">
|
||||
<div class="ed-sec-title">能力声明</div>
|
||||
<div class="tags" v-if="detail.capabilities?.length">
|
||||
<el-tag v-for="c in detail.capabilities" :key="c" size="small" effect="plain" round>{{ c }}</el-tag>
|
||||
<el-tag v-for="c in detail.capabilities" :key="c" size="small" effect="plain" round class="mono">{{ c }}</el-tag>
|
||||
</div>
|
||||
<span v-else class="dim">—</span>
|
||||
</div>
|
||||
|
||||
<div class="d-sec">
|
||||
<label>版本历史</label>
|
||||
<div class="vlist" v-if="detail.versions?.length">
|
||||
<div class="vrow" v-for="v in detail.versions" :key="v.version">
|
||||
<el-tag size="small" round effect="light" class="mono"
|
||||
:type="v.version === detail.latest_version ? 'primary' : 'info'">{{ v.version }}</el-tag>
|
||||
<span class="vtime mono dim-sm">{{ fmtTime(v.uploaded_at) }}</span>
|
||||
<div class="dt-cols">
|
||||
<div class="dt-sec">
|
||||
<div class="ed-sec-title">版本历史</div>
|
||||
<div class="vlist" v-if="detail.versions?.length">
|
||||
<div class="vrow" v-for="v in detail.versions" :key="v.version">
|
||||
<el-tag size="small" round effect="light" class="mono"
|
||||
:type="v.version === detail.latest_version ? 'primary' : 'info'">{{ v.version }}</el-tag>
|
||||
<el-tag v-if="v.version === detail.latest_version" size="small" round effect="plain"
|
||||
type="success" class="v-latest">当前</el-tag>
|
||||
<span class="vtime mono dim-sm">{{ fmtTime(v.uploaded_at) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<span v-else class="dim">暂无版本</span>
|
||||
</div>
|
||||
<span v-else class="dim">暂无版本</span>
|
||||
</div>
|
||||
|
||||
<div class="d-sec">
|
||||
<label>授权账号</label>
|
||||
<div class="tags" v-if="detail.accounts?.length">
|
||||
<el-tag v-for="a in detail.accounts" :key="a" size="small" effect="plain" type="success" round class="mono">{{ a }}</el-tag>
|
||||
<div class="dt-sec">
|
||||
<div class="ed-sec-title">授权账号</div>
|
||||
<div class="tags" v-if="detail.accounts?.length">
|
||||
<el-tag v-for="a in detail.accounts" :key="a" size="small" effect="plain" type="success" round class="mono">{{ a }}</el-tag>
|
||||
</div>
|
||||
<span v-else class="dim">未授权任何账号,执行端不可见</span>
|
||||
</div>
|
||||
<span v-else class="dim">未授权</span>
|
||||
</div>
|
||||
</div>
|
||||
<template #footer>
|
||||
@@ -167,7 +215,7 @@
|
||||
<script setup>
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { ElMessage as message, ElMessageBox as dialog } from 'element-plus'
|
||||
import { Refresh, UploadFilled, FolderOpened, Edit, Delete, View } from '@element-plus/icons-vue'
|
||||
import { Refresh, UploadFilled, FolderOpened, Edit, Delete, View, Box, Files, User, Clock } from '@element-plus/icons-vue'
|
||||
import { overview, overviewBusy, loadOverview } from '../store'
|
||||
import { adminUpload, adminPluginDelete, adminPluginPatch } from '../api'
|
||||
import { fmtTime } from '../format'
|
||||
@@ -225,9 +273,10 @@ async function saveEdit() {
|
||||
saving.value = true
|
||||
try {
|
||||
const body = { name: edit.name, category: edit.category, description: edit.description, status: edit.status }
|
||||
// 强制更新:min 与 deadline 均填则成对下发;否则清除强制更新
|
||||
body.force_min_version = edit.force_min || null
|
||||
body.force_deadline = edit.force_dl ? new Date(edit.force_dl).toISOString() : null
|
||||
// 强制更新:min 与 deadline 均填则成对下发;否则清除强制更新。
|
||||
// 注意:后端 PluginPatchIn 的 str 字段不接受 null,空值必须传 ''(否则 422 保存失败)
|
||||
body.force_min_version = edit.force_min || ''
|
||||
body.force_deadline = edit.force_dl ? new Date(edit.force_dl).toISOString() : ''
|
||||
body.clear_force = !(edit.force_min && edit.force_dl)
|
||||
await adminPluginPatch(edit.pid, body)
|
||||
message.success(`已更新插件 ${edit.pid}`)
|
||||
@@ -271,27 +320,53 @@ onMounted(refresh)
|
||||
.up-form :deep(.el-form-item) { margin-bottom: 16px; }
|
||||
.file-row { display: flex; align-items: center; gap: 10px; }
|
||||
.hint { font-size: 12px; color: var(--cp-ink-3); margin-top: 2px; line-height: 1.7; }
|
||||
.force-row { display: flex; flex-direction: column; gap: 8px; width: 100%; }
|
||||
.force-line { display: flex; gap: 10px; }
|
||||
.modal-foot { display: flex; justify-content: flex-end; gap: 10px; }
|
||||
.cell-ops { display: flex; align-items: center; gap: 6px; white-space: nowrap; }
|
||||
.cell-ops .el-button { padding: 0 4px; }
|
||||
.cell-ops .el-button + .el-button { margin-left: 0; }
|
||||
|
||||
/* 插件详情 */
|
||||
.plg-detail { display: flex; flex-direction: column; gap: 18px; }
|
||||
.d-head { display: flex; align-items: center; gap: 10px; }
|
||||
.d-id { font-size: 16px; font-weight: 800; color: var(--cp-ink-1); }
|
||||
.d-name { font-size: 15px; color: var(--cp-ink-2); flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.d-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; }
|
||||
.d-item { display: flex; flex-direction: column; gap: 5px; padding: 12px 14px; background: var(--cp-panel-2); border-radius: 12px; }
|
||||
.d-item label { font-size: 11px; font-weight: 700; color: var(--cp-ink-3); letter-spacing: .4px; }
|
||||
.d-item span { font-size: 13px; font-weight: 600; color: var(--cp-ink-1); }
|
||||
.d-sec { display: flex; flex-direction: column; gap: 8px; }
|
||||
.d-sec > label { font-size: 11px; font-weight: 700; color: var(--cp-ink-3); letter-spacing: .4px; }
|
||||
.d-desc { margin: 0; font-size: 13px; line-height: 1.7; color: var(--cp-ink); background: var(--cp-panel-2); padding: 10px 14px; border-radius: 10px; }
|
||||
.vlist { display: flex; flex-direction: column; gap: 6px; }
|
||||
.vrow { display: flex; align-items: center; gap: 12px; }
|
||||
.vtime { font-size: 12px; }
|
||||
/* 弹窗通用 */
|
||||
.modal-foot { display: flex; justify-content: flex-end; gap: 10px; }
|
||||
.form-2col { display: grid; grid-template-columns: 1fr 1fr; gap: 0 16px; }
|
||||
.hint { font-size: 12px; color: var(--cp-ink-3); line-height: 1.7; }
|
||||
|
||||
/* 编辑弹窗:分区卡片 */
|
||||
.ed-head { display: flex; align-items: center; gap: 12px; }
|
||||
.ed-avatar { width: 42px; height: 42px; border-radius: 12px; display: grid; place-items: center; color: #fff; font-size: 18px; font-weight: 800; background: linear-gradient(135deg, var(--cp-blue), var(--cp-teal)); box-shadow: var(--cp-shadow); flex-shrink: 0; }
|
||||
.ed-headmeta { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
|
||||
.ed-title { font-size: 15px; font-weight: 800; color: var(--cp-ink-1); }
|
||||
.ed-sub { font-size: 12px; color: var(--cp-ink-3); }
|
||||
.ed-sec { margin-bottom: 12px; padding: 13px 16px 3px; background: var(--cp-panel-2); border-radius: 12px; }
|
||||
.ed-sec :deep(.el-form-item) { margin-bottom: 13px; }
|
||||
.ed-sec-title { display: flex; align-items: center; gap: 8px; font-size: 12px; font-weight: 800; color: var(--cp-ink-2); letter-spacing: .5px; margin-bottom: 10px; }
|
||||
.ed-sec-title::before { content: ''; width: 3px; height: 13px; border-radius: 2px; background: var(--cp-blue); }
|
||||
.ed-opt { font-weight: 500; color: var(--cp-ink-3); letter-spacing: 0; }
|
||||
.force-box { display: flex; flex-direction: column; gap: 8px; padding-bottom: 13px; }
|
||||
.force-line { display: flex; gap: 10px; }
|
||||
|
||||
/* 详情弹窗:头部 + 统计卡 + 分区 */
|
||||
.plg-detail { display: flex; flex-direction: column; gap: 14px; max-height: 66vh; overflow-y: auto; padding-right: 6px; }
|
||||
.dt-head { display: flex; align-items: center; gap: 12px; }
|
||||
.dt-avatar { width: 46px; height: 46px; border-radius: 13px; display: grid; place-items: center; color: #fff; font-size: 20px; font-weight: 800; background: linear-gradient(135deg, var(--cp-blue), var(--cp-teal)); box-shadow: var(--cp-shadow); flex-shrink: 0; }
|
||||
.dt-headmeta { display: flex; flex-direction: column; gap: 3px; min-width: 0; }
|
||||
.dt-title-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
.dt-id { font-size: 15px; font-weight: 800; color: var(--cp-ink-1); }
|
||||
.dt-name { font-size: 13px; color: var(--cp-ink-2); }
|
||||
.dt-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; }
|
||||
.dt-item { display: flex; align-items: center; gap: 10px; padding: 12px 14px; background: var(--cp-panel-2); border-radius: 12px; min-width: 0; }
|
||||
.dt-ic { font-size: 20px; color: var(--cp-ink-3); flex-shrink: 0; }
|
||||
.dt-ic-on { color: var(--cp-amber); }
|
||||
.dt-item div { display: flex; flex-direction: column; gap: 3px; min-width: 0; }
|
||||
.dt-item label { font-size: 11px; font-weight: 700; color: var(--cp-ink-3); letter-spacing: .4px; }
|
||||
.dt-item span { font-size: 13px; font-weight: 600; color: var(--cp-ink-1); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.dt-sec { display: flex; flex-direction: column; }
|
||||
.dt-desc { margin: 0; font-size: 13px; line-height: 1.9; color: var(--cp-ink); background: var(--cp-panel-2); padding: 12px 16px; border-radius: 10px; white-space: pre-wrap; word-break: break-word; }
|
||||
.dt-cols { display: grid; grid-template-columns: 1.15fr .85fr; gap: 14px; align-items: start; }
|
||||
.tags { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.vlist { display: flex; flex-direction: column; gap: 8px; }
|
||||
.vrow { display: flex; align-items: center; gap: 8px; padding: 7px 10px; background: var(--cp-panel-2); border-radius: 9px; }
|
||||
.vtime { font-size: 12px; margin-left: auto; }
|
||||
.dim-sm { color: var(--cp-ink-3); }
|
||||
.dim { font-size: 12px; color: var(--cp-ink-3); }
|
||||
</style>
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -10,12 +10,13 @@
|
||||
- 查看插件 / 账号 / 运行统计
|
||||
|
||||
鉴权:
|
||||
管理接口同时需要 内部凭证(X-API-Token) + 管理票据(X-Admin-Token)。
|
||||
本脚本运行在中心机本机,直接复用 desktop/controlplane/.env 与 .admin_secret:
|
||||
- X-API-Token 取自 CONTROLPLANE_TOKEN(.env);为空则该接口不强制,无需携带。
|
||||
- X-Admin-Token 用 CONTROLPLANE_ADMIN_SECRET > CONTROLPLANE_TOKEN > .admin_secret
|
||||
对指定管理员账号临时签发短期票据(与 app.py 完全一致,签名不可伪造)。
|
||||
因此本 CLI 只在"中心机本机 + 拥有管理密钥"的环境下可用,等价于本地管理台白名单。
|
||||
管理接口同时需要 内部凭证(X-API-Token) + 管理票据(X-Admin-Token)。管理票据两种获取方式:
|
||||
- 密码登录(推荐,任意机器可用):--password 或环境变量 AGENT_ADMIN_PASSWORD,
|
||||
走 /api/admin/auth 用账号+密码换 1 小时票据,管理主密钥不出服务器。
|
||||
- 本机密钥自签(原方式,中心机本机):直接复用 desktop/controlplane/.env 与 .admin_secret,
|
||||
X-API-Token 取自 CONTROLPLANE_TOKEN(.env);为空则该接口不强制,无需携带。
|
||||
X-Admin-Token 用 CONTROLPLANE_ADMIN_SECRET > CONTROLPLANE_TOKEN > .admin_secret 本地自签。
|
||||
中心机地址默认本机 8800;远程发版用 --base 或环境变量 CONTROLPLANE_AGENT_BASE 指向中心机公网地址。
|
||||
|
||||
管理员账号:需用 --admin 显式指定(或设环境变量 AGENT_ADMIN_ACCOUNT),该账号须 is_admin=1。
|
||||
|
||||
@@ -61,6 +62,9 @@ _load_dotenv()
|
||||
BASE_URL = os.getenv("CONTROLPLANE_AGENT_BASE", "").rstrip("/") or \
|
||||
f"http://127.0.0.1:{os.getenv('CONTROLPLANE_PORT', '8800')}"
|
||||
API_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
# 内网文件服务器:上传直链来源(复用 controlplane/.env 新增键)
|
||||
FILESERVER_BASE_URL = os.getenv("FILESERVER_BASE_URL", "").rstrip("/")
|
||||
FILESERVER_TOKEN = os.getenv("FILESERVER_TOKEN", "")
|
||||
|
||||
|
||||
def _admin_secret() -> str:
|
||||
@@ -86,17 +90,20 @@ def _mint_admin_token(account: str, secret: str) -> str:
|
||||
class Client:
|
||||
"""携带 X-API-Token + X-Admin-Token 的中心机 API 客户端。"""
|
||||
|
||||
def __init__(self, base: str, api_token: str, admin: str, secret: str):
|
||||
def __init__(self, base: str, api_token: str, admin: str, secret: str, token: str = ""):
|
||||
self.base = base
|
||||
self.api_token = api_token
|
||||
self.admin = admin
|
||||
self.secret = secret
|
||||
self.token = token # 密码登录换取的票据;非空时直接使用,不再本地自签
|
||||
|
||||
def _headers(self, json_body: bool = True) -> dict:
|
||||
h = {}
|
||||
if self.api_token:
|
||||
h["X-API-Token"] = self.api_token
|
||||
if self.admin and self.secret:
|
||||
if self.admin and self.token:
|
||||
h["X-Admin-Token"] = self.token
|
||||
elif self.admin and self.secret:
|
||||
h["X-Admin-Token"] = _mint_admin_token(self.admin, self.secret)
|
||||
if json_body:
|
||||
h["Content-Type"] = "application/json"
|
||||
@@ -178,6 +185,68 @@ def _plugin_rows(plugins) -> None:
|
||||
f"{str(p.get('latest_version') or ''):<10}{str(p.get('status') or ''):<12}{len(p.get('accounts') or [])}")
|
||||
|
||||
|
||||
def _run_file(args: argparse.Namespace, c: Client) -> int:
|
||||
"""file push / list / rm:内网大文件源管理。"""
|
||||
try:
|
||||
import requests as _rq
|
||||
except ModuleNotFoundError:
|
||||
raise SystemExit("[x] 缺少 requests,请用项目 .venv 运行。")
|
||||
fcmd = args.file_cmd
|
||||
|
||||
if fcmd == "push":
|
||||
path = Path(args.path)
|
||||
if not path.is_file():
|
||||
raise SystemExit(f"[x] 文件不存在:{path}")
|
||||
if not FILESERVER_BASE_URL or not FILESERVER_TOKEN:
|
||||
raise SystemExit("[x] 未配置内网文件服务器:请设 controlplane/.env 的 "
|
||||
"FILESERVER_BASE_URL 与 FILESERVER_TOKEN")
|
||||
# 第一步:传到文件服务器
|
||||
try:
|
||||
with open(path, "rb") as fp:
|
||||
r = _rq.post(f"{FILESERVER_BASE_URL}/api/upload",
|
||||
headers={"X-API-Token": FILESERVER_TOKEN},
|
||||
files={"upload": (path.name, fp, "application/octet-stream")},
|
||||
timeout=600)
|
||||
except _rq.ConnectionError as exc:
|
||||
raise SystemExit(f"[x] 无法连接内网文件服务器 {FILESERVER_BASE_URL}({exc})")
|
||||
if r.status_code >= 400:
|
||||
raise SystemExit(f"[x] 上传到文件服务器失败 HTTP {r.status_code}:{r.text[:200]}")
|
||||
up = r.json()
|
||||
url = up.get("url", "")
|
||||
if not url:
|
||||
raise SystemExit("[x] 文件服务器未返回 url")
|
||||
sha256 = args.sha256 or up.get("sha256", "")
|
||||
# 第二步:登记到中心机 file_sources
|
||||
body = {"category": args.category, "version": args.version,
|
||||
"filename": up.get("filename", path.name), "url": url,
|
||||
"sha256": sha256, "notes": args.notes, "enabled": True}
|
||||
rec = c.call("POST", "/api/admin/file-sources", body)
|
||||
print(f"[ok] 已登记 {args.category} v{args.version or '?'} → {url}")
|
||||
print(f" id={rec.get('id')} filename={path.name} sha256={str(sha256)[:16]}…")
|
||||
return 0
|
||||
|
||||
if fcmd == "list":
|
||||
data = c.call("GET", f"/api/admin/file-sources?category={args.category}", None, False)
|
||||
files = data.get("files", [])
|
||||
if not files:
|
||||
print("(暂无大文件源)")
|
||||
return 0
|
||||
print(f"{'ID':<4}{'分类':<10}{'版本':<12}{'启用':<6}文件名 / 链接")
|
||||
for f in files:
|
||||
print(f"{str(f.get('id')):<4}{str(f.get('category') or ''):<10}"
|
||||
f"{str(f.get('version') or ''):<12}{'是' if f.get('enabled') else '否':<6}"
|
||||
f"{f.get('filename') or ''}")
|
||||
print(f" {f.get('url') or ''}")
|
||||
return 0
|
||||
|
||||
if fcmd == "rm":
|
||||
r = c.call("DELETE", f"/api/admin/file-sources/{args.id}", None, False)
|
||||
print(f"[ok] 已删除登记 id={args.id}")
|
||||
return 0
|
||||
|
||||
raise SystemExit(f"[x] 未知 file 子命令:{fcmd}")
|
||||
|
||||
|
||||
# ================================ main ================================
|
||||
def _build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
@@ -186,6 +255,9 @@ def _build_parser() -> argparse.ArgumentParser:
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||
parser.add_argument("--admin", default=os.getenv("AGENT_ADMIN_ACCOUNT", ""),
|
||||
help="用于签发管理票据的管理员账号(须 is_admin=1)")
|
||||
parser.add_argument("--password", default=os.getenv("AGENT_ADMIN_PASSWORD", ""),
|
||||
dest="admin_password",
|
||||
help="管理员密码(密码登录模式,任意机器可用;须放在子命令之前。留空则回退本机密钥自签票据)")
|
||||
parser.add_argument("--base", default=BASE_URL, help="中心机服务地址")
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
@@ -259,16 +331,43 @@ def _build_parser() -> argparse.ArgumentParser:
|
||||
p_shell.add_argument("--notes", default="", help="更新说明(可选,执行机前端提示展示)")
|
||||
p_shell.add_argument("--sha256", default="", help="安装包 sha256(可选,缺省自动计算)")
|
||||
|
||||
p_file = sub.add_parser("file", help="内网大文件源管理:push/list/rm")
|
||||
file_sub = p_file.add_subparsers(dest="file_cmd", required=True)
|
||||
p_fpush = file_sub.add_parser("push", help="上传到内网文件服务器并登记到中心机")
|
||||
p_fpush.add_argument("path", help="本地文件路径")
|
||||
p_fpush.add_argument("--category", required=True, help="分类:shell/chrome/browser 等")
|
||||
p_fpush.add_argument("--version", default="", help="版本号(可选)")
|
||||
p_fpush.add_argument("--notes", default="", help="说明(可选)")
|
||||
p_fpush.add_argument("--sha256", default="", help="sha256(可选,缺省自动计算)")
|
||||
p_flist = file_sub.add_parser("list", help="列出大文件源")
|
||||
p_flist.add_argument("--category", default="", help="按分类过滤")
|
||||
p_frm = file_sub.add_parser("rm", help="删除中心机登记(不动内网服务器文件)")
|
||||
p_frm.add_argument("id", type=int, help="file_sources.id")
|
||||
|
||||
return parser
|
||||
|
||||
|
||||
def _run(args: argparse.Namespace) -> int:
|
||||
if not args.admin:
|
||||
raise SystemExit("[x] 未指定管理员账号:请用 --admin <账号> 或设置环境变量 AGENT_ADMIN_ACCOUNT。")
|
||||
secret = _admin_secret()
|
||||
if not secret:
|
||||
raise SystemExit("[x] 未找到管理密钥(CONTROLPLANE_ADMIN_SECRET / CONTROLPLANE_TOKEN / .admin_secret 均为空),无法签发管理票据。")
|
||||
c = Client(args.base, API_TOKEN, args.admin, secret)
|
||||
if args.admin_password.strip():
|
||||
# 密码登录模式(推荐,任意机器可用):账号+密码换 1 小时票据,主密钥不出服务器
|
||||
c = Client(args.base, API_TOKEN, args.admin, "")
|
||||
r = c.call("POST", "/api/admin/auth",
|
||||
{"account": args.admin, "password": args.admin_password})
|
||||
if not r.get("token"):
|
||||
raise SystemExit("[x] 登录成功但未返回票据,请检查中心机版本。")
|
||||
if not r.get("is_admin"):
|
||||
raise SystemExit(f"[x] 账号 {args.admin} 不是管理员(is_admin=0),无法执行管理操作。")
|
||||
c.token = str(r["token"])
|
||||
print(f"[ok] 已以 {args.admin} 登录 {args.base}(密码模式,票据 1 小时有效)")
|
||||
else:
|
||||
# 本机密钥自签模式(中心机本机):复用 .env/.admin_secret 本地签发票据
|
||||
secret = _admin_secret()
|
||||
if not secret:
|
||||
raise SystemExit("[x] 未找到管理密钥(CONTROLPLANE_ADMIN_SECRET / CONTROLPLANE_TOKEN / .admin_secret 均为空),"
|
||||
"无法签发管理票据;远程机器请改用密码登录:--password 或环境变量 AGENT_ADMIN_PASSWORD。")
|
||||
c = Client(args.base, API_TOKEN, args.admin, secret)
|
||||
cmd = args.command
|
||||
|
||||
if cmd == "shell-release":
|
||||
@@ -278,6 +377,9 @@ def _run(args: argparse.Namespace) -> int:
|
||||
print(f" 各执行机下次启动自动检测下载,前端提示后点击「重启更新」即静默升级。")
|
||||
return 0
|
||||
|
||||
if cmd == "file":
|
||||
return _run_file(args, c)
|
||||
|
||||
if cmd == "publish":
|
||||
r = c.upload_pkg(args.pkg, args.plugin_id, args.name, args.version)
|
||||
print(f"[ok] 已发布 {r.get('plugin_id')} v{r.get('version')} → {r.get('filename')}")
|
||||
|
||||
@@ -187,3 +187,31 @@ CREATE TABLE IF NOT EXISTS system_settings (
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`key`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='系统级键值配置';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 执行机敏感凭证:中心机统一存明文源,下发时用执行机 RSA 公钥加密为密文
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS client_creds (
|
||||
account VARCHAR(64) NOT NULL COMMENT '执行机账号(工号)',
|
||||
pubkey_pem TEXT NOT NULL COMMENT '该账号上报的 RSA 公钥(PEM)',
|
||||
creds MEDIUMTEXT NOT NULL COMMENT '敏感凭证密文 JSON:{key: base64(RSA 密文)},各值用 pubkey_pem 加密',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (account)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='执行机敏感凭证(中心机下发,RSA 加密)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 大文件源:内网直链,走内网文件服务器(中心机不存大包)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS file_sources (
|
||||
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '自增ID',
|
||||
category VARCHAR(32) NOT NULL DEFAULT '' COMMENT '分类:shell/chrome/browser 等',
|
||||
version VARCHAR(32) NOT NULL DEFAULT '' COMMENT '版本号(对比/展示用,可选)',
|
||||
filename VARCHAR(255) NOT NULL DEFAULT '' COMMENT '原文件名',
|
||||
url TEXT NOT NULL COMMENT '内网文件服务器直链',
|
||||
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT 'sha256 校验值(可选,有则校验)',
|
||||
notes VARCHAR(512) NOT NULL DEFAULT '' COMMENT '说明',
|
||||
enabled TINYINT(1) NOT NULL DEFAULT 1 COMMENT '1=启用 0=停用',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_category (category)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='大文件源(内网直链,走内网文件服务器)';
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""内网文件服务器配置:只读加载 fileserver/.env(环境变量优先,不覆盖已存在值)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import secrets
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _app_dir() -> Path:
|
||||
"""定位 .env / 数据所在目录。
|
||||
|
||||
- 源码运行:fileserver/core/config.py → fileserver/
|
||||
- PyInstaller 打包(exe):取可执行文件同目录,便于随 exe 摆放 .env 与 data/
|
||||
"""
|
||||
if getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS"):
|
||||
return Path(sys.executable).resolve().parent
|
||||
return Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
APP_DIR = _app_dir()
|
||||
|
||||
PORT = int(os.getenv("FILESERVER_PORT", "8802") or "8802")
|
||||
TOKEN = os.getenv("FILESERVER_TOKEN", "") # 上传/删除/列表鉴权 token
|
||||
# 落盘目录:.env 未配时默认 应用目录/data(受 .env 的 FILESERVER_DATA_DIR 覆盖)
|
||||
DATA_DIR = Path(os.getenv("FILESERVER_DATA_DIR", "") or (APP_DIR / "data")).resolve()
|
||||
# 对外下载根(生成 url 用,须内网机器可访问);未配时回退 本机 IP 端口 形式
|
||||
BASE_URL = os.getenv("FILESERVER_BASE_URL", "").rstrip("/") or f"http://127.0.0.1:{PORT}"
|
||||
|
||||
|
||||
def load_dotenv() -> None:
|
||||
"""读取本地 .env(同中心机 app.py 规则:环境变量优先)。"""
|
||||
env_path = APP_DIR / ".env"
|
||||
if not env_path.is_file():
|
||||
return
|
||||
for _ln in env_path.read_text(encoding="utf-8").splitlines():
|
||||
_line = _ln.strip()
|
||||
if not _line or _line.startswith("#") or "=" not in _line:
|
||||
continue
|
||||
_k, _v = _line.split("=", 1)
|
||||
k = _k.strip()
|
||||
if k and k not in os.environ:
|
||||
os.environ[k] = _v.strip()
|
||||
|
||||
|
||||
load_dotenv()
|
||||
|
||||
# load_dotenv 后再取一次,保证 .env 值生效
|
||||
PORT = int(os.getenv("FILESERVER_PORT", "8802") or "8802")
|
||||
TOKEN = os.getenv("FILESERVER_TOKEN", "")
|
||||
DATA_DIR = Path(os.getenv("FILESERVER_DATA_DIR", "") or (APP_DIR / "data")).resolve()
|
||||
BASE_URL = os.getenv("FILESERVER_BASE_URL", "").rstrip("/") or f"http://127.0.0.1:{PORT}"
|
||||
|
||||
|
||||
def default_token() -> str:
|
||||
"""未配置 token 时一次性生成(仅开发便利,生产应写死到 .env)。"""
|
||||
return TOKEN or secrets.token_urlsafe(24)
|
||||
Binary file not shown.
@@ -0,0 +1,72 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""内网文件服务器打包入口(PyInstaller 使用本文件作为 entry)。
|
||||
|
||||
作用:初始化应用目录(.env / data),并启动 uvicorn 服务。
|
||||
支持命令行参数(兼容开机自启脚本注入):
|
||||
--port 覆盖端口(默认读 .env 的 FILESERVER_PORT)
|
||||
--base-url 覆盖对外下载根(默认读 .env 的 FILESERVER_BASE_URL)
|
||||
|
||||
运行:
|
||||
python fileserver/launch.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import traceback
|
||||
|
||||
|
||||
def _bootstrap_config(base_dir: str | None = None, port: str = "",
|
||||
base_url: str = "") -> None:
|
||||
"""确保 .env / data 目录就绪;可注入临时覆盖。"""
|
||||
import os
|
||||
# 命令行/调用方覆盖优先(initialization 里各项覆盖均会在 import config 后由 config 重新读取)
|
||||
os.environ["FILESERVER_PORT"] = port or os.getenv("FILESERVER_PORT", "8802")
|
||||
if base_url:
|
||||
os.environ["FILESERVER_BASE_URL"] = base_url
|
||||
from fileserver.core import config
|
||||
# 首次 import 即会执行 config 模块级读取(含 load_dotenv),port/base 覆盖已注入 os.environ
|
||||
config.DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="37du 内网文件服务器")
|
||||
parser.add_argument("--port", default="", help="服务端口(默认读 .env FILESERVER_PORT)")
|
||||
parser.add_argument("--base-url", default="", help="对外下载根(默认读 .env FILESERVER_BASE_URL)")
|
||||
args, _ = parser.parse_known_args()
|
||||
|
||||
log_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
|
||||
# windowed(无窗口)模式下 stdout/stderr 不可见,统一落盘 fileserver.log 便于排错
|
||||
_log_file = os.path.join(log_dir, "fileserver.log")
|
||||
logging.basicConfig(level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(message)s",
|
||||
handlers=[logging.FileHandler(_log_file, encoding="utf-8"),
|
||||
logging.StreamHandler()])
|
||||
try:
|
||||
_bootstrap_config(port=args.port, base_url=args.base_url)
|
||||
import uvicorn
|
||||
from fileserver.main import app
|
||||
from fileserver.core import config
|
||||
logging.info("37du 内网文件服务器启动: http://0.0.0.0:%s (数据目录 %s,日志 %s)",
|
||||
config.PORT, config.DATA_DIR, _log_file)
|
||||
uvicorn.run(app, host="0.0.0.0", port=config.PORT,
|
||||
log_level="info", access_log=False,
|
||||
log_config=None)
|
||||
return 0
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
|
||||
err = f"[fatal] {type(exc).__name__}: {exc}\n{traceback.format_exc()}"
|
||||
try:
|
||||
(os.path.join(log_dir, "fileserver.err.log"))
|
||||
with open(os.path.join(log_dir, "fileserver.err.log"), "a", encoding="utf-8") as f:
|
||||
f.write(err + "\n")
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
print(err, file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,137 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""内网文件服务器(独立 FastAPI,端口 8802)。
|
||||
|
||||
职责:存放大型文件(壳子更新包、Chrome 安装包等),供执行机内网直连下载。
|
||||
设计:中心机只存本服务器返回的内网直链,不转发大包。
|
||||
|
||||
接口鉴权:
|
||||
- 上传 / 删除 / 列表需 HTTP 头 `X-API-Token`(值 = FILESERVER_TOKEN)
|
||||
- 下载开放(内网环境,客户端拿到链接直接下)
|
||||
|
||||
运行(桌面端,cwd = desktop/):python -m fileserver.main
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import secrets
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI, Header, HTTPException, UploadFile
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
from fileserver.core import config
|
||||
|
||||
app = FastAPI(title="37du 内网文件服务器")
|
||||
|
||||
_DATA_DIR = config.DATA_DIR
|
||||
_DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
_STATUS_DIR = _DATA_DIR / ".meta"
|
||||
_STATUS_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
def _require_token(x_api_token: str = "") -> None:
|
||||
"""校验管理 token;未配置 token 时放行(纯开发模式)。"""
|
||||
if not config.TOKEN:
|
||||
return
|
||||
if x_api_token.strip() != config.TOKEN:
|
||||
raise HTTPException(401, "无效的文件服务器令牌")
|
||||
|
||||
|
||||
def _safe_link_name(name: str) -> str:
|
||||
"""下载文件名清洗:仅保留安全 basename,去除路径与危险字符。"""
|
||||
name = Path(name or "").name
|
||||
return re.sub(r"[^\w.\-]", "_", name)[:200]
|
||||
|
||||
|
||||
def _store_path(fid: str) -> Path:
|
||||
return _DATA_DIR / fid
|
||||
|
||||
|
||||
def _file_meta(fid: str) -> dict:
|
||||
"""读 .meta/{fid}.json;缺失返回空 dict。"""
|
||||
mf = _STATUS_DIR / f"{fid}.json"
|
||||
if not mf.is_file():
|
||||
return {}
|
||||
try:
|
||||
return json.loads(mf.read_text(encoding="utf-8"))
|
||||
except Exception: # noqa: BLE001
|
||||
return {}
|
||||
|
||||
|
||||
@app.post("/api/upload")
|
||||
async def api_upload(upload: UploadFile,
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""上传文件:存唯一 id,返回 {id, filename, sha256, size, url}。"""
|
||||
_require_token(x_api_token)
|
||||
raw = await upload.read()
|
||||
if not raw:
|
||||
raise HTTPException(400, "上传内容为空")
|
||||
fid = secrets.token_urlsafe(12)
|
||||
origin = _safe_link_name(upload.filename or "")
|
||||
size = len(raw)
|
||||
sha = hashlib.sha256(raw).hexdigest()
|
||||
(_DATA_DIR / fid).write_bytes(raw)
|
||||
(_STATUS_DIR / f"{fid}.json").write_text(
|
||||
json.dumps({"fid": fid, "filename": origin, "sha256": sha, "size": size,
|
||||
"created": time.time()},
|
||||
ensure_ascii=False), encoding="utf-8")
|
||||
url = f"{config.BASE_URL}/files/{fid}?dl={origin}"
|
||||
return {"ok": True, "id": fid, "filename": origin, "sha256": sha,
|
||||
"size": size, "url": url}
|
||||
|
||||
|
||||
@app.get("/api/files")
|
||||
def api_files(x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""列表已上传文件(管理)。"""
|
||||
_require_token(x_api_token)
|
||||
items = []
|
||||
for mf in sorted(_STATUS_DIR.glob("*.json")):
|
||||
m = _file_meta(mf.stem)
|
||||
if m:
|
||||
m["url"] = f"{config.BASE_URL}/files/{m['fid']}?dl={m['filename']}"
|
||||
items.append(m)
|
||||
return {"files": items}
|
||||
|
||||
|
||||
@app.delete("/api/files/{fid}")
|
||||
def api_delete(fid: str, x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""删除文件与元数据(管理)。"""
|
||||
_require_token(x_api_token)
|
||||
if not re.fullmatch(r"[A-Za-z0-9_-]{1,64}", fid):
|
||||
raise HTTPException(400, "非法的文件 id")
|
||||
removed = False
|
||||
p = _store_path(fid)
|
||||
if p.is_file():
|
||||
p.unlink(missing_ok=True)
|
||||
removed = True
|
||||
(_STATUS_DIR / f"{fid}.json").unlink(missing_ok=True)
|
||||
return {"ok": True, "removed": removed, "id": fid}
|
||||
|
||||
|
||||
@app.get("/files/{fid}")
|
||||
def api_download(fid: str):
|
||||
"""开放下载(内网直链);?dl=文件名 时以该名 attachment 落盘。"""
|
||||
if not re.fullmatch(r"[A-Za-z0-9_-]{1,64}", fid):
|
||||
raise HTTPException(404, "文件不存在")
|
||||
p = _store_path(fid)
|
||||
if not p.is_file():
|
||||
raise HTTPException(404, "文件不存在")
|
||||
m = _file_meta(fid)
|
||||
default_name = m.get("filename") or fid
|
||||
return FileResponse(p, filename=default_name, media_type="application/octet-stream")
|
||||
|
||||
|
||||
@app.get("/")
|
||||
def index() -> dict:
|
||||
"""健康检查(无鉴权)。"""
|
||||
return {"ok": True, "service": "37du内网文件服务器",
|
||||
"files": len(list(_STATUS_DIR.glob("*.json")))}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
uvicorn.run(app, host="0.0.0.0", port=config.PORT)
|
||||
@@ -0,0 +1,3 @@
|
||||
fastapi>=0.110
|
||||
uvicorn>=0.29
|
||||
python-multipart>=0.0.9
|
||||
@@ -0,0 +1,31 @@
|
||||
@echo off
|
||||
REM ===== 37du 内网文件服务器 打包脚本(在 Windows 本机执行)=====
|
||||
REM 前置:desktop/.venv 已安装 fastapi uvicorn python-multipart pyinstaller
|
||||
REM 用法:在 desktop\ 目录下用项目 .venv 执行本脚本
|
||||
|
||||
setlocal
|
||||
cd /d %~dp0\..\..
|
||||
set PY=..\.venv\Scripts\python.exe
|
||||
if not exist %PY% (
|
||||
echo [err] 未找到 %PY% ,请确认在 desktop\ 目录且 .venv 存在
|
||||
pause & exit /b 1
|
||||
)
|
||||
|
||||
echo [1/3] 打包 exe ...
|
||||
%PY% -m PyInstaller desktop\fileserver\tools\37du-fileserver.spec ^
|
||||
--distpath desktop\fileserver\dist-exe ^
|
||||
--workpath desktop\fileserver\build-exe ^
|
||||
--noconfirm
|
||||
if errorlevel 1 (echo [err] 打包失败 & pause & exit /b 1)
|
||||
|
||||
echo [2/3] 装配部署目录 ...
|
||||
set DEP=desktop\fileserver\dist-exe\fileserver
|
||||
if not exist %DEP% mkdir %DEP%
|
||||
REM 拷贝 .env 到 exe 同目录(含 FILESERVER_BASE_URL 指向内网)
|
||||
copy /y desktop\fileserver\.env %DEP%\.env >nul
|
||||
move /y desktop\fileserver\dist-exe\37du-fileserver.exe %DEP%\37du-fileserver.exe >nul
|
||||
|
||||
echo [3/3] 完成。
|
||||
echo 部署目录: %DEP%
|
||||
echo 部署到内网机器 172.30.35.135,先改该 .env 的 FILESERVER_BASE_URL/TOKEN 再运行 install_autostart.bat
|
||||
pause
|
||||
@@ -0,0 +1,47 @@
|
||||
@echo off
|
||||
REM ===== 37du 内网文件服务器 一键配置:开放端口 + 安装开机自启 =====
|
||||
REM 用法:在文件服务器部署目录(含 37du-fileserver.exe、start_server.bat、.env)内
|
||||
REM 以管理员身份双击运行一次(放行防火墙需管理员权限)
|
||||
setlocal
|
||||
cd /d "%~dp0"
|
||||
|
||||
if not exist "%~dp037du-fileserver.exe" (
|
||||
echo [err] 未找到 37du-fileserver.exe,请把本脚本拷贝到 exe 同目录再运行
|
||||
pause & exit /b 1
|
||||
)
|
||||
if not exist "%~dp0start_server.bat" (
|
||||
echo [err] 未找到 start_server.bat,请与 exe 放在同一目录
|
||||
pause & exit /b 1
|
||||
)
|
||||
|
||||
echo ============================================
|
||||
echo [1/2] 开放防火墙端口 8802(TCP)...
|
||||
echo ============================================
|
||||
netsh advfirewall firewall show rule name="37du-FileServer-8802" >nul 2>&1
|
||||
if not errorlevel 1 (
|
||||
echo 规则已存在,跳过创建。
|
||||
) else (
|
||||
netsh advfirewall firewall add rule name="37du-FileServer-8802" ^
|
||||
dir=in action=allow protocol=TCP localport=8802 profile=any >nul
|
||||
if errorlevel 1 (
|
||||
echo [err] 放行端口失败(请以管理员身份运行本脚本)
|
||||
pause & exit /b 1
|
||||
) else (
|
||||
echo [ok] TCP 8802 已放行(内网 172.30.35.135:8802 可访问)。
|
||||
)
|
||||
)
|
||||
|
||||
echo.
|
||||
echo ============================================
|
||||
echo [2/2] 安装开机自启计划任务...
|
||||
echo ============================================
|
||||
schtasks /create /tn "37du-FileServer" /tr "\"%~dp0start_server.bat\"" ^
|
||||
/sc onlogon /rl limited /f >nul 2>&1
|
||||
if errorlevel 1 (
|
||||
echo [err] 自启安装失败(可能被安全软件拦截)
|
||||
pause & exit /b 1
|
||||
)
|
||||
|
||||
echo [ok] 完成:端口已放行,登录 Windows 自动启动内网文件服务器。
|
||||
echo 验证:http://127.0.0.1:8802 (返回 ok 即服务在线)
|
||||
pause
|
||||
@@ -0,0 +1,17 @@
|
||||
@echo off
|
||||
REM ===== 37du 内网文件服务器 启动脚本 =====
|
||||
REM 由计划任务(开机自启)调用:先启动本机内网文件服务器,并记录启动日志
|
||||
REM 请确保本脚本与 37du-fileserver.exe、.env 位于同一目录
|
||||
|
||||
setlocal
|
||||
cd /d "%~dp0"
|
||||
|
||||
REM 若已在运行则跳过(避免自启+手动重复起)
|
||||
tasklist /fi "imagename eq 37du-fileserver.exe" 2>nul | find /i "37du-fileserver.exe" >nul && (
|
||||
echo [%date% %time%] 已运行,跳过 >> fileserver.start.log
|
||||
exit /b 0
|
||||
)
|
||||
|
||||
echo [%date% %time%] starting >> fileserver.start.log
|
||||
start "" "%~dp037du-fileserver.exe"
|
||||
exit /b 0
|
||||
@@ -0,0 +1,7 @@
|
||||
@echo off
|
||||
REM ===== 37du 内网文件服务器 卸载开机自启 =====
|
||||
setlocal
|
||||
echo 正在删除 37du-FileServer 计划任务 ...
|
||||
schtasks /delete /tn "37du-FileServer" /f >nul 2>&1
|
||||
echo [ok] 已卸载开机自启(服务文件未删除,可手动运行 exe 启动)。
|
||||
pause
|
||||
@@ -12,7 +12,7 @@ from pydantic import BaseModel
|
||||
from webhost.backend import config
|
||||
from webhost.backend.core.cpapi import _cp_call, _cp_headers, _sync_licensing
|
||||
from webhost.backend.core.session import (SESSION_COOKIE, _SESS, _SESS_LOCK,
|
||||
_sess_account, _sess_persist)
|
||||
_sess_account, _sess_persist, _ACCT_CLOUD_TOKEN)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -66,6 +66,10 @@ def admin_login(b: _LoginIn, response: Response) -> dict:
|
||||
_SESS[token] = (b.account.strip(), time.time())
|
||||
_sess_persist()
|
||||
response.set_cookie(SESSION_COOKIE, token, httponly=True, samesite="lax")
|
||||
# 沿用中心机登录时签发的用户云令牌,后续 /api/admin/me 等调用凭它定位账号(无需机器 TOKEN)
|
||||
_cloud_tok = (r or {}).get("cloud_token") or ""
|
||||
if _cloud_tok:
|
||||
_ACCT_CLOUD_TOKEN[b.account.strip()] = _cloud_tok
|
||||
# 登录成功即联网同步该账号的离线授权票据 + 管控清单 + 中心机公钥(供离线运行)
|
||||
if config.CONTROLPLANE_URL:
|
||||
try:
|
||||
@@ -82,6 +86,15 @@ def admin_login(b: _LoginIn, response: Response) -> dict:
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
import logging
|
||||
logging.getLogger(__name__).warning("登录后插件同步失败:%s", _exc)
|
||||
# 登录后刷新该账号敏感凭证(管理员可拉到;员工被服务端 403 拒绝 → 走本地缓存,无害)
|
||||
try:
|
||||
from webhost.backend.core import creds_sync
|
||||
_creds = creds_sync.load(b.account.strip())
|
||||
if _creds:
|
||||
config.apply_creds(_creds)
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
import logging
|
||||
logging.getLogger(__name__).warning("登录后敏感凭证刷新失败:%s", _exc)
|
||||
return {**r, "account": b.account.strip()}
|
||||
|
||||
|
||||
|
||||
@@ -11,7 +11,6 @@ import secrets
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, Response
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||
@@ -84,6 +83,14 @@ def _dingtalk_establish(account: str, nickname: str, dingtalk_uid: str, response
|
||||
_sync_licensing(acct)
|
||||
except Exception as _exc: # noqa: BLE001 同步失败不影响登录本身
|
||||
_LOGGER.warning("登录后同步离线授权票据失败:%s", _exc)
|
||||
# 登录后刷新该账号敏感凭证(管理员可拉到;员工被服务端 403 拒绝 → 走本地缓存,无害)
|
||||
try:
|
||||
from webhost.backend.core import creds_sync
|
||||
_creds = creds_sync.load(acct)
|
||||
if _creds:
|
||||
config.apply_creds(_creds)
|
||||
except Exception as _exc: # noqa: BLE001 刷新失败不影响登录本身
|
||||
_LOGGER.warning("登录后敏感凭证刷新失败:%s", _exc)
|
||||
return {"ok": True, "account": acct, "is_admin": bool(r.get("is_admin")),
|
||||
"created": bool(r.get("created")), "must_change_pwd": bool(r.get("must_change_pwd"))}
|
||||
|
||||
@@ -131,21 +138,20 @@ def admin_dingtalk_inline_qr(request: Request) -> dict:
|
||||
|
||||
@router.get("/api/auth/dingtalk")
|
||||
def auth_dingtalk_url() -> dict:
|
||||
"""生成并返回钉钉扫码授权 URL(redirect_uri=本机 /auth/done)。前端「钉钉登录」当前窗口跳转该 URL。"""
|
||||
if not config.DINGTALK_APP_KEY:
|
||||
raise HTTPException(503, "未配置钉钉开放平台应用(DINGTALK_APP_KEY)")
|
||||
"""生成并返回钉钉扫码授权 URL(redirect_uri=本机 /auth/done),URL 由控制面代理构造。
|
||||
|
||||
执行机无需任何钉钉应用凭证(凭证只在控制面);前端「钉钉登录」当前窗口跳转该 URL,
|
||||
扫码后浏览器自动回跳本机 /auth/done。
|
||||
"""
|
||||
if not config.CONTROLPLANE_URL:
|
||||
raise HTTPException(503, "未配置中心机地址(CONTROLPLANE_URL)")
|
||||
state = _login_state_new()
|
||||
redirect_uri = f"http://localhost:{config.PORT}/auth/done"
|
||||
login_url = "https://login.dingtalk.com/oauth2/challenge.htm?" + urlencode({
|
||||
"redirect_uri": redirect_uri,
|
||||
"response_type": "code",
|
||||
"client_id": config.DINGTALK_APP_KEY,
|
||||
"scope": "openid",
|
||||
"prompt": "consent",
|
||||
"state": state})
|
||||
return {"url": login_url, "state": state}
|
||||
r = _cp_call(
|
||||
"GET", "/api/dingtalk/login-url",
|
||||
params={"back": redirect_uri, "state": state},
|
||||
headers=({"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}))
|
||||
return {"url": r.get("url") or "", "state": state}
|
||||
|
||||
|
||||
@router.get("/auth/done")
|
||||
|
||||
@@ -12,6 +12,8 @@ from webhost.backend.plugins import PLUGINS, load_plugins
|
||||
from webhost.backend.core.plugin_sync import sync_plugins, _cloud_plugin_manifest
|
||||
from webhost.backend.core import shell_updater as _shell_updater
|
||||
from webhost.backend.core.session import _require_login, _sess_account
|
||||
from webhost.backend.core import licensing
|
||||
from webhost.backend.core import chrome_manager as _chrome
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -19,13 +21,17 @@ router = APIRouter()
|
||||
@router.get("/api/meta")
|
||||
def meta(request: Request) -> dict:
|
||||
account = _sess_account(request)
|
||||
# 插件清单仅对已登录账号可见(未登录不泄露插件元数据);
|
||||
# 已登录且能按云端权限(authorization)解析时,仅返回该员工被授权插件(§2.2 权限隔离)。
|
||||
# 插件可见性 = 本地授权票据快照(统一真源,与运行门禁一致):仅展示票据内被授权插件;
|
||||
# 票据不可用(缺失/过期且刷新失败)→ 空列表 + authExpired,前端提示联网刷新(超时不能使用)。
|
||||
auth_expired = False
|
||||
if account:
|
||||
allowed = _meta._cloud_plugin_ids(account)
|
||||
plugins = ([_meta._plugin_schema(p) for p in PLUGINS if p.id in allowed]
|
||||
if allowed is not None # 云端按员工返回了授权集(也可能是空集=无权限)
|
||||
else [_meta._plugin_schema(p) for p in PLUGINS]) # 无 token/云端不可达 → 离线兜底全量
|
||||
ok, lic = licensing.ensure_license(account)
|
||||
if ok:
|
||||
allowed = {p.get("pluginId") for p in (lic or {}).get("plugins", [])}
|
||||
plugins = [_meta._plugin_schema(p) for p in PLUGINS if p.id in allowed]
|
||||
else:
|
||||
plugins = []
|
||||
auth_expired = True
|
||||
else:
|
||||
plugins = []
|
||||
allowed_plats = _meta._account_allowed_platforms(account) if account else None
|
||||
@@ -35,10 +41,10 @@ def meta(request: Request) -> dict:
|
||||
"allowed": (pid in allowed_plats) if allowed_plats is not None else True}
|
||||
for pid, m in _st.PLATFORMS.items()]
|
||||
return {
|
||||
# controlplane_url 供前端管理员跳转控制面;未配置时为空(前端隐藏管理入口)
|
||||
"controlplane": config.CONTROLPLANE_URL,
|
||||
"appName": "37du 自动化工作台",
|
||||
"dingtalkScan": bool(config.DINGTALK_APP_KEY),
|
||||
# 钉钉扫码 URL 由控制面代理构造,客户端零钉钉凭证;控制面配置了即可用扫码入口
|
||||
"dingtalkScan": bool(config.CONTROLPLANE_URL),
|
||||
"authExpired": auth_expired,
|
||||
"platforms": platforms,
|
||||
"plugins": plugins,
|
||||
}
|
||||
@@ -49,29 +55,55 @@ def plugins_sync(request: Request) -> dict:
|
||||
"""按当前登录账号权限自下载/更新插件,成功后重载注册表。
|
||||
|
||||
离线(控制面不可达)/未配置时返回空统计,前端直接沿用本地插件进入主界面。
|
||||
全程持 SYNC_LOCK:与启动后台同步串行,避免旧账号白名单覆盖本次同步结果。
|
||||
"""
|
||||
account = _require_login(request)
|
||||
result = sync_plugins(account)
|
||||
try:
|
||||
# 以「登录账号的授权插件集」作为加载白名单(替代启动时 CONTROLPLANE_ACCOUNT 的固定白名单),
|
||||
# 保证给员工账号授权插件后登录即可见/可运行;控制面不可达(manifest=None)时保持原白名单。
|
||||
manifest = _cloud_plugin_manifest(account)
|
||||
if manifest is not None:
|
||||
_st.set_allowed({p.get("id") for p in manifest})
|
||||
load_plugins(_st.ALLOWED, reload=True)
|
||||
from webhost.backend.core.plugin_sync import SYNC_LOCK
|
||||
with SYNC_LOCK:
|
||||
result = sync_plugins(account)
|
||||
manifest = _cloud_plugin_manifest(account)
|
||||
if manifest is not None:
|
||||
_st.set_allowed({p.get("id") for p in manifest})
|
||||
load_plugins(_st.ALLOWED, reload=True)
|
||||
except Exception as _exc: # noqa: BLE001 重载失败不阻断返回
|
||||
import logging
|
||||
logging.getLogger(__name__).warning("插件同步后重载失败:%s", _exc)
|
||||
# 授权票据一并刷新:管理台新授的插件在「F5 同步」后立即可运行,
|
||||
# 否则本地许可票据停留在上次登录时的快照,点执行会被 403 拒绝(须重登才恢复)。
|
||||
try:
|
||||
from webhost.backend.core.cpapi import _sync_licensing
|
||||
_sync_licensing(account)
|
||||
except Exception as _exc: # noqa: BLE001 票据刷新失败不阻断同步结果
|
||||
logging.getLogger(__name__).warning("同步后刷新授权票据失败:%s", _exc)
|
||||
return result
|
||||
|
||||
|
||||
@router.get("/api/shell/update-status")
|
||||
def shell_update_status(request: Request) -> dict:
|
||||
"""壳子更新状态:前端据此显示"发现新版本,点击重启更新"提示。"""
|
||||
"""壳子更新状态:前端据此显示"发现新版本,点击重启更新"提示与手动检查结果轮询。"""
|
||||
_require_login(request)
|
||||
return _shell_updater.pending_status()
|
||||
|
||||
|
||||
@router.post("/api/shell/check")
|
||||
def shell_check(request: Request) -> dict:
|
||||
"""手动检查壳子更新:只比对版本(秒级),不下载;有新版由前端提示用户确认下载。"""
|
||||
_require_login(request)
|
||||
_shell_updater.start_check()
|
||||
return {"ok": True, "checking": True}
|
||||
|
||||
|
||||
@router.post("/api/shell/download")
|
||||
def shell_download(request: Request) -> dict:
|
||||
"""开始下载新版安装包(后台流式下载,进度经 update-status 的 dl 字段轮询)。"""
|
||||
_require_login(request)
|
||||
_shell_updater.start_download()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/api/shell/apply")
|
||||
def shell_apply(request: Request) -> dict:
|
||||
"""应用壳子更新:运行新版安装包静默安装并退出进程(升级完成后自动重启新版本)。"""
|
||||
@@ -80,13 +112,48 @@ def shell_apply(request: Request) -> dict:
|
||||
return {"ok": True} # 实际不会走到这里(apply 内 os._exit)
|
||||
|
||||
|
||||
# ===================== 浏览器(Chrome)检测/下载/安装 =====================
|
||||
|
||||
@router.get("/api/chrome/status")
|
||||
def chrome_status(request: Request) -> dict:
|
||||
"""浏览器状态:是否已装、版本、需否下载、下载进度。前端据此显示"安装 Chrome"图标提示。"""
|
||||
_require_login(request)
|
||||
return _chrome.status()
|
||||
|
||||
|
||||
@router.post("/api/chrome/check")
|
||||
def chrome_check(request: Request) -> dict:
|
||||
"""手动检测浏览器:刷新本机安装状态 + 中心机有无登记内网安装包。"""
|
||||
_require_login(request)
|
||||
_chrome.refresh()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/api/chrome/download")
|
||||
def chrome_download(request: Request) -> dict:
|
||||
"""开始后台下载 Chrome 安装包(进度经 /api/chrome/status 的 dl 字段轮询)。"""
|
||||
_require_login(request)
|
||||
_chrome.start_download()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/api/chrome/install")
|
||||
def chrome_install(request: Request) -> dict:
|
||||
"""静默安装已下载的 Chrome 安装包(后台进行,前端轮询 status.installed 感知成功)。"""
|
||||
_require_login(request)
|
||||
return _chrome.install()
|
||||
|
||||
|
||||
@router.post("/api/platforms/{pid}/login")
|
||||
def platform_login(pid: str, request: Request) -> dict:
|
||||
"""真实登录:需先通过统一账户登录(有会话),且该账号已获中心机平台授权。"""
|
||||
"""真实登录:需先通过统一账户登录(有会话)、授权票据有效,且该账号已获中心机平台授权。"""
|
||||
account = _require_login(request)
|
||||
plat = _st.PLATFORMS.get(pid)
|
||||
if not plat:
|
||||
raise HTTPException(404, "平台不存在")
|
||||
ok, _lic = licensing.ensure_license(account)
|
||||
if not ok:
|
||||
raise HTTPException(403, "授权已过期(最长离线 7 天),请联网刷新后重试")
|
||||
allowed = _meta._account_allowed_platforms(account)
|
||||
if allowed is None:
|
||||
raise HTTPException(503, "控制面不可达,无法校验平台权限")
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主「插件配置 + 插件 UI」路由:带 UI 插件的底座通用约定。
|
||||
|
||||
两块能力(插件包内 ui/ 目录 + 本地配置存取):
|
||||
- GET/POST /api/plugin-config/{pid} per-plugin JSON 配置存取(落执行机本机
|
||||
%LOCALAPPDATA%\\37duAutomation\\plugin_configs\\,账号密码等个性化配置改一次永久生效)
|
||||
- GET /pui/{pid}[/path] 插件自带前端静态托管(源码态与打包态都从
|
||||
plugins/<pid>/ui/ 现读,插件 UI 更新只发插件包、不随壳子发版)
|
||||
鉴权与其他 API 一致:统一账户 cookie 会话(壳子内嵌 iframe 同源自动携带)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import mimetypes
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
from webhost.backend import config
|
||||
from webhost.backend import state as _st
|
||||
from webhost.backend.core.session import _require_login
|
||||
from webhost.backend.plugins import PLUGINS, _PLUGINS_ROOT # noqa: SLF001 插件根单一真源
|
||||
|
||||
router = APIRouter()
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_UI_DIRNAME = "ui" # 插件包内前端目录名(与 plugin.json 的 "ui": true 声明配套)
|
||||
_MIME = {".html": "text/html", ".js": "application/javascript",
|
||||
".mjs": "application/javascript", ".css": "text/css",
|
||||
".json": "application/json", ".map": "application/json",
|
||||
".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg",
|
||||
".gif": "image/gif", ".ico": "image/x-icon", ".woff": "font/woff",
|
||||
".woff2": "font/woff2", ".ttf": "font/ttf", ".txt": "text/plain"}
|
||||
|
||||
|
||||
def _check_ui_allowed(plugin_id: str) -> None:
|
||||
"""托管/配置读写的前置校验:插件已加载且在账号白名单内,否则 404(不泄露存在性)。"""
|
||||
try:
|
||||
PLUGINS.find(plugin_id)
|
||||
except KeyError:
|
||||
raise HTTPException(404, "插件不存在")
|
||||
if _st.ALLOWED is not None and plugin_id not in _st.ALLOWED:
|
||||
raise HTTPException(404, "插件不存在")
|
||||
|
||||
|
||||
# ==================== per-plugin 本地配置存取 ====================
|
||||
def _config_path(plugin_id: str):
|
||||
return config.PLUGIN_CONFIG_DIR / f"{plugin_id}.json"
|
||||
|
||||
|
||||
@router.get("/api/plugin-config/{plugin_id}")
|
||||
def get_plugin_config(plugin_id: str, request: Request):
|
||||
"""读取插件本地配置;从未保存过返回空对象(前端用默认值兜底)。"""
|
||||
_require_login(request)
|
||||
_check_ui_allowed(plugin_id)
|
||||
path = _config_path(plugin_id)
|
||||
if not path.is_file():
|
||||
return {}
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
return data if isinstance(data, dict) else {}
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
|
||||
|
||||
@router.post("/api/plugin-config/{plugin_id}")
|
||||
async def save_plugin_config(plugin_id: str, request: Request):
|
||||
"""整体保存插件配置(前端提交完整表单对象,本地原子落盘)。"""
|
||||
_require_login(request)
|
||||
_check_ui_allowed(plugin_id)
|
||||
try:
|
||||
data = await request.json()
|
||||
except Exception:
|
||||
raise HTTPException(400, "配置体必须是 JSON 对象")
|
||||
if not isinstance(data, dict):
|
||||
raise HTTPException(400, "配置体必须是 JSON 对象")
|
||||
path = _config_path(plugin_id)
|
||||
try:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = path.with_suffix(".json.tmp")
|
||||
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
tmp.replace(path) # 原子替换,避免写一半被读到
|
||||
except OSError as exc:
|
||||
_LOGGER.warning("插件 %s 配置保存失败:%s", plugin_id, exc)
|
||||
raise HTTPException(500, "配置保存失败")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
# ==================== 插件 UI 静态托管 ====================
|
||||
def _serve_ui(plugin_id: str, rel: str, request: Request) -> FileResponse:
|
||||
_require_login(request)
|
||||
_check_ui_allowed(plugin_id)
|
||||
ui_root = (_PLUGINS_ROOT / plugin_id / _UI_DIRNAME).resolve()
|
||||
if not ui_root.is_dir():
|
||||
raise HTTPException(404, "该插件未提供前端界面")
|
||||
target = (ui_root / rel).resolve() if rel.strip() else ui_root / "index.html"
|
||||
if not target.is_relative_to(ui_root): # 防路径穿越(..、绝对路径拼接等)
|
||||
raise HTTPException(404, "not found")
|
||||
if target.is_dir():
|
||||
target = target / "index.html"
|
||||
if not target.is_file():
|
||||
# SPA 兜底:未知路径回 index.html(history 路由可用)
|
||||
target = ui_root / "index.html"
|
||||
if not target.is_file():
|
||||
raise HTTPException(404, "not found")
|
||||
media_type = (_MIME.get(target.suffix.lower())
|
||||
or mimetypes.guess_type(str(target))[0] or "application/octet-stream")
|
||||
# index.html 不缓存(插件更新后刷新即生效);带 hash 的静态资源可长缓存
|
||||
headers = {"Cache-Control": "no-cache" if target.name == "index.html"
|
||||
else "public, max-age=86400"}
|
||||
return FileResponse(str(target), media_type=media_type, headers=headers)
|
||||
|
||||
|
||||
@router.get("/pui/{plugin_id}")
|
||||
def plugin_ui_root(plugin_id: str, request: Request):
|
||||
return _serve_ui(plugin_id, "", request)
|
||||
|
||||
|
||||
@router.get("/pui/{plugin_id}/{path:path}")
|
||||
def plugin_ui_file(plugin_id: str, path: str, request: Request):
|
||||
return _serve_ui(plugin_id, path, request)
|
||||
@@ -63,13 +63,21 @@ def start_run(req: RunReq, request: Request) -> dict:
|
||||
"level": "INFO",
|
||||
"msg": "设备正有其他插件执行中,排队等待其完成后自动启动…"})
|
||||
|
||||
def _start(_run_id):
|
||||
# start_fn 无参调用(scheduler 约定):run_id 由外层闭包捕获;
|
||||
# 之前签名带 _run_id 形参会因 TypeError 启动失败且被静默吞掉,运行记录永久卡 running
|
||||
def _start():
|
||||
threading.Thread(target=_run_target,
|
||||
args=(plugin, req.fields, _run_id),
|
||||
args=(plugin, req.fields, run_id),
|
||||
daemon=True, name=f"exec-{plugin.id}").start()
|
||||
return _run_id
|
||||
_scheduler.request_start(account, plugin.id,
|
||||
getattr(plugin, "version", "0"), _start)
|
||||
return run_id
|
||||
r = _scheduler.request_start(account, plugin.id,
|
||||
getattr(plugin, "version", "0"), _start)
|
||||
if not r.get("ok"):
|
||||
# 启动失败(回滚已发生):落地错误结果并广播,避免前端永久等待
|
||||
_st._set_run(run_id, status="error", result=None,
|
||||
error=r.get("error") or "启动失败")
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False,
|
||||
"error": r.get("error") or "启动失败"})
|
||||
|
||||
threading.Thread(target=_queued, daemon=True,
|
||||
name=f"run-{plugin.id}").start()
|
||||
|
||||
@@ -0,0 +1,322 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""执行机浏览器(Chrome)管理:检测本机是否已装 Chrome → 从中心机拿内网链接下载安装包 → 静默安装。
|
||||
|
||||
流程(对应前端交互):
|
||||
1. 检测:启动时/前端手动"检测",读注册表判断 Chrome 是否已装、装了给出版本号。
|
||||
在此基础上向前端返回"已安装(版本) / 未安装",未安装时展示"下载安装 Chrome"图标按钮。
|
||||
2. 下载:用户点击 → 后台流式下载中心机 file_sources(chrome) 登记的内网直链到
|
||||
%LOCALAPPDATA%\\37duAutomation\\chrome\\(先写 .part,完成校验后改名),
|
||||
进度写入状态供前端轮询展示。
|
||||
3. 安装:下载完成后前端提示"安装 Chrome",用户点击 → ChromeStandaloneSetup64.exe
|
||||
/silent /install 后台静默安装(Chrome 官方安装器参数,不需 Inno)。
|
||||
4. 中心机未登记 chrome / 校验失败 / 不可达:记录错误原因,前端提示,不影响其它功能。
|
||||
|
||||
并发控制:下载持独立锁防重入;检测轻量(读注册表),直接同步返回。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import threading
|
||||
import winreg
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend.core import config
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 下载缓存目录:独立于程序目录(升级/清理不受影响)
|
||||
_CHROME_CACHE = Path(os.getenv("LOCALAPPDATA", str(Path.home()))) / "37duAutomation" / "chrome"
|
||||
|
||||
# 下载互斥锁:防止并发重复下载
|
||||
_DL_LOCK = threading.Lock()
|
||||
|
||||
# 已下载待安装的安装包路径
|
||||
_PENDING_PKG: Path | None = None
|
||||
|
||||
# 运行态(供前端轮询 chrome status)
|
||||
_STATE: dict = {
|
||||
"installed": True, # 本机是否已装 Chrome
|
||||
"version": "", # 已装版本(未装为空)
|
||||
"checking": False, # 正在重新检测
|
||||
"check_error": "", # 检测/拉取云端信息错误
|
||||
"cloud_available": True, # 中心机是否登记了 chrome 内网链接
|
||||
# 下载
|
||||
"dl_status": "idle", # idle | downloading | downloaded | failed
|
||||
"dl_received": 0,
|
||||
"dl_total": 0,
|
||||
"dl_pct": 0,
|
||||
"dl_error": "",
|
||||
"installing": False, # 正在静默安装
|
||||
}
|
||||
|
||||
|
||||
# ===================== 检测 =====================
|
||||
|
||||
# Chrome 注册表探测点:按优先级尝试,兼容 64/32 位安装
|
||||
_CHROME_REGS = [
|
||||
(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"),
|
||||
(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"),
|
||||
(winreg.HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"),
|
||||
]
|
||||
# 64 位 Google Chrome 默认安装目录(版本目录里 max.exe 可读 Product Version)
|
||||
_CHROME_INSTALL_DIRS = [
|
||||
Path(os.environ.get("PROGRAMFILES", "C:/Program Files")) / "Google" / "Chrome" / "Application",
|
||||
Path(os.environ.get("PROGRAMFILES(X86)", "C:/Program Files (x86)")) / "Google" / "Chrome" / "Application",
|
||||
Path(os.environ.get("LOCALAPPDATA", Path.home().as_posix())) / "Google" / "Chrome" / "Application",
|
||||
]
|
||||
|
||||
_VERSION_RE = re.compile(r"^(\d+)\.(\d+)\.(\d+)\.(\d+)$")
|
||||
|
||||
|
||||
def detect_local() -> dict:
|
||||
"""检测本机 Chrome:返回 {"installed": bool, "version": str},读注册表为主。"""
|
||||
exe = _find_chrome_exe()
|
||||
if not exe:
|
||||
return {"installed": False, "version": ""}
|
||||
version = _read_version(exe)
|
||||
return {"installed": True, "version": version}
|
||||
|
||||
|
||||
def _find_chrome_exe() -> Path | None:
|
||||
for hive, key in _CHROME_REGS:
|
||||
try:
|
||||
with winreg.OpenKey(hive, key, 0, winreg.KEY_READ) as k:
|
||||
value, _ = winreg.QueryValueEx(k, "")
|
||||
if value and Path(value).is_file():
|
||||
return Path(value)
|
||||
except OSError:
|
||||
continue
|
||||
# 注册表探测失败时回退目录扫描(无版本目录成功语义)
|
||||
for d in _CHROME_INSTALL_DIRS:
|
||||
p = d / "chrome.exe"
|
||||
if p.is_file():
|
||||
return p
|
||||
return None
|
||||
|
||||
|
||||
def _read_version(exe: Path) -> str:
|
||||
try:
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
size, handle = wintypes.DWORD(0), wintypes.HANDLE()
|
||||
r = ctypes.windll.version.GetFileVersionInfoSizeW(str(exe), ctypes.byref(handle))
|
||||
if not r:
|
||||
return ""
|
||||
buf = ctypes.create_string_buffer(r)
|
||||
if not ctypes.windll.version.GetFileVersionInfoW(str(exe), wintypes.DWORD(0), r, buf):
|
||||
return ""
|
||||
# 用 subprocess wmic/powershell 更稳,但这里走纯方案:解析 VS_FIXEDFILEINFO 偏移
|
||||
fixed = ctypes.c_ubyte * r
|
||||
out = fixed.from_buffer(buf)
|
||||
# 简单方案:调用 wmic(存在但慢),改用 powershell 取 ProductVersion
|
||||
import subprocess as _sp
|
||||
try:
|
||||
out2 = _sp.run(
|
||||
["powershell", "-NoProfile", "-Command",
|
||||
"(Get-Item -LiteralPath '%s').VersionInfo.ProductVersion" % exe],
|
||||
capture_output=True, text=True, timeout=5)
|
||||
v = (out2.stdout or "").strip()
|
||||
return v if _VERSION_RE.match(v) else ""
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
|
||||
|
||||
def _cloud_info() -> dict | None:
|
||||
"""从中心机取 file_sources(chrome) 登记信息:{url, sha256, version, filename}。"""
|
||||
if not config.CONTROLPLANE_URL:
|
||||
return None
|
||||
import requests
|
||||
try:
|
||||
headers = {}
|
||||
if config.CONTROLPLANE_TOKEN:
|
||||
headers["X-API-Token"] = config.CONTROLPLANE_TOKEN
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/file-sources/chrome",
|
||||
headers=headers, timeout=5)
|
||||
if r.status_code != 200:
|
||||
_STATE["cloud_available"] = False
|
||||
return None
|
||||
data = r.json()
|
||||
if not data.get("available"):
|
||||
_STATE["cloud_available"] = False
|
||||
return None
|
||||
_STATE["cloud_available"] = True
|
||||
return data
|
||||
except Exception as _exc: # noqa: BLE001 离线/中心机不可达
|
||||
_LOGGER.info("获取浏览器云端信息失败(离线跳过):%s", _exc)
|
||||
_STATE["cloud_available"] = False
|
||||
return None
|
||||
|
||||
|
||||
# ===================== 对外状态 =====================
|
||||
|
||||
def status() -> dict:
|
||||
"""当前浏览器状态快照(供前端展示与轮询)。"""
|
||||
local = detect_local()
|
||||
installed = local["installed"]
|
||||
if installed:
|
||||
_STATE["installed"] = True
|
||||
_STATE["version"] = local["version"]
|
||||
_STATE["check_error"] = ""
|
||||
else:
|
||||
_STATE["installed"] = False
|
||||
_STATE["version"] = ""
|
||||
pkg_ok = bool(_PENDING_PKG) and _PENDING_PKG.is_file()
|
||||
return {
|
||||
"installed": _STATE["installed"],
|
||||
"version": _STATE["version"],
|
||||
"downloaded": bool(pkg_ok),
|
||||
"cloud_available": bool(_STATE["cloud_available"]),
|
||||
"error": _STATE["check_error"],
|
||||
"installing": bool(_STATE["installing"]),
|
||||
"dl": {
|
||||
"status": _STATE["dl_status"],
|
||||
"received": _STATE.get("dl_received", 0),
|
||||
"total": _STATE.get("dl_total", 0),
|
||||
"pct": _STATE.get("dl_pct", 0),
|
||||
"error": _STATE.get("dl_error", ""),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def refresh() -> None:
|
||||
"""前端手动触发一次检测:拉取云端登记,更新 cloud_available。"""
|
||||
global _STATE
|
||||
_STATE["checking"] = True
|
||||
try:
|
||||
detect_local()
|
||||
_cloud_info()
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("浏览器检测异常:%s", _exc)
|
||||
finally:
|
||||
_STATE["checking"] = False
|
||||
|
||||
|
||||
# ===================== 下载 =====================
|
||||
|
||||
def start_download() -> None:
|
||||
"""开始下载 Chrome 安装包(后台线程)。已有下载/已下载则直接沿用。"""
|
||||
if _STATE["dl_status"] == "downloading":
|
||||
return
|
||||
if _STATE["dl_status"] == "downloaded" and _PENDING_PKG and _PENDING_PKG.is_file():
|
||||
return
|
||||
info = _cloud_info()
|
||||
if not info or not info.get("url"):
|
||||
return
|
||||
url = str(info["url"]).strip()
|
||||
expect = (info.get("sha256") or "").lower()
|
||||
filename = (info.get("filename") or "ChromeStandaloneSetup64.exe").strip()
|
||||
_STATE["dl_version"] = info.get("version", "")
|
||||
_STATE["dl_status"] = "downloading"
|
||||
_STATE["dl_received"] = 0
|
||||
_STATE["dl_total"] = 0
|
||||
_STATE["dl_pct"] = 0
|
||||
_STATE["dl_error"] = ""
|
||||
threading.Thread(target=_download, args=(url, expect, filename), daemon=True,
|
||||
name="chrome-download").start()
|
||||
_LOGGER.info("开始下载 Chrome 安装包:%s", url)
|
||||
|
||||
|
||||
def _download(url: str, expect: str, filename: str) -> None:
|
||||
import requests
|
||||
try:
|
||||
with _DL_LOCK:
|
||||
_download_locked(url, expect, filename)
|
||||
except Exception as _exc: # noqa: BLE001 异常兜底
|
||||
_LOGGER.exception("下载 Chrome 异常")
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = f"下载异常({_exc.__class__.__name__})"
|
||||
_cleanup_part()
|
||||
|
||||
|
||||
def _download_locked(url: str, expect: str, filename: str) -> None:
|
||||
import requests
|
||||
tmp = _CHROME_CACHE / f"{filename}.part"
|
||||
pkg = _CHROME_CACHE / filename
|
||||
try:
|
||||
_CHROME_CACHE.mkdir(parents=True, exist_ok=True)
|
||||
with requests.get(url, stream=True, timeout=600) as r:
|
||||
r.raise_for_status()
|
||||
_STATE["dl_total"] = int(r.headers.get("Content-Length") or 0)
|
||||
sha = hashlib.sha256()
|
||||
with open(tmp, "wb") as f:
|
||||
for chunk in r.iter_content(256 * 1024):
|
||||
if not chunk:
|
||||
continue
|
||||
f.write(chunk)
|
||||
sha.update(chunk)
|
||||
_STATE["dl_received"] = _STATE.get("dl_received", 0) + len(chunk)
|
||||
total = _STATE["dl_total"]
|
||||
_STATE["dl_pct"] = int(_STATE["dl_received"] * 100 / total) if total else 0
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("下载 Chrome 安装包失败:%s", _exc)
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = f"安装包下载失败({_exc.__class__.__name__})"
|
||||
_cleanup_part()
|
||||
return
|
||||
if expect and sha.hexdigest() != expect:
|
||||
_LOGGER.error("Chrome 安装包 sha256 校验失败")
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = "安装包校验失败,请重试"
|
||||
_cleanup_part()
|
||||
return
|
||||
try:
|
||||
os.replace(tmp, pkg)
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("Chrome 安装包落盘失败:%s", _exc)
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = "安装包保存失败"
|
||||
_cleanup_part()
|
||||
return
|
||||
global _PENDING_PKG
|
||||
_PENDING_PKG = pkg
|
||||
_STATE["dl_status"] = "downloaded"
|
||||
_STATE["dl_pct"] = 100
|
||||
_STATE["dl_received"] = _STATE["dl_total"]
|
||||
_LOGGER.info("Chrome 安装包下载完成:%s", pkg)
|
||||
|
||||
|
||||
def _cleanup_part() -> None:
|
||||
try:
|
||||
for p in _CHROME_CACHE.glob("*.part"):
|
||||
p.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
# ===================== 安装 =====================
|
||||
|
||||
def install() -> dict:
|
||||
"""静默安装已下载的 Chrome 安装包。返回立即,安装后台进行。"""
|
||||
pkg = _PENDING_PKG
|
||||
if not pkg or not pkg.is_file():
|
||||
raise FileNotFoundError("未找到已下载的 Chrome 安装包")
|
||||
_STATE["installing"] = True
|
||||
_LOGGER.info("开始静默安装 Chrome:%s", pkg)
|
||||
# Chrome 官方安装器:/silent 静默 + /install 装机(对未登录用户安装)
|
||||
subprocess.Popen(
|
||||
[str(pkg), "/silent", "/install"],
|
||||
cwd=str(pkg.parent), creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
|
||||
# 安装完成后由前端轮询 installed 状态感知成功
|
||||
threading.Thread(target=_poll_install, daemon=True, name="chrome-install-watch").start()
|
||||
return {"ok": True, "installing": True}
|
||||
|
||||
|
||||
def _poll_install() -> None:
|
||||
"""轮询等待 Chrome 装好(最长 ~5 分钟),完成后重置 downloading 态供再次检测。"""
|
||||
import time
|
||||
for _ in range(60):
|
||||
time.sleep(5)
|
||||
if detect_local()["installed"]:
|
||||
_STATE["installing"] = False
|
||||
_STATE["installed"] = True
|
||||
_STATE["version"] = detect_local()["version"]
|
||||
_LOGGER.info("Chrome 安装完成:%s", _STATE["version"])
|
||||
return
|
||||
_STATE["installing"] = False
|
||||
_LOGGER.warning("等待 Chrome 安装完成超时")
|
||||
@@ -24,6 +24,11 @@ else:
|
||||
|
||||
PORT = 8799
|
||||
|
||||
# 插件本地配置目录:per-plugin JSON 持久化(账号密码/仓库编码等个性化配置)。
|
||||
# 放 %LOCALAPPDATA% 下:按 Windows 用户隔离、清浏览器缓存不丢、壳子升级不丢。
|
||||
PLUGIN_CONFIG_DIR = (Path(os.getenv("LOCALAPPDATA") or os.getenv("APPDATA") or Path.home())
|
||||
/ "37duAutomation" / "plugin_configs")
|
||||
|
||||
|
||||
def _load_dotenv() -> None:
|
||||
"""轻量读取 webhost/.env,灌入 os.environ(仅当变量缺失时)。UTF-8、'#'/'空行'跳过。"""
|
||||
@@ -45,12 +50,17 @@ def _load_dotenv() -> None:
|
||||
|
||||
_load_dotenv()
|
||||
|
||||
# ==================== 插件权限源(阶段二:控制面接口;默认全量兜底) ====================
|
||||
PLUGIN_SOURCE = os.getenv("PLUGIN_SOURCE", "all") # all | controlplane
|
||||
# ==================== 插件权限源(控制面拉取 + 本地缓存,见 cpapi._resolve_allowed) ====================
|
||||
CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/")
|
||||
CONTROLPLANE_ACCOUNT = os.getenv("CONTROLPLANE_ACCOUNT", "")
|
||||
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
# 钉钉扫码登录(可选):配置了钉钉开放平台应用后前端显示扫码入口。
|
||||
# 未配置时仅保留账号+密码登录。真实扫码 OAuth 在中心机换取工号/姓名后走 /api/admin/dingtalk/login。
|
||||
# 兼容旧配置名 DINGTALK_APPKEY:任一名非空即视为已启用扫码。
|
||||
DINGTALK_APP_KEY = os.getenv("DINGTALK_APP_KEY", "") or os.getenv("DINGTALK_APPKEY", "")
|
||||
# ==================== 敏感凭证中心化下发(唯一来源:中心机下发/本地加密缓存) ====================
|
||||
# 钉钉扫码 URL 已改由控制面代理构造(/api/dingtalk/login-url),执行机不再消费下发的钉钉凭证值;
|
||||
# apply_creds 仅保留进程级覆盖存储,供未来每账号敏感值下发能力使用(当前无消费点)。
|
||||
# 启动时由 main.py 调 creds_sync.load() 从中心机拉取(RSA 解密)后经 apply_creds() 注入。
|
||||
_CREDS_OVERRIDE: dict = {}
|
||||
|
||||
|
||||
def apply_creds(values: dict) -> None:
|
||||
"""把中心机下发的敏感凭证写入进程级覆盖 dict(敏感值唯一来源,不做本地 .env 回退)。"""
|
||||
_CREDS_OVERRIDE.update(values or {})
|
||||
@@ -5,7 +5,10 @@
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import HTTPException, Request
|
||||
|
||||
@@ -16,32 +19,76 @@ from webhost.backend.core.session import _sess_account
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _resolve_allowed() -> set | None:
|
||||
"""按权限源决定可加载插件白名单。None = 全量加载(默认/控制面不可达兜底)。"""
|
||||
if config.PLUGIN_SOURCE != "controlplane" or not config.CONTROLPLANE_URL:
|
||||
_ALLOW_CACHE = (Path(os.environ.get("LOCALAPPDATA") or os.environ.get("APPDATA") or Path.home())
|
||||
/ "37duAutomation" / "plugin_allow.json")
|
||||
|
||||
|
||||
def _save_allowed_cache(ids: set) -> None:
|
||||
"""权限清单落盘缓存(登录拉取时写入,离线/中心机不可达时直接复用)。"""
|
||||
try:
|
||||
_ALLOW_CACHE.parent.mkdir(parents=True, exist_ok=True)
|
||||
_ALLOW_CACHE.write_text(json.dumps(sorted(ids), ensure_ascii=False), encoding="utf-8")
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("插件权限清单缓存写入失败: %s", _exc)
|
||||
|
||||
|
||||
def _load_allowed_cache() -> set | None:
|
||||
"""读权限清单缓存;无缓存/损坏返回 None。"""
|
||||
if not _ALLOW_CACHE.is_file():
|
||||
return None
|
||||
if not config.CONTROLPLANE_ACCOUNT:
|
||||
_LOGGER.warning("PLUGIN_SOURCE=controlplane 但未设置 CONTROLPLANE_ACCOUNT,回退全量加载")
|
||||
try:
|
||||
raw = json.loads(_ALLOW_CACHE.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
return {str(x) for x in (raw or [])}
|
||||
|
||||
|
||||
def _resolve_allowed() -> set:
|
||||
"""插件权限白名单(fail-closed,绝不回退全量):控制面拉取 + 本地缓存。
|
||||
|
||||
语义:
|
||||
- 未登录(无恢复会话账号)→ 无权限,返回空集(零权限,不加载任何插件);
|
||||
- 登录过 → 拉取账号插件清单并落盘缓存;后续离线直接复用缓存清单;
|
||||
- 有账号但离线且无缓存 → 空集(无权限依据,fail-closed 防越权)。
|
||||
"""
|
||||
if not config.CONTROLPLANE_URL:
|
||||
return set()
|
||||
from webhost.backend.core.session import _sess_active_account
|
||||
account = config.CONTROLPLANE_ACCOUNT or _sess_active_account()
|
||||
if not account:
|
||||
_LOGGER.info("未登录(无会话账号),插件零权限加载")
|
||||
return set()
|
||||
import requests
|
||||
|
||||
headers = {"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/plugins",
|
||||
params={"account": config.CONTROLPLANE_ACCOUNT},
|
||||
headers=headers, timeout=5)
|
||||
params={"account": account}, headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
allowed = {p["id"] for p in r.json().get("plugins", [])}
|
||||
_LOGGER.info("控制面权限清单(%s):%s", config.CONTROLPLANE_ACCOUNT,
|
||||
sorted(allowed) or "(空)")
|
||||
_LOGGER.info("控制面权限清单(%s):%s", account, sorted(allowed) or "(空)")
|
||||
_save_allowed_cache(allowed)
|
||||
return allowed
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.error("拉取控制面权限清单失败,回退全量加载:%s", _exc)
|
||||
return None
|
||||
except Exception as _exc: # noqa: BLE001 不可达/失败:缓存兜底,无缓存零权限
|
||||
cached = _load_allowed_cache()
|
||||
if cached is not None:
|
||||
_LOGGER.info("权限清单拉取失败,用本地缓存(%s):%s", account, _exc)
|
||||
return cached
|
||||
_LOGGER.warning("权限清单拉取失败且无缓存,插件零权限加载:%s", _exc)
|
||||
return set()
|
||||
|
||||
|
||||
def _cp_headers(request: Request) -> dict:
|
||||
h = {"X-Admin-User": _sess_account(request)}
|
||||
"""构造到中心机的调用头:优先带「当前登录账号的云令牌」(登录时中心机签发,中心机
|
||||
_cloud_account 据此定位用户),不再依赖 CONTROLPLANE_TOKEN;X-Admin-User 仅作兜底。"""
|
||||
from webhost.backend.core.session import _ACCT_CLOUD_TOKEN
|
||||
h = {}
|
||||
account = _sess_account(request)
|
||||
if account:
|
||||
_cloud_tok = (_ACCT_CLOUD_TOKEN or {}).get(account)
|
||||
if _cloud_tok:
|
||||
h["Authorization"] = f"Bearer {_cloud_tok}"
|
||||
h["X-Admin-User"] = account
|
||||
if config.CONTROLPLANE_TOKEN:
|
||||
h["X-API-Token"] = config.CONTROLPLANE_TOKEN
|
||||
return h
|
||||
@@ -65,21 +112,36 @@ def _cp_call(method: str, path: str, **kw) -> dict:
|
||||
def _sync_licensing(account: str) -> None:
|
||||
"""联网拉取并缓存 中心机公钥 + 该账号离线授权票据 + 管控清单;成功后补报离线记录。
|
||||
|
||||
离线票据/管控清单持久化到 %LOCALAPPDATA%\\37duAutomation,供断网时在线验签运行。
|
||||
逐资源容错:公钥/授权票据/管控清单各自 try,单个接口失败不阻断其余(成功部分照常落盘
|
||||
+ touch_sync),保证一次刷新尽量完整;全部失败也静默,调用方按本地缓存兜底。
|
||||
"""
|
||||
if not config.CONTROLPLANE_URL or not account:
|
||||
return
|
||||
import requests
|
||||
|
||||
headers = {"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/me/pubkey", headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
licensing.cache_public_key(r.json().get("pub", ""))
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/me/license",
|
||||
params={"account": account}, headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
licensing.save_license(r.json())
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/me/control-list", headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
licensing.save_control(r.json())
|
||||
licensing.flush_offline_reports()
|
||||
got_any = False
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/me/pubkey", headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
licensing.cache_public_key(r.json().get("pub", ""))
|
||||
got_any = True
|
||||
except Exception as _exc: # noqa: BLE001 公钥拉取失败不阻断授权/管控刷新
|
||||
_LOGGER.warning("中心机公钥拉取失败:%s", _exc)
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/me/license",
|
||||
params={"account": account}, headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
licensing.save_license(r.json())
|
||||
got_any = True
|
||||
except Exception as _exc: # noqa: BLE001 授权票据拉取失败不阻断公钥/管控刷新
|
||||
_LOGGER.warning("离线授权票据拉取失败:%s", _exc)
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/me/control-list", headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
licensing.save_control(r.json())
|
||||
got_any = True
|
||||
except Exception as _exc: # noqa: BLE001 管控清单拉取失败不阻断公钥/授权刷新
|
||||
_LOGGER.warning("管控清单拉取失败:%s", _exc)
|
||||
if got_any:
|
||||
licensing.flush_offline_reports()
|
||||
@@ -0,0 +1,61 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""执行机敏感凭证:RSA 密钥对管理(私钥本机持久化,公钥上报中心机用于加密下发)。
|
||||
|
||||
- 首启生成 RSA-2048 密钥对,私钥 PKCS8(PEM) 落盘
|
||||
%LOCALAPPDATA%\\37duAutomation\\creds\\id_rsa.pem(公钥由私钥导出)。
|
||||
- 私钥必须在执行机本机可解(解密中心机下发的敏感凭证),故本机明文存私钥是必要权衡
|
||||
(与现有 %LOCALAPPDATA%\\37duAutomation\\.env 同级保护;如需更高级别可后续加 DPAPI,本期不做)。
|
||||
- 公钥上报中心机后,中心机用它 OAEP-SHA256 逐个加密敏感值下发,本机私钥解密。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import padding, rsa
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_CREDS_DIR = (Path(os.environ.get("LOCALAPPDATA") or os.environ.get("APPDATA") or Path.home())
|
||||
/ "37duAutomation" / "creds")
|
||||
_PRIV_PATH = _CREDS_DIR / "id_rsa.pem"
|
||||
|
||||
|
||||
def _load_or_create() -> rsa.RSAPrivateKey:
|
||||
"""加载本机 RSA 私钥;不存在则生成 RSA-2048 并持久化(重启复用)。"""
|
||||
if _PRIV_PATH.is_file():
|
||||
try:
|
||||
_key = serialization.load_pem_private_key(_PRIV_PATH.read_bytes(), password=None)
|
||||
if isinstance(_key, rsa.RSAPrivateKey):
|
||||
return _key
|
||||
except (ValueError, TypeError, OSError) as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("读取 RSA 私钥失败,重新生成: %s", _exc)
|
||||
_CREDS_DIR.mkdir(parents=True, exist_ok=True)
|
||||
_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||
_PRIV_PATH.write_bytes(_key.private_bytes(
|
||||
serialization.Encoding.PEM,
|
||||
serialization.PrivateFormat.PKCS8,
|
||||
serialization.NoEncryption()))
|
||||
return _key
|
||||
|
||||
|
||||
_priv = _load_or_create() # 进程内复用同一私钥
|
||||
|
||||
|
||||
def public_key_pem() -> str:
|
||||
"""本机 RSA 公钥 PEM(上报中心机用)。"""
|
||||
return _priv.public_key().public_bytes(
|
||||
serialization.Encoding.PEM,
|
||||
serialization.PublicFormat.SubjectPublicKeyInfo).decode()
|
||||
|
||||
|
||||
def decrypt(cipher_b64: str) -> str:
|
||||
"""用本机私钥 OAEP-SHA256 解密密文 base64 → 明文(与服务端 rsa_encrypt 对称)。"""
|
||||
_ct = base64.b64decode(cipher_b64)
|
||||
_pt = _priv.decrypt(_ct, padding.OAEP(
|
||||
mgf=padding.MGF1(algorithm=hashes.SHA256()),
|
||||
algorithm=hashes.SHA256(), label=None))
|
||||
return _pt.decode("utf-8")
|
||||
@@ -0,0 +1,133 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""执行机敏感凭证下发与缓存:中心机在线拉取(RSA 解密) + 加密缓存(离线复用)。
|
||||
|
||||
流程:
|
||||
sync(): 有登录云令牌且中心机可达 →
|
||||
1. POST /api/admin/creds/register 上报本机 RSA 公钥(幂等 upsert,本人云令牌可登记)
|
||||
2. GET /api/admin/creds (Bearer) 拉取 {key: base64(RSA 密文)}——服务端仅管理员可拉,
|
||||
员工账号 403 会走缓存(本地无密文则为空,不影响业务)
|
||||
3. 本机私钥逐个解密 → 返回明文 dict
|
||||
4. 拉到的密文 JSON 原样写缓存 %LOCALAPPDATA%\\37duAutomation\\creds\\cache.json
|
||||
(落盘的是密文,叠加中心机加密层)
|
||||
load(): 中心机可达走 sync();不可达/无云令牌则读缓存密文用私钥解密(离线可用)。
|
||||
|
||||
敏感键白名单与服务端 config_push._ALLOWED_KEYS 保持一致(仅钉钉开放平台凭证;
|
||||
HR/OA 平台登录账号由本地加密存储 platform_accounts,不经中心机)。
|
||||
钉钉扫码 URL 已由控制面代理构造(/api/dingtalk/login-url),本模块下发的值当前无消费点,
|
||||
链路保留供未来每账号敏感值下发能力使用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend.core import config
|
||||
from webhost.backend.core.creds_store import decrypt, public_key_pem
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 与服务端 apis/config_push.py _ALLOWED_KEYS 保持一致(双重保障:下发限定范围)
|
||||
_ALLOWED_KEYS = (
|
||||
"DINGTALK_APPKEY", "DINGTALK_APPSECRET", "DINGTALK_AGENT_ID", "DINGTALK_CORP_ID",
|
||||
)
|
||||
|
||||
_CACHE_DIR = (Path(os.environ.get("LOCALAPPDATA") or os.environ.get("APPDATA") or Path.home())
|
||||
/ "37duAutomation" / "creds")
|
||||
_CACHE_FILE = _CACHE_DIR / "cache.json"
|
||||
|
||||
|
||||
def _cloud_token(account: str) -> str:
|
||||
"""当前账号的云端会话 token(登录时中心机签发,进程内存态;重启后需重新登录才有)。"""
|
||||
from webhost.backend.core.session import _ACCT_CLOUD_TOKEN
|
||||
return (_ACCT_CLOUD_TOKEN or {}).get(account) or ""
|
||||
|
||||
|
||||
def _headers(account: str) -> dict:
|
||||
h = {"Authorization": f"Bearer {_cloud_token(account)}"}
|
||||
if config.CONTROLPLANE_TOKEN:
|
||||
h["X-API-Token"] = config.CONTROLPLANE_TOKEN
|
||||
return h
|
||||
|
||||
|
||||
def _save_cache(encrypted: dict) -> None:
|
||||
"""密文 JSON 原样落盘(落盘的是密文,叠加中心机加密层;离线用私钥解密)。"""
|
||||
try:
|
||||
_CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
_CACHE_FILE.write_text(json.dumps(encrypted, ensure_ascii=False), encoding="utf-8")
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("敏感凭证缓存写入失败: %s", _exc)
|
||||
|
||||
|
||||
def _load_cache() -> dict:
|
||||
"""读缓存密文并用本机私钥解密为明文 dict;缺失/解密失败返回空 dict(不阻断)。"""
|
||||
if not _CACHE_FILE.is_file():
|
||||
return {}
|
||||
try:
|
||||
raw = json.loads(_CACHE_FILE.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
out = {}
|
||||
for _k, _b64 in (raw or {}).items():
|
||||
if _k not in _ALLOWED_KEYS:
|
||||
continue
|
||||
try:
|
||||
out[_k] = decrypt(_b64)
|
||||
except Exception: # noqa: BLE001 单值解密失败跳过(如密钥更换后旧缓存)
|
||||
_LOGGER.warning("敏感凭证缓存解密失败: %s", _k)
|
||||
return out
|
||||
|
||||
|
||||
def sync(account: str) -> dict | None:
|
||||
"""中心机在线拉取并解密敏感凭证,返回明文 dict;不可用返回 None(走缓存兜底)。"""
|
||||
if not config.CONTROLPLANE_URL or not account or not _cloud_token(account):
|
||||
return None
|
||||
import requests
|
||||
|
||||
try:
|
||||
# 1. 上报本机 RSA 公钥(幂等 upsert;中心机用该公钥加密下发)
|
||||
r = requests.post(f"{config.CONTROLPLANE_URL}/api/admin/creds/register",
|
||||
json={"account": account, "pubkey_pem": public_key_pem()},
|
||||
headers=_headers(account), timeout=10)
|
||||
r.raise_for_status()
|
||||
# 2. 拉取加密后的敏感凭证
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/admin/creds",
|
||||
headers=_headers(account), timeout=10)
|
||||
r.raise_for_status()
|
||||
encrypted = r.json().get("creds") or {}
|
||||
except Exception as _exc: # noqa: BLE001 中心机不可达/鉴权失败 → 走缓存
|
||||
_LOGGER.warning("中心机敏感凭证拉取失败(用本地缓存): %s", _exc)
|
||||
return None
|
||||
if not encrypted:
|
||||
return {}
|
||||
# 3. 本机私钥逐个解密
|
||||
out = {}
|
||||
for _k, _b64 in encrypted.items():
|
||||
if _k not in _ALLOWED_KEYS:
|
||||
continue
|
||||
try:
|
||||
out[_k] = decrypt(_b64)
|
||||
except Exception as _exc: # noqa: BLE001 单值解密失败跳过
|
||||
_LOGGER.warning("敏感凭证解密失败: %s", _k)
|
||||
# 4. 密文原样落盘缓存(离线复用)
|
||||
_save_cache(encrypted)
|
||||
return out
|
||||
|
||||
|
||||
def load(account: str = "") -> dict:
|
||||
"""获取当前账号敏感凭证明文:中心机可达走 sync();否则读缓存密文解密(离线可用)。
|
||||
|
||||
返回 dict[key]=明文,仅含成功解密项;空 dict 表示无可用的下发值(不阻断启动)。
|
||||
"""
|
||||
account = account or config.CONTROLPLANE_ACCOUNT
|
||||
if not account:
|
||||
from webhost.backend.core.session import _sess_active_account
|
||||
account = _sess_active_account()
|
||||
synced = sync(account)
|
||||
if synced is not None:
|
||||
return synced
|
||||
cached = _load_cache()
|
||||
if cached:
|
||||
_LOGGER.info("使用本地敏感凭证缓存(中心机不可达或无云令牌)")
|
||||
return cached
|
||||
@@ -125,6 +125,43 @@ def verify_control() -> dict:
|
||||
return {"revokedPlugins": [], "disabledPlugins": [], "forcedUpdates": []}
|
||||
|
||||
|
||||
# ==================== 授权周期(离线最多 LICENSE_TTL_DAYS 天) ====================
|
||||
def license_status() -> tuple[str, dict | None]:
|
||||
"""本地授权票据状态:("ok", payload) / ("missing", None) / ("invalid", None) / ("expired", payload)。
|
||||
|
||||
过期判定以票据内 expiresAt(控制面签发,issuedAt + 7 天)为基准;缺该字段一律视为过期
|
||||
(fail-safe,触发联网刷新,不因旧票据而永久放行)。
|
||||
"""
|
||||
if not license_path.is_file():
|
||||
return ("missing", None)
|
||||
try:
|
||||
lic = verify_license()
|
||||
except ValueError:
|
||||
return ("invalid", None)
|
||||
exp = lic.get("expiresAt")
|
||||
if not exp or time.time() > int(exp):
|
||||
return ("expired", lic)
|
||||
return ("ok", lic)
|
||||
|
||||
|
||||
def ensure_license(account: str) -> tuple[bool, dict | None]:
|
||||
"""确保本地授权票据可用:ok → (True, payload);否则联网刷新一次后复查。
|
||||
|
||||
刷新失败(离线/控制面不可达)→ (False, None)。这是「可见性/运行/平台登录」的统一授权门禁,
|
||||
过期且实际在线时会自动刷新恢复(用户无感),离线则拒绝并提示联网刷新。
|
||||
"""
|
||||
status, payload = license_status()
|
||||
if status == "ok":
|
||||
return True, payload
|
||||
try:
|
||||
from webhost.backend.core.cpapi import _sync_licensing # 延迟导入,避免模块环
|
||||
_sync_licensing(account)
|
||||
except Exception as _exc: # noqa: BLE001 联网刷新失败(离线/控制面不可达)
|
||||
_LOGGER.warning("授权票据联网刷新失败(离线或控制面不可达):%s", _exc)
|
||||
status, payload = license_status()
|
||||
return (status == "ok"), payload
|
||||
|
||||
|
||||
# ==================== 缓存写读 ====================
|
||||
def save_license(ticket_json: dict | str) -> None:
|
||||
"""持久化授权票据。ticket 可为 {ticket,...} 或原始签名串。"""
|
||||
@@ -149,24 +186,24 @@ def save_control(ticket_json: dict | str) -> None:
|
||||
def run_check_allowed(plugin_id: str, account: str, online: bool) -> str | None:
|
||||
"""启动前校验链(离线/联网通用骨架),返回 None=可运行,否则返回拒绝原因字符串。
|
||||
|
||||
- 授权周期:本地票据须有效(7 天窗口,见 ensure_license);缺失/过期先联网刷新一次,
|
||||
仍不可用则拒绝(离线超期必须联网更新票据)。
|
||||
- 验签授权票据,校验该插件 canRun。
|
||||
- 下架/禁用(用本地缓存清单;联网时旧缓存同样先校验,联网后再拉最新)。
|
||||
- 离线:跳过强制更新 deadline 检查(不联网一直能用)。
|
||||
- 联网:额外校验强制更新 deadline 已过则拒启旧版本。
|
||||
"""
|
||||
ok, lic = ensure_license(account)
|
||||
if not ok:
|
||||
return "授权已过期(最长离线 7 天),请联网刷新后重试"
|
||||
|
||||
control = verify_control()
|
||||
if plugin_id in control.get("revokedPlugins", []):
|
||||
return "插件已被下架(revoked),禁止运行"
|
||||
if plugin_id in control.get("disabledPlugins", []):
|
||||
return "插件已被禁用(disabled),禁止运行"
|
||||
|
||||
# 授权:先验签本地授权票据(离线可用)
|
||||
try:
|
||||
lic = verify_license()
|
||||
except Exception as _exc: # noqa: BLE001 授权票据不可用
|
||||
return f"本地授权票据校验失败:{_exc}" if online else "本地授权票据校验失败"
|
||||
|
||||
lic_plugins = {p.get("pluginId"): p for p in lic.get("plugins", [])}
|
||||
lic_plugins = {p.get("pluginId"): p for p in (lic or {}).get("plugins", [])}
|
||||
grant = lic_plugins.get(plugin_id)
|
||||
if not grant:
|
||||
return f"账号 {account} 无插件「{plugin_id}」的授权"
|
||||
|
||||
@@ -12,7 +12,6 @@ import sys
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend.core import config
|
||||
from webhost.backend.core.session import _ACCT_CLOUD_TOKEN
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -35,6 +34,7 @@ def _plugin_schema(p) -> dict:
|
||||
perms = (manifest or {}).get("permissions") or p.permissions
|
||||
return {"id": p.id, "name": name, "version": p.version,
|
||||
"description": description, "uses_month": getattr(p, "uses_month", False),
|
||||
"ui": bool((manifest or {}).get("ui")),
|
||||
"capabilities": caps, "permissions": perms, "fields": fields}
|
||||
|
||||
|
||||
@@ -64,6 +64,13 @@ def _fields_from_schema(schema: dict) -> list | None:
|
||||
elif t == "string" and "enum" in prop:
|
||||
item["type"] = "select"
|
||||
item["options"] = prop["enum"]
|
||||
elif t == "string" and prop.get("format") == "password":
|
||||
item["type"] = "password"
|
||||
elif t == "array":
|
||||
# 多选:items.enum 为预设选项;无 enum 则纯自由输入(前端 tags 可自建条目)
|
||||
item["type"] = "multiselect"
|
||||
if isinstance(prop.get("items"), dict) and "enum" in prop["items"]:
|
||||
item["options"] = prop["items"]["enum"]
|
||||
else:
|
||||
item["type"] = "text"
|
||||
d = prop.get("description")
|
||||
@@ -86,29 +93,4 @@ def _account_allowed_platforms(account: str) -> set | None:
|
||||
r.raise_for_status()
|
||||
return set(r.json().get("allowed", []))
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
|
||||
|
||||
def _cloud_plugin_ids(account: str) -> set | None:
|
||||
"""已登录且有云端会话 token 时,用 Bearer 向中心机 /api/plugins 拉账号可用插件 id 集(§2.2)。
|
||||
|
||||
降级策略(三态):
|
||||
- 200 → 返回账号允许的插件 id 集(真正按员工权限过滤)
|
||||
- 401 → 云端可达但 token 失效(如云端重启):返回空集,**不给全量**,防越权泄露
|
||||
- 其它(超时/断连/5xx) → 返回 None,调用方按离线兜底放行本地全量(§2.5)
|
||||
"""
|
||||
token = (_ACCT_CLOUD_TOKEN or {}).get(account) if account else None
|
||||
if not token or not config.CONTROLPLANE_URL:
|
||||
return None
|
||||
import requests
|
||||
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/plugins",
|
||||
headers={"Authorization": f"Bearer {token}"}, timeout=5)
|
||||
except Exception: # noqa: BLE001 云端不可达 → 离线兜底
|
||||
return None
|
||||
if r.status_code == 401:
|
||||
return set()
|
||||
if r.status_code != 200:
|
||||
return None
|
||||
return {p["id"] for p in r.json().get("plugins", [])}
|
||||
return None
|
||||
@@ -5,6 +5,9 @@
|
||||
缺失/落后则走 download-ticket 一次性票据下载 zip → sha256 校验 → 解压到
|
||||
plugins/<id>/ 原子替换;更新成功后由宿主重载插件注册表。
|
||||
|
||||
本地清理:云端清单可达时,本地存在但不在清单中的插件(中心机已删除/已收回
|
||||
授权)同步移除本地目录;清单不可达(离线)时不动本地,保证离线可继续运行。
|
||||
|
||||
降级策略:
|
||||
- 控制面不可达/未配置 → 跳过同步,沿用本地已有插件(离线可继续运行)
|
||||
- 单个插件下载/校验/解压失败 → 记 ERROR 跳过,不影响其它插件与本地旧版本
|
||||
@@ -17,6 +20,7 @@ import json
|
||||
import logging
|
||||
import shutil
|
||||
import tempfile
|
||||
import threading
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
@@ -25,9 +29,13 @@ from webhost.backend.plugins import _PLUGINS_ROOT
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_DL_TIMEOUT = 30 # 包下载超时(秒)
|
||||
_DL_TIMEOUT = 300 # 包下载超时(秒);插件包含 ui 资源可达数 MB,留足弱网余量
|
||||
_MAX_PKG_BYTES = 200 * 1024 * 1024 # 包大小上限,与控制面一致
|
||||
|
||||
# 同步串行锁:启动后台同步 / 登录后同步 / 手动刷新共用,防止并发同步互相覆盖
|
||||
# (后完成的旧账号白名单 set_allowed+reload 会清掉刚同步好的插件清单)
|
||||
SYNC_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def _headers() -> dict:
|
||||
h = {}
|
||||
@@ -145,14 +153,62 @@ def _install_pkg(plugin_id: str, content: bytes) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
def _local_plugin_entries() -> list:
|
||||
"""本地已落盘的插件条目(目录包 + 旧式单文件),发现规则与 plugins._discover_modules 对齐。
|
||||
|
||||
目录包:含 __init__.py 或 plugin.json(后者兜底覆盖下载中断的残缺目录);
|
||||
单文件:排除 __init__/base 与 `_` 前缀私有文件。
|
||||
"""
|
||||
out = []
|
||||
for entry in _PLUGINS_ROOT.iterdir():
|
||||
if entry.name.startswith("_") or entry.name == "__pycache__":
|
||||
continue
|
||||
if entry.is_dir():
|
||||
if (entry / "__init__.py").is_file() or (entry / "plugin.json").is_file():
|
||||
out.append(entry)
|
||||
elif entry.suffix == ".py" and entry.name not in ("__init__.py", "base.py"):
|
||||
out.append(entry)
|
||||
return out
|
||||
|
||||
|
||||
def _prune_stale(keep_ids: set) -> list:
|
||||
"""清理中心机已删除/已收回授权的本地插件(仅在云端清单成功拉取后调用)。
|
||||
|
||||
设备正有任务执行时整轮跳过(避免动到运行中插件的文件),留待下次同步补删;
|
||||
单个目录删除失败记 WARNING 跳过,不影响其它清理与本次同步。
|
||||
"""
|
||||
from webhost.backend.core import scheduler
|
||||
|
||||
if not _PLUGINS_ROOT.is_dir() or scheduler._is_busy():
|
||||
return []
|
||||
removed = []
|
||||
for entry in _local_plugin_entries():
|
||||
pid = entry.stem if entry.is_file() else entry.name
|
||||
if pid in keep_ids:
|
||||
continue
|
||||
try:
|
||||
if entry.is_dir():
|
||||
shutil.rmtree(entry)
|
||||
else:
|
||||
entry.unlink()
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("清理本地插件 %s 失败:%s", pid, _exc)
|
||||
continue
|
||||
removed.append(pid)
|
||||
_LOGGER.info("插件 %s 已在中心机删除/收回授权,本地目录同步移除", pid)
|
||||
return removed
|
||||
|
||||
|
||||
def sync_plugins(account: str) -> dict:
|
||||
"""按账号权限同步插件(首次下载 + 版本更新)。离线/失败静默降级,返回统计。"""
|
||||
result = {"downloaded": [], "updated": [], "up_to_date": [], "failed": []}
|
||||
"""按账号权限同步插件(首次下载 + 版本更新 + 清理已删除)。离线/失败静默降级,返回统计。"""
|
||||
result = {"downloaded": [], "updated": [], "up_to_date": [], "failed": [], "removed": []}
|
||||
if not config.CONTROLPLANE_URL or not account:
|
||||
return result
|
||||
manifest = _cloud_plugin_manifest(account)
|
||||
if manifest is None:
|
||||
return result
|
||||
# 中心机已删除/收回授权的插件:本地同步清理(云端清单不可达时不动本地)
|
||||
result["removed"] = _prune_stale({p.get("id", "") for p in manifest})
|
||||
for p in manifest:
|
||||
pid = p.get("id", "")
|
||||
ver = p.get("version", "") or p.get("latest_version", "")
|
||||
@@ -179,7 +235,7 @@ def sync_plugins(account: str) -> dict:
|
||||
(result["updated"] if local else result["downloaded"]).append(pid)
|
||||
else:
|
||||
result["failed"].append(pid)
|
||||
_LOGGER.info("插件同步完成:下载=%s 更新=%s 最新=%s 失败=%s",
|
||||
_LOGGER.info("插件同步完成:下载=%s 更新=%s 最新=%s 清理=%s 失败=%s",
|
||||
result["downloaded"], result["updated"],
|
||||
result["up_to_date"], result["failed"])
|
||||
result["up_to_date"], result["removed"], result["failed"])
|
||||
return result
|
||||
|
||||
@@ -87,4 +87,11 @@ def _require_login(request: Request) -> str:
|
||||
return account
|
||||
|
||||
|
||||
def _sess_active_account() -> str:
|
||||
"""取最近活跃的本机会话账号(重启恢复的会话;CONTROLPLANE_ACCOUNT 不再配置时的兜底)。"""
|
||||
with _SESS_LOCK:
|
||||
items = sorted(_SESS.values(), key=lambda _it: _it[1], reverse=True)
|
||||
return items[0][0] if items else ""
|
||||
|
||||
|
||||
_sess_load() # 启动即恢复本机会话(重启后端不丢会话)
|
||||
@@ -1,13 +1,20 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""执行机壳子(主程序)自动更新:自动下载新版安装包,由用户点击触发静默升级重启。
|
||||
"""执行机壳子(主程序)自动更新:检查 → 用户确认下载(带进度)→ 点击重启升级。
|
||||
|
||||
流程(对应前端交互):
|
||||
1. 检查+下载:启动时后台检查控制面 /api/shell/version,版本落后则自动把新版安装包
|
||||
下载到 %LOCALAPPDATA%\\37duAutomation\\shell\\(本地缓存,不打断用户)。
|
||||
2. 应用:前端提示"发现新版本"后用户点击 → apply_update() 运行安装包
|
||||
1. 检查:启动时/每 30 分钟/手动"检查更新",只比对控制面 /api/shell/version,
|
||||
秒级返回"有新版/已是最新/不可达",不下载大包。发现新版后由前端提示用户,
|
||||
由用户决定是否下载(不默默后台拉包)。
|
||||
2. 下载:用户点击"立即下载" → 后台流式下载到
|
||||
%LOCALAPPDATA%\\37duAutomation\\shell\\(先写 .part 临时文件,完成校验后改名),
|
||||
进度(已下载/总量/百分比)写入状态供前端轮询展示。
|
||||
3. 应用:下载完成后前端提示"重启更新",用户点击 → apply_update() 运行安装包
|
||||
/VERYSILENT 静默覆盖安装,随后本进程退出,Inno CloseApplications 收尾,
|
||||
安装完成由 [Run] 自动重启新版本主程序。
|
||||
3. 离线/控制面不可达/校验失败:静默跳过,不影响使用。
|
||||
4. 离线/控制面不可达/校验失败:状态记录错误原因,前端提示,不影响使用。
|
||||
|
||||
并发控制:检查与下载各持独立锁(检查是 5s 的版本接口,下载是数百 MB 大包,
|
||||
两者互不阻塞)。下载内部再防重入,避免重复拉包。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -16,6 +23,7 @@ import logging
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
@@ -25,8 +33,36 @@ _LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 下载缓存的安装包目录:独立于程序目录(升级时不被覆盖/清理)
|
||||
_SHELL_CACHE = Path(os.environ.get("LOCALAPPDATA", str(Path.home()))) / "37duAutomation" / "shell"
|
||||
|
||||
# 检查互斥锁:启动/周期/手动三入口共用,检查期间视为"检查中"(pending_status.checking)
|
||||
_CHECK_LOCK = threading.Lock()
|
||||
# 下载互斥锁:防止并发重复下载同一大包
|
||||
_DL_LOCK = threading.Lock()
|
||||
|
||||
# 已下载待应用的新版本(模块内状态,供 update-status 查询)
|
||||
_PENDING: dict = {}
|
||||
_PENDING_VERSION = ""
|
||||
_PENDING_NOTES = ""
|
||||
|
||||
# 运行态(供前端轮询 update-status)
|
||||
_STATE: dict = {
|
||||
# 版本检查
|
||||
"checking": False, # 版本检查进行中(秒级,很快结束)
|
||||
"check_at": 0.0, # 最近一次检查完成时间
|
||||
"latest": "", # 云端最新版本
|
||||
"notes": "", # 云端最新版本更新说明
|
||||
"available": False, # 检测到可用新版本(当前 < 云端 且 尚未下载完成)
|
||||
"check_error": "", # 检查失败原因(控制面不可达/源码模式等)
|
||||
# 下载(流式,带进度)
|
||||
"dl_version": "", # 正在下载/刚下载完成的版本
|
||||
"dl_status": "idle", # idle | downloading | downloaded | failed
|
||||
"dl_received": 0, # 已下载字节
|
||||
"dl_total": 0, # 总字节(0 = 未知,无法算百分比)
|
||||
"dl_pct": 0, # 0-100
|
||||
"dl_error": "", # 下载失败原因
|
||||
"applying": False, # 正在静默安装升级
|
||||
}
|
||||
|
||||
_PERIODIC_INTERVAL = 30 * 60 # 周期检查间隔(秒)
|
||||
|
||||
|
||||
def local_shell_version() -> str:
|
||||
@@ -56,10 +92,10 @@ def _version_lt(a: str, b: str) -> bool:
|
||||
return a != b and a < b
|
||||
|
||||
|
||||
def check_and_download() -> dict | None:
|
||||
"""检查壳子更新并自动下载安装包到本地缓存。有可用更新返回 {version, notes};否则 None。"""
|
||||
cur = local_shell_version()
|
||||
if not cur or not config.CONTROLPLANE_URL:
|
||||
def fetch_cloud_version() -> dict | None:
|
||||
"""拉取控制面壳子版本信息;非打包运行/未配置/不可达返回 None(失败原因记入 _STATE)。"""
|
||||
if not local_shell_version() or not config.CONTROLPLANE_URL:
|
||||
_STATE["check_error"] = "源码开发模式,不参与自更新" if not local_shell_version() else "未配置中心机地址"
|
||||
return None
|
||||
import requests
|
||||
|
||||
@@ -67,38 +103,183 @@ def check_and_download() -> dict | None:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/shell/version",
|
||||
headers=_headers(), timeout=5)
|
||||
r.raise_for_status()
|
||||
info = r.json()
|
||||
return r.json()
|
||||
except Exception as _exc: # noqa: BLE001 离线/不可达
|
||||
_LOGGER.info("检查壳子更新失败(离线跳过):%s", _exc)
|
||||
_STATE["check_error"] = f"控制面不可达({_exc.__class__.__name__})"
|
||||
return None
|
||||
if not info.get("available") or not info.get("version"):
|
||||
return None
|
||||
cloud = str(info["version"])
|
||||
if not _version_lt(cur, cloud):
|
||||
return None
|
||||
|
||||
|
||||
# ===================== 检查(只比对版本,不下载) =====================
|
||||
|
||||
def check_update() -> None:
|
||||
"""只检查版本:比对控制面最新版,写入 _STATE。秒级完成,不下载大包。"""
|
||||
if not _CHECK_LOCK.acquire(blocking=False):
|
||||
return # 已有检查在进行,沿用其状态
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/shell/pkg",
|
||||
headers=_headers(), timeout=300)
|
||||
r.raise_for_status()
|
||||
data = r.content
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("下载壳子安装包失败:%s", _exc)
|
||||
return None
|
||||
_STATE["checking"] = True
|
||||
cur = local_shell_version()
|
||||
info = fetch_cloud_version()
|
||||
_STATE["check_at"] = time.time()
|
||||
if not cur:
|
||||
_STATE["latest"] = ""
|
||||
_STATE["notes"] = ""
|
||||
_STATE["available"] = False
|
||||
return
|
||||
if not info:
|
||||
_STATE["available"] = False
|
||||
return
|
||||
cloud = str(info.get("version") or "")
|
||||
notes = str(info.get("notes") or "")
|
||||
_STATE["latest"] = cloud
|
||||
_STATE["notes"] = notes
|
||||
_STATE["check_error"] = ""
|
||||
if not cloud or not _version_lt(cur, cloud):
|
||||
# 已是最新:清掉"待下载"占位(若之前处于 failed,供用户重试的 available 也置 False)
|
||||
_STATE["available"] = False
|
||||
return
|
||||
_STATE["available"] = True
|
||||
# 缓存中已有该版本安装包 → 恢复为"已下载待应用",提示重启更新
|
||||
if cached_pkg(cloud) is not None:
|
||||
_restore_pending(cloud, notes)
|
||||
finally:
|
||||
_STATE["checking"] = False
|
||||
_CHECK_LOCK.release()
|
||||
|
||||
|
||||
def _restore_pending(cloud: str, notes: str) -> None:
|
||||
"""把已落盘的安装包恢复为待应用状态(重启后/下载完成后沿用)。"""
|
||||
global _PENDING_VERSION, _PENDING_NOTES
|
||||
_PENDING_VERSION = cloud
|
||||
_PENDING_NOTES = notes
|
||||
_STATE["dl_version"] = cloud
|
||||
_STATE["dl_status"] = "downloaded"
|
||||
_STATE["dl_pct"] = 100
|
||||
_LOGGER.info("壳子新版本 %s 已在缓存中,等待用户重启更新", cloud)
|
||||
|
||||
|
||||
def start_check() -> None:
|
||||
"""后台线程触发一次检查(启动/手动入口):立即返回,结果经 pending_status 轮询获取。"""
|
||||
threading.Thread(target=check_update, daemon=True, name="shell-check").start()
|
||||
|
||||
|
||||
def start_periodic_check(interval: int = _PERIODIC_INTERVAL) -> None:
|
||||
"""常驻周期检查:壳子长开时也能自动发现新版本(只比对版本,不自动下载)。"""
|
||||
def _loop() -> None:
|
||||
while True:
|
||||
time.sleep(interval)
|
||||
try:
|
||||
check_update()
|
||||
except Exception as _exc: # noqa: BLE001 周期失败不中断循环
|
||||
_LOGGER.warning("周期检查壳子更新失败:%s", _exc)
|
||||
|
||||
threading.Thread(target=_loop, daemon=True, name="shell-check-loop").start()
|
||||
|
||||
|
||||
# ===================== 下载(流式 + 进度) =====================
|
||||
|
||||
def start_download() -> None:
|
||||
"""开始下载新版本安装包(后台线程)。已有下载/已完成则直接沿用,不重复拉包。"""
|
||||
cur = local_shell_version()
|
||||
if not cur:
|
||||
return
|
||||
if _STATE["dl_status"] == "downloading":
|
||||
return
|
||||
if _STATE["dl_status"] == "downloaded" and _PENDING_VERSION:
|
||||
return
|
||||
info = fetch_cloud_version()
|
||||
if not info:
|
||||
return
|
||||
cloud = str(info.get("version") or "")
|
||||
if not cloud or not _version_lt(cur, cloud):
|
||||
return
|
||||
if cached_pkg(cloud) is not None:
|
||||
_restore_pending(cloud, str(info.get("notes") or ""))
|
||||
return
|
||||
# 占位防重入,随后后台流式下载
|
||||
_STATE["dl_version"] = cloud
|
||||
_STATE["dl_status"] = "downloading"
|
||||
_STATE["dl_received"] = 0
|
||||
_STATE["dl_total"] = 0
|
||||
_STATE["dl_pct"] = 0
|
||||
_STATE["dl_error"] = ""
|
||||
threading.Thread(target=_download, args=(cloud, info), daemon=True,
|
||||
name="shell-download").start()
|
||||
_LOGGER.info("开始下载壳子新版本 %s", cloud)
|
||||
|
||||
|
||||
def _download(cloud: str, info: dict) -> None:
|
||||
try:
|
||||
with _DL_LOCK:
|
||||
_download_locked(cloud, info)
|
||||
except Exception as _exc: # noqa: BLE001 下载异常兜底
|
||||
_LOGGER.exception("下载壳子安装包异常")
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = f"下载异常({_exc.__class__.__name__})"
|
||||
_cleanup_part(cloud)
|
||||
|
||||
|
||||
def _download_locked(cloud: str, info: dict) -> None:
|
||||
import requests
|
||||
|
||||
# 中心机 version 接口新增 url 字段:有则直连内网文件服务器下载大包(无鉴权);
|
||||
# 为空回退中心机 /api/shell/pkg(该路径带 X-API-Token)。
|
||||
inner_url = (info.get("url") or "").strip()
|
||||
if inner_url:
|
||||
url = inner_url
|
||||
dl_headers = {}
|
||||
else:
|
||||
url = f"{config.CONTROLPLANE_URL}/api/shell/pkg"
|
||||
dl_headers = _headers()
|
||||
expect = (info.get("sha256") or "").lower()
|
||||
if expect and hashlib.sha256(data).hexdigest() != expect:
|
||||
_LOGGER.error("壳子安装包 sha256 校验失败,放弃更新")
|
||||
return None
|
||||
tmp = _SHELL_CACHE / f"setup-37du-host-{cloud}.exe.part"
|
||||
pkg = _SHELL_CACHE / f"setup-37du-host-{cloud}.exe"
|
||||
try:
|
||||
_SHELL_CACHE.mkdir(parents=True, exist_ok=True)
|
||||
pkg = _SHELL_CACHE / f"setup-37du-host-{cloud}.exe"
|
||||
pkg.write_bytes(data)
|
||||
with requests.get(url, headers=dl_headers, stream=True, timeout=600) as r:
|
||||
r.raise_for_status()
|
||||
_STATE["dl_total"] = int(r.headers.get("Content-Length") or 0)
|
||||
sha = hashlib.sha256()
|
||||
with open(tmp, "wb") as f:
|
||||
for chunk in r.iter_content(256 * 1024):
|
||||
if not chunk:
|
||||
continue
|
||||
f.write(chunk)
|
||||
sha.update(chunk)
|
||||
_STATE["dl_received"] = _STATE.get("dl_received", 0) + len(chunk)
|
||||
total = _STATE["dl_total"]
|
||||
_STATE["dl_pct"] = int(_STATE["dl_received"] * 100 / total) if total else 0
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("下载壳子安装包失败:%s", _exc)
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = f"安装包下载失败({_exc.__class__.__name__})"
|
||||
_cleanup_part(cloud)
|
||||
return
|
||||
if expect and sha.hexdigest() != expect:
|
||||
_LOGGER.error("壳子安装包 sha256 校验失败,放弃更新")
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = "安装包校验失败,请重试"
|
||||
_cleanup_part(cloud)
|
||||
return
|
||||
try:
|
||||
os.replace(tmp, pkg)
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("壳子安装包落盘失败:%s", _exc)
|
||||
return None
|
||||
_PENDING["version"] = cloud
|
||||
_PENDING["notes"] = info.get("notes", "")
|
||||
_LOGGER.info("壳子新版本已下载待应用:%s → %s(%d 字节)", cur, cloud, len(data))
|
||||
return {"version": cloud, "notes": _PENDING["notes"]}
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = "安装包保存失败"
|
||||
_cleanup_part(cloud)
|
||||
return
|
||||
_STATE["dl_status"] = "downloaded"
|
||||
_STATE["dl_pct"] = 100
|
||||
_STATE["dl_received"] = _STATE["dl_total"]
|
||||
_restore_pending(cloud, str(info.get("notes") or ""))
|
||||
|
||||
|
||||
def _cleanup_part(cloud: str) -> None:
|
||||
try:
|
||||
(_SHELL_CACHE / f"setup-37du-host-{cloud}.exe.part").unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def cached_pkg(version: str) -> Path | None:
|
||||
@@ -108,13 +289,32 @@ def cached_pkg(version: str) -> Path | None:
|
||||
|
||||
|
||||
def pending_status() -> dict:
|
||||
"""当前更新状态(供前端提示):当前版本 / 待应用新版本 / 是否已下载。"""
|
||||
"""当前更新状态(供前端展示与轮询):兼容旧字段,并补充下载进度/可用版本。"""
|
||||
global _PENDING_VERSION, _PENDING_NOTES
|
||||
cur = local_shell_version()
|
||||
downloaded = bool(_PENDING_VERSION) and cached_pkg(_PENDING_VERSION) is not None
|
||||
if not downloaded:
|
||||
_PENDING_VERSION = ""
|
||||
_PENDING_NOTES = ""
|
||||
return {
|
||||
"current": local_shell_version(),
|
||||
"new": _PENDING.get("version", ""),
|
||||
"notes": _PENDING.get("notes", ""),
|
||||
"downloaded": bool(_PENDING.get("version"))
|
||||
and cached_pkg(_PENDING.get("version", "")) is not None,
|
||||
"current": cur,
|
||||
"new": _PENDING_VERSION if downloaded else "",
|
||||
"notes": _PENDING_NOTES if downloaded else "",
|
||||
"downloaded": downloaded,
|
||||
"available": bool(_STATE["available"]),
|
||||
"latest": _STATE.get("latest", ""),
|
||||
"checked_at": _STATE.get("check_at", 0),
|
||||
"checking": bool(_STATE.get("checking", False)),
|
||||
"error": _STATE.get("check_error", ""),
|
||||
"applying": bool(_STATE.get("applying", False)),
|
||||
"dl": {
|
||||
"version": _STATE.get("dl_version", ""),
|
||||
"status": _STATE.get("dl_status", "idle"),
|
||||
"received": _STATE.get("dl_received", 0),
|
||||
"total": _STATE.get("dl_total", 0),
|
||||
"pct": _STATE.get("dl_pct", 0),
|
||||
"error": _STATE.get("dl_error", ""),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -123,10 +323,11 @@ def apply_update() -> None:
|
||||
|
||||
注意:本函数在返回前 os._exit(0) 退出整个进程,调用方无需继续处理。
|
||||
"""
|
||||
version = _PENDING.get("version", "")
|
||||
version = _PENDING_VERSION
|
||||
pkg = cached_pkg(version)
|
||||
if not pkg:
|
||||
raise FileNotFoundError(f"未找到已下载的安装包:setup-37du-host-{version}.exe")
|
||||
_STATE["applying"] = True
|
||||
_LOGGER.info("开始静默升级到 %s:%s", version, pkg)
|
||||
subprocess.Popen(
|
||||
[str(pkg), "/VERYSILENT", "/SUPPRESSMSGBOXES", "/NORESTART"],
|
||||
|
||||
@@ -12,8 +12,10 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import logging
|
||||
import socket
|
||||
import sys
|
||||
import threading
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
@@ -29,6 +31,7 @@ from webhost.backend.plugins import load_plugins
|
||||
from webhost.backend.apis import admin as api_admin
|
||||
from webhost.backend.apis import dingtalk as api_dingtalk
|
||||
from webhost.backend.apis import meta as api_meta
|
||||
from webhost.backend.apis import plugin_ui as api_plugin_ui
|
||||
from webhost.backend.apis import runs as api_runs
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
@@ -36,48 +39,73 @@ _LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
HUB.bind(asyncio.get_running_loop())
|
||||
# 显式加载插件:默认全量;配置 controlplane 源则按账号权限白名单加载
|
||||
_st.set_allowed(_resolve_allowed())
|
||||
load_plugins(_st.ALLOWED)
|
||||
# 产品化初始化:授权缓存 + 单活调度 + 启动即同步离线票据
|
||||
licensing.init(config.CONTROLPLANE_URL, threading.Lock())
|
||||
_scheduler.init_active()
|
||||
if config.CONTROLPLANE_URL:
|
||||
try:
|
||||
_sync_licensing(config.CONTROLPLANE_ACCOUNT)
|
||||
_LOGGER.info("启动同步离线授权票据成功(账号 %s)", config.CONTROLPLANE_ACCOUNT)
|
||||
except Exception as _exc: # noqa: BLE001 首启/断网时同步失败不阻断,离线用缓存兜底
|
||||
_LOGGER.warning("启动同步离线授权票据失败:%s", _exc)
|
||||
# 启动即检查插件更新:有恢复的会话账号时后台同步(每次启动确定是否更新,不阻塞启动)
|
||||
try:
|
||||
from webhost.backend.core.session import _SESS
|
||||
_accts = {_a for _, (_a, _t) in _SESS.items()}
|
||||
except Exception: # noqa: BLE001
|
||||
_accts = set()
|
||||
if _accts:
|
||||
_acct = next(iter(_accts))
|
||||
|
||||
def _boot_sync() -> None:
|
||||
try:
|
||||
from webhost.backend.core.plugin_sync import sync_plugins
|
||||
sync_plugins(_acct)
|
||||
load_plugins(_st.ALLOWED, reload=True)
|
||||
_LOGGER.info("启动插件更新完成(账号 %s)", _acct)
|
||||
except Exception as _exc: # noqa: BLE001 更新失败不阻断启动
|
||||
_LOGGER.warning("启动插件更新失败:%s", _exc)
|
||||
|
||||
threading.Thread(target=_boot_sync, daemon=True).start()
|
||||
# 启动即检查壳子(主程序)更新:有新版本自动下载,前端提示后由用户点击重启升级
|
||||
def _boot_shell_check() -> None:
|
||||
try:
|
||||
HUB.bind(asyncio.get_running_loop())
|
||||
# 显式加载插件:默认全量;配置 controlplane 源则按账号权限白名单加载
|
||||
_st.set_allowed(_resolve_allowed())
|
||||
load_plugins(_st.ALLOWED)
|
||||
# 产品化初始化:授权缓存 + 单活调度 + 启动即同步离线票据
|
||||
licensing.init(config.CONTROLPLANE_URL, threading.Lock())
|
||||
_scheduler.init_active()
|
||||
if config.CONTROLPLANE_URL:
|
||||
# 敏感凭证中心化下发:优先服务端在线拉取(RSA 解密),否则用本地缓存密文解密;
|
||||
# 失败不阻断启动(.env 回退 / 等待下次登录后刷新)
|
||||
try:
|
||||
from webhost.backend.core.shell_updater import check_and_download
|
||||
check_and_download()
|
||||
except Exception as _exc: # noqa: BLE001 检查失败不阻断启动
|
||||
_LOGGER.warning("启动壳子更新检查失败:%s", _exc)
|
||||
from webhost.backend.core import creds_sync
|
||||
_creds = creds_sync.load()
|
||||
if _creds:
|
||||
config.apply_creds(_creds)
|
||||
_LOGGER.info("中心机敏感凭证下发完成(%s 个键)", len(_creds))
|
||||
except Exception as _exc: # noqa: BLE001 下发失败不影响启动
|
||||
_LOGGER.warning("加载中心机敏感凭证失败:%s", _exc)
|
||||
# 账号:.env 不再配置 CONTROLPLANE_ACCOUNT,取最近活跃的本机会话账号(重启恢复)
|
||||
from webhost.backend.core.session import _sess_active_account
|
||||
_acct = config.CONTROLPLANE_ACCOUNT or _sess_active_account()
|
||||
if _acct:
|
||||
try:
|
||||
_sync_licensing(_acct)
|
||||
_LOGGER.info("启动同步离线授权票据成功(账号 %s)", _acct)
|
||||
except Exception as _exc: # noqa: BLE001 首启/断网时同步失败不阻断,离线用缓存兜底
|
||||
_LOGGER.warning("启动同步离线授权票据失败:%s", _exc)
|
||||
# 启动即检查插件更新:有恢复的会话账号时后台同步(每次启动确定是否更新,不阻塞启动)
|
||||
try:
|
||||
from webhost.backend.core.session import _SESS
|
||||
_accts = {_a for _, (_a, _t) in _SESS.items()}
|
||||
except Exception: # noqa: BLE001
|
||||
_accts = set()
|
||||
if _accts:
|
||||
_acct = next(iter(_accts))
|
||||
|
||||
threading.Thread(target=_boot_shell_check, daemon=True).start()
|
||||
yield
|
||||
def _boot_sync() -> None:
|
||||
try:
|
||||
from webhost.backend.core.plugin_sync import sync_plugins, SYNC_LOCK
|
||||
with SYNC_LOCK:
|
||||
sync_plugins(_acct)
|
||||
load_plugins(_st.ALLOWED, reload=True)
|
||||
_LOGGER.info("启动插件更新完成(账号 %s)", _acct)
|
||||
except Exception as _exc: # noqa: BLE001 更新失败不阻断启动
|
||||
_LOGGER.warning("启动插件更新失败:%s", _exc)
|
||||
|
||||
threading.Thread(target=_boot_sync, daemon=True).start()
|
||||
# 启动即检查壳子(主程序)更新:有新版本自动下载,前端提示后由用户点击重启升级;
|
||||
# 并常驻周期检查(默认 30 分钟),壳子长开时也能自动发现新版本
|
||||
from webhost.backend.core import shell_updater as _shell_updater
|
||||
_shell_updater.start_check()
|
||||
_shell_updater.start_periodic_check()
|
||||
yield
|
||||
except BaseException:
|
||||
# lifespan 失败会被 uvicorn 吞成 SystemExit(3);frozen 下 stderr 已重定向 devnull,
|
||||
# 报错无处可看:崩溃现场记入 webhost.log,frozen 时并追加到 exe 同级 crash.log
|
||||
import traceback
|
||||
_tb = traceback.format_exc()
|
||||
_LOGGER.error("启动初始化失败:\n%s", _tb)
|
||||
if getattr(sys, "frozen", False):
|
||||
try:
|
||||
with open(Path(sys.executable).parent / "crash.log", "a", encoding="utf-8") as _f:
|
||||
_f.write("\n[lifespan]\n" + _tb)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
|
||||
app = FastAPI(title="37du Web Host", lifespan=lifespan)
|
||||
@@ -87,6 +115,7 @@ app.include_router(api_admin.router)
|
||||
app.include_router(api_dingtalk.router)
|
||||
app.include_router(api_meta.router)
|
||||
app.include_router(api_runs.router)
|
||||
app.include_router(api_plugin_ui.router)
|
||||
|
||||
|
||||
if config.DIST.exists():
|
||||
|
||||
@@ -41,7 +41,13 @@ _LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _discover_modules() -> list:
|
||||
"""发现插件模块:目录优先,排除 base 与 `_` 前缀的私有文件。"""
|
||||
"""发现插件模块:目录优先,排除 base 与 `_` 前缀的私有文件。
|
||||
|
||||
全新安装时 plugins/ 尚不存在(插件由登录后按权限自下载,不随安装包分发),
|
||||
必须视为"零插件"而不是抛错——否则 lifespan 失败导致壳子无法启动。
|
||||
"""
|
||||
if not _PLUGINS_ROOT.is_dir():
|
||||
return []
|
||||
names: list = []
|
||||
seen: set = set()
|
||||
for d in sorted(_PLUGINS_ROOT.iterdir()):
|
||||
@@ -66,8 +72,11 @@ def load_plugins(allowed: set = None, reload: bool = False) -> None:
|
||||
"""
|
||||
if reload:
|
||||
PLUGINS.clear()
|
||||
# base 是 PLUGINS 注册表的单例宿主:reload 时绝不能删,否则插件模块重新
|
||||
# import base 会得到全新空注册表,注册的插件对 meta/runs 等引用方全部不可见。
|
||||
for _m in [m for m in sys.modules
|
||||
if m.startswith(_PKG_NAME + ".") and m != _PKG_NAME]:
|
||||
if m.startswith(_PKG_NAME + ".") and m != _PKG_NAME
|
||||
and m != _PKG_NAME + ".base"]:
|
||||
del sys.modules[_m]
|
||||
for _mod in _discover_modules():
|
||||
if allowed is not None and _mod not in allowed:
|
||||
|
||||
@@ -6,10 +6,35 @@
|
||||
</div>
|
||||
<LoginPage v-else-if="!store.current" :app-name="store.appName" @ok="onLogin" />
|
||||
<div class="__app" v-else>
|
||||
<!-- 壳子更新提示:控制面有新版本且已自动下载,点击重启升级 -->
|
||||
<div v-if="shellUpdate.downloaded" class="update-bar">
|
||||
<span class="upd-txt">发现新版本 <b>v{{ shellUpdate.new }}</b><em v-if="shellUpdate.notes">{{ shellUpdate.notes }}</em></span>
|
||||
<el-button size="small" type="primary" round :loading="updating" @click="doShellUpdate">重启更新</el-button>
|
||||
<!-- 壳子更新提示:下载进度 / 已就绪重启更新 / 发现新版本可下载 -->
|
||||
<div v-if="updBarVisible" class="update-bar">
|
||||
<template v-if="updDl.status === 'downloading'">
|
||||
<span class="upd-txt">正在下载新版本 <b>v{{ updDl.version }}</b></span>
|
||||
<div class="upd-mid">
|
||||
<el-progress :percentage="updDl.pct" :show-text="false" :stroke-width="6" class="upd-progress" />
|
||||
<span class="upd-pct">{{ updDl.total ? updDl.pct + '%' : fmtBytes(updDl.received) }}</span>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else-if="shellUpdate.downloaded">
|
||||
<span class="upd-txt">发现新版本 <b>v{{ shellUpdate.new }}</b><em v-if="shellUpdate.notes">{{ shellUpdate.notes }}</em></span>
|
||||
<el-button size="small" type="primary" round :loading="updating" @click="doShellUpdate">重启更新</el-button>
|
||||
</template>
|
||||
<template v-else-if="updDl.status === 'failed'">
|
||||
<span class="upd-txt">新版本下载失败<em>{{ updDl.error }}</em></span>
|
||||
<el-button size="small" type="primary" round :loading="downloading" @click="onShellDownload">重试</el-button>
|
||||
</template>
|
||||
<template v-else-if="shellUpdate.available">
|
||||
<span class="upd-txt">发现新版本 <b>v{{ shellUpdate.latest }}</b><em v-if="shellUpdate.notes">{{ shellUpdate.notes }}</em></span>
|
||||
<div class="upd-actions">
|
||||
<el-button size="small" type="primary" round :loading="downloading" @click="onShellDownload">立即下载</el-button>
|
||||
<el-button size="small" round @click="shellDismissed = true">暂不</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
<!-- 授权已过期:离线超 7 天须联网刷新票据后才能继续使用 -->
|
||||
<div v-if="store.authExpired" class="auth-expired-bar">
|
||||
<span class="ae-txt">授权已过期(最长离线 7 天),需联网刷新授权后才能继续使用</span>
|
||||
<el-button size="small" type="primary" round :loading="syncingPlugins" @click="onPluginSync">立即刷新</el-button>
|
||||
</div>
|
||||
<!-- 顶部:品牌 + 平台登录态 + 当前账号/登出 + 进度 -->
|
||||
<header class="topbar panel">
|
||||
@@ -46,6 +71,25 @@
|
||||
</el-tooltip>
|
||||
</div>
|
||||
|
||||
<!-- 浏览器(Chrome)状态图标:已安装显示版本(绿),未安装高亮可点击进入下载/安装 -->
|
||||
<div class="band chrome-band" v-if="chromeVis">
|
||||
<el-tooltip
|
||||
:content="chromeTip"
|
||||
placement="bottom"
|
||||
>
|
||||
<el-button
|
||||
class="chip chrome-chip"
|
||||
:class="{ ok: chromeInstalled, warn: !chromeInstalled && chromeCloud, loading: chromeBusy }"
|
||||
round
|
||||
:loading="chromeBusy"
|
||||
@click="onChromeClick"
|
||||
>
|
||||
<i class="chrome-icon" :class="{ blink: !chromeInstalled }"></i>
|
||||
<span>{{ chromeLabel }}</span>
|
||||
</el-button>
|
||||
</el-tooltip>
|
||||
</div>
|
||||
|
||||
<div class="spacer"></div>
|
||||
|
||||
<div class="run-state">
|
||||
@@ -67,18 +111,7 @@
|
||||
<span class="acct-avatar-fb">{{ (store.nickname || store.current).slice(0, 1).toUpperCase() }}</span>
|
||||
</el-avatar>
|
||||
<span class="acct-name">{{ store.nickname || store.current }}</span>
|
||||
<el-tag v-if="store.isAdmin" size="small" type="primary" effect="light" round>管理员</el-tag>
|
||||
</button>
|
||||
<el-button
|
||||
v-if="store.isAdmin"
|
||||
v-show="store.controlplane"
|
||||
class="chip admin-chip"
|
||||
title="打开中心机控制面进行插件/账号/授权管理"
|
||||
round
|
||||
@click="openConsole"
|
||||
>
|
||||
<el-icon class="geo"><Setting /></el-icon>管理控制台
|
||||
</el-button>
|
||||
<el-button class="chip" round @click="logout">登出</el-button>
|
||||
</div>
|
||||
</header>
|
||||
@@ -88,7 +121,13 @@
|
||||
<aside class="panel side">
|
||||
<div class="side-head">
|
||||
<span class="sec-title">场景</span>
|
||||
<span class="count">{{ store.plugins.length }}</span>
|
||||
<div class="side-head-r">
|
||||
<span class="count">{{ store.plugins.length }}</span>
|
||||
<el-tooltip content="插件同步" placement="top">
|
||||
<el-button class="sync-btn" text :icon="Refresh" :loading="syncingPlugins"
|
||||
:disabled="store.running" @click="onPluginSync" />
|
||||
</el-tooltip>
|
||||
</div>
|
||||
</div>
|
||||
<ul class="scene-list">
|
||||
<li
|
||||
@@ -105,7 +144,15 @@
|
||||
</li>
|
||||
</ul>
|
||||
<div v-if="!store.plugins.length" class="scene-empty">当前账号暂无可用场景<br><span>请联系管理员进行授权</span></div>
|
||||
<div class="side-foot">场景以插件方式接入</div>
|
||||
<div class="side-foot">
|
||||
<div class="foot-ver">
|
||||
<span class="ver-num">壳子 {{ shellUpdate.current ? 'v' + shellUpdate.current : '未打包' }}</span>
|
||||
<el-link type="primary" :underline="false" class="check-link"
|
||||
:disabled="shellChecking" @click="onShellCheck">
|
||||
{{ shellChecking ? '检查中…' : '检查更新' }}</el-link>
|
||||
</div>
|
||||
<div>场景以插件方式接入</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<main class="main">
|
||||
@@ -120,19 +167,15 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { Refresh } from '@element-plus/icons-vue'
|
||||
import PluginPage from './components/PluginPage.vue'
|
||||
import LogPanel from './components/LogPanel.vue'
|
||||
import LoginPage from './components/LoginPage.vue'
|
||||
import ProfilePanel from './components/ProfilePanel.vue'
|
||||
import { store, handleEvent, clearLogs, log, loadAvatar, clearAvatarCache, accountAvatar } from './store'
|
||||
import { connectWS, fetchMeta, loginPlatform, adminLogout, adminMe, adminPassword, syncPlugins, getShellStatus, applyShellUpdate } from './api'
|
||||
|
||||
function openConsole() {
|
||||
if (!store.controlplane) return
|
||||
window.open(store.controlplane, '_blank', 'noopener')
|
||||
}
|
||||
import { connectWS, fetchMeta, loginPlatform, adminLogout, adminMe, adminPassword, syncPlugins, getShellStatus, applyShellUpdate, checkShellUpdate, downloadShellUpdate, getChromeStatus, checkChrome, downloadChrome, installChrome } from './api'
|
||||
|
||||
const PALETTE = ['#3b6cff', '#7c5cff', '#12a4d8', '#22b07a', '#e88a3a', '#e5484d']
|
||||
|
||||
@@ -164,9 +207,9 @@ function openWS() {
|
||||
onMounted(async () => {
|
||||
const meta = await fetchMeta()
|
||||
store.appName = meta.appName
|
||||
store.controlplane = meta.controlplane || ''
|
||||
store.platforms = meta.platforms
|
||||
store.plugins = meta.plugins || []
|
||||
store.authExpired = !!meta.authExpired
|
||||
store.selectedId = store.plugins[0]?.id || ''
|
||||
clearLogs()
|
||||
openWS()
|
||||
@@ -174,19 +217,158 @@ onMounted(async () => {
|
||||
booting.value = false // 会话判定完成(登录/未登录/后端不可达均已定),再渲染首屏
|
||||
loadAvatar()
|
||||
loadShellStatus()
|
||||
loadChromeStatus()
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
if (shellPollTimer) { clearTimeout(shellPollTimer); shellPollTimer = null }
|
||||
if (chromePollTimer) { clearTimeout(chromePollTimer); chromePollTimer = null }
|
||||
})
|
||||
|
||||
// ===== 浏览器(Chrome)检测/下载/安装 =====
|
||||
const chrome = ref({})
|
||||
let chromePollTimer = null
|
||||
const chromeBusy = ref(false) // 正在轮询/下载/安装(按钮 loading)
|
||||
|
||||
const chromeInstalled = computed(() => !!chrome.value.installed)
|
||||
const chromeVisible = computed(() => {
|
||||
// 下载中/已下载待安装/未安装但中心机有登记 → 显示;已装则不显示(已可用不占用空间)
|
||||
return chrome.value.installed || chrome.value.downloaded || chrome.value.cloud_available
|
||||
})
|
||||
// 与模板 v-if 共用(template 里用的是字符串写法,这里保持简单)
|
||||
const chromeVis = computed(() =>
|
||||
!chrome.value.installed || chrome.value.downloaded || chrome.value.dl?.status === 'downloading')
|
||||
|
||||
const chromeLabel = computed(() => {
|
||||
const c = chrome.value
|
||||
if (c.installing) return '安装中…'
|
||||
if (!c.installed) {
|
||||
if (c.dl?.status === 'downloading') return c.dl?.pct + '%'
|
||||
if (c.downloaded) return '点击安装'
|
||||
if (c.cloud_available) return '装浏览器'
|
||||
return '浏览器'
|
||||
}
|
||||
return c.version ? 'Chrome ' + c.version : 'Chrome'
|
||||
})
|
||||
|
||||
const chromeTip = computed(() => {
|
||||
const c = chrome.value
|
||||
if (c.installed) return `本机已安装 Chrome ${c.version},点击重新检测`
|
||||
if (c.installing) return '正在安装 Chrome,请稍候…'
|
||||
if (c.downloaded) return 'Chrome 安装包已下载,点击安装'
|
||||
if (c.dl?.status === 'downloading') return '正在下载 Chrome 安装包 ' + c.dl?.pct + '%'
|
||||
if (!c.cloud_available) return '中心机暂未登记浏览器安装包,点击重新检测'
|
||||
return '本机未安装 Chrome,点击下载安装'
|
||||
})
|
||||
|
||||
async function loadChromeStatus() {
|
||||
try { chrome.value = await getChromeStatus() } catch (_) {}
|
||||
// 未安装或操作中才轮询;已安装无需常驻
|
||||
if (!chrome.value.installed || chrome.value.installing || chrome.value.dl?.status === 'downloading') {
|
||||
startChromePoll()
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshChromeStatus() {
|
||||
try {
|
||||
const s = await getChromeStatus()
|
||||
chrome.value = s
|
||||
if (chrome.value.installed && chrome.value.dl?.status !== 'downloading' && !chrome.value.installing) {
|
||||
if (chromePollTimer) { clearTimeout(chromePollTimer); chromePollTimer = null }
|
||||
return // 已装好,停止轮询
|
||||
}
|
||||
} catch (_) {}
|
||||
chromePollTimer = setTimeout(refreshChromeStatus, 1500)
|
||||
}
|
||||
function startChromePoll() {
|
||||
if (chromePollTimer) return
|
||||
refreshChromeStatus()
|
||||
}
|
||||
|
||||
async function onChromeClick() {
|
||||
if (chromeBusy.value) return
|
||||
const c = chrome.value
|
||||
// 安装中:仅刷新状态
|
||||
if (c.installing) { return }
|
||||
// 已下载:直接安装
|
||||
if (c.downloaded) {
|
||||
chromeBusy.value = true
|
||||
try { await installChrome(); chrome.value.installing = true; startChromePoll() }
|
||||
catch (e) { ElMessage.error('安装失败:' + (e.message || e)) }
|
||||
chromeBusy.value = false
|
||||
return
|
||||
}
|
||||
// 未装且中心机有登记:下载
|
||||
if (!c.installed && c.cloud_available) {
|
||||
chromeBusy.value = true
|
||||
try { await downloadChrome(); loadChromeStatus() }
|
||||
catch (e) { ElMessage.error('开始下载失败:' + (e.message || e)) }
|
||||
chromeBusy.value = false
|
||||
return
|
||||
}
|
||||
// 其余:重新检测
|
||||
chromeBusy.value = true
|
||||
try { await checkChrome(); loadChromeStatus() }
|
||||
catch (e) { ElMessage.error('检测失败:' + (e.message || e)) }
|
||||
chromeBusy.value = false
|
||||
}
|
||||
|
||||
const profileOpen = ref(false)
|
||||
const busyLogin = ref('')
|
||||
const booting = ref(true) // 鉴权判定中:未确定会话前先显示加载骨架,避免「闪一下登录页再进首页」
|
||||
const syncing = ref(false) // 首次启动/启动时:按账号权限自下载/更新插件(等待下载界面)
|
||||
|
||||
// ===== 壳子自动更新:控制面有新版本且已自动下载 → 提示用户点击重启升级 =====
|
||||
// ===== 壳子自动更新:检查 → 用户确认下载(带进度)→ 重启更新 =====
|
||||
const shellUpdate = ref({})
|
||||
const updating = ref(false)
|
||||
const downloading = ref(false)
|
||||
const shellChecking = ref(false) // 手动检查请求进行中(秒级)
|
||||
const shellDismissed = ref(false) // 用户点了"暂不",本会话内隐藏"立即下载"提示
|
||||
let shellPollTimer = null // 状态轮询(setTimeout 递归,下载中 1.2s / 常态 15s)
|
||||
let lastDlStatus = '' // 上一轮下载状态,用于下载完成/失败时的一次性提示
|
||||
|
||||
const updDl = computed(() => shellUpdate.value.dl || {})
|
||||
const updBarVisible = computed(() =>
|
||||
shellUpdate.value.downloaded ||
|
||||
updDl.value.status === 'downloading' ||
|
||||
updDl.value.status === 'failed' ||
|
||||
(shellUpdate.value.available && !shellDismissed.value)
|
||||
)
|
||||
|
||||
function fmtBytes(n) {
|
||||
if (!n) return '0 B'
|
||||
const u = ['B', 'KB', 'MB', 'GB']
|
||||
let i = 0
|
||||
while (n >= 1024 && i < u.length - 1) { n /= 1024; i++ }
|
||||
return (n >= 100 || i === 0 ? n.toFixed(0) : n.toFixed(1)) + ' ' + u[i]
|
||||
}
|
||||
|
||||
async function loadShellStatus() {
|
||||
try { shellUpdate.value = await getShellStatus() } catch (_) {}
|
||||
startShellPoll()
|
||||
}
|
||||
|
||||
// 常驻状态轮询:驱动下载进度条与 available/downloaded 提示;下载完成/失败各提示一次
|
||||
async function refreshShellStatus() {
|
||||
try {
|
||||
const s = await getShellStatus()
|
||||
shellUpdate.value = s
|
||||
const st = s.dl?.status || ''
|
||||
if (lastDlStatus === 'downloading' && st === 'downloaded') {
|
||||
ElMessage.success(`新版本 v${s.new} 已下载完成,点击顶部「重启更新」完成升级`)
|
||||
log('INFO', `壳子新版本 v${s.new} 已就绪,可重启更新`)
|
||||
} else if (lastDlStatus === 'downloading' && st === 'failed') {
|
||||
ElMessage.warning('新版本下载失败:' + (s.dl?.error || ''))
|
||||
}
|
||||
lastDlStatus = st
|
||||
} catch (_) {}
|
||||
shellPollTimer = setTimeout(refreshShellStatus, updDl.value.status === 'downloading' ? 1200 : 15000)
|
||||
}
|
||||
function startShellPoll() {
|
||||
if (shellPollTimer) return
|
||||
refreshShellStatus()
|
||||
}
|
||||
|
||||
async function doShellUpdate() {
|
||||
updating.value = true
|
||||
try {
|
||||
@@ -197,6 +379,100 @@ async function doShellUpdate() {
|
||||
}
|
||||
}
|
||||
|
||||
async function onShellDownload() {
|
||||
if (downloading.value) return
|
||||
downloading.value = true
|
||||
shellDismissed.value = false
|
||||
try {
|
||||
await downloadShellUpdate() // 后端后台流式下载,进度经轮询展示
|
||||
} catch (e) {
|
||||
ElMessage.error('开始下载失败:' + (e.message || e))
|
||||
}
|
||||
downloading.value = false
|
||||
}
|
||||
|
||||
// 手动"检查更新":触发秒级版本比对 → 轮询检查结束后按结果提示
|
||||
async function onShellCheck() {
|
||||
if (shellChecking.value) return
|
||||
try { await checkShellUpdate() } catch (e) {
|
||||
ElMessage.error('检查更新失败:' + (e.message || e))
|
||||
return
|
||||
}
|
||||
shellChecking.value = true
|
||||
const timer = setInterval(async () => {
|
||||
try {
|
||||
const s = await getShellStatus()
|
||||
shellUpdate.value = s
|
||||
if (s.checking) return
|
||||
clearInterval(timer)
|
||||
shellChecking.value = false
|
||||
handleCheckResult(s)
|
||||
} catch (_) {}
|
||||
}, 800)
|
||||
// 兜底:30s 仍未结束则停止轮询,避免无限等待
|
||||
setTimeout(() => {
|
||||
if (shellChecking.value) {
|
||||
clearInterval(timer)
|
||||
shellChecking.value = false
|
||||
}
|
||||
}, 30000)
|
||||
}
|
||||
|
||||
function handleCheckResult(s) {
|
||||
if (!s.current) {
|
||||
ElMessage.info('当前为源码开发模式,不参与壳子自更新')
|
||||
return
|
||||
}
|
||||
if (s.downloaded) {
|
||||
ElMessage.info(`新版本 v${s.new} 已就绪,点击顶部「重启更新」完成升级`)
|
||||
return
|
||||
}
|
||||
if (updDl.value.status === 'downloading') return // 正在下载,进度条展示中
|
||||
if (s.error) {
|
||||
ElMessage.warning('检查更新失败:' + s.error)
|
||||
log('WARN', `检查壳子更新失败:${s.error}`)
|
||||
return
|
||||
}
|
||||
if (s.available) {
|
||||
ElMessageBox.confirm(
|
||||
`发现新版本 v${s.latest},是否立即下载?${s.notes ? '\n\n更新说明:' + s.notes : ''}`,
|
||||
'发现新版本',
|
||||
{ confirmButtonText: '立即下载', cancelButtonText: '稍后再说', type: 'info' }
|
||||
).then(() => onShellDownload()).catch(() => {})
|
||||
} else {
|
||||
ElMessage.info(`已是最新版本 v${s.current}`)
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 插件同步:按当前账号权限重新同步(新装/更新/清理已删除),完成后刷新清单 =====
|
||||
// 登录成功与手动刷新共用;同步失败也补拉清单,保证离线时沿用本地已装插件
|
||||
const syncingPlugins = ref(false)
|
||||
async function onPluginSync() {
|
||||
if (syncingPlugins.value || store.running) return
|
||||
syncingPlugins.value = true
|
||||
try {
|
||||
const r = await syncPlugins()
|
||||
const parts = []
|
||||
if (r.downloaded?.length) parts.push(`新装 ${r.downloaded.length} 个`)
|
||||
if (r.updated?.length) parts.push(`更新 ${r.updated.length} 个`)
|
||||
if (r.removed?.length) parts.push(`清理 ${r.removed.length} 个`)
|
||||
if (r.failed?.length) parts.push(`失败 ${r.failed.length} 个`)
|
||||
if (parts.length) {
|
||||
ElMessage.success('插件同步完成:' + parts.join(','))
|
||||
const detail = [...(r.downloaded || []), ...(r.updated || []), ...(r.removed || [])].join('、')
|
||||
if (detail) log('INFO', `插件同步完成:${parts.join(',')}(${detail})`)
|
||||
} else {
|
||||
ElMessage.info('插件已是最新')
|
||||
}
|
||||
if (r.failed?.length) log('ERROR', `插件同步失败:${r.failed.join('、')}`)
|
||||
} catch (e) {
|
||||
ElMessage.error('插件同步失败:' + (e.message || e))
|
||||
} finally {
|
||||
await refreshMeta()
|
||||
syncingPlugins.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 平台登录等轻量操作反馈:统一走 element-plus 全局消息
|
||||
function showToast(msg, type = 'info') {
|
||||
ElMessage({ message: msg, type, duration: 2200 })
|
||||
@@ -208,12 +484,11 @@ async function checkSession() {
|
||||
try {
|
||||
const me = await adminMe()
|
||||
if (!me.account) {
|
||||
store.current = ''; store.isAdmin = false; store.dept = ''; store.nickname = ''; store.avatar = ''
|
||||
store.current = ''; store.dept = ''; store.nickname = ''; store.avatar = ''
|
||||
try { localStorage.removeItem('cp_account') } catch (_) {}
|
||||
return
|
||||
}
|
||||
store.current = me.account
|
||||
store.isAdmin = !!me.is_admin
|
||||
store.dept = me.dept || ''
|
||||
store.nickname = me.nickname || ''
|
||||
store.avatar = me.avatar || ''
|
||||
@@ -230,24 +505,28 @@ async function checkSession() {
|
||||
async function refreshMeta() {
|
||||
try {
|
||||
const meta = await fetchMeta()
|
||||
store.controlplane = meta.controlplane || ''
|
||||
store.platforms = meta.platforms
|
||||
store.plugins = meta.plugins || []
|
||||
if (!store.selectedId) store.selectedId = store.plugins[0]?.id || ''
|
||||
store.authExpired = !!meta.authExpired
|
||||
// 选中场景不存在(被同步清理/授权收回)时回落到第一个可用场景
|
||||
if (!store.plugins.find((p) => p.id === store.selectedId)) {
|
||||
store.selectedId = store.plugins[0]?.id || ''
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
async function onLogin(ok) {
|
||||
store.current = ok.account
|
||||
store.isAdmin = !!ok.is_admin
|
||||
store.dept = ok.dept || ''
|
||||
store.nickname = ok.nickname || ''
|
||||
store.avatar = ok.avatar || ''
|
||||
try { localStorage.setItem('cp_account', ok.account) } catch (_) {}
|
||||
// 登录后:刷新平台权限与插件清单,并用带会话的连接重建 WS
|
||||
await refreshMeta()
|
||||
// 登录成功后立即按该账号权限同步插件(新装机首次登录即下载授权插件),再刷新平台/清单
|
||||
await onPluginSync()
|
||||
openWS()
|
||||
loadAvatar()
|
||||
loadShellStatus() // 挂载时未登录拉不到更新状态,登录后补拉(版本显示/更新提示)
|
||||
loadChromeStatus() // 浏览器状态同此
|
||||
// 首次登录/钉钉自动建号的默认密码:提示立即改密
|
||||
if (ok.must_change_pwd) { promptChangePwd(ok.account) }
|
||||
}
|
||||
@@ -270,10 +549,10 @@ async function promptChangePwd(account) {
|
||||
async function logout() {
|
||||
try { await adminLogout() } catch (_) {}
|
||||
store.current = ''
|
||||
store.isAdmin = false
|
||||
store.nickname = ''
|
||||
store.avatar = ''
|
||||
store.avatarUrl = ''
|
||||
store.authExpired = false
|
||||
try { localStorage.removeItem('cp_account') } catch (_) {}
|
||||
}
|
||||
|
||||
@@ -342,6 +621,10 @@ async function login(id) {
|
||||
}
|
||||
.update-bar b { color: var(--primary); }
|
||||
.update-bar em { font-style: normal; color: var(--text-faint); margin-left: 6px; }
|
||||
.update-bar .upd-mid { display: flex; align-items: center; gap: 10px; flex: 1; max-width: 340px; }
|
||||
.update-bar .upd-progress { flex: 1; }
|
||||
.update-bar .upd-pct { font-size: 12px; color: var(--text-faint); min-width: 46px; text-align: right; }
|
||||
.update-bar .upd-actions { display: flex; align-items: center; gap: 8px; }
|
||||
.brand { display: flex; align-items: center; gap: 11px; }
|
||||
.logo {
|
||||
width: 36px; height: 36px; border-radius: 10px;
|
||||
@@ -364,9 +647,32 @@ async function login(id) {
|
||||
.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.locked { border-style: dashed; opacity: .5; }
|
||||
.admin-chip { border-color: rgba(59,108,255,.45); color: var(--primary); background: var(--primary-weak-2); margin-left: 4px; }
|
||||
.admin-chip:hover { border-color: var(--primary); }
|
||||
.admin-chip .geo { margin-right: 4px; }
|
||||
|
||||
/* 浏览器(Chrome)状态图标 */
|
||||
.chrome-band { margin-left: 2px; }
|
||||
.chrome-chip { border-color: transparent; background: var(--surface-2); color: var(--text-sub); }
|
||||
.chrome-chip.ok { background: var(--ok-weak); color: #1a8f63; }
|
||||
.chrome-chip.warn { background: #FFF4E5; color: #9A5B14; border-color: rgba(224,122,40,.4); }
|
||||
.chrome-icon {
|
||||
width: 14px; height: 14px; border-radius: 50%;
|
||||
margin-right: 6px; display: inline-block; flex-shrink: 0;
|
||||
background: radial-gradient(circle at 30% 30%, #e6f2ff, #4a8cf7 55%, #2b6be0);
|
||||
box-shadow: 0 0 0 3px rgba(74, 140, 247, .18);
|
||||
}
|
||||
.chrome-chip.warn .chrome-icon { background: radial-gradient(circle at 30% 30%, #fff6e6, #f7a23a 55%, #e07324); box-shadow: 0 0 0 3px rgba(247,162,58,.2); }
|
||||
.chrome-chip.loading .chrome-icon { opacity: .4; }
|
||||
.chrome-icon.blink { animation: chromeblink 1s infinite ease-in-out; }
|
||||
@keyframes chromeblink { 0%,100% { opacity: 1; } 50% { opacity: .35; } }
|
||||
|
||||
.auth-expired-bar {
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 12px;
|
||||
padding: 8px 14px; margin-bottom: 12px; flex-shrink: 0;
|
||||
background: #FFF4E5;
|
||||
border: 1px solid rgba(224, 122, 40, .45);
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 13px; color: #9A5B14;
|
||||
}
|
||||
.auth-expired-bar .ae-txt { flex: 1; }
|
||||
|
||||
.spacer { flex: 1; }
|
||||
.run-state { display: flex; align-items: center; gap: 10px; }
|
||||
@@ -389,6 +695,9 @@ async function login(id) {
|
||||
|
||||
.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; }
|
||||
.side-head-r { display: flex; align-items: center; gap: 2px; }
|
||||
.sync-btn { padding: 5px 6px; font-size: 14px; color: var(--text-faint); }
|
||||
.sync-btn:hover { color: var(--primary); }
|
||||
.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 {
|
||||
@@ -415,7 +724,10 @@ async function login(id) {
|
||||
font-size: 12.5px; color: var(--text-sub); line-height: 1.9; padding: 20px 12px;
|
||||
}
|
||||
.scene-empty span { font-size: 11px; 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; }
|
||||
.side-foot { font-size: 10px; color: var(--text-faint); text-align: center; padding-top: 10px; border-top: 1px dashed var(--border); margin-top: 8px; display: flex; flex-direction: column; gap: 4px; }
|
||||
.foot-ver { display: flex; align-items: center; justify-content: center; gap: 8px; }
|
||||
.ver-num { font-variant-numeric: tabular-nums; }
|
||||
.check-link { font-size: 10px; vertical-align: baseline; }
|
||||
|
||||
.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; }
|
||||
|
||||
@@ -23,10 +23,32 @@ export async function getShellStatus() {
|
||||
return j('/api/shell/update-status')
|
||||
}
|
||||
|
||||
export async function checkShellUpdate() {
|
||||
return j('/api/shell/check', { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function downloadShellUpdate() {
|
||||
return j('/api/shell/download', { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function applyShellUpdate() {
|
||||
return j('/api/shell/apply', { method: 'POST' })
|
||||
}
|
||||
|
||||
// ===== 浏览器(Chrome)安装 =====
|
||||
export async function getChromeStatus() {
|
||||
return j('/api/chrome/status')
|
||||
}
|
||||
export async function checkChrome() {
|
||||
return j('/api/chrome/check', { method: 'POST' })
|
||||
}
|
||||
export async function downloadChrome() {
|
||||
return j('/api/chrome/download', { method: 'POST' })
|
||||
}
|
||||
export async function installChrome() {
|
||||
return j('/api/chrome/install', { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function loginPlatform(id) {
|
||||
return j(`/api/platforms/${id}/login`, { method: 'POST' })
|
||||
}
|
||||
|
||||
@@ -62,9 +62,9 @@
|
||||
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { ChatDotRound } from '@element-plus/icons-vue'
|
||||
import { adminLogin, adminPassword, authDingtalk } from '../api'
|
||||
import { adminLogin, authDingtalk } from '../api'
|
||||
|
||||
defineProps({ appName: { type: String, default: '' } })
|
||||
const emit = defineEmits(['ok'])
|
||||
@@ -83,7 +83,6 @@ async function doLogin() {
|
||||
ElMessage.success('登录成功')
|
||||
emit('ok', {
|
||||
account: account.value.trim(),
|
||||
is_admin: !!r.is_admin,
|
||||
dept: r.dept || '',
|
||||
must_change_pwd: !!r.must_change_pwd,
|
||||
nickname: r.nickname || '',
|
||||
@@ -112,25 +111,6 @@ async function openDing() {
|
||||
}
|
||||
dingBusy.value = false
|
||||
}
|
||||
|
||||
async function promptChangePwd(acc, r) {
|
||||
try {
|
||||
const { value: np } = await ElMessageBox.prompt(
|
||||
'当前为系统默认密码,请立即设置新密码(至少 6 位)',
|
||||
'首次登录 · 修改密码',
|
||||
{
|
||||
inputType: 'password', inputPattern: /^.{6,}$/, inputErrorMessage: '密码至少 6 位',
|
||||
confirmButtonText: '设置新密码', cancelButtonText: '稍后再说'
|
||||
})
|
||||
try {
|
||||
await adminPassword({ account: acc, old_password: '', new_password: np })
|
||||
ElMessage.success('密码已更新')
|
||||
} catch (e2) {
|
||||
ElMessage.warning('改密失败:' + (e2.message || e2))
|
||||
}
|
||||
} catch (_) { /* 用户取消 */ }
|
||||
emit('ok', { account: acc, is_admin: !!r.is_admin, dept: '', created: !!r.created, nickname: r.nickname || '' })
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
@@ -27,42 +27,62 @@
|
||||
</template>
|
||||
</el-alert>
|
||||
|
||||
<!-- 参数 -->
|
||||
<div class="sec-head">
|
||||
<span class="sec-title">参数配置</span>
|
||||
<el-button v-if="Object.keys(form).length" size="small" text :disabled="store.running" :icon="RefreshLeft"
|
||||
@click="resetForm">恢复默认</el-button>
|
||||
<!-- 专属界面插件:插件 UI 直接内嵌在页面主体(同源共享会话 cookie,不再弹窗/外跳),日志保持在其下方可见 -->
|
||||
<div v-if="plugin.ui" class="ui-inline">
|
||||
<div class="ui-tip">账号密码、仓库编码、日期选项等个性化配置在界面内填写并自动保存在本机,下次打开自动回填;执行日志实时显示在下方日志区。</div>
|
||||
<iframe :key="plugin.id" :src="uiSrc" class="pui-frame" title="插件界面"></iframe>
|
||||
</div>
|
||||
<el-form label-width="auto" class="form-card">
|
||||
<div class="fields">
|
||||
<el-form-item v-for="f in plugin.fields" :key="f.key" :label="f.label">
|
||||
<template v-if="f.type === 'int'">
|
||||
<el-input-number v-model="form[f.key]" :controls="false" placeholder="0" :disabled="store.running" />
|
||||
</template>
|
||||
<el-input v-else-if="f.type === 'text'" v-model="form[f.key]" :placeholder="String(f.default ?? '')"
|
||||
:disabled="store.running">
|
||||
<template v-if="f.help" #suffix>
|
||||
<el-tooltip :content="f.help" placement="bottom"><el-icon class="help-ic">
|
||||
<QuestionFilled />
|
||||
</el-icon></el-tooltip>
|
||||
</template>
|
||||
</el-input>
|
||||
<el-select v-else v-model="form[f.key]" :disabled="store.running">
|
||||
<el-option v-for="opt in f.options" :key="opt" :value="opt" :label="opt" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<span v-if="store.running" class="run-ind">
|
||||
<el-progress :percentage="store.progress" :show-text="false" color="#3b6cff" />
|
||||
</span>
|
||||
<el-button type="primary" size="large" :loading="store.running" @click="run">
|
||||
{{ store.running ? '执行中 ' + store.progress + '%' : '一键执行' }}
|
||||
</el-button>
|
||||
</div>
|
||||
</el-form>
|
||||
|
||||
<p class="hint">执行日志与进度实时显示在下方日志区,结果完成后自动汇总于此。</p>
|
||||
<!-- 参数 -->
|
||||
<template v-else>
|
||||
<div class="sec-head">
|
||||
<span class="sec-title">参数配置</span>
|
||||
<el-button v-if="Object.keys(form).length" size="small" text :disabled="store.running" :icon="RefreshLeft"
|
||||
@click="resetForm">恢复默认</el-button>
|
||||
</div>
|
||||
<el-form label-width="auto" class="form-card">
|
||||
<div class="fields">
|
||||
<el-form-item v-for="f in plugin.fields" :key="f.key" :label="f.label">
|
||||
<template v-if="f.type === 'int'">
|
||||
<el-input-number v-model="form[f.key]" :controls="false" placeholder="0" :disabled="store.running" />
|
||||
</template>
|
||||
<el-input v-else-if="f.type === 'password'" v-model="form[f.key]" type="password" show-password
|
||||
:placeholder="String(f.default ?? '')" :disabled="store.running">
|
||||
<template v-if="f.help || f.description" #suffix>
|
||||
<el-tooltip :content="f.help || f.description" placement="bottom"><el-icon class="help-ic">
|
||||
<QuestionFilled />
|
||||
</el-icon></el-tooltip>
|
||||
</template>
|
||||
</el-input>
|
||||
<el-input v-else-if="f.type === 'text'" v-model="form[f.key]" :placeholder="String(f.default ?? '')"
|
||||
:disabled="store.running">
|
||||
<template v-if="f.help || f.description" #suffix>
|
||||
<el-tooltip :content="f.help || f.description" placement="bottom"><el-icon class="help-ic">
|
||||
<QuestionFilled />
|
||||
</el-icon></el-tooltip>
|
||||
</template>
|
||||
</el-input>
|
||||
<el-select v-else-if="f.type === 'multiselect'" v-model="form[f.key]" multiple filterable allow-create
|
||||
default-first-option placeholder="选择或输入后回车" :disabled="store.running">
|
||||
<el-option v-for="opt in (f.options || [])" :key="opt" :value="opt" :label="opt" />
|
||||
</el-select>
|
||||
<el-select v-else v-model="form[f.key]" :disabled="store.running">
|
||||
<el-option v-for="opt in f.options" :key="opt" :value="opt" :label="opt" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<span v-if="store.running" class="run-ind">
|
||||
<el-progress :percentage="store.progress" :show-text="false" color="#3b6cff" />
|
||||
</span>
|
||||
<el-button type="primary" size="large" :loading="store.running" @click="run">
|
||||
{{ store.running ? '执行中 ' + store.progress + '%' : '一键执行' }}
|
||||
</el-button>
|
||||
</div>
|
||||
</el-form>
|
||||
</template>
|
||||
|
||||
<p v-if="!plugin.ui" class="hint">执行日志与进度实时显示在下方日志区,结果完成后自动汇总于此。</p>
|
||||
</div>
|
||||
|
||||
<el-empty v-else-if="!store.plugins.length" description="当前账号暂无可用场景" />
|
||||
@@ -112,6 +132,10 @@ function resetForm() {
|
||||
form.value = buildFormDefaults(plugin.value)
|
||||
}
|
||||
|
||||
// 专属界面插件:插件 UI 直接内嵌在页面主体(同源自动携带会话 cookie,不再弹窗/外跳)。
|
||||
// 不能用 window.open 外跳:壳子是 PyWebView 窗口,系统浏览器里没有会话 cookie,会 401。
|
||||
const uiSrc = computed(() => (plugin.value?.ui ? `/pui/${plugin.value.id}/` : ''))
|
||||
|
||||
async function run() {
|
||||
if (!plugin.value || store.running) return
|
||||
if (plugin.value.platform && !(store.platforms.find((p) => p.id === plugin.value.platform)?.online)) {
|
||||
@@ -240,6 +264,33 @@ function closeBanner() {
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.ui-inline {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.ui-tip {
|
||||
font-size: 12px;
|
||||
color: var(--text-sub);
|
||||
background: var(--surface-2, #f7f8fa);
|
||||
border: 1px dashed var(--border);
|
||||
border-radius: 10px;
|
||||
padding: 8px 12px;
|
||||
}
|
||||
|
||||
.pui-frame {
|
||||
display: block;
|
||||
width: 100%;
|
||||
flex: 1;
|
||||
min-height: 420px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
background: #f6f7fb;
|
||||
}
|
||||
|
||||
.fields {
|
||||
display: flex;
|
||||
gap: 24px;
|
||||
|
||||
@@ -3,24 +3,28 @@
|
||||
v-model="visible"
|
||||
title="个人中心"
|
||||
direction="rtl"
|
||||
size="350px"
|
||||
size="360px"
|
||||
:with-header="true"
|
||||
@close="emit('close')"
|
||||
>
|
||||
<!-- 个人信息 -->
|
||||
<!-- 个人信息:头像 + 昵称(大字)/ 工号(小字),更换头像收进小图标 -->
|
||||
<section class="pcard">
|
||||
<div class="cover"></div>
|
||||
<div class="pcard-main">
|
||||
<el-avatar :size="60" :src="accountAvatar()" @error="onAvatarError" class="avatar">
|
||||
<span>{{ displayName.slice(0, 1).toUpperCase() }}</span>
|
||||
</el-avatar>
|
||||
<div class="avatar-wrap">
|
||||
<el-avatar :size="64" :src="accountAvatar()" @error="onAvatarError" class="avatar">
|
||||
<span>{{ displayName.slice(0, 1) }}</span>
|
||||
</el-avatar>
|
||||
<button class="avatar-pick" title="更换头像" @click="pickAvatar">
|
||||
<el-icon :size="11"><Camera /></el-icon>
|
||||
</button>
|
||||
</div>
|
||||
<div class="pcard-id">
|
||||
<div class="name-line">
|
||||
<strong>{{ displayName }}</strong>
|
||||
<em v-if="store.isAdmin" class="admin">管理员</em>
|
||||
</div>
|
||||
<span class="acct mono">{{ store.current }}</span>
|
||||
<span class="dept">{{ store.dept || '未设置部门' }}</span>
|
||||
<span class="avatar-act" @click="pickAvatar">更换头像</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="pcard-rows">
|
||||
@@ -39,7 +43,7 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 平台登录态 -->
|
||||
<!-- 折叠面板:平台登录态 / 我的插件 / 修改密码 -->
|
||||
<el-collapse v-model="activeNames">
|
||||
<el-collapse-item name="platforms">
|
||||
<template #title>
|
||||
@@ -59,7 +63,6 @@
|
||||
</div>
|
||||
</el-collapse-item>
|
||||
|
||||
<!-- 我的插件 -->
|
||||
<el-collapse-item name="plugins">
|
||||
<template #title>
|
||||
<div class="panel-title">
|
||||
@@ -67,7 +70,7 @@
|
||||
<span>我的插件 ({{ store.plugins.length }})</span>
|
||||
</div>
|
||||
</template>
|
||||
<el-empty v-if="!store.plugins.length" description="当前账号暂无可用插件" />
|
||||
<p v-if="!store.plugins.length" class="empty-tip">当前账号暂无可用插件</p>
|
||||
<div v-else class="ilist">
|
||||
<div v-for="(p, i) in store.plugins" :key="p.id" class="irow">
|
||||
<span class="ridx mono">{{ String(i + 1).padStart(2, '0') }}</span>
|
||||
@@ -77,34 +80,37 @@
|
||||
</div>
|
||||
</div>
|
||||
</el-collapse-item>
|
||||
</el-collapse>
|
||||
|
||||
<!-- 修改密码 -->
|
||||
<el-card class="pwd-card" shadow="never" title="修改密码">
|
||||
<el-form label-position="top" :model="form" :rules="rules" ref="formRef">
|
||||
<el-form-item label="旧密码" prop="oldPwd">
|
||||
<el-input v-model="form.oldPwd" type="password" show-password placeholder="请输入旧密码" />
|
||||
</el-form-item>
|
||||
<el-form-item label="新密码" prop="newPwd">
|
||||
<el-input v-model="form.newPwd" type="password" show-password placeholder="至少 6 位,不与原密码相同" />
|
||||
</el-form-item>
|
||||
<el-form-item label="确认新密码" prop="newPwd2">
|
||||
<el-input v-model="form.newPwd2" type="password" show-password placeholder="再次输入新密码" />
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" :loading="pwdBusy" @click="changePwd" style="width: 100%">
|
||||
<el-collapse-item name="password">
|
||||
<template #title>
|
||||
<div class="panel-title">
|
||||
<el-icon><Lock /></el-icon>
|
||||
<span>修改密码</span>
|
||||
</div>
|
||||
</template>
|
||||
<el-form label-position="top" :model="form" :rules="rules" ref="formRef" class="pwd-form">
|
||||
<el-form-item label="旧密码" prop="oldPwd">
|
||||
<el-input v-model="form.oldPwd" type="password" show-password placeholder="请输入旧密码" />
|
||||
</el-form-item>
|
||||
<el-form-item label="新密码" prop="newPwd">
|
||||
<el-input v-model="form.newPwd" type="password" show-password placeholder="至少 6 位,不与原密码相同" />
|
||||
</el-form-item>
|
||||
<el-form-item label="确认新密码" prop="newPwd2">
|
||||
<el-input v-model="form.newPwd2" type="password" show-password placeholder="再次输入新密码" />
|
||||
</el-form-item>
|
||||
<el-button type="primary" :loading="pwdBusy" @click="changePwd" class="pwd-submit">
|
||||
{{ pwdBusy ? '提交中…' : '保存新密码' }}
|
||||
</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
</el-card>
|
||||
</el-form>
|
||||
</el-collapse-item>
|
||||
</el-collapse>
|
||||
</el-drawer>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, reactive, computed } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { Connection, Box } from '@element-plus/icons-vue'
|
||||
import { Connection, Box, Lock, Camera } from '@element-plus/icons-vue'
|
||||
import { store, log, clearAvatarCache, accountAvatar } from '../store'
|
||||
import { loginPlatform, logoutPlatform, adminPassword, adminAvatarUpload } from '../api'
|
||||
|
||||
@@ -112,7 +118,7 @@ const emit = defineEmits(['close'])
|
||||
// 由父组件 v-if 控制挂载,挂载即展开;关闭经 @close 通知父组件卸载
|
||||
const visible = ref(true)
|
||||
|
||||
// 展示名:优先真实姓名(钉钉登录带入),无姓名时回退账号(工号)
|
||||
// 展示名:优先昵称(真实姓名),无昵称时回退账号(工号)
|
||||
const displayName = computed(() => store.nickname || store.current)
|
||||
|
||||
// 头像:复用全局 store 的在线头像(带 localStorage 缓存);加载失败时清除缓存并回退首字符色块
|
||||
@@ -143,7 +149,7 @@ function pickAvatar() {
|
||||
fileInput.click()
|
||||
}
|
||||
|
||||
const activeNames = ref(['platforms', 'plugins'])
|
||||
const activeNames = ref(['platforms', 'plugins']) // 修改密码默认折叠,点击展开
|
||||
const busy = ref('')
|
||||
|
||||
async function relogin(id) {
|
||||
@@ -235,55 +241,50 @@ async function changePwd() {
|
||||
|
||||
/* ================= 个人信息卡 ================= */
|
||||
.pcard {
|
||||
margin-bottom: 18px;
|
||||
background: #ffffff;
|
||||
margin-bottom: 14px;
|
||||
background: #fff;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 14px;
|
||||
border-radius: var(--radius);
|
||||
overflow: hidden;
|
||||
box-shadow: 0 10px 28px -18px rgba(23, 24, 26, .35);
|
||||
}
|
||||
.cover {
|
||||
height: 66px;
|
||||
background:
|
||||
radial-gradient(360px 200px at 90% -30%, rgba(208, 74, 36, .5), transparent 60%),
|
||||
radial-gradient(300px 180px at -10% 120%, rgba(120, 128, 140, .4), transparent 60%),
|
||||
#1a1c1f;
|
||||
position: relative;
|
||||
height: 58px;
|
||||
background: linear-gradient(135deg, #dfe7ff 0%, #eef2ff 55%, #f6f8ff 100%);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.pcard-main {
|
||||
display: flex; align-items: center; gap: 14px;
|
||||
padding: 0 18px 16px;
|
||||
padding: 0 18px 14px;
|
||||
margin-top: -30px;
|
||||
position: relative;
|
||||
}
|
||||
.avatar-wrap { position: relative; flex: none; }
|
||||
.avatar {
|
||||
border: 3px solid #fff;
|
||||
border-radius: 50%;
|
||||
box-shadow: 0 6px 16px -6px rgba(23, 24, 26, .45);
|
||||
background: #17181a;
|
||||
color: #f6f4ec;
|
||||
box-shadow: 0 4px 14px -4px rgba(59, 108, 255, .35);
|
||||
background: var(--primary-grad);
|
||||
color: #fff;
|
||||
font-weight: 700;
|
||||
flex: none;
|
||||
}
|
||||
.avatar-pick {
|
||||
position: absolute; right: -2px; bottom: -2px;
|
||||
width: 20px; height: 20px; border-radius: 50%;
|
||||
display: grid; place-items: center;
|
||||
border: 2px solid #fff;
|
||||
background: var(--primary); color: #fff;
|
||||
cursor: pointer; padding: 0;
|
||||
transition: transform .12s;
|
||||
}
|
||||
.avatar-pick:hover { transform: scale(1.12); }
|
||||
.pcard-id { min-width: 0; }
|
||||
.name-line { display: flex; align-items: center; gap: 8px; }
|
||||
.name-line strong { font-size: 16px; letter-spacing: .01em; color: #17181a; }
|
||||
.admin {
|
||||
font-style: normal; font-size: 10.5px; font-weight: 600;
|
||||
color: #d04a24;
|
||||
border: 1px solid rgba(208, 74, 36, .35);
|
||||
background: rgba(208, 74, 36, .07);
|
||||
border-radius: 4px;
|
||||
padding: 1px 6px;
|
||||
letter-spacing: .04em;
|
||||
.name-line strong {
|
||||
font-size: 17px; font-weight: 700; letter-spacing: .01em; color: var(--text);
|
||||
white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 210px;
|
||||
}
|
||||
.dept { font-size: 12px; color: var(--text-faint); }
|
||||
.avatar-act {
|
||||
display: inline-block; margin-top: 5px;
|
||||
font-size: 11px; color: #d04a24; cursor: pointer;
|
||||
border-bottom: 1px dashed rgba(208, 74, 36, .4);
|
||||
}
|
||||
.avatar-act:hover { color: #b23c1b; }
|
||||
.acct { display: block; margin-top: 3px; font-size: 11.5px; color: var(--text-faint); }
|
||||
.dept { display: block; margin-top: 2px; font-size: 12px; color: var(--text-sub); }
|
||||
|
||||
.pcard-rows { border-top: 1px solid var(--border); }
|
||||
.crow {
|
||||
@@ -294,11 +295,21 @@ async function changePwd() {
|
||||
}
|
||||
.crow:last-child { border-bottom: none; }
|
||||
.crow span:first-child { color: var(--text-sub); }
|
||||
.crow .mono { color: #17181a; font-size: 13px; font-weight: 600; }
|
||||
.crow .mono { color: var(--text); font-size: 13px; font-weight: 600; }
|
||||
|
||||
/* ================= 折叠面板 ================= */
|
||||
.panel-title { display: flex; align-items: center; gap: 8px; font-size: 13px; color: var(--text-sub); }
|
||||
.panel-title :deep(.el-icon) { color: #d04a24; }
|
||||
.panel-title :deep(.el-icon) { color: var(--primary); }
|
||||
:deep(.el-collapse) { border: none; }
|
||||
:deep(.el-collapse-item__header) {
|
||||
height: 42px; background: #f6f8fd;
|
||||
border: 1px solid var(--border); border-radius: 9px;
|
||||
padding: 0 14px; margin-bottom: 8px;
|
||||
font-weight: 500;
|
||||
}
|
||||
:deep(.el-collapse-item__header.is-active) { border-color: rgba(59, 108, 255, .45); }
|
||||
:deep(.el-collapse-item__wrap) { border-bottom: none; }
|
||||
:deep(.el-collapse-item__content) { padding: 4px 6px 8px; }
|
||||
|
||||
/* ---------- 平台登录态:编号 + 发丝线 ---------- */
|
||||
.prow {
|
||||
@@ -327,17 +338,16 @@ async function changePwd() {
|
||||
.irow:last-child { border-bottom: none; }
|
||||
.iname { flex: 1; color: var(--text); font-size: 13.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.iver { font-size: 11px; color: var(--text-faint); }
|
||||
.i-dot { flex: none; width: 5px; height: 5px; border-radius: 50%; background: #d04a24; }
|
||||
.i-dot { flex: none; width: 5px; height: 5px; border-radius: 50%; background: var(--primary); }
|
||||
.empty-tip {
|
||||
margin: 2px 0 8px; padding: 14px 0;
|
||||
text-align: center; font-size: 12.5px; color: var(--text-faint);
|
||||
border: 1px dashed var(--border-strong); border-radius: 9px;
|
||||
background: #fafbfe;
|
||||
}
|
||||
|
||||
/* ---------- 修改密码 ---------- */
|
||||
.pwd-card { margin-top: 16px; border-radius: 14px; border-color: var(--border); }
|
||||
.pwd-card :deep(.el-card__header) {
|
||||
font-size: 13px; font-weight: 600;
|
||||
border-bottom: 1px solid var(--border);
|
||||
padding: 12px 16px;
|
||||
}
|
||||
.pwd-card :deep(.el-card__body) { padding: 16px; }
|
||||
.pwd-card :deep(.el-form-item__label) { color: var(--text-sub); font-weight: 500; }
|
||||
.pwd-card :deep(.el-button--primary) { width: 100%; border-color: transparent; background: #17181a; }
|
||||
.pwd-card :deep(.el-button--primary:hover) { background: #26282c; }
|
||||
.pwd-form { padding-top: 2px; }
|
||||
.pwd-form :deep(.el-form-item__label) { color: var(--text-sub); font-weight: 500; }
|
||||
.pwd-submit { width: 100%; border-color: transparent; }
|
||||
</style>
|
||||
@@ -2,7 +2,6 @@ import { reactive } from 'vue'
|
||||
|
||||
export const store = reactive({
|
||||
appName: '',
|
||||
controlplane: '', // 控制面地址(管理员跳转用),来自 /api/meta
|
||||
platforms: [],
|
||||
plugins: [],
|
||||
selectedId: '',
|
||||
@@ -14,14 +13,14 @@ export const store = reactive({
|
||||
lastResult: null, // {ok, error}
|
||||
lastSummary: '', // 完成时后端返回的摘要
|
||||
wsOn: false,
|
||||
// 控制面管理视图(统一后端数据库 API)
|
||||
isAdmin: false,
|
||||
// 个人身份信息(中心机 accounts,登录/会话校验回填)
|
||||
dept: '',
|
||||
nickname: '', // 真实姓名(中心机 accounts.nickname,钉钉登录时自动带入)
|
||||
avatar: '', // 账号头像文件名(中心机 accounts.avatar,用户上传)
|
||||
avatarUrl: '', // 在线头像(localStorage 缓存,避免每次刷新都请求)
|
||||
current: (() => { try { return localStorage.getItem('cp_account') || '' } catch (_) { return '' } })(),
|
||||
view: 'plugin', // 'plugin' | 'admin'
|
||||
view: 'plugin', // 当前主视图(插件页)
|
||||
authExpired: false, // 授权票据已过期(最长离线 7 天),须联网刷新才能继续使用
|
||||
})
|
||||
|
||||
// ===== 在线头像:优先读缓存,无缓存时请求接口并落盘;图片加载失败时清除缓存重新拉取 =====
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
@@ -23,6 +24,34 @@ URL = f"http://127.0.0.1:{PORT}"
|
||||
HERE = Path(sys.executable).resolve().parent if FROZEN else Path(__file__).resolve().parent
|
||||
PID_FILE = HERE / ".webhost.pid"
|
||||
|
||||
# 跨解释器单实例锁:launch.py 可能被 venv 与系统 Python 等不同入口重复启动,
|
||||
# 端口冲突时互相 kill/重建导致卡顿;命名互斥量保证全局只有一份实例。
|
||||
_MUTEX_HANDLE = None
|
||||
|
||||
|
||||
def _acquire_singleton(name: str = "Local\\37duWebhostSingleton") -> bool:
|
||||
"""获取 Windows 命名互斥量;失败(已存在)返回 False,调用方应退出。"""
|
||||
global _MUTEX_HANDLE
|
||||
if sys.platform != "win32":
|
||||
return True
|
||||
try:
|
||||
from ctypes import wintypes
|
||||
import ctypes
|
||||
|
||||
k32 = ctypes.windll.kernel32
|
||||
k32.CreateMutexW.restype = wintypes.HANDLE
|
||||
k32.GetLastError.restype = wintypes.DWORD
|
||||
handle = k32.CreateMutexW(None, False, name)
|
||||
if not handle:
|
||||
return False
|
||||
if k32.GetLastError() == 183: # ERROR_ALREADY_EXISTS
|
||||
k32.CloseHandle(handle)
|
||||
return False
|
||||
_MUTEX_HANDLE = handle # 持有句柄,防止被 GC 释放导致锁失效
|
||||
return True
|
||||
except Exception:
|
||||
return True # 非关键路径,获取失败不阻塞启动
|
||||
|
||||
|
||||
def _port_pids() -> list[int]:
|
||||
return [c.pid for c in psutil.net_connections(kind="inet")
|
||||
@@ -75,6 +104,11 @@ def _start_server():
|
||||
# 窗口模式无 stdout/stderr(None),uvicorn 日志 formatter 会调 sys.stdout.isatty() 崩溃
|
||||
_devnull = open(os.devnull, "w", encoding="utf-8") # noqa: SIM115 进程级常驻
|
||||
sys.stdout = sys.stderr = _devnull
|
||||
# frozen 模式无控制台:日志落盘 exe 同级 webhost.log(排查启动失败/运行异常的唯一窗口)
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
handlers=[logging.FileHandler(HERE / "webhost.log", encoding="utf-8")])
|
||||
import uvicorn
|
||||
from webhost.backend.main import app
|
||||
|
||||
@@ -165,6 +199,12 @@ def _stop(server) -> None:
|
||||
|
||||
|
||||
def main() -> int:
|
||||
# 单实例锁:已有实例(无论 venv/系统 Python 哪个入口)直接退出,避免端口互杀卡顿
|
||||
if not _acquire_singleton():
|
||||
if not _port_free():
|
||||
print("[webhost] 已有实例在运行,本次启动退出。")
|
||||
return 0
|
||||
# 端口空闲说明旧实例只剩窗口壳、服务已死:接管重启
|
||||
app_name = "37du 自动化工作台"
|
||||
# 任务栏图标分组/固定:统一 AppUserModelID(如做快捷方式需保持一致)
|
||||
try:
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
; 37du 自动化工作台 - Inno Setup 安装脚本 (Inno Setup 7)
|
||||
; 编译: "C:\Program Files\Inno Setup 7\ISCC.exe" webhost\tools\install.iss
|
||||
; 打包内容: 主程序 37du-host.exe + 插件执行壳 37du-host-runner.exe + plugins/
|
||||
; 不含: 37du-host-console.exe(调试版)、.env(机器特定配置,缺失时使用默认值)
|
||||
; 打包内容: 主程序 37du-host.exe + 插件执行壳 37du-host-runner.exe + .env 默认配置
|
||||
; .env 与 webhost/.env 同源(控制面/平台共享配置):仅首次安装写入(onlyifdoesntexist),
|
||||
; 升级不覆盖机器已有 .env;不含 37du-host-console.exe(调试版)、plugins/(登录后自下载)
|
||||
|
||||
#define MyAppName "37du 自动化工作台"
|
||||
#define MyAppVersion "1.0.0"
|
||||
#define MyAppVersion "1.1.3"
|
||||
#define MyAppExeName "37du-host.exe"
|
||||
|
||||
[Setup]
|
||||
@@ -34,6 +35,8 @@ Source: "..\dist-exe\37du-host\*"; DestDir: "{app}"; Flags: recursesu
|
||||
Source: "..\dist-exe\37du-host-runner.exe"; DestDir: "{app}"; Flags: ignoreversion
|
||||
; 壳子版本标记:执行端据此比对控制面版本判断是否需要自动升级
|
||||
Source: "..\tools\shell.version"; DestDir: "{app}"; Flags: ignoreversion
|
||||
; .env 默认配置:仅首次安装写入,升级/重装不覆盖机器已有配置
|
||||
Source: "..\.env"; DestDir: "{app}"; Flags: onlyifdoesntexist uninsneveruninstall
|
||||
; 插件不由安装包分发:执行机首次启动/登录后按账号权限从控制面自下载(见 backend/core/plugin_sync.py)
|
||||
|
||||
[Icons]
|
||||
|
||||
@@ -1 +1 @@
|
||||
1.0.0
|
||||
1.1.3
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
# -*- 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())
|
||||
@@ -1,59 +0,0 @@
|
||||
# -*- 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())
|
||||
@@ -1,109 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""社保系统增减员办理 - webhost 场景插件(XQ0008 + XQ0014 合并版)
|
||||
|
||||
四个执行模式 + 预检,覆盖重庆社保增减员业务闭环:
|
||||
增员名单制作 / 减员名单制作(XQ0008,纯 Excel 离线生成)
|
||||
增员办理 / 核查回盘(XQ0014,DrissionPage 登录政务平台逐单位办理)
|
||||
预检(只读源表 + 台账取号校验,不开浏览器)
|
||||
执行分批:增员办理/核查回盘按 limit 字段控制单次处理的单位数(0=不限)。
|
||||
登录与凭证:按参保单位从「社保户头管理台账」取号,浏览器现场真登录(无 cookies 缓存)。
|
||||
"""
|
||||
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
||||
|
||||
from . import config
|
||||
from . import source
|
||||
|
||||
|
||||
class SbPersonChangePlugin(ScenePlugin):
|
||||
id = "sb_person_change"
|
||||
name = "社保系统增减员办理"
|
||||
version = "1.0.0"
|
||||
description = "重庆社保增减员全流程:增员/减员名单制作 → 平台增员办理 → 核查回盘(含预检)"
|
||||
platform = "" # 政务网自登录(台账取号 + 浏览器现场登录),不使用底座共享登录态
|
||||
uses_month = False # 源表按最新 *社保*.xlsx 自动定位,无需月份参数
|
||||
fields = [
|
||||
{"key": "mode", "label": "执行模式", "type": "select",
|
||||
"options": ["增员名单制作", "减员名单制作", "增员办理", "核查回盘", "预检"],
|
||||
"default": "增员名单制作"},
|
||||
{"key": "limit", "label": "分批条数(0=不限)", "type": "int", "default": 0},
|
||||
{"key": "debug_mode", "label": "调试模式", "type": "select",
|
||||
"options": ["关闭", "开启"], "default": "关闭"},
|
||||
]
|
||||
|
||||
def run(self, fields: dict, ctx) -> dict:
|
||||
fields = fields or {}
|
||||
# 注入日志与调试开关(插件内全部模块经 config.log 输出)
|
||||
config.set_log(ctx.log)
|
||||
config.set_debug(str(fields.get("debug_mode") or "关闭") == "开启")
|
||||
mode = str(fields.get("mode") or "增员名单制作").strip()
|
||||
try:
|
||||
limit = max(0, int(fields.get("limit") or 0))
|
||||
except (TypeError, ValueError):
|
||||
limit = 0
|
||||
|
||||
ctx.log(f"开始执行:{mode}" + (f"(分批 {limit})" if limit else ""))
|
||||
|
||||
if mode == "预检":
|
||||
return self._run_precheck(ctx)
|
||||
if mode == "增员名单制作":
|
||||
from . import mode_make_add
|
||||
return mode_make_add.run(ctx)
|
||||
if mode == "减员名单制作":
|
||||
from . import mode_make_stop
|
||||
return mode_make_stop.run(ctx)
|
||||
if mode == "增员办理":
|
||||
from . import mode_do_add
|
||||
return mode_do_add.run(ctx, limit=limit)
|
||||
if mode == "核查回盘":
|
||||
from . import mode_check
|
||||
return mode_check.run(ctx, limit=limit)
|
||||
raise ValueError(f"未知执行模式:{mode}")
|
||||
|
||||
# ---------- 预检(不开浏览器,验证数据链路) ----------
|
||||
def _run_precheck(self, ctx) -> dict:
|
||||
from . import mode_do_add
|
||||
from datetime import datetime
|
||||
|
||||
ctx.progress(5)
|
||||
notes, problems = [], []
|
||||
|
||||
# 1) 增员办理预检:待办单位 + 导入文件 + 台账取号
|
||||
units = source.load_add_units()
|
||||
if units:
|
||||
ctx.progress(30)
|
||||
accounts = source.load_accounts([u for u, _ in units])
|
||||
tasks = mode_do_add.precheck(units, accounts)
|
||||
if tasks is None:
|
||||
problems.append("增员办理预检未通过(缺导入文件/台账账号,详见日志)")
|
||||
else:
|
||||
notes.append(f"增员办理:{len(tasks)} 个单位可办(共 {sum(t['count'] for t in tasks)} 人)")
|
||||
else:
|
||||
notes.append("增员办理:无待办数据(办理状态为空的新参保-增员)")
|
||||
ctx.progress(55)
|
||||
|
||||
# 2) 核查回盘预检:待审核单位 + 台账取号
|
||||
tasks_chk = source.load_check_tasks()
|
||||
if tasks_chk:
|
||||
ctx.progress(75)
|
||||
accounts_chk = source.load_accounts([t['unit'] for t in tasks_chk])
|
||||
errs = []
|
||||
for t in tasks_chk:
|
||||
acc = accounts_chk.get(t['unit'])
|
||||
if acc is None:
|
||||
errs.append(f"[{t['unit']}] 台账未匹配")
|
||||
elif not acc['username'] or not acc['password']:
|
||||
errs.append(f"[{t['unit']}] 账号或密码缺失")
|
||||
if errs:
|
||||
problems.append("核查回盘预检未通过:" + ";".join(errs))
|
||||
else:
|
||||
notes.append(f"核查回盘:{len(tasks_chk)} 个单位可核查"
|
||||
f"(共 {sum(t['count'] for t in tasks_chk)} 人待审核)")
|
||||
else:
|
||||
notes.append("核查回盘:无待核查数据(办理状态=待审核)")
|
||||
ctx.progress(100)
|
||||
|
||||
summary = f"预检完成 {datetime.now():%H:%M:%S}:" + (";".join(notes) if notes else "无待办")
|
||||
return {"summary": summary, "rows": [], "notes": notes + problems}
|
||||
|
||||
|
||||
PLUGINS.append(SbPersonChangePlugin())
|
||||
@@ -1,256 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""社保系统增减员办理(sb_person_change)插件配置。
|
||||
|
||||
合并 XQ0008(名单制作)+ XQ0014(增员办理/核查回盘)的固化配置,
|
||||
与 workflows 影刀版各源文件的常量保持同源(四方向零依赖,各自演进)。
|
||||
"""
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
from glob import glob
|
||||
from pathlib import Path
|
||||
|
||||
# ==================== 插件内目录 ====================
|
||||
_HERE = Path(__file__).resolve().parent
|
||||
DEBUG_DIR = _HERE / "debug" # 截图/验证码/回写缓存落盘目录(debug 开启或崩溃恢复用)
|
||||
CKPT_FILE = DEBUG_DIR / "writeback_pending.json"
|
||||
|
||||
# ==================== 1. 文件路径配置 ====================
|
||||
SOURCE_DIR = os.getenv("cq_social_change_dir") or r"D:\资料\人资\重庆社保增减员导入名单制作"
|
||||
LEDGER_DIR = os.getenv("cq_social_ledger_dir") or r"D:\资料\人资\社保系统增减员办理"
|
||||
SOURCE_GLOB = "*社保*.xlsx" # 源名单文件(年月动态,取最新)
|
||||
LEDGER_GLOB = "*社保户头管理台账*.xlsx" # 台账文件(可能加前后缀,取最新)
|
||||
IMPORT_DIR_NAME = "新参保-增员" # 增员导入名单产出目录(按参保类型分文件夹)
|
||||
HUIPAN_DIR = r"D:\资料\人资\社保系统增减员办理\回盘打印\新参保-增员" # 回盘文件保存目录
|
||||
|
||||
# ==================== 2. 源表结构配置 ====================
|
||||
REGION = "重庆" # 区域筛选值
|
||||
OPERATION_TYPE = "新参保" # 参保类型筛选值
|
||||
TYPE_COL, REGION_COL, STATUS_COL, UNIT_COL = "参保类型", "区域", "办理状态", "参保单位"
|
||||
SOURCE_HEADER_ROW = 3 # 源表表头在第3行
|
||||
|
||||
# 台账「缴费比例」sheet 数据列(0-based,表头占 1-2 行已跳过)
|
||||
LEDGER_COL = {"户头": 1, "城市": 3, "在用": 4, "信用代码": 8, "平台用户名": 10, "平台密码": 11}
|
||||
|
||||
# ==================== 3. 增员名单模板映射(generate_add 同源) ====================
|
||||
ADD_SHEET_KEY = "参保名单"
|
||||
ADD_TEMPLATE_FILE = "增员模版.xls"
|
||||
OUTPUT_DIR_NAME = {"新参保": "新参保-增员", "转移参保": "转移参保-增员"}
|
||||
COLUMN_MAP_ADD = {
|
||||
'姓名': '姓名',
|
||||
'证件号码': '身份证号码',
|
||||
'民族': '民族',
|
||||
'月基本工资额': '工资', # 用户指定:月基本工资额取「工资」列(申报基数大量为空)
|
||||
'户口性质': '户口性质',
|
||||
'文化程度': '文化程度',
|
||||
'联系电话': '电话号码',
|
||||
'单位名称': '参保单位',
|
||||
'社保号': '社保号',
|
||||
'参保单位全称': '参保单位全称',
|
||||
'备注': '备注',
|
||||
}
|
||||
EDU_MAP = {
|
||||
'硕士研究生': '14.硕士研究生', '本科': '21.大学本科', '大专': '31.大学专科',
|
||||
'高中': '61.普通中学', '职高/中专/中技': '44.职业高中', '初中': '71.初级中学',
|
||||
'小学': '81.小学',
|
||||
}
|
||||
NATION_MAP = {
|
||||
'汉族': '01.汉族', '蒙古族': '02.蒙古族', '回族': '03.回族', '藏族': '04.藏族',
|
||||
'维吾尔族': '05.维吾尔族', '苗族': '06.苗族', '彝族': '07.彝族', '壮族': '08.壮族',
|
||||
'布依族': '09.布依族', '朝鲜族': '10.朝鲜族', '满族': '11.满族', '侗族': '12.侗族',
|
||||
'瑶族': '13.瑶族', '白族': '14.白族', '土家族': '15.土家族', '哈尼族': '16.哈尼族',
|
||||
'哈萨克族': '17.哈萨克族', '傣族': '18.傣族', '黎族': '19.黎族', '傈僳族': '20.傈僳族',
|
||||
'佤族': '21.佤族', '畲族': '22.畲族', '高山族': '23.高山族', '拉祜族': '24.拉祜族',
|
||||
'水族': '25.水族', '东乡族': '26.东乡族', '纳西族': '27.纳西族', '景颇族': '28.景颇族',
|
||||
'柯尔克孜族': '29.柯尔克孜族', '土族': '30.土族', '达斡尔族': '31.达斡尔族',
|
||||
'仫佬族': '32.仫佬族', '羌族': '33.羌族', '布朗族': '34.布朗族', '撒拉族': '35.撒拉族',
|
||||
'毛南族': '36.毛南族', '仡佬族': '37.仡佬族', '锡伯族': '38.锡伯族', '阿昌族': '39.阿昌族',
|
||||
'普米族': '40.普米族', '塔吉克族': '41.塔吉克族', '怒族': '42.怒族',
|
||||
'乌孜别克族': '43.乌孜别克族', '俄罗斯族': '44.俄罗斯族', '鄂温克族': '45.鄂温克族',
|
||||
'德昂族': '46.德昂族', '保安族': '47.保安族', '裕固族': '48.裕固族', '京族': '49.京族',
|
||||
'塔塔尔族': '50.塔塔尔族', '独龙族': '51.独龙族', '鄂伦春族': '52.鄂伦春族',
|
||||
'赫哲族': '53.赫哲族', '门巴族': '54.门巴族', '珞巴族': '55.珞巴族', '基诺族': '56.基诺族',
|
||||
'少数民族': '57.少数民族', '其他': '99.其他',
|
||||
}
|
||||
RESIDENCE_MAP = {
|
||||
'本地城镇': '11.本市城镇', '本地农村': '21.本市农村',
|
||||
'外地城镇': '12.外市城镇', '外地农村': '22.外市农村',
|
||||
}
|
||||
DEFAULT_VALUES_ADD = {
|
||||
'个人身份': '24.工人',
|
||||
'证件类型': '01.居民身份证(户口簿)',
|
||||
'国籍': 'CHN.中国',
|
||||
'专职技能': '499.未定职级',
|
||||
'技能等级': '无',
|
||||
'工种': '',
|
||||
'备注': '',
|
||||
}
|
||||
TPL_DATA_START_ROW = 4
|
||||
TPL_COLS_ADD = [
|
||||
'证件号码', '姓名', '民族', '首次参加工作日期', '月基本工资额', '工种', '个人身份',
|
||||
'户口性质', '联系电话', '文化程度', '养老保险参保时间', '失业保险参保时间',
|
||||
'医疗保险参保时间', '工伤保险参保时间', '生育保险参保时间', '证件类型', '国籍',
|
||||
'备注', '专职技能', '技能等级',
|
||||
]
|
||||
DATE_COLS_ADD = {
|
||||
'首次参加工作日期', '养老保险参保时间', '失业保险参保时间',
|
||||
'医疗保险参保时间', '工伤保险参保时间', '生育保险参保时间',
|
||||
}
|
||||
|
||||
# ==================== 4. 减员名单模板映射(generate_stop 同源) ====================
|
||||
STOP_SHEET_KEY = "停保名单"
|
||||
STOP_TEMPLATE_FILE = "减员模版.xls"
|
||||
STOP_OUTPUT_DIR_NAME = "停保-减员"
|
||||
GROUP_COL_STOP = "参保单位"
|
||||
COLUMN_MAP_STOP = {
|
||||
'个人编号': '社保编号',
|
||||
'证件号码': '身份证号码',
|
||||
'姓名': '停保人姓名',
|
||||
'单位社保号': '单位社保号',
|
||||
'单位名称': '参保单位',
|
||||
}
|
||||
DEFAULT_VALUES_STOP = {
|
||||
'减少原因': '在职人员主动解除劳动合同',
|
||||
'养老保险减少标志': '1 减少',
|
||||
'失业保险减少标志': '1 减少',
|
||||
'医疗保险减少标志': '1 减少',
|
||||
'工伤保险减少标志': '1 减少',
|
||||
'生育保险减少标志': '1 减少',
|
||||
'失业原因': '3 劳动者自愿辞职',
|
||||
}
|
||||
TPL_COLS_STOP = [
|
||||
'个人编号', '证件号码', '姓名', '减少时间', '减少原因',
|
||||
'养老保险减少标志', '失业保险减少标志', '医疗保险减少标志',
|
||||
'工伤保险减少标志', '生育保险减少标志', '失业原因',
|
||||
]
|
||||
DATE_COLS_STOP = {'减少时间'}
|
||||
|
||||
# ==================== 5. 增员办理 / 核查回盘配置(import_add/check_review 同源) ====================
|
||||
CHECK_STATUS = "待审核" # 核查范围:办理状态为该值的人员
|
||||
DONE_STATUS = "已办结" # 已申报查询里第一条的该状态才继续查看
|
||||
PASS_STATUS = "参保成功" # 审核通过 → 办理状态
|
||||
FAIL_STATUS = "参保失败" # 审核不通过(非系统错误)→ 办理状态
|
||||
ERR_400_KEYWORD = "status 400" # aae111 含该关键字 = 系统错误,需重新增员
|
||||
RUN_400_CLEAR = True # 400系统错误:运行结束后统一清空办理状态回待办
|
||||
REPLAY_PREFIX = "人员增减申请回盘表" # 回盘保存文件名:前缀_单位_日期.xlsx
|
||||
INS_STATUSES = ["养老参保状态", "失业参保状态", "医疗参保状态",
|
||||
"工伤参保状态", "生育参保状态"]
|
||||
INS_OK = "参保缴费"
|
||||
|
||||
# ==================== 6. 运行开关(由 fields 注入,不在文件内固化 limit/debug) ====================
|
||||
DEBUG_MODE = False
|
||||
|
||||
|
||||
def set_debug(on) -> None:
|
||||
global DEBUG_MODE
|
||||
DEBUG_MODE = bool(on)
|
||||
|
||||
|
||||
# ==================== 7. 日志钩子(print → ctx.log) ====================
|
||||
_log_fn = print
|
||||
|
||||
|
||||
def set_log(fn) -> None:
|
||||
"""插件 run() 启动时把 ctx.log 注入进来,全部模块经 log() 输出。"""
|
||||
global _log_fn
|
||||
_log_fn = fn if fn else print
|
||||
|
||||
|
||||
def log(msg: str) -> None:
|
||||
try:
|
||||
_log_fn(msg)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ==================== 8. 共享文本/文件辅助 ====================
|
||||
def _safe_name(value):
|
||||
"""单位名转安全文件名(与影刀版规则一致,保证产出文件名可复现)。"""
|
||||
if value is None or not str(value).strip():
|
||||
return "未知单位"
|
||||
try:
|
||||
if value != value: # NaN
|
||||
return "未知单位"
|
||||
except Exception:
|
||||
pass
|
||||
name = str(value).replace("/", "_").replace("\\", "_").replace(":", "_").strip()
|
||||
if name.endswith("店"):
|
||||
name = name[:-1]
|
||||
return name
|
||||
|
||||
|
||||
def _to_text(value):
|
||||
"""None/NaN → '',其余转去空白字符串(台账号/密码列用)。"""
|
||||
if value is None:
|
||||
return ""
|
||||
try:
|
||||
if value != value: # NaN
|
||||
return ""
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if isinstance(value, float) and value.is_integer():
|
||||
return str(int(value))
|
||||
return str(value).strip()
|
||||
|
||||
|
||||
def _clean_value(value):
|
||||
"""None/NaN 归一为 '',其余原样(用于写入模板单元格)。"""
|
||||
if value is None:
|
||||
return ''
|
||||
if isinstance(value, float) and math.isnan(value):
|
||||
return ''
|
||||
return value
|
||||
|
||||
|
||||
def _norm_id(v):
|
||||
"""身份证号规范化:去空格、转大写;数值型(纯数字身份证存成数值)转整数字符串。"""
|
||||
if v is None:
|
||||
return ''
|
||||
if isinstance(v, float) and v.is_integer():
|
||||
v = int(v)
|
||||
return str(v).strip().upper()
|
||||
|
||||
|
||||
def _id_hit(cid, ref_ids):
|
||||
"""身份证匹配:规范化后精确匹配(不做前缀/模糊,防同区县同出生日期撞车回写错行)。"""
|
||||
return bool(cid) and cid in ref_ids
|
||||
|
||||
|
||||
def _latest_file(directory, pattern):
|
||||
"""目录内按模式取最新文件(排除 Excel 临时文件 ~$)。"""
|
||||
candidates = [p for p in glob(os.path.join(directory, pattern))
|
||||
if not os.path.basename(p).startswith("~$")]
|
||||
if not candidates:
|
||||
raise FileNotFoundError(f"在 {directory} 下未找到匹配 {pattern} 的文件")
|
||||
return max(candidates, key=os.path.getmtime)
|
||||
|
||||
|
||||
def _pick_sheet(xl, exact_name, keyword, pattern=None):
|
||||
"""优先精确 sheet 名,其次按关键字/正则匹配;正则匹配时取年月最新。"""
|
||||
if hasattr(xl, "sheet_names"):
|
||||
names = [n.strip() for n in xl.sheet_names]
|
||||
else: # openpyxl workbook
|
||||
names = [n.strip() for n in xl.sheetnames]
|
||||
if exact_name in names:
|
||||
return exact_name
|
||||
if pattern:
|
||||
hits = [(int(m.group(1)), int(m.group(2)), n)
|
||||
for n in names if (m := re.match(pattern, n))]
|
||||
if hits:
|
||||
return max(hits)[2]
|
||||
for n in names:
|
||||
if keyword in n:
|
||||
return n
|
||||
raise ValueError(f"未找到目标 sheet(精确={exact_name},关键字={keyword}),"
|
||||
f"实际 sheets:{names}")
|
||||
|
||||
|
||||
def check_not_locked(path):
|
||||
"""文件占用预检:被 Excel 独占打开时抛出友好错误,提示先关闭再运行。"""
|
||||
if not path or not os.path.isfile(path):
|
||||
return
|
||||
try:
|
||||
with open(path, "r+b"):
|
||||
pass
|
||||
except PermissionError:
|
||||
raise RuntimeError(f"文件被占用(请先关闭 Excel 再运行):{path}")
|
||||
@@ -1,209 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Excel 读写层(sb_person_change 插件)。
|
||||
|
||||
- 模板生成:xlrd 读取 + xlutils 复制《增员模版.xls》/《减员模版.xls》,
|
||||
保留 Sheet2 下拉字典与数据有效性(generate_add/generate_stop 同源);
|
||||
- 源名单回写:JSON 缓存防崩溃,运行结束统一 openpyxl 回写一次
|
||||
(import_add/check_review 同源机制,缓存文件落在插件 debug/ 目录)。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
from datetime import datetime
|
||||
from glob import glob
|
||||
|
||||
import xlrd
|
||||
from xlutils.copy import copy as xl_copy
|
||||
|
||||
from . import config
|
||||
|
||||
|
||||
def _log(msg):
|
||||
config.log(msg)
|
||||
|
||||
|
||||
# ==================== 模板写入(增员/减员共用) ====================
|
||||
def write_template(template_file, output_path, unit_no, unit_name, records, tpl_cols, date_cols):
|
||||
"""复制模板写入 B1/D1 及第4行起数据,另存为 output_path。
|
||||
|
||||
- xlrd 读取(formatting_info 保留样式)+ xlutils.copy 复制,保留下拉字典;
|
||||
- B1=社保号(或单位社保号),D1=单位全称;数据从模板第4行起,按 tpl_cols 顺序写入;
|
||||
- 日期列以 yyyy/m/d 文本写入(不补零,如 2026/9/1);
|
||||
- 模板原数据区中未被覆盖的多余示例行清空。
|
||||
"""
|
||||
rb = xlrd.open_workbook(template_file, formatting_info=True)
|
||||
orig_rows = rb.sheet_by_index(0).nrows
|
||||
wb = xl_copy(rb)
|
||||
ws = wb.get_sheet(0) # 批量导入
|
||||
ws.write(0, 1, unit_no) # B1 社保号/单位社保号
|
||||
ws.write(0, 3, unit_name) # D1 参保单位全称
|
||||
start = config.TPL_DATA_START_ROW - 1 # 0-based:模板第4行 → index 3
|
||||
for i, rec in enumerate(records):
|
||||
r = start + i
|
||||
for c, col in enumerate(tpl_cols):
|
||||
val = rec.get(col)
|
||||
if col in date_cols and val is not None:
|
||||
ws.write(r, c + 1, f"{val.year}/{val.month}/{val.day}")
|
||||
else:
|
||||
ws.write(r, c + 1, config._clean_value(val))
|
||||
# 清空模板原数据区未被覆盖的多余示例行
|
||||
for r in range(start + len(records), orig_rows):
|
||||
for c in range(1, len(tpl_cols) + 1):
|
||||
ws.write(r, c, "")
|
||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||
wb.save(output_path)
|
||||
|
||||
|
||||
def find_template_file(name):
|
||||
"""定位模板(优先精确名,其次按 *<名>*.xls 匹配,取最新)。name 如「增员模版.xls」。"""
|
||||
exact = os.path.join(config.SOURCE_DIR, name)
|
||||
if os.path.isfile(exact):
|
||||
return exact
|
||||
keyword = name.rsplit(".", 1)[0]
|
||||
candidates = glob(os.path.join(config.SOURCE_DIR, f"*{keyword}*.xls"))
|
||||
if not candidates:
|
||||
raise FileNotFoundError(
|
||||
f"在 {config.SOURCE_DIR} 下未找到《{name}》,请先准备导入模板。")
|
||||
return max(candidates, key=os.path.getmtime)
|
||||
|
||||
|
||||
def get_output_dir_add(operation_type):
|
||||
"""增员输出目录(SOURCE_DIR/新参保-增员 或 转移参保-增员),不存在则自动创建。"""
|
||||
sub = config.OUTPUT_DIR_NAME.get(operation_type)
|
||||
if not sub:
|
||||
raise ValueError(f"未知参保类型:{operation_type}(可选:{'/'.join(config.OUTPUT_DIR_NAME)})")
|
||||
out_dir = os.path.join(config.SOURCE_DIR, sub)
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
return out_dir
|
||||
|
||||
|
||||
def get_output_dir_stop():
|
||||
"""减员输出目录(SOURCE_DIR/停保-减员),不存在则自动创建。"""
|
||||
out_dir = os.path.join(config.SOURCE_DIR, config.STOP_OUTPUT_DIR_NAME)
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
return out_dir
|
||||
|
||||
|
||||
# ==================== 源名单回写(JSON 缓存防崩溃 + 结束统一回写) ====================
|
||||
# 回写内容只追加进内存 + 写轻量 JSON 缓存(防中途崩溃丢失,不碰 Excel);
|
||||
# 运行结束时 flush_writeback 统一写 Excel 一次,保存成功校验后删除缓存;
|
||||
# 下次启动若发现残留缓存(上次崩溃)先恢复回写再办新单。
|
||||
_PENDING_STATUS, _PENDING_REMARK = {}, {}
|
||||
_SOURCE_FILE_USED, _SOURCE_SHEET_USED = None, None
|
||||
|
||||
|
||||
def set_writeback_target(source_file, sheet_name):
|
||||
"""登记本次使用的源名单(供回写与文件占用预检)。"""
|
||||
global _SOURCE_FILE_USED, _SOURCE_SHEET_USED
|
||||
_SOURCE_FILE_USED, _SOURCE_SHEET_USED = source_file, sheet_name
|
||||
|
||||
|
||||
def get_writeback_target():
|
||||
return _SOURCE_FILE_USED, _SOURCE_SHEET_USED
|
||||
|
||||
|
||||
def _save_ckpt():
|
||||
"""把累积的回写内容写 JSON 缓存(临时文件+替换,避免写一半损坏)。"""
|
||||
data = [{"id": cid, "status": _PENDING_STATUS.get(cid, ""),
|
||||
"remark": _PENDING_REMARK.get(cid, "")}
|
||||
for cid in dict.fromkeys(list(_PENDING_STATUS) + list(_PENDING_REMARK))]
|
||||
config.DEBUG_DIR.mkdir(parents=True, exist_ok=True)
|
||||
tmp = config.CKPT_FILE.with_suffix(".tmp")
|
||||
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
tmp.replace(config.CKPT_FILE)
|
||||
|
||||
|
||||
def load_ckpt():
|
||||
"""启动时恢复上次未回写的累积内容(崩溃恢复)。返回已回写人员的身份证号集合。"""
|
||||
recovered = set()
|
||||
if not config.CKPT_FILE.exists():
|
||||
return recovered
|
||||
try:
|
||||
for it in json.loads(config.CKPT_FILE.read_text(encoding="utf-8")):
|
||||
cid = it.get("id")
|
||||
if it.get("status"):
|
||||
_PENDING_STATUS[cid] = it["status"]
|
||||
if it.get("remark"):
|
||||
_PENDING_REMARK[cid] = it["remark"]
|
||||
if cid:
|
||||
recovered.add(cid)
|
||||
return recovered
|
||||
except Exception as e:
|
||||
_log(f" 恢复回写缓存失败:{e}")
|
||||
return recovered
|
||||
|
||||
|
||||
def writeback_source(status_map, remark_map):
|
||||
"""按身份证号码聚合回写内容(内存 + JSON 缓存,不碰 Excel):
|
||||
status_map {身份证: 办理状态};remark_map {身份证: 备注}。"""
|
||||
_PENDING_STATUS.update(status_map or {})
|
||||
_PENDING_REMARK.update(remark_map or {})
|
||||
try:
|
||||
_save_ckpt()
|
||||
except Exception as e:
|
||||
_log(f" 回写缓存写入失败(不影响办理,仅崩溃后需人工补状态):{e}")
|
||||
|
||||
|
||||
def flush_writeback():
|
||||
"""把累积的回写内容统一写回源名单 Excel(openpyxl 直改原文件),
|
||||
保存成功(校验)后删除 JSON 缓存。保存失败则缓存保留,下次启动自动恢复。"""
|
||||
if not (_PENDING_STATUS or _PENDING_REMARK):
|
||||
return
|
||||
if not _SOURCE_FILE_USED:
|
||||
raise RuntimeError("无源名单文件记录,无法回写")
|
||||
from openpyxl import load_workbook
|
||||
wb = load_workbook(_SOURCE_FILE_USED)
|
||||
ws = wb[_SOURCE_SHEET_USED]
|
||||
# 表头第3行定位列号
|
||||
hdr = {}
|
||||
for c in ws[3]:
|
||||
if c.value is not None:
|
||||
hdr[str(c.value).strip()] = c.column
|
||||
col_id = hdr.get('身份证号码')
|
||||
col_status = hdr.get('办理状态')
|
||||
col_remark = hdr.get('备注')
|
||||
if not col_id or not col_status:
|
||||
raise RuntimeError("源名单缺少身份证号码/办理状态列,无法回写")
|
||||
changed = 0
|
||||
pending_ids = set(_PENDING_STATUS) | set(_PENDING_REMARK)
|
||||
ref = [config._norm_id(x) for x in pending_ids]
|
||||
for row in ws.iter_rows(min_row=4):
|
||||
cid = config._norm_id(row[col_id - 1].value)
|
||||
if cid and config._id_hit(cid, ref):
|
||||
r = row[0].row
|
||||
if cid in _PENDING_STATUS:
|
||||
ws.cell(row=r, column=col_status, value=_PENDING_STATUS[cid])
|
||||
if cid in _PENDING_REMARK and col_remark:
|
||||
# 备注追加不覆盖:新备注换行追加在后面(已存在则不重复追加)
|
||||
cell = ws.cell(row=r, column=col_remark)
|
||||
old = str(cell.value or '').strip()
|
||||
new = str(_PENDING_REMARK[cid]).strip()
|
||||
if new not in old: # 重查场景:备注已写过则跳过防重复
|
||||
cell.value = f"{old}\n{new}" if old else new
|
||||
changed += 1
|
||||
try:
|
||||
wb.save(_SOURCE_FILE_USED)
|
||||
except PermissionError:
|
||||
# 缓存保留,下次启动自动恢复回写
|
||||
raise RuntimeError("源名单文件被占用(请关闭 Excel 后重跑),回写未保存")
|
||||
_PENDING_STATUS.clear()
|
||||
_PENDING_REMARK.clear()
|
||||
if config.CKPT_FILE.exists():
|
||||
config.CKPT_FILE.unlink()
|
||||
_log(f" 源名单回写完成:更新 {changed} 行 → {os.path.basename(_SOURCE_FILE_USED)}(缓存已清除)")
|
||||
_log(" 注意:openpyxl 保存会清掉公式缓存(如「区域」列 XLOOKUP),"
|
||||
"下次运行前请先用 Excel 打开并保存一次该名单以重算公式")
|
||||
|
||||
|
||||
# ==================== 调试截图 ====================
|
||||
def shot(tab, name):
|
||||
"""调试截图:仅 DEBUG_MODE 开启时保存页面截图并记录当前 URL。"""
|
||||
if not config.DEBUG_MODE:
|
||||
return
|
||||
try:
|
||||
shot_dir = config.DEBUG_DIR / "shots"
|
||||
shot_dir.mkdir(parents=True, exist_ok=True)
|
||||
ts = datetime.now().strftime("%H%M%S")
|
||||
tab.get_screenshot(path=str(shot_dir), name=f"{ts}_{name}.png")
|
||||
_log(f" [截图] {ts}_{name}.png url={str(tab.url)[:90]}")
|
||||
except Exception as e:
|
||||
_log(f" [截图失败] {name}: {e}")
|
||||
@@ -1,513 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""重庆人社网上服务大厅(政务平台)法人登录模块(sb_person_change 插件)。
|
||||
|
||||
自 workflows/XQ0014 sb_login.py 迁移:
|
||||
- 每个参保单位一套账号(统一社会信用代码/用户名 + 密码),登录一次办一家的业务;
|
||||
- 不做 cookies 缓存(政务平台 cookies 极易失效),统一每次现场真登录;
|
||||
- SSO 完整流程 + ddddocr 识别图形验证码(验证码 5 次/轮 × 流程 3 轮)。
|
||||
|
||||
改造点:print → config.log;验证码调试落盘受 config.DEBUG_MODE 控制;
|
||||
去掉影刀 glv/main 入口。默认账号兜底读共享 .env(%LOCALAPPDATA%\37duAutomation\.env)。
|
||||
"""
|
||||
import base64
|
||||
import os
|
||||
import random
|
||||
import time
|
||||
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
from dotenv import load_dotenv
|
||||
|
||||
from . import config
|
||||
|
||||
# 默认账号只从共享 .env 读取,不内置明文;主流程按参保单位从台账取号传入,这里仅作兜底。
|
||||
if os.path.exists(os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation', '.env')):
|
||||
load_dotenv(os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation', '.env'))
|
||||
load_dotenv()
|
||||
|
||||
APPLY_URL = 'https://ggfw.rlsbj.cq.gov.cn/onlinehall/nethall/pc/cqzhrs/arrondi/ApplyOnline'
|
||||
SSO_KEYWORD = 'authcq.cqdcg.com:1443/sso/login'
|
||||
HOME_KEYWORD = 'ggfw.rlsbj.cq.gov.cn'
|
||||
WORK_KEYWORD = 'onlineoffice/index' # 登录成功后新开的工作台 tab
|
||||
|
||||
RETRY_MAX = 5 # 验证码最大重试次数(每轮)
|
||||
FLOW_RETRY = 3 # 整个登录流程最大轮数
|
||||
TIMEOUT = 10 # 元素等待超时(秒)
|
||||
HEADLESS = False
|
||||
HUMAN_DELAY = (0.4, 1.2) # 操作间随机延时区间(秒),模拟人工降低脚本特征
|
||||
|
||||
|
||||
def _recognize_captcha(img_bytes):
|
||||
"""ddddocr 识别图形验证码,返回文本。懒加载避免无关场景的导入开销。"""
|
||||
import ddddocr
|
||||
ocr = ddddocr.DdddOcr(show_ad=False)
|
||||
return ocr.classification(img_bytes).strip()
|
||||
|
||||
|
||||
def _dump_debug_captcha(img_bytes, text):
|
||||
"""可选:落盘验证码调试图片(仅 config.DEBUG_MODE 开启时),便于分析识别失败样本。"""
|
||||
if not config.DEBUG_MODE:
|
||||
return
|
||||
try:
|
||||
cfg_dir = config.DEBUG_DIR / "captcha"
|
||||
cfg_dir.mkdir(parents=True, exist_ok=True)
|
||||
path = cfg_dir / f"captcha_{int(time.time() * 1000)}_{text or 'unknown'}.png"
|
||||
with open(path, 'wb') as f:
|
||||
f.write(img_bytes)
|
||||
except Exception as e:
|
||||
config.log(f"保存调试图片失败:{e}")
|
||||
|
||||
|
||||
def _find_input(tab, selectors):
|
||||
"""按候选选择器顺序查找输入框。"""
|
||||
for sel in selectors:
|
||||
ele = tab.ele(sel, timeout=2)
|
||||
if ele:
|
||||
return ele
|
||||
return None
|
||||
|
||||
|
||||
def _find_captcha(tab):
|
||||
"""定位验证码图片 + 输入框。
|
||||
|
||||
从验证码输入框的容器往上找(DOM 结构:div.normalCode > span包input + img.code),
|
||||
避免命中页面其它 base64 图标(img[src^=data:image] 会抓到 icon)。
|
||||
"""
|
||||
code_input = tab.ele('css:input[placeholder*="图形验证码"]', timeout=TIMEOUT)
|
||||
img = None
|
||||
if code_input:
|
||||
holder = code_input.parent(2) # div.normalCode 容器
|
||||
if holder:
|
||||
img = holder.ele('tag:img', timeout=1)
|
||||
if img is None:
|
||||
# 兜底:激活面板内第一个 base64 图
|
||||
img = tab.ele('css:.ant-tabs-tabpane-active img[src^="data:image"]', timeout=2)
|
||||
return img, code_input
|
||||
|
||||
|
||||
def _read_img_bytes(img):
|
||||
"""验证码图转 bytes:优先直接解码 base64 src(像素无损、无 DPR 缩放),失败退回元素截图。"""
|
||||
try:
|
||||
src = img.attr('src') or ''
|
||||
if 'base64,' in src:
|
||||
return base64.b64decode(src.split('base64,', 1)[1])
|
||||
except Exception:
|
||||
pass
|
||||
return img.get_screenshot(as_bytes='png')
|
||||
|
||||
|
||||
# ================== 登录主流程 ==================
|
||||
def _human_pause(a=None, b=None):
|
||||
"""操作间随机延时,模拟人工节奏。"""
|
||||
lo, hi = HUMAN_DELAY if (a is None or b is None) else (a, b)
|
||||
time.sleep(random.uniform(lo, hi))
|
||||
|
||||
|
||||
def _dismiss_notice(page):
|
||||
"""关闭首页/工作台弹窗(「温馨提示」我知道了、授权提示同意等),避免遮挡操作。"""
|
||||
candidates = [
|
||||
'tag:button@@text()=我知道了',
|
||||
'tag:button@@text()=知道了',
|
||||
'tag:button@@text()=同意',
|
||||
'tag:button@@text()=确定',
|
||||
]
|
||||
for _ in range(3):
|
||||
btn = None
|
||||
for sel in candidates:
|
||||
try:
|
||||
btn = page.ele(sel, timeout=1)
|
||||
except Exception:
|
||||
btn = None
|
||||
if btn:
|
||||
break
|
||||
if not btn:
|
||||
return
|
||||
try:
|
||||
btn.click()
|
||||
config.log(f"已关闭弹窗(点击:{btn.text.strip()})")
|
||||
time.sleep(0.5)
|
||||
except Exception:
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def _sso_form_ready(t):
|
||||
"""判断某 tab 是否已是渲染完成的 SSO 登录页:URL 在 SSO 且「法人用户」tab 已出现。
|
||||
注意用 text()= 精确匹配——text(): 模糊匹配会命中包含该文字的外层容器 div(如 #user-sso-pc)。"""
|
||||
try:
|
||||
if SSO_KEYWORD not in t.url:
|
||||
return False
|
||||
return bool(t.ele('tag:div@@text()=法人用户', timeout=0.5))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _is_work_tab(t):
|
||||
"""是否登录完成的工作台页(onlineoffice/index)。
|
||||
必须 origin 前缀匹配 + 路径含 onlineoffice/index——跳转链中间页(zwykb 授权页、
|
||||
ggfw 回调页)的 redirectUrl 查询参数里也含 ggfw/onlinehall 字样,用包含匹配会误判。"""
|
||||
try:
|
||||
u = (t.url or '').strip()
|
||||
except Exception:
|
||||
return False
|
||||
return u.startswith('https://' + HOME_KEYWORD) and WORK_KEYWORD in u
|
||||
|
||||
|
||||
def _open_sso_tab(page):
|
||||
"""点击首页「登录」,等待新 tab 打开、跳转链结束且登录表单渲染完成后返回。
|
||||
返回 (tab, already_logged):
|
||||
already_logged=False → SSO 登录页(需填表)
|
||||
already_logged=True → SSO 会话有效直接跳回大厅(登录成功,无需填表)"""
|
||||
_dismiss_notice(page)
|
||||
# 登录入口:loginBox 内的第一个 <a>(「登录」,无 href)
|
||||
login_link = page.ele('css:[class*="loginBox"] a', timeout=TIMEOUT)
|
||||
if not login_link:
|
||||
login_link = page.ele('tag:a@@text():登录', timeout=TIMEOUT)
|
||||
if not login_link:
|
||||
# 可能残留上一账号登录态(首页已免登录):清除 cookies 后刷新重试一次
|
||||
config.log("未找到登录入口(可能残留上一账号登录态),清除 cookies 后重试")
|
||||
try:
|
||||
page.clear_cache(cookies=True)
|
||||
except Exception:
|
||||
try:
|
||||
page.run_js("document.cookie.split(';').forEach(c=>{"
|
||||
"document.cookie=c.trim().split('=')[0]+"
|
||||
"'=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/'});")
|
||||
except Exception:
|
||||
pass
|
||||
page.get(APPLY_URL)
|
||||
time.sleep(2)
|
||||
login_link = page.ele('css:[class*="loginBox"] a', timeout=TIMEOUT) \
|
||||
or page.ele('tag:a@@text():登录', timeout=TIMEOUT)
|
||||
if not login_link:
|
||||
# 首页已是登录态(无登录入口):提示需清登录态,由调用方处理
|
||||
config.log("找不到登录入口(首页可能已是登录态)")
|
||||
return None, False
|
||||
before_ids = set(page.tab_ids)
|
||||
login_link.click()
|
||||
# 点击「登录」后是中转跳转链:轮询所有新开 tab,直到某个 tab 的 URL 稳定停在
|
||||
# SSO 且「法人用户」登录表单真实渲染出来(避免拿到闪现中的中转页就操作);
|
||||
# 若 SSO 会话仍有效(同账号二次登录),新 tab 会直接跳回大厅页 → 视为已登录
|
||||
tab = None
|
||||
for _ in range(90): # 最多等 45 秒
|
||||
time.sleep(0.5)
|
||||
for tid in [i for i in page.tab_ids if i not in before_ids]:
|
||||
try:
|
||||
t = page.get_tab(tid)
|
||||
except Exception:
|
||||
continue
|
||||
if _is_work_tab(t):
|
||||
config.log(f"SSO 会话有效,已直接登录:{t.url}")
|
||||
_close_extra_tabs(page, before_ids, t)
|
||||
_dismiss_notice(t)
|
||||
return t, True
|
||||
if _sso_form_ready(t):
|
||||
tab = t
|
||||
break
|
||||
if tab:
|
||||
break
|
||||
if tab is None:
|
||||
# 部分场景可能不新开 tab 而是当前页跳转
|
||||
if _sso_form_ready(page):
|
||||
return page, False
|
||||
config.log("点击登录后未检测到就绪的 SSO 登录页")
|
||||
return None, False
|
||||
_close_extra_tabs(page, before_ids, tab)
|
||||
return tab, False
|
||||
|
||||
|
||||
def _close_extra_tabs(page, before_ids, keep_tab):
|
||||
"""关掉一次「点登录」产生的多余新开 tab(中转页等),保持会话干净。"""
|
||||
for tid in [i for i in page.tab_ids if i not in before_ids and i != keep_tab.tab_id]:
|
||||
try:
|
||||
page.get_tab(tid).close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _wait_sso_ready(tab):
|
||||
"""等 SSO 登录页彻底稳定(URL 不再跳变 + 表单已渲染),再开始操作,
|
||||
避免跳转/React 重渲染过程中拿到元素随即失效(元素对象已失效)。"""
|
||||
last_url = None
|
||||
for _ in range(60): # 最多等 30 秒
|
||||
try:
|
||||
url = tab.url
|
||||
except Exception:
|
||||
return False
|
||||
stable = (url == last_url)
|
||||
last_url = url
|
||||
if _sso_form_ready(tab) and stable:
|
||||
break
|
||||
time.sleep(0.5)
|
||||
time.sleep(1.5) # 再缓冲,确保 React 渲染完成
|
||||
return True
|
||||
|
||||
|
||||
def _try_login_once(tab, page, username, password, retry_index):
|
||||
"""在 SSO tab 内完成一次填表 + 验证码 + 提交。返回 True 表示登录成功。
|
||||
所有动作间加随机延时,模拟人工节奏,降低脚本特征。"""
|
||||
_wait_sso_ready(tab)
|
||||
# 法人用户 tab:精确文本匹配(text(): 模糊会命中包含文字的外层容器,如 #user-sso-pc)
|
||||
legal_tab = tab.ele('tag:div@@text()=法人用户', timeout=TIMEOUT)
|
||||
if legal_tab:
|
||||
legal_tab.click()
|
||||
_human_pause(0.3, 0.8)
|
||||
# 校验确实切到法人用户面板(没点上会把账号填进个人用户表单)
|
||||
for _ in range(3):
|
||||
active = tab.ele('css:.ant-tabs-tab-active .ant-tabs-tab-btn', timeout=2)
|
||||
if active and active.text.strip() == '法人用户':
|
||||
break
|
||||
if legal_tab:
|
||||
try:
|
||||
legal_tab.click()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
|
||||
# 账号(统一社会信用代码)+ 密码
|
||||
# SSO 法人用户表单真实结构(2026-09 探针实测):
|
||||
# 账号框 id=identifier placeholder「请输入统一社会信用代码」
|
||||
user_input = _find_input(tab, [
|
||||
'css:input[placeholder*="统一社会信用代码"]',
|
||||
'css:input[placeholder*="社会信用代码"]',
|
||||
'css:#identifier',
|
||||
])
|
||||
if not user_input:
|
||||
config.log("找不到账号输入框")
|
||||
return False
|
||||
user_input.clear()
|
||||
user_input.input(username)
|
||||
_human_pause()
|
||||
|
||||
pwd_input = _find_input(tab, ['css:#password', 'css:input[type="password"]'])
|
||||
if not pwd_input:
|
||||
config.log("找不到密码输入框")
|
||||
return False
|
||||
pwd_input.clear()
|
||||
pwd_input.input(password)
|
||||
_human_pause()
|
||||
|
||||
# 图形验证码:base64 内嵌图(从验证码输入框容器定位,避免抓到页面其它图标)
|
||||
for attempt in range(RETRY_MAX):
|
||||
config.log(f"--- 第 {retry_index}-{attempt + 1} 次验证码识别 ---")
|
||||
img, code_input = _find_captcha(tab)
|
||||
if not img or not code_input:
|
||||
config.log("找不到验证码图片或输入框")
|
||||
return False
|
||||
img_bytes = _read_img_bytes(img)
|
||||
if not img_bytes:
|
||||
config.log("验证码图数据为空")
|
||||
time.sleep(1)
|
||||
continue
|
||||
try:
|
||||
code = _recognize_captcha(img_bytes)
|
||||
except Exception as e:
|
||||
config.log(f"ddddocr 识别异常:{e}")
|
||||
return False
|
||||
config.log(f" 识别结果:{code!r}")
|
||||
if not code:
|
||||
_refresh_captcha(tab, img)
|
||||
continue
|
||||
code = code.upper() # 页面显示为大写,按大写提交
|
||||
_dump_debug_captcha(img_bytes, code)
|
||||
code_input.clear()
|
||||
code_input.input(code)
|
||||
_human_pause(0.3, 0.9)
|
||||
|
||||
# 提交:登录按钮(button[type=submit],文案「登 录」)
|
||||
btn = tab.ele('css:button[type="submit"]', timeout=TIMEOUT) \
|
||||
or tab.ele('tag:button@@text():登录', timeout=TIMEOUT)
|
||||
if not btn:
|
||||
config.log("找不到登录提交按钮")
|
||||
return False
|
||||
_human_pause(0.2, 0.6) # 点提交前再停顿一下
|
||||
btn.click()
|
||||
|
||||
# 等待结果:SSO tab 跳回大厅 / 新开 onlineoffice 工作台 tab = 成功;错误提示 = 刷新重试
|
||||
ok, work_tab = _wait_login_result(tab, page)
|
||||
if ok:
|
||||
_try_login_once.work_tab = work_tab # 供 _do_login 保存会话
|
||||
return True
|
||||
_refresh_captcha(tab, img)
|
||||
return False
|
||||
|
||||
|
||||
def _wait_login_result(tab, page):
|
||||
"""提交后轮询判定登录结果。返回 (ok, work_tab)。"""
|
||||
before_ids = set(page.tab_ids)
|
||||
for _ in range(30): # 最多等 15 秒
|
||||
time.sleep(0.5)
|
||||
# 成功标志 1:登录后新开的 onlineoffice 工作台 tab
|
||||
for tid in [i for i in page.tab_ids if i not in before_ids]:
|
||||
try:
|
||||
t = page.get_tab(tid)
|
||||
except Exception:
|
||||
continue
|
||||
if _is_work_tab(t):
|
||||
config.log(f"登录成功(新开工作台 tab):{t.url}")
|
||||
_close_extra_tabs(page, before_ids, t)
|
||||
_dismiss_notice(t) # 工作台可能闪现授权/提示弹窗
|
||||
return True, t
|
||||
# 成功标志 2:SSO tab 自身跳到工作台页(origin 前缀匹配,防 redirectUrl 参数误判)
|
||||
try:
|
||||
url = (tab.url or '').strip()
|
||||
except Exception:
|
||||
url = ''
|
||||
if url.startswith('https://' + HOME_KEYWORD) and SSO_KEYWORD not in url and WORK_KEYWORD in url:
|
||||
config.log(f"登录成功,已跳转:{url}")
|
||||
_dismiss_notice(tab)
|
||||
return True, tab
|
||||
# ant-message 错误提示(验证码错误/账号密码错误等)
|
||||
try:
|
||||
err = tab.ele('css:.ant-message-error', timeout=0.5)
|
||||
if err:
|
||||
config.log(f"登录失败提示:{err.text}")
|
||||
return False, None
|
||||
except Exception:
|
||||
pass
|
||||
config.log("等待登录结果超时")
|
||||
return False, None
|
||||
|
||||
|
||||
def _refresh_captcha(tab, img):
|
||||
"""点击验证码图片刷新,校验 base64 src 是否真的变化(连续点 2 次)。"""
|
||||
try:
|
||||
old = img.attr('src') or ''
|
||||
except Exception:
|
||||
old = ''
|
||||
for _ in range(2):
|
||||
try:
|
||||
img.click()
|
||||
except Exception:
|
||||
try:
|
||||
img.click(by_js=True)
|
||||
except Exception:
|
||||
pass
|
||||
# 刷新是异步的:轮询 src 变化(最多 3 秒)
|
||||
for _p in range(10):
|
||||
time.sleep(0.3)
|
||||
try:
|
||||
new = img.attr('src') or ''
|
||||
except Exception:
|
||||
new = old
|
||||
if new and new != old:
|
||||
return True
|
||||
# src 还没变,再点一次
|
||||
config.log("警告:验证码图片刷新后未变化")
|
||||
return False
|
||||
|
||||
|
||||
LAST_SESSION = {'page': None, 'tab': None} # 登录成功后保留的浏览器会话(供后续网页操作使用)
|
||||
|
||||
|
||||
def _teardown(page):
|
||||
"""清 cookies/本地存储后关浏览器(账号切换彻底隔离,避免残留登录态)。"""
|
||||
if page is None:
|
||||
return
|
||||
try:
|
||||
page.clear_cache(cookies=True, local_storage=True, session_storage=True)
|
||||
except Exception:
|
||||
try:
|
||||
page.clear_cache()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def close_session():
|
||||
"""清 cookies 并关闭当前保留的登录会话(每个账号业务办完后必须调用)。"""
|
||||
_teardown(LAST_SESSION['page'])
|
||||
LAST_SESSION['page'] = None
|
||||
LAST_SESSION['tab'] = None
|
||||
|
||||
|
||||
def _do_login(username, password):
|
||||
"""打开浏览器现场完成登录(含图形验证码)。不做任何 cookies 缓存。
|
||||
成功保留浏览器会话(工作台 tab 供后续导入操作),失败关闭浏览器。
|
||||
返回 (ok, work_tab)。"""
|
||||
# 账号切换隔离:先关掉上一账号的浏览器会话(auto_port 临时目录本就不互通,双保险)
|
||||
close_session()
|
||||
co = ChromiumOptions()
|
||||
if HEADLESS:
|
||||
co.headless()
|
||||
# auto_port:每次启动独立端口+独立临时用户目录,账号间 cookies 天然隔离
|
||||
co.auto_port(True)
|
||||
co.set_argument('--start-maximized') # 浏览器启动即全屏(最大化),避免小窗口下元素被折叠/遮挡
|
||||
page = ChromiumPage(co)
|
||||
work_tab_holder = {'tab': None}
|
||||
|
||||
def _finish(ok):
|
||||
if ok:
|
||||
LAST_SESSION['page'] = page
|
||||
LAST_SESSION['tab'] = work_tab_holder['tab']
|
||||
return True, work_tab_holder['tab']
|
||||
_teardown(page)
|
||||
return False, None
|
||||
|
||||
try:
|
||||
page.get(APPLY_URL)
|
||||
_human_pause(1.0, 2.5)
|
||||
|
||||
tab = None
|
||||
for retry in range(FLOW_RETRY):
|
||||
try:
|
||||
_dismiss_notice(page)
|
||||
# 登录 tab 跨轮次复用:只在丢失/失效时才重新点「登录」,
|
||||
# 避免每轮重开浏览器 tab 越积越多(手动只点一次,代码不能反复点)
|
||||
if tab is not None:
|
||||
try:
|
||||
if SSO_KEYWORD not in tab.url:
|
||||
tab = None # 已跳走(登录成功或会话变化),需重新进入
|
||||
except Exception:
|
||||
tab = None # tab 已关闭/失效
|
||||
if tab is None:
|
||||
tab, already = _open_sso_tab(page)
|
||||
if tab is None:
|
||||
config.log(f"进入 SSO 登录页失败(第 {retry + 1}/{FLOW_RETRY} 轮)")
|
||||
time.sleep(2)
|
||||
continue
|
||||
if already:
|
||||
# 同账号 SSO 会话仍有效:免验证码直接登录成功
|
||||
work_tab_holder['tab'] = tab
|
||||
return _finish(True)
|
||||
if _try_login_once(tab, page, username, password, retry + 1):
|
||||
work_tab_holder['tab'] = getattr(_try_login_once, 'work_tab', None) or tab
|
||||
return _finish(True)
|
||||
# 登录失败:复用同一 tab 刷新重来,不再重复点「登录」
|
||||
try:
|
||||
tab.refresh()
|
||||
time.sleep(2)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
# 元素失效/页面刷新等异常:不中断整体流程,进入下一轮
|
||||
config.log(f"第 {retry + 1}/{FLOW_RETRY} 轮流程异常(将重试):{e}")
|
||||
time.sleep(1)
|
||||
config.log("登录失败(验证码识别未通过或流程异常)")
|
||||
return _finish(False)
|
||||
except Exception:
|
||||
# 整体异常也要保证清理(失败场景不留会话)
|
||||
_teardown(page)
|
||||
raise
|
||||
|
||||
|
||||
def ensure_login(username=None, password=None):
|
||||
"""以指定账号现场登录政务平台(无缓存,每次真登录)。
|
||||
返回 dict:{success, username, message}"""
|
||||
# 未传账号时回落到 .env 默认账号(兜底场景)
|
||||
username = (username or os.getenv('sb_login_username', '') or '').strip()
|
||||
password = (password or os.getenv('sb_login_password', '') or '').strip()
|
||||
if not (username and password):
|
||||
return {"success": False, "username": username,
|
||||
"message": "登录账号/密码缺失(台账未取到且 .env 未配置 sb_login_username / sb_login_password)"}
|
||||
|
||||
ok, _work_tab = _do_login(username, password)
|
||||
if ok:
|
||||
return {"success": True, "username": username, "message": "登录成功"}
|
||||
return {"success": False, "username": username,
|
||||
"message": "登录失败(验证码识别未通过或流程异常)"}
|
||||
@@ -1,7 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""中心机插件包入口 shim(zip 包根必含 main.py)。
|
||||
|
||||
包以目录形式安装到 plugins/<id>/(webhost 宿主按账号权限自下载解压处)时由包扫描加载 __init__.py;
|
||||
以 zip 分发/存储时中心机校验要求包根含 main.py。导入本模块即触发插件注册。
|
||||
"""
|
||||
from . import SbPersonChangePlugin, PLUGINS # noqa: F401
|
||||
@@ -1,218 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""核查回盘模式(sb_person_change 插件)。
|
||||
|
||||
自 workflows/XQ0014 check_review.py 主流程迁移:恢复缓存 → 读待审核名单 → 取号 →
|
||||
预检 → 逐单位登录核查审核结论 + 回盘打印下载核对 → 400系统错误统一清状态 → 统一回写。
|
||||
print → config.log。
|
||||
"""
|
||||
from . import config
|
||||
from . import excelio
|
||||
from . import login
|
||||
from . import source
|
||||
from . import webops
|
||||
|
||||
|
||||
def _log(msg):
|
||||
config.log(msg)
|
||||
|
||||
|
||||
def build_writeback(results, task_cids, unit_name):
|
||||
"""按回写规则处理明细,返回 (status_map, remark_map, redo400_list, log_lines)。
|
||||
只处理本单位「待审核」人员(证件号码精确匹配),其余仅记录日志。
|
||||
400系统错误不立即清状态:先记录,运行结束后统一清空办理状态回待办再新增。"""
|
||||
status_map, remark_map, redo400, logs = {}, {}, [], []
|
||||
for r in results:
|
||||
if not r['cid'] or r['cid'] not in task_cids:
|
||||
continue
|
||||
concl, opinion = r['conclusion'], r['opinion']
|
||||
line = f" {r['name']}({r['cid']}):{concl}"
|
||||
if concl == '审核通过':
|
||||
status_map[r['cid']] = config.PASS_STATUS
|
||||
line += f" → 办理状态={config.PASS_STATUS}"
|
||||
elif concl == '不通过':
|
||||
if config.ERR_400_KEYWORD in opinion:
|
||||
# 系统错误:仅记录,运行结束后统一清空办理状态回待办重新增员
|
||||
if config.RUN_400_CLEAR:
|
||||
redo400.append({"cid": r['cid'], "name": r['name'], "unit": unit_name})
|
||||
line += " → 400系统错误,已记录(结束后统一清状态回待办重新增员)"
|
||||
else:
|
||||
status_map[r['cid']] = config.FAIL_STATUS
|
||||
remark_map[r['cid']] = opinion or '审核不通过'
|
||||
line += f" → 办理状态={config.FAIL_STATUS},备注追加:{opinion[:60]}"
|
||||
else:
|
||||
line += " → 非终态结论,跳过"
|
||||
logs.append(line)
|
||||
return status_map, remark_map, redo400, logs
|
||||
|
||||
|
||||
def do_unit_check(task):
|
||||
"""登录后的完整核查流程。返回结果 dict(JSON 安全)。"""
|
||||
page = login.LAST_SESSION.get('page')
|
||||
work_tab = login.LAST_SESSION.get('tab')
|
||||
if page is None or work_tab is None:
|
||||
return {"success": False, "message": "无有效登录会话"}
|
||||
|
||||
res = {"success": False, "checked": 0, "passed": 0, "failed": 0,
|
||||
"redo400": [], "skipped": False}
|
||||
try:
|
||||
excelfio.shot(work_tab, "c1_workbench")
|
||||
biz_tab = webops.open_business_page(page, work_tab)
|
||||
webops._dismiss_popups(biz_tab)
|
||||
# 关键:必须等单位信息接口(getAab001)返回本单位,否则后续查询全部拿不到数据
|
||||
unit_info = webops.wait_unit_loaded(biz_tab, task['unit'])
|
||||
if unit_info is None:
|
||||
# 页面没加载出单位:重开一次业务页再等
|
||||
_log(" 单位信息未加载,重开业务页重试...")
|
||||
biz_tab = webops.open_business_page(page, work_tab)
|
||||
webops._dismiss_popups(biz_tab)
|
||||
unit_info = webops.wait_unit_loaded(biz_tab, task['unit'])
|
||||
if unit_info is None:
|
||||
res.update(success=True, skipped=True,
|
||||
message="单位信息未加载(getAab001无数据),跳过")
|
||||
return res
|
||||
unit_full = str(unit_info.get('aab004') or '').strip() # 平台单位全称,用于回盘命名
|
||||
fail_cids = set() # 审核不通过(参保失败)人员:平台无回盘记录,回盘阶段跳过其未查询备注
|
||||
excelfio.shot(biz_tab, "c2_biz_page")
|
||||
|
||||
table = webops.open_query_menu(biz_tab)
|
||||
excelfio.shot(biz_tab, "c3_query_list")
|
||||
status, view = webops.read_first_row(table)
|
||||
if not status:
|
||||
res.update(success=True, skipped=True, message="已申报查询无记录,跳过")
|
||||
elif status != config.DONE_STATUS:
|
||||
res.update(success=True, skipped=True,
|
||||
message=f"第一条状态「{status}」非{config.DONE_STATUS},跳过")
|
||||
else:
|
||||
_log(f" 第一条状态:{status},点击查看读取审核结论")
|
||||
url = webops._capture_query_url(page, biz_tab, view)
|
||||
results, detail_full = webops.replay_query_all(biz_tab, url)
|
||||
unit_full = unit_full or detail_full
|
||||
excelfio.shot(biz_tab, "c4_detail_fetched")
|
||||
if not results:
|
||||
res.update(success=True, message="明细接口返回 0 条,跳过")
|
||||
else:
|
||||
status_map, remark_map, redo400, logs = build_writeback(
|
||||
results, task['cids'], task['unit'])
|
||||
fail_cids = {cid for cid, st in status_map.items() if st == config.FAIL_STATUS}
|
||||
for line in logs:
|
||||
_log(line)
|
||||
if status_map or remark_map:
|
||||
excelfio.writeback_source(status_map, remark_map)
|
||||
n_match = len([r for r in results if r['cid'] in task['cids']])
|
||||
n_pass = len([v for v in status_map.values() if v == config.PASS_STATUS])
|
||||
n_fail = len([v for v in status_map.values() if v == config.FAIL_STATUS])
|
||||
res.update(
|
||||
success=True,
|
||||
checked=n_match,
|
||||
passed=n_pass,
|
||||
failed=n_fail,
|
||||
redo400=redo400,
|
||||
message=(f"核查{n_match}条,通过{n_pass} 失败{n_fail} "
|
||||
f"400系统错误{len(redo400)}(结束后统一清状态)"))
|
||||
|
||||
# 回盘打印:每个账号核查完都要下载回盘记录并核对参保状态(无论是否已办结)
|
||||
try:
|
||||
webops.do_huipan(page, biz_tab, task, res, unit_full, fail_cids)
|
||||
except Exception as e:
|
||||
res["huipan"] = f"回盘打印失败:{e}"
|
||||
_log(f" 回盘打印失败:{e}")
|
||||
return res
|
||||
except Exception as e:
|
||||
res["message"] = f"核查异常:{e}"
|
||||
return res
|
||||
|
||||
|
||||
def process_units(tasks, accounts, ctx):
|
||||
"""逐参保单位:登录 → 已申报查询核查 → 回写。每账号办完清 cookies 关浏览器。"""
|
||||
results = []
|
||||
n = len(tasks)
|
||||
for i, task in enumerate(tasks, 1):
|
||||
_log(f"\n========== [{i}/{n}] {task['unit']}({task['count']}人待审核)==========")
|
||||
ctx.progress(20 + int(70 * (i - 1) / max(n, 1)))
|
||||
acc = accounts.get(task['unit'])
|
||||
try:
|
||||
login_res = login.ensure_login(acc["username"], acc["password"])
|
||||
except Exception as e:
|
||||
login_res = {"success": False, "message": f"登录调用异常:{e}"}
|
||||
_log(f"登录结果:{login_res.get('message')}")
|
||||
try:
|
||||
if login_res.get("success"):
|
||||
web_res = do_unit_check(task)
|
||||
_log(f"核查结果:{web_res.get('message')}")
|
||||
results.append({**task, **web_res})
|
||||
else:
|
||||
results.append({**task, "success": False, "message": login_res.get("message", "")})
|
||||
finally:
|
||||
login.close_session()
|
||||
return results
|
||||
|
||||
|
||||
def run(ctx, limit=0):
|
||||
"""主流程:恢复缓存 → 读待审核名单 → 取号 → 预检 → 逐单位登录核查 → 统一回写。"""
|
||||
ctx.progress(5)
|
||||
recovered_ids = excelfio.load_ckpt()
|
||||
tasks = source.load_check_tasks(exclude_ids=recovered_ids)
|
||||
if recovered_ids:
|
||||
_log("\n检测到上次未回写的内容,先统一回写:")
|
||||
try:
|
||||
excelfio.flush_writeback()
|
||||
except Exception as e:
|
||||
_log(f"恢复回写失败(缓存保留,下次启动重试):{e}")
|
||||
if not tasks:
|
||||
ctx.progress(100)
|
||||
return {"summary": "无待核查数据", "rows": [], "notes": []}
|
||||
|
||||
ctx.progress(15)
|
||||
# 文件占用预检:源名单被 Excel 打开会卡回写,提前报错
|
||||
source_file, _ = excelfio.get_writeback_target()
|
||||
config.check_not_locked(source_file)
|
||||
|
||||
accounts = source.load_accounts([t['unit'] for t in tasks])
|
||||
# 预检:账号齐备才继续(与增员一致的严格预检)
|
||||
errors = []
|
||||
for t in tasks:
|
||||
acc = accounts.get(t['unit'])
|
||||
if acc is None:
|
||||
errors.append(f"[{t['unit']}] 台账未匹配")
|
||||
elif not acc['username'] or not acc['password']:
|
||||
errors.append(f"[{t['unit']}] 账号或密码缺失")
|
||||
if errors:
|
||||
_log("\n预检未通过:")
|
||||
for e in errors:
|
||||
_log(f" - {e}")
|
||||
raise RuntimeError("预检未通过,详见日志(台账未匹配/账号密码缺失),修正后重跑")
|
||||
|
||||
todo = tasks[:limit] if limit > 0 else tasks
|
||||
if limit > 0:
|
||||
_log(f"分批运行:本次仅核查前 {limit} 个单位")
|
||||
ctx.progress(20)
|
||||
results = process_units(todo, accounts, ctx)
|
||||
ctx.progress(92)
|
||||
# 400系统错误:核查时只记录,全部单位核查完后统一清空办理状态回待办(重新走名单制作+增员)
|
||||
redo_all = [p for r in results for p in (r.get("redo400") or [])]
|
||||
notes = []
|
||||
if redo_all:
|
||||
excelfio.writeback_source({p['cid']: "" for p in redo_all}, {})
|
||||
_log(f"\n400系统错误共 {len(redo_all)} 人,已统一清空办理状态回待办,"
|
||||
f"请重新执行名单制作后增员:")
|
||||
for p in redo_all:
|
||||
_log(f" - {p['name']}({p['cid']}){p['unit']}")
|
||||
notes.append(f"400系统错误:{p['name']}({p['cid']}){p['unit']} 已清状态回待办")
|
||||
try:
|
||||
excelfio.flush_writeback()
|
||||
except Exception as e:
|
||||
_log(f"回写失败:{e}")
|
||||
ok = [r for r in results if r["success"]]
|
||||
fail = [r for r in results if not r["success"]]
|
||||
skip = [r for r in ok if r.get("skipped")]
|
||||
_log(f"\n========== 汇总 ==========")
|
||||
_log(f"核查完成 {len(ok) - len(skip)} 家,跳过(未办结/无记录){len(skip)} 家,失败 {len(fail)} 家")
|
||||
for r in fail:
|
||||
_log(f" ✗ {r['unit']}:{r.get('message', '')}")
|
||||
notes.append(f"{r['unit']}:{r.get('message', '')}")
|
||||
ctx.progress(100)
|
||||
return {"summary": f"核查回盘 完成{len(ok) - len(skip)}/跳过{len(skip)}/失败{len(fail)}",
|
||||
"rows": [{k: r.get(k) for k in ('unit', 'count', 'checked', 'passed', 'failed',
|
||||
'huipan', 'message')}
|
||||
for r in results],
|
||||
"notes": notes}
|
||||
@@ -1,187 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""增员办理模式(sb_person_change 插件)。
|
||||
|
||||
自 workflows/XQ0014 import_add.py 主流程迁移:恢复缓存 → 读名单(排除已回写人员)
|
||||
→ 取号 → 预检 → 逐单位登录政务平台导入申报 → 统一回写。print → config.log。
|
||||
"""
|
||||
from . import config
|
||||
from . import excelio
|
||||
from . import login
|
||||
from . import source
|
||||
from . import webops
|
||||
|
||||
|
||||
def _log(msg):
|
||||
config.log(msg)
|
||||
|
||||
|
||||
def precheck(units, accounts):
|
||||
"""预检:核对每个单位的导入文件与账号。返回待办列表 [{unit, count, file, username, password}]。"""
|
||||
import os
|
||||
import_dir = os.path.join(config.SOURCE_DIR, config.IMPORT_DIR_NAME)
|
||||
tasks, errors = [], []
|
||||
_log("\n========== 预检 ==========")
|
||||
for unit, count in units:
|
||||
file_path = os.path.join(import_dir, f"{config._safe_name(unit)}增员导入名单.xls")
|
||||
acc = accounts.get(unit)
|
||||
problems = []
|
||||
if not os.path.isfile(file_path):
|
||||
problems.append(f"缺导入文件({config.IMPORT_DIR_NAME}\\{os.path.basename(file_path)})")
|
||||
if acc is None:
|
||||
problems.append("台账未匹配(检查户头名/城市=重庆/是否在用=是)")
|
||||
else:
|
||||
if not acc["username"]:
|
||||
problems.append("账号缺失(信用代码与平台用户名均为空)")
|
||||
if not acc["password"]:
|
||||
problems.append("密码缺失(平台密码为空)")
|
||||
if problems:
|
||||
errors.append(f"[{unit}] " + ";".join(problems))
|
||||
_log(f" ✗ {unit}({count}人):{';'.join(problems)}")
|
||||
else:
|
||||
tasks.append({"unit": unit, "count": count, "file": file_path,
|
||||
"username": acc["username"], "password": acc["password"]})
|
||||
_log(f" ✓ {unit}({count}人)账号={acc['username']}"
|
||||
f"({acc['username_src']})文件={os.path.basename(file_path)}")
|
||||
if errors:
|
||||
_log(f"\n预检未通过,共 {len(errors)} 个问题,请先修正后重跑:")
|
||||
for e in errors:
|
||||
_log(f" - {e}")
|
||||
return None
|
||||
_log(f"预检通过:{len(tasks)} 个单位待办理\n")
|
||||
return tasks
|
||||
|
||||
|
||||
def do_web_import(task):
|
||||
"""登录后的完整业务流程:进业务页 → 上传导入 → 校验回写 → 预申报提交 → 查询回写。
|
||||
返回结果 dict(JSON 安全)。"""
|
||||
page = login.LAST_SESSION.get('page')
|
||||
work_tab = login.LAST_SESSION.get('tab')
|
||||
if page is None or work_tab is None:
|
||||
return {"success": False, "message": "无有效登录会话"}
|
||||
|
||||
res = {"success": False, "imported": 0, "failed": [], "review": {}}
|
||||
try:
|
||||
excelfio.shot(work_tab, "01_workbench")
|
||||
biz_tab = webops.open_business_page(page, work_tab)
|
||||
excelfio.shot(biz_tab, "02_biz_upload_page")
|
||||
|
||||
# 1) 上传导入
|
||||
total, _failed_cnt = webops.upload_import(biz_tab, task['file'])
|
||||
res['imported'] = total
|
||||
|
||||
# 2) 校验未通过:回写 参保失败 + 备注(详细信息)
|
||||
# 平账规则:弹窗「成功N人」+「校验未通过人员」= 名单人数,不平账中止防止漏人导致下次重复申报
|
||||
fail_rows = webops.read_failed_rows(biz_tab)
|
||||
res['failed'] = [{"id": cid, "detail": d} for cid, d in fail_rows]
|
||||
expected = task.get('count', 0)
|
||||
if expected and total + len(fail_rows) != expected:
|
||||
raise RuntimeError(
|
||||
f"人数不平账:导入成功{total} + 校验未通过{len(fail_rows)} ≠ 名单{expected}人,"
|
||||
f"中止该单位(防漏人/重复申报),请人工核对")
|
||||
if fail_rows:
|
||||
excelfio.writeback_source({cid: "参保失败" for cid, _ in fail_rows},
|
||||
{cid: d for cid, d in fail_rows})
|
||||
passed = total
|
||||
|
||||
# 3) 全员未通过 → 跳过申报
|
||||
if passed <= 0:
|
||||
_log(" 校验通过人数为 0,跳过申报")
|
||||
res.update(success=True, message=f"导入{total}人,全部校验未通过,已回写未申报")
|
||||
return res
|
||||
|
||||
# 4) 预申报 → 正式提交 → 查询审核结论回写
|
||||
webops.predeclare_and_submit(page, biz_tab)
|
||||
review = webops.query_review_results(page, biz_tab)
|
||||
res['review'] = [{"id": cid, "conclusion": c, "sn": sn}
|
||||
for cid, (c, sn) in review.items()]
|
||||
if review:
|
||||
excelfio.writeback_source({cid: concl for cid, (concl, _) in review.items()}, {})
|
||||
res.update(success=True,
|
||||
message=f"导入{total}人,未通过{len(fail_rows)}人,提交{passed}人")
|
||||
return res
|
||||
except Exception as e:
|
||||
res["message"] = f"网页操作异常:{e}"
|
||||
return res
|
||||
|
||||
|
||||
def process_units(tasks, ctx):
|
||||
"""逐参保单位:登录政务平台 → 完整网页导入申报 → 回写。
|
||||
每个账号办完(无论成败)都清 cookies 关浏览器,下个账号全新开始。
|
||||
回写策略:单位内累积到内存并写 JSON 缓存(防崩溃),运行结束统一回写 Excel 一次。"""
|
||||
results = []
|
||||
n = len(tasks)
|
||||
for i, task in enumerate(tasks, 1):
|
||||
_log(f"\n========== [{i}/{n}] {task['unit']}({task['count']}人)==========")
|
||||
_log(f"导入文件:{task['file']}")
|
||||
ctx.progress(20 + int(70 * (i - 1) / max(n, 1)))
|
||||
try:
|
||||
login_res = login.ensure_login(task["username"], task["password"])
|
||||
except Exception as e:
|
||||
login_res = {"success": False, "message": f"登录调用异常:{e}"}
|
||||
_log(f"登录结果:{login_res.get('message')}")
|
||||
try:
|
||||
if login_res.get("success"):
|
||||
web_res = do_web_import(task)
|
||||
_log(f"办理结果:{web_res.get('message')}")
|
||||
results.append({**task, **web_res})
|
||||
else:
|
||||
results.append({**task, "success": False,
|
||||
"message": login_res.get("message", "")})
|
||||
finally:
|
||||
# 账号隔离:清 cookies + 关浏览器,再进入下一单位
|
||||
login.close_session()
|
||||
return results
|
||||
|
||||
|
||||
def run(ctx, limit=0):
|
||||
"""主流程:恢复缓存 → 读名单(排除已回写人员)→ 取号 → 预检 → 逐单位登录导入 → 统一回写。
|
||||
返回 JSON 安全 dict。"""
|
||||
ctx.progress(5)
|
||||
recovered_ids = excelfio.load_ckpt()
|
||||
units = source.load_add_units(exclude_ids=recovered_ids)
|
||||
# 崩溃恢复:上次运行残留的回写缓存统一落盘(排除逻辑已在 load_add_units 中生效,
|
||||
# 即使下面回写失败,这些人也不会被当成待办重复申报)
|
||||
if recovered_ids:
|
||||
_log("\n检测到上次未回写的内容,先统一回写:")
|
||||
try:
|
||||
excelfio.flush_writeback()
|
||||
except Exception as e:
|
||||
_log(f"恢复回写失败(缓存保留,下次启动重试):{e}")
|
||||
if not units:
|
||||
return {"summary": "无待办数据", "rows": [], "notes": []}
|
||||
|
||||
ctx.progress(15)
|
||||
# 文件占用预检:源名单被 Excel 打开会卡回写,提前报错
|
||||
source_file, _ = excelfio.get_writeback_target()
|
||||
config.check_not_locked(source_file)
|
||||
|
||||
accounts = source.load_accounts([u for u, _ in units])
|
||||
tasks = precheck(units, accounts)
|
||||
if tasks is None:
|
||||
raise RuntimeError("预检未通过,详见日志(缺导入文件/台账账号),修正后重跑")
|
||||
|
||||
if limit > 0:
|
||||
tasks = tasks[:limit]
|
||||
_log(f"分批运行:本次仅办理前 {limit} 个单位")
|
||||
|
||||
ctx.progress(20)
|
||||
results = process_units(tasks, ctx)
|
||||
ctx.progress(92)
|
||||
# 运行结束:本次累积的回写内容统一写 Excel 一次(失败则 JSON 缓存保留,下次启动恢复)
|
||||
try:
|
||||
excelfio.flush_writeback()
|
||||
except Exception as e:
|
||||
_log(f"回写失败:{e}")
|
||||
ok = [r for r in results if r["success"]]
|
||||
fail = [r for r in results if not r["success"]]
|
||||
_log(f"\n========== 汇总 ==========")
|
||||
_log(f"成功 {len(ok)} 家,失败 {len(fail)} 家")
|
||||
notes = []
|
||||
for r in fail:
|
||||
_log(f" ✗ {r['unit']}:{r.get('message', '')}")
|
||||
notes.append(f"{r['unit']}:{r.get('message', '')}")
|
||||
ctx.progress(100)
|
||||
return {"summary": f"增员办理 成功{len(ok)}/失败{len(fail)}",
|
||||
"rows": [{k: r.get(k) for k in ('unit', 'count', 'imported', 'message')}
|
||||
for r in results],
|
||||
"notes": notes}
|
||||
@@ -1,108 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""增员名单制作模式(sb_person_change 插件)。
|
||||
|
||||
自 workflows/XQ0008 generate_add.py 迁移:读取【参保名单】sheet,筛选 区域=重庆 ∩
|
||||
参保类型=指定类型 ∩ 办理状态为空,按参保单位分组复制《增员模版.xls》(保留下拉字典),
|
||||
逐店生成《XX增员导入名单.xls》。日期规则与影刀版一致:先「转移参保」后「新参保」,
|
||||
工伤参保时间=当日,其余参保时间=本月1日。
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
from . import config
|
||||
from . import excelio
|
||||
from . import source
|
||||
|
||||
|
||||
def _log(msg):
|
||||
config.log(msg)
|
||||
|
||||
|
||||
def _translate_education(val):
|
||||
if val is None or config._to_text(val) == '':
|
||||
return '90.其他'
|
||||
return config.EDU_MAP.get(str(val).strip(), '90.其他')
|
||||
|
||||
|
||||
def _translate_nation(val):
|
||||
if val is None or config._to_text(val) == '':
|
||||
return '99.其他'
|
||||
return config.NATION_MAP.get(str(val).strip(), '99.其他')
|
||||
|
||||
|
||||
def _translate_residence(val):
|
||||
if val is None or config._to_text(val) == '':
|
||||
return ''
|
||||
return config.RESIDENCE_MAP.get(str(val).strip(), '')
|
||||
|
||||
|
||||
def _process_add_members(operation_type):
|
||||
"""生成指定参保类型的增员导入名单。"""
|
||||
cm = config.COLUMN_MAP_ADD
|
||||
source_file, df_filtered = source.load_add_rows(operation_type)
|
||||
if df_filtered.empty:
|
||||
return []
|
||||
config.check_not_locked(source_file)
|
||||
|
||||
today = datetime.now()
|
||||
first_day = today.replace(day=1)
|
||||
_log(f"今日日期:{today.strftime('%Y-%m-%d')}")
|
||||
_log(f"本月1日:{first_day.strftime('%Y-%m-%d')}(首次参加/养老/失业/医疗/生育参保时间)")
|
||||
_log(f"工伤参保时间:{today.strftime('%Y-%m-%d')}(当日)")
|
||||
|
||||
template_file = excelio.find_template_file(config.ADD_TEMPLATE_FILE)
|
||||
output_dir = excelio.get_output_dir_add(operation_type)
|
||||
_log(f"输出目录:{output_dir}")
|
||||
produced = []
|
||||
for store_name, group in df_filtered.groupby(cm['单位名称']):
|
||||
_log(f" 正在处理:{store_name},共 {len(group)} 人")
|
||||
first_row = group.iloc[0]
|
||||
unit_no = first_row[cm['社保号']]
|
||||
unit_full_name = first_row[cm['参保单位全称']]
|
||||
|
||||
# 逐行生成数据(键 = 模板列名)
|
||||
records = []
|
||||
for _, row in group.iterrows():
|
||||
records.append({
|
||||
'证件号码': config._to_text(row[cm['证件号码']]),
|
||||
'姓名': row[cm['姓名']],
|
||||
'民族': _translate_nation(row[cm['民族']]),
|
||||
'首次参加工作日期': first_day,
|
||||
'月基本工资额': config._clean_value(row[cm['月基本工资额']]),
|
||||
'工种': config.DEFAULT_VALUES_ADD['工种'],
|
||||
'个人身份': config.DEFAULT_VALUES_ADD['个人身份'],
|
||||
'户口性质': _translate_residence(row[cm['户口性质']]),
|
||||
'联系电话': config._to_text(row[cm['联系电话']]),
|
||||
'文化程度': _translate_education(row[cm['文化程度']]),
|
||||
'养老保险参保时间': first_day,
|
||||
'失业保险参保时间': first_day,
|
||||
'医疗保险参保时间': first_day,
|
||||
'工伤保险参保时间': today,
|
||||
'生育保险参保时间': first_day,
|
||||
'证件类型': config.DEFAULT_VALUES_ADD['证件类型'],
|
||||
'国籍': config.DEFAULT_VALUES_ADD['国籍'],
|
||||
'备注': config.DEFAULT_VALUES_ADD['备注'],
|
||||
'专职技能': config.DEFAULT_VALUES_ADD['专职技能'],
|
||||
'技能等级': config.DEFAULT_VALUES_ADD['技能等级'],
|
||||
})
|
||||
|
||||
output_path = f"{output_dir}\\{config._safe_name(store_name)}增员导入名单.xls"
|
||||
excelio.write_template(template_file, output_path, unit_no, unit_full_name,
|
||||
records, config.TPL_COLS_ADD, config.DATE_COLS_ADD)
|
||||
_log(f" 已生成:{output_path}")
|
||||
produced.append({"unit": str(store_name), "count": len(group), "path": output_path})
|
||||
|
||||
_log(f"所有【{operation_type}】导入名单生成完成!")
|
||||
return produced
|
||||
|
||||
|
||||
def run(ctx):
|
||||
"""主入口(与影刀版一致):依次生成「转移参保」和「新参保」两类名单。"""
|
||||
ctx.progress(5)
|
||||
produced = []
|
||||
produced += _process_add_members('转移参保')
|
||||
ctx.progress(40)
|
||||
produced += _process_add_members('新参保')
|
||||
ctx.progress(100)
|
||||
total = sum(p["count"] for p in produced)
|
||||
return {"summary": f"增员名单制作:{len(produced)} 个单位 / {total} 人",
|
||||
"rows": produced, "notes": []}
|
||||
@@ -1,66 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""减员名单制作模式(sb_person_change 插件)。
|
||||
|
||||
自 workflows/XQ0008 generate_stop.py 迁移:读取【停保名单】sheet,筛选 区域=重庆,
|
||||
按参保单位分组复制《减员模版.xls》(保留下拉字典),逐单位生成《XX减员导入名单.xls》。
|
||||
填写标准:减少时间=当天、减少原因=在职人员主动解除劳动合同、
|
||||
五个险种减少标志=1 减少、失业原因=3 劳动者自愿辞职。
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
from . import config
|
||||
from . import excelio
|
||||
from . import source
|
||||
|
||||
|
||||
def _log(msg):
|
||||
config.log(msg)
|
||||
|
||||
|
||||
def run(ctx):
|
||||
"""主流程:读【停保名单】→ 筛选重庆 → 按单位生成减员导入名单。"""
|
||||
ctx.progress(5)
|
||||
source_file, df_filtered = source.load_stop_rows()
|
||||
if df_filtered.empty:
|
||||
ctx.progress(100)
|
||||
return {"summary": f"无【{config.REGION}】区域停保数据", "rows": [], "notes": []}
|
||||
config.check_not_locked(source_file)
|
||||
_log(f"共找到 {len(df_filtered)} 条 {config.REGION} 区域停保记录")
|
||||
|
||||
today = datetime.now()
|
||||
_log(f"制作日期:{today.strftime('%Y-%m-%d')}(减少时间 = 当天)")
|
||||
|
||||
cm = config.COLUMN_MAP_STOP
|
||||
template_file = excelio.find_template_file(config.STOP_TEMPLATE_FILE)
|
||||
output_dir = excelio.get_output_dir_stop()
|
||||
_log(f"输出目录:{output_dir}")
|
||||
produced = []
|
||||
for group_key, group in df_filtered.groupby(config.GROUP_COL_STOP):
|
||||
_log(f" 正在处理:单位【{group_key}】,共 {len(group)} 人")
|
||||
first_row = group.iloc[0]
|
||||
unit_no = first_row[cm['单位社保号']] # 单位社保号 → B1
|
||||
unit_name = first_row[cm['单位名称']] # 参保单位 → D1
|
||||
|
||||
records = []
|
||||
for _, row in group.iterrows():
|
||||
rec = {'减少时间': today}
|
||||
for tpl_col in config.TPL_COLS_STOP:
|
||||
if tpl_col == '减少时间':
|
||||
continue
|
||||
if tpl_col in cm:
|
||||
rec[tpl_col] = config._clean_value(row[cm[tpl_col]])
|
||||
else:
|
||||
rec[tpl_col] = config.DEFAULT_VALUES_STOP[tpl_col]
|
||||
records.append(rec)
|
||||
|
||||
output_path = f"{output_dir}\\{config._safe_name(group_key)}减员导入名单.xls"
|
||||
excelio.write_template(template_file, output_path, unit_no, unit_name,
|
||||
records, config.TPL_COLS_STOP, config.DATE_COLS_STOP)
|
||||
_log(f" 已生成:{output_path}")
|
||||
produced.append({"unit": str(group_key), "count": len(group), "path": output_path})
|
||||
|
||||
_log(f"所有停保导入名单生成完成!共 {len(produced)} 个单位")
|
||||
ctx.progress(100)
|
||||
total = sum(p["count"] for p in produced)
|
||||
return {"summary": f"减员名单制作:{len(produced)} 个单位 / {total} 人",
|
||||
"rows": produced, "notes": []}
|
||||
@@ -1,41 +0,0 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "sb_person_change",
|
||||
"name": "社保系统增减员办理",
|
||||
"version": "1.0.0",
|
||||
"description": "重庆社保增减员全流程:增员/减员名单制作 → 平台增员办理 → 核查回盘(含预检)",
|
||||
"category": "社保",
|
||||
"icon": "",
|
||||
"platform": "",
|
||||
"uses_month": false,
|
||||
"capabilities": ["sb_person_change"],
|
||||
"permissions": {
|
||||
"platforms": []
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"mode": {
|
||||
"type": "string",
|
||||
"title": "执行模式",
|
||||
"default": "增员名单制作",
|
||||
"enum": ["增员名单制作", "减员名单制作", "增员办理", "核查回盘", "预检"],
|
||||
"description": "预检=只读源表与台账校验,不开浏览器"
|
||||
},
|
||||
"limit": {
|
||||
"type": "integer",
|
||||
"title": "分批条数",
|
||||
"default": 0,
|
||||
"description": "增员办理/核查回盘每次最多处理的单位数,0=不限"
|
||||
},
|
||||
"debug_mode": {
|
||||
"type": "string",
|
||||
"title": "调试模式",
|
||||
"default": "关闭",
|
||||
"enum": ["关闭", "开启"],
|
||||
"description": "开启后保存页面截图与验证码调试图(插件 debug/ 目录)"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
DrissionPage>=4.1
|
||||
ddddocr>=1.5
|
||||
python-dotenv>=1.0
|
||||
openpyxl>=3.1
|
||||
pandas>=2.0
|
||||
xlrd>=2.0
|
||||
xlwt>=1.3
|
||||
xlutils>=2.0
|
||||
@@ -1,182 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""源名单/台账数据层(sb_person_change 插件)。
|
||||
|
||||
自 workflows/XQ0014 import_add.py(名单读取、台账取号)与 check_review.py(核查任务)
|
||||
迁移;名单制作模式的源表读取也在此(与 generate_add/generate_stop 同源)。
|
||||
print → config.log。
|
||||
"""
|
||||
import os
|
||||
from datetime import datetime
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from . import config
|
||||
from . import excelio
|
||||
|
||||
|
||||
def _log(msg):
|
||||
config.log(msg)
|
||||
|
||||
|
||||
# ==================== 源名单读取(增员办理) ====================
|
||||
def load_add_units(exclude_ids=frozenset()):
|
||||
"""读取源名单并筛选,返回 [(参保单位, 人数), ...](按单位分组)。
|
||||
|
||||
筛选:区域=重庆 ∩ 参保类型=新参保 ∩ 办理状态为空/NULL
|
||||
(待审核=已提交社保局、参保失败=已在其它流程处理,均不再办理)。
|
||||
exclude_ids:需排除的身份证号集合(上次运行已回写办理状态的人员,防重复申报)。
|
||||
"""
|
||||
source_file = config._latest_file(config.SOURCE_DIR, config.SOURCE_GLOB)
|
||||
now = datetime.now()
|
||||
xl = pd.ExcelFile(source_file)
|
||||
sheet_name = config._pick_sheet(xl, f"{now:%Y%m}参保名单", config.ADD_SHEET_KEY)
|
||||
_log(f"源名单:{os.path.basename(source_file)}(sheet: {sheet_name})")
|
||||
# 增员办理/核查的回写都落在该源名单上
|
||||
excelio.set_writeback_target(source_file, sheet_name)
|
||||
|
||||
df = pd.read_excel(source_file, sheet_name=sheet_name, header=config.SOURCE_HEADER_ROW - 1)
|
||||
status_text = df[config.STATUS_COL].astype(str).str.strip().str.lower()
|
||||
mask = (
|
||||
(df[config.REGION_COL].astype(str).str.strip() == config.REGION)
|
||||
& (df[config.TYPE_COL].astype(str).str.strip() == config.OPERATION_TYPE)
|
||||
& (df[config.STATUS_COL].isna() | status_text.isin(['', 'nan', 'none', 'nat']))
|
||||
)
|
||||
sub = df[mask].copy()
|
||||
if exclude_ids and '身份证号码' in sub.columns:
|
||||
before = len(sub)
|
||||
ref = [config._norm_id(x) for x in exclude_ids]
|
||||
sub = sub[~sub['身份证号码'].map(lambda v: config._id_hit(config._norm_id(v), ref))]
|
||||
dropped = before - len(sub)
|
||||
if dropped:
|
||||
_log(f" 已排除 {dropped} 行上次运行已回写的人员(防重复申报)")
|
||||
if sub.empty:
|
||||
_log(f"没有筛选到数据({config.REGION} ∩ {config.OPERATION_TYPE} ∩ 办理状态为空)")
|
||||
return []
|
||||
grouped = sub.groupby(sub[config.UNIT_COL].astype(str).str.strip()).size()
|
||||
units = sorted(grouped.items(), key=lambda t: t[0])
|
||||
_log(f"筛选结果:共 {sum(n for _, n in units)} 人 / {len(units)} 个参保单位")
|
||||
return units
|
||||
|
||||
|
||||
# ==================== 源名单读取(核查回盘) ====================
|
||||
def load_check_tasks(exclude_ids=frozenset()):
|
||||
"""读取源名单,筛选 办理状态=待审核 的行,按参保单位分组。
|
||||
|
||||
返回 [{unit, count, cids(set)}]。
|
||||
exclude_ids:上次运行已回写的人员身份证号(防重复核查)。
|
||||
"""
|
||||
source_file = config._latest_file(config.SOURCE_DIR, config.SOURCE_GLOB)
|
||||
now = datetime.now()
|
||||
xl = pd.ExcelFile(source_file)
|
||||
sheet_name = config._pick_sheet(xl, f"{now:%Y%m}参保名单", config.ADD_SHEET_KEY)
|
||||
_log(f"源名单:{os.path.basename(source_file)}(sheet: {sheet_name})")
|
||||
excelio.set_writeback_target(source_file, sheet_name)
|
||||
|
||||
df = pd.read_excel(source_file, sheet_name=sheet_name, header=config.SOURCE_HEADER_ROW - 1)
|
||||
status = df[config.STATUS_COL].astype(str).str.strip()
|
||||
mask = (
|
||||
(df[config.REGION_COL].astype(str).str.strip() == config.REGION)
|
||||
& (df[config.TYPE_COL].astype(str).str.strip() == config.OPERATION_TYPE)
|
||||
& (status == config.CHECK_STATUS)
|
||||
)
|
||||
sub = df[mask].copy()
|
||||
if exclude_ids and '身份证号码' in sub.columns:
|
||||
before = len(sub)
|
||||
ref = [config._norm_id(x) for x in exclude_ids]
|
||||
sub = sub[~sub['身份证号码'].map(lambda v: config._id_hit(config._norm_id(v), ref))]
|
||||
dropped = before - len(sub)
|
||||
if dropped:
|
||||
_log(f" 已排除 {dropped} 行上次运行已回写的人员(防重复核查)")
|
||||
if sub.empty:
|
||||
_log(f"没有筛选到数据({config.REGION} ∩ {config.OPERATION_TYPE} ∩ "
|
||||
f"办理状态={config.CHECK_STATUS})")
|
||||
return []
|
||||
|
||||
tasks = []
|
||||
for unit, g in sub.groupby(sub[config.UNIT_COL].astype(str).str.strip()):
|
||||
cids = {config._norm_id(v) for v in g['身份证号码']}
|
||||
cids.discard('')
|
||||
tasks.append({"unit": unit, "count": len(cids), "cids": cids})
|
||||
tasks.sort(key=lambda t: t['unit'])
|
||||
_log(f"核查范围:共 {sum(t['count'] for t in tasks)} 人 / {len(tasks)} 个参保单位"
|
||||
f"(办理状态={config.CHECK_STATUS})")
|
||||
return tasks
|
||||
|
||||
|
||||
# ==================== 源名单读取(名单制作) ====================
|
||||
def load_add_rows(operation_type):
|
||||
"""读取【参保名单】sheet,筛选 区域=重庆 ∩ 参保类型=指定类型 ∩ 办理状态为空。
|
||||
|
||||
返回 (source_file, df_filtered)。身份证/电话按文本读,防 18 位丢精度。
|
||||
"""
|
||||
source_file = config._latest_file(config.SOURCE_DIR, config.SOURCE_GLOB)
|
||||
xl = pd.ExcelFile(source_file)
|
||||
sheet_name = config._pick_sheet(xl, "", config.ADD_SHEET_KEY)
|
||||
_log(f"源表:{os.path.basename(source_file)}(sheet: {sheet_name})")
|
||||
df_source = pd.read_excel(
|
||||
source_file, sheet_name=sheet_name, header=config.SOURCE_HEADER_ROW - 1,
|
||||
dtype={'身份证号码': str, '电话号码': str})
|
||||
status_text = df_source[config.STATUS_COL].astype(str).str.strip().str.lower()
|
||||
mask = (
|
||||
(df_source[config.REGION_COL] == config.REGION)
|
||||
& (df_source[config.TYPE_COL] == operation_type)
|
||||
& (df_source[config.STATUS_COL].isna() | status_text.isin(['', 'nan', 'none', 'nat']))
|
||||
)
|
||||
df_filtered = df_source[mask].copy()
|
||||
if df_filtered.empty:
|
||||
_log(f"没有找到【{operation_type}】的数据({config.REGION}区域,办理状态为空)")
|
||||
return source_file, df_filtered
|
||||
|
||||
|
||||
def load_stop_rows():
|
||||
"""读取【停保名单】sheet,筛选 区域=重庆。全列按文本读,保住身份证/社保编号完整值。
|
||||
|
||||
返回 (source_file, df_filtered)。
|
||||
"""
|
||||
source_file = config._latest_file(config.SOURCE_DIR, config.SOURCE_GLOB)
|
||||
xl = pd.ExcelFile(source_file)
|
||||
sheet_name = config._pick_sheet(xl, "", config.STOP_SHEET_KEY)
|
||||
_log(f"源表:{os.path.basename(source_file)}(sheet: {sheet_name})")
|
||||
df_source = pd.read_excel(
|
||||
source_file, sheet_name=sheet_name, header=config.SOURCE_HEADER_ROW - 1, dtype=str)
|
||||
df_filtered = df_source[df_source[config.REGION_COL] == config.REGION].copy()
|
||||
if df_filtered.empty:
|
||||
_log(f"没有找到【{config.REGION}】区域的停保数据")
|
||||
return source_file, df_filtered
|
||||
|
||||
|
||||
# ==================== 台账取号 ====================
|
||||
def load_accounts(unit_names):
|
||||
"""从台账「YYYY年M月缴费比例」sheet 取各单位账号。
|
||||
|
||||
返回 {参保单位: {"username":..., "username_src": "信用代码|平台用户名", "password":...}},
|
||||
取不到的单位不在返回值中(由预检统一报错)。
|
||||
"""
|
||||
ledger_file = config._latest_file(config.LEDGER_DIR, config.LEDGER_GLOB)
|
||||
now = datetime.now()
|
||||
xl = pd.ExcelFile(ledger_file)
|
||||
sheet_name = config._pick_sheet(xl, f"{now.year}年{now.month}月缴费比例", "缴费比例",
|
||||
pattern=r"(20\d{2})年(1[0-2]|[1-9])月缴费比例")
|
||||
_log(f"台账:{os.path.basename(ledger_file)}(sheet: {sheet_name})")
|
||||
|
||||
# 表头为 1-2 行合并结构:跳过前 2 行,B列(户头)非空即数据行
|
||||
df = pd.read_excel(ledger_file, sheet_name=sheet_name, header=None, skiprows=2)
|
||||
df = df[df[config.LEDGER_COL["户头"]].notna()].copy()
|
||||
for c in config.LEDGER_COL.values():
|
||||
df[c] = df[c].map(config._to_text)
|
||||
|
||||
pool = df[(df[config.LEDGER_COL["城市"]] == config.REGION)
|
||||
& (df[config.LEDGER_COL["在用"]] == "是")]
|
||||
accounts = {}
|
||||
for name in unit_names:
|
||||
hit = pool[pool[config.LEDGER_COL["户头"]] == name]
|
||||
if hit.empty:
|
||||
continue # 预检阶段统一报「台账未匹配」
|
||||
row = hit.iloc[0]
|
||||
credit, plat_user, plat_pwd = (
|
||||
row[config.LEDGER_COL["信用代码"]], row[config.LEDGER_COL["平台用户名"]],
|
||||
row[config.LEDGER_COL["平台密码"]])
|
||||
# 用户名规则:信用代码优先,空则回退平台用户名
|
||||
username, src = (credit, "信用代码") if credit else (plat_user, "平台用户名")
|
||||
accounts[name] = {"username": username, "username_src": src, "password": plat_pwd}
|
||||
return accounts
|
||||
@@ -1,742 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""政务平台网页操作层(sb_person_change 插件)。
|
||||
|
||||
自 workflows/XQ0014 import_add.py(增员导入申报)与 check_review.py(已申报查询核查、
|
||||
回盘打印下载核对)迁移。全部 print → config.log,截图统一走 excelio.shot。
|
||||
依赖登录会话:login.LAST_SESSION(每个单位登录一次,办完 close_session)。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse, parse_qsl, urlencode
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from . import config
|
||||
from . import excelio
|
||||
from . import login
|
||||
|
||||
BUSINESS_ITEM = "城保参保单位人员增加" # 单位办事列表里的业务名称
|
||||
WEB_TIMEOUT = 20 # 网页元素等待超时(秒)
|
||||
|
||||
# 核查回盘相关(check_review 同源)
|
||||
MENU_QUERY = "已申报查询" # 业务页左侧菜单
|
||||
API_KEYWORD = "queryYsbWs04orWs01" # 已申报明细查询接口(监听 + 重放)
|
||||
API_UNIT_INFO = ("https://ggfw.rlsbj.cq.gov.cn/onlinehall/declare/server/gourd/"
|
||||
"cloud/ggfw/declare/query/DwCx/dwyl/getAab001") # 单位信息接口(页面加载完成标志)
|
||||
MENU_PAGE_URL = ("https://ggfw.rlsbj.cq.gov.cn/onlinehall/nethall/pc/cqzhrs/"
|
||||
"onlineoffice/OdCommon") # 左侧菜单页(刷新/直跳即可回到菜单)
|
||||
PAGE_SIZE = 10 # 重放接口每页条数(与平台默认一致,翻页取全量)
|
||||
MAX_PAGES = 50 # 重放翻页上限(防死循环)
|
||||
|
||||
|
||||
def _log(msg):
|
||||
config.log(msg)
|
||||
|
||||
|
||||
def _shot(tab, name):
|
||||
excelio.shot(tab, name)
|
||||
|
||||
|
||||
def _click_any(tab, selectors, desc, timeout=WEB_TIMEOUT):
|
||||
"""按候选选择器顺序定位并点击第一个命中元素,全部未命中抛异常。"""
|
||||
last_err = None
|
||||
for sel in selectors:
|
||||
try:
|
||||
ele = tab.ele(sel, timeout=timeout)
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
continue
|
||||
if ele:
|
||||
ele.click()
|
||||
return ele
|
||||
raise RuntimeError(f"网页操作失败:找不到{desc}({last_err})")
|
||||
|
||||
|
||||
def _find_any(tab, selectors, desc, timeout=WEB_TIMEOUT):
|
||||
"""按候选选择器顺序查找元素,全部未命中抛异常。"""
|
||||
for sel in selectors:
|
||||
ele = tab.ele(sel, timeout=timeout)
|
||||
if ele:
|
||||
return ele
|
||||
raise RuntimeError(f"网页操作失败:找不到{desc}")
|
||||
|
||||
|
||||
def _wait_modal(tab, keyword, timeout=60):
|
||||
"""等待某 ant-modal 弹窗正文出现指定关键字,返回该弹窗元素;超时返回 None。"""
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
for m in tab.eles('css:.ant-modal-body'):
|
||||
if keyword in (m.text or ''):
|
||||
return m
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
return None
|
||||
|
||||
|
||||
def _dismiss_popups(tab, rounds=5):
|
||||
"""循环关闭常见提示弹窗(我已知晓/我知道了/确定/同意),直到没有可关的。"""
|
||||
texts = ["我已知晓", "我知道了", "知道了", "确 定", "确定", "同 意", "同意"]
|
||||
for _ in range(rounds):
|
||||
hit = False
|
||||
for t in texts:
|
||||
try:
|
||||
btn = tab.ele(f'tag:button@@text()={t}', timeout=0.5)
|
||||
except Exception:
|
||||
btn = None
|
||||
if btn:
|
||||
try:
|
||||
btn.click()
|
||||
_log(f" 关闭弹窗:{t}")
|
||||
hit = True
|
||||
time.sleep(1.2)
|
||||
except Exception:
|
||||
pass
|
||||
if not hit:
|
||||
break
|
||||
|
||||
|
||||
# ==================== 增员导入:业务页与上传 ====================
|
||||
def open_business_page(page, work_tab):
|
||||
"""工作台 → 单位办事 → 「城保参保单位人员增加」在线办理。返回承载业务页的 tab。"""
|
||||
before = set(page.tab_ids)
|
||||
_click_any(work_tab, ['tag:button@@text()=单位办事'], '「单位办事」菜单')
|
||||
time.sleep(2.5)
|
||||
# 列表项:h4 标题定位 → 上溯到 li.ant-list-item → 点其「在线办理」
|
||||
h4 = _find_any(work_tab, [f'tag:h4@@text()={BUSINESS_ITEM}'], f'业务入口「{BUSINESS_ITEM}」')
|
||||
li = h4
|
||||
for _ in range(6):
|
||||
li = li.parent()
|
||||
if li is None:
|
||||
break
|
||||
if li.tag == 'li':
|
||||
break
|
||||
act = li.ele('text=在线办理', timeout=3) if li is not None else None
|
||||
if act is None:
|
||||
raise RuntimeError("网页操作失败:找不到「在线办理」按钮")
|
||||
act.click()
|
||||
# 业务页可能新开 tab 或当前页跳转:轮询识别出现上传控件(input[type=file])的页面
|
||||
deadline = time.time() + 30
|
||||
while time.time() < deadline:
|
||||
time.sleep(1)
|
||||
cand_tids = [i for i in page.tab_ids if i not in before] + [work_tab.tab_id]
|
||||
for tid in cand_tids:
|
||||
try:
|
||||
t = page.get_tab(tid)
|
||||
if t.ele('#customized_form_controls_data', timeout=0.5):
|
||||
return t
|
||||
except Exception:
|
||||
continue
|
||||
raise RuntimeError("进入在线办理页失败(未出现文件上传控件)")
|
||||
|
||||
|
||||
def _wait_import_result(tab, timeout=90):
|
||||
"""导入结果探针:等待「导入完成」成功弹窗,或捕获失败提示(modal/toast)。
|
||||
返回 ("ok", modal元素) / ("fail", 提示文本) / ("timeout", None)。"""
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
for m in tab.eles('css:.ant-modal-body'):
|
||||
t = (m.text or '').strip()
|
||||
if '导入完成' in t:
|
||||
return "ok", m
|
||||
if t and not any(k in t for k in ('提交中', '导入中', '加载中')):
|
||||
return "fail", t
|
||||
for msg in tab.eles('css:.ant-message'):
|
||||
t = (msg.text or '').strip()
|
||||
if t:
|
||||
return "fail", t
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.4)
|
||||
return "timeout", None
|
||||
|
||||
|
||||
def _wait_unit_ready(tab, timeout=5):
|
||||
"""等参保单位信息真正显示出来(导入请求 aab001 部件的就绪信号)。
|
||||
|
||||
单位信息由上传文件解析而来,显示在 borderless 下拉框里:
|
||||
可能先以 placeholder 形式出现,也可能直接是选中值。
|
||||
必须等文本内容真正渲染出来(非空)才算就绪,仅元素挂载不算。"""
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
for sel in tab.eles('css:.ant-select-borderless'):
|
||||
for kind in ('css:.ant-select-selection-placeholder',
|
||||
'css:.ant-select-selection-item'):
|
||||
ele = sel.ele(kind, timeout=1)
|
||||
if ele and (ele.text or '').strip():
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
return False
|
||||
|
||||
|
||||
def upload_import(tab, xls_path, max_rounds=3):
|
||||
"""上传名单 xls 并点「导入」,带失败探针与重试:
|
||||
每轮都重新选文件(重新触发页面解析单位信息),就绪后再点导入。
|
||||
返回 (导入成功人数, 导入失败人数)。"""
|
||||
last_err = "导入超时无响应"
|
||||
for rnd in range(1, max_rounds + 1):
|
||||
inp = _find_any(tab, ['#customized_form_controls_data',
|
||||
'css:input[type="file"]'], '文件上传控件')
|
||||
inp.input(xls_path) # DrissionPage 对 file input 直接写路径即上传
|
||||
# 等单位信息出现(placeholder 或选中值),未就绪点导入会报 aab001 缺失
|
||||
if not _wait_unit_ready(tab, timeout=40):
|
||||
_log(" 警告:40s 内单位信息未出现,本轮仍尝试导入")
|
||||
time.sleep(1.0) # 就绪后再留缓冲,避免点太快
|
||||
_shot(tab, "03_file_selected")
|
||||
_click_any(tab, ['tag:button@@text()=导 入', 'tag:button@@text():导入'], '「导 入」按钮')
|
||||
state, payload = _wait_import_result(tab, timeout=90)
|
||||
if state == "ok":
|
||||
_shot(tab, "04_import_result")
|
||||
text = payload.text or ''
|
||||
m_ok = re.search(r'成功[::]\s*(\d+)\s*人', text)
|
||||
m_fail = re.search(r'失败[::]\s*(\d+)\s*人', text)
|
||||
total = int(m_ok.group(1)) if m_ok else 0
|
||||
failed = int(m_fail.group(1)) if m_fail else 0
|
||||
_log(f" 导入完成:成功 {total} 人,失败 {failed} 人")
|
||||
if total == 0:
|
||||
raise RuntimeError(f"导入完成但成功人数为 0,提示:{text.strip()[:120]}")
|
||||
for t in ('确 定', '确定'):
|
||||
try:
|
||||
btn = tab.ele(f'tag:button@@text()={t}', timeout=2)
|
||||
except Exception:
|
||||
btn = None
|
||||
if btn:
|
||||
btn.click()
|
||||
break
|
||||
time.sleep(1.5)
|
||||
return total, failed
|
||||
# 失败/超时:记录提示,重试
|
||||
last_err = payload if state == "fail" else "导入后未出现结果弹窗(超时)"
|
||||
_log(f" 第 {rnd} 轮导入未成功:{str(last_err)[:120]}")
|
||||
time.sleep(2 + rnd) # 失败后多等一会,避免连点触发风控
|
||||
raise RuntimeError(f"导入重试 {max_rounds} 轮均失败,最后提示:{str(last_err)[:160]}")
|
||||
|
||||
|
||||
def read_failed_rows(tab):
|
||||
"""切到「校验未通过人员」tab 读表格,返回 [(证件号码, 详细信息), ...]。
|
||||
按表头(含「证件号码」+「详细信息」列)定位表格,避免抓到左侧导航等其它 tab 组件的面板。"""
|
||||
try:
|
||||
tab_btn = tab.ele('tag:span@@text()=校验未通过人员', timeout=10)
|
||||
except Exception:
|
||||
tab_btn = None
|
||||
if not tab_btn:
|
||||
return []
|
||||
tab_btn.click()
|
||||
time.sleep(2)
|
||||
rows = []
|
||||
try:
|
||||
for tb in tab.eles('tag:table'):
|
||||
ths = [th.text.strip() for th in tb.eles('tag:th')]
|
||||
if '证件号码' in ths and '详细信息' in ths:
|
||||
i_id, i_detail = ths.index('证件号码'), ths.index('详细信息')
|
||||
for tr in tb.eles('css:tbody tr'):
|
||||
tds = [td.text.strip() for td in tr.eles('tag:td')]
|
||||
if len(tds) > max(i_id, i_detail) and len(tds[i_id]) >= 15:
|
||||
detail = tds[i_detail]
|
||||
# 备注只保留冒号后的内容(去掉"校验通过业务校验失败:"这类前缀)
|
||||
for sep in (':', ':'):
|
||||
if sep in detail:
|
||||
detail = detail.split(sep, 1)[1].strip()
|
||||
break
|
||||
rows.append((tds[i_id], detail))
|
||||
break
|
||||
except Exception as e:
|
||||
_log(f" 读取校验未通过表格异常:{e}")
|
||||
_shot(tab, "05_check_failed_tab")
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 增员导入:预申报与提交 ====================
|
||||
def _wait_pdf_ready(tab, timeout=60):
|
||||
"""等 react-pdf canvas 出现且 2 秒不变,视为 PDF 绘制完成。超时仅告警不拦截。"""
|
||||
last, stable_since = None, None
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
canvases = tab.eles('css:.react-pdf__Page__canvas')
|
||||
sig = (len(canvases), canvases[0].attr('width') if canvases else None)
|
||||
except Exception:
|
||||
sig = None
|
||||
if sig and sig[0] > 0:
|
||||
if sig == last:
|
||||
if stable_since and time.time() - stable_since >= 2:
|
||||
return True
|
||||
else:
|
||||
stable_since = time.time()
|
||||
last = sig
|
||||
time.sleep(1)
|
||||
_log(" 警告:等待 PDF 渲染超时,继续尝试提交")
|
||||
return False
|
||||
|
||||
|
||||
def _goto_submit_page(tab, tries=3):
|
||||
"""点「下一步」进入提交页,验证「提 交」按钮出现;未出现则重试。"""
|
||||
for i in range(tries):
|
||||
_click_any(tab, ['tag:button@@text()=下一步'], '「下一步」按钮')
|
||||
deadline = time.time() + 12
|
||||
while time.time() < deadline:
|
||||
if tab.ele('tag:button@@text()=提 交', timeout=1):
|
||||
return True
|
||||
time.sleep(0.5)
|
||||
_log(f" 下一步后未出现「提 交」按钮(第 {i + 1} 次),重试")
|
||||
time.sleep(1.5)
|
||||
return False
|
||||
|
||||
|
||||
def _click_submit(tab, tries=3):
|
||||
"""点「提 交」,验证「已知晓」确认弹窗出现;第一次可能因按钮未就绪失效,重试。
|
||||
期间打印页面 toast 提示,便于诊断失败原因。"""
|
||||
for i in range(tries):
|
||||
btn = tab.ele('tag:button@@text()=提 交', timeout=5)
|
||||
if btn:
|
||||
try:
|
||||
btn.click()
|
||||
except Exception:
|
||||
pass
|
||||
deadline = time.time() + 10
|
||||
while time.time() < deadline:
|
||||
if tab.ele('tag:button@@text()=已知晓', timeout=1):
|
||||
return True
|
||||
try:
|
||||
for msg in tab.eles('css:.ant-message'):
|
||||
t = (msg.text or '').strip()
|
||||
if t:
|
||||
_log(f" 提交提示:{t[:100]}")
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
_log(f" 第 {i + 1} 次提交未出现「已知晓」确认弹窗,重试")
|
||||
time.sleep(1.5)
|
||||
return False
|
||||
|
||||
|
||||
def _confirm_submit(tab, tries=3):
|
||||
"""点「已知晓」→ 等「您已成功提交」弹窗;未出现则重点已知晓。"""
|
||||
for i in range(tries):
|
||||
btn = tab.ele('tag:button@@text()=已知晓', timeout=5)
|
||||
if btn:
|
||||
try:
|
||||
btn.click()
|
||||
except Exception:
|
||||
pass
|
||||
if _wait_modal(tab, '您已成功提交', timeout=60):
|
||||
return True
|
||||
_log(f" 第 {i + 1} 次点击已知晓后未见成功弹窗,重试")
|
||||
return False
|
||||
|
||||
|
||||
def predeclare_and_submit(page, tab):
|
||||
"""预申报 → 去申报 → 关弹窗 → 全部提交 → 等 PDF → 下一步 → 提交(带重试)→ 已知晓 → 等成功。"""
|
||||
_click_any(tab, ['tag:button@@text()=预申报'], '「预申报」按钮')
|
||||
if _wait_modal(tab, '预申报成功', timeout=60) is None:
|
||||
raise RuntimeError("预申报后未出现成功弹窗")
|
||||
_click_any(tab, ['tag:button@@text()=去申报'], '「去申报」按钮')
|
||||
# 等申报页就绪:提示弹窗或「全部提交」按钮任一出现即继续(替代固定 sleep,省 ~8s 空等)
|
||||
deadline = time.time() + 15
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
if tab.ele('tag:button@@text()=我已知晓', timeout=0.5) or \
|
||||
tab.ele('tag:button@@text()=我知道了', timeout=0.5) or \
|
||||
tab.ele('tag:button@@text()=全部提交', timeout=0.5):
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.3)
|
||||
_dismiss_popups(tab) # 系统提示「我已知晓」+ 操作说明「我知道了」
|
||||
_shot(tab, "06_declare_page")
|
||||
_click_any(tab, ['tag:button@@text()=全部提交'], '「全部提交」按钮')
|
||||
_wait_pdf_ready(tab)
|
||||
_shot(tab, "07_pdf_ready")
|
||||
if not _goto_submit_page(tab):
|
||||
_shot(tab, "08_no_submit_btn")
|
||||
raise RuntimeError("点击下一步后未出现「提 交」按钮")
|
||||
_shot(tab, "08_submit_page")
|
||||
if not _click_submit(tab):
|
||||
_shot(tab, "09_submit_no_confirm")
|
||||
raise RuntimeError("点击提交后未出现「已知晓」确认弹窗")
|
||||
if not _confirm_submit(tab):
|
||||
_shot(tab, "10_confirm_no_success")
|
||||
raise RuntimeError("点击已知晓后未出现「您已成功提交」弹窗(提交可能未完成)")
|
||||
_shot(tab, "11_submit_success")
|
||||
_log(" 提交成功")
|
||||
|
||||
|
||||
def _collect_review_rows(tab):
|
||||
"""从明细表收集审核结论:{证件号码: (审核结论, 业务流水号)}。"""
|
||||
results = {}
|
||||
for tr in tab.eles('css:.ant-table-tbody tr.ant-table-row'):
|
||||
try:
|
||||
tds = [td.text.strip() for td in tr.eles('tag:td')]
|
||||
except Exception:
|
||||
continue
|
||||
# 明细表结构:业务流水号/业务类型/姓名/证件号码/审核结论/审核意见/操作
|
||||
# 证件号码可能是 15/18 位,尾号可为 X,不能只 isdigit
|
||||
cid = tds[3] if len(tds) > 3 else ''
|
||||
if len(cid) in (15, 18) and cid.rstrip('Xx').isdigit():
|
||||
results[cid] = (tds[4], tds[0])
|
||||
return results
|
||||
|
||||
|
||||
def _open_query_page(page, tab, timeout=25):
|
||||
"""点「去查看」进入申报查询列表(可能新开 tab),返回承载列表的 tab。"""
|
||||
before = set(page.tab_ids)
|
||||
_click_any(tab, ['tag:button@@text()=去查看'], '「去查看」按钮')
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
time.sleep(1)
|
||||
tids = [i for i in page.tab_ids if i not in before] + [tab.tab_id]
|
||||
for tid in tids:
|
||||
try:
|
||||
t = page.get_tab(tid)
|
||||
row = t.ele('css:.ant-table-tbody tr.ant-table-row', timeout=0.5)
|
||||
if row and row.ele('tag:a@@text()=查看', timeout=0.5):
|
||||
_shot(t, "12_query_list")
|
||||
return t
|
||||
except Exception:
|
||||
continue
|
||||
raise RuntimeError("点击去查看后未找到申报查询列表(含「查看」按钮的记录表)")
|
||||
|
||||
|
||||
def query_review_results(page, tab):
|
||||
"""进入申报查询列表 → 打开序号1记录的「查看」→ 读明细表审核结论。
|
||||
返回 {证件号码: (审核结论, 业务流水号)}。"""
|
||||
qtab = _open_query_page(page, tab)
|
||||
for attempt in range(3):
|
||||
row = qtab.ele('css:.ant-table-tbody tr.ant-table-row', timeout=10)
|
||||
view = row.ele('tag:a@@text()=查看', timeout=3) if row else None
|
||||
if view:
|
||||
try:
|
||||
view.click()
|
||||
except Exception:
|
||||
pass
|
||||
# 等明细表出现(含 18 位证件号码的行)
|
||||
deadline = time.time() + 12
|
||||
while time.time() < deadline:
|
||||
time.sleep(1)
|
||||
results = _collect_review_rows(qtab)
|
||||
if results:
|
||||
_shot(qtab, "13_review_detail")
|
||||
return results
|
||||
_log(f" 第 {attempt + 1} 次查看未读到审核结论明细,重试")
|
||||
_shot(qtab, "13_review_detail_miss")
|
||||
time.sleep(1.5)
|
||||
raise RuntimeError("未读取到审核结论明细表")
|
||||
|
||||
|
||||
# ==================== 核查回盘:已申报查询 + 接口重放 ====================
|
||||
def open_query_menu(tab):
|
||||
"""业务页左侧菜单点「已申报查询」,等记录表(表头含 当前状态/操作)出现。"""
|
||||
_click_any(tab, [f'tag:li@@text()={MENU_QUERY}', f'text={MENU_QUERY}'],
|
||||
f'左侧菜单「{MENU_QUERY}」')
|
||||
_dismiss_popups(tab)
|
||||
deadline = time.time() + 15
|
||||
while time.time() < deadline:
|
||||
for tb in tab.eles('tag:table'):
|
||||
try:
|
||||
ths = [th.text.strip() for th in tb.eles('tag:th')]
|
||||
except Exception:
|
||||
continue
|
||||
if '当前状态' in ths and '操作' in ths:
|
||||
return tb
|
||||
time.sleep(0.5)
|
||||
raise RuntimeError(f"点击「{MENU_QUERY}」后未出现申报记录表")
|
||||
|
||||
|
||||
def read_first_row(table):
|
||||
"""读申报记录表第一条:返回 (当前状态, 查看按钮元素)。无记录返回 (None, None)。"""
|
||||
row = table.ele('css:tbody tr.ant-table-row', timeout=3) \
|
||||
or table.ele('css:tbody tr', timeout=1)
|
||||
if row is None:
|
||||
return None, None
|
||||
ths = [th.text.strip() for th in table.eles('tag:th')]
|
||||
i_status = ths.index('当前状态')
|
||||
tds = [td.text.strip() for td in row.eles('tag:td')]
|
||||
status = tds[i_status] if len(tds) > i_status else ''
|
||||
view = None
|
||||
for sel in ('tag:a@@text()=查看', 'tag:span@@text()=查看', 'text=查看'):
|
||||
try:
|
||||
view = row.ele(sel, timeout=1)
|
||||
except Exception:
|
||||
view = None
|
||||
if view:
|
||||
break
|
||||
return status, view
|
||||
|
||||
|
||||
def _capture_query_url(page, tab, view):
|
||||
"""点「查看」并监听明细查询接口,返回请求 URL。
|
||||
明细可能在当前 tab 打开也可能新开 tab:两个方向都轮询监听。"""
|
||||
before = set(page.tab_ids)
|
||||
tab.listen.start(API_KEYWORD)
|
||||
new_tabs = []
|
||||
packet = None
|
||||
try:
|
||||
try:
|
||||
view.click()
|
||||
except Exception:
|
||||
view.click(by_js=True)
|
||||
deadline = time.time() + 25
|
||||
while time.time() < deadline and packet is None:
|
||||
# 新开 tab 也挂上监听(明细页可能新 tab 加载接口)
|
||||
for tid in [i for i in page.tab_ids if i not in before and i not in new_tabs]:
|
||||
new_tabs.append(tid)
|
||||
try:
|
||||
page.get_tab(tid).listen.start(API_KEYWORD)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
packet = tab.listen.wait(count=1, timeout=2)
|
||||
except Exception:
|
||||
packet = None
|
||||
if packet is None:
|
||||
for tid in new_tabs:
|
||||
try:
|
||||
packet = page.get_tab(tid).listen.wait(count=1, timeout=0.5)
|
||||
except Exception:
|
||||
packet = None
|
||||
if packet:
|
||||
break
|
||||
finally:
|
||||
for t in [tab] + [page.get_tab(tid) for tid in new_tabs if tid in page.tab_ids]:
|
||||
try:
|
||||
t.listen.stop()
|
||||
except Exception:
|
||||
pass
|
||||
if not packet:
|
||||
raise RuntimeError("点击查看后未监听到明细查询接口(queryYsbWs04orWs01)")
|
||||
url = packet.request.url
|
||||
_log(f" 已捕获明细接口:{url[:100]}...")
|
||||
return url
|
||||
|
||||
|
||||
def _fetch_via_xhr(tab, url):
|
||||
"""页内同步 XHR GET(自带登录态 cookies),返回响应文本。"""
|
||||
js = ("const xhr=new XMLHttpRequest();"
|
||||
"xhr.open('GET',arguments[0],false);"
|
||||
"xhr.setRequestHeader('Accept','application/json, text/javascript');"
|
||||
"xhr.send();return xhr.responseText;")
|
||||
return tab.run_js(js, url)
|
||||
|
||||
|
||||
def wait_unit_loaded(tab, unit_name, timeout=40):
|
||||
"""等业务页单位信息加载完成:轮询 getAab001 接口直到返回本单位数据。
|
||||
该接口没返回时页面没加载出单位,后续已申报查询/回盘打印都拿不到数据。
|
||||
接口轮询失败但页面已出现单位名时也视为加载成功(可能错过响应窗口)。
|
||||
返回 data[0](含 aab001、aab004 平台单位全称),页面已加载但接口拿不到时返回 {},超时返回 None。"""
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
raw = _fetch_via_xhr(tab, API_UNIT_INFO)
|
||||
data = (json.loads(raw).get('data') or [None])[0]
|
||||
if data and data.get('aab001'):
|
||||
_log(f" 单位信息已加载:{data.get('aab004')}(aab001={data.get('aab001')})")
|
||||
return data
|
||||
except Exception:
|
||||
pass
|
||||
# 接口没拿到但页面已经出现单位名 → 页面其实加载完了,不必再等
|
||||
try:
|
||||
if tab.ele(f'text:{unit_name}', timeout=0.5):
|
||||
_log(f" 页面已显示单位「{unit_name}」,视为加载完成(接口轮询未取到全称)")
|
||||
return {}
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
return None
|
||||
|
||||
|
||||
def replay_query_all(tab, captured_url):
|
||||
"""用捕获的请求参数重放接口翻页,取全量明细行。
|
||||
返回 ([{name, cid, conclusion, opinion}, ...], unit_full)。
|
||||
字段取 aac003/aac002/aae110s/aae111/aab004。"""
|
||||
parsed = urlparse(captured_url)
|
||||
base_params = [(k, v) for k, v in parse_qsl(parsed.query, keep_blank_values=True)
|
||||
if k != 'pageIndex']
|
||||
root = f"{parsed.scheme}://{parsed.netloc}{parsed.path}"
|
||||
rows, total = [], None
|
||||
for idx in range(MAX_PAGES):
|
||||
params = base_params + [('pageIndex', json.dumps(
|
||||
{"pageIndex": idx, "pageSize": PAGE_SIZE}, separators=(',', ':')))]
|
||||
full = f"{root}?{urlencode(params)}"
|
||||
raw = _fetch_via_xhr(tab, full)
|
||||
if not raw:
|
||||
raise RuntimeError(f"接口重放第 {idx + 1} 页返回空")
|
||||
payload = json.loads(raw)
|
||||
data = payload.get('data') or {}
|
||||
items = data.get('data') or []
|
||||
if total is None:
|
||||
total = data.get('total')
|
||||
rows.extend(items)
|
||||
_log(f" 接口重放第 {idx + 1} 页:取到 {len(items)} 条(累计 {len(rows)}/{total})")
|
||||
if not items or (total is not None and len(rows) >= total):
|
||||
break
|
||||
results = []
|
||||
for it in rows:
|
||||
results.append({
|
||||
"name": str(it.get('aac003') or '').strip(),
|
||||
"cid": config._norm_id(it.get('aac002')),
|
||||
"conclusion": str(it.get('aae110s') or '').strip(),
|
||||
"opinion": str(it.get('aae111') or '').strip(),
|
||||
})
|
||||
# 平台登记的参保单位全称(aab004),用于回盘文件命名
|
||||
unit_full = ""
|
||||
for it in rows:
|
||||
v = str(it.get('aab004') or '').strip()
|
||||
if v:
|
||||
unit_full = v
|
||||
break
|
||||
return results, unit_full
|
||||
|
||||
|
||||
# ==================== 核查回盘:回盘打印下载与核对 ====================
|
||||
def _clean_cell(v):
|
||||
"""单元格值转干净字符串:浮点整数去掉 .0,其余去首尾空白。"""
|
||||
if v is None:
|
||||
return ""
|
||||
if isinstance(v, float) and v.is_integer():
|
||||
return str(int(v))
|
||||
return str(v).strip()
|
||||
|
||||
|
||||
def download_huipan(page, biz_tab, unit):
|
||||
"""左侧菜单「回盘打印」→ 页内「回盘打印」按钮,等下载完成后重命名为规范文件名。
|
||||
返回保存的文件 Path。"""
|
||||
save_dir = Path(config.HUIPAN_DIR)
|
||||
save_dir.mkdir(parents=True, exist_ok=True)
|
||||
target = save_dir / f"{config.REPLAY_PREFIX}_{unit}_{datetime.now():%Y%m%d}.xlsx"
|
||||
menu_sel = ['tag:li@@text()=回盘打印', 'text=回盘打印']
|
||||
try:
|
||||
_click_any(biz_tab, menu_sel, '左侧菜单「回盘打印」')
|
||||
except Exception:
|
||||
# 点「查看」后会跳到明细详情页,左侧菜单不可见:直跳 OdCommon 菜单页即可
|
||||
try:
|
||||
_log(" 当前页看不到左侧菜单,直跳菜单页...")
|
||||
biz_tab.get(MENU_PAGE_URL)
|
||||
time.sleep(2)
|
||||
_click_any(biz_tab, menu_sel, '左侧菜单「回盘打印」(菜单页)')
|
||||
except Exception:
|
||||
# 直跳也不行:重开业务页再点(最后兜底)
|
||||
biz_tab = open_business_page(page, login.LAST_SESSION['tab'])
|
||||
_dismiss_popups(biz_tab)
|
||||
_click_any(biz_tab, menu_sel, '左侧菜单「回盘打印」(重开业务页)')
|
||||
_dismiss_popups(biz_tab)
|
||||
|
||||
# 页内「回盘打印」按钮(menu li 已处理,这里只找按钮/链接/文本)
|
||||
btn = None
|
||||
for sel in ('tag:button@@text()=回盘打印', 'tag:a@@text()=回盘打印',
|
||||
'tag:span@@text()=回盘打印'):
|
||||
try:
|
||||
btn = biz_tab.ele(sel, timeout=2)
|
||||
except Exception:
|
||||
btn = None
|
||||
if btn:
|
||||
break
|
||||
if btn is None:
|
||||
raise RuntimeError("未找到页内「回盘打印」按钮")
|
||||
|
||||
biz_tab.set.download_path(str(save_dir))
|
||||
before = {f.name for f in save_dir.iterdir() if f.is_file()}
|
||||
try:
|
||||
btn.click()
|
||||
except Exception:
|
||||
btn.click(by_js=True)
|
||||
|
||||
# 轮询等下载:新文件出现且大小连续2秒稳定(最多90秒)
|
||||
new_file, last_size, stable = None, -1, 0
|
||||
deadline = time.time() + 90
|
||||
while time.time() < deadline:
|
||||
time.sleep(1)
|
||||
files = [f for f in save_dir.iterdir() if f.is_file() and f.name not in before
|
||||
and f.suffix.lower() not in ('.crdownload', '.tmp')]
|
||||
if not files:
|
||||
stable, last_size = 0, -1
|
||||
continue
|
||||
f = max(files, key=lambda x: x.stat().st_mtime)
|
||||
size = f.stat().st_size
|
||||
if size > 0 and size == last_size:
|
||||
stable += 1
|
||||
if stable >= 2:
|
||||
new_file = f
|
||||
break
|
||||
else:
|
||||
stable = 0
|
||||
last_size = size
|
||||
if new_file is None:
|
||||
raise RuntimeError("点击回盘打印后90秒内未检测到新下载文件")
|
||||
os.replace(new_file, target) # 同名覆盖,保证文件名=回盘表_单位_日期.xlsx
|
||||
return target
|
||||
|
||||
|
||||
def verify_huipan(filepath, task_cids):
|
||||
"""读回盘表(表头在第2行),按身份证号核对五项参保状态,生成备注回写内容。
|
||||
同人多条记录:取参保缴费数量最多的那条(并列取先出现的)。
|
||||
返回 (remark_map, logs)。"""
|
||||
df = pd.read_excel(filepath, header=1)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
need = ['个人编号', '身份证号'] + config.INS_STATUSES
|
||||
missing = [c for c in need if c not in df.columns]
|
||||
if missing:
|
||||
raise RuntimeError(f"回盘表缺少列:{missing}")
|
||||
remarks, logs = {}, []
|
||||
for cid in task_cids:
|
||||
rows = df[df['身份证号'].map(
|
||||
lambda v: config._id_hit(config._norm_id(_clean_cell(v)), [cid]))]
|
||||
if rows.empty:
|
||||
remarks[cid] = "未查询到回盘记录"
|
||||
logs.append(f" 证件{cid}:回盘表中未找到记录 → 备注追加「未查询到回盘记录」")
|
||||
continue
|
||||
# 同人多条记录:取参保缴费数量最多的那条(并列取先出现的)
|
||||
best_row, best_ok = None, -1
|
||||
for _, row in rows.iterrows():
|
||||
ok = sum(1 for c in config.INS_STATUSES if _clean_cell(row[c]) == config.INS_OK)
|
||||
if ok > best_ok:
|
||||
best_row, best_ok = row, ok
|
||||
target = best_row
|
||||
bh = _clean_cell(target['个人编号'])
|
||||
if best_ok == len(config.INS_STATUSES):
|
||||
# 五项全参保缴费 = 正常,备注只追加个人编号
|
||||
remarks[cid] = f"个人编号:{bh}"
|
||||
logs.append(f" 证件{cid}:五项均参保缴费,个人编号 {bh} → 备注追加")
|
||||
else:
|
||||
# 有不是参保缴费的:记录个人编号 + 异常字段名和对应内容
|
||||
bad = [f"{c}:{_clean_cell(target[c])}"
|
||||
for c in config.INS_STATUSES if _clean_cell(target[c]) != config.INS_OK]
|
||||
remarks[cid] = f"个人编号:{bh};" + "、".join(bad)
|
||||
logs.append(f" 证件{cid}:参保状态异常 → {';'.join(bad)}(个人编号 {bh})→ 备注追加")
|
||||
return remarks, logs
|
||||
|
||||
|
||||
def do_huipan(page, biz_tab, task, res, unit_full="", fail_cids=()):
|
||||
"""每个账号核查完都执行:下载回盘记录 + 核对参保状态 + 备注追加(含与核查备注合并)。
|
||||
文件名单位优先用平台 aab004 全称,未取到(未办结跳过等)退回源名单参保单位名。
|
||||
fail_cids:审核不通过(参保失败)人员,平台无其回盘记录,跳过「未查询到回盘记录」回写。"""
|
||||
name_for_file = (unit_full or task['unit']).strip()
|
||||
if unit_full and unit_full != task['unit']:
|
||||
_log(f" 使用平台单位全称命名:{unit_full}")
|
||||
_log(" 开始回盘打印下载...")
|
||||
hp_file = download_huipan(page, biz_tab, name_for_file)
|
||||
_log(f" 回盘文件已保存:{hp_file}")
|
||||
hp_remarks, hp_logs = verify_huipan(hp_file, task['cids'])
|
||||
for line in hp_logs:
|
||||
_log(line)
|
||||
for cid in fail_cids:
|
||||
if hp_remarks.get(cid, "").strip() == "未查询到回盘记录":
|
||||
hp_remarks.pop(cid)
|
||||
_log(f" 证件{cid}:审核不通过无回盘记录,跳过未查询备注")
|
||||
# 与核查阶段已生成的备注合并(writeback_source 按证件号覆盖,需手动拼接)
|
||||
pending_remark = excelio._PENDING_REMARK
|
||||
for cid in list(hp_remarks):
|
||||
old = pending_remark.get(cid)
|
||||
if old:
|
||||
hp_remarks[cid] = f"{old}\n{hp_remarks[cid]}"
|
||||
if hp_remarks:
|
||||
excelio.writeback_source({}, hp_remarks)
|
||||
res["huipan"] = f"回盘已下载,核对回写 {len(hp_remarks)} 人"
|
||||
@@ -1,115 +0,0 @@
|
||||
# -*- 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())
|
||||
@@ -1,35 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""考勤月报封存检查(webhost 场景插件)配置。
|
||||
|
||||
与 plugins/seal_check/config.py 保持同步(根级 plugins/ 为单一真源)。
|
||||
"""
|
||||
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 = "休息"
|
||||
@@ -1,160 +0,0 @@
|
||||
# -*- 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「封存值是否最新」的对比接口尚未封装,本次跳过该检查,请在数据层补充接口后启用"
|
||||
@@ -1,279 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""考勤月报封存检查 - 规则引擎与五项检查(webhost 场景插件)
|
||||
|
||||
与 plugins/seal_check/logic.py 保持同步(根级 plugins/ 为单一真源)。
|
||||
|
||||
规则完全由运行人员每月在界面录入的天数值驱动:
|
||||
- 固休:应休 = 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}
|
||||
@@ -1,24 +0,0 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "seal_check",
|
||||
"name": "考勤月报封存检查",
|
||||
"version": "1.0.0",
|
||||
"description": "填写每月正休规则,一键执行五项检查并导出多 Sheet Excel 报告",
|
||||
"category": "考勤",
|
||||
"icon": "",
|
||||
"platform": "hr",
|
||||
"uses_month": true,
|
||||
"capabilities": ["seal_check", "hr.seal_check"],
|
||||
"permissions": {
|
||||
"platforms": ["hr"]
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"fixed_rest_days": { "type": "integer", "title": "固休应休天数", "default": 5, "description": "" },
|
||||
"size_rest_days": { "type": "integer", "title": "大小休应休天数", "default": 6, "description": "" },
|
||||
"quota_rest_days": { "type": "integer", "title": "限额排休上限", "default": 8, "description": "" }
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""考勤月报封存检查 - Excel 报告导出(webhost 场景插件)
|
||||
|
||||
与 plugins/seal_check/report.py 保持同步(根级 plugins/ 为单一真源)。
|
||||
|
||||
输出:考勤月报封存检查_{月份}_{时间戳}.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,41 @@
|
||||
# ERP报表导出(xq0031_xq0032)
|
||||
|
||||
金蝶 K3Cloud 报表自动导出插件:物料收发汇总表(需求31)+ 采购订单列表(需求32),
|
||||
支持新旧系统切换、仓库编码多选(或关系)、日期多档(N天 / 自定义区间)逐档导出。
|
||||
|
||||
## 目录结构
|
||||
|
||||
- `*.py` — 插件后端(ScenePlugin 注册 + ERP 登录 + 两报表逻辑),自包含,
|
||||
只引用标准库 / 第三方依赖 / 底座注入接口(`webhost.backend.plugins.base`)
|
||||
- `ui/` — 插件前端**构建产物**(壳子后端托管于 `/pui/xq0031_xq0032/`,勿手改)
|
||||
- `ui-src/` — 插件前端源码(Vue 3 + Element Plus + Vite)
|
||||
- `_pack.py` — 发布打包辅助(`_` 前缀,运行时不会被插件扫描加载)
|
||||
|
||||
## 前端开发 / 构建
|
||||
|
||||
```bash
|
||||
cd ui-src
|
||||
npm install
|
||||
npm run build # 产物输出到 ../ui/(vite.config.js 里 base=/pui/xq0031_xq0032/)
|
||||
```
|
||||
|
||||
联调:先启动壳子(webhost),`npm run dev` 走 vite 代理(5180 → 127.0.0.1:8799)。
|
||||
|
||||
## 打包发布
|
||||
|
||||
1. 构建 ui(见上)
|
||||
2. `desktop/` 下执行:`../.venv/Scripts/python.exe ../plugins/xq0031_xq0032/_pack.py`
|
||||
→ 产出 `dist-plugin/xq0031_xq0032_v<版本>.zip`(自动排除 ui-src 等)
|
||||
3. `desktop/` 下发布:
|
||||
`.venv\Scripts\python.exe -m controlplane.tools.agent_cli publish dist-plugin\xq0031_xq0032_v<版本>.zip --id xq0031_xq0032 --version <版本> --admin puddy`
|
||||
|
||||
## 个性化配置(自带界面)
|
||||
|
||||
`plugin.json` 声明 `"ui": true`,壳子插件页展示「打开插件界面」入口(弹独立窗口,
|
||||
同源自动携带登录会话)。账号密码 / 仓库编码 / 日期选项等在窗口内填写:
|
||||
|
||||
- 配置经壳子 `GET/POST /api/plugin-config/xq0031_xq0032` 保存,
|
||||
落执行机本机 `%LOCALAPPDATA%\37duAutomation\plugin_configs\xq0031_xq0032.json`,
|
||||
下次打开自动回填(表单改动防抖自动保存);
|
||||
- 执行经现有 `POST /api/runs`,日志/进度经 `WS /ws` 实时回显(另有 5 秒轮询兜底);
|
||||
- 浏览器每次现场真登录(auto_port 独立实例),确保登录的就是本次配置的账号。
|
||||
@@ -0,0 +1,185 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""ERP报表导出 - webhost 场景插件(XQ0031 + XQ0032 合并版)
|
||||
|
||||
金蝶 K3Cloud 报表自动导出,两种报表可单选或同次会话连导(登录一次):
|
||||
物料收发汇总表(XQ0031):组织/仓库编码(或关系多行)/日期多档(N天或自定义区间)逐档导出
|
||||
采购订单列表(XQ0032):快捷方案 → 等查询 → 按列表引出数据
|
||||
|
||||
个性化设计(自带 Vue 界面,plugin.json 声明 "ui": true):
|
||||
- ERP 新/旧系统、登录账号密码由用户在插件窗口内自行填写,
|
||||
经 /api/plugin-config 保存在执行机本机,下次打开自动回填;
|
||||
- 仓库编码、日期选项均为多选(可自建条目,日期可混入自定义区间);
|
||||
- 浏览器每次现场真登录(auto_port 独立实例),确保用的就是本次配置的账号。
|
||||
"""
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
||||
|
||||
from . import config
|
||||
from . import erp_login
|
||||
|
||||
# 执行模式
|
||||
MODE_31 = '物料收发汇总表'
|
||||
MODE_32 = '采购订单列表'
|
||||
MODE_BOTH = '两个都导'
|
||||
|
||||
|
||||
def _as_str_list(value):
|
||||
"""fields 里的多选值归一为去空去重的字符串列表(兼容逗号/空格分隔的字符串)。"""
|
||||
if value is None:
|
||||
return []
|
||||
if isinstance(value, str):
|
||||
parts = value.replace(',', ',').replace(' ', ',').split(',')
|
||||
elif isinstance(value, (list, tuple)):
|
||||
parts = list(value)
|
||||
else:
|
||||
parts = [value]
|
||||
out, seen = [], set()
|
||||
for p in parts:
|
||||
s = str(p).strip()
|
||||
if s and s not in seen:
|
||||
seen.add(s)
|
||||
out.append(s)
|
||||
return out
|
||||
|
||||
|
||||
class ErpReportExportPlugin(ScenePlugin):
|
||||
id = "xq0031_xq0032"
|
||||
name = "ERP物料收发汇总-采购订单报表导出"
|
||||
version = "1.0.2"
|
||||
description = "金蝶K3Cloud报表导出:物料收发汇总表(需求31)+ 采购订单列表(需求32),支持新旧系统与个性化配置"
|
||||
platform = "" # ERP 自带登录页(无验证码),插件内现场真登录,不使用底座共享登录态
|
||||
uses_month = False
|
||||
# 富字段声明(与 plugin.json 保持一致):ui=true 时壳子隐藏通用表单、展示打开插件窗口入口;
|
||||
# 此处仅作为无 manifest 时的兜底与参数契约文档
|
||||
fields = [
|
||||
{"key": "mode", "label": "执行模式", "type": "select",
|
||||
"options": [MODE_BOTH, MODE_31, MODE_32], "default": MODE_BOTH},
|
||||
{"key": "erp_system", "label": "ERP系统", "type": "select",
|
||||
"options": ["新版", "旧版"], "default": "新版"},
|
||||
{"key": "erp_username", "label": "ERP登录账号", "type": "text", "default": ""},
|
||||
{"key": "erp_password", "label": "ERP登录密码", "type": "password", "default": ""},
|
||||
{"key": "org_name", "label": "查询组织", "type": "text",
|
||||
"default": config.ORG_NAME},
|
||||
{"key": "stock_codes", "label": "仓库编码(多选,或关系)", "type": "multiselect",
|
||||
"options": config.STOCK_CODES_DEFAULT, "default": list(config.STOCK_CODES_DEFAULT)},
|
||||
{"key": "date_options", "label": "日期选项(多选,逐个导出)", "type": "multiselect",
|
||||
"options": config.DATE_OPTIONS_DEFAULT, "default": list(config.DATE_OPTIONS_DEFAULT)},
|
||||
{"key": "scheme_name", "label": "采购订单快捷方案", "type": "text",
|
||||
"default": config.SCHEME_NAME},
|
||||
{"key": "save_dir", "label": "保存目录(空=桌面/采购计划报表_日期)", "type": "text", "default": ""},
|
||||
]
|
||||
|
||||
def run(self, fields: dict, ctx) -> dict:
|
||||
fields = fields or {}
|
||||
# 注入日志钩子(插件内全部模块经 config.log 输出)
|
||||
config.set_log(ctx.log)
|
||||
|
||||
# ---------- 解析与校验 ----------
|
||||
mode = str(fields.get("mode") or MODE_BOTH).strip()
|
||||
erp = 'old' if str(fields.get("erp_system") or "新版").strip() == "旧版" else 'new'
|
||||
username = str(fields.get("erp_username") or "").strip()
|
||||
password = str(fields.get("erp_password") or "")
|
||||
org = str(fields.get("org_name") or "").strip() or config.ORG_NAME
|
||||
scheme = str(fields.get("scheme_name") or "").strip() or config.SCHEME_NAME
|
||||
codes = _as_str_list(fields.get("stock_codes")) or list(config.STOCK_CODES_DEFAULT)
|
||||
dates = _as_str_list(fields.get("date_options")) or list(config.DATE_OPTIONS_DEFAULT)
|
||||
if not username or not password:
|
||||
raise RuntimeError("ERP 登录账号/密码缺失:请在插件界面填写并保存配置后重试")
|
||||
if mode not in (MODE_BOTH, MODE_31, MODE_32):
|
||||
raise RuntimeError(f"未知执行模式:{mode}")
|
||||
if mode in (MODE_BOTH, MODE_31) and not (codes and dates):
|
||||
raise RuntimeError("物料收发汇总表需要仓库编码与日期选项(请在插件界面配置)")
|
||||
|
||||
save_dir_raw = str(fields.get("save_dir") or "").strip().strip('"')
|
||||
save_dir = Path(save_dir_raw) if save_dir_raw else Path(
|
||||
_desktop()) / f"{config.FOLDER_NAME}_{datetime.now():%Y-%m-%d}"
|
||||
save_dir.mkdir(parents=True, exist_ok=True)
|
||||
ctx.log(f"保存目录: {save_dir}")
|
||||
|
||||
# ---------- 登录(一次,两种报表共用会话) ----------
|
||||
ctx.progress(3)
|
||||
ctx.log(f"ERP 系统:{'新版' if erp == 'new' else '旧版'}({erp_login.ERP_URLS[erp]})")
|
||||
ok, page = erp_login.erp_login(erp, username, password)
|
||||
if not ok:
|
||||
raise RuntimeError("ERP 登录失败(账号密码错误或网络异常),详见日志")
|
||||
ctx.progress(8)
|
||||
|
||||
# ---------- 执行计划与整体进度(进度 = 8 + 88*已完成单元/总单元) ----------
|
||||
do_31 = mode in (MODE_BOTH, MODE_31)
|
||||
do_32 = mode in (MODE_BOTH, MODE_32)
|
||||
units_31 = len(dates) if do_31 else 0
|
||||
total = units_31 + (1 if do_32 else 0)
|
||||
|
||||
def _report(done_abs):
|
||||
ctx.progress(8 + int(88 * done_abs / max(1, total)))
|
||||
|
||||
saved, failed = [], []
|
||||
try:
|
||||
try:
|
||||
page.set.window.max()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
from . import material_summary, purchase_order
|
||||
|
||||
if do_31:
|
||||
try:
|
||||
ctx.log(f"开始导出物料收发汇总表:仓库 {len(codes)} 个 / 日期 {len(dates)} 档")
|
||||
files31, failed31 = material_summary.run(
|
||||
page, save_dir, org, codes, dates,
|
||||
progress=lambda done_i, _total: _report(done_i))
|
||||
saved += files31
|
||||
failed += [f"物料收发汇总表[{x}]" for x in failed31]
|
||||
except RuntimeError as e:
|
||||
failed.append(f"物料收发汇总表[{e}]")
|
||||
if do_32:
|
||||
_back_home(page, erp) # 报表间回到主界面,保证全局搜索可用
|
||||
if do_32:
|
||||
try:
|
||||
ctx.log(f"开始导出采购订单列表(方案:{scheme})")
|
||||
f32 = purchase_order.run(page, save_dir, scheme,
|
||||
progress=lambda _i, _t: _report(units_31 + 1))
|
||||
if f32:
|
||||
saved.append(f32)
|
||||
else:
|
||||
failed.append("采购订单列表")
|
||||
except RuntimeError as e:
|
||||
failed.append(f"采购订单列表[{e}]")
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
ctx.progress(100)
|
||||
|
||||
# ---------- 汇总 ----------
|
||||
notes = [f"已保存 {len(saved)} 个文件:"] + [f" {p}" for p in saved]
|
||||
if failed:
|
||||
notes.append(f"失败 {len(failed)} 项:{'、'.join(failed)}")
|
||||
summary = f"导出完成(部分失败):成功 {len(saved)} 个,失败 {len(failed)} 项"
|
||||
else:
|
||||
summary = f"导出完成:共 {len(saved)} 个文件 → {save_dir}"
|
||||
return {"summary": summary, "rows": [], "notes": notes}
|
||||
|
||||
|
||||
# ================== 小工具 ==================
|
||||
def _desktop():
|
||||
from .k3_common import get_desktop
|
||||
return get_desktop()
|
||||
|
||||
|
||||
def _back_home(page, erp):
|
||||
"""两种报表连导时回到 K3 主界面(全局搜索入口所在页),保证下个报表可打开。"""
|
||||
try:
|
||||
home = erp_login.ERP_URLS.get(erp, erp_login.ERP_URLS['new'])
|
||||
if erp_login.SUCCESS_KEYWORD not in (page.url or ''):
|
||||
page.get(home)
|
||||
time.sleep(2)
|
||||
except Exception as e:
|
||||
config.log(f"回主界面异常(继续尝试): {e}")
|
||||
|
||||
|
||||
PLUGINS.append(ErpReportExportPlugin())
|
||||
@@ -0,0 +1,43 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""发布打包辅助(开发工具,`_` 前缀运行时不会被插件扫描加载)。
|
||||
|
||||
把本插件压成 dist-plugin/xq0031_xq0032_v<版本>.zip,
|
||||
包根布局与 sb_person_change 一致:plugin.json / 各 .py / ui/ 直接位于 zip 根。
|
||||
排除项:ui-src(前端源码与 node_modules)、__pycache__、debug、本脚本、*.pyc。
|
||||
|
||||
用法(desktop/ 下执行):
|
||||
../.venv/Scripts/python.exe ../plugins/xq0031_xq0032/_pack.py
|
||||
随后发布:
|
||||
.venv\\Scripts\\python.exe -m controlplane.tools.agent_cli publish \
|
||||
dist-plugin\\xq0031_xq0032_v1.0.0.zip --id xq0031_xq0032 --version 1.0.0
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
_HERE = Path(__file__).resolve().parent
|
||||
_OUT_DIR = _HERE.parents[1] / "dist-plugin"
|
||||
_EXCLUDE_DIRS = {"ui-src", "__pycache__", "debug", ".sessions"}
|
||||
_EXCLUDE_FILES = {"_pack.py"}
|
||||
|
||||
|
||||
def main():
|
||||
manifest = json.loads((_HERE / "plugin.json").read_text(encoding="utf-8"))
|
||||
pid, ver = manifest["id"], manifest["version"]
|
||||
if not (_HERE / "ui" / "index.html").is_file():
|
||||
sys.exit("缺少 ui/index.html:请先在 ui-src 下执行 npm install && npm run build")
|
||||
_OUT_DIR.mkdir(exist_ok=True)
|
||||
out = _OUT_DIR / f"{pid}_v{ver}.zip"
|
||||
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||
for p in sorted(_HERE.rglob("*")):
|
||||
rel = p.relative_to(_HERE)
|
||||
if set(rel.parts) & _EXCLUDE_DIRS or p.name in _EXCLUDE_FILES or p.suffix == ".pyc":
|
||||
continue
|
||||
if p.is_file():
|
||||
zf.write(p, str(rel))
|
||||
print(f"已打包: {out}({out.stat().st_size / 1024:.0f} KB)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,39 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""ERP报表导出(xq0031_xq0032)插件配置:默认值与运行参数。
|
||||
|
||||
合并 XQ0031(物料收发汇总表)+ XQ0032(采购订单列表)的固化配置,
|
||||
与 workflows 影刀版各源文件常量保持同源(四方向零依赖,各自演进)。
|
||||
|
||||
个性化配置(账号密码/仓库编码/日期选项等)由插件自带 Vue 界面维护,经
|
||||
webhost /api/plugin-config 落执行机本机,run() 时经 fields 注入;
|
||||
本文件只承载 fields 未传时的兜底默认与运行参数。
|
||||
"""
|
||||
|
||||
# ==================== 1. 业务默认值(fields 未传/留空时的兜底) ====================
|
||||
ORG_NAME = '99.01 重庆金七象供应链管理有限公司' # 查询组织
|
||||
STOCK_CODES_DEFAULT = ['0101010101', '0101010201', '0101020201', '0101030201', '0101040201']
|
||||
DATE_OPTIONS_DEFAULT = ['60D', '30D', '15D', '7D', '3D']
|
||||
SCHEME_NAME = '默认方案(个人)' # 需求32 快捷方案(精确匹配)
|
||||
FOLDER_NAME = '采购计划报表' # 保存目录命名前缀(31/32 同目录)
|
||||
FILE_PREFIX_31 = '物料收发汇总表' # 31 导出文件名前缀
|
||||
FILE_PREFIX_32 = '采购订单列表' # 32 导出文件名前缀
|
||||
|
||||
# ==================== 2. 运行参数(项目规范:全局重试 3 次) ====================
|
||||
RETRY_MAX = 3
|
||||
TIMEOUT = 15 # 元素查找超时(秒)
|
||||
|
||||
# ==================== 3. 日志钩子(print → ctx.log) ====================
|
||||
_log_fn = print
|
||||
|
||||
|
||||
def set_log(fn) -> None:
|
||||
"""插件 run() 启动时把 ctx.log 注入进来,全部模块经 log() 输出。"""
|
||||
global _log_fn
|
||||
_log_fn = fn if fn else print
|
||||
|
||||
|
||||
def log(msg: str) -> None:
|
||||
try:
|
||||
_log_fn(msg)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,163 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""金蝶 K3Cloud(HTML5)ERP 登录模块(xq0031_xq0032 插件内自包含)。
|
||||
|
||||
自 workflows/share/erp_login.py 迁移,插件化改造点:
|
||||
- 账号密码由插件界面配置经 fields 注入(不再读 .env),个性化归属明确;
|
||||
- auto_port 独立浏览器实例:不接管用户已开的浏览器,cookies 天然隔离,
|
||||
确保每次真实登录的就是本次配置的账号(不做 cookies 缓存复用);
|
||||
- print → config.log。
|
||||
|
||||
登录页元素(新旧版一致):
|
||||
用户名输入框 <input id="user" placeholder="用户名">
|
||||
密码输入框 <input id="password" type="password">
|
||||
登录按钮 <button id="btnLogin" class="btnlogin k-button">登录</button>
|
||||
登录成功判定:URL 包含 /k3cloud/html5/dform.aspx。
|
||||
特殊弹窗:登录时若弹出「该帐号已登录在线,确认让对方下线」警告框,自动点确认。
|
||||
"""
|
||||
import time
|
||||
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
from . import config
|
||||
|
||||
# ================== 站点定义(新旧 ERP) ==================
|
||||
ERP_URLS = {
|
||||
'old': 'https://erp.37du.co/k3cloud/html5/index.aspx',
|
||||
'new': 'https://criterion.erp.37du.co/k3cloud/html5/index.aspx',
|
||||
}
|
||||
|
||||
# 登录页元素定位(新旧版元素 id 一致)
|
||||
USER_INPUT = '#user'
|
||||
PWD_INPUT = '#password'
|
||||
LOGIN_BTN = '#btnLogin'
|
||||
# 「该帐号已登录在线」弹窗的确认按钮(蓝色样式 class 固定,id 为动态 UUID)
|
||||
KICK_CONFIRM_BTN = 'css:.k-window .BlueButtonStyle'
|
||||
|
||||
# 登录成功标志:URL 包含该关键字即视为已登录(跳转到默认表单页)
|
||||
SUCCESS_KEYWORD = '/k3cloud/html5/dform.aspx'
|
||||
|
||||
# ================== 运行参数 ==================
|
||||
RETRY_MAX = config.RETRY_MAX # 全局重试次数(项目规范:最多 3 次)
|
||||
TIMEOUT = 10 # 元素等待超时(秒)
|
||||
LOGIN_WAIT = 3 # 点击登录后等待(秒)
|
||||
HEADLESS = False
|
||||
|
||||
|
||||
def _resolve_url(erp):
|
||||
"""把 'old'/'new'/完整URL 统一解析为登录页 URL。"""
|
||||
if erp in ERP_URLS:
|
||||
return ERP_URLS[erp]
|
||||
if erp and erp.lower().startswith('http'):
|
||||
return erp
|
||||
raise ValueError(f"无效的 ERP 标识:{erp},可选 'old'、'new' 或完整登录页 URL")
|
||||
|
||||
|
||||
def _is_login_page(url):
|
||||
"""判断当前 URL 是否仍停留在登录页。"""
|
||||
return 'index.aspx' in (url or '').lower()
|
||||
|
||||
|
||||
def _is_login_success(url):
|
||||
"""登录成功判定:URL 包含 dform.aspx 即视为已登录。"""
|
||||
return SUCCESS_KEYWORD in (url or '')
|
||||
|
||||
|
||||
def _handle_kick_dialog(page):
|
||||
"""处理「该帐号已登录在线,确认让对方下线」弹窗:存在则点击蓝色确认按钮。"""
|
||||
for _ in range(3):
|
||||
btn = page.ele(KICK_CONFIRM_BTN, timeout=2)
|
||||
if not btn:
|
||||
return False
|
||||
try:
|
||||
btn.click()
|
||||
config.log("[ERP登录] 检测到「已登录在线」弹窗,点击确认(让对方下线)")
|
||||
return True
|
||||
except Exception as e:
|
||||
config.log(f"[ERP登录] 点击弹窗确认异常:{e}")
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
def erp_login(erp='new', username='', password='', headless=None):
|
||||
"""
|
||||
登录金蝶 K3Cloud ERP(新旧系统通用,现场真登录)。
|
||||
|
||||
参数:
|
||||
erp 'old' 旧版 erp.37du.co / 'new' 新版 criterion.erp.37du.co / 完整登录页 URL
|
||||
username 用户名(插件界面配置注入,必填)
|
||||
password 密码(插件界面配置注入,必填)
|
||||
|
||||
返回:
|
||||
(success, page) success=True 时 page 为已登录的 ChromiumPage;
|
||||
失败时 page 为 None(浏览器已关闭)。调用方负责成功后的 page.quit()。
|
||||
"""
|
||||
login_url = _resolve_url(erp)
|
||||
username = (username or '').strip()
|
||||
password = password or ''
|
||||
if not (username and password):
|
||||
config.log("[ERP登录] 登录账号/密码缺失(请在插件界面填写并保存配置)")
|
||||
return False, None
|
||||
headless = HEADLESS if headless is None else bool(headless)
|
||||
|
||||
for attempt in range(1, RETRY_MAX + 1):
|
||||
page = None
|
||||
try:
|
||||
config.log(f"[ERP登录] 第 {attempt}/{RETRY_MAX} 次 → {login_url}")
|
||||
co = ChromiumOptions()
|
||||
if headless:
|
||||
co.headless()
|
||||
# auto_port:独立端口 + 独立临时用户目录,不接管用户浏览器、不残留旧登录态
|
||||
co.auto_port(True)
|
||||
co.set_argument('--start-maximized')
|
||||
page = ChromiumPage(co)
|
||||
page.get(login_url)
|
||||
time.sleep(2)
|
||||
|
||||
user = page.ele(USER_INPUT, timeout=TIMEOUT)
|
||||
if not user:
|
||||
config.log("[ERP登录] 找不到用户名输入框")
|
||||
continue
|
||||
user.clear()
|
||||
user.input(username)
|
||||
time.sleep(0.5)
|
||||
# 用户名框是 autocomplete 控件,需按回车关闭弹出的下拉提示框
|
||||
page.actions.key_down('Enter')
|
||||
page.actions.key_up('Enter')
|
||||
time.sleep(0.3)
|
||||
|
||||
pwd = page.ele(PWD_INPUT, timeout=TIMEOUT)
|
||||
if not pwd:
|
||||
config.log("[ERP登录] 找不到密码输入框")
|
||||
continue
|
||||
pwd.clear()
|
||||
pwd.input(password)
|
||||
time.sleep(0.3)
|
||||
|
||||
btn = page.ele(LOGIN_BTN, timeout=TIMEOUT)
|
||||
if not btn:
|
||||
config.log("[ERP登录] 找不到登录按钮")
|
||||
continue
|
||||
btn.click()
|
||||
|
||||
# 登录后轮询:处理「已登录在线」弹窗 + 等待跳转到 dform.aspx
|
||||
for _ in range(6):
|
||||
time.sleep(LOGIN_WAIT)
|
||||
if _is_login_success(page.url):
|
||||
config.log(f"[ERP登录] 登录成功 → {page.url}")
|
||||
return True, page
|
||||
_handle_kick_dialog(page)
|
||||
|
||||
config.log("[ERP登录] 点击登录后未跳转到 dform.aspx(账号密码错误或网络异常)")
|
||||
except Exception as e:
|
||||
config.log(f"[ERP登录] 异常:{e}")
|
||||
|
||||
# 走到这里说明本轮失败,关闭浏览器后重试(成功时在上方已直接 return)
|
||||
if page is not None:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
|
||||
config.log("[ERP登录] 重试 3 次均失败")
|
||||
return False, None
|
||||
@@ -0,0 +1,249 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""K3Cloud HTML5 页面操作公共件(xq0031_xq0032 插件内共享)。
|
||||
|
||||
自 workflows/XQ0031、XQ0032 影刀版迁移的稳定交互原语,两报表共用。
|
||||
K3 现场验证结论(勿随手"优化",均为踩坑后的修复):
|
||||
- 残留窗口会被移到屏幕外,is_displayed 仍 True 但点击无效 → 必须同时校验视口位置
|
||||
- 工具栏/菜单项物理点击只选中文字不触发菜单 → 用 by_js;嵌套悬浮子菜单相反,
|
||||
必须真实鼠标悬浮(move_to 链不能断)
|
||||
- 浏览器断连(PageDisconnectedError)属致命异常,直接上抛,避免被容错吞掉空转
|
||||
"""
|
||||
import shutil
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
from DrissionPage.errors import PageDisconnectedError
|
||||
except Exception:
|
||||
PageDisconnectedError = None
|
||||
|
||||
from . import config
|
||||
|
||||
|
||||
def get_desktop():
|
||||
"""获取真实桌面路径,适配 OneDrive 等重定向的不同电脑。"""
|
||||
try:
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
guid = wintypes.GUID(
|
||||
data1=0xB4BFCC3A, data2=0xDB2C, data3=0x424C,
|
||||
data4=(0xB0, 0x29, 0x7F, 0xE9, 0x9A, 0x87, 0xC6, 0x41))
|
||||
func = ctypes.windll.shell32.SHGetKnownFolderPath
|
||||
func.argtypes = [wintypes.GUID, wintypes.DWORD, wintypes.HANDLE,
|
||||
ctypes.POINTER(ctypes.c_wchar_p)]
|
||||
ptr = ctypes.c_wchar_p()
|
||||
func(ctypes.byref(guid), 0, None, ctypes.byref(ptr))
|
||||
return ptr.value
|
||||
except Exception:
|
||||
return str(Path.home() / 'Desktop')
|
||||
|
||||
|
||||
def is_in_viewport(el, page):
|
||||
"""元素是否真实显示在视口内。K3 残留窗口会被移到屏幕外,此时 is_displayed
|
||||
仍为 True,但其内元素点击无效——必须同时校验位置在视口内。"""
|
||||
try:
|
||||
if not el.states.is_displayed:
|
||||
return False
|
||||
w, h = el.rect.size
|
||||
if w <= 0 or h <= 0:
|
||||
return False
|
||||
x, y = el.rect.location
|
||||
vw, vh = page.run_js(
|
||||
'return [window.innerWidth || document.documentElement.clientWidth,'
|
||||
' window.innerHeight || document.documentElement.clientHeight];')
|
||||
return 0 <= x < vw and 0 <= y < vh
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def click_visible(page, css, timeout=None, by_js=False):
|
||||
"""点击第一个在视口内可见的匹配元素,成功返回 True。浏览器断连等致命异常直接上抛。
|
||||
by_js=True 用于 K3 工具栏/菜单项:物理点击只会选中文字,不触发菜单。"""
|
||||
timeout = config.TIMEOUT if timeout is None else timeout
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
try:
|
||||
for el in page.eles(css):
|
||||
if is_in_viewport(el, page):
|
||||
el.click(by_js=True) if by_js else el.click()
|
||||
return True
|
||||
except Exception as e:
|
||||
if PageDisconnectedError is not None and isinstance(e, PageDisconnectedError):
|
||||
raise
|
||||
time.sleep(0.5)
|
||||
return False
|
||||
|
||||
|
||||
def ele_visible(page, css, timeout=1):
|
||||
"""元素存在、且在视口内可见才算命中(K3 过滤窗口关闭后 DOM 里仍残留隐藏/屏幕外节点)。"""
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
try:
|
||||
for el in page.eles(css):
|
||||
if is_in_viewport(el, page):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.3)
|
||||
return False
|
||||
|
||||
|
||||
def press_enter(page):
|
||||
"""模拟按一次回车键。"""
|
||||
page.actions.key_down('Enter')
|
||||
page.actions.key_up('Enter')
|
||||
|
||||
|
||||
def press_enter_in(el, page):
|
||||
"""向指定元素直接发送回车(元素级,避免页面焦点漂移导致回车无效)。"""
|
||||
try:
|
||||
from DrissionPage.common import Keys
|
||||
el.input(Keys.ENTER)
|
||||
except Exception:
|
||||
press_enter(page)
|
||||
|
||||
|
||||
def visible_titles(page):
|
||||
"""返回所有可见窗口标题文本列表。"""
|
||||
titles = []
|
||||
try:
|
||||
for t in page.eles('css:.k-window-title'):
|
||||
try:
|
||||
if t.states.is_displayed:
|
||||
titles.append(t.text)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
return titles
|
||||
|
||||
|
||||
def close_window_by_title(page, title, timeout=3, tag=''):
|
||||
"""物理点击关闭标题包含关键字的 k-window 弹窗(K3 下载窗口等残留,关闭按钮 by_js 不触发)。
|
||||
用包含匹配:实际标题可能是「文件下载」或「文档下载」,避免因标题差异关不掉。"""
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
for w in page.eles('css:.k-window'):
|
||||
try:
|
||||
if not w.states.is_displayed:
|
||||
continue
|
||||
t = w.ele('css:.k-window-title', timeout=0.3)
|
||||
if t is None or title not in (t.text or ''):
|
||||
continue
|
||||
btn = w.ele('css:.k-window-actions .k-i-close', timeout=0.5)
|
||||
if btn is None:
|
||||
return False
|
||||
try:
|
||||
btn.click()
|
||||
except Exception:
|
||||
btn.click(by_js=True)
|
||||
time.sleep(0.3)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
return False
|
||||
|
||||
|
||||
def reset_filter_state(page, tag='', wait_query=False):
|
||||
"""重试前清理脏界面状态:按 ESC 关闭残留的弹层/过滤窗口,兜底点各面板「取消」按钮。
|
||||
wait_query=True(需求31):若查询正在进行先等其结束(ESC 会打断正常查询)。"""
|
||||
if wait_query:
|
||||
end = time.time() + 120
|
||||
while time.time() < end:
|
||||
if not any('查询进度' in x for x in visible_titles(page)):
|
||||
break
|
||||
time.sleep(1)
|
||||
for _ in range(2):
|
||||
try:
|
||||
page.actions.key_down('ESC')
|
||||
page.actions.key_up('ESC')
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
click_visible(page, 'css:[id*="FBTNCANCEL_c"]', timeout=1)
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def download_file(page, save_dir, new_name, tag=''):
|
||||
"""点「下载」按钮 → 等文件落盘到保存目录。
|
||||
做法:把浏览器默认下载目录直接指到 save_dir,再点「下载」按钮(target=_blank 也会下载到该目录),
|
||||
然后盯着文件夹等新文件出现且大小稳定(下载完成),不依赖 DrissionPage 的任务捕获,避免静默卡住。"""
|
||||
save_dir = Path(save_dir)
|
||||
try:
|
||||
save_dir.mkdir(parents=True, exist_ok=True)
|
||||
page.set.download_path(str(save_dir))
|
||||
page.set.when_download_file_exists('overwrite')
|
||||
except Exception as e:
|
||||
config.log(f'{tag} 设置下载目录异常: {e}')
|
||||
before_names = {b.name for b in save_dir.glob('*')} if save_dir.exists() else set()
|
||||
|
||||
# 找可见的「下载」按钮
|
||||
dl = None
|
||||
end = time.time() + config.TIMEOUT
|
||||
while time.time() < end:
|
||||
for el in page.eles('css:[id*="FDOWNLOAD_c"]'):
|
||||
try:
|
||||
if el.states.is_displayed:
|
||||
dl = el
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
if dl:
|
||||
break
|
||||
time.sleep(0.5)
|
||||
if not dl:
|
||||
config.log(f'{tag} 找不到下载按钮')
|
||||
return False
|
||||
config.log(f'{tag} 点击下载按钮...')
|
||||
try:
|
||||
dl.click()
|
||||
except Exception:
|
||||
dl.click(by_js=True)
|
||||
|
||||
# 等新文件出现且大小连续两次不变(下载完成)
|
||||
config.log(f'{tag} 等待文件下载完成...')
|
||||
last_size, last_name = -1, None
|
||||
end = time.time() + 300
|
||||
while time.time() < end:
|
||||
new_files = [f for f in save_dir.glob('*')
|
||||
if f.is_file() and f.name not in before_names]
|
||||
if new_files:
|
||||
f = max(new_files, key=lambda x: x.stat().st_mtime)
|
||||
try:
|
||||
s = f.stat().st_size
|
||||
except Exception:
|
||||
s = 0
|
||||
if (f.suffix not in ('.crdownload', '.tmp', '.part')
|
||||
and s > 0 and s == last_size and f.name == last_name):
|
||||
dst = _save_as(f, save_dir / new_name)
|
||||
config.log(f'{tag} 已保存: {dst}')
|
||||
close_window_by_title(page, '文件下载', tag=tag) # 只关下载窗口,其余残留不主动关
|
||||
return True
|
||||
last_size, last_name = s, f.name
|
||||
time.sleep(1)
|
||||
|
||||
# 兜底:超时但确有新文件也尝试落名
|
||||
new_files = [f for f in save_dir.glob('*')
|
||||
if f.is_file() and f.name not in before_names
|
||||
and f.suffix not in ('.crdownload', '.tmp', '.part')]
|
||||
for f in new_files:
|
||||
dst = _save_as(f, save_dir / new_name)
|
||||
config.log(f'{tag} 已保存: {dst}')
|
||||
close_window_by_title(page, '文件下载', tag=tag)
|
||||
return True
|
||||
config.log(f'{tag} 下载失败/超时')
|
||||
return False
|
||||
|
||||
|
||||
def _save_as(src, dst):
|
||||
"""把下载产物重命名/移动到目标名;移动失败则原样保留并返回实际路径。"""
|
||||
if src == dst:
|
||||
return src
|
||||
try:
|
||||
if dst.exists():
|
||||
dst.unlink()
|
||||
shutil.move(str(src), str(dst))
|
||||
return dst
|
||||
except Exception:
|
||||
return src
|
||||
@@ -0,0 +1,673 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""需求31 - 金蝶 K3Cloud ERP「物料收发汇总表」自动导出(xq0031_xq0032 插件内模块)。
|
||||
|
||||
自 workflows/XQ0031 material_summary_export.py 迁移:
|
||||
搜索打开报表 → 设置组织/日期/仓库编码 → 查询 → 引出所有页 → 下载保存。
|
||||
组织/仓库编码/日期选项由插件界面配置经 run() 参数注入;交互逻辑与影刀版保持同源。
|
||||
"""
|
||||
import json
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from . import config
|
||||
from . import k3_common as kc
|
||||
|
||||
TAG = '[物料收发汇总表]'
|
||||
|
||||
|
||||
# ================== 工具函数 ==================
|
||||
def resolve_dates(option):
|
||||
"""解析单个日期选项 → (开始日期, 结束日期, 文件标签)。
|
||||
支持:
|
||||
'60D' 今天往前推 N 天(60/30/15/7/3)
|
||||
('2026-01-01', '2026-09-15') 元组/列表自定义起止
|
||||
'2026-01-01~2026-09-15' 字符串自定义起止(~ , ,空格分隔均可)"""
|
||||
if isinstance(option, (list, tuple)):
|
||||
if len(option) == 2:
|
||||
begin, end = str(option[0]), str(option[1])
|
||||
return begin, end, f'{begin}_{end}'
|
||||
raise ValueError(f'自定义日期需为(开始, 结束)两项: {option!r}')
|
||||
s = str(option).strip()
|
||||
for sep in ('~', ',', ',', ' '):
|
||||
if sep in s:
|
||||
parts = [p.strip() for p in s.split(sep) if p.strip()]
|
||||
if len(parts) == 2:
|
||||
return parts[0], parts[1], f'{parts[0]}_{parts[1]}'
|
||||
raise ValueError(f'自定义日期需为 开始~结束 两项: {option!r}')
|
||||
days = int(s.rstrip('Dd'))
|
||||
end = datetime.now().date()
|
||||
begin = end - timedelta(days=days)
|
||||
return begin.isoformat(), end.isoformat(), str(option)
|
||||
|
||||
|
||||
def _wait_window_title(page, keyword, timeout=None):
|
||||
"""等待出现标题包含关键字的窗口,返回 True/False。"""
|
||||
timeout = config.TIMEOUT if timeout is None else timeout
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
t = page.ele('css:.k-window-title', timeout=1)
|
||||
if t and keyword in t.text:
|
||||
return True
|
||||
time.sleep(0.5)
|
||||
return False
|
||||
|
||||
|
||||
# ================== 报表操作 ==================
|
||||
def _open_report(page):
|
||||
"""点击全局搜索 → 输入「物料收发汇总表」→ 回车 → 等待过滤界面出现。"""
|
||||
if not kc.click_visible(page, 'css:.kd-fullsearch-searchicon', timeout=10):
|
||||
config.log(f'{TAG} 找不到全局搜索图标')
|
||||
return False
|
||||
time.sleep(1)
|
||||
sbox = page.ele('css:.kd-appplat-searchinput', timeout=5)
|
||||
if not sbox:
|
||||
config.log(f'{TAG} 找不到搜索输入框')
|
||||
return False
|
||||
sbox.clear()
|
||||
sbox.input('物料收发汇总表')
|
||||
time.sleep(0.3)
|
||||
kc.press_enter(page)
|
||||
time.sleep(1.5)
|
||||
|
||||
# 等待过滤界面(含组织字段 FSTOCKORGID)出现,限定在 .k-window 弹窗内
|
||||
end = time.time() + 40
|
||||
while time.time() < end:
|
||||
if kc.ele_visible(page, 'css:.k-window [id*="FSTOCKORGID"]', timeout=1):
|
||||
config.log(f'{TAG} 报表过滤界面已打开')
|
||||
return True
|
||||
time.sleep(0.5)
|
||||
|
||||
# 兜底:点击搜索结果中的「物料收发汇总表」菜单项
|
||||
config.log(f'{TAG} 未自动打开,尝试点击搜索结果')
|
||||
els = page.eles('xpath://*[contains(text(), "物料收发汇总表")]')
|
||||
for el in els:
|
||||
try:
|
||||
if el.states.is_displayed and not el.closest('css:.k-window-titlebar'):
|
||||
el.click()
|
||||
time.sleep(2)
|
||||
if kc.ele_visible(page, 'css:.k-window [id*="FSTOCKORGID"]', timeout=1):
|
||||
config.log(f'{TAG} 报表过滤界面已打开')
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _open_filter(page):
|
||||
"""确保过滤界面打开:
|
||||
1. 先关闭「文件下载」窗口(K3 下载完成后残留、挡在最上层)
|
||||
2. 若过滤窗口已开(.k-window 内组织字段可见)→ 直接复用
|
||||
3. 未开 → 点主报表「过滤」按钮重开
|
||||
注意:过滤按钮真实 id 为 BILLMENU_TOOLBAR-tbnFilter(tbnFilter,非 tbFilter)。"""
|
||||
kc.close_window_by_title(page, '文件下载', tag=TAG)
|
||||
if kc.ele_visible(page, 'css:.k-window [id*="FSTOCKORGID"]', timeout=2):
|
||||
return True
|
||||
# 点「过滤」重开(by_js 避免 K3 菜单物理点击选中文字)
|
||||
if kc.click_visible(page, 'css:[id*="BILLMENU_TOOLBAR-tbnFilter"]', by_js=True):
|
||||
time.sleep(1.5)
|
||||
return kc.ele_visible(page, 'css:.k-window [id*="FSTOCKORGID"]', timeout=5)
|
||||
return False
|
||||
|
||||
|
||||
def _set_org(page, org):
|
||||
"""确保过滤界面组织为指定值;不是则打开多选列表重新选择(只保留目标组织)。
|
||||
探针确认的结构:li.k-item > input.k-checkboxItem[name=组织名] + button.k-checkbox-button。"""
|
||||
# 统一限定在 .k-window 内,避免读到主界面残留的同 id 节点
|
||||
disp = page.ele('css:.k-window [id*="FSTOCKORGID"] .ui-poplistedit-displayname', timeout=config.TIMEOUT)
|
||||
if disp:
|
||||
title = disp.attr('title') or ''
|
||||
if title.strip() == org:
|
||||
config.log(f'{TAG} 组织已是: {org}')
|
||||
return True
|
||||
|
||||
if not kc.click_visible(page, 'css:.k-window [id*="FSTOCKORGID-EDITOR"] .kd-editor-btn'):
|
||||
config.log(f'{TAG} 找不到组织下拉按钮')
|
||||
return False
|
||||
time.sleep(1)
|
||||
# 组织多选列表弹层(_dataListdiv)独立挂载,不限定窗口;
|
||||
# 页面可能残留上次中断留下的隐藏弹层,必须取当前可见的那一个
|
||||
dl = None
|
||||
for cand in page.eles('css:[id*="FSTOCKORGID-EDITOR_dataListdiv"]', timeout=config.TIMEOUT):
|
||||
try:
|
||||
if cand.states.is_displayed:
|
||||
dl = cand
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
if dl is None:
|
||||
config.log(f'{TAG} 组织多选列表未出现')
|
||||
return False
|
||||
|
||||
# 输入关键字过滤列表(需回车才会过滤出结果)
|
||||
sbox = dl.ele('css:.kd-list-search-container input', timeout=5)
|
||||
if sbox:
|
||||
sbox.clear()
|
||||
sbox.input(org.split(' ', 1)[-1])
|
||||
kc.press_enter_in(sbox, page)
|
||||
time.sleep(1)
|
||||
|
||||
def _visible_lis():
|
||||
"""仅返回当前可见的选项行(过滤后隐藏行无位置尺寸,不可操作)。"""
|
||||
out = []
|
||||
for li in dl.eles('css:li.k-item'):
|
||||
try:
|
||||
if li.states.is_displayed:
|
||||
out.append(li)
|
||||
except Exception:
|
||||
pass
|
||||
return out
|
||||
|
||||
def _toggle(li, want):
|
||||
"""want=True 勾选 / False 取消勾选;实际发生点击返回 True。"""
|
||||
chk = li.ele('css:input.k-checkboxItem', timeout=0.5)
|
||||
btn = li.ele('css:button.k-checkbox-button', timeout=0.5)
|
||||
if not chk or not btn:
|
||||
return False
|
||||
name = chk.attr('name') or ''
|
||||
try:
|
||||
checked = bool(chk.run_js('return this.checked;'))
|
||||
except Exception:
|
||||
return False
|
||||
if want == checked:
|
||||
return False
|
||||
try:
|
||||
btn.click()
|
||||
time.sleep(0.3)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
# 勾选目标项
|
||||
target_found = False
|
||||
for li in _visible_lis():
|
||||
chk = li.ele('css:input.k-checkboxItem', timeout=0.5)
|
||||
if chk and org in (chk.attr('name') or ''):
|
||||
target_found = True
|
||||
_toggle(li, True)
|
||||
|
||||
# 清空搜索恢复全量列表,取消其它已勾选项
|
||||
if sbox:
|
||||
sbox.clear()
|
||||
kc.press_enter_in(sbox, page)
|
||||
time.sleep(1)
|
||||
for li in _visible_lis():
|
||||
chk = li.ele('css:input.k-checkboxItem', timeout=0.5)
|
||||
if chk and org not in (chk.attr('name') or ''):
|
||||
_toggle(li, False)
|
||||
|
||||
if not target_found:
|
||||
config.log(f'{TAG} 组织中未找到: {org}')
|
||||
return False
|
||||
|
||||
# 点弹层底部「确定」:只点一次。先弹层内找,找不到再全局找可见的兜底
|
||||
ok = kc.click_visible(dl, 'css:.kd-multiSelectOK')
|
||||
if not ok:
|
||||
ok = kc.click_visible(page, 'css:.kd-multiSelectOK')
|
||||
if not ok:
|
||||
config.log(f'{TAG} 找不到组织多选确定按钮')
|
||||
return False
|
||||
time.sleep(1)
|
||||
# 回读确认设置生效,防止点了确定但值没落上(限定 .k-window 内)
|
||||
disp = page.ele('css:.k-window [id*="FSTOCKORGID"] .ui-poplistedit-displayname', timeout=config.TIMEOUT)
|
||||
if disp and (disp.attr('title') or '').strip() == org:
|
||||
config.log(f'{TAG} 组织已设置为: {org}')
|
||||
return True
|
||||
config.log(f'{TAG} 组织设置未生效,回读不一致: {org}')
|
||||
return False
|
||||
|
||||
|
||||
def _set_datepicker(page, key, date):
|
||||
"""在 .k-window 过滤窗口内定位日期字段的 Kendo datepicker 并设值。
|
||||
key: 'FBEGINDATE' / 'FENDDATE'。
|
||||
K3 必须「触发日历组件」才会刷新绑定的过滤值(直接调控件 value() 无效):
|
||||
方式一 真实输入日期文本 + 回车提交(Kendo 解析输入并触发 change)
|
||||
方式二 打开日历面板 → 导航到目标月份 → 点选目标日期(触发 Kendo select)
|
||||
每次设值后回读 input 显示值验证;失败返回 False 由外层重试,绝不假成功。"""
|
||||
end = time.time() + config.TIMEOUT
|
||||
last = ''
|
||||
while time.time() < end:
|
||||
for el in page.eles(f'css:.k-window [id*="{key}-EDITOR_c"]', timeout=2):
|
||||
# 只处理真正持有 kendoDatePicker 控件的节点
|
||||
try:
|
||||
if not el.run_js(
|
||||
"return !!(window.jQuery && window.jQuery(this).data('kendoDatePicker'));"):
|
||||
continue
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
# ---- 方式一:真实输入 + 回车 ----
|
||||
try:
|
||||
el.click()
|
||||
time.sleep(0.15)
|
||||
el.clear()
|
||||
el.input(date)
|
||||
time.sleep(0.2)
|
||||
kc.press_enter_in(el, page)
|
||||
time.sleep(0.3)
|
||||
val = el.run_js("return this.value || '';")
|
||||
if date in str(val):
|
||||
config.log(f'{TAG} {key} 输入+回车生效(input显示 {val})')
|
||||
return True
|
||||
last = f'输入+回车 input={val!r}'
|
||||
except Exception as e:
|
||||
last = f'输入+回车异常: {e}'
|
||||
|
||||
# ---- 方式二:打开日历点选目标日期(触发组件刷新)----
|
||||
try:
|
||||
r = el.run_js("""
|
||||
var k = window.jQuery && window.jQuery(this).data('kendoDatePicker');
|
||||
if (!k) { return JSON.stringify({ok:false, why:'nok'}); }
|
||||
var y = +arguments[0], m = +arguments[1], d = +arguments[2];
|
||||
var dt = new Date(y, m - 1, d);
|
||||
k.open();
|
||||
if (k.calendar) { k.calendar.navigate(dt); }
|
||||
var cal = (k.calendar && k.calendar.element())
|
||||
|| window.jQuery('.k-calendar:visible').last();
|
||||
var hit = null;
|
||||
cal.find('td').each(function () {
|
||||
var $td = window.jQuery(this);
|
||||
if ($td.hasClass('k-other-month') || $td.hasClass('k-state-other-month')) return;
|
||||
var $a = $td.find('a.k-link');
|
||||
var txt = $a.length ? $a.text() : $td.text();
|
||||
if (parseInt(txt, 10) === d) hit = $a.length ? $a : $td;
|
||||
});
|
||||
if (hit) { hit.click(); }
|
||||
var v = k.value(), s = '';
|
||||
if (v) {
|
||||
var mo = v.getMonth() + 1, da = v.getDate();
|
||||
s = v.getFullYear() + '-' + (mo < 10 ? '0' + mo : mo)
|
||||
+ '-' + (da < 10 ? '0' + da : da);
|
||||
}
|
||||
return JSON.stringify({ok: !!hit, set: s, input: this.value || ''});
|
||||
""", *date.split('-'))
|
||||
try:
|
||||
r = json.loads(r) if isinstance(r, str) else r
|
||||
except Exception:
|
||||
r = {'ok': False}
|
||||
if r.get('ok') and date in (r.get('set') or ''):
|
||||
config.log(f'{TAG} {key} 日历点选生效(input显示 {r.get("input")})')
|
||||
return True
|
||||
last = f'日历点选 {r}'
|
||||
except Exception as e:
|
||||
last = f'日历点选异常: {e}'
|
||||
time.sleep(0.5)
|
||||
config.log(f'{TAG} {key} 日期设置失败,最后回读: {last}')
|
||||
return False
|
||||
|
||||
|
||||
def _set_date(page, begin, end):
|
||||
"""设置起始/结束日期(Kendo datepicker),限定在 .k-window 过滤窗口内。"""
|
||||
if not _set_datepicker(page, 'FBEGINDATE', begin):
|
||||
config.log(f'{TAG} 起始日期设置失败')
|
||||
return False
|
||||
if not _set_datepicker(page, 'FENDDATE', end):
|
||||
config.log(f'{TAG} 结束日期设置失败')
|
||||
return False
|
||||
config.log(f'{TAG} 日期: {begin} ~ {end}')
|
||||
return True
|
||||
|
||||
|
||||
def _click_add_row(page):
|
||||
"""点击仓库过滤面板「新增行」。
|
||||
全局 li.k-link.kdFilterAdd 会同时匹配「主报表过滤」+「仓库过滤」两个面板,
|
||||
原实现总点到主过滤那个(其行数不增加导致误判失败)。因此必须限定在仓库过滤
|
||||
容器(id 含 FBeginStockId_Filter)内定位。物理点击只会选中文字,改用 JS click 触发。"""
|
||||
for css in (
|
||||
'xpath://li[contains(@class,"kdFilterAdd") and ancestor::div[contains(@id,"FBeginStockId_Filter")]]',
|
||||
'css:[id*="FBeginStockId_Filter-FBATCHFILTERGRID_ENTRYBAR-tbAddRow"]',
|
||||
):
|
||||
# 直接取单个元素命中即点,避免 eles 遍历整页拖慢
|
||||
el = page.ele(css, timeout=2)
|
||||
if el is not None:
|
||||
try:
|
||||
if el.states.is_displayed:
|
||||
el.click(by_js=True)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _row_tr(v):
|
||||
"""上溯到包含该值输入框的条件行 <tr>(一个过滤条件一行,内含逻辑/字段/比较/值)。"""
|
||||
node = v
|
||||
for _ in range(8):
|
||||
try:
|
||||
node = node.parent()
|
||||
except Exception:
|
||||
break
|
||||
if node is not None and node.tag == 'tr':
|
||||
return node
|
||||
return None
|
||||
|
||||
|
||||
def _ensure_logic_or(page, v):
|
||||
"""把指定值输入框所在行的逻辑下拉制为「或者」(OR)。
|
||||
多个仓库编码之间需为或关系;行内逻辑下拉类名含 _PART_Logic_listbox,选项 并且/或者。"""
|
||||
tr = _row_tr(v)
|
||||
if tr is None:
|
||||
return False
|
||||
lg = tr.ele('css:span[role="listbox"][aria-owns*="_PART_Logic_listbox"]', timeout=2)
|
||||
if lg is None:
|
||||
return False
|
||||
try:
|
||||
cur = lg.ele('css:.k-input', timeout=1)
|
||||
if cur and cur.text.strip() == '或者':
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
lg.ele('css:.k-select', timeout=2).click()
|
||||
time.sleep(0.3)
|
||||
lb = page.ele('#' + lg.attr('aria-owns'), timeout=2)
|
||||
if lb is None:
|
||||
return False
|
||||
for it in lb.eles('css:li', timeout=2):
|
||||
try:
|
||||
if it.text.strip() == '或者':
|
||||
it.click()
|
||||
time.sleep(0.2)
|
||||
return True
|
||||
except Exception:
|
||||
continue
|
||||
except Exception as e:
|
||||
config.log(f'{TAG} 设置逻辑为或者失败: {e}')
|
||||
return False
|
||||
return False
|
||||
|
||||
|
||||
def _diag_stock_btn(page):
|
||||
"""仓库搜索按钮找不到时输出诊断信息,定位是过滤窗口没开还是按钮不可见。"""
|
||||
try:
|
||||
wins = [t.text for t in page.eles('css:.k-window-title') if t.states.is_displayed]
|
||||
config.log(f' [诊断] 当前可见窗口标题: {wins}')
|
||||
c = page.ele('css:[id*="FBEGINSTOCKID-EDITOR"]', timeout=1)
|
||||
config.log(f' [诊断] FBEGINSTOCKID-EDITOR 容器存在={bool(c)}'
|
||||
f' 可见={c.states.is_displayed if c else "-"}')
|
||||
btns = page.eles('css:[id*="FBEGINSTOCKID"] .kd-editor-btn')
|
||||
vis = 0
|
||||
for b in btns:
|
||||
try:
|
||||
if b.states.is_displayed:
|
||||
vis += 1
|
||||
except Exception:
|
||||
pass
|
||||
config.log(f' [诊断] FBEGINSTOCKID 内 .kd-editor-btn 总数={len(btns)} 可见={vis}')
|
||||
org_css = 'css:.k-window [id*="FSTOCKORGID"]'
|
||||
config.log(f' [诊断] 过滤窗口内(.k-window) FSTOCKORGID 可见节点: '
|
||||
f'{kc.ele_visible(page, org_css, timeout=1)}')
|
||||
except Exception as e:
|
||||
config.log(f' [诊断] 异常: {e}')
|
||||
|
||||
|
||||
def _submit_query(page, with_date=None):
|
||||
"""点主过滤界面「确定」触发查询。with_date 传 (begin, end) 时先重设日期防覆盖。
|
||||
注意:[id*="_Filter-FBTNOK_c"] 也会命中仓库过滤面板的 FBeginStockId_Filter-FBTNOK_c,
|
||||
用 :not 排除 + .k-window 限定,防止误点(含主界面残留节点)。
|
||||
查询是否真被受理交给 _wait_progress(「查询进度」窗口是最可靠信号)。"""
|
||||
if with_date:
|
||||
if not _set_date(page, *with_date):
|
||||
config.log(f'{TAG} 提交前日期重设失败')
|
||||
return False
|
||||
if not kc.click_visible(page, 'css:.k-window [id*="_Filter-FBTNOK_c"]:not([id*="FBeginStockId"])'):
|
||||
config.log(f'{TAG} 找不到主过滤界面确定按钮')
|
||||
return False
|
||||
config.log(f'{TAG} 已提交查询')
|
||||
return True
|
||||
|
||||
|
||||
def _set_stock_codes(page, codes, begin, end):
|
||||
"""仓库编码:点搜索 → 点过滤 → 逐行新增输入(或关系)→ 确定 → 退出 → 主界面确定触发查询。
|
||||
每行结构:括号 + 逻辑(或) + 字段(基本信息-编码) + 比较(等于) + 值(输入后回车查询)。
|
||||
新增行后填仓库编码(一行一个),并把每行逻辑设为「或者」(OR) 保证多仓库为或关系。
|
||||
提交查询(点主过滤确定)前重设一次日期:仓库面板操作过程可能把过滤条件重置为默认。"""
|
||||
if not codes:
|
||||
return False
|
||||
# 1. 点仓库编码搜索按钮,打开仓库列表窗口(限定 .k-window 过滤窗口内)
|
||||
if not kc.click_visible(page, 'css:.k-window [id*="FBEGINSTOCKID-EDITOR"] .kd-editor-btn'):
|
||||
config.log(f'{TAG} 找不到仓库编码搜索按钮')
|
||||
_diag_stock_btn(page)
|
||||
return False
|
||||
time.sleep(1.5)
|
||||
# 2. 点「过滤」打开过滤面板
|
||||
if not kc.click_visible(page, 'css:[id*="FBeginStockId-BILLMENU_TOOLBAR-tbFilter"]'):
|
||||
config.log(f'{TAG} 找不到过滤按钮')
|
||||
return False
|
||||
time.sleep(1)
|
||||
|
||||
# 3. 逐行新增输入仓库编码,并将每行逻辑设为「或者」
|
||||
val_css = 'css:[id*="FBeginStockId_Filter-FFILTERGRID"] input[placeholder*="请输入关键字"]'
|
||||
for i, code in enumerate(codes):
|
||||
# 快捷过滤网格初始为空(无默认行),每行都得先「新增行」再填值
|
||||
vs = page.eles(val_css)
|
||||
if len(vs) <= i:
|
||||
added = False
|
||||
for _ in range(3):
|
||||
if _click_add_row(page):
|
||||
time.sleep(0.8)
|
||||
if len(page.eles(val_css)) > i:
|
||||
added = True
|
||||
break
|
||||
if not added:
|
||||
config.log(f'{TAG} 点击新增行失败(第{i + 1}行,当前值输入框{len(vs)}个)')
|
||||
return False
|
||||
vs = page.eles(val_css)
|
||||
config.log(f'{TAG} 当前过滤值输入框数: {len(vs)}')
|
||||
v = vs[i] if len(vs) > i else None
|
||||
if not v:
|
||||
config.log(f'{TAG} 找不到第{i + 1}行过滤值输入框')
|
||||
return False
|
||||
v.clear()
|
||||
v.input(code)
|
||||
kc.press_enter_in(v, page) # 回车直接发给输入框,触发查询确认
|
||||
time.sleep(0.8)
|
||||
_ensure_logic_or(page, v) # 保证该行逻辑为「或者」
|
||||
config.log(f'{TAG} 仓库条件行{i + 1}: {code}(逻辑或)')
|
||||
|
||||
# 4. 过滤面板内「确定」
|
||||
if not kc.click_visible(page, 'css:[id*="FBeginStockId_Filter-FBTNOK_c"]'):
|
||||
config.log(f'{TAG} 找不到过滤面板确定按钮')
|
||||
return False
|
||||
time.sleep(0.8)
|
||||
# 5. 「退出」关闭仓库过滤窗口
|
||||
kc.click_visible(page, 'css:[id*="FBeginStockId-BILLMENU_TOOLBAR-tbClose"]', timeout=8)
|
||||
time.sleep(0.8)
|
||||
# 6. 提交查询(提交前重设日期防仓库面板操作覆盖)
|
||||
return _submit_query(page, (begin, end))
|
||||
|
||||
|
||||
def _wait_progress(page, timeout=300):
|
||||
"""等待「查询进度」窗口出现并消失(遍历所有窗口标题)。
|
||||
- 进度窗口出现但超时不消失 → 返回 False(查询失败/卡死,防止把旧报表当本次结果)
|
||||
- 全程未出现进度窗口 → 报表网格已渲染且连续 3 秒稳定视为快速完成(兜底)
|
||||
- 进度窗口消失后需连续 3 秒无进度窗口才算结束(防分阶段查询误判)"""
|
||||
end = time.time() + timeout
|
||||
appeared = False
|
||||
stable = 0
|
||||
while time.time() < end:
|
||||
in_progress = any('查询进度' in x for x in kc.visible_titles(page))
|
||||
if in_progress:
|
||||
if not appeared:
|
||||
appeared = True
|
||||
config.log(f'{TAG} 查询进度中,等待完成...')
|
||||
stable = 0
|
||||
elif appeared:
|
||||
stable += 1
|
||||
if stable >= 3:
|
||||
config.log(f'{TAG} 查询完成')
|
||||
time.sleep(2) # 缓冲:数据渲染
|
||||
return True
|
||||
else:
|
||||
# 进度窗口未出现:网格已渲染且稳定视为快速完成(兜底)
|
||||
if kc.ele_visible(page, 'css:.k-grid', timeout=1):
|
||||
stable += 1
|
||||
if stable >= 3:
|
||||
config.log(f'{TAG} 查询完成(进度窗口未出现)')
|
||||
return True
|
||||
else:
|
||||
stable = 0
|
||||
time.sleep(1)
|
||||
config.log(f'{TAG} 查询进度超时未结束'
|
||||
if appeared else f'{TAG} 未检测到查询进度且报表未渲染')
|
||||
return False
|
||||
|
||||
|
||||
def _export_all_pages(page):
|
||||
"""选项 → 引出(真实鼠标悬浮展开子菜单)→ 引出所有页。
|
||||
现场结论:物理点击内容 span 只会『全选文字』不触发菜单;JS click 又触发不了
|
||||
K3 的悬浮式嵌套子菜单。故全程用 page.actions 的真实鼠标 move_to(悬浮,不点击文字),
|
||||
让子菜单展开后用 move_to+click 点中「引出所有页」;不点 span 文本,避免全选。
|
||||
注意:必须复用同一个 ac=page.actions,保证光标位置连续(悬浮链不中断子菜单不收起)。"""
|
||||
ac = page.actions
|
||||
|
||||
def _clickable(span):
|
||||
"""内容 span 的父级可点击元素(a/li),避免点到文本被『全选文字』。"""
|
||||
try:
|
||||
a = span.closest('css:a')
|
||||
if a is not None and a.tag.lower() == 'a' and a.states.is_displayed:
|
||||
return a
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
li = span.closest('css:li')
|
||||
if li is not None and li.states.is_displayed:
|
||||
return li
|
||||
except Exception:
|
||||
pass
|
||||
return span
|
||||
|
||||
# 1. 点「选项」打开配置菜单(点其 a/li,避开文本)
|
||||
opt = page.ele('css:span[id*="BILLMENU_TOOLBAR-tbParamList"]', timeout=5)
|
||||
if opt is None or not opt.states.is_displayed:
|
||||
opt = page.ele('css:[id*="BILLMENU_TOOLBAR-tbParamList"]', timeout=5)
|
||||
if opt is None or not opt.states.is_displayed:
|
||||
config.log(f'{TAG} 找不到选项按钮')
|
||||
return False
|
||||
try:
|
||||
ac.move_to(_clickable(opt)).click()
|
||||
except Exception:
|
||||
try:
|
||||
opt.click(by_js=True)
|
||||
except Exception:
|
||||
config.log(f'{TAG} 点选项失败')
|
||||
return False
|
||||
time.sleep(1.2)
|
||||
|
||||
# 2. 定位「引出」(splitbutton)
|
||||
split = page.ele('css:span[id*="BILLMENU_TOOLBAR-tbSplitExport"]', timeout=5)
|
||||
if split is None or not split.states.is_displayed:
|
||||
split = page.ele('css:[id*="BILLMENU_TOOLBAR-tbSplitExport"]', timeout=5)
|
||||
if split is None or not split.states.is_displayed:
|
||||
config.log(f'{TAG} 找不到导出(引出)按钮')
|
||||
return False
|
||||
|
||||
def _trigger():
|
||||
"""悬浮目标:优先右箭头(悬浮开子菜单),无箭头则悬浮整体。"""
|
||||
try:
|
||||
ar = split.parent().ele('css:span.k-icon', timeout=1)
|
||||
if ar is not None and ar.states.is_displayed:
|
||||
return ar
|
||||
except Exception:
|
||||
pass
|
||||
return _clickable(split)
|
||||
|
||||
trigger = _trigger()
|
||||
|
||||
# 3. 悬浮展开「引出所有页」子菜单
|
||||
target = None
|
||||
for _ in range(4):
|
||||
try:
|
||||
ac.move_to(trigger) # 真实鼠标悬浮到右箭头,子菜单展开
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1.0)
|
||||
t = page.ele('css:span[id*="BILLMENU_TOOLBAR-tbButtonExportAllPage"]', timeout=2)
|
||||
if t is not None and t.states.is_displayed:
|
||||
target = t
|
||||
break
|
||||
if target is None or not target.states.is_displayed:
|
||||
# 悬浮未展开 → 点击箭头切换(部分版本点击才弹出)
|
||||
for _ in range(3):
|
||||
try:
|
||||
trigger.click()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
t = page.ele('css:span[id*="BILLMENU_TOOLBAR-tbButtonExportAllPage"]', timeout=2)
|
||||
if t is not None and t.states.is_displayed:
|
||||
target = t
|
||||
break
|
||||
if target is None or not target.states.is_displayed:
|
||||
config.log(f'{TAG} 找不到引出所有页')
|
||||
return False
|
||||
|
||||
# 4. 光标从「引出」连续移入「引出所有页」再点击(悬浮链不断,菜单不收起)
|
||||
try:
|
||||
ac.move_to(_clickable(target))
|
||||
time.sleep(0.5)
|
||||
ac.click()
|
||||
except Exception:
|
||||
try:
|
||||
target.click(by_js=True)
|
||||
except Exception:
|
||||
config.log(f'{TAG} 点击引出所有页失败')
|
||||
return False
|
||||
config.log(f'{TAG} 已触发引出所有页')
|
||||
return True
|
||||
|
||||
|
||||
# ================== 单次导出 ==================
|
||||
def _run_once(page, begin, end, codes, save_dir, new_name, first, org):
|
||||
if not _open_filter(page):
|
||||
return False
|
||||
if first:
|
||||
# 首档:完整设置 组织 → 仓库(内部提交前重设日期并触发查询)
|
||||
if not _set_org(page, org):
|
||||
return False
|
||||
if not _set_stock_codes(page, codes, begin, end):
|
||||
return False
|
||||
else:
|
||||
# 后续档:组织/仓库等条件 K3 已保留,只需改日期后提交查询
|
||||
if not _set_date(page, begin, end):
|
||||
return False
|
||||
if not _submit_query(page):
|
||||
return False
|
||||
if not _wait_progress(page):
|
||||
return False
|
||||
if not _export_all_pages(page):
|
||||
return False
|
||||
return kc.download_file(page, save_dir, new_name, tag=TAG)
|
||||
|
||||
|
||||
# ================== 入口 ==================
|
||||
def run(page, save_dir, org, codes, date_options, progress=None):
|
||||
"""先全局搜索打开报表,再逐日期选项导出(组织/仓库仅首档完整设置,后续档只改日期)。
|
||||
progress(done, total) 为整体进度回调;返回 (saved_files, failed_labels)。"""
|
||||
if not _open_report(page):
|
||||
raise RuntimeError("打开「物料收发汇总表」失败:全局搜索未打开报表过滤界面(详见日志)")
|
||||
saved, failed = [], []
|
||||
total = max(1, len(date_options))
|
||||
for i, option in enumerate(date_options):
|
||||
begin, end, label = resolve_dates(option)
|
||||
new_name = f'{config.FILE_PREFIX_31}_{label}.xlsx'
|
||||
success = False
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
config.log(f'{TAG} [{label}] 第 {attempt}/{config.RETRY_MAX} 次: {begin} ~ {end}')
|
||||
if _run_once(page, begin, end, codes, save_dir, new_name,
|
||||
first=(i == 0), org=org):
|
||||
success = True
|
||||
break
|
||||
kc.reset_filter_state(page, tag=TAG, wait_query=True) # 清掉失败留下的弹层/半填条件再重试
|
||||
time.sleep(2)
|
||||
if success:
|
||||
saved.append(str(save_dir / new_name))
|
||||
else:
|
||||
config.log(f'{TAG} [{label}] 重试 {config.RETRY_MAX} 次均失败,继续下一个日期选项')
|
||||
failed.append(label)
|
||||
if progress:
|
||||
try:
|
||||
progress(i + 1, total)
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
return saved, failed
|
||||
@@ -0,0 +1,86 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0031_xq0032",
|
||||
"name": "ERP物料收发汇总-采购订单报表导出",
|
||||
"version": "1.0.3",
|
||||
"description": "金蝶K3Cloud报表自动导出:物料收发汇总表(需求31)+ 采购订单列表(需求32),支持新旧系统、仓库编码多选、日期多选(含自定义区间),个性化配置保存在本机",
|
||||
"category": "报表",
|
||||
"icon": "",
|
||||
"platform": "",
|
||||
"uses_month": false,
|
||||
"ui": true,
|
||||
"capabilities": ["xq0031_xq0032"],
|
||||
"permissions": {
|
||||
"platforms": []
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"mode": {
|
||||
"type": "string",
|
||||
"title": "执行模式",
|
||||
"default": "两个都导",
|
||||
"enum": ["两个都导", "物料收发汇总表", "采购订单列表"],
|
||||
"description": "需求31=物料收发汇总表(按仓库/日期多档导出),需求32=采购订单列表(按方案导出)"
|
||||
},
|
||||
"erp_system": {
|
||||
"type": "string",
|
||||
"title": "ERP系统",
|
||||
"default": "新版",
|
||||
"enum": ["新版", "旧版"],
|
||||
"description": "新版 criterion.erp.37du.co / 旧版 erp.37du.co"
|
||||
},
|
||||
"erp_username": {
|
||||
"type": "string",
|
||||
"title": "ERP登录账号",
|
||||
"default": "",
|
||||
"description": "用户自己的ERP账号,保存在本机下次免填"
|
||||
},
|
||||
"erp_password": {
|
||||
"type": "string",
|
||||
"title": "ERP登录密码",
|
||||
"default": "",
|
||||
"format": "password",
|
||||
"description": "仅保存在本机(%LOCALAPPDATA%\\37duAutomation\\plugin_configs),下次免填"
|
||||
},
|
||||
"org_name": {
|
||||
"type": "string",
|
||||
"title": "查询组织",
|
||||
"default": "99.01 重庆金七象供应链管理有限公司"
|
||||
},
|
||||
"stock_codes": {
|
||||
"type": "array",
|
||||
"title": "仓库编码(可多选,或关系)",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"enum": ["0101010101", "0101010201", "0101020201", "0101030201", "0101040201"]
|
||||
},
|
||||
"default": ["0101010101", "0101010201", "0101020201", "0101030201", "0101040201"],
|
||||
"description": "每个编码一行过滤条件(或关系);可输入新编码后回车添加"
|
||||
},
|
||||
"date_options": {
|
||||
"type": "array",
|
||||
"title": "日期选项(多选,逐个导出)",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"enum": ["60D", "30D", "15D", "7D", "3D"]
|
||||
},
|
||||
"default": ["60D", "30D", "15D", "7D", "3D"],
|
||||
"description": "N天=今天往前推N天;可混入自定义区间如 2026-01-01~2026-09-15"
|
||||
},
|
||||
"scheme_name": {
|
||||
"type": "string",
|
||||
"title": "采购订单快捷方案",
|
||||
"default": "默认方案(个人)",
|
||||
"description": "需求32使用的过滤方案名(精确匹配)"
|
||||
},
|
||||
"save_dir": {
|
||||
"type": "string",
|
||||
"title": "保存目录",
|
||||
"default": "",
|
||||
"description": "留空=桌面/采购计划报表_日期"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,406 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""需求32 - 金蝶 K3Cloud ERP「采购订单列表」自动导出(xq0031_xq0032 插件内模块)。
|
||||
|
||||
自 workflows/XQ0032 purchase_order_list_export.py 迁移:
|
||||
全局搜索「采购订单列表」→ 选中编号 CGDDLB 项 → 点快捷方案 → 等查询完成 →
|
||||
选项 → 引出 → 按列表引出数据 → 下载保存(与需求31同目录)。
|
||||
快捷方案名由插件界面配置注入;交互逻辑与影刀版保持同源。
|
||||
"""
|
||||
import re
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
from . import config
|
||||
from . import k3_common as kc
|
||||
|
||||
TAG = '[采购订单列表]'
|
||||
REPORT_KEYWORD = '采购订单列表' # 全局搜索关键字
|
||||
REPORT_NUMBER = 'CGDDLB' # 搜索结果编号(列表项唯一标识)
|
||||
|
||||
|
||||
# ================== 列表操作 ==================
|
||||
def _diag_search(page):
|
||||
"""探针:搜索失败时打印当前页面/下拉状态,定位是下拉没出来还是选择器不匹配。"""
|
||||
try:
|
||||
config.log(f'{TAG} [探针] 当前 URL: {(page.url or "")[:120]}')
|
||||
except Exception as e:
|
||||
config.log(f'{TAG} [探针] 读 URL 异常: {e}')
|
||||
try:
|
||||
items = page.eles('css:.kd-fullsearch-selectable li.kd-fullsearch-item-container',
|
||||
timeout=2)
|
||||
config.log(f'{TAG} [探针] 下拉结果项数量: {len(items)}')
|
||||
for i, li in enumerate(items[:10]):
|
||||
try:
|
||||
num = li.ele('css:span[searchitem="number"]', timeout=0.3)
|
||||
txt = li.ele('css:span[searchitem="text"]', timeout=0.3)
|
||||
config.log(f'{TAG} [探针] 第{i + 1}项: '
|
||||
f'number={num.text if num else "?"} '
|
||||
f'text={txt.text if txt else "?"} '
|
||||
f'displayed={li.states.is_displayed}')
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
config.log(f'{TAG} [探针] 枚举下拉异常: {e}')
|
||||
filter_visible = kc.ele_visible(
|
||||
page, 'css:[id*="BILLMENU_TOOLBAR-tbFilter"]', timeout=1)
|
||||
config.log(f'{TAG} [探针] 过滤按钮可见: {filter_visible}')
|
||||
|
||||
|
||||
def _open_report(page):
|
||||
"""点击全局搜索 → 输入「采购订单列表」→ 等联想下拉出现 → 点选编号 CGDDLB 项。
|
||||
注意:不能按回车——K3 全局搜索回车会默认直接进入第一个结果,下拉随即关闭,
|
||||
无法精确选中 CGDDLB 项。输入后等待联想下拉,再点对应项。"""
|
||||
if not kc.click_visible(page, 'css:.kd-fullsearch-searchicon', timeout=10):
|
||||
config.log(f'{TAG} 找不到全局搜索图标')
|
||||
return False
|
||||
time.sleep(1)
|
||||
sbox = page.ele('css:.kd-appplat-searchinput', timeout=5)
|
||||
if not sbox:
|
||||
config.log(f'{TAG} 找不到搜索输入框')
|
||||
return False
|
||||
sbox.clear()
|
||||
sbox.input(REPORT_KEYWORD)
|
||||
time.sleep(0.8) # 输入即出联想下拉;不按回车(回车=直接进第一个结果)
|
||||
|
||||
# 结果下拉列表中找编号为 CGDDLB 的「采购订单列表」项
|
||||
end = time.time() + 20
|
||||
while time.time() < end:
|
||||
for li in page.eles('css:.kd-fullsearch-selectable li.kd-fullsearch-item-container',
|
||||
timeout=2):
|
||||
try:
|
||||
if not li.states.is_displayed:
|
||||
continue
|
||||
num = li.ele('css:span[searchitem="number"]', timeout=0.5)
|
||||
if num is None:
|
||||
continue
|
||||
num_text = (num.attr('title') or num.text or '').strip().upper()
|
||||
if num_text == REPORT_NUMBER.upper():
|
||||
li.click()
|
||||
time.sleep(2)
|
||||
if kc.ele_visible(page, 'css:[id*="BILLMENU_TOOLBAR-tbFilter"]', timeout=2):
|
||||
config.log(f'{TAG} 已打开列表({REPORT_NUMBER})')
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
config.log(f'{TAG} 未找到编号 {REPORT_NUMBER} 的搜索结果项')
|
||||
_diag_search(page) # 探针:输出诊断信息
|
||||
return False
|
||||
|
||||
|
||||
def _open_filter(page):
|
||||
"""确保过滤窗口打开:已开则复用,未开则点「过滤」按钮(by_js 触发菜单项)。"""
|
||||
if kc.ele_visible(page, 'css:.k-window [id*="_Filter-FSCHEMELIST"]', timeout=2):
|
||||
return True
|
||||
if kc.click_visible(page, 'css:[id*="BILLMENU_TOOLBAR-tbFilter"]', by_js=True):
|
||||
time.sleep(1.5)
|
||||
return kc.ele_visible(page, 'css:[id*="_Filter-FSCHEMELIST"]', timeout=5)
|
||||
return False
|
||||
|
||||
|
||||
def _select_scheme(page, scheme):
|
||||
"""在过滤窗口方案树中选中目标方案(默认「默认方案(个人)」)。
|
||||
方案树节点结构:li.k-item > .k-in.kd-treenode-textcnt > .kd-treenode-text。
|
||||
注意:K3 树节点用 by_js click 不触发选中事件(现场验证),必须真实鼠标点击
|
||||
.k-in.kd-treenode-textcnt 节点;选中成功后界面出现 SelectedSchemeItemControlTemplate。"""
|
||||
ac = page.actions
|
||||
end = time.time() + config.TIMEOUT
|
||||
while time.time() < end:
|
||||
for li in page.eles('css:.k-window li.k-item', timeout=2):
|
||||
try:
|
||||
if not li.states.is_displayed:
|
||||
continue
|
||||
t = li.ele('css:.kd-treenode-text', timeout=0.5)
|
||||
if t is None or scheme not in (t.text or ''):
|
||||
continue
|
||||
# 已选中:选中模板(SelectedSchemeItemControlTemplate)的文本须是目标方案,
|
||||
# 否则可能是上次选的其它方案,误判会导出错误数据
|
||||
cur = page.ele('css:.SelectedSchemeItemControlTemplate', timeout=1)
|
||||
if cur is not None and scheme in (cur.text or ''):
|
||||
config.log(f'{TAG} 方案已是: {t.text.strip()}')
|
||||
return True
|
||||
# 真实鼠标点击节点外层 .k-in.kd-treenode-textcnt(by_js 不触发选中)
|
||||
node = t.parent() # .k-in.kd-treenode-textcnt
|
||||
if node is None or not node.states.is_displayed:
|
||||
node = t
|
||||
try:
|
||||
ac.move_to(node)
|
||||
time.sleep(0.3)
|
||||
ac.click()
|
||||
except Exception:
|
||||
try:
|
||||
node.click(by_js=True)
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.8)
|
||||
# 确认选中:出现 SelectedSchemeItemControlTemplate 才算点击成功
|
||||
if kc.ele_visible(page, 'css:.SelectedSchemeItemControlTemplate', timeout=2):
|
||||
config.log(f'{TAG} 已选择方案: {t.text.strip()}')
|
||||
return True
|
||||
# 未生效:可能点到文本被全选,改为点 li 下的 .kd-treenode-textcnt 外层再试一次
|
||||
try:
|
||||
cnt = li.ele('css:.kd-treenode-textcnt', timeout=1)
|
||||
if cnt is not None and cnt.states.is_displayed:
|
||||
ac.move_to(cnt)
|
||||
time.sleep(0.3)
|
||||
ac.click()
|
||||
time.sleep(0.8)
|
||||
if kc.ele_visible(page, 'css:.SelectedSchemeItemControlTemplate',
|
||||
timeout=2):
|
||||
config.log(f'{TAG} 已选择方案: {t.text.strip()}')
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
config.log(f'{TAG} 过滤窗口方案树中未找到: {scheme}')
|
||||
return False
|
||||
|
||||
|
||||
def _submit_filter(page):
|
||||
"""点过滤窗口「确定」触发查询。注意:[id*="_Filter-FBTNOK_c"] 也会命中仓库等其它
|
||||
过滤面板的同 id 按钮,用 :not + .k-window 限定,防止误点。"""
|
||||
if not kc.click_visible(page, 'css:.k-window [id*="_Filter-FBTNOK_c"]:not([id*="FBeginStockId"])'):
|
||||
config.log(f'{TAG} 找不到过滤窗口确定按钮')
|
||||
return False
|
||||
config.log(f'{TAG} 已提交过滤查询')
|
||||
return True
|
||||
|
||||
|
||||
def _read_rowcount(page):
|
||||
"""读分页栏行数统计(span[data-kdid="rowcount_pagerlist2"],文本形如「共519行」)。
|
||||
返回 (文本, 条数);未找到/未显示返回 (None, -1)。"""
|
||||
try:
|
||||
for el in page.eles('css:span[data-kdid="rowcount_pagerlist2"]', timeout=1):
|
||||
try:
|
||||
if not el.states.is_displayed:
|
||||
continue
|
||||
txt = (el.text or '').strip()
|
||||
m = re.search(r'共\s*(\d+)\s*行', txt)
|
||||
return txt, (int(m.group(1)) if m else -1)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
return None, -1
|
||||
|
||||
|
||||
def _wait_progress(page, timeout=300):
|
||||
"""等待查询完成:进入页面时分页栏已带旧条数,查询时会先变 0(或消失)再变新条数。
|
||||
故记录初始条数,等行数经历「变 0/消失」或「发生变化」后,再出现非 0 条数才算完成。"""
|
||||
_, init_cnt = _read_rowcount(page)
|
||||
config.log(f'{TAG} 当前条数: {init_cnt if init_cnt >= 0 else "无"},等待查询刷新...')
|
||||
saw_reset = init_cnt < 0 # 初始无条数视为已重置
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
txt, cnt = _read_rowcount(page)
|
||||
if cnt == 0:
|
||||
saw_reset = True # 先变 0:查询已触发,正在刷新
|
||||
elif cnt > 0:
|
||||
if saw_reset or cnt != init_cnt:
|
||||
config.log(f'{TAG} 查询完成: {txt}')
|
||||
return True
|
||||
time.sleep(1)
|
||||
config.log(f'{TAG} 等待查询完成超时(行数未刷新)')
|
||||
return False
|
||||
|
||||
|
||||
def _export_all_pages(page):
|
||||
"""选项 → 引出(真实鼠标悬浮展开子菜单)→ 按列表引出数据。
|
||||
现场结论:物理点击内容 span 只会『全选文字』不触发菜单;JS click 又触发不了
|
||||
K3 的悬浮式嵌套子菜单。故全程用 page.actions 的真实鼠标 move_to(悬浮,不点击文字),
|
||||
让子菜单展开后用 move_to+click 点中「按列表引出数据」;不点 span 文本,避免全选。
|
||||
注意:必须复用同一个 ac=page.actions,保证光标位置连续(悬浮链不中断子菜单不收起)。
|
||||
本列表页与需求31不同:选项=tbOptionLists,引出=tbInputOutput,目标=按列表引出数据(tbOutput)。"""
|
||||
ac = page.actions
|
||||
|
||||
def _clickable(span):
|
||||
"""内容 span 的父级可点击元素(a/li),避免点到文本被『全选文字』。"""
|
||||
try:
|
||||
a = span.closest('css:a')
|
||||
if a is not None and a.tag.lower() == 'a' and a.states.is_displayed:
|
||||
return a
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
li = span.closest('css:li')
|
||||
if li is not None and li.states.is_displayed:
|
||||
return li
|
||||
except Exception:
|
||||
pass
|
||||
return span
|
||||
|
||||
# 1. 点「选项」打开配置菜单(点其 a/li,避开文本)
|
||||
opt = page.ele('css:span[id*="BILLMENU_TOOLBAR-tbOptionLists"]', timeout=5)
|
||||
if opt is None or not opt.states.is_displayed:
|
||||
opt = page.ele('css:[id*="BILLMENU_TOOLBAR-tbOptionLists"]', timeout=5)
|
||||
if opt is None or not opt.states.is_displayed:
|
||||
config.log(f'{TAG} 找不到选项按钮')
|
||||
return False
|
||||
try:
|
||||
ac.move_to(_clickable(opt)).click()
|
||||
except Exception:
|
||||
try:
|
||||
opt.click(by_js=True)
|
||||
except Exception:
|
||||
config.log(f'{TAG} 点选项失败')
|
||||
return False
|
||||
time.sleep(1.2)
|
||||
|
||||
# 2. 定位「引出」(splitbutton)
|
||||
split = page.ele('css:span[id*="BILLMENU_TOOLBAR-tbInputOutput"]', timeout=5)
|
||||
if split is None or not split.states.is_displayed:
|
||||
split = page.ele('css:[id*="BILLMENU_TOOLBAR-tbInputOutput"]', timeout=5)
|
||||
if split is None or not split.states.is_displayed:
|
||||
config.log(f'{TAG} 找不到导出(引出)按钮')
|
||||
return False
|
||||
|
||||
def _trigger():
|
||||
"""悬浮目标:优先右箭头(悬浮开子菜单),无箭头则悬浮整体。"""
|
||||
try:
|
||||
ar = split.parent().ele('css:span.k-icon', timeout=1)
|
||||
if ar is not None and ar.states.is_displayed:
|
||||
return ar
|
||||
except Exception:
|
||||
pass
|
||||
return _clickable(split)
|
||||
|
||||
trigger = _trigger()
|
||||
|
||||
# 3. 悬浮展开「按列表引出数据」子菜单
|
||||
target = None
|
||||
for _ in range(4):
|
||||
try:
|
||||
ac.move_to(trigger) # 真实鼠标悬浮到右箭头,子菜单展开
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1.0)
|
||||
t = page.ele('css:span[id$="BILLMENU_TOOLBAR-tbOutput"]', timeout=2)
|
||||
if t is not None and t.states.is_displayed:
|
||||
target = t
|
||||
break
|
||||
if target is None or not target.states.is_displayed:
|
||||
for _ in range(3):
|
||||
try:
|
||||
trigger.click()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
t = page.ele('css:span[id$="BILLMENU_TOOLBAR-tbOutput"]', timeout=2)
|
||||
if t is not None and t.states.is_displayed:
|
||||
target = t
|
||||
break
|
||||
if target is None or not target.states.is_displayed:
|
||||
config.log(f'{TAG} 找不到按列表引出数据')
|
||||
return False
|
||||
|
||||
# 4. 光标从「引出」连续移入「按列表引出数据」再点击(悬浮链不断,菜单不收起)
|
||||
try:
|
||||
ac.move_to(_clickable(target))
|
||||
time.sleep(0.5)
|
||||
ac.click()
|
||||
except Exception:
|
||||
try:
|
||||
target.click(by_js=True)
|
||||
except Exception:
|
||||
config.log(f'{TAG} 点击按列表引出数据失败')
|
||||
return False
|
||||
config.log(f'{TAG} 已触发按列表引出数据')
|
||||
return True
|
||||
|
||||
|
||||
def _click_quick_scheme(page, scheme):
|
||||
"""直接点击列表页顶部快捷方案条中的目标方案,无需打开过滤窗口。
|
||||
结构:div[filter-role="filterschemecontent"] > div.SchemeItemControlTemplate(含方案名,
|
||||
选中的为 SelectedSchemeItemControlTemplate)。
|
||||
注意:K3 控件用 by_js click 可能不触发,优先真实鼠标点击。"""
|
||||
ac = page.actions
|
||||
end = time.time() + config.TIMEOUT
|
||||
while time.time() < end:
|
||||
for item in page.eles(
|
||||
'css:div[filter-role="filterschemecontent"] '
|
||||
'div[class*="SchemeItemControlTemplate"]', timeout=2):
|
||||
try:
|
||||
if not item.states.is_displayed:
|
||||
continue
|
||||
txt = (item.text or '').strip()
|
||||
if txt != scheme: # 精确匹配:避免「默认方案」误命中「采购订单宽表默认方案」
|
||||
continue
|
||||
cls = item.attr('class') or ''
|
||||
if 'Selected' in cls:
|
||||
config.log(f'{TAG} 快捷方案已是: {txt}')
|
||||
return True
|
||||
try:
|
||||
ac.move_to(item)
|
||||
time.sleep(0.3)
|
||||
ac.click()
|
||||
except Exception:
|
||||
try:
|
||||
item.click(by_js=True)
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
# 确认选中:快捷条中 Selected 方案变为目标方案
|
||||
cur = page.ele(
|
||||
'css:div[filter-role="filterschemecontent"] '
|
||||
'div.SelectedSchemeItemControlTemplate', timeout=2)
|
||||
if cur is not None and scheme in (cur.text or ''):
|
||||
config.log(f'{TAG} 已点选快捷方案: {txt}')
|
||||
return True
|
||||
# 未确认选中:返回 False 走过滤窗口回退,防止把旧数据当本次结果
|
||||
config.log(f'{TAG} 点击快捷方案未确认选中: {txt}')
|
||||
return False
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
config.log(f'{TAG} 快捷方案条中未找到: {scheme}')
|
||||
return False
|
||||
|
||||
|
||||
def _run_once(page, scheme):
|
||||
"""直接点快捷方案 → 等查询 → 按列表引出数据。
|
||||
快捷方案条不存在时回退到过滤窗口选方案。"""
|
||||
if _click_quick_scheme(page, scheme):
|
||||
if not _wait_progress(page):
|
||||
return False
|
||||
else:
|
||||
# 回退:过滤窗口选方案
|
||||
if not _open_filter(page):
|
||||
return False
|
||||
if not _select_scheme(page, scheme):
|
||||
return False
|
||||
if not _submit_filter(page):
|
||||
return False
|
||||
if not _wait_progress(page):
|
||||
return False
|
||||
return _export_all_pages(page)
|
||||
|
||||
|
||||
# ================== 入口 ==================
|
||||
def run(page, save_dir, scheme, progress=None):
|
||||
"""先全局搜索打开列表,再按方案导出(快捷方案 → 等查询 → 引出 → 下载,重试 3 次)。
|
||||
progress(done, total) 为整体进度回调;返回保存文件路径,失败返回 None。"""
|
||||
if not _open_report(page):
|
||||
raise RuntimeError("打开「采购订单列表」失败:全局搜索未命中 CGDDLB 列表(详见日志)")
|
||||
new_name = f'{config.FILE_PREFIX_32}_{datetime.now():%Y-%m-%d}.xlsx'
|
||||
config.log(f'{TAG} 导出文件: {new_name}')
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
config.log(f'{TAG} 第 {attempt}/{config.RETRY_MAX} 次导出')
|
||||
if _run_once(page, scheme):
|
||||
if kc.download_file(page, save_dir, new_name, tag=TAG):
|
||||
if progress:
|
||||
try:
|
||||
progress(1, 1)
|
||||
except Exception:
|
||||
pass
|
||||
return str(save_dir / new_name)
|
||||
kc.reset_filter_state(page, tag=TAG) # 清掉失败留下的弹层/半填条件再重试
|
||||
time.sleep(2)
|
||||
config.log(f'{TAG} 重试 {config.RETRY_MAX} 次均失败')
|
||||
if progress:
|
||||
try:
|
||||
progress(1, 1)
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
@@ -0,0 +1 @@
|
||||
DrissionPage>=4.0
|
||||
@@ -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>ERP报表导出</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
+1576
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "xq0031-xq0032-ui",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "^2.3.2",
|
||||
"element-plus": "^2.14.5",
|
||||
"vue": "^3.5.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^5.2.1",
|
||||
"vite": "^6.0.3"
|
||||
},
|
||||
"allowScripts": {
|
||||
"esbuild@0.25.12": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<!-- 未登录 / 结果横幅 -->
|
||||
<el-alert v-if="needLogin" type="warning" :closable="false" show-icon
|
||||
title="未登录:请先在壳子(工作台)登录统一账户,再刷新本界面" />
|
||||
<el-alert v-else-if="banner" :type="banner.type" :closable="true" show-icon @close="banner = null">
|
||||
<template #title>{{ banner.text }}</template>
|
||||
</el-alert>
|
||||
|
||||
<!-- 执行配置 -->
|
||||
<el-card shadow="never" class="card">
|
||||
<template #header>
|
||||
<span class="card-title">执行配置</span>
|
||||
<span v-if="lastSavedAt" class="saved">已保存 {{ lastSavedAt }}</span>
|
||||
</template>
|
||||
<el-form label-width="120px" label-position="right">
|
||||
<div class="grid">
|
||||
<el-form-item label="执行模式">
|
||||
<el-select v-model="form.mode" :disabled="running">
|
||||
<el-option label="两个都导(同一登录会话连导)" value="两个都导" />
|
||||
<el-option label="物料收发汇总表(需求31)" value="物料收发汇总表" />
|
||||
<el-option label="采购订单列表(需求32)" value="采购订单列表" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="ERP系统">
|
||||
<el-radio-group v-model="form.erp_system" :disabled="running">
|
||||
<el-radio-button value="新版">新版</el-radio-button>
|
||||
<el-radio-button value="旧版">旧版</el-radio-button>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
</div>
|
||||
|
||||
<div class="grid">
|
||||
<el-form-item label="登录账号">
|
||||
<el-input v-model="form.erp_username" placeholder="你的ERP登录账号" :disabled="running" clearable />
|
||||
</el-form-item>
|
||||
<el-form-item label="登录密码">
|
||||
<el-input v-model="form.erp_password" type="password" show-password
|
||||
placeholder="仅保存在本机,下次免填" :disabled="running" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
|
||||
<el-form-item label="查询组织">
|
||||
<el-input v-model="form.org_name" :disabled="running" clearable
|
||||
placeholder="确保过滤界面组织为该值,否则自动重新选择" />
|
||||
</el-form-item>
|
||||
|
||||
<template v-if="form.mode !== '采购订单列表'">
|
||||
<el-form-item label="仓库编码">
|
||||
<el-select v-model="form.stock_codes" multiple filterable allow-create default-first-option
|
||||
:reserve-keyword="false" placeholder="勾选预设或输入新编码后回车" :disabled="running" class="wide">
|
||||
<el-option v-for="c in STOCK_PRESETS" :key="c" :value="c" :label="c" />
|
||||
</el-select>
|
||||
<div class="tip">多选为「或」关系,每个编码占一行过滤条件</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="日期选项">
|
||||
<el-select v-model="form.date_options" multiple filterable allow-create default-first-option
|
||||
:reserve-keyword="false" placeholder="勾选预设,或输入自定义区间后回车" :disabled="running" class="wide">
|
||||
<el-option v-for="d in DATE_PRESETS" :key="d" :value="d" :label="d" />
|
||||
</el-select>
|
||||
<div class="tip">N天 = 今天往前推N天,逐档导出;自定义区间格式:2026-01-01~2026-09-15(输入后回车)</div>
|
||||
</el-form-item>
|
||||
</template>
|
||||
|
||||
<el-form-item v-if="form.mode !== '物料收发汇总表'" label="快捷方案">
|
||||
<el-input v-model="form.scheme_name" :disabled="running" clearable
|
||||
placeholder="采购订单列表使用的过滤方案名(精确匹配)" />
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="保存目录">
|
||||
<el-input v-model="form.save_dir" :disabled="running" clearable
|
||||
placeholder="留空 = 桌面/采购计划报表_今天日期" />
|
||||
</el-form-item>
|
||||
|
||||
<div class="actions">
|
||||
<el-button type="primary" size="large" :loading="running" @click="run">
|
||||
{{ running ? '执行中 ' + progress + '%' : '一键执行' }}
|
||||
</el-button>
|
||||
<el-button size="large" :disabled="running" @click="saveNow(true)">保存配置</el-button>
|
||||
<el-button size="large" text :disabled="running" @click="resetDefaults">恢复默认</el-button>
|
||||
</div>
|
||||
</el-form>
|
||||
</el-card>
|
||||
|
||||
<!-- 运行状态:进度条 + 日志位置提示(日志实时显示在壳子下方日志区) -->
|
||||
<div v-if="running" class="status">
|
||||
<el-progress :percentage="progress" :stroke-width="8" class="status-bar" />
|
||||
<span class="status-txt">正在执行,日志与进度实时显示在工作台下方【运行日志】区</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { onMounted, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { connectWS, getRun, loadConfig, saveConfig, startRun } from './api'
|
||||
|
||||
const STOCK_PRESETS = ['0101010101', '0101010201', '0101020201', '0101030201', '0101040201']
|
||||
const DATE_PRESETS = ['60D', '30D', '15D', '7D', '3D']
|
||||
|
||||
const DEFAULTS = () => ({
|
||||
mode: '两个都导',
|
||||
erp_system: '新版',
|
||||
erp_username: '',
|
||||
erp_password: '',
|
||||
org_name: '99.01 重庆金七象供应链管理有限公司',
|
||||
stock_codes: [...STOCK_PRESETS],
|
||||
date_options: [...DATE_PRESETS],
|
||||
scheme_name: '默认方案(个人)',
|
||||
save_dir: '',
|
||||
})
|
||||
|
||||
const form = reactive(DEFAULTS())
|
||||
const loaded = ref(false)
|
||||
const needLogin = ref(false)
|
||||
const banner = ref(null)
|
||||
const lastSavedAt = ref('')
|
||||
const running = ref(false)
|
||||
const progress = ref(0)
|
||||
|
||||
let ws = null
|
||||
let runId = ''
|
||||
let pollTimer = null
|
||||
let saveTimer = null
|
||||
|
||||
// ---------- 配置加载 / 保存 ----------
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const saved = await loadConfig()
|
||||
Object.keys(form).forEach((k) => {
|
||||
if (saved[k] !== undefined && saved[k] !== null && saved[k] !== '') form[k] = saved[k]
|
||||
if (k === 'stock_codes' && Array.isArray(saved[k])) form.stock_codes = saved[k]
|
||||
if (k === 'date_options' && Array.isArray(saved[k])) form.date_options = saved[k]
|
||||
})
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.warning('读取本机配置失败,已用默认值:' + e.message)
|
||||
}
|
||||
loaded.value = true
|
||||
})
|
||||
|
||||
// 配置变更自动保存(防抖),执行中不改存
|
||||
watch(form, () => {
|
||||
if (!loaded.value || running.value) return
|
||||
clearTimeout(saveTimer)
|
||||
saveTimer = setTimeout(() => saveNow(false), 800)
|
||||
}, { deep: true })
|
||||
|
||||
async function saveNow(explicit) {
|
||||
try {
|
||||
await saveConfig(JSON.parse(JSON.stringify(form)))
|
||||
lastSavedAt.value = new Date().toLocaleTimeString('zh-CN', { hour12: false })
|
||||
if (explicit) ElMessage.success('配置已保存到本机')
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.error('配置保存失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
function resetDefaults() {
|
||||
Object.assign(form, DEFAULTS())
|
||||
ElMessage.info('已恢复默认配置')
|
||||
}
|
||||
|
||||
// ---------- 执行 ----------
|
||||
function validate() {
|
||||
if (!form.erp_username.trim() || !form.erp_password) {
|
||||
ElMessage.warning('请先填写 ERP 登录账号和密码')
|
||||
return false
|
||||
}
|
||||
if (form.mode !== '采购订单列表') {
|
||||
if (!form.stock_codes.length) { ElMessage.warning('请至少选择一个仓库编码'); return false }
|
||||
if (!form.date_options.length) { ElMessage.warning('请至少选择一个日期选项'); return false }
|
||||
}
|
||||
if (form.mode !== '物料收发汇总表' && !form.scheme_name.trim()) {
|
||||
ElMessage.warning('请填写采购订单快捷方案名')
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
async function run() {
|
||||
if (running.value) return
|
||||
// 未登录不再静默返回:先重试一次配置读取(会话可能在打开后已恢复),仍失败则明确提示
|
||||
if (needLogin.value) {
|
||||
try {
|
||||
await loadConfig()
|
||||
needLogin.value = false
|
||||
ElMessage.success('登录态已恢复,请再次点击执行')
|
||||
return
|
||||
} catch (_) { /* 仍未登录 */ }
|
||||
ElMessage.warning('未登录:请先在壳子登录统一账户,再打开本界面')
|
||||
return
|
||||
}
|
||||
if (!validate()) return
|
||||
await saveNow(false)
|
||||
running.value = true
|
||||
progress.value = 0
|
||||
banner.value = null
|
||||
try {
|
||||
const r = await startRun(JSON.parse(JSON.stringify(form)))
|
||||
runId = r.run_id
|
||||
connect() // runId 就绪后再连 WS,避免早到的运行事件被过滤掉
|
||||
startPolling()
|
||||
} catch (e) {
|
||||
running.value = false
|
||||
stopPolling()
|
||||
if (e.code === 401) needLogin.value = true
|
||||
banner.value = { type: 'error', text: '启动执行失败:' + e.message }
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 实时进度 + 完成(WS 只取进度/结束事件,日志由壳子下方日志区展示) ----------
|
||||
function connect() {
|
||||
if (ws && ws.readyState <= 1) return
|
||||
ws = connectWS((ev) => {
|
||||
if (ev.run_id && ev.run_id !== runId) return // 只看本次运行
|
||||
if (ev.t === 'progress') progress.value = Math.max(progress.value, ev.pct || 0)
|
||||
else if (ev.t === 'run_done') ev.ok ? finished() : failed(ev.error || '执行失败')
|
||||
})
|
||||
ws.onclose = () => { ws = null } // 断开后由轮询兜底
|
||||
}
|
||||
|
||||
function startPolling() {
|
||||
stopPolling()
|
||||
pollTimer = setInterval(async () => {
|
||||
if (!runId) return
|
||||
try {
|
||||
const r = await getRun(runId)
|
||||
if (r.status === 'done') finished(r.result?.summary || '执行完成')
|
||||
else if (r.status === 'error') failed(r.error || '执行失败')
|
||||
} catch (_) { /* 下轮再试 */ }
|
||||
}, 5000)
|
||||
}
|
||||
|
||||
function stopPolling() {
|
||||
if (pollTimer) { clearInterval(pollTimer); pollTimer = null }
|
||||
}
|
||||
|
||||
async function finished(summary) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
progress.value = 100
|
||||
banner.value = { type: 'success', text: summary || '执行完成' }
|
||||
}
|
||||
|
||||
function failed(err) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
banner.value = { type: 'error', text: '执行失败:' + err }
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.page {
|
||||
max-width: 860px;
|
||||
margin: 0 auto;
|
||||
padding: 4px 0 20px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.card {
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.card-title {
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.saved {
|
||||
float: right;
|
||||
font-size: 12px;
|
||||
font-weight: 400;
|
||||
color: #67c23a;
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: flex;
|
||||
gap: 18px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.grid .el-form-item {
|
||||
flex: 1;
|
||||
min-width: 280px;
|
||||
}
|
||||
|
||||
.wide {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.tip {
|
||||
width: 100%;
|
||||
font-size: 12px;
|
||||
color: #909399;
|
||||
line-height: 1.6;
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
border-top: 1px dashed var(--el-border-color);
|
||||
padding-top: 16px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 10px 14px;
|
||||
border-radius: 10px;
|
||||
background: var(--el-color-primary-light-9);
|
||||
border: 1px solid var(--el-color-primary-light-7);
|
||||
}
|
||||
|
||||
.status-bar {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.status-txt {
|
||||
font-size: 12px;
|
||||
color: #606266;
|
||||
white-space: nowrap;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,46 @@
|
||||
// 与壳子后端交互(同源,统一账户会话 cookie 自动携带)+ WebSocket 实时流
|
||||
export const PLUGIN_ID = 'xq0031_xq0032'
|
||||
|
||||
async function j(url, opts) {
|
||||
const res = await fetch(url, opts)
|
||||
if (res.status === 401) {
|
||||
throw Object.assign(new Error('未登录:请先在壳子登录统一账户再打开本界面'), { code: 401 })
|
||||
}
|
||||
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 function loadConfig() {
|
||||
return j(`/api/plugin-config/${PLUGIN_ID}`)
|
||||
}
|
||||
|
||||
export function saveConfig(data) {
|
||||
return j(`/api/plugin-config/${PLUGIN_ID}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export function startRun(fields) {
|
||||
return j('/api/runs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, fields }),
|
||||
})
|
||||
}
|
||||
|
||||
export function getRun(runId) {
|
||||
return j(`/api/runs/${runId}`)
|
||||
}
|
||||
|
||||
export function connectWS(onEvent) {
|
||||
const ws = new WebSocket((location.protocol === 'https:' ? 'wss://' : 'ws://')
|
||||
+ location.host + '/ws')
|
||||
ws.onmessage = (e) => { try { onEvent(JSON.parse(e.data)) } catch (_) { /* 忽略脏帧 */ } }
|
||||
return ws
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user