diff --git a/docs/slider-captcha-frozen-spec.md b/docs/slider-captcha-frozen-spec.md index 88163b7..967aaf2 100644 --- a/docs/slider-captcha-frozen-spec.md +++ b/docs/slider-captcha-frozen-spec.md @@ -207,6 +207,17 @@ Playwright 主引擎 - `CAPTCHA_REAL_MOUSE=true` 在当前 Go/Docker 实现中只记录物理鼠标不可用,并继续备用逻辑;不得假装已启用物理鼠标。 - `CAPTCHA_DRISSIONPAGE_FALLBACK_ENABLED` 默认为启用。 - 备用引擎成功返回的引擎标识保持为 `drissionpage`,虽然底层实现是直接 Chromium + CDP。 +- `CAPTCHA_IGNORE_CERT_ERRORS` 默认关闭。仅当运行环境存在 TLS 检查代理、且诊断明确记录 + Alibaba 风控资源出现 `ERR_CERT_AUTHORITY_INVALID` 时,才允许显式设为 `true`;此时主引擎和 + 备用 Chromium 都追加 `--ignore-certificate-errors`,HTTP 客户端仍保持正常证书校验。该开关 + 必须记录在部署配置中,不能默认开启或静默改变。 +- 初始化时必须从随包 Chromium 实测 UA 和 Client Hints。无头上下文只允许把 legacy UA 中的 + `HeadlessChrome/<实际版本>` 规范化为 `Chrome/<相同实际版本>`;不得伪造版本、操作系统或移动端 + 状态。有头上下文不覆盖 Chromium 原生 UA。Playwright 主引擎必须同时使用 context `userAgent` + 和导航前保持连接的页面级 `Emulation.setUserAgentOverride`,后者携带从实际 Chromium 读取并去除 + 无头品牌、去重后的 `userAgentMetadata`;只设置 context `userAgent` 不合格,因为其默认 + `Sec-CH-UA` 和 `navigator.userAgentData` 仍可能包含 `HeadlessChrome`。非浏览器 HTTP 请求使用同一份 + 规范化运行时指纹。 ## 7. 备用引擎行为 @@ -219,6 +230,8 @@ Playwright 主引擎 - headless 时使用 `--headless=new`。 - 直接 Chromium 必须同时携带与当前 Playwright runtime 匹配的兼容启动参数集合(包括后台网络、扩展、Storage 分区、渲染器后台化、SwiftShader 等参数),否则通过 CDP 访问默认上下文的 Cookie Storage 可能无响应;该集合必须随 Playwright runtime 升级同步核对。 - 备用引擎对默认上下文执行 Cookie 清理、注入和读取时,每次操作最多等待 `5s`;超时必须中止当前备用引擎流程并释放浏览器,不得无限阻塞续期协程。 +- headless 时必须在导航前通过 `--user-agent` 应用同版本、已去除 `HeadlessChrome` 标记的运行时 UA; + 有头模式不得追加该覆盖。Chromium 原生 Client Hints 必须继续保留,且不得出现 `HeadlessChrome`。 - 默认总超时为 `25s`,可由现有环境变量控制;导航超时为 `15s`。 备用距离规则固定如下: @@ -248,6 +261,8 @@ Playwright 主引擎 - 最终 `left`、最终 class 或最终 X 偏移。 - 失败时的按钮 style/class、轨道 class、可见重试选择器和重试文本。 - 恢复方式是 `click` 还是 `reload`、所用选择器以及是否重新归位。 +- 诊断包的 `page_state` 必须保留页面实际看到的 `navigator.userAgent`、`navigator.webdriver`、 + `navigator.userAgentData` 基础字段及可读取的 high-entropy values,用于识别 UA/Client Hints 矛盾。 - 自动滑块最终失败时,错误文本和 `token 风控滑块处理失败` 日志的 `verification_url` 字段必须包含最后实际使用的完整验证地址(包括 query),供用户复制到本机浏览器手动验证。此字段是仅在最终失败时提供的人工接管信息;常规页面/frame 诊断日志仍必须去掉 query 与 fragment。 页面可能被浏览器扩展注入大量无关 DOM。当前仅把下列注入作为诊断信息记录,不允许它们改变滑块定位、距离或成功判定: @@ -278,6 +293,9 @@ go vet ./internal/browser ./internal/engine ./internal/account ./internal/server - 没有可见滑块、只显示直接错误提示的真实 Chromium 页面必须被识别,并且不得进入滑动或备用引擎。 - 标准 `300px` 轨道与 `42px` 按钮得到精确 `258px`。 - 旧 `x5sec` 不得判成功,新 `x5sec` 才能判成功。 +- 主 Playwright 无头上下文和直接 Chromium/CDP 无头上下文的 HTTP `User-Agent`、`Sec-CH-UA`、 + `navigator.userAgent`、`navigator.userAgentData` 都不得出现 `HeadlessChrome`/`headless` 标记,UA 中 + 的 Chrome 完整版本必须与随包 Chromium 一致。 不得删除、跳过、弱化或改写断言来让行为变化通过测试。 @@ -287,6 +305,13 @@ go vet ./internal/browser ./internal/engine ./internal/account ./internal/server 用户明确要求改变“未找到滑块时仍执行失败恢复/备用引擎”和“最终失败日志只保留脱敏页面地址”的既有契约。原因是风控页有时只显示平台错误信息而没有可操作滑块,继续 reload、拖动或切换引擎没有验证意义且会增加风控;而真实滑块自动处理失败时,用户需要完整地址在本机浏览器中接管验证。本规范第 3.1、6、8、9 节已同步纳入新的页面分类、编排、日志和集成验证要求。 +### 2026-08-17 当前授权变更 + +用户明确要求解决无头 Chromium 指纹暴露 `HeadlessChrome` 的问题。此前随包 Chromium 在服务端 +风控页中实测返回 `HeadlessChrome/149.0.7827.55`,会让 HTTP UA 与正常桌面 Chromium 身份不同。 +本规范第 6 至 9 节同步加入了只移除无头产品标记、保留实际版本与 Client Hints、覆盖主/备用引擎、 +并在诊断包及真实 Chromium 集成测试中核验页面实际指纹的契约。 + 只有用户在当前任务中明确点名要求修改滑块认证时,才允许触碰冻结范围。获得授权后也必须在同一个变更中: 1. 说明要改变本文哪一条冻结契约及原因。 diff --git a/frontend/app/features/apiAdapters.test.ts b/frontend/app/features/apiAdapters.test.ts index f935bf0..d962c1b 100644 --- a/frontend/app/features/apiAdapters.test.ts +++ b/frontend/app/features/apiAdapters.test.ts @@ -71,11 +71,11 @@ test('chat APIs preserve account and conversation scope', async () => { await getChatSessions('a1'); await getChatMessages('a1', 'c1', 9); await sendChatMessage({ account_id: 'a1', chat_id: 'c1', buyer_id: 'b1', text: 'hi' }); - await markChatRead('a1', 'c1'); + await markChatRead('a1', 'c1', [{ messageId: 'm1', sessionId: 'c1', cid: 'c1@goofish', conversationType: 1 }]); 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' }); + expect(JSON.parse(fetchMock.mock.calls[3][1].body)).toEqual({ account_id: 'a1', chat_id: 'c1', message_ids: [{ messageId: 'm1', sessionId: 'c1', cid: 'c1@goofish', conversationType: 1 }] }); } /* 回调函数负责当前业务流程。 */); test('Chat 会话、消息和发送 API 转发外部取消信号', async () => { @@ -93,7 +93,7 @@ test('Chat 会话、消息和发送 API 转发外部取消信号', async () => { await getChatMessagePage('a1', 'c1', undefined, undefined, { signal: controller.signal }); await sendChatMessage({ account_id: 'a1', chat_id: 'c1', buyer_id: 'b1', text: 'hi' }, { signal: controller.signal }); await sendChatImage({ account_id: 'a1', chat_id: 'c1', buyer_id: 'b1', image: new File(['image'], 'chat.png', { type: 'image/png' }) }, { signal: controller.signal }); - await markChatRead('a1', 'c1', { signal: controller.signal }); + await markChatRead('a1', 'c1', [], { signal: controller.signal }); expect(fetchMock).toHaveBeenNthCalledWith(1, '/api/v1/chat/sessions?account_id=a1', expect.objectContaining({ signal: expect.any(AbortSignal) })); expect(fetchMock).toHaveBeenNthCalledWith(2, '/api/v1/chat/messages?account_id=a1&chat_id=c1', expect.objectContaining({ signal: expect.any(AbortSignal) })); expect(fetchMock).toHaveBeenNthCalledWith(3, '/api/v1/chat/messages', expect.objectContaining({ signal: expect.any(AbortSignal) })); @@ -1369,7 +1369,7 @@ const runVersionedChatTaskAPITest = async () => { 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 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'); diff --git a/frontend/app/features/chat/api.ts b/frontend/app/features/chat/api.ts index 9175f11..fb26001 100644 --- a/frontend/app/features/chat/api.ts +++ b/frontend/app/features/chat/api.ts @@ -7,6 +7,7 @@ import { CookieSettingsResponse, CookieProfileResponse, ItemDetailResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, OrderRefreshResponse, OrderRefreshJobStartResponse, OrderRefreshJobStatusResponse, OrderRefreshJobCancelResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, QRLoginStatusResponse, QRLoginVerificationResponse, ValidOrderResponse, ValidOrdersResponse } from '../../../shared/api-contract'; import { collectionFrom, objectFrom } from '../../../shared/http/contract'; +import type { ChatReadReceipt } from './types'; /** 聊天账号选择器读取非敏感账号摘要。 */ export const getAccountDetails = async (options?: RequestControlOptions): Promise => get('/api/v1/accounts/details', undefined, options); @@ -68,6 +69,6 @@ export const sendChatImage = async (input: { return postForm('/api/v1/chat/images', form, { timeoutMs: 120_000, ...options }); }; -// markChatRead 标记聊天消息已读。 -export const markChatRead = async (accountId: string, chatId: string, options?: RequestControlOptions): Promise => - post('/api/v1/chat/read', { account_id: accountId, chat_id: chatId }, options); +/** 向平台确认指定会话中的入站消息已读。 */ +export const markChatRead = async (accountId: string, chatId: string, messageIDs: ChatReadReceipt[], options?: RequestControlOptions): Promise => + post('/api/v1/chat/read', { account_id: accountId, chat_id: chatId, message_ids: messageIDs }, options); diff --git a/frontend/app/features/chat/hooks.test.tsx b/frontend/app/features/chat/hooks.test.tsx index 870b54e..026805e 100644 --- a/frontend/app/features/chat/hooks.test.tsx +++ b/frontend/app/features/chat/hooks.test.tsx @@ -99,7 +99,9 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时 expect(hook.result.current.accounts[0]).toMatchObject(accountFixture); expect(hook.result.current.activeChatID).toBe('chat-1'); expect(hook.result.current.messages).toEqual([messageFixture]); - expect(markReadMock).toHaveBeenCalledWith('account-1', 'chat-1', expect.objectContaining({ signal: expect.any(AbortSignal) })); + expect(markReadMock).toHaveBeenCalledWith('account-1', 'chat-1', [ + { messageId: 'message-1', sessionId: 'chat-1', cid: 'chat-1@goofish', conversationType: 1 }, + ], expect.objectContaining({ signal: expect.any(AbortSignal) })); expect(hook.result.current.unreadForAccount('account-1')).toBe(0); await act( // emptySendAction 在没有草稿时阻止文字发送。 @@ -191,6 +193,31 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时 hook.unmount(); }); + test('会话刷新不会让当前打开会话重新显示未读', /* 当前回调验证已读状态与慢刷新响应的竞态边界。 */ async () => { + // hook 是当前会话已读后执行刷新的 Hook 渲染结果。 + const hook = renderHook( + // refreshHookFactory 创建会话刷新竞态场景。 + () => useChat(), + ); + await waitFor( + // activeChatAssertion 等待默认会话完成消息读取。 + () => expect(hook.result.current.activeChatID).toBe('chat-1'), + ); + await waitFor( + // readAssertion 等待初始消息读取将本地未读数归零。 + () => expect(hook.result.current.unreadForAccount('account-1')).toBe(0), + ); + // staleSessionPage 模拟服务端延迟返回的旧未读计数。 + const staleSessionPage = { ...sessionFixture, unread_count: 4 }; + getSessionPageMock.mockResolvedValueOnce({ sessions: [staleSessionPage], has_more: false }); + await act( + // refreshAction 执行返回旧未读数据的会话刷新。 + async () => hook.result.current.reloadSessions('account-1'), + ); + expect(hook.result.current.unreadForAccount('account-1')).toBe(0); + hook.unmount(); + }); + test('WebSocket 连接和消息事件更新聊天状态', /* 当前回调验证实时连接和消息回调边界。 */ async () => { // secondSession 是用于覆盖实时会话排序比较器的第二条会话。 const secondSession = { ...sessionFixture, chat_id: 'chat-2', last_message_at: 2, unread_count: 0 }; @@ -221,7 +248,9 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时 () => latestSocket?.onmessage?.({ data: JSON.stringify({ message: incomingMessage }) }), ); expect(hook.result.current.messages).toContainEqual(incomingMessage); - expect(markReadMock).toHaveBeenCalledWith('account-1', 'chat-1'); + expect(markReadMock).toHaveBeenCalledWith('account-1', 'chat-1', [ + { messageId: 'message-3', sessionId: 'chat-1', cid: 'chat-1@goofish', conversationType: 1 }, + ]); await act( // invalidMessageAction 触发非法消息帧并保持状态稳定。 () => latestSocket?.onmessage?.({ data: '{broken' }), diff --git a/frontend/app/features/chat/hooks.ts b/frontend/app/features/chat/hooks.ts index 1bd4968..ca2771b 100644 --- a/frontend/app/features/chat/hooks.ts +++ b/frontend/app/features/chat/hooks.ts @@ -3,7 +3,7 @@ import type React from 'react'; import type { AccountDetail, ChatMessage, ChatSession } from '../../../shared/api-contract'; import { emojiURL, renderXianyuText, xianyuEmojis } from '../../../chatEmojis'; import { getAccountDetails, getAccountRuntimeStatuses, getChatMessagePage, getChatSessionPage, markChatRead, sendChatImage, sendChatMessage } from './api'; -import { filterChatSessions, formatClock, isChatAbortError, isCurrentChatRequest, mergeLiveMessage, mergeOlderMessages, messageTime } from './state'; +import { collectChatReadReceipts, filterChatSessions, formatClock, isChatAbortError, isCurrentChatRequest, mergeLiveMessage, mergeOlderMessages, messageTime } from './state'; import type { ChatFeatureState, ChatLiveState, SessionsByAccount } from './types'; /** Chat Hook 对外暴露的状态、引用和交互动作。 */ @@ -156,10 +156,16 @@ export const useChat = (): UseChatResult => { // page 页码。 const page = await getChatSessionPage(accountID, undefined, { signal: controller.signal }, true); if (!isCurrentChatRequest(sessionSequence.current, sequence, controller.signal)) return []; - setSessionsByAccount(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, [accountID]: page.sessions })); + // sessions 保留当前打开会话的本地已读状态,避免刷新响应迟到后重新展示未读徽标。 + const sessions = page.sessions.map(/* session 按当前活跃会话覆写已读计数。 */ session => ( + accountID === activeAccountRef.current && session.chat_id === activeChatRef.current + ? { ...session, unread_count: 0 } + : session + )); + setSessionsByAccount(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, [accountID]: sessions })); setContactCursors(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, [accountID]: page.next_cursor })); setHasMoreContacts(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, [accountID]: page.has_more })); - return page.sessions; + return sessions; } catch (/* error 表示错误。 */ error) { if (isCurrentChatRequest(sessionSequence.current, sequence, controller.signal) && !isChatAbortError(error)) setError(error instanceof Error ? error.message : '同步会话失败'); return []; @@ -271,11 +277,11 @@ export const useChat = (): UseChatResult => { const controller = new AbortController(); messageController.current = controller; setMessagesLoading(true); - void Promise.all([ - getChatMessagePage(activeAccountID, activeChatID, undefined, undefined, { signal: controller.signal }), - markChatRead(activeAccountID, activeChatID, { signal: controller.signal }), - ]).then(/* 当前回调处理用户交互或异步状态变化。 */ ([page]) => { + void getChatMessagePage(activeAccountID, activeChatID, undefined, undefined, { signal: controller.signal }).then(/* 当前回调处理用户交互或异步状态变化。 */ page => { if (!isCurrentChatRequest(messageSequence.current, sequence, controller.signal)) return; + // readReceipts 只确认可被平台接受的普通入站消息。 + const readReceipts = collectChatReadReceipts(page.messages, activeChatID); + void markChatRead(activeAccountID, activeChatID, readReceipts, { signal: controller.signal }); setMessages(page.messages); setHasOlder(page.has_more); setHistoryCursor(page.next_cursor); @@ -394,12 +400,16 @@ export const useChat = (): UseChatResult => { ...row, last_message: message.content, last_message_at: message.sent_at, - unread_count: message.direction === 'incoming' && (activeAccountRef.current !== accountID || activeChatRef.current !== message.chat_id) ? row.unread_count + 1 : row.unread_count, + unread_count: message.direction === 'incoming' && message.message_type !== 'system' && (activeAccountRef.current !== accountID || activeChatRef.current !== message.chat_id) ? row.unread_count + 1 : row.unread_count, } : row).sort(/* 当前回调处理集合中的单个元素。 */ (a, b) => b.last_message_at - a.last_message_at) }; }); if (activeAccountRef.current === accountID && activeChatRef.current === message.chat_id) { setMessages(/* 当前回调处理用户交互或异步状态变化。 */ current => mergeLiveMessage(current, message)); - if (message.direction === 'incoming') void markChatRead(accountID, message.chat_id); + if (message.direction === 'incoming' && message.message_type !== 'system') { + // readReceipts 为当前实时消息生成平台要求的会话读取回执。 + const readReceipts = collectChatReadReceipts([message], message.chat_id); + void markChatRead(accountID, message.chat_id, readReceipts); + } } } catch { // 忽略非聊天格式的 WebSocket 帧,后续 REST 查询会恢复权威状态。 diff --git a/frontend/app/features/chat/state.test.ts b/frontend/app/features/chat/state.test.ts index 20d0be5..e4d88c4 100644 --- a/frontend/app/features/chat/state.test.ts +++ b/frontend/app/features/chat/state.test.ts @@ -1,6 +1,6 @@ import { expect, test } from 'vitest'; import type { ChatMessage, ChatSession } from '../../../shared/api-contract'; -import { filterChatSessions, formatClock, isChatAbortError, isCurrentChatRequest, mergeLiveMessage, mergeOlderMessages, messageTime } from './state'; +import { collectChatReadReceipts, filterChatSessions, formatClock, isChatAbortError, isCurrentChatRequest, mergeLiveMessage, mergeOlderMessages, messageTime } from './state'; // sessionFixture 是覆盖搜索、未读筛选和联系人隔离的最小会话数据。 const sessionFixture: ChatSession[] = [ @@ -11,6 +11,21 @@ const sessionFixture: ChatSession[] = [ // messageFixture 是覆盖消息去重和实时替换的最小消息数据。 const messageFixture: ChatMessage = { id: 1, account_id: 'a1', chat_id: 'c1', message_key: 'm1', direction: 'incoming', sender_id: 'b1', sender_name: '张三', message_type: 'text', content: '旧消息', status: 'received', sent_at: 1 }; +test('Chat 已读回执排除系统消息和平台内部消息', + // 已读回执测试确保接口仅接收可确认的普通入站消息。 + () => { + // messages 覆盖普通消息、系统通知、内部标记及出站消息。 + const messages: ChatMessage[] = [ + messageFixture, + { ...messageFixture, id: 2, message_key: 'in-local', message_type: 'text' }, + { ...messageFixture, id: 3, message_key: 'system-1', message_type: 'system' }, + { ...messageFixture, id: 4, message_key: 'outgoing-1', direction: 'outgoing' }, + ]; + expect(collectChatReadReceipts(messages, 'c1')).toEqual([ + { messageId: 'm1', sessionId: 'c1', cid: 'c1@goofish', conversationType: 1 }, + ]); + }); + test('Chat 会话筛选和历史消息合并保持账号内顺序', // 会话状态测试验证搜索、未读筛选和历史消息去重语义。 () => { diff --git a/frontend/app/features/chat/state.ts b/frontend/app/features/chat/state.ts index 004d533..b6da959 100644 --- a/frontend/app/features/chat/state.ts +++ b/frontend/app/features/chat/state.ts @@ -1,4 +1,19 @@ import type { ChatMessage, ChatSession } from '../../../shared/api-contract'; +import type { ChatReadReceipt } from './types'; + +/** 将可确认的普通入站消息转换为平台已读回执。 */ +export const collectChatReadReceipts = (messages: ChatMessage[], chatID: string): ChatReadReceipt[] => messages + .filter(/* currentMessage 只保留平台可接受的普通入站消息。 */ currentMessage => ( + currentMessage.direction === 'incoming' + && currentMessage.message_type !== 'system' + && !currentMessage.message_key.startsWith('in-') + )) + .map(/* currentMessage 为每条消息构造其所属会话的已读确认。 */ currentMessage => ({ + messageId: currentMessage.message_key, + sessionId: chatID, + cid: `${chatID}@goofish`, + conversationType: 1, + })); /** 按搜索条件筛选会话列表。 */ export const filterChatSessions = (sessions: ChatSession[], search: string, unreadOnly: boolean): ChatSession[] => { diff --git a/frontend/app/features/chat/types.ts b/frontend/app/features/chat/types.ts index 783a49a..974e0dd 100644 --- a/frontend/app/features/chat/types.ts +++ b/frontend/app/features/chat/types.ts @@ -6,6 +6,18 @@ export type SessionsByAccount = Record; /** Chat 实时连接状态。 */ export type ChatLiveState = 'connecting' | 'online' | 'offline'; +/** 平台已读接口要求的单条消息回执。 */ +export interface ChatReadReceipt { + /** 平台消息去重键。 */ + messageId: string; + /** 所属平台会话标识。 */ + sessionId: string; + /** 平台会话复合标识。 */ + cid: string; + /** 平台定义的单聊会话类型。 */ + conversationType: number; +} + /** Chat Hook 的状态与交互能力。 */ export type ChatFeatureState = { /** 当前启用账号列表。 */ diff --git a/frontend/shared/api-contract/index.ts b/frontend/shared/api-contract/index.ts index 1c7a565..3bf5a87 100644 --- a/frontend/shared/api-contract/index.ts +++ b/frontend/shared/api-contract/index.ts @@ -199,6 +199,10 @@ export interface ChatMessage { content: string; /** 消息发送状态。 */ status: 'received' | 'sending' | 'sent' | 'failed'; + /** 平台已读状态;旧消息可能没有该字段。 */ + read_status?: number; + /** 平台确认已读的 Unix 秒时间戳;未确认时省略。 */ + read_at?: number; /** 消息发送时间的 Unix 秒。 */ sent_at: number; } diff --git a/internal/adapter/adapter.go b/internal/adapter/adapter.go index 710fafe..5d73e19 100644 --- a/internal/adapter/adapter.go +++ b/internal/adapter/adapter.go @@ -25,6 +25,7 @@ import ( "xianyu-go/internal/renewal" "xianyu-go/internal/xianyu/cookierefresh" "xianyu-go/internal/xianyu/mtop" + "xianyu-go/internal/xianyu/protocol" xrenew "xianyu-go/internal/xianyu/renew" ) @@ -82,9 +83,20 @@ type Adapter struct { orderFetchMu sync.Mutex lastOrderFetch time.Time - // passwordCoordinator 按账号协调协议凭证恢复,避免重复外部续期并允许不同账号并行执行。 passwordCoordinator *accountapp.CredentialRefreshCoordinator + // passwordResultMu 仅保护 passwordResults;持锁期间不执行凭证读取或平台 I/O。 + passwordResultMu sync.Mutex + // passwordResults 保存正在执行的协议续期结果,后到调用方可等待同一账号的结果。 + passwordResults map[string]*passwordRenewalResult +} + +// passwordRenewalResult 是同账号并发续期调用共享的完成信号与最终成功状态。 +type passwordRenewalResult struct { + // done 由首次续期调用关闭,所有等待者只接收不关闭。 + done chan struct{} + // renewed 在关闭 done 前写入,关闭 channel 建立等待者读取该字段的 happens-before 关系。 + renewed bool } // notifyNotifier 是 *notify.Notifier 的最小接口,避免 adapter 直接依赖 notify 包 @@ -115,6 +127,7 @@ func New(store *db.Store, bm *browser.Manager, logger *slog.Logger) *Adapter { captchaReq: mtop.NewClient(), orderMTop: mtop.NewClient(), passwordCoordinator: accountapp.NewCredentialRefreshCoordinator(), + passwordResults: make(map[string]*passwordRenewalResult), } } @@ -175,14 +188,21 @@ func (a *Adapter) HandleChatMessage(ctx context.Context, message engine.ChatMess // Xianyu echoes messages sent by this account back over the same WS. Those // sends are already captured by HandleOutgoingChatMessage; recording the // echo as incoming would put our own bubble on the buyer side and duplicate it. - if strings.TrimSuffix(message.SenderUserID, "@goofish") == strings.TrimSuffix(message.AccountID, "@goofish") { + // selfID 保存当前账号从 Cookie 解析出的平台用户标识,用于过滤同账号 WebSocket 回显。 + if selfID := protocol.TransCookies(message.CookieStr)["unb"]; selfID != "" && + strings.TrimSuffix(strings.TrimSpace(message.SenderUserID), "@goofish") == strings.TrimSuffix(strings.TrimSpace(selfID), "@goofish") { + a.logger.Info("忽略账号自身发送的聊天回显", "account", message.AccountID, "chat_id", message.ChatID, "sender_id", message.SenderUserID) return nil } - // err 保存err,供当前处理流程使用 - _, _, err := a.chat.RecordIncoming(ctx, chat.Incoming{ + // stored、inserted、err 保存落库消息、是否首次插入及持久化错误。 + stored, inserted, err := a.chat.RecordIncoming(ctx, chat.Incoming{ AccountID: message.AccountID, ChatID: message.ChatID, BuyerID: message.SenderUserID, - BuyerName: message.SenderName, Text: message.Text, ItemID: message.ItemID, Raw: message.Raw, + BuyerName: message.SenderName, Text: message.Text, MessageID: message.MessageID, ItemID: message.ItemID, Raw: message.Raw, }) + if stored != nil { + a.logger.Info("实时聊天消息已入库", "account", message.AccountID, "chat_id", message.ChatID, + "message_key", stored.MessageKey, "message_type", stored.MessageType, "inserted", inserted) + } return err } @@ -199,6 +219,23 @@ func (a *Adapter) HandleOutgoingChatMessage(ctx context.Context, message engine. return err } +// HandleMessageRead 接收平台出站消息已读回执,并把非敏感已读状态更新委托给聊天服务。 +func (a *Adapter) HandleMessageRead(ctx context.Context, event engine.MessageReadEvent) error { + if a.chat == nil { + return nil + } + // message、err 保存按平台消息键更新的出站消息及持久化错误,以便缺键时回退会话最近消息。 + message, err := a.chat.MarkOutgoingRead(ctx, event.AccountID, event.MessageID, event.ReadAt) + if errors.Is(err, db.ErrNotFound) && event.ChatID != "" { + message, err = a.chat.MarkLatestOutgoingRead(ctx, event.AccountID, event.ChatID, event.ReadAt) + } + if err == nil && message != nil { + a.logger.Info("聊天出站消息已标记已读", "account", event.AccountID, "chat_id", event.ChatID, + "message_id", event.MessageID, "message_key", message.MessageKey, "read_status", message.ReadStatus) + } + return err +} + // OnAccountAlert 把账号告警(token 失效/自动恢复失败/风控验证等)转发给通知器, // 推送到该账号已绑定的通知渠道。 // OnAccountAlert 负责On账号Alert相关处理。 @@ -611,6 +648,14 @@ func (a *Adapter) OnPasswordLoginRefresh(ctx context.Context, cookieID string) b a.recordPasswordLogin(ctx, cookieID, 0, "skipped_cooldown", reason, fmt.Sprintf("协议续期冷却中,还需等待 %s", remain.Round(time.Second))) return false } + // primary 标识当前调用是否负责执行协议续期;后到调用方只等待其结果。 + if primary := a.beginPasswordRenewalResult(cookieID); !primary { + a.logger.Warn("协议续期已在处理中,等待当前结果", "account", cookieID) + return a.waitPasswordRenewalResult(ctx, cookieID) + } + // sharedRenewed 保存首次调用的最终恢复结果,并在所有返回路径唤醒等待者。 + sharedRenewed := false + defer func() { a.finishPasswordRenewalResult(cookieID, sharedRenewed) }() // platformData 保存成功或失败时用于审计的账号平台运行数据;明文凭证只在续期工作闭包内短暂使用。 var platformData db.CookiePlatformRuntimeData // lookupFailed 标识是否在调用协议续期前读取账号数据失败,以保持历史审计原因。 @@ -626,6 +671,7 @@ func (a *Adapter) OnPasswordLoginRefresh(ctx context.Context, cookieID string) b platformData = loaded return a.tryProtocolCredentialRenew(runCtx, &platformData) }) + sharedRenewed = renewed if !accepted { if errors.Is(renewErr, accountapp.ErrCredentialRefreshInFlight) { a.logger.Warn("协议续期已在处理中", "account", cookieID) @@ -690,6 +736,55 @@ func (a *Adapter) finishPasswordLogin(cookieID string) { } } +// beginPasswordRenewalResult 为账号首次协议续期创建共享结果状态;返回 false 表示已有调用负责续期。 +func (a *Adapter) beginPasswordRenewalResult(cookieID string) bool { + // passwordResultMu 只保护账号到共享结果状态的映射,绝不跨越慢速外部 I/O。 + a.passwordResultMu.Lock() + defer a.passwordResultMu.Unlock() + if a.passwordResults == nil { + a.passwordResults = make(map[string]*passwordRenewalResult) + } + // exists 表示该账号是否已有首个调用负责协议续期,存在时当前调用改为等待共享结果。 + if _, exists := a.passwordResults[cookieID]; exists { + return false + } + a.passwordResults[cookieID] = &passwordRenewalResult{done: make(chan struct{})} + return true +} + +// finishPasswordRenewalResult 写入首次协议续期结果并唤醒同账号等待者;重复收尾保持幂等。 +func (a *Adapter) finishPasswordRenewalResult(cookieID string, renewed bool) { + // passwordResultMu 只保护结果写入、映射删除和 channel 关闭的唯一性。 + a.passwordResultMu.Lock() + defer a.passwordResultMu.Unlock() + // result 保存当前账号等待者共享的续期结果状态,负责承载最终结果并关闭通知通道。 + result := a.passwordResults[cookieID] + if result == nil { + return + } + result.renewed = renewed + delete(a.passwordResults, cookieID) + close(result.done) +} + +// waitPasswordRenewalResult 等待首次协议续期完成或调用上下文取消,返回其最终恢复结果。 +func (a *Adapter) waitPasswordRenewalResult(ctx context.Context, cookieID string) bool { + // passwordResultMu 只保护共享状态快照读取,等待发生在释放锁之后。 + a.passwordResultMu.Lock() + // result 保存锁内取得的共享续期状态快照;释放锁后只等待其完成信号。 + result := a.passwordResults[cookieID] + a.passwordResultMu.Unlock() + if result == nil { + return false + } + select { + case <-result.done: + return result.renewed + case <-ctx.Done(): + return false + } +} + // recordPasswordLogin 负责record密码登录相关处理。 func (a *Adapter) recordPasswordLogin(ctx context.Context, cookieID string, userID int64, status, failureReason, message string) { if a.store == nil || a.store.LoginLogs == nil { @@ -827,6 +922,17 @@ func (a *Adapter) tryProtocolCredentialRenew(ctx context.Context, d *db.CookiePl a.logger.Info("Go 协议续期成功", "account", d.ID) return true, nil } + if err == nil { + // message 保存平台续期失败原因;空原因使用稳定的非敏感默认提示。 + message := strings.TrimSpace(res.Message) + if message == "" { + message = "协议续期未通过" + } + return false, errors.New(message) + } + } + if err == nil { + err = errors.New("协议续期未返回结果") } return false, err } diff --git a/internal/adapter/adapter_test.go b/internal/adapter/adapter_test.go index f562c5e..b435cff 100644 --- a/internal/adapter/adapter_test.go +++ b/internal/adapter/adapter_test.go @@ -605,6 +605,45 @@ func TestOnPasswordLoginRefreshWaitsForPendingFinalResult(t *testing.T) { } } +// TestOnPasswordLoginRefreshConcurrentCallersShareResult 验证同账号并发续期只执行一次外部请求且共享成功结果。 +func TestOnPasswordLoginRefreshConcurrentCallersShareResult(t *testing.T) { + // store、cleanup 保存测试专用数据库及其资源释放函数,避免并发用例污染其他测试。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + renewal.GlobalCooldown.Reset("cid") + // err 保存写入可续期账号 Cookie 的错误;失败时无法建立本用例的续期前置状态。 + if err := store.Cookies.UpdateValueExisting(context.Background(), "cid", "unb=1; havana_lgc_exp=9999999999999"); err != nil { + t.Fatal(err) + } + // started 用于确认首个调用已进入慢速续期请求,使第二个调用确实与其并发。 + started := make(chan struct{}) + // once 保证测试 HTTP 处理器只关闭一次开始信号。 + var once sync.Once + // srv 模拟延迟完成的协议续期端点,暴露并发调用共享结果的时序。 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + once.Do(func() { close(started) }) + time.Sleep(60 * time.Millisecond) + _, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}}}`)) + })) + defer srv.Close() + // a 是注入测试续期服务的适配器,被两个调用方并发复用。 + a := New(store, nil, nil) + a.SetRenewService(xrenew.Service{ + HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, + RetryDelay: -1, PromiseTimeout: 5 * time.Millisecond, + }) + // first 接收首个续期调用的最终布尔结果,避免 goroutine 泄漏。 + first := make(chan bool, 1) + go func() { first <- a.OnPasswordLoginRefresh(context.Background(), "cid") }() + <-started + // second 保存第二个并发调用收到的共享续期结果。 + second := a.OnPasswordLoginRefresh(context.Background(), "cid") + // got 保存首个调用的最终结果,应与等待共享状态的第二个调用一致。 + if got := <-first; !got || !second { + t.Fatalf("并发续期调用应共享成功结果: first=%v second=%v", got, second) + } +} + // TestOnPasswordLoginRefresh_BrowserNilReturnsFalseAfterAPIFailure 接口轻量续期也失败后才因浏览器不可用失败。 func TestOnPasswordLoginRefresh_BrowserNilReturnsFalseAfterAPIFailure(t *testing.T) { // store、cleanup 保存store、cleanup,供当前处理流程使用 diff --git a/internal/adapter/chat_repository.go b/internal/adapter/chat_repository.go index aa40d0b..f80b584 100644 --- a/internal/adapter/chat_repository.go +++ b/internal/adapter/chat_repository.go @@ -84,6 +84,14 @@ func (r chatRepository) MarkRead(ctx context.Context, userID int64, accountID, c return r.store.Chats.MarkRead(ctx, userID, accountID, chatID) } +// FindInboundParsedJSONContaining 提供旧版聊天消息标识迁移所需的受限诊断帧查询。 +func (r chatRepository) FindInboundParsedJSONContaining(ctx context.Context, accountID, fragment string, limit int) ([]string, error) { + if r.store == nil || r.store.WSMessages == nil { + return nil, errors.New("聊天诊断存储未初始化") + } + return r.store.WSMessages.FindInboundParsedJSONContaining(ctx, accountID, fragment, limit) +} + // chatIdentityResolver 在适配器内读取 Cookie 并调用平台身份查询接口。 type chatIdentityResolver struct { // store 提供账号凭证读取能力,明文只在本次平台调用期间存在。 diff --git a/internal/adapter/chat_repository_test.go b/internal/adapter/chat_repository_test.go index 883d9cf..b77beab 100644 --- a/internal/adapter/chat_repository_test.go +++ b/internal/adapter/chat_repository_test.go @@ -46,6 +46,21 @@ func (subscriptionDomainRepository) UpdateMessageStatus(context.Context, string, return &db.ChatMessage{}, nil } +// CountUnreadUserMessages 为订阅测试提供没有本地未读消息的稳定结果。 +func (subscriptionDomainRepository) CountUnreadUserMessages(context.Context, string, string) (int, error) { + return 0, nil +} + +// MarkMessageRead 为订阅测试模拟指定出站消息的已读回执写入。 +func (subscriptionDomainRepository) MarkMessageRead(_ context.Context, _ string, key string, readAt int64) (*db.ChatMessage, error) { + return &db.ChatMessage{MessageKey: key, ReadStatus: 2, ReadAt: readAt}, nil +} + +// MarkLatestOutgoingRead 为订阅测试模拟缺失消息键时的会话级已读回退。 +func (subscriptionDomainRepository) MarkLatestOutgoingRead(_ context.Context, _ string, chatID string, readAt int64) (*db.ChatMessage, error) { + return &db.ChatMessage{ChatID: chatID, ReadStatus: 2, ReadAt: readAt}, nil +} + // TestChatSubscriptionProviderConvertsAndCleansEvents 验证领域事件转换和订阅取消可重复执行。 func TestChatSubscriptionProviderConvertsAndCleansEvents(t *testing.T) { // service 是使用内存仓储构造的领域聊天事件中心。 diff --git a/internal/adapter/item_dependencies.go b/internal/adapter/item_dependencies.go index e3adf0d..928776c 100644 --- a/internal/adapter/item_dependencies.go +++ b/internal/adapter/item_dependencies.go @@ -48,7 +48,7 @@ func (d *ItemDependencies) NewItemBatchPublishPort(client func() MTOPClient, log } // NewItemPublishPort 创建单商品发布与类目推荐共用的平台端口。 -func (d *ItemDependencies) NewItemPublishPort(client func() MTOPClient, logger *slog.Logger, update func(context.Context, string, string), recover func(context.Context, string, error)) *ItemPublishPort { +func (d *ItemDependencies) NewItemPublishPort(client func() MTOPClient, logger *slog.Logger, update func(context.Context, string, string), recover func(context.Context, string, error) bool) *ItemPublishPort { if d == nil { return nil } diff --git a/internal/adapter/item_publish.go b/internal/adapter/item_publish.go index f1042df..1b00726 100644 --- a/internal/adapter/item_publish.go +++ b/internal/adapter/item_publish.go @@ -24,12 +24,12 @@ type ItemPublishPort struct { logger *slog.Logger // updateRunningCookie 将平台返回的新 Cookie 同步到运行中的账号实例。 updateRunningCookie func(context.Context, string, string) - // recoverExpiredSession 在平台报告会话过期时触发账号恢复。 - recoverExpiredSession func(context.Context, string, error) + // recoverExpiredSession 在平台报告会话过期时触发账号恢复并返回是否已获得可重试凭证。 + recoverExpiredSession func(context.Context, string, error) bool } // NewItemPublishPort 构造单商品发布基础设施端口。 -func NewItemPublishPort(store *db.Store, client func() mtop.Client, logger *slog.Logger, updateRunningCookie func(context.Context, string, string), recoverExpiredSession func(context.Context, string, error)) *ItemPublishPort { +func NewItemPublishPort(store *db.Store, client func() mtop.Client, logger *slog.Logger, updateRunningCookie func(context.Context, string, string), recoverExpiredSession func(context.Context, string, error) bool) *ItemPublishPort { // resolvedLogger 保存可用于记录发布适配错误的日志器。 resolvedLogger := logger if resolvedLogger == nil { @@ -120,6 +120,11 @@ func (p *ItemPublishPort) persistCategorySession(ctx context.Context, userID int // Publish 执行单商品平台发布及响应 Cookie 持久化,不向应用层泄露 MTOP 类型。 func (p *ItemPublishPort) Publish(ctx context.Context, input itemapp.PublishInput) (itemapp.PublishOutcome, error) { + return p.publish(ctx, input, true) +} + +// publish 执行一次商品发布;会话恢复成功时最多用新凭证重试一次。 +func (p *ItemPublishPort) publish(ctx context.Context, input itemapp.PublishInput, allowRetry bool) (itemapp.PublishOutcome, error) { if p == nil || p.store == nil || p.store.Cookies == nil { return itemapp.PublishOutcome{}, errors.New("商品发布存储未初始化") } @@ -173,6 +178,9 @@ func (p *ItemPublishPort) Publish(ctx context.Context, input itemapp.PublishInpu if persistErr != nil { callErr = errors.Join(callErr, fmt.Errorf("保存发布响应 Cookie: %w", persistErr)) } + if allowRetry && mtop.IsSessionExpiredErr(callErr) && p.recoverExpired(ctx, input.CookieID, callErr) { + return p.publish(ctx, input, false) + } p.recoverExpired(ctx, input.CookieID, callErr) return itemapp.PublishOutcome{ResponseCookieErr: persistErr}, callErr } @@ -289,10 +297,11 @@ func (p *ItemPublishPort) mtopClient() mtop.Client { } // recoverExpired 在平台会话过期时通知账号恢复协调器。 -func (p *ItemPublishPort) recoverExpired(ctx context.Context, cookieID string, err error) { +func (p *ItemPublishPort) recoverExpired(ctx context.Context, cookieID string, err error) bool { if p != nil && p.recoverExpiredSession != nil && err != nil { - p.recoverExpiredSession(ctx, cookieID, err) + return p.recoverExpiredSession(ctx, cookieID, err) } + return false } // 确保发布端口和仓储实现覆盖应用层定义的最小接口。 diff --git a/internal/adapter/item_publish_test.go b/internal/adapter/item_publish_test.go index 778f98b..81cee87 100644 --- a/internal/adapter/item_publish_test.go +++ b/internal/adapter/item_publish_test.go @@ -141,6 +141,47 @@ func TestItemPublishPortReleasesCredentialLockDuringRemoteCall(t *testing.T) { } } +// TestItemPublishPortRetriesAfterSessionRecovery 验证续期成功后发布端口使用重新读取的凭证重试一次。 +func TestItemPublishPortRetriesAfterSessionRecovery(t *testing.T) { + // store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // calls 保存平台发布调用次数,用于确认最多执行一次恢复后的重试。 + calls := 0 + // secondCookies 保存第二次发布实际使用的凭证快照。 + secondCookies := "" + // client 是首次返回会话失效、第二次成功的平台客户端替身。 + client := itemPublishClientStub{publish: func(_ context.Context, cookies string, _ mtop.PublishItemRequest) (*mtop.PublishItemResult, error) { + calls++ + if calls == 1 { + return nil, &mtop.SessionExpiredError{API: "publish"} + } + secondCookies = cookies + return &mtop.PublishItemResult{ItemID: "retry-item", Title: "重试商品"}, nil + }} + // recovered 保存恢复回调是否被调用,确保发布端口不会静默跳过会话恢复。 + recovered := false + // recovery 保存测试用会话恢复回调,并模拟恢复逻辑写入的新凭证。 + recovery := func(ctx context.Context, cookieID string, recoveryErr error) bool { + recovered = recoveryErr != nil + // updateErr 保存模拟续期凭证写入的持久化错误。 + if updateErr := store.Cookies.UpdateValueExisting(ctx, cookieID, "unb=1; fresh=1"); updateErr != nil { + t.Fatalf("写入续期凭证失败: %v", updateErr) + } + return true + } + // port 是注入恢复回调后的发布适配器。 + port := NewItemPublishPort(store, func() mtop.Client { return client }, nil, nil, recovery) + // outcome、publishErr 保存恢复重试后的发布结果及错误。 + outcome, publishErr := port.Publish(context.Background(), itemapp.PublishInput{UserID: 1, CookieID: "cid", Title: "重试商品", PriceCents: 100, Quantity: 1}) + if publishErr != nil || outcome.Result == nil || outcome.Result.ItemID != "retry-item" { + t.Fatalf("恢复后发布结果异常: outcome=%+v err=%v", outcome, publishErr) + } + if !recovered || calls != 2 || secondCookies != "unb=1; fresh=1" { + t.Fatalf("续期重试未使用新凭证: recovered=%v calls=%d cookies=%q", recovered, calls, secondCookies) + } +} + // TestItemPublishRepositoryUpsertMapsApplicationRecord 验证商品仓储适配器正确转换应用记录。 func TestItemPublishRepositoryUpsertMapsApplicationRecord(t *testing.T) { // store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。 diff --git a/internal/application/chat/service.go b/internal/application/chat/service.go index 82ccbeb..ed39f05 100644 --- a/internal/application/chat/service.go +++ b/internal/application/chat/service.go @@ -3,7 +3,9 @@ package chat import ( "context" + "encoding/json" "errors" + "fmt" "strings" "sync" "time" @@ -166,6 +168,12 @@ type SessionRepository interface { MarkRead(ctx context.Context, userID int64, accountID, chatID string) error } +// ReadMessageIDResolver 定义旧版聊天关联标识解析需要的最小诊断查询能力。 +type ReadMessageIDResolver interface { + // FindInboundParsedJSONContaining 返回可能包含旧关联标识的有限已解密入站诊断帧。 + FindInboundParsedJSONContaining(ctx context.Context, accountID, fragment string, limit int) ([]string, error) +} + // Service 编排聊天历史查询,不持有 HTTP 请求或数据库连接。 type Service struct { // repository 保存由调用方注入的最小持久化端口。 @@ -260,6 +268,116 @@ func (s *Service) FindSession(ctx context.Context, userID int64, accountID, chat return session, nil } +// ResolveReadMessageID 将旧版实时消息关联标识转换为闲鱼已读接口要求的 PNM 标识。 +func (s *Service) ResolveReadMessageID(ctx context.Context, accountID, chatID, messageID string) string { + // legacyID 保存去除空白后的待迁移消息关联标识。 + legacyID := strings.TrimSpace(messageID) + if legacyID == "" || strings.HasSuffix(legacyID, ".PNM") || s == nil || s.repository == nil { + return legacyID + } + // resolver 保存仓储实现的可选诊断帧查询能力。 + resolver, ok := s.repository.(ReadMessageIDResolver) + if !ok { + return "" + } + // values、err 保存可能匹配旧标识的诊断 JSON 及读取错误。 + values, err := resolver.FindInboundParsedJSONContaining(ctx, accountID, legacyID, 20) + if err != nil { + return "" + } + // value 保存当前待解析的诊断 JSON。 + for _, value := range values { + // decoded 保存当前诊断帧反序列化后的动态结构。 + var decoded any + if json.Unmarshal([]byte(value), &decoded) != nil { + continue + } + // platformID 保存当前诊断帧中解析出的平台 PNM 标识。 + if platformID := FindPlatformMessageID(decoded, chatID, legacyID); platformID != "" { + return platformID + } + } + return "" +} + +// FindPlatformMessageID 在已解密的实时消息结构中定位与旧关联标识对应的 PNM 标识。 +func FindPlatformMessageID(value any, chatID, legacyID string) string { + // walk 递归检查嵌套 map、数组和嵌入 JSON 文本。 + var walk func(any) string + walk = func(current any) string { + // typed 保存当前动态节点按容器类别断言后的值。 + switch typed := current.(type) { + case map[string]any: + // payload、ok 保存协议第 10 段及其存在标识。 + if payload, ok := typed["10"]; ok && readValueContainsID(payload, legacyID) { + // candidate 保存当前协议节点提供的平台消息标识。 + candidate := strings.TrimSpace(fmt.Sprint(typed["3"])) + if strings.HasSuffix(candidate, ".PNM") { + // currentChatID 保存协议节点所属的聊天会话标识。 + currentChatID := strings.TrimSuffix(strings.TrimSpace(fmt.Sprint(typed["2"])), "@goofish") + if currentChatID == "" || currentChatID == chatID { + return candidate + } + } + } + // child 保存当前 map 的嵌套协议节点。 + for _, child := range typed { + // candidate 保存递归解析得到的候选 PNM 标识。 + if candidate := walk(child); candidate != "" { + return candidate + } + } + case []any: + // child 保存当前数组中的嵌套协议节点。 + for _, child := range typed { + // candidate 保存递归解析得到的候选 PNM 标识。 + if candidate := walk(child); candidate != "" { + return candidate + } + } + case string: + // nested 保存嵌入 JSON 文本反序列化后的结构。 + var nested any + if json.Unmarshal([]byte(typed), &nested) == nil { + return walk(nested) + } + } + return "" + } + return walk(value) +} + +// readValueContainsID 判断嵌套诊断字段是否保存了指定旧关联标识。 +func readValueContainsID(value any, legacyID string) bool { + // typed 保存当前动态节点按容器类别断言后的值。 + switch typed := value.(type) { + case map[string]any: + // key、child 保存当前字段名及其嵌套值。 + for key, child := range typed { + if (strings.EqualFold(key, "messageId") || strings.EqualFold(key, "message_id")) && strings.TrimSpace(fmt.Sprint(child)) == legacyID { + return true + } + if readValueContainsID(child, legacyID) { + return true + } + } + case []any: + // child 保存当前数组中的嵌套值。 + for _, child := range typed { + if readValueContainsID(child, legacyID) { + return true + } + } + case string: + // nested 保存嵌入 JSON 文本反序列化后的结构。 + var nested any + if json.Unmarshal([]byte(typed), &nested) == nil { + return readValueContainsID(nested, legacyID) + } + } + return false +} + // CleanupEmptySessions 清理平台分页产生的无效空会话壳。 func (s *Service) CleanupEmptySessions(ctx context.Context, accountID string) error { accountID = strings.TrimSpace(accountID) diff --git a/internal/browser/cookierenew.go b/internal/browser/cookierenew.go index 2da0949..d2ded5b 100644 --- a/internal/browser/cookierenew.go +++ b/internal/browser/cookierenew.go @@ -90,9 +90,9 @@ func (m *Manager) newPersistentPasswordContext(ctx context.Context, cookieID, us var bctx playwright.BrowserContext // lastErr 保存lastErr,供当前处理流程使用 var lastErr error - for // attempt 保存尝试次数,供当前处理流程使用 - attempt := 1; attempt <= 2; attempt++ { - bctx, err = m.pw.Chromium.LaunchPersistentContext(userDataDir, passwordPersistentContextOptions(headless)) + // attempt 表示当前持久化 Chromium 的重试序号;启动失败时会先清理 profile 锁文件再重试一次。 + for attempt := 1; attempt <= 2; attempt++ { + bctx, err = m.pw.Chromium.LaunchPersistentContext(userDataDir, passwordPersistentContextOptions(headless, m.headlessUserAgent())) if err == nil { break } @@ -116,9 +116,10 @@ func (m *Manager) newPersistentPasswordContext(ctx context.Context, cookieID, us return bctx, release, nil } -// passwordPersistentContextOptions 负责密码Persistent上下文Options相关处理。 -func passwordPersistentContextOptions(headless bool) playwright.BrowserTypeLaunchPersistentContextOptions { - return playwright.BrowserTypeLaunchPersistentContextOptions{ +// passwordPersistentContextOptions 为密码登录构造持久化上下文;无头模式仅使用实测运行时并去除 HeadlessChrome 标记的 UA。 +func passwordPersistentContextOptions(headless bool, headlessUserAgent ...*string) playwright.BrowserTypeLaunchPersistentContextOptions { + // options 是密码登录持久化 context 的完整启动配置,避免把 UA 覆盖泄漏到有头会话。 + options := playwright.BrowserTypeLaunchPersistentContextOptions{ Headless: playwright.Bool(headless), Args: chromiumLaunchArgs(), ExecutablePath: chromiumExecutablePath(), @@ -132,6 +133,10 @@ func passwordPersistentContextOptions(headless bool) playwright.BrowserTypeLaunc }, Timeout: playwright.Float(quickRenewTimeoutMS), } + if headless && len(headlessUserAgent) > 0 { + options.UserAgent = headlessUserAgent[0] + } + return options } // BrowserQuickRenew 使用持久化浏览器上下文执行“快速进入”Cookie 续期。 @@ -154,15 +159,17 @@ func (m *Manager) BrowserQuickRenewSnapshot(ctx context.Context, cookieID, cooki // effectiveSnapshot 保存effectiveSnapshot,供当前处理流程使用 effectiveSnapshot := reconcileSnapshotWithCurrentCookie(snapshot, cookieStr, goofishIMURL) - // bctx、release、err 保存bctx、release、err,供当前处理流程使用 - bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, cookieStr, effectiveSnapshot, quickRenewHeadless(headless)) + // headless 是经环境覆盖后的本次续期浏览器可见性,并决定是否必须应用运行时指纹。 + headless = quickRenewHeadless(headless) + // bctx 是持久化续期上下文;release 释放 profile 锁和并发槽位;err 仅表示上下文创建失败。 + bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, cookieStr, effectiveSnapshot, headless) if err != nil { return "", nil, err } defer release() - // page、err 保存page、err,供当前处理流程使用 - page, err := bctx.NewPage() + // page 是已在导航前附加无头 UA 和 Client Hints 覆盖的续期页面。 + page, err := m.newBrowserPage(bctx, headless) if err != nil { return "", nil, fmt.Errorf("新建 page 失败: %w", err) } @@ -222,15 +229,17 @@ func (m *Manager) CookiesRefreshSnapshot(ctx context.Context, cookieID, cookieSt } // effectiveSnapshot 保存effectiveSnapshot,供当前处理流程使用 effectiveSnapshot := reconcileSnapshotWithCurrentCookie(snapshot, cookieStr, goofishIMURL) - // bctx、release、err 保存bctx、release、err,供当前处理流程使用 - bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, cookieStr, effectiveSnapshot, cookiesRefreshHeadless(headless)) + // headless 是经环境覆盖后的定时续期浏览器可见性,并决定页面级指纹覆盖。 + headless = cookiesRefreshHeadless(headless) + // bctx 是定时续期使用的持久化上下文;release 归还 profile 资源;err 表示启动或注入 Cookie 失败。 + bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, cookieStr, effectiveSnapshot, headless) if err != nil { return "", nil, false, err } defer release() - // page、err 保存page、err,供当前处理流程使用 - page, err := bctx.NewPage() + // page 是已在导航前附加无头 UA 和 Client Hints 覆盖的官方续期页。 + page, err := m.newBrowserPage(bctx, headless) if err != nil { return "", nil, false, fmt.Errorf("新建 page 失败: %w", err) } @@ -588,9 +597,10 @@ func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cooki var bctx playwright.BrowserContext // lastErr 保存lastErr,供当前处理流程使用 var lastErr error - for // attempt 保存尝试次数,供当前处理流程使用 - attempt := 1; attempt <= 2; attempt++ { - bctx, err = m.pw.Chromium.LaunchPersistentContext(userDataDir, playwright.BrowserTypeLaunchPersistentContextOptions{ + // attempt 表示当前持久化 profile 的启动序号;失败后只进行一次清理后的重试。 + for attempt := 1; attempt <= 2; attempt++ { + // options 保存本次启动的独立配置,避免重试时复用可能被 Playwright 修改的对象。 + options := playwright.BrowserTypeLaunchPersistentContextOptions{ Headless: playwright.Bool(headless), Args: chromiumLaunchArgs(), ExecutablePath: chromiumExecutablePath(), @@ -598,7 +608,11 @@ func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cooki Locale: playwright.String(defaultLang), TimezoneId: playwright.String(defaultTZ), Timeout: playwright.Float(quickRenewTimeoutMS), - }) + } + if headless { + options.UserAgent = m.headlessUserAgent() + } + bctx, err = m.pw.Chromium.LaunchPersistentContext(userDataDir, options) if err == nil { break } diff --git a/internal/browser/headless_fingerprint_integration_test.go b/internal/browser/headless_fingerprint_integration_test.go new file mode 100644 index 0000000..3dc8660 --- /dev/null +++ b/internal/browser/headless_fingerprint_integration_test.go @@ -0,0 +1,177 @@ +package browser + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "strings" + "testing" + "time" + + "github.com/mxschmitt/playwright-go" +) + +// TestHeadlessFingerprintBrowserIntegration 在真实 Chromium 中验证 Playwright 与直连 CDP 的请求和页面指纹均不暴露无头标记;仅在显式开启浏览器集成测试时运行。 +func TestHeadlessFingerprintBrowserIntegration(t *testing.T) { + if os.Getenv("RUN_BROWSER_INTEGRATION") != "1" { + t.Skip("set RUN_BROWSER_INTEGRATION=1 to verify the effective headless browser fingerprint") + } + + // requests 接收两个浏览器路径访问本地探针时的请求头,由测试 goroutine 创建且不关闭。 + requests := make(chan http.Header, 2) + // server 是本地指纹探针,只记录目标路径请求而不涉及真实平台或凭证。 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/fingerprint" { + requests <- r.Header.Clone() + } + w.Header().Set("Content-Type", "text/html; charset=utf-8") + _, _ = io.WriteString(w, "fingerprint") + })) + defer server.Close() + + // m 管理本次测试创建的 Playwright runtime,defer Close 负责同步回收其浏览器资源。 + m := NewManager(nil) + defer m.Close() + // err 表示 runtime 初始化或实测 Chromium 指纹读取失败。 + if err := m.init(); err != nil { + t.Fatal(err) + } + // userAgent 是从当前打包 Chromium 实测并移除 HeadlessChrome 标记后的 UA。 + userAgent := m.headlessUserAgent() + if userAgent == nil { + t.Fatal("初始化后无头 UA 为空") + } + + t.Run("playwright-context", func(t *testing.T) { + // browser 是 Playwright 独立启动的无头 Chromium,子测试结束时关闭。 + browser, err := m.pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{ + Headless: playwright.Bool(true), + Args: chromiumLaunchArgs(), + ExecutablePath: chromiumExecutablePath(), + }) + if err != nil { + t.Fatal(err) + } + defer func() { _ = browser.Close() }() + // bctx 是 browser 的隔离上下文,使用实测 UA 并在子测试结束时释放。 + bctx, err := browser.NewContext(playwright.BrowserNewContextOptions{UserAgent: userAgent}) + if err != nil { + t.Fatal(err) + } + defer func() { _ = bctx.Close() }() + // page 是导航前已应用 Client Hints 覆盖的探针页面;err 表示页面或覆盖创建失败。 + page, err := m.newBrowserPage(bctx, true) + if err != nil { + t.Fatal(err) + } + verifyEffectiveHeadlessFingerprint(t, page, server.URL+"/fingerprint", requests, *userAgent) + }) + + t.Run("direct-cdp-context", func(t *testing.T) { + // profileDir 是直连 CDP Chromium 的临时用户目录,测试结束后由 testing 清理。 + profileDir := t.TempDir() + // executable 默认使用 Playwright 管理的 Chromium,环境配置可指定同一兼容运行时。 + executable := m.pw.Chromium.ExecutablePath() + // configured 是可选的环境指定可执行路径,存在时覆盖默认 runtime 路径。 + if configured := chromiumExecutablePath(); configured != nil { + executable = *configured + } + // cmd 是直连 CDP 的 Chromium 进程,defer 中终止并等待其退出。 + cmd := exec.Command(executable, fallbackChromiumArgs(profileDir, true, userAgent)...) + cmd.Stdout = io.Discard + cmd.Stderr = io.Discard + // err 表示 Chromium 子进程未能启动。 + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + // processDone 由等待 goroutine 发送一次子进程退出结果,defer 接收以避免遗留 goroutine。 + processDone := make(chan error, 1) + // 等待 goroutine 只负责把 cmd.Wait 的结果转交给测试清理逻辑。 + go func() { processDone <- cmd.Wait() }() + defer func() { + if cmd.Process != nil { + _ = cmd.Process.Kill() + } + select { + case <-processDone: + case <-time.After(2 * time.Second): + } + }() + + // ctx 限制 DevTools 发现总时长;cancel 在子测试退出时释放 timer 资源。 + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + // endpoint 是发现到的本地 DevTools 地址;err 表示进程提前退出或在限定时间内未就绪。 + endpoint, err := waitForDevToolsEndpoint(ctx, profileDir, processDone, 10*time.Second) + if err != nil { + t.Fatal(err) + } + // browser 是附着到外部 Chromium 的 CDP 句柄;关闭仅断开客户端连接。 + browser, err := m.pw.Chromium.ConnectOverCDP(endpoint) + if err != nil { + t.Fatal(err) + } + defer func() { _ = browser.Close() }() + // contexts 是外部 Chromium 已创建的 context 列表,直连模式应至少提供默认 context。 + contexts := browser.Contexts() + if len(contexts) == 0 { + t.Fatal("直接 CDP 浏览器无默认 context") + } + // page 是默认 context 中附加 CDP 指纹覆盖的验证页;err 表示覆盖建立失败。 + page, err := m.newBrowserPage(contexts[0], true) + if err != nil { + t.Fatal(err) + } + verifyEffectiveHeadlessFingerprint(t, page, server.URL+"/fingerprint", requests, *userAgent) + }) +} + +// verifyEffectiveHeadlessFingerprint 导航 page 到本地 target,读取 requests 中的 HTTP 指纹并与 expectedUserAgent 对比;失败即终止所属测试。 +func verifyEffectiveHeadlessFingerprint(t *testing.T, page playwright.Page, target string, requests <-chan http.Header, expectedUserAgent string) { + t.Helper() + // err 表示探针页面导航失败,页面未完成 DOM 加载时不能继续断言。 + if _, err := page.Goto(target, playwright.PageGotoOptions{WaitUntil: playwright.WaitUntilStateDomcontentloaded}); err != nil { + t.Fatal(err) + } + // headers 保存本次导航由本地探针捕获的 HTTP 请求头。 + var headers http.Header + select { + case headers = <-requests: + case <-time.After(5 * time.Second): + t.Fatal("等待浏览器指纹请求超时") + } + // pageIdentity 是页面内 navigator 暴露的 UA 与 Client Hints;err 表示脚本执行失败。 + pageIdentity, err := page.Evaluate(`() => ({ + userAgent: navigator.userAgent, + userAgentData: navigator.userAgentData ? navigator.userAgentData.toJSON() : null + })`) + if err != nil { + t.Fatal(err) + } + t.Logf("effective user-agent=%q sec-ch-ua=%q page=%v", headers.Get("User-Agent"), headers.Get("Sec-CH-UA"), pageIdentity) + // source 标识待检查的 HTTP 或页面指纹来源;value 是该来源暴露给目标站点的文本。 + for source, value := range map[string]string{ + "http-user-agent": headers.Get("User-Agent"), + "http-sec-ch-ua": headers.Get("Sec-CH-UA"), + "page-identity": fmt.Sprint(pageIdentity), + } { + if strings.Contains(strings.ToLower(value), "headless") { + t.Fatalf("%s 仍暴露 headless 标记: %s", source, value) + } + } + if !strings.Contains(headers.Get("User-Agent"), "Chrome/") { + t.Fatalf("HTTP UA 缺少 Chrome 版本: %q", headers.Get("User-Agent")) + } + if headers.Get("User-Agent") != expectedUserAgent { + t.Fatalf("HTTP UA 与实测 Chromium 版本不一致: got %q want %q", headers.Get("User-Agent"), expectedUserAgent) + } + // identity 是页面脚本结果的对象形式;ok 证明 Playwright 未改变预期的对象编码。 + identity, ok := pageIdentity.(map[string]any) + if !ok || identity["userAgent"] != expectedUserAgent { + t.Fatalf("navigator.userAgent 与实测 Chromium 版本不一致: %#v", pageIdentity) + } +} diff --git a/internal/browser/lifecycle.go b/internal/browser/lifecycle.go index cbc1fb5..768414a 100644 --- a/internal/browser/lifecycle.go +++ b/internal/browser/lifecycle.go @@ -12,6 +12,7 @@ import ( "os" "path/filepath" "runtime" + "strconv" "strings" "sync" "time" @@ -36,13 +37,30 @@ const ( // chromiumLaunchArgs 统一 Chromium 启动参数。 func chromiumLaunchArgs() []string { - return []string{ + // args 是所有 Chromium 启动路径共享的参数;证书绕过仅在环境明确授权时追加。 + args := []string{ "--no-sandbox", "--disable-setuid-sandbox", "--disable-dev-shm-usage", "--disable-blink-features=AutomationControlled", "--lang=zh-CN", } + if captchaIgnoreCertificateErrors() { + args = append(args, "--ignore-certificate-errors") + } + return args +} + +// captchaIgnoreCertificateErrors 仅为 TLS 检查代理替换平台证书链的受控环境提供浏览器证书校验绕过;默认关闭,且不会影响 HTTP 客户端或已保存凭证的校验。 +func captchaIgnoreCertificateErrors() bool { + // value 是环境变量的去空白值,空值按安全默认值禁用证书绕过。 + value := strings.TrimSpace(os.Getenv("CAPTCHA_IGNORE_CERT_ERRORS")) + if value == "" { + return false + } + // parsed 是环境开关的布尔解释;err 表示值不属于 Go 支持的布尔文本。 + parsed, err := strconv.ParseBool(value) + return err == nil && parsed } // chromiumExecutablePath 负责chromiumExecutable路径相关处理。 @@ -139,6 +157,13 @@ type Manager struct { pw *playwright.Playwright logger *slog.Logger + // browserFingerprint is observed from the bundled Chromium once during + // initialization. Headless contexts use the same identity with only the + // HeadlessChrome product token removed; headed contexts keep Chromium's + // native identity. + browserFingerprint xianyu.BrowserFingerprint + userAgentMetadata map[string]any + once sync.Once initErr error installed bool @@ -363,13 +388,219 @@ func (m *Manager) detectBrowserFingerprint() error { if strings.TrimSpace(headers.Get("User-Agent")) == "" { return fmt.Errorf("Chromium 返回空 userAgent") } - xianyu.SetBrowserFingerprint(xianyu.BrowserFingerprint{ + // metadata 是本次实测 Chromium 的高熵 Client Hints;err 表示页面未暴露或无法读取该浏览器信息。 + metadata, err := readUserAgentMetadata(page) + if err != nil { + return fmt.Errorf("读取 Chromium User-Agent Client Hints 失败: %w", err) + } + // fingerprint 是去除无头产品标记后的运行时身份,供后续无头页面和协议请求一致使用。 + fingerprint := normalizeBrowserFingerprint(xianyu.BrowserFingerprint{ UserAgent: headers.Get("User-Agent"), SecChUA: headers.Get("sec-ch-ua"), Platform: strings.Trim(headers.Get("sec-ch-ua-platform"), `"`), Mobile: headers.Get("sec-ch-ua-mobile"), }) - m.logger.Info("已读取 Playwright Chromium 原生指纹", "browser_version", b.Version(), "user_agent", headers.Get("User-Agent")) + m.browserFingerprint = fingerprint + m.userAgentMetadata = normalizeUserAgentMetadata(metadata) + xianyu.SetBrowserFingerprint(fingerprint) + m.logger.Info("已读取 Playwright Chromium 浏览器指纹", "browser_version", b.Version(), "user_agent", fingerprint.UserAgent, "headless_token_removed", fingerprint.UserAgent != headers.Get("User-Agent")) + return nil +} + +// normalizeBrowserFingerprint 移除 Chromium 无头模式附加的产品标记,同时保留同一运行时实测的版本和 Client Hints。 +func normalizeBrowserFingerprint(fingerprint xianyu.BrowserFingerprint) xianyu.BrowserFingerprint { + fingerprint.UserAgent = normalizeHeadlessUserAgent(fingerprint.UserAgent) + fingerprint.SecChUA = normalizeSecChUA(fingerprint.SecChUA) + return fingerprint +} + +// normalizeHeadlessUserAgent 只替换 UA 中的 HeadlessChrome 产品名,避免伪造浏览器版本、平台或其他身份字段。 +func normalizeHeadlessUserAgent(userAgent string) string { + return strings.ReplaceAll(strings.TrimSpace(userAgent), "HeadlessChrome/", "Chrome/") +} + +// normalizeSecChUA 规范化 Sec-CH-UA 品牌并按品牌去重,保证无头标记不会通过 Client Hints 泄露。 +func normalizeSecChUA(value string) string { + // parts 是按逗号拆分的原始品牌条目,保留同一 Chromium 实测版本字段。 + parts := strings.Split(value, ",") + // result 以原始顺序收集保留后的品牌条目;seen 防止替换 HeadlessChrome 后的重复品牌。 + result := make([]string, 0, len(parts)) + // seen 按规范化品牌名去重,避免同一产品经替换后重复出现在请求头。 + seen := make(map[string]struct{}, len(parts)) + // part 是当前待规范化的 Sec-CH-UA 品牌条目。 + for _, part := range parts { + part = strings.TrimSpace(strings.ReplaceAll(part, "HeadlessChrome", "Chromium")) + if part == "" { + continue + } + // brand 是用于去重的品牌名,不含版本参数。 + brand := part + // index 是品牌名与版本参数分隔分号的位置,负值表示条目没有参数。 + if index := strings.IndexByte(brand, ';'); index >= 0 { + brand = strings.TrimSpace(brand[:index]) + } + // exists 表示同名品牌已被保留,避免 HeadlessChrome 归一化后出现重复条目。 + if _, exists := seen[brand]; exists { + continue + } + seen[brand] = struct{}{} + result = append(result, part) + } + return strings.Join(result, ", ") +} + +// readUserAgentMetadata 从页面读取 Chromium 公开的低、高熵 Client Hints,返回可传给 CDP 的对象或读取失败原因。 +func readUserAgentMetadata(page playwright.Page) (map[string]any, error) { + // value 是页面脚本返回的任意值;err 表示浏览器脚本执行或高熵字段读取失败。 + value, err := page.Evaluate(`async () => { + const data = navigator.userAgentData; + if (!data) return null; + const high = await data.getHighEntropyValues([ + 'architecture', 'bitness', 'fullVersionList', 'model', 'platformVersion', 'wow64' + ]); + return { + brands: data.brands, + fullVersionList: high.fullVersionList, + platform: data.platform, + platformVersion: high.platformVersion, + architecture: high.architecture, + model: high.model, + mobile: data.mobile, + bitness: high.bitness, + wow64: high.wow64 + }; + }`) + if err != nil { + return nil, err + } + if value == nil { + return nil, fmt.Errorf("navigator.userAgentData 不可用") + } + // metadata 是可作为 CDP userAgentMetadata 使用的对象;ok 证明脚本结果的结构正确。 + metadata, ok := value.(map[string]any) + if !ok { + return nil, fmt.Errorf("navigator.userAgentData 类型异常: %T", value) + } + return metadata, nil +} + +// normalizeUserAgentMetadata 复制 Client Hints 并仅规范化品牌列表,避免修改 Manager 持有的实测元数据。 +func normalizeUserAgentMetadata(metadata map[string]any) map[string]any { + if len(metadata) == 0 { + return nil + } + // result 是供当前页面 CDP 覆盖使用的独立元数据副本。 + result := make(map[string]any, len(metadata)) + // key 是当前 Client Hints 字段名;value 是其待复制或规范化的值。 + for key, value := range metadata { + switch key { + case "brands", "fullVersionList": + result[key] = normalizeUserAgentBrands(value) + default: + result[key] = value + } + } + return result +} + +// normalizeUserAgentBrands 将品牌列表中的无头标记替换为 Chromium,并按品牌保留首个实测版本条目。 +func normalizeUserAgentBrands(value any) []any { + // brands 是页面返回的品牌数组;ok 表示该字段可以安全按数组处理。 + brands, ok := value.([]any) + if !ok { + return nil + } + // result 收集归一化后的品牌对象;seen 防止别名替换后的品牌重复。 + result := make([]any, 0, len(brands)) + // seen 记录已经保留的规范化品牌名,保证 CDP metadata 与 Sec-CH-UA 一致。 + seen := make(map[string]struct{}, len(brands)) + // item 是当前页面返回的候选品牌对象。 + for _, item := range brands { + // brandEntry 是转换后的品牌对象;ok 表示候选条目有可读取字段。 + brandEntry, ok := item.(map[string]any) + if !ok { + continue + } + // brand 是去重和覆盖写回使用的产品名,非字符串字段按空值丢弃。 + brand, _ := brandEntry["brand"].(string) + brand = strings.ReplaceAll(brand, "HeadlessChrome", "Chromium") + if brand == "" { + continue + } + // exists 表示相同规范化品牌已经收录。 + if _, exists := seen[brand]; exists { + continue + } + seen[brand] = struct{}{} + // entry 是独立拷贝,防止更改本次页面覆盖时改写原始实测对象。 + entry := make(map[string]any, len(brandEntry)) + // key 是当前品牌字段名;itemValue 是需原样保留的版本等字段。 + for key, itemValue := range brandEntry { + entry[key] = itemValue + } + entry["brand"] = brand + result = append(result, entry) + } + return result +} + +// headlessUserAgent 返回当前实测 Chromium 的规范化无头 UA;未完成指纹探测时回退全局实测值,仍不可用则返回 nil。 +func (m *Manager) headlessUserAgent() *string { + // userAgent 是移除 HeadlessChrome 标记后的 runtime UA,保持版本与协议侧指纹一致。 + userAgent := normalizeHeadlessUserAgent(m.browserFingerprint.UserAgent) + if userAgent == "" { + userAgent = normalizeHeadlessUserAgent(xianyu.CurrentBrowserFingerprint().UserAgent) + } + if userAgent == "" { + return nil + } + return playwright.String(userAgent) +} + +// newBrowserPage 从 bctx 创建页面;无头模式会在首次导航前应用 UA/Client Hints 覆盖,失败时关闭半成品页面并返回错误。 +func (m *Manager) newBrowserPage(bctx playwright.BrowserContext, headless bool) (playwright.Page, error) { + // page 是新建的浏览器页面;err 表示 context 不可用或页面创建失败。 + page, err := bctx.NewPage() + if err != nil { + return nil, err + } + if !headless { + return page, nil + } + // err 表示页面级 CDP 指纹覆盖失败,不能继续导航以免暴露无头身份。 + if err := m.applyHeadlessFingerprint(page); err != nil { + _ = page.Close() + return nil, err + } + return page, nil +} + +// applyHeadlessFingerprint 通过页面级 CDP 在首次导航前覆盖 UA 与 Client Hints;成功后故意保持会话附着以维持页面身份。 +func (m *Manager) applyHeadlessFingerprint(page playwright.Page) error { + // userAgent 是当前运行时的规范化 UA,nil 表示未完成必须的初始化探测。 + userAgent := m.headlessUserAgent() + if userAgent == nil { + return fmt.Errorf("无头 Chromium User-Agent 未初始化") + } + // metadata 是可安全传给当前页面的 Client Hints 拷贝,不能含 HeadlessChrome 品牌。 + metadata := normalizeUserAgentMetadata(m.userAgentMetadata) + if len(metadata) == 0 { + return fmt.Errorf("无头 Chromium User-Agent Client Hints 未初始化") + } + // session 是页面生命周期内保持附着的 CDP 会话;err 表示 Chromium 拒绝创建目标会话。 + session, err := page.Context().NewCDPSession(page) + if err != nil { + return fmt.Errorf("创建 Chromium 指纹 CDP 会话: %w", err) + } + // err 表示 Chromium 未接受身份覆盖;此时立即分离 session 防止资源泄漏。 + if _, err := session.Send("Emulation.setUserAgentOverride", map[string]any{ + "userAgent": *userAgent, + "userAgentMetadata": metadata, + }); err != nil { + _ = session.Detach() + return fmt.Errorf("应用 Chromium 无头指纹: %w", err) + } + // session 在 page 生命周期内必须保持附着;目标级仿真会话分离后 Chromium 会还原 navigator.userAgentData。 return nil } @@ -471,8 +702,8 @@ func (m *Manager) newPage(ctx context.Context, cookieID, cookieStr string, headl finishOperation() return nil, nil, err } - // page、err 保存page、err,供当前处理流程使用 - page, err := entry.context.NewPage() + // page 在无头模式下会在首次导航前收到运行时 UA 与 Client Hints 覆盖。 + page, err := m.newBrowserPage(entry.context, headless) if err != nil { // context 损坏,丢弃重建一次。 m.releaseEntry(cookieID, entry) @@ -482,7 +713,7 @@ func (m *Manager) newPage(ctx context.Context, cookieID, cookieStr string, headl finishOperation() return nil, nil, err } - page, err = entry.context.NewPage() + page, err = m.newBrowserPage(entry.context, headless) if err != nil { m.releaseEntry(cookieID, entry) m.evict(cookieID) @@ -578,12 +809,17 @@ func (m *Manager) createEntry(cookieID, cookieStr string, headless bool) (*poolE if err != nil { return nil, fmt.Errorf("启动 chromium 失败: %w", err) } - // context、err 保存context、err,供当前处理流程使用 - context, err := browser.NewContext(playwright.BrowserNewContextOptions{ + // contextOptions 保留 Chromium 原生上下文配置;无头 UA 仅使用本次实测 runtime 的规范化版本。 + contextOptions := playwright.BrowserNewContextOptions{ Viewport: &playwright.Size{Width: defaultW, Height: defaultH}, Locale: playwright.String(defaultLang), TimezoneId: playwright.String(defaultTZ), - }) + } + if headless { + contextOptions.UserAgent = m.headlessUserAgent() + } + // context 是 browser 的新隔离上下文;err 表示 context 创建失败并触发已启动浏览器回收。 + context, err := browser.NewContext(contextOptions) if err != nil { _ = browser.Close() return nil, fmt.Errorf("创建 context 失败: %w", err) diff --git a/internal/browser/passwordlogin.go b/internal/browser/passwordlogin.go index 552ab13..1a92baa 100644 --- a/internal/browser/passwordlogin.go +++ b/internal/browser/passwordlogin.go @@ -74,8 +74,8 @@ func (m *Manager) passwordLogin(ctx context.Context, account, password, cookieID } defer release() - // page、err 保存page、err,供当前处理流程使用 - page, err := bctx.NewPage() + // page 在无头密码登录时会在导航前覆盖 UA 和 Client Hints,避免暴露 HeadlessChrome。 + page, err := m.newBrowserPage(bctx, headless) if err != nil { return nil, fmt.Errorf("新建 page 失败: %w", err) } diff --git a/internal/browser/passwordlogin_detect_test.go b/internal/browser/passwordlogin_detect_test.go index d972dab..7195ced 100644 --- a/internal/browser/passwordlogin_detect_test.go +++ b/internal/browser/passwordlogin_detect_test.go @@ -92,13 +92,15 @@ func TestPasswordLoginReferenceProfileAndTiming(t *testing.T) { // TestPasswordPersistentContextOptionsMatchReference 负责Test密码Persistent上下文OptionsMatchReference相关处理。 func TestPasswordPersistentContextOptionsMatchReference(t *testing.T) { t.Setenv("PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH", "/opt/chromium") - // opts 保存opts,供当前处理流程使用 - opts := passwordPersistentContextOptions(true) + // userAgent 模拟从同版本 Chromium 实测后规范化出的无头身份。 + userAgent := "Mozilla/5.0 Chrome/149.0.7827.55 Safari/537.36" + // opts 验证无头持久化密码登录会把该身份交给 Playwright context。 + opts := passwordPersistentContextOptions(true, &userAgent) if opts.Headless == nil || !*opts.Headless { t.Fatal("密码登录应按调用参数使用无头模式") } - if opts.UserAgent != nil { - t.Fatalf("密码登录不应覆盖 Playwright Chromium 原生 UA: %v", *opts.UserAgent) + if opts.UserAgent == nil || *opts.UserAgent != userAgent { + t.Fatalf("无头密码登录应使用去除 HeadlessChrome 的运行时 UA: %v", opts.UserAgent) } if opts.Viewport == nil || opts.Viewport.Width != 1980 || opts.Viewport.Height != 1024 { t.Fatalf("密码登录 viewport=%+v", opts.Viewport) @@ -118,6 +120,11 @@ func TestPasswordPersistentContextOptionsMatchReference(t *testing.T) { if opts.ExecutablePath == nil || *opts.ExecutablePath != "/opt/chromium" { t.Fatalf("Chromium 路径=%v", opts.ExecutablePath) } + // headed 是有头密码登录配置,必须保留 Chromium 的原生 UA 而不使用无头覆盖。 + headed := passwordPersistentContextOptions(false, &userAgent) + if headed.UserAgent != nil { + t.Fatalf("有头密码登录应保留 Chromium 原生 UA: %v", headed.UserAgent) + } } // TestPasswordLoginRejectsBlankCredentialsBeforeBrowserInit 负责Test密码登录RejectsBlankCredentialsBefore浏览器Init相关处理。 diff --git a/internal/browser/pure_extra_test.go b/internal/browser/pure_extra_test.go index ddb80d4..5eff67a 100644 --- a/internal/browser/pure_extra_test.go +++ b/internal/browser/pure_extra_test.go @@ -1,6 +1,12 @@ package browser -import "testing" +import ( + "fmt" + "strings" + "testing" + + "xianyu-go/internal/xianyu" +) // TestSanitize 特殊字符替换为下划线(用于 userDataDir 命名)。 func TestSanitize(t *testing.T) { @@ -107,7 +113,88 @@ func TestChromiumExecutablePathFromEnv(t *testing.T) { } } -// TestSkipPlaywrightBrowserDownloadFromEnv 负责TestSkipPlaywright浏览器DownloadFromEnv相关处理。 +// TestCaptchaIgnoreCertificateErrors 验证证书例外仅在明确环境开关为真时进入浏览器启动参数。 +func TestCaptchaIgnoreCertificateErrors(t *testing.T) { + t.Setenv("CAPTCHA_IGNORE_CERT_ERRORS", "") + if captchaIgnoreCertificateErrors() { + t.Fatal("默认不应忽略证书错误") + } + t.Setenv("CAPTCHA_IGNORE_CERT_ERRORS", "true") + if !captchaIgnoreCertificateErrors() { + t.Fatal("true 应启用 CAPTCHA 证书错误忽略开关") + } + t.Setenv("CAPTCHA_IGNORE_CERT_ERRORS", "not-a-bool") + if captchaIgnoreCertificateErrors() { + t.Fatal("无效值不应启用证书错误忽略开关") + } +} + +// TestNormalizeBrowserFingerprintRemovesOnlyHeadlessMarker 验证规范化不伪造 Chromium 的版本或平台身份。 +func TestNormalizeBrowserFingerprintRemovesOnlyHeadlessMarker(t *testing.T) { + // fingerprint 是含无头标记的实测身份经过规范化后的结果,用于断言只移除产品标记。 + fingerprint := normalizeBrowserFingerprint(xianyu.BrowserFingerprint{ + UserAgent: " Mozilla/5.0 HeadlessChrome/149.0.7827.55 Safari/537.36 ", + SecChUA: `"HeadlessChrome";v="149", "Chromium";v="149"`, + Platform: "macOS", + Mobile: "?0", + }) + if strings.Contains(fingerprint.UserAgent, "HeadlessChrome") || strings.Contains(fingerprint.SecChUA, "HeadlessChrome") { + t.Fatalf("无头标记未清除: %+v", fingerprint) + } + if !strings.Contains(fingerprint.UserAgent, "Chrome/149.0.7827.55") { + t.Fatalf("Chromium 版本不应变化: %q", fingerprint.UserAgent) + } + if fingerprint.Platform != "macOS" || fingerprint.Mobile != "?0" { + t.Fatalf("非无头字段不应变化: %+v", fingerprint) + } + if strings.Count(fingerprint.SecChUA, `"Chromium"`) != 1 { + t.Fatalf("Client Hints 品牌应去重: %q", fingerprint.SecChUA) + } +} + +// TestNormalizeUserAgentMetadataRemovesAndDeduplicatesHeadlessBrand 验证导航前 CDP 覆盖不会泄露无头品牌。 +func TestNormalizeUserAgentMetadataRemovesAndDeduplicatesHeadlessBrand(t *testing.T) { + // metadata 是模拟页面返回的 Client Hints 经规范化后的副本,不应再暴露无头品牌。 + metadata := normalizeUserAgentMetadata(map[string]any{ + "brands": []any{ + map[string]any{"brand": "HeadlessChrome", "version": "149"}, + map[string]any{"brand": "Chromium", "version": "149"}, + map[string]any{"brand": "Not)A;Brand", "version": "24"}, + }, + "fullVersionList": []any{ + map[string]any{"brand": "HeadlessChrome", "version": "149.0.7827.55"}, + map[string]any{"brand": "Chromium", "version": "149.0.7827.55"}, + }, + "platform": "macOS", + "mobile": false, + }) + if strings.Contains(strings.ToLower(fmt.Sprint(metadata)), "headless") { + t.Fatalf("User-Agent metadata 仍暴露 headless: %#v", metadata) + } + // brands 是规范化后的基础品牌列表;ok 表示 CDP 可接收数组结构。 + brands, ok := metadata["brands"].([]any) + if !ok || len(brands) != 2 { + t.Fatalf("brands 未正确去重: %#v", metadata["brands"]) + } + // fullVersions 是规范化后的完整版本品牌列表;ok 表示字段没有被意外改变类型。 + fullVersions, ok := metadata["fullVersionList"].([]any) + if !ok || len(fullVersions) != 1 { + t.Fatalf("fullVersionList 未正确去重: %#v", metadata["fullVersionList"]) + } +} + +// TestManagerHeadlessUserAgentUsesDetectedRuntimeVersion 验证无头 UA 沿用实测 Chromium 版本而非静态伪造值。 +func TestManagerHeadlessUserAgentUsesDetectedRuntimeVersion(t *testing.T) { + // m 模拟已完成运行时指纹探测的管理器,不需要启动真实 Chromium。 + m := &Manager{browserFingerprint: xianyu.BrowserFingerprint{UserAgent: "Mozilla/5.0 HeadlessChrome/149.0.7827.55 Safari/537.36"}} + // userAgent 是 m 基于实测版本生成的无头 UA,应只替换产品标记。 + userAgent := m.headlessUserAgent() + if userAgent == nil || *userAgent != "Mozilla/5.0 Chrome/149.0.7827.55 Safari/537.36" { + t.Fatalf("headlessUserAgent=%v", userAgent) + } +} + +// TestSkipPlaywrightBrowserDownloadFromEnv 验证打包运行时可显式禁止 Playwright 下载新的浏览器。 func TestSkipPlaywrightBrowserDownloadFromEnv(t *testing.T) { t.Setenv("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD", "") if skipPlaywrightBrowserDownload() { diff --git a/internal/browser/qrrefresh.go b/internal/browser/qrrefresh.go index 1c44aea..b271f82 100644 --- a/internal/browser/qrrefresh.go +++ b/internal/browser/qrrefresh.go @@ -47,6 +47,7 @@ func (m *Manager) QRCookieRefresh(ctx context.Context, tmpCookies, verificationU Viewport: &playwright.Size{Width: 1100, Height: 760}, Locale: playwright.String(defaultLang), TimezoneId: playwright.String(defaultTZ), + UserAgent: m.headlessUserAgent(), }) if err != nil { return "", "", fmt.Errorf("创建 context 失败: %w", err) @@ -62,8 +63,8 @@ func (m *Manager) QRCookieRefresh(ctx context.Context, tmpCookies, verificationU return "", "", fmt.Errorf("注入临时 cookie 失败: %w", err) } - // page、err 保存page、err,供当前处理流程使用 - page, err := bctx.NewPage() + // page 在导航前应用无头运行时指纹,避免扫码换取 Cookie 时暴露 HeadlessChrome。 + page, err := m.newBrowserPage(bctx, true) if err != nil { return "", "", fmt.Errorf("新建 page 失败: %w", err) } diff --git a/internal/browser/token_captcha.go b/internal/browser/token_captcha.go index ccba55a..2c972d9 100644 --- a/internal/browser/token_captcha.go +++ b/internal/browser/token_captcha.go @@ -174,7 +174,7 @@ func (m *Manager) TokenCaptchaRecoverWithEngine(ctx context.Context, cookieID, c ) } -func (m *Manager) tokenCaptchaPlaywrightRecover(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, _ TokenCaptchaURLProvider) (string, error) { +func (m *Manager) tokenCaptchaPlaywrightRecover(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, _ TokenCaptchaURLProvider) (result string, resultErr error) { if strings.TrimSpace(cookieStr) == "" { return "", fmt.Errorf("Cookie为空,无法处理 token 风控验证") } @@ -183,7 +183,8 @@ func (m *Manager) tokenCaptchaPlaywrightRecover(ctx context.Context, cookieID, c } currentCookies := cookieStr - bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, currentCookies, nil, quickRenewHeadless(headless), true) + headless = quickRenewHeadless(headless) + bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, currentCookies, nil, headless, true) if err != nil { return "", err } @@ -196,11 +197,18 @@ func (m *Manager) tokenCaptchaPlaywrightRecover(ctx context.Context, cookieID, c } previousX5SecValues := x5SecValues(beforeCookies) - page, err := bctx.NewPage() + page, err := m.newBrowserPage(bctx, headless) if err != nil { return "", fmt.Errorf("新建 page 失败: %w", err) } defer func() { _ = page.Close() }() + diagnostic := newTokenCaptchaDiagnostic(cookieID, "playwright", verificationURL, page, m.logger) + diagnosticSucceeded := false + defer func() { + if diagnostic != nil && !diagnosticSucceeded { + diagnostic.capture(page, "playwright_failed", resultErr) + } + }() if time.Now().After(browserDeadline) { return "", fmt.Errorf("token 风控浏览器验证超过 %s", tokenCaptchaBrowserTTL) @@ -230,6 +238,9 @@ func (m *Manager) tokenCaptchaPlaywrightRecover(ctx context.Context, cookieID, c m.logger.Warn("token 风控页面没有可验证滑块,停止自动验证", "cookieID", cookieID, "err", pageErr) return "", pageErr } + if diagnostic != nil { + diagnostic.snapshotInitial(page) + } scratch := isScratchCaptcha(content) if err := solveSliderStrict(page, scratch, m.logger, previousX5SecValues, browserDeadline); err != nil { @@ -245,6 +256,7 @@ func (m *Manager) tokenCaptchaPlaywrightRecover(ctx context.Context, cookieID, c merged[k] = v } m.logger.Info("token风控验证成功", "cookieID", cookieID, "x5_cookie_count", len(x5)) + diagnosticSucceeded = true return cookieMarshal(merged), nil } diff --git a/internal/browser/token_captcha_diagnostic.go b/internal/browser/token_captcha_diagnostic.go new file mode 100644 index 0000000..0e80af8 --- /dev/null +++ b/internal/browser/token_captcha_diagnostic.go @@ -0,0 +1,661 @@ +package browser + +// Token CAPTCHA diagnostics are deliberately opt-in. They collect enough +// information to distinguish a page/DOM change from a server-side rejection, +// without changing the frozen slider implementation or writing credentials to +// the normal application log. + +import ( + "archive/zip" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "log/slog" + "net/url" + "os" + "path/filepath" + "regexp" + "sort" + "strings" + "sync" + "time" + + "github.com/mxschmitt/playwright-go" + + "xianyu-go/internal/logsafe" +) + +const ( + // tokenCaptchaDiagnosticDirEnv 指定诊断 zip 的本地目录;未设置时完全不创建诊断器。 + tokenCaptchaDiagnosticDirEnv = "CAPTCHA_DIAGNOSTIC_DIR" + // tokenCaptchaDiagnosticSensitiveEnv 允许显式保留敏感正文,仅供受控排障环境,默认一律脱敏。 + tokenCaptchaDiagnosticSensitiveEnv = "CAPTCHA_DIAGNOSTIC_INCLUDE_SENSITIVE" + // tokenCaptchaDiagnosticMaxEvents 限制每类事件最多记录 500 条,避免诊断失败放大内存或磁盘消耗。 + tokenCaptchaDiagnosticMaxEvents = 500 +) + +// tokenCaptchaDiagnostic 在显式启用时收集一次 token CAPTCHA 失败现场;mu 保护事件与 initial,once 保证只写出一个包,且不得影响验证码结果路径。 +type tokenCaptchaDiagnostic struct { + cookieID string + engine string + requestedURL string + includeSensitive bool + dir string + startedAt time.Time + logger *slog.Logger + + mu sync.Mutex + requests []tokenCaptchaDiagnosticNetworkEvent + responses []tokenCaptchaDiagnosticNetworkEvent + console []tokenCaptchaDiagnosticConsoleEvent + pageError []string + initial tokenCaptchaDiagnosticSnapshot + once sync.Once +} + +// tokenCaptchaDiagnosticSnapshot 保存首次现场的页面、frame、选择器和截图,用于与最终失败现场比较。 +type tokenCaptchaDiagnosticSnapshot struct { + CapturedAt string + PageHTML string + Screenshot []byte + FrameHTML map[int]string + Frames []tokenCaptchaDiagnosticFrame + Selectors []tokenCaptchaDiagnosticSelector +} + +// tokenCaptchaDiagnosticNetworkEvent 是脱敏后的单条网络请求、响应或失败记录。 +type tokenCaptchaDiagnosticNetworkEvent struct { + Kind string `json:"kind"` + At string `json:"at"` + URL string `json:"url"` + Method string `json:"method,omitempty"` + ResourceType string `json:"resource_type,omitempty"` + Navigation bool `json:"navigation,omitempty"` + Status int `json:"status,omitempty"` + ContentType string `json:"content_type,omitempty"` + Failure string `json:"failure,omitempty"` +} + +// tokenCaptchaDiagnosticConsoleEvent 保存页面控制台输出,默认先去除可能出现的凭证和验证参数。 +type tokenCaptchaDiagnosticConsoleEvent struct { + At string `json:"at"` + Type string `json:"type"` + Text string `json:"text"` +} + +// tokenCaptchaDiagnosticFrame 描述当前页面树中一个 frame 的来源、父级和可读 HTML 状态。 +type tokenCaptchaDiagnosticFrame struct { + Index int `json:"index"` + Name string `json:"name,omitempty"` + URL string `json:"url"` + ParentURL string `json:"parent_url,omitempty"` + HTMLBytes int `json:"html_bytes,omitempty"` + ContentErr string `json:"content_error,omitempty"` +} + +// tokenCaptchaDiagnosticSelector 记录冻结选择器在某个 frame 中的发现、可见和边界框状态,不改变选择器本身。 +type tokenCaptchaDiagnosticSelector struct { + FrameIndex int `json:"frame_index"` + FrameURL string `json:"frame_url"` + Selector string `json:"selector"` + Found bool `json:"found"` + Visible bool `json:"visible,omitempty"` + Box string `json:"box,omitempty"` + Error string `json:"error,omitempty"` +} + +// tokenCaptchaDiagnosticManifest 是诊断 zip 的脱敏索引,关联失败阶段、页面快照和有限事件流。 +type tokenCaptchaDiagnosticManifest struct { + Version int `json:"version"` + CreatedAt string `json:"created_at"` + CookieIDHash string `json:"cookie_id_hash"` + Engine string `json:"engine"` + Phase string `json:"phase"` + Cause string `json:"cause,omitempty"` + RequestedURL string `json:"requested_url"` + CurrentURL string `json:"current_url"` + Title string `json:"title,omitempty"` + IncludeSensitive bool `json:"include_sensitive"` + PageState map[string]any `json:"page_state,omitempty"` + Frames []tokenCaptchaDiagnosticFrame `json:"frames,omitempty"` + Selectors []tokenCaptchaDiagnosticSelector `json:"selectors,omitempty"` + InitialCapturedAt string `json:"initial_captured_at,omitempty"` + InitialFrames []tokenCaptchaDiagnosticFrame `json:"initial_frames,omitempty"` + InitialSelectors []tokenCaptchaDiagnosticSelector `json:"initial_selectors,omitempty"` + Requests []tokenCaptchaDiagnosticNetworkEvent `json:"requests,omitempty"` + Responses []tokenCaptchaDiagnosticNetworkEvent `json:"responses,omitempty"` + Console []tokenCaptchaDiagnosticConsoleEvent `json:"console,omitempty"` + PageErrors []string `json:"page_errors,omitempty"` +} + +// newTokenCaptchaDiagnostic 在环境指定目录且 page 可用时安装只读诊断监听器;cookieID 仅存于内存且写包时哈希,返回 nil 表示诊断未启用。 +func newTokenCaptchaDiagnostic(cookieID, engine, requestedURL string, page playwright.Page, logger *slog.Logger) *tokenCaptchaDiagnostic { + // dir 是诊断包输出目录,空值保持功能完全关闭。 + dir := strings.TrimSpace(os.Getenv(tokenCaptchaDiagnosticDirEnv)) + if dir == "" || page == nil { + return nil + } + // d 持有本页监听器共享的诊断状态,回调通过 mu 串行写入有限事件列表。 + d := &tokenCaptchaDiagnostic{ + cookieID: cookieID, + engine: engine, + requestedURL: requestedURL, + includeSensitive: diagnosticBoolEnv(tokenCaptchaDiagnosticSensitiveEnv), + dir: dir, + startedAt: time.Now().UTC(), + logger: logger, + } + // request 是 Playwright 提供的请求事件,回调仅记录已脱敏的元数据。 + page.OnRequest(func(request playwright.Request) { + d.recordRequest(request) + }) + // response 是 Playwright 提供的响应事件,回调不会读取或持久化响应正文。 + page.OnResponse(func(response playwright.Response) { + d.recordResponse(response) + }) + // request 是失败的网络请求,回调在 d.mu 保护下追加一条受限数量的失败事件。 + page.OnRequestFailed(func(request playwright.Request) { + d.mu.Lock() + defer d.mu.Unlock() + if len(d.responses) >= tokenCaptchaDiagnosticMaxEvents { + return + } + // failure 保存底层失败文本,默认不会包含请求 Cookie;err 表示 Playwright 无法提供失败详情。 + failure := "" + // err 表示 Playwright 未能返回底层失败详情,失败事件仍保留其他无敏感元数据。 + if err := request.Failure(); err != nil { + failure = err.Error() + } + d.responses = append(d.responses, tokenCaptchaDiagnosticNetworkEvent{ + Kind: "request_failed", + At: time.Now().UTC().Format(time.RFC3339Nano), + URL: d.safeURL(request.URL()), + Method: request.Method(), + ResourceType: request.ResourceType(), + Navigation: request.IsNavigationRequest(), + Failure: failure, + }) + }) + // message 是页面控制台事件,内容在未授权敏感采集时先经过文本脱敏。 + page.OnConsole(func(message playwright.ConsoleMessage) { + d.mu.Lock() + defer d.mu.Unlock() + if len(d.console) >= tokenCaptchaDiagnosticMaxEvents { + return + } + // text 是待写入诊断包的控制台文本,敏感模式关闭时会就地替换秘密参数。 + text := message.Text() + if !d.includeSensitive { + text = redactDiagnosticText(text) + } + d.console = append(d.console, tokenCaptchaDiagnosticConsoleEvent{ + At: time.Now().UTC().Format(time.RFC3339Nano), + Type: message.Type(), + Text: text, + }) + }) + page.OnPageError(func(pageErr error) { + d.mu.Lock() + defer d.mu.Unlock() + if pageErr == nil || len(d.pageError) >= tokenCaptchaDiagnosticMaxEvents { + return + } + // text 是待脱敏的页面异常文本,不能直接写入普通应用日志。 + text := pageErr.Error() + if !d.includeSensitive { + text = redactDiagnosticText(text) + } + d.pageError = append(d.pageError, text) + }) + return d +} + +// diagnosticBoolEnv 按受限真值集合读取诊断开关,任何未知文本均按关闭处理。 +func diagnosticBoolEnv(name string) bool { + switch strings.ToLower(strings.TrimSpace(os.Getenv(name))) { + case "1", "true", "yes", "on": + return true + default: + return false + } +} + +// recordRequest 在 d.mu 保护下记录一条脱敏请求元数据;达到上限后静默丢弃后续事件。 +func (d *tokenCaptchaDiagnostic) recordRequest(request playwright.Request) { + d.mu.Lock() + defer d.mu.Unlock() + if len(d.requests) >= tokenCaptchaDiagnosticMaxEvents { + return + } + d.requests = append(d.requests, tokenCaptchaDiagnosticNetworkEvent{ + Kind: "request", + At: time.Now().UTC().Format(time.RFC3339Nano), + URL: d.safeURL(request.URL()), + Method: request.Method(), + ResourceType: request.ResourceType(), + Navigation: request.IsNavigationRequest(), + }) +} + +// recordResponse 在 d.mu 保护下记录一条脱敏响应元数据,不读取可能包含凭证的响应正文。 +func (d *tokenCaptchaDiagnostic) recordResponse(response playwright.Response) { + d.mu.Lock() + defer d.mu.Unlock() + if len(d.responses) >= tokenCaptchaDiagnosticMaxEvents { + return + } + // request 是与响应关联的请求,只用于记录方法和资源类型;contentType 只记录公开的响应媒体类型。 + request := response.Request() + // contentType 记录响应的公开媒体类型,不读取可能携带账号数据的响应正文。 + contentType := response.Headers()["content-type"] + d.responses = append(d.responses, tokenCaptchaDiagnosticNetworkEvent{ + Kind: "response", + At: time.Now().UTC().Format(time.RFC3339Nano), + URL: d.safeURL(response.URL()), + Method: request.Method(), + ResourceType: request.ResourceType(), + Navigation: request.IsNavigationRequest(), + Status: response.Status(), + ContentType: contentType, + }) +} + +// safeURL 在默认模式删除 URL 查询值与 fragment,仅保留排序后的参数名和查询摘要;敏感模式由显式环境授权才原样返回。 +func (d *tokenCaptchaDiagnostic) safeURL(raw string) string { + if d.includeSensitive { + return raw + } + // u 是可结构化脱敏的 URL;err 表示输入不符合完整 URL 格式,此时回退通用日志脱敏。 + u, err := url.Parse(strings.TrimSpace(raw)) + if err != nil || u.Scheme == "" || u.Host == "" { + return logsafe.URL(raw) + } + if u.RawQuery == "" && u.Fragment == "" { + return logsafe.URL(raw) + } + // values 是解析出的查询参数;keys 只保留键名以表达请求形状而不暴露验证值。 + values := u.Query() + // keys 只收集诊断中允许暴露的参数名,容量按查询字段数预留。 + keys := make([]string, 0, len(values)) + // key 是当前查询参数名,诊断包中允许保留但不保留对应值。 + for key := range values { + keys = append(keys, key) + } + sort.Strings(keys) + // queryDigest 是原始查询串的短摘要,用于关联重复请求而不记录实际参数值。 + queryDigest := sha256.Sum256([]byte(u.RawQuery)) + u.RawQuery = "keys=" + strings.Join(keys, ",") + "&query_sha256=" + hex.EncodeToString(queryDigest[:])[:16] + u.Fragment = "" + return u.String() +} + +// capture 在 d.once 保护下为一次失败写出诊断包;任何写包错误只输出脱敏错误并绝不改变 CAPTCHA 结果。 +func (d *tokenCaptchaDiagnostic) capture(page playwright.Page, phase string, cause error) { + if d == nil || page == nil { + return + } + // once 回调是唯一允许写包的路径,避免多个失败回调竞争创建诊断文件。 + d.once.Do(func() { + // path 是生成 zip 的本地路径;err 表示诊断写入失败,不能向调用路径传播。 + path, err := d.writeBundle(page, phase, cause) + if err != nil { + // Diagnostics must never affect the CAPTCHA result path. + fmt.Fprintf(os.Stderr, "token captcha diagnostic capture failed: %v\n", err) + } else if d.logger != nil { + d.logger.Info("token风控诊断包已生成", "cookieID", d.cookieID, "engine", d.engine, "path", path, "include_sensitive", d.includeSensitive) + } + }) +} + +// snapshotInitial 最多捕获一次导航后的初始现场;先在无锁状态读取 Playwright,再持锁发布完整快照,避免持锁外部 I/O。 +func (d *tokenCaptchaDiagnostic) snapshotInitial(page playwright.Page) { + if d == nil || page == nil { + return + } + d.mu.Lock() + if d.initial.CapturedAt != "" { + d.mu.Unlock() + return + } + d.mu.Unlock() + + // snapshot 是无锁构造的初始页面副本,完成后仅在 initial 仍为空时发布。 + snapshot := tokenCaptchaDiagnosticSnapshot{ + CapturedAt: time.Now().UTC().Format(time.RFC3339Nano), + FrameHTML: make(map[int]string), + } + snapshot.PageHTML, _ = page.Content() + snapshot.Screenshot, _ = page.Screenshot(playwright.PageScreenshotOptions{FullPage: playwright.Bool(true), Timeout: playwright.Float(5000)}) + snapshot.Frames, snapshot.Selectors = diagnosticFramesAndSelectors(page, d) + // index 是诊断包中的稳定 frame 序号;frame 是当前待抓取 HTML 的页面 frame。 + for index, frame := range append([]playwright.Frame{page.MainFrame()}, page.Frames()...) { + // htmlText 是 frame 的初始 HTML;err 表示 frame 内容暂不可读,此时不影响整体诊断。 + if htmlText, err := frame.Content(); err == nil { + snapshot.FrameHTML[index] = htmlText + } + } + d.mu.Lock() + if d.initial.CapturedAt == "" { + d.initial = snapshot + } + d.mu.Unlock() +} + +// writeBundle 将当前和初始诊断现场写为原子 zip;返回最终本地路径,错误仅供 capture 记录而不得影响验证码流程。 +func (d *tokenCaptchaDiagnostic) writeBundle(page playwright.Page, phase string, cause error) (string, error) { + // err 表示私有诊断目录无法创建,目录权限固定为仅当前用户可访问。 + if err := os.MkdirAll(d.dir, 0o700); err != nil { + return "", err + } + // name 是不含明文账号标识的诊断文件名;target 是最终原子替换目标。 + name := fmt.Sprintf("token-captcha-%s-%s-%s.zip", logsafe.ID(d.cookieID), d.startedAt.Format("20060102T150405.000000000Z"), sanitize(d.engine)) + // target 是完成写入后通过同目录 Rename 发布的最终诊断 zip 路径。 + target := filepath.Join(d.dir, name) + // tmp 是同目录的临时 zip;err 表示临时文件无法创建。 + tmp, err := os.CreateTemp(d.dir, ".token-captcha-*.zip.tmp") + if err != nil { + return "", err + } + // tmpName 用于 defer 清理和最终同目录 Rename,保证读者不会看到半写入文件。 + tmpName := tmp.Name() + defer func() { + _ = tmp.Close() + _ = os.Remove(tmpName) + }() + // zw 是写入临时文件的 zip 流;closeZip 负责按成功或失败路径关闭并执行原子发布。 + zw := zip.NewWriter(tmp) + // closeZip 在任一路径关闭流;成功时关闭临时文件并原子发布,失败时只返回原始操作错误。 + closeZip := func(closeErr error) error { + if closeErr != nil { + _ = zw.Close() + return closeErr + } + // err 表示 zip 尾部无法完成写入,此时不发布损坏的诊断包。 + if err := zw.Close(); err != nil { + return err + } + // err 表示临时文件无法落盘关闭,Rename 前必须返回失败。 + if err := tmp.Close(); err != nil { + return err + } + return os.Rename(tmpName, target) + } + + d.mu.Lock() + // requests、responses、console、pageErrors 是锁内事件的独立副本,后续 zip I/O 不持有 d.mu。 + requests := append([]tokenCaptchaDiagnosticNetworkEvent(nil), d.requests...) + // responses 是响应和请求失败事件的锁内副本,后续写 zip 时不访问共享切片。 + responses := append([]tokenCaptchaDiagnosticNetworkEvent(nil), d.responses...) + // console 是已按敏感模式处理的控制台事件副本。 + console := append([]tokenCaptchaDiagnosticConsoleEvent(nil), d.console...) + // pageErrors 是已按敏感模式处理的页面异常文本副本。 + pageErrors := append([]string(nil), d.pageError...) + d.mu.Unlock() + // manifest 汇总可安全序列化的失败上下文,URL 和正文依赖当前敏感模式决定是否脱敏。 + manifest := tokenCaptchaDiagnosticManifest{ + Version: 1, + CreatedAt: time.Now().UTC().Format(time.RFC3339Nano), + CookieIDHash: logsafe.ID(d.cookieID), + Engine: d.engine, + Phase: phase, + RequestedURL: d.safeURL(d.requestedURL), + CurrentURL: d.safeURL(page.URL()), + IncludeSensitive: d.includeSensitive, + Requests: requests, + Responses: responses, + Console: console, + PageErrors: pageErrors, + } + if cause != nil { + manifest.Cause = cause.Error() + } + // title 是当前页面标题;titleErr 表示读取失败,此项可缺失且不阻塞诊断。 + if title, titleErr := page.Title(); titleErr == nil { + manifest.Title = title + } + manifest.PageState = diagnosticPageState(page, d.includeSensitive) + manifest.Frames, manifest.Selectors = diagnosticFramesAndSelectors(page, d) + d.mu.Lock() + // initial 是初始快照副本,FrameHTML 与 Screenshot 必须深拷贝后才能在无锁状态写包。 + initial := d.initial + initial.FrameHTML = cloneDiagnosticFrameHTML(initial.FrameHTML) + initial.Screenshot = append([]byte(nil), initial.Screenshot...) + d.mu.Unlock() + manifest.InitialCapturedAt = initial.CapturedAt + manifest.InitialFrames = initial.Frames + manifest.InitialSelectors = initial.Selectors + + // manifestJSON 是格式化后的索引内容;err 表示存在无法编码的诊断字段。 + manifestJSON, err := json.MarshalIndent(manifest, "", " ") + if err != nil { + return "", closeZip(err) + } + // err 表示索引条目未能写入 zip,closeZip 负责关闭资源并保留原始错误。 + if err := writeZipEntry(zw, "manifest.json", manifestJSON); err != nil { + return "", closeZip(err) + } + // readme 说明诊断包来源和默认脱敏边界,不包含任何运行时凭证。 + readme := []byte("This archive was generated by the opt-in token CAPTCHA diagnostic mode.\n" + + "It contains page/frame/selector/network metadata and a screenshot captured on failure.\n" + + "Cookie values and verification query values are redacted unless CAPTCHA_DIAGNOSTIC_INCLUDE_SENSITIVE=1.\n") + // err 表示说明文件写入失败,诊断包不能作为完整工件发布。 + if err := writeZipEntry(zw, "README.txt", readme); err != nil { + return "", closeZip(err) + } + // htmlText 是最终页面 HTML;htmlErr 表示页面内容暂不可读取,可继续输出其余诊断信息。 + if htmlText, htmlErr := page.Content(); htmlErr == nil { + if !d.includeSensitive { + htmlText = redactDiagnosticText(htmlText) + } + // err 表示最终页面 HTML 条目写入失败。 + if err := writeZipEntry(zw, "page.html", []byte(htmlText)); err != nil { + return "", closeZip(err) + } + } + if initial.PageHTML != "" { + // initialHTML 是待输出的初始页面 HTML,敏感模式关闭时在写入前脱敏。 + initialHTML := initial.PageHTML + if !d.includeSensitive { + initialHTML = redactDiagnosticText(initialHTML) + } + // err 表示初始页面 HTML 条目写入失败。 + if err := writeZipEntry(zw, "initial/page.html", []byte(initialHTML)); err != nil { + return "", closeZip(err) + } + } + // index 是初始 frame 序号;frameHTML 是对应 HTML 副本,写前按敏感模式脱敏。 + for index, frameHTML := range initial.FrameHTML { + if !d.includeSensitive { + frameHTML = redactDiagnosticText(frameHTML) + } + // err 表示初始 frame 条目写入失败。 + if err := writeZipEntry(zw, fmt.Sprintf("initial/frames/frame-%02d.html", index), []byte(frameHTML)); err != nil { + return "", closeZip(err) + } + } + if len(initial.Screenshot) > 0 { + // err 表示初始截图条目写入失败。 + if err := writeZipEntry(zw, "initial/page.png", initial.Screenshot); err != nil { + return "", closeZip(err) + } + } + // index 是最终现场 frame 序号;frame 是待读取和输出 HTML 的页面 frame。 + for index, frame := range append([]playwright.Frame{page.MainFrame()}, page.Frames()...) { + // frameHTML 是最终 HTML;frameErr 表示当前 frame 内容不可用,可跳过而继续打包。 + frameHTML, frameErr := frame.Content() + if frameErr != nil { + continue + } + if !d.includeSensitive { + frameHTML = redactDiagnosticText(frameHTML) + } + // err 表示最终 frame 条目写入失败。 + if err := writeZipEntry(zw, fmt.Sprintf("frames/frame-%02d.html", index), []byte(frameHTML)); err != nil { + return "", closeZip(err) + } + } + // screenshot 是最终页面截图;screenshotErr 表示截图暂不可用,此时仍允许发布文本诊断。 + if screenshot, screenshotErr := page.Screenshot(playwright.PageScreenshotOptions{FullPage: playwright.Bool(true), Timeout: playwright.Float(5000)}); screenshotErr == nil { + // err 表示截图条目写入失败。 + if err := writeZipEntry(zw, "page.png", screenshot); err != nil { + return "", closeZip(err) + } + } + // err 表示 zip 收尾或原子发布失败,调用方只记录该诊断错误。 + if err := closeZip(nil); err != nil { + return "", err + } + return target, nil +} + +// cloneDiagnosticFrameHTML 深拷贝 frame HTML 索引,避免 writeBundle 无锁处理时与 snapshot 发布共享 map。 +func cloneDiagnosticFrameHTML(input map[int]string) map[int]string { + if len(input) == 0 { + return nil + } + // output 是供调用方独占修改的 frame HTML map。 + output := make(map[int]string, len(input)) + // index 是 frame 序号;htmlText 是其已捕获的 HTML 文本。 + for index, htmlText := range input { + output[index] = htmlText + } + return output +} + +// writeZipEntry 在 zw 中创建 name 并写入 data,返回创建或写入错误但不关闭调用方拥有的 zip 流。 +func writeZipEntry(zw *zip.Writer, name string, data []byte) error { + // writer 是当前 zip 条目的写入器;err 表示条目名冲突或底层临时文件写入失败。 + writer, err := zw.Create(name) + if err != nil { + return err + } + _, err = writer.Write(data) + return err +} + +// diagnosticPageState 读取页面公开运行状态;includeSensitive 为 false 时正文文本在返回前脱敏,脚本失败也返回可序列化错误状态。 +func diagnosticPageState(page playwright.Page, includeSensitive bool) map[string]any { + // value 是页面脚本状态对象;err 表示脚本评估失败并转换为诊断字段而非向上返回。 + value, err := page.Evaluate(`async () => { + let userAgentData = null; + if (navigator.userAgentData) { + userAgentData = { + brands: navigator.userAgentData.brands, + mobile: navigator.userAgentData.mobile, + platform: navigator.userAgentData.platform + }; + try { + userAgentData.high_entropy = await navigator.userAgentData.getHighEntropyValues([ + 'architecture', 'bitness', 'fullVersionList', 'model', 'platformVersion', 'wow64' + ]); + } catch (error) { + userAgentData.high_entropy_error = String(error); + } + } + return { + ready_state: document.readyState, + location_path: window.location.pathname, + location_query_present: Boolean(window.location.search), + inner_width: window.innerWidth, + inner_height: window.innerHeight, + device_pixel_ratio: window.devicePixelRatio, + user_agent: navigator.userAgent, + user_agent_data: userAgentData, + webdriver: navigator.webdriver, + has_nc_container: Boolean(document.querySelector('.nc-container')), + has_errloading: Boolean(document.querySelector('.errloading')), + body_text: (document.body && document.body.innerText || '').slice(0, 1200) + }; + }`) + if err != nil { + return map[string]any{"error": err.Error()} + } + // state 是可写入 manifest 的页面状态对象;ok 表示脚本结果保持了预期结构。 + if state, ok := value.(map[string]any); ok { + // body 是页面正文摘要;ok 表示该字段可按字符串脱敏处理。 + if body, ok := state["body_text"].(string); ok && !includeSensitive { + state["body_text"] = redactDiagnosticText(body) + } + return state + } + return map[string]any{"value": value} +} + +// diagnosticFramesAndSelectors 枚举页面及嵌套 frame 中冻结选择器的观测结果;仅读取 DOM,不改变滑块实现、选择器优先级或页面状态。 +func diagnosticFramesAndSelectors(page playwright.Page, d *tokenCaptchaDiagnostic) ([]tokenCaptchaDiagnosticFrame, []tokenCaptchaDiagnosticSelector) { + // frames 是主 frame 加全部已知 frame 的诊断遍历序列。 + frames := append([]playwright.Frame{page.MainFrame()}, page.Frames()...) + // frameMetadata 保存每个 frame 的来源和 HTML 可读性;selectors 是冻结选择器的本地副本,仅供观测。 + frameMetadata := make([]tokenCaptchaDiagnosticFrame, 0, len(frames)) + // selectors 是三个冻结选择器列表的本地拼接副本,仅用于诊断查询。 + selectors := append([]string{}, sliderButtonSelectors...) + selectors = append(selectors, sliderTrackSelectors...) + selectors = append(selectors, sliderRetrySelectors...) + // index 是 frame 在诊断包中的稳定序号;frame 是当前待记录的页面 frame。 + for index, frame := range frames { + // parentURL 是脱敏后的父 frame 地址,主 frame 保持空字符串。 + parentURL := "" + // parent 是当前 frame 的父级,存在时用于记录嵌套来源。 + if parent := frame.ParentFrame(); parent != nil { + parentURL = d.safeURL(parent.URL()) + } + // metadata 是当前 frame 的可序列化观测记录。 + metadata := tokenCaptchaDiagnosticFrame{Index: index, Name: frame.Name(), URL: d.safeURL(frame.URL()), ParentURL: parentURL} + // htmlText 是用来计算大小的 frame HTML;err 表示内容不可读并记录到 metadata。 + if htmlText, err := frame.Content(); err == nil { + metadata.HTMLBytes = len(htmlText) + } else { + metadata.ContentErr = err.Error() + } + frameMetadata = append(frameMetadata, metadata) + } + // selectorRecords 保存每个 frame/选择器组合的只读探测结果。 + selectorRecords := make([]tokenCaptchaDiagnosticSelector, 0, len(frames)*len(selectors)) + // index 是当前被探测 frame 的序号;frame 是执行只读选择器查询的 frame。 + for index, frame := range frames { + // frameURL 是写入诊断包的脱敏 frame 地址。 + frameURL := d.safeURL(frame.URL()) + // selector 是当前冻结选择器文本,只读取其可用状态,绝不修改定义或顺序。 + for _, selector := range selectors { + // entry 是当前 frame/选择器组合的诊断结果。 + entry := tokenCaptchaDiagnosticSelector{FrameIndex: index, FrameURL: frameURL, Selector: selector} + // el 是匹配到的页面元素;err 表示查询失败并记录在 entry 中。 + el, err := frame.QuerySelector(selector) + if err != nil { + entry.Error = err.Error() + } else if el != nil { + entry.Found = true + entry.Visible = elementVisible(el) + // box 是元素边界框;boxErr 表示当前无法读取位置,仍保留已发现状态。 + if box, boxErr := el.BoundingBox(); boxErr == nil { + entry.Box = formatBoundingBox(box) + } + } + selectorRecords = append(selectorRecords, entry) + } + } + return frameMetadata, selectorRecords +} + +// redactDiagnosticText 替换已知 Cookie、验证码和签名参数值,供默认诊断包的 URL、HTML、控制台和错误文本共同使用。 +func redactDiagnosticText(text string) string { + // key 是当前要隐藏值的敏感参数名,保留键名以便定位问题类别。 + for _, key := range []string{"x5secdata", "x5sec", "_m_h5_tk", "_m_h5_tk_enc", "token", "sign"} { + text = redactDiagnosticKey(text, key) + } + return text +} + +// redactDiagnosticKey 用大小写无关模式隐藏 text 中指定 key 的值,不记录 Cookie、Token 或签名明文。 +func redactDiagnosticKey(text, key string) string { + // pattern 匹配参数值直到常见分隔符,键名由 QuoteMeta 处理以避免改变正则语义。 + pattern := regexp.MustCompile(`(?i)` + regexp.QuoteMeta(key) + `=[^&'"<>\s\\` + "`" + `)]*`) + return pattern.ReplaceAllStringFunc(text, func(match string) string { + // index 是键和值之间等号的位置,存在时仅保留键和等号。 + if index := strings.IndexByte(match, '='); index >= 0 { + return match[:index+1] + "" + } + return match + }) +} diff --git a/internal/browser/token_captcha_diagnostic_test.go b/internal/browser/token_captcha_diagnostic_test.go new file mode 100644 index 0000000..d6a1566 --- /dev/null +++ b/internal/browser/token_captcha_diagnostic_test.go @@ -0,0 +1,141 @@ +package browser + +import ( + "archive/zip" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/mxschmitt/playwright-go" +) + +// TestTokenCaptchaDiagnosticRedactsSensitiveValues 验证默认诊断输出不会保留验证码查询值、fragment 或文本中的敏感凭证。 +func TestTokenCaptchaDiagnosticRedactsSensitiveValues(t *testing.T) { + // d 是禁用敏感内容采集的最小诊断器,不需要真实浏览器或输出目录。 + d := &tokenCaptchaDiagnostic{includeSensitive: false} + // got 是脱敏后的 URL,允许保留参数名与查询摘要以支持问题关联。 + got := d.safeURL("https://example.test/punish?x5secdata=secret-value&action=captcha#fragment") + if strings.Contains(got, "secret-value") || strings.Contains(got, "fragment") { + t.Fatalf("safeURL leaked sensitive data: %q", got) + } + if !strings.Contains(got, "x5secdata") || !strings.Contains(got, "query_sha256") { + t.Fatalf("safeURL lost query diagnostics: %q", got) + } + // text 是同时含 Cookie 验证和签名类参数的模拟诊断文本。 + text := `x5secdata=secret-value&token=another-secret sign=third-secret` + // redacted 是可安全写入默认诊断包的替换后文本。 + redacted := redactDiagnosticText(text) + if strings.Contains(redacted, "secret-value") || strings.Contains(redacted, "another-secret") || strings.Contains(redacted, "third-secret") { + t.Fatalf("redactDiagnosticText leaked sensitive data: %q", redacted) + } +} + +// TestTokenCaptchaDiagnosticBundleBrowserIntegration 在真实 Chromium 中验证诊断包包含必要现场且默认不泄漏验证码查询值;仅在显式浏览器集成模式运行。 +func TestTokenCaptchaDiagnosticBundleBrowserIntegration(t *testing.T) { + if os.Getenv("RUN_BROWSER_INTEGRATION") != "1" { + t.Skip("set RUN_BROWSER_INTEGRATION=1 to exercise token CAPTCHA diagnostics") + } + // server 提供含冻结滑块元素的本地页面,避免访问真实平台或使用真实账号。 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + _, _ = io.WriteString(w, `诊断验证码 +
+`) + })) + defer server.Close() + + // dir 是 testing 管理的临时诊断输出目录,测试结束后自动清理。 + dir := t.TempDir() + t.Setenv(tokenCaptchaDiagnosticDirEnv, dir) + t.Setenv(tokenCaptchaDiagnosticSensitiveEnv, "") + // m 管理本次集成测试的 Playwright runtime,defer Close 负责回收资源。 + m := NewManager(nil) + defer m.Close() + // err 表示 runtime 初始化失败,无法继续验证真实浏览器诊断。 + if err := m.init(); err != nil { + t.Fatal(err) + } + // browser 是测试启动的无头 Chromium;err 表示启动失败。 + browser, err := m.pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{ + Headless: playwright.Bool(true), + Args: chromiumLaunchArgs(), + }) + if err != nil { + t.Fatal(err) + } + defer func() { _ = browser.Close() }() + // bctx 是 browser 的隔离页面上下文;err 表示 context 创建失败。 + bctx, err := browser.NewContext() + if err != nil { + t.Fatal(err) + } + defer func() { _ = bctx.Close() }() + // page 是承载诊断监听器的本地测试页面;err 表示页面创建失败。 + page, err := bctx.NewPage() + if err != nil { + t.Fatal(err) + } + // diagnostic 是由显式临时目录启用的诊断器,账户标识在产物中仅以哈希形式出现。 + diagnostic := newTokenCaptchaDiagnostic("diagnostic-account", "playwright", server.URL+"/punish?x5secdata=secret", page, m.logger) + // err 表示本地滑块页面导航失败,不能继续捕获诊断快照。 + if _, err := page.Goto(server.URL+"/punish?x5secdata=secret", playwright.PageGotoOptions{WaitUntil: playwright.WaitUntilStateDomcontentloaded}); err != nil { + t.Fatal(err) + } + diagnostic.snapshotInitial(page) + diagnostic.capture(page, "test_failure", io.ErrUnexpectedEOF) + + // archives 是输出目录中生成的诊断 zip;err 表示文件模式匹配失败。 + archives, err := filepath.Glob(filepath.Join(dir, "*.zip")) + if err != nil || len(archives) != 1 { + t.Fatalf("diagnostic archive count=%d err=%v", len(archives), err) + } + // archive 是待检查的唯一诊断 zip;err 表示压缩包无法读取。 + archive, err := zip.OpenReader(archives[0]) + if err != nil { + t.Fatal(err) + } + defer archive.Close() + // entries 按条目名保存压缩包内容,供后续完整性和脱敏断言使用。 + entries := make(map[string][]byte) + // file 是当前压缩包条目,逐个读取后立即关闭其 reader。 + for _, file := range archive.File { + // reader 是当前条目的读取器;readErr 表示条目打开失败。 + reader, readErr := file.Open() + if readErr != nil { + t.Fatal(readErr) + } + // data 是条目完整字节内容;readErr 表示读取过程失败。 + data, readErr := io.ReadAll(reader) + _ = reader.Close() + if readErr != nil { + t.Fatal(readErr) + } + entries[file.Name] = data + } + // name 是每个必须存在的诊断条目路径,缺失说明捕获或写包协议被破坏。 + for _, name := range []string{"README.txt", "manifest.json", "page.html", "page.png", "initial/page.html", "initial/page.png", "frames/frame-00.html", "initial/frames/frame-00.html"} { + if len(entries[name]) == 0 { + t.Fatalf("diagnostic archive missing %s", name) + } + } + // manifest 是从包内索引反序列化的结构,供断言失败阶段与初始快照信息。 + var manifest tokenCaptchaDiagnosticManifest + // err 表示 manifest JSON 不符合诊断包契约。 + if err := json.Unmarshal(entries["manifest.json"], &manifest); err != nil { + t.Fatal(err) + } + if manifest.Phase != "test_failure" || manifest.Engine != "playwright" { + t.Fatalf("unexpected manifest: %+v", manifest) + } + if manifest.InitialCapturedAt == "" || len(manifest.InitialFrames) == 0 || len(manifest.InitialSelectors) == 0 { + t.Fatalf("initial snapshot metadata missing: %+v", manifest) + } + if strings.Contains(string(entries["page.html"]), "secret") { + t.Fatalf("page HTML leaked query value") + } +} diff --git a/internal/browser/token_captcha_fallback.go b/internal/browser/token_captcha_fallback.go index c214c25..9a9e15f 100644 --- a/internal/browser/token_captcha_fallback.go +++ b/internal/browser/token_captcha_fallback.go @@ -29,7 +29,7 @@ var fallbackTrackSelectors = []string{ // tokenCaptchaCDPFallback 直接启动 Chromium 并通过 CDP 连接,复现参考项目的 // DrissionPage 第二引擎:它不复用 Playwright launch 协议,使用同一持久化目录和另一套轨迹。 -func (m *Manager) tokenCaptchaCDPFallback(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, _ TokenCaptchaURLProvider) (string, error) { +func (m *Manager) tokenCaptchaCDPFallback(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, _ TokenCaptchaURLProvider) (result string, resultErr error) { if strings.TrimSpace(cookieStr) == "" || strings.TrimSpace(verificationURL) == "" { return "", fmt.Errorf("备用滑块引擎参数不完整") } @@ -59,7 +59,7 @@ func (m *Manager) tokenCaptchaCDPFallback(ctx context.Context, cookieID, cookieS if strings.TrimSpace(executable) == "" { return "", fmt.Errorf("备用滑块引擎未找到 Chromium") } - args := fallbackChromiumArgs(profileDir, headless) + args := fallbackChromiumArgs(profileDir, headless, m.headlessUserAgent()) cmd := exec.Command(executable, args...) cmd.Stdout = io.Discard cmd.Stderr = io.Discard @@ -103,11 +103,18 @@ func (m *Manager) tokenCaptchaCDPFallback(ctx context.Context, cookieID, cookieS return "", fmt.Errorf("备用滑块引擎读取旧 Cookie: %w", err) } previousX5 := x5SecValues(before) - page, err := bctx.NewPage() + page, err := m.newBrowserPage(bctx, headless) if err != nil { return "", fmt.Errorf("备用滑块引擎创建页面: %w", err) } defer func() { _ = page.Close() }() + diagnostic := newTokenCaptchaDiagnostic(cookieID, "drissionpage", verificationURL, page, m.logger) + diagnosticSucceeded := false + defer func() { + if diagnostic != nil && !diagnosticSucceeded { + diagnostic.capture(page, "drissionpage_failed", resultErr) + } + }() deadline := time.Now().Add(drissionFallbackTimeout()) if _, err := page.Goto(verificationURL, playwright.PageGotoOptions{ @@ -123,6 +130,9 @@ func (m *Manager) tokenCaptchaCDPFallback(ctx context.Context, cookieID, cookieS m.logger.Warn("备用滑块引擎页面没有可验证滑块,停止自动验证", "cookieID", cookieID, "err", pageErr) return "", pageErr } + if diagnostic != nil { + diagnostic.snapshotInitial(page) + } for attempt := 0; attempt < 3; attempt++ { if err := contextDeadlineError(ctx, deadline); err != nil { @@ -182,6 +192,7 @@ func (m *Manager) tokenCaptchaCDPFallback(ctx context.Context, cookieID, cookieS merged[name] = value } m.logger.Info("备用滑块引擎验证成功", "cookieID", cookieID, "attempt", attempt+1) + diagnosticSucceeded = true return cookieMarshal(merged), nil } logSliderFailureState(m.logger, page, attempt+1) @@ -196,7 +207,7 @@ func (m *Manager) tokenCaptchaCDPFallback(ctx context.Context, cookieID, cookieS return "", fmt.Errorf("备用滑块引擎 3 次均失败") } -func fallbackChromiumArgs(profileDir string, headless bool) []string { +func fallbackChromiumArgs(profileDir string, headless bool, headlessUserAgent ...*string) []string { args := []string{ "--user-data-dir=" + profileDir, "--remote-debugging-port=0", @@ -205,9 +216,17 @@ func fallbackChromiumArgs(profileDir string, headless bool) []string { "--disable-blink-features=AutomationControlled", "--window-size=1920,1080", "--lang=zh-CN", - "about:blank", } args = append(playwrightChromiumCompatibilityArgs(), args...) + if captchaIgnoreCertificateErrors() { + args = append(args, "--ignore-certificate-errors") + } + if headless && len(headlessUserAgent) > 0 && headlessUserAgent[0] != nil { + if userAgent := normalizeHeadlessUserAgent(*headlessUserAgent[0]); userAgent != "" { + args = append(args, "--user-agent="+userAgent) + } + } + args = append(args, "about:blank") if headless { args = append([]string{"--headless=new"}, args...) } diff --git a/internal/browser/token_captcha_orchestrator_test.go b/internal/browser/token_captcha_orchestrator_test.go index 32071ca..fb9b2d0 100644 --- a/internal/browser/token_captcha_orchestrator_test.go +++ b/internal/browser/token_captcha_orchestrator_test.go @@ -259,12 +259,16 @@ func TestFallbackUsableDistanceMatchesStandardNCDOM(t *testing.T) { } func TestFallbackChromiumArgsUsePersistentCDPProfile(t *testing.T) { - args := strings.Join(fallbackChromiumArgs("/tmp/profile", true), " ") - for _, want := range []string{"--headless=new", "--user-data-dir=/tmp/profile", "--remote-debugging-port=0", "--window-size=1920,1080", "--disable-blink-features=AutomationControlled"} { + userAgent := "Mozilla/5.0 HeadlessChrome/149.0.7827.55 Safari/537.36" + args := strings.Join(fallbackChromiumArgs("/tmp/profile", true, &userAgent), " ") + for _, want := range []string{"--headless=new", "--user-data-dir=/tmp/profile", "--remote-debugging-port=0", "--window-size=1920,1080", "--disable-blink-features=AutomationControlled", "--user-agent=Mozilla/5.0 Chrome/149.0.7827.55 Safari/537.36"} { if !strings.Contains(args, want) { t.Fatalf("args 缺少 %q: %s", want, args) } } + if strings.Contains(args, "HeadlessChrome") { + t.Fatalf("备用 Chromium 参数仍暴露 HeadlessChrome: %s", args) + } } // TestFallbackChromiumArgsIncludePlaywrightCompatibilityFlags 验证备用 Chromium 保留 Playwright 兼容启动参数。 diff --git a/internal/chat/repository.go b/internal/chat/repository.go index d57c357..6c0c3ef 100644 --- a/internal/chat/repository.go +++ b/internal/chat/repository.go @@ -22,6 +22,12 @@ type Repository interface { UpdateMessageType(ctx context.Context, cookieID, key, messageType string) error // UpdateMessageStatus 更新外发消息状态并返回最新消息。 UpdateMessageStatus(ctx context.Context, cookieID, key, status string) (*db.ChatMessage, error) + // CountUnreadUserMessages 返回当前会话中非系统入站消息的未读数量。 + CountUnreadUserMessages(ctx context.Context, cookieID, chatID string) (int, error) + // MarkMessageRead 根据平台回执标记指定出站消息已读。 + MarkMessageRead(ctx context.Context, cookieID, key string, readAt int64) (*db.ChatMessage, error) + // MarkLatestOutgoingRead 在回执缺失消息键时标记会话最近一条未读出站消息。 + MarkLatestOutgoingRead(ctx context.Context, cookieID, chatID string, readAt int64) (*db.ChatMessage, error) } // storeRepository 将聚合 Store 的聊天相关 repository 适配为窄接口。 @@ -65,6 +71,21 @@ func (r storeRepository) UpdateMessageStatus(ctx context.Context, cookieID, key, return r.store.Chats.UpdateMessageStatus(ctx, cookieID, key, status) } +// CountUnreadUserMessages 委托消息级真实用户未读数统计。 +func (r storeRepository) CountUnreadUserMessages(ctx context.Context, cookieID, chatID string) (int, error) { + return r.store.Chats.CountUnreadUserMessages(ctx, cookieID, chatID) +} + +// MarkMessageRead 委托指定出站消息的已读回执写入。 +func (r storeRepository) MarkMessageRead(ctx context.Context, cookieID, key string, readAt int64) (*db.ChatMessage, error) { + return r.store.Chats.MarkMessageRead(ctx, cookieID, key, readAt) +} + +// MarkLatestOutgoingRead 委托会话级出站消息已读回退写入。 +func (r storeRepository) MarkLatestOutgoingRead(ctx context.Context, cookieID, chatID string, readAt int64) (*db.ChatMessage, error) { + return r.store.Chats.MarkLatestOutgoingRead(ctx, cookieID, chatID, readAt) +} + // newStoreRepository 从完整 Store 构造聊天服务使用的窄 repository。 func newStoreRepository(store *db.Store) Repository { if store == nil || store.Cookies == nil || store.Chats == nil { diff --git a/internal/chat/repository_test.go b/internal/chat/repository_test.go index df67d35..c44fd35 100644 --- a/internal/chat/repository_test.go +++ b/internal/chat/repository_test.go @@ -42,6 +42,21 @@ func (*fakeRepository) UpdateMessageStatus(_ context.Context, _ string, _ string return &db.ChatMessage{Status: status}, nil } +// CountUnreadUserMessages 为窄仓储测试提供空的真实用户未读统计结果。 +func (*fakeRepository) CountUnreadUserMessages(context.Context, string, string) (int, error) { + return 0, nil +} + +// MarkMessageRead 为窄仓储测试模拟指定出站消息的已读更新。 +func (*fakeRepository) MarkMessageRead(_ context.Context, _ string, key string, readAt int64) (*db.ChatMessage, error) { + return &db.ChatMessage{MessageKey: key, ReadStatus: 2, ReadAt: readAt}, nil +} + +// MarkLatestOutgoingRead 为窄仓储测试模拟缺失消息键时的会话级回退更新。 +func (*fakeRepository) MarkLatestOutgoingRead(_ context.Context, _ string, chatID string, readAt int64) (*db.ChatMessage, error) { + return &db.ChatMessage{ChatID: chatID, ReadStatus: 2, ReadAt: readAt}, nil +} + // TestServiceUsesNarrowRepository 验证聊天服务可以脱离完整 db.Store 运行。 func TestServiceUsesNarrowRepository(t *testing.T) { // repository 是只实现聊天所需方法的内存替身。 diff --git a/internal/chat/service.go b/internal/chat/service.go index 99b2bb4..8cff02c 100644 --- a/internal/chat/service.go +++ b/internal/chat/service.go @@ -145,10 +145,12 @@ func (s *Service) RecordConversationPage(ctx context.Context, accountID, myID st if lastMessageAt <= 0 { lastMessageAt = modifyTime } - // session 保存会话,供当前处理流程使用 + // unreadCount 是平台红点与本地真实用户消息状态归一后的展示数量。 + unreadCount := s.conversationUnreadCount(ctx, accountID, cid, peerID, conv, last, summary) + // session 保存待写入的非敏感会话摘要及归一后的未读数量。 session := db.ChatSession{CookieID: accountID, ChatID: cid, BuyerID: peerID, BuyerName: peerName, BuyerAvatar: avatar, ItemID: cleanNilString(ext["itemId"]), ItemTitle: cleanNilString(ext["itemTitle"]), LastMessage: summary, - LastMessageAt: lastMessageAt, UnreadCount: int(int64Value(conv["redPoint"]))} + LastMessageAt: lastMessageAt, UnreadCount: unreadCount} if // err 保存err,供当前处理流程使用 err := s.repository.UpsertSession(ctx, session); err != nil { return page, err @@ -161,7 +163,79 @@ func (s *Service) RecordConversationPage(ctx context.Context, accountID, myID st return page, nil } -// invalidNicknames 保存invalidNicknames,供当前处理流程使用 +// conversationUnreadCount 以平台红点为上限,并用本地真实用户消息已读状态排除系统卡片。 +func (s *Service) conversationUnreadCount(ctx context.Context, accountID, chatID, peerID string, conv, last map[string]any, summary string) int { + // official 保存平台会话红点;负数响应按零处理。 + official := int(int64Value(conv["redPoint"])) + if official < 0 { + official = 0 + } + if official == 0 { + return 0 + } + + // local、err 保存本地真实用户未读数及查询错误;查询失败时回退平台红点。 + if local, err := s.repository.CountUnreadUserMessages(ctx, accountID, chatID); err == nil && local > 0 { + // A stale local event must not make the badge exceed the official + // conversation signal. In normal operation these values are equal. + if local > official { + return official + } + return local + } + + if !historyMessageIsSystem(last, summary) { + // No message-level row exists yet (for example immediately after a + // fresh login), so retain the official count as a safe fallback. + return official + } + + // 闲小蜜会话只包含平台消息,永远不能制造用户红点。 + if strings.TrimSuffix(strings.TrimSpace(peerID), "@goofish") == "1400" { + return 0 + } + + // The official last-message envelope exposes unreadCount/readStatus for + // that item. Subtract that system portion from redPoint; when older server + // responses omit the fields, conservatively remove one system item. + // systemUnread 保存最后一条系统消息在官方会话红点中的未读份额。 + systemUnread := int(int64Value(last["unreadCount"])) + // readStatus 保存最后一条系统消息的协议已读状态,缺少未读数时用于保守扣除。 + readStatus := int64Value(last["readStatus"]) + if systemUnread <= 0 && readStatus != 2 { + systemUnread = 1 + } + if systemUnread > official { + systemUnread = official + } + return official - systemUnread +} + +// historyMessageIsSystem 判断平台会话摘要是否代表系统消息,避免系统卡片制造用户未读。 +func historyMessageIsSystem(last map[string]any, summary string) bool { + // extension 保存会话末条消息的扩展字段,包含协议发送者身份。 + extension := mapValue(last["extension"]) + // senderID 保存协议发送者标识,供系统账号和系统卡片分类使用。 + senderID := cleanNilString(extension["senderUserId"]) + // content 保存解码后的系统卡片内容;解码失败时保留空对象供后续摘要规则判断。 + content := map[string]any{} + // contentMap、ok 保存消息内容对象及其类型断言结果,非对象响应无需继续读取卡片字段。 + if contentMap, ok := last["content"].(map[string]any); ok { + // custom、ok 保存自定义消息容器及其类型断言结果,卡片编码仅存在于该容器。 + if custom, ok := contentMap["custom"].(map[string]any); ok { + // encoded 保存 Base64 卡片载荷,空载荷代表没有可解码的系统协议内容。 + if encoded := cleanNilString(custom["data"]); encoded != "" { + // raw、err 保存解码后的卡片 JSON 与解码错误;错误时退回摘要分类,且不传播载荷。 + if raw, err := base64.StdEncoding.DecodeString(encoded); err == nil { + _ = json.Unmarshal(raw, &content) + } + } + } + } + return isOfficialSystemMessage(content, senderID, summary) +} + +// invalidNicknames 保存不能作为买家真实昵称持久化的系统展示文本。 var invalidNicknames = map[string]struct{}{ "交易消息": {}, "系统消息": {}, "卡片消息": {}, "我完成了评价": {}, "对方完成了评价": {}, "快给ta一个评价吧~": {}, "卖家已发货": {}, "买家已付款": {}, "买家已确认收货": {}, @@ -207,6 +281,7 @@ type Incoming struct { BuyerID string BuyerName string Text string + MessageID string ItemID string Raw map[string]any } @@ -308,8 +383,11 @@ func (s *Service) RecordIncoming(ctx context.Context, in Incoming) (*db.ChatMess if sentAt == 0 { sentAt = time.Now().UTC().UnixMilli() } - // key 保存key,供当前处理流程使用 - key := extractString(in.Raw, "messageId", "message_id", "msgId", "mid", "uuid") + // key 优先使用引擎提供的稳定平台消息 ID,缺失时再从原始消息递归提取。 + key := strings.TrimSpace(in.MessageID) + if key == "" { + key = extractString(in.Raw, "messageId", "message_id", "msgId", "mid", "uuid") + } if key == "" { // raw 保存原始,供当前处理流程使用 raw, _ := json.Marshal(in.Raw) @@ -334,8 +412,8 @@ func (s *Service) RecordIncoming(ctx context.Context, in Incoming) (*db.ChatMess // message 保存消息,供当前处理流程使用 message := db.ChatMessage{MessageKey: key, Direction: "incoming", SenderID: in.BuyerID, SenderName: in.BuyerName, MessageType: messageType, Content: content, Status: "received", SentAt: sentAt} - // stored、inserted、err 保存stored、inserted、err,供当前处理流程使用 - stored, inserted, err := s.repository.SaveMessage(ctx, session, message, true) + // stored、inserted、err 保存落库消息、首次插入标识及错误;系统消息永不增加用户红点。 + stored, inserted, err := s.repository.SaveMessage(ctx, session, message, messageType != "system") if err == nil && inserted { s.Publish(in.AccountID, Event{Type: "message.created", Message: stored, Session: &session}) } @@ -665,7 +743,27 @@ func (s *Service) SetOutgoingStatus(ctx context.Context, accountID, key, status return message, err } -// randomID 负责randomID相关处理。 +// MarkOutgoingRead 根据平台回执把指定出站消息标记已读并广播增量事件。 +func (s *Service) MarkOutgoingRead(ctx context.Context, accountID, key string, readAt int64) (*db.ChatMessage, error) { + // message、err 保存已读更新后的消息及持久化错误。 + message, err := s.repository.MarkMessageRead(ctx, accountID, key, readAt) + if err == nil { + s.Publish(accountID, Event{Type: "message.updated", Message: message}) + } + return message, err +} + +// MarkLatestOutgoingRead 在回执未带幂等键时回退标记会话最近待确认的出站消息。 +func (s *Service) MarkLatestOutgoingRead(ctx context.Context, accountID, chatID string, readAt int64) (*db.ChatMessage, error) { + // message、err 保存回退更新后的消息及持久化错误。 + message, err := s.repository.MarkLatestOutgoingRead(ctx, accountID, chatID, readAt) + if err == nil { + s.Publish(accountID, Event{Type: "message.updated", Message: message}) + } + return message, err +} + +// randomID 生成本地出站消息幂等键的随机后缀;随机源失败时使用时间回退避免阻断发送。 func randomID() string { // value 保存值,供当前处理流程使用 var value [16]byte @@ -715,6 +813,18 @@ func extractString(value any, keys ...string) string { return text } } + case string: + // Live WS envelopes often keep extJson/bizTag as an encoded JSON + // string. Decode it so messageId is preserved instead of falling + // back to a local in-* key. + // decoded 保存 extJson/bizTag 解码后的动态对象,供递归查找平台消息键。 + var decoded any + if json.Unmarshal([]byte(x), &decoded) == nil { + // text 保存递归命中的非空消息键,命中后立即返回避免生成本地回退键。 + if text := walk(decoded); text != "" { + return text + } + } } return "" } diff --git a/internal/chat/service_test.go b/internal/chat/service_test.go index 23f74e2..4ec8dc4 100644 --- a/internal/chat/service_test.go +++ b/internal/chat/service_test.go @@ -130,7 +130,29 @@ func TestRecordIncomingClassifiesXianxiaomiAndPlaceholder(t *testing.T) { } } -// TestRecordConversationPageImportsHistoricalContacts 负责TestRecordConversation页码ImportsHistoricalContacts相关处理。 +// TestRecordIncomingExtractsMessageIDFromEncodedExtension 验证嵌套扩展中的平台消息键优先进入实时落库。 +func TestRecordIncomingExtractsMessageIDFromEncodedExtension(t *testing.T) { + // store、cleanup 保存隔离聊天数据库及清理函数,确保消息键提取不依赖其他用例数据。 + store, cleanup := chatTestStore(t) + defer cleanup() + // service 是待测聊天服务,使用上述存储验证实时消息落库。 + service := New(store) + // message、err 保存落库后的消息和处理错误,消息键必须来自编码扩展字段。 + message, _, err := service.RecordIncoming(context.Background(), Incoming{ + AccountID: "account-1", ChatID: "live", BuyerID: "peer", BuyerName: "对方", Text: "实时消息", + Raw: map[string]any{"1": map[string]any{"10": map[string]any{ + "extJson": `{"messageId":"live-123"}`, + }}}, + }) + if err != nil { + t.Fatal(err) + } + if message.MessageKey != "live-123" { + t.Fatalf("实时消息未提取平台 messageId: %+v", message) + } +} + +// TestRecordConversationPageImportsHistoricalContacts 验证联系人历史页不会覆盖较新的会话摘要。 func TestRecordConversationPageImportsHistoricalContacts(t *testing.T) { // store、cleanup 保存store、cleanup,供当前处理流程使用 store, cleanup := chatTestStore(t) @@ -197,6 +219,7 @@ func TestRecordConversationPageHandlesXianxiaomiAndRemovesInvisibleSessions(t *t map[string]any{"singleChatUserConversation": map[string]any{"visible": float64(1), "singleChatConversation": map[string]any{"cid": "platform@goofish", "pairFirst": "self@goofish", "pairSecond": "0@goofish", "extension": map[string]any{"extUserId": "900"}}}}, map[string]any{"singleChatUserConversation": map[string]any{"visible": float64(1), "modifyTime": float64(123), "singleChatConversation": map[string]any{"cid": "xiaomi@goofish", "pairFirst": "self@goofish", "pairSecond": "0@goofish", "extension": map[string]any{"extUserId": "1400"}}, + "redPoint": float64(3), "lastMessage": map[string]any{"message": map[string]any{"extension": map[string]any{"senderUserId": "1400@goofish", "reminderTitle": "闲小蜜发来一条新消息"}, "content": map[string]any{"custom": map[string]any{"summary": "邀您填写售后问卷"}}}}}}, }} if // err 保存err,供当前处理流程使用 @@ -210,12 +233,75 @@ func TestRecordConversationPageHandlesXianxiaomiAndRemovesInvisibleSessions(t *t if err != nil { t.Fatal(err) } - if len(rows) != 1 || rows[0].BuyerID != "1400" || rows[0].BuyerName != "闲小蜜" || rows[0].BuyerAvatar != xianxiaomiAvatar { + if len(rows) != 1 || rows[0].BuyerID != "1400" || rows[0].BuyerName != "闲小蜜" || rows[0].BuyerAvatar != xianxiaomiAvatar || rows[0].UnreadCount != 0 { t.Fatalf("unexpected sessions: %+v", rows) } } -// TestRecordConversationPageSkipsEmptyConversationShells 负责TestRecordConversation页码SkipsEmptyConversationShells相关处理。 +// TestConversationUnreadCountUsesRedPointButFiltersSystemMessages 验证官方红点不会把系统卡片计为用户未读。 +func TestConversationUnreadCountUsesRedPointButFiltersSystemMessages(t *testing.T) { + // store、cleanup 保存隔离聊天数据库及清理函数,供红点与本地未读数交叉验证。 + store, cleanup := chatTestStore(t) + defer cleanup() + // service 是待测聊天服务,负责按系统消息规则折算会话红点。 + service := New(store) + + // systemCard 保存模拟交易通知的 Base64 卡片载荷,使末条消息被归类为系统消息。 + systemCard := base64.StdEncoding.EncodeToString([]byte(`{"contentType":26}`)) + // systemLast 保存带官方红点和系统未读状态的末条消息协议对象。 + systemLast := map[string]any{ + "extension": map[string]any{"senderUserId": "peer@goofish"}, + "content": map[string]any{"custom": map[string]any{"summary": "[交易通知]", "data": systemCard}}, + "unreadCount": float64(1), "readStatus": float64(1), + } + // got 保存扣除系统消息后的用户未读数,系统部分不得显示为用户红点。 + if got := service.conversationUnreadCount(context.Background(), "account-1", "system-last", "peer", map[string]any{"redPoint": float64(3)}, systemLast, "[交易通知]"); got != 2 { + t.Fatalf("系统未读未从 redPoint 扣除: got=%d", got) + } + // got 保存闲小蜜会话的折算未读数;该官方系统账号永远不产生用户红点。 + if got := service.conversationUnreadCount(context.Background(), "account-1", "xiaomi", "1400", map[string]any{"redPoint": float64(3)}, systemLast, "[交易通知]"); got != 0 { + t.Fatalf("闲小蜜全是系统消息时仍显示红点: got=%d", got) + } + + // err 保存真实用户消息持久化错误;成功后本地消息级未读数应优先于官方红点。 + if _, _, err := service.RecordIncoming(context.Background(), Incoming{ + AccountID: "account-1", ChatID: "real", BuyerID: "peer", BuyerName: "真实用户", Text: "未读消息", + MessageID: "real-unread", Raw: map[string]any{"messageId": "real-unread"}, + }); err != nil { + t.Fatal(err) + } + // userLast 保存真实用户末条消息协议对象,不含系统卡片字段。 + userLast := map[string]any{ + "extension": map[string]any{"senderUserId": "peer@goofish"}, + "content": map[string]any{"custom": map[string]any{"summary": "未读消息"}}, + } + // got 保存本地记录的真实用户未读数,必须防止较慢官方刷新复活已读红点。 + if got := service.conversationUnreadCount(context.Background(), "account-1", "real", "peer", map[string]any{"redPoint": float64(3)}, userLast, "未读消息"); got != 1 { + t.Fatalf("未使用消息级真实未读数: got=%d", got) + } +} + +// TestHistoryMessageIsSystem 验证历史卡片载荷和普通用户文本被正确区分,避免误算未读。 +func TestHistoryMessageIsSystem(t *testing.T) { + // encoded 保存模拟交易卡片的 Base64 载荷,触发内容类型的系统消息识别。 + encoded := base64.StdEncoding.EncodeToString([]byte(`{"contentType":26,"dxCard":{}}`)) + // last 保存待识别的历史末条消息协议对象。 + last := map[string]any{ + "extension": map[string]any{"senderUserId": "peer@goofish"}, + "content": map[string]any{"custom": map[string]any{"data": encoded}}, + } + if !historyMessageIsSystem(last, "[我已拍下,待付款]") { + t.Fatal("交易卡片应被识别为系统消息") + } + if historyMessageIsSystem(map[string]any{ + "extension": map[string]any{"senderUserId": "peer@goofish"}, + "content": map[string]any{"custom": map[string]any{"summary": "你好"}}, + }, "你好") { + t.Fatal("真实用户文本不应被识别为系统消息") + } +} + +// TestRecordConversationPageSkipsEmptyConversationShells 验证空会话壳不会被错误展示为联系人。 func TestRecordConversationPageSkipsEmptyConversationShells(t *testing.T) { // store、cleanup 保存store、cleanup,供当前处理流程使用 store, cleanup := chatTestStore(t) diff --git a/internal/db/chat.go b/internal/db/chat.go index fa69dcf..fe37b57 100644 --- a/internal/db/chat.go +++ b/internal/db/chat.go @@ -35,6 +35,8 @@ type ChatMessage struct { MessageType string `json:"message_type"` Content string `json:"content"` Status string `json:"status"` + ReadStatus int `json:"read_status"` + ReadAt int64 `json:"read_at,omitempty"` SentAt int64 `json:"sent_at"` } @@ -156,6 +158,13 @@ func (s *ChatStore) SaveMessage(ctx context.Context, session ChatSession, messag if message.SentAt <= 0 { message.SentAt = time.Now().UTC().UnixMilli() } + // read_status is also used for incoming messages: only a newly received + // real-user message starts unread. Imported history and official system + // notices must never contribute to the chat badge. + if message.Direction == "incoming" && (!unread || message.MessageType == "system") { + message.ReadStatus = 2 + message.ReadAt = time.Now().UTC().UnixMilli() + } message.CookieID, message.ChatID = session.CookieID, session.ChatID // now 保存now,供当前处理流程使用 now := time.Now().UTC().Unix() @@ -181,14 +190,14 @@ func (s *ChatStore) SaveMessage(ctx context.Context, session ChatSession, messag // prefix 保存prefix,供当前处理流程使用 prefix := dialectInsertIgnorePrefix(s.Dialect) - // query 保存查询,供当前处理流程使用 + // query 保存带已读字段的幂等插入 SQL,三方言冲突时保持同一列顺序。 query := prefix + ` INTO chat_messages - (cookie_id,chat_id,message_key,direction,sender_id,sender_name,message_type,content,status,sent_at,created_at) - VALUES(?,?,?,?,?,?,?,?,?,?,?)` + dialectInsertIgnore(s.Dialect, []string{"cookie_id", "message_key"}) - // res、err 保存res、err,供当前处理流程使用 + (cookie_id,chat_id,message_key,direction,sender_id,sender_name,message_type,content,status,read_status,read_at,sent_at,created_at) + VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)` + dialectInsertIgnore(s.Dialect, []string{"cookie_id", "message_key"}) + // res、err 保存插入结果及执行错误,用于判断是否更新会话摘要。 res, err := tx.ExecContext(ctx, query, message.CookieID, message.ChatID, message.MessageKey, message.Direction, message.SenderID, message.SenderName, message.MessageType, message.Content, - message.Status, message.SentAt, now) + message.Status, message.ReadStatus, message.ReadAt, message.SentAt, now) if err != nil { return nil, false, fmt.Errorf("保存聊天消息: %w", err) } @@ -222,13 +231,13 @@ func (s *ChatStore) SaveMessage(ctx context.Context, session ChatSession, messag // GetMessageByKey 读取消息ByKey。 func (s *ChatStore) GetMessageByKey(ctx context.Context, cookieID, key string) (*ChatMessage, error) { - // m 保存m,供当前处理流程使用 + // m 保存按账号和幂等键读取的完整聊天消息。 var m ChatMessage - // err 保存err,供当前处理流程使用 - err := s.DB.QueryRowContext(ctx, `SELECT id,cookie_id,chat_id,message_key,direction,sender_id,sender_name,message_type,content,status,sent_at + // err 保存查询错误;不存在时转换为仓储统一的 ErrNotFound。 + err := s.DB.QueryRowContext(ctx, `SELECT id,cookie_id,chat_id,message_key,direction,sender_id,sender_name,message_type,content,status,read_status,read_at,sent_at FROM chat_messages WHERE cookie_id=? AND message_key=?`, cookieID, key).Scan( &m.ID, &m.CookieID, &m.ChatID, &m.MessageKey, &m.Direction, &m.SenderID, &m.SenderName, - &m.MessageType, &m.Content, &m.Status, &m.SentAt) + &m.MessageType, &m.Content, &m.Status, &m.ReadStatus, &m.ReadAt, &m.SentAt) if errors.Is(err, sql.ErrNoRows) { return nil, ErrNotFound } @@ -279,8 +288,8 @@ func (s *ChatStore) ListMessages(ctx context.Context, userID int64, cookieID, ch if limit <= 0 || limit > 200 { limit = 50 } - // query 保存查询,供当前处理流程使用 - query := `SELECT m.id,m.cookie_id,m.chat_id,m.message_key,m.direction,m.sender_id,m.sender_name,m.message_type,m.content,m.status,m.sent_at + // query 保存按时间倒序读取再反转为时间正序的分页 SQL。 + query := `SELECT m.id,m.cookie_id,m.chat_id,m.message_key,m.direction,m.sender_id,m.sender_name,m.message_type,m.content,m.status,m.read_status,m.read_at,m.sent_at FROM chat_messages m JOIN cookies c ON c.id=m.cookie_id WHERE c.user_id=? AND m.cookie_id=? AND m.chat_id=?` // args 保存args,供当前处理流程使用 @@ -301,11 +310,11 @@ func (s *ChatStore) ListMessages(ctx context.Context, userID int64, cookieID, ch // result 保存结果,供当前处理流程使用 var result []ChatMessage for rows.Next() { - // m 保存m,供当前处理流程使用 + // m 保存当前扫描出的消息及其本地已读状态。 var m ChatMessage - if // err 保存err,供当前处理流程使用 - err := rows.Scan(&m.ID, &m.CookieID, &m.ChatID, &m.MessageKey, &m.Direction, &m.SenderID, - &m.SenderName, &m.MessageType, &m.Content, &m.Status, &m.SentAt); err != nil { + // err 保存当前行字段映射错误,避免返回缺少已读字段的不完整消息。 + if err := rows.Scan(&m.ID, &m.CookieID, &m.ChatID, &m.MessageKey, &m.Direction, &m.SenderID, + &m.SenderName, &m.MessageType, &m.Content, &m.Status, &m.ReadStatus, &m.ReadAt, &m.SentAt); err != nil { return nil, err } result = append(result, m) @@ -318,15 +327,33 @@ func (s *ChatStore) ListMessages(ctx context.Context, userID int64, cookieID, ch return result, rows.Err() } -// MarkRead 负责MarkRead相关处理。 +// MarkRead 仅对当前用户拥有账号的非系统入站消息标记已读,并同步归零会话红点。 func (s *ChatStore) MarkRead(ctx context.Context, userID int64, cookieID, chatID string) error { - // err 保存err,供当前处理流程使用 + // now 是同一批消息和会话状态使用的统一 UTC 时间,避免页面显示先后矛盾。 + now := time.Now().UTC() + // err 保存批量更新非系统入站消息的错误;失败时不得清空会话红点以避免状态不一致。 + if _, err := s.DB.ExecContext(ctx, `UPDATE chat_messages SET read_status=2,read_at=? + WHERE cookie_id=? AND chat_id=? AND direction='incoming' AND message_type<>'system' AND read_status<>2`, + now.UnixMilli(), cookieID, chatID); err != nil { + return err + } + // err 保存归零会话红点的错误,该更新通过用户归属子查询阻止越权修改。 _, err := s.DB.ExecContext(ctx, `UPDATE chat_sessions SET unread_count=0,updated_at=? WHERE cookie_id=? AND chat_id=? AND EXISTS(SELECT 1 FROM cookies c WHERE c.id=chat_sessions.cookie_id AND c.user_id=?)`, - time.Now().UTC().Unix(), cookieID, chatID, userID) + now.Unix(), cookieID, chatID, userID) return err } +// CountUnreadUserMessages 返回界面红点使用的入站真实用户未读数,系统消息永不计入。 +func (s *ChatStore) CountUnreadUserMessages(ctx context.Context, cookieID, chatID string) (int, error) { + // count 保存符合当前账号、会话及未读条件的消息总数。 + var count int + // err 保存聚合查询错误,调用方可在平台响应缺失时退回官方红点值。 + err := s.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM chat_messages + WHERE cookie_id=? AND chat_id=? AND direction='incoming' AND message_type<>'system' AND read_status<>2`, cookieID, chatID).Scan(&count) + return count, err +} + // UpdateMessageStatus 更新消息状态。 func (s *ChatStore) UpdateMessageStatus(ctx context.Context, cookieID, key, status string) (*ChatMessage, error) { if // err 保存err,供当前处理流程使用 @@ -335,3 +362,35 @@ func (s *ChatStore) UpdateMessageStatus(ctx context.Context, cookieID, key, stat } return s.GetMessageByKey(ctx, cookieID, key) } + +// MarkMessageRead 按平台回执把一条出站消息标记为已读,并返回更新后的消息。 +func (s *ChatStore) MarkMessageRead(ctx context.Context, cookieID, key string, readAt int64) (*ChatMessage, error) { + // readAt 保存平台已读时间;缺失时使用本机 UTC 时间作为展示回退。 + if readAt <= 0 { + readAt = time.Now().UTC().UnixMilli() + } + // err 保存只更新出站消息的数据库错误,防止错误改写入站状态。 + if _, err := s.DB.ExecContext(ctx, `UPDATE chat_messages SET read_status=2,read_at=? WHERE cookie_id=? AND message_key=? AND direction='outgoing'`, readAt, cookieID, key); err != nil { + return nil, err + } + return s.GetMessageByKey(ctx, cookieID, key) +} + +// MarkLatestOutgoingRead 在回执未带消息键时回退标记会话中最近待确认的出站消息。 +func (s *ChatStore) MarkLatestOutgoingRead(ctx context.Context, cookieID, chatID string, readAt int64) (*ChatMessage, error) { + // readAt 保存平台已读时间;缺失时使用本机 UTC 时间作为展示回退。 + if readAt <= 0 { + readAt = time.Now().UTC().UnixMilli() + } + // key 保存最近一条已发送且未标记已读的消息幂等键。 + var key string + // err 保存查询错误;没有可更新消息时返回统一 ErrNotFound。 + err := s.DB.QueryRowContext(ctx, `SELECT message_key FROM chat_messages WHERE cookie_id=? AND chat_id=? AND direction='outgoing' AND status='sent' AND read_status<>2 ORDER BY sent_at DESC,id DESC LIMIT 1`, cookieID, chatID).Scan(&key) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrNotFound + } + if err != nil { + return nil, err + } + return s.MarkMessageRead(ctx, cookieID, key, readAt) +} diff --git a/internal/db/migrate_test.go b/internal/db/migrate_test.go index 9afdaa4..8077030 100644 --- a/internal/db/migrate_test.go +++ b/internal/db/migrate_test.go @@ -105,6 +105,53 @@ func TestMigrate_AppliesCleanSchema(t *testing.T) { db2.Close() } +// TestMigrate_UpgradesDatabaseWithMainChatVersions 验证已发布 main 的 00029/00030 +// 聊天迁移可以原样升级到合并后的 dev 最终版本。 +func TestMigrate_UpgradesDatabaseWithMainChatVersions(t *testing.T) { + // tmpDir 保存隔离的已发布 main 数据库目录,测试结束后由 testing 清理。 + tmpDir := t.TempDir() + // dbPath 指向模拟已运行至 main 00030 的 SQLite 文件。 + dbPath := filepath.Join(tmpDir, "main-chat-v30.db") + // rawDB 在调用 Open 前控制 Goose 只执行已发布的 main 迁移。 + rawDB, openErr := sql.Open("sqlite", sqliteDSN(dbPath)) + if openErr != nil { + t.Fatalf("open legacy database: %v", openErr) + } + defer rawDB.Close() + + // dialectErr 保存 Goose SQLite 方言设置失败,失败时不能构造已发布迁移基线。 + if dialectErr := goose.SetDialect("sqlite3"); dialectErr != nil { + t.Fatalf("set goose dialect: %v", dialectErr) + } + goose.SetBaseFS(migrationsFS) + // upErr 将数据库推进到已发布 main 的 00030,验证之后的 dev 迁移连续接续。 + upErr := goose.UpTo(rawDB, "migrations/sqlite", 30) + if upErr != nil { + t.Fatalf("apply released main migrations: %v", upErr) + } + + // ctx 提供迁移 API 所需的调用上下文;升级本身不依赖请求生命周期。 + ctx := context.Background() + // migrateErr 保存从 main 00030 接续 dev 00031 时的迁移失败。 + if migrateErr := Migrate(ctx, rawDB, DialectSQLite); migrateErr != nil { + t.Fatalf("upgrade from main 00030: %v", migrateErr) + } + if !tableExists(t, rawDB, "order_reconciliations") { + t.Fatal("order_reconciliations should be created by the dev schema baseline migration") + } + if !columnExists(t, rawDB, "chat_messages", "read_status") || !columnExists(t, rawDB, "chat_messages", "read_at") { + t.Fatal("chat read tracking columns should remain after dev schema baseline upgrade") + } + // finalVersion 验证迁移账本已推进到合并后的单一 dev schema 基线版本。 + finalVersion, versionErr := goose.GetDBVersion(rawDB) + if versionErr != nil { + t.Fatalf("read final migration version: %v", versionErr) + } + if finalVersion != 31 { + t.Fatalf("final migration version=%d, want 31", finalVersion) + } +} + // columnExists 负责columnExists相关处理。 func columnExists(t *testing.T, db *sql.DB, table, col string) bool { t.Helper() @@ -156,7 +203,7 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) { } // i 表示本次回滚操作序号。 for i := 0; version >= 14; i++ { - if // err 保存err,供当前处理流程使用 + if // err 保存当前迁移回滚错误,任一方言步骤失败即终止验证。 err := goose.Down(d, "migrations/sqlite"); err != nil { t.Fatalf("down migration #%d: %v", i+1, err) } @@ -220,6 +267,8 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) { {"account_task_runs", "run_key"}, {"chat_sessions", "unread_count"}, {"chat_messages", "message_key"}, + {"chat_messages", "read_status"}, + {"chat_messages", "read_at"}, {"notification_outbox", "uncertain_at"}, } { if !columnExists(t, d, c.table, c.col) { diff --git a/internal/db/migrations/mysql/00029_chat_read_status.sql b/internal/db/migrations/mysql/00029_chat_read_status.sql new file mode 100644 index 0000000..1ff3aac --- /dev/null +++ b/internal/db/migrations/mysql/00029_chat_read_status.sql @@ -0,0 +1,6 @@ +-- +goose Up +ALTER TABLE chat_messages ADD COLUMN read_status INT NOT NULL DEFAULT 0; +ALTER TABLE chat_messages ADD COLUMN read_at BIGINT NOT NULL DEFAULT 0; +-- +goose Down +ALTER TABLE chat_messages DROP COLUMN read_at; +ALTER TABLE chat_messages DROP COLUMN read_status; diff --git a/internal/db/migrations/mysql/00029_order_reconciliations.sql b/internal/db/migrations/mysql/00029_order_reconciliations.sql deleted file mode 100644 index 7227dac..0000000 --- a/internal/db/migrations/mysql/00029_order_reconciliations.sql +++ /dev/null @@ -1,16 +0,0 @@ --- +goose Up -CREATE TABLE IF NOT EXISTS order_reconciliations ( - id VARCHAR(36) PRIMARY KEY, - order_id VARCHAR(255) NOT NULL, - cookie_id VARCHAR(255) NOT NULL, - kind VARCHAR(100) NOT NULL, - status VARCHAR(32) NOT NULL DEFAULT 'pending', - error_message TEXT NOT NULL, - attempts INTEGER NOT NULL DEFAULT 0, - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - INDEX idx_order_reconciliations_pending (status, created_at, id) -); - --- +goose Down -DROP TABLE IF EXISTS order_reconciliations; diff --git a/internal/db/migrations/mysql/00030_chat_unread_state.sql b/internal/db/migrations/mysql/00030_chat_unread_state.sql new file mode 100644 index 0000000..77e072b --- /dev/null +++ b/internal/db/migrations/mysql/00030_chat_unread_state.sql @@ -0,0 +1,6 @@ +-- +goose Up +UPDATE chat_messages SET read_status=2, read_at=CASE WHEN read_at=0 THEN UNIX_TIMESTAMP(CURRENT_TIMESTAMP) * 1000 ELSE read_at END +WHERE direction='incoming' AND read_status=0; + +-- +goose Down +-- No safe reverse: the previous schema had no per-message read boundary. diff --git a/internal/db/migrations/mysql/00030_order_cursor_index.sql b/internal/db/migrations/mysql/00030_order_cursor_index.sql deleted file mode 100644 index 84e3266..0000000 --- a/internal/db/migrations/mysql/00030_order_cursor_index.sql +++ /dev/null @@ -1,5 +0,0 @@ --- +goose Up -CREATE INDEX idx_orders_cursor ON orders(cookie_id, deleted_at, created_at DESC, order_id DESC); - --- +goose Down -DROP INDEX idx_orders_cursor ON orders; diff --git a/internal/db/migrations/mysql/00031_dev_schema_baseline.sql b/internal/db/migrations/mysql/00031_dev_schema_baseline.sql new file mode 100644 index 0000000..8e9023b --- /dev/null +++ b/internal/db/migrations/mysql/00031_dev_schema_baseline.sql @@ -0,0 +1,57 @@ +-- +goose Up +CREATE TABLE IF NOT EXISTS order_reconciliations ( + id VARCHAR(36) PRIMARY KEY, + order_id VARCHAR(255) NOT NULL, + cookie_id VARCHAR(255) NOT NULL, + kind VARCHAR(100) NOT NULL, + status VARCHAR(32) NOT NULL DEFAULT 'pending', + error_message TEXT NOT NULL, + attempts INTEGER NOT NULL DEFAULT 0, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + INDEX idx_order_reconciliations_pending (status, created_at, id) +); + +CREATE INDEX idx_orders_cursor ON orders(cookie_id, deleted_at, created_at DESC, order_id DESC); + +CREATE TABLE IF NOT EXISTS order_refresh_jobs ( + id VARCHAR(64) PRIMARY KEY, + user_id BIGINT NOT NULL, + cookie_id VARCHAR(255) NOT NULL DEFAULT '', + filter_status VARCHAR(64) NOT NULL DEFAULT '', + status VARCHAR(32) NOT NULL DEFAULT 'queued', + result_json LONGTEXT NOT NULL, + error_message TEXT NOT NULL, + worker_token VARCHAR(128) NOT NULL DEFAULT '', + lease_expires_at BIGINT NOT NULL DEFAULT 0, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT fk_order_refresh_jobs_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + INDEX idx_order_refresh_jobs_user (user_id, created_at, id), + INDEX idx_order_refresh_jobs_lease (status, lease_expires_at) +); + +CREATE TABLE IF NOT EXISTS security_audit_logs ( + id BIGINT PRIMARY KEY AUTO_INCREMENT, + user_id BIGINT NOT NULL, + action VARCHAR(128) NOT NULL, + resource VARCHAR(255) NOT NULL, + keys_json TEXT NOT NULL, + outcome VARCHAR(32) NOT NULL DEFAULT 'accepted', + created_at BIGINT NOT NULL, + INDEX idx_security_audit_logs_user_created (user_id, created_at, id) +); + +ALTER TABLE notification_outbox ADD COLUMN uncertain_at BIGINT NOT NULL DEFAULT 0; +ALTER TABLE notification_outbox ADD COLUMN idempotency_key VARCHAR(255) NULL; +CREATE UNIQUE INDEX idx_notification_outbox_channel_idempotency + ON notification_outbox(channel_id, idempotency_key); + +-- +goose Down +DROP INDEX idx_notification_outbox_channel_idempotency ON notification_outbox; +ALTER TABLE notification_outbox DROP COLUMN idempotency_key; +ALTER TABLE notification_outbox DROP COLUMN uncertain_at; +DROP TABLE IF EXISTS security_audit_logs; +DROP TABLE IF EXISTS order_refresh_jobs; +DROP INDEX idx_orders_cursor ON orders; +DROP TABLE IF EXISTS order_reconciliations; diff --git a/internal/db/migrations/mysql/00031_order_refresh_jobs.sql b/internal/db/migrations/mysql/00031_order_refresh_jobs.sql deleted file mode 100644 index 62e2dc9..0000000 --- a/internal/db/migrations/mysql/00031_order_refresh_jobs.sql +++ /dev/null @@ -1,20 +0,0 @@ --- +goose Up -CREATE TABLE IF NOT EXISTS order_refresh_jobs ( - id VARCHAR(64) PRIMARY KEY, - user_id BIGINT NOT NULL, - cookie_id VARCHAR(255) NOT NULL DEFAULT '', - filter_status VARCHAR(64) NOT NULL DEFAULT '', - status VARCHAR(32) NOT NULL DEFAULT 'queued', - result_json LONGTEXT NOT NULL, - error_message TEXT NOT NULL, - worker_token VARCHAR(128) NOT NULL DEFAULT '', - lease_expires_at BIGINT NOT NULL DEFAULT 0, - created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - CONSTRAINT fk_order_refresh_jobs_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, - INDEX idx_order_refresh_jobs_user (user_id, created_at, id), - INDEX idx_order_refresh_jobs_lease (status, lease_expires_at) -); - --- +goose Down -DROP TABLE IF EXISTS order_refresh_jobs; diff --git a/internal/db/migrations/mysql/00032_security_audit_logs.sql b/internal/db/migrations/mysql/00032_security_audit_logs.sql deleted file mode 100644 index 42d82f2..0000000 --- a/internal/db/migrations/mysql/00032_security_audit_logs.sql +++ /dev/null @@ -1,14 +0,0 @@ --- +goose Up -CREATE TABLE IF NOT EXISTS security_audit_logs ( - id BIGINT PRIMARY KEY AUTO_INCREMENT, - user_id BIGINT NOT NULL, - action VARCHAR(128) NOT NULL, - resource VARCHAR(255) NOT NULL, - keys_json TEXT NOT NULL, - outcome VARCHAR(32) NOT NULL DEFAULT 'accepted', - created_at BIGINT NOT NULL, - INDEX idx_security_audit_logs_user_created (user_id, created_at, id) -); - --- +goose Down -DROP TABLE IF EXISTS security_audit_logs; diff --git a/internal/db/migrations/mysql/00033_notification_outbox_uncertain.sql b/internal/db/migrations/mysql/00033_notification_outbox_uncertain.sql deleted file mode 100644 index aad54ea..0000000 --- a/internal/db/migrations/mysql/00033_notification_outbox_uncertain.sql +++ /dev/null @@ -1,6 +0,0 @@ --- +goose Up --- uncertain_at 记录外部发送成功但本地确认失败的隔离时间,避免租约过期后自动重复发送。 -ALTER TABLE notification_outbox ADD COLUMN uncertain_at BIGINT NOT NULL DEFAULT 0; - --- +goose Down -ALTER TABLE notification_outbox DROP COLUMN uncertain_at; diff --git a/internal/db/migrations/mysql/00034_notification_outbox_idempotency.sql b/internal/db/migrations/mysql/00034_notification_outbox_idempotency.sql deleted file mode 100644 index 0a190dc..0000000 --- a/internal/db/migrations/mysql/00034_notification_outbox_idempotency.sql +++ /dev/null @@ -1,10 +0,0 @@ --- +goose Up --- idempotency_key 让同一自动化运行终态对同一渠道只保留一条 outbox 记录。 --- NULL 保持历史普通通知可重复投递;uncertain 记录保留原键,从而禁止恢复时自动重新入队。 -ALTER TABLE notification_outbox ADD COLUMN idempotency_key VARCHAR(255) NULL; -CREATE UNIQUE INDEX idx_notification_outbox_channel_idempotency - ON notification_outbox(channel_id, idempotency_key); - --- +goose Down -DROP INDEX idx_notification_outbox_channel_idempotency ON notification_outbox; -ALTER TABLE notification_outbox DROP COLUMN idempotency_key; diff --git a/internal/db/migrations/postgres/00029_chat_read_status.sql b/internal/db/migrations/postgres/00029_chat_read_status.sql new file mode 100644 index 0000000..54336b1 --- /dev/null +++ b/internal/db/migrations/postgres/00029_chat_read_status.sql @@ -0,0 +1,6 @@ +-- +goose Up +ALTER TABLE chat_messages ADD COLUMN read_status INTEGER NOT NULL DEFAULT 0; +ALTER TABLE chat_messages ADD COLUMN read_at BIGINT NOT NULL DEFAULT 0; +-- +goose Down +ALTER TABLE chat_messages DROP COLUMN read_at; +ALTER TABLE chat_messages DROP COLUMN read_status; diff --git a/internal/db/migrations/postgres/00029_order_reconciliations.sql b/internal/db/migrations/postgres/00029_order_reconciliations.sql deleted file mode 100644 index 343a955..0000000 --- a/internal/db/migrations/postgres/00029_order_reconciliations.sql +++ /dev/null @@ -1,17 +0,0 @@ --- +goose Up -CREATE TABLE IF NOT EXISTS order_reconciliations ( - id TEXT PRIMARY KEY, - order_id TEXT NOT NULL, - cookie_id TEXT NOT NULL, - kind TEXT NOT NULL, - status TEXT NOT NULL DEFAULT 'pending', - error_message TEXT NOT NULL DEFAULT '', - attempts INTEGER NOT NULL DEFAULT 0, - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP -); -CREATE INDEX IF NOT EXISTS idx_order_reconciliations_pending - ON order_reconciliations(status, created_at, id); - --- +goose Down -DROP TABLE IF EXISTS order_reconciliations; diff --git a/internal/db/migrations/postgres/00030_chat_unread_state.sql b/internal/db/migrations/postgres/00030_chat_unread_state.sql new file mode 100644 index 0000000..90e334a --- /dev/null +++ b/internal/db/migrations/postgres/00030_chat_unread_state.sql @@ -0,0 +1,6 @@ +-- +goose Up +UPDATE chat_messages SET read_status=2, read_at=CASE WHEN read_at=0 THEN (EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000)::BIGINT ELSE read_at END +WHERE direction='incoming' AND read_status=0; + +-- +goose Down +-- No safe reverse: the previous schema had no per-message read boundary. diff --git a/internal/db/migrations/postgres/00030_order_cursor_index.sql b/internal/db/migrations/postgres/00030_order_cursor_index.sql deleted file mode 100644 index abf1579..0000000 --- a/internal/db/migrations/postgres/00030_order_cursor_index.sql +++ /dev/null @@ -1,5 +0,0 @@ --- +goose Up -CREATE INDEX IF NOT EXISTS idx_orders_cursor ON orders(cookie_id, deleted_at, created_at DESC, order_id DESC); - --- +goose Down -DROP INDEX IF EXISTS idx_orders_cursor; diff --git a/internal/db/migrations/postgres/00031_dev_schema_baseline.sql b/internal/db/migrations/postgres/00031_dev_schema_baseline.sql new file mode 100644 index 0000000..46f7247 --- /dev/null +++ b/internal/db/migrations/postgres/00031_dev_schema_baseline.sql @@ -0,0 +1,60 @@ +-- +goose Up +CREATE TABLE IF NOT EXISTS order_reconciliations ( + id TEXT PRIMARY KEY, + order_id TEXT NOT NULL, + cookie_id TEXT NOT NULL, + kind TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'pending', + error_message TEXT NOT NULL DEFAULT '', + attempts INTEGER NOT NULL DEFAULT 0, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); +CREATE INDEX IF NOT EXISTS idx_order_reconciliations_pending + ON order_reconciliations(status, created_at, id); + +CREATE INDEX IF NOT EXISTS idx_orders_cursor ON orders(cookie_id, deleted_at, created_at DESC, order_id DESC); + +CREATE TABLE IF NOT EXISTS order_refresh_jobs ( + id TEXT PRIMARY KEY, + user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + cookie_id TEXT NOT NULL DEFAULT '', + filter_status TEXT NOT NULL DEFAULT '', + status TEXT NOT NULL DEFAULT 'queued', + result_json TEXT NOT NULL DEFAULT '{}', + error_message TEXT NOT NULL DEFAULT '', + worker_token TEXT NOT NULL DEFAULT '', + lease_expires_at BIGINT NOT NULL DEFAULT 0, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP +); +CREATE INDEX IF NOT EXISTS idx_order_refresh_jobs_user ON order_refresh_jobs(user_id, created_at DESC, id DESC); +CREATE INDEX IF NOT EXISTS idx_order_refresh_jobs_lease ON order_refresh_jobs(status, lease_expires_at); + +CREATE TABLE IF NOT EXISTS security_audit_logs ( + id BIGSERIAL PRIMARY KEY, + user_id BIGINT NOT NULL, + action VARCHAR(128) NOT NULL, + resource VARCHAR(255) NOT NULL, + keys_json TEXT NOT NULL DEFAULT '[]', + outcome VARCHAR(32) NOT NULL DEFAULT 'accepted', + created_at BIGINT NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_security_audit_logs_user_created + ON security_audit_logs(user_id, created_at DESC, id DESC); + +ALTER TABLE notification_outbox ADD COLUMN uncertain_at BIGINT NOT NULL DEFAULT 0; +ALTER TABLE notification_outbox ADD COLUMN idempotency_key TEXT NULL; +CREATE UNIQUE INDEX idx_notification_outbox_channel_idempotency + ON notification_outbox(channel_id, idempotency_key); + +-- +goose Down +DROP INDEX IF EXISTS idx_notification_outbox_channel_idempotency; +ALTER TABLE notification_outbox DROP COLUMN idempotency_key; +ALTER TABLE notification_outbox DROP COLUMN uncertain_at; +DROP TABLE IF EXISTS security_audit_logs; +DROP INDEX IF EXISTS idx_order_refresh_jobs_lease; +DROP INDEX IF EXISTS idx_order_refresh_jobs_user; +DROP TABLE IF EXISTS order_refresh_jobs; +DROP INDEX IF EXISTS idx_orders_cursor; +DROP TABLE IF EXISTS order_reconciliations; diff --git a/internal/db/migrations/postgres/00031_order_refresh_jobs.sql b/internal/db/migrations/postgres/00031_order_refresh_jobs.sql deleted file mode 100644 index 66e1ee6..0000000 --- a/internal/db/migrations/postgres/00031_order_refresh_jobs.sql +++ /dev/null @@ -1,21 +0,0 @@ --- +goose Up -CREATE TABLE IF NOT EXISTS order_refresh_jobs ( - id TEXT PRIMARY KEY, - user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE, - cookie_id TEXT NOT NULL DEFAULT '', - filter_status TEXT NOT NULL DEFAULT '', - status TEXT NOT NULL DEFAULT 'queued', - result_json TEXT NOT NULL DEFAULT '{}', - error_message TEXT NOT NULL DEFAULT '', - worker_token TEXT NOT NULL DEFAULT '', - lease_expires_at BIGINT NOT NULL DEFAULT 0, - created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP -); -CREATE INDEX IF NOT EXISTS idx_order_refresh_jobs_user ON order_refresh_jobs(user_id, created_at DESC, id DESC); -CREATE INDEX IF NOT EXISTS idx_order_refresh_jobs_lease ON order_refresh_jobs(status, lease_expires_at); - --- +goose Down -DROP INDEX IF EXISTS idx_order_refresh_jobs_lease; -DROP INDEX IF EXISTS idx_order_refresh_jobs_user; -DROP TABLE IF EXISTS order_refresh_jobs; diff --git a/internal/db/migrations/postgres/00032_security_audit_logs.sql b/internal/db/migrations/postgres/00032_security_audit_logs.sql deleted file mode 100644 index d1860b4..0000000 --- a/internal/db/migrations/postgres/00032_security_audit_logs.sql +++ /dev/null @@ -1,16 +0,0 @@ --- +goose Up -CREATE TABLE IF NOT EXISTS security_audit_logs ( - id BIGSERIAL PRIMARY KEY, - user_id BIGINT NOT NULL, - action VARCHAR(128) NOT NULL, - resource VARCHAR(255) NOT NULL, - keys_json TEXT NOT NULL DEFAULT '[]', - outcome VARCHAR(32) NOT NULL DEFAULT 'accepted', - created_at BIGINT NOT NULL -); - -CREATE INDEX IF NOT EXISTS idx_security_audit_logs_user_created - ON security_audit_logs(user_id, created_at DESC, id DESC); - --- +goose Down -DROP TABLE IF EXISTS security_audit_logs; diff --git a/internal/db/migrations/postgres/00033_notification_outbox_uncertain.sql b/internal/db/migrations/postgres/00033_notification_outbox_uncertain.sql deleted file mode 100644 index aad54ea..0000000 --- a/internal/db/migrations/postgres/00033_notification_outbox_uncertain.sql +++ /dev/null @@ -1,6 +0,0 @@ --- +goose Up --- uncertain_at 记录外部发送成功但本地确认失败的隔离时间,避免租约过期后自动重复发送。 -ALTER TABLE notification_outbox ADD COLUMN uncertain_at BIGINT NOT NULL DEFAULT 0; - --- +goose Down -ALTER TABLE notification_outbox DROP COLUMN uncertain_at; diff --git a/internal/db/migrations/postgres/00034_notification_outbox_idempotency.sql b/internal/db/migrations/postgres/00034_notification_outbox_idempotency.sql deleted file mode 100644 index fbb6bd5..0000000 --- a/internal/db/migrations/postgres/00034_notification_outbox_idempotency.sql +++ /dev/null @@ -1,10 +0,0 @@ --- +goose Up --- idempotency_key 让同一自动化运行终态对同一渠道只保留一条 outbox 记录。 --- NULL 保持历史普通通知可重复投递;uncertain 记录保留原键,从而禁止恢复时自动重新入队。 -ALTER TABLE notification_outbox ADD COLUMN idempotency_key TEXT NULL; -CREATE UNIQUE INDEX idx_notification_outbox_channel_idempotency - ON notification_outbox(channel_id, idempotency_key); - --- +goose Down -DROP INDEX IF EXISTS idx_notification_outbox_channel_idempotency; -ALTER TABLE notification_outbox DROP COLUMN idempotency_key; diff --git a/internal/db/migrations/sqlite/00029_chat_read_status.sql b/internal/db/migrations/sqlite/00029_chat_read_status.sql new file mode 100644 index 0000000..dd72cc5 --- /dev/null +++ b/internal/db/migrations/sqlite/00029_chat_read_status.sql @@ -0,0 +1,6 @@ +-- +goose Up +ALTER TABLE chat_messages ADD COLUMN read_status INTEGER NOT NULL DEFAULT 0; +ALTER TABLE chat_messages ADD COLUMN read_at INTEGER NOT NULL DEFAULT 0; +-- +goose Down +ALTER TABLE chat_messages DROP COLUMN read_at; +ALTER TABLE chat_messages DROP COLUMN read_status; diff --git a/internal/db/migrations/sqlite/00029_order_reconciliations.sql b/internal/db/migrations/sqlite/00029_order_reconciliations.sql deleted file mode 100644 index 343a955..0000000 --- a/internal/db/migrations/sqlite/00029_order_reconciliations.sql +++ /dev/null @@ -1,17 +0,0 @@ --- +goose Up -CREATE TABLE IF NOT EXISTS order_reconciliations ( - id TEXT PRIMARY KEY, - order_id TEXT NOT NULL, - cookie_id TEXT NOT NULL, - kind TEXT NOT NULL, - status TEXT NOT NULL DEFAULT 'pending', - error_message TEXT NOT NULL DEFAULT '', - attempts INTEGER NOT NULL DEFAULT 0, - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP -); -CREATE INDEX IF NOT EXISTS idx_order_reconciliations_pending - ON order_reconciliations(status, created_at, id); - --- +goose Down -DROP TABLE IF EXISTS order_reconciliations; diff --git a/internal/db/migrations/sqlite/00030_chat_unread_state.sql b/internal/db/migrations/sqlite/00030_chat_unread_state.sql new file mode 100644 index 0000000..5923059 --- /dev/null +++ b/internal/db/migrations/sqlite/00030_chat_unread_state.sql @@ -0,0 +1,8 @@ +-- +goose Up +-- Messages already stored before message-level read tracking was introduced +-- are history snapshots, not newly received unread messages. +UPDATE chat_messages SET read_status=2, read_at=CASE WHEN read_at=0 THEN strftime('%s','now') * 1000 ELSE read_at END +WHERE direction='incoming' AND read_status=0; + +-- +goose Down +-- No safe reverse: the previous schema had no per-message read boundary. diff --git a/internal/db/migrations/sqlite/00030_order_cursor_index.sql b/internal/db/migrations/sqlite/00030_order_cursor_index.sql deleted file mode 100644 index abf1579..0000000 --- a/internal/db/migrations/sqlite/00030_order_cursor_index.sql +++ /dev/null @@ -1,5 +0,0 @@ --- +goose Up -CREATE INDEX IF NOT EXISTS idx_orders_cursor ON orders(cookie_id, deleted_at, created_at DESC, order_id DESC); - --- +goose Down -DROP INDEX IF EXISTS idx_orders_cursor; diff --git a/internal/db/migrations/sqlite/00031_dev_schema_baseline.sql b/internal/db/migrations/sqlite/00031_dev_schema_baseline.sql new file mode 100644 index 0000000..e033f3e --- /dev/null +++ b/internal/db/migrations/sqlite/00031_dev_schema_baseline.sql @@ -0,0 +1,60 @@ +-- +goose Up +CREATE TABLE IF NOT EXISTS order_reconciliations ( + id TEXT PRIMARY KEY, + order_id TEXT NOT NULL, + cookie_id TEXT NOT NULL, + kind TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'pending', + error_message TEXT NOT NULL DEFAULT '', + attempts INTEGER NOT NULL DEFAULT 0, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); +CREATE INDEX IF NOT EXISTS idx_order_reconciliations_pending + ON order_reconciliations(status, created_at, id); + +CREATE INDEX IF NOT EXISTS idx_orders_cursor ON orders(cookie_id, deleted_at, created_at DESC, order_id DESC); + +CREATE TABLE IF NOT EXISTS order_refresh_jobs ( + id TEXT PRIMARY KEY, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + cookie_id TEXT NOT NULL DEFAULT '', + filter_status TEXT NOT NULL DEFAULT '', + status TEXT NOT NULL DEFAULT 'queued', + result_json TEXT NOT NULL DEFAULT '{}', + error_message TEXT NOT NULL DEFAULT '', + worker_token TEXT NOT NULL DEFAULT '', + lease_expires_at INTEGER NOT NULL DEFAULT 0, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP +); +CREATE INDEX IF NOT EXISTS idx_order_refresh_jobs_user ON order_refresh_jobs(user_id, created_at DESC, id DESC); +CREATE INDEX IF NOT EXISTS idx_order_refresh_jobs_lease ON order_refresh_jobs(status, lease_expires_at); + +CREATE TABLE IF NOT EXISTS security_audit_logs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL, + action TEXT NOT NULL, + resource TEXT NOT NULL, + keys_json TEXT NOT NULL DEFAULT '[]', + outcome TEXT NOT NULL DEFAULT 'accepted', + created_at INTEGER NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_security_audit_logs_user_created + ON security_audit_logs(user_id, created_at DESC, id DESC); + +ALTER TABLE notification_outbox ADD COLUMN uncertain_at INTEGER NOT NULL DEFAULT 0; +ALTER TABLE notification_outbox ADD COLUMN idempotency_key TEXT NULL; +CREATE UNIQUE INDEX idx_notification_outbox_channel_idempotency + ON notification_outbox(channel_id, idempotency_key); + +-- +goose Down +DROP INDEX IF EXISTS idx_notification_outbox_channel_idempotency; +ALTER TABLE notification_outbox DROP COLUMN idempotency_key; +ALTER TABLE notification_outbox DROP COLUMN uncertain_at; +DROP TABLE IF EXISTS security_audit_logs; +DROP INDEX IF EXISTS idx_order_refresh_jobs_lease; +DROP INDEX IF EXISTS idx_order_refresh_jobs_user; +DROP TABLE IF EXISTS order_refresh_jobs; +DROP INDEX IF EXISTS idx_orders_cursor; +DROP TABLE IF EXISTS order_reconciliations; diff --git a/internal/db/migrations/sqlite/00031_order_refresh_jobs.sql b/internal/db/migrations/sqlite/00031_order_refresh_jobs.sql deleted file mode 100644 index 900fa50..0000000 --- a/internal/db/migrations/sqlite/00031_order_refresh_jobs.sql +++ /dev/null @@ -1,21 +0,0 @@ --- +goose Up -CREATE TABLE IF NOT EXISTS order_refresh_jobs ( - id TEXT PRIMARY KEY, - user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, - cookie_id TEXT NOT NULL DEFAULT '', - filter_status TEXT NOT NULL DEFAULT '', - status TEXT NOT NULL DEFAULT 'queued', - result_json TEXT NOT NULL DEFAULT '{}', - error_message TEXT NOT NULL DEFAULT '', - worker_token TEXT NOT NULL DEFAULT '', - lease_expires_at INTEGER NOT NULL DEFAULT 0, - created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP -); -CREATE INDEX IF NOT EXISTS idx_order_refresh_jobs_user ON order_refresh_jobs(user_id, created_at DESC, id DESC); -CREATE INDEX IF NOT EXISTS idx_order_refresh_jobs_lease ON order_refresh_jobs(status, lease_expires_at); - --- +goose Down -DROP INDEX IF EXISTS idx_order_refresh_jobs_lease; -DROP INDEX IF EXISTS idx_order_refresh_jobs_user; -DROP TABLE IF EXISTS order_refresh_jobs; diff --git a/internal/db/migrations/sqlite/00032_security_audit_logs.sql b/internal/db/migrations/sqlite/00032_security_audit_logs.sql deleted file mode 100644 index 7760b92..0000000 --- a/internal/db/migrations/sqlite/00032_security_audit_logs.sql +++ /dev/null @@ -1,16 +0,0 @@ --- +goose Up -CREATE TABLE IF NOT EXISTS security_audit_logs ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - user_id INTEGER NOT NULL, - action TEXT NOT NULL, - resource TEXT NOT NULL, - keys_json TEXT NOT NULL DEFAULT '[]', - outcome TEXT NOT NULL DEFAULT 'accepted', - created_at INTEGER NOT NULL -); - -CREATE INDEX IF NOT EXISTS idx_security_audit_logs_user_created - ON security_audit_logs(user_id, created_at DESC, id DESC); - --- +goose Down -DROP TABLE IF EXISTS security_audit_logs; diff --git a/internal/db/migrations/sqlite/00033_notification_outbox_uncertain.sql b/internal/db/migrations/sqlite/00033_notification_outbox_uncertain.sql deleted file mode 100644 index 7b81536..0000000 --- a/internal/db/migrations/sqlite/00033_notification_outbox_uncertain.sql +++ /dev/null @@ -1,6 +0,0 @@ --- +goose Up --- uncertain_at 记录外部发送成功但本地确认失败的隔离时间,避免租约过期后自动重复发送。 -ALTER TABLE notification_outbox ADD COLUMN uncertain_at INTEGER NOT NULL DEFAULT 0; - --- +goose Down -ALTER TABLE notification_outbox DROP COLUMN uncertain_at; diff --git a/internal/db/migrations/sqlite/00034_notification_outbox_idempotency.sql b/internal/db/migrations/sqlite/00034_notification_outbox_idempotency.sql deleted file mode 100644 index fbb6bd5..0000000 --- a/internal/db/migrations/sqlite/00034_notification_outbox_idempotency.sql +++ /dev/null @@ -1,10 +0,0 @@ --- +goose Up --- idempotency_key 让同一自动化运行终态对同一渠道只保留一条 outbox 记录。 --- NULL 保持历史普通通知可重复投递;uncertain 记录保留原键,从而禁止恢复时自动重新入队。 -ALTER TABLE notification_outbox ADD COLUMN idempotency_key TEXT NULL; -CREATE UNIQUE INDEX idx_notification_outbox_channel_idempotency - ON notification_outbox(channel_id, idempotency_key); - --- +goose Down -DROP INDEX IF EXISTS idx_notification_outbox_channel_idempotency; -ALTER TABLE notification_outbox DROP COLUMN idempotency_key; diff --git a/internal/db/multidb_test.go b/internal/db/multidb_test.go index 27e1f41..e1ab4c7 100644 --- a/internal/db/multidb_test.go +++ b/internal/db/multidb_test.go @@ -1222,7 +1222,7 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) { } // i 表示本次回滚操作序号。 for i := 0; version >= 14; i++ { - if // err 保存err,供当前处理流程使用 + if // err 保存当前方言迁移回滚错误,失败时保留步骤号诊断。 err := goose.Down(tg.store.DB, "migrations/"+subdir); err != nil { t.Fatalf("migration down #%d: %v", i+1, err) } @@ -1285,6 +1285,8 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) { {"account_task_runs", "run_key"}, {"chat_sessions", "unread_count"}, {"chat_messages", "message_key"}, + {"chat_messages", "read_status"}, + {"chat_messages", "read_at"}, } { if !columnExistsForDialect(t, tg.store.DB, tg.dialect, c.table, c.col) { t.Fatalf("column missing after re-up: %s.%s", c.table, c.col) diff --git a/internal/db/ws_message.go b/internal/db/ws_message.go index 354ed51..c555507 100644 --- a/internal/db/ws_message.go +++ b/internal/db/ws_message.go @@ -68,3 +68,32 @@ func (w *WSMessageStore) DeleteBefore(ctx context.Context, cookieID string, cuto } return result.RowsAffected() } + +// FindInboundParsedJSONContaining 返回最近的已解密入站诊断帧,供旧版聊天消息标识迁移使用。 +func (w *WSMessageStore) FindInboundParsedJSONContaining(ctx context.Context, cookieID, fragment string, limit int) ([]string, error) { + // safeLimit 限制诊断查询行数,避免单次已读操作读取过多历史帧。 + safeLimit := limit + if safeLimit <= 0 || safeLimit > 100 { + safeLimit = 20 + } + // rows、err 保存匹配的诊断帧游标及数据库查询错误。 + rows, err := w.DB.QueryContext(ctx, `SELECT parsed_json FROM ws_messages + WHERE cookie_id=? AND direction='in' AND parse_status='decrypted' AND parsed_json LIKE ? + ORDER BY id DESC LIMIT ?`, cookieID, "%"+fragment+"%", safeLimit) + if err != nil { + return nil, err + } + defer rows.Close() + // values 保存按时间倒序读取的已解密诊断 JSON。 + values := make([]string, 0, safeLimit) + for rows.Next() { + // value 保存当前诊断帧的解析 JSON。 + var value string + // scanErr 保存当前诊断帧字段扫描错误。 + if scanErr := rows.Scan(&value); scanErr != nil { + return nil, scanErr + } + values = append(values, value) + } + return values, rows.Err() +} diff --git a/internal/engine/account.go b/internal/engine/account.go index 67f9dd0..a03dd71 100644 --- a/internal/engine/account.go +++ b/internal/engine/account.go @@ -85,7 +85,25 @@ type Handler interface { OnAccountAlert(ctx context.Context, cookieID, level, title, body string) } -// accountEventHandler 保存账号EventHandler,供当前处理流程使用 +// MessageReadHandler 是可选的聊天已读回执端口,旧 Handler 实现不必承担该能力。 +type MessageReadHandler interface { + // HandleMessageRead 接收已解析且不包含凭证的平台已读事件。 + HandleMessageRead(context.Context, MessageReadEvent) error +} + +// MessageReadEvent 是平台出站消息已读状态的非敏感事件载体。 +type MessageReadEvent struct { + // AccountID 是当前运行时账号标识。 + AccountID string + // ChatID 是平台会话标识。 + ChatID string + // MessageID 是平台 PNM 消息标识。 + MessageID string + // ReadAt 是平台或本机记录的 Unix 毫秒已读时间。 + ReadAt int64 +} + +// accountEventHandler 保存账号事件扩展端口,供可选通知器识别类型化告警。 type accountEventHandler interface { OnAccountEvent(ctx context.Context, cookieID, eventType, level, title, body string) } @@ -129,6 +147,7 @@ type ChatMessage struct { SenderUserID string SenderName string Text string + MessageID string ItemID string Raw map[string]any // 解密后的完整消息 } @@ -838,6 +857,26 @@ func (a *Account) SendText(ctx context.Context, chatID, toUserID, text string) e return a.outgoing.sendText(ctx, chatID, toUserID, text) } +// MarkChatRead 向已连接的 WebSocket 上报会话消息已读状态,调用方负责用户所有权校验。 +func (a *Account) MarkChatRead(ctx context.Context, chatID string, messageIDs []map[string]any) error { + // conn、err 保存当前连接快照及不可发送时的生命周期错误。 + conn, _, err := a.outgoing.currentSenderState() + if err != nil { + return err + } + // readCtx、cancel 为平台上报设置固定超时,取消责任在本方法返回时释放。 + readCtx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + // reader、ok 保存连接是否支持可选的已读上报能力。 + reader, ok := conn.(interface { + MarkChatRead(context.Context, string, []map[string]any) error + }) + if !ok { + return fmt.Errorf("当前 WebSocket 不支持已读上报") + } + return reader.MarkChatRead(readCtx, chatID, messageIDs) +} + // SendImage 通过当前 WebSocket 给买家发送图片消息。当前仅支持可直接访问的 CDN/公网 URL。 func (a *Account) SendImage(ctx context.Context, chatID, toUserID, imageURL string, cardID int64) error { return a.outgoing.sendImage(ctx, chatID, toUserID, imageURL, cardID) diff --git a/internal/engine/dispatch.go b/internal/engine/dispatch.go index 88a6bc2..2a3de01 100644 --- a/internal/engine/dispatch.go +++ b/internal/engine/dispatch.go @@ -3,8 +3,12 @@ package engine import ( "context" "encoding/json" + "fmt" + "net/url" "strings" "time" + + "xianyu-go/internal/xianyu/protocol" ) // dispatch 是 ws.ReceiveLoop 的回调,对每条解密后的消息做: @@ -19,6 +23,107 @@ func (a *Account) handleMessage(decrypted map[string]any) { a.messageDispatcher.handleMessage(decrypted) } +// extractMessageReadEvent 从解密 WebSocket 事件中提取出站消息已读回执。 +func extractMessageReadEvent(v map[string]any) (MessageReadEvent, bool) { + // 40103 解密后不会保留外层 objectType,只剩下固定的紧凑字段: + // 1=PNM 消息 ID、2=状态(2=已读)、4=会话 ID、6=事件时间。 + // 不能只在解密后的 map 里继续寻找 "bizType":40103,否则真实回执 + // 会被当成普通消息静默丢弃。 + // messageID 保存紧凑回执或嵌套事件中的平台 PNM 消息 ID。 + messageID := strings.TrimSpace(toString(v["1"])) + // ids 保存批量回执携带的 PNM ID 列表;ok 表示字段 1 是否采用批量编码。 + if ids, ok := v["1"].([]any); ok && len(ids) > 0 { + messageID = strings.TrimSpace(toString(ids[0])) + } + if strings.HasSuffix(messageID, ".PNM") && toString(v["2"]) == "2" { + // chatID 保存紧凑回执携带的会话 ID,旧信封缺失时回退字段 3。 + chatID := strings.TrimSpace(toString(v["4"])) + if !strings.Contains(chatID, "@goofish") { + chatID = strings.TrimSpace(toString(v["3"])) + } + chatID = strings.TrimSuffix(chatID, "@goofish") + return MessageReadEvent{ChatID: chatID, MessageID: messageID, ReadAt: time.Now().UTC().UnixMilli()}, true + } + // found 标记已定位 40103 信封;ev 累积其会话和消息标识;walk 递归读取兼容嵌套结构。 + var found bool + // ev 保存从嵌套兼容回执中提取的平台会话与消息标识。 + var ev MessageReadEvent + // walk 解析对象、数组或 JSON 字符串形式的嵌套事件,命中后停止后续遍历。 + var walk func(any) + walk = func(x any) { + if found { + return + } + // m 保存当前遍历节点被识别出的具体 JSON 数据类型。 + switch m := x.(type) { + case map[string]any: + // k 为当前字段名;val 为其原始 JSON 值,用来定位回执事件类型。 + for k, val := range m { + // lk 是小写化字段名,兼容平台信封的不同字段命名。 + lk := strings.ToLower(k) + if lk == "biztype" || lk == "biz_type" || lk == "type" { + if toString(val) == "40103" { + found = true + } + } + } + if found { + ev.MessageID = extractNestedString(m, "messageid", "message_id") + ev.ChatID = extractNestedString(m, "cid", "chatid", "chat_id") + if ev.MessageID == "" { + ev.MessageID = extractNestedString(m, "id") + } + return + } + // child 为当前对象中的嵌套值,继续搜索未解包的回执信封。 + for _, child := range m { + walk(child) + } + case []any: + // child 为当前批量信封中的一个候选事件。 + for _, child := range m { + walk(child) + } + case string: + // 部分同步信封将事件体编码为转义 JSON 字符串,而非已解码对象。 + // decoded 保存反序列化后的事件体,兼容字符串包装的同步消息。 + var decoded any + if json.Unmarshal([]byte(m), &decoded) == nil { + walk(decoded) + } + } + } + walk(v) + if !found || ev.MessageID == "" { + return MessageReadEvent{}, false + } + return ev, true +} + +// extractNestedString 在嵌套信封中按大小写无关键名查找第一个非空字符串。 +func extractNestedString(m map[string]any, keys ...string) string { + // k 是当前字段名;v 是字段原值,用于大小写无关地匹配候选键。 + for k, v := range m { + // want 为调用方允许的目标字段名。 + for _, want := range keys { + if strings.EqualFold(k, want) && strings.TrimSpace(toString(v)) != "" { + return strings.TrimSpace(toString(v)) + } + } + } + // v 为当前对象中的嵌套值,继续查询其中的兼容子信封。 + for _, v := range m { + // child 为可继续递归解析的对象;ok 表示当前值是否是对象结构。 + if child, ok := v.(map[string]any); ok { + // s 保存子信封中找到的第一个非空目标字段值。 + if s := extractNestedString(child, keys...); s != "" { + return s + } + } + } + return "" +} + // markAndCheckDedup 提取消息 ID,检查 1 小时内是否已处理;未处理则标记。 // 返回 true 表示应继续处理。移植自 _schedule_debounced_reply 的去重段。 // markAndCheckDedup 负责markAndCheckDedup相关处理。 @@ -38,16 +143,24 @@ func (a *Account) scheduleDebouncedReply(chat ChatMessage) { a.messageDispatcher.scheduleDebouncedReply(chat) } -// extractMessageID 从 message["1"]["10"]["bizTag"] 或 extJson 中提取 messageId。 -// 移植自 _extract_message_id。 -// extractMessageID 负责extract消息ID相关处理。 +// extractMessageID 提取闲鱼消息状态接口使用的消息 ID。 +// +// 实时 WS 聊天消息同时包含两种 ID:message["1"]["3"] 是消息在 IM +// 服务中的 PNM ID,/r/MessageStatus/read 使用的正是这个 ID;10.bizTag、 +// extJson 和 reminderUrl 里的 messageId 是通知/推送侧的关联 ID,不能用来 +// 上报会话已读。历史消息接口也返回 PNM ID,因此优先使用字段 3,其他 +// 字段只作为兼容旧消息或缺失字段 3 的兜底。 func extractMessageID(decrypted map[string]any) string { // m1、ok 保存m1、ok,供当前处理流程使用 m1, ok := decrypted["1"].(map[string]any) if !ok { return "" } - // m10、ok 保存m10、ok,供当前处理流程使用 + // id 保存实时消息最可靠的 PNM ID,存在时不可用推送关联 ID 覆盖。 + if id := strings.TrimSpace(toString(m1["3"])); id != "" && id != "" { + return id + } + // m10、ok 保存消息展示扩展及其是否存在,用于兼容旧消息关联 ID。 m10, ok := m1["10"].(map[string]any) if !ok { return "" @@ -66,6 +179,55 @@ func extractMessageID(decrypted map[string]any) string { return id } } + // reminderURL 保存提醒链接,旧消息会将推送关联 ID 编码在其查询参数中。 + if reminderURL, _ := m10["reminderUrl"].(string); reminderURL != "" { + // parsed 保存已解析的提醒链接;err 表示 URL 格式不合法时的解析失败。 + if parsed, err := url.Parse(reminderURL); err == nil { + // id 保存 reminderUrl 查询参数中的兼容消息关联 ID。 + if id := strings.TrimSpace(parsed.Query().Get("messageId")); id != "" { + return id + } + } + } + return findMessageID(decrypted) +} + +// findMessageID 递归解析兼容消息信封中可能存在的关联消息 ID。 +func findMessageID(value any) string { + // x 保存当前待搜索节点的具体值,按对象、数组和 JSON 字符串分别处理。 + switch x := value.(type) { + case map[string]any: + // key 是对象字段名;child 是字段值,用于先检查本层关联 ID。 + for key, child := range x { + if strings.EqualFold(key, "messageId") || strings.EqualFold(key, "message_id") { + // id 保存当前字段提供的非空关联消息 ID。 + if id := strings.TrimSpace(fmt.Sprint(child)); id != "" && id != "" { + return id + } + } + } + // child 为本层嵌套字段值,递归兼容更深层信封。 + for _, child := range x { + // id 保存子节点中首先发现的关联消息 ID。 + if id := findMessageID(child); id != "" { + return id + } + } + case []any: + // child 为批量消息中的一个候选事件或子信封。 + for _, child := range x { + // id 保存数组成员中首先发现的关联消息 ID。 + if id := findMessageID(child); id != "" { + return id + } + } + case string: + // decoded 保存从 JSON 字符串解码后的兼容嵌套结构。 + var decoded any + if json.Unmarshal([]byte(x), &decoded) == nil { + return findMessageID(decoded) + } + } return "" } @@ -110,9 +272,14 @@ func extractChatMessage(decrypted map[string]any, accountID, cookieStr string) * if i := strings.Index(chatID, "@"); i >= 0 { chatID = chatID[:i] } - // senderUserID 保存sender用户ID,供当前处理流程使用 - senderUserID, _ := m10["senderUserId"].(string) - // senderName 保存sender名称,供当前处理流程使用 + // senderUserID 保存经兼容字段归一后的发送者身份。 + senderUserID := extractChatSenderUserIDFromMaps(m1, m10) + if isSelfUserID(senderUserID, protocol.TransCookies(cookieStr)["unb"]) { + // 官方客户端会通过同一 WebSocket 回显本账号发出的消息;它仅表示投递观察, + // 并非买家新输入,绝不能进入自动回复链。 + return nil + } + // senderName 保存发送者展示名称,字段缺失时由提醒标题补齐。 senderName, _ := m10["senderNick"].(string) if strings.TrimSpace(senderName) == "" { senderName, _ = m10["reminderTitle"].(string) @@ -128,11 +295,37 @@ func extractChatMessage(decrypted map[string]any, accountID, cookieStr string) * SenderUserID: senderUserID, SenderName: senderName, Text: reminder, + MessageID: extractMessageID(decrypted), ItemID: itemID, Raw: decrypted, } } +// extractChatSenderUserIDFromMaps 优先读取展示扩展,并兼容紧凑信封中的发送者账号 ID。 +func extractChatSenderUserIDFromMaps(m1, m10 map[string]any) string { + if m10 != nil { + // sender 保存标准 senderUserId 的去空白结果。 + if sender := strings.TrimSpace(toString(m10["senderUserId"])); sender != "" { + return sender + } + } + // 部分回显消息缺少 10.senderUserId,但仍在紧凑 1.1 信封中保留发送者身份。 + // sender 保存紧凑信封中的发送者对象;ok 表示该兼容字段是否存在。 + if sender, ok := m1["1"].(map[string]any); ok { + return strings.TrimSpace(toString(sender["1"])) + } + return "" +} + +// isSelfUserID 比较发送者与当前账号身份,忽略 IM 协议后缀以过滤官方客户端回显。 +func isSelfUserID(senderUserID, selfUserID string) bool { + // sender 是归一化后的消息发送者身份。 + sender := strings.TrimSuffix(strings.TrimSpace(senderUserID), "@goofish") + // self 是归一化后的当前账号身份。 + self := strings.TrimSuffix(strings.TrimSpace(selfUserID), "@goofish") + return sender != "" && self != "" && sender == self +} + // isNonUserChatNotice 判断闲鱼 IM 中不应进入自动回复的系统提示或交易卡片。 // 典型样本: // - contentType=14:“有蚂蚁森林能量可领”“不想宝贝被砍价?设置不砍价回复”“退款成功” diff --git a/internal/engine/dispatch_extra_test.go b/internal/engine/dispatch_extra_test.go index d781c86..f04e0c0 100644 --- a/internal/engine/dispatch_extra_test.go +++ b/internal/engine/dispatch_extra_test.go @@ -146,6 +146,24 @@ func TestHandleMessage_DedupSkipsRepeat(t *testing.T) { } } +// TestHandleMessage_IgnoresOwnWebSocketEcho 验证当前账号的 WS 回显不会触发自动回复。 +func TestHandleMessage_IgnoresOwnWebSocketEcho(t *testing.T) { + // acc 是待测账号;h 记录业务处理调用;cleanup 释放测试数据库和运行时资源。 + acc, h, _, cleanup := newAccountForTest(t) + defer cleanup() + defer acc.Stop() + + // newAccountForTest 使用 unb=123;模拟同一账号在闲鱼官方客户端发出的 + // 消息回显,不能进入自动回复或业务消息处理链。 + acc.handleMessage(plainChatMessage(t, "官方客户端发送", "123", "chat-own")) + time.Sleep(MessageDebounceDelay + 200*time.Millisecond) + h.mu.Lock() + defer h.mu.Unlock() + if len(h.chats) != 0 { + t.Fatalf("账号自身消息回显不应触发自动回复,got %d", len(h.chats)) + } +} + // TestHandleMessage_NoReminderNoOp 无 reminderContent 的消息不进入回复链也不报错。 func TestHandleMessage_NoReminderNoOp(t *testing.T) { // acc、h、cleanup 保存acc、h、cleanup,供当前处理流程使用 @@ -584,3 +602,22 @@ func plainChatMessage(t *testing.T, text, senderUserID, chatID string) map[strin } return m } + +// TestExtractMessageReadEvent40103 验证紧凑和批量 40103 已读事件均能生成规范回执。 +func TestExtractMessageReadEvent40103(t *testing.T) { + // event 是单条紧凑回执的解析结果;ok 表示该输入已被识别为已读事件。 + event, ok := extractMessageReadEvent(map[string]any{ + "1": "4263141580162.PNM", "2": 2, "3": 0, + "4": "64725235816@goofish", "5": 1, "6": 1786945729928, + }) + if !ok || event.MessageID != "4263141580162.PNM" || event.ChatID != "64725235816" || event.ReadAt <= 0 { + t.Fatalf("40103 event=%+v ok=%v", event, ok) + } + // batch 是批量编码回执的解析结果;ok 复用为该回执的事件识别结果。 + batch, ok := extractMessageReadEvent(map[string]any{ + "1": []any{"4263107993838.PNM"}, "2": 2, "3": "64725235816@goofish", "4": 1, + }) + if !ok || batch.MessageID != "4263107993838.PNM" || batch.ChatID != "64725235816" { + t.Fatalf("40103 batch event=%+v ok=%v", batch, ok) + } +} diff --git a/internal/engine/engine_test.go b/internal/engine/engine_test.go index 9515f24..8ff8257 100644 --- a/internal/engine/engine_test.go +++ b/internal/engine/engine_test.go @@ -124,7 +124,20 @@ func TestExtractChatMessageUsesReminderTitleAsNickname(t *testing.T) { } } -// TestExtractChatMessage_FiltersRefundTradeCard 负责TestExtract聊天消息FiltersRefundTrade卡密相关处理。 +// TestExtractChatMessageIgnoresOwnWebSocketEcho 验证账号自身的 WebSocket 回显不会进入回复链。 +func TestExtractChatMessageIgnoresOwnWebSocketEcho(t *testing.T) { + // decrypted 模拟账号自身发送后由同一 WebSocket 回传的解密聊天信封。 + decrypted := map[string]any{"1": map[string]any{ + "2": "chat-1@goofish", + "10": map[string]any{"reminderContent": "我在官方客户端发送的消息", "senderUserId": "self-1", "senderNick": "我"}, + }} + // chat 是提取结果;账号自身的回显必须被过滤,因此应为 nil。 + if chat := extractChatMessage(decrypted, "account-1", "unb=self-1;"); chat != nil { + t.Fatalf("账号自身发送的 WS 回显不应进入自动回复链: %+v", chat) + } +} + +// TestExtractChatMessage_FiltersRefundTradeCard 验证退款交易卡不会被识别为用户聊天。 func TestExtractChatMessage_FiltersRefundTradeCard(t *testing.T) { // decrypted 保存decrypted,供当前处理流程使用 decrypted := mustRefundTradeCard(t) diff --git a/internal/engine/message_dispatcher.go b/internal/engine/message_dispatcher.go index b928d7f..a94112e 100644 --- a/internal/engine/message_dispatcher.go +++ b/internal/engine/message_dispatcher.go @@ -157,6 +157,21 @@ func (d *messageDispatcher) handleMessage(decrypted map[string]any) { // handleMessageContext 将系统事件和聊天消息分别交给对应业务链。 func (d *messageDispatcher) handleMessageContext(ctx context.Context, decrypted map[string]any) { + // receipt、ok 保存解析出的平台已读回执及是否命中已读事件格式。 + if receipt, ok := extractMessageReadEvent(decrypted); ok { + receipt.AccountID = d.cookieID + // handler 保存当前可选处理器;旧集成不实现回执端口时保持兼容。 + if handler := d.currentHandler(); handler != nil { + // reader 是可消费已读回执的可选端口;supported 表示当前集成实现了该端口。 + if reader, supported := handler.(MessageReadHandler); supported { + // err 保存回执持久化错误;失败不应中断 WebSocket 接收循环。 + if err := reader.HandleMessageRead(ctx, receipt); err != nil { + d.logger.Warn("处理聊天已读回执失败", "err", err, "message_id", receipt.MessageID) + } + } + } + return + } // 系统卡片和平台通知优先进入自动化中心,永远不进入 AI 回复范围。 if task := automation.ExtractTaskFromWS(d.cookieID, d.currentCookie(), decrypted); task != nil { if // handler 保存handler,供当前处理流程使用 diff --git a/internal/engine/reply_extra_test.go b/internal/engine/reply_extra_test.go index 4bfe72c..376d8b5 100644 --- a/internal/engine/reply_extra_test.go +++ b/internal/engine/reply_extra_test.go @@ -262,18 +262,19 @@ func TestParseMessageIDFromJSON(t *testing.T) { } } -// TestExtractMessageID 优先 bizTag,其次 extJson,无则空。 +// TestExtractMessageID 优先实时消息的 PNM ID,其次兼容 bizTag/extJson,无则空。 func TestExtractMessageID(t *testing.T) { if // got 保存got,供当前处理流程使用 got := extractMessageID(map[string]any{ "1": map[string]any{ + "3": "4263141580162.PNM", "10": map[string]any{ "bizTag": `{"messageId":"biz-id"}`, "extJson": `{"messageId":"ext-id"}`, }, }, - }); got != "biz-id" { - t.Errorf("bizTag 优先: got %q", got) + }); got != "4263141580162.PNM" { + t.Errorf("PNM 优先: got %q", got) } if // got 保存got,供当前处理流程使用 got := extractMessageID(map[string]any{ diff --git a/internal/server/application_services.go b/internal/server/application_services.go index a09b3df..eaf4d18 100644 --- a/internal/server/application_services.go +++ b/internal/server/application_services.go @@ -366,10 +366,8 @@ func newApplicationServices(server *Server) *applicationServices { panic(itemCatalogMutationErr) } // itemPublishPort 是单商品与批量发布共享的平台凭证适配器。 - itemPublishPort := server.itemDependencies.NewItemPublishPort(server.mtopClient, server.Logger, server.updateRunningCookie, func(ctx context.Context, cookieID string, err error) { - if sessionRecovery != nil { - sessionRecovery(ctx, cookieID, err) - } + itemPublishPort := server.itemDependencies.NewItemPublishPort(server.mtopClient, server.Logger, server.updateRunningCookie, func(ctx context.Context, cookieID string, err error) bool { + return sessionRecovery != nil && sessionRecovery(ctx, cookieID, err) }) // itemCategoryRecommendation 复用商品发布端口承载类目推荐和响应会话写回。 itemCategoryRecommendation, itemCategoryRecommendationErr := itemapp.NewCategoryRecommendationService(itemPublishPort) diff --git a/internal/server/card_handlers.go b/internal/server/card_handlers.go index 7cc2dcf..dd26c95 100644 --- a/internal/server/card_handlers.go +++ b/internal/server/card_handlers.go @@ -64,6 +64,9 @@ func (s *Server) listCards(w http.ResponseWriter, r *http.Request) { // cards、err 保存应用服务返回的用户卡券列表及查询错误。 cards, err := s.cardsApplication().List(r.Context(), session.UserID) if err != nil { + if s.Logger != nil { + s.Logger.Error("查询卡密失败", "user_id", session.UserID, "err", err) + } writeErr(w, http.StatusInternalServerError, "查询失败") return } diff --git a/internal/server/chat_account_tasks_test.go b/internal/server/chat_account_tasks_test.go index 9395ee2..de71bab 100644 --- a/internal/server/chat_account_tasks_test.go +++ b/internal/server/chat_account_tasks_test.go @@ -147,3 +147,43 @@ func TestChatAndTaskEndpointsEnforceOwnershipAndValidation(t *testing.T) { } } } + +// TestFindChatPlatformMessageID 验证历史推送关联 ID 只在同一会话内映射为 PNM 已读 ID。 +func TestFindChatPlatformMessageID(t *testing.T) { + // raw 模拟持久化的解密 WS 消息,包含推送关联 ID 与平台 PNM ID。 + raw := map[string]any{ + "1": map[string]any{ + "2": "64725235816@goofish", + "3": "4263141580162.PNM", + "10": map[string]any{ + "extJson": `{"messageId":"f87f8f6dabca4eff940863ef72a393f7"}`, + }, + }, + } + // got 保存同会话匹配后可向平台上报的 PNM ID。 + if got := findChatPlatformMessageID(raw, "64725235816", "f87f8f6dabca4eff940863ef72a393f7"); got != "4263141580162.PNM" { + t.Fatalf("platform message id=%q", got) + } + // got 保存跨会话查询结果,必须为空以禁止错误标记其他会话已读。 + if got := findChatPlatformMessageID(raw, "other-chat", "f87f8f6dabca4eff940863ef72a393f7"); got != "" { + t.Fatalf("跨会话错误匹配: %q", got) + } +} + +// TestResolveChatReadMessageIDsMigratesLegacyID 验证历史关联 ID 会转换为平台接受的 PNM ID。 +func TestResolveChatReadMessageIDsMigratesLegacyID(t *testing.T) { + // srv 提供待测解析路径;store 写入历史 WS 消息;cleanup 释放测试服务器和数据库。 + srv, store, cleanup := newTestServer(t) + defer cleanup() + // raw 是保存到数据库的解密信封 JSON,含旧关联 ID 及其对应的 PNM ID。 + raw := `{"1":{"2":"64725235816@goofish","3":"4263141580162.PNM","10":{"extJson":"{\"messageId\":\"f87f8f6dabca4eff940863ef72a393f7\"}"}}}` + // err 保存写入历史 WS 消息失败的原因,写入失败会使后续解析夹具无效。 + if err := store.WSMessages.Add(context.Background(), db.WSMessage{CookieID: "acc1", Direction: "in", ParsedJSON: raw, ParseStatus: "decrypted"}); err != nil { + t.Fatal(err) + } + // got 是兼容解析后的上报参数,旧关联 ID 必须被替换为 PNM ID。 + got := srv.resolveChatReadMessageIDs(context.Background(), "acc1", "64725235816", []map[string]any{{"messageId": "f87f8f6dabca4eff940863ef72a393f7"}}) + if len(got) != 1 || got[0]["messageId"] != "4263141580162.PNM" { + t.Fatalf("resolved=%+v", got) + } +} diff --git a/internal/server/chat_handlers.go b/internal/server/chat_handlers.go index 4e0d85b..ad24749 100644 --- a/internal/server/chat_handlers.go +++ b/internal/server/chat_handlers.go @@ -4,6 +4,7 @@ import ( "context" "errors" "io" + "log/slog" "net/http" "strconv" "strings" @@ -284,8 +285,9 @@ func (s *Server) sendChatMessage(w http.ResponseWriter, r *http.Request) { func (s *Server) markChatRead(w http.ResponseWriter, r *http.Request) { // input 保存input,供当前处理流程使用 var input struct { - AccountID string `json:"account_id"` - ChatID string `json:"chat_id"` + AccountID string `json:"account_id"` + ChatID string `json:"chat_id"` + MessageIDs []map[string]any `json:"message_ids"` } if decodeJSON(r, &input) != nil || input.ChatID == "" { writeErr(w, http.StatusBadRequest, "请求格式错误") @@ -295,17 +297,90 @@ func (s *Server) markChatRead(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusForbidden, "无权操作该账号") return } - // sess 保存当前认证用户,用于应用层归属隔离。 + // sess 保存当前认证用户,用于本地未读状态归属隔离。 sess := auth.SessionFromContext(r.Context()) + slog.Info("收到聊天已读请求", "account", input.AccountID, "chat_id", input.ChatID, "message_count", len(input.MessageIDs)) + if len(input.MessageIDs) == 0 { + // page 保存应用层返回的本地消息页,只含非敏感字段。 + page, listErr := s.chatApplication().ListStoredMessages(r.Context(), sess.UserID, input.AccountID, input.ChatID, 0, 200) + if listErr == nil { + // message 是当前用于补全平台已读消息标识的入站消息。 + for _, message := range page.Messages { + if message.Direction == "incoming" && message.MessageType != "system" { + input.MessageIDs = append(input.MessageIDs, map[string]any{"messageId": message.MessageKey}) + } + } + } + } + // 旧版本把实时 WS 通知里的 bizTag/extJson messageId 当成了平台消息 + // ID,数据库里会留下 32 位关联 ID。闲鱼的 read 接口实际要求 1.3 的 + // PNM ID;这里从已保存的解密 WS 诊断帧把旧 ID 转回 PNM,避免升级后 + // 仍有历史实时消息无法被标记已读。 + input.MessageIDs = s.resolveChatReadMessageIDs(r.Context(), input.AccountID, input.ChatID, input.MessageIDs) if // err 保存应用层已读状态更新错误。 err := s.chatApplication().MarkRead(r.Context(), sess.UserID, input.AccountID, input.ChatID); err != nil { writeErr(w, http.StatusInternalServerError, "更新已读状态失败") return } + if s.Manager != nil { + // sender、ok 保存当前账号运行时及其在线状态。 + if sender, ok := s.Manager.GetInstance(input.AccountID); ok { + // reader、ok 保存运行时是否支持平台已读上报。 + if reader, ok := sender.(interface { + MarkChatRead(context.Context, string, []map[string]any) error + }); ok { + // err 保存平台已读上报失败,失败不影响本地状态已落库。 + if err := reader.MarkChatRead(r.Context(), input.ChatID, input.MessageIDs); err != nil { + slog.Warn("上报闲鱼已读状态失败", "account", input.AccountID, "chat_id", input.ChatID, "err", err) + } + } + } + } writeJSON(w, http.StatusOK, operationResponse{Success: true}) } -// chatWebSocket 负责聊天WebSocket相关处理。 +// resolveChatReadMessageIDs 将旧版关联标识交给应用服务解析,并移除无效或重复的已读项。 +func (s *Server) resolveChatReadMessageIDs(ctx context.Context, accountID, chatID string, messageIDs []map[string]any) []map[string]any { + // resolved 保存可安全提交给平台的去重消息标识列表。 + resolved := make([]map[string]any, 0, len(messageIDs)) + // seen 保存已加入结果的平台 PNM 标识,避免重复上报。 + seen := make(map[string]struct{}, len(messageIDs)) + // item 是当前待转换的已读消息参数。 + for _, item := range messageIDs { + // rawID 保存请求携带的原始消息标识。 + rawID, ok := item["messageId"].(string) + if !ok || strings.TrimSpace(rawID) == "" { + continue + } + // id 保存应用层解析后的平台消息标识。 + id := s.chatApplication().ResolveReadMessageID(ctx, accountID, chatID, rawID) + if !strings.HasSuffix(id, ".PNM") { + slog.Warn("未找到旧聊天消息对应的 PNM,跳过已读上报", "account", accountID, "chat_id", chatID, "message_id", rawID) + continue + } + // exists 表示该平台消息标识是否已经加入本次上报请求。 + if _, exists := seen[id]; exists { + continue + } + seen[id] = struct{}{} + // copyItem 保存保留其他平台参数、只替换消息标识的请求副本。 + copyItem := make(map[string]any, len(item)+1) + // key、value 保存当前平台参数名及其原始值。 + for key, value := range item { + copyItem[key] = value + } + copyItem["messageId"] = id + resolved = append(resolved, copyItem) + } + return resolved +} + +// findChatPlatformMessageID 保留既有包内测试入口,实际解析由聊天应用服务拥有。 +func findChatPlatformMessageID(value any, chatID, legacyID string) string { + return chatapp.FindPlatformMessageID(value, chatID, legacyID) +} + +// chatWebSocket 将应用层聊天事件转发到当前认证用户的 WebSocket 连接。 func (s *Server) chatWebSocket(w http.ResponseWriter, r *http.Request) { // sess 保存sess,供当前处理流程使用 sess := auth.SessionFromContext(r.Context()) diff --git a/internal/server/item_handlers.go b/internal/server/item_handlers.go index 06881d4..e7e2241 100644 --- a/internal/server/item_handlers.go +++ b/internal/server/item_handlers.go @@ -111,7 +111,6 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) { } selectedLocation = &location } - // outcome、callErr 保存outcome、callErr,供当前处理流程使用 // applicationLocation 是 HTTP DTO 转换后的应用发货地模型。 var applicationLocation *itemapp.Location if selectedLocation != nil { @@ -154,8 +153,6 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusConflict, callErr.Error()) return } - writeErr(w, http.StatusBadGateway, callErr.Error()) - return } if res == nil || strings.TrimSpace(res.ItemID) == "" { writeErrCode(w, http.StatusBadGateway, "publish_result_missing_item_id", "平台返回发布成功,但缺少商品 ID,无法确认发布结果", "") diff --git a/internal/server/server.go b/internal/server/server.go index 3a6ac31..0799cd6 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -84,7 +84,7 @@ type itemDependencyFactory interface { // NewItemBatchPublishPort 创建批量远端发布端口。 NewItemBatchPublishPort(func() adapter.MTOPClient, *slog.Logger, func(context.Context, string, string), func(context.Context, string, error), adapter.ReadPublishImageFile, adapter.DownloadPublishImageURL) *adapter.ItemBatchPublishPort // NewItemPublishPort 创建单商品发布端口。 - NewItemPublishPort(func() adapter.MTOPClient, *slog.Logger, func(context.Context, string, string), func(context.Context, string, error)) *adapter.ItemPublishPort + NewItemPublishPort(func() adapter.MTOPClient, *slog.Logger, func(context.Context, string, string), func(context.Context, string, error) bool) *adapter.ItemPublishPort // NewItemPublishRepository 创建单商品发布结果仓储。 NewItemPublishRepository() *adapter.ItemPublishRepository // NewItemCatalogRepository 创建商品目录仓储。 diff --git a/internal/webui/static/assets/AccountList-fhDk6BDY.js b/internal/webui/static/assets/AccountList-Bb-tGjAS.js similarity index 99% rename from internal/webui/static/assets/AccountList-fhDk6BDY.js rename to internal/webui/static/assets/AccountList-Bb-tGjAS.js index 2e9a992..f3e9864 100644 --- a/internal/webui/static/assets/AccountList-fhDk6BDY.js +++ b/internal/webui/static/assets/AccountList-Bb-tGjAS.js @@ -1,3 +1,3 @@ -import{r as n,j as e,b as ie,c as Oe}from"./react-vendor-C_od1ZSF.js";import{g as X,p as ae,a as ce,d as Pe}from"./index-CFzx5gQT.js";import{c as Le,o as ke}from"./contract-COFcZjyb.js";import{X as de,n as ze,L as J,o as Ge,p as Ie,q as Te,r as $e,s as te,t as De,K as We,u as Ve,v as Je,e as Ke,w as ue,f as He,U as Ee,x as Xe,k as _e,Q as ve,R as Ye,y as Ze,z as Fe,F as Ne,H as es}from"./icons-vendor-CvzvbbIV.js";const ss=(s,t)=>{const r=s.avatar_url||"";if(!r)return"";try{const a=new URL(r,window.location.origin);return a.hostname.endsWith("alicdn.com")&&a.searchParams.set("_v",t),a.toString()}catch{return r}},ts=async s=>{const t=await X("/api/v1/accounts/details",void 0,s),r=Le(t,["data","accounts","details"]),a=Date.now().toString();return r.map(l=>({id:l.id,cookie_configured:l.has_cookie===!0,enabled:l.enabled,auto_confirm:l.auto_confirm,remark:l.remark,pause_duration:l.pause_duration,paused_until:Number(l.paused_until||0),paused:l.paused===!0,username:l.username||"",login_password_configured:void 0,show_browser:l.show_browser===!0||l.show_browser===1||l.show_browser==="1"||l.show_browser==="true",nickname:l.nickname||l.remark||`账号 ${l.id.substring(0,6)}`,avatar_url:ss(l,a),profile_error:l.profile_error||"",ai_enabled:!1,auto_rate_enabled:l.auto_rate_enabled,rate_content:l.rate_content||"不错的买家,交易愉快",auto_polish_enabled:l.auto_polish_enabled,polish_time:l.polish_time||"03:00",last_rate_scan_at:Number(l.last_rate_scan_at||0),last_polish_date:l.last_polish_date||"",last_polish_at:Number(l.last_polish_at||0)}))},as=async s=>{const t=await X("/api/v1/accounts/runtime-status",void 0,s);return ke(t,["statuses","data","result"])||{}},rs=async s=>ce("/api/v1/qr-login/generate",void 0,{...s,timeoutMs:(s==null?void 0:s.timeoutMs)??13e4}),ns=async(s,t)=>X(`/api/v1/qr-login/check/${s}`,void 0,{signal:t,timeoutMs:1e4}),ls=async(s,t)=>ce(`/api/v1/qr-login/complete-verification/${s}`,{target_account_id:t||""}),os=async(s,t)=>ae(`/api/v1/accounts/${s}/status`,{enabled:t}),is=async s=>Pe(`/api/v1/accounts/${s}`),cs=async(s,t,r)=>ae(`/api/v1/accounts/${s}/pause-duration`,{pause_duration:t},r),ds=async(s,t,r)=>ae(`/api/v1/accounts/${s}/settings`,t,r),us=async(s,t)=>X(`/api/v1/accounts/${s}/long-login`,void 0,t),xs=async(s,t,r)=>ae(`/api/v1/accounts/${s}/long-login`,{enabled:t},r),ms=async(s,t)=>ce("/api/v1/password-login",s,t),bs=async(s,t)=>X(`/api/v1/password-login/check/${s}`,void 0,{signal:t,timeoutMs:1e4}),hs=async(s,t)=>Pe(`/api/v1/password-login/cancel/${s}`,void 0,t),gs=async s=>ce(`/api/v1/accounts/${s}/refresh-profile`,{}),ps=async s=>{const t=await X("/api/v1/settings/ai-reply",void 0,s);return ke(t,["settings","data","result"])||{}},fs=async(s,t)=>X(`/api/v1/settings/ai-reply/${s}`,void 0,t),ys=async(s,t,r)=>{const a={ai_enabled:t.ai_enabled??!1,max_discount_percent:t.max_discount_percent??10,max_discount_amount:t.max_discount_amount??100,max_bargain_rounds:t.max_bargain_rounds??3,custom_prompts:t.custom_prompts??""};return ae(`/api/v1/settings/ai-reply/${s}`,a,r)},js=s=>{if(Array.isArray(s))return s.filter(Boolean);if(typeof s!="string"||!s.trim())return[];try{const t=JSON.parse(s);if(Array.isArray(t))return t.filter(Boolean)}catch{}return s.split(/[,\s;]+/).map(t=>t.trim()).filter(Boolean)},ws=async s=>{const t=await X("/api/v1/notifications/channels",void 0,s);return{success:!0,data:Le(t,["data","channels","items"]).map(a=>{let l;try{l=typeof a.config=="string"?JSON.parse(a.config):a.config}catch{l={}}const c=a.type==="ding_talk"?"dingtalk":a.type==="lark"?"feishu":a.type;return{id:String(a.id),name:a.name,type:c,config:l,event_types:js(a.event_types),enabled:a.enabled,created_at:a.created_at,updated_at:a.updated_at}})}},_s=async(s,t)=>{const r=await X(`/api/v1/notifications/accounts/${s}/bindings`,void 0,t),a=ke(r,["data","result"])||{};return Array.isArray(a.channel_ids)?a.channel_ids:[]},Ce=async(s,t)=>X(`/api/v1/account-tasks/${s}`,void 0,t),Se=async(s,t,r)=>ae(`/api/v1/account-tasks/${s}`,t,r),vs=async(s,t,r)=>ce(`/api/v1/account-tasks/${s}/run`,{task_type:t},{timeoutMs:12e4,...r}),Re=s=>({account_id:s.id,auto_rate_enabled:s.auto_rate_enabled===!0,rate_content:s.rate_content||"不错的买家,交易愉快",auto_polish_enabled:s.auto_polish_enabled===!0,polish_time:s.polish_time||"03:00",last_rate_scan_at:s.last_rate_scan_at,last_polish_date:s.last_polish_date,last_polish_at:s.last_polish_at}),Y=(s,t,r)=>s===t&&!r.aborted,je=(s,t)=>s instanceof Error?s.message:t,we=s=>s instanceof Error&&s.message==="请求已取消",Ae=(s,t)=>!s&&t==="",Ns=({account:s,onSaved:t})=>{const[r,a]=n.useState(()=>Re(s)),[l,c]=n.useState(!0),[i,d]=n.useState(!1),[b,m]=n.useState(""),[f,h]=n.useState(""),[u,A]=n.useState(null),[k,g]=n.useState(null),p=n.useRef(0),L=n.useRef(null);n.useEffect(()=>{var v;const S=++p.current;(v=L.current)==null||v.abort();const j=new AbortController;return L.current=j,a(Re(s)),A(null),h(""),d(!1),m(""),g(null),c(!0),Ce(s.id,{signal:j.signal}).then(R=>{Y(p.current,S,j.signal)&&a(R)}).catch(R=>{Y(p.current,S,j.signal)&&!we(R)&&h(je(R,"加载任务设置失败"))}).finally(()=>{Y(p.current,S,j.signal)&&c(!1)}),(()=>j.abort())},[s.id]),n.useEffect(()=>(()=>{var S;return(S=L.current)==null?void 0:S.abort()}),[]);const U=n.useCallback(async()=>{var v;if(!Ae(i,b))return;const S=++p.current;(v=L.current)==null||v.abort();const j=new AbortController;L.current=j,d(!0),h(""),g(null);try{const R=await Se(s.id,r,{signal:j.signal});if(!Y(p.current,S,j.signal))return;a(R),t(R)}catch(R){Y(p.current,S,j.signal)&&!we(R)&&(h(je(R,"保存失败")),g(()=>U))}finally{Y(p.current,S,j.signal)&&d(!1)}},[s.id,r,t,b,i]),M=n.useCallback(async S=>{var R;if(!Ae(i,b)||!s.enabled)return;const j=++p.current;(R=L.current)==null||R.abort();const v=new AbortController;L.current=v,m(S),h(""),A(null),g(null);try{await Se(s.id,r,{signal:v.signal});const w=await vs(s.id,S,{signal:v.signal}),q=await Ce(s.id,{signal:v.signal});if(!Y(p.current,j,v.signal))return;A(w.summary),a(q),t(q)}catch(w){Y(p.current,j,v.signal)&&!we(w)&&(h(je(w,"任务执行失败")),g(()=>(()=>M(S))))}finally{Y(p.current,j,v.signal)&&m("")}},[s.enabled,s.id,r,t,b,i]),T=n.useCallback(async()=>{k&&await k()},[k]);return{form:r,loading:l,saving:i,running:b,summary:u,error:f,retryAvailable:k!==null,setForm:a,save:U,run:M,retry:T}},qe=({checked:s,onChange:t,label:r})=>e.jsx("button",{type:"button","aria-label":r,"aria-pressed":s,onClick:t,className:`relative h-8 w-14 shrink-0 rounded-full transition-colors ${s?"bg-sky-500":"bg-slate-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-sm transition-transform ${s?"translate-x-6":""}`})}),ks=({account:s,onClose:t,onSaved:r})=>{const{form:a,loading:l,saving:c,running:i,error:d,summary:b,retryAvailable:m,setForm:f,save:h,run:u,retry:A}=Ns({account:s,onSaved:r});return e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"640px"},role:"dialog","aria-modal":"true","aria-labelledby":"account-task-title",children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("h3",{id:"account-task-title",className:"text-2xl font-extrabold text-slate-950",children:"账号自动任务"}),e.jsx("p",{className:"mt-1 text-sm text-slate-500",children:s.nickname||s.remark||s.id})]}),e.jsx("button",{type:"button",onClick:t,className:"rounded-xl p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700","aria-label":"关闭",children:e.jsx(de,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[l&&e.jsx("div",{className:"rounded-xl bg-slate-50 px-4 py-3 text-sm text-slate-500",children:"正在读取任务设置..."}),e.jsx("section",{className:"rounded-2xl border border-slate-200 bg-white p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-emerald-50 text-emerald-600",children:e.jsx(ze,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-black text-slate-900",children:"自动评价"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-slate-500",children:"持续扫描待评价订单,按订单执行;不是每日任务。"})]}),e.jsx(qe,{checked:a.auto_rate_enabled,onChange:(()=>f(k=>({...k,auto_rate_enabled:!k.auto_rate_enabled}))),label:"自动评价"})]}),e.jsx("label",{className:"mt-4 block text-xs font-extrabold text-slate-600",children:"统一好评文案"}),e.jsx("textarea",{"aria-label":"统一好评文案",value:a.rate_content,maxLength:500,onChange:(k=>f(g=>({...g,rate_content:k.target.value}))),className:"mt-2 h-24 w-full resize-none rounded-xl border border-slate-200 bg-slate-50 px-3 py-2.5 text-sm leading-6 text-slate-800 placeholder:text-slate-400 outline-none focus:border-sky-400 focus:ring-2 focus:ring-sky-100"}),e.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3",children:[e.jsxs("span",{className:"text-xs text-slate-400",children:["最近扫描:",a.last_rate_scan_at?new Date(a.last_rate_scan_at*1e3).toLocaleString("zh-CN"):"尚未执行"]}),e.jsxs("button",{type:"button",disabled:i!==""||!s.enabled,onClick:(()=>void u("auto_rate")),className:"flex items-center gap-2 rounded-xl bg-emerald-50 px-3 py-2 text-xs font-extrabold text-emerald-700 hover:bg-emerald-100 disabled:opacity-50",children:[i==="auto_rate"?e.jsx(J,{className:"h-4 w-4 animate-spin"}):e.jsx(Ge,{className:"h-4 w-4"}),"立即评价"]})]})]})]})}),e.jsx("section",{className:"rounded-2xl border border-slate-200 bg-white p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-amber-50 text-amber-600",children:e.jsx(Ie,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-black text-slate-900",children:"每日自动擦亮"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-slate-500",children:"每个账号每天最多执行一次,按北京时间判断。"})]}),e.jsx(qe,{checked:a.auto_polish_enabled,onChange:(()=>f(k=>({...k,auto_polish_enabled:!k.auto_polish_enabled}))),label:"每日自动擦亮"})]}),e.jsxs("div",{className:"mt-4 flex items-end justify-between gap-4",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-xs font-extrabold text-slate-600",children:"每日执行时间"}),e.jsx("input",{type:"time",value:a.polish_time,onChange:(k=>f(g=>({...g,polish_time:k.target.value}))),className:"mt-2 block rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm font-bold text-slate-800 outline-none focus:border-sky-400"})]}),e.jsxs("button",{type:"button",disabled:i!==""||!s.enabled,onClick:(()=>void u("auto_polish")),className:"flex items-center gap-2 rounded-xl bg-amber-50 px-3 py-2 text-xs font-extrabold text-amber-700 hover:bg-amber-100 disabled:opacity-50",children:[i==="auto_polish"?e.jsx(J,{className:"h-4 w-4 animate-spin"}):e.jsx(Te,{className:"h-4 w-4"}),"立即擦亮"]})]}),e.jsxs("div",{className:"mt-3 text-xs text-slate-400",children:["上次完成:",a.last_polish_at?new Date(a.last_polish_at*1e3).toLocaleString("zh-CN"):"尚未执行"]})]})]})}),b&&e.jsxs("div",{className:"rounded-xl border border-sky-100 bg-sky-50 px-4 py-3 text-sm text-sky-900",children:["本次发现 ",b.found," 项,成功 ",b.success,",失败 ",b.failed,",跳过 ",b.skipped,"。",b.message||""]}),d&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm font-medium text-red-700",children:[e.jsx("span",{children:d}),m&&e.jsx("button",{type:"button",className:"font-bold underline",onClick:(()=>void A()),children:"重试"})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex w-full gap-3",children:[e.jsx("button",{type:"button",onClick:t,disabled:c||i!=="",className:"flex-1 rounded-xl bg-gray-100 px-6 py-3 font-bold text-gray-700 transition-colors hover:bg-gray-200 disabled:opacity-50",children:"关闭"}),e.jsxs("button",{type:"button",onClick:(()=>void h()),disabled:c||i!==""||a.auto_rate_enabled&&!a.rate_content.trim(),className:"ios-btn-primary flex flex-1 items-center justify-center gap-2 rounded-xl px-6 py-3 font-bold disabled:opacity-50",children:[c?e.jsx(J,{className:"h-4 w-4 animate-spin"}):e.jsx($e,{className:"h-4 w-4"}),"保存"]})]})})]})})},Qe=({src:s,alt:t,className:r=""})=>e.jsx("img",{src:s,alt:t,className:`block aspect-square h-auto w-full object-contain ${r}`.trim()}),Cs=({account:s,editForm:t,setEditForm:r,saving:a,onClose:l,onSave:c,onRestartPause:i,longLogin:d,onToggleLongLogin:b,passwordLoginView:m,onPasswordLogin:f,onCancelPasswordLogin:h,notifChannels:u,selectedChannelIds:A,bindingsLoaded:k,bindingsLoading:g,bindingsLoadError:p,onRetryBindings:L,onToggleChannel:U,onSettingsDirty:M})=>{const T=(C,W)=>{r(ee=>({...ee,[C]:W}))},S=()=>void l(),j=()=>void c(),v=C=>T("remark",C.target.value),R=C=>T("cookie",C.target.value),w=()=>T("auto_confirm",!t.auto_confirm),q=C=>T("pause_duration",parseInt(C.target.value,10)||0),D=()=>void i(),H=()=>void b(),K=C=>T("username",C.target.value),G=C=>r(W=>({...W,login_password:C.target.value,clear_password:!1})),V=()=>T("showLoginPassword",!t.showLoginPassword),O=C=>r(W=>({...W,clear_password:C.target.checked,login_password:C.target.checked?"":W.login_password})),I=()=>T("show_browser",!t.show_browser),z=()=>void h(),E=()=>void f(),Q=()=>void L(),F=C=>{k&&(U(C),M())},re=C=>{const W=A.includes(Number(C.id)),ee=()=>F(Number(C.id));return e.jsxs("label",{className:"flex items-center gap-3 p-3 rounded-xl border border-gray-200 hover:bg-gray-50 cursor-pointer transition-colors",children:[e.jsx("button",{type:"button",onClick:ee,disabled:!k,className:`w-5 h-5 rounded-md border-2 flex items-center justify-center transition-colors flex-shrink-0 ${W?"bg-brand border-brand":"bg-white border-gray-300"}`,children:W&&e.jsx(te,{className:"w-3.5 h-3.5 text-white"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:C.name}),e.jsxs("div",{className:"text-xs text-gray-500",children:[C.type,C.enabled?"":" · 已停用"]})]})]},C.id)};return ie.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"600px"},children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑账号"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:s.nickname||s.remark||s.id})]}),e.jsx("button",{onClick:S,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",children:e.jsx(de,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"账号ID"}),e.jsx("input",{type:"text",value:s.id,disabled:!0,className:"w-full ios-input px-4 py-3 rounded-xl bg-gray-50 text-gray-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注"}),e.jsx("input",{type:"text",value:t.remark,onChange:v,placeholder:"为账号添加备注",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"Cookie"}),e.jsx("textarea",{value:t.cookie,onChange:R,placeholder:"更新账号Cookie",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none font-mono text-xs"}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["当前Cookie长度: ",t.cookie.length," 字符"]})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-bold text-gray-900 flex items-center gap-2",children:[e.jsx(te,{className:"w-4 h-4 text-green-500"}),"自动确认发货"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"自动将闲鱼订单标记为已发货"})]}),e.jsx("button",{type:"button",onClick:w,className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${t.auto_confirm?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${t.auto_confirm?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2 flex items-center gap-2",children:[e.jsx(De,{className:"w-4 h-4 text-blue-500"}),"暂停处理时长(分钟)"]}),e.jsx("input",{type:"number",value:t.pause_duration,onChange:q,placeholder:"0",min:"0",max:"1440",className:"w-full ios-input px-4 py-3 rounded-xl"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"设置后会暂停处理该账号的订单,到时间后自动恢复"}),t.pause_duration>0&&!s.paused&&t.pause_duration===(s.pause_duration||0)&&e.jsx("button",{type:"button",disabled:a,onClick:D,className:"mt-3 px-4 py-2 rounded-xl bg-amber-50 text-amber-700 hover:bg-amber-100 text-sm font-bold disabled:opacity-50",children:"立即按当前时长重新暂停"})]}),e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsxs("h3",{className:"text-lg font-bold text-gray-900 mb-4 flex items-center gap-2",children:[e.jsx(We,{className:"w-5 h-5 text-blue-500"}),"登录信息"]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-xl bg-blue-50 p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900",children:"保存登录信息"}),e.jsx("div",{className:"mt-1 text-xs text-gray-500",children:"状态直接读取并修改闲鱼官方长登录设置"}),d.error&&e.jsx("div",{className:"mt-1 text-xs text-red-600",children:d.error})]}),e.jsx("button",{type:"button","aria-label":"保存登录信息",disabled:d.loading||d.saving||!d.canOpen,onClick:H,className:`relative h-8 w-14 flex-shrink-0 rounded-full transition-colors ${d.enabled?"bg-brand":"bg-gray-300"} disabled:cursor-not-allowed disabled:opacity-50`,children:e.jsx("span",{className:`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-md transition-transform ${d.enabled?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"用户名"}),e.jsx("input",{type:"text",value:t.username,onChange:K,placeholder:"闲鱼账号/手机号",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"登录密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:t.showLoginPassword?"text":"password",value:t.login_password,onChange:G,placeholder:"用于自动登录",className:"w-full ios-input px-4 py-3 rounded-xl pr-12"}),e.jsx("button",{type:"button",onClick:V,className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",children:t.showLoginPassword?e.jsx(Ve,{className:"w-5 h-5"}):e.jsx(Je,{className:"w-5 h-5"})})]}),e.jsxs("label",{className:"mt-3 flex items-center gap-3 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:t.clear_password,onChange:O,className:"w-4 h-4 accent-brand"}),e.jsx("span",{className:"text-sm font-bold text-gray-700",children:"清空已保存密码"})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900",children:"登录时显示浏览器"}),e.jsx("div",{className:"text-xs text-gray-500",children:"调试时可开启查看登录过程"})]}),e.jsx("button",{type:"button",onClick:I,className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${t.show_browser?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${t.show_browser?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{className:"rounded-xl border border-blue-100 bg-blue-50 p-4 space-y-3",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-blue-950",children:"立即执行账号密码登录"}),e.jsx("div",{className:"text-xs text-blue-700 mt-1",children:"需要在上方重新输入本次登录密码;成功后后端会更新 Cookie 和保存的登录信息。"})]}),m.status==="processing"||m.status==="verification_required"?e.jsx("button",{type:"button",onClick:z,className:"px-4 py-2 rounded-xl bg-white text-red-600 font-bold text-sm border border-red-100",children:"取消登录"}):e.jsx("button",{type:"button",onClick:E,className:"px-4 py-2 rounded-xl bg-blue-600 text-white font-bold text-sm whitespace-nowrap",children:"密码登录刷新授权"})]}),m.message&&e.jsx("div",{className:`text-sm font-medium ${m.status==="failed"?"text-red-700":m.status==="success"?"text-green-700":"text-blue-800"}`,children:m.message}),m.status==="verification_required"&&e.jsxs("div",{className:"rounded-xl border border-amber-200 bg-amber-50 p-3 text-amber-900",children:[e.jsx("div",{className:"font-extrabold",children:"账号已触发平台风控,需要完成人脸识别"}),e.jsx("div",{className:"text-xs mt-1 leading-5",children:"请在闲鱼 App 或已打开的登录浏览器中按提示完成验证。本页面不会提供可直接打开的风控链接。"}),m.qrCodeUrl&&e.jsx("div",{className:"mt-3 aspect-square w-48 overflow-hidden rounded-xl border bg-white",children:e.jsx(Qe,{src:m.qrCodeUrl,alt:"密码登录风控二维码",className:"p-2"})})]})]})]})]}),(u.length>0||g||p)&&e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsxs("h3",{className:"text-lg font-bold text-gray-900 mb-1 flex items-center gap-2",children:[e.jsx(Ke,{className:"w-5 h-5 text-blue-500"}),"通知渠道绑定"]}),e.jsx("p",{className:"text-xs text-gray-500 mb-4",children:"勾选后,该账号的 token 失效、自动恢复失败、风控验证等事件会推送到这些渠道"}),g&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500",children:[e.jsx(J,{className:"w-4 h-4 animate-spin"}),"正在加载通知绑定"]}),p&&!g&&e.jsxs("div",{className:"mb-3 rounded-xl bg-amber-50 p-3 text-sm text-amber-800 flex items-center justify-between gap-3",children:[e.jsx("span",{children:p}),e.jsx("button",{type:"button",className:"font-bold whitespace-nowrap",onClick:Q,children:"重试"})]}),e.jsx("div",{className:"space-y-2",children:u.map(re)})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:S,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:a,children:"取消"}),e.jsxs("button",{onClick:j,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:a,children:[a?e.jsx(J,{className:"w-4 h-4 animate-spin"}):e.jsx(te,{className:"w-4 h-4"}),a?"保存中...":"保存"]})]})})]})}),document.body)},Ss=({account:s,settings:t,saving:r,onChange:a,onClose:l,onSave:c})=>{const i=u=>a({...t,...u}),d=()=>i({ai_enabled:!t.ai_enabled}),b=u=>i({max_discount_percent:parseInt(u.target.value,10)||0}),m=u=>i({max_discount_amount:parseInt(u.target.value,10)||0}),f=u=>i({max_bargain_rounds:parseInt(u.target.value,10)||1}),h=u=>i({custom_prompts:u.target.value});return ie.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"600px"},children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-2xl font-extrabold text-gray-900 flex items-center gap-2",children:[e.jsx(ue,{className:"w-6 h-6 text-purple-500"}),"AI助手设置"]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:s.nickname||s.remark||s.id})]}),e.jsx("button",{onClick:l,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0","aria-label":"关闭 AI 设置",children:e.jsx(de,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 bg-purple-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-bold text-gray-900 flex items-center gap-2",children:[e.jsx(ue,{className:"w-4 h-4 text-purple-500"}),"启用AI自动回复"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"AI将自动处理买家的砍价消息"})]}),e.jsx("button",{type:"button",onClick:d,className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${t.ai_enabled?"bg-brand":"bg-gray-300"}`,"aria-label":"切换 AI 自动回复",children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${t.ai_enabled?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsx("h3",{className:"text-lg font-bold text-gray-900 mb-4",children:"砍价策略"}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大折扣比例 (%)"}),e.jsx("input",{type:"number",value:t.max_discount_percent,onChange:b,className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"100"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"例如:10 表示最多降价 10%;设为 0 表示不允许降价"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大折扣金额 (元)"}),e.jsx("input",{type:"number",value:t.max_discount_amount,onChange:m,className:"w-full ios-input px-4 py-3 rounded-xl",min:"0"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"例如:100 表示最多降价 100 元;设为 0 表示不允许降价"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大砍价轮次"}),e.jsx("input",{type:"number",value:t.max_bargain_rounds,onChange:f,className:"w-full ios-input px-4 py-3 rounded-xl",min:"1",max:"10"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"买家最多可以砍价的次数"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"自定义提示词(可选)"}),e.jsx("textarea",{value:t.custom_prompts,onChange:h,placeholder:`输入自定义的AI回复规则或风格指引... +import{r as n,j as e,b as ie,c as Oe}from"./react-vendor-C_od1ZSF.js";import{g as X,p as ae,a as ce,d as Pe}from"./index-hByDAHGj.js";import{c as Le,o as ke}from"./contract-COFcZjyb.js";import{X as de,n as ze,L as J,o as Ge,p as Ie,q as Te,r as $e,s as te,t as De,K as We,u as Ve,v as Je,e as Ke,w as ue,f as He,U as Ee,x as Xe,k as _e,Q as ve,R as Ye,y as Ze,z as Fe,F as Ne,H as es}from"./icons-vendor-CvzvbbIV.js";const ss=(s,t)=>{const r=s.avatar_url||"";if(!r)return"";try{const a=new URL(r,window.location.origin);return a.hostname.endsWith("alicdn.com")&&a.searchParams.set("_v",t),a.toString()}catch{return r}},ts=async s=>{const t=await X("/api/v1/accounts/details",void 0,s),r=Le(t,["data","accounts","details"]),a=Date.now().toString();return r.map(l=>({id:l.id,cookie_configured:l.has_cookie===!0,enabled:l.enabled,auto_confirm:l.auto_confirm,remark:l.remark,pause_duration:l.pause_duration,paused_until:Number(l.paused_until||0),paused:l.paused===!0,username:l.username||"",login_password_configured:void 0,show_browser:l.show_browser===!0||l.show_browser===1||l.show_browser==="1"||l.show_browser==="true",nickname:l.nickname||l.remark||`账号 ${l.id.substring(0,6)}`,avatar_url:ss(l,a),profile_error:l.profile_error||"",ai_enabled:!1,auto_rate_enabled:l.auto_rate_enabled,rate_content:l.rate_content||"不错的买家,交易愉快",auto_polish_enabled:l.auto_polish_enabled,polish_time:l.polish_time||"03:00",last_rate_scan_at:Number(l.last_rate_scan_at||0),last_polish_date:l.last_polish_date||"",last_polish_at:Number(l.last_polish_at||0)}))},as=async s=>{const t=await X("/api/v1/accounts/runtime-status",void 0,s);return ke(t,["statuses","data","result"])||{}},rs=async s=>ce("/api/v1/qr-login/generate",void 0,{...s,timeoutMs:(s==null?void 0:s.timeoutMs)??13e4}),ns=async(s,t)=>X(`/api/v1/qr-login/check/${s}`,void 0,{signal:t,timeoutMs:1e4}),ls=async(s,t)=>ce(`/api/v1/qr-login/complete-verification/${s}`,{target_account_id:t||""}),os=async(s,t)=>ae(`/api/v1/accounts/${s}/status`,{enabled:t}),is=async s=>Pe(`/api/v1/accounts/${s}`),cs=async(s,t,r)=>ae(`/api/v1/accounts/${s}/pause-duration`,{pause_duration:t},r),ds=async(s,t,r)=>ae(`/api/v1/accounts/${s}/settings`,t,r),us=async(s,t)=>X(`/api/v1/accounts/${s}/long-login`,void 0,t),xs=async(s,t,r)=>ae(`/api/v1/accounts/${s}/long-login`,{enabled:t},r),ms=async(s,t)=>ce("/api/v1/password-login",s,t),bs=async(s,t)=>X(`/api/v1/password-login/check/${s}`,void 0,{signal:t,timeoutMs:1e4}),hs=async(s,t)=>Pe(`/api/v1/password-login/cancel/${s}`,void 0,t),gs=async s=>ce(`/api/v1/accounts/${s}/refresh-profile`,{}),ps=async s=>{const t=await X("/api/v1/settings/ai-reply",void 0,s);return ke(t,["settings","data","result"])||{}},fs=async(s,t)=>X(`/api/v1/settings/ai-reply/${s}`,void 0,t),ys=async(s,t,r)=>{const a={ai_enabled:t.ai_enabled??!1,max_discount_percent:t.max_discount_percent??10,max_discount_amount:t.max_discount_amount??100,max_bargain_rounds:t.max_bargain_rounds??3,custom_prompts:t.custom_prompts??""};return ae(`/api/v1/settings/ai-reply/${s}`,a,r)},js=s=>{if(Array.isArray(s))return s.filter(Boolean);if(typeof s!="string"||!s.trim())return[];try{const t=JSON.parse(s);if(Array.isArray(t))return t.filter(Boolean)}catch{}return s.split(/[,\s;]+/).map(t=>t.trim()).filter(Boolean)},ws=async s=>{const t=await X("/api/v1/notifications/channels",void 0,s);return{success:!0,data:Le(t,["data","channels","items"]).map(a=>{let l;try{l=typeof a.config=="string"?JSON.parse(a.config):a.config}catch{l={}}const c=a.type==="ding_talk"?"dingtalk":a.type==="lark"?"feishu":a.type;return{id:String(a.id),name:a.name,type:c,config:l,event_types:js(a.event_types),enabled:a.enabled,created_at:a.created_at,updated_at:a.updated_at}})}},_s=async(s,t)=>{const r=await X(`/api/v1/notifications/accounts/${s}/bindings`,void 0,t),a=ke(r,["data","result"])||{};return Array.isArray(a.channel_ids)?a.channel_ids:[]},Ce=async(s,t)=>X(`/api/v1/account-tasks/${s}`,void 0,t),Se=async(s,t,r)=>ae(`/api/v1/account-tasks/${s}`,t,r),vs=async(s,t,r)=>ce(`/api/v1/account-tasks/${s}/run`,{task_type:t},{timeoutMs:12e4,...r}),Re=s=>({account_id:s.id,auto_rate_enabled:s.auto_rate_enabled===!0,rate_content:s.rate_content||"不错的买家,交易愉快",auto_polish_enabled:s.auto_polish_enabled===!0,polish_time:s.polish_time||"03:00",last_rate_scan_at:s.last_rate_scan_at,last_polish_date:s.last_polish_date,last_polish_at:s.last_polish_at}),Y=(s,t,r)=>s===t&&!r.aborted,je=(s,t)=>s instanceof Error?s.message:t,we=s=>s instanceof Error&&s.message==="请求已取消",Ae=(s,t)=>!s&&t==="",Ns=({account:s,onSaved:t})=>{const[r,a]=n.useState(()=>Re(s)),[l,c]=n.useState(!0),[i,d]=n.useState(!1),[b,m]=n.useState(""),[f,h]=n.useState(""),[u,A]=n.useState(null),[k,g]=n.useState(null),p=n.useRef(0),L=n.useRef(null);n.useEffect(()=>{var v;const S=++p.current;(v=L.current)==null||v.abort();const j=new AbortController;return L.current=j,a(Re(s)),A(null),h(""),d(!1),m(""),g(null),c(!0),Ce(s.id,{signal:j.signal}).then(R=>{Y(p.current,S,j.signal)&&a(R)}).catch(R=>{Y(p.current,S,j.signal)&&!we(R)&&h(je(R,"加载任务设置失败"))}).finally(()=>{Y(p.current,S,j.signal)&&c(!1)}),(()=>j.abort())},[s.id]),n.useEffect(()=>(()=>{var S;return(S=L.current)==null?void 0:S.abort()}),[]);const U=n.useCallback(async()=>{var v;if(!Ae(i,b))return;const S=++p.current;(v=L.current)==null||v.abort();const j=new AbortController;L.current=j,d(!0),h(""),g(null);try{const R=await Se(s.id,r,{signal:j.signal});if(!Y(p.current,S,j.signal))return;a(R),t(R)}catch(R){Y(p.current,S,j.signal)&&!we(R)&&(h(je(R,"保存失败")),g(()=>U))}finally{Y(p.current,S,j.signal)&&d(!1)}},[s.id,r,t,b,i]),M=n.useCallback(async S=>{var R;if(!Ae(i,b)||!s.enabled)return;const j=++p.current;(R=L.current)==null||R.abort();const v=new AbortController;L.current=v,m(S),h(""),A(null),g(null);try{await Se(s.id,r,{signal:v.signal});const w=await vs(s.id,S,{signal:v.signal}),q=await Ce(s.id,{signal:v.signal});if(!Y(p.current,j,v.signal))return;A(w.summary),a(q),t(q)}catch(w){Y(p.current,j,v.signal)&&!we(w)&&(h(je(w,"任务执行失败")),g(()=>(()=>M(S))))}finally{Y(p.current,j,v.signal)&&m("")}},[s.enabled,s.id,r,t,b,i]),T=n.useCallback(async()=>{k&&await k()},[k]);return{form:r,loading:l,saving:i,running:b,summary:u,error:f,retryAvailable:k!==null,setForm:a,save:U,run:M,retry:T}},qe=({checked:s,onChange:t,label:r})=>e.jsx("button",{type:"button","aria-label":r,"aria-pressed":s,onClick:t,className:`relative h-8 w-14 shrink-0 rounded-full transition-colors ${s?"bg-sky-500":"bg-slate-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-sm transition-transform ${s?"translate-x-6":""}`})}),ks=({account:s,onClose:t,onSaved:r})=>{const{form:a,loading:l,saving:c,running:i,error:d,summary:b,retryAvailable:m,setForm:f,save:h,run:u,retry:A}=Ns({account:s,onSaved:r});return e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"640px"},role:"dialog","aria-modal":"true","aria-labelledby":"account-task-title",children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("h3",{id:"account-task-title",className:"text-2xl font-extrabold text-slate-950",children:"账号自动任务"}),e.jsx("p",{className:"mt-1 text-sm text-slate-500",children:s.nickname||s.remark||s.id})]}),e.jsx("button",{type:"button",onClick:t,className:"rounded-xl p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700","aria-label":"关闭",children:e.jsx(de,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[l&&e.jsx("div",{className:"rounded-xl bg-slate-50 px-4 py-3 text-sm text-slate-500",children:"正在读取任务设置..."}),e.jsx("section",{className:"rounded-2xl border border-slate-200 bg-white p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-emerald-50 text-emerald-600",children:e.jsx(ze,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-black text-slate-900",children:"自动评价"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-slate-500",children:"持续扫描待评价订单,按订单执行;不是每日任务。"})]}),e.jsx(qe,{checked:a.auto_rate_enabled,onChange:(()=>f(k=>({...k,auto_rate_enabled:!k.auto_rate_enabled}))),label:"自动评价"})]}),e.jsx("label",{className:"mt-4 block text-xs font-extrabold text-slate-600",children:"统一好评文案"}),e.jsx("textarea",{"aria-label":"统一好评文案",value:a.rate_content,maxLength:500,onChange:(k=>f(g=>({...g,rate_content:k.target.value}))),className:"mt-2 h-24 w-full resize-none rounded-xl border border-slate-200 bg-slate-50 px-3 py-2.5 text-sm leading-6 text-slate-800 placeholder:text-slate-400 outline-none focus:border-sky-400 focus:ring-2 focus:ring-sky-100"}),e.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3",children:[e.jsxs("span",{className:"text-xs text-slate-400",children:["最近扫描:",a.last_rate_scan_at?new Date(a.last_rate_scan_at*1e3).toLocaleString("zh-CN"):"尚未执行"]}),e.jsxs("button",{type:"button",disabled:i!==""||!s.enabled,onClick:(()=>void u("auto_rate")),className:"flex items-center gap-2 rounded-xl bg-emerald-50 px-3 py-2 text-xs font-extrabold text-emerald-700 hover:bg-emerald-100 disabled:opacity-50",children:[i==="auto_rate"?e.jsx(J,{className:"h-4 w-4 animate-spin"}):e.jsx(Ge,{className:"h-4 w-4"}),"立即评价"]})]})]})]})}),e.jsx("section",{className:"rounded-2xl border border-slate-200 bg-white p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-amber-50 text-amber-600",children:e.jsx(Ie,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-black text-slate-900",children:"每日自动擦亮"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-slate-500",children:"每个账号每天最多执行一次,按北京时间判断。"})]}),e.jsx(qe,{checked:a.auto_polish_enabled,onChange:(()=>f(k=>({...k,auto_polish_enabled:!k.auto_polish_enabled}))),label:"每日自动擦亮"})]}),e.jsxs("div",{className:"mt-4 flex items-end justify-between gap-4",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-xs font-extrabold text-slate-600",children:"每日执行时间"}),e.jsx("input",{type:"time",value:a.polish_time,onChange:(k=>f(g=>({...g,polish_time:k.target.value}))),className:"mt-2 block rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm font-bold text-slate-800 outline-none focus:border-sky-400"})]}),e.jsxs("button",{type:"button",disabled:i!==""||!s.enabled,onClick:(()=>void u("auto_polish")),className:"flex items-center gap-2 rounded-xl bg-amber-50 px-3 py-2 text-xs font-extrabold text-amber-700 hover:bg-amber-100 disabled:opacity-50",children:[i==="auto_polish"?e.jsx(J,{className:"h-4 w-4 animate-spin"}):e.jsx(Te,{className:"h-4 w-4"}),"立即擦亮"]})]}),e.jsxs("div",{className:"mt-3 text-xs text-slate-400",children:["上次完成:",a.last_polish_at?new Date(a.last_polish_at*1e3).toLocaleString("zh-CN"):"尚未执行"]})]})]})}),b&&e.jsxs("div",{className:"rounded-xl border border-sky-100 bg-sky-50 px-4 py-3 text-sm text-sky-900",children:["本次发现 ",b.found," 项,成功 ",b.success,",失败 ",b.failed,",跳过 ",b.skipped,"。",b.message||""]}),d&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm font-medium text-red-700",children:[e.jsx("span",{children:d}),m&&e.jsx("button",{type:"button",className:"font-bold underline",onClick:(()=>void A()),children:"重试"})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex w-full gap-3",children:[e.jsx("button",{type:"button",onClick:t,disabled:c||i!=="",className:"flex-1 rounded-xl bg-gray-100 px-6 py-3 font-bold text-gray-700 transition-colors hover:bg-gray-200 disabled:opacity-50",children:"关闭"}),e.jsxs("button",{type:"button",onClick:(()=>void h()),disabled:c||i!==""||a.auto_rate_enabled&&!a.rate_content.trim(),className:"ios-btn-primary flex flex-1 items-center justify-center gap-2 rounded-xl px-6 py-3 font-bold disabled:opacity-50",children:[c?e.jsx(J,{className:"h-4 w-4 animate-spin"}):e.jsx($e,{className:"h-4 w-4"}),"保存"]})]})})]})})},Qe=({src:s,alt:t,className:r=""})=>e.jsx("img",{src:s,alt:t,className:`block aspect-square h-auto w-full object-contain ${r}`.trim()}),Cs=({account:s,editForm:t,setEditForm:r,saving:a,onClose:l,onSave:c,onRestartPause:i,longLogin:d,onToggleLongLogin:b,passwordLoginView:m,onPasswordLogin:f,onCancelPasswordLogin:h,notifChannels:u,selectedChannelIds:A,bindingsLoaded:k,bindingsLoading:g,bindingsLoadError:p,onRetryBindings:L,onToggleChannel:U,onSettingsDirty:M})=>{const T=(C,W)=>{r(ee=>({...ee,[C]:W}))},S=()=>void l(),j=()=>void c(),v=C=>T("remark",C.target.value),R=C=>T("cookie",C.target.value),w=()=>T("auto_confirm",!t.auto_confirm),q=C=>T("pause_duration",parseInt(C.target.value,10)||0),D=()=>void i(),H=()=>void b(),K=C=>T("username",C.target.value),G=C=>r(W=>({...W,login_password:C.target.value,clear_password:!1})),V=()=>T("showLoginPassword",!t.showLoginPassword),O=C=>r(W=>({...W,clear_password:C.target.checked,login_password:C.target.checked?"":W.login_password})),I=()=>T("show_browser",!t.show_browser),z=()=>void h(),E=()=>void f(),Q=()=>void L(),F=C=>{k&&(U(C),M())},re=C=>{const W=A.includes(Number(C.id)),ee=()=>F(Number(C.id));return e.jsxs("label",{className:"flex items-center gap-3 p-3 rounded-xl border border-gray-200 hover:bg-gray-50 cursor-pointer transition-colors",children:[e.jsx("button",{type:"button",onClick:ee,disabled:!k,className:`w-5 h-5 rounded-md border-2 flex items-center justify-center transition-colors flex-shrink-0 ${W?"bg-brand border-brand":"bg-white border-gray-300"}`,children:W&&e.jsx(te,{className:"w-3.5 h-3.5 text-white"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:C.name}),e.jsxs("div",{className:"text-xs text-gray-500",children:[C.type,C.enabled?"":" · 已停用"]})]})]},C.id)};return ie.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"600px"},children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑账号"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:s.nickname||s.remark||s.id})]}),e.jsx("button",{onClick:S,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",children:e.jsx(de,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"账号ID"}),e.jsx("input",{type:"text",value:s.id,disabled:!0,className:"w-full ios-input px-4 py-3 rounded-xl bg-gray-50 text-gray-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注"}),e.jsx("input",{type:"text",value:t.remark,onChange:v,placeholder:"为账号添加备注",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"Cookie"}),e.jsx("textarea",{value:t.cookie,onChange:R,placeholder:"更新账号Cookie",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none font-mono text-xs"}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["当前Cookie长度: ",t.cookie.length," 字符"]})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-bold text-gray-900 flex items-center gap-2",children:[e.jsx(te,{className:"w-4 h-4 text-green-500"}),"自动确认发货"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"自动将闲鱼订单标记为已发货"})]}),e.jsx("button",{type:"button",onClick:w,className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${t.auto_confirm?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${t.auto_confirm?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2 flex items-center gap-2",children:[e.jsx(De,{className:"w-4 h-4 text-blue-500"}),"暂停处理时长(分钟)"]}),e.jsx("input",{type:"number",value:t.pause_duration,onChange:q,placeholder:"0",min:"0",max:"1440",className:"w-full ios-input px-4 py-3 rounded-xl"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"设置后会暂停处理该账号的订单,到时间后自动恢复"}),t.pause_duration>0&&!s.paused&&t.pause_duration===(s.pause_duration||0)&&e.jsx("button",{type:"button",disabled:a,onClick:D,className:"mt-3 px-4 py-2 rounded-xl bg-amber-50 text-amber-700 hover:bg-amber-100 text-sm font-bold disabled:opacity-50",children:"立即按当前时长重新暂停"})]}),e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsxs("h3",{className:"text-lg font-bold text-gray-900 mb-4 flex items-center gap-2",children:[e.jsx(We,{className:"w-5 h-5 text-blue-500"}),"登录信息"]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-xl bg-blue-50 p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900",children:"保存登录信息"}),e.jsx("div",{className:"mt-1 text-xs text-gray-500",children:"状态直接读取并修改闲鱼官方长登录设置"}),d.error&&e.jsx("div",{className:"mt-1 text-xs text-red-600",children:d.error})]}),e.jsx("button",{type:"button","aria-label":"保存登录信息",disabled:d.loading||d.saving||!d.canOpen,onClick:H,className:`relative h-8 w-14 flex-shrink-0 rounded-full transition-colors ${d.enabled?"bg-brand":"bg-gray-300"} disabled:cursor-not-allowed disabled:opacity-50`,children:e.jsx("span",{className:`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-md transition-transform ${d.enabled?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"用户名"}),e.jsx("input",{type:"text",value:t.username,onChange:K,placeholder:"闲鱼账号/手机号",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"登录密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:t.showLoginPassword?"text":"password",value:t.login_password,onChange:G,placeholder:"用于自动登录",className:"w-full ios-input px-4 py-3 rounded-xl pr-12"}),e.jsx("button",{type:"button",onClick:V,className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",children:t.showLoginPassword?e.jsx(Ve,{className:"w-5 h-5"}):e.jsx(Je,{className:"w-5 h-5"})})]}),e.jsxs("label",{className:"mt-3 flex items-center gap-3 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:t.clear_password,onChange:O,className:"w-4 h-4 accent-brand"}),e.jsx("span",{className:"text-sm font-bold text-gray-700",children:"清空已保存密码"})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900",children:"登录时显示浏览器"}),e.jsx("div",{className:"text-xs text-gray-500",children:"调试时可开启查看登录过程"})]}),e.jsx("button",{type:"button",onClick:I,className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${t.show_browser?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${t.show_browser?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{className:"rounded-xl border border-blue-100 bg-blue-50 p-4 space-y-3",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-blue-950",children:"立即执行账号密码登录"}),e.jsx("div",{className:"text-xs text-blue-700 mt-1",children:"需要在上方重新输入本次登录密码;成功后后端会更新 Cookie 和保存的登录信息。"})]}),m.status==="processing"||m.status==="verification_required"?e.jsx("button",{type:"button",onClick:z,className:"px-4 py-2 rounded-xl bg-white text-red-600 font-bold text-sm border border-red-100",children:"取消登录"}):e.jsx("button",{type:"button",onClick:E,className:"px-4 py-2 rounded-xl bg-blue-600 text-white font-bold text-sm whitespace-nowrap",children:"密码登录刷新授权"})]}),m.message&&e.jsx("div",{className:`text-sm font-medium ${m.status==="failed"?"text-red-700":m.status==="success"?"text-green-700":"text-blue-800"}`,children:m.message}),m.status==="verification_required"&&e.jsxs("div",{className:"rounded-xl border border-amber-200 bg-amber-50 p-3 text-amber-900",children:[e.jsx("div",{className:"font-extrabold",children:"账号已触发平台风控,需要完成人脸识别"}),e.jsx("div",{className:"text-xs mt-1 leading-5",children:"请在闲鱼 App 或已打开的登录浏览器中按提示完成验证。本页面不会提供可直接打开的风控链接。"}),m.qrCodeUrl&&e.jsx("div",{className:"mt-3 aspect-square w-48 overflow-hidden rounded-xl border bg-white",children:e.jsx(Qe,{src:m.qrCodeUrl,alt:"密码登录风控二维码",className:"p-2"})})]})]})]})]}),(u.length>0||g||p)&&e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsxs("h3",{className:"text-lg font-bold text-gray-900 mb-1 flex items-center gap-2",children:[e.jsx(Ke,{className:"w-5 h-5 text-blue-500"}),"通知渠道绑定"]}),e.jsx("p",{className:"text-xs text-gray-500 mb-4",children:"勾选后,该账号的 token 失效、自动恢复失败、风控验证等事件会推送到这些渠道"}),g&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500",children:[e.jsx(J,{className:"w-4 h-4 animate-spin"}),"正在加载通知绑定"]}),p&&!g&&e.jsxs("div",{className:"mb-3 rounded-xl bg-amber-50 p-3 text-sm text-amber-800 flex items-center justify-between gap-3",children:[e.jsx("span",{children:p}),e.jsx("button",{type:"button",className:"font-bold whitespace-nowrap",onClick:Q,children:"重试"})]}),e.jsx("div",{className:"space-y-2",children:u.map(re)})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:S,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:a,children:"取消"}),e.jsxs("button",{onClick:j,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:a,children:[a?e.jsx(J,{className:"w-4 h-4 animate-spin"}):e.jsx(te,{className:"w-4 h-4"}),a?"保存中...":"保存"]})]})})]})}),document.body)},Ss=({account:s,settings:t,saving:r,onChange:a,onClose:l,onSave:c})=>{const i=u=>a({...t,...u}),d=()=>i({ai_enabled:!t.ai_enabled}),b=u=>i({max_discount_percent:parseInt(u.target.value,10)||0}),m=u=>i({max_discount_amount:parseInt(u.target.value,10)||0}),f=u=>i({max_bargain_rounds:parseInt(u.target.value,10)||1}),h=u=>i({custom_prompts:u.target.value});return ie.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"600px"},children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-2xl font-extrabold text-gray-900 flex items-center gap-2",children:[e.jsx(ue,{className:"w-6 h-6 text-purple-500"}),"AI助手设置"]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:s.nickname||s.remark||s.id})]}),e.jsx("button",{onClick:l,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0","aria-label":"关闭 AI 设置",children:e.jsx(de,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 bg-purple-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-bold text-gray-900 flex items-center gap-2",children:[e.jsx(ue,{className:"w-4 h-4 text-purple-500"}),"启用AI自动回复"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"AI将自动处理买家的砍价消息"})]}),e.jsx("button",{type:"button",onClick:d,className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${t.ai_enabled?"bg-brand":"bg-gray-300"}`,"aria-label":"切换 AI 自动回复",children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${t.ai_enabled?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsx("h3",{className:"text-lg font-bold text-gray-900 mb-4",children:"砍价策略"}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大折扣比例 (%)"}),e.jsx("input",{type:"number",value:t.max_discount_percent,onChange:b,className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"100"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"例如:10 表示最多降价 10%;设为 0 表示不允许降价"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大折扣金额 (元)"}),e.jsx("input",{type:"number",value:t.max_discount_amount,onChange:m,className:"w-full ios-input px-4 py-3 rounded-xl",min:"0"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"例如:100 表示最多降价 100 元;设为 0 表示不允许降价"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大砍价轮次"}),e.jsx("input",{type:"number",value:t.max_bargain_rounds,onChange:f,className:"w-full ios-input px-4 py-3 rounded-xl",min:"1",max:"10"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"买家最多可以砍价的次数"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"自定义提示词(可选)"}),e.jsx("textarea",{value:t.custom_prompts,onChange:h,placeholder:`输入自定义的AI回复规则或风格指引... 例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,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(He,{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:l,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:r,children:"取消"}),e.jsxs("button",{onClick:(()=>void c()),className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:r,children:[r?e.jsx(J,{className:"w-4 h-4 animate-spin"}):e.jsx($e,{className:"w-4 h-4"}),r?"保存中...":"保存"]})]})})]})}),document.body)},Rs=(s,t)=>{if(!s||!t)return!1;const r=Date.parse(s),a=Date.parse(t);return Number.isFinite(r)&&Number.isFinite(a)&&as.map(r=>{const a=t[r.id];return!a||Rs(r.runtime_updated_at,a.updated_at)?r:{...r,runtime_state:a.state,runtime_message:a.message||"",runtime_connected:a.connected,runtime_updated_at:a.updated_at}}),qs=s=>{if(!s.enabled||s.runtime_state==="disabled")return{label:"已停用",badge:"bg-gray-100 text-gray-500",dot:"bg-gray-300"};switch(s.runtime_state){case"online":return{label:"在线",badge:"bg-green-100 text-green-700",dot:"bg-green-500"};case"starting":case"connecting":return{label:"连接中",badge:"bg-blue-100 text-blue-700",dot:"bg-blue-500"};case"reconnecting":return{label:"重连中",badge:"bg-amber-100 text-amber-700",dot:"bg-amber-500"};case"auth_expired":return{label:"登录已失效",badge:"bg-red-100 text-red-700",dot:"bg-red-500"};case"verification_required":return{label:"需要验证",badge:"bg-orange-100 text-orange-700",dot:"bg-orange-500"};case"error":case"stopped":return{label:"运行异常",badge:"bg-red-100 text-red-700",dot:"bg-red-500"};default:return{label:"状态检测中",badge:"bg-gray-100 text-gray-600",dot:"bg-gray-400"}}},Ps=Oe.memo(function({account:t,refreshing:r,deleting:a,onRefreshProfile:l,onReauthorize:c,onEdit:i,onAI:d,onTasks:b,onToggle:m,onDelete:f}){const h=qs(t),u=t.runtime_state==="auth_expired"||t.runtime_state==="verification_required";return e.jsx("div",{className:"ios-card rounded-xl p-6 group transition-all duration-300 hover:border-brand",children:e.jsxs("div",{className:"flex min-w-0 items-start gap-5 sm:gap-8",children:[e.jsxs("div",{className:"relative",children:[t.avatar_url?e.jsx("img",{src:t.avatar_url,alt:t.nickname||"账号头像",className:"w-20 h-20 rounded-full object-cover shadow-md ring-4 ring-white bg-gray-100"}):e.jsx("div",{className:"w-20 h-20 rounded-full bg-gray-100 text-gray-400 shadow-md ring-4 ring-white flex items-center justify-center",children:e.jsx(Ee,{className:"w-9 h-9"})}),e.jsx("div",{className:`absolute -bottom-1 -right-1 w-6 h-6 rounded-full border-4 border-white flex items-center justify-center ${h.dot}`,children:t.runtime_state==="online"&&e.jsx(te,{className:"w-3 h-3 text-white"})})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2.5 mb-1",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900 break-words",children:t.nickname||t.remark||`账号 ${t.id.substring(0,6)}...`}),e.jsx("span",{className:`px-2.5 py-0.5 rounded-lg text-xs font-bold ${h.badge}`,children:h.label}),t.ai_enabled&&e.jsxs("span",{className:"px-2.5 py-0.5 rounded-lg bg-purple-100 text-purple-700 text-xs font-bold flex items-center gap-1",children:[e.jsx(ue,{className:"w-3 h-3"})," AI"]}),t.auto_rate_enabled&&e.jsxs("span",{className:"flex items-center gap-1 rounded-lg bg-emerald-100 px-2.5 py-0.5 text-xs font-bold text-emerald-700",children:[e.jsx(Xe,{className:"h-3 w-3"})," 自动评价"]}),t.auto_polish_enabled&&e.jsxs("span",{className:"flex items-center gap-1 rounded-lg bg-amber-100 px-2.5 py-0.5 text-xs font-bold text-amber-700",children:[e.jsx(Ie,{className:"h-3 w-3"})," 每日擦亮"]}),t.auto_confirm&&e.jsxs("span",{className:"flex items-center gap-1 rounded-lg bg-blue-50 px-2.5 py-0.5 text-xs font-bold text-blue-700",children:[e.jsx(te,{className:"h-3 w-3"})," 自动确认发货"]}),t.profile_error&&e.jsxs("span",{className:"px-2.5 py-0.5 rounded-lg bg-amber-100 text-amber-700 text-xs font-bold flex items-center gap-1",title:t.profile_error,children:[e.jsx(_e,{className:"w-3 h-3"})," 资料未同步"]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-4",children:[e.jsxs("div",{className:"text-sm font-medium text-gray-500",children:[e.jsx("p",{children:t.remark||"暂无备注"}),e.jsxs("p",{className:"font-mono text-xs text-gray-400",children:["ID: ",t.id]})]}),t.runtime_message&&t.runtime_state!=="online"&&t.runtime_state!=="disabled"&&e.jsxs("div",{className:`mb-3 flex flex-wrap items-center gap-2 text-sm font-medium ${u?"text-red-700":"text-amber-700"}`,children:[e.jsx(_e,{className:"w-4 h-4 flex-shrink-0"}),e.jsx("span",{children:t.runtime_message}),u&&e.jsxs("button",{type:"button",onClick:(()=>c(t)),className:"inline-flex items-center gap-1.5 rounded-lg bg-red-50 px-2.5 py-1 text-xs font-bold text-red-700 hover:bg-red-100",children:[e.jsx(ve,{className:"w-3.5 h-3.5"})," 重新授权"]})]}),t.paused&&e.jsxs("span",{className:"flex items-center gap-1.5 rounded-lg bg-blue-50 px-3 py-1.5 text-xs font-bold text-blue-700",children:[e.jsx(De,{className:"h-3 w-3"})," 暂停处理中"]}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-end gap-2",children:[e.jsx("button",{onClick:(()=>l(t)),disabled:r,className:"p-3 rounded-xl transition-colors text-gray-600 hover:bg-gray-100 disabled:opacity-50",title:"刷新昵称和头像",children:e.jsx(Ye,{className:`w-5 h-5 ${r?"animate-spin":""}`})}),e.jsx("button",{onClick:(()=>c(t)),className:`p-3 rounded-xl transition-colors ${u?"text-red-600 bg-red-50 hover:bg-red-100":"text-blue-600 hover:bg-blue-50"}`,title:"重新扫码授权当前账号",children:e.jsx(ve,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>i(t)),className:"p-3 rounded-xl hover:bg-gray-100 transition-colors text-gray-600",title:"编辑账号",children:e.jsx(Ze,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>d(t)),className:"p-3 rounded-xl hover:bg-purple-100 transition-colors text-purple-600",title:"AI设置",children:e.jsx(ue,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>b(t)),className:"p-3 rounded-xl hover:bg-amber-100 transition-colors text-amber-600",title:"自动评价与每日擦亮",children:e.jsx(Te,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>m(t.id,t.enabled)),className:`p-3 rounded-xl transition-colors ${t.enabled?"text-green-600 hover:bg-green-50":"text-gray-400 hover:bg-gray-100"}`,title:t.enabled?"停用账号":"启用账号",children:e.jsx(Fe,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>f(t)),disabled:a,className:"p-3 rounded-xl hover:bg-red-100 transition-colors text-red-500 disabled:cursor-not-allowed disabled:opacity-40",title:a?"删除中…":`删除账号 ${t.nickname||t.remark||t.id}`,children:a?e.jsx(J,{className:"w-5 h-5 animate-spin"}):e.jsx(Ne,{className:"w-5 h-5"})})]})]})]})]})})}),Ls=({account:s,deleting:t,error:r,onClose:a,onConfirm:l})=>ie.createPortal(e.jsx("div",{className:"modal-overlay-centered",role:"presentation",children:e.jsxs("div",{className:"h-fit w-full max-w-[400px] self-center overflow-hidden rounded-2xl border border-white/80 bg-white shadow-modal",role:"dialog","aria-modal":"true","aria-labelledby":"delete-account-title","aria-describedby":"delete-account-description",children:[e.jsxs("div",{className:"relative overflow-hidden border-b border-red-100 bg-gradient-to-br from-red-50 via-white to-orange-50 px-5 py-5",children:[e.jsx("div",{className:"absolute -right-12 -top-16 h-36 w-36 rounded-full bg-red-200/35 blur-2xl"}),e.jsxs("div",{className:"relative flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl bg-red-600 text-white shadow-md shadow-red-200",children:e.jsx(Ne,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{id:"delete-account-title",className:"text-lg font-extrabold tracking-tight text-gray-950",children:"删除这个账号?"}),e.jsx("p",{id:"delete-account-description",className:"mt-1 text-xs leading-5 text-gray-600",children:"删除后,该账号的关联配置也会一并清理,此操作无法撤销。"})]}),e.jsx("button",{type:"button",onClick:a,disabled:t,className:"flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-full text-gray-400 transition-colors hover:bg-white hover:text-gray-700 disabled:cursor-not-allowed disabled:opacity-40","aria-label":"关闭删除确认",children:e.jsx(de,{className:"h-5 w-5"})})]})]}),e.jsxs("div",{className:"px-5 py-4",children:[e.jsxs("div",{className:"rounded-xl border border-gray-100 bg-gray-50/80 px-4 py-3",children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:s.nickname||s.remark||"未命名账号"}),s.remark&&s.nickname&&e.jsxs("div",{className:"mt-1 text-sm text-gray-500",children:["备注:",s.remark]}),e.jsxs("div",{className:"mt-1.5 break-all font-mono text-[11px] text-gray-400",children:["ID: ",s.id]})]}),t&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 rounded-xl border border-blue-100 bg-blue-50 px-4 py-3",role:"progressbar","aria-label":"正在删除账号",children:[e.jsx(J,{className:"h-5 w-5 flex-shrink-0 animate-spin text-brand"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-blue-950",children:"正在删除账号"}),e.jsx("div",{className:"mt-0.5 text-xs text-blue-700",children:"正在清理关联数据,请保持页面打开…"})]})]}),r&&e.jsxs("div",{className:"mt-4 flex items-start gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3",role:"alert",children:[e.jsx(_e,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-red-600"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-red-800",children:"删除失败"}),e.jsx("div",{className:"mt-1 text-xs leading-5 text-red-700",children:r})]})]})]}),e.jsxs("div",{className:"flex gap-3 border-t border-gray-100 bg-gray-50/70 px-5 py-4",children:[e.jsx("button",{type:"button",onClick:a,disabled:t,className:"flex-1 rounded-xl bg-white px-5 py-3 text-sm font-extrabold text-gray-700 ring-1 ring-gray-200 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-50",children:"取消"}),e.jsx("button",{type:"button",onClick:(()=>void l()),disabled:t,className:"flex flex-1 items-center justify-center gap-2 rounded-xl bg-red-600 px-5 py-3 text-sm font-extrabold text-white shadow-lg shadow-red-200 transition-colors hover:bg-red-700 disabled:cursor-not-allowed disabled:bg-red-400",children:t?e.jsxs(e.Fragment,{children:[e.jsx(J,{className:"h-4 w-4 animate-spin"}),"处理中"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ne,{className:"h-4 w-4"}),"确认删除"]})})]})]})}),document.body),Is=({faceQrUrl:s,verificationScreenshot:t})=>e.jsxs("div",{className:"w-full min-w-0 max-h-[min(64vh,28rem)] overflow-y-auto overscroll-contain px-1 py-2 text-center",children:[e.jsx("div",{className:"mx-auto mb-2 flex h-10 w-10 items-center justify-center rounded-full bg-amber-100 text-amber-700",children:e.jsx(es,{className:"h-5 w-5","aria-hidden":"true"})}),e.jsx("h4",{className:"break-words text-base font-extrabold leading-6 text-amber-900",children:"需要完成安全风控验证"}),e.jsx("p",{className:"mx-auto mt-1 max-w-[15rem] break-words text-xs leading-5 text-amber-800",children:"当前账号触发了闲鱼平台风控。请使用手机闲鱼 App 扫描下方二维码,并按 App 提示完成人脸识别。"}),e.jsx("div",{className:"mx-auto mt-3 flex min-h-36 w-full max-w-[12rem] items-center justify-center overflow-hidden rounded-xl border border-amber-200 bg-white p-2 shadow-sm",children:s?e.jsx("img",{src:s,alt:"闲鱼安全风控验证二维码",className:"block max-h-44 w-full object-contain"}):t?e.jsx("img",{src:t,alt:"闲鱼风控验证页面",className:"block max-h-44 w-full object-contain"}):e.jsxs("div",{className:"flex flex-col items-center gap-2 text-amber-700",children:[e.jsx(J,{className:"h-6 w-6 animate-spin","aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-bold",children:"正在准备风控二维码…"})]})}),e.jsx("p",{className:"mx-auto mt-2 max-w-[15rem] break-words text-[11px] leading-4 text-gray-500",children:"请勿在浏览器中打开验证链接。完成验证后系统会自动检测并刷新登录状态,无需手动确认。"})]}),Ts=({target:s,status:t,codeUrl:r,errorMessage:a,faceQrUrl:l,verificationScreenshot:c,onClose:i})=>ie.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container relative",style:{maxWidth:"26rem"},children:[e.jsx("button",{onClick:i,className:"absolute top-4 right-4 z-10 w-9 h-9 flex items-center justify-center bg-gray-100 hover:bg-gray-200 rounded-full transition-colors","aria-label":"关闭二维码登录",children:e.jsx(de,{className:"w-5 h-5 text-gray-600"})}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900 mb-2",children:s?"重新授权账号":"扫码添加账号"}),e.jsx("p",{className:"text-gray-500 mb-8 font-medium",children:s?`请用闲鱼APP扫码,为「${s.nickname||s.remark||s.id}」刷新授权`:"请打开闲鱼APP扫描下方二维码"}),e.jsxs("div",{className:`w-full bg-surface-subtle rounded-xl mx-auto flex items-center justify-center overflow-hidden border-4 border-white shadow-inner mb-6 relative ${t==="verification"?"max-w-72 min-h-64 h-auto p-2":"max-w-64 aspect-square"}`,children:[t==="loading"&&e.jsx(J,{className:"w-10 h-10 text-brand animate-spin"}),t==="waiting"&&e.jsx(Qe,{src:r,alt:"闲鱼登录二维码",className:"p-2"}),t==="success"&&e.jsxs("div",{className:"absolute inset-0 bg-white/95 flex flex-col items-center justify-center text-green-600 animate-fade-in",children:[e.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mb-4",children:e.jsx(te,{className:"w-8 h-8"})}),e.jsx("span",{className:"font-bold text-lg",children:"登录成功"})]}),t==="error"&&e.jsxs("div",{className:"px-5 text-center",children:[e.jsx("span",{className:"block text-red-600 font-bold",children:"二维码获取失败"}),e.jsx("span",{className:"mt-2 block text-xs leading-5 text-gray-500",children:a||"请关闭窗口后重新发起扫码登录。"})]}),t==="verification"&&e.jsx(Is,{faceQrUrl:l,verificationScreenshot:c})]}),t!=="verification"&&e.jsx("p",{className:"text-xs text-gray-400 font-medium bg-gray-50 py-2 rounded-xl",children:"二维码有效期为5分钟,请尽快扫码。"})]})})]})}),document.body),$s=(s,t)=>s.map(r=>{var a,l,c,i,d;return{...r,ai_enabled:((a=t[r.id])==null?void 0:a.ai_enabled)??!1,max_discount_percent:((l=t[r.id])==null?void 0:l.max_discount_percent)??10,max_discount_amount:((c=t[r.id])==null?void 0:c.max_discount_amount)??100,max_bargain_rounds:((i=t[r.id])==null?void 0:i.max_bargain_rounds)??3,custom_prompts:((d=t[r.id])==null?void 0:d.custom_prompts)??""}}),Ds=()=>{const[s,t]=n.useState([]),[r,a]=n.useState(!0),l=n.useRef(0),c=n.useRef(null),i=n.useCallback(async()=>{var m;const d=++l.current;(m=c.current)==null||m.abort();const b=new AbortController;c.current=b,a(!0);try{const f={signal:b.signal},[h,u]=await Promise.allSettled([ts(f),ps(f)]);if(d!==l.current)return;if(h.status==="rejected")throw h.reason;const A=u.status==="fulfilled"?u.value:{};u.status==="rejected"&&console.error("加载 AI 设置失败:",u.reason),t($s(h.value,A))}catch(f){d===l.current&&!b.signal.aborted&&console.error("加载账号失败:",f)}finally{d===l.current&&a(!1)}},[]);return n.useEffect(()=>{let d=!1,b=null;const m=new AbortController,f=async()=>{try{const u=await as({signal:m.signal,timeoutMs:1e4});d||t(A=>As(A,u))}catch(u){d||console.error("加载账号运行状态失败:",u)}finally{d||(b=window.setTimeout(()=>void f(),2e3))}};return i().finally(()=>{d||f()}),()=>{var u;d=!0,m.abort(),l.current+=1,(u=c.current)==null||u.abort(),b!==null&&window.clearTimeout(b)}},[i]),{accounts:s,setAccounts:t,loading:r,loadAccounts:i}},Es=new Set(["expired","cancelled","error","not_found"]),Qs=()=>{let s=0;return{next:()=>(s+=1,s),cancel:()=>{s+=1},isCurrent:(t=>t===s)}},Us=(s={setInterval:globalThis.setInterval.bind(globalThis),clearInterval:globalThis.clearInterval.bind(globalThis)})=>{let t=null,r=null,a=-1,l=0;const c=()=>{l+=1,r==null||r.abort(),r=null,t!==null&&(s.clearInterval(t),t=null)};return{start:(d,b,m,f=2e3)=>{c();const h=l;r=new AbortController;const u=r.signal;t=s.setInterval(()=>{a===h||h!==l||(a=h,(async()=>{var A,k;try{const g=await b(d,u);if(g.status==="success"){c(),await m.onSuccess(g);return}if(g.status==="scanned"){(A=m.onScanned)==null||A.call(m,g);return}if(g.status==="verification_required"){(k=m.onVerificationRequired)==null||k.call(m,g);return}g.status&&Es.has(g.status)&&(c(),m.onTerminalError(g))}catch(g){if(u.aborted||h!==l)return;c(),m.onPollError(g)}finally{a===h&&(a=-1)}})())},f)},stop:c,isActive:(()=>t!==null)}},Ms=({onLoginSuccess:s})=>{const[t,r]=n.useState(!1),[a,l]=n.useState(""),[c,i]=n.useState("pending"),[d,b]=n.useState(""),[m,f]=n.useState(""),[h,u]=n.useState(""),[A,k]=n.useState(null),g=n.useRef(null),p=n.useRef(null),L=n.useRef(null),U=n.useRef(null);g.current===null&&(g.current=Us()),p.current===null&&(p.current=Qs());const M=()=>{U.current!==null&&(window.clearTimeout(U.current),U.current=null)},T=()=>{var w;(w=g.current)==null||w.stop()},S=()=>{var w,q;(w=L.current)==null||w.abort(),(q=p.current)==null||q.cancel(),T(),M(),r(!1)},j=()=>{M(),U.current=window.setTimeout(()=>{U.current=null,r(!1),s()},1e3)};n.useEffect(()=>()=>{var q,D;T(),(q=p.current)==null||q.cancel(),(D=L.current)==null||D.abort(),M()},[]);const v=async(w,q)=>{const D=await ls(w,q==null?void 0:q.id);if(!D.success||!D.account_id)throw new Error(D.message||"保存扫码授权失败");return D.account_id};return{showQRModal:t,qrCodeUrl:a,qrStatus:c,qrErrorMessage:d,verificationScreenshot:m,faceQrUrl:h,qrReauthTarget:A,startQRLogin:async w=>{var K,G,V,O;T(),(K=L.current)==null||K.abort();const q=new AbortController;L.current=q;const D=p.current.next();M();const H=w||null;k(H),r(!0),i("loading"),b(""),l(""),f(""),u("");try{const I=await rs({signal:q.signal});if(!((G=p.current)!=null&&G.isCurrent(D)))return;if(!I.success||!I.qr_code_url||!I.session_id)throw new Error(I.message||"闲鱼未返回可用的登录二维码");const z=I.session_id;l(I.qr_code_url),i("waiting"),(V=g.current)==null||V.start(z,ns,{onSuccess:(async()=>{try{await v(z,H)}catch(E){console.error("保存扫码授权失败",E),i("error");return}i("success"),j()}),onScanned:(()=>{i("waiting")}),onTerminalError:(()=>{i("error")}),onPollError:(E=>{console.error("轮询扫码状态失败",E),i("error")}),onVerificationRequired:(E=>{i("verification"),E.face_qr_url&&u(E.face_qr_url),E.verification_screenshot&&f(E.verification_screenshot)})})}catch(I){if(!((O=p.current)!=null&&O.isCurrent(D))||q.signal.aborted)return;b(I instanceof Error?I.message:"二维码获取失败,请稍后重试"),i("error")}finally{L.current===q&&(L.current=null)}},closeQRModal:S}},Bs=(s,t)=>s!==(t.pause_duration||0),Os=(s,t)=>{const r=t.username!==(s.username||""),a=t.show_browser!==(s.show_browser||!1),l=t.login_password!=="",c=t.clear_password===!0;if(!r&&!a&&!l&&!c)return null;const i={username:t.username,show_browser:t.show_browser};return c?i.clear_password=!0:l&&(i.login_password=t.login_password),i},Z=(s,t,r,a)=>s===t&&r===a,zs=s=>s.status==="success"?{sessionId:"",status:"success",message:s.message||"账号密码登录成功,授权信息已更新",qrCodeUrl:""}:s.status==="processing"||s.status==="verification_required"?{sessionId:"",status:s.status,message:s.message||(s.status==="verification_required"?"账号触发风控,需要完成人脸识别":"登录处理中"),qrCodeUrl:s.qr_code_url||""}:{sessionId:"",status:"failed",message:s.error||s.message||"密码登录失败,请检查账号信息后重试",qrCodeUrl:""},Gs=(s,t)=>s&&t,Ws=({editingAccount:s,setEditingAccount:t,setActiveModal:r,editForm:a,setEditForm:l,loadAccounts:c})=>{const[i,d]=n.useState({loading:!1,saving:!1,canOpen:!1,enabled:!1,error:""}),[b,m]=n.useState([]),[f,h]=n.useState([]),[u,A]=n.useState(!1),[k,g]=n.useState(!1),[p,L]=n.useState(!1),[U,M]=n.useState(""),[T,S]=n.useState({ai_enabled:!1,max_discount_percent:10,max_discount_amount:100,max_bargain_rounds:3,custom_prompts:""}),[j,v]=n.useState(!1),[R,w]=n.useState({sessionId:"",status:"idle",message:"",qrCodeUrl:""}),q=n.useRef(0),D=n.useRef(null),H=n.useRef(0),K=n.useRef(null),G=n.useRef(0),V=n.useRef(null),O=n.useRef(0),I=n.useRef(""),z=n.useRef(null),E=n.useRef(null),Q=n.useCallback(()=>{E.current!==null&&(window.clearTimeout(E.current),E.current=null)},[]),F=n.useCallback(async o=>{var B;const x=++q.current;(B=D.current)==null||B.abort();const N=new AbortController;D.current=N,g(!0),A(!1),L(!1),M("");const[$,_]=await Promise.allSettled([ws({signal:N.signal}),_s(o,{signal:N.signal})]);Z(x,q.current,o,o)&&($.status==="fulfilled"?m($.value.data||[]):(m([]),M("通知渠道列表加载失败,请重试")),_.status==="fulfilled"?(h(_.value||[]),A(!0)):(h([]),M("通知绑定加载失败;本次保存不会修改现有绑定")),g(!1))},[]),re=n.useCallback(o=>{h(x=>x.includes(o)?x.filter(N=>N!==o):[...x,o]),L(!0)},[]),C=n.useCallback(async o=>{var _,B;const x=++H.current;(_=K.current)==null||_.abort();const N=new AbortController;K.current=N,O.current+=1,I.current=o.id,(B=z.current)==null||B.abort(),Q(),w({sessionId:"",status:"idle",message:"",qrCodeUrl:""}),t(o),l({remark:o.remark||"",cookie:"",auto_confirm:o.auto_confirm||!1,pause_duration:o.pause_duration||0,username:o.username||"",login_password:"",show_browser:o.show_browser||!1,showLoginPassword:!1,clear_password:!1}),r("edit"),d({loading:!0,saving:!1,canOpen:!1,enabled:!1,error:""});const[,$]=await Promise.allSettled([F(o.id),us(o.id,{signal:N.signal})]);x===H.current&&($.status==="fulfilled"?d({loading:!1,saving:!1,canOpen:$.value.can_open_long_login,enabled:$.value.enabled,error:""}):d({loading:!1,saving:!1,canOpen:!1,enabled:!1,error:"无法读取闲鱼保存登录信息状态"}))},[Q,F,r,l,t]),W=n.useCallback(async()=>{if(!s||i.loading||i.saving||!i.canOpen)return;const o=!i.enabled;d(x=>({...x,saving:!0,error:""}));try{const x=await xs(s.id,o);d({loading:!1,saving:!1,canOpen:x.can_open_long_login,enabled:x.enabled,error:""})}catch(x){d(N=>({...N,saving:!1,error:x instanceof Error?x.message:"保存登录信息设置失败"}))}},[s,i]),ee=n.useCallback(async o=>{var $;const x=++G.current;($=V.current)==null||$.abort();const N=new AbortController;V.current=N,t(o),r("ai-settings"),v(!0);try{const _=await fs(o.id,{signal:N.signal});if(!Z(x,G.current,o.id,o.id))return;S({ai_enabled:_.ai_enabled??!1,max_discount_percent:_.max_discount_percent??10,max_discount_amount:_.max_discount_amount??100,max_bargain_rounds:_.max_bargain_rounds??3,custom_prompts:_.custom_prompts??""})}catch(_){Z(x,G.current,o.id,o.id)&&console.error("加载 AI 设置失败:",_)}finally{Z(x,G.current,o.id,o.id)&&v(!1)}},[r,t]),xe=n.useCallback(async()=>{if(!(!s||j)){v(!0);try{await ys(s.id,T),r(null),await c()}catch(o){console.error("更新 AI 设置失败:",o)}finally{v(!1)}}},[T,s,c,j,r]),me=n.useCallback(async()=>{if(!(!s||j)){v(!0);try{const o={};a.remark!==(s.remark||"")&&(o.remark=a.remark),a.cookie&&(o.cookie=a.cookie),a.auto_confirm!==s.auto_confirm&&(o.auto_confirm=a.auto_confirm),Bs(a.pause_duration,s)&&(o.pause_duration=a.pause_duration);const x=Os(s,a);x&&Object.assign(o,x),Gs(u,p)&&(o.channel_ids=f),Object.keys(o).length>0&&await ds(s.id,o),r(null),await c()}catch(o){console.error("更新账号失败:",o)}finally{v(!1)}}},[p,u,a,s,c,f,j,r]),be=n.useCallback(async()=>{if(!(!s||a.pause_duration<=0||j)){v(!0);try{const o=await cs(s.id,a.pause_duration);t(x=>x&&{...x,pause_duration:a.pause_duration,paused:(o==null?void 0:o.paused)===!0,paused_until:Number((o==null?void 0:o.paused_until)||0)}),await c()}catch(o){console.error("重新暂停失败:",o)}finally{v(!1)}}},[a.pause_duration,s,c,j,t]),ne=n.useCallback(async(o,x,N)=>{var _;(_=z.current)==null||_.abort();const $=new AbortController;z.current=$;try{const B=await bs(o,$.signal);if(!Z(x,O.current,N,I.current))return;const oe={...zs(B),sessionId:o};if(B.status==="success"){Q(),w(oe),l(fe=>({...fe,login_password:"",showLoginPassword:!1})),await c();return}if(B.status==="processing"||B.status==="verification_required"){w(oe),Q(),E.current=window.setTimeout(()=>void ne(o,x,N),1500);return}Q(),w(oe)}catch(B){if(!Z(x,O.current,N,I.current))return;Q(),w({sessionId:o,status:"failed",message:B instanceof Error?B.message:"查询密码登录状态失败",qrCodeUrl:""})}},[Q,c,l]),he=n.useCallback(async()=>{var $;if(!s)return;const o=a.username.trim();if(!o||!a.login_password)return;Q(),($=z.current)==null||$.abort();const x=++O.current;I.current=s.id;const N=new AbortController;z.current=N,w({sessionId:"",status:"processing",message:"正在启动密码登录…",qrCodeUrl:""});try{const _=await ms({account_id:s.id,account:o,password:a.login_password,show_browser:a.show_browser},{signal:N.signal});if(!Z(x,O.current,s.id,I.current))return;if(!_.success||!_.session_id)throw new Error(_.message||"无法启动密码登录");w({sessionId:_.session_id,status:"processing",message:_.message||"登录处理中",qrCodeUrl:""}),await ne(_.session_id,x,s.id)}catch(_){if(!Z(x,O.current,s.id,I.current))return;w({sessionId:"",status:"failed",message:_ instanceof Error?_.message:"启动密码登录失败",qrCodeUrl:""})}},[Q,a.login_password,a.show_browser,a.username,s,ne]),le=n.useCallback(async()=>{var x;const o=R.sessionId;O.current+=1,I.current="",(x=z.current)==null||x.abort(),Q(),o&&await hs(o).catch(()=>{}),w({sessionId:"",status:"idle",message:"",qrCodeUrl:""})},[Q,R.sessionId]),ge=n.useCallback(async()=>{var o,x,N;(o=D.current)==null||o.abort(),H.current+=1,(x=K.current)==null||x.abort(),(N=V.current)==null||N.abort(),(R.status==="processing"||R.status==="verification_required")&&await le(),r(null)},[le,R.status,r]),pe=n.useCallback(()=>{var o;G.current+=1,(o=V.current)==null||o.abort(),r(null)},[r]);return n.useEffect(()=>(()=>{var o,x,N,$;(o=D.current)==null||o.abort(),(x=K.current)==null||x.abort(),(N=V.current)==null||N.abort(),($=z.current)==null||$.abort(),Q()}),[Q]),{longLogin:i,notifChannels:b,selectedChannelIds:f,bindingsLoaded:u,bindingsLoading:k,bindingsDirty:p,bindingsLoadError:U,aiSettings:T,saving:j,passwordLoginView:R,setAiSettings:S,setBindingsDirty:L,setEditForm:l,openEditModal:C,closeEditModal:ge,openAIModal:ee,closeAIModal:pe,loadNotificationBindings:F,toggleNotificationChannel:re,handleLongLoginToggle:W,handleSaveAISettings:xe,handleSaveEdit:me,handleRestartPause:be,handlePasswordLogin:he,handleCancelPasswordLogin:le}},Xs=()=>{const{accounts:s,setAccounts:t,loading:r,loadAccounts:a}=Ds(),[l,c]=n.useState(""),[i,d]=n.useState(""),[b,m]=n.useState(""),[f,h]=n.useState(null),[u,A]=n.useState(""),[k,g]=n.useState(null),[p,L]=n.useState(null),[U,M]=n.useState(null),[T,S]=n.useState({remark:"",cookie:"",auto_confirm:!1,pause_duration:0,username:"",login_password:"",show_browser:!1,showLoginPassword:!1,clear_password:!1}),j=Ws({editingAccount:p,setEditingAccount:L,setActiveModal:g,editForm:T,setEditForm:S,loadAccounts:a}),{longLogin:v,notifChannels:R,selectedChannelIds:w,bindingsLoaded:q,bindingsLoading:D,bindingsLoadError:H,aiSettings:K,saving:G,passwordLoginView:V,setAiSettings:O,setBindingsDirty:I,openEditModal:z,closeEditModal:E,openAIModal:Q,closeAIModal:F,loadNotificationBindings:re,toggleNotificationChannel:C,handleLongLoginToggle:W,handleSaveAISettings:ee,handleSaveEdit:xe,handleRestartPause:me,handlePasswordLogin:be,handleCancelPasswordLogin:ne}=j,he=Ms({onLoginSuccess:a}),{showQRModal:le,qrCodeUrl:ge,qrStatus:pe,qrErrorMessage:o,verificationScreenshot:x,faceQrUrl:N,qrReauthTarget:$,startQRLogin:_,closeQRModal:B}=he,oe=async(y,P)=>{await os(y,!P),a()},fe=y=>{b||(A(""),h(y))},Ue=()=>{b||(A(""),h(null))},Me=async()=>{const y=f;if(!(!y||b)){m(y.id),A("");try{await is(y.id),t(P=>P.filter(se=>se.id!==y.id)),h(null)}catch(P){console.error("删除账号失败:",P),A((P==null?void 0:P.message)||"删除账号失败,请稍后重试")}finally{m("")}}},Be=async y=>{d(y.id);try{const P=await gs(y.id);P!=null&&P.profile_error&&alert("资料刷新失败:"+P.profile_error),await a()}catch(P){console.error("刷新账号资料失败:",P),alert((P==null?void 0:P.message)||"刷新账号资料失败,请先重新授权该账号")}finally{d("")}};if(r)return e.jsx("div",{className:"p-20 flex justify-center",children:e.jsx(J,{className:"w-8 h-8 text-brand animate-spin"})});const ye=s.filter(y=>{const P=l.trim().toLowerCase();return P?[y.id,y.nickname,y.remark,y.username,y.runtime_message].some(se=>(se||"").toLowerCase().includes(P)):!0});return e.jsxs("div",{className:"space-y-8 animate-fade-in relative",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"账号管理"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理您的闲鱼授权账号及设置。建议给账号填写备注,便于多账号区分。"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx("input",{value:l,onChange:(y=>c(y.target.value)),placeholder:"搜索昵称 / 备注 / 账号ID",className:"ios-input px-4 py-3 rounded-2xl text-sm w-full sm:w-72"}),e.jsxs("button",{onClick:(()=>_()),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(ve,{className:"w-5 h-5"}),"扫码添加新账号"]})]})]}),e.jsxs("div",{className:"rounded-2xl border border-blue-100 bg-blue-50 px-5 py-4 text-sm text-blue-900 flex flex-col md:flex-row md:items-center md:justify-between gap-2",children:[e.jsxs("div",{className:"font-bold",children:["当前显示 ",ye.length," / ",s.length," 个账号"]}),e.jsx("div",{className:"text-blue-700",children:"如果某个账号只显示 ID,点该账号右侧“刷新资料”;若刷新失败,先点二维码重新授权。"})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-6",children:[ye.map(y=>e.jsx(Ps,{account:y,refreshing:i===y.id,deleting:b===y.id,onRefreshProfile:Be,onReauthorize:_,onEdit:z,onAI:Q,onTasks:M,onToggle:oe,onDelete:fe},y.id)),s.length===0&&e.jsxs("div",{className:"ios-card p-12 text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(Ee,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:"暂无账号"}),e.jsx("p",{className:"text-gray-500 mt-1",children:"请点击右上角扫码添加您的闲鱼账号"})]}),s.length>0&&ye.length===0&&e.jsxs("div",{className:"ios-card p-12 text-center",children:[e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:"没有匹配的账号"}),e.jsx("p",{className:"text-gray-500 mt-1",children:"换一个关键词搜索昵称、备注或账号ID。"})]})]}),U&&ie.createPortal(e.jsx(ks,{account:U,onClose:(()=>M(null)),onSaved:(y=>{t(P=>P.map(se=>se.id===U.id?{...se,auto_rate_enabled:y.auto_rate_enabled,rate_content:y.rate_content,auto_polish_enabled:y.auto_polish_enabled,polish_time:y.polish_time,last_rate_scan_at:y.last_rate_scan_at,last_polish_date:y.last_polish_date,last_polish_at:y.last_polish_at}:se))})}),document.body),f&&e.jsx(Ls,{account:f,deleting:b===f.id,error:u,onClose:Ue,onConfirm:Me}),le&&e.jsx(Ts,{target:$,status:pe,codeUrl:ge,errorMessage:o,faceQrUrl:N,verificationScreenshot:x,onClose:B}),k==="edit"&&p&&e.jsx(Cs,{account:p,editForm:T,setEditForm:S,saving:G,onClose:E,onSave:xe,onRestartPause:me,longLogin:v,onToggleLongLogin:W,passwordLoginView:V,onPasswordLogin:be,onCancelPasswordLogin:ne,notifChannels:R,selectedChannelIds:w,bindingsLoaded:q,bindingsLoading:D,bindingsLoadError:H,onRetryBindings:(()=>re(p.id)),onToggleChannel:C,onSettingsDirty:(()=>I(!0))}),k==="ai-settings"&&p&&e.jsx(Ss,{account:p,settings:K,saving:G,onChange:O,onClose:F,onSave:ee})]})};export{Xs as default}; diff --git a/internal/webui/static/assets/CardList-D-c7QNTB.js b/internal/webui/static/assets/CardList-D43xNKm6.js similarity index 99% rename from internal/webui/static/assets/CardList-D-c7QNTB.js rename to internal/webui/static/assets/CardList-D43xNKm6.js index e4fc7fe..a6a2c1c 100644 --- a/internal/webui/static/assets/CardList-D-c7QNTB.js +++ b/internal/webui/static/assets/CardList-D43xNKm6.js @@ -1,4 +1,4 @@ -import{b as z,j as e,r as i}from"./react-vendor-C_od1ZSF.js";import{X as G,W as Z,J as D,Y as ee,L as U,N as V,C as H,_ as te,$ as W,a0 as X,a1 as ae,I as se,a2 as le,V as ne,F as re,P as oe,r as ie}from"./icons-vendor-CvzvbbIV.js";import{g as ce,p as de,d as xe,a as Y,b as pe}from"./index-CFzx5gQT.js";import{c as me}from"./contract-COFcZjyb.js";const he=({dataCards:l,downloadCardTemplate:n,...a})=>{var x;const u=s=>{var h;a.setBatchFile(((h=s.target.files)==null?void 0:h[0])||null)},m=s=>{a.setAppendContent(s.target.value)},_=s=>{a.setAppendTargetId(s.target.value)},f=()=>a.closeBatchModal(),j=()=>a.setBatchTab("create"),d=()=>a.setBatchTab("append"),A=()=>void a.handleRetryBatchCreate(),c=()=>void a.handleRetryBatchAppend(),y=a.batchResult&&"rows"in a.batchResult?a.batchResult:null,N=s=>e.jsxs("option",{value:String(s.id),children:[s.name,"(ID: ",s.id,")"]},s.id),b=()=>void a.handleBatchCreate(),r=()=>void a.handleBatchAppend();return a.showBatchModal?z.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:f,className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(G,{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:j,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${a.batchTab==="create"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Z,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:d,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${a.batchTab==="append"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(D,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),a.batchTab==="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:n,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 transition-colors",children:[e.jsx(ee,{className:"w-4 h-4"}),"下载模板"]}),e.jsxs("label",{className:"flex-1 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 cursor-pointer transition-colors",children:[e.jsx(D,{className:"w-4 h-4"}),a.batchFile?a.batchFile.name:"选择 .xlsx / .csv / .tsv",e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv",className:"hidden",onChange:u})]})]}),((x=a.batchResult)==null?void 0:x.error)&&e.jsxs("div",{className:"rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:a.batchResult.error}),e.jsx("button",{type:"button",onClick:A,disabled:!a.batchFile||a.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),y&&e.jsxs("div",{className:"rounded-xl border border-gray-200 p-4 space-y-2",children:[e.jsxs("div",{className:"text-sm font-bold text-gray-900",children:["共 ",y.total," 行 · 成功 ",y.created," · 失败 ",y.failed]}),y.failed>0&&e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:y.rows.filter(s=>!s.success).map(s=>e.jsxs("div",{className:"text-xs text-red-600",children:["第 ",s.row_no," 行「",s.name,"」:",s.error]},s.row_no))})]})]}):e.jsx("div",{className:"space-y-4",children:l.length===0?e.jsx("div",{className:"rounded-xl bg-amber-50 border border-amber-200 p-4 text-sm text-amber-800",children:"暂无 data(批量卡密)类型的卡密组,请先创建一个再充卡密。"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"选择卡密组"}),e.jsx("select",{value:a.appendTargetId,onChange:_,className:"w-full ios-input px-4 py-3 rounded-xl text-sm",children:l.map(N)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"卡密号(每行一个)"}),e.jsx("textarea",{value:a.appendContent,onChange:m,placeholder:`VIP-001 +import{b as z,j as e,r as i}from"./react-vendor-C_od1ZSF.js";import{X as G,W as Z,J as D,Y as ee,L as U,N as V,C as H,_ as te,$ as W,a0 as X,a1 as ae,I as se,a2 as le,V as ne,F as re,P as oe,r as ie}from"./icons-vendor-CvzvbbIV.js";import{g as ce,p as de,d as xe,a as Y,b as pe}from"./index-hByDAHGj.js";import{c as me}from"./contract-COFcZjyb.js";const he=({dataCards:l,downloadCardTemplate:n,...a})=>{var x;const u=s=>{var h;a.setBatchFile(((h=s.target.files)==null?void 0:h[0])||null)},m=s=>{a.setAppendContent(s.target.value)},_=s=>{a.setAppendTargetId(s.target.value)},f=()=>a.closeBatchModal(),j=()=>a.setBatchTab("create"),d=()=>a.setBatchTab("append"),A=()=>void a.handleRetryBatchCreate(),c=()=>void a.handleRetryBatchAppend(),y=a.batchResult&&"rows"in a.batchResult?a.batchResult:null,N=s=>e.jsxs("option",{value:String(s.id),children:[s.name,"(ID: ",s.id,")"]},s.id),b=()=>void a.handleBatchCreate(),r=()=>void a.handleBatchAppend();return a.showBatchModal?z.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:f,className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(G,{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:j,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${a.batchTab==="create"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Z,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:d,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${a.batchTab==="append"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(D,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),a.batchTab==="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:n,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 transition-colors",children:[e.jsx(ee,{className:"w-4 h-4"}),"下载模板"]}),e.jsxs("label",{className:"flex-1 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 cursor-pointer transition-colors",children:[e.jsx(D,{className:"w-4 h-4"}),a.batchFile?a.batchFile.name:"选择 .xlsx / .csv / .tsv",e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv",className:"hidden",onChange:u})]})]}),((x=a.batchResult)==null?void 0:x.error)&&e.jsxs("div",{className:"rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:a.batchResult.error}),e.jsx("button",{type:"button",onClick:A,disabled:!a.batchFile||a.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),y&&e.jsxs("div",{className:"rounded-xl border border-gray-200 p-4 space-y-2",children:[e.jsxs("div",{className:"text-sm font-bold text-gray-900",children:["共 ",y.total," 行 · 成功 ",y.created," · 失败 ",y.failed]}),y.failed>0&&e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:y.rows.filter(s=>!s.success).map(s=>e.jsxs("div",{className:"text-xs text-red-600",children:["第 ",s.row_no," 行「",s.name,"」:",s.error]},s.row_no))})]})]}):e.jsx("div",{className:"space-y-4",children:l.length===0?e.jsx("div",{className:"rounded-xl bg-amber-50 border border-amber-200 p-4 text-sm text-amber-800",children:"暂无 data(批量卡密)类型的卡密组,请先创建一个再充卡密。"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"选择卡密组"}),e.jsx("select",{value:a.appendTargetId,onChange:_,className:"w-full ios-input px-4 py-3 rounded-xl text-sm",children:l.map(N)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"卡密号(每行一个)"}),e.jsx("textarea",{value:a.appendContent,onChange:m,placeholder:`VIP-001 VIP-002 VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["预览:",a.appendPreview.length," 个有效卡密,空行自动忽略。"]})]}),a.appendError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-200 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:a.appendError}),e.jsx("button",{type:"button",onClick:c,disabled:a.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),a.appendResult&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",a.appendResult.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:f,className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),a.batchTab==="create"?e.jsxs("button",{onClick:b,disabled:!a.batchFile||a.batchBusy,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(U,{className:"w-4 h-4 animate-spin"}):e.jsx(D,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:r,disabled:!a.appendTargetId||a.appendPreview.length===0||a.batchBusy||l.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(U,{className:"w-4 h-4 animate-spin"}):e.jsx(V,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"追加卡密"]})]})]})}),document.body):null},ue=({type:l})=>{switch(l){case"text":return e.jsx(X,{className:"w-5 h-5 text-blue-500"});case"image":return e.jsx(W,{className:"w-5 h-5 text-purple-500"});case"api":return e.jsx(te,{className:"w-5 h-5 text-blue-500"});default:return e.jsx(H,{className:"w-5 h-5 text-gray-500"})}},be=l=>{let n=l.api_config;if(typeof n=="string"&&n.trim())try{n=JSON.parse(n)}catch{n=void 0}return{...l,api_config:n||void 0}},K=l=>({...l,api_config:l.api_config?JSON.stringify(l.api_config):""}),ge=async l=>{const n=await ce("/api/v1/cards",void 0,l);return me(n,["cards","data","items"]).map(be)},ye=async l=>Y("/api/v1/cards",K(l)),J=async(l,n)=>de(`/api/v1/cards/${l}`,K(n)),fe=async l=>xe(`/api/v1/cards/${l}`),je=async(l,n)=>{const a=new FormData;return a.append("file",l),pe("/api/v1/cards/batch",a,n)},Ne=async(l,n,a)=>Y(`/api/v1/cards/${l}/append-data`,{content:n},a),ve=(l,n,a)=>{const u=a.trim().toLocaleLowerCase();return l.filter(m=>(!n||m.type===n)&&(!u||m.name.toLocaleLowerCase().includes(u)))},Q=l=>l.split(` `).map(n=>n.trim()).filter(Boolean),we=(l,n,a)=>!!(l&&Q(n).length>0&&!a),F=(l,n,a,u)=>l===n&&a===u,Ce=()=>{const[l,n]=i.useState([]),[a,u]=i.useState(!0),m=i.useRef(0),_=i.useRef(null),f=i.useCallback(async()=>{var A;const j=++m.current;(A=_.current)==null||A.abort();const d=new AbortController;_.current=d,u(!0);try{const c=await ge({signal:d.signal});if(j!==m.current)return;n(c)}catch(c){j===m.current&&!d.signal.aborted&&console.error("加载卡密库存失败:",c)}finally{j===m.current&&u(!1)}},[]);return i.useEffect(()=>(f(),()=>{var d;m.current+=1,(d=_.current)==null||d.abort()}),[f]),{cards:l,setCards:n,loading:a,loadCards:f}},_e=l=>{const n=l.dataCards,a=l.loadCards,[u,m]=i.useState(!1),[_,f]=i.useState("create"),[j,d]=i.useState(null),[A,c]=i.useState(null),[y,N]=i.useState(!1),[b,r]=i.useState(""),[x,s]=i.useState(""),[h,E]=i.useState(null),[M,R]=i.useState(""),v=i.useRef(0),T=i.useRef(null),P=i.useRef("");i.useEffect(()=>(()=>{var p;v.current+=1,(p=T.current)==null||p.abort()}),[]);const $=i.useMemo(()=>Q(x),[x]),o=i.useCallback(()=>{var p;f("create"),d(null),c(null),r((p=n[0])!=null&&p.id?String(n[0].id):""),s(""),E(null),R(""),m(!0)},[n]),t=i.useCallback(()=>{var p;v.current+=1,(p=T.current)==null||p.abort(),N(!1),m(!1)},[]),g=i.useCallback(async()=>{var w;if(!j||y)return;const p=++v.current;(w=T.current)==null||w.abort();const B=new AbortController;T.current=B,N(!0),c(null);try{const I=await je(j,{signal:B.signal});if(!F(p,v.current,"",""))return;c(I),I.created>0&&await a()}catch(I){if(!F(p,v.current,"",""))return;c({error:(I==null?void 0:I.message)||"上传失败"})}finally{F(p,v.current,"","")&&N(!1)}},[y,j,a]),k=i.useCallback(async()=>{var I;if(!we(b,x,y))return;const p=b,B=++v.current;P.current=p,(I=T.current)==null||I.abort();const w=new AbortController;T.current=w,N(!0),E(null),R("");try{const O=await Ne(p,x,{signal:w.signal});if(!F(B,v.current,p,b))return;E({added:O.added}),s(""),await a()}catch(O){if(!F(B,v.current,p,b))return;R((O==null?void 0:O.message)||"追加失败")}finally{F(B,v.current,p,b)&&N(!1)}},[x,b,y,a]),S=i.useCallback(async()=>{await g()},[g]),C=i.useCallback(async()=>{P.current&&b!==P.current||await k()},[b,k]);return{showBatchModal:u,setShowBatchModal:m,batchTab:_,setBatchTab:f,batchFile:j,setBatchFile:d,batchResult:A,batchBusy:y,appendTargetId:b,setAppendTargetId:r,appendContent:x,setAppendContent:s,appendResult:h,appendError:M,appendPreview:$,openBatchModal:o,closeBatchModal:t,handleBatchCreate:g,handleBatchAppend:k,handleRetryBatchCreate:S,handleRetryBatchAppend:C}},q=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),L=(l,n)=>l instanceof Error?l.message:n,ke=({cards:l,loadCards:n})=>{const[a,u]=i.useState(!1),[m,_]=i.useState(!1),[f,j]=i.useState(null),[d,A]=i.useState({}),[c,y]=i.useState(q),[N,b]=i.useState(""),[r,x]=i.useState(""),s=i.useMemo(()=>l.filter(o=>o.type==="data"),[l]),h=i.useMemo(()=>ve(l,N,r),[l,r,N]),E=i.useCallback(o=>{var t,g,k,S,C;j(o),A({id:o.id,name:o.name||"",type:o.type||"text",api_url:((t=o.api_config)==null?void 0:t.url)||"",api_method:((g=o.api_config)==null?void 0:g.method)||"GET",api_timeout:((k=o.api_config)==null?void 0:k.timeout)||10,api_headers:((S=o.api_config)==null?void 0:S.headers)||"",api_params:((C=o.api_config)==null?void 0:C.params)||"",text_content:o.text_content||"",data_content:o.data_content||"",image_url:o.image_url||"",delay_seconds:o.delay_seconds||0,description:o.description||"",enabled:o.enabled}),u(!0)},[]),M=i.useCallback(async()=>{var o,t,g,k,S,C,p,B;if(f){if(!((o=d.name)!=null&&o.trim())){alert("请输入卡密名称");return}if(!d.type){alert("请选择卡密类型");return}try{const w={name:d.name.trim(),type:d.type,description:(t=d.description)==null?void 0:t.trim(),delay_seconds:d.delay_seconds||0,enabled:d.enabled??!0};d.type==="api"?w.api_config={url:((g=d.api_url)==null?void 0:g.trim())||"",method:d.api_method||"GET",timeout:d.api_timeout||10,headers:((k=d.api_headers)==null?void 0:k.trim())||void 0,params:((S=d.api_params)==null?void 0:S.trim())||void 0}:d.type==="text"?w.text_content=((C=d.text_content)==null?void 0:C.trim())||"":d.type==="data"?w.data_content=((p=d.data_content)==null?void 0:p.trim())||"":d.type==="image"&&(w.image_url=((B=d.image_url)==null?void 0:B.trim())||""),await J(f.id,w),u(!1),await n()}catch(w){console.error("更新卡密失败:",w),alert(L(w,"更新失败,请重试"))}}},[d,n,f]),R=i.useCallback(async o=>{if(confirm("确认删除该卡密吗?"))try{await fe(o),await n()}catch(t){console.error("删除卡密失败:",t),alert(L(t,"删除失败,请重试"))}},[n]),v=i.useCallback(async()=>{if(!c.name.trim()){alert("请输入卡密名称");return}if(!c.content.trim()){alert(c.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const o={name:c.name.trim(),type:c.type,description:c.description.trim(),enabled:c.enabled,delay_seconds:c.delay_seconds};c.type==="text"&&(o.text_content=c.content.trim()),c.type==="data"&&(o.data_content=c.content.trim()),c.type==="image"&&(o.image_url=c.content.trim()),c.type==="api"&&(o.api_config={url:c.content.trim(),method:c.api_method,timeout:c.api_timeout,headers:c.api_headers.trim()||void 0,params:c.api_params.trim()||void 0}),await ye(o),_(!1),y(q()),await n()}catch(o){console.error("添加卡密失败:",o),alert(L(o,"添加失败,请重试"))}},[c,n]),T=i.useCallback(async o=>{try{await J(o.id,{...o,enabled:!o.enabled}),await n()}catch(t){console.error("切换状态失败:",t)}},[n]),P=i.useCallback(async o=>{try{await navigator.clipboard.writeText(String(o)),alert(`已复制卡密组ID:${o}`)}catch{prompt("复制卡密组ID",String(o))}},[]),$=i.useCallback(()=>{const g=[["名称","类型","内容","描述","启用","延迟秒","多规格","规格名","规格值"],...[["VIP月卡","data",`VIP-MONTH-001 diff --git a/internal/webui/static/assets/Chat-By_xPFNH.js b/internal/webui/static/assets/Chat-By_xPFNH.js deleted file mode 100644 index 724b3a6..0000000 --- a/internal/webui/static/assets/Chat-By_xPFNH.js +++ /dev/null @@ -1 +0,0 @@ -import{j as e,c as $0,r as i}from"./react-vendor-C_od1ZSF.js";import{g as b0,a as F0,b as ee}from"./index-CFzx5gQT.js";import{o as J0}from"./contract-COFcZjyb.js";import{L as r0,ak as te,al as se,M as L0,I as ae,R as ie,ad as I0,k as ne,am as re,s as ce,an as le,ao as oe,ah as pe}from"./icons-vendor-CvzvbbIV.js";const B0=[["尊嘟假嘟","https://img.alicdn.com/imgextra/i2/O1CN01hWzOgD1KcmFEIaGwE_!!6000000001185-2-tps-64-64.png_110x10000.jpg_.webp"],["鸡哔你","https://img.alicdn.com/imgextra/i1/O1CN01P9TVJl1JCqCZcQIdW_!!6000000000993-2-tps-64-64.png_110x10000.jpg_.webp"],["谁懂啊","https://img.alicdn.com/imgextra/i1/O1CN01r9qUnx1g3tcrtSmcs_!!6000000004087-2-tps-64-64.png_110x10000.jpg_.webp"],["吗喽","https://img.alicdn.com/imgextra/i4/O1CN01dTynZh1LnbIYTHI1D_!!6000000001344-2-tps-64-64.png_110x10000.jpg_.webp"],["功德+1","https://img.alicdn.com/imgextra/i1/O1CN01l1G5pS1IVn37pfQJi_!!6000000000899-2-tps-64-64.png_110x10000.jpg_.webp"],["city不city啊","https://img.alicdn.com/imgextra/i2/O1CN01zRjPTR29lWHqabmDA_!!6000000008108-2-tps-64-64.png_110x10000.jpg_.webp"],["激推","https://img.alicdn.com/imgextra/i3/O1CN01ADTJ6u1khypfxbfnQ_!!6000000004716-2-tps-64-64.png_110x10000.jpg_.webp"],["微笑","https://img.alicdn.com/imgextra/i1/O1CN017b61R51wRk2lVV7vx_!!6000000006305-2-tps-980-980.png_110x10000.jpg_.webp"],["龇牙","https://img.alicdn.com/imgextra/i2/O1CN01nmOh4S22Yxz8IdEVf_!!6000000007133-2-tps-980-980.png_110x10000.jpg_.webp"],["流泪","https://img.alicdn.com/imgextra/i2/O1CN01Ec1EaL1zqQETcM2dX_!!6000000006765-2-tps-980-980.png_110x10000.jpg_.webp"],["尴尬","https://img.alicdn.com/imgextra/i2/O1CN01UrWH7a1ZVBrgRYXlc_!!6000000003199-2-tps-980-980.png_110x10000.jpg_.webp"],["撇嘴","https://img.alicdn.com/imgextra/i2/O1CN01Sr7o2b1lUWg5KfOD8_!!6000000004822-2-tps-980-980.png_110x10000.jpg_.webp"],["破涕为笑","https://img.alicdn.com/imgextra/i4/O1CN01pPetah1gkwndfn7Fs_!!6000000004181-2-tps-980-980.png_110x10000.jpg_.webp"],["捂脸哭","https://img.alicdn.com/imgextra/i2/O1CN0170KgpE1dE1TuQgd66_!!6000000003703-2-tps-980-980.png_110x10000.jpg_.webp"],["害羞","https://img.alicdn.com/imgextra/i3/O1CN01ZoB0Lb1ps7XpqP8PQ_!!6000000005415-2-tps-980-980.png_110x10000.jpg_.webp"],["感动","https://img.alicdn.com/imgextra/i2/O1CN01wqD4ly29yndR3Qp3A_!!6000000008137-2-tps-980-980.png_110x10000.jpg_.webp"],["滴泪","https://img.alicdn.com/imgextra/i1/O1CN01MpkJ3L1oUTTqfryOn_!!6000000005228-2-tps-980-980.png_110x10000.jpg_.webp"],["暗中观察","https://img.alicdn.com/imgextra/i1/O1CN010LO9yj272W07GlLls_!!6000000007739-2-tps-980-980.png_110x10000.jpg_.webp"],["偷笑","https://img.alicdn.com/imgextra/i4/O1CN01vJtO031g818IuYO7x_!!6000000004096-2-tps-980-980.png_110x10000.jpg_.webp"],["ok","https://img.alicdn.com/imgextra/i3/O1CN01QRkqDF25tz0WcANje_!!6000000007585-2-tps-980-980.png_110x10000.jpg_.webp"],["送花","https://img.alicdn.com/imgextra/i2/O1CN01PpzBNX1JNpeJBWnvr_!!6000000001017-2-tps-980-980.png_110x10000.jpg_.webp"],["大哭","https://img.alicdn.com/imgextra/i4/O1CN014TiaNb1ViEgNvRrTB_!!6000000002686-2-tps-980-980.png_110x10000.jpg_.webp"],["色","https://img.alicdn.com/imgextra/i2/O1CN01840t1B1JaCLGvHnBK_!!6000000001044-2-tps-980-980.png_110x10000.jpg_.webp"],["惊慌","https://img.alicdn.com/imgextra/i1/O1CN01mnqO7G1LAfUnfAN2U_!!6000000001259-2-tps-980-980.png_110x10000.jpg_.webp"],["惊讶","https://img.alicdn.com/imgextra/i3/O1CN0127IeyS1Kw0p0P4jzI_!!6000000001227-2-tps-980-980.png_110x10000.jpg_.webp"],["得意","https://img.alicdn.com/imgextra/i4/O1CN018QUnFv1WpOUES9POZ_!!6000000002837-2-tps-980-980.png_110x10000.jpg_.webp"],["睡","https://img.alicdn.com/imgextra/i2/O1CN01RprGZl1lqVgnEJLCx_!!6000000004870-2-tps-980-980.png_110x10000.jpg_.webp"],["不好意思","https://img.alicdn.com/imgextra/i3/O1CN01rMJJgn1SUXzuVpUhO_!!6000000002250-2-tps-980-980.png_110x10000.jpg_.webp"],["托腮","https://img.alicdn.com/imgextra/i1/O1CN01w3reBU1d3wlgOBtyZ_!!6000000003681-2-tps-980-980.png_110x10000.jpg_.webp"],["发怒","https://img.alicdn.com/imgextra/i2/O1CN013Wzy8d2A8PxGJZPpT_!!6000000008158-2-tps-980-980.png_110x10000.jpg_.webp"],["难过","https://img.alicdn.com/imgextra/i2/O1CN01zcwaSh1G9gZCFuFal_!!6000000000580-2-tps-980-980.png_110x10000.jpg_.webp"],["调皮","https://img.alicdn.com/imgextra/i3/O1CN01Zd1YHi1TI0lwpBe8c_!!6000000002358-2-tps-980-980.png_110x10000.jpg_.webp"],["愉快","https://img.alicdn.com/imgextra/i2/O1CN0145wDk21SWpyjTvsvA_!!6000000002255-2-tps-980-980.png_110x10000.jpg_.webp"],["白眼","https://img.alicdn.com/imgextra/i4/O1CN01nexGth1hwEAT1SHO2_!!6000000004341-2-tps-980-980.png_110x10000.jpg_.webp"],["拒绝","https://img.alicdn.com/imgextra/i2/O1CN01nqusqS1uHXzoUcpXr_!!6000000006012-2-tps-980-980.png_110x10000.jpg_.webp"],["期待","https://img.alicdn.com/imgextra/i3/O1CN01M44QY11Oh8Q5PdMIx_!!6000000001736-2-tps-980-980.png_110x10000.jpg_.webp"],["困","https://img.alicdn.com/imgextra/i4/O1CN01J4hFFz1Y9pmNdBq76_!!6000000003017-2-tps-980-980.png_110x10000.jpg_.webp"],["流汗","https://img.alicdn.com/imgextra/i4/O1CN01BU3NZ21gdcSjkqnST_!!6000000004165-2-tps-980-980.png_110x10000.jpg_.webp"],["憨笑","https://img.alicdn.com/imgextra/i2/O1CN01Pee9Ql1SJ661eH9By_!!6000000002225-2-tps-980-980.png_110x10000.jpg_.webp"],["耶","https://img.alicdn.com/imgextra/i2/O1CN01pFicsL1ipBhIqzcgs_!!6000000004461-2-tps-980-980.png_110x10000.jpg_.webp"],["奋斗","https://img.alicdn.com/imgextra/i3/O1CN01ZhQ4AV25xBmTK3CnF_!!6000000007592-2-tps-980-980.png_110x10000.jpg_.webp"],["咒骂","https://img.alicdn.com/imgextra/i3/O1CN01r1Zh9927QKb4pnf7k_!!6000000007791-2-tps-980-980.png_110x10000.jpg_.webp"],["疑问","https://img.alicdn.com/imgextra/i4/O1CN01UZqbzt29MmlNctCQS_!!6000000008054-2-tps-980-980.png_110x10000.jpg_.webp"],["嘘","https://img.alicdn.com/imgextra/i1/O1CN01qBlYkM1ojaYF75On5_!!6000000005261-2-tps-980-980.png_110x10000.jpg_.webp"],["晕","https://img.alicdn.com/imgextra/i2/O1CN014zhM2h1wPuSUFoMwV_!!6000000006301-2-tps-980-980.png_110x10000.jpg_.webp"],["开心到模糊","https://img.alicdn.com/imgextra/i1/O1CN01T1Dy271j6akZWo7Vr_!!6000000004499-2-tps-980-980.png_110x10000.jpg_.webp"],["衰","https://img.alicdn.com/imgextra/i1/O1CN01aOXsNr1LmgMvtyzOO_!!6000000001342-2-tps-980-980.png_110x10000.jpg_.webp"],["委屈","https://img.alicdn.com/imgextra/i2/O1CN013J0bMk1QNYih3UFTk_!!6000000001964-2-tps-980-980.png_110x10000.jpg_.webp"],["再见","https://img.alicdn.com/imgextra/i2/O1CN01IHKsQx1UdpFgeTHcA_!!6000000002541-2-tps-980-980.png_110x10000.jpg_.webp"],["鼓掌","https://img.alicdn.com/imgextra/i4/O1CN01DHxB5s1G1RRBxekIu_!!6000000000562-2-tps-980-980.png_110x10000.jpg_.webp"],["吐","https://img.alicdn.com/imgextra/i1/O1CN01xyVxH21LNUaMgW4hh_!!6000000001287-2-tps-980-980.png_110x10000.jpg_.webp"],["坏笑","https://img.alicdn.com/imgextra/i1/O1CN01zV7opv1bIU6iI8OhM_!!6000000003442-2-tps-980-980.png_110x10000.jpg_.webp"],["抠鼻","https://img.alicdn.com/imgextra/i1/O1CN01QOanju1sNqCrtYstu_!!6000000005755-2-tps-980-980.png_110x10000.jpg_.webp"],["叹气","https://img.alicdn.com/imgextra/i3/O1CN01RElx7R1QD1c8ZN07f_!!6000000001941-2-tps-980-980.png_110x10000.jpg_.webp"],["无聊","https://img.alicdn.com/imgextra/i2/O1CN01d91LnZ1UJDQjKCouC_!!6000000002496-2-tps-980-980.png_110x10000.jpg_.webp"],["思考","https://img.alicdn.com/imgextra/i2/O1CN01wQjg2f1tO84ZWitn9_!!6000000005891-2-tps-980-980.png_110x10000.jpg_.webp"],["呆","https://img.alicdn.com/imgextra/i1/O1CN01GLqBWC1DGbhqmpD2L_!!6000000000189-2-tps-980-980.png_110x10000.jpg_.webp"],["哇哦","https://img.alicdn.com/imgextra/i2/O1CN01MtLpS21qRO2bnAA5k_!!6000000005492-2-tps-980-980.png_110x10000.jpg_.webp"],["飞吻","https://img.alicdn.com/imgextra/i4/O1CN01q1WpFE25ljsNKjvHX_!!6000000007567-2-tps-980-980.png_110x10000.jpg_.webp"],["好喜欢","https://img.alicdn.com/imgextra/i2/O1CN01mD4iQM1O57XyQ5SHD_!!6000000001653-2-tps-980-980.png_110x10000.jpg_.webp"],["拜托","https://img.alicdn.com/imgextra/i4/O1CN01SQgrTH1dzCH3pIyRN_!!6000000003806-2-tps-980-980.png_110x10000.jpg_.webp"],["真棒","https://img.alicdn.com/imgextra/i2/O1CN017fcAmd1SCgYCj9Upk_!!6000000002211-2-tps-980-980.png_110x10000.jpg_.webp"],["流鼻血","https://img.alicdn.com/imgextra/i3/O1CN0139JscY1rC6RS9GR4j_!!6000000005594-2-tps-980-980.png_110x10000.jpg_.webp"],["费解","https://img.alicdn.com/imgextra/i1/O1CN01FqAVvR1tyJMPj13ie_!!6000000005970-2-tps-980-980.png_110x10000.jpg_.webp"],["秃头","https://img.alicdn.com/imgextra/i4/O1CN01ZF4bV11thMhqm2Z1h_!!6000000005933-2-tps-980-980.png_110x10000.jpg_.webp"],["嘿哈","https://img.alicdn.com/imgextra/i4/O1CN01ObcOw61FOVlvQg7Mw_!!6000000000477-2-tps-980-980.png_110x10000.jpg_.webp"],["吃土","https://img.alicdn.com/imgextra/i3/O1CN01Z6nJ1b1ZYr22YseHN_!!6000000003207-2-tps-980-980.png_110x10000.jpg_.webp"],["机智","https://img.alicdn.com/imgextra/i1/O1CN01rfKY351zDUZJlBiir_!!6000000006680-2-tps-980-980.png_110x10000.jpg_.webp"],["举杯","https://img.alicdn.com/imgextra/i4/O1CN01R2tn4F1mn8NuEIE8J_!!6000000004998-2-tps-980-980.png_110x10000.jpg_.webp"],["握手","https://img.alicdn.com/imgextra/i4/O1CN01NDcA251JDkvuFhSDb_!!6000000000995-2-tps-980-980.png_110x10000.jpg_.webp"],["挥手","https://img.alicdn.com/imgextra/i4/O1CN01iVN0ht1TmEuSwauGt_!!6000000002424-2-tps-980-980.png_110x10000.jpg_.webp"],["yeah","https://img.alicdn.com/imgextra/i3/O1CN01opt7hh27Wk8omjR4t_!!6000000007805-2-tps-980-980.png_110x10000.jpg_.webp"],["666","https://img.alicdn.com/imgextra/i3/O1CN01YRWDPF1OjQOpXeuTC_!!6000000001741-2-tps-980-980.png_110x10000.jpg_.webp"],["棒","https://img.alicdn.com/imgextra/i3/O1CN01agprvs1HU7rPRxOnB_!!6000000000760-2-tps-980-980.png_110x10000.jpg_.webp"],["爱你","https://img.alicdn.com/imgextra/i1/O1CN01SzxgcH1GSSo6Lwmwk_!!6000000000621-2-tps-980-980.png_110x10000.jpg_.webp"],["比心","https://img.alicdn.com/imgextra/i1/O1CN01YHZ39t1DeQIeb0TWQ_!!6000000000241-2-tps-980-980.png_110x10000.jpg_.webp"],["感谢","https://img.alicdn.com/imgextra/i3/O1CN01ywacF81baLYNeyK1n_!!6000000003481-2-tps-980-980.png_110x10000.jpg_.webp"],["拍手","https://img.alicdn.com/imgextra/i4/O1CN01wbj4wv1K7ArD9AU44_!!6000000001116-2-tps-980-980.png_110x10000.jpg_.webp"],["拉钩","https://img.alicdn.com/imgextra/i1/O1CN01dePkKH1HOd6ivAcu8_!!6000000000748-2-tps-980-980.png_110x10000.jpg_.webp"],["没钱","https://img.alicdn.com/imgextra/i3/O1CN01qhxGjp1zD2AfqmWx5_!!6000000006679-2-tps-980-980.png_110x10000.jpg_.webp"],["小刀","https://img.alicdn.com/imgextra/i3/O1CN01tFVx5Y1T2thPjhR6b_!!6000000002325-2-tps-980-980.png_110x10000.jpg_.webp"],["不刀","https://img.alicdn.com/imgextra/i4/O1CN01zTxff61clcvOcTS3n_!!6000000003641-2-tps-980-980.png_110x10000.jpg_.webp"],["同出","https://img.alicdn.com/imgextra/i3/O1CN01URKas6249R8ozS98O_!!6000000007348-2-tps-980-980.png_110x10000.jpg_.webp"],["递钱","https://img.alicdn.com/imgextra/i4/O1CN01PzhgV51FLlOaZHZ6n_!!6000000000471-2-tps-980-980.png_110x10000.jpg_.webp"],["数钱","https://img.alicdn.com/imgextra/i3/O1CN01CzXXvp23khkljToQH_!!6000000007294-2-tps-980-980.png_110x10000.jpg_.webp"],["打call","https://img.alicdn.com/imgextra/i1/O1CN01X7VUVm1il48IYv8Qw_!!6000000004452-2-tps-980-980.png_110x10000.jpg_.webp"],["号外","https://img.alicdn.com/imgextra/i2/O1CN01vg6xSM1Vxo9EKyfjR_!!6000000002720-2-tps-980-980.png_110x10000.jpg_.webp"],["包邮","https://img.alicdn.com/imgextra/i3/O1CN01yVS7ys24jA22oVZ2T_!!6000000007426-2-tps-980-980.png_110x10000.jpg_.webp"],["求赞","https://img.alicdn.com/imgextra/i1/O1CN01Xwqi5A1giCQMRcX6N_!!6000000004175-2-tps-980-980.png_110x10000.jpg_.webp"],["非主流","https://img.alicdn.com/imgextra/i1/O1CN013wyI1j1hlEfDUoATI_!!6000000004317-2-tps-980-980.png_110x10000.jpg_.webp"],["吃瓜","https://img.alicdn.com/imgextra/i1/O1CN01LLOFsh1UUCw0deZba_!!6000000002520-2-tps-980-980.png_110x10000.jpg_.webp"],["种草","https://img.alicdn.com/imgextra/i2/O1CN01ooeRC81hA8a4x9S3q_!!6000000004236-2-tps-980-980.png_110x10000.jpg_.webp"],["佛系","https://img.alicdn.com/imgextra/i4/O1CN01BYXEe321GMHMZ9w66_!!6000000006957-2-tps-980-980.png_110x10000.jpg_.webp"],["超便宜","https://img.alicdn.com/imgextra/i4/O1CN01mqgSZi1Er4rOIDiP7_!!6000000000404-2-tps-980-980.png_110x10000.jpg_.webp"],["拥抱","https://img.alicdn.com/imgextra/i1/O1CN01yuGD9c1hJkttfKHAm_!!6000000004257-2-tps-980-980.png_110x10000.jpg_.webp"],["摊手","https://img.alicdn.com/imgextra/i2/O1CN014AiIqE1o9repE6STR_!!6000000005183-2-tps-980-980.png_110x10000.jpg_.webp"],["举手","https://img.alicdn.com/imgextra/i1/O1CN01xizuHZ1WPkJCogbuj_!!6000000002781-2-tps-980-980.png_110x10000.jpg_.webp"],["蹲","https://img.alicdn.com/imgextra/i3/O1CN01Midjjn1FrMj2CWer6_!!6000000000540-2-tps-980-980.png_110x10000.jpg_.webp"],["跪了","https://img.alicdn.com/imgextra/i3/O1CN01F2y52j24E16L6RIjF_!!6000000007358-2-tps-980-980.png_110x10000.jpg_.webp"],["拜","https://img.alicdn.com/imgextra/i4/O1CN01Jldd1G1oXDrEHH2qr_!!6000000005234-2-tps-980-980.png_110x10000.jpg_.webp"],["排","https://img.alicdn.com/imgextra/i3/O1CN01uSUmYD1jD0IJf0UVU_!!6000000004513-2-tps-980-980.png_110x10000.jpg_.webp"],["旺财","https://img.alicdn.com/imgextra/i3/O1CN01A25Mv01DKjGseAmuP_!!6000000000198-2-tps-980-980.png_110x10000.jpg_.webp"],["招财猫","https://img.alicdn.com/imgextra/i3/O1CN01WmJ7Sr20EhDyp86Bd_!!6000000006818-2-tps-980-980.png_110x10000.jpg_.webp"],["酸了","https://img.alicdn.com/imgextra/i3/O1CN01UFgjn61JJi5Iqxdk7_!!6000000001008-2-tps-980-980.png_110x10000.jpg_.webp"],["鸭鸭","https://img.alicdn.com/imgextra/i3/O1CN01pHSCSQ1deaS8WDiqG_!!6000000003761-2-tps-980-980.png_110x10000.jpg_.webp"],["方了","https://img.alicdn.com/imgextra/i3/O1CN01br7g711whlu8xOPUt_!!6000000006340-2-tps-980-980.png_110x10000.jpg_.webp"],["白菜","https://img.alicdn.com/imgextra/i1/O1CN01KABFLt24WKwXjVp08_!!6000000007398-2-tps-980-980.png_110x10000.jpg_.webp"],["桃子","https://img.alicdn.com/imgextra/i1/O1CN01CQhhPH1vJfRjDGBv5_!!6000000006152-2-tps-980-980.png_110x10000.jpg_.webp"],["打包","https://img.alicdn.com/imgextra/i3/O1CN01oYOkUI1VT7c0ivZHV_!!6000000002653-2-tps-980-980.png_110x10000.jpg_.webp"],["沙发","https://img.alicdn.com/imgextra/i4/O1CN018qUFaE1DGbhqpMIit_!!6000000000189-2-tps-980-980.png_110x10000.jpg_.webp"],["南","https://img.alicdn.com/imgextra/i1/O1CN01ZSA6wg1PEZKf4h99R_!!6000000001809-2-tps-980-980.png_110x10000.jpg_.webp"],["盯","https://img.alicdn.com/imgextra/i4/O1CN01OWB1Gx1s01bzBhHN6_!!6000000005703-2-tps-980-980.png_110x10000.jpg_.webp"],["hot","https://img.alicdn.com/imgextra/i4/O1CN01DDD9uA22cAl7VDH7d_!!6000000007140-2-tps-980-980.png_110x10000.jpg_.webp"],["new","https://img.alicdn.com/imgextra/i3/O1CN01rRJXJo1qwzN4YnOHX_!!6000000005561-2-tps-980-980.png_110x10000.jpg_.webp"],["cool","https://img.alicdn.com/imgextra/i4/O1CN013bUubF2855qb2Qt5l_!!6000000007880-2-tps-980-980.png_110x10000.jpg_.webp"],["1","https://img.alicdn.com/imgextra/i1/O1CN01U8XG5y1Ie22frQHCQ_!!6000000000917-2-tps-980-980.png_110x10000.jpg_.webp"],["可","https://img.alicdn.com/imgextra/i2/O1CN01SMjtPG1iJaN17p94N_!!6000000004392-2-tps-980-980.png_110x10000.jpg_.webp"],["搬砖","https://img.alicdn.com/imgextra/i1/O1CN01GbqW6G1LOrm0Gllcb_!!6000000001290-2-tps-980-980.png_110x10000.jpg_.webp"],["菜狗","https://img.alicdn.com/imgextra/i2/O1CN01VtN0t91USNLmvfmol_!!6000000002516-2-tps-980-980.png_110x10000.jpg_.webp"],["开心面具","https://img.alicdn.com/imgextra/i3/O1CN017elkpk22EoYlBPKd3_!!6000000007089-2-tps-980-980.png_110x10000.jpg_.webp"],["快递","https://img.alicdn.com/imgextra/i2/O1CN01AmUZXk1d3wle5O8IJ_!!6000000003681-2-tps-980-980.png_110x10000.jpg_.webp"],["裂开","https://img.alicdn.com/imgextra/i1/O1CN01BihwvO1a5N9bFt0LU_!!6000000003278-2-tps-980-980.png_110x10000.jpg_.webp"],["啤酒","https://img.alicdn.com/imgextra/i4/O1CN01jDkgEj1WvLdXUVBDx_!!6000000002850-2-tps-980-980.png_110x10000.jpg_.webp"],["瑞思拜","https://img.alicdn.com/imgextra/i4/O1CN011gR0Um1K3VgpYjPOi_!!6000000001108-2-tps-980-980.png_110x10000.jpg_.webp"],["小丑","https://img.alicdn.com/imgextra/i3/O1CN01jMikhO1NJUM15XKTf_!!6000000001549-2-tps-980-980.png_110x10000.jpg_.webp"],["爱心","https://img.alicdn.com/imgextra/i1/O1CN015RVSWf23s25eETJqO_!!6000000007310-2-tps-980-980.png_110x10000.jpg_.webp"]],me=l=>l,ge=new Map(B0.map(([l,m])=>[l,m])),de=l=>l.split(/(\[[^\]]+\])/g).map((m,s)=>{const n=m.startsWith("[")?ge.get(m.slice(1,-1)):void 0;return n?e.jsx("img",{src:n,alt:m,title:m,className:"mx-0.5 inline-block h-7 w-7 align-middle"},s):e.jsx($0.Fragment,{children:m},s)}),xe=async l=>b0("/api/v1/accounts/details",void 0,l),U0=async l=>b0("/api/v1/accounts/runtime-status",void 0,l),M0=async(l,m,s,n=!1)=>{const d=await b0("/api/v1/chat/sessions",{account_id:l,cursor:m,refresh:n?1:void 0},n?{timeoutMs:6e4,...s}:s),j=J0(d,["data","result"])||{};return{sessions:j.sessions||[],has_more:j.has_more===!0,next_cursor:j.next_cursor}},A0=async(l,m,s,n,d)=>{const j=await b0("/api/v1/chat/messages",{account_id:l,chat_id:m,cursor:s,before_id:n},d),_=J0(j,["data","result"])||{};return{messages:_.messages||[],has_more:_.has_more===!0,next_cursor:_.next_cursor,session:_.session}},_e=async(l,m)=>F0("/api/v1/chat/messages",l,m),ue=async(l,m)=>{const s=new FormData;return Object.entries(l).forEach(([n,d])=>s.append(n,d)),ee("/api/v1/chat/images",s,{timeoutMs:12e4,...m})},H0=async(l,m,s)=>F0("/api/v1/chat/read",{account_id:l,chat_id:m},s),he=(l,m,s)=>{const n=m.trim().toLowerCase();return l.filter(d=>s&&d.unread_count<=0?!1:n?[d.buyer_name,d.buyer_id,d.item_title,d.last_message].some(j=>(j||"").toLowerCase().includes(n)):!0)},be=(l,m)=>{const s=new Set(l.map(n=>n.message_key));return[...m.filter(n=>!s.has(n.message_key)),...l]},q0=(l,m)=>{const s=l.findIndex(n=>n.message_key===m.message_key);return s<0?[...l,m]:l.map((n,d)=>d===s?m:n)},N=(l,m,s)=>l===m&&!s.aborted,Z=l=>l instanceof Error&&l.message==="请求已取消",fe=l=>{if(!l)return"";const m=new Date(l<1e10?l*1e3:l),s=new Date;return m.toDateString()===s.toDateString()?m.toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit",hour12:!1}):m.toLocaleDateString("zh-CN",{month:"2-digit",day:"2-digit"})},je=l=>new Date(l<1e10?l*1e3:l).toLocaleString("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),we=()=>{const[l,m]=i.useState([]),[s,n]=i.useState(""),[d,j]=i.useState({}),[_,z]=i.useState(""),[D,S]=i.useState([]),[V,f0]=i.useState(""),[M,j0]=i.useState(!1),[q,c0]=i.useState(""),[w0,T]=i.useState(!0),[A,I]=i.useState(!1),[W,G]=i.useState(!1),[X,l0]=i.useState(!1),[o0,p0]=i.useState(),[Y,H]=i.useState({}),[K,$]=i.useState({}),[e0,m0]=i.useState(!1),[g0,N0]=i.useState(!1),[y,F]=i.useState(!1),[C0,C]=i.useState(""),[y0,J]=i.useState("connecting"),[B,t0]=i.useState(null),[a,f]=i.useState(null),v=i.useRef(""),s0=i.useRef(""),d0=i.useRef(null),O0=i.useRef({accountID:"",chatID:""}),v0=i.useRef(!0),Q=i.useRef(!1),k0=i.useRef(null),T0=i.useRef(new Set),S0=i.useRef(0),R0=i.useRef(null),L=i.useRef(0),E0=i.useRef(null),U=i.useRef(0),a0=i.useRef(null),i0=i.useRef(0),x0=i.useRef(null),R=i.useRef(0),P=i.useRef(null);i.useEffect(()=>{v.current=s},[s]),i.useEffect(()=>{s0.current=_},[_]);const n0=i.useCallback(async t=>{var c;const o=++S0.current;(c=R0.current)==null||c.abort();const p=new AbortController;R0.current=p;try{const r=await M0(t,void 0,{signal:p.signal},!0);return N(S0.current,o,p.signal)?(j(g=>({...g,[t]:r.sessions})),H(g=>({...g,[t]:r.next_cursor})),$(g=>({...g,[t]:r.has_more})),r.sessions):[]}catch(r){return N(S0.current,o,p.signal)&&!Z(r)&&C(r instanceof Error?r.message:"同步会话失败"),[]}},[]);i.useEffect(()=>{const t=new AbortController;return(async()=>{var p;T(!0);try{const[c,r]=await Promise.all([xe({signal:t.signal}),U0({signal:t.signal})]),x=c.map(u=>{var O,D0;return{...u,runtime_state:((O=r[u.id])==null?void 0:O.state)||(u.enabled?"connecting":"disabled"),runtime_connected:((D0=r[u.id])==null?void 0:D0.connected)===!0}}).filter(u=>u.enabled),w=await Promise.all(x.map(async u=>[u.id,await M0(u.id,void 0,{signal:t.signal})]));if(t.signal.aborted)return;m(x),j(Object.fromEntries(w.map(([u,O])=>[u,O.sessions]))),H(Object.fromEntries(w.map(([u,O])=>[u,O.next_cursor]))),$(Object.fromEntries(w.map(([u,O])=>[u,O.has_more])));const h=window.localStorage.getItem("ydisks.chat.account.v1")||"",k=x.some(u=>u.id===h)?h:((p=x[0])==null?void 0:p.id)||"";n(k)}catch(c){t.signal.aborted||C(c instanceof Error?c.message:"加载聊天数据失败")}finally{t.signal.aborted||T(!1)}})(),(()=>t.abort())},[]),i.useEffect(()=>{let t=!1,o=0,p=null;const c=async()=>{p=new AbortController;try{const r=await U0({signal:p.signal,timeoutMs:1e4});t||m(g=>g.map(x=>{var w,h;return{...x,runtime_state:((w=r[x.id])==null?void 0:w.state)||x.runtime_state,runtime_connected:((h=r[x.id])==null?void 0:h.connected)??x.runtime_connected}}))}catch{}finally{t||(o=window.setTimeout(c,3e3))}};return o=window.setTimeout(c,3e3),(()=>{t=!0,window.clearTimeout(o),p==null||p.abort()})},[]),i.useEffect(()=>{if(!s)return;window.localStorage.setItem("ydisks.chat.account.v1",s);const t=d[s]||[];z(o=>{var p;return t.some(c=>c.chat_id===o)?o:((p=t[0])==null?void 0:p.chat_id)||""})},[s,d]),i.useEffect(()=>{!s||T0.current.has(s)||(T0.current.add(s),n0(s))},[s,n0]),i.useEffect(()=>{var p,c;if(!s||!_){L.current+=1,U.current+=1,(p=a0.current)==null||p.abort(),Q.current=!1,S([]);return}const t=++L.current;(c=E0.current)==null||c.abort();const o=new AbortController;return E0.current=o,I(!0),Promise.all([A0(s,_,void 0,void 0,{signal:o.signal}),H0(s,_,{signal:o.signal})]).then(([r])=>{N(L.current,t,o.signal)&&(S(r.messages),l0(r.has_more),p0(r.next_cursor),r.session&&j(g=>({...g,[s]:(g[s]||[]).map(x=>{var w;return x.chat_id===((w=r.session)==null?void 0:w.chat_id)?r.session:x})})),j(g=>({...g,[s]:(g[s]||[]).map(x=>x.chat_id===_?{...x,unread_count:0}:x)})))}).catch(r=>{N(L.current,t,o.signal)&&!Z(r)&&C(r instanceof Error?r.message:"加载消息失败")}).finally(()=>{N(L.current,t,o.signal)&&I(!1)}),(()=>o.abort())},[s,_]),i.useEffect(()=>{var t;(t=x0.current)==null||t.abort(),i0.current+=1},[s]),i.useEffect(()=>{var t;(t=P.current)==null||t.abort(),R.current+=1},[s,_]),i.useEffect(()=>{var t;U.current+=1,(t=a0.current)==null||t.abort(),Q.current=!1},[s,_]),i.useEffect(()=>(()=>{var t,o,p,c,r;(t=R0.current)==null||t.abort(),(o=E0.current)==null||o.abort(),U.current+=1,(p=a0.current)==null||p.abort(),(c=x0.current)==null||c.abort(),(r=P.current)==null||r.abort()}),[]);const Q0=i.useCallback(async()=>{var g,x;if(!s||!_||W||!X)return;const t=d0.current,o=(t==null?void 0:t.scrollHeight)||0,p=L.current,c=++U.current;(g=a0.current)==null||g.abort();const r=new AbortController;a0.current=r,Q.current=!0,G(!0),C("");try{const w=(x=D[0])==null?void 0:x.id,h=await A0(s,_,o0,w,{signal:r.signal});if(!N(L.current,p,r.signal)||c!==U.current)return;S(k=>be(k,h.messages)),l0(h.has_more),p0(h.next_cursor),requestAnimationFrame(()=>{c===U.current&&!r.signal.aborted&&t&&(t.scrollTop+=t.scrollHeight-o)})}catch(w){Q.current=!1,Z(w)||C(w instanceof Error?w.message:"加载历史消息失败")}finally{c===U.current&&G(!1)}},[s,_,X,o0,D,W]);i.useEffect(()=>{let t=!1,o=0,p=0,c=null;const r=()=>{if(t)return;J("connecting");const g=window.location.protocol==="https:"?"wss:":"ws:";c=new WebSocket(`${g}//${window.location.host}/api/v1/chat/ws`),c.onopen=()=>{p=0,J("online")},c.onmessage=x=>{try{const h=JSON.parse(x.data).message;if(!h)return;const k=h.account_id;j(u=>{const O=u[k]||[];return O.some(E=>E.chat_id===h.chat_id)?{...u,[k]:O.map(E=>E.chat_id===h.chat_id?{...E,last_message:h.content,last_message_at:h.sent_at,unread_count:h.direction==="incoming"&&(v.current!==k||s0.current!==h.chat_id)?E.unread_count+1:E.unread_count}:E).sort((E,K0)=>K0.last_message_at-E.last_message_at)}:(n0(k),u)}),v.current===k&&s0.current===h.chat_id&&(S(u=>q0(u,h)),h.direction==="incoming"&&H0(k,h.chat_id))}catch{}},c.onclose=()=>{if(t)return;J("offline");const x=Math.min(15e3,1e3*2**Math.min(p++,4));o=window.setTimeout(r,x)},c.onerror=()=>c==null?void 0:c.close()};return r(),(()=>{t=!0,window.clearTimeout(o),c==null||c.close()})},[n0]);const P0=i.useCallback(()=>{const t=d0.current;if(!t)return;const o=t.scrollHeight-t.scrollTop-t.clientHeight;v0.current=o<=48},[]);i.useLayoutEffect(()=>{const t=O0.current.accountID!==s||O0.current.chatID!==_;O0.current={accountID:s,chatID:_},t&&(v0.current=!0);const o=d0.current;if(o){if(Q.current){Q.current=!1;return}(A||v0.current)&&(o.scrollTop=o.scrollHeight)}},[s,_,D,A]);const Z0=l.find(t=>t.id===s),_0=d[s]||[],b=_0.find(t=>t.chat_id===_),z0=i.useMemo(()=>he(_0,V,M),[_0,V,M]),V0=i.useCallback(t=>(d[t]||[]).reduce((o,p)=>o+p.unread_count,0),[d]),W0=i.useCallback(async()=>{var c;if(!s||e0||!K[s])return;const t=++i0.current;(c=x0.current)==null||c.abort();const o=new AbortController;x0.current=o;const p=s;m0(!0),C("");try{const r=await M0(p,Y[p],{signal:o.signal},!0);if(!N(i0.current,t,o.signal))return;j(g=>({...g,[p]:r.sessions})),H(g=>({...g,[p]:r.next_cursor})),$(g=>({...g,[p]:r.has_more}))}catch(r){N(i0.current,t,o.signal)&&!Z(r)&&C(r instanceof Error?r.message:"加载历史联系人失败")}finally{N(i0.current,t,o.signal)&&m0(!1)}},[s,Y,e0,K]),u0=i.useCallback(async(t,o)=>{var r;if(!b||!s||y)return;const p=++R.current;(r=P.current)==null||r.abort();const c=new AbortController;P.current=c,F(!0),C("");try{const g=await _e({account_id:s,chat_id:b.chat_id,buyer_id:b.buyer_id,buyer_name:b.buyer_name,item_id:b.item_id,item_title:b.item_title,text:t},{signal:c.signal});if(!N(R.current,p,c.signal))return;c0(""),t0(null),S(x=>q0(x,g.message))}catch(g){N(R.current,p,c.signal)&&(o&&t0(t),Z(g)||C(g instanceof Error?g.message:"消息发送失败"))}finally{N(R.current,p,c.signal)&&F(!1)}},[s,b,y]),h0=i.useCallback(async(t,o)=>{var r;if(!b||!s||y)return;const p=++R.current;(r=P.current)==null||r.abort();const c=new AbortController;P.current=c,F(!0),C("");try{const g=await ue({account_id:s,chat_id:b.chat_id,buyer_id:b.buyer_id,buyer_name:b.buyer_name,buyer_avatar_url:b.buyer_avatar_url,item_id:b.item_id,item_title:b.item_title,image:t},{signal:c.signal});if(!N(R.current,p,c.signal))return;f(null),S(x=>q0(x,g.message))}catch(g){N(R.current,p,c.signal)&&(o&&f(t),Z(g)||C(g instanceof Error?g.message:"图片发送失败"))}finally{N(R.current,p,c.signal)&&(F(!1),k0.current&&(k0.current.value=""))}},[s,b,y]),G0=i.useCallback(async()=>{const t=q.trim();!t||!b||!s||y||await u0(t,!0)},[s,q,b,u0,y]),X0=i.useCallback(async t=>{!t||!b||!s||y||await h0(t,!0)},[s,b,h0,y]),Y0=i.useCallback(async()=>{B?await u0(B,!1):a&&await h0(a,!1)},[a,B,h0,u0]);return{accounts:l,activeAccountID:s,activeSessions:_0,selectedSession:b,activeAccount:Z0,messages:D,search:V,unreadOnly:M,draft:q,loading:w0,messagesLoading:A,olderLoading:W,hasOlder:X,contactsLoading:e0,hasMoreContacts:K[s]===!0,emojiOpen:g0,sending:y,error:C0,liveState:y0,activeChatID:_,filteredSessions:z0,scrollRef:d0,imageInputRef:k0,setActiveAccountID:n,setActiveChatID:z,setSearch:f0,setUnreadOnly:j0,setDraft:c0,setEmojiOpen:N0,reloadSessions:n0,loadMoreContacts:W0,loadOlderMessages:Q0,handleMessageScroll:P0,handleSend:G0,handleImage:X0,retrySend:Y0,retryAvailable:!!(B||a),unreadForAccount:V0,emojiURL:me,xianyuEmojis:B0,renderXianyuText:de,formatClock:fe,messageTime:je}},ve=()=>{const{accounts:l,activeAccountID:m,activeChatID:s,activeAccount:n,selectedSession:d,filteredSessions:j,messages:_,search:z,unreadOnly:D,draft:S,loading:V,messagesLoading:f0,olderLoading:M,hasOlder:j0,contactsLoading:q,hasMoreContacts:c0,emojiOpen:w0,sending:T,error:A,liveState:I,scrollRef:W,imageInputRef:G,setActiveAccountID:X,setActiveChatID:l0,setSearch:o0,setUnreadOnly:p0,setDraft:Y,setEmojiOpen:H,reloadSessions:K,loadMoreContacts:$,loadOlderMessages:e0,handleMessageScroll:m0,handleSend:g0,handleImage:N0,retrySend:y,retryAvailable:F,unreadForAccount:C0,emojiURL:C,xianyuEmojis:y0,renderXianyuText:J,formatClock:B,messageTime:t0}=we();return V?e.jsx("div",{className:"flex h-[calc(100vh-4rem)] items-center justify-center",children:e.jsx(r0,{className:"h-8 w-8 animate-spin text-sky-500"})}):e.jsxs("section",{className:"flex h-[calc(100vh-4rem)] min-h-[560px] flex-col overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-chat",children:[e.jsxs("header",{className:"border-b border-slate-200 bg-slate-50/70 px-5 pt-4",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-black tracking-tight text-slate-950",children:"在线聊天"}),e.jsx("p",{className:"mt-0.5 text-xs font-medium text-slate-500",children:"复用账号实时连接,消息按账号完全隔离"})]}),e.jsxs("div",{className:`flex items-center gap-2 rounded-full px-3 py-1.5 text-xs font-bold ${I==="online"?"bg-emerald-50 text-emerald-700":I==="connecting"?"bg-amber-50 text-amber-700":"bg-red-50 text-red-700"}`,children:[I==="online"?e.jsx(te,{className:"h-3.5 w-3.5"}):e.jsx(se,{className:"h-3.5 w-3.5"}),I==="online"?"实时同步中":I==="connecting"?"正在连接":"连接已断开"]})]}),e.jsx("div",{className:"flex gap-1 overflow-x-auto pb-0",role:"tablist","aria-label":"聊天账号",children:l.map(a=>{const f=a.id===m,v=C0(a.id),s0=a.runtime_state==="online";return e.jsxs("button",{type:"button",role:"tab","aria-selected":f,onClick:(()=>X(a.id)),className:`relative flex h-11 shrink-0 items-center gap-2 border-b-2 px-3 text-sm font-extrabold transition-colors ${f?"border-sky-500 text-sky-700":"border-transparent text-slate-500 hover:text-slate-900"}`,children:[e.jsx("span",{className:`h-2 w-2 rounded-full ${s0?"bg-emerald-500":"bg-slate-300"}`}),e.jsx("span",{className:"max-w-36 truncate",children:a.nickname||a.remark||a.id}),v>0&&e.jsx("span",{className:"min-w-5 rounded-full bg-red-500 px-1.5 py-0.5 text-[10px] text-white",children:v>99?"99+":v})]},a.id)})})]}),l.length===0?e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center text-center",children:[e.jsx(L0,{className:"h-12 w-12 text-slate-300"}),e.jsx("h3",{className:"mt-4 font-black text-slate-800",children:"暂无启用账号"}),e.jsx("p",{className:"mt-1 text-sm text-slate-500",children:"先在账号管理中启用账号,聊天会话会自动出现。"})]}):e.jsxs("div",{className:"grid min-h-0 flex-1 overflow-hidden grid-cols-[320px_minmax(0,1fr)]",children:[e.jsxs("aside",{className:"flex min-h-0 flex-col border-r border-slate-200 bg-slate-50/40",children:[e.jsxs("div",{className:"space-y-3 border-b border-slate-200 p-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ae,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400"}),e.jsx("input",{value:z,onChange:(a=>o0(a.target.value)),placeholder:"搜索用户、商品或消息",className:"h-10 w-full rounded-xl border border-slate-200 bg-white pl-9 pr-3 text-sm outline-none transition focus:border-sky-400 focus:ring-2 focus:ring-sky-100"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("button",{type:"button",onClick:(()=>p0(a=>!a)),className:`rounded-lg px-2.5 py-1.5 text-xs font-bold ${D?"bg-sky-100 text-sky-700":"text-slate-500 hover:bg-slate-100"}`,children:D?"只看未读":"全部会话"}),e.jsx("button",{type:"button",title:"刷新会话",onClick:(()=>void K(m)),className:"rounded-lg p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700",children:e.jsx(ie,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto",children:[j.map(a=>e.jsxs("button",{type:"button",onClick:(()=>l0(a.chat_id)),className:`flex w-full gap-3 border-b border-slate-100 p-4 text-left transition-colors ${a.chat_id===s?"bg-white shadow-chat-active":"hover:bg-white/80"}`,children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center overflow-hidden rounded-full bg-slate-200 text-slate-500",children:a.buyer_avatar_url?e.jsx("img",{src:a.buyer_avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx(I0,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate text-sm font-extrabold text-slate-900",children:a.buyer_name||`用户 ${a.buyer_id}`}),e.jsx("span",{className:"ml-auto shrink-0 text-[10px] font-medium text-slate-400",children:B(a.last_message_at)})]}),e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsx("span",{className:"truncate text-xs text-slate-500",children:a.last_message||"暂无消息"}),a.unread_count>0&&e.jsx("span",{className:"ml-auto min-w-5 shrink-0 rounded-full bg-red-500 px-1.5 py-0.5 text-center text-[10px] font-bold text-white",children:a.unread_count})]}),a.item_title&&e.jsxs("div",{className:"mt-1.5 truncate text-[10px] font-medium text-sky-700",children:["商品 · ",a.item_title]})]})]},a.chat_id)),j.length===0&&e.jsx("div",{className:"px-6 py-16 text-center text-sm text-slate-400",children:"当前账号暂无匹配会话"}),c0&&!z&&!D&&e.jsx("div",{className:"flex justify-center p-4",children:e.jsxs("button",{type:"button",onClick:(()=>void $()),disabled:q,className:"flex items-center gap-2 rounded-full border border-slate-200 bg-white px-4 py-2 text-xs font-bold text-slate-500 shadow-sm hover:border-sky-200 hover:text-sky-600 disabled:opacity-50",children:[q&&e.jsx(r0,{className:"h-3.5 w-3.5 animate-spin"}),q?"正在加载":"加载更多历史联系人"]})})]})]}),e.jsx("main",{className:"flex min-h-0 min-w-0 flex-col overflow-hidden bg-surface-subtle",children:d?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex h-16 shrink-0 items-center border-b border-slate-200 bg-white px-5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-black text-slate-950",children:d.buyer_name||d.buyer_id}),e.jsxs("div",{className:"mt-0.5 truncate text-xs text-slate-500",children:["用户 ID:",d.buyer_id]})]}),e.jsx("span",{className:`ml-auto rounded-full px-2.5 py-1 text-[10px] font-bold ${(n==null?void 0:n.runtime_state)==="online"?"bg-emerald-50 text-emerald-700":"bg-slate-100 text-slate-500"}`,children:(n==null?void 0:n.runtime_state)==="online"?"账号在线":"账号离线"})]}),e.jsx("div",{ref:W,onScroll:m0,className:"min-h-0 flex-1 space-y-5 overflow-y-auto px-6 py-5",children:f0?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(r0,{className:"h-6 w-6 animate-spin text-sky-500"})}):e.jsxs(e.Fragment,{children:[j0&&e.jsx("div",{className:"flex justify-center pb-1",children:e.jsxs("button",{type:"button",onClick:(()=>void e0()),disabled:M,className:"flex items-center gap-2 rounded-full border border-slate-200 bg-white px-4 py-1.5 text-xs font-bold text-slate-500 shadow-sm transition hover:border-sky-200 hover:text-sky-600 disabled:opacity-50",children:[M&&e.jsx(r0,{className:"h-3.5 w-3.5 animate-spin"}),M?"正在加载":"加载更早消息"]})}),_.map(a=>{const f=a.direction==="outgoing";return a.message_type==="system"?e.jsx("div",{className:"flex justify-center py-1",children:e.jsxs("div",{className:"max-w-[82%] rounded-xl border border-slate-200 bg-slate-100 px-4 py-2 text-center text-xs leading-5 text-slate-500",children:[J(a.content),e.jsx("div",{className:"mt-1 text-[10px] text-slate-400",children:t0(a.sent_at)})]})},a.message_key):e.jsxs("div",{className:`flex items-end gap-2.5 ${f?"justify-end":"justify-start"}`,children:[!f&&e.jsx("div",{className:"h-9 w-9 shrink-0 overflow-hidden rounded-full bg-slate-200 ring-2 ring-white",children:d.buyer_avatar_url?e.jsx("img",{src:d.buyer_avatar_url,alt:d.buyer_name||"用户",className:"h-full w-full object-cover"}):e.jsx(I0,{className:"m-2 h-5 w-5 text-slate-500"})}),e.jsxs("div",{className:`max-w-[72%] ${f?"items-end":"items-start"} flex flex-col`,children:[e.jsx("div",{className:"mb-1 px-1 text-[10px] font-semibold text-slate-400",children:f?(n==null?void 0:n.nickname)||(n==null?void 0:n.remark)||"我":d.buyer_name||a.sender_name||d.buyer_id}),a.message_type==="image"?e.jsx("a",{href:a.content,target:"_blank",rel:"noreferrer",className:`block overflow-hidden rounded-2xl border bg-white p-1 shadow-sm ${f?"rounded-br-md border-sky-200":"rounded-bl-md border-slate-200"}`,children:e.jsx("img",{src:a.content,alt:"聊天图片",className:"max-h-80 max-w-full rounded-xl object-contain"})}):a.message_type==="video"?e.jsx("video",{src:a.content,controls:!0,preload:"metadata",className:"max-h-80 max-w-full rounded-2xl bg-black"}):e.jsx("div",{className:`rounded-2xl px-4 py-2.5 text-sm leading-6 shadow-sm ${f?"rounded-br-md bg-sky-500 text-white":"rounded-bl-md border border-slate-200 bg-white text-slate-800"}`,children:J(a.content)}),e.jsxs("div",{className:"mt-1 flex items-center gap-1 text-[10px] text-slate-400",children:[t0(a.sent_at),f&&(a.status==="failed"?e.jsx(ne,{className:"h-3 w-3 text-red-500"}):a.status==="sent"?e.jsx(re,{className:"h-3 w-3 text-sky-500"}):e.jsx(ce,{className:"h-3 w-3"}))]})]}),f&&e.jsx("div",{className:"h-9 w-9 shrink-0 overflow-hidden rounded-full bg-sky-100 ring-2 ring-white",children:n!=null&&n.avatar_url?e.jsx("img",{src:n.avatar_url,alt:"我",className:"h-full w-full object-cover"}):e.jsx(I0,{className:"m-2 h-5 w-5 text-sky-600"})})]},a.message_key)})]})}),A&&e.jsxs("div",{className:"flex items-center justify-between gap-3 border-t border-red-100 bg-red-50 px-5 py-2 text-xs font-medium text-red-700",children:[e.jsx("span",{children:A}),F&&e.jsx("button",{type:"button",className:"font-bold underline",onClick:(()=>void y()),children:"重试发送"})]}),e.jsxs("div",{className:"relative z-10 shrink-0 border-t border-slate-200 bg-white p-4 shadow-chat-input",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-1",children:[e.jsxs("div",{className:"relative",children:[e.jsx("button",{type:"button",onClick:(()=>H(a=>!a)),disabled:T||(n==null?void 0:n.runtime_state)!=="online",className:"rounded-lg p-2 text-slate-500 hover:bg-sky-50 hover:text-sky-600 disabled:opacity-40",title:"闲鱼表情",children:e.jsx(le,{className:"h-5 w-5"})}),w0&&e.jsxs("div",{className:"absolute bottom-11 left-0 z-30 w-[360px] rounded-2xl border border-slate-200 bg-white p-3 shadow-2xl",children:[e.jsx("div",{className:"mb-2 text-xs font-bold text-slate-500",children:"全部表情"}),e.jsx("div",{className:"grid max-h-72 grid-cols-8 gap-1 overflow-y-auto",children:y0.map(([a,f])=>e.jsx("button",{type:"button",title:`[${a}]`,onClick:(()=>{Y(v=>v+`[${a}]`),H(!1)}),className:"flex h-10 w-10 items-center justify-center rounded-lg hover:bg-slate-100",children:e.jsx("img",{src:C(f),alt:`[${a}]`,className:"h-8 w-8 object-contain"})},a))})]})]}),e.jsx("input",{ref:G,type:"file",accept:"image/*",className:"hidden",onChange:(a=>{var f;return void N0((f=a.target.files)==null?void 0:f[0])})}),e.jsx("button",{type:"button",onClick:(()=>{var a;return(a=G.current)==null?void 0:a.click()}),disabled:T||(n==null?void 0:n.runtime_state)!=="online",className:"rounded-lg p-2 text-slate-500 transition hover:bg-sky-50 hover:text-sky-600 disabled:opacity-40",title:"发送图片(最大 10MB)",children:e.jsx(oe,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"flex items-end gap-3 rounded-2xl border border-slate-200 bg-slate-50 p-2 transition focus-within:border-sky-400 focus-within:ring-2 focus-within:ring-sky-100",children:[e.jsx("textarea",{value:S,onChange:(a=>Y(a.target.value)),rows:2,maxLength:2e3,onKeyDown:(a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),g0())}),disabled:(n==null?void 0:n.runtime_state)!=="online",placeholder:(n==null?void 0:n.runtime_state)==="online"?"输入消息,Enter 发送,Shift + Enter 换行":"账号离线,暂时无法发送",className:"max-h-32 min-h-12 flex-1 resize-none bg-transparent px-2 py-2 text-sm leading-6 outline-none disabled:cursor-not-allowed"}),e.jsx("button",{type:"button",onClick:(()=>void g0()),disabled:!S.trim()||T||(n==null?void 0:n.runtime_state)!=="online",className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-sky-500 text-white shadow-md shadow-sky-100 transition hover:bg-sky-600 disabled:cursor-not-allowed disabled:bg-slate-300 disabled:shadow-none","aria-label":"发送消息",children:T?e.jsx(r0,{className:"h-4 w-4 animate-spin"}):e.jsx(pe,{className:"h-4 w-4"})})]})]})]}):e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center text-center",children:[e.jsx(L0,{className:"h-12 w-12 text-slate-300"}),e.jsx("h3",{className:"mt-4 font-black text-slate-700",children:"选择一个用户开始聊天"}),e.jsx("p",{className:"mt-1 text-sm text-slate-400",children:"该账号的新消息会实时出现在左侧列表。"})]})})]})]})};export{ve as default}; diff --git a/internal/webui/static/assets/Chat-DSkOtUaB.js b/internal/webui/static/assets/Chat-DSkOtUaB.js new file mode 100644 index 0000000..ba897df --- /dev/null +++ b/internal/webui/static/assets/Chat-DSkOtUaB.js @@ -0,0 +1 @@ +import{j as e,c as ee,r as i}from"./react-vendor-C_od1ZSF.js";import{g as b0,a as J0,b as te}from"./index-hByDAHGj.js";import{o as B0}from"./contract-COFcZjyb.js";import{L as r0,ak as se,al as ae,M as L0,I as ie,R as ne,ad as I0,k as re,am as ce,s as le,an as oe,ao as pe,ah as me}from"./icons-vendor-CvzvbbIV.js";const Q0=[["尊嘟假嘟","https://img.alicdn.com/imgextra/i2/O1CN01hWzOgD1KcmFEIaGwE_!!6000000001185-2-tps-64-64.png_110x10000.jpg_.webp"],["鸡哔你","https://img.alicdn.com/imgextra/i1/O1CN01P9TVJl1JCqCZcQIdW_!!6000000000993-2-tps-64-64.png_110x10000.jpg_.webp"],["谁懂啊","https://img.alicdn.com/imgextra/i1/O1CN01r9qUnx1g3tcrtSmcs_!!6000000004087-2-tps-64-64.png_110x10000.jpg_.webp"],["吗喽","https://img.alicdn.com/imgextra/i4/O1CN01dTynZh1LnbIYTHI1D_!!6000000001344-2-tps-64-64.png_110x10000.jpg_.webp"],["功德+1","https://img.alicdn.com/imgextra/i1/O1CN01l1G5pS1IVn37pfQJi_!!6000000000899-2-tps-64-64.png_110x10000.jpg_.webp"],["city不city啊","https://img.alicdn.com/imgextra/i2/O1CN01zRjPTR29lWHqabmDA_!!6000000008108-2-tps-64-64.png_110x10000.jpg_.webp"],["激推","https://img.alicdn.com/imgextra/i3/O1CN01ADTJ6u1khypfxbfnQ_!!6000000004716-2-tps-64-64.png_110x10000.jpg_.webp"],["微笑","https://img.alicdn.com/imgextra/i1/O1CN017b61R51wRk2lVV7vx_!!6000000006305-2-tps-980-980.png_110x10000.jpg_.webp"],["龇牙","https://img.alicdn.com/imgextra/i2/O1CN01nmOh4S22Yxz8IdEVf_!!6000000007133-2-tps-980-980.png_110x10000.jpg_.webp"],["流泪","https://img.alicdn.com/imgextra/i2/O1CN01Ec1EaL1zqQETcM2dX_!!6000000006765-2-tps-980-980.png_110x10000.jpg_.webp"],["尴尬","https://img.alicdn.com/imgextra/i2/O1CN01UrWH7a1ZVBrgRYXlc_!!6000000003199-2-tps-980-980.png_110x10000.jpg_.webp"],["撇嘴","https://img.alicdn.com/imgextra/i2/O1CN01Sr7o2b1lUWg5KfOD8_!!6000000004822-2-tps-980-980.png_110x10000.jpg_.webp"],["破涕为笑","https://img.alicdn.com/imgextra/i4/O1CN01pPetah1gkwndfn7Fs_!!6000000004181-2-tps-980-980.png_110x10000.jpg_.webp"],["捂脸哭","https://img.alicdn.com/imgextra/i2/O1CN0170KgpE1dE1TuQgd66_!!6000000003703-2-tps-980-980.png_110x10000.jpg_.webp"],["害羞","https://img.alicdn.com/imgextra/i3/O1CN01ZoB0Lb1ps7XpqP8PQ_!!6000000005415-2-tps-980-980.png_110x10000.jpg_.webp"],["感动","https://img.alicdn.com/imgextra/i2/O1CN01wqD4ly29yndR3Qp3A_!!6000000008137-2-tps-980-980.png_110x10000.jpg_.webp"],["滴泪","https://img.alicdn.com/imgextra/i1/O1CN01MpkJ3L1oUTTqfryOn_!!6000000005228-2-tps-980-980.png_110x10000.jpg_.webp"],["暗中观察","https://img.alicdn.com/imgextra/i1/O1CN010LO9yj272W07GlLls_!!6000000007739-2-tps-980-980.png_110x10000.jpg_.webp"],["偷笑","https://img.alicdn.com/imgextra/i4/O1CN01vJtO031g818IuYO7x_!!6000000004096-2-tps-980-980.png_110x10000.jpg_.webp"],["ok","https://img.alicdn.com/imgextra/i3/O1CN01QRkqDF25tz0WcANje_!!6000000007585-2-tps-980-980.png_110x10000.jpg_.webp"],["送花","https://img.alicdn.com/imgextra/i2/O1CN01PpzBNX1JNpeJBWnvr_!!6000000001017-2-tps-980-980.png_110x10000.jpg_.webp"],["大哭","https://img.alicdn.com/imgextra/i4/O1CN014TiaNb1ViEgNvRrTB_!!6000000002686-2-tps-980-980.png_110x10000.jpg_.webp"],["色","https://img.alicdn.com/imgextra/i2/O1CN01840t1B1JaCLGvHnBK_!!6000000001044-2-tps-980-980.png_110x10000.jpg_.webp"],["惊慌","https://img.alicdn.com/imgextra/i1/O1CN01mnqO7G1LAfUnfAN2U_!!6000000001259-2-tps-980-980.png_110x10000.jpg_.webp"],["惊讶","https://img.alicdn.com/imgextra/i3/O1CN0127IeyS1Kw0p0P4jzI_!!6000000001227-2-tps-980-980.png_110x10000.jpg_.webp"],["得意","https://img.alicdn.com/imgextra/i4/O1CN018QUnFv1WpOUES9POZ_!!6000000002837-2-tps-980-980.png_110x10000.jpg_.webp"],["睡","https://img.alicdn.com/imgextra/i2/O1CN01RprGZl1lqVgnEJLCx_!!6000000004870-2-tps-980-980.png_110x10000.jpg_.webp"],["不好意思","https://img.alicdn.com/imgextra/i3/O1CN01rMJJgn1SUXzuVpUhO_!!6000000002250-2-tps-980-980.png_110x10000.jpg_.webp"],["托腮","https://img.alicdn.com/imgextra/i1/O1CN01w3reBU1d3wlgOBtyZ_!!6000000003681-2-tps-980-980.png_110x10000.jpg_.webp"],["发怒","https://img.alicdn.com/imgextra/i2/O1CN013Wzy8d2A8PxGJZPpT_!!6000000008158-2-tps-980-980.png_110x10000.jpg_.webp"],["难过","https://img.alicdn.com/imgextra/i2/O1CN01zcwaSh1G9gZCFuFal_!!6000000000580-2-tps-980-980.png_110x10000.jpg_.webp"],["调皮","https://img.alicdn.com/imgextra/i3/O1CN01Zd1YHi1TI0lwpBe8c_!!6000000002358-2-tps-980-980.png_110x10000.jpg_.webp"],["愉快","https://img.alicdn.com/imgextra/i2/O1CN0145wDk21SWpyjTvsvA_!!6000000002255-2-tps-980-980.png_110x10000.jpg_.webp"],["白眼","https://img.alicdn.com/imgextra/i4/O1CN01nexGth1hwEAT1SHO2_!!6000000004341-2-tps-980-980.png_110x10000.jpg_.webp"],["拒绝","https://img.alicdn.com/imgextra/i2/O1CN01nqusqS1uHXzoUcpXr_!!6000000006012-2-tps-980-980.png_110x10000.jpg_.webp"],["期待","https://img.alicdn.com/imgextra/i3/O1CN01M44QY11Oh8Q5PdMIx_!!6000000001736-2-tps-980-980.png_110x10000.jpg_.webp"],["困","https://img.alicdn.com/imgextra/i4/O1CN01J4hFFz1Y9pmNdBq76_!!6000000003017-2-tps-980-980.png_110x10000.jpg_.webp"],["流汗","https://img.alicdn.com/imgextra/i4/O1CN01BU3NZ21gdcSjkqnST_!!6000000004165-2-tps-980-980.png_110x10000.jpg_.webp"],["憨笑","https://img.alicdn.com/imgextra/i2/O1CN01Pee9Ql1SJ661eH9By_!!6000000002225-2-tps-980-980.png_110x10000.jpg_.webp"],["耶","https://img.alicdn.com/imgextra/i2/O1CN01pFicsL1ipBhIqzcgs_!!6000000004461-2-tps-980-980.png_110x10000.jpg_.webp"],["奋斗","https://img.alicdn.com/imgextra/i3/O1CN01ZhQ4AV25xBmTK3CnF_!!6000000007592-2-tps-980-980.png_110x10000.jpg_.webp"],["咒骂","https://img.alicdn.com/imgextra/i3/O1CN01r1Zh9927QKb4pnf7k_!!6000000007791-2-tps-980-980.png_110x10000.jpg_.webp"],["疑问","https://img.alicdn.com/imgextra/i4/O1CN01UZqbzt29MmlNctCQS_!!6000000008054-2-tps-980-980.png_110x10000.jpg_.webp"],["嘘","https://img.alicdn.com/imgextra/i1/O1CN01qBlYkM1ojaYF75On5_!!6000000005261-2-tps-980-980.png_110x10000.jpg_.webp"],["晕","https://img.alicdn.com/imgextra/i2/O1CN014zhM2h1wPuSUFoMwV_!!6000000006301-2-tps-980-980.png_110x10000.jpg_.webp"],["开心到模糊","https://img.alicdn.com/imgextra/i1/O1CN01T1Dy271j6akZWo7Vr_!!6000000004499-2-tps-980-980.png_110x10000.jpg_.webp"],["衰","https://img.alicdn.com/imgextra/i1/O1CN01aOXsNr1LmgMvtyzOO_!!6000000001342-2-tps-980-980.png_110x10000.jpg_.webp"],["委屈","https://img.alicdn.com/imgextra/i2/O1CN013J0bMk1QNYih3UFTk_!!6000000001964-2-tps-980-980.png_110x10000.jpg_.webp"],["再见","https://img.alicdn.com/imgextra/i2/O1CN01IHKsQx1UdpFgeTHcA_!!6000000002541-2-tps-980-980.png_110x10000.jpg_.webp"],["鼓掌","https://img.alicdn.com/imgextra/i4/O1CN01DHxB5s1G1RRBxekIu_!!6000000000562-2-tps-980-980.png_110x10000.jpg_.webp"],["吐","https://img.alicdn.com/imgextra/i1/O1CN01xyVxH21LNUaMgW4hh_!!6000000001287-2-tps-980-980.png_110x10000.jpg_.webp"],["坏笑","https://img.alicdn.com/imgextra/i1/O1CN01zV7opv1bIU6iI8OhM_!!6000000003442-2-tps-980-980.png_110x10000.jpg_.webp"],["抠鼻","https://img.alicdn.com/imgextra/i1/O1CN01QOanju1sNqCrtYstu_!!6000000005755-2-tps-980-980.png_110x10000.jpg_.webp"],["叹气","https://img.alicdn.com/imgextra/i3/O1CN01RElx7R1QD1c8ZN07f_!!6000000001941-2-tps-980-980.png_110x10000.jpg_.webp"],["无聊","https://img.alicdn.com/imgextra/i2/O1CN01d91LnZ1UJDQjKCouC_!!6000000002496-2-tps-980-980.png_110x10000.jpg_.webp"],["思考","https://img.alicdn.com/imgextra/i2/O1CN01wQjg2f1tO84ZWitn9_!!6000000005891-2-tps-980-980.png_110x10000.jpg_.webp"],["呆","https://img.alicdn.com/imgextra/i1/O1CN01GLqBWC1DGbhqmpD2L_!!6000000000189-2-tps-980-980.png_110x10000.jpg_.webp"],["哇哦","https://img.alicdn.com/imgextra/i2/O1CN01MtLpS21qRO2bnAA5k_!!6000000005492-2-tps-980-980.png_110x10000.jpg_.webp"],["飞吻","https://img.alicdn.com/imgextra/i4/O1CN01q1WpFE25ljsNKjvHX_!!6000000007567-2-tps-980-980.png_110x10000.jpg_.webp"],["好喜欢","https://img.alicdn.com/imgextra/i2/O1CN01mD4iQM1O57XyQ5SHD_!!6000000001653-2-tps-980-980.png_110x10000.jpg_.webp"],["拜托","https://img.alicdn.com/imgextra/i4/O1CN01SQgrTH1dzCH3pIyRN_!!6000000003806-2-tps-980-980.png_110x10000.jpg_.webp"],["真棒","https://img.alicdn.com/imgextra/i2/O1CN017fcAmd1SCgYCj9Upk_!!6000000002211-2-tps-980-980.png_110x10000.jpg_.webp"],["流鼻血","https://img.alicdn.com/imgextra/i3/O1CN0139JscY1rC6RS9GR4j_!!6000000005594-2-tps-980-980.png_110x10000.jpg_.webp"],["费解","https://img.alicdn.com/imgextra/i1/O1CN01FqAVvR1tyJMPj13ie_!!6000000005970-2-tps-980-980.png_110x10000.jpg_.webp"],["秃头","https://img.alicdn.com/imgextra/i4/O1CN01ZF4bV11thMhqm2Z1h_!!6000000005933-2-tps-980-980.png_110x10000.jpg_.webp"],["嘿哈","https://img.alicdn.com/imgextra/i4/O1CN01ObcOw61FOVlvQg7Mw_!!6000000000477-2-tps-980-980.png_110x10000.jpg_.webp"],["吃土","https://img.alicdn.com/imgextra/i3/O1CN01Z6nJ1b1ZYr22YseHN_!!6000000003207-2-tps-980-980.png_110x10000.jpg_.webp"],["机智","https://img.alicdn.com/imgextra/i1/O1CN01rfKY351zDUZJlBiir_!!6000000006680-2-tps-980-980.png_110x10000.jpg_.webp"],["举杯","https://img.alicdn.com/imgextra/i4/O1CN01R2tn4F1mn8NuEIE8J_!!6000000004998-2-tps-980-980.png_110x10000.jpg_.webp"],["握手","https://img.alicdn.com/imgextra/i4/O1CN01NDcA251JDkvuFhSDb_!!6000000000995-2-tps-980-980.png_110x10000.jpg_.webp"],["挥手","https://img.alicdn.com/imgextra/i4/O1CN01iVN0ht1TmEuSwauGt_!!6000000002424-2-tps-980-980.png_110x10000.jpg_.webp"],["yeah","https://img.alicdn.com/imgextra/i3/O1CN01opt7hh27Wk8omjR4t_!!6000000007805-2-tps-980-980.png_110x10000.jpg_.webp"],["666","https://img.alicdn.com/imgextra/i3/O1CN01YRWDPF1OjQOpXeuTC_!!6000000001741-2-tps-980-980.png_110x10000.jpg_.webp"],["棒","https://img.alicdn.com/imgextra/i3/O1CN01agprvs1HU7rPRxOnB_!!6000000000760-2-tps-980-980.png_110x10000.jpg_.webp"],["爱你","https://img.alicdn.com/imgextra/i1/O1CN01SzxgcH1GSSo6Lwmwk_!!6000000000621-2-tps-980-980.png_110x10000.jpg_.webp"],["比心","https://img.alicdn.com/imgextra/i1/O1CN01YHZ39t1DeQIeb0TWQ_!!6000000000241-2-tps-980-980.png_110x10000.jpg_.webp"],["感谢","https://img.alicdn.com/imgextra/i3/O1CN01ywacF81baLYNeyK1n_!!6000000003481-2-tps-980-980.png_110x10000.jpg_.webp"],["拍手","https://img.alicdn.com/imgextra/i4/O1CN01wbj4wv1K7ArD9AU44_!!6000000001116-2-tps-980-980.png_110x10000.jpg_.webp"],["拉钩","https://img.alicdn.com/imgextra/i1/O1CN01dePkKH1HOd6ivAcu8_!!6000000000748-2-tps-980-980.png_110x10000.jpg_.webp"],["没钱","https://img.alicdn.com/imgextra/i3/O1CN01qhxGjp1zD2AfqmWx5_!!6000000006679-2-tps-980-980.png_110x10000.jpg_.webp"],["小刀","https://img.alicdn.com/imgextra/i3/O1CN01tFVx5Y1T2thPjhR6b_!!6000000002325-2-tps-980-980.png_110x10000.jpg_.webp"],["不刀","https://img.alicdn.com/imgextra/i4/O1CN01zTxff61clcvOcTS3n_!!6000000003641-2-tps-980-980.png_110x10000.jpg_.webp"],["同出","https://img.alicdn.com/imgextra/i3/O1CN01URKas6249R8ozS98O_!!6000000007348-2-tps-980-980.png_110x10000.jpg_.webp"],["递钱","https://img.alicdn.com/imgextra/i4/O1CN01PzhgV51FLlOaZHZ6n_!!6000000000471-2-tps-980-980.png_110x10000.jpg_.webp"],["数钱","https://img.alicdn.com/imgextra/i3/O1CN01CzXXvp23khkljToQH_!!6000000007294-2-tps-980-980.png_110x10000.jpg_.webp"],["打call","https://img.alicdn.com/imgextra/i1/O1CN01X7VUVm1il48IYv8Qw_!!6000000004452-2-tps-980-980.png_110x10000.jpg_.webp"],["号外","https://img.alicdn.com/imgextra/i2/O1CN01vg6xSM1Vxo9EKyfjR_!!6000000002720-2-tps-980-980.png_110x10000.jpg_.webp"],["包邮","https://img.alicdn.com/imgextra/i3/O1CN01yVS7ys24jA22oVZ2T_!!6000000007426-2-tps-980-980.png_110x10000.jpg_.webp"],["求赞","https://img.alicdn.com/imgextra/i1/O1CN01Xwqi5A1giCQMRcX6N_!!6000000004175-2-tps-980-980.png_110x10000.jpg_.webp"],["非主流","https://img.alicdn.com/imgextra/i1/O1CN013wyI1j1hlEfDUoATI_!!6000000004317-2-tps-980-980.png_110x10000.jpg_.webp"],["吃瓜","https://img.alicdn.com/imgextra/i1/O1CN01LLOFsh1UUCw0deZba_!!6000000002520-2-tps-980-980.png_110x10000.jpg_.webp"],["种草","https://img.alicdn.com/imgextra/i2/O1CN01ooeRC81hA8a4x9S3q_!!6000000004236-2-tps-980-980.png_110x10000.jpg_.webp"],["佛系","https://img.alicdn.com/imgextra/i4/O1CN01BYXEe321GMHMZ9w66_!!6000000006957-2-tps-980-980.png_110x10000.jpg_.webp"],["超便宜","https://img.alicdn.com/imgextra/i4/O1CN01mqgSZi1Er4rOIDiP7_!!6000000000404-2-tps-980-980.png_110x10000.jpg_.webp"],["拥抱","https://img.alicdn.com/imgextra/i1/O1CN01yuGD9c1hJkttfKHAm_!!6000000004257-2-tps-980-980.png_110x10000.jpg_.webp"],["摊手","https://img.alicdn.com/imgextra/i2/O1CN014AiIqE1o9repE6STR_!!6000000005183-2-tps-980-980.png_110x10000.jpg_.webp"],["举手","https://img.alicdn.com/imgextra/i1/O1CN01xizuHZ1WPkJCogbuj_!!6000000002781-2-tps-980-980.png_110x10000.jpg_.webp"],["蹲","https://img.alicdn.com/imgextra/i3/O1CN01Midjjn1FrMj2CWer6_!!6000000000540-2-tps-980-980.png_110x10000.jpg_.webp"],["跪了","https://img.alicdn.com/imgextra/i3/O1CN01F2y52j24E16L6RIjF_!!6000000007358-2-tps-980-980.png_110x10000.jpg_.webp"],["拜","https://img.alicdn.com/imgextra/i4/O1CN01Jldd1G1oXDrEHH2qr_!!6000000005234-2-tps-980-980.png_110x10000.jpg_.webp"],["排","https://img.alicdn.com/imgextra/i3/O1CN01uSUmYD1jD0IJf0UVU_!!6000000004513-2-tps-980-980.png_110x10000.jpg_.webp"],["旺财","https://img.alicdn.com/imgextra/i3/O1CN01A25Mv01DKjGseAmuP_!!6000000000198-2-tps-980-980.png_110x10000.jpg_.webp"],["招财猫","https://img.alicdn.com/imgextra/i3/O1CN01WmJ7Sr20EhDyp86Bd_!!6000000006818-2-tps-980-980.png_110x10000.jpg_.webp"],["酸了","https://img.alicdn.com/imgextra/i3/O1CN01UFgjn61JJi5Iqxdk7_!!6000000001008-2-tps-980-980.png_110x10000.jpg_.webp"],["鸭鸭","https://img.alicdn.com/imgextra/i3/O1CN01pHSCSQ1deaS8WDiqG_!!6000000003761-2-tps-980-980.png_110x10000.jpg_.webp"],["方了","https://img.alicdn.com/imgextra/i3/O1CN01br7g711whlu8xOPUt_!!6000000006340-2-tps-980-980.png_110x10000.jpg_.webp"],["白菜","https://img.alicdn.com/imgextra/i1/O1CN01KABFLt24WKwXjVp08_!!6000000007398-2-tps-980-980.png_110x10000.jpg_.webp"],["桃子","https://img.alicdn.com/imgextra/i1/O1CN01CQhhPH1vJfRjDGBv5_!!6000000006152-2-tps-980-980.png_110x10000.jpg_.webp"],["打包","https://img.alicdn.com/imgextra/i3/O1CN01oYOkUI1VT7c0ivZHV_!!6000000002653-2-tps-980-980.png_110x10000.jpg_.webp"],["沙发","https://img.alicdn.com/imgextra/i4/O1CN018qUFaE1DGbhqpMIit_!!6000000000189-2-tps-980-980.png_110x10000.jpg_.webp"],["南","https://img.alicdn.com/imgextra/i1/O1CN01ZSA6wg1PEZKf4h99R_!!6000000001809-2-tps-980-980.png_110x10000.jpg_.webp"],["盯","https://img.alicdn.com/imgextra/i4/O1CN01OWB1Gx1s01bzBhHN6_!!6000000005703-2-tps-980-980.png_110x10000.jpg_.webp"],["hot","https://img.alicdn.com/imgextra/i4/O1CN01DDD9uA22cAl7VDH7d_!!6000000007140-2-tps-980-980.png_110x10000.jpg_.webp"],["new","https://img.alicdn.com/imgextra/i3/O1CN01rRJXJo1qwzN4YnOHX_!!6000000005561-2-tps-980-980.png_110x10000.jpg_.webp"],["cool","https://img.alicdn.com/imgextra/i4/O1CN013bUubF2855qb2Qt5l_!!6000000007880-2-tps-980-980.png_110x10000.jpg_.webp"],["1","https://img.alicdn.com/imgextra/i1/O1CN01U8XG5y1Ie22frQHCQ_!!6000000000917-2-tps-980-980.png_110x10000.jpg_.webp"],["可","https://img.alicdn.com/imgextra/i2/O1CN01SMjtPG1iJaN17p94N_!!6000000004392-2-tps-980-980.png_110x10000.jpg_.webp"],["搬砖","https://img.alicdn.com/imgextra/i1/O1CN01GbqW6G1LOrm0Gllcb_!!6000000001290-2-tps-980-980.png_110x10000.jpg_.webp"],["菜狗","https://img.alicdn.com/imgextra/i2/O1CN01VtN0t91USNLmvfmol_!!6000000002516-2-tps-980-980.png_110x10000.jpg_.webp"],["开心面具","https://img.alicdn.com/imgextra/i3/O1CN017elkpk22EoYlBPKd3_!!6000000007089-2-tps-980-980.png_110x10000.jpg_.webp"],["快递","https://img.alicdn.com/imgextra/i2/O1CN01AmUZXk1d3wle5O8IJ_!!6000000003681-2-tps-980-980.png_110x10000.jpg_.webp"],["裂开","https://img.alicdn.com/imgextra/i1/O1CN01BihwvO1a5N9bFt0LU_!!6000000003278-2-tps-980-980.png_110x10000.jpg_.webp"],["啤酒","https://img.alicdn.com/imgextra/i4/O1CN01jDkgEj1WvLdXUVBDx_!!6000000002850-2-tps-980-980.png_110x10000.jpg_.webp"],["瑞思拜","https://img.alicdn.com/imgextra/i4/O1CN011gR0Um1K3VgpYjPOi_!!6000000001108-2-tps-980-980.png_110x10000.jpg_.webp"],["小丑","https://img.alicdn.com/imgextra/i3/O1CN01jMikhO1NJUM15XKTf_!!6000000001549-2-tps-980-980.png_110x10000.jpg_.webp"],["爱心","https://img.alicdn.com/imgextra/i1/O1CN015RVSWf23s25eETJqO_!!6000000007310-2-tps-980-980.png_110x10000.jpg_.webp"]],ge=r=>r,de=new Map(Q0.map(([r,m])=>[r,m])),xe=r=>r.split(/(\[[^\]]+\])/g).map((m,t)=>{const n=m.startsWith("[")?de.get(m.slice(1,-1)):void 0;return n?e.jsx("img",{src:n,alt:m,title:m,className:"mx-0.5 inline-block h-7 w-7 align-middle"},t):e.jsx(ee.Fragment,{children:m},t)}),_e=async r=>b0("/api/v1/accounts/details",void 0,r),U0=async r=>b0("/api/v1/accounts/runtime-status",void 0,r),M0=async(r,m,t,n=!1)=>{const x=await b0("/api/v1/chat/sessions",{account_id:r,cursor:m,refresh:n?1:void 0},n?{timeoutMs:6e4,...t}:t),w=B0(x,["data","result"])||{};return{sessions:w.sessions||[],has_more:w.has_more===!0,next_cursor:w.next_cursor}},A0=async(r,m,t,n,x)=>{const w=await b0("/api/v1/chat/messages",{account_id:r,chat_id:m,cursor:t,before_id:n},x),u=B0(w,["data","result"])||{};return{messages:u.messages||[],has_more:u.has_more===!0,next_cursor:u.next_cursor,session:u.session}},ue=async(r,m)=>J0("/api/v1/chat/messages",r,m),he=async(r,m)=>{const t=new FormData;return Object.entries(r).forEach(([n,x])=>t.append(n,x)),te("/api/v1/chat/images",t,{timeoutMs:12e4,...m})},H0=async(r,m,t,n)=>J0("/api/v1/chat/read",{account_id:r,chat_id:m,message_ids:t},n),F0=(r,m)=>r.filter(t=>t.direction==="incoming"&&t.message_type!=="system"&&!t.message_key.startsWith("in-")).map(t=>({messageId:t.message_key,sessionId:m,cid:`${m}@goofish`,conversationType:1})),be=(r,m,t)=>{const n=m.trim().toLowerCase();return r.filter(x=>t&&x.unread_count<=0?!1:n?[x.buyer_name,x.buyer_id,x.item_title,x.last_message].some(w=>(w||"").toLowerCase().includes(n)):!0)},fe=(r,m)=>{const t=new Set(r.map(n=>n.message_key));return[...m.filter(n=>!t.has(n.message_key)),...r]},q0=(r,m)=>{const t=r.findIndex(n=>n.message_key===m.message_key);return t<0?[...r,m]:r.map((n,x)=>x===t?m:n)},N=(r,m,t)=>r===m&&!t.aborted,P=r=>r instanceof Error&&r.message==="请求已取消",je=r=>{if(!r)return"";const m=new Date(r<1e10?r*1e3:r),t=new Date;return m.toDateString()===t.toDateString()?m.toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit",hour12:!1}):m.toLocaleDateString("zh-CN",{month:"2-digit",day:"2-digit"})},we=r=>new Date(r<1e10?r*1e3:r).toLocaleString("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),Ne=()=>{const[r,m]=i.useState([]),[t,n]=i.useState(""),[x,w]=i.useState({}),[u,V]=i.useState(""),[D,S]=i.useState([]),[W,f0]=i.useState(""),[M,j0]=i.useState(!1),[q,c0]=i.useState(""),[w0,T]=i.useState(!0),[A,I]=i.useState(!1),[G,X]=i.useState(!1),[Y,l0]=i.useState(!1),[o0,p0]=i.useState(),[K,H]=i.useState({}),[$,e0]=i.useState({}),[t0,m0]=i.useState(!1),[g0,N0]=i.useState(!1),[y,F]=i.useState(!1),[C0,C]=i.useState(""),[y0,J]=i.useState("connecting"),[B,s0]=i.useState(null),[a,j]=i.useState(null),O=i.useRef(""),Q=i.useRef(""),d0=i.useRef(null),O0=i.useRef({accountID:"",chatID:""}),v0=i.useRef(!0),Z=i.useRef(!1),k0=i.useRef(null),T0=i.useRef(new Set),S0=i.useRef(0),R0=i.useRef(null),L=i.useRef(0),E0=i.useRef(null),U=i.useRef(0),a0=i.useRef(null),i0=i.useRef(0),x0=i.useRef(null),R=i.useRef(0),z=i.useRef(null);i.useEffect(()=>{O.current=t},[t]),i.useEffect(()=>{Q.current=u},[u]);const n0=i.useCallback(async s=>{var l;const o=++S0.current;(l=R0.current)==null||l.abort();const p=new AbortController;R0.current=p;try{const c=await M0(s,void 0,{signal:p.signal},!0);if(!N(S0.current,o,p.signal))return[];const d=c.sessions.map(g=>s===O.current&&g.chat_id===Q.current?{...g,unread_count:0}:g);return w(g=>({...g,[s]:d})),H(g=>({...g,[s]:c.next_cursor})),e0(g=>({...g,[s]:c.has_more})),d}catch(c){return N(S0.current,o,p.signal)&&!P(c)&&C(c instanceof Error?c.message:"同步会话失败"),[]}},[]);i.useEffect(()=>{const s=new AbortController;return(async()=>{var p;T(!0);try{const[l,c]=await Promise.all([_e({signal:s.signal}),U0({signal:s.signal})]),g=l.map(h=>{var v,D0;return{...h,runtime_state:((v=c[h.id])==null?void 0:v.state)||(h.enabled?"connecting":"disabled"),runtime_connected:((D0=c[h.id])==null?void 0:D0.connected)===!0}}).filter(h=>h.enabled),f=await Promise.all(g.map(async h=>[h.id,await M0(h.id,void 0,{signal:s.signal})]));if(s.signal.aborted)return;m(g),w(Object.fromEntries(f.map(([h,v])=>[h,v.sessions]))),H(Object.fromEntries(f.map(([h,v])=>[h,v.next_cursor]))),e0(Object.fromEntries(f.map(([h,v])=>[h,v.has_more])));const _=window.localStorage.getItem("ydisks.chat.account.v1")||"",k=g.some(h=>h.id===_)?_:((p=g[0])==null?void 0:p.id)||"";n(k)}catch(l){s.signal.aborted||C(l instanceof Error?l.message:"加载聊天数据失败")}finally{s.signal.aborted||T(!1)}})(),(()=>s.abort())},[]),i.useEffect(()=>{let s=!1,o=0,p=null;const l=async()=>{p=new AbortController;try{const c=await U0({signal:p.signal,timeoutMs:1e4});s||m(d=>d.map(g=>{var f,_;return{...g,runtime_state:((f=c[g.id])==null?void 0:f.state)||g.runtime_state,runtime_connected:((_=c[g.id])==null?void 0:_.connected)??g.runtime_connected}}))}catch{}finally{s||(o=window.setTimeout(l,3e3))}};return o=window.setTimeout(l,3e3),(()=>{s=!0,window.clearTimeout(o),p==null||p.abort()})},[]),i.useEffect(()=>{if(!t)return;window.localStorage.setItem("ydisks.chat.account.v1",t);const s=x[t]||[];V(o=>{var p;return s.some(l=>l.chat_id===o)?o:((p=s[0])==null?void 0:p.chat_id)||""})},[t,x]),i.useEffect(()=>{!t||T0.current.has(t)||(T0.current.add(t),n0(t))},[t,n0]),i.useEffect(()=>{var p,l;if(!t||!u){L.current+=1,U.current+=1,(p=a0.current)==null||p.abort(),Z.current=!1,S([]);return}const s=++L.current;(l=E0.current)==null||l.abort();const o=new AbortController;return E0.current=o,I(!0),A0(t,u,void 0,void 0,{signal:o.signal}).then(c=>{if(!N(L.current,s,o.signal))return;const d=F0(c.messages,u);H0(t,u,d,{signal:o.signal}),S(c.messages),l0(c.has_more),p0(c.next_cursor),c.session&&w(g=>({...g,[t]:(g[t]||[]).map(f=>{var _;return f.chat_id===((_=c.session)==null?void 0:_.chat_id)?c.session:f})})),w(g=>({...g,[t]:(g[t]||[]).map(f=>f.chat_id===u?{...f,unread_count:0}:f)}))}).catch(c=>{N(L.current,s,o.signal)&&!P(c)&&C(c instanceof Error?c.message:"加载消息失败")}).finally(()=>{N(L.current,s,o.signal)&&I(!1)}),(()=>o.abort())},[t,u]),i.useEffect(()=>{var s;(s=x0.current)==null||s.abort(),i0.current+=1},[t]),i.useEffect(()=>{var s;(s=z.current)==null||s.abort(),R.current+=1},[t,u]),i.useEffect(()=>{var s;U.current+=1,(s=a0.current)==null||s.abort(),Z.current=!1},[t,u]),i.useEffect(()=>(()=>{var s,o,p,l,c;(s=R0.current)==null||s.abort(),(o=E0.current)==null||o.abort(),U.current+=1,(p=a0.current)==null||p.abort(),(l=x0.current)==null||l.abort(),(c=z.current)==null||c.abort()}),[]);const Z0=i.useCallback(async()=>{var d,g;if(!t||!u||G||!Y)return;const s=d0.current,o=(s==null?void 0:s.scrollHeight)||0,p=L.current,l=++U.current;(d=a0.current)==null||d.abort();const c=new AbortController;a0.current=c,Z.current=!0,X(!0),C("");try{const f=(g=D[0])==null?void 0:g.id,_=await A0(t,u,o0,f,{signal:c.signal});if(!N(L.current,p,c.signal)||l!==U.current)return;S(k=>fe(k,_.messages)),l0(_.has_more),p0(_.next_cursor),requestAnimationFrame(()=>{l===U.current&&!c.signal.aborted&&s&&(s.scrollTop+=s.scrollHeight-o)})}catch(f){Z.current=!1,P(f)||C(f instanceof Error?f.message:"加载历史消息失败")}finally{l===U.current&&X(!1)}},[t,u,Y,o0,D,G]);i.useEffect(()=>{let s=!1,o=0,p=0,l=null;const c=()=>{if(s)return;J("connecting");const d=window.location.protocol==="https:"?"wss:":"ws:";l=new WebSocket(`${d}//${window.location.host}/api/v1/chat/ws`),l.onopen=()=>{p=0,J("online")},l.onmessage=g=>{try{const _=JSON.parse(g.data).message;if(!_)return;const k=_.account_id;if(w(h=>{const v=h[k]||[];return v.some(E=>E.chat_id===_.chat_id)?{...h,[k]:v.map(E=>E.chat_id===_.chat_id?{...E,last_message:_.content,last_message_at:_.sent_at,unread_count:_.direction==="incoming"&&_.message_type!=="system"&&(O.current!==k||Q.current!==_.chat_id)?E.unread_count+1:E.unread_count}:E).sort((E,$0)=>$0.last_message_at-E.last_message_at)}:(n0(k),h)}),O.current===k&&Q.current===_.chat_id&&(S(h=>q0(h,_)),_.direction==="incoming"&&_.message_type!=="system")){const h=F0([_],_.chat_id);H0(k,_.chat_id,h)}}catch{}},l.onclose=()=>{if(s)return;J("offline");const g=Math.min(15e3,1e3*2**Math.min(p++,4));o=window.setTimeout(c,g)},l.onerror=()=>l==null?void 0:l.close()};return c(),(()=>{s=!0,window.clearTimeout(o),l==null||l.close()})},[n0]);const z0=i.useCallback(()=>{const s=d0.current;if(!s)return;const o=s.scrollHeight-s.scrollTop-s.clientHeight;v0.current=o<=48},[]);i.useLayoutEffect(()=>{const s=O0.current.accountID!==t||O0.current.chatID!==u;O0.current={accountID:t,chatID:u},s&&(v0.current=!0);const o=d0.current;if(o){if(Z.current){Z.current=!1;return}(A||v0.current)&&(o.scrollTop=o.scrollHeight)}},[t,u,D,A]);const P0=r.find(s=>s.id===t),_0=x[t]||[],b=_0.find(s=>s.chat_id===u),V0=i.useMemo(()=>be(_0,W,M),[_0,W,M]),W0=i.useCallback(s=>(x[s]||[]).reduce((o,p)=>o+p.unread_count,0),[x]),G0=i.useCallback(async()=>{var l;if(!t||t0||!$[t])return;const s=++i0.current;(l=x0.current)==null||l.abort();const o=new AbortController;x0.current=o;const p=t;m0(!0),C("");try{const c=await M0(p,K[p],{signal:o.signal},!0);if(!N(i0.current,s,o.signal))return;w(d=>({...d,[p]:c.sessions})),H(d=>({...d,[p]:c.next_cursor})),e0(d=>({...d,[p]:c.has_more}))}catch(c){N(i0.current,s,o.signal)&&!P(c)&&C(c instanceof Error?c.message:"加载历史联系人失败")}finally{N(i0.current,s,o.signal)&&m0(!1)}},[t,K,t0,$]),u0=i.useCallback(async(s,o)=>{var c;if(!b||!t||y)return;const p=++R.current;(c=z.current)==null||c.abort();const l=new AbortController;z.current=l,F(!0),C("");try{const d=await ue({account_id:t,chat_id:b.chat_id,buyer_id:b.buyer_id,buyer_name:b.buyer_name,item_id:b.item_id,item_title:b.item_title,text:s},{signal:l.signal});if(!N(R.current,p,l.signal))return;c0(""),s0(null),S(g=>q0(g,d.message))}catch(d){N(R.current,p,l.signal)&&(o&&s0(s),P(d)||C(d instanceof Error?d.message:"消息发送失败"))}finally{N(R.current,p,l.signal)&&F(!1)}},[t,b,y]),h0=i.useCallback(async(s,o)=>{var c;if(!b||!t||y)return;const p=++R.current;(c=z.current)==null||c.abort();const l=new AbortController;z.current=l,F(!0),C("");try{const d=await he({account_id:t,chat_id:b.chat_id,buyer_id:b.buyer_id,buyer_name:b.buyer_name,buyer_avatar_url:b.buyer_avatar_url,item_id:b.item_id,item_title:b.item_title,image:s},{signal:l.signal});if(!N(R.current,p,l.signal))return;j(null),S(g=>q0(g,d.message))}catch(d){N(R.current,p,l.signal)&&(o&&j(s),P(d)||C(d instanceof Error?d.message:"图片发送失败"))}finally{N(R.current,p,l.signal)&&(F(!1),k0.current&&(k0.current.value=""))}},[t,b,y]),X0=i.useCallback(async()=>{const s=q.trim();!s||!b||!t||y||await u0(s,!0)},[t,q,b,u0,y]),Y0=i.useCallback(async s=>{!s||!b||!t||y||await h0(s,!0)},[t,b,h0,y]),K0=i.useCallback(async()=>{B?await u0(B,!1):a&&await h0(a,!1)},[a,B,h0,u0]);return{accounts:r,activeAccountID:t,activeSessions:_0,selectedSession:b,activeAccount:P0,messages:D,search:W,unreadOnly:M,draft:q,loading:w0,messagesLoading:A,olderLoading:G,hasOlder:Y,contactsLoading:t0,hasMoreContacts:$[t]===!0,emojiOpen:g0,sending:y,error:C0,liveState:y0,activeChatID:u,filteredSessions:V0,scrollRef:d0,imageInputRef:k0,setActiveAccountID:n,setActiveChatID:V,setSearch:f0,setUnreadOnly:j0,setDraft:c0,setEmojiOpen:N0,reloadSessions:n0,loadMoreContacts:G0,loadOlderMessages:Z0,handleMessageScroll:z0,handleSend:X0,handleImage:Y0,retrySend:K0,retryAvailable:!!(B||a),unreadForAccount:W0,emojiURL:ge,xianyuEmojis:Q0,renderXianyuText:xe,formatClock:je,messageTime:we}},ke=()=>{const{accounts:r,activeAccountID:m,activeChatID:t,activeAccount:n,selectedSession:x,filteredSessions:w,messages:u,search:V,unreadOnly:D,draft:S,loading:W,messagesLoading:f0,olderLoading:M,hasOlder:j0,contactsLoading:q,hasMoreContacts:c0,emojiOpen:w0,sending:T,error:A,liveState:I,scrollRef:G,imageInputRef:X,setActiveAccountID:Y,setActiveChatID:l0,setSearch:o0,setUnreadOnly:p0,setDraft:K,setEmojiOpen:H,reloadSessions:$,loadMoreContacts:e0,loadOlderMessages:t0,handleMessageScroll:m0,handleSend:g0,handleImage:N0,retrySend:y,retryAvailable:F,unreadForAccount:C0,emojiURL:C,xianyuEmojis:y0,renderXianyuText:J,formatClock:B,messageTime:s0}=Ne();return W?e.jsx("div",{className:"flex h-[calc(100vh-4rem)] items-center justify-center",children:e.jsx(r0,{className:"h-8 w-8 animate-spin text-sky-500"})}):e.jsxs("section",{className:"flex h-[calc(100vh-4rem)] min-h-[560px] flex-col overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-chat",children:[e.jsxs("header",{className:"border-b border-slate-200 bg-slate-50/70 px-5 pt-4",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-black tracking-tight text-slate-950",children:"在线聊天"}),e.jsx("p",{className:"mt-0.5 text-xs font-medium text-slate-500",children:"复用账号实时连接,消息按账号完全隔离"})]}),e.jsxs("div",{className:`flex items-center gap-2 rounded-full px-3 py-1.5 text-xs font-bold ${I==="online"?"bg-emerald-50 text-emerald-700":I==="connecting"?"bg-amber-50 text-amber-700":"bg-red-50 text-red-700"}`,children:[I==="online"?e.jsx(se,{className:"h-3.5 w-3.5"}):e.jsx(ae,{className:"h-3.5 w-3.5"}),I==="online"?"实时同步中":I==="connecting"?"正在连接":"连接已断开"]})]}),e.jsx("div",{className:"flex gap-1 overflow-x-auto pb-0",role:"tablist","aria-label":"聊天账号",children:r.map(a=>{const j=a.id===m,O=C0(a.id),Q=a.runtime_state==="online";return e.jsxs("button",{type:"button",role:"tab","aria-selected":j,onClick:(()=>Y(a.id)),className:`relative flex h-11 shrink-0 items-center gap-2 border-b-2 px-3 text-sm font-extrabold transition-colors ${j?"border-sky-500 text-sky-700":"border-transparent text-slate-500 hover:text-slate-900"}`,children:[e.jsx("span",{className:`h-2 w-2 rounded-full ${Q?"bg-emerald-500":"bg-slate-300"}`}),e.jsx("span",{className:"max-w-36 truncate",children:a.nickname||a.remark||a.id}),O>0&&e.jsx("span",{className:"min-w-5 rounded-full bg-red-500 px-1.5 py-0.5 text-[10px] text-white",children:O>99?"99+":O})]},a.id)})})]}),r.length===0?e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center text-center",children:[e.jsx(L0,{className:"h-12 w-12 text-slate-300"}),e.jsx("h3",{className:"mt-4 font-black text-slate-800",children:"暂无启用账号"}),e.jsx("p",{className:"mt-1 text-sm text-slate-500",children:"先在账号管理中启用账号,聊天会话会自动出现。"})]}):e.jsxs("div",{className:"grid min-h-0 flex-1 overflow-hidden grid-cols-[320px_minmax(0,1fr)]",children:[e.jsxs("aside",{className:"flex min-h-0 flex-col border-r border-slate-200 bg-slate-50/40",children:[e.jsxs("div",{className:"space-y-3 border-b border-slate-200 p-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ie,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400"}),e.jsx("input",{value:V,onChange:(a=>o0(a.target.value)),placeholder:"搜索用户、商品或消息",className:"h-10 w-full rounded-xl border border-slate-200 bg-white pl-9 pr-3 text-sm outline-none transition focus:border-sky-400 focus:ring-2 focus:ring-sky-100"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("button",{type:"button",onClick:(()=>p0(a=>!a)),className:`rounded-lg px-2.5 py-1.5 text-xs font-bold ${D?"bg-sky-100 text-sky-700":"text-slate-500 hover:bg-slate-100"}`,children:D?"只看未读":"全部会话"}),e.jsx("button",{type:"button",title:"刷新会话",onClick:(()=>void $(m)),className:"rounded-lg p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700",children:e.jsx(ne,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto",children:[w.map(a=>e.jsxs("button",{type:"button",onClick:(()=>l0(a.chat_id)),className:`flex w-full gap-3 border-b border-slate-100 p-4 text-left transition-colors ${a.chat_id===t?"bg-white shadow-chat-active":"hover:bg-white/80"}`,children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center overflow-hidden rounded-full bg-slate-200 text-slate-500",children:a.buyer_avatar_url?e.jsx("img",{src:a.buyer_avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx(I0,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate text-sm font-extrabold text-slate-900",children:a.buyer_name||`用户 ${a.buyer_id}`}),e.jsx("span",{className:"ml-auto shrink-0 text-[10px] font-medium text-slate-400",children:B(a.last_message_at)})]}),e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsx("span",{className:"truncate text-xs text-slate-500",children:a.last_message||"暂无消息"}),a.unread_count>0&&e.jsx("span",{className:"ml-auto min-w-5 shrink-0 rounded-full bg-red-500 px-1.5 py-0.5 text-center text-[10px] font-bold text-white",children:a.unread_count})]}),a.item_title&&e.jsxs("div",{className:"mt-1.5 truncate text-[10px] font-medium text-sky-700",children:["商品 · ",a.item_title]})]})]},a.chat_id)),w.length===0&&e.jsx("div",{className:"px-6 py-16 text-center text-sm text-slate-400",children:"当前账号暂无匹配会话"}),c0&&!V&&!D&&e.jsx("div",{className:"flex justify-center p-4",children:e.jsxs("button",{type:"button",onClick:(()=>void e0()),disabled:q,className:"flex items-center gap-2 rounded-full border border-slate-200 bg-white px-4 py-2 text-xs font-bold text-slate-500 shadow-sm hover:border-sky-200 hover:text-sky-600 disabled:opacity-50",children:[q&&e.jsx(r0,{className:"h-3.5 w-3.5 animate-spin"}),q?"正在加载":"加载更多历史联系人"]})})]})]}),e.jsx("main",{className:"flex min-h-0 min-w-0 flex-col overflow-hidden bg-surface-subtle",children:x?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex h-16 shrink-0 items-center border-b border-slate-200 bg-white px-5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-black text-slate-950",children:x.buyer_name||x.buyer_id}),e.jsxs("div",{className:"mt-0.5 truncate text-xs text-slate-500",children:["用户 ID:",x.buyer_id]})]}),e.jsx("span",{className:`ml-auto rounded-full px-2.5 py-1 text-[10px] font-bold ${(n==null?void 0:n.runtime_state)==="online"?"bg-emerald-50 text-emerald-700":"bg-slate-100 text-slate-500"}`,children:(n==null?void 0:n.runtime_state)==="online"?"账号在线":"账号离线"})]}),e.jsx("div",{ref:G,onScroll:m0,className:"min-h-0 flex-1 space-y-5 overflow-y-auto px-6 py-5",children:f0?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(r0,{className:"h-6 w-6 animate-spin text-sky-500"})}):e.jsxs(e.Fragment,{children:[j0&&e.jsx("div",{className:"flex justify-center pb-1",children:e.jsxs("button",{type:"button",onClick:(()=>void t0()),disabled:M,className:"flex items-center gap-2 rounded-full border border-slate-200 bg-white px-4 py-1.5 text-xs font-bold text-slate-500 shadow-sm transition hover:border-sky-200 hover:text-sky-600 disabled:opacity-50",children:[M&&e.jsx(r0,{className:"h-3.5 w-3.5 animate-spin"}),M?"正在加载":"加载更早消息"]})}),u.map(a=>{const j=a.direction==="outgoing";return a.message_type==="system"?e.jsx("div",{className:"flex justify-center py-1",children:e.jsxs("div",{className:"max-w-[82%] rounded-xl border border-slate-200 bg-slate-100 px-4 py-2 text-center text-xs leading-5 text-slate-500",children:[J(a.content),e.jsx("div",{className:"mt-1 text-[10px] text-slate-400",children:s0(a.sent_at)})]})},a.message_key):e.jsxs("div",{className:`flex items-end gap-2.5 ${j?"justify-end":"justify-start"}`,children:[!j&&e.jsx("div",{className:"h-9 w-9 shrink-0 overflow-hidden rounded-full bg-slate-200 ring-2 ring-white",children:x.buyer_avatar_url?e.jsx("img",{src:x.buyer_avatar_url,alt:x.buyer_name||"用户",className:"h-full w-full object-cover"}):e.jsx(I0,{className:"m-2 h-5 w-5 text-slate-500"})}),e.jsxs("div",{className:`max-w-[72%] ${j?"items-end":"items-start"} flex flex-col`,children:[e.jsx("div",{className:"mb-1 px-1 text-[10px] font-semibold text-slate-400",children:j?(n==null?void 0:n.nickname)||(n==null?void 0:n.remark)||"我":x.buyer_name||a.sender_name||x.buyer_id}),a.message_type==="image"?e.jsx("a",{href:a.content,target:"_blank",rel:"noreferrer",className:`block overflow-hidden rounded-2xl border bg-white p-1 shadow-sm ${j?"rounded-br-md border-sky-200":"rounded-bl-md border-slate-200"}`,children:e.jsx("img",{src:a.content,alt:"聊天图片",className:"max-h-80 max-w-full rounded-xl object-contain"})}):a.message_type==="video"?e.jsx("video",{src:a.content,controls:!0,preload:"metadata",className:"max-h-80 max-w-full rounded-2xl bg-black"}):e.jsx("div",{className:`rounded-2xl px-4 py-2.5 text-sm leading-6 shadow-sm ${j?"rounded-br-md bg-sky-500 text-white":"rounded-bl-md border border-slate-200 bg-white text-slate-800"}`,children:J(a.content)}),e.jsxs("div",{className:"mt-1 flex items-center gap-1 text-[10px] text-slate-400",children:[s0(a.sent_at),j&&(a.status==="failed"?e.jsx(re,{className:"h-3 w-3 text-red-500"}):a.status==="sent"?e.jsx(ce,{className:"h-3 w-3 text-sky-500"}):e.jsx(le,{className:"h-3 w-3"}))]})]}),j&&e.jsx("div",{className:"h-9 w-9 shrink-0 overflow-hidden rounded-full bg-sky-100 ring-2 ring-white",children:n!=null&&n.avatar_url?e.jsx("img",{src:n.avatar_url,alt:"我",className:"h-full w-full object-cover"}):e.jsx(I0,{className:"m-2 h-5 w-5 text-sky-600"})})]},a.message_key)})]})}),A&&e.jsxs("div",{className:"flex items-center justify-between gap-3 border-t border-red-100 bg-red-50 px-5 py-2 text-xs font-medium text-red-700",children:[e.jsx("span",{children:A}),F&&e.jsx("button",{type:"button",className:"font-bold underline",onClick:(()=>void y()),children:"重试发送"})]}),e.jsxs("div",{className:"relative z-10 shrink-0 border-t border-slate-200 bg-white p-4 shadow-chat-input",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-1",children:[e.jsxs("div",{className:"relative",children:[e.jsx("button",{type:"button",onClick:(()=>H(a=>!a)),disabled:T||(n==null?void 0:n.runtime_state)!=="online",className:"rounded-lg p-2 text-slate-500 hover:bg-sky-50 hover:text-sky-600 disabled:opacity-40",title:"闲鱼表情",children:e.jsx(oe,{className:"h-5 w-5"})}),w0&&e.jsxs("div",{className:"absolute bottom-11 left-0 z-30 w-[360px] rounded-2xl border border-slate-200 bg-white p-3 shadow-2xl",children:[e.jsx("div",{className:"mb-2 text-xs font-bold text-slate-500",children:"全部表情"}),e.jsx("div",{className:"grid max-h-72 grid-cols-8 gap-1 overflow-y-auto",children:y0.map(([a,j])=>e.jsx("button",{type:"button",title:`[${a}]`,onClick:(()=>{K(O=>O+`[${a}]`),H(!1)}),className:"flex h-10 w-10 items-center justify-center rounded-lg hover:bg-slate-100",children:e.jsx("img",{src:C(j),alt:`[${a}]`,className:"h-8 w-8 object-contain"})},a))})]})]}),e.jsx("input",{ref:X,type:"file",accept:"image/*",className:"hidden",onChange:(a=>{var j;return void N0((j=a.target.files)==null?void 0:j[0])})}),e.jsx("button",{type:"button",onClick:(()=>{var a;return(a=X.current)==null?void 0:a.click()}),disabled:T||(n==null?void 0:n.runtime_state)!=="online",className:"rounded-lg p-2 text-slate-500 transition hover:bg-sky-50 hover:text-sky-600 disabled:opacity-40",title:"发送图片(最大 10MB)",children:e.jsx(pe,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"flex items-end gap-3 rounded-2xl border border-slate-200 bg-slate-50 p-2 transition focus-within:border-sky-400 focus-within:ring-2 focus-within:ring-sky-100",children:[e.jsx("textarea",{value:S,onChange:(a=>K(a.target.value)),rows:2,maxLength:2e3,onKeyDown:(a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),g0())}),disabled:(n==null?void 0:n.runtime_state)!=="online",placeholder:(n==null?void 0:n.runtime_state)==="online"?"输入消息,Enter 发送,Shift + Enter 换行":"账号离线,暂时无法发送",className:"max-h-32 min-h-12 flex-1 resize-none bg-transparent px-2 py-2 text-sm leading-6 outline-none disabled:cursor-not-allowed"}),e.jsx("button",{type:"button",onClick:(()=>void g0()),disabled:!S.trim()||T||(n==null?void 0:n.runtime_state)!=="online",className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-sky-500 text-white shadow-md shadow-sky-100 transition hover:bg-sky-600 disabled:cursor-not-allowed disabled:bg-slate-300 disabled:shadow-none","aria-label":"发送消息",children:T?e.jsx(r0,{className:"h-4 w-4 animate-spin"}):e.jsx(me,{className:"h-4 w-4"})})]})]})]}):e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center text-center",children:[e.jsx(L0,{className:"h-12 w-12 text-slate-300"}),e.jsx("h3",{className:"mt-4 font-black text-slate-700",children:"选择一个用户开始聊天"}),e.jsx("p",{className:"mt-1 text-sm text-slate-400",children:"该账号的新消息会实时出现在左侧列表。"})]})})]})]})};export{ke as default}; diff --git a/internal/webui/static/assets/Dashboard-RK26q9J7.js b/internal/webui/static/assets/Dashboard-MmgsZAic.js similarity index 99% rename from internal/webui/static/assets/Dashboard-RK26q9J7.js rename to internal/webui/static/assets/Dashboard-MmgsZAic.js index 699812e..22cfcbf 100644 --- a/internal/webui/static/assets/Dashboard-RK26q9J7.js +++ b/internal/webui/static/assets/Dashboard-MmgsZAic.js @@ -1 +1 @@ -import{r as c,j as e}from"./react-vendor-C_od1ZSF.js";import{f as me}from"./dateTime-DDi7rqpW.js";import{g as q}from"./index-CFzx5gQT.js";import{c as de,o as ge}from"./contract-COFcZjyb.js";import{j as xe,k as he,l as te,D as pe,c as be,P as fe,m as se,E as ye,T as je}from"./icons-vendor-CvzvbbIV.js";import{R as E,B as ve,X as ae,Y as re,T as F,a as Ne,C as U,A as we,b as _e,c as ke,P as ne,d as le,L as De}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";const M=t=>{const a=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),l=String(t.getDate()).padStart(2,"0");return`${a}-${s}-${l}`},H=(t,a)=>{const s=new Date(t);return s.setHours(12,0,0,0),s.setDate(s.getDate()+a),s},X=(t,a)=>({startDate:M(H(t,-(a-1))),endDate:M(t)}),ue=(t,a=new Date,s="",l="")=>{if(t==="custom"&&s&&l){if(s>l)throw new Error("开始日期不能晚于结束日期");return{startDate:s,endDate:l}}return t==="yesterday"?X(H(a,-1),1):X(a,t==="3days"?3:t==="30days"?30:t==="today"?1:7)},Se=t=>{const a=new Date(`${t.startDate}T12:00:00`),s=new Date(`${t.endDate}T12:00:00`),l=Math.round((s.getTime()-a.getTime())/864e5)+1,n=H(a,-1);return X(n,l)},Ce=t=>{const a={};return t.forEach(s=>{a[s.item_id]=s.item_title||s.item_id}),a},$e=t=>{var a;return((a=t.daily_stats)==null?void 0:a.map(s=>({name:s.date.slice(5),amount:s.amount,orders:s.order_count,avgAmount:s.order_count>0?(s.amount/s.order_count).toFixed(2):0})))||[]},Re=(t,a)=>(t.item_stats||[]).map(s=>{const l=a[s.item_id]||s.item_id;return{name:l.length>12?`${l.substring(0,12)}...`:l,sales:s.order_count}}).sort((s,l)=>l.sales-s.sales).slice(0,10),Le=(t,a,s)=>{const l=t.revenue_stats.total_orders||0;return(t.item_stats||[]).map(n=>{const o=a[n.item_id]||n.item_id;return{name:o.length>10?`${o.substring(0,10)}...`:o,value:n.order_count,percent:l>0?n.order_count/l*100:0}}).sort((n,o)=>o.value-n.value).slice(0,6).map((n,o)=>({...n,color:s[o%s.length]}))},Ae=(t,a,s)=>{const l=t.revenue_stats.total_amount||0;return(t.item_stats||[]).map(n=>{const o=a[n.item_id]||n.item_id;return{name:o.length>12?`${o.substring(0,12)}...`:o,value:n.total_amount,orderCount:n.order_count,percentage:l>0?n.total_amount/l*100:0}}).sort((n,o)=>o.value-n.value).slice(0,5).map((n,o)=>({...n,color:s[o%s.length],percentage:n.percentage.toFixed(1)}))},Oe=(t,a)=>{if(!t||!a)return null;const s=t.revenue_stats.total_amount,l=a.revenue_stats.total_amount;if(l===0)return s>0?"+100%":"0%";const n=(s-l)/l*100;return`${n>=0?"+":""}${n.toFixed(1)}%`},Te=t=>({today:"今天",yesterday:"昨天","3days":"三天内","7days":"7天内","30days":"一个月内",custom:"自定义"})[t.range]||"所选范围",ze=t=>Math.max(...t.map(a=>a.sales),1),P=(t,a,s)=>t===a&&!s.aborted,oe=t=>{const a=String(t||"");return a==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(a)?a:"unknown"},Pe=async t=>q("/api/v1/analytics/dashboard",void 0,t),We=async(t,a)=>{const s=await q("/api/v1/items",void 0,a);return de(s,["items","data","results"]).map(n=>({...n,id:n.id||`${n.cookie_id}-${n.item_id}`,is_multi_spec:n.is_multi_spec===!0||n.is_multi_spec===1,multi_quantity_delivery:n.multi_quantity_delivery===!0||n.multi_quantity_delivery===1}))},ie=async(t=7,a)=>{let s;if(typeof t=="number"){const l=new Date,n=new Date;n.setDate(n.getDate()-t),s={start_date:M(n),end_date:M(l)}}else s=t;return q("/api/v1/analytics/orders",{...s,timezone_offset_minutes:-new Date().getTimezoneOffset()},a)},Ee=async(t,a)=>{const s=await q("/api/v1/analytics/orders/valid",{...t,timezone_offset_minutes:-new Date().getTimezoneOffset()},a),l=ge(s,["data","result"])||{},o=de(s,["orders","data","items"]).map(b=>({...b,id:b.order_id,status:oe(b.status||b.order_status),order_status:oe(b.order_status),quantity:Number(b.quantity||1)}));return{orders:o,total:Number(l.total??o.length),truncated:l.truncated===!0}},ce=t=>t instanceof Error&&t.message==="请求已取消",G=(t,a)=>t instanceof Error?t.message:a,Fe=t=>{const{range:a,customStartDate:s,customEndDate:l,customRangeVersion:n}=t,[o,b]=c.useState(null),[_,I]=c.useState(null),[K,v]=c.useState({overview:"idle",range:"idle",error:""}),[d,T]=c.useState(0),R=c.useRef(0),S=c.useRef(0),L=c.useMemo(()=>({range:a,customStartDate:s,customEndDate:l}),[l,s,a]),D=c.useCallback(()=>T(u=>u+1),[]);c.useEffect(()=>{const u=++S.current,h=new AbortController;return v(m=>({...m,overview:"loading",error:""})),Promise.all([Pe({signal:h.signal}),We(void 0,{signal:h.signal})]).then(([m,g])=>{P(S.current,u,h.signal)&&(b({stats:m,items:g,itemNames:Ce(g)}),v(p=>({...p,overview:"success"})))}).catch(m=>{!P(S.current,u,h.signal)||ce(m)||v(g=>({...g,overview:"error",error:G(m,"概览加载失败")}))}),(()=>h.abort())},[d]),c.useEffect(()=>{let u;try{u=ue(a,new Date,s,l)}catch(p){v(w=>({...w,range:"error",error:G(p,"日期范围无效")}));return}const h=Se(u),m=++R.current,g=new AbortController;return v(p=>({...p,range:"loading",error:""})),Promise.all([ie({start_date:u.startDate,end_date:u.endDate},{signal:g.signal}),ie({start_date:h.startDate,end_date:h.endDate},{signal:g.signal}),Ee({start_date:u.startDate,end_date:u.endDate},{signal:g.signal})]).then(([p,w,Y])=>{P(R.current,m,g.signal)&&(I({analytics:p,previousAnalytics:w,validOrders:Y,dateRange:u}),v($=>({...$,range:"success"})))}).catch(p=>{!P(R.current,m,g.signal)||ce(p)||v(w=>({...w,range:"error",error:G(p,"经营数据加载失败")}))}),(()=>g.abort())},[n,a,d]);const C=c.useMemo(()=>o&&_?{...o,..._}:null,[o,_]),k=(o==null?void 0:o.itemNames)||{},x=(_==null?void 0:_.analytics)||null,z=c.useMemo(()=>x?$e(x):[],[x]),N=c.useMemo(()=>x?Re(x,k):[],[x,k]),f=c.useMemo(()=>["rgb(var(--color-brand))","rgb(var(--color-brand-highlight))","rgb(var(--color-success-500))","rgb(var(--color-warning-500))","rgb(var(--color-accent-500))"],[]),A=c.useMemo(()=>x?Le(x,k,f):[],[x,f,k]),B=c.useMemo(()=>x?Ae(x,k,f):[],[x,f,k]),V=c.useMemo(()=>ze(N),[N]);return{data:C,status:K,chartData:z,productSalesData:N,sourceData:A,categoryData:B,maxProductSales:V,trendPercent:Oe(x,(C==null?void 0:C.previousAnalytics)||null),selectedRangeLabel:Te(L),refresh:D}},i=(t,a)=>a===void 0?`rgb(var(--color-${t}))`:`rgb(var(--color-${t}) / ${a})`,Me=({chartData:t,selectedRangeLabel:a,totalAmount:s})=>e.jsxs("div",{className:"ios-card p-8 rounded-xl",children:[e.jsxs("div",{className:"mb-10",children:[e.jsx("h3",{className:"text-xl font-bold text-gray-900",children:"营收趋势分析"}),e.jsxs("p",{className:"text-sm text-gray-400 mt-1",children:[a,"的销售额走势"]})]}),e.jsx("div",{className:"dashboard-revenue-chart h-[350px] w-full",children:t.length===0||s===0?e.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-gray-400",children:[e.jsx(xe,{className:"w-16 h-16 mb-4 opacity-20"}),e.jsx("p",{className:"text-lg font-medium",children:"暂无营收数据"}),e.jsx("p",{className:"text-sm mt-2",children:"所选时间范围内暂无订单记录"})]}):t.length<=2?e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(ve,{data:t,margin:{top:30,right:20,left:0,bottom:30},barCategoryGap:"45%",children:[e.jsx(ae,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:i("neutral-700"),fontSize:14,fontWeight:600},dy:10}),e.jsx(re,{axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500},tickFormatter:(l=>`¥${l}`)}),e.jsx(F,{contentStyle:{backgroundColor:i("white"),borderRadius:"8px",border:`1px solid ${i("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:i("neutral-500"),fontWeight:500},itemStyle:{color:i("brand"),fontWeight:600},cursor:{fill:i("brand",.08)},formatter:(l=>[`¥${Number(l).toFixed(2)}`,"营收"])}),e.jsx(Ne,{dataKey:"amount",fill:i("brand"),maxBarSize:72,radius:[12,12,0,0],activeBar:!1,stroke:"none",strokeWidth:0,children:t.map((l,n)=>e.jsx(U,{fill:i("brand"),stroke:"none",strokeWidth:0},`cell-${n}`))})]})}):e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(we,{data:t,margin:{top:10,right:10,left:-20,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"colorAmount",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:i("brand"),stopOpacity:.5}),e.jsx("stop",{offset:"95%",stopColor:i("brand"),stopOpacity:0})]})}),e.jsx(ae,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500},dy:15}),e.jsx(re,{axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500}}),e.jsx(_e,{vertical:!1,stroke:i("neutral-100"),strokeDasharray:"3 3"}),e.jsx(F,{contentStyle:{backgroundColor:i("white"),borderRadius:"8px",border:`1px solid ${i("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:i("neutral-500"),fontWeight:500},itemStyle:{color:i("brand"),fontWeight:600},cursor:{stroke:i("brand"),strokeWidth:2,strokeDasharray:"4 4"}}),e.jsx(ke,{type:"monotone",dataKey:"amount",stroke:i("brand"),strokeWidth:4,fillOpacity:1,fill:"url(#colorAmount)",activeDot:{r:8,fill:i("white"),stroke:i("brand"),strokeWidth:2}})]})})})]}),j=(t,a)=>`rgb(var(--color-${t}))`,qe=({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"},s={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`inline-flex items-center justify-center whitespace-nowrap px-3 py-1.5 rounded-lg text-xs leading-none font-bold ${a[t]||a.cancelled}`,children:s[t]||t})},W=({title:t,value:a,icon:s,colorClass:l,trend:n})=>e.jsxs("div",{className:"ios-card p-6 rounded-xl flex flex-col justify-between hover:translate-y-[-4px] transition-all duration-300 h-full relative overflow-hidden group border-0",children:[e.jsx("div",{className:`absolute -right-6 -top-6 w-32 h-32 ${l} opacity-10 rounded-full group-hover:scale-125 transition-transform duration-500 blur-2xl`}),e.jsxs("div",{className:"flex justify-between items-start mb-6",children:[e.jsx("div",{className:`p-4 rounded-2xl ${l} bg-opacity-10 backdrop-blur-sm`,children:e.jsx(s,{className:`w-6 h-6 ${l.replace("bg-","text-")}`})}),n&&e.jsxs("span",{className:"text-xs font-bold text-white bg-brand px-3 py-1.5 rounded-full flex items-center gap-1 shadow-sm",children:[e.jsx(je,{className:"w-3 h-3"})," ",n]})]}),e.jsxs("div",{className:"relative z-10",children:[e.jsx("h3",{className:"text-3xl font-extrabold text-gray-900 tracking-tight font-feature-settings-tnum",children:a}),e.jsx("p",{className:"text-gray-500 text-sm font-medium mt-1",children:t})]})]}),Xe=()=>{const[t,a]=c.useState("7days"),[s,l]=c.useState(""),[n,o]=c.useState(""),[b,_]=c.useState(""),[I,K]=c.useState(0),v=Fe({range:t,customStartDate:s,customEndDate:n,customRangeVersion:I}),{data:d,status:T,chartData:R,productSalesData:S,sourceData:L,categoryData:D,maxProductSales:C,trendPercent:k,selectedRangeLabel:x,refresh:z}=v,N=(d==null?void 0:d.stats)||null,f=(d==null?void 0:d.analytics)||null;d!=null&&d.previousAnalytics;const A=(d==null?void 0:d.validOrders.orders)||[],B=(d==null?void 0:d.validOrders.total)||0,V=(d==null?void 0:d.validOrders.truncated)||!1,u=T.range==="loading",h=T.error,m=[j("brand"),j("brand-highlight"),j("success-500"),j("warning-500"),j("accent-500")],g=r=>`¥${Number(r||0).toLocaleString("zh-CN",{maximumFractionDigits:2})}`;if(h&&(!N||!f))return e.jsxs("div",{className:"p-8 flex flex-col items-center gap-3 text-red-600",children:[e.jsx(he,{className:"w-8 h-8"}),e.jsx("span",{children:h}),e.jsx("button",{type:"button",className:"ios-btn-primary px-4 py-2 rounded-xl",onClick:z,children:"重新加载"})]});if(!N||!f)return e.jsx("div",{className:"p-8 flex justify-center text-gray-400",children:e.jsx(te,{className:"w-8 h-8 animate-spin text-brand"})});const p=f.revenue_stats.total_orders||0,w=f.revenue_stats.total_amount||0,Y=[{key:"today",label:"今天"},{key:"yesterday",label:"昨天"},{key:"3days",label:"三天内"},{key:"7days",label:"7天内"},{key:"30days",label:"一个月内"},{key:"custom",label:"自定义"}];let $;try{$=ue(t,new Date,s,n)}catch{$={startDate:s,endDate:n}}const O=b.trim().toLowerCase(),J=A.filter(r=>{var y,Q,Z,ee;return((y=r.order_id)==null?void 0:y.toLowerCase().includes(O))||((Q=r.item_id)==null?void 0:Q.toLowerCase().includes(O))||((Z=r.item_title)==null?void 0:Z.toLowerCase().includes(O))||((ee=r.buyer_id)==null?void 0:ee.toLowerCase().includes(O))});return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[h&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm text-red-700",children:[e.jsx("span",{children:h}),e.jsx("button",{type:"button",className:"font-bold underline",onClick:z,children:"重试"})]}),e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"运营概览"}),e.jsx("p",{className:"text-gray-500 mt-2 text-base",children:"欢迎回来,以下是闲鱼店铺的实时经营数据。"})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs("div",{className:"text-sm font-bold text-gray-700 bg-white px-5 py-2.5 rounded-full shadow-sm border border-gray-100 flex items-center gap-2",children:[e.jsx("span",{className:"w-2.5 h-2.5 bg-green-500 rounded-full animate-pulse"}),"系统正常运行"]})})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[Y.map(r=>e.jsx("button",{onClick:(()=>a(r.key)),className:`px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${t===r.key?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:r.label},r.key)),t==="custom"&&e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"date",value:s,onChange:(r=>l(r.target.value)),className:"px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand"}),e.jsx("span",{className:"self-center text-gray-400",children:"-"}),e.jsx("input",{type:"date",value:n,onChange:(r=>o(r.target.value)),className:"px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand"}),e.jsx("button",{onClick:(()=>K(r=>r+1)),className:"px-4 py-2 rounded-xl text-sm font-bold bg-black text-white hover:bg-gray-800 transition-colors",children:"应用"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6",children:[e.jsx(W,{title:"累计营收 (CNY)",value:`¥${f.revenue_stats.total_amount.toLocaleString("zh-CN",{minimumFractionDigits:2})}`,icon:pe,colorClass:"bg-blue-400",trend:k||void 0}),e.jsx(W,{title:"活跃账号 / 总数",value:`${N.active_cookies} / ${N.total_cookies}`,icon:be,colorClass:"bg-blue-500"}),e.jsx(W,{title:"订单数",value:f.revenue_stats.total_orders.toLocaleString(),icon:xe,colorClass:"bg-blue-500"}),e.jsx(W,{title:"库存卡密余量",value:N.available_card_stock,icon:fe,colorClass:"bg-purple-500"})]}),e.jsx(Me,{chartData:R,selectedRangeLabel:x,totalAmount:w}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsxs("div",{className:"ios-card p-6 rounded-xl",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品销量排行"}),e.jsx("div",{className:"h-[280px]",children:S.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:"暂无数据"}):e.jsx("div",{className:"h-full space-y-4 overflow-y-auto pr-2",children:S.map((r,y)=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("span",{className:`w-7 h-7 rounded-xl flex items-center justify-center text-xs font-extrabold ${y<3?"bg-blue-600 text-white":"bg-gray-100 text-gray-500"}`,children:y+1}),e.jsx("span",{className:"font-bold text-gray-800 text-sm truncate",children:r.name})]}),e.jsxs("span",{className:"font-mono text-sm font-extrabold text-gray-900",children:[r.sales," 单"]})]}),e.jsx("div",{className:"h-3 rounded-full bg-gray-100 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-brand",style:{width:`${Math.max(8,r.sales/C*100)}%`}})})]},`${r.name}-${y}`))})})]}),e.jsxs("div",{className:"ios-card p-6 rounded-xl",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品下单占比"}),e.jsx("div",{className:"dashboard-pie-chart h-[280px] relative",role:"img","aria-label":`商品下单占比,共 ${p} 单`,children:L.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:"暂无数据"}):e.jsxs(e.Fragment,{children:[e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(ne,{accessibilityLayer:!1,children:[e.jsx(le,{data:L,cx:"50%",cy:"45%",innerRadius:60,outerRadius:90,paddingAngle:2,dataKey:"value",activeShape:{outerRadius:96,stroke:"none",strokeWidth:0},rootTabIndex:-1,label:!1,labelLine:!1,children:L.map((r,y)=>e.jsx(U,{fill:r.color},`cell-${y}`))}),e.jsx(F,{formatter:(r=>`${Number(r||0)} 单`),wrapperStyle:{zIndex:30,outline:"none"},contentStyle:{backgroundColor:j("white"),border:`1px solid ${j("neutral-200")}`,borderRadius:"10px",boxShadow:"var(--shadow-md)"}}),e.jsx(De,{verticalAlign:"bottom",height:36,iconType:"circle",formatter:(r=>e.jsx("span",{style:{color:j("neutral-500"),fontWeight:500},children:r}))})]})}),e.jsxs("div",{className:"pointer-events-none absolute inset-0 z-10 flex flex-col items-center justify-center pb-9",children:[e.jsx("span",{className:"text-2xl font-extrabold text-gray-900 tabular-nums",children:p}),e.jsx("span",{className:"text-xs font-medium text-gray-400 mt-0.5",children:"总订单"})]})]})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"lg:col-span-2 ios-card p-0 rounded-xl border-0 bg-white overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"p-6 border-b border-gray-50 flex justify-between items-center bg-surface-muted",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900",children:"参与统计的订单"}),V&&e.jsxs("p",{className:"text-xs text-amber-700 mt-1",children:["当前显示最近 ",A.length," / ",B," 条,搜索仅覆盖已加载明细。"]})]}),e.jsx("div",{className:"relative",children:e.jsx("input",{placeholder:"搜索订单号/商品/买家...",value:b,onChange:(r=>_(r.target.value)),className:"pl-4 pr-4 py-2 rounded-xl bg-white border border-gray-100 text-sm focus:border-blue-400 outline-none w-48",type:"text"})})]}),e.jsx("div",{className:"overflow-x-auto flex-1 max-h-[400px]",children:u?e.jsxs("div",{className:"flex items-center justify-center py-20 text-gray-400",children:[e.jsx(te,{className:"w-6 h-6 animate-spin mr-2"}),"加载中..."]}):J.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-8 text-center",children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-gray-100 flex items-center justify-center mb-4",children:e.jsx(se,{className:"w-7 h-7 text-gray-300"})}),O?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"没有匹配的订单"}),e.jsxs("div",{className:"text-xs text-gray-400 mt-2 max-w-md",children:["当前共有 ",A.length," 单参与统计,但没有订单号、商品、买家匹配“",b,"”。"]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"当前范围内没有参与统计的订单"}),e.jsxs("div",{className:"text-xs text-gray-400 mt-2 max-w-lg leading-6",children:["日期范围:",$.startDate," 至 ",$.endDate,"; 统计口径:待发货、已发货、已完成,且订单金额不为空。 当前统计卡片订单数:",f.revenue_stats.total_orders," 单。"]})]})]}):e.jsxs("table",{className:"w-full min-w-[760px] text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"px-6 py-4",children:"订单信息"}),e.jsx("th",{className:"px-6 py-4",children:"买家信息"}),e.jsx("th",{className:"px-6 py-4",children:"金额"}),e.jsx("th",{className:"px-6 py-4 whitespace-nowrap",children:"状态"}),e.jsx("th",{className:"px-6 py-4 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:J.map(r=>e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-6 py-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-gray-100 overflow-hidden shadow-sm border border-gray-100 flex-shrink-0",children:e.jsx(se,{className:"w-full h-full text-gray-300 p-2"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm line-clamp-1",children:r.item_title||r.item_id||"未知商品"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 font-mono",children:r.order_id}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",r.quantity||1]})]})]})}),e.jsxs("td",{className:"px-6 py-4",children:[e.jsx("div",{className:"text-sm font-bold text-gray-800",children:r.buyer_id}),r.created_at&&e.jsx("div",{className:"text-xs text-gray-400 mt-1",children:me(r.created_at)})]}),e.jsxs("td",{className:"px-6 py-4 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:["¥",r.amount||"0.00"]}),e.jsx("td",{className:"px-6 py-4 whitespace-nowrap",children:e.jsx(qe,{status:r.status||r.order_status||"unknown"})}),e.jsx("td",{className:"px-6 py-4 text-right",children:e.jsx("a",{href:`https://www.goofish.com/order-detail?orderId=${r.order_id}&role=seller`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看闲鱼详情",children:e.jsx(ye,{className:"w-4 h-4"})})})]},r.order_id))})]})})]}),e.jsxs("div",{className:"ios-card p-6 rounded-xl bg-white",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品金额分析 (TOP5)"}),D.length===0?e.jsx("div",{className:"flex items-center justify-center h-[300px] text-gray-400",children:"暂无数据"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"dashboard-pie-chart h-[280px] relative",role:"img","aria-label":`商品金额分析,总金额 ${g(w)}`,children:[e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(ne,{accessibilityLayer:!1,children:[e.jsx(le,{data:D,cx:"50%",cy:"50%",innerRadius:60,outerRadius:92,paddingAngle:2,dataKey:"value",activeShape:{outerRadius:98,stroke:"none",strokeWidth:0},rootTabIndex:-1,label:!1,labelLine:!1,children:D.map((r,y)=>e.jsx(U,{fill:r.color||m[y%m.length]},`cell-${y}`))}),e.jsx(F,{wrapperStyle:{zIndex:30,outline:"none"},contentStyle:{backgroundColor:j("white"),border:`1px solid ${j("neutral-200")}`,borderRadius:"6px",boxShadow:"var(--shadow-md)"},formatter:(r=>`¥${Number(r||0).toLocaleString()}`)})]})}),e.jsxs("div",{className:"pointer-events-none absolute inset-0 z-10 flex flex-col items-center justify-center",children:[e.jsx("span",{className:"text-lg font-extrabold text-gray-900 tabular-nums",children:g(w)}),e.jsx("span",{className:"text-xs font-medium text-gray-400 mt-0.5",children:"总金额"})]})]}),e.jsx("div",{className:"space-y-3 mt-4",children:D.map(r=>e.jsxs("div",{className:"flex justify-between items-center gap-3 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[e.jsx("div",{className:"w-3 h-3 rounded-full shrink-0",style:{backgroundColor:r.color||m[D.indexOf(r)%m.length]}}),e.jsx("span",{className:"text-gray-600 font-medium truncate",title:r.name,children:r.name})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0 whitespace-nowrap",children:[e.jsxs("span",{className:"font-bold text-gray-900",children:["¥",r.value.toLocaleString()]}),e.jsxs("span",{className:"text-xs text-gray-500 bg-gray-100 px-2 py-0.5 rounded",children:[r.percentage,"%"]})]})]},r.name))})]})]})]})]})};export{qe as StatusBadge,Xe as default}; +import{r as c,j as e}from"./react-vendor-C_od1ZSF.js";import{f as me}from"./dateTime-DDi7rqpW.js";import{g as q}from"./index-hByDAHGj.js";import{c as de,o as ge}from"./contract-COFcZjyb.js";import{j as xe,k as he,l as te,D as pe,c as be,P as fe,m as se,E as ye,T as je}from"./icons-vendor-CvzvbbIV.js";import{R as E,B as ve,X as ae,Y as re,T as F,a as Ne,C as U,A as we,b as _e,c as ke,P as ne,d as le,L as De}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";const M=t=>{const a=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),l=String(t.getDate()).padStart(2,"0");return`${a}-${s}-${l}`},H=(t,a)=>{const s=new Date(t);return s.setHours(12,0,0,0),s.setDate(s.getDate()+a),s},X=(t,a)=>({startDate:M(H(t,-(a-1))),endDate:M(t)}),ue=(t,a=new Date,s="",l="")=>{if(t==="custom"&&s&&l){if(s>l)throw new Error("开始日期不能晚于结束日期");return{startDate:s,endDate:l}}return t==="yesterday"?X(H(a,-1),1):X(a,t==="3days"?3:t==="30days"?30:t==="today"?1:7)},Se=t=>{const a=new Date(`${t.startDate}T12:00:00`),s=new Date(`${t.endDate}T12:00:00`),l=Math.round((s.getTime()-a.getTime())/864e5)+1,n=H(a,-1);return X(n,l)},Ce=t=>{const a={};return t.forEach(s=>{a[s.item_id]=s.item_title||s.item_id}),a},$e=t=>{var a;return((a=t.daily_stats)==null?void 0:a.map(s=>({name:s.date.slice(5),amount:s.amount,orders:s.order_count,avgAmount:s.order_count>0?(s.amount/s.order_count).toFixed(2):0})))||[]},Re=(t,a)=>(t.item_stats||[]).map(s=>{const l=a[s.item_id]||s.item_id;return{name:l.length>12?`${l.substring(0,12)}...`:l,sales:s.order_count}}).sort((s,l)=>l.sales-s.sales).slice(0,10),Le=(t,a,s)=>{const l=t.revenue_stats.total_orders||0;return(t.item_stats||[]).map(n=>{const o=a[n.item_id]||n.item_id;return{name:o.length>10?`${o.substring(0,10)}...`:o,value:n.order_count,percent:l>0?n.order_count/l*100:0}}).sort((n,o)=>o.value-n.value).slice(0,6).map((n,o)=>({...n,color:s[o%s.length]}))},Ae=(t,a,s)=>{const l=t.revenue_stats.total_amount||0;return(t.item_stats||[]).map(n=>{const o=a[n.item_id]||n.item_id;return{name:o.length>12?`${o.substring(0,12)}...`:o,value:n.total_amount,orderCount:n.order_count,percentage:l>0?n.total_amount/l*100:0}}).sort((n,o)=>o.value-n.value).slice(0,5).map((n,o)=>({...n,color:s[o%s.length],percentage:n.percentage.toFixed(1)}))},Oe=(t,a)=>{if(!t||!a)return null;const s=t.revenue_stats.total_amount,l=a.revenue_stats.total_amount;if(l===0)return s>0?"+100%":"0%";const n=(s-l)/l*100;return`${n>=0?"+":""}${n.toFixed(1)}%`},Te=t=>({today:"今天",yesterday:"昨天","3days":"三天内","7days":"7天内","30days":"一个月内",custom:"自定义"})[t.range]||"所选范围",ze=t=>Math.max(...t.map(a=>a.sales),1),P=(t,a,s)=>t===a&&!s.aborted,oe=t=>{const a=String(t||"");return a==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(a)?a:"unknown"},Pe=async t=>q("/api/v1/analytics/dashboard",void 0,t),We=async(t,a)=>{const s=await q("/api/v1/items",void 0,a);return de(s,["items","data","results"]).map(n=>({...n,id:n.id||`${n.cookie_id}-${n.item_id}`,is_multi_spec:n.is_multi_spec===!0||n.is_multi_spec===1,multi_quantity_delivery:n.multi_quantity_delivery===!0||n.multi_quantity_delivery===1}))},ie=async(t=7,a)=>{let s;if(typeof t=="number"){const l=new Date,n=new Date;n.setDate(n.getDate()-t),s={start_date:M(n),end_date:M(l)}}else s=t;return q("/api/v1/analytics/orders",{...s,timezone_offset_minutes:-new Date().getTimezoneOffset()},a)},Ee=async(t,a)=>{const s=await q("/api/v1/analytics/orders/valid",{...t,timezone_offset_minutes:-new Date().getTimezoneOffset()},a),l=ge(s,["data","result"])||{},o=de(s,["orders","data","items"]).map(b=>({...b,id:b.order_id,status:oe(b.status||b.order_status),order_status:oe(b.order_status),quantity:Number(b.quantity||1)}));return{orders:o,total:Number(l.total??o.length),truncated:l.truncated===!0}},ce=t=>t instanceof Error&&t.message==="请求已取消",G=(t,a)=>t instanceof Error?t.message:a,Fe=t=>{const{range:a,customStartDate:s,customEndDate:l,customRangeVersion:n}=t,[o,b]=c.useState(null),[_,I]=c.useState(null),[K,v]=c.useState({overview:"idle",range:"idle",error:""}),[d,T]=c.useState(0),R=c.useRef(0),S=c.useRef(0),L=c.useMemo(()=>({range:a,customStartDate:s,customEndDate:l}),[l,s,a]),D=c.useCallback(()=>T(u=>u+1),[]);c.useEffect(()=>{const u=++S.current,h=new AbortController;return v(m=>({...m,overview:"loading",error:""})),Promise.all([Pe({signal:h.signal}),We(void 0,{signal:h.signal})]).then(([m,g])=>{P(S.current,u,h.signal)&&(b({stats:m,items:g,itemNames:Ce(g)}),v(p=>({...p,overview:"success"})))}).catch(m=>{!P(S.current,u,h.signal)||ce(m)||v(g=>({...g,overview:"error",error:G(m,"概览加载失败")}))}),(()=>h.abort())},[d]),c.useEffect(()=>{let u;try{u=ue(a,new Date,s,l)}catch(p){v(w=>({...w,range:"error",error:G(p,"日期范围无效")}));return}const h=Se(u),m=++R.current,g=new AbortController;return v(p=>({...p,range:"loading",error:""})),Promise.all([ie({start_date:u.startDate,end_date:u.endDate},{signal:g.signal}),ie({start_date:h.startDate,end_date:h.endDate},{signal:g.signal}),Ee({start_date:u.startDate,end_date:u.endDate},{signal:g.signal})]).then(([p,w,Y])=>{P(R.current,m,g.signal)&&(I({analytics:p,previousAnalytics:w,validOrders:Y,dateRange:u}),v($=>({...$,range:"success"})))}).catch(p=>{!P(R.current,m,g.signal)||ce(p)||v(w=>({...w,range:"error",error:G(p,"经营数据加载失败")}))}),(()=>g.abort())},[n,a,d]);const C=c.useMemo(()=>o&&_?{...o,..._}:null,[o,_]),k=(o==null?void 0:o.itemNames)||{},x=(_==null?void 0:_.analytics)||null,z=c.useMemo(()=>x?$e(x):[],[x]),N=c.useMemo(()=>x?Re(x,k):[],[x,k]),f=c.useMemo(()=>["rgb(var(--color-brand))","rgb(var(--color-brand-highlight))","rgb(var(--color-success-500))","rgb(var(--color-warning-500))","rgb(var(--color-accent-500))"],[]),A=c.useMemo(()=>x?Le(x,k,f):[],[x,f,k]),B=c.useMemo(()=>x?Ae(x,k,f):[],[x,f,k]),V=c.useMemo(()=>ze(N),[N]);return{data:C,status:K,chartData:z,productSalesData:N,sourceData:A,categoryData:B,maxProductSales:V,trendPercent:Oe(x,(C==null?void 0:C.previousAnalytics)||null),selectedRangeLabel:Te(L),refresh:D}},i=(t,a)=>a===void 0?`rgb(var(--color-${t}))`:`rgb(var(--color-${t}) / ${a})`,Me=({chartData:t,selectedRangeLabel:a,totalAmount:s})=>e.jsxs("div",{className:"ios-card p-8 rounded-xl",children:[e.jsxs("div",{className:"mb-10",children:[e.jsx("h3",{className:"text-xl font-bold text-gray-900",children:"营收趋势分析"}),e.jsxs("p",{className:"text-sm text-gray-400 mt-1",children:[a,"的销售额走势"]})]}),e.jsx("div",{className:"dashboard-revenue-chart h-[350px] w-full",children:t.length===0||s===0?e.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-gray-400",children:[e.jsx(xe,{className:"w-16 h-16 mb-4 opacity-20"}),e.jsx("p",{className:"text-lg font-medium",children:"暂无营收数据"}),e.jsx("p",{className:"text-sm mt-2",children:"所选时间范围内暂无订单记录"})]}):t.length<=2?e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(ve,{data:t,margin:{top:30,right:20,left:0,bottom:30},barCategoryGap:"45%",children:[e.jsx(ae,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:i("neutral-700"),fontSize:14,fontWeight:600},dy:10}),e.jsx(re,{axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500},tickFormatter:(l=>`¥${l}`)}),e.jsx(F,{contentStyle:{backgroundColor:i("white"),borderRadius:"8px",border:`1px solid ${i("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:i("neutral-500"),fontWeight:500},itemStyle:{color:i("brand"),fontWeight:600},cursor:{fill:i("brand",.08)},formatter:(l=>[`¥${Number(l).toFixed(2)}`,"营收"])}),e.jsx(Ne,{dataKey:"amount",fill:i("brand"),maxBarSize:72,radius:[12,12,0,0],activeBar:!1,stroke:"none",strokeWidth:0,children:t.map((l,n)=>e.jsx(U,{fill:i("brand"),stroke:"none",strokeWidth:0},`cell-${n}`))})]})}):e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(we,{data:t,margin:{top:10,right:10,left:-20,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"colorAmount",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:i("brand"),stopOpacity:.5}),e.jsx("stop",{offset:"95%",stopColor:i("brand"),stopOpacity:0})]})}),e.jsx(ae,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500},dy:15}),e.jsx(re,{axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500}}),e.jsx(_e,{vertical:!1,stroke:i("neutral-100"),strokeDasharray:"3 3"}),e.jsx(F,{contentStyle:{backgroundColor:i("white"),borderRadius:"8px",border:`1px solid ${i("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:i("neutral-500"),fontWeight:500},itemStyle:{color:i("brand"),fontWeight:600},cursor:{stroke:i("brand"),strokeWidth:2,strokeDasharray:"4 4"}}),e.jsx(ke,{type:"monotone",dataKey:"amount",stroke:i("brand"),strokeWidth:4,fillOpacity:1,fill:"url(#colorAmount)",activeDot:{r:8,fill:i("white"),stroke:i("brand"),strokeWidth:2}})]})})})]}),j=(t,a)=>`rgb(var(--color-${t}))`,qe=({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"},s={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`inline-flex items-center justify-center whitespace-nowrap px-3 py-1.5 rounded-lg text-xs leading-none font-bold ${a[t]||a.cancelled}`,children:s[t]||t})},W=({title:t,value:a,icon:s,colorClass:l,trend:n})=>e.jsxs("div",{className:"ios-card p-6 rounded-xl flex flex-col justify-between hover:translate-y-[-4px] transition-all duration-300 h-full relative overflow-hidden group border-0",children:[e.jsx("div",{className:`absolute -right-6 -top-6 w-32 h-32 ${l} opacity-10 rounded-full group-hover:scale-125 transition-transform duration-500 blur-2xl`}),e.jsxs("div",{className:"flex justify-between items-start mb-6",children:[e.jsx("div",{className:`p-4 rounded-2xl ${l} bg-opacity-10 backdrop-blur-sm`,children:e.jsx(s,{className:`w-6 h-6 ${l.replace("bg-","text-")}`})}),n&&e.jsxs("span",{className:"text-xs font-bold text-white bg-brand px-3 py-1.5 rounded-full flex items-center gap-1 shadow-sm",children:[e.jsx(je,{className:"w-3 h-3"})," ",n]})]}),e.jsxs("div",{className:"relative z-10",children:[e.jsx("h3",{className:"text-3xl font-extrabold text-gray-900 tracking-tight font-feature-settings-tnum",children:a}),e.jsx("p",{className:"text-gray-500 text-sm font-medium mt-1",children:t})]})]}),Xe=()=>{const[t,a]=c.useState("7days"),[s,l]=c.useState(""),[n,o]=c.useState(""),[b,_]=c.useState(""),[I,K]=c.useState(0),v=Fe({range:t,customStartDate:s,customEndDate:n,customRangeVersion:I}),{data:d,status:T,chartData:R,productSalesData:S,sourceData:L,categoryData:D,maxProductSales:C,trendPercent:k,selectedRangeLabel:x,refresh:z}=v,N=(d==null?void 0:d.stats)||null,f=(d==null?void 0:d.analytics)||null;d!=null&&d.previousAnalytics;const A=(d==null?void 0:d.validOrders.orders)||[],B=(d==null?void 0:d.validOrders.total)||0,V=(d==null?void 0:d.validOrders.truncated)||!1,u=T.range==="loading",h=T.error,m=[j("brand"),j("brand-highlight"),j("success-500"),j("warning-500"),j("accent-500")],g=r=>`¥${Number(r||0).toLocaleString("zh-CN",{maximumFractionDigits:2})}`;if(h&&(!N||!f))return e.jsxs("div",{className:"p-8 flex flex-col items-center gap-3 text-red-600",children:[e.jsx(he,{className:"w-8 h-8"}),e.jsx("span",{children:h}),e.jsx("button",{type:"button",className:"ios-btn-primary px-4 py-2 rounded-xl",onClick:z,children:"重新加载"})]});if(!N||!f)return e.jsx("div",{className:"p-8 flex justify-center text-gray-400",children:e.jsx(te,{className:"w-8 h-8 animate-spin text-brand"})});const p=f.revenue_stats.total_orders||0,w=f.revenue_stats.total_amount||0,Y=[{key:"today",label:"今天"},{key:"yesterday",label:"昨天"},{key:"3days",label:"三天内"},{key:"7days",label:"7天内"},{key:"30days",label:"一个月内"},{key:"custom",label:"自定义"}];let $;try{$=ue(t,new Date,s,n)}catch{$={startDate:s,endDate:n}}const O=b.trim().toLowerCase(),J=A.filter(r=>{var y,Q,Z,ee;return((y=r.order_id)==null?void 0:y.toLowerCase().includes(O))||((Q=r.item_id)==null?void 0:Q.toLowerCase().includes(O))||((Z=r.item_title)==null?void 0:Z.toLowerCase().includes(O))||((ee=r.buyer_id)==null?void 0:ee.toLowerCase().includes(O))});return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[h&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm text-red-700",children:[e.jsx("span",{children:h}),e.jsx("button",{type:"button",className:"font-bold underline",onClick:z,children:"重试"})]}),e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"运营概览"}),e.jsx("p",{className:"text-gray-500 mt-2 text-base",children:"欢迎回来,以下是闲鱼店铺的实时经营数据。"})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs("div",{className:"text-sm font-bold text-gray-700 bg-white px-5 py-2.5 rounded-full shadow-sm border border-gray-100 flex items-center gap-2",children:[e.jsx("span",{className:"w-2.5 h-2.5 bg-green-500 rounded-full animate-pulse"}),"系统正常运行"]})})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[Y.map(r=>e.jsx("button",{onClick:(()=>a(r.key)),className:`px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${t===r.key?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:r.label},r.key)),t==="custom"&&e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"date",value:s,onChange:(r=>l(r.target.value)),className:"px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand"}),e.jsx("span",{className:"self-center text-gray-400",children:"-"}),e.jsx("input",{type:"date",value:n,onChange:(r=>o(r.target.value)),className:"px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand"}),e.jsx("button",{onClick:(()=>K(r=>r+1)),className:"px-4 py-2 rounded-xl text-sm font-bold bg-black text-white hover:bg-gray-800 transition-colors",children:"应用"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6",children:[e.jsx(W,{title:"累计营收 (CNY)",value:`¥${f.revenue_stats.total_amount.toLocaleString("zh-CN",{minimumFractionDigits:2})}`,icon:pe,colorClass:"bg-blue-400",trend:k||void 0}),e.jsx(W,{title:"活跃账号 / 总数",value:`${N.active_cookies} / ${N.total_cookies}`,icon:be,colorClass:"bg-blue-500"}),e.jsx(W,{title:"订单数",value:f.revenue_stats.total_orders.toLocaleString(),icon:xe,colorClass:"bg-blue-500"}),e.jsx(W,{title:"库存卡密余量",value:N.available_card_stock,icon:fe,colorClass:"bg-purple-500"})]}),e.jsx(Me,{chartData:R,selectedRangeLabel:x,totalAmount:w}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsxs("div",{className:"ios-card p-6 rounded-xl",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品销量排行"}),e.jsx("div",{className:"h-[280px]",children:S.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:"暂无数据"}):e.jsx("div",{className:"h-full space-y-4 overflow-y-auto pr-2",children:S.map((r,y)=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("span",{className:`w-7 h-7 rounded-xl flex items-center justify-center text-xs font-extrabold ${y<3?"bg-blue-600 text-white":"bg-gray-100 text-gray-500"}`,children:y+1}),e.jsx("span",{className:"font-bold text-gray-800 text-sm truncate",children:r.name})]}),e.jsxs("span",{className:"font-mono text-sm font-extrabold text-gray-900",children:[r.sales," 单"]})]}),e.jsx("div",{className:"h-3 rounded-full bg-gray-100 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-brand",style:{width:`${Math.max(8,r.sales/C*100)}%`}})})]},`${r.name}-${y}`))})})]}),e.jsxs("div",{className:"ios-card p-6 rounded-xl",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品下单占比"}),e.jsx("div",{className:"dashboard-pie-chart h-[280px] relative",role:"img","aria-label":`商品下单占比,共 ${p} 单`,children:L.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:"暂无数据"}):e.jsxs(e.Fragment,{children:[e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(ne,{accessibilityLayer:!1,children:[e.jsx(le,{data:L,cx:"50%",cy:"45%",innerRadius:60,outerRadius:90,paddingAngle:2,dataKey:"value",activeShape:{outerRadius:96,stroke:"none",strokeWidth:0},rootTabIndex:-1,label:!1,labelLine:!1,children:L.map((r,y)=>e.jsx(U,{fill:r.color},`cell-${y}`))}),e.jsx(F,{formatter:(r=>`${Number(r||0)} 单`),wrapperStyle:{zIndex:30,outline:"none"},contentStyle:{backgroundColor:j("white"),border:`1px solid ${j("neutral-200")}`,borderRadius:"10px",boxShadow:"var(--shadow-md)"}}),e.jsx(De,{verticalAlign:"bottom",height:36,iconType:"circle",formatter:(r=>e.jsx("span",{style:{color:j("neutral-500"),fontWeight:500},children:r}))})]})}),e.jsxs("div",{className:"pointer-events-none absolute inset-0 z-10 flex flex-col items-center justify-center pb-9",children:[e.jsx("span",{className:"text-2xl font-extrabold text-gray-900 tabular-nums",children:p}),e.jsx("span",{className:"text-xs font-medium text-gray-400 mt-0.5",children:"总订单"})]})]})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"lg:col-span-2 ios-card p-0 rounded-xl border-0 bg-white overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"p-6 border-b border-gray-50 flex justify-between items-center bg-surface-muted",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900",children:"参与统计的订单"}),V&&e.jsxs("p",{className:"text-xs text-amber-700 mt-1",children:["当前显示最近 ",A.length," / ",B," 条,搜索仅覆盖已加载明细。"]})]}),e.jsx("div",{className:"relative",children:e.jsx("input",{placeholder:"搜索订单号/商品/买家...",value:b,onChange:(r=>_(r.target.value)),className:"pl-4 pr-4 py-2 rounded-xl bg-white border border-gray-100 text-sm focus:border-blue-400 outline-none w-48",type:"text"})})]}),e.jsx("div",{className:"overflow-x-auto flex-1 max-h-[400px]",children:u?e.jsxs("div",{className:"flex items-center justify-center py-20 text-gray-400",children:[e.jsx(te,{className:"w-6 h-6 animate-spin mr-2"}),"加载中..."]}):J.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-8 text-center",children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-gray-100 flex items-center justify-center mb-4",children:e.jsx(se,{className:"w-7 h-7 text-gray-300"})}),O?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"没有匹配的订单"}),e.jsxs("div",{className:"text-xs text-gray-400 mt-2 max-w-md",children:["当前共有 ",A.length," 单参与统计,但没有订单号、商品、买家匹配“",b,"”。"]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"当前范围内没有参与统计的订单"}),e.jsxs("div",{className:"text-xs text-gray-400 mt-2 max-w-lg leading-6",children:["日期范围:",$.startDate," 至 ",$.endDate,"; 统计口径:待发货、已发货、已完成,且订单金额不为空。 当前统计卡片订单数:",f.revenue_stats.total_orders," 单。"]})]})]}):e.jsxs("table",{className:"w-full min-w-[760px] text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"px-6 py-4",children:"订单信息"}),e.jsx("th",{className:"px-6 py-4",children:"买家信息"}),e.jsx("th",{className:"px-6 py-4",children:"金额"}),e.jsx("th",{className:"px-6 py-4 whitespace-nowrap",children:"状态"}),e.jsx("th",{className:"px-6 py-4 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:J.map(r=>e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-6 py-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-gray-100 overflow-hidden shadow-sm border border-gray-100 flex-shrink-0",children:e.jsx(se,{className:"w-full h-full text-gray-300 p-2"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm line-clamp-1",children:r.item_title||r.item_id||"未知商品"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 font-mono",children:r.order_id}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",r.quantity||1]})]})]})}),e.jsxs("td",{className:"px-6 py-4",children:[e.jsx("div",{className:"text-sm font-bold text-gray-800",children:r.buyer_id}),r.created_at&&e.jsx("div",{className:"text-xs text-gray-400 mt-1",children:me(r.created_at)})]}),e.jsxs("td",{className:"px-6 py-4 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:["¥",r.amount||"0.00"]}),e.jsx("td",{className:"px-6 py-4 whitespace-nowrap",children:e.jsx(qe,{status:r.status||r.order_status||"unknown"})}),e.jsx("td",{className:"px-6 py-4 text-right",children:e.jsx("a",{href:`https://www.goofish.com/order-detail?orderId=${r.order_id}&role=seller`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看闲鱼详情",children:e.jsx(ye,{className:"w-4 h-4"})})})]},r.order_id))})]})})]}),e.jsxs("div",{className:"ios-card p-6 rounded-xl bg-white",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品金额分析 (TOP5)"}),D.length===0?e.jsx("div",{className:"flex items-center justify-center h-[300px] text-gray-400",children:"暂无数据"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"dashboard-pie-chart h-[280px] relative",role:"img","aria-label":`商品金额分析,总金额 ${g(w)}`,children:[e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(ne,{accessibilityLayer:!1,children:[e.jsx(le,{data:D,cx:"50%",cy:"50%",innerRadius:60,outerRadius:92,paddingAngle:2,dataKey:"value",activeShape:{outerRadius:98,stroke:"none",strokeWidth:0},rootTabIndex:-1,label:!1,labelLine:!1,children:D.map((r,y)=>e.jsx(U,{fill:r.color||m[y%m.length]},`cell-${y}`))}),e.jsx(F,{wrapperStyle:{zIndex:30,outline:"none"},contentStyle:{backgroundColor:j("white"),border:`1px solid ${j("neutral-200")}`,borderRadius:"6px",boxShadow:"var(--shadow-md)"},formatter:(r=>`¥${Number(r||0).toLocaleString()}`)})]})}),e.jsxs("div",{className:"pointer-events-none absolute inset-0 z-10 flex flex-col items-center justify-center",children:[e.jsx("span",{className:"text-lg font-extrabold text-gray-900 tabular-nums",children:g(w)}),e.jsx("span",{className:"text-xs font-medium text-gray-400 mt-0.5",children:"总金额"})]})]}),e.jsx("div",{className:"space-y-3 mt-4",children:D.map(r=>e.jsxs("div",{className:"flex justify-between items-center gap-3 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[e.jsx("div",{className:"w-3 h-3 rounded-full shrink-0",style:{backgroundColor:r.color||m[D.indexOf(r)%m.length]}}),e.jsx("span",{className:"text-gray-600 font-medium truncate",title:r.name,children:r.name})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0 whitespace-nowrap",children:[e.jsxs("span",{className:"font-bold text-gray-900",children:["¥",r.value.toLocaleString()]}),e.jsxs("span",{className:"text-xs text-gray-500 bg-gray-100 px-2 py-0.5 rounded",children:[r.percentage,"%"]})]})]},r.name))})]})]})]})]})};export{qe as StatusBadge,Xe as default}; diff --git a/internal/webui/static/assets/ItemList-FcKS3Z5e.js b/internal/webui/static/assets/ItemList-BHJwErgP.js similarity index 99% rename from internal/webui/static/assets/ItemList-FcKS3Z5e.js rename to internal/webui/static/assets/ItemList-BHJwErgP.js index cbbbf6b..bf9f8af 100644 --- a/internal/webui/static/assets/ItemList-FcKS3Z5e.js +++ b/internal/webui/static/assets/ItemList-BHJwErgP.js @@ -1,2 +1,2 @@ -import{r as l,j as e,b as ge}from"./react-vendor-C_od1ZSF.js";import{g as de,a as te,b as Ge,d as Ve,p as ot}from"./index-CFzx5gQT.js";import{c as We}from"./contract-COFcZjyb.js";import{a3 as xt,U as Ee,R as we,N as Re,a4 as _e,a5 as be,V as mt,F as ht,B as ut,a6 as $e,a7 as pt,a8 as gt,A as bt,d as yt,X as re,r as ft,a9 as De,I as qe}from"./icons-vendor-CvzvbbIV.js";const Ue="ydisks-amap-js-api",jt="c9b68d4ce9a2a97f22a4a439404488ca";let ce=null;const Nt=()=>jt,vt=()=>window.AMap?Promise.resolve(window.AMap):ce||(ce=new Promise((s,a)=>{const x=document.getElementById(Ue),o=x||document.createElement("script"),d=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(P)},g=()=>{window.AMap?(d(),s(window.AMap)):(d(),a(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},P=window.setTimeout(()=>{d(),a(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=g,o.id=Ue,o.async=!0,o.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(Nt())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,o.onerror=()=>{d(),a(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},x||document.head.appendChild(o)}).catch(s=>{throw ce=null,s}),ce),ye=s=>Number.isFinite(s)&&s!==0,wt=s=>{var d,g;const a=Number((d=s.location)==null?void 0:d.lng),x=Number((g=s.location)==null?void 0:g.lat),o={area:String(s.adname||"").trim(),city:String(s.cityname||"").trim(),division_id:String(s.adcode||"").trim(),longitude:a,latitude:x,poi_id:String(s.id||"").trim(),poi_name:String(s.name||"").trim(),province:String(s.pname||"").trim()};return!o.division_id||!o.province||!o.city||!o.poi_id||!o.poi_name||!ye(a)||!ye(x)||a<-180||a>180||x<-90||x>90?null:o},_t=async(s,a)=>{if(!ye(s)||!ye(a)||s<-180||s>180||a<-90||a>90)throw new Error("经纬度无效");const x=await vt();return new Promise((o,d)=>{new x.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[s,a],1e3,(P,f)=>{var w;if(P!=="complete"){if(P==="no_data"){o([]);return}d(new Error("高德地图附近地址查询失败,请稍后重试"));return}const L=(((w=f==null?void 0:f.poiList)==null?void 0:w.pois)||[]).map(wt).filter(T=>T!==null);o(L)})})},kt=async s=>de("/api/v1/accounts/details",void 0,s),ze=async()=>de("/api/v1/automation-rules"),ke=s=>s===!0||s===1||s==="1",Oe=async(s,a)=>{const x=await de("/api/v1/items",void 0,a);return We(x,["items","data","results"]).map(d=>({...d,id:d.id||`${d.cookie_id}-${d.item_id}`,is_multi_spec:ke(d.is_multi_spec),is_multi_qty_ship:ke(d.is_multi_qty_ship??d.multi_quantity_delivery),multi_quantity_delivery:ke(d.multi_quantity_delivery??d.is_multi_qty_ship)}))},Ct=async s=>te("/api/v1/items/get-all-from-account",{cookie_id:s}),It=async(s,a)=>Ve(`/api/v1/items/${s}/${a}`),St=async(s,a)=>te(`/api/v1/items/${s}`,a),Pt=async s=>{const a=new FormData;a.set("cookie_id",s.cookie_id),a.set("title",s.title),a.set("description",s.description),a.set("price",s.price),a.set("original_price",s.original_price||""),a.set("quantity",String(s.quantity)),a.set("postage_mode",s.postage_mode),a.set("postage",s.postage||""),s.location&&a.set("location",JSON.stringify(s.location));for(const x of s.images)a.append("images",x);return Ge("/api/v1/items/publish",a)},Bt=async(s,a)=>te("/api/v1/items/publish-categories/recommend",{cookie_id:s,keyword:a}),Ft=async s=>{const a=new FormData;return a.set("file",s.file),s.imagesZip&&a.set("images_zip",s.imagesZip),s.defaultCookieId&&a.set("default_cookie_id",s.defaultCookieId),a.set("fallback_category_id",s.fallbackCategory.catId),a.set("fallback_category_name",s.fallbackCategory.catName),a.set("fallback_channel_category_id",s.fallbackCategory.channelCatId||""),a.set("fallback_tb_category_id",s.fallbackCategory.tbCatId||""),s.location&&a.set("location",JSON.stringify(s.location)),Ge("/api/v1/items/publish-batches/preview",a)},Lt=async s=>te("/api/v1/items/publish-batches",{preview_id:s}),ee=async s=>de(`/api/v1/items/publish-batches/${s}`),Ye=async(s=20)=>{const a=await de("/api/v1/items/publish-batches",{limit:s});return We(a,["batches","data","items"])},At=async s=>Ve(`/api/v1/items/publish-batches/${s}`),Mt=async s=>te(`/api/v1/items/publish-batches/${s}/cancel`,{}),Et=async s=>te(`/api/v1/items/publish-batches/${s}/retry-failed`,{}),Rt=async(s,a,x)=>ot(`/api/v1/items/${s}/${a}`,x),$t=s=>s.find(a=>a.status==="running"||a.status==="canceling"),Ie=s=>s==="running"||s==="canceling",Dt=s=>!!(s!=null&&s.preview_id&&Number(s.valid||0)>0),qt=s=>!!(s!=null&&s.id&&Number(s.retryable||0)>0&&!Ie(s.status)),Ut=(s,a)=>s===a,Te=s=>{switch(s){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 s||"-"}},Ke=s=>{switch(s){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"}},zt=s=>{const[a,x]=l.useState(!1),[o,d]=l.useState("upload"),[g,P]=l.useState(null),[f,L]=l.useState(null),[w,T]=l.useState(""),[K,J]=l.useState(!1),[R,G]=l.useState({catId:"",catName:"",channelCatId:"",tbCatId:""}),[y,N]=l.useState(null),[c,_]=l.useState(null),[I,$]=l.useState(null),[V,D]=l.useState([]),[q,B]=l.useState(null),[U,p]=l.useState(!1),k=l.useRef(!1),m=l.useRef(0),A=l.useCallback(async()=>{d("upload"),N(null),_(null),P(null),L(null),T(""),G({catId:"",catName:"",channelCatId:"",tbCatId:""}),D([]),B(null),x(!0),p(!0);try{const r=await Ye(20),h=$t(r);if(h!=null&&h.id){const S=await ee(h.id);$(S),_(S),d(["running","canceling"].includes(S.status)?"running":"done")}}catch(r){console.error("恢复最近批量铺货任务失败:",r)}finally{p(!1)}},[]),u=l.useCallback(async()=>{const r=w.trim();if(!s.selectedAccount){alert("请先选择默认发布账号");return}if(!r){alert("请输入类目关键词");return}J(!0);try{const S=(await Bt(s.selectedAccount,r)).category;G({catId:S.cat_id,catName:S.cat_name,channelCatId:S.channel_cat_id,tbCatId:S.tb_cat_id||""})}catch(h){console.error("获取推荐类目失败:",h),alert((h==null?void 0:h.message)||"没有匹配到类目,请换一个更具体的关键词")}finally{J(!1)}},[w,s.selectedAccount]),M=l.useCallback(async()=>{if(I!=null&&I.id){p(!0),x(!0);try{const r=await ee(I.id);_(r),d(["running","canceling"].includes(r.status)?"running":"done")}catch(r){console.error("加载最近批量铺货结果失败:",r)}finally{p(!1)}}},[I==null?void 0:I.id]),se=l.useCallback(async()=>{if(!g){alert("请先上传商品表格");return}if(!s.selectedAccount){alert("请先选择默认发布账号");return}p(!0);try{const r=await Ft({file:g,imagesZip:f,defaultCookieId:s.selectedAccount,fallbackCategory:R,location:q||void 0});N(r),_(null),d("preview")}catch(r){console.error("批量铺货预检失败:",r),alert((r==null?void 0:r.message)||"预检失败,请检查表格和图片 zip")}finally{p(!1)}},[R,g,f,q,s.selectedAccount]),W=l.useCallback(async()=>{if(y!=null&&y.preview_id){if(!Dt(y)){alert("没有可发布的商品行");return}p(!0);try{const r=await Lt(y.preview_id),h=await ee(r.batch_id||y.preview_id);_(h),$(h),d(h.status==="running"?"running":"done")}catch(r){console.error("启动批量铺货失败:",r),alert((r==null?void 0:r.message)||"启动发布任务失败")}finally{p(!1)}}},[y]),Y=l.useCallback(async()=>{if(c!=null&&c.id&&confirm("确认取消当前批量铺货任务吗?正在发布的单个商品可能会继续完成。")){p(!0);try{const r=await Mt(c.id),h=await ee(c.id);_(h),d((r==null?void 0:r.status)==="canceling"||h.status==="canceling"?"running":"done")}catch(r){alert((r==null?void 0:r.message)||"取消失败")}finally{p(!1)}}},[c==null?void 0:c.id]),H=l.useCallback(async()=>{const r=y==null?void 0:y.preview_id;if(r&&o==="preview")try{await At(r)}catch(h){console.error("清理批量铺货预检失败:",h)}N(null),d("upload")},[o,y==null?void 0:y.preview_id]),Q=l.useCallback(async()=>{await H(),x(!1)},[H]),ae=l.useCallback(async()=>{if(!(!(c!=null&&c.id)||!qt(c))){p(!0);try{await Et(c.id),_(await ee(c.id)),d("running")}catch(r){alert((r==null?void 0:r.message)||"重试失败")}finally{p(!1)}}},[c]);return l.useEffect(()=>{if(!a||!(c!=null&&c.id)||!Ie(c.status))return;const r=++m.current,h=async()=>{if(!k.current){k.current=!0;try{const z=await ee(c.id);if(!Ut(r,m.current))return;_(z),$(z),Ie(z.status)||(d("done"),await Promise.all([s.loadItems(),s.loadShippingRules()]))}catch(z){console.error("刷新批量铺货进度失败:",z)}finally{k.current=!1}}},S=window.setInterval(()=>void h(),3e3);return(()=>{window.clearInterval(S),m.current+=1})},[c==null?void 0:c.id,c==null?void 0:c.status,s.loadItems,s.loadShippingRules,a]),{showBatchModal:a,setShowBatchModal:x,batchLoading:U,batchPhase:o,setBatchPhase:d,batchFile:g,setBatchFile:P,batchImagesZip:f,setBatchImagesZip:L,batchCategoryKeyword:w,setBatchCategoryKeyword:T,batchCategoryLoading:K,batchFallbackCategory:R,setBatchFallbackCategory:G,batchPreview:y,setBatchPreview:N,batchDetail:c,setBatchDetail:_,recentBatch:I,setRecentBatch:$,batchLocations:V,batchLocation:q,setBatchLocations:D,setBatchLocation:B,openBatchModal:A,handleRecommendBatchCategory:u,openRecentBatchResult:M,handlePreviewBatch:se,handleStartBatch:W,handleCancelBatch:Y,abandonBatchPreview:H,closeBatchModal:Q,handleRetryBatchFailed:ae}},Je=()=>({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),Ze=(s="")=>({cookie_id:s,title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),Ce=(s,a)=>{if(s instanceof Error)return s.message;const x=typeof s=="object"&&s!==null&&"message"in s?s.message:void 0;return typeof x=="string"?x:a},Ot=({selectedAccount:s,setSelectedAccount:a,setItems:x,loadItems:o,loadShippingRules:d,onConfigureDelivery:g,setBatchLocations:P,setBatchLocation:f})=>{const[L,w]=l.useState(!1),[T,K]=l.useState(!1),[J,R]=l.useState(!1),[G,y]=l.useState(!1),[N,c]=l.useState(!1),[_,I]=l.useState(!1),[$,V]=l.useState([]),[D,q]=l.useState(null),[B,U]=l.useState(null),[p,k]=l.useState({}),[m,A]=l.useState(Je),[u,M]=l.useState(Ze),[se,W]=l.useState([]);l.useEffect(()=>{if(!N||u.images.length===0){W([]);return}const i=u.images.map((j,C)=>({key:j.name+C,url:URL.createObjectURL(j)}));return W(i),(()=>i.forEach(j=>URL.revokeObjectURL(j.url)))},[u.images,N]);const Y=l.useCallback(async()=>{if(!s)return alert("请先选择账号");w(!0);try{const i=await Ct(s);await o(),alert((i==null?void 0:i.message)||"商品同步完成")}catch(i){console.error("同步商品失败:",i),alert(Ce(i,"同步失败,请重试"))}finally{w(!1)}},[o,s]),H=l.useCallback(i=>{U(i),k({...i}),R(!0)},[]),Q=l.useCallback(async()=>{if(B)try{await Rt(B.cookie_id,B.item_id,{item_title:p.item_title||"",item_description:p.item_description||"",item_category:p.item_category||"",item_price:p.item_price||"",item_detail:p.item_detail||B.item_detail||""}),await o(),await d(),R(!1),U(null)}catch(i){console.error("更新商品失败:",i),alert("更新失败,请重试")}},[p,o,d,B]),ae=l.useCallback(async i=>{if(confirm(`确认删除商品"${i.item_title}"吗?`))try{await It(i.cookie_id,i.item_id),x(j=>j.filter(C=>!(C.cookie_id===i.cookie_id&&C.item_id===i.item_id)))}catch(j){console.error("删除商品失败:",j),alert("删除失败,请重试")}},[x]),oe=l.useCallback(async()=>{try{if(!m.cookie_id||!m.item_id){alert("请选择账号并填写商品ID");return}await St(m.cookie_id,{item_id:m.item_id,item_title:m.item_title,item_price:m.item_price,item_detail:m.item_image?JSON.stringify({item_image:m.item_image}):""}),await o(),y(!1),A(Je())}catch(i){console.error("添加商品失败:",i),alert("添加失败,请重试")}},[m,o]),r=l.useCallback(async()=>{if(!u.cookie_id)return alert("请选择发布账号");if(!u.title.trim())return alert("请填写商品标题");if(!u.price.trim())return alert("请填写商品价格");if(!u.quantity||Number(u.quantity)<=0)return alert("库存数量必须大于 0");if(u.images.length===0)return alert("至少上传 1 张商品图片");if(u.postage_mode==="fixed"&&!u.postage.trim())return alert("请填写一口价邮费");K(!0);try{const i=await Pt({...u,location:D||void 0});if(await o(),c(!1),M(Ze(s||"")),V([]),q(null),i!=null&&i.item_id){const j={id:i.item_id,cookie_id:u.cookie_id,item_id:i.item_id,item_title:i.item_title||u.title,item_price:i.item_price||u.price,item_image:i.item_image};g(j),alert("商品发布成功,ID: "+i.item_id+",已为你打开发货规则配置")}else alert("商品发布成功")}catch(i){console.error("发布商品失败:",i);const j=i==null?void 0:i.payload;if((j==null?void 0:j.code)==="stock_permission_missing"){alert("发布失败:该账号没有库存发布权限,无法按库存数量发布商品。请换账号或先在闲鱼确认库存能力。");return}alert(Ce(i,"发布失败,请重试"))}finally{K(!1)}},[o,g,u,D,s]),h=l.useCallback(()=>{const C=[["账号ID","标题","描述","价格","原价","库存","邮费模式","邮费","图片","类目ID","类目名称","频道类目ID","淘宝类目ID","付款发货启用","付款发货内容","评价赠品启用","评价赠品内容","求评价启用","求评价等待小时","求评价文案","求评价最多次数"],...[["","会员组合包自动发货","下单后发送主卡和附赠卡。","19.90","29.90","10","free","","images/bundle-1.jpg;images/bundle-2.jpg","","","","","是","101:1;102:1","是","201:1;202:2","是","72","亲,满意的话麻烦给个评价,谢谢~","1"],["","普通商品","仅发布商品,不创建自动化规则。","49.90","","10","fixed","8.00","https://example.com/product.jpg","","","","","否","","否","","否","","",""]]].map(je=>je.map(Ne=>`"${String(Ne).replace(/"/g,'""')}"`).join(",")).join(` +import{r as l,j as e,b as ge}from"./react-vendor-C_od1ZSF.js";import{g as de,a as te,b as Ge,d as Ve,p as ot}from"./index-hByDAHGj.js";import{c as We}from"./contract-COFcZjyb.js";import{a3 as xt,U as Ee,R as we,N as Re,a4 as _e,a5 as be,V as mt,F as ht,B as ut,a6 as $e,a7 as pt,a8 as gt,A as bt,d as yt,X as re,r as ft,a9 as De,I as qe}from"./icons-vendor-CvzvbbIV.js";const Ue="ydisks-amap-js-api",jt="c9b68d4ce9a2a97f22a4a439404488ca";let ce=null;const Nt=()=>jt,vt=()=>window.AMap?Promise.resolve(window.AMap):ce||(ce=new Promise((s,a)=>{const x=document.getElementById(Ue),o=x||document.createElement("script"),d=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(P)},g=()=>{window.AMap?(d(),s(window.AMap)):(d(),a(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},P=window.setTimeout(()=>{d(),a(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=g,o.id=Ue,o.async=!0,o.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(Nt())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,o.onerror=()=>{d(),a(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},x||document.head.appendChild(o)}).catch(s=>{throw ce=null,s}),ce),ye=s=>Number.isFinite(s)&&s!==0,wt=s=>{var d,g;const a=Number((d=s.location)==null?void 0:d.lng),x=Number((g=s.location)==null?void 0:g.lat),o={area:String(s.adname||"").trim(),city:String(s.cityname||"").trim(),division_id:String(s.adcode||"").trim(),longitude:a,latitude:x,poi_id:String(s.id||"").trim(),poi_name:String(s.name||"").trim(),province:String(s.pname||"").trim()};return!o.division_id||!o.province||!o.city||!o.poi_id||!o.poi_name||!ye(a)||!ye(x)||a<-180||a>180||x<-90||x>90?null:o},_t=async(s,a)=>{if(!ye(s)||!ye(a)||s<-180||s>180||a<-90||a>90)throw new Error("经纬度无效");const x=await vt();return new Promise((o,d)=>{new x.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[s,a],1e3,(P,f)=>{var w;if(P!=="complete"){if(P==="no_data"){o([]);return}d(new Error("高德地图附近地址查询失败,请稍后重试"));return}const L=(((w=f==null?void 0:f.poiList)==null?void 0:w.pois)||[]).map(wt).filter(T=>T!==null);o(L)})})},kt=async s=>de("/api/v1/accounts/details",void 0,s),ze=async()=>de("/api/v1/automation-rules"),ke=s=>s===!0||s===1||s==="1",Oe=async(s,a)=>{const x=await de("/api/v1/items",void 0,a);return We(x,["items","data","results"]).map(d=>({...d,id:d.id||`${d.cookie_id}-${d.item_id}`,is_multi_spec:ke(d.is_multi_spec),is_multi_qty_ship:ke(d.is_multi_qty_ship??d.multi_quantity_delivery),multi_quantity_delivery:ke(d.multi_quantity_delivery??d.is_multi_qty_ship)}))},Ct=async s=>te("/api/v1/items/get-all-from-account",{cookie_id:s}),It=async(s,a)=>Ve(`/api/v1/items/${s}/${a}`),St=async(s,a)=>te(`/api/v1/items/${s}`,a),Pt=async s=>{const a=new FormData;a.set("cookie_id",s.cookie_id),a.set("title",s.title),a.set("description",s.description),a.set("price",s.price),a.set("original_price",s.original_price||""),a.set("quantity",String(s.quantity)),a.set("postage_mode",s.postage_mode),a.set("postage",s.postage||""),s.location&&a.set("location",JSON.stringify(s.location));for(const x of s.images)a.append("images",x);return Ge("/api/v1/items/publish",a)},Bt=async(s,a)=>te("/api/v1/items/publish-categories/recommend",{cookie_id:s,keyword:a}),Ft=async s=>{const a=new FormData;return a.set("file",s.file),s.imagesZip&&a.set("images_zip",s.imagesZip),s.defaultCookieId&&a.set("default_cookie_id",s.defaultCookieId),a.set("fallback_category_id",s.fallbackCategory.catId),a.set("fallback_category_name",s.fallbackCategory.catName),a.set("fallback_channel_category_id",s.fallbackCategory.channelCatId||""),a.set("fallback_tb_category_id",s.fallbackCategory.tbCatId||""),s.location&&a.set("location",JSON.stringify(s.location)),Ge("/api/v1/items/publish-batches/preview",a)},Lt=async s=>te("/api/v1/items/publish-batches",{preview_id:s}),ee=async s=>de(`/api/v1/items/publish-batches/${s}`),Ye=async(s=20)=>{const a=await de("/api/v1/items/publish-batches",{limit:s});return We(a,["batches","data","items"])},At=async s=>Ve(`/api/v1/items/publish-batches/${s}`),Mt=async s=>te(`/api/v1/items/publish-batches/${s}/cancel`,{}),Et=async s=>te(`/api/v1/items/publish-batches/${s}/retry-failed`,{}),Rt=async(s,a,x)=>ot(`/api/v1/items/${s}/${a}`,x),$t=s=>s.find(a=>a.status==="running"||a.status==="canceling"),Ie=s=>s==="running"||s==="canceling",Dt=s=>!!(s!=null&&s.preview_id&&Number(s.valid||0)>0),qt=s=>!!(s!=null&&s.id&&Number(s.retryable||0)>0&&!Ie(s.status)),Ut=(s,a)=>s===a,Te=s=>{switch(s){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 s||"-"}},Ke=s=>{switch(s){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"}},zt=s=>{const[a,x]=l.useState(!1),[o,d]=l.useState("upload"),[g,P]=l.useState(null),[f,L]=l.useState(null),[w,T]=l.useState(""),[K,J]=l.useState(!1),[R,G]=l.useState({catId:"",catName:"",channelCatId:"",tbCatId:""}),[y,N]=l.useState(null),[c,_]=l.useState(null),[I,$]=l.useState(null),[V,D]=l.useState([]),[q,B]=l.useState(null),[U,p]=l.useState(!1),k=l.useRef(!1),m=l.useRef(0),A=l.useCallback(async()=>{d("upload"),N(null),_(null),P(null),L(null),T(""),G({catId:"",catName:"",channelCatId:"",tbCatId:""}),D([]),B(null),x(!0),p(!0);try{const r=await Ye(20),h=$t(r);if(h!=null&&h.id){const S=await ee(h.id);$(S),_(S),d(["running","canceling"].includes(S.status)?"running":"done")}}catch(r){console.error("恢复最近批量铺货任务失败:",r)}finally{p(!1)}},[]),u=l.useCallback(async()=>{const r=w.trim();if(!s.selectedAccount){alert("请先选择默认发布账号");return}if(!r){alert("请输入类目关键词");return}J(!0);try{const S=(await Bt(s.selectedAccount,r)).category;G({catId:S.cat_id,catName:S.cat_name,channelCatId:S.channel_cat_id,tbCatId:S.tb_cat_id||""})}catch(h){console.error("获取推荐类目失败:",h),alert((h==null?void 0:h.message)||"没有匹配到类目,请换一个更具体的关键词")}finally{J(!1)}},[w,s.selectedAccount]),M=l.useCallback(async()=>{if(I!=null&&I.id){p(!0),x(!0);try{const r=await ee(I.id);_(r),d(["running","canceling"].includes(r.status)?"running":"done")}catch(r){console.error("加载最近批量铺货结果失败:",r)}finally{p(!1)}}},[I==null?void 0:I.id]),se=l.useCallback(async()=>{if(!g){alert("请先上传商品表格");return}if(!s.selectedAccount){alert("请先选择默认发布账号");return}p(!0);try{const r=await Ft({file:g,imagesZip:f,defaultCookieId:s.selectedAccount,fallbackCategory:R,location:q||void 0});N(r),_(null),d("preview")}catch(r){console.error("批量铺货预检失败:",r),alert((r==null?void 0:r.message)||"预检失败,请检查表格和图片 zip")}finally{p(!1)}},[R,g,f,q,s.selectedAccount]),W=l.useCallback(async()=>{if(y!=null&&y.preview_id){if(!Dt(y)){alert("没有可发布的商品行");return}p(!0);try{const r=await Lt(y.preview_id),h=await ee(r.batch_id||y.preview_id);_(h),$(h),d(h.status==="running"?"running":"done")}catch(r){console.error("启动批量铺货失败:",r),alert((r==null?void 0:r.message)||"启动发布任务失败")}finally{p(!1)}}},[y]),Y=l.useCallback(async()=>{if(c!=null&&c.id&&confirm("确认取消当前批量铺货任务吗?正在发布的单个商品可能会继续完成。")){p(!0);try{const r=await Mt(c.id),h=await ee(c.id);_(h),d((r==null?void 0:r.status)==="canceling"||h.status==="canceling"?"running":"done")}catch(r){alert((r==null?void 0:r.message)||"取消失败")}finally{p(!1)}}},[c==null?void 0:c.id]),H=l.useCallback(async()=>{const r=y==null?void 0:y.preview_id;if(r&&o==="preview")try{await At(r)}catch(h){console.error("清理批量铺货预检失败:",h)}N(null),d("upload")},[o,y==null?void 0:y.preview_id]),Q=l.useCallback(async()=>{await H(),x(!1)},[H]),ae=l.useCallback(async()=>{if(!(!(c!=null&&c.id)||!qt(c))){p(!0);try{await Et(c.id),_(await ee(c.id)),d("running")}catch(r){alert((r==null?void 0:r.message)||"重试失败")}finally{p(!1)}}},[c]);return l.useEffect(()=>{if(!a||!(c!=null&&c.id)||!Ie(c.status))return;const r=++m.current,h=async()=>{if(!k.current){k.current=!0;try{const z=await ee(c.id);if(!Ut(r,m.current))return;_(z),$(z),Ie(z.status)||(d("done"),await Promise.all([s.loadItems(),s.loadShippingRules()]))}catch(z){console.error("刷新批量铺货进度失败:",z)}finally{k.current=!1}}},S=window.setInterval(()=>void h(),3e3);return(()=>{window.clearInterval(S),m.current+=1})},[c==null?void 0:c.id,c==null?void 0:c.status,s.loadItems,s.loadShippingRules,a]),{showBatchModal:a,setShowBatchModal:x,batchLoading:U,batchPhase:o,setBatchPhase:d,batchFile:g,setBatchFile:P,batchImagesZip:f,setBatchImagesZip:L,batchCategoryKeyword:w,setBatchCategoryKeyword:T,batchCategoryLoading:K,batchFallbackCategory:R,setBatchFallbackCategory:G,batchPreview:y,setBatchPreview:N,batchDetail:c,setBatchDetail:_,recentBatch:I,setRecentBatch:$,batchLocations:V,batchLocation:q,setBatchLocations:D,setBatchLocation:B,openBatchModal:A,handleRecommendBatchCategory:u,openRecentBatchResult:M,handlePreviewBatch:se,handleStartBatch:W,handleCancelBatch:Y,abandonBatchPreview:H,closeBatchModal:Q,handleRetryBatchFailed:ae}},Je=()=>({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),Ze=(s="")=>({cookie_id:s,title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),Ce=(s,a)=>{if(s instanceof Error)return s.message;const x=typeof s=="object"&&s!==null&&"message"in s?s.message:void 0;return typeof x=="string"?x:a},Ot=({selectedAccount:s,setSelectedAccount:a,setItems:x,loadItems:o,loadShippingRules:d,onConfigureDelivery:g,setBatchLocations:P,setBatchLocation:f})=>{const[L,w]=l.useState(!1),[T,K]=l.useState(!1),[J,R]=l.useState(!1),[G,y]=l.useState(!1),[N,c]=l.useState(!1),[_,I]=l.useState(!1),[$,V]=l.useState([]),[D,q]=l.useState(null),[B,U]=l.useState(null),[p,k]=l.useState({}),[m,A]=l.useState(Je),[u,M]=l.useState(Ze),[se,W]=l.useState([]);l.useEffect(()=>{if(!N||u.images.length===0){W([]);return}const i=u.images.map((j,C)=>({key:j.name+C,url:URL.createObjectURL(j)}));return W(i),(()=>i.forEach(j=>URL.revokeObjectURL(j.url)))},[u.images,N]);const Y=l.useCallback(async()=>{if(!s)return alert("请先选择账号");w(!0);try{const i=await Ct(s);await o(),alert((i==null?void 0:i.message)||"商品同步完成")}catch(i){console.error("同步商品失败:",i),alert(Ce(i,"同步失败,请重试"))}finally{w(!1)}},[o,s]),H=l.useCallback(i=>{U(i),k({...i}),R(!0)},[]),Q=l.useCallback(async()=>{if(B)try{await Rt(B.cookie_id,B.item_id,{item_title:p.item_title||"",item_description:p.item_description||"",item_category:p.item_category||"",item_price:p.item_price||"",item_detail:p.item_detail||B.item_detail||""}),await o(),await d(),R(!1),U(null)}catch(i){console.error("更新商品失败:",i),alert("更新失败,请重试")}},[p,o,d,B]),ae=l.useCallback(async i=>{if(confirm(`确认删除商品"${i.item_title}"吗?`))try{await It(i.cookie_id,i.item_id),x(j=>j.filter(C=>!(C.cookie_id===i.cookie_id&&C.item_id===i.item_id)))}catch(j){console.error("删除商品失败:",j),alert("删除失败,请重试")}},[x]),oe=l.useCallback(async()=>{try{if(!m.cookie_id||!m.item_id){alert("请选择账号并填写商品ID");return}await St(m.cookie_id,{item_id:m.item_id,item_title:m.item_title,item_price:m.item_price,item_detail:m.item_image?JSON.stringify({item_image:m.item_image}):""}),await o(),y(!1),A(Je())}catch(i){console.error("添加商品失败:",i),alert("添加失败,请重试")}},[m,o]),r=l.useCallback(async()=>{if(!u.cookie_id)return alert("请选择发布账号");if(!u.title.trim())return alert("请填写商品标题");if(!u.price.trim())return alert("请填写商品价格");if(!u.quantity||Number(u.quantity)<=0)return alert("库存数量必须大于 0");if(u.images.length===0)return alert("至少上传 1 张商品图片");if(u.postage_mode==="fixed"&&!u.postage.trim())return alert("请填写一口价邮费");K(!0);try{const i=await Pt({...u,location:D||void 0});if(await o(),c(!1),M(Ze(s||"")),V([]),q(null),i!=null&&i.item_id){const j={id:i.item_id,cookie_id:u.cookie_id,item_id:i.item_id,item_title:i.item_title||u.title,item_price:i.item_price||u.price,item_image:i.item_image};g(j),alert("商品发布成功,ID: "+i.item_id+",已为你打开发货规则配置")}else alert("商品发布成功")}catch(i){console.error("发布商品失败:",i);const j=i==null?void 0:i.payload;if((j==null?void 0:j.code)==="stock_permission_missing"){alert("发布失败:该账号没有库存发布权限,无法按库存数量发布商品。请换账号或先在闲鱼确认库存能力。");return}alert(Ce(i,"发布失败,请重试"))}finally{K(!1)}},[o,g,u,D,s]),h=l.useCallback(()=>{const C=[["账号ID","标题","描述","价格","原价","库存","邮费模式","邮费","图片","类目ID","类目名称","频道类目ID","淘宝类目ID","付款发货启用","付款发货内容","评价赠品启用","评价赠品内容","求评价启用","求评价等待小时","求评价文案","求评价最多次数"],...[["","会员组合包自动发货","下单后发送主卡和附赠卡。","19.90","29.90","10","free","","images/bundle-1.jpg;images/bundle-2.jpg","","","","","是","101:1;102:1","是","201:1;202:2","是","72","亲,满意的话麻烦给个评价,谢谢~","1"],["","普通商品","仅发布商品,不创建自动化规则。","49.90","","10","fixed","8.00","https://example.com/product.jpg","","","","","否","","否","","否","","",""]]].map(je=>je.map(Ne=>`"${String(Ne).replace(/"/g,'""')}"`).join(",")).join(` `),F=new Blob(["\uFEFF"+C],{type:"text/csv;charset=utf-8"}),xe=URL.createObjectURL(F),X=document.createElement("a");X.href=xe,X.download="批量铺货模板.csv",document.body.appendChild(X),X.click(),X.remove(),URL.revokeObjectURL(xe)},[]),S=l.useCallback(()=>{A(i=>({...i,cookie_id:s||i.cookie_id})),y(!0)},[s]),z=l.useCallback(()=>{M(i=>({...i,cookie_id:s||i.cookie_id})),c(!0)},[s]),fe=l.useCallback(async i=>{if(!(i?s:u.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");I(!0),navigator.geolocation.getCurrentPosition(async C=>{try{const F=await _t(C.coords.longitude,C.coords.latitude);if(!F.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");i?(P(F),f(F[0])):(V(F),q(F[0]))}catch(F){alert(Ce(F,"获取发货地失败"))}finally{I(!1)}},C=>{I(!1),alert(C.code===C.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},[u.cookie_id,s,f,P]);return{selectedAccount:s,setSelectedAccount:a,loading:L,publishing:T,showEditModal:J,setShowEditModal:R,showAddModal:G,setShowAddModal:y,showPublishModal:N,setShowPublishModal:c,locationLoading:_,publishLocations:$,setPublishLocations:V,publishLocation:D,setPublishLocation:q,selectedItem:B,editForm:p,setEditForm:k,addForm:m,setAddForm:A,publishForm:u,setPublishForm:M,publishImagePreviews:se,handleSync:Y,handleEdit:H,handleSaveEdit:Q,handleDelete:ae,handleAddItem:oe,handlePublishItem:r,downloadPublishTemplate:h,openAddModal:S,openPublishModal:z,locateForPublish:fe}},Tt=({phase:s})=>{const a=[["upload","1 上传"],["preview","2 预检"],["running","3 发布"],["done","4 结果"]];return e.jsx("div",{className:"grid grid-cols-4 gap-2",children:a.map(([x,o])=>e.jsx("div",{className:`rounded-xl px-3 py-2 text-center text-xs font-extrabold border ${s===x?"bg-blue-600 text-white border-blue-600":"bg-gray-50 text-gray-500 border-gray-100"}`,children:o},x))})},Kt=s=>{const a=String(s||"").trim();return a?/^[¥¥]/.test(a)?a:`¥${a}`:"-"},Wt=({onConfigureDelivery:s})=>{const[a,x]=l.useState([]),[o,d]=l.useState([]),[g,P]=l.useState([]),[f,L]=l.useState(""),[w,T]=l.useState(""),K=l.useCallback(async()=>{const t=await Oe();x(t)},[]),J=l.useCallback(async()=>{d(await ze())},[]),R=zt({selectedAccount:f,loadItems:K,loadShippingRules:J}),{showBatchModal:G,setShowBatchModal:y,batchLoading:N,batchPhase:c,batchFile:_,setBatchFile:I,batchImagesZip:$,setBatchImagesZip:V,batchCategoryKeyword:D,setBatchCategoryKeyword:q,batchCategoryLoading:B,batchFallbackCategory:U,setBatchFallbackCategory:p,batchPreview:k,batchDetail:m,recentBatch:A,setRecentBatch:u,batchLocations:M,batchLocation:se,setBatchLocations:W,setBatchLocation:Y,openBatchModal:H,handleRecommendBatchCategory:Q,openRecentBatchResult:ae,handlePreviewBatch:oe,handleStartBatch:r,handleCancelBatch:h,abandonBatchPreview:S,closeBatchModal:z,handleRetryBatchFailed:fe}=R,i=Ot({selectedAccount:f,setSelectedAccount:L,setItems:x,loadItems:K,loadShippingRules:J,onConfigureDelivery:s,setBatchLocations:W,setBatchLocation:Y}),{loading:j,publishing:C,showEditModal:F,setShowEditModal:xe,showAddModal:X,setShowAddModal:je,showPublishModal:Ne,setShowPublishModal:He,locationLoading:me,publishLocations:he,setPublishLocations:Xe,publishLocation:Qe,setPublishLocation:Se,selectedItem:Pe,editForm:Z,setEditForm:ue,addForm:E,setAddForm:le,publishForm:b,setPublishForm:O,publishImagePreviews:Be,handleSync:et,handleEdit:tt,handleSaveEdit:st,handleDelete:at,handleAddItem:lt,handlePublishItem:it,downloadPublishTemplate:nt,openAddModal:rt,openPublishModal:ct,locateForPublish:Fe}=i;l.useEffect(()=>{Promise.all([kt(),Oe(),ze(),Ye(20)]).then(([t,n,v,ne])=>{P(t),x(n),d(v);const pe=ne.find(ve=>["running","canceling"].includes(ve.status))||ne.find(ve=>ve.status!=="preview");u(pe||null)}).catch(t=>console.error("加载商品配置失败:",t))},[]);const dt=t=>o.filter(n=>n.cookie_id===t.cookie_id&&n.item_id===t.item_id).length>0?o.filter(n=>n.cookie_id===t.cookie_id&&n.item_id===t.item_id):o.filter(n=>n.cookie_id===t.cookie_id&&!n.item_id),Le=l.useMemo(()=>new Map(g.map(t=>[t.id,t])),[g]),Ae=l.useMemo(()=>w?a.filter(t=>t.cookie_id===w):a,[w,a]),ie=t=>{const n=Le.get(t),v=(n==null?void 0:n.remark)||(n==null?void 0:n.nickname);return v?`${v} · ${t.slice(0,6)}`:`账号 ${t.slice(0,8)}`},Me=t=>{const n=Le.get(t);return(n==null?void 0:n.remark)||(n==null?void 0:n.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(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-account-filter","aria-label":"按账号筛选商品列表",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:w,onChange:(t=>T(t.target.value)),children:[e.jsx("option",{value:"",children:"全部账号"}),g.map(t=>e.jsx("option",{value:t.id,children:ie(t.id)},t.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(Ee,{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:f,onChange:(t=>L(t.target.value)),children:[e.jsx("option",{value:"",children:"请选择账号"}),g.map(t=>e.jsx("option",{value:t.id,children:ie(t.id)},t.id))]})]})]}),e.jsxs("button",{onClick:et,disabled:j||!f,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(we,{className:`w-4 h-4 ${j?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:rt,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(Re,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:ct,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(_e,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:(()=>void H()),className:"px-5 py-3 rounded-2xl font-bold bg-brand text-white hover:bg-brand-highlight transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[e.jsx(be,{className:"w-4 h-4"}),A&&["running","canceling"].includes(A.status)?"继续批量任务":"批量铺货"]}),A&&!["running","canceling"].includes(A.status)&&e.jsx("button",{onClick:(()=>void ae()),className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"最近批次结果"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[Ae.map(t=>{const n=dt(t),v=n.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relative flex flex-col",children:[e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity z-10",children:[e.jsx("button",{onClick:(()=>tt(t)),className:"p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md text-gray-600 hover:bg-brand hover:text-white transition-colors",title:"编辑",children:e.jsx(mt,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:(()=>at(t)),className:"p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md hover:bg-red-100 text-red-500 transition-colors",title:"删除",children:e.jsx(ht,{className:"w-3.5 h-3.5"})})]}),e.jsxs("div",{className:"aspect-square bg-gray-100 rounded-xl mb-2.5 overflow-hidden relative",children:[t.item_image?e.jsx("img",{src:t.item_image,alt:"",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-gray-300",children:e.jsx(ut,{className:"w-8 h-8"})}),e.jsx("div",{className:"absolute top-1.5 left-1.5 bg-black/50 backdrop-blur-md text-white text-[10px] font-bold px-1.5 py-0.5 rounded-md",children:Kt(t.item_price)})]}),e.jsx("h3",{className:"font-bold text-gray-900 line-clamp-2 text-xs mb-1.5 h-8 leading-4",children:t.item_title}),e.jsxs("div",{className:"mb-2 inline-flex min-w-0 max-w-full items-center gap-1 self-start rounded-md bg-blue-50 px-2 py-1 text-[10px] font-extrabold text-blue-700",title:Me(t.cookie_id),children:[e.jsx(Ee,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"min-w-0 truncate whitespace-nowrap",children:Me(t.cookie_id)})]}),e.jsxs("div",{className:"flex justify-between items-center text-[10px] text-gray-500 mb-2",children:[e.jsxs("span",{className:"bg-gray-100 px-1.5 py-0.5 rounded truncate max-w-[80px]",children:["ID: ",t.item_id]}),e.jsxs("span",{className:`inline-flex items-center gap-1 font-bold ${v?"text-emerald-600":"text-amber-600"}`,children:[v?e.jsx($e,{className:"w-3 h-3"}):e.jsx(pt,{className:"w-3 h-3"}),v?`${n.length} 规则`:"未配置"]})]}),e.jsx("div",{className:"space-y-2 mt-auto",children:e.jsxs("button",{onClick:(()=>s(t)),className:`w-full flex items-center justify-between gap-1 px-2.5 py-2 rounded-lg text-[11px] font-extrabold transition-all ${v?"bg-gray-900 text-white hover:bg-black":"bg-brand text-white hover:bg-brand-highlight shadow-md shadow-blue-100"}`,children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(gt,{className:"w-3.5 h-3.5"}),v?"查看发货规则":"关联发货规则"]}),e.jsx(bt,{className:"w-3.5 h-3.5"})]})})]},`${t.cookie_id}-${t.item_id}`)}),Ae.length===0&&e.jsxs("div",{className:"col-span-full py-20 text-center text-gray-400",children:[e.jsx(yt,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),w?"该账号暂无商品数据":"暂无商品数据,请选择账号进行同步"]})]}),F&&Pe&&ge.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"560px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"编辑商品"}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["ID: ",Pe.item_id]})]}),e.jsx("button",{onClick:(()=>xe(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(re,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-4",children:[e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"商品标题",value:Z.item_title||"",onChange:(t=>ue({...Z,item_title:t.target.value}))}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"价格",value:Z.item_price||"",onChange:(t=>ue({...Z,item_price:t.target.value}))}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"分类",value:Z.item_category||"",onChange:(t=>ue({...Z,item_category:t.target.value}))}),e.jsx("textarea",{className:"w-full ios-input px-4 py-3 rounded-xl h-28 resize-none",placeholder:"描述",value:Z.item_description||"",onChange:(t=>ue({...Z,item_description:t.target.value}))})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{onClick:st,className:"w-full ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(ft,{className:"w-4 h-4"}),"保存"]})})]})}),document.body),X&&ge.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"720px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"添加商品"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"手动建立商品与自动发货规则的关联"})]}),e.jsx("button",{onClick:(()=>je(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(re,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-5",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",{className:"w-full ios-input px-4 py-3 rounded-xl",value:E.cookie_id,onChange:(t=>le({...E,cookie_id:t.target.value})),children:[e.jsx("option",{value:"",children:"选择账号"}),g.map(t=>e.jsx("option",{value:t.id,children:ie(t.id)},t.id))]})]}),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:"商品 ID"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"输入闲鱼商品 ID",value:E.item_id,onChange:(t=>le({...E,item_id:t.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品价格"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如 99.00",value:E.item_price,onChange:(t=>le({...E,item_price:t.target.value}))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品标题"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"输入商品标题",value:E.item_title,onChange:(t=>le({...E,item_title:t.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"图片 URL"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"https://...",value:E.item_image,onChange:(t=>le({...E,item_image:t.target.value}))})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{onClick:lt,className:"w-full ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Re,{className:"w-4 h-4"}),"添加商品"]})})]})}),document.body),Ne&&ge.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"820px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"发布商品到闲鱼"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"普通单规格发布;库存数量会写入闲鱼发布参数,用于判断账号库存能力。"})]}),e.jsx("button",{onClick:(()=>He(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(re,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsx("div",{className:"rounded-2xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-800 leading-6",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",{className:"w-full ios-input px-4 py-3 rounded-xl",value:b.cookie_id,onChange:(t=>{O({...b,cookie_id:t.target.value}),Xe([]),Se(null)}),children:[e.jsx("option",{value:"",children:"选择账号"}),g.map(t=>e.jsx("option",{value:t.id,children:ie(t.id)},t.id))]})]}),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.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:会员月卡自动发货",value:b.title,onChange:(t=>O({...b,title:t.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"库存数量"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",type:"number",min:"1",placeholder:"必须大于 0",value:b.quantity,onChange:(t=>O({...b,quantity:t.target.value}))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品描述"}),e.jsx("textarea",{className:"w-full ios-input px-4 py-3 rounded-xl h-28 resize-none",placeholder:"描述会用于自动识别类目;留空时使用标题",value:b.description,onChange:(t=>O({...b,description:t.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 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",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"99.00",value:b.price,onChange:(t=>O({...b,price:t.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"原价(可选)"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"129.00",value:b.original_price,onChange:(t=>O({...b,original_price:t.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"运费方式"}),e.jsxs("select",{className:"w-full ios-input px-4 py-3 rounded-xl",value:b.postage_mode,onChange:(t=>O({...b,postage_mode:t.target.value})),children:[e.jsx("option",{value:"free",children:"包邮"}),e.jsx("option",{value:"distance",children:"按距离计费"}),e.jsx("option",{value:"fixed",children:"一口价邮费"}),e.jsx("option",{value:"none",children:"无需邮寄"})]})]})]}),b.postage_mode==="fixed"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"一口价邮费"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如 8.00",value:b.postage,onChange:(t=>O({...b,postage:t.target.value}))})]}),e.jsxs("div",{className:"rounded-2xl border border-sky-200 bg-sky-50 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"发货地(可选)"}),e.jsx("p",{className:"mt-1 text-xs text-sky-800",children:"虚拟商品无需发货地;发布失败时可再定位并作为补充信息提交。"})]}),e.jsxs("button",{type:"button",disabled:me||!b.cookie_id,onClick:(()=>void Fe(!1)),className:"ios-btn-primary flex items-center gap-2 rounded-xl px-4 py-2 text-sm font-bold disabled:opacity-50",children:[e.jsx(De,{className:"h-4 w-4"}),me?"定位中...":"获取当前位置"]})]}),he.length>0&&e.jsx("select",{className:"w-full ios-input rounded-xl bg-white px-4 py-3",value:String(Math.max(0,he.indexOf(Qe))),onChange:(t=>Se(he[Number(t.target.value)]||null)),children:he.map((t,n)=>e.jsx("option",{value:String(n),children:[t.province,t.city,t.area,t.poi_name].filter(Boolean).join(" ")},`${t.division_id}-${t.poi_id}-${n}`))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品图片(1-9 张)"}),e.jsxs("label",{className:"flex min-h-[120px] cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed border-gray-200 bg-gray-50 px-4 py-6 text-center hover:border-emerald-300 hover:bg-emerald-50/50 transition-colors",children:[e.jsx(be,{className:"w-8 h-8 text-emerald-600 mb-2"}),e.jsx("span",{className:"text-sm font-bold text-gray-800",children:"选择图片"}),e.jsx("span",{className:"text-xs text-gray-500 mt-1",children:b.images.length?"已选择 "+b.images.length+" 张":"支持 JPG / PNG / GIF"}),e.jsx("input",{className:"hidden",type:"file",accept:"image/*",multiple:!0,onChange:(t=>O({...b,images:Array.from(t.target.files||[]).slice(0,9)}))})]}),Be.length>0&&e.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-3",children:Be.map(t=>e.jsx("div",{className:"aspect-square rounded-xl bg-gray-100 overflow-hidden border border-gray-100",children:e.jsx("img",{src:t.url,alt:"",className:"w-full h-full object-cover"})},t.key))})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{disabled:C,onClick:it,className:"w-full bg-emerald-500 hover:bg-emerald-600 disabled:opacity-60 text-white px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(_e,{className:"w-4 h-4"}),C?"正在发布...":"发布到闲鱼"]})})]})}),document.body),G&&ge.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"980px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量铺货"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"上传商品表格和图片 zip,先预检,再逐条发布到闲鱼。"})]}),e.jsx("button",{onClick:(()=>void z()),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(re,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsx(Tt,{phase:c}),c==="upload"&&e.jsxs("div",{className:"space-y-5",children:[e.jsx("div",{className:"rounded-2xl border border-blue-100 bg-blue-50 p-4 text-sm text-blue-900 leading-6",children:e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-extrabold",children:"先下载模板,再按字段填写。"}),e.jsxs("div",{children:["图片字段写 zip 内相对路径,多个图片用英文分号分隔,例如 ",e.jsx("span",{className:"font-mono font-bold",children:"images/a.jpg;images/b.jpg"}),"。也支持直接填写图片 URL。"]})]}),e.jsx("button",{type:"button",onClick:nt,className:"shrink-0 rounded-xl bg-blue-600 px-4 py-2 text-sm font-extrabold text-white hover:bg-blue-700",children:"下载CSV模板"})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"默认发布账号"}),e.jsxs("select",{className:"w-full ios-input px-4 py-3 rounded-xl",value:f,onChange:(t=>{L(t.target.value),W([]),Y(null)}),children:[e.jsx("option",{value:"",children:"选择账号"}),g.map(t=>e.jsx("option",{value:t.id,children:ie(t.id)},t.id))]}),e.jsx("p",{className:"text-xs text-gray-500",children:"表格中“账号ID”为空时,会使用这里选择的账号。"})]}),e.jsxs("div",{className:"rounded-xl border border-amber-200 bg-amber-50/70 p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-sm font-extrabold text-gray-900",children:["默认类目 ",e.jsx("span",{className:"font-medium text-gray-500",children:"(可为空)"})]}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-amber-800",children:"填写后优先使用该类目;留空时由闲鱼根据每件商品自动识别。仍无法识别时,系统最终使用“电子资料”兜底。"})]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[e.jsxs("label",{className:"relative flex-1",children:[e.jsx("span",{className:"sr-only",children:"类目关键词"}),e.jsx(qe,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{className:"w-full ios-input rounded-xl bg-white py-2.5 pl-10 pr-3",placeholder:"输入关键词,例如:课程资料、设计素材",value:D,onChange:(t=>q(t.target.value)),onKeyDown:(t=>{t.key==="Enter"&&(t.preventDefault(),Q())})})]}),e.jsxs("button",{type:"button",disabled:!f||!D.trim()||B,onClick:(()=>void Q()),className:"ios-btn-primary flex min-h-[42px] items-center justify-center gap-2 rounded-xl px-4 text-sm font-bold disabled:opacity-50",children:[e.jsx(qe,{className:"h-4 w-4"}),B?"匹配中...":"获取类目"]})]}),U.catId?e.jsxs("div",{className:"flex min-h-[46px] items-center justify-between gap-3 border-t border-amber-200 pt-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-bold text-gray-900",children:[e.jsx($e,{className:"h-4 w-4 shrink-0 text-emerald-600"}),e.jsx("span",{className:"truncate",children:U.catName})]}),e.jsxs("div",{className:"mt-1 font-mono text-xs text-gray-500",children:["类目 ",U.catId," · 频道 ",U.channelCatId]})]}),e.jsx("button",{type:"button",title:"清除默认类目",onClick:(()=>p({catId:"",catName:"",channelCatId:"",tbCatId:""})),className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg text-gray-500 hover:bg-white hover:text-gray-900",children:e.jsx(re,{className:"h-4 w-4"})})]}):null]}),e.jsxs("div",{className:"rounded-xl border border-sky-200 bg-sky-50 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"批次发货地(可选)"}),e.jsx("p",{className:"mt-1 text-xs text-sky-800",children:"虚拟商品可留空;填写后整个批次使用同一个发货地,并随任务保存用于恢复和重试。"})]}),e.jsxs("button",{type:"button",disabled:me||!f,onClick:(()=>void Fe(!0)),className:"ios-btn-primary flex items-center gap-2 rounded-xl px-4 py-2 text-sm font-bold disabled:opacity-50",children:[e.jsx(De,{className:"h-4 w-4"}),me?"定位中...":"获取当前位置"]})]}),M.length>0&&e.jsx("select",{className:"w-full ios-input rounded-xl bg-white px-4 py-3",value:String(Math.max(0,M.indexOf(se))),onChange:(t=>Y(M[Number(t.target.value)]||null)),children:M.map((t,n)=>e.jsx("option",{value:String(n),children:[t.province,t.city,t.area,t.poi_name].filter(Boolean).join(" ")},`${t.division_id}-${t.poi_id}-${n}`))})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("label",{className:"flex min-h-[150px] cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed border-gray-200 bg-gray-50 px-4 py-6 text-center hover:border-blue-300 hover:bg-blue-50 transition-colors",children:[e.jsx(be,{className:"w-9 h-9 text-blue-600 mb-3"}),e.jsx("span",{className:"text-sm font-extrabold text-gray-900",children:"上传商品表格"}),e.jsx("span",{className:"text-xs text-gray-500 mt-1",children:_?_.name:"支持 .xlsx / .csv / .tsv"}),e.jsx("input",{className:"hidden",type:"file",accept:".xlsx,.csv,.tsv",onChange:(t=>{var n;return I(((n=t.target.files)==null?void 0:n[0])||null)})})]}),e.jsxs("label",{className:"flex min-h-[150px] cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed border-gray-200 bg-gray-50 px-4 py-6 text-center hover:border-emerald-300 hover:bg-emerald-50 transition-colors",children:[e.jsx(be,{className:"w-9 h-9 text-emerald-600 mb-3"}),e.jsx("span",{className:"text-sm font-extrabold text-gray-900",children:"上传图片 zip(可选)"}),e.jsx("span",{className:"text-xs text-gray-500 mt-1",children:$?$.name:"表格图片字段使用 zip 内相对路径"}),e.jsx("input",{className:"hidden",type:"file",accept:".zip",onChange:(t=>{var n;return V(((n=t.target.files)==null?void 0:n[0])||null)})})]})]}),e.jsxs("div",{className:"rounded-2xl bg-gray-50 border border-gray-100 p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"字段说明"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"照着下面的“什么时候填写”处理即可。预检发现问题时,会指出具体哪一行需要修改。"})]}),e.jsxs("div",{className:"rounded-xl border border-blue-100 bg-blue-50 p-4 text-xs text-blue-950",children:[e.jsx("div",{className:"text-sm font-extrabold",children:"“付款后发送的卡密”怎么填"}),e.jsxs("div",{className:"mt-3 grid grid-cols-1 gap-3 lg:grid-cols-3",children:[e.jsxs("div",{className:"rounded-lg bg-white/80 p-3",children:[e.jsx("code",{className:"font-bold text-blue-700",children:"101"}),e.jsx("p",{className:"mt-1 leading-5",children:"从卡密组 101 立即发送 1 份。卡密组 ID 可以在“卡密库存”页面查看。"})]}),e.jsxs("div",{className:"rounded-lg bg-white/80 p-3",children:[e.jsx("code",{className:"font-bold text-blue-700",children:"101:2"}),e.jsx("p",{className:"mt-1 leading-5",children:"每购买 1 件,就从卡密组 101 发送 2 份。买家购买 3 件时会发送 6 份。"})]}),e.jsxs("div",{className:"rounded-lg bg-white/80 p-3",children:[e.jsx("code",{className:"font-bold text-blue-700",children:"101:1:0;102:2:3"}),e.jsx("p",{className:"mt-1 leading-5",children:"先立即发送卡密组 101 的 1 份,再等待 3 秒发送卡密组 102 的 2 份。"})]})]}),e.jsxs("p",{className:"mt-3 leading-5 text-blue-800",children:["每一组依次写“卡密组 ID : 每件发送几份 : 等待几秒”。份数不写时按 1 份处理,等待时间不写时立即发送。需要发送多种卡密时,用英文分号 ",e.jsx("code",{className:"font-bold",children:";"})," 隔开。"]})]}),e.jsx("div",{className:"overflow-x-auto rounded-xl border border-gray-100 bg-white",children:e.jsxs("table",{className:"w-full text-left text-xs",children:[e.jsx("thead",{className:"bg-gray-50 text-gray-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2",children:"字段"}),e.jsx("th",{className:"px-3 py-2",children:"什么时候填写"}),e.jsx("th",{className:"px-3 py-2",children:"填写方法"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50 text-gray-700",children:[["账号ID","需要覆盖默认账号时填写","上方默认发布账号为必选;本列留空时使用默认账号,填写后仅覆盖当前行"],["标题","每个商品都要填","填写买家能看到的商品标题"],["描述","可以留空","留空时会使用商品标题作为描述"],["价格","每个商品都要填","只填数字,例如 19.90"],["原价","可以留空","需要展示划线原价时填写,例如 29.90"],["库存","可以留空","留空按 1 件处理;填写时必须大于 0"],["邮费模式","可以留空","留空表示包邮;包邮填 free,固定邮费填 fixed"],["邮费","邮费模式填 fixed 时填写","只填数字,例如 8.00"],["图片","每个商品都要填","填写 zip 内图片路径或图片网址;多张图片用英文分号隔开"],["类目ID","需要指定当前行默认类目时填写","必须和“类目名称、频道类目ID”同时填写;优先于自动识别"],["类目名称","填写了“类目ID”时必填","填写该 ID 对应的准确类目名称"],["频道类目ID","覆盖类目时必填","必须填写闲鱼返回的准确频道类目 ID"],["淘宝类目ID","按闲鱼返回填写","“电子资料”无淘宝类目 ID,保持为空"],["付款发货启用","需要付款后自动发货时填写","填“是”表示开启;不需要时填“否”或留空"],["付款发货内容","“付款发货启用”填“是”时填写","从“卡密库存”页面取得卡密组 ID,按上方示例填写"],["评价赠品启用","需要评价赠品时填写","填“是”表示开启;不需要时填“否”或留空"],["评价赠品内容","“评价赠品启用”填“是”时填写","格式和付款发货内容相同,也可以同时发送多个卡密组"],["求评价启用","需要自动求评价时填写","填“是”表示开启;不需要时填“否”或留空"],["求评价等待小时","“求评价启用”填“是”时填写","填写等待小时数;留空按 72 小时处理"],["求评价文案","“求评价启用”填“是”时填写","填写要发送给买家的求评价消息"],["求评价最多次数","可以留空","留空只提醒 1 次"]].map(([t,n,v])=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-bold text-gray-900 whitespace-nowrap",children:t}),e.jsx("td",{className:`px-3 py-2 min-w-[210px] font-bold ${n==="每个商品都要填"?"text-red-600":n==="可以留空"?"text-gray-500":"text-amber-700"}`,children:n}),e.jsx("td",{className:"px-3 py-2 min-w-[260px]",children:v})]},t))})]})})]})]}),c==="preview"&&k&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"rounded-2xl bg-gray-50 p-4 border border-gray-100",children:[e.jsx("div",{className:"text-xs font-bold text-gray-500",children:"总行数"}),e.jsx("div",{className:"text-2xl font-extrabold text-gray-900 mt-1",children:k.total})]}),e.jsxs("div",{className:"rounded-2xl bg-emerald-50 p-4 border border-emerald-100",children:[e.jsx("div",{className:"text-xs font-bold text-emerald-700",children:"可发布"}),e.jsx("div",{className:"text-2xl font-extrabold text-emerald-700 mt-1",children:k.valid})]}),e.jsxs("div",{className:"rounded-2xl bg-red-50 p-4 border border-red-100",children:[e.jsx("div",{className:"text-xs font-bold text-red-700",children:"有问题"}),e.jsx("div",{className:"text-2xl font-extrabold text-red-700 mt-1",children:k.invalid})]})]}),e.jsx("div",{className:"max-h-[380px] overflow-y-auto rounded-2xl border border-gray-100",children:e.jsxs("table",{className:"w-full text-left text-sm",children:[e.jsx("thead",{className:"sticky top-0 bg-white text-xs text-gray-400 border-b border-gray-100",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3",children:"行号"}),e.jsx("th",{className:"px-4 py-3",children:"状态"}),e.jsx("th",{className:"px-4 py-3",children:"标题"}),e.jsx("th",{className:"px-4 py-3",children:"价格/库存"}),e.jsx("th",{className:"px-4 py-3",children:"类目策略"}),e.jsx("th",{className:"px-4 py-3",children:"图片"}),e.jsx("th",{className:"px-4 py-3",children:"问题"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:k.rows.map(t=>{var n,v,ne,pe;return e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 font-mono text-xs",children:t.row_no}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:`inline-flex px-2 py-1 rounded-lg border text-xs font-extrabold ${t.valid?"bg-emerald-50 text-emerald-700 border-emerald-100":"bg-red-50 text-red-700 border-red-100"}`,children:t.valid?"可发布":"需修正"})}),e.jsx("td",{className:"px-4 py-3 font-bold text-gray-900 max-w-[240px] truncate",children:t.title||"-"}),e.jsxs("td",{className:"px-4 py-3 text-gray-600",children:["¥",t.price||"-"," / ",t.quantity||1]}),e.jsxs("td",{className:"px-4 py-3 text-xs text-gray-600 min-w-[150px]",children:[e.jsx("div",{className:"font-bold text-gray-800",children:((n=t.category)==null?void 0:n.cat_name)||"自动识别"}),e.jsx("div",{className:"font-mono text-gray-400",children:((v=t.category)==null?void 0:v.cat_id)||"失败后使用电子资料"})]}),e.jsxs("td",{className:"px-4 py-3 text-gray-600",children:[((ne=t.images)==null?void 0:ne.length)||0," 张"]}),e.jsx("td",{className:"px-4 py-3 text-red-600 text-xs max-w-[280px]",children:((pe=t.errors)==null?void 0:pe.join(";"))||"-"})]},t.row_no)})})]})})]}),(c==="running"||c==="done")&&m&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsxs("div",{className:`rounded-2xl p-4 border ${Ke(m.status)}`,children:[e.jsx("div",{className:"text-xs font-bold opacity-70",children:"任务状态"}),e.jsx("div",{className:"text-xl font-extrabold mt-1",children:Te(m.status)})]}),e.jsxs("div",{className:"rounded-2xl bg-gray-50 p-4 border border-gray-100",children:[e.jsx("div",{className:"text-xs font-bold text-gray-500",children:"总数"}),e.jsx("div",{className:"text-xl font-extrabold text-gray-900 mt-1",children:m.total})]}),e.jsxs("div",{className:"rounded-2xl bg-emerald-50 p-4 border border-emerald-100",children:[e.jsx("div",{className:"text-xs font-bold text-emerald-700",children:"成功"}),e.jsx("div",{className:"text-xl font-extrabold text-emerald-700 mt-1",children:m.success})]}),e.jsxs("div",{className:"rounded-2xl bg-red-50 p-4 border border-red-100",children:[e.jsx("div",{className:"text-xs font-bold text-red-700",children:"失败"}),e.jsx("div",{className:"text-xl font-extrabold text-red-700 mt-1",children:m.failed})]}),e.jsxs("div",{className:"rounded-2xl bg-blue-50 p-4 border border-blue-100",children:[e.jsx("div",{className:"text-xs font-bold text-blue-700",children:"等待"}),e.jsx("div",{className:"text-xl font-extrabold text-blue-700 mt-1",children:m.pending})]})]}),e.jsx("div",{className:"max-h-[420px] overflow-y-auto rounded-2xl border border-gray-100",children:e.jsxs("table",{className:"w-full text-left text-sm",children:[e.jsx("thead",{className:"sticky top-0 bg-white text-xs text-gray-400 border-b border-gray-100",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3",children:"行号"}),e.jsx("th",{className:"px-4 py-3",children:"状态"}),e.jsx("th",{className:"px-4 py-3",children:"标题"}),e.jsx("th",{className:"px-4 py-3",children:"类目策略"}),e.jsx("th",{className:"px-4 py-3",children:"商品ID"}),e.jsx("th",{className:"px-4 py-3",children:"错误原因"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:m.rows.map(t=>{var n,v;return e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 font-mono text-xs",children:t.row_no}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:`inline-flex px-2 py-1 rounded-lg border text-xs font-extrabold ${Ke(t.status)}`,children:Te(t.status)})}),e.jsx("td",{className:"px-4 py-3 font-bold text-gray-900 max-w-[260px] truncate",children:t.title}),e.jsxs("td",{className:"px-4 py-3 text-xs text-gray-600 min-w-[150px]",children:[e.jsx("div",{className:"font-bold text-gray-800",children:((n=t.category)==null?void 0:n.cat_name)||"自动识别"}),e.jsx("div",{className:"font-mono text-gray-400",children:((v=t.category)==null?void 0:v.cat_id)||"失败后使用电子资料"})]}),e.jsx("td",{className:"px-4 py-3 text-xs font-mono",children:t.item_url?e.jsx("a",{href:t.item_url,target:"_blank",rel:"noreferrer",className:"text-blue-600 hover:underline",children:t.item_id}):t.item_id||"-"}),e.jsx("td",{className:"px-4 py-3 text-red-600 text-xs max-w-[340px]",children:t.error_message||"-"})]},t.id)})})]})})]})]}),e.jsxs("div",{className:"modal-footer",children:[c==="upload"&&e.jsxs("button",{disabled:N||!_||!f,onClick:oe,className:"w-full ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2 disabled:opacity-50",children:[e.jsx(we,{className:`w-4 h-4 ${N?"animate-spin":""}`}),N?"正在预检...":"开始预检"]}),c==="preview"&&k&&e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{disabled:N,onClick:(()=>void S()),className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold",children:"返回修改"}),e.jsxs("button",{disabled:N||k.valid<=0,onClick:r,className:"flex-1 ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2 disabled:opacity-50",children:[e.jsx(_e,{className:"w-4 h-4"}),N?"启动中...":`确认发布 ${k.valid} 个商品`]})]}),(c==="running"||c==="done")&&m&&e.jsxs("div",{className:"flex gap-3 w-full",children:[m.status==="running"?e.jsx("button",{disabled:N,onClick:h,className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-900 text-white hover:bg-black font-bold",children:"取消任务"}):m.status==="canceling"?e.jsx("button",{disabled:!0,className:"flex-1 px-6 py-3.5 rounded-xl bg-amber-100 text-amber-800 font-bold",children:"正在保存远端结果并安全取消…"}):e.jsx("button",{onClick:(()=>window.open(`/api/v1/items/publish-batches/${m.id}/result.csv`,"_blank")),className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-900 text-white hover:bg-black font-bold",children:"下载结果"}),m.retryable>0&&!["running","canceling"].includes(m.status)&&e.jsxs("button",{disabled:N,onClick:fe,className:"flex-1 ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(we,{className:`w-4 h-4 ${N?"animate-spin":""}`}),"重试失败项"]}),!["running","canceling"].includes(m.status)&&e.jsx("button",{onClick:(()=>{y(!1),K(),J()}),className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold",children:"完成"})]})]})]})}),document.body)]})};export{Wt as default}; diff --git a/internal/webui/static/assets/Notifications-BJQ8JgFo.js b/internal/webui/static/assets/Notifications-Dvclt-gX.js similarity index 99% rename from internal/webui/static/assets/Notifications-BJQ8JgFo.js rename to internal/webui/static/assets/Notifications-Dvclt-gX.js index 2c200e2..a0b6de7 100644 --- a/internal/webui/static/assets/Notifications-BJQ8JgFo.js +++ b/internal/webui/static/assets/Notifications-Dvclt-gX.js @@ -1 +1 @@ -import{j as e,b as _e,r as d}from"./react-vendor-C_od1ZSF.js";import{ai as ee,ah as se,aj as Ne,x as K,e as W,L as I,y as ve,F as ke,s as Q,X as te,u as ae,v as ne,r as we,R as Se,N as Ce}from"./icons-vendor-CvzvbbIV.js";import{g as re,p as le,a as oe,d as Te}from"./index-CFzx5gQT.js";const H=["smtp_server","smtp_port","smtp_user","smtp_password","smtp_from_name","smtp_from_address","smtp_use_tls","smtp_use_ssl"],G=(s,t)=>{if(typeof s=="boolean")return s;if(typeof s=="string"){if(["true","1","yes","on"].includes(s.toLowerCase()))return!0;if(["false","0","no","off"].includes(s.toLowerCase()))return!1}return t},ie=s=>{const t=Object.prototype.hasOwnProperty.call(s,"use_custom_smtp"),a=H.some(n=>String(s[n]??"").trim()!=="");return{...s,use_custom_smtp:t?G(s.use_custom_smtp,!1):a}},ce=(s,t)=>{const a={...s,use_custom_smtp:!0};for(const n of H)String(a[n]??"").trim()===""&&t[n]!==void 0&&(a[n]=t[n]);return a.smtp_port||(a.smtp_port=587),a.smtp_from_address||(a.smtp_from_address=a.smtp_user||""),a.smtp_use_tls=G(a.smtp_use_tls,!0),a.smtp_use_ssl=G(a.smtp_use_ssl,!1),a},de=s=>{const t=ie(s),a={to_email:String(t.to_email??"").trim(),use_custom_smtp:t.use_custom_smtp===!0};if(a.use_custom_smtp)for(const n of H)a[n]=t[n];return a},B={bark:{label:"Bark",icon:W,fields:[{key:"server_url",label:"Bark 服务器",placeholder:"https://api.day.app",required:!0},{key:"device_key",label:"Device Key",placeholder:"你的 Bark 设备 Key",required:!0},{key:"title",label:"标题(可选)",placeholder:"Ydisks闲鱼助手"},{key:"sound",label:"铃声(可选)",placeholder:"default"},{key:"group",label:"分组(可选)",placeholder:"xianyu"}],guide:{steps:["App Store 搜索并安装 Bark(免费)","打开 Bark App,首页会显示一条测试 URL,形如 https://api.day.app//这是测试推送内容","URL 路径里 那一段就是 Device Key,复制填入","服务器地址默认 https://api.day.app,自建服务端则填自建域名"],urlFormat:"https://api.day.app/<你的key>/测试内容",note:"不需要 secret,Device Key 本身就是唯一凭证。"}},dingtalk:{label:"钉钉机器人",icon:K,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://oapi.dingtalk.com/robot/send?access_token=...",required:!0},{key:"secret",label:"加签密钥",placeholder:"SEC...",help:"安全设置勾选「加签」后生成,SEC 开头"}],guide:{steps:["钉钉进入一个群(可建单人群)→ 右上角 群设置","机器人 → 添加机器人 → 选择「自定义机器人」","安全设置勾选「加签」","完成页同时展示 Webhook 地址和 SEC 开头的 Secret,两个都复制","Webhook URL 填上面,Secret 填加签密钥"],urlFormat:"https://oapi.dingtalk.com/robot/send?access_token=XXX",note:"加签密钥可选,但强烈建议启用,否则机器人可能被滥用。"}},feishu:{label:"飞书机器人",icon:K,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://open.feishu.cn/open-apis/bot/v2/hook/...",required:!0},{key:"secret",label:"签名校验密钥",placeholder:"sec-...",help:"安全设置选「签名校验」后生成"}],guide:{steps:["飞书进入目标群 → 右上角 更多 → 设置","群机器人 → 添加机器人 → 自定义机器人","安全设置选择「签名校验」,复制生成的秘钥","完成会给 Webhook 地址,复制","Webhook URL 填上面,秘钥填签名校验密钥"],urlFormat:"https://open.feishu.cn/open-apis/bot/v2/hook/xxx",note:"签名密钥可选,建议启用。频率限制:单机器人 100 次/分钟。"}},wechat:{label:"企业微信机器人",icon:K,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...",required:!0}],guide:{steps:["企业微信进入一个内部群 → 右上角 … → 群设置","找到「群机器人」(新版可能叫「消息推送」)","添加 → 选择自定义机器人","完成给 Webhook 地址(含 ?key=),复制填入"],urlFormat:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=XXX",note:"不需要 secret,URL 里的 key 就是唯一凭证,注意不要泄露。频率限制 20 条/分钟。"}},webhook:{label:"自定义 Webhook",icon:Ne,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://your-server/notify",required:!0}],guide:{steps:["仅适用于自己有服务器的用户:在你自己的机器上起一个 HTTP 接口收 JSON","系统会 POST 这个 URL,Content-Type: application/json","请求体固定为右侧 JSON 格式,按需解析 message 字段"],urlFormat:'{"message":"告警正文","timestamp":"2026-07-05 12:00:00","source":"xianyu-auto-reply"}',note:"若用 Server酱 / PushPlus 等第三方推送服务,格式不兼容,需写中间脚本转发,或改用对应专用渠道。"}},telegram:{label:"Telegram",icon:se,fields:[{key:"bot_token",label:"Bot Token",placeholder:"123456:ABC-DEF...",required:!0},{key:"chat_id",label:"Chat ID",placeholder:"-1001234567890 或你的用户 ID",required:!0}],guide:{steps:["在 Telegram 搜索 @BotFather,发送 /newbot,按提示创建机器人,拿到 Bot Token","把你的 Bot 拉进一个群,或私聊它发一条消息","浏览器访问 https://api.telegram.org/bot<你的Token>/getUpdates",'从返回 JSON 里找 "chat":{"id":xxx},xxx 就是 Chat ID(群是负数,私聊是正数)'],urlFormat:"Bot Token: 123456:ABC-DEF... Chat ID: -1001234567890",note:"群聊需先把 Bot 设为管理员才能发消息。"}},email:{label:"邮件",icon:ee,fields:[{key:"to_email",label:"收件邮箱",placeholder:"receiver@example.com",required:!0}],guide:{steps:["通常先保存页面中的系统 SMTP 配置","邮件渠道只需填写收件邮箱,即可完整继承系统 SMTP","只有确实需要另一套发件服务时,才开启“使用独立 SMTP”并填写整套配置"],note:"继承和独立 SMTP 是互斥模式,不会再混用两套配置中的部分字段。"}}},pe=[{value:"account_offline",label:"掉线通知",description:"账号过期、断线或登录态失效"},{value:"account_recovered",label:"恢复通知",description:"自动恢复成功并重新在线"},{value:"account_disabled",label:"禁用通知",description:"连续失败、账密错误等导致账号停用"},{value:"security_verification",label:"风控验证",description:"滑块、人脸、扫码验证等安全校验"},{value:"delivery_result",label:"交易通知",description:"订单发货、卡密发送等交易结果"},{value:"token_renewal",label:"续期通知",description:"Cookie/token 续期和自动恢复过程"},{value:"system_error",label:"系统错误",description:"后台任务或系统级异常"}],Y=()=>({name:"",type:"bark",enabled:!0,config:{},event_types:[]}),Pe=s=>!s||s.length===0?"全部事件":s.map(t=>{var a;return((a=pe.find(n=>n.value===t))==null?void 0:a.label)||t}).join("、"),Ee=(s,t)=>{const a=s.type==="email"?ie({...s.config||{}}):null,n=a?a.use_custom_smtp===!0?ce(a,t):a:{...s.config||{}};return{name:s.name,type:s.type,enabled:s.enabled,config:n,event_types:s.event_types||[]}},Me=s=>{const a=B[s.type].fields.find(n=>n.required&&!String(s.config[n.key]||"").trim());if(a)return`请填写 ${a.label}`;if(!s.name.trim())return"请填写渠道名称";if(s.type==="email"){const n=de(s.config);if(n.use_custom_smtp){const k=[["smtp_server","独立 SMTP 服务器"],["smtp_port","独立 SMTP 端口"],["smtp_user","独立 SMTP 登录邮箱"],["smtp_password","独立 SMTP 密码 / 授权码"],["smtp_from_address","独立 SMTP 发件地址"]].find(([h])=>!String(n[h]||"").trim());if(k)return`请填写 ${k[1]}`}}return""},qe=s=>({name:s.name.trim(),type:s.type,config:s.type==="email"?de(s.config):s.config,event_types:s.event_types,enabled:s.enabled}),g=(s,t)=>s===t,O=(s,t)=>s instanceof Error&&s.message?s.message:t,Ae=({channels:s,testingId:t,onEdit:a,onDelete:n,onToggleEnabled:b,onTest:k})=>{const h=l=>s.find(o=>o.id===l.currentTarget.dataset.channelId)||null,_=l=>{const o=h(l);o&&b(o)},S=l=>{const o=h(l);o&&k(o)},E=l=>{const o=h(l);o&&a(o)},j=l=>{const o=h(l);o&&n(o)},M=l=>{const o=B[l.type]||B.webhook,P=o.icon;return e.jsxs("div",{className:"ios-card rounded-xl p-5 bg-white flex items-center gap-4",children:[e.jsx("div",{className:"w-11 h-11 rounded-xl bg-gray-100 flex items-center justify-center flex-shrink-0",children:e.jsx(P,{className:"w-5 h-5 text-gray-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-bold text-gray-900 truncate",children:l.name}),e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-600 font-medium",children:o.label}),!l.enabled&&e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-400 font-medium",children:"已停用"})]}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 truncate",children:o.fields.map(x=>{var w;return(w=l.config)==null?void 0:w[x.key]}).filter(Boolean).map((x,w)=>e.jsx("span",{className:"mr-3",children:String(x).length>40?`${String(x).slice(0,40)}…`:String(x)},w))}),e.jsxs("div",{className:"text-xs text-gray-400 mt-1 truncate",children:["订阅:",Pe(l.event_types)]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{"data-channel-id":l.id,onClick:_,className:`px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${l.enabled?"bg-green-50 text-green-700 hover:bg-green-100":"bg-gray-100 text-gray-500 hover:bg-gray-200"}`,children:l.enabled?"启用中":"已停用"}),e.jsxs("button",{"data-channel-id":l.id,onClick:S,disabled:t===l.id,className:"px-3 py-1.5 rounded-lg text-xs font-bold bg-blue-50 text-brand hover:bg-blue-100 transition-colors flex items-center gap-1 disabled:opacity-50",children:[t===l.id?e.jsx(I,{className:"w-3 h-3 animate-spin"}):e.jsx(se,{className:"w-3 h-3"}),"测试"]}),e.jsx("button",{"data-channel-id":l.id,onClick:E,className:"w-8 h-8 rounded-lg bg-gray-100 hover:bg-gray-200 flex items-center justify-center text-gray-600 transition-colors",title:"编辑",children:e.jsx(ve,{className:"w-4 h-4"})}),e.jsx("button",{"data-channel-id":l.id,onClick:j,className:"w-8 h-8 rounded-lg bg-red-50 hover:bg-red-100 flex items-center justify-center text-red-500 transition-colors",title:"删除",children:e.jsx(ke,{className:"w-4 h-4"})})]})]},l.id)};return s.length===0?e.jsxs("div",{className:"ios-card rounded-xl p-12 bg-white text-center",children:[e.jsx(W,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-500 font-medium",children:"还没有配置任何通知渠道"}),e.jsx("p",{className:"text-gray-400 text-sm mt-1",children:"点击右上角「新建渠道」开始配置"})]}):e.jsx("div",{className:"space-y-3",children:s.map(M)})},Le=({selectedEvents:s,onToggleEvent:t})=>{const a=n=>{const b=n.currentTarget.dataset.event;b&&t(b)};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"通知内容"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"不选择表示接收全部通知;选择后仅接收勾选类型。"})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:pe.map(n=>{const b=s.includes(n.value);return e.jsxs("button",{type:"button","data-event":n.value,onClick:a,className:`text-left rounded-xl border px-3 py-2.5 transition-colors ${b?"border-brand bg-blue-50":"border-gray-100 hover:border-gray-300"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`w-4 h-4 rounded border flex items-center justify-center ${b?"bg-brand border-brand":"border-gray-300"}`,children:b&&e.jsx(Q,{className:"w-3 h-3 text-white"})}),e.jsx("span",{className:`text-sm font-bold ${b?"text-brand":"text-gray-800"}`,children:n.label})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1 pl-6 leading-5",children:n.description})]},n.value)})})]})},Re=({showModal:s,editing:t,form:a,setForm:n,smtp:b,showChannelSmtpPassword:k,setShowChannelSmtpPassword:h,saving:_,onClose:S,onSave:E})=>{const j=B[a.type],M=r=>n(p=>({...p,name:r.target.value})),l=r=>{const p=r.currentTarget.dataset.type;p&&n(N=>({...N,type:p,config:{}}))},o=r=>{const p=r.currentTarget.dataset.field;p&&n(N=>({...N,config:{...N.config,[p]:r.target.value}}))},P=()=>n(r=>({...r,config:r.config.use_custom_smtp===!0?{...r.config,use_custom_smtp:!1}:ce(r.config,b)})),x=r=>n(p=>({...p,config:{...p.config,smtp_use_tls:r.target.checked,smtp_use_ssl:r.target.checked?!1:p.config.smtp_use_ssl}})),w=r=>n(p=>({...p,config:{...p.config,smtp_use_ssl:r.target.checked,smtp_use_tls:r.target.checked?!1:p.config.smtp_use_tls}})),U=r=>n(p=>({...p,event_types:p.event_types.includes(r)?p.event_types.filter(N=>N!==r):[...p.event_types,r]})),F=()=>n(r=>({...r,enabled:!r.enabled})),J=()=>h(r=>!r),X=(r,p)=>e.jsx("li",{children:r},p);return s?_e.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"36rem"},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:t?"编辑通知渠道":"新建通知渠道"}),e.jsx("button",{onClick:S,className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(te,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5 overflow-y-auto flex-1 min-h-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"渠道名称"}),e.jsx("input",{type:"text",value:a.name,onChange:M,placeholder:"例如:我的 Bark",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"渠道类型"}),e.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-2",children:Object.keys(B).map(r=>{const p=B[r],N=p.icon,q=a.type===r;return e.jsxs("button",{"data-type":r,type:"button",onClick:l,className:`p-3 rounded-xl border-2 flex flex-col items-center gap-1.5 transition-all ${q?"border-brand bg-blue-50":"border-gray-100 hover:border-gray-300"}`,children:[e.jsx(N,{className:`w-5 h-5 ${q?"text-brand":"text-gray-500"}`}),e.jsx("span",{className:`text-xs font-bold ${q?"text-brand":"text-gray-600"}`,children:p.label})]},r)})})]}),e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-200 p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(W,{className:"w-4 h-4 text-amber-600"}),e.jsxs("span",{className:"text-sm font-bold text-amber-800",children:["如何获取 ",j.label," 配置?"]})]}),e.jsx("ol",{className:"space-y-1.5 text-xs text-amber-900/90 leading-5 list-decimal pl-5",children:j.guide.steps.map(X)}),j.guide.urlFormat&&e.jsxs("div",{className:"text-xs text-amber-900/90",children:[e.jsx("span",{className:"font-bold",children:"格式示例:"}),e.jsx("code",{className:"mt-1 block bg-amber-100/70 px-2.5 py-1.5 rounded-lg break-all font-mono text-[11px]",children:j.guide.urlFormat})]}),j.guide.note&&e.jsxs("p",{className:"text-xs text-amber-800/80 leading-5 pt-1",children:["💡 ",j.guide.note]})]}),e.jsx("div",{className:"space-y-3",children:j.fields.map(r=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:[r.label,r.required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),e.jsx("input",{"data-field":r.key,type:r.type==="password"?"password":r.type==="number"?"number":"text",value:String(a.config[r.key]||""),onChange:o,placeholder:r.placeholder,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),r.help&&e.jsx("p",{className:"text-xs text-gray-500",children:r.help})]},r.key))}),a.type==="email"&&e.jsxs("div",{className:"overflow-hidden rounded-2xl border border-blue-100 bg-blue-50/40",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"SMTP 来源"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-gray-500",children:a.config.use_custom_smtp===!0?"当前渠道使用一套完整、独立的发件配置。":"当前渠道完整继承系统 SMTP,只单独设置收件邮箱。"})]}),e.jsx("button",{type:"button",onClick:P,className:`relative h-7 w-12 shrink-0 rounded-full transition-colors ${a.config.use_custom_smtp===!0?"bg-brand":"bg-gray-300"}`,"aria-label":"使用独立 SMTP",children:e.jsx("span",{className:`absolute left-1 top-1 h-5 w-5 rounded-full bg-white shadow-sm transition-transform ${a.config.use_custom_smtp===!0?"translate-x-5":""}`})})]}),a.config.use_custom_smtp===!0&&e.jsxs("div",{className:"space-y-4 border-t border-blue-100 bg-white/80 p-4",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["SMTP 服务器 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{"data-field":"smtp_server",type:"text",value:String(a.config.smtp_server||""),onChange:o,placeholder:"smtp.qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["SMTP 端口 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{"data-field":"smtp_port",type:"number",value:String(a.config.smtp_port||587),onChange:o,placeholder:"587",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["登录邮箱 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{"data-field":"smtp_user",type:"email",value:String(a.config.smtp_user||""),onChange:o,placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["密码 / 授权码 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{"data-field":"smtp_password",type:k?"text":"password",value:String(a.config.smtp_password||""),onChange:o,placeholder:"输入密码或授权码",className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"}),e.jsx("button",{type:"button",onClick:J,className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",children:k?e.jsx(ae,{className:"w-4 h-4"}):e.jsx(ne,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件人显示名(可选)"}),e.jsx("input",{"data-field":"smtp_from_name",type:"text",value:String(a.config.smtp_from_name||""),onChange:o,placeholder:"闲鱼自动回复系统",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["发件邮箱地址 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{"data-field":"smtp_from_address",type:"email",value:String(a.config.smtp_from_address||""),onChange:o,placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-3 text-xs font-bold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:a.config.smtp_use_tls!==!1,onChange:x}),"STARTTLS(常用于 587)"]}),e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-3 text-xs font-bold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:a.config.smtp_use_ssl===!0,onChange:w}),"SSL/TLS 直连(常用于 465)"]})]})]})]}),e.jsx(Le,{selectedEvents:a.event_types,onToggleEvent:U}),e.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[e.jsx("button",{type:"button",onClick:F,className:`relative w-11 h-6 rounded-full transition-colors ${a.enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full transition-transform ${a.enabled?"translate-x-5":""}`})}),e.jsx("span",{className:"text-sm font-bold text-gray-800",children:"启用此渠道"})]})]}),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:S,className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"取消"}),e.jsxs("button",{onClick:E,disabled:_,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[_?e.jsx(I,{className:"w-4 h-4 animate-spin"}):e.jsx(Q,{className:"w-4 h-4"}),_?"保存中...":"保存"]})]})]})}),document.body):null},Be=({smtp:s,setSmtp:t,smtpSaving:a,showPassword:n,setShowPassword:b,onSave:k})=>{const h=l=>{const o=l.currentTarget.dataset.field;o&&t(P=>({...P,[o]:l.target.value}))},_=l=>{t(o=>({...o,smtp_port:parseInt(l.target.value,10)||587}))},S=l=>{t(o=>({...o,smtp_use_tls:l.target.checked,smtp_use_ssl:l.target.checked?!1:o.smtp_use_ssl}))},E=l=>{t(o=>({...o,smtp_use_ssl:l.target.checked,smtp_use_tls:l.target.checked?!1:o.smtp_use_tls}))},j=l=>{t(o=>({...o,smtp_password:l.target.value}))},M=()=>b(l=>!l);return e.jsxs("section",{className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-extrabold text-gray-800",children:"SMTP 邮件配置"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"系统级邮件发送服务,供邮件通知渠道复用"})]}),e.jsx("div",{className:"p-2 rounded-xl bg-blue-50 text-blue-600",children:e.jsx(ee,{className:"w-5 h-5"})})]}),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-800",children:"SMTP 服务器"}),e.jsx("input",{"data-field":"smtp_server",type:"text",value:s.smtp_server||"",onChange:h,placeholder:"smtp.qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"SMTP 端口"}),e.jsx("input",{type:"number",value:s.smtp_port||587,onChange:_,placeholder:"587",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件邮箱"}),e.jsx("input",{"data-field":"smtp_user",type:"email",value:s.smtp_user||"",onChange:h,placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"邮箱密码 / 授权码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:n?"text":"password",value:s.smtp_password||"",onChange:j,placeholder:s.smtp_password_configured?"已配置,如需替换请输入新密码":"输入密码或授权码",className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"}),e.jsx("button",{type:"button",onClick:M,className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:n?e.jsx(ae,{className:"w-4 h-4"}):e.jsx(ne,{className:"w-4 h-4"})})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"QQ 邮箱需使用授权码(QQ 邮箱设置 → 账号 → 开启 SMTP → 生成授权码)"})]}),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-800",children:"发件人显示名(可选)"}),e.jsx("input",{"data-field":"smtp_from_name",type:"text",value:s.smtp_from_name||"",onChange:h,placeholder:"闲鱼自动回复系统",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件邮箱地址"}),e.jsx("input",{"data-field":"smtp_from_address",type:"email",value:s.smtp_from_address||s.smtp_user||"",onChange:h,placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-4 text-sm font-semibold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:s.smtp_use_tls!==!1,onChange:S}),"STARTTLS(常用于 587 端口)"]}),e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-4 text-sm font-semibold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:s.smtp_use_ssl===!0,onChange:E}),"SSL/TLS 直连(常用于 465 端口)"]})]}),e.jsxs("button",{onClick:k,disabled:a,className:"ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a?e.jsx(I,{className:"w-4 h-4 animate-spin"}):e.jsx(we,{className:"w-4 h-4"}),a?"保存中...":"保存 SMTP 配置"]})]})},$e=s=>{if(Array.isArray(s))return s.filter(Boolean);if(typeof s!="string"||!s.trim())return[];try{const t=JSON.parse(s);if(Array.isArray(t))return t.filter(Boolean)}catch{}return s.split(/[,\s;]+/).map(t=>t.trim()).filter(Boolean)},me=s=>{const t=Array.from(new Set((s||[]).filter(Boolean)));return t.length>0?JSON.stringify(t):""},Oe=s=>{let t={};try{const n=typeof s.config=="string"?JSON.parse(s.config):s.config;n&&typeof n=="object"&&!Array.isArray(n)&&(t=n)}catch{}const a=s.type==="ding_talk"?"dingtalk":s.type==="lark"?"feishu":s.type;return{id:String(s.id),name:s.name,type:a,config:t,event_types:$e(s.event_types),enabled:s.enabled,created_at:s.created_at,updated_at:s.updated_at}},Fe=async s=>{const t=await re("/api/v1/notifications/channels",void 0,s);return{success:!0,data:(Array.isArray(t)?t:t.data||t.channels||[]).map(Oe)}},De=async(s,t)=>oe("/api/v1/notifications/channels",{...s,config:JSON.stringify(s.config),event_types:me(s.event_types)},t),Z=async(s,t,a)=>{const n={...t};return"config"in t&&(n.config=JSON.stringify(t.config)),"event_types"in t&&(n.event_types=me(t.event_types)),le(`/api/v1/notifications/channels/${s}`,n,a)},We=async(s,t)=>Te(`/api/v1/notifications/channels/${s}`,void 0,t),Ie=async(s,t)=>oe(`/api/v1/notifications/channels/${s}/test`,{},t),Ue=s=>{const t={...s};if("renewal_log_retention_days"in t){const a=Number(t.renewal_log_retention_days);t.renewal_log_retention_days=Number.isFinite(a)?a:10}return t},Je=async s=>{const t=await re("/api/v1/settings/system",void 0,s);return Ue(t.data||t.settings||t)},Xe=async(s,t)=>le("/api/v1/settings/system",s,t),ze=s=>{const[t,a]=d.useState([]),[n,b]=d.useState(!0),[k,h]=d.useState(!1),[_,S]=d.useState(null),[E,j]=d.useState(!1),[M,l]=d.useState(""),[o,P]=d.useState(null),[x,w]=d.useState({}),[U,F]=d.useState(!1),[J,X]=d.useState(!1),[r,p]=d.useState(!1),[N,q]=d.useState(Y),$=d.useRef(0),z=d.useRef(null),C=d.useRef(0),L=d.useRef(null),y=d.useRef(0),T=d.useRef(null),R=d.useRef(null),f=d.useCallback((i,c)=>{P({type:i,text:c}),R.current!==null&&window.clearTimeout(R.current),R.current=window.setTimeout(()=>{R.current=null,P(null)},3e3)},[]),A=d.useCallback(async()=>{var m;const i=++$.current;(m=z.current)==null||m.abort();const c=new AbortController;z.current=c,b(!0);try{const u=await Fe({signal:c.signal});if(!g(i,$.current))return;a(u.data||[])}catch(u){g(i,$.current)&&!c.signal.aborted&&console.error("加载通知渠道失败",u)}finally{g(i,$.current)&&b(!1)}},[]),V=d.useCallback(async()=>{var m;const i=++C.current;(m=L.current)==null||m.abort();const c=new AbortController;L.current=c;try{const u=await Je({signal:c.signal});g(i,C.current)&&w(u||{})}catch(u){g(i,C.current)&&!c.signal.aborted&&console.error("加载 SMTP 配置失败",u)}},[]);d.useEffect(()=>{var i;return A(),s?V():(C.current+=1,(i=L.current)==null||i.abort(),w({})),(()=>{var c,m;$.current+=1,(c=z.current)==null||c.abort(),C.current+=1,(m=L.current)==null||m.abort()})},[s,A,V]),d.useEffect(()=>(()=>{R.current!==null&&window.clearTimeout(R.current)}),[]);const ue=d.useCallback(()=>{S(null),q(Y()),p(!1),h(!0)},[]),xe=d.useCallback(i=>{S(i),q(Ee(i,x)),p(!1),h(!0)},[x]),ge=d.useCallback(()=>{var i;y.current+=1,(i=T.current)==null||i.abort(),j(!1),h(!1)},[]),he=d.useCallback(async()=>{var u;const i=Me(N);if(i){f("error",i);return}const c=++y.current;(u=T.current)==null||u.abort();const m=new AbortController;T.current=m,j(!0);try{const v=qe(N);if(_?await Z(_.id,v,{signal:m.signal}):await De(v,{signal:m.signal}),!g(c,y.current)||(h(!1),await A(),!g(c,y.current)))return;f("success",_?"已更新":"已创建")}catch(v){g(c,y.current)&&!m.signal.aborted&&f("error",O(v,"保存失败"))}finally{g(c,y.current)&&j(!1)}},[_,N,A,f]),be=d.useCallback(async i=>{var u;if(!confirm(`确认删除渠道「${i.name}」吗?已绑定该渠道的账号会自动解绑。`))return;const c=++y.current;(u=T.current)==null||u.abort();const m=new AbortController;T.current=m;try{if(await We(i.id,{signal:m.signal}),!g(c,y.current)||(await A(),!g(c,y.current)))return;f("success","已删除")}catch(v){g(c,y.current)&&!m.signal.aborted&&f("error",O(v,"删除失败"))}},[A,f]),ye=d.useCallback(async i=>{var u;const c=++y.current;(u=T.current)==null||u.abort();const m=new AbortController;T.current=m;try{if(await Z(i.id,{enabled:!i.enabled},{signal:m.signal}),!g(c,y.current))return;a(v=>v.map(D=>D.id===i.id?{...D,enabled:!D.enabled}:D))}catch(v){g(c,y.current)&&!m.signal.aborted&&f("error",O(v,"切换失败"))}},[f]),fe=d.useCallback(async i=>{var u;l(i.id);const c=++y.current;(u=T.current)==null||u.abort();const m=new AbortController;T.current=m;try{await Ie(i.id,{signal:m.signal}),g(c,y.current)&&f("success","测试通知已发送,请检查对应渠道")}catch(v){g(c,y.current)&&!m.signal.aborted&&f("error",O(v,"发送失败"))}finally{g(c,y.current)&&l("")}},[f]),je=d.useCallback(async()=>{var m;const i=++C.current;(m=L.current)==null||m.abort();const c=new AbortController;L.current=c,F(!0);try{const u={smtp_server:x.smtp_server||"",smtp_port:x.smtp_port||587,smtp_user:x.smtp_user||"",smtp_from_name:x.smtp_from_name||"",smtp_from_address:x.smtp_from_address||x.smtp_user||"",smtp_use_tls:x.smtp_use_tls!==!1,smtp_use_ssl:x.smtp_use_ssl===!0};Object.prototype.hasOwnProperty.call(x,"smtp_password")&&(u.smtp_password=x.smtp_password),await Xe(u,{signal:c.signal}),g(i,C.current)&&f("success","SMTP 配置已保存")}catch(u){g(i,C.current)&&!c.signal.aborted&&f("error",O(u,"保存失败"))}finally{g(i,C.current)&&F(!1)}},[f,x]);return{channels:t,loading:n,showModal:k,editing:_,saving:E,testingId:M,toast:o,smtp:x,smtpSaving:U,showSmtpPassword:J,showChannelSmtpPassword:r,form:N,setForm:q,setSmtp:w,setShowSmtpPassword:X,setShowChannelSmtpPassword:p,loadChannels:A,openCreate:ue,openEdit:xe,closeModal:ge,showToast:f,handleSave:he,handleDelete:be,handleToggleEnabled:ye,handleTest:fe,handleSaveSmtp:je}},He=({isAdmin:s=!1})=>{const t=ze(s);return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"通知设置"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"配置通知渠道,账号异常时主动推送告警"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:t.loadChannels,className:"px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(Se,{className:"w-4 h-4"}),"刷新"]}),e.jsxs("button",{onClick:t.openCreate,className:"ios-btn-primary px-5 py-2.5 rounded-xl font-bold flex items-center gap-2",children:[e.jsx(Ce,{className:"w-4 h-4"}),"新建渠道"]})]})]}),e.jsx("div",{className:"ios-card rounded-xl p-5 bg-blue-50/50 border border-blue-100",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(W,{className:"w-5 h-5 text-brand mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"text-sm text-gray-700 leading-6",children:["配置通知渠道并在「账号管理 → 编辑」里绑定后,以下事件会主动推送到该账号绑定的渠道:",e.jsxs("ul",{className:"mt-2 space-y-1 text-gray-600",children:[e.jsxs("li",{children:["• ",e.jsx("strong",{children:"账号 session 失效"}),":系统正在尝试自动恢复(警告)"]}),e.jsxs("li",{children:["• ",e.jsx("strong",{children:"自动恢复失败"}),":账号已停止,需人工处理(严重)"]}),e.jsxs("li",{children:["• ",e.jsx("strong",{children:"触发风控验证"}),":可能需要扫码完成验证(警告)"]})]})]})]})}),t.loading?e.jsx("div",{className:"flex justify-center py-20",children:e.jsx(I,{className:"w-8 h-8 text-brand animate-spin"})}):e.jsx(Ae,{channels:t.channels,testingId:t.testingId,onEdit:t.openEdit,onDelete:t.handleDelete,onToggleEnabled:t.handleToggleEnabled,onTest:t.handleTest}),s&&e.jsx(Be,{smtp:t.smtp,setSmtp:t.setSmtp,smtpSaving:t.smtpSaving,showPassword:t.showSmtpPassword,setShowPassword:t.setShowSmtpPassword,onSave:t.handleSaveSmtp}),e.jsx(Re,{showModal:t.showModal,editing:t.editing,form:t.form,setForm:t.setForm,smtp:t.smtp,showChannelSmtpPassword:t.showChannelSmtpPassword,setShowChannelSmtpPassword:t.setShowChannelSmtpPassword,saving:t.saving,onClose:t.closeModal,onSave:t.handleSave}),t.toast&&e.jsxs("div",{className:`fixed bottom-8 left-1/2 -translate-x-1/2 z-[10000] px-5 py-3 rounded-xl shadow-lg font-bold text-sm flex items-center gap-2 animate-fade-in text-white ${t.toast.type==="success"?"bg-success-500":"bg-danger-500"}`,children:[t.toast.type==="success"?e.jsx(Q,{className:"w-4 h-4"}):e.jsx(te,{className:"w-4 h-4"}),t.toast.text]})]})};export{He as default}; +import{j as e,b as _e,r as d}from"./react-vendor-C_od1ZSF.js";import{ai as ee,ah as se,aj as Ne,x as K,e as W,L as I,y as ve,F as ke,s as Q,X as te,u as ae,v as ne,r as we,R as Se,N as Ce}from"./icons-vendor-CvzvbbIV.js";import{g as re,p as le,a as oe,d as Te}from"./index-hByDAHGj.js";const H=["smtp_server","smtp_port","smtp_user","smtp_password","smtp_from_name","smtp_from_address","smtp_use_tls","smtp_use_ssl"],G=(s,t)=>{if(typeof s=="boolean")return s;if(typeof s=="string"){if(["true","1","yes","on"].includes(s.toLowerCase()))return!0;if(["false","0","no","off"].includes(s.toLowerCase()))return!1}return t},ie=s=>{const t=Object.prototype.hasOwnProperty.call(s,"use_custom_smtp"),a=H.some(n=>String(s[n]??"").trim()!=="");return{...s,use_custom_smtp:t?G(s.use_custom_smtp,!1):a}},ce=(s,t)=>{const a={...s,use_custom_smtp:!0};for(const n of H)String(a[n]??"").trim()===""&&t[n]!==void 0&&(a[n]=t[n]);return a.smtp_port||(a.smtp_port=587),a.smtp_from_address||(a.smtp_from_address=a.smtp_user||""),a.smtp_use_tls=G(a.smtp_use_tls,!0),a.smtp_use_ssl=G(a.smtp_use_ssl,!1),a},de=s=>{const t=ie(s),a={to_email:String(t.to_email??"").trim(),use_custom_smtp:t.use_custom_smtp===!0};if(a.use_custom_smtp)for(const n of H)a[n]=t[n];return a},B={bark:{label:"Bark",icon:W,fields:[{key:"server_url",label:"Bark 服务器",placeholder:"https://api.day.app",required:!0},{key:"device_key",label:"Device Key",placeholder:"你的 Bark 设备 Key",required:!0},{key:"title",label:"标题(可选)",placeholder:"Ydisks闲鱼助手"},{key:"sound",label:"铃声(可选)",placeholder:"default"},{key:"group",label:"分组(可选)",placeholder:"xianyu"}],guide:{steps:["App Store 搜索并安装 Bark(免费)","打开 Bark App,首页会显示一条测试 URL,形如 https://api.day.app//这是测试推送内容","URL 路径里 那一段就是 Device Key,复制填入","服务器地址默认 https://api.day.app,自建服务端则填自建域名"],urlFormat:"https://api.day.app/<你的key>/测试内容",note:"不需要 secret,Device Key 本身就是唯一凭证。"}},dingtalk:{label:"钉钉机器人",icon:K,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://oapi.dingtalk.com/robot/send?access_token=...",required:!0},{key:"secret",label:"加签密钥",placeholder:"SEC...",help:"安全设置勾选「加签」后生成,SEC 开头"}],guide:{steps:["钉钉进入一个群(可建单人群)→ 右上角 群设置","机器人 → 添加机器人 → 选择「自定义机器人」","安全设置勾选「加签」","完成页同时展示 Webhook 地址和 SEC 开头的 Secret,两个都复制","Webhook URL 填上面,Secret 填加签密钥"],urlFormat:"https://oapi.dingtalk.com/robot/send?access_token=XXX",note:"加签密钥可选,但强烈建议启用,否则机器人可能被滥用。"}},feishu:{label:"飞书机器人",icon:K,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://open.feishu.cn/open-apis/bot/v2/hook/...",required:!0},{key:"secret",label:"签名校验密钥",placeholder:"sec-...",help:"安全设置选「签名校验」后生成"}],guide:{steps:["飞书进入目标群 → 右上角 更多 → 设置","群机器人 → 添加机器人 → 自定义机器人","安全设置选择「签名校验」,复制生成的秘钥","完成会给 Webhook 地址,复制","Webhook URL 填上面,秘钥填签名校验密钥"],urlFormat:"https://open.feishu.cn/open-apis/bot/v2/hook/xxx",note:"签名密钥可选,建议启用。频率限制:单机器人 100 次/分钟。"}},wechat:{label:"企业微信机器人",icon:K,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...",required:!0}],guide:{steps:["企业微信进入一个内部群 → 右上角 … → 群设置","找到「群机器人」(新版可能叫「消息推送」)","添加 → 选择自定义机器人","完成给 Webhook 地址(含 ?key=),复制填入"],urlFormat:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=XXX",note:"不需要 secret,URL 里的 key 就是唯一凭证,注意不要泄露。频率限制 20 条/分钟。"}},webhook:{label:"自定义 Webhook",icon:Ne,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://your-server/notify",required:!0}],guide:{steps:["仅适用于自己有服务器的用户:在你自己的机器上起一个 HTTP 接口收 JSON","系统会 POST 这个 URL,Content-Type: application/json","请求体固定为右侧 JSON 格式,按需解析 message 字段"],urlFormat:'{"message":"告警正文","timestamp":"2026-07-05 12:00:00","source":"xianyu-auto-reply"}',note:"若用 Server酱 / PushPlus 等第三方推送服务,格式不兼容,需写中间脚本转发,或改用对应专用渠道。"}},telegram:{label:"Telegram",icon:se,fields:[{key:"bot_token",label:"Bot Token",placeholder:"123456:ABC-DEF...",required:!0},{key:"chat_id",label:"Chat ID",placeholder:"-1001234567890 或你的用户 ID",required:!0}],guide:{steps:["在 Telegram 搜索 @BotFather,发送 /newbot,按提示创建机器人,拿到 Bot Token","把你的 Bot 拉进一个群,或私聊它发一条消息","浏览器访问 https://api.telegram.org/bot<你的Token>/getUpdates",'从返回 JSON 里找 "chat":{"id":xxx},xxx 就是 Chat ID(群是负数,私聊是正数)'],urlFormat:"Bot Token: 123456:ABC-DEF... Chat ID: -1001234567890",note:"群聊需先把 Bot 设为管理员才能发消息。"}},email:{label:"邮件",icon:ee,fields:[{key:"to_email",label:"收件邮箱",placeholder:"receiver@example.com",required:!0}],guide:{steps:["通常先保存页面中的系统 SMTP 配置","邮件渠道只需填写收件邮箱,即可完整继承系统 SMTP","只有确实需要另一套发件服务时,才开启“使用独立 SMTP”并填写整套配置"],note:"继承和独立 SMTP 是互斥模式,不会再混用两套配置中的部分字段。"}}},pe=[{value:"account_offline",label:"掉线通知",description:"账号过期、断线或登录态失效"},{value:"account_recovered",label:"恢复通知",description:"自动恢复成功并重新在线"},{value:"account_disabled",label:"禁用通知",description:"连续失败、账密错误等导致账号停用"},{value:"security_verification",label:"风控验证",description:"滑块、人脸、扫码验证等安全校验"},{value:"delivery_result",label:"交易通知",description:"订单发货、卡密发送等交易结果"},{value:"token_renewal",label:"续期通知",description:"Cookie/token 续期和自动恢复过程"},{value:"system_error",label:"系统错误",description:"后台任务或系统级异常"}],Y=()=>({name:"",type:"bark",enabled:!0,config:{},event_types:[]}),Pe=s=>!s||s.length===0?"全部事件":s.map(t=>{var a;return((a=pe.find(n=>n.value===t))==null?void 0:a.label)||t}).join("、"),Ee=(s,t)=>{const a=s.type==="email"?ie({...s.config||{}}):null,n=a?a.use_custom_smtp===!0?ce(a,t):a:{...s.config||{}};return{name:s.name,type:s.type,enabled:s.enabled,config:n,event_types:s.event_types||[]}},Me=s=>{const a=B[s.type].fields.find(n=>n.required&&!String(s.config[n.key]||"").trim());if(a)return`请填写 ${a.label}`;if(!s.name.trim())return"请填写渠道名称";if(s.type==="email"){const n=de(s.config);if(n.use_custom_smtp){const k=[["smtp_server","独立 SMTP 服务器"],["smtp_port","独立 SMTP 端口"],["smtp_user","独立 SMTP 登录邮箱"],["smtp_password","独立 SMTP 密码 / 授权码"],["smtp_from_address","独立 SMTP 发件地址"]].find(([h])=>!String(n[h]||"").trim());if(k)return`请填写 ${k[1]}`}}return""},qe=s=>({name:s.name.trim(),type:s.type,config:s.type==="email"?de(s.config):s.config,event_types:s.event_types,enabled:s.enabled}),g=(s,t)=>s===t,O=(s,t)=>s instanceof Error&&s.message?s.message:t,Ae=({channels:s,testingId:t,onEdit:a,onDelete:n,onToggleEnabled:b,onTest:k})=>{const h=l=>s.find(o=>o.id===l.currentTarget.dataset.channelId)||null,_=l=>{const o=h(l);o&&b(o)},S=l=>{const o=h(l);o&&k(o)},E=l=>{const o=h(l);o&&a(o)},j=l=>{const o=h(l);o&&n(o)},M=l=>{const o=B[l.type]||B.webhook,P=o.icon;return e.jsxs("div",{className:"ios-card rounded-xl p-5 bg-white flex items-center gap-4",children:[e.jsx("div",{className:"w-11 h-11 rounded-xl bg-gray-100 flex items-center justify-center flex-shrink-0",children:e.jsx(P,{className:"w-5 h-5 text-gray-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-bold text-gray-900 truncate",children:l.name}),e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-600 font-medium",children:o.label}),!l.enabled&&e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-400 font-medium",children:"已停用"})]}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 truncate",children:o.fields.map(x=>{var w;return(w=l.config)==null?void 0:w[x.key]}).filter(Boolean).map((x,w)=>e.jsx("span",{className:"mr-3",children:String(x).length>40?`${String(x).slice(0,40)}…`:String(x)},w))}),e.jsxs("div",{className:"text-xs text-gray-400 mt-1 truncate",children:["订阅:",Pe(l.event_types)]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{"data-channel-id":l.id,onClick:_,className:`px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${l.enabled?"bg-green-50 text-green-700 hover:bg-green-100":"bg-gray-100 text-gray-500 hover:bg-gray-200"}`,children:l.enabled?"启用中":"已停用"}),e.jsxs("button",{"data-channel-id":l.id,onClick:S,disabled:t===l.id,className:"px-3 py-1.5 rounded-lg text-xs font-bold bg-blue-50 text-brand hover:bg-blue-100 transition-colors flex items-center gap-1 disabled:opacity-50",children:[t===l.id?e.jsx(I,{className:"w-3 h-3 animate-spin"}):e.jsx(se,{className:"w-3 h-3"}),"测试"]}),e.jsx("button",{"data-channel-id":l.id,onClick:E,className:"w-8 h-8 rounded-lg bg-gray-100 hover:bg-gray-200 flex items-center justify-center text-gray-600 transition-colors",title:"编辑",children:e.jsx(ve,{className:"w-4 h-4"})}),e.jsx("button",{"data-channel-id":l.id,onClick:j,className:"w-8 h-8 rounded-lg bg-red-50 hover:bg-red-100 flex items-center justify-center text-red-500 transition-colors",title:"删除",children:e.jsx(ke,{className:"w-4 h-4"})})]})]},l.id)};return s.length===0?e.jsxs("div",{className:"ios-card rounded-xl p-12 bg-white text-center",children:[e.jsx(W,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-500 font-medium",children:"还没有配置任何通知渠道"}),e.jsx("p",{className:"text-gray-400 text-sm mt-1",children:"点击右上角「新建渠道」开始配置"})]}):e.jsx("div",{className:"space-y-3",children:s.map(M)})},Le=({selectedEvents:s,onToggleEvent:t})=>{const a=n=>{const b=n.currentTarget.dataset.event;b&&t(b)};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"通知内容"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"不选择表示接收全部通知;选择后仅接收勾选类型。"})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:pe.map(n=>{const b=s.includes(n.value);return e.jsxs("button",{type:"button","data-event":n.value,onClick:a,className:`text-left rounded-xl border px-3 py-2.5 transition-colors ${b?"border-brand bg-blue-50":"border-gray-100 hover:border-gray-300"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`w-4 h-4 rounded border flex items-center justify-center ${b?"bg-brand border-brand":"border-gray-300"}`,children:b&&e.jsx(Q,{className:"w-3 h-3 text-white"})}),e.jsx("span",{className:`text-sm font-bold ${b?"text-brand":"text-gray-800"}`,children:n.label})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1 pl-6 leading-5",children:n.description})]},n.value)})})]})},Re=({showModal:s,editing:t,form:a,setForm:n,smtp:b,showChannelSmtpPassword:k,setShowChannelSmtpPassword:h,saving:_,onClose:S,onSave:E})=>{const j=B[a.type],M=r=>n(p=>({...p,name:r.target.value})),l=r=>{const p=r.currentTarget.dataset.type;p&&n(N=>({...N,type:p,config:{}}))},o=r=>{const p=r.currentTarget.dataset.field;p&&n(N=>({...N,config:{...N.config,[p]:r.target.value}}))},P=()=>n(r=>({...r,config:r.config.use_custom_smtp===!0?{...r.config,use_custom_smtp:!1}:ce(r.config,b)})),x=r=>n(p=>({...p,config:{...p.config,smtp_use_tls:r.target.checked,smtp_use_ssl:r.target.checked?!1:p.config.smtp_use_ssl}})),w=r=>n(p=>({...p,config:{...p.config,smtp_use_ssl:r.target.checked,smtp_use_tls:r.target.checked?!1:p.config.smtp_use_tls}})),U=r=>n(p=>({...p,event_types:p.event_types.includes(r)?p.event_types.filter(N=>N!==r):[...p.event_types,r]})),F=()=>n(r=>({...r,enabled:!r.enabled})),J=()=>h(r=>!r),X=(r,p)=>e.jsx("li",{children:r},p);return s?_e.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"36rem"},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:t?"编辑通知渠道":"新建通知渠道"}),e.jsx("button",{onClick:S,className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(te,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5 overflow-y-auto flex-1 min-h-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"渠道名称"}),e.jsx("input",{type:"text",value:a.name,onChange:M,placeholder:"例如:我的 Bark",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"渠道类型"}),e.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-2",children:Object.keys(B).map(r=>{const p=B[r],N=p.icon,q=a.type===r;return e.jsxs("button",{"data-type":r,type:"button",onClick:l,className:`p-3 rounded-xl border-2 flex flex-col items-center gap-1.5 transition-all ${q?"border-brand bg-blue-50":"border-gray-100 hover:border-gray-300"}`,children:[e.jsx(N,{className:`w-5 h-5 ${q?"text-brand":"text-gray-500"}`}),e.jsx("span",{className:`text-xs font-bold ${q?"text-brand":"text-gray-600"}`,children:p.label})]},r)})})]}),e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-200 p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(W,{className:"w-4 h-4 text-amber-600"}),e.jsxs("span",{className:"text-sm font-bold text-amber-800",children:["如何获取 ",j.label," 配置?"]})]}),e.jsx("ol",{className:"space-y-1.5 text-xs text-amber-900/90 leading-5 list-decimal pl-5",children:j.guide.steps.map(X)}),j.guide.urlFormat&&e.jsxs("div",{className:"text-xs text-amber-900/90",children:[e.jsx("span",{className:"font-bold",children:"格式示例:"}),e.jsx("code",{className:"mt-1 block bg-amber-100/70 px-2.5 py-1.5 rounded-lg break-all font-mono text-[11px]",children:j.guide.urlFormat})]}),j.guide.note&&e.jsxs("p",{className:"text-xs text-amber-800/80 leading-5 pt-1",children:["💡 ",j.guide.note]})]}),e.jsx("div",{className:"space-y-3",children:j.fields.map(r=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:[r.label,r.required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),e.jsx("input",{"data-field":r.key,type:r.type==="password"?"password":r.type==="number"?"number":"text",value:String(a.config[r.key]||""),onChange:o,placeholder:r.placeholder,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),r.help&&e.jsx("p",{className:"text-xs text-gray-500",children:r.help})]},r.key))}),a.type==="email"&&e.jsxs("div",{className:"overflow-hidden rounded-2xl border border-blue-100 bg-blue-50/40",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"SMTP 来源"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-gray-500",children:a.config.use_custom_smtp===!0?"当前渠道使用一套完整、独立的发件配置。":"当前渠道完整继承系统 SMTP,只单独设置收件邮箱。"})]}),e.jsx("button",{type:"button",onClick:P,className:`relative h-7 w-12 shrink-0 rounded-full transition-colors ${a.config.use_custom_smtp===!0?"bg-brand":"bg-gray-300"}`,"aria-label":"使用独立 SMTP",children:e.jsx("span",{className:`absolute left-1 top-1 h-5 w-5 rounded-full bg-white shadow-sm transition-transform ${a.config.use_custom_smtp===!0?"translate-x-5":""}`})})]}),a.config.use_custom_smtp===!0&&e.jsxs("div",{className:"space-y-4 border-t border-blue-100 bg-white/80 p-4",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["SMTP 服务器 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{"data-field":"smtp_server",type:"text",value:String(a.config.smtp_server||""),onChange:o,placeholder:"smtp.qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["SMTP 端口 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{"data-field":"smtp_port",type:"number",value:String(a.config.smtp_port||587),onChange:o,placeholder:"587",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["登录邮箱 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{"data-field":"smtp_user",type:"email",value:String(a.config.smtp_user||""),onChange:o,placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["密码 / 授权码 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{"data-field":"smtp_password",type:k?"text":"password",value:String(a.config.smtp_password||""),onChange:o,placeholder:"输入密码或授权码",className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"}),e.jsx("button",{type:"button",onClick:J,className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",children:k?e.jsx(ae,{className:"w-4 h-4"}):e.jsx(ne,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件人显示名(可选)"}),e.jsx("input",{"data-field":"smtp_from_name",type:"text",value:String(a.config.smtp_from_name||""),onChange:o,placeholder:"闲鱼自动回复系统",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["发件邮箱地址 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{"data-field":"smtp_from_address",type:"email",value:String(a.config.smtp_from_address||""),onChange:o,placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-3 text-xs font-bold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:a.config.smtp_use_tls!==!1,onChange:x}),"STARTTLS(常用于 587)"]}),e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-3 text-xs font-bold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:a.config.smtp_use_ssl===!0,onChange:w}),"SSL/TLS 直连(常用于 465)"]})]})]})]}),e.jsx(Le,{selectedEvents:a.event_types,onToggleEvent:U}),e.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[e.jsx("button",{type:"button",onClick:F,className:`relative w-11 h-6 rounded-full transition-colors ${a.enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full transition-transform ${a.enabled?"translate-x-5":""}`})}),e.jsx("span",{className:"text-sm font-bold text-gray-800",children:"启用此渠道"})]})]}),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:S,className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"取消"}),e.jsxs("button",{onClick:E,disabled:_,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[_?e.jsx(I,{className:"w-4 h-4 animate-spin"}):e.jsx(Q,{className:"w-4 h-4"}),_?"保存中...":"保存"]})]})]})}),document.body):null},Be=({smtp:s,setSmtp:t,smtpSaving:a,showPassword:n,setShowPassword:b,onSave:k})=>{const h=l=>{const o=l.currentTarget.dataset.field;o&&t(P=>({...P,[o]:l.target.value}))},_=l=>{t(o=>({...o,smtp_port:parseInt(l.target.value,10)||587}))},S=l=>{t(o=>({...o,smtp_use_tls:l.target.checked,smtp_use_ssl:l.target.checked?!1:o.smtp_use_ssl}))},E=l=>{t(o=>({...o,smtp_use_ssl:l.target.checked,smtp_use_tls:l.target.checked?!1:o.smtp_use_tls}))},j=l=>{t(o=>({...o,smtp_password:l.target.value}))},M=()=>b(l=>!l);return e.jsxs("section",{className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-extrabold text-gray-800",children:"SMTP 邮件配置"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"系统级邮件发送服务,供邮件通知渠道复用"})]}),e.jsx("div",{className:"p-2 rounded-xl bg-blue-50 text-blue-600",children:e.jsx(ee,{className:"w-5 h-5"})})]}),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-800",children:"SMTP 服务器"}),e.jsx("input",{"data-field":"smtp_server",type:"text",value:s.smtp_server||"",onChange:h,placeholder:"smtp.qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"SMTP 端口"}),e.jsx("input",{type:"number",value:s.smtp_port||587,onChange:_,placeholder:"587",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件邮箱"}),e.jsx("input",{"data-field":"smtp_user",type:"email",value:s.smtp_user||"",onChange:h,placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"邮箱密码 / 授权码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:n?"text":"password",value:s.smtp_password||"",onChange:j,placeholder:s.smtp_password_configured?"已配置,如需替换请输入新密码":"输入密码或授权码",className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"}),e.jsx("button",{type:"button",onClick:M,className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:n?e.jsx(ae,{className:"w-4 h-4"}):e.jsx(ne,{className:"w-4 h-4"})})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"QQ 邮箱需使用授权码(QQ 邮箱设置 → 账号 → 开启 SMTP → 生成授权码)"})]}),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-800",children:"发件人显示名(可选)"}),e.jsx("input",{"data-field":"smtp_from_name",type:"text",value:s.smtp_from_name||"",onChange:h,placeholder:"闲鱼自动回复系统",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件邮箱地址"}),e.jsx("input",{"data-field":"smtp_from_address",type:"email",value:s.smtp_from_address||s.smtp_user||"",onChange:h,placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-4 text-sm font-semibold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:s.smtp_use_tls!==!1,onChange:S}),"STARTTLS(常用于 587 端口)"]}),e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-4 text-sm font-semibold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:s.smtp_use_ssl===!0,onChange:E}),"SSL/TLS 直连(常用于 465 端口)"]})]}),e.jsxs("button",{onClick:k,disabled:a,className:"ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a?e.jsx(I,{className:"w-4 h-4 animate-spin"}):e.jsx(we,{className:"w-4 h-4"}),a?"保存中...":"保存 SMTP 配置"]})]})},$e=s=>{if(Array.isArray(s))return s.filter(Boolean);if(typeof s!="string"||!s.trim())return[];try{const t=JSON.parse(s);if(Array.isArray(t))return t.filter(Boolean)}catch{}return s.split(/[,\s;]+/).map(t=>t.trim()).filter(Boolean)},me=s=>{const t=Array.from(new Set((s||[]).filter(Boolean)));return t.length>0?JSON.stringify(t):""},Oe=s=>{let t={};try{const n=typeof s.config=="string"?JSON.parse(s.config):s.config;n&&typeof n=="object"&&!Array.isArray(n)&&(t=n)}catch{}const a=s.type==="ding_talk"?"dingtalk":s.type==="lark"?"feishu":s.type;return{id:String(s.id),name:s.name,type:a,config:t,event_types:$e(s.event_types),enabled:s.enabled,created_at:s.created_at,updated_at:s.updated_at}},Fe=async s=>{const t=await re("/api/v1/notifications/channels",void 0,s);return{success:!0,data:(Array.isArray(t)?t:t.data||t.channels||[]).map(Oe)}},De=async(s,t)=>oe("/api/v1/notifications/channels",{...s,config:JSON.stringify(s.config),event_types:me(s.event_types)},t),Z=async(s,t,a)=>{const n={...t};return"config"in t&&(n.config=JSON.stringify(t.config)),"event_types"in t&&(n.event_types=me(t.event_types)),le(`/api/v1/notifications/channels/${s}`,n,a)},We=async(s,t)=>Te(`/api/v1/notifications/channels/${s}`,void 0,t),Ie=async(s,t)=>oe(`/api/v1/notifications/channels/${s}/test`,{},t),Ue=s=>{const t={...s};if("renewal_log_retention_days"in t){const a=Number(t.renewal_log_retention_days);t.renewal_log_retention_days=Number.isFinite(a)?a:10}return t},Je=async s=>{const t=await re("/api/v1/settings/system",void 0,s);return Ue(t.data||t.settings||t)},Xe=async(s,t)=>le("/api/v1/settings/system",s,t),ze=s=>{const[t,a]=d.useState([]),[n,b]=d.useState(!0),[k,h]=d.useState(!1),[_,S]=d.useState(null),[E,j]=d.useState(!1),[M,l]=d.useState(""),[o,P]=d.useState(null),[x,w]=d.useState({}),[U,F]=d.useState(!1),[J,X]=d.useState(!1),[r,p]=d.useState(!1),[N,q]=d.useState(Y),$=d.useRef(0),z=d.useRef(null),C=d.useRef(0),L=d.useRef(null),y=d.useRef(0),T=d.useRef(null),R=d.useRef(null),f=d.useCallback((i,c)=>{P({type:i,text:c}),R.current!==null&&window.clearTimeout(R.current),R.current=window.setTimeout(()=>{R.current=null,P(null)},3e3)},[]),A=d.useCallback(async()=>{var m;const i=++$.current;(m=z.current)==null||m.abort();const c=new AbortController;z.current=c,b(!0);try{const u=await Fe({signal:c.signal});if(!g(i,$.current))return;a(u.data||[])}catch(u){g(i,$.current)&&!c.signal.aborted&&console.error("加载通知渠道失败",u)}finally{g(i,$.current)&&b(!1)}},[]),V=d.useCallback(async()=>{var m;const i=++C.current;(m=L.current)==null||m.abort();const c=new AbortController;L.current=c;try{const u=await Je({signal:c.signal});g(i,C.current)&&w(u||{})}catch(u){g(i,C.current)&&!c.signal.aborted&&console.error("加载 SMTP 配置失败",u)}},[]);d.useEffect(()=>{var i;return A(),s?V():(C.current+=1,(i=L.current)==null||i.abort(),w({})),(()=>{var c,m;$.current+=1,(c=z.current)==null||c.abort(),C.current+=1,(m=L.current)==null||m.abort()})},[s,A,V]),d.useEffect(()=>(()=>{R.current!==null&&window.clearTimeout(R.current)}),[]);const ue=d.useCallback(()=>{S(null),q(Y()),p(!1),h(!0)},[]),xe=d.useCallback(i=>{S(i),q(Ee(i,x)),p(!1),h(!0)},[x]),ge=d.useCallback(()=>{var i;y.current+=1,(i=T.current)==null||i.abort(),j(!1),h(!1)},[]),he=d.useCallback(async()=>{var u;const i=Me(N);if(i){f("error",i);return}const c=++y.current;(u=T.current)==null||u.abort();const m=new AbortController;T.current=m,j(!0);try{const v=qe(N);if(_?await Z(_.id,v,{signal:m.signal}):await De(v,{signal:m.signal}),!g(c,y.current)||(h(!1),await A(),!g(c,y.current)))return;f("success",_?"已更新":"已创建")}catch(v){g(c,y.current)&&!m.signal.aborted&&f("error",O(v,"保存失败"))}finally{g(c,y.current)&&j(!1)}},[_,N,A,f]),be=d.useCallback(async i=>{var u;if(!confirm(`确认删除渠道「${i.name}」吗?已绑定该渠道的账号会自动解绑。`))return;const c=++y.current;(u=T.current)==null||u.abort();const m=new AbortController;T.current=m;try{if(await We(i.id,{signal:m.signal}),!g(c,y.current)||(await A(),!g(c,y.current)))return;f("success","已删除")}catch(v){g(c,y.current)&&!m.signal.aborted&&f("error",O(v,"删除失败"))}},[A,f]),ye=d.useCallback(async i=>{var u;const c=++y.current;(u=T.current)==null||u.abort();const m=new AbortController;T.current=m;try{if(await Z(i.id,{enabled:!i.enabled},{signal:m.signal}),!g(c,y.current))return;a(v=>v.map(D=>D.id===i.id?{...D,enabled:!D.enabled}:D))}catch(v){g(c,y.current)&&!m.signal.aborted&&f("error",O(v,"切换失败"))}},[f]),fe=d.useCallback(async i=>{var u;l(i.id);const c=++y.current;(u=T.current)==null||u.abort();const m=new AbortController;T.current=m;try{await Ie(i.id,{signal:m.signal}),g(c,y.current)&&f("success","测试通知已发送,请检查对应渠道")}catch(v){g(c,y.current)&&!m.signal.aborted&&f("error",O(v,"发送失败"))}finally{g(c,y.current)&&l("")}},[f]),je=d.useCallback(async()=>{var m;const i=++C.current;(m=L.current)==null||m.abort();const c=new AbortController;L.current=c,F(!0);try{const u={smtp_server:x.smtp_server||"",smtp_port:x.smtp_port||587,smtp_user:x.smtp_user||"",smtp_from_name:x.smtp_from_name||"",smtp_from_address:x.smtp_from_address||x.smtp_user||"",smtp_use_tls:x.smtp_use_tls!==!1,smtp_use_ssl:x.smtp_use_ssl===!0};Object.prototype.hasOwnProperty.call(x,"smtp_password")&&(u.smtp_password=x.smtp_password),await Xe(u,{signal:c.signal}),g(i,C.current)&&f("success","SMTP 配置已保存")}catch(u){g(i,C.current)&&!c.signal.aborted&&f("error",O(u,"保存失败"))}finally{g(i,C.current)&&F(!1)}},[f,x]);return{channels:t,loading:n,showModal:k,editing:_,saving:E,testingId:M,toast:o,smtp:x,smtpSaving:U,showSmtpPassword:J,showChannelSmtpPassword:r,form:N,setForm:q,setSmtp:w,setShowSmtpPassword:X,setShowChannelSmtpPassword:p,loadChannels:A,openCreate:ue,openEdit:xe,closeModal:ge,showToast:f,handleSave:he,handleDelete:be,handleToggleEnabled:ye,handleTest:fe,handleSaveSmtp:je}},He=({isAdmin:s=!1})=>{const t=ze(s);return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"通知设置"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"配置通知渠道,账号异常时主动推送告警"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:t.loadChannels,className:"px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(Se,{className:"w-4 h-4"}),"刷新"]}),e.jsxs("button",{onClick:t.openCreate,className:"ios-btn-primary px-5 py-2.5 rounded-xl font-bold flex items-center gap-2",children:[e.jsx(Ce,{className:"w-4 h-4"}),"新建渠道"]})]})]}),e.jsx("div",{className:"ios-card rounded-xl p-5 bg-blue-50/50 border border-blue-100",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(W,{className:"w-5 h-5 text-brand mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"text-sm text-gray-700 leading-6",children:["配置通知渠道并在「账号管理 → 编辑」里绑定后,以下事件会主动推送到该账号绑定的渠道:",e.jsxs("ul",{className:"mt-2 space-y-1 text-gray-600",children:[e.jsxs("li",{children:["• ",e.jsx("strong",{children:"账号 session 失效"}),":系统正在尝试自动恢复(警告)"]}),e.jsxs("li",{children:["• ",e.jsx("strong",{children:"自动恢复失败"}),":账号已停止,需人工处理(严重)"]}),e.jsxs("li",{children:["• ",e.jsx("strong",{children:"触发风控验证"}),":可能需要扫码完成验证(警告)"]})]})]})]})}),t.loading?e.jsx("div",{className:"flex justify-center py-20",children:e.jsx(I,{className:"w-8 h-8 text-brand animate-spin"})}):e.jsx(Ae,{channels:t.channels,testingId:t.testingId,onEdit:t.openEdit,onDelete:t.handleDelete,onToggleEnabled:t.handleToggleEnabled,onTest:t.handleTest}),s&&e.jsx(Be,{smtp:t.smtp,setSmtp:t.setSmtp,smtpSaving:t.smtpSaving,showPassword:t.showSmtpPassword,setShowPassword:t.setShowSmtpPassword,onSave:t.handleSaveSmtp}),e.jsx(Re,{showModal:t.showModal,editing:t.editing,form:t.form,setForm:t.setForm,smtp:t.smtp,showChannelSmtpPassword:t.showChannelSmtpPassword,setShowChannelSmtpPassword:t.setShowChannelSmtpPassword,saving:t.saving,onClose:t.closeModal,onSave:t.handleSave}),t.toast&&e.jsxs("div",{className:`fixed bottom-8 left-1/2 -translate-x-1/2 z-[10000] px-5 py-3 rounded-xl shadow-lg font-bold text-sm flex items-center gap-2 animate-fade-in text-white ${t.toast.type==="success"?"bg-success-500":"bg-danger-500"}`,children:[t.toast.type==="success"?e.jsx(Q,{className:"w-4 h-4"}):e.jsx(te,{className:"w-4 h-4"}),t.toast.text]})]})};export{He as default}; diff --git a/internal/webui/static/assets/OrderList-CSGFKOqw.js b/internal/webui/static/assets/OrderList-BAnpJSM4.js similarity index 99% rename from internal/webui/static/assets/OrderList-CSGFKOqw.js rename to internal/webui/static/assets/OrderList-BAnpJSM4.js index 4ca91b8..28874e7 100644 --- a/internal/webui/static/assets/OrderList-CSGFKOqw.js +++ b/internal/webui/static/assets/OrderList-BAnpJSM4.js @@ -1 +1 @@ -import{j as e,b as J,r as a}from"./react-vendor-C_od1ZSF.js";import{U as te,I as re,X as W,J as ne,R as H,N as ie,O as Y,m as Z,E as ce,v as oe,V as de,F as xe,h as me,g as ue,r as he}from"./icons-vendor-CvzvbbIV.js";import{g as X,b as ae,a as K,p as ge,d as pe}from"./index-CFzx5gQT.js";import{o as be,c as ye}from"./contract-COFcZjyb.js";import{f as ee}from"./dateTime-DDi7rqpW.js";const fe=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],je=s=>{const t=typeof s=="object"&&s!==null?s:{},c=Array.isArray(t.results)?t.results:[];return{total:Number(t.total||0),success_count:Number(t.success_count||0),failed_count:Number(t.failed_count||0),results:c.map(ve)}},ve=s=>{const t=typeof s=="object"&&s!==null?s:{};return{order_id:String(t.order_id||"unknown"),success:t.success===!0,message:String(t.message||"")}},Ne=s=>(s==null?void 0:s.results.filter(we))||[],we=s=>!s.success,_e=(s,t)=>s!==null&&!t,ke=s=>{if(!s)return"请选择订单文件";const t=s.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(t)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},T=(s,t)=>s===t,Ce=(s,t)=>s instanceof Error&&s.message?s.message:t,Se=({filter:s,onFilterChange:t,accountFilter:c,onAccountFilterChange:h,accounts:g,accountName:m,searchText:u,onSearchChange:p})=>{const b=r=>t(r.currentTarget.dataset.status||"all"),_=r=>h(r.target.value),y=r=>p(r.target.value);return e.jsxs("div",{className:"p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-surface-muted",children:[e.jsx("div",{className:"flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full",children:fe.map(r=>e.jsx("button",{"data-status":r.key,onClick:b,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${s===r.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:r.label},r.key))}),e.jsxs("div",{className:"flex w-full md:w-auto flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(te,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{"aria-label":"按账号筛选订单",value:c,onChange:_,className:"ios-input pl-10 pr-9 py-2.5 rounded-xl w-full sm:w-56 bg-white border-none shadow-sm",children:[e.jsx("option",{value:"",children:"全部账号"}),g.map(r=>e.jsx("option",{value:r.id,children:m(r.id)},r.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(re,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-brand transition-colors"}),e.jsx("input",{type:"text",placeholder:"搜索订单号/商品/买家...",value:u,onChange:y,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},Ee=s=>{const t=m=>{var u;s.setImportFile(((u=m.target.files)==null?void 0:u[0])||null)},c=()=>s.closeImportModal(),h=()=>void s.handleImportOrders(),g=()=>void s.handleRetryImport();return s.showImportModal?J.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"插入订单"}),e.jsx("button",{onClick:c,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(W,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"选择Excel文件"}),e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv,.json",onChange:t,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持 .xlsx、.csv、.tsv、.json 格式"})]}),s.importFile&&e.jsx("div",{className:"p-3 bg-blue-50 rounded-xl",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ne,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{className:"text-sm font-medium text-blue-900",children:s.importFile.name})]})}),s.importError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-100 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:s.importError}),e.jsx("button",{type:"button",onClick:g,disabled:s.importing||!s.importFile,className:"font-bold whitespace-nowrap",children:"重试"})]}),s.importResult&&s.importResult.failed_count>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-100 p-3 text-sm font-bold text-amber-800",children:["导入完成:成功 ",s.importResult.success_count," 条,失败 ",s.importResult.failed_count," 条"]}),e.jsx("div",{className:"max-h-64 overflow-y-auto rounded-xl border border-gray-100",children:e.jsxs("table",{className:"w-full text-left text-xs",children:[e.jsx("thead",{className:"sticky top-0 bg-gray-50 text-gray-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2",children:"订单ID"}),e.jsx("th",{className:"px-3 py-2",children:"失败原因"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-100",children:Ne(s.importResult).map((m,u)=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-mono",children:m.order_id}),e.jsx("td",{className:"px-3 py-2 text-red-600",children:m.message||"导入失败"})]},`${m.order_id}-${u}`))})]})})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:c,className:"flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:"取消"}),e.jsx("button",{onClick:h,disabled:!s.importFile||s.importing,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:s.importing?"正在导入…":"导入订单"})]})})]})}),document.body):null},Ie=async s=>X("/api/v1/accounts/details",void 0,s),Oe=async(s,t)=>X("/api/v1/items",void 0,t),Fe=s=>{const t=String(s||"");return t==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(t)?t:"unknown"},Me=async(s,t,c=1,h=20,g,m)=>{const u={page:c,page_size:h};s&&(u.cookie_id=s),t&&t!=="all"&&(u.status=t),g!=null&&g.trim()&&(u.search=g.trim());const p=await X("/api/v1/orders",u,m),b=be(p,["data","result"])||{},y=(Array.isArray(b.orders)?b.orders:ye(b.data,["data","orders","items"])).map(r=>({...r,id:r.id||r.order_id,status:Fe(r.status||r.order_status),quantity:Number(r.quantity||1)}));return{success:!0,data:y,total:b.total||y.length,page:b.page||c,page_size:b.page_size||h,total_pages:b.total_pages||1}},De=async(s,t)=>ge(`/api/v1/orders/${s}`,t),Re=async s=>pe(`/api/v1/orders/${s}`),$e=async(s,t,c)=>{const h=new FormData;s&&h.append("cookie_id",s),t&&h.append("status",t);const g=await ae("/api/v1/orders/refresh",h,c),m=180;let u=0;try{for(;u{const r=()=>{globalThis.clearTimeout(i),y(new Error("请求已取消"))},i=globalThis.setTimeout(()=>{var C;(C=c==null?void 0:c.signal)==null||C.removeEventListener("abort",r),_()},b);c!=null&&c.signal&&(c.signal.aborted?r():c.signal.addEventListener("abort",r,{once:!0}))}),u+=1}}finally{}throw new Error("订单刷新任务等待超时")},Ae=async s=>K(`/api/v1/orders/${s}/refresh`),Le=async(s,t)=>K("/api/v1/orders/manual-ship",{order_ids:s,ship_mode:t}),Pe=async(s,t)=>s instanceof FormData?ae("/api/v1/orders/import",s,t):K("/api/v1/orders/import",s,t),Te=(s={pageSize:20})=>{const[t,c]=a.useState([]),[h,g]=a.useState([]),[m,u]=a.useState([]),[p,b]=a.useState("all"),[_,y]=a.useState(""),[r,i]=a.useState(""),[C,$]=a.useState(""),[O,S]=a.useState(1),[w,A]=a.useState(1),[F,o]=a.useState(!1),N=a.useRef(0),f=a.useRef(null),M=a.useRef(null),D=a.useCallback(async()=>{var j;const d=++N.current;(j=f.current)==null||j.abort();const x=new AbortController;f.current=x,o(!0);try{const E=await Me(_||void 0,p,O,s.pageSize,C,{signal:x.signal});if(!T(d,N.current))return;c(E.data),A(E.total_pages)}catch(E){T(d,N.current)&&!x.signal.aborted&&console.error("加载订单失败:",E)}finally{T(d,N.current)&&o(!1)}},[_,C,p,s.pageSize,O]);a.useEffect(()=>{const d=window.setTimeout(()=>{S(1),$(r.trim())},300);return(()=>window.clearTimeout(d))},[r]),a.useEffect(()=>(D(),(()=>{var d;N.current+=1,(d=f.current)==null||d.abort()})),[D]),a.useEffect(()=>{var x;const d=new AbortController;return(x=M.current)==null||x.abort(),M.current=d,Promise.all([Ie({signal:d.signal}),Oe(void 0,{signal:d.signal})]).then(([j,E])=>{d.signal.aborted||(u(j),g(E))}).catch(j=>{d.signal.aborted||console.error("加载订单辅助数据失败:",j)}),(()=>d.abort())},[]);const k=a.useMemo(()=>new Map(m.map(d=>[d.id,d])),[m]),P=a.useMemo(()=>{const d={};return h.forEach(x=>{x.item_id&&(d[`${x.cookie_id}:${x.item_id}`]=x.item_title||x.item_id)}),d},[h]),U=a.useCallback(d=>{const x=k.get(d),j=(x==null?void 0:x.remark)||(x==null?void 0:x.nickname);return j?`${j} · ${d.slice(0,6)}`:`账号 ${d.slice(0,8)}`},[k]),V=a.useCallback(d=>{const x=k.get(d);return(x==null?void 0:x.remark)||(x==null?void 0:x.nickname)||"未命名账号"},[k]),q=a.useCallback((d,x,j)=>{if(j!=null&&j.trim())return j;const E=P[`${d}:${x}`];if(E)return E;const I=h.find(z=>{if(!j||!z.item_title)return!1;const B=j.toLowerCase(),L=z.item_title.toLowerCase();return L.includes(B)||B.includes(L)});return(I==null?void 0:I.item_title)||"未知商品"},[P,h]);return{orders:t,items:h,accounts:m,filter:p,setFilter:b,accountFilter:_,setAccountFilter:y,searchText:r,setSearchText:i,page:O,setPage:S,totalPages:w,loading:F,loadOrders:D,accountName:U,accountNickname:V,getItemNameById:q}},qe=s=>{const[t,c]=a.useState(!1),[h,g]=a.useState(null),[m,u]=a.useState(null),[p,b]=a.useState(!1),[_,y]=a.useState(""),r=a.useRef(0),i=a.useRef(null);a.useEffect(()=>(()=>{var w;r.current+=1,(w=i.current)==null||w.abort()}),[]);const C=a.useCallback(()=>{g(null),u(null),y(""),c(!0)},[]),$=a.useCallback(()=>{var w;r.current+=1,(w=i.current)==null||w.abort(),b(!1),c(!1),g(null),u(null),y("")},[]),O=a.useCallback(async()=>{var N;if(!_e(h,p))return;const w=h;if(!w)return;const A=ke(w);if(A){y(A);return}const F=++r.current;(N=i.current)==null||N.abort();const o=new AbortController;i.current=o,b(!0),u(null),y("");try{const f=new FormData;f.append("file",w);const M=je(await Pe(f,{signal:o.signal}));if(!T(F,r.current))return;u(M),g(null),await s(),M.failed_count===0&&T(F,r.current)&&(alert(`订单导入成功,共 ${M.success_count} 条`),c(!1),u(null))}catch(f){T(F,r.current)&&!o.signal.aborted&&y(Ce(f,"导入失败,请检查文件格式"))}finally{T(F,r.current)&&b(!1)}},[h,p,s]),S=a.useCallback(async()=>{await O()},[O]);return{showImportModal:t,importFile:h,setImportFile:g,importResult:m,importing:p,importError:_,openImportModal:C,closeImportModal:$,handleImportOrders:O,handleRetryImport:S}},Q=(s,t)=>s instanceof Error?s.message:t,ze=({orders:s,page:t,accountFilter:c,filter:h,setPage:g,loadOrders:m})=>{const[u,p]=a.useState(!1),[b,_]=a.useState(null),[y,r]=a.useState(!1),[i,C]=a.useState(null),[$,O]=a.useState(!1),[S,w]=a.useState(""),[A,F]=a.useState(!1),[o,N]=a.useState(null),[f,M]=a.useState(null),[D,k]=a.useState(null),P=a.useCallback(async()=>{try{const n=await $e(c||void 0,h);await m(),n.message&&alert(n.message)}catch(n){console.error("同步订单失败:",n),alert(Q(n,"同步失败,请重试"))}},[c,h,m]),U=a.useCallback(n=>{w(n),N(null),O(!0)},[]),V=a.useCallback(async n=>{var v;F(!0),N(null);try{const R=(v=(await Le([S],n)).results)==null?void 0:v[0];R!=null&&R.success?(N({success:!0,message:R.message}),m()):N({success:!1,message:(R==null?void 0:R.message)||"发货失败"})}catch(G){N({success:!1,message:Q(G,"请求失败")})}finally{F(!1)}},[m,S]),q=a.useCallback(n=>{_(n),p(!0)},[]),d=a.useCallback(n=>{C({...n}),r(!0)},[]),x=a.useCallback(n=>{C(v=>v&&{...v,...n})},[]),j=a.useCallback(async()=>{if(i!=null&&i.order_id)try{const n={};i.status!==void 0&&(n.order_status=i.status),i.buyer_id!==void 0&&(n.buyer_id=i.buyer_id),i.amount!==void 0&&(n.amount=i.amount),i.receiver_name!==void 0&&(n.receiver_name=i.receiver_name),i.receiver_phone!==void 0&&(n.receiver_phone=i.receiver_phone),i.receiver_address!==void 0&&(n.receiver_address=i.receiver_address),i.item_id!==void 0&&(n.item_id=i.item_id),i.quantity!==void 0&&(n.quantity=i.quantity),i.item_title!==void 0&&(n.item_title=i.item_title),await De(i.order_id,n),r(!1),C(null),await m()}catch(n){console.error("更新订单失败:",n),alert("更新失败,请重试")}},[i,m]),E=a.useCallback(async n=>{M(n);try{const v=await Ae(n);v.success?await m():alert(v.message||"同步失败")}catch(v){console.error("同步订单失败:",v),alert(Q(v,"同步失败,请重试"))}finally{M(null)}},[m]),I=a.useCallback(async n=>{if(confirm("确认删除该订单吗?删除后无法恢复。")){k(n);try{await Re(n),s.length===1&&t>1?g(v=>v-1):await m()}catch(v){console.error("删除订单失败:",v),alert(Q(v,"删除失败,请重试")),await m()}finally{k(null)}}},[m,s.length,t,g]),z=a.useCallback(()=>p(!1),[]),B=a.useCallback(()=>r(!1),[]),L=a.useCallback(()=>{O(!1),N(null)},[]);return{showDetailModal:u,selectedOrder:b,showEditModal:y,editingOrder:i,showShipModal:$,shipOrderId:S,shipLoading:A,shipResult:o,syncingOrderId:f,deletingOrderId:D,handleSync:P,handleShip:U,executeShip:V,handleViewDetail:q,handleEdit:d,handleSaveEdit:j,updateEditingOrder:x,handleSyncSingle:E,handleDelete:I,closeDetailModal:z,closeEditModal:B,closeShipModal:L}},se=({status:s})=>{const t={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"},c={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${t[s]||t.cancelled}`,children:c[s]||s})},Je=()=>{const s=Te(),t=qe(s.loadOrders),{orders:c,accounts:h,filter:g,setFilter:m,accountFilter:u,setAccountFilter:p,searchText:b,setSearchText:_,page:y,setPage:r,totalPages:i,loading:C,loadOrders:$,accountName:O,accountNickname:S,getItemNameById:w}=s,A=ze({orders:c,page:y,accountFilter:u,filter:g,setPage:r,loadOrders:$}),{showDetailModal:F,selectedOrder:o,showEditModal:N,editingOrder:f,showShipModal:M,shipLoading:D,shipResult:k,syncingOrderId:P,deletingOrderId:U,handleSync:V,handleShip:q,executeShip:d,handleViewDetail:x,handleEdit:j,handleSaveEdit:E,updateEditingOrder:I,handleSyncSingle:z,handleDelete:B,closeDetailModal:L,closeEditModal:n,closeShipModal:v}=A,G=l=>{m(l),r(1),_("")},R=l=>{p(l),r(1)},le=l=>{_(l),r(1)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"订单中心"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"查看所有闲鱼交易记录与状态。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:$,className:"p-3 rounded-2xl bg-white border border-gray-100 text-gray-600 hover:bg-gray-50 hover:text-black transition-colors shadow-sm",children:e.jsx(H,{className:`w-5 h-5 ${C?"animate-spin":""}`})}),e.jsxs("button",{onClick:t.openImportModal,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors text-sm flex items-center gap-2 shadow-lg",children:[e.jsx(ie,{className:"w-4 h-4"}),"插入订单"]}),e.jsxs("button",{onClick:V,className:"ios-btn-primary px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 text-sm flex items-center gap-2",children:[e.jsx(Y,{className:"w-5 h-5"}),"一键同步订单"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsx(Se,{filter:g,onFilterChange:G,accountFilter:u,onAccountFilterChange:R,accounts:h,accountName:O,searchText:b,onSearchChange:le}),e.jsx("div",{className:"overflow-x-auto min-h-[400px]",children:e.jsxs("table",{className:"w-full text-left border-collapse table-fixed",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"px-6 py-5",style:{width:"28%"},children:"订单信息"}),e.jsx("th",{className:"px-6 py-5",style:{width:"26%"},children:"买家信息"}),e.jsx("th",{className:"px-6 py-5",style:{width:"11%"},children:"实付金额"}),e.jsx("th",{className:"px-6 py-5",style:{width:"13%"},children:"当前状态"}),e.jsx("th",{className:"px-6 py-5 text-right",style:{width:"22%"},children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:c.map(l=>e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-6 py-5",children:e.jsxs("div",{className:"flex items-center gap-5",children:[e.jsx("div",{className:"w-14 h-14 rounded-xl bg-gray-100 overflow-hidden shadow-sm border border-gray-100 flex-shrink-0",children:l.item_image?e.jsx("img",{src:l.item_image,alt:"",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-gray-300",children:e.jsx(Z,{})})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 line-clamp-1 text-sm",children:w(l.cookie_id,l.item_id,l.item_title)}),e.jsxs("div",{className:"mt-1 flex w-fit min-w-0 max-w-full items-center gap-1 rounded-md bg-blue-50 px-2 py-1 text-[10px] font-extrabold text-blue-700",title:S(l.cookie_id),children:[e.jsx(te,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"min-w-0 truncate whitespace-nowrap",children:S(l.cookie_id)})]}),e.jsxs("div",{className:"text-xs text-gray-500 mt-1 font-medium",children:["订单ID: ",l.order_id]}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",l.quantity," • ",ee(l.created_at)]})]})]})}),e.jsx("td",{className:"px-6 py-5",children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("div",{className:"text-xs text-gray-500",children:"买家ID"}),e.jsx("div",{className:"text-sm font-bold text-gray-800",children:l.buyer_id}),l.receiver_name&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"收货人"}),e.jsx("div",{className:"text-xs text-gray-600",children:l.receiver_name})]}),l.receiver_phone&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"联系电话"}),e.jsx("div",{className:"text-xs text-gray-600 font-mono",children:l.receiver_phone})]}),l.receiver_address&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"收货地址"}),e.jsx("div",{className:"text-xs text-gray-600 line-clamp-1",children:l.receiver_address})]})]})}),e.jsx("td",{className:"px-6 py-5 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:l.amount?`¥${l.amount}`:e.jsx("span",{className:"text-xs text-amber-600 font-bold",children:"待获取"})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx(se,{status:l.status})}),e.jsxs("td",{className:"px-6 py-5 text-right",children:[l.status==="pending_ship"&&e.jsx("button",{onClick:(()=>q(l.order_id)),className:"mr-2 text-white bg-black hover:bg-gray-800 shadow-lg shadow-gray-200 text-xs font-bold px-3 py-2 rounded-xl transition-all active:scale-95",children:"立即发货"}),e.jsx("a",{href:`https://www.goofish.com/order-detail?orderId=${l.order_id}&role=seller`,target:"_blank",rel:"noopener noreferrer",className:"mr-2 inline-flex text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看闲鱼详情",children:e.jsx(ce,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>x(l)),className:"mr-2 text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看详情",children:e.jsx(oe,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>j(l)),className:"mr-2 text-gray-400 hover:text-black p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"编辑订单",children:e.jsx(de,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>z(l.order_id)),disabled:P===l.order_id,className:"mr-2 text-gray-400 hover:text-green-600 p-2 rounded-xl hover:bg-green-50 transition-colors disabled:opacity-50",title:"同步订单",children:e.jsx(H,{className:`w-4 h-4 ${P===l.order_id?"animate-spin":""}`})}),e.jsx("button",{onClick:(()=>B(l.order_id)),disabled:U===l.order_id,className:"text-gray-400 hover:text-red-500 p-2 rounded-xl hover:bg-red-50 transition-colors disabled:opacity-50",title:"删除订单",children:e.jsx(xe,{className:"w-4 h-4"})})]})]},l.id))})]})}),e.jsxs("div",{className:"p-4 border-t border-gray-50 flex items-center justify-between bg-white",children:[e.jsxs("div",{className:"text-sm text-gray-500 font-medium pl-2",children:["第 ",y," 页 / 共 ",i," 页"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{disabled:y<=1,onClick:(()=>r(l=>l-1)),"aria-label":"上一页",className:"p-2.5 rounded-xl bg-gray-50 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 transition-colors",children:e.jsx(me,{className:"w-5 h-5"})}),e.jsx("button",{disabled:y>=i,onClick:(()=>r(l=>l+1)),"aria-label":"下一页",className:"p-2.5 rounded-xl bg-gray-50 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 transition-colors",children:e.jsx(ue,{className:"w-5 h-5"})})]})]})]}),F&&o&&J.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"订单详情"}),e.jsx("button",{onClick:L,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(W,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"订单信息"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"订单号"}),e.jsx("div",{className:"font-mono text-sm font-bold text-gray-900",children:o.order_id})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"所属账号"}),e.jsx("div",{className:"truncate whitespace-nowrap text-sm font-bold text-blue-700",title:S(o.cookie_id),children:S(o.cookie_id)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"状态"}),e.jsx(se,{status:o.status})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"实付金额"}),e.jsx("div",{className:"text-lg font-extrabold text-gray-900",children:o.amount?`¥${o.amount}`:"待获取"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"数量"}),e.jsx("div",{className:"font-bold text-gray-900",children:o.quantity})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"创建时间"}),e.jsx("div",{className:"text-sm font-medium text-gray-700",children:ee(o.created_at)})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"商品信息"}),e.jsxs("div",{className:"p-4 bg-gray-50 rounded-xl flex items-center gap-4",children:[o.item_image&&e.jsx("img",{src:o.item_image,alt:"",className:"w-20 h-20 rounded-xl object-cover border border-gray-200"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-bold text-gray-900 mb-1",children:w(o.cookie_id,o.item_id,o.item_title)}),e.jsxs("div",{className:"text-sm text-gray-500",children:["商品ID: ",o.item_id]}),o.item_price&&e.jsxs("div",{className:"text-sm text-gray-500 mt-1",children:["标价: ¥",o.item_price]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"买家信息"}),e.jsxs("div",{className:"p-4 bg-gray-50 rounded-xl space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"买家ID"}),e.jsx("div",{className:"font-bold text-gray-900",children:o.buyer_id})]}),o.receiver_name&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"收货人"}),e.jsx("div",{className:"font-medium text-gray-700",children:o.receiver_name})]}),o.receiver_phone&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"联系电话"}),e.jsx("div",{className:"font-mono text-sm text-gray-700",children:o.receiver_phone})]}),o.receiver_address&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"收货地址"}),e.jsx("div",{className:"text-sm text-gray-700",children:o.receiver_address})]})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:L,className:"flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:"关闭"}),o.status==="pending_ship"&&e.jsx("button",{onClick:(()=>{L(),q(o.order_id)}),className:"flex-1 px-6 py-3 rounded-xl ios-btn-primary font-bold shadow-lg shadow-blue-200",children:"立即发货"})]})})]})}),document.body),e.jsx(Ee,{...t}),M&&J.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"480px"},children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"立即发货"}),e.jsx("button",{onClick:v,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(W,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-4",children:[e.jsx("p",{className:"text-sm text-gray-600",children:"请选择发货方式:"}),e.jsx("button",{onClick:(()=>d("status_only")),disabled:D,className:"w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-gray-400 hover:bg-gray-50 transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(Y,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:"仅修改闲鱼发货状态"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 leading-relaxed",children:'不实际扣除或发送卡券,仅在闲鱼平台将订单标记为"已发货"。 适用于已经给客户发过货、只是忘记在闲鱼修改状态的情况。'})]})]})}),e.jsx("button",{onClick:(()=>d("full_delivery")),disabled:D,className:"w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-brand hover:bg-blue-50 transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(Z,{className:"w-5 h-5 text-blue-700"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:"完整发货(匹配卡券并发送)"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 leading-relaxed",children:"自动匹配发货规则、获取卡券、发送卡券信息给买家,并修改发货状态。 适用于订单既没有发送卡券给买家、也没有修改发货状态的情况。"})]})]})}),D&&e.jsxs("div",{className:"flex items-center justify-center gap-2 py-3",children:[e.jsx(H,{className:"w-4 h-4 animate-spin text-gray-500"}),e.jsx("span",{className:"text-sm text-gray-500",children:"正在处理中..."})]}),k&&e.jsxs("div",{className:`p-3 rounded-xl text-sm ${k.success?"bg-green-50 text-green-800":"bg-red-50 text-red-800"}`,children:[k.success?"✓ ":"✗ ",k.message]})]}),e.jsx("div",{className:"modal-footer",children:e.jsx("button",{onClick:v,className:"w-full px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:k!=null&&k.success?"完成":"取消"})})]})}),document.body),N&&f&&J.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑订单"}),e.jsx("button",{onClick:n,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(W,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"订单号"}),e.jsx("input",{type:"text",value:f.order_id,disabled:!0,className:"w-full ios-input px-4 py-3 rounded-xl bg-gray-50 text-gray-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"订单状态"}),e.jsxs("select",{value:f.status,onChange:(l=>I({status:l.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"processing",children:"处理中"}),e.jsx("option",{value:"pending_ship",children:"待发货"}),e.jsx("option",{value:"shipped",children:"已发货"}),e.jsx("option",{value:"completed",children:"已完成"}),e.jsx("option",{value:"cancelled",children:"已取消"}),e.jsx("option",{value:"refunding",children:"退款中"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"买家ID"}),e.jsx("input",{type:"text",value:f.buyer_id,onChange:(l=>I({buyer_id:l.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"实付金额"}),e.jsx("input",{type:"number",value:f.amount,onChange:(l=>I({amount:l.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"收货人"}),e.jsx("input",{type:"text",value:f.receiver_name||"",onChange:(l=>I({receiver_name:l.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"联系电话"}),e.jsx("input",{type:"text",value:f.receiver_phone||"",onChange:(l=>I({receiver_phone:l.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"收货地址"}),e.jsx("textarea",{value:f.receiver_address||"",onChange:(l=>I({receiver_address:l.target.value})),rows:2,className:"w-full ios-input px-4 py-3 rounded-xl resize-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"商品标题"}),e.jsx("input",{type:"text",value:f.item_title||"",onChange:(l=>I({item_title:l.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),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",children:"取消"}),e.jsxs("button",{onClick:E,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(he,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body)]})};export{Je as default}; +import{j as e,b as J,r as a}from"./react-vendor-C_od1ZSF.js";import{U as te,I as re,X as W,J as ne,R as H,N as ie,O as Y,m as Z,E as ce,v as oe,V as de,F as xe,h as me,g as ue,r as he}from"./icons-vendor-CvzvbbIV.js";import{g as X,b as ae,a as K,p as ge,d as pe}from"./index-hByDAHGj.js";import{o as be,c as ye}from"./contract-COFcZjyb.js";import{f as ee}from"./dateTime-DDi7rqpW.js";const fe=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],je=s=>{const t=typeof s=="object"&&s!==null?s:{},c=Array.isArray(t.results)?t.results:[];return{total:Number(t.total||0),success_count:Number(t.success_count||0),failed_count:Number(t.failed_count||0),results:c.map(ve)}},ve=s=>{const t=typeof s=="object"&&s!==null?s:{};return{order_id:String(t.order_id||"unknown"),success:t.success===!0,message:String(t.message||"")}},Ne=s=>(s==null?void 0:s.results.filter(we))||[],we=s=>!s.success,_e=(s,t)=>s!==null&&!t,ke=s=>{if(!s)return"请选择订单文件";const t=s.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(t)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},T=(s,t)=>s===t,Ce=(s,t)=>s instanceof Error&&s.message?s.message:t,Se=({filter:s,onFilterChange:t,accountFilter:c,onAccountFilterChange:h,accounts:g,accountName:m,searchText:u,onSearchChange:p})=>{const b=r=>t(r.currentTarget.dataset.status||"all"),_=r=>h(r.target.value),y=r=>p(r.target.value);return e.jsxs("div",{className:"p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-surface-muted",children:[e.jsx("div",{className:"flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full",children:fe.map(r=>e.jsx("button",{"data-status":r.key,onClick:b,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${s===r.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:r.label},r.key))}),e.jsxs("div",{className:"flex w-full md:w-auto flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(te,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{"aria-label":"按账号筛选订单",value:c,onChange:_,className:"ios-input pl-10 pr-9 py-2.5 rounded-xl w-full sm:w-56 bg-white border-none shadow-sm",children:[e.jsx("option",{value:"",children:"全部账号"}),g.map(r=>e.jsx("option",{value:r.id,children:m(r.id)},r.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(re,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-brand transition-colors"}),e.jsx("input",{type:"text",placeholder:"搜索订单号/商品/买家...",value:u,onChange:y,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},Ee=s=>{const t=m=>{var u;s.setImportFile(((u=m.target.files)==null?void 0:u[0])||null)},c=()=>s.closeImportModal(),h=()=>void s.handleImportOrders(),g=()=>void s.handleRetryImport();return s.showImportModal?J.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"插入订单"}),e.jsx("button",{onClick:c,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(W,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"选择Excel文件"}),e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv,.json",onChange:t,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持 .xlsx、.csv、.tsv、.json 格式"})]}),s.importFile&&e.jsx("div",{className:"p-3 bg-blue-50 rounded-xl",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ne,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{className:"text-sm font-medium text-blue-900",children:s.importFile.name})]})}),s.importError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-100 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:s.importError}),e.jsx("button",{type:"button",onClick:g,disabled:s.importing||!s.importFile,className:"font-bold whitespace-nowrap",children:"重试"})]}),s.importResult&&s.importResult.failed_count>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-100 p-3 text-sm font-bold text-amber-800",children:["导入完成:成功 ",s.importResult.success_count," 条,失败 ",s.importResult.failed_count," 条"]}),e.jsx("div",{className:"max-h-64 overflow-y-auto rounded-xl border border-gray-100",children:e.jsxs("table",{className:"w-full text-left text-xs",children:[e.jsx("thead",{className:"sticky top-0 bg-gray-50 text-gray-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2",children:"订单ID"}),e.jsx("th",{className:"px-3 py-2",children:"失败原因"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-100",children:Ne(s.importResult).map((m,u)=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-mono",children:m.order_id}),e.jsx("td",{className:"px-3 py-2 text-red-600",children:m.message||"导入失败"})]},`${m.order_id}-${u}`))})]})})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:c,className:"flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:"取消"}),e.jsx("button",{onClick:h,disabled:!s.importFile||s.importing,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:s.importing?"正在导入…":"导入订单"})]})})]})}),document.body):null},Ie=async s=>X("/api/v1/accounts/details",void 0,s),Oe=async(s,t)=>X("/api/v1/items",void 0,t),Fe=s=>{const t=String(s||"");return t==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(t)?t:"unknown"},Me=async(s,t,c=1,h=20,g,m)=>{const u={page:c,page_size:h};s&&(u.cookie_id=s),t&&t!=="all"&&(u.status=t),g!=null&&g.trim()&&(u.search=g.trim());const p=await X("/api/v1/orders",u,m),b=be(p,["data","result"])||{},y=(Array.isArray(b.orders)?b.orders:ye(b.data,["data","orders","items"])).map(r=>({...r,id:r.id||r.order_id,status:Fe(r.status||r.order_status),quantity:Number(r.quantity||1)}));return{success:!0,data:y,total:b.total||y.length,page:b.page||c,page_size:b.page_size||h,total_pages:b.total_pages||1}},De=async(s,t)=>ge(`/api/v1/orders/${s}`,t),Re=async s=>pe(`/api/v1/orders/${s}`),$e=async(s,t,c)=>{const h=new FormData;s&&h.append("cookie_id",s),t&&h.append("status",t);const g=await ae("/api/v1/orders/refresh",h,c),m=180;let u=0;try{for(;u{const r=()=>{globalThis.clearTimeout(i),y(new Error("请求已取消"))},i=globalThis.setTimeout(()=>{var C;(C=c==null?void 0:c.signal)==null||C.removeEventListener("abort",r),_()},b);c!=null&&c.signal&&(c.signal.aborted?r():c.signal.addEventListener("abort",r,{once:!0}))}),u+=1}}finally{}throw new Error("订单刷新任务等待超时")},Ae=async s=>K(`/api/v1/orders/${s}/refresh`),Le=async(s,t)=>K("/api/v1/orders/manual-ship",{order_ids:s,ship_mode:t}),Pe=async(s,t)=>s instanceof FormData?ae("/api/v1/orders/import",s,t):K("/api/v1/orders/import",s,t),Te=(s={pageSize:20})=>{const[t,c]=a.useState([]),[h,g]=a.useState([]),[m,u]=a.useState([]),[p,b]=a.useState("all"),[_,y]=a.useState(""),[r,i]=a.useState(""),[C,$]=a.useState(""),[O,S]=a.useState(1),[w,A]=a.useState(1),[F,o]=a.useState(!1),N=a.useRef(0),f=a.useRef(null),M=a.useRef(null),D=a.useCallback(async()=>{var j;const d=++N.current;(j=f.current)==null||j.abort();const x=new AbortController;f.current=x,o(!0);try{const E=await Me(_||void 0,p,O,s.pageSize,C,{signal:x.signal});if(!T(d,N.current))return;c(E.data),A(E.total_pages)}catch(E){T(d,N.current)&&!x.signal.aborted&&console.error("加载订单失败:",E)}finally{T(d,N.current)&&o(!1)}},[_,C,p,s.pageSize,O]);a.useEffect(()=>{const d=window.setTimeout(()=>{S(1),$(r.trim())},300);return(()=>window.clearTimeout(d))},[r]),a.useEffect(()=>(D(),(()=>{var d;N.current+=1,(d=f.current)==null||d.abort()})),[D]),a.useEffect(()=>{var x;const d=new AbortController;return(x=M.current)==null||x.abort(),M.current=d,Promise.all([Ie({signal:d.signal}),Oe(void 0,{signal:d.signal})]).then(([j,E])=>{d.signal.aborted||(u(j),g(E))}).catch(j=>{d.signal.aborted||console.error("加载订单辅助数据失败:",j)}),(()=>d.abort())},[]);const k=a.useMemo(()=>new Map(m.map(d=>[d.id,d])),[m]),P=a.useMemo(()=>{const d={};return h.forEach(x=>{x.item_id&&(d[`${x.cookie_id}:${x.item_id}`]=x.item_title||x.item_id)}),d},[h]),U=a.useCallback(d=>{const x=k.get(d),j=(x==null?void 0:x.remark)||(x==null?void 0:x.nickname);return j?`${j} · ${d.slice(0,6)}`:`账号 ${d.slice(0,8)}`},[k]),V=a.useCallback(d=>{const x=k.get(d);return(x==null?void 0:x.remark)||(x==null?void 0:x.nickname)||"未命名账号"},[k]),q=a.useCallback((d,x,j)=>{if(j!=null&&j.trim())return j;const E=P[`${d}:${x}`];if(E)return E;const I=h.find(z=>{if(!j||!z.item_title)return!1;const B=j.toLowerCase(),L=z.item_title.toLowerCase();return L.includes(B)||B.includes(L)});return(I==null?void 0:I.item_title)||"未知商品"},[P,h]);return{orders:t,items:h,accounts:m,filter:p,setFilter:b,accountFilter:_,setAccountFilter:y,searchText:r,setSearchText:i,page:O,setPage:S,totalPages:w,loading:F,loadOrders:D,accountName:U,accountNickname:V,getItemNameById:q}},qe=s=>{const[t,c]=a.useState(!1),[h,g]=a.useState(null),[m,u]=a.useState(null),[p,b]=a.useState(!1),[_,y]=a.useState(""),r=a.useRef(0),i=a.useRef(null);a.useEffect(()=>(()=>{var w;r.current+=1,(w=i.current)==null||w.abort()}),[]);const C=a.useCallback(()=>{g(null),u(null),y(""),c(!0)},[]),$=a.useCallback(()=>{var w;r.current+=1,(w=i.current)==null||w.abort(),b(!1),c(!1),g(null),u(null),y("")},[]),O=a.useCallback(async()=>{var N;if(!_e(h,p))return;const w=h;if(!w)return;const A=ke(w);if(A){y(A);return}const F=++r.current;(N=i.current)==null||N.abort();const o=new AbortController;i.current=o,b(!0),u(null),y("");try{const f=new FormData;f.append("file",w);const M=je(await Pe(f,{signal:o.signal}));if(!T(F,r.current))return;u(M),g(null),await s(),M.failed_count===0&&T(F,r.current)&&(alert(`订单导入成功,共 ${M.success_count} 条`),c(!1),u(null))}catch(f){T(F,r.current)&&!o.signal.aborted&&y(Ce(f,"导入失败,请检查文件格式"))}finally{T(F,r.current)&&b(!1)}},[h,p,s]),S=a.useCallback(async()=>{await O()},[O]);return{showImportModal:t,importFile:h,setImportFile:g,importResult:m,importing:p,importError:_,openImportModal:C,closeImportModal:$,handleImportOrders:O,handleRetryImport:S}},Q=(s,t)=>s instanceof Error?s.message:t,ze=({orders:s,page:t,accountFilter:c,filter:h,setPage:g,loadOrders:m})=>{const[u,p]=a.useState(!1),[b,_]=a.useState(null),[y,r]=a.useState(!1),[i,C]=a.useState(null),[$,O]=a.useState(!1),[S,w]=a.useState(""),[A,F]=a.useState(!1),[o,N]=a.useState(null),[f,M]=a.useState(null),[D,k]=a.useState(null),P=a.useCallback(async()=>{try{const n=await $e(c||void 0,h);await m(),n.message&&alert(n.message)}catch(n){console.error("同步订单失败:",n),alert(Q(n,"同步失败,请重试"))}},[c,h,m]),U=a.useCallback(n=>{w(n),N(null),O(!0)},[]),V=a.useCallback(async n=>{var v;F(!0),N(null);try{const R=(v=(await Le([S],n)).results)==null?void 0:v[0];R!=null&&R.success?(N({success:!0,message:R.message}),m()):N({success:!1,message:(R==null?void 0:R.message)||"发货失败"})}catch(G){N({success:!1,message:Q(G,"请求失败")})}finally{F(!1)}},[m,S]),q=a.useCallback(n=>{_(n),p(!0)},[]),d=a.useCallback(n=>{C({...n}),r(!0)},[]),x=a.useCallback(n=>{C(v=>v&&{...v,...n})},[]),j=a.useCallback(async()=>{if(i!=null&&i.order_id)try{const n={};i.status!==void 0&&(n.order_status=i.status),i.buyer_id!==void 0&&(n.buyer_id=i.buyer_id),i.amount!==void 0&&(n.amount=i.amount),i.receiver_name!==void 0&&(n.receiver_name=i.receiver_name),i.receiver_phone!==void 0&&(n.receiver_phone=i.receiver_phone),i.receiver_address!==void 0&&(n.receiver_address=i.receiver_address),i.item_id!==void 0&&(n.item_id=i.item_id),i.quantity!==void 0&&(n.quantity=i.quantity),i.item_title!==void 0&&(n.item_title=i.item_title),await De(i.order_id,n),r(!1),C(null),await m()}catch(n){console.error("更新订单失败:",n),alert("更新失败,请重试")}},[i,m]),E=a.useCallback(async n=>{M(n);try{const v=await Ae(n);v.success?await m():alert(v.message||"同步失败")}catch(v){console.error("同步订单失败:",v),alert(Q(v,"同步失败,请重试"))}finally{M(null)}},[m]),I=a.useCallback(async n=>{if(confirm("确认删除该订单吗?删除后无法恢复。")){k(n);try{await Re(n),s.length===1&&t>1?g(v=>v-1):await m()}catch(v){console.error("删除订单失败:",v),alert(Q(v,"删除失败,请重试")),await m()}finally{k(null)}}},[m,s.length,t,g]),z=a.useCallback(()=>p(!1),[]),B=a.useCallback(()=>r(!1),[]),L=a.useCallback(()=>{O(!1),N(null)},[]);return{showDetailModal:u,selectedOrder:b,showEditModal:y,editingOrder:i,showShipModal:$,shipOrderId:S,shipLoading:A,shipResult:o,syncingOrderId:f,deletingOrderId:D,handleSync:P,handleShip:U,executeShip:V,handleViewDetail:q,handleEdit:d,handleSaveEdit:j,updateEditingOrder:x,handleSyncSingle:E,handleDelete:I,closeDetailModal:z,closeEditModal:B,closeShipModal:L}},se=({status:s})=>{const t={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"},c={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${t[s]||t.cancelled}`,children:c[s]||s})},Je=()=>{const s=Te(),t=qe(s.loadOrders),{orders:c,accounts:h,filter:g,setFilter:m,accountFilter:u,setAccountFilter:p,searchText:b,setSearchText:_,page:y,setPage:r,totalPages:i,loading:C,loadOrders:$,accountName:O,accountNickname:S,getItemNameById:w}=s,A=ze({orders:c,page:y,accountFilter:u,filter:g,setPage:r,loadOrders:$}),{showDetailModal:F,selectedOrder:o,showEditModal:N,editingOrder:f,showShipModal:M,shipLoading:D,shipResult:k,syncingOrderId:P,deletingOrderId:U,handleSync:V,handleShip:q,executeShip:d,handleViewDetail:x,handleEdit:j,handleSaveEdit:E,updateEditingOrder:I,handleSyncSingle:z,handleDelete:B,closeDetailModal:L,closeEditModal:n,closeShipModal:v}=A,G=l=>{m(l),r(1),_("")},R=l=>{p(l),r(1)},le=l=>{_(l),r(1)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"订单中心"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"查看所有闲鱼交易记录与状态。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:$,className:"p-3 rounded-2xl bg-white border border-gray-100 text-gray-600 hover:bg-gray-50 hover:text-black transition-colors shadow-sm",children:e.jsx(H,{className:`w-5 h-5 ${C?"animate-spin":""}`})}),e.jsxs("button",{onClick:t.openImportModal,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors text-sm flex items-center gap-2 shadow-lg",children:[e.jsx(ie,{className:"w-4 h-4"}),"插入订单"]}),e.jsxs("button",{onClick:V,className:"ios-btn-primary px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 text-sm flex items-center gap-2",children:[e.jsx(Y,{className:"w-5 h-5"}),"一键同步订单"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsx(Se,{filter:g,onFilterChange:G,accountFilter:u,onAccountFilterChange:R,accounts:h,accountName:O,searchText:b,onSearchChange:le}),e.jsx("div",{className:"overflow-x-auto min-h-[400px]",children:e.jsxs("table",{className:"w-full text-left border-collapse table-fixed",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"px-6 py-5",style:{width:"28%"},children:"订单信息"}),e.jsx("th",{className:"px-6 py-5",style:{width:"26%"},children:"买家信息"}),e.jsx("th",{className:"px-6 py-5",style:{width:"11%"},children:"实付金额"}),e.jsx("th",{className:"px-6 py-5",style:{width:"13%"},children:"当前状态"}),e.jsx("th",{className:"px-6 py-5 text-right",style:{width:"22%"},children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:c.map(l=>e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-6 py-5",children:e.jsxs("div",{className:"flex items-center gap-5",children:[e.jsx("div",{className:"w-14 h-14 rounded-xl bg-gray-100 overflow-hidden shadow-sm border border-gray-100 flex-shrink-0",children:l.item_image?e.jsx("img",{src:l.item_image,alt:"",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-gray-300",children:e.jsx(Z,{})})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 line-clamp-1 text-sm",children:w(l.cookie_id,l.item_id,l.item_title)}),e.jsxs("div",{className:"mt-1 flex w-fit min-w-0 max-w-full items-center gap-1 rounded-md bg-blue-50 px-2 py-1 text-[10px] font-extrabold text-blue-700",title:S(l.cookie_id),children:[e.jsx(te,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"min-w-0 truncate whitespace-nowrap",children:S(l.cookie_id)})]}),e.jsxs("div",{className:"text-xs text-gray-500 mt-1 font-medium",children:["订单ID: ",l.order_id]}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",l.quantity," • ",ee(l.created_at)]})]})]})}),e.jsx("td",{className:"px-6 py-5",children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("div",{className:"text-xs text-gray-500",children:"买家ID"}),e.jsx("div",{className:"text-sm font-bold text-gray-800",children:l.buyer_id}),l.receiver_name&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"收货人"}),e.jsx("div",{className:"text-xs text-gray-600",children:l.receiver_name})]}),l.receiver_phone&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"联系电话"}),e.jsx("div",{className:"text-xs text-gray-600 font-mono",children:l.receiver_phone})]}),l.receiver_address&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"收货地址"}),e.jsx("div",{className:"text-xs text-gray-600 line-clamp-1",children:l.receiver_address})]})]})}),e.jsx("td",{className:"px-6 py-5 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:l.amount?`¥${l.amount}`:e.jsx("span",{className:"text-xs text-amber-600 font-bold",children:"待获取"})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx(se,{status:l.status})}),e.jsxs("td",{className:"px-6 py-5 text-right",children:[l.status==="pending_ship"&&e.jsx("button",{onClick:(()=>q(l.order_id)),className:"mr-2 text-white bg-black hover:bg-gray-800 shadow-lg shadow-gray-200 text-xs font-bold px-3 py-2 rounded-xl transition-all active:scale-95",children:"立即发货"}),e.jsx("a",{href:`https://www.goofish.com/order-detail?orderId=${l.order_id}&role=seller`,target:"_blank",rel:"noopener noreferrer",className:"mr-2 inline-flex text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看闲鱼详情",children:e.jsx(ce,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>x(l)),className:"mr-2 text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看详情",children:e.jsx(oe,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>j(l)),className:"mr-2 text-gray-400 hover:text-black p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"编辑订单",children:e.jsx(de,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>z(l.order_id)),disabled:P===l.order_id,className:"mr-2 text-gray-400 hover:text-green-600 p-2 rounded-xl hover:bg-green-50 transition-colors disabled:opacity-50",title:"同步订单",children:e.jsx(H,{className:`w-4 h-4 ${P===l.order_id?"animate-spin":""}`})}),e.jsx("button",{onClick:(()=>B(l.order_id)),disabled:U===l.order_id,className:"text-gray-400 hover:text-red-500 p-2 rounded-xl hover:bg-red-50 transition-colors disabled:opacity-50",title:"删除订单",children:e.jsx(xe,{className:"w-4 h-4"})})]})]},l.id))})]})}),e.jsxs("div",{className:"p-4 border-t border-gray-50 flex items-center justify-between bg-white",children:[e.jsxs("div",{className:"text-sm text-gray-500 font-medium pl-2",children:["第 ",y," 页 / 共 ",i," 页"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{disabled:y<=1,onClick:(()=>r(l=>l-1)),"aria-label":"上一页",className:"p-2.5 rounded-xl bg-gray-50 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 transition-colors",children:e.jsx(me,{className:"w-5 h-5"})}),e.jsx("button",{disabled:y>=i,onClick:(()=>r(l=>l+1)),"aria-label":"下一页",className:"p-2.5 rounded-xl bg-gray-50 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 transition-colors",children:e.jsx(ue,{className:"w-5 h-5"})})]})]})]}),F&&o&&J.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"订单详情"}),e.jsx("button",{onClick:L,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(W,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"订单信息"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"订单号"}),e.jsx("div",{className:"font-mono text-sm font-bold text-gray-900",children:o.order_id})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"所属账号"}),e.jsx("div",{className:"truncate whitespace-nowrap text-sm font-bold text-blue-700",title:S(o.cookie_id),children:S(o.cookie_id)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"状态"}),e.jsx(se,{status:o.status})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"实付金额"}),e.jsx("div",{className:"text-lg font-extrabold text-gray-900",children:o.amount?`¥${o.amount}`:"待获取"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"数量"}),e.jsx("div",{className:"font-bold text-gray-900",children:o.quantity})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"创建时间"}),e.jsx("div",{className:"text-sm font-medium text-gray-700",children:ee(o.created_at)})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"商品信息"}),e.jsxs("div",{className:"p-4 bg-gray-50 rounded-xl flex items-center gap-4",children:[o.item_image&&e.jsx("img",{src:o.item_image,alt:"",className:"w-20 h-20 rounded-xl object-cover border border-gray-200"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-bold text-gray-900 mb-1",children:w(o.cookie_id,o.item_id,o.item_title)}),e.jsxs("div",{className:"text-sm text-gray-500",children:["商品ID: ",o.item_id]}),o.item_price&&e.jsxs("div",{className:"text-sm text-gray-500 mt-1",children:["标价: ¥",o.item_price]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"买家信息"}),e.jsxs("div",{className:"p-4 bg-gray-50 rounded-xl space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"买家ID"}),e.jsx("div",{className:"font-bold text-gray-900",children:o.buyer_id})]}),o.receiver_name&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"收货人"}),e.jsx("div",{className:"font-medium text-gray-700",children:o.receiver_name})]}),o.receiver_phone&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"联系电话"}),e.jsx("div",{className:"font-mono text-sm text-gray-700",children:o.receiver_phone})]}),o.receiver_address&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"收货地址"}),e.jsx("div",{className:"text-sm text-gray-700",children:o.receiver_address})]})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:L,className:"flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:"关闭"}),o.status==="pending_ship"&&e.jsx("button",{onClick:(()=>{L(),q(o.order_id)}),className:"flex-1 px-6 py-3 rounded-xl ios-btn-primary font-bold shadow-lg shadow-blue-200",children:"立即发货"})]})})]})}),document.body),e.jsx(Ee,{...t}),M&&J.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"480px"},children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"立即发货"}),e.jsx("button",{onClick:v,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(W,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-4",children:[e.jsx("p",{className:"text-sm text-gray-600",children:"请选择发货方式:"}),e.jsx("button",{onClick:(()=>d("status_only")),disabled:D,className:"w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-gray-400 hover:bg-gray-50 transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(Y,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:"仅修改闲鱼发货状态"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 leading-relaxed",children:'不实际扣除或发送卡券,仅在闲鱼平台将订单标记为"已发货"。 适用于已经给客户发过货、只是忘记在闲鱼修改状态的情况。'})]})]})}),e.jsx("button",{onClick:(()=>d("full_delivery")),disabled:D,className:"w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-brand hover:bg-blue-50 transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(Z,{className:"w-5 h-5 text-blue-700"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:"完整发货(匹配卡券并发送)"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 leading-relaxed",children:"自动匹配发货规则、获取卡券、发送卡券信息给买家,并修改发货状态。 适用于订单既没有发送卡券给买家、也没有修改发货状态的情况。"})]})]})}),D&&e.jsxs("div",{className:"flex items-center justify-center gap-2 py-3",children:[e.jsx(H,{className:"w-4 h-4 animate-spin text-gray-500"}),e.jsx("span",{className:"text-sm text-gray-500",children:"正在处理中..."})]}),k&&e.jsxs("div",{className:`p-3 rounded-xl text-sm ${k.success?"bg-green-50 text-green-800":"bg-red-50 text-red-800"}`,children:[k.success?"✓ ":"✗ ",k.message]})]}),e.jsx("div",{className:"modal-footer",children:e.jsx("button",{onClick:v,className:"w-full px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:k!=null&&k.success?"完成":"取消"})})]})}),document.body),N&&f&&J.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑订单"}),e.jsx("button",{onClick:n,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(W,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"订单号"}),e.jsx("input",{type:"text",value:f.order_id,disabled:!0,className:"w-full ios-input px-4 py-3 rounded-xl bg-gray-50 text-gray-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"订单状态"}),e.jsxs("select",{value:f.status,onChange:(l=>I({status:l.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"processing",children:"处理中"}),e.jsx("option",{value:"pending_ship",children:"待发货"}),e.jsx("option",{value:"shipped",children:"已发货"}),e.jsx("option",{value:"completed",children:"已完成"}),e.jsx("option",{value:"cancelled",children:"已取消"}),e.jsx("option",{value:"refunding",children:"退款中"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"买家ID"}),e.jsx("input",{type:"text",value:f.buyer_id,onChange:(l=>I({buyer_id:l.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"实付金额"}),e.jsx("input",{type:"number",value:f.amount,onChange:(l=>I({amount:l.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"收货人"}),e.jsx("input",{type:"text",value:f.receiver_name||"",onChange:(l=>I({receiver_name:l.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"联系电话"}),e.jsx("input",{type:"text",value:f.receiver_phone||"",onChange:(l=>I({receiver_phone:l.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"收货地址"}),e.jsx("textarea",{value:f.receiver_address||"",onChange:(l=>I({receiver_address:l.target.value})),rows:2,className:"w-full ios-input px-4 py-3 rounded-xl resize-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"商品标题"}),e.jsx("input",{type:"text",value:f.item_title||"",onChange:(l=>I({item_title:l.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),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",children:"取消"}),e.jsxs("button",{onClick:E,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(he,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body)]})};export{Je as default}; diff --git a/internal/webui/static/assets/Rules-D79nNK3r.js b/internal/webui/static/assets/Rules-BplaKbZv.js similarity index 99% rename from internal/webui/static/assets/Rules-D79nNK3r.js rename to internal/webui/static/assets/Rules-BplaKbZv.js index 82120e5..2e7ce2d 100644 --- a/internal/webui/static/assets/Rules-D79nNK3r.js +++ b/internal/webui/static/assets/Rules-BplaKbZv.js @@ -1 +1 @@ -import{j as e,r as o,b as De}from"./react-vendor-C_od1ZSF.js";import{k as Je,ae as it,af as vt,m as Nt,R as Te,N as Ye,Z as He,x as wt,w as et,I as kt,a1 as Ct,X as ke,V as ze,F as Ce,h as St,g as Rt,a6 as At,ag as $t,r as tt,ah as Mt}from"./icons-vendor-CvzvbbIV.js";import{g as Z,p as Ge,a as fe,d as Ke}from"./index-CFzx5gQT.js";import{o as Ae,c as Ue}from"./contract-COFcZjyb.js";const Ee=(t,a)=>t.allowed_resolutions.includes(a),Pt=(t,a)=>({runs:t.runs.filter(i=>!a||i.cookie_id===a),pending_tasks:t.pending_tasks.filter(i=>!a||i.cookie_id===a)}),Lt=t=>({external_result_unknown:"外部动作结果未知",invalid_snapshot:"历史数据无法恢复",rule_unavailable:"规则不可用",partial_failure:"部分动作失败",execution_failed:"动作执行失败"})[t]||"自动化异常",It=({runs:t,pendingTasks:a,onResolveRun:i,onResolveDeferredTask:u})=>e.jsxs("section",{className:"rounded-2xl border border-red-200 bg-red-50 p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Je,{className:"w-5 h-5 text-red-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-black text-red-900",children:"需要人工处理的自动化任务"}),e.jsx("p",{className:"text-sm text-red-700 mt-1",children:"请先在闲鱼聊天、订单或商品列表中核对真实结果,再选择继续或重试。"})]})]}),e.jsxs("div",{className:"space-y-3",children:[t.map(r=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",r.cookie_id," · 订单 ",r.order_id||"-"," · 已记录发送 ",r.sent_count," 条"]}),e.jsx("div",{className:"text-xs font-bold text-red-800 mt-1",children:Lt(r.issue_kind)}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 shrink-0",children:[Ee(r,"continue")&&e.jsx("button",{onClick:(()=>i(r.id,"continue")),className:"px-3 py-2 rounded-lg bg-emerald-100 text-emerald-800 text-xs font-bold",children:"已执行,继续下一步"}),Ee(r,"retry")&&e.jsx("button",{onClick:(()=>i(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"未执行,安全重试"}),Ee(r,"cancel")&&e.jsx("button",{onClick:(()=>i(r.id,"cancel")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"终止"})]})]},`run-${r.id}`)),a.map(r=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",r.cookie_id," · 延迟任务重试已达 ",r.attempt_count," 次"]}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsx("button",{onClick:(()=>u(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"重新入队"}),e.jsx("button",{onClick:(()=>u(r.id,"dismiss")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"忽略"})]})]},`task-${r.id}`))]})]}),Ft=async t=>Z("/api/v1/accounts/details",void 0,t),ot=async t=>Z("/api/v1/cards",void 0,t),dt=async(t,a)=>Z("/api/v1/items",void 0,a),ct=t=>t.map(a=>{var i,u;return{id:String(a.id),name:a.name||"",trigger_type:a.trigger_type||"order_paid",item_keyword:a.item_title||a.item_id||"",cookie_id:a.cookie_id||"",item_id:a.item_id||"",item_title:a.item_title||"",card_group_id:Number(((i=(a.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:i.card_id)||0),card_group_name:((u=(a.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:u.card_name)||"",priority:a.priority||100,enabled:a.enabled||!1,config_json:a.config_json||"{}",actions:(a.actions||[]).map(r=>({id:r.id?String(r.id):void 0,action_type:r.action_type,card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),message_template:r.message_template||"",delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}",enabled:r.enabled!==!1,sort_order:Number(r.sort_order||0)})),variants:(a.actions||[]).filter(r=>r.action_type==="send_card").map(r=>{let y={};try{y=JSON.parse(r.config_json||"{}")}catch{}return{id:r.id?String(r.id):void 0,spec_name:y.spec_name||"",spec_value:y.spec_value||"",card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),enabled:r.enabled!==!1,delay_override:y.delay_override===!0,delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}"}})}}),Dt=async()=>{const t=await Z("/api/v1/automation-rules"),a=Ue(t,["data","rules","items"]);return ct(a)},Tt=async({cookieId:t,triggerType:a,enabled:i,search:u,page:r=1,pageSize:y=10}={})=>{const A=await Z("/api/v1/automation-rules",{page:r,page_size:y,cookie_id:t||void 0,trigger_type:a||void 0,enabled:i,search:(u==null?void 0:u.trim())||void 0}),C=Ae(A,["data","result"])||{},m=ct(Ue(A,["data","rules","items"]));return{success:!0,data:m,total:Number(C.total??m.length),page:Number(C.page??r),page_size:Number(C.page_size??y),total_pages:Number(C.total_pages??(m.length?1:0)),trigger_counts:Object.fromEntries(Object.entries(C.trigger_counts||{}).map(([I,T])=>[I,Number(T)]))}},zt=(t,a)=>{if(t!=="order_paid")return a.map((r,y)=>({...r,sort_order:r.sort_order||y+1}));const i=a.filter(r=>r.action_type==="send_card").map((r,y)=>({...r,sort_order:y+1})),u=a.filter(r=>r.action_type!=="send_card"&&r.action_type!=="confirm_shipment");return[...i,...u.map((r,y)=>({...r,sort_order:i.length+y+1})),{action_type:"confirm_shipment",enabled:!0,sort_order:i.length+u.length+1}]},st=async t=>{const a=t.trigger_type||"order_paid",u=[{order_paid:"付款后自动发货",buyer_reviewed:"评价后发送赠品",review_missing_timeout:"超时未评价求评价"}[a]||"自动化规则",t.item_title||t.item_id||t.cookie_id||""].filter(Boolean).join(" - "),r=(t.actions||[]).filter(m=>m.action_type!=="send_card"&&m.action_type!=="confirm_shipment"),y=t.variants&&t.variants.length>0?[...t.variants.map((m,I)=>({action_type:"send_card",card_id:m.card_id,delivery_count:m.delivery_count||1,enabled:m.enabled!==!1,sort_order:I+1,delay_seconds:m.delay_seconds||0,config_json:JSON.stringify({spec_name:m.spec_name||"",spec_value:m.spec_value||"",delay_override:m.delay_override===!0})})),...r]:t.actions&&t.actions.length>0?t.actions:[{action_type:"send_card",card_id:t.card_group_id||0,delivery_count:1,enabled:!0,sort_order:1}],A=zt(a,y),C={cookie_id:t.cookie_id||"",item_id:t.item_id||"",name:(t.name||"").trim()||u||"自动化规则",trigger_type:a,enabled:t.enabled??!0,priority:t.priority||100,config_json:t.config_json||"{}",actions:A.map((m,I)=>({action_type:m.action_type,card_id:m.card_id||0,delivery_count:m.delivery_count||1,message_template:m.message_template||"",delay_seconds:m.delay_seconds||0,config_json:m.config_json||"{}",enabled:m.enabled!==!1,sort_order:m.sort_order||I+1}))};return t.id?Ge(`/api/v1/automation-rules/${t.id}`,C):fe("/api/v1/automation-rules",C)},Et=async t=>Ke(`/api/v1/automation-rules/${t}`),Ot=async()=>{const t=await Z("/api/v1/automation-issues"),a=Ae(t,["data","result"])||{};return{runs:Array.isArray(a==null?void 0:a.runs)?a.runs:[],pending_tasks:Array.isArray(a==null?void 0:a.pending_tasks)?a.pending_tasks:[]}},qt=async(t,a)=>fe(`/api/v1/automation-runs/${t}/resolve`,{resolution:a}),Vt=async(t,a)=>fe(`/api/v1/automation-pending-tasks/${t}/resolve`,{resolution:a}),Bt=t=>({id:String((t==null?void 0:t.id)||""),keyword:(t==null?void 0:t.keyword)||"",reply:(t==null?void 0:t.reply)||"",item_id:(t==null?void 0:t.item_id)||"",type:(t==null?void 0:t.type)==="image"?"image":"text",image_url:(t==null?void 0:t.image_url)||""}),Jt=async t=>{const a=await Z(`/api/v1/reply-rules/${t}/typed`);return Ue(a,["data","items","rules"]).map(Bt)},Gt=async t=>t?(await Jt(t)).map(i=>({id:i.id,keyword:i.keyword||"",reply_content:i.reply||"",match_type:"fuzzy",enabled:!0,item_id:i.item_id||"",type:i.type==="image"?"image":"text",image_url:i.image_url||""})):[],Kt=async(t,a)=>{const i=t.type||"text",u={keyword:t.keyword||"",reply:i==="text"&&t.reply_content||"",item_id:t.item_id||"",type:i,image_url:i==="image"&&t.image_url||""};return t.id?Ge(`/api/v1/reply-rules/${a}/typed/${t.id}`,u):fe(`/api/v1/reply-rules/${a}/items`,u)},Ut=async(t,a)=>Ke(`/api/v1/reply-rules/${a}/typed/${t}`),at=async()=>{const t=await Z("/api/v1/default-replies");return Ae(t,["data","replies","items"])||{}},Wt=async t=>{const a=await Z(`/api/v1/default-replies/${t}`),i=Ae(a,["data","result"])||{};return{cookie_id:t,enabled:i.enabled||!1,reply_content:i.reply_content||"",reply_once:i.reply_once||!1,reply_image_url:i.reply_image_url||""}},Zt=async(t,a)=>Ge(`/api/v1/default-replies/${t}`,{enabled:a.enabled??!1,reply_content:a.reply_content||"",reply_once:a.reply_once??!1,reply_image_url:a.reply_image_url||""}),Xt=async t=>Ke(`/api/v1/default-replies/${t}`),Qt=async t=>fe(`/api/v1/default-replies/${t}/clear-records`,{}),Oe=()=>({submitting:!1,result:"idle"}),qe=t=>t.submitting?t:{submitting:!0,result:"idle"},Ve=(t,a)=>({submitting:!1,result:a?"success":"failure"}),rt=t=>t+1,Be=(t,a,i,u)=>t===a&&i===u,Yt=t=>{const[a,i]=o.useState([]),[u,r]=o.useState({runs:[],pending_tasks:[]}),[y,A]=o.useState([]),[C,m]=o.useState({}),[I,T]=o.useState([]),[J,w]=o.useState([]),[G,F]=o.useState([]),[v,X]=o.useState(!1),q=o.useRef(0),re=o.useRef(0),[Q,K]=o.useState(0),[le,Y]=o.useState(0),[V,H]=o.useState({}),U=o.useCallback(async()=>{const P=Promise.all([Ft(),ot(),dt(),at()]),[_,j,D,ee]=await P;T(_),w(j),F(D),m(ee),t.setSelectedAccountId(ne=>{var E;return ne||((E=_[0])==null?void 0:E.id)||""})},[t.setSelectedAccountId]),n=o.useCallback(async()=>{var ee;const P=rt(q.current);q.current=P;const _=Ot().catch(ne=>(console.warn("加载自动化异常列表失败,不阻断规则展示",ne),null)),j=await Tt({cookieId:t.selectedAccountId||void 0,triggerType:t.automationTriggerFilter,enabled:t.automationStatusFilter==="all"?void 0:t.automationStatusFilter==="enabled",search:t.debouncedAutomationSearch,page:t.automationPage,pageSize:t.automationPageSize});if(!Be(P,q.current,t.selectedAccountId,t.selectedAccountId))return;i(j.data),K(j.total),Y(j.total_pages),H(j.trigger_counts||{}),j.page!==t.automationPage&&((ee=t.onAutomationPageChange)==null||ee.call(t,j.page));const D=await _;Be(P,q.current,t.selectedAccountId,t.selectedAccountId)&&D&&r(D)},[t.automationPage,t.automationPageSize,t.automationStatusFilter,t.automationTriggerFilter,t.debouncedAutomationSearch,t.onAutomationPageChange,t.selectedAccountId]),$=o.useCallback(async()=>{const P=rt(re.current);re.current=P;const _=t.selectedAccountId;if(A([]),!_)return;const j=await Gt(_);Be(P,re.current,_,t.selectedAccountId)&&A(j)},[t.selectedAccountId]),R=o.useCallback(async()=>{m(await at())},[]),z=o.useCallback(async()=>{X(!0);try{t.activeTab==="automation"?await n():t.activeTab==="reply"?await $():await R()}finally{X(!1)}},[n,R,$,t.activeTab]);return{automationRules:a,automationIssues:u,replyRules:y,defaultReplies:C,accounts:I,cards:J,items:G,automationTotal:Q,automationTotalPages:le,automationTriggerCounts:V,loading:v,setLoading:X,setAutomationRules:i,setCards:w,setItems:F,loadReferenceData:U,loadAutomationRules:n,loadReplyRules:$,loadDefaultReplies:R,refresh:z}},ae={order_paid:{label:"付款后自动发货",shortLabel:"自动发货",description:"闲鱼付款系统卡片进入自动化中心后,先发送卡密,成功后再确认发货。",flow:["付款系统卡片","匹配商品/规格","发送卡密","确认发货"],accent:"blue",icon:Nt},buyer_reviewed:{label:"评价后发送赠品",shortLabel:"评价赠品",description:"闲鱼评价系统卡片进入自动化中心后,给买家发送赠品卡密。",flow:["评价系统卡片","匹配商品/规格","发送赠品"],accent:"emerald",icon:vt},review_missing_timeout:{label:"超时未评价求评价",shortLabel:"求评价",description:"计划任务扫描已发货未评价订单,到期后发送求评价文案。",flow:["计划任务扫描","已发货未评价","达到等待时间","发送提醒"],accent:"amber",icon:it}},Se=["order_paid","buyer_reviewed","review_missing_timeout"],Ht="亲,商品使用满意的话,麻烦给个评价,谢谢~",he=()=>({spec_name:"",spec_value:"",card_id:0,delivery_count:1,enabled:!0,delay_override:!1,delay_seconds:0}),mt=t=>{if(!t)return{};try{const a=JSON.parse(t);return a&&typeof a=="object"&&!Array.isArray(a)?a:{}}catch{return{}}},ce=(t,a={})=>{const i=mt(t);return JSON.stringify({after_shipped_hours:Number(i.after_shipped_hours||72),repeat_interval_hours:Number(i.repeat_interval_hours||24),max_attempts:Number(i.max_attempts||1),...a})},ye=(t,a)=>{var u;const i=((u=ae[t])==null?void 0:u.label)||"自动化规则";return a?`${i} - ${a}`:i},lt=t=>{const a=(t||"").trim();return a?Object.values(ae).some(i=>a===i.label||a.startsWith(`${i.label} -`)):!0},_e=(t,a=0)=>{if(t==="review_missing_timeout")return[{action_type:"send_text",message_template:Ht,enabled:!0,sort_order:1}];const i={action_type:"send_card",card_id:a,delivery_count:1,enabled:!0,sort_order:1};return t==="order_paid"?[i,{action_type:"confirm_shipment",enabled:!0,sort_order:2}]:[i]},es=t=>{var i,u;if(t.trigger_type==="review_missing_timeout")return((u=(i=t.actions)==null?void 0:i.find(r=>r.action_type==="send_text"))==null?void 0:u.message_template)||"发送求评价文案";const a=(t.actions||[]).filter(r=>r.action_type==="send_card");return a.length?a.map(r=>r.card_name||`卡密 ${r.card_id}`).join(" / "):"未配置卡密库存"},nt=(t,a=!1)=>{const i={blue:a?"border-blue-500 bg-blue-50 text-blue-700":"border-blue-100 bg-blue-50/60 text-blue-700 hover:border-blue-300",emerald:a?"border-emerald-500 bg-emerald-50 text-emerald-700":"border-emerald-100 bg-emerald-50/60 text-emerald-700 hover:border-emerald-300",amber:a?"border-amber-500 bg-amber-50 text-amber-700":"border-amber-100 bg-amber-50/60 text-amber-700 hover:border-amber-300"};return i[t]||i.blue},ts=t=>t?"bg-emerald-100 text-emerald-700":"bg-gray-200 text-gray-500",Re=t=>(t==null?void 0:t.nickname)||(t==null?void 0:t.remark)||(t==null?void 0:t.id)||"未知账号",ss=t=>t===!0||t===1||t==="1",as=({selectedAccountId:t,setSelectedAccountId:a,setActiveTab:i,items:u,setAutomationRules:r,setCards:y,setItems:A,setLoading:C,loadAutomationRules:m,loadReferenceData:I,loadReplyRules:T,loadDefaultReplies:J,initialDeliveryTarget:w,onDeliveryTargetHandled:G})=>{var xe;const[F,v]=o.useState(!1),[X,q]=o.useState(!1),[re,Q]=o.useState(!1),[K,le]=o.useState(Oe),[Y,V]=o.useState(Oe),[H,U]=o.useState(Oe),[n,$]=o.useState(null),[R,z]=o.useState(null),[M,P]=o.useState({cookie_id:"",enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""}),_=o.useMemo(()=>n!=null&&n.cookie_id&&n.item_id?u.find(l=>l.cookie_id===n.cookie_id&&l.item_id===n.item_id):void 0,[n==null?void 0:n.cookie_id,n==null?void 0:n.item_id,u]),j=ss(_==null?void 0:_.is_multi_spec),D=(n==null?void 0:n.trigger_type)||"order_paid",ee=ae[D],ne=mt(n==null?void 0:n.config_json),E=(xe=n==null?void 0:n.variants)!=null&&xe.length?n.variants:[he()],W=o.useCallback((l="order_paid",d=t,b="")=>{const p=u.find(N=>N.cookie_id===d&&N.item_id===b),h=(p==null?void 0:p.item_title)||b;return{name:ye(l,h),trigger_type:l,cookie_id:d,item_id:b,item_title:(p==null?void 0:p.item_title)||"",item_keyword:h,card_group_id:0,priority:100,enabled:!0,config_json:l==="review_missing_timeout"?ce():"{}",actions:_e(l),variants:l==="review_missing_timeout"?[]:[he()]}},[u,t]),ue=o.useCallback(l=>{var b,p;const d=l.trigger_type||"order_paid";$({...l,trigger_type:d,config_json:d==="review_missing_timeout"?ce(l.config_json):l.config_json||"{}",actions:(b=l.actions)!=null&&b.length?l.actions.map(h=>({...h})):_e(d,l.card_group_id),variants:(p=l.variants)!=null&&p.length?l.variants.map(h=>({...h})):d==="review_missing_timeout"?[]:[he()]}),v(!0)},[]);o.useEffect(()=>{if(!w)return;let l=!1;return(async()=>{i("automation"),a(w.cookieId),C(!0);try{const[b,p,h]=await Promise.all([Dt(),dt(),ot().catch(f=>(console.warn("加载卡密库存失败,不阻断打开自动化规则",f),[]))]);if(l)return;r(b),A(p),y(h);const N=b.find(f=>f.cookie_id===w.cookieId&&f.item_id===w.itemId&&f.trigger_type==="order_paid");if(N)ue(N);else{const f=p.find(B=>B.cookie_id===w.cookieId&&B.item_id===w.itemId);$({...W("order_paid",w.cookieId,w.itemId),item_title:(f==null?void 0:f.item_title)||"",item_keyword:(f==null?void 0:f.item_title)||w.itemId,name:ye("order_paid",(f==null?void 0:f.item_title)||w.itemId)}),v(!0)}}catch(b){console.error("打开商品自动化规则失败",b),alert("无法加载该商品的自动化规则")}finally{l||(C(!1),G==null||G())}})(),(()=>{l=!0})},[W,w,G,ue,i,r,y,A,C,a]);const $e=o.useCallback((l="order_paid")=>{if(!t){alert("请先选择账号");return}$(W(l)),v(!0)},[W,t]),je=o.useCallback(l=>{var p,h,N,f,B;if(!n)return;const d=((h=(p=n.variants)==null?void 0:p.find(se=>se.card_id))==null?void 0:h.card_id)||((f=(N=n.actions)==null?void 0:N.find(se=>se.action_type==="send_card"))==null?void 0:f.card_id)||n.card_group_id||0,b=(_==null?void 0:_.item_title)||n.item_title||n.item_id||"";$({...n,trigger_type:l,name:lt(n.name)?ye(l,b):n.name,card_group_id:d,config_json:l==="review_missing_timeout"?ce(n.config_json):"{}",actions:_e(l,d),variants:l==="review_missing_timeout"?[]:(B=n.variants)!=null&&B.length?n.variants:[{...he(),card_id:d}]})},[n,_]),Me=o.useCallback(l=>{if(!n)return;const d=u.find(p=>p.cookie_id===(n.cookie_id||t)&&p.item_id===l),b=(d==null?void 0:d.item_title)||l;$({...n,item_id:l,item_title:(d==null?void 0:d.item_title)||"",item_keyword:b,name:lt(n.name)?ye(D,b):n.name})},[D,n,u,t]),pe=o.useCallback((l,d)=>{var p;if(!n)return;const b=E.map((h,N)=>N===l?{...h,...d}:h);$({...n,variants:b,card_group_id:((p=b[0])==null?void 0:p.card_id)||0})},[E,n]),Pe=o.useCallback(()=>{if(!n)return;const l=E[E.length-1];$({...n,variants:[...E,{...he(),spec_name:j&&(l==null?void 0:l.spec_name)||"",spec_value:j&&(l==null?void 0:l.spec_value)||""}]})},[E,n,j]),ve=o.useCallback(async()=>{var h,N,f,B,se;if(!n||K.submitting)return;const l=n.trigger_type||"order_paid";if(!n.cookie_id)return alert("请选择账号");const d=(h=n.variants)!=null&&h.length?n.variants:[];if(l!=="review_missing_timeout"){if(!d.length||d.some(k=>!k.card_id))return alert(l==="buyer_reviewed"?"请选择评价赠品卡密库存":"请选择发货卡密库存");if(j&&d.some(k=>!k.spec_name.trim()||!k.spec_value.trim()))return alert("多规格商品必须填写每一行的规格名称和规格值")}if(l==="review_missing_timeout"&&!(((f=(N=n.actions)==null?void 0:N.find(Le=>Le.action_type==="send_text"))==null?void 0:f.message_template)||"").trim())return alert("请填写求评价文案");const b=l==="review_missing_timeout"?[]:d.map(k=>({...k,spec_name:j?k.spec_name.trim():"",spec_value:j?k.spec_value.trim():"",delivery_count:Math.max(1,Number(k.delivery_count)||1),enabled:k.enabled!==!1}));le(qe(K));let p=!1;try{await st({...n,trigger_type:l,name:(n.name||"").trim()||ye(l,(_==null?void 0:_.item_title)||n.item_id||""),config_json:l==="review_missing_timeout"?ce(n.config_json):n.config_json||"{}",actions:(B=n.actions)!=null&&B.length?n.actions:_e(l,((se=b[0])==null?void 0:se.card_id)||n.card_group_id||0),variants:b}),v(!1),await Promise.all([m(),I()]),alert("保存成功"),p=!0}catch(k){console.error("保存自动化规则失败:",k),alert("保存失败:"+k.message)}finally{le(k=>Ve(k,p))}},[K,n,j,m,I,_]),g=o.useCallback(async l=>{if(confirm("确定删除该自动化规则吗?"))try{await Et(l),await m(),alert("删除成功")}catch(d){alert("删除失败:"+d.message)}},[m]),O=o.useCallback(async l=>{try{await st({...l,enabled:!l.enabled}),await m()}catch(d){alert("操作失败:"+d.message)}},[m]),S=o.useCallback(async(l,d)=>{if(confirm(d==="continue"?"确认外部动作已经执行成功,并跳到下一步吗?":d==="retry"?"确认外部动作没有执行,可以安全重试吗?错误判断可能造成重复发送。":"确认终止该自动化运行吗?"))try{await qt(l,d),await m()}catch(p){alert("处理失败:"+p.message)}},[m]),te=o.useCallback(async(l,d)=>{if(confirm(d==="retry"?"确认重新执行该任务吗?":"确认忽略并删除该异常任务吗?"))try{await Vt(l,d),await m()}catch(b){alert("处理失败:"+b.message)}},[m]),L=o.useCallback(()=>{if(!t)return alert("请先选择账号");z({keyword:"",reply_content:"",image_url:"",item_id:"",type:"text",match_type:"fuzzy",enabled:!0}),q(!0)},[t]),ie=o.useCallback(async()=>{var b,p,h;if(!R||!t||Y.submitting)return;const l=R.type==="image"?!!((b=R.image_url)!=null&&b.trim()):!!((p=R.reply_content)!=null&&p.trim());if(!((h=R.keyword)!=null&&h.trim())||!l)return alert("请填写关键词和回复内容");V(qe(Y));let d=!1;try{await Kt({...R,match_type:"fuzzy",enabled:!0},t),q(!1),await T(),alert("保存成功"),d=!0}catch(N){alert("保存失败:"+N.message)}finally{V(N=>Ve(N,d))}},[R,T,Y,t]),ge=o.useCallback(async l=>{if(!(!t||!confirm("确定删除该回复规则吗?")))try{await Ut(l,t),await T(),alert("删除成功")}catch(d){alert("删除失败:"+d.message)}},[T,t]),oe=o.useCallback(async(l=t)=>{if(!l)return alert("请先选择账号");try{const d=await Wt(l);P({cookie_id:l,enabled:d.enabled,reply_content:d.reply_content,reply_once:d.reply_once,reply_image_url:d.reply_image_url||""})}catch{P({cookie_id:l,enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""})}Q(!0)},[t]),me=o.useCallback(async()=>{if(H.submitting)return;if(!M.cookie_id)return alert("请先选择账号");if(M.enabled&&!M.reply_content.trim()&&!M.reply_image_url.trim())return alert("启用默认回复时,请填写回复内容或图片 URL");U(qe(H));let l=!1;try{await Zt(M.cookie_id,{enabled:M.enabled,reply_content:M.reply_content,reply_once:M.reply_once,reply_image_url:M.reply_image_url}),Q(!1),await J(),alert("保存成功"),l=!0}catch(d){alert("保存失败:"+d.message)}finally{U(d=>Ve(d,l))}},[M,H,J]),Ne=o.useCallback(async l=>{if(confirm("确定删除该账号默认回复吗?"))try{await Xt(l),await J(),alert("删除成功")}catch(d){alert("删除失败:"+d.message)}},[J]),be=o.useCallback(async l=>{if(confirm("确定清空该账号的默认回复记录吗?清空后可重新对所有会话使用“只回复一次”。"))try{await Qt(l),alert("清空成功")}catch(d){alert("清空失败:"+d.message)}},[]);return{showAutomationModal:F,setShowAutomationModal:v,showReplyModal:X,setShowReplyModal:q,showDefaultModal:re,setShowDefaultModal:Q,automationSubmitState:K,replySubmitState:Y,defaultReplySubmitState:H,editingAutomationRule:n,setEditingAutomationRule:$,editingReplyRule:R,setEditingReplyRule:z,defaultForm:M,setDefaultForm:P,selectedRuleItem:_,isMultiSpecRule:j,currentTrigger:D,currentMeta:ee,reviewConfig:ne,displayVariants:E,buildAutomationDraft:W,openAutomationRule:ue,openNewAutomationRule:$e,handleTriggerChange:je,handleAutomationItemChange:Me,updateVariant:pe,appendDeliveryContent:Pe,handleSaveAutomationRule:ve,handleDeleteAutomation:g,handleToggleAutomation:O,handleResolveRunIssue:S,handleResolveDeferredIssue:te,handleAddReplyRule:L,handleSaveReplyRule:ie,handleDeleteReply:ge,openDefaultReplyModal:oe,handleSaveDefaultReply:me,handleDeleteDefaultReply:Ne,handleClearDefaultReplyRecords:be}},os=({initialDeliveryTarget:t,onDeliveryTargetHandled:a})=>{var Xe,Qe;const[i,u]=o.useState("automation"),[r,y]=o.useState(""),[A,C]=o.useState(""),[m,I]=o.useState(""),[T,J]=o.useState(""),[w,G]=o.useState("all"),[F,v]=o.useState(1),[X,q]=o.useState(10),re=Yt({activeTab:i,selectedAccountId:r,automationTriggerFilter:T,automationStatusFilter:w,debouncedAutomationSearch:m,automationPage:F,automationPageSize:X,setSelectedAccountId:y,onAutomationPageChange:v}),{automationRules:Q,automationIssues:K,replyRules:le,defaultReplies:Y,accounts:V,cards:H,items:U,loading:n,setLoading:$,automationTotal:R,automationTotalPages:z,automationTriggerCounts:M,setAutomationRules:P,setCards:_,setItems:j,loadReferenceData:D,loadAutomationRules:ee,loadReplyRules:ne,loadDefaultReplies:E,refresh:W}=re,ue=as({selectedAccountId:r,setSelectedAccountId:y,setActiveTab:u,items:U,setAutomationRules:P,setCards:_,setItems:j,setLoading:$,loadAutomationRules:ee,loadReferenceData:D,loadReplyRules:ne,loadDefaultReplies:E,initialDeliveryTarget:t,onDeliveryTargetHandled:a}),{showAutomationModal:$e,setShowAutomationModal:je,showReplyModal:Me,setShowReplyModal:pe,showDefaultModal:Pe,setShowDefaultModal:ve,editingAutomationRule:g,setEditingAutomationRule:O,editingReplyRule:S,setEditingReplyRule:te,defaultForm:L,setDefaultForm:ie,selectedRuleItem:ge,isMultiSpecRule:oe,currentTrigger:me,currentMeta:Ne,reviewConfig:be,displayVariants:xe,openAutomationRule:l,openNewAutomationRule:d,handleTriggerChange:b,handleAutomationItemChange:p,updateVariant:h,appendDeliveryContent:N,handleSaveAutomationRule:f,handleDeleteAutomation:B,handleToggleAutomation:se,handleResolveRunIssue:k,handleResolveDeferredIssue:Le,handleAddReplyRule:xt,handleSaveReplyRule:ut,handleDeleteReply:pt,openDefaultReplyModal:We,handleSaveDefaultReply:gt,handleDeleteDefaultReply:bt,handleClearDefaultReplyRecords:ht}=ue;o.useEffect(()=>{const s=window.setTimeout(()=>{v(1),I(A.trim())},300);return(()=>window.clearTimeout(s))},[A]),o.useEffect(()=>{D().catch(s=>console.error("加载规则参考数据失败",s))},[D]),o.useEffect(()=>{W().catch(s=>console.error("刷新规则页面失败",s))},[W]);const Ie=o.useMemo(()=>Q.filter(s=>!r||s.cookie_id===r),[Q,r]),we=o.useMemo(()=>Pt(K,r),[K,r]),Ze=o.useMemo(()=>V.filter(s=>!r||s.id===r),[V,r]),yt=o.useMemo(()=>{if(z<=1)return[];const s=Math.max(1,Math.min(F-2,z-4)),c=Math.min(z,s+4);return Array.from({length:c-s+1},(x,de)=>s+de)},[F,z]),Fe=!!(A.trim()||T||w!=="all"),_t=()=>{C(""),I(""),J(""),G("all"),v(1)},ft=o.useMemo(()=>{const s=(g==null?void 0:g.cookie_id)||r;return U.filter(c=>c.cookie_id===s)},[g==null?void 0:g.cookie_id,U,r]),jt=i==="automation"?"新建自动化":i==="reply"?"新增关键词":"编辑默认回复";return e.jsxs("div",{className:"min-w-0 space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row justify-between xl:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"自动化规则"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"系统通知卡片只进入自动化判断;买家消息进入关键词、默认或 AI 回复。"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:flex-wrap gap-3",children:[e.jsxs("select",{value:r,onChange:(s=>{y(s.target.value),v(1)}),className:"ios-input w-full px-4 py-3 rounded-2xl text-sm sm:w-64",children:[e.jsx("option",{value:"",children:"全部账号"}),V.map(s=>e.jsx("option",{value:s.id,children:Re(s)},s.id))]}),e.jsxs("button",{onClick:W,className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 hover:bg-gray-200 text-gray-700 flex items-center justify-center gap-2 whitespace-nowrap transition-colors",children:[e.jsx(Te,{className:`w-4 h-4 ${n?"animate-spin":""}`}),"刷新"]}),e.jsxs("button",{onClick:i==="automation"?(()=>d("order_paid")):i==="reply"?xt:(()=>void We()),disabled:!r,className:"ios-btn-primary px-5 py-3 rounded-2xl text-sm font-extrabold flex items-center justify-center gap-2 whitespace-nowrap disabled:opacity-50",children:[e.jsx(Ye,{className:"w-4 h-4"}),jt]})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[{id:"automation",label:"交易自动化",icon:He},{id:"reply",label:"关键词回复",icon:wt},{id:"default",label:"账号默认回复",icon:et}].map(s=>{const c=s.icon;return e.jsxs("button",{onClick:(()=>u(s.id)),className:`inline-flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${i===s.id?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:[e.jsx(c,{className:"w-4 h-4"}),s.label]},s.id)})}),i==="automation"&&(we.runs.length>0||we.pending_tasks.length>0)&&e.jsx(It,{runs:we.runs,pendingTasks:we.pending_tasks,onResolveRun:((s,c)=>void k(s,c)),onResolveDeferredTask:((s,c)=>void Le(s,c))}),i==="automation"&&e.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-6 xl:grid-cols-[minmax(270px,0.72fr)_minmax(0,1.28fr)]",children:[e.jsxs("aside",{className:"min-w-0 space-y-4",children:[e.jsxs("div",{className:"bg-white rounded-xl p-5 border border-gray-100 shadow-sm",children:[e.jsx("h3",{className:"font-black text-gray-900 mb-1",children:"新建规则"}),e.jsx("p",{className:"text-sm text-gray-500 mb-4",children:"先选自动化类型,再配置对应动作。"}),e.jsx("div",{className:"space-y-3",children:Se.map(s=>{const c=ae[s],x=c.icon;return e.jsx("button",{type:"button",onClick:(()=>d(s)),className:`w-full text-left rounded-2xl border p-4 transition-colors ${nt(c.accent)}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/80 flex items-center justify-center shrink-0",children:e.jsx(x,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-extrabold",children:c.label}),e.jsx("div",{className:"text-xs opacity-75 mt-1 leading-5",children:c.description})]})]})},s)})})]}),e.jsxs("div",{className:"bg-white rounded-xl p-5 border border-gray-100 shadow-sm",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between gap-3",children:[e.jsx("h3",{className:"font-black text-gray-900",children:"筛选结果构成"}),e.jsxs("span",{className:"text-xs font-bold text-gray-400",children:["共 ",R," 条"]})]}),e.jsx("div",{className:"space-y-3",children:Se.map(s=>{const c=ae[s],x=c.icon;return e.jsxs("div",{className:"flex items-center justify-between rounded-2xl bg-gray-50 p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(x,{className:"w-4 h-4 text-gray-500"}),e.jsx("span",{className:"text-sm font-bold text-gray-700",children:c.shortLabel})]}),e.jsx("span",{className:"text-sm font-black text-gray-900",children:M[s]||0})]},s)})})]})]}),e.jsxs("section",{className:"min-w-0 space-y-4",children:[e.jsxs("div",{className:"rounded-xl border border-gray-100 bg-surface-muted p-4 shadow-sm",children:[e.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center",children:[e.jsxs("div",{className:"relative min-w-0 flex-1",children:[e.jsx(kt,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"搜索自动化规则",placeholder:"搜索规则名、商品名或商品 ID...",value:A,onChange:(s=>{C(s.target.value),v(1)}),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]}),e.jsxs("div",{className:"relative xl:w-52",children:[e.jsx(Ct,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsxs("select",{"aria-label":"按自动化类型筛选",value:T,onChange:(s=>{J(s.target.value),v(1)}),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部自动化类型"}),Se.map(s=>e.jsx("option",{value:s,children:ae[s].shortLabel},s))]})]}),e.jsxs("select",{"aria-label":"按启用状态筛选",value:w,onChange:(s=>{G(s.target.value),v(1)}),className:"ios-input rounded-xl border-none bg-white px-4 py-2.5 text-sm shadow-sm xl:w-36",children:[e.jsx("option",{value:"all",children:"全部状态"}),e.jsx("option",{value:"enabled",children:"已启用"}),e.jsx("option",{value:"disabled",children:"已禁用"})]}),Fe&&e.jsx("button",{type:"button",onClick:_t,className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-white text-gray-500 shadow-sm transition-colors hover:bg-gray-100 hover:text-gray-900",title:"清除筛选","aria-label":"清除筛选",children:e.jsx(ke,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"mt-3 flex items-center justify-between text-xs font-bold text-gray-400",children:[e.jsxs("span",{children:["找到 ",R," 条规则"]}),n&&e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Te,{className:"h-3.5 w-3.5 animate-spin"}),"正在更新"]})]})]}),n&&Ie.length===0?e.jsxs("div",{className:"flex min-h-56 items-center justify-center rounded-xl border border-gray-100 bg-white text-sm font-bold text-gray-400",children:[e.jsx(Te,{className:"mr-2 h-4 w-4 animate-spin"}),"正在加载规则"]}):Ie.length===0?e.jsxs("div",{className:"bg-white rounded-xl border border-dashed border-gray-200 p-16 text-center",children:[e.jsx(He,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),e.jsx("h3",{className:"text-xl font-black text-gray-900",children:Fe?"没有匹配的自动化规则":"还没有自动化规则"}),e.jsx("p",{className:"text-gray-500 mt-2",children:Fe?"调整或清除筛选条件后再试。":"从左侧选择一个模板开始配置。"})]}):Ie.map(s=>{const c=ae[s.trigger_type],x=c.icon;return e.jsx("article",{className:"bg-white rounded-xl border border-gray-100 p-5 shadow-sm hover:shadow-lg transition-all",children:e.jsxs("div",{className:"flex flex-col lg:flex-row lg:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-4 min-w-0",children:[e.jsx("div",{className:`w-12 h-12 rounded-2xl flex items-center justify-center shrink-0 ${nt(c.accent,!0)}`,children:e.jsx(x,{className:"w-5 h-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-2",children:[e.jsx("h3",{className:"text-lg font-black text-gray-900 truncate",children:s.name}),e.jsx("span",{className:`px-2.5 py-1 rounded-full text-xs font-bold ${ts(s.enabled)}`,children:s.enabled?"已启用":"已禁用"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-xs font-bold",children:[e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-gray-100 text-gray-600",children:c.label}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-gray-100 text-gray-600",children:s.item_title||s.item_id||"账号级规则"}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-blue-50 text-blue-700",children:es(s)})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("button",{onClick:(()=>l(s)),className:"px-4 py-2 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-700 text-sm font-bold flex items-center gap-2",children:[e.jsx(ze,{className:"w-4 h-4"}),"编辑"]}),e.jsx("button",{onClick:(()=>se(s)),className:`px-4 py-2 rounded-xl text-sm font-bold ${s.enabled?"bg-amber-50 text-amber-700 hover:bg-amber-100":"bg-emerald-50 text-emerald-700 hover:bg-emerald-100"}`,children:s.enabled?"禁用":"启用"}),e.jsx("button",{onClick:(()=>B(s.id)),className:"p-2.5 rounded-xl text-red-500 hover:bg-red-50",title:"删除",children:e.jsx(Ce,{className:"w-4 h-4"})})]})]})},s.id)}),R>0&&e.jsxs("div",{className:"flex flex-col gap-3 rounded-xl border border-gray-100 bg-white px-4 py-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3 text-sm font-medium text-gray-500",children:[e.jsxs("span",{children:["第 ",F," / ",Math.max(z,1)," 页"]}),e.jsx("span",{className:"h-4 w-px bg-gray-200"}),e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"sr-only",children:"每页显示数量"}),e.jsx("select",{value:X,onChange:(s=>{q(Number(s.target.value)),v(1)}),className:"ios-input rounded-lg border-none bg-gray-50 px-2.5 py-2 text-sm",children:[10,20,50].map(s=>e.jsxs("option",{value:s,children:[s," 条/页"]},s))})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{type:"button",disabled:F<=1||n,onClick:(()=>v(s=>Math.max(1,s-1))),className:"flex h-9 w-9 items-center justify-center rounded-lg bg-gray-50 text-gray-600 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-40","aria-label":"上一页",title:"上一页",children:e.jsx(St,{className:"h-4 w-4"})}),yt.map(s=>e.jsx("button",{type:"button",disabled:n,onClick:(()=>v(s)),className:`h-9 min-w-9 rounded-lg px-2 text-sm font-bold transition-colors ${s===F?"bg-brand text-white":"bg-gray-50 text-gray-600 hover:bg-gray-100"} disabled:cursor-not-allowed disabled:opacity-60`,"aria-label":`第 ${s} 页`,"aria-current":s===F?"page":void 0,children:s},s)),e.jsx("button",{type:"button",disabled:F>=z||n,onClick:(()=>v(s=>Math.min(z,s+1))),className:"flex h-9 w-9 items-center justify-center rounded-lg bg-gray-50 text-gray-600 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-40","aria-label":"下一页",title:"下一页",children:e.jsx(Rt,{className:"h-4 w-4"})})]})]})]})]}),i==="reply"&&e.jsxs("section",{className:"bg-white rounded-xl border border-gray-100 p-6 shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-blue-700 bg-blue-50 px-4 py-2 rounded-xl mb-5 w-fit",children:[e.jsx(Je,{className:"w-4 h-4"}),"这里只处理买家用户消息;系统通知不会进入关键词或 AI 回复。"]}),e.jsxs("div",{className:"space-y-3",children:[le.map(s=>e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between p-5 rounded-2xl border border-gray-100 bg-surface-subtle hover:bg-white hover:shadow-lg transition-all gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("span",{className:"px-3 py-1 bg-black text-white rounded-lg text-xs font-bold",children:"包含匹配"}),e.jsxs("h3",{className:"font-bold text-gray-900",children:["“",s.keyword,"”"]})]}),e.jsx("div",{className:"bg-white p-3 rounded-xl border border-gray-100 text-sm text-gray-600 leading-relaxed",children:s.type==="image"&&s.image_url?s.image_url:s.reply_content})]}),e.jsxs("div",{className:"flex items-center gap-3 border-t md:border-t-0 md:border-l border-gray-200 pt-4 md:pt-0 md:pl-6",children:[e.jsx("button",{onClick:(()=>{te({...s}),pe(!0)}),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(ze,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>pt(s.id)),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(Ce,{className:"w-5 h-5"})})]})]},s.id)),le.length===0&&e.jsx("div",{className:"text-center py-20 text-gray-400",children:"暂无关键词回复规则"})]})]}),i==="default"&&e.jsxs("section",{className:"bg-white rounded-xl border border-gray-100 p-6 shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-blue-700 bg-blue-50 px-4 py-2 rounded-xl mb-5 w-fit",children:[e.jsx(Je,{className:"w-4 h-4"}),"默认回复只处理买家用户消息;关键词未命中且 AI 未接管时才会使用。"]}),e.jsxs("div",{className:"space-y-3",children:[Ze.map(s=>{const c=Y[s.id],x=!!(c!=null&&c.enabled);return e.jsxs("div",{className:`flex flex-col md:flex-row md:items-center justify-between p-5 rounded-2xl border transition-all gap-4 ${x?"border-purple-100 bg-purple-50/50 hover:bg-white hover:shadow-lg":"border-gray-100 bg-surface-subtle hover:bg-white hover:shadow-lg"}`,children:[e.jsxs("div",{className:"flex items-center gap-4 min-w-0",children:[e.jsx("div",{className:`w-12 h-12 rounded-2xl flex items-center justify-center ${x?"bg-purple-600 text-white":"bg-gray-200 text-gray-400"}`,children:e.jsx(et,{className:"w-5 h-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("h3",{className:"font-bold text-gray-900 text-lg truncate",children:Re(s)}),e.jsx("span",{className:`px-2 py-0.5 rounded-lg text-xs font-bold ${x?"bg-green-100 text-green-700":"bg-gray-200 text-gray-500"}`,children:x?"已启用":"未启用"}),(c==null?void 0:c.reply_once)&&e.jsx("span",{className:"px-2 py-0.5 rounded-lg text-xs font-bold bg-purple-100 text-purple-700",children:"只回复一次"})]}),e.jsx("div",{className:"text-sm text-gray-600 line-clamp-2",children:x?c.reply_content||c.reply_image_url||"已配置默认回复":"未配置默认回复"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 border-t md:border-t-0 md:border-l border-gray-200 pt-4 md:pt-0 md:pl-6",children:[e.jsx("button",{onClick:(()=>void We(s.id)),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(ze,{className:"w-4 h-4"})}),x&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:(()=>void ht(s.id)),className:"px-3 py-2 text-xs font-bold text-blue-600 hover:bg-blue-50 rounded-xl transition-colors",children:"清空记录"}),e.jsx("button",{onClick:(()=>void bt(s.id)),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(Ce,{className:"w-5 h-5"})})]})]})]},s.id)}),Ze.length===0&&e.jsx("div",{className:"text-center py-20 text-gray-400",children:"暂无账号"})]})]}),$e&&g&&De.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"72rem",maxHeight:"92vh"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-black text-gray-900",children:g.id?"编辑自动化规则":"新建自动化规则"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:Ne.description})]}),e.jsx("button",{onClick:(()=>je(!1)),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",title:"关闭",children:e.jsx(ke,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[320px_1fr] min-h-0",children:[e.jsxs("aside",{className:"bg-slate-900 text-white p-5 overflow-y-auto",children:[e.jsx("div",{className:"text-xs font-bold text-slate-400 mb-3",children:"选择自动化类型"}),e.jsx("div",{className:"space-y-3",children:Se.map(s=>{const c=ae[s],x=c.icon,de=me===s;return e.jsx("button",{type:"button",onClick:(()=>b(s)),className:`w-full rounded-2xl p-4 text-left border transition-all ${de?"bg-white text-slate-950 border-white":"bg-white/5 text-white border-white/10 hover:bg-white/10"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(x,{className:`w-5 h-5 mt-0.5 ${de?"text-brand":"text-white"}`}),e.jsxs("div",{children:[e.jsx("div",{className:"font-black",children:c.label}),e.jsx("div",{className:`text-xs mt-1 leading-5 ${de?"text-gray-500":"text-gray-400"}`,children:c.description})]})]})},s)})}),e.jsxs("div",{className:"mt-6 rounded-2xl bg-white/5 border border-white/10 p-4",children:[e.jsx("div",{className:"text-xs font-bold text-slate-400 mb-3",children:"执行流程"}),e.jsx("div",{className:"space-y-3",children:Ne.flow.map((s,c)=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-white text-slate-950 text-xs font-black flex items-center justify-center",children:c+1}),e.jsx("span",{className:"text-sm font-bold text-gray-100",children:s})]},s))})]})]}),e.jsx("div",{className:"p-6 overflow-y-auto bg-surface-subtle",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(At,{className:"w-5 h-5 text-brand"}),e.jsx("h4",{className:"font-black text-gray-900",children:"生效范围"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"规则名称"}),e.jsx("input",{type:"text",value:g.name||"",onChange:(s=>O({...g,name:s.target.value})),placeholder:"不填时按类型和商品自动生成",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"闲鱼账号"}),e.jsxs("select",{value:g.cookie_id||"",onChange:(s=>O({...g,cookie_id:s.target.value,item_id:"",item_title:"",item_keyword:""})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"选择账号"}),V.map(s=>e.jsx("option",{value:s.id,children:Re(s)},s.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关联商品"}),e.jsxs("select",{value:g.item_id||"",onChange:(s=>p(s.target.value)),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级规则(不限定商品)"}),ft.map(s=>e.jsx("option",{value:s.item_id,children:s.item_title||s.item_id},`${s.cookie_id}-${s.item_id}`))]})]})]}),ge&&me!=="review_missing_timeout"&&e.jsxs("div",{className:"mt-4 rounded-2xl bg-gray-50 border border-gray-100 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-2",children:[e.jsx("span",{className:"px-3 py-1.5 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:ge.item_title||ge.item_id}),e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${oe?"bg-blue-50 text-blue-700":"bg-gray-100 text-gray-500"}`,children:oe?"多规格商品":"普通商品"}),e.jsx("span",{className:"px-3 py-1.5 rounded-lg text-xs font-bold bg-emerald-50 text-emerald-700",children:"按订单购买数量自动发货"})]}),e.jsx("p",{className:"text-xs leading-5 text-gray-500",children:"多规格状态来自闲鱼商品本身,发布后不能在这里修改;系统会在买家付款后读取订单详情,按实际购买规格和数量匹配下面的发货规则。"})]})]}),me!=="review_missing_timeout"?e.jsxs("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($t,{className:"w-5 h-5 text-brand"}),e.jsx("h4",{className:"font-black text-gray-900",children:me==="buyer_reviewed"?"赠品库存":"发货库存"})]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:oe?"每条发货内容绑定一个订单规格;同一规格可添加多条内容并全部发送。":"可添加多条发货内容,买家付款后会按顺序全部发送。"})]}),e.jsxs("button",{type:"button",onClick:N,className:"px-3 py-2 rounded-xl bg-gray-900 text-white text-xs font-bold hover:bg-black flex items-center gap-1.5",children:[e.jsx(Ye,{className:"w-3.5 h-3.5"}),"添加发货内容"]})]}),e.jsx("div",{className:"space-y-3",children:xe.map((s,c)=>e.jsxs("div",{className:`grid grid-cols-1 gap-3 items-end rounded-2xl border border-gray-200 p-4 ${oe?"md:grid-cols-[1fr_1fr_1.4fr_110px_40px]":"md:grid-cols-[1.4fr_110px_40px]"}`,children:[oe&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"规格名称"}),e.jsx("input",{value:s.spec_name,onChange:(x=>h(c,{spec_name:x.target.value})),className:"w-full ios-input px-3 py-2.5 rounded-lg",placeholder:"例如:套餐"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"规格值"}),e.jsx("input",{value:s.spec_value,onChange:(x=>h(c,{spec_value:x.target.value})),className:"w-full ios-input px-3 py-2.5 rounded-lg",placeholder:"例如:30天"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"卡密库存"}),e.jsxs("select",{value:s.card_id||"",onChange:(x=>h(c,{card_id:Number(x.target.value)})),className:"w-full ios-input px-3 py-2.5 rounded-lg",children:[e.jsx("option",{value:"",children:"请选择卡密库存"}),H.filter(x=>x.enabled&&x.type!=="api").map(x=>e.jsx("option",{value:x.id,children:x.name},x.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"每件份数"}),e.jsx("input",{type:"number",min:"1",max:"100",value:s.delivery_count,onChange:(x=>h(c,{delivery_count:Math.max(1,Number(x.target.value)||1)})),className:"w-full ios-input px-3 py-2.5 rounded-lg"})]}),e.jsxs("div",{className:"md:col-span-full flex flex-wrap items-center gap-3 rounded-xl bg-gray-50 px-3 py-2",children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs font-bold text-gray-600 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:s.delay_override===!0,onChange:(x=>h(c,{delay_override:x.target.checked})),className:"accent-brand"}),"覆盖卡密默认延时"]}),s.delay_override&&e.jsx("input",{type:"number",min:"0",max:"3600",value:s.delay_seconds||0,onChange:(x=>h(c,{delay_seconds:Math.max(0,Number(x.target.value)||0)})),className:"w-28 ios-input px-2 py-1.5 rounded-lg text-xs","aria-label":"动作延时秒数"}),e.jsx("span",{className:"text-xs text-gray-500",children:s.delay_override?`本动作延时 ${s.delay_seconds||0} 秒`:"使用卡密默认延时"})]}),e.jsx("button",{type:"button",disabled:xe.length===1,onClick:(()=>O({...g,variants:xe.filter((x,de)=>de!==c)})),className:"w-10 h-10 flex items-center justify-center rounded-lg text-red-500 hover:bg-red-50 disabled:opacity-25",title:"删除发货内容",children:e.jsx(Ce,{className:"w-4 h-4"})})]},s.id||c))})]}):e.jsxs("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(it,{className:"w-5 h-5 text-amber-600"}),e.jsx("h4",{className:"font-black text-gray-900",children:"求评价计划"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"发货后等待小时"}),e.jsx("input",{type:"number",min:"1",value:Number(be.after_shipped_hours||72),onChange:(s=>O({...g,config_json:ce(g.config_json,{after_shipped_hours:Math.max(1,Number(s.target.value)||72)})})),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"再次求评间隔小时"}),e.jsx("input",{type:"number",min:"1",value:Number(be.repeat_interval_hours||24),onChange:(s=>O({...g,config_json:ce(g.config_json,{repeat_interval_hours:Math.max(1,Number(s.target.value)||24)})})),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最多求评次数"}),e.jsx("input",{type:"number",min:"1",value:Number(be.max_attempts||1),onChange:(s=>O({...g,config_json:ce(g.config_json,{max_attempts:Math.max(1,Number(s.target.value)||1)})})),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"md:col-span-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"求评价文案"}),e.jsx("textarea",{value:((Qe=(Xe=g.actions)==null?void 0:Xe.find(s=>s.action_type==="send_text"))==null?void 0:Qe.message_template)||"",onChange:(s=>{var c;return O({...g,actions:((c=g.actions)!=null&&c.length?g.actions:_e("review_missing_timeout")).map(x=>x.action_type==="send_text"?{...x,message_template:s.target.value}:x)})}),className:"w-full ios-input px-4 py-3 rounded-xl h-28 resize-none"})]})]})]}),e.jsx("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-[180px_1fr] gap-4 items-end",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"优先级"}),e.jsx("p",{className:"text-xs text-gray-500 mb-2",children:"数字越小优先级越高;同一账号、商品和触发条件只执行优先级最高的一条规则。"}),e.jsx("input",{type:"number",value:g.priority||100,onChange:(s=>O({...g,priority:Number(s.target.value)||100})),min:"1",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("label",{className:"h-[48px] flex items-center gap-3 px-4 bg-gray-50 rounded-xl text-sm font-bold text-gray-800",children:[e.jsx("input",{type:"checkbox",checked:g.enabled!==!1,onChange:(s=>O({...g,enabled:s.target.checked})),className:"w-4 h-4 rounded"}),"启用规则"]})]})})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 bg-white flex gap-3",children:[e.jsx("button",{onClick:(()=>je(!1)),className:"flex-1 px-6 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200",children:"取消"}),e.jsxs("button",{onClick:f,className:"flex-1 ios-btn-primary px-6 py-3 rounded-2xl font-bold flex items-center justify-center gap-2",children:[e.jsx(tt,{className:"w-4 h-4"}),"保存自动化规则"]})]})]})}),document.body),Me&&S&&De.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:S.id?"编辑回复规则":"新增回复规则"}),e.jsx("button",{onClick:(()=>pe(!1)),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(ke,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关联商品"}),e.jsxs("select",{value:S.item_id||"",onChange:(s=>te({...S,item_id:s.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级回复"}),U.filter(s=>!r||s.cookie_id===r).map(s=>e.jsx("option",{value:s.item_id,children:s.item_title||s.item_id},`${s.cookie_id}-${s.item_id}`))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复类型"}),e.jsxs("select",{value:S.type||"text",onChange:(s=>{const c=s.target.value;te({...S,type:c,reply_content:c==="text"?S.reply_content:"",image_url:c==="image"?S.image_url:""})}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"text",children:"文字"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关键词"}),e.jsx("input",{type:"text",value:S.keyword||"",onChange:(s=>te({...S,keyword:s.target.value})),placeholder:"买家发送的关键词",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),S.type==="image"?e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{value:S.image_url||"",onChange:(s=>te({...S,image_url:s.target.value})),placeholder:"https://...",className:"w-full ios-input px-4 py-3 rounded-xl"})]}):e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复内容"}),e.jsx("textarea",{value:S.reply_content||"",onChange:(s=>te({...S,reply_content:s.target.value})),placeholder:"自动回复的内容",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none"})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx("button",{onClick:(()=>pe(!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:ut,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Mt,{className:"w-4 h-4"}),"保存规则"]})]})]})]})}),document.body),Pe&&De.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"账号默认回复"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"关键词和 AI 都未处理时,才会使用默认回复。"})]}),e.jsx("button",{onClick:(()=>ve(!1)),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",title:"关闭",children:e.jsx(ke,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"闲鱼账号"}),e.jsxs("select",{value:L.cookie_id,onChange:(s=>ie({...L,cookie_id:s.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"选择账号"}),V.map(s=>e.jsx("option",{value:s.id,children:Re(s)},s.id))]})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900",children:"启用默认回复"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1",children:"启用后,未命中关键词时自动发送"})]}),e.jsx("button",{type:"button",onClick:(()=>ie({...L,enabled:!L.enabled})),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${L.enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${L.enabled?"translate-x-7":"translate-x-1"}`})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复内容"}),e.jsx("textarea",{value:L.reply_content,onChange:(s=>ie({...L,reply_content:s.target.value})),placeholder:"输入默认回复内容",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复图片 URL(可选)"}),e.jsx("input",{type:"text",value:L.reply_image_url,onChange:(s=>ie({...L,reply_image_url:s.target.value})),placeholder:"https://example.com/image.jpg",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("label",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl text-sm font-bold text-gray-800",children:[e.jsxs("span",{children:["只回复一次",e.jsx("span",{className:"block text-xs text-gray-500 font-medium mt-1",children:"同一会话只发送一次默认回复"})]}),e.jsx("input",{type:"checkbox",checked:L.reply_once,onChange:(s=>ie({...L,reply_once:s.target.checked})),className:"w-4 h-4 rounded"})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx("button",{onClick:(()=>ve(!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:gt,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(tt,{className:"w-4 h-4"}),"保存默认回复"]})]})]})]})}),document.body)]})};export{os as default}; +import{j as e,r as o,b as De}from"./react-vendor-C_od1ZSF.js";import{k as Je,ae as it,af as vt,m as Nt,R as Te,N as Ye,Z as He,x as wt,w as et,I as kt,a1 as Ct,X as ke,V as ze,F as Ce,h as St,g as Rt,a6 as At,ag as $t,r as tt,ah as Mt}from"./icons-vendor-CvzvbbIV.js";import{g as Z,p as Ge,a as fe,d as Ke}from"./index-hByDAHGj.js";import{o as Ae,c as Ue}from"./contract-COFcZjyb.js";const Ee=(t,a)=>t.allowed_resolutions.includes(a),Pt=(t,a)=>({runs:t.runs.filter(i=>!a||i.cookie_id===a),pending_tasks:t.pending_tasks.filter(i=>!a||i.cookie_id===a)}),Lt=t=>({external_result_unknown:"外部动作结果未知",invalid_snapshot:"历史数据无法恢复",rule_unavailable:"规则不可用",partial_failure:"部分动作失败",execution_failed:"动作执行失败"})[t]||"自动化异常",It=({runs:t,pendingTasks:a,onResolveRun:i,onResolveDeferredTask:u})=>e.jsxs("section",{className:"rounded-2xl border border-red-200 bg-red-50 p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Je,{className:"w-5 h-5 text-red-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-black text-red-900",children:"需要人工处理的自动化任务"}),e.jsx("p",{className:"text-sm text-red-700 mt-1",children:"请先在闲鱼聊天、订单或商品列表中核对真实结果,再选择继续或重试。"})]})]}),e.jsxs("div",{className:"space-y-3",children:[t.map(r=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",r.cookie_id," · 订单 ",r.order_id||"-"," · 已记录发送 ",r.sent_count," 条"]}),e.jsx("div",{className:"text-xs font-bold text-red-800 mt-1",children:Lt(r.issue_kind)}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 shrink-0",children:[Ee(r,"continue")&&e.jsx("button",{onClick:(()=>i(r.id,"continue")),className:"px-3 py-2 rounded-lg bg-emerald-100 text-emerald-800 text-xs font-bold",children:"已执行,继续下一步"}),Ee(r,"retry")&&e.jsx("button",{onClick:(()=>i(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"未执行,安全重试"}),Ee(r,"cancel")&&e.jsx("button",{onClick:(()=>i(r.id,"cancel")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"终止"})]})]},`run-${r.id}`)),a.map(r=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",r.cookie_id," · 延迟任务重试已达 ",r.attempt_count," 次"]}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsx("button",{onClick:(()=>u(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"重新入队"}),e.jsx("button",{onClick:(()=>u(r.id,"dismiss")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"忽略"})]})]},`task-${r.id}`))]})]}),Ft=async t=>Z("/api/v1/accounts/details",void 0,t),ot=async t=>Z("/api/v1/cards",void 0,t),dt=async(t,a)=>Z("/api/v1/items",void 0,a),ct=t=>t.map(a=>{var i,u;return{id:String(a.id),name:a.name||"",trigger_type:a.trigger_type||"order_paid",item_keyword:a.item_title||a.item_id||"",cookie_id:a.cookie_id||"",item_id:a.item_id||"",item_title:a.item_title||"",card_group_id:Number(((i=(a.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:i.card_id)||0),card_group_name:((u=(a.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:u.card_name)||"",priority:a.priority||100,enabled:a.enabled||!1,config_json:a.config_json||"{}",actions:(a.actions||[]).map(r=>({id:r.id?String(r.id):void 0,action_type:r.action_type,card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),message_template:r.message_template||"",delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}",enabled:r.enabled!==!1,sort_order:Number(r.sort_order||0)})),variants:(a.actions||[]).filter(r=>r.action_type==="send_card").map(r=>{let y={};try{y=JSON.parse(r.config_json||"{}")}catch{}return{id:r.id?String(r.id):void 0,spec_name:y.spec_name||"",spec_value:y.spec_value||"",card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),enabled:r.enabled!==!1,delay_override:y.delay_override===!0,delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}"}})}}),Dt=async()=>{const t=await Z("/api/v1/automation-rules"),a=Ue(t,["data","rules","items"]);return ct(a)},Tt=async({cookieId:t,triggerType:a,enabled:i,search:u,page:r=1,pageSize:y=10}={})=>{const A=await Z("/api/v1/automation-rules",{page:r,page_size:y,cookie_id:t||void 0,trigger_type:a||void 0,enabled:i,search:(u==null?void 0:u.trim())||void 0}),C=Ae(A,["data","result"])||{},m=ct(Ue(A,["data","rules","items"]));return{success:!0,data:m,total:Number(C.total??m.length),page:Number(C.page??r),page_size:Number(C.page_size??y),total_pages:Number(C.total_pages??(m.length?1:0)),trigger_counts:Object.fromEntries(Object.entries(C.trigger_counts||{}).map(([I,T])=>[I,Number(T)]))}},zt=(t,a)=>{if(t!=="order_paid")return a.map((r,y)=>({...r,sort_order:r.sort_order||y+1}));const i=a.filter(r=>r.action_type==="send_card").map((r,y)=>({...r,sort_order:y+1})),u=a.filter(r=>r.action_type!=="send_card"&&r.action_type!=="confirm_shipment");return[...i,...u.map((r,y)=>({...r,sort_order:i.length+y+1})),{action_type:"confirm_shipment",enabled:!0,sort_order:i.length+u.length+1}]},st=async t=>{const a=t.trigger_type||"order_paid",u=[{order_paid:"付款后自动发货",buyer_reviewed:"评价后发送赠品",review_missing_timeout:"超时未评价求评价"}[a]||"自动化规则",t.item_title||t.item_id||t.cookie_id||""].filter(Boolean).join(" - "),r=(t.actions||[]).filter(m=>m.action_type!=="send_card"&&m.action_type!=="confirm_shipment"),y=t.variants&&t.variants.length>0?[...t.variants.map((m,I)=>({action_type:"send_card",card_id:m.card_id,delivery_count:m.delivery_count||1,enabled:m.enabled!==!1,sort_order:I+1,delay_seconds:m.delay_seconds||0,config_json:JSON.stringify({spec_name:m.spec_name||"",spec_value:m.spec_value||"",delay_override:m.delay_override===!0})})),...r]:t.actions&&t.actions.length>0?t.actions:[{action_type:"send_card",card_id:t.card_group_id||0,delivery_count:1,enabled:!0,sort_order:1}],A=zt(a,y),C={cookie_id:t.cookie_id||"",item_id:t.item_id||"",name:(t.name||"").trim()||u||"自动化规则",trigger_type:a,enabled:t.enabled??!0,priority:t.priority||100,config_json:t.config_json||"{}",actions:A.map((m,I)=>({action_type:m.action_type,card_id:m.card_id||0,delivery_count:m.delivery_count||1,message_template:m.message_template||"",delay_seconds:m.delay_seconds||0,config_json:m.config_json||"{}",enabled:m.enabled!==!1,sort_order:m.sort_order||I+1}))};return t.id?Ge(`/api/v1/automation-rules/${t.id}`,C):fe("/api/v1/automation-rules",C)},Et=async t=>Ke(`/api/v1/automation-rules/${t}`),Ot=async()=>{const t=await Z("/api/v1/automation-issues"),a=Ae(t,["data","result"])||{};return{runs:Array.isArray(a==null?void 0:a.runs)?a.runs:[],pending_tasks:Array.isArray(a==null?void 0:a.pending_tasks)?a.pending_tasks:[]}},qt=async(t,a)=>fe(`/api/v1/automation-runs/${t}/resolve`,{resolution:a}),Vt=async(t,a)=>fe(`/api/v1/automation-pending-tasks/${t}/resolve`,{resolution:a}),Bt=t=>({id:String((t==null?void 0:t.id)||""),keyword:(t==null?void 0:t.keyword)||"",reply:(t==null?void 0:t.reply)||"",item_id:(t==null?void 0:t.item_id)||"",type:(t==null?void 0:t.type)==="image"?"image":"text",image_url:(t==null?void 0:t.image_url)||""}),Jt=async t=>{const a=await Z(`/api/v1/reply-rules/${t}/typed`);return Ue(a,["data","items","rules"]).map(Bt)},Gt=async t=>t?(await Jt(t)).map(i=>({id:i.id,keyword:i.keyword||"",reply_content:i.reply||"",match_type:"fuzzy",enabled:!0,item_id:i.item_id||"",type:i.type==="image"?"image":"text",image_url:i.image_url||""})):[],Kt=async(t,a)=>{const i=t.type||"text",u={keyword:t.keyword||"",reply:i==="text"&&t.reply_content||"",item_id:t.item_id||"",type:i,image_url:i==="image"&&t.image_url||""};return t.id?Ge(`/api/v1/reply-rules/${a}/typed/${t.id}`,u):fe(`/api/v1/reply-rules/${a}/items`,u)},Ut=async(t,a)=>Ke(`/api/v1/reply-rules/${a}/typed/${t}`),at=async()=>{const t=await Z("/api/v1/default-replies");return Ae(t,["data","replies","items"])||{}},Wt=async t=>{const a=await Z(`/api/v1/default-replies/${t}`),i=Ae(a,["data","result"])||{};return{cookie_id:t,enabled:i.enabled||!1,reply_content:i.reply_content||"",reply_once:i.reply_once||!1,reply_image_url:i.reply_image_url||""}},Zt=async(t,a)=>Ge(`/api/v1/default-replies/${t}`,{enabled:a.enabled??!1,reply_content:a.reply_content||"",reply_once:a.reply_once??!1,reply_image_url:a.reply_image_url||""}),Xt=async t=>Ke(`/api/v1/default-replies/${t}`),Qt=async t=>fe(`/api/v1/default-replies/${t}/clear-records`,{}),Oe=()=>({submitting:!1,result:"idle"}),qe=t=>t.submitting?t:{submitting:!0,result:"idle"},Ve=(t,a)=>({submitting:!1,result:a?"success":"failure"}),rt=t=>t+1,Be=(t,a,i,u)=>t===a&&i===u,Yt=t=>{const[a,i]=o.useState([]),[u,r]=o.useState({runs:[],pending_tasks:[]}),[y,A]=o.useState([]),[C,m]=o.useState({}),[I,T]=o.useState([]),[J,w]=o.useState([]),[G,F]=o.useState([]),[v,X]=o.useState(!1),q=o.useRef(0),re=o.useRef(0),[Q,K]=o.useState(0),[le,Y]=o.useState(0),[V,H]=o.useState({}),U=o.useCallback(async()=>{const P=Promise.all([Ft(),ot(),dt(),at()]),[_,j,D,ee]=await P;T(_),w(j),F(D),m(ee),t.setSelectedAccountId(ne=>{var E;return ne||((E=_[0])==null?void 0:E.id)||""})},[t.setSelectedAccountId]),n=o.useCallback(async()=>{var ee;const P=rt(q.current);q.current=P;const _=Ot().catch(ne=>(console.warn("加载自动化异常列表失败,不阻断规则展示",ne),null)),j=await Tt({cookieId:t.selectedAccountId||void 0,triggerType:t.automationTriggerFilter,enabled:t.automationStatusFilter==="all"?void 0:t.automationStatusFilter==="enabled",search:t.debouncedAutomationSearch,page:t.automationPage,pageSize:t.automationPageSize});if(!Be(P,q.current,t.selectedAccountId,t.selectedAccountId))return;i(j.data),K(j.total),Y(j.total_pages),H(j.trigger_counts||{}),j.page!==t.automationPage&&((ee=t.onAutomationPageChange)==null||ee.call(t,j.page));const D=await _;Be(P,q.current,t.selectedAccountId,t.selectedAccountId)&&D&&r(D)},[t.automationPage,t.automationPageSize,t.automationStatusFilter,t.automationTriggerFilter,t.debouncedAutomationSearch,t.onAutomationPageChange,t.selectedAccountId]),$=o.useCallback(async()=>{const P=rt(re.current);re.current=P;const _=t.selectedAccountId;if(A([]),!_)return;const j=await Gt(_);Be(P,re.current,_,t.selectedAccountId)&&A(j)},[t.selectedAccountId]),R=o.useCallback(async()=>{m(await at())},[]),z=o.useCallback(async()=>{X(!0);try{t.activeTab==="automation"?await n():t.activeTab==="reply"?await $():await R()}finally{X(!1)}},[n,R,$,t.activeTab]);return{automationRules:a,automationIssues:u,replyRules:y,defaultReplies:C,accounts:I,cards:J,items:G,automationTotal:Q,automationTotalPages:le,automationTriggerCounts:V,loading:v,setLoading:X,setAutomationRules:i,setCards:w,setItems:F,loadReferenceData:U,loadAutomationRules:n,loadReplyRules:$,loadDefaultReplies:R,refresh:z}},ae={order_paid:{label:"付款后自动发货",shortLabel:"自动发货",description:"闲鱼付款系统卡片进入自动化中心后,先发送卡密,成功后再确认发货。",flow:["付款系统卡片","匹配商品/规格","发送卡密","确认发货"],accent:"blue",icon:Nt},buyer_reviewed:{label:"评价后发送赠品",shortLabel:"评价赠品",description:"闲鱼评价系统卡片进入自动化中心后,给买家发送赠品卡密。",flow:["评价系统卡片","匹配商品/规格","发送赠品"],accent:"emerald",icon:vt},review_missing_timeout:{label:"超时未评价求评价",shortLabel:"求评价",description:"计划任务扫描已发货未评价订单,到期后发送求评价文案。",flow:["计划任务扫描","已发货未评价","达到等待时间","发送提醒"],accent:"amber",icon:it}},Se=["order_paid","buyer_reviewed","review_missing_timeout"],Ht="亲,商品使用满意的话,麻烦给个评价,谢谢~",he=()=>({spec_name:"",spec_value:"",card_id:0,delivery_count:1,enabled:!0,delay_override:!1,delay_seconds:0}),mt=t=>{if(!t)return{};try{const a=JSON.parse(t);return a&&typeof a=="object"&&!Array.isArray(a)?a:{}}catch{return{}}},ce=(t,a={})=>{const i=mt(t);return JSON.stringify({after_shipped_hours:Number(i.after_shipped_hours||72),repeat_interval_hours:Number(i.repeat_interval_hours||24),max_attempts:Number(i.max_attempts||1),...a})},ye=(t,a)=>{var u;const i=((u=ae[t])==null?void 0:u.label)||"自动化规则";return a?`${i} - ${a}`:i},lt=t=>{const a=(t||"").trim();return a?Object.values(ae).some(i=>a===i.label||a.startsWith(`${i.label} -`)):!0},_e=(t,a=0)=>{if(t==="review_missing_timeout")return[{action_type:"send_text",message_template:Ht,enabled:!0,sort_order:1}];const i={action_type:"send_card",card_id:a,delivery_count:1,enabled:!0,sort_order:1};return t==="order_paid"?[i,{action_type:"confirm_shipment",enabled:!0,sort_order:2}]:[i]},es=t=>{var i,u;if(t.trigger_type==="review_missing_timeout")return((u=(i=t.actions)==null?void 0:i.find(r=>r.action_type==="send_text"))==null?void 0:u.message_template)||"发送求评价文案";const a=(t.actions||[]).filter(r=>r.action_type==="send_card");return a.length?a.map(r=>r.card_name||`卡密 ${r.card_id}`).join(" / "):"未配置卡密库存"},nt=(t,a=!1)=>{const i={blue:a?"border-blue-500 bg-blue-50 text-blue-700":"border-blue-100 bg-blue-50/60 text-blue-700 hover:border-blue-300",emerald:a?"border-emerald-500 bg-emerald-50 text-emerald-700":"border-emerald-100 bg-emerald-50/60 text-emerald-700 hover:border-emerald-300",amber:a?"border-amber-500 bg-amber-50 text-amber-700":"border-amber-100 bg-amber-50/60 text-amber-700 hover:border-amber-300"};return i[t]||i.blue},ts=t=>t?"bg-emerald-100 text-emerald-700":"bg-gray-200 text-gray-500",Re=t=>(t==null?void 0:t.nickname)||(t==null?void 0:t.remark)||(t==null?void 0:t.id)||"未知账号",ss=t=>t===!0||t===1||t==="1",as=({selectedAccountId:t,setSelectedAccountId:a,setActiveTab:i,items:u,setAutomationRules:r,setCards:y,setItems:A,setLoading:C,loadAutomationRules:m,loadReferenceData:I,loadReplyRules:T,loadDefaultReplies:J,initialDeliveryTarget:w,onDeliveryTargetHandled:G})=>{var xe;const[F,v]=o.useState(!1),[X,q]=o.useState(!1),[re,Q]=o.useState(!1),[K,le]=o.useState(Oe),[Y,V]=o.useState(Oe),[H,U]=o.useState(Oe),[n,$]=o.useState(null),[R,z]=o.useState(null),[M,P]=o.useState({cookie_id:"",enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""}),_=o.useMemo(()=>n!=null&&n.cookie_id&&n.item_id?u.find(l=>l.cookie_id===n.cookie_id&&l.item_id===n.item_id):void 0,[n==null?void 0:n.cookie_id,n==null?void 0:n.item_id,u]),j=ss(_==null?void 0:_.is_multi_spec),D=(n==null?void 0:n.trigger_type)||"order_paid",ee=ae[D],ne=mt(n==null?void 0:n.config_json),E=(xe=n==null?void 0:n.variants)!=null&&xe.length?n.variants:[he()],W=o.useCallback((l="order_paid",d=t,b="")=>{const p=u.find(N=>N.cookie_id===d&&N.item_id===b),h=(p==null?void 0:p.item_title)||b;return{name:ye(l,h),trigger_type:l,cookie_id:d,item_id:b,item_title:(p==null?void 0:p.item_title)||"",item_keyword:h,card_group_id:0,priority:100,enabled:!0,config_json:l==="review_missing_timeout"?ce():"{}",actions:_e(l),variants:l==="review_missing_timeout"?[]:[he()]}},[u,t]),ue=o.useCallback(l=>{var b,p;const d=l.trigger_type||"order_paid";$({...l,trigger_type:d,config_json:d==="review_missing_timeout"?ce(l.config_json):l.config_json||"{}",actions:(b=l.actions)!=null&&b.length?l.actions.map(h=>({...h})):_e(d,l.card_group_id),variants:(p=l.variants)!=null&&p.length?l.variants.map(h=>({...h})):d==="review_missing_timeout"?[]:[he()]}),v(!0)},[]);o.useEffect(()=>{if(!w)return;let l=!1;return(async()=>{i("automation"),a(w.cookieId),C(!0);try{const[b,p,h]=await Promise.all([Dt(),dt(),ot().catch(f=>(console.warn("加载卡密库存失败,不阻断打开自动化规则",f),[]))]);if(l)return;r(b),A(p),y(h);const N=b.find(f=>f.cookie_id===w.cookieId&&f.item_id===w.itemId&&f.trigger_type==="order_paid");if(N)ue(N);else{const f=p.find(B=>B.cookie_id===w.cookieId&&B.item_id===w.itemId);$({...W("order_paid",w.cookieId,w.itemId),item_title:(f==null?void 0:f.item_title)||"",item_keyword:(f==null?void 0:f.item_title)||w.itemId,name:ye("order_paid",(f==null?void 0:f.item_title)||w.itemId)}),v(!0)}}catch(b){console.error("打开商品自动化规则失败",b),alert("无法加载该商品的自动化规则")}finally{l||(C(!1),G==null||G())}})(),(()=>{l=!0})},[W,w,G,ue,i,r,y,A,C,a]);const $e=o.useCallback((l="order_paid")=>{if(!t){alert("请先选择账号");return}$(W(l)),v(!0)},[W,t]),je=o.useCallback(l=>{var p,h,N,f,B;if(!n)return;const d=((h=(p=n.variants)==null?void 0:p.find(se=>se.card_id))==null?void 0:h.card_id)||((f=(N=n.actions)==null?void 0:N.find(se=>se.action_type==="send_card"))==null?void 0:f.card_id)||n.card_group_id||0,b=(_==null?void 0:_.item_title)||n.item_title||n.item_id||"";$({...n,trigger_type:l,name:lt(n.name)?ye(l,b):n.name,card_group_id:d,config_json:l==="review_missing_timeout"?ce(n.config_json):"{}",actions:_e(l,d),variants:l==="review_missing_timeout"?[]:(B=n.variants)!=null&&B.length?n.variants:[{...he(),card_id:d}]})},[n,_]),Me=o.useCallback(l=>{if(!n)return;const d=u.find(p=>p.cookie_id===(n.cookie_id||t)&&p.item_id===l),b=(d==null?void 0:d.item_title)||l;$({...n,item_id:l,item_title:(d==null?void 0:d.item_title)||"",item_keyword:b,name:lt(n.name)?ye(D,b):n.name})},[D,n,u,t]),pe=o.useCallback((l,d)=>{var p;if(!n)return;const b=E.map((h,N)=>N===l?{...h,...d}:h);$({...n,variants:b,card_group_id:((p=b[0])==null?void 0:p.card_id)||0})},[E,n]),Pe=o.useCallback(()=>{if(!n)return;const l=E[E.length-1];$({...n,variants:[...E,{...he(),spec_name:j&&(l==null?void 0:l.spec_name)||"",spec_value:j&&(l==null?void 0:l.spec_value)||""}]})},[E,n,j]),ve=o.useCallback(async()=>{var h,N,f,B,se;if(!n||K.submitting)return;const l=n.trigger_type||"order_paid";if(!n.cookie_id)return alert("请选择账号");const d=(h=n.variants)!=null&&h.length?n.variants:[];if(l!=="review_missing_timeout"){if(!d.length||d.some(k=>!k.card_id))return alert(l==="buyer_reviewed"?"请选择评价赠品卡密库存":"请选择发货卡密库存");if(j&&d.some(k=>!k.spec_name.trim()||!k.spec_value.trim()))return alert("多规格商品必须填写每一行的规格名称和规格值")}if(l==="review_missing_timeout"&&!(((f=(N=n.actions)==null?void 0:N.find(Le=>Le.action_type==="send_text"))==null?void 0:f.message_template)||"").trim())return alert("请填写求评价文案");const b=l==="review_missing_timeout"?[]:d.map(k=>({...k,spec_name:j?k.spec_name.trim():"",spec_value:j?k.spec_value.trim():"",delivery_count:Math.max(1,Number(k.delivery_count)||1),enabled:k.enabled!==!1}));le(qe(K));let p=!1;try{await st({...n,trigger_type:l,name:(n.name||"").trim()||ye(l,(_==null?void 0:_.item_title)||n.item_id||""),config_json:l==="review_missing_timeout"?ce(n.config_json):n.config_json||"{}",actions:(B=n.actions)!=null&&B.length?n.actions:_e(l,((se=b[0])==null?void 0:se.card_id)||n.card_group_id||0),variants:b}),v(!1),await Promise.all([m(),I()]),alert("保存成功"),p=!0}catch(k){console.error("保存自动化规则失败:",k),alert("保存失败:"+k.message)}finally{le(k=>Ve(k,p))}},[K,n,j,m,I,_]),g=o.useCallback(async l=>{if(confirm("确定删除该自动化规则吗?"))try{await Et(l),await m(),alert("删除成功")}catch(d){alert("删除失败:"+d.message)}},[m]),O=o.useCallback(async l=>{try{await st({...l,enabled:!l.enabled}),await m()}catch(d){alert("操作失败:"+d.message)}},[m]),S=o.useCallback(async(l,d)=>{if(confirm(d==="continue"?"确认外部动作已经执行成功,并跳到下一步吗?":d==="retry"?"确认外部动作没有执行,可以安全重试吗?错误判断可能造成重复发送。":"确认终止该自动化运行吗?"))try{await qt(l,d),await m()}catch(p){alert("处理失败:"+p.message)}},[m]),te=o.useCallback(async(l,d)=>{if(confirm(d==="retry"?"确认重新执行该任务吗?":"确认忽略并删除该异常任务吗?"))try{await Vt(l,d),await m()}catch(b){alert("处理失败:"+b.message)}},[m]),L=o.useCallback(()=>{if(!t)return alert("请先选择账号");z({keyword:"",reply_content:"",image_url:"",item_id:"",type:"text",match_type:"fuzzy",enabled:!0}),q(!0)},[t]),ie=o.useCallback(async()=>{var b,p,h;if(!R||!t||Y.submitting)return;const l=R.type==="image"?!!((b=R.image_url)!=null&&b.trim()):!!((p=R.reply_content)!=null&&p.trim());if(!((h=R.keyword)!=null&&h.trim())||!l)return alert("请填写关键词和回复内容");V(qe(Y));let d=!1;try{await Kt({...R,match_type:"fuzzy",enabled:!0},t),q(!1),await T(),alert("保存成功"),d=!0}catch(N){alert("保存失败:"+N.message)}finally{V(N=>Ve(N,d))}},[R,T,Y,t]),ge=o.useCallback(async l=>{if(!(!t||!confirm("确定删除该回复规则吗?")))try{await Ut(l,t),await T(),alert("删除成功")}catch(d){alert("删除失败:"+d.message)}},[T,t]),oe=o.useCallback(async(l=t)=>{if(!l)return alert("请先选择账号");try{const d=await Wt(l);P({cookie_id:l,enabled:d.enabled,reply_content:d.reply_content,reply_once:d.reply_once,reply_image_url:d.reply_image_url||""})}catch{P({cookie_id:l,enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""})}Q(!0)},[t]),me=o.useCallback(async()=>{if(H.submitting)return;if(!M.cookie_id)return alert("请先选择账号");if(M.enabled&&!M.reply_content.trim()&&!M.reply_image_url.trim())return alert("启用默认回复时,请填写回复内容或图片 URL");U(qe(H));let l=!1;try{await Zt(M.cookie_id,{enabled:M.enabled,reply_content:M.reply_content,reply_once:M.reply_once,reply_image_url:M.reply_image_url}),Q(!1),await J(),alert("保存成功"),l=!0}catch(d){alert("保存失败:"+d.message)}finally{U(d=>Ve(d,l))}},[M,H,J]),Ne=o.useCallback(async l=>{if(confirm("确定删除该账号默认回复吗?"))try{await Xt(l),await J(),alert("删除成功")}catch(d){alert("删除失败:"+d.message)}},[J]),be=o.useCallback(async l=>{if(confirm("确定清空该账号的默认回复记录吗?清空后可重新对所有会话使用“只回复一次”。"))try{await Qt(l),alert("清空成功")}catch(d){alert("清空失败:"+d.message)}},[]);return{showAutomationModal:F,setShowAutomationModal:v,showReplyModal:X,setShowReplyModal:q,showDefaultModal:re,setShowDefaultModal:Q,automationSubmitState:K,replySubmitState:Y,defaultReplySubmitState:H,editingAutomationRule:n,setEditingAutomationRule:$,editingReplyRule:R,setEditingReplyRule:z,defaultForm:M,setDefaultForm:P,selectedRuleItem:_,isMultiSpecRule:j,currentTrigger:D,currentMeta:ee,reviewConfig:ne,displayVariants:E,buildAutomationDraft:W,openAutomationRule:ue,openNewAutomationRule:$e,handleTriggerChange:je,handleAutomationItemChange:Me,updateVariant:pe,appendDeliveryContent:Pe,handleSaveAutomationRule:ve,handleDeleteAutomation:g,handleToggleAutomation:O,handleResolveRunIssue:S,handleResolveDeferredIssue:te,handleAddReplyRule:L,handleSaveReplyRule:ie,handleDeleteReply:ge,openDefaultReplyModal:oe,handleSaveDefaultReply:me,handleDeleteDefaultReply:Ne,handleClearDefaultReplyRecords:be}},os=({initialDeliveryTarget:t,onDeliveryTargetHandled:a})=>{var Xe,Qe;const[i,u]=o.useState("automation"),[r,y]=o.useState(""),[A,C]=o.useState(""),[m,I]=o.useState(""),[T,J]=o.useState(""),[w,G]=o.useState("all"),[F,v]=o.useState(1),[X,q]=o.useState(10),re=Yt({activeTab:i,selectedAccountId:r,automationTriggerFilter:T,automationStatusFilter:w,debouncedAutomationSearch:m,automationPage:F,automationPageSize:X,setSelectedAccountId:y,onAutomationPageChange:v}),{automationRules:Q,automationIssues:K,replyRules:le,defaultReplies:Y,accounts:V,cards:H,items:U,loading:n,setLoading:$,automationTotal:R,automationTotalPages:z,automationTriggerCounts:M,setAutomationRules:P,setCards:_,setItems:j,loadReferenceData:D,loadAutomationRules:ee,loadReplyRules:ne,loadDefaultReplies:E,refresh:W}=re,ue=as({selectedAccountId:r,setSelectedAccountId:y,setActiveTab:u,items:U,setAutomationRules:P,setCards:_,setItems:j,setLoading:$,loadAutomationRules:ee,loadReferenceData:D,loadReplyRules:ne,loadDefaultReplies:E,initialDeliveryTarget:t,onDeliveryTargetHandled:a}),{showAutomationModal:$e,setShowAutomationModal:je,showReplyModal:Me,setShowReplyModal:pe,showDefaultModal:Pe,setShowDefaultModal:ve,editingAutomationRule:g,setEditingAutomationRule:O,editingReplyRule:S,setEditingReplyRule:te,defaultForm:L,setDefaultForm:ie,selectedRuleItem:ge,isMultiSpecRule:oe,currentTrigger:me,currentMeta:Ne,reviewConfig:be,displayVariants:xe,openAutomationRule:l,openNewAutomationRule:d,handleTriggerChange:b,handleAutomationItemChange:p,updateVariant:h,appendDeliveryContent:N,handleSaveAutomationRule:f,handleDeleteAutomation:B,handleToggleAutomation:se,handleResolveRunIssue:k,handleResolveDeferredIssue:Le,handleAddReplyRule:xt,handleSaveReplyRule:ut,handleDeleteReply:pt,openDefaultReplyModal:We,handleSaveDefaultReply:gt,handleDeleteDefaultReply:bt,handleClearDefaultReplyRecords:ht}=ue;o.useEffect(()=>{const s=window.setTimeout(()=>{v(1),I(A.trim())},300);return(()=>window.clearTimeout(s))},[A]),o.useEffect(()=>{D().catch(s=>console.error("加载规则参考数据失败",s))},[D]),o.useEffect(()=>{W().catch(s=>console.error("刷新规则页面失败",s))},[W]);const Ie=o.useMemo(()=>Q.filter(s=>!r||s.cookie_id===r),[Q,r]),we=o.useMemo(()=>Pt(K,r),[K,r]),Ze=o.useMemo(()=>V.filter(s=>!r||s.id===r),[V,r]),yt=o.useMemo(()=>{if(z<=1)return[];const s=Math.max(1,Math.min(F-2,z-4)),c=Math.min(z,s+4);return Array.from({length:c-s+1},(x,de)=>s+de)},[F,z]),Fe=!!(A.trim()||T||w!=="all"),_t=()=>{C(""),I(""),J(""),G("all"),v(1)},ft=o.useMemo(()=>{const s=(g==null?void 0:g.cookie_id)||r;return U.filter(c=>c.cookie_id===s)},[g==null?void 0:g.cookie_id,U,r]),jt=i==="automation"?"新建自动化":i==="reply"?"新增关键词":"编辑默认回复";return e.jsxs("div",{className:"min-w-0 space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row justify-between xl:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"自动化规则"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"系统通知卡片只进入自动化判断;买家消息进入关键词、默认或 AI 回复。"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:flex-wrap gap-3",children:[e.jsxs("select",{value:r,onChange:(s=>{y(s.target.value),v(1)}),className:"ios-input w-full px-4 py-3 rounded-2xl text-sm sm:w-64",children:[e.jsx("option",{value:"",children:"全部账号"}),V.map(s=>e.jsx("option",{value:s.id,children:Re(s)},s.id))]}),e.jsxs("button",{onClick:W,className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 hover:bg-gray-200 text-gray-700 flex items-center justify-center gap-2 whitespace-nowrap transition-colors",children:[e.jsx(Te,{className:`w-4 h-4 ${n?"animate-spin":""}`}),"刷新"]}),e.jsxs("button",{onClick:i==="automation"?(()=>d("order_paid")):i==="reply"?xt:(()=>void We()),disabled:!r,className:"ios-btn-primary px-5 py-3 rounded-2xl text-sm font-extrabold flex items-center justify-center gap-2 whitespace-nowrap disabled:opacity-50",children:[e.jsx(Ye,{className:"w-4 h-4"}),jt]})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[{id:"automation",label:"交易自动化",icon:He},{id:"reply",label:"关键词回复",icon:wt},{id:"default",label:"账号默认回复",icon:et}].map(s=>{const c=s.icon;return e.jsxs("button",{onClick:(()=>u(s.id)),className:`inline-flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${i===s.id?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:[e.jsx(c,{className:"w-4 h-4"}),s.label]},s.id)})}),i==="automation"&&(we.runs.length>0||we.pending_tasks.length>0)&&e.jsx(It,{runs:we.runs,pendingTasks:we.pending_tasks,onResolveRun:((s,c)=>void k(s,c)),onResolveDeferredTask:((s,c)=>void Le(s,c))}),i==="automation"&&e.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-6 xl:grid-cols-[minmax(270px,0.72fr)_minmax(0,1.28fr)]",children:[e.jsxs("aside",{className:"min-w-0 space-y-4",children:[e.jsxs("div",{className:"bg-white rounded-xl p-5 border border-gray-100 shadow-sm",children:[e.jsx("h3",{className:"font-black text-gray-900 mb-1",children:"新建规则"}),e.jsx("p",{className:"text-sm text-gray-500 mb-4",children:"先选自动化类型,再配置对应动作。"}),e.jsx("div",{className:"space-y-3",children:Se.map(s=>{const c=ae[s],x=c.icon;return e.jsx("button",{type:"button",onClick:(()=>d(s)),className:`w-full text-left rounded-2xl border p-4 transition-colors ${nt(c.accent)}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/80 flex items-center justify-center shrink-0",children:e.jsx(x,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-extrabold",children:c.label}),e.jsx("div",{className:"text-xs opacity-75 mt-1 leading-5",children:c.description})]})]})},s)})})]}),e.jsxs("div",{className:"bg-white rounded-xl p-5 border border-gray-100 shadow-sm",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between gap-3",children:[e.jsx("h3",{className:"font-black text-gray-900",children:"筛选结果构成"}),e.jsxs("span",{className:"text-xs font-bold text-gray-400",children:["共 ",R," 条"]})]}),e.jsx("div",{className:"space-y-3",children:Se.map(s=>{const c=ae[s],x=c.icon;return e.jsxs("div",{className:"flex items-center justify-between rounded-2xl bg-gray-50 p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(x,{className:"w-4 h-4 text-gray-500"}),e.jsx("span",{className:"text-sm font-bold text-gray-700",children:c.shortLabel})]}),e.jsx("span",{className:"text-sm font-black text-gray-900",children:M[s]||0})]},s)})})]})]}),e.jsxs("section",{className:"min-w-0 space-y-4",children:[e.jsxs("div",{className:"rounded-xl border border-gray-100 bg-surface-muted p-4 shadow-sm",children:[e.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center",children:[e.jsxs("div",{className:"relative min-w-0 flex-1",children:[e.jsx(kt,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"搜索自动化规则",placeholder:"搜索规则名、商品名或商品 ID...",value:A,onChange:(s=>{C(s.target.value),v(1)}),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]}),e.jsxs("div",{className:"relative xl:w-52",children:[e.jsx(Ct,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsxs("select",{"aria-label":"按自动化类型筛选",value:T,onChange:(s=>{J(s.target.value),v(1)}),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部自动化类型"}),Se.map(s=>e.jsx("option",{value:s,children:ae[s].shortLabel},s))]})]}),e.jsxs("select",{"aria-label":"按启用状态筛选",value:w,onChange:(s=>{G(s.target.value),v(1)}),className:"ios-input rounded-xl border-none bg-white px-4 py-2.5 text-sm shadow-sm xl:w-36",children:[e.jsx("option",{value:"all",children:"全部状态"}),e.jsx("option",{value:"enabled",children:"已启用"}),e.jsx("option",{value:"disabled",children:"已禁用"})]}),Fe&&e.jsx("button",{type:"button",onClick:_t,className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-white text-gray-500 shadow-sm transition-colors hover:bg-gray-100 hover:text-gray-900",title:"清除筛选","aria-label":"清除筛选",children:e.jsx(ke,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"mt-3 flex items-center justify-between text-xs font-bold text-gray-400",children:[e.jsxs("span",{children:["找到 ",R," 条规则"]}),n&&e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Te,{className:"h-3.5 w-3.5 animate-spin"}),"正在更新"]})]})]}),n&&Ie.length===0?e.jsxs("div",{className:"flex min-h-56 items-center justify-center rounded-xl border border-gray-100 bg-white text-sm font-bold text-gray-400",children:[e.jsx(Te,{className:"mr-2 h-4 w-4 animate-spin"}),"正在加载规则"]}):Ie.length===0?e.jsxs("div",{className:"bg-white rounded-xl border border-dashed border-gray-200 p-16 text-center",children:[e.jsx(He,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),e.jsx("h3",{className:"text-xl font-black text-gray-900",children:Fe?"没有匹配的自动化规则":"还没有自动化规则"}),e.jsx("p",{className:"text-gray-500 mt-2",children:Fe?"调整或清除筛选条件后再试。":"从左侧选择一个模板开始配置。"})]}):Ie.map(s=>{const c=ae[s.trigger_type],x=c.icon;return e.jsx("article",{className:"bg-white rounded-xl border border-gray-100 p-5 shadow-sm hover:shadow-lg transition-all",children:e.jsxs("div",{className:"flex flex-col lg:flex-row lg:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-4 min-w-0",children:[e.jsx("div",{className:`w-12 h-12 rounded-2xl flex items-center justify-center shrink-0 ${nt(c.accent,!0)}`,children:e.jsx(x,{className:"w-5 h-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-2",children:[e.jsx("h3",{className:"text-lg font-black text-gray-900 truncate",children:s.name}),e.jsx("span",{className:`px-2.5 py-1 rounded-full text-xs font-bold ${ts(s.enabled)}`,children:s.enabled?"已启用":"已禁用"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-xs font-bold",children:[e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-gray-100 text-gray-600",children:c.label}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-gray-100 text-gray-600",children:s.item_title||s.item_id||"账号级规则"}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-blue-50 text-blue-700",children:es(s)})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("button",{onClick:(()=>l(s)),className:"px-4 py-2 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-700 text-sm font-bold flex items-center gap-2",children:[e.jsx(ze,{className:"w-4 h-4"}),"编辑"]}),e.jsx("button",{onClick:(()=>se(s)),className:`px-4 py-2 rounded-xl text-sm font-bold ${s.enabled?"bg-amber-50 text-amber-700 hover:bg-amber-100":"bg-emerald-50 text-emerald-700 hover:bg-emerald-100"}`,children:s.enabled?"禁用":"启用"}),e.jsx("button",{onClick:(()=>B(s.id)),className:"p-2.5 rounded-xl text-red-500 hover:bg-red-50",title:"删除",children:e.jsx(Ce,{className:"w-4 h-4"})})]})]})},s.id)}),R>0&&e.jsxs("div",{className:"flex flex-col gap-3 rounded-xl border border-gray-100 bg-white px-4 py-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3 text-sm font-medium text-gray-500",children:[e.jsxs("span",{children:["第 ",F," / ",Math.max(z,1)," 页"]}),e.jsx("span",{className:"h-4 w-px bg-gray-200"}),e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"sr-only",children:"每页显示数量"}),e.jsx("select",{value:X,onChange:(s=>{q(Number(s.target.value)),v(1)}),className:"ios-input rounded-lg border-none bg-gray-50 px-2.5 py-2 text-sm",children:[10,20,50].map(s=>e.jsxs("option",{value:s,children:[s," 条/页"]},s))})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{type:"button",disabled:F<=1||n,onClick:(()=>v(s=>Math.max(1,s-1))),className:"flex h-9 w-9 items-center justify-center rounded-lg bg-gray-50 text-gray-600 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-40","aria-label":"上一页",title:"上一页",children:e.jsx(St,{className:"h-4 w-4"})}),yt.map(s=>e.jsx("button",{type:"button",disabled:n,onClick:(()=>v(s)),className:`h-9 min-w-9 rounded-lg px-2 text-sm font-bold transition-colors ${s===F?"bg-brand text-white":"bg-gray-50 text-gray-600 hover:bg-gray-100"} disabled:cursor-not-allowed disabled:opacity-60`,"aria-label":`第 ${s} 页`,"aria-current":s===F?"page":void 0,children:s},s)),e.jsx("button",{type:"button",disabled:F>=z||n,onClick:(()=>v(s=>Math.min(z,s+1))),className:"flex h-9 w-9 items-center justify-center rounded-lg bg-gray-50 text-gray-600 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-40","aria-label":"下一页",title:"下一页",children:e.jsx(Rt,{className:"h-4 w-4"})})]})]})]})]}),i==="reply"&&e.jsxs("section",{className:"bg-white rounded-xl border border-gray-100 p-6 shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-blue-700 bg-blue-50 px-4 py-2 rounded-xl mb-5 w-fit",children:[e.jsx(Je,{className:"w-4 h-4"}),"这里只处理买家用户消息;系统通知不会进入关键词或 AI 回复。"]}),e.jsxs("div",{className:"space-y-3",children:[le.map(s=>e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between p-5 rounded-2xl border border-gray-100 bg-surface-subtle hover:bg-white hover:shadow-lg transition-all gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("span",{className:"px-3 py-1 bg-black text-white rounded-lg text-xs font-bold",children:"包含匹配"}),e.jsxs("h3",{className:"font-bold text-gray-900",children:["“",s.keyword,"”"]})]}),e.jsx("div",{className:"bg-white p-3 rounded-xl border border-gray-100 text-sm text-gray-600 leading-relaxed",children:s.type==="image"&&s.image_url?s.image_url:s.reply_content})]}),e.jsxs("div",{className:"flex items-center gap-3 border-t md:border-t-0 md:border-l border-gray-200 pt-4 md:pt-0 md:pl-6",children:[e.jsx("button",{onClick:(()=>{te({...s}),pe(!0)}),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(ze,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>pt(s.id)),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(Ce,{className:"w-5 h-5"})})]})]},s.id)),le.length===0&&e.jsx("div",{className:"text-center py-20 text-gray-400",children:"暂无关键词回复规则"})]})]}),i==="default"&&e.jsxs("section",{className:"bg-white rounded-xl border border-gray-100 p-6 shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-blue-700 bg-blue-50 px-4 py-2 rounded-xl mb-5 w-fit",children:[e.jsx(Je,{className:"w-4 h-4"}),"默认回复只处理买家用户消息;关键词未命中且 AI 未接管时才会使用。"]}),e.jsxs("div",{className:"space-y-3",children:[Ze.map(s=>{const c=Y[s.id],x=!!(c!=null&&c.enabled);return e.jsxs("div",{className:`flex flex-col md:flex-row md:items-center justify-between p-5 rounded-2xl border transition-all gap-4 ${x?"border-purple-100 bg-purple-50/50 hover:bg-white hover:shadow-lg":"border-gray-100 bg-surface-subtle hover:bg-white hover:shadow-lg"}`,children:[e.jsxs("div",{className:"flex items-center gap-4 min-w-0",children:[e.jsx("div",{className:`w-12 h-12 rounded-2xl flex items-center justify-center ${x?"bg-purple-600 text-white":"bg-gray-200 text-gray-400"}`,children:e.jsx(et,{className:"w-5 h-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("h3",{className:"font-bold text-gray-900 text-lg truncate",children:Re(s)}),e.jsx("span",{className:`px-2 py-0.5 rounded-lg text-xs font-bold ${x?"bg-green-100 text-green-700":"bg-gray-200 text-gray-500"}`,children:x?"已启用":"未启用"}),(c==null?void 0:c.reply_once)&&e.jsx("span",{className:"px-2 py-0.5 rounded-lg text-xs font-bold bg-purple-100 text-purple-700",children:"只回复一次"})]}),e.jsx("div",{className:"text-sm text-gray-600 line-clamp-2",children:x?c.reply_content||c.reply_image_url||"已配置默认回复":"未配置默认回复"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 border-t md:border-t-0 md:border-l border-gray-200 pt-4 md:pt-0 md:pl-6",children:[e.jsx("button",{onClick:(()=>void We(s.id)),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(ze,{className:"w-4 h-4"})}),x&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:(()=>void ht(s.id)),className:"px-3 py-2 text-xs font-bold text-blue-600 hover:bg-blue-50 rounded-xl transition-colors",children:"清空记录"}),e.jsx("button",{onClick:(()=>void bt(s.id)),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(Ce,{className:"w-5 h-5"})})]})]})]},s.id)}),Ze.length===0&&e.jsx("div",{className:"text-center py-20 text-gray-400",children:"暂无账号"})]})]}),$e&&g&&De.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"72rem",maxHeight:"92vh"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-black text-gray-900",children:g.id?"编辑自动化规则":"新建自动化规则"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:Ne.description})]}),e.jsx("button",{onClick:(()=>je(!1)),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",title:"关闭",children:e.jsx(ke,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[320px_1fr] min-h-0",children:[e.jsxs("aside",{className:"bg-slate-900 text-white p-5 overflow-y-auto",children:[e.jsx("div",{className:"text-xs font-bold text-slate-400 mb-3",children:"选择自动化类型"}),e.jsx("div",{className:"space-y-3",children:Se.map(s=>{const c=ae[s],x=c.icon,de=me===s;return e.jsx("button",{type:"button",onClick:(()=>b(s)),className:`w-full rounded-2xl p-4 text-left border transition-all ${de?"bg-white text-slate-950 border-white":"bg-white/5 text-white border-white/10 hover:bg-white/10"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(x,{className:`w-5 h-5 mt-0.5 ${de?"text-brand":"text-white"}`}),e.jsxs("div",{children:[e.jsx("div",{className:"font-black",children:c.label}),e.jsx("div",{className:`text-xs mt-1 leading-5 ${de?"text-gray-500":"text-gray-400"}`,children:c.description})]})]})},s)})}),e.jsxs("div",{className:"mt-6 rounded-2xl bg-white/5 border border-white/10 p-4",children:[e.jsx("div",{className:"text-xs font-bold text-slate-400 mb-3",children:"执行流程"}),e.jsx("div",{className:"space-y-3",children:Ne.flow.map((s,c)=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-white text-slate-950 text-xs font-black flex items-center justify-center",children:c+1}),e.jsx("span",{className:"text-sm font-bold text-gray-100",children:s})]},s))})]})]}),e.jsx("div",{className:"p-6 overflow-y-auto bg-surface-subtle",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(At,{className:"w-5 h-5 text-brand"}),e.jsx("h4",{className:"font-black text-gray-900",children:"生效范围"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"规则名称"}),e.jsx("input",{type:"text",value:g.name||"",onChange:(s=>O({...g,name:s.target.value})),placeholder:"不填时按类型和商品自动生成",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"闲鱼账号"}),e.jsxs("select",{value:g.cookie_id||"",onChange:(s=>O({...g,cookie_id:s.target.value,item_id:"",item_title:"",item_keyword:""})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"选择账号"}),V.map(s=>e.jsx("option",{value:s.id,children:Re(s)},s.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关联商品"}),e.jsxs("select",{value:g.item_id||"",onChange:(s=>p(s.target.value)),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级规则(不限定商品)"}),ft.map(s=>e.jsx("option",{value:s.item_id,children:s.item_title||s.item_id},`${s.cookie_id}-${s.item_id}`))]})]})]}),ge&&me!=="review_missing_timeout"&&e.jsxs("div",{className:"mt-4 rounded-2xl bg-gray-50 border border-gray-100 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-2",children:[e.jsx("span",{className:"px-3 py-1.5 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:ge.item_title||ge.item_id}),e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${oe?"bg-blue-50 text-blue-700":"bg-gray-100 text-gray-500"}`,children:oe?"多规格商品":"普通商品"}),e.jsx("span",{className:"px-3 py-1.5 rounded-lg text-xs font-bold bg-emerald-50 text-emerald-700",children:"按订单购买数量自动发货"})]}),e.jsx("p",{className:"text-xs leading-5 text-gray-500",children:"多规格状态来自闲鱼商品本身,发布后不能在这里修改;系统会在买家付款后读取订单详情,按实际购买规格和数量匹配下面的发货规则。"})]})]}),me!=="review_missing_timeout"?e.jsxs("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($t,{className:"w-5 h-5 text-brand"}),e.jsx("h4",{className:"font-black text-gray-900",children:me==="buyer_reviewed"?"赠品库存":"发货库存"})]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:oe?"每条发货内容绑定一个订单规格;同一规格可添加多条内容并全部发送。":"可添加多条发货内容,买家付款后会按顺序全部发送。"})]}),e.jsxs("button",{type:"button",onClick:N,className:"px-3 py-2 rounded-xl bg-gray-900 text-white text-xs font-bold hover:bg-black flex items-center gap-1.5",children:[e.jsx(Ye,{className:"w-3.5 h-3.5"}),"添加发货内容"]})]}),e.jsx("div",{className:"space-y-3",children:xe.map((s,c)=>e.jsxs("div",{className:`grid grid-cols-1 gap-3 items-end rounded-2xl border border-gray-200 p-4 ${oe?"md:grid-cols-[1fr_1fr_1.4fr_110px_40px]":"md:grid-cols-[1.4fr_110px_40px]"}`,children:[oe&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"规格名称"}),e.jsx("input",{value:s.spec_name,onChange:(x=>h(c,{spec_name:x.target.value})),className:"w-full ios-input px-3 py-2.5 rounded-lg",placeholder:"例如:套餐"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"规格值"}),e.jsx("input",{value:s.spec_value,onChange:(x=>h(c,{spec_value:x.target.value})),className:"w-full ios-input px-3 py-2.5 rounded-lg",placeholder:"例如:30天"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"卡密库存"}),e.jsxs("select",{value:s.card_id||"",onChange:(x=>h(c,{card_id:Number(x.target.value)})),className:"w-full ios-input px-3 py-2.5 rounded-lg",children:[e.jsx("option",{value:"",children:"请选择卡密库存"}),H.filter(x=>x.enabled&&x.type!=="api").map(x=>e.jsx("option",{value:x.id,children:x.name},x.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"每件份数"}),e.jsx("input",{type:"number",min:"1",max:"100",value:s.delivery_count,onChange:(x=>h(c,{delivery_count:Math.max(1,Number(x.target.value)||1)})),className:"w-full ios-input px-3 py-2.5 rounded-lg"})]}),e.jsxs("div",{className:"md:col-span-full flex flex-wrap items-center gap-3 rounded-xl bg-gray-50 px-3 py-2",children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs font-bold text-gray-600 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:s.delay_override===!0,onChange:(x=>h(c,{delay_override:x.target.checked})),className:"accent-brand"}),"覆盖卡密默认延时"]}),s.delay_override&&e.jsx("input",{type:"number",min:"0",max:"3600",value:s.delay_seconds||0,onChange:(x=>h(c,{delay_seconds:Math.max(0,Number(x.target.value)||0)})),className:"w-28 ios-input px-2 py-1.5 rounded-lg text-xs","aria-label":"动作延时秒数"}),e.jsx("span",{className:"text-xs text-gray-500",children:s.delay_override?`本动作延时 ${s.delay_seconds||0} 秒`:"使用卡密默认延时"})]}),e.jsx("button",{type:"button",disabled:xe.length===1,onClick:(()=>O({...g,variants:xe.filter((x,de)=>de!==c)})),className:"w-10 h-10 flex items-center justify-center rounded-lg text-red-500 hover:bg-red-50 disabled:opacity-25",title:"删除发货内容",children:e.jsx(Ce,{className:"w-4 h-4"})})]},s.id||c))})]}):e.jsxs("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(it,{className:"w-5 h-5 text-amber-600"}),e.jsx("h4",{className:"font-black text-gray-900",children:"求评价计划"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"发货后等待小时"}),e.jsx("input",{type:"number",min:"1",value:Number(be.after_shipped_hours||72),onChange:(s=>O({...g,config_json:ce(g.config_json,{after_shipped_hours:Math.max(1,Number(s.target.value)||72)})})),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"再次求评间隔小时"}),e.jsx("input",{type:"number",min:"1",value:Number(be.repeat_interval_hours||24),onChange:(s=>O({...g,config_json:ce(g.config_json,{repeat_interval_hours:Math.max(1,Number(s.target.value)||24)})})),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最多求评次数"}),e.jsx("input",{type:"number",min:"1",value:Number(be.max_attempts||1),onChange:(s=>O({...g,config_json:ce(g.config_json,{max_attempts:Math.max(1,Number(s.target.value)||1)})})),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"md:col-span-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"求评价文案"}),e.jsx("textarea",{value:((Qe=(Xe=g.actions)==null?void 0:Xe.find(s=>s.action_type==="send_text"))==null?void 0:Qe.message_template)||"",onChange:(s=>{var c;return O({...g,actions:((c=g.actions)!=null&&c.length?g.actions:_e("review_missing_timeout")).map(x=>x.action_type==="send_text"?{...x,message_template:s.target.value}:x)})}),className:"w-full ios-input px-4 py-3 rounded-xl h-28 resize-none"})]})]})]}),e.jsx("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-[180px_1fr] gap-4 items-end",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"优先级"}),e.jsx("p",{className:"text-xs text-gray-500 mb-2",children:"数字越小优先级越高;同一账号、商品和触发条件只执行优先级最高的一条规则。"}),e.jsx("input",{type:"number",value:g.priority||100,onChange:(s=>O({...g,priority:Number(s.target.value)||100})),min:"1",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("label",{className:"h-[48px] flex items-center gap-3 px-4 bg-gray-50 rounded-xl text-sm font-bold text-gray-800",children:[e.jsx("input",{type:"checkbox",checked:g.enabled!==!1,onChange:(s=>O({...g,enabled:s.target.checked})),className:"w-4 h-4 rounded"}),"启用规则"]})]})})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 bg-white flex gap-3",children:[e.jsx("button",{onClick:(()=>je(!1)),className:"flex-1 px-6 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200",children:"取消"}),e.jsxs("button",{onClick:f,className:"flex-1 ios-btn-primary px-6 py-3 rounded-2xl font-bold flex items-center justify-center gap-2",children:[e.jsx(tt,{className:"w-4 h-4"}),"保存自动化规则"]})]})]})}),document.body),Me&&S&&De.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:S.id?"编辑回复规则":"新增回复规则"}),e.jsx("button",{onClick:(()=>pe(!1)),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(ke,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关联商品"}),e.jsxs("select",{value:S.item_id||"",onChange:(s=>te({...S,item_id:s.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级回复"}),U.filter(s=>!r||s.cookie_id===r).map(s=>e.jsx("option",{value:s.item_id,children:s.item_title||s.item_id},`${s.cookie_id}-${s.item_id}`))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复类型"}),e.jsxs("select",{value:S.type||"text",onChange:(s=>{const c=s.target.value;te({...S,type:c,reply_content:c==="text"?S.reply_content:"",image_url:c==="image"?S.image_url:""})}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"text",children:"文字"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关键词"}),e.jsx("input",{type:"text",value:S.keyword||"",onChange:(s=>te({...S,keyword:s.target.value})),placeholder:"买家发送的关键词",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),S.type==="image"?e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{value:S.image_url||"",onChange:(s=>te({...S,image_url:s.target.value})),placeholder:"https://...",className:"w-full ios-input px-4 py-3 rounded-xl"})]}):e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复内容"}),e.jsx("textarea",{value:S.reply_content||"",onChange:(s=>te({...S,reply_content:s.target.value})),placeholder:"自动回复的内容",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none"})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx("button",{onClick:(()=>pe(!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:ut,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Mt,{className:"w-4 h-4"}),"保存规则"]})]})]})]})}),document.body),Pe&&De.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"账号默认回复"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"关键词和 AI 都未处理时,才会使用默认回复。"})]}),e.jsx("button",{onClick:(()=>ve(!1)),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",title:"关闭",children:e.jsx(ke,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"闲鱼账号"}),e.jsxs("select",{value:L.cookie_id,onChange:(s=>ie({...L,cookie_id:s.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"选择账号"}),V.map(s=>e.jsx("option",{value:s.id,children:Re(s)},s.id))]})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900",children:"启用默认回复"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1",children:"启用后,未命中关键词时自动发送"})]}),e.jsx("button",{type:"button",onClick:(()=>ie({...L,enabled:!L.enabled})),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${L.enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${L.enabled?"translate-x-7":"translate-x-1"}`})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复内容"}),e.jsx("textarea",{value:L.reply_content,onChange:(s=>ie({...L,reply_content:s.target.value})),placeholder:"输入默认回复内容",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复图片 URL(可选)"}),e.jsx("input",{type:"text",value:L.reply_image_url,onChange:(s=>ie({...L,reply_image_url:s.target.value})),placeholder:"https://example.com/image.jpg",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("label",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl text-sm font-bold text-gray-800",children:[e.jsxs("span",{children:["只回复一次",e.jsx("span",{className:"block text-xs text-gray-500 font-medium mt-1",children:"同一会话只发送一次默认回复"})]}),e.jsx("input",{type:"checkbox",checked:L.reply_once,onChange:(s=>ie({...L,reply_once:s.target.checked})),className:"w-4 h-4 rounded"})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx("button",{onClick:(()=>ve(!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:gt,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(tt,{className:"w-4 h-4"}),"保存默认回复"]})]})]})]})}),document.body)]})};export{os as default}; diff --git a/internal/webui/static/assets/Settings-fa7In0jk.js b/internal/webui/static/assets/Settings-DUEkZoEv.js similarity index 99% rename from internal/webui/static/assets/Settings-fa7In0jk.js rename to internal/webui/static/assets/Settings-DUEkZoEv.js index 06da5dc..dd53679 100644 --- a/internal/webui/static/assets/Settings-fa7In0jk.js +++ b/internal/webui/static/assets/Settings-DUEkZoEv.js @@ -1 +1 @@ -import{r,j as e}from"./react-vendor-C_od1ZSF.js";import{a as xe,g as re,p as le}from"./index-CFzx5gQT.js";import{f as ue,R as se,aa as pe,p as me,u as R,v as O,ab as he,s as ge,S as te,ac as ae,ad as ye,r as fe}from"./icons-vendor-CvzvbbIV.js";const ne="https://dashscope.aliyuncs.com/compatible-mode/v1",be=[{value:"debug",label:"Debug"},{value:"info",label:"Info"},{value:"warn",label:"Warn"},{value:"error",label:"Error"}],we=new Set(["ai_api_key_configured","smtp_password_configured","qq_reply_secret_key_configured","captcha.remote_secret_key_configured","smtp_server","smtp_port","smtp_user","smtp_password","smtp_from","smtp_from_name","smtp_from_address","registration_enabled","show_default_login_info","login_captcha_enabled","item_sync_enabled","item_sync_interval","item_sync_max_pages","default_reply"]),oe=new Set(["ai_api_key","smtp_password","qq_reply_secret_key","captcha.remote_secret_key"]),je=s=>{if("values"in s||"secrets"in s)return s;const a={},o={};for(const[d,h]of Object.entries(s))if(h!=null){if(oe.has(d)){o[d]=h===""?{action:"clear"}:{action:"replace",value:String(h)};continue}a[d]=h}return Object.keys(o).length>0?{values:a,secrets:o}:a},ve=s=>{const a={...s};for(const o of oe){const d=`${o}_configured`;d in a&&(a[d]=a[d]===!0||a[d]==="true")}if("renewal_log_retention_days"in a){const o=Number(a.renewal_log_retention_days);a.renewal_log_retention_days=Number.isFinite(o)?o:10}return a},_e=async(s,a)=>le("/api/v1/session/credentials",s,a),Ne=async s=>{const a=await re("/api/v1/settings/system",void 0,s),o=a.data||a.settings||a;return ve(o)},Se=async(s,a)=>le("/api/v1/settings/system",je(s),a),ke=async(s,a="",o)=>{const d=await xe("/api/v1/settings/ai-models",{base_url:s,api_key:a},o);return Array.isArray(d.models)?d.models:[]},Ce=async s=>re("/api/v1/session",void 0,s),Ee=s=>Object.fromEntries(Object.entries(s).filter(([a,o])=>!we.has(a)&&o!==void 0&&o!==null)),Ae=s=>s.new_username.trim().length<3?"用户名至少需要 3 个字符":s.current_password?s.new_password&&s.new_password.length<8?"新密码至少需要 8 个字符":s.new_password!==s.confirm_password?"两次输入的新密码不一致":"":"请输入当前密码确认身份",f=(s,a,o)=>s===a&&!o.aborted,D=s=>s instanceof Error&&s.message==="请求已取消",K=(s,a)=>s instanceof Error?s.message:a,Ie=(s="")=>({new_username:s,current_password:"",new_password:"",confirm_password:""}),T=(s,a)=>({type:s,text:a}),Me=()=>{const[s,a]=r.useState(null),[o,d]=r.useState(!1),[h,p]=r.useState(""),[S,A]=r.useState(!1),[P,k]=r.useState(""),[C,w]=r.useState([]),[j,I]=r.useState(!1),[M,x]=r.useState(""),[$,v]=r.useState(!1),[U,q]=r.useState(!1),[z,u]=r.useState(!1),[b,F]=r.useState(!1),[G,V]=r.useState(!1),[Y,_]=r.useState(!1),[L,y]=r.useState(null),[t,X]=r.useState(()=>Ie()),[ce,J]=r.useState("idle"),Z=r.useRef(null),ee=r.useRef(null),m=r.useRef(0),W=r.useRef(null);ee.current=s;const E=r.useCallback(()=>{var c;(c=W.current)==null||c.abort();const n=new AbortController;return W.current=n,m.current+=1,{controller:n,sequence:m.current}},[]),B=r.useCallback(async(n,c=!1,l)=>{const i=n||ee.current,g=(i==null?void 0:i.ai_api_url)||(i==null?void 0:i.ai_base_url)||ne;I(!0),x("");try{const N=await ke(g,(i==null?void 0:i.ai_api_key)||"",{signal:l});if(l!=null&&l.aborted)return;w(N),v(c&&N.length>0),!(i!=null&&i.ai_model)&&N.length>0&&a(Q=>Q&&{...Q,ai_model:N[0]})}catch(N){if(l!=null&&l.aborted||D(N))return;w([]),v(!1),x(K(N,"读取模型失败"))}finally{l!=null&&l.aborted||I(!1)}},[]),H=r.useCallback(()=>{const{controller:n,sequence:c}=E();d(!0),J("loading"),p(""),Promise.all([Ne({signal:n.signal}),Ce({signal:n.signal})]).then(([l,i])=>{f(m.current,c,n.signal)&&(a(l),i.username&&X(g=>({...g,new_username:i.username||""})),B(l,!1,n.signal),J("success"))}).catch(l=>{!f(m.current,c,n.signal)||D(l)||(a(null),p(K(l,"加载配置失败")),J("error"))}).finally(()=>{f(m.current,c,n.signal)&&d(!1)})},[E,B]);r.useEffect(()=>(H(),(()=>{var n;return(n=W.current)==null?void 0:n.abort()})),[H]),r.useEffect(()=>{const n=c=>{var l;(l=Z.current)!=null&&l.contains(c.target)||v(!1)};return document.addEventListener("mousedown",n),(()=>document.removeEventListener("mousedown",n))},[]);const ie=r.useCallback(async()=>{if(!s||S)return;const{controller:n,sequence:c}=E();A(!0),k("");try{if(await Se(Ee(s),{signal:n.signal}),!f(m.current,c,n.signal))return;window.alert("系统配置已保存")}catch(l){if(!f(m.current,c,n.signal)||D(l))return;k(K(l,"保存配置失败"))}finally{f(m.current,c,n.signal)&&A(!1)}},[E,S,s]),de=r.useCallback(async n=>{n.preventDefault(),y(null);const c=Ae(t);if(c){y(T("error",c));return}const{controller:l,sequence:i}=E();_(!0);try{const g=await _e({current_password:t.current_password,new_username:t.new_username.trim(),new_password:t.new_password||void 0},{signal:l.signal});if(!f(m.current,i,l.signal))return;if(!g.success){y(T("error",g.message||"登录凭据更新失败"));return}y(T("success",g.message||"登录凭据已更新")),window.setTimeout(()=>window.location.reload(),1400)}catch(g){if(!f(m.current,i,l.signal)||D(g))return;y(T("error",K(g,"登录凭据更新失败")))}finally{f(m.current,i,l.signal)&&_(!1)}},[E,t]);return{settings:s,loading:o,loadError:h,saving:S,saveError:P,aiModels:C,modelsLoading:j,modelError:M,modelDropdownOpen:$,showApiKey:U,showCaptchaSecret:z,showCurrentPassword:b,showNewPassword:G,credentialsSaving:Y,credentialsMessage:L,credentials:t,requestStatus:ce,modelPickerRef:Z,loadSettings:H,loadAIModels:((n,c)=>void B(n,c)),handleSave:ie,handleCredentialsSave:de,setSettings:a,setModelDropdownOpen:v,setShowApiKey:q,setShowCaptchaSecret:u,setShowCurrentPassword:F,setShowNewPassword:V,setCredentials:X,setCredentialsMessage:y}},Re=()=>{const{settings:s,loading:a,loadError:o,saving:d,saveError:h,aiModels:p,modelsLoading:S,modelError:A,modelDropdownOpen:P,showApiKey:k,showCaptchaSecret:C,showCurrentPassword:w,showNewPassword:j,credentialsSaving:I,credentialsMessage:M,credentials:x,modelPickerRef:$,loadSettings:v,loadAIModels:U,handleSave:q,handleCredentialsSave:z,setSettings:u,setModelDropdownOpen:b,setShowApiKey:F,setShowCaptchaSecret:G,setShowCurrentPassword:V,setShowNewPassword:Y,setCredentials:_}=Me();if(!s)return e.jsxs("div",{className:"p-8 text-center text-gray-400 space-y-3",children:[o||(a?"加载配置中...":"暂无配置"),!a&&o&&e.jsx("div",{children:e.jsx("button",{type:"button",className:"ios-btn-primary px-4 py-2 rounded-xl",onClick:v,children:"重新加载"})})]});const L=s.ai_model||"",y=p;return e.jsxs("div",{className:"max-w-6xl mx-auto space-y-8 animate-fade-in pb-24",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-12 h-12 bg-gray-100 rounded-2xl flex items-center justify-center",children:e.jsx(ue,{className:"w-6 h-6 text-gray-600"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-extrabold text-gray-900",children:"系统设置"}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm font-medium",children:"配置全局自动化规则与系统参数"})]})]}),e.jsxs("button",{onClick:v,className:"px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(se,{className:"w-4 h-4"}),"刷新"]})]}),h&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm text-red-700",children:[e.jsx("span",{children:h}),e.jsx("button",{type:"button",className:"font-bold underline",onClick:(()=>{}),children:"重试保存"})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsxs("div",{className:"space-y-8",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-gray-100 text-gray-600",children:e.jsx(pe,{className:"w-4 h-4"})}),"基础设置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white 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-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"日志输出等级"}),e.jsx("select",{value:s.log_level||"info",onChange:(t=>u({...s,log_level:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:be.map(t=>e.jsx("option",{value:t.value,children:t.label},t.value))}),e.jsx("p",{className:"text-xs text-gray-500",children:"等级越低输出越详细,Debug 适合排查问题"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"日志输出格式"}),e.jsxs("select",{value:s.log_format||"text",onChange:(t=>u({...s,log_format:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"text",children:"Text"}),e.jsx("option",{value:"json",children:"JSON"})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"JSON 适合接入集中式日志系统,保存后需重启服务生效"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"续期日志保留天数"}),e.jsx("input",{type:"number",value:s.renewal_log_retention_days??10,onChange:(t=>u({...s,renewal_log_retention_days:parseInt(t.target.value)||0})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"365"}),e.jsx("p",{className:"text-xs text-gray-500",children:"0 表示不自动清理续期日志"})]})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-brand text-white",children:e.jsx(me,{className:"w-4 h-4"})}),"AI 智能回复配置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"API 地址"}),e.jsx("input",{type:"text",value:s.ai_api_url||ne,onChange:(t=>u({...s,ai_api_url:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"https://api.openai.com/v1"}),e.jsx("p",{className:"text-xs text-gray-500",children:"无需补全 /chat/completions"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"API Key"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:k?"text":"password",value:s.ai_api_key||"",onChange:(t=>u({...s,ai_api_key:t.target.value})),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl font-mono text-sm",placeholder:s.ai_api_key_configured?"已配置,如需替换请输入新密钥":"sk-..."}),e.jsx("button",{type:"button",onClick:(()=>F(!k)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:k?e.jsx(R,{className:"w-4 h-4"}):e.jsx(O,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"模型"}),e.jsxs("div",{ref:$,className:"relative flex flex-col sm:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx("input",{value:L,onFocus:(()=>p.length>0&&b(!0)),onChange:(t=>{u({...s,ai_model:t.target.value}),p.length>0&&b(!0)}),onKeyDown:(t=>{t.key==="Escape"&&b(!1),t.key==="ArrowDown"&&p.length>0&&b(!0)}),className:"w-full ios-input px-4 py-3 pr-10 rounded-xl",placeholder:"从接口读取或手动输入模型名"}),e.jsx("button",{type:"button",onClick:(()=>p.length>0&&b(t=>!t)),disabled:p.length===0,className:"absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 disabled:opacity-30","aria-label":"展开模型列表",children:e.jsx(he,{className:`w-4 h-4 transition-transform ${P?"rotate-180":""}`})}),P&&e.jsx("div",{className:"absolute left-0 right-0 top-[calc(100%+6px)] z-40 max-h-64 overflow-y-auto rounded-xl border border-gray-200 bg-white shadow-xl shadow-gray-200/70 py-1",children:y.length>0?y.map(t=>e.jsxs("button",{type:"button",onClick:(()=>{u({...s,ai_model:t}),b(!1)}),className:"w-full px-4 py-2.5 text-left text-sm text-gray-700 hover:bg-blue-50 hover:text-brand flex items-center justify-between gap-3",children:[e.jsx("span",{className:"truncate",children:t}),t===L&&e.jsx(ge,{className:"w-4 h-4 shrink-0 text-brand"})]},t)):e.jsx("div",{className:"px-4 py-3 text-sm text-gray-400",children:"没有匹配的模型"})})]}),e.jsxs("button",{type:"button",onClick:(()=>U(void 0,!0)),disabled:S,className:"px-4 py-3 rounded-xl bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-60 font-bold flex items-center justify-center gap-2 whitespace-nowrap",children:[e.jsx(se,{className:`w-4 h-4 ${S?"animate-spin":""}`}),"读取模型"]})]}),A?e.jsx("p",{className:"text-xs text-red-500",children:A}):e.jsx("p",{className:"text-xs text-gray-500",children:p.length>0?`已从当前 API 地址读取到 ${p.length} 个模型`:"模型列表从当前 API 地址读取,也可以手动输入模型名"})]}),e.jsxs("div",{className:"p-3 bg-blue-50 rounded-xl text-xs text-blue-700",children:[e.jsx("strong",{children:"常见 AI 服务:"}),e.jsxs("ul",{className:"list-disc list-inside mt-1 space-y-0.5",children:[e.jsx("li",{children:"阿里云通义千问: https://dashscope.aliyuncs.com/compatible-mode/v1"}),e.jsx("li",{children:"OpenAI: https://api.openai.com/v1"})]})]})]})]})]}),e.jsxs("div",{className:"space-y-8",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-amber-500 text-white",children:e.jsx(te,{className:"w-4 h-4"})}),"远程过滑块配置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"服务地址"}),e.jsx("input",{type:"url",value:s["captcha.remote_service_url"]||"",onChange:(t=>u({...s,"captcha.remote_service_url":t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"https://example.com/internal/captcha/solve"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"服务秘钥"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:C?"text":"password",value:s["captcha.remote_secret_key"]||"",onChange:(t=>u({...s,"captcha.remote_secret_key":t.target.value})),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl font-mono text-sm",autoComplete:"off",placeholder:s["captcha.remote_secret_key_configured"]?"已配置,如需替换请输入新密钥":"请输入服务秘钥"}),e.jsx("button",{type:"button",onClick:(()=>G(!C)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:C?"隐藏秘钥":"显示秘钥",children:C?e.jsx(R,{className:"w-4 h-4"}):e.jsx(O,{className:"w-4 h-4"})})]})]}),e.jsxs("label",{className:"flex items-start gap-3 rounded-xl bg-amber-50 p-4 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:String(s["captcha.remote_pass_cookies"]||"").toLowerCase()==="true",onChange:(t=>u({...s,"captcha.remote_pass_cookies":t.target.checked})),className:"mt-0.5 w-4 h-4 rounded border-gray-300"}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-bold text-amber-900",children:"允许向远程服务传递账号 Cookie"}),e.jsx("span",{className:"block mt-1 text-xs text-amber-700",children:"默认关闭。仅在信任远程服务且需要由其自动重取过期验证链接时开启。"})]})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"配置地址和秘钥后优先调用远程服务;只有网络不可用或超时才回退本机引擎,远程明确返回失败时不会重复触发本机验证。"})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-gray-900 text-white",children:e.jsx(ae,{className:"w-4 h-4"})}),"登录凭据"]}),e.jsxs("form",{onSubmit:z,className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"登录用户名"}),e.jsxs("div",{className:"relative",children:[e.jsx(ye,{className:"absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx("input",{type:"text",value:x.new_username,onChange:(t=>_({...x,new_username:t.target.value})),className:"w-full ios-input pl-11 pr-4 py-3 rounded-xl text-sm",autoComplete:"username"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"当前密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:w?"text":"password",value:x.current_password,onChange:(t=>_({...x,current_password:t.target.value})),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm",placeholder:"用于确认当前身份",autoComplete:"current-password"}),e.jsx("button",{type:"button",onClick:(()=>V(!w)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:w?"隐藏密码":"显示密码",children:w?e.jsx(R,{className:"w-4 h-4"}):e.jsx(O,{className:"w-4 h-4"})})]})]}),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-800",children:"新密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:j?"text":"password",value:x.new_password,onChange:(t=>_({...x,new_password:t.target.value})),className:"w-full ios-input px-4 py-3 pr-11 rounded-xl text-sm",placeholder:"不修改则留空",autoComplete:"new-password"}),e.jsx("button",{type:"button",onClick:(()=>Y(!j)),className:"absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:j?"隐藏密码":"显示密码",children:j?e.jsx(R,{className:"w-4 h-4"}):e.jsx(O,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"确认新密码"}),e.jsx("input",{type:j?"text":"password",value:x.confirm_password,onChange:(t=>_({...x,confirm_password:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"再次输入新密码",autoComplete:"new-password"})]})]}),M&&e.jsxs("div",{className:`flex items-start gap-2 rounded-xl px-3 py-2.5 text-sm font-medium ${M.type==="success"?"bg-green-50 text-green-700":"bg-red-50 text-red-700"}`,children:[e.jsx(te,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),e.jsx("span",{children:M.text})]}),e.jsxs("button",{type:"submit",disabled:I||!x.new_username||!x.current_password,className:"w-full bg-gray-900 hover:bg-black text-white px-5 py-3 rounded-xl font-bold text-sm flex items-center justify-center gap-2 transition-colors disabled:opacity-40",children:[e.jsx(ae,{className:"w-4 h-4"}),I?"正在更新...":"更新登录凭据"]})]})]})]})]}),e.jsx("div",{className:"fixed bottom-10 right-10 z-30",children:e.jsxs("button",{onClick:q,disabled:d,className:"ios-btn-primary px-10 py-5 rounded-xl text-lg shadow-2xl shadow-blue-200 flex items-center gap-3 transform hover:scale-105 active:scale-95 transition-all disabled:opacity-70",children:[e.jsx(fe,{className:"w-6 h-6"}),d?"保存中...":"保存所有配置"]})})]})};export{Re as default}; +import{r,j as e}from"./react-vendor-C_od1ZSF.js";import{a as xe,g as re,p as le}from"./index-hByDAHGj.js";import{f as ue,R as se,aa as pe,p as me,u as R,v as O,ab as he,s as ge,S as te,ac as ae,ad as ye,r as fe}from"./icons-vendor-CvzvbbIV.js";const ne="https://dashscope.aliyuncs.com/compatible-mode/v1",be=[{value:"debug",label:"Debug"},{value:"info",label:"Info"},{value:"warn",label:"Warn"},{value:"error",label:"Error"}],we=new Set(["ai_api_key_configured","smtp_password_configured","qq_reply_secret_key_configured","captcha.remote_secret_key_configured","smtp_server","smtp_port","smtp_user","smtp_password","smtp_from","smtp_from_name","smtp_from_address","registration_enabled","show_default_login_info","login_captcha_enabled","item_sync_enabled","item_sync_interval","item_sync_max_pages","default_reply"]),oe=new Set(["ai_api_key","smtp_password","qq_reply_secret_key","captcha.remote_secret_key"]),je=s=>{if("values"in s||"secrets"in s)return s;const a={},o={};for(const[d,h]of Object.entries(s))if(h!=null){if(oe.has(d)){o[d]=h===""?{action:"clear"}:{action:"replace",value:String(h)};continue}a[d]=h}return Object.keys(o).length>0?{values:a,secrets:o}:a},ve=s=>{const a={...s};for(const o of oe){const d=`${o}_configured`;d in a&&(a[d]=a[d]===!0||a[d]==="true")}if("renewal_log_retention_days"in a){const o=Number(a.renewal_log_retention_days);a.renewal_log_retention_days=Number.isFinite(o)?o:10}return a},_e=async(s,a)=>le("/api/v1/session/credentials",s,a),Ne=async s=>{const a=await re("/api/v1/settings/system",void 0,s),o=a.data||a.settings||a;return ve(o)},Se=async(s,a)=>le("/api/v1/settings/system",je(s),a),ke=async(s,a="",o)=>{const d=await xe("/api/v1/settings/ai-models",{base_url:s,api_key:a},o);return Array.isArray(d.models)?d.models:[]},Ce=async s=>re("/api/v1/session",void 0,s),Ee=s=>Object.fromEntries(Object.entries(s).filter(([a,o])=>!we.has(a)&&o!==void 0&&o!==null)),Ae=s=>s.new_username.trim().length<3?"用户名至少需要 3 个字符":s.current_password?s.new_password&&s.new_password.length<8?"新密码至少需要 8 个字符":s.new_password!==s.confirm_password?"两次输入的新密码不一致":"":"请输入当前密码确认身份",f=(s,a,o)=>s===a&&!o.aborted,D=s=>s instanceof Error&&s.message==="请求已取消",K=(s,a)=>s instanceof Error?s.message:a,Ie=(s="")=>({new_username:s,current_password:"",new_password:"",confirm_password:""}),T=(s,a)=>({type:s,text:a}),Me=()=>{const[s,a]=r.useState(null),[o,d]=r.useState(!1),[h,p]=r.useState(""),[S,A]=r.useState(!1),[P,k]=r.useState(""),[C,w]=r.useState([]),[j,I]=r.useState(!1),[M,x]=r.useState(""),[$,v]=r.useState(!1),[U,q]=r.useState(!1),[z,u]=r.useState(!1),[b,F]=r.useState(!1),[G,V]=r.useState(!1),[Y,_]=r.useState(!1),[L,y]=r.useState(null),[t,X]=r.useState(()=>Ie()),[ce,J]=r.useState("idle"),Z=r.useRef(null),ee=r.useRef(null),m=r.useRef(0),W=r.useRef(null);ee.current=s;const E=r.useCallback(()=>{var c;(c=W.current)==null||c.abort();const n=new AbortController;return W.current=n,m.current+=1,{controller:n,sequence:m.current}},[]),B=r.useCallback(async(n,c=!1,l)=>{const i=n||ee.current,g=(i==null?void 0:i.ai_api_url)||(i==null?void 0:i.ai_base_url)||ne;I(!0),x("");try{const N=await ke(g,(i==null?void 0:i.ai_api_key)||"",{signal:l});if(l!=null&&l.aborted)return;w(N),v(c&&N.length>0),!(i!=null&&i.ai_model)&&N.length>0&&a(Q=>Q&&{...Q,ai_model:N[0]})}catch(N){if(l!=null&&l.aborted||D(N))return;w([]),v(!1),x(K(N,"读取模型失败"))}finally{l!=null&&l.aborted||I(!1)}},[]),H=r.useCallback(()=>{const{controller:n,sequence:c}=E();d(!0),J("loading"),p(""),Promise.all([Ne({signal:n.signal}),Ce({signal:n.signal})]).then(([l,i])=>{f(m.current,c,n.signal)&&(a(l),i.username&&X(g=>({...g,new_username:i.username||""})),B(l,!1,n.signal),J("success"))}).catch(l=>{!f(m.current,c,n.signal)||D(l)||(a(null),p(K(l,"加载配置失败")),J("error"))}).finally(()=>{f(m.current,c,n.signal)&&d(!1)})},[E,B]);r.useEffect(()=>(H(),(()=>{var n;return(n=W.current)==null?void 0:n.abort()})),[H]),r.useEffect(()=>{const n=c=>{var l;(l=Z.current)!=null&&l.contains(c.target)||v(!1)};return document.addEventListener("mousedown",n),(()=>document.removeEventListener("mousedown",n))},[]);const ie=r.useCallback(async()=>{if(!s||S)return;const{controller:n,sequence:c}=E();A(!0),k("");try{if(await Se(Ee(s),{signal:n.signal}),!f(m.current,c,n.signal))return;window.alert("系统配置已保存")}catch(l){if(!f(m.current,c,n.signal)||D(l))return;k(K(l,"保存配置失败"))}finally{f(m.current,c,n.signal)&&A(!1)}},[E,S,s]),de=r.useCallback(async n=>{n.preventDefault(),y(null);const c=Ae(t);if(c){y(T("error",c));return}const{controller:l,sequence:i}=E();_(!0);try{const g=await _e({current_password:t.current_password,new_username:t.new_username.trim(),new_password:t.new_password||void 0},{signal:l.signal});if(!f(m.current,i,l.signal))return;if(!g.success){y(T("error",g.message||"登录凭据更新失败"));return}y(T("success",g.message||"登录凭据已更新")),window.setTimeout(()=>window.location.reload(),1400)}catch(g){if(!f(m.current,i,l.signal)||D(g))return;y(T("error",K(g,"登录凭据更新失败")))}finally{f(m.current,i,l.signal)&&_(!1)}},[E,t]);return{settings:s,loading:o,loadError:h,saving:S,saveError:P,aiModels:C,modelsLoading:j,modelError:M,modelDropdownOpen:$,showApiKey:U,showCaptchaSecret:z,showCurrentPassword:b,showNewPassword:G,credentialsSaving:Y,credentialsMessage:L,credentials:t,requestStatus:ce,modelPickerRef:Z,loadSettings:H,loadAIModels:((n,c)=>void B(n,c)),handleSave:ie,handleCredentialsSave:de,setSettings:a,setModelDropdownOpen:v,setShowApiKey:q,setShowCaptchaSecret:u,setShowCurrentPassword:F,setShowNewPassword:V,setCredentials:X,setCredentialsMessage:y}},Re=()=>{const{settings:s,loading:a,loadError:o,saving:d,saveError:h,aiModels:p,modelsLoading:S,modelError:A,modelDropdownOpen:P,showApiKey:k,showCaptchaSecret:C,showCurrentPassword:w,showNewPassword:j,credentialsSaving:I,credentialsMessage:M,credentials:x,modelPickerRef:$,loadSettings:v,loadAIModels:U,handleSave:q,handleCredentialsSave:z,setSettings:u,setModelDropdownOpen:b,setShowApiKey:F,setShowCaptchaSecret:G,setShowCurrentPassword:V,setShowNewPassword:Y,setCredentials:_}=Me();if(!s)return e.jsxs("div",{className:"p-8 text-center text-gray-400 space-y-3",children:[o||(a?"加载配置中...":"暂无配置"),!a&&o&&e.jsx("div",{children:e.jsx("button",{type:"button",className:"ios-btn-primary px-4 py-2 rounded-xl",onClick:v,children:"重新加载"})})]});const L=s.ai_model||"",y=p;return e.jsxs("div",{className:"max-w-6xl mx-auto space-y-8 animate-fade-in pb-24",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-12 h-12 bg-gray-100 rounded-2xl flex items-center justify-center",children:e.jsx(ue,{className:"w-6 h-6 text-gray-600"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-extrabold text-gray-900",children:"系统设置"}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm font-medium",children:"配置全局自动化规则与系统参数"})]})]}),e.jsxs("button",{onClick:v,className:"px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(se,{className:"w-4 h-4"}),"刷新"]})]}),h&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm text-red-700",children:[e.jsx("span",{children:h}),e.jsx("button",{type:"button",className:"font-bold underline",onClick:(()=>{}),children:"重试保存"})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsxs("div",{className:"space-y-8",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-gray-100 text-gray-600",children:e.jsx(pe,{className:"w-4 h-4"})}),"基础设置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white 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-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"日志输出等级"}),e.jsx("select",{value:s.log_level||"info",onChange:(t=>u({...s,log_level:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:be.map(t=>e.jsx("option",{value:t.value,children:t.label},t.value))}),e.jsx("p",{className:"text-xs text-gray-500",children:"等级越低输出越详细,Debug 适合排查问题"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"日志输出格式"}),e.jsxs("select",{value:s.log_format||"text",onChange:(t=>u({...s,log_format:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"text",children:"Text"}),e.jsx("option",{value:"json",children:"JSON"})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"JSON 适合接入集中式日志系统,保存后需重启服务生效"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"续期日志保留天数"}),e.jsx("input",{type:"number",value:s.renewal_log_retention_days??10,onChange:(t=>u({...s,renewal_log_retention_days:parseInt(t.target.value)||0})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"365"}),e.jsx("p",{className:"text-xs text-gray-500",children:"0 表示不自动清理续期日志"})]})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-brand text-white",children:e.jsx(me,{className:"w-4 h-4"})}),"AI 智能回复配置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"API 地址"}),e.jsx("input",{type:"text",value:s.ai_api_url||ne,onChange:(t=>u({...s,ai_api_url:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"https://api.openai.com/v1"}),e.jsx("p",{className:"text-xs text-gray-500",children:"无需补全 /chat/completions"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"API Key"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:k?"text":"password",value:s.ai_api_key||"",onChange:(t=>u({...s,ai_api_key:t.target.value})),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl font-mono text-sm",placeholder:s.ai_api_key_configured?"已配置,如需替换请输入新密钥":"sk-..."}),e.jsx("button",{type:"button",onClick:(()=>F(!k)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:k?e.jsx(R,{className:"w-4 h-4"}):e.jsx(O,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"模型"}),e.jsxs("div",{ref:$,className:"relative flex flex-col sm:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx("input",{value:L,onFocus:(()=>p.length>0&&b(!0)),onChange:(t=>{u({...s,ai_model:t.target.value}),p.length>0&&b(!0)}),onKeyDown:(t=>{t.key==="Escape"&&b(!1),t.key==="ArrowDown"&&p.length>0&&b(!0)}),className:"w-full ios-input px-4 py-3 pr-10 rounded-xl",placeholder:"从接口读取或手动输入模型名"}),e.jsx("button",{type:"button",onClick:(()=>p.length>0&&b(t=>!t)),disabled:p.length===0,className:"absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 disabled:opacity-30","aria-label":"展开模型列表",children:e.jsx(he,{className:`w-4 h-4 transition-transform ${P?"rotate-180":""}`})}),P&&e.jsx("div",{className:"absolute left-0 right-0 top-[calc(100%+6px)] z-40 max-h-64 overflow-y-auto rounded-xl border border-gray-200 bg-white shadow-xl shadow-gray-200/70 py-1",children:y.length>0?y.map(t=>e.jsxs("button",{type:"button",onClick:(()=>{u({...s,ai_model:t}),b(!1)}),className:"w-full px-4 py-2.5 text-left text-sm text-gray-700 hover:bg-blue-50 hover:text-brand flex items-center justify-between gap-3",children:[e.jsx("span",{className:"truncate",children:t}),t===L&&e.jsx(ge,{className:"w-4 h-4 shrink-0 text-brand"})]},t)):e.jsx("div",{className:"px-4 py-3 text-sm text-gray-400",children:"没有匹配的模型"})})]}),e.jsxs("button",{type:"button",onClick:(()=>U(void 0,!0)),disabled:S,className:"px-4 py-3 rounded-xl bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-60 font-bold flex items-center justify-center gap-2 whitespace-nowrap",children:[e.jsx(se,{className:`w-4 h-4 ${S?"animate-spin":""}`}),"读取模型"]})]}),A?e.jsx("p",{className:"text-xs text-red-500",children:A}):e.jsx("p",{className:"text-xs text-gray-500",children:p.length>0?`已从当前 API 地址读取到 ${p.length} 个模型`:"模型列表从当前 API 地址读取,也可以手动输入模型名"})]}),e.jsxs("div",{className:"p-3 bg-blue-50 rounded-xl text-xs text-blue-700",children:[e.jsx("strong",{children:"常见 AI 服务:"}),e.jsxs("ul",{className:"list-disc list-inside mt-1 space-y-0.5",children:[e.jsx("li",{children:"阿里云通义千问: https://dashscope.aliyuncs.com/compatible-mode/v1"}),e.jsx("li",{children:"OpenAI: https://api.openai.com/v1"})]})]})]})]})]}),e.jsxs("div",{className:"space-y-8",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-amber-500 text-white",children:e.jsx(te,{className:"w-4 h-4"})}),"远程过滑块配置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"服务地址"}),e.jsx("input",{type:"url",value:s["captcha.remote_service_url"]||"",onChange:(t=>u({...s,"captcha.remote_service_url":t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"https://example.com/internal/captcha/solve"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"服务秘钥"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:C?"text":"password",value:s["captcha.remote_secret_key"]||"",onChange:(t=>u({...s,"captcha.remote_secret_key":t.target.value})),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl font-mono text-sm",autoComplete:"off",placeholder:s["captcha.remote_secret_key_configured"]?"已配置,如需替换请输入新密钥":"请输入服务秘钥"}),e.jsx("button",{type:"button",onClick:(()=>G(!C)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:C?"隐藏秘钥":"显示秘钥",children:C?e.jsx(R,{className:"w-4 h-4"}):e.jsx(O,{className:"w-4 h-4"})})]})]}),e.jsxs("label",{className:"flex items-start gap-3 rounded-xl bg-amber-50 p-4 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:String(s["captcha.remote_pass_cookies"]||"").toLowerCase()==="true",onChange:(t=>u({...s,"captcha.remote_pass_cookies":t.target.checked})),className:"mt-0.5 w-4 h-4 rounded border-gray-300"}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-bold text-amber-900",children:"允许向远程服务传递账号 Cookie"}),e.jsx("span",{className:"block mt-1 text-xs text-amber-700",children:"默认关闭。仅在信任远程服务且需要由其自动重取过期验证链接时开启。"})]})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"配置地址和秘钥后优先调用远程服务;只有网络不可用或超时才回退本机引擎,远程明确返回失败时不会重复触发本机验证。"})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-gray-900 text-white",children:e.jsx(ae,{className:"w-4 h-4"})}),"登录凭据"]}),e.jsxs("form",{onSubmit:z,className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"登录用户名"}),e.jsxs("div",{className:"relative",children:[e.jsx(ye,{className:"absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx("input",{type:"text",value:x.new_username,onChange:(t=>_({...x,new_username:t.target.value})),className:"w-full ios-input pl-11 pr-4 py-3 rounded-xl text-sm",autoComplete:"username"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"当前密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:w?"text":"password",value:x.current_password,onChange:(t=>_({...x,current_password:t.target.value})),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm",placeholder:"用于确认当前身份",autoComplete:"current-password"}),e.jsx("button",{type:"button",onClick:(()=>V(!w)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:w?"隐藏密码":"显示密码",children:w?e.jsx(R,{className:"w-4 h-4"}):e.jsx(O,{className:"w-4 h-4"})})]})]}),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-800",children:"新密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:j?"text":"password",value:x.new_password,onChange:(t=>_({...x,new_password:t.target.value})),className:"w-full ios-input px-4 py-3 pr-11 rounded-xl text-sm",placeholder:"不修改则留空",autoComplete:"new-password"}),e.jsx("button",{type:"button",onClick:(()=>Y(!j)),className:"absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:j?"隐藏密码":"显示密码",children:j?e.jsx(R,{className:"w-4 h-4"}):e.jsx(O,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"确认新密码"}),e.jsx("input",{type:j?"text":"password",value:x.confirm_password,onChange:(t=>_({...x,confirm_password:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"再次输入新密码",autoComplete:"new-password"})]})]}),M&&e.jsxs("div",{className:`flex items-start gap-2 rounded-xl px-3 py-2.5 text-sm font-medium ${M.type==="success"?"bg-green-50 text-green-700":"bg-red-50 text-red-700"}`,children:[e.jsx(te,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),e.jsx("span",{children:M.text})]}),e.jsxs("button",{type:"submit",disabled:I||!x.new_username||!x.current_password,className:"w-full bg-gray-900 hover:bg-black text-white px-5 py-3 rounded-xl font-bold text-sm flex items-center justify-center gap-2 transition-colors disabled:opacity-40",children:[e.jsx(ae,{className:"w-4 h-4"}),I?"正在更新...":"更新登录凭据"]})]})]})]})]}),e.jsx("div",{className:"fixed bottom-10 right-10 z-30",children:e.jsxs("button",{onClick:q,disabled:d,className:"ios-btn-primary px-10 py-5 rounded-xl text-lg shadow-2xl shadow-blue-200 flex items-center gap-3 transform hover:scale-105 active:scale-95 transition-all disabled:opacity-70",children:[e.jsx(fe,{className:"w-6 h-6"}),d?"保存中...":"保存所有配置"]})})]})};export{Re as default}; diff --git a/internal/webui/static/assets/index-CFzx5gQT.js b/internal/webui/static/assets/index-hByDAHGj.js similarity index 95% rename from internal/webui/static/assets/index-CFzx5gQT.js rename to internal/webui/static/assets/index-hByDAHGj.js index 33ab584..16357a7 100644 --- a/internal/webui/static/assets/index-CFzx5gQT.js +++ b/internal/webui/static/assets/index-hByDAHGj.js @@ -1,2 +1,2 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Dashboard-RK26q9J7.js","assets/react-vendor-C_od1ZSF.js","assets/dateTime-DDi7rqpW.js","assets/contract-COFcZjyb.js","assets/icons-vendor-CvzvbbIV.js","assets/charts-vendor-BxxJOyEX.js","assets/vendor-D-Edl3pr.js","assets/AccountList-fhDk6BDY.js","assets/OrderList-CSGFKOqw.js","assets/CardList-D-c7QNTB.js","assets/ItemList-FcKS3Z5e.js","assets/Settings-fa7In0jk.js","assets/Rules-D79nNK3r.js","assets/Notifications-BJQ8JgFo.js","assets/Chat-By_xPFNH.js"])))=>i.map(i=>d[i]); -import{c as S,j as e,r as c,d as H}from"./react-vendor-C_od1ZSF.js";import{L as T,a as P,S as J,U as Y,A as K,b as Q,c as W,M as X,C as ee,B as te,d as se,Z as ne,e as re,f as ae,G as k,g as oe,h as ie,i as le}from"./icons-vendor-CvzvbbIV.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))d(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&d(a)}).observe(document,{childList:!0,subtree:!0});function s(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function d(r){if(r.ep)return;r.ep=!0;const i=s(r);fetch(r.href,i)}})();class ce extends S.Component{constructor(){super(...arguments),this.state={hasError:!1},this.handleReload=()=>{window.location.reload()}}static getDerivedStateFromError(){return{hasError:!0}}render(){const{hasError:n}=this.state,{children:s}=this.props;return n?e.jsx("main",{className:"flex min-h-screen items-center justify-center bg-canvas p-6 text-ink",children:e.jsxs("section",{className:"max-w-md text-center",children:[e.jsx("h1",{className:"text-xl font-semibold",children:"页面暂时无法显示"}),e.jsx("button",{className:"ios-btn-primary mt-6 px-4 py-2",type:"button",onClick:this.handleReload,children:"重新加载"})]})}):s}}const de=3e4,ue=10*6e4;let N=!1;const I=()=>{N||typeof window>"u"||(N=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{N=!1}))},he=t=>{if(!t)return"";const n=new URLSearchParams;for(const[d,r]of Object.entries(t))r!=null&&n.set(d,String(r));const s=n.toString();return s?`?${s}`:""},L=async(t,n,s={})=>{var o;const d=he(s.params),r=`${n}${d}`,i=$(s.signal,s.timeoutMs??de);let a;try{a=await fetch(r,{method:t,credentials:"include",signal:i.signal,headers:{...s.body===void 0?{}:{"Content-Type":"application/json"}},body:s.body===void 0?void 0:JSON.stringify(s.body)})}catch(m){throw i.signal.aborted?new Error((o=s.signal)!=null&&o.aborted?"请求已取消":"请求超时,请稍后重试"):m}finally{i.cleanup()}const h=(a.headers.get("content-type")||"").includes("application/json");if(!a.ok){a.status===401&&!s.skipAuthLogout&&I();const m=h?await a.json().catch(()=>{}):await a.text().catch(()=>{}),f=z(m,a.status);throw new Error(f)}return h?await a.json():await a.text()},D=async(t,n,s)=>L("GET",t,{params:n,...s}),_=async(t,n,s)=>L("POST",t,{body:n,...s}),Ve=async(t,n,s)=>L("PUT",t,{body:n,...s}),Ue=async(t,n,s)=>L("DELETE",t,{params:n,...s}),Ge=async(t,n,s={})=>{var h;const d=$(s.signal,s.timeoutMs??ue);let r;try{r=await fetch(t,{method:"POST",credentials:"include",signal:d.signal,body:n})}catch(o){throw d.signal.aborted?new Error((h=s.signal)!=null&&h.aborted?"请求已取消":"上传超时,请稍后重试"):o}finally{d.cleanup()}const l=(r.headers.get("content-type")||"").includes("application/json")?await r.json().catch(()=>{}):await r.text().catch(()=>{});if(!r.ok){r.status===401&&I();const o=z(l,r.status),m=new Error(o);throw m.payload=l,m}return l},$=(t,n)=>{const s=new AbortController,d=()=>s.abort(t==null?void 0:t.reason);t!=null&&t.aborted?d():t==null||t.addEventListener("abort",d,{once:!0});const r=globalThis.setTimeout(()=>s.abort(new DOMException("timeout","TimeoutError")),Math.max(1,n));return{signal:s.signal,cleanup:()=>{globalThis.clearTimeout(r),t==null||t.removeEventListener("abort",d)}}},me=t=>{if(typeof t!="object"||t===null)return!1;const n=t;return typeof n.code=="string"&&typeof n.message=="string"},z=(t,n)=>typeof t=="string"?t:me(t)?t.message:`请求失败: ${n}`,fe=async t=>_("/api/v1/session/login",t,{skipAuthLogout:!0}),xe=async t=>_("/api/v1/session/initialize",{password:t},{skipAuthLogout:!0}),pe=async t=>D("/api/v1/session",void 0,t),ge=async()=>_("/api/v1/session/logout",{}),M=c.createContext(void 0),be=({children:t})=>{const[n,s]=c.useState(!1),[d,r]=c.useState(!1),[i,a]=c.useState(!0),[l,h]=c.useState(!1),o=()=>{s(!1),r(!1)};c.useEffect(()=>{const b=new AbortController;let g=!0;pe({signal:b.signal}).then(p=>{if(g){if((p==null?void 0:p.initialized)===!1){h(!0),o();return}h(!1),p!=null&&p.authenticated?(s(!0),r(p.is_admin===!0)):o()}}).catch(p=>{!g||p instanceof DOMException&&p.name==="AbortError"||(h(!1),o())}).finally(()=>{g&&a(!1)});const u=()=>o();return window.addEventListener("auth:logout",u),(()=>{g=!1,b.abort(),window.removeEventListener("auth:logout",u)})},[]);const m=async b=>{const g=await fe(b);return g.success&&(h(!1),s(!0),r(g.is_admin===!0)),g},f=async b=>{const g=await xe(b);return g.success&&(h(!1),s(!0),r(g.is_admin===!0)),g},x=async()=>{try{await ge()}finally{o()}};return e.jsx(M.Provider,{value:{checkingAuth:i,isLoggedIn:n,isAdmin:d,needsInit:l,signIn:m,initialize:f,signOut:x},children:t})},B=()=>{const t=c.useContext(M);if(!t)throw new Error("useSession 必须在 SessionProvider 内使用");return t},q="ydisks.sidebar.v1",ye=()=>{try{return window.localStorage.getItem(q)==="collapsed"}catch{return!1}},ve=t=>{try{window.localStorage.setItem(q,t?"collapsed":"expanded")}catch{}},we=({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"})})}),F=({sizeClass:t="w-12 h-12",logoClassName:n="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 23.51 12.25 L 27.29 10.34 L 31.54 8.78 L 36.33 7.56 L 41.84 6.69 L 48.52 6.17 L 60.00 6.00 L 71.48 6.17 L 78.16 6.69 L 83.67 7.56 L 88.46 8.78 L 92.71 10.34 L 96.49 12.25 L 99.87 14.52 L 102.86 17.14 L 105.48 20.13 L 107.75 23.51 L 109.66 27.29 L 111.22 31.54 L 112.44 36.33 L 113.31 41.84 L 113.83 48.52 Z",fill:"url(#login-squircle-gradient)"})]}),e.jsx("div",{className:"relative z-10 flex items-center justify-center w-full h-full",children:e.jsx(we,{className:n})})]})]}),je=()=>{const{checkingAuth:t,needsInit:n,signIn:s,initialize:d}=B(),[r,i]=c.useState(""),[a,l]=c.useState(""),[h,o]=c.useState(""),[m,f]=c.useState(""),[x,b]=c.useState(!1),[g,u]=c.useState(""),p=async y=>{y.preventDefault(),b(!0),u("");try{const v=await s({username:r,password:a});v.success||u(v.message||"登录失败")}catch(v){u(v instanceof Error&&v.message||"登录失败")}finally{b(!1)}},j=async y=>{if(y.preventDefault(),u(""),h.length<8){u("密码至少需要 8 个字符");return}if(h!==m){u("两次输入的密码不一致");return}b(!0);try{const v=await d(h);if(!v.success){u(v.message||"初始化失败,请重试");return}o(""),f("")}catch(v){u(v instanceof Error&&v.message||"初始化失败,请重试")}finally{b(!1)}};if(t)return e.jsx("main",{className:"flex min-h-screen items-center justify-center bg-surface","aria-label":"正在校验会话",children:e.jsx(T,{className:"h-8 w-8 animate-spin text-brand"})});const G=n?"首次设置管理员密码":"欢迎回来",Z=n?"设置完成后会自动进入系统,管理员账号为 admin。":"Ydisks闲鱼助手 · 自动发货与管家系统";return e.jsx("main",{className:"flex min-h-screen items-center justify-center bg-canvas p-4 font-sans",children:e.jsxs("section",{className:"w-full max-w-lg rounded-xl border border-white bg-white/80 p-8 shadow-panel backdrop-blur-3xl md:p-12",children:[e.jsxs("header",{className:"mb-8 text-center",children:[e.jsx("div",{className:"mx-auto mb-6 flex justify-center",children:e.jsx(F,{sizeClass:"h-24 w-24"})}),e.jsx("h1",{className:"text-3xl font-extrabold text-gray-900",children:G}),e.jsx("p",{className:"mt-2 font-medium text-gray-600",children:Z})]}),n?e.jsxs("form",{className:"space-y-5",onSubmit:j,children:[e.jsxs("label",{className:"relative block",children:[e.jsx("span",{className:"sr-only",children:"设置管理员密码"}),e.jsx(P,{className:"absolute left-5 top-1/2 h-5 w-5 -translate-y-1/2 text-gray-400"}),e.jsx("input",{autoFocus:!0,className:"ios-input h-14 w-full rounded-xl py-4 pl-14 pr-6",onChange:(y=>o(y.target.value)),placeholder:"设置管理员密码(至少 8 个字符)",type:"password",value:h})]}),e.jsxs("label",{className:"relative block",children:[e.jsx("span",{className:"sr-only",children:"确认管理员密码"}),e.jsx(J,{className:"absolute left-5 top-1/2 h-5 w-5 -translate-y-1/2 text-gray-400"}),e.jsx("input",{className:"ios-input h-14 w-full rounded-xl py-4 pl-14 pr-6",onChange:(y=>f(y.target.value)),placeholder:"再次输入密码",type:"password",value:m})]}),e.jsx(A,{submitting:x,text:"设置密码并进入系统"})]}):e.jsxs("form",{className:"space-y-5",onSubmit:p,children:[e.jsxs("label",{className:"relative block",children:[e.jsx("span",{className:"sr-only",children:"管理员账号"}),e.jsx(Y,{className:"absolute left-5 top-1/2 h-5 w-5 -translate-y-1/2 text-gray-400"}),e.jsx("input",{autoFocus:!0,className:"ios-input h-14 w-full rounded-xl py-4 pl-14 pr-6",onChange:(y=>i(y.target.value)),placeholder:"管理员账号",type:"text",value:r})]}),e.jsxs("label",{className:"relative block",children:[e.jsx("span",{className:"sr-only",children:"管理员密码"}),e.jsx(P,{className:"absolute left-5 top-1/2 h-5 w-5 -translate-y-1/2 text-gray-400"}),e.jsx("input",{className:"ios-input h-14 w-full rounded-xl py-4 pl-14 pr-6",onChange:(y=>l(y.target.value)),placeholder:"密码",type:"password",value:a})]}),e.jsx(A,{submitting:x,text:"立即登录"})]}),g?e.jsx("p",{className:"mt-5 rounded-xl bg-red-50 p-3 text-center text-sm font-medium text-red-600",children:g}):null]})})},A=({submitting:t,text:n})=>e.jsx("button",{className:"ios-btn-primary flex h-14 w-full items-center justify-center gap-2 rounded-xl text-lg disabled:opacity-70",disabled:t,type:"submit",children:t?e.jsx(T,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx("span",{children:n}),e.jsx(K,{className:"h-5 w-5"})]})}),Le="modulepreload",Ne=function(t){return"/static/"+t},O={},w=function(n,s,d){let r=Promise.resolve();if(s&&s.length>0){let a=function(o){return Promise.all(o.map(m=>Promise.resolve(m).then(f=>({status:"fulfilled",value:f}),f=>({status:"rejected",reason:f}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),h=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));r=a(s.map(o=>{if(o=Ne(o),o in O)return;O[o]=!0;const m=o.endsWith(".css"),f=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${o}"]${f}`))return;const x=document.createElement("link");if(x.rel=m?"stylesheet":Le,m||(x.as="script"),x.crossOrigin="",x.href=o,h&&x.setAttribute("nonce",h),document.head.appendChild(x),m)return new Promise((b,g)=>{x.addEventListener("load",b),x.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${o}`)))})}))}function i(a){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=a,window.dispatchEvent(l),!l.defaultPrevented)throw a}return r.then(a=>{for(const l of a||[])l.status==="rejected"&&i(l.reason);return n().catch(i)})},Ce=({activeTab:t,isAdmin:n=!1,collapsed:s,onToggleCollapsed:d,onNavigate:r,onLogout:i,buildInfo:a})=>{const l=[{id:"dashboard",icon:Q,label:"仪表盘"},{id:"accounts",icon:W,label:"账号管理"},{id:"chat",icon:X,label:"在线聊天"},{id:"cards",icon:ee,label:"卡密库存"},{id:"items",icon:te,label:"商品列表"},{id:"orders",icon:se,label:"订单管理"},{id:"rules",icon:ne,label:"自动化规则"},{id:"notifications",icon:re,label:"通知设置"},...n?[{id:"settings",icon:ae,label:"系统与AI"}]:[]],h=/^\d+\.\d+\.\d+$/.test(a.version)?`v${a.version}`:a.version;return e.jsxs("aside",{className:`fixed inset-y-0 left-0 z-20 flex flex-col border-r border-slate-200/80 bg-white/95 shadow-sidebar backdrop-blur-xl transition-[width] duration-300 ${s?"w-16":"w-64"}`,children:[e.jsxs("div",{className:`flex h-20 items-center border-b border-slate-100 ${s?"justify-center px-2":"gap-3 px-5"}`,children:[e.jsx(F,{sizeClass:"h-10 w-10"}),!s&&e.jsxs("div",{className:"min-w-0 leading-tight",children:[e.jsx("div",{className:"truncate text-base font-black tracking-tight text-slate-950",children:"Ydisks 闲鱼助手"}),e.jsx("div",{className:"mt-1 text-[10px] font-extrabold uppercase tracking-[0.22em] text-sky-600",children:"Operations"})]})]}),e.jsx("nav",{className:`flex-1 space-y-1.5 overflow-y-auto pt-5 ${s?"px-2":"px-3"}`,"aria-label":"主导航",children:l.map(o=>{const m=o.icon,f=t===o.id;return e.jsx(S.Fragment,{children:e.jsxs("button",{type:"button",title:s?o.label:void 0,"aria-label":o.label,"aria-current":f?"page":void 0,onClick:(()=>r(o.id)),className:`group relative flex h-11 w-full items-center rounded-xl transition-colors ${s?"justify-center":"gap-3 px-3.5"} ${f?"bg-brand text-white shadow-brand-active":"text-slate-500 hover:bg-slate-100 hover:text-slate-900"}`,children:[e.jsx(m,{className:`h-[19px] w-[19px] shrink-0 ${f?"text-white":"text-slate-400 group-hover:text-slate-700"}`}),!s&&e.jsx("span",{className:"truncate text-sm font-bold",children:o.label}),f&&!s&&e.jsx("span",{className:"ml-auto h-1.5 w-1.5 rounded-full bg-white/90"})]})},o.id)})}),e.jsxs("div",{children:[e.jsx("div",{title:s?`版本 ${a.version} · ${a.commit}`:void 0,className:`border-y border-slate-100 bg-slate-50/70 py-2.5 ${s?"flex justify-center px-1":"px-6"}`,children:s?e.jsx(k,{className:"h-[18px] w-[18px] text-slate-400","aria-label":`版本 ${a.version}`}):e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-extrabold uppercase tracking-[0.18em] text-slate-400",children:[e.jsx(k,{className:"h-3.5 w-3.5"}),"运行版本"]}),e.jsxs("div",{className:"mt-1 flex items-baseline gap-2",children:[e.jsx("span",{className:"truncate font-mono text-xs font-bold text-slate-700",children:h}),e.jsx("span",{className:"truncate font-mono text-[10px] text-slate-400",children:a.commit})]})]})}),e.jsxs("div",{className:`space-y-2 p-2 ${s?"":"p-3"}`,children:[e.jsxs("button",{type:"button",onClick:d,title:s?"展开侧边栏":"收起侧边栏","aria-label":s?"展开侧边栏":"收起侧边栏",className:`flex h-10 w-full items-center rounded-xl text-slate-500 transition-colors hover:bg-slate-100 hover:text-slate-900 ${s?"justify-center":"gap-3 px-3"}`,children:[s?e.jsx(oe,{className:"h-5 w-5"}):e.jsx(ie,{className:"h-5 w-5"}),!s&&e.jsx("span",{className:"text-sm font-bold",children:"收起侧边栏"})]}),e.jsxs("button",{type:"button",onClick:i,title:s?"退出登录":void 0,"aria-label":"退出登录",className:`flex h-10 w-full items-center rounded-xl text-slate-500 transition-colors hover:bg-red-50 hover:text-red-600 ${s?"justify-center":"gap-3 px-3"}`,children:[e.jsx(le,{className:"h-5 w-5"}),!s&&e.jsx("span",{className:"text-sm font-bold",children:"退出登录"})]})]})]})]})},Ee=async t=>D("/health",void 0,t),C=c.lazy(()=>w(()=>import("./Dashboard-RK26q9J7.js"),__vite__mapDeps([0,1,2,3,4,5,6]))),Se=c.lazy(()=>w(()=>import("./AccountList-fhDk6BDY.js"),__vite__mapDeps([7,1,3,4]))),_e=c.lazy(()=>w(()=>import("./OrderList-CSGFKOqw.js"),__vite__mapDeps([8,1,4,3,2]))),Pe=c.lazy(()=>w(()=>import("./CardList-D-c7QNTB.js"),__vite__mapDeps([9,1,4,3]))),ke=c.lazy(()=>w(()=>import("./ItemList-FcKS3Z5e.js"),__vite__mapDeps([10,1,3,4]))),Ae=c.lazy(()=>w(()=>import("./Settings-fa7In0jk.js"),__vite__mapDeps([11,1,4]))),Oe=c.lazy(()=>w(()=>import("./Rules-D79nNK3r.js"),__vite__mapDeps([12,1,4,3]))),Re=c.lazy(()=>w(()=>import("./Notifications-BJQ8JgFo.js"),__vite__mapDeps([13,1,4]))),Te=c.lazy(()=>w(()=>import("./Chat-By_xPFNH.js"),__vite__mapDeps([14,1,3,4]))),Ie=()=>e.jsx("div",{className:"flex min-h-[24rem] items-center justify-center",role:"status","aria-label":"正在加载页面",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-brand/20 border-t-brand"})}),De=({activeTab:t,isAdmin:n,deliveryRuleTarget:s,onConfigureDelivery:d,onDeliveryTargetHandled:r})=>{const i=l=>{d({cookieId:l.cookie_id,itemId:l.item_id,requestId:Date.now()})},a=()=>{switch(t){case"dashboard":return e.jsx(C,{});case"accounts":return e.jsx(Se,{});case"chat":return e.jsx(Te,{});case"orders":return e.jsx(_e,{});case"cards":return e.jsx(Pe,{});case"items":return e.jsx(ke,{onConfigureDelivery:i});case"rules":return e.jsx(Oe,{initialDeliveryTarget:s,onDeliveryTargetHandled:r});case"notifications":return e.jsx(Re,{isAdmin:n});case"settings":return n?e.jsx(Ae,{}):e.jsx(C,{});default:return e.jsx(C,{})}};return e.jsx(c.Suspense,{fallback:e.jsx(Ie,{}),children:a()})},$e=({activeTab:t,isAdmin:n,collapsed:s,deliveryRuleTarget:d,onToggleCollapsed:r,onNavigate:i,onLogout:a,onConfigureDelivery:l,onDeliveryTargetHandled:h})=>{const[o,m]=c.useState({version:"dev",commit:"unknown"});return c.useEffect(()=>{const f=new AbortController;return Ee({signal:f.signal}).then(x=>m({version:String(x.version||"dev"),commit:String(x.commit||"unknown")})).catch(x=>{x instanceof DOMException&&x.name}),(()=>f.abort())},[]),e.jsxs("div",{className:"flex min-h-screen bg-canvas text-ink",children:[e.jsx(Ce,{activeTab:t,isAdmin:n,collapsed:s,onToggleCollapsed:r,onNavigate:i,onLogout:a,buildInfo:o}),e.jsxs("main",{className:`h-screen min-w-0 flex-1 overflow-x-hidden overflow-y-auto scroll-smooth transition-[margin] duration-300 ${s?"ml-16":"ml-64"} ${t==="chat"?"p-4 md:p-6":"p-8 md:p-12"}`,children:[e.jsx("div",{className:"fixed top-0 right-0 -z-10 h-[800px] w-[800px] pointer-events-none rounded-full bg-gradient-to-bl from-blue-50 to-transparent opacity-60 blur-[120px]"}),e.jsx("div",{className:`${t==="chat"?"mx-auto max-w-[1680px]":"mx-auto max-w-[1400px] pb-10"}`,children:e.jsx(De,{activeTab:t,isAdmin:n,deliveryRuleTarget:d,onConfigureDelivery:l,onDeliveryTargetHandled:h})})]})]})},V={"/app/dashboard":"dashboard","/app/accounts":"accounts","/app/chat":"chat","/app/orders":"orders","/app/cards":"cards","/app/items":"items","/app/rules":"rules","/app/notifications":"notifications","/app/settings":"settings"},E=Object.fromEntries(Object.entries(V).map(([t,n])=>[n,t])),R=()=>V[window.location.pathname]??"dashboard",ze=()=>{const{isLoggedIn:t,isAdmin:n,signOut:s}=B(),[d,r]=c.useState(R),[i,a]=c.useState(),[l,h]=c.useState(ye);c.useEffect(()=>{const u=()=>r(R());return window.addEventListener("popstate",u),(()=>window.removeEventListener("popstate",u))},[]),c.useEffect(()=>{t&&!n&&d==="settings"&&(window.history.replaceState({},"",E.dashboard),r("dashboard"))},[d,n,t]);const o=u=>{const p=u==="settings"&&!n?"dashboard":u,j=E[p];j!==window.location.pathname&&window.history.pushState({},"",j),r(p)},m=u=>{const p=Object.prototype.hasOwnProperty.call(E,u)?u:"dashboard";o(p)},f=async()=>{try{await s()}catch(u){console.error("退出登录失败",u)}},x=()=>{h(u=>{const p=!u;return ve(p),p})},b=u=>{a(u),o("rules")},g=()=>a(void 0);return t?e.jsx($e,{activeTab:d,isAdmin:n,collapsed:l,deliveryRuleTarget:i,onToggleCollapsed:x,onNavigate:m,onLogout:f,onConfigureDelivery:b,onDeliveryTargetHandled:g}):e.jsx(je,{})},Me=()=>e.jsx(ce,{children:e.jsx(be,{children:e.jsx(ze,{})})}),U=document.getElementById("root");if(!U)throw new Error("Could not find root element to mount to");const Be=H.createRoot(U);Be.render(e.jsx(S.StrictMode,{children:e.jsx(Me,{})}));export{_ as a,Ge as b,Ue as d,D as g,Ve as p}; +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Dashboard-MmgsZAic.js","assets/react-vendor-C_od1ZSF.js","assets/dateTime-DDi7rqpW.js","assets/contract-COFcZjyb.js","assets/icons-vendor-CvzvbbIV.js","assets/charts-vendor-BxxJOyEX.js","assets/vendor-D-Edl3pr.js","assets/AccountList-Bb-tGjAS.js","assets/OrderList-BAnpJSM4.js","assets/CardList-D43xNKm6.js","assets/ItemList-BHJwErgP.js","assets/Settings-DUEkZoEv.js","assets/Rules-BplaKbZv.js","assets/Notifications-Dvclt-gX.js","assets/Chat-DSkOtUaB.js"])))=>i.map(i=>d[i]); +import{c as S,j as e,r as c,d as H}from"./react-vendor-C_od1ZSF.js";import{L as T,a as P,S as J,U as Y,A as K,b as Q,c as W,M as X,C as ee,B as te,d as se,Z as ne,e as re,f as ae,G as k,g as oe,h as ie,i as le}from"./icons-vendor-CvzvbbIV.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))d(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&d(a)}).observe(document,{childList:!0,subtree:!0});function s(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function d(r){if(r.ep)return;r.ep=!0;const i=s(r);fetch(r.href,i)}})();class ce extends S.Component{constructor(){super(...arguments),this.state={hasError:!1},this.handleReload=()=>{window.location.reload()}}static getDerivedStateFromError(){return{hasError:!0}}render(){const{hasError:n}=this.state,{children:s}=this.props;return n?e.jsx("main",{className:"flex min-h-screen items-center justify-center bg-canvas p-6 text-ink",children:e.jsxs("section",{className:"max-w-md text-center",children:[e.jsx("h1",{className:"text-xl font-semibold",children:"页面暂时无法显示"}),e.jsx("button",{className:"ios-btn-primary mt-6 px-4 py-2",type:"button",onClick:this.handleReload,children:"重新加载"})]})}):s}}const de=3e4,ue=10*6e4;let N=!1;const I=()=>{N||typeof window>"u"||(N=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{N=!1}))},he=t=>{if(!t)return"";const n=new URLSearchParams;for(const[d,r]of Object.entries(t))r!=null&&n.set(d,String(r));const s=n.toString();return s?`?${s}`:""},L=async(t,n,s={})=>{var o;const d=he(s.params),r=`${n}${d}`,i=$(s.signal,s.timeoutMs??de);let a;try{a=await fetch(r,{method:t,credentials:"include",signal:i.signal,headers:{...s.body===void 0?{}:{"Content-Type":"application/json"}},body:s.body===void 0?void 0:JSON.stringify(s.body)})}catch(m){throw i.signal.aborted?new Error((o=s.signal)!=null&&o.aborted?"请求已取消":"请求超时,请稍后重试"):m}finally{i.cleanup()}const h=(a.headers.get("content-type")||"").includes("application/json");if(!a.ok){a.status===401&&!s.skipAuthLogout&&I();const m=h?await a.json().catch(()=>{}):await a.text().catch(()=>{}),f=z(m,a.status);throw new Error(f)}return h?await a.json():await a.text()},D=async(t,n,s)=>L("GET",t,{params:n,...s}),_=async(t,n,s)=>L("POST",t,{body:n,...s}),Ve=async(t,n,s)=>L("PUT",t,{body:n,...s}),Ue=async(t,n,s)=>L("DELETE",t,{params:n,...s}),Ge=async(t,n,s={})=>{var h;const d=$(s.signal,s.timeoutMs??ue);let r;try{r=await fetch(t,{method:"POST",credentials:"include",signal:d.signal,body:n})}catch(o){throw d.signal.aborted?new Error((h=s.signal)!=null&&h.aborted?"请求已取消":"上传超时,请稍后重试"):o}finally{d.cleanup()}const l=(r.headers.get("content-type")||"").includes("application/json")?await r.json().catch(()=>{}):await r.text().catch(()=>{});if(!r.ok){r.status===401&&I();const o=z(l,r.status),m=new Error(o);throw m.payload=l,m}return l},$=(t,n)=>{const s=new AbortController,d=()=>s.abort(t==null?void 0:t.reason);t!=null&&t.aborted?d():t==null||t.addEventListener("abort",d,{once:!0});const r=globalThis.setTimeout(()=>s.abort(new DOMException("timeout","TimeoutError")),Math.max(1,n));return{signal:s.signal,cleanup:()=>{globalThis.clearTimeout(r),t==null||t.removeEventListener("abort",d)}}},me=t=>{if(typeof t!="object"||t===null)return!1;const n=t;return typeof n.code=="string"&&typeof n.message=="string"},z=(t,n)=>typeof t=="string"?t:me(t)?t.message:`请求失败: ${n}`,fe=async t=>_("/api/v1/session/login",t,{skipAuthLogout:!0}),xe=async t=>_("/api/v1/session/initialize",{password:t},{skipAuthLogout:!0}),pe=async t=>D("/api/v1/session",void 0,t),ge=async()=>_("/api/v1/session/logout",{}),M=c.createContext(void 0),be=({children:t})=>{const[n,s]=c.useState(!1),[d,r]=c.useState(!1),[i,a]=c.useState(!0),[l,h]=c.useState(!1),o=()=>{s(!1),r(!1)};c.useEffect(()=>{const b=new AbortController;let g=!0;pe({signal:b.signal}).then(p=>{if(g){if((p==null?void 0:p.initialized)===!1){h(!0),o();return}h(!1),p!=null&&p.authenticated?(s(!0),r(p.is_admin===!0)):o()}}).catch(p=>{!g||p instanceof DOMException&&p.name==="AbortError"||(h(!1),o())}).finally(()=>{g&&a(!1)});const u=()=>o();return window.addEventListener("auth:logout",u),(()=>{g=!1,b.abort(),window.removeEventListener("auth:logout",u)})},[]);const m=async b=>{const g=await fe(b);return g.success&&(h(!1),s(!0),r(g.is_admin===!0)),g},f=async b=>{const g=await xe(b);return g.success&&(h(!1),s(!0),r(g.is_admin===!0)),g},x=async()=>{try{await ge()}finally{o()}};return e.jsx(M.Provider,{value:{checkingAuth:i,isLoggedIn:n,isAdmin:d,needsInit:l,signIn:m,initialize:f,signOut:x},children:t})},B=()=>{const t=c.useContext(M);if(!t)throw new Error("useSession 必须在 SessionProvider 内使用");return t},q="ydisks.sidebar.v1",ye=()=>{try{return window.localStorage.getItem(q)==="collapsed"}catch{return!1}},ve=t=>{try{window.localStorage.setItem(q,t?"collapsed":"expanded")}catch{}},we=({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"})})}),F=({sizeClass:t="w-12 h-12",logoClassName:n="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 23.51 12.25 L 27.29 10.34 L 31.54 8.78 L 36.33 7.56 L 41.84 6.69 L 48.52 6.17 L 60.00 6.00 L 71.48 6.17 L 78.16 6.69 L 83.67 7.56 L 88.46 8.78 L 92.71 10.34 L 96.49 12.25 L 99.87 14.52 L 102.86 17.14 L 105.48 20.13 L 107.75 23.51 L 109.66 27.29 L 111.22 31.54 L 112.44 36.33 L 113.31 41.84 L 113.83 48.52 Z",fill:"url(#login-squircle-gradient)"})]}),e.jsx("div",{className:"relative z-10 flex items-center justify-center w-full h-full",children:e.jsx(we,{className:n})})]})]}),je=()=>{const{checkingAuth:t,needsInit:n,signIn:s,initialize:d}=B(),[r,i]=c.useState(""),[a,l]=c.useState(""),[h,o]=c.useState(""),[m,f]=c.useState(""),[x,b]=c.useState(!1),[g,u]=c.useState(""),p=async y=>{y.preventDefault(),b(!0),u("");try{const v=await s({username:r,password:a});v.success||u(v.message||"登录失败")}catch(v){u(v instanceof Error&&v.message||"登录失败")}finally{b(!1)}},j=async y=>{if(y.preventDefault(),u(""),h.length<8){u("密码至少需要 8 个字符");return}if(h!==m){u("两次输入的密码不一致");return}b(!0);try{const v=await d(h);if(!v.success){u(v.message||"初始化失败,请重试");return}o(""),f("")}catch(v){u(v instanceof Error&&v.message||"初始化失败,请重试")}finally{b(!1)}};if(t)return e.jsx("main",{className:"flex min-h-screen items-center justify-center bg-surface","aria-label":"正在校验会话",children:e.jsx(T,{className:"h-8 w-8 animate-spin text-brand"})});const G=n?"首次设置管理员密码":"欢迎回来",Z=n?"设置完成后会自动进入系统,管理员账号为 admin。":"Ydisks闲鱼助手 · 自动发货与管家系统";return e.jsx("main",{className:"flex min-h-screen items-center justify-center bg-canvas p-4 font-sans",children:e.jsxs("section",{className:"w-full max-w-lg rounded-xl border border-white bg-white/80 p-8 shadow-panel backdrop-blur-3xl md:p-12",children:[e.jsxs("header",{className:"mb-8 text-center",children:[e.jsx("div",{className:"mx-auto mb-6 flex justify-center",children:e.jsx(F,{sizeClass:"h-24 w-24"})}),e.jsx("h1",{className:"text-3xl font-extrabold text-gray-900",children:G}),e.jsx("p",{className:"mt-2 font-medium text-gray-600",children:Z})]}),n?e.jsxs("form",{className:"space-y-5",onSubmit:j,children:[e.jsxs("label",{className:"relative block",children:[e.jsx("span",{className:"sr-only",children:"设置管理员密码"}),e.jsx(P,{className:"absolute left-5 top-1/2 h-5 w-5 -translate-y-1/2 text-gray-400"}),e.jsx("input",{autoFocus:!0,className:"ios-input h-14 w-full rounded-xl py-4 pl-14 pr-6",onChange:(y=>o(y.target.value)),placeholder:"设置管理员密码(至少 8 个字符)",type:"password",value:h})]}),e.jsxs("label",{className:"relative block",children:[e.jsx("span",{className:"sr-only",children:"确认管理员密码"}),e.jsx(J,{className:"absolute left-5 top-1/2 h-5 w-5 -translate-y-1/2 text-gray-400"}),e.jsx("input",{className:"ios-input h-14 w-full rounded-xl py-4 pl-14 pr-6",onChange:(y=>f(y.target.value)),placeholder:"再次输入密码",type:"password",value:m})]}),e.jsx(A,{submitting:x,text:"设置密码并进入系统"})]}):e.jsxs("form",{className:"space-y-5",onSubmit:p,children:[e.jsxs("label",{className:"relative block",children:[e.jsx("span",{className:"sr-only",children:"管理员账号"}),e.jsx(Y,{className:"absolute left-5 top-1/2 h-5 w-5 -translate-y-1/2 text-gray-400"}),e.jsx("input",{autoFocus:!0,className:"ios-input h-14 w-full rounded-xl py-4 pl-14 pr-6",onChange:(y=>i(y.target.value)),placeholder:"管理员账号",type:"text",value:r})]}),e.jsxs("label",{className:"relative block",children:[e.jsx("span",{className:"sr-only",children:"管理员密码"}),e.jsx(P,{className:"absolute left-5 top-1/2 h-5 w-5 -translate-y-1/2 text-gray-400"}),e.jsx("input",{className:"ios-input h-14 w-full rounded-xl py-4 pl-14 pr-6",onChange:(y=>l(y.target.value)),placeholder:"密码",type:"password",value:a})]}),e.jsx(A,{submitting:x,text:"立即登录"})]}),g?e.jsx("p",{className:"mt-5 rounded-xl bg-red-50 p-3 text-center text-sm font-medium text-red-600",children:g}):null]})})},A=({submitting:t,text:n})=>e.jsx("button",{className:"ios-btn-primary flex h-14 w-full items-center justify-center gap-2 rounded-xl text-lg disabled:opacity-70",disabled:t,type:"submit",children:t?e.jsx(T,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx("span",{children:n}),e.jsx(K,{className:"h-5 w-5"})]})}),Le="modulepreload",Ne=function(t){return"/static/"+t},O={},w=function(n,s,d){let r=Promise.resolve();if(s&&s.length>0){let a=function(o){return Promise.all(o.map(m=>Promise.resolve(m).then(f=>({status:"fulfilled",value:f}),f=>({status:"rejected",reason:f}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),h=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));r=a(s.map(o=>{if(o=Ne(o),o in O)return;O[o]=!0;const m=o.endsWith(".css"),f=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${o}"]${f}`))return;const x=document.createElement("link");if(x.rel=m?"stylesheet":Le,m||(x.as="script"),x.crossOrigin="",x.href=o,h&&x.setAttribute("nonce",h),document.head.appendChild(x),m)return new Promise((b,g)=>{x.addEventListener("load",b),x.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${o}`)))})}))}function i(a){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=a,window.dispatchEvent(l),!l.defaultPrevented)throw a}return r.then(a=>{for(const l of a||[])l.status==="rejected"&&i(l.reason);return n().catch(i)})},Ce=({activeTab:t,isAdmin:n=!1,collapsed:s,onToggleCollapsed:d,onNavigate:r,onLogout:i,buildInfo:a})=>{const l=[{id:"dashboard",icon:Q,label:"仪表盘"},{id:"accounts",icon:W,label:"账号管理"},{id:"chat",icon:X,label:"在线聊天"},{id:"cards",icon:ee,label:"卡密库存"},{id:"items",icon:te,label:"商品列表"},{id:"orders",icon:se,label:"订单管理"},{id:"rules",icon:ne,label:"自动化规则"},{id:"notifications",icon:re,label:"通知设置"},...n?[{id:"settings",icon:ae,label:"系统与AI"}]:[]],h=/^\d+\.\d+\.\d+$/.test(a.version)?`v${a.version}`:a.version;return e.jsxs("aside",{className:`fixed inset-y-0 left-0 z-20 flex flex-col border-r border-slate-200/80 bg-white/95 shadow-sidebar backdrop-blur-xl transition-[width] duration-300 ${s?"w-16":"w-64"}`,children:[e.jsxs("div",{className:`flex h-20 items-center border-b border-slate-100 ${s?"justify-center px-2":"gap-3 px-5"}`,children:[e.jsx(F,{sizeClass:"h-10 w-10"}),!s&&e.jsxs("div",{className:"min-w-0 leading-tight",children:[e.jsx("div",{className:"truncate text-base font-black tracking-tight text-slate-950",children:"Ydisks 闲鱼助手"}),e.jsx("div",{className:"mt-1 text-[10px] font-extrabold uppercase tracking-[0.22em] text-sky-600",children:"Operations"})]})]}),e.jsx("nav",{className:`flex-1 space-y-1.5 overflow-y-auto pt-5 ${s?"px-2":"px-3"}`,"aria-label":"主导航",children:l.map(o=>{const m=o.icon,f=t===o.id;return e.jsx(S.Fragment,{children:e.jsxs("button",{type:"button",title:s?o.label:void 0,"aria-label":o.label,"aria-current":f?"page":void 0,onClick:(()=>r(o.id)),className:`group relative flex h-11 w-full items-center rounded-xl transition-colors ${s?"justify-center":"gap-3 px-3.5"} ${f?"bg-brand text-white shadow-brand-active":"text-slate-500 hover:bg-slate-100 hover:text-slate-900"}`,children:[e.jsx(m,{className:`h-[19px] w-[19px] shrink-0 ${f?"text-white":"text-slate-400 group-hover:text-slate-700"}`}),!s&&e.jsx("span",{className:"truncate text-sm font-bold",children:o.label}),f&&!s&&e.jsx("span",{className:"ml-auto h-1.5 w-1.5 rounded-full bg-white/90"})]})},o.id)})}),e.jsxs("div",{children:[e.jsx("div",{title:s?`版本 ${a.version} · ${a.commit}`:void 0,className:`border-y border-slate-100 bg-slate-50/70 py-2.5 ${s?"flex justify-center px-1":"px-6"}`,children:s?e.jsx(k,{className:"h-[18px] w-[18px] text-slate-400","aria-label":`版本 ${a.version}`}):e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-extrabold uppercase tracking-[0.18em] text-slate-400",children:[e.jsx(k,{className:"h-3.5 w-3.5"}),"运行版本"]}),e.jsxs("div",{className:"mt-1 flex items-baseline gap-2",children:[e.jsx("span",{className:"truncate font-mono text-xs font-bold text-slate-700",children:h}),e.jsx("span",{className:"truncate font-mono text-[10px] text-slate-400",children:a.commit})]})]})}),e.jsxs("div",{className:`space-y-2 p-2 ${s?"":"p-3"}`,children:[e.jsxs("button",{type:"button",onClick:d,title:s?"展开侧边栏":"收起侧边栏","aria-label":s?"展开侧边栏":"收起侧边栏",className:`flex h-10 w-full items-center rounded-xl text-slate-500 transition-colors hover:bg-slate-100 hover:text-slate-900 ${s?"justify-center":"gap-3 px-3"}`,children:[s?e.jsx(oe,{className:"h-5 w-5"}):e.jsx(ie,{className:"h-5 w-5"}),!s&&e.jsx("span",{className:"text-sm font-bold",children:"收起侧边栏"})]}),e.jsxs("button",{type:"button",onClick:i,title:s?"退出登录":void 0,"aria-label":"退出登录",className:`flex h-10 w-full items-center rounded-xl text-slate-500 transition-colors hover:bg-red-50 hover:text-red-600 ${s?"justify-center":"gap-3 px-3"}`,children:[e.jsx(le,{className:"h-5 w-5"}),!s&&e.jsx("span",{className:"text-sm font-bold",children:"退出登录"})]})]})]})]})},Ee=async t=>D("/health",void 0,t),C=c.lazy(()=>w(()=>import("./Dashboard-MmgsZAic.js"),__vite__mapDeps([0,1,2,3,4,5,6]))),Se=c.lazy(()=>w(()=>import("./AccountList-Bb-tGjAS.js"),__vite__mapDeps([7,1,3,4]))),_e=c.lazy(()=>w(()=>import("./OrderList-BAnpJSM4.js"),__vite__mapDeps([8,1,4,3,2]))),Pe=c.lazy(()=>w(()=>import("./CardList-D43xNKm6.js"),__vite__mapDeps([9,1,4,3]))),ke=c.lazy(()=>w(()=>import("./ItemList-BHJwErgP.js"),__vite__mapDeps([10,1,3,4]))),Ae=c.lazy(()=>w(()=>import("./Settings-DUEkZoEv.js"),__vite__mapDeps([11,1,4]))),Oe=c.lazy(()=>w(()=>import("./Rules-BplaKbZv.js"),__vite__mapDeps([12,1,4,3]))),Re=c.lazy(()=>w(()=>import("./Notifications-Dvclt-gX.js"),__vite__mapDeps([13,1,4]))),Te=c.lazy(()=>w(()=>import("./Chat-DSkOtUaB.js"),__vite__mapDeps([14,1,3,4]))),Ie=()=>e.jsx("div",{className:"flex min-h-[24rem] items-center justify-center",role:"status","aria-label":"正在加载页面",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-brand/20 border-t-brand"})}),De=({activeTab:t,isAdmin:n,deliveryRuleTarget:s,onConfigureDelivery:d,onDeliveryTargetHandled:r})=>{const i=l=>{d({cookieId:l.cookie_id,itemId:l.item_id,requestId:Date.now()})},a=()=>{switch(t){case"dashboard":return e.jsx(C,{});case"accounts":return e.jsx(Se,{});case"chat":return e.jsx(Te,{});case"orders":return e.jsx(_e,{});case"cards":return e.jsx(Pe,{});case"items":return e.jsx(ke,{onConfigureDelivery:i});case"rules":return e.jsx(Oe,{initialDeliveryTarget:s,onDeliveryTargetHandled:r});case"notifications":return e.jsx(Re,{isAdmin:n});case"settings":return n?e.jsx(Ae,{}):e.jsx(C,{});default:return e.jsx(C,{})}};return e.jsx(c.Suspense,{fallback:e.jsx(Ie,{}),children:a()})},$e=({activeTab:t,isAdmin:n,collapsed:s,deliveryRuleTarget:d,onToggleCollapsed:r,onNavigate:i,onLogout:a,onConfigureDelivery:l,onDeliveryTargetHandled:h})=>{const[o,m]=c.useState({version:"dev",commit:"unknown"});return c.useEffect(()=>{const f=new AbortController;return Ee({signal:f.signal}).then(x=>m({version:String(x.version||"dev"),commit:String(x.commit||"unknown")})).catch(x=>{x instanceof DOMException&&x.name}),(()=>f.abort())},[]),e.jsxs("div",{className:"flex min-h-screen bg-canvas text-ink",children:[e.jsx(Ce,{activeTab:t,isAdmin:n,collapsed:s,onToggleCollapsed:r,onNavigate:i,onLogout:a,buildInfo:o}),e.jsxs("main",{className:`h-screen min-w-0 flex-1 overflow-x-hidden overflow-y-auto scroll-smooth transition-[margin] duration-300 ${s?"ml-16":"ml-64"} ${t==="chat"?"p-4 md:p-6":"p-8 md:p-12"}`,children:[e.jsx("div",{className:"fixed top-0 right-0 -z-10 h-[800px] w-[800px] pointer-events-none rounded-full bg-gradient-to-bl from-blue-50 to-transparent opacity-60 blur-[120px]"}),e.jsx("div",{className:`${t==="chat"?"mx-auto max-w-[1680px]":"mx-auto max-w-[1400px] pb-10"}`,children:e.jsx(De,{activeTab:t,isAdmin:n,deliveryRuleTarget:d,onConfigureDelivery:l,onDeliveryTargetHandled:h})})]})]})},V={"/app/dashboard":"dashboard","/app/accounts":"accounts","/app/chat":"chat","/app/orders":"orders","/app/cards":"cards","/app/items":"items","/app/rules":"rules","/app/notifications":"notifications","/app/settings":"settings"},E=Object.fromEntries(Object.entries(V).map(([t,n])=>[n,t])),R=()=>V[window.location.pathname]??"dashboard",ze=()=>{const{isLoggedIn:t,isAdmin:n,signOut:s}=B(),[d,r]=c.useState(R),[i,a]=c.useState(),[l,h]=c.useState(ye);c.useEffect(()=>{const u=()=>r(R());return window.addEventListener("popstate",u),(()=>window.removeEventListener("popstate",u))},[]),c.useEffect(()=>{t&&!n&&d==="settings"&&(window.history.replaceState({},"",E.dashboard),r("dashboard"))},[d,n,t]);const o=u=>{const p=u==="settings"&&!n?"dashboard":u,j=E[p];j!==window.location.pathname&&window.history.pushState({},"",j),r(p)},m=u=>{const p=Object.prototype.hasOwnProperty.call(E,u)?u:"dashboard";o(p)},f=async()=>{try{await s()}catch(u){console.error("退出登录失败",u)}},x=()=>{h(u=>{const p=!u;return ve(p),p})},b=u=>{a(u),o("rules")},g=()=>a(void 0);return t?e.jsx($e,{activeTab:d,isAdmin:n,collapsed:l,deliveryRuleTarget:i,onToggleCollapsed:x,onNavigate:m,onLogout:f,onConfigureDelivery:b,onDeliveryTargetHandled:g}):e.jsx(je,{})},Me=()=>e.jsx(ce,{children:e.jsx(be,{children:e.jsx(ze,{})})}),U=document.getElementById("root");if(!U)throw new Error("Could not find root element to mount to");const Be=H.createRoot(U);Be.render(e.jsx(S.StrictMode,{children:e.jsx(Me,{})}));export{_ as a,Ge as b,Ue as d,D as g,Ve as p}; diff --git a/internal/webui/static/index.html b/internal/webui/static/index.html index 6a04b2c..b45c326 100644 --- a/internal/webui/static/index.html +++ b/internal/webui/static/index.html @@ -6,7 +6,7 @@ Ydisks闲鱼助手 - 自动发货与管家系统 - + diff --git a/internal/xianyu/ws/client.go b/internal/xianyu/ws/client.go index d4b00bf..d5f4fac 100644 --- a/internal/xianyu/ws/client.go +++ b/internal/xianyu/ws/client.go @@ -904,6 +904,33 @@ func (c *Conn) SendText(ctx context.Context, myID, cid, toID, text string) error return c.sendChatContent(ctx, myID, cid, toID, content) } +// MarkChatRead 将当前会话的 PNM 消息 ID 上报为已读。 +// ctx 控制远端请求生命周期;cid 仅用于本地可观测日志;messageIDs 为待上报消息对象。 +// 返回值仅报告远端调用失败,平台拒绝会被记录为告警以保留既有调用兼容性。 +func (c *Conn) MarkChatRead(ctx context.Context, cid string, messageIDs []map[string]any) error { + // ids 是剔除空值后的 PNM ID 列表,按平台 MessageStatusService 的参数格式发送。 + ids := make([]string, 0, len(messageIDs)) + // item 为调用方传入的一条待读消息对象,可能缺少平台消息 ID。 + for _, item := range messageIDs { + // id 是当前对象中可上报的非空 PNM 消息 ID。 + if id := strings.TrimSpace(fmt.Sprint(item["messageId"])); id != "" && id != "" { + ids = append(ids, id) + } + } + c.logger.Info("准备上报闲鱼已读", "cid", cid, "message_count", len(ids), "message_ids", ids) + // response 保存平台响应;err 表示请求或传输失败。服务只接受一个 string 列表参数。 + response, err := c.request(ctx, "/r/MessageStatus/read", map[string]any{}, []any{ids}, regResponseTimeout) + if err == nil { + // code 是平台业务状态码;ok 表示响应中的状态码可被规范解析。 + if code, ok := responseCode(response["code"]); ok && code >= 400 { + c.logger.Warn("闲鱼已读上报被拒绝", "cid", cid, "message_count", len(ids), "code", code, "body", response["body"]) + } else { + c.logger.Info("闲鱼已读上报成功", "cid", cid, "message_count", len(ids), "message_ids", ids, "code", response["code"]) + } + } + return err +} + // SendImage 发送一条闲鱼聊天图片消息。imageURL 应为闲鱼可访问的 CDN/公网 URL。 func (c *Conn) SendImage(ctx context.Context, myID, cid, toID, imageURL string, width, height int) error { if width <= 0 {