API版本化:迁移聊天与账号任务入口

This commit is contained in:
Christ committed 2026-08-14 18:01:24 +08:00
1 parent 42e37f7898
commit d3648e9985
11 files changed
+166 -25

No files matched your search

@@ -15,10 +15,10 @@
| 设置 | `/system-settings...`、`/user-settings...`、`/ai-reply-settings...`、`/ai-models` | `/api/v1/settings/system...`、`/api/v1/settings/user...`、`/api/v1/settings/ai-reply...`、`/api/v1/settings/ai-models` | React 系统设置、AI 设置调用已迁移;版本化入口覆盖公开设置、管理员设置、用户设置和 AI 模型查询;旧路径保留 |
| 卡券 | `/cards...` | `/api/v1/cards...` | React 卡券列表、CRUD、批量创建和追加调用已迁移;旧路径保留并由同一 handler 提供 |
| 通知 | `/notification-channels...`、`/message-notifications...` | `/api/v1/notifications/channels...`、`/api/v1/notifications/messages...`、`/api/v1/notifications/accounts/{cid}/bindings` | React 通知渠道、消息绑定和账号绑定调用已迁移;旧路径保留并由同一 handler 提供 |
| 聊天 | `/api/chat...` | `/api/v1/chat...` | 旧路径保留,会话/消息 DTO 已落地 |
| 聊天 | `/api/chat...` | `/api/v1/chat...` | React 会话、消息、图片、已读和 WebSocket 调用已迁移;旧路径保留并由同一 handler 提供 |
| 关键词回复 | `/keywords...`、`/keywords-with-item-id...`、`/keywords-with-type...`、`/item-reply...` | `/api/v1/reply-rules...` | 旧路径保留,基础/商品/类型规则与指定商品回复 DTO 已落地 |
| 默认回复 | `/default-replies...`、`/api/default-reply...` | `/api/v1/default-replies...` | 旧路径保留,单账号、列表和映射 DTO 已落地 |
| 账号任务 | `/api/account-tasks...` | `/api/v1/account-tasks...` | 旧路径保留,设置、运行记录和执行摘要 DTO 已落地 |
| 账号任务 | `/api/account-tasks...` | `/api/v1/account-tasks...` | React 设置和执行调用已迁移;版本化入口覆盖设置、运行记录和执行摘要;旧路径保留并由同一 handler 提供 |
| 管理员 | `/admin/users...`、`/admin/cookies...`、`/admin/stats` | `/api/v1/admin/...` | 旧路径保留,用户/账号/全局统计 DTO 已落地 |
| 统计 | `/dashboard/stats`、`/analytics/orders...` | `/api/v1/analytics/...` | 旧路径保留,概览、收益、维度和有效订单分页 DTO 已落地 |
| 二维码生成 | `/qr-login/generate` | `/api/v1/qr-login/generate` | 旧路径保留,二维码生成、状态和验证完成 DTO 已落地;`qrLoginStatusResponse` 仅保留非敏感动态字段,状态响应继续保留兼容扩展 |
@@ -50,6 +50,7 @@
- 商品列表、详情、发布、更新和删除已由 React 请求层迁移到 `/api/v1/items...`;Go 契约测试确认新旧入口保持商品所有权校验、具名响应和持久化语义一致。
- 商品同步、类目推荐、批量发布预检、任务查询、取消、重试和结果下载已由版本化路由提供;React 现有同步/批量发布调用已迁移,Go 契约测试确认新旧入口状态码和参数校验语义一致。
- 系统/用户/AI 设置、卡券 CRUD/批量/追加和通知渠道/消息/账号绑定已由版本化路由提供;React 设置、卡券和通知调用已迁移,Go 契约测试确认新旧入口权限、状态码和参数校验语义一致。
- 聊天会话、消息、图片、已读和 WebSocket,以及账号任务设置、运行记录和执行已由版本化路由提供;React REST/WebSocket 调用已迁移,Go 契约测试确认新旧入口权限、状态码和参数校验语义一致。
- 聊天会话、消息分页和发送结果使用独立 DTO,不直接暴露数据库模型。
- React `frontend/types.ts` 与 `frontend/services/api.ts` 已同步具名成功响应类型,同时保留旧字段归一逻辑。
- 会话、账号、订单、商品、设置、卡券和通知版本化入口已可用;聊天、关键词、默认回复、账号任务、管理员与统计等领域仍未宣称可用,旧路径继续保留。
- 会话、账号、订单、商品、设置、卡券、通知、聊天和账号任务版本化入口已可用;关键词、默认回复、管理员与统计等领域仍未宣称可用,旧路径继续保留。
+3 -1
View File
@@ -147,7 +147,8 @@ app shell / routes
- 已完成阶段 3 第十八个 PR 切片“商品 API 版本化兼容入口与调用方迁移”:新增商品列表、详情、发布、更新和删除 `/api/v1/items...` 薄适配入口,复用既有商品所有权校验与 handler;React 对应调用已迁移,旧路径保留;新增商品契约测试并保持独立可回滚提交;
- 已完成阶段 3 第十九个 PR 切片“商品同步与批量发布 API 版本化兼容入口迁移”:新增商品同步、类目推荐、批量发布预检、任务、详情、取消、重试和结果下载 `/api/v1/items...` 薄适配入口,复用既有商品 handler;React 对应同步/批量发布调用已迁移,旧路径保留;新增商品批量契约测试并保持独立可回滚提交;
- 已完成阶段 3 第二十个 PR 切片“设置、卡券与通知 API 版本化兼容入口迁移”:新增系统/用户/AI 设置、卡券和通知渠道/消息/账号绑定 `/api/v1/settings`、`/api/v1/cards`、`/api/v1/notifications` 薄适配入口,复用既有权限边界与 handler;React 系统设置、AI 设置、卡券和通知调用已迁移,旧路径保留;新增三领域契约测试并保持独立可回滚提交;
- 阶段 3 下一 PR 切片为“聊天与账号任务 API 版本化兼容入口迁移”:迁移聊天会话/消息和账号任务设置/执行调用方,继续保留旧路径,不拆分单个 handler 提交;
- 已完成阶段 3 第二十一个 PR 切片“聊天与账号任务 API 版本化兼容入口迁移”:新增聊天 REST/WebSocket 和账号任务设置/运行记录/执行 `/api/v1/chat...`、`/api/v1/account-tasks...` 薄适配入口,复用既有权限边界与 handler;React REST/WebSocket、账号任务设置和执行调用已迁移,旧路径保留;新增聊天/账号任务契约测试并保持独立可回滚提交;
- 阶段 3 下一 PR 切片为“关键词回复与默认回复 API 版本化兼容入口迁移”:迁移关键词基础/商品/类型规则、指定商品回复和默认回复调用方,继续保留旧路径,不拆分单个 handler 提交;
- 禁止跳过当前入口直接开始 Engine、Automation 或 DB 的大规模拆分。
## 6. 阶段 0:治理文档与强约束
@@ -544,3 +545,4 @@ npm --prefix frontend run build
| 2026-08-14 | 完成阶段 3 第十八个 PR 切片“商品 API 版本化兼容入口与调用方迁移” | 新增商品列表、详情、发布、更新和删除 `/api/v1/items...` 薄适配入口,复用既有商品 handler 与所有权校验;React 列表、详情、发布、更新和删除调用已迁移;Go/React 契约测试确认新旧入口兼容;全量门禁通过并合并为一个可回滚提交 | 阶段 3:商品同步与批量发布 API 版本化兼容入口迁移 |
| 2026-08-14 | 完成阶段 3 第十九个 PR 切片“商品同步与批量发布 API 版本化兼容入口迁移” | 新增商品同步、类目推荐、批量发布预检/任务/详情、取消、重试和结果下载 `/api/v1/items...` 薄适配入口,复用既有商品 handler;React 同步和批量发布调用已迁移;Go/React 契约测试确认新旧入口兼容;全量门禁通过并合并为一个可回滚提交 | 阶段 3:设置、卡券与通知 API 版本化兼容入口迁移 |
| 2026-08-14 | 完成阶段 3 第二十个 PR 切片“设置、卡券与通知 API 版本化兼容入口迁移” | 新增系统/用户/AI 设置、卡券和通知渠道/消息/账号绑定 `/api/v1/settings`、`/api/v1/cards`、`/api/v1/notifications` 薄适配入口,复用既有权限边界与 handler;React 设置、卡券和通知调用已迁移;Go/React 契约测试确认新旧入口兼容;全量门禁通过并合并为一个可回滚提交 | 阶段 3:聊天与账号任务 API 版本化兼容入口迁移 |
| 2026-08-14 | 完成阶段 3 第二十一个 PR 切片“聊天与账号任务 API 版本化兼容入口迁移” | 新增聊天 REST/WebSocket、账号任务设置/运行记录/执行 `/api/v1/chat...`、`/api/v1/account-tasks...` 薄适配入口,复用既有 handler 与权限校验;React 聊天 REST/WebSocket 和账号任务调用已迁移;Go/React 契约测试确认新旧入口兼容;全量门禁通过并合并为一个可回滚提交 | 阶段 3:关键词回复与默认回复 API 版本化兼容入口迁移 |
+1 -1
View File
@@ -24,7 +24,7 @@ describe('online chat UI contract', () => {
test('frontend connects only to the application chat websocket', () => {
const chat = source('components/Chat.tsx');
expect(chat).toContain('/api/chat/ws');
expect(chat).toContain('/api/v1/chat/ws');
expect(chat).not.toContain('wss-goofish.dingtalk.com');
});
+1 -1
View File
@@ -212,7 +212,7 @@ const Chat: React.FC = () => {
if (disposed) return;
setLiveState('connecting');
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
socket = new WebSocket(`${protocol}//${window.location.host}/api/chat/ws`);
socket = new WebSocket(`${protocol}//${window.location.host}/api/v1/chat/ws`);
socket.onopen = () => { retry = 0; setLiveState('online'); };
socket.onmessage = event => {
try {
+49 -8
View File
@@ -34,11 +34,11 @@ import {
updateNotificationChannel, deleteNotificationChannel, setMessageNotification, deleteMessageNotification, deleteAccountNotifications, setAccountBindings, testNotificationChannel,
updateSystemSettings,
updateShippingRule,
getChatSessions,
getChatMessages,
sendChatMessage,
getChatSessions, getChatSessionPage,
getChatMessages, getChatMessagePage,
sendChatMessage, sendChatImage,
markChatRead,
updateAccountTaskSettings,
getAccountTaskSettings, updateAccountTaskSettings,
runAccountTask, login, initializeAdmin, verifySession,
} from './api';
@@ -66,8 +66,8 @@ test('chat APIs preserve account and conversation scope', async () => {
await getChatMessages('a1', 'c1', 9);
await sendChatMessage({ account_id: 'a1', chat_id: 'c1', buyer_id: 'b1', text: 'hi' });
await markChatRead('a1', 'c1');
expect(fetchMock.mock.calls[0][0]).toBe('/api/chat/sessions?account_id=a1');
expect(fetchMock.mock.calls[1][0]).toBe('/api/chat/messages?account_id=a1&chat_id=c1&before_id=9');
expect(fetchMock.mock.calls[0][0]).toBe('/api/v1/chat/sessions?account_id=a1');
expect(fetchMock.mock.calls[1][0]).toBe('/api/v1/chat/messages?account_id=a1&chat_id=c1&before_id=9');
expect(JSON.parse(fetchMock.mock.calls[2][1].body)).toMatchObject({ account_id: 'a1', chat_id: 'c1', buyer_id: 'b1' });
expect(JSON.parse(fetchMock.mock.calls[3][1].body)).toEqual({ account_id: 'a1', chat_id: 'c1' });
});
@@ -80,9 +80,9 @@ test('account task APIs keep rating and polish account-scoped', async () => {
auto_polish_enabled: true, polish_time: '03:00',
});
await runAccountTask('a1', 'auto_rate');
expect(fetchMock.mock.calls[0][0]).toBe('/api/account-tasks/a1');
expect(fetchMock.mock.calls[0][0]).toBe('/api/v1/account-tasks/a1');
expect(fetchMock.mock.calls[0][1].method).toBe('PUT');
expect(fetchMock.mock.calls[1][0]).toBe('/api/account-tasks/a1/run');
expect(fetchMock.mock.calls[1][0]).toBe('/api/v1/account-tasks/a1/run');
expect(JSON.parse(fetchMock.mock.calls[1][1].body)).toEqual({ task_type: 'auto_rate' });
});
@@ -1005,3 +1005,44 @@ const runVersionedSettingsCardNotificationAPITest = async () => {
};
test('settings, card, and notification APIs use versioned compatibility routes', runVersionedSettingsCardNotificationAPITest);
// 聊天和账号任务 API 使用版本化兼容入口。
const runVersionedChatTaskAPITest = async () => {
// fetchMock 是聊天和账号任务请求的测试替身。
const fetchMock = vi.fn()
.mockResolvedValueOnce(jsonResponse({ sessions: [], has_more: false }))
.mockResolvedValueOnce(jsonResponse({ messages: [], has_more: false }))
.mockResolvedValueOnce(jsonResponse({ sessions: [], has_more: false }))
.mockResolvedValueOnce(jsonResponse({ messages: [], has_more: false }))
.mockResolvedValueOnce(jsonResponse({ message: { message_key: 'message-1' } }))
.mockResolvedValueOnce(jsonResponse({ message: { message_key: 'message-2' } }))
.mockResolvedValueOnce(jsonResponse({ success: true }))
.mockResolvedValueOnce(jsonResponse({ account_id: 'acc1' }))
.mockResolvedValueOnce(jsonResponse({ account_id: 'acc1' }))
.mockResolvedValueOnce(jsonResponse({ success: true, summary: { task_type: 'auto_rate' } }));
vi.stubGlobal('fetch', fetchMock);
await getChatSessionPage('acc1', 3, undefined, true);
await getChatMessagePage('acc1', 'chat-1', 4, 9);
await getChatSessions('acc1');
await getChatMessages('acc1', 'chat-1', 9);
await sendChatMessage({ account_id: 'acc1', chat_id: 'chat-1', buyer_id: 'buyer-1', text: '你好' });
await sendChatImage({ account_id: 'acc1', chat_id: 'chat-1', buyer_id: 'buyer-1', image: new File(['image'], 'chat.png', { type: 'image/png' }) });
await markChatRead('acc1', 'chat-1');
await getAccountTaskSettings('acc1');
await updateAccountTaskSettings('acc1', { account_id: 'acc1', auto_rate_enabled: true, rate_content: '交易愉快', auto_polish_enabled: false, polish_time: '03:00' });
await runAccountTask('acc1', 'auto_rate');
expect(fetchMock).toHaveBeenNthCalledWith(1, '/api/v1/chat/sessions?account_id=acc1&cursor=3&refresh=1', expect.objectContaining({ method: 'GET' }));
expect(fetchMock).toHaveBeenNthCalledWith(2, '/api/v1/chat/messages?account_id=acc1&chat_id=chat-1&cursor=4&before_id=9', expect.objectContaining({ method: 'GET' }));
expect(fetchMock).toHaveBeenNthCalledWith(3, '/api/v1/chat/sessions?account_id=acc1', expect.objectContaining({ method: 'GET' }));
expect(fetchMock).toHaveBeenNthCalledWith(4, '/api/v1/chat/messages?account_id=acc1&chat_id=chat-1&before_id=9', expect.objectContaining({ method: 'GET' }));
expect(fetchMock).toHaveBeenNthCalledWith(5, '/api/v1/chat/messages', expect.objectContaining({ method: 'POST' }));
expect(fetchMock).toHaveBeenNthCalledWith(6, '/api/v1/chat/images', expect.objectContaining({ method: 'POST', body: expect.any(FormData) }));
expect(fetchMock).toHaveBeenNthCalledWith(7, '/api/v1/chat/read', expect.objectContaining({ method: 'POST' }));
expect(fetchMock).toHaveBeenNthCalledWith(8, '/api/v1/account-tasks/acc1', expect.objectContaining({ method: 'GET' }));
expect(fetchMock).toHaveBeenNthCalledWith(9, '/api/v1/account-tasks/acc1', expect.objectContaining({ method: 'PUT' }));
expect(fetchMock).toHaveBeenNthCalledWith(10, '/api/v1/account-tasks/acc1/run', expect.objectContaining({ method: 'POST' }));
};
test('chat and account task APIs use versioned compatibility routes', runVersionedChatTaskAPITest);
+8 -8
View File
@@ -98,18 +98,18 @@ export const getAccountDetails = async (options?: RequestControlOptions): Promis
};
export const getAccountTaskSettings = async (id: string): Promise<AccountTaskSettingsResponse> =>
get(`/api/account-tasks/${id}`);
get(`/api/v1/account-tasks/${id}`);
export const updateAccountTaskSettings = async (id: string, settings: AccountTaskSettings): Promise<AccountTaskSettingsResponse> =>
put(`/api/account-tasks/${id}`, settings);
put(`/api/v1/account-tasks/${id}`, settings);
export const runAccountTask = async (id: string, taskType: 'auto_rate' | 'auto_polish'): Promise<AccountTaskRunResponseEnvelope> =>
post(`/api/account-tasks/${id}/run`, { task_type: taskType }, { timeoutMs: 120_000 });
post(`/api/v1/account-tasks/${id}/run`, { task_type: taskType }, { timeoutMs: 120_000 });
export interface ChatSessionPage { sessions: ChatSession[]; has_more: boolean; next_cursor?: number }
export const getChatSessionPage = async (accountId: string, cursor?: number, options?: RequestControlOptions, refresh = false): Promise<ChatSessionPage> => {
const result = await get<ChatSessionPage>('/api/chat/sessions', { account_id: accountId, cursor, refresh: refresh ? 1 : undefined },
const result = await get<ChatSessionPage>('/api/v1/chat/sessions', { account_id: accountId, cursor, refresh: refresh ? 1 : undefined },
refresh ? { timeoutMs: 60_000, ...options } : options);
return { sessions: result.sessions || [], has_more: result.has_more === true, next_cursor: result.next_cursor };
};
@@ -125,7 +125,7 @@ export interface ChatMessagePage {
}
export const getChatMessagePage = async (accountId: string, chatId: string, cursor?: number, beforeId?: number, options?: RequestControlOptions): Promise<ChatMessagePage> => {
const result = await get<ChatMessagePage>('/api/chat/messages', {
const result = await get<ChatMessagePage>('/api/v1/chat/messages', {
account_id: accountId, chat_id: chatId, cursor, before_id: beforeId,
}, options);
return { messages: result.messages || [], has_more: result.has_more === true, next_cursor: result.next_cursor, session: result.session };
@@ -137,7 +137,7 @@ export const getChatMessages = async (accountId: string, chatId: string, beforeI
export const sendChatMessage = async (input: {
account_id: string; chat_id: string; buyer_id: string; buyer_name?: string;
item_id?: string; item_title?: string; text: string;
}): Promise<{message: ChatMessage}> => post('/api/chat/messages', input);
}): Promise<{message: ChatMessage}> => post('/api/v1/chat/messages', input);
export const sendChatImage = async (input: {
account_id: string; chat_id: string; buyer_id: string; buyer_name?: string;
@@ -145,11 +145,11 @@ export const sendChatImage = async (input: {
}): Promise<{message: ChatMessage}> => {
const form = new FormData();
Object.entries(input).forEach(([key, value]) => form.append(key, value));
return postForm('/api/chat/images', form, { timeoutMs: 120_000 });
return postForm('/api/v1/chat/images', form, { timeoutMs: 120_000 });
};
export const markChatRead = async (accountId: string, chatId: string): Promise<ApiResponse> =>
post('/api/chat/read', { account_id: accountId, chat_id: chatId });
post('/api/v1/chat/read', { account_id: accountId, chat_id: chatId });
export interface AccountRuntimeStatus {
state: NonNullable<AccountDetail['runtime_state']>;
@@ -0,0 +1,69 @@
package server
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// chatTaskRouteCase 描述一个聊天或账号任务兼容路由测试样例。
type chatTaskRouteCase struct {
// name 是测试样例名称。
name string
// method 是请求使用的 HTTP 方法。
method string
// versionedPath 是版本化入口路径。
versionedPath string
// legacyPath 是旧兼容入口路径。
legacyPath string
// body 是两条入口共用的请求体。
body string
// wantStatus 是两条入口应返回的状态码。
wantStatus int
}
// requestChatTaskRoute 发送带认证会话的聊天或账号任务请求并返回状态码。
func requestChatTaskRoute(t *testing.T, handler http.Handler, sessionCookie *http.Cookie, method, path, body string) int {
t.Helper()
// request 是当前聊天或账号任务兼容入口请求。
request := httptest.NewRequest(method, path, strings.NewReader(body))
request.AddCookie(sessionCookie)
// recorder 是捕获兼容入口响应的记录器。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
return recorder.Code
}
// TestVersionedChatTaskRoutesPreserveLegacyContracts 验证聊天和账号任务入口复用旧 handler 与权限边界。
func TestVersionedChatTaskRoutesPreserveLegacyContracts(t *testing.T) {
// srv 是用于验证聊天与账号任务路由的 HTTP 测试服务。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// handler 是当前测试使用的完整路由树。
handler := srv.Router()
// sessionCookie 是管理员登录后得到的认证会话。
sessionCookie := loginHelper(t, handler)
// cases 是覆盖版本化与旧路径状态码兼容性的测试样例集合。
cases := []chatTaskRouteCase{
{name: "chat-sessions-missing-account", method: http.MethodGet, versionedPath: "/api/v1/chat/sessions?account_id=missing", legacyPath: "/api/chat/sessions?account_id=missing", wantStatus: http.StatusForbidden},
{name: "chat-messages-missing-chat", method: http.MethodGet, versionedPath: "/api/v1/chat/messages?account_id=acc1", legacyPath: "/api/chat/messages?account_id=acc1", wantStatus: http.StatusBadRequest},
{name: "chat-message-service-disabled", method: http.MethodPost, versionedPath: "/api/v1/chat/messages", legacyPath: "/api/chat/messages", body: `{}`, wantStatus: http.StatusServiceUnavailable},
{name: "chat-image-service-disabled", method: http.MethodPost, versionedPath: "/api/v1/chat/images", legacyPath: "/api/chat/images", wantStatus: http.StatusServiceUnavailable},
{name: "chat-read-invalid", method: http.MethodPost, versionedPath: "/api/v1/chat/read", legacyPath: "/api/chat/read", body: `{}`, wantStatus: http.StatusBadRequest},
{name: "chat-websocket-service-disabled", method: http.MethodGet, versionedPath: "/api/v1/chat/ws", legacyPath: "/api/chat/ws", wantStatus: http.StatusServiceUnavailable},
{name: "account-task-settings-missing", method: http.MethodGet, versionedPath: "/api/v1/account-tasks/missing", legacyPath: "/api/account-tasks/missing", wantStatus: http.StatusForbidden},
{name: "account-task-settings-invalid", method: http.MethodPut, versionedPath: "/api/v1/account-tasks/acc1", legacyPath: "/api/account-tasks/acc1", body: `{"auto_rate_enabled":true,"rate_content":"","auto_polish_enabled":false,"polish_time":"03:00"}`, wantStatus: http.StatusBadRequest},
{name: "account-task-runs-missing", method: http.MethodGet, versionedPath: "/api/v1/account-tasks/missing/runs", legacyPath: "/api/account-tasks/missing/runs", wantStatus: http.StatusForbidden},
{name: "account-task-run-service-disabled", method: http.MethodPost, versionedPath: "/api/v1/account-tasks/acc1/run", legacyPath: "/api/account-tasks/acc1/run", body: `{}`, wantStatus: http.StatusServiceUnavailable},
}
for _, routeCase := range cases { // routeCase 是当前正在执行的聊天或账号任务路由样例。
// versionedStatus 是版本化入口实际返回的状态码。
versionedStatus := requestChatTaskRoute(t, handler, sessionCookie, routeCase.method, routeCase.versionedPath, routeCase.body)
// legacyStatus 是旧兼容入口实际返回的状态码。
legacyStatus := requestChatTaskRoute(t, handler, sessionCookie, routeCase.method, routeCase.legacyPath, routeCase.body)
if versionedStatus != routeCase.wantStatus || legacyStatus != routeCase.wantStatus {
t.Errorf("%s status versioned=%d legacy=%d want=%d", routeCase.name, versionedStatus, legacyStatus, routeCase.wantStatus)
}
}
}
@@ -0,0 +1,27 @@
package server
import (
"github.com/go-chi/chi/v5"
"xianyu-go/internal/auth"
)
// mountVersionedChatTaskRoutes 挂载聊天和账号任务的 `/api/v1` 兼容入口。
func (s *Server) mountVersionedChatTaskRoutes(r chi.Router) {
r.Group(func(r chi.Router) {
r.Use(s.Auth.Middleware)
r.Use(auth.RequireAuth)
r.Get("/api/v1/chat/sessions", s.listChatSessions)
r.Get("/api/v1/chat/messages", s.listChatMessages)
r.Post("/api/v1/chat/messages", s.sendChatMessage)
r.Post("/api/v1/chat/images", s.sendChatImage)
r.Post("/api/v1/chat/read", s.markChatRead)
r.Get("/api/v1/chat/ws", s.chatWebSocket)
r.Get("/api/v1/account-tasks/{cid}", s.getAccountTaskSettings)
r.Put("/api/v1/account-tasks/{cid}", s.updateAccountTaskSettings)
r.Get("/api/v1/account-tasks/{cid}/runs", s.listAccountTaskRuns)
r.Post("/api/v1/account-tasks/{cid}/run", s.runAccountTask)
})
}
@@ -11,6 +11,7 @@ func (s *Server) mountHealthAndVersionedRoutes(r chi.Router) {
s.mountVersionedItems(r)
s.mountVersionedItemBatchRoutes(r)
s.mountVersionedSettingsCardNotificationRoutes(r)
s.mountVersionedChatTaskRoutes(r)
}
// mountVersionedSession 挂载会话 API 的 `/api/v1` 兼容入口,复用现有 handler。
@@ -1,4 +1,4 @@
import{j as e,r,c as ys,b as qe,d as Wa}from"./react-vendor-C_od1ZSF.js";import{L as Ja,U as ha,M as is,C as os,B as ga,S as ba,Z as cs,a as jt,b as js,G as As,c as Ns,d as _s,e as Va,f as rt,A as $s,D as Qa,g as Ps,P as fa,h as qt,E as ya,T as Ga,i as Ka,j as Pe,X as Me,k as Ha,l as Za,m as vs,n as ja,o as He,Q as Xt,p as xt,q as Ke,r as yt,s as Tt,t as Rs,R as ze,u as Na,v as Ya,w as Qe,K as Xa,x as dt,y as lt,z as et,F as Es,H as _t,I as Nt,J as Dt,N as _a,O as el,V as Ds,W as Ts,Y as tl,_ as sl,$ as al,a0 as ll,a1 as es,a2 as Bt,a3 as ds,a4 as rl,a5 as nl,a6 as xs,a7 as Ms,a8 as il,a9 as ol,aa as Mt,ab as qs,ac as Gt,ad as va,ae as cl,af as dl,ag as Zt,ah as wa,ai as xl,aj as ml,ak as pl,al as ul,am as hl,an as gl,ao as Fs}from"./icons-vendor-BpMgNNfy.js";import{R as zt,B as bl,X as Bs,Y as zs,T as Ut,a as fl,C as ts,A as yl,b as jl,c as Nl,P as Us,d as Ws,L as _l}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";(function(){const a=document.createElement("link").relList;if(a&&a.supports&&a.supports("modulepreload"))return;for(const m of document.querySelectorAll('link[rel="modulepreload"]'))i(m);new MutationObserver(m=>{for(const _ of m)if(_.type==="childList")for(const N of _.addedNodes)N.tagName==="LINK"&&N.rel==="modulepreload"&&i(N)}).observe(document,{childList:!0,subtree:!0});function l(m){const _={};return m.integrity&&(_.integrity=m.integrity),m.referrerPolicy&&(_.referrerPolicy=m.referrerPolicy),m.crossOrigin==="use-credentials"?_.credentials="include":m.crossOrigin==="anonymous"?_.credentials="omit":_.credentials="same-origin",_}function i(m){if(m.ep)return;m.ep=!0;const _=l(m);fetch(m.href,_)}})();const vl=({className:t="w-full h-full text-white"})=>e.jsx("svg",{className:t,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),ms=({sizeClass:t="w-12 h-12",logoClassName:a="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${t} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgb(var(--color-brand))"}),e.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23Line truncated
import{j as e,r,c as ys,b as qe,d as Wa}from"./react-vendor-C_od1ZSF.js";import{L as Ja,U as ha,M as is,C as os,B as ga,S as ba,Z as cs,a as jt,b as js,G as As,c as Ns,d as _s,e as Va,f as rt,A as $s,D as Qa,g as Ps,P as fa,h as qt,E as ya,T as Ga,i as Ka,j as Pe,X as Me,k as Ha,l as Za,m as vs,n as ja,o as He,Q as Xt,p as xt,q as Ke,r as yt,s as Tt,t as Rs,R as ze,u as Na,v as Ya,w as Qe,K as Xa,x as dt,y as lt,z as et,F as Es,H as _t,I as Nt,J as Dt,N as _a,O as el,V as Ds,W as Ts,Y as tl,_ as sl,$ as al,a0 as ll,a1 as es,a2 as Bt,a3 as ds,a4 as rl,a5 as nl,a6 as xs,a7 as Ms,a8 as il,a9 as ol,aa as Mt,ab as qs,ac as Gt,ad as va,ae as cl,af as dl,ag as Zt,ah as wa,ai as xl,aj as ml,ak as pl,al as ul,am as hl,an as gl,ao as Fs}from"./icons-vendor-BpMgNNfy.js";import{R as zt,B as bl,X as Bs,Y as zs,T as Ut,a as fl,C as ts,A as yl,b as jl,c as Nl,P as Us,d as Ws,L as _l}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";(function(){const a=document.createElement("link").relList;if(a&&a.supports&&a.supports("modulepreload"))return;for(const m of document.querySelectorAll('link[rel="modulepreload"]'))i(m);new MutationObserver(m=>{for(const _ of m)if(_.type==="childList")for(const N of _.addedNodes)N.tagName==="LINK"&&N.rel==="modulepreload"&&i(N)}).observe(document,{childList:!0,subtree:!0});function l(m){const _={};return m.integrity&&(_.integrity=m.integrity),m.referrerPolicy&&(_.referrerPolicy=m.referrerPolicy),m.crossOrigin==="use-credentials"?_.credentials="include":m.crossOrigin==="anonymous"?_.credentials="omit":_.credentials="same-origin",_}function i(m){if(m.ep)return;m.ep=!0;const _=l(m);fetch(m.href,_)}})();const vl=({className:t="w-full h-full text-white"})=>e.jsx("svg",{className:t,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),ms=({sizeClass:t="w-12 h-12",logoClassName:a="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${t} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgb(var(--color-brand))"}),e.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23Line truncated
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(js,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:n,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:Y,children:"取消"}),e.jsxs("button",{onClick:ut,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:Y,children:[Y?e.jsx(Pe,{className:"w-4 h-4 animate-spin"}):e.jsx(He,{className:"w-4 h-4"}),Y?"保存中...":"保存"]})]})})]})}),document.body)]})},nn=t=>({total:Number((t==null?void 0:t.total)||0),success_count:Number((t==null?void 0:t.success_count)||0),failed_count:Number((t==null?void 0:t.failed_count)||0),results:Array.isArray(t==null?void 0:t.results)?t.results.map(a=>({order_id:String((a==null?void 0:a.order_id)||"unknown"),success:(a==null?void 0:a.success)===!0,message:String((a==null?void 0:a.message)||"")})):[]}),on=t=>(t==null?void 0:t.results.filter(a=>!a.success))||[],sa=({status:t})=>{const a={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-brand text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},l={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${a[t]||a.cancelled}`,children:l[t]||t})},cn=()=>{const[t,a]=r.useState([]),[l,i]=r.useState([]),[m,_]=r.useState([]),[N,R]=r.useState({}),[g,C]=r.useState("all"),[j,F]=r.useState(""),[G,me]=r.useState(""),[oe,v]=r.useState(""),q=r.useRef(0),[ce,Q]=r.useState(1),[ee,B]=r.useState(1),[ge,ue]=r.useState(!1),[k,Z]=r.useState(!1),[se,K]=r.useState(!1),[ve,J]=r.useState(!1),[I,E]=r.useState(null),[$,be]=r.useState(null),[Re,ae]=r.useState({}),[T,p]=r.useState(!1),[b,U]=r.useState(""),[M,ne]=r.useState(!1),[he,ye]=r.useState(null),[Ee,ke]=r.useState(null),[x,V]=r.useState(null),[X,c]=r.useState(!1),[d,D]=r.useState(null),[S,Y]=r.useState(null),O=async()=>{const u=++q.current;ue(!0);try{const L=await tr(j||void 0,g,ce,20,oe);if(u!==q.current)return;a(L.data),B(L.total_pages)}catch(L){console.error("加载订单失败:",L)}finally{u===q.current&&ue(!1)}},de=(u,L,le)=>{if(le&&le.trim())return le;if(N[`${u}:${L}`])return N[`${u}:${L}`];const Ne=l.find(Ue=>{if(le&&Ue.item_title){const Fe=le.toLowerCase(),tt=Ue.item_title.toLowerCase();return tt.includes(Fe)||Fe.includes(tt)}return!1});return Ne!=null&&Ne.item_title?Ne.item_title:"未知商品"},Se=u=>{const L={};u.forEach(le=>{le.item_id&&(L[`${le.cookie_id}:${le.item_id}`]=le.item_title||le.item_id)}),R(L)};r.useEffect(()=>{const u=window.setTimeout(()=>{Q(1),v(G.trim())},300);return()=>window.clearTimeout(u)},[G]),r.useEffect(()=>{O()},[j,g,ce,oe]),r.useEffect(()=>{Promise.all([Ft(),vt()]).then(([u,L])=>{_(u),i(L),Se(L)}).catch(u=>{console.error("加载商品列表失败:",u)})},[]);const fe=r.useMemo(()=>new Map(m.map(u=>[u.id,u])),[m]),Oe=u=>{const L=fe.get(u),le=(L==null?void 0:L.remark)||(L==null?void 0:L.nickname);return le?`${le} · ${u.slice(0,6)}`:`账号 ${u.slice(0,8)}`},re=u=>{const L=fe.get(u);return(L==null?void 0:L.remark)||(L==null?void 0:L.nickname)||"未命名账号"},h=async()=>{ue(!0);try{const u=await lr(j||void 0,g);await O(),u!=null&&u.message&&alert(u.message)}catch(u){console.error("同步订单失败:",u),alert((u==null?void 0:u.message)||"同步失败,请重试")}finally{ue(!1)}},f=u=>{U(u),ye(null),p(!0)},P=async u=>{var L;ne(!0),ye(null);try{const le=await nr([b],u),Ne=(L=le==null?void 0:le.results)==null?void 0:L[0];Ne!=null&&Ne.success?(ye({success:!0,message:Ne.message}),O()):ye({success:!1,message:(Ne==null?void 0:Ne.message)||"发货失败"})}catch(le){ye({success:!1,message:(le==null?void 0:le.message)||"请求失败"})}finally{ne(!1)}},z=u=>{E(u),Z(!0)},Ie=u=>{be({...u}),K(!0)},Ae=async()=>{if(!(!$||!$.order_id))try{const u={};$.status!==void 0&&(u.order_status=$.status),$.buyer_id!==void 0&&(u.buyer_id=$.buyer_id),$.amount!==void 0&&(u.amount=$.amount),$.receiver_name!==void 0&&(u.receiver_name=$.receiver_name),$.receiver_phone!== Line truncated
VIP-MONTH-002
@@ -16,4 +16,4 @@ CODE-789012
`).filter(x=>x.trim()).length})," 条"]})]}),j.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:j.api_method,onChange:x=>F({...j,api_method:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:j.api_timeout,onChange:x=>F({...j,api_timeout:parseInt(x.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:j.api_headers,onChange:x=>F({...j,api_headers:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:j.api_params,onChange:x=>F({...j,api_params:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:j.description,onChange:x=>F({...j,description:x.target.value}),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:j.delay_seconds,onChange:x=>F({...j,delay_seconds:parseInt(x.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>_(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:p,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(et,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),G&&qe.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:()=>me(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(Me,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[e.jsxs("button",{onClick:()=>v("create"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${oe==="create"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(tl,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:()=>v("append"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${oe==="append"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Dt,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),oe==="create"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5",children:["上传表格,每行一个卡密组。表头:",e.jsx("code",{className:"bg-blue-100/70 px-1.5 py-0.5 rounded",children:"名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值"}),'。 类型填 text/data/image;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。']}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:he,className:"px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm tran Line truncated
VIP-002
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsx("p",{className:"text-xs text-gray-500",children:"一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。"})]}),K&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",K.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:()=>me(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),oe==="create"?e.jsxs("button",{onClick:ye,disabled:!q||B,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[B?e.jsx(Pe,{className:"w-4 h-4 animate-spin"}):e.jsx(Dt,{className:"w-4 h-4"}),B?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:Ee,disabled:!ue||!Z.trim()||B||M.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[B?e.jsx(Pe,{className:"w-4 h-4 animate-spin"}):e.jsx(et,{className:"w-4 h-4"}),B?"处理中...":"追加卡密"]})]})]})}),document.body)]})},mn=t=>t.find(a=>a.status==="running"||a.status==="canceling"),la="ydisks-amap-js-api",pn="c9b68d4ce9a2a97f22a4a439404488ca";let $t=null;const un=()=>pn,hn=()=>window.AMap?Promise.resolve(window.AMap):$t||($t=new Promise((t,a)=>{const l=document.getElementById(la),i=l||document.createElement("script"),m=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(N)},_=()=>{window.AMap?(m(),t(window.AMap)):(m(),a(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},N=window.setTimeout(()=>{m(),a(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=_,i.id=la,i.async=!0,i.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(un())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,i.onerror=()=>{m(),a(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},l||document.head.appendChild(i)}).catch(t=>{throw $t=null,t}),$t),Ht=t=>Number.isFinite(t)&&t!==0,gn=t=>{var m,_;const a=Number((m=t.location)==null?void 0:m.lng),l=Number((_=t.location)==null?void 0:_.lat),i={area:String(t.adname||"").trim(),city:String(t.cityname||"").trim(),division_id:String(t.adcode||"").trim(),longitude:a,latitude:l,poi_id:String(t.id||"").trim(),poi_name:String(t.name||"").trim(),province:String(t.pname||"").trim()};return!i.division_id||!i.province||!i.city||!i.poi_id||!i.poi_name||!Ht(a)||!Ht(l)||a<-180||a>180||l<-90||l>90?null:i},bn=async(t,a)=>{if(!Ht(t)||!Ht(a)||t<-180||t>180||a<-90||a>90)throw new Error("经纬度无效");const l=await hn();return new Promise((i,m)=>{new l.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[t,a],1e3,(N,R)=>{var C;if(N!=="complete"){if(N==="no_data"){i([]);return}m(new Error("高德地图附近地址查询失败,请稍后重试"));return}const g=(((C=R==null?void 0:R.poiList)==null?void 0:C.pois)||[]).map(gn).filter(j=>j!==null);i(g)})})},fn=t=>{const a=String(t||"").trim();return a?/^[¥¥]/.test(a)?a:`¥${a}`:"-"},yn=({onConfigureDelivery:t})=>{const[a,l]=r.useState([]),[i,m]=r.useState([]),[_,N]=r.useState([]),[R,g]=r.useState(""),[C,j]=r.useState(""),[F,G]=r.useState(!1),[me,oe]=r.useState(!1),[v,q]=r.useState(!1),[ce,Q]=r.useState(!1),[ee,B]=r.useState(!1),[ge,ue]=r.useState(!1),[k,Z]=r.useState(!1),[se,K]=r.useState("upload"),[ve,J]=r.useState(null),[I,E]=r.useState(null),[$,be]=r.useState(""),[Re,ae]=r.useState(!1),[T,p]=r.useState(!1),[b,U]=r.useState([]),[M,ne]=r.useState(null),[he,ye]=r.useState([]),[Ee,ke]=r.useState(null),[x,V]=r.useState({catId:"",catName:"",channelCatId:"",tbCatId:""}),[X,c]=r.useState(null),[d,D]=r.useState(null),[S,Y]=r.useState(null),O=r.useRef(!1),[de,Se]=r.useState(null),[fe,Oe]=r.useState({}),[re,h]=r.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[f,P]=r.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),[z,Ie]=r.useState([]);r.useEffect(()=>{if(!ge||f.images.length===0){Ie([]);return}const n=f.images.map((w,H)=>({key:w.name+H,url:URL.createObjectURL(w)}));return Ie(n),()=>{n.forEach(w=>URL.revokeObjectURL(w.url))}},[ge,f.images]);const Ae=async()=>{const n=await vt();l(n)},we=async()=>{m(await gs())};r.useEffect(()=>{Promise.all([Ft(),vt(),gs(),Hs(20)]).then(([n,w,H,Te])=>{N(n),l(w),m(H);const s=Te.find(o=>["running","canceling"].includes(o.status))||Te.find(o=>o.status!=="preview");Y(s||null)}).catch(n=>console.error("加载商品配置失败:",n))},[]),r.useEffect(()=>{if(!k||!(d!=null&&d.id)||!["running","canceling"].includes(d.status))return;const n=window.setInterval(async()=>{if(!O.current){O.current=!0;try{const w=await bt(d.id);D(w),Y(w),[ Line truncated
`),Te=new Blob(["\uFEFF"+H],{type:"text/csv;charset=utf-8"}),s=URL.createObjectURL(Te),o=document.createElement("a");o.href=s,o.download="批量铺货模板.csv",document.body.appendChild(o),o.click(),o.remove(),URL.revokeObjectURL(s)},Lt=()=>{h(n=>({...n,cookie_id:R||n.cookie_id})),B(!0)},nt=()=>{P(n=>({...n,cookie_id:R||n.cookie_id})),ue(!0)},it=async n=>{if(!(n?R:f.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");p(!0),navigator.geolocation.getCurrentPosition(async H=>{try{const Te=await bn(H.coords.longitude,H.coords.latitude);if(!Te.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");n?(ye(Te),ke(Te[0])):(U(Te),ne(Te[0]))}catch(Te){alert((Te==null?void 0:Te.message)||"获取发货地失败")}finally{p(!1)}},H=>{p(!1),alert(H.code===H.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},Ot=n=>i.filter(w=>w.cookie_id===n.cookie_id&&w.item_id===n.item_id).length>0?i.filter(w=>w.cookie_id===n.cookie_id&&w.item_id===n.item_id):i.filter(w=>w.cookie_id===n.cookie_id&&!w.item_id),pt=n=>{switch(n){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"canceling":return"正在安全取消";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":return"部分失败";case"canceled":return"已取消";default:return n||"-"}},ut=n=>{switch(n){case"success":case"completed":return"bg-emerald-50 text-emerald-700 border-emerald-100";case"partially_failed":case"failed":return"bg-red-50 text-red-700 border-red-100";case"running":return"bg-blue-50 text-blue-700 border-blue-100";case"canceled":return"bg-gray-100 text-gray-600 border-gray-200";default:return"bg-amber-50 text-amber-700 border-amber-100"}},st=r.useMemo(()=>new Map(_.map(n=>[n.id,n])),[_]),ht=r.useMemo(()=>C?a.filter(n=>n.cookie_id===C):a,[C,a]),Ge=n=>{const w=st.get(n),H=(w==null?void 0:w.remark)||(w==null?void 0:w.nickname);return H?`${H} · ${n.slice(0,6)}`:`账号 ${n.slice(0,8)}`},ot=n=>{const w=st.get(n);return(w==null?void 0:w.remark)||(w==null?void 0:w.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(ll,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-account-filter","aria-label":"按账号筛选商品列表",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:C,onChange:n=>j(n.target.value),children:[e.jsx("option",{value:"",children:"全部账号"}),_.map(n=>e.jsx("option",{value:n.id,children:Ge(n.id)},n.id))]})]})]}),e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-sync-account",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"同步商品账号"}),e.jsxs("div",{className:"relative",children:[e.jsx(xt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-sync-account","aria-label":"选择要同步商品的账号",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:R,onChange:n=>g(n.target.value),children:[e.jsx("option",{value:"",children:"请选择账号"}),_.map(n=>e.jsx("option",{value:n.id,children:Ge(n.id)},n.id))]})]})]}),e.jsxs("button",{onClick:De,disabled:F||!R,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(ze,{className:`w-4 h-4 ${F?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:Lt,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(et,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:nt,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-500 text-white hover:bg-emerald-600 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(es,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void Ne(),className:"px-5 py-3 rounded-2xl font-bold bg-brand text-white Line truncated
`),Te=new Blob(["\uFEFF"+H],{type:"text/csv;charset=utf-8"}),s=URL.createObjectURL(Te),o=document.createElement("a");o.href=s,o.download="批量铺货模板.csv",document.body.appendChild(o),o.click(),o.remove(),URL.revokeObjectURL(s)},Lt=()=>{h(n=>({...n,cookie_id:R||n.cookie_id})),B(!0)},nt=()=>{P(n=>({...n,cookie_id:R||n.cookie_id})),ue(!0)},it=async n=>{if(!(n?R:f.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");p(!0),navigator.geolocation.getCurrentPosition(async H=>{try{const Te=await bn(H.coords.longitude,H.coords.latitude);if(!Te.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");n?(ye(Te),ke(Te[0])):(U(Te),ne(Te[0]))}catch(Te){alert((Te==null?void 0:Te.message)||"获取发货地失败")}finally{p(!1)}},H=>{p(!1),alert(H.code===H.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},Ot=n=>i.filter(w=>w.cookie_id===n.cookie_id&&w.item_id===n.item_id).length>0?i.filter(w=>w.cookie_id===n.cookie_id&&w.item_id===n.item_id):i.filter(w=>w.cookie_id===n.cookie_id&&!w.item_id),pt=n=>{switch(n){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"canceling":return"正在安全取消";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":return"部分失败";case"canceled":return"已取消";default:return n||"-"}},ut=n=>{switch(n){case"success":case"completed":return"bg-emerald-50 text-emerald-700 border-emerald-100";case"partially_failed":case"failed":return"bg-red-50 text-red-700 border-red-100";case"running":return"bg-blue-50 text-blue-700 border-blue-100";case"canceled":return"bg-gray-100 text-gray-600 border-gray-200";default:return"bg-amber-50 text-amber-700 border-amber-100"}},st=r.useMemo(()=>new Map(_.map(n=>[n.id,n])),[_]),ht=r.useMemo(()=>C?a.filter(n=>n.cookie_id===C):a,[C,a]),Ge=n=>{const w=st.get(n),H=(w==null?void 0:w.remark)||(w==null?void 0:w.nickname);return H?`${H} · ${n.slice(0,6)}`:`账号 ${n.slice(0,8)}`},ot=n=>{const w=st.get(n);return(w==null?void 0:w.remark)||(w==null?void 0:w.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(ll,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-account-filter","aria-label":"按账号筛选商品列表",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:C,onChange:n=>j(n.target.value),children:[e.jsx("option",{value:"",children:"全部账号"}),_.map(n=>e.jsx("option",{value:n.id,children:Ge(n.id)},n.id))]})]})]}),e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-sync-account",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"同步商品账号"}),e.jsxs("div",{className:"relative",children:[e.jsx(xt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-sync-account","aria-label":"选择要同步商品的账号",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:R,onChange:n=>g(n.target.value),children:[e.jsx("option",{value:"",children:"请选择账号"}),_.map(n=>e.jsx("option",{value:n.id,children:Ge(n.id)},n.id))]})]})]}),e.jsxs("button",{onClick:De,disabled:F||!R,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(ze,{className:`w-4 h-4 ${F?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:Lt,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(et,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:nt,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-500 text-white hover:bg-emerald-600 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(es,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void Ne(),className:"px-5 py-3 rounded-2xl font-bold bg-brand text-white Line truncated
+1 -1
View File
@@ -6,7 +6,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ydisks闲鱼助手 - 自动发货与管家系统</title>
<meta name="description" content="Ydisks闲鱼助手 - 自动回复、自动发货、订单管理、AI智能议价一体化解决方案" />
<script type="module" crossorigin src="/static/assets/index-CVnL93T4.js"></script>
<script type="module" crossorigin src="/static/assets/index-o2hq0dGH.js"></script>
<link rel="modulepreload" crossorigin href="/static/assets/react-vendor-C_od1ZSF.js">
<link rel="modulepreload" crossorigin href="/static/assets/icons-vendor-BpMgNNfy.js">
<link rel="modulepreload" crossorigin href="/static/assets/vendor-D-Edl3pr.js">