feat(fileserver): 新增内网文件服务器服务与管理页面

新增 FastAPI 文件服务器核心模块(配置、鉴权、存储、心跳上报),新增 HTTP 路由接口(健康检查、文件上传/下载/删除、管理登录/密码修改/统计),新增 Vue3 管理页面源码;新增 MySQL 元数据存储支持,新增 PyMySQL 依赖;新增 .gitignore 忽略 IDE 与备份文件;新增文件服务器工具脚本;删除旧的 build/ 脚本与 exe 构建产物,优化 Electron 平台登录逻辑为纯接口模式,新增平台账号环境变量注入,优化试用期异常检查逻辑,拆分服务岗转正流程为独立脚本。
This commit is contained in:
2026-10-12 09:45:04 +08:00
parent a66006115a
commit d3236e2c63
56 changed files with 6499 additions and 39922 deletions
+4
View File
@@ -63,6 +63,10 @@ desktop/**/_cp_sessions.json
.vscode/
*.swp
*.swo
# Trae IDE 本地配置/技能(不入库)
.trae/
# 工具 ACL 恢复备份产物
.dsh-acl-recovery/
# ---------- 操作系统 ----------
.DS_Store
+138 -40
View File
@@ -1,40 +1,138 @@
一、功能需求内容
1.系统登录
1. 需登录 EHR 人事系统及钉钉AI表格,用于查询合同台账、试用期人员、未签合同人员及门店服务岗转正跟进台账数据;
2. 登录态失效时应自动重新登录并继续处理,无需人工干预。
2. 报表查询
1. 查询生效中合同数据:通过员工工号查询EHR系统劳动关系下生效中的合同台账记录;
2. 查询试用期人员数据:通过员工工号查询在岗试用期人员原始试用期、到期日期等信息;
3. 查询未签合同数据:通过员工工号查询离职改签后未签约人员台账记录;
4. 查询转正跟进台账数据:读取钉钉AI表格【门店服务岗转正跟进-周更新】全量台账字段,包含考核结果、处理意见、合同单位、处理状态等信息。
3. 文件导出与存储
1. 支持导出EHR系统合同台账、试用期人员台账原始数据,用于人工核对校验;
2. 支持导出钉钉AI表格转正跟进台账明细,留存周度处理记录;
3. 导出文件带日期时间戳命名,保存至指定目录,保证操作记录可追溯。
4. 数据后处理
所有台账记录严格按照规则1>规则2>规则3优先级匹配执行。
规则1:离职后再入职(最高优先级)
适配条件:钉钉台账记录满足【人员处理意见=离职后再入职】
1. EHR合同调动解除操作:进入EHR系统【劳动关系→合同台账→生效中合同】,通过员工工号精准匹配人员记录,执行调动解除(电子签)操作,发起《(改签)离职电子签流程》;流程参数固定为:新签合同=否、实际离职日期=员工原始试用期到期日期,完善信息后提交并发起电子签办理流程。
2. EHR试用期变更操作:进入EHR系统【试用期台账→试用期人员】,通过员工工号匹配对应人员,执行试用期变更操作;固定参数为:新试用期时长=1个月,新试用期到期日期=原试用期到期日期顺延1个月(示例:原到期日2026-09-02,新到期日2026-10-02)。
3. 变更确认:试用期信息保存后,自动跳转EHR【变更/转正待确认】页面,完成该员工试用期变更确认操作,并校验台账数据准确性。
4. 台账回填规则:仅当调动解除电子签发起成功、试用期变更及确认全部完成后,自动回填钉钉台账:人资处理=是、离职推送日期=业务操作当天日期;任意环节执行失败,不更新台账,保留原始状态,支持重试。
规则2:到期考核正常通过
适配条件:钉钉台账记录满足【到期能否考核通过=能】
1. 无需执行任何EHR系统操作、无电子签推送、无人员信息变更。
2. 自动回填钉钉台账固定标记:人资是否处理=否。
规则3:离职改签后新签合同推送(最低优先级)
适配条件:钉钉台账记录满足【人资是否处理=是】且【离职推送日期不为空】
1. 数据校验:进入EHR系统【劳动关系→合同台账→未签合同】,通过员工工号查询人员是否存在未签约记录。
2. 无匹配人员:无需执行任何操作,保留台账原始状态。
3. 有匹配人员:执行新签合同电子签推送操作,核心参数规则:合同类型、合同期限、合同终止日期,严格按照员工达龄规则判定(同EHR系统员工续签达龄判定标准);合同签署单位直接读取钉钉台账【合同单位】字段;电子签期望推送时间=操作当天。
4. 台账回填规则:新签电子签推送成功后,自动回填钉钉台账:新合同推送日期=操作当天;推送失败则不更新台账,保留待处理状态,支持重试。
二、异常场景处理
1. 登录态失效:自动重新登录并继续处理,无需人工干预;
2. 人员数据缺失:工号未查询到合同、试用期、未签合同数据时,自动跳过当前人员,不执行操作,保留原始台账状态;
3. 系统操作失败:电子签发起、试用期变更、合同新签提交失败时,不更新台账处理字段,保留待处理状态,支持重试操作;
4. 台账回填异常:系统业务执行成功但台账字段回填失败,保留原始数据,可人工补录修正;
5. 所有流程仅按规则执行推送与回填,异常记录由HR人工复核确认。
三、项目交付物
1. 一套可自动运行的门店服务岗转正跟进处理流程,支持按台账规则自动完成试用期顺延、离职改签、新签合同推送及台账回填;
3. 配套需求文档、流程文档、开发文档、验收文档。
# 门店服务岗转正(离职+入职)自动化流程说明
AI表格:【门店服务岗转正跟进-周更新】(下称"AI表格")
字段对照:人资是否处理、离职推送时间、到期能否考核通过、人员处理意见、合同签署单位、新合同推送日期、签署跟进
---
## 分支1:到期能否考核通过 = 能
「人资是否处理」直接回填「否」(无需离职+入职处理)。
## 分支2:人员处理意见 = 离职后再入职
- 「到期能否考核通过」= 不能 → 进入子分支处理;
- 「到期能否考核通过」未填写 → 先回填「不能」,再进入子分支处理。
### 超龄判定(进入子分支后、跑流程前先判定)
按工号调用员工花名册接口,取三个字段:
| 字段 | 用途 |
|---|---|
| 性别 | 退休年龄:男 60 / 女 50,退休日 = 出生日期 + 对应年数(生日当天即满龄) |
| 出生日期 | 算退休日 |
| 序列 | 新合同期限:XX服务序列、XX技师序列 = 1 年,其他序列 = 3 年 |
两级判定:
1. **已达龄**:操作当天 ≥ 退休日;
2. **新签合同超龄**:未达龄,但新合同估算终止日 ≥ 退休日
(估算起点 = 实际离职日期(=试用期到期日期)+1 天,终止日 = 起始 + 期限 - 1 天)。
两类都算"超龄",走子分支1;都未超龄走子分支2。
### 子分支1:超龄记录(照常办离职与延期转正,仅不自动新签合同)
1. 发起「调动解除(电子签)」流程;
2. 完善信息:**「是否需要新签合同」= 否**(超龄/未超龄一律填否,新签全由独立分支延后办理)、
实际离职日期 = 试用期到期日期;
3. 先检测该员工离职电子签流程是否已发起(断点续跑保护,见下):
未发起 → 发起电子签流程(员工真实 CA 签署);
已发起 → 跳过发起,记下实际发起日期;
发起失败 → 记录异常,**变更试用期仍继续**(实测变更试用期不依赖电子签完成);
4. 变更试用期:新试用期(月) = 1、新试用结束日期 = 原试用期结束日期 + 1 个月;
5. 进入【变更/转正待确认】页面,找到该员工记录后进行确认;
6. 上述环节完成后,AI表格回填「人资是否处理 = 是、离职推送时间 = 电子签实际发起当天」;
7. **新签合同不进入自动化流程**,只记录异常转人工:
- 已达龄 → 人工新签超龄用工协议;
- 新签合同超龄 → 人工分段新签(先签至退休日前,退休后另签超龄用工协议)。
### 子分支2:未超龄记录
第 1~6 步与子分支1完全相同,完善信息同样「是否需要新签合同 = 否」
差异:电子签不是马上完成的(员工 CA 签署需要时间),所以**新签合同是分阶段的独立分支**,不在本次运行立即签,等后续运行检测(见下)。
**断点续跑说明**:回填「人资是否处理=是」之前的任何环节失败,记录下次运行会被重新捞出。
重处理时先检测该员工离职电子签流程是否已发起:已发起 → 不再重复发起,
跳过发起环节,继续补齐变更试用期 / 确认 / 回填
(离职推送时间取电子签实际发起日期,而非本次操作日期)。
## 新签合同分支(独立阶段,每次运行执行)
选择条件(AI表格):**人资是否处理 = 是 且 离职推送时间不为空 且 新合同推送日期为空**,
且工号不在异常记录表(超龄)名单中。
1. 查该员工离职电子签流程状态:已全部办结?未办结 → 跳过,等下一次运行再检测;
2. 查合同台账【生效中合同】:无生效中合同?仍有 → 跳过,等下一次运行再检测;
3. 在【劳动关系→合同台账→未签合同】按工号查询该员工:
已办结但查无此人 = 旧合同解除尚未生效/数据未同步 → 跳过,等下一次运行(不按"无需处理"漏掉);
4. 存在则点击「新签」:
- 合同类型 = 劳动合同;期限按序列(服务/技师序列 1 年,其他 3 年);
- 起始日期 = 上一份合同终止/解除日期 + 1 天,终止日期 = 起始 + 期限 - 1 天;
(签署前复核:终止日 ≥ 退休日 → 记录异常,不签,转人工)
- 合同签署单位 = AI表格「合同签署单位」;
- 电子签期望推送时间 = 操作当天;
5. 成功后 AI表格写入「新合同推送日期 = 操作当天」;
6. 推送后合同是否已签署生效,由下方「签署生效复核分支」独立检测回填。
## 签署生效复核分支(独立阶段,每次运行执行)
新签合同推送后,需复核合同是否已签署生效(同时覆盖自动新签与超龄人工新签两种情形)。
选择条件(AI表格):**人资是否处理 = 是 且 签署跟进 ≠ 是**。
1. 到合同台账【生效中合同】按工号查询;
2. 用「合同起始日期 > 试用期到期日期」判断是否为新合同:
旧合同起始日必然早于试用期到期日(先签合同后进试用期),
新合同起始日必然晚于试用期到期日(离职后才签);
3. 查到起始日期晚于试用期到期日期的生效中合同 → 新合同已签署生效,
AI表格回填「签署跟进 = 是」;
4. 只查到旧合同(起始日期 ≤ 试用期到期日期,离职解除尚未生效)或查无 →
尚未生效,跳过,等下一次运行再检测。
## 拆分方案
三个分支各自独立排程,互不依赖、单文件自包含
(登录 / AI表格读写等公共逻辑各自内置,允许少量重复换取完全解耦):
| 脚本 | 职责 | 建议排程 |
|---|---|---|
| 主流程 | 分支1回填否;分支2超龄判定 → 离职电子签(断点续跑)→ 变更试用期 → 确认 → 回填「人资是否处理」 | 每日 1 次(如 09:00) |
| 新签合同 | 新签分支:电子签办结 + 无生效中合同 + 不在异常表 → 新签 → 回填「新合同推送日期」 | 主流程后(如 09:30) |
| 生效复核 | 生效复核分支:生效中合同起始日 > 试用期到期日 → 回填「签署跟进 = 是」 | 新签脚本后(如 10:00) |
## 异常与消息
- 异常记录表:`D:\资料\人资\试用期变更\异常记录.xlsx`
(员工工号/姓名/异常类型/异常详情/记录时间;类型:已达法定退休年龄、超龄需分段、提交报错;同工号重复出现保留最新一条);
- 钉钉群消息四类:成功 / 跳过(已被他人处理)/ 超龄异常转人工 / 失败;
- 全局失败重试 3 次,仍失败才记录。
## 与当前脚本实现的差异(待改造项)
1. 回填时机:离职电子签(含发起前断点续跑检测)+ 变更试用期 + 确认完成后即回填
「人资是否处理=是 + 离职推送时间」,新签合同不再阻塞回填
(当前实现 = 包含新签在内的全部环节完成后才回填);
2. 新签合同:改为独立分支延后签(当前实现 = 发起电子签后同次运行立即签);
3. 超龄处理:超龄不再终止全流程,继续走解除/电子签/变更试用期/确认(完善信息与其他记录一致),
仅新签环节改为记录异常转人工(当前实现 = 已达龄直接终止);
4. 完善信息表单覆写「是否需要新签合同 = 否」(当前只覆写实际离职日期、其余透传;字段名已确认);
5. 分支2前置:到期能否考核通过未填写 → 先回填「不能」(当前未实现);
6. 签署生效复核分支:查生效中合同 + 起始日期判新旧 + 回填「签署跟进=是」(当前未实现);
7. 脚本拆分:按分支拆为主流程 / 新签合同 / 生效复核 3 个独立影刀脚本(当前 = 单文件全流程)。
## 已确认事项(2026-10-09)
- 回填时机:「人资是否处理=是」在离职电子签 + 变更试用期 + 确认完成后回填;
回填前检测电子签流程是否已发起(断点续跑,应对仅试用期变更失败的情况);
- 新签分支排除超龄记录:按异常记录表过滤(不改 AI表格结构);
- AI表格已有「签署跟进」列,无需加列;
- 超龄人工新签的记录,生效后同样自动回填「签署跟进=是」;
- 脚本形态:拆为 3 个独立影刀脚本(主流程 / 新签合同 / 生效复核);
- 完善信息表单字段名为「是否需要新签合同」,超龄/未超龄一律填"否"
(新签全部由新签合同分支延后办理,解除流程不自动带出新签)。
## 待需求方确认
(暂无,口径已全部确认。)
+2 -13
View File
@@ -374,21 +374,13 @@ def _init_db() -> None:
def _seed() -> None:
"""首次启动写入插件种子 + 默认管理员(puddy),并生成示例包。
"""首次启动写入默认管理员(puddy)。
不再种子 demo 普通账号(alice/bob 曾带弱口令入生产库),普通账号一律由管理员建号。
曾有的 seal_check 占位插件种子已移除(demo 遗留,会随服务重启复活,对真实插件清单造成干扰)。
"""
config.PKG_DIR.mkdir(exist_ok=True)
with _db() as conn:
conn.execute(
"INSERT IGNORE INTO plugins(id, name, latest_version) VALUES (%s, %s, %s)",
("seal_check", "考勤月报封存检查", "1.0.0"),
)
conn.execute(
"INSERT IGNORE INTO plugin_versions(plugin_id, version, filename, uploaded_at) "
"VALUES (%s, %s, %s, %s)",
("seal_check", "1.0.0", "seal_check_v1.0.0.zip", _now()),
)
# 默认管理员:仅作首次引导,密码随机生成并记入日志(不再硬编码 123456,P0 安全债)。
# 已有库不重跑本种子(INSERT IGNORE 幂等);生产环境建号后应立即改密。
for _acc, _dept in (("puddy", "IT"),):
@@ -399,9 +391,6 @@ def _seed() -> None:
"VALUES (%s, %s, %s, %s, %s)", (_acc, _hex, _salt, 1, _dept))
_LOGGER.warning("首次引导:初始管理员 %s 初始密码为 %s(请立即登录修改)", _acc, _pwd)
conn.commit()
pkg = config.PKG_DIR / "seal_check_v1.0.0.zip"
if not pkg.exists():
pkg.write_bytes(b"# placeholder controlplane package v1.0.0\n")
def _audit(account: str, action: str, target: str = "", detail: str = "") -> None:
File diff suppressed because it is too large Load Diff
+3 -2
View File
@@ -236,10 +236,11 @@ npm run pack # → dist-app/setup-37du-shell-<version>.exe(NSIS 静
- 每个人的 HR/OA 账号密码由本人在「个人中心 → 平台账号」填写(AES-256-GCM 本机加密,
存 `%LOCALAPPDATA%\37duAutomation\platform-creds\creds.json`),顶栏不再显示设备级平台徽章
- 平台会话 cookies 按账号隔离:`.sessions/<账号>/hr_cookies.json`、`oa_cookies.json`;
Python 共享模块(hr_login / oa_login / seal_data_export / roster_export_api / org_export /
Python 共享模块(hr_login_api / oa_login_api / seal_data_export / roster_export_api / org_export /
core.auth)通过 `PLATFORM_ACCOUNT` 环境变量解析各自的会话目录,未设置时沿用共享目录(兼容旧逻辑)
- 登录/登出:壳端 `platform-auth` 拉起 Python 登录子进程时注入 `PLATFORM_ACCOUNT`
与账号的 `hr_login_username/password`(个人账号密码优先,未配置回退共享 .env)
与账号的 `hr_login_username/password`(个人账号密码优先,未配置回退共享 .env);
登录为纯 requests 接口版(HR 含滑块接口破解),全程无浏览器
- 插件执行:runner 子进程同样注入 `PLATFORM_ACCOUNT`,插件内数据导出按当前登录账号的身份执行;
同平台并发闸键改为(账号, 平台)
- 接口:`GET /api/meta` 平台在线按当前账号返回;`GET /api/platforms/status` 返回当前账号
@@ -63,8 +63,10 @@ if (!app.requestSingleInstanceLock()) {
app.quit();
} else {
app.on("second-instance", () => {
if (mainWindow) {
if (mainWindow && !mainWindow.isDestroyed()) {
if (mainWindow.isMinimized()) mainWindow.restore();
// 收托盘走的是 hide():隐藏窗口不是 minimized,focus() 也唤不回,必须先 show()
mainWindow.show();
mainWindow.focus();
}
});
@@ -1,7 +1,7 @@
// 平台登录态(HR/OA):真实登录/登出/在线校验。
// 保持 Python 子进程执行登录自动化(壳内置 python/webhost/backend/shared 下的
// hr_login、oa_login,DrissionPage 滑块;自包含 vendor,不依赖老 webhost 底座),
// Node 壳只负责拉起子进程与解析结果。
// 保持 Python 子进程执行登录(壳内置 python/webhost/backend/shared 下的
// hr_login_api、oa_login_api,纯 requests 接口登录无浏览器;自包含 vendor,
// 不依赖老 webhost 底座),Node 壳只负责拉起子进程与解析结果。
// ★ 按账号隔离:每个登录账号拥有独立的会话目录(.sessions/<账号>/)与独立 HR/OA 账号密码,
// 子进程通过 PLATFORM_ACCOUNT 环境变量 + hr_login_username/password 注入各自身份。
"use strict";
@@ -182,7 +182,7 @@ async function isOnline(pid, account) {
return value;
}
// 真实登录:cookies 有效则复用(不弹浏览器),失效则浏览器自动化登录。
// 真实登录:cookies 有效则复用(不弹浏览器),失效则纯接口登录(无浏览器)。
// account:当前登录账号;其个人 HR/OA 账号密码通过环境变量注入登录子进程。
async function login(pid, account) {
if (!LABELS[pid]) throw Object.assign(new Error(`未知平台: ${pid}`), { status: 404 });
@@ -199,8 +199,8 @@ async function login(pid, account) {
try {
const snippet =
pid === "hr"
? `from webhost.backend.shared import hr_login; import json; print(json.dumps(hr_login.main({"force": False}), ensure_ascii=False))`
: `from webhost.backend.shared import oa_login; import json; print(json.dumps(oa_login.main(force=False), ensure_ascii=False))`;
? `from webhost.backend.shared import hr_login_api; import json; print(json.dumps(hr_login_api.main({"force": False}), ensure_ascii=False))`
: `from webhost.backend.shared import oa_login_api; import json; print(json.dumps(oa_login_api.main(force=False), ensure_ascii=False))`;
const out = await runPython(snippet, 5 * 60 * 1000, extraEnv);
const result = extractJson(out) || {};
const ok = !!result.success;
@@ -94,6 +94,9 @@ function pluginSchema(pluginId) {
uses_month: !!manifest.uses_month,
ui: !!manifest.ui,
platform: manifest.platform || "", // hr / oa / ""(前端平台徽章 + 运行并发闸按(账号,平台)隔离)
platforms: Array.isArray(manifest.platforms) && manifest.platforms.length
? manifest.platforms // 插件声明的全部平台依赖(运行前登录态预检按此逐个检查)
: manifest.platform ? [manifest.platform] : [], // 缺省回退单 platform 字段
min_runtime_version: manifest.minRuntimeVersion || "", // 版本兼容校验声明(安装时强校验,此处透传前端展示)
capabilities: manifest.capabilities || [],
permissions: manifest.permissions || {},
+29 -17
View File
@@ -14,6 +14,7 @@ const scheduler = require("./scheduler");
const licensing = require("./licensing");
const runHistory = require("./run-history");
const platformAuth = require("./platform-auth");
const platformCreds = require("./platform-creds");
const { HUB } = require("./hub");
const { makeLogger } = require("./logger");
@@ -67,26 +68,33 @@ function nsKey(account, platform) {
return `${account || "anon"}:${platform || "local"}`;
}
// 平台登录态预检(HR/OA):插件执行前检测该账号的平台登录态,
// 失效时自动拉起自动登录(platform-auth.login,Python 子进程滑块自动化;
// cookies 实际有效时不会弹浏览器)。登录成功继续执行,失败则本次运行报错,
// 提示用户去个人中心手动登录(手动登录入口保留,不冲突)。
// 在(账号, 平台)命名空间锁内调用,天然避免并发双开登录浏览器。
// 平台登录态预检(HR/OA):点击执行后、拉起插件前,按插件声明(plugin.json 的 platforms
// 数组,缺省回退 platform 单字段)逐个校验登录态(真实轻量 API 探测),失效时自动调
// platform-auth.login 纯接口补登(无浏览器,凭据来自平台账号配置)。任一平台补登失败
// 则本次运行直接报错中止,不进入插件执行。在(账号, 平台)命名空间锁内调用,天然避免
// 并发双开登录。
const PLATFORM_LABELS = { hr: "HR 系统", oa: "OA 系统" };
function pluginPlatforms(plugin) {
if (Array.isArray(plugin.platforms) && plugin.platforms.length) {
return plugin.platforms.filter((p) => PLATFORM_LABELS[p]);
}
const pid = plugin.platform;
return pid && PLATFORM_LABELS[pid] ? [pid] : [];
}
async function ensurePlatformSession(plugin, runId, account) {
const pid = plugin.platform;
if (!pid || !PLATFORM_LABELS[pid]) return; // 无平台要求(或未知平台)直接执行
if (await platformAuth.isOnline(pid, account)) return; // 登录态有效,直接执行
if (isUserStopped(runId)) throw new Error("用户已取消该排队任务");
const label = PLATFORM_LABELS[pid];
emitLog(runId, plugin.id, "INFO", `检测到${label}登录态失效,正在自动登录…(如需人工介入请观察弹出的浏览器窗口)`);
const r = await platformAuth.login(pid, account);
if (isUserStopped(runId)) throw new Error("用户已取消该排队任务"); // 登录期间用户点了停止
if (!r || !r.online) {
const msg = (r && r.message) || "登录未生效";
throw new Error(`${label}自动登录失败:${msg}。请在「个人中心 → 平台账号」手动登录后重试`);
for (const pid of pluginPlatforms(plugin)) {
if (await platformAuth.isOnline(pid, account)) continue; // 登录态有效,无需处理
if (isUserStopped(runId)) throw new Error("用户已取消该排队任务");
const label = PLATFORM_LABELS[pid];
emitLog(runId, plugin.id, "INFO", `检测到${label}登录态失效,正在自动登录…`);
const r = await platformAuth.login(pid, account);
if (isUserStopped(runId)) throw new Error("用户已取消该排队任务"); // 登录期间用户点了停止
if (!r || !r.online) {
const msg = (r && r.message) || "登录未生效";
throw new Error(`${label}自动登录失败:${msg}。请在「个人中心 → 平台账号」检查账号密码配置后重试`);
}
emitLog(runId, plugin.id, "INFO", `${label}自动登录成功,开始执行插件`);
}
emitLog(runId, plugin.id, "INFO", `${label}自动登录成功,开始执行插件`);
}
// 发布日志事件,并同步累积到"这一次运行"的记录里(结束后随运行历史落盘,供点击回放)
@@ -287,6 +295,10 @@ function startChild(plugin, fields, runId, account) {
PYTHONIOENCODING: "utf-8",
PYTHONUTF8: "1",
PLATFORM_ACCOUNT: account || "",
// 平台凭据:供插件内登录态失效时自动补登录(未配置的平台/账号不注入,
// 此时登录模块回退读共享 .env)
...(platformCreds.envFor(account, "hr") || {}),
...(platformCreds.envFor(account, "oa") || {}),
// 环境包插件加载器据此定位插件根(dev 直拉模式传了也无害)
PLUGINS_ROOT: config.pluginRoot(),
},
+3 -2
View File
@@ -693,7 +693,8 @@ async function refreshShellStatus() {
shellUpdate.value = s
const st = s.dl?.status || ''
if (lastDlStatus === 'downloading' && st === 'downloaded') {
updDlg.value = false // 弹窗开着时自动收起,顶部提示条转为「重启更新」
// 内网直链下载很快(80MB 秒下),延迟收窗让人看清 100% 完成态,再转顶部「重启更新」条
setTimeout(() => { updDlg.value = false }, 1500)
ElMessage.success(`新版本 v${s.new} 已下载完成,点击顶部「重启更新」完成升级`)
log('INFO', `客户端新版本 v${s.new} 已就绪,可重启更新`)
} else if (lastDlStatus === 'downloading' && st === 'failed') {
@@ -701,7 +702,7 @@ async function refreshShellStatus() {
}
lastDlStatus = st
} catch (_) {}
shellPollTimer = setTimeout(refreshShellStatus, updDl.value.status === 'downloading' ? 1200 : 15000)
shellPollTimer = setTimeout(refreshShellStatus, updDl.value.status === 'downloading' ? 400 : 15000)
}
function startShellPoll() {
if (shellPollTimer) return
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "37du-electron-shell",
"productName": "37du 自动化工作台",
"version": "1.0.6",
"version": "1.0.9",
"description": "37du 执行机 Node/Electron 客户端(替代 Python webhost 底座,插件保持 Python 子进程执行)",
"main": "electron/main.js",
"private": true,
@@ -4,7 +4,7 @@
- cookies 与 desktop/影刀版共用同一份共享文件(%LOCALAPPDATA%\37duAutomation\.sessions),
任一端登录成功后,webhost 直接复用,无需重复登录
- is_online():真实校验(轻量 API 校验 cookies 有效性),不是内存假状态
- login():真实登录(cookies 有效则秒级复用;失效则浏览器自动化滑块登录)
- login():真实登录(cookies 有效则秒级复用;失效则纯接口登录,无浏览器)
- build_session():从共享 cookies 构建 requests.Session,供插件直接调用 shared 数据模块
约定:webhost 只依赖 desktop/shared 的真源登录模块,不复制登录逻辑。
@@ -16,8 +16,8 @@ import os
import requests
from webhost.backend.shared import hr_login as _hr
from webhost.backend.shared import oa_login as _oa
from webhost.backend.shared import hr_login_api as _hr
from webhost.backend.shared import oa_login_api as _oa
from webhost.backend.shared import seal_data_export as _seal
_LABELS = {"hr": "HR 系统", "oa": "OA 系统"}
@@ -62,7 +62,7 @@ def is_online(pid: str) -> bool:
def login(pid: str) -> dict:
"""真实登录:cookies 有效则复用(不弹浏览器),失效则浏览器自动化登录。
"""真实登录:cookies 有效则复用(不弹浏览器),失效则纯接口登录(无浏览器)。
返回 {id, label, online, message}
"""
@@ -0,0 +1,490 @@
# -*- coding: utf-8 -*-
"""
@FileName: hr_login_api.py
@Description: HR 纯接口登录(无浏览器版),webhost 宿主壳平台登录模块。
与 webhost/backend/shared/hr_login.py(浏览器版)输出完全兼容:
- 登录态落盘同一文件 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json
(PLATFORM_ACCOUNT 存在时按账号隔离到 .sessions/<账号>/);
- cookies 结构一致(name/value/domain/path/...),各业务脚本零改动;
- 对外入口 main(args) 与返回结构 {success, cookie_path, message, relogin} 一致。
区别:全程 requests 接口完成登录(含滑块验证),不打开浏览器、无拖拽拟人。
登录链路(从登录页前端 JS 逆向 + 2025-10 实测验证):
1. GET /RedseaPlatform/ 建立 Session 基础 cookie(routeEhr/JSESSIONID);
2. GET /RedseaPlatform/captcha/get/verification/image.mob 取滑块图,返回
result = {shadeImage(带缺口背景 jpg b64), originImage(原始背景 jpg b64),
cutoutImage(55x55 拼图块 png b64), y(拼图块 top), x(恒 0)};
前端 CSS 固定 340x171 容器、background 原尺寸绘制 => 浏览器只显示原图
左上角 min(w,340) x min(h,171) 的窗口,坐标系 1:1,匹配前需先裁切到该窗口;
3. 定位缺口 x:
a) 首选 diff 法:|shadeImage - originImage| 最大连通域左边界 = 缺口 x
(两图同源成对,diff 定位最准,且天然免疫整图变换);
b) 兜底模板匹配法(与 hr_login.py 浏览器截图版同源算法);
两者互验:diff 可信用 diff,diff 缺失用模板,分歧过大判定本图不可信换图重取;
4. POST /RedseaPlatform/captcha/check/verification/result.mob?x=&y= 校验滑块(返回 true/false);
5. POST /RedseaPlatform/j_red_security_check/PW 提交登录:
form: MENU_TYPE=classic & sysCode=RedseaP & j_username & j_password=<AES密文> & x & y
header: Csrf-Token: RP(前端写死常量);
密码加密:AES-128-ECB + PKCS7,key='ps_uer_!@#BGYUJN'(前端硬编码),输出 base64;
成功判定:state != "0";失败 state == "0" 且 meg 为错误信息;
6. GET getCurUserInfo 校验会话有效后,cookies 落盘 hr_cookies.json。
配置(与 hr_login.py 一致,读共享 .env:%LOCALAPPDATA%\\37duAutomation\\.env):
hr_login_username=用户名
hr_login_password=密码
hr_validate_url=(可选)HR 会话校验接口 URL;默认使用 getCurUserInfo 接口
全局变量(影刀环境可用,webhost 宿主下静默跳过):
login_state 登录成功或缓存的 cookies 有效时写入 True,否则为 False
依赖:
pip install requests python-dotenv opencv-python-headless numpy pycryptodome
入口:
main(args) 平台登录调用入口(platform-auth.js / core.auth),args 传
{"force": true|false},返回 JSON 安全 dict
"""
import os
import json
import time
import random
import base64
import requests
import cv2
import numpy as np
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from dotenv import load_dotenv
# ================== 共享路径(与 hr_login.py 统一,按账号隔离) ==================
_APP_DATA_DIR = os.path.join(
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
'37duAutomation')
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
# 按账号隔离会话目录:PLATFORM_ACCOUNT 指定当前登录账号(壳/插件由执行机注入),
# 未设置时沿用共享目录(兼容影刀版/命令行直跑)
_ACCOUNT = os.getenv('PLATFORM_ACCOUNT', '').strip()
if _ACCOUNT:
_SESSIONS_DIR = os.path.join(_SESSIONS_DIR, _ACCOUNT)
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
def _load_shared_env():
"""统一加载配置:优先固定路径共享 .env,再兼容当前工作目录 .env 与系统变量。"""
if os.path.exists(SHARED_ENV_FILE):
load_dotenv(SHARED_ENV_FILE)
load_dotenv()
_load_shared_env()
# ================== 配置 ==================
BASE_URL = 'https://hr.37du.co'
LOGIN_URL = BASE_URL + '/RedseaPlatform/'
CAPTCHA_GET_URL = BASE_URL + '/RedseaPlatform/captcha/get/verification/image.mob'
CAPTCHA_CHECK_URL = BASE_URL + '/RedseaPlatform/captcha/check/verification/result.mob'
LOGIN_POST_URL = BASE_URL + '/RedseaPlatform/j_red_security_check/PW'
GET_CUR_USER_INFO_URL = BASE_URL + '/RedseaPlatform/PtUsers.mc?method=getCurUserInfo'
# 前端登录页硬编码:AES 密钥与 CSRF 常量
AES_KEY = b'ps_uer_!@#BGYUJN'
CSRF_TOKEN = 'RP'
USERNAME = os.getenv('hr_login_username', '')
PASSWORD = os.getenv('hr_login_password', '')
# 浏览器可见窗口(登录页 CSS:.imgBg 340x171 固定、background 原尺寸绘制)
VIEW_W = 340
VIEW_H = 171
RETRY_MAX = 5 # 单轮滑块重试次数(与浏览器版一致)
LOGIN_ROUND_MAX = 3 # 整轮登录最大重试(项目级重试机制)
TIMEOUT = 15
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"Chrome/120.0.0.0 Safari/537.36")
def ensure_dir(path):
if path:
os.makedirs(path, exist_ok=True)
# ================== Cookies 持久化(格式与 hr_login.py 兼容) ==================
def save_session_cookies(session):
"""requests.Session cookies -> [{name, value, domain, path, expires}, ...],
与 hr_login.py(DrissionPage page.cookies)落盘结构兼容,业务脚本零改动。"""
cookies = []
for c in session.cookies:
cookies.append({
"name": c.name,
"value": c.value,
"domain": c.domain,
"path": c.path or "/",
"expires": int(c.expires) if c.expires else None,
})
if not cookies:
print("未获取到 Cookies,跳过保存")
return
ensure_dir(_SESSIONS_DIR)
with open(COOKIE_FILE, 'w', encoding='utf-8') as f:
json.dump(cookies, f, ensure_ascii=False, indent=2)
print(f"已保存 {len(cookies)} 个 Cookies 到 {COOKIE_FILE}")
def load_cookies():
if not os.path.exists(COOKIE_FILE):
return None
with open(COOKIE_FILE, encoding='utf-8') as f:
cookies = json.load(f)
return cookies or None
# ================== 影刀全局变量 ==================
def _set_login_state(value):
"""写入影刀全局变量 login_state(影刀指令环境可用;独立运行/非影刀环境时静默跳过)。"""
try:
glv['login_state'] = value
print(f"已写入影刀全局变量 login_state={value}")
except Exception as e:
print(f"写入影刀全局变量 login_state 失败(非影刀环境?):{e}")
# ================== API 校验 cookies 有效性(与 hr_login.py 同款) ==================
def _is_hr_session_valid():
"""API 轻量校验 HR cookies:请求 hr_validate_url(默认 getCurUserInfo 接口),
返回 JSON 视为 cookies 有效;返回登录页等非 JSON 即视为失效。"""
validate_url = os.getenv('hr_validate_url', '').strip() or GET_CUR_USER_INFO_URL
try:
cookies = load_cookies()
if not cookies:
return False
session = requests.Session()
session.headers.update({
"User-Agent": UA,
"Content-Type": "application/x-www-form-urlencoded",
})
for c in cookies:
if c.get("domain") and "37du.co" in c["domain"]:
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
resp = session.post(validate_url, data={}, timeout=15)
if resp.status_code != 200:
print(f"API 校验 cookies 状态码异常:{resp.status_code}")
return False
text = resp.text
return bool(text) and text.lstrip().startswith(("{", "["))
except Exception as e:
print(f"API 校验 cookies 异常:{e}")
return False
# ================== 密码加密(前端 pubAesEncrypt 等价实现) ==================
def aes_encrypt_password(password):
"""AES-128-ECB + PKCS7,key 前端硬编码,输出 base64(与 CryptoJS encrypted.toString() 一致)。"""
cipher = AES.new(AES_KEY, AES.MODE_ECB)
return base64.b64encode(cipher.encrypt(pad(password.encode('utf-8'), 16))).decode('ascii')
# ================== 滑块图获取与裁切 ==================
def new_session():
"""建立会话:先访问登录页拿基础 cookie(routeEhr/JSESSIONID),验证码/登录绑定同一会话。"""
s = requests.Session()
s.headers.update({
"User-Agent": UA,
"Referer": LOGIN_URL,
"X-Requested-With": "XMLHttpRequest",
})
s.get(LOGIN_URL, timeout=TIMEOUT)
return s
def _b64_to_img(b64str, flag):
"""base64 -> cv2 图像(失败返回 None)。"""
if not b64str:
return None
try:
buf = base64.b64decode(b64str)
return cv2.imdecode(np.frombuffer(buf, np.uint8), flag)
except Exception:
return None
def _crop_view(img):
"""裁切到浏览器可见窗口(左上角 min(w,340) x min(h,171)),坐标系与浏览器 1:1。"""
if img is None:
return None
h, w = img.shape[:2]
return img[:min(h, VIEW_H), :min(w, VIEW_W)]
def get_captcha(session):
"""取滑块图,返回 dict(shade, origin, cutout, y);y 为拼图块 top(服务端给定)。"""
resp = session.get(CAPTCHA_GET_URL, timeout=TIMEOUT)
data = resp.json()
res = data.get("result") or {}
shade = _crop_view(_b64_to_img(res.get("shadeImage"), cv2.IMREAD_COLOR))
origin = _crop_view(_b64_to_img(res.get("originImage"), cv2.IMREAD_COLOR))
cutout = _b64_to_img(res.get("cutoutImage"), cv2.IMREAD_UNCHANGED)
y = int(res.get("y") or 0)
return {"shade": shade, "origin": origin, "cutout": cutout, "y": y}
# ================== 缺口定位 ==================
def locate_by_diff(shade, origin):
"""diff 法:shade/origin 同源成对,逐像素差异的最大连通域左边界 = 缺口 x。
返回 (x, 可信度说明);不可信返回 (None, 原因)。"""
if shade is None or origin is None or shade.shape != origin.shape:
return None, "图片缺失或尺寸不一致"
diff = cv2.absdiff(shade, origin).max(axis=2)
mask = (diff > 30).astype(np.uint8) * 255
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8))
n, _, stats, _ = cv2.connectedComponentsWithStats(mask)
if n <= 1:
return None, "无差异区域"
best = max(range(1, n), key=lambda i: stats[i, cv2.CC_STAT_AREA])
area = int(stats[best, cv2.CC_STAT_AREA])
x = int(stats[best, cv2.CC_STAT_LEFT])
# 缺口约 55x55(面积 ~3000),过大/过小视为 jpg 噪声或异常
if area < 300 or area > 12000:
return None, f"差异区域面积异常({area})"
return x, f"diff(area={area})"
def match_slider_dual(bg_img, slider_color):
"""模板匹配滑块缺口,返回物理距离 px。
算法与 hr_login.py 浏览器截图版同源(边缘 Canny + TM_CCOEFF_NORMED + 白区加权)。"""
if bg_img is None or slider_color is None:
return None
bg_h, bg_w = bg_img.shape[:2]
x_offset = 0
if len(slider_color.shape) == 3 and slider_color.shape[2] == 4:
alpha = slider_color[:, :, 3]
slider_rgb = slider_color[:, :, :3]
ys, xs = np.where(alpha > 0)
if len(ys) > 0:
y_min, y_max = np.min(ys), np.max(ys)
x_min, x_max = np.min(xs), np.max(xs)
slider_rgb = slider_rgb[y_min:y_max + 1, x_min:x_max + 1]
x_offset, _ = x_min, np.min(ys)
else:
slider_rgb = slider_color[:, :, :3] if len(slider_color.shape) == 3 else slider_color
s_h, s_w = slider_rgb.shape[:2]
if s_h <= 0 or s_w <= 0 or s_w >= bg_w or s_h >= bg_h:
return None
gray_bg = cv2.GaussianBlur(cv2.cvtColor(bg_img, cv2.COLOR_BGR2GRAY), (3, 3), 0)
gray_slider = cv2.GaussianBlur(cv2.cvtColor(slider_rgb, cv2.COLOR_BGR2GRAY), (3, 3), 0)
bg_edges = cv2.Canny(gray_bg, 50, 150)
slider_edges = cv2.Canny(gray_slider, 50, 150)
result = cv2.matchTemplate(bg_edges, slider_edges, cv2.TM_CCOEFF_NORMED)
candidates = []
temp_result = result.copy()
for _ in range(6):
_, max_val, _, max_loc = cv2.minMaxLoc(temp_result)
if max_val < 0.03:
break
candidates.append((max_val, max_loc))
y0 = max(0, max_loc[1] - s_h // 2); y1 = min(temp_result.shape[0], max_loc[1] + s_h // 2)
x0 = max(0, max_loc[0] - s_w // 2); x1 = min(temp_result.shape[1], max_loc[0] + s_w // 2)
temp_result[y0:y1, x0:x1] = -2.0
if not candidates:
return None
right_limit = bg_w - s_w - max(15, int(bg_w * 0.06))
def region_whiteness(x, y, w, h):
roi = bg_img[y:y + h, x:x + w]
if roi.size == 0:
return 0.0
return float(np.all(roi > 200, axis=2).mean())
scored = []
for val, loc in candidates:
x, y = loc
if x <= s_w or x > right_limit:
continue
scored.append((val + 0.5 * region_whiteness(x, y, s_w, s_h), val, loc))
if scored:
scored.sort(key=lambda t: t[0], reverse=True)
best_loc = scored[0][2]
else:
best_loc = candidates[0][1]
distance = best_loc[0] - x_offset
if distance < 0:
distance = 0
if distance + s_w > bg_w:
distance = bg_w - s_w
return distance
def solve_distance(cap):
"""定位缺口并输出应提交的 x(= 滑块从 0 到缺口的距离,即缺口左边界 - 拼图透明边)。
返回 (x, 说明);本图不可信返回 (None, 原因)。
几何说明(与浏览器画面一致):
- 原图宽 >= 340:浏览器只显示左上 340x171 裁切窗口;
- 原图宽 < 340:.imgBg 的 background 默认 repeat 会把原图复制拼接到右侧,
画面上缺口可能出现副本(x_g 与 x_g+原图宽),但服务端记录的是原图缺口
坐标 x_g,提交 x_g 即可通过;
因此匹配始终在原图(裁切后)上进行——拼接成画面等价图反而会让 diff 出双峰
(副本也带缺口)——越界过滤上限用实际图宽。
"""
shade = cap["shade"]
cutout = cap["cutout"]
s_w = cutout.shape[1] if cutout is not None else 55
view_w = shade.shape[1] if shade is not None else VIEW_W
x_diff, info = locate_by_diff(cap["shade"], cap["origin"])
x_tpl = match_slider_dual(cap["shade"], cutout)
print(f" 缺口定位:{info} diff_x={x_diff} tpl_x={x_tpl}")
x, how = None, "无法定位"
if x_diff is not None and x_tpl is not None and abs(x_diff - x_tpl) <= 12:
x, how = x_diff, "diff+tpl 一致"
elif x_diff is not None:
x, how = x_diff, "仅 diff(与模板分歧)"
elif x_tpl is not None:
x, how = x_tpl, "仅模板"
if x is None:
return None, how
# 合理性校验:缺口不会贴最左/最右(贴边缺口可能是平铺坐标映射产物,直接换图)
if x <= s_w or x > view_w - s_w:
return None, f"缺口位置越界({x}, 图宽{view_w})"
return x, how
# ================== 滑块校验与登录提交 ==================
def check_slider(session, x, y):
"""提交滑块校验,返回 True/False。"""
resp = session.post(CAPTCHA_CHECK_URL, params={"x": int(round(x)), "y": int(y)}, timeout=TIMEOUT)
try:
return bool(resp.json())
except Exception:
return False
def submit_login(session, username, password, x, y):
"""提交登录,返回 (ok, message)。"""
form = {
"MENU_TYPE": "classic",
"sysCode": "RedseaP",
"j_username": username,
"j_password": aes_encrypt_password(password),
"x": int(round(x)),
"y": int(y),
}
headers = {"Csrf-Token": CSRF_TOKEN}
resp = session.post(LOGIN_POST_URL, data=form, headers=headers, timeout=TIMEOUT)
try:
result = resp.json()
except Exception:
return False, f"登录响应非 JSON(HTTP {resp.status_code})"
if result.get("state") == "0":
return False, str(result.get("meg") or "登录失败")
return True, "登录成功"
def do_login_api(username, password):
"""完整接口登录:滑块校验(带重试)+ 提交登录。成功返回 True。"""
for rnd in range(LOGIN_ROUND_MAX):
print(f"--- 第 {rnd + 1} 轮登录(接口版) ---")
try:
session = new_session()
except Exception as e:
print(f"建立会话异常:{e}")
time.sleep(1)
continue
for attempt in range(RETRY_MAX):
print(f"--- 第 {attempt + 1} 次尝试验证 ---")
try:
cap = get_captcha(session)
except Exception as e:
print(f"取验证码图异常:{e}")
time.sleep(1)
continue
shade = cap["shade"]
y = cap["y"]
# y 用实际图高校验(裁切窗口高 = min(图高, 171),小图场景更严谨)
if shade is None or not (0 <= y <= shade.shape[0] - 55):
print(f"验证码图异常(shade={None if shade is None else shade.shape}, y={y})")
time.sleep(0.5)
continue
x, info = solve_distance(cap)
if x is None:
time.sleep(random.uniform(0.3, 0.8))
continue
print(f" 提交滑块校验 x={x} y={y}({info})")
if check_slider(session, x, y):
print(" 滑块校验通过")
ok, msg = submit_login(session, username, password, x, y)
if ok:
save_session_cookies(session)
return True
print(f"登录失败:{msg}")
return False # 账号密码类错误,重试无意义
else:
print(" 滑块校验未通过,换图重试")
time.sleep(random.uniform(0.5, 1.2))
time.sleep(1)
return False
# ================== 登录主入口(与 hr_login.py 同构) ==================
def ensure_login(force=False):
"""
确保存在有效的 HR 登录态并缓存 cookies(纯接口,无浏览器)。
返回 JSON 安全 dict:{success, cookie_path, message, relogin}
"""
_load_shared_env()
_set_login_state(False)
if not (USERNAME and PASSWORD):
return {"success": False, "cookie_path": COOKIE_FILE,
"message": "登录配置缺失(hr_login_username / hr_login_password 未配置)", "relogin": False}
# 优先复用已保存的 cookies(通过 API 校验有效性,无需登录)
if not force and _is_hr_session_valid():
print("已通过缓存的 Cookies 复用 HR 登录态")
_set_login_state(True)
return {"success": True, "cookie_path": COOKIE_FILE,
"message": "复用缓存登录态", "relogin": False}
ok = do_login_api(USERNAME, PASSWORD)
if ok:
# 登录后校验一次会话有效性,确保落盘的 cookies 可用
if _is_hr_session_valid():
_set_login_state(True)
return {"success": True, "cookie_path": COOKIE_FILE, "message": "登录成功", "relogin": True}
return {"success": False, "cookie_path": COOKIE_FILE,
"message": "登录接口返回成功但会话校验未通过", "relogin": False}
return {"success": False, "cookie_path": COOKIE_FILE,
"message": "登录失败(滑块验证未通过或接口异常)", "relogin": False}
# ================== 调用入口 ==================
def main(args):
"""
平台登录调用入口。
args: dict,可选字段 force(bool) 是否强制重新登录
返回: dict {success, cookie_path, message, relogin}
"""
if not args:
args = {}
force = bool(args.get("force", False))
try:
return ensure_login(force=force)
except Exception as e:
return {"success": False, "cookie_path": COOKIE_FILE,
"message": f"登录过程异常:{e}", "relogin": False}
if __name__ == "__main__":
result = main({"force": False})
print("最终结果:", result)
@@ -0,0 +1,326 @@
# -*- coding: utf-8 -*-
"""
@FileName: oa_login_api.py
@Description: OA 纯接口登录(无浏览器版),webhost 宿主壳平台登录模块。
与 webhost/backend/shared/oa_login.py(浏览器版)输出完全兼容:
- 登录态落盘同一文件 %LOCALAPPDATA%\\37duAutomation\\.sessions\\oa_cookies.json
(PLATFORM_ACCOUNT 存在时按账号隔离到 .sessions/<账号>/);
- cookies 结构一致(name/value/domain/path/...),各业务脚本零改动;
- 配置读取一致(共享 .env 的 oa_login_username / oa_login_password);
- 对外入口 main(force) 与返回结构 {success, cookie_path, message, relogin} 一致。
区别:全程 requests 接口完成登录,不打开浏览器。
登录链路(蓝凌 EKP security.js 逆向 + 2026-10 实测验证):
1. GET /login.jsp 建立 Session 基础 cookie(SESSION/sl-session);
2. GET /resource/js/session.jsp?_=时间戳 服务端按会话下发密钥串:
window.getSessionId = function(){ return "<36位UUID>"; }
同一会话内固定,登录 POST 必须与本次取密钥同会话;
3. 密码加密(复刻 security.js desEncrypt 的 des 分支,浏览器默认走 sm2 分支,
但密文前缀带算法标记、服务端按标记选算法解密,des 同样受支持):
a) 密钥串不足 16 位补 "abcdefghijklmnopqrstuvwxyz",再 toUpperCase;
b) key = 前 8 字符 toHexString、iv = 第 8~16 字符 toHexString
(toHexString = 逐字符 charCode 转 16 进制拼接,ASCII 即 .encode().hex());
c) DES-CBC + PKCS7 加密密码,输出 base64;
d) j_password = 标记前缀 "\\u4445\\u5320\\u4d45" + base64 密文;
4. POST /j_acegi_security_check form: j_username & j_password & j_redirectto(空)
成功 302 跳转(实测跳 "/",浏览器端再由前端跳 /sys/portal/page.jsp);
5. GET sysNotifyTodo.do?method=sumTodoCount 校验会话有效后,cookies 落盘 oa_cookies.json
(返回 JSON 视为有效,被重定向回登录页返回 HTML 即失效)。
配置(与 oa_login.py 一致,读共享 .env:%LOCALAPPDATA%\\37duAutomation\\.env):
oa_login_username=用户名
oa_login_password=密码
oa_validate_url=(可选)OA 会话校验接口 URL;默认使用 sumTodoCount 待办统计接口
全局变量(影刀环境可用,webhost 宿主下静默跳过):
login_state 登录成功或缓存的 cookies 有效时写入 True,否则为 False
依赖:
pip install requests python-dotenv pycryptodome
入口:
main(force) 平台登录调用入口(platform-auth.js / core.auth),force 传 True/False,
返回 JSON 安全 dict
"""
import os
import re
import json
import time
import base64
import requests
from Crypto.Cipher import DES
from Crypto.Util.Padding import pad
from dotenv import load_dotenv
# ================== 共享路径(与 oa_login.py 统一,按账号隔离) ==================
_APP_DATA_DIR = os.path.join(
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
'37duAutomation')
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
# 按账号隔离会话目录:PLATFORM_ACCOUNT 指定当前登录账号(壳/插件由执行机注入),
# 未设置时沿用共享目录(兼容影刀版/命令行直跑)
_ACCOUNT = os.getenv('PLATFORM_ACCOUNT', '').strip()
if _ACCOUNT:
_SESSIONS_DIR = os.path.join(_SESSIONS_DIR, _ACCOUNT)
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
def _load_shared_env():
"""统一加载配置:优先固定路径共享 .env,再兼容当前工作目录 .env 与系统变量。"""
if os.path.exists(SHARED_ENV_FILE):
load_dotenv(SHARED_ENV_FILE)
load_dotenv()
_load_shared_env()
# ================== 配置 ==================
BASE_URL = 'https://oa.37du.co'
LOGIN_URL = BASE_URL + '/login.jsp'
SESSION_KEY_URL = BASE_URL + '/resource/js/session.jsp'
LOGIN_POST_URL = BASE_URL + '/j_acegi_security_check'
# OA 会话校验接口:cookies 有效时返回 JSON,失效时被重定向到登录页返回 HTML
TODO_COUNT_URL = BASE_URL + "/sys/notify/sys_notify_todo/sysNotifyTodo.do"
USERNAME = os.getenv('oa_login_username', '')
PASSWORD = os.getenv('oa_login_password', '')
# security.js 密码加密常量(逆向自 /resource/js/security.js,Dean Edwards packer 混淆已还原)
DES_MARKER = "\u4445\u5320\u4d45" # des 分支密文标记前缀(服务端按标记选算法)
DES_PADDING = "abcdefghijklmnopqrstuvwxyz" # 密钥串不足 16 位时的补齐串
SESSION_KEY_RE = re.compile(
r'getSessionId\s*=\s*function\s*\(\s*\)\s*\{\s*return\s*"([^"]*)"')
LOGIN_ROUND_MAX = 3 # 整轮登录最大重试(项目级重试机制)
TIMEOUT = 15
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"Chrome/120.0.0.0 Safari/537.36")
def ensure_dir(path):
if path:
os.makedirs(path, exist_ok=True)
# ================== Cookies 持久化(格式与 oa_login.py 兼容) ==================
def save_session_cookies(session):
"""requests.Session cookies -> [{name, value, domain, path, expires}, ...],
与 oa_login.py(DrissionPage page.cookies)落盘结构兼容,业务脚本零改动。"""
cookies = []
for c in session.cookies:
cookies.append({
"name": c.name,
"value": c.value,
"domain": c.domain,
"path": c.path or "/",
"expires": int(c.expires) if c.expires else None,
})
if not cookies:
print("未获取到 Cookies,跳过保存")
return
ensure_dir(_SESSIONS_DIR)
with open(COOKIE_FILE, 'w', encoding='utf-8') as f:
json.dump(cookies, f, ensure_ascii=False, indent=2)
print(f"已保存 {len(cookies)} 个 Cookies 到 {COOKIE_FILE}")
def load_cookies():
if not os.path.exists(COOKIE_FILE):
return None
with open(COOKIE_FILE, encoding='utf-8') as f:
cookies = json.load(f)
return cookies or None
# ================== 影刀全局变量 ==================
def _set_login_state(value):
"""写入影刀全局变量 login_state(影刀指令环境可用;独立运行/非影刀环境时静默跳过)。"""
try:
glv['login_state'] = value
print(f"已写入影刀全局变量 login_state={value}")
except Exception as e:
print(f"写入影刀全局变量 login_state 失败(非影刀环境?):{e}")
# ================== 会话校验(与 oa_login.py 同款逻辑) ==================
def _is_todo_count_json(resp):
"""sumTodoCount 响应判定:200 且返回 JSON 视为登录态有效。"""
try:
return (resp.status_code == 200 and bool(resp.text)
and resp.text.lstrip().startswith(("{", "[")))
except Exception:
return False
def _is_oa_session_valid():
"""API 轻量校验 OA cookies:请求 oa_validate_url(默认 sumTodoCount 待办统计接口),
返回 JSON 视为 cookies 有效;被重定向到登录页返回 HTML 即视为失效。
与 oa_login.py 及业务脚本使用同一套接口与校验逻辑。"""
validate_url = os.getenv('oa_validate_url', '').strip() or TODO_COUNT_URL
try:
cookies = load_cookies()
if not cookies:
return False
session = requests.Session()
session.headers.update({
"User-Agent": UA,
"Content-Type": "application/x-www-form-urlencoded",
})
for c in cookies:
if c.get("domain") and "37du.co" in c["domain"]:
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
resp = session.get(validate_url, params={"method": "sumTodoCount"}, timeout=15)
if resp.status_code != 200:
print(f"API 校验 cookies 状态码异常:{resp.status_code}")
return False
return _is_todo_count_json(resp)
except Exception as e:
print(f"API 校验 cookies 异常:{e}")
return False
def check_session_alive(session):
"""用当前登录会话直接校验(登录后、落盘前使用)。"""
validate_url = os.getenv('oa_validate_url', '').strip() or TODO_COUNT_URL
try:
resp = session.get(validate_url, params={"method": "sumTodoCount"}, timeout=15)
return _is_todo_count_json(resp)
except Exception as e:
print(f"会话校验异常:{e}")
return False
# ================== 密码加密(复刻 security.js desEncrypt 的 des 分支) ==================
def to_hex_str(text):
"""复刻 security.js 的 toHexString:逐字符 charCode 转 16 进制(小写、无补零)拼接。"""
return ''.join(format(ord(ch), 'x') for ch in text)
def fetch_session_key(session):
"""GET session.jsp 取服务端按会话下发的密钥串(同会话固定)。"""
url = f"{SESSION_KEY_URL}?_={int(time.time() * 1000)}"
resp = session.get(url, timeout=TIMEOUT)
m = SESSION_KEY_RE.search(resp.text)
return m.group(1) if m else ""
def des_encrypt_password(session, password):
"""返回可直接提交的 j_password:标记前缀 + DES-CBC-PKCS7 base64 密文。
密钥派生:密钥串不足 16 位补齐 -> 大写 -> key/iv 各取 8 字符 toHexString。"""
sid = fetch_session_key(session)
if not sid:
raise RuntimeError("session.jsp 未返回 getSessionId 密钥串")
b = sid
if len(b) < 16:
b += DES_PADDING
b = b.upper()
key = bytes.fromhex(to_hex_str(b[:8]))
iv = bytes.fromhex(to_hex_str(b[8:16]))
cipher = DES.new(key, DES.MODE_CBC, iv)
ct = base64.b64encode(cipher.encrypt(pad(password.encode('utf-8'), 8))).decode('ascii')
return DES_MARKER + ct
# ================== 登录主流程 ==================
def new_session():
"""建立会话:先访问登录页拿基础 cookie(SESSION/sl-session),取密钥与登录绑定同一会话。"""
s = requests.Session()
s.headers.update({"User-Agent": UA})
s.get(LOGIN_URL, timeout=TIMEOUT)
return s
def do_login_api(username, password):
"""完整接口登录:取密钥 -> DES 加密 -> 表单提交 -> 会话校验。返回 (ok, message)。"""
for rnd in range(LOGIN_ROUND_MAX):
print(f"--- 第 {rnd + 1} 轮登录(接口版) ---")
try:
session = new_session()
except Exception as e:
print(f"建立会话异常:{e}")
time.sleep(1)
continue
try:
j_password = des_encrypt_password(session, password)
except Exception as e:
print(f"获取会话密钥/加密异常:{e}")
time.sleep(1)
continue
try:
resp = session.post(
LOGIN_POST_URL,
data={"j_username": username, "j_password": j_password, "j_redirectto": ""},
headers={"Referer": LOGIN_URL, "Origin": BASE_URL},
timeout=TIMEOUT, allow_redirects=True)
except Exception as e:
print(f"提交登录异常:{e}")
time.sleep(1)
continue
final_url = str(resp.url)
if "login.jsp" in final_url:
# Acegi 拒绝(凭据错误/解密失败)会重定向回登录页,重试无意义
return False, f"登录被拒绝(用户名或密码错误?):{final_url}"
if check_session_alive(session):
save_session_cookies(session)
return True, "登录成功"
print(f"登录后会话校验未通过,最终URL:{final_url}")
time.sleep(1)
return False, "登录失败(重试耗尽或接口异常)"
# ================== 登录主入口(与 oa_login.py 同构) ==================
def ensure_login(force=False):
"""
确保存在有效的 OA 登录态并缓存 cookies(纯接口,无浏览器)。
返回 JSON 安全 dict:{success, cookie_path, message, relogin}
"""
_load_shared_env()
_set_login_state(False)
if not (USERNAME and PASSWORD):
return {"success": False, "cookie_path": COOKIE_FILE,
"message": "登录配置缺失(oa_login_username / oa_login_password 未配置)", "relogin": False}
# 优先复用已保存的 cookies(通过 API 校验有效性,无需登录)
if not force and _is_oa_session_valid():
print("已通过缓存的 Cookies 复用 OA 登录态")
_set_login_state(True)
return {"success": True, "cookie_path": COOKIE_FILE,
"message": "复用缓存登录态", "relogin": False}
ok, msg = do_login_api(USERNAME, PASSWORD)
if ok:
# 登录后校验一次落盘 cookies 可用性,确保业务脚本拿到的登录态真实有效
if _is_oa_session_valid():
_set_login_state(True)
return {"success": True, "cookie_path": COOKIE_FILE, "message": "登录成功", "relogin": True}
return {"success": False, "cookie_path": COOKIE_FILE,
"message": "登录接口返回成功但会话校验未通过", "relogin": False}
return {"success": False, "cookie_path": COOKIE_FILE, "message": msg, "relogin": False}
# ================== 调用入口(与 oa_login.py 契约一致) ==================
def main(force=True):
"""
平台登录调用入口。
force: bool 是否强制重新登录
返回: dict {success, cookie_path, message, relogin}
"""
try:
return ensure_login(force=force)
except Exception as e:
return {"success": False, "cookie_path": COOKIE_FILE,
"message": f"登录过程异常:{e}", "relogin": False}
if __name__ == "__main__":
result = main(force=True)
print("最终结果:", result)
@@ -24,7 +24,9 @@
依赖安装(启动校验:必须预先装齐):
pip install requests pandas openpyxl python-dotenv
运行前置:需存在「37duHR登录」写入的共享登录态(hr_cookies.json)。
运行前置:无需预先登录——无共享登录态或登录态失效时,宿主(webhost)环境会
自动调用内置接口版登录(hr_login_api,无浏览器)补登录;影刀环境需先运行
「37duHR登录(接口版)」指令。
环境变量(可选):
monthly_seal_save_dir 输出目录(默认 D:\\资料\\人资\\考勤异常)
@@ -160,12 +162,26 @@ def _load_shared_hr_cookies():
return json.load(f) or None
def _force_relogin():
"""登录态缺失/失效时自动补登录:调用宿主内置接口版登录(无浏览器,凭据来自
执行机注入的环境变量或共享 .env)。影刀等无宿主环境时抛出带指引的 RuntimeError。"""
try:
from webhost.backend.shared import hr_login_api
except ImportError:
raise RuntimeError(
"HR 登录态缺失或已失效,且当前环境无内置接口登录模块。\n"
"请先调用「37duHR登录(接口版)」指令完成登录,再运行本模块")
result = hr_login_api.ensure_login(force=True)
if not result.get("success"):
raise RuntimeError(f"HR 自动补登录失败:{result.get('message')}")
logger.info("HR 自动补登录成功")
def _ensure_hr_cookies():
if _load_shared_hr_cookies():
return True
raise RuntimeError(
"未找到 HR 登录态(hr_cookies.json)或已失效。\n"
"请在影刀流程开头先调用「37duHR登录」指令,或本地先运行 python workflows/share/hr_login.py")
_force_relogin()
return True
def build_hr_session():
@@ -213,8 +229,8 @@ def fetch_cur_user_info(session):
def _relogin_get_user_id():
"""登录态失效后:重建会话 → 重新获取 userId。"""
_ensure_hr_cookies()
"""登录态失效后:强制补登录 → 重建会话 → 重新获取 userId。"""
_force_relogin()
session = build_hr_session()
info = fetch_cur_user_info(session)
return session, _clean(info.get("userId"))
@@ -361,9 +377,14 @@ def export_seal_data(month: str = None) -> List[dict]:
yearmonth = ym.replace("-", "")
logger.info("===== 封存数据导出与预处理,月份:%s =====", ym)
# 1. 拉取当月全集团封存数据(base_code 留空批量)
# 1. 拉取当月全集团封存数据(base_code 留空批量);缓存 cookies 失效时自动补登录重试
session = build_hr_session()
user_id = _clean(fetch_cur_user_info(session).get("userId"))
try:
user_id = _clean(fetch_cur_user_info(session).get("userId"))
except HRSessionExpiredError:
_force_relogin()
session = build_hr_session()
user_id = _clean(fetch_cur_user_info(session).get("userId"))
if not user_id:
raise RuntimeError("获取当前用户 userId 失败")
seal_rows = fetch_all_seal(session, user_id, yearmonth)
@@ -1,4 +1,4 @@
# Build portable Python + environment package (python-env-<version>.zip)
# Build portable Python + environment package (python-env-<version>.zip)
# ============================================================================
# Purpose: give the packaged Electron client a self-contained Python runtime so
# plugins and platform-login no longer depend on an external Python install.
@@ -41,7 +41,7 @@ $PipIndex = $null # e.g. "https://pypi.tuna.tsinghua.ed
# All dependencies (top-level + key transitive), pinned to .venv-validated versions
$Pinned = @(
"requests==2.34.2", "python-dotenv==1.2.2", "cryptography==50.0.1",
"requests==2.34.2", "python-dotenv==1.2.2", "cryptography==50.0.1", "pycryptodome==3.24.0",
"pandas==3.0.5", "numpy==2.3.5", "openpyxl==3.1.5",
"python-dateutil==2.9.0.post0", "tzdata==2026.3", "et-xmlfile",
"websocket-client==1.9.0",
@@ -191,7 +191,7 @@ Get-ChildItem -Path (Join-Path $Wb "shared") -Filter "*.py" | ForEach-Object {
# ---------- 4. smoke test ----------
Write-Host "=== smoke test ===" -ForegroundColor Cyan
& $PyExe -c "import sys; print(' python:', sys.version.split()[0])" | Out-Host
& $PyExe -c "import requests,pandas,numpy,openpyxl,websocket,dotenv,cryptography; print(' core deps ok')" | Out-Host
& $PyExe -c "import requests,pandas,numpy,openpyxl,websocket,dotenv,cryptography,Crypto,cv2; print(' core deps ok')" | Out-Host
if ($LASTEXITCODE -ne 0) { throw "core deps import failed" }
& $PyExe -c "import DrissionPage; print(' DrissionPage', DrissionPage.__version__)" | Out-Host
& $PyExe -c "import ddddocr; print(' ddddocr ok')" | Out-Host
+74
View File
@@ -0,0 +1,74 @@
# fileserver(37du 内网文件服务器)管理页 + 服务
文件服务器(FastAPI,端口 8802):存放大文件(壳子包/Chrome 包等),执行机内网直连下载。
配套 Vue3 管理页面(经 Nginx,端口 **8899**):查看/上传/下载/删除,展示上传时间、上传人、下载次数。
## 目录结构
```
fileserver/
├── main.py # 入口(组装路由 + lifespan)
├── launch.py # PyInstaller 打包入口
├── requirements.txt # fastapi / uvicorn / python-multipart / PyMySQL
├── .env # 配置(各环境各自维护)
├── core/
│ ├── config.py # 配置加载(.env,环境变量优先)
│ ├── auth.py # 鉴权:X-API-Token(中心机) + 管理会话(HMAC)
│ ├── store.py # 存储:文件落盘 + MySQL 元数据(未配库时 JSON 兜底)
│ └── heartbeat.py # 中心机心跳上报(daemon 线程)
├── apis/
│ ├── meta.py # GET /(健康检查)
│ ├── files.py # 上传/列表/删除/下载
│ └── admin.py # 登录/改密码/统计
└── frontend/ # Vue3 管理页源码(部署到服务器 /opt/37du/fileserver-admin/)
├── index.html
├── app.js
└── README.md
```
## 架构
```
执行机(内网直连下载) ──▶ fileserver :8802(下载开放)
中心机/自动化 ─────────▶ fileserver :8802(X-API-Token:上传/删除/列表)
浏览器(管理页) ──▶ Nginx :8899 ──/fs-api/──▶ fileserver :8802(登录后 Bearer Token)
文件本体 ──▶ FILESERVER_DATA_DIR(磁盘)
元数据 ──▶ MySQL 37du_fileserver.fs_files(fid/filename/sha256/size/created/uploader/downloads)
```
- 管理接口(上传/删除/列表/统计)需**页面内登录**:`POST /api/admin/login`(账号密码在 `FILESERVER_ADMIN_USER/PASSWORD`),签发 HMAC 会话 Token(默认 12h),前端存 localStorage、以 `Authorization: Bearer` 携带
- **默认账号**:`puddy / 123456`(登录后请尽快在页面「改密码」)
- 前端不接触 X-API-Token(中心机直连 8802 时用)
- 下载 `/files/{fid}` 开放(执行机内网直连),并累计下载次数
## 部署位置(服务器 172.30.30.243)
- 代码/venv:`/opt/37du/fileserver/`、`/opt/37du/venv`
- 数据目录:`/opt/37du/fileserver/data/`
- 管理页静态文件:`/opt/37du/fileserver-admin/`
- Nginx 站点:`/etc/nginx/sites-available/37du-fileserver-admin`(监听 **8899**)
- 服务:`systemctl status/restart 37du-fileserver`,日志 `journalctl -u 37du-fileserver -f`
## 常用维护
```bash
# 改管理密码(页面内改,或改 .env 后重启)
sed -i 's/^FILESERVER_ADMIN_PASSWORD=.*/FILESERVER_ADMIN_PASSWORD=新密码/' /opt/37du/fileserver/.env
systemctl restart 37du-fileserver
# 查 MySQL 元数据
mysql -h 127.0.0.1 -u fs -p 37du_fileserver -e "SELECT fid,filename,size,created,uploader,downloads FROM fs_files ORDER BY created DESC LIMIT 20;"
# 防火墙
ufw status verbose # 放行 22/8899/3306/8802
```
## 端口规划(不给 80 占位)
| 端口 | 用途 |
|------|------|
| 22 | SSH |
| 8802 | 文件服务器(执行机直连下载) |
| 8899 | 管理页面(Nginx) |
| 3306 | MySQL |
| 80 | 预留后续其他项目 |
+2
View File
@@ -0,0 +1,2 @@
# -*- coding: utf-8 -*-
"""fileserver.apis 包:HTTP 路由(meta / files / admin)。"""
+53
View File
@@ -0,0 +1,53 @@
# -*- coding: utf-8 -*-
"""管理接口:登录 / 修改密码 / 统计。"""
from __future__ import annotations
import hmac
import time
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from fileserver.core import auth, config, store
router = APIRouter(tags=["admin"])
class _LoginIn(BaseModel):
username: str = ""
password: str = ""
class _ChangePwdIn(BaseModel):
old_password: str = ""
new_password: str = ""
@router.post("/api/admin/login")
def api_login(d: _LoginIn) -> dict:
"""管理页面登录:校验账号密码,签发管理会话 token(HMAC 签名 + 有效期)。"""
if not auth.verify_login(d.username, d.password):
time.sleep(0.5) # 失败延迟,降低爆破速度
raise HTTPException(401, "用户名或密码错误")
return {"ok": True, "token": auth.sign_admin_token(d.username),
"expires_in": config.ADMIN_TOKEN_TTL, "user": d.username}
@router.post("/api/admin/change-password")
def api_change_password(d: _ChangePwdIn,
_: str = Depends(auth.check_admin)) -> dict:
"""修改管理密码:需旧密码正确;成功后旧会话全部失效(重新登录)。"""
if not config.ADMIN_PASSWORD:
raise HTTPException(400, "当前未配置管理密码")
if not hmac.compare_digest(d.old_password, config.ADMIN_PASSWORD):
raise HTTPException(400, "旧密码不正确")
if len(d.new_password) < 6:
raise HTTPException(400, "新密码至少 6 位")
config.update_admin_password(d.new_password)
return {"ok": True, "message": "密码已修改,请重新登录"}
@router.get("/api/admin/stats")
def api_stats(_: str = Depends(auth.check_admin)) -> dict:
"""汇总统计:文件数 / 总大小 / 总下载次数。"""
return {"ok": True, **store.stats()}
+57
View File
@@ -0,0 +1,57 @@
# -*- coding: utf-8 -*-
"""文件接口:上传 / 列表 / 删除 / 下载。"""
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException, UploadFile
from fastapi.responses import FileResponse
from fileserver.core import auth, store
router = APIRouter(tags=["files"])
@router.post("/api/upload")
async def api_upload(upload: UploadFile, who: str = Depends(auth.check_admin)) -> dict:
"""上传文件:存唯一 id,返回 {id, filename, sha256, size, url}。"""
raw = await upload.read()
if not raw:
raise HTTPException(400, "上传内容为空")
m = store.save(raw, upload.filename or "", uploader=who)
return {"ok": True, "id": m["fid"], "fid": m["fid"],
"filename": m["filename"], "sha256": m["sha256"], "size": m["size"],
"created": m["created"], "uploader": m["uploader"],
"url": store.file_url(m["fid"], m["filename"])}
@router.get("/api/files")
def api_files(_: str = Depends(auth.check_admin)) -> dict:
"""列表已上传文件(管理)。"""
items = []
for m in store.list_files():
m = dict(m)
m["url"] = store.file_url(m["fid"], m["filename"])
items.append(m)
return {"files": items}
@router.delete("/api/files/{fid}")
def api_delete(fid: str, _: str = Depends(auth.check_admin)) -> dict:
"""删除文件与元数据(管理)。"""
try:
removed = store.remove(fid)
except ValueError:
raise HTTPException(400, "非法的文件 id")
return {"ok": True, "removed": removed, "id": fid}
@router.get("/files/{fid}")
def api_download(fid: str, dl: str = ""):
"""开放下载(内网直链);?dl=文件名 时以该名 attachment 落盘;统计下载次数。"""
p = store.path_of(fid)
if p is None:
raise HTTPException(404, "文件不存在")
store.increment_downloads(fid)
m = store.meta(fid)
default_name = m.get("filename") or fid
return FileResponse(p, filename=dl or default_name,
media_type="application/octet-stream")
+17
View File
@@ -0,0 +1,17 @@
# -*- coding: utf-8 -*-
"""基础接口:健康检查。"""
from __future__ import annotations
from fastapi import APIRouter
from fileserver.core import config, store
router = APIRouter(tags=["meta"])
@router.get("/")
def index() -> dict:
"""健康检查(无鉴权)。"""
return {"ok": True, "service": "37du内网文件服务器",
"version": config.VERSION,
"files": len(store.list_files())}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,128 +0,0 @@
This file lists modules PyInstaller was not able to find. This does not
necessarily mean these modules are required for running your program. Both
Python's standard library and 3rd-party Python packages often conditionally
import optional modules, some of which may be available only on certain
platforms.
Types of import:
* top-level: imported at the top-level - look at these first
* conditional: imported within an if-statement
* delayed: imported within a function
* optional: imported within a try-except-statement
IMPORTANT: Do NOT post this list to the issue-tracker. Use it as a basis for
tracking down the missing module yourself. Thanks!
missing module named _frozen_importlib_external - imported by importlib._bootstrap (delayed), importlib (optional), importlib.abc (optional), zipimport (top-level)
excluded module named _frozen_importlib - imported by importlib (optional), importlib.abc (optional), zipimport (top-level)
missing module named 'org.python' - imported by copy (optional), xml.sax (delayed, conditional)
missing module named posix - imported by os (conditional, optional), posixpath (optional), shutil (conditional), importlib._bootstrap_external (conditional)
missing module named resource - imported by posix (top-level)
missing module named grp - imported by shutil (delayed, optional), tarfile (optional), pathlib (delayed, optional), subprocess (delayed, conditional, optional)
missing module named pwd - imported by posixpath (delayed, conditional, optional), shutil (delayed, optional), tarfile (optional), pathlib (delayed, optional), subprocess (delayed, conditional, optional), webbrowser (delayed), getpass (delayed), netrc (delayed, conditional)
missing module named _posixsubprocess - imported by subprocess (conditional), multiprocessing.util (delayed)
missing module named fcntl - imported by subprocess (optional)
missing module named _posixshmem - imported by multiprocessing.resource_tracker (conditional), multiprocessing.shared_memory (conditional)
missing module named _scproxy - imported by urllib.request (conditional)
missing module named termios - imported by click._termui_impl (conditional), tty (top-level), getpass (optional)
missing module named 'java.lang' - imported by platform (delayed, optional), xml.sax._exceptions (conditional)
missing module named multiprocessing.BufferTooShort - imported by multiprocessing (top-level), multiprocessing.connection (top-level)
missing module named multiprocessing.AuthenticationError - imported by multiprocessing (top-level), multiprocessing.connection (top-level)
missing module named multiprocessing.get_context - imported by multiprocessing (top-level), multiprocessing.pool (top-level), multiprocessing.managers (top-level), multiprocessing.sharedctypes (top-level)
missing module named multiprocessing.TimeoutError - imported by multiprocessing (top-level), multiprocessing.pool (top-level)
missing module named org - imported by pickle (optional)
missing module named multiprocessing.set_start_method - imported by multiprocessing (top-level), multiprocessing.spawn (top-level)
missing module named multiprocessing.get_start_method - imported by multiprocessing (top-level), multiprocessing.spawn (top-level)
missing module named multiprocessing.Pipe - imported by multiprocessing (top-level), uvicorn.supervisors.multiprocess (top-level)
missing module named pyimod02_importers - imported by D:\work\code\37duAutomation\.venv\Lib\site-packages\PyInstaller\hooks\rthooks\pyi_rth_pkgutil.py (delayed)
missing module named email_validator - imported by pydantic.networks (delayed, conditional, optional), pydantic.v1.networks (delayed, conditional, optional), fastapi.openapi.models (optional), D:\work\code\37duAutomation\desktop\fileserver\launch.py (top-level), pydantic.v1._hypothesis_plugin (optional)
missing module named asyncio.DefaultEventLoopPolicy - imported by asyncio (delayed, conditional), asyncio.events (delayed, conditional)
missing module named annotationlib - imported by typing_extensions (conditional), pydantic._internal._typing_extra (delayed, conditional), pydantic._internal._model_construction (delayed, conditional), pydantic.v1.main (delayed, conditional), fastapi.dependencies.utils (delayed, conditional, optional)
missing module named vms_lib - imported by platform (delayed, optional)
missing module named java - imported by platform (delayed)
missing module named _winreg - imported by platform (delayed, optional)
missing module named trio - imported by httpx._transports.asgi (delayed, conditional), httpcore._synchronization (optional), httpcore._backends.trio (top-level), websockets.trio.client (top-level), websockets.trio.connection (top-level), websockets.trio.messages (top-level), websockets.trio.utils (top-level), websockets.trio.router (top-level), websockets.trio.server (top-level)
missing module named sniffio - imported by anyio._core._eventloop (optional), httpx._transports.asgi (delayed, optional), httpcore._synchronization (delayed, optional)
missing module named socksio - imported by httpcore._sync.socks_proxy (top-level), httpcore._async.socks_proxy (top-level), httpx._transports.default (delayed, conditional, optional)
missing module named 'h2.settings' - imported by httpcore._sync.http2 (top-level), httpcore._async.http2 (top-level)
missing module named 'h2.exceptions' - imported by httpcore._sync.http2 (top-level), httpcore._async.http2 (top-level)
missing module named 'h2.events' - imported by httpcore._sync.http2 (top-level), httpcore._async.http2 (top-level)
missing module named 'h2.connection' - imported by httpcore._sync.http2 (top-level), httpcore._async.http2 (top-level)
missing module named h2 - imported by httpcore._sync.http2 (top-level), httpx._client (delayed, conditional, optional)
missing module named 'h2.config' - imported by httpcore._async.http2 (top-level)
missing module named 'rich.table' - imported by httpx._main (top-level)
missing module named 'rich.syntax' - imported by httpx._main (top-level)
missing module named 'rich.progress' - imported by httpx._main (top-level)
missing module named 'rich.markup' - imported by httpx._main (top-level)
missing module named 'rich.console' - imported by httpx._main (top-level)
missing module named 'pygments.util' - imported by httpx._main (top-level)
missing module named pygments - imported by httpx._main (top-level)
missing module named '_typeshed.wsgi' - imported by httpx._transports.wsgi (conditional)
missing module named _typeshed - imported by anyio.abc._eventloop (conditional), anyio._core._sockets (conditional), anyio._core._fileio (conditional), anyio._core._tempfile (conditional), pydantic_core._pydantic_core (top-level), pydantic._internal._dataclasses (conditional), httpx._transports.wsgi (conditional), anyio._backends._asyncio (conditional), anyio._core._asyncio_selector_thread (conditional), anyio._backends._trio (conditional)
missing module named zstandard - imported by httpx._decoders (optional)
missing module named brotlicffi - imported by httpx._decoders (optional)
missing module named brotli - imported by httpx._decoders (optional)
missing module named wsproto - imported by uvicorn.protocols.websockets.wsproto_impl (top-level), uvicorn.protocols.websockets.auto (optional), D:\work\code\37duAutomation\desktop\fileserver\launch.py (top-level)
missing module named 'trio.abc' - imported by websockets.trio.connection (top-level), websockets.trio.server (top-level)
missing module named 'werkzeug.routing' - imported by websockets.asyncio.router (optional), websockets.sync.router (optional), websockets.trio.router (optional)
missing module named 'werkzeug.exceptions' - imported by websockets.sync.router (optional), websockets.trio.router (optional)
missing module named 'python_socks.async_' - imported by websockets.asyncio.client (optional), websockets.trio.client (optional)
missing module named python_socks - imported by websockets.asyncio.client (optional), websockets.sync.client (optional), websockets.trio.client (optional)
missing module named 'python_socks.sync' - imported by websockets.sync.client (optional)
missing module named readline - imported by websockets.cli (delayed, optional)
missing module named werkzeug - imported by websockets.asyncio.router (optional)
missing module named httptools - imported by uvicorn.protocols.http.httptools_impl (top-level), uvicorn.protocols.http.auto (optional), D:\work\code\37duAutomation\desktop\fileserver\launch.py (top-level)
missing module named a2wsgi - imported by uvicorn.middleware.wsgi (optional)
missing module named zttp - imported by uvicorn.protocols.http.zttp_impl (top-level)
missing module named 'IPython.core' - imported by dotenv.ipython (top-level)
missing module named IPython - imported by dotenv.ipython (top-level)
excluded module named win32con - imported by win32evtlogutil (top-level)
excluded module named win32api - imported by win32evtlogutil (top-level)
missing module named 'wsproto.utilities' - imported by uvicorn.protocols.websockets.wsproto_impl (top-level)
missing module named 'wsproto.extensions' - imported by uvicorn.protocols.websockets.wsproto_impl (top-level)
missing module named 'wsproto.connection' - imported by uvicorn.protocols.websockets.wsproto_impl (top-level)
missing module named uvloop - imported by uvicorn.loops.auto (delayed, optional), uvicorn.loops.uvloop (top-level), anyio._backends._asyncio (delayed, conditional)
missing module named 'trio.testing' - imported by anyio._backends._trio (delayed)
missing module named exceptiongroup - imported by anyio._core._exceptions (conditional), anyio._core._sockets (conditional), starlette._utils (conditional, optional), anyio._backends._asyncio (conditional), anyio._backends._trio (conditional)
missing module named 'trio.to_thread' - imported by anyio._backends._trio (top-level)
missing module named 'trio.socket' - imported by anyio._backends._trio (top-level)
missing module named outcome - imported by anyio._backends._trio (top-level)
missing module named 'trio.lowlevel' - imported by anyio._backends._trio (top-level)
missing module named 'trio.from_thread' - imported by anyio._backends._trio (top-level)
missing module named '_pytest.outcomes' - imported by anyio._backends._asyncio (delayed)
missing module named _pytest - imported by anyio._backends._asyncio (delayed)
missing module named winloop - imported by anyio._backends._asyncio (delayed, conditional)
missing module named 'pathlib.types' - imported by anyio._core._fileio (conditional)
missing module named cython - imported by pydantic.v1.version (optional)
missing module named toml - imported by pydantic.v1.mypy (delayed, conditional, optional)
missing module named tomli - imported by pydantic.mypy (delayed, conditional, optional), pydantic.v1.mypy (delayed, conditional, optional)
missing module named 'mypy.version' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
missing module named 'mypy.util' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
missing module named 'mypy.typevars' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
missing module named 'mypy.types' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
missing module named 'mypy.server' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
missing module named 'mypy.semanal' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
missing module named 'mypy.plugins' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
missing module named 'mypy.plugin' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
missing module named 'mypy.options' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
missing module named 'mypy.nodes' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
missing module named 'mypy.errorcodes' - imported by pydantic.v1.mypy (top-level)
missing module named hypothesis - imported by pydantic.v1._hypothesis_plugin (top-level)
missing module named 'mypy.typeops' - imported by pydantic.mypy (top-level)
missing module named 'mypy.type_visitor' - imported by pydantic.mypy (top-level)
missing module named 'mypy.state' - imported by pydantic.mypy (top-level)
missing module named 'mypy.expandtype' - imported by pydantic.mypy (top-level)
missing module named mypy - imported by pydantic.mypy (top-level)
missing module named eval_type_backport - imported by pydantic._internal._typing_extra (delayed, optional)
missing module named 'rich.pretty' - imported by pydantic._internal._core_utils (delayed)
missing module named rich - imported by pydantic._internal._core_utils (conditional)
missing module named pydantic.PydanticSchemaGenerationError - imported by pydantic (delayed), pydantic.functional_validators (delayed), fastapi._compat.v2 (top-level)
missing module named pydantic.PydanticUserError - imported by pydantic (top-level), pydantic.root_model (top-level)
missing module named pydantic.BaseModel - imported by pydantic (conditional), pydantic._internal._typing_extra (conditional), pydantic._internal._core_utils (delayed), pydantic._internal._import_utils (delayed, conditional), pydantic.deprecated.copy_internals (delayed, conditional), fastapi.exceptions (top-level), fastapi.types (top-level), fastapi._compat.shared (top-level), fastapi._compat.v2 (top-level), fastapi.openapi.models (top-level), fastapi.security.http (top-level), fastapi.dependencies.utils (top-level), fastapi.encoders (top-level), fastapi.sse (top-level), fastapi.openapi.utils (top-level)
missing module named 'itsdangerous.exc' - imported by starlette.middleware.sessions (top-level)
missing module named itsdangerous - imported by starlette.middleware.sessions (top-level)
missing module named pydantic_extra_types - imported by fastapi.encoders (optional)
missing module named 'gunicorn.workers' - imported by uvicorn.workers (top-level)
missing module named gunicorn - imported by uvicorn.workers (top-level)
missing module named watchfiles - imported by uvicorn.supervisors.watchfilesreload (top-level)
File diff suppressed because it is too large Load Diff
+2
View File
@@ -0,0 +1,2 @@
# -*- coding: utf-8 -*-
"""fileserver.core 包:配置 / 鉴权 / 存储 / 心跳。"""
+73
View File
@@ -0,0 +1,73 @@
# -*- coding: utf-8 -*-
"""鉴权层:中心机 X-API-Token 与 管理页面会话 token(HMAC 签名)双通道。"""
from __future__ import annotations
import base64
import hashlib
import hmac
import time
from fastapi import Header, HTTPException
from fileserver.core import config
def sign_admin_token(user: str) -> str:
"""签发管理会话 token:base64("{user}|{exp}|{hmac}"),默认 12h 有效。"""
exp = int(time.time()) + config.ADMIN_TOKEN_TTL
payload = f"{user}|{exp}"
sig = hmac.new(config.ADMIN_SECRET.encode("utf-8"),
payload.encode("utf-8"), hashlib.sha256).hexdigest()
return base64.urlsafe_b64encode(f"{payload}|{sig}".encode("utf-8")).decode("utf-8")
def verify_admin_token(token: str) -> bool:
"""校验管理会话 Bearer token(HMAC 签名 + 过期时间)。"""
return bool(_decode_admin(token))
def _decode_admin(token: str) -> str:
"""解析管理会话,返回登录用户名;无效/过期返回空串。"""
if not token:
return ""
try:
raw = base64.urlsafe_b64decode(token.encode("utf-8")).decode("utf-8")
user, exp, sig = raw.rsplit("|", 2)
expect = hmac.new(config.ADMIN_SECRET.encode("utf-8"),
f"{user}|{exp}".encode("utf-8"), hashlib.sha256).hexdigest()
if not hmac.compare_digest(sig, expect):
return ""
if int(exp) <= time.time():
return ""
return user
except Exception: # noqa: BLE001
return ""
def admin_identity(x_api_token: str, authorization: str) -> str:
"""解析当前调用方身份:X-API-Token → "center";管理会话 → 登录用户名;否则空串。"""
if config.TOKEN and x_api_token.strip() == config.TOKEN:
return "center"
if authorization.startswith("Bearer "):
user = _decode_admin(authorization[7:].strip())
if user:
return user
return ""
def check_admin(x_api_token: str = Header(default="", alias="X-API-Token"),
authorization: str = Header(default="", alias="Authorization")) -> str:
"""FastAPI 依赖:X-API-Token(中心机/自动化)或管理会话 Bearer(管理页面)二选一通过。
返回调用方身份("center" 或登录用户名),供记录上传人等审计字段。"""
who = admin_identity(x_api_token, authorization)
if not who:
raise HTTPException(401, "无效的文件服务器令牌")
return who
def verify_login(username: str, password: str) -> bool:
"""校验管理页面账号密码(常量时间比较)。"""
if not (config.ADMIN_USER and config.ADMIN_PASSWORD):
return False
return (hmac.compare_digest(username, config.ADMIN_USER)
and hmac.compare_digest(password, config.ADMIN_PASSWORD))
+97 -68
View File
@@ -1,68 +1,97 @@
# -*- 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}"
# 中心机(控制面)上报:非空时后台线程周期上报心跳状态,中心机据此监控在线/离线。
# CONTROLPLANE_URL 中心机地址,如 http://117.72.191.188:8800
# CONTROLPLANE_TOKEN 与中心机 controlplane/.env 的 CONTROLPLANE_TOKEN 一致
CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/")
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
# 心跳上报间隔(秒)
HEARTBEAT_INTERVAL = int(os.getenv("FILESERVER_HEARTBEAT_INTERVAL", "60") or "60")
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}"
CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/")
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
HEARTBEAT_INTERVAL = int(os.getenv("FILESERVER_HEARTBEAT_INTERVAL", "60") or "60")
def default_token() -> str:
"""未配置 token 时一次性生成(仅开发便利,生产应写死到 .env)。"""
return TOKEN or secrets.token_urlsafe(24)
# -*- coding: utf-8 -*-
"""内网文件服务器配置:只读加载 fileserver/.env(环境变量优先,不覆盖已存在值)。"""
from __future__ import annotations
import os
import sys
from pathlib import Path
def _app_dir() -> Path:
"""定位 .env / 数据所在目录(源码与 PyInstaller 打包两种形态)。"""
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()
def load_dotenv() -> None:
"""读取本地 .env(环境变量优先,不覆盖已存在值)。"""
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()
# ===== 基础服务 =====
PORT = int(os.getenv("FILESERVER_PORT", "8802") or "8802")
# 中心机/自动化管理 token(X-API-Token);未配置时管理接口仅允许登录会话
TOKEN = os.getenv("FILESERVER_TOKEN", "")
# 落盘目录:.env 未配时默认 应用目录/data
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}"
VERSION = "37du-fileserver/2.0"
# ===== 中心机心跳上报 =====
CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/")
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
HEARTBEAT_INTERVAL = int(os.getenv("FILESERVER_HEARTBEAT_INTERVAL", "60") or "60")
# ===== 管理页面登录(内置管理会话,替代 nginx Basic Auth)=====
ADMIN_USER = os.getenv("FILESERVER_ADMIN_USER", "").strip()
ADMIN_PASSWORD = os.getenv("FILESERVER_ADMIN_PASSWORD", "")
# 管理会话有效期(秒,默认 12h)
ADMIN_TOKEN_TTL = int(os.getenv("FILESERVER_ADMIN_TOKEN_TTL", "43200") or "43200")
def _admin_secret() -> str:
"""管理会话签名密钥:优先 .env 的 FILESERVER_ADMIN_SECRET;未配则由 ADMIN_PASSWORD
派生(固定盐,保证重启后已签发 token 仍然有效)。密码变更后密钥随之变化,
已签发 token 全部失效(需重新登录)。"""
_s = os.getenv("FILESERVER_ADMIN_SECRET", "").strip()
if _s:
return _s
import hashlib
return hashlib.sha256(f"{ADMIN_PASSWORD}|37du-fs-admin".encode("utf-8")).hexdigest()
ADMIN_SECRET = _admin_secret()
# ===== MySQL 元数据存储(文件本体仍在磁盘,元数据/统计入库)=====
DB_HOST = os.getenv("FILESERVER_DB_HOST", "").strip()
DB_PORT = int(os.getenv("FILESERVER_DB_PORT", "3306") or "3306")
DB_USER = os.getenv("FILESERVER_DB_USER", "").strip()
DB_PASSWORD = os.getenv("FILESERVER_DB_PASSWORD", "")
DB_NAME = os.getenv("FILESERVER_DB_NAME", "37du_fileserver").strip()
DB_ENABLED = bool(DB_HOST and DB_USER)
def update_admin_password(new_password: str) -> None:
"""更新管理密码并持久化到 .env(管理页面「修改密码」用)。"""
global ADMIN_PASSWORD, ADMIN_SECRET
ADMIN_PASSWORD = new_password
ADMIN_SECRET = _admin_secret()
env_path = APP_DIR / ".env"
lines = env_path.read_text(encoding="utf-8").splitlines() if env_path.is_file() else []
out, hit = [], False
for ln in lines:
if ln.strip().startswith("FILESERVER_ADMIN_PASSWORD="):
out.append(f"FILESERVER_ADMIN_PASSWORD={new_password}")
hit = True
else:
out.append(ln)
if not hit:
out.append(f"FILESERVER_ADMIN_PASSWORD={new_password}")
env_path.write_text("\n".join(out) + "\n", encoding="utf-8")
+80
View File
@@ -0,0 +1,80 @@
# -*- coding: utf-8 -*-
"""心跳上报:后台线程周期向中心机上报本机状态,供中心机监控在线/离线并钉钉告警。"""
from __future__ import annotations
import json
import logging
import socket
import threading
import time
import urllib.request
from fileserver.core import config
from fileserver.core import store
log = logging.getLogger("fileserver.heartbeat")
_START_TS = time.time()
def _server_status() -> dict:
"""收集本服务器状态快照:文件数/占用/主机/IP/运行时长等。"""
metas = store.list_files()
total = sum(int(m.get("size") or 0) for m in metas)
hostname = socket.gethostname()
try:
ip = socket.gethostbyname(hostname)
except OSError: # noqa: BLE001
ip = ""
return {
"host": config.BASE_URL, # 中心机以其唯一标识本服务器(默认=对外下载根)
"base_url": config.BASE_URL,
"hostname": hostname,
"ip": ip,
"port": config.PORT,
"file_count": len(metas),
"total_size": total,
"version": config.VERSION,
"uptime_sec": int(time.time() - _START_TS),
}
def _post_heartbeat() -> bool:
"""单次上报心跳到中心机;成功返回 True。"""
payload = json.dumps(_server_status(), ensure_ascii=False).encode("utf-8")
req = urllib.request.Request(
f"{config.CONTROLPLANE_URL}/api/fileserver/heartbeat",
data=payload, method="POST")
req.add_header("Content-Type", "application/json")
if config.CONTROLPLANE_TOKEN:
req.add_header("X-API-Token", config.CONTROLPLANE_TOKEN)
try:
with urllib.request.urlopen(req, timeout=10) as resp:
return resp.status < 400
except OSError as exc: # noqa: BLE001 网络/中心机异常按失败处理
log.warning("心跳上报失败:%s", exc)
return False
def _loop() -> None:
"""周期上报;每次最多重试 3 次(项目级重试约定),三次失败记错误日志;不阻塞文件服务。"""
if not config.CONTROLPLANE_URL:
log.info("未配置 CONTROLPLANE_URL,跳过心跳上报")
return
while True:
try:
ok = False
for _i in range(3):
if _post_heartbeat():
ok = True
break
if not ok:
log.error("心跳上报连续失败(3 次):%s", config.CONTROLPLANE_URL)
except Exception: # noqa: BLE001
log.exception("心跳上报线程异常")
time.sleep(max(5, config.HEARTBEAT_INTERVAL))
def start() -> None:
"""启动心跳上报线程(daemon)。"""
threading.Thread(target=_loop, daemon=True,
name="fileserver-heartbeat").start()
+207
View File
@@ -0,0 +1,207 @@
# -*- coding: utf-8 -*-
"""存储层:文件本体落盘 + 元数据入库(MySQL 优先,未配置时 JSON 兜底)。
元数据字段:fid / filename / sha256 / size / created / uploader / downloads / note。
文件本体保存在 DATA_DIR(大文件不放数据库),元数据与统计进 MySQL。
"""
from __future__ import annotations
import hashlib
import json
import re
import secrets
import time
from pathlib import Path
from fileserver.core import config
_DATA_DIR = config.DATA_DIR
_STATUS_DIR = _DATA_DIR / ".meta"
_FID_RE = re.compile(r"[A-Za-z0-9_-]{1,64}")
_SCHEMA = """
CREATE TABLE IF NOT EXISTS fs_files (
fid VARCHAR(64) NOT NULL PRIMARY KEY,
filename VARCHAR(200) NOT NULL,
sha256 CHAR(64) NOT NULL,
size BIGINT NOT NULL DEFAULT 0,
created DOUBLE NOT NULL,
uploader VARCHAR(64) NOT NULL DEFAULT '',
downloads BIGINT NOT NULL DEFAULT 0,
note VARCHAR(255) NOT NULL DEFAULT '',
KEY idx_created (created),
KEY idx_filename (filename)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
"""
def _db_conn():
"""建立 PyMySQL 连接(每操作短连接,轻量文件服务够用)。"""
import pymysql
return pymysql.connect(
host=config.DB_HOST, port=config.DB_PORT, user=config.DB_USER,
password=config.DB_PASSWORD, database=config.DB_NAME,
charset="utf8mb4", autocommit=False)
def _db_exec(sql: str, args=()) -> int:
"""执行写操作,返回 rowcount。"""
conn = _db_conn()
try:
with conn.cursor() as cur:
n = cur.execute(sql, args)
conn.commit()
return n
finally:
conn.close()
def _db_fetch(sql: str, args=()) -> list[dict]:
"""查询并返回 dict 列表。"""
conn = _db_conn()
try:
with conn.cursor() as cur:
cur.execute(sql, args)
cols = [d[0] for d in cur.description] if cur.description else []
rows = [dict(zip(cols, r)) for r in cur.fetchall()]
return rows
finally:
conn.close()
# ==================== 初始化 ====================
def init() -> None:
"""确保数据目录与元数据目录就绪;DB 模式下自动建表。"""
_DATA_DIR.mkdir(parents=True, exist_ok=True)
_STATUS_DIR.mkdir(parents=True, exist_ok=True)
if config.DB_ENABLED:
_db_exec(_SCHEMA)
def _using_db() -> bool:
return config.DB_ENABLED
# ==================== 工具 ====================
def safe_name(name: str) -> str:
"""清洗文件名:仅保留安全 basename,去除路径与危险字符。"""
return re.sub(r"[^\w.\-]", "_", Path(name or "").name)[:200]
def _row_to_meta(row: dict) -> dict:
return {
"fid": row["fid"], "filename": row["filename"],
"sha256": row["sha256"], "size": int(row["size"] or 0),
"created": float(row["created"]),
"uploader": row.get("uploader") or "",
"downloads": int(row.get("downloads") or 0),
"note": row.get("note") or "",
}
# ==================== 写 ====================
def save(raw: bytes, filename: str, uploader: str = "", note: str = "") -> dict:
"""保存文件:唯一 id 落盘 + 元数据入库,返回 meta。"""
fid = secrets.token_urlsafe(12)
origin = safe_name(filename)
sha = hashlib.sha256(raw).hexdigest()
created = time.time()
(_DATA_DIR / fid).write_bytes(raw)
if _using_db():
_db_exec(
"INSERT INTO fs_files (fid, filename, sha256, size, created, uploader, note) "
"VALUES (%s, %s, %s, %s, %s, %s, %s)",
(fid, origin, sha, len(raw), created, uploader, note))
else:
m = {"fid": fid, "filename": origin, "sha256": sha, "size": len(raw),
"created": created, "uploader": uploader, "downloads": 0, "note": note}
(_STATUS_DIR / f"{fid}.json").write_text(
json.dumps(m, ensure_ascii=False), encoding="utf-8")
return meta(fid)
def increment_downloads(fid: str) -> None:
"""下载计数 +1(仅统计,不影响下载)。"""
if _using_db():
_db_exec("UPDATE fs_files SET downloads = downloads + 1 WHERE fid = %s", (fid,))
else:
mf = _STATUS_DIR / f"{fid}.json"
if mf.is_file():
try:
m = json.loads(mf.read_text(encoding="utf-8"))
m["downloads"] = int(m.get("downloads") or 0) + 1
mf.write_text(json.dumps(m, ensure_ascii=False), encoding="utf-8")
except Exception: # noqa: BLE001
pass
# ==================== 读 ====================
def meta(fid: str) -> dict:
"""读元数据;不存在返回空 dict。"""
if _using_db():
rows = _db_fetch("SELECT * FROM fs_files WHERE fid = %s", (fid,))
return _row_to_meta(rows[0]) if rows else {}
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 {}
def list_files() -> list[dict]:
"""列出全部文件元数据(按上传时间倒序)。"""
if _using_db():
rows = _db_fetch("SELECT * FROM fs_files ORDER BY created DESC")
return [_row_to_meta(r) for r in rows]
items = []
for mf in sorted(_STATUS_DIR.glob("*.json")):
m = meta(mf.stem)
if m:
items.append(m)
items.sort(key=lambda m: m.get("created") or 0, reverse=True)
return items
def path_of(fid: str) -> Path | None:
"""返回文件落盘路径;不存在/非法 id 返回 None。"""
if not _FID_RE.fullmatch(fid):
return None
p = _DATA_DIR / fid
return p if p.is_file() else None
def remove(fid: str) -> bool:
"""删除文件与元数据;非法 id 抛 ValueError。"""
if not _FID_RE.fullmatch(fid):
raise ValueError("非法文件 id")
removed = False
p = _DATA_DIR / fid
if p.is_file():
p.unlink(missing_ok=True)
removed = True
if _using_db():
_db_exec("DELETE FROM fs_files WHERE fid = %s", (fid,))
else:
(_STATUS_DIR / f"{fid}.json").unlink(missing_ok=True)
return removed
def file_url(fid: str, filename: str = "") -> str:
"""对外下载直链。"""
return f"{config.BASE_URL}/files/{fid}?dl={filename or fid}"
def stats() -> dict:
"""汇总统计:文件数 / 总大小 / 总下载。"""
if _using_db():
rows = _db_fetch(
"SELECT COUNT(*) AS c, COALESCE(SUM(size),0) AS s, COALESCE(SUM(downloads),0) AS d "
"FROM fs_files")
return {"count": int(rows[0]["c"]), "total_size": int(rows[0]["s"]),
"total_downloads": int(rows[0]["d"])}
metas = list_files()
return {"count": len(metas),
"total_size": sum(int(m.get("size") or 0) for m in metas),
"total_downloads": sum(int(m.get("downloads") or 0) for m in metas)}
+47
View File
@@ -0,0 +1,47 @@
# fileserver 管理页面(Vue 3)
文件服务器(8802)的 Web 管理界面:查看文件列表、上传时间、大小、SHA256,支持上传/下载/删除。
## 文件说明
| 文件 | 说明 |
|------|------|
| `index.html` | 页面骨架 + 样式 |
| `app.js` | Vue 3 应用逻辑(列表/上传/删除/搜索) |
| `vue.global.prod.js` | Vue 运行时(本地托管,离线可用,部署在服务器 `/opt/37du/fileserver-admin/`) |
## 架构
```
浏览器 → Nginx(:80)
├── 页面静态文件(/opt/37du/fileserver-admin/)
└── /fs-api/* → 反代到 127.0.0.1:8802
```
- 管理接口(列表/上传/删除)需**页面内登录**:`POST /api/admin/login`(账号密码在 fileserver/.env 的 `FILESERVER_ADMIN_USER/PASSWORD`),签发 HMAC 会话 Token(默认 12h),前端存 localStorage、以 `Authorization: Bearer` 携带
- 前端**不接触** X-API-Token(中心机/自动化直连 8802 时用)
- 下载 `/files/{fid}` 保持开放(执行机内网直连)
- Nginx `client_max_body_size 0` 支持大文件上传
## 部署位置(服务器 172.30.30.243)
- 站点配置:`/etc/nginx/sites-available/37du-fileserver-admin`
- 页面文件:`/opt/37du/fileserver-admin/`
- 认证文件:`/etc/nginx/.htpasswd`
## 修改管理密码
```bash
# 修改 /opt/37du/fileserver/.env 中的 FILESERVER_ADMIN_PASSWORD,然后重启服务:
systemctl restart 37du-fileserver
```
## 更新页面
1. 本地修改 `desktop/fileserver/frontend/` 下文件
2. 上传覆盖 `/opt/37du/fileserver-admin/` 同名文件
3. `systemctl reload nginx`
## 防火墙(ufw)
已启用:默认拒绝入站,放行 `22/tcp`(limit)、`80/tcp`、`3306/tcp`、`8802/tcp`。
管理:`ufw status verbose` / `ufw allow <port>/tcp` / `ufw delete allow <port>/tcp`
+316
View File
@@ -0,0 +1,316 @@
// 37du 文件服务器管理页面 v2.0 - Vue 3 应用逻辑
// API 走同源 /fs-api 反代;管理接口用登录后的会话 Bearer Token 鉴权。
"use strict";
const API_BASE = "/fs-api";
const TOKEN_KEY = "fs_admin_token";
const { createApp } = Vue;
createApp({
data() {
return {
files: [],
loading: false,
keyword: "",
sortKey: "created",
sortDir: -1, // -1 降序 1 升序
uploading: false,
uploadIdx: 0,
uploadTotal: 0,
uploadPercent: 0,
statusMsg: "",
statusClass: "",
baseUrl: location.origin,
// 登录态
token: localStorage.getItem(TOKEN_KEY) || "",
username: "",
password: "",
showPwd: false,
loginMsg: "",
loggingIn: false,
// 改密码
showPwdModal: false,
oldPwd: "",
newPwd: "",
newPwd2: "",
pwdMsg: "",
savingPwd: false,
};
},
computed: {
loggedIn() {
return !!this.token;
},
tokenUser() {
try {
const raw = atob(this.token.split(".")[0]);
return raw.split("|")[0] || "?";
} catch (e) {
return "?";
}
},
sortedFiles() {
const k = this.keyword.trim().toLowerCase();
let list = this.files;
if (k) list = list.filter((f) => (f.filename || "").toLowerCase().includes(k));
const dir = this.sortDir;
const key = this.sortKey;
return list.slice().sort((a, b) => {
let r = 0;
if (key === "filename") r = (a.filename || "").localeCompare(b.filename || "", "zh");
else if (key === "size") r = (Number(a.size) || 0) - (Number(b.size) || 0);
else if (key === "created") r = (a.created || 0) - (b.created || 0);
else if (key === "downloads") r = (Number(a.downloads) || 0) - (Number(b.downloads) || 0);
return r * dir;
});
},
totalCount() {
return this.files.length;
},
totalSizeText() {
return this.fmtSize(this.files.reduce((s, f) => s + (Number(f.size) || 0), 0));
},
totalDownloads() {
return this.files.reduce((s, f) => s + (Number(f.downloads) || 0), 0);
},
lastUploadText() {
if (!this.files.length) return "-";
const t = Math.max(...this.files.map((f) => Number(f.created) || 0));
return this.fmtTime(t);
},
},
methods: {
authHeaders() {
return { Authorization: "Bearer " + this.token };
},
flash(msg, ok) {
this.statusMsg = msg;
this.statusClass = ok ? "ok" : "err";
clearTimeout(this._t);
this._t = setTimeout(() => {
this.statusMsg = "";
this.statusClass = "";
}, 3000);
},
sortBy(key) {
if (this.sortKey === key) {
this.sortDir = -this.sortDir;
} else {
this.sortKey = key;
this.sortDir = key === "filename" ? 1 : -1;
}
},
// ===== 登录 =====
async login() {
this.loggingIn = true;
this.loginMsg = "";
try {
const r = await fetch(`${API_BASE}/api/admin/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username: this.username, password: this.password }),
});
const j = await r.json().catch(() => ({}));
if (!r.ok) {
this.loginMsg = j.detail || ("登录失败 HTTP " + r.status);
return;
}
this.token = j.token;
localStorage.setItem(TOKEN_KEY, j.token);
this.password = "";
this.load();
} catch (e) {
this.loginMsg = "网络错误:" + e.message;
} finally {
this.loggingIn = false;
}
},
logout() {
this.token = "";
localStorage.removeItem(TOKEN_KEY);
this.files = [];
this.loginMsg = "";
this.keyword = "";
},
// ===== 数据 =====
async load() {
this.loading = true;
try {
const r = await fetch(`${API_BASE}/api/files`, { headers: this.authHeaders() });
if (r.status === 401) {
this.logout();
this.loginMsg = "登录已过期,请重新登录";
return;
}
if (!r.ok) throw new Error("HTTP " + r.status);
const j = await r.json();
this.files = j.files || [];
this.flash("已刷新,共 " + this.files.length + " 个文件", true);
} catch (e) {
this.flash("加载文件列表失败:" + e.message, false);
} finally {
this.loading = false;
}
},
// ===== 上传(支持多文件)=====
async onFilesPicked(ev) {
const files = Array.from(ev.target.files || []);
ev.target.value = "";
if (!files.length) return;
this.uploading = true;
this.uploadTotal = files.length;
let okCount = 0;
for (let i = 0; i < files.length; i++) {
this.uploadIdx = i + 1;
this.uploadPercent = 0;
if (await this.uploadOne(files[i])) okCount++;
}
this.uploading = false;
this.flash(`上传完成:成功 ${okCount}/${files.length} 个`, okCount > 0);
this.load();
},
uploadOne(file) {
return new Promise((resolve) => {
const fd = new FormData();
fd.append("upload", file);
const xhr = new XMLHttpRequest();
xhr.open("POST", `${API_BASE}/api/upload`);
xhr.setRequestHeader("Authorization", "Bearer " + this.token);
xhr.upload.onprogress = (e) => {
if (e.lengthComputable) this.uploadPercent = Math.round((e.loaded / e.total) * 100);
};
xhr.onload = () => {
if (xhr.status === 401) {
this.logout();
this.loginMsg = "登录已过期,请重新登录";
resolve(false);
return;
}
if (xhr.status < 300) resolve(true);
else {
this.flash(`上传 ${file.name} 失败:HTTP ${xhr.status}`, false);
resolve(false);
}
};
xhr.onerror = () => {
this.flash(`上传 ${file.name} 失败:网络错误`, false);
resolve(false);
};
xhr.send(fd);
});
},
// ===== 删除 =====
async remove(f) {
if (!confirm(`确定删除文件「${f.filename}」?此操作不可恢复。`)) return;
try {
const r = await fetch(`${API_BASE}/api/files/${f.fid}`, {
method: "DELETE",
headers: this.authHeaders(),
});
if (r.status === 401) {
this.logout();
this.loginMsg = "登录已过期,请重新登录";
return;
}
if (!r.ok) throw new Error("HTTP " + r.status);
const j = await r.json();
if (j.ok) {
this.files = this.files.filter((x) => x.fid !== f.fid);
this.flash("已删除:" + f.filename, true);
} else {
this.flash("删除失败", false);
}
} catch (e) {
this.flash("删除失败:" + e.message, false);
}
},
// ===== 链接复制 =====
async copyLink(f) {
const url = this.downloadUrl(f);
try {
await navigator.clipboard.writeText(url);
this.flash("下载链接已复制", true);
} catch (e) {
const ta = document.createElement("textarea");
ta.value = url;
document.body.appendChild(ta);
ta.select();
document.execCommand("copy");
ta.remove();
this.flash("下载链接已复制", true);
}
},
// ===== 修改密码 =====
openPwdModal() {
this.oldPwd = this.newPwd = this.newPwd2 = "";
this.pwdMsg = "";
this.showPwdModal = true;
},
closePwdModal() {
this.showPwdModal = false;
},
async changePwd() {
this.pwdMsg = "";
if (this.newPwd !== this.newPwd2) {
this.pwdMsg = "两次输入的新密码不一致";
return;
}
if (this.newPwd.length < 6) {
this.pwdMsg = "新密码至少 6 位";
return;
}
this.savingPwd = true;
try {
const r = await fetch(`${API_BASE}/api/admin/change-password`, {
method: "POST",
headers: Object.assign({ "Content-Type": "application/json" }, this.authHeaders()),
body: JSON.stringify({ old_password: this.oldPwd, new_password: this.newPwd }),
});
const j = await r.json().catch(() => ({}));
if (!r.ok) {
this.pwdMsg = j.detail || ("修改失败 HTTP " + r.status);
return;
}
this.showPwdModal = false;
this.logout();
this.loginMsg = "密码已修改,请用新密码重新登录";
} catch (e) {
this.pwdMsg = "网络错误:" + e.message;
} finally {
this.savingPwd = false;
}
},
// ===== 工具 =====
downloadUrl(f) {
return `${API_BASE}/files/${f.fid}?dl=${encodeURIComponent(f.filename || f.fid)}`;
},
extOf(name) {
const m = /\.([A-Za-z0-9]+)$/.exec(name || "");
return m ? m[1].toUpperCase().slice(0, 6) : "FILE";
},
whoLabel(who) {
if (!who) return "-";
return who === "center" ? "中心机" : who;
},
fmtSize(bytes) {
const b = Number(bytes) || 0;
if (b < 1024) return b + " B";
if (b < 1024 * 1024) return (b / 1024).toFixed(1) + " KB";
if (b < 1024 * 1024 * 1024) return (b / 1024 / 1024).toFixed(1) + " MB";
return (b / 1024 / 1024 / 1024).toFixed(2) + " GB";
},
fmtTime(ts) {
if (!ts) return "-";
const d = new Date(Number(ts) * 1000);
const p = (n) => String(n).padStart(2, "0");
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
},
shortSha(s) {
return (s || "").slice(0, 12) + "…";
},
},
mounted() {
if (this.token) this.load();
},
}).mount("#app");
+424
View File
@@ -0,0 +1,424 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>37du 文件服务器管理</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: "Comic Sans MS", "Comic Neue", "Segoe Print", "Marker Felt", "Bradley Hand", cursive;
background-color: #fffdf3;
background-image:
repeating-linear-gradient(transparent 0 31px, rgba(120, 150, 210, .15) 31px 32px),
url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='120' height='120'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2' stitchTiles='stitch'/><feColorMatrix type='saturate' values='0'/></filter><rect width='120' height='120' filter='url(%23n)' opacity='0.035'/></svg>");
color: #2b2b2b; font-size: 15px; min-height: 100vh;
}
::selection { background: #ffe066; color: #2b2b2b; }
/* ===== 手绘通用 ===== */
.hand { border: 2.5px solid #2b2b2b; border-radius: 255px 15px 225px 15px / 15px 225px 15px 255px; }
.squiggle {
display: inline-block; height: 7px; margin-top: 3px;
background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='140' height='7'><path d='M0 3 Q 10 0, 20 3 T 40 3 T 60 3 T 80 3 T 100 3 T 120 3 T 140 3' stroke='%23e8590c' stroke-width='2.6' fill='none' stroke-linecap='round'/></svg>");
background-repeat: no-repeat; background-size: 100% 100%;
}
.pin { position: absolute; font-size: 20px; line-height: 1; filter: drop-shadow(0 2px 2px rgba(0,0,0,.25)); }
.tape {
position: absolute; width: 92px; height: 26px; z-index: 2;
background: rgba(255, 224, 130, .62);
border-left: 2px dashed rgba(0,0,0,.18);
border-right: 2px dashed rgba(0,0,0,.18);
box-shadow: 0 2px 4px rgba(0,0,0,.12);
}
/* ===== 登录页 ===== */
.login-wrap { min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 24px; }
.login-card {
position: relative; width: 410px; background: #fffef8;
border: 2.5px solid #2b2b2b;
border-radius: 15px 255px 15px 255px / 255px 15px 255px 15px;
box-shadow: 5px 7px 0 rgba(0,0,0,.12);
padding: 44px 38px 36px; transform: rotate(-.6deg);
}
.login-card .tape { top: -14px; left: 50%; margin-left: -46px; transform: rotate(-3deg); }
.login-card .pin { top: -12px; right: 22px; transform: rotate(12deg); }
.login-card .emblem {
width: 58px; height: 58px; border-radius: 50%;
background: #fff; border: 3px solid #2b2b2b;
display: flex; align-items: center; justify-content: center;
font-weight: 800; font-size: 24px; color: #e8590c;
transform: rotate(-7deg); box-shadow: 2px 3px 0 rgba(0,0,0,.14);
margin-bottom: 16px;
}
.login-card h2 { font-size: 27px; font-weight: 800; letter-spacing: .5px; }
.login-card .login-sub { font-size: 13px; color: #868e96; font-weight: 700; margin: 4px 0 20px; }
.login-field { position: relative; margin-bottom: 13px; }
.login-field input {
width: 100%; padding: 11px 44px 11px 14px;
border: 2.5px solid #2b2b2b;
border-radius: 255px 15px 225px 15px / 15px 225px 15px 255px;
font-family: inherit; font-size: 15px; font-weight: 600; outline: none;
background: #fff;
}
.login-field input:focus { background: #fff9db; }
.eye { position: absolute; right: 14px; top: 50%; transform: translateY(-50%); cursor: pointer; font-size: 17px; user-select: none; }
.login-card .btn { width: 100%; padding: 12px; font-size: 16px; margin-top: 4px; }
.login-hint { margin-top: 14px; font-size: 12.5px; color: #868e96; font-weight: 700; }
.login-msg {
margin-top: 12px; background: #ffe3e3; color: #c92a2a;
padding: 10px 12px; font-weight: 700; font-size: 13px;
border: 2.5px dashed #c92a2a; border-radius: 15px 255px 15px 255px / 255px 15px 255px 15px;
}
/* ===== 顶栏(便签条)===== */
.header {
position: relative; background: #ffe066;
border-bottom: 3px solid #2b2b2b;
padding: 16px 30px;
display: flex; align-items: center; justify-content: space-between; gap: 16px;
transform: rotate(-.35deg); margin: 0 -4px;
}
.header .pin.l { top: 6px; left: 14px; transform: rotate(-14deg); }
.header .pin.r { top: 6px; right: 200px; transform: rotate(10deg); }
.header .brand { display: flex; align-items: center; gap: 14px; }
.header .emblem {
width: 48px; height: 48px; border-radius: 50%;
background: #fff; border: 3px solid #2b2b2b;
display: flex; align-items: center; justify-content: center;
font-weight: 800; font-size: 21px; color: #e8590c;
transform: rotate(-6deg); box-shadow: 2px 3px 0 rgba(0,0,0,.14);
}
.header h1 { font-size: 23px; font-weight: 800; line-height: 1.1; }
.header h1 .squiggle { width: 150px; }
.header .sub { font-size: 12.5px; color: #5c5c5c; font-weight: 700; margin-top: 2px; }
.header .actions { display: flex; gap: 10px; flex-wrap: wrap; }
/* ===== 统计条 ===== */
.stats {
display: grid; grid-template-columns: repeat(4, 1fr); gap: 18px;
padding: 22px 30px 18px;
}
.stat {
position: relative; background: #fffef8; padding: 12px 16px 13px;
border: 2.5px solid #2b2b2b;
border-radius: 255px 15px 225px 15px / 15px 225px 15px 255px;
box-shadow: 3px 5px 0 rgba(0,0,0,.1);
transition: transform .18s ease, box-shadow .18s ease;
}
.stat:nth-child(odd) { transform: rotate(-1.2deg); }
.stat:nth-child(even) { transform: rotate(1deg); }
.stat:hover { transform: rotate(0) translateY(-3px); box-shadow: 5px 8px 0 rgba(0,0,0,.14); }
.stat .tape { top: -11px; left: 50%; margin-left: -46px; transform: rotate(-2deg); width: 74px; height: 22px; }
.stat .k { font-size: 12.5px; font-weight: 700; color: #868e96; letter-spacing: .5px; }
.stat .v { font-size: 23px; font-weight: 800; margin-top: 3px; color: #2b2b2b; }
.stat:nth-child(1) .v { color: #e8590c; }
.stat:nth-child(2) .v { color: #1971c2; }
.stat:nth-child(3) .v { color: #2f9e44; }
.stat:nth-child(4) .v { color: #9c36b5; }
/* ===== 工具栏 ===== */
.toolbar {
display: flex; gap: 12px; align-items: center; flex-wrap: wrap;
padding: 8px 30px 18px;
}
.toolbar input[type="text"] {
padding: 9px 14px; border: 2.5px solid #2b2b2b;
border-radius: 255px 15px 225px 15px / 15px 225px 15px 255px;
font-family: inherit; font-size: 14px; font-weight: 600; outline: none;
width: 280px; background: #fff;
}
.toolbar input[type="text"]:focus { background: #fff9db; }
.toolbar .hint { color: #868e96; font-size: 12.5px; font-weight: 700; }
/* ===== 按钮(标记笔)===== */
.btn {
font-family: inherit; font-weight: 700; font-size: 14.5px;
border: 2.5px solid #2b2b2b;
border-radius: 255px 15px 225px 15px / 15px 225px 15px 255px;
background: #fff; color: #2b2b2b;
padding: 9px 18px; cursor: pointer;
box-shadow: 2px 3px 0 rgba(0,0,0,.14);
transition: transform .12s ease, background .12s ease;
user-select: none;
}
.btn:hover { transform: rotate(-1.6deg) scale(1.04); }
.btn:active { transform: rotate(0) translateY(2px); box-shadow: 0 1px 0 rgba(0,0,0,.14); }
.btn-primary { background: #ffe066; }
.btn-primary:hover { background: #ffd43b; }
.btn-success { background: #b2f2bb; }
.btn-success:hover { background: #8ce99a; }
.btn:disabled { opacity: .5; cursor: not-allowed; }
.upload-btn input[type="file"] { display: none; }
.tag {
display: inline-block; padding: 6px 12px;
border: 2.5px solid #2b2b2b;
border-radius: 255px 15px 225px 15px / 15px 225px 15px 255px;
font-size: 13px; font-weight: 700; background: #ffd8a8; color: #2b2b2b;
transform: rotate(-1deg); box-shadow: 2px 3px 0 rgba(0,0,0,.1);
}
/* ===== 状态条(标记笔高亮)===== */
.status-bar { display: none; padding: 11px 30px; font-weight: 700; font-size: 14px; }
.status-bar.ok { display: block; background: #fff3bf; color: #2b2b2b; border-bottom: 2.5px dashed #f59f00; }
.status-bar.err { display: block; background: #ffe3e3; color: #c92a2a; border-bottom: 2.5px dashed #e03131; }
.main { padding: 8px 30px 30px; }
/* ===== 主卡片(纸页 + 折角)===== */
.card {
position: relative; background: #fffef8;
border: 2.5px solid #2b2b2b;
border-radius: 15px 255px 15px 255px / 255px 15px 255px 15px;
box-shadow: 5px 7px 0 rgba(0,0,0,.1);
transform: rotate(.2deg);
}
.card > .tape { top: -13px; left: 50%; margin-left: -46px; transform: rotate(-3deg); }
.card::after {
content: ""; position: absolute; top: 0; right: 0;
width: 0; height: 0;
border-style: solid;
border-width: 0 0 30px 30px;
border-color: transparent transparent #ffe066 transparent;
filter: drop-shadow(-2px 2px 1px rgba(0,0,0,.08));
}
/* ===== 加载中(翻本子)===== */
.loading {
padding: 70px; text-align: center; font-weight: 800; font-size: 18px; color: #495057;
}
.loading .pen { display: inline-block; animation: pen 1.1s ease-in-out infinite; }
@keyframes pen {
0%, 100% { transform: rotate(-8deg) translateY(0); }
50% { transform: rotate(10deg) translateY(-6px); }
}
/* ===== 表格 ===== */
table { width: 100%; border-collapse: collapse; }
th {
background: #fff3bf; color: #2b2b2b; text-align: left; cursor: pointer; user-select: none;
padding: 11px 14px; font-weight: 800; letter-spacing: .3px;
border-bottom: 3px solid #2b2b2b; font-size: 14px; white-space: nowrap;
}
th .arrow { color: #e8590c; margin-left: 3px; }
td { padding: 11px 14px; border-bottom: 2px dashed #ced4da; font-weight: 600; vertical-align: middle; }
tr:last-child td { border-bottom: none; }
tbody tr:hover td { background: #ffecb3; }
.fname-cell { display: flex; flex-direction: column; gap: 4px; min-width: 200px; }
.filename { font-weight: 800; word-break: break-all; }
.fname-meta { display: flex; gap: 8px; align-items: center; }
.ext {
display: inline-block; padding: 1px 8px;
border: 2px solid #2b2b2b; border-radius: 50%;
background: #d0ebff; font-size: 10px; font-weight: 800; color: #1971c2;
transform: rotate(-4deg);
}
.sha { font-family: "Courier New", Consolas, monospace; color: #868e96; font-size: 11.5px; cursor: help; font-weight: 700; }
tbody tr:hover .sha { color: #2b2b2b; }
.empty { padding: 46px 20px; text-align: center; font-weight: 700; font-size: 15px; color: #2b2b2b; }
.empty svg { margin-bottom: 14px; }
.empty .et { display: inline-block; border: 2.5px dashed #adb5bd;
border-radius: 15px 255px 15px 255px / 255px 15px 255px 15px;
padding: 10px 26px; background: #fffdf3; }
a.dl, a.cp, a.rm { text-decoration: none; font-weight: 800; font-size: 13.5px; padding: 0 3px; margin-right: 6px; }
a.dl { color: #1971c2; background: linear-gradient(transparent 62%, #a5d8ff 62%); }
a.dl:hover { background: #a5d8ff; }
a.cp { color: #2f9e44; background: linear-gradient(transparent 62%, #b2f2bb 62%); }
a.cp:hover { background: #b2f2bb; }
a.rm { color: #e03131; background: linear-gradient(transparent 62%, #ffc9c9 62%); }
a.rm:hover { background: #ffc9c9; }
.who { font-weight: 800; }
.who.center { color: #1971c2; }
.footer {
display: flex; justify-content: space-between; align-items: center;
padding: 12px 18px; border-top: 2.5px dashed #adb5bd;
font-weight: 700; font-size: 12.5px; color: #495057;
}
.footer .dot { color: #e8590c; }
/* ===== 修改密码弹窗(便签)===== */
.mask {
position: fixed; inset: 0; background: rgba(43,43,43,.45);
display: flex; align-items: center; justify-content: center; z-index: 99; padding: 24px;
}
.modal {
position: relative; width: 410px; background: #fffef8;
border: 2.5px solid #2b2b2b;
border-radius: 255px 15px 225px 15px / 15px 225px 15px 255px;
box-shadow: 6px 8px 0 rgba(0,0,0,.16); padding: 36px 34px 30px;
transform: rotate(.5deg);
}
.modal .tape { top: -13px; left: 50%; margin-left: -46px; transform: rotate(2deg); }
.modal h3 { font-size: 21px; font-weight: 800; }
.modal .msub { font-size: 12.5px; color: #868e96; font-weight: 700; margin: 3px 0 16px; }
.modal input {
width: 100%; padding: 10px 14px; border: 2.5px solid #2b2b2b;
border-radius: 255px 15px 225px 15px / 15px 225px 15px 255px;
font-family: inherit; font-size: 14px; font-weight: 600; outline: none;
margin-bottom: 12px; background: #fff;
}
.modal input:focus { background: #fff9db; }
.modal .mrow { display: flex; gap: 10px; justify-content: flex-end; margin-top: 8px; }
.modal .pwd-msg {
margin-bottom: 12px; background: #ffe3e3; color: #c92a2a;
padding: 9px 12px; font-weight: 700; font-size: 12.5px;
border: 2.5px dashed #c92a2a;
border-radius: 15px 255px 15px 255px / 255px 15px 255px 15px;
}
@media (max-width: 1000px) {
.stats { grid-template-columns: repeat(2, 1fr); }
th:nth-child(4), td:nth-child(4), th:nth-child(5), td:nth-child(5) { display: none; }
.header .pin.r { display: none; }
}
</style>
</head>
<body>
<div id="app">
<!-- 登录界面 -->
<div class="login-wrap" v-if="!loggedIn">
<div class="login-card">
<span class="tape"></span>
<span class="pin">📌</span>
<div class="emblem">37</div>
<h2>文件服务器管理</h2>
<div class="login-sub">37DU 内网文件服务器 · 管理台</div>
<div class="login-field">
<input type="text" v-model="username" placeholder="账号" @keyup.enter="login">
</div>
<div class="login-field">
<input :type="showPwd ? 'text' : 'password'" v-model="password" placeholder="密码" @keyup.enter="login">
<span class="eye" @click="showPwd = !showPwd">{{ showPwd ? '🙈' : '👁' }}</span>
</div>
<button class="btn btn-primary" @click="login" :disabled="loggingIn">{{ loggingIn ? "登录中…" : "登 录" }}</button>
<div class="login-hint">初始账号 puddy / 123456,登录后请尽快修改密码</div>
<div class="login-msg" v-if="loginMsg">{{ loginMsg }}</div>
</div>
</div>
<!-- 主界面 -->
<template v-else>
<div class="header">
<span class="pin l">📌</span>
<span class="pin r">📌</span>
<div class="brand">
<div class="emblem">37</div>
<div>
<h1>文件服务器管理 <span class="squiggle"></span></h1>
<div class="sub">{{ baseUrl }} · 登录用户:{{ tokenUser }}</div>
</div>
</div>
<div class="actions">
<button class="btn" @click="openPwdModal">改密码</button>
<button class="btn" @click="logout">退出</button>
<button class="btn btn-primary" @click="load">↻ 刷新</button>
</div>
</div>
<div class="stats">
<div class="stat"><span class="tape"></span><div class="k">文件数</div><div class="v">{{ totalCount }}</div></div>
<div class="stat"><span class="tape"></span><div class="k">总大小</div><div class="v">{{ totalSizeText }}</div></div>
<div class="stat"><span class="tape"></span><div class="k">总下载</div><div class="v">{{ totalDownloads }}</div></div>
<div class="stat"><span class="tape"></span><div class="k">最近上传</div><div class="v" style="font-size:15px;line-height:1.4">{{ lastUploadText }}</div></div>
</div>
<div class="toolbar">
<input type="text" v-model="keyword" placeholder="搜索文件名…">
<label class="btn btn-success upload-btn">
⬆ 上传文件
<input type="file" multiple @change="onFilesPicked">
</label>
<span v-if="uploading" class="tag">上传 {{ uploadIdx }}/{{ uploadTotal }} {{ uploadPercent }}%</span>
<span class="hint" style="flex:1"></span>
<span class="hint">点击表头排序 · 元数据存 MySQL</span>
</div>
<div class="status-bar" :class="statusClass">{{ statusMsg }}</div>
<div class="main">
<div class="loading" v-if="loading"><span class="pen">✏️</span> 翻本子中…</div>
<div class="card" v-else>
<span class="tape"></span>
<table>
<thead>
<tr>
<th style="width:42px">#</th>
<th @click="sortBy('filename')">文件名<span class="arrow" v-if="sortKey==='filename'">{{ sortDir===1?'▲':'▼' }}</span></th>
<th style="width:90px" @click="sortBy('size')">大小<span class="arrow" v-if="sortKey==='size'">{{ sortDir===1?'▲':'▼' }}</span></th>
<th style="width:160px" @click="sortBy('created')">上传时间<span class="arrow" v-if="sortKey==='created'">{{ sortDir===1?'▲':'▼' }}</span></th>
<th style="width:90px">上传人</th>
<th style="width:70px" @click="sortBy('downloads')">下载<span class="arrow" v-if="sortKey==='downloads'">{{ sortDir===1?'▲':'▼' }}</span></th>
<th style="width:190px">操作</th>
</tr>
</thead>
<tbody v-if="sortedFiles.length">
<tr v-for="(f, i) in sortedFiles" :key="f.fid">
<td style="color:#adb5bd;font-weight:800">{{ i + 1 }}</td>
<td>
<div class="fname-cell">
<span class="filename">{{ f.filename }}</span>
<span class="fname-meta">
<span class="ext">{{ extOf(f.filename) }}</span>
<span class="sha" :title="f.sha256">{{ shortSha(f.sha256) }}</span>
</span>
</div>
</td>
<td>{{ fmtSize(f.size) }}</td>
<td>{{ fmtTime(f.created) }}</td>
<td><span class="who" :class="f.uploader==='center'?'center':''">{{ whoLabel(f.uploader) }}</span></td>
<td>{{ f.downloads || 0 }}</td>
<td>
<a class="dl" :href="downloadUrl(f)" target="_blank" rel="noopener">下载</a>
<a class="cp" href="javascript:;" @click="copyLink(f)">复制</a>
<a class="rm" href="javascript:;" @click="remove(f)">删除</a>
</td>
</tr>
</tbody>
<tbody v-else>
<tr><td colspan="7">
<div class="empty">
<svg width="150" height="120" viewBox="0 0 150 120" fill="none" stroke="#2b2b2b" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
<path d="M20 36 Q22 31 27 31 L56 31 L67 41 L129 41"/>
<path d="M15 41 L135 41 Q139 42 139 46 L139 96 Q139 101 134 101 L16 101 Q11 101 11 96 L11 46 Q11 42 15 41 Z"/>
<path d="M18 51 L132 51" stroke="#ffd43b" stroke-width="5" opacity=".65"/>
<path d="M96 22 L110 13"/>
<path d="M112 28 L128 20"/>
<path d="M86 14 L92 4"/>
<path d="M102 8 l13 8 -6 10 -13 -8 z" transform="rotate(-12 108 17)"/>
<path d="M82 4 l10 6 -5 8 -10 -6 z" transform="rotate(-30 87 11)"/>
</svg>
<div class="et">📭 暂无文件{{ keyword ? '(与搜索条件匹配)' : '' }}</div>
</div>
</td></tr>
</tbody>
</table>
<div class="footer">
<span>37DU <span class="dot">✏️</span> 内网文件服务器</span>
<span>DOODLE ADMIN v2.2</span>
</div>
</div>
</div>
<!-- 修改密码弹窗 -->
<div class="mask" v-if="showPwdModal">
<div class="modal">
<span class="tape"></span>
<h3>修改密码</h3>
<div class="msub">修改后需重新登录</div>
<div class="pwd-msg" v-if="pwdMsg">{{ pwdMsg }}</div>
<input type="password" v-model="oldPwd" placeholder="旧密码">
<input type="password" v-model="newPwd" placeholder="新密码(至少 6 位)">
<input type="password" v-model="newPwd2" placeholder="确认新密码">
<div class="mrow">
<button class="btn" @click="closePwdModal">取消</button>
<button class="btn btn-primary" @click="changePwd" :disabled="savingPwd">{{ savingPwd ? "保存中…" : "保存" }}</button>
</div>
</div>
</div>
</template>
</div>
<script src="/vue.global.prod.js"></script>
<script src="/app.js"></script>
</body>
</html>
+20 -204
View File
@@ -1,224 +1,40 @@
# -*- coding: utf-8 -*-
"""内网文件服务器(独立 FastAPI,端口 8802)。
"""内网文件服务器入口(组装层)。
职责:存放大型文件(壳子更新包、Chrome 安装包等),供执行机内网直连下载。
设计:中心机只存本服务器返回的内网直链,不转发大包。
职责:lifespan 初始化存储(自动建表)+ 启动心跳上报,装配各领域路由。
- core/config.py 配置(.env)
- core/auth.py 鉴权(X-API-Token / 管理会话)
- core/store.py 存储(文件落盘 + MySQL 元数据,未配库时 JSON 兜底)
- core/heartbeat.py 中心机心跳上报
- apis/ 路由子包(meta / files / admin)
接口鉴权:
- 上传 / 删除 / 列表需 HTTP 头 `X-API-Token`(值 = FILESERVER_TOKEN)
- 下载开放(内网环境,客户端拿到链接直接下)
运行(桌面端,cwd = desktop/):python -m fileserver.main
运行(cwd = desktop/,模块搜索根 = desktop/):
python -m fileserver.main
"""
from __future__ import annotations
import hashlib
import json
import logging
import re
import secrets
import socket
import threading
import time
import urllib.request
from contextlib import asynccontextmanager
from pathlib import Path
from fastapi import FastAPI, Header, HTTPException, UploadFile
from fastapi.responses import FileResponse
from fastapi import FastAPI
from fileserver.core import config
log = logging.getLogger("fileserver.heartbeat")
_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)
# 进程启动时间(心跳上报 uptime 用)
_START_TS = time.time()
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 {}
# ==================== 中心机心跳上报(主动上报状态,供中心机监控在线/离线) ====================
def _server_status() -> dict:
"""收集本服务器状态快照:文件数/占用/主机/IP/运行时长等。"""
meta_files = list(_STATUS_DIR.glob("*.json"))
total = 0
for mf in meta_files:
try:
m = json.loads(mf.read_text(encoding="utf-8"))
total += int(m.get("size") or 0)
except Exception: # noqa: BLE001
pass
hostname = socket.gethostname()
ip = ""
try:
ip = socket.gethostbyname(hostname)
except OSError: # noqa: BLE001
pass
return {
"host": config.BASE_URL, # 中心机以其唯一标识本服务器(默认=对外下载根)
"base_url": config.BASE_URL,
"hostname": hostname,
"ip": ip,
"port": config.PORT,
"file_count": len(meta_files),
"total_size": total,
"version": "37du-fileserver",
"uptime_sec": int(time.time() - _START_TS),
}
def _post_heartbeat() -> bool:
"""单次上报心跳到中心机;成功返回 True。"""
payload = json.dumps(_server_status(), ensure_ascii=False).encode("utf-8")
req = urllib.request.Request(
f"{config.CONTROLPLANE_URL}/api/fileserver/heartbeat",
data=payload, method="POST")
req.add_header("Content-Type", "application/json")
if config.CONTROLPLANE_TOKEN:
req.add_header("X-API-Token", config.CONTROLPLANE_TOKEN)
try:
with urllib.request.urlopen(req, timeout=10) as resp:
return resp.status < 400
except OSError as exc: # noqa: BLE001 网络/中心机异常按失败处理
log.warning("心跳上报失败:%s", exc)
return False
def _heartbeat_loop() -> None:
"""后台线程:周期向中心机上报心跳。未配置 CONTROLPLANE_URL 则直接退出。
每次上报最多重试 3 次(项目级重试约定),三次失败记错误日志;不阻塞文件服务。
"""
if not config.CONTROLPLANE_URL:
log.info("未配置 CONTROLPLANE_URL,跳过心跳上报")
return
while True:
try:
ok = False
for _i in range(3):
if _post_heartbeat():
ok = True
break
if not ok:
log.error("心跳上报连续失败(3 次):%s", config.CONTROLPLANE_URL)
except Exception: # noqa: BLE001 上报异常不拖垮文件服务
log.exception("心跳上报线程异常")
time.sleep(max(5, config.HEARTBEAT_INTERVAL))
from fileserver.core import config, store
from fileserver.core.heartbeat import start as start_heartbeat
from fileserver.apis import admin, files, meta
@asynccontextmanager
async def _lifespan(_app: FastAPI):
threading.Thread(target=_heartbeat_loop, daemon=True,
name="fileserver-heartbeat").start()
store.init() # 建数据目录 + DB 模式自动建表
start_heartbeat() # 中心机心跳上报(daemon 线程)
yield
app = FastAPI(title="37du 内网文件服务器", lifespan=_lifespan)
@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")))}
app = FastAPI(title="37du 内网文件服务器", version=config.VERSION, lifespan=_lifespan)
app.include_router(meta.router)
app.include_router(files.router)
app.include_router(admin.router)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=config.PORT)
uvicorn.run(app, host="0.0.0.0", port=config.PORT)
+4 -3
View File
@@ -1,3 +1,4 @@
fastapi>=0.110
uvicorn>=0.29
python-multipart>=0.0.9
fastapi>=0.110
uvicorn>=0.29
python-multipart>=0.0.9
PyMySQL>=1.1
-31
View File
@@ -1,31 +0,0 @@
@echo off
REM ===== 37du intranet file server build script (run on Windows) =====
REM prereq: desktop/.venv with fastapi uvicorn python-multipart pyinstaller
REM usage: run inside desktop\ directory with project .venv
setlocal
cd /d %~dp0\..\..
set PY=..\.venv\Scripts\python.exe
if not exist %PY% (
echo [err] PYTHON NOT FOUND: %PY% - run from desktop\ and ensure .venv exists
pause & exit /b 1
)
echo [1/3] building exe ...
%PY% -m PyInstaller fileserver\tools\37du-fileserver.spec ^
--distpath fileserver\dist-exe ^
--workpath fileserver\build-exe ^
--noconfirm
if errorlevel 1 (echo [err] BUILD FAILED & pause & exit /b 1)
echo [2/3] assembling deploy dir ...
set DEP=fileserver\dist-exe\fileserver
if not exist %DEP% mkdir %DEP%
REM copy .env next to exe (contains FILESERVER_BASE_URL pointing to intranet)
copy /y fileserver\.env %DEP%\.env >nul
move /y fileserver\dist-exe\37du-fileserver.exe %DEP%\37du-fileserver.exe >nul
echo [3/3] done.
echo deploy dir: %DEP%
echo deploy to 172.30.35.135: adjust FILESERVER_BASE_URL/TOKEN in .env, then run install_autostart.bat
pause
@@ -1,47 +0,0 @@
@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
-17
View File
@@ -1,17 +0,0 @@
@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
@@ -1,7 +0,0 @@
@echo off
REM ===== 37du 内网文件服务器 卸载开机自启 =====
setlocal
echo 正在删除 37du-FileServer 计划任务 ...
schtasks /delete /tn "37du-FileServer" /f >nul 2>&1
echo [ok] 已卸载开机自启(服务文件未删除,可手动运行 exe 启动)。
pause
+13
View File
@@ -98,3 +98,16 @@ d:\work\code\37duAutomation\.venv\Scripts\python.exe -m controlplane.tools.agent
- 插件发布后:执行机下次启动自动检测下载;插件登录后按权限自动下载更新。
- 壳子发布后:执行机自动下载,前端提示后点击升级。
- 版本冲突 / 更新失败:查执行机 `plugin_sync.py` 与 `shell_updater.py` 日志;核对中心机版本清单与授权。
## 7. Agent 技能(skills)
发版/上传/账号管理已封装为 Trae agent 技能,agent 按需加载执行:
| 技能 | 用途 |
|------|------|
| `.trae/skills/37du-Agent-CLI/SKILL.md` | CLI 用法与鉴权总纲(先读) |
| `.trae/skills/37du-Plugin-Release/SKILL.md` | 插件发版 / 授权 / 状态管理 |
| `.trae/skills/37du-File-Release/SKILL.md` | 壳子/大文件上传发版(file push) |
| `.trae/skills/37du-Account-Permission/SKILL.md` | 账号与权限管理 |
> 实际账号统一 `puddy / 123456`;`agent_cli` 已默认 `--admin puddy`,支持 `--json` 机器输出与 `ping` 预检。
@@ -38,6 +38,8 @@
不推送过滤(不纳入异常、不推送):
- 「现职位序列」命中 经营系管理序列 / 职能系专业序列 / 门店技师序列 的,直接剔除;
- 调动名单:「现职位序列」为 职能管理序列/职能系管理序列、职能专业序列/职能系专业序列
且「原单位」=「现单位」(单位未变)的,不纳入异常;
- 花名册查不到工号的按离职处理剔除(调动+预入职均生效)。
店长解析(花名册):
@@ -165,6 +167,12 @@ MANAGER_KEYWORD = "店长"
# 现职位序列命中以下序列的异常不推送(不纳入异常、不推送)
EXCLUDE_SEQ_KEYWORDS = ("经营系管理序列", "职能系专业序列", "门店技师序列")
# 调动名单:现职位序列命中以下职能序列且「原单位」=「现单位」(单位未变)的,不纳入异常
# (台账实际值带"系",如「职能系管理序列」,故带系/不带系两种写法都收录)
FUNC_SEQ_UNIT_UNCHANGED_KEYWORDS = (
"职能管理序列", "职能系管理序列",
"职能专业序列", "职能系专业序列",
)
# 无法解析店长时归入默认处理人(多个英文逗号分隔则轮流分配;空则不归并、仅记录不推送)
DEFAULT_MANAGER = os.getenv("shift_abnormal_default_manager", "")
@@ -513,6 +521,11 @@ def _check_transfer_row(fetcher: "_ShiftFetcher", dept_fetcher: "_DeptShiftFetch
seq = _clean(r.get("现职位序列"))
if _seq_excluded(seq):
return None
# 职能管理序列/职能专业序列:原单位与现单位保持一致(单位未变)的不纳入异常
if any(kw in seq for kw in FUNC_SEQ_UNIT_UNCHANGED_KEYWORDS):
old_unit, new_unit = _clean(r.get("原单位")), _clean(r.get("现单位"))
if old_unit and new_unit and old_unit == new_unit:
return None
if "职能" in seq:
target_field, target_name = "现单位", _clean(r.get("现单位"))
else:
@@ -0,0 +1,48 @@
# -*- coding: utf-8 -*-
"""只读探针:新签合同分支跑前排查(AI表格名单 + 门控状态核查,不写库不回填)。"""
import importlib.util
import json
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
def _load(name, path):
spec = importlib.util.spec_from_file_location(name, path)
m = importlib.util.module_from_spec(spec)
sys.modules[name] = m
spec.loader.exec_module(m)
return m
s = _load("snc", os.path.join(HERE, "sign_new_contract.py"))
sess = s._build_session()
print("== 1) AI表格待新签名单(人资处理=是 且 离职推送时间非空 且 新合同推送日期为空,排除超龄)==")
targets = s.fetch_new_contract_targets()
for t in targets:
print(f" {t['base_code']} {t['staff_name']} 单位={t['contract_unit']!r} 行ID={t['record_id']}")
print("\n== 2) 逐条门控核查(只读)==")
for t in targets:
code = t["base_code"]
print(f"\n-- {code} {t['staff_name']} --")
c = s.query_active_contract(sess, code)
print(f" 生效中合同: {'有 contract_id=' + str(c.get('contract_id')) if c and c.get('contract_id') else '无'}")
row = s._query_no_contract_roster(sess, code)
if row is None:
print(" 未签合同: 查无此人")
continue
lc = s._parse_last_contract(row.get("lastContractInfo.last_contract_info"))
print(f" 未签合同: 命中 姓名={row.get('hr_staff_base.staff_name')!r} "
f"sex={row.get('hr_staff_base.sex')!r} birthday={row.get('hr_staff_base.birthday')!r}")
print(f" 上一份合同: {json.dumps(lc, ensure_ascii=False)[:300]}")
contract_id = row.get("hr_staff_contract.contract_id") or ""
wf = s.query_transfer_workflow(sess, business_key=contract_id) if contract_id else None
if wf:
pid = wf.get("process_id") or ""
done = s.is_flow_completed(sess, pid) if pid else None
print(f" 离职电子签: 已发起 process_id={pid} 办结={done}")
else:
print(" 离职电子签: 反查不到流程(视为可继续,由合同状态兜底)")
@@ -0,0 +1,75 @@
# -*- coding: utf-8 -*-
"""
@FileName: run_change_confirm.py
@Description: XQ0035 单独执行「变更试用期 + 确认」两步(真实 HR 写操作,跳过电子签环节)。
链路:查询试用期人员 -> 提交变更试用期(变更试用期/新1个月/结束=原到期+1月)-> 查待确认 -> 确认生效。
用法:.venv\\Scripts\\python.exe run_change_confirm.py [工号](默认 37036273)
"""
import importlib.util
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
MODULE_PATH = os.path.join(HERE, "trial_period_change.py")
def _load(name, path):
spec = importlib.util.spec_from_file_location(name, path)
m = importlib.util.module_from_spec(spec)
sys.modules[name] = m
spec.loader.exec_module(m)
return m
def main():
code = (sys.argv[1] if len(sys.argv) > 1 else "37036273").strip()
tpc = _load("tpc", MODULE_PATH)
# 与 process_one 一致的任务参数(延期转正、新试用期 1 个月、结束=原到期顺延 1 个月)
trial_end_date = "2026-09-26"
task = {"base_code": code, "trial_end_date": trial_end_date,
"correction_type": tpc.FIXED_CORRECTION_TYPE, "new_period_date": tpc.FIXED_NEW_PERIOD_MONTHS}
new_period_end_date = tpc._defer_end_date(task["trial_end_date"])
print(f"工号 {code}:变更类型={task['correction_type']} 新试用期={task['new_period_date']}月 "
f"结束={new_period_end_date}(原到期 {trial_end_date} 顺延 1 个月)")
s = tpc._build_session()
# 2) 查询试用期人员
print("\n[2/4] 查询试用期人员……")
staff = tpc.query_trial_staff(s, code)
if not staff:
print("❌ 未在「试用期人员」找到,无法继续")
return
base_id = staff.get("hr_staff_base.base_id")
print(f" 命中 {staff.get('hr_staff_base.staff_name')} base_id={base_id}")
# 3) 提交变更试用期
print("\n[3/4] 提交变更试用期……")
resp = tpc.change_trial_period(s, base_id, task["correction_type"],
task["new_period_date"], new_period_end_date)
print(f" state={resp.get('state')} meg={resp.get('meg')}")
if str(resp.get("state")) != "1":
print("❌ 变更提交失败")
return
# 4) 查询待确认记录
print("\n[4/4] 查询「变更/转正待确认」……")
pend = tpc.query_pending(s, code)
if not pend:
print("❌ 未找到待确认记录,需人工检查")
return
management_id = pend.get("hr_staff_probation.management_id")
print(f" 命中 management_id={management_id}")
# 5) 确认
print("\n[5/4] 执行确认……")
c_resp = tpc.confirm_pending(s, management_id)
print(f" state={c_resp.get('state')} meg={c_resp.get('meg')}")
if str(c_resp.get("state")) != "1":
print("❌ 确认失败")
return
print("\n✅ 变更试用期 + 确认完成并生效。")
if __name__ == "__main__":
main()
@@ -0,0 +1,47 @@
# -*- coding: utf-8 -*-
"""
@FileName: run_sign_new_contract.py
@Description: XQ0035 单独执行「新签合同」(真实 HR 写操作,跳过 AI表格选择,按工号直接驱动新签分支)。
链路:查生效中合同(仍有→跳过)-> 查未签合同(查无→跳过)-> 查离职电子签流程办结(未办结→跳过)-> 新签。
用法:.venv\\Scripts\\python.exe run_sign_new_contract.py [工号](默认 37036273)
"""
import importlib.util
import json
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
MODULE_PATH = os.path.join(HERE, "sign_new_contract.py")
def _load(name, path):
spec = importlib.util.spec_from_file_location(name, path)
m = importlib.util.module_from_spec(spec)
sys.modules[name] = m
spec.loader.exec_module(m)
return m
def main():
code = (sys.argv[1] if len(sys.argv) > 1 else "37036273").strip()
s = _load("sign_new_contract", MODULE_PATH)
session = s._build_session()
task = {"base_code": code, "staff_name": "", "contract_unit": None, "record_id": None}
print(f"工号 {code}:驱动新签合同分支 process_one(含门控:生效中合同/未签合同/流程办结)……")
result = s.process_one(session, task)
print()
print("== 结果 ==")
print(json.dumps({k: v for k, v in result.items() if k != "record_id"},
ensure_ascii=False, indent=1))
if result.get("status") == "成功" and result.get("signed"):
print("\n✅ 新签合同成功(真实写,已创建劳动合同并推送电子签)。")
elif result.get("error_type"):
print(f"\n🚨 超龄异常转人工:{result['error_type']}")
elif result.get("status") == "跳过":
print("\n⏳ 新签跳过(门控拦截,等下一次运行):", result.get("message"))
else:
print("\n❌ 新签失败:", result.get("message"))
if __name__ == "__main__":
main()
@@ -0,0 +1,666 @@
# -*- coding: utf-8 -*-
"""
@FileName: sign_effect_check.py
@Author: 小布丁
@CreateTime: 2026-10-09
@Description: XQ0035 服务岗转正不通过电子签(离职+入职)——签署生效复核分支(影刀单文件自包含,独立排程 10:00)。
与主流程 trial_period_change.py / 新签分支 sign_new_contract.py 完全解耦(登录/AI表格读写等公共逻辑各自内置)。
选择条件(钉钉 AI表格「门店服务岗转正跟进-周更新」,aa.md 签署生效复核分支):
人资是否处理 = 是 且 签署跟进 ≠ 是。
同时覆盖自动新签与超龄人工新签两种情形(超龄人工新签生效后同样自动回填「签署跟进=是」)。
执行链(每条记录):
1. 到合同台账【生效中合同】按工号查询(返回全部匹配行,含合同起始日期);
2. 用「合同起始日期 > 试用期到期日期」判断是否为新合同:
旧合同起始日必然早于试用期到期日(先签合同后进试用期),
新合同起始日必然晚于试用期到期日(离职后才签);
3. 查到起始日期晚于试用期到期日期的生效中合同 -> 交叉验证电子签状态:
WeProcess 查该员工是否存在未办结的「改签离职电子签」流程(title 含「{姓名}-改签离职电子签」),
有 -> 台账先行/流程未走完,跳过等下次;无 -> 双证据齐备;
4. 双证据通过 -> 新合同已签署生效,AI表格回填「签署跟进 = 是」;
5. 只查到旧合同(起始日期 <= 试用期到期日期,离职解除尚未生效)或查无 ->
尚未生效,跳过,等下一次运行再检测。
接口清单(抓包确认,登录态基于共享 HR cookies):
0. 查生效中合同:POST /RedseaPlatform/hrRoster/614ffe05-b4f1-11ea-b588-14187743d052/queryRealTimeData.mc
(menuName=合同台账,tableId=assemble-hr_staff_contract;行含 hr_staff_contract.contract_start_date)
0b. 电子签办结交叉验证:POST /RedseaPlatform/WeProcess.mc?method=getProcessAndData
(title=改签离职电子签;仅含运行中流程的活动任务,title 含「{姓名}-改签离职电子签流程」)
⚠️ 安全提示:本脚本回填钉钉 AI表格(签署跟进=是),执行前请务必核对员工与参数。
登录态直接读取共享 hr_cookies.json(由「37duHR登录」指令写入),缺失/失效时友好提示,不自动补登。
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
pip install requests pandas openpyxl
运行方式:
1. 影刀:注册为自定义指令「37du签署生效复核」,main() 关键字传参;从 AI表格名单读取待复核记录。
2. 命令行:python sign_effect_check.py 直接运行(默认不执行,打印用法,避免误触线上写操作)。
3. 业务脚本:importlib 加载本模块调用 main(...)。
全局变量:messages(结果摘要文本列表,供「37du钉钉群机器人推送」指令逐条发送)
"""
import json
import os
import time
import urllib.parse
from datetime import date, datetime, timedelta
try:
import requests
import pandas as pd
except ImportError as _import_err:
raise RuntimeError(
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
"请先执行安装:\n"
" pip install requests pandas openpyxl\n"
f"缺失依赖详情: {_import_err}"
)
# ==================== 日志(print 替代 logging,正常 INFO 不输出大体积 JSON) ====================
class _PrintLogger:
def debug(self, msg, *args, **kwargs):
print(msg % args if args else msg)
def info(self, msg, *args, **kwargs):
print(msg % args if args else msg)
def warning(self, msg, *args, **kwargs):
print(msg % args if args else msg)
def error(self, msg, *args, **kwargs):
print(msg % args if args else msg)
logger = _PrintLogger()
# ==================== 路径 & 常量配置 ====================
_APP_DATA_DIR = os.path.join(
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
'37duAutomation')
SHARED_HR_COOKIE_FILE = os.path.join(_APP_DATA_DIR, '.sessions', 'hr_cookies.json')
HR_BASE_URL = "https://hr.37du.co"
# ---------- 合同台账-生效中合同 Tab ----------
ROSTER_ID_ACTIVE_CONTRACT = "614ffe05-b4f1-11ea-b588-14187743d052"
TABLE_ID_CONTRACT = "assemble-hr_staff_contract"
QUERY_ACTIVE_CONTRACT_URL = (f"{HR_BASE_URL}/RedseaPlatform/hrRoster/"
f"{ROSTER_ID_ACTIVE_CONTRACT}/queryRealTimeData.mc")
# ---------- 流程实例查询(电子签办结交叉验证;与 sign_new_contract.py 同源抓包) ----------
WE_PROCESS_QUERY_URL = f"{HR_BASE_URL}/RedseaPlatform/WeProcess.mc?method=getProcessAndData"
# ---------- 会话/登录用户固定参数(抓包提取;登录用户变更时需同步更新) ----------
CURRENT_USER_ID = "178b0efa-8a65-11f1-a7d9-000c296f9469"
CURRENT_USER_NAME = "人资专用号"
CURRENT_STAFF_ID = "1342173e-36cf-4160-8826-6b17d7d084a4"
CURRENT_ROLE_IDS = "POST_SYS_ADMIN,renshi"
USER_AGENT = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"Chrome/120.0.0.0 Safari/537.36")
XHR_HEADERS = {"X-Requested-With": "XMLHttpRequest"}
# ==================== 钉钉 AI表格(名单来源:门店服务岗转正跟进-周更新) ====================
# 配置直接内置(影刀环境不读取 .env,统一在代码内固化,保证本地/影刀行为一致)
DINGTALK_APP_KEY = "dingc1fnokzybr3u5bbl"
DINGTALK_APP_SECRET = "AOKyKOc0byGpQkzd20_GqK9-G1LI-Py2qlNeOiCQpR2TnBtzuJCpBuldIqRWX58A"
AITABLE_BASE_ID = "YndMj49yWjPmvXXDFb1OBGAoJ3pmz5aA"
AITABLE_TABLE_ID = "uchjxPW"
AITABLE_OPERATOR_UNIONID = "zCEEdHDqKpY3iSAKxg33jEQiEiE"
# AI表格字段(生效复核分支用;AI表格已有「签署跟进」列,无需加列——已确认事项)
AITABLE_DONE_FIELD = "人资是否处理"
AITABLE_DONE_VALUE = "是"
AITABLE_SIGN_FOLLOW_FIELD = "签署跟进"
AITABLE_SIGN_FOLLOW_VALUE = "是"
AITABLE_TRIAL_END_FIELD = "试用期到期日期"
# 钉钉 AI表格接口(notable OpenAPI,头 x-acs-dingtalk-access-token;operatorId=操作人 unionId)
AITABLE_TOKEN_URL = "https://api.dingtalk.com/v1.0/oauth2/accessToken"
AITABLE_LIST_URL = (f"https://api.dingtalk.com/v1.0/notable/bases/{AITABLE_BASE_ID}/"
f"sheets/{AITABLE_TABLE_ID}/records/list")
AITABLE_UPDATE_URL = (f"https://api.dingtalk.com/v1.0/notable/bases/{AITABLE_BASE_ID}/"
f"sheets/{AITABLE_TABLE_ID}/records")
AITABLE_PAGE_SIZE = 100 # records/list 单页最大 100
AITABLE_WRITE_BATCH = 20 # 回写单次条数(≤100 即可,保守分批)
AITABLE_TOKEN_TTL = 3600 # 钉钉 accessToken 有效期兜底
# ---------- 项目级重试(最大 3 次,三次失败后再记录错误) ----------
MAX_ATTEMPTS = 3
RETRY_DELAY_BASE = 2.0
# ==================== commonQuery 前端加密(与主脚本同源实现) ====================
_CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
_SALT = "yyryrtweasdasd"
def _custom_base64_encode(data):
"""自定义字符表 Base64 编码(索引0~63 数据字符,64('7')为填充字符)。"""
result = []
for i in range(0, len(data), 3):
chunk = data[i:i + 3]
b1 = chunk[0] if len(chunk) > 0 else 0
b2 = chunk[1] if len(chunk) > 1 else 0
b3 = chunk[2] if len(chunk) > 2 else 0
enc1 = (b1 >> 2) & 0x3F
enc2 = ((b1 << 4) | (b2 >> 4)) & 0x3F
enc3 = ((b2 << 2) | (b3 >> 6)) & 0x3F
enc4 = b3 & 0x3F
if len(chunk) == 1:
enc3 = 64
enc4 = 64
elif len(chunk) == 2:
enc4 = 64
result.append(_CUSTOM_CHARS[enc1])
result.append(_CUSTOM_CHARS[enc2])
result.append(_CUSTOM_CHARS[enc3])
result.append(_CUSTOM_CHARS[enc4])
return ''.join(result)
def _encode_common_query(query_list):
"""将查询条件列表加密为 commonQuery(JSON->URI编码->自定义Base64+盐值->首尾重排)。"""
json_str = json.dumps(query_list, ensure_ascii=False, separators=(',', ':'))
uri_encoded = urllib.parse.quote(json_str, safe="-_.~!*'()")
en_str = _custom_base64_encode(uri_encoded.encode('utf-8')) + _SALT
return en_str[:2] + en_str[-3:] + en_str[2:-3]
def _build_like_condition(field, value):
"""构造 like 查询条件(等价前端 base_code like 抓包格式)。"""
return {
"queryField": f"`{field}`",
"leftBracket": "",
"queryType": "like",
"queryValue": str(value),
"queryText": str(value),
"rightBracket": "",
"logic": "AND",
"inputType": "text",
}
# ==================== 登录态(共享 cookies 文件) ====================
class LoginRequiredError(Exception):
"""HR 登录态缺失或失效。"""
def _build_session():
"""读取共享 HR cookies 构造 requests 会话(仅注入 37du.co 域 cookies)。"""
if not os.path.exists(SHARED_HR_COOKIE_FILE):
raise LoginRequiredError(
"未找到 HR 登录态 cookies,请先调用「37duHR登录」指令完成登录后再重试。")
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
cookies = json.load(f)
session = requests.Session()
session.headers.update({
"User-Agent": USER_AGENT,
"Content-Type": "application/x-www-form-urlencoded",
})
for c in cookies or []:
if c.get("domain") and "37du.co" in c["domain"]:
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
return session
def _is_expired(text):
"""接口正常返回 JSON;返回登录页/错误页等非 JSON 即视为登录态过期。"""
return bool(text) and not text.lstrip().startswith(("{", "["))
def _request_retry(method, url, session=None, retries=MAX_ATTEMPTS, **kwargs):
"""项目级重试:POST 请求,最大 MAX_ATTEMPTS 次;登录态失效不重试直接抛 LoginRequiredError。"""
headers = dict(kwargs.pop("headers", XHR_HEADERS))
last_exc = None
for attempt in range(1, retries + 1):
try:
resp = session.post(url, headers=headers, timeout=30, **kwargs)
text = resp.text
if _is_expired(text):
raise LoginRequiredError(
f"HR 登录态已失效({url} 返回非 JSON)。请先重新调用「37duHR登录」指令。")
return resp
except LoginRequiredError:
raise
except Exception as e:
last_exc = e
if attempt >= retries:
break
logger.warning("请求 %s 第 %d 次失败:%s,%.1f 秒后重试", url, attempt, e,
RETRY_DELAY_BASE * attempt)
time.sleep(RETRY_DELAY_BASE * attempt)
raise last_exc
# ==================== 动态日期参数 ====================
def _get_date_params():
"""生成查询接口所需的当月/上月/当年首月参数。"""
now = datetime.now()
year, month, day = now.year, now.month, now.day
last_month_date = datetime(year, month, 1) - timedelta(days=1)
return {
"currentDate": f"{year}-{month:02d}-{day:02d}",
"currentMonth": f"{year}{month:02d}",
"currentMonthBar": f"{year}-{month:02d}",
"lastMonth": f"{last_month_date.year}{last_month_date.month:02d}",
"lastMonFirstDay": f"{last_month_date.year}-{last_month_date.month:02d}-01",
"lastMonLastDay": last_month_date.strftime("%Y-%m-%d"),
"curYearFirstMon": f"{year}01",
"curYearFirstMonBar": f"{year}-01",
}
def _build_query_params(roster_id, table_id, common_query, menu_name="合同台账"):
"""构造 queryRealTimeData.mc 完整参数(menu_name 按台账传入)。"""
now_ms = str(int(time.time() * 1000))
return {
"menuName": menu_name,
"useSealTreeData": "0",
"treePermitType": "permit",
"clickFlag": "true",
"_t": now_ms,
"in_use": "1",
"commonQuery": common_query,
"newCondition": "",
"urlConditions": f"_t:{now_ms}#clickFlag:true#treePermitType:permit#useSealTreeData:0#menuName:{menu_name}#_t:{now_ms}#",
"exportConfig": "",
"tableId": table_id,
"rosterId": roster_id,
"includeChildrenSetting": "",
"struTreeCode": "",
"djStruTreeCode": "",
"djStruId": "",
"djOrgName": "",
"struId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
"belongUnitStruId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
"rootId": "cq37du",
"isVirtual": "0",
"currentUserRootId": "cq37du",
"currentUserId": CURRENT_USER_ID,
"currentRoleIds": CURRENT_ROLE_IDS,
"currentStaffId": CURRENT_STAFF_ID,
"baseHrefPath": "http:hr.37du.co:80RedseaPlatform",
"qrCodeUrl": "jspresumepage-01.jsp",
"orgName": "集团",
"belongUnitOrgName": "集团",
"throughParam": "",
"start": "0",
"sortType": "",
"sortName": "",
"pageNo": "1",
"pageSize": "15",
}
# ==================== 生效中合同查询(含起始日期,判新旧合同) ====================
def query_active_contracts(session, base_code):
"""按工号在【劳动关系→合同台账→生效中合同】Tab 查询所有匹配行。
Returns:
list[dict]:{contract_id, staff_name, contract_start_date, contract_end_date};无匹配返回 []
"""
params = _build_query_params(
ROSTER_ID_ACTIVE_CONTRACT, TABLE_ID_CONTRACT,
_encode_common_query([_build_like_condition("hr_staff_base.base_code", base_code)]),
menu_name="合同台账")
params.update(_get_date_params())
resp = _request_retry("POST", QUERY_ACTIVE_CONTRACT_URL, session, data=params)
datas = resp.json().get("datas") or []
rows = []
for row in datas:
if str(row.get("hr_staff_base.base_code")) == str(base_code):
rows.append({
"contract_id": row.get("hr_staff_contract.contract_id") or "",
"staff_name": row.get("hr_staff_base.staff_name") or "",
"contract_start_date": row.get("hr_staff_contract.contract_start_date") or "",
"contract_end_date": row.get("hr_staff_contract.contract_end_date") or "",
})
return rows
def has_running_esign_process(session, staff_name):
"""电子签办结交叉验证:该员工是否存在未办结的「改签离职电子签」流程。
WeProcess 列表(title=改签离职电子签)仅含运行中流程的活动任务行,行 title 形如
「门店 岗位 {姓名}-改签离职电子签流程」;已办结流程或从未发起(纯人工新签)均查不到。
因此「查无匹配行」⟺ 流程已办结/未发起 ⟺ 交叉验证通过(保守方向:宁跳过不误回填)。
Returns:
(bool 是否存在未办结流程, str 描述信息)
"""
params = {
"version": "", "PACKAGE_ID": "cq37du", "process_type": "", "defProcessType": "",
"struId": "", "rootId": "cq37du", "taskIds": "", "title": "改签离职电子签",
"state": "", "startTime": "", "endTime": "",
"sortType": "desc", "sortName": "CREATE_TIME",
"commonQuery": "[]", "start": "0", "pageNo": "1", "pageSize": "50",
}
resp = _request_retry("POST", WE_PROCESS_QUERY_URL, session, data=params)
d = resp.json()
if str(d.get("state")) == "Nosession":
raise LoginRequiredError(f"流程查询返回 Nosession:{d.get('meg') or '会话过期,请重新登录!'}")
rows = d.get("jsonList") or d.get("datas") or []
key = f"{(staff_name or '').strip()}-改签离职电子签"
matched = [r for r in rows if key in str(r.get("title") or "")]
if not matched:
return False, "无未办结的改签离职电子签流程"
m = matched[0]
desc = (f"流程未办结:{m.get('title')}(环节 {m.get('currentActivityName') or m.get('activityName')},"
f"发起人 {m.get('createUserName') or '未知'} {m.get('startTime') or ''})")
return True, desc
# ==================== 日期工具 ====================
def _to_date(val):
"""统一为 date:支持毫秒时间戳 / datetime / Timestamp / yyyy-MM-dd 字符串;失败返回 None。"""
if val is None or val == "":
return None
if isinstance(val, datetime):
return val.date()
if isinstance(val, pd.Timestamp):
return val.date()
if isinstance(val, (int, float)):
try:
return datetime.fromtimestamp(float(val) / 1000.0).date() # AI表格 date 字段为毫秒时间戳
except (ValueError, OSError, OverflowError):
return None
s = str(val).strip().replace("/", "-")
for fmt in ("%Y-%m-%d", "%Y-%m-%d %H:%M:%S"):
try:
return datetime.strptime(s[:19], fmt).date()
except ValueError:
continue
return None
# ==================== 钉钉 AI表格:名单读取 + 回填 ====================
_aitable_tok = {"at": "", "exp": 0.0}
def _aitable_token():
"""获取钉钉企业内部应用 accessToken(缓存到临近过期)。"""
now = time.time()
if _aitable_tok["at"] and _aitable_tok["exp"] > now + 60:
return _aitable_tok["at"]
resp = requests.post(AITABLE_TOKEN_URL,
json={"appKey": DINGTALK_APP_KEY, "appSecret": DINGTALK_APP_SECRET},
timeout=15)
d = resp.json()
at = d.get("accessToken", "")
if not at:
raise RuntimeError(f"钉钉 accessToken 获取失败:{d}")
_aitable_tok["at"] = at
_aitable_tok["exp"] = now + int(d.get("expireIn", AITABLE_TOKEN_TTL))
return at
def _aitable_headers():
return {"x-acs-dingtalk-access-token": _aitable_token(),
"Content-Type": "application/json"}
def _aitable_request(method, url, params=None, json_body=None, retries=MAX_ATTEMPTS):
"""钉钉 AI表格接口请求(带项目级重试 3 次)。"""
last_exc = None
for attempt in range(1, retries + 1):
try:
resp = requests.request(method, url, headers=_aitable_headers(),
params=params, json=json_body, timeout=20)
d = resp.json()
if d.get("code") not in (None, ""):
raise RuntimeError(f"钉钉接口错误 {d.get('code')}: {d.get('message')}")
return d
except Exception as e:
last_exc = e
if attempt >= retries:
break
logger.warning("钉钉请求 %s %s 第 %d 次失败:%s,%.1f 秒后重试",
method, url.split("/v1.0/")[-1], attempt, e,
RETRY_DELAY_BASE * attempt)
time.sleep(RETRY_DELAY_BASE * attempt)
raise last_exc
def _aitable_opt_name(field_value):
"""singleSelect 字段值 -> 选项名(记录值为 {"name": "...", "id": "..."})。"""
if isinstance(field_value, dict):
return field_value.get("name")
return field_value
def fetch_aitable_records():
"""分页全量读取钉钉 AI表格原始记录(含所有字段),供筛选/回填复用。
Returns:
list[dict]:原始 records 列表;失败抛 RuntimeError
"""
records, token = [], ""
for _ in range(200): # 兜底上限(200 页 * 100 条)
d = _aitable_request("POST", AITABLE_LIST_URL,
params={"operatorId": AITABLE_OPERATOR_UNIONID},
json_body={"maxResults": AITABLE_PAGE_SIZE, "nextToken": token})
recs = d.get("records") or []
records.extend(recs)
if d.get("hasMore") and d.get("nextToken"):
token = d["nextToken"]
else:
break
return records
def fetch_sign_effect_targets(records=None):
"""从钉钉 AI表格筛选待生效复核名单(aa.md 签署生效复核分支选择条件)。
条件:人资是否处理 = 是 且 签署跟进 ≠ 是(同时覆盖自动新签与超龄人工新签两种情形)。
Returns:
list[dict]:{record_id, base_code, staff_name, trial_end_date}
"""
records = records if records is not None else fetch_aitable_records()
targets = []
for rec in records:
fields = rec.get("fields") or {}
done = _aitable_opt_name(fields.get(AITABLE_DONE_FIELD))
follow = _aitable_opt_name(fields.get(AITABLE_SIGN_FOLLOW_FIELD))
if done != AITABLE_DONE_VALUE:
continue
if follow == AITABLE_SIGN_FOLLOW_VALUE:
continue
base_code = str(fields.get("员工工号") or "").strip()
if not base_code:
continue
targets.append({
"record_id": rec.get("id"),
"base_code": base_code,
"staff_name": str(fields.get("员工姓名") or "").strip(),
"trial_end_date": fields.get(AITABLE_TRIAL_END_FIELD),
})
logger.info("生效复核选择:AI表格 %d 条,命中待复核 %d 条", len(records), len(targets))
return targets
def mark_sign_follow(record_ids):
"""把 AI表格对应行「签署跟进」回填为「是」(新合同已签署生效)。
幂等分批;仅由 main() 在检测到新合同生效后调用。
Returns:
(成功数, 失败数)
"""
record_ids = [r for r in record_ids if r]
if not record_ids:
return 0, 0
ok, fail = 0, 0
for i in range(0, len(record_ids), AITABLE_WRITE_BATCH):
batch = record_ids[i:i + AITABLE_WRITE_BATCH]
try:
d = _aitable_request("PUT", AITABLE_UPDATE_URL,
params={"operatorId": AITABLE_OPERATOR_UNIONID},
json_body={"records": [
{"id": rid, "fields": {AITABLE_SIGN_FOLLOW_FIELD: AITABLE_SIGN_FOLLOW_VALUE}}
for rid in batch]})
value = d.get("value") or []
ok += len(value)
except Exception as e:
logger.error("AI表格回填「签署跟进=是」批次失败(%s):%s", batch, e)
fail += len(batch)
logger.info("AI表格回填「签署跟进=是」完成:成功 %d 条,失败 %d 条", ok, fail)
return ok, fail
# ==================== 影刀全局变量 ====================
def _set_glv(name, value):
"""写入影刀全局变量;非影刀环境(本地独立运行)时静默跳过。"""
try:
glv[name] = value
except Exception:
pass
def _build_messages(results):
"""按结果类型构造钉钉群推送消息列表(成功/跳过各一条汇总)。"""
ok = [r for r in results if r["status"] == "成功"]
skip = [r for r in results if r["status"] == "跳过"]
fail = [r for r in results if r["status"] not in ("成功", "跳过")]
messages = []
if ok:
lines = [f"✅ 新合同签署生效复核成功 {len(ok)} 人(回填「签署跟进=是」):"]
lines += [f" - {r.get('staff_name') or ''}({r['base_code']}):{r['message']}" for r in ok]
messages.append("\n".join(lines))
if skip:
lines = [f"⏳ 新合同生效复核跳过 {len(skip)} 人(未签署生效,等下次检测):"]
lines += [f" - {r['base_code']}:{r['message']}" for r in skip]
messages.append("\n".join(lines))
if fail:
lines = [f"❌ 新合同生效复核失败 {len(fail)} 人:"]
lines += [f" - {r['base_code']}:{r['message']}" for r in fail]
messages.append("\n".join(lines))
if not messages:
messages = ["签署生效复核:无任务"]
return messages
# ==================== 单员工处理 ====================
def process_one(session, task):
"""复核单条记录的新合同是否已签署生效。
执行链(aa.md 签署生效复核分支):
1) 生效中合同按工号查询(全部匹配行);
2) 用「合同起始日期 > 试用期到期日期」判断是否为新合同:
旧合同起始日必然早于试用期到期日(先签合同后进试用期),
新合同起始日必然晚于试用期到期日(离职后才签);
3) 查到起始日 > 试用期到期日的生效中合同 -> 新合同已签署生效,回填「签署跟进=是」;
4) 只查到旧合同(起始日 <= 试用期到期日,离职解除尚未生效)或查无 -> 跳过,等下次运行。
Returns:
dict {base_code, staff_name, status: 成功/跳过/失败, message, record_id}
"""
base_code = str(task["base_code"]).strip()
result = {
"base_code": base_code,
"staff_name": task.get("staff_name") or "",
"status": "跳过",
"message": "",
"record_id": task.get("record_id"),
}
trial_end = _to_date(task.get("trial_end_date"))
if trial_end is None:
result["status"] = "失败"
result["message"] = "无法解析 AI表格「试用期到期日期」,无法判断新旧合同,请人工核查"
logger.error("【%s】%s", base_code, result["message"])
return result
contracts = query_active_contracts(session, base_code)
if not contracts:
result["message"] = "【生效中合同】查无记录(新合同尚未签署生效),跳过,等下一次运行"
logger.info("【%s】%s", base_code, result["message"])
return result
result["staff_name"] = contracts[0].get("staff_name") or result["staff_name"]
for c in contracts:
start = _to_date(c.get("contract_start_date"))
if start and start > trial_end:
# 交叉验证:台账虽显示新合同生效,仍确认无未办结的改签离职电子签流程
# (防台账先行落行而流程实际未走完;宁跳过不误回填)
pending, esign_desc = has_running_esign_process(session, result["staff_name"])
if pending:
result["message"] = (f"台账显示新合同生效(起始 {start.isoformat()}),但交叉验证未过:"
f"{esign_desc},跳过,等下一次运行再检测")
logger.info("【%s】⏳ %s", base_code, result["message"])
return result
result["status"] = "成功"
result["message"] = (f"新合同已签署生效(起始 {start.isoformat()} > 试用期到期 "
f"{trial_end.isoformat()};电子签交叉验证:{esign_desc}),"
f"回填「签署跟进=是」")
logger.info("【%s】✅ %s", base_code, result["message"])
return result
old = contracts[0]
result["message"] = (f"生效中合同起始日 {old.get('contract_start_date') or '未知'} <= 试用期到期日"
f" {trial_end.isoformat()}(旧合同,离职解除尚未生效),跳过,等下一次运行")
logger.info("【%s】%s", base_code, result["message"])
return result
# ==================== 入口 ====================
def main(records=None, write_back=True):
"""影刀自定义指令入口「37du签署生效复核」(独立排程:新签脚本后,如 10:00)。
名单来源:钉钉 AI表格「门店服务岗转正跟进-周更新」——人资是否处理=是 且 签署跟进≠是。
执行:生效中合同起始日 > 试用期到期日期 -> 新合同已签署生效 -> 回填「签署跟进=是」;
只查到旧合同或查无 -> 跳过等下次。同时覆盖超龄人工新签的生效回填。
write_back: 是否回填「签署跟进=是」(默认 True)。
Returns:
{"success": bool, "message": str, "results": [...]}
"""
try:
session = _build_session()
records = records if records is not None else fetch_aitable_records()
targets = fetch_sign_effect_targets(records=records)
if not targets:
_set_glv("messages", ["签署生效复核:AI表格暂无待复核名单"])
return {"success": True, "message": "签署生效复核:AI表格暂无待复核名单", "results": []}
logger.info("生效复核待处理名单 %d 条,逐条执行……", len(targets))
results = []
for t in targets:
r = process_one(session, t)
results.append(r)
# 回填:仅检测到新合同已生效的行写入「签署跟进=是」
if write_back:
done_ids = [r.get("record_id") for r in results
if r["status"] == "成功" and r.get("record_id")]
if done_ids:
wok, wfail = mark_sign_follow(done_ids)
logger.info("AI表格回填「签署跟进=是」:成功 %d 失败 %d", wok, wfail)
else:
logger.info("AI表格回填「签署跟进=是」:本次无新合同已生效的行")
messages = _build_messages(results)
_set_glv("messages", messages)
ok_cnt = sum(1 for r in results if r["status"] == "成功")
return {"success": True,
"message": f"签署生效复核共 {len(results)} 条,成功 {ok_cnt} 条",
"results": results}
except LoginRequiredError as e:
return {"success": False, "message": str(e), "results": []}
except Exception as e:
return {"success": False, "message": f"签署生效复核执行异常:{e}", "results": []}
if __name__ == "__main__":
# 命令行独立运行时默认不执行(避免误触线上写操作),仅打印用法
print("本脚本为 XQ0035 签署生效复核分支(影刀指令「37du签署生效复核」,独立排程 10:00)。")
print("默认不自动执行线上写操作。请在影刀流程中调用 main() 使用:")
print(" 从钉钉 AI表格读取待复核名单(人资是否处理=是 且 签署跟进≠是),执行:")
print(" 生效中合同起始日 > 试用期到期日期 -> 新合同已签署生效 -> 回填「签署跟进=是」;")
print(" 只查到旧合同或查无 -> 跳过等下次。")
print("只读自检:python -c \"import importlib.util,sys; spec=importlib.util.spec_from_file_location('m',r'%s');"
% os.path.abspath(__file__))
print("m=importlib.util.module_from_spec(spec);sys.modules['m']=m;spec.loader.exec_module(m);")
print("print(m.fetch_sign_effect_targets())\"")
@@ -0,0 +1,76 @@
# -*- coding: utf-8 -*-
"""
@FileName: step1_transfer_release.py
@Description: XQ0035 第一步单独执行(真实写操作)——仅发起「调动解除(电子签)」
《(改签)离职电子签流程》,不做试用期变更/确认/AI表格回填。
链路:查生效中合同 -> 防重校验 -> 发起流程 -> 反查流程实例详情链接。
⚠️ 真实线上写操作:会对指定工号真实发起离职电子签流程。
用法:.venv\\Scripts\\python.exe step1_transfer_release.py [工号](默认 37036273)
"""
import importlib.util
import json
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
MODULE_PATH = os.path.join(HERE, "trial_period_change.py")
def _load_module(name, path):
spec = importlib.util.spec_from_file_location(name, path)
m = importlib.util.module_from_spec(spec)
sys.modules[name] = m
spec.loader.exec_module(m)
return m
def main():
base_code = (sys.argv[1] if len(sys.argv) > 1 else "37036273").strip()
tpc = _load_module("trial_period_change", MODULE_PATH)
session = tpc._build_session()
print(f"[1/4] 查询工号 {base_code} 的【生效中合同】……")
contract = tpc.query_active_contract(session, base_code)
if not contract or not contract.get("contract_id"):
print(f"❌ 未找到生效合同,无法发起。查询结果:{contract}")
return
print(f" 命中 contract_id={contract['contract_id']}"
f"({contract.get('staff_name')},到期 {contract.get('contract_end_date') or '未知'})")
print("[2/4] 防重校验……")
allowed, chk_msg = tpc.check_transfer_allowed(session, contract["contract_id"])
if not allowed:
print(f"❌ 防重校验拦截:{chk_msg}")
return
if chk_msg:
print(f" ⚠️ {chk_msg}(此前已发起过,本次不重复发起)")
flow = None
if chk_msg:
print("[3/4] 流程此前已发起,跳过发起动作。")
else:
print("[3/4] 发起《(改签)离职电子签流程》……")
ok, msg, flow = tpc.initiate_transfer_release(session, contract["contract_id"])
if not ok:
print(f"❌ {msg}")
return
print(f" ✅ {msg}")
if flow:
print(f" 流程实例参数:{json.dumps(flow, ensure_ascii=False)}")
print("[4/4] 反查流程待办(WeProcess)获取详情链接……")
wf = tpc.query_transfer_workflow(session, business_key=(flow or {}).get("business_key"))
if wf:
print(f" ✅ {wf['title']}(发起人={wf.get('create_user')},时间={wf.get('create_time')})")
print(f" 详情链接: {wf['url']}")
print(f" formId={wf['form_id']} businessKey={wf['business_key']} "
f"processId={wf['process_id']} taskId={wf['task_id']}")
else:
print(" ⚠️ 未反查到流程实例(需人工在 HR 系统待办中查看)")
print()
print("第一步(调动解除-电子签)执行完毕。下一步:进入详情链接「完善信息」。")
if __name__ == "__main__":
main()
@@ -0,0 +1,134 @@
# -*- coding: utf-8 -*-
"""
@FileName: test_mode_check.py
@Description: XQ0035 测试模式(只读)——校验「人资专用号」登录态与各台账查询权限。
全程仅调用查询接口,不发起流程、不改数据、不回填:
1) getCurUserInfo 确认当前登录账号身份,并与 trial_period_change.py
内硬编码操作人(CURRENT_USER_ID/CURRENT_STAFF_ID)比对
2) 试用期人员 / 合同台账-生效中合同 / 变更转正三 Tab 按工号只读查询
3) WeProcess 流程待办查询(改签离职电子签)
用法:.venv\\Scripts\\python.exe test_mode_check.py [工号1 工号2 ...]
(默认查询 37036273 本人)
"""
import importlib.util
import json
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
MODULE_PATH = os.path.join(HERE, "trial_period_change.py")
GET_CUR_USER_INFO_URL = ("https://hr.37du.co/RedseaPlatform/"
"PtUsers.mc?method=getCurUserInfo")
def _load_module(name, path):
spec = importlib.util.spec_from_file_location(name, path)
m = importlib.util.module_from_spec(spec)
sys.modules[name] = m
spec.loader.exec_module(m)
return m
def _pick_identity_fields(obj, out, depth=0):
"""递归摘取身份相关字段(name/code/id 类),便于人工核对当前账号。"""
if depth > 4 or len(out) > 20:
return
if isinstance(obj, dict):
for k, v in obj.items():
kl = str(k).lower()
if isinstance(v, str) and any(t in kl for t in ("name", "code", "id", "account")):
out.append(f"{k}={v}")
else:
_pick_identity_fields(v, out, depth + 1)
elif isinstance(obj, list):
for v in obj[:5]:
_pick_identity_fields(v, out, depth + 1)
def main():
tpc = _load_module("trial_period_change", MODULE_PATH)
session = tpc._build_session()
print("共享 cookies 文件:", tpc.SHARED_HR_COOKIE_FILE)
print()
# ---------- 1) 当前登录身份 ----------
print("=" * 60)
print("1) 当前登录身份(getCurUserInfo)")
print("=" * 60)
try:
resp = session.post(GET_CUR_USER_INFO_URL, data={}, timeout=15)
text = resp.text
if not text.lstrip().startswith(("{", "[")):
print("❌ 登录态已失效(返回非 JSON)。请先运行「37duHR登录」指令重新登录后重试。")
print("返回内容片段:", text[:200])
return
info = resp.json()
fields = []
_pick_identity_fields(info, fields)
print("身份字段:", "; ".join(fields) if fields else json.dumps(info, ensure_ascii=False)[:500])
uid_ok = tpc.CURRENT_USER_ID in text
sid_ok = tpc.CURRENT_STAFF_ID in text
print()
print(f"脚本硬编码 CURRENT_USER_ID={tpc.CURRENT_USER_ID} 在当前登录态响应中: "
f"{'✅ 命中' if uid_ok else '⚠️ 未命中'}")
print(f"脚本硬编码 CURRENT_STAFF_ID={tpc.CURRENT_STAFF_ID} 在当前登录态响应中: "
f"{'✅ 命中' if sid_ok else '⚠️ 未命中'}")
if not (uid_ok and sid_ok):
print("⚠️ 硬编码操作人与当前登录账号可能不一致:写操作(发起流程/确认)会以别人身份提交,")
print(" 正式使用前需把 trial_period_change.py 内三个 CURRENT_* 常量更新为当前账号的值。")
except Exception as e:
print(f"❌ 身份查询异常:{e}")
return
# ---------- 2) 各台账 Tab 只读查询 ----------
codes = [c for c in (sys.argv[1:] or ["37036273", "37036361"]) if c.strip()]
for code in codes:
print()
print("=" * 60)
print(f"2) 工号 {code} 只读查询")
print("=" * 60)
try:
staff = tpc.query_trial_staff(session, code)
if staff:
print(f" 试用期人员: ✅ 命中 {staff.get('hr_staff_base.staff_name', '')} "
f"(base_id={staff.get('hr_staff_base.base_id', '')})")
else:
print(" 试用期人员: 无记录(接口可查,无该工号数据)")
except Exception as e:
print(f" 试用期人员: ❌ {e}")
try:
contract = tpc.query_active_contract(session, code)
if contract:
print(f" 生效中合同: ✅ 命中 contract_id={contract['contract_id']} "
f"({contract.get('staff_name', '')},到期 {contract.get('contract_end_date') or '未知'})")
else:
print(" 生效中合同: 无记录(接口可查,无该工号数据)")
except Exception as e:
print(f" 生效中合同: ❌ {e}")
try:
stage, rec = tpc.check_processed_stage(session, code)
print(f" 变更三Tab(已生效/待确认/待生效): {stage or '均无记录'}")
except Exception as e:
print(f" 变更三Tab: ❌ {e}")
# ---------- 3) 流程待办 ----------
print()
print("=" * 60)
print("3) 流程待办查询(改签离职电子签,WeProcess)")
print("=" * 60)
try:
wf = tpc.query_transfer_workflow(session)
if wf:
print(f" ✅ 命中:{wf['title']}(发起人={wf.get('create_user')},时间={wf.get('create_time')})")
print(f" 详情链接: {wf['url']}")
else:
print(" 无记录(接口可查,暂无该类流程实例)")
except Exception as e:
print(f" ❌ {e}")
print()
print("测试模式(只读)执行完毕:以上均为查询接口,未做任何写操作。")
if __name__ == "__main__":
main()
@@ -0,0 +1,219 @@
# XQ0035 服务岗转正不通过电子签(离职+入职)— 交接文档
> 生成时间:2026-10-08 · 最近更新:2026-10-09 · 会话交接用,方便新会话直接续接。
## 1. 业务背景与目标
需求:服务岗转正不通过 → 离职再入职。
> ✅ **2026-10-09 口径已全面定稿,3 脚本拆分重构已完成**(权威口径见 `aa.md` 定稿版 + 本文 2.2 节):
> 主流程 trial_period_change.py / 新签合同分支 sign_new_contract.py / 签署生效复核分支 sign_effect_check.py,
> 建议排程 09:00 / 09:30 / 10:00。三个脚本均单文件自包含、完全解耦。
主流程(trial_period_change.py,重构后口径):
1. **分支1**:到期能否考核通过=能 → 「人资是否处理」直接回填「否」(已有 `mark_aitable_no`);
**分支2**:人员处理意见=离职后再入职;到期能否考核通过**未填写 → 先回填「不能」**再处理(新增)
2. **① 发起调动解除(电子签)**:合同台账-生效中合同 → 发起《(改签)离职电子签流程》
(**断点续跑**:回填前检测电子签是否已发起,已发起则跳过发起环节)
3. **①.5 完善信息**:补全实际离职日期 + **覆写「是否需要新签合同」= 否**(超龄/未超龄一律填否)并提交
4. **①.6 发起离职电子签**:对员工真实发起电子签署(第三方 CA);发起失败仅记异常,**变更试用期仍继续**
5. **② 变更试用期/延期转正** → **③ 待确认 + ④ 确认**
6. **回填钉钉 AI表格**:「人资是否处理=是、离职推送时间=**电子签实际发起日期**」
(回填时机移到确认完成后,新签不再阻塞回填)
独立分支(新脚本):
- **新签合同分支** `sign_new_contract.py`(09:30):选择条件=人资是否处理=是 + 离职推送时间非空 +
新合同推送日期为空 + **工号不在异常记录表(超龄过滤)** → 查离职电子签已办结 → 查无生效中合同 →
未签合同查到人 → 「新签」→ 回填「新合同推送日期=操作当天」
- **签署生效复核分支** `sign_effect_check.py`(10:00):选择条件=人资是否处理=是 且 签署跟进≠是 →
生效中合同**起始日期 > 试用期到期日期**(=新合同已生效,先签合同后进试用期/离职后才签新合同)→
回填「签署跟进=是」;同时覆盖超龄人工新签的生效回填
## 2. 代码状态(trial_period_change.py,影刀单文件自包含)
> 状态:✅ 已按 2026-10-09 新口径完成 3 脚本拆分重构(见 6.1~6.3 均已落地,py_compile 通过)。
> 下表为主脚本现状(新签合同相关行已迁往 sign_new_contract.py)。
| 环节 | 函数 | 状态 | 实测 |
|---|---|---|---|
| 发起调动解除 | `initiate_transfer_release` + 防重 `check_transfer_allowed` | ✅ 已实现(断点续跑检测 `query_transfer_workflow` 前置) | ✅ 37036273 已发起 |
| 完善信息 | `complete_transfer_info`(saveWorkform→getNextWfActivity→sendWeTask,**覆写「是否需要新签合同=否」**) | ✅ 已实现 | ✅ 已推进到离职电子签办理 |
| 发起离职电子签 | `initiate_resign_esign`(getLastContract→mscaCreateSign;失败仅记异常,变更试用期仍继续) | ✅ 已实现 | ⚠️ 实测被 CA 拒(测试员工身份证非法) |
| 新签合同 | 已迁往 sign_new_contract.py(独立分支,不再在主脚本) | ✅ 已拆出 | — |
| 变更试用期 | `change_trial_period`(getPropPageData→savePropPageData) | ✅ 已修复 | ✅ 37036273 变更+确认成功 |
| 确认 | `confirm_pending` | ✅ | ✅ |
| AI表格回填 | `mark_aitable_done`(**离职推送时间=电子签实际发起日期**,push_date_map 传入) | ✅ 已实现 | 未实测 |
| 超龄前置判定 | `query_staff_roster` + `_retire_date`/`_is_reach_retire`/`_estimate_new_contract_overage`(**不再阻断流程**) | ✅ 已实现(2026-10-09) | ✅ 花名册接口实测命中(37036273) |
| 异常记录表 | `write_abnormal_excel`(error_type/flow_error/status=失败 收录,同工号留最新) | ✅ 已实现(2026-10-09) | ✅ 本地自测通过 |
入口 `main(tasks=None, output_path=None, use_aitable=True, write_back=True)`:AI表格名单兜底(默认)或 tasks 传参。**Excel 入口已按需求移除**。
### 2.1 超龄判定链路(2026-10-09 新增,口径已与需求方确认)
判定口径:**已达龄 → 直接异常转人工(后续步骤全部跳过);未达龄但新合同越退休日 → 异常转人工(分段新签);仅未达龄且新合同也未达龄才自动化新签**。
- **前置判定**(`process_one` 步骤 0,所有环节之前):调员工花名册接口查 `sex/birthday`,`today >= 退休日`(生日当天即达龄)→ `error_type=已达法定退休年龄`,直接返回,不再发起任何流程。花名册查无此人仅告警继续(后续环节兜底)。
- **新签环节精确复核**(`sign_new_contract` 步骤 4.5):算出新合同 `end_s` 后比对退休日,`end_s >= 退休日` → `error_type=超龄需分段`,`ok=False`,后续 2/5~5/5 自然终止。人工分段新签后下次运行自动续跑(防重校验命中→未签合同无此人→「无需新签」→变更环节继续)。
- **行为变更**:`sign_new_contract` 内已达龄**不再自动签超龄用工协议**,直接报 `已达法定退休年龄` 异常(新口径);`TREATY_TYPE_OVERAGE` 常量保留(`_parse_last_contract` 识别历史超龄合同仍用)。
- **返回值变更**:`sign_new_contract` 返回四元组 `(ok, msg, signed, error_type)`;`process_one` 结果 dict 新增 `error_type` 字段(空=正常流程)。
- **异常记录表** `D:\资料\人资\试用期变更\异常记录.xlsx`(`DEFAULT_ABNORMAL_EXCEL`,env `xq0035_abnormal_excel` 可覆盖):列=员工工号/员工姓名/异常类型/异常详情/记录时间;收录口径=`error_type` 非空(超龄转人工)或 `status=失败`(提交报错),普通「跳过」不收录;累积追加、同工号去重留最新;`main()` 两个分支收尾自动写入。
- **钉钉消息**:`_build_messages` 四分类——成功/跳过/🚨超龄异常转人工(`error_type` 非空,含类型标注)/失败。
**员工花名册接口要点**(`query_staff_roster`,抓包逆向结论):
- URL:`hrRoster/1116da64-b094-11ea-b588-14187743d052/queryRealTimeData.mc`(POST),`menuName=员工花名册`、`tableId=assemble-hr_staff_base`
- **与试用期台账查询的两处必改差异**(缺则返回空数据):`struTreeCode=cq37du` + `currentRoleIds` 用花名册专用 4 角色集 `STAFF_ROSTER_ROLE_IDS`(含两个角色 UUID + POST_SYS_ADMIN + renshi)
- commonQuery 沿用 `_encode_common_query`(字段 `hr_staff_base.base_code` like),日期参数照常带
- **Nosession JSON 陷阱**:会话过期返回合法 JSON `{"state":"Nosession",...}`,绕过 `_is_expired` 的非 JSON 检测——`query_staff_roster` 内已显式检查 `state=="Nosession"` 抛 `LoginRequiredError`
- 关键字段:`hr_staff_base.sex`(1=男 2=女)、`hr_staff_base.birthday`(yyyy-MM-dd)、`staff_name/idCard/person_status`、`hr_staff_contract.contract_start_date/contract_end_date`
### 2.2 本轮口径定稿(2026-10-09,需求方逐条确认完毕,权威文档=aa.md)
已确认事项(全部写入 aa.md「已确认事项」,待需求方确认已清零):
1. **回填时机**:「人资是否处理=是」改到 离职电子签+变更试用期+确认 完成后回填;
回填前检测电子签流程是否已发起(断点续跑,应对仅试用期变更失败的情况);
「离职推送时间」取**电子签实际发起日期**(非本次操作日期)。
2. **完善信息表单**:覆写字段名为「**是否需要新签合同**」(用户直接给出,无需抓包),
超龄/未超龄**一律填"否"**——解除流程不自动带出新签,新签全部由独立分支延后办理。
注意:现有 `complete_transfer_info` 只覆写 `leaveoffice_time`(其余透传),「能提交≠能改指定字段」,需显式覆写该字段。
3. **新签分支排除超龄**:按异常记录表(`D:\资料\人资\试用期变更\异常记录.xlsx`)工号过滤,不改 AI表格结构。
4. **超龄人工新签生效后**也自动回填「签署跟进=是」(由生效复核分支覆盖)。
5. **脚本形态**:拆 3 个独立单文件自包含脚本(主流程 / 新签合同 / 生效复核),
登录/AI表格读写等公共逻辑各自内置,允许少量重复换取完全解耦。
6. AI表格已有「签署跟进」列,无需加列。
**trial_period_change.py 分区地图(约 2020 行,已全文通读,行号供改造定位)**:
| 行号 | 内容 |
|---|---|
| 1-90 | 模块 docstring(接口清单 0/0a-0e/1-4 全量文档) |
| 91-130 | imports + 依赖校验 + `load_dotenv()` + `_PrintLogger` |
| 133-314 | 常量区(rosterId、URL、AI表格配置、`AITABLE_*_FIELD` 字段常量、MAX_ATTEMPTS=3);**尚无「签署跟进」常量** |
| 317-477 | commonQuery 加密 + `_build_session`/`_request_retry`/`_get_date_params`/`_build_query_params` |
| 480-593 | `query_active_contract`(**返回不含 contract_start_date,需扩展**)、`check_transfer_allowed`、`_extract_flow_params`、`initiate_transfer_release` |
| 596-634 | `query_transfer_workflow`(WeProcess 查流程实例,返回 create_time=实际发起日期的数据源) |
| 636-820 | 完善信息四接口 + `complete_transfer_info`;**行 774-779 = 表单覆写点**(现仅 `leaveoffice_time`) |
| 823-912 | `initiate_resign_esign`(含「任务已结束则跳过」幂等模式,可复用于断点续跑检测) |
| 915-1209 | 新签合同函数群(`sign_new_contract` 等 10 个函数)→ **整体迁往 sign_new_contract.py** |
| 1212-1322 | `query_trial_staff`/`change_trial_period`/`query_pending`/`confirm_pending` |
| 1325-1374 | `check_processed_stage` + `_build_processed_msg` |
| 1377-1598 | AI表格函数群(`mark_aitable_done` 现写 today_ms + new_push_map,需改传实际发起日期) |
| 1601-1808 | `process_one`(**步骤 1.7 行 1738-1751 新签合同需移除**;步骤 0 超龄前置判定已有) |
| 1810-2020 | `_set_glv`/`_build_messages`(四分类)/`write_abnormal_excel`/`main()` |
## 3. 已确认接口清单(详见模块 docstring 0~0e)
- 0 生效中合同查询 / 0a 防重 / 0b 发起流程(startWorkFlowScheduled)
- 0c 完善信息:getBusinessDate → saveWorkform → getNextWfActivity → sendWeTask
- 0d 发起电子签:redapi msca getLastContract / mscaCreateSign(JSON)
- 0e 新签合同:未签合同 roster 查询 → getPropPageData → savePropPageData + ④单位下拉字典 ⑤单位详情联动 ⑥模板 SP(sign_way=ext_1)
- 1~4 试用期变更链路(query_trial_staff / savePropPageData / query_pending / confirm)
**关键坑(已踩过并修复):**
- 属性页提交(变更试用期、新签合同)必须**先 getPropPageData 读全量数据再整表单提交**,只传变更字段会报「数据校验缺失重要信息」
- savePropPageData 必须带 `operator_id=CURRENT_USER_ID`、`operator_name`,否则存储过程报 `USER_ID cannot be null`(错误为自定义加密,需解密:`text[:2]+text[5:]+text[2:5]` 去盐再自定义 base64 解码)
- `weStruId` 优先取 WAIT 页 `curStruid`(任务字段 `weTaskExt5` 是组织 id,多数情况不同)
- 日期字段提交前格式化为 `yyyy-MM-dd`
- **correction_type 只认数字码**(1按期/2变更试用期/3延期/4提前):传中文名服务端不识别、按延期转正(3)落库(2026-10-09 实测);Tab 列按数字码存储、页面渲染中文名;getPropPageData 响应不含该下拉字典定义(2026-10-09 已修复:process_one 归一化为数字码提交,中文名仅供展示)
- **员工花名册(queryRealTimeData)响应行在 `datas`,不是 `jsonList`**(试用期台账才是 jsonList)——读错字段=永远"未查到"(2026-10-09 修复 query_staff_roster)
- **花名册超龄判定须带 `person_status in (1,4)`**(在职+返聘):从「员工花名册-返聘」Tab 抓包 commonQuery 解密所得;不带该条件服务端默认视图会漏返聘/超龄人员。commonQuery 解密方法:逆首尾重排 `A=B[:2]+B[5:]+B[2:5]` → 去盐 `yyryrtweasdasd` → 自定义 Base64 解码(字符表 _CUSTOM_CHARS,'7'=填充)→ URI 解码 → JSON 条件
- 实例印证:吴彩红 37037403(女,1974-09-25 生,退休日 2024-09-25,**已超龄 2 年**)此前因上述两坑漏判超龄、未进异常表;修复后 `_is_reach_retire` 正确返回 True,新签环节会转人工
## 4. 测试实例 37036273 当前状态(真实 HR 系统,2026-10-09 下午更新)
- ✅ 调动解除电子签已发起、完善信息已完成(流程推进到「离职电子签办理」)
- ❌ 发起离职电子签失败:**测试员工身份证 `500154202410063708` 出生 2024 年,CA 开户校验「身份证年龄不合法」**——测试数据问题,非代码问题
- ✅ 变更试用期接口版实测通过:correction_type=2 落库「变更试用期」(13:28 记录,曾因提交中文名落成 3 的坑已修复)
- ✅ 新签合同**接口版**实测通过(生产入口 main()):劳动合同 12 个月 2026-10-01~2027-09-30、单位=大学城富力行政会馆、3 模板、推送电子签 2026-10-09——与此前浏览器手签参数完全一致;提交后员工即移出「未签合同」,esign 办结前不进「生效中合同」;AI表格「新合同推送日期」回填正常
## 5. 已知问题 / 阻塞
1. **发起离职电子签(①.6)**:`mscaCreateSign` 参数已确认(payload 正确送达 CA),但测试员工身份证非法。**正式名单需先核实身份证**;代码会把 CA 报错原样返回。
2. ~~**新签合同接口版(①.7)未实测**~~ → **✅ 2026-10-09 已实测通过**(37036273,生产入口 main() 全链路:门控→新签→回填;37037403 吴彩红被「仍有生效中合同」门控正确跳过)。原 3 个风险点已于 2026-10-08 用只读探针实测解决(结论沉淀在主脚本 docstring 0e,探针已删,产物在 .sessions/unitdict_*.json):
- `contract_type_template`:sign_way 由 ext_3 改为 **ext_1**(属性页 dataGetDesc 定义;实测 ext_1 返回与浏览器页面默认 3 模板一致,ext_3 中间模板不同)
- `ext_license_name`/`ext_seal_number` 置空问题:新增 `_unit_set_detail`(`rf_hr_contract_unit_set_select_sp_cq37du`,UNIT_SET_ID=si_area 入参 → 营业执照名称/印章编号),实测与浏览器自动带出值一致,已接入 prop
- `si_area` 下拉字典(AI表格单位来源):实测确认 `customer_contract_unit_set_query_module_conf_sp_cq37du` 与属性页 dictCode `contract_unit_set_query_module_conf` 返回完全相同(111 单位、inUse=1),**AI表格单位名→code 映射链路正确,无需改动**
- 预防性补齐 operator_id/operator_name(同「变更试用期 USER_ID cannot be null」坑)
3. ~~**离职电子签办理任务的提交(sendWeTask 推进 activity_tr_1)未实现**~~ → **⛔ 不属于本需求范围(2026-10-09 用户澄清)**:员工 CA 签署完成后,该任务的提交办结由 **XQ0020(20号需求)** 自动审核处理;XQ0035 的职责到「发起离职电子签 + 回填推送时间」为止,无需实现。
4. ~~AI表格回填(新合同推送日期)未实测~~ → **✅ 2026-10-09 已实测**(mark_new_push_date 成功 1 条)。
5. ~~**签署生效复核(sign_effect_check.py)未实测**~~ → **✅ 2026-10-09 已实测通过**(scoped main(records=…, write_back=True)):37036966 文兰英「起始日 2026-09-30 > 试用期到期 2026-09-29」命中 → 回填「签署跟进=是」成功(AI表格复核确认);37037403 吴彩红正确跳过(生效中合同 2026-09-14~2027-09-13 系旧合同——她还处离职电子签阶段,旧合同未废弃、新合同未签;注:其 AI表格行「离职推送时间 2026-09-07」早于入职时间,属错填,以合同台账为准)。同日按用户要求增加**电子签办结交叉验证**(`has_running_esign_process`:WeProcess 查 title 含「{姓名}-改签离职电子签」的运行中流程,列表仅含活动任务行,查无=已办结/未发起;台账命中但流程未办结则跳过不回填),双向实测:文兰英通过、吴彩红识别出 RUNNING 流程(离职电子签办理环节,陈莲 2026-10-07 发起)。至此本需求三个分支的自动化环节全部闭环,无遗留事项(离职电子签办理任务的提交办结属 XQ0020 范围,见第 3 项)。
## 6. 下一步待办(已全部完成 ✅ 2026-10-09)
> aa.md 定稿 + 3 脚本拆分重构已全部落地,三个文件 `.venv\Scripts\python.exe -m py_compile` 均通过、无残留引用。
### 6.1 重构主流程 trial_period_change.py ✅
1. **完善信息覆写**:`complete_transfer_info` 已加 `form_data["是否需要新签合同"] = "否"`(超龄/未超龄一律否)。
2. **断点续跑检测**:`process_one` 发起环节前先 `query_transfer_workflow(business_key=合同ID)` 反查
「改签离职电子签」实例:已发起 → 跳过发起、离职推送时间取 `create_time`;未发起 → 正常发起
(防重校验「已存在」保留兜底)。
3. **回填时机后移 + 移除即时新签**:步骤 1.7 新签已移除、`signed_new_contract` 已删;
`mark_aitable_done(record_ids, push_date_map)` 接受 `{record_id: 实际发起日期毫秒时间戳}`,移除 `new_push_map`;
电子签发起失败仅记 `flow_error` 异常,变更试用期仍继续(`stages.transfer` 调动解除失败时不置 True)。
4. **分支1/分支2 前置**(`main()` AI表格分支):分支1「能→否」保留;分支2「未填→先回填不能」(新增
`mark_aitable_cannot`);`fetch_aitable_targets` 同时排除「是/否」。
5. 常量区补充:`AITABLE_CANNOT_VALUE = "不能"`。
### 6.2 新建 sign_new_contract.py(新签合同分支,09:30)✅
- 单文件自包含:commonQuery 加密 / 登录 / AI表格 / 新签函数群 / 异常表读写全部内置;
- 选择条件:人资是否处理=是 且 离职推送时间非空 且 新合同推送日期为空,且工号不在异常记录表
(`read_abnormal_codes` 仅过滤超龄类型:已达法定退休年龄/超龄需分段);
- 执行链:查【生效中合同】(仍有 → 跳过)→ 查【未签合同】(查无 → 跳过,不当"无需处理"漏掉)→
查离职电子签流程办结(`is_flow_completed`,流程反查不到视为可继续,由前两步合同状态兜底)→ `sign_new_contract` →
回填「新合同推送日期=操作当天」;
- 签署前复核保留:终止日 ≥ 退休日 → 记异常表转人工,不签。
### 6.3 新建 sign_effect_check.py(签署生效复核分支,10:00)✅
- 单文件自包含:登录/AI表格公共逻辑内置;
- `query_active_contracts` 返回全部匹配行(含 `contract_start_date`);
- 选择条件:人资是否处理=是 且 **签署跟进≠是**;常量 `AITABLE_SIGN_FOLLOW_FIELD="签署跟进"`;
- 执行链:生效中合同按工号查询 → 起始日期 > 试用期到期日期(AI表格台账字段)判新合同已生效 →
**电子签办结交叉验证**(WeProcess 查无该员工运行中的「改签离职电子签」流程才放行)→
回填「签署跟进=是」;只查到旧合同或查无 → 跳过等下次。
### 6.4 收尾 ✅
- 三个文件各跑 `.venv\Scripts\python.exe -m py_compile` → 通过;`GetDiagnostics` 无告警;
- 影刀端需注册 2 个新自定义指令「37du新签合同」「37du签署生效复核」,排程 09:00 / 09:30 / 10:00;
- 实测策略沿用:先只读探针/小名单验证,真实写操作前核对员工与参数。
(`probe_new_contract_unit_dict.py` 引用已改为从 `sign_new_contract.py` 加载,因常量已迁出主脚本。)
### 6.5 遗留(2026-10-09 复核后清零)
1. **发起离职电子签(①.6)——⚠️ 半验证(2026-10-09)**:提交链路已通过(参数组装→HR 受理→回填推送时间→CA 拒签后异常兜底落表并继续,37036273 实测);但 **CA 成功受理→生成待签任务→员工可签的完整路径未验证过**(测试号身份证 2024 年生不合法被 CA 拒;接口发起的成功案例为 0,吴彩红那条 RUNNING 流程系人工发起不算数)。收口需一个身份证合法的员工进名单跑一次,或 HR 把测试号身份证改为合法值。
2. ~~新签合同接口版未实测~~ → ✅ 2026-10-09 37036273 生产入口全链路实测通过(见第 5 节第 2 项)。
3. ~~AI表格回填未实测~~ → ✅ 离职推送时间 / 新合同推送日期 / 签署跟进 均已实测(见第 5 节)。
4. ~~「离职电子签办理」任务的推进(sendWeTask,defActivityId=activity_tr_1)~~ → ⛔ **不属本需求范围**(2026-10-09 用户澄清):员工 CA 签署完成后由 **XQ0020** 自动审核提交办结;XQ0035 职责到「发起电子签+回填推送时间」为止。
注(仍有效):`is_flow_completed` 对「流程反查不到」的记录不阻断(由生效中合同+未签合同两个合同状态兜底),避免因流程未办结永久漏签。
## 7. 目录脚本清单(2026-10-08 已清理:27 个一次性逆向探针已删除,结论沉淀在主脚本 docstring 0~0e 与 .sessions 产物)
- `trial_period_change.py` — 主流程脚本(09:00,影刀指令「37du试用期变更」)
- `sign_new_contract.py` — **新签合同分支**(09:30,影刀指令「37du新签合同」,单文件自包含)
- `sign_effect_check.py` — **签署生效复核分支**(10:00,影刀指令「37du签署生效复核」,单文件自包含)
- `step1_transfer_release.py` — 真实写:单独发起「调动解除(电子签)」
- `run_change_confirm.py` — 真实写:单独执行变更试用期+确认
- `run_sign_new_contract.py` — 真实写:按工号直接驱动新签分支 process_one(不含 AI表格回填)
- `test_mode_check.py` — 只读自检(登录态/台账权限,真实写前先跑)
- `probe_new_contract_survey.py` — 只读预检:AI表格待新签名单 + 逐条门控状态(生效中合同/未签合同/电子签办结),新签真实写前跑
- `.sessions` 分析产物(`%LOCALAPPDATA%\37duAutomation\.sessions`):各环节抓包 HTML/JSON/请求体(含 unitdict_* 字典验证、prop_fields_新签合同 属性页字段定义)
> 2026-10-09 收尾清理:一次性探针(probe_check_all_37036273 / probe_check_trial_state / probe_correction_type / probe_new_contract_unit_dict 等)已删除,结论沉淀在主脚本 docstring、第 3 节关键坑与项目记忆。
## 8. 环境与运行
- 本地 `.venv`(requests/pandas/openpyxl/DrissionPage 已装)
- **配置直接内置在脚本常量区(影刀环境不读取 .env,2026-10-09 起 XQ0035 不再依赖根 .env)**:
AI表格(appkey/appsecret/baseId/tableId/操作人 unionId)、变更类型 `FIXED_CORRECTION_TYPE="2"`(变更试用期,
aa.md 口径;**提交只认数字码,勿传中文名**,见第 3 节关键坑)、`FIXED_NEW_PERIOD_MONTHS="1"`、`DEFER_MONTHS=1`、
结果/异常表路径 `DEFAULT_OUTPUT_EXCEL`/`DEFAULT_ABNORMAL_EXCEL`;根 .env 的 xq0035 块已删除
- 登录态:共享 `hr_cookies.json`(`%LOCALAPPDATA%\37duAutomation\.sessions\hr_cookies.json`),由「37duHR登录」指令写入;
本地可跑 `workflows/share/hr_login_api.py`(接口版,含滑块)刷新
- 操作人固定参数:`CURRENT_USER_ID=178b0efa-8a65-11f1-a7d9-000c296f9469`、`CURRENT_USER_NAME=人资专用号`、`CURRENT_STAFF_ID=1342173e-...`
- 结果输出:`D:\资料\人资\试用期变更\处理结果.xlsx`;异常记录:`D:\资料\人资\试用期变更\异常记录.xlsx`
- 语法检查:`.venv\Scripts\python.exe -m py_compile trial_period_change.py`
- ⚠️ 全为线上真实写操作,跑前务必核对员工与参数