发布(0.4.1): 优化分配性能与客服数据边界
修复分配页皮肤查询并发慢查询;客服导入账号严格限制为本人名下;分配概览改用真实归属数量;标题区展示版本并提示刷新。
This commit is contained in:
@@ -1,6 +1,6 @@
|
|||||||
# 直播账号运营后台
|
# 直播账号运营后台
|
||||||
|
|
||||||
斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.0)。
|
斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.1)。
|
||||||
|
|
||||||
## 能做什么
|
## 能做什么
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
[project]
|
[project]
|
||||||
name = "live-hub-py"
|
name = "live-hub-py"
|
||||||
version = "0.4.0"
|
version = "0.4.1"
|
||||||
description = "直播账号运营 Web 后台"
|
description = "直播账号运营 Web 后台"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
requires-python = ">=3.12,<3.13"
|
requires-python = ">=3.12,<3.13"
|
||||||
|
|||||||
@@ -113,6 +113,25 @@ class TestAssignFilter(_Base):
|
|||||||
|
|
||||||
assert self.names(assigned_user_id=self.other.id) == ["a-of-kf2"]
|
assert self.names(assigned_user_id=self.other.id) == ["a-of-kf2"]
|
||||||
|
|
||||||
|
def test_support_with_view_all_permission_still_only_sees_owned_accounts(self):
|
||||||
|
own = self.make_account("a-support-own", assigned_to=self.support.id)
|
||||||
|
self.make_account("a-support-other", assigned_to=self.other.id)
|
||||||
|
self.support.custom_permissions = [
|
||||||
|
"account:view_assigned",
|
||||||
|
"account:view_all",
|
||||||
|
]
|
||||||
|
self.session.commit()
|
||||||
|
|
||||||
|
result = list_accounts(
|
||||||
|
page=1,
|
||||||
|
page_size=50,
|
||||||
|
include_sensitive=False,
|
||||||
|
db=self.session,
|
||||||
|
current=self.support,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert [item.id for item in result["items"]] == [own.id]
|
||||||
|
|
||||||
def test_combines_with_tag(self):
|
def test_combines_with_tag(self):
|
||||||
"""综合筛选:归属 + 标签要**同时**生效,而不是后一个覆盖前一个。"""
|
"""综合筛选:归属 + 标签要**同时**生效,而不是后一个覆盖前一个。"""
|
||||||
self.make_account("tag-a-free", tag="10.1-测试")
|
self.make_account("tag-a-free", tag="10.1-测试")
|
||||||
@@ -142,7 +161,7 @@ class TestAssignablePool(_Base):
|
|||||||
"ap-valid",
|
"ap-valid",
|
||||||
]
|
]
|
||||||
|
|
||||||
def test_summary_counts_only_assignable(self):
|
def test_summary_counts_actual_assignment_not_only_fresh_ck(self):
|
||||||
self.make_account("as-valid", ck_check_status="valid")
|
self.make_account("as-valid", ck_check_status="valid")
|
||||||
self.make_account("as-invalid", ck_check_status="invalid")
|
self.make_account("as-invalid", ck_check_status="invalid")
|
||||||
self.make_account(
|
self.make_account(
|
||||||
@@ -156,13 +175,14 @@ class TestAssignablePool(_Base):
|
|||||||
|
|
||||||
summary = assignments_summary(db=self.session, current=self.admin)
|
summary = assignments_summary(db=self.session, current=self.admin)
|
||||||
|
|
||||||
assert summary["unassigned_count"] == 1
|
assert summary["unassigned_count"] == 2
|
||||||
assert summary["assigned_count"] == 1
|
assert summary["assigned_count"] == 2
|
||||||
assert summary["total_count"] == 2
|
assert summary["orphaned_count"] == 0
|
||||||
|
assert summary["total_count"] == 4
|
||||||
support = next(
|
support = next(
|
||||||
u for u in summary["support_users"] if u["id"] == self.support.id
|
u for u in summary["support_users"] if u["id"] == self.support.id
|
||||||
)
|
)
|
||||||
assert support["assigned_count"] == 1
|
assert support["assigned_count"] == 2
|
||||||
|
|
||||||
def test_all_matching_assignable_only_skips_invalid(self):
|
def test_all_matching_assignable_only_skips_invalid(self):
|
||||||
valid = self.make_account("am-valid", ck_check_status="valid")
|
valid = self.make_account("am-valid", ck_check_status="valid")
|
||||||
@@ -346,12 +366,15 @@ class TestAssignmentPools(_Base):
|
|||||||
)
|
)
|
||||||
self.session.add(inactive)
|
self.session.add(inactive)
|
||||||
self.session.commit()
|
self.session.commit()
|
||||||
|
self.make_account("inactive-support-account", assigned_to=inactive.id)
|
||||||
|
|
||||||
result = assignments_summary(db=self.session, current=self.admin)
|
result = assignments_summary(db=self.session, current=self.admin)
|
||||||
|
|
||||||
support_ids = {user["id"] for user in result["support_users"]}
|
support_ids = {user["id"] for user in result["support_users"]}
|
||||||
assert self.support.id in support_ids
|
assert self.support.id in support_ids
|
||||||
assert inactive.id not in support_ids
|
assert inactive.id not in support_ids
|
||||||
|
assert result["orphaned_count"] == 1
|
||||||
|
assert result["assigned_count"] == 0
|
||||||
|
|
||||||
def test_dispatch_rejects_inactive_support(self):
|
def test_dispatch_rejects_inactive_support(self):
|
||||||
inactive = User(
|
inactive = User(
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
"""应用版本与前端构建标识。"""
|
||||||
|
|
||||||
|
from web.backend.version import get_app_version, get_frontend_release_id
|
||||||
|
|
||||||
|
|
||||||
|
def test_frontend_release_id_combines_version_and_build_digest():
|
||||||
|
get_frontend_release_id.cache_clear()
|
||||||
|
|
||||||
|
version = get_app_version()
|
||||||
|
release_id = get_frontend_release_id()
|
||||||
|
|
||||||
|
assert release_id.startswith(f"{version}+")
|
||||||
|
digest = release_id.split("+", 1)[1]
|
||||||
|
assert digest == "source" or len(digest) == 12
|
||||||
@@ -10,6 +10,8 @@ from web.backend.models import Account, DouyuTask, DouyuWorkbenchAccount, User
|
|||||||
from web.backend.routers.douyu import (
|
from web.backend.routers.douyu import (
|
||||||
_split_task_scope_query,
|
_split_task_scope_query,
|
||||||
_visible_tasks_query,
|
_visible_tasks_query,
|
||||||
|
list_task_account_ids,
|
||||||
|
list_task_accounts,
|
||||||
list_tasks,
|
list_tasks,
|
||||||
)
|
)
|
||||||
from web.backend.services.douyu_service import (
|
from web.backend.services.douyu_service import (
|
||||||
@@ -372,6 +374,38 @@ def test_workbench_task_list_is_limited_to_selected_accounts(db):
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_support_with_view_all_permission_still_only_sees_own_import_pool(db):
|
||||||
|
support, _, _, _, tasks = _seed_tasks(db)
|
||||||
|
support.custom_permissions = [
|
||||||
|
"douyu:task",
|
||||||
|
"account:view_assigned",
|
||||||
|
"account:view_all",
|
||||||
|
]
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
expected_account_id = tasks["assigned_elite"].account_id
|
||||||
|
rows = list_task_accounts(
|
||||||
|
search="",
|
||||||
|
tag="",
|
||||||
|
ids="",
|
||||||
|
account_names="",
|
||||||
|
page=None,
|
||||||
|
page_size=100,
|
||||||
|
db=db,
|
||||||
|
current=support,
|
||||||
|
)
|
||||||
|
ids = list_task_account_ids(
|
||||||
|
search="",
|
||||||
|
tag="",
|
||||||
|
account_names="",
|
||||||
|
db=db,
|
||||||
|
current=support,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert [row.id for row in rows] == [expected_account_id]
|
||||||
|
assert ids["account_ids"] == [expected_account_id]
|
||||||
|
|
||||||
|
|
||||||
def test_empty_support_task_list_stays_empty(db):
|
def test_empty_support_task_list_stays_empty(db):
|
||||||
support = User(
|
support = User(
|
||||||
username="empty-task-support",
|
username="empty-task-support",
|
||||||
|
|||||||
@@ -381,7 +381,7 @@ wheels = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "live-hub-py"
|
name = "live-hub-py"
|
||||||
version = "0.4.0"
|
version = "0.4.1"
|
||||||
source = { editable = "." }
|
source = { editable = "." }
|
||||||
dependencies = [
|
dependencies = [
|
||||||
{ name = "alembic" },
|
{ name = "alembic" },
|
||||||
|
|||||||
+5
-2
@@ -41,7 +41,7 @@ from .routers import (
|
|||||||
)
|
)
|
||||||
from .schemas import AppInfo
|
from .schemas import AppInfo
|
||||||
from .session import SessionRenewalMiddleware
|
from .session import SessionRenewalMiddleware
|
||||||
from .version import get_app_version
|
from .version import get_app_version, get_frontend_release_id
|
||||||
|
|
||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
@@ -203,7 +203,10 @@ async def health():
|
|||||||
|
|
||||||
@app.get("/api/app-info", response_model=AppInfo)
|
@app.get("/api/app-info", response_model=AppInfo)
|
||||||
def app_info():
|
def app_info():
|
||||||
return AppInfo(version=get_app_version())
|
return AppInfo(
|
||||||
|
version=get_app_version(),
|
||||||
|
release_id=get_frontend_release_id(),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
# ---- 生产环境:serve 前端静态文件 ----
|
# ---- 生产环境:serve 前端静态文件 ----
|
||||||
|
|||||||
+109
-52
@@ -1,5 +1,7 @@
|
|||||||
import csv
|
import csv
|
||||||
import io
|
import io
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
from datetime import UTC, datetime
|
from datetime import UTC, datetime
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
@@ -88,11 +90,18 @@ from ..services.login_failure import classify_failure, failure_kind_label
|
|||||||
|
|
||||||
router = APIRouter(prefix="/api/accounts", tags=["账号管理"])
|
router = APIRouter(prefix="/api/accounts", tags=["账号管理"])
|
||||||
|
|
||||||
|
_ASSIGNMENT_SKIN_CACHE_SECONDS = 60.0
|
||||||
|
_assignment_skin_cache_lock = threading.Lock()
|
||||||
|
_assignment_skin_cache: tuple[float, int, list[dict[str, Any]]] | None = None
|
||||||
|
|
||||||
|
|
||||||
def _visible_accounts_query(db: Session, current: User):
|
def _visible_accounts_query(db: Session, current: User):
|
||||||
"""返回当前用户可见的斗鱼账号查询。"""
|
"""返回当前用户可见的斗鱼账号查询。"""
|
||||||
query = db.query(Account)
|
query = db.query(Account)
|
||||||
if user_has_permission(current, "account:view_all"):
|
if (
|
||||||
|
current.role != "support"
|
||||||
|
and user_has_permission(current, "account:view_all")
|
||||||
|
):
|
||||||
return query
|
return query
|
||||||
if user_has_permission(current, "account:view_assigned"):
|
if user_has_permission(current, "account:view_assigned"):
|
||||||
return query.filter(Account.assigned_to == current.id)
|
return query.filter(Account.assigned_to == current.id)
|
||||||
@@ -125,6 +134,79 @@ def _assignment_support_target(db: Session, user_id: int) -> User:
|
|||||||
return target
|
return target
|
||||||
|
|
||||||
|
|
||||||
|
def _assignment_skin_options(
|
||||||
|
db: Session,
|
||||||
|
*,
|
||||||
|
now: datetime,
|
||||||
|
) -> list[dict[str, Any]]:
|
||||||
|
"""候选皮肤列表只查能力快照,不提前 JOIN 账号占用。
|
||||||
|
|
||||||
|
“某皮肤有多少账号可发”的完整口径由正式候选查询负责;选项接口只需要
|
||||||
|
提供可选择的商品。把归属、租约和预售 EXISTS 放进这里会让 GROUP BY
|
||||||
|
对几十万商品状态逐行做相关子查询,生产实测单条 SQL 可跑数分钟。
|
||||||
|
"""
|
||||||
|
global _assignment_skin_cache
|
||||||
|
engine_key = id(db.get_bind().engine)
|
||||||
|
cached = _assignment_skin_cache
|
||||||
|
if (
|
||||||
|
cached is not None
|
||||||
|
and cached[1] == engine_key
|
||||||
|
and time.monotonic() - cached[0] < _ASSIGNMENT_SKIN_CACHE_SECONDS
|
||||||
|
):
|
||||||
|
return [dict(item) for item in cached[2]]
|
||||||
|
|
||||||
|
with _assignment_skin_cache_lock:
|
||||||
|
cached = _assignment_skin_cache
|
||||||
|
if (
|
||||||
|
cached is not None
|
||||||
|
and cached[1] == engine_key
|
||||||
|
and time.monotonic() - cached[0] < _ASSIGNMENT_SKIN_CACHE_SECONDS
|
||||||
|
):
|
||||||
|
return [dict(item) for item in cached[2]]
|
||||||
|
|
||||||
|
rows = (
|
||||||
|
db.query(
|
||||||
|
AccountCommodityState.commodity_id,
|
||||||
|
func.max(AccountCommodityState.commodity_name).label(
|
||||||
|
"commodity_name"
|
||||||
|
),
|
||||||
|
AccountCommodityState.scope,
|
||||||
|
func.count(AccountCommodityState.id).label("account_count"),
|
||||||
|
)
|
||||||
|
.filter(
|
||||||
|
AccountCommodityState.platform == "douyu",
|
||||||
|
AccountCommodityState.account_eligibility
|
||||||
|
== ACCOUNT_ELIGIBILITY_ELIGIBLE,
|
||||||
|
AccountCommodityState.offer_state.in_(
|
||||||
|
(OFFER_STATE_ACTIVE, OFFER_STATE_BEFORE)
|
||||||
|
),
|
||||||
|
AccountCommodityState.valid_until.isnot(None),
|
||||||
|
AccountCommodityState.valid_until > now,
|
||||||
|
)
|
||||||
|
.group_by(
|
||||||
|
AccountCommodityState.commodity_id,
|
||||||
|
AccountCommodityState.scope,
|
||||||
|
)
|
||||||
|
.order_by(
|
||||||
|
func.count(AccountCommodityState.id).desc(),
|
||||||
|
func.max(AccountCommodityState.commodity_name).asc(),
|
||||||
|
)
|
||||||
|
.limit(200)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
result = [
|
||||||
|
{
|
||||||
|
"commodity_id": str(commodity_id),
|
||||||
|
"commodity_name": str(commodity_name or commodity_id),
|
||||||
|
"scope": str(scope or "elite"),
|
||||||
|
"account_count": int(account_count or 0),
|
||||||
|
}
|
||||||
|
for commodity_id, commodity_name, scope, account_count in rows
|
||||||
|
]
|
||||||
|
_assignment_skin_cache = (time.monotonic(), engine_key, result)
|
||||||
|
return [dict(item) for item in result]
|
||||||
|
|
||||||
|
|
||||||
def _query_str(value) -> str:
|
def _query_str(value) -> str:
|
||||||
"""把查询参数安全地取成字符串。
|
"""把查询参数安全地取成字符串。
|
||||||
|
|
||||||
@@ -187,7 +269,11 @@ def _filter_accounts_query(
|
|||||||
query = query.filter(Account.cookie.isnot(None), Account.cookie != "")
|
query = query.filter(Account.cookie.isnot(None), Account.cookie != "")
|
||||||
if _query_bool(assignable_only):
|
if _query_bool(assignable_only):
|
||||||
query = query.filter(_assignable_account_filter())
|
query = query.filter(_assignable_account_filter())
|
||||||
if _query_bool(assigned_only) and user_has_permission(current, "account:view_all"):
|
if (
|
||||||
|
_query_bool(assigned_only)
|
||||||
|
and current.role != "support"
|
||||||
|
and user_has_permission(current, "account:view_all")
|
||||||
|
):
|
||||||
query = query.filter(Account.assigned_to.isnot(None))
|
query = query.filter(Account.assigned_to.isnot(None))
|
||||||
# 归属筛选:未分配 / 已分配,再叠加「指定客服」。与其它条件(标签、CK、
|
# 归属筛选:未分配 / 已分配,再叠加「指定客服」。与其它条件(标签、CK、
|
||||||
# 搜索…)是**同时生效**的,这正是「综合筛选」的用法。
|
# 搜索…)是**同时生效**的,这正是「综合筛选」的用法。
|
||||||
@@ -902,7 +988,10 @@ def accounts_summary(
|
|||||||
):
|
):
|
||||||
"""账号管理统计,避免前端为了卡片统计拉全量账号。"""
|
"""账号管理统计,避免前端为了卡片统计拉全量账号。"""
|
||||||
query = db.query(Account)
|
query = db.query(Account)
|
||||||
if not user_has_permission(current, "account:view_all"):
|
if (
|
||||||
|
current.role == "support"
|
||||||
|
or not user_has_permission(current, "account:view_all")
|
||||||
|
):
|
||||||
if user_has_permission(current, "account:view_assigned"):
|
if user_has_permission(current, "account:view_assigned"):
|
||||||
query = query.filter(Account.assigned_to == current.id)
|
query = query.filter(Account.assigned_to == current.id)
|
||||||
else:
|
else:
|
||||||
@@ -1445,35 +1534,37 @@ def assignments_summary(
|
|||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
current: User = Depends(require_permission("account:assign")),
|
current: User = Depends(require_permission("account:assign")),
|
||||||
):
|
):
|
||||||
"""分配概览:每个客服分到了多少**可分配账号**(当前 Cookie 已通过新鲜 CK 检测)。
|
"""分配概览:统计真实归属数量,另由候选池接口统计新鲜可分配数量。"""
|
||||||
|
|
||||||
未检测、检测失败或旧结论的账号必须先重登/复检,放进分配池只会让客服以为能跑任务,
|
|
||||||
所以列表、全量分配与这里的统计统一用 `_assignable_account_filter()`。
|
|
||||||
"""
|
|
||||||
results = (
|
results = (
|
||||||
db.query(User.id, User.username, func.count(Account.id).label("count"))
|
db.query(User.id, User.username, func.count(Account.id).label("count"))
|
||||||
.outerjoin(
|
.outerjoin(
|
||||||
Account,
|
Account,
|
||||||
and_(
|
Account.assigned_to == User.id,
|
||||||
Account.assigned_to == User.id,
|
|
||||||
_assignable_account_filter(),
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
.filter(User.role == "support", User.is_active.is_(True))
|
.filter(User.role == "support", User.is_active.is_(True))
|
||||||
.group_by(User.id, User.username)
|
.group_by(User.id, User.username)
|
||||||
.order_by(func.count(Account.id).desc())
|
.order_by(func.count(Account.id).desc())
|
||||||
.all()
|
.all()
|
||||||
)
|
)
|
||||||
|
active_support_ids = select(User.id).where(
|
||||||
|
User.role == "support",
|
||||||
|
User.is_active.is_(True),
|
||||||
|
)
|
||||||
total_unassigned = (
|
total_unassigned = (
|
||||||
|
db.query(func.count(Account.id))
|
||||||
|
.filter(Account.assigned_to.is_(None))
|
||||||
|
.scalar()
|
||||||
|
) or 0
|
||||||
|
total_orphaned = (
|
||||||
db.query(func.count(Account.id))
|
db.query(func.count(Account.id))
|
||||||
.filter(
|
.filter(
|
||||||
Account.assigned_to.is_(None),
|
Account.assigned_to.isnot(None),
|
||||||
_assignable_account_filter(),
|
~Account.assigned_to.in_(active_support_ids),
|
||||||
)
|
)
|
||||||
.scalar()
|
.scalar()
|
||||||
) or 0
|
) or 0
|
||||||
total_assigned = sum(int(cnt or 0) for _, _, cnt in results)
|
total_assigned = sum(int(cnt or 0) for _, _, cnt in results)
|
||||||
total_accounts = total_assigned + total_unassigned
|
total_accounts = total_assigned + total_unassigned + total_orphaned
|
||||||
return {
|
return {
|
||||||
"support_users": [
|
"support_users": [
|
||||||
{"id": uid, "username": uname, "assigned_count": int(cnt or 0)}
|
{"id": uid, "username": uname, "assigned_count": int(cnt or 0)}
|
||||||
@@ -1481,6 +1572,7 @@ def assignments_summary(
|
|||||||
],
|
],
|
||||||
"unassigned_count": total_unassigned,
|
"unassigned_count": total_unassigned,
|
||||||
"assigned_count": total_assigned,
|
"assigned_count": total_assigned,
|
||||||
|
"orphaned_count": total_orphaned,
|
||||||
"total_count": total_accounts,
|
"total_count": total_accounts,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1539,46 +1631,11 @@ def assignment_options(
|
|||||||
),
|
),
|
||||||
}
|
}
|
||||||
|
|
||||||
skin_rows = (
|
skins = _assignment_skin_options(db, now=now)
|
||||||
db.query(
|
|
||||||
AccountCommodityState.commodity_id,
|
|
||||||
func.max(AccountCommodityState.commodity_name).label("commodity_name"),
|
|
||||||
AccountCommodityState.scope,
|
|
||||||
func.count(func.distinct(AccountCommodityState.account_id)).label(
|
|
||||||
"account_count"
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.join(Account, Account.id == AccountCommodityState.account_id)
|
|
||||||
.filter(
|
|
||||||
AccountCommodityState.platform == "douyu",
|
|
||||||
AccountCommodityState.account_eligibility
|
|
||||||
== ACCOUNT_ELIGIBILITY_ELIGIBLE,
|
|
||||||
AccountCommodityState.offer_state.in_(
|
|
||||||
(OFFER_STATE_ACTIVE, OFFER_STATE_BEFORE)
|
|
||||||
),
|
|
||||||
AccountCommodityState.valid_until.isnot(None),
|
|
||||||
AccountCommodityState.valid_until > now,
|
|
||||||
*base_filters,
|
|
||||||
~has_lease,
|
|
||||||
~in_collab,
|
|
||||||
)
|
|
||||||
.group_by(AccountCommodityState.commodity_id, AccountCommodityState.scope)
|
|
||||||
.order_by(func.count(func.distinct(AccountCommodityState.account_id)).desc())
|
|
||||||
.limit(200)
|
|
||||||
.all()
|
|
||||||
)
|
|
||||||
return {
|
return {
|
||||||
"occupancy": occupancy,
|
"occupancy": occupancy,
|
||||||
"presets": presets,
|
"presets": presets,
|
||||||
"skins": [
|
"skins": skins,
|
||||||
{
|
|
||||||
"commodity_id": str(commodity_id),
|
|
||||||
"commodity_name": str(commodity_name or commodity_id),
|
|
||||||
"scope": str(scope or "elite"),
|
|
||||||
"account_count": int(account_count or 0),
|
|
||||||
}
|
|
||||||
for commodity_id, commodity_name, scope, account_count in skin_rows
|
|
||||||
],
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -298,7 +298,8 @@ async def supplier_recharge_callback(request: Request, db: Session = Depends(get
|
|||||||
|
|
||||||
|
|
||||||
def _can_view_all(user: User) -> bool:
|
def _can_view_all(user: User) -> bool:
|
||||||
return user_has_permission(user, "account:view_all")
|
"""客服始终只能看自己名下账号,额外权限也不能突破这个角色边界。"""
|
||||||
|
return user.role != "support" and user_has_permission(user, "account:view_all")
|
||||||
|
|
||||||
|
|
||||||
def _visible_task_accounts_query(db: Session, current: User):
|
def _visible_task_accounts_query(db: Session, current: User):
|
||||||
|
|||||||
@@ -2030,6 +2030,7 @@ class PlatformInfo(BaseModel):
|
|||||||
# ---- 通用 ----
|
# ---- 通用 ----
|
||||||
class AppInfo(BaseModel):
|
class AppInfo(BaseModel):
|
||||||
version: str
|
version: str
|
||||||
|
release_id: str = ""
|
||||||
|
|
||||||
|
|
||||||
class MessageResponse(BaseModel):
|
class MessageResponse(BaseModel):
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
"""应用版本信息。"""
|
"""应用版本信息。"""
|
||||||
|
|
||||||
|
import hashlib
|
||||||
import tomllib
|
import tomllib
|
||||||
from functools import lru_cache
|
from functools import lru_cache
|
||||||
from importlib.metadata import PackageNotFoundError
|
from importlib.metadata import PackageNotFoundError
|
||||||
@@ -22,3 +23,22 @@ def get_app_version() -> str:
|
|||||||
return package_version("live-hub-py")
|
return package_version("live-hub-py")
|
||||||
except PackageNotFoundError:
|
except PackageNotFoundError:
|
||||||
return "0.0.0"
|
return "0.0.0"
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache(maxsize=1)
|
||||||
|
def get_frontend_release_id() -> str:
|
||||||
|
"""当前前端构建的稳定标识。
|
||||||
|
|
||||||
|
Vite 的 index.html 引用带内容哈希的 JS/CSS 文件,因此构建产物变化时
|
||||||
|
index.html 也会变化。只升级 pyproject 版本不足以识别同版本重新部署,
|
||||||
|
所以把它和版本号组合成 release_id,供前端判断是否需要刷新。
|
||||||
|
"""
|
||||||
|
version = get_app_version()
|
||||||
|
index_path = (
|
||||||
|
Path(__file__).resolve().parents[2] / "web" / "frontend" / "dist" / "index.html"
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
digest = hashlib.sha256(index_path.read_bytes()).hexdigest()[:12]
|
||||||
|
except OSError:
|
||||||
|
digest = "source"
|
||||||
|
return f"{version}+{digest}"
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ export interface MessageDeletedResponse extends MessageResponse {
|
|||||||
|
|
||||||
export interface AppInfo {
|
export interface AppInfo {
|
||||||
version: string;
|
version: string;
|
||||||
|
/** 服务端当前前端构建标识;同版本重新构建时也会变化 */
|
||||||
|
release_id?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PageParams {
|
export interface PageParams {
|
||||||
@@ -477,6 +479,7 @@ export interface AssignmentsSummary {
|
|||||||
support_users: SupportUserItem[];
|
support_users: SupportUserItem[];
|
||||||
unassigned_count: number;
|
unassigned_count: number;
|
||||||
assigned_count?: number;
|
assigned_count?: number;
|
||||||
|
orphaned_count?: number;
|
||||||
total_count?: number;
|
total_count?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
|
||||||
|
import { appApi, type AppInfo } from '../api/modules';
|
||||||
|
|
||||||
|
const VERSION_POLL_INTERVAL_MS = 30_000;
|
||||||
|
|
||||||
|
function versionParts(version: string): number[] {
|
||||||
|
return (version.match(/\d+/g) || []).map((value) => Number(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
function compareVersions(left: string, right: string): number {
|
||||||
|
const leftParts = versionParts(left);
|
||||||
|
const rightParts = versionParts(right);
|
||||||
|
const length = Math.max(leftParts.length, rightParts.length);
|
||||||
|
for (let index = 0; index < length; index += 1) {
|
||||||
|
const leftValue = leftParts[index] ?? 0;
|
||||||
|
const rightValue = rightParts[index] ?? 0;
|
||||||
|
if (leftValue !== rightValue) return leftValue - rightValue;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isNewerRelease(latest: AppInfo, loaded: AppInfo): boolean {
|
||||||
|
const versionDiff = compareVersions(latest.version, loaded.version);
|
||||||
|
if (versionDiff !== 0) return versionDiff > 0;
|
||||||
|
return Boolean(
|
||||||
|
latest.release_id
|
||||||
|
&& latest.release_id !== loaded.release_id,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useVersionMonitor() {
|
||||||
|
const [loaded, setLoaded] = useState<AppInfo | null>(null);
|
||||||
|
const [latest, setLatest] = useState<AppInfo | null>(null);
|
||||||
|
const [updateAvailable, setUpdateAvailable] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false;
|
||||||
|
let inFlight = false;
|
||||||
|
let baseline: AppInfo | null = null;
|
||||||
|
|
||||||
|
const checkVersion = async () => {
|
||||||
|
if (inFlight) return;
|
||||||
|
inFlight = true;
|
||||||
|
try {
|
||||||
|
const next = await appApi.info();
|
||||||
|
if (cancelled) return;
|
||||||
|
if (baseline === null) {
|
||||||
|
baseline = next;
|
||||||
|
setLoaded(next);
|
||||||
|
setLatest(next);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setLatest(next);
|
||||||
|
if (isNewerRelease(next, baseline)) {
|
||||||
|
setUpdateAvailable(true);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 网络抖动不提示版本更新;下一次轮询或窗口聚焦时会重试。
|
||||||
|
} finally {
|
||||||
|
inFlight = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
void checkVersion();
|
||||||
|
const timer = window.setInterval(() => {
|
||||||
|
if (document.visibilityState === 'visible') {
|
||||||
|
void checkVersion();
|
||||||
|
}
|
||||||
|
}, VERSION_POLL_INTERVAL_MS);
|
||||||
|
const handleFocus = () => {
|
||||||
|
if (document.visibilityState === 'visible') void checkVersion();
|
||||||
|
};
|
||||||
|
document.addEventListener('visibilitychange', handleFocus);
|
||||||
|
window.addEventListener('focus', handleFocus);
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
window.clearInterval(timer);
|
||||||
|
document.removeEventListener('visibilitychange', handleFocus);
|
||||||
|
window.removeEventListener('focus', handleFocus);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return { loaded, latest, updateAvailable };
|
||||||
|
}
|
||||||
@@ -1,5 +1,16 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import { Layout, Menu, Avatar, Space, Typography, Button, App, Dropdown } from 'antd';
|
import {
|
||||||
|
App,
|
||||||
|
Avatar,
|
||||||
|
Badge,
|
||||||
|
Button,
|
||||||
|
Dropdown,
|
||||||
|
Layout,
|
||||||
|
Menu,
|
||||||
|
Space,
|
||||||
|
Tag,
|
||||||
|
Typography,
|
||||||
|
} from 'antd';
|
||||||
import type { MenuProps } from 'antd';
|
import type { MenuProps } from 'antd';
|
||||||
import {
|
import {
|
||||||
DashboardOutlined, UserOutlined, LogoutOutlined,
|
DashboardOutlined, UserOutlined, LogoutOutlined,
|
||||||
@@ -8,6 +19,7 @@ import {
|
|||||||
SunOutlined, MoonOutlined, DesktopOutlined, GiftOutlined, ApartmentOutlined, MobileOutlined, ShoppingCartOutlined,
|
SunOutlined, MoonOutlined, DesktopOutlined, GiftOutlined, ApartmentOutlined, MobileOutlined, ShoppingCartOutlined,
|
||||||
BookOutlined, GlobalOutlined,
|
BookOutlined, GlobalOutlined,
|
||||||
SafetyCertificateOutlined, FileSearchOutlined, RobotOutlined, FileExcelOutlined, ThunderboltOutlined,
|
SafetyCertificateOutlined, FileSearchOutlined, RobotOutlined, FileExcelOutlined, ThunderboltOutlined,
|
||||||
|
ReloadOutlined,
|
||||||
} from '@ant-design/icons';
|
} from '@ant-design/icons';
|
||||||
import { useNavigate, useLocation, Outlet } from 'react-router-dom';
|
import { useNavigate, useLocation, Outlet } from 'react-router-dom';
|
||||||
import { getUser, clearAuth, type AuthUser } from '../store/auth';
|
import { getUser, clearAuth, type AuthUser } from '../store/auth';
|
||||||
@@ -15,7 +27,7 @@ import { authApi } from '../api/modules';
|
|||||||
import { type ThemeMode } from '../store/theme';
|
import { type ThemeMode } from '../store/theme';
|
||||||
import { useTheme } from '../store/useTheme';
|
import { useTheme } from '../store/useTheme';
|
||||||
import { usePermissions } from '../hooks/usePermissions';
|
import { usePermissions } from '../hooks/usePermissions';
|
||||||
import { useAppInfo } from '../hooks/useAppInfo';
|
import { useVersionMonitor } from '../hooks/useVersionMonitor';
|
||||||
|
|
||||||
const { Sider, Content } = Layout;
|
const { Sider, Content } = Layout;
|
||||||
const { Text } = Typography;
|
const { Text } = Typography;
|
||||||
@@ -39,7 +51,11 @@ export default function MainLayout({ onLogout }: { onLogout?: () => void }) {
|
|||||||
const [collapsed, setCollapsed] = useState(false);
|
const [collapsed, setCollapsed] = useState(false);
|
||||||
const { mode, isDark, setMode } = useTheme();
|
const { mode, isDark, setMode } = useTheme();
|
||||||
const { can, canAny } = usePermissions(user);
|
const { can, canAny } = usePermissions(user);
|
||||||
const appInfo = useAppInfo();
|
const {
|
||||||
|
loaded: appInfo,
|
||||||
|
latest: latestAppInfo,
|
||||||
|
updateAvailable,
|
||||||
|
} = useVersionMonitor();
|
||||||
// App.useApp() 的 modal 实例会继承 ConfigProvider 主题(静态 Modal.confirm 不会,暗色模式下是白底)
|
// App.useApp() 的 modal 实例会继承 ConfigProvider 主题(静态 Modal.confirm 不会,暗色模式下是白底)
|
||||||
const { modal } = App.useApp();
|
const { modal } = App.useApp();
|
||||||
|
|
||||||
@@ -182,10 +198,23 @@ export default function MainLayout({ onLogout }: { onLogout?: () => void }) {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const refreshForUpdate = () => {
|
||||||
|
modal.confirm({
|
||||||
|
title: '服务器已有新版本',
|
||||||
|
content: `当前页面 ${versionText},服务器 ${latestVersionText}。请先刷新页面,避免继续使用旧界面提交数据。`,
|
||||||
|
okText: '立即刷新',
|
||||||
|
cancelText: '稍后',
|
||||||
|
onOk: () => window.location.reload(),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
const siderTheme = isDark ? 'dark' : 'light';
|
const siderTheme = isDark ? 'dark' : 'light';
|
||||||
const siderTextColor = isDark ? '#fff' : undefined;
|
const siderTextColor = isDark ? '#fff' : undefined;
|
||||||
const secondaryTextColor = isDark ? 'rgba(255,255,255,0.65)' : 'rgba(0,0,0,0.45)';
|
const secondaryTextColor = isDark ? 'rgba(255,255,255,0.65)' : 'rgba(0,0,0,0.45)';
|
||||||
const versionText = appInfo?.version ? `v${appInfo.version}` : 'v--';
|
const versionText = appInfo?.version ? `v${appInfo.version}` : 'v--';
|
||||||
|
const latestVersionText = latestAppInfo?.version
|
||||||
|
? `v${latestAppInfo.version}`
|
||||||
|
: versionText;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Layout style={{ height: '100vh', overflow: 'hidden' }}>
|
<Layout style={{ height: '100vh', overflow: 'hidden' }}>
|
||||||
@@ -194,22 +223,72 @@ export default function MainLayout({ onLogout }: { onLogout?: () => void }) {
|
|||||||
display: 'flex', flexDirection: 'column', height: '100%',
|
display: 'flex', flexDirection: 'column', height: '100%',
|
||||||
}}>
|
}}>
|
||||||
<div style={{
|
<div style={{
|
||||||
height: 48, margin: '12px 12px 0', fontSize: 16,
|
margin: '12px 12px 0',
|
||||||
textAlign: 'center', lineHeight: '48px', fontWeight: 'bold',
|
display: 'flex',
|
||||||
whiteSpace: 'nowrap', overflow: 'hidden', flexShrink: 0,
|
flexDirection: 'column',
|
||||||
display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
|
gap: 6,
|
||||||
|
flexShrink: 0,
|
||||||
color: siderTextColor,
|
color: siderTextColor,
|
||||||
}}>
|
}}>
|
||||||
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>
|
<div style={{
|
||||||
{collapsed ? <ApartmentOutlined /> : '直播运营后台'}
|
minHeight: 40,
|
||||||
</span>
|
display: 'flex',
|
||||||
<Button
|
alignItems: 'center',
|
||||||
type="text"
|
justifyContent: 'space-between',
|
||||||
size="small"
|
gap: 6,
|
||||||
icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
|
}}>
|
||||||
onClick={() => setCollapsed(!collapsed)}
|
{collapsed ? (
|
||||||
style={{ color: siderTextColor, flexShrink: 0 }}
|
<Badge dot={updateAvailable}>
|
||||||
/>
|
<ApartmentOutlined style={{ fontSize: 18 }} />
|
||||||
|
</Badge>
|
||||||
|
) : (
|
||||||
|
<div style={{ minWidth: 0, flex: 1 }}>
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 }}>
|
||||||
|
<span style={{
|
||||||
|
fontSize: 16,
|
||||||
|
fontWeight: 'bold',
|
||||||
|
overflow: 'hidden',
|
||||||
|
textOverflow: 'ellipsis',
|
||||||
|
whiteSpace: 'nowrap',
|
||||||
|
}}>
|
||||||
|
直播运营后台
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<Button
|
||||||
|
type="text"
|
||||||
|
size="small"
|
||||||
|
icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
|
||||||
|
onClick={() => setCollapsed(!collapsed)}
|
||||||
|
style={{ color: siderTextColor, flexShrink: 0 }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{!collapsed ? (
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
|
||||||
|
<Text style={{ color: secondaryTextColor, fontSize: 12 }}>
|
||||||
|
当前版本
|
||||||
|
</Text>
|
||||||
|
<Tag
|
||||||
|
color={updateAvailable ? 'red' : 'blue'}
|
||||||
|
style={{ marginInlineEnd: 0, fontSize: 11, lineHeight: '18px' }}
|
||||||
|
>
|
||||||
|
{versionText}
|
||||||
|
</Tag>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
{updateAvailable && !collapsed ? (
|
||||||
|
<Button
|
||||||
|
block
|
||||||
|
danger
|
||||||
|
type="primary"
|
||||||
|
size="small"
|
||||||
|
icon={<ReloadOutlined />}
|
||||||
|
onClick={refreshForUpdate}
|
||||||
|
>
|
||||||
|
服务器已更新,请刷新
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
<Menu
|
<Menu
|
||||||
theme={siderTheme}
|
theme={siderTheme}
|
||||||
@@ -235,17 +314,6 @@ export default function MainLayout({ onLogout }: { onLogout?: () => void }) {
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</Space>
|
</Space>
|
||||||
{!collapsed && (
|
|
||||||
<Text style={{
|
|
||||||
display: 'block',
|
|
||||||
color: secondaryTextColor,
|
|
||||||
fontSize: 12,
|
|
||||||
lineHeight: '20px',
|
|
||||||
marginBottom: 8,
|
|
||||||
}}>
|
|
||||||
当前版本 {versionText}
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
{collapsed ? (
|
{collapsed ? (
|
||||||
<>
|
<>
|
||||||
<Space orientation="vertical" style={{ width: '100%' }}>
|
<Space orientation="vertical" style={{ width: '100%' }}>
|
||||||
@@ -270,16 +338,6 @@ export default function MainLayout({ onLogout }: { onLogout?: () => void }) {
|
|||||||
style={{ color: secondaryTextColor }}
|
style={{ color: secondaryTextColor }}
|
||||||
/>
|
/>
|
||||||
</Space>
|
</Space>
|
||||||
<Text style={{
|
|
||||||
display: 'block',
|
|
||||||
color: secondaryTextColor,
|
|
||||||
fontSize: 11,
|
|
||||||
lineHeight: '18px',
|
|
||||||
textAlign: 'center',
|
|
||||||
marginTop: 8,
|
|
||||||
}}>
|
|
||||||
{versionText}
|
|
||||||
</Text>
|
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<Space style={{ width: '100%', justifyContent: 'space-between' }}>
|
<Space style={{ width: '100%', justifyContent: 'space-between' }}>
|
||||||
|
|||||||
@@ -211,7 +211,6 @@ export default function AssignmentsPage() {
|
|||||||
Object.assign(params, candidateFilters);
|
Object.assign(params, candidateFilters);
|
||||||
} else if (selectedUser) {
|
} else if (selectedUser) {
|
||||||
params.assigned_user_id = selectedUser.id;
|
params.assigned_user_id = selectedUser.id;
|
||||||
params.assignable_only = true;
|
|
||||||
}
|
}
|
||||||
const data = await accountApi.listPaged(params);
|
const data = await accountApi.listPaged(params);
|
||||||
if (requestId !== pagedRequestRef.current) return;
|
if (requestId !== pagedRequestRef.current) return;
|
||||||
@@ -409,7 +408,9 @@ export default function AssignmentsPage() {
|
|||||||
?? 0;
|
?? 0;
|
||||||
const assignedCount = summary?.assigned_count ?? 0;
|
const assignedCount = summary?.assigned_count ?? 0;
|
||||||
const unassignedCount = summary?.unassigned_count ?? 0;
|
const unassignedCount = summary?.unassigned_count ?? 0;
|
||||||
const totalAccountCount = summary?.total_count ?? assignedCount + unassignedCount;
|
const orphanedCount = summary?.orphaned_count ?? 0;
|
||||||
|
const totalAccountCount =
|
||||||
|
summary?.total_count ?? assignedCount + unassignedCount + orphanedCount;
|
||||||
|
|
||||||
const columns = [
|
const columns = [
|
||||||
{ title: 'ID', dataIndex: 'id', width: 72 },
|
{ title: 'ID', dataIndex: 'id', width: 72 },
|
||||||
@@ -504,7 +505,10 @@ export default function AssignmentsPage() {
|
|||||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||||
<div>
|
<div>
|
||||||
<h2 style={{ margin: 0 }}>账号分配中心</h2>
|
<h2 style={{ margin: 0 }}>账号分配中心</h2>
|
||||||
<Text type="secondary">按生命周期、占用、资产与皮肤能力筛选后定向发放</Text>
|
<Text type="secondary">
|
||||||
|
按生命周期、占用、资产与皮肤能力筛选后定向发放
|
||||||
|
{orphanedCount > 0 ? `;另有 ${orphanedCount} 个账号仍归属已停用客服` : ''}
|
||||||
|
</Text>
|
||||||
</div>
|
</div>
|
||||||
<Button icon={<ReloadOutlined />} loading={refreshing} onClick={() => void handleRefresh()}>
|
<Button icon={<ReloadOutlined />} loading={refreshing} onClick={() => void handleRefresh()}>
|
||||||
刷新
|
刷新
|
||||||
@@ -514,7 +518,7 @@ export default function AssignmentsPage() {
|
|||||||
<Row gutter={12} style={{ flexShrink: 0 }}>
|
<Row gutter={12} style={{ flexShrink: 0 }}>
|
||||||
<Col flex="1 1 180px">
|
<Col flex="1 1 180px">
|
||||||
<Card size="small">
|
<Card size="small">
|
||||||
<Statistic title="可分配账号" value={totalAccountCount} prefix={<TeamOutlined />} />
|
<Statistic title="账号总数" value={totalAccountCount} prefix={<TeamOutlined />} />
|
||||||
</Card>
|
</Card>
|
||||||
</Col>
|
</Col>
|
||||||
<Col flex="1 1 180px">
|
<Col flex="1 1 180px">
|
||||||
@@ -746,7 +750,7 @@ export default function AssignmentsPage() {
|
|||||||
}
|
}
|
||||||
options={(options?.skins || []).map((skin) => ({
|
options={(options?.skins || []).map((skin) => ({
|
||||||
value: skin.commodity_id,
|
value: skin.commodity_id,
|
||||||
label: `${skin.commodity_name} · ${skin.account_count}`,
|
label: `${skin.commodity_name} · 能力 ${skin.account_count}`,
|
||||||
}))}
|
}))}
|
||||||
/>
|
/>
|
||||||
<Select
|
<Select
|
||||||
|
|||||||
Reference in New Issue
Block a user