阶段七:完成AccountList子模块收口与页面组合边界

This commit is contained in:
Christ committed 2026-08-15 02:21:25 +08:00
1 parent 867ced6849
commit 448713735f
11 files changed
+847 -1107

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -608,3 +608,4 @@ npm --prefix frontend run build
| 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 化与任务设置行为边界 |
| 2026-08-15 | 完成阶段 7 第十个 PR 切片“React AccountAutomation feature 化与任务设置行为边界” | 按 `app/features/accountAutomation` 提取账号任务 API、默认设置与重复执行状态模型、任务设置 Hook;账号切换支持取消和请求代次保护,保存/立即执行支持重复提交阻断、失败重试和结果刷新;新增默认值、动作门禁、API 取消信号测试,保留旧弹窗入口和 API 路径 | 阶段 7:React AccountList 子模块收口与页面组合边界 |
| 2026-08-15 | 完成阶段 7 第十一个 PR 切片“React AccountList 子模块收口与页面组合边界” | 新增 `useAccountSubmodules`,集中管理账号编辑、长登录、通知绑定、AI 设置和密码登录状态;编辑弹窗仅保留页面组合与二维码/删除职责,子模块请求支持并行加载、取消和账号/代次隔离;新增跨子模块过期响应、密码登录取消信号和路由边界测试;前端类型检查、全量测试和构建门禁通过并合并为一个可回滚提交 | 阶段 7:React feature 依赖门禁与旧页面入口瘦身 |
@@ -26,6 +26,15 @@ test('账号切换后只接受当前请求代次和账号的响应',
expect(isCurrentAccountRequest(2, 2, 'account-1', 'account-2')).toBe(false);
});
test('编辑子模块共享同一账号边界,旧绑定、AI 和密码登录响应全部失效',
// 三类异步子模块都使用相同的代次与账号判定,防止旧弹窗响应污染新账号。
() => {
const currentGeneration = 4;
const currentAccountId = 'account-4';
expect(isCurrentAccountRequest(3, currentGeneration, 'account-3', currentAccountId)).toBe(false);
expect(isCurrentAccountRequest(currentGeneration, currentGeneration, currentAccountId, currentAccountId)).toBe(true);
});
test('暂停时长未变化时不会重复启动已结束的暂停',
// 相同的时长只保留当前状态,不自动重新提交暂停请求。
() => {
@@ -0,0 +1,347 @@
import { useCallback, useEffect, useRef, useState, type Dispatch, type SetStateAction } from 'react';
import type { AccountDetail, AIReplySettings, NotificationChannel } from '../../../types';
import { cancelPasswordLogin, checkPasswordLoginStatus, getAccountAISettings, getAccountBindings, getLongLoginSettings, getNotificationChannels, passwordLogin, setLongLoginSettings, updateAccountAISettings, updateAccountPauseDuration, updateAccountSettings } from './api';
import { buildAccountLoginInfoUpdate, isCurrentAccountRequest, passwordLoginViewFromStatus, shouldUpdateAccountPause } from './state';
import type { AccountEditForm, LongLoginState, PasswordLoginView } from './types';
import { shouldSaveNotificationBindings } from '../../../components/accountBindings';
/** AccountList 当前编辑弹窗类型。 */
export type AccountModalType = 'edit' | 'ai-settings' | null;
/** AccountList 子模块 Hook 的输入。 */
export type AccountSubmoduleOptions = {
/** 当前编辑账号。 */
editingAccount: AccountDetail | null;
/** 写入当前编辑账号。 */
setEditingAccount: Dispatch<SetStateAction<AccountDetail | null>>;
/** 当前编辑弹窗类型。 */
setActiveModal: Dispatch<SetStateAction<AccountModalType>>;
/** 当前编辑表单。 */
editForm: AccountEditForm;
/** 更新编辑表单。 */
setEditForm: Dispatch<SetStateAction<AccountEditForm>>;
/** 刷新账号列表。 */
loadAccounts: () => Promise<void>;
};
/** 账号编辑、AI、通知绑定和密码登录子模块共享状态。 */
export const useAccountSubmodules = ({ editingAccount, setEditingAccount, setActiveModal, editForm, setEditForm, loadAccounts }: AccountSubmoduleOptions) => {
// longLogin 保存官方长登录设置状态。
const [longLogin, setLongLogin] = useState<LongLoginState>({ loading: false, saving: false, canOpen: false, enabled: false, error: '' });
// notifChannels 保存可供账号绑定的通知渠道。
const [notifChannels, setNotifChannels] = useState<NotificationChannel[]>([]);
// selectedChannelIds 保存当前选中的通知渠道。
const [selectedChannelIds, setSelectedChannelIds] = useState<number[]>([]);
// bindingsLoaded 表示绑定关系是否成功加载。
const [bindingsLoaded, setBindingsLoaded] = useState(false);
// bindingsLoading 表示通知绑定请求是否进行中。
const [bindingsLoading, setBindingsLoading] = useState(false);
// bindingsDirty 表示用户是否修改过通知绑定。
const [bindingsDirty, setBindingsDirty] = useState(false);
// bindingsLoadError 保存通知绑定加载错误。
const [bindingsLoadError, setBindingsLoadError] = useState('');
// aiSettings 保存账号 AI 编辑草稿。
const [aiSettings, setAiSettings] = useState<AIReplySettings>({ ai_enabled: false, max_discount_percent: 10, max_discount_amount: 100, max_bargain_rounds: 3, custom_prompts: '' });
// saving 表示编辑、AI 或暂停动作是否正在保存。
const [saving, setSaving] = useState(false);
// passwordLoginView 保存密码登录刷新授权状态。
const [passwordLoginView, setPasswordLoginView] = useState<PasswordLoginView>({ sessionId: '', status: 'idle', message: '', qrCodeUrl: '' });
// bindingsSequence 隔离账号切换后的绑定响应。
const bindingsSequence = useRef(0);
// bindingsAbort 保存通知绑定请求控制器。
const bindingsAbort = useRef<AbortController | null>(null);
// longLoginSequence 隔离账号切换后的长登录响应。
const longLoginSequence = useRef(0);
// longLoginAbort 保存长登录状态读取控制器。
const longLoginAbort = useRef<AbortController | null>(null);
// aiSequence 隔离账号切换后的 AI 响应。
const aiSequence = useRef(0);
// aiAbort 保存 AI 查询控制器。
const aiAbort = useRef<AbortController | null>(null);
// passwordGeneration 隔离密码登录轮询响应。
const passwordGeneration = useRef(0);
// passwordAccount 保存密码登录所属账号。
const passwordAccount = useRef('');
// passwordAbort 保存密码登录状态查询控制器。
const passwordAbort = useRef<AbortController | null>(null);
// passwordTimer 保存下一次密码登录轮询定时器。
const passwordTimer = useRef<number | null>(null);
/** 清理密码登录轮询定时器。 */
// clearPasswordTimerCallback 是 React 稳定的定时器清理函数。
const clearPasswordTimer = useCallback(() => {
if (passwordTimer.current !== null) {
window.clearTimeout(passwordTimer.current);
passwordTimer.current = null;
}
}, []);
/** 加载当前账号通知渠道和绑定关系,并隔离过期响应。 */
// loadNotificationBindingsCallback 是通知绑定加载回调。
const loadNotificationBindings = useCallback(async (accountId: string): Promise<void> => {
// sequence 是通知绑定请求的递增代次。
const sequence = ++bindingsSequence.current;
bindingsAbort.current?.abort();
// controller 控制当前通知绑定请求的取消。
const controller = new AbortController();
bindingsAbort.current = controller;
setBindingsLoading(true);
setBindingsLoaded(false);
setBindingsDirty(false);
setBindingsLoadError('');
// bindingResults 保存通知渠道和账号绑定的并行结果。
const [channelsResult, bindingsResult] = await Promise.allSettled([
getNotificationChannels({ signal: controller.signal }),
getAccountBindings(accountId, { signal: controller.signal }),
]);
if (!isCurrentAccountRequest(sequence, bindingsSequence.current, accountId, accountId)) return;
if (channelsResult.status === 'fulfilled') setNotifChannels(channelsResult.value.data || []);
else { setNotifChannels([]); setBindingsLoadError('通知渠道列表加载失败,请重试'); }
if (bindingsResult.status === 'fulfilled') { setSelectedChannelIds(bindingsResult.value || []); setBindingsLoaded(true); }
else { setSelectedChannelIds([]); setBindingsLoadError('通知绑定加载失败;本次保存不会修改现有绑定'); }
setBindingsLoading(false);
}, []);
/** 切换一个通知渠道绑定。 */
// toggleNotificationChannelCallback 是通知渠道切换回调。
const toggleNotificationChannel = useCallback((channelId: number) => {
setSelectedChannelIds(current => current.includes(channelId) ? current.filter(id => id !== channelId) : [...current, channelId]);
setBindingsDirty(true);
}, []);
/** 打开账号编辑弹窗并并行读取绑定和长登录状态。 */
// openEditModalCallback 是账号编辑弹窗打开回调。
const openEditModal = useCallback(async (account: AccountDetail): Promise<void> => {
// longLoginRequest 是当前长登录读取请求代次。
const longLoginRequest = ++longLoginSequence.current;
longLoginAbort.current?.abort();
// longLoginController 控制当前长登录读取请求的取消。
const longLoginController = new AbortController();
longLoginAbort.current = longLoginController;
passwordGeneration.current += 1;
passwordAccount.current = account.id;
passwordAbort.current?.abort();
clearPasswordTimer();
setPasswordLoginView({ sessionId: '', status: 'idle', message: '', qrCodeUrl: '' });
setEditingAccount(account);
setEditForm({ remark: account.remark || account.note || '', cookie: account.cookie || account.value || '', auto_confirm: account.auto_confirm || false, pause_duration: account.pause_duration || 0, username: account.username || '', login_password: account.login_password || '', show_browser: account.show_browser || false, showLoginPassword: false, clear_password: false });
setActiveModal('edit');
setLongLogin({ loading: true, saving: false, canOpen: false, enabled: false, error: '' });
// longLoginResult 保存长登录设置读取结果。
const [, longLoginResult] = await Promise.allSettled([loadNotificationBindings(account.id), getLongLoginSettings(account.id, { signal: longLoginController.signal })]);
if (longLoginRequest !== longLoginSequence.current) return;
if (longLoginResult.status === 'fulfilled') setLongLogin({ loading: false, saving: false, canOpen: longLoginResult.value.can_open_long_login, enabled: longLoginResult.value.enabled, error: '' });
else setLongLogin({ loading: false, saving: false, canOpen: false, enabled: false, error: '无法读取闲鱼保存登录信息状态' });
}, [clearPasswordTimer, loadNotificationBindings, setActiveModal, setEditForm, setEditingAccount]);
/** 切换官方长登录设置。 */
// handleLongLoginToggleCallback 是长登录设置切换回调。
const handleLongLoginToggle = useCallback(async (): Promise<void> => {
if (!editingAccount || longLogin.loading || longLogin.saving || !longLogin.canOpen) return;
// enabled 是本次准备提交的长登录开关值。
const enabled = !longLogin.enabled;
setLongLogin(current => ({ ...current, saving: true, error: '' }));
try {
// result 保存长登录设置接口返回值。
const result = await setLongLoginSettings(editingAccount.id, enabled);
setLongLogin({ loading: false, saving: false, canOpen: result.can_open_long_login, enabled: result.enabled, error: '' });
} catch (error) {
// error 保存长登录设置保存失败原因。
setLongLogin(current => ({ ...current, saving: false, error: error instanceof Error ? error.message : '保存登录信息设置失败' }));
}
}, [editingAccount, longLogin]);
/** 打开 AI 设置并隔离过期账号响应。 */
// openAIModalCallback 是 AI 设置弹窗打开回调。
const openAIModal = useCallback(async (account: AccountDetail): Promise<void> => {
// sequence 是 AI 设置请求的递增代次。
const sequence = ++aiSequence.current;
aiAbort.current?.abort();
// controller 控制当前 AI 设置请求的取消。
const controller = new AbortController();
aiAbort.current = controller;
setEditingAccount(account);
setActiveModal('ai-settings');
setSaving(true);
try {
// settings 保存当前账号的 AI 设置。
const settings = await getAccountAISettings(account.id, { signal: controller.signal });
if (!isCurrentAccountRequest(sequence, aiSequence.current, account.id, account.id)) return;
setAiSettings({ ai_enabled: settings.ai_enabled ?? false, max_discount_percent: settings.max_discount_percent ?? 10, max_discount_amount: settings.max_discount_amount ?? 100, max_bargain_rounds: settings.max_bargain_rounds ?? 3, custom_prompts: settings.custom_prompts ?? '' });
} catch (error) {
// error 保存 AI 设置读取失败原因。
if (isCurrentAccountRequest(sequence, aiSequence.current, account.id, account.id)) console.error('加载 AI 设置失败:', error);
} finally {
if (isCurrentAccountRequest(sequence, aiSequence.current, account.id, account.id)) setSaving(false);
}
}, [setActiveModal, setEditingAccount]);
/** 保存 AI 设置并刷新账号列表。 */
// handleSaveAISettingsCallback 是 AI 设置保存回调。
const handleSaveAISettings = useCallback(async (): Promise<void> => {
if (!editingAccount || saving) return;
setSaving(true);
try {
await updateAccountAISettings(editingAccount.id, aiSettings);
setActiveModal(null);
await loadAccounts();
} catch (error) {
// error 保存 AI 设置保存失败原因。
console.error('更新 AI 设置失败:', error);
} finally { setSaving(false); }
}, [aiSettings, editingAccount, loadAccounts, saving, setActiveModal]);
/** 保存账号编辑表单和通知绑定。 */
// handleSaveEditCallback 是账号编辑表单保存回调。
const handleSaveEdit = useCallback(async (): Promise<void> => {
if (!editingAccount || saving) return;
setSaving(true);
try {
// payload 保存需要提交的账号编辑补丁。
const payload: Parameters<typeof updateAccountSettings>[1] = {};
if (editForm.remark !== (editingAccount.remark || editingAccount.note || '')) payload.remark = editForm.remark;
if (editForm.cookie && editForm.cookie !== (editingAccount.cookie || editingAccount.value || '')) payload.cookie = editForm.cookie;
if (editForm.auto_confirm !== editingAccount.auto_confirm) payload.auto_confirm = editForm.auto_confirm;
if (shouldUpdateAccountPause(editForm.pause_duration, editingAccount)) payload.pause_duration = editForm.pause_duration;
// loginInfo 保存登录字段变更补丁。
const loginInfo = buildAccountLoginInfoUpdate(editingAccount, editForm);
if (loginInfo) Object.assign(payload, loginInfo);
if (shouldSaveNotificationBindings(bindingsLoaded, bindingsDirty)) payload.channel_ids = selectedChannelIds;
if (Object.keys(payload).length > 0) await updateAccountSettings(editingAccount.id, payload);
setActiveModal(null);
await loadAccounts();
} catch (error) {
// error 保存账号编辑保存失败原因。
console.error('更新账号失败:', error);
} finally { setSaving(false); }
}, [bindingsDirty, bindingsLoaded, editForm, editingAccount, loadAccounts, selectedChannelIds, saving, setActiveModal]);
/** 按当前暂停时长重新暂停账号。 */
// handleRestartPauseCallback 是重新暂停账号回调。
const handleRestartPause = useCallback(async (): Promise<void> => {
if (!editingAccount || editForm.pause_duration <= 0 || saving) return;
setSaving(true);
try {
// result 保存重新暂停接口返回的账号状态。
const result = await updateAccountPauseDuration(editingAccount.id, editForm.pause_duration);
setEditingAccount(current => current ? { ...current, pause_duration: editForm.pause_duration, paused: result?.paused === true, paused_until: Number(result?.paused_until || 0) } : current);
await loadAccounts();
} catch (error) { console.error('重新暂停失败:', error); }
finally { setSaving(false); }
}, [editForm.pause_duration, editingAccount, loadAccounts, saving, setEditingAccount]);
/** 按账号和请求代次轮询密码登录状态。 */
// pollPasswordLoginCallback 是密码登录状态轮询回调。
const pollPasswordLogin = useCallback(async (sessionId: string, generation: number, accountId: string): Promise<void> => {
passwordAbort.current?.abort();
// controller 控制当前密码登录状态查询的取消。
const controller = new AbortController();
passwordAbort.current = controller;
try {
// result 保存后端返回的密码登录状态。
const result = await checkPasswordLoginStatus(sessionId, controller.signal);
if (!isCurrentAccountRequest(generation, passwordGeneration.current, accountId, passwordAccount.current)) return;
// nextView 是面向编辑弹窗展示的状态。
const nextView = { ...passwordLoginViewFromStatus(result), sessionId };
if (result.status === 'success') {
clearPasswordTimer();
setPasswordLoginView(nextView);
setEditForm(current => ({ ...current, login_password: '', showLoginPassword: false }));
await loadAccounts();
return;
}
if (result.status === 'processing' || result.status === 'verification_required') {
setPasswordLoginView(nextView);
clearPasswordTimer();
passwordTimer.current = window.setTimeout(() => void pollPasswordLogin(sessionId, generation, accountId), 1500);
return;
}
clearPasswordTimer();
setPasswordLoginView(nextView);
} catch (error) {
// error 保存密码登录状态查询失败原因。
if (!isCurrentAccountRequest(generation, passwordGeneration.current, accountId, passwordAccount.current)) return;
clearPasswordTimer();
setPasswordLoginView({ sessionId, status: 'failed', message: error instanceof Error ? error.message : '查询密码登录状态失败', qrCodeUrl: '' });
}
}, [clearPasswordTimer, loadAccounts, setEditForm]);
/** 启动账号密码登录刷新授权。 */
// handlePasswordLoginCallback 是密码登录启动回调。
const handlePasswordLogin = useCallback(async (): Promise<void> => {
if (!editingAccount) return;
// accountName 是本次登录使用的闲鱼账号名。
const accountName = editForm.username.trim();
if (!accountName || !editForm.login_password) return;
clearPasswordTimer();
passwordAbort.current?.abort();
// generation 是本次密码登录请求的递增代次。
const generation = ++passwordGeneration.current;
passwordAccount.current = editingAccount.id;
// startController 控制密码登录启动请求的取消。
const startController = new AbortController();
passwordAbort.current = startController;
setPasswordLoginView({ sessionId: '', status: 'processing', message: '正在启动密码登录…', qrCodeUrl: '' });
try {
// result 保存密码登录启动接口返回值。
const result = await passwordLogin({ account_id: editingAccount.id, account: accountName, password: editForm.login_password, show_browser: editForm.show_browser }, { signal: startController.signal });
if (!isCurrentAccountRequest(generation, passwordGeneration.current, editingAccount.id, passwordAccount.current)) return;
if (!result.success || !result.session_id) throw new Error(result.message || '无法启动密码登录');
setPasswordLoginView({ sessionId: result.session_id, status: 'processing', message: result.message || '登录处理中', qrCodeUrl: '' });
await pollPasswordLogin(result.session_id, generation, editingAccount.id);
} catch (error) {
// error 保存密码登录启动失败原因。
if (!isCurrentAccountRequest(generation, passwordGeneration.current, editingAccount.id, passwordAccount.current)) return;
setPasswordLoginView({ sessionId: '', status: 'failed', message: error instanceof Error ? error.message : '启动密码登录失败', qrCodeUrl: '' });
}
}, [clearPasswordTimer, editForm.login_password, editForm.show_browser, editForm.username, editingAccount, pollPasswordLogin]);
/** 取消当前密码登录会话。 */
// handleCancelPasswordLoginCallback 是密码登录取消回调。
const handleCancelPasswordLogin = useCallback(async (): Promise<void> => {
// sessionId 是当前待取消的密码登录会话。
const sessionId = passwordLoginView.sessionId;
passwordGeneration.current += 1;
passwordAccount.current = '';
passwordAbort.current?.abort();
clearPasswordTimer();
if (sessionId) await cancelPasswordLogin(sessionId).catch(() => undefined);
setPasswordLoginView({ sessionId: '', status: 'idle', message: '', qrCodeUrl: '' });
}, [clearPasswordTimer, passwordLoginView.sessionId]);
/** 关闭编辑弹窗并取消未完成的子模块请求。 */
// closeEditModalCallback 是编辑弹窗关闭回调。
const closeEditModal = useCallback(async (): Promise<void> => {
bindingsAbort.current?.abort();
longLoginSequence.current += 1;
longLoginAbort.current?.abort();
aiAbort.current?.abort();
if (passwordLoginView.status === 'processing' || passwordLoginView.status === 'verification_required') await handleCancelPasswordLogin();
setActiveModal(null);
}, [handleCancelPasswordLogin, passwordLoginView.status, setActiveModal]);
/** 关闭 AI 设置弹窗并取消读取请求。 */
// closeAIModalCallback 是 AI 设置弹窗关闭回调。
const closeAIModal = useCallback(() => {
aiSequence.current += 1;
aiAbort.current?.abort();
setActiveModal(null);
}, [setActiveModal]);
// cleanupSubmodulesEffect 在 Hook 卸载时取消所有子模块请求。
useEffect(() => () => {
bindingsAbort.current?.abort();
longLoginAbort.current?.abort();
aiAbort.current?.abort();
passwordAbort.current?.abort();
clearPasswordTimer();
}, [clearPasswordTimer]);
return {
longLogin, notifChannels, selectedChannelIds, bindingsLoaded, bindingsLoading, bindingsDirty, bindingsLoadError,
aiSettings, saving, passwordLoginView, setAiSettings, setBindingsDirty, setEditForm, openEditModal,
closeEditModal, openAIModal, closeAIModal, loadNotificationBindings, toggleNotificationChannel,
handleLongLoginToggle, handleSaveAISettings, handleSaveEdit, handleRestartPause, handlePasswordLogin,
handleCancelPasswordLogin,
};
};
+80 -362
View File
@@ -1,71 +1,65 @@
import React, { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { AccountDetail, AIReplySettings, NotificationChannel } from '../types';
import { AccountDetail } from '../types';
import {
updateAccountStatus,
deleteAccount,
generateQRLogin,
checkQRLoginStatus,
completeQRVerification,
updateAccountPauseDuration,
refreshAccountProfile,
updateAccountSettings,
passwordLogin,
checkPasswordLoginStatus,
cancelPasswordLogin,
updateAccountAISettings,
getAccountAISettings,
getNotificationChannels,
getAccountBindings,
getLongLoginSettings,
setLongLoginSettings,
} from '../app/features/accounts/api';
import {
Power, Edit2, Trash2, QrCode, X, Check, Loader2,
RefreshCw, Save, User, Clock, MessageCircle,
Bot, Settings, AlertCircle, CalendarClock, Sparkles
} from 'lucide-react';
import { buildAccountLoginInfoUpdate, isCurrentAccountRequest, passwordLoginViewFromStatus, shouldUpdateAccountPause } from '../app/features/accounts/state';
import { shouldSaveNotificationBindings } from './accountBindings';
import { createLatestRequestGate, createQRLoginPoller } from './qrPolling';
import { RiskVerificationPanel } from './RiskVerificationPanel';
import { SquareQRCode } from './SquareQRCode';
import AccountAutomationModal from './AccountAutomationModal';
import { AccountEditModal } from '../app/features/accounts/components/AccountEditModal';
import { useAccountsData } from '../app/features/accounts/hooks';
import { useAccountSubmodules, type AccountModalType } from '../app/features/accounts/submoduleHooks';
import { accountRuntimePresentation } from '../app/features/accounts/runtime';
import type { AccountEditForm, LongLoginState, PasswordLoginView } from '../app/features/accounts/types';
type ModalType = 'edit' | 'ai-settings' | null;
import type { AccountEditForm } from '../app/features/accounts/types';
const AccountList: React.FC = () => {
// accountData 保存账号列表及其加载控制器。
const { accounts, setAccounts, loading, loadAccounts } = useAccountsData();
// accountSearch 保存列表过滤关键词。
const [accountSearch, setAccountSearch] = useState('');
// refreshingProfileId 保存正在刷新资料的账号 ID。
const [refreshingProfileId, setRefreshingProfileId] = useState<string>('');
// deletingAccountId 保存正在删除的账号 ID。
const [deletingAccountId, setDeletingAccountId] = useState<string>('');
// deleteDialogAccount 保存待确认删除的账号。
const [deleteDialogAccount, setDeleteDialogAccount] = useState<AccountDetail | null>(null);
// deleteError 保存删除失败提示。
const [deleteError, setDeleteError] = useState('');
// showQRModal 表示二维码登录弹窗是否打开。
const [showQRModal, setShowQRModal] = useState(false);
// qrCodeUrl 保存当前二维码登录地址。
const [qrCodeUrl, setQrCodeUrl] = useState<string>('');
// qrStatus 保存二维码登录流程状态。
const [qrStatus, setQrStatus] = useState<string>('pending');
// qrErrorMessage 保存二维码登录错误说明。
const [qrErrorMessage, setQrErrorMessage] = useState<string>('');
// verificationScreenshot 保存风控验证截图地址。
const [verificationScreenshot, setVerificationScreenshot] = useState<string>('');
// faceQrUrl 保存人脸验证二维码地址。
const [faceQrUrl, setFaceQrUrl] = useState<string>('');
// qrReauthTarget 保存需要重新授权的目标账号。
const [qrReauthTarget, setQrReauthTarget] = useState<AccountDetail | null>(null);
const [activeModal, setActiveModal] = useState<ModalType>(null);
// activeModal 保存当前打开的账号配置弹窗。
const [activeModal, setActiveModal] = useState<AccountModalType>(null);
// editingAccount 保存当前编辑账号。
const [editingAccount, setEditingAccount] = useState<AccountDetail | null>(null);
// taskAccount 保存当前打开自动化任务弹窗的账号。
const [taskAccount, setTaskAccount] = useState<AccountDetail | null>(null);
const [longLogin, setLongLogin] = useState<LongLoginState>({ loading: false, saving: false, canOpen: false, enabled: false, error: '' });
// 通知渠道绑定(编辑弹窗用)
const [notifChannels, setNotifChannels] = useState<NotificationChannel[]>([]);
const [selectedChannelIds, setSelectedChannelIds] = useState<number[]>([]);
const [bindingsLoaded, setBindingsLoaded] = useState(false);
const [bindingsLoading, setBindingsLoading] = useState(false);
const [bindingsDirty, setBindingsDirty] = useState(false);
const [bindingsLoadError, setBindingsLoadError] = useState('');
// 编辑表单状态
// 编辑表单状态。
// editForm 保存编辑弹窗中的账号草稿。
const [editForm, setEditForm] = useState<AccountEditForm>({
remark: '',
cookie: '',
@@ -78,37 +72,58 @@ const AccountList: React.FC = () => {
clear_password: false,
});
// AI设置表单状态
const [aiSettings, setAiSettings] = useState<AIReplySettings>({
ai_enabled: false,
max_discount_percent: 10,
max_discount_amount: 100,
max_bargain_rounds: 3,
custom_prompts: '',
// accountSubmodules 集中管理编辑弹窗的长登录、通知绑定、AI 和密码登录状态。
const accountSubmodules = useAccountSubmodules({
editingAccount,
setEditingAccount,
setActiveModal,
editForm,
setEditForm,
loadAccounts,
});
const [saving, setSaving] = useState(false);
const [passwordLoginView, setPasswordLoginView] = useState<PasswordLoginView>({ sessionId: '', status: 'idle', message: '', qrCodeUrl: '' });
// submoduleHandlers 保存编辑弹窗子模块的状态和事件处理函数。
const {
longLogin,
notifChannels,
selectedChannelIds,
bindingsLoaded,
bindingsLoading,
bindingsLoadError,
aiSettings,
saving,
passwordLoginView,
setAiSettings,
setBindingsDirty,
openEditModal,
closeEditModal,
openAIModal,
closeAIModal,
loadNotificationBindings,
toggleNotificationChannel,
handleLongLoginToggle,
handleSaveAISettings,
handleSaveEdit,
handleRestartPause,
handlePasswordLogin,
handleCancelPasswordLogin,
} = accountSubmodules;
// qrPollerRef 保存二维码登录状态轮询器。
const qrPollerRef = useRef<ReturnType<typeof createQRLoginPoller> | null>(null);
// qrRequestGateRef 隔离过期的二维码生成请求。
const qrRequestGateRef = useRef<ReturnType<typeof createLatestRequestGate> | null>(null);
const bindingsLoadGateRef = useRef<ReturnType<typeof createLatestRequestGate> | null>(null);
const aiLoadGateRef = useRef<ReturnType<typeof createLatestRequestGate> | null>(null);
const bindingsLoadAbortRef = useRef<AbortController | null>(null);
const aiLoadAbortRef = useRef<AbortController | null>(null);
// qrGenerateAbortRef 保存二维码生成请求控制器。
const qrGenerateAbortRef = useRef<AbortController | null>(null);
const passwordPollAbortRef = useRef<AbortController | null>(null);
// qrCloseTimerRef 保存二维码弹窗延迟关闭定时器。
const qrCloseTimerRef = useRef<number | null>(null);
const passwordPollTimerRef = useRef<number | null>(null);
const passwordPollGenerationRef = useRef(0);
const passwordPollAccountRef = useRef('');
if (qrPollerRef.current === null) {
qrPollerRef.current = createQRLoginPoller();
}
if (qrRequestGateRef.current === null) {
qrRequestGateRef.current = createLatestRequestGate();
}
if (bindingsLoadGateRef.current === null) bindingsLoadGateRef.current = createLatestRequestGate();
if (aiLoadGateRef.current === null) aiLoadGateRef.current = createLatestRequestGate();
// clearQRCloseTimer 清理二维码弹窗延迟关闭定时器。
const clearQRCloseTimer = () => {
if (qrCloseTimerRef.current !== null) {
window.clearTimeout(qrCloseTimerRef.current);
@@ -116,17 +131,12 @@ const AccountList: React.FC = () => {
}
};
const clearPasswordPollTimer = () => {
if (passwordPollTimerRef.current !== null) {
window.clearTimeout(passwordPollTimerRef.current);
passwordPollTimerRef.current = null;
}
};
// stopQRPolling 停止二维码登录状态轮询。
const stopQRPolling = () => {
qrPollerRef.current?.stop();
};
// closeQRModal 关闭二维码登录弹窗并取消请求。
const closeQRModal = () => {
qrGenerateAbortRef.current?.abort();
qrRequestGateRef.current?.cancel();
@@ -135,6 +145,7 @@ const AccountList: React.FC = () => {
setShowQRModal(false);
};
// scheduleQRModalClose 在登录成功后延迟关闭二维码弹窗。
const scheduleQRModalClose = () => {
clearQRCloseTimer();
qrCloseTimerRef.current = window.setTimeout(() => {
@@ -149,36 +160,34 @@ const AccountList: React.FC = () => {
return () => {
stopQRPolling();
qrRequestGateRef.current?.cancel();
bindingsLoadGateRef.current?.cancel();
aiLoadGateRef.current?.cancel();
bindingsLoadAbortRef.current?.abort();
aiLoadAbortRef.current?.abort();
qrGenerateAbortRef.current?.abort();
passwordPollAbortRef.current?.abort();
clearQRCloseTimer();
passwordPollGenerationRef.current += 1;
clearPasswordPollTimer();
};
}, []);
// handleToggle 切换账号启用状态。
const handleToggle = async (id: string, currentStatus: boolean) => {
await updateAccountStatus(id, !currentStatus);
loadAccounts();
};
// openDeleteDialog 打开账号删除确认框。
const openDeleteDialog = (account: AccountDetail) => {
if (deletingAccountId) return;
setDeleteError('');
setDeleteDialogAccount(account);
};
// closeDeleteDialog 关闭账号删除确认框。
const closeDeleteDialog = () => {
if (deletingAccountId) return;
setDeleteError('');
setDeleteDialogAccount(null);
};
// confirmDeleteAccount 执行账号删除并刷新列表状态。
const confirmDeleteAccount = async () => {
// account 保存当前确认删除的账号。
const account = deleteDialogAccount;
if (!account || deletingAccountId) return;
setDeletingAccountId(account.id);
@@ -195,9 +204,11 @@ const AccountList: React.FC = () => {
}
};
// handleRefreshProfile 刷新账号资料并同步列表。
const handleRefreshProfile = async (account: AccountDetail) => {
setRefreshingProfileId(account.id);
try {
// res 保存资料刷新接口返回值。
const res = await refreshAccountProfile(account.id);
if (res?.profile_error) {
alert('资料刷新失败:' + res.profile_error);
@@ -210,308 +221,9 @@ const AccountList: React.FC = () => {
setRefreshingProfileId('');
}
};
const loadNotificationBindings = async (accountId: string) => {
const generation = bindingsLoadGateRef.current!.next();
bindingsLoadAbortRef.current?.abort();
const controller = new AbortController();
bindingsLoadAbortRef.current = controller;
setBindingsLoading(true);
setBindingsLoaded(false);
setBindingsDirty(false);
setBindingsLoadError('');
const [channelsResult, bindingsResult] = await Promise.allSettled([
getNotificationChannels({ signal: controller.signal }),
getAccountBindings(accountId, { signal: controller.signal }),
]);
if (!bindingsLoadGateRef.current?.isCurrent(generation)) return;
if (channelsResult.status === 'fulfilled') {
setNotifChannels(channelsResult.value.data || []);
} else {
setNotifChannels([]);
setBindingsLoadError('通知渠道列表加载失败,请重试');
}
if (bindingsResult.status === 'fulfilled') {
setSelectedChannelIds(bindingsResult.value || []);
setBindingsLoaded(true);
} else {
setSelectedChannelIds([]);
setBindingsLoadError('通知绑定加载失败;本次保存不会修改现有绑定');
}
setBindingsLoading(false);
};
// toggleNotificationChannel 使用函数式更新切换通知绑定,避免连续点击覆盖选择结果。
const toggleNotificationChannel = (channelId: number) => {
setSelectedChannelIds(current => current.includes(channelId)
? current.filter(id => id !== channelId)
: [...current, channelId]);
};
const openEditModal = async (account: AccountDetail) => {
passwordPollGenerationRef.current += 1;
passwordPollAccountRef.current = account.id;
passwordPollAbortRef.current?.abort();
clearPasswordPollTimer();
setPasswordLoginView({ sessionId: '', status: 'idle', message: '', qrCodeUrl: '' });
setEditingAccount(account);
setEditForm({
remark: account.remark || account.note || '',
cookie: account.cookie || account.value || '',
auto_confirm: account.auto_confirm || false,
pause_duration: account.pause_duration || 0,
username: account.username || '',
login_password: account.login_password || '',
show_browser: account.show_browser || false,
showLoginPassword: false,
clear_password: false,
});
setActiveModal('edit');
setLongLogin({ loading: true, saving: false, canOpen: false, enabled: false, error: '' });
const [, longLoginResult] = await Promise.allSettled([
loadNotificationBindings(account.id),
getLongLoginSettings(account.id),
]);
if (longLoginResult.status === 'fulfilled') {
setLongLogin({ loading: false, saving: false, canOpen: longLoginResult.value.can_open_long_login, enabled: longLoginResult.value.enabled, error: '' });
} else {
setLongLogin({ loading: false, saving: false, canOpen: false, enabled: false, error: '无法读取闲鱼保存登录信息状态' });
}
};
const handleLongLoginToggle = async () => {
if (!editingAccount || longLogin.loading || longLogin.saving || !longLogin.canOpen) return;
const enabled = !longLogin.enabled;
setLongLogin(current => ({ ...current, saving: true, error: '' }));
try {
const result = await setLongLoginSettings(editingAccount.id, enabled);
setLongLogin({ loading: false, saving: false, canOpen: result.can_open_long_login, enabled: result.enabled, error: '' });
} catch (error) {
setLongLogin(current => ({ ...current, saving: false, error: error instanceof Error ? error.message : '保存登录信息设置失败' }));
}
};
const openAIModal = async (account: AccountDetail) => {
const generation = aiLoadGateRef.current!.next();
aiLoadAbortRef.current?.abort();
const controller = new AbortController();
aiLoadAbortRef.current = controller;
setEditingAccount(account);
setActiveModal('ai-settings');
setSaving(true);
try {
const settings = await getAccountAISettings(account.id, { signal: controller.signal });
if (!aiLoadGateRef.current?.isCurrent(generation)) return;
setAiSettings({
ai_enabled: settings.ai_enabled ?? false,
max_discount_percent: settings.max_discount_percent ?? 10,
max_discount_amount: settings.max_discount_amount ?? 100,
max_bargain_rounds: settings.max_bargain_rounds ?? 3,
custom_prompts: settings.custom_prompts ?? '',
});
} catch (e) {
if (aiLoadGateRef.current?.isCurrent(generation)) console.error('Failed to load AI settings:', e);
} finally {
if (aiLoadGateRef.current?.isCurrent(generation)) setSaving(false);
}
};
const handleSaveEdit = async () => {
if (!editingAccount) return;
setSaving(true);
try {
const payload: Parameters<typeof updateAccountSettings>[1] = {};
// 更新备注
if (editForm.remark !== (editingAccount.remark || editingAccount.note || '')) {
payload.remark = editForm.remark;
}
// 更新Cookie
if (editForm.cookie && editForm.cookie !== (editingAccount.cookie || editingAccount.value || '')) {
payload.cookie = editForm.cookie;
}
// 更新自动确认
if (editForm.auto_confirm !== editingAccount.auto_confirm) {
payload.auto_confirm = editForm.auto_confirm;
}
// 更新暂停时长
if (shouldUpdateAccountPause(editForm.pause_duration, editingAccount)) {
payload.pause_duration = editForm.pause_duration;
}
// 更新登录信息
const loginInfo = buildAccountLoginInfoUpdate(editingAccount, editForm);
if (loginInfo) {
Object.assign(payload, loginInfo);
}
// 只有成功加载且用户确实改动后才覆盖,避免加载失败被误解释成解绑全部。
if (shouldSaveNotificationBindings(bindingsLoaded, bindingsDirty)) {
payload.channel_ids = selectedChannelIds;
}
if (Object.keys(payload).length > 0) await updateAccountSettings(editingAccount.id, payload);
setActiveModal(null);
loadAccounts();
} catch (error) {
console.error('更新账号失败:', error);
alert('更新失败,请重试');
} finally {
setSaving(false);
}
};
const handleRestartPause = async () => {
if (!editingAccount || editForm.pause_duration <= 0) return;
setSaving(true);
try {
const result = await updateAccountPauseDuration(editingAccount.id, editForm.pause_duration);
setEditingAccount({
...editingAccount,
pause_duration: editForm.pause_duration,
paused: result?.paused === true,
paused_until: Number(result?.paused_until || 0),
});
await loadAccounts();
} catch (error) {
alert(error instanceof Error ? error.message : '重新暂停失败');
} finally {
setSaving(false);
}
};
const handleSaveAISettings = async () => {
if (!editingAccount) return;
setSaving(true);
try {
await updateAccountAISettings(editingAccount.id, aiSettings);
setActiveModal(null);
loadAccounts();
} catch (error) {
console.error('更新AI设置失败:', error);
alert('更新失败,请重试');
} finally {
setSaving(false);
}
};
// pollPasswordLogin 轮询密码登录状态,并按账号和请求代次隔离过期响应。
const pollPasswordLogin = async (sessionId: string, generation: number, accountId: string) => {
passwordPollAbortRef.current?.abort();
// controller 取消上一轮仍未完成的密码登录状态请求。
const controller = new AbortController();
passwordPollAbortRef.current = controller;
try {
// result 是后端返回的当前密码登录状态。
const result = await checkPasswordLoginStatus(sessionId, controller.signal);
if (!isCurrentAccountRequest(generation, passwordPollGenerationRef.current, accountId, passwordPollAccountRef.current)) return;
// nextView 是统一转换后的密码登录展示状态。
const nextView = { ...passwordLoginViewFromStatus(result), sessionId };
if (result.status === 'success') {
clearPasswordPollTimer();
setPasswordLoginView(nextView);
setEditForm(current => ({ ...current, login_password: '', showLoginPassword: false }));
await loadAccounts();
return;
}
if (result.status === 'processing' || result.status === 'verification_required') {
setPasswordLoginView(nextView);
clearPasswordPollTimer();
passwordPollTimerRef.current = window.setTimeout(
// pollNextStatus 在短暂间隔后继续查询当前密码登录会话。
() => void pollPasswordLogin(sessionId, generation, accountId),
1500,
);
return;
}
clearPasswordPollTimer();
setPasswordLoginView(nextView);
} catch (error /* 密码登录状态查询错误 */) {
if (!isCurrentAccountRequest(generation, passwordPollGenerationRef.current, accountId, passwordPollAccountRef.current)) return;
clearPasswordPollTimer();
setPasswordLoginView({
sessionId,
status: 'failed',
message: error instanceof Error ? error.message : '查询密码登录状态失败',
qrCodeUrl: '',
});
}
};
const handlePasswordLogin = async () => {
if (!editingAccount) return;
const account = editForm.username.trim();
if (!account || !editForm.login_password) {
alert('请先填写登录账号和本次登录密码');
return;
}
clearPasswordPollTimer();
passwordPollAbortRef.current?.abort();
const generation = ++passwordPollGenerationRef.current;
passwordPollAccountRef.current = editingAccount.id;
setPasswordLoginView({ sessionId: '', status: 'processing', message: '正在启动密码登录…', qrCodeUrl: '' });
try {
const result = await passwordLogin({
account_id: editingAccount.id,
account,
password: editForm.login_password,
show_browser: editForm.show_browser,
});
if (!isCurrentAccountRequest(generation, passwordPollGenerationRef.current, editingAccount.id, passwordPollAccountRef.current)) return;
if (!result.success || !result.session_id) {
throw new Error(result.message || '无法启动密码登录');
}
setPasswordLoginView({ sessionId: result.session_id, status: 'processing', message: result.message || '登录处理中', qrCodeUrl: '' });
await pollPasswordLogin(result.session_id, generation, editingAccount.id);
} catch (error) {
if (!isCurrentAccountRequest(generation, passwordPollGenerationRef.current, editingAccount.id, passwordPollAccountRef.current)) return;
setPasswordLoginView({
sessionId: '',
status: 'failed',
message: error instanceof Error ? error.message : '启动密码登录失败',
qrCodeUrl: '',
});
}
};
const handleCancelPasswordLogin = async () => {
const sessionId = passwordLoginView.sessionId;
passwordPollGenerationRef.current += 1;
passwordPollAccountRef.current = '';
passwordPollAbortRef.current?.abort();
clearPasswordPollTimer();
if (sessionId) {
try {
await cancelPasswordLogin(sessionId);
} catch (error) {
console.error('取消密码登录失败', error);
}
}
setPasswordLoginView({ sessionId: '', status: 'idle', message: '', qrCodeUrl: '' });
};
const closeEditModal = async () => {
bindingsLoadGateRef.current?.cancel();
bindingsLoadAbortRef.current?.abort();
if (passwordLoginView.status === 'processing' || passwordLoginView.status === 'verification_required') {
await handleCancelPasswordLogin();
}
setActiveModal(null);
};
const closeAIModal = () => {
aiLoadGateRef.current?.cancel();
aiLoadAbortRef.current?.abort();
setActiveModal(null);
};
// completeAndPersistQRSession 完成二维码风控验证并持久化授权结果。
const completeAndPersistQRSession = async (sessionId: string, target?: AccountDetail | null) => {
// res 保存风控验证完成接口返回值。
const res = await completeQRVerification(sessionId, target?.id);
if (!res.success || !res.account_id) {
throw new Error(res.message || '保存扫码授权失败');
@@ -519,13 +231,17 @@ const AccountList: React.FC = () => {
return res.account_id;
};
// startQRLogin 启动二维码登录或账号重新授权流程。
const startQRLogin = async (target?: AccountDetail) => {
stopQRPolling();
qrGenerateAbortRef.current?.abort();
// controller 控制当前二维码生成请求的取消。
const controller = new AbortController();
qrGenerateAbortRef.current = controller;
// requestGeneration 标识当前二维码生成请求代次。
const requestGeneration = qrRequestGateRef.current!.next();
clearQRCloseTimer();
// targetAccount 保存当前二维码授权目标账号。
const targetAccount = target || null;
setQrReauthTarget(targetAccount);
setShowQRModal(true);
@@ -535,12 +251,14 @@ const AccountList: React.FC = () => {
setVerificationScreenshot('');
setFaceQrUrl('');
try {
// res 保存二维码生成接口返回值。
const res = await generateQRLogin({ signal: controller.signal });
if (!qrRequestGateRef.current?.isCurrent(requestGeneration)) return;
if (!res.success || !res.qr_code_url || !res.session_id) {
throw new Error(res.message || '闲鱼未返回可用的登录二维码');
}
if (res.success && res.qr_code_url && res.session_id) {
// generatedSessionID 保存后端生成的二维码登录会话。
const generatedSessionID = res.session_id;
setQrCodeUrl(res.qr_code_url);
setQrStatus('waiting');
+1
View File
@@ -177,6 +177,7 @@ describe('frontend navigation routing', () => {
const accounts = [
readFrontendFile('components/AccountList.tsx'),
readFrontendFile('app/features/accounts/components/AccountEditModal.tsx'),
readFrontendFile('app/features/accounts/submoduleHooks.ts'),
].join('\n');
expect(accounts).toContain('passwordLogin({');
expect(accounts).toContain('checkPasswordLoginStatus(sessionId, controller.signal)');
+18
View File
@@ -559,6 +559,24 @@ test('password login service uses upstream-compatible routes', async () => {
expect(fetchMock).toHaveBeenNthCalledWith(3, '/api/v1/password-login/cancel/sid', expect.objectContaining({ method: 'DELETE' }));
});
test('账号编辑子模块请求支持取消过期响应', async () => {
// fetchMock 是验证请求取消信号透传的测试替身。
const fetchMock = vi.fn()
.mockResolvedValueOnce(jsonResponse({ can_open_long_login: true, enabled: false }))
.mockResolvedValueOnce(jsonResponse({ ai_enabled: true }))
.mockResolvedValueOnce(jsonResponse({ success: true, session_id: 'sid' }));
vi.stubGlobal('fetch', fetchMock);
const controller = new AbortController();
await getLongLoginSettings('acc1', { signal: controller.signal });
await getAccountAISettings('acc1', { signal: controller.signal });
await passwordLogin({ account_id: 'acc1', account: 'u', password: 'p' }, { signal: controller.signal });
expect(fetchMock.mock.calls[0][1].signal).toBeInstanceOf(AbortSignal);
expect(fetchMock.mock.calls[1][1].signal).toBeInstanceOf(AbortSignal);
expect(fetchMock.mock.calls[2][1].signal).toBeInstanceOf(AbortSignal);
});
test('getShippingRules exposes buyer reviewed gift rules as automation rules', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse([{
id: 12,
+14 -14
View File
@@ -202,8 +202,8 @@ export const updateAccountAutoConfirm = async (id: string, autoConfirm: boolean)
return put(`/api/v1/accounts/${id}/auto-confirm`, { auto_confirm: autoConfirm });
};
export const updateAccountPauseDuration = async (id: string, pauseDuration: number): Promise<CookieSettingsResponse> => {
return put(`/api/v1/accounts/${id}/pause-duration`, { pause_duration: pauseDuration });
export const updateAccountPauseDuration = async (id: string, pauseDuration: number, options?: RequestControlOptions): Promise<CookieSettingsResponse> => {
return put(`/api/v1/accounts/${id}/pause-duration`, { pause_duration: pauseDuration }, options);
};
export const updateAccountCookie = async (id: string, value: string, loginMethod?: string): Promise<OperationResponse> => {
@@ -222,8 +222,8 @@ export interface AccountSettingsUpdate {
channel_ids?: number[];
}
export const updateAccountSettings = async (id: string, data: AccountSettingsUpdate): Promise<CookieSettingsResponse> => {
return put(`/api/v1/accounts/${id}/settings`, data);
export const updateAccountSettings = async (id: string, data: AccountSettingsUpdate, options?: RequestControlOptions): Promise<CookieSettingsResponse> => {
return put(`/api/v1/accounts/${id}/settings`, data, options);
};
export interface LongLoginSettings {
@@ -231,12 +231,12 @@ export interface LongLoginSettings {
enabled: boolean;
}
export const getLongLoginSettings = async (id: string): Promise<LongLoginSettings> => {
return get(`/api/v1/accounts/${id}/long-login`);
export const getLongLoginSettings = async (id: string, options?: RequestControlOptions): Promise<LongLoginSettings> => {
return get(`/api/v1/accounts/${id}/long-login`, undefined, options);
};
export const setLongLoginSettings = async (id: string, enabled: boolean): Promise<LongLoginSettings> => {
return put(`/api/v1/accounts/${id}/long-login`, { enabled });
export const setLongLoginSettings = async (id: string, enabled: boolean, options?: RequestControlOptions): Promise<LongLoginSettings> => {
return put(`/api/v1/accounts/${id}/long-login`, { enabled }, options);
};
export interface PasswordLoginStartResponse {
@@ -264,16 +264,16 @@ export const passwordLogin = async (data: {
account: string;
password: string;
show_browser?: boolean;
}): Promise<PasswordLoginStartResponse> => {
return post('/api/v1/password-login', data);
}, options?: RequestControlOptions): Promise<PasswordLoginStartResponse> => {
return post('/api/v1/password-login', data, options);
};
export const checkPasswordLoginStatus = async (sessionId: string, signal?: AbortSignal): Promise<PasswordLoginStatusResponse> => {
return get(`/api/v1/password-login/check/${sessionId}`, undefined, { signal, timeoutMs: 10_000 });
};
export const cancelPasswordLogin = async (sessionId: string): Promise<ApiResponse> => {
return del(`/api/v1/password-login/cancel/${sessionId}`);
export const cancelPasswordLogin = async (sessionId: string, options?: RequestControlOptions): Promise<ApiResponse> => {
return del(`/api/v1/password-login/cancel/${sessionId}`, undefined, options);
};
export const refreshAccountProfile = async (id: string): Promise<CookieProfileResponse> => {
@@ -896,7 +896,7 @@ export const getAccountAISettings = async (cookieId: string, options?: RequestCo
return get(`/api/v1/settings/ai-reply/${cookieId}`, undefined, options);
}
export const updateAccountAISettings = async (cookieId: string, settings: Partial<AIReplySettings>): Promise<OperationResponse> => {
export const updateAccountAISettings = async (cookieId: string, settings: Partial<AIReplySettings>, options?: RequestControlOptions): Promise<OperationResponse> => {
const payload = {
ai_enabled: settings.ai_enabled ?? false,
max_discount_percent: settings.max_discount_percent ?? 10,
@@ -904,7 +904,7 @@ export const updateAccountAISettings = async (cookieId: string, settings: Partia
max_bargain_rounds: settings.max_bargain_rounds ?? 3,
custom_prompts: settings.custom_prompts ?? ''
};
return put(`/api/v1/settings/ai-reply/${cookieId}`, payload);
return put(`/api/v1/settings/ai-reply/${cookieId}`, payload, options);
}
export const fetchAIModels = async (baseUrl: string, apiKey: string = '', options?: RequestControlOptions): Promise<string[]> => {
@@ -1,20 +0,0 @@
import{j as e,r,c as Es,b as Me,d as cr}from"./react-vendor-C_od1ZSF.js";import{L as dr,U as wa,M as Ns,C as Ts,B as ka,S as Ca,Z as _s,a as It,b as Ds,G as Us,c as $s,d as Ms,e as xr,f as Sa,g as ht,A as Ws,D as mr,P as Aa,h as zt,E as Ra,T as ur,i as pr,j as Ce,X as Oe,k as hr,l as gr,m as qs,n as La,o as ct,p as at,q as Ia,K as br,r as yt,s as pt,Q as ns,t as vt,u as Ct,v as qt,R as He,w as Oa,x as fr,y as st,z as Rt,F as Bt,H as dt,I as Gs,J as St,N as yr,O as jr,V as vr,W as Pa,Y as Ea,_ as Ta,$ as Nr,a0 as _r,a1 as is,a2 as Gt,a3 as ws,a4 as wr,a5 as kr,a6 as ks,a7 as Js,a8 as Cr,a9 as Sr,aa as Ft,ab as Qs,ac as Xt,ad as Da,ae as Ar,af as Rr,ag as rs,ah as $a,ai as Lr,aj as Ir,ak as Or,al as Pr,am as Er,an as Tr,ao as Vs}from"./icons-vendor-i_74xDZy.js";import{R as es,B as Dr,X as Ks,Y as Hs,T as ts,a as $r,C as Cs,A as Mr,b as qr,c as Br,P as Zs,d as Ys,L as Fr}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 zr=({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"})})}),Ss=({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(Ds,{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(ct,{className:"w-4 h-4"}),ge?"保存中...":"保存"]})]})})]})}),document.body)]})},Bn=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],Fn=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(zn)}},zn=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||"")}},Un=t=>(t==null?void 0:t.results.filter(Wn))||[],Wn=t=>!t.success,Gn=(t,s)=>t!==null&&!s,Jn=t=>{if(!t)return"请选择订单文件";const s=t.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(s)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},jt=(t,s)=>t===s,Qn=(t,s)=>t instanceof Error&&t.message?t.message:s,Vn=({filter:t,onFilterChange:s,accountFilter:a,onAccountFilterChange:l,accounts:n,accountName:x,searchText:p,onSearchChange:f})=>{const u=g=>s(g.currentTarget.dataset.status||"all"),j=g=>l(g.target.value),m=g=>f(g.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:Bn.map(g=>e.jsx("button",{"data-status":g.key,onClick:u,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${t===g.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:g.label},g.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(vt,{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(g=>e.jsx("option",{value:g.id,children:x(g.id)},g.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(Rt,{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"})]})]})]})},Kn=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:C,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(Bt,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:D,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(dt,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"追加卡密"]})]})]})}),document.body):null},ei=({type:t})=>{switch(t){case"text":return e.jsx(Ea,{className:"w-5 h-5 text-blue-500"});case"image":return e.jsx(Pa,{className:"w-5 h-5 text-purple-500"});case"api":return e.jsx(vr,{className:"w-5 h-5 text-blue-500"});default:return e.jsx(Ts,{className:"w-5 h-5 text-gray-500"})}},ti=(t,s,a)=>{const l=a.trim().toLocaleLowerCase();return t.filter(n=>(!s||n.type===s)&&(!l||n.name.toLocaleLowerCase().includes(l)))},Ya=t=>t.split(`
`).map(s=>s.trim()).filter(Boolean),si=(t,s,a)=>!!(t&&Ya(s).length>0&&!a),wt=(t,s,a,l)=>t===s&&a===l,ai=()=>{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 Fs({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}},ri=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),[g,v]=r.useState(!1),[C,D]=r.useState(""),[_,I]=r.useState(""),[L,W]=r.useState(null),[K,X]=r.useState(""),y=r.useRef(0),N=r.useRef(null),F=r.useRef(""),O=r.useMemo(()=>Ya(_),[_]),z=r.useCallback(()=>{var k;p("create"),u(null),m(null),D((k=s[0])!=null&&k.id?String(s[0].id):""),I(""),W(null),X(""),n(!0)},[s]),d=r.useCallback(()=>{var k;y.current+=1,(k=N.current)==null||k.abort(),v(!1),n(!1)},[]),q=r.useCallback(async()=>{var R;if(!f||g)return;const k=++y.current;(R=N.current)==null||R.abort();const $=new AbortController;N.current=$,v(!0),m(null);try{const G=await Ml(f,{signal:$.signal});if(!wt(k,y.current,"",""))return;m(G),G.created>0&&await a()}catch(G){if(!wt(k,y.current,"",""))return;m({error:(G==null?void 0:G.message)||"上传失败"})}finally{wt(k,y.current,"","")&&v(!1)}},[g,f,a]),Z=r.useCallback(async()=>{var G;if(!si(C,_,g))return;const k=C,$=++y.current;F.current=k,(G=N.current)==null||G.abort();const R=new AbortController;N.current=R,v(!0),W(null),X("");try{const J=await ql(k,_,{signal:R.signal});if(!wt($,y.current,k,C))return;W({added:J.added}),I(""),await a()}catch(J){if(!wt($,y.current,k,C))return;X((J==null?void 0:J.message)||"追加失败")}finally{wt($,y.current,k,C)&&v(!1)}},[_,C,g,a]),E=r.useCallback(async()=>{await q()},[q]),h=r.useCallback(async()=>{F.current&&C!==F.current||await Z()},[C,Z]);return{showBatchModal:l,setShowBatchModal:n,batchTab:x,setBatchTab:p,batchFile:f,setBatchFile:u,batchResult:j,batchBusy:g,appendTargetId:C,setAppendTargetId:D,appendContent:_,setAppendContent:I,appendResult:L,appendError:K,appendPreview:O,openBatchModal:z,closeBatchModal:d,handleBatchCreate:q,handleBatchAppend:Z,handleRetryBatchCreate:E,handleRetryBatchAppend:h}},pa=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),li=()=>{const{cards:t,loadCards:s}=ai(),[a,l]=r.useState(!1),[n,x]=r.useState(!1),[p,f]=r.useState(null),[u,j]=r.useState({}),[m,g]=r.useState(pa),[v,C]=r.useState(""),[D,_]=r.useState(""),I=r.useMemo(()=>t.filter(d=>d.type==="data"),[t]),L=ri({dataCards:I,loadCards:s}),W=d=>{var q,Z,E,h,k;f(d),j({id:d.id,name:d.name||"",type:d.type||"text",api_url:((q=d.api_config)==null?void 0:q.url)||"",api_method:((Z=d.api_config)==null?void 0:Z.method)||"GET",api_timeout:((E=d.api_config)==null?void 0:E.timeout)||10,api_headers:((h=d.api_config)==null?void 0:h.headers)||"",api_params:((k=d.api_config)==null?void 0:k.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,q,Z,E,h,k,$,R;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:(q=u.description)==null?void 0:q.trim(),delay_seconds:u.delay_seconds||0,enabled:u.enabled??!0};u.type==="api"?G.api_config={url:((Z=u.api_url)==null?void 0:Z.trim())||"",method:u.api_method,timeout:u.api_timeout||10,headers:((E=u.api_headers)==null?void 0:E.trim())||void 0,params:((h=u.api_params)==null?void 0:h.trim())||void 0}:u.type==="text"?G.text_content=((k=u.text_content)==null?void 0:k.trim())||"":u.type==="data"?G.data_content=(($=u.data_content)==null?void 0:$.trim())||"":u.type==="image"&&(G.image_url=((R=u.image_url)==null?void 0:R.trim())||""),await la(p.id,G),l(!1),await s()}catch(G){console.error("更新卡密失败:",G),alert("更新失败,请重试")}}},X=async d=>{if(confirm("确认删除该卡密吗?"))try{await $l(d),await s()}catch(q){console.error("删除卡密失败:",q),alert("删除失败,请重试")}},y=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($=>$.map(R=>`"${String(R).replace(/"/g,'""')}"`).join(",")).join(`
`),E=new Blob(["\uFEFF"+Z],{type:"text/csv;charset=utf-8"}),h=URL.createObjectURL(E),k=document.createElement("a");k.href=h,k.download="卡密组批量导入模板.csv",document.body.appendChild(k),k.click(),k.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:L.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(Bt,{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(dt,{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(Ta,{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=>C(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(Rt,{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:D,onChange:d=>_(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:["显示 ",O.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:O.map(d=>{let q="";return d.type==="data"&&d.data_content?q=`库存: ${d.data_content.split(`
`).filter(E=>E.trim()).length} 条`:d.type==="text"&&d.text_content?q=d.text_content:d.type==="api"&&d.api_config?q=d.api_config.url:d.type==="image"&&d.image_url&&(q="图片链接"),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(ei,{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:()=>F(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(Nr,{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:q,children:q})}),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:()=>N(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(St,{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)})})]})}),O.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(Aa,{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(ct,{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=>g({...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:()=>g({...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(Ts,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>g({...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(Ea,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>g({...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=>g({...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=>g({...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=>g({...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=>g({...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=>g({...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=>g({...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:y,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(dt,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),e.jsx(Xn,{dataCards:I,downloadCardTemplate:z,...L})]})},ha="ydisks-amap-js-api",ni="c9b68d4ce9a2a97f22a4a439404488ca";let Et=null;const ii=()=>ni,oi=()=>window.AMap?Promise.resolve(window.AMap):Et||(Et=new Promise((t,s)=>{const a=document.getElementById(ha),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=ha,l.async=!0,l.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(ii())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,l.onerror=()=>{n(),s(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},a||document.head.appendChild(l)}).catch(t=>{throw Et=null,t}),Et),as=t=>Number.isFinite(t)&&t!==0,ci=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||!as(s)||!as(a)||s<-180||s>180||a<-90||a>90?null:l},di=async(t,s)=>{if(!as(t)||!as(s)||t<-180||t>180||s<-90||s>90)throw new Error("经纬度无效");const a=await oi();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(ci).filter(m=>m!==null);l(u)})})},xi=t=>t.find(s=>s.status==="running"||s.status==="canceling"),Os=t=>t==="running"||t==="canceling",mi=t=>!!(t!=null&&t.previ Line truncated
`),Re=new Blob(["\uFEFF"+ie],{type:"text/csv;charset=utf-8"}),tt=URL.createObjectURL(Re),Ge=document.createElement("a");Ge.href=tt,Ge.download="批量铺货模板.csv",document.body.appendChild(Ge),Ge.click(),Ge.remove(),URL.revokeObjectURL(tt)},ee=()=>{$(c=>({...c,cookie_id:f||c.cookie_id})),W(!0)},ne=()=>{G(c=>({...c,cookie_id:f||c.cookie_id})),X(!0)},le=async c=>{if(!(c?f:R.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");N(!0),navigator.geolocation.getCurrentPosition(async ie=>{try{const Re=await di(ie.coords.longitude,ie.coords.latitude);if(!Re.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");c?(Te(Re),Ue(Re[0])):(O(Re),d(Re[0]))}catch(Re){alert((Re==null?void 0:Re.message)||"获取发货地失败")}finally{N(!1)}},ie=>{N(!1),alert(ie.code===ie.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},ve=c=>l.filter(V=>V.cookie_id===c.cookie_id&&V.item_id===c.item_id).length>0?l.filter(V=>V.cookie_id===c.cookie_id&&V.item_id===c.item_id):l.filter(V=>V.cookie_id===c.cookie_id&&!V.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 V=We.get(c),ie=(V==null?void 0:V.remark)||(V==null?void 0:V.nickname);return ie?`${ie} · ${c.slice(0,6)}`:`账号 ${c.slice(0,8)}`},Ne=c=>{const V=We.get(c);return(V==null?void 0:V.remark)||(V==null?void 0:V.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(_r,{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(vt,{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:g||!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 ${g?"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(dt,{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(is,{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(Gt,{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 V=ve(c),ie=V.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relative flex fl Line truncated
@@ -0,0 +1,20 @@
import{j as e,r,c as Is,b as Oe,d as ir}from"./react-vendor-C_od1ZSF.js";import{L as or,U as Na,M as ys,C as Os,B as va,S as _a,Z as js,a as Rt,b as Ps,G as Bs,c as Ts,d as Es,e as cr,f as wa,g as ut,A as Fs,D as dr,P as ka,h as Bt,E as Ca,T as xr,i as mr,j as _e,X as ke,k as ur,l as pr,m as Ds,n as Sa,o as lt,p as Ye,q as La,K as hr,r as bt,s as mt,Q as rs,t as yt,u as wt,v as $t,R as We,w as Ra,x as gr,y as Ze,z as St,F as Mt,H as nt,I as zs,J as kt,N as br,O as fr,V as yr,W as Aa,Y as Ia,_ as Oa,$ as jr,a0 as Nr,a1 as ls,a2 as Wt,a3 as Ns,a4 as vr,a5 as _r,a6 as vs,a7 as Us,a8 as wr,a9 as kr,aa as qt,ab as Ws,ac as Zt,ad as Pa,ae as Cr,af as Sr,ag as ss,ah as Ta,ai as Lr,aj as Rr,ak as Ar,al as Ir,am as Or,an as Pr,ao as Js}from"./icons-vendor-i_74xDZy.js";import{R as Yt,B as Tr,X as Gs,Y as Vs,T as Xt,a as Er,C as _s,A as Dr,b as $r,c as Mr,P as Qs,d as Ks,L as qr}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 c of n)if(c.type==="childList")for(const u of c.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&l(u)}).observe(document,{childList:!0,subtree:!0});function a(n){const c={};return n.integrity&&(c.integrity=n.integrity),n.referrerPolicy&&(c.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?c.credentials="include":n.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function l(n){if(n.ep)return;n.ep=!0;const c=a(n);fetch(n.href,c)}})();const Br=({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:g,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:Q,children:"取消"}),e.jsxs("button",{onClick:de,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:Q,children:[Q?e.jsx(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(lt,{className:"w-4 h-4"}),Q?"保存中...":"保存"]})]})})]})}),document.body)]})},Bn=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],Fn=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(zn)}},zn=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||"")}},Un=t=>(t==null?void 0:t.results.filter(Wn))||[],Wn=t=>!t.success,Jn=(t,s)=>t!==null&&!s,Gn=t=>{if(!t)return"请选择订单文件";const s=t.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(s)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},ft=(t,s)=>t===s,Vn=(t,s)=>t instanceof Error&&t.message?t.message:s,Qn=({filter:t,onFilterChange:s,accountFilter:a,onAccountFilterChange:l,accounts:n,accountName:c,searchText:u,onSearchChange:h})=>{const m=p=>s(p.currentTarget.dataset.status||"all"),N=p=>l(p.target.value),x=p=>h(p.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:Bn.map(p=>e.jsx("button",{"data-status":p.key,onClick:m,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${t===p.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:p.label},p.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(yt,{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:N,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(p=>e.jsx("option",{value:p.id,children:c(p.id)},p.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(St,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-brand transition-colors"}),e.jsx("input",{type:"text",placeholder:"搜索订单号/商品/买家...",value:u,onChange:x,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},Kn=t=>{const s=c=>{var u;t.setImportFile(((u=c.target.files)==null?void 0:u[0])||null)},a=()=>t.closeImportModal(),l=()=>void t.handleImportOrders(),n=()=>void t.handleRetryImport();return t.showImportModal?Oe.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(ke,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"选择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:"支持 .xlsx 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:u,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:S,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(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(Mt,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:q,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(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(nt,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"追加卡密"]})]})]})}),document.body):null},ei=({type:t})=>{switch(t){case"text":return e.jsx(Ia,{className:"w-5 h-5 text-blue-500"});case"image":return e.jsx(Aa,{className:"w-5 h-5 text-purple-500"});case"api":return e.jsx(yr,{className:"w-5 h-5 text-blue-500"});default:return e.jsx(Os,{className:"w-5 h-5 text-gray-500"})}},ti=(t,s,a)=>{const l=a.trim().toLocaleLowerCase();return t.filter(n=>(!s||n.type===s)&&(!l||n.name.toLocaleLowerCase().includes(l)))},Ka=t=>t.split(`
`).map(s=>s.trim()).filter(Boolean),si=(t,s,a)=>!!(t&&Ka(s).length>0&&!a),vt=(t,s,a,l)=>t===s&&a===l,ai=()=>{const[t,s]=r.useState([]),[a,l]=r.useState(!0),n=r.useRef(0),c=r.useRef(null),u=r.useCallback(async()=>{var N;const h=++n.current;(N=c.current)==null||N.abort();const m=new AbortController;c.current=m,l(!0);try{const x=await Ms({signal:m.signal});if(h!==n.current)return;s(x)}catch(x){h===n.current&&!m.signal.aborted&&console.error("加载卡密库存失败:",x)}finally{h===n.current&&l(!1)}},[]);return r.useEffect(()=>(u(),()=>{var m;n.current+=1,(m=c.current)==null||m.abort()}),[u]),{cards:t,setCards:s,loading:a,loadCards:u}},ri=t=>{const s=t.dataCards,a=t.loadCards,[l,n]=r.useState(!1),[c,u]=r.useState("create"),[h,m]=r.useState(null),[N,x]=r.useState(null),[p,_]=r.useState(!1),[S,q]=r.useState(""),[w,P]=r.useState(""),[A,G]=r.useState(null),[H,X]=r.useState(""),f=r.useRef(0),y=r.useRef(null),z=r.useRef(""),O=r.useMemo(()=>Ka(w),[w]),F=r.useCallback(()=>{var k;u("create"),m(null),x(null),q((k=s[0])!=null&&k.id?String(s[0].id):""),P(""),G(null),X(""),n(!0)},[s]),d=r.useCallback(()=>{var k;f.current+=1,(k=y.current)==null||k.abort(),_(!1),n(!1)},[]),B=r.useCallback(async()=>{var C;if(!h||p)return;const k=++f.current;(C=y.current)==null||C.abort();const D=new AbortController;y.current=D,_(!0),x(null);try{const W=await Dl(h,{signal:D.signal});if(!vt(k,f.current,"",""))return;x(W),W.created>0&&await a()}catch(W){if(!vt(k,f.current,"",""))return;x({error:(W==null?void 0:W.message)||"上传失败"})}finally{vt(k,f.current,"","")&&_(!1)}},[p,h,a]),Z=r.useCallback(async()=>{var W;if(!si(S,w,p))return;const k=S,D=++f.current;z.current=k,(W=y.current)==null||W.abort();const C=new AbortController;y.current=C,_(!0),G(null),X("");try{const V=await $l(k,w,{signal:C.signal});if(!vt(D,f.current,k,S))return;G({added:V.added}),P(""),await a()}catch(V){if(!vt(D,f.current,k,S))return;X((V==null?void 0:V.message)||"追加失败")}finally{vt(D,f.current,k,S)&&_(!1)}},[w,S,p,a]),M=r.useCallback(async()=>{await B()},[B]),b=r.useCallback(async()=>{z.current&&S!==z.current||await Z()},[S,Z]);return{showBatchModal:l,setShowBatchModal:n,batchTab:c,setBatchTab:u,batchFile:h,setBatchFile:m,batchResult:N,batchBusy:p,appendTargetId:S,setAppendTargetId:q,appendContent:w,setAppendContent:P,appendResult:A,appendError:H,appendPreview:O,openBatchModal:F,closeBatchModal:d,handleBatchCreate:B,handleBatchAppend:Z,handleRetryBatchCreate:M,handleRetryBatchAppend:b}},xa=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),li=()=>{const{cards:t,loadCards:s}=ai(),[a,l]=r.useState(!1),[n,c]=r.useState(!1),[u,h]=r.useState(null),[m,N]=r.useState({}),[x,p]=r.useState(xa),[_,S]=r.useState(""),[q,w]=r.useState(""),P=r.useMemo(()=>t.filter(d=>d.type==="data"),[t]),A=ri({dataCards:P,loadCards:s}),G=d=>{var B,Z,M,b,k;h(d),N({id:d.id,name:d.name||"",type:d.type||"text",api_url:((B=d.api_config)==null?void 0:B.url)||"",api_method:((Z=d.api_config)==null?void 0:Z.method)||"GET",api_timeout:((M=d.api_config)==null?void 0:M.timeout)||10,api_headers:((b=d.api_config)==null?void 0:b.headers)||"",api_params:((k=d.api_config)==null?void 0:k.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)},H=async()=>{var d,B,Z,M,b,k,D,C;if(u){if(!((d=m.name)!=null&&d.trim())){alert("请输入卡密名称");return}if(!m.type){alert("请选择卡密类型");return}try{const W={name:m.name.trim(),type:m.type,description:(B=m.description)==null?void 0:B.trim(),delay_seconds:m.delay_seconds||0,enabled:m.enabled??!0};m.type==="api"?W.api_config={url:((Z=m.api_url)==null?void 0:Z.trim())||"",method:m.api_method,timeout:m.api_timeout||10,headers:((M=m.api_headers)==null?void 0:M.trim())||void 0,params:((b=m.api_params)==null?void 0:b.trim())||void 0}:m.type==="text"?W.text_content=((k=m.text_content)==null?void 0:k.trim())||"":m.type==="data"?W.data_content=((D=m.data_content)==null?void 0:D.trim())||"":m.type==="image"&&(W.image_url=((C=m.image_url)==null?void 0:C.trim())||""),await sa(u.id,W),l(!1),await s()}catch(W){console.error("更新卡密失败:",W),alert("更新失败,请重试")}}},X=async d=>{if(confirm("确认删除该卡密吗?"))try{await El(d),await s()}catch(B){console.error("删除卡密失败:",B),alert("删除失败,请重试")}},f=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.api_me Line truncated
VIP-MONTH-002
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(D=>D.map(C=>`"${String(C).replace(/"/g,'""')}"`).join(",")).join(`
`),M=new Blob(["\uFEFF"+Z],{type:"text/csv;charset=utf-8"}),b=URL.createObjectURL(M),k=document.createElement("a");k.href=b,k.download="卡密组批量导入模板.csv",document.body.appendChild(k),k.click(),k.remove(),URL.revokeObjectURL(b)};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:A.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(Mt,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>c(!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(nt,{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(Oa,{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=>S(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(St,{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:q,onChange:d=>w(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:["显示 ",O.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:O.map(d=>{let B="";return d.type==="data"&&d.data_content?B=`库存: ${d.data_content.split(`
`).filter(M=>M.trim()).length} 条`:d.type==="text"&&d.text_content?B=d.text_content:d.type==="api"&&d.api_config?B=d.api_config.url:d.type==="image"&&d.image_url&&(B="图片链接"),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(ei,{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(jr,{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:B,children:B})}),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:()=>y(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:()=>G(d),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(kt,{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(Ze,{className:"h-4 w-4"})})]})})]},d.id)})})]})}),O.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(ka,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:t.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),a&&u&&Oe.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(ke,{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:m.name||"",onChange:d=>N({...m,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:m.type||"text",onChange:d=>N({...m,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:"批量数据"}),(u==null?void 0:u.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),m.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:m.api_url||"",onChange:d=>N({...m,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:m.data_content?m.data_content.split(`
`).filter(d=>d.trim()).length:0})," 条"]})]})]}),m.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:m.image_url||"",onChange:d=>N({...m,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 地址"})]}),m.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:m.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:m.delay_seconds||0,onChange:d=>N({...m,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:m.description||"",onChange:d=>N({...m,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:()=>N({...m,enabled:!m.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${m.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 ${m.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:H,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(lt,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),n&&Oe.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:()=>c(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(ke,{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=>p({...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:()=>p({...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(Os,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>p({...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(Ia,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>p({...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=>p({...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=>p({...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=>p({...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=>p({...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=>p({...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=>p({...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:()=>c(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:f,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(nt,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),e.jsx(Xn,{dataCards:P,downloadCardTemplate:F,...A})]})},ma="ydisks-amap-js-api",ni="c9b68d4ce9a2a97f22a4a439404488ca";let Ot=null;const ii=()=>ni,oi=()=>window.AMap?Promise.resolve(window.AMap):Ot||(Ot=new Promise((t,s)=>{const a=document.getElementById(ma),l=a||document.createElement("script"),n=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(u)},c=()=>{window.AMap?(n(),t(window.AMap)):(n(),s(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},u=window.setTimeout(()=>{n(),s(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=c,l.id=ma,l.async=!0,l.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(ii())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,l.onerror=()=>{n(),s(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},a||document.head.appendChild(l)}).catch(t=>{throw Ot=null,t}),Ot),ts=t=>Number.isFinite(t)&&t!==0,ci=t=>{var n,c;const s=Number((n=t.location)==null?void 0:n.lng),a=Number((c=t.location)==null?void 0:c.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||!ts(s)||!ts(a)||s<-180||s>180||a<-90||a>90?null:l},di=async(t,s)=>{if(!ts(t)||!ts(s)||t<-180||t>180||s<-90||s>90)throw new Error("经纬度无效");const a=await oi();return new Promise((l,n)=>{new a.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[t,s],1e3,(u,h)=>{var N;if(u!=="complete"){if(u==="no_data"){l([]);return}n(new Error("高德地图附近地址查询失败,请稍后重试"));return}const m=(((N=h==null?void 0:h.poiList)==null?void 0:N.pois)||[]).map(ci).filter(x=>x!==null);l(m)})})},xi=t=>t.find(s=>s.status==="running"||s.status==="canceling"),Rs=t=>t==="running"||t==="canceling",mi=t=>!!(t!=null&&t.previ Line truncated
`),Le=new Blob(["\uFEFF"+xe],{type:"text/csv;charset=utf-8"}),st=URL.createObjectURL(Le),Ke=document.createElement("a");Ke.href=st,Ke.download="批量铺货模板.csv",document.body.appendChild(Ke),Ke.click(),Ke.remove(),URL.revokeObjectURL(st)},E=()=>{D(o=>({...o,cookie_id:h||o.cookie_id})),G(!0)},se=()=>{W(o=>({...o,cookie_id:h||o.cookie_id})),X(!0)},ce=async o=>{if(!(o?h:C.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");y(!0),navigator.geolocation.getCurrentPosition(async xe=>{try{const Le=await di(xe.coords.longitude,xe.coords.latitude);if(!Le.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");o?(Ue(Le),Me(Le[0])):(O(Le),d(Le[0]))}catch(Le){alert((Le==null?void 0:Le.message)||"获取发货地失败")}finally{y(!1)}},xe=>{y(!1),alert(xe.code===xe.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},fe=o=>l.filter(K=>K.cookie_id===o.cookie_id&&K.item_id===o.item_id).length>0?l.filter(K=>K.cookie_id===o.cookie_id&&K.item_id===o.item_id):l.filter(K=>K.cookie_id===o.cookie_id&&!K.item_id),De=r.useMemo(()=>new Map(c.map(o=>[o.id,o])),[c]),ve=r.useMemo(()=>N?s.filter(o=>o.cookie_id===N):s,[N,s]),Pe=o=>{const K=De.get(o),xe=(K==null?void 0:K.remark)||(K==null?void 0:K.nickname);return xe?`${xe} · ${o.slice(0,6)}`:`账号 ${o.slice(0,8)}`},me=o=>{const K=De.get(o);return(K==null?void 0:K.remark)||(K==null?void 0:K.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(Nr,{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:N,onChange:o=>x(o.target.value),children:[e.jsx("option",{value:"",children:"全部账号"}),c.map(o=>e.jsx("option",{value:o.id,children:Pe(o.id)},o.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(yt,{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:h,onChange:o=>m(o.target.value),children:[e.jsx("option",{value:"",children:"请选择账号"}),c.map(o=>e.jsx("option",{value:o.id,children:Pe(o.id)},o.id))]})]})]}),e.jsxs("button",{onClick:Ge,disabled:p||!h,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 ${p?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:E,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(nt,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:se,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(ls,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void Be(),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"}),de&&["running","canceling"].includes(de.status)?"继续批量任务":"批量铺货"]}),de&&!["running","canceling"].includes(de.status)&&e.jsx("button",{onClick:()=>void He(),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:[ve.map(o=>{const K=fe(o),xe=K.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relative flex flex Line truncated
+1 -1
View File
@@ -6,7 +6,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ydisks闲鱼助手 - 自动发货与管家系统</title>
<meta name="description" content="Ydisks闲鱼助手 - 自动回复、自动发货、订单管理、AI智能议价一体化解决方案" />
<script type="module" crossorigin src="/static/assets/index-CQUrFUKL.js"></script>
<script type="module" crossorigin src="/static/assets/index-jRlHx8b7.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">