Compare commits
4
Commits
1664821117
...
2d2cf506fe
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2d2cf506fe | ||
|
|
229e3e6878 | ||
|
|
46749aa711 | ||
|
|
a4697b368a |
@@ -44,3 +44,12 @@ AI 智能体开发约束 & 项目执行规范
|
||||
- **插件发布必须走「测试通道 → 人工验证 → 转正」**(2026-10-31 起):`publish` 默认进测试通道(`plugins.status=testing` + `plugins.test_version`),**只有管理员账号**能同步到在测版本,其他账号继续用 `latest_version`;人工验证通过后由**人**执行 `plugin-status <id> --status published` 转正(服务端把 test_version 提升为 latest_version,复用同一版本号、不重新打包),全量已授权账号下次同步生效。⚠️ **agent 不得自行执行转正**,也不得默认使用 `publish --prod` 直发正式(仅紧急热修且经人确认时使用)。测试版本号必须高于当前正式版(执行机只升不降)。
|
||||
- 鉴权:密码登录 `--admin puddy --password 123456`,**一律显式加 `--base http://172.30.30.243:8800`(内网生产控制面,执行机实际连接源)**,或中心机本机密钥自签。⚠️ 控制面只有内网这一套(执行机唯一连接源),不存在第二套库;端口分工(**控制面与文件服务器同机部署在内网 `172.30.30.243`**):8800 控制面(controlplane-next)/ 8090 控制台前端(nginx 反代 /api)/ 8802 文件服务器下载(`desktop/fileserver/`,现役目录 `/opt/37du/fileserver`)/ 8899 文件服务器管理台。
|
||||
- 完整流程、命令示例见 docs/插件/发版规范.md、docs/桌面端/桌面端发版SOP.md;中心机部署见 docs/部署/服务端前后端部署SOP.md 或技能 `.skills/37du-Center-Deploy/SKILL.md`(SSH、编译、重启、验证)。
|
||||
|
||||
6. 误删防护(命令守卫 / 硬规则)
|
||||
- **禁止用 shell 做删除/还原/迁移工程的操作**:`Remove-Item`、`del`、`erase`、`rd`/`rmdir`、`rm`、`Move-Item`、`git clean`、`git reset --hard`、`git restore .`、`git checkout -- .`、`git stash drop/clear`、`robocopy /MIR` 等一律不许出现在 PowerShell/CMD 命令里。删除文件只用 `delete_file` 工具(单文件、带路径校验与用户审批);丢弃改动优先 `git stash`,不要 `reset --hard`。
|
||||
- 清理构建产物、临时目录交给现成脚本(打包/清理脚本),不要手写递归删除命令。
|
||||
- 兜底机制(用户级 CodeBuddy 钩子,对所有项目生效):`%USERPROFILE%\.codebuddy\hooks\cmd_guard.py`,注册在 `%USERPROFILE%\.codebuddy\settings.json` 的 `hooks.PreToolUse`(matcher `.*`,只检查 shell 类工具的 command 字段,写文件内容不参与判定)。
|
||||
- **硬拦截(不可绕过)**:删除/移动目标命中「项目根、当前 cwd、其祖先目录、盘符根(`C:\`)、`/MIR` 镜像、格式化/diskpart/cipher 擦盘」,以及 `delete_file` 指向工程本体;命中即 exit 2 阻断。
|
||||
- **软拦截**:其余删除类命令同样阻断(exit 2),确属人工确认过的清理才可在命令里加注释标记 `# 37du-guard-allow` 放行。
|
||||
- 命中记录在 `%USERPROFILE%\.codebuddy\hooks\cmd_guard.log`;守卫自身异常一律放行(exit 0),不会卡死工作流。
|
||||
- 校验改动是否生效:`python "%USERPROFILE%\.codebuddy\hooks\cmd_guard.py" --selftest <用例.json>`(用例为每行一个 `{"name","command","expect"}` JSON)。
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "37du-electron-shell",
|
||||
"version": "1.0.3",
|
||||
"version": "1.10.8",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "37du-electron-shell",
|
||||
"version": "1.0.3",
|
||||
"version": "1.10.8",
|
||||
"dependencies": {
|
||||
"adm-zip": "^0.5.18",
|
||||
"better-sqlite3": "12.4.1",
|
||||
|
||||
@@ -77,6 +77,13 @@ PASSWORD = os.getenv('oa_login_password', '')
|
||||
# OA 会话校验接口:cookies 有效时返回 JSON,失效时被重定向到登录页返回 HTML
|
||||
TODO_COUNT_URL = "https://oa.37du.co/sys/notify/sys_notify_todo/sysNotifyTodo.do"
|
||||
|
||||
# OA(蓝凌 EKP)会对缺 XHR 标记的接口请求直接返回 468(2026-11 起实测):
|
||||
# 不带 X-Requested-With / Referer 的 sysNotifyTodo.do 一律 468,带任一即正常返回 JSON。
|
||||
VALIDATE_HEADERS = {
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
"Referer": "https://oa.37du.co/sys/portal/page.jsp",
|
||||
}
|
||||
|
||||
USERNAME_INPUT = 'tag:input@name=j_username'
|
||||
PASSWORD_INPUT = 'tag:input@name=j_password'
|
||||
LOGIN_BTN = '.lui_login_button_div_c'
|
||||
@@ -141,7 +148,8 @@ def _is_oa_session_valid():
|
||||
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)
|
||||
resp = session.get(validate_url, params={"method": "sumTodoCount"},
|
||||
headers=VALIDATE_HEADERS, timeout=15)
|
||||
if resp.status_code != 200:
|
||||
print(f"API 校验 cookies 状态码异常:{resp.status_code}")
|
||||
return False
|
||||
|
||||
@@ -26,6 +26,8 @@
|
||||
成功 302 跳转(实测跳 "/",浏览器端再由前端跳 /sys/portal/page.jsp);
|
||||
5. GET sysNotifyTodo.do?method=sumTodoCount 校验会话有效后,cookies 落盘 oa_cookies.json
|
||||
(返回 JSON 视为有效,被重定向回登录页返回 HTML 即失效)。
|
||||
⚠ 2026-11 起该接口对缺 XHR 标记的请求返回 468,校验请求必须带
|
||||
X-Requested-With: XMLHttpRequest(或 Referer),否则登录成功也会被误判为失败。
|
||||
|
||||
配置(与 oa_login.py 一致,读共享 .env:%LOCALAPPDATA%\\37duAutomation\\.env):
|
||||
oa_login_username=用户名
|
||||
@@ -86,6 +88,16 @@ 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"
|
||||
|
||||
# OA(蓝凌 EKP)会对缺 XHR 标记的接口请求直接返回 468(2026-11 起实测):
|
||||
# 不带 X-Requested-With / Referer 的 sysNotifyTodo.do 一律 468,带任一即正常返回 JSON。
|
||||
VALIDATE_HEADERS = {
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
"Referer": BASE_URL + "/sys/portal/page.jsp",
|
||||
}
|
||||
# OA 网关偶发 468(风控瞬时拦截,前端 JS 未定义该状态码、非会话失效信号,数秒后自愈):
|
||||
# 退避重试一次到两次,避免把「登录其实成功」误判成失败。
|
||||
VALIDATE_RETRY_DELAYS = (0.8, 2.0)
|
||||
|
||||
USERNAME = os.getenv('oa_login_username', '')
|
||||
PASSWORD = os.getenv('oa_login_password', '')
|
||||
|
||||
@@ -157,6 +169,20 @@ def _is_todo_count_json(resp):
|
||||
return False
|
||||
|
||||
|
||||
def _get_validate(session, validate_url):
|
||||
"""请求会话校验接口;遇 468(风控瞬时拦截)按 VALIDATE_RETRY_DELAYS 退避重试。
|
||||
返回最后一次响应,判定逻辑仍由调用方 _is_todo_count_json 统一处理。"""
|
||||
resp = None
|
||||
for delay in (0,) + VALIDATE_RETRY_DELAYS:
|
||||
if delay:
|
||||
time.sleep(delay)
|
||||
resp = session.get(validate_url, params={"method": "sumTodoCount"},
|
||||
headers=VALIDATE_HEADERS, timeout=15)
|
||||
if resp.status_code != 468:
|
||||
break
|
||||
return resp
|
||||
|
||||
|
||||
def _is_oa_session_valid():
|
||||
"""API 轻量校验 OA cookies:请求 oa_validate_url(默认 sumTodoCount 待办统计接口),
|
||||
返回 JSON 视为 cookies 有效;被重定向到登录页返回 HTML 即视为失效。
|
||||
@@ -171,10 +197,11 @@ def _is_oa_session_valid():
|
||||
"User-Agent": UA,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
session.headers.update(VALIDATE_HEADERS)
|
||||
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)
|
||||
resp = _get_validate(session, validate_url)
|
||||
if resp.status_code != 200:
|
||||
print(f"API 校验 cookies 状态码异常:{resp.status_code}")
|
||||
return False
|
||||
@@ -188,7 +215,7 @@ 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)
|
||||
resp = _get_validate(session, validate_url)
|
||||
return _is_todo_count_json(resp)
|
||||
except Exception as e:
|
||||
print(f"会话校验异常:{e}")
|
||||
|
||||
@@ -21,7 +21,8 @@ param(
|
||||
[string]$EnvVersion = "1.0.0",
|
||||
[switch]$FromVenv, # 从本地 .venv 全量打包(推荐,不联网)
|
||||
[switch]$SkipLocal, # do NOT install into electron-shell/python-env/
|
||||
[switch]$Force # re-download embeddable / get-pip
|
||||
[switch]$Force, # re-download embeddable / get-pip
|
||||
[switch]$ShowDeps # 只解析并打印依赖清单后退出(校验 requirements.txt 用,不打包)
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
@@ -39,27 +40,85 @@ $EmbedZip = Join-Path $DownloadDir "python-$PythonVersion-embed-amd64.zip"
|
||||
$GetPip = Join-Path $DownloadDir "get-pip.py"
|
||||
$PipIndex = $null # e.g. "https://pypi.tuna.tsinghua.edu.cn/simple"
|
||||
|
||||
# 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", "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",
|
||||
"DrissionPage==4.1.1.4", "DrissionGet==1.2.1", "DrissionRecord==2.0.1",
|
||||
"lxml==6.1.1", "psutil==7.2.2", "tldextract==5.3.2", "cssselect==1.5.0", "click==8.4.2",
|
||||
"ddddocr==1.6.1", "onnxruntime==1.28.0", "Pillow==12.3.0",
|
||||
"opencv-python-headless==5.0.0.93", "flatbuffers==25.12.19", "protobuf==7.35.1",
|
||||
# ================== 依赖清单:版本唯一真源 = 仓库根 requirements.txt ==================
|
||||
# 历史坑:这里曾硬编码一份 pin 列表(第三份清单),与 requirements.txt 长期漂移
|
||||
# (numpy/pandas/onnxruntime 等都落后多个小版本),而 .venv 装的是 requirements 的版本,
|
||||
# 导致「-FromVenv 打包」与「embeddable+pip 打包」产物不一致。
|
||||
# 现在只维护「环境包需要哪些包」的白名单,版本一律从 requirements.txt 解析。
|
||||
$ReqFile = Join-Path $Repo "requirements.txt"
|
||||
if (-not (Test-Path $ReqFile)) { throw "缺少依赖清单:$ReqFile" }
|
||||
$ReqVersion = @{}
|
||||
foreach ($line in Get-Content -Path $ReqFile) {
|
||||
if ($line -match '^\s*([A-Za-z0-9][A-Za-z0-9_.\-]*)\s*==\s*([^\s;#]+)') {
|
||||
$ReqVersion[$matches[1].ToLower().Replace('_', '-').Replace('.', '-')] = $matches[2]
|
||||
}
|
||||
}
|
||||
|
||||
# 环境包白名单(只写包名,版本取自 requirements.txt)
|
||||
$EnvPackages = @(
|
||||
"requests", "python-dotenv", "cryptography", "pycryptodome",
|
||||
"pandas", "numpy", "openpyxl",
|
||||
"python-dateutil", "tzdata", "et-xmlfile",
|
||||
"websocket-client",
|
||||
"DrissionPage", "DrissionGet", "DrissionRecord",
|
||||
"lxml", "psutil", "tldextract", "cssselect", "click",
|
||||
"ddddocr", "onnxruntime", "Pillow",
|
||||
"opencv-python-headless", "flatbuffers", "protobuf",
|
||||
# OCR(XQ0003 请假附件:病假/结婚证/产检关键词与登记日期核验)
|
||||
# rapidocr>=3 必须显式固定,连同 opencv_python/omegaconf 等运行依赖,否则
|
||||
# 走 embeddable+pip 模式时该栈不会装、插件 OCR 全面降级为人工复核。
|
||||
"rapidocr==3.9.2", "opencv-python==5.0.0.93",
|
||||
"omegaconf==2.3.1", "antlr4-python3-runtime==4.9.3", "colorlog==6.12.0",
|
||||
"pyclipper==1.4.0", "Shapely==2.1.2", "PyYAML==6.0.3", "tqdm==4.70.1",
|
||||
"pywin32==312",
|
||||
"urllib3==2.7.0", "certifi==2026.7.22", "idna==3.18",
|
||||
"charset-normalizer==3.4.9", "six==1.17.0", "packaging==26.3"
|
||||
"rapidocr", "opencv-python",
|
||||
"omegaconf", "antlr4-python3-runtime", "colorlog",
|
||||
"pyclipper", "Shapely", "PyYAML", "tqdm",
|
||||
"pywin32",
|
||||
"urllib3", "certifi", "idna",
|
||||
"charset-normalizer", "six", "packaging"
|
||||
)
|
||||
|
||||
$Pinned = @()
|
||||
foreach ($p in $EnvPackages) {
|
||||
$k = $p.ToLower().Replace('_', '-').Replace('.', '-')
|
||||
if (-not $ReqVersion.ContainsKey($k)) { throw "requirements.txt 缺少环境包依赖:$p" }
|
||||
$Pinned += "$p==$($ReqVersion[$k])"
|
||||
}
|
||||
Write-Host "依赖来源:requirements.txt(白名单 $($Pinned.Count) 个包)" -ForegroundColor DarkGray
|
||||
# 版本守卫:本地 .venv 必须与 requirements.txt 一致(唯一真源),否则打出来的包会跟随
|
||||
# 一个「没被记录」的版本。返回对象(用对象而非数组:PowerShell 里返回空数组会被展开成 $null):
|
||||
# Found = $false 表示 .venv 不存在;否则 Drift 为漂移项数组。
|
||||
function Get-VenvDrift([string]$VenvPath) {
|
||||
$VenvPy = Join-Path $VenvPath "Scripts\python.exe"
|
||||
if (-not (Test-Path $VenvPy)) { return [pscustomobject]@{ Found = $false; Drift = @() } }
|
||||
$Frozen = @{}
|
||||
& $VenvPy -m pip freeze 2>$null | ForEach-Object {
|
||||
if ($_ -match '^([A-Za-z0-9][A-Za-z0-9_.\-]*)\s*==\s*([^\s]+)') {
|
||||
$Frozen[$matches[1].ToLower().Replace('_', '-').Replace('.', '-')] = $matches[2]
|
||||
}
|
||||
}
|
||||
$drift = @()
|
||||
foreach ($p in $EnvPackages) {
|
||||
$k = $p.ToLower().Replace('_', '-').Replace('.', '-')
|
||||
$want = $ReqVersion[$k]
|
||||
$have = $Frozen[$k]
|
||||
if ($have -ne $want) { $drift += "$p .venv=$have / requirements.txt=$want" }
|
||||
}
|
||||
return [pscustomobject]@{ Found = $true; Drift = $drift }
|
||||
}
|
||||
|
||||
if ($ShowDeps) {
|
||||
$Pinned | ForEach-Object { Write-Host " $_" }
|
||||
$guard = Get-VenvDrift (Join-Path $Repo ".venv")
|
||||
if (-not $guard.Found) {
|
||||
Write-Host " (.venv 不存在,跳过版本一致性校验)" -ForegroundColor DarkGray
|
||||
} elseif ($guard.Drift.Count -eq 0) {
|
||||
Write-Host " 版本守卫通过:.venv 与 requirements.txt 一致($($EnvPackages.Count) 个包)" -ForegroundColor Green
|
||||
} else {
|
||||
Write-Host " [!] 本地 .venv 与 requirements.txt 不一致:" -ForegroundColor Yellow
|
||||
$guard.Drift | ForEach-Object { Write-Host " $_" -ForegroundColor Yellow }
|
||||
}
|
||||
Write-Host "(-ShowDeps:仅解析依赖,不执行打包)" -ForegroundColor Cyan
|
||||
return
|
||||
}
|
||||
|
||||
function Download-File([string]$Url, [string]$Dest) {
|
||||
if (-not $Force -and (Test-Path $Dest) -and (Get-Item $Dest).Length -gt 0) {
|
||||
Write-Host " cache hit: $Dest"
|
||||
@@ -92,6 +151,16 @@ if ($FromVenv) {
|
||||
-not (Test-Path (Join-Path $Venv "Lib\site-packages"))) {
|
||||
throw "venv 打包所需目录缺失:基础解释器($BasePy) 或 .venv\Lib\site-packages"
|
||||
}
|
||||
# 版本守卫:本地 .venv 必须与 requirements.txt 一致(唯一真源),否则打出来的包会跟随
|
||||
# 一个「没被记录」的版本。不一致时先 pip install -r requirements.txt 对齐再打包。
|
||||
$guard = Get-VenvDrift $Venv
|
||||
if (-not $guard.Found) {
|
||||
Write-Host " 未发现 .venv,跳过版本一致性校验" -ForegroundColor DarkGray
|
||||
} elseif ($guard.Drift.Count -gt 0) {
|
||||
throw ("本地 .venv 与 requirements.txt 版本不一致,请先 pip install -r requirements.txt 对齐:`n " + ($guard.Drift -join "`n "))
|
||||
} else {
|
||||
Write-Host " 版本守卫通过:.venv 与 requirements.txt 一致($($EnvPackages.Count) 个包)"
|
||||
}
|
||||
Write-Host "base interpreter: $BasePy"
|
||||
# 解释器 + 运行时 DLL + 标准库 + 扩展模块目录(DLLs/)
|
||||
foreach ($f in @("python.exe", "python311.dll", "python3.dll",
|
||||
|
||||
+13
-2
@@ -83,10 +83,21 @@ curl -s -H "X-API-Token: <CONTROLPLANE_TOKEN>" http://172.30.30.243:8800/api/she
|
||||
|
||||
```powershell
|
||||
cd d:\work\code\37duAutomation\desktop\electron-shell
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File scripts\build-python-env.ps1 -EnvVersion 1.1.4
|
||||
# 产物:dist-env\python-env-1.1.4.zip + .sha256,并本地安装到 python-env\1.1.4\ 供联调
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File scripts\build-python-env.ps1 -EnvVersion 1.1.9 -FromVenv
|
||||
# 产物:dist-env\python-env-1.1.9.zip + .sha256,并本地安装到 python-env\1.1.9\ 供联调
|
||||
# 只看依赖解析结果(不打包):加 -ShowDeps,会打印 41 个包版本 + .venv 一致性校验结果
|
||||
```
|
||||
|
||||
**依赖版本唯一真源 = 仓库根 `requirements.txt`**(2026-11-09 收敛):
|
||||
|
||||
* 脚本里只维护「环境包需要哪些包」的白名单(`$EnvPackages`,仅包名),版本一律从 `requirements.txt` 解析,不再硬编码第三份清单;
|
||||
* `-FromVenv` 打包前有**版本守卫**:`.venv` 里白名单包的版本与 `requirements.txt` 不一致会直接报错,提示先 `pip install -r requirements.txt` 对齐;
|
||||
* 因此流程固定为:改依赖 → 改 `requirements.txt` → 本地 `pip install` → 打包;
|
||||
* `.venv` 的 site-packages 是**全量**拷进环境包的,`.venv` 里装了什么包,环境包里就有什么,多余的历史依赖(如 1.1.7 里的 selenium/trio/screenvision 那一整棵树)会在重打包时自动消失。
|
||||
|
||||
⚠ 历史坑(勿回退):`-FromVenv` 与「embeddable + pip」两种模式产物必须一致;1.1.7 之前硬编码清单落后多个小版本(numpy 2.3.5/pandas 3.0.5/onnxruntime 1.28.0),与 `.venv` 分裂。
|
||||
⚠ 若只想在上一版基础上打补丁(改 webhost 某个 `.py`),不要用 `-FromVenv` 重打全量包(会丢包/换版本),应解出上一版 zip、只替换目标文件后重新压缩。
|
||||
|
||||
```powershell
|
||||
d:\work\code\37duAutomation\.venv\Scripts\python.exe tools\agent_cli.py `
|
||||
--admin puddy --password 123456 --base http://172.30.30.243:8800 `
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# 续签电子签 开发文档
|
||||
|
||||
> 状态:定稿(基于 `plugins/XQ0001-0100/XQ0034 续签电子签/` 与 `workflows/XQ0001-0100/XQ0034 续签电子签/` 实际代码,当前版本 v1.0.27)
|
||||
> 状态:定稿(基于 `plugins/XQ0001-0100/XQ0034 续签电子签/` 与 `workflows/XQ0001-0100/XQ0034 续签电子签/` 实际代码,当前版本 v1.0.28)
|
||||
> 所属需求单:XQ0034 续签电子签(插件 `xq0034`;影刀自定义指令「XQ0034续签电子签」)
|
||||
> 形态:执行机插件(宿主 electron-shell,Vue3 界面 + HR 会话由壳子注入 + 钉钉群通知)+ 影刀单文件脚本(双形态并存)
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
```
|
||||
plugins/XQ0001-0100/XQ0034 续签电子签/
|
||||
├── plugin.json # 插件清单:id=xq0034、version=1.0.27、platform=hr、uses_month=false、ui=true、
|
||||
├── plugin.json # 插件清单:id=xq0034、version=1.0.28、platform=hr、uses_month=false、ui=true、
|
||||
│ # capabilities=["xq0034"]、permissions.platforms=["hr"]、
|
||||
│ # fields 参数契约:dry_run / notify_dingtalk / dingtalk_env(required=[];未声明 runTimeoutSeconds)
|
||||
├── __init__.py # Xq0034Plugin:钩子注入(set_log/set_session_factory)、print 改道 _LogWriter、
|
||||
@@ -78,6 +78,8 @@ base=`YndMj49yWjPmvXXDFb1OBGAoJ3pmz5aA`、table=`agznnlF`、operator 固定人
|
||||
9. **钉钉 notable 写约定**:singleSelect 写选项名字符串(非 id)、date 写当天 0 点毫秒时间戳、回写按 20 条分批,分页读 `nextToken` 需与 `hasMore` 配合。
|
||||
10. **AI 表字段改名会整批 404**:2026-11-04 发现人资已把「完成签署」改名为「完成签署/系统处理」(singleSelect 是/否),写旧名直接 `fail to find field`、整批回写失败、完成签署永远回填不上;代码常量 `F_DONE` 已同步新名,并以执行前置字段契约校验(`FIELD_SPECS`)兜底,字段名/类型/选项不符时整体不处理。
|
||||
11. **用工类型字典与延迟落库**:HR 用工类型走 `COMMON.IDENTITY` 28 项名↔code(如 1=全日制用工、2=事务代理、6=退休返聘人员、ext_20=非全日制用工、ext_24=兼职人员、gov_identity_03=劳务派遣人员);`identity` 与联系方式同在员工基本信息 `saveTableData` 保存(`compeletCount=52`),保存后花名册延迟变更,需复查 5 次×3 秒。
|
||||
12. **签订方式 `sign_way` 决定台账显示「新签/续签」**(2026-11-09 实测收口):合同行 `hr_staff_contract.sign_way` = `1` 新签 / `2` 续签 / `3` 改签;该值原样带到【电子签署记录台账】(`tableId=cq37du-hr_staff_contract_signature`,roster `837bb1b8-6937-11f1-a965-822ff8ed5b28`)的 `sign_type`(`ext_1/ext_2/ext_3`)与 `sign_way`,台账即按此显示新签/续签/改签。抽样验证(2026-11-09):待生效 200 行中 158 行 `sign_way=2`(正常续签)、19 行 `=1`(新入职首签,工号 370383xx)、23 行 `=3`(改签)。⇒ 续签提交体的 `new_sign_way` **必须固定 `"2"`**(`RENEW_SIGN_WAY`),**不能复制原合同值**:原合同为首次新签(1)时,新合同会被记成新签,签署记录变 `sign_type=ext_1`(37020458 李阳 2026-11-09 复现,原合同 `sign_way=1` → 新合同 `sign_way=1`)。另注:`hr_staff_contract.contract_count`(合同签订次数)在台账/待生效 Tab 恒为空,不能作为判据。
|
||||
13. **AI 表「合同签署单位」常填营业执照全称**:HR 单位下拉(`customer_contract_unit_set_query_module_conf_sp_cq37du`,116 条)只有简称(如「三十七度公司」),与 AI 表「重庆三十七度健康管理(集团)有限公司」永远匹配不上。此时以原合同行 `hr_contract_unit_set.ext_license_name` 归一比对(NFKC 折叠全半角)判断是否同一家:一致 → INFO 沿用原单位;不一致 → 保留 WARNING 待人工核对(真正换单位时不能静默沿用)。
|
||||
|
||||
## 四、核心实现要点
|
||||
|
||||
@@ -133,7 +135,7 @@ base=`YndMj49yWjPmvXXDFb1OBGAoJ3pmz5aA`、table=`agznnlF`、operator 固定人
|
||||
|
||||
| 配置 | 值 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `plugin.json` id / version | `xq0034` / `1.0.27` | 与 `Xq0034Plugin` 类属性一致 |
|
||||
| `plugin.json` id / version | `xq0034` / `1.0.28` | 与 `Xq0034Plugin` 类属性一致 |
|
||||
| fields | `dry_run=false`、`notify_dingtalk=true`、`dingtalk_env=prod`(enum prod/dev) | `required=[]`;未声明 `runTimeoutSeconds` |
|
||||
| `config.DINGTALK_ENV` | `prod` | `dingtalk_env` 非法值回退 |
|
||||
| `AITABLE_BASE_ID` / `AITABLE_TABLE_ID` | `YndMj49yWjPmvXXDFb1OBGAoJ3pmz5aA` / `agznnlF` | 钉钉 AI 表 |
|
||||
@@ -179,7 +181,7 @@ npm run build
|
||||
# 打包(仓库根执行)
|
||||
.venv\Scripts\python.exe "plugins\XQ0001-0100\XQ0034 续签电子签\_pack.py"
|
||||
# 发布(desktop/ 下执行,详见 docs/插件/发版规范.md)
|
||||
.venv\Scripts\python.exe tools\agent_cli.py publish dist-plugin\xq0034_v1.0.27.zip --id xq0034 --version 1.0.27 --admin puddy --password 123456 --base http://172.30.30.243:8800
|
||||
.venv\Scripts\python.exe tools\agent_cli.py publish dist-plugin\xq0034_v1.0.28.zip --id xq0034 --version 1.0.28 --admin puddy --password 123456 --base http://172.30.30.243:8800
|
||||
```
|
||||
|
||||
产物:`dist-plugin/xq0034_v<版本>.zip`(排除 `ui-src`、`__pycache__`、`debug`、`.sessions`、`_pack.py`、`*.pyc`;包根为 plugin.json / 各 .py / requirements.txt / ui)。依赖:`requests`。执行机按账号权限自动同步插件(plugin_sync.py),无需随底座发布。
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# 续签电子签 流程文档
|
||||
|
||||
> 状态:定稿(基于 `plugins/XQ0001-0100/XQ0034 续签电子签/` 与 `workflows/XQ0001-0100/XQ0034 续签电子签/step1_renewal_esign.py` 实际代码)
|
||||
> 所属需求单:XQ0034 续签电子签(插件 `xq0034` v1.0.27;影刀自定义指令「XQ0034续签电子签」)
|
||||
> 所属需求单:XQ0034 续签电子签(插件 `xq0034` v1.0.28;影刀自定义指令「XQ0034续签电子签」)
|
||||
> 入口:插件 `Xq0034Plugin.run(fields, ctx)`(`__init__.py`)→ `data/renewal_esign.main(dry_run)`;影刀 `step1_renewal_esign.main(dry_run=None)`;公共设施在 `data/xq_common.py`,通知在 `data/dingtalk_robot.py`
|
||||
|
||||
## 一、总览
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
插件版 `plugins/XQ0001-0100/XQ0034 续签电子签/`
|
||||
|
||||
- `__init__.py`(`Xq0034Plugin.run`):钩子注入、print 改道、进度 5→95→100、钉钉通知调度、结果汇总
|
||||
- `plugin.json`:id=xq0034、v1.0.27、fields 参数契约(dry_run / notify_dingtalk / dingtalk_env)
|
||||
- `plugin.json`:id=xq0034、v1.0.28、fields 参数契约(dry_run / notify_dingtalk / dingtalk_env)
|
||||
- `config/__init__.py`:全局钩子(set_log / set_session_factory / get_session)、DINGTALK_ENV
|
||||
- `data/xq_common.py`:HR 会话与重试/失效识别、commonQuery 加密、生效中合同/花名册查询、单位下拉、钉钉 AI 表 token 与请求、日期工具
|
||||
- `data/renewal_esign.py`:执行前置字段契约校验(validate_sheet_fields)/ ④ 用工类型同步(sync_employee_type、_fix_hr_identity)/ ①否回填 / ②续签执行链(手机号闸门、防重、闸门、模板防呆、属性页提交、复查)/ ③核验、AI 表读写、messages 组装
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
- 需求方:杨芸
|
||||
- 形态:双形态并存
|
||||
- **插件版**:`plugins/XQ0001-0100/XQ0034 续签电子签/`(id=`xq0034`,当前 v1.0.27,宿主 electron-shell,Vue3 网页界面配置 + HR 会话由壳子注入 + 钉钉群机器人通知)
|
||||
- **插件版**:`plugins/XQ0001-0100/XQ0034 续签电子签/`(id=`xq0034`,当前 v1.0.28,宿主 electron-shell,Vue3 网页界面配置 + HR 会话由壳子注入 + 钉钉群机器人通知)
|
||||
- **影刀版**:`workflows/XQ0001-0100/XQ0034 续签电子签/step1_renewal_esign.py`(单文件脚本,注册为影刀自定义指令「XQ0034续签电子签」,`main(dry_run=...)` 关键字传参,结果写全局变量 `messages` 交影刀「37du钉钉群机器人推送」指令逐条发送)
|
||||
- 对接系统:钉钉开放平台(AI 表格 notable OpenAPI 名单读写 + 群机器人 webhook 通知)、37du HR(合同台账 / 续签属性页 / 员工基本信息 / 员工花名册)
|
||||
- 驱动方式:AI 表字段「空/非空」接力触发——「人资是否推送」为空才进入处理,处理完回填;核验靠「人资是否推送=是 且 完成签署/系统处理未填」接力,回填「完成签署/系统处理=是」后不再进入,天然防重;每轮先做 AI 表字段契约校验,再全量读表按字段状态分流——推送阶段 ④ 用工类型同步 → ① 否回填 → ② 是续签,核验阶段 ③ 核验
|
||||
@@ -136,4 +136,4 @@ base=`YndMj49yWjPmvXXDFb1OBGAoJ3pmz5aA`,table=`agznnlF`,操作人固定为
|
||||
- **影刀版**:注册为自定义指令「XQ0034续签电子签」,`main(dry_run=...)` 关键字传参(不传 = 实跑);业务脚本可 importlib 加载调用 `main()`,试算需显式 `main(dry_run=True)` 或环境变量 `XQ0034_DRY_RUN=1`(缺省 `"0"` = 实跑提交);结果写全局变量 `messages` 交「37du钉钉群机器人推送」指令逐条发送。
|
||||
- **试算**:插件界面开「试算模式」(只检查不回写);影刀按上述两种方式之一。生产默认实跑提交。
|
||||
- **依赖与超时**:插件仅依赖 `requests`(requirements.txt);`plugin.json` 未声明 `runTimeoutSeconds` 字段(按宿主默认超时)。
|
||||
- **打包发布**:`ui-src` 构建 → 仓库根执行 `_pack.py` 产 `dist-plugin/xq0034_v1.0.27.zip` → `desktop/` 下 `agent_cli publish`(详见 docs/插件/发版规范.md);双形态源码路径见第一节。
|
||||
- **打包发布**:`ui-src` 构建 → 仓库根执行 `_pack.py` 产 `dist-plugin/xq0034_v1.0.28.zip` → `desktop/` 下 `agent_cli publish`(详见 docs/插件/发版规范.md);双形态源码路径见第一节。
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
pt DistutilsExecError as msg:
|
||||
raise CompileError(msg)
|
||||
continue
|
||||
elif ext in self._mc_extensions:
|
||||
# Compile .MC to .RC file to .RES file.
|
||||
# * '-h dir' specifies the directory for the
|
||||
# generated include file
|
||||
# * '-r dir' specifies the target directory of the
|
||||
# generated RC file and the binary message resource
|
||||
# it includes
|
||||
#
|
||||
# For now (since there are no options to change this),
|
||||
# we use the source-directory for the include file and
|
||||
# the build directory for the RC file and message
|
||||
# resources. This works at least for win32all.
|
||||
h_dir = os.path.dirname(src)
|
||||
rc_dir = os.path.dirname(obj)
|
||||
try:
|
||||
# first compile .MC to .RC and .H file
|
||||
self.spawn([self.mc, '-h', h_dir, '-r', rc_dir, src])
|
||||
base, _ = os.path.splitext(os.path.basename(src))
|
||||
rc_file = os.path.join(rc_dir, base + '.rc')
|
||||
# then compile .RC to .RES file
|
||||
self.spawn([self.rc, "/fo" + obj, rc_file])
|
||||
|
||||
except DistutilsExecError as msg:
|
||||
raise CompileError(msg)
|
||||
continue
|
||||
else:
|
||||
# how to handle this file?
|
||||
raise CompileError(f"Don't know how to compile {src} to {obj}")
|
||||
|
||||
args = [self.cc] + compile_opts + pp_opts
|
||||
if add_cpp_opts:
|
||||
args.append('/EHsc')
|
||||
args.append(input_opt)
|
||||
args.append("/Fo" + obj)
|
||||
args.extend(extra_postargs)
|
||||
|
||||
try:
|
||||
self.spawn
|
||||
Binary file not shown.
@@ -57,7 +57,7 @@ class _LogWriter:
|
||||
class Xq0034Plugin(ScenePlugin):
|
||||
id = "xq0034"
|
||||
name = "续签电子签"
|
||||
version = "1.0.27"
|
||||
version = "1.0.28"
|
||||
description = ("XQ0034 续签电子签:AI表格【续签名单到期跟进-月更新】驱动——否续签回填、"
|
||||
"是续签手机号校验后 HR 生效中合同属性页「续签合同」提交推送电子签并回填;"
|
||||
"按步骤执行(全流程/仅推送/仅核验),HR 会话由壳子注入")
|
||||
|
||||
@@ -61,7 +61,8 @@ HR【劳动关系-合同台账-生效中合同】属性页「续签合同」提
|
||||
填错也视为已续签)-> 防重不回填发起;否则为旧合同 -> 核对 AI 表「合同/协议
|
||||
到期日」与生效中合同截止日期一致(不一致/未填 -> 异常,不发起续签)。
|
||||
4. 属性页 getPropPageData(businessKey=contract_id)-> 原样字段 + AI 表覆盖字段
|
||||
-> savePropPageData 提交(state=="1" 为成功);
|
||||
-> savePropPageData 提交(state=="1" 为成功);new_sign_way 固定 "2"(续签),
|
||||
不可复制原合同 sign_way(原合同是首次新签=1 时会让新合同被记成新签);
|
||||
5. 复查:轮询【待生效合同】Tab 出现该员工行(HR 落库有秒级延迟);
|
||||
6. AI 表回填「人资是否推送=是」「推送时间=期望推送日期」。
|
||||
|
||||
@@ -174,6 +175,13 @@ TEMPLATE_SELECT_URL = (f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/"
|
||||
"rf_hr_contract_template_select_sp_cq37du/getExecuteResult.mc")
|
||||
|
||||
TREATY_MAP = {"劳动合同": "1", "超龄用工协议": "ext_8"}
|
||||
# 签订方式 sign_way(2026-11-09 实测台账口径):1=新签、2=续签、3=改签。
|
||||
# 新合同行的 sign_way 会原样带到【电子签署记录台账】的 sign_type(ext_1/ext_2/ext_3),
|
||||
# 台账即按它显示「新签/续签/改签」——续签必须写 "2"。
|
||||
# ⚠️ 历史坑:曾写成 _rc("hr_staff_contract.sign_way")(复制原合同值),原合同是首次新签(1)
|
||||
# 时新合同也被记成新签(37020458 李阳 2026-11-09 复现:待生效行 sign_way=1,
|
||||
# 签署记录 sign_type=ext_1 显示"新签")。
|
||||
RENEW_SIGN_WAY = "2"
|
||||
ILLEGAL_FILETYPE = ("js,jsp,exe,vbs,jspx,sys,dll,jspf,php,sh,bat,py,java,"
|
||||
"c,class,com,out,elf,jsf.jsp")
|
||||
RENEW_COMPELET_COUNT = "11" # 续签属性页必填数(2026-10-14 浏览器抓包实测值)
|
||||
@@ -222,6 +230,13 @@ def _norm_phone(v):
|
||||
return digits
|
||||
|
||||
|
||||
def _norm_name(v):
|
||||
"""单位名归一:NFKC 折叠全半角括号/空格后比对(AI 表常填营业执照全称,
|
||||
HR 单位下拉里是简称,两者可能全角/半角括号不同)。"""
|
||||
s = unicodedata.normalize("NFKC", str(v or ""))
|
||||
return re.sub(r"\s+", "", s)
|
||||
|
||||
|
||||
# ==================== HR:员工联系方式自动修正(2026-10-14 页面抓包实测) ====================
|
||||
# 员工信息详情页「基本信息」编辑保存接口(tableId=assemble-hr_staff_base 模块):
|
||||
# 读 getTableData(businessKey=base_id) -> 改 mobile_phone -> saveTableData 全量回传
|
||||
@@ -549,6 +564,13 @@ def renew_contract(session, ai, dry_run):
|
||||
if diffs:
|
||||
return "异常", ("防重命中但待生效合同与AI表信息不一致:"
|
||||
+ ";".join(diffs) + ",报异常待人工核对")
|
||||
# 历史错推提示(不改判重结论):2026-11-09 前 new_sign_way 复制原合同值,
|
||||
# 首次续签的人会被记成新签(台账 sign_type=ext_1)
|
||||
w_sign_way = _s(latest_w.get("hr_staff_contract.sign_way"))
|
||||
if w_sign_way and w_sign_way != RENEW_SIGN_WAY:
|
||||
logger.warning("【%s】待生效合同行签订方式 sign_way=%s(非续签 %s),"
|
||||
"疑为历史版本按原合同值写入,请在HR台账人工核对签署类型",
|
||||
code, w_sign_way, RENEW_SIGN_WAY)
|
||||
push_time = _s(latest_w.get("hr_staff_contract_ext.ext_push_time"))
|
||||
if not push_time:
|
||||
return "异常", ("防重命中且合同信息与AI表一致,但待生效合同行无电子签推送时间"
|
||||
@@ -628,11 +650,19 @@ def renew_contract(session, ai, dry_run):
|
||||
expect = ai["expect"].strftime("%Y-%m-%d")
|
||||
|
||||
# 签署单位:AI 表填了才覆盖(名->code 映射失败沿用原合同单位)
|
||||
# 2026-11-09:AI 表常用「营业执照全称」,而 HR 单位下拉里是简称(如 AI 表
|
||||
# 「重庆三十七度健康管理(集团)有限公司」vs 下拉「三十七度公司」),映射必然失败。
|
||||
# 此时若 AI 表名与原合同单位营业执照名称(hr_contract_unit_set.ext_license_name)
|
||||
# 一致,说明本来就同一家 -> 沿用原单位即可,记 INFO(不再误报 WARN);
|
||||
# 否则才是真的「填了别的单位但字典查不到」,保留 WARN 待人工核对。
|
||||
si_area = _rc("hr_staff_contract.si_area")
|
||||
if ai["unit"]:
|
||||
si = _unit_set_id_by_name(session, ai["unit"])
|
||||
if si:
|
||||
si_area = si
|
||||
elif _norm_name(ai["unit"]) == _norm_name(_rc("hr_contract_unit_set.ext_license_name")):
|
||||
logger.info("【%s】合同签署单位「%s」为原合同单位营业执照名称,视为一致,沿用原合同单位",
|
||||
code, ai["unit"])
|
||||
else:
|
||||
logger.warning("【%s】合同签署单位「%s」未匹配到单位 code,沿用原合同单位",
|
||||
code, ai["unit"])
|
||||
@@ -675,7 +705,7 @@ def renew_contract(session, ai, dry_run):
|
||||
"ext_seal_number": _rc("hr_contract_unit_set.ext_seal_number"),
|
||||
"new_contract_no": "",
|
||||
"contract_type_template": template_ids,
|
||||
"new_sign_way": _rc("hr_staff_contract.sign_way", "2"),
|
||||
"new_sign_way": RENEW_SIGN_WAY, # 续签固定 2(勿复制原合同值,见常量注释)
|
||||
"new_data_source": _rc("hr_staff_contract.data_source", "2"),
|
||||
"new_contract_file": "",
|
||||
"new_contract_count": "1",
|
||||
@@ -722,10 +752,21 @@ def renew_contract(session, ai, dry_run):
|
||||
return "失败", f"续签提交失败:{d.get('meg') or d}"
|
||||
|
||||
# 7) 复查:待生效合同出现该员工行(HR 落库有秒级延迟)
|
||||
# 命中后把签订方式打出来(续签应为 2),便于核对台账是否被记成新签
|
||||
# (2026-11-09 37020458 曾落成 sign_way=1)
|
||||
for i in range(VERIFY_TIMES):
|
||||
time.sleep(VERIFY_WAIT_SEC)
|
||||
if query_wait_effect_rows(session, code):
|
||||
return "已推送", f"续签提交成功并已落库(待生效合同出现新行,contract_id={contract_id})"
|
||||
new_rows = query_wait_effect_rows(session, code)
|
||||
if new_rows:
|
||||
latest_n = max(new_rows, key=lambda r: (_to_date(
|
||||
r.get("hr_staff_contract.contract_start_date")) or datetime.min))
|
||||
sign_way = _s(latest_n.get("hr_staff_contract.sign_way")) or "?"
|
||||
new_cid = _s(latest_n.get("hr_staff_contract.contract_id")) or "?"
|
||||
logger.info("【%s】续签已落库:新合同 contract_id=%s,签订方式 sign_way=%s"
|
||||
"(续签应为 %s)", code, new_cid, sign_way, RENEW_SIGN_WAY)
|
||||
return "已推送", (f"续签提交成功并已落库(待生效合同出现新行,"
|
||||
f"新合同 contract_id={new_cid},签订方式 sign_way={sign_way};"
|
||||
f"原合同 contract_id={contract_id})")
|
||||
return "已推送", (f"续签提交接口返回成功(待生效Tab复查暂未命中,HR落库可能有延迟,"
|
||||
f"contract_id={contract_id})")
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0034",
|
||||
"name": "续签电子签",
|
||||
"version": "1.0.27",
|
||||
"version": "1.0.28",
|
||||
"description": "XQ0034 续签电子签(全流程/仅推送/仅核验):钉钉AI表格【续签名单到期跟进-月更新】驱动——否续签回填人资是否推送=否;是续签先补全电话/期望日期并与花名册校验(不一致自动修正联系方式),核对到期日后在HR生效中合同属性页「续签合同」推送电子签并回填;核验最新合同is_initiate_sign=2才回填完成签署=是;推送阶段按「用工类型是否调整」同步花名册用工类型(不一致才改);执行前校验字段不符不处理并推钉钉",
|
||||
"category": "人事考勤",
|
||||
"icon": "",
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""携程数据导出 - webhost 场景插件(XQ0077)
|
||||
|
||||
流程(纯接口,不使用浏览器):
|
||||
1) 登录深大/lotsmall 管理端(图片验证码 OCR + RSA 密码加密;token 缓存复用);
|
||||
2) statisticsSupport(取报表接入参数)→ verifySaasAuthCode(换 JWT)→ preview(取元数据);
|
||||
3) searchFilter 先查询判有无数据,无数据直接跳过;有数据才 newExport 下载 xlsx
|
||||
→ 检票员检票报表_YYYYMMDD_HHMMSS.xlsx。
|
||||
"""
|
||||
import os
|
||||
|
||||
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
||||
|
||||
from . import config
|
||||
from .data import lotsmall_report
|
||||
|
||||
|
||||
class TicketInspectorReportPlugin(ScenePlugin):
|
||||
id = "xq0077"
|
||||
name = "携程数据导出"
|
||||
version = "1.0.2"
|
||||
description = ("深大/lotsmall 管理端「检票员检票报表」导出:账密自动登录(图片验证码 OCR + RSA 密码加密),"
|
||||
"纯接口查询判有无数据后导出 xlsx,日期口径固定昨天 00:00:00 ~ 今天 23:59:59")
|
||||
platform = "" # 管理端自带账密登录,不使用底座共享登录态
|
||||
uses_month = False
|
||||
capabilities = ["xq0077"]
|
||||
permissions = {"platforms": []}
|
||||
# 与 plugin.json.fields 一致
|
||||
fields = {
|
||||
"account": {"type": "string", "title": "登录账号", "default": "",
|
||||
"description": "深大/lotsmall 管理端账号(手机号或用户名)"},
|
||||
"password": {"type": "string", "title": "登录密码", "default": "",
|
||||
"description": "管理端登录密码(明文存本地配置)"},
|
||||
"save_dir": {"type": "string", "title": "保存目录", "default": "",
|
||||
"description": "留空=D:\\资料\\财务\\携程数据导出"},
|
||||
"debug_mode": {"type": "boolean", "title": "调试日志", "default": False},
|
||||
}
|
||||
|
||||
def run(self, fields, ctx) -> dict:
|
||||
fields = fields or {}
|
||||
config.set_log(ctx.log)
|
||||
config.set_progress(ctx.progress)
|
||||
config.set_debug(bool(fields.get("debug_mode")))
|
||||
|
||||
account = str(fields.get("account") or "").strip()
|
||||
password = str(fields.get("password") or "").strip()
|
||||
if not (account and password):
|
||||
raise RuntimeError("请在插件界面填写深大/lotsmall 管理端的登录账号与密码")
|
||||
|
||||
save_dir = str(fields.get("save_dir") or "").strip().strip('"') or config.default_output_dir()
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
begin, end = config.date_window()
|
||||
ctx.log(f"日期区间:{begin} ~ {end}")
|
||||
ctx.log(f"保存目录:{save_dir}")
|
||||
|
||||
result = lotsmall_report.run_export(account, password, save_dir)
|
||||
config.progress(100)
|
||||
|
||||
total = int(result.get("total") or 0)
|
||||
file = result.get("file") or ""
|
||||
date_range = f"{begin} ~ {end}"
|
||||
if total <= 0 or not file:
|
||||
return {
|
||||
"summary": f"无数据,未导出({date_range})",
|
||||
"detail": {"range": date_range, "total": 0, "save_dir": save_dir},
|
||||
"path": save_dir,
|
||||
}
|
||||
return {
|
||||
"summary": f"检票员检票报表导出完成:{os.path.basename(file)}({total} 条)",
|
||||
"detail": {"range": date_range, "total": total, "file": file, "save_dir": save_dir},
|
||||
"path": file,
|
||||
}
|
||||
|
||||
|
||||
PLUGINS.append(TicketInspectorReportPlugin())
|
||||
@@ -1,161 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0077 携程数据导出 插件 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:本包只依赖 Python 标准库 / 第三方库 / 底座注入的 RunContext。
|
||||
业务模块统一经 config.log() 输出日志(转发到 ctx.log,无 ctx 时回落到 print)。
|
||||
|
||||
站点(深大/lotsmall 管理端):
|
||||
- 管理端 www.lotsmall.cn(/admin/api/checkCode 图片验证码 + /admin/storeMerchant/logining 账密登录,
|
||||
返回 user.token 即管理端 tyAuthToken;statisticsSupport 换取报表接入参数);
|
||||
- 报表平台 platform-report-sh1.zhiyoubao.com(换 JWT → preview → searchFilter → newExport)。
|
||||
"""
|
||||
import os
|
||||
import time
|
||||
from datetime import date, timedelta
|
||||
|
||||
# ==================== 站点与接口 ====================
|
||||
ADMIN_BASE = 'https://www.lotsmall.cn'
|
||||
REPORT_BASE = 'https://platform-report-sh1.zhiyoubao.com'
|
||||
|
||||
API_CHECKCODE = '/admin/api/checkCode' # 管理端图片验证码(JPEG 直出)
|
||||
API_ADMIN_LOGIN = '/admin/storeMerchant/logining' # 管理端账密登录(返回 user.token)
|
||||
API_STATISTICS_SUPPORT = '/statistics/webApi/statisticsSupport/'
|
||||
API_VERIFY_SAAS = '/api/partner/auth/verifySaasAuthCode'
|
||||
API_PREVIEW = '/api/report/preview/{report_id}'
|
||||
API_SEARCH = '/api/report/searchFilter'
|
||||
API_EXPORT = '/api/report/newExport'
|
||||
|
||||
# 登录页密码 RSA 公钥(PKCS#1 v1.5,平台前端硬编码,2026-11 实测;管理端与用户中心同一把)
|
||||
RSA_PUBLIC_KEY = (
|
||||
'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDI5kmdW9rmxQlTraZ6Wx+C7kYRDjL332N53dsqFsqq'
|
||||
'T+PX6mosaM5hW4MS4vUbQNtUblhmQgzmUD0KBJFH9YZMmSPLdCC+G4r7d2PPFBrCy+9dFUMUNaT4Penya'
|
||||
'VQJyAp3bhUJ7n93bRJT9jtxsdDwJ/Zl12A/kO93fr7+waaepwIDAQAB'
|
||||
)
|
||||
CAPTCHA_MIN_LEN = 3 # 管理端图片验证码长度范围(实测 4~5 位)
|
||||
CAPTCHA_MAX_LEN = 6
|
||||
|
||||
# 管理端 token 失效(请跳转到登录页)
|
||||
CODE_TOKEN_EXPIRED = 1004001011
|
||||
CODE_OK = 200
|
||||
|
||||
# ==================== 报表(检票员检票报表) ====================
|
||||
REPORT_ID = 3066
|
||||
REPORT_NAME = '检票员检票报表'
|
||||
REPORT_URL = f'https://platform-report-sh1.zhiyoubao.com/reportView?id={REPORT_ID}'
|
||||
# 报表查询固定入参(平台页面实测值)
|
||||
TERMINAL_TPE = '0'
|
||||
MERCHANT_ID = '23985'
|
||||
USER_INFO_ID = '59567'
|
||||
SUB_ACCOUNT_ID = '59925'
|
||||
ROLE_TYPE = '4'
|
||||
APP_ID_DEFAULT = 'xj'
|
||||
PAGE_INDEX = 1
|
||||
PAGE_SIZE = 50
|
||||
|
||||
# ==================== 输出路径 ====================
|
||||
DEFAULT_SAVE_DIR = r'D:\资料\财务\携程数据导出'
|
||||
|
||||
|
||||
def _app_data_dir():
|
||||
return os.path.join(
|
||||
os.environ.get('LOCALAPPDATA') or os.environ.get('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
|
||||
|
||||
SESSIONS_DIR = os.path.join(_app_data_dir(), '.sessions')
|
||||
TOKEN_FILE = os.path.join(SESSIONS_DIR, 'lotsmall_token.json') # {"accessToken": ...}
|
||||
|
||||
|
||||
def default_output_dir():
|
||||
"""默认输出目录。"""
|
||||
return DEFAULT_SAVE_DIR
|
||||
|
||||
|
||||
# ==================== 日期口径(固定规则) ====================
|
||||
def date_window():
|
||||
"""返回 (起, 止) 时间字符串:昨天 00:00:00 ~ 今天 23:59:59。"""
|
||||
today = date.today()
|
||||
prev = today - timedelta(days=1)
|
||||
return f'{prev:%Y-%m-%d} 00:00:00', f'{today:%Y-%m-%d} 23:59:59'
|
||||
|
||||
|
||||
def export_filename():
|
||||
"""导出文件名:检票员检票报表_YYYYMMDD_HHMMSS.xlsx。"""
|
||||
return f'{REPORT_NAME}_{time.strftime("%Y%m%d_%H%M%S")}.xlsx'
|
||||
|
||||
|
||||
# ==================== 运行参数(项目规范:全局重试 3 次) ====================
|
||||
RETRY_MAX = 3 # 接口请求/验证码轮次重试
|
||||
TIMEOUT = 30 # 普通接口超时
|
||||
DOWNLOAD_TIMEOUT = 180 # 导出 xlsx 下载超时
|
||||
|
||||
UA = ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
|
||||
'Chrome/120.0.0.0 Safari/537.36')
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
_progress = None
|
||||
_debug = False
|
||||
|
||||
|
||||
def set_log(fn):
|
||||
"""注入 ctx.log(RunContext.log),各模块经 log()/logger 输出。"""
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def log(msg, level="INFO"):
|
||||
if level == "DEBUG" and not _debug:
|
||||
return
|
||||
if _log:
|
||||
_log(str(msg), level)
|
||||
else:
|
||||
print(f"[{level}] {msg}")
|
||||
|
||||
|
||||
class _ModuleLogger:
|
||||
"""模块级 logger 适配:统一转发到 config.log。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
log(msg % args if args else msg, "DEBUG")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
log(msg % args if args else msg, "INFO")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
log(msg % args if args else msg, "WARN")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
log(msg % args if args else msg, "ERROR")
|
||||
|
||||
|
||||
logger = _ModuleLogger()
|
||||
|
||||
|
||||
def set_progress(fn):
|
||||
"""注入 ctx.progress。"""
|
||||
global _progress
|
||||
_progress = fn
|
||||
|
||||
|
||||
def progress(pct):
|
||||
"""上报进度(0~100);无 ctx 或异常时静默忽略,不影响主流程。"""
|
||||
if not _progress:
|
||||
return
|
||||
try:
|
||||
_progress(max(0, min(100, int(pct))))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def set_debug(flag):
|
||||
global _debug
|
||||
_debug = bool(flag)
|
||||
|
||||
|
||||
def is_debug():
|
||||
return _debug
|
||||
@@ -1,2 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0077 携程数据导出 - 数据层(登录 + 检票员检票报表导出)。"""
|
||||
@@ -1,222 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0077 携程数据导出 - 管理端登录模块(纯接口,自包含)。
|
||||
|
||||
流程(2026-11 实测):
|
||||
1) GET /admin/api/checkCode?rand=<ms> 取图片验证码(JPEG 直出,需同一会话 Cookie);
|
||||
2) ddddocr 识别验证码;
|
||||
3) POST /admin/storeMerchant/logining JSON {username, password: RSA加密, checkcode, cipherText:1},
|
||||
返回 user.token 即管理端 tyAuthToken(后续 statisticsSupport 等接口用它)。
|
||||
|
||||
重试策略:验证码类失败最多 3 轮;账号/密码错误立即停止,绝不重试(避免锁号)。
|
||||
token 缓存:%LOCALAPPDATA%\\37duAutomation\\.sessions\\lotsmall_token.json({"accessToken": ...}),
|
||||
每次运行先用缓存 token 调 statisticsSupport 探测,失效再登录。
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.parse
|
||||
|
||||
import requests
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import padding
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def _log(msg, level="INFO"):
|
||||
config.log(msg, level)
|
||||
|
||||
|
||||
# ==================== 基础会话 ====================
|
||||
def new_session():
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": config.UA,
|
||||
"Origin": config.ADMIN_BASE,
|
||||
"Referer": config.ADMIN_BASE + "/admin/storeMerchant/login",
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
})
|
||||
return session
|
||||
|
||||
|
||||
def fetch_code_image(session):
|
||||
"""取管理端图片验证码(JPEG 字节);验证码与当前会话 Cookie 绑定。"""
|
||||
resp = session.get(config.ADMIN_BASE + config.API_CHECKCODE,
|
||||
params={"rand": int(time.time() * 1000)}, timeout=config.TIMEOUT)
|
||||
if resp.status_code != 200 or not resp.content:
|
||||
raise RuntimeError(f"获取图片验证码失败(HTTP {resp.status_code})")
|
||||
if resp.content[:2] != b'\xff\xd8': # JPEG 魔数,避免把错误 JSON 当图片
|
||||
raise RuntimeError(f"图片验证码返回非图片:{resp.text[:120]}")
|
||||
return resp.content
|
||||
|
||||
|
||||
def ocr_code(img_bytes):
|
||||
"""ddddocr 识别验证码;长度不在合理区间视为识别失败。"""
|
||||
try:
|
||||
import ddddocr
|
||||
except ImportError:
|
||||
raise RuntimeError("未安装 ddddocr,请先 pip install ddddocr")
|
||||
code = ddddocr.DdddOcr(show_ad=False).classification(img_bytes).strip()
|
||||
if config.CAPTCHA_MIN_LEN <= len(code) <= config.CAPTCHA_MAX_LEN:
|
||||
return code
|
||||
return ""
|
||||
|
||||
|
||||
def rsa_encrypt(text):
|
||||
"""RSA PKCS#1 v1.5 加密 + URL 编码(与前端 setRSA 一致)。"""
|
||||
pem = ("-----BEGIN PUBLIC KEY-----\n" + config.RSA_PUBLIC_KEY +
|
||||
"\n-----END PUBLIC KEY-----")
|
||||
key = serialization.load_pem_public_key(pem.encode())
|
||||
cipher = key.encrypt(text.encode(), padding.PKCS1v15())
|
||||
return urllib.parse.quote(base64.b64encode(cipher).decode(), safe="")
|
||||
|
||||
|
||||
def do_login(session, account, password, code):
|
||||
"""账密登录。注意:管理端 apiPost 用 x-www-form-urlencoded(qs 序列化),不能发 JSON。"""
|
||||
payload = {
|
||||
"username": account,
|
||||
"password": rsa_encrypt(password),
|
||||
"checkcode": code,
|
||||
"cipherText": 1,
|
||||
}
|
||||
resp = session.post(config.ADMIN_BASE + config.API_ADMIN_LOGIN, data=payload,
|
||||
headers={"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"},
|
||||
timeout=config.TIMEOUT)
|
||||
try:
|
||||
return resp.json(), resp.text
|
||||
except ValueError:
|
||||
raise RuntimeError(f"登录接口返回非 JSON(HTTP {resp.status_code}):{resp.text[:200]}")
|
||||
|
||||
|
||||
# ==================== token 缓存 ====================
|
||||
def _atomic_write(path, text):
|
||||
"""原子写:先写临时文件再整体替换,避免中断留下半截文件。"""
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
tmp = f'{path}.tmp'
|
||||
with open(tmp, 'w', encoding='utf-8') as f:
|
||||
f.write(text)
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def load_token():
|
||||
if not os.path.exists(config.TOKEN_FILE):
|
||||
return ""
|
||||
try:
|
||||
with open(config.TOKEN_FILE, encoding='utf-8') as f:
|
||||
return str((json.load(f) or {}).get("accessToken") or "")
|
||||
except Exception as e:
|
||||
_log(f"读取 token 缓存失败:{e}", "WARN")
|
||||
return ""
|
||||
|
||||
|
||||
def save_token(token):
|
||||
try:
|
||||
_atomic_write(config.TOKEN_FILE, json.dumps({"accessToken": token}, ensure_ascii=False))
|
||||
_log(f"token 已缓存 → {config.TOKEN_FILE}")
|
||||
except Exception as e:
|
||||
_log(f"token 缓存写入失败(不影响本次运行):{e}", "WARN")
|
||||
|
||||
|
||||
# ==================== 管理端 token 探测 / 报表接入参数 ====================
|
||||
def fetch_report_params(token):
|
||||
"""statisticsSupport 探测 token 并取报表接入参数。
|
||||
|
||||
返回 data(含 authCode/appId/sign/timestamp/bigDataLoginAuthCode/corpCode);
|
||||
token 失效或返回异常时返回 None。
|
||||
"""
|
||||
if not token:
|
||||
return None
|
||||
ts = int(time.time() * 1000)
|
||||
url = (f"{config.ADMIN_BASE}{config.API_STATISTICS_SUPPORT}"
|
||||
f"?timestamp={ts}&reportId={config.REPORT_ID}"
|
||||
f"&reportUrl={config.REPORT_URL}&terminalTpe=0")
|
||||
try:
|
||||
resp = requests.get(url, headers={
|
||||
"tyAuthToken": token,
|
||||
"User-Agent": config.UA,
|
||||
"Referer": config.ADMIN_BASE + "/manage/",
|
||||
}, timeout=config.TIMEOUT)
|
||||
data = resp.json()
|
||||
except Exception as e:
|
||||
_log(f"statisticsSupport 探测异常:{e}", "WARN")
|
||||
return None
|
||||
if data.get("code") == config.CODE_TOKEN_EXPIRED:
|
||||
_log("管理端 token 已失效(请跳转到登录页)")
|
||||
return None
|
||||
if data.get("code") != config.CODE_OK or not data.get("data"):
|
||||
_log(f"statisticsSupport 失败:{str(data)[:200]}", "WARN")
|
||||
return None
|
||||
return data["data"]
|
||||
|
||||
|
||||
# ==================== 主入口 ====================
|
||||
def ensure_login(account, password, force=False):
|
||||
"""确保存在可用的管理端 token。
|
||||
|
||||
先复用缓存 token(statisticsSupport 探测),失效再走账密登录。
|
||||
返回 dict:{success, token, message, relogin}
|
||||
"""
|
||||
account = (account or '').strip()
|
||||
password = (password or '').strip()
|
||||
|
||||
if not force:
|
||||
token = load_token()
|
||||
if token and fetch_report_params(token):
|
||||
_log("已通过缓存的 token 复用管理端登录态")
|
||||
return {"success": True, "token": token, "message": "复用缓存登录态", "relogin": False}
|
||||
|
||||
if not (account and password):
|
||||
msg = "登录账号/密码缺失:请在插件界面填写并保存配置"
|
||||
_log(msg, "ERROR")
|
||||
return {"success": False, "token": "", "message": msg, "relogin": False}
|
||||
|
||||
session = new_session()
|
||||
last_msg = ""
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
_log(f"登录第 {attempt}/{config.RETRY_MAX} 轮")
|
||||
try:
|
||||
code = ocr_code(fetch_code_image(session))
|
||||
_log(f"图片验证码 OCR:{code or '识别失败'}")
|
||||
except Exception as e:
|
||||
last_msg = f"获取验证码异常:{e}"
|
||||
_log(last_msg, "WARN")
|
||||
continue
|
||||
if not code:
|
||||
last_msg = "本轮验证码未识别出来"
|
||||
_log(last_msg, "WARN")
|
||||
continue
|
||||
|
||||
try:
|
||||
resp, raw = do_login(session, account, password, code)
|
||||
except Exception as e:
|
||||
last_msg = f"登录请求异常:{e}"
|
||||
_log(last_msg, "WARN")
|
||||
continue
|
||||
|
||||
if not isinstance(resp, dict):
|
||||
last_msg = f"登录返回异常:{raw[:300]}"
|
||||
_log(last_msg, "WARN")
|
||||
continue
|
||||
|
||||
if resp.get("success"):
|
||||
user = resp.get("user") or {}
|
||||
token = str(user.get("token") or "")
|
||||
if not token:
|
||||
last_msg = "登录成功但未返回 user.token"
|
||||
_log(last_msg, "WARN")
|
||||
continue
|
||||
_log(f"登录成功,token={token[:24]}...")
|
||||
save_token(token)
|
||||
return {"success": True, "token": token, "message": "登录成功", "relogin": True}
|
||||
|
||||
msg = str(resp.get("message") or "")
|
||||
last_msg = f"登录失败:{msg or raw[:300]}"
|
||||
_log(last_msg, "WARN")
|
||||
|
||||
if "双因子" in msg or resp.get("twoFactorValidationSwitch") == "T":
|
||||
return {"success": False, "token": "", "message": "账号开启了双因子验证,无法自动登录", "relogin": False}
|
||||
if "密码" in msg or "账号" in msg:
|
||||
return {"success": False, "token": "", "message": f"账号或密码错误,已停止:{msg}", "relogin": False}
|
||||
|
||||
return {"success": False, "token": "", "message": last_msg or "登录失败", "relogin": False}
|
||||
@@ -1,222 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0077 携程数据导出 - 检票员检票报表导出(纯接口,自包含)。
|
||||
|
||||
链路(2026-11 实测):
|
||||
statisticsSupport(管理端 token 换 authCode/appId/sign/timestamp/userCode/corpCode)
|
||||
→ verifySaasAuthCode(换报表平台 JWT)
|
||||
→ preview(取 reportDetailId 与 reportColumnList)
|
||||
→ searchFilter(查询,判 total)
|
||||
→ total > 0 才 newExport(下载 xlsx 二进制)。
|
||||
|
||||
日期口径固定:昨天 00:00:00 ~ 今天 23:59:59;
|
||||
查询无数据(total 为 0 或缺失)直接跳过导出,返回 {"total": 0, "file": ""}。
|
||||
"""
|
||||
import os
|
||||
import time
|
||||
import urllib.parse
|
||||
|
||||
import requests
|
||||
|
||||
from .. import config
|
||||
from . import lotsmall_login
|
||||
|
||||
|
||||
class AuthError(RuntimeError):
|
||||
"""账密错误/配置缺失:不可重试(避免锁号)。"""
|
||||
|
||||
|
||||
def _log(msg, level="INFO"):
|
||||
config.log(msg, level)
|
||||
|
||||
|
||||
# ==================== 报表平台会话 ====================
|
||||
def _report_session():
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": config.UA,
|
||||
"Origin": config.REPORT_BASE,
|
||||
"Referer": config.REPORT_BASE + "/",
|
||||
})
|
||||
return session
|
||||
|
||||
|
||||
def _verify_saas(session, auth_code, app_id):
|
||||
"""authCode/appId 换报表平台 JWT。"""
|
||||
resp = session.get(config.REPORT_BASE + config.API_VERIFY_SAAS,
|
||||
params={"authCode": auth_code, "appId": app_id},
|
||||
timeout=config.TIMEOUT)
|
||||
try:
|
||||
body = resp.json()
|
||||
except ValueError:
|
||||
raise RuntimeError(f"verifySaasAuthCode 返回非 JSON(HTTP {resp.status_code}):{resp.text[:200]}")
|
||||
result = body.get("result") or {}
|
||||
jwt = (result.get("token") or result.get("accessToken")
|
||||
or (body.get("data") or {}).get("token"))
|
||||
if not jwt:
|
||||
raise RuntimeError(f"未取到 JWT:{str(body)[:300]}")
|
||||
return jwt
|
||||
|
||||
|
||||
def _auth_headers(info, app_id, jwt):
|
||||
"""报表平台后续接口统一请求头(除 JWT 外还要带 authCode/appId/timestamp/sign)。"""
|
||||
return {
|
||||
"authCode": info["authCode"],
|
||||
"appId": app_id,
|
||||
"timestamp": str(info["timestamp"]),
|
||||
"sign": info["sign"],
|
||||
"Authorization": jwt,
|
||||
"Content-Type": "application/json",
|
||||
"Origin": config.REPORT_BASE,
|
||||
"Referer": config.REPORT_BASE + "/",
|
||||
}
|
||||
|
||||
|
||||
def _preview(session, info, app_id, headers):
|
||||
"""取报表元数据:reportDetailId 与 reportColumnList。"""
|
||||
params = {
|
||||
"authCode": info["authCode"],
|
||||
"appId": app_id,
|
||||
"sign": info["sign"],
|
||||
"timestamp": info["timestamp"],
|
||||
"userCode": info.get("bigDataLoginAuthCode"),
|
||||
"corpCode": info.get("corpCode"),
|
||||
"terminalTpe": 0,
|
||||
}
|
||||
url = config.REPORT_BASE + config.API_PREVIEW.format(report_id=config.REPORT_ID)
|
||||
resp = session.get(url, params=params, headers=headers, timeout=config.TIMEOUT)
|
||||
try:
|
||||
body = resp.json()
|
||||
except ValueError:
|
||||
raise RuntimeError(f"preview 返回非 JSON(HTTP {resp.status_code}):{resp.text[:200]}")
|
||||
result = body.get("result") or {}
|
||||
detail_id = result.get("reportDetailId") or result.get("id")
|
||||
columns = result.get("reportColumnList") or []
|
||||
if not detail_id:
|
||||
raise RuntimeError(f"preview 未返回 reportDetailId:{str(body)[:300]}")
|
||||
return detail_id, columns
|
||||
|
||||
|
||||
def _query_body(info, app_id, detail_id, columns, begin, end):
|
||||
"""searchFilter / newExport 共用请求体(newExport 再追加 reportColumnFilterList)。"""
|
||||
return {
|
||||
"shareMode": 0,
|
||||
"reportType": 0,
|
||||
"id": detail_id,
|
||||
"params": {
|
||||
"terminalTpe": config.TERMINAL_TPE,
|
||||
"merchant_id": config.MERCHANT_ID,
|
||||
"userInfoId": config.USER_INFO_ID,
|
||||
"corpCode": info.get("corpCode"),
|
||||
"appId": app_id,
|
||||
"userCode": info.get("bigDataLoginAuthCode"),
|
||||
"subAccountId": config.SUB_ACCOUNT_ID,
|
||||
"roleType": config.ROLE_TYPE,
|
||||
"pageIndex": config.PAGE_INDEX,
|
||||
"pageSize": config.PAGE_SIZE,
|
||||
"beginTradeDate": begin,
|
||||
"endTradeDate": end,
|
||||
"id": str(config.REPORT_ID),
|
||||
},
|
||||
"reportColumnDisplayList": columns,
|
||||
}
|
||||
|
||||
|
||||
def _search(session, headers, body):
|
||||
"""查询报表,返回 total(0 或缺省即无数据)。"""
|
||||
resp = session.post(config.REPORT_BASE + config.API_SEARCH,
|
||||
headers=headers, json=body, timeout=config.TIMEOUT)
|
||||
try:
|
||||
result = (resp.json() or {}).get("result") or {}
|
||||
except ValueError:
|
||||
raise RuntimeError(f"searchFilter 返回非 JSON(HTTP {resp.status_code}):{resp.text[:200]}")
|
||||
items = result.get("reportSearchList") or []
|
||||
first = items[0] if items else {}
|
||||
try:
|
||||
total = int(first.get("total") or 0)
|
||||
except (TypeError, ValueError):
|
||||
total = 0
|
||||
_log(f"查询结果:total={total},rows={len(first.get('rows') or [])}"
|
||||
f"({config.PAGE_SIZE} 条/页仅用于探测,导出为全量)")
|
||||
return total
|
||||
|
||||
|
||||
def _export(session, headers, body, save_dir):
|
||||
"""下载 xlsx 并落盘,返回文件路径。"""
|
||||
resp = session.post(config.REPORT_BASE + config.API_EXPORT,
|
||||
headers=headers, json=body, timeout=config.DOWNLOAD_TIMEOUT)
|
||||
if resp.content[:2] != b'PK':
|
||||
raise RuntimeError(f"导出返回非 xlsx(HTTP {resp.status_code}):{resp.text[:300]}")
|
||||
cd = resp.headers.get("content-disposition") or ""
|
||||
if "filename=" in cd:
|
||||
server_name = cd.split("filename=", 1)[1].strip().strip('"')
|
||||
_log(f"服务端文件名:{urllib.parse.unquote(server_name)}")
|
||||
path = os.path.join(save_dir, config.export_filename())
|
||||
with open(path, 'wb') as f:
|
||||
f.write(resp.content)
|
||||
_log(f"导出完成 → {path}({len(resp.content)} bytes)")
|
||||
return path
|
||||
|
||||
|
||||
# ==================== 主入口 ====================
|
||||
def run_export(account, password, save_dir=''):
|
||||
"""查询并导出「检票员检票报表」。
|
||||
|
||||
返回:{'total': 查询总数, 'file': 落盘路径(无数据时为空字符串)}
|
||||
登录/接口失败抛 RuntimeError(账密错误立即停止,不重试)。
|
||||
"""
|
||||
save_dir = (save_dir or '').strip().strip('"') or config.default_output_dir()
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
begin, end = config.date_window()
|
||||
_log(f"日期区间:{begin} ~ {end}")
|
||||
_log(f"保存目录:{save_dir}")
|
||||
config.progress(5)
|
||||
|
||||
last_err = None
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
try:
|
||||
# 1) 登录(优先复用缓存 token)
|
||||
login = lotsmall_login.ensure_login(account, password, force=(attempt > 1))
|
||||
if not login.get("success"):
|
||||
msg = login.get("message") or "登录失败"
|
||||
if "账号或密码错误" in msg or "缺失" in msg:
|
||||
raise AuthError(msg)
|
||||
raise RuntimeError(f"登录失败:{msg}")
|
||||
info = lotsmall_login.fetch_report_params(login.get("token"))
|
||||
if not info:
|
||||
raise RuntimeError("取不到报表接入参数(token 可能已失效)")
|
||||
app_id = str(info.get("appId") or config.APP_ID_DEFAULT)
|
||||
for key in ("authCode", "sign", "timestamp"):
|
||||
if not info.get(key):
|
||||
raise RuntimeError(f"statisticsSupport 缺少 {key}:{str(info)[:300]}")
|
||||
config.progress(25)
|
||||
|
||||
# 2) 换 JWT → preview
|
||||
session = _report_session()
|
||||
jwt = _verify_saas(session, info["authCode"], app_id)
|
||||
headers = _auth_headers(info, app_id, jwt)
|
||||
detail_id, columns = _preview(session, info, app_id, headers)
|
||||
_log(f"报表元数据:reportDetailId={detail_id},列数={len(columns)}")
|
||||
config.progress(45)
|
||||
|
||||
# 3) 查询判有无数据(无数据跳过导出)
|
||||
body = _query_body(info, app_id, detail_id, columns, begin, end)
|
||||
total = _search(session, headers, body)
|
||||
if total <= 0:
|
||||
_log("查询无数据,跳过导出")
|
||||
config.progress(100)
|
||||
return {'total': 0, 'file': ''}
|
||||
config.progress(65)
|
||||
|
||||
# 4) 导出
|
||||
body["reportColumnFilterList"] = [{"reportDetailId": detail_id}]
|
||||
path = _export(session, headers, body, save_dir)
|
||||
config.progress(100)
|
||||
return {'total': total, 'file': path}
|
||||
except AuthError:
|
||||
raise
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
_log(f"第 {attempt}/{config.RETRY_MAX} 次导出失败:{e}", "WARN")
|
||||
time.sleep(1)
|
||||
|
||||
raise RuntimeError(f"检票员检票报表导出失败(重试 {config.RETRY_MAX} 次耗尽):{last_err}")
|
||||
@@ -1,51 +0,0 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0077",
|
||||
"name": "携程数据导出",
|
||||
"version": "1.0.2",
|
||||
"description": "深大/lotsmall 管理端「检票员检票报表」导出:账密自动登录(图片验证码 OCR + RSA 密码加密),纯接口查询判有无数据后导出 xlsx,日期口径固定昨天 00:00:00 ~ 今天 23:59:59。登录 token 缓存复用,密码错误立即停止避免锁号。",
|
||||
"category": "财务",
|
||||
"icon": "",
|
||||
"platform": "",
|
||||
"uses_month": false,
|
||||
"ui": true,
|
||||
"capabilities": [
|
||||
"xq0077"
|
||||
],
|
||||
"permissions": {
|
||||
"platforms": []
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"account": {
|
||||
"type": "string",
|
||||
"title": "登录账号",
|
||||
"default": "",
|
||||
"description": "深大/lotsmall 管理端账号(手机号或用户名)"
|
||||
},
|
||||
"password": {
|
||||
"type": "string",
|
||||
"title": "登录密码",
|
||||
"default": "",
|
||||
"description": "管理端登录密码(明文存本地配置)"
|
||||
},
|
||||
"save_dir": {
|
||||
"type": "string",
|
||||
"title": "保存目录",
|
||||
"default": "D:\\资料\\财务\\携程数据导出",
|
||||
"description": "导出的 xlsx 统一输出目录"
|
||||
},
|
||||
"debug_mode": {
|
||||
"type": "boolean",
|
||||
"title": "调试日志",
|
||||
"default": false,
|
||||
"description": "开启后输出完整调试日志(默认关闭)"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"account",
|
||||
"password"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
requests>=2.28
|
||||
cryptography>=39.0
|
||||
ddddocr>=1.4
|
||||
opencv-python-headless>=4.8
|
||||
numpy>=1.24
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,13 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>携程数据导出</title>
|
||||
<script type="module" crossorigin src="/pui/xq0077/assets/index-B5bAs3Hl.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0077/assets/index-CXuG8RKx.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -43,6 +43,7 @@ proxy_tools==0.1.0
|
||||
psutil==7.2.2
|
||||
pyclipper==1.4.0
|
||||
pycparser==3.0
|
||||
pycryptodome==3.24.0
|
||||
pydantic==2.13.5
|
||||
pydantic_core==2.46.5
|
||||
pyinstaller==6.22.3
|
||||
|
||||
@@ -101,6 +101,7 @@ workflows/
|
||||
|
||||
- 环境变量:`oa_login_url`、`oa_target_url_keyword`、`oa_login_username`、`oa_login_password`、`oa_validate_url`(可选)
|
||||
- 会话校验接口(默认):`sysNotifyTodo.do?method=sumTodoCount`,cookies 有效时返回 JSON、失效时被重定向返回 HTML
|
||||
- ⚠ 校验请求必须带 `X-Requested-With: XMLHttpRequest`(+ `Referer` 门户页),与业务脚本口径一致;OA 网关偶发 **468**(风控瞬时拦截,前端 JS 未定义该状态码、非会话失效,数秒自愈)→ 模块内置退避重试,勿把 468 当登录失败
|
||||
- 入口:`main(args)`、`ensure_login(force=False)`、`_load_shared_env()`
|
||||
- 写 `oa_cookies.json`;流程全局变量 `login_state`
|
||||
- 依赖:`DrissionPage requests python-dotenv`;接口版只用 `requests`,无浏览器
|
||||
|
||||
@@ -145,8 +145,8 @@ F_END = "续签截止日期" # date -> contract_end_date
|
||||
F_TYPE = "续签类型" # text 劳动合同/超龄用工协议 -> treaty_type
|
||||
F_UNIT = "合同签署单位" # text -> si_area(填了才覆盖)
|
||||
F_PHONE = "电子签接收电话号码" # text,与花名册 hr_staff_base.mobile_phone 比对
|
||||
# ⚠️ 2026-11-03 张玲玲把「完成签署」改名为「完成签署/系统处理」(旧名已不存在,
|
||||
# 写旧名 AI 表直接 404 fail to find field,整批回写失败、完成签署永远回填不上)
|
||||
# ⚠️ 2026-11-03 张玲玲把「完成签署」改名为「完成签署/系统处理」(旧名已不存在,
|
||||
# 写旧名 AI 表直接 404 fail to find field,整批回写失败、完成签署永远回填不上)
|
||||
F_DONE = "完成签署/系统处理" # singleSelect 是/否(核验步骤回填:最新合同已完成电子签)
|
||||
F_EXPIRE = "合同/协议到期日" # date(旧合同到期日,2026-10-19 用于判断生效中合同是否已续签)
|
||||
F_EMP_TYPE = "用工类型是否调整" # text:填目标用工类型名(空/0/#N/A 等 = 不调整)
|
||||
@@ -197,6 +197,12 @@ SAVE_PROP_URL_RENEW = (f"{HR_BASE_URL}/RedseaPlatform/HrTableEngine/"
|
||||
f"{PROP_PAGE_RENEW}/savePropPageData.mc")
|
||||
|
||||
TREATY_MAP = {"劳动合同": "1", "超龄用工协议": "ext_8"}
|
||||
# 签订方式 sign_way(2026-11-09 实测台账口径):1=新签、2=续签、3=改签。
|
||||
# 新合同行的 sign_way 会原样带到【电子签署记录台账】的 sign_type(ext_1/ext_2/ext_3),
|
||||
# 台账即按它显示「新签/续签/改签」——续签必须写 "2"。
|
||||
# ⚠️ 历史坑:曾写成 _rc("hr_staff_contract.sign_way")(复制原合同值),原合同是首次新签(1)
|
||||
# 时新合同也被记成新签(37020458 李阳 2026-11-09 复现)。
|
||||
RENEW_SIGN_WAY = "2"
|
||||
ILLEGAL_FILETYPE = ("js,jsp,exe,vbs,jspx,sys,dll,jspf,php,sh,bat,py,java,"
|
||||
"c,class,com,out,elf,jsf.jsp")
|
||||
RENEW_COMPELET_COUNT = "11" # 续签属性页必填数(2026-10-14 浏览器抓包实测值)
|
||||
@@ -237,6 +243,13 @@ def _norm_phone(v):
|
||||
return digits
|
||||
|
||||
|
||||
def _norm_name(v):
|
||||
"""单位名归一:NFKC 折叠全半角括号/空格后比对(AI 表常填营业执照全称,
|
||||
HR 单位下拉里是简称,两者可能全角/半角括号不同)。"""
|
||||
s = unicodedata.normalize("NFKC", str(v or ""))
|
||||
return re.sub(r"\s+", "", s)
|
||||
|
||||
|
||||
# ==================== HR:员工联系方式自动修正(2026-10-14 页面抓包实测) ====================
|
||||
# 员工信息详情页「基本信息」编辑保存接口(tableId=assemble-hr_staff_base 模块):
|
||||
# 读 getTableData(businessKey=base_id) -> 改 mobile_phone -> saveTableData 全量回传
|
||||
@@ -307,133 +320,133 @@ def _fix_hr_mobile_phone(session, base_id, target_phone):
|
||||
if roster and _norm_phone(roster.get("hr_staff_base.mobile_phone")) == _norm_phone(target_phone):
|
||||
return True, f"HR联系方式已自动修正:{old or '(空)'} -> {target_phone}"
|
||||
logger.info("联系方式修正复查第 %d 次未命中(延迟落库等待)", i + 1)
|
||||
return False, "保存返回成功但复查花名册联系方式未变更,请人工核实"
|
||||
|
||||
|
||||
def _fix_hr_identity(session, base_id, target_code, target_name):
|
||||
"""把 HR 员工「用工类型」修正为 AI 表指定值(读全量 -> 改 identity -> 存 -> 复查)。"""
|
||||
resp = _request_retry("POST", STAFF_GET_URL, session,
|
||||
data={"businessKey": base_id, "roleId": ""})
|
||||
d = resp.json()
|
||||
if str(d.get("state")) != "1":
|
||||
return False, f"读取员工基本信息失败:{d.get('meg') or d}"
|
||||
form = {}
|
||||
for k, v in (d.get("result") or {}).items():
|
||||
if k.startswith("_"):
|
||||
continue
|
||||
if "." in k:
|
||||
k = k.split(".", 1)[1]
|
||||
s2 = "" if v is None else str(v).strip()
|
||||
if re.match(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$", s2):
|
||||
s2 = s2[:10]
|
||||
form[k] = s2
|
||||
old = form.get("identity") or ""
|
||||
if old == target_code:
|
||||
return True, f"HR用工类型已是 {target_name}(无需修正)"
|
||||
form["identity"] = target_code
|
||||
form.update({
|
||||
"businessKey": base_id, "table_id": STAFF_TABLE_ID,
|
||||
"fkId": "", "struTreeCode": "", "belongUnitStruId": "", "struId": "",
|
||||
"illegalFiletype": STAFF_ILLEGAL_FILETYPE, "uploadLimitSize": "500",
|
||||
"rootId": "", "isVirtual": "", "isHrTable": "1",
|
||||
"compeletCount": STAFF_COMPELET_COUNT, "is_collect_info": "1",
|
||||
"operator_name": CURRENT_USER_NAME, "OPERATOR": CURRENT_USER_ID,
|
||||
"OPERAT_TIME": "@operate_time@yyyy-MM-dd HH:mm:ss",
|
||||
})
|
||||
resp = _request_retry("POST", STAFF_SAVE_URL, session, data=form, headers=CSRF_HEADERS)
|
||||
d = resp.json()
|
||||
if str(d.get("state")) != "1":
|
||||
return False, f"保存员工用工类型失败:{d.get('meg') or d}"
|
||||
|
||||
staff_code = form.get("base_code") or ""
|
||||
for i in range(5):
|
||||
time.sleep(3)
|
||||
roster = query_staff_roster(session, staff_code)
|
||||
if roster and _s(roster.get(F_HR_IDENTITY)) == target_code:
|
||||
old_name = IDENTITY_NAME_BY_CODE.get(old, old or "(空)")
|
||||
return True, f"HR用工类型已自动修正:{old_name} -> {target_name}"
|
||||
logger.info("用工类型修正复查第 %d 次未命中(延迟落库等待)", i + 1)
|
||||
return False, "保存返回成功但复查花名册用工类型未变更,请人工核实"
|
||||
|
||||
|
||||
def sync_employee_type(session, records, dry_run):
|
||||
"""④ 用工类型同步:AI表「用工类型是否调整」有合法值时,把 HR 花名册用工类型改成该值。
|
||||
|
||||
与手机号口径一致——只有 HR 当前值与 AI 表目标值不一致时才改;空、0、#N/A、
|
||||
数字等公式残留一律跳过(不调整)。值不在 HR 用工类型字典内也跳过并记日志。
|
||||
"""
|
||||
todo = []
|
||||
for rec in records:
|
||||
f = rec.get("fields") or {}
|
||||
raw = _s(f.get(F_EMP_TYPE))
|
||||
if not raw:
|
||||
continue
|
||||
key = unicodedata.normalize("NFKC", raw).strip()
|
||||
if key in IDENTITY_NO_CHANGE:
|
||||
continue
|
||||
code = _norm_code(f.get(F_CODE))
|
||||
name = _s(f.get(F_NAME))
|
||||
target_code = IDENTITY_CODE_BY_NAME.get(key)
|
||||
if not target_code and key in IDENTITY_NAME_BY_CODE: # AI 表直接填 code 也接受
|
||||
target_code = key
|
||||
if not target_code:
|
||||
logger.warning("【%s】用工类型是否调整=「%s」不是合法用工类型,跳过(不改花名册)",
|
||||
code, raw)
|
||||
continue
|
||||
if not code:
|
||||
logger.warning("【%s】用工类型是否调整=「%s」但工号为空,跳过", name, raw)
|
||||
continue
|
||||
todo.append((rec, code, name, target_code))
|
||||
|
||||
results = []
|
||||
if not todo:
|
||||
logger.info("④ 用工类型同步:无待调整记录")
|
||||
return results
|
||||
# 同一工号在 AI 表可能有多条批次行:目标值冲突时不做任何修改,避免改错
|
||||
targets = {}
|
||||
for _, code, _, target_code in todo:
|
||||
targets.setdefault(code, set()).add(target_code)
|
||||
conflicted = {c for c, s in targets.items() if len(s) > 1}
|
||||
for c in sorted(conflicted):
|
||||
logger.warning("【%s】AI表多条记录的用工类型调整值不一致(%s),本次跳过不改花名册",
|
||||
c, "/".join(sorted(IDENTITY_NAME_BY_CODE.get(x, x) for x in targets[c])))
|
||||
if conflicted:
|
||||
todo = [t for t in todo if t[1] not in conflicted]
|
||||
if not todo:
|
||||
return results
|
||||
logger.info("④ 用工类型同步:%d 条有合法调整值,逐条核对花名册", len(todo))
|
||||
for rec, code, name, target_code in todo:
|
||||
target_name = IDENTITY_NAME_BY_CODE.get(target_code, target_code)
|
||||
r = {"record_id": rec.get("id"), "code": code, "name": name, "status": "跳过",
|
||||
"msg": "", "backfill": None, "prefill": None, "alert": False}
|
||||
roster = query_staff_roster(session, code)
|
||||
if not roster:
|
||||
r["status"], r["msg"] = "异常", f"花名册查无此人,无法同步用工类型(AI表={target_name})"
|
||||
logger.error("【%s】%s", code, r["msg"])
|
||||
results.append(r)
|
||||
continue
|
||||
cur = _s(roster.get(F_HR_IDENTITY))
|
||||
if cur == target_code:
|
||||
logger.info("【%s】用工类型与AI表一致(%s),无需调整", code, target_name)
|
||||
continue
|
||||
if dry_run:
|
||||
r["status"] = "试算"
|
||||
r["msg"] = (f"[试算] 将把HR用工类型 "
|
||||
f"{IDENTITY_NAME_BY_CODE.get(cur, cur or '(空)')} 改为 {target_name}")
|
||||
logger.info("【%s】%s", code, r["msg"])
|
||||
results.append(r)
|
||||
continue
|
||||
base_id = roster.get("hr_staff_base.base_id") or ""
|
||||
if not base_id:
|
||||
r["status"], r["msg"] = "异常", "花名册缺少 base_id,无法同步用工类型"
|
||||
logger.error("【%s】%s", code, r["msg"])
|
||||
results.append(r)
|
||||
continue
|
||||
ok, note = _fix_hr_identity(session, base_id, target_code, target_name)
|
||||
r["status"] = "已同步" if ok else "异常"
|
||||
r["msg"] = note
|
||||
(logger.info if ok else logger.error)("【%s】用工类型同步:%s", code, note)
|
||||
results.append(r)
|
||||
return False, "保存返回成功但复查花名册联系方式未变更,请人工核实"
|
||||
|
||||
|
||||
def _fix_hr_identity(session, base_id, target_code, target_name):
|
||||
"""把 HR 员工「用工类型」修正为 AI 表指定值(读全量 -> 改 identity -> 存 -> 复查)。"""
|
||||
resp = _request_retry("POST", STAFF_GET_URL, session,
|
||||
data={"businessKey": base_id, "roleId": ""})
|
||||
d = resp.json()
|
||||
if str(d.get("state")) != "1":
|
||||
return False, f"读取员工基本信息失败:{d.get('meg') or d}"
|
||||
form = {}
|
||||
for k, v in (d.get("result") or {}).items():
|
||||
if k.startswith("_"):
|
||||
continue
|
||||
if "." in k:
|
||||
k = k.split(".", 1)[1]
|
||||
s2 = "" if v is None else str(v).strip()
|
||||
if re.match(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$", s2):
|
||||
s2 = s2[:10]
|
||||
form[k] = s2
|
||||
old = form.get("identity") or ""
|
||||
if old == target_code:
|
||||
return True, f"HR用工类型已是 {target_name}(无需修正)"
|
||||
form["identity"] = target_code
|
||||
form.update({
|
||||
"businessKey": base_id, "table_id": STAFF_TABLE_ID,
|
||||
"fkId": "", "struTreeCode": "", "belongUnitStruId": "", "struId": "",
|
||||
"illegalFiletype": STAFF_ILLEGAL_FILETYPE, "uploadLimitSize": "500",
|
||||
"rootId": "", "isVirtual": "", "isHrTable": "1",
|
||||
"compeletCount": STAFF_COMPELET_COUNT, "is_collect_info": "1",
|
||||
"operator_name": CURRENT_USER_NAME, "OPERATOR": CURRENT_USER_ID,
|
||||
"OPERAT_TIME": "@operate_time@yyyy-MM-dd HH:mm:ss",
|
||||
})
|
||||
resp = _request_retry("POST", STAFF_SAVE_URL, session, data=form, headers=CSRF_HEADERS)
|
||||
d = resp.json()
|
||||
if str(d.get("state")) != "1":
|
||||
return False, f"保存员工用工类型失败:{d.get('meg') or d}"
|
||||
|
||||
staff_code = form.get("base_code") or ""
|
||||
for i in range(5):
|
||||
time.sleep(3)
|
||||
roster = query_staff_roster(session, staff_code)
|
||||
if roster and _s(roster.get(F_HR_IDENTITY)) == target_code:
|
||||
old_name = IDENTITY_NAME_BY_CODE.get(old, old or "(空)")
|
||||
return True, f"HR用工类型已自动修正:{old_name} -> {target_name}"
|
||||
logger.info("用工类型修正复查第 %d 次未命中(延迟落库等待)", i + 1)
|
||||
return False, "保存返回成功但复查花名册用工类型未变更,请人工核实"
|
||||
|
||||
|
||||
def sync_employee_type(session, records, dry_run):
|
||||
"""④ 用工类型同步:AI表「用工类型是否调整」有合法值时,把 HR 花名册用工类型改成该值。
|
||||
|
||||
与手机号口径一致——只有 HR 当前值与 AI 表目标值不一致时才改;空、0、#N/A、
|
||||
数字等公式残留一律跳过(不调整)。值不在 HR 用工类型字典内也跳过并记日志。
|
||||
"""
|
||||
todo = []
|
||||
for rec in records:
|
||||
f = rec.get("fields") or {}
|
||||
raw = _s(f.get(F_EMP_TYPE))
|
||||
if not raw:
|
||||
continue
|
||||
key = unicodedata.normalize("NFKC", raw).strip()
|
||||
if key in IDENTITY_NO_CHANGE:
|
||||
continue
|
||||
code = _norm_code(f.get(F_CODE))
|
||||
name = _s(f.get(F_NAME))
|
||||
target_code = IDENTITY_CODE_BY_NAME.get(key)
|
||||
if not target_code and key in IDENTITY_NAME_BY_CODE: # AI 表直接填 code 也接受
|
||||
target_code = key
|
||||
if not target_code:
|
||||
logger.warning("【%s】用工类型是否调整=「%s」不是合法用工类型,跳过(不改花名册)",
|
||||
code, raw)
|
||||
continue
|
||||
if not code:
|
||||
logger.warning("【%s】用工类型是否调整=「%s」但工号为空,跳过", name, raw)
|
||||
continue
|
||||
todo.append((rec, code, name, target_code))
|
||||
|
||||
results = []
|
||||
if not todo:
|
||||
logger.info("④ 用工类型同步:无待调整记录")
|
||||
return results
|
||||
# 同一工号在 AI 表可能有多条批次行:目标值冲突时不做任何修改,避免改错
|
||||
targets = {}
|
||||
for _, code, _, target_code in todo:
|
||||
targets.setdefault(code, set()).add(target_code)
|
||||
conflicted = {c for c, s in targets.items() if len(s) > 1}
|
||||
for c in sorted(conflicted):
|
||||
logger.warning("【%s】AI表多条记录的用工类型调整值不一致(%s),本次跳过不改花名册",
|
||||
c, "/".join(sorted(IDENTITY_NAME_BY_CODE.get(x, x) for x in targets[c])))
|
||||
if conflicted:
|
||||
todo = [t for t in todo if t[1] not in conflicted]
|
||||
if not todo:
|
||||
return results
|
||||
logger.info("④ 用工类型同步:%d 条有合法调整值,逐条核对花名册", len(todo))
|
||||
for rec, code, name, target_code in todo:
|
||||
target_name = IDENTITY_NAME_BY_CODE.get(target_code, target_code)
|
||||
r = {"record_id": rec.get("id"), "code": code, "name": name, "status": "跳过",
|
||||
"msg": "", "backfill": None, "prefill": None, "alert": False}
|
||||
roster = query_staff_roster(session, code)
|
||||
if not roster:
|
||||
r["status"], r["msg"] = "异常", f"花名册查无此人,无法同步用工类型(AI表={target_name})"
|
||||
logger.error("【%s】%s", code, r["msg"])
|
||||
results.append(r)
|
||||
continue
|
||||
cur = _s(roster.get(F_HR_IDENTITY))
|
||||
if cur == target_code:
|
||||
logger.info("【%s】用工类型与AI表一致(%s),无需调整", code, target_name)
|
||||
continue
|
||||
if dry_run:
|
||||
r["status"] = "试算"
|
||||
r["msg"] = (f"[试算] 将把HR用工类型 "
|
||||
f"{IDENTITY_NAME_BY_CODE.get(cur, cur or '(空)')} 改为 {target_name}")
|
||||
logger.info("【%s】%s", code, r["msg"])
|
||||
results.append(r)
|
||||
continue
|
||||
base_id = roster.get("hr_staff_base.base_id") or ""
|
||||
if not base_id:
|
||||
r["status"], r["msg"] = "异常", "花名册缺少 base_id,无法同步用工类型"
|
||||
logger.error("【%s】%s", code, r["msg"])
|
||||
results.append(r)
|
||||
continue
|
||||
ok, note = _fix_hr_identity(session, base_id, target_code, target_name)
|
||||
r["status"] = "已同步" if ok else "异常"
|
||||
r["msg"] = note
|
||||
(logger.info if ok else logger.error)("【%s】用工类型同步:%s", code, note)
|
||||
results.append(r)
|
||||
return results
|
||||
|
||||
|
||||
@@ -630,6 +643,13 @@ def renew_contract(session, ai, dry_run):
|
||||
if diffs:
|
||||
return "异常", ("防重命中但待生效合同与AI表信息不一致:"
|
||||
+ ";".join(diffs) + ",报异常待人工核对")
|
||||
# 历史错推提示(不改判重结论):2026-11-09 前 new_sign_way 复制原合同值,
|
||||
# 首次续签的人会被记成新签(台账 sign_type=ext_1)
|
||||
w_sign_way = _s(latest_w.get("hr_staff_contract.sign_way"))
|
||||
if w_sign_way and w_sign_way != RENEW_SIGN_WAY:
|
||||
logger.warning("【%s】待生效合同行签订方式 sign_way=%s(非续签 %s),"
|
||||
"疑为历史版本按原合同值写入,请在HR台账人工核对签署类型",
|
||||
code, w_sign_way, RENEW_SIGN_WAY)
|
||||
push_time = _s(latest_w.get("hr_staff_contract_ext.ext_push_time"))
|
||||
if not push_time:
|
||||
return "异常", ("防重命中且合同信息与AI表一致,但待生效合同行无电子签推送时间"
|
||||
@@ -709,11 +729,17 @@ def renew_contract(session, ai, dry_run):
|
||||
r_name = ai.get("name") or "" # AI表姓名(tab行缺名时兜底)
|
||||
|
||||
# 签署单位:AI 表填了才覆盖(名->code 映射失败沿用原合同单位)
|
||||
# 2026-11-09:AI 表常用「营业执照全称」,HR 单位下拉是简称(如「重庆三十七度健康管理
|
||||
# (集团)有限公司」vs「三十七度公司」),映射必然失败;若与原合同单位营业执照名称一致
|
||||
# 说明本来就同一家 -> INFO 沿用原单位;否则保留 WARN 待人工核对。
|
||||
si_area = _rc("hr_staff_contract.si_area")
|
||||
if ai["unit"]:
|
||||
si = _unit_set_id_by_name(session, ai["unit"])
|
||||
if si:
|
||||
si_area = si
|
||||
elif _norm_name(ai["unit"]) == _norm_name(_rc("hr_contract_unit_set.ext_license_name")):
|
||||
logger.info("【%s】合同签署单位「%s」为原合同单位营业执照名称,视为一致,沿用原合同单位",
|
||||
code, ai["unit"])
|
||||
else:
|
||||
logger.warning("【%s】合同签署单位「%s」未匹配到单位 code,沿用原合同单位",
|
||||
code, ai["unit"])
|
||||
@@ -747,7 +773,7 @@ def renew_contract(session, ai, dry_run):
|
||||
"ext_seal_number": _rc("hr_contract_unit_set.ext_seal_number"),
|
||||
"new_contract_no": "",
|
||||
"contract_type_template": template_ids,
|
||||
"new_sign_way": _rc("hr_staff_contract.sign_way", "2"),
|
||||
"new_sign_way": RENEW_SIGN_WAY, # 续签固定 2(勿复制原合同值,见常量注释)
|
||||
"new_data_source": _rc("hr_staff_contract.data_source", "2"),
|
||||
"new_contract_file": "",
|
||||
"new_contract_count": "1",
|
||||
@@ -794,10 +820,20 @@ def renew_contract(session, ai, dry_run):
|
||||
return "失败", f"续签提交失败:{d.get('meg') or d}"
|
||||
|
||||
# 7) 复查:待生效合同出现该员工行(HR 落库有秒级延迟)
|
||||
# 命中后把签订方式打出来(续签应为 2),便于核对台账是否被记成新签
|
||||
for i in range(VERIFY_TIMES):
|
||||
time.sleep(VERIFY_WAIT_SEC)
|
||||
if query_wait_effect_rows(session, code):
|
||||
return "已推送", f"续签提交成功并已落库(待生效合同出现新行,contract_id={contract_id})"
|
||||
new_rows = query_wait_effect_rows(session, code)
|
||||
if new_rows:
|
||||
latest_n = max(new_rows, key=lambda r: (_to_date(
|
||||
r.get("hr_staff_contract.contract_start_date")) or datetime.min))
|
||||
sign_way = _s(latest_n.get("hr_staff_contract.sign_way")) or "?"
|
||||
new_cid = _s(latest_n.get("hr_staff_contract.contract_id")) or "?"
|
||||
logger.info("【%s】续签已落库:新合同 contract_id=%s,签订方式 sign_way=%s"
|
||||
"(续签应为 %s)", code, new_cid, sign_way, RENEW_SIGN_WAY)
|
||||
return "已推送", (f"续签提交成功并已落库(待生效合同出现新行,"
|
||||
f"新合同 contract_id={new_cid},签订方式 sign_way={sign_way};"
|
||||
f"原合同 contract_id={contract_id})")
|
||||
return "已推送", (f"续签提交接口返回成功(待生效Tab复查暂未命中,HR落库可能有延迟,"
|
||||
f"contract_id={contract_id})")
|
||||
|
||||
@@ -1009,12 +1045,12 @@ def main(dry_run=None):
|
||||
logger.info("AI表【续签名单到期跟进-月更新】共 %d 条(dry_run=%s)",
|
||||
len(records), dry_run)
|
||||
|
||||
# ④ 用工类型同步(前置):AI表「用工类型是否调整」有合法值 -> HR 花名册用工类型(不一致才改)
|
||||
if any(_s((rec.get("fields") or {}).get(F_EMP_TYPE)) for rec in records):
|
||||
if session is None:
|
||||
session = _hr_session()
|
||||
results.extend(sync_employee_type(session, records, dry_run))
|
||||
|
||||
# ④ 用工类型同步(前置):AI表「用工类型是否调整」有合法值 -> HR 花名册用工类型(不一致才改)
|
||||
if any(_s((rec.get("fields") or {}).get(F_EMP_TYPE)) for rec in records):
|
||||
if session is None:
|
||||
session = _hr_session()
|
||||
results.extend(sync_employee_type(session, records, dry_run))
|
||||
|
||||
# ① 是否续签=否 -> 人资是否推送=否
|
||||
no_rows = [{"id": rec.get("id"),
|
||||
"code": _norm_code((rec.get("fields") or {}).get(F_CODE)),
|
||||
|
||||
@@ -71,6 +71,13 @@ PASSWORD = os.getenv('oa_login_password', '')
|
||||
# OA 会话校验接口:cookies 有效时返回 JSON,失效时被重定向到登录页返回 HTML
|
||||
TODO_COUNT_URL = "https://oa.37du.co/sys/notify/sys_notify_todo/sysNotifyTodo.do"
|
||||
|
||||
# OA(蓝凌 EKP)会对缺 XHR 标记的接口请求直接返回 468(2026-11 起实测):
|
||||
# 不带 X-Requested-With / Referer 的 sysNotifyTodo.do 一律 468,带任一即正常返回 JSON。
|
||||
VALIDATE_HEADERS = {
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
"Referer": "https://oa.37du.co/sys/portal/page.jsp",
|
||||
}
|
||||
|
||||
USERNAME_INPUT = 'tag:input@name=j_username'
|
||||
PASSWORD_INPUT = 'tag:input@name=j_password'
|
||||
LOGIN_BTN = '.lui_login_button_div_c'
|
||||
@@ -135,7 +142,8 @@ def _is_oa_session_valid():
|
||||
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)
|
||||
resp = session.get(validate_url, params={"method": "sumTodoCount"},
|
||||
headers=VALIDATE_HEADERS, timeout=15)
|
||||
if resp.status_code != 200:
|
||||
print(f"API 校验 cookies 状态码异常:{resp.status_code}")
|
||||
return False
|
||||
|
||||
@@ -25,6 +25,8 @@
|
||||
成功 302 跳转(实测跳 "/",浏览器端再由前端跳 /sys/portal/page.jsp);
|
||||
5. GET sysNotifyTodo.do?method=sumTodoCount 校验会话有效后,cookies 落盘 oa_cookies.json
|
||||
(返回 JSON 视为有效,被重定向回登录页返回 HTML 即失效)。
|
||||
⚠ 2026-11 起该接口对缺 XHR 标记的请求返回 468,校验请求必须带
|
||||
X-Requested-With: XMLHttpRequest(或 Referer),否则登录成功也会被误判为失败。
|
||||
|
||||
配置(与 oa_login.py 一致,读项目根 .env):
|
||||
oa_login_username=用户名
|
||||
@@ -80,6 +82,16 @@ 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"
|
||||
|
||||
# OA(蓝凌 EKP)会对缺 XHR 标记的接口请求直接返回 468(2026-11 起实测):
|
||||
# 不带 X-Requested-With / Referer 的 sysNotifyTodo.do 一律 468,带任一即正常返回 JSON。
|
||||
VALIDATE_HEADERS = {
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
"Referer": BASE_URL + "/sys/portal/page.jsp",
|
||||
}
|
||||
# OA 网关偶发 468(风控瞬时拦截,前端 JS 未定义该状态码、非会话失效信号,数秒后自愈):
|
||||
# 退避重试一次到两次,避免把「登录其实成功」误判成失败。
|
||||
VALIDATE_RETRY_DELAYS = (0.8, 2.0)
|
||||
|
||||
USERNAME = os.getenv('oa_login_username', '')
|
||||
PASSWORD = os.getenv('oa_login_password', '')
|
||||
|
||||
@@ -151,6 +163,20 @@ def _is_todo_count_json(resp):
|
||||
return False
|
||||
|
||||
|
||||
def _get_validate(session, validate_url):
|
||||
"""请求会话校验接口;遇 468(风控瞬时拦截)按 VALIDATE_RETRY_DELAYS 退避重试。
|
||||
返回最后一次响应,判定逻辑仍由调用方 _is_todo_count_json 统一处理。"""
|
||||
resp = None
|
||||
for delay in (0,) + VALIDATE_RETRY_DELAYS:
|
||||
if delay:
|
||||
time.sleep(delay)
|
||||
resp = session.get(validate_url, params={"method": "sumTodoCount"},
|
||||
headers=VALIDATE_HEADERS, timeout=15)
|
||||
if resp.status_code != 468:
|
||||
break
|
||||
return resp
|
||||
|
||||
|
||||
def _is_oa_session_valid():
|
||||
"""API 轻量校验 OA cookies:请求 oa_validate_url(默认 sumTodoCount 待办统计接口),
|
||||
返回 JSON 视为 cookies 有效;被重定向到登录页返回 HTML 即视为失效。
|
||||
@@ -165,10 +191,11 @@ def _is_oa_session_valid():
|
||||
"User-Agent": UA,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
session.headers.update(VALIDATE_HEADERS)
|
||||
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)
|
||||
resp = _get_validate(session, validate_url)
|
||||
if resp.status_code != 200:
|
||||
print(f"API 校验 cookies 状态码异常:{resp.status_code}")
|
||||
return False
|
||||
@@ -182,7 +209,7 @@ 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)
|
||||
resp = _get_validate(session, validate_url)
|
||||
return _is_todo_count_json(resp)
|
||||
except Exception as e:
|
||||
print(f"会话校验异常:{e}")
|
||||
|
||||
Reference in New Issue
Block a user