阶段七:完成Chat React feature化与会话消息边界

This commit is contained in:
Christ committed 2026-08-15 01:57:40 +08:00
1 parent d388d76851
commit c6da6d96c1
16 files changed
+1913 -1668

No files matched your search

File diff suppressed because it is too large. Load diff
+3 -1
View File
@@ -177,7 +177,8 @@ app shell / routes
- 已完成阶段 7 第六个 PR 切片“React Notifications feature 化与渠道/事件绑定行为边界”:按 `app/features/notifications` 提取通知渠道/SMTP API 适配层、静态渠道配置、数据与动作 Hook、渠道列表、事件绑定选择器、渠道编辑弹窗和 SMTP 面板;渠道与 SMTP 请求支持取消和代次门禁,表单支持渠道字段/独立 SMTP 校验、保存失败重试和过期响应保护;更新架构字符串测试并新增状态/API 取消信号测试,保留旧页面入口和 API 路径;前端类型检查、全量测试、注释检查和构建门禁通过,合并为一个可回滚提交;
- 已完成阶段 7 第七个 PR 切片“React Dashboard feature 化与统计/趋势查询行为边界”:按 `app/features/dashboard` 提取 Dashboard API 适配层、统计数据 Hook、趋势/排行派生状态和请求边界;概览、趋势和有效订单支持并行加载、刷新取消、失败重试与过期响应保护;新增统计派生数据、API 取消信号和请求代次测试,保留旧页面入口和 API 路径;前端类型检查、全量测试、注释检查和构建门禁通过并合并为一个可回滚提交;
- 已完成阶段 7 第八个 PR 切片“React Settings feature 化与系统配置校验边界”:按 `app/features/settings` 提取系统配置/模型/凭据 API 适配层、配置常量、表单状态和敏感字段校验;配置读取与保存支持并行加载、请求取消、失败重试和过期响应保护,登录凭据提交保留现有校验与重登录语义;新增配置裁剪、凭据校验、API 取消信号和请求代次测试,保留旧页面入口和 API 路径;
- 阶段 7 下一 PR 切片为“React Chat feature 化与会话消息行为边界”:提取聊天 API、会话/消息分页 Hook 和消息发送状态,补充会话切换取消、分页过期响应和发送失败重试测试;
- 已完成阶段 7 第九个 PR 切片“React Chat feature 化与会话消息行为边界”:按 `app/features/chat` 提取聊天 API、会话筛选/消息合并状态、账号/会话/消息分页 Hook;会话切换、联系人分页和消息加载支持取消与请求代次保护,文本/图片发送支持失败重试,WebSocket 和滚动语义保持不变;新增会话筛选、消息去重、分页过期响应、发送取消与 API 取消信号测试,保留旧页面入口和 API 路径;
- 阶段 7 下一 PR 切片为“React AccountAutomation feature 化与任务设置行为边界”:提取账号任务设置/执行 API、任务表单状态和运行结果面板,补充账号切换取消、重复执行阻断和失败重试测试;
- 禁止跳过当前入口直接开始 Engine、Automation 或 DB 的大规模拆分。
## 6. 阶段 0:治理文档与强约束
@@ -604,3 +605,4 @@ npm --prefix frontend run build
| 2026-08-15 | 完成阶段 7 第六个 PR 切片“React Notifications feature 化与渠道/事件绑定行为边界” | 按 `app/features/notifications` 提取通知渠道/SMTP API 适配层、静态渠道配置、数据与动作 Hook、渠道列表、事件绑定选择器、渠道编辑弹窗和 SMTP 面板;渠道与 SMTP 请求支持取消和代次门禁,表单支持渠道字段/独立 SMTP 校验、保存失败重试和过期响应保护;更新架构字符串测试并新增状态/API 取消信号测试,保留旧页面入口和 API 路径;前端类型检查、全量测试、注释检查和构建门禁通过并合并为一个可回滚提交 | 阶段 7:React Dashboard feature 化与统计/趋势查询行为边界 |
| 2026-08-15 | 完成阶段 7 第七个 PR 切片“React Dashboard feature 化与统计/趋势查询行为边界” | 按 `app/features/dashboard` 提取 Dashboard API 适配层、统计数据 Hook、趋势/排行派生状态和请求边界;概览、趋势和有效订单支持并行加载、刷新取消、失败重试与过期响应保护;新增统计派生数据、API 取消信号和请求代次测试,保留旧页面入口和 API 路径;前端类型检查、全量测试、注释检查和构建门禁通过并合并为一个可回滚提交 | 阶段 7:React Settings feature 化与系统配置校验边界 |
| 2026-08-15 | 完成阶段 7 第八个 PR 切片“React Settings feature 化与系统配置校验边界” | 按 `app/features/settings` 提取系统配置/模型/凭据 API 适配层、配置常量、表单状态和敏感字段校验;配置读取与保存支持并行加载、请求取消、失败重试和过期响应保护,登录凭据提交保留现有校验与重登录语义;新增配置裁剪、凭据校验、API 取消信号和请求代次测试,保留旧页面入口和 API 路径 | 阶段 7:React Chat feature 化与会话消息行为边界 |
| 2026-08-15 | 完成阶段 7 第九个 PR 切片“React Chat feature 化与会话消息行为边界” | 按 `app/features/chat` 提取聊天 API、会话筛选/消息合并状态、账号/会话/消息分页 Hook;会话切换、联系人分页和消息加载支持取消与请求代次保护,文本/图片发送支持失败重试,WebSocket 和滚动语义保持不变;新增会话筛选、消息去重、分页过期响应、发送取消与 API 取消信号测试,保留旧页面入口和 API 路径 | 阶段 7:React AccountAutomation feature 化与任务设置行为边界 |
+12
View File
@@ -0,0 +1,12 @@
/** Chat feature 使用的会话、消息和账号运行状态 API。 */
export {
getAccountDetails,
getAccountRuntimeStatuses,
getChatMessagePage,
getChatMessages,
getChatSessionPage,
getChatSessions,
markChatRead,
sendChatImage,
sendChatMessage,
} from '../../../services/api';
+491
View File
@@ -0,0 +1,491 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import type React from 'react';
import type { AccountDetail, ChatMessage, ChatSession } from '../../../types';
import { emojiURL, renderXianyuText, xianyuEmojis } from '../../../chatEmojis';
import { getAccountDetails, getAccountRuntimeStatuses, getChatMessagePage, getChatSessionPage, markChatRead, sendChatImage, sendChatMessage } from './api';
import { filterChatSessions, formatClock, isChatAbortError, isCurrentChatRequest, mergeLiveMessage, mergeOlderMessages, messageTime } from './state';
import type { ChatFeatureState, ChatLiveState, SessionsByAccount } from './types';
/** Chat Hook 对外暴露的状态、引用和交互动作。 */
export type UseChatResult = ChatFeatureState & {
/** 当前选中的会话 ID。 */
activeChatID: string;
/** 当前账号过滤后的会话。 */
filteredSessions: ChatSession[];
/** 消息滚动容器引用。 */
scrollRef: React.MutableRefObject<HTMLDivElement | null>;
/** 图片文件输入引用。 */
imageInputRef: React.MutableRefObject<HTMLInputElement | null>;
/** 更新当前账号。 */
setActiveAccountID: React.Dispatch<React.SetStateAction<string>>;
/** 更新当前会话。 */
setActiveChatID: React.Dispatch<React.SetStateAction<string>>;
/** 更新搜索文本。 */
setSearch: React.Dispatch<React.SetStateAction<string>>;
/** 更新未读筛选。 */
setUnreadOnly: React.Dispatch<React.SetStateAction<boolean>>;
/** 更新消息草稿。 */
setDraft: React.Dispatch<React.SetStateAction<string>>;
/** 更新表情选择器状态。 */
setEmojiOpen: React.Dispatch<React.SetStateAction<boolean>>;
/** 刷新当前账号会话。 */
reloadSessions: (accountID: string) => Promise<ChatSession[]>;
/** 加载更早的联系人。 */
loadMoreContacts: () => Promise<void>;
/** 加载更早的消息。 */
loadOlderMessages: () => Promise<void>;
/** 根据滚动位置更新自动滚动策略。 */
handleMessageScroll: () => void;
/** 发送文本消息。 */
handleSend: () => Promise<void>;
/** 发送图片消息。 */
handleImage: (file?: File) => Promise<void>;
/** 重试最近一次失败发送。 */
retrySend: () => Promise<void>;
/** 是否存在可重试的发送动作。 */
retryAvailable: boolean;
/** 列出指定账号的未读总数。 */
unreadForAccount: (accountID: string) => number;
/** 表情资源导出,保持页面兼容入口。 */
emojiURL: typeof emojiURL;
/** 闲鱼表情列表导出,保持页面兼容入口。 */
xianyuEmojis: typeof xianyuEmojis;
/** 闲鱼文本渲染器导出,保持页面兼容入口。 */
renderXianyuText: typeof renderXianyuText;
/** 时间格式化函数导出,保持页面兼容入口。 */
formatClock: typeof formatClock;
/** 消息时间格式化函数导出,保持页面兼容入口。 */
messageTime: typeof messageTime;
};
/** 统一管理聊天账号、会话、消息分页、实时连接和发送重试状态。 */
export const useChat = (): UseChatResult => {
// accounts 保存启用账号及其运行状态。
const [accounts, setAccounts] = useState<AccountDetail[]>([]);
// activeAccountID 保存当前选中的账号。
const [activeAccountID, setActiveAccountID] = useState('');
// sessionsByAccount 按账号隔离会话列表。
const [sessionsByAccount, setSessionsByAccount] = useState<SessionsByAccount>({});
// activeChatID 保存当前选中的会话。
const [activeChatID, setActiveChatID] = useState('');
// messages 保存当前会话消息。
const [messages, setMessages] = useState<ChatMessage[]>([]);
// search 保存会话搜索文本。
const [search, setSearch] = useState('');
// unreadOnly 控制是否仅展示未读会话。
const [unreadOnly, setUnreadOnly] = useState(false);
// draft 保存待发送文本。
const [draft, setDraft] = useState('');
// loading 表示聊天初始数据加载状态。
const [loading, setLoading] = useState(true);
// messagesLoading 表示当前会话消息加载状态。
const [messagesLoading, setMessagesLoading] = useState(false);
// olderLoading 表示历史消息分页状态。
const [olderLoading, setOlderLoading] = useState(false);
// hasOlder 表示当前会话是否还有历史消息。
const [hasOlder, setHasOlder] = useState(false);
// historyCursor 保存历史消息分页游标。
const [historyCursor, setHistoryCursor] = useState<number | undefined>();
// contactCursors 保存各账号联系人分页游标。
const [contactCursors, setContactCursors] = useState<Record<string, number | undefined>>({});
// hasMoreContacts 保存各账号是否还有联系人。
const [hasMoreContacts, setHasMoreContacts] = useState<Record<string, boolean>>({});
// contactsLoading 表示联系人分页状态。
const [contactsLoading, setContactsLoading] = useState(false);
// emojiOpen 控制表情选择器显示。
const [emojiOpen, setEmojiOpen] = useState(false);
// sending 表示当前是否正在发送消息。
const [sending, setSending] = useState(false);
// error 保存聊天页面最近错误。
const [error, setError] = useState('');
// liveState 保存 WebSocket 连接状态。
const [liveState, setLiveState] = useState<ChatLiveState>('connecting');
// retryText 保存最近失败的文本消息。
const [retryText, setRetryText] = useState<string | null>(null);
// retryImage 保存最近失败的图片消息。
const [retryImage, setRetryImage] = useState<File | null>(null);
// activeAccountRef 供实时回调读取最新账号。
const activeAccountRef = useRef('');
// activeChatRef 供实时回调读取最新会话。
const activeChatRef = useRef('');
// scrollRef 指向消息滚动容器。
const scrollRef = useRef<HTMLDivElement | null>(null);
// scrollContextRef 保存滚动上下文。
const scrollContextRef = useRef({ accountID: '', chatID: '' });
// shouldScrollToBottomRef 控制新消息是否自动滚到底部。
const shouldScrollToBottomRef = useRef(true);
// skipNextMessageScrollRef 防止加载历史消息后跳到底部。
const skipNextMessageScrollRef = useRef(false);
// imageInputRef 指向图片文件输入框。
const imageInputRef = useRef<HTMLInputElement | null>(null);
// refreshedAccountsRef 防止同一账号重复刷新联系人。
const refreshedAccountsRef = useRef(new Set<string>());
// sessionSequence 隔离联系人刷新请求。
const sessionSequence = useRef(0);
// sessionController 保存当前联系人请求控制器。
const sessionController = useRef<AbortController | null>(null);
// messageSequence 隔离会话切换产生的旧消息响应。
const messageSequence = useRef(0);
// messageController 保存当前消息请求控制器。
const messageController = useRef<AbortController | null>(null);
// contactSequence 隔离联系人分页产生的旧响应。
const contactSequence = useRef(0);
// contactController 保存当前联系人分页控制器。
const contactController = useRef<AbortController | null>(null);
// sendSequence 隔离账号或会话切换产生的旧发送响应。
const sendSequence = useRef(0);
// sendController 保存当前消息发送控制器。
const sendController = useRef<AbortController | null>(null);
useEffect(() => { activeAccountRef.current = activeAccountID; }, [activeAccountID]);
useEffect(() => { activeChatRef.current = activeChatID; }, [activeChatID]);
/** 刷新指定账号的联系人列表,并丢弃过期响应。 */
const reloadSessions = useCallback(async (accountID: string): Promise<ChatSession[]> => {
const sequence = ++sessionSequence.current;
sessionController.current?.abort();
const controller = new AbortController();
sessionController.current = controller;
try {
const page = await getChatSessionPage(accountID, undefined, { signal: controller.signal }, true);
if (!isCurrentChatRequest(sessionSequence.current, sequence, controller.signal)) return [];
setSessionsByAccount(current => ({ ...current, [accountID]: page.sessions }));
setContactCursors(current => ({ ...current, [accountID]: page.next_cursor }));
setHasMoreContacts(current => ({ ...current, [accountID]: page.has_more }));
return page.sessions;
} catch (error) {
if (isCurrentChatRequest(sessionSequence.current, sequence, controller.signal) && !isChatAbortError(error)) setError(error instanceof Error ? error.message : '同步会话失败');
return [];
}
}, []);
useEffect(() => {
const controller = new AbortController();
const load = async (): Promise<void> => {
setLoading(true);
try {
const [details, statuses] = await Promise.all([
getAccountDetails({ signal: controller.signal }),
getAccountRuntimeStatuses({ signal: controller.signal }),
]);
const withRuntime = details.map(account => ({
...account,
runtime_state: statuses[account.id]?.state || (account.enabled ? 'connecting' : 'disabled'),
runtime_connected: statuses[account.id]?.connected === true,
}));
const enabled = withRuntime.filter(account => account.enabled);
const sessionPages = await Promise.all(enabled.map(async account => [account.id, await getChatSessionPage(account.id, undefined, { signal: controller.signal })] as const));
if (controller.signal.aborted) return;
setAccounts(enabled);
setSessionsByAccount(Object.fromEntries(sessionPages.map(([id, page]) => [id, page.sessions])));
setContactCursors(Object.fromEntries(sessionPages.map(([id, page]) => [id, page.next_cursor])));
setHasMoreContacts(Object.fromEntries(sessionPages.map(([id, page]) => [id, page.has_more])));
const stored = window.localStorage.getItem('ydisks.chat.account.v1') || '';
const first = enabled.some(account => account.id === stored) ? stored : enabled[0]?.id || '';
setActiveAccountID(first);
} catch (loadError) {
if (!controller.signal.aborted) setError(loadError instanceof Error ? loadError.message : '加载聊天数据失败');
} finally {
if (!controller.signal.aborted) setLoading(false);
}
};
void load();
return () => controller.abort();
}, []);
useEffect(() => {
let disposed = false;
let timer = 0;
let controller: AbortController | null = null;
const poll = async (): Promise<void> => {
controller = new AbortController();
try {
const statuses = await getAccountRuntimeStatuses({ signal: controller.signal, timeoutMs: 10_000 });
if (!disposed) setAccounts(current => current.map(account => ({
...account,
runtime_state: statuses[account.id]?.state || account.runtime_state,
runtime_connected: statuses[account.id]?.connected ?? account.runtime_connected,
})));
} catch {
// WebSocket 拥有独立的可见状态,短暂轮询失败不清除已加载会话。
} finally {
if (!disposed) timer = window.setTimeout(poll, 3_000);
}
};
timer = window.setTimeout(poll, 3_000);
return () => {
disposed = true;
window.clearTimeout(timer);
controller?.abort();
};
}, []);
useEffect(() => {
if (!activeAccountID) return;
window.localStorage.setItem('ydisks.chat.account.v1', activeAccountID);
const sessions = sessionsByAccount[activeAccountID] || [];
setActiveChatID(current => sessions.some(session => session.chat_id === current) ? current : sessions[0]?.chat_id || '');
}, [activeAccountID, sessionsByAccount]);
useEffect(() => {
if (!activeAccountID || refreshedAccountsRef.current.has(activeAccountID)) return;
refreshedAccountsRef.current.add(activeAccountID);
void reloadSessions(activeAccountID);
}, [activeAccountID, reloadSessions]);
useEffect(() => {
if (!activeAccountID || !activeChatID) {
setMessages([]);
return;
}
const sequence = ++messageSequence.current;
messageController.current?.abort();
const controller = new AbortController();
messageController.current = controller;
setMessagesLoading(true);
void Promise.all([
getChatMessagePage(activeAccountID, activeChatID, undefined, undefined, { signal: controller.signal }),
markChatRead(activeAccountID, activeChatID, { signal: controller.signal }),
]).then(([page]) => {
if (!isCurrentChatRequest(messageSequence.current, sequence, controller.signal)) return;
setMessages(page.messages);
setHasOlder(page.has_more);
setHistoryCursor(page.next_cursor);
if (page.session) setSessionsByAccount(current => ({ ...current, [activeAccountID]: (current[activeAccountID] || []).map(session => session.chat_id === page.session?.chat_id ? page.session! : session) }));
setSessionsByAccount(current => ({ ...current, [activeAccountID]: (current[activeAccountID] || []).map(session => session.chat_id === activeChatID ? { ...session, unread_count: 0 } : session) }));
}).catch(loadError => {
if (isCurrentChatRequest(messageSequence.current, sequence, controller.signal) && !isChatAbortError(loadError)) setError(loadError instanceof Error ? loadError.message : '加载消息失败');
}).finally(() => {
if (isCurrentChatRequest(messageSequence.current, sequence, controller.signal)) setMessagesLoading(false);
});
return () => controller.abort();
}, [activeAccountID, activeChatID]);
useEffect(() => {
contactController.current?.abort();
contactSequence.current += 1;
}, [activeAccountID]);
useEffect(() => {
sendController.current?.abort();
sendSequence.current += 1;
}, [activeAccountID, activeChatID]);
useEffect(() => () => {
sessionController.current?.abort();
messageController.current?.abort();
contactController.current?.abort();
sendController.current?.abort();
}, []);
/** 加载当前会话更早消息并保持滚动位置。 */
const loadOlderMessages = useCallback(async (): Promise<void> => {
if (!activeAccountID || !activeChatID || olderLoading || !hasOlder) return;
const container = scrollRef.current;
const previousHeight = container?.scrollHeight || 0;
const sequence = messageSequence.current;
const controller = new AbortController();
skipNextMessageScrollRef.current = true;
setOlderLoading(true);
setError('');
try {
const oldestID = messages[0]?.id;
const page = await getChatMessagePage(activeAccountID, activeChatID, historyCursor, oldestID, { signal: controller.signal });
if (!isCurrentChatRequest(messageSequence.current, sequence, controller.signal)) return;
setMessages(current => mergeOlderMessages(current, page.messages));
setHasOlder(page.has_more);
setHistoryCursor(page.next_cursor);
requestAnimationFrame(() => {
if (container) container.scrollTop += container.scrollHeight - previousHeight;
});
} catch (loadError) {
skipNextMessageScrollRef.current = false;
if (!isChatAbortError(loadError)) setError(loadError instanceof Error ? loadError.message : '加载历史消息失败');
} finally {
setOlderLoading(false);
}
}, [activeAccountID, activeChatID, hasOlder, historyCursor, messages, olderLoading]);
useEffect(() => {
let disposed = false;
let reconnectTimer = 0;
let retry = 0;
let socket: WebSocket | null = null;
const connect = (): void => {
if (disposed) return;
setLiveState('connecting');
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 {
const payload = JSON.parse(event.data);
const message = payload.message as ChatMessage | undefined;
if (!message) return;
const accountID = message.account_id;
setSessionsByAccount(current => {
const rows = current[accountID] || [];
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' && (activeAccountRef.current !== accountID || activeChatRef.current !== message.chat_id) ? row.unread_count + 1 : row.unread_count,
} : row).sort((a, b) => b.last_message_at - a.last_message_at) };
});
if (activeAccountRef.current === accountID && activeChatRef.current === message.chat_id) {
setMessages(current => mergeLiveMessage(current, message));
if (message.direction === 'incoming') void markChatRead(accountID, message.chat_id);
}
} catch {
// 忽略非聊天格式的 WebSocket 帧,后续 REST 查询会恢复权威状态。
}
};
socket.onclose = () => {
if (disposed) return;
setLiveState('offline');
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();
};
}, [reloadSessions]);
/** 根据滚动位置决定新消息是否自动滚到底部。 */
const handleMessageScroll = useCallback(() => {
const container = scrollRef.current;
if (!container) return;
const distanceFromBottom = container.scrollHeight - container.scrollTop - container.clientHeight;
shouldScrollToBottomRef.current = distanceFromBottom <= 48;
}, []);
useLayoutEffect(() => {
const contextChanged = scrollContextRef.current.accountID !== activeAccountID || scrollContextRef.current.chatID !== activeChatID;
scrollContextRef.current = { accountID: activeAccountID, chatID: activeChatID };
if (contextChanged) shouldScrollToBottomRef.current = true;
const container = scrollRef.current;
if (!container) return;
if (skipNextMessageScrollRef.current) {
skipNextMessageScrollRef.current = false;
return;
}
if (messagesLoading || shouldScrollToBottomRef.current) container.scrollTop = container.scrollHeight;
}, [activeAccountID, activeChatID, messages, messagesLoading]);
const activeAccount = accounts.find(account => account.id === activeAccountID);
const activeSessions = sessionsByAccount[activeAccountID] || [];
const selectedSession = activeSessions.find(session => session.chat_id === activeChatID);
const filteredSessions = useMemo(() => filterChatSessions(activeSessions, search, unreadOnly), [activeSessions, search, unreadOnly]);
const unreadForAccount = useCallback((accountID: string) => (sessionsByAccount[accountID] || []).reduce((sum, session) => sum + session.unread_count, 0), [sessionsByAccount]);
/** 加载当前账号下一页联系人。 */
const loadMoreContacts = useCallback(async (): Promise<void> => {
if (!activeAccountID || contactsLoading || !hasMoreContacts[activeAccountID]) return;
const sequence = ++contactSequence.current;
contactController.current?.abort();
const controller = new AbortController();
contactController.current = controller;
const accountID = activeAccountID;
setContactsLoading(true);
setError('');
try {
const page = await getChatSessionPage(accountID, contactCursors[accountID], { signal: controller.signal }, true);
if (!isCurrentChatRequest(contactSequence.current, sequence, controller.signal)) return;
setSessionsByAccount(current => ({ ...current, [accountID]: page.sessions }));
setContactCursors(current => ({ ...current, [accountID]: page.next_cursor }));
setHasMoreContacts(current => ({ ...current, [accountID]: page.has_more }));
} catch (loadError) {
if (isCurrentChatRequest(contactSequence.current, sequence, controller.signal) && !isChatAbortError(loadError)) setError(loadError instanceof Error ? loadError.message : '加载历史联系人失败');
} finally {
if (isCurrentChatRequest(contactSequence.current, sequence, controller.signal)) setContactsLoading(false);
}
}, [activeAccountID, contactCursors, contactsLoading, hasMoreContacts]);
/** 发送文本消息并记录失败重试数据。 */
const sendText = useCallback(async (text: string, rememberRetry: boolean): Promise<void> => {
if (!selectedSession || !activeAccountID || sending) return;
const sequence = ++sendSequence.current;
sendController.current?.abort();
const controller = new AbortController();
sendController.current = controller;
setSending(true);
setError('');
try {
const result = await sendChatMessage({ account_id: activeAccountID, chat_id: selectedSession.chat_id, buyer_id: selectedSession.buyer_id, buyer_name: selectedSession.buyer_name, item_id: selectedSession.item_id, item_title: selectedSession.item_title, text }, { signal: controller.signal });
if (!isCurrentChatRequest(sendSequence.current, sequence, controller.signal)) return;
setDraft('');
setRetryText(null);
setMessages(current => mergeLiveMessage(current, result.message));
} catch (sendError) {
if (isCurrentChatRequest(sendSequence.current, sequence, controller.signal)) {
if (rememberRetry) setRetryText(text);
if (!isChatAbortError(sendError)) setError(sendError instanceof Error ? sendError.message : '消息发送失败');
}
} finally {
if (isCurrentChatRequest(sendSequence.current, sequence, controller.signal)) setSending(false);
}
}, [activeAccountID, selectedSession, sending]);
/** 发送图片消息并记录失败重试数据。 */
const sendImage = useCallback(async (file: File, rememberRetry: boolean): Promise<void> => {
if (!selectedSession || !activeAccountID || sending) return;
const sequence = ++sendSequence.current;
sendController.current?.abort();
const controller = new AbortController();
sendController.current = controller;
setSending(true);
setError('');
try {
const result = await sendChatImage({ account_id: activeAccountID, chat_id: selectedSession.chat_id, buyer_id: selectedSession.buyer_id, buyer_name: selectedSession.buyer_name, buyer_avatar_url: selectedSession.buyer_avatar_url, item_id: selectedSession.item_id, item_title: selectedSession.item_title, image: file }, { signal: controller.signal });
if (!isCurrentChatRequest(sendSequence.current, sequence, controller.signal)) return;
setRetryImage(null);
setMessages(current => mergeLiveMessage(current, result.message));
} catch (sendError) {
if (isCurrentChatRequest(sendSequence.current, sequence, controller.signal)) {
if (rememberRetry) setRetryImage(file);
if (!isChatAbortError(sendError)) setError(sendError instanceof Error ? sendError.message : '图片发送失败');
}
} finally {
if (isCurrentChatRequest(sendSequence.current, sequence, controller.signal)) {
setSending(false);
if (imageInputRef.current) imageInputRef.current.value = '';
}
}
}, [activeAccountID, selectedSession, sending]);
/** 处理文本发送按钮和 Enter 快捷键。 */
const handleSend = useCallback(async (): Promise<void> => {
const text = draft.trim();
if (!text || !selectedSession || !activeAccountID || sending) return;
await sendText(text, true);
}, [activeAccountID, draft, selectedSession, sendText, sending]);
/** 处理图片选择并发送。 */
const handleImage = useCallback(async (file?: File): Promise<void> => {
if (!file || !selectedSession || !activeAccountID || sending) return;
await sendImage(file, true);
}, [activeAccountID, selectedSession, sendImage, sending]);
/** 重试最近一次失败的文本或图片发送。 */
const retrySend = useCallback(async (): Promise<void> => {
if (retryText) await sendText(retryText, false);
else if (retryImage) await sendImage(retryImage, false);
}, [retryImage, retryText, sendImage, sendText]);
return {
accounts, activeAccountID, activeSessions, selectedSession, activeAccount, messages, search, unreadOnly, draft, loading, messagesLoading, olderLoading, hasOlder, contactsLoading, hasMoreContacts: hasMoreContacts[activeAccountID] === true, emojiOpen, sending, error, liveState,
activeChatID, filteredSessions, scrollRef, imageInputRef, setActiveAccountID, setActiveChatID, setSearch, setUnreadOnly, setDraft, setEmojiOpen,
reloadSessions, loadMoreContacts, loadOlderMessages, handleMessageScroll, handleSend, handleImage, retrySend, retryAvailable: Boolean(retryText || retryImage), unreadForAccount,
emojiURL, xianyuEmojis, renderXianyuText, formatClock, messageTime,
};
};
+30
View File
@@ -0,0 +1,30 @@
import { expect, test } from 'vitest';
import type { ChatMessage, ChatSession } from '../../../types';
import { filterChatSessions, isCurrentChatRequest, mergeLiveMessage, mergeOlderMessages } from './state';
// sessionFixture 是覆盖搜索、未读筛选和联系人隔离的最小会话数据。
const sessionFixture: ChatSession[] = [
{ account_id: 'a1', chat_id: 'c1', buyer_id: 'b1', buyer_name: '张三', item_title: '测试商品', last_message: '你好', last_message_at: 1, unread_count: 2 },
{ account_id: 'a1', chat_id: 'c2', buyer_id: 'b2', buyer_name: '李四', item_title: '另一个商品', last_message: '已发货', last_message_at: 2, unread_count: 0 },
];
// messageFixture 是覆盖消息去重和实时替换的最小消息数据。
const messageFixture: ChatMessage = { id: 1, account_id: 'a1', chat_id: 'c1', message_key: 'm1', direction: 'incoming', sender_id: 'b1', sender_name: '张三', message_type: 'text', content: '旧消息', status: 'received', sent_at: 1 };
test('Chat 会话筛选和历史消息合并保持账号内顺序',
// 会话状态测试验证搜索、未读筛选和历史消息去重语义。
() => {
expect(filterChatSessions(sessionFixture, '张三', false)).toHaveLength(1);
expect(filterChatSessions(sessionFixture, '', true)).toEqual([sessionFixture[0]]);
expect(mergeOlderMessages([messageFixture], [{ ...messageFixture, id: 0, message_key: 'm0', content: '更早' }])).toHaveLength(2);
});
test('Chat 实时消息替换同键记录并拒绝过期请求',
// 请求边界测试验证实时回执不会产生重复消息,切换会话后的旧请求不能写入。
() => {
const controller = new AbortController();
expect(mergeLiveMessage([messageFixture], { ...messageFixture, content: '新消息' })[0].content).toBe('新消息');
expect(isCurrentChatRequest(3, 3, controller.signal)).toBe(true);
expect(isCurrentChatRequest(2, 3, controller.signal)).toBe(false);
controller.abort();
expect(isCurrentChatRequest(3, 3, controller.signal)).toBe(false);
});
+50
View File
@@ -0,0 +1,50 @@
import type { ChatMessage, ChatSession } from '../../../types';
/** 按搜索条件筛选会话列表。 */
export const filterChatSessions = (sessions: ChatSession[], search: string, unreadOnly: boolean): ChatSession[] => {
const keyword = search.trim().toLowerCase();
return sessions.filter(session => {
if (unreadOnly && session.unread_count <= 0) return false;
if (!keyword) return true;
return [session.buyer_name, session.buyer_id, session.item_title, session.last_message]
.some(value => (value || '').toLowerCase().includes(keyword));
});
};
/** 合并历史消息并按消息键去重。 */
export const mergeOlderMessages = (current: ChatMessage[], older: ChatMessage[]): ChatMessage[] => {
const keys = new Set(current.map(message => message.message_key));
return [...older.filter(message => !keys.has(message.message_key)), ...current];
};
/** 合并实时消息并替换同消息键的临时记录。 */
export const mergeLiveMessage = (current: ChatMessage[], incoming: ChatMessage): ChatMessage[] => {
const index = current.findIndex(message => message.message_key === incoming.message_key);
if (index < 0) return [...current, incoming];
return current.map((message, currentIndex) => currentIndex === index ? incoming : message);
};
/** 判断 Chat 请求响应是否仍属于当前账号和会话。 */
export const isCurrentChatRequest = (currentSequence: number, requestSequence: number, signal: AbortSignal): boolean => (
currentSequence === requestSequence && !signal.aborted
);
/** 判断错误是否来自请求主动取消。 */
export const isChatAbortError = (error: unknown): boolean => error instanceof Error && error.message === '请求已取消';
/** 将聊天时间戳格式化为列表时间。 */
export const formatClock = (value: number): string => {
if (!value) return '';
const date = new Date(value < 10_000_000_000 ? value * 1000 : value);
const today = new Date();
if (date.toDateString() === today.toDateString()) {
return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false });
}
return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' });
};
/** 将聊天时间戳格式化为消息详情时间。 */
export const messageTime = (value: number): string => {
const date = new Date(value < 10_000_000_000 ? value * 1000 : value);
return date.toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false });
};
+49
View File
@@ -0,0 +1,49 @@
import type { AccountDetail, ChatMessage, ChatSession } from '../../../types';
/** 按账号保存会话列表。 */
export type SessionsByAccount = Record<string, ChatSession[]>;
/** Chat 实时连接状态。 */
export type ChatLiveState = 'connecting' | 'online' | 'offline';
/** Chat Hook 的状态与交互能力。 */
export type ChatFeatureState = {
/** 当前启用账号列表。 */
accounts: AccountDetail[];
/** 当前选中的账号 ID。 */
activeAccountID: string;
/** 当前账号的会话列表。 */
activeSessions: ChatSession[];
/** 当前选中的会话。 */
selectedSession?: ChatSession;
/** 当前选中的账号。 */
activeAccount?: AccountDetail;
/** 当前会话消息。 */
messages: ChatMessage[];
/** 会话搜索文本。 */
search: string;
/** 是否只显示未读会话。 */
unreadOnly: boolean;
/** 消息输入草稿。 */
draft: string;
/** 初始数据加载状态。 */
loading: boolean;
/** 当前会话消息加载状态。 */
messagesLoading: boolean;
/** 历史消息加载状态。 */
olderLoading: boolean;
/** 是否还有更早消息。 */
hasOlder: boolean;
/** 历史联系人加载状态。 */
contactsLoading: boolean;
/** 当前账号是否还有更多联系人。 */
hasMoreContacts: boolean;
/** 表情选择器展开状态。 */
emojiOpen: boolean;
/** 消息发送状态。 */
sending: boolean;
/** 当前错误信息。 */
error: string;
/** WebSocket 实时连接状态。 */
liveState: ChatLiveState;
};
+10 -8
View File
@@ -23,18 +23,19 @@ describe('online chat UI contract', () => {
});
test('frontend connects only to the application chat websocket', () => {
const chat = source('components/Chat.tsx');
expect(chat).toContain('/api/v1/chat/ws');
expect(chat).not.toContain('wss-goofish.dingtalk.com');
const chatHook = source('app/features/chat/hooks.ts');
expect(chatHook).toContain('/api/v1/chat/ws');
expect(chatHook).not.toContain('wss-goofish.dingtalk.com');
});
test('renders peer/self identity and verified media capabilities', () => {
const chat = source('components/Chat.tsx');
const chatHook = source('app/features/chat/hooks.ts');
expect(chat).toContain('selectedSession.buyer_avatar_url');
expect(chat).toContain('activeAccount?.avatar_url');
expect(chat).toContain("message.message_type === 'image'");
expect(chat).toContain("message.message_type === 'video'");
expect(chat).toContain('sendChatImage');
expect(chatHook).toContain('sendChatImage');
});
test('renders official notices as neutral system messages', () => {
@@ -45,11 +46,12 @@ describe('online chat UI contract', () => {
test('keeps the active chat at the bottom when new messages arrive', () => {
const chat = source('components/Chat.tsx');
expect(chat).toContain('shouldScrollToBottomRef');
expect(chat).toContain('skipNextMessageScrollRef');
const chatHook = source('app/features/chat/hooks.ts');
expect(chatHook).toContain('shouldScrollToBottomRef');
expect(chatHook).toContain('skipNextMessageScrollRef');
expect(chat).toContain('onScroll={handleMessageScroll}');
expect(chat).toContain('container.scrollHeight - container.scrollTop - container.clientHeight');
expect(chat).toContain('[activeAccountID, activeChatID, messages, messagesLoading]');
expect(chatHook).toContain('container.scrollHeight - container.scrollTop - container.clientHeight');
expect(chatHook).toContain('[activeAccountID, activeChatID, messages, messagesLoading]');
});
test('sidebar exposes collapse control and chat primary navigation', () => {
+18 -366
View File
@@ -1,367 +1,21 @@
import React, { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import React from 'react';
import {
AlertCircle, Check, CheckCheck, ImagePlus, Loader2, MessageCircleMore, RefreshCw,
Search, Send, Smile, UserRound, Wifi, WifiOff,
} from 'lucide-react';
import { AccountDetail, ChatMessage, ChatSession } from '../types';
import {
getAccountDetails, getAccountRuntimeStatuses, getChatMessagePage, getChatMessages, getChatSessionPage, getChatSessions,
markChatRead, sendChatImage, sendChatMessage,
} from '../services/api';
import { emojiURL, renderXianyuText, xianyuEmojis } from '../chatEmojis';
type SessionsByAccount = Record<string, ChatSession[]>;
const accountStorageKey = 'ydisks.chat.account.v1';
const formatClock = (value: number): string => {
if (!value) return '';
const date = new Date(value < 10_000_000_000 ? value * 1000 : value);
const today = new Date();
if (date.toDateString() === today.toDateString()) {
return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false });
}
return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' });
};
const messageTime = (value: number): string => {
const date = new Date(value < 10_000_000_000 ? value * 1000 : value);
return date.toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false });
};
import { useChat } from '../app/features/chat/hooks';
// Chat 展示实时会话、消息分页和消息发送界面。
const Chat: React.FC = () => {
const [accounts, setAccounts] = useState<AccountDetail[]>([]);
const [activeAccountID, setActiveAccountID] = useState('');
const [sessionsByAccount, setSessionsByAccount] = useState<SessionsByAccount>({});
const [activeChatID, setActiveChatID] = useState('');
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [search, setSearch] = useState('');
const [unreadOnly, setUnreadOnly] = useState(false);
const [draft, setDraft] = useState('');
const [loading, setLoading] = useState(true);
const [messagesLoading, setMessagesLoading] = useState(false);
const [olderLoading, setOlderLoading] = useState(false);
const [hasOlder, setHasOlder] = useState(false);
const [historyCursor, setHistoryCursor] = useState<number | undefined>();
const [contactCursors, setContactCursors] = useState<Record<string, number | undefined>>({});
const [hasMoreContacts, setHasMoreContacts] = useState<Record<string, boolean>>({});
const [contactsLoading, setContactsLoading] = useState(false);
const [emojiOpen, setEmojiOpen] = useState(false);
const [sending, setSending] = useState(false);
const [error, setError] = useState('');
const [liveState, setLiveState] = useState<'connecting' | 'online' | 'offline'>('connecting');
const activeAccountRef = useRef('');
const activeChatRef = useRef('');
const scrollRef = useRef<HTMLDivElement | null>(null);
const scrollContextRef = useRef({ accountID: '', chatID: '' });
const shouldScrollToBottomRef = useRef(true);
const skipNextMessageScrollRef = useRef(false);
const imageInputRef = useRef<HTMLInputElement | null>(null);
const refreshedAccountsRef = useRef(new Set<string>());
useEffect(() => { activeAccountRef.current = activeAccountID; }, [activeAccountID]);
useEffect(() => { activeChatRef.current = activeChatID; }, [activeChatID]);
const reloadSessions = async (accountID: string) => {
const page = await getChatSessionPage(accountID, undefined, undefined, true);
setSessionsByAccount(current => ({ ...current, [accountID]: page.sessions }));
setContactCursors(current => ({ ...current, [accountID]: page.next_cursor }));
setHasMoreContacts(current => ({ ...current, [accountID]: page.has_more }));
return page.sessions;
};
useEffect(() => {
let cancelled = false;
const load = async () => {
setLoading(true);
try {
const [details, statuses] = await Promise.all([getAccountDetails(), getAccountRuntimeStatuses()]);
const withRuntime = details.map(account => ({
...account,
runtime_state: statuses[account.id]?.state || (account.enabled ? 'connecting' : 'disabled'),
runtime_connected: statuses[account.id]?.connected === true,
}));
const enabled = withRuntime.filter(account => account.enabled);
const sessionPages = await Promise.all(enabled.map(async account => [account.id, await getChatSessionPage(account.id)] as const));
if (cancelled) return;
setAccounts(enabled);
setSessionsByAccount(Object.fromEntries(sessionPages.map(([id, page]) => [id, page.sessions])));
setContactCursors(Object.fromEntries(sessionPages.map(([id, page]) => [id, page.next_cursor])));
setHasMoreContacts(Object.fromEntries(sessionPages.map(([id, page]) => [id, page.has_more])));
const stored = window.localStorage.getItem(accountStorageKey) || '';
const first = enabled.some(account => account.id === stored) ? stored : enabled[0]?.id || '';
setActiveAccountID(first);
} catch (loadError) {
if (!cancelled) setError(loadError instanceof Error ? loadError.message : '加载聊天数据失败');
} finally {
if (!cancelled) setLoading(false);
}
};
void load();
return () => { cancelled = true; };
}, []);
useEffect(() => {
let disposed = false;
let timer = 0;
let controller: AbortController | null = null;
const poll = async () => {
controller = new AbortController();
try {
const statuses = await getAccountRuntimeStatuses({ signal: controller.signal, timeoutMs: 10_000 });
if (!disposed) {
setAccounts(current => current.map(account => ({
...account,
runtime_state: statuses[account.id]?.state || account.runtime_state,
runtime_connected: statuses[account.id]?.connected ?? account.runtime_connected,
})));
}
} catch {
// The app WebSocket has its own visible state; a transient status poll
// failure does not invalidate the loaded conversations.
} finally {
if (!disposed) timer = window.setTimeout(poll, 3_000);
}
};
timer = window.setTimeout(poll, 3_000);
return () => {
disposed = true;
window.clearTimeout(timer);
controller?.abort();
};
}, []);
useEffect(() => {
if (!activeAccountID) return;
window.localStorage.setItem(accountStorageKey, activeAccountID);
const sessions = sessionsByAccount[activeAccountID] || [];
setActiveChatID(current => sessions.some(session => session.chat_id === current) ? current : sessions[0]?.chat_id || '');
}, [activeAccountID, sessionsByAccount]);
useEffect(() => {
if (!activeAccountID || refreshedAccountsRef.current.has(activeAccountID)) return;
refreshedAccountsRef.current.add(activeAccountID);
void reloadSessions(activeAccountID).catch(loadError => {
setError(loadError instanceof Error ? loadError.message : '同步会话失败');
});
}, [activeAccountID]);
useEffect(() => {
if (!activeAccountID || !activeChatID) {
setMessages([]);
return;
}
const controller = new AbortController();
setMessagesLoading(true);
void Promise.all([
getChatMessagePage(activeAccountID, activeChatID, undefined, undefined, { signal: controller.signal }),
markChatRead(activeAccountID, activeChatID),
]).then(([page]) => {
setMessages(page.messages);
setHasOlder(page.has_more);
setHistoryCursor(page.next_cursor);
if (page.session) {
setSessionsByAccount(current => ({ ...current, [activeAccountID]: (current[activeAccountID] || []).map(session => session.chat_id === page.session?.chat_id ? page.session! : session) }));
}
setSessionsByAccount(current => ({
...current,
[activeAccountID]: (current[activeAccountID] || []).map(session =>
session.chat_id === activeChatID ? { ...session, unread_count: 0 } : session),
}));
}).catch(loadError => {
if (!controller.signal.aborted) setError(loadError instanceof Error ? loadError.message : '加载消息失败');
}).finally(() => {
if (!controller.signal.aborted) setMessagesLoading(false);
});
return () => controller.abort();
}, [activeAccountID, activeChatID]);
const loadOlderMessages = async () => {
if (!activeAccountID || !activeChatID || olderLoading || !hasOlder) return;
const container = scrollRef.current;
const previousHeight = container?.scrollHeight || 0;
skipNextMessageScrollRef.current = true;
setOlderLoading(true);
setError('');
try {
const oldestID = messages[0]?.id;
const page = await getChatMessagePage(activeAccountID, activeChatID, historyCursor, oldestID);
setMessages(current => {
const keys = new Set(current.map(message => message.message_key));
return [...page.messages.filter(message => !keys.has(message.message_key)), ...current];
});
setHasOlder(page.has_more);
setHistoryCursor(page.next_cursor);
requestAnimationFrame(() => {
if (container) container.scrollTop += container.scrollHeight - previousHeight;
});
} catch (loadError) {
skipNextMessageScrollRef.current = false;
setError(loadError instanceof Error ? loadError.message : '加载历史消息失败');
} finally {
setOlderLoading(false);
}
};
useEffect(() => {
let disposed = false;
let reconnectTimer = 0;
let retry = 0;
let socket: WebSocket | null = null;
const connect = () => {
if (disposed) return;
setLiveState('connecting');
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 {
const payload = JSON.parse(event.data);
const message = payload.message as ChatMessage | undefined;
if (!message) return;
const accountID = message.account_id;
setSessionsByAccount(current => {
const rows = current[accountID] || [];
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' && (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 => {
const index = current.findIndex(item => item.message_key === message.message_key);
if (index >= 0) return current.map((item, i) => i === index ? message : item);
return [...current, message];
});
if (message.direction === 'incoming') void markChatRead(accountID, message.chat_id);
}
} catch {
// Ignore malformed non-chat frames and recover from authoritative REST state.
}
};
socket.onclose = () => {
if (disposed) return;
setLiveState('offline');
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();
};
}, []);
const handleMessageScroll = () => {
const container = scrollRef.current;
if (!container) return;
const distanceFromBottom = container.scrollHeight - container.scrollTop - container.clientHeight;
shouldScrollToBottomRef.current = distanceFromBottom <= 48;
};
useLayoutEffect(() => {
const contextChanged = scrollContextRef.current.accountID !== activeAccountID
|| scrollContextRef.current.chatID !== activeChatID;
scrollContextRef.current = { accountID: activeAccountID, chatID: activeChatID };
if (contextChanged) shouldScrollToBottomRef.current = true;
const container = scrollRef.current;
if (!container) return;
if (skipNextMessageScrollRef.current) {
skipNextMessageScrollRef.current = false;
return;
}
if (messagesLoading || shouldScrollToBottomRef.current) container.scrollTop = container.scrollHeight;
}, [activeAccountID, activeChatID, messages, messagesLoading]);
const activeAccount = accounts.find(account => account.id === activeAccountID);
const activeSessions = sessionsByAccount[activeAccountID] || [];
const selectedSession = activeSessions.find(session => session.chat_id === activeChatID);
const filteredSessions = useMemo(() => {
const keyword = search.trim().toLowerCase();
return activeSessions.filter(session => {
if (unreadOnly && session.unread_count <= 0) return false;
if (!keyword) return true;
return [session.buyer_name, session.buyer_id, session.item_title, session.last_message]
.some(value => (value || '').toLowerCase().includes(keyword));
});
}, [activeSessions, search, unreadOnly]);
const unreadForAccount = (accountID: string) =>
(sessionsByAccount[accountID] || []).reduce((sum, session) => sum + session.unread_count, 0);
const loadMoreContacts = async () => {
if (!activeAccountID || contactsLoading || !hasMoreContacts[activeAccountID]) return;
setContactsLoading(true);
setError('');
try {
const page = await getChatSessionPage(activeAccountID, contactCursors[activeAccountID], undefined, true);
setSessionsByAccount(current => ({ ...current, [activeAccountID]: page.sessions }));
setContactCursors(current => ({ ...current, [activeAccountID]: page.next_cursor }));
setHasMoreContacts(current => ({ ...current, [activeAccountID]: page.has_more }));
} catch (loadError) {
setError(loadError instanceof Error ? loadError.message : '加载历史联系人失败');
} finally { setContactsLoading(false); }
};
const handleSend = async () => {
const text = draft.trim();
if (!text || !selectedSession || !activeAccountID || sending) return;
setSending(true);
setError('');
try {
const result = await sendChatMessage({
account_id: activeAccountID, chat_id: selectedSession.chat_id, buyer_id: selectedSession.buyer_id,
buyer_name: selectedSession.buyer_name, item_id: selectedSession.item_id,
item_title: selectedSession.item_title, text,
});
setDraft('');
setMessages(current => current.some(item => item.message_key === result.message.message_key)
? current.map(item => item.message_key === result.message.message_key ? result.message : item)
: [...current, result.message]);
} catch (sendError) {
setError(sendError instanceof Error ? sendError.message : '消息发送失败');
void getChatMessages(activeAccountID, selectedSession.chat_id).then(setMessages);
} finally {
setSending(false);
}
};
const handleImage = async (file?: File) => {
if (!file || !selectedSession || !activeAccountID || sending) return;
setSending(true);
setError('');
try {
const result = await sendChatImage({
account_id: activeAccountID, chat_id: selectedSession.chat_id, buyer_id: selectedSession.buyer_id,
buyer_name: selectedSession.buyer_name, buyer_avatar_url: selectedSession.buyer_avatar_url,
item_id: selectedSession.item_id, item_title: selectedSession.item_title, image: file,
});
setMessages(current => current.some(item => item.message_key === result.message.message_key)
? current.map(item => item.message_key === result.message.message_key ? result.message : item)
: [...current, result.message]);
} catch (sendError) {
setError(sendError instanceof Error ? sendError.message : '图片发送失败');
} finally {
setSending(false);
if (imageInputRef.current) imageInputRef.current.value = '';
}
};
// chatState 是 Chat feature Hook 提供的状态、引用和交互动作。
const {
accounts, activeAccountID, activeChatID, activeAccount, selectedSession, filteredSessions,
messages, search, unreadOnly, draft, loading, messagesLoading, olderLoading, hasOlder, contactsLoading,
hasMoreContacts, emojiOpen, sending, error, liveState, scrollRef, imageInputRef, setActiveAccountID,
setActiveChatID, setSearch, setUnreadOnly, setDraft, setEmojiOpen, reloadSessions, loadMoreContacts,
loadOlderMessages, handleMessageScroll, handleSend, handleImage, retrySend, retryAvailable,
unreadForAccount, emojiURL, xianyuEmojis, renderXianyuText, formatClock, messageTime,
} = useChat();
if (loading) return <div className="flex h-[calc(100vh-4rem)] items-center justify-center"><Loader2 className="h-8 w-8 animate-spin text-sky-500" /></div>;
@@ -441,7 +95,7 @@ const Chat: React.FC = () => {
</button>
))}
{filteredSessions.length === 0 && <div className="px-6 py-16 text-center text-sm text-slate-400">当前账号暂无匹配会话</div>}
{hasMoreContacts[activeAccountID] && !search && !unreadOnly && <div className="flex justify-center p-4">
{hasMoreContacts && !search && !unreadOnly && <div className="flex justify-center p-4">
<button type="button" onClick={() => void loadMoreContacts()} disabled={contactsLoading}
className="flex items-center gap-2 rounded-full border border-slate-200 bg-white px-4 py-2 text-xs font-bold text-slate-500 shadow-sm hover:border-sky-200 hover:text-sky-600 disabled:opacity-50">
{contactsLoading && <Loader2 className="h-3.5 w-3.5 animate-spin" />}{contactsLoading ? '正在加载' : '加载更多历史联系人'}
@@ -489,7 +143,7 @@ const Chat: React.FC = () => {
{selectedSession.buyer_avatar_url ? <img src={selectedSession.buyer_avatar_url} alt={selectedSession.buyer_name || '用户'} className="h-full w-full object-cover" /> : <UserRound className="m-2 h-5 w-5 text-slate-500" />}
</div>}
<div className={`max-w-[72%] ${outgoing ? 'items-end' : 'items-start'} flex flex-col`}>
<div className={`mb-1 px-1 text-[10px] font-semibold text-slate-400`}>{outgoing ? (activeAccount?.nickname || activeAccount?.remark || '我') : (selectedSession.buyer_name || message.sender_name || selectedSession.buyer_id)}</div>
<div className="mb-1 px-1 text-[10px] font-semibold text-slate-400">{outgoing ? (activeAccount?.nickname || activeAccount?.remark || '我') : (selectedSession.buyer_name || message.sender_name || selectedSession.buyer_id)}</div>
{message.message_type === 'image' ? (
<a href={message.content} target="_blank" rel="noreferrer" className={`block overflow-hidden rounded-2xl border bg-white p-1 shadow-sm ${outgoing ? 'rounded-br-md border-sky-200' : 'rounded-bl-md border-slate-200'}`}>
<img src={message.content} alt="聊天图片" className="max-h-80 max-w-full rounded-xl object-contain" />
@@ -512,7 +166,7 @@ const Chat: React.FC = () => {
})}
</>}
</div>
{error && <div className="border-t border-red-100 bg-red-50 px-5 py-2 text-xs font-medium text-red-700">{error}</div>}
{error && <div className="flex items-center justify-between gap-3 border-t border-red-100 bg-red-50 px-5 py-2 text-xs font-medium text-red-700"><span>{error}</span>{retryAvailable && <button type="button" className="font-bold underline" onClick={() => void retrySend()}>重试发送</button>}</div>}
<div className="relative z-10 shrink-0 border-t border-slate-200 bg-white p-4 shadow-chat-input">
<div className="mb-2 flex items-center gap-1">
<div className="relative">
@@ -520,21 +174,19 @@ const Chat: React.FC = () => {
{emojiOpen && <div className="absolute bottom-11 left-0 z-30 w-[360px] rounded-2xl border border-slate-200 bg-white p-3 shadow-2xl">
<div className="mb-2 text-xs font-bold text-slate-500">全部表情</div>
<div className="grid max-h-72 grid-cols-8 gap-1 overflow-y-auto">
{xianyuEmojis.map(([name,file]) => <button key={name} type="button" title={`[${name}]`} onClick={() => { setDraft(value => value + `[${name}]`); setEmojiOpen(false); }} className="flex h-10 w-10 items-center justify-center rounded-lg hover:bg-slate-100"><img src={emojiURL(file)} alt={`[${name}]`} className="h-8 w-8 object-contain" /></button>)}
{xianyuEmojis.map(([name, file]) => <button key={name} type="button" title={`[${name}]`} onClick={() => { setDraft(value => value + `[${name}]`); setEmojiOpen(false); }} className="flex h-10 w-10 items-center justify-center rounded-lg hover:bg-slate-100"><img src={emojiURL(file)} alt={`[${name}]`} className="h-8 w-8 object-contain" /></button>)}
</div>
</div>}
</div>
<input ref={imageInputRef} type="file" accept="image/*" className="hidden" onChange={event => void handleImage(event.target.files?.[0])} />
<button type="button" onClick={() => imageInputRef.current?.click()} disabled={sending || activeAccount?.runtime_state !== 'online'}
className="rounded-lg p-2 text-slate-500 transition hover:bg-sky-50 hover:text-sky-600 disabled:opacity-40" title="发送图片(最大 10MB)"><ImagePlus className="h-5 w-5" /></button>
<button type="button" onClick={() => imageInputRef.current?.click()} disabled={sending || activeAccount?.runtime_state !== 'online'} className="rounded-lg p-2 text-slate-500 transition hover:bg-sky-50 hover:text-sky-600 disabled:opacity-40" title="发送图片(最大 10MB)"><ImagePlus className="h-5 w-5" /></button>
</div>
<div className="flex items-end gap-3 rounded-2xl border border-slate-200 bg-slate-50 p-2 transition focus-within:border-sky-400 focus-within:ring-2 focus-within:ring-sky-100">
<textarea value={draft} onChange={event => setDraft(event.target.value)} rows={2} maxLength={2000}
onKeyDown={event => { if (event.key === 'Enter' && !event.shiftKey) { event.preventDefault(); void handleSend(); } }}
disabled={activeAccount?.runtime_state !== 'online'} placeholder={activeAccount?.runtime_state === 'online' ? '输入消息,Enter 发送,Shift + Enter 换行' : '账号离线,暂时无法发送'}
className="max-h-32 min-h-12 flex-1 resize-none bg-transparent px-2 py-2 text-sm leading-6 outline-none disabled:cursor-not-allowed" />
<button type="button" onClick={() => void handleSend()} disabled={!draft.trim() || sending || activeAccount?.runtime_state !== 'online'}
className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-sky-500 text-white shadow-md shadow-sky-100 transition hover:bg-sky-600 disabled:cursor-not-allowed disabled:bg-slate-300 disabled:shadow-none" aria-label="发送消息">
<button type="button" onClick={() => void handleSend()} disabled={!draft.trim() || sending || activeAccount?.runtime_state !== 'online'} className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-sky-500 text-white shadow-md shadow-sky-100 transition hover:bg-sky-600 disabled:cursor-not-allowed disabled:bg-slate-300 disabled:shadow-none" aria-label="发送消息">
{sending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Send className="h-4 w-4" />}
</button>
</div>
+23
View File
@@ -72,6 +72,29 @@ test('chat APIs preserve account and conversation scope', async () => {
expect(JSON.parse(fetchMock.mock.calls[3][1].body)).toEqual({ account_id: 'a1', chat_id: 'c1' });
});
test('Chat 会话、消息和发送 API 转发外部取消信号', async () => {
// fetchMock 验证会话切换、消息分页和文本/图片发送共享取消控制能力。
const fetchMock = vi.fn()
.mockResolvedValueOnce(jsonResponse({ sessions: [], has_more: false }))
.mockResolvedValueOnce(jsonResponse({ messages: [], has_more: false }))
.mockResolvedValueOnce(jsonResponse({ success: true, message: { message_key: 'm1' } }))
.mockResolvedValueOnce(jsonResponse({ success: true, message: { message_key: 'm2' } }))
.mockResolvedValueOnce(jsonResponse({ success: true }));
vi.stubGlobal('fetch', fetchMock);
// controller 是 Chat feature Hook 使用的请求控制器。
const controller = new AbortController();
await getChatSessionPage('a1', undefined, { signal: controller.signal });
await getChatMessagePage('a1', 'c1', undefined, undefined, { signal: controller.signal });
await sendChatMessage({ account_id: 'a1', chat_id: 'c1', buyer_id: 'b1', text: 'hi' }, { signal: controller.signal });
await sendChatImage({ account_id: 'a1', chat_id: 'c1', buyer_id: 'b1', image: new File(['image'], 'chat.png', { type: 'image/png' }) }, { signal: controller.signal });
await markChatRead('a1', 'c1', { signal: controller.signal });
expect(fetchMock).toHaveBeenNthCalledWith(1, '/api/v1/chat/sessions?account_id=a1', expect.objectContaining({ signal: expect.any(AbortSignal) }));
expect(fetchMock).toHaveBeenNthCalledWith(2, '/api/v1/chat/messages?account_id=a1&chat_id=c1', expect.objectContaining({ signal: expect.any(AbortSignal) }));
expect(fetchMock).toHaveBeenNthCalledWith(3, '/api/v1/chat/messages', expect.objectContaining({ signal: expect.any(AbortSignal) }));
expect(fetchMock).toHaveBeenNthCalledWith(4, '/api/v1/chat/images', expect.objectContaining({ signal: expect.any(AbortSignal) }));
expect(fetchMock).toHaveBeenNthCalledWith(5, '/api/v1/chat/read', expect.objectContaining({ signal: expect.any(AbortSignal) }));
});
test('account task APIs keep rating and polish account-scoped', async () => {
const fetchMock = vi.fn().mockImplementation(() => Promise.resolve(jsonResponse({ success: true, summary: { task_type: 'auto_rate' } })));
vi.stubGlobal('fetch', fetchMock);
+9 -9
View File
@@ -135,21 +135,21 @@ export const getChatMessages = async (accountId: string, chatId: string, beforeI
(await getChatMessagePage(accountId, chatId, undefined, beforeId, options)).messages;
export const sendChatMessage = async (input: {
account_id: string; chat_id: string; buyer_id: string; buyer_name?: string;
item_id?: string; item_title?: string; text: string;
}): Promise<{message: ChatMessage}> => post('/api/v1/chat/messages', input);
account_id: string; chat_id: string; buyer_id: string; buyer_name?: string;
item_id?: string; item_title?: string; text: string;
}, options?: RequestControlOptions): Promise<{message: ChatMessage}> => post('/api/v1/chat/messages', input, options);
export const sendChatImage = async (input: {
account_id: string; chat_id: string; buyer_id: string; buyer_name?: string;
buyer_avatar_url?: string; item_id?: string; item_title?: string; image: File;
}): Promise<{message: ChatMessage}> => {
account_id: string; chat_id: string; buyer_id: string; buyer_name?: string;
buyer_avatar_url?: string; item_id?: string; item_title?: string; image: File;
}, options?: RequestControlOptions): Promise<{message: ChatMessage}> => {
const form = new FormData();
Object.entries(input).forEach(([key, value]) => form.append(key, value));
return postForm('/api/v1/chat/images', form, { timeoutMs: 120_000 });
return postForm('/api/v1/chat/images', form, { timeoutMs: 120_000, ...options });
};
export const markChatRead = async (accountId: string, chatId: string): Promise<ApiResponse> =>
post('/api/v1/chat/read', { account_id: accountId, chat_id: chatId });
export const markChatRead = async (accountId: string, chatId: string, options?: RequestControlOptions): Promise<ApiResponse> =>
post('/api/v1/chat/read', { account_id: accountId, chat_id: chatId }, options);
export interface AccountRuntimeStatus {
state: NonNullable<AccountDetail['runtime_state']>;
@@ -1,20 +0,0 @@
import{j as e,r,c as Ls,b as Ee,d as ar}from"./react-vendor-C_od1ZSF.js";import{L as rr,U as fa,M as gs,C as Rs,B as ya,S as ja,Z as bs,a as kt,b as Is,G as Ms,c as Os,d as Ps,e as lr,f as Na,g as nt,A as Bs,D as nr,P as va,h as Bt,E as _a,T as ir,i as or,j as Se,X as Re,k as cr,l as dr,m as Es,n as wa,o as tt,p as Ke,q as ka,K as xr,r as ct,s as lt,Q as as,t as xt,u as jt,v as $t,R as We,w as Ca,x as mr,y as Ve,z as _t,F as Dt,H as st,I as qs,J as Nt,N as ur,O as pr,V as hr,W as Sa,Y as Aa,_ as La,$ as gr,a0 as br,a1 as rs,a2 as zt,a3 as fs,a4 as fr,a5 as yr,a6 as ys,a7 as Fs,a8 as jr,a9 as Nr,aa as Mt,ab as zs,ac as Ht,ad as Ra,ae as vr,af as _r,ag as ts,ah as Ia,ai as wr,aj as kr,ak as Cr,al as Sr,am as Ar,an as Lr,ao as Us}from"./icons-vendor-i_74xDZy.js";import{R as Zt,B as Rr,X as Ws,Y as Gs,T as Yt,a as Ir,C as js,A as Or,b as Pr,c as Er,P as Js,d as Qs,L as Tr}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))l(n);new MutationObserver(n=>{for(const m of n)if(m.type==="childList")for(const p of m.addedNodes)p.tagName==="LINK"&&p.rel==="modulepreload"&&l(p)}).observe(document,{childList:!0,subtree:!0});function a(n){const m={};return n.integrity&&(m.integrity=n.integrity),n.referrerPolicy&&(m.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?m.credentials="include":n.crossOrigin==="anonymous"?m.credentials="omit":m.credentials="same-origin",m}function l(n){if(n.ep)return;n.ep=!0;const m=a(n);fetch(n.href,m)}})();const $r=({className:t="w-full h-full text-white"})=>e.jsx("svg",{className:t,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),Ns=({sizeClass:t="w-12 h-12",logoClassName:s="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${t} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgb(var(--color-brand))"}),e.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23Line truncated
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(Is,{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:Fe,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:me,children:"取消"}),e.jsxs("button",{onClick:c,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:me,children:[me?e.jsx(Se,{className:"w-4 h-4 animate-spin"}):e.jsx(tt,{className:"w-4 h-4"}),me?"保存中...":"保存"]})]})})]})}),document.body)]})},Tn=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],$n=t=>{const s=typeof t=="object"&&t!==null?t:{},a=Array.isArray(s.results)?s.results:[];return{total:Number(s.total||0),success_count:Number(s.success_count||0),failed_count:Number(s.failed_count||0),results:a.map(Dn)}},Dn=t=>{const s=typeof t=="object"&&t!==null?t:{};return{order_id:String(s.order_id||"unknown"),success:s.success===!0,message:String(s.message||"")}},Mn=t=>(t==null?void 0:t.results.filter(Bn))||[],Bn=t=>!t.success,qn=(t,s)=>t!==null&&!s,Fn=t=>{if(!t)return"请选择订单文件";const s=t.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(s)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},dt=(t,s)=>t===s,zn=(t,s)=>t instanceof Error&&t.message?t.message:s,Un=({filter:t,onFilterChange:s,accountFilter:a,onAccountFilterChange:l,accounts:n,accountName:m,searchText:p,onSearchChange:f})=>{const u=b=>s(b.currentTarget.dataset.status||"all"),v=b=>l(b.target.value),x=b=>f(b.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:Tn.map(b=>e.jsx("button",{"data-status":b.key,onClick:u,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${t===b.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:b.label},b.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(xt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{"aria-label":"按账号筛选订单",value:a,onChange:v,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:"全部账号"}),n.map(b=>e.jsx("option",{value:b.id,children:m(b.id)},b.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(_t,{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:p,onChange:x,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},Wn=t=>{const s=m=>{var p;t.setImportFile(((p=m.target.files)==null?void 0:p[0])||null)},a=()=>t.closeImportModal(),l=()=>void t.handleImportOrders(),n=()=>void t.handleRetryImport();return t.showImportModal?Ee.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:a,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(Re,{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:s,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:"支持 .xl Line truncated
VIP-002
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.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:x,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:p,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:R,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(Se,{className:"w-4 h-4 animate-spin"}):e.jsx(Dt,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:z,disabled:!a.appendTargetId||a.appendPreview.length===0||a.batchBusy||t.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(Se,{className:"w-4 h-4 animate-spin"}):e.jsx(st,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"追加卡密"]})]})]})}),document.body):null},Kn=({type:t})=>{switch(t){case"text":return e.jsx(Aa,{className:"w-5 h-5 text-blue-500"});case"image":return e.jsx(Sa,{className:"w-5 h-5 text-purple-500"});case"api":return e.jsx(hr,{className:"w-5 h-5 text-blue-500"});default:return e.jsx(Rs,{className:"w-5 h-5 text-gray-500"})}},Hn=(t,s,a)=>{const l=a.trim().toLocaleLowerCase();return t.filter(n=>(!s||n.type===s)&&(!l||n.name.toLocaleLowerCase().includes(l)))},Ja=t=>t.split(`
`).map(s=>s.trim()).filter(Boolean),Zn=(t,s,a)=>!!(t&&Ja(s).length>0&&!a),yt=(t,s,a,l)=>t===s&&a===l,Yn=()=>{const[t,s]=r.useState([]),[a,l]=r.useState(!0),n=r.useRef(0),m=r.useRef(null),p=r.useCallback(async()=>{var v;const f=++n.current;(v=m.current)==null||v.abort();const u=new AbortController;m.current=u,l(!0);try{const x=await $s({signal:u.signal});if(f!==n.current)return;s(x)}catch(x){f===n.current&&!u.signal.aborted&&console.error("加载卡密库存失败:",x)}finally{f===n.current&&l(!1)}},[]);return r.useEffect(()=>(p(),()=>{var u;n.current+=1,(u=m.current)==null||u.abort()}),[p]),{cards:t,setCards:s,loading:a,loadCards:p}},Xn=t=>{const s=t.dataCards,a=t.loadCards,[l,n]=r.useState(!1),[m,p]=r.useState("create"),[f,u]=r.useState(null),[v,x]=r.useState(null),[b,_]=r.useState(!1),[R,z]=r.useState(""),[j,I]=r.useState(""),[P,U]=r.useState(null),[Z,ee]=r.useState(""),k=r.useRef(0),S=r.useRef(null),H=r.useRef(""),M=r.useMemo(()=>Ja(j),[j]),W=r.useCallback(()=>{var C;p("create"),u(null),x(null),z((C=s[0])!=null&&C.id?String(s[0].id):""),I(""),U(null),ee(""),n(!0)},[s]),d=r.useCallback(()=>{var C;k.current+=1,(C=S.current)==null||C.abort(),_(!1),n(!1)},[]),D=r.useCallback(async()=>{var A;if(!f||b)return;const C=++k.current;(A=S.current)==null||A.abort();const T=new AbortController;S.current=T,_(!0),x(null);try{const G=await El(f,{signal:T.signal});if(!yt(C,k.current,"",""))return;x(G),G.created>0&&await a()}catch(G){if(!yt(C,k.current,"",""))return;x({error:(G==null?void 0:G.message)||"上传失败"})}finally{yt(C,k.current,"","")&&_(!1)}},[b,f,a]),K=r.useCallback(async()=>{var G;if(!Zn(R,j,b))return;const C=R,T=++k.current;H.current=C,(G=S.current)==null||G.abort();const A=new AbortController;S.current=A,_(!0),U(null),ee("");try{const F=await Tl(C,j,{signal:A.signal});if(!yt(T,k.current,C,R))return;U({added:F.added}),I(""),await a()}catch(F){if(!yt(T,k.current,C,R))return;ee((F==null?void 0:F.message)||"追加失败")}finally{yt(T,k.current,C,R)&&_(!1)}},[j,R,b,a]),O=r.useCallback(async()=>{await D()},[D]),h=r.useCallback(async()=>{H.current&&R!==H.current||await K()},[R,K]);return{showBatchModal:l,setShowBatchModal:n,batchTab:m,setBatchTab:p,batchFile:f,setBatchFile:u,batchResult:v,batchBusy:b,appendTargetId:R,setAppendTargetId:z,appendContent:j,setAppendContent:I,appendResult:P,appendError:Z,appendPreview:M,openBatchModal:W,closeBatchModal:d,handleBatchCreate:D,handleBatchAppend:K,handleRetryBatchCreate:O,handleRetryBatchAppend:h}},la=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),ei=()=>{const{cards:t,loadCards:s}=Yn(),[a,l]=r.useState(!1),[n,m]=r.useState(!1),[p,f]=r.useState(null),[u,v]=r.useState({}),[x,b]=r.useState(la),[_,R]=r.useState(""),[z,j]=r.useState(""),I=r.useMemo(()=>t.filter(d=>d.type==="data"),[t]),P=Xn({dataCards:I,loadCards:s}),U=d=>{var D,K,O,h,C;f(d),v({id:d.id,name:d.name||"",type:d.type||"text",api_url:((D=d.api_config)==null?void 0:D.url)||"",api_method:((K=d.api_config)==null?void 0:K.method)||"GET",api_timeout:((O=d.api_config)==null?void 0:O.timeout)||10,api_headers:((h=d.api_config)==null?void 0:h.headers)||"",api_params:((C=d.api_config)==null?void 0:C.params)||"",text_content:d.text_content||"",data_content:d.data_content||"",image_url:d.image_url||"",delay_seconds:d.delay_seconds||0,description:d.description||"",enabled:d.enabled}),l(!0)},Z=async()=>{var d,D,K,O,h,C,T,A;if(p){if(!((d=u.name)!=null&&d.trim())){alert("请输入卡密名称");return}if(!u.type){alert("请选择卡密类型");return}try{const G={name:u.name.trim(),type:u.type,description:(D=u.description)==null?void 0:D.trim(),delay_seconds:u.delay_seconds||0,enabled:u.enabled??!0};u.type==="api"?G.api_config={url:((K=u.api_url)==null?void 0:K.trim())||"",method:u.api_method,timeout:u.api_timeout||10,headers:((O=u.api_headers)==null?void 0:O.trim())||void 0,params:((h=u.api_params)==null?void 0:h.trim())||void 0}:u.type==="text"?G.text_content=((C=u.text_content)==null?void 0:C.trim())||"":u.type==="data"?G.data_content=((T=u.data_content)==null?void 0:T.trim())||"":u.type==="image"&&(G.image_url=((A=u.image_url)==null?void 0:A.trim())||""),await Ys(p.id,G),l(!1),await s()}catch(G){console.error("更新卡密失败:",G),alert("更新失败,请重试")}}},ee=async d=>{if(confirm("确认删除该卡密吗?"))try{await Pl(d),await s()}catch(D){console.error("删除卡密失败:",D),alert("删除失败,请重试")}},k=async()=>{if(!x.name.trim()){alert("请输入卡密名称");return}if(!x.content.trim()){alert(x.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const d={name:x.name.trim(),type:x.type,description:x.description.trim(),enabled:x.enabled,delay_seconds:x.delay_seconds};x.type==="text"&&(d.text_content=x.content.trim()),x.type==="data"&&(d.data_content=x.content.trim()),x.type==="image"&&(d.image_url=x.content.trim()),x.type==="api"&&(d.api_config={url:x.content.trim(),method:x.a Line truncated
VIP-MONTH-002
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(T=>T.map(A=>`"${String(A).replace(/"/g,'""')}"`).join(",")).join(`
`),O=new Blob(["\uFEFF"+K],{type:"text/csv;charset=utf-8"}),h=URL.createObjectURL(O),C=document.createElement("a");C.href=h,C.download="卡密组批量导入模板.csv",document.body.appendChild(C),C.click(),C.remove(),URL.revokeObjectURL(h)};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:P.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(Dt,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>m(!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(st,{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(La,{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:d=>R(d.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(_t,{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:z,onChange:d=>j(d.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," / ",t.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(d=>{let D="";return d.type==="data"&&d.data_content?D=`库存: ${d.data_content.split(`
`).filter(O=>O.trim()).length} 条`:d.type==="text"&&d.text_content?D=d.text_content:d.type==="api"&&d.api_config?D=d.api_config.url:d.type==="image"&&d.image_url&&(D="图片链接"),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(Kn,{type:d.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:d.name,children:d.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:()=>H(d.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:d.id}),e.jsx(gr,{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 ${d.type==="text"?"bg-blue-50 text-blue-600":d.type==="data"?"bg-purple-50 text-purple-600":d.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:d.type==="text"?"文本":d.type==="data"?"批量":d.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:D,children:D})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:d.description||"-",children:d.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:()=>S(d),className:`w-12 h-8 rounded-full relative transition-colors ${d.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 ${d.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:()=>U(d),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(Nt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>ee(d.id),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(Ve,{className:"h-4 w-4"})})]})})]},d.id)})})]})}),M.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(va,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:t.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),a&&p&&Ee.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:()=>l(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(Re,{className:"w-5 h-5 text-gray-500"})})]}),e.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:u.name||"",onChange:d=>v({...u,name:d.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:u.type||"text",onChange:d=>v({...u,type:d.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:"批量数据"}),(p==null?void 0:p.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),u.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:u.api_url||"",onChange:d=>v({...u,api_url:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxLine truncated
卡号1:密码1
卡号2:密码2
或者
兑换码1
兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:u.data_content?u.data_content.split(`
`).filter(d=>d.trim()).length:0})," 条"]})]})]}),u.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:u.image_url||"",onChange:d=>v({...u,image_url:d.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 地址"})]}),u.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:u.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:d=>{d.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:u.delay_seconds||0,onChange:d=>v({...u,delay_seconds:parseInt(d.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:u.description||"",onChange:d=>v({...u,description:d.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:()=>v({...u,enabled:!u.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${u.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 ${u.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:()=>l(!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:Z,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(tt,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),n&&Ee.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:()=>m(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(Re,{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:x.name,onChange:d=>b({...x,name:d.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:()=>b({...x,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${x.type==="data"?"bg-brand text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(Rs,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>b({...x,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${x.type==="text"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(Aa,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>b({...x,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${x.type==="image"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children: Line truncated
CODE-789012
...`:"请输入每次发货时发送的固定文字"}),x.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-brand",children:x.content.split(`
`).filter(d=>d.trim()).length})," 条"]})]}),x.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:x.api_method,onChange:d=>b({...x,api_method:d.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:x.api_timeout,onChange:d=>b({...x,api_timeout:parseInt(d.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:x.api_headers,onChange:d=>b({...x,api_headers:d.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:x.api_params,onChange:d=>b({...x,api_params:d.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:x.description,onChange:d=>b({...x,description:d.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:x.delay_seconds,onChange:d=>b({...x,delay_seconds:parseInt(d.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:()=>m(!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:k,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(st,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),e.jsx(Vn,{dataCards:I,downloadCardTemplate:W,...P})]})},na="ydisks-amap-js-api",ti="c9b68d4ce9a2a97f22a4a439404488ca";let It=null;const si=()=>ti,ai=()=>window.AMap?Promise.resolve(window.AMap):It||(It=new Promise((t,s)=>{const a=document.getElementById(na),l=a||document.createElement("script"),n=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(p)},m=()=>{window.AMap?(n(),t(window.AMap)):(n(),s(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},p=window.setTimeout(()=>{n(),s(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=m,l.id=na,l.async=!0,l.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(si())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,l.onerror=()=>{n(),s(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},a||document.head.appendChild(l)}).catch(t=>{throw It=null,t}),It),es=t=>Number.isFinite(t)&&t!==0,ri=t=>{var n,m;const s=Number((n=t.location)==null?void 0:n.lng),a=Number((m=t.location)==null?void 0:m.lat),l={area:String(t.adname||"").trim(),city:String(t.cityname||"").trim(),division_id:String(t.adcode||"").trim(),longitude:s,latitude:a,poi_id:String(t.id||"").trim(),poi_name:String(t.name||"").trim(),province:String(t.pname||"").trim()};return!l.division_id||!l.province||!l.city||!l.poi_id||!l.poi_name||!es(s)||!es(a)||s<-180||s>180||a<-90||a>90?null:l},li=async(t,s)=>{if(!es(t)||!es(s)||t<-180||t>180||s<-90||s>90)throw new Error("经纬度无效");const a=await ai();return new Promise((l,n)=>{new a.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[t,s],1e3,(p,f)=>{var v;if(p!=="complete"){if(p==="no_data"){l([]);return}n(new Error("高德地图附近地址查询失败,请稍后重试"));return}const u=(((v=f==null?void 0:f.poiList)==null?void 0:v.pois)||[]).map(ri).filter(x=>x!==null);l(u)})})},ni=t=>t.find(s=>s.status==="running"||s.status==="canceling"),Ss=t=>t==="running"||t==="canceling",ii=t=>!!(t!=null&&t.previ Line truncated
`),Ie=new Blob(["\uFEFF"+pe],{type:"text/csv;charset=utf-8"}),Qe=URL.createObjectURL(Ie),Fe=document.createElement("a");Fe.href=Qe,Fe.download="批量铺货模板.csv",document.body.appendChild(Fe),Fe.click(),Fe.remove(),URL.revokeObjectURL(Qe)},At=()=>{T(c=>({...c,cookie_id:f||c.cookie_id})),U(!0)},mt=()=>{G(c=>({...c,cookie_id:f||c.cookie_id})),ee(!0)},ut=async c=>{if(!(c?f:A.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");S(!0),navigator.geolocation.getCurrentPosition(async pe=>{try{const Ie=await li(pe.coords.longitude,pe.coords.latitude);if(!Ie.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");c?(y(Ie),E(Ie[0])):(M(Ie),d(Ie[0]))}catch(Ie){alert((Ie==null?void 0:Ie.message)||"获取发货地失败")}finally{S(!1)}},pe=>{S(!1),alert(pe.code===pe.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},Lt=c=>l.filter(Q=>Q.cookie_id===c.cookie_id&&Q.item_id===c.item_id).length>0?l.filter(Q=>Q.cookie_id===c.cookie_id&&Q.item_id===c.item_id):l.filter(Q=>Q.cookie_id===c.cookie_id&&!Q.item_id),pt=r.useMemo(()=>new Map(m.map(c=>[c.id,c])),[m]),ht=r.useMemo(()=>v?s.filter(c=>c.cookie_id===v):s,[v,s]),Ye=c=>{const Q=pt.get(c),pe=(Q==null?void 0:Q.remark)||(Q==null?void 0:Q.nickname);return pe?`${pe} · ${c.slice(0,6)}`:`账号 ${c.slice(0,8)}`},gt=c=>{const Q=pt.get(c);return(Q==null?void 0:Q.remark)||(Q==null?void 0:Q.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(br,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-account-filter","aria-label":"按账号筛选商品列表",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:v,onChange:c=>x(c.target.value),children:[e.jsx("option",{value:"",children:"全部账号"}),m.map(c=>e.jsx("option",{value:c.id,children:Ye(c.id)},c.id))]})]})]}),e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-sync-account",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"同步商品账号"}),e.jsxs("div",{className:"relative",children:[e.jsx(xt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-sync-account","aria-label":"选择要同步商品的账号",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:f,onChange:c=>u(c.target.value),children:[e.jsx("option",{value:"",children:"请选择账号"}),m.map(c=>e.jsx("option",{value:c.id,children:Ye(c.id)},c.id))]})]})]}),e.jsxs("button",{onClick:Ae,disabled:b||!f,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(We,{className:`w-4 h-4 ${b?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:At,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(st,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:mt,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-500 text-white hover:bg-emerald-600 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(rs,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void te(),className:"px-5 py-3 rounded-2xl font-bold bg-brand text-white hover:bg-brand-highlight transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[e.jsx(zt,{className:"w-4 h-4"}),de&&["running","canceling"].includes(de.status)?"继续批量任务":"批量铺货"]}),de&&!["running","canceling"].includes(de.status)&&e.jsx("button",{onClick:()=>void Ce(),className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"最近批次结果"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[ht.map(c=>{const Q=Lt(c),pe=Q.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relative flex fle 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
@@ -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%}@media(min-width:640px){.container{max-width:640px}}@media(min-width:768px){.container{max-width:768px}}@media(min-widtLine truncated
@@ -0,0 +1,20 @@
import{j as e,r,c as Is,b as Me,d as ar}from"./react-vendor-C_od1ZSF.js";import{L as rr,U as fa,M as ys,C as Os,B as ya,S as ja,Z as js,a as Rt,b as Ps,G as Bs,c as Es,d as Ts,e as lr,f as va,g as pt,A as Fs,D as nr,P as Na,h as Ft,E as _a,T as ir,i as or,j as Ce,X as Oe,k as cr,l as dr,m as Ds,n as wa,o as ot,p as at,q as ka,K as xr,r as ft,s as ut,Q as ls,t as jt,u as kt,v as Mt,R as He,w as Ca,x as mr,y as st,z as At,F as qt,H as ct,I as zs,J as Ct,N as ur,O as pr,V as hr,W as Sa,Y as Aa,_ as La,$ as gr,a0 as br,a1 as ns,a2 as Wt,a3 as vs,a4 as fr,a5 as yr,a6 as Ns,a7 as Us,a8 as jr,a9 as vr,aa as Bt,ab as Ws,ac as Yt,ad as Ra,ae as Nr,af as _r,ag as as,ah as Ia,ai as wr,aj as kr,ak as Cr,al as Sr,am as Ar,an as Lr,ao as Gs}from"./icons-vendor-i_74xDZy.js";import{R as Xt,B as Rr,X as Js,Y as Qs,T as es,a as Ir,C as _s,A as Or,b as Pr,c as Er,P as Vs,d as Ks,L as Tr}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))l(n);new MutationObserver(n=>{for(const x of n)if(x.type==="childList")for(const p of x.addedNodes)p.tagName==="LINK"&&p.rel==="modulepreload"&&l(p)}).observe(document,{childList:!0,subtree:!0});function a(n){const x={};return n.integrity&&(x.integrity=n.integrity),n.referrerPolicy&&(x.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?x.credentials="include":n.crossOrigin==="anonymous"?x.credentials="omit":x.credentials="same-origin",x}function l(n){if(n.ep)return;n.ep=!0;const x=a(n);fetch(n.href,x)}})();const Dr=({className:t="w-full h-full text-white"})=>e.jsx("svg",{className:t,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),ws=({sizeClass:t="w-12 h-12",logoClassName:s="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${t} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgb(var(--color-brand))"}),e.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23Line truncated
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(Ps,{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:Ge,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:ge,children:"取消"}),e.jsxs("button",{onClick:c,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:ge,children:[ge?e.jsx(Ce,{className:"w-4 h-4 animate-spin"}):e.jsx(ot,{className:"w-4 h-4"}),ge?"保存中...":"保存"]})]})})]})}),document.body)]})},En=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],Tn=t=>{const s=typeof t=="object"&&t!==null?t:{},a=Array.isArray(s.results)?s.results:[];return{total:Number(s.total||0),success_count:Number(s.success_count||0),failed_count:Number(s.failed_count||0),results:a.map(Dn)}},Dn=t=>{const s=typeof t=="object"&&t!==null?t:{};return{order_id:String(s.order_id||"unknown"),success:s.success===!0,message:String(s.message||"")}},$n=t=>(t==null?void 0:t.results.filter(Mn))||[],Mn=t=>!t.success,qn=(t,s)=>t!==null&&!s,Bn=t=>{if(!t)return"请选择订单文件";const s=t.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(s)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},yt=(t,s)=>t===s,Fn=(t,s)=>t instanceof Error&&t.message?t.message:s,zn=({filter:t,onFilterChange:s,accountFilter:a,onAccountFilterChange:l,accounts:n,accountName:x,searchText:p,onSearchChange:f})=>{const u=b=>s(b.currentTarget.dataset.status||"all"),j=b=>l(b.target.value),m=b=>f(b.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:En.map(b=>e.jsx("button",{"data-status":b.key,onClick:u,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${t===b.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:b.label},b.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(jt,{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:a,onChange:j,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:"全部账号"}),n.map(b=>e.jsx("option",{value:b.id,children:x(b.id)},b.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(At,{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:p,onChange:m,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},Un=t=>{const s=x=>{var p;t.setImportFile(((p=x.target.files)==null?void 0:p[0])||null)},a=()=>t.closeImportModal(),l=()=>void t.handleImportOrders(),n=()=>void t.handleRetryImport();return t.showImportModal?Me.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:a,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(Oe,{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:s,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:"支持 .xl Line truncated
VIP-002
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.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:m,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:p,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:L,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(Ce,{className:"w-4 h-4 animate-spin"}):e.jsx(qt,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:F,disabled:!a.appendTargetId||a.appendPreview.length===0||a.batchBusy||t.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(Ce,{className:"w-4 h-4 animate-spin"}):e.jsx(ct,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"追加卡密"]})]})]})}),document.body):null},Vn=({type:t})=>{switch(t){case"text":return e.jsx(Aa,{className:"w-5 h-5 text-blue-500"});case"image":return e.jsx(Sa,{className:"w-5 h-5 text-purple-500"});case"api":return e.jsx(hr,{className:"w-5 h-5 text-blue-500"});default:return e.jsx(Os,{className:"w-5 h-5 text-gray-500"})}},Kn=(t,s,a)=>{const l=a.trim().toLocaleLowerCase();return t.filter(n=>(!s||n.type===s)&&(!l||n.name.toLocaleLowerCase().includes(l)))},Ja=t=>t.split(`
`).map(s=>s.trim()).filter(Boolean),Hn=(t,s,a)=>!!(t&&Ja(s).length>0&&!a),_t=(t,s,a,l)=>t===s&&a===l,Zn=()=>{const[t,s]=r.useState([]),[a,l]=r.useState(!0),n=r.useRef(0),x=r.useRef(null),p=r.useCallback(async()=>{var j;const f=++n.current;(j=x.current)==null||j.abort();const u=new AbortController;x.current=u,l(!0);try{const m=await Ms({signal:u.signal});if(f!==n.current)return;s(m)}catch(m){f===n.current&&!u.signal.aborted&&console.error("加载卡密库存失败:",m)}finally{f===n.current&&l(!1)}},[]);return r.useEffect(()=>(p(),()=>{var u;n.current+=1,(u=x.current)==null||u.abort()}),[p]),{cards:t,setCards:s,loading:a,loadCards:p}},Yn=t=>{const s=t.dataCards,a=t.loadCards,[l,n]=r.useState(!1),[x,p]=r.useState("create"),[f,u]=r.useState(null),[j,m]=r.useState(null),[b,v]=r.useState(!1),[L,F]=r.useState(""),[y,O]=r.useState(""),[R,W]=r.useState(null),[K,X]=r.useState(""),_=r.useRef(0),k=r.useRef(null),Z=r.useRef(""),M=r.useMemo(()=>Ja(y),[y]),G=r.useCallback(()=>{var w;p("create"),u(null),m(null),F((w=s[0])!=null&&w.id?String(s[0].id):""),O(""),W(null),X(""),n(!0)},[s]),d=r.useCallback(()=>{var w;_.current+=1,(w=k.current)==null||w.abort(),v(!1),n(!1)},[]),$=r.useCallback(async()=>{var A;if(!f||b)return;const w=++_.current;(A=k.current)==null||A.abort();const T=new AbortController;k.current=T,v(!0),m(null);try{const z=await Pl(f,{signal:T.signal});if(!_t(w,_.current,"",""))return;m(z),z.created>0&&await a()}catch(z){if(!_t(w,_.current,"",""))return;m({error:(z==null?void 0:z.message)||"上传失败"})}finally{_t(w,_.current,"","")&&v(!1)}},[b,f,a]),H=r.useCallback(async()=>{var z;if(!Hn(L,y,b))return;const w=L,T=++_.current;Z.current=w,(z=k.current)==null||z.abort();const A=new AbortController;k.current=A,v(!0),W(null),X("");try{const U=await El(w,y,{signal:A.signal});if(!_t(T,_.current,w,L))return;W({added:U.added}),O(""),await a()}catch(U){if(!_t(T,_.current,w,L))return;X((U==null?void 0:U.message)||"追加失败")}finally{_t(T,_.current,w,L)&&v(!1)}},[y,L,b,a]),P=r.useCallback(async()=>{await $()},[$]),h=r.useCallback(async()=>{Z.current&&L!==Z.current||await H()},[L,H]);return{showBatchModal:l,setShowBatchModal:n,batchTab:x,setBatchTab:p,batchFile:f,setBatchFile:u,batchResult:j,batchBusy:b,appendTargetId:L,setAppendTargetId:F,appendContent:y,setAppendContent:O,appendResult:R,appendError:K,appendPreview:M,openBatchModal:G,closeBatchModal:d,handleBatchCreate:$,handleBatchAppend:H,handleRetryBatchCreate:P,handleRetryBatchAppend:h}},oa=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),Xn=()=>{const{cards:t,loadCards:s}=Zn(),[a,l]=r.useState(!1),[n,x]=r.useState(!1),[p,f]=r.useState(null),[u,j]=r.useState({}),[m,b]=r.useState(oa),[v,L]=r.useState(""),[F,y]=r.useState(""),O=r.useMemo(()=>t.filter(d=>d.type==="data"),[t]),R=Yn({dataCards:O,loadCards:s}),W=d=>{var $,H,P,h,w;f(d),j({id:d.id,name:d.name||"",type:d.type||"text",api_url:(($=d.api_config)==null?void 0:$.url)||"",api_method:((H=d.api_config)==null?void 0:H.method)||"GET",api_timeout:((P=d.api_config)==null?void 0:P.timeout)||10,api_headers:((h=d.api_config)==null?void 0:h.headers)||"",api_params:((w=d.api_config)==null?void 0:w.params)||"",text_content:d.text_content||"",data_content:d.data_content||"",image_url:d.image_url||"",delay_seconds:d.delay_seconds||0,description:d.description||"",enabled:d.enabled}),l(!0)},K=async()=>{var d,$,H,P,h,w,T,A;if(p){if(!((d=u.name)!=null&&d.trim())){alert("请输入卡密名称");return}if(!u.type){alert("请选择卡密类型");return}try{const z={name:u.name.trim(),type:u.type,description:($=u.description)==null?void 0:$.trim(),delay_seconds:u.delay_seconds||0,enabled:u.enabled??!0};u.type==="api"?z.api_config={url:((H=u.api_url)==null?void 0:H.trim())||"",method:u.api_method,timeout:u.api_timeout||10,headers:((P=u.api_headers)==null?void 0:P.trim())||void 0,params:((h=u.api_params)==null?void 0:h.trim())||void 0}:u.type==="text"?z.text_content=((w=u.text_content)==null?void 0:w.trim())||"":u.type==="data"?z.data_content=((T=u.data_content)==null?void 0:T.trim())||"":u.type==="image"&&(z.image_url=((A=u.image_url)==null?void 0:A.trim())||""),await ta(p.id,z),l(!1),await s()}catch(z){console.error("更新卡密失败:",z),alert("更新失败,请重试")}}},X=async d=>{if(confirm("确认删除该卡密吗?"))try{await Ol(d),await s()}catch($){console.error("删除卡密失败:",$),alert("删除失败,请重试")}},_=async()=>{if(!m.name.trim()){alert("请输入卡密名称");return}if(!m.content.trim()){alert(m.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const d={name:m.name.trim(),type:m.type,description:m.description.trim(),enabled:m.enabled,delay_seconds:m.delay_seconds};m.type==="text"&&(d.text_content=m.content.trim()),m.type==="data"&&(d.data_content=m.content.trim()),m.type==="image"&&(d.image_url=m.content.trim()),m.type==="api"&&(d.api_config={url:m.content.trim(),method:m.api_me Line truncated
VIP-MONTH-002
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(T=>T.map(A=>`"${String(A).replace(/"/g,'""')}"`).join(",")).join(`
`),P=new Blob(["\uFEFF"+H],{type:"text/csv;charset=utf-8"}),h=URL.createObjectURL(P),w=document.createElement("a");w.href=h,w.download="卡密组批量导入模板.csv",document.body.appendChild(w),w.click(),w.remove(),URL.revokeObjectURL(h)};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:R.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(qt,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>x(!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(ct,{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(La,{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:v,onChange:d=>L(d.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(At,{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:F,onChange:d=>y(d.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," / ",t.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(d=>{let $="";return d.type==="data"&&d.data_content?$=`库存: ${d.data_content.split(`
`).filter(P=>P.trim()).length} 条`:d.type==="text"&&d.text_content?$=d.text_content:d.type==="api"&&d.api_config?$=d.api_config.url:d.type==="image"&&d.image_url&&($="图片链接"),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(Vn,{type:d.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:d.name,children:d.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:()=>Z(d.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:d.id}),e.jsx(gr,{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 ${d.type==="text"?"bg-blue-50 text-blue-600":d.type==="data"?"bg-purple-50 text-purple-600":d.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:d.type==="text"?"文本":d.type==="data"?"批量":d.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:$,children:$})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:d.description||"-",children:d.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:()=>k(d),className:`w-12 h-8 rounded-full relative transition-colors ${d.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 ${d.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:()=>W(d),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(Ct,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>X(d.id),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(st,{className:"h-4 w-4"})})]})})]},d.id)})})]})}),M.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(Na,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:t.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),a&&p&&Me.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:()=>l(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(Oe,{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:u.name||"",onChange:d=>j({...u,name:d.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:u.type||"text",onChange:d=>j({...u,type:d.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:"批量数据"}),(p==null?void 0:p.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),u.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:u.api_url||"",onChange:d=>j({...u,api_url:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxsLine truncated
卡号1:密码1
卡号2:密码2
或者
兑换码1
兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:u.data_content?u.data_content.split(`
`).filter(d=>d.trim()).length:0})," 条"]})]})]}),u.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:u.image_url||"",onChange:d=>j({...u,image_url:d.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 地址"})]}),u.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:u.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:d=>{d.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:u.delay_seconds||0,onChange:d=>j({...u,delay_seconds:parseInt(d.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:u.description||"",onChange:d=>j({...u,description:d.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:()=>j({...u,enabled:!u.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${u.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 ${u.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:()=>l(!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:K,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(ot,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),n&&Me.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:()=>x(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(Oe,{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:m.name,onChange:d=>b({...m,name:d.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:()=>b({...m,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${m.type==="data"?"bg-brand text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(Os,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>b({...m,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${m.type==="text"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(Aa,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>b({...m,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${m.type==="image"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children: Line truncated
CODE-789012
...`:"请输入每次发货时发送的固定文字"}),m.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-brand",children:m.content.split(`
`).filter(d=>d.trim()).length})," 条"]})]}),m.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:m.api_method,onChange:d=>b({...m,api_method:d.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:m.api_timeout,onChange:d=>b({...m,api_timeout:parseInt(d.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:m.api_headers,onChange:d=>b({...m,api_headers:d.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:m.api_params,onChange:d=>b({...m,api_params:d.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:m.description,onChange:d=>b({...m,description:d.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:m.delay_seconds,onChange:d=>b({...m,delay_seconds:parseInt(d.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:()=>x(!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:_,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(ct,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),e.jsx(Qn,{dataCards:O,downloadCardTemplate:G,...R})]})},ca="ydisks-amap-js-api",ei="c9b68d4ce9a2a97f22a4a439404488ca";let Pt=null;const ti=()=>ei,si=()=>window.AMap?Promise.resolve(window.AMap):Pt||(Pt=new Promise((t,s)=>{const a=document.getElementById(ca),l=a||document.createElement("script"),n=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(p)},x=()=>{window.AMap?(n(),t(window.AMap)):(n(),s(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},p=window.setTimeout(()=>{n(),s(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=x,l.id=ca,l.async=!0,l.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(ti())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,l.onerror=()=>{n(),s(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},a||document.head.appendChild(l)}).catch(t=>{throw Pt=null,t}),Pt),ss=t=>Number.isFinite(t)&&t!==0,ai=t=>{var n,x;const s=Number((n=t.location)==null?void 0:n.lng),a=Number((x=t.location)==null?void 0:x.lat),l={area:String(t.adname||"").trim(),city:String(t.cityname||"").trim(),division_id:String(t.adcode||"").trim(),longitude:s,latitude:a,poi_id:String(t.id||"").trim(),poi_name:String(t.name||"").trim(),province:String(t.pname||"").trim()};return!l.division_id||!l.province||!l.city||!l.poi_id||!l.poi_name||!ss(s)||!ss(a)||s<-180||s>180||a<-90||a>90?null:l},ri=async(t,s)=>{if(!ss(t)||!ss(s)||t<-180||t>180||s<-90||s>90)throw new Error("经纬度无效");const a=await si();return new Promise((l,n)=>{new a.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[t,s],1e3,(p,f)=>{var j;if(p!=="complete"){if(p==="no_data"){l([]);return}n(new Error("高德地图附近地址查询失败,请稍后重试"));return}const u=(((j=f==null?void 0:f.poiList)==null?void 0:j.pois)||[]).map(ai).filter(m=>m!==null);l(u)})})},li=t=>t.find(s=>s.status==="running"||s.status==="canceling"),Ls=t=>t==="running"||t==="canceling",ni=t=>!!(t!=null&&t.previ Line truncated
`),Le=new Blob(["\uFEFF"+ie],{type:"text/csv;charset=utf-8"}),tt=URL.createObjectURL(Le),Ge=document.createElement("a");Ge.href=tt,Ge.download="批量铺货模板.csv",document.body.appendChild(Ge),Ge.click(),Ge.remove(),URL.revokeObjectURL(tt)},ee=()=>{T(c=>({...c,cookie_id:f||c.cookie_id})),W(!0)},ne=()=>{z(c=>({...c,cookie_id:f||c.cookie_id})),X(!0)},le=async c=>{if(!(c?f:A.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");k(!0),navigator.geolocation.getCurrentPosition(async ie=>{try{const Le=await ri(ie.coords.longitude,ie.coords.latitude);if(!Le.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");c?(Te(Le),Ue(Le[0])):(M(Le),d(Le[0]))}catch(Le){alert((Le==null?void 0:Le.message)||"获取发货地失败")}finally{k(!1)}},ie=>{k(!1),alert(ie.code===ie.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},ve=c=>l.filter(Q=>Q.cookie_id===c.cookie_id&&Q.item_id===c.item_id).length>0?l.filter(Q=>Q.cookie_id===c.cookie_id&&Q.item_id===c.item_id):l.filter(Q=>Q.cookie_id===c.cookie_id&&!Q.item_id),We=r.useMemo(()=>new Map(x.map(c=>[c.id,c])),[x]),Ae=r.useMemo(()=>j?s.filter(c=>c.cookie_id===j):s,[j,s]),ze=c=>{const Q=We.get(c),ie=(Q==null?void 0:Q.remark)||(Q==null?void 0:Q.nickname);return ie?`${ie} · ${c.slice(0,6)}`:`账号 ${c.slice(0,8)}`},Ne=c=>{const Q=We.get(c);return(Q==null?void 0:Q.remark)||(Q==null?void 0:Q.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(br,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-account-filter","aria-label":"按账号筛选商品列表",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:j,onChange:c=>m(c.target.value),children:[e.jsx("option",{value:"",children:"全部账号"}),x.map(c=>e.jsx("option",{value:c.id,children:ze(c.id)},c.id))]})]})]}),e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-sync-account",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"同步商品账号"}),e.jsxs("div",{className:"relative",children:[e.jsx(jt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-sync-account","aria-label":"选择要同步商品的账号",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:f,onChange:c=>u(c.target.value),children:[e.jsx("option",{value:"",children:"请选择账号"}),x.map(c=>e.jsx("option",{value:c.id,children:ze(c.id)},c.id))]})]})]}),e.jsxs("button",{onClick:Ke,disabled:b||!f,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(He,{className:`w-4 h-4 ${b?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:ee,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(ct,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:ne,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-500 text-white hover:bg-emerald-600 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(ns,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void Ye(),className:"px-5 py-3 rounded-2xl font-bold bg-brand text-white hover:bg-brand-highlight transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[e.jsx(Wt,{className:"w-4 h-4"}),ue&&["running","canceling"].includes(ue.status)?"继续批量任务":"批量铺货"]}),ue&&!["running","canceling"].includes(ue.status)&&e.jsx("button",{onClick:()=>void Xe(),className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"最近批次结果"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[Ae.map(c=>{const Q=ve(c),ie=Q.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relative flex fl Line truncated
+2 -2
View File
@@ -6,12 +6,12 @@
<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-7RF419ck.js"></script>
<script type="module" crossorigin src="/static/assets/index-DMOAPZ9K.js"></script>
<link rel="modulepreload" crossorigin href="/static/assets/react-vendor-C_od1ZSF.js">
<link rel="modulepreload" crossorigin href="/static/assets/icons-vendor-i_74xDZy.js">
<link rel="modulepreload" crossorigin href="/static/assets/vendor-D-Edl3pr.js">
<link rel="modulepreload" crossorigin href="/static/assets/charts-vendor-BxxJOyEX.js">
<link rel="stylesheet" crossorigin href="/static/assets/index-CstHnrBD.css">
<link rel="stylesheet" crossorigin href="/static/assets/index-DFFQFH9n.css">
</head>
<body>
<div id="root"></div>