阶段七:完成Settings React feature化与配置校验边界

This commit is contained in:
Christ committed 2026-08-15 01:45:21 +08:00
1 parent 56b20507f3
commit d388d76851
15 files changed
+896 -769

No files matched your search

File diff suppressed because it is too large. Load diff
+3 -1
View File
@@ -176,7 +176,8 @@ app shell / routes
- 已完成阶段 7 第五个 PR 切片“React OrderList feature 化与订单导入/刷新行为边界”:按 `app/features/orders` 提取订单 API 适配层、查询/分页 Hook、导入 Hook、筛选栏和导入弹窗;订单查询与辅助数据支持并行加载、取消和代次门禁,导入支持文件预检、取消、失败重试和导入后刷新;新增筛选、导入归一化、API 取消信号和过期响应测试,保留旧组件入口和 API 路径;前端类型检查、全量测试、注释检查和构建门禁通过,合并为一个可回滚提交;
- 已完成阶段 7 第六个 PR 切片“React Notifications feature 化与渠道/事件绑定行为边界”:按 `app/features/notifications` 提取通知渠道/SMTP API 适配层、静态渠道配置、数据与动作 Hook、渠道列表、事件绑定选择器、渠道编辑弹窗和 SMTP 面板;渠道与 SMTP 请求支持取消和代次门禁,表单支持渠道字段/独立 SMTP 校验、保存失败重试和过期响应保护;更新架构字符串测试并新增状态/API 取消信号测试,保留旧页面入口和 API 路径;前端类型检查、全量测试、注释检查和构建门禁通过,合并为一个可回滚提交;
- 已完成阶段 7 第七个 PR 切片“React Dashboard feature 化与统计/趋势查询行为边界”:按 `app/features/dashboard` 提取 Dashboard API 适配层、统计数据 Hook、趋势/排行派生状态和请求边界;概览、趋势和有效订单支持并行加载、刷新取消、失败重试与过期响应保护;新增统计派生数据、API 取消信号和请求代次测试,保留旧页面入口和 API 路径;前端类型检查、全量测试、注释检查和构建门禁通过并合并为一个可回滚提交;
- 阶段 7 下一 PR 切片为“React Settings feature 化与系统配置校验边界”:提取设置 API、配置表单状态和敏感字段校验,补充保存取消、失败重试和过期响应测试;
- 已完成阶段 7 第八个 PR 切片“React Settings feature 化与系统配置校验边界”:按 `app/features/settings` 提取系统配置/模型/凭据 API 适配层、配置常量、表单状态和敏感字段校验;配置读取与保存支持并行加载、请求取消、失败重试和过期响应保护,登录凭据提交保留现有校验与重登录语义;新增配置裁剪、凭据校验、API 取消信号和请求代次测试,保留旧页面入口和 API 路径;
- 阶段 7 下一 PR 切片为“React Chat feature 化与会话消息行为边界”:提取聊天 API、会话/消息分页 Hook 和消息发送状态,补充会话切换取消、分页过期响应和发送失败重试测试;
- 禁止跳过当前入口直接开始 Engine、Automation 或 DB 的大规模拆分。
## 6. 阶段 0:治理文档与强约束
@@ -602,3 +603,4 @@ npm --prefix frontend run build
| 2026-08-15 | 完成阶段 7 第五个 PR 切片“React OrderList feature 化与订单导入/刷新行为边界” | 按 `app/features/orders` 提取订单 API 适配层、查询/分页 Hook、导入 Hook、筛选栏和导入弹窗;订单查询与辅助数据支持并行加载、取消和代次门禁,导入支持文件预检、取消、失败重试和导入后刷新;新增筛选、导入归一化、API 取消信号和过期响应测试,保留旧组件入口和 API 路径;前端类型检查、全量测试、注释检查和构建门禁通过并合并为一个可回滚提交 | 阶段 7:React Notifications feature 化与渠道/事件绑定行为边界 |
| 2026-08-15 | 完成阶段 7 第六个 PR 切片“React Notifications feature 化与渠道/事件绑定行为边界” | 按 `app/features/notifications` 提取通知渠道/SMTP API 适配层、静态渠道配置、数据与动作 Hook、渠道列表、事件绑定选择器、渠道编辑弹窗和 SMTP 面板;渠道与 SMTP 请求支持取消和代次门禁,表单支持渠道字段/独立 SMTP 校验、保存失败重试和过期响应保护;更新架构字符串测试并新增状态/API 取消信号测试,保留旧页面入口和 API 路径;前端类型检查、全量测试、注释检查和构建门禁通过并合并为一个可回滚提交 | 阶段 7:React Dashboard feature 化与统计/趋势查询行为边界 |
| 2026-08-15 | 完成阶段 7 第七个 PR 切片“React Dashboard feature 化与统计/趋势查询行为边界” | 按 `app/features/dashboard` 提取 Dashboard API 适配层、统计数据 Hook、趋势/排行派生状态和请求边界;概览、趋势和有效订单支持并行加载、刷新取消、失败重试与过期响应保护;新增统计派生数据、API 取消信号和请求代次测试,保留旧页面入口和 API 路径;前端类型检查、全量测试、注释检查和构建门禁通过并合并为一个可回滚提交 | 阶段 7:React Settings feature 化与系统配置校验边界 |
| 2026-08-15 | 完成阶段 7 第八个 PR 切片“React Settings feature 化与系统配置校验边界” | 按 `app/features/settings` 提取系统配置/模型/凭据 API 适配层、配置常量、表单状态和敏感字段校验;配置读取与保存支持并行加载、请求取消、失败重试和过期响应保护,登录凭据提交保留现有校验与重登录语义;新增配置裁剪、凭据校验、API 取消信号和请求代次测试,保留旧页面入口和 API 路径 | 阶段 7:React Chat feature 化与会话消息行为边界 |
+2
View File
@@ -0,0 +1,2 @@
/** Settings feature 使用的系统配置与身份 API。 */
export { fetchAIModels, getSystemSettings, updateLoginCredentials, updateSystemSettings, verifySession } from '../../../services/api';
@@ -0,0 +1,28 @@
/** AI 服务默认兼容 API 地址。 */
export const DEFAULT_AI_API_URL = 'https://dashscope.aliyuncs.com/compatible-mode/v1';
/** 日志等级选择项。 */
export const LOG_LEVELS = [
{ value: 'debug', label: 'Debug' },
{ value: 'info', label: 'Info' },
{ value: 'warn', label: 'Warn' },
{ value: 'error', label: 'Error' },
];
/** 不应通过系统配置批量保存的兼容字段集合。 */
export const SETTINGS_SAVE_OMIT_KEYS = new Set([
'smtp_server',
'smtp_port',
'smtp_user',
'smtp_password',
'smtp_from',
'smtp_from_name',
'smtp_from_address',
'registration_enabled',
'show_default_login_info',
'login_captcha_enabled',
'item_sync_enabled',
'item_sync_interval',
'item_sync_max_pages',
'default_reply',
]);
+222
View File
@@ -0,0 +1,222 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import type React from 'react';
import type { SystemSettings } from '../../../types';
import { fetchAIModels, getSystemSettings, updateLoginCredentials, updateSystemSettings, verifySession } from './api';
import { DEFAULT_AI_API_URL } from './constants';
import { buildPersistableSettings, createCredentials, createCredentialsMessage, isCurrentSettingsRequest, isSettingsAbortError, settingsErrorMessage, validateCredentials } from './state';
import type { CredentialsForm, CredentialsMessage, SettingsFeatureState, SettingsRequestStatus } from './types';
/** Settings feature 的 Hook 返回值。 */
export type UseSettingsResult = SettingsFeatureState & {
/** 模型选择器 DOM 引用。 */
modelPickerRef: React.RefObject<HTMLDivElement | null>;
/** 重新加载系统配置与模型。 */
loadSettings: () => void;
/** 加载模型列表。 */
loadAIModels: (source?: SystemSettings | null, openAfterLoad?: boolean) => void;
/** 保存系统配置。 */
handleSave: () => Promise<void>;
/** 保存登录凭据。 */
handleCredentialsSave: (event: React.FormEvent) => Promise<void>;
/** 更新配置草稿。 */
setSettings: React.Dispatch<React.SetStateAction<SystemSettings | null>>;
/** 更新模型下拉框状态。 */
setModelDropdownOpen: React.Dispatch<React.SetStateAction<boolean>>;
/** 更新敏感字段显示状态。 */
setShowApiKey: React.Dispatch<React.SetStateAction<boolean>>;
/** 更新远程秘钥显示状态。 */
setShowCaptchaSecret: React.Dispatch<React.SetStateAction<boolean>>;
/** 更新当前密码显示状态。 */
setShowCurrentPassword: React.Dispatch<React.SetStateAction<boolean>>;
/** 更新新密码显示状态。 */
setShowNewPassword: React.Dispatch<React.SetStateAction<boolean>>;
/** 更新凭据表单。 */
setCredentials: React.Dispatch<React.SetStateAction<CredentialsForm>>;
/** 更新凭据提示。 */
setCredentialsMessage: React.Dispatch<React.SetStateAction<CredentialsMessage>>;
};
/** 管理系统设置、AI 模型和登录凭据的请求与表单状态。 */
export const useSettings = (): UseSettingsResult => {
// settings 保存当前系统配置草稿。
const [settings, setSettings] = useState<SystemSettings | null>(null);
// loading 表示系统配置是否正在加载。
const [loading, setLoading] = useState(false);
// loadError 保存系统配置加载失败信息。
const [loadError, setLoadError] = useState('');
// saving 表示系统配置是否正在保存。
const [saving, setSaving] = useState(false);
// saveError 保存系统配置保存失败信息。
const [saveError, setSaveError] = useState('');
// aiModels 保存远端模型发现结果。
const [aiModels, setAiModels] = useState<string[]>([]);
// modelsLoading 表示模型发现请求是否进行中。
const [modelsLoading, setModelsLoading] = useState(false);
// modelError 保存模型发现失败信息。
const [modelError, setModelError] = useState('');
// modelDropdownOpen 表示模型选择下拉框是否展开。
const [modelDropdownOpen, setModelDropdownOpen] = useState(false);
// showApiKey 控制 AI API Key 是否明文显示。
const [showApiKey, setShowApiKey] = useState(false);
// showCaptchaSecret 控制远程验证秘钥是否明文显示。
const [showCaptchaSecret, setShowCaptchaSecret] = useState(false);
// showCurrentPassword 控制当前密码是否明文显示。
const [showCurrentPassword, setShowCurrentPassword] = useState(false);
// showNewPassword 控制新密码是否明文显示。
const [showNewPassword, setShowNewPassword] = useState(false);
// credentialsSaving 表示登录凭据是否正在保存。
const [credentialsSaving, setCredentialsSaving] = useState(false);
// credentialsMessage 保存登录凭据操作提示。
const [credentialsMessage, setCredentialsMessage] = useState<CredentialsMessage>(null);
// credentials 保存登录凭据编辑草稿。
const [credentials, setCredentials] = useState<CredentialsForm>(() => createCredentials());
// requestStatus 表示最近一次设置请求的阶段。
const [requestStatus, setRequestStatus] = useState<SettingsRequestStatus>('idle');
// modelPickerRef 指向模型选择器根节点。
const modelPickerRef = useRef<HTMLDivElement>(null);
// settingsRef 保存最新配置供稳定回调读取。
const settingsRef = useRef<SystemSettings | null>(null);
// requestSequence 隔离刷新产生的旧响应。
const requestSequence = useRef(0);
// requestController 保存当前可取消的设置请求。
const requestController = useRef<AbortController | null>(null);
// settingsRef 保存最新配置,供稳定的模型加载回调读取。
settingsRef.current = settings;
/** 取消当前设置请求并创建新的请求控制器。 */
const beginRequest = useCallback(() => {
// controller 是本次请求的取消控制器。
requestController.current?.abort();
const controller = new AbortController();
requestController.current = controller;
requestSequence.current += 1;
return { controller, sequence: requestSequence.current };
}, []);
const loadAIModels = useCallback(async (source?: SystemSettings | null, openAfterLoad = false, signal?: AbortSignal) => {
// current 是本次模型发现使用的配置快照。
const current = source || settingsRef.current;
// baseUrl 是兼容模型发现接口的服务地址。
const baseUrl = current?.ai_api_url || current?.ai_base_url || DEFAULT_AI_API_URL;
setModelsLoading(true);
setModelError('');
try {
const models = await fetchAIModels(baseUrl, current?.ai_api_key || '', { signal });
if (signal?.aborted) return;
setAiModels(models);
setModelDropdownOpen(openAfterLoad && models.length > 0);
if (!current?.ai_model && models.length > 0) {
setSettings(previous => previous ? { ...previous, ai_model: models[0] } : previous);
}
} catch (error) {
if (signal?.aborted || isSettingsAbortError(error)) return;
setAiModels([]);
setModelDropdownOpen(false);
setModelError(settingsErrorMessage(error, '读取模型失败'));
} finally {
if (!signal?.aborted) setModelsLoading(false);
}
}, []);
const loadSettings = useCallback(() => {
// request 是本次设置读取的代次与控制器。
const { controller, sequence } = beginRequest();
setLoading(true);
setRequestStatus('loading');
setLoadError('');
Promise.all([
getSystemSettings({ signal: controller.signal }),
verifySession({ signal: controller.signal }),
]).then(([data, session]) => {
if (!isCurrentSettingsRequest(requestSequence.current, sequence, controller.signal)) return;
setSettings(data);
if (session.username) setCredentials(previous => ({ ...previous, new_username: session.username || '' }));
void loadAIModels(data, false, controller.signal);
setRequestStatus('success');
}).catch(error => {
if (!isCurrentSettingsRequest(requestSequence.current, sequence, controller.signal) || isSettingsAbortError(error)) return;
setSettings(null);
setLoadError(settingsErrorMessage(error, '加载配置失败'));
setRequestStatus('error');
}).finally(() => {
if (isCurrentSettingsRequest(requestSequence.current, sequence, controller.signal)) setLoading(false);
});
}, [beginRequest, loadAIModels]);
useEffect(() => {
loadSettings();
return () => requestController.current?.abort();
}, [loadSettings]);
useEffect(() => {
// handlePointerDown 负责点击模型选择器外部时关闭下拉框。
const handlePointerDown = (event: MouseEvent) => {
if (!modelPickerRef.current?.contains(event.target as Node)) setModelDropdownOpen(false);
};
document.addEventListener('mousedown', handlePointerDown);
return () => document.removeEventListener('mousedown', handlePointerDown);
}, []);
const handleSave = useCallback(async () => {
// handleSave 提交当前配置草稿并保护过期响应。
if (!settings || saving) return;
// request 是本次保存动作的代次与控制器。
const { controller, sequence } = beginRequest();
setSaving(true);
setSaveError('');
try {
await updateSystemSettings(buildPersistableSettings(settings), { signal: controller.signal });
if (!isCurrentSettingsRequest(requestSequence.current, sequence, controller.signal)) return;
window.alert('系统配置已保存');
} catch (error) {
if (!isCurrentSettingsRequest(requestSequence.current, sequence, controller.signal) || isSettingsAbortError(error)) return;
setSaveError(settingsErrorMessage(error, '保存配置失败'));
} finally {
if (isCurrentSettingsRequest(requestSequence.current, sequence, controller.signal)) setSaving(false);
}
}, [beginRequest, saving, settings]);
const handleCredentialsSave = useCallback(async (event: React.FormEvent) => {
// handleCredentialsSave 校验并提交登录凭据表单。
event.preventDefault();
setCredentialsMessage(null);
// validationError 是前端校验得到的第一条可见错误。
const validationError = validateCredentials(credentials);
if (validationError) {
setCredentialsMessage(createCredentialsMessage('error', validationError));
return;
}
// request 是本次凭据保存动作的代次与控制器。
const { controller, sequence } = beginRequest();
setCredentialsSaving(true);
try {
// result 是后端返回的凭据更新结果。
const result = await updateLoginCredentials({
current_password: credentials.current_password,
new_username: credentials.new_username.trim(),
new_password: credentials.new_password || undefined,
}, { signal: controller.signal });
if (!isCurrentSettingsRequest(requestSequence.current, sequence, controller.signal)) return;
if (!result.success) {
setCredentialsMessage(createCredentialsMessage('error', result.message || '登录凭据更新失败'));
return;
}
setCredentialsMessage(createCredentialsMessage('success', result.message || '登录凭据已更新'));
window.setTimeout(() => window.location.reload(), 1400);
} catch (error) {
if (!isCurrentSettingsRequest(requestSequence.current, sequence, controller.signal) || isSettingsAbortError(error)) return;
setCredentialsMessage(createCredentialsMessage('error', settingsErrorMessage(error, '登录凭据更新失败')));
} finally {
if (isCurrentSettingsRequest(requestSequence.current, sequence, controller.signal)) setCredentialsSaving(false);
}
}, [beginRequest, credentials]);
return {
settings, loading, loadError, saving, saveError, aiModels, modelsLoading, modelError, modelDropdownOpen,
showApiKey, showCaptchaSecret, showCurrentPassword, showNewPassword, credentialsSaving, credentialsMessage,
credentials, requestStatus, modelPickerRef, loadSettings, loadAIModels: (source, openAfterLoad) => void loadAIModels(source, openAfterLoad),
handleSave, handleCredentialsSave, setSettings, setModelDropdownOpen, setShowApiKey, setShowCaptchaSecret,
setShowCurrentPassword, setShowNewPassword, setCredentials, setCredentialsMessage,
};
};
@@ -0,0 +1,39 @@
import { expect, test } from 'vitest';
import type { SystemSettings } from '../../../types';
import { buildPersistableSettings, createCredentials, createCredentialsMessage, isCurrentSettingsRequest, validateCredentials } from './state';
// settingsFixture 是覆盖敏感字段过滤和系统配置保留字段的最小草稿。
const settingsFixture: SystemSettings = {
log_level: 'info',
smtp_password: 'secret',
ai_api_key: 'api-key',
renewal_log_retention_days: 15,
};
test('Settings 保存草稿只提交允许的系统配置字段',
// 配置裁剪测试验证 SMTP 等兼容字段不会被系统设置批量接口覆盖。
() => {
expect(buildPersistableSettings(settingsFixture)).toEqual({ log_level: 'info', ai_api_key: 'api-key', renewal_log_retention_days: 15 });
});
test('登录凭据校验覆盖用户名、密码和确认密码边界',
// 凭据校验测试验证所有前端可直接阻断的错误都在请求前返回。
() => {
expect(validateCredentials(createCredentials('ab'))).toContain('用户名');
expect(validateCredentials({ ...createCredentials('admin'), current_password: '' })).toContain('当前密码');
expect(validateCredentials({ ...createCredentials('admin'), current_password: 'old', new_password: 'short', confirm_password: 'short' })).toContain('8 个字符');
expect(validateCredentials({ ...createCredentials('admin'), current_password: 'old', new_password: 'long-password', confirm_password: 'different' })).toContain('不一致');
expect(validateCredentials({ ...createCredentials('admin'), current_password: 'old' })).toBe('');
expect(createCredentialsMessage('success', '已保存')).toEqual({ type: 'success', text: '已保存' });
});
test('Settings 请求代次拒绝过期响应和取消响应',
// 请求边界测试验证刷新或组件卸载后旧响应不会覆盖当前状态。
() => {
// controller 是模拟组件卸载取消的控制器。
const controller = new AbortController();
expect(isCurrentSettingsRequest(2, 2, controller.signal)).toBe(true);
expect(isCurrentSettingsRequest(1, 2, controller.signal)).toBe(false);
controller.abort();
expect(isCurrentSettingsRequest(2, 2, controller.signal)).toBe(false);
});
+46
View File
@@ -0,0 +1,46 @@
import type { SystemSettings } from '../../../types';
import { SETTINGS_SAVE_OMIT_KEYS } from './constants';
import type { CredentialsForm, CredentialsMessage } from './types';
/** 将配置草稿裁剪为可以保存到后端的字段。 */
export const buildPersistableSettings = (settings: SystemSettings): Partial<SystemSettings> => (
Object.fromEntries(
Object.entries(settings).filter(
// entry 是配置键值对,过滤掉兼容字段和空值。
([key, value]) => !SETTINGS_SAVE_OMIT_KEYS.has(key) && value !== undefined && value !== null,
),
) as Partial<SystemSettings>
);
/** 校验登录凭据表单并返回用户可见错误。 */
export const validateCredentials = (credentials: CredentialsForm): string => {
// username 是去除首尾空白后的登录用户名。
const username = credentials.new_username.trim();
if (username.length < 3) return '用户名至少需要 3 个字符';
if (!credentials.current_password) return '请输入当前密码确认身份';
if (credentials.new_password && credentials.new_password.length < 8) return '新密码至少需要 8 个字符';
if (credentials.new_password !== credentials.confirm_password) return '两次输入的新密码不一致';
return '';
};
/** 判断设置请求响应是否仍可写入当前页面。 */
export const isCurrentSettingsRequest = (currentSequence: number, requestSequence: number, signal: AbortSignal): boolean => (
currentSequence === requestSequence && !signal.aborted
);
/** 判断错误是否来自主动取消。 */
export const isSettingsAbortError = (error: unknown): boolean => error instanceof Error && error.message === '请求已取消';
/** 统一提取设置请求错误文本。 */
export const settingsErrorMessage = (error: unknown, fallback: string): string => error instanceof Error ? error.message : fallback;
/** 创建登录凭据的初始表单。 */
export const createCredentials = (username = ''): CredentialsForm => ({
new_username: username,
current_password: '',
new_password: '',
confirm_password: '',
});
/** 创建凭据保存结果提示。 */
export const createCredentialsMessage = (type: 'success' | 'error', text: string): CredentialsMessage => ({ type, text });
+62
View File
@@ -0,0 +1,62 @@
import type { SystemSettings } from '../../../types';
/** 登录凭据编辑表单。 */
export type CredentialsForm = {
/** 新登录用户名。 */
new_username: string;
/** 当前密码。 */
current_password: string;
/** 新密码。 */
new_password: string;
/** 确认新密码。 */
confirm_password: string;
};
/** 登录凭据操作提示。 */
export type CredentialsMessage = {
/** 提示类型。 */
type: 'success' | 'error';
/** 提示文本。 */
text: string;
} | null;
/** Settings feature 暴露的请求状态。 */
export type SettingsRequestStatus = 'idle' | 'loading' | 'success' | 'error';
/** Settings feature 的统一状态。 */
export type SettingsFeatureState = {
/** 当前系统配置草稿。 */
settings: SystemSettings | null;
/** 系统配置加载状态。 */
loading: boolean;
/** 系统配置加载错误。 */
loadError: string;
/** 系统配置保存状态。 */
saving: boolean;
/** 系统配置保存错误。 */
saveError: string;
/** 可选 AI 模型列表。 */
aiModels: string[];
/** AI 模型列表加载状态。 */
modelsLoading: boolean;
/** AI 模型列表错误。 */
modelError: string;
/** 模型下拉框是否展开。 */
modelDropdownOpen: boolean;
/** API Key 是否明文显示。 */
showApiKey: boolean;
/** 远程验证秘钥是否明文显示。 */
showCaptchaSecret: boolean;
/** 当前密码是否明文显示。 */
showCurrentPassword: boolean;
/** 新密码是否明文显示。 */
showNewPassword: boolean;
/** 登录凭据保存状态。 */
credentialsSaving: boolean;
/** 登录凭据操作提示。 */
credentialsMessage: CredentialsMessage;
/** 登录凭据草稿。 */
credentials: CredentialsForm;
/** 最近一次请求状态。 */
requestStatus: SettingsRequestStatus;
};
+27 -172
View File
@@ -1,191 +1,39 @@
import React, { useEffect, useRef, useState } from 'react';
import {
fetchAIModels,
getSystemSettings,
updateLoginCredentials,
updateSystemSettings,
verifySession,
} from '../services/api';
import { SystemSettings } from '../types';
import React from 'react';
import {
Save, Sparkles, Settings as SettingsIcon,
Eye, EyeOff, RefreshCw, Database, ChevronDown, Check,
LockKeyhole, UserRound, ShieldCheck
} from 'lucide-react';
import { DEFAULT_AI_API_URL, LOG_LEVELS } from '../app/features/settings/constants';
import { useSettings } from '../app/features/settings/hooks';
const DEFAULT_AI_API_URL = 'https://dashscope.aliyuncs.com/compatible-mode/v1';
const LOG_LEVELS = [
{ value: 'debug', label: 'Debug' },
{ value: 'info', label: 'Info' },
{ value: 'warn', label: 'Warn' },
{ value: 'error', label: 'Error' },
];
const SETTINGS_SAVE_OMIT_KEYS = new Set([
'smtp_server',
'smtp_port',
'smtp_user',
'smtp_password',
'smtp_from',
'smtp_from_name',
'smtp_from_address',
'registration_enabled',
'show_default_login_info',
'login_captcha_enabled',
'item_sync_enabled',
'item_sync_interval',
'item_sync_max_pages',
'default_reply',
]);
// Settings 展示系统配置、AI 模型和登录凭据编辑页面。
const Settings: React.FC = () => {
const [settings, setSettings] = useState<SystemSettings | null>(null);
const [loading, setLoading] = useState(false);
const [loadError, setLoadError] = useState('');
const [saving, setSaving] = useState(false);
const [aiModels, setAiModels] = useState<string[]>([]);
const [modelsLoading, setModelsLoading] = useState(false);
const [modelError, setModelError] = useState('');
const [modelDropdownOpen, setModelDropdownOpen] = useState(false);
const modelPickerRef = useRef<HTMLDivElement>(null);
// Password visibility states
const [showApiKey, setShowApiKey] = useState(false);
const [showCaptchaSecret, setShowCaptchaSecret] = useState(false);
const [showCurrentPassword, setShowCurrentPassword] = useState(false);
const [showNewPassword, setShowNewPassword] = useState(false);
const [credentialsSaving, setCredentialsSaving] = useState(false);
const [credentialsMessage, setCredentialsMessage] = useState<{type: 'success' | 'error'; text: string} | null>(null);
const [credentials, setCredentials] = useState({
new_username: '',
current_password: '',
new_password: '',
confirm_password: '',
});
useEffect(() => {
loadSettings();
verifySession().then(session => {
if (session.username) {
setCredentials(current => ({...current, new_username: session.username || ''}));
}
}).catch(() => undefined);
}, []);
useEffect(() => {
const handlePointerDown = (event: MouseEvent) => {
if (!modelPickerRef.current?.contains(event.target as Node)) {
setModelDropdownOpen(false);
}
};
document.addEventListener('mousedown', handlePointerDown);
return () => document.removeEventListener('mousedown', handlePointerDown);
}, []);
const loadAIModels = async (source?: SystemSettings | null, openAfterLoad = false) => {
const current = source || settings;
const baseUrl = current?.ai_api_url || current?.ai_base_url || DEFAULT_AI_API_URL;
setModelsLoading(true);
setModelError('');
try {
const models = await fetchAIModels(baseUrl, current?.ai_api_key || '');
setAiModels(models);
setModelDropdownOpen(openAfterLoad && models.length > 0);
if (!current?.ai_model && models.length > 0) {
setSettings(prev => prev ? { ...prev, ai_model: models[0] } : prev);
}
} catch (e) {
setAiModels([]);
setModelDropdownOpen(false);
setModelError((e as Error).message || '读取模型失败');
} finally {
setModelsLoading(false);
}
};
const loadSettings = () => {
setLoading(true);
setLoadError('');
getSystemSettings()
.then(data => {
setSettings(data);
loadAIModels(data);
})
.catch(error => {
setSettings(null);
setLoadError((error as Error).message || '加载配置失败');
})
.finally(() => setLoading(false));
};
const handleSave = async () => {
if(!settings) return;
setSaving(true);
try {
const persistable = Object.fromEntries(
Object.entries(settings).filter(([key, value]) =>
!SETTINGS_SAVE_OMIT_KEYS.has(key) && value !== undefined && value !== null
)
) as Partial<SystemSettings>;
await updateSystemSettings(persistable);
alert('系统配置已保存');
} catch (e) {
alert('保存失败:' + (e as Error).message);
} finally {
setSaving(false);
}
};
const handleCredentialsSave = async (event: React.FormEvent) => {
event.preventDefault();
setCredentialsMessage(null);
const username = credentials.new_username.trim();
if (username.length < 3) {
setCredentialsMessage({type: 'error', text: '用户名至少需要 3 个字符'});
return;
}
if (!credentials.current_password) {
setCredentialsMessage({type: 'error', text: '请输入当前密码确认身份'});
return;
}
if (credentials.new_password && credentials.new_password.length < 8) {
setCredentialsMessage({type: 'error', text: '新密码至少需要 8 个字符'});
return;
}
if (credentials.new_password !== credentials.confirm_password) {
setCredentialsMessage({type: 'error', text: '两次输入的新密码不一致'});
return;
}
setCredentialsSaving(true);
try {
const result = await updateLoginCredentials({
current_password: credentials.current_password,
new_username: username,
new_password: credentials.new_password || undefined,
});
if (!result.success) {
setCredentialsMessage({type: 'error', text: result.message || '登录凭据更新失败'});
return;
}
setCredentialsMessage({type: 'success', text: result.message || '登录凭据已更新'});
window.setTimeout(() => window.location.reload(), 1400);
} catch (error) {
setCredentialsMessage({type: 'error', text: (error as Error).message || '登录凭据更新失败'});
} finally {
setCredentialsSaving(false);
}
};
// featureState 是 Settings Hook 提供的状态与动作集合。
const {
settings, loading, loadError, saving, saveError, aiModels, modelsLoading, modelError, modelDropdownOpen,
showApiKey, showCaptchaSecret, showCurrentPassword, showNewPassword, credentialsSaving, credentialsMessage,
credentials, modelPickerRef, loadSettings, loadAIModels, handleSave, handleCredentialsSave,
setSettings, setModelDropdownOpen, setShowApiKey, setShowCaptchaSecret, setShowCurrentPassword,
setShowNewPassword, setCredentials,
} = useSettings();
if (!settings) {
return (
<div className="p-8 text-center text-gray-400">
<div className="p-8 text-center text-gray-400 space-y-3">
{loadError || (loading ? '加载配置中...' : '暂无配置')}
{!loading && loadError && (
<div>
<button type="button" className="ios-btn-primary px-4 py-2 rounded-xl" onClick={loadSettings}>重新加载</button>
</div>
)}
</div>
);
}
// currentModel 是当前配置中的模型名称。
const currentModel = settings.ai_model || '';
// visibleAIModels 是模型下拉框当前展示的候选列表。
const visibleAIModels = aiModels;
return (
@@ -210,6 +58,13 @@ const Settings: React.FC = () => {
</button>
</div>
{saveError && (
<div className="flex items-center justify-between gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm text-red-700">
<span>{saveError}</span>
<button type="button" className="font-bold underline" onClick={() => void handleSave}>重试保存</button>
</div>
)}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
{/* Left Column */}
<div className="space-y-8">
+4 -3
View File
@@ -43,20 +43,21 @@ describe('frontend navigation routing', () => {
test('settings page does not expose backend-inactive system controls', () => {
const settings = readFrontendFile('components/Settings.tsx');
const settingsConstants = readFrontendFile('app/features/settings/constants.ts');
expect(settings).not.toContain('允许用户注册');
expect(settings).not.toContain('显示默认登录信息');
expect(settings).not.toContain('启用商品自动同步');
expect(settings).not.toContain('商品同步间隔');
expect(settings).not.toContain('默认自动回复内容');
expect(settings).toContain('SETTINGS_SAVE_OMIT_KEYS');
expect(settingsConstants).toContain('SETTINGS_SAVE_OMIT_KEYS');
expect(settings).toContain('保存后需重启服务生效');
});
test('admin-only settings navigation is gated by session role', () => {
const app = readFrontendFile('App.tsx');
const sidebar = readFrontendFile('components/Sidebar.tsx');
const settings = readFrontendFile('components/Settings.tsx');
const settingsHook = readFrontendFile('app/features/settings/hooks.ts');
expect(app).toContain('const [isAdmin, setIsAdmin] = useState(false)');
expect(app).toContain('setIsAdmin(res.is_admin === true)');
@@ -64,7 +65,7 @@ describe('frontend navigation routing', () => {
expect(app).toContain('isAdmin ? <Settings /> : <Dashboard />');
expect(sidebar).toContain('isAdmin = false');
expect(sidebar).toContain("...(isAdmin ? [{ id: 'settings'");
expect(settings).toContain('setLoadError');
expect(settingsHook).toContain('setLoadError');
});
test('captcha remote settings expose the reference privacy and fallback semantics', () => {
+20
View File
@@ -180,6 +180,26 @@ test('Dashboard 统计 API 转发外部取消信号', async () => {
expect(fetchMock).toHaveBeenNthCalledWith(4, expect.stringContaining('/api/v1/analytics/orders/valid?'), expect.objectContaining({ signal: expect.any(AbortSignal) }));
});
test('Settings 配置、模型和凭据 API 转发外部取消信号', async () => {
// fetchMock 验证 Settings 的读取、模型发现和凭据保存共享取消控制能力。
const fetchMock = vi.fn()
.mockResolvedValueOnce(jsonResponse({ data: { log_level: 'info' } }))
.mockResolvedValueOnce(jsonResponse({ models: ['model-a'] }))
.mockResolvedValueOnce(jsonResponse({ authenticated: true, username: 'admin' }))
.mockResolvedValueOnce(jsonResponse({ success: true, message: '已更新' }));
vi.stubGlobal('fetch', fetchMock);
// controller 是 Settings feature Hook 使用的请求控制器。
const controller = new AbortController();
await getSystemSettings({ signal: controller.signal });
await fetchAIModels('https://ai.example.com', 'secret', { signal: controller.signal });
await verifySession({ signal: controller.signal });
await updateLoginCredentials({ current_password: 'old', new_username: 'admin' }, { signal: controller.signal });
expect(fetchMock).toHaveBeenNthCalledWith(1, '/api/v1/settings/system', expect.objectContaining({ signal: expect.any(AbortSignal) }));
expect(fetchMock).toHaveBeenNthCalledWith(2, '/api/v1/settings/ai-models', expect.objectContaining({ signal: expect.any(AbortSignal) }));
expect(fetchMock).toHaveBeenNthCalledWith(3, '/api/v1/session', expect.objectContaining({ signal: expect.any(AbortSignal) }));
expect(fetchMock).toHaveBeenNthCalledWith(4, '/api/v1/session/credentials', expect.objectContaining({ signal: expect.any(AbortSignal) }));
});
test('通知渠道和 SMTP API 转发外部取消信号', async () => {
// fetchMock 验证渠道读取、保存和 SMTP 读写都支持取消控制。
const fetchMock = vi.fn()
+6 -6
View File
@@ -26,8 +26,8 @@ export const initializeAdmin = async (password: string): Promise<LoginResponse>
return post('/api/v1/session/initialize', { password }, { skipAuthLogout: true });
};
export const verifySession = async (): Promise<{ authenticated: boolean; initialized?: boolean; user_id?: number; username?: string; is_admin?: boolean }> => {
return get('/api/v1/session');
export const verifySession = async (options?: RequestControlOptions): Promise<{ authenticated: boolean; initialized?: boolean; user_id?: number; username?: string; is_admin?: boolean }> => {
return get('/api/v1/session', undefined, options);
};
export const logout = async (): Promise<ApiResponse> => {
@@ -42,8 +42,8 @@ export const updateLoginCredentials = async (data: {
current_password: string;
new_username: string;
new_password?: string;
}): Promise<ApiResponse & { requires_relogin?: boolean }> => {
return put('/api/v1/session/credentials', data);
}, options?: RequestControlOptions): Promise<ApiResponse & { requires_relogin?: boolean }> => {
return put('/api/v1/session/credentials', data, options);
};
// Accounts
@@ -907,11 +907,11 @@ export const updateAccountAISettings = async (cookieId: string, settings: Partia
return put(`/api/v1/settings/ai-reply/${cookieId}`, payload);
}
export const fetchAIModels = async (baseUrl: string, apiKey: string = ''): Promise<string[]> => {
export const fetchAIModels = async (baseUrl: string, apiKey: string = '', options?: RequestControlOptions): Promise<string[]> => {
const result = await post<AIModelsResponse>('/api/v1/settings/ai-models', {
base_url: baseUrl,
api_key: apiKey,
});
}, options);
return result.models || [];
};
@@ -0,0 +1,20 @@
import{j as e,r,c as Ls,b as Ee,d as ar}from"./react-vendor-C_od1ZSF.js";import{L as rr,U as fa,M as gs,C as Rs,B as ya,S as ja,Z as bs,a as kt,b as Is,G as Ms,c as Os,d as Ps,e as lr,f as Na,g as nt,A as Bs,D as nr,P as va,h as Bt,E as _a,T as ir,i as or,j as Se,X as Re,k as cr,l as dr,m as Es,n as wa,o as tt,p as Ke,q as ka,K as xr,r as ct,s as lt,Q as as,t as xt,u as jt,v as $t,R as We,w as Ca,x as mr,y as Ve,z as _t,F as Dt,H as st,I as qs,J as Nt,N as ur,O as pr,V as hr,W as Sa,Y as Aa,_ as La,$ as gr,a0 as br,a1 as rs,a2 as zt,a3 as fs,a4 as fr,a5 as yr,a6 as ys,a7 as Fs,a8 as jr,a9 as Nr,aa as Mt,ab as zs,ac as Ht,ad as Ra,ae as vr,af as _r,ag as ts,ah as Ia,ai as wr,aj as kr,ak as Cr,al as Sr,am as Ar,an as Lr,ao as Us}from"./icons-vendor-i_74xDZy.js";import{R as Zt,B as Rr,X as Ws,Y as Gs,T as Yt,a as Ir,C as js,A as Or,b as Pr,c as Er,P as Js,d as Qs,L as Tr}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))l(n);new MutationObserver(n=>{for(const m of n)if(m.type==="childList")for(const p of m.addedNodes)p.tagName==="LINK"&&p.rel==="modulepreload"&&l(p)}).observe(document,{childList:!0,subtree:!0});function a(n){const m={};return n.integrity&&(m.integrity=n.integrity),n.referrerPolicy&&(m.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?m.credentials="include":n.crossOrigin==="anonymous"?m.credentials="omit":m.credentials="same-origin",m}function l(n){if(n.ep)return;n.ep=!0;const m=a(n);fetch(n.href,m)}})();const $r=({className:t="w-full h-full text-white"})=>e.jsx("svg",{className:t,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),Ns=({sizeClass:t="w-12 h-12",logoClassName:s="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${t} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgb(var(--color-brand))"}),e.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23Line truncated
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(Is,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:Fe,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:me,children:"取消"}),e.jsxs("button",{onClick:c,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:me,children:[me?e.jsx(Se,{className:"w-4 h-4 animate-spin"}):e.jsx(tt,{className:"w-4 h-4"}),me?"保存中...":"保存"]})]})})]})}),document.body)]})},Tn=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],$n=t=>{const s=typeof t=="object"&&t!==null?t:{},a=Array.isArray(s.results)?s.results:[];return{total:Number(s.total||0),success_count:Number(s.success_count||0),failed_count:Number(s.failed_count||0),results:a.map(Dn)}},Dn=t=>{const s=typeof t=="object"&&t!==null?t:{};return{order_id:String(s.order_id||"unknown"),success:s.success===!0,message:String(s.message||"")}},Mn=t=>(t==null?void 0:t.results.filter(Bn))||[],Bn=t=>!t.success,qn=(t,s)=>t!==null&&!s,Fn=t=>{if(!t)return"请选择订单文件";const s=t.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(s)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},dt=(t,s)=>t===s,zn=(t,s)=>t instanceof Error&&t.message?t.message:s,Un=({filter:t,onFilterChange:s,accountFilter:a,onAccountFilterChange:l,accounts:n,accountName:m,searchText:p,onSearchChange:f})=>{const u=b=>s(b.currentTarget.dataset.status||"all"),v=b=>l(b.target.value),x=b=>f(b.target.value);return e.jsxs("div",{className:"p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-surface-muted",children:[e.jsx("div",{className:"flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full",children:Tn.map(b=>e.jsx("button",{"data-status":b.key,onClick:u,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${t===b.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:b.label},b.key))}),e.jsxs("div",{className:"flex w-full md:w-auto flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(xt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{"aria-label":"按账号筛选订单",value:a,onChange:v,className:"ios-input pl-10 pr-9 py-2.5 rounded-xl w-full sm:w-56 bg-white border-none shadow-sm",children:[e.jsx("option",{value:"",children:"全部账号"}),n.map(b=>e.jsx("option",{value:b.id,children:m(b.id)},b.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(_t,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-brand transition-colors"}),e.jsx("input",{type:"text",placeholder:"搜索订单号/商品/买家...",value:p,onChange:x,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},Wn=t=>{const s=m=>{var p;t.setImportFile(((p=m.target.files)==null?void 0:p[0])||null)},a=()=>t.closeImportModal(),l=()=>void t.handleImportOrders(),n=()=>void t.handleRetryImport();return t.showImportModal?Ee.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"插入订单"}),e.jsx("button",{onClick:a,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(Re,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"选择Excel文件"}),e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv,.json",onChange:s,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持 .xl Line truncated
VIP-002
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["预览:",a.appendPreview.length," 个有效卡密,空行自动忽略。"]})]}),a.appendError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-200 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:a.appendError}),e.jsx("button",{type:"button",onClick:x,disabled:a.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),a.appendResult&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",a.appendResult.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:p,className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),a.batchTab==="create"?e.jsxs("button",{onClick:R,disabled:!a.batchFile||a.batchBusy,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(Se,{className:"w-4 h-4 animate-spin"}):e.jsx(Dt,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:z,disabled:!a.appendTargetId||a.appendPreview.length===0||a.batchBusy||t.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(Se,{className:"w-4 h-4 animate-spin"}):e.jsx(st,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"追加卡密"]})]})]})}),document.body):null},Kn=({type:t})=>{switch(t){case"text":return e.jsx(Aa,{className:"w-5 h-5 text-blue-500"});case"image":return e.jsx(Sa,{className:"w-5 h-5 text-purple-500"});case"api":return e.jsx(hr,{className:"w-5 h-5 text-blue-500"});default:return e.jsx(Rs,{className:"w-5 h-5 text-gray-500"})}},Hn=(t,s,a)=>{const l=a.trim().toLocaleLowerCase();return t.filter(n=>(!s||n.type===s)&&(!l||n.name.toLocaleLowerCase().includes(l)))},Ja=t=>t.split(`
`).map(s=>s.trim()).filter(Boolean),Zn=(t,s,a)=>!!(t&&Ja(s).length>0&&!a),yt=(t,s,a,l)=>t===s&&a===l,Yn=()=>{const[t,s]=r.useState([]),[a,l]=r.useState(!0),n=r.useRef(0),m=r.useRef(null),p=r.useCallback(async()=>{var v;const f=++n.current;(v=m.current)==null||v.abort();const u=new AbortController;m.current=u,l(!0);try{const x=await $s({signal:u.signal});if(f!==n.current)return;s(x)}catch(x){f===n.current&&!u.signal.aborted&&console.error("加载卡密库存失败:",x)}finally{f===n.current&&l(!1)}},[]);return r.useEffect(()=>(p(),()=>{var u;n.current+=1,(u=m.current)==null||u.abort()}),[p]),{cards:t,setCards:s,loading:a,loadCards:p}},Xn=t=>{const s=t.dataCards,a=t.loadCards,[l,n]=r.useState(!1),[m,p]=r.useState("create"),[f,u]=r.useState(null),[v,x]=r.useState(null),[b,_]=r.useState(!1),[R,z]=r.useState(""),[j,I]=r.useState(""),[P,U]=r.useState(null),[Z,ee]=r.useState(""),k=r.useRef(0),S=r.useRef(null),H=r.useRef(""),M=r.useMemo(()=>Ja(j),[j]),W=r.useCallback(()=>{var C;p("create"),u(null),x(null),z((C=s[0])!=null&&C.id?String(s[0].id):""),I(""),U(null),ee(""),n(!0)},[s]),d=r.useCallback(()=>{var C;k.current+=1,(C=S.current)==null||C.abort(),_(!1),n(!1)},[]),D=r.useCallback(async()=>{var A;if(!f||b)return;const C=++k.current;(A=S.current)==null||A.abort();const T=new AbortController;S.current=T,_(!0),x(null);try{const G=await El(f,{signal:T.signal});if(!yt(C,k.current,"",""))return;x(G),G.created>0&&await a()}catch(G){if(!yt(C,k.current,"",""))return;x({error:(G==null?void 0:G.message)||"上传失败"})}finally{yt(C,k.current,"","")&&_(!1)}},[b,f,a]),K=r.useCallback(async()=>{var G;if(!Zn(R,j,b))return;const C=R,T=++k.current;H.current=C,(G=S.current)==null||G.abort();const A=new AbortController;S.current=A,_(!0),U(null),ee("");try{const F=await Tl(C,j,{signal:A.signal});if(!yt(T,k.current,C,R))return;U({added:F.added}),I(""),await a()}catch(F){if(!yt(T,k.current,C,R))return;ee((F==null?void 0:F.message)||"追加失败")}finally{yt(T,k.current,C,R)&&_(!1)}},[j,R,b,a]),O=r.useCallback(async()=>{await D()},[D]),h=r.useCallback(async()=>{H.current&&R!==H.current||await K()},[R,K]);return{showBatchModal:l,setShowBatchModal:n,batchTab:m,setBatchTab:p,batchFile:f,setBatchFile:u,batchResult:v,batchBusy:b,appendTargetId:R,setAppendTargetId:z,appendContent:j,setAppendContent:I,appendResult:P,appendError:Z,appendPreview:M,openBatchModal:W,closeBatchModal:d,handleBatchCreate:D,handleBatchAppend:K,handleRetryBatchCreate:O,handleRetryBatchAppend:h}},la=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),ei=()=>{const{cards:t,loadCards:s}=Yn(),[a,l]=r.useState(!1),[n,m]=r.useState(!1),[p,f]=r.useState(null),[u,v]=r.useState({}),[x,b]=r.useState(la),[_,R]=r.useState(""),[z,j]=r.useState(""),I=r.useMemo(()=>t.filter(d=>d.type==="data"),[t]),P=Xn({dataCards:I,loadCards:s}),U=d=>{var D,K,O,h,C;f(d),v({id:d.id,name:d.name||"",type:d.type||"text",api_url:((D=d.api_config)==null?void 0:D.url)||"",api_method:((K=d.api_config)==null?void 0:K.method)||"GET",api_timeout:((O=d.api_config)==null?void 0:O.timeout)||10,api_headers:((h=d.api_config)==null?void 0:h.headers)||"",api_params:((C=d.api_config)==null?void 0:C.params)||"",text_content:d.text_content||"",data_content:d.data_content||"",image_url:d.image_url||"",delay_seconds:d.delay_seconds||0,description:d.description||"",enabled:d.enabled}),l(!0)},Z=async()=>{var d,D,K,O,h,C,T,A;if(p){if(!((d=u.name)!=null&&d.trim())){alert("请输入卡密名称");return}if(!u.type){alert("请选择卡密类型");return}try{const G={name:u.name.trim(),type:u.type,description:(D=u.description)==null?void 0:D.trim(),delay_seconds:u.delay_seconds||0,enabled:u.enabled??!0};u.type==="api"?G.api_config={url:((K=u.api_url)==null?void 0:K.trim())||"",method:u.api_method,timeout:u.api_timeout||10,headers:((O=u.api_headers)==null?void 0:O.trim())||void 0,params:((h=u.api_params)==null?void 0:h.trim())||void 0}:u.type==="text"?G.text_content=((C=u.text_content)==null?void 0:C.trim())||"":u.type==="data"?G.data_content=((T=u.data_content)==null?void 0:T.trim())||"":u.type==="image"&&(G.image_url=((A=u.image_url)==null?void 0:A.trim())||""),await Ys(p.id,G),l(!1),await s()}catch(G){console.error("更新卡密失败:",G),alert("更新失败,请重试")}}},ee=async d=>{if(confirm("确认删除该卡密吗?"))try{await Pl(d),await s()}catch(D){console.error("删除卡密失败:",D),alert("删除失败,请重试")}},k=async()=>{if(!x.name.trim()){alert("请输入卡密名称");return}if(!x.content.trim()){alert(x.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const d={name:x.name.trim(),type:x.type,description:x.description.trim(),enabled:x.enabled,delay_seconds:x.delay_seconds};x.type==="text"&&(d.text_content=x.content.trim()),x.type==="data"&&(d.data_content=x.content.trim()),x.type==="image"&&(d.image_url=x.content.trim()),x.type==="api"&&(d.api_config={url:x.content.trim(),method:x.a Line truncated
VIP-MONTH-002
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(T=>T.map(A=>`"${String(A).replace(/"/g,'""')}"`).join(",")).join(`
`),O=new Blob(["\uFEFF"+K],{type:"text/csv;charset=utf-8"}),h=URL.createObjectURL(O),C=document.createElement("a");C.href=h,C.download="卡密组批量导入模板.csv",document.body.appendChild(C),C.click(),C.remove(),URL.revokeObjectURL(h)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"卡密库存"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理自动发货的卡密、链接或图片资源。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:P.openBatchModal,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(Dt,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>m(!0),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(st,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-gray-50 bg-surface-muted p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative sm:w-48",children:[e.jsx(La,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsxs("select",{"aria-label":"按卡密类型筛选",value:_,onChange:d=>R(d.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(_t,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"按卡密名称搜索",placeholder:"搜索卡密名称...",value:z,onChange:d=>j(d.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]})]}),e.jsxs("div",{className:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",M.length," / ",t.length," 组"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"w-[23%] px-5 py-5",children:"卡密名称"}),e.jsx("th",{className:"w-[8%] px-3 py-5",children:"卡密组ID"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"类型"}),e.jsx("th",{className:"w-[27%] px-5 py-5",children:"内容/库存"}),e.jsx("th",{className:"w-[19%] px-5 py-5",children:"描述"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"状态"}),e.jsx("th",{className:"w-[9%] px-3 py-5 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:M.map(d=>{let D="";return d.type==="data"&&d.data_content?D=`库存: ${d.data_content.split(`
`).filter(O=>O.trim()).length} 条`:d.type==="text"&&d.text_content?D=d.text_content:d.type==="api"&&d.api_config?D=d.api_config.url:d.type==="image"&&d.image_url&&(D="图片链接"),e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(Kn,{type:d.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:d.name,children:d.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:()=>H(d.id),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:d.id}),e.jsx(gr,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${d.type==="text"?"bg-blue-50 text-blue-600":d.type==="data"?"bg-purple-50 text-purple-600":d.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:d.type==="text"?"文本":d.type==="data"?"批量":d.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:D,children:D})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:d.description||"-",children:d.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:()=>S(d),className:`w-12 h-8 rounded-full relative transition-colors ${d.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${d.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:()=>U(d),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(Nt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>ee(d.id),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(Ve,{className:"h-4 w-4"})})]})})]},d.id)})})]})}),M.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(va,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:t.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),a&&p&&Ee.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:()=>l(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(Re,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:u.name||"",onChange:d=>v({...u,name:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:u.type||"text",onChange:d=>v({...u,type:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(p==null?void 0:p.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),u.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:u.api_url||"",onChange:d=>v({...u,api_url:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxLine truncated
卡号1:密码1
卡号2:密码2
或者
兑换码1
兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:u.data_content?u.data_content.split(`
`).filter(d=>d.trim()).length:0})," 条"]})]})]}),u.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:u.image_url||"",onChange:d=>v({...u,image_url:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),u.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:u.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:d=>{d.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"}})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:u.delay_seconds||0,onChange:d=>v({...u,delay_seconds:parseInt(d.target.value)||0}),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:u.description||"",onChange:d=>v({...u,description:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:()=>v({...u,enabled:!u.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${u.enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${u.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>l(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:Z,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(tt,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),n&&Ee.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:()=>m(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(Re,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:x.name,onChange:d=>b({...x,name:d.target.value}),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>b({...x,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${x.type==="data"?"bg-brand text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(Rs,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>b({...x,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${x.type==="text"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(Aa,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>b({...x,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${x.type==="image"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children: Line truncated
CODE-789012
...`:"请输入每次发货时发送的固定文字"}),x.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-brand",children:x.content.split(`
`).filter(d=>d.trim()).length})," 条"]})]}),x.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:x.api_method,onChange:d=>b({...x,api_method:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:x.api_timeout,onChange:d=>b({...x,api_timeout:parseInt(d.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:x.api_headers,onChange:d=>b({...x,api_headers:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:x.api_params,onChange:d=>b({...x,api_params:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:x.description,onChange:d=>b({...x,description:d.target.value}),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:x.delay_seconds,onChange:d=>b({...x,delay_seconds:parseInt(d.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>m(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:k,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(st,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),e.jsx(Vn,{dataCards:I,downloadCardTemplate:W,...P})]})},na="ydisks-amap-js-api",ti="c9b68d4ce9a2a97f22a4a439404488ca";let It=null;const si=()=>ti,ai=()=>window.AMap?Promise.resolve(window.AMap):It||(It=new Promise((t,s)=>{const a=document.getElementById(na),l=a||document.createElement("script"),n=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(p)},m=()=>{window.AMap?(n(),t(window.AMap)):(n(),s(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},p=window.setTimeout(()=>{n(),s(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=m,l.id=na,l.async=!0,l.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(si())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,l.onerror=()=>{n(),s(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},a||document.head.appendChild(l)}).catch(t=>{throw It=null,t}),It),es=t=>Number.isFinite(t)&&t!==0,ri=t=>{var n,m;const s=Number((n=t.location)==null?void 0:n.lng),a=Number((m=t.location)==null?void 0:m.lat),l={area:String(t.adname||"").trim(),city:String(t.cityname||"").trim(),division_id:String(t.adcode||"").trim(),longitude:s,latitude:a,poi_id:String(t.id||"").trim(),poi_name:String(t.name||"").trim(),province:String(t.pname||"").trim()};return!l.division_id||!l.province||!l.city||!l.poi_id||!l.poi_name||!es(s)||!es(a)||s<-180||s>180||a<-90||a>90?null:l},li=async(t,s)=>{if(!es(t)||!es(s)||t<-180||t>180||s<-90||s>90)throw new Error("经纬度无效");const a=await ai();return new Promise((l,n)=>{new a.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[t,s],1e3,(p,f)=>{var v;if(p!=="complete"){if(p==="no_data"){l([]);return}n(new Error("高德地图附近地址查询失败,请稍后重试"));return}const u=(((v=f==null?void 0:f.poiList)==null?void 0:v.pois)||[]).map(ri).filter(x=>x!==null);l(u)})})},ni=t=>t.find(s=>s.status==="running"||s.status==="canceling"),Ss=t=>t==="running"||t==="canceling",ii=t=>!!(t!=null&&t.previ Line truncated
`),Ie=new Blob(["\uFEFF"+pe],{type:"text/csv;charset=utf-8"}),Qe=URL.createObjectURL(Ie),Fe=document.createElement("a");Fe.href=Qe,Fe.download="批量铺货模板.csv",document.body.appendChild(Fe),Fe.click(),Fe.remove(),URL.revokeObjectURL(Qe)},At=()=>{T(c=>({...c,cookie_id:f||c.cookie_id})),U(!0)},mt=()=>{G(c=>({...c,cookie_id:f||c.cookie_id})),ee(!0)},ut=async c=>{if(!(c?f:A.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");S(!0),navigator.geolocation.getCurrentPosition(async pe=>{try{const Ie=await li(pe.coords.longitude,pe.coords.latitude);if(!Ie.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");c?(y(Ie),E(Ie[0])):(M(Ie),d(Ie[0]))}catch(Ie){alert((Ie==null?void 0:Ie.message)||"获取发货地失败")}finally{S(!1)}},pe=>{S(!1),alert(pe.code===pe.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},Lt=c=>l.filter(Q=>Q.cookie_id===c.cookie_id&&Q.item_id===c.item_id).length>0?l.filter(Q=>Q.cookie_id===c.cookie_id&&Q.item_id===c.item_id):l.filter(Q=>Q.cookie_id===c.cookie_id&&!Q.item_id),pt=r.useMemo(()=>new Map(m.map(c=>[c.id,c])),[m]),ht=r.useMemo(()=>v?s.filter(c=>c.cookie_id===v):s,[v,s]),Ye=c=>{const Q=pt.get(c),pe=(Q==null?void 0:Q.remark)||(Q==null?void 0:Q.nickname);return pe?`${pe} · ${c.slice(0,6)}`:`账号 ${c.slice(0,8)}`},gt=c=>{const Q=pt.get(c);return(Q==null?void 0:Q.remark)||(Q==null?void 0:Q.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(br,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-account-filter","aria-label":"按账号筛选商品列表",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:v,onChange:c=>x(c.target.value),children:[e.jsx("option",{value:"",children:"全部账号"}),m.map(c=>e.jsx("option",{value:c.id,children:Ye(c.id)},c.id))]})]})]}),e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-sync-account",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"同步商品账号"}),e.jsxs("div",{className:"relative",children:[e.jsx(xt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-sync-account","aria-label":"选择要同步商品的账号",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:f,onChange:c=>u(c.target.value),children:[e.jsx("option",{value:"",children:"请选择账号"}),m.map(c=>e.jsx("option",{value:c.id,children:Ye(c.id)},c.id))]})]})]}),e.jsxs("button",{onClick:Ae,disabled:b||!f,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(We,{className:`w-4 h-4 ${b?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:At,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(st,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:mt,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-500 text-white hover:bg-emerald-600 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(rs,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void te(),className:"px-5 py-3 rounded-2xl font-bold bg-brand text-white hover:bg-brand-highlight transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[e.jsx(zt,{className:"w-4 h-4"}),de&&["running","canceling"].includes(de.status)?"继续批量任务":"批量铺货"]}),de&&!["running","canceling"].includes(de.status)&&e.jsx("button",{onClick:()=>void Ce(),className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"最近批次结果"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[ht.map(c=>{const Q=Lt(c),pe=Q.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relative flex fle Line truncated
@@ -1,20 +0,0 @@
import{j as e,r,c as ks,b as Te,d as Xa}from"./react-vendor-C_od1ZSF.js";import{L as er,U as ha,M as ms,C as Cs,B as ga,S as ba,Z as us,a as wt,b as Ss,G as Ts,c as As,d as Ls,e as tr,f as fa,g as lt,A as Es,D as sr,P as ya,h as Mt,E as ja,T as ar,i as rr,j as Se,X as Ie,k as lr,l as nr,m as Is,n as Na,o as et,p as Ke,q as va,K as ir,r as ot,s as rt,Q as Xt,t as dt,u as yt,v as Et,R as We,w as _a,x as or,y as Ve,z as vt,F as $t,H as tt,I as $s,J as jt,N as cr,O as dr,V as xr,W as wa,Y as ka,_ as Ca,$ as mr,a0 as ur,a1 as es,a2 as Ft,a3 as ps,a4 as pr,a5 as hr,a6 as hs,a7 as Ds,a8 as gr,a9 as br,aa as Dt,ab as Ms,ac as Jt,ad as Sa,ae as fr,af as yr,ag as Zt,ah as Aa,ai as jr,aj as Nr,ak as vr,al as _r,am as wr,an as kr,ao as Bs}from"./icons-vendor-i_74xDZy.js";import{R as Qt,B as Cr,X as qs,Y as Fs,T as Vt,a as Sr,C as gs,A as Ar,b as Lr,c as Ir,P as zs,d as Us,L as Rr}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))l(n);new MutationObserver(n=>{for(const m of n)if(m.type==="childList")for(const p of m.addedNodes)p.tagName==="LINK"&&p.rel==="modulepreload"&&l(p)}).observe(document,{childList:!0,subtree:!0});function a(n){const m={};return n.integrity&&(m.integrity=n.integrity),n.referrerPolicy&&(m.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?m.credentials="include":n.crossOrigin==="anonymous"?m.credentials="omit":m.credentials="same-origin",m}function l(n){if(n.ep)return;n.ep=!0;const m=a(n);fetch(n.href,m)}})();const Or=({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"})})}),bs=({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(Ss,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:Fe,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:ue,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:ue,children:[ue?e.jsx(Se,{className:"w-4 h-4 animate-spin"}):e.jsx(et,{className:"w-4 h-4"}),ue?"保存中...":"保存"]})]})})]})}),document.body)]})},Rn=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],On=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(Pn)}},Pn=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||"")}},Tn=t=>(t==null?void 0:t.results.filter(En))||[],En=t=>!t.success,$n=(t,s)=>t!==null&&!s,Dn=t=>{if(!t)return"请选择订单文件";const s=t.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(s)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},ct=(t,s)=>t===s,Mn=(t,s)=>t instanceof Error&&t.message?t.message:s,Bn=({filter:t,onFilterChange:s,accountFilter:a,onAccountFilterChange:l,accounts:n,accountName:m,searchText:p,onSearchChange:f})=>{const u=g=>s(g.currentTarget.dataset.status||"all"),N=g=>l(g.target.value),x=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:Rn.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(dt,{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(g=>e.jsx("option",{value:g.id,children:m(g.id)},g.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(vt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-brand transition-colors"}),e.jsx("input",{type:"text",placeholder:"搜索订单号/商品/买家...",value:p,onChange:x,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},qn=t=>{const s=m=>{var p;t.setImportFile(((p=m.target.files)==null?void 0:p[0])||null)},a=()=>t.closeImportModal(),l=()=>void t.handleImportOrders(),n=()=>void t.handleRetryImport();return t.showImportModal?Te.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(Ie,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"选择Excel文件"}),e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv,.json",onChange:s,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持 .xl Line truncated
VIP-002
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["预览:",a.appendPreview.length," 个有效卡密,空行自动忽略。"]})]}),a.appendError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-200 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:a.appendError}),e.jsx("button",{type:"button",onClick:x,disabled:a.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),a.appendResult&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",a.appendResult.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:p,className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),a.batchTab==="create"?e.jsxs("button",{onClick:P,disabled:!a.batchFile||a.batchBusy,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(Se,{className:"w-4 h-4 animate-spin"}):e.jsx($t,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:W,disabled:!a.appendTargetId||a.appendPreview.length===0||a.batchBusy||t.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(Se,{className:"w-4 h-4 animate-spin"}):e.jsx(tt,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"追加卡密"]})]})]})}),document.body):null},Gn=({type:t})=>{switch(t){case"text":return e.jsx(ka,{className:"w-5 h-5 text-blue-500"});case"image":return e.jsx(wa,{className:"w-5 h-5 text-purple-500"});case"api":return e.jsx(xr,{className:"w-5 h-5 text-blue-500"});default:return e.jsx(Cs,{className:"w-5 h-5 text-gray-500"})}},Jn=(t,s,a)=>{const l=a.trim().toLocaleLowerCase();return t.filter(n=>(!s||n.type===s)&&(!l||n.name.toLocaleLowerCase().includes(l)))},Ua=t=>t.split(`
`).map(s=>s.trim()).filter(Boolean),Qn=(t,s,a)=>!!(t&&Ua(s).length>0&&!a),ft=(t,s,a,l)=>t===s&&a===l,Vn=()=>{const[t,s]=r.useState([]),[a,l]=r.useState(!0),n=r.useRef(0),m=r.useRef(null),p=r.useCallback(async()=>{var N;const f=++n.current;(N=m.current)==null||N.abort();const u=new AbortController;m.current=u,l(!0);try{const x=await Os({signal:u.signal});if(f!==n.current)return;s(x)}catch(x){f===n.current&&!u.signal.aborted&&console.error("加载卡密库存失败:",x)}finally{f===n.current&&l(!1)}},[]);return r.useEffect(()=>(p(),()=>{var u;n.current+=1,(u=m.current)==null||u.abort()}),[p]),{cards:t,setCards:s,loading:a,loadCards:p}},Kn=t=>{const s=t.dataCards,a=t.loadCards,[l,n]=r.useState(!1),[m,p]=r.useState("create"),[f,u]=r.useState(null),[N,x]=r.useState(null),[g,v]=r.useState(!1),[P,W]=r.useState(""),[j,T]=r.useState(""),[D,G]=r.useState(null),[K,Z]=r.useState(""),S=r.useRef(0),L=r.useRef(null),V=r.useRef(""),q=r.useMemo(()=>Ua(j),[j]),z=r.useCallback(()=>{var w;p("create"),u(null),x(null),W((w=s[0])!=null&&w.id?String(s[0].id):""),T(""),G(null),Z(""),n(!0)},[s]),d=r.useCallback(()=>{var w;S.current+=1,(w=L.current)==null||w.abort(),v(!1),n(!1)},[]),M=r.useCallback(async()=>{var I;if(!f||g)return;const w=++S.current;(I=L.current)==null||I.abort();const E=new AbortController;L.current=E,v(!0),x(null);try{const U=await Il(f,{signal:E.signal});if(!ft(w,S.current,"",""))return;x(U),U.created>0&&await a()}catch(U){if(!ft(w,S.current,"",""))return;x({error:(U==null?void 0:U.message)||"上传失败"})}finally{ft(w,S.current,"","")&&v(!1)}},[g,f,a]),J=r.useCallback(async()=>{var U;if(!Qn(P,j,g))return;const w=P,E=++S.current;V.current=w,(U=L.current)==null||U.abort();const I=new AbortController;L.current=I,v(!0),G(null),Z("");try{const F=await Rl(w,j,{signal:I.signal});if(!ft(E,S.current,w,P))return;G({added:F.added}),T(""),await a()}catch(F){if(!ft(E,S.current,w,P))return;Z((F==null?void 0:F.message)||"追加失败")}finally{ft(E,S.current,w,P)&&v(!1)}},[j,P,g,a]),R=r.useCallback(async()=>{await M()},[M]),_=r.useCallback(async()=>{V.current&&P!==V.current||await J()},[P,J]);return{showBatchModal:l,setShowBatchModal:n,batchTab:m,setBatchTab:p,batchFile:f,setBatchFile:u,batchResult:N,batchBusy:g,appendTargetId:P,setAppendTargetId:W,appendContent:j,setAppendContent:T,appendResult:D,appendError:K,appendPreview:q,openBatchModal:z,closeBatchModal:d,handleBatchCreate:M,handleBatchAppend:J,handleRetryBatchCreate:R,handleRetryBatchAppend:_}},ta=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),Hn=()=>{const{cards:t,loadCards:s}=Vn(),[a,l]=r.useState(!1),[n,m]=r.useState(!1),[p,f]=r.useState(null),[u,N]=r.useState({}),[x,g]=r.useState(ta),[v,P]=r.useState(""),[W,j]=r.useState(""),T=r.useMemo(()=>t.filter(d=>d.type==="data"),[t]),D=Kn({dataCards:T,loadCards:s}),G=d=>{var M,J,R,_,w;f(d),N({id:d.id,name:d.name||"",type:d.type||"text",api_url:((M=d.api_config)==null?void 0:M.url)||"",api_method:((J=d.api_config)==null?void 0:J.method)||"GET",api_timeout:((R=d.api_config)==null?void 0:R.timeout)||10,api_headers:((_=d.api_config)==null?void 0:_.headers)||"",api_params:((w=d.api_config)==null?void 0:w.params)||"",text_content:d.text_content||"",data_content:d.data_content||"",image_url:d.image_url||"",delay_seconds:d.delay_seconds||0,description:d.description||"",enabled:d.enabled}),l(!0)},K=async()=>{var d,M,J,R,_,w,E,I;if(p){if(!((d=u.name)!=null&&d.trim())){alert("请输入卡密名称");return}if(!u.type){alert("请选择卡密类型");return}try{const U={name:u.name.trim(),type:u.type,description:(M=u.description)==null?void 0:M.trim(),delay_seconds:u.delay_seconds||0,enabled:u.enabled??!0};u.type==="api"?U.api_config={url:((J=u.api_url)==null?void 0:J.trim())||"",method:u.api_method,timeout:u.api_timeout||10,headers:((R=u.api_headers)==null?void 0:R.trim())||void 0,params:((_=u.api_params)==null?void 0:_.trim())||void 0}:u.type==="text"?U.text_content=((w=u.text_content)==null?void 0:w.trim())||"":u.type==="data"?U.data_content=((E=u.data_content)==null?void 0:E.trim())||"":u.type==="image"&&(U.image_url=((I=u.image_url)==null?void 0:I.trim())||""),await Vs(p.id,U),l(!1),await s()}catch(U){console.error("更新卡密失败:",U),alert("更新失败,请重试")}}},Z=async d=>{if(confirm("确认删除该卡密吗?"))try{await Ll(d),await s()}catch(M){console.error("删除卡密失败:",M),alert("删除失败,请重试")}},S=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(E=>E.map(I=>`"${String(I).replace(/"/g,'""')}"`).join(",")).join(`
`),R=new Blob(["\uFEFF"+J],{type:"text/csv;charset=utf-8"}),_=URL.createObjectURL(R),w=document.createElement("a");w.href=_,w.download="卡密组批量导入模板.csv",document.body.appendChild(w),w.click(),w.remove(),URL.revokeObjectURL(_)};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:D.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($t,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>m(!0),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(tt,{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(Ca,{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=>P(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(vt,{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:W,onChange:d=>j(d.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]})]}),e.jsxs("div",{className:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",q.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:q.map(d=>{let M="";return d.type==="data"&&d.data_content?M=`库存: ${d.data_content.split(`
`).filter(R=>R.trim()).length} 条`:d.type==="text"&&d.text_content?M=d.text_content:d.type==="api"&&d.api_config?M=d.api_config.url:d.type==="image"&&d.image_url&&(M="图片链接"),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(Gn,{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:()=>V(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(mr,{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:M,children:M})}),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:()=>L(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(jt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>Z(d.id),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(Ve,{className:"h-4 w-4"})})]})})]},d.id)})})]})}),q.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(ya,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:t.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),a&&p&&Te.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(Ie,{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=>N({...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=>N({...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=>N({...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=>N({...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=>N({...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=>N({...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:()=>N({...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(et,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),n&&Te.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:()=>m(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(Ie,{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=>g({...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:()=>g({...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(Cs,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>g({...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(ka,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>g({...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=>g({...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=>g({...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=>g({...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=>g({...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=>g({...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=>g({...x,delay_seconds:parseInt(d.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>m(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:S,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(tt,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),e.jsx(Wn,{dataCards:T,downloadCardTemplate:z,...D})]})},sa="ydisks-amap-js-api",Zn="c9b68d4ce9a2a97f22a4a439404488ca";let It=null;const Yn=()=>Zn,Xn=()=>window.AMap?Promise.resolve(window.AMap):It||(It=new Promise((t,s)=>{const a=document.getElementById(sa),l=a||document.createElement("script"),n=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(p)},m=()=>{window.AMap?(n(),t(window.AMap)):(n(),s(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},p=window.setTimeout(()=>{n(),s(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=m,l.id=sa,l.async=!0,l.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(Yn())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,l.onerror=()=>{n(),s(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},a||document.head.appendChild(l)}).catch(t=>{throw It=null,t}),It),Ht=t=>Number.isFinite(t)&&t!==0,ei=t=>{var n,m;const s=Number((n=t.location)==null?void 0:n.lng),a=Number((m=t.location)==null?void 0:m.lat),l={area:String(t.adname||"").trim(),city:String(t.cityname||"").trim(),division_id:String(t.adcode||"").trim(),longitude:s,latitude:a,poi_id:String(t.id||"").trim(),poi_name:String(t.name||"").trim(),province:String(t.pname||"").trim()};return!l.division_id||!l.province||!l.city||!l.poi_id||!l.poi_name||!Ht(s)||!Ht(a)||s<-180||s>180||a<-90||a>90?null:l},ti=async(t,s)=>{if(!Ht(t)||!Ht(s)||t<-180||t>180||s<-90||s>90)throw new Error("经纬度无效");const a=await Xn();return new Promise((l,n)=>{new a.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[t,s],1e3,(p,f)=>{var N;if(p!=="complete"){if(p==="no_data"){l([]);return}n(new Error("高德地图附近地址查询失败,请稍后重试"));return}const u=(((N=f==null?void 0:f.poiList)==null?void 0:N.pois)||[]).map(ei).filter(x=>x!==null);l(u)})})},si=t=>t.find(s=>s.status==="running"||s.status==="canceling"),_s=t=>t==="running"||t==="canceling",ai=t=>!!(t!=null&&t.previ Line truncated
`),Re=new Blob(["\uFEFF"+he],{type:"text/csv;charset=utf-8"}),Qe=URL.createObjectURL(Re),Fe=document.createElement("a");Fe.href=Qe,Fe.download="批量铺货模板.csv",document.body.appendChild(Fe),Fe.click(),Fe.remove(),URL.revokeObjectURL(Qe)},St=()=>{E(c=>({...c,cookie_id:f||c.cookie_id})),G(!0)},xt=()=>{U(c=>({...c,cookie_id:f||c.cookie_id})),Z(!0)},mt=async c=>{if(!(c?f:I.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");L(!0),navigator.geolocation.getCurrentPosition(async he=>{try{const Re=await ti(he.coords.longitude,he.coords.latitude);if(!Re.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");c?(b(Re),$(Re[0])):(q(Re),d(Re[0]))}catch(Re){alert((Re==null?void 0:Re.message)||"获取发货地失败")}finally{L(!1)}},he=>{L(!1),alert(he.code===he.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},At=c=>l.filter(Q=>Q.cookie_id===c.cookie_id&&Q.item_id===c.item_id).length>0?l.filter(Q=>Q.cookie_id===c.cookie_id&&Q.item_id===c.item_id):l.filter(Q=>Q.cookie_id===c.cookie_id&&!Q.item_id),ut=r.useMemo(()=>new Map(m.map(c=>[c.id,c])),[m]),pt=r.useMemo(()=>N?s.filter(c=>c.cookie_id===N):s,[N,s]),Ye=c=>{const Q=ut.get(c),he=(Q==null?void 0:Q.remark)||(Q==null?void 0:Q.nickname);return he?`${he} · ${c.slice(0,6)}`:`账号 ${c.slice(0,8)}`},ht=c=>{const Q=ut.get(c);return(Q==null?void 0:Q.remark)||(Q==null?void 0:Q.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(ur,{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:c=>x(c.target.value),children:[e.jsx("option",{value:"",children:"全部账号"}),m.map(c=>e.jsx("option",{value:c.id,children:Ye(c.id)},c.id))]})]})]}),e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-sync-account",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"同步商品账号"}),e.jsxs("div",{className:"relative",children:[e.jsx(dt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-sync-account","aria-label":"选择要同步商品的账号",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:f,onChange:c=>u(c.target.value),children:[e.jsx("option",{value:"",children:"请选择账号"}),m.map(c=>e.jsx("option",{value:c.id,children:Ye(c.id)},c.id))]})]})]}),e.jsxs("button",{onClick:Ae,disabled: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(We,{className:`w-4 h-4 ${g?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:St,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(tt,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:xt,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-500 text-white hover:bg-emerald-600 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(es,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void Y(),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(Ft,{className:"w-4 h-4"}),oe&&["running","canceling"].includes(oe.status)?"继续批量任务":"批量铺货"]}),oe&&!["running","canceling"].includes(oe.status)&&e.jsx("button",{onClick:()=>void Ce(),className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"最近批次结果"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[pt.map(c=>{const Q=At(c),he=Q.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-CEH5GXBq.js"></script>
<script type="module" crossorigin src="/static/assets/index-7RF419ck.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">