feat: 重构控制面安全机制与分页规范
本次提交包含多项安全加固和体验优化: 1. 分离管理密钥与传输凭证,避免持 API Token 者伪造管理员票据 2. 钉钉回调地址增加白名单校验,防止开放重定向钓鱼 3. 初始管理员密码改为随机生成并日志记录,移除硬编码 123456 4. 新增登录防爆破计数表,支持 MySQL 多 worker 共享 5. 统一分页规范,新增 usePagedList composable 和 PagerBar 组件 6. 控制面 CORS 收敛为白名单,避免公网环境下任意站点跨域 7. 插件管理、凭证管理等列表接口支持分页和搜索 8. 强制初始密码修改,未改密前禁止使用管理功能 9. 定时任务触发被拒日志节流,避免授权失效时刷屏 10. 健康检查接口移除环境信息泄露,返回固定响应
This commit is contained in:
@@ -1 +1,74 @@
|
||||
<div class="zlq-login-form relative w-full px-5 py-8 mx-auto my-auto rounded-md shadow-md xl:ml-16 xl:bg-transparent sm:px-8 xl:p-4 xl:shadow-none sm:w-3/4 lg:w-2/4 xl:w-auto enter-x"><h2 class="mb-3 text-2xl font-bold text-center xl:text-3xl enter-x xl:text-left enter-x">登录</h2><form class="ant-form ant-form-horizontal p-4 enter-x"><div class="ant-row ant-form-item enter-x" style="row-gap: 0px;"><!----><div class="ant-col ant-form-item-control"><div class="ant-form-item-control-input"><div class="ant-form-item-control-input-content"><input placeholder="账号" type="text" id="form_item_account" class="ant-input ant-input-lg fix-auto-fill" value=""></div><!----></div><!----><!----></div></div><div class="ant-row ant-form-item enter-x" style="row-gap: 0px;"><!----><div class="ant-col ant-form-item-control"><div class="ant-form-item-control-input"><div class="ant-form-item-control-input-content"><span class="ant-input-affix-wrapper ant-input-affix-wrapper-lg ant-input-password ant-input-password-large"><!----><input placeholder="密码" id="form_item_password" type="password" class="ant-input ant-input-lg"><span class="ant-input-suffix"><!----><!----><span role="img" aria-label="eye-invisible" tabindex="-1" class="anticon anticon-eye-invisible ant-input-password-icon"><svg focusable="false" class="" data-icon="eye-invisible" width="1em" height="1em" fill="currentColor" aria-hidden="true" viewBox="64 64 896 896"><path d="M942.2 486.2Q889.47 375.11 816.7 305l-50.88 50.88C807.31 395.53 843.45 447.4 874.7 512 791.5 684.2 673.4 766 512 766q-72.67 0-133.87-22.38L323 798.75Q408 838 512 838q288.3 0 430.2-300.3a60.29 60.29 0 000-51.5zm-63.57-320.64L836 122.88a8 8 0 00-11.32 0L715.31 232.2Q624.86 186 512 186q-288.3 0-430.2 300.3a60.3 60.3 0 000 51.5q56.69 119.4 136.5 191.41L112.48 835a8 8 0 000 11.31L155.17 889a8 8 0 0011.31 0l712.15-712.12a8 8 0 000-11.32zM149.3 512C232.6 339.8 350.7 258 512 258c54.54 0 104.13 9.36 149.12 28.39l-70.3 70.3a176 176 0 00-238.13 238.13l-83.42 83.42C223.1 637.49 183.3 582.28 149.3 512zm246.7 0a112.11 112.11 0 01146.2-106.69L401.31 546.2A112 112 0 01396 512z"></path><path d="M508 624c-3.46 0-6.87-.16-10.25-.47l-52.82 52.82a176.09 176.09 0 00227.42-227.42l-52.82 52.82c.31 3.38.47 6.79.47 10.25a111.94 111.94 0 01-112 112z"></path></svg></span></span></span></div><!----></div><!----><!----></div></div><div class="ant-row enter-x" style="row-gap: 0px;"><div class="ant-col ant-col-12"><div class="ant-row ant-form-item" style="row-gap: 0px;"><!----><div class="ant-col ant-form-item-control"><div class="ant-form-item-control-input"><div class="ant-form-item-control-input-content"><label class="ant-checkbox-wrapper"><span class="ant-checkbox"><input type="checkbox" class="ant-checkbox-input"><span class="ant-checkbox-inner"></span></span><span>记住我</span></label></div><!----></div><!----><!----></div></div></div><div class="ant-col ant-col-12"><div class="ant-row ant-form-item" style="text-align: right; row-gap: 0px;"><!----><div class="ant-col ant-form-item-control"><div class="ant-form-item-control-input"><div class="ant-form-item-control-input-content"><!----><button class="ant-btn ant-btn-link ant-btn-sm" type="button"><!----><span>忘记密码?</span></button></div><!----></div><!----><!----></div></div></div></div><div class="ant-row ant-form-item enter-x" style="row-gap: 0px;"><!----><div class="ant-col ant-form-item-control"><div class="ant-form-item-control-input"><div class="ant-form-item-control-input-content"><button class="ant-btn ant-btn-primary ant-btn-lg ant-btn-block" type="button"><!----><span>登 录</span></button></div><!----></div><!----><!----></div></div><div class="ant-divider ant-divider-horizontal ant-divider-with-text ant-divider-with-text-center enter-x" role="separator"><span class="ant-divider-inner-text">其他登录方式</span></div><div class="flex justify-center enter-x zlq-login-sign-in-way"><span role="img" aria-label="dingding" tabindex="-1" class="anticon anticon-dingding"><svg focusable="false" class="" data-icon="dingding" width="1em" height="1em" fill="currentColor" aria-hidden="true" viewBox="64 64 896 896"><path d="M573.7 252.5C422.5 197.4 201.3 96.7 201.3 96.7c-15.7-4.1-17.9 11.1-17.9 11.1-5 61.1 33.6 160.5 53.6 182.8 19.9 22.3 319.1 113.7 319.1 113.7S326 357.9 270.5 341.9c-55.6-16-37.9 17.8-37.9 17.8 11.4 61.7 64.9 131.8 107.2 138.4 42.2 6.6 220.1 4 220.1 4s-35.5 4.1-93.2 11.9c-42.7 5.8-97 12.5-111.1 17.8-33.1 12.5 24 62.6 24 62.6 84.7 76.8 129.7 50.5 129.7 50.5 33.3-10.7 61.4-18.5 85.2-24.2L565 743.1h84.6L603 928l205.3-271.9H700.8l22.3-38.7c.3.5.4.8.4.8S799.8 496.1 829 433.8l.6-1h-.1c5-10.8 8.6-19.7 10-25.8 17-71.3-114.5-99.4-265.8-154.5z"></path></svg></span></div></form><!----><!----></div>
|
||||
https://cus.allinpay.com/login
|
||||
<div class="tab-content" id="loginTabContent">
|
||||
<!-- 账号登录 -->
|
||||
<div class="tab-pane fade active show" id="account" role="tabpanel">
|
||||
<form id="accountForm" action="/login" method="post" accept-charset="utf-8" style="width: 331.25px; min-height: 349px;">
|
||||
<div class="form-group" id="userid_div">
|
||||
<label class="label-username" for="userid"></label>
|
||||
<input type="text" class="form-control" id="userid" name="userid" placeholder="请输入登录帐号">
|
||||
<div class="invalid-feedback" id="userid_err"></div>
|
||||
</div>
|
||||
<div class="form-group" id="password_div">
|
||||
<label class="label-psw" for="password"></label>
|
||||
<input type="password" class="form-control usableClick" id="password" placeholder="请输入登录密码" readonly="readonly" onfocus="this.removeAttribute('readonly'); this.classList.remove('usableClick');">
|
||||
<input type="password" id="encpassword" name="encpassword" style="display: none;" readonly="readonly" class="usableClick" onfocus="this.removeAttribute('readonly'); this.classList.remove('usableClick');">
|
||||
<div class="invalid-feedback" id="password_err"></div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="label-vCode" for="captcha"></label>
|
||||
<div class="input-group" id="captcha_div">
|
||||
<input type="text" class="form-control usableClick" id="captcha" name="cuserrorCode" placeholder="请输入验证码" readonly="readonly" onfocus="this.removeAttribute('readonly'); this.classList.remove('usableClick');">
|
||||
<div class="invalid-feedback" id="captcha_err"></div>
|
||||
<div class="input-group-append">
|
||||
<img src="/getvalidCode?type=cuserrorCode" dataflag="cuserrorCode" onclick="cusjsUtil.changeCode(this)" alt="验证码" class="captcha-img">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" class="btn btn-primary btn-block btn-lg" onclick="javascript:valandsubmit(this);">登录</button>
|
||||
</form>
|
||||
<div class="tab-pane__bottom">
|
||||
<a href="javascript:void(0)" class="text-muted btnFirstLogin_a">创建账号</a>
|
||||
<a href="javascript:void(0)" class="text-muted btnForgetPsw_a">忘记密码</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 验证码登录 -->
|
||||
<div class="tab-pane fade" id="sms" role="tabpanel">
|
||||
<form id="smsForm" style="width: 331.25px; min-height: 349px;">
|
||||
<div class="form-group" id="phone_div">
|
||||
<label class="label-phonenumber" for="phone"></label>
|
||||
<input type="tel" class="form-control" id="phone" placeholder="请输入手机号">
|
||||
<input type="hidden" id="hid_uifMobile" readonly="readonly" class="usableClick" onfocus="this.removeAttribute('readonly'); this.classList.remove('usableClick');">
|
||||
<div class="invalid-feedback" id="phone_err"></div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="label-vCode" for="captcha"></label>
|
||||
<div class="input-group" id="phone_captcha_div">
|
||||
<input type="text" class="form-control usableClick" id="phone_captcha" name="cuserrorCode" placeholder="请输入验证码" readonly="readonly" onfocus="this.removeAttribute('readonly'); this.classList.remove('usableClick');">
|
||||
<div class="invalid-feedback" id="phone_captcha_err"></div>
|
||||
<div class="input-group-append">
|
||||
<img src="/getvalidCode?type=mobileloginCode" dataflag="mobileloginCode" id="phone_captcha_id" onclick="cusjsUtil.changeCode(this)" alt="验证码" class="captcha-img">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group" id="smsCode_div">
|
||||
<label class="label-vCode" for="smsCode"></label>
|
||||
<div class="input-group">
|
||||
<input type="text" class="form-control" id="smsCode" placeholder="请输入验证码">
|
||||
<div class="invalid-feedback" id="smsCode_err"></div>
|
||||
<div class="input-group-append">
|
||||
<button class="btn btn-smsCode" type="button" id="getSmsCode">获取验证码</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" class="btn btn-primary btn-block btn-lg" onclick="javascript:valandsubmit(this);">登录</button>
|
||||
<div class="tab-pane__tips">
|
||||
<i class="icon-warning"></i><p class="text-muted">请先绑定用户后,再使用快捷登录</p><a href="javascript:void(0)" onclick="bindMobie('')">去绑定</a>
|
||||
</div>
|
||||
</form>
|
||||
<div class="tab-pane__bottom">
|
||||
<a href="javascript:void(0)" class="text-muted btnFirstLogin_a">创建账号</a>
|
||||
<a href="javascript:void(0)" class="text-muted btnForgetPsw_a">忘记密码</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
Binary file not shown.
@@ -14,10 +14,11 @@ from fastapi import APIRouter, File, Header, HTTPException, Query, UploadFile
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
from controlplane import config, schemas
|
||||
from controlplane.core.auth import _require_admin, _resolve_login
|
||||
from controlplane.core.auth import _identity, _require_admin, _revoke_account_tokens
|
||||
from controlplane.core.crypto import _hash_password
|
||||
from controlplane.core.db import _audit, _db, _now
|
||||
from controlplane.core.notify import notify_account_created
|
||||
from controlplane.core.paging import count_rows, page_bounds
|
||||
from controlplane.core.pkgutil import (
|
||||
_SAFE_NAME_RE, _extract_manifest, _load_manifest, _prune_versions,
|
||||
_validate_pkg_zip, _version_key,
|
||||
@@ -28,15 +29,24 @@ router = APIRouter()
|
||||
|
||||
# ==================== 账号 CRUD(统一账户,含部门;仅管理员可操作) ====================
|
||||
@router.get("/api/admin/accounts")
|
||||
def admin_accounts(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
def admin_accounts(page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, ge=1, le=1000),
|
||||
q: str = Query(default=""),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""全部账号(含部门/管理员标记/已授权插件/可登录平台)。"""
|
||||
"""账号列表(统一分页 + 服务端搜索 q:账号/昵称/部门模糊,含已授权插件/可登录平台)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
limit, offset = page_bounds(page, page_size)
|
||||
where, args = "", []
|
||||
if q.strip():
|
||||
where = " WHERE (account LIKE %s OR nickname LIKE %s OR dept LIKE %s)"
|
||||
args = ["%" + q.strip() + "%"] * 3
|
||||
with _db() as conn:
|
||||
total = count_rows(conn, "SELECT COUNT(*) AS c FROM accounts" + where, args)
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT id, account, is_admin, dept, nickname, dingtalk_uid, must_change_pwd, "
|
||||
" avatar, status, created_at "
|
||||
"FROM accounts ORDER BY id")]
|
||||
"FROM accounts" + where + " ORDER BY id LIMIT %s OFFSET %s", args + [limit, offset])]
|
||||
for a in rows:
|
||||
a["plugins"] = [dict(r)["plugin_id"] for r in conn.execute(
|
||||
"SELECT plugin_id FROM account_plugins WHERE account = %s", (a["account"],))]
|
||||
@@ -45,7 +55,7 @@ def admin_accounts(x_admin_token: str = Header(default="", alias="X-Admin-Token"
|
||||
(a["account"],))]
|
||||
a["platforms"] = [dict(r)["platform_id"] for r in conn.execute(
|
||||
"SELECT platform_id FROM account_platforms WHERE account = %s", (a["account"],))]
|
||||
return {"accounts": rows}
|
||||
return {"items": rows, "total": total}
|
||||
|
||||
|
||||
@router.post("/api/admin/account")
|
||||
@@ -53,10 +63,12 @@ def admin_account_create(a: schemas.AccountCreateIn,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""新建账号:密码必填,可指定部门/昵称/是否管理员。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
account = a.account.strip()
|
||||
if not account or not a.password:
|
||||
raise HTTPException(400, "account 与 password 必填")
|
||||
if len(a.password) < 8:
|
||||
raise HTTPException(400, "密码至少 8 位")
|
||||
with _db() as conn:
|
||||
exists = conn.execute("SELECT 1 FROM accounts WHERE account = %s", (account,)).fetchone()
|
||||
if exists:
|
||||
@@ -70,6 +82,8 @@ def admin_account_create(a: schemas.AccountCreateIn,
|
||||
conn.commit()
|
||||
# 钉钉工作通知(异步,失败不阻断建号):新用户收账号密码(按昵称解析),管理员收权限开通提醒
|
||||
notify_account_created(account, (a.nickname or "").strip(), a.password, source="管理台")
|
||||
_audit(login, "account-create", account,
|
||||
f"is_admin={int(a.is_admin)}, dept={(a.dept or '').strip()}")
|
||||
return {"ok": True, "account": account, "dept": (a.dept or "").strip(),
|
||||
"nickname": (a.nickname or "").strip(), "is_admin": a.is_admin}
|
||||
|
||||
@@ -106,6 +120,12 @@ def admin_account_update(a: schemas.AccountUpdateIn,
|
||||
conn.execute("UPDATE accounts SET status = %s WHERE account = %s",
|
||||
(int(bool(a.status)), account))
|
||||
conn.commit()
|
||||
if a.status is not None and not a.status:
|
||||
# 停用账号即吊销其云令牌,防止残留会话继续使用(P1 安全债)
|
||||
_revoke_account_tokens(account)
|
||||
_audit(login, "account-update", account,
|
||||
f"dept={a.dept is not None}, nickname={a.nickname is not None}, "
|
||||
f"is_admin={a.is_admin is not None}, status={a.status is not None}")
|
||||
return {"ok": True, "account": account}
|
||||
|
||||
|
||||
@@ -114,10 +134,12 @@ def admin_account_reset(r: schemas.AccountResetIn,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""管理员重置任意账号密码(无需原密码)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
account = r.account.strip()
|
||||
if not account or not r.new_password:
|
||||
raise HTTPException(400, "account 与新密码必填")
|
||||
if len(r.new_password) < 8:
|
||||
raise HTTPException(400, "新密码至少 8 位")
|
||||
with _db() as conn:
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = %s", (account,)).fetchone():
|
||||
raise HTTPException(400, f"账号 {account} 不存在")
|
||||
@@ -125,6 +147,7 @@ def admin_account_reset(r: schemas.AccountResetIn,
|
||||
conn.execute("UPDATE accounts SET password_hash = %s, salt = %s WHERE account = %s",
|
||||
(_hex, _salt, account))
|
||||
conn.commit()
|
||||
_audit(login, "account-reset-pwd", account)
|
||||
return {"ok": True, "account": account}
|
||||
|
||||
|
||||
@@ -145,6 +168,9 @@ def admin_account_delete(d: schemas.AccountDelIn,
|
||||
# account_plugins / account_platforms 由外键 ON DELETE CASCADE 级联清理
|
||||
conn.execute("DELETE FROM accounts WHERE account = %s", (account,))
|
||||
conn.commit()
|
||||
# 删除账号即吊销其云令牌(防残留令牌继续解析,P1 安全债)
|
||||
_revoke_account_tokens(account)
|
||||
_audit(login, "account-delete", account)
|
||||
return {"ok": True, "account": account}
|
||||
|
||||
|
||||
@@ -155,17 +181,21 @@ _AVATAR_EXT = {".jpg", ".jpeg", ".png", ".gif", ".webp"}
|
||||
@router.post("/api/admin/avatar")
|
||||
def admin_avatar_upload(file: UploadFile = File(...),
|
||||
account: str = Query(...),
|
||||
authorization: str = Header(default="", alias="Authorization"),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
|
||||
"""上传账号头像:自服务传自己;管理员可传任意账号。覆盖旧头像。"""
|
||||
try:
|
||||
login = _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||||
login = _identity(authorization=authorization, x_admin_token=x_admin_token,
|
||||
x_api_token=x_api_token, x_admin_user=x_admin_user)
|
||||
except Exception:
|
||||
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||||
account = account.strip()
|
||||
if not account:
|
||||
raise HTTPException(400, "account 不能为空")
|
||||
if not _SAFE_NAME_RE.match(account):
|
||||
raise HTTPException(400, "account 含非法字符(仅允许字母数字及 . _ -,防止文件名穿越)")
|
||||
if account != login:
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
ext = Path(file.filename or "").suffix.lower()
|
||||
@@ -216,7 +246,7 @@ def admin_grant(g: schemas.GrantIn,
|
||||
MySQL 版合并表:权限位(can_download/can_run)即存在 account_plugins 本身,
|
||||
不再有独立 plugin_grants 表;撤销即删除 account_plugins 行。
|
||||
"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
account = g.account.strip()
|
||||
plugin_id = g.plugin_id.strip()
|
||||
if not account or not plugin_id:
|
||||
@@ -237,8 +267,9 @@ def admin_grant(g: schemas.GrantIn,
|
||||
conn.execute("DELETE FROM account_plugins WHERE account = %s AND plugin_id = %s",
|
||||
(account, plugin_id))
|
||||
conn.commit()
|
||||
_audit(account, "grant" if g.granted else "revoke-grant", plugin_id,
|
||||
f"can_download={g.can_download},can_run={g.can_run}")
|
||||
# 审计 actor 用操作者 login(可追溯"谁操作的"),target 为插件、detail 记录被授权账号
|
||||
_audit(login, "grant" if g.granted else "revoke-grant", plugin_id,
|
||||
f"account={account},can_download={g.can_download},can_run={g.can_run}")
|
||||
return {"ok": True, "account": account, "plugin_id": plugin_id, "granted": g.granted}
|
||||
|
||||
|
||||
@@ -247,7 +278,7 @@ def admin_platform_grant(g: schemas.PlatformGrantIn,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""授予或撤销某账号对某平台的登录权限。granted=True 授,False 撤。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
account = g.account.strip()
|
||||
platform_id = g.platform_id.strip()
|
||||
if not account or not platform_id:
|
||||
@@ -263,6 +294,8 @@ def admin_platform_grant(g: schemas.PlatformGrantIn,
|
||||
conn.execute("DELETE FROM account_platforms WHERE account = %s AND platform_id = %s",
|
||||
(account, platform_id))
|
||||
conn.commit()
|
||||
# 审计 actor 用操作者 login,target 为平台、detail 记录被授权账号
|
||||
_audit(login, "grant-platform" if g.granted else "revoke-platform", platform_id, account)
|
||||
return {"ok": True, "account": account, "platform_id": platform_id, "granted": g.granted}
|
||||
|
||||
|
||||
@@ -273,7 +306,7 @@ async def admin_upload_plugin(upload: UploadFile = File(...),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""上传并发布插件包:完整性校验 → 存盘 → 登记版本 → 更新最新版 → 仅保留最近 3 个版本。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
plugin_id = plugin_id.strip()
|
||||
name = name.strip() or plugin_id
|
||||
version = version.strip()
|
||||
@@ -284,7 +317,19 @@ async def admin_upload_plugin(upload: UploadFile = File(...),
|
||||
raise HTTPException(400, "plugin_id/version 仅允许字母数字及 . _ -")
|
||||
filename = f"{plugin_id}_v{version}.zip"
|
||||
target = config.PKG_DIR / filename
|
||||
content = await upload.read()
|
||||
# 流式读取并限长(最大 200MB,与控制面插件包上限一致),避免整包先读入内存(P1 安全债)
|
||||
_MAX_PKG_BYTES = 200 * 1024 * 1024
|
||||
chunks: list[bytes] = []
|
||||
total = 0
|
||||
while True:
|
||||
chunk = await upload.read(1024 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
total += len(chunk)
|
||||
if total > _MAX_PKG_BYTES:
|
||||
raise HTTPException(413, f"插件包超过大小上限({_MAX_PKG_BYTES // (1024 * 1024)}MB)")
|
||||
chunks.append(chunk)
|
||||
content = b"".join(chunks)
|
||||
if not content:
|
||||
raise HTTPException(400, "上传内容为空")
|
||||
_validate_pkg_zip(content)
|
||||
@@ -330,6 +375,7 @@ async def admin_upload_plugin(upload: UploadFile = File(...),
|
||||
(config.PKG_DIR / fn).unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
_audit(login, "plugin-publish", plugin_id, f"version={version}, filename={filename}")
|
||||
return {"ok": True, "plugin_id": plugin_id, "version": version, "filename": filename}
|
||||
|
||||
|
||||
@@ -338,7 +384,7 @@ def admin_plugin_delete(d: schemas.PluginDelIn,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""删除插件:连带删除其全部版本记录、授权,并清理磁盘包文件。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
plugin_id = d.plugin_id.strip()
|
||||
if not plugin_id:
|
||||
raise HTTPException(400, "plugin_id 必填")
|
||||
@@ -357,6 +403,7 @@ def admin_plugin_delete(d: schemas.PluginDelIn,
|
||||
(config.PKG_DIR / fn).unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
_audit(login, "plugin-delete", plugin_id, f"files={len(files)}")
|
||||
return {"ok": True, "plugin_id": plugin_id}
|
||||
|
||||
|
||||
@@ -405,11 +452,46 @@ def admin_plugin_patch(d: schemas.PluginPatchIn,
|
||||
conn.execute(f"UPDATE plugins SET {', '.join(fields)} WHERE id = %s", vals)
|
||||
conn.commit()
|
||||
_audit("", "plugin-patch", pid, ", ".join(
|
||||
f"{k.split(' ')[0]}={v}" for k, v in zip(fields, vals[:-1])))
|
||||
f"{k.split(' ')[0]}={v}" for k, v in zip(fields, vals[:-1])) or "clear_force")
|
||||
return {"ok": True, "plugin_id": pid}
|
||||
|
||||
|
||||
# ==================== 看板 / 审计 / 运行记录 ====================
|
||||
@router.get("/api/admin/plugins")
|
||||
def admin_plugins(page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, ge=1, le=1000),
|
||||
q: str = Query(default=""),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""插件列表(统一分页 + 服务端搜索 q:ID/名称模糊;含状态/版本/强制更新/能力声明/版本历史/授权账号)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
limit, offset = page_bounds(page, page_size)
|
||||
where, args = "", []
|
||||
if q.strip():
|
||||
where = " WHERE (id LIKE %s OR name LIKE %s)"
|
||||
args = ["%" + q.strip() + "%"] * 2
|
||||
with _db() as conn:
|
||||
total = count_rows(conn, "SELECT COUNT(*) AS c FROM plugins" + where, args)
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT id, name, description, category, icon, status, latest_version, "
|
||||
" force_min_version, force_deadline, manifest "
|
||||
"FROM plugins" + where + " ORDER BY id LIMIT %s OFFSET %s", args + [limit, offset])]
|
||||
for p in rows:
|
||||
m = _load_manifest(p.pop("manifest"))
|
||||
p["manifest"] = m
|
||||
p["capabilities"] = m.get("capabilities") or []
|
||||
props = (m.get("fields") or {}).get("properties") or {}
|
||||
p["field_count"] = len(props)
|
||||
p["versions"] = [dict(r) for r in conn.execute(
|
||||
"SELECT version, filename, sha256, uploaded_at FROM plugin_versions "
|
||||
"WHERE plugin_id = %s ORDER BY version", (p["id"],))]
|
||||
p["accounts"] = [dict(r) for r in conn.execute(
|
||||
"SELECT ap.account, a.nickname FROM account_plugins ap "
|
||||
"LEFT JOIN accounts a ON a.account = ap.account "
|
||||
"WHERE ap.plugin_id = %s ORDER BY ap.account", (p["id"],))]
|
||||
return {"items": rows, "total": total}
|
||||
|
||||
|
||||
@router.get("/api/admin/overview")
|
||||
def admin_overview(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
@@ -430,31 +512,54 @@ def admin_overview(x_admin_token: str = Header(default="", alias="X-Admin-Token"
|
||||
p["versions"] = [dict(r) for r in conn.execute(
|
||||
"SELECT version, filename, sha256, uploaded_at FROM plugin_versions "
|
||||
"WHERE plugin_id = %s ORDER BY version", (p["id"],))]
|
||||
p["accounts"] = [dict(r)["account"] for r in conn.execute(
|
||||
"SELECT account FROM account_plugins WHERE plugin_id = %s", (p["id"],))]
|
||||
p["grants"] = {dict(r)["account"]: {"canDownload": bool(dict(r)["can_download"]),
|
||||
"canRun": bool(dict(r)["can_run"])}
|
||||
for r in conn.execute(
|
||||
"SELECT account, can_download, can_run FROM account_plugins "
|
||||
"WHERE plugin_id = %s", (p["id"],))}
|
||||
accounts = [dict(r) for r in conn.execute(
|
||||
"SELECT id, account, is_admin, dept, nickname, avatar, status, created_at "
|
||||
"FROM accounts ORDER BY id")]
|
||||
for a in accounts:
|
||||
a["plugins"] = [dict(r)["plugin_id"] for r in conn.execute(
|
||||
"SELECT plugin_id FROM account_plugins WHERE account = %s", (a["account"],))]
|
||||
a["platforms"] = [dict(r)["platform_id"] for r in conn.execute(
|
||||
"SELECT platform_id FROM account_platforms WHERE account = %s", (a["account"],))]
|
||||
a["grants"] = {dict(r)["plugin_id"]: {"canDownload": bool(dict(r)["can_download"]),
|
||||
"canRun": bool(dict(r)["can_run"])}
|
||||
for r in conn.execute(
|
||||
"SELECT plugin_id, can_download, can_run FROM account_plugins "
|
||||
"WHERE account = %s", (a["account"],))}
|
||||
admins = [dict(r)["account"] for r in conn.execute(
|
||||
"SELECT account FROM accounts WHERE is_admin = 1 ORDER BY account")]
|
||||
return {"plugins": plugins, "accounts": accounts, "admins": admins}
|
||||
|
||||
|
||||
@router.get("/api/admin/grant_data")
|
||||
def admin_grant_data(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""授权页轻量数据:全部插件(id/name/status,一次查询无 N+1)+ 全部账号(含昵称/部门)。
|
||||
替代授权页对 /overview 全量聚合的依赖,插件/账号多时依然轻快。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
with _db() as conn:
|
||||
plugins = [dict(r) for r in conn.execute(
|
||||
"SELECT id, name, status FROM plugins ORDER BY id")]
|
||||
accounts = [dict(r) for r in conn.execute(
|
||||
"SELECT account, nickname, dept, status FROM accounts "
|
||||
"WHERE status = 1 ORDER BY account")]
|
||||
return {"plugins": plugins, "accounts": accounts}
|
||||
|
||||
|
||||
@router.get("/api/admin/account_grants")
|
||||
def admin_account_grants(account: str = Query(default=""),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""某账号的现有授权明细:已授权插件(含 can_run/can_download)+ 已授权平台。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
account = account.strip()
|
||||
with _db() as conn:
|
||||
grants = [dict(r) for r in conn.execute(
|
||||
"SELECT plugin_id, can_run, can_download FROM account_plugins "
|
||||
"WHERE account = %s ORDER BY plugin_id", (account,))]
|
||||
platforms = [dict(r)["platform_id"] for r in conn.execute(
|
||||
"SELECT platform_id FROM account_platforms "
|
||||
"WHERE account = %s ORDER BY platform_id", (account,))]
|
||||
return {
|
||||
"plugins": [{"plugin_id": g["plugin_id"],
|
||||
"canRun": bool(g["can_run"]),
|
||||
"canDownload": bool(g["can_download"])} for g in grants],
|
||||
"platforms": platforms,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/api/admin/stats")
|
||||
def admin_stats(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
@@ -520,18 +625,17 @@ def admin_stats(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
"WHERE status = 'start' AND account <> '' GROUP BY account "
|
||||
"ORDER BY runs DESC LIMIT 8")]
|
||||
|
||||
# 最近运行列表
|
||||
recent = [dict(r) for r in conn.execute(
|
||||
"SELECT at, account, plugin_id AS pluginId, version, status, msg, duration_sec AS durationSec "
|
||||
"FROM runtime_reports WHERE status <> 'start' "
|
||||
"ORDER BY id DESC LIMIT 20")]
|
||||
# 活跃用户排行
|
||||
top_users = [{"account": r["account"], "runs": int(r["runs"])}
|
||||
for r in conn.execute(
|
||||
"SELECT account, COUNT(*) AS runs FROM runtime_reports "
|
||||
"WHERE status = 'start' AND account <> '' GROUP BY account "
|
||||
"ORDER BY runs DESC LIMIT 8")]
|
||||
|
||||
nick = {dict(r)["account"]: dict(r)["nickname"] for r in conn.execute(
|
||||
"SELECT account, nickname FROM accounts")}
|
||||
for tu in top_users:
|
||||
tu["nickname"] = nick.get(tu["account"], "")
|
||||
for rc in recent:
|
||||
rc["nickname"] = nick.get(rc.get("account", ""), "")
|
||||
|
||||
now_day = datetime.now().strftime("%Y-%m-%d")
|
||||
return {
|
||||
@@ -543,56 +647,107 @@ def admin_stats(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
"failed": int(runs["failed"] or 0), "durationSec": int(runs["duration_sec"] or 0),
|
||||
"activeUsers": int(runs["active_users"] or 0), "activePlugins": int(runs["active_plugins"] or 0)},
|
||||
"trend": trend, "topPlugins": top_plugins, "topUsers": top_users,
|
||||
"recent": recent, "today": now_day,
|
||||
"today": now_day,
|
||||
}
|
||||
|
||||
|
||||
# ==================== 审计 / 运行上报(统一分页 + 服务端筛选) ====================
|
||||
def _audit_where(action: str, q: str) -> tuple[str, list]:
|
||||
"""审计筛选条件:action 精确 + q 模糊(账号/对象/详情)。"""
|
||||
where, args = [], []
|
||||
if action.strip():
|
||||
where.append("action = %s")
|
||||
args.append(action.strip())
|
||||
if q.strip():
|
||||
where.append("(account LIKE %s OR target LIKE %s OR detail LIKE %s)")
|
||||
args += ["%" + q.strip() + "%"] * 3
|
||||
return (" WHERE " + " AND ".join(where)) if where else "", args
|
||||
|
||||
|
||||
def _report_where(status: str, q: str) -> tuple[str, list]:
|
||||
"""运行上报筛选条件:status 支持逗号分隔多值(如 done,success)+ q 模糊(账号/设备/插件/消息)。"""
|
||||
where, args = [], []
|
||||
if status.strip():
|
||||
vals = [s.strip() for s in status.split(",") if s.strip()]
|
||||
if len(vals) == 1:
|
||||
where.append("status = %s")
|
||||
args.append(vals[0])
|
||||
elif len(vals) > 1:
|
||||
where.append("status IN (%s)" % ", ".join(["%s"] * len(vals)))
|
||||
args += vals
|
||||
if q.strip():
|
||||
where.append("(account LIKE %s OR device_id LIKE %s OR plugin_id LIKE %s OR msg LIKE %s)")
|
||||
args += ["%" + q.strip() + "%"] * 4
|
||||
return (" WHERE " + " AND ".join(where)) if where else "", args
|
||||
|
||||
|
||||
@router.get("/api/admin/audit")
|
||||
def admin_audit(limit: int = Query(default=200, ge=1, le=1000),
|
||||
def admin_audit(page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, ge=1, le=1000),
|
||||
action: str = Query(default=""),
|
||||
q: str = Query(default=""),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""审计日志(最新在前,分页取 limit 条)。"""
|
||||
"""审计日志(统一分页 + 服务端筛选:action 操作类型、q 账号/对象/详情关键字,today 今日条数)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
limit, offset = page_bounds(page, page_size)
|
||||
where, args = _audit_where(action, q)
|
||||
with _db() as conn:
|
||||
total = count_rows(conn, "SELECT COUNT(*) AS c FROM audit_logs" + where, args)
|
||||
today = count_rows(conn, "SELECT COUNT(*) AS c FROM audit_logs WHERE at >= CURDATE()")
|
||||
nick = {dict(r)["account"]: dict(r)["nickname"] for r in conn.execute(
|
||||
"SELECT account, nickname FROM accounts")}
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT id, account, action, target, detail, at FROM audit_logs "
|
||||
"ORDER BY id DESC LIMIT %s", (limit,))]
|
||||
"SELECT id, account, action, target, detail, at FROM audit_logs" + where +
|
||||
" ORDER BY id DESC LIMIT %s OFFSET %s", args + [limit, offset])]
|
||||
for r in rows:
|
||||
r["nickname"] = nick.get(r["account"], "")
|
||||
return {"auditlogs": rows}
|
||||
return {"items": rows, "total": total, "today": today}
|
||||
|
||||
|
||||
@router.get("/api/admin/reports")
|
||||
def admin_reports(limit: int = Query(default=200, ge=1, le=1000),
|
||||
def admin_reports(page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, ge=1, le=1000),
|
||||
status: str = Query(default=""),
|
||||
q: str = Query(default=""),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""运行上报记录(最新在前)。"""
|
||||
"""运行上报记录(统一分页 + 服务端筛选:status 状态、q 账号/设备/插件/消息,today 今日条数)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
limit, offset = page_bounds(page, page_size)
|
||||
where, args = _report_where(status, q)
|
||||
with _db() as conn:
|
||||
total = count_rows(conn, "SELECT COUNT(*) AS c FROM runtime_reports" + where, args)
|
||||
today = count_rows(conn, "SELECT COUNT(*) AS c FROM runtime_reports WHERE at >= CURDATE()")
|
||||
failed = count_rows(conn, "SELECT COUNT(*) AS c FROM runtime_reports "
|
||||
"WHERE status IN ('error','failed')")
|
||||
nick = {dict(r)["account"]: dict(r)["nickname"] for r in conn.execute(
|
||||
"SELECT account, nickname FROM accounts")}
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT id, account, device_id, plugin_id, version, status, msg, duration_sec, at "
|
||||
"FROM runtime_reports ORDER BY id DESC LIMIT %s", (limit,))]
|
||||
"SELECT id, account, device_id AS deviceId, plugin_id AS pluginId, version, status, msg, "
|
||||
"duration_sec AS durationSec, at "
|
||||
"FROM runtime_reports" + where + " ORDER BY id DESC LIMIT %s OFFSET %s",
|
||||
args + [limit, offset])]
|
||||
for r in rows:
|
||||
r["nickname"] = nick.get(r["account"], "")
|
||||
return {"reports": rows}
|
||||
return {"items": rows, "total": total, "today": today, "failed": failed}
|
||||
|
||||
|
||||
@router.get("/api/admin/devices")
|
||||
def admin_devices(limit: int = Query(default=200, ge=1, le=1000),
|
||||
def admin_devices(page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, ge=1, le=1000),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""执行机设备列表(按最近心跳倒序):环境信息 + Chrome 检测结果。"""
|
||||
"""执行机设备列表(统一分页,按最近心跳倒序):环境信息 + Chrome 检测结果。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
limit, offset = page_bounds(page, page_size)
|
||||
with _db() as conn:
|
||||
total = count_rows(conn, "SELECT COUNT(*) AS c FROM devices")
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT device_id, account, hostname, os, ip, chrome_installed, chrome_version, "
|
||||
" chrome_ok, last_seen, status, created_at, updated_at "
|
||||
"FROM devices ORDER BY last_seen DESC LIMIT %s", (limit,))]
|
||||
return {"devices": rows}
|
||||
"FROM devices ORDER BY last_seen DESC LIMIT %s OFFSET %s", (limit, offset))]
|
||||
return {"items": rows, "total": total}
|
||||
|
||||
|
||||
@router.post("/api/admin/shell-release")
|
||||
@@ -606,7 +761,7 @@ async def admin_shell_release(upload: UploadFile = File(...),
|
||||
|
||||
供 agent CLI / 管理端从任意机器上传壳子安装包,执行机据此自动下载升级。
|
||||
"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
version = version.strip()
|
||||
if not version:
|
||||
raise HTTPException(400, "version 不能为空")
|
||||
@@ -614,7 +769,19 @@ async def admin_shell_release(upload: UploadFile = File(...),
|
||||
raise HTTPException(400, "version 仅允许字母数字及 . _ -")
|
||||
config.SHELL_DIR.mkdir(parents=True, exist_ok=True)
|
||||
filename = f"setup-37du-host-{version}.exe"
|
||||
content = await upload.read()
|
||||
# 流式读取并限长(壳子安装包上限 1GB,防磁盘/内存耗尽,P1 安全债)
|
||||
_MAX_SHELL_BYTES = 1024 * 1024 * 1024
|
||||
chunks: list[bytes] = []
|
||||
total = 0
|
||||
while True:
|
||||
chunk = await upload.read(1024 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
total += len(chunk)
|
||||
if total > _MAX_SHELL_BYTES:
|
||||
raise HTTPException(413, f"壳子安装包超过大小上限({_MAX_SHELL_BYTES // (1024 * 1024)}MB)")
|
||||
chunks.append(chunk)
|
||||
content = b"".join(chunks)
|
||||
if not content:
|
||||
raise HTTPException(400, "上传内容为空")
|
||||
if not sha256:
|
||||
@@ -624,5 +791,5 @@ async def admin_shell_release(upload: UploadFile = File(...),
|
||||
json.dumps({"version": version, "filename": filename,
|
||||
"sha256": sha256, "notes": notes},
|
||||
ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
_audit("", "shell-release", filename)
|
||||
_audit(login, "shell-release", filename)
|
||||
return {"ok": True, "version": version, "filename": filename, "sha256": sha256}
|
||||
@@ -10,8 +10,9 @@ from fastapi import APIRouter, Header, HTTPException
|
||||
|
||||
from controlplane import config, schemas
|
||||
from controlplane.core.auth import (
|
||||
_AUTH_FAILS, _auth_fail, _auth_gate, _check_token,
|
||||
_cloud_account, _issue_cloud_token, _resolve_login, _require_admin, _sign_admin_token,
|
||||
_auth_fail, _auth_gate, _auth_reset, _check_token,
|
||||
_cloud_account, _identity, _issue_cloud_token,
|
||||
_require_admin, _sign_admin_token,
|
||||
)
|
||||
from controlplane.core.crypto import _hash_password, _verify_password
|
||||
from controlplane.core.db import _db
|
||||
@@ -36,26 +37,28 @@ def admin_me(authorization: str = Header(default="", alias="Authorization"),
|
||||
身份来源依次:登录时签发的用户云令牌(Bearer) → 签名票据(X-Admin-Token) →
|
||||
底座注入的 X-Admin-User(仅当配了 CONTROLPLANE_TOKEN 时可信)。
|
||||
"""
|
||||
account = _cloud_account(authorization)
|
||||
try:
|
||||
account = _identity(authorization, x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
account = ""
|
||||
if not account:
|
||||
try:
|
||||
account = _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
account = ""
|
||||
if not account:
|
||||
return {"account": "", "is_admin": False, "dept": "", "nickname": "", "avatar": ""}
|
||||
return {"account": "", "is_admin": False, "dept": "", "nickname": "", "avatar": "",
|
||||
"must_change_pwd": False}
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT is_admin, dept, nickname, status, avatar FROM accounts WHERE account = %s",
|
||||
"SELECT is_admin, dept, nickname, status, avatar, must_change_pwd "
|
||||
"FROM accounts WHERE account = %s",
|
||||
(account,)).fetchone()
|
||||
# 账号停用:视为未登录(执行机/控制面前端据此自动登出)
|
||||
if not row or not row["status"]:
|
||||
return {"account": "", "is_admin": False, "dept": "", "nickname": "", "avatar": ""}
|
||||
return {"account": "", "is_admin": False, "dept": "", "nickname": "", "avatar": "",
|
||||
"must_change_pwd": False}
|
||||
return {"account": account,
|
||||
"is_admin": bool(row["is_admin"]),
|
||||
"dept": (row["dept"] if row else "") or "",
|
||||
"nickname": (row["nickname"] if row else "") or "",
|
||||
"avatar": (row["avatar"] if row else "") or ""}
|
||||
"avatar": (row["avatar"] if row else "") or "",
|
||||
"must_change_pwd": bool(row["must_change_pwd"])}
|
||||
|
||||
|
||||
@router.get("/api/admin/platforms")
|
||||
@@ -85,7 +88,7 @@ def admin_auth(a: schemas.AuthIn,
|
||||
raise HTTPException(401, "账号或密码错误")
|
||||
if not row["status"]:
|
||||
raise HTTPException(403, "账号已停用,请联系管理员")
|
||||
_AUTH_FAILS.pop(account, None)
|
||||
_auth_reset(account)
|
||||
_nickname = (row["nickname"] or "")
|
||||
return {"ok": True, "account": account, "is_admin": bool(row["is_admin"]),
|
||||
"dept": (row["dept"] or ""), "nickname": _nickname,
|
||||
@@ -102,14 +105,14 @@ def admin_password(p: schemas.PwdIn,
|
||||
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
|
||||
"""自助修改密码:任何统一账号可改自己的密码(需旧密码校验通过)。"""
|
||||
login = _cloud_account(authorization)
|
||||
if not login:
|
||||
try:
|
||||
login = _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||||
try:
|
||||
login = _identity(authorization, x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||||
if not p.account.strip() or not p.new_password:
|
||||
raise HTTPException(400, "account 与新密码不能为空")
|
||||
if len(p.new_password) < 8:
|
||||
raise HTTPException(400, "新密码至少 8 位")
|
||||
if p.account != login:
|
||||
raise HTTPException(403, "只能修改自己的密码")
|
||||
with _db() as conn:
|
||||
@@ -153,7 +156,7 @@ def auth_exchange(d: schemas.AuthExchangeIn) -> dict:
|
||||
# 找建账号(与 /api/admin/dingtalk/auth 同语义):已存在则同步昵称;不存在则自动建号并通知
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT nickname, status, must_change_pwd FROM accounts WHERE account = %s",
|
||||
"SELECT nickname, status, must_change_pwd, is_admin FROM accounts WHERE account = %s",
|
||||
(account,)).fetchone()
|
||||
if row:
|
||||
if not row["status"]:
|
||||
@@ -163,6 +166,7 @@ def auth_exchange(d: schemas.AuthExchangeIn) -> dict:
|
||||
(nickname, account))
|
||||
conn.commit()
|
||||
created, must_change = False, bool(row["must_change_pwd"])
|
||||
is_admin = bool(row["is_admin"])
|
||||
else:
|
||||
# 自动建号(空壳):初始密码取默认值,强制首次改密
|
||||
pwd = config.DINGTALK_DEFAULT_PASSWORD
|
||||
@@ -172,9 +176,9 @@ def auth_exchange(d: schemas.AuthExchangeIn) -> dict:
|
||||
"dingtalk_uid, must_change_pwd) VALUES (%s, %s, %s, 0, '', %s, %s, 1)",
|
||||
(account, _hex, _salt, nickname, unionid))
|
||||
conn.commit()
|
||||
created, must_change = True, True
|
||||
created, must_change, is_admin = True, True, False
|
||||
notify_account_created(account, nickname, pwd, unionid, source="钉钉扫码")
|
||||
token = _issue_cloud_token(account, nickname)
|
||||
return {"token": token, "account": account, "nickname": nickname,
|
||||
"exists": True, "created": created, "must_change_pwd": must_change,
|
||||
"is_admin": False}
|
||||
"exists": not created, "created": created, "must_change_pwd": must_change,
|
||||
"is_admin": is_admin}
|
||||
@@ -14,12 +14,13 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException
|
||||
from fastapi import APIRouter, Header, HTTPException, Query
|
||||
|
||||
from controlplane import schemas
|
||||
from controlplane.core.auth import _cloud_account, _resolve_login, _require_admin
|
||||
from controlplane.core.auth import _cloud_account, _identity, _require_admin
|
||||
from controlplane.core.crypto import rsa_encrypt
|
||||
from controlplane.core.db import _db, _now
|
||||
from controlplane.core.db import _audit, _db, _now
|
||||
from controlplane.core.paging import count_rows, page_bounds
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -74,7 +75,7 @@ def creds_seed(b: schemas.CredsSeedIn,
|
||||
仅当 pubkey_pem 非空时才需要用现有公钥给新增值加密留档;这里统一存明文源,
|
||||
/creds 下发时实时用该账号公钥加密,故无需在此预加密。
|
||||
"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
account = b.account.strip()
|
||||
if not account:
|
||||
raise HTTPException(400, "account 不能为空")
|
||||
@@ -91,24 +92,34 @@ def creds_seed(b: schemas.CredsSeedIn,
|
||||
"INSERT INTO client_creds(account, pubkey_pem, creds, updated_at) VALUES (%s, '', %s, %s)",
|
||||
(account, json.dumps(allowed, ensure_ascii=False), _now()))
|
||||
conn.commit()
|
||||
# 敏感明文源写入属高危操作,审计留痕(不记录明文值本身)
|
||||
_audit(login, "creds-seed", account, f"keys={sorted(allowed)}")
|
||||
return {"ok": True, "account": account, "seeded_keys": sorted(allowed)}
|
||||
|
||||
|
||||
@router.get("/api/admin/creds/manage")
|
||||
def creds_manage(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
def creds_manage(page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, ge=1, le=1000),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""管理台:列出已注册账号及其敏感凭证明文源(管理员回显,供页面编辑;值仅管理台可见)。"""
|
||||
"""管理台:列出已注册账号及其敏感凭证明文源(统一分页,items/total;值仅管理台可见)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
limit, offset = page_bounds(page, page_size)
|
||||
with _db() as conn:
|
||||
total = count_rows(conn, "SELECT COUNT(*) AS c FROM client_creds")
|
||||
rows = conn.execute(
|
||||
"SELECT account, pubkey_pem, creds, updated_at FROM client_creds ORDER BY account").fetchall()
|
||||
"SELECT c.account, c.pubkey_pem, c.creds, c.updated_at, a.nickname "
|
||||
"FROM client_creds c LEFT JOIN accounts a ON a.account = c.account "
|
||||
"ORDER BY c.account LIMIT %s OFFSET %s", (limit, offset)).fetchall()
|
||||
return {
|
||||
"accounts": [{
|
||||
"items": [{
|
||||
"account": r["account"],
|
||||
"nickname": r["nickname"] or "",
|
||||
"has_pubkey": bool(r["pubkey_pem"]),
|
||||
"creds": json.loads(r["creds"] or "{}"),
|
||||
"updated_at": str(r["updated_at"] or ""),
|
||||
} for r in rows],
|
||||
"total": total,
|
||||
"allowed_keys": list(_ALLOWED_KEYS),
|
||||
}
|
||||
|
||||
@@ -123,12 +134,10 @@ def creds_fetch(authorization: str = Header(default="", alias="Authorization"),
|
||||
解析出账号后校验 is_admin=1,非管理员一律 403(员工无法拉取,堵住越权窃取口子)。
|
||||
用账号上报的 RSA 公钥把每个明文值 OAEP 加密为 base64;无公钥或无明文源返回空。
|
||||
"""
|
||||
account = _cloud_account(authorization)
|
||||
if not account:
|
||||
try:
|
||||
account = _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
account = ""
|
||||
try:
|
||||
account = _identity(authorization, x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
account = ""
|
||||
if not account:
|
||||
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||||
with _db() as conn:
|
||||
|
||||
@@ -6,9 +6,10 @@
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import re
|
||||
import secrets
|
||||
from urllib.parse import quote, urlencode
|
||||
from urllib.parse import quote, urlencode, urlparse
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException, Query
|
||||
from fastapi.responses import RedirectResponse
|
||||
@@ -23,6 +24,27 @@ from controlplane.core.notify import notify_account_created
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _safe_back_url(url: str) -> bool:
|
||||
"""回跳地址白名单:仅允许 http(s) + 回环 / 内网私有网段 / 配置的控制面域名。
|
||||
|
||||
防止开放重定向钓鱼(原实现仅校验 http(s) 前缀,可被引导到任意站点并携带身份信息)。
|
||||
"""
|
||||
if not url or not (url.startswith("http://") or url.startswith("https://")):
|
||||
return False
|
||||
host = (urlparse(url).hostname or "").lower()
|
||||
if host in ("localhost", "127.0.0.1", "::1"):
|
||||
return True
|
||||
if config.DINGTALK_CALLBACK:
|
||||
cb_host = (urlparse(config.DINGTALK_CALLBACK).hostname or "").lower()
|
||||
if host == cb_host:
|
||||
return True
|
||||
try:
|
||||
ip = ipaddress.ip_address(host)
|
||||
return bool(ip.is_loopback or ip.is_private)
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
@router.post("/api/admin/dingtalk/auth")
|
||||
def admin_dingtalk_auth(d: schemas.DingTalkIn,
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
@@ -80,8 +102,8 @@ def dingtalk_scan(back: str = Query(..., description="扫码成功后的回跳
|
||||
"""扫码入口:302 到钉钉扫码登录页;state 携带部署机回跳地址,扫码成功后由 /cb 带回。"""
|
||||
if not config.DINGTALK_APP_KEY or not config.DINGTALK_APP_SECRET:
|
||||
raise HTTPException(503, "未配置钉钉开放平台应用(DINGTALK_APP_KEY / DINGTALK_APP_SECRET)")
|
||||
if not (back.startswith("http://") or back.startswith("https://")):
|
||||
raise HTTPException(400, "回跳地址非法(防止开放重定向)")
|
||||
if not _safe_back_url(back):
|
||||
raise HTTPException(400, "回跳地址非法(仅允许回环/内网/控制面域名,防止开放重定向)")
|
||||
if not config.DINGTALK_CALLBACK:
|
||||
raise HTTPException(400, "未配置 DINGTALK_CALLBACK(钉钉后台登记的回调地址)")
|
||||
login_url = "https://login.dingtalk.com/oauth2/challenge.htm?" + urlencode({
|
||||
@@ -97,8 +119,8 @@ def dingtalk_scan(back: str = Query(..., description="扫码成功后的回跳
|
||||
@router.get("/api/admin/dingtalk/cb")
|
||||
def dingtalk_cb(code: str = Query(...), state: str = Query(...)) -> RedirectResponse:
|
||||
"""钉钉回调:换 token 拉工号/姓名后,302 回部署机(state 里的回跳地址)携带身份。"""
|
||||
if not (state.startswith("http://") or state.startswith("https://")):
|
||||
raise HTTPException(400, "非法回跳地址")
|
||||
if not _safe_back_url(state):
|
||||
raise HTTPException(400, "非法回跳地址(仅允许回环/内网/控制面域名)")
|
||||
info = _dingtalk_userinfo(code)
|
||||
qs = urlencode({"account": info["account"] or "", "nickname": info["nickname"],
|
||||
"unionid": info["unionid"] or ""})
|
||||
@@ -144,8 +166,8 @@ def dingtalk_login_url(back: str = Query(...),
|
||||
_check_token(x_api_token)
|
||||
if not config.DINGTALK_APP_KEY or not config.DINGTALK_APP_SECRET:
|
||||
raise HTTPException(503, "控制面未配置钉钉开放平台应用(DINGTALK_APP_KEY / DINGTALK_APP_SECRET)")
|
||||
if not (back.startswith("http://") or back.startswith("https://")):
|
||||
raise HTTPException(400, "回跳地址非法(防止开放重定向)")
|
||||
if not _safe_back_url(back):
|
||||
raise HTTPException(400, "回跳地址非法(仅允许回环/内网/控制面域名)")
|
||||
login_url = "https://login.dingtalk.com/oauth2/challenge.htm?" + urlencode({
|
||||
"redirect_uri": back,
|
||||
"response_type": "code",
|
||||
|
||||
@@ -8,11 +8,13 @@ from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException
|
||||
from fastapi import APIRouter, Header, HTTPException, Query
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from controlplane.core.auth import _check_token, _require_admin
|
||||
from controlplane.core.db import _db, _now
|
||||
from controlplane.core.db import _audit, _db, _now
|
||||
from controlplane.core.paging import page_bounds
|
||||
from controlplane.core.pkgutil import _version_key
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -46,19 +48,23 @@ def _rows_to_dicts(rows) -> list[dict]:
|
||||
|
||||
@router.get("/api/admin/file-sources")
|
||||
def file_sources_list(category: str = "",
|
||||
page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, ge=1, le=1000),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""按 category 列出大文件源(可按 category 过滤,分组也可由 category 字段区分)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
"""按 category 列出大文件源(统一分页:先按版本号数值语义排序,再切片 items/total)。"""
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
with _db() as conn:
|
||||
if category.strip():
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM file_sources WHERE category = %s ORDER BY version, id",
|
||||
(category.strip(),)).fetchall()
|
||||
"SELECT * FROM file_sources WHERE category = %s", (category.strip(),)).fetchall()
|
||||
else:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM file_sources ORDER BY category, version, id").fetchall()
|
||||
return {"category": category, "files": _rows_to_dicts(rows)}
|
||||
rows = conn.execute("SELECT * FROM file_sources").fetchall()
|
||||
# 版本号按数值语义排序("1.10" > "1.9"),避免字符串排序取错(P2 修复)
|
||||
rows = sorted(rows, key=lambda r: (_version_key(r["version"]), r["id"]), reverse=True)
|
||||
total = len(rows)
|
||||
limit, offset = page_bounds(page, page_size)
|
||||
return {"category": category, "items": _rows_to_dicts(rows[offset:offset + limit]), "total": total}
|
||||
|
||||
|
||||
@router.post("/api/admin/file-sources")
|
||||
@@ -66,7 +72,7 @@ def file_sources_upsert(b: FileSourceIn,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""登记/覆盖一条大文件源(同一 category+version 去重)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
category, version = b.category.strip(), b.version.strip()
|
||||
url = b.url.strip()
|
||||
if not category:
|
||||
@@ -92,6 +98,7 @@ def file_sources_upsert(b: FileSourceIn,
|
||||
b.notes.strip(), int(b.enabled), _now()))
|
||||
fid = cur.lastrowid
|
||||
conn.commit()
|
||||
_audit(login, "file-source-upsert", f"{category}@{version}", url)
|
||||
return {"ok": True, "id": fid, "category": category, "version": version}
|
||||
|
||||
|
||||
@@ -100,7 +107,7 @@ def file_sources_patch(fid: int, b: FileSourcePatch,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""启停 / 改说明。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
fields, vals = [], []
|
||||
if b.enabled is not None:
|
||||
fields.append("enabled = %s"); vals.append(int(b.enabled))
|
||||
@@ -115,6 +122,7 @@ def file_sources_patch(fid: int, b: FileSourcePatch,
|
||||
conn.commit()
|
||||
if cur.rowcount == 0:
|
||||
raise HTTPException(404, "记录不存在")
|
||||
_audit(login, "file-source-patch", str(fid), f"enabled={b.enabled}, notes={b.notes is not None}")
|
||||
return {"ok": True, "id": fid}
|
||||
|
||||
|
||||
@@ -123,12 +131,13 @@ def file_sources_delete(fid: int,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""删除一条大文件源(仅删中心机登记,不动内网服务器文件)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
with _db() as conn:
|
||||
cur = conn.execute("DELETE FROM file_sources WHERE id = %s", (fid,))
|
||||
conn.commit()
|
||||
if cur.rowcount == 0:
|
||||
raise HTTPException(404, "记录不存在")
|
||||
_audit(login, "file-source-delete", str(fid))
|
||||
return {"ok": True, "id": fid}
|
||||
|
||||
|
||||
@@ -141,13 +150,13 @@ def file_sources_public_latest(category: str,
|
||||
"""
|
||||
_check_token(x_api_token)
|
||||
with _db() as conn:
|
||||
rows = conn.execute(
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT id, category, version, filename, url, sha256, notes FROM file_sources "
|
||||
"WHERE category = %s AND enabled = 1 ORDER BY version DESC, id DESC LIMIT 1",
|
||||
(category.strip(),)).fetchall()
|
||||
"WHERE category = %s AND enabled = 1", (category.strip(),))]
|
||||
if not rows:
|
||||
return {"available": False, "category": category.strip()}
|
||||
r = rows[0]
|
||||
# 版本号按数值语义取最新("1.10" > "1.9"),避免字符串排序取错(P2 修复)
|
||||
r = max(rows, key=lambda r: (_version_key(r["version"]), r["id"]))
|
||||
return {
|
||||
"available": True,
|
||||
"category": r["category"], "version": r["version"],
|
||||
|
||||
@@ -4,11 +4,10 @@ from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from controlplane import config
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
def health() -> dict:
|
||||
return {"ok": True, "db": "mysql", "host": config.MYSQL_HOST, "database": config.MYSQL_DB}
|
||||
"""健康检查:不泄露任何环境信息(原实现返回 MYSQL_HOST/库名,公网可探,P2 收敛)。"""
|
||||
return {"ok": True}
|
||||
@@ -13,7 +13,7 @@ import json
|
||||
from fastapi import APIRouter, Header, HTTPException
|
||||
from pydantic import BaseModel
|
||||
|
||||
from controlplane.core.auth import _cloud_account, _resolve_login
|
||||
from controlplane.core.auth import _identity
|
||||
from controlplane.core.db import _db, _now
|
||||
|
||||
router = APIRouter()
|
||||
@@ -23,18 +23,13 @@ class _BackupIn(BaseModel):
|
||||
data: dict = {}
|
||||
|
||||
|
||||
def _identity(authorization: str = "", x_admin_token: str = "",
|
||||
x_api_token: str = "", x_admin_user: str = "") -> str:
|
||||
"""解析请求身份;无效则抛 401。"""
|
||||
account = _cloud_account(authorization)
|
||||
if not account:
|
||||
try:
|
||||
account = _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
account = ""
|
||||
if not account:
|
||||
def _require_identity(authorization: str = "", x_admin_token: str = "",
|
||||
x_api_token: str = "", x_admin_user: str = "") -> str:
|
||||
"""统一身份解析(core.auth._identity),无效则抛 401。"""
|
||||
try:
|
||||
return _identity(authorization, x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||||
return account
|
||||
|
||||
|
||||
@router.post("/api/schedules/backup")
|
||||
@@ -44,7 +39,7 @@ def sched_backup_save(b: _BackupIn,
|
||||
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
|
||||
"""覆盖保存某账号的定时任务全量配置(执行机变更后异步推送)。"""
|
||||
account = _identity(authorization, x_admin_token, x_api_token, x_admin_user)
|
||||
account = _require_identity(authorization, x_admin_token, x_api_token, x_admin_user)
|
||||
payload = b.data if isinstance(b.data, dict) else {}
|
||||
if not isinstance(payload.get("schedules"), list):
|
||||
raise HTTPException(400, "data.schedules 必须为数组")
|
||||
@@ -63,7 +58,7 @@ def sched_backup_load(authorization: str = Header(default="", alias="Authorizati
|
||||
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
|
||||
"""读取某账号备份的定时任务全量配置(执行机启动时合并恢复缺失任务)。"""
|
||||
account = _identity(authorization, x_admin_token, x_api_token, x_admin_user)
|
||||
account = _require_identity(authorization, x_admin_token, x_api_token, x_admin_user)
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT data FROM schedule_backups WHERE account = %s", (account,)).fetchone()
|
||||
|
||||
@@ -18,6 +18,7 @@ X-API-Token 请求头。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
from contextlib import asynccontextmanager
|
||||
@@ -38,9 +39,16 @@ from controlplane.apis import meta as api_meta
|
||||
from controlplane.apis import plugins as api_plugins
|
||||
from controlplane.apis import schedules as api_schedules
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
if not config.CONTROLPLANE_TOKEN:
|
||||
# 内部凭证为空时客户端接口无鉴权(P0 安全债)。不阻断本地开发,但生产必须配置:
|
||||
# 公网部署时请务必在 controlplane/.env 设置 CONTROLPLANE_TOKEN。
|
||||
_LOGGER.error(
|
||||
"CONTROLPLANE_TOKEN 未配置:全部客户端接口将无鉴权放行,生产环境禁止!")
|
||||
_init_db()
|
||||
_seed()
|
||||
# 内网文件服务器离线监控:心跳超时判离线并钉钉告警管理员(daemon 线程)
|
||||
@@ -49,7 +57,12 @@ async def lifespan(app: FastAPI):
|
||||
|
||||
|
||||
app = FastAPI(title="37du 插件管理平台", lifespan=lifespan)
|
||||
app.add_middleware(CORSMiddleware, allow_origins=["*"],
|
||||
# CORS 收敛为白名单(原 allow_origins=["*"],控制面走公网时任何站点可跨域调接口)。
|
||||
# 默认放行本地控制面前端(8090 静态站);公网/反代部署用 CORS_ALLOW_ORIGINS 配置实际来源。
|
||||
_CORS_ORIGINS = [o.strip() for o in os.getenv(
|
||||
"CORS_ALLOW_ORIGINS",
|
||||
"http://127.0.0.1:8090,http://localhost:8090").split(",") if o.strip()]
|
||||
app.add_middleware(CORSMiddleware, allow_origins=_CORS_ORIGINS,
|
||||
allow_methods=["*"], allow_headers=["*"])
|
||||
|
||||
app.include_router(api_meta.router)
|
||||
|
||||
@@ -58,7 +58,11 @@ def _verify_admin_token(tok: str) -> str:
|
||||
|
||||
|
||||
def _require_admin(x_admin_token: str = "", x_api_token: str = "") -> str:
|
||||
"""管理操作:仅校验登录票据(X-Admin-Token)对应账号 is_admin=1(浏览器管理面免 X-API-Token)。返回账号。"""
|
||||
"""管理操作:仅校验登录票据(X-Admin-Token)对应账号 is_admin=1(浏览器管理面免 X-API-Token)。返回账号。
|
||||
|
||||
停用账号立即失效(status=0 拒绝);must_change_pwd=1(仍持初始密码)拒绝管理操作,
|
||||
强制先改密(P0/P1 安全债)。
|
||||
"""
|
||||
try:
|
||||
account = _verify_admin_token(x_admin_token)
|
||||
except Exception:
|
||||
@@ -67,9 +71,14 @@ def _require_admin(x_admin_token: str = "", x_api_token: str = "") -> str:
|
||||
raise HTTPException(401, "缺少有效登录态")
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT 1 FROM accounts WHERE account = %s AND is_admin = 1", (account,)).fetchone()
|
||||
if not row:
|
||||
"SELECT is_admin, status, must_change_pwd FROM accounts WHERE account = %s",
|
||||
(account,)).fetchone()
|
||||
if not row or not row["is_admin"]:
|
||||
raise HTTPException(403, f"账号 {account} 无管理权限")
|
||||
if not row["status"]:
|
||||
raise HTTPException(403, "账号已停用,请联系管理员")
|
||||
if row["must_change_pwd"]:
|
||||
raise HTTPException(403, "请先修改初始密码后再执行管理操作")
|
||||
return account
|
||||
|
||||
|
||||
@@ -93,25 +102,50 @@ def _resolve_login(x_admin_token: str = "", x_api_token: str = "",
|
||||
raise ValueError("no identity")
|
||||
|
||||
|
||||
# ==================== 登录防爆破(进程内计数,失败锁定退避) ====================
|
||||
_AUTH_FAILS: dict = {} # account -> [连续失败次数, 锁定截止时间戳]
|
||||
# ==================== 登录防爆破(MySQL 共享计数,gunicorn 多 worker 通用) ====================
|
||||
# 原进程内 dict 计数在多 worker 下可绕过、且无锁读写不原子;改落库 auth_fail_counts 表
|
||||
# (原子 UPSERT),锁定到期后自动重置计数,避免"锁定过期仍累计导致永久锁定"。
|
||||
_AUTH_FAIL_LIMIT = 5 # 连续失败 N 次后锁定
|
||||
_AUTH_LOCK_SECS = 300 # 锁定 5 分钟
|
||||
|
||||
|
||||
def _auth_gate(account: str) -> None:
|
||||
fails, locked_until = _AUTH_FAILS.get(account, (0, 0.0))
|
||||
if locked_until > time.time():
|
||||
raise HTTPException(429, f"失败次数过多,账号已临时锁定,请 {int(locked_until - time.time())} 秒后重试")
|
||||
"""登录前检查:DB 记录处于锁定中则拒绝。计数失败不阻断(安全兜底:宁可放宽)。"""
|
||||
try:
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT 1 FROM auth_fail_counts WHERE account = %s AND locked_until > NOW()",
|
||||
(account,)).fetchone()
|
||||
except Exception: # noqa: BLE001
|
||||
return
|
||||
if row:
|
||||
raise HTTPException(429, "失败次数过多,账号已临时锁定,请 5 分钟后再试")
|
||||
|
||||
|
||||
def _auth_fail(account: str) -> None:
|
||||
fails, _ = _AUTH_FAILS.get(account, (0, 0.0))
|
||||
fails += 1
|
||||
if fails >= _AUTH_FAIL_LIMIT:
|
||||
_AUTH_FAILS[account] = (0, time.time() + _AUTH_LOCK_SECS)
|
||||
else:
|
||||
_AUTH_FAILS[account] = (fails, 0.0)
|
||||
"""记录一次登录失败;连续达到阈值则锁定(原子 UPSERT,多 worker 一致)。"""
|
||||
try:
|
||||
with _db() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO auth_fail_counts(account, fails, locked_until) VALUES (%s, 1, NULL) "
|
||||
"ON DUPLICATE KEY UPDATE "
|
||||
"fails = IF(locked_until IS NOT NULL AND locked_until <= NOW(), 1, fails + 1), "
|
||||
"locked_until = IF(fails + 1 >= %s, "
|
||||
"DATE_ADD(NOW(), INTERVAL %s SECOND), NULL)",
|
||||
(account, _AUTH_FAIL_LIMIT, _AUTH_LOCK_SECS))
|
||||
conn.commit()
|
||||
except Exception: # noqa: BLE001 计数失败不阻断登录流程
|
||||
pass
|
||||
|
||||
|
||||
def _auth_reset(account: str) -> None:
|
||||
"""登录成功后清除失败计数。"""
|
||||
try:
|
||||
with _db() as conn:
|
||||
conn.execute("DELETE FROM auth_fail_counts WHERE account = %s", (account,))
|
||||
conn.commit()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
|
||||
# ==================== 云端会话 token(员工端扫码登录,§2.2) ====================
|
||||
@@ -136,8 +170,9 @@ def _auth_account_lookup(account: str) -> dict:
|
||||
def _cloud_account(bearer: str) -> str:
|
||||
"""从 Bearer 云端会话 token 解出工号(§2.2);无效/过期/缺失返回空串。
|
||||
|
||||
查 cloud_tokens 表(落库共享):签发与解析不再受 worker 进程限制。
|
||||
库不可用时返回空串(身份解析失败不抛异常,交由各路由的兜底逻辑处理)。
|
||||
查 cloud_tokens 表(落库共享)并 JOIN accounts 校验账号存在且未停用:删号/停用后
|
||||
残留令牌立即失效(P1 安全债)。库不可用时返回空串(身份解析失败不抛异常,
|
||||
交由各路由的兜底逻辑处理)。
|
||||
"""
|
||||
token = (bearer or "").strip()
|
||||
if token.lower().startswith("bearer "):
|
||||
@@ -147,7 +182,9 @@ def _cloud_account(bearer: str) -> str:
|
||||
try:
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT account FROM cloud_tokens WHERE token = %s AND expires_at > NOW()",
|
||||
"SELECT t.account FROM cloud_tokens t "
|
||||
"JOIN accounts a ON a.account = t.account "
|
||||
"WHERE t.token = %s AND t.expires_at > NOW() AND a.status = 1",
|
||||
(token,)).fetchone()
|
||||
except Exception: # noqa: BLE001 库异常按“无身份”处理,不阻断请求
|
||||
return ""
|
||||
@@ -168,4 +205,25 @@ def _issue_cloud_token(account: str, nickname: str) -> str:
|
||||
"INSERT INTO cloud_tokens(token, account, nickname, expires_at) VALUES (%s, %s, %s, %s)",
|
||||
(token, account, nickname, expires.strftime("%Y-%m-%d %H:%M:%S")))
|
||||
conn.commit()
|
||||
return token
|
||||
return token
|
||||
|
||||
|
||||
def _identity(authorization: str = "", x_admin_token: str = "",
|
||||
x_api_token: str = "", x_admin_user: str = "") -> str:
|
||||
"""统一身份解析(三源,消除各路由复制粘贴):Bearer 云令牌 → X-Admin-Token →
|
||||
X-Admin-User(+X-API-Token)。返回账号;无有效身份抛 ValueError(调用方决定 401/空响应)。
|
||||
"""
|
||||
acct = _cloud_account(authorization)
|
||||
if acct:
|
||||
return acct
|
||||
return _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||||
|
||||
|
||||
def _revoke_account_tokens(account: str) -> None:
|
||||
"""吊销某账号全部云令牌(删号/停用时调用,防止残留令牌继续解析)。"""
|
||||
try:
|
||||
with _db() as conn:
|
||||
conn.execute("DELETE FROM cloud_tokens WHERE account = %s", (account,))
|
||||
conn.commit()
|
||||
except Exception: # noqa: BLE001 吊销失败不阻断主流程
|
||||
pass
|
||||
@@ -62,7 +62,24 @@ MYSQL_USER = os.getenv("MYSQL_USER", "root")
|
||||
MYSQL_PASSWORD = os.getenv("MYSQL_PASSWORD", "")
|
||||
MYSQL_DB = os.getenv("MYSQL_DB") or os.getenv("MYSQL_DATABASE") or "37du_center"
|
||||
# 钉钉扫码自动建号的初始密码;新号无插件权限、仅空壳,首次登录须改密。
|
||||
DINGTALK_DEFAULT_PASSWORD = os.getenv("DINGTALK_DEFAULT_PASSWORD", "123456")
|
||||
# 未配置时首次启动生成随机密码并持久化到 .dingtalk_default_pwd(重启复用,保证未改密
|
||||
# 用户拿到的初始密码稳定),经钉钉工作通知下发给本人。不再使用硬编码 123456(P0 安全债)。
|
||||
def _dingtalk_default_password() -> str:
|
||||
_v = os.getenv("DINGTALK_DEFAULT_PASSWORD", "").strip()
|
||||
if _v:
|
||||
return _v
|
||||
_f = APP_DIR / ".dingtalk_default_pwd"
|
||||
if _f.is_file():
|
||||
return _f.read_text(encoding="utf-8").strip()
|
||||
_pwd = secrets.token_urlsafe(9) # 约 12 位,大小写字母+数字,无易混淆字符
|
||||
try:
|
||||
_f.write_text(_pwd, encoding="utf-8")
|
||||
except OSError:
|
||||
pass
|
||||
return _pwd
|
||||
|
||||
|
||||
DINGTALK_DEFAULT_PASSWORD = _dingtalk_default_password()
|
||||
# 钉钉开放平台应用(真实扫码;未配置则钉钉扫码入口自动隐藏,仅保留账号密码登录)。
|
||||
# 同一套 KEY/SECRET 即可:扫码换 unionid/昵称 → gettoken 企业内部 token
|
||||
# → getbyunionid 取 userid → v2/user/get 取 job_number(工号),无需第二组凭证。
|
||||
@@ -96,9 +113,12 @@ CREDS_DEFAULT = {
|
||||
"CREDS_DINGTALK_AGENT_ID", "CREDS_DINGTALK_CORP_ID")
|
||||
}
|
||||
|
||||
# 管理台会话票据签名密钥:CONTROLPLANE_ADMIN_SECRET > CONTROLPLANE_TOKEN > 首次随机生成并
|
||||
# 持久化到 .admin_secret(保证重启不回退,杜绝凭用户名 X-Admin-User 直接伪造身份)。
|
||||
_ADMIN_SECRET_CANDIDATE = os.getenv("CONTROLPLANE_ADMIN_SECRET") or os.getenv("CONTROLPLANE_TOKEN") or ""
|
||||
# 管理台会话票据签名密钥:CONTROLPLANE_ADMIN_SECRET > .admin_secret 文件(首次随机生成并持久化,
|
||||
# 保证重启不回退,杜绝凭用户名 X-Admin-User 直接伪造身份)。
|
||||
# 注意:不再回退 CONTROLPLANE_TOKEN —— 传输凭证与管理密钥必须分离,否则持 X-API-Token 的执行机
|
||||
# 可本地 HMAC 自签任意管理员票据全量接管系统(P0 安全债)。变更该密钥会使已签发的管理票据
|
||||
# 全部失效(管理员需重新登录一次),普通用户的云令牌与底座 X-API-Token 不受影响。
|
||||
_ADMIN_SECRET_CANDIDATE = os.getenv("CONTROLPLANE_ADMIN_SECRET") or ""
|
||||
_ADMIN_SECRET_FALLBACK: str = ""
|
||||
_ADMIN_TOKEN_TTL = 12 * 3600 # 票据有效期 12h
|
||||
|
||||
|
||||
@@ -11,6 +11,9 @@ from __future__ import annotations
|
||||
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime
|
||||
import logging
|
||||
import secrets
|
||||
import time
|
||||
|
||||
import pymysql
|
||||
from pymysql.cursors import DictCursor
|
||||
@@ -18,8 +21,10 @@ from pymysql.cursors import DictCursor
|
||||
from controlplane.core import config
|
||||
from controlplane.core.crypto import _hash_password
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 初始迁移版本:全量 DDL 建齐后登记;后续增量 DDL 在此追加新版本并配套迁移逻辑
|
||||
_SCHEMA_VERSION = "20260919_002"
|
||||
_SCHEMA_VERSION = "20260920_001"
|
||||
|
||||
# 全量 DDL(15 张表,MySQL 5.7 兼容;与 tools/schema_mysql.sql 逐条一致)
|
||||
_DDL_TABLES = (
|
||||
@@ -258,16 +263,26 @@ _DDL_TABLES = (
|
||||
KEY idx_last_seen (last_seen)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='内网文件服务器状态(心跳上报+离线监控)'
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS auth_fail_counts (
|
||||
account VARCHAR(64) NOT NULL COMMENT '登录账号(工号,主键)',
|
||||
fails INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '连续失败次数',
|
||||
locked_until DATETIME NULL COMMENT '锁定截止时间(NULL=未锁定)',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (account)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='登录防爆破共享计数(落库,gunicorn 多 worker 通用)'
|
||||
""",
|
||||
)
|
||||
|
||||
|
||||
def _connect(server: bool = False) -> pymysql.connections.Connection:
|
||||
"""建立 PyMySQL 连接;server=True 时不指定 database(用于建库)。"""
|
||||
"""建立 PyMySQL 连接(带连接超时,防 MySQL 挂起时无限阻塞);server=True 时不指定 database(用于建库)。"""
|
||||
return pymysql.connect(
|
||||
host=config.MYSQL_HOST, port=config.MYSQL_PORT,
|
||||
user=config.MYSQL_USER, password=config.MYSQL_PASSWORD,
|
||||
database=None if server else config.MYSQL_DB,
|
||||
charset="utf8mb4", cursorclass=DictCursor, autocommit=False)
|
||||
charset="utf8mb4", cursorclass=DictCursor, autocommit=False,
|
||||
connect_timeout=10)
|
||||
|
||||
|
||||
class _DbConn:
|
||||
@@ -299,13 +314,26 @@ class _DbConn:
|
||||
|
||||
@contextmanager
|
||||
def _db():
|
||||
"""打开连接并在退出时 commit + close(统一收口,避免长运行服务累积连接)。
|
||||
"""打开连接(建立失败自动重试 3 次)并在退出时 commit + close(统一收口)。
|
||||
|
||||
与旧 sqlite3 语义一致:异常时不 commit 等价于回滚。
|
||||
与旧 sqlite3 语义一致:异常时不 commit 等价于回滚;仅连接建立阶段重试,
|
||||
业务块内异常不重试(语义不变),避免把业务失败误当连接故障无限重放。
|
||||
"""
|
||||
if not config.MYSQL_HOST:
|
||||
raise RuntimeError("未配置 MySQL 连接(MYSQL_HOST),请查看 desktop/controlplane/.env")
|
||||
conn = _connect()
|
||||
conn = None
|
||||
last_exc = None
|
||||
for _attempt in range(3):
|
||||
try:
|
||||
conn = _connect()
|
||||
break
|
||||
except Exception as _exc: # noqa: BLE001 连接失败重试(对齐 AGENTS.md 最大重试 3 次)
|
||||
last_exc = _exc
|
||||
conn = None
|
||||
if _attempt < 2:
|
||||
time.sleep(0.5 * (_attempt + 1))
|
||||
if conn is None:
|
||||
raise RuntimeError(f"MySQL 连接失败(重试 3 次后放弃):{last_exc}")
|
||||
try:
|
||||
yield _DbConn(conn)
|
||||
conn.commit()
|
||||
@@ -361,12 +389,15 @@ def _seed() -> None:
|
||||
"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"),):
|
||||
_hex, _salt = _hash_password("123456")
|
||||
_pwd = secrets.token_urlsafe(9) # 约 12 位随机密码
|
||||
_hex, _salt = _hash_password(_pwd)
|
||||
conn.execute(
|
||||
"INSERT IGNORE INTO accounts(account, password_hash, salt, is_admin, dept) "
|
||||
"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():
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""统一分页规范(控制面管理端列表接口)。
|
||||
|
||||
约定:
|
||||
- 请求参数统一:``page``(第 1 页起)、``page_size``(默认 20,上限 1000)
|
||||
- 响应统一:``{"items": [...], "total": int}``
|
||||
|
||||
路由用法示例:
|
||||
from fastapi import Query
|
||||
from controlplane.core.paging import page_bounds
|
||||
|
||||
@router.get("/api/admin/xxx")
|
||||
def admin_xxx(page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, ge=1, le=1000), ...):
|
||||
_require_admin(...)
|
||||
limit, offset = page_bounds(page, page_size)
|
||||
with _db() as conn:
|
||||
total = count_rows(conn, "SELECT COUNT(*) AS c FROM t")
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT ... ORDER BY id DESC LIMIT %s OFFSET %s", (limit, offset))]
|
||||
return {"items": rows, "total": total}
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def page_bounds(page: int, page_size: int) -> tuple[int, int]:
|
||||
"""page(1 起) 与 page_size -> (limit, offset),带防抖(page>=1,page_size 1..1000)。"""
|
||||
page = max(1, int(page))
|
||||
page_size = min(max(1, int(page_size)), 1000)
|
||||
return page_size, (page - 1) * page_size
|
||||
|
||||
|
||||
def count_rows(conn, sql: str, args=()) -> int:
|
||||
"""统一取总数:sql 为 ``SELECT COUNT(*) AS c ...``,返回 int。"""
|
||||
return int(conn.execute(sql, args).fetchone()["c"])
|
||||
Binary file not shown.
+26
@@ -9,6 +9,7 @@
|
||||
"version": "0.1.0",
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "^2.3.2",
|
||||
"echarts": "^6.1.0",
|
||||
"element-plus": "^2.14.5",
|
||||
"vue": "^3.5.13"
|
||||
},
|
||||
@@ -1170,6 +1171,16 @@
|
||||
"integrity": "sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/echarts": {
|
||||
"version": "6.1.0",
|
||||
"resolved": "https://registry.npmjs.org/echarts/-/echarts-6.1.0.tgz",
|
||||
"integrity": "sha512-q0yaFPggC9FUdsWH4blavRWFmxdrIodbkoKNAjJudAI6CA9gNPxHtV2RcZNEepZVlk4yvBYkOkbk6HIVpIyHZA==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"tslib": "2.3.0",
|
||||
"zrender": "6.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/element-plus": {
|
||||
"version": "2.14.5",
|
||||
"resolved": "https://registry.npmjs.org/element-plus/-/element-plus-2.14.5.tgz",
|
||||
@@ -1470,6 +1481,12 @@
|
||||
"url": "https://github.com/sponsors/SuperchupuDev"
|
||||
}
|
||||
},
|
||||
"node_modules/tslib": {
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.0.tgz",
|
||||
"integrity": "sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg==",
|
||||
"license": "0BSD"
|
||||
},
|
||||
"node_modules/vite": {
|
||||
"version": "6.4.3",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz",
|
||||
@@ -1571,6 +1588,15 @@
|
||||
"resolved": "https://registry.npmjs.org/vue-component-type-helpers/-/vue-component-type-helpers-3.3.11.tgz",
|
||||
"integrity": "sha512-LwcxzeliO9fkQcpJG0PoX8X5kmAhKmH9wkpDLxNabwzkQ9Zeib2YVHwFV4pcWmMLfXVfjr/dSV+DaJ3cIPgSNA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/zrender": {
|
||||
"version": "6.1.0",
|
||||
"resolved": "https://registry.npmjs.org/zrender/-/zrender-6.1.0.tgz",
|
||||
"integrity": "sha512-oEGMDB6pOP2S6OwRR4PdVv610zrjnA3Bh+JnSG12fYJlBKjtNAoEb5fSUoCOOINlH96I2fU38/A2UpRKs67xYQ==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"tslib": "2.3.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "^2.3.2",
|
||||
"echarts": "^6.1.0",
|
||||
"element-plus": "^2.14.5",
|
||||
"vue": "^3.5.13"
|
||||
},
|
||||
|
||||
@@ -43,7 +43,7 @@
|
||||
</transition>
|
||||
</main>
|
||||
</div>
|
||||
<PasswordDialog v-model="pwdOpen" />
|
||||
<PasswordDialog v-model="pwdOpen" :force="pwdForce" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -113,17 +113,24 @@ function onMenu(key) {
|
||||
const initial = computed(() => (store.nickname || store.current || '')[0]?.toUpperCase() || '?')
|
||||
|
||||
const pwdOpen = ref(false)
|
||||
const pwdForce = ref(false)
|
||||
function onCommand(cmd) {
|
||||
if (cmd === 'pwd') pwdOpen.value = true
|
||||
if (cmd === 'pwd') { pwdForce.value = false; pwdOpen.value = true }
|
||||
else if (cmd === 'logout') {
|
||||
clearSession()
|
||||
message.success('已退出登录')
|
||||
}
|
||||
}
|
||||
|
||||
function onLogin() {
|
||||
function onLogin(r) {
|
||||
route.value = '#/overview'
|
||||
location.hash = '#/overview'
|
||||
// 服务端强制:仍持初始密码(must_change_pwd=1)时拒绝一切管理操作,必须先改密
|
||||
if (r && r.must_change_pwd) {
|
||||
pwdForce.value = true
|
||||
pwdOpen.value = true
|
||||
message.warning('首次登录请先修改初始密码,修改成功后才能使用管理功能')
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
@@ -132,7 +139,15 @@ onMounted(async () => {
|
||||
try {
|
||||
const me = await adminMe()
|
||||
if (!me.account || !me.is_admin) clearSession()
|
||||
else { store.isAdmin = true; store.nickname = me.nickname || '' }
|
||||
else {
|
||||
store.isAdmin = true; store.nickname = me.nickname || ''
|
||||
// 刷新后仍需先改初始密码(服务端拒绝一切管理操作)
|
||||
if (me.must_change_pwd) {
|
||||
pwdForce.value = true
|
||||
pwdOpen.value = true
|
||||
message.warning('请先修改初始密码,修改成功后才能使用管理功能')
|
||||
}
|
||||
}
|
||||
} catch (_) { /* 后端 down:保持本地态 */ }
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -26,6 +26,14 @@ function adminHeaders(extra = {}) {
|
||||
return { 'X-Admin-Token': store.token || '', ...extra }
|
||||
}
|
||||
|
||||
// 统一分页规范:所有列表接口 page(page≥1) + page_size,返回 {items, total}
|
||||
function pagedQuery(params = {}) {
|
||||
const qs = new URLSearchParams()
|
||||
if (params.page) qs.set('page', params.page)
|
||||
if (params.page_size) qs.set('page_size', params.page_size)
|
||||
return qs.toString()
|
||||
}
|
||||
|
||||
export async function adminLogin(account, password) {
|
||||
return req('/api/admin/auth', {
|
||||
method: 'POST',
|
||||
@@ -46,6 +54,12 @@ export async function adminMe() {
|
||||
export async function adminOverview() {
|
||||
return req('/api/admin/overview', { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminGrantData() {
|
||||
return req('/api/admin/grant_data', { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminAccountGrants(account) {
|
||||
return req('/api/admin/account_grants?account=' + encodeURIComponent(account), { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminPlatforms() {
|
||||
return req('/api/admin/platforms', { headers: adminHeaders() })
|
||||
}
|
||||
@@ -63,8 +77,17 @@ export async function adminPlatformGrant(body) {
|
||||
body: JSON.stringify(body)
|
||||
})
|
||||
}
|
||||
export async function adminAccounts() {
|
||||
return req('/api/admin/accounts', { headers: adminHeaders() })
|
||||
export async function adminAccounts(page = 1, pageSize = 20, q = '') {
|
||||
const qs = new URLSearchParams()
|
||||
qs.set('page', page); qs.set('page_size', pageSize)
|
||||
if (q) qs.set('q', q)
|
||||
return req('/api/admin/accounts?' + qs.toString(), { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminPlugins(page = 1, pageSize = 20, q = '') {
|
||||
const qs = new URLSearchParams()
|
||||
qs.set('page', page); qs.set('page_size', pageSize)
|
||||
if (q) qs.set('q', q)
|
||||
return req('/api/admin/plugins?' + qs.toString(), { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminAccountCreate(body) {
|
||||
return req('/api/admin/account', {
|
||||
@@ -115,17 +138,25 @@ export async function adminPluginPatch(pluginId, body) {
|
||||
body: JSON.stringify(body)
|
||||
})
|
||||
}
|
||||
export async function adminAudit(limit = 300) {
|
||||
return req('/api/admin/audit?limit=' + limit, { headers: adminHeaders() })
|
||||
export async function adminAudit(page = 1, pageSize = 20, filters = {}) {
|
||||
const qs = new URLSearchParams()
|
||||
qs.set('page', page); qs.set('page_size', pageSize)
|
||||
if (filters.action) qs.set('action', filters.action)
|
||||
if (filters.q) qs.set('q', filters.q)
|
||||
return req('/api/admin/audit?' + qs.toString(), { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminReports(limit = 300) {
|
||||
return req('/api/admin/reports?limit=' + limit, { headers: adminHeaders() })
|
||||
export async function adminReports(page = 1, pageSize = 20, filters = {}) {
|
||||
const qs = new URLSearchParams()
|
||||
qs.set('page', page); qs.set('page_size', pageSize)
|
||||
if (filters.status) qs.set('status', filters.status)
|
||||
if (filters.q) qs.set('q', filters.q)
|
||||
return req('/api/admin/reports?' + qs.toString(), { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminStats() {
|
||||
return req('/api/admin/stats', { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminCredsList() {
|
||||
return req('/api/admin/creds/manage', { headers: adminHeaders() })
|
||||
export async function adminCredsList(page = 1, pageSize = 20) {
|
||||
return req('/api/admin/creds/manage?' + pagedQuery({ page, page_size: pageSize }), { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminCredsSeed(body) {
|
||||
return req('/api/admin/creds/seed', {
|
||||
@@ -134,8 +165,12 @@ export async function adminCredsSeed(body) {
|
||||
body: JSON.stringify(body)
|
||||
})
|
||||
}
|
||||
export async function adminFileSources(category = '') {
|
||||
const qs = category ? '?category=' + encodeURIComponent(category) : ''
|
||||
export async function adminFileSources(category = '', page = 1, pageSize = 20) {
|
||||
const parts = []
|
||||
if (category) parts.push('category=' + encodeURIComponent(category))
|
||||
const pq = pagedQuery({ page, page_size: pageSize })
|
||||
if (pq) parts.push(pq)
|
||||
const qs = parts.length ? '?' + parts.join('&') : ''
|
||||
return req('/api/admin/file-sources' + qs, { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminFileSourceCreate(body) {
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
<template>
|
||||
<div class="pager-bar" v-if="total > 0">
|
||||
<el-pagination background layout="total, sizes, prev, pager, next"
|
||||
:total="total" :current-page="page" :page-size="pageSize"
|
||||
:page-sizes="[10, 20, 50, 100]"
|
||||
@current-change="p => emit('change', p, pageSize)"
|
||||
@size-change="s => emit('change', 1, s)" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
// 统一分页条:配合后端 page/page_size 分页接口({items,total})。
|
||||
// 用法:<PagerBar :total="total" :page="page" :page-size="pageSize"
|
||||
// @change="(p, s) => { page = p; pageSize = s; load() }" />
|
||||
defineProps({ total: { type: Number, default: 0 }, page: { type: Number, default: 1 }, pageSize: { type: Number, default: 20 } })
|
||||
const emit = defineEmits(['change'])
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.pager-bar { display: flex; justify-content: flex-end; padding: 12px 4px 2px; }
|
||||
</style>
|
||||
@@ -1,5 +1,10 @@
|
||||
<template>
|
||||
<el-dialog v-model="visible" title="修改密码" width="440px" align-center destroy-on-close @closed="reset">
|
||||
<el-dialog v-model="visible" title="修改密码" width="440px" align-center destroy-on-close
|
||||
:close-on-click-modal="!force" :close-on-press-escape="!force" :show-close="!force"
|
||||
@closed="onClosed">
|
||||
<el-alert v-if="force" type="warning" :closable="false" class="force-tip" show-icon>
|
||||
首次登录请先修改初始密码,修改成功后才能使用管理功能。
|
||||
</el-alert>
|
||||
<el-alert v-if="store.current" type="info" :closable="false" class="acct-tip" show-icon>
|
||||
当前账号:<b class="mono">{{ store.current }}</b>
|
||||
</el-alert>
|
||||
@@ -8,7 +13,7 @@
|
||||
<el-input v-model="form.oldPwd" type="password" placeholder="请输入原密码" show-password @keyup.enter="submit" />
|
||||
</el-form-item>
|
||||
<el-form-item label="新密码" prop="newPwd">
|
||||
<el-input v-model="form.newPwd" type="password" placeholder="至少 6 位,不与原密码相同" show-password @keyup.enter="submit" />
|
||||
<el-input v-model="form.newPwd" type="password" placeholder="至少 8 位,不与原密码相同" show-password @keyup.enter="submit" />
|
||||
</el-form-item>
|
||||
<el-form-item label="确认新密码" prop="newPwd2">
|
||||
<el-input v-model="form.newPwd2" type="password" placeholder="再次输入新密码" show-password @keyup.enter="submit" />
|
||||
@@ -16,7 +21,7 @@
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<div class="modal-foot">
|
||||
<el-button @click="visible = false">取消</el-button>
|
||||
<el-button v-if="!force" @click="visible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="busy" @click="submit">保存</el-button>
|
||||
</div>
|
||||
</template>
|
||||
@@ -29,16 +34,19 @@ import { ElMessage as message } from 'element-plus'
|
||||
import { store } from '../store'
|
||||
import { adminPassword } from '../api'
|
||||
|
||||
// force=true 强制改密模式(首次登录 must_change_pwd):不可取消/关闭,改密成功前不允许进入管理面
|
||||
const props = defineProps({ force: { type: Boolean, default: false } })
|
||||
const visible = defineModel({ type: Boolean, default: false })
|
||||
const formRef = ref()
|
||||
const busy = ref(false)
|
||||
const changed = ref(false)
|
||||
const form = reactive({ oldPwd: '', newPwd: '', newPwd2: '' })
|
||||
|
||||
const rules = {
|
||||
oldPwd: { required: true, message: '请输入原密码' },
|
||||
newPwd: [
|
||||
{ required: true, message: '请输入新密码' },
|
||||
{ min: 6, message: '新密码至少 6 位' },
|
||||
{ min: 8, message: '新密码至少 8 位' },
|
||||
{ validator: (_r, v, cb) => (v && v === form.oldPwd ? cb(new Error('新密码不能与原密码相同')) : cb()), message: '新密码不能与原密码相同' },
|
||||
],
|
||||
newPwd2: [
|
||||
@@ -52,11 +60,17 @@ function reset() {
|
||||
formRef.value?.resetFields()
|
||||
}
|
||||
|
||||
function onClosed() {
|
||||
// 强制模式下未改密成功不允许关闭:自动重新打开
|
||||
if (props.force && !changed.value) visible.value = true
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
try { await formRef.value.validate() } catch (_) { return }
|
||||
busy.value = true
|
||||
try {
|
||||
await adminPassword({ account: store.current, old_password: form.oldPwd, new_password: form.newPwd })
|
||||
changed.value = true
|
||||
message.success('密码已修改,下次登录请使用新密码')
|
||||
visible.value = false
|
||||
} catch (e) {
|
||||
@@ -68,6 +82,7 @@ async function submit() {
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.force-tip { margin-bottom: 14px; }
|
||||
.acct-tip { margin-bottom: 16px; }
|
||||
.modal-foot { display: flex; justify-content: flex-end; gap: 10px; }
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
// 统一分页列表 composable:对接后端 page/page_size → {items,total} 契约。
|
||||
//
|
||||
// 统一管理:items/total/page/pageSize/busy 状态 + load/onPageChange/reset 行为;
|
||||
// 自动处理越界回退(删除/筛选后当前页为空时回到最后一页);
|
||||
// 请求竞态控制(快速翻页/切筛选时丢弃过期响应);
|
||||
// 错误统一走 onError 回调(不向上抛),各页面不再各自 try/catch。
|
||||
//
|
||||
// 用法:
|
||||
// const { items: accounts, total, page, size: pageSize, busy, load: refresh, onPageChange, reset } =
|
||||
// usePagedList((p, s) => adminAccounts(p, s), {
|
||||
// onError: e => message.error('读取失败:' + (e.message || e)),
|
||||
// })
|
||||
// 模板中直接使用解构出的 ref(自动解包),PagerBar 绑定 :total :page :page-size @change="onPageChange"。
|
||||
import { ref } from 'vue'
|
||||
|
||||
export function usePagedList(fetcher, opts = {}) {
|
||||
const onError = typeof opts.onError === 'function' ? opts.onError : () => {}
|
||||
const items = ref([])
|
||||
const total = ref(0)
|
||||
const page = ref(1)
|
||||
const size = ref(opts.pageSize || 20)
|
||||
const busy = ref(false)
|
||||
// 响应里除 items/total 外的附加字段(如 today/failed)透传到 meta
|
||||
const meta = ref({})
|
||||
// 请求序号:只接受最后一次发起的响应,丢弃过期响应
|
||||
let seq = 0
|
||||
|
||||
async function load() {
|
||||
const my = ++seq
|
||||
busy.value = true
|
||||
try {
|
||||
const r = await fetcher(page.value, size.value)
|
||||
if (my !== seq) return // 已过期(期间又发起了新请求)
|
||||
items.value = r.items || []
|
||||
total.value = r.total || 0
|
||||
meta.value = r
|
||||
// 越界回退:数据被删/筛选变化导致当前页为空,且总数>0 → 回到最后一页
|
||||
if (!items.value.length && page.value > 1 && total.value > 0) {
|
||||
const last = Math.max(1, Math.ceil(total.value / size.value))
|
||||
if (last !== page.value) {
|
||||
page.value = last
|
||||
return load()
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
if (my === seq) onError(e)
|
||||
} finally {
|
||||
if (my === seq) busy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function onPageChange(p, s) {
|
||||
if (p === page.value && s === size.value) return
|
||||
page.value = p
|
||||
size.value = s
|
||||
load()
|
||||
}
|
||||
|
||||
// 筛选条件/外部数据变化后回到第一页重新加载
|
||||
function reset() {
|
||||
page.value = 1
|
||||
load()
|
||||
}
|
||||
|
||||
return { items, total, page, size, busy, meta, load, onPageChange, reset }
|
||||
}
|
||||
@@ -6,11 +6,17 @@
|
||||
<p>建号 · 部门 / 管理员维护 · 密码重置(不能操作自己的账号)</p>
|
||||
</div>
|
||||
<div class="head-acts">
|
||||
<el-button :loading="overviewBusy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
<el-button :loading="busy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
<el-button type="primary" :icon="Plus" @click="openCreate">新建账号</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 账号搜索(服务端模糊:账号/昵称/部门) -->
|
||||
<div class="search-bar cp-card cp-rise">
|
||||
<el-input v-model="kw" placeholder="搜索账号 / 昵称 / 部门" clearable :prefix-icon="Search" style="width: 300px" @keyup.enter="onSearch" @clear="onSearch" />
|
||||
<span v-if="kw" class="dim-sm">搜索中:{{ kw }}</span>
|
||||
</div>
|
||||
|
||||
<!-- 账号卡片 -->
|
||||
<div class="acct-grid" v-if="accounts.length">
|
||||
<div class="acct-card cp-card cp-rise" v-for="(a, i) in accounts" :key="a.account" :style="{ animationDelay: i * 40 + 'ms' }">
|
||||
@@ -46,8 +52,8 @@
|
||||
|
||||
<div class="acct-tags" v-if="a.plugins?.length">
|
||||
<span class="tag-label">插件</span>
|
||||
<el-tag v-for="p in a.plugins.slice(0, 3)" :key="p" size="small" type="primary" effect="light" round class="mono">{{ p }}</el-tag>
|
||||
<span v-if="a.plugins.length > 3" class="more mono">+{{ a.plugins.length - 3 }}</span>
|
||||
<el-tag v-for="p in a.plugins.slice(0, 2)" :key="p" size="small" type="primary" effect="light" round class="mono">{{ p }}</el-tag>
|
||||
<span v-if="a.plugins.length > 2" class="more mono">+{{ a.plugins.length - 2 }}</span>
|
||||
</div>
|
||||
<div class="acct-tags" v-else>
|
||||
<span class="tag-label">插件</span>
|
||||
@@ -65,7 +71,8 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<el-empty v-else-if="!overviewBusy" description="暂无账号,点击右上角「新建账号」" :image-size="90" class="cp-card" />
|
||||
<el-empty v-else-if="!busy" description="暂无账号,点击右上角「新建账号」" :image-size="90" class="cp-card" />
|
||||
<PagerBar v-if="total > 0" :total="total" :page="page" :page-size="pageSize" @change="onPageChange" />
|
||||
|
||||
<!-- 新建账号 -->
|
||||
<el-dialog v-model="createOpen" title="新建账号" width="440px" align-center destroy-on-close @closed="resetCreate">
|
||||
@@ -77,7 +84,7 @@
|
||||
<el-input v-model="form.nickname" placeholder="真实姓名,方便识别(可填钉钉名)" />
|
||||
</el-form-item>
|
||||
<el-form-item label="初始密码" prop="password">
|
||||
<el-input v-model="form.password" type="password" placeholder="至少 6 位" show-password />
|
||||
<el-input v-model="form.password" type="password" placeholder="至少 8 位" show-password />
|
||||
</el-form-item>
|
||||
<el-form-item label="部门">
|
||||
<el-input v-model="form.dept" placeholder="如 财务部 / IT" />
|
||||
@@ -121,9 +128,9 @@
|
||||
<!-- 重置密码 -->
|
||||
<el-dialog v-model="resetOpen" title="重置密码" width="420px" align-center destroy-on-close>
|
||||
<el-alert type="info" :closable="false" class="reset-tip" show-icon>
|
||||
为账号 <b class="mono">{{ resetTarget }}</b> 设置新密码(至少 6 位)
|
||||
为账号 <b class="mono">{{ resetTarget }}</b> 设置新密码(至少 8 位)
|
||||
</el-alert>
|
||||
<el-input v-model="resetPwdVal" type="password" placeholder="新密码(至少 6 位)" show-password @keyup.enter="confirmReset" />
|
||||
<el-input v-model="resetPwdVal" type="password" placeholder="新密码(至少 8 位)" show-password @keyup.enter="confirmReset" />
|
||||
<template #footer>
|
||||
<div class="modal-foot">
|
||||
<el-button @click="resetOpen = false">取消</el-button>
|
||||
@@ -137,18 +144,19 @@
|
||||
<script setup>
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { ElMessage as message, ElMessageBox as dialog } from 'element-plus'
|
||||
import { Refresh, Plus, Camera, EditPen, Edit, Delete } from '@element-plus/icons-vue'
|
||||
import { store, overview, overviewBusy, loadOverview } from '../store'
|
||||
import { adminAccountCreate, adminAccountUpdate, adminAccountReset, adminAccountDelete, adminAvatarUpload } from '../api'
|
||||
import { Refresh, Plus, Camera, EditPen, Edit, Delete, Search } from '@element-plus/icons-vue'
|
||||
import { store } from '../store'
|
||||
import { adminAccounts, adminAccountCreate, adminAccountUpdate, adminAccountReset, adminAccountDelete, adminAvatarUpload } from '../api'
|
||||
import { fmtTime } from '../format'
|
||||
import PagerBar from '../components/PagerBar.vue'
|
||||
import { usePagedList } from '../composables/usePagedList'
|
||||
|
||||
const current = computed(() => store.current || '')
|
||||
const accounts = computed(() => overview.value?.accounts || [])
|
||||
const kw = ref('')
|
||||
const list = usePagedList((p, s) => adminAccounts(p, s, kw.value), { onError: e => message.error('读取失败:' + (e.message || e)) })
|
||||
const { items: accounts, total, page, size: pageSize, busy, load: refresh, onPageChange, reset } = list
|
||||
const busySwitch = ref('')
|
||||
|
||||
async function refresh() {
|
||||
try { await loadOverview(true) } catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
}
|
||||
function onSearch() { reset() }
|
||||
|
||||
// ---------- 头像(显示 + 上传) ----------
|
||||
const _fileInput = (() => {
|
||||
@@ -188,7 +196,7 @@ const rules = {
|
||||
account: { required: true, message: '请输入账号' },
|
||||
password: [
|
||||
{ required: true, message: '请输入初始密码' },
|
||||
{ min: 6, message: '密码至少 6 位' },
|
||||
{ min: 8, message: '密码至少 8 位' },
|
||||
],
|
||||
}
|
||||
function openCreate() { createOpen.value = true }
|
||||
@@ -244,7 +252,7 @@ function resetPwd(a) {
|
||||
}
|
||||
async function confirmReset() {
|
||||
const p = resetPwdVal.value
|
||||
if (p.length < 6) { message.warning('密码至少 6 位'); return }
|
||||
if (p.length < 8) { message.warning('密码至少 8 位'); return }
|
||||
resetting.value = true
|
||||
try {
|
||||
await adminAccountReset({ account: resetTarget.value, new_password: p })
|
||||
@@ -271,6 +279,7 @@ onMounted(refresh)
|
||||
<style scoped>
|
||||
.head-acts { display: flex; gap: 10px; }
|
||||
|
||||
.search-bar { display: flex; align-items: center; gap: 12px; padding: 14px 18px; margin-bottom: 16px; }
|
||||
.acct-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(330px, 1fr));
|
||||
|
||||
@@ -23,12 +23,12 @@
|
||||
<el-tabs v-model="tab">
|
||||
<el-tab-pane label="操作审计" name="audit">
|
||||
<div class="toolbar">
|
||||
<el-select v-model="actionFilter" clearable placeholder="操作类型" style="width: 150px">
|
||||
<el-select v-model="actionFilter" clearable placeholder="操作类型" style="width: 150px" @change="onAuditFilter">
|
||||
<el-option v-for="(lb, key) in DETAIL_LABEL" :key="key" :label="lb" :value="key" />
|
||||
</el-select>
|
||||
<el-input v-model="search" placeholder="搜索账号 / 对象 / 详情" clearable :prefix-icon="Search" style="width: 240px" />
|
||||
<el-input v-model="search" placeholder="搜索账号 / 对象 / 详情" clearable :prefix-icon="Search" style="width: 240px" @keyup.enter="onAuditFilter" @clear="onAuditFilter" />
|
||||
</div>
|
||||
<el-table :data="filteredAudits" size="small" :row-key="r => r.id">
|
||||
<el-table :data="audits" size="small" v-loading="auditBusy" :row-key="r => r.id">
|
||||
<el-table-column label="时间" width="170">
|
||||
<template #default="{ row }"><span class="mono dim-sm">{{ fmtTime(row.at) }}</span></template>
|
||||
</el-table-column>
|
||||
@@ -55,16 +55,26 @@
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
<PagerBar :total="auditTotal" :page="auditPage" :page-size="auditPageSize" @change="onAuditPage" />
|
||||
</el-tab-pane>
|
||||
|
||||
<el-tab-pane label="运行上报" name="report">
|
||||
<el-table :data="reports" size="small" :row-key="r => r.id">
|
||||
<div class="toolbar">
|
||||
<el-select v-model="statusFilter" clearable placeholder="状态" style="width: 130px" @change="onReportFilter">
|
||||
<el-option label="成功" value="done,success" />
|
||||
<el-option label="失败" value="error,failed" />
|
||||
<el-option label="运行中" value="running" />
|
||||
<el-option label="已触发" value="start" />
|
||||
</el-select>
|
||||
<el-input v-model="reportSearch" placeholder="搜索账号 / 设备 / 插件 / 消息" clearable :prefix-icon="Search" style="width: 260px" @keyup.enter="onReportFilter" @clear="onReportFilter" />
|
||||
</div>
|
||||
<el-table :data="reports" size="small" v-loading="reportBusy" :row-key="r => r.id">
|
||||
<el-table-column label="时间" width="170">
|
||||
<template #default="{ row }"><span class="mono dim-sm">{{ fmtTime(row.at) }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="状态" width="110">
|
||||
<template #default="{ row }">
|
||||
<span class="status-dot"><i :style="{ background: statusColor(row.status) }"></i><span :style="{ color: statusColor(row.status) }">{{ row.status || '—' }}</span></span>
|
||||
<span class="status-dot"><i :style="{ background: statusColor(row.status) }"></i><span :style="{ color: statusColor(row.status) }">{{ statusLabel(row.status) }}</span></span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="账号" width="140">
|
||||
@@ -80,13 +90,13 @@
|
||||
<template #default="{ row }"><span class="mono dim-sm">{{ row.device_id || '—' }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="插件" width="150" show-overflow-tooltip>
|
||||
<template #default="{ row }"><span class="mono">{{ row.plugin_id || '—' }}</span></template>
|
||||
<template #default="{ row }"><span class="mono">{{ row.pluginId || '—' }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="版本" width="90">
|
||||
<template #default="{ row }"><span class="mono">{{ row.version || '—' }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="时长" width="90">
|
||||
<template #default="{ row }"><span class="mono">{{ typeof row.duration_sec === 'number' ? fmtDur(row.duration_sec) : '—' }}</span></template>
|
||||
<template #default="{ row }"><span class="mono">{{ typeof row.durationSec === 'number' ? fmtDur(row.durationSec) : '—' }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="消息" min-width="200" show-overflow-tooltip>
|
||||
<template #default="{ row }">
|
||||
@@ -94,6 +104,7 @@
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
<PagerBar :total="reportTotal" :page="reportPage" :page-size="reportPageSize" @change="onReportPage" />
|
||||
</el-tab-pane>
|
||||
</el-tabs>
|
||||
</div>
|
||||
@@ -102,20 +113,36 @@
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { Refresh, Search, Document, DataLine, CircleCloseFilled, WarningFilled } from '@element-plus/icons-vue'
|
||||
import { Refresh, Search, Document, DataLine, CircleCloseFilled } from '@element-plus/icons-vue'
|
||||
import { ElMessage as message } from 'element-plus'
|
||||
import { adminAudit, adminReports } from '../api'
|
||||
import { fmtTime } from '../format'
|
||||
import PagerBar from '../components/PagerBar.vue'
|
||||
import { usePagedList } from '../composables/usePagedList'
|
||||
|
||||
const tab = ref('audit')
|
||||
const busy = ref(false)
|
||||
const loaded = ref(false)
|
||||
const audits = ref([])
|
||||
const reports = ref([])
|
||||
|
||||
// 两个分页列表(服务端筛选:筛选/搜索条件作为闭包实时传给 fetcher)
|
||||
const actionFilter = ref('')
|
||||
const search = ref('')
|
||||
const statusFilter = ref('')
|
||||
const reportSearch = ref('')
|
||||
|
||||
const auditsList = usePagedList((p, s) => adminAudit(p, s, { action: actionFilter.value, q: search.value }), { onError: e => message.error('读取审计失败:' + (e.message || e)) })
|
||||
const reportsList = usePagedList((p, s) => adminReports(p, s, { status: statusFilter.value, q: reportSearch.value }), { onError: e => message.error('读取上报失败:' + (e.message || e)) })
|
||||
const { items: audits, total: auditTotal, page: auditPage, size: auditPageSize, busy: auditBusy, meta: auditMeta } = auditsList
|
||||
const { items: reports, total: reportTotal, page: reportPage, size: reportPageSize, busy: reportBusy, meta: reportMeta } = reportsList
|
||||
|
||||
const DETAIL_LABEL = {
|
||||
// 新命名(2026-09 服务端重构后)
|
||||
'account-reset-pwd': '重置密码', 'grant-platform': '平台授权', 'revoke-platform': '撤销平台授权',
|
||||
'plugin-publish': '上传发布', 'plugin-delete': '删除插件',
|
||||
'creds-seed': '更新凭证',
|
||||
'file-source-upsert': '登记文件源', 'file-source-patch': '更新文件源', 'file-source-delete': '删除文件源',
|
||||
'shell-release': '发布壳子',
|
||||
// 历史命名(旧版本审计记录兼容)
|
||||
grant: '授权', 'revoke-grant': '撤销授权', 'plugin-patch': '更新插件',
|
||||
'download-ticket': '下载', 'upload-pkg': '上传', 'account-create': '建号',
|
||||
'account-update': '改号', 'account-reset': '重置密码', 'account-delete': '删除',
|
||||
@@ -123,11 +150,18 @@ const DETAIL_LABEL = {
|
||||
}
|
||||
function actType(a) {
|
||||
return { grant: 'primary', 'revoke-grant': 'danger', 'plugin-patch': 'warning',
|
||||
'download-ticket': 'success', 'upload-pkg': 'success', login: 'primary' }[a] || 'info'
|
||||
'download-ticket': 'success', 'upload-pkg': 'success', login: 'primary',
|
||||
'plugin-publish': 'success', 'plugin-delete': 'danger',
|
||||
'grant-platform': 'primary', 'revoke-platform': 'danger',
|
||||
'account-reset-pwd': 'warning', 'creds-seed': 'warning',
|
||||
'shell-release': 'success' }[a] || 'info'
|
||||
}
|
||||
function statusColor(s) {
|
||||
return { start: '#2f5cf0', running: '#2f5cf0', done: '#1d9d5c', success: '#1d9d5c', error: '#d6453d', failed: '#d6453d' }[s] || '#9aa2b4'
|
||||
}
|
||||
function statusLabel(s) {
|
||||
return ({ done: '成功', success: '成功', error: '失败', failed: '失败', running: '运行中', start: '已触发' })[s] || s
|
||||
}
|
||||
function fmtDur(sec) {
|
||||
sec = +sec || 0
|
||||
if (sec < 60) return sec + 's'
|
||||
@@ -136,36 +170,27 @@ function fmtDur(sec) {
|
||||
return `${Math.floor(m / 60)}h${m % 60}m`
|
||||
}
|
||||
|
||||
const kpis = computed(() => {
|
||||
const today = new Date().toISOString().slice(0, 10)
|
||||
const tActs = audits.value.filter(a => (a.at || '').slice(0, 10) === today).length
|
||||
const tReports = reports.value.filter(r => (r.at || '').slice(0, 10) === today).length
|
||||
const fails = reports.value.filter(r => r.status === 'error' || r.status === 'failed').length
|
||||
return [
|
||||
{ label: '审计记录', value: audits.value.length, icon: Document, color: '#2f5cf0', bg: 'linear-gradient(135deg,#e8edfe,#d7e1fd)' },
|
||||
{ label: '今日操作', value: tActs, icon: DataLine, color: '#0f9f9b', bg: 'linear-gradient(135deg,#e4f6f5,#d2efee)' },
|
||||
{ label: '运行上报', value: reports.value.length, icon: DataLine, color: '#7c5cf6', bg: 'linear-gradient(135deg,#f0ebfe,#e4dcfd)' },
|
||||
{ label: '今日上报', value: tReports, icon: DataLine, color: '#d97706', bg: 'linear-gradient(135deg,#fbf0df,#f6e4c8)' },
|
||||
{ label: '上报失败', value: fails, icon: CircleCloseFilled, color: '#d6453d', bg: 'linear-gradient(135deg,#fbe9e8,#f6d8d6)' },
|
||||
]
|
||||
})
|
||||
// KPI 全用后端统计值(total/today/failed),不依赖当前页 slice,保证分页后口径不变
|
||||
const kpis = computed(() => [
|
||||
{ label: '审计记录', value: auditTotal.value, icon: Document, color: '#2f5cf0', bg: 'linear-gradient(135deg,#e8edfe,#d7e1fd)' },
|
||||
{ label: '今日操作', value: auditMeta.value.today || 0, icon: DataLine, color: '#0f9f9b', bg: 'linear-gradient(135deg,#e4f6f5,#d2efee)' },
|
||||
{ label: '运行上报', value: reportTotal.value, icon: DataLine, color: '#7c5cf6', bg: 'linear-gradient(135deg,#f0ebfe,#e4dcfd)' },
|
||||
{ label: '今日上报', value: reportMeta.value.today || 0, icon: DataLine, color: '#d97706', bg: 'linear-gradient(135deg,#fbf0df,#f6e4c8)' },
|
||||
{ label: '上报失败', value: reportMeta.value.failed || 0, icon: CircleCloseFilled, color: '#d6453d', bg: 'linear-gradient(135deg,#fbe9e8,#f6d8d6)' },
|
||||
])
|
||||
|
||||
const filteredAudits = computed(() => {
|
||||
let list = audits.value
|
||||
if (actionFilter.value) list = list.filter(a => a.action === actionFilter.value)
|
||||
const kw = search.value.trim().toLowerCase()
|
||||
if (kw) list = list.filter(a => [a.account, a.nickname, a.target, a.detail].join(' ').toLowerCase().includes(kw))
|
||||
return list
|
||||
})
|
||||
// 筛选变化 → 回到第一页(服务端重新查询)
|
||||
function onAuditFilter() { auditsList.reset() }
|
||||
function onReportFilter() { reportsList.reset() }
|
||||
function onAuditPage(p, s) { auditsList.onPageChange(p, s) }
|
||||
function onReportPage(p, s) { reportsList.onPageChange(p, s) }
|
||||
|
||||
async function refresh() {
|
||||
busy.value = true
|
||||
try {
|
||||
const [a, r] = await Promise.all([adminAudit(), adminReports()])
|
||||
audits.value = a.auditlogs || []
|
||||
reports.value = r.reports || []
|
||||
await Promise.all([auditsList.load(), reportsList.load()])
|
||||
loaded.value = true
|
||||
} catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
} catch (_) { /* 子加载器已提示 */ }
|
||||
finally { busy.value = false }
|
||||
}
|
||||
onMounted(refresh)
|
||||
|
||||
@@ -10,9 +10,9 @@
|
||||
|
||||
<div class="cp-card panel cp-rise">
|
||||
<el-table :data="rows" v-loading="busy" size="default" style="width: 100%">
|
||||
<el-table-column prop="account" label="执行机账号" width="150">
|
||||
<el-table-column prop="account" label="执行机账号" width="180">
|
||||
<template #default="{ row }">
|
||||
<span class="mono">{{ row.account }}</span>
|
||||
<span class="mono">{{ row.nickname ? `${row.nickname} · ${row.account}` : row.account }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="公钥" width="90">
|
||||
@@ -37,6 +37,7 @@
|
||||
<el-empty description="暂无账号,客户端启动注册后自动出现" :image-size="80" />
|
||||
</template>
|
||||
</el-table>
|
||||
<PagerBar :total="total" :page="page" :page-size="pageSize" @change="onPageChange" />
|
||||
</div>
|
||||
|
||||
<el-dialog v-model="dlg" :title="`编辑凭证 · ${editing?.account || ''}`" width="540px">
|
||||
@@ -61,6 +62,8 @@ import { onMounted, ref } from 'vue'
|
||||
import { Refresh, EditPen } from '@element-plus/icons-vue'
|
||||
import { ElMessage as message } from 'element-plus'
|
||||
import { adminCredsList, adminCredsSeed } from '../api'
|
||||
import PagerBar from '../components/PagerBar.vue'
|
||||
import { usePagedList } from '../composables/usePagedList'
|
||||
|
||||
const KEY_COLS = [
|
||||
{ key: 'DINGTALK_APPKEY', label: 'AppKey' },
|
||||
@@ -70,22 +73,13 @@ const KEY_COLS = [
|
||||
]
|
||||
|
||||
const keyCols = KEY_COLS
|
||||
const busy = ref(false)
|
||||
const rows = ref([])
|
||||
const list = usePagedList((p, s) => adminCredsList(p, s), { onError: e => message.error('读取失败:' + (e.message || e)) })
|
||||
const { items: rows, total, page, size: pageSize, busy, load: refresh, onPageChange } = list
|
||||
const dlg = ref(false)
|
||||
const saving = ref(false)
|
||||
const editing = ref(null)
|
||||
const form = ref({})
|
||||
|
||||
async function refresh() {
|
||||
busy.value = true
|
||||
try {
|
||||
const r = await adminCredsList()
|
||||
rows.value = r.accounts || []
|
||||
} catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
finally { busy.value = false }
|
||||
}
|
||||
|
||||
function openEdit(row) {
|
||||
editing.value = row
|
||||
form.value = {}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
<p>内网大文件(壳子/Chrome 等)直链登记。中心机只存链接,文件本身走内网文件服务器</p>
|
||||
</div>
|
||||
<div class="head-actions">
|
||||
<el-select v-model="filter" placeholder="按分类过滤" style="width: 150px" clearable @change="refresh">
|
||||
<el-select v-model="filter" placeholder="按分类过滤" style="width: 150px" clearable @change="onFilterChange">
|
||||
<el-option v-for="c in categories" :key="c" :label="c" :value="c" />
|
||||
</el-select>
|
||||
<el-button :loading="busy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
@@ -57,6 +57,7 @@
|
||||
<el-empty description="暂无登记的大文件源" :image-size="80" />
|
||||
</template>
|
||||
</el-table>
|
||||
<PagerBar :total="total" :page="page" :page-size="pageSize" @change="onPageChange" />
|
||||
</div>
|
||||
|
||||
<el-dialog v-model="dlg" title="登记内网直链" width="560px">
|
||||
@@ -96,32 +97,30 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { onMounted, ref, watch } from 'vue'
|
||||
import { Refresh, Plus, Delete } from '@element-plus/icons-vue'
|
||||
import { ElMessage as message, ElMessageBox } from 'element-plus'
|
||||
import { adminFileSources, adminFileSourceCreate, adminFileSourcePatch, adminFileSourceDelete } from '../api'
|
||||
import PagerBar from '../components/PagerBar.vue'
|
||||
import { usePagedList } from '../composables/usePagedList'
|
||||
|
||||
const CATS = ['shell', 'chrome']
|
||||
const categories = CATS
|
||||
const busy = ref(false)
|
||||
const rows = ref([])
|
||||
const filter = ref('')
|
||||
const list = usePagedList((p, s) => adminFileSources(filter.value || '', p, s), { onError: e => message.error('读取失败:' + (e.message || e)) })
|
||||
const { items: rows, total, page, size: pageSize, busy, load: refresh, onPageChange, reset } = list
|
||||
const dlg = ref(false)
|
||||
const saving = ref(false)
|
||||
const form = ref({})
|
||||
|
||||
async function refresh() {
|
||||
busy.value = true
|
||||
try {
|
||||
const r = await adminFileSources(filter.value || '')
|
||||
rows.value = r.files || []
|
||||
const seen = new Set(CATS)
|
||||
;(r.files || []).forEach((f) => seen.add(f.category))
|
||||
categories.length = 0
|
||||
;[...seen].sort().forEach((c) => categories.push(c))
|
||||
} catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
finally { busy.value = false }
|
||||
}
|
||||
function onFilterChange() { reset() }
|
||||
// 分类下拉:由当前页数据补充实际出现的分类
|
||||
watch(rows, () => {
|
||||
const seen = new Set(CATS)
|
||||
;(rows.value || []).forEach((f) => seen.add(f.category))
|
||||
categories.length = 0
|
||||
;[...seen].sort().forEach((c) => categories.push(c))
|
||||
})
|
||||
|
||||
function catType(c) {
|
||||
return { shell: 'success', chrome: 'warning' }[c] || 'info'
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<h3>权限授权 <span class="badge">Grants</span></h3>
|
||||
<p>按账号勾选可用插件与可登录平台,保存时仅提交差异项</p>
|
||||
</div>
|
||||
<el-button :loading="overviewBusy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
<el-button :loading="grantDataBusy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
</div>
|
||||
|
||||
<div class="cp-card panel cp-rise">
|
||||
@@ -25,10 +25,13 @@
|
||||
<div class="section">
|
||||
<div class="section-head">
|
||||
<div class="card-title">插件授权</div>
|
||||
<el-checkbox :model-value="allChecked" :indeterminate="someChecked" @change="toggleAll">全选</el-checkbox>
|
||||
<div class="gh-sec-right">
|
||||
<el-input v-model="pluginKw" placeholder="搜索插件 ID / 名称" clearable :prefix-icon="Search" size="small" style="width: 210px" />
|
||||
<el-checkbox :model-value="allChecked" :indeterminate="someChecked" @change="toggleAll">全选</el-checkbox>
|
||||
</div>
|
||||
</div>
|
||||
<el-checkbox-group v-model="grantedIds" class="plist">
|
||||
<div class="prow" v-for="p in plugins" :key="p.id" :class="{ on: grantedIds.includes(p.id) }">
|
||||
<el-checkbox-group v-model="grantedIds" class="plist" v-loading="grantsBusy">
|
||||
<div class="prow" v-for="p in visiblePlugins" :key="p.id" :class="{ on: grantedIds.includes(p.id) }">
|
||||
<el-checkbox :value="p.id" class="pck">
|
||||
<span class="pname mono">{{ p.id }}</span>
|
||||
<span class="psub dim">{{ p.name }}</span>
|
||||
@@ -45,7 +48,7 @@
|
||||
</div>
|
||||
</div>
|
||||
</el-checkbox-group>
|
||||
<el-empty v-if="!plugins.length" description="暂无插件,请先在「插件管理」上传" :image-size="60" />
|
||||
<el-empty v-if="!visiblePlugins.length" description="暂无插件,请先在「插件管理」上传" :image-size="60" />
|
||||
</div>
|
||||
|
||||
<!-- 平台授权 -->
|
||||
@@ -82,19 +85,28 @@
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { Refresh, User, Check } from '@element-plus/icons-vue'
|
||||
import { Refresh, Search, User, Check } from '@element-plus/icons-vue'
|
||||
import { ElMessage as message } from 'element-plus'
|
||||
import { overview, overviewBusy, loadOverview } from '../store'
|
||||
import { adminGrant, adminPlatformGrant, adminPlatforms } from '../api'
|
||||
import { adminGrant, adminPlatformGrant, adminPlatforms, adminGrantData, adminAccountGrants } from '../api'
|
||||
|
||||
const PLATFORM_OPTS = ref([])
|
||||
const grantDataBusy = ref(false)
|
||||
const grantsBusy = ref(false)
|
||||
|
||||
const plugins = computed(() => overview.value?.plugins || [])
|
||||
const accounts = computed(() => overview.value?.accounts || [])
|
||||
// 轻量数据源(/grant_data 一次查询,不依赖 overview 全量聚合)
|
||||
const plugins = ref([]) // {id,name,status}
|
||||
const accounts = ref([]) // {account,nickname,dept,status}
|
||||
const accountOptions = computed(() => accounts.value.map(a => ({
|
||||
label: a.dept ? `${a.account} · ${a.dept}` : a.account,
|
||||
label: [a.nickname, a.account, a.dept].filter(Boolean).join(' · '),
|
||||
value: a.account,
|
||||
})))
|
||||
// 插件搜索(数据为全量,前端过滤安全)
|
||||
const pluginKw = ref('')
|
||||
const visiblePlugins = computed(() => {
|
||||
const kw = pluginKw.value.trim().toLowerCase()
|
||||
if (!kw) return plugins.value
|
||||
return plugins.value.filter(p => [p.id, p.name].join(' ').toLowerCase().includes(kw))
|
||||
})
|
||||
|
||||
const account = ref('')
|
||||
const grantedIds = ref([])
|
||||
@@ -111,26 +123,38 @@ function setGrant(pid, patch) {
|
||||
function canRun(pid) { return grantState.value[pid]?.canRun !== false }
|
||||
function canDownload(pid) { return grantState.value[pid]?.canDownload !== false }
|
||||
|
||||
// 全选 / 半选
|
||||
const allChecked = computed(() => plugins.value.length > 0 && grantedIds.value.length === plugins.value.length)
|
||||
const someChecked = computed(() => grantedIds.value.length > 0 && !allChecked.value)
|
||||
// 全选 / 半选(基于当前可见插件:搜索后全选 = 全选搜索结果)
|
||||
const allChecked = computed(() => visiblePlugins.value.length > 0 &&
|
||||
visiblePlugins.value.every(p => grantedIds.value.includes(p.id)))
|
||||
const someChecked = computed(() => visiblePlugins.value.some(p => grantedIds.value.includes(p.id)) && !allChecked.value)
|
||||
function toggleAll(v) {
|
||||
grantedIds.value = v ? plugins.value.map(p => p.id) : []
|
||||
const visible = visiblePlugins.value.map(p => p.id)
|
||||
grantedIds.value = v
|
||||
? [...new Set([...grantedIds.value, ...visible])]
|
||||
: grantedIds.value.filter(id => !visible.includes(id))
|
||||
}
|
||||
|
||||
// 选中账号即自动载入其现有授权
|
||||
watch(account, (acc) => {
|
||||
const a = accounts.value.find(x => x.account === acc)
|
||||
const state = {}
|
||||
;(a?.plugins || []).forEach(pid => {
|
||||
const g = a?.grants?.[pid] || {}
|
||||
state[pid] = { granted: true, canRun: g.canRun !== false, canDownload: g.canDownload !== false }
|
||||
})
|
||||
heldGrantState = JSON.parse(JSON.stringify(state))
|
||||
grantState.value = JSON.parse(JSON.stringify(state))
|
||||
grantedIds.value = [...(a?.plugins || [])]
|
||||
heldPlatforms = new Set(a?.platforms || [])
|
||||
platChecked.value = [...heldPlatforms]
|
||||
// 选中账号即拉取其现有授权(按账号 2 次查询,无 N+1)
|
||||
watch(account, async (acc) => {
|
||||
if (!acc) {
|
||||
grantState.value = {}; grantedIds.value = []; platChecked.value = []
|
||||
heldGrantState = {}; heldPlatforms = new Set()
|
||||
return
|
||||
}
|
||||
grantsBusy.value = true
|
||||
try {
|
||||
const r = await adminAccountGrants(acc)
|
||||
const state = {}
|
||||
;(r.plugins || []).forEach(g => {
|
||||
state[g.plugin_id] = { granted: true, canRun: g.canRun !== false, canDownload: g.canDownload !== false }
|
||||
})
|
||||
heldGrantState = JSON.parse(JSON.stringify(state))
|
||||
grantState.value = JSON.parse(JSON.stringify(state))
|
||||
grantedIds.value = [...(r.plugins || []).map(g => g.plugin_id)]
|
||||
heldPlatforms = new Set(r.platforms || [])
|
||||
platChecked.value = [...heldPlatforms]
|
||||
} catch (e) { message.error('读取授权失败:' + (e.message || e)) }
|
||||
finally { grantsBusy.value = false }
|
||||
})
|
||||
|
||||
// 勾选/取消勾选插件时同步 granted 状态
|
||||
@@ -165,13 +189,14 @@ const platDirty = computed(() => {
|
||||
const dirtyCount = computed(() => pluginDirty.value.length + platDirty.value.length)
|
||||
|
||||
async function refresh() {
|
||||
try { await loadOverview(true) } catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
}
|
||||
async function loadPlatforms() {
|
||||
grantDataBusy.value = true
|
||||
try {
|
||||
const r = await adminPlatforms()
|
||||
PLATFORM_OPTS.value = (r.platforms || []).map(p => ({ id: p.id, label: p.label }))
|
||||
} catch (e) { message.error('平台列表读取失败:' + (e.message || e)) }
|
||||
const [gd, pf] = await Promise.all([adminGrantData(), adminPlatforms()])
|
||||
plugins.value = gd.plugins || []
|
||||
accounts.value = gd.accounts || []
|
||||
PLATFORM_OPTS.value = (pf.platforms || []).map(p => ({ id: p.id, label: p.label }))
|
||||
} catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
finally { grantDataBusy.value = false }
|
||||
}
|
||||
|
||||
async function savePluginDiff() {
|
||||
@@ -216,7 +241,7 @@ async function saveAll() {
|
||||
} catch (e) { message.error('保存失败:' + (e.message || e)) }
|
||||
finally { saving.value = false }
|
||||
}
|
||||
onMounted(() => { refresh(); loadPlatforms() })
|
||||
onMounted(refresh)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
@@ -230,6 +255,7 @@ onMounted(() => { refresh(); loadPlatforms() })
|
||||
.section { margin-top: 24px; }
|
||||
.section-head { display: flex; justify-content: space-between; align-items: center; margin-bottom: 14px; }
|
||||
.section-head .card-title { margin-bottom: 0; }
|
||||
.gh-sec-right { display: flex; align-items: center; gap: 14px; }
|
||||
|
||||
/* 插件授权行 */
|
||||
.plist { display: flex; flex-direction: column; gap: 8px; }
|
||||
|
||||
@@ -8,18 +8,56 @@
|
||||
<el-button :loading="overviewBusy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
</div>
|
||||
|
||||
<div class="stat-grid" v-if="ov">
|
||||
<div class="stat-card cp-card cp-rise" v-for="(s, i) in stats" :key="s.label" :class="{ wide: s.wide }" :style="{ animationDelay: i * 60 + 'ms' }">
|
||||
<div class="stat-ic" :style="{ background: s.bg, color: s.color }">
|
||||
<el-icon :size="20"><component :is="s.icon" /></el-icon>
|
||||
<template v-if="ov">
|
||||
<!-- 统计卡(4 列,与下方图表区对齐) -->
|
||||
<div class="stat-grid">
|
||||
<div class="stat-card cp-card cp-rise" v-for="(s, i) in stats" :key="s.label" :style="{ animationDelay: i * 60 + 'ms' }">
|
||||
<div class="stat-ic" :style="{ background: s.bg, color: s.color }">
|
||||
<el-icon :size="20"><component :is="s.icon" /></el-icon>
|
||||
</div>
|
||||
<div class="stat-meta">
|
||||
<div class="stat-num mono">{{ s.value }}</div>
|
||||
<div class="stat-label">{{ s.label }}</div>
|
||||
</div>
|
||||
<span class="stat-glow" :style="{ background: s.color }"></span>
|
||||
</div>
|
||||
<div class="stat-meta">
|
||||
<div class="stat-num mono" :class="{ sm: s.small }">{{ s.value }}</div>
|
||||
<div class="stat-label">{{ s.label }}</div>
|
||||
</div>
|
||||
<span class="stat-glow" :style="{ background: s.color }"></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 图表区(两列独立高度,不拉伸) -->
|
||||
<div class="ov-grid">
|
||||
<div class="cp-card cp-rise chart-card">
|
||||
<div class="card-title">插件状态分布 <span class="sub">已发布 / 停用 / 已撤销</span></div>
|
||||
<div ref="pieEl" class="pie-chart"></div>
|
||||
<div class="pie-legend">
|
||||
<span v-for="c in pieLegend" :key="c.name">
|
||||
<i :style="{ background: c.color }"></i>{{ c.name }} <b class="mono">{{ c.value }}</b>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="cp-card cp-rise chart-card">
|
||||
<div class="card-title">授权覆盖 <span class="sub">已授权插件账号 / 账号总数</span></div>
|
||||
<div ref="gaugeEl" class="gauge-chart"></div>
|
||||
<div class="gauge-num mono">
|
||||
<b>{{ authCount }}</b><span class="dim"> / {{ (ov.accounts || []).length }} 个账号已授权插件</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 最近动态 -->
|
||||
<div class="page-head sub cp-rise">
|
||||
<div><h4>最近动态</h4></div>
|
||||
</div>
|
||||
<div class="cp-card cp-rise feed-card">
|
||||
<div class="feed-item" v-for="v in recentUploads" :key="v.key">
|
||||
<span class="feed-dot"></span>
|
||||
<span class="feed-text mono">{{ v.plugin }}</span>
|
||||
<el-tag size="small" effect="plain" round type="primary" class="mono">v{{ v.version }}</el-tag>
|
||||
<span class="feed-time mono dim-sm">{{ fmtTime(v.uploaded_at) }}</span>
|
||||
</div>
|
||||
<div v-if="!recentUploads.length" class="empty">暂无上传记录</div>
|
||||
</div>
|
||||
</template>
|
||||
<el-skeleton v-else-if="overviewBusy" animated :rows="3" style="margin-top: 20px" />
|
||||
|
||||
<div class="tip-card cp-card cp-rise">
|
||||
@@ -33,9 +71,16 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted } from 'vue'
|
||||
import { Refresh, InfoFilled, Box, Collection, User, UserFilled, UploadFilled } from '@element-plus/icons-vue'
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { Refresh, InfoFilled, Box, Collection, User, UserFilled } from '@element-plus/icons-vue'
|
||||
import { ElMessage as message } from 'element-plus'
|
||||
// ECharts 按需引入(环图)
|
||||
import * as echarts from 'echarts/core'
|
||||
import { PieChart } from 'echarts/charts'
|
||||
import { TooltipComponent, LegendComponent } from 'echarts/components'
|
||||
import { CanvasRenderer } from 'echarts/renderers'
|
||||
echarts.use([PieChart, TooltipComponent, LegendComponent, CanvasRenderer])
|
||||
|
||||
import { store, overview, overviewBusy, loadOverview } from '../store'
|
||||
import { fmtTime } from '../format'
|
||||
|
||||
@@ -47,56 +92,115 @@ const stats = computed(() => {
|
||||
{ label: '版本总数', value: plugins.reduce((n, p) => n + (p.versions?.length || 0), 0), icon: Collection, color: '#7c5cf6', bg: 'linear-gradient(135deg,#f0ebfe,#e4dcfd)' },
|
||||
{ label: '账号', value: (ov.value?.accounts || []).length, icon: User, color: '#0f9f9b', bg: 'linear-gradient(135deg,#e4f6f5,#d2efee)' },
|
||||
{ label: '管理员', value: (ov.value?.admins || []).length, icon: UserFilled, color: '#1d9d5c', bg: 'linear-gradient(135deg,#e5f6ed,#d2efe0)' },
|
||||
{ label: '最近上传', value: latest(), icon: UploadFilled, color: '#d97706', bg: 'linear-gradient(135deg,#fbf0df,#f6e4c8)', small: true, wide: true },
|
||||
]
|
||||
})
|
||||
function latest() {
|
||||
const all = (ov.value?.plugins || []).flatMap(p => p.versions || []).map(v => v.uploaded_at).filter(Boolean)
|
||||
if (!all.length) return '—'
|
||||
return fmtTime(all.sort().at(-1))
|
||||
|
||||
// 最近上传(按时间倒序取 6 条)
|
||||
const recentUploads = computed(() => {
|
||||
const items = []
|
||||
for (const p of ov.value?.plugins || []) {
|
||||
for (const v of p.versions || []) {
|
||||
items.push({ key: p.id + v.version, plugin: p.id, version: v.version, uploaded_at: v.uploaded_at })
|
||||
}
|
||||
}
|
||||
return items.filter(i => i.uploaded_at).sort((a, b) => (a.uploaded_at < b.uploaded_at ? 1 : -1)).slice(0, 6)
|
||||
})
|
||||
|
||||
const authCount = computed(() => (ov.value?.accounts || []).filter(a => a.plugins?.length).length)
|
||||
const pieLegend = computed(() => [
|
||||
{ name: '已发布', color: '#1d9d5c', value: countStatus('published') },
|
||||
{ name: '停用', color: '#d97706', value: countStatus('disabled') },
|
||||
{ name: '已撤销', color: '#d6453d', value: countStatus('revoked') },
|
||||
])
|
||||
function countStatus(s) { return (ov.value?.plugins || []).filter(p => p.status === s).length }
|
||||
|
||||
// ---------- ECharts ----------
|
||||
const pieEl = ref(null)
|
||||
const gaugeEl = ref(null)
|
||||
let pieChart = null
|
||||
let gaugeChart = null
|
||||
|
||||
function renderCharts() {
|
||||
if (!ov.value) return
|
||||
const pieData = pieLegend.value.filter(c => c.value > 0)
|
||||
if (pieEl.value) {
|
||||
if (!pieChart) pieChart = echarts.init(pieEl.value)
|
||||
pieChart.setOption({
|
||||
tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
|
||||
series: [{
|
||||
type: 'pie', radius: ['58%', '78%'], center: ['50%', '50%'],
|
||||
avoidLabelOverlap: true,
|
||||
itemStyle: { borderRadius: 6, borderColor: '#fffdf8', borderWidth: 2 },
|
||||
label: { show: false }, emphasis: { label: { show: false } },
|
||||
data: pieData.map(c => ({ name: c.name, value: c.value, itemStyle: { color: c.color } })),
|
||||
}],
|
||||
})
|
||||
}
|
||||
const acc = (ov.value.accounts || []).length
|
||||
const authed = authCount.value
|
||||
const rate = acc ? Math.round(authed / acc * 100) : 0
|
||||
if (gaugeEl.value) {
|
||||
if (!gaugeChart) gaugeChart = echarts.init(gaugeEl.value)
|
||||
gaugeChart.setOption({
|
||||
series: [{
|
||||
type: 'pie', radius: ['62%', '80%'], center: ['50%', '50%'],
|
||||
silent: true,
|
||||
label: { show: true, position: 'center', formatter: rate + '%', fontSize: 26, fontWeight: 800, color: '#232a3a' },
|
||||
data: [
|
||||
{ value: authed, itemStyle: { color: '#2f5cf0' } },
|
||||
{ value: acc - authed, itemStyle: { color: 'rgba(35,42,58,.08)' } },
|
||||
],
|
||||
}],
|
||||
})
|
||||
}
|
||||
}
|
||||
// immediate:overview 有缓存(store 模块级)且 force 重拉失败时,ov 不变化也能渲染已有数据
|
||||
watch(ov, () => nextTick(renderCharts), { immediate: true })
|
||||
const onResize = () => { pieChart && pieChart.resize(); gaugeChart && gaugeChart.resize() }
|
||||
|
||||
async function refresh() {
|
||||
try { await loadOverview(true) } catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
}
|
||||
onMounted(refresh)
|
||||
onMounted(() => { refresh(); window.addEventListener('resize', onResize) })
|
||||
onBeforeUnmount(() => { window.removeEventListener('resize', onResize); pieChart && pieChart.dispose(); gaugeChart && gaugeChart.dispose(); pieChart = gaugeChart = null })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.stat-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(236px, 1fr));
|
||||
gap: 18px;
|
||||
}
|
||||
.stat-card {
|
||||
display: flex; align-items: center; gap: 16px;
|
||||
padding: 20px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.stat-card.wide { grid-column: span 2; }
|
||||
.stat-ic {
|
||||
width: 48px; height: 48px; border-radius: 14px; flex-shrink: 0;
|
||||
display: grid; place-items: center;
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .7);
|
||||
}
|
||||
.stat-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 18px; }
|
||||
@media (max-width: 1100px) { .stat-grid { grid-template-columns: repeat(2, 1fr); } }
|
||||
.stat-card { display: flex; align-items: center; gap: 16px; padding: 20px; overflow: hidden; }
|
||||
.stat-ic { width: 48px; height: 48px; border-radius: 14px; flex-shrink: 0; display: grid; place-items: center; box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .7); }
|
||||
.stat-meta { min-width: 0; }
|
||||
.stat-num { font-size: 27px; font-weight: 800; letter-spacing: .3px; line-height: 1.15; color: var(--cp-ink-1); }
|
||||
.stat-num.sm { font-size: 18px; font-weight: 700; white-space: nowrap; line-height: 1.4; }
|
||||
.stat-label { font-size: 12px; color: var(--cp-ink-3); margin-top: 4px; letter-spacing: .3px; }
|
||||
.stat-glow { position: absolute; left: 0; top: 0; bottom: 0; width: 3px; border-radius: 0 6px 6px 0; opacity: .9; }
|
||||
|
||||
.tip-card {
|
||||
margin-top: 20px;
|
||||
display: flex; gap: 14px;
|
||||
padding: 20px 22px;
|
||||
background: linear-gradient(135deg, rgba(47, 92, 240, .05), rgba(15, 159, 155, .04)), var(--cp-panel);
|
||||
}
|
||||
.tip-ic {
|
||||
width: 40px; height: 40px; border-radius: 12px; flex-shrink: 0;
|
||||
display: grid; place-items: center;
|
||||
background: linear-gradient(135deg, var(--cp-blue), var(--cp-teal));
|
||||
color: #fff;
|
||||
box-shadow: 0 8px 16px -8px rgba(47, 92, 240, .6);
|
||||
}
|
||||
/* 图表区两列独立高度 */
|
||||
.ov-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 18px; margin: 18px 0 0; align-items: start; }
|
||||
@media (max-width: 1100px) { .ov-grid { grid-template-columns: 1fr; } }
|
||||
.chart-card { padding: 20px; }
|
||||
.card-title { margin-bottom: 10px; }
|
||||
.card-title .sub { font-size: 11px; font-weight: 500; color: var(--cp-ink-3); margin-left: 4px; }
|
||||
.pie-chart { height: 210px; }
|
||||
.gauge-chart { height: 210px; }
|
||||
.pie-legend { display: flex; justify-content: center; gap: 20px; margin-top: 4px; font-size: 12.5px; color: var(--cp-ink-2); }
|
||||
.pie-legend i { width: 10px; height: 10px; border-radius: 3px; display: inline-block; margin-right: 6px; }
|
||||
.pie-legend b { margin-left: 3px; color: var(--cp-ink-1); }
|
||||
.gauge-num { text-align: center; margin-top: 2px; font-size: 13px; color: var(--cp-ink-2); }
|
||||
.gauge-num b { font-size: 20px; color: var(--cp-blue); }
|
||||
|
||||
.page-head.sub h4 { margin: 0; font-size: 15px; font-weight: 800; color: var(--cp-ink-1); }
|
||||
.feed-card { padding: 8px 18px; }
|
||||
.feed-item { display: flex; align-items: center; gap: 10px; padding: 9px 0; border-bottom: 1px dashed var(--cp-line); }
|
||||
.feed-item:last-child { border-bottom: none; }
|
||||
.feed-dot { width: 8px; height: 8px; border-radius: 50%; background: linear-gradient(135deg, var(--cp-blue), var(--cp-teal)); flex: none; }
|
||||
.feed-text { font-size: 13px; color: var(--cp-ink-1); min-width: 120px; }
|
||||
.feed-time { margin-left: auto; }
|
||||
.empty { color: var(--cp-ink-3); font-size: 12px; padding: 14px 0; text-align: center; }
|
||||
|
||||
.tip-card { margin-top: 20px; display: flex; gap: 14px; padding: 20px 22px; background: linear-gradient(135deg, rgba(47, 92, 240, .05), rgba(15, 159, 155, .04)), var(--cp-panel); }
|
||||
.tip-ic { width: 40px; height: 40px; border-radius: 12px; flex-shrink: 0; display: grid; place-items: center; background: linear-gradient(135deg, var(--cp-blue), var(--cp-teal)); color: #fff; box-shadow: 0 8px 16px -8px rgba(47, 92, 240, .6); }
|
||||
.tip-body b { display: block; font-size: 14px; color: var(--cp-ink-1); margin-bottom: 5px; }
|
||||
.tip-body p { margin: 0; font-size: 12.5px; line-height: 1.8; color: var(--cp-ink-2); }
|
||||
.dim-sm { color: var(--cp-ink-3); font-size: 12px; }
|
||||
</style>
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<h3>插件管理 <span class="badge">Plugins</span></h3>
|
||||
<p>上传发布插件包 · 每插件保留最近 3 个版本,超出自动清理</p>
|
||||
</div>
|
||||
<el-button :loading="overviewBusy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
<el-button :loading="listBusy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
</div>
|
||||
|
||||
<div class="cp-card block cp-rise up-card">
|
||||
@@ -38,8 +38,11 @@
|
||||
</div>
|
||||
|
||||
<div class="cp-card block cp-rise list-card">
|
||||
<div class="card-title">插件列表</div>
|
||||
<el-table :data="plugins" size="small" :loading="overviewBusy" :row-key="r => r.id">
|
||||
<div class="list-head">
|
||||
<div class="card-title">插件列表</div>
|
||||
<el-input v-model="kw" placeholder="搜索插件 ID / 名称" clearable :prefix-icon="Search" size="small" style="width: 230px" @keyup.enter="onSearch" @clear="onSearch" />
|
||||
</div>
|
||||
<el-table :data="plugins" size="small" :loading="listBusy" :row-key="r => r.id">
|
||||
<el-table-column label="插件 ID" min-width="160">
|
||||
<template #default="{ row }"><b class="cell-strong mono">{{ row.id }}</b></template>
|
||||
</el-table-column>
|
||||
@@ -70,6 +73,7 @@
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
<PagerBar :total="total" :page="page" :page-size="pageSize" @change="onPageChange" />
|
||||
</div>
|
||||
|
||||
<!-- 编辑插件 -->
|
||||
@@ -199,7 +203,7 @@
|
||||
<div class="dt-sec">
|
||||
<div class="ed-sec-title">授权账号</div>
|
||||
<div class="tags" v-if="detail.accounts?.length">
|
||||
<el-tag v-for="a in detail.accounts" :key="a" size="small" effect="plain" type="success" round class="mono">{{ a }}</el-tag>
|
||||
<el-tag v-for="a in detail.accounts" :key="a.account" size="small" effect="plain" type="success" round class="mono">{{ a.nickname ? `${a.nickname} · ${a.account}` : a.account }}</el-tag>
|
||||
</div>
|
||||
<span v-else class="dim">未授权任何账号,执行端不可见</span>
|
||||
</div>
|
||||
@@ -213,15 +217,19 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { onMounted, reactive, ref } from 'vue'
|
||||
import { ElMessage as message, ElMessageBox as dialog } from 'element-plus'
|
||||
import { Refresh, UploadFilled, FolderOpened, Edit, Delete, View, Box, Files, User, Clock } from '@element-plus/icons-vue'
|
||||
import { overview, overviewBusy, loadOverview } from '../store'
|
||||
import { adminUpload, adminPluginDelete, adminPluginPatch } from '../api'
|
||||
import { Refresh, UploadFilled, FolderOpened, Edit, Delete, View, Box, Files, User, Clock, Search } from '@element-plus/icons-vue'
|
||||
import { adminPlugins, adminUpload, adminPluginDelete, adminPluginPatch } from '../api'
|
||||
import { fmtTime } from '../format'
|
||||
import PagerBar from '../components/PagerBar.vue'
|
||||
import { usePagedList } from '../composables/usePagedList'
|
||||
|
||||
const plugins = computed(() => overview.value?.plugins || [])
|
||||
const kw = ref('')
|
||||
const list = usePagedList((p, s) => adminPlugins(p, s, kw.value), { onError: e => message.error('读取失败:' + (e.message || e)) })
|
||||
const { items: plugins, total, page, size: pageSize, busy: listBusy, load: refresh, onPageChange, reset } = list
|
||||
const pid = ref(''); const pname = ref(''); const pver = ref(''); const pfile = ref(null)
|
||||
function onSearch() { reset() }
|
||||
const uploading = ref(false)
|
||||
const upRef = ref()
|
||||
|
||||
@@ -286,9 +294,6 @@ async function saveEdit() {
|
||||
finally { saving.value = false }
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
try { await loadOverview(true) } catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
}
|
||||
async function upload() {
|
||||
if (!pid.value || !pver.value || !pfile.value) { message.warning('请填写插件 ID / 版本并选择 ZIP 包'); return }
|
||||
uploading.value = true
|
||||
@@ -317,6 +322,8 @@ onMounted(refresh)
|
||||
<style scoped>
|
||||
.up-card, .list-card { padding: 20px 22px; }
|
||||
.up-card .card-title { margin-bottom: 16px; }
|
||||
.list-head { display: flex; justify-content: space-between; align-items: center; margin-bottom: 14px; }
|
||||
.list-head .card-title { margin-bottom: 0; }
|
||||
.up-form :deep(.el-form-item) { margin-bottom: 16px; }
|
||||
.file-row { display: flex; align-items: center; gap: 10px; }
|
||||
.hint { font-size: 12px; color: var(--cp-ink-3); margin-top: 2px; line-height: 1.7; }
|
||||
|
||||
@@ -2,19 +2,17 @@
|
||||
<div class="page">
|
||||
<div class="page-head cp-rise">
|
||||
<div>
|
||||
<h3>运行统计 <span class="badge">Stats</span></h3>
|
||||
<p>账号 · 插件规模 · 执行次数/时长/成败 · 近 14 天趋势</p>
|
||||
<h3>数据看板 <span class="badge">Stats</span></h3>
|
||||
<p>运行统计 · 近 14 天趋势曲线 · 插件/用户排行 · 最近运行记录(分页)</p>
|
||||
</div>
|
||||
<el-button :loading="busy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
</div>
|
||||
|
||||
<template v-if="st">
|
||||
<!-- 指标卡 -->
|
||||
<!-- KPI -->
|
||||
<div class="kpis cp-rise">
|
||||
<div class="kpi cp-card" v-for="(k, i) in kpis" :key="k.label" :style="{ animationDelay: i * 50 + 'ms' }">
|
||||
<div class="kpi-ic" :style="{ background: k.bg, color: k.color }">
|
||||
<el-icon :size="18"><component :is="k.icon" /></el-icon>
|
||||
</div>
|
||||
<div class="kpi-ic" :style="{ background: k.bg, color: k.color }"><el-icon :size="17"><component :is="k.icon" /></el-icon></div>
|
||||
<div class="kpi-meta">
|
||||
<div class="kpi-num mono" :style="{ color: k.color }">{{ k.value }}</div>
|
||||
<div class="kpi-lab">{{ k.label }}</div>
|
||||
@@ -22,68 +20,55 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid">
|
||||
<!-- 近 14 天趋势 -->
|
||||
<div class="cp-card trend-card cp-rise">
|
||||
<div class="card-title">近 14 天运行趋势</div>
|
||||
<div class="trend">
|
||||
<div class="tcol" v-for="d in st.trend" :key="d.day" :title="`${d.day} · ${d.runs} 次(成功 ${d.success} / 失败 ${d.failed})`">
|
||||
<div class="tstack">
|
||||
<div class="tbar failed" :style="{ height: pct(d.failed, maxRuns) + '%' }"></div>
|
||||
<div class="tbar success" :style="{ height: pct(d.success, maxRuns) + '%' }"></div>
|
||||
<!-- 趋势曲线(全宽置顶) -->
|
||||
<div class="cp-card cp-rise chart-card">
|
||||
<div class="card-title">近 14 天运行趋势 <span class="sub">成功 / 失败 · 平滑曲线</span></div>
|
||||
<div ref="trendEl" class="chart"></div>
|
||||
</div>
|
||||
|
||||
<!-- 排行(两列左右分布) -->
|
||||
<div class="rank-grid">
|
||||
<div class="cp-card cp-rise rank-card">
|
||||
<div class="card-title">插件排行 <span class="sub">按触发次数</span></div>
|
||||
<ul class="rank" v-if="st.topPlugins.length">
|
||||
<li v-for="(p, i) in st.topPlugins" :key="p.pluginId">
|
||||
<span class="rk" :class="{ top: i < 3 }">{{ i + 1 }}</span>
|
||||
<div class="rbody">
|
||||
<div class="rhead">
|
||||
<span class="rname">{{ p.name }}</span>
|
||||
<em>{{ p.runs }} 次</em>
|
||||
</div>
|
||||
<div class="rbar"><i :style="{ width: Math.round(p.runs / rankMax(st.topPlugins) * 100) + '%' }"></i></div>
|
||||
</div>
|
||||
<span class="tday mono">{{ d.day }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="trend-legend">
|
||||
<span><i class="dot ok"></i>成功</span>
|
||||
<span><i class="dot fail"></i>失败</span>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
<div v-else class="empty">暂无运行数据</div>
|
||||
</div>
|
||||
|
||||
<!-- 插件 / 用户排行 -->
|
||||
<div class="rank-wrap">
|
||||
<div class="cp-card rank-card cp-rise">
|
||||
<div class="card-title">插件排行 <span class="sub">按运行次数</span></div>
|
||||
<ul class="rank">
|
||||
<li v-for="(p, i) in st.topPlugins" :key="p.pluginId">
|
||||
<span class="rk mono" :class="{ top: i < 3 }">{{ i + 1 }}</span>
|
||||
<div class="rbody">
|
||||
<div class="rhead">
|
||||
<span class="rname mono">{{ p.name || p.pluginId }}</span>
|
||||
<em class="mono">{{ p.runs }} 次</em>
|
||||
</div>
|
||||
<div class="rbar"><i :style="{ width: pct(p.runs, rankMax(st.topPlugins)) + '%' }"></i></div>
|
||||
<div class="cp-card cp-rise rank-card">
|
||||
<div class="card-title">活跃用户 <span class="sub">按执行次数</span></div>
|
||||
<ul class="rank" v-if="st.topUsers.length">
|
||||
<li v-for="(u, i) in st.topUsers" :key="u.account">
|
||||
<span class="rk" :class="{ top: i < 3 }">{{ i + 1 }}</span>
|
||||
<div class="rbody">
|
||||
<div class="rhead">
|
||||
<span class="rname mono">{{ u.nickname ? `${u.nickname} · ${u.account}` : u.account }}</span>
|
||||
<em>{{ u.runs }} 次</em>
|
||||
</div>
|
||||
</li>
|
||||
<li v-if="!st.topPlugins.length" class="empty">暂无运行记录</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="cp-card rank-card cp-rise">
|
||||
<div class="card-title">活跃用户 <span class="sub">按运行次数</span></div>
|
||||
<ul class="rank">
|
||||
<li v-for="(u, i) in st.topUsers" :key="u.account">
|
||||
<span class="rk mono" :class="{ top: i < 3 }">{{ i + 1 }}</span>
|
||||
<div class="rbody">
|
||||
<div class="rhead">
|
||||
<span class="rname mono">{{ u.account }}</span>
|
||||
<em class="mono">{{ u.runs }} 次</em>
|
||||
</div>
|
||||
<div class="rbar"><i :style="{ width: pct(u.runs, rankMax(st.topUsers)) + '%' }"></i></div>
|
||||
</div>
|
||||
</li>
|
||||
<li v-if="!st.topUsers.length" class="empty">暂无运行记录</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="rbar"><i :style="{ width: Math.round(u.runs / rankMax(st.topUsers) * 100) + '%' }"></i></div>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
<div v-else class="empty">暂无执行记录</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 最近运行 -->
|
||||
<!-- 最近运行(后端分页) -->
|
||||
<div class="page-head sub cp-rise">
|
||||
<div><h4>最近运行</h4></div>
|
||||
</div>
|
||||
<div class="cp-card cp-rise recent-card">
|
||||
<el-table :data="st.recent" size="small" :row-key="r => r.at + r.pluginId">
|
||||
<el-table :data="recent" size="small" v-loading="recentBusy" :row-key="r => r.id">
|
||||
<el-table-column label="时间" width="170">
|
||||
<template #default="{ row }"><span class="mono dim-sm">{{ fmtTime(row.at) }}</span></template>
|
||||
</el-table-column>
|
||||
@@ -92,13 +77,9 @@
|
||||
<span class="status-dot"><i :style="{ background: statusColor(row.status) }"></i><span :style="{ color: statusColor(row.status) }">{{ statusLabel(row.status) }}</span></span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="账号" width="140">
|
||||
<el-table-column label="账号" width="150">
|
||||
<template #default="{ row }">
|
||||
<div class="acct" v-if="row.nickname">
|
||||
<div class="ann">{{ row.account }}</div>
|
||||
<div class="anick">{{ row.nickname }}</div>
|
||||
</div>
|
||||
<span v-else>{{ row.account || '—' }}</span>
|
||||
<span class="mono">{{ row.nickname ? `${row.nickname} · ${row.account}` : (row.account || '—') }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="插件" width="160" show-overflow-tooltip>
|
||||
@@ -110,12 +91,11 @@
|
||||
<el-table-column label="时长" width="100">
|
||||
<template #default="{ row }"><span class="mono">{{ fmtDur(row.durationSec) }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="信息" min-width="220" show-overflow-tooltip>
|
||||
<template #default="{ row }">
|
||||
<span :class="{ dim: !row.msg }">{{ row.msg || '—' }}</span>
|
||||
</template>
|
||||
<el-table-column label="信息" min-width="200" show-overflow-tooltip>
|
||||
<template #default="{ row }"><span :class="{ dim: !row.msg }">{{ row.msg || '—' }}</span></template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
<PagerBar :total="recentTotal" :page="page" :page-size="pageSize" @change="onPageChange" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -125,22 +105,37 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { Refresh, User, Box, VideoPlay, CircleCheckFilled, CircleCloseFilled, Timer } from '@element-plus/icons-vue'
|
||||
import { ElMessage as message } from 'element-plus'
|
||||
import { adminStats } from '../api'
|
||||
// ECharts 按需引入(折线图),避免全量包
|
||||
import * as echarts from 'echarts/core'
|
||||
import { LineChart } from 'echarts/charts'
|
||||
import { GridComponent, TooltipComponent, LegendComponent } from 'echarts/components'
|
||||
import { CanvasRenderer } from 'echarts/renderers'
|
||||
echarts.use([LineChart, GridComponent, TooltipComponent, LegendComponent, CanvasRenderer])
|
||||
|
||||
import { adminStats, adminReports } from '../api'
|
||||
import { fmtTime } from '../format'
|
||||
import PagerBar from '../components/PagerBar.vue'
|
||||
|
||||
const busy = ref(false)
|
||||
const st = ref(null)
|
||||
|
||||
// 最近运行:独立走 /api/admin/reports 后端分页(数据增长无压力)
|
||||
import { usePagedList } from '../composables/usePagedList'
|
||||
const recentList = usePagedList((p, s) => adminReports(p, s), { onError: e => message.error('读取失败:' + (e.message || e)) })
|
||||
const { items: recent, total: recentTotal, page, size: pageSize, busy: recentBusy, load: loadRecent, onPageChange } = recentList
|
||||
|
||||
const kpis = computed(() => {
|
||||
if (!st.value) return []
|
||||
const r = st.value
|
||||
// 累计执行 = 成功 + 失败(已完成任务数,口径一致);触发数 start(含运行中/中断残留)不作为累计
|
||||
const finished = (r.runs.success || 0) + (r.runs.failed || 0)
|
||||
return [
|
||||
{ label: '用户总数', value: r.users.total, icon: User, color: '#2f5cf0', bg: 'linear-gradient(135deg,#e8edfe,#d7e1fd)' },
|
||||
{ label: '插件总数', value: r.plugins.total, icon: Box, color: '#7c5cf6', bg: 'linear-gradient(135deg,#f0ebfe,#e4dcfd)' },
|
||||
{ label: '累计执行', value: r.runs.total, icon: VideoPlay, color: '#0f9f9b', bg: 'linear-gradient(135deg,#e4f6f5,#d2efee)' },
|
||||
{ label: '累计执行', value: finished, icon: VideoPlay, color: '#0f9f9b', bg: 'linear-gradient(135deg,#e4f6f5,#d2efee)' },
|
||||
{ label: '成功', value: r.runs.success, icon: CircleCheckFilled, color: '#1d9d5c', bg: 'linear-gradient(135deg,#e5f6ed,#d2efe0)' },
|
||||
{ label: '失败', value: r.runs.failed, icon: CircleCloseFilled, color: '#d6453d', bg: 'linear-gradient(135deg,#fbe9e8,#f6d8d6)' },
|
||||
{ label: '总运行时长', value: fmtDur(r.runs.durationSec), icon: Timer, color: '#d97706', bg: 'linear-gradient(135deg,#fbf0df,#f6e4c8)' },
|
||||
@@ -151,7 +146,7 @@ function statusColor(s) {
|
||||
return { done: '#1d9d5c', success: '#1d9d5c', error: '#d6453d', failed: '#d6453d', running: '#2f5cf0', start: '#2f5cf0' }[s] || '#9aa2b4'
|
||||
}
|
||||
function statusLabel(s) {
|
||||
return (s === 'done' || s === 'success') ? '成功' : (s === 'error' || s === 'failed') ? '失败' : s
|
||||
return ({ done: '成功', success: '成功', error: '失败', failed: '失败', running: '运行中', start: '已触发' })[s] || s
|
||||
}
|
||||
function fmtDur(sec) {
|
||||
sec = +sec || 0
|
||||
@@ -161,10 +156,40 @@ function fmtDur(sec) {
|
||||
const hh = Math.floor(m / 60)
|
||||
return `${hh}h${m % 60}m`
|
||||
}
|
||||
const maxRuns = () => Math.max(1, ...(st.value?.trend || []).map(t => t.runs || 0))
|
||||
const pct = (n, max) => Math.max(2, Math.round((n || 0) / (max || 1) * 100))
|
||||
const rankMax = list => Math.max(1, ...(list || []).map(x => x.runs || 1))
|
||||
|
||||
// ---------- ECharts 趋势曲线 ----------
|
||||
const trendEl = ref(null)
|
||||
let chart = null
|
||||
|
||||
function renderTrend() {
|
||||
if (!st.value || !trendEl.value) return
|
||||
if (!chart) chart = echarts.init(trendEl.value)
|
||||
chart.setOption({
|
||||
tooltip: { trigger: 'axis', backgroundColor: 'rgba(35,42,58,.92)', borderWidth: 0, textStyle: { color: '#fff', fontSize: 12 } },
|
||||
legend: { data: ['成功', '失败'], right: 4, top: 0, icon: 'roundRect', itemWidth: 14, itemHeight: 5, textStyle: { color: '#6b7488', fontSize: 12 } },
|
||||
grid: { left: 36, right: 16, top: 36, bottom: 24 },
|
||||
xAxis: { type: 'category', boundaryGap: false, data: st.value.trend.map(t => t.day),
|
||||
axisLine: { lineStyle: { color: 'rgba(35,42,58,.16)' } }, axisTick: { show: false },
|
||||
axisLabel: { fontSize: 10.5, color: '#9aa2b4' } },
|
||||
yAxis: { type: 'value', minInterval: 1, splitLine: { lineStyle: { color: 'rgba(35,42,58,.07)' } },
|
||||
axisLabel: { fontSize: 10.5, color: '#9aa2b4' } },
|
||||
series: [
|
||||
{ name: '成功', type: 'line', smooth: true, symbolSize: 6, data: st.value.trend.map(t => t.success || 0),
|
||||
lineStyle: { width: 2.6, color: '#1d9d5c' }, itemStyle: { color: '#1d9d5c' },
|
||||
areaStyle: { color: { type: 'linear', x: 0, y: 0, x2: 0, y2: 1, colorStops: [
|
||||
{ offset: 0, color: 'rgba(29,157,92,.20)' }, { offset: 1, color: 'rgba(29,157,92,.01)' }] } } },
|
||||
{ name: '失败', type: 'line', smooth: true, symbolSize: 6, data: st.value.trend.map(t => t.failed || 0),
|
||||
lineStyle: { width: 2.6, color: '#d6453d' }, itemStyle: { color: '#d6453d' },
|
||||
areaStyle: { color: { type: 'linear', x: 0, y: 0, x2: 0, y2: 1, colorStops: [
|
||||
{ offset: 0, color: 'rgba(214,69,61,.16)' }, { offset: 1, color: 'rgba(214,69,61,.01)' }] } } },
|
||||
],
|
||||
})
|
||||
}
|
||||
watch(st, () => nextTick(renderTrend))
|
||||
const onResize = () => chart && chart.resize()
|
||||
|
||||
// ---------- 数据 ----------
|
||||
async function refresh() {
|
||||
busy.value = true
|
||||
try {
|
||||
@@ -172,57 +197,39 @@ async function refresh() {
|
||||
st.value = {
|
||||
users: r.users || {}, plugins: r.plugins || {}, runs: r.runs || {},
|
||||
trend: r.trend || [], topPlugins: r.topPlugins || [], topUsers: r.topUsers || [],
|
||||
recent: r.recent || [],
|
||||
}
|
||||
await loadRecent()
|
||||
} catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
finally { busy.value = false }
|
||||
}
|
||||
onMounted(refresh)
|
||||
|
||||
onMounted(() => { refresh(); window.addEventListener('resize', onResize) })
|
||||
onBeforeUnmount(() => { window.removeEventListener('resize', onResize); chart && chart.dispose(); chart = null })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.kpis { display: grid; grid-template-columns: repeat(6, 1fr); gap: 16px; margin-bottom: 18px; }
|
||||
@media (max-width: 1100px) { .kpis { grid-template-columns: repeat(3, 1fr); } }
|
||||
.kpi {
|
||||
display: flex; align-items: center; gap: 14px;
|
||||
padding: 18px;
|
||||
}
|
||||
.kpi-ic {
|
||||
width: 42px; height: 42px; border-radius: 13px; flex-shrink: 0;
|
||||
display: grid; place-items: center;
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .7);
|
||||
}
|
||||
.kpi { display: flex; align-items: center; gap: 14px; padding: 18px; }
|
||||
.kpi-ic { width: 42px; height: 42px; border-radius: 13px; flex-shrink: 0; display: grid; place-items: center; box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .7); }
|
||||
.kpi-meta { min-width: 0; }
|
||||
.kpi-num { font-size: 24px; font-weight: 800; line-height: 1.1; }
|
||||
.kpi-lab { font-size: 12px; color: var(--cp-ink-3); margin-top: 4px; letter-spacing: .3px; }
|
||||
|
||||
.grid { display: grid; grid-template-columns: 1.45fr 1fr; gap: 18px; margin-bottom: 20px; }
|
||||
@media (max-width: 1100px) { .grid { grid-template-columns: 1fr; } }
|
||||
.rank-wrap { display: flex; flex-direction: column; gap: 18px; }
|
||||
.trend-card, .rank-card { padding: 20px; }
|
||||
.card-title { margin-bottom: 16px; }
|
||||
/* 趋势图全宽置顶 */
|
||||
.chart-card { padding: 20px; margin-bottom: 18px; }
|
||||
.chart { height: 320px; }
|
||||
|
||||
/* 排行两列左右分布 */
|
||||
.rank-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 18px; margin-bottom: 20px; }
|
||||
@media (max-width: 900px) { .rank-grid { grid-template-columns: 1fr; } }
|
||||
.rank-card { padding: 20px; }
|
||||
.card-title { margin-bottom: 14px; }
|
||||
.card-title .sub { font-size: 11px; font-weight: 500; color: var(--cp-ink-3); margin-left: 4px; }
|
||||
|
||||
.trend { display: flex; gap: 5px; height: 176px; align-items: stretch; }
|
||||
.tcol { flex: 1; display: flex; flex-direction: column; justify-content: flex-end; align-items: center; gap: 6px; }
|
||||
.tstack { flex: 1; display: flex; align-items: flex-end; gap: 2px; width: 100%; }
|
||||
.tbar { flex: 1; border-radius: 3px 3px 0 0; transition: filter .18s, transform .18s; }
|
||||
.tbar.success { background: linear-gradient(180deg, #34b877, #1d9d5c); }
|
||||
.tbar.failed { background: linear-gradient(180deg, #f07a72, #d6453d); }
|
||||
.tcol:hover .tbar { filter: brightness(1.05); }
|
||||
.tday { font-size: 10px; color: var(--cp-ink-3); }
|
||||
.trend-legend { display: flex; gap: 18px; margin-top: 14px; font-size: 12px; color: var(--cp-ink-2); }
|
||||
.trend-legend .dot { width: 9px; height: 9px; border-radius: 3px; display: inline-block; margin-right: 6px; }
|
||||
.trend-legend .ok { background: #1d9d5c; }
|
||||
.trend-legend .fail { background: #d6453d; }
|
||||
|
||||
.rank { list-style: none; margin: 0; padding: 0; }
|
||||
.rank li { display: flex; align-items: center; gap: 11px; padding: 8px 0; }
|
||||
.rank .rk {
|
||||
width: 24px; height: 24px; flex: none; border-radius: 8px;
|
||||
background: var(--cp-panel-2); color: var(--cp-ink-3);
|
||||
font-size: 12px; font-weight: 700; display: flex; align-items: center; justify-content: center;
|
||||
}
|
||||
.rank li { display: flex; align-items: center; gap: 11px; padding: 7px 0; }
|
||||
.rank .rk { width: 24px; height: 24px; flex: none; border-radius: 8px; background: var(--cp-panel-2); color: var(--cp-ink-3); font-size: 12px; font-weight: 700; display: flex; align-items: center; justify-content: center; }
|
||||
.rank .rk.top { background: linear-gradient(135deg, var(--cp-blue), var(--cp-teal)); color: #fff; box-shadow: 0 4px 10px -4px rgba(47, 92, 240, .5); }
|
||||
.rank .rbody { flex: 1; min-width: 0; }
|
||||
.rhead { display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px; gap: 10px; }
|
||||
@@ -230,10 +237,12 @@ onMounted(refresh)
|
||||
.rhead em { font-style: normal; font-size: 11.5px; color: var(--cp-ink-3); flex: none; }
|
||||
.rbar { height: 6px; border-radius: 4px; background: var(--cp-panel-2); overflow: hidden; }
|
||||
.rbar i { display: block; height: 100%; background: linear-gradient(90deg, var(--cp-blue), var(--cp-teal)); border-radius: 4px; transition: width .6s cubic-bezier(.22, .61, .36, 1); }
|
||||
.empty { color: var(--cp-ink-3); font-size: 12px; justify-content: center; padding: 18px 0 !important; }
|
||||
.empty { color: var(--cp-ink-3); font-size: 12px; justify-content: center; padding: 18px 0 !important; display: flex; }
|
||||
.empty-tip { padding: 40px; text-align: center; color: var(--cp-ink-3); }
|
||||
|
||||
.page-head.sub h4 { margin: 0; font-size: 15px; font-weight: 800; color: var(--cp-ink-1); }
|
||||
.recent-card { padding: 12px 16px; }
|
||||
.dim-sm { color: var(--cp-ink-2); }
|
||||
.dim-sm { color: var(--cp-ink-2); font-size: 12px; }
|
||||
.status-dot { display: inline-flex; align-items: center; gap: 6px; font-size: 12.5px; }
|
||||
.status-dot i { width: 8px; height: 8px; border-radius: 50%; display: inline-block; }
|
||||
</style>
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
走 /api/admin/auth 用账号+密码换 1 小时票据,管理主密钥不出服务器。
|
||||
- 本机密钥自签(原方式,中心机本机):直接复用 desktop/controlplane/.env 与 .admin_secret,
|
||||
X-API-Token 取自 CONTROLPLANE_TOKEN(.env);为空则该接口不强制,无需携带。
|
||||
X-Admin-Token 用 CONTROLPLANE_ADMIN_SECRET > CONTROLPLANE_TOKEN > .admin_secret 本地自签。
|
||||
X-Admin-Token 用 CONTROLPLANE_ADMIN_SECRET > .admin_secret 本地自签(不再回退 CONTROLPLANE_TOKEN)。
|
||||
中心机地址默认本机 8800;远程发版用 --base 或环境变量 CONTROLPLANE_AGENT_BASE 指向中心机公网地址。
|
||||
|
||||
管理员账号:需用 --admin 显式指定(或设环境变量 AGENT_ADMIN_ACCOUNT),该账号须 is_admin=1。
|
||||
@@ -68,8 +68,9 @@ FILESERVER_TOKEN = os.getenv("FILESERVER_TOKEN", "")
|
||||
|
||||
|
||||
def _admin_secret() -> str:
|
||||
"""与 app.py 完全一致:CONTROLPLANE_ADMIN_SECRET > CONTROLPLANE_TOKEN > .admin_secret。"""
|
||||
cand = os.getenv("CONTROLPLANE_ADMIN_SECRET") or os.getenv("CONTROLPLANE_TOKEN") or ""
|
||||
"""与 app.py 完全一致:CONTROLPLANE_ADMIN_SECRET > .admin_secret(不再回退 CONTROLPLANE_TOKEN,
|
||||
传输凭证与管理密钥分离,避免持 X-API-Token 者自签管理员票据)。"""
|
||||
cand = os.getenv("CONTROLPLANE_ADMIN_SECRET") or ""
|
||||
if cand:
|
||||
return cand
|
||||
_f = APP_DIR / ".admin_secret"
|
||||
|
||||
@@ -69,6 +69,10 @@ def submit_run(account: str, plugin, fields: dict) -> str:
|
||||
"msg": "设备正有其他插件执行中,排队等待其完成后自动启动…"})
|
||||
|
||||
def _start():
|
||||
if _is_user_stopped(run_id):
|
||||
# 排队期间用户已点停止:不真正拉起插件,抛异常让 request_start 回滚单活槽位,
|
||||
# 由下方 !ok 分支把 run 落为"用户手动强制停止",避免"看似取消实际还在跑"。
|
||||
raise RuntimeError("用户已取消该排队任务")
|
||||
threading.Thread(target=_run_target,
|
||||
args=(plugin, fields, run_id),
|
||||
daemon=True, name=f"exec-{plugin.id}").start()
|
||||
@@ -78,10 +82,14 @@ def submit_run(account: str, plugin, fields: dict) -> str:
|
||||
getattr(plugin, "version", "0"), _start)
|
||||
if not r.get("ok"):
|
||||
# 启动失败(回滚已发生):落地错误结果并广播,避免前端永久等待
|
||||
_st._set_run(run_id, status="error", result=None,
|
||||
error=r.get("error") or "启动失败")
|
||||
err = r.get("error") or "启动失败"
|
||||
if _is_user_stopped(run_id):
|
||||
err = "用户手动强制停止"
|
||||
with _STOP_LOCK:
|
||||
_USER_STOPPED.discard(run_id)
|
||||
_st._set_run(run_id, status="error", result=None, error=err)
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False,
|
||||
"error": r.get("error") or "启动失败"})
|
||||
"error": err})
|
||||
|
||||
threading.Thread(target=_queued, daemon=True,
|
||||
name=f"run-{plugin.id}").start()
|
||||
|
||||
@@ -26,11 +26,14 @@ _APP_DATA = Path(os.getenv("LOCALAPPDATA") or os.getenv("APPDATA")
|
||||
_SCHED_FILE = _APP_DATA / "schedules.json"
|
||||
|
||||
_TICK_SECS = 30 # 后台检查周期(秒)
|
||||
_DENY_LOG_CD = 300 # 同一任务触发被拒后,拒绝日志的最小间隔(秒),避免离线时刷屏
|
||||
_STARTED = False
|
||||
|
||||
_LOCK = threading.RLock()
|
||||
# 内存中的任务列表(dict 列表),持久化到 _SCHED_FILE
|
||||
_SCHEDULES: list = []
|
||||
# 任务 id → 上次打印"触发被拒"日志的时间戳(节流用)
|
||||
_deny_log_ts: dict = {}
|
||||
|
||||
|
||||
# ==================== 标准 5 段 cron 解析 ====================
|
||||
@@ -256,7 +259,8 @@ def _public(s: dict) -> dict:
|
||||
out = dict(s)
|
||||
out["enabled"] = bool(out.get("enabled"))
|
||||
out["last_run_at"] = out.get("last_run_at") or ""
|
||||
nxt = next_run_at(s)
|
||||
# 已停用任务不再推算/展示下次执行,避免误导
|
||||
nxt = next_run_at(s) if out["enabled"] else None
|
||||
out["next_run_at"] = nxt.strftime("%Y-%m-%d %H:%M:%S") if nxt else ""
|
||||
return out
|
||||
|
||||
@@ -331,8 +335,14 @@ def _fire(s: dict) -> bool:
|
||||
account = s.get("account", "")
|
||||
deny = licensing.run_check_allowed(plugin.id, account, licensing.is_online())
|
||||
if deny:
|
||||
_LOGGER.warning("定时任务「%s」触发被拒(账号 %s):%s",
|
||||
s.get("name"), account, deny)
|
||||
# 拒绝日志节流:同一任务至少间隔 _DENY_LOG_CD 秒才再记一条,避免授权失效时每 tick 刷屏
|
||||
_ts = time.time()
|
||||
with _LOCK:
|
||||
_last = _deny_log_ts.get(s.get("id"))
|
||||
_deny_log_ts[s.get("id")] = _ts
|
||||
if _last is None or _ts - _last >= _DENY_LOG_CD:
|
||||
_LOGGER.warning("定时任务「%s」触发被拒(账号 %s):%s",
|
||||
s.get("name"), account, deny)
|
||||
return False
|
||||
try:
|
||||
submit_run(account, plugin, s.get("fields") or {})
|
||||
|
||||
@@ -29,7 +29,7 @@
|
||||
|
||||
<!-- 专属界面插件:插件 UI 直接内嵌在页面主体(同源共享会话 cookie,不再弹窗/外跳),日志保持在其下方可见 -->
|
||||
<div v-if="plugin.ui" class="ui-inline">
|
||||
<div class="ui-tip">账号密码、仓库编码、日期选项等个性化配置在界面内填写并自动保存在本机,下次打开自动回填;执行日志实时显示在下方日志区。</div>
|
||||
<div class="ui-tip">个性化配置项在界面内填写并自动保存在本机,下次打开自动回填;执行日志实时显示在下方日志区。</div>
|
||||
<iframe :key="plugin.id" :src="uiSrc" class="pui-frame" title="插件界面"></iframe>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -46,7 +46,8 @@
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
|
||||
<el-dialog v-model="dlg" :title="editing ? '编辑定时任务' : '新建定时任务'" width="560px" align-center>
|
||||
<el-dialog v-model="dlg" :title="editing ? '编辑定时任务' : '新建定时任务'" width="min(780px, 94vw)" align-center
|
||||
class="sched-dlg">
|
||||
<el-form label-width="86px" class="dlg-form">
|
||||
<el-form-item label="任务名称">
|
||||
<el-input v-model="form.name" placeholder="如:每日考勤封存检查" maxlength="32" />
|
||||
@@ -58,15 +59,68 @@
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="触发时间">
|
||||
<div class="cron-row">
|
||||
<el-input v-model="form.cron" placeholder="标准 5 段 cron,如 0 8 * * *" class="cron-input">
|
||||
<template #prepend>cron</template>
|
||||
</el-input>
|
||||
<el-select v-model="preset" placeholder="快捷项" class="preset-sel" @change="onPreset">
|
||||
<el-option v-for="p in presets" :key="p.cron" :value="p.cron" :label="p.label" />
|
||||
</el-select>
|
||||
<div class="freq-zone">
|
||||
<el-radio-group v-model="freq" class="freq-tabs" size="small">
|
||||
<el-radio-button value="daily">每天</el-radio-button>
|
||||
<el-radio-button value="weekdays">工作日</el-radio-button>
|
||||
<el-radio-button value="weekly">每周</el-radio-button>
|
||||
<el-radio-button value="monthly">每月</el-radio-button>
|
||||
<el-radio-button value="hourly">每隔 N 小时</el-radio-button>
|
||||
<el-radio-button value="advanced">高级</el-radio-button>
|
||||
</el-radio-group>
|
||||
|
||||
<!-- 每天 / 工作日 -->
|
||||
<div v-if="freq === 'daily' || freq === 'weekdays'" class="freq-row">
|
||||
<span class="freq-desc">{{ freq === 'daily' ? '每天' : '周一至周五' }}</span>
|
||||
<el-time-select v-model="timeStr" start="00:00" step="00:05" end="23:55"
|
||||
placeholder="选择时间" class="time-sel" />
|
||||
</div>
|
||||
|
||||
<!-- 每周:选周几 + 时间 -->
|
||||
<div v-else-if="freq === 'weekly'" class="freq-row">
|
||||
<span class="freq-desc">每周</span>
|
||||
<el-checkbox-group v-model="weekdays" class="week-days">
|
||||
<el-checkbox-button v-for="d in weekDayOpts" :key="d.v" :value="d.v">{{ d.label }}</el-checkbox-button>
|
||||
</el-checkbox-group>
|
||||
<el-time-select v-model="timeStr" start="00:00" step="00:05" end="23:55"
|
||||
placeholder="选择时间" class="time-sel" />
|
||||
</div>
|
||||
|
||||
<!-- 每月:选几号 + 时间 -->
|
||||
<div v-else-if="freq === 'monthly'" class="freq-row">
|
||||
<span class="freq-desc">每月</span>
|
||||
<el-select v-model="monthDay" class="day-sel">
|
||||
<el-option v-for="d in 31" :key="d" :value="d" :label="`${d} 日`" />
|
||||
</el-select>
|
||||
<el-time-select v-model="timeStr" start="00:00" step="00:05" end="23:55"
|
||||
placeholder="选择时间" class="time-sel" />
|
||||
</div>
|
||||
|
||||
<!-- 每隔 N 小时 -->
|
||||
<div v-else-if="freq === 'hourly'" class="freq-row">
|
||||
<span class="freq-desc">每隔</span>
|
||||
<el-input-number v-model="hourlyStep" :min="1" :max="24" :controls="false" class="step-num" />
|
||||
<span class="freq-desc">小时执行一次(整点)</span>
|
||||
</div>
|
||||
|
||||
<!-- 高级:直接写 cron -->
|
||||
<div v-else class="freq-row col">
|
||||
<div class="cron-row">
|
||||
<el-input v-model="advancedCron" placeholder="标准 5 段 cron,如 0 8 * * *" class="cron-input">
|
||||
<template #prepend>cron</template>
|
||||
</el-input>
|
||||
<el-select v-model="preset" placeholder="快捷项" class="preset-sel" @change="onPreset">
|
||||
<el-option v-for="p in presets" :key="p.cron" :value="p.cron" :label="p.label" />
|
||||
</el-select>
|
||||
</div>
|
||||
<div class="cron-tip">5 段格式:分 时 日 月 周(0-59 0-23 1-31 1-12 0-6,0/7 均为周日)</div>
|
||||
</div>
|
||||
|
||||
<!-- 非高级模式下实时预览生成的 cron -->
|
||||
<div v-if="freq !== 'advanced'" class="cron-preview">
|
||||
表达式 <code>{{ form.cron }}</code>
|
||||
</div>
|
||||
</div>
|
||||
<div class="cron-tip">5 段格式:分 时 日 月 周(0-59 0-23 1-31 1-12 0-6,0/7 均为周日)</div>
|
||||
</el-form-item>
|
||||
<el-form-item v-if="pluginFields.length" label="执行参数">
|
||||
<div class="fields">
|
||||
@@ -101,7 +155,7 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, ref } from 'vue'
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { Clock, Plus } from '@element-plus/icons-vue'
|
||||
import { store } from '../store'
|
||||
@@ -113,6 +167,80 @@ const editing = ref(null)
|
||||
const saving = ref(false)
|
||||
const preset = ref('')
|
||||
|
||||
// ---- 闹钟式触发时间选择状态 ----
|
||||
// freq: daily=每天 weekdays=工作日 weekly=每周 monthly=每月 hourly=每隔N小时 advanced=高级cron
|
||||
const freq = ref('daily')
|
||||
const timeStr = ref('08:00')
|
||||
const weekdays = ref([1])
|
||||
const monthDay = ref(1)
|
||||
const hourlyStep = ref(1)
|
||||
const advancedCron = ref('')
|
||||
const weekDayOpts = [
|
||||
{ v: 1, label: '周一' }, { v: 2, label: '周二' }, { v: 3, label: '周三' },
|
||||
{ v: 4, label: '周四' }, { v: 5, label: '周五' }, { v: 6, label: '周六' }, { v: 7, label: '周日' },
|
||||
]
|
||||
|
||||
function pad2(n) { return String(n).padStart(2, '0') }
|
||||
|
||||
// 由可视化选择状态生成 cron 表达式(分钟/小时补齐 2 位,兼容解析)
|
||||
function buildCron() {
|
||||
const [h, m] = timeStr.value.split(':').map(Number)
|
||||
switch (freq.value) {
|
||||
case 'daily': return `${pad2(m)} ${pad2(h)} * * *`
|
||||
case 'weekdays': return `${pad2(m)} ${pad2(h)} * * 1-5`
|
||||
case 'weekly': {
|
||||
const ds = (weekdays.value.length ? weekdays.value : [1]).slice().sort((a, b) => a - b)
|
||||
return `${pad2(m)} ${pad2(h)} * * ${ds.join(',')}`
|
||||
}
|
||||
case 'monthly': return `${pad2(m)} ${pad2(h)} ${monthDay.value} * *`
|
||||
case 'hourly': return `0 */${hourlyStep.value || 1} * * *`
|
||||
default: return advancedCron.value.trim()
|
||||
}
|
||||
}
|
||||
|
||||
// 把已有 cron 反向解析为可视化选择状态;无法识别的回退到高级模式原样展示
|
||||
function cronToState(cron) {
|
||||
const s = String(cron || '').trim()
|
||||
const parts = s.split(/\s+/)
|
||||
const st = { freq: 'advanced', timeStr: '08:00', weekdays: [1], monthDay: 1, hourlyStep: 1, advancedCron: s }
|
||||
if (parts.length !== 5) return st
|
||||
const [m, h, dom, mon, dow] = parts
|
||||
// 每隔 N 小时:0 */N * * *
|
||||
if (m === '0' && /^\*\/\d+$/.test(h) && dom === '*' && mon === '*' && dow === '*') {
|
||||
const step = parseInt(h.split('/')[1], 10)
|
||||
if (step >= 1 && step <= 24) return { ...st, freq: 'hourly', hourlyStep: step }
|
||||
}
|
||||
const num = (x) => (/^\d+$/.test(x) ? parseInt(x, 10) : null)
|
||||
const mn = num(m), hr = num(h)
|
||||
if (mn == null || hr == null || mn < 0 || mn > 59 || hr < 0 || hr > 23) return st
|
||||
const hhmm = pad2(hr) + ':' + pad2(mn)
|
||||
if (dom === '*' && mon === '*') {
|
||||
if (dow === '*') return { ...st, freq: 'daily', timeStr: hhmm }
|
||||
if (dow === '1-5') return { ...st, freq: 'weekdays', timeStr: hhmm }
|
||||
if (/^[0-7](,[0-7])*$/.test(dow)) {
|
||||
const ds = [...new Set(dow.split(',').map(Number).map((x) => (x === 0 ? 7 : x)))].sort((a, b) => a - b)
|
||||
return { ...st, freq: 'weekly', timeStr: hhmm, weekdays: ds }
|
||||
}
|
||||
return st
|
||||
}
|
||||
if (dow === '*' && mon === '*') {
|
||||
const dd = num(dom)
|
||||
if (dd != null && dd >= 1 && dd <= 31) return { ...st, freq: 'monthly', timeStr: hhmm, monthDay: dd }
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
// 同步状态 → form.cron(打开弹窗时立即生成一次)
|
||||
function syncCron() {
|
||||
if (freq.value !== 'advanced') form.value.cron = buildCron()
|
||||
}
|
||||
|
||||
// 选择状态变化时自动重写 form.cron
|
||||
watch([freq, timeStr, weekdays, monthDay, hourlyStep], syncCron)
|
||||
watch(advancedCron, (v) => {
|
||||
if (freq.value === 'advanced') form.value.cron = v.trim()
|
||||
})
|
||||
|
||||
const presets = [
|
||||
{ label: '每天 08:00', cron: '0 8 * * *' },
|
||||
{ label: '每天 12:00', cron: '0 12 * * *' },
|
||||
@@ -144,7 +272,7 @@ function onPluginChange(id) {
|
||||
}
|
||||
|
||||
function onPreset(cron) {
|
||||
form.value.cron = cron
|
||||
advancedCron.value = cron
|
||||
preset.value = ''
|
||||
}
|
||||
|
||||
@@ -160,6 +288,14 @@ async function load() {
|
||||
function openCreate() {
|
||||
editing.value = null
|
||||
form.value = { name: '', plugin_id: '', cron: '', enabled: true, fields: {} }
|
||||
// 默认:每天 08:00
|
||||
freq.value = 'daily'
|
||||
timeStr.value = '08:00'
|
||||
weekdays.value = [1]
|
||||
monthDay.value = 1
|
||||
hourlyStep.value = 1
|
||||
advancedCron.value = ''
|
||||
syncCron()
|
||||
dlg.value = true
|
||||
}
|
||||
|
||||
@@ -173,6 +309,15 @@ function openEdit(row) {
|
||||
fields: buildFields(store.plugins.find((x) => x.id === row.plugin_id)),
|
||||
}
|
||||
Object.assign(form.value.fields, row.fields || {})
|
||||
// 把已有 cron 解析回可视化选择状态
|
||||
const st = cronToState(row.cron || '')
|
||||
freq.value = st.freq
|
||||
timeStr.value = st.timeStr
|
||||
weekdays.value = st.weekdays
|
||||
monthDay.value = st.monthDay
|
||||
hourlyStep.value = st.hourlyStep
|
||||
advancedCron.value = st.advancedCron
|
||||
syncCron()
|
||||
dlg.value = true
|
||||
}
|
||||
|
||||
@@ -331,13 +476,80 @@ load()
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.fields {
|
||||
/* ---- 闹钟式触发时间选择 ---- */
|
||||
.freq-zone {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.freq-tabs {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.freq-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.freq-row.col {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.freq-desc {
|
||||
font-size: 13px;
|
||||
color: var(--text-sub);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.time-sel {
|
||||
width: 130px;
|
||||
}
|
||||
|
||||
.day-sel {
|
||||
width: 110px;
|
||||
}
|
||||
|
||||
.step-num {
|
||||
width: 90px;
|
||||
}
|
||||
|
||||
.week-days {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.cron-preview {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 12px;
|
||||
color: var(--text-faint);
|
||||
}
|
||||
|
||||
.cron-preview code {
|
||||
padding: 1px 8px;
|
||||
border-radius: 6px;
|
||||
background: var(--surface-2, #f7f8fa);
|
||||
border: 1px solid var(--border);
|
||||
font-size: 12px;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.fields {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
|
||||
gap: 10px 14px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -358,4 +570,14 @@ load()
|
||||
.w-full {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* 定时任务弹窗:内容超高时弹窗内滚动,避免配置多的插件把弹窗顶出屏幕 */
|
||||
:deep(.sched-dlg .el-dialog) {
|
||||
max-height: 90vh;
|
||||
}
|
||||
|
||||
:deep(.sched-dlg .el-dialog__body) {
|
||||
max-height: 62vh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
; 37du 自动化工作台 - Inno Setup 安装脚本 (Inno Setup 7)
|
||||
; 37du 自动化工作台 - Inno Setup 安装脚本 (Inno Setup 7)
|
||||
; 编译: "C:\Program Files\Inno Setup 7\ISCC.exe" webhost\tools\install.iss
|
||||
; 打包内容: 主程序 37du-host.exe + 插件执行壳 37du-host-runner.exe + .env 默认配置
|
||||
; .env 与 webhost/.env 同源(控制面/平台共享配置):仅首次安装写入(onlyifdoesntexist),
|
||||
; 升级不覆盖机器已有 .env;不含 37du-host-console.exe(调试版)、plugins/(登录后自下载)
|
||||
|
||||
#define MyAppName "37du 自动化工作台"
|
||||
#define MyAppVersion "1.1.8"
|
||||
#define MyAppVersion "1.2.0"
|
||||
#define MyAppExeName "37du-host.exe"
|
||||
|
||||
[Setup]
|
||||
|
||||
@@ -1 +1 @@
|
||||
1.1.8
|
||||
1.2.0
|
||||
@@ -0,0 +1 @@
|
||||
{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}
|
||||
@@ -0,0 +1,171 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""金色印象通联数据导出 - webhost 场景插件(XQ0045 + XQ0046 合并版)
|
||||
|
||||
通联支付商户服务平台(cus.allinpay.com)交易数据自动导出:
|
||||
- XQ0045 按日:导某一天(YYYY-MM-DD)的交易;
|
||||
- XQ0046 按月:导某个月(YYYY-MM)的交易;
|
||||
服务端导出接口忽略商户参数、始终返回账号全量结果集(实测),因此每个日期只导一份
|
||||
全量文件(含账号下所有商户),直存本地,不再按商户拆分。
|
||||
|
||||
个性化设计:
|
||||
- 通联登录账号密码由插件界面配置经 fields 注入(plugin_configs 本机保存,下次免填);
|
||||
- 浏览器现场真登录(固定默认用户目录 + ddddocr 验证码识别),登录后转 requests.Session
|
||||
直调导出接口(服务端有 Referer 外链校验,插件内统一带 Referer);
|
||||
- 日期支持多个(逗号分隔,逐个导出);mode=日+月 时按日期串格式自动识别日/月。
|
||||
"""
|
||||
import os
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
||||
|
||||
from . import config
|
||||
from .data import allinpay_login, allinpay_export
|
||||
|
||||
MODE_DAY = '日'
|
||||
MODE_MONTH = '月'
|
||||
MODE_BOTH = '日+月'
|
||||
|
||||
CONTENT_TRX = '交易查询'
|
||||
CONTENT_BILL = '账单'
|
||||
CONTENT_BOTH = '两个都导'
|
||||
|
||||
|
||||
def _default_save_dir():
|
||||
return str(Path(config.get_desktop()) / f"金色印象通联数据_{datetime.now():%Y%m%d}")
|
||||
|
||||
|
||||
def _build_tasks(mode, day_date, month_date):
|
||||
"""按执行模式组合 (模式, 日期) 任务列表(前端已用日期选择器选好值,这里只做组装)。"""
|
||||
tasks = []
|
||||
if mode in (MODE_DAY, MODE_BOTH) and day_date:
|
||||
tasks.append((MODE_DAY, day_date))
|
||||
if mode in (MODE_MONTH, MODE_BOTH) and month_date:
|
||||
tasks.append((MODE_MONTH, month_date))
|
||||
if not tasks:
|
||||
raise RuntimeError("请选择按日导出的日期和/或按月导出的月份")
|
||||
return tasks
|
||||
|
||||
|
||||
class TongLianExportPlugin(ScenePlugin):
|
||||
id = "xq0045_xq0046"
|
||||
name = "金色印象通联数据导出"
|
||||
version = "1.0.5"
|
||||
description = ("通联支付交易数据自动导出:XQ0045 按日 / XQ0046 按月,"
|
||||
"账号全量数据导出(含全部商户),服务端生成文件直存本地")
|
||||
platform = "" # 通联自带登录页(验证码),插件内现场真登录,不使用底座共享登录态
|
||||
uses_month = False
|
||||
capabilities = ["xq0045_xq0046"]
|
||||
permissions = {"platforms": []}
|
||||
# 与 plugin.json.fields 一致(ui=true 前端自渲染,此处分层作为参数契约文档)
|
||||
fields = {
|
||||
"mode": {"type": "string", "title": "执行模式", "default": MODE_BOTH,
|
||||
"enum": [MODE_BOTH, MODE_DAY, MODE_MONTH]},
|
||||
"content": {"type": "string", "title": "导出内容", "default": CONTENT_BOTH,
|
||||
"enum": [CONTENT_BOTH, CONTENT_TRX, CONTENT_BILL]},
|
||||
"day_date": {"type": "string", "format": "date", "title": "按日导出(数据起始日)", "default": ""},
|
||||
"month_date": {"type": "string", "format": "month", "title": "按月导出", "default": ""},
|
||||
"tl_username": {"type": "string", "title": "通联登录账号", "default": ""},
|
||||
"tl_password": {"type": "string", "title": "通联登录密码", "default": ""},
|
||||
"save_dir": {"type": "string", "title": "保存目录", "default": ""},
|
||||
}
|
||||
|
||||
def run(self, fields, ctx) -> dict:
|
||||
fields = fields or {}
|
||||
config.set_log(ctx.log)
|
||||
|
||||
# ---------- 解析与校验 ----------
|
||||
mode = str(fields.get("mode") or MODE_BOTH).strip()
|
||||
content = str(fields.get("content") or CONTENT_BOTH).strip()
|
||||
username = str(fields.get("tl_username") or "").strip()
|
||||
password = str(fields.get("tl_password") or "")
|
||||
day_date = str(fields.get("day_date") or "").strip()
|
||||
month_date = str(fields.get("month_date") or "").strip()
|
||||
save_dir = str(fields.get("save_dir") or "").strip().strip('"') or _default_save_dir()
|
||||
|
||||
if not username or not password:
|
||||
raise RuntimeError("通联登录账号/密码缺失:请在插件界面填写并保存配置后重试")
|
||||
if mode not in (MODE_BOTH, MODE_DAY, MODE_MONTH):
|
||||
raise RuntimeError(f"未知执行模式:{mode}")
|
||||
if content not in (CONTENT_BOTH, CONTENT_TRX, CONTENT_BILL):
|
||||
raise RuntimeError(f"未知导出内容:{content}")
|
||||
|
||||
do_trx = content in (CONTENT_TRX, CONTENT_BOTH)
|
||||
do_bill = content in (CONTENT_BILL, CONTENT_BOTH)
|
||||
tasks = _build_tasks(mode, day_date, month_date)
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
ctx.log(f"导出内容:{content},模式:{mode},任务 {len(tasks)} 项,保存目录:{save_dir}")
|
||||
|
||||
# ---------- 登录 ----------
|
||||
ctx.progress(3)
|
||||
ctx.log("开始通联平台登录(接口优先,浏览器兜底)…")
|
||||
session = allinpay_login.tl_login(username, password)
|
||||
if session is None:
|
||||
raise RuntimeError("通联平台登录失败(账号密码错误或验证码多次识别失败),详见日志")
|
||||
ctx.progress(10)
|
||||
|
||||
saved, failed = [], []
|
||||
|
||||
# ---------- 交易查询导出(15~70:每个任务导一份账号全量,服务端忽略商户参数) ----------
|
||||
if do_trx:
|
||||
# 服务端 cusid 不能传空串(传空会直接 504),但会忽略其筛选语义、始终返回
|
||||
# 账号全量结果集;故取账号下首个真实商户号作为种子参数即可。
|
||||
ctx.log("获取账号商户列表(取首个商户号作查询种子,服务端返回全量)…")
|
||||
cus_list = allinpay_export.get_cus_list(session)
|
||||
seed_cusid = cus_list[0]['key'] if cus_list else ''
|
||||
ctx.log(f"账号下商户 {len(cus_list)} 个,查询种子商户号:{seed_cusid}")
|
||||
if not seed_cusid:
|
||||
raise RuntimeError("获取商户列表失败:账号下无商户,无法发起导出")
|
||||
units = len(tasks)
|
||||
done = 0
|
||||
for m, d in tasks:
|
||||
done += 1
|
||||
label = f"交易[{m} {d}](账号全量)"
|
||||
ctx.log(f"--- [{done}/{units}] 导出 {label} ---")
|
||||
try:
|
||||
start, end = allinpay_export.build_date_range(m, d)
|
||||
ctx.log(f" 查询区间 {start} ~ {end}")
|
||||
fid = allinpay_export.start_export(session, seed_cusid, start, end)
|
||||
ctx.log(f" 导出任务已提交 fid={fid},等待服务端生成…")
|
||||
allinpay_export.wait_export_done(session, fid)
|
||||
url = allinpay_export.get_download_url(session, fid)
|
||||
ctx.log(" 开始下载导出文件…")
|
||||
path = allinpay_export.download_file(session, url, save_dir, f"{m}交易查询结果_{d}")
|
||||
saved.append(path)
|
||||
except Exception as e:
|
||||
ctx.log(f" 交易导出失败:{e}", "ERROR")
|
||||
failed.append(f"{label}[{e}]")
|
||||
ctx.progress(15 + int(55 * done / max(1, units)))
|
||||
ctx.progress(70)
|
||||
|
||||
# ---------- 账单导出(70~95,主账号 zip 下载 + 解压) ----------
|
||||
if do_bill:
|
||||
units = len(tasks)
|
||||
done = 0
|
||||
for m, d in tasks:
|
||||
done += 1
|
||||
label = f"账单[{m} {d}]"
|
||||
ctx.log(f"--- [{done}/{units}] 导出 {label} ---")
|
||||
try:
|
||||
bill_type = 'month' if m == MODE_MONTH else 'day'
|
||||
_, extract_dir = allinpay_export.bill_download(
|
||||
session, d, bill_type, save_dir)
|
||||
saved.append(extract_dir)
|
||||
except Exception as e:
|
||||
ctx.log(f" 账单导出失败:{e}", "ERROR")
|
||||
failed.append(f"{label}[{e}]")
|
||||
ctx.progress(70 + int(25 * done / max(1, units)))
|
||||
ctx.progress(100)
|
||||
|
||||
# ---------- 汇总 ----------
|
||||
notes = [f"已保存 {len(saved)} 个文件/目录:"] + [f" {p}" for p in saved]
|
||||
if failed:
|
||||
notes.append(f"失败 {len(failed)} 项:{'、'.join(failed)}")
|
||||
summary = (f"通联数据导出完成(部分失败):成功 {len(saved)} 个,"
|
||||
f"失败 {len(failed)} 项 → {save_dir}")
|
||||
else:
|
||||
summary = f"通联数据导出完成:共 {len(saved)} 个文件/目录 → {save_dir}"
|
||||
return {"summary": summary, "rows": [], "notes": notes}
|
||||
|
||||
|
||||
PLUGINS.append(TongLianExportPlugin())
|
||||
@@ -0,0 +1,42 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""发布打包辅助(开发工具,`_` 前缀运行时不会被插件扫描加载)。
|
||||
|
||||
把本插件压成 dist-plugin/xq0045_xq0046_v<版本>.zip,
|
||||
包根布局:plugin.json / 各 .py / requirements.txt 直接位于 zip 根。
|
||||
排除项:__pycache__、debug、.sessions、本脚本、*.pyc。
|
||||
|
||||
用法(仓库根下执行):
|
||||
.venv\\Scripts\\python.exe "plugins\\XQ0001-0100\\XQ0045_XQ0046 金色印象通联数据导出\\_pack.py"
|
||||
随后发布(desktop/ 下执行,见 docs/插件/发版规范.md):
|
||||
.venv\\Scripts\\python.exe -m controlplane.tools.agent_cli publish \\
|
||||
dist-plugin/xq0045_xq0046_v1.0.0.zip --id xq0045_xq0046 --version 1.0.0
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
_HERE = Path(__file__).resolve().parent
|
||||
# 仓库根 = plugins/XQ0001-0100/<插件目录>/ 的 parents[2],统一出包位置
|
||||
_OUT_DIR = _HERE.parents[2] / "dist-plugin"
|
||||
_EXCLUDE_DIRS = {"ui-src", "__pycache__", "debug", ".sessions"}
|
||||
_EXCLUDE_FILES = {"_pack.py"}
|
||||
|
||||
|
||||
def main():
|
||||
manifest = json.loads((_HERE / "plugin.json").read_text(encoding="utf-8"))
|
||||
pid, ver = manifest["id"], manifest["version"]
|
||||
_OUT_DIR.mkdir(exist_ok=True)
|
||||
out = _OUT_DIR / f"{pid}_v{ver}.zip"
|
||||
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||
for p in sorted(_HERE.rglob("*")):
|
||||
rel = p.relative_to(_HERE)
|
||||
if set(rel.parts) & _EXCLUDE_DIRS or p.name in _EXCLUDE_FILES or p.suffix == ".pyc":
|
||||
continue
|
||||
if p.is_file():
|
||||
zf.write(p, str(rel))
|
||||
print(f"已打包: {out}({out.stat().st_size / 1024:.0f} KB)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,102 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0045_xq0046 金色印象通联数据导出 插件 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:本包只依赖 Python 标准库 / 第三方库 / 底座注入的 RunContext。
|
||||
业务模块统一经 config.log() 输出日志(转发到 ctx.log,无 ctx 时回落到 print)。
|
||||
"""
|
||||
import os
|
||||
|
||||
# ==================== 通联平台 ====================
|
||||
LOGIN_URL = 'https://cus.allinpay.com/login'
|
||||
MAIN_URL = 'https://cus.allinpay.com/main.dsr' # 已登录首页(预热/Referer 来源)
|
||||
SEARCH_URL = 'https://cus.allinpay.com/tranx25/search'
|
||||
STATUS_URL = 'https://cus.allinpay.com/export/statusdownload'
|
||||
DOWNLOAD_INFO_URL = 'https://cus.allinpay.com/export/downloadexport/'
|
||||
BILL_URL = 'https://cus.allinpay.com/checkacct25/download'
|
||||
TRXCODE_URL = 'https://cus.allinpay.com/unauth/queryInterCode'
|
||||
TRXSTATE_URL = 'https://cus.allinpay.com/unauth/queryRecordState'
|
||||
|
||||
# 服务端有 Referer 外链校验:直接访问会被重定向回 /main.dsr
|
||||
SEARCH_HEADERS = {'Referer': MAIN_URL}
|
||||
|
||||
# ==================== 导出参数 ====================
|
||||
EXPORT_CURRENT = 'onebtnexpt' # 导出当前页
|
||||
EXPORT_ALL = 'all' # 导出全部(默认用这个)
|
||||
|
||||
# 异步导出状态轮询:每 6 秒一次,最多 12 次(服务端超时上限约 10 次/60 秒)
|
||||
STATUS_POLL_INTERVAL = 6
|
||||
STATUS_POLL_MAX = 12
|
||||
|
||||
# 登录/验证码 —— 风控敏感:每次提交都计入服务端登录尝试次数,从严控制重试,
|
||||
# 避免连续多次提交触发平台「登录失败次数已达上限」锁定(曾实测踩雷,账号被锁 2 小时)
|
||||
RETRY_MAX = 1 # 浏览器兜底登录轮数(失败即停,不反复登录)
|
||||
CAPTCHA_RETRY = 3 # 浏览器每轮验证码重试次数
|
||||
API_CAPTCHA_RETRY = 3 # 接口登录验证码重试次数
|
||||
LOGIN_FAIL_BACKOFF = 8 # 登录提交失败后的退避秒数(让风控计数沉降)
|
||||
TIMEOUT = 10 # 元素等待超时(秒)
|
||||
|
||||
# ==================== 默认保存目录 ====================
|
||||
_DESKTOP = os.path.join(os.path.expanduser('~'), 'Desktop')
|
||||
|
||||
|
||||
def get_desktop():
|
||||
return _DESKTOP
|
||||
|
||||
|
||||
# ==================== 浏览器用户目录 ====================
|
||||
def get_browser_profile_dir():
|
||||
"""独立固定浏览器用户目录:登录态跨次保留(免验证码),且不占用用户日常 Chrome 配置。
|
||||
|
||||
放 %LOCALAPPDATA% 下而非系统临时目录,避免被磁盘清理工具清掉导致登录态丢失。
|
||||
"""
|
||||
base = os.environ.get('LOCALAPPDATA') or os.path.expanduser('~')
|
||||
return os.path.join(base, '37duAutomation', 'browser_sessions', 'xq0045_xq0046')
|
||||
|
||||
|
||||
# ==================== 登录会话复用 ====================
|
||||
def get_session_file():
|
||||
"""已登录会话 cookies 落盘路径:跨 run 复用通联登录,避免每次执行都重新登录。"""
|
||||
base = os.environ.get('LOCALAPPDATA') or os.path.expanduser('~')
|
||||
d = os.path.join(base, '37duAutomation', 'sessions')
|
||||
os.makedirs(d, exist_ok=True)
|
||||
return os.path.join(d, 'allinpay_xq0045_xq0046.json')
|
||||
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
|
||||
|
||||
def set_log(fn):
|
||||
"""注入 ctx.log(RunContext.log),各模块经 log()/logger 输出。"""
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def log(msg, level="INFO"):
|
||||
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()
|
||||
@@ -0,0 +1 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
@@ -0,0 +1,259 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""通联平台交易数据导出(xq0045_xq0046 插件内自包含)。
|
||||
|
||||
服务端行为已探明(探针 workflows/share/debug_tranx25 实测验证):
|
||||
- 请求必须带 Referer,否则被重定向回 /main.dsr;
|
||||
- 商户列表内嵌在搜索页 JS:var childcuslist = '[{"key":"商户号","value":"商户名"},...]';
|
||||
- 查询:POST /tranx25/search,data={issubmit,cusid,startDate,endDate,export:false,pageIndex,
|
||||
canemptycusid},响应为整页 HTML(结果表格 #dataTable);
|
||||
- 导出(异步三步):
|
||||
1) POST /tranx25/search 带 export=all → JSON {"code":"0","message":"<fid>"}(code=1 失败);
|
||||
2) POST /export/statusdownload {id:fid} 每 6 秒轮询至 code=0(就绪);
|
||||
3) POST /export/downloadexport/ {id:fid} → {"code":"0","message":"<下载URL>"} → GET 落文件。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import zipfile
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
# ==================== HTTP 封装(统一带 Referer) ====================
|
||||
def _get(session, url, **kw):
|
||||
return session.get(url, headers=config.SEARCH_HEADERS, timeout=20, **kw)
|
||||
|
||||
|
||||
def _post(session, url, data=None, **kw):
|
||||
return session.post(url, data=data, headers=config.SEARCH_HEADERS, timeout=30, **kw)
|
||||
|
||||
|
||||
def _parse_code_message(text):
|
||||
"""解析服务端返回的 JS 风格对象(单引号,如 {code:'0',message:'fid'})。
|
||||
|
||||
前端用 eval('('+data+')') 解析,说明响应不是标准 JSON;
|
||||
先试标准 JSON,失败再正则提取 code/message。返回 (code, message)。
|
||||
"""
|
||||
text = (text or '').strip()
|
||||
try:
|
||||
j = json.loads(text)
|
||||
return str(j.get('code')), str(j.get('message') or '')
|
||||
except Exception:
|
||||
pass
|
||||
m_code = re.search(r"code\s*:\s*'?([^',}]+)'?", text)
|
||||
m_msg = re.search(r"message\s*:\s*'([^']*)'", text)
|
||||
code = m_code.group(1).strip() if m_code else ''
|
||||
msg = m_msg.group(1) if m_msg else ''
|
||||
if not (m_code or m_msg):
|
||||
raise RuntimeError(f"响应无法解析(可能会话失效被踢回页面):{text[:200]}")
|
||||
return code, msg
|
||||
|
||||
|
||||
# ==================== 商户列表 ====================
|
||||
def get_cus_list(session):
|
||||
"""GET 搜索页解析 childcuslist → [{'key': 商户号, 'value': 商户名}, ...]。"""
|
||||
resp = _get(session, config.SEARCH_URL)
|
||||
m = re.search(r"var childcuslist\s*=\s*'([^']*)'", resp.text)
|
||||
if not m:
|
||||
raise RuntimeError("搜索页未找到 childcuslist(会话可能失效,请重新登录)")
|
||||
data = json.loads(m.group(1))
|
||||
if not isinstance(data, list):
|
||||
raise RuntimeError("childcuslist 解析异常")
|
||||
return data
|
||||
|
||||
|
||||
# ==================== 异步导出三步 ====================
|
||||
def start_export(session, cusid, start, end):
|
||||
"""发起导出 → 返回 fid。
|
||||
|
||||
服务端实测(探针 exp_probe + 实跑 + 测速验证):
|
||||
- export=all 会忽略日期参数、导出当天全量(错误行为);
|
||||
- export=onebtnexpt(导出当前查询结果集)才按日期区间导出;
|
||||
- cusid 必须非空:传空串时服务端直接 504 Gateway Timeout(实测 60s 超时);
|
||||
但服务端忽略 cusid 的筛选语义——传任意真实商户号都返回账号全量结果集
|
||||
(不同商户同日期返回同一 fid、同一文件),故用账号下首个商户号即可。
|
||||
因此必须先查询(export=false)建立结果集,再用 onebtnexpt 导出。
|
||||
"""
|
||||
base = {
|
||||
'issubmit': 'issubmit',
|
||||
'cusid': cusid,
|
||||
'startDate': start,
|
||||
'endDate': end,
|
||||
'pageIndex': '1',
|
||||
'canemptycusid': 'true',
|
||||
}
|
||||
# 1) 查询建立结果集(export=false)
|
||||
_post(session, config.SEARCH_URL, {**base, 'export': 'false'})
|
||||
# 2) 导出当前结果集(onebtnexpt)
|
||||
code, msg = _parse_code_message(
|
||||
_post(session, config.SEARCH_URL, {**base, 'export': config.EXPORT_CURRENT}).text)
|
||||
if code == '1':
|
||||
raise RuntimeError(f"导出失败:{msg}")
|
||||
fid = msg
|
||||
if not fid:
|
||||
raise RuntimeError("导出响应缺少 fid")
|
||||
return fid
|
||||
|
||||
|
||||
def wait_export_done(session, fid):
|
||||
"""轮询导出状态,直到就绪(code=0)或超时。
|
||||
|
||||
状态契约(探针实测):code='0'=文件就绪;code='1'=生成中。
|
||||
其它码(如 '2' 失败)只告警不判就绪,避免误把失败态当成功去取下载地址;
|
||||
超时错误里带最后状态,便于定位。
|
||||
"""
|
||||
last = ""
|
||||
for i in range(1, config.STATUS_POLL_MAX + 1):
|
||||
code, msg = _parse_code_message(_post(session, config.STATUS_URL, {'id': fid}).text)
|
||||
last = f"code={code} {msg}".strip()
|
||||
if code == '0':
|
||||
config.log(f"[导出] fid={fid} 文件就绪(轮询 {i} 次)")
|
||||
return True
|
||||
if code != '1':
|
||||
config.log(f"[导出] fid={fid} 状态异常({last}),继续等待", "WARN")
|
||||
else:
|
||||
# 每次轮询都打进度,避免长时间静默被误认为卡死
|
||||
config.log(f"[导出] fid={fid} 文件生成中(第 {i} 次轮询,已等待 {i * config.STATUS_POLL_INTERVAL} 秒)…")
|
||||
time.sleep(config.STATUS_POLL_INTERVAL)
|
||||
raise RuntimeError(f"导出超时(服务端未在时限内生成文件,最后状态:{last})")
|
||||
|
||||
|
||||
def get_download_url(session, fid):
|
||||
"""获取下载地址。"""
|
||||
code, msg = _parse_code_message(_post(session, config.DOWNLOAD_INFO_URL, {'id': fid}).text)
|
||||
if code != '0':
|
||||
raise RuntimeError(f"获取下载地址失败:{msg}")
|
||||
return msg
|
||||
|
||||
|
||||
# ==================== 下载校验 ====================
|
||||
def _check_download_content_type(resp):
|
||||
"""下载响应 Content-Type 校验:HTML/文本说明可能被踢回登录页,直接报错。"""
|
||||
ct = (resp.headers.get('Content-Type') or '').lower()
|
||||
if 'html' in ct or ct.startswith('text/'):
|
||||
raise RuntimeError(
|
||||
f"下载返回非文件内容(Content-Type={ct or 'unknown'}),会话可能已失效,请重新登录")
|
||||
|
||||
|
||||
def _is_zip_file(path):
|
||||
"""文件头魔数校验:zip/xlsx 均以 PK 开头。"""
|
||||
try:
|
||||
with open(path, 'rb') as f:
|
||||
return f.read(2) == b'PK'
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def _safe_extract(zip_path, extract_dir):
|
||||
"""解压 zip,并拦截路径穿越条目(.. / 绝对路径)。"""
|
||||
with zipfile.ZipFile(zip_path) as zf:
|
||||
for info in zf.infolist():
|
||||
parts = Path(info.filename).parts
|
||||
if info.filename.startswith('/') or '..' in parts or ':' in parts:
|
||||
raise RuntimeError(f"压缩包含非法路径条目,已中止解压:{info.filename}")
|
||||
zf.extractall(extract_dir)
|
||||
|
||||
|
||||
def download_file(session, url, folder, stem):
|
||||
"""下载导出文件到 folder/,文件名 stem + 扩展名(优先 Content-Disposition,默认 .xlsx)。
|
||||
返回最终文件路径。带 Content-Type 与文件魔数校验,防会话失效时把 HTML 落成伪文件。"""
|
||||
resp = session.get(url, headers=config.SEARCH_HEADERS, timeout=180, stream=True)
|
||||
resp.raise_for_status()
|
||||
_check_download_content_type(resp)
|
||||
ext = '.xlsx'
|
||||
cd = resp.headers.get('Content-Disposition', '')
|
||||
m = re.search(r'filename\*?=(?:UTF-8\'\')?"?([^\";]+)"?', cd, re.I)
|
||||
if m:
|
||||
nm = m.group(1).strip().strip('"')
|
||||
if '.' in nm:
|
||||
ext = '.' + nm.rsplit('.', 1)[1].lower()
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
path = os.path.join(folder, f"{stem}{ext}")
|
||||
total = int(resp.headers.get('Content-Length') or 0)
|
||||
received, last_log = 0, time.time()
|
||||
with open(path, 'wb') as f:
|
||||
for chunk in resp.iter_content(chunk_size=8192):
|
||||
f.write(chunk)
|
||||
received += len(chunk)
|
||||
now = time.time()
|
||||
if now - last_log >= 8: # 每 8 秒报一次下载进度,避免长下载静默
|
||||
last_log = now
|
||||
mb = received / 1048576
|
||||
if total:
|
||||
pct = received * 100 // max(1, total)
|
||||
config.log(f"[导出] 下载中 {mb:.1f}MB / {total / 1048576:.1f}MB({pct}%)…")
|
||||
else:
|
||||
config.log(f"[导出] 下载中 {mb:.1f}MB…")
|
||||
if not _is_zip_file(path): # xlsx 本质是 zip,文件头须为 PK
|
||||
os.remove(path)
|
||||
raise RuntimeError(f"下载文件不是有效 xlsx(文件头异常),已删除:{path}")
|
||||
config.log(f"[导出] 已保存:{path}({received / 1048576:.1f} MB)")
|
||||
return path
|
||||
|
||||
|
||||
# ==================== 日期范围 ====================
|
||||
def build_date_range(mode, date_str):
|
||||
"""按模式把日期字符串转成查询区间 (start, end)。
|
||||
mode='月':date_str=YYYY-MM → 当月 1 日 10:00:00 ~ 下月 1 日 10:00:00(对账 10 点切日口径);
|
||||
mode='日':date_str=YYYY-MM-DD(数据起始日,默认昨天)→ 当天 00:00:00 ~ 次日 23:59:59
|
||||
(即默认 = 昨天0点 ~ 今天24点,今天数据少基本无影响)。"""
|
||||
if mode == '月':
|
||||
ym = datetime.strptime(date_str, '%Y-%m')
|
||||
next_month = (ym.replace(day=1) + timedelta(days=32)).replace(day=1)
|
||||
return (ym.strftime('%Y-%m-01 10:00:00'),
|
||||
next_month.strftime('%Y-%m-01 10:00:00'))
|
||||
d = datetime.strptime(date_str, '%Y-%m-%d')
|
||||
nxt = d + timedelta(days=1)
|
||||
return d.strftime('%Y-%m-%d 00:00:00'), nxt.strftime('%Y-%m-%d 23:59:59')
|
||||
|
||||
|
||||
def default_dates(mode):
|
||||
"""未填日期时的默认值:日=昨天;月=上月。"""
|
||||
today = datetime.now()
|
||||
if mode == '月':
|
||||
first_this = today.replace(day=1)
|
||||
last_month = first_this - timedelta(days=1)
|
||||
return last_month.strftime('%Y-%m')
|
||||
yesterday = today - timedelta(days=1)
|
||||
return yesterday.strftime('%Y-%m-%d')
|
||||
|
||||
|
||||
# ==================== 账单导出(主账号,zip 下载 + 解压) ====================
|
||||
def bill_download(session, date_str, bill_type, folder):
|
||||
"""通联账单下载(只导主账号/当前商户)。
|
||||
|
||||
POST /checkacct25/download:日账单 ?reportdate=YYYYMMDD;月账单 ?type=month&reportdate=YYYYMM。
|
||||
服务端返回 {"code":"0","message":"<zip 下载 URL>"},GET 下载 zip 并解压。
|
||||
date_str = YYYY-MM-DD(日)或 YYYY-MM(月);bill_type = 'day' | 'month'。
|
||||
返回 (zip_path, extract_dir)。
|
||||
"""
|
||||
reportdate = date_str.replace('-', '')
|
||||
params = {'reportdate': reportdate}
|
||||
if bill_type == 'month':
|
||||
params['type'] = 'month'
|
||||
resp = _post(session, config.BILL_URL, params=params)
|
||||
code, msg = _parse_code_message(resp.text)
|
||||
if code != '0':
|
||||
raise RuntimeError(f"账单下载失败:{msg}")
|
||||
url = msg
|
||||
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
zr = session.get(url, headers=config.SEARCH_HEADERS, timeout=180, stream=True)
|
||||
zr.raise_for_status()
|
||||
_check_download_content_type(zr)
|
||||
prefix = '日账单' if bill_type == 'day' else '月账单'
|
||||
zip_path = os.path.join(folder, f"{prefix}_{date_str}.zip")
|
||||
with open(zip_path, 'wb') as f:
|
||||
for chunk in zr.iter_content(chunk_size=8192):
|
||||
f.write(chunk)
|
||||
if not _is_zip_file(zip_path):
|
||||
os.remove(zip_path)
|
||||
raise RuntimeError(f"账单下载不是有效 zip(文件头异常),已删除:{zip_path}")
|
||||
|
||||
extract_dir = os.path.join(folder, f"{prefix}_{date_str}")
|
||||
_safe_extract(zip_path, extract_dir)
|
||||
config.log(f"[账单] 已下载并解压:{extract_dir}")
|
||||
return zip_path, extract_dir
|
||||
@@ -0,0 +1,478 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""通联支付商户服务平台登录模块(xq0045_xq0046 插件内自包含)。
|
||||
|
||||
自 workflows/share/allinpay_login.py 迁移,插件化改造点:
|
||||
- 账号密码由插件界面配置经 fields 注入(不再读 .env);
|
||||
- print → config.log;返回 requests.Session(登录后会话直接可用,无需浏览器常驻)。
|
||||
|
||||
登录方式(接口优先,浏览器兜底):
|
||||
1) 接口登录(首选,已实测一次成功):GET /login(拿 SESSION + 页面内嵌 publicKey)
|
||||
→ GET /getvalidCode?type=cuserrorCode 验证码图 → ddddocr 识别(4位)
|
||||
→ JSEncrypt 兼容 RSA 加密密码(PKCS#1 v1.5 + base64)→ POST /login(userid/
|
||||
encpassword/cuserrorCode,带 Referer)→ 302 离开 /login 即成功;
|
||||
2) 浏览器兜底:DrissionPage 现场登录(验证码元素截图 + ddddocr),成功后从浏览器
|
||||
cookies 构建 requests.Session。
|
||||
|
||||
登录页(账号登录 tab,DOM 参考 aa.md):
|
||||
账号 #userid / 密码 #password(初始 readonly,onfocus 移除;提交时页面 JS 加密进 #encpassword)
|
||||
验证码 #captcha + 图 <img src="/getvalidCode?type=cuserrorCode">(URL 型,元素截图 + ddddocr)
|
||||
登录按钮 button[onclick*="valandsubmit"](触发 valandsubmit JS 加密密码后提交表单)
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import random
|
||||
import re
|
||||
import time
|
||||
|
||||
import requests
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
from .. import config
|
||||
|
||||
_UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"Chrome/120.0.0.0 Safari/537.36")
|
||||
HUMAN_DELAY = (0.4, 1.2)
|
||||
_VALIDCODE_URL = config.LOGIN_URL.replace('/login', '/getvalidCode?type=cuserrorCode')
|
||||
_PUBKEY_RE = re.compile(r"var publicKey='([^']+)'")
|
||||
_LOGIN_FORM_RE = re.compile(r'<form[^>]*id=["\']?accountForm|action=["\']?/login')
|
||||
|
||||
_ocr = None
|
||||
|
||||
|
||||
def _get_ocr():
|
||||
"""ddddocr 单例(懒加载),接口/浏览器登录共用。"""
|
||||
global _ocr
|
||||
if _ocr is None:
|
||||
import ddddocr
|
||||
_ocr = ddddocr.DdddOcr(show_ad=False)
|
||||
return _ocr
|
||||
|
||||
|
||||
def _human_pause(a=None, b=None):
|
||||
"""操作间随机延时,模拟人工节奏。"""
|
||||
lo, hi = HUMAN_DELAY if (a is None or b is None) else (a, b)
|
||||
time.sleep(random.uniform(lo, hi))
|
||||
|
||||
|
||||
def _rsa_encrypt(pubkey, pwd):
|
||||
"""JSEncrypt 兼容:RSA PKCS#1 v1.5 加密 + base64。
|
||||
|
||||
页面 publicKey 是 SPKI/X.509 SubjectPublicKeyInfo(BEGIN PUBLIC KEY)裸 DER,
|
||||
用 cryptography 解析后按 PKCS#1 v1.5 填充加密(1024 位公钥,明文 ≤117 字节)。
|
||||
"""
|
||||
from cryptography.hazmat.backends import default_backend
|
||||
from cryptography.hazmat.primitives.asymmetric import padding
|
||||
from cryptography.hazmat.primitives.serialization import load_der_public_key
|
||||
pub = load_der_public_key(base64.b64decode(pubkey), default_backend())
|
||||
ct = pub.encrypt(pwd.encode(), padding.PKCS1v15())
|
||||
return base64.b64encode(ct).decode()
|
||||
|
||||
|
||||
def _api_login(username, password):
|
||||
"""接口登录(纯 requests,不弹浏览器)。成功返回 requests.Session,失败返回 None。
|
||||
|
||||
服务端行为(探针实测):
|
||||
- /login 页面内嵌固定 RSA 公钥(publicKey,1024 位 PKCS#1);
|
||||
- 验证码 4 位,GET /getvalidCode?type=cuserrorCode 返回图片(session 绑定);
|
||||
- POST /login 需带 Referer(外链校验),成功 302 到 /main。
|
||||
"""
|
||||
session = requests.Session()
|
||||
session.headers.update({"User-Agent": _UA})
|
||||
try:
|
||||
if len(password.encode()) > 117:
|
||||
# 页面公钥 1024 位,PKCS#1 v1.5 明文上限 117 字节;超长无法加密,
|
||||
# 明确提示后走浏览器兜底登录
|
||||
config.log("[通联登录] 密码过长(>117 字节),接口登录无法加密,将回退浏览器登录")
|
||||
return None
|
||||
html = session.get(config.LOGIN_URL, timeout=20).text
|
||||
m = _PUBKEY_RE.search(html)
|
||||
if not m:
|
||||
config.log("[通联登录] 接口登录失败:未找到 publicKey")
|
||||
return None
|
||||
pubkey = m.group(1)
|
||||
enc = _rsa_encrypt(pubkey, password)
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 接口登录准备异常:{e}")
|
||||
return None
|
||||
|
||||
ocr = _get_ocr()
|
||||
for attempt in range(config.API_CAPTCHA_RETRY):
|
||||
try:
|
||||
img = session.get(_VALIDCODE_URL, timeout=20).content
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 获取验证码图异常:{e}")
|
||||
return None
|
||||
code = ocr.classification(img).strip()
|
||||
config.log(f"[通联登录] 接口登录 第 {attempt + 1}/{config.API_CAPTCHA_RETRY} 次验证码识别:{code!r}")
|
||||
if len(code) != 4:
|
||||
time.sleep(1)
|
||||
continue
|
||||
try:
|
||||
resp = session.post(config.LOGIN_URL, data={
|
||||
'userid': username,
|
||||
'encpassword': enc,
|
||||
'cuserrorCode': code,
|
||||
}, headers={'Referer': config.LOGIN_URL}, timeout=20, allow_redirects=True)
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 提交登录异常:{e}")
|
||||
return None
|
||||
if '/login' not in resp.url:
|
||||
config.log(f"[通联登录] 接口登录成功:{resp.url}")
|
||||
return session
|
||||
# 仍在登录页:验证码错/账号密码错/风控。每次提交都计入服务端尝试次数,
|
||||
# 失败后退避并停止(不连续重试,避免触发登录次数风控锁定)
|
||||
hit = re.search(r'验证码错误|验证码不正确|账号或密码|密码错误|登录失败|次数已达上限|锁定', resp.text)
|
||||
if hit:
|
||||
config.log(f"[通联登录] 服务端提示:{hit.group(0)}")
|
||||
if '次数已达上限' in hit.group(0) or '锁定' in hit.group(0):
|
||||
config.log("[通联登录] 检测到风控锁定提示,立即停止登录尝试")
|
||||
return None
|
||||
time.sleep(config.LOGIN_FAIL_BACKOFF)
|
||||
config.log("[通联登录] 接口登录验证码多次未通过,停止重试")
|
||||
return None
|
||||
|
||||
|
||||
def _on_target(page):
|
||||
"""登录成功判定:URL 离开 /login。"""
|
||||
try:
|
||||
return '/login' not in (page.url or '')
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _find_input(page, selectors):
|
||||
for sel in selectors:
|
||||
ele = page.ele(sel, timeout=2)
|
||||
if ele:
|
||||
return ele
|
||||
return None
|
||||
|
||||
|
||||
def _find_captcha(page):
|
||||
"""定位验证码输入框 + 图片(从 #captcha 容器向上找,避免命中验证码登录 tab 的图)。"""
|
||||
code_input = page.ele('#captcha', timeout=config.TIMEOUT)
|
||||
img = None
|
||||
if code_input:
|
||||
holder = code_input.parent(1) # div.input-group#captcha_div
|
||||
if holder:
|
||||
img = holder.ele('tag:img', timeout=1)
|
||||
if img is None:
|
||||
img = page.ele('css:.tab-pane.active img[src*="getvalidCode"]', timeout=2)
|
||||
return img, code_input
|
||||
|
||||
|
||||
def _read_img_bytes(img):
|
||||
"""URL 型验证码(/getvalidCode)直接元素截图;兼容 base64 内嵌 src。"""
|
||||
try:
|
||||
src = img.attr('src') or ''
|
||||
if 'base64,' in src:
|
||||
return base64.b64decode(src.split('base64,', 1)[1])
|
||||
except Exception:
|
||||
pass
|
||||
return img.get_screenshot(as_bytes='png')
|
||||
|
||||
|
||||
def _recognize_captcha(img_bytes):
|
||||
"""ddddocr 识别图形验证码,返回文本。懒加载避免无关场景导入开销。"""
|
||||
import ddddocr
|
||||
ocr = ddddocr.DdddOcr(show_ad=False)
|
||||
return ocr.classification(img_bytes).strip()
|
||||
|
||||
|
||||
def _refresh_captcha(page, img):
|
||||
"""点击验证码图片刷新(onclick=cusjsUtil.changeCode)。URL 型验证码无法可靠比对,点击后等渲染。"""
|
||||
for _ in range(2):
|
||||
try:
|
||||
img.click()
|
||||
except Exception:
|
||||
try:
|
||||
img.click(by_js=True)
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.8)
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def _ensure_account_tab(page):
|
||||
"""确保「账号登录」tab 激活(默认激活;若页面记住验证码登录则切回)。"""
|
||||
uid = page.ele('#userid', timeout=2)
|
||||
if uid:
|
||||
try:
|
||||
if uid.states.is_displayed:
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
tab_btn = page.ele('css:a[href="#account"], css:a[data-target="#account"]', timeout=3) \
|
||||
or page.ele('tag:a@@text():账号登录', timeout=3)
|
||||
if tab_btn:
|
||||
try:
|
||||
tab_btn.click()
|
||||
time.sleep(0.5)
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
|
||||
|
||||
def _wait_login_result(page):
|
||||
"""提交后轮询判定登录结果,返回 bool。"""
|
||||
for _ in range(30): # 最多等 15 秒
|
||||
time.sleep(0.5)
|
||||
if _on_target(page):
|
||||
config.log(f"[通联登录] 登录成功:{page.url}")
|
||||
return True
|
||||
for sel in ('css:.invalid-feedback', 'css:.alert-danger', 'css:.toast'):
|
||||
try:
|
||||
eles = page.eles(sel, timeout=0.3)
|
||||
except Exception:
|
||||
continue
|
||||
for ele in eles:
|
||||
try:
|
||||
text = ele.text.strip()
|
||||
except Exception:
|
||||
text = ''
|
||||
if text:
|
||||
config.log(f"[通联登录] 失败提示:{text}")
|
||||
return False
|
||||
return False
|
||||
|
||||
|
||||
def _input_value(ele):
|
||||
"""读取输入框当前值(页面刷新后表单清空,用于判断是否需要重填)。"""
|
||||
try:
|
||||
return ele.value or ''
|
||||
except Exception:
|
||||
try:
|
||||
return ele.attr('value') or ''
|
||||
except Exception:
|
||||
return ''
|
||||
|
||||
|
||||
def _fill_account(page, username, password):
|
||||
"""确保账号密码已填(每轮提交前调用)。
|
||||
|
||||
通联登录失败后页面会整页刷新、表单被清空;这里做幂等填充——
|
||||
账号/密码已存在则跳过,被清空则重新输入,避免后续重试提交空表单。
|
||||
"""
|
||||
user_input = page.ele('#userid', timeout=config.TIMEOUT)
|
||||
if not user_input:
|
||||
config.log("[通联登录] 找不到账号输入框")
|
||||
return False
|
||||
if _input_value(user_input) != username:
|
||||
user_input.clear()
|
||||
user_input.input(username)
|
||||
_human_pause()
|
||||
|
||||
pwd_input = _find_input(page, ['#password', 'css:input[type="password"]:not([name="encpassword"])'])
|
||||
if not pwd_input:
|
||||
config.log("[通联登录] 找不到密码输入框")
|
||||
return False
|
||||
if not _input_value(pwd_input):
|
||||
pwd_input.click() # 触发 onfocus 移除 readonly
|
||||
_human_pause(0.2, 0.5)
|
||||
pwd_input.clear()
|
||||
pwd_input.input(password)
|
||||
_human_pause()
|
||||
return True
|
||||
|
||||
|
||||
def _try_login_once(page, username, password):
|
||||
"""完成一次填表 + 验证码 + 提交,返回 bool。
|
||||
每轮提交前都会确保账号密码已填(页面刷新后自动重填)。"""
|
||||
_ensure_account_tab(page)
|
||||
|
||||
for attempt in range(config.CAPTCHA_RETRY):
|
||||
if not _fill_account(page, username, password):
|
||||
return False
|
||||
config.log(f"[通联登录] 第 {attempt + 1}/{config.CAPTCHA_RETRY} 次验证码识别")
|
||||
img, code_input = _find_captcha(page)
|
||||
if not img or not code_input:
|
||||
config.log("[通联登录] 找不到验证码图片或输入框")
|
||||
return False
|
||||
img_bytes = _read_img_bytes(img)
|
||||
if not img_bytes:
|
||||
time.sleep(1)
|
||||
continue
|
||||
try:
|
||||
code = _recognize_captcha(img_bytes)
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] ddddocr 识别异常:{e}")
|
||||
return False
|
||||
config.log(f"[通联登录] 识别结果:{code!r}")
|
||||
if not code:
|
||||
_refresh_captcha(page, img)
|
||||
continue
|
||||
code_input.click() # 触发 onfocus 移除 readonly
|
||||
code_input.clear()
|
||||
code_input.input(code)
|
||||
_human_pause(0.3, 0.9)
|
||||
|
||||
btn = page.ele('css:.tab-pane.active button[onclick*="valandsubmit"]', timeout=config.TIMEOUT) \
|
||||
or page.ele('tag:button@@text():登录', timeout=config.TIMEOUT)
|
||||
if not btn:
|
||||
config.log("[通联登录] 找不到登录提交按钮")
|
||||
return False
|
||||
_human_pause(0.2, 0.6)
|
||||
btn.click()
|
||||
|
||||
if _wait_login_result(page):
|
||||
return True
|
||||
_refresh_captcha(page, img)
|
||||
return False
|
||||
|
||||
|
||||
def _build_session(page):
|
||||
"""从浏览器 cookies 构建 requests.Session(仅保留 allinpay.com 域)。"""
|
||||
session = requests.Session()
|
||||
session.headers.update({"User-Agent": _UA})
|
||||
try:
|
||||
for c in page.cookies():
|
||||
domain = (c.get('domain') or '')
|
||||
if 'allinpay.com' not in domain:
|
||||
continue
|
||||
session.cookies.set(c['name'], c['value'],
|
||||
domain=domain.lstrip('.'), path=c.get('path', '/'))
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 提取 cookies 异常:{e}")
|
||||
return session
|
||||
|
||||
|
||||
# ==================== 会话落盘复用(跨 run,子进程隔离下也生效) ====================
|
||||
def _dump_cookies(session):
|
||||
"""把 requests.Session 的 cookies 序列化为可持久化列表。"""
|
||||
out = []
|
||||
for c in session.cookies:
|
||||
out.append({'name': c.name, 'value': c.value, 'domain': c.domain or '',
|
||||
'path': c.path or '/'})
|
||||
return out
|
||||
|
||||
|
||||
def save_session(username, session):
|
||||
"""登录成功后把会话 cookies 落盘,供下次运行直接复用。失败不影响本次执行。"""
|
||||
try:
|
||||
data = {'username': username, 'cookies': _dump_cookies(session)}
|
||||
with open(config.get_session_file(), 'w', encoding='utf-8') as f:
|
||||
json.dump(data, f, ensure_ascii=False)
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 保存会话失败(不影响本次执行):{e}")
|
||||
|
||||
|
||||
def _session_valid(session):
|
||||
"""会话探活:GET 首页,未落回 /login 且页面内容不含登录表单即视为有效。
|
||||
|
||||
平台为单点登录(多地互斥):一旦其它设备/浏览器用同一账号重新登录,
|
||||
本会话立即失效。此时 main.dsr 仍返回 200,但页面内容是登录表单
|
||||
(<form id="accountForm" action="/login">)而非业务首页——仅看 URL 会误判
|
||||
为有效,导致后续 API 全部失败,必须校验页面内容。
|
||||
"""
|
||||
try:
|
||||
resp = session.get(config.MAIN_URL, headers=config.SEARCH_HEADERS,
|
||||
timeout=15, allow_redirects=True)
|
||||
if resp.status_code != 200 or '/login' in resp.url:
|
||||
return False
|
||||
return not _LOGIN_FORM_RE.search(resp.text)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def load_session(username):
|
||||
"""读取并重建上次登录会话;有效则返回 requests.Session,否则返回 None。"""
|
||||
path = config.get_session_file()
|
||||
try:
|
||||
with open(path, 'r', encoding='utf-8') as f:
|
||||
data = json.load(f)
|
||||
if data.get('username') != username:
|
||||
config.log("[通联登录] 本地会话账号与当前账号不一致,重新登录")
|
||||
return None
|
||||
session = requests.Session()
|
||||
session.headers.update({"User-Agent": _UA})
|
||||
for c in data.get('cookies') or []:
|
||||
session.cookies.set(c['name'], c['value'],
|
||||
domain=c['domain'] or '', path=c['path'] or '/')
|
||||
if _session_valid(session):
|
||||
return session
|
||||
config.log("[通联登录] 本地会话已失效,重新登录")
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 读取本地会话异常:{e}")
|
||||
return None
|
||||
|
||||
|
||||
def tl_login(username, password):
|
||||
"""通联平台登录(本地会话复用 → 接口登录 → 浏览器兜底)。
|
||||
|
||||
成功返回 requests.Session,失败返回 None。登录成功后会话 cookies 落盘,
|
||||
下次运行直接复用免登录(探活失败才重新登录)。
|
||||
"""
|
||||
username = (username or '').strip()
|
||||
password = password or ''
|
||||
if not (username and password):
|
||||
config.log("[通联登录] 账号/密码缺失(请在插件界面填写并保存配置)")
|
||||
return None
|
||||
|
||||
# 1) 复用本地已保存会话(免重新登录)
|
||||
session = load_session(username)
|
||||
if session is not None:
|
||||
config.log("[通联登录] 复用本地已登录会话,免重新登录(单点登录:请勿同时在其")
|
||||
config.log("[通联登录] 它设备/浏览器登录同一账号,否则本会话会被踢下线)")
|
||||
return session
|
||||
|
||||
# 2) 接口登录(首选,不弹浏览器)
|
||||
config.log("[通联登录] 本地会话失效,开始重新登录(单点登录:本次登录会顶掉其它")
|
||||
config.log("[通联登录] 设备/浏览器上的同一账号登录)")
|
||||
session = _api_login(username, password)
|
||||
if session is not None:
|
||||
save_session(username, session)
|
||||
return session
|
||||
config.log("[通联登录] 接口登录未成功,回退浏览器登录")
|
||||
# 3) 浏览器兜底
|
||||
session = _browser_login(username, password)
|
||||
if session is not None:
|
||||
save_session(username, session)
|
||||
return session
|
||||
|
||||
|
||||
def _browser_login(username, password):
|
||||
"""浏览器兜底登录(DrissionPage + ddddocr 图形验证码,元素截图)。
|
||||
|
||||
返回:成功 → requests.Session(从浏览器 cookies 构建);失败 → None。
|
||||
固定默认用户目录保留登录态:已登录会话直接复用(免验证码)。
|
||||
调用方使用完毕无需额外操作(本函数已 page.quit())。
|
||||
"""
|
||||
co = ChromiumOptions()
|
||||
co.set_argument('--start-maximized')
|
||||
co.set_pref('credentials_enable_service', False)
|
||||
co.set_pref('profile.password_manager_enabled', False)
|
||||
# 独立固定用户目录(%LOCALAPPDATA% 下,非临时目录):登录态跨次保留免验证码,
|
||||
# 且不占用用户日常 Chrome 配置、不被系统磁盘清理清掉
|
||||
co.set_user_data_path(config.get_browser_profile_dir())
|
||||
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
page = None
|
||||
try:
|
||||
config.log(f"[通联登录] 浏览器登录 第 {attempt}/{config.RETRY_MAX} 次 → {config.LOGIN_URL}")
|
||||
page = ChromiumPage(co)
|
||||
page.get(config.LOGIN_URL)
|
||||
_human_pause(1.0, 2.0)
|
||||
|
||||
if _on_target(page):
|
||||
config.log(f"[通联登录] 检测到已登录会话,直接复用:{page.url}")
|
||||
session = _build_session(page)
|
||||
page.quit()
|
||||
return session
|
||||
|
||||
if _try_login_once(page, username, password):
|
||||
config.log(f"[通联登录] 登录成功 → {page.url}")
|
||||
session = _build_session(page)
|
||||
page.quit()
|
||||
return session
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 异常:{e}")
|
||||
if page is not None:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
config.log("[通联登录] 浏览器登录重试多次均失败")
|
||||
return None
|
||||
@@ -0,0 +1,69 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0045_xq0046",
|
||||
"name": "金色印象通联数据导出",
|
||||
"version": "1.0.5",
|
||||
"description": "通联支付商户服务平台(cus.allinpay.com)交易数据自动导出:XQ0045 按日、XQ0046 按月,账号全量数据导出(含全部商户),服务端生成文件直存本地",
|
||||
"category": "报表",
|
||||
"icon": "",
|
||||
"platform": "",
|
||||
"uses_month": false,
|
||||
"ui": true,
|
||||
"capabilities": ["xq0045_xq0046"],
|
||||
"permissions": {
|
||||
"platforms": []
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"mode": {
|
||||
"type": "string",
|
||||
"title": "执行模式",
|
||||
"default": "日+月",
|
||||
"enum": ["日", "月", "日+月"],
|
||||
"description": "日/月/日+月:决定日期选择器粒度;交易查询与账单导出共用日期选择器,插件内部自动换算各自区间"
|
||||
},
|
||||
"content": {
|
||||
"type": "string",
|
||||
"title": "导出内容",
|
||||
"default": "两个都导",
|
||||
"enum": ["两个都导", "交易查询", "账单"],
|
||||
"description": "交易查询=逐商户导交易明细(xlsx);账单=主账号日/月账单(zip 下载并解压)"
|
||||
},
|
||||
"day_date": {
|
||||
"type": "string",
|
||||
"format": "date",
|
||||
"title": "按日导出",
|
||||
"default": "",
|
||||
"description": "默认昨天;交易查询区间 = 所选日 00:00 ~ 次日 24:00;账单 = 所选日账单"
|
||||
},
|
||||
"month_date": {
|
||||
"type": "string",
|
||||
"format": "month",
|
||||
"title": "按月导出",
|
||||
"default": "",
|
||||
"description": "默认上月;交易查询区间 = 当月1日 10:00 ~ 下月1日 10:00(对账10点切日);账单 = 该月账单"
|
||||
},
|
||||
"tl_username": {
|
||||
"type": "string",
|
||||
"title": "通联登录账号",
|
||||
"default": "",
|
||||
"description": "商户服务平台登录账号(保存在本机,下次免填)"
|
||||
},
|
||||
"tl_password": {
|
||||
"type": "string",
|
||||
"title": "通联登录密码",
|
||||
"default": "",
|
||||
"format": "password",
|
||||
"description": "仅保存在本机(%LOCALAPPDATA%\\37duAutomation\\plugin_configs),下次免填"
|
||||
},
|
||||
"save_dir": {
|
||||
"type": "string",
|
||||
"title": "保存目录",
|
||||
"default": "",
|
||||
"description": "留空=桌面/金色印象通联数据_YYYYMMDD;交易查询每日期一份全量文件(日_日期.xlsx / 月_月份.xlsx),账单按 账单_YYYYMM 目录存放"
|
||||
}
|
||||
},
|
||||
"required": ["tl_username", "tl_password"]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
DrissionPage>=4.1
|
||||
requests>=2.28
|
||||
ddddocr>=1.4
|
||||
cryptography>=39.0
|
||||
@@ -0,0 +1,12 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>金色印象通联数据导出</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "xq0045-xq0046-ui",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "^2.3.2",
|
||||
"element-plus": "^2.14.5",
|
||||
"vue": "^3.5.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^5.2.1",
|
||||
"vite": "^6.0.3"
|
||||
},
|
||||
"allowScripts": {
|
||||
"esbuild@0.25.12": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<!-- 未登录 / 结果横幅 -->
|
||||
<el-alert v-if="needLogin" type="warning" :closable="false" show-icon title="未登录:请先在壳子(工作台)登录统一账户,再刷新本界面" />
|
||||
<el-alert v-else-if="banner" :type="banner.type" :closable="true" show-icon @close="banner = null">
|
||||
<template #title>{{ banner.text }}</template>
|
||||
</el-alert>
|
||||
|
||||
<!-- 执行配置 -->
|
||||
<el-card shadow="never" class="card">
|
||||
<template #header>
|
||||
<span class="card-title">执行配置</span>
|
||||
<span v-if="lastSavedAt" class="saved">已保存 {{ lastSavedAt }}</span>
|
||||
</template>
|
||||
<el-form label-width="110px" label-position="right">
|
||||
<!-- 通联账号密码 -->
|
||||
<div class="grid">
|
||||
<el-form-item label="通联账号">
|
||||
<el-input v-model="form.tl_username" placeholder="商户服务平台登录账号" :disabled="running" clearable />
|
||||
</el-form-item>
|
||||
<el-form-item label="登录密码">
|
||||
<el-input v-model="form.tl_password" type="password" show-password placeholder="仅保存在本机,下次免填"
|
||||
:disabled="running" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
|
||||
<!-- 执行模式 + 导出内容 -->
|
||||
<div class="grid">
|
||||
<el-form-item label="执行模式">
|
||||
<el-radio-group v-model="form.mode" :disabled="running">
|
||||
<el-radio-button value="日">按日</el-radio-button>
|
||||
<el-radio-button value="月">按月</el-radio-button>
|
||||
<el-radio-button value="日+月">日 + 月</el-radio-button>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
<el-form-item label="导出内容">
|
||||
<el-radio-group v-model="form.content" :disabled="running">
|
||||
<el-radio-button value="交易查询">交易查询</el-radio-button>
|
||||
<el-radio-button value="账单">账单</el-radio-button>
|
||||
<el-radio-button value="两个都导">两个都导</el-radio-button>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
</div>
|
||||
|
||||
<!-- 日期选择器(组件复用:交易查询与账单共用,插件内部按导出类型自动换算区间) -->
|
||||
<div v-if="form.mode === '日+月'" class="grid">
|
||||
<el-form-item label="按日导出">
|
||||
<el-date-picker v-model="form.day_date" type="date" value-format="YYYY-MM-DD"
|
||||
placeholder="选择日期(默认昨天)" :disabled="running"
|
||||
:disabled-date="disableFuture" class="wide" />
|
||||
<div class="tip">默认昨天;区间=所选日 00:00 ~ 次日 24:00(跨 2 天)</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="按月导出">
|
||||
<el-date-picker v-model="form.month_date" type="month" value-format="YYYY-MM"
|
||||
placeholder="选择月份(默认上月)" :disabled="running"
|
||||
:disabled-date="disableFutureMonth" class="wide" />
|
||||
<div class="tip">默认上月;区间=当月1日 10:00 ~ 下月1日 10:00(对账10点切日)</div>
|
||||
</el-form-item>
|
||||
</div>
|
||||
|
||||
<el-form-item v-else-if="form.mode === '日'" label="按日导出">
|
||||
<el-date-picker v-model="form.day_date" type="date" value-format="YYYY-MM-DD"
|
||||
placeholder="选择日期(默认昨天)" :disabled="running"
|
||||
:disabled-date="disableFuture" class="wide" />
|
||||
<div class="tip">默认昨天;区间=所选日 00:00 ~ 次日 24:00(跨 2 天);账单 = 所选日账单</div>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item v-else label="按月导出">
|
||||
<el-date-picker v-model="form.month_date" type="month" value-format="YYYY-MM"
|
||||
placeholder="选择月份(默认上月)" :disabled="running"
|
||||
:disabled-date="disableFutureMonth" class="wide" />
|
||||
<div class="tip">默认上月;区间=当月1日 10:00 ~ 下月1日 10:00(对账10点切日);账单 = 该月账单</div>
|
||||
</el-form-item>
|
||||
|
||||
<!-- 保存目录 -->
|
||||
<el-form-item label="保存目录">
|
||||
<el-input v-model="form.save_dir" :disabled="running" clearable
|
||||
placeholder="留空 = 桌面/金色印象通联数据_今天日期" class="wide" />
|
||||
<div class="tip">交易查询=每日期一份账号全量文件(日_日期.xlsx / 月_月份.xlsx,含全部商户);账单=按 账单_YYYYMM 目录存放</div>
|
||||
</el-form-item>
|
||||
|
||||
<div class="actions">
|
||||
<el-button type="primary" size="large" :loading="running" @click="run">
|
||||
{{ running ? '执行中 ' + progress + '%' : '一键执行' }}
|
||||
</el-button>
|
||||
<el-button v-if="running" type="danger" size="large" plain :loading="stopping"
|
||||
@click="forceStop">强制停止</el-button>
|
||||
<el-button size="large" :disabled="running" @click="saveNow(true)">保存配置</el-button>
|
||||
<el-button size="large" text :disabled="running" @click="resetDefaults">恢复默认</el-button>
|
||||
</div>
|
||||
</el-form>
|
||||
</el-card>
|
||||
|
||||
<!-- 运行状态 -->
|
||||
<div v-if="running" class="status">
|
||||
<el-progress :percentage="progress" :stroke-width="8" class="status-bar" />
|
||||
<span class="status-txt">正在执行,日志与进度实时显示在工作台下方【运行日志】区</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { onMounted, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { connectWS, getRun, loadConfig, saveConfig, startRun, stopRun } from './api'
|
||||
|
||||
function fmtDate(d) {
|
||||
const y = d.getFullYear()
|
||||
const m = String(d.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(d.getDate()).padStart(2, '0')
|
||||
return `${y}-${m}-${day}`
|
||||
}
|
||||
|
||||
function fmtMonth(d) {
|
||||
const y = d.getFullYear()
|
||||
const m = String(d.getMonth() + 1).padStart(2, '0')
|
||||
return `${y}-${m}`
|
||||
}
|
||||
|
||||
function lastMonthStr(now) {
|
||||
const d = new Date(now.getFullYear(), now.getMonth() - 1, 1)
|
||||
return fmtMonth(d)
|
||||
}
|
||||
|
||||
function yesterdayStr(now) {
|
||||
const d = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1)
|
||||
return fmtDate(d)
|
||||
}
|
||||
|
||||
const DEFAULTS = () => {
|
||||
const now = new Date()
|
||||
return {
|
||||
mode: '日+月',
|
||||
content: '两个都导',
|
||||
day_date: yesterdayStr(now), // 默认昨天
|
||||
month_date: lastMonthStr(now), // 默认上月
|
||||
tl_username: '',
|
||||
tl_password: '',
|
||||
save_dir: '',
|
||||
}
|
||||
}
|
||||
|
||||
const form = reactive(DEFAULTS())
|
||||
const loaded = ref(false)
|
||||
const needLogin = ref(false)
|
||||
const banner = ref(null)
|
||||
const lastSavedAt = ref('')
|
||||
const running = ref(false)
|
||||
const progress = ref(0)
|
||||
const stopping = ref(false)
|
||||
|
||||
let ws = null
|
||||
let runId = ''
|
||||
let pollTimer = null
|
||||
let saveTimer = null
|
||||
|
||||
function disableFuture(date) {
|
||||
return date.getTime() > Date.now() + 86400000 // 今天及以前可选
|
||||
}
|
||||
|
||||
function disableFutureMonth(date) {
|
||||
const now = new Date()
|
||||
return date.getTime() > new Date(now.getFullYear(), now.getMonth() + 1, 1).getTime()
|
||||
}
|
||||
|
||||
// ---------- 配置加载 / 保存(自动保存到本机 plugin_configs) ----------
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const saved = await loadConfig()
|
||||
Object.keys(form).forEach((k) => {
|
||||
if (saved[k] !== undefined && saved[k] !== null && saved[k] !== '') {
|
||||
form[k] = saved[k]
|
||||
}
|
||||
})
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.warning('读取本机配置失败,已用默认值:' + e.message)
|
||||
}
|
||||
loaded.value = true
|
||||
})
|
||||
|
||||
watch(form, () => {
|
||||
if (!loaded.value || running.value) return
|
||||
clearTimeout(saveTimer)
|
||||
saveTimer = setTimeout(() => saveNow(false), 800)
|
||||
}, { deep: true })
|
||||
|
||||
async function saveNow(explicit) {
|
||||
try {
|
||||
await saveConfig(JSON.parse(JSON.stringify(form)))
|
||||
lastSavedAt.value = new Date().toLocaleTimeString('zh-CN', { hour12: false })
|
||||
if (explicit) ElMessage.success('配置已保存到本机')
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.error('配置保存失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
function resetDefaults() {
|
||||
Object.assign(form, DEFAULTS())
|
||||
ElMessage.info('已恢复默认配置')
|
||||
}
|
||||
|
||||
// ---------- 执行 ----------
|
||||
function validate() {
|
||||
if (!form.tl_username.trim() || !form.tl_password) {
|
||||
ElMessage.warning('请先填写通联登录账号和密码')
|
||||
return false
|
||||
}
|
||||
if (form.mode !== '月' && !form.day_date) { ElMessage.warning('请选择按日导出的日期'); return false }
|
||||
if (form.mode !== '日' && !form.month_date) { ElMessage.warning('请选择按月导出的月份'); return false }
|
||||
return true
|
||||
}
|
||||
|
||||
async function run() {
|
||||
if (running.value) return
|
||||
if (needLogin.value) {
|
||||
try {
|
||||
await loadConfig()
|
||||
needLogin.value = false
|
||||
ElMessage.success('登录态已恢复,请再次点击执行')
|
||||
return
|
||||
} catch (_) { /* 仍未登录 */ }
|
||||
ElMessage.warning('未登录:请先在壳子登录统一账户,再打开本界面')
|
||||
return
|
||||
}
|
||||
if (!validate()) return
|
||||
await saveNow(false)
|
||||
running.value = true
|
||||
progress.value = 0
|
||||
banner.value = null
|
||||
try {
|
||||
const payload = {
|
||||
mode: form.mode,
|
||||
content: form.content,
|
||||
day_date: form.mode === '月' ? '' : form.day_date,
|
||||
month_date: form.mode === '日' ? '' : form.month_date,
|
||||
tl_username: form.tl_username,
|
||||
tl_password: form.tl_password,
|
||||
save_dir: form.save_dir,
|
||||
}
|
||||
const r = await startRun(payload)
|
||||
runId = r.run_id
|
||||
connect()
|
||||
startPolling()
|
||||
} catch (e) {
|
||||
running.value = false
|
||||
stopPolling()
|
||||
if (e.code === 401) needLogin.value = true
|
||||
banner.value = { type: 'error', text: '启动执行失败:' + e.message }
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 强制停止 ----------
|
||||
async function forceStop() {
|
||||
if (!runId || stopping.value) return
|
||||
stopping.value = true
|
||||
try {
|
||||
await stopRun(runId)
|
||||
ElMessage.warning('已发出强制停止指令,正在终止执行进程…')
|
||||
} catch (e) {
|
||||
ElMessage.error('停止失败:' + e.message)
|
||||
} finally {
|
||||
stopping.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 实时进度 + 完成 ----------
|
||||
function connect() {
|
||||
if (ws && ws.readyState <= 1) return
|
||||
ws = connectWS((ev) => {
|
||||
if (ev.run_id && ev.run_id !== runId) return
|
||||
if (ev.t === 'progress') progress.value = Math.max(progress.value, ev.pct || 0)
|
||||
else if (ev.t === 'run_done') ev.ok ? finished() : failed(ev.error || '执行失败')
|
||||
})
|
||||
ws.onclose = () => { ws = null }
|
||||
}
|
||||
|
||||
function startPolling() {
|
||||
stopPolling()
|
||||
pollTimer = setInterval(async () => {
|
||||
if (!runId) return
|
||||
try {
|
||||
const r = await getRun(runId)
|
||||
if (r.status === 'done') finished(r.result?.summary || '执行完成')
|
||||
else if (r.status === 'error') failed(r.error || '执行失败')
|
||||
} catch (_) { /* 下轮再试 */ }
|
||||
}, 5000)
|
||||
}
|
||||
|
||||
function stopPolling() {
|
||||
if (pollTimer) { clearInterval(pollTimer); pollTimer = null }
|
||||
}
|
||||
|
||||
async function finished(summary) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
progress.value = 100
|
||||
banner.value = { type: 'success', text: summary || '执行完成' }
|
||||
}
|
||||
|
||||
function failed(err) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
banner.value = { type: 'error', text: '执行失败:' + err }
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.page {
|
||||
width: 100%;
|
||||
padding: 4px 2px 20px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.card {
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.card-title {
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.saved {
|
||||
float: right;
|
||||
font-size: 12px;
|
||||
font-weight: 400;
|
||||
color: #67c23a;
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: flex;
|
||||
gap: 18px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.grid .el-form-item {
|
||||
flex: 1;
|
||||
min-width: 280px;
|
||||
}
|
||||
|
||||
.wide {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.tip {
|
||||
width: 100%;
|
||||
font-size: 12px;
|
||||
color: #909399;
|
||||
line-height: 1.6;
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
border-top: 1px dashed var(--el-border-color);
|
||||
padding-top: 16px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 10px 14px;
|
||||
border-radius: 10px;
|
||||
background: var(--el-color-primary-light-9);
|
||||
border: 1px solid var(--el-color-primary-light-7);
|
||||
}
|
||||
|
||||
.status-bar {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.status-txt {
|
||||
font-size: 12px;
|
||||
color: #606266;
|
||||
white-space: nowrap;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,50 @@
|
||||
// 与壳子后端交互(同源,统一账户会话 cookie 自动携带)+ WebSocket 实时流
|
||||
export const PLUGIN_ID = 'xq0045_xq0046'
|
||||
|
||||
async function j(url, opts) {
|
||||
const res = await fetch(url, opts)
|
||||
if (res.status === 401) {
|
||||
throw Object.assign(new Error('未登录:请先在壳子登录统一账户再打开本界面'), { code: 401 })
|
||||
}
|
||||
if (!res.ok) {
|
||||
let msg = `HTTP ${res.status}`
|
||||
try { msg = (await res.json()).detail || msg } catch (e) { /* 保留默认 */ }
|
||||
throw new Error(msg)
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
export function loadConfig() {
|
||||
return j(`/api/plugin-config/${PLUGIN_ID}`)
|
||||
}
|
||||
|
||||
export function saveConfig(data) {
|
||||
return j(`/api/plugin-config/${PLUGIN_ID}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export function startRun(fields) {
|
||||
return j('/api/runs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, fields }),
|
||||
})
|
||||
}
|
||||
|
||||
export function getRun(runId) {
|
||||
return j(`/api/runs/${runId}`)
|
||||
}
|
||||
|
||||
export function stopRun(runId) {
|
||||
return j(`/api/runs/${runId}/stop`, { method: 'POST' })
|
||||
}
|
||||
|
||||
export function connectWS(onEvent) {
|
||||
const ws = new WebSocket((location.protocol === 'https:' ? 'wss://' : 'ws://')
|
||||
+ location.host + '/ws')
|
||||
ws.onmessage = (e) => { try { onEvent(JSON.parse(e.data)) } catch (_) { /* 忽略脏帧 */ } }
|
||||
return ws
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { createApp } from 'vue'
|
||||
import ElementPlus from 'element-plus'
|
||||
import 'element-plus/dist/index.css'
|
||||
import zhCn from 'element-plus/es/locale/lang/zh-cn'
|
||||
import App from './App.vue'
|
||||
|
||||
createApp(App).use(ElementPlus, { locale: zhCn }).mount('#app')
|
||||
@@ -0,0 +1,21 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
// 插件 UI 由壳子后端托管在 /pui/xq0045_xq0046/ 下,
|
||||
// 构建产物直接输出到插件包 ui/ 目录(随插件 zip 发布,壳子零改动)。
|
||||
// dev 模式经代理访问本机壳子后端,便于联调。
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
base: '/pui/xq0045_xq0046/',
|
||||
build: {
|
||||
outDir: '../ui',
|
||||
emptyOutDir: true,
|
||||
},
|
||||
server: {
|
||||
port: 5180,
|
||||
proxy: {
|
||||
'/api': 'http://127.0.0.1:8799',
|
||||
'/ws': { target: 'ws://127.0.0.1:8799', ws: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,13 @@
|
||||
<!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/xq0045_xq0046/assets/index-CuUBZGG_.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0045_xq0046/assets/index-CmyoQ4x2.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,41 @@
|
||||
# ERP报表导出(xq0031_xq0032)
|
||||
|
||||
金蝶 K3Cloud 报表自动导出插件:物料收发汇总表(需求31)+ 采购订单列表(需求32),
|
||||
支持新旧系统切换、仓库编码多选(或关系)、日期多档(N天 / 自定义区间)逐档导出。
|
||||
|
||||
## 目录结构
|
||||
|
||||
- `*.py` — 插件后端(ScenePlugin 注册 + ERP 登录 + 两报表逻辑),自包含,
|
||||
只引用标准库 / 第三方依赖 / 底座注入接口(`webhost.backend.plugins.base`)
|
||||
- `ui/` — 插件前端**构建产物**(壳子后端托管于 `/pui/xq0031_xq0032/`,勿手改)
|
||||
- `ui-src/` — 插件前端源码(Vue 3 + Element Plus + Vite)
|
||||
- `_pack.py` — 发布打包辅助(`_` 前缀,运行时不会被插件扫描加载)
|
||||
|
||||
## 前端开发 / 构建
|
||||
|
||||
```bash
|
||||
cd ui-src
|
||||
npm install
|
||||
npm run build # 产物输出到 ../ui/(vite.config.js 里 base=/pui/xq0031_xq0032/)
|
||||
```
|
||||
|
||||
联调:先启动壳子(webhost),`npm run dev` 走 vite 代理(5180 → 127.0.0.1:8799)。
|
||||
|
||||
## 打包发布
|
||||
|
||||
1. 构建 ui(见上)
|
||||
2. `desktop/` 下执行:`../.venv/Scripts/python.exe ../plugins/xq0031_xq0032/_pack.py`
|
||||
→ 产出 `dist-plugin/xq0031_xq0032_v<版本>.zip`(自动排除 ui-src 等)
|
||||
3. `desktop/` 下发布:
|
||||
`.venv\Scripts\python.exe -m controlplane.tools.agent_cli publish dist-plugin\xq0031_xq0032_v<版本>.zip --id xq0031_xq0032 --version <版本> --admin puddy`
|
||||
|
||||
## 个性化配置(自带界面)
|
||||
|
||||
`plugin.json` 声明 `"ui": true`,壳子插件页展示「打开插件界面」入口(弹独立窗口,
|
||||
同源自动携带登录会话)。账号密码 / 仓库编码 / 日期选项等在窗口内填写:
|
||||
|
||||
- 配置经壳子 `GET/POST /api/plugin-config/xq0031_xq0032` 保存,
|
||||
落执行机本机 `%LOCALAPPDATA%\37duAutomation\plugin_configs\xq0031_xq0032.json`,
|
||||
下次打开自动回填(表单改动防抖自动保存);
|
||||
- 执行经现有 `POST /api/runs`,日志/进度经 `WS /ws` 实时回显(另有 5 秒轮询兜底);
|
||||
- 浏览器每次现场真登录(auto_port 独立实例),确保登录的就是本次配置的账号。
|
||||
@@ -0,0 +1,184 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""ERP报表导出 - webhost 场景插件(XQ0031 + XQ0032 合并版)
|
||||
|
||||
金蝶 K3Cloud 报表自动导出,两种报表可单选或同次会话连导(登录一次):
|
||||
物料收发汇总表(XQ0031):组织/仓库编码(或关系多行)/日期多档(N天或自定义区间)逐档导出
|
||||
采购订单列表(XQ0032):快捷方案 → 等查询 → 按列表引出数据
|
||||
|
||||
个性化设计(自带 Vue 界面,plugin.json 声明 "ui": true):
|
||||
- ERP 新/旧系统、登录账号密码由用户在插件窗口内自行填写,
|
||||
经 /api/plugin-config 保存在执行机本机,下次打开自动回填;
|
||||
- 仓库编码、日期选项均为多选(可自建条目,日期可混入自定义区间);
|
||||
- 浏览器现场真登录(固定默认用户目录,保留登录态/配置),确保用的就是本次配置的账号。
|
||||
"""
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
||||
|
||||
from . import config
|
||||
from . import erp_login
|
||||
|
||||
# 执行模式
|
||||
MODE_31 = '物料收发汇总表'
|
||||
MODE_32 = '采购订单列表'
|
||||
MODE_BOTH = '两个都导'
|
||||
|
||||
|
||||
def _as_str_list(value):
|
||||
"""fields 里的多选值归一为去空去重的字符串列表(兼容逗号/空格分隔的字符串)。"""
|
||||
if value is None:
|
||||
return []
|
||||
if isinstance(value, str):
|
||||
parts = value.replace(',', ',').replace(' ', ',').split(',')
|
||||
elif isinstance(value, (list, tuple)):
|
||||
parts = list(value)
|
||||
else:
|
||||
parts = [value]
|
||||
out, seen = [], set()
|
||||
for p in parts:
|
||||
s = str(p).strip()
|
||||
if s and s not in seen:
|
||||
seen.add(s)
|
||||
out.append(s)
|
||||
return out
|
||||
|
||||
|
||||
class ErpReportExportPlugin(ScenePlugin):
|
||||
id = "xq0031_xq0032"
|
||||
name = "ERP物料收发汇总-采购订单报表导出"
|
||||
version = "1.0.10"
|
||||
description = "金蝶K3Cloud报表导出:物料收发汇总表+ 采购订单列表,支持新旧系统与个性化配置"
|
||||
platform = "" # ERP 自带登录页(无验证码),插件内现场真登录,不使用底座共享登录态
|
||||
uses_month = False
|
||||
# 富字段声明(与 plugin.json 保持一致):ui=true 时壳子隐藏通用表单、展示打开插件窗口入口;
|
||||
# 此处仅作为无 manifest 时的兜底与参数契约文档
|
||||
fields = [
|
||||
{"key": "mode", "label": "执行模式", "type": "select",
|
||||
"options": [MODE_BOTH, MODE_31, MODE_32], "default": MODE_BOTH},
|
||||
{"key": "erp_system", "label": "ERP系统", "type": "select",
|
||||
"options": ["新版", "旧版"], "default": "新版"},
|
||||
{"key": "erp_username", "label": "ERP登录账号", "type": "text", "default": ""},
|
||||
{"key": "erp_password", "label": "ERP登录密码", "type": "password", "default": ""},
|
||||
{"key": "org_name", "label": "查询组织", "type": "text",
|
||||
"default": config.ORG_NAME},
|
||||
{"key": "stock_codes", "label": "仓库编码(多选,或关系)", "type": "multiselect",
|
||||
"options": config.STOCK_CODES_DEFAULT + config.STOCK_CODES_DEFAULT_OLD,
|
||||
"default": list(config.STOCK_CODES_DEFAULT)},
|
||||
{"key": "date_options", "label": "日期选项(多选,逐个导出)", "type": "multiselect",
|
||||
"options": config.DATE_OPTIONS_DEFAULT, "default": list(config.DATE_OPTIONS_DEFAULT)},
|
||||
{"key": "scheme_name", "label": "采购订单快捷方案", "type": "text",
|
||||
"default": config.SCHEME_NAME},
|
||||
{"key": "save_dir", "label": "保存目录(空=桌面/采购计划报表_日期)", "type": "text", "default": ""},
|
||||
]
|
||||
|
||||
def run(self, fields: dict, ctx) -> dict:
|
||||
fields = fields or {}
|
||||
# 注入日志钩子(插件内全部模块经 config.log 输出)
|
||||
config.set_log(ctx.log)
|
||||
|
||||
# ---------- 解析与校验 ----------
|
||||
mode = str(fields.get("mode") or MODE_BOTH).strip()
|
||||
erp = 'old' if str(fields.get("erp_system") or "新版").strip() == "旧版" else 'new'
|
||||
username = str(fields.get("erp_username") or "").strip()
|
||||
password = str(fields.get("erp_password") or "")
|
||||
org = str(fields.get("org_name") or "").strip() or (
|
||||
config.ORG_NAME_OLD if erp == 'old' else config.ORG_NAME)
|
||||
scheme = str(fields.get("scheme_name") or "").strip() or config.SCHEME_NAME
|
||||
codes = _as_str_list(fields.get("stock_codes")) # 空 = 全部仓库不筛选
|
||||
dates = _as_str_list(fields.get("date_options")) or list(config.DATE_OPTIONS_DEFAULT)
|
||||
if not username or not password:
|
||||
raise RuntimeError("ERP 登录账号/密码缺失:请在插件界面填写并保存配置后重试")
|
||||
if mode not in (MODE_BOTH, MODE_31, MODE_32):
|
||||
raise RuntimeError(f"未知执行模式:{mode}")
|
||||
if mode in (MODE_BOTH, MODE_31) and not dates:
|
||||
raise RuntimeError("物料收发汇总表需要日期选项(请在插件界面配置);仓库编码可留空=下载全部仓库")
|
||||
|
||||
save_dir_raw = str(fields.get("save_dir") or "").strip().strip('"')
|
||||
save_dir = Path(save_dir_raw) if save_dir_raw else Path(
|
||||
_desktop()) / f"{config.FOLDER_NAME}_{datetime.now():%Y-%m-%d}"
|
||||
save_dir.mkdir(parents=True, exist_ok=True)
|
||||
ctx.log(f"保存目录: {save_dir}")
|
||||
|
||||
# ---------- 登录(一次,两种报表共用会话) ----------
|
||||
ctx.progress(3)
|
||||
ctx.log(f"ERP 系统:{'新版' if erp == 'new' else '旧版'}({erp_login.ERP_URLS[erp]}),查询组织:{org}")
|
||||
ok, page = erp_login.erp_login(erp, username, password)
|
||||
if not ok:
|
||||
raise RuntimeError("ERP 登录失败(账号密码错误或网络异常),详见日志")
|
||||
ctx.progress(8)
|
||||
|
||||
# ---------- 执行计划与整体进度(进度 = 8 + 88*已完成单元/总单元) ----------
|
||||
do_31 = mode in (MODE_BOTH, MODE_31)
|
||||
do_32 = mode in (MODE_BOTH, MODE_32)
|
||||
units_31 = len(dates) if do_31 else 0
|
||||
total = units_31 + (1 if do_32 else 0)
|
||||
|
||||
def _report(done_abs):
|
||||
ctx.progress(8 + int(88 * done_abs / max(1, total)))
|
||||
|
||||
saved, failed = [], []
|
||||
try:
|
||||
try:
|
||||
page.set.window.max()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
from . import material_summary, purchase_order
|
||||
|
||||
if do_31:
|
||||
try:
|
||||
ctx.log(f"开始导出物料收发汇总表:下载全部仓库,按所选 {len(codes)} 个仓库中文名筛选" if codes else "开始导出物料收发汇总表:下载全部仓库(未筛选)")
|
||||
files31, failed31 = material_summary.run(
|
||||
page, save_dir, org, codes, dates,
|
||||
progress=lambda done_i, _total: _report(done_i),
|
||||
set_org=True) # 新旧系统均显式设置查询组织(旧系统登录默认组织已不再默认)
|
||||
saved += files31
|
||||
failed += [f"物料收发汇总表[{x}]" for x in failed31]
|
||||
except RuntimeError as e:
|
||||
failed.append(f"物料收发汇总表[{e}]")
|
||||
files31 = []
|
||||
# 各档报表导出后合并为汇总文件(合并失败不阻断整体结果)
|
||||
if files31:
|
||||
try:
|
||||
merged = material_summary.merge_summary(save_dir)
|
||||
if merged:
|
||||
saved.append(str(merged))
|
||||
except Exception as e:
|
||||
ctx.log(f"汇总文件生成失败: {e}")
|
||||
if do_32:
|
||||
try:
|
||||
ctx.log(f"开始导出采购订单列表(方案:{scheme})")
|
||||
f32 = purchase_order.run(page, save_dir, scheme, erp=erp,
|
||||
progress=lambda _i, _t: _report(units_31 + 1))
|
||||
if f32:
|
||||
saved.append(f32)
|
||||
else:
|
||||
failed.append("采购订单列表")
|
||||
except RuntimeError as e:
|
||||
failed.append(f"采购订单列表[{e}]")
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
ctx.progress(100)
|
||||
|
||||
# ---------- 汇总 ----------
|
||||
notes = [f"已保存 {len(saved)} 个文件:"] + [f" {p}" for p in saved]
|
||||
if failed:
|
||||
notes.append(f"失败 {len(failed)} 项:{'、'.join(failed)}")
|
||||
summary = f"导出完成(部分失败):成功 {len(saved)} 个,失败 {len(failed)} 项"
|
||||
else:
|
||||
summary = f"导出完成:共 {len(saved)} 个文件 → {save_dir}"
|
||||
return {"summary": summary, "rows": [], "notes": notes}
|
||||
|
||||
|
||||
# ================== 小工具 ==================
|
||||
def _desktop():
|
||||
from .k3_common import get_desktop
|
||||
return get_desktop()
|
||||
|
||||
|
||||
PLUGINS.append(ErpReportExportPlugin())
|
||||
@@ -0,0 +1,56 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""ERP报表导出(xq0031_xq0032)插件配置:默认值与运行参数。
|
||||
|
||||
合并 XQ0031(物料收发汇总表)+ XQ0032(采购订单列表)的固化配置,
|
||||
与 workflows 影刀版各源文件常量保持同源(四方向零依赖,各自演进)。
|
||||
|
||||
个性化配置(账号密码/仓库编码/日期选项等)由插件自带 Vue 界面维护,经
|
||||
webhost /api/plugin-config 落执行机本机,run() 时经 fields 注入;
|
||||
本文件只承载 fields 未传时的兜底默认与运行参数。
|
||||
"""
|
||||
|
||||
# ==================== 1. 业务默认值(fields 未传/留空时的兜底) ====================
|
||||
ORG_NAME = '99.01 重庆金七象供应链管理有限公司' # 查询组织(新版默认)
|
||||
ORG_NAME_OLD = '99.01.07.01.01 石桥铺会馆' # 查询组织(旧版默认;登录已不再默认,须显式选择)
|
||||
# 仓库编码→仓库中文名(现场映射,供「下载全部仓库后按中文名筛选」使用):
|
||||
# 0101010101 重庆运营总仓 / 0101010201 重庆美得三方仓 / 0101020201 成都美得三方仓
|
||||
# 0101030201 长沙乐行三方仓 / 0101040201 西安美得三方仓 / 03010127 代管仓(旧版登录默认)
|
||||
# 前端仍要求选择仓库编码(决定最终保留哪些仓库),查询统一下载全部仓库,
|
||||
# 下载后用 openpyxl 按本映射把仓库中文名列筛到所选编码对应仓库,覆盖保存。
|
||||
STOCK_NAME_MAP = {
|
||||
'0101010101': '重庆运营总仓',
|
||||
'0101010201': '重庆美得三方仓',
|
||||
'0101020201': '成都美得三方仓',
|
||||
'0101030201': '长沙乐行三方仓',
|
||||
'0101040201': '西安美得三方仓',
|
||||
'03010127': '代管仓',
|
||||
}
|
||||
|
||||
# 前端可选仓库编码列表(与 STOCK_NAME_MAP 键一致;留空 = 全部仓库不筛选)
|
||||
STOCK_CODES_DEFAULT = ['0101010101', '0101010201', '0101020201', '0101030201', '0101040201']
|
||||
STOCK_CODES_DEFAULT_OLD = ['03010127'] # 旧版默认仓库(代管仓,随 ERP 系统选项切换)
|
||||
DATE_OPTIONS_DEFAULT = ['60D', '30D', '15D', '7D', '3D']
|
||||
SCHEME_NAME = '默认方案(个人)' # 需求32 快捷方案(精确匹配)
|
||||
FOLDER_NAME = '采购计划报表' # 保存目录命名前缀(31/32 同目录)
|
||||
FILE_PREFIX_31 = '物料收发汇总表' # 31 导出文件名前缀
|
||||
FILE_PREFIX_32 = '采购订单列表' # 32 导出文件名前缀
|
||||
|
||||
# ==================== 2. 运行参数(项目规范:全局重试 3 次) ====================
|
||||
RETRY_MAX = 3
|
||||
TIMEOUT = 15 # 元素查找超时(秒)
|
||||
|
||||
# ==================== 3. 日志钩子(print → ctx.log) ====================
|
||||
_log_fn = print
|
||||
|
||||
|
||||
def set_log(fn) -> None:
|
||||
"""插件 run() 启动时把 ctx.log 注入进来,全部模块经 log() 输出。"""
|
||||
global _log_fn
|
||||
_log_fn = fn if fn else print
|
||||
|
||||
|
||||
def log(msg: str) -> None:
|
||||
try:
|
||||
_log_fn(msg)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,181 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""金蝶 K3Cloud(HTML5)ERP 登录模块(xq0031_xq0032 插件内自包含)。
|
||||
|
||||
自 workflows/share/erp_login.py 迁移,插件化改造点:
|
||||
- 账号密码由插件界面配置经 fields 注入(不再读 .env),个性化归属明确;
|
||||
- 使用固定默认用户目录(不再每次独立临时目录),保留登录态与浏览器配置;
|
||||
用完由调用方 page.quit() 关闭;
|
||||
- print → config.log。
|
||||
|
||||
登录页元素(新旧版一致):
|
||||
用户名输入框 <input id="user" placeholder="用户名">
|
||||
密码输入框 <input id="password" type="password">
|
||||
登录按钮 <button id="btnLogin" class="btnlogin k-button">登录</button>
|
||||
登录成功判定:URL 包含 /k3cloud/html5/dform.aspx,或站点页面无登录输入框(已登录态)。
|
||||
特殊弹窗:登录时若弹出「该帐号已登录在线,确认让对方下线」警告框,自动点确认。
|
||||
"""
|
||||
import time
|
||||
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
from . import config
|
||||
|
||||
# ================== 站点定义(新旧 ERP) ==================
|
||||
ERP_URLS = {
|
||||
'old': 'https://erp.37du.co/k3cloud/html5/index.aspx',
|
||||
'new': 'https://criterion.erp.37du.co/k3cloud/html5/index.aspx',
|
||||
}
|
||||
|
||||
# 登录页元素定位(新旧版元素 id 一致)
|
||||
USER_INPUT = '#user'
|
||||
PWD_INPUT = '#password'
|
||||
LOGIN_BTN = '#btnLogin'
|
||||
# 「该帐号已登录在线」弹窗的确认按钮(蓝色样式 class 固定,id 为动态 UUID)
|
||||
KICK_CONFIRM_BTN = 'css:.k-window .BlueButtonStyle'
|
||||
|
||||
# 登录成功标志:URL 包含该关键字即视为已登录(跳转到默认表单页)
|
||||
SUCCESS_KEYWORD = '/k3cloud/html5/dform.aspx'
|
||||
|
||||
# ================== 运行参数 ==================
|
||||
RETRY_MAX = config.RETRY_MAX # 全局重试次数(项目规范:最多 3 次)
|
||||
TIMEOUT = 10 # 元素等待超时(秒)
|
||||
LOGIN_WAIT = 3 # 点击登录后等待(秒)
|
||||
HEADLESS = False
|
||||
|
||||
|
||||
def _resolve_url(erp):
|
||||
"""把 'old'/'new'/完整URL 统一解析为登录页 URL。"""
|
||||
if erp in ERP_URLS:
|
||||
return ERP_URLS[erp]
|
||||
if erp and erp.lower().startswith('http'):
|
||||
return erp
|
||||
raise ValueError(f"无效的 ERP 标识:{erp},可选 'old'、'new' 或完整登录页 URL")
|
||||
|
||||
|
||||
def _is_login_page(url):
|
||||
"""判断当前 URL 是否仍停留在登录页。"""
|
||||
return 'index.aspx' in (url or '').lower()
|
||||
|
||||
|
||||
def _is_login_success(url):
|
||||
"""登录成功判定:URL 包含 dform.aspx 即视为已登录。"""
|
||||
return SUCCESS_KEYWORD in (url or '')
|
||||
|
||||
|
||||
def _handle_kick_dialog(page):
|
||||
"""处理「该帐号已登录在线,确认让对方下线」弹窗:存在则点击蓝色确认按钮。"""
|
||||
for _ in range(3):
|
||||
btn = page.ele(KICK_CONFIRM_BTN, timeout=2)
|
||||
if not btn:
|
||||
return False
|
||||
try:
|
||||
btn.click()
|
||||
config.log("[ERP登录] 检测到「已登录在线」弹窗,点击确认(让对方下线)")
|
||||
return True
|
||||
except Exception as e:
|
||||
config.log(f"[ERP登录] 点击弹窗确认异常:{e}")
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
def _open_browser(headless):
|
||||
"""启动浏览器(DrissionPage 固定默认用户目录,不再每次独立临时目录,保留登录态/配置)。
|
||||
附加禁用浏览器自身弹窗的 prefs/启动参数:保存密码、权限请求(通知/定位/音视频)、
|
||||
自动化测试 infobar、首次运行向导、打开外部应用确认框(K3 点引出/下载会请求打开
|
||||
Excel 等,防止弹「访问应用和服务」)等。"""
|
||||
co = ChromiumOptions()
|
||||
if headless:
|
||||
co.headless()
|
||||
co.set_argument('--start-maximized')
|
||||
# —— 禁用浏览器自身弹窗(避免干扰自动化)——
|
||||
co.set_pref('credentials_enable_service', False) # 不保存密码
|
||||
co.set_pref('profile.password_manager_enabled', False) # 关闭密码管理器
|
||||
return ChromiumPage(co)
|
||||
|
||||
|
||||
def erp_login(erp='new', username='', password='', headless=None):
|
||||
"""
|
||||
登录金蝶 K3Cloud ERP(新旧系统通用,现场真登录)。
|
||||
|
||||
参数:
|
||||
erp 'old' 旧版 erp.37du.co / 'new' 新版 criterion.erp.37du.co / 完整登录页 URL
|
||||
username 用户名(插件界面配置注入,必填)
|
||||
password 密码(插件界面配置注入,必填)
|
||||
|
||||
返回:
|
||||
(success, page) success=True 时 page 为已登录的 ChromiumPage;失败时 page 为 None。
|
||||
调用方使用完毕应 page.quit() 关闭浏览器(不保存任何目录/cookies)。
|
||||
"""
|
||||
login_url = _resolve_url(erp)
|
||||
username = (username or '').strip()
|
||||
password = password or ''
|
||||
if not (username and password):
|
||||
config.log("[ERP登录] 登录账号/密码缺失(请在插件界面填写并保存配置)")
|
||||
return False, None
|
||||
headless = HEADLESS if headless is None else bool(headless)
|
||||
|
||||
for attempt in range(1, RETRY_MAX + 1):
|
||||
page = None
|
||||
try:
|
||||
config.log(f"[ERP登录] 第 {attempt}/{RETRY_MAX} 次 → {login_url}")
|
||||
page = _open_browser(headless)
|
||||
config.log("[ERP登录] 浏览器已启动(默认用户目录,保留登录态)")
|
||||
|
||||
# 回到目标登录页;已登录站点会跳转/保留会话,未登录则停在登录页
|
||||
page.get(login_url)
|
||||
time.sleep(2)
|
||||
|
||||
# 3) 已登录判定:页面无登录输入框 → 会话有效,直接复用
|
||||
if page.ele(USER_INPUT, timeout=3) is None:
|
||||
config.log("[ERP登录] 检测到已登录会话,直接复用")
|
||||
return True, page
|
||||
|
||||
# 4) 未登录 → 填表登录
|
||||
user = page.ele(USER_INPUT, timeout=TIMEOUT)
|
||||
if not user:
|
||||
config.log("[ERP登录] 找不到用户名输入框")
|
||||
continue
|
||||
user.clear()
|
||||
user.input(username)
|
||||
time.sleep(0.5)
|
||||
# 用户名框是 autocomplete 控件,需按回车关闭弹出的下拉提示框
|
||||
page.actions.key_down('Enter')
|
||||
page.actions.key_up('Enter')
|
||||
time.sleep(0.3)
|
||||
|
||||
pwd = page.ele(PWD_INPUT, timeout=TIMEOUT)
|
||||
if not pwd:
|
||||
config.log("[ERP登录] 找不到密码输入框")
|
||||
continue
|
||||
pwd.clear()
|
||||
pwd.input(password)
|
||||
time.sleep(0.3)
|
||||
|
||||
btn = page.ele(LOGIN_BTN, timeout=TIMEOUT)
|
||||
if not btn:
|
||||
config.log("[ERP登录] 找不到登录按钮")
|
||||
continue
|
||||
btn.click()
|
||||
|
||||
# 登录后轮询:处理「已登录在线」弹窗 + 等待跳转到 dform.aspx
|
||||
for _ in range(6):
|
||||
time.sleep(LOGIN_WAIT)
|
||||
if _is_login_success(page.url):
|
||||
config.log(f"[ERP登录] 登录成功 → {page.url}")
|
||||
return True, page
|
||||
_handle_kick_dialog(page)
|
||||
|
||||
config.log("[ERP登录] 点击登录后未跳转到 dform.aspx(账号密码错误或网络异常)")
|
||||
except Exception as e:
|
||||
config.log(f"[ERP登录] 异常:{e}")
|
||||
|
||||
# 走到这里说明本轮失败,关闭浏览器后重试(成功时在上方已直接 return)
|
||||
if page is not None:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
|
||||
config.log("[ERP登录] 重试 3 次均失败")
|
||||
return False, None
|
||||
@@ -0,0 +1,299 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""K3Cloud HTML5 页面操作公共件(xq0031_xq0032 插件内共享)。
|
||||
|
||||
自 workflows/XQ0031、XQ0032 影刀版迁移的稳定交互原语,两报表共用。
|
||||
K3 现场验证结论(勿随手"优化",均为踩坑后的修复):
|
||||
- 残留窗口会被移到屏幕外,is_displayed 仍 True 但点击无效 → 必须同时校验视口位置
|
||||
- 工具栏/菜单项物理点击只选中文字不触发菜单 → 用 by_js;嵌套悬浮子菜单相反,
|
||||
必须真实鼠标悬浮(move_to 链不能断)
|
||||
- 浏览器断连(PageDisconnectedError)属致命异常,直接上抛,避免被容错吞掉空转
|
||||
"""
|
||||
import shutil
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
from DrissionPage.errors import PageDisconnectedError
|
||||
except Exception:
|
||||
PageDisconnectedError = None
|
||||
|
||||
from . import config
|
||||
|
||||
|
||||
def get_desktop():
|
||||
"""获取真实桌面路径,适配 OneDrive 等重定向的不同电脑。"""
|
||||
try:
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
guid = wintypes.GUID(
|
||||
data1=0xB4BFCC3A, data2=0xDB2C, data3=0x424C,
|
||||
data4=(0xB0, 0x29, 0x7F, 0xE9, 0x9A, 0x87, 0xC6, 0x41))
|
||||
func = ctypes.windll.shell32.SHGetKnownFolderPath
|
||||
func.argtypes = [wintypes.GUID, wintypes.DWORD, wintypes.HANDLE,
|
||||
ctypes.POINTER(ctypes.c_wchar_p)]
|
||||
ptr = ctypes.c_wchar_p()
|
||||
func(ctypes.byref(guid), 0, None, ctypes.byref(ptr))
|
||||
return ptr.value
|
||||
except Exception:
|
||||
return str(Path.home() / 'Desktop')
|
||||
|
||||
|
||||
def is_in_viewport(el, page):
|
||||
"""元素是否真实显示在视口内。K3 残留窗口会被移到屏幕外,此时 is_displayed
|
||||
仍为 True,但其内元素点击无效——必须同时校验位置在视口内。"""
|
||||
try:
|
||||
if not el.states.is_displayed:
|
||||
return False
|
||||
w, h = el.rect.size
|
||||
if w <= 0 or h <= 0:
|
||||
return False
|
||||
x, y = el.rect.location
|
||||
vw, vh = page.run_js(
|
||||
'return [window.innerWidth || document.documentElement.clientWidth,'
|
||||
' window.innerHeight || document.documentElement.clientHeight];')
|
||||
return 0 <= x < vw and 0 <= y < vh
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def click_visible(page, css, timeout=None, by_js=False):
|
||||
"""点击第一个在视口内可见的匹配元素,成功返回 True。浏览器断连等致命异常直接上抛。
|
||||
by_js=True 用于 K3 工具栏/菜单项:物理点击只会选中文字,不触发菜单。"""
|
||||
timeout = config.TIMEOUT if timeout is None else timeout
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
try:
|
||||
for el in page.eles(css):
|
||||
if is_in_viewport(el, page):
|
||||
el.click(by_js=True) if by_js else el.click()
|
||||
return True
|
||||
except Exception as e:
|
||||
if PageDisconnectedError is not None and isinstance(e, PageDisconnectedError):
|
||||
raise
|
||||
time.sleep(0.5)
|
||||
return False
|
||||
|
||||
|
||||
def ele_visible(page, css, timeout=1):
|
||||
"""元素存在、且在视口内可见才算命中(K3 过滤窗口关闭后 DOM 里仍残留隐藏/屏幕外节点)。"""
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
try:
|
||||
for el in page.eles(css):
|
||||
if is_in_viewport(el, page):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.3)
|
||||
return False
|
||||
|
||||
|
||||
def press_enter(page):
|
||||
"""模拟按一次回车键。"""
|
||||
page.actions.key_down('Enter')
|
||||
page.actions.key_up('Enter')
|
||||
|
||||
|
||||
def press_enter_in(el, page):
|
||||
"""向指定元素直接发送回车(元素级,避免页面焦点漂移导致回车无效)。"""
|
||||
try:
|
||||
from DrissionPage.common import Keys
|
||||
el.input(Keys.ENTER)
|
||||
except Exception:
|
||||
press_enter(page)
|
||||
|
||||
|
||||
def visible_titles(page):
|
||||
"""返回所有可见窗口标题文本列表。"""
|
||||
titles = []
|
||||
try:
|
||||
for t in page.eles('css:.k-window-title'):
|
||||
try:
|
||||
if t.states.is_displayed:
|
||||
titles.append(t.text)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
return titles
|
||||
|
||||
|
||||
def close_window_by_title(page, title, timeout=3, tag=''):
|
||||
"""物理点击关闭标题包含关键字的 k-window 弹窗(K3 下载窗口等残留,关闭按钮 by_js 不触发)。
|
||||
用包含匹配:实际标题可能是「文件下载」或「文档下载」,避免因标题差异关不掉。"""
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
for w in page.eles('css:.k-window'):
|
||||
try:
|
||||
if not w.states.is_displayed:
|
||||
continue
|
||||
t = w.ele('css:.k-window-title', timeout=0.3)
|
||||
if t is None or title not in (t.text or ''):
|
||||
continue
|
||||
btn = w.ele('css:.k-window-actions .k-i-close', timeout=0.5)
|
||||
if btn is None:
|
||||
return False
|
||||
try:
|
||||
btn.click()
|
||||
except Exception:
|
||||
btn.click(by_js=True)
|
||||
time.sleep(0.3)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
return False
|
||||
|
||||
|
||||
def reset_filter_state(page, tag='', wait_query=False):
|
||||
"""重试前清理脏界面状态:按 ESC 关闭残留的弹层/过滤窗口,兜底点各面板「取消」按钮。
|
||||
wait_query=True(需求31):若查询正在进行先等其结束(ESC 会打断正常查询)。"""
|
||||
if wait_query:
|
||||
end = time.time() + 120
|
||||
while time.time() < end:
|
||||
if not any('查询进度' in x for x in visible_titles(page)):
|
||||
break
|
||||
time.sleep(1)
|
||||
for _ in range(2):
|
||||
try:
|
||||
page.actions.key_down('ESC')
|
||||
page.actions.key_up('ESC')
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
click_visible(page, 'css:[id*="FBTNCANCEL_c"]', timeout=1)
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def download_file(page, save_dir, new_name, tag=''):
|
||||
"""点「下载」按钮 → 等文件落盘到保存目录。
|
||||
做法:把浏览器默认下载目录直接指到 save_dir,再点「下载」按钮(target=_blank 也会下载到该目录),
|
||||
然后盯着文件夹等新文件出现且大小稳定(下载完成),不依赖 DrissionPage 的任务捕获,避免静默卡住。"""
|
||||
save_dir = Path(save_dir)
|
||||
try:
|
||||
save_dir.mkdir(parents=True, exist_ok=True)
|
||||
page.set.download_path(str(save_dir))
|
||||
page.set.when_download_file_exists('overwrite')
|
||||
except Exception as e:
|
||||
config.log(f'{tag} 设置下载目录异常: {e}')
|
||||
before_names = {b.name for b in save_dir.glob('*')} if save_dir.exists() else set()
|
||||
|
||||
# 清除上个报表/上次导出残留的「文件下载/文档下载」窗口,防止全页匹配误命中旧下载按钮
|
||||
# (需求31多档连导或需求31→32连导时残留)。此刻本次引出刚触发、尚在生成阶段,
|
||||
# 其下载窗口还未弹出,关闭残留窗口不影响本次导出。
|
||||
for _title in ('文件下载', '文档下载'):
|
||||
try:
|
||||
close_window_by_title(page, _title, timeout=1, tag=tag)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 找可见的「下载」按钮,以「引出进度」窗口为信号判定引出是否仍在进行:
|
||||
# - 点击引出后,K3 会先弹「引出进度」窗口(进度条 + 「正在获取引出数据:(n/N)」caption),
|
||||
# 取数完成后该窗口关闭并弹出「文件下载」窗口;正常 ≤30s,大数据量(百万行)约 1 分钟多;
|
||||
# - 「引出进度」窗口始终未出现 → 引出未被受理/已失败,快速返回失败,不做无谓死等;
|
||||
# - 进度窗口已消失但 GONE_GAP 内下载按钮未出现 → 引出失败,快速返回交外层重试。
|
||||
dl = None
|
||||
start = time.time()
|
||||
seen_busy = False # 是否见过「引出进度」窗口
|
||||
busy_gone_since = None # 进度窗口消失的时刻(None=尚未消失)
|
||||
WAIT_BUSY = 20 # 等「引出进度」窗口出现的最长时间
|
||||
GONE_GAP = 10 # 进度窗口消失后等下载按钮的窗口期
|
||||
OVERALL = 150 # 整体硬上限(含百万行大数据的取数时间)
|
||||
last_report = start
|
||||
|
||||
def _busy(titles):
|
||||
return any(k in t for t in titles for k in ('生成', '进度', '稍候', '处理中', '导出'))
|
||||
|
||||
def _progress_text():
|
||||
"""读「引出进度」窗口 caption(如「正在获取引出数据:(100001/1242812)」)。"""
|
||||
try:
|
||||
cap = page.ele('css:[id*="FPROGRESSBAR"] div[id*="lblCaption"]', timeout=0.3)
|
||||
return (cap.attr('title') or cap.text or '').strip() if cap else ''
|
||||
except Exception:
|
||||
return ''
|
||||
|
||||
while time.time() - start < OVERALL:
|
||||
for el in page.eles('css:[id*="FDOWNLOAD_c"]'):
|
||||
try:
|
||||
if el.states.is_displayed:
|
||||
dl = el
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
if dl:
|
||||
break
|
||||
busy = _busy(visible_titles(page))
|
||||
if busy:
|
||||
seen_busy = True
|
||||
busy_gone_since = None
|
||||
elif seen_busy:
|
||||
if busy_gone_since is None:
|
||||
busy_gone_since = time.time()
|
||||
elif time.time() - busy_gone_since > GONE_GAP:
|
||||
config.log(f'{tag} 引出进度窗口已消失且下载按钮未出现,判定本次引出失败')
|
||||
return False
|
||||
elif time.time() - start > WAIT_BUSY:
|
||||
config.log(f'{tag} 未检测到「引出进度」窗口,判定本次引出未触发/失败')
|
||||
return False
|
||||
now = time.time()
|
||||
if now - last_report >= 30:
|
||||
last_report = now
|
||||
txt = _progress_text()
|
||||
config.log(f'{tag} 仍在等待(引出进度窗口'
|
||||
f'{txt or "可见"},已等 {int(now - start)}s)')
|
||||
time.sleep(0.5)
|
||||
if not dl:
|
||||
config.log(f'{tag} 找不到下载按钮(等待 {OVERALL}s 后 K3 仍未生成完成)')
|
||||
return False
|
||||
config.log(f'{tag} 点击下载按钮...')
|
||||
try:
|
||||
dl.click()
|
||||
except Exception:
|
||||
dl.click(by_js=True)
|
||||
|
||||
# 等新文件出现且大小连续两次不变(下载完成)
|
||||
config.log(f'{tag} 等待文件下载完成...')
|
||||
last_size, last_name = -1, None
|
||||
end = time.time() + 300
|
||||
while time.time() < end:
|
||||
new_files = [f for f in save_dir.glob('*')
|
||||
if f.is_file() and f.name not in before_names]
|
||||
if new_files:
|
||||
f = max(new_files, key=lambda x: x.stat().st_mtime)
|
||||
try:
|
||||
s = f.stat().st_size
|
||||
except Exception:
|
||||
s = 0
|
||||
if (f.suffix not in ('.crdownload', '.tmp', '.part')
|
||||
and s > 0 and s == last_size and f.name == last_name):
|
||||
dst = _save_as(f, save_dir / new_name)
|
||||
config.log(f'{tag} 已保存: {dst}')
|
||||
close_window_by_title(page, '文件下载', tag=tag) # 只关下载窗口,其余残留不主动关
|
||||
return True
|
||||
last_size, last_name = s, f.name
|
||||
time.sleep(1)
|
||||
|
||||
# 兜底:超时但确有新文件也尝试落名
|
||||
new_files = [f for f in save_dir.glob('*')
|
||||
if f.is_file() and f.name not in before_names
|
||||
and f.suffix not in ('.crdownload', '.tmp', '.part')]
|
||||
for f in new_files:
|
||||
dst = _save_as(f, save_dir / new_name)
|
||||
config.log(f'{tag} 已保存: {dst}')
|
||||
close_window_by_title(page, '文件下载', tag=tag)
|
||||
return True
|
||||
config.log(f'{tag} 下载失败/超时')
|
||||
return False
|
||||
|
||||
|
||||
def _save_as(src, dst):
|
||||
"""把下载产物重命名/移动到目标名;移动失败则原样保留并返回实际路径。"""
|
||||
if src == dst:
|
||||
return src
|
||||
try:
|
||||
if dst.exists():
|
||||
dst.unlink()
|
||||
shutil.move(str(src), str(dst))
|
||||
return dst
|
||||
except Exception:
|
||||
return src
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,87 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0031_xq0032",
|
||||
"name": "ERP物料收发汇总-采购订单报表导出",
|
||||
"version": "1.0.10",
|
||||
"description": "金蝶K3Cloud报表自动导出:物料收发汇总表+ 采购订单列表,支持新旧系统、下载全部仓库后按所选仓库中文名自动筛选、日期多选(含自定义区间),个性化配置保存在本机",
|
||||
"category": "报表",
|
||||
"icon": "",
|
||||
"platform": "",
|
||||
"uses_month": false,
|
||||
"ui": true,
|
||||
"capabilities": ["xq0031_xq0032"],
|
||||
"permissions": {
|
||||
"platforms": []
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"mode": {
|
||||
"type": "string",
|
||||
"title": "执行模式",
|
||||
"default": "两个都导",
|
||||
"enum": ["两个都导", "物料收发汇总表", "采购订单列表"],
|
||||
"description": "需求31=物料收发汇总表(按仓库/日期多档导出),需求32=采购订单列表(按方案导出)"
|
||||
},
|
||||
"erp_system": {
|
||||
"type": "string",
|
||||
"title": "ERP系统",
|
||||
"default": "新版",
|
||||
"enum": ["新版", "旧版"],
|
||||
"description": "新版 criterion.erp.37du.co / 旧版 erp.37du.co"
|
||||
},
|
||||
"erp_username": {
|
||||
"type": "string",
|
||||
"title": "ERP登录账号",
|
||||
"default": "",
|
||||
"description": "用户自己的ERP账号,保存在本机下次免填"
|
||||
},
|
||||
"erp_password": {
|
||||
"type": "string",
|
||||
"title": "ERP登录密码",
|
||||
"default": "",
|
||||
"format": "password",
|
||||
"description": "仅保存在本机(%LOCALAPPDATA%\\37duAutomation\\plugin_configs),下次免填"
|
||||
},
|
||||
"org_name": {
|
||||
"type": "string",
|
||||
"title": "查询组织",
|
||||
"default": "99.01 重庆金七象供应链管理有限公司",
|
||||
"description": "新版默认=金七象;旧版默认=99.01.07.01.01 石桥铺会馆,插件界面切换ERP系统自动带出"
|
||||
},
|
||||
"stock_codes": {
|
||||
"type": "array",
|
||||
"title": "仓库编码(可多选)",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"enum": ["0101010101", "0101010201", "0101020201", "0101030201", "0101040201", "03010127"]
|
||||
},
|
||||
"default": ["0101010101", "0101010201", "0101020201", "0101030201", "0101040201"],
|
||||
"description": "查询统一下载全部仓库,下载后按所选编码对应的中文仓库名自动筛选保存;留空=全部仓库不筛选。新版默认=五个三方仓;旧版默认=03010127(代管仓,切换ERP系统自动带出)"
|
||||
},
|
||||
"date_options": {
|
||||
"type": "array",
|
||||
"title": "日期选项(多选,逐个导出)",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"enum": ["60D", "30D", "15D", "7D", "3D"]
|
||||
},
|
||||
"default": ["60D", "30D", "15D", "7D", "3D"],
|
||||
"description": "N天=今天往前推N天;可混入自定义区间如 2026-01-01~2026-09-15"
|
||||
},
|
||||
"scheme_name": {
|
||||
"type": "string",
|
||||
"title": "采购订单快捷方案",
|
||||
"default": "默认方案(个人)",
|
||||
"description": "需求32使用的过滤方案名(精确匹配)"
|
||||
},
|
||||
"save_dir": {
|
||||
"type": "string",
|
||||
"title": "保存目录",
|
||||
"default": "",
|
||||
"description": "留空=桌面/采购计划报表_日期"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,510 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""需求32 - 金蝶 K3Cloud ERP「采购订单列表」自动导出(xq0031_xq0032 插件内模块)。
|
||||
|
||||
自 workflows/XQ0032 purchase_order_list_export.py 迁移:
|
||||
全局搜索「采购订单列表」→ 选中编号 CGDDLB 项 → 点快捷方案 → 等查询完成 →
|
||||
选项 → 引出 → 按列表引出数据 → 下载保存(与需求31同目录)。
|
||||
快捷方案名由插件界面配置注入;交互逻辑与影刀版保持同源。
|
||||
"""
|
||||
import re
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
from . import config
|
||||
from . import k3_common as kc
|
||||
|
||||
TAG = '[采购订单列表]'
|
||||
REPORT_KEYWORD = '采购订单列表' # 全局搜索关键字
|
||||
REPORT_NUMBER = 'CGDDLB' # 搜索结果编号(列表项唯一标识)
|
||||
|
||||
|
||||
# ================== 列表操作 ==================
|
||||
def _diag_search(page):
|
||||
"""探针:搜索失败时打印当前页面/下拉状态,定位是下拉没出来还是选择器不匹配。"""
|
||||
try:
|
||||
config.log(f'{TAG} [探针] 当前 URL: {(page.url or "")[:120]}')
|
||||
except Exception as e:
|
||||
config.log(f'{TAG} [探针] 读 URL 异常: {e}')
|
||||
try:
|
||||
items = page.eles('css:.kd-fullsearch-selectable li.kd-fullsearch-item-container',
|
||||
timeout=2)
|
||||
config.log(f'{TAG} [探针] 下拉结果项数量: {len(items)}')
|
||||
for i, li in enumerate(items[:10]):
|
||||
try:
|
||||
num = li.ele('css:span[searchitem="number"]', timeout=0.3)
|
||||
txt = li.ele('css:span[searchitem="text"]', timeout=0.3)
|
||||
config.log(f'{TAG} [探针] 第{i + 1}项: '
|
||||
f'number={num.text if num else "?"} '
|
||||
f'text={txt.text if txt else "?"} '
|
||||
f'displayed={li.states.is_displayed}')
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
config.log(f'{TAG} [探针] 枚举下拉异常: {e}')
|
||||
filter_visible = kc.ele_visible(
|
||||
page, 'css:[id*="BILLMENU_TOOLBAR-tbFilter"]', timeout=1)
|
||||
config.log(f'{TAG} [探针] 过滤按钮可见: {filter_visible}')
|
||||
|
||||
|
||||
def _back_home(page, erp='new'):
|
||||
"""回 K3 主控台首页:优先点顶部常驻「主页」按钮(SPA 内部跳转,一次清掉全部标签页/浮动窗口)。
|
||||
注意:禁止用 page.get(index.aspx) 整页回首页——K3 整页重新加载会重新走会话校验,
|
||||
连导时需求31的 tab 还开着,实测会被判为重复登录直接跳登录页(全局搜索图标随之消失、
|
||||
卡在「找不到全局搜索图标」)。主页按钮找不到时,退化为逐个关闭非激活标签页。"""
|
||||
if _click_home_btn(page):
|
||||
config.log(f'{TAG} 已点主页按钮回主控台')
|
||||
time.sleep(2.5)
|
||||
return
|
||||
config.log(f'{TAG} 未找到主页按钮,改为逐个关闭非激活标签页')
|
||||
for _ in range(5): # 关闭一个后 DOM 会刷新,多次扫描确保关干净
|
||||
closed = 0
|
||||
for li in page.eles('css:ul.k-tabstrip-items li', timeout=2):
|
||||
try:
|
||||
if not li.states.is_displayed:
|
||||
continue
|
||||
if (li.attr('aria-selected') or '').strip().lower() == 'true':
|
||||
continue # 保留当前激活 tab
|
||||
btn = li.ele('css:.k-i-close', timeout=0.5)
|
||||
if btn is None:
|
||||
btn = li.ele('css:.k-tabstrip-close', timeout=0.5)
|
||||
if btn is None:
|
||||
continue
|
||||
try:
|
||||
btn.click()
|
||||
except Exception:
|
||||
btn.click(by_js=True)
|
||||
closed += 1
|
||||
time.sleep(0.6)
|
||||
except Exception:
|
||||
pass
|
||||
if closed == 0:
|
||||
break
|
||||
config.log(f'{TAG} 已关闭 {closed} 个残留标签页')
|
||||
|
||||
|
||||
def _click_home_btn(page):
|
||||
"""点击 K3 顶部常驻「主页」按钮(span.k-link.kd-item-home)回主控台首页。
|
||||
K3 控件 by_js click 有时不触发,先物理点击,失败再 by_js 兜底。"""
|
||||
if kc.click_visible(page, 'css:.k-link.kd-item-home', timeout=3):
|
||||
return True
|
||||
return kc.click_visible(page, 'css:.k-link.kd-item-home', timeout=3, by_js=True)
|
||||
|
||||
|
||||
def _active_tab_title(page):
|
||||
"""当前激活的主标签页标题。K3 多表单标签残留(物料收发汇总表/采购订单列表并存)时,
|
||||
必须确认操作的是激活的那个,否则会读到隐藏标签页的旧条数。"""
|
||||
try:
|
||||
t = page.ele('css:li[aria-selected="true"] .k-link', timeout=2)
|
||||
if t is not None:
|
||||
return (t.text or '').strip()
|
||||
except Exception:
|
||||
pass
|
||||
return ''
|
||||
|
||||
|
||||
def _open_report(page, erp='new'):
|
||||
"""点击全局搜索 → 输入「采购订单列表」→ 等联想下拉出现 → 点选编号 CGDDLB 项。
|
||||
打开后必须校验主标签页已切到「采购订单列表」,否则可能停留在上一个报表标签、
|
||||
读到错页面的行数;校验不过回主控台首页重新搜索进入(最多 2 轮)。"""
|
||||
for _ in range(2):
|
||||
if _do_search_open(page):
|
||||
if REPORT_KEYWORD in _active_tab_title(page):
|
||||
config.log(f'{TAG} 已打开列表({REPORT_NUMBER})')
|
||||
return True
|
||||
config.log(f'{TAG} 列表标签页未激活(可能残留其它表单标签),清理后重新搜索')
|
||||
_back_home(page, erp)
|
||||
time.sleep(1)
|
||||
config.log(f'{TAG} 打开「采购订单列表」失败:未能确认列表标签页激活')
|
||||
return False
|
||||
|
||||
|
||||
def _do_search_open(page):
|
||||
"""执行一次全局搜索并点选 CGDDLB 结果(不校验标签页是否真的激活,由 _open_report 负责)。"""
|
||||
if not kc.click_visible(page, 'css:.kd-fullsearch-searchicon', timeout=10):
|
||||
config.log(f'{TAG} 找不到全局搜索图标')
|
||||
return False
|
||||
time.sleep(1)
|
||||
sbox = page.ele('css:.kd-appplat-searchinput', timeout=5)
|
||||
if not sbox:
|
||||
config.log(f'{TAG} 找不到搜索输入框')
|
||||
return False
|
||||
sbox.clear()
|
||||
sbox.input(REPORT_KEYWORD)
|
||||
time.sleep(0.8) # 输入即出联想下拉;不按回车(回车=直接进第一个结果)
|
||||
|
||||
# 结果下拉列表中找编号为 CGDDLB 的「采购订单列表」项
|
||||
end = time.time() + 20
|
||||
while time.time() < end:
|
||||
for li in page.eles('css:.kd-fullsearch-selectable li.kd-fullsearch-item-container',
|
||||
timeout=2):
|
||||
try:
|
||||
if not li.states.is_displayed:
|
||||
continue
|
||||
num = li.ele('css:span[searchitem="number"]', timeout=0.5)
|
||||
if num is None:
|
||||
continue
|
||||
num_text = (num.attr('title') or num.text or '').strip().upper()
|
||||
if num_text == REPORT_NUMBER.upper():
|
||||
li.click()
|
||||
time.sleep(2)
|
||||
if kc.ele_visible(page, 'css:[id*="BILLMENU_TOOLBAR-tbFilter"]', timeout=2):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
config.log(f'{TAG} 未找到编号 {REPORT_NUMBER} 的搜索结果项')
|
||||
_diag_search(page) # 探针:输出诊断信息
|
||||
return False
|
||||
|
||||
|
||||
def _open_filter(page):
|
||||
"""确保过滤窗口打开:已开则复用,未开则点「过滤」按钮(by_js 触发菜单项)。"""
|
||||
if kc.ele_visible(page, 'css:.k-window [id*="_Filter-FSCHEMELIST"]', timeout=2):
|
||||
return True
|
||||
if kc.click_visible(page, 'css:[id*="BILLMENU_TOOLBAR-tbFilter"]', by_js=True):
|
||||
time.sleep(1.5)
|
||||
return kc.ele_visible(page, 'css:[id*="_Filter-FSCHEMELIST"]', timeout=5)
|
||||
return False
|
||||
|
||||
|
||||
def _select_scheme(page, scheme):
|
||||
"""在过滤窗口方案树中选中目标方案(默认「默认方案(个人)」)。
|
||||
方案树节点结构:li.k-item > .k-in.kd-treenode-textcnt > .kd-treenode-text。
|
||||
注意:K3 树节点用 by_js click 不触发选中事件(现场验证),必须真实鼠标点击
|
||||
.k-in.kd-treenode-textcnt 节点;选中成功后界面出现 SelectedSchemeItemControlTemplate。"""
|
||||
ac = page.actions
|
||||
end = time.time() + config.TIMEOUT
|
||||
while time.time() < end:
|
||||
for li in page.eles('css:.k-window li.k-item', timeout=2):
|
||||
try:
|
||||
if not li.states.is_displayed:
|
||||
continue
|
||||
t = li.ele('css:.kd-treenode-text', timeout=0.5)
|
||||
if t is None or scheme not in (t.text or ''):
|
||||
continue
|
||||
# 已选中:选中模板(SelectedSchemeItemControlTemplate)的文本须是目标方案,
|
||||
# 否则可能是上次选的其它方案,误判会导出错误数据
|
||||
cur = page.ele('css:.SelectedSchemeItemControlTemplate', timeout=1)
|
||||
if cur is not None and scheme in (cur.text or ''):
|
||||
config.log(f'{TAG} 方案已是: {t.text.strip()}')
|
||||
return True
|
||||
# 真实鼠标点击节点外层 .k-in.kd-treenode-textcnt(by_js 不触发选中)
|
||||
node = t.parent() # .k-in.kd-treenode-textcnt
|
||||
if node is None or not node.states.is_displayed:
|
||||
node = t
|
||||
try:
|
||||
ac.move_to(node)
|
||||
time.sleep(0.3)
|
||||
ac.click()
|
||||
except Exception:
|
||||
try:
|
||||
node.click(by_js=True)
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.8)
|
||||
# 确认选中:出现 SelectedSchemeItemControlTemplate 才算点击成功
|
||||
if kc.ele_visible(page, 'css:.SelectedSchemeItemControlTemplate', timeout=2):
|
||||
config.log(f'{TAG} 已选择方案: {t.text.strip()}')
|
||||
return True
|
||||
# 未生效:可能点到文本被全选,改为点 li 下的 .kd-treenode-textcnt 外层再试一次
|
||||
try:
|
||||
cnt = li.ele('css:.kd-treenode-textcnt', timeout=1)
|
||||
if cnt is not None and cnt.states.is_displayed:
|
||||
ac.move_to(cnt)
|
||||
time.sleep(0.3)
|
||||
ac.click()
|
||||
time.sleep(0.8)
|
||||
if kc.ele_visible(page, 'css:.SelectedSchemeItemControlTemplate',
|
||||
timeout=2):
|
||||
config.log(f'{TAG} 已选择方案: {t.text.strip()}')
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
config.log(f'{TAG} 过滤窗口方案树中未找到: {scheme}')
|
||||
return False
|
||||
|
||||
|
||||
def _submit_filter(page):
|
||||
"""点过滤窗口「确定」触发查询。注意:[id*="_Filter-FBTNOK_c"] 也会命中仓库等其它
|
||||
过滤面板的同 id 按钮,用 :not + .k-window 限定,防止误点。"""
|
||||
if not kc.click_visible(page, 'css:.k-window [id*="_Filter-FBTNOK_c"]:not([id*="FBeginStockId"])'):
|
||||
config.log(f'{TAG} 找不到过滤窗口确定按钮')
|
||||
return False
|
||||
config.log(f'{TAG} 已提交过滤查询')
|
||||
return True
|
||||
|
||||
|
||||
def _read_rowcount(page):
|
||||
"""读分页栏行数统计(span[data-kdid="rowcount_pagerlist2"],文本形如「共519行」)。
|
||||
返回 (文本, 条数);未找到/未显示返回 (None, -1)。"""
|
||||
try:
|
||||
for el in page.eles('css:span[data-kdid="rowcount_pagerlist2"]', timeout=1):
|
||||
try:
|
||||
if not el.states.is_displayed:
|
||||
continue
|
||||
txt = (el.text or '').strip()
|
||||
m = re.search(r'共\s*(\d+)\s*行', txt)
|
||||
return txt, (int(m.group(1)) if m else -1)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
return None, -1
|
||||
|
||||
|
||||
def _wait_progress(page, timeout=30):
|
||||
"""等待查询完成:进入页面时分页栏已带旧条数,查询时会先变 0(或消失)再变新条数。
|
||||
故记录初始条数,等行数经历「变 0/消失」或「发生变化」后,再出现非 0 条数才算完成。
|
||||
- 条数可用(数字):行数变 0 / 变化即完成。
|
||||
- 条数不可用:K3 未翻到最后一页时总行数显示「共*行」星号(读不到数字,现场确认),
|
||||
查询中不会有数字信号,仅等一个短窗口(NO_COUNT_GAP)让 K3 算出行数;
|
||||
窗口内星号→数字出现即视为查询完成,始终无数字 → 按查询已完成直接继续
|
||||
(避免 30s 白等,由上层重试机制兜底)。
|
||||
超时不再判定失败:现场结论查询可能太快、行数不经历 0 直接保持旧值,死等会白白卡
|
||||
几分钟。故超时后直接继续导出(由上层重试机制兜底,避免整单卡死)。"""
|
||||
txt0, init_cnt = _read_rowcount(page)
|
||||
if init_cnt >= 0:
|
||||
config.log(f'{TAG} 当前条数: {init_cnt},等待查询刷新...')
|
||||
elif txt0:
|
||||
config.log(f'{TAG} 当前条数: {txt0}(星号=总行数未计算),等待查询刷新...')
|
||||
else:
|
||||
config.log(f'{TAG} 当前条数: 无,等待查询刷新...')
|
||||
if init_cnt < 0:
|
||||
# 条数不可用:短窗口内等待 K3 算出数字;星号→数字出现即完成,否则直接继续
|
||||
NO_COUNT_GAP = 10
|
||||
end = time.time() + NO_COUNT_GAP
|
||||
while time.time() < end:
|
||||
txt, cnt = _read_rowcount(page)
|
||||
if cnt > 0:
|
||||
config.log(f'{TAG} 查询完成: {txt}')
|
||||
return True
|
||||
time.sleep(1)
|
||||
config.log(f'{TAG} 条数不可用({txt0 or "无"}),按查询已完成直接继续导出')
|
||||
return True
|
||||
saw_reset = False
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
txt, cnt = _read_rowcount(page)
|
||||
if cnt == 0:
|
||||
saw_reset = True # 先变 0:查询已触发,正在刷新
|
||||
elif cnt > 0:
|
||||
if saw_reset or cnt != init_cnt:
|
||||
config.log(f'{TAG} 查询完成: {txt}')
|
||||
return True
|
||||
time.sleep(1)
|
||||
config.log(f'{TAG} 等待查询完成超时(行数未刷新,直接继续导出)')
|
||||
return True
|
||||
|
||||
|
||||
def _export_all_pages(page):
|
||||
"""选项 → 引出(真实鼠标悬浮展开子菜单)→ 按列表引出数据。
|
||||
现场结论:物理点击内容 span 只会『全选文字』不触发菜单;JS click 又触发不了
|
||||
K3 的悬浮式嵌套子菜单。故全程用 page.actions 的真实鼠标 move_to(悬浮,不点击文字),
|
||||
让子菜单展开后用 move_to+click 点中「按列表引出数据」;不点 span 文本,避免全选。
|
||||
注意:必须复用同一个 ac=page.actions,保证光标位置连续(悬浮链不中断子菜单不收起)。
|
||||
本列表页与需求31不同:选项=tbOptionLists,引出=tbInputOutput,目标=按列表引出数据(tbOutput)。"""
|
||||
ac = page.actions
|
||||
|
||||
def _clickable(span):
|
||||
"""内容 span 的父级可点击元素(a/li),避免点到文本被『全选文字』。"""
|
||||
try:
|
||||
a = span.closest('css:a')
|
||||
if a is not None and a.tag.lower() == 'a' and a.states.is_displayed:
|
||||
return a
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
li = span.closest('css:li')
|
||||
if li is not None and li.states.is_displayed:
|
||||
return li
|
||||
except Exception:
|
||||
pass
|
||||
return span
|
||||
|
||||
# 1. 点「选项」打开配置菜单(点其 a/li,避开文本)
|
||||
opt = page.ele('css:span[id*="BILLMENU_TOOLBAR-tbOptionLists"]', timeout=5)
|
||||
if opt is None or not opt.states.is_displayed:
|
||||
opt = page.ele('css:[id*="BILLMENU_TOOLBAR-tbOptionLists"]', timeout=5)
|
||||
if opt is None or not opt.states.is_displayed:
|
||||
config.log(f'{TAG} 找不到选项按钮')
|
||||
return False
|
||||
try:
|
||||
ac.move_to(_clickable(opt)).click()
|
||||
except Exception:
|
||||
try:
|
||||
opt.click(by_js=True)
|
||||
except Exception:
|
||||
config.log(f'{TAG} 点选项失败')
|
||||
return False
|
||||
time.sleep(1.2)
|
||||
|
||||
# 2. 定位「引出」(splitbutton)
|
||||
split = page.ele('css:span[id*="BILLMENU_TOOLBAR-tbInputOutput"]', timeout=5)
|
||||
if split is None or not split.states.is_displayed:
|
||||
split = page.ele('css:[id*="BILLMENU_TOOLBAR-tbInputOutput"]', timeout=5)
|
||||
if split is None or not split.states.is_displayed:
|
||||
config.log(f'{TAG} 找不到导出(引出)按钮')
|
||||
return False
|
||||
|
||||
def _trigger():
|
||||
"""悬浮目标:优先右箭头(悬浮开子菜单),无箭头则悬浮整体。"""
|
||||
try:
|
||||
ar = split.parent().ele('css:span.k-icon', timeout=1)
|
||||
if ar is not None and ar.states.is_displayed:
|
||||
return ar
|
||||
except Exception:
|
||||
pass
|
||||
return _clickable(split)
|
||||
|
||||
trigger = _trigger()
|
||||
|
||||
# 3. 悬浮展开「按列表引出数据」子菜单
|
||||
target = None
|
||||
for _ in range(4):
|
||||
try:
|
||||
ac.move_to(trigger) # 真实鼠标悬浮到右箭头,子菜单展开
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1.0)
|
||||
t = page.ele('css:span[id$="BILLMENU_TOOLBAR-tbOutput"]', timeout=2)
|
||||
if t is not None and t.states.is_displayed:
|
||||
target = t
|
||||
break
|
||||
if target is None or not target.states.is_displayed:
|
||||
for _ in range(3):
|
||||
try:
|
||||
trigger.click()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
t = page.ele('css:span[id$="BILLMENU_TOOLBAR-tbOutput"]', timeout=2)
|
||||
if t is not None and t.states.is_displayed:
|
||||
target = t
|
||||
break
|
||||
if target is None or not target.states.is_displayed:
|
||||
config.log(f'{TAG} 找不到按列表引出数据')
|
||||
return False
|
||||
|
||||
# 4. 光标从「引出」连续移入「按列表引出数据」再点击(悬浮链不断,菜单不收起)
|
||||
try:
|
||||
ac.move_to(_clickable(target))
|
||||
time.sleep(0.5)
|
||||
ac.click()
|
||||
except Exception:
|
||||
try:
|
||||
target.click(by_js=True)
|
||||
except Exception:
|
||||
config.log(f'{TAG} 点击按列表引出数据失败')
|
||||
return False
|
||||
config.log(f'{TAG} 已触发按列表引出数据')
|
||||
return True
|
||||
|
||||
|
||||
def _click_quick_scheme(page, scheme):
|
||||
"""直接点击列表页顶部快捷方案条中的目标方案,无需打开过滤窗口。
|
||||
结构:div[filter-role="filterschemecontent"] > div.SchemeItemControlTemplate(含方案名,
|
||||
选中的为 SelectedSchemeItemControlTemplate)。
|
||||
注意:K3 控件用 by_js click 可能不触发,优先真实鼠标点击。"""
|
||||
ac = page.actions
|
||||
end = time.time() + config.TIMEOUT
|
||||
while time.time() < end:
|
||||
for item in page.eles(
|
||||
'css:div[filter-role="filterschemecontent"] '
|
||||
'div[class*="SchemeItemControlTemplate"]', timeout=2):
|
||||
try:
|
||||
if not item.states.is_displayed:
|
||||
continue
|
||||
txt = (item.text or '').strip()
|
||||
if txt != scheme: # 精确匹配:避免「默认方案」误命中「采购订单宽表默认方案」
|
||||
continue
|
||||
cls = item.attr('class') or ''
|
||||
if 'Selected' in cls:
|
||||
config.log(f'{TAG} 快捷方案已是: {txt}')
|
||||
return True
|
||||
try:
|
||||
ac.move_to(item)
|
||||
time.sleep(0.3)
|
||||
ac.click()
|
||||
except Exception:
|
||||
try:
|
||||
item.click(by_js=True)
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
# 确认选中:快捷条中 Selected 方案变为目标方案
|
||||
cur = page.ele(
|
||||
'css:div[filter-role="filterschemecontent"] '
|
||||
'div.SelectedSchemeItemControlTemplate', timeout=2)
|
||||
if cur is not None and scheme in (cur.text or ''):
|
||||
config.log(f'{TAG} 已点选快捷方案: {txt}')
|
||||
return True
|
||||
# 未确认选中:返回 False 走过滤窗口回退,防止把旧数据当本次结果
|
||||
config.log(f'{TAG} 点击快捷方案未确认选中: {txt}')
|
||||
return False
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
config.log(f'{TAG} 快捷方案条中未找到: {scheme}')
|
||||
return False
|
||||
|
||||
|
||||
def _run_once(page, scheme):
|
||||
"""直接点快捷方案 → 等查询 → 按列表引出数据。
|
||||
快捷方案条不存在时回退到过滤窗口选方案。"""
|
||||
if _click_quick_scheme(page, scheme):
|
||||
if not _wait_progress(page):
|
||||
return False
|
||||
else:
|
||||
# 回退:过滤窗口选方案
|
||||
if not _open_filter(page):
|
||||
return False
|
||||
if not _select_scheme(page, scheme):
|
||||
return False
|
||||
if not _submit_filter(page):
|
||||
return False
|
||||
if not _wait_progress(page):
|
||||
return False
|
||||
return _export_all_pages(page)
|
||||
|
||||
|
||||
# ================== 入口 ==================
|
||||
def run(page, save_dir, scheme, erp='new', progress=None):
|
||||
"""先全局搜索打开列表(校验列表标签页已激活),再按方案导出(快捷方案 → 等查询 → 引出 → 下载,重试 3 次)。
|
||||
每次导出前校验仍处于「采购订单列表」标签页,不对则清理残留标签页后重新搜索进入。
|
||||
progress(done, total) 为整体进度回调;返回保存文件路径,失败返回 None。"""
|
||||
# 连导场景(需求31物料收发汇总后接需求32)会残留「物料收发汇总表」标签页:
|
||||
# 多标签下 page.eles 全页匹配可能命中残留标签页里的元素,干扰后续操作。
|
||||
# 先关掉非激活标签页(SPA 内关 tab,不能整页回 index.aspx,否则跳登录页),
|
||||
# 确保从干净状态开始本次导出。
|
||||
_back_home(page, erp)
|
||||
if not _open_report(page, erp):
|
||||
raise RuntimeError("打开「采购订单列表」失败:全局搜索未命中 CGDDLB 列表(详见日志)")
|
||||
new_name = f'{config.FILE_PREFIX_32}_{datetime.now():%Y-%m-%d}.xlsx'
|
||||
config.log(f'{TAG} 导出文件: {new_name}')
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
config.log(f'{TAG} 第 {attempt}/{config.RETRY_MAX} 次导出')
|
||||
# 做之前校验:当前激活标签必须是「采购订单列表」,否则回首页重新搜索进入
|
||||
if REPORT_KEYWORD not in _active_tab_title(page):
|
||||
config.log(f'{TAG} 当前标签页不是「采购订单列表」,清理残留标签页后重新搜索进入')
|
||||
if not _open_report(page, erp):
|
||||
break
|
||||
if _run_once(page, scheme):
|
||||
if kc.download_file(page, save_dir, new_name, tag=TAG):
|
||||
if progress:
|
||||
try:
|
||||
progress(1, 1)
|
||||
except Exception:
|
||||
pass
|
||||
return str(save_dir / new_name)
|
||||
kc.reset_filter_state(page, tag=TAG) # 清掉失败留下的弹层/半填条件再重试
|
||||
time.sleep(2)
|
||||
config.log(f'{TAG} 重试 {config.RETRY_MAX} 次均失败')
|
||||
if progress:
|
||||
try:
|
||||
progress(1, 1)
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
@@ -0,0 +1 @@
|
||||
DrissionPage>=4.0
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>ERP报表导出</title>
|
||||
<script type="module" crossorigin src="/pui/xq0031_xq0032/assets/index-B7DSB6ed.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0031_xq0032/assets/index-C1QhPHbp.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,171 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""金色印象通联数据导出 - webhost 场景插件(XQ0045 + XQ0046 合并版)
|
||||
|
||||
通联支付商户服务平台(cus.allinpay.com)交易数据自动导出:
|
||||
- XQ0045 按日:导某一天(YYYY-MM-DD)的交易;
|
||||
- XQ0046 按月:导某个月(YYYY-MM)的交易;
|
||||
服务端导出接口忽略商户参数、始终返回账号全量结果集(实测),因此每个日期只导一份
|
||||
全量文件(含账号下所有商户),直存本地,不再按商户拆分。
|
||||
|
||||
个性化设计:
|
||||
- 通联登录账号密码由插件界面配置经 fields 注入(plugin_configs 本机保存,下次免填);
|
||||
- 浏览器现场真登录(固定默认用户目录 + ddddocr 验证码识别),登录后转 requests.Session
|
||||
直调导出接口(服务端有 Referer 外链校验,插件内统一带 Referer);
|
||||
- 日期支持多个(逗号分隔,逐个导出);mode=日+月 时按日期串格式自动识别日/月。
|
||||
"""
|
||||
import os
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
||||
|
||||
from . import config
|
||||
from .data import allinpay_login, allinpay_export
|
||||
|
||||
MODE_DAY = '日'
|
||||
MODE_MONTH = '月'
|
||||
MODE_BOTH = '日+月'
|
||||
|
||||
CONTENT_TRX = '交易查询'
|
||||
CONTENT_BILL = '账单'
|
||||
CONTENT_BOTH = '两个都导'
|
||||
|
||||
|
||||
def _default_save_dir():
|
||||
return str(Path(config.get_desktop()) / f"金色印象通联数据_{datetime.now():%Y%m%d}")
|
||||
|
||||
|
||||
def _build_tasks(mode, day_date, month_date):
|
||||
"""按执行模式组合 (模式, 日期) 任务列表(前端已用日期选择器选好值,这里只做组装)。"""
|
||||
tasks = []
|
||||
if mode in (MODE_DAY, MODE_BOTH) and day_date:
|
||||
tasks.append((MODE_DAY, day_date))
|
||||
if mode in (MODE_MONTH, MODE_BOTH) and month_date:
|
||||
tasks.append((MODE_MONTH, month_date))
|
||||
if not tasks:
|
||||
raise RuntimeError("请选择按日导出的日期和/或按月导出的月份")
|
||||
return tasks
|
||||
|
||||
|
||||
class TongLianExportPlugin(ScenePlugin):
|
||||
id = "xq0045_xq0046"
|
||||
name = "金色印象通联数据导出"
|
||||
version = "1.0.5"
|
||||
description = ("通联支付交易数据自动导出:XQ0045 按日 / XQ0046 按月,"
|
||||
"账号全量数据导出(含全部商户),服务端生成文件直存本地")
|
||||
platform = "" # 通联自带登录页(验证码),插件内现场真登录,不使用底座共享登录态
|
||||
uses_month = False
|
||||
capabilities = ["xq0045_xq0046"]
|
||||
permissions = {"platforms": []}
|
||||
# 与 plugin.json.fields 一致(ui=true 前端自渲染,此处分层作为参数契约文档)
|
||||
fields = {
|
||||
"mode": {"type": "string", "title": "执行模式", "default": MODE_BOTH,
|
||||
"enum": [MODE_BOTH, MODE_DAY, MODE_MONTH]},
|
||||
"content": {"type": "string", "title": "导出内容", "default": CONTENT_BOTH,
|
||||
"enum": [CONTENT_BOTH, CONTENT_TRX, CONTENT_BILL]},
|
||||
"day_date": {"type": "string", "format": "date", "title": "按日导出(数据起始日)", "default": ""},
|
||||
"month_date": {"type": "string", "format": "month", "title": "按月导出", "default": ""},
|
||||
"tl_username": {"type": "string", "title": "通联登录账号", "default": ""},
|
||||
"tl_password": {"type": "string", "title": "通联登录密码", "default": ""},
|
||||
"save_dir": {"type": "string", "title": "保存目录", "default": ""},
|
||||
}
|
||||
|
||||
def run(self, fields, ctx) -> dict:
|
||||
fields = fields or {}
|
||||
config.set_log(ctx.log)
|
||||
|
||||
# ---------- 解析与校验 ----------
|
||||
mode = str(fields.get("mode") or MODE_BOTH).strip()
|
||||
content = str(fields.get("content") or CONTENT_BOTH).strip()
|
||||
username = str(fields.get("tl_username") or "").strip()
|
||||
password = str(fields.get("tl_password") or "")
|
||||
day_date = str(fields.get("day_date") or "").strip()
|
||||
month_date = str(fields.get("month_date") or "").strip()
|
||||
save_dir = str(fields.get("save_dir") or "").strip().strip('"') or _default_save_dir()
|
||||
|
||||
if not username or not password:
|
||||
raise RuntimeError("通联登录账号/密码缺失:请在插件界面填写并保存配置后重试")
|
||||
if mode not in (MODE_BOTH, MODE_DAY, MODE_MONTH):
|
||||
raise RuntimeError(f"未知执行模式:{mode}")
|
||||
if content not in (CONTENT_BOTH, CONTENT_TRX, CONTENT_BILL):
|
||||
raise RuntimeError(f"未知导出内容:{content}")
|
||||
|
||||
do_trx = content in (CONTENT_TRX, CONTENT_BOTH)
|
||||
do_bill = content in (CONTENT_BILL, CONTENT_BOTH)
|
||||
tasks = _build_tasks(mode, day_date, month_date)
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
ctx.log(f"导出内容:{content},模式:{mode},任务 {len(tasks)} 项,保存目录:{save_dir}")
|
||||
|
||||
# ---------- 登录 ----------
|
||||
ctx.progress(3)
|
||||
ctx.log("开始通联平台登录(接口优先,浏览器兜底)…")
|
||||
session = allinpay_login.tl_login(username, password)
|
||||
if session is None:
|
||||
raise RuntimeError("通联平台登录失败(账号密码错误或验证码多次识别失败),详见日志")
|
||||
ctx.progress(10)
|
||||
|
||||
saved, failed = [], []
|
||||
|
||||
# ---------- 交易查询导出(15~70:每个任务导一份账号全量,服务端忽略商户参数) ----------
|
||||
if do_trx:
|
||||
# 服务端 cusid 不能传空串(传空会直接 504),但会忽略其筛选语义、始终返回
|
||||
# 账号全量结果集;故取账号下首个真实商户号作为种子参数即可。
|
||||
ctx.log("获取账号商户列表(取首个商户号作查询种子,服务端返回全量)…")
|
||||
cus_list = allinpay_export.get_cus_list(session)
|
||||
seed_cusid = cus_list[0]['key'] if cus_list else ''
|
||||
ctx.log(f"账号下商户 {len(cus_list)} 个,查询种子商户号:{seed_cusid}")
|
||||
if not seed_cusid:
|
||||
raise RuntimeError("获取商户列表失败:账号下无商户,无法发起导出")
|
||||
units = len(tasks)
|
||||
done = 0
|
||||
for m, d in tasks:
|
||||
done += 1
|
||||
label = f"交易[{m} {d}](账号全量)"
|
||||
ctx.log(f"--- [{done}/{units}] 导出 {label} ---")
|
||||
try:
|
||||
start, end = allinpay_export.build_date_range(m, d)
|
||||
ctx.log(f" 查询区间 {start} ~ {end}")
|
||||
fid = allinpay_export.start_export(session, seed_cusid, start, end)
|
||||
ctx.log(f" 导出任务已提交 fid={fid},等待服务端生成…")
|
||||
allinpay_export.wait_export_done(session, fid)
|
||||
url = allinpay_export.get_download_url(session, fid)
|
||||
ctx.log(" 开始下载导出文件…")
|
||||
path = allinpay_export.download_file(session, url, save_dir, f"{m}交易查询结果_{d}")
|
||||
saved.append(path)
|
||||
except Exception as e:
|
||||
ctx.log(f" 交易导出失败:{e}", "ERROR")
|
||||
failed.append(f"{label}[{e}]")
|
||||
ctx.progress(15 + int(55 * done / max(1, units)))
|
||||
ctx.progress(70)
|
||||
|
||||
# ---------- 账单导出(70~95,主账号 zip 下载 + 解压) ----------
|
||||
if do_bill:
|
||||
units = len(tasks)
|
||||
done = 0
|
||||
for m, d in tasks:
|
||||
done += 1
|
||||
label = f"账单[{m} {d}]"
|
||||
ctx.log(f"--- [{done}/{units}] 导出 {label} ---")
|
||||
try:
|
||||
bill_type = 'month' if m == MODE_MONTH else 'day'
|
||||
_, extract_dir = allinpay_export.bill_download(
|
||||
session, d, bill_type, save_dir)
|
||||
saved.append(extract_dir)
|
||||
except Exception as e:
|
||||
ctx.log(f" 账单导出失败:{e}", "ERROR")
|
||||
failed.append(f"{label}[{e}]")
|
||||
ctx.progress(70 + int(25 * done / max(1, units)))
|
||||
ctx.progress(100)
|
||||
|
||||
# ---------- 汇总 ----------
|
||||
notes = [f"已保存 {len(saved)} 个文件/目录:"] + [f" {p}" for p in saved]
|
||||
if failed:
|
||||
notes.append(f"失败 {len(failed)} 项:{'、'.join(failed)}")
|
||||
summary = (f"通联数据导出完成(部分失败):成功 {len(saved)} 个,"
|
||||
f"失败 {len(failed)} 项 → {save_dir}")
|
||||
else:
|
||||
summary = f"通联数据导出完成:共 {len(saved)} 个文件/目录 → {save_dir}"
|
||||
return {"summary": summary, "rows": [], "notes": notes}
|
||||
|
||||
|
||||
PLUGINS.append(TongLianExportPlugin())
|
||||
@@ -0,0 +1,102 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0045_xq0046 金色印象通联数据导出 插件 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:本包只依赖 Python 标准库 / 第三方库 / 底座注入的 RunContext。
|
||||
业务模块统一经 config.log() 输出日志(转发到 ctx.log,无 ctx 时回落到 print)。
|
||||
"""
|
||||
import os
|
||||
|
||||
# ==================== 通联平台 ====================
|
||||
LOGIN_URL = 'https://cus.allinpay.com/login'
|
||||
MAIN_URL = 'https://cus.allinpay.com/main.dsr' # 已登录首页(预热/Referer 来源)
|
||||
SEARCH_URL = 'https://cus.allinpay.com/tranx25/search'
|
||||
STATUS_URL = 'https://cus.allinpay.com/export/statusdownload'
|
||||
DOWNLOAD_INFO_URL = 'https://cus.allinpay.com/export/downloadexport/'
|
||||
BILL_URL = 'https://cus.allinpay.com/checkacct25/download'
|
||||
TRXCODE_URL = 'https://cus.allinpay.com/unauth/queryInterCode'
|
||||
TRXSTATE_URL = 'https://cus.allinpay.com/unauth/queryRecordState'
|
||||
|
||||
# 服务端有 Referer 外链校验:直接访问会被重定向回 /main.dsr
|
||||
SEARCH_HEADERS = {'Referer': MAIN_URL}
|
||||
|
||||
# ==================== 导出参数 ====================
|
||||
EXPORT_CURRENT = 'onebtnexpt' # 导出当前页
|
||||
EXPORT_ALL = 'all' # 导出全部(默认用这个)
|
||||
|
||||
# 异步导出状态轮询:每 6 秒一次,最多 12 次(服务端超时上限约 10 次/60 秒)
|
||||
STATUS_POLL_INTERVAL = 6
|
||||
STATUS_POLL_MAX = 12
|
||||
|
||||
# 登录/验证码 —— 风控敏感:每次提交都计入服务端登录尝试次数,从严控制重试,
|
||||
# 避免连续多次提交触发平台「登录失败次数已达上限」锁定(曾实测踩雷,账号被锁 2 小时)
|
||||
RETRY_MAX = 1 # 浏览器兜底登录轮数(失败即停,不反复登录)
|
||||
CAPTCHA_RETRY = 3 # 浏览器每轮验证码重试次数
|
||||
API_CAPTCHA_RETRY = 3 # 接口登录验证码重试次数
|
||||
LOGIN_FAIL_BACKOFF = 8 # 登录提交失败后的退避秒数(让风控计数沉降)
|
||||
TIMEOUT = 10 # 元素等待超时(秒)
|
||||
|
||||
# ==================== 默认保存目录 ====================
|
||||
_DESKTOP = os.path.join(os.path.expanduser('~'), 'Desktop')
|
||||
|
||||
|
||||
def get_desktop():
|
||||
return _DESKTOP
|
||||
|
||||
|
||||
# ==================== 浏览器用户目录 ====================
|
||||
def get_browser_profile_dir():
|
||||
"""独立固定浏览器用户目录:登录态跨次保留(免验证码),且不占用用户日常 Chrome 配置。
|
||||
|
||||
放 %LOCALAPPDATA% 下而非系统临时目录,避免被磁盘清理工具清掉导致登录态丢失。
|
||||
"""
|
||||
base = os.environ.get('LOCALAPPDATA') or os.path.expanduser('~')
|
||||
return os.path.join(base, '37duAutomation', 'browser_sessions', 'xq0045_xq0046')
|
||||
|
||||
|
||||
# ==================== 登录会话复用 ====================
|
||||
def get_session_file():
|
||||
"""已登录会话 cookies 落盘路径:跨 run 复用通联登录,避免每次执行都重新登录。"""
|
||||
base = os.environ.get('LOCALAPPDATA') or os.path.expanduser('~')
|
||||
d = os.path.join(base, '37duAutomation', 'sessions')
|
||||
os.makedirs(d, exist_ok=True)
|
||||
return os.path.join(d, 'allinpay_xq0045_xq0046.json')
|
||||
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
|
||||
|
||||
def set_log(fn):
|
||||
"""注入 ctx.log(RunContext.log),各模块经 log()/logger 输出。"""
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def log(msg, level="INFO"):
|
||||
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()
|
||||
@@ -0,0 +1 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
@@ -0,0 +1,259 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""通联平台交易数据导出(xq0045_xq0046 插件内自包含)。
|
||||
|
||||
服务端行为已探明(探针 workflows/share/debug_tranx25 实测验证):
|
||||
- 请求必须带 Referer,否则被重定向回 /main.dsr;
|
||||
- 商户列表内嵌在搜索页 JS:var childcuslist = '[{"key":"商户号","value":"商户名"},...]';
|
||||
- 查询:POST /tranx25/search,data={issubmit,cusid,startDate,endDate,export:false,pageIndex,
|
||||
canemptycusid},响应为整页 HTML(结果表格 #dataTable);
|
||||
- 导出(异步三步):
|
||||
1) POST /tranx25/search 带 export=all → JSON {"code":"0","message":"<fid>"}(code=1 失败);
|
||||
2) POST /export/statusdownload {id:fid} 每 6 秒轮询至 code=0(就绪);
|
||||
3) POST /export/downloadexport/ {id:fid} → {"code":"0","message":"<下载URL>"} → GET 落文件。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import zipfile
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
# ==================== HTTP 封装(统一带 Referer) ====================
|
||||
def _get(session, url, **kw):
|
||||
return session.get(url, headers=config.SEARCH_HEADERS, timeout=20, **kw)
|
||||
|
||||
|
||||
def _post(session, url, data=None, **kw):
|
||||
return session.post(url, data=data, headers=config.SEARCH_HEADERS, timeout=30, **kw)
|
||||
|
||||
|
||||
def _parse_code_message(text):
|
||||
"""解析服务端返回的 JS 风格对象(单引号,如 {code:'0',message:'fid'})。
|
||||
|
||||
前端用 eval('('+data+')') 解析,说明响应不是标准 JSON;
|
||||
先试标准 JSON,失败再正则提取 code/message。返回 (code, message)。
|
||||
"""
|
||||
text = (text or '').strip()
|
||||
try:
|
||||
j = json.loads(text)
|
||||
return str(j.get('code')), str(j.get('message') or '')
|
||||
except Exception:
|
||||
pass
|
||||
m_code = re.search(r"code\s*:\s*'?([^',}]+)'?", text)
|
||||
m_msg = re.search(r"message\s*:\s*'([^']*)'", text)
|
||||
code = m_code.group(1).strip() if m_code else ''
|
||||
msg = m_msg.group(1) if m_msg else ''
|
||||
if not (m_code or m_msg):
|
||||
raise RuntimeError(f"响应无法解析(可能会话失效被踢回页面):{text[:200]}")
|
||||
return code, msg
|
||||
|
||||
|
||||
# ==================== 商户列表 ====================
|
||||
def get_cus_list(session):
|
||||
"""GET 搜索页解析 childcuslist → [{'key': 商户号, 'value': 商户名}, ...]。"""
|
||||
resp = _get(session, config.SEARCH_URL)
|
||||
m = re.search(r"var childcuslist\s*=\s*'([^']*)'", resp.text)
|
||||
if not m:
|
||||
raise RuntimeError("搜索页未找到 childcuslist(会话可能失效,请重新登录)")
|
||||
data = json.loads(m.group(1))
|
||||
if not isinstance(data, list):
|
||||
raise RuntimeError("childcuslist 解析异常")
|
||||
return data
|
||||
|
||||
|
||||
# ==================== 异步导出三步 ====================
|
||||
def start_export(session, cusid, start, end):
|
||||
"""发起导出 → 返回 fid。
|
||||
|
||||
服务端实测(探针 exp_probe + 实跑 + 测速验证):
|
||||
- export=all 会忽略日期参数、导出当天全量(错误行为);
|
||||
- export=onebtnexpt(导出当前查询结果集)才按日期区间导出;
|
||||
- cusid 必须非空:传空串时服务端直接 504 Gateway Timeout(实测 60s 超时);
|
||||
但服务端忽略 cusid 的筛选语义——传任意真实商户号都返回账号全量结果集
|
||||
(不同商户同日期返回同一 fid、同一文件),故用账号下首个商户号即可。
|
||||
因此必须先查询(export=false)建立结果集,再用 onebtnexpt 导出。
|
||||
"""
|
||||
base = {
|
||||
'issubmit': 'issubmit',
|
||||
'cusid': cusid,
|
||||
'startDate': start,
|
||||
'endDate': end,
|
||||
'pageIndex': '1',
|
||||
'canemptycusid': 'true',
|
||||
}
|
||||
# 1) 查询建立结果集(export=false)
|
||||
_post(session, config.SEARCH_URL, {**base, 'export': 'false'})
|
||||
# 2) 导出当前结果集(onebtnexpt)
|
||||
code, msg = _parse_code_message(
|
||||
_post(session, config.SEARCH_URL, {**base, 'export': config.EXPORT_CURRENT}).text)
|
||||
if code == '1':
|
||||
raise RuntimeError(f"导出失败:{msg}")
|
||||
fid = msg
|
||||
if not fid:
|
||||
raise RuntimeError("导出响应缺少 fid")
|
||||
return fid
|
||||
|
||||
|
||||
def wait_export_done(session, fid):
|
||||
"""轮询导出状态,直到就绪(code=0)或超时。
|
||||
|
||||
状态契约(探针实测):code='0'=文件就绪;code='1'=生成中。
|
||||
其它码(如 '2' 失败)只告警不判就绪,避免误把失败态当成功去取下载地址;
|
||||
超时错误里带最后状态,便于定位。
|
||||
"""
|
||||
last = ""
|
||||
for i in range(1, config.STATUS_POLL_MAX + 1):
|
||||
code, msg = _parse_code_message(_post(session, config.STATUS_URL, {'id': fid}).text)
|
||||
last = f"code={code} {msg}".strip()
|
||||
if code == '0':
|
||||
config.log(f"[导出] fid={fid} 文件就绪(轮询 {i} 次)")
|
||||
return True
|
||||
if code != '1':
|
||||
config.log(f"[导出] fid={fid} 状态异常({last}),继续等待", "WARN")
|
||||
else:
|
||||
# 每次轮询都打进度,避免长时间静默被误认为卡死
|
||||
config.log(f"[导出] fid={fid} 文件生成中(第 {i} 次轮询,已等待 {i * config.STATUS_POLL_INTERVAL} 秒)…")
|
||||
time.sleep(config.STATUS_POLL_INTERVAL)
|
||||
raise RuntimeError(f"导出超时(服务端未在时限内生成文件,最后状态:{last})")
|
||||
|
||||
|
||||
def get_download_url(session, fid):
|
||||
"""获取下载地址。"""
|
||||
code, msg = _parse_code_message(_post(session, config.DOWNLOAD_INFO_URL, {'id': fid}).text)
|
||||
if code != '0':
|
||||
raise RuntimeError(f"获取下载地址失败:{msg}")
|
||||
return msg
|
||||
|
||||
|
||||
# ==================== 下载校验 ====================
|
||||
def _check_download_content_type(resp):
|
||||
"""下载响应 Content-Type 校验:HTML/文本说明可能被踢回登录页,直接报错。"""
|
||||
ct = (resp.headers.get('Content-Type') or '').lower()
|
||||
if 'html' in ct or ct.startswith('text/'):
|
||||
raise RuntimeError(
|
||||
f"下载返回非文件内容(Content-Type={ct or 'unknown'}),会话可能已失效,请重新登录")
|
||||
|
||||
|
||||
def _is_zip_file(path):
|
||||
"""文件头魔数校验:zip/xlsx 均以 PK 开头。"""
|
||||
try:
|
||||
with open(path, 'rb') as f:
|
||||
return f.read(2) == b'PK'
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def _safe_extract(zip_path, extract_dir):
|
||||
"""解压 zip,并拦截路径穿越条目(.. / 绝对路径)。"""
|
||||
with zipfile.ZipFile(zip_path) as zf:
|
||||
for info in zf.infolist():
|
||||
parts = Path(info.filename).parts
|
||||
if info.filename.startswith('/') or '..' in parts or ':' in parts:
|
||||
raise RuntimeError(f"压缩包含非法路径条目,已中止解压:{info.filename}")
|
||||
zf.extractall(extract_dir)
|
||||
|
||||
|
||||
def download_file(session, url, folder, stem):
|
||||
"""下载导出文件到 folder/,文件名 stem + 扩展名(优先 Content-Disposition,默认 .xlsx)。
|
||||
返回最终文件路径。带 Content-Type 与文件魔数校验,防会话失效时把 HTML 落成伪文件。"""
|
||||
resp = session.get(url, headers=config.SEARCH_HEADERS, timeout=180, stream=True)
|
||||
resp.raise_for_status()
|
||||
_check_download_content_type(resp)
|
||||
ext = '.xlsx'
|
||||
cd = resp.headers.get('Content-Disposition', '')
|
||||
m = re.search(r'filename\*?=(?:UTF-8\'\')?"?([^\";]+)"?', cd, re.I)
|
||||
if m:
|
||||
nm = m.group(1).strip().strip('"')
|
||||
if '.' in nm:
|
||||
ext = '.' + nm.rsplit('.', 1)[1].lower()
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
path = os.path.join(folder, f"{stem}{ext}")
|
||||
total = int(resp.headers.get('Content-Length') or 0)
|
||||
received, last_log = 0, time.time()
|
||||
with open(path, 'wb') as f:
|
||||
for chunk in resp.iter_content(chunk_size=8192):
|
||||
f.write(chunk)
|
||||
received += len(chunk)
|
||||
now = time.time()
|
||||
if now - last_log >= 8: # 每 8 秒报一次下载进度,避免长下载静默
|
||||
last_log = now
|
||||
mb = received / 1048576
|
||||
if total:
|
||||
pct = received * 100 // max(1, total)
|
||||
config.log(f"[导出] 下载中 {mb:.1f}MB / {total / 1048576:.1f}MB({pct}%)…")
|
||||
else:
|
||||
config.log(f"[导出] 下载中 {mb:.1f}MB…")
|
||||
if not _is_zip_file(path): # xlsx 本质是 zip,文件头须为 PK
|
||||
os.remove(path)
|
||||
raise RuntimeError(f"下载文件不是有效 xlsx(文件头异常),已删除:{path}")
|
||||
config.log(f"[导出] 已保存:{path}({received / 1048576:.1f} MB)")
|
||||
return path
|
||||
|
||||
|
||||
# ==================== 日期范围 ====================
|
||||
def build_date_range(mode, date_str):
|
||||
"""按模式把日期字符串转成查询区间 (start, end)。
|
||||
mode='月':date_str=YYYY-MM → 当月 1 日 10:00:00 ~ 下月 1 日 10:00:00(对账 10 点切日口径);
|
||||
mode='日':date_str=YYYY-MM-DD(数据起始日,默认昨天)→ 当天 00:00:00 ~ 次日 23:59:59
|
||||
(即默认 = 昨天0点 ~ 今天24点,今天数据少基本无影响)。"""
|
||||
if mode == '月':
|
||||
ym = datetime.strptime(date_str, '%Y-%m')
|
||||
next_month = (ym.replace(day=1) + timedelta(days=32)).replace(day=1)
|
||||
return (ym.strftime('%Y-%m-01 10:00:00'),
|
||||
next_month.strftime('%Y-%m-01 10:00:00'))
|
||||
d = datetime.strptime(date_str, '%Y-%m-%d')
|
||||
nxt = d + timedelta(days=1)
|
||||
return d.strftime('%Y-%m-%d 00:00:00'), nxt.strftime('%Y-%m-%d 23:59:59')
|
||||
|
||||
|
||||
def default_dates(mode):
|
||||
"""未填日期时的默认值:日=昨天;月=上月。"""
|
||||
today = datetime.now()
|
||||
if mode == '月':
|
||||
first_this = today.replace(day=1)
|
||||
last_month = first_this - timedelta(days=1)
|
||||
return last_month.strftime('%Y-%m')
|
||||
yesterday = today - timedelta(days=1)
|
||||
return yesterday.strftime('%Y-%m-%d')
|
||||
|
||||
|
||||
# ==================== 账单导出(主账号,zip 下载 + 解压) ====================
|
||||
def bill_download(session, date_str, bill_type, folder):
|
||||
"""通联账单下载(只导主账号/当前商户)。
|
||||
|
||||
POST /checkacct25/download:日账单 ?reportdate=YYYYMMDD;月账单 ?type=month&reportdate=YYYYMM。
|
||||
服务端返回 {"code":"0","message":"<zip 下载 URL>"},GET 下载 zip 并解压。
|
||||
date_str = YYYY-MM-DD(日)或 YYYY-MM(月);bill_type = 'day' | 'month'。
|
||||
返回 (zip_path, extract_dir)。
|
||||
"""
|
||||
reportdate = date_str.replace('-', '')
|
||||
params = {'reportdate': reportdate}
|
||||
if bill_type == 'month':
|
||||
params['type'] = 'month'
|
||||
resp = _post(session, config.BILL_URL, params=params)
|
||||
code, msg = _parse_code_message(resp.text)
|
||||
if code != '0':
|
||||
raise RuntimeError(f"账单下载失败:{msg}")
|
||||
url = msg
|
||||
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
zr = session.get(url, headers=config.SEARCH_HEADERS, timeout=180, stream=True)
|
||||
zr.raise_for_status()
|
||||
_check_download_content_type(zr)
|
||||
prefix = '日账单' if bill_type == 'day' else '月账单'
|
||||
zip_path = os.path.join(folder, f"{prefix}_{date_str}.zip")
|
||||
with open(zip_path, 'wb') as f:
|
||||
for chunk in zr.iter_content(chunk_size=8192):
|
||||
f.write(chunk)
|
||||
if not _is_zip_file(zip_path):
|
||||
os.remove(zip_path)
|
||||
raise RuntimeError(f"账单下载不是有效 zip(文件头异常),已删除:{zip_path}")
|
||||
|
||||
extract_dir = os.path.join(folder, f"{prefix}_{date_str}")
|
||||
_safe_extract(zip_path, extract_dir)
|
||||
config.log(f"[账单] 已下载并解压:{extract_dir}")
|
||||
return zip_path, extract_dir
|
||||
@@ -0,0 +1,478 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""通联支付商户服务平台登录模块(xq0045_xq0046 插件内自包含)。
|
||||
|
||||
自 workflows/share/allinpay_login.py 迁移,插件化改造点:
|
||||
- 账号密码由插件界面配置经 fields 注入(不再读 .env);
|
||||
- print → config.log;返回 requests.Session(登录后会话直接可用,无需浏览器常驻)。
|
||||
|
||||
登录方式(接口优先,浏览器兜底):
|
||||
1) 接口登录(首选,已实测一次成功):GET /login(拿 SESSION + 页面内嵌 publicKey)
|
||||
→ GET /getvalidCode?type=cuserrorCode 验证码图 → ddddocr 识别(4位)
|
||||
→ JSEncrypt 兼容 RSA 加密密码(PKCS#1 v1.5 + base64)→ POST /login(userid/
|
||||
encpassword/cuserrorCode,带 Referer)→ 302 离开 /login 即成功;
|
||||
2) 浏览器兜底:DrissionPage 现场登录(验证码元素截图 + ddddocr),成功后从浏览器
|
||||
cookies 构建 requests.Session。
|
||||
|
||||
登录页(账号登录 tab,DOM 参考 aa.md):
|
||||
账号 #userid / 密码 #password(初始 readonly,onfocus 移除;提交时页面 JS 加密进 #encpassword)
|
||||
验证码 #captcha + 图 <img src="/getvalidCode?type=cuserrorCode">(URL 型,元素截图 + ddddocr)
|
||||
登录按钮 button[onclick*="valandsubmit"](触发 valandsubmit JS 加密密码后提交表单)
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import random
|
||||
import re
|
||||
import time
|
||||
|
||||
import requests
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
from .. import config
|
||||
|
||||
_UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"Chrome/120.0.0.0 Safari/537.36")
|
||||
HUMAN_DELAY = (0.4, 1.2)
|
||||
_VALIDCODE_URL = config.LOGIN_URL.replace('/login', '/getvalidCode?type=cuserrorCode')
|
||||
_PUBKEY_RE = re.compile(r"var publicKey='([^']+)'")
|
||||
_LOGIN_FORM_RE = re.compile(r'<form[^>]*id=["\']?accountForm|action=["\']?/login')
|
||||
|
||||
_ocr = None
|
||||
|
||||
|
||||
def _get_ocr():
|
||||
"""ddddocr 单例(懒加载),接口/浏览器登录共用。"""
|
||||
global _ocr
|
||||
if _ocr is None:
|
||||
import ddddocr
|
||||
_ocr = ddddocr.DdddOcr(show_ad=False)
|
||||
return _ocr
|
||||
|
||||
|
||||
def _human_pause(a=None, b=None):
|
||||
"""操作间随机延时,模拟人工节奏。"""
|
||||
lo, hi = HUMAN_DELAY if (a is None or b is None) else (a, b)
|
||||
time.sleep(random.uniform(lo, hi))
|
||||
|
||||
|
||||
def _rsa_encrypt(pubkey, pwd):
|
||||
"""JSEncrypt 兼容:RSA PKCS#1 v1.5 加密 + base64。
|
||||
|
||||
页面 publicKey 是 SPKI/X.509 SubjectPublicKeyInfo(BEGIN PUBLIC KEY)裸 DER,
|
||||
用 cryptography 解析后按 PKCS#1 v1.5 填充加密(1024 位公钥,明文 ≤117 字节)。
|
||||
"""
|
||||
from cryptography.hazmat.backends import default_backend
|
||||
from cryptography.hazmat.primitives.asymmetric import padding
|
||||
from cryptography.hazmat.primitives.serialization import load_der_public_key
|
||||
pub = load_der_public_key(base64.b64decode(pubkey), default_backend())
|
||||
ct = pub.encrypt(pwd.encode(), padding.PKCS1v15())
|
||||
return base64.b64encode(ct).decode()
|
||||
|
||||
|
||||
def _api_login(username, password):
|
||||
"""接口登录(纯 requests,不弹浏览器)。成功返回 requests.Session,失败返回 None。
|
||||
|
||||
服务端行为(探针实测):
|
||||
- /login 页面内嵌固定 RSA 公钥(publicKey,1024 位 PKCS#1);
|
||||
- 验证码 4 位,GET /getvalidCode?type=cuserrorCode 返回图片(session 绑定);
|
||||
- POST /login 需带 Referer(外链校验),成功 302 到 /main。
|
||||
"""
|
||||
session = requests.Session()
|
||||
session.headers.update({"User-Agent": _UA})
|
||||
try:
|
||||
if len(password.encode()) > 117:
|
||||
# 页面公钥 1024 位,PKCS#1 v1.5 明文上限 117 字节;超长无法加密,
|
||||
# 明确提示后走浏览器兜底登录
|
||||
config.log("[通联登录] 密码过长(>117 字节),接口登录无法加密,将回退浏览器登录")
|
||||
return None
|
||||
html = session.get(config.LOGIN_URL, timeout=20).text
|
||||
m = _PUBKEY_RE.search(html)
|
||||
if not m:
|
||||
config.log("[通联登录] 接口登录失败:未找到 publicKey")
|
||||
return None
|
||||
pubkey = m.group(1)
|
||||
enc = _rsa_encrypt(pubkey, password)
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 接口登录准备异常:{e}")
|
||||
return None
|
||||
|
||||
ocr = _get_ocr()
|
||||
for attempt in range(config.API_CAPTCHA_RETRY):
|
||||
try:
|
||||
img = session.get(_VALIDCODE_URL, timeout=20).content
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 获取验证码图异常:{e}")
|
||||
return None
|
||||
code = ocr.classification(img).strip()
|
||||
config.log(f"[通联登录] 接口登录 第 {attempt + 1}/{config.API_CAPTCHA_RETRY} 次验证码识别:{code!r}")
|
||||
if len(code) != 4:
|
||||
time.sleep(1)
|
||||
continue
|
||||
try:
|
||||
resp = session.post(config.LOGIN_URL, data={
|
||||
'userid': username,
|
||||
'encpassword': enc,
|
||||
'cuserrorCode': code,
|
||||
}, headers={'Referer': config.LOGIN_URL}, timeout=20, allow_redirects=True)
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 提交登录异常:{e}")
|
||||
return None
|
||||
if '/login' not in resp.url:
|
||||
config.log(f"[通联登录] 接口登录成功:{resp.url}")
|
||||
return session
|
||||
# 仍在登录页:验证码错/账号密码错/风控。每次提交都计入服务端尝试次数,
|
||||
# 失败后退避并停止(不连续重试,避免触发登录次数风控锁定)
|
||||
hit = re.search(r'验证码错误|验证码不正确|账号或密码|密码错误|登录失败|次数已达上限|锁定', resp.text)
|
||||
if hit:
|
||||
config.log(f"[通联登录] 服务端提示:{hit.group(0)}")
|
||||
if '次数已达上限' in hit.group(0) or '锁定' in hit.group(0):
|
||||
config.log("[通联登录] 检测到风控锁定提示,立即停止登录尝试")
|
||||
return None
|
||||
time.sleep(config.LOGIN_FAIL_BACKOFF)
|
||||
config.log("[通联登录] 接口登录验证码多次未通过,停止重试")
|
||||
return None
|
||||
|
||||
|
||||
def _on_target(page):
|
||||
"""登录成功判定:URL 离开 /login。"""
|
||||
try:
|
||||
return '/login' not in (page.url or '')
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _find_input(page, selectors):
|
||||
for sel in selectors:
|
||||
ele = page.ele(sel, timeout=2)
|
||||
if ele:
|
||||
return ele
|
||||
return None
|
||||
|
||||
|
||||
def _find_captcha(page):
|
||||
"""定位验证码输入框 + 图片(从 #captcha 容器向上找,避免命中验证码登录 tab 的图)。"""
|
||||
code_input = page.ele('#captcha', timeout=config.TIMEOUT)
|
||||
img = None
|
||||
if code_input:
|
||||
holder = code_input.parent(1) # div.input-group#captcha_div
|
||||
if holder:
|
||||
img = holder.ele('tag:img', timeout=1)
|
||||
if img is None:
|
||||
img = page.ele('css:.tab-pane.active img[src*="getvalidCode"]', timeout=2)
|
||||
return img, code_input
|
||||
|
||||
|
||||
def _read_img_bytes(img):
|
||||
"""URL 型验证码(/getvalidCode)直接元素截图;兼容 base64 内嵌 src。"""
|
||||
try:
|
||||
src = img.attr('src') or ''
|
||||
if 'base64,' in src:
|
||||
return base64.b64decode(src.split('base64,', 1)[1])
|
||||
except Exception:
|
||||
pass
|
||||
return img.get_screenshot(as_bytes='png')
|
||||
|
||||
|
||||
def _recognize_captcha(img_bytes):
|
||||
"""ddddocr 识别图形验证码,返回文本。懒加载避免无关场景导入开销。"""
|
||||
import ddddocr
|
||||
ocr = ddddocr.DdddOcr(show_ad=False)
|
||||
return ocr.classification(img_bytes).strip()
|
||||
|
||||
|
||||
def _refresh_captcha(page, img):
|
||||
"""点击验证码图片刷新(onclick=cusjsUtil.changeCode)。URL 型验证码无法可靠比对,点击后等渲染。"""
|
||||
for _ in range(2):
|
||||
try:
|
||||
img.click()
|
||||
except Exception:
|
||||
try:
|
||||
img.click(by_js=True)
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.8)
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def _ensure_account_tab(page):
|
||||
"""确保「账号登录」tab 激活(默认激活;若页面记住验证码登录则切回)。"""
|
||||
uid = page.ele('#userid', timeout=2)
|
||||
if uid:
|
||||
try:
|
||||
if uid.states.is_displayed:
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
tab_btn = page.ele('css:a[href="#account"], css:a[data-target="#account"]', timeout=3) \
|
||||
or page.ele('tag:a@@text():账号登录', timeout=3)
|
||||
if tab_btn:
|
||||
try:
|
||||
tab_btn.click()
|
||||
time.sleep(0.5)
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
|
||||
|
||||
def _wait_login_result(page):
|
||||
"""提交后轮询判定登录结果,返回 bool。"""
|
||||
for _ in range(30): # 最多等 15 秒
|
||||
time.sleep(0.5)
|
||||
if _on_target(page):
|
||||
config.log(f"[通联登录] 登录成功:{page.url}")
|
||||
return True
|
||||
for sel in ('css:.invalid-feedback', 'css:.alert-danger', 'css:.toast'):
|
||||
try:
|
||||
eles = page.eles(sel, timeout=0.3)
|
||||
except Exception:
|
||||
continue
|
||||
for ele in eles:
|
||||
try:
|
||||
text = ele.text.strip()
|
||||
except Exception:
|
||||
text = ''
|
||||
if text:
|
||||
config.log(f"[通联登录] 失败提示:{text}")
|
||||
return False
|
||||
return False
|
||||
|
||||
|
||||
def _input_value(ele):
|
||||
"""读取输入框当前值(页面刷新后表单清空,用于判断是否需要重填)。"""
|
||||
try:
|
||||
return ele.value or ''
|
||||
except Exception:
|
||||
try:
|
||||
return ele.attr('value') or ''
|
||||
except Exception:
|
||||
return ''
|
||||
|
||||
|
||||
def _fill_account(page, username, password):
|
||||
"""确保账号密码已填(每轮提交前调用)。
|
||||
|
||||
通联登录失败后页面会整页刷新、表单被清空;这里做幂等填充——
|
||||
账号/密码已存在则跳过,被清空则重新输入,避免后续重试提交空表单。
|
||||
"""
|
||||
user_input = page.ele('#userid', timeout=config.TIMEOUT)
|
||||
if not user_input:
|
||||
config.log("[通联登录] 找不到账号输入框")
|
||||
return False
|
||||
if _input_value(user_input) != username:
|
||||
user_input.clear()
|
||||
user_input.input(username)
|
||||
_human_pause()
|
||||
|
||||
pwd_input = _find_input(page, ['#password', 'css:input[type="password"]:not([name="encpassword"])'])
|
||||
if not pwd_input:
|
||||
config.log("[通联登录] 找不到密码输入框")
|
||||
return False
|
||||
if not _input_value(pwd_input):
|
||||
pwd_input.click() # 触发 onfocus 移除 readonly
|
||||
_human_pause(0.2, 0.5)
|
||||
pwd_input.clear()
|
||||
pwd_input.input(password)
|
||||
_human_pause()
|
||||
return True
|
||||
|
||||
|
||||
def _try_login_once(page, username, password):
|
||||
"""完成一次填表 + 验证码 + 提交,返回 bool。
|
||||
每轮提交前都会确保账号密码已填(页面刷新后自动重填)。"""
|
||||
_ensure_account_tab(page)
|
||||
|
||||
for attempt in range(config.CAPTCHA_RETRY):
|
||||
if not _fill_account(page, username, password):
|
||||
return False
|
||||
config.log(f"[通联登录] 第 {attempt + 1}/{config.CAPTCHA_RETRY} 次验证码识别")
|
||||
img, code_input = _find_captcha(page)
|
||||
if not img or not code_input:
|
||||
config.log("[通联登录] 找不到验证码图片或输入框")
|
||||
return False
|
||||
img_bytes = _read_img_bytes(img)
|
||||
if not img_bytes:
|
||||
time.sleep(1)
|
||||
continue
|
||||
try:
|
||||
code = _recognize_captcha(img_bytes)
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] ddddocr 识别异常:{e}")
|
||||
return False
|
||||
config.log(f"[通联登录] 识别结果:{code!r}")
|
||||
if not code:
|
||||
_refresh_captcha(page, img)
|
||||
continue
|
||||
code_input.click() # 触发 onfocus 移除 readonly
|
||||
code_input.clear()
|
||||
code_input.input(code)
|
||||
_human_pause(0.3, 0.9)
|
||||
|
||||
btn = page.ele('css:.tab-pane.active button[onclick*="valandsubmit"]', timeout=config.TIMEOUT) \
|
||||
or page.ele('tag:button@@text():登录', timeout=config.TIMEOUT)
|
||||
if not btn:
|
||||
config.log("[通联登录] 找不到登录提交按钮")
|
||||
return False
|
||||
_human_pause(0.2, 0.6)
|
||||
btn.click()
|
||||
|
||||
if _wait_login_result(page):
|
||||
return True
|
||||
_refresh_captcha(page, img)
|
||||
return False
|
||||
|
||||
|
||||
def _build_session(page):
|
||||
"""从浏览器 cookies 构建 requests.Session(仅保留 allinpay.com 域)。"""
|
||||
session = requests.Session()
|
||||
session.headers.update({"User-Agent": _UA})
|
||||
try:
|
||||
for c in page.cookies():
|
||||
domain = (c.get('domain') or '')
|
||||
if 'allinpay.com' not in domain:
|
||||
continue
|
||||
session.cookies.set(c['name'], c['value'],
|
||||
domain=domain.lstrip('.'), path=c.get('path', '/'))
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 提取 cookies 异常:{e}")
|
||||
return session
|
||||
|
||||
|
||||
# ==================== 会话落盘复用(跨 run,子进程隔离下也生效) ====================
|
||||
def _dump_cookies(session):
|
||||
"""把 requests.Session 的 cookies 序列化为可持久化列表。"""
|
||||
out = []
|
||||
for c in session.cookies:
|
||||
out.append({'name': c.name, 'value': c.value, 'domain': c.domain or '',
|
||||
'path': c.path or '/'})
|
||||
return out
|
||||
|
||||
|
||||
def save_session(username, session):
|
||||
"""登录成功后把会话 cookies 落盘,供下次运行直接复用。失败不影响本次执行。"""
|
||||
try:
|
||||
data = {'username': username, 'cookies': _dump_cookies(session)}
|
||||
with open(config.get_session_file(), 'w', encoding='utf-8') as f:
|
||||
json.dump(data, f, ensure_ascii=False)
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 保存会话失败(不影响本次执行):{e}")
|
||||
|
||||
|
||||
def _session_valid(session):
|
||||
"""会话探活:GET 首页,未落回 /login 且页面内容不含登录表单即视为有效。
|
||||
|
||||
平台为单点登录(多地互斥):一旦其它设备/浏览器用同一账号重新登录,
|
||||
本会话立即失效。此时 main.dsr 仍返回 200,但页面内容是登录表单
|
||||
(<form id="accountForm" action="/login">)而非业务首页——仅看 URL 会误判
|
||||
为有效,导致后续 API 全部失败,必须校验页面内容。
|
||||
"""
|
||||
try:
|
||||
resp = session.get(config.MAIN_URL, headers=config.SEARCH_HEADERS,
|
||||
timeout=15, allow_redirects=True)
|
||||
if resp.status_code != 200 or '/login' in resp.url:
|
||||
return False
|
||||
return not _LOGIN_FORM_RE.search(resp.text)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def load_session(username):
|
||||
"""读取并重建上次登录会话;有效则返回 requests.Session,否则返回 None。"""
|
||||
path = config.get_session_file()
|
||||
try:
|
||||
with open(path, 'r', encoding='utf-8') as f:
|
||||
data = json.load(f)
|
||||
if data.get('username') != username:
|
||||
config.log("[通联登录] 本地会话账号与当前账号不一致,重新登录")
|
||||
return None
|
||||
session = requests.Session()
|
||||
session.headers.update({"User-Agent": _UA})
|
||||
for c in data.get('cookies') or []:
|
||||
session.cookies.set(c['name'], c['value'],
|
||||
domain=c['domain'] or '', path=c['path'] or '/')
|
||||
if _session_valid(session):
|
||||
return session
|
||||
config.log("[通联登录] 本地会话已失效,重新登录")
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 读取本地会话异常:{e}")
|
||||
return None
|
||||
|
||||
|
||||
def tl_login(username, password):
|
||||
"""通联平台登录(本地会话复用 → 接口登录 → 浏览器兜底)。
|
||||
|
||||
成功返回 requests.Session,失败返回 None。登录成功后会话 cookies 落盘,
|
||||
下次运行直接复用免登录(探活失败才重新登录)。
|
||||
"""
|
||||
username = (username or '').strip()
|
||||
password = password or ''
|
||||
if not (username and password):
|
||||
config.log("[通联登录] 账号/密码缺失(请在插件界面填写并保存配置)")
|
||||
return None
|
||||
|
||||
# 1) 复用本地已保存会话(免重新登录)
|
||||
session = load_session(username)
|
||||
if session is not None:
|
||||
config.log("[通联登录] 复用本地已登录会话,免重新登录(单点登录:请勿同时在其")
|
||||
config.log("[通联登录] 它设备/浏览器登录同一账号,否则本会话会被踢下线)")
|
||||
return session
|
||||
|
||||
# 2) 接口登录(首选,不弹浏览器)
|
||||
config.log("[通联登录] 本地会话失效,开始重新登录(单点登录:本次登录会顶掉其它")
|
||||
config.log("[通联登录] 设备/浏览器上的同一账号登录)")
|
||||
session = _api_login(username, password)
|
||||
if session is not None:
|
||||
save_session(username, session)
|
||||
return session
|
||||
config.log("[通联登录] 接口登录未成功,回退浏览器登录")
|
||||
# 3) 浏览器兜底
|
||||
session = _browser_login(username, password)
|
||||
if session is not None:
|
||||
save_session(username, session)
|
||||
return session
|
||||
|
||||
|
||||
def _browser_login(username, password):
|
||||
"""浏览器兜底登录(DrissionPage + ddddocr 图形验证码,元素截图)。
|
||||
|
||||
返回:成功 → requests.Session(从浏览器 cookies 构建);失败 → None。
|
||||
固定默认用户目录保留登录态:已登录会话直接复用(免验证码)。
|
||||
调用方使用完毕无需额外操作(本函数已 page.quit())。
|
||||
"""
|
||||
co = ChromiumOptions()
|
||||
co.set_argument('--start-maximized')
|
||||
co.set_pref('credentials_enable_service', False)
|
||||
co.set_pref('profile.password_manager_enabled', False)
|
||||
# 独立固定用户目录(%LOCALAPPDATA% 下,非临时目录):登录态跨次保留免验证码,
|
||||
# 且不占用用户日常 Chrome 配置、不被系统磁盘清理清掉
|
||||
co.set_user_data_path(config.get_browser_profile_dir())
|
||||
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
page = None
|
||||
try:
|
||||
config.log(f"[通联登录] 浏览器登录 第 {attempt}/{config.RETRY_MAX} 次 → {config.LOGIN_URL}")
|
||||
page = ChromiumPage(co)
|
||||
page.get(config.LOGIN_URL)
|
||||
_human_pause(1.0, 2.0)
|
||||
|
||||
if _on_target(page):
|
||||
config.log(f"[通联登录] 检测到已登录会话,直接复用:{page.url}")
|
||||
session = _build_session(page)
|
||||
page.quit()
|
||||
return session
|
||||
|
||||
if _try_login_once(page, username, password):
|
||||
config.log(f"[通联登录] 登录成功 → {page.url}")
|
||||
session = _build_session(page)
|
||||
page.quit()
|
||||
return session
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 异常:{e}")
|
||||
if page is not None:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
config.log("[通联登录] 浏览器登录重试多次均失败")
|
||||
return None
|
||||
@@ -0,0 +1,69 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0045_xq0046",
|
||||
"name": "金色印象通联数据导出",
|
||||
"version": "1.0.5",
|
||||
"description": "通联支付商户服务平台(cus.allinpay.com)交易数据自动导出:XQ0045 按日、XQ0046 按月,账号全量数据导出(含全部商户),服务端生成文件直存本地",
|
||||
"category": "报表",
|
||||
"icon": "",
|
||||
"platform": "",
|
||||
"uses_month": false,
|
||||
"ui": true,
|
||||
"capabilities": ["xq0045_xq0046"],
|
||||
"permissions": {
|
||||
"platforms": []
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"mode": {
|
||||
"type": "string",
|
||||
"title": "执行模式",
|
||||
"default": "日+月",
|
||||
"enum": ["日", "月", "日+月"],
|
||||
"description": "日/月/日+月:决定日期选择器粒度;交易查询与账单导出共用日期选择器,插件内部自动换算各自区间"
|
||||
},
|
||||
"content": {
|
||||
"type": "string",
|
||||
"title": "导出内容",
|
||||
"default": "两个都导",
|
||||
"enum": ["两个都导", "交易查询", "账单"],
|
||||
"description": "交易查询=逐商户导交易明细(xlsx);账单=主账号日/月账单(zip 下载并解压)"
|
||||
},
|
||||
"day_date": {
|
||||
"type": "string",
|
||||
"format": "date",
|
||||
"title": "按日导出",
|
||||
"default": "",
|
||||
"description": "默认昨天;交易查询区间 = 所选日 00:00 ~ 次日 24:00;账单 = 所选日账单"
|
||||
},
|
||||
"month_date": {
|
||||
"type": "string",
|
||||
"format": "month",
|
||||
"title": "按月导出",
|
||||
"default": "",
|
||||
"description": "默认上月;交易查询区间 = 当月1日 10:00 ~ 下月1日 10:00(对账10点切日);账单 = 该月账单"
|
||||
},
|
||||
"tl_username": {
|
||||
"type": "string",
|
||||
"title": "通联登录账号",
|
||||
"default": "",
|
||||
"description": "商户服务平台登录账号(保存在本机,下次免填)"
|
||||
},
|
||||
"tl_password": {
|
||||
"type": "string",
|
||||
"title": "通联登录密码",
|
||||
"default": "",
|
||||
"format": "password",
|
||||
"description": "仅保存在本机(%LOCALAPPDATA%\\37duAutomation\\plugin_configs),下次免填"
|
||||
},
|
||||
"save_dir": {
|
||||
"type": "string",
|
||||
"title": "保存目录",
|
||||
"default": "",
|
||||
"description": "留空=桌面/金色印象通联数据_YYYYMMDD;交易查询每日期一份全量文件(日_日期.xlsx / 月_月份.xlsx),账单按 账单_YYYYMM 目录存放"
|
||||
}
|
||||
},
|
||||
"required": ["tl_username", "tl_password"]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
DrissionPage>=4.1
|
||||
requests>=2.28
|
||||
ddddocr>=1.4
|
||||
cryptography>=39.0
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,13 @@
|
||||
<!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/xq0045_xq0046/assets/index-CuUBZGG_.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0045_xq0046/assets/index-CmyoQ4x2.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
+487
@@ -0,0 +1,487 @@
|
||||
# 桌面客户端 v2.0 联合方案(Electron 壳 + 服务端重构 + 插件契约稳定)
|
||||
|
||||
> 版本:v2.0 Final(重写自 v1.2)
|
||||
> 定位:**换壳不换插件、趁人少修服务端**。客户端从 Python/PyWebView 底座替换为 Electron 壳,中心机服务端同步重构(修前期债),插件体系作为稳定契约层原样保留。
|
||||
> 技术栈:Electron 30 + Vue3 + Node.js + WebSocket(仅中心机变更通知)+ Electron IPC(本地事件)
|
||||
> 适用场景:公司内网/公网混合、部分同事使用、纯中文环境
|
||||
> 本文依据:desktop/controlplane 与 desktop/webhost 全量代码体检(2026 年当前代码基线,控制面已迁 MySQL)
|
||||
|
||||
---
|
||||
|
||||
## 〇、v2.0 相对 v1.2 的根本变化
|
||||
|
||||
| 维度 | v1.2(旧设计) | v2.0(本方案) |
|
||||
|---|---|---|
|
||||
| 定位 | 从零重写一套"插件工作台" | **换壳不换插件**:Electron 替换 PyWebView 底座,复用全部现有契约 |
|
||||
| 插件元数据 | 自造 manifest.json / main.py | **复用现有 plugin.json / plugin_runner 执行协议**,插件代码零改动 |
|
||||
| 插件依赖 | 声称"环境统一,移除 dependencies" | 环境包 = **runner 运行时 + 插件 requirements 依赖**,依赖真实存在 |
|
||||
| WebSocket | 客户端↔中心机"心跳/重连/日志" | **仅中心机变更通知**(插件/壳子/权限/配置推送);日志进度走本地 IPC |
|
||||
| 服务端 | 未提 | **同步重构**:修 P0/P1 安全与稳定债 + 新增 WS 通知端点,契约层不动 |
|
||||
| 排期 | 16.5 周(从零估) | **约 6-9 周**(契约移植 + 修债 + 联调) |
|
||||
|
||||
---
|
||||
|
||||
## 一、方案总览与核心决策
|
||||
|
||||
### 1.1 范围三角
|
||||
|
||||
| 方向 | 动作 | 理由 |
|
||||
|---|---|---|
|
||||
| **客户端壳子** | Python/PyWebView → **Electron 壳**(重写壳,移植契约) | 体验差(窗口/托盘/通知/UI),换壳 |
|
||||
| **中心机服务端** | **趁人少重构**(修债 + 接口规范化 + 新增 WS 通知) | 前期 P0/P1 问题多,后期人多了改不起 |
|
||||
| **插件体系** | **保持稳定、尽量不动** | 几十个已上线插件 + plugin.json 规范 + 发布链路全绑定,动一处伤一片 |
|
||||
|
||||
### 1.2 三条核心决策
|
||||
|
||||
1. **契约层定死不动**:插件执行协议(`plugin_runner` 的 argv/stdin/stdout/cookie)、插件同步(白名单/download-ticket/sha256)、`plugin.json` 字段、`xq{单号}` id 规则、schedules/plugin_configs 数据格式——重构只改实现、不改契约。
|
||||
2. **Electron 壳保留 8799 本地 HTTP 兼容层**:`/auth/done`(钉钉回调,端口+路径编码在控制面授权 URL 里)、`/pui/<id>/`(插件 UI,vite base 约定)、`/api/*`(插件 iframe 同源调用)必须原路径保留;渲染进程主通道走 IPC,HTTP 层只做兼容。
|
||||
3. **服务端重构 = 修债 + WS 通知,契约稳定**:体检 P0/P1 全量修掉,新增 `/ws/notify` 变更通知端点;对外接口路径与返回结构不变(向后兼容旧契约,前端可平滑迁移)。
|
||||
|
||||
### 1.3 分期路线图(总览)
|
||||
|
||||
| 阶段 | 内容 | 工期(1 人) |
|
||||
|---|---|---|
|
||||
| **P1 服务端重构** | 修 P0/P1 债 + 接口规范化 + `/ws/notify` 变更通知 | 1.5-2 周 |
|
||||
| **P2 Electron 壳** | 按契约表逐项移植 + 联调(登录/插件执行/同步/定时/更新/通知) | 4-5 周 |
|
||||
| **P3 切换** | 并行灰度 + 回退窗口 + 旧壳下线 | 0.5-1 周 |
|
||||
| 合计 | | **约 6-8 周** |
|
||||
|
||||
> P1 期间现有 Python 底座照常使用(契约未变,两端兼容);P2 期间新旧壳并行,同一契约互不干扰。
|
||||
|
||||
---
|
||||
|
||||
## 二、现状基线(已核实,代码为准)
|
||||
|
||||
### 2.1 中心机 controlplane(后端,本次重构对象)
|
||||
|
||||
- **技术栈**:FastAPI + **MySQL**(15 张表,PyMySQL,库 37du_center;`controlplane.db` 仅为历史迁移源,[db.py](desktop/controlplane/core/db.py))
|
||||
- **已实现能力**(重构时作为存量资产保留):
|
||||
- Ed25519 离线授权票据 `/api/me/license`、管控清单 `/api/me/control-list`
|
||||
- 一次性下载票据 `/api/plugins/{id}/versions/{v}/download-ticket` + `/api/download/{ticket}`(**已落库**,解决 gunicorn 多 worker 踩坑)
|
||||
- 云令牌 `cloud_tokens` 落库共享(多 worker 通用)、登录防爆破、管理员 HMAC 签名票据
|
||||
- 运行上报 `/api/runtime/report`、设备心跳 `/api/device/report`
|
||||
- 壳子版本源 `/api/shell/version`、`/api/shell/pkg`(file_sources 表 + shell/version.json 双源)
|
||||
- 敏感凭证 RSA 下发(creds/register、creds)、定时任务备份(schedules/backup)、审计、钉钉 OAuth
|
||||
- **54 个路由**,身份三源(Bearer 云令牌 / X-Admin-Token / X-Admin-User+X-API-Token)
|
||||
|
||||
### 2.2 执行机底座 webhost(客户端,本次替换对象)
|
||||
|
||||
- **技术栈**:FastAPI 监听 `127.0.0.1:8799`,PyWebView(WebView2) 窗口加载该 URL,前端 Vue3
|
||||
- **已实现能力**(Electron 壳需按契约 1:1 移植):
|
||||
- 插件执行:`spawn python plugin_runner.py --plugin --run --allowed`,stdin 单行 JSON fields,stdout JSON 事件行,stderr 诊断通道,Job Object 整树托管 + 超时强杀 + 内存上限
|
||||
- 插件同步:白名单 → download-ticket → sha256 → 原子替换到 `plugins/<id>/`
|
||||
- 定时任务:schedules.json + 5 段 cron + 中心机备份/恢复
|
||||
- 壳子自更新:`/api/shell/version` 比对 → 流式下载 → sha256 → Inno 静默升级
|
||||
- 平台登录态:shared/hr_login.py、oa_login.py(DrissionPage 自动化),cookie 共享 `.sessions/`
|
||||
- 插件配置 `/api/plugin-config/<id>` + `/pui/<id>/` UI 托管
|
||||
- 统一会话 cp_session cookie、`/_cp_call` 中心机代理、license/control-list 离线门禁
|
||||
|
||||
### 2.3 关键结论
|
||||
|
||||
- **90% 的"设计"已经存在且在生产运行**。Electron 壳不是从零开发,而是**用 Node 重实现现有契约 + 换 UI 壳**;服务端重构是**在现有实现上修债**,不是推倒重来。
|
||||
- 换壳的破坏面集中在:插件子进程协议(★)、跨端共享文件(cookie/插件目录/schedules/plugin_configs/授权票据)、钉钉回调端口路径——这三类必须逐字节兼容,其余可重新实现。
|
||||
|
||||
---
|
||||
|
||||
## 三、稳定契约层(两端均不得破坏)
|
||||
|
||||
> 这些契约是插件、已上线数据、外部系统(钉钉/平台/文件服务器)的绑定面。重构与换壳期间**只改实现,不改契约**;如需扩展(如 minRuntimeVersion),以**可选新增字段**形式向后兼容。
|
||||
|
||||
| # | 契约 | 绑定面 | 兼容级别 |
|
||||
|---|---|---|---|
|
||||
| 1 | 插件执行协议(argv/stdin/stdout/stderr/env/超时/整树杀/退出码) | 全部已上线插件代码 | ★ 逐字节 |
|
||||
| 2 | `.sessions/<platform>_cookies.json` 路径+DrissionPage 格式 | 影刀版 / 插件子进程三方共享 | ★ |
|
||||
| 3 | 插件包布局 `plugins/<id>/` + `plugin.json` + 原子替换 | 离线运行 / 发布产物 dist-plugin/<id>_v<v>.zip | ★ |
|
||||
| 4 | `schedules.json` 结构 + cron 5 段语义 + 中心机 backup/restore | 用户已配置定时任务数据 | ★ |
|
||||
| 5 | `plugin_configs/<id>.json` + `/pui/<id>/` 托管规则 + `/api/plugin-config` | 插件 UI(按 /pui/<id>/ 构建并同源 fetch) | ★ |
|
||||
| 6 | RSA creds 密钥对/缓存格式(OAEP-SHA256) | `creds/id_rsa.pem`、cache.json | ★ |
|
||||
| 7 | 钉钉回调 `http://localhost:8799/auth/done` + state 机制 + cp_session | 控制面构造的授权 URL | ★ |
|
||||
| 8 | license.json / control.json / keys/pub.pem / offline_reports.jsonl + 7 天离线窗口 | 产品化门禁真源 | ★ |
|
||||
| 9 | 中心机 `_cp_call` 全契约(X-API-Token/Bearer/X-Admin-User 头规则) | 身份解析 | ◐ |
|
||||
| 10 | 壳子自更新消费契约(/api/shell/version、shell.version、缓存目录) | agent_cli file push 发布链 | ◐ |
|
||||
| 11 | 定时任务触发语义(dom/dow OR 规则、0/7 周日归一、30s tick 粒度) | 任务调度行为 | ◐ |
|
||||
|
||||
> ★ = 字节级兼容(改动即破坏插件/数据/登录);◐ = 结构兼容(实现可换,语义与格式不变)。
|
||||
|
||||
---
|
||||
|
||||
## 四、Electron 客户端壳设计
|
||||
|
||||
### 4.1 技术选型
|
||||
|
||||
| 层级 | 技术 | 版本 |
|
||||
|---|---|---|
|
||||
| 桌面壳 | Electron | 30+ |
|
||||
| 前端 | Vue3 + TypeScript + Pinia + Vue Router(hash) | 3.4+ |
|
||||
| UI | Element Plus | 2.x |
|
||||
| 构建/打包 | electron-vite / electron-builder(NSIS) | 2.x / 24+ |
|
||||
| 定时任务 | node-cron 或自实现 5 段解析(语义对齐 tasks.py) | 3.x |
|
||||
| 本地存储 | better-sqlite3(需 electron-rebuild)或 JSON 文件 | 11+ |
|
||||
| WS(中心机通知) | ws | 8.x |
|
||||
| HTTP(本地兼容层) | Node 内置 http + axios(出站) | — |
|
||||
| Python 执行 | child_process.spawn | 内置 |
|
||||
|
||||
### 4.2 总体架构
|
||||
|
||||
```
|
||||
┌────────────────────────── 中心机 controlplane(P1 重构后) ──────────────────────────┐
|
||||
│ FastAPI + MySQL(8800,公网 117.72.191.188) │
|
||||
│ ├─ 现有:登录/权限/插件分发/download-ticket/license/control-list/上报/壳子版本/creds │
|
||||
│ ├─ 修债:P0 管理密钥分离、口令治理、token 空拒启;P1 云令牌吊销/限流/审计/连接池 │
|
||||
│ └─ 新增:WS 变更通知端点 /ws/notify(publish/grant/revoke/file push/config 后广播) │
|
||||
└──────────────┬──────────────────────────────┬──────────────────────┘
|
||||
│ REST(权威数据,契约不变) │ WS(变更通知)
|
||||
┌──────────────▼──────────────────────────────▼──────────────────────┐
|
||||
│ Electron 壳(内网/本机) │
|
||||
│ │
|
||||
│ 主进程 (Node.js) │
|
||||
│ ├─ 本地 HTTP 兼容层 (127.0.0.1:8799) │
|
||||
│ │ /auth/done(钉钉回调) /pui/<id>/(插件UI) /api/*(iframe) │
|
||||
│ │ /ws(本机事件,可选) │
|
||||
│ ├─ 插件执行:spawn python plugin_runner(契约★) + 整树强杀 │
|
||||
│ ├─ 插件同步:白名单/download-ticket/sha256/原子替换 │
|
||||
│ ├─ 平台登录态:spawn Python 登录子进程(shared/hr_login 等) │
|
||||
│ ├─ 定时任务:schedules.json + 5段cron + 备份/恢复 │
|
||||
│ ├─ 壳子更新:/api/shell/version 比对 + 下载 + sha256 + 静默安装 │
|
||||
│ ├─ 变更通知:订阅中心机 /ws/notify → 触发同步/检查/重拉 │
|
||||
│ ├─ 系统:单实例锁 / 托盘 / 自启 / 通知 / 日志 / 崩溃恢复 │
|
||||
│ └─ 安全:路径白名单 / iframe 隔离 / 出站白名单 │
|
||||
│ │
|
||||
│ 渲染进程 (Vue3) │
|
||||
│ ├─ 登录页 / 插件列表 / 任务管理 / 设置面板 │
|
||||
│ └─ iframe 容器(插件配置页面,加载 /pui/<id>/) │
|
||||
│ │
|
||||
│ Python 运行时(随壳分发) │
|
||||
│ └─ 便携 Python + runner 运行时 + 插件依赖(环境包,版本化+回滚) │
|
||||
└──────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 4.3 模块设计(对照现有契约移植)
|
||||
|
||||
#### 4.3.1 本地 HTTP 兼容层 ★
|
||||
|
||||
**必须保留**(否则破坏插件 UI 与钉钉登录):
|
||||
|
||||
| 路径 | 用途 | 移植要点 |
|
||||
|---|---|---|
|
||||
| `GET /auth/done` | 钉钉扫码回跳 | 端口 8799 固定(编码在控制面 URL);state 5 分钟 TTL 防 CSRF;成功后 302 到渲染层 |
|
||||
| `GET /pui/<id>/` + 子路径 | 插件 UI 静态托管 | 根=`plugins/<id>/ui/`;防路径穿越;目录→index.html;缺失→SPA 兜底;缓存头 index.html no-cache、其余 max-age=86400 |
|
||||
| `GET/POST /api/plugin-config/<id>` | 插件 iframe 同源保存配置 | 整体保存、原子写、404 不泄露存在性 |
|
||||
| `GET /api/meta`、`/api/runs`、`/api/schedules` | 旧前端/插件兼容 | 返回结构与现状 1:1(渲染层主通道用 IPC,这些仅作兼容) |
|
||||
| `WS /ws` | 本机事件广播(可选) | payload 结构不变(`t/run_id/plugin_id/level/pct/ok/error`);渲染层主通道改 IPC,保留 /ws 供旧插件页消费 |
|
||||
|
||||
#### 4.3.2 插件执行(★ 逐字节兼容)
|
||||
|
||||
主进程复刻 [runner.py](desktop/webhost/backend/core/runner.py) 的完整执行链:
|
||||
|
||||
```
|
||||
spawn(python 或 runner-exe, ["-m","webhost.backend.core.plugin_runner" | exe路径,
|
||||
"--plugin", id, "--run", run_id, "--allowed", ",".join(sorted(ALLOWED))],
|
||||
{ cwd: 项目根/exe同级, env: {PYTHONIOENCODING:"utf-8", PYTHONUTF8:"1", ...},
|
||||
windowsHide: true })
|
||||
→ stdin 写单行 JSON fields(UTF-8 原始字节,ensure_ascii=false)→ close
|
||||
→ stdout 逐行 JSON 事件(ev: log/progress/result)→ 转发 IPC 给渲染层
|
||||
→ stderr 逐行 → 转发为 level=ERROR 日志
|
||||
→ 超时 RUN_TIMEOUT(1800s) → 整树强杀(Job Object / taskkill /T /F)→ 补 run_done
|
||||
→ 结束判定:result→ok 落 done/error;用户停止/超时/异常退出 三分支
|
||||
→ 每次结束:单活槽位回空闲 + 运行上报(联网实时/离线补报)
|
||||
```
|
||||
|
||||
- **整树终止**:Node 侧无内建 Job Object。推荐两个方案:
|
||||
- **方案 A(推荐,过渡期)**:继续用 `37du-host-runner.exe`(现成 onefile 执行壳,内置 winjob),Electron 只负责 spawn + 超时后 `taskkill /pid <pid> /T /F`;
|
||||
- **方案 B(目标态)**:环境包内含 plugin_runner.py + webhost.backend 运行时,spawn 环境包 python.exe,整树终止用 `taskkill /T /F` 或小型 Python helper 创建 Job Object。
|
||||
- **设备级单活**:主进程实现单活槽位(对齐 scheduler.py:active.json 同路径同格式 + 条件互斥),同平台命名空间串行(防 cookie 争抢)。
|
||||
- **手动停止**:登记停止标记 + 整树强杀;排队中停止不真正拉起。
|
||||
|
||||
#### 4.3.3 插件同步
|
||||
|
||||
复刻 [plugin_sync.py](desktop/webhost/backend/core/plugin_sync.py):
|
||||
|
||||
- 白名单:`GET {cp}/api/plugins?account=` 或 Bearer 云令牌 → 缓存 `plugin_allow.json`;**fail-closed**(无账号/离线无缓存=零权限)
|
||||
- 版本比对 → 落后则 `download-ticket` → `GET /api/download/{ticket}` → sha256 → 解压到临时目录(拒绝对路径/`..` 穿越、zip 根必须含 plugin.json)→ 删旧目录 → 原子替换
|
||||
- 清理:云端清单可达时删除本地不在清单的插件;离线不动本地;单插件失败跳过不阻断
|
||||
- 同步后刷新本地授权票据(license.json),保证新授插件立即可运行
|
||||
- SYNC_LOCK 串行(启动/登录/手动/WS 通知触发共用)
|
||||
|
||||
#### 4.3.4 平台登录态
|
||||
|
||||
- **保持 Python 子进程执行登录自动化**(shared/hr_login.py、oa_login.py,DrissionPage 浏览器 + 滑块),Electron **不重写登录逻辑**
|
||||
- 触发/登出门槛链复刻 meta.py:会话 → 插件存在 → license 有效(否则"授权已过期(最长离线 7 天)")→ 平台白名单(不可达 503 / 无权限 403)→ 拉起登录子进程
|
||||
- cookie 写入 `.sessions/<platform>_cookies.json`(与影刀版/插件子进程三方共享)
|
||||
- 凭证来源:`%LOCALAPPDATA%\37duAutomation\.env` 的 `hr_login_*`/`oa_login_*`(现状如此;`platform_accounts` 加密存储为文档意图,未实现,不在本次范围)
|
||||
|
||||
#### 4.3.5 插件配置与 UI
|
||||
|
||||
- `plugin_configs/<id>.json` 同路径同格式(`ensure_ascii=false, indent=2`,原子写)
|
||||
- `/pui/<id>/` 托管规则与缓存头 1:1(见 4.3.1)
|
||||
- 渲染层 iframe 容器加载 `/pui/<id>/`,同源 cookie 自动鉴权
|
||||
|
||||
#### 4.3.6 定时任务
|
||||
|
||||
- `schedules.json` 同路径同结构(`{schedules:[{id,name,account,plugin_id,fields,cron,enabled,last_run_at,...}]}`)
|
||||
- cron 解析:Node 自实现或 node-cron,**语义必须对齐** tasks.py(`分 时 日 月 周`;`*/n a-b a-b/n 逗号`;周日 0/7 归一;dom+dow 同时限制时"命中其一即可")
|
||||
- 触发:主进程 tick(30s 粒度),到点校验(run_check_allowed)→ 走同一 submit 链路
|
||||
- 备份/恢复:变更后异步 POST `/api/schedules/backup`;启动时 GET 合并恢复缺失任务(本地为真源)
|
||||
|
||||
#### 4.3.7 壳子自更新
|
||||
|
||||
- 消费 `GET {cp}/api/shell/version`(X-API-Token)→ `{available,version,filename,url,sha256,notes}`;url 非空走内网文件服务器直链,空则回退 `/api/shell/pkg`
|
||||
- 下载到 `%LOCALAPPDATA%\37duAutomation\shell\`(.part + sha256 校验 + os.replace)
|
||||
- 应用:静默安装 + 退出重启。**注意**:现为 Inno(`/VERYSILENT /SUPPRESSMSGBOXES /NORESTART`);Electron 若换 NSIS/electron-updater,需同步调整发布链(agent_cli `file push --category shell` 契约不变,产物类型变化需验证)
|
||||
- 周期检查 30 分钟;检查/下载独立锁
|
||||
|
||||
#### 4.3.8 变更通知(中心机 WS)
|
||||
|
||||
见第六节。
|
||||
|
||||
#### 4.3.9 认证与会话
|
||||
|
||||
- 会话持久化:Electron 可用自己的存储(safeStorage 加密),但保留"重启免登录"体验;`_cp_sessions.json` 格式不强制沿用(◐)
|
||||
- 出站头规则与 `_cp_call` 一致:`Authorization: Bearer <cloud_token>`(有则带)+ `X-Admin-User: account` + `X-API-Token`(配置时);timeout 30;≥400 → 异常透传
|
||||
- 钉钉登录两条链路:链接授权(/auth/done 回跳)与内嵌二维码(inline_qr + sns),AppSecret 只在中心机
|
||||
|
||||
#### 4.3.10 安全
|
||||
|
||||
| 项 | 做法 |
|
||||
|---|---|
|
||||
| 渲染进程 | contextIsolation 开、nodeIntegration 关、sandbox 开;仅 preload 暴露白名单 IPC |
|
||||
| iframe(插件 UI) | 仅允许加载 `/pui/<id>/`;拦截外跳;postMessage 白名单 |
|
||||
| 本地 HTTP 层 | 仅绑定 127.0.0.1;`/pui/` 路径穿越防护;静态 MIME 白名单 |
|
||||
| Python 子进程 | `--allowed` 白名单加载防越权 import;不注入 shell;环境变量最小化 |
|
||||
| 文件写入 | 插件包解压拒绝 `/` `..`;配置原子写;路径统一收敛到 userData |
|
||||
|
||||
### 4.4 目录结构(Electron 壳,独立方向,不跨目录 import)
|
||||
|
||||
```
|
||||
desktop/electron-shell/
|
||||
├── electron/
|
||||
│ ├── main.ts # 应用入口:单实例锁/托盘/窗口/生命周期
|
||||
│ ├── preload.ts # contextBridge 白名单 IPC
|
||||
│ ├── compat-http/ # 本地 8799 HTTP 兼容层
|
||||
│ │ ├── server.ts # http 服务:/auth/done /pui /api/plugin-config
|
||||
│ │ └── routes.ts
|
||||
│ ├── plugin/
|
||||
│ │ ├── executor.ts # spawn python plugin_runner(契约★)
|
||||
│ │ ├── sync.ts # 白名单/download-ticket/原子替换
|
||||
│ │ ├── registry.ts # plugin.json 解析/加载白名单
|
||||
│ │ └── scheduler.ts # 设备级单活 + 同平台命名空间串行
|
||||
│ ├── tasks/
|
||||
│ │ ├── cron.ts # 5 段 cron 解析(语义对齐 tasks.py)
|
||||
│ │ └── manager.ts # schedules.json + 备份/恢复
|
||||
│ ├── platform-auth/ # spawn 登录子进程(shared/hr_login 等)
|
||||
│ ├── update/
|
||||
│ │ ├── shell-updater.ts # 壳子版本比对/下载/sha256/静默安装
|
||||
│ │ └── chrome.ts # Chrome 检测/下载/安装(可简化)
|
||||
│ ├── notify/
|
||||
│ │ └── ws-client.ts # 中心机 /ws/notify 订阅 + 重连补偿
|
||||
│ ├── net/
|
||||
│ │ ├── cp-client.ts # _cp_call 等价(头规则一致)
|
||||
│ │ └── downloader.ts # 流式下载 + sha256
|
||||
│ ├── system/
|
||||
│ │ ├── tray.ts / autolaunch.ts / logger.ts / crash.ts
|
||||
│ └── ipc/handlers.ts
|
||||
├── src/ # 渲染进程(Vue3 + Pinia)
|
||||
├── python-runtime/ # 便携 Python 解释器(随壳)
|
||||
├── package.json
|
||||
├── electron-builder.yml
|
||||
└── vite.config.ts
|
||||
```
|
||||
|
||||
> 目录遵循 AGENTS.md 桌面端规范:作为 `desktop/` 下独立方向,与 controlplane/webhost 互不 import,可单独拷贝演进。**webhost 保留作为回退**(P3 前不删除)。
|
||||
|
||||
---
|
||||
|
||||
## 五、中心机服务端重构方案
|
||||
|
||||
> 输入:controlplane 全量代码体检(P0×3、P1×7、P2×9)。重构期间对外接口路径/返回结构不变(向后兼容)。
|
||||
|
||||
### 5.1 P0 必修(安全)
|
||||
|
||||
| # | 问题 | 现状 | 重构动作 |
|
||||
|---|---|---|---|
|
||||
| 1 | **管理密钥可伪造** | `_admin_secret()` 默认回退 = CONTROLPLANE_TOKEN(config.py:101),持共享 X-API-Token 的执行机可自签任意管理员票据 | 强制独立 `CONTROLPLANE_ADMIN_SECRET`,缺失则拒绝启动;提供轮换机制 |
|
||||
| 2 | **硬编码弱口令** | 种子管理员 puddy/123456(db.py:366);钉钉默认密码 123456(config.py:65);must_change_pwd 无服务端强制 | 移除种子弱口令(改为首次启动强制生成随机密码并打印一次);服务端强制 must_change_pwd 拦截;云令牌登录链路同步要求改密 |
|
||||
| 3 | **token 为空全放行** | CONTROLPLANE_TOKEN 空时 `_check_token` 全放行(auth.py:27-30),全部客户端接口无鉴权 | token 为空拒绝启动(或启动告警+只允许内网绑定);公网部署必须配置 |
|
||||
|
||||
### 5.2 P1 必修(稳定/安全)
|
||||
|
||||
| # | 问题 | 重构动作 |
|
||||
|---|---|---|
|
||||
| 1 | `/cb` 开放重定向 + 身份拼 URL(dingtalk.py:97-106) | 重定向白名单化;身份改一次性票据传递 |
|
||||
| 2 | 管理员校验缺 status(auth.py:60-73) | `_require_admin` 加 status 校验;停用即失效 |
|
||||
| 3 | 云令牌不校验账号状态/存在性(auth.py:136-154);删号后 plugins.py:22-26 视为"未停用" | 云令牌解析关联 accounts 校验 + 支持吊销;删号/停用立即失效 |
|
||||
| 4 | 防爆破进程内 dict(auth.py:97-114):多 worker 可绕过 + 可锁号 DoS | 共享计数(DB/Redis)+ 限流;锁号上限保护 |
|
||||
| 5 | 头像文件名目录穿越(admin.py:183) | 文件名白名单(仅允许服务端生成的 uuid)+ 大小上限 |
|
||||
| 6 | `/auth/exchange` is_admin 硬编码 False、exists 恒 True(apis/auth.py:178-180) | 改为真实查询;不存在账号不发令牌 |
|
||||
| 7 | 审计覆盖不一致(账号 CRUD/平台授权/插件发布/creds/file-sources 缺审计) | 统一审计:写操作全覆盖,抽公共 `_audit` 装饰器 |
|
||||
| 8 | 身份三源解析复制粘贴 6+ 处 | 抽 FastAPI dependency 统一解析 |
|
||||
| 9 | CORS `allow_origins=["*"]`(app.py:52) | 收敛为白名单(控制面前端 + 本机回环) |
|
||||
| 10 | DB 无连接池无超时;每请求多连接;urlopen 10s 无重试 | 连接池 + 连接超时 + 重试(对齐 AGENTS.md 重试 3 次);单请求单连接 |
|
||||
| 11 | 上传先整读后限长;shell-release 无大小上限 | 流式限长上传;shell 包上限(如 1GB) |
|
||||
|
||||
### 5.3 P2 清理(随重构顺手做)
|
||||
|
||||
- 删死表死列(chrome_releases、system_settings、plugin_versions.size_bytes、cloud_tokens.nickname、download_tickets.sha256)或补齐实现
|
||||
- 文档与代码对齐(架构设计_插件管理系统.md 的 PATCH/grants/manifest 与实际路由不符)
|
||||
- agent_cli 复用 core(签名算法双份 → 单份)
|
||||
- `/health` 收敛(当前泄露 MYSQL_HOST/库名)
|
||||
- 版本排序用 `_version_key`(当前 "1.10"<"1.9")
|
||||
- 26 处 bare except 分类治理(审计/通知/身份解析失败至少记日志)
|
||||
- 删除 `_seed` 占位 zip;runtime_reports/devices 保留期清理
|
||||
- 登录防爆破的进程内状态在重构后随共享计数方案一并替换
|
||||
|
||||
### 5.4 重构后目标接口(不变部分)
|
||||
|
||||
对外接口路径、方法、返回结构**全部保持现状**(见三、稳定契约层),客户端(新旧壳)零感知迁移。仅新增:
|
||||
|
||||
| 接口 | 方法 | 说明 |
|
||||
|---|---|---|
|
||||
| `/ws/notify` | WS | **新增**:变更通知端点(见第六节) |
|
||||
| `/api/notifications` | GET | 可选:长轮询兜底(WS 不可用时的降级通道,按 `since=` 返回增量事件) |
|
||||
|
||||
---
|
||||
|
||||
## 六、WS 变更通知设计(中心机新增后端能力)
|
||||
|
||||
### 6.1 定位
|
||||
|
||||
单向通知:**中心机 → 客户端**。权威数据永远走 REST,WS 只告诉客户端"某类东西变了",客户端收到后主动拉取。
|
||||
|
||||
### 6.2 事件类型
|
||||
|
||||
| 事件 | 触发点 | 客户端收到后的动作 |
|
||||
|---|---|---|
|
||||
| `plugin.updated` | agent_cli `publish`(新版本/新插件) | 后台触发插件同步(对比版本 → download-ticket → 更新) |
|
||||
| `plugin.revoked` | agent_cli `revoke` / 管理员下架/禁用/强制更新 | 触发同步(清本地/更新 control.json);正在执行的插件停止 |
|
||||
| `shell.updated` | agent_cli `file push --category shell` | 触发壳子版本检查 → 提示更新 |
|
||||
| `config.pushed` | 中心机 creds 更新 | 触发 creds_sync 重拉 |
|
||||
|
||||
事件体:`{"type":"plugin.updated","payload":{...}}`,只带变更提示,不含敏感数据。
|
||||
|
||||
### 6.3 服务端实现
|
||||
|
||||
- FastAPI WebSocket 端点 `/ws/notify`,连接鉴权用 X-API-Token(query/header);连接数少(个位数~几十),进程内广播即可
|
||||
- **部署注意**:控制面为 gunicorn 8800(宝塔),WS 需 uvicorn worker 或独立 WS 进程/端口;多 worker 下广播需共享(简单方案:Redis pub/sub 或独立 ws 端口进程)
|
||||
- 广播点:`agent_cli`(publish/grant/revoke/file push)内嵌发布调用;管理 API 写操作后触发
|
||||
|
||||
### 6.4 客户端(Electron 主进程)实现
|
||||
|
||||
- 单例连接 + ping/pong 心跳(公网经反代,空闲连接可能被断)
|
||||
- **重连补偿(比连接本身重要)**:断线重连成功后,无条件全量补偿:重新拉插件清单 + 壳子版本检查 + 授权票据刷新——断线期间错过的变更靠补偿兜住
|
||||
- WS 不可用(中心机不支持/被墙)→ 降级为 `GET /api/notifications?since=` 长轮询
|
||||
|
||||
---
|
||||
|
||||
## 七、Python 环境分发(沿用 v1.2 有价值部分,修正组成)
|
||||
|
||||
### 7.1 三层分发
|
||||
|
||||
| 组件 | 分发方式 | 更新频率 |
|
||||
|---|---|---|
|
||||
| **壳子**(Electron 安装包) | 内网/公网下载,含便携 Python 解释器 | 低 |
|
||||
| **Python 环境包** | 内网服务器,首次启动下载(几百 MB) | 中(依赖/运行时升级) |
|
||||
| **插件包** | 公网,随权限下发 | 高 |
|
||||
|
||||
### 7.2 环境包组成(v2.0 修正:不只是 pip 依赖)
|
||||
|
||||
```
|
||||
python-env-<version>/ # 版本化目录
|
||||
├── python.exe / python311.dll # 便携解释器
|
||||
├── Lib/site-packages/ # runner 运行时 + 插件依赖
|
||||
│ ├── webhost/backend/plugins/ # ← plugin_runner 契约所需(base.py 等)
|
||||
│ ├── webhost/backend/shared/ # ← 平台登录自动化(hr_login/oa_login)
|
||||
│ ├── webhost/backend/core/auth.py 等
|
||||
│ └── requests/pandas/openpyxl/drissionpage/... # 各插件 requirements 依赖
|
||||
└── webhost/backend/core/plugin_runner.py # 执行入口
|
||||
```
|
||||
|
||||
> 环境包 = **runner 运行时(webhost.backend 可执行子集)+ 插件依赖**。这与现有 `37du-host-runner.spec` 打包内容一致,只是从安装包里拆出来独立版本化。
|
||||
|
||||
### 7.3 版本绑定与回滚
|
||||
|
||||
- `plugin.json` **可选新增** `minRuntimeVersion`(旧插件无此字段不校验,向后兼容)
|
||||
- 客户端校验:插件声明的 minRuntimeVersion > 当前环境包版本 → 提示更新环境,后台下载,下次生效
|
||||
- 版本化目录 + 保留上一版回滚;`current.json` 指向当前版本
|
||||
- 下载 → SHA256 全量校验 → 解压 → 切 current.json;失败清理重试
|
||||
|
||||
### 7.4 明确不做的优化(沿用 v1.2 克制原则)
|
||||
|
||||
断点续传、后台静默下载、下载限流/并发控制、分阶段进度、解压格式改造(zstd/TAR)——内网秒级下载,1 分钟首次启动可接受。
|
||||
|
||||
---
|
||||
|
||||
## 八、分期路线图与切换策略
|
||||
|
||||
### 8.1 P1:服务端重构(1.5-2 周)
|
||||
|
||||
1. P0 三项(管理密钥分离、口令治理、token 空拒启)
|
||||
2. P1 十一项(/cb 白名单、admin status、云令牌吊销、共享限流、上传限制、审计统一、鉴权 dependency、CORS 白名单、连接池、重试)
|
||||
3. 新增 `/ws/notify` + 广播点 + `/api/notifications` 兜底
|
||||
4. 验证:现有 Python 底座全量回归(契约未变,应零感知)
|
||||
|
||||
### 8.2 P2:Electron 壳(4-5 周)
|
||||
|
||||
按 4.3 模块表逐项移植 + 联调:
|
||||
|
||||
- W1:工程骨架 + 单实例/托盘/窗口 + 本地 8799 兼容层(/auth/done、/pui、/api/plugin-config)+ 渲染层登录页
|
||||
- W2:插件执行(spawn 协议★ + 单活调度 + IPC 事件)+ 插件同步
|
||||
- W3:平台登录态子进程 + 定时任务 + 配置持久化
|
||||
- W4:壳子更新 + Chrome + 变更通知 WS + 重连补偿
|
||||
- W5:安全加固(contextIsolation/iframe/白名单)+ 体验打磨 + 端到端回归
|
||||
|
||||
### 8.3 P3:切换(0.5-1 周)
|
||||
|
||||
- 新旧壳并行(同一契约、同一数据目录,互不冲突):先内部灰度 → 部分同事试用 → 全量
|
||||
- `37du-host`(旧 Python 底座)保留一个回退窗口(建议 ≥ 1 个月);数据目录(schedules.json、plugin_configs、.sessions、plugins/)天然共用,回退零迁移
|
||||
- 旧壳下线后:删除 webhost 发版链路(可选保留源码归档)
|
||||
|
||||
### 8.4 风险与缓解
|
||||
|
||||
| 风险 | 缓解 |
|
||||
|---|---|
|
||||
| 插件子进程协议字节级偏差 | ★ 契约先行:以 plugin_runner.py 为唯一真源,P2 首周先跑通 W2 执行链路再往下做 |
|
||||
| 钉钉回调端口破坏 | 8799 端口固定保留;P2 首周验证 /auth/done 全链路 |
|
||||
| 服务端重构影响在产底座 | 契约不变 + P1 期间旧底座回归 + 灰度 |
|
||||
| WS 多 worker 广播 | 独立 WS 进程/端口或 Redis pub/sub;客户端重连补偿兜底 |
|
||||
| better-sqlite3 原生模块 | electron-rebuild 接入构建链;量小可退 JSON 文件 |
|
||||
|
||||
---
|
||||
|
||||
## 九、优化优先级(同 v1.2 精神,更新为 v2.0)
|
||||
|
||||
| 优先级 | 事项 | 理由 |
|
||||
|---|---|---|
|
||||
| **P0** | 服务端安全债(P0×3) | 公网可达,风险最高 |
|
||||
| **P0** | 插件执行稳定性(超时/崩溃/单活) | 日常使用,感知最强 |
|
||||
| **P0** | 契约兼容(8799 / spawn 协议 / 共享文件) | 换壳成败关键 |
|
||||
| **P1** | 变更通知 + 重连补偿 | 提升更新/权限时效 |
|
||||
| **P1** | 定时任务可靠性(备份/恢复) | 无人值守,出问题影响大 |
|
||||
| **P2** | 平台登录体验、Chrome 按需、性能监控 | 有用户量后再补 |
|
||||
|
||||
---
|
||||
|
||||
## 十、功能清单
|
||||
|
||||
### ✅ 保留(换壳移植)
|
||||
|
||||
| 模块 | 现状 → Electron 壳 |
|
||||
|---|---|
|
||||
| 登录 | 统一账号 + 钉钉扫码(/auth/done 保留)+ cp_session 会话 |
|
||||
| 权限 | 客户端无角色,服务端票据/清单即权限(license/control-list 原样沿用) |
|
||||
| 插件管理 | 加载/执行/启停/更新/回滚/同步(download-ticket 契约原样) |
|
||||
| 插件前端 | iframe 嵌入 /pui/<id>/ + 同源配置持久化 |
|
||||
| 定时任务 | schedules.json + cron + 中心机备份/恢复 |
|
||||
| 壳子自更新 | /api/shell/version + sha256 + 静默升级(安装器类型可选调整) |
|
||||
| 平台登录态 | Python 登录子进程 + 共享 .sessions cookie |
|
||||
| 离线可用 | license/control-list 缓存 + 离线执行 + 补报 |
|
||||
| 系统集成 | 单实例/自启/托盘/通知/日志/窗口状态/崩溃恢复 |
|
||||
|
||||
### ❌ 砍掉(相对 v1.2)
|
||||
|
||||
| 砍掉 | 原因 |
|
||||
|---|---|
|
||||
| 客户端↔中心机"心跳/日志" WS | 日志走本地 IPC;变更通知才是真需求(已重设计) |
|
||||
| manifest.json / main.py 新插件格式 | 复用现有 plugin.json / plugin_runner |
|
||||
| MySQL 服务端(v1.2 引入) | 现状已是 MySQL,属既有资产不是新增 |
|
||||
| 环境包断点续传/静默下载/限流/分阶段进度 | 内网秒级下载,不优化 |
|
||||
| "插件依赖声明移除" | 依赖真实存在,环境包承担而非移除 |
|
||||
Reference in New Issue
Block a user