feat(聊天): 增加全局未读消息提示

This commit is contained in:
Christ committed 2026-08-18 18:41:13 +08:00
1 parent 3c46dd910b
commit 9da450d940
28 files changed
+581 -142

No files matched your search

+13 -46
View File
@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, test, vi } from 'vitest';
import type { AccountDetail, ChatMessage, ChatSession } from '../../../shared/api-contract';
import { getAccountDetails, getAccountRuntimeStatuses, getChatMessagePage, getChatSessionPage, markChatRead, sendChatImage, sendChatMessage } from './api';
import { useChat } from './hooks';
import { publishChatConnectionState, publishChatLiveMessage } from './liveEvents';
vi.mock('./api', /* chatApiMockFactory 提供聊天 Hook 的确定性 API 替身。 */ () => ({
getAccountDetails: vi.fn(),
@@ -39,22 +40,8 @@ const messageFixture = { id: 1, account_id: 'account-1', chat_id: 'chat-1', mess
// sentMessageFixture 是文字发送成功后返回的消息。
const sentMessageFixture = { ...messageFixture, id: 2, message_key: 'message-2', direction: 'outgoing', content: '回复内容' } as ChatMessage;
// latestSocket 保存当前测试创建的 WebSocket 替身。
let latestSocket: {
// close 是关闭 WebSocket 的替身方法。
close: ReturnType<typeof vi.fn>;
// onopen 是 WebSocket 建立连接回调。
onopen: (() => void) | null;
// onmessage 是 WebSocket 消息回调。
onmessage: ((event: { /* data 是 WebSocket 事件数据。 */ data: string }) => void) | null;
// onclose 是 WebSocket 断开回调。
onclose: (() => void) | null;
// onerror 是 WebSocket 错误回调。
onerror: (() => void) | null;
} | null = null;
describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时连接状态。 */ () => {
beforeEach(/* 当前回调重置聊天 API 替身和 WebSocket。 */ () => {
beforeEach(/* 当前回调重置聊天 API 替身和全局实时连接状态。 */ () => {
vi.clearAllMocks();
getDetailsMock.mockResolvedValue([accountFixture]);
getRuntimeMock.mockResolvedValue({ 'account-1': { state: 'online', connected: true, failures: 0, updated_at: '2026-08-15T00:00:00Z' } });
@@ -63,17 +50,7 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时
markReadMock.mockResolvedValue({ success: true });
sendMessageMock.mockResolvedValue({ message: sentMessageFixture });
sendImageMock.mockResolvedValue({ message: sentMessageFixture });
// websocketFactory 是不连接真实服务器的 WebSocket 构造替身。
const websocketFactory = vi.fn(
// websocketConstructor 创建不连接真实服务器的 WebSocket 实例。
function websocketConstructor() {
// socket 是当前 WebSocket 连接的可控替身。
const socket = { close: vi.fn(), onopen: null, onmessage: null, onclose: null, onerror: null };
latestSocket = socket;
return socket;
},
);
vi.stubGlobal('WebSocket', websocketFactory);
publishChatConnectionState('connecting');
// localStorageStub 是聊天 Hook 记忆账号选择所需的浏览器存储替身。
Object.defineProperty(window, 'localStorage', { configurable: true, value: { getItem: vi.fn().mockReturnValue(''), setItem: vi.fn(), removeItem: vi.fn() } });
// createObjectURLMock 和 revokeObjectURLMock 模拟浏览器图片预览地址的创建与释放。
@@ -230,7 +207,7 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时
hook.unmount();
});
test('WebSocket 连接和消息事件更新聊天状态', /* 当前回调验证实时连接和消息回调边界。 */ async () => {
test('应用壳唯一实时连接发布的状态和消息会更新聊天状态', /* 当前回调验证 Chat 页面不再自行创建 WebSocket。 */ async () => {
// secondSession 是用于覆盖实时会话排序比较器的第二条会话。
const secondSession = { ...sessionFixture, chat_id: 'chat-2', last_message_at: 2, unread_count: 0 };
getSessionPageMock.mockResolvedValue({ sessions: [sessionFixture, secondSession], has_more: true, next_cursor: 2 });
@@ -250,17 +227,16 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时
// activeChatAssertion 等待实时消息目标会话选中。
() => expect(hook.result.current.activeChatID).toBe('chat-1'),
);
expect(latestSocket).not.toBeNull();
await act(
// openAction 触发 WebSocket 建立连接事件。
() => latestSocket?.onopen?.(),
// onlineAction 触发应用壳全局连接建立成功事件。
() => publishChatConnectionState('online'),
);
expect(hook.result.current.liveState).toBe('online');
// incomingMessage 是实时 WebSocket 推送的入站消息。
const incomingMessage = { ...messageFixture, id: 3, message_key: 'message-3', sent_at: 3, content: '实时消息' };
await act(
// messageAction 触发合法的实时消息事件。
() => latestSocket?.onmessage?.({ data: JSON.stringify({ message: incomingMessage }) }),
// messageAction 触发应用壳发布的合法实时消息事件。
() => publishChatLiveMessage(incomingMessage),
);
expect(hook.result.current.messages).toContainEqual(incomingMessage);
expect(hook.result.current.messages.find(/* 当前回调定位需要验证已读状态的出站消息。 */ message => message.message_key === 'outgoing-1')).toMatchObject({ read_status: 2, read_at: 3 });
@@ -268,12 +244,8 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时
{ messageId: 'message-3', sessionId: 'chat-1', cid: 'chat-1@goofish', conversationType: 1 },
]);
await act(
// invalidMessageAction 触发非法消息帧并保持状态稳定。
() => latestSocket?.onmessage?.({ data: '{broken' }),
);
await act(
// closeAction 触发 WebSocket 断开事件。
() => latestSocket?.onclose?.(),
// closeAction 触发应用壳全局连接断开事件。
() => publishChatConnectionState('offline'),
);
expect(hook.result.current.liveState).toBe('offline');
hook.unmount();
@@ -516,7 +488,7 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时
getSessionPageMock.mockResolvedValueOnce({ sessions: [unknownSession, sessionFixture], has_more: false, next_cursor: undefined });
await act(
// unknownMessageAction 触发未知会话的联系人刷新。
() => latestSocket?.onmessage?.({ data: JSON.stringify({ message: unknownMessage }) }),
() => publishChatLiveMessage(unknownMessage),
);
await waitFor(
// reloadAssertion 等待未知会话触发联系人刷新。
@@ -527,14 +499,9 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时
() => expect(hook.result.current.activeSessions).toContainEqual(unknownSession),
);
await act(
// emptyMessageAction 触发无消息载荷并保持状态稳定。
() => latestSocket?.onmessage?.({ data: JSON.stringify({}) }),
// offlineAction 触发全局连接断开状态并保持消息列表稳定。
() => publishChatConnectionState('offline'),
);
await act(
// errorAction 触发 WebSocket 错误并关闭连接。
() => latestSocket?.onerror?.(),
);
expect(latestSocket?.close).toHaveBeenCalled();
hook.unmount();
});
+50 -69
View File
@@ -3,6 +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 { publishChatUnreadStatus, subscribeToChatLiveEvents } from './liveEvents';
import { collectChatReadReceipts, filterChatSessions, formatClock, isChatAbortError, isCurrentChatRequest, markOutgoingMessagesReadByIncoming, mergeLiveMessage, mergeOlderMessages, messageTime } from './state';
import type { ChatFeatureState, ChatLiveState, SessionsByAccount } from './types';
@@ -272,6 +273,15 @@ export const useChat = (): UseChatResult => {
setActiveChatID(/* 当前回调处理集合中的单个元素。 */ current => sessions.some(/* 当前回调处理集合中的单个元素。 */ session => session.chat_id === current) ? current : sessions[0]?.chat_id || '');
}, [activeAccountID, sessionsByAccount]);
useEffect(/* 当前副作用将所有已加载账号会话的未读聚合状态回传给应用壳,红点只能在没有任何未读时消失。 */ () => {
// loadedAccountCount 保存已成功写入会话列表状态的账号数量;初始请求尚未完成或失败时不得错误发布无未读。
const loadedAccountCount = Object.keys(sessionsByAccount).length;
if (loading || (accounts.length > 0 && loadedAccountCount === 0)) return;
// hasUnreadChatMessage 保存当前所有已加载会话是否至少存在一条未读消息。
const hasUnreadChatMessage = Object.values(sessionsByAccount).some(/* sessions 保存当前账号的会话列表。 */ sessions => sessions.some(/* session 保存当前参与未读聚合判断的会话。 */ session => session.unread_count > 0));
publishChatUnreadStatus(hasUnreadChatMessage);
}, [accounts.length, loading, sessionsByAccount]);
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => {
if (!activeAccountID || refreshedAccountsRef.current.has(activeAccountID)) return;
refreshedAccountsRef.current.add(activeAccountID);
@@ -392,77 +402,48 @@ export const useChat = (): UseChatResult => {
}
}, [activeAccountID, activeChatID, hasOlder, historyCursor, messages, olderLoading]);
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => {
// disposed disposed,负责当前功能中的对应处理。
let disposed = false;
// reconnectTimer reconnect定时器,负责当前功能中的对应处理。
let reconnectTimer = 0;
// retry 重试当前操作。
let retry = 0;
// socket WebSocket 连接。
let socket: WebSocket | null = null;
// connect 连接。
const connect = (): void => {
if (disposed) return;
setLiveState('connecting');
// protocol 连接协议。
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
socket = new WebSocket(`${protocol}//${window.location.host}/api/v1/chat/ws`);
socket.onopen = /* 当前回调处理用户交互或异步状态变化。 */ () => { retry = 0; setLiveState('online'); };
socket.onmessage = /* 当前回调处理用户交互或异步状态变化。 */ event => {
try {
// payload 请求载荷。
const payload = JSON.parse(event.data);
// message 消息。
const message = payload.message as ChatMessage | undefined;
if (!message) return;
// accountID 账号标识。
const accountID = message.account_id;
setSessionsByAccount(/* 当前回调处理用户交互或异步状态变化。 */ current => {
// rows 行数据。
const rows = current[accountID] || [];
// found 匹配结果。
const found = rows.some(/* 当前回调处理集合中的单个元素。 */ row => row.chat_id === message.chat_id);
if (!found) {
void reloadSessions(accountID);
return current;
}
return { ...current, [accountID]: rows.map(/* 当前回调处理集合中的单个元素。 */ row => row.chat_id === message.chat_id ? {
...row,
last_message: message.content,
last_message_at: message.sent_at,
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 => markOutgoingMessagesReadByIncoming(mergeLiveMessage(current, message), message));
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 查询会恢复权威状态。
}
};
socket.onclose = /* 当前回调处理用户交互或异步状态变化。 */ () => {
if (disposed) return;
setLiveState('offline');
// delay 延迟。
const delay = Math.min(15_000, 1_000 * 2 ** Math.min(retry++, 4));
reconnectTimer = window.setTimeout(connect, delay);
};
socket.onerror = /* 当前回调处理用户交互或异步状态变化。 */ () => socket?.close();
};
connect();
return /* 当前回调处理用户交互或异步状态变化。 */ () => {
disposed = true;
window.clearTimeout(reconnectTimer);
socket?.close();
};
/** handleLiveMessage 将应用壳唯一连接发布的消息同步到当前聊天页的会话、消息和已读状态。 */
const handleLiveMessage = useCallback(/* 当前回调只处理类型化聊天消息,不解析原始 WebSocket 帧。 */ (message: ChatMessage): void => {
// accountID 保存当前实时消息所属账号,用于隔离不同闲鱼账号的会话状态。
const accountID = message.account_id;
setSessionsByAccount(/* 当前回调在对应账号会话列表中合并最新消息与未读计数。 */ current => {
// rows 保存当前账号已有的会话行。
const rows = current[accountID] || [];
// found 表示推送消息是否能匹配当前已加载会话;缺失时异步刷新该账号会话。
const found = rows.some(/* row 保存当前参与会话匹配的联系人行。 */ row => row.chat_id === message.chat_id);
if (!found) {
void reloadSessions(accountID);
return current;
}
return { ...current, [accountID]: rows.map(/* row 保存当前待合并实时消息的联系人行。 */ row => row.chat_id === message.chat_id ? {
...row,
last_message: message.content,
last_message_at: message.sent_at,
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 保存参与时间倒序比较的两条会话行。 */ (a, b) => b.last_message_at - a.last_message_at) };
});
if (activeAccountRef.current === accountID && activeChatRef.current === message.chat_id) {
setMessages(/* 当前回调合并实时消息并同步后续入站消息确认的出站已读状态。 */ current => markOutgoingMessagesReadByIncoming(mergeLiveMessage(current, message), message));
if (message.direction === 'incoming' && message.message_type !== 'system') {
// readReceipts 为当前实时消息生成平台要求的会话读取回执。
const readReceipts = collectChatReadReceipts([message], message.chat_id);
void markChatRead(accountID, message.chat_id, readReceipts);
}
}
}, [reloadSessions]);
useEffect(/* 当前副作用订阅认证应用壳唯一连接发布的事件,聊天页卸载时取消订阅而不关闭全局连接。 */ () => {
/** handleLiveEvent 根据事件类型分别同步连接状态或消息内容。 */
const handleLiveEvent = (event: Parameters<Parameters<typeof subscribeToChatLiveEvents>[0]>[0]): void => {
if (event.type === 'connection') {
setLiveState(event.state);
return;
}
handleLiveMessage(event.message);
};
return subscribeToChatLiveEvents(handleLiveEvent);
}, [handleLiveMessage]);
/** 根据滚动位置决定新消息是否自动滚到底部。 */
const handleMessageScroll = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ () => {
// container 容器。
+49
View File
@@ -0,0 +1,49 @@
import type { ChatMessage } from '../../../shared/api-contract';
import type { ChatLiveState } from './types';
/** ChatLiveEvent 描述全局聊天连接向已挂载聊天页面发布的最小实时事件集合。 */
export type ChatLiveEvent =
| { /** type 标识事件为连接状态变更。 */ type: 'connection'; /** state 保存连接的最新可展示状态。 */ state: ChatLiveState }
| { /** type 标识事件为一条实时聊天消息。 */ type: 'message'; /** message 保存已通过服务端权限过滤的非敏感聊天消息。 */ message: ChatMessage };
/** ChatLiveEventListener 描述聊天页订阅全局连接事件时提供的接收回调。 */
export type ChatLiveEventListener = (event: ChatLiveEvent) => void;
// listeners 保存当前已挂载聊天页面的事件订阅者;应用壳 WebSocket 是唯一发布者,订阅者自行注销。
const listeners = new Set<ChatLiveEventListener>();
// currentConnectionState 保存最近一次全局聊天连接状态,使晚进入聊天页能立即渲染准确状态。
let currentConnectionState: ChatLiveState = 'connecting';
// unreadStatusListeners 保存全局通知 owner 的未读状态监听者;Chat 页面是唯一汇总并发布未读状态的消费者。
const unreadStatusListeners = new Set<(hasUnreadChatMessage: boolean) => void>();
/** subscribeToChatLiveEvents 注册聊天页实时事件监听,并立即回放当前连接状态,返回取消订阅函数。 */
export const subscribeToChatLiveEvents = (/** listener 保存当前聊天页接收全局实时事件的回调。 */ listener: ChatLiveEventListener): (() => void) => {
listener({ type: 'connection', state: currentConnectionState });
listeners.add(listener);
return /* 当前清理函数在聊天页卸载时移除订阅,避免保留失效 React 状态写入。 */ () => listeners.delete(listener);
};
/** publishChatConnectionState 由认证应用壳唯一 WebSocket 所有者发布连接状态给当前聊天页。 */
export const publishChatConnectionState = (state: ChatLiveState): void => {
currentConnectionState = state;
// listener 保存当前遍历到的聊天页面订阅回调。
for (const listener /* listener 保存当前遍历到的聊天页面订阅回调。 */ of listeners) listener({ type: 'connection', state });
};
/** publishChatLiveMessage 由认证应用壳唯一 WebSocket 所有者发布一条服务端聊天消息给当前聊天页。 */
export const publishChatLiveMessage = (message: ChatMessage): void => {
// listener 保存当前遍历到的聊天页面订阅回调。
for (const listener /* listener 保存当前遍历到的聊天页面订阅回调。 */ of listeners) listener({ type: 'message', message });
};
/** subscribeToChatUnreadStatus 注册全局未读状态监听,返回由通知 owner 卸载时调用的取消订阅函数。 */
export const subscribeToChatUnreadStatus = (/** listener 保存接收全部聊天会话未读聚合结果的回调。 */ listener: (hasUnreadChatMessage: boolean) => void): (() => void) => {
unreadStatusListeners.add(listener);
return /* 当前清理函数在应用壳卸载时释放未读状态监听,避免保留失效状态 setter。 */ () => unreadStatusListeners.delete(listener);
};
/** publishChatUnreadStatus 由 Chat 页面按所有已加载会话的 unread_count 聚合结果更新侧边栏红点。 */
export const publishChatUnreadStatus = (hasUnreadChatMessage: boolean): void => {
// listener 保存当前遍历到的未读状态监听回调。
for (const listener /* listener 保存当前遍历到的未读状态监听回调。 */ of unreadStatusListeners) listener(hasUnreadChatMessage);
};
@@ -0,0 +1,205 @@
// @vitest-environment jsdom
import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { ChatMessage } from '../../../shared/api-contract';
import { getAccountDetails, getChatSessionPage } from './api';
import { publishChatUnreadStatus } from './liveEvents';
import { formatChatNewMessageTitle, useChatTitleNotification, useChatTitleNotifier } from './titleNotification';
vi.mock('./api', /* chatApiMockFactory 提供标题通知初始化未读状态读取的确定性 API 替身。 */ () => ({
getAccountDetails: vi.fn(),
getChatSessionPage: vi.fn(),
}));
// getAccountDetailsMock 是标题通知初始化账号读取的可控替身。
const getAccountDetailsMock = vi.mocked(getAccountDetails);
// getChatSessionPageMock 是标题通知初始化会话未读读取的可控替身。
const getChatSessionPageMock = vi.mocked(getChatSessionPage);
// originalTitle 保存每个测试开始前的浏览器标题,测试结束后必须恢复以避免影响其他聊天 Hook 用例。
let originalTitle = '';
// incomingMessageFixture 是触发标题提醒的普通买家入站消息。
const incomingMessageFixture = { direction: 'incoming', message_type: 'text' } as ChatMessage;
// latestSocket 保存全局标题通知 Hook 创建的可控 WebSocket 替身。
let latestSocket: {
// close 是关闭通知连接的替身方法。
close: ReturnType<typeof vi.fn>;
// onopen 是通知连接建立成功回调。
onopen: (() => void) | null;
// onmessage 是服务端广播聊天帧的回调。
onmessage: ((event: { /* data 保存服务端推送的 JSON 文本。 */ data: string }) => void) | null;
// onclose 是通知连接关闭回调。
onclose: (() => void) | null;
// onerror 是通知连接异常回调。
onerror: (() => void) | null;
} | null = null;
describe('chat title notification', /* 当前测试组验证后台实时消息的浏览器标题提示行为。 */ () => {
beforeEach(/* 当前回调重置标题和时间,隔离浏览器全局状态。 */ () => {
originalTitle = document.title;
document.title = 'Ydisks闲鱼助手';
vi.useFakeTimers();
latestSocket = null;
getAccountDetailsMock.mockResolvedValue([]);
getChatSessionPageMock.mockResolvedValue({ sessions: [], has_more: false });
});
afterEach(/* 当前回调恢复真实计时器、标题和浏览器焦点方法,避免泄漏到其他前端测试。 */ () => {
vi.useRealTimers();
vi.restoreAllMocks();
vi.unstubAllGlobals();
document.title = originalTitle;
});
test('格式化标题不会暴露新消息数量', /* 当前回调验证标题只展示固定的新消息标记。 */ () => {
expect(formatChatNewMessageTitle('应用')).toBe('【新消息】应用');
});
test('新消息会累计闪烁标题并在重新聚焦后恢复', /* 当前回调验证前后台一致的实时计数、闪烁周期与用户确认后的清除行为。 */ () => {
// hook 是标题通知 Hook 的渲染结果。
const hook = renderHook(
// titleNotificationHookFactory 创建浏览器标题通知 Hook。
() => useChatTitleNotifier(),
);
act(
// firstMessageAction 模拟第一条实时消息。
() => hook.result.current.notifyIncomingMessage(incomingMessageFixture),
);
act(
// secondMessageAction 模拟同一提醒周期收到第二条消息。
() => hook.result.current.notifyIncomingMessage(incomingMessageFixture),
);
expect(document.title).toBe('【新消息】Ydisks闲鱼助手');
expect(hook.result.current.hasUnreadChatMessage).toBe(true);
act(
// flashAction 推进一个闪烁周期以展示原始标题相位。
() => vi.advanceTimersByTime(1_000),
);
expect(document.title).toBe('Ydisks闲鱼助手');
expect(hook.result.current.hasUnreadChatMessage).toBe(true);
act(
// unreadClearedAction 模拟聊天页确认所有会话均无未读消息。
() => publishChatUnreadStatus(false),
);
expect(hook.result.current.hasUnreadChatMessage).toBe(false);
act(
// focusAction 模拟用户重新聚焦浏览器窗口,确认已看到提醒。
() => window.dispatchEvent(new Event('focus')),
);
expect(document.title).toBe('Ydisks闲鱼助手');
hook.unmount();
});
test('系统消息和本机发出的消息不会改写浏览器标题', /* 当前回调验证不属于买家新消息的事件不会触发标题提醒。 */ () => {
// hook 是消息方向过滤场景的标题通知 Hook 渲染结果。
const hook = renderHook(
// messageDirectionHookFactory 创建消息方向过滤场景。
() => useChatTitleNotifier(),
);
act(
// outgoingMessageAction 模拟本机发送的消息。
() => hook.result.current.notifyIncomingMessage({ ...incomingMessageFixture, direction: 'outgoing' }),
);
act(
// systemMessageAction 模拟后台收到不应通知用户的系统消息。
() => hook.result.current.notifyIncomingMessage({ ...incomingMessageFixture, message_type: 'system' }),
);
expect(document.title).toBe('Ydisks闲鱼助手');
hook.unmount();
});
test('认证应用壳挂载的通知连接会接收在线聊天页之外的消息', /* 当前回调验证标题提醒的 WebSocket 不依赖 Chat 页面是否已打开。 */ () => {
// websocketFactory 创建不连接真实服务的全局通知连接替身。
const websocketFactory = vi.fn(
// websocketConstructor 创建可手动触发服务端消息的连接对象。
function websocketConstructor() {
// socket 是当前全局通知连接的可控替身。
const socket = { close: vi.fn(), onopen: null, onmessage: null, onclose: null, onerror: null };
latestSocket = socket;
return socket;
},
);
vi.stubGlobal('WebSocket', websocketFactory);
// hook 是认证应用壳中全局标题通知连接的渲染结果。
const hook = renderHook(
// globalNotificationHookFactory 挂载不依赖 Chat 页面存在的全局通知 Hook。
() => useChatTitleNotification(),
);
expect(websocketFactory).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/chat\/ws$/));
act(
// incomingMessageAction 模拟用户停留在仪表盘等其他页面时服务端推送买家消息。
() => latestSocket?.onmessage?.({ data: JSON.stringify({ message: incomingMessageFixture }) }),
);
expect(document.title).toBe('【新消息】Ydisks闲鱼助手');
expect(hook.result.current.hasUnreadChatMessage).toBe(true);
hook.unmount();
expect(latestSocket?.close).toHaveBeenCalledTimes(1);
});
test('应用壳启动时会根据已有未读会话点亮聊天红点', /* 当前回调验证红点不只依赖当前浏览器会话期间的新 WebSocket 消息。 */ async () => {
// unreadSession 保存服务端返回的一条历史未读会话。
const unreadSession = { account_id: 'account-1', chat_id: 'chat-1', buyer_id: 'buyer-1', buyer_name: '买家', last_message: '历史未读消息', last_message_at: 1, unread_count: 1 };
getAccountDetailsMock.mockResolvedValue([{ id: 'account-1', enabled: true }] as never);
getChatSessionPageMock.mockResolvedValue({ sessions: [unreadSession], has_more: false });
// websocketFactory 创建不会连接真实服务的全局通知连接替身。
const websocketFactory = vi.fn(
// websocketConstructor 创建初始化未读读取测试所需的通知连接对象。
function websocketConstructor() {
// socket 是当前测试创建的通知连接替身。
const socket = { close: vi.fn(), onopen: null, onmessage: null, onclose: null, onerror: null };
latestSocket = socket;
return socket;
},
);
vi.stubGlobal('WebSocket', websocketFactory);
// hook 是应用壳初始化阶段的全局标题通知 Hook。
const hook = renderHook(
// initialUnreadHookFactory 创建验证历史未读状态的通知 Hook。
() => useChatTitleNotification(),
);
await act(
// initialUnreadFlushAction 显式刷新初始化账号和会话读取 Promise,避免假定时器阻塞 waitFor 轮询。
async () => { await Promise.resolve(); await Promise.resolve(); },
);
expect(hook.result.current.hasUnreadChatMessage).toBe(true);
expect(getChatSessionPageMock).toHaveBeenCalledWith('account-1', undefined, expect.objectContaining({ signal: expect.any(AbortSignal) }));
hook.unmount();
});
test('延迟的初始未读快照不会覆盖期间收到的实时消息', /* 当前回调验证初始查询与 WebSocket 入站消息的先后竞态。 */ async () => {
// resolveAccounts 用于在实时消息到达后才完成初始账号快照请求。
let resolveAccounts: ((accounts: never[]) => void) | undefined;
getAccountDetailsMock.mockImplementationOnce(
// delayedAccountsRequest 维持初始账号读取未完成,模拟网络慢响应。
() => new Promise<never[]>(/* delayedAccountsExecutor 保存延迟账号快照的完成函数。 */ resolve => { resolveAccounts = resolve; }),
);
// websocketFactory 创建可在初始快照未完成时接收消息的全局通知连接替身。
const websocketFactory = vi.fn(
// websocketConstructor 创建实时竞态测试所需的通知连接对象。
function websocketConstructor() {
// socket 是当前测试创建的通知连接替身。
const socket = { close: vi.fn(), onopen: null, onmessage: null, onclose: null, onerror: null };
latestSocket = socket;
return socket;
},
);
vi.stubGlobal('WebSocket', websocketFactory);
// hook 是初始未读快照仍在加载时的全局标题通知 Hook。
const hook = renderHook(
// delayedSnapshotHookFactory 创建初始快照与实时消息竞态场景。
() => useChatTitleNotification(),
);
act(
// realtimeMessageAction 模拟慢快照期间先收到一条买家消息。
() => latestSocket?.onmessage?.({ data: JSON.stringify({ message: incomingMessageFixture }) }),
);
await act(
// staleSnapshotAction 在收到实时消息后才让旧快照返回无账号、无未读结果。
async () => { resolveAccounts?.([]); await Promise.resolve(); },
);
expect(hook.result.current.hasUnreadChatMessage).toBe(true);
hook.unmount();
});
});
@@ -0,0 +1,178 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import type { ChatMessage } from '../../../shared/api-contract';
import { getAccountDetails, getChatSessionPage } from './api';
import { publishChatConnectionState, publishChatLiveMessage, subscribeToChatUnreadStatus } from './liveEvents';
/** titleFlashIntervalMs 定义浏览器标题在提示文本与原始标题间切换的周期,单位为毫秒。 */
const titleFlashIntervalMs = 1_000;
/** formatChatNewMessageTitle 根据原始标题生成不暴露消息数量的浏览器新消息提示文本。 */
export const formatChatNewMessageTitle = (baseTitle: string): string => {
return `【新消息】${baseTitle}`;
};
/** ChatTitleNotifierResult 描述标题闪烁与侧边栏新消息标记的受控状态。 */
export type ChatTitleNotifierResult = {
/** notifyIncomingMessage 接收实时消息并决定是否产生标题和红点提醒。 */
notifyIncomingMessage: (message: ChatMessage) => void;
/** hasUnreadChatMessage 表示所有已知聊天会话中是否仍存在未读普通消息。 */
hasUnreadChatMessage: boolean;
};
/** useChatTitleNotifier 管理浏览器标题闪烁,并返回由实时消息连接调用的通知入口。 */
export const useChatTitleNotifier = (): ChatTitleNotifierResult => {
// newMessageCount 保存当前应用会话收到、尚未被浏览器重新聚焦确认的入站消息数量。
const [newMessageCount, setNewMessageCount] = useState(0);
// hasUnreadChatMessage 保存在线聊天入口的持久红点状态;只有所有会话未读数归零时才清除。
const [hasUnreadChatMessage, setHasUnreadChatMessage] = useState(false);
// baseTitleRef 保存挂载通知服务前的标题;本 Hook 卸载时必须恢复该标题,不覆盖其他页面的标题策略。
const baseTitleRef = useRef(document.title);
// realtimeUnreadVersionRef 记录初始未读快照开始后收到的实时消息次数,阻止旧快照覆盖新消息提醒。
const realtimeUnreadVersionRef = useRef(0);
useEffect(/* 当前副作用在用户回到页面时清除标题提示,并在卸载时移除全局监听。 */ () => {
/** clearTitleNotification 在用户重新看到聊天页面后确认所有临时标题提醒。 */
const clearTitleNotification = (): void => setNewMessageCount(0);
/** handleVisibilityChange 只在页面重新可见时清除提醒,后台切换不影响未读计数。 */
const handleVisibilityChange = (): void => {
if (document.visibilityState === 'visible') clearTitleNotification();
};
window.addEventListener('focus', clearTitleNotification);
document.addEventListener('visibilitychange', handleVisibilityChange);
return /* 当前清理函数释放浏览器事件监听,避免注销后仍修改标题状态。 */ () => {
window.removeEventListener('focus', clearTitleNotification);
document.removeEventListener('visibilitychange', handleVisibilityChange);
};
}, []);
useEffect(/* 当前副作用将未确认消息数同步到浏览器标题,并负责闪烁定时器的创建和销毁。 */ () => {
if (newMessageCount <= 0) {
document.title = baseTitleRef.current;
return;
}
// showNotificationTitle 表示本次闪烁周期是否展示带计数的提醒标题。
let showNotificationTitle = true;
/** updateTitle 将当前闪烁相位写入浏览器标签标题。 */
const updateTitle = (): void => {
document.title = showNotificationTitle
? formatChatNewMessageTitle(baseTitleRef.current)
: baseTitleRef.current;
};
updateTitle();
// flashTimer 由此 effect 独占;计数变化或 Hook 卸载时必须清除,避免后台残留定时器。
const flashTimer = window.setInterval(/* 当前回调切换标题相位以形成新消息闪烁提示。 */ () => {
showNotificationTitle = !showNotificationTitle;
updateTitle();
}, titleFlashIntervalMs);
return /* 当前清理函数停止旧计数对应的定时器,并将标题恢复为进入聊天页前的值。 */ () => {
window.clearInterval(flashTimer);
document.title = baseTitleRef.current;
};
}, [newMessageCount]);
useEffect(/* 当前副作用在认证应用壳启动时读取各启用账号的会话未读状态,取消后不写入页面状态。 */ () => {
// controller 取消应用壳卸载后尚未完成的账号和会话读取请求。
const controller = new AbortController();
// snapshotVersion 保存本次未读快照启动时的实时消息版本,响应只有版本未变化时才可写入红点状态。
const snapshotVersion = realtimeUnreadVersionRef.current;
/** loadUnreadStatus 并行读取启用账号的会话首页,以服务端 unread_count 初始化侧边栏红点。 */
const loadUnreadStatus = async (): Promise<void> => {
try {
// accounts 保存当前用户可见的账号摘要,敏感凭证不会进入前端状态。
const accounts = await getAccountDetails({ signal: controller.signal });
// enabledAccounts 保存需要查询会话未读数的启用账号。
const enabledAccounts = accounts.filter(/* account 保存当前判断启用状态的账号摘要。 */ account => account.enabled);
// pages 保存各启用账号并行读取的会话首页结果。
const pages = await Promise.all(enabledAccounts.map(/* account 保存当前需要读取会话首页的启用账号。 */ account => getChatSessionPage(account.id, undefined, { signal: controller.signal })));
if (controller.signal.aborted || realtimeUnreadVersionRef.current !== snapshotVersion) return;
// hasUnread 保存所有账号会话中是否仍有服务端标记的未读消息。
const hasUnread = pages.some(/* page 保存当前账号会话首页,用于检查其未读计数。 */ page => page.sessions.some(/* session 保存当前参与未读判断的会话。 */ session => session.unread_count > 0));
setHasUnreadChatMessage(hasUnread);
} catch {
// 初始未读读取失败时保留实时消息已点亮的红点,避免网络暂态错误错误清除提醒。
}
};
void loadUnreadStatus();
return /* 当前清理函数取消初始未读读取,避免注销后响应覆盖新会话状态。 */ () => controller.abort();
}, []);
useEffect(/* 当前副作用接收 Chat 页面已读确认后的会话未读聚合状态,只有为 false 才清除红点。 */ () => subscribeToChatUnreadStatus(setHasUnreadChatMessage), []);
/** notifyIncomingMessage 在收到普通入站消息时累加标题提示并标记全局仍有未读聊天消息。 */
const notifyIncomingMessage = useCallback(/* 当前回调由实时 WebSocket 消息入口调用,使用户在当前浏览器窗口也能看见标题变化。 */ (message: ChatMessage): void => {
if (message.direction !== 'incoming' || message.message_type === 'system') return;
realtimeUnreadVersionRef.current += 1;
setNewMessageCount(/* 当前状态更新基于上一条实时消息计数累计,避免同一批 WebSocket 帧丢失数量。 */ current => current + 1);
setHasUnreadChatMessage(true);
}, []);
return { notifyIncomingMessage, hasUnreadChatMessage };
};
/** ChatTitleNotificationResult 描述应用壳向侧边栏提供的聊天新消息标记控制。 */
export type ChatTitleNotificationResult = Pick<ChatTitleNotifierResult, 'hasUnreadChatMessage'>;
/** useChatTitleNotification 在认证应用壳内维持全局聊天 WebSocket,并把普通入站消息转为标题提醒。 */
export const useChatTitleNotification = (): ChatTitleNotificationResult => {
// titleNotifier 保存标题和侧边栏红点状态;其消息处理函数保持稳定,重连 effect 不会因计数更新而重建 WebSocket。
const titleNotifier = useChatTitleNotifier();
// notifyIncomingMessage 保存标题提醒的稳定入口;hasUnreadChatMessage 保存侧边栏红点应展示的全局未读状态。
const { notifyIncomingMessage, hasUnreadChatMessage } = titleNotifier;
useEffect(/* 当前副作用拥有全局通知 WebSocket 的连接、退避重连和卸载清理生命周期。 */ () => {
// disposed 标记应用壳是否已经卸载;卸载后禁止关闭回调重新创建连接。
let disposed = false;
// reconnectTimer 保存当前退避重连定时器;仅此 effect 可以清理它。
let reconnectTimer = 0;
// retryCount 保存连续断开次数,用于限制退避延迟的最大值。
let retryCount = 0;
// socket 保存本轮通知连接;卸载时由该 Hook 关闭。
let socket: WebSocket | null = null;
/** connect 建立认证 Cookie 自动携带的通知连接,并在异常关闭后安排有限退避重连。 */
const connect = (): void => {
if (disposed) return;
publishChatConnectionState('connecting');
// protocol 根据当前页面协议选择对应安全级别的 WebSocket 方案,避免 HTTPS 页面混合内容失败。
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
socket = new WebSocket(`${protocol}//${window.location.host}/api/v1/chat/ws`);
socket.onopen = /* 当前回调在连接成功后重置后续异常关闭的退避次数并通知聊天页。 */ () => {
retryCount = 0;
publishChatConnectionState('online');
};
socket.onmessage = /* 当前回调只解析服务端广播的聊天消息,损坏帧不影响后续连接。 */ event => {
try {
// payload 保存服务端推送的 JSON 对象。
const payload = JSON.parse(event.data) as {
/** message 保存服务端广播的可选实时聊天消息。 */
message?: ChatMessage;
};
// message 保存可能存在的实时聊天消息;其他 WebSocket 帧无需产生标题提醒。
const message = payload.message;
if (message) {
notifyIncomingMessage(message);
publishChatLiveMessage(message);
}
} catch {
// 忽略非聊天格式帧,下一条合法广播仍可正常触发通知。
}
};
socket.onclose = /* 当前回调在连接非主动关闭时以有限指数退避重新订阅通知。 */ () => {
if (disposed) return;
publishChatConnectionState('offline');
// delayMs 保存下一次重连等待时间,单位为毫秒,最长不超过十五秒。
const delayMs = Math.min(15_000, 1_000 * 2 ** Math.min(retryCount++, 4));
reconnectTimer = window.setTimeout(connect, delayMs);
};
socket.onerror = /* 当前回调将错误统一转换为关闭事件,以复用唯一的重连策略。 */ () => socket?.close();
};
connect();
return /* 当前清理函数停止待执行重连并关闭当前连接,确保应用壳注销后不保留后台通知任务。 */ () => {
disposed = true;
window.clearTimeout(reconnectTimer);
socket?.close();
publishChatConnectionState('offline');
};
}, [notifyIncomingMessage]);
return { hasUnreadChatMessage };
};
@@ -1,6 +1,7 @@
import React, { lazy, Suspense, useEffect, useState } from 'react';
import Sidebar from '../../shared/ui/Sidebar';
import type { Item } from '../../shared/api-contract';
import { useChatTitleNotification } from '../features/chat/titleNotification';
import { getHealth } from '../features/system/api';
import type { BuildInfo } from '../features/system/types';
@@ -133,6 +134,8 @@ const AuthenticatedShell: React.FC<AuthenticatedShellProps> = ({
}) => {
// buildInfo 保存壳层加载的公开构建版本,侧边栏保持为无请求的共享展示组件。
const [buildInfo, setBuildInfo] = useState<BuildInfo>({ version: 'dev', commit: 'unknown' });
// hasUnreadChatMessage 保存侧边栏在线聊天入口的服务端/实时聚合未读状态,不因导航动作改变。
const { hasUnreadChatMessage } = useChatTitleNotification();
useEffect(/* effect 在壳层挂载时读取版本信息,并在卸载时中止尚未完成的请求。 */ () => {
// controller 取消壳层卸载后不再需要的健康检查请求。
@@ -158,6 +161,7 @@ const AuthenticatedShell: React.FC<AuthenticatedShellProps> = ({
onNavigate={onNavigate}
onLogout={onLogout}
buildInfo={buildInfo}
hasUnreadChatMessage={hasUnreadChatMessage}
/>
<main className={`h-screen min-w-0 flex-1 overflow-x-hidden overflow-y-auto scroll-smooth transition-[margin] duration-300 ${collapsed ? 'ml-16' : 'ml-64'} ${activeTab === 'chat' ? 'p-4 md:p-6' : 'p-8 md:p-12'}`}>
+8 -5
View File
@@ -22,11 +22,14 @@ describe('online chat UI contract', () => {
expect(chat).not.toContain('选择一个买家');
} /* 测试回调断言用户标签不误用买家角色。 */);
test('frontend connects only to the application chat websocket', () => {
const chatHook = source('app/features/chat/hooks.ts'); /* chatHook 表示chatHook。 */
expect(chatHook).toContain('/api/v1/chat/ws');
expect(chatHook).not.toContain('wss-goofish.dingtalk.com');
} /* 测试回调断言前端只连接应用层聊天 WebSocket。 */);
test('应用壳拥有唯一应用层聊天 WebSocket,聊天页仅订阅其事件', () => {
const chatHook = source('app/features/chat/hooks.ts'); /* chatHook 保存聊天页状态 Hook 源码。 */
const titleNotification = source('app/features/chat/titleNotification.ts'); /* titleNotification 保存认证应用壳实时连接 owner 源码。 */
expect(titleNotification).toContain('/api/v1/chat/ws');
expect(titleNotification).not.toContain('wss-goofish.dingtalk.com');
expect(chatHook).toContain('subscribeToChatLiveEvents');
expect(chatHook).not.toContain('new WebSocket(');
} /* 测试回调断言前端唯一连接归属应用壳,Chat 页面不会重复建连。 */);
test('renders peer/self identity and verified media capabilities', () => {
const chat = source('app/features/chat/pages/Chat.tsx'); /* chat 表示chat。 */
+49
View File
@@ -0,0 +1,49 @@
// @vitest-environment jsdom
import { render, screen } from '@testing-library/react';
import { describe, expect, test, vi } from 'vitest';
import Sidebar from './Sidebar';
describe('Sidebar', /* 当前测试组验证全局聊天新消息状态在侧边栏中的可见标记。 */ () => {
test('未查看聊天消息时仅在在线聊天入口显示红点', /* 当前回调验证红点出现与消失不依赖页面标题状态。 */ () => {
// navigationHandler 是侧边栏导航测试使用的无副作用回调。
const navigationHandler = vi.fn();
// logoutHandler 是侧边栏注销测试使用的无副作用回调。
const logoutHandler = vi.fn();
// collapseHandler 是侧边栏折叠测试使用的无副作用回调。
const collapseHandler = vi.fn();
// buildInfo 是渲染侧边栏所需的最小公开构建标识。
const buildInfo = { version: 'dev', commit: 'test' };
// view 保存带有新消息状态的侧边栏渲染控制器。
const view = render(
<Sidebar
activeTab="dashboard"
collapsed={false}
onToggleCollapsed={collapseHandler}
onNavigate={navigationHandler}
onLogout={logoutHandler}
buildInfo={buildInfo}
hasUnreadChatMessage
/>,
);
// unreadIndicator 表示挂载在聊天图标右上角的未读提示元素。
const unreadIndicator = screen.getByLabelText('在线聊天有未读消息');
expect(unreadIndicator).toBeTruthy();
expect(unreadIndicator.classList.contains('absolute')).toBe(true);
expect(unreadIndicator.classList.contains('-right-1')).toBe(true);
expect(unreadIndicator.classList.contains('-top-1')).toBe(true);
expect(unreadIndicator.classList.contains('h-3')).toBe(true);
expect(unreadIndicator.classList.contains('w-3')).toBe(true);
view.rerender(
<Sidebar
activeTab="dashboard"
collapsed={false}
onToggleCollapsed={collapseHandler}
onNavigate={navigationHandler}
onLogout={logoutHandler}
buildInfo={buildInfo}
hasUnreadChatMessage={false}
/>,
);
expect(screen.queryByLabelText('在线聊天有未读消息')).toBeNull();
});
});
+6 -2
View File
@@ -22,11 +22,12 @@ interface SidebarProps {
/** onNavigate 表示切换主导航页面的回调。 */ onNavigate: (tab: string) => void;
/** onLogout 表示注销当前会话的回调。 */ onLogout: () => void;
/** buildInfo 是由应用壳加载并传入的公开构建版本信息。 */ buildInfo: SidebarBuildInfo;
/** hasUnreadChatMessage 表示在线聊天入口是否仍有未读消息,需要展示红点。 */ hasUnreadChatMessage?: boolean;
}
// Sidebar 渲染侧边栏导航组件。
const Sidebar: React.FC<SidebarProps> = ({
activeTab, isAdmin = false, collapsed, onToggleCollapsed, onNavigate, onLogout, buildInfo,
activeTab, isAdmin = false, collapsed, onToggleCollapsed, onNavigate, onLogout, buildInfo, hasUnreadChatMessage = false,
}) => {
// menuItems 侧边栏菜单项。
const menuItems = [
@@ -77,7 +78,10 @@ const Sidebar: React.FC<SidebarProps> = ({
: 'text-slate-500 hover:bg-slate-100 hover:text-slate-900'
}`}
>
<Icon className={`h-[19px] w-[19px] shrink-0 ${active ? 'text-white' : 'text-slate-400 group-hover:text-slate-700'}`} />
<span className="relative flex h-[19px] w-[19px] shrink-0">
<Icon className={`h-[19px] w-[19px] ${active ? 'text-white' : 'text-slate-400 group-hover:text-slate-700'}`} />
{item.id === 'chat' && hasUnreadChatMessage && <span className="absolute -right-1 -top-1 h-3 w-3 rounded-full border-2 border-white bg-red-500" role="status" aria-label="在线聊天有未读消息" />}
</span>
{!collapsed && <span className="truncate text-sm font-bold">{item.label}</span>}
{active && !collapsed && <span className="ml-auto h-1.5 w-1.5 rounded-full bg-white/90" />}
</button>
@@ -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-D_-iR6Jf.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.siLine truncated
import{r as n,j as e,b as ie,c as Oe}from"./react-vendor-C_od1ZSF.js";import{g as X,c as Pe,o as ke,p as ae,a as ce,d as Le}from"./index-CNpXfeP4.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=Pe(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=>Le(`/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)=>Le(`/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:Pe(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,Line truncated
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(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)&&a<r},As=(s,t)=>s.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 Line truncated
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(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)&&a<r},As=(s,t)=>s.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 Line truncated
@@ -1,10 +1,10 @@
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 O,Y as ee,L as V,N as U,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-D_-iR6Jf.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(O,{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(O,{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",{vaLine truncated
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 O,Y as ee,L as V,N as U,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,c as de,p as xe,d as pe,a as Y,b as me}from"./index-CNpXfeP4.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(O,{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(O,{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,placeLine truncated
VIP-002
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.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(V,{className:"w-4 h-4 animate-spin"}):e.jsx(O,{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(V,{className:"w-4 h-4 animate-spin"}):e.jsx(U,{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(`
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(V,{className:"w-4 h-4 animate-spin"}):e.jsx(O,{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(V,{className:"w-4 h-4 animate-spin"}):e.jsx(U,{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 de(n,["cards","data","items"]).map(be)},ye=async l=>Y("/api/v1/cards",K(l)),J=async(l,n)=>xe(`/api/v1/cards/${l}`,K(n)),fe=async l=>pe(`/api/v1/cards/${l}`),je=async(l,n)=>{const a=new FormData;return a.append("file",l),me("/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 L=await Ne(p,x,{signal:w.signal});if(!F(B,v.current,p,b))return;E({added:L.added}),s(""),await a()}catch(L){if(!F(B,v.current,p,b))return;R((L==null?void 0:L.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:""}),D=(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(D(w,"更新失败,请重试"))}}},[d,n,f]),R=i.useCallback(async o=>{if(confirm("确认删除该卡密吗?"))try{await fe(o),await n()}catch(t){console.error("删除卡密失败:",t),alert(D(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"&&( Line truncated
VIP-MONTH-002
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(p=>p.map(B=>`"${String(B).replace(/"/g,'""')}"`).join(",")).join(`
`),k=new Blob(["\uFEFF"+g],{type:"text/csv;charset=utf-8"}),S=URL.createObjectURL(k),C=document.createElement("a");C.href=S,C.download="卡密组批量导入模板.csv",document.body.appendChild(C),C.click(),C.remove(),URL.revokeObjectURL(S)},[]);return{dataCards:s,filteredCards:h,typeFilter:N,setTypeFilter:b,nameSearch:r,setNameSearch:x,showEditModal:a,setShowEditModal:u,showAddModal:m,setShowAddModal:_,selectedCard:f,editForm:d,setEditForm:A,addForm:c,setAddForm:y,handleEdit:E,handleSaveEdit:M,handleDelete:R,handleAddCard:v,toggleCardStatus:T,copyCardID:P,downloadCardTemplate:$}},Ie=()=>{const{cards:l,loadCards:n}=Ce(),a=ke({cards:l,loadCards:n}),{dataCards:u,filteredCards:m,typeFilter:_,setTypeFilter:f,nameSearch:j,setNameSearch:d,showEditModal:A,setShowEditModal:c,showAddModal:y,setShowAddModal:N,selectedCard:b,editForm:r,setEditForm:x,addForm:s,setAddForm:h,handleEdit:E,handleSaveEdit:M,handleDelete:R,handleAddCard:v,toggleCardStatus:T,copyCardID:P,downloadCardTemplate:$}=a,o=_e({dataCards:u,loadCards:n});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.jsxs("button",{onClick:o.openBatchModal,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(O,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:(()=>N(!0)),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(U,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-gray-50 bg-surface-muted p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative sm:w-48",children:[e.jsx(ae,{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:_,onChange:(t=>f(t.target.value)),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:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(se,{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:"搜索卡密名称...",value:j,onChange:(t=>d(t.target.value)),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:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",m.length," / ",l.length," 组"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed 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:"w-[23%] px-5 py-5",children:"卡密名称"}),e.jsx("th",{className:"w-[8%] px-3 py-5",children:"卡密组ID"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"类型"}),e.jsx("th",{className:"w-[27%] px-5 py-5",children:"内容/库存"}),e.jsx("th",{className:"w-[19%] px-5 py-5",children:"描述"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"状态"}),e.jsx("th",{className:"w-[9%] px-3 py-5 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:m.map(t=>{let g="";return t.type==="data"&&t.data_content?g=`库存: ${t.data_content.split(`
`),k=new Blob(["\uFEFF"+g],{type:"text/csv;charset=utf-8"}),S=URL.createObjectURL(k),C=document.createElement("a");C.href=S,C.download="卡密组批量导入模板.csv",document.body.appendChild(C),C.click(),C.remove(),URL.revokeObjectURL(S)},[]);return{dataCards:s,filteredCards:h,typeFilter:N,setTypeFilter:b,nameSearch:r,setNameSearch:x,showEditModal:a,setShowEditModal:u,showAddModal:m,setShowAddModal:_,selectedCard:f,editForm:d,setEditForm:A,addForm:c,setAddForm:y,handleEdit:E,handleSaveEdit:M,handleDelete:R,handleAddCard:v,toggleCardStatus:T,copyCardID:P,downloadCardTemplate:$}},Te=()=>{const{cards:l,loadCards:n}=Ce(),a=ke({cards:l,loadCards:n}),{dataCards:u,filteredCards:m,typeFilter:_,setTypeFilter:f,nameSearch:j,setNameSearch:d,showEditModal:A,setShowEditModal:c,showAddModal:y,setShowAddModal:N,selectedCard:b,editForm:r,setEditForm:x,addForm:s,setAddForm:h,handleEdit:E,handleSaveEdit:M,handleDelete:R,handleAddCard:v,toggleCardStatus:T,copyCardID:P,downloadCardTemplate:$}=a,o=_e({dataCards:u,loadCards:n});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.jsxs("button",{onClick:o.openBatchModal,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(O,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:(()=>N(!0)),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(U,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-gray-50 bg-surface-muted p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative sm:w-48",children:[e.jsx(ae,{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:_,onChange:(t=>f(t.target.value)),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:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(se,{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:"搜索卡密名称...",value:j,onChange:(t=>d(t.target.value)),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:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",m.length," / ",l.length," 组"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed 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:"w-[23%] px-5 py-5",children:"卡密名称"}),e.jsx("th",{className:"w-[8%] px-3 py-5",children:"卡密组ID"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"类型"}),e.jsx("th",{className:"w-[27%] px-5 py-5",children:"内容/库存"}),e.jsx("th",{className:"w-[19%] px-5 py-5",children:"描述"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"状态"}),e.jsx("th",{className:"w-[9%] px-3 py-5 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:m.map(t=>{let g="";return t.type==="data"&&t.data_content?g=`库存: ${t.data_content.split(`
`).filter(S=>S.trim()).length} 条`:t.type==="text"&&t.text_content?g=t.text_content:t.type==="api"&&t.api_config?g=t.api_config.url:t.type==="image"&&t.image_url&&(g="图片链接"),e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(ue,{type:t.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:t.name,children:t.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:(()=>P(t.id)),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:t.id}),e.jsx(le,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${t.type==="text"?"bg-blue-50 text-blue-600":t.type==="data"?"bg-purple-50 text-purple-600":t.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:t.type==="text"?"文本":t.type==="data"?"批量":t.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:g,children:g})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:t.description||"-",children:t.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:(()=>T(t)),"aria-label":`切换卡密 ${t.name} 状态`,className:`w-12 h-8 rounded-full relative transition-colors ${t.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${t.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:(()=>E(t)),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(ne,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>R(t.id)),"aria-label":`删除卡密 ${t.name}`,className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(re,{className:"h-4 w-4"})})]})})]},t.id)})})]})}),m.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(oe,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:l.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),A&&b&&z.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:(()=>c(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(G,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:r.name||"",onChange:(t=>x({...r,name:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:r.type||"text",onChange:(t=>x({...r,type:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(b==null?void 0:b.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),r.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:r.api_url||"",onChange:(t=>x({...r,api_url:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https:/Line truncated
卡号1:密码1
卡号2:密码2
@@ -14,4 +14,4 @@ VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文
`).filter(t=>t.trim()).length:0})," 条"]})]})]}),r.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:r.image_url||"",onChange:(t=>x({...r,image_url:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"仅保存图片 URL;发货时会临时下载并上传到闲鱼"})]}),r.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:r.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:(t=>{t.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"})})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:r.delay_seconds||0,onChange:(t=>x({...r,delay_seconds:parseInt(t.target.value)||0})),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:r.description||"",onChange:(t=>x({...r,description:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:(()=>x({...r,enabled:!r.enabled})),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${r.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 ${r.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:(()=>c(!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:M,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(ie,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),y&&z.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",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:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:(()=>N(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(G,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:s.name,onChange:(t=>h({...s,name:t.target.value})),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:(()=>h({...s,type:"data",content:""})),className:`p-3 rounded-xl font-bold transition-all ${s.type==="data"?"bg-brand text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(H,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:(()=>h({...s,type:"text",content:""})),className:`p-3 rounded-xl font-bold transition-all ${s.type==="text"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(X,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:(()=>h({...s,type:"image",content:""})),className:`p-3 rounded-xl font-bold transition-all ${s.type==="image"?"bg-brand tLine truncated
CODE-789012
...`:"请输入每次发货时发送的固定文字"}),s.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-brand",children:s.content.split(`
`).filter(t=>t.trim()).length})," 条"]})]}),s.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:s.api_method,onChange:(t=>h({...s,api_method:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:s.api_timeout,onChange:(t=>h({...s,api_timeout:parseInt(t.target.value)||10})),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:s.api_headers,onChange:(t=>h({...s,api_headers:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:s.api_params,onChange:(t=>h({...s,api_params:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:s.description,onChange:(t=>h({...s,description:t.target.value})),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:s.delay_seconds,onChange:(t=>h({...s,delay_seconds:parseInt(t.target.value)||0})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:(()=>N(!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:v,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(U,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),e.jsx(he,{dataCards:u,downloadCardTemplate:$,...o})]})};export{Ie as default};
`).filter(t=>t.trim()).length})," 条"]})]}),s.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:s.api_method,onChange:(t=>h({...s,api_method:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:s.api_timeout,onChange:(t=>h({...s,api_timeout:parseInt(t.target.value)||10})),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:s.api_headers,onChange:(t=>h({...s,api_headers:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:s.api_params,onChange:(t=>h({...s,api_params:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:s.description,onChange:(t=>h({...s,description:t.target.value})),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:s.delay_seconds,onChange:(t=>h({...s,delay_seconds:parseInt(t.target.value)||0})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:(()=>N(!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:v,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(U,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),e.jsx(he,{dataCards:u,downloadCardTemplate:$,...o})]})};export{Te as default};
@@ -1 +0,0 @@
import{j as e,c as h0,r as i}from"./react-vendor-C_od1ZSF.js";import{L as me}from"./vendor-Es4K8PXl.js";import{g as k0,a as G0,b as pe}from"./index-D_-iR6Jf.js";import{o as X0}from"./contract-COFcZjyb.js";import{L as K,ak as ge,al as de,M as P0,I as xe,R as ue,ad as U0,k as he,am as _e,s as z0,an as be,ao as fe,ah as B0,X as je}from"./icons-vendor-CvzvbbIV.js";const K0=[["尊嘟假嘟","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_!!60 Line truncated
@@ -0,0 +1 @@
import{j as e,c as x0,r as i}from"./react-vendor-C_od1ZSF.js";import{L as re}from"./vendor-Es4K8PXl.js";import{e as M0,f as le,h as F0,m as P0,s as ce,i as oe,j as pe,k as me,l as z0}from"./index-CNpXfeP4.js";import{L as X,ak as ge,al as de,M as B0,I as xe,R as ue,ad as U0,k as he,am as _e,s as J0,an as be,ao as fe,ah as Q0,X as je}from"./icons-vendor-CvzvbbIV.js";const Z0=[["尊嘟假嘟","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_ Line truncated
@@ -0,0 +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,c as de,o as ge}from"./index-CNpXfeP4.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-deWqkrdG.js";import"./vendor-Es4K8PXl.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.startLine truncated
@@ -1 +0,0 @@
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-D_-iR6Jf.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-deWqkrdG.js";import"./vendor-Es4K8PXl.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},{signLine truncated
@@ -1,2 +1,2 @@
import{r as n,j as e,b as be}from"./react-vendor-C_od1ZSF.js";import{g as me,a as Q,b as We,d as Ye,p as yt}from"./index-D_-iR6Jf.js";import{c as He}from"./contract-COFcZjyb.js";import{a3 as ft,U as Me,R as we,N as Ee,a4 as _e,a5 as ye,V as jt,F as vt,B as Nt,a6 as Ge,a7 as wt,a8 as _t,A as kt,d as Ct,X as de,r as It,a9 as $e,I as De}from"./icons-vendor-CvzvbbIV.js";const Ue="ydisks-amap-js-api",St="c9b68d4ce9a2a97f22a4a439404488ca";let xe=null;const Pt=()=>St,Bt=()=>window.AMap?Promise.resolve(window.AMap):xe||(xe=new Promise((s,r)=>{const c=document.getElementById(Ue),m=c||document.createElement("script"),u=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(S)},j=()=>{window.AMap?(u(),s(window.AMap)):(u(),r(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},S=window.setTimeout(()=>{u(),r(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=j,m.id=Ue,m.async=!0,m.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(Pt())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,m.onerror=()=>{u(),r(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},c||document.head.appendChild(m)}).catch(s=>{throw xe=null,s}),xe),fe=s=>Number.isFinite(s)&&s!==0,qt=s=>{var u,j;const r=Number((u=s.location)==null?void 0:u.lng),c=Number((j=s.location)==null?void 0:j.lat),m={area:String(s.adname||"").trim(),city:String(s.cityname||"").trim(),division_id:String(s.adcode||"").trim(),longitude:r,latitude:c,poi_id:String(s.id||"").trim(),poi_name:String(s.name||"").trim(),province:String(s.pname||"").trim()};return!m.division_id||!m.province||!m.city||!m.poi_id||!m.poi_name||!fe(r)||!fe(c)||r<-180||r>180||c<-90||c>90?null:m},Ft=async(s,r)=>{if(!fe(s)||!fe(r)||s<-180||s>180||r<-90||r>90)throw new Error("经纬度无效");const c=await Bt();return new Promise((m,u)=>{new c.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[s,r],1e3,(S,w)=>{var I;if(S!=="complete"){if(S==="no_data"){m([]);return}u(new Error("高德地图附近地址查询失败,请稍后重试"));return}const R=(((I=w==null?void 0:w.poiList)==null?void 0:I.pois)||[]).map(qt).filter(U=>U!==null);m(R)})})},Rt=async s=>me("/api/v1/accounts/details",void 0,s),ze=async s=>me("/api/v1/automation-rules",void 0,s),ke=s=>s===!0||s===1||s==="1",Oe=async(s,r)=>{const c=await me("/api/v1/items",void 0,r);return He(c,["items","data","results"]).map(u=>({...u,id:u.id||`${u.cookie_id}-${u.item_id}`,is_multi_spec:ke(u.is_multi_spec),is_multi_qty_ship:ke(u.is_multi_qty_ship??u.multi_quantity_delivery),multi_quantity_delivery:ke(u.multi_quantity_delivery??u.is_multi_qty_ship)}))},Lt=async s=>Q("/api/v1/items/get-all-from-account",{cookie_id:s}),At=async(s,r)=>Ye(`/api/v1/items/${s}/${r}`),Mt=async(s,r)=>Q(`/api/v1/items/${s}`,r),Et=async s=>{const r=new FormData;r.set("cookie_id",s.cookie_id),r.set("title",s.title),r.set("description",s.description),r.set("price",s.price),r.set("original_price",s.original_price||""),r.set("quantity",String(s.quantity)),r.set("postage_mode",s.postage_mode),r.set("postage",s.postage||""),s.location&&r.set("location",JSON.stringify(s.location));for(const c of s.images)r.append("images",c);return We("/api/v1/items/publish",r)},Gt=async(s,r,c)=>Q("/api/v1/items/publish-categories/recommend",{cookie_id:s,keyword:r},c),$t=async(s,r)=>{const c=new FormData;return c.set("file",s.file),s.imagesZip&&c.set("images_zip",s.imagesZip),s.defaultCookieId&&c.set("default_cookie_id",s.defaultCookieId),c.set("fallback_category_id",s.fallbackCategory.catId),c.set("fallback_category_name",s.fallbackCategory.catName),c.set("fallback_channel_category_id",s.fallbackCategory.channelCatId||""),c.set("fallback_tb_category_id",s.fallbackCategory.tbCatId||""),s.location&&c.set("location",JSON.stringify(s.location)),c.set("publish_interval_seconds",String(s.publishIntervalSeconds??5)),We("/api/v1/items/publish-batches/preview",c,r)},Dt=async(s,r)=>Q("/api/v1/items/publish-batches",{preview_id:s},r),X=async(s,r)=>me(`/api/v1/items/publish-batches/${s}`,void 0,r),Xe=async(s=20,r)=>{const c=await me("/api/v1/items/publish-batches",{limit:s},r);return He(c,["batches","data","items"])},Te=async(s,r)=>Ye(`/api/v1/items/publish-batches/${s}`,void 0,r),Ut=async(s,r)=>Q(`/api/v1/items/publish-batches/${s}/cancel`,{},r),zt=async(s,r)=>Q(`/api/v1/items/publish-batches/${s}/retry-failed`,{},r),Ot=async(s,r,c)=>yt(`/api/v1/items/${s}/${r}`,c),Tt=s=>s.find(r=>r.status==="running"||r.status==="canceling"),Ie=s=>s==="running"||s==="canceling",Kt=s=>!!(s!=null&&s.preview_id&&Number(s.valid||0)>0),Jt=s=>!!(s!=null&&s.id&&Number(s.retryable||0)>0&&!Ie(s.status)),Zt=(s,r)=>s===r,Ke=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":returLine truncated
`),g=new Blob(["\uFEFF"+o],{type:"text/csv;charset=utf-8"}),ne=URL.createObjectURL(g),K=document.createElement("a");K.href=ne,K.download="批量铺货模板.csv",document.body.appendChild(K),K.click(),K.remove(),URL.revokeObjectURL(ne)},[]),le=n.useCallback(()=>{y(a=>({...a,cookie_id:s||a.cookie_id})),b(!0)},[s]),re=n.useCallback(()=>{F(a=>({...a,cookie_id:s||a.cookie_id})),d(!0)},[s]),ue=n.useCallback(async a=>{if(!(a?s:p.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");C(!0),navigator.geolocation.getCurrentPosition(async o=>{try{const g=await Ft(o.coords.longitude,o.coords.latitude);if(!g.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");a?(S(g),w(g[0])):(O(g),L(g[0]))}catch(g){alert(Ce(g,"获取发货地失败"))}finally{C(!1)}},o=>{C(!1),alert(o.code===o.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},[p.cookie_id,s,w,S]);return{selectedAccount:s,setSelectedAccount:r,loading:R,publishing:U,showEditModal:E,setShowEditModal:P,showAddModal:G,setShowAddModal:b,showPublishModal:B,setShowPublishModal:d,locationLoading:v,publishLocations:z,setPublishLocations:O,publishLocation:T,setPublishLocation:L,selectedItem:q,editForm:k,setEditForm:V,addForm:h,setAddForm:y,publishForm:p,setPublishForm:F,publishImagePreviews:f,handleSync:ee,handleEdit:te,handleSaveEdit:W,handleDelete:Z,handleAddItem:se,handlePublishItem:Y,downloadPublishTemplate:ae,openAddModal:le,openPublishModal:re,locateForPublish:ue}},Yt=({phase:s})=>{const r=[["upload","1 上传"],["preview","2 预检"],["running","3 发布"],["done","4 结果"]];return e.jsx("div",{className:"grid grid-cols-4 gap-2",children:r.map(([c,m])=>e.jsx("div",{className:`rounded-xl px-3 py-2 text-center text-xs font-extrabold border ${s===c?"bg-blue-600 text-white border-blue-600":"bg-gray-50 text-gray-500 border-gray-100"}`,children:m},c))})},Ht=s=>{const r=String(s||"").trim();return r?/^[¥¥]/.test(r)?r:`¥${r}`:"-"},ss=({onConfigureDelivery:s})=>{const[r,c]=n.useState([]),[m,u]=n.useState([]),[j,S]=n.useState([]),[w,R]=n.useState(""),[I,U]=n.useState(""),M=n.useRef(0),E=n.useRef(0),P=n.useCallback(async()=>{const t=++M.current,i=await Oe();t===M.current&&c(i)},[]),G=n.useCallback(async()=>{const t=++E.current,i=await ze();t===E.current&&u(i)},[]),b=Vt({selectedAccount:w,loadItems:P,loadShippingRules:G}),{showBatchModal:B,batchLoading:d,batchPhase:v,batchFile:C,setBatchFile:z,batchImagesZip:O,setBatchImagesZip:T,batchCategoryKeyword:L,setBatchCategoryKeyword:q,batchCategoryLoading:$,batchFallbackCategory:k,setBatchFallbackCategory:V,batchPreview:h,batchDetail:y,recentBatch:p,setRecentBatch:F,batchLocations:f,batchLocation:x,batchPublishIntervalSeconds:ee,setBatchPublishIntervalSeconds:te,setBatchLocations:W,setBatchLocation:Z,openBatchModal:se,handleRecommendBatchCategory:Y,openRecentBatchResult:ae,handlePreviewBatch:le,handleStartBatch:re,handleCancelBatch:ue,abandonBatchPreview:a,closeBatchModal:l,handleRetryBatchFailed:o}=b,g=Wt({selectedAccount:w,setSelectedAccount:R,setItems:c,loadItems:P,loadShippingRules:G,onConfigureDelivery:s,setBatchLocations:W,setBatchLocation:Z}),{loading:ne,publishing:K,showEditModal:je,setShowEditModal:ve,showAddModal:Qe,setShowAddModal:et,showPublishModal:tt,setShowPublishModal:st,locationLoading:he,publishLocations:pe,setPublishLocations:at,publishLocation:lt,setPublishLocation:Se,selectedItem:Pe,editForm:J,setEditForm:ge,addForm:A,setAddForm:ie,publishForm:N,setPublishForm:D,publishImagePreviews:Be,handleSync:rt,handleEdit:nt,handleSaveEdit:it,handleDelete:ct,handleAddItem:ot,handlePublishItem:dt,downloadPublishTemplate:xt,openAddModal:mt,openPublishModal:ut,locateForPublish:qe}=g;n.useEffect(()=>{const t=new AbortController,i=++M.current,_=++E.current;let oe=!0;return Promise.all([Rt({signal:t.signal}),Oe(void 0,{signal:t.signal}),ze({signal:t.signal}),Xe(20,{signal:t.signal})]).then(([H,pt,gt,Ae])=>{if(!oe||t.signal.aborted||i!==M.current||_!==E.current)return;S(H),c(pt),u(gt);const bt=Ae.find(Ne=>["running","canceling"].includes(Ne.status))||Ae.find(Ne=>Ne.status!=="preview");F(bt||null)}).catch(H=>{t.signal.aborted||console.error("加载商品配置失败:",H)}),(()=>{oe=!1,t.abort()})},[]);const ht=t=>m.filter(i=>i.cookie_id===t.cookie_id&&i.item_id===t.item_id).length>0?m.filter(i=>i.cookie_id===t.cookie_id&&i.item_id===t.item_id):m.filter(i=>i.cookie_id===t.cookie_id&&!i.item_id),Fe=n.useMemo(()=>new Map(j.map(t=>[t.id,t])),[j]),Re=n.useMemo(()=>I?r.filter(t=>t.cookie_id===I):r,[I,r]),ce=t=>{const i=Fe.get(t),_=(i==null?void 0:i.remark)||(i==null?void 0:i.nickname);return _?`${_} · ${t.slice(0,6)}`:`账号 ${t.slice(0,8)}`},Le=t=>{const i=Fe.get(t);return(i==null?void 0:i.remark)||(i==null?void 0:i.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fa Line truncated
import{r as n,j as e,b as be}from"./react-vendor-C_od1ZSF.js";import{g as me,c as We,a as Q,b as Ye,d as He,p as yt}from"./index-CNpXfeP4.js";import{a3 as ft,U as Me,R as we,N as Ee,a4 as _e,a5 as ye,V as jt,F as vt,B as Nt,a6 as Ge,a7 as wt,a8 as _t,A as kt,d as Ct,X as de,r as It,a9 as $e,I as De}from"./icons-vendor-CvzvbbIV.js";const Ue="ydisks-amap-js-api",St="c9b68d4ce9a2a97f22a4a439404488ca";let xe=null;const Pt=()=>St,Bt=()=>window.AMap?Promise.resolve(window.AMap):xe||(xe=new Promise((s,r)=>{const c=document.getElementById(Ue),m=c||document.createElement("script"),u=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(S)},j=()=>{window.AMap?(u(),s(window.AMap)):(u(),r(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},S=window.setTimeout(()=>{u(),r(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=j,m.id=Ue,m.async=!0,m.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(Pt())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,m.onerror=()=>{u(),r(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},c||document.head.appendChild(m)}).catch(s=>{throw xe=null,s}),xe),fe=s=>Number.isFinite(s)&&s!==0,qt=s=>{var u,j;const r=Number((u=s.location)==null?void 0:u.lng),c=Number((j=s.location)==null?void 0:j.lat),m={area:String(s.adname||"").trim(),city:String(s.cityname||"").trim(),division_id:String(s.adcode||"").trim(),longitude:r,latitude:c,poi_id:String(s.id||"").trim(),poi_name:String(s.name||"").trim(),province:String(s.pname||"").trim()};return!m.division_id||!m.province||!m.city||!m.poi_id||!m.poi_name||!fe(r)||!fe(c)||r<-180||r>180||c<-90||c>90?null:m},Ft=async(s,r)=>{if(!fe(s)||!fe(r)||s<-180||s>180||r<-90||r>90)throw new Error("经纬度无效");const c=await Bt();return new Promise((m,u)=>{new c.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[s,r],1e3,(S,w)=>{var I;if(S!=="complete"){if(S==="no_data"){m([]);return}u(new Error("高德地图附近地址查询失败,请稍后重试"));return}const R=(((I=w==null?void 0:w.poiList)==null?void 0:I.pois)||[]).map(qt).filter(U=>U!==null);m(R)})})},Rt=async s=>me("/api/v1/accounts/details",void 0,s),ze=async s=>me("/api/v1/automation-rules",void 0,s),ke=s=>s===!0||s===1||s==="1",Oe=async(s,r)=>{const c=await me("/api/v1/items",void 0,r);return We(c,["items","data","results"]).map(u=>({...u,id:u.id||`${u.cookie_id}-${u.item_id}`,is_multi_spec:ke(u.is_multi_spec),is_multi_qty_ship:ke(u.is_multi_qty_ship??u.multi_quantity_delivery),multi_quantity_delivery:ke(u.multi_quantity_delivery??u.is_multi_qty_ship)}))},Lt=async s=>Q("/api/v1/items/get-all-from-account",{cookie_id:s}),At=async(s,r)=>He(`/api/v1/items/${s}/${r}`),Mt=async(s,r)=>Q(`/api/v1/items/${s}`,r),Et=async s=>{const r=new FormData;r.set("cookie_id",s.cookie_id),r.set("title",s.title),r.set("description",s.description),r.set("price",s.price),r.set("original_price",s.original_price||""),r.set("quantity",String(s.quantity)),r.set("postage_mode",s.postage_mode),r.set("postage",s.postage||""),s.location&&r.set("location",JSON.stringify(s.location));for(const c of s.images)r.append("images",c);return Ye("/api/v1/items/publish",r)},Gt=async(s,r,c)=>Q("/api/v1/items/publish-categories/recommend",{cookie_id:s,keyword:r},c),$t=async(s,r)=>{const c=new FormData;return c.set("file",s.file),s.imagesZip&&c.set("images_zip",s.imagesZip),s.defaultCookieId&&c.set("default_cookie_id",s.defaultCookieId),c.set("fallback_category_id",s.fallbackCategory.catId),c.set("fallback_category_name",s.fallbackCategory.catName),c.set("fallback_channel_category_id",s.fallbackCategory.channelCatId||""),c.set("fallback_tb_category_id",s.fallbackCategory.tbCatId||""),s.location&&c.set("location",JSON.stringify(s.location)),c.set("publish_interval_seconds",String(s.publishIntervalSeconds??5)),Ye("/api/v1/items/publish-batches/preview",c,r)},Dt=async(s,r)=>Q("/api/v1/items/publish-batches",{preview_id:s},r),X=async(s,r)=>me(`/api/v1/items/publish-batches/${s}`,void 0,r),Xe=async(s=20,r)=>{const c=await me("/api/v1/items/publish-batches",{limit:s},r);return We(c,["batches","data","items"])},Te=async(s,r)=>He(`/api/v1/items/publish-batches/${s}`,void 0,r),Ut=async(s,r)=>Q(`/api/v1/items/publish-batches/${s}/cancel`,{},r),zt=async(s,r)=>Q(`/api/v1/items/publish-batches/${s}/retry-failed`,{},r),Ot=async(s,r,c)=>yt(`/api/v1/items/${s}/${r}`,c),Tt=s=>s.find(r=>r.status==="running"||r.status==="canceling"),Ie=s=>s==="running"||s==="canceling",Kt=s=>!!(s!=null&&s.preview_id&&Number(s.valid||0)>0),Jt=s=>!!(s!=null&&s.id&&Number(s.retryable||0)>0&&!Ie(s.status)),Zt=(s,r)=>s===r,Ke=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":returLine truncated
`),g=new Blob(["\uFEFF"+o],{type:"text/csv;charset=utf-8"}),ne=URL.createObjectURL(g),K=document.createElement("a");K.href=ne,K.download="批量铺货模板.csv",document.body.appendChild(K),K.click(),K.remove(),URL.revokeObjectURL(ne)},[]),le=n.useCallback(()=>{y(a=>({...a,cookie_id:s||a.cookie_id})),b(!0)},[s]),re=n.useCallback(()=>{F(a=>({...a,cookie_id:s||a.cookie_id})),d(!0)},[s]),ue=n.useCallback(async a=>{if(!(a?s:p.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");C(!0),navigator.geolocation.getCurrentPosition(async o=>{try{const g=await Ft(o.coords.longitude,o.coords.latitude);if(!g.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");a?(S(g),w(g[0])):(O(g),L(g[0]))}catch(g){alert(Ce(g,"获取发货地失败"))}finally{C(!1)}},o=>{C(!1),alert(o.code===o.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},[p.cookie_id,s,w,S]);return{selectedAccount:s,setSelectedAccount:r,loading:R,publishing:U,showEditModal:E,setShowEditModal:P,showAddModal:G,setShowAddModal:b,showPublishModal:B,setShowPublishModal:d,locationLoading:v,publishLocations:z,setPublishLocations:O,publishLocation:T,setPublishLocation:L,selectedItem:q,editForm:k,setEditForm:V,addForm:h,setAddForm:y,publishForm:p,setPublishForm:F,publishImagePreviews:f,handleSync:ee,handleEdit:te,handleSaveEdit:W,handleDelete:Z,handleAddItem:se,handlePublishItem:Y,downloadPublishTemplate:ae,openAddModal:le,openPublishModal:re,locateForPublish:ue}},Yt=({phase:s})=>{const r=[["upload","1 上传"],["preview","2 预检"],["running","3 发布"],["done","4 结果"]];return e.jsx("div",{className:"grid grid-cols-4 gap-2",children:r.map(([c,m])=>e.jsx("div",{className:`rounded-xl px-3 py-2 text-center text-xs font-extrabold border ${s===c?"bg-blue-600 text-white border-blue-600":"bg-gray-50 text-gray-500 border-gray-100"}`,children:m},c))})},Ht=s=>{const r=String(s||"").trim();return r?/^[¥¥]/.test(r)?r:`¥${r}`:"-"},ts=({onConfigureDelivery:s})=>{const[r,c]=n.useState([]),[m,u]=n.useState([]),[j,S]=n.useState([]),[w,R]=n.useState(""),[I,U]=n.useState(""),M=n.useRef(0),E=n.useRef(0),P=n.useCallback(async()=>{const t=++M.current,i=await Oe();t===M.current&&c(i)},[]),G=n.useCallback(async()=>{const t=++E.current,i=await ze();t===E.current&&u(i)},[]),b=Vt({selectedAccount:w,loadItems:P,loadShippingRules:G}),{showBatchModal:B,batchLoading:d,batchPhase:v,batchFile:C,setBatchFile:z,batchImagesZip:O,setBatchImagesZip:T,batchCategoryKeyword:L,setBatchCategoryKeyword:q,batchCategoryLoading:$,batchFallbackCategory:k,setBatchFallbackCategory:V,batchPreview:h,batchDetail:y,recentBatch:p,setRecentBatch:F,batchLocations:f,batchLocation:x,batchPublishIntervalSeconds:ee,setBatchPublishIntervalSeconds:te,setBatchLocations:W,setBatchLocation:Z,openBatchModal:se,handleRecommendBatchCategory:Y,openRecentBatchResult:ae,handlePreviewBatch:le,handleStartBatch:re,handleCancelBatch:ue,abandonBatchPreview:a,closeBatchModal:l,handleRetryBatchFailed:o}=b,g=Wt({selectedAccount:w,setSelectedAccount:R,setItems:c,loadItems:P,loadShippingRules:G,onConfigureDelivery:s,setBatchLocations:W,setBatchLocation:Z}),{loading:ne,publishing:K,showEditModal:je,setShowEditModal:ve,showAddModal:Qe,setShowAddModal:et,showPublishModal:tt,setShowPublishModal:st,locationLoading:he,publishLocations:pe,setPublishLocations:at,publishLocation:lt,setPublishLocation:Se,selectedItem:Pe,editForm:J,setEditForm:ge,addForm:A,setAddForm:ie,publishForm:N,setPublishForm:D,publishImagePreviews:Be,handleSync:rt,handleEdit:nt,handleSaveEdit:it,handleDelete:ct,handleAddItem:ot,handlePublishItem:dt,downloadPublishTemplate:xt,openAddModal:mt,openPublishModal:ut,locateForPublish:qe}=g;n.useEffect(()=>{const t=new AbortController,i=++M.current,_=++E.current;let oe=!0;return Promise.all([Rt({signal:t.signal}),Oe(void 0,{signal:t.signal}),ze({signal:t.signal}),Xe(20,{signal:t.signal})]).then(([H,pt,gt,Ae])=>{if(!oe||t.signal.aborted||i!==M.current||_!==E.current)return;S(H),c(pt),u(gt);const bt=Ae.find(Ne=>["running","canceling"].includes(Ne.status))||Ae.find(Ne=>Ne.status!=="preview");F(bt||null)}).catch(H=>{t.signal.aborted||console.error("加载商品配置失败:",H)}),(()=>{oe=!1,t.abort()})},[]);const ht=t=>m.filter(i=>i.cookie_id===t.cookie_id&&i.item_id===t.item_id).length>0?m.filter(i=>i.cookie_id===t.cookie_id&&i.item_id===t.item_id):m.filter(i=>i.cookie_id===t.cookie_id&&!i.item_id),Fe=n.useMemo(()=>new Map(j.map(t=>[t.id,t])),[j]),Re=n.useMemo(()=>I?r.filter(t=>t.cookie_id===I):r,[I,r]),ce=t=>{const i=Fe.get(t),_=(i==null?void 0:i.remark)||(i==null?void 0:i.nickname);return _?`${_} · ${t.slice(0,6)}`:`账号 ${t.slice(0,8)}`},Le=t=>{const i=Fe.get(t);return(i==null?void 0:i.remark)||(i==null?void 0:i.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fa Line truncated
@@ -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-D_-iR6Jf.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/<key>/这是测试推送内容","URL 路径里 <key> 那一段就是 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",Line truncated
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-CNpXfeP4.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/<key>/这是测试推送内容","URL 路径里 <key> 那一段就是 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",Line truncated
@@ -0,0 +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,o as ge,c as pe,b as ae,a as K,p as be,d as ye}from"./index-CNpXfeP4.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.imLine truncated
@@ -1 +0,0 @@
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-D_-iR6Jf.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.importResultLine truncated
@@ -0,0 +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,o as Ae,c as Ge,p as Ke,a as fe,d as Ue}from"./index-CNpXfeP4.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=Ge(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/vLine truncated
@@ -1 +0,0 @@
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-D_-iR6Jf.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,pageSizeLine truncated
@@ -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-D_-iR6Jf.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(()=>windLine truncated
import{r,j as e}from"./react-vendor-C_od1ZSF.js";import{a as xe,g as re,p as le}from"./index-CNpXfeP4.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(()=>windLine truncated
@@ -1 +0,0 @@
const a=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),i=(t,s=["data","items","results"])=>{let r=t,e=0;for(;e<2;e+=1){if(Array.isArray(r))return r;if(!a(r))return[];for(const n of s){const c=r[n];if(Array.isArray(c))return c;if(c===null)return[]}const o=r.data;if(a(o)){r=o;continue}return[]}return[]},d=(t,s=["data","result"])=>{let r=t,e=0;for(;e<2;e+=1){if(!a(r))return;for(const o of s){const n=r[o];if(a(n))return n}return r}};export{i as c,d as o};
@@ -0,0 +1,2 @@
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Dashboard-cuEci6bi.js","assets/react-vendor-C_od1ZSF.js","assets/dateTime-DDi7rqpW.js","assets/icons-vendor-CvzvbbIV.js","assets/charts-vendor-deWqkrdG.js","assets/vendor-Es4K8PXl.js","assets/vendor-DUblxfbA.css","assets/AccountList-B6-OE96i.js","assets/OrderList-BVg4AoME.js","assets/CardList-DqonN_6I.js","assets/ItemList-DoFg4LZD.js","assets/Settings-Cq94-QvI.js","assets/Rules-BN1y7N0V.js","assets/Notifications-BjiGqfvh.js","assets/Chat-JXKGhyxF.js"])))=>i.map(i=>d[i]);
import{c as I,j as t,r as d,d as X}from"./react-vendor-C_od1ZSF.js";import{L as z,a as R,S as ee,U as te,A as se,b as ne,c as ae,M as re,C as oe,B as ie,d as ce,Z as le,e as de,f as ue,G as O,g as he,h as me,i as fe}from"./icons-vendor-CvzvbbIV.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))o(a);new MutationObserver(a=>{for(const c of a)if(c.type==="childList")for(const r of c.addedNodes)r.tagName==="LINK"&&r.rel==="modulepreload"&&o(r)}).observe(document,{childList:!0,subtree:!0});function s(a){const c={};return a.integrity&&(c.integrity=a.integrity),a.referrerPolicy&&(c.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?c.credentials="include":a.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function o(a){if(a.ep)return;a.ep=!0;const c=s(a);fetch(a.href,c)}})();class pe extends I.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?t.jsx("main",{className:"flex min-h-screen items-center justify-center bg-canvas p-6 text-ink",children:t.jsxs("section",{className:"max-w-md text-center",children:[t.jsx("h1",{className:"text-xl font-semibold",children:"页面暂时无法显示"}),t.jsx("button",{className:"ios-btn-primary mt-6 px-4 py-2",type:"button",onClick:this.handleReload,children:"重新加载"})]})}):s}}const xe=3e4,ge=10*6e4;let A=!1;const U=()=>{A||typeof window>"u"||(A=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{A=!1}))},ye=e=>{if(!e)return"";const n=new URLSearchParams;for(const[o,a]of Object.entries(e))a!=null&&n.set(o,String(a));const s=n.toString();return s?`?${s}`:""},_=async(e,n,s={})=>{var l;const o=ye(s.params),a=`${n}${o}`,c=F(s.signal,s.timeoutMs??xe);let r;try{r=await fetch(a,{method:e,credentials:"include",signal:c.signal,headers:{...s.body===void 0?{}:{"Content-Type":"application/json"}},body:s.body===void 0?void 0:JSON.stringify(s.body)})}catch(h){throw c.signal.aborted?new Error((l=s.signal)!=null&&l.aborted?"请求已取消":"请求超时,请稍后重试"):h}finally{c.cleanup()}const u=(r.headers.get("content-type")||"").includes("application/json");if(!r.ok){r.status===401&&!s.skipAuthLogout&&U();const h=u?await r.json().catch(()=>{}):await r.text().catch(()=>{}),x=B(h,r.status);throw new Error(x)}return u?await r.json():await r.text()},j=async(e,n,s)=>_("GET",e,{params:n,...s}),L=async(e,n,s)=>_("POST",e,{body:n,...s}),at=async(e,n,s)=>_("PUT",e,{body:n,...s}),rt=async(e,n,s)=>_("DELETE",e,{params:n,...s}),be=async(e,n,s={})=>{var u;const o=F(s.signal,s.timeoutMs??ge);let a;try{a=await fetch(e,{method:"POST",credentials:"include",signal:o.signal,body:n})}catch(l){throw o.signal.aborted?new Error((u=s.signal)!=null&&u.aborted?"请求已取消":"上传超时,请稍后重试"):l}finally{o.cleanup()}const i=(a.headers.get("content-type")||"").includes("application/json")?await a.json().catch(()=>{}):await a.text().catch(()=>{});if(!a.ok){a.status===401&&U();const l=B(i,a.status),h=new Error(l);throw h.payload=i,h}return i},F=(e,n)=>{const s=new AbortController,o=()=>s.abort(e==null?void 0:e.reason);e!=null&&e.aborted?o():e==null||e.addEventListener("abort",o,{once:!0});const a=globalThis.setTimeout(()=>s.abort(new DOMException("timeout","TimeoutError")),Math.max(1,n));return{signal:s.signal,cleanup:()=>{globalThis.clearTimeout(a),e==null||e.removeEventListener("abort",o)}}},ve=e=>{if(typeof e!="object"||e===null)return!1;const n=e;return typeof n.code=="string"&&typeof n.message=="string"},B=(e,n)=>typeof e=="string"?e:ve(e)?e.message:`请求失败: ${n}`,we=async e=>L("/api/v1/session/login",e,{skipAuthLogout:!0}),je=async e=>L("/api/v1/session/initialize",{password:e},{skipAuthLogout:!0}),Le=async e=>j("/api/v1/session",void 0,e),Ce=async()=>L("/api/v1/session/logout",{}),V=d.createContext(void 0),Ne=({children:e})=>{const[n,s]=d.useState(!1),[o,a]=d.useState(!1),[c,r]=d.useState(!0),[i,u]=d.useState(!1),l=()=>{s(!1),a(!1)};d.useEffect(()=>{const g=new AbortController;let p=!0;Le({signal:g.signal}).then(y=>{if(p){if((y==null?void 0:y.initialized)===!1){u(!0),l();return}u(!1),y!=null&&y.authenticated?(s(!0),a(y.is_admin===!0)):l()}}).catch(y=>{!p||y instanceof DOMException&&y.name==="AbortError"||(u(!1),l())}).finally(()=>{p&&r(!1)});const m=()=>l();return window.addEventListener("auth:logout",m),(()=>{p=!1,g.abort(),window.removeEventListener("auth:logout",m)})},[]);const h=async g=>{const p=await we(g);return p.success&&(u(!1),s(!0),a(p.is_admin===!0)),p},x=async g=>{const p=await je(g);return p.success&&(u(!1),s(!0),a(p.is_admin===!0)),p},f=async()=>{try{await Ce()}finally{l()}};return t.jsx(V.Provider,{value:{checkingAuth:c,isLoggedIn:n,isAdmin:o,needsInit:i,signIn:h,initialize:x,siLine truncated
@@ -0,0 +1 @@
*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(147 197 253 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(147 197 253 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:rgb(var(--color-neutral-200) / 1)}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:rgb(var(--color-neutral-400) / 1)}input::placeholder,textarea::placeholder{opacity:1;color:rgb(var(--color-neutral-400) / 1)}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.\!container{width:100%!important}.container{width:100%}@media(min-width:640px){.\!container{max-width:640px!important}.container{max-width:6Line truncated
@@ -1,2 +0,0 @@
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Dashboard-f8YKyHjy.js","assets/react-vendor-C_od1ZSF.js","assets/dateTime-DDi7rqpW.js","assets/contract-COFcZjyb.js","assets/icons-vendor-CvzvbbIV.js","assets/charts-vendor-deWqkrdG.js","assets/vendor-Es4K8PXl.js","assets/vendor-DUblxfbA.css","assets/AccountList-YEP7gkPK.js","assets/OrderList-DCHT7UJE.js","assets/CardList-DLDaW7yY.js","assets/ItemList-Bdw_qpXR.js","assets/Settings-5chASb_5.js","assets/Rules-Bl0Kw94P.js","assets/Notifications-DhFFP-IW.js","assets/Chat-CAAlTzxu.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:Line truncated
@@ -1 +0,0 @@
*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(147 197 253 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(147 197 253 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:rgb(var(--color-neutral-200) / 1)}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:rgb(var(--color-neutral-400) / 1)}input::placeholder,textarea::placeholder{opacity:1;color:rgb(var(--color-neutral-400) / 1)}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.\!container{width:100%!important}.container{width:100%}@media(min-width:640px){.\!container{max-width:640px!important}.container{max-width:6Line truncated
+2 -2
View File
@@ -6,10 +6,10 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ydisks闲鱼助手 - 自动发货与管家系统</title>
<meta name="description" content="Ydisks闲鱼助手 - 自动回复、自动发货、订单管理、AI智能议价一体化解决方案" />
<script type="module" crossorigin src="/static/assets/index-D_-iR6Jf.js"></script>
<script type="module" crossorigin src="/static/assets/index-CNpXfeP4.js"></script>
<link rel="modulepreload" crossorigin href="/static/assets/react-vendor-C_od1ZSF.js">
<link rel="modulepreload" crossorigin href="/static/assets/icons-vendor-CvzvbbIV.js">
<link rel="stylesheet" crossorigin href="/static/assets/index-fhlAsi4b.css">
<link rel="stylesheet" crossorigin href="/static/assets/index-D5pYdG6n.css">
</head>
<body>
<div id="root"></div>