feat(weibo): 增加工作台批量充值与批量导入

This commit is contained in:
yml
2026-11-11 20:11:35 +08:00
parent c9814ab4d2
commit 50bb829101
9 changed files with 1353 additions and 60 deletions
+174
View File
@@ -3,6 +3,7 @@
from __future__ import annotations
import os
import re
from fastapi import APIRouter, Depends, HTTPException, Query
from loguru import logger
@@ -41,6 +42,9 @@ from ..schemas import (
WeiboRechargeOrderOut,
WeiboRechargeRequest,
WeiboWorkbenchAccountsRequest,
WeiboWorkbenchBatchImportItem,
WeiboWorkbenchBatchImportOut,
WeiboWorkbenchBatchImportRequest,
)
from ..services.audit_service import record_audit
from ..services.weibo_service import (
@@ -61,6 +65,7 @@ from ..services.weibo_service import (
router = APIRouter(prefix="/api/weibo", tags=["微博微豆"])
WEIBO_DEFAULT_ACTIVITY = os.getenv("WEIBO_DEFAULT_ACTIVITY", "").strip()
WEIBO_WORKBENCH_BATCH_IMPORT_MAX = 200
def _require_weibo_perm(user: User, permission: str) -> None:
@@ -319,6 +324,175 @@ def list_workbench_pool(
return _paginated_accounts(query, page=page, page_size=page_size)
@router.post(
"/workbench/accounts/batch-import",
response_model=WeiboWorkbenchBatchImportOut,
)
def import_workbench_accounts_by_text(
req: WeiboWorkbenchBatchImportRequest,
db: Session = Depends(get_db),
current: User = Depends(get_current_user),
):
"""按 UID/用户名/角色批量解析账号并加入当前用户工作台。"""
_require_weibo_perm(current, "weibo:workbench")
identifiers: list[str] = []
for token in re.split(r"[\s,,;;]+", req.text.strip()):
value = token.strip()
if value and value not in identifiers:
identifiers.append(value)
if not identifiers:
raise HTTPException(status_code=400, detail="请先粘贴微博用户名或 UID")
if len(identifiers) > WEIBO_WORKBENCH_BATCH_IMPORT_MAX:
raise HTTPException(
status_code=400,
detail=f"一次最多导入 {WEIBO_WORKBENCH_BATCH_IMPORT_MAX} 个账号",
)
visible_query = _visible_weibo_accounts_query(db.query(WeiboAccount), current)
accounts = visible_query.filter(
or_(
WeiboAccount.uid.in_(identifiers),
WeiboAccount.nickname.in_(identifiers),
WeiboAccount.game_role_name.in_(identifiers),
)
).all()
def grouped(field: str) -> dict[str, list[WeiboAccount]]:
result: dict[str, list[WeiboAccount]] = {}
for account in accounts:
value = str(getattr(account, field) or "").strip()
if value:
result.setdefault(value, []).append(account)
return result
by_uid = grouped("uid")
by_nickname = grouped("nickname")
by_role = grouped("game_role_name")
account_ids = [account.id for account in accounts]
occupancy = {
account_id: user_id
for account_id, user_id in db.query(
WeiboWorkbenchAccount.account_id,
WeiboWorkbenchAccount.user_id,
)
.filter(WeiboWorkbenchAccount.account_id.in_(account_ids))
.all()
}
items: list[WeiboWorkbenchBatchImportItem] = []
to_add: list[WeiboAccount] = []
planned_ids: set[int] = set()
for identifier in identifiers:
candidates = by_uid.get(identifier) or by_nickname.get(identifier) or []
if not candidates:
candidates = by_role.get(identifier) or []
if not candidates:
items.append(
WeiboWorkbenchBatchImportItem(
identifier=identifier,
status="not_found",
message="当前可见账号池中没有匹配项",
)
)
continue
if len(candidates) > 1 and identifier not in by_uid:
items.append(
WeiboWorkbenchBatchImportItem(
identifier=identifier,
status="ambiguous",
message=f"匹配到 {len(candidates)} 个账号,请改用 UID",
)
)
continue
account = candidates[0]
base = {
"identifier": identifier,
"account_id": account.id,
"uid": account.uid,
"nickname": account.nickname,
}
occupant = occupancy.get(account.id)
if not account.is_enabled:
items.append(
WeiboWorkbenchBatchImportItem(
status="disabled",
message="账号已停用",
**base,
)
)
elif occupant is not None and occupant != current.id:
items.append(
WeiboWorkbenchBatchImportItem(
status="unavailable",
message="账号已在其他人的工作台中使用",
**base,
)
)
elif occupant == current.id:
items.append(
WeiboWorkbenchBatchImportItem(
status="already_added",
message="账号已在本工作台",
**base,
)
)
elif account.id in planned_ids:
items.append(
WeiboWorkbenchBatchImportItem(
status="duplicate",
message="同一账号在本次名单中重复",
**base,
)
)
else:
planned_ids.add(account.id)
to_add.append(account)
items.append(
WeiboWorkbenchBatchImportItem(
status="added",
message="已加入工作台",
**base,
)
)
try:
db.add_all(
[
WeiboWorkbenchAccount(user_id=current.id, account_id=account.id)
for account in to_add
]
)
db.commit()
except IntegrityError as exc:
db.rollback()
raise HTTPException(
status_code=409,
detail="部分账号刚被其他工作台占用,请刷新后重试",
) from exc
if to_add:
_record_audit_safely(
db,
current,
action="weibo:workbench:batch_import",
target=f"weibo_user:{current.id}",
detail={"account_ids": [account.id for account in to_add]},
)
added = sum(item.status == "added" for item in items)
already_added = sum(item.status == "already_added" for item in items)
failed = len(items) - added - already_added
return WeiboWorkbenchBatchImportOut(
requested=len(identifiers),
added=added,
already_added=already_added,
failed=failed,
account_ids=[account.id for account in to_add],
items=items,
)
@router.get("/workbench/tags")
def list_workbench_tags(
db: Session = Depends(get_db),
+22
View File
@@ -521,6 +521,28 @@ class WeiboWorkbenchAccountsRequest(BaseModel):
account_ids: list[int] = Field(default_factory=list)
class WeiboWorkbenchBatchImportRequest(BaseModel):
text: str = Field(..., min_length=1, max_length=100_000)
class WeiboWorkbenchBatchImportItem(BaseModel):
identifier: str
status: str
message: str = ""
account_id: int | None = None
uid: str = ""
nickname: str = ""
class WeiboWorkbenchBatchImportOut(BaseModel):
requested: int
added: int
already_added: int
failed: int
account_ids: list[int] = Field(default_factory=list)
items: list[WeiboWorkbenchBatchImportItem] = Field(default_factory=list)
class WeiboBatchAssignRequest(BaseModel):
account_ids: list[int] = Field(min_length=1)
assigned_to: int | None = None
+25
View File
@@ -814,6 +814,31 @@ export interface WeiboWorkbenchMutationResult {
success: boolean;
}
export interface WeiboWorkbenchBatchImportItem {
identifier: string;
status:
| 'added'
| 'already_added'
| 'not_found'
| 'ambiguous'
| 'unavailable'
| 'disabled'
| 'duplicate';
message: string;
account_id: number | null;
uid: string;
nickname: string;
}
export interface WeiboWorkbenchBatchImportResult {
requested: number;
added: number;
already_added: number;
failed: number;
account_ids: number[];
items: WeiboWorkbenchBatchImportItem[];
}
export interface WeiboBatchTagResult {
updated: number;
tag: string;
+6
View File
@@ -15,6 +15,7 @@ import type {
WeiboRechargeOrderResult,
WeiboImportResult,
WeiboWorkbenchMutationResult,
WeiboWorkbenchBatchImportResult,
} from './types';
export const weiboApi = {
@@ -122,6 +123,11 @@ export const weiboApi = {
'/weibo/workbench/accounts',
{ account_ids: accountIds },
),
batchImportWorkbenchAccounts: (text: string) =>
api.post<WeiboWorkbenchBatchImportResult, WeiboWorkbenchBatchImportResult>(
'/weibo/workbench/accounts/batch-import',
{ text },
),
removeWorkbenchAccounts: (accountIds: number[]) =>
api.post<WeiboWorkbenchMutationResult, WeiboWorkbenchMutationResult>(
'/weibo/workbench/accounts/remove',
File diff suppressed because it is too large Load Diff
+110 -3
View File
@@ -24,6 +24,7 @@ import {
} from 'antd';
import type { TableProps } from 'antd';
import {
CopyOutlined,
DeleteOutlined,
EditOutlined,
FileExcelOutlined,
@@ -58,6 +59,7 @@ import { useCollabRealtime } from '../hooks/useCollabRealtime';
import { usePermissions } from '../hooks/usePermissions';
import { getErrorMessage } from '../utils/error';
import { message } from '../utils/antdMessage';
import { copyTextToClipboard } from '../utils/clipboard';
import { formatTime } from '../utils/time';
const { Text, Title } = Typography;
@@ -578,6 +580,38 @@ export default function WeiboCollabPage() {
[summary],
);
const copySelectedAccountValues = async (kind: 'username' | 'uid') => {
const selectedOrders = orders.filter((row) => selectedIds.includes(row.id));
const values = Array.from(
new Set(
selectedOrders
.map((row) =>
kind === 'uid'
? row.account_uid
: row.account_nickname || row.account_uid,
)
.map((value) => String(value || '').trim())
.filter(Boolean),
),
);
if (values.length === 0) {
message.warning(
kind === 'uid' ? '所选订单没有微博 UID' : '所选订单没有微博用户名',
);
return;
}
try {
await copyTextToClipboard(values.join('\n'));
message.success(
`已复制 ${values.length} 个${
kind === 'uid' ? ' UID' : '用户名'
},可直接粘贴到工作台导入搜索框`,
);
} catch (error) {
message.error(getErrorMessage(error));
}
};
const columns: TableProps<WeiboCollabOrder>['columns'] = [
{
title: '序号',
@@ -618,9 +652,33 @@ export default function WeiboCollabPage() {
width: 210,
render: (_, row) => (
<Space orientation="vertical" size={0}>
<Text>{row.account_nickname || row.account_uid || '未关联'}</Text>
<Text
copyable={
row.account_nickname || row.account_uid
? {
text: row.account_nickname || row.account_uid || '',
tooltips: ['复制用户名', '已复制用户名'],
}
: false
}
>
{row.account_nickname || row.account_uid || '未关联'}
</Text>
<Text type="secondary" style={{ fontSize: 12 }}>
UID {row.account_uid || '-'}
{row.account_uid ? (
<Text
type="secondary"
style={{ fontSize: 12 }}
copyable={{
text: row.account_uid,
tooltips: ['复制 UID', '已复制 UID'],
}}
>
UID {row.account_uid}
</Text>
) : (
'UID -'
)}
</Text>
<Text type="secondary" style={{ fontSize: 12 }}>
{row.game_role_name || '未读到角色'}
@@ -900,6 +958,22 @@ export default function WeiboCollabPage() {
<Space wrap>
<Text type="secondary">已选 {selectedIds.length} 单</Text>
{selectedIds.length > 0 && (
<>
<Button
icon={<CopyOutlined />}
onClick={() => void copySelectedAccountValues('username')}
>
复制所选用户名
</Button>
<Button
icon={<CopyOutlined />}
onClick={() => void copySelectedAccountValues('uid')}
>
复制所选 UID
</Button>
</>
)}
{canEdit && selectedIds.length > 0 && archiveScope !== 'archived' && (
<>
<Button
@@ -1168,7 +1242,40 @@ export default function WeiboCollabPage() {
column={2}
items={[
{ key: 'shop', label: '店铺 / 负责人', children: `${detail.shop || '-'} / ${detail.owner_name || '-'}` },
{ key: 'account', label: '微博账号', children: `${detail.account_nickname || '-'} · UID ${detail.account_uid || '-'}` },
{
key: 'account',
label: '微博账号',
children: (
<Space size={4} wrap>
<Text
copyable={
detail.account_nickname || detail.account_uid
? {
text:
detail.account_nickname ||
detail.account_uid ||
'',
tooltips: ['复制用户名', '已复制用户名'],
}
: false
}
>
{detail.account_nickname || '-'}
</Text>
{detail.account_uid && (
<Text
type="secondary"
copyable={{
text: detail.account_uid,
tooltips: ['复制 UID', '已复制 UID'],
}}
>
UID {detail.account_uid}
</Text>
)}
</Space>
),
},
{ key: 'role', label: '绑定角色', children: detail.game_role_name || '-' },
{ key: 'goods', label: '商品 / 所需微豆', children: `${detail.goods_name || '-'} / ${detail.required_weidou ?? '-'}` },
{ key: 'status', label: '业务状态', children: <Tag color={STATUS_META[detail.status]?.color}>{detail.status_label}</Tag> },
+17
View File
@@ -0,0 +1,17 @@
export async function runWithConcurrency<T>(
items: T[],
limit: number,
worker: (item: T) => Promise<void>,
) {
let nextIndex = 0;
const workerCount = Math.min(Math.max(1, limit), items.length);
await Promise.all(
Array.from({ length: workerCount }, async () => {
while (nextIndex < items.length) {
const index = nextIndex;
nextIndex += 1;
await worker(items[index]);
}
}),
);
}