阶段十:完成前端组件与 Hook 注释基线清零

This commit is contained in:
Christ committed 2026-08-15 04:44:06 +08:00
1 parent c90461226b
commit 6257fad453
43 files changed
+1094 -7356

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -626,3 +626,4 @@ npm --prefix frontend run build
| 2026-08-15 | 完成阶段 9 第四个 PR 切片“旧路由与剩余兼容字段最终审计” | 新增 API 兼容边界清单,明确旧服务端入口的保留条件、复用 handler 约束和删除证据要求;新增 React 架构测试,禁止生产 API 适配层重新调用未版本化 `/api/...` 路径;服务端新旧入口契约测试继续覆盖兼容行为,前端 185 个测试、类型检查和注释门禁通过并合并为一个可回滚提交 | 阶段 10:注释基线清零与严格门禁 |
| 2026-08-15 | 完成阶段 10 第一个 PR 切片“前端共享 types.ts 注释基线清零” | 为分页、会话、账号、聊天、订单、卡券、商品、自动化规则、统计、设置、AI、默认回复和通知 DTO 的全部字段补齐准确中文注释,解释字段职责、敏感性、状态和时间/数量单位;`frontend/types.ts` 历史注释基线清零,前端注释门禁、类型检查、185 个测试和生产构建通过并合并为一个可回滚提交 | 阶段 10:前端 services/api.ts 注释基线清零 |
| 2026-08-15 | 完成阶段 10 第二个 PR 切片“前端 services/api.ts 注释基线清零” | 为 API 适配层全部导出函数、局部变量、请求参数和内联响应字段补齐中文注释,明确认证、账号、聊天、订单、商品、卡密、自动化、设置和通知接口的数据职责;增强注释检查器对调用参数、类型字面量和循环变量内联注释的识别能力,`services/api.ts` 注释基线清零;前端注释门禁、类型检查和 185 个测试通过并合并为一个可回滚提交 | 阶段 10:前端 components/hooks 注释基线按领域清零 |
| 2026-08-15 | 完成阶段 10 第三个 PR 切片“前端 components/hooks 注释基线按领域清零” | 为账号、聊天、仪表盘、设置、规则、商品、卡密、订单、通知和二维码等组件、Hook、状态模块及其测试补齐函数、变量、回调和字段中文注释;补强注释检查器对箭头函数主体内联注释的识别,保持路由源码断言和 JSX 行为不变;目标目录注释基线清零,前端注释门禁、类型检查、185 个测试和生产构建通过并合并为一个可回滚提交 | 阶段 10:Go 核心领域注释基线按领域清零 |
@@ -19,7 +19,7 @@ export type UseAccountAutomationResult = AccountAutomationState & {
/** 管理账号自动评价和自动擦亮的设置、执行、取消与重试。 */
export const useAccountAutomation = ({ account, onSaved }: AccountAutomationOptions): UseAccountAutomationResult => {
// form 保存当前账号任务设置草稿。
const [form, setForm] = useState<AccountTaskSettings>(() => buildAccountTaskDefaults(account));
const [form, setForm] = useState<AccountTaskSettings>(/* 当前回调处理用户交互或异步状态变化。 */ () => buildAccountTaskDefaults(account));
// loading 表示账号任务设置是否正在读取。
const [loading, setLoading] = useState(true);
// saving 表示任务设置是否正在保存。
@@ -37,9 +37,11 @@ export const useAccountAutomation = ({ account, onSaved }: AccountAutomationOpti
// requestController 保存当前账号任务请求控制器。
const requestController = useRef<AbortController | null>(null);
useEffect(() => {
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => {
// sequence 请求序号。
const sequence = ++requestSequence.current;
requestController.current?.abort();
// controller 请求取消控制器。
const controller = new AbortController();
requestController.current = controller;
setForm(buildAccountTaskDefaults(account));
@@ -49,38 +51,41 @@ export const useAccountAutomation = ({ account, onSaved }: AccountAutomationOpti
setRunning('');
setRetryAction(null);
setLoading(true);
getAccountTaskSettings(account.id, { signal: controller.signal }).then(settings => {
getAccountTaskSettings(account.id, { signal: controller.signal }).then(/* 当前回调处理异步操作结果。 */ settings => {
if (!isCurrentAccountTaskRequest(requestSequence.current, sequence, controller.signal)) return;
setForm(settings);
}).catch(loadError => {
}).catch(/* 当前回调处理异步操作结果。 */ loadError => {
if (isCurrentAccountTaskRequest(requestSequence.current, sequence, controller.signal) && !isAccountTaskAbortError(loadError)) setError(accountTaskErrorMessage(loadError, '加载任务设置失败'));
}).finally(() => {
}).finally(/* 当前回调处理异步操作结果。 */ () => {
if (isCurrentAccountTaskRequest(requestSequence.current, sequence, controller.signal)) setLoading(false);
});
return () => controller.abort();
return /* 当前回调处理用户交互或异步状态变化。 */ () => controller.abort();
}, [account.id]);
useEffect(() => () => requestController.current?.abort(), []);
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => /* 当前回调同步 React 副作用和资源生命周期。 */ () => requestController.current?.abort(), []);
/** 保存任务设置并在成功后同步账号列表。 */
const save = useCallback(async (): Promise<void> => {
const save = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (): Promise<void> => {
if (!canStartAccountTask(saving, running)) return;
// sequence 请求序号。
const sequence = ++requestSequence.current;
requestController.current?.abort();
// controller 请求取消控制器。
const controller = new AbortController();
requestController.current = controller;
setSaving(true);
setError('');
setRetryAction(null);
try {
// stored 已保存数据。
const stored = await updateAccountTaskSettings(account.id, form, { signal: controller.signal });
if (!isCurrentAccountTaskRequest(requestSequence.current, sequence, controller.signal)) return;
setForm(stored);
onSaved(stored);
} catch (saveError) {
} catch (/* saveError 表示保存错误。 */ saveError) {
if (isCurrentAccountTaskRequest(requestSequence.current, sequence, controller.signal) && !isAccountTaskAbortError(saveError)) {
setError(accountTaskErrorMessage(saveError, '保存失败'));
setRetryAction(() => save);
setRetryAction(/* 当前回调处理用户交互或异步状态变化。 */ () => save);
}
} finally {
if (isCurrentAccountTaskRequest(requestSequence.current, sequence, controller.signal)) setSaving(false);
@@ -88,10 +93,12 @@ export const useAccountAutomation = ({ account, onSaved }: AccountAutomationOpti
}, [account.id, form, onSaved, running, saving]);
/** 保存设置后立即执行指定账号任务并刷新结果。 */
const run = useCallback(async (taskType: AccountTaskType): Promise<void> => {
const run = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (taskType: AccountTaskType): Promise<void> => {
if (!canStartAccountTask(saving, running) || !account.enabled) return;
// sequence 请求序号。
const sequence = ++requestSequence.current;
requestController.current?.abort();
// controller 请求取消控制器。
const controller = new AbortController();
requestController.current = controller;
setRunning(taskType);
@@ -100,16 +107,18 @@ export const useAccountAutomation = ({ account, onSaved }: AccountAutomationOpti
setRetryAction(null);
try {
await updateAccountTaskSettings(account.id, form, { signal: controller.signal });
// result 处理结果。
const result = await runAccountTask(account.id, taskType, { signal: controller.signal });
// stored 已保存数据。
const stored = await getAccountTaskSettings(account.id, { signal: controller.signal });
if (!isCurrentAccountTaskRequest(requestSequence.current, sequence, controller.signal)) return;
setSummary(result.summary);
setForm(stored);
onSaved(stored);
} catch (runError) {
} catch (/* runError 表示执行错误。 */ runError) {
if (isCurrentAccountTaskRequest(requestSequence.current, sequence, controller.signal) && !isAccountTaskAbortError(runError)) {
setError(accountTaskErrorMessage(runError, '任务执行失败'));
setRetryAction(() => () => run(taskType));
setRetryAction(/* 当前回调处理用户交互或异步状态变化。 */ () => /* 当前回调处理用户交互或异步状态变化。 */ () => run(taskType));
}
} finally {
if (isCurrentAccountTaskRequest(requestSequence.current, sequence, controller.signal)) setRunning('');
@@ -117,7 +126,7 @@ export const useAccountAutomation = ({ account, onSaved }: AccountAutomationOpti
}, [account.enabled, account.id, form, onSaved, running, saving]);
/** 重试最近一次保存或执行动作。 */
const retry = useCallback(async (): Promise<void> => {
const retry = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (): Promise<void> => {
if (retryAction) await retryAction();
}, [retryAction]);
@@ -16,6 +16,7 @@ test('账号任务默认设置继承账号配置并保持安全文案',
test('账号任务阻断重复提交并拒绝过期响应',
// 动作边界测试验证保存或执行中不会重复发起任务,账号切换后的旧响应不能写入。
() => {
// controller 请求取消控制器。
const controller = new AbortController();
expect(canStartAccountTask(false, '')).toBe(true);
expect(canStartAccountTask(true, '')).toBe(false);
@@ -11,8 +11,8 @@ const account = (overrides: Partial<AccountDetail> = {}): AccountDetail => ({
...overrides,
});
describe('Accounts runtime state', () => {
test('最新在线状态替换风控恢复中的旧提示', () => {
describe('Accounts runtime state', /* 当前回调处理用户交互或异步状态变化。 */ () => {
test('最新在线状态替换风控恢复中的旧提示', /* 当前回调处理用户交互或异步状态变化。 */ () => {
// result 是合并当前运行状态后的账号列表。
const result = mergeAccountRuntimeStatuses([account({
runtime_state: 'connecting',
@@ -31,13 +31,14 @@ describe('Accounts runtime state', () => {
expect(result[0]).toMatchObject({ runtime_state: 'online', runtime_message: '消息服务连接正常', runtime_connected: true });
});
test('晚到达的旧状态响应不会覆盖当前账号状态', () => {
test('晚到达的旧状态响应不会覆盖当前账号状态', /* 当前回调处理用户交互或异步状态变化。 */ () => {
// current 是当前页面已经展示的较新账号状态。
const current = account({
runtime_state: 'online',
runtime_message: '消息服务连接正常',
runtime_updated_at: '2026-07-13T13:16:02+08:00',
});
// result 处理结果。
const result = mergeAccountRuntimeStatuses([current], {
'account-1': {
state: 'connecting',
@@ -51,7 +52,7 @@ describe('Accounts runtime state', () => {
expect(result[0]).toBe(current);
});
test('缺少对应运行状态时保留原账号对象', () => {
test('缺少对应运行状态时保留原账号对象', /* 当前回调处理用户交互或异步状态变化。 */ () => {
// current 是没有新运行状态可合并的账号对象。
const current = account();
expect(mergeAccountRuntimeStatuses([current], {})[0]).toBe(current);
@@ -29,7 +29,9 @@ test('账号切换后只接受当前请求代次和账号的响应',
test('编辑子模块共享同一账号边界,旧绑定、AI 和密码登录响应全部失效',
// 三类异步子模块都使用相同的代次与账号判定,防止旧弹窗响应污染新账号。
() => {
// currentGeneration 当前请求代次,负责当前功能中的对应处理。
const currentGeneration = 4;
// currentAccountId 当前账号标识,负责当前功能中的对应处理。
const currentAccountId = 'account-4';
expect(isCurrentAccountRequest(3, currentGeneration, 'account-3', currentAccountId)).toBe(false);
expect(isCurrentAccountRequest(currentGeneration, currentGeneration, currentAccountId, currentAccountId)).toBe(true);
@@ -69,7 +69,7 @@ export const useAccountSubmodules = ({ editingAccount, setEditingAccount, setAct
/** 清理密码登录轮询定时器。 */
// clearPasswordTimerCallback 是 React 稳定的定时器清理函数。
const clearPasswordTimer = useCallback(() => {
const clearPasswordTimer = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ () => {
if (passwordTimer.current !== null) {
window.clearTimeout(passwordTimer.current);
passwordTimer.current = null;
@@ -78,7 +78,7 @@ export const useAccountSubmodules = ({ editingAccount, setEditingAccount, setAct
/** 加载当前账号通知渠道和绑定关系,并隔离过期响应。 */
// loadNotificationBindingsCallback 是通知绑定加载回调。
const loadNotificationBindings = useCallback(async (accountId: string): Promise<void> => {
const loadNotificationBindings = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (accountId: string): Promise<void> => {
// sequence 是通知绑定请求的递增代次。
const sequence = ++bindingsSequence.current;
bindingsAbort.current?.abort();
@@ -104,14 +104,14 @@ export const useAccountSubmodules = ({ editingAccount, setEditingAccount, setAct
/** 切换一个通知渠道绑定。 */
// toggleNotificationChannelCallback 是通知渠道切换回调。
const toggleNotificationChannel = useCallback((channelId: number) => {
setSelectedChannelIds(current => current.includes(channelId) ? current.filter(id => id !== channelId) : [...current, channelId]);
const toggleNotificationChannel = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ (channelId: number) => {
setSelectedChannelIds(/* 当前回调处理集合中的单个元素。 */ current => current.includes(channelId) ? current.filter(/* 当前回调处理集合中的单个元素。 */ id => id !== channelId) : [...current, channelId]);
setBindingsDirty(true);
}, []);
/** 打开账号编辑弹窗并并行读取绑定和长登录状态。 */
// openEditModalCallback 是账号编辑弹窗打开回调。
const openEditModal = useCallback(async (account: AccountDetail): Promise<void> => {
const openEditModal = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (account: AccountDetail): Promise<void> => {
// longLoginRequest 是当前长登录读取请求代次。
const longLoginRequest = ++longLoginSequence.current;
longLoginAbort.current?.abort();
@@ -136,24 +136,24 @@ export const useAccountSubmodules = ({ editingAccount, setEditingAccount, setAct
/** 切换官方长登录设置。 */
// handleLongLoginToggleCallback 是长登录设置切换回调。
const handleLongLoginToggle = useCallback(async (): Promise<void> => {
const handleLongLoginToggle = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (): Promise<void> => {
if (!editingAccount || longLogin.loading || longLogin.saving || !longLogin.canOpen) return;
// enabled 是本次准备提交的长登录开关值。
const enabled = !longLogin.enabled;
setLongLogin(current => ({ ...current, saving: true, error: '' }));
setLongLogin(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, saving: true, error: '' }));
try {
// result 保存长登录设置接口返回值。
const result = await setLongLoginSettings(editingAccount.id, enabled);
setLongLogin({ loading: false, saving: false, canOpen: result.can_open_long_login, enabled: result.enabled, error: '' });
} catch (error) {
} catch (/* error 表示错误。 */ error) {
// error 保存长登录设置保存失败原因。
setLongLogin(current => ({ ...current, saving: false, error: error instanceof Error ? error.message : '保存登录信息设置失败' }));
setLongLogin(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, saving: false, error: error instanceof Error ? error.message : '保存登录信息设置失败' }));
}
}, [editingAccount, longLogin]);
/** 打开 AI 设置并隔离过期账号响应。 */
// openAIModalCallback 是 AI 设置弹窗打开回调。
const openAIModal = useCallback(async (account: AccountDetail): Promise<void> => {
const openAIModal = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (account: AccountDetail): Promise<void> => {
// sequence 是 AI 设置请求的递增代次。
const sequence = ++aiSequence.current;
aiAbort.current?.abort();
@@ -168,7 +168,7 @@ export const useAccountSubmodules = ({ editingAccount, setEditingAccount, setAct
const settings = await getAccountAISettings(account.id, { signal: controller.signal });
if (!isCurrentAccountRequest(sequence, aiSequence.current, account.id, account.id)) return;
setAiSettings({ ai_enabled: settings.ai_enabled ?? false, max_discount_percent: settings.max_discount_percent ?? 10, max_discount_amount: settings.max_discount_amount ?? 100, max_bargain_rounds: settings.max_bargain_rounds ?? 3, custom_prompts: settings.custom_prompts ?? '' });
} catch (error) {
} catch (/* error 表示错误。 */ error) {
// error 保存 AI 设置读取失败原因。
if (isCurrentAccountRequest(sequence, aiSequence.current, account.id, account.id)) console.error('加载 AI 设置失败:', error);
} finally {
@@ -178,14 +178,14 @@ export const useAccountSubmodules = ({ editingAccount, setEditingAccount, setAct
/** 保存 AI 设置并刷新账号列表。 */
// handleSaveAISettingsCallback 是 AI 设置保存回调。
const handleSaveAISettings = useCallback(async (): Promise<void> => {
const handleSaveAISettings = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (): Promise<void> => {
if (!editingAccount || saving) return;
setSaving(true);
try {
await updateAccountAISettings(editingAccount.id, aiSettings);
setActiveModal(null);
await loadAccounts();
} catch (error) {
} catch (/* error 表示错误。 */ error) {
// error 保存 AI 设置保存失败原因。
console.error('更新 AI 设置失败:', error);
} finally { setSaving(false); }
@@ -193,7 +193,7 @@ export const useAccountSubmodules = ({ editingAccount, setEditingAccount, setAct
/** 保存账号编辑表单和通知绑定。 */
// handleSaveEditCallback 是账号编辑表单保存回调。
const handleSaveEdit = useCallback(async (): Promise<void> => {
const handleSaveEdit = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (): Promise<void> => {
if (!editingAccount || saving) return;
setSaving(true);
try {
@@ -210,7 +210,7 @@ export const useAccountSubmodules = ({ editingAccount, setEditingAccount, setAct
if (Object.keys(payload).length > 0) await updateAccountSettings(editingAccount.id, payload);
setActiveModal(null);
await loadAccounts();
} catch (error) {
} catch (/* error 表示错误。 */ error) {
// error 保存账号编辑保存失败原因。
console.error('更新账号失败:', error);
} finally { setSaving(false); }
@@ -218,21 +218,21 @@ export const useAccountSubmodules = ({ editingAccount, setEditingAccount, setAct
/** 按当前暂停时长重新暂停账号。 */
// handleRestartPauseCallback 是重新暂停账号回调。
const handleRestartPause = useCallback(async (): Promise<void> => {
const handleRestartPause = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (): Promise<void> => {
if (!editingAccount || editForm.pause_duration <= 0 || saving) return;
setSaving(true);
try {
// result 保存重新暂停接口返回的账号状态。
const result = await updateAccountPauseDuration(editingAccount.id, editForm.pause_duration);
setEditingAccount(current => current ? { ...current, pause_duration: editForm.pause_duration, paused: result?.paused === true, paused_until: Number(result?.paused_until || 0) } : current);
setEditingAccount(/* 当前回调处理用户交互或异步状态变化。 */ current => current ? { ...current, pause_duration: editForm.pause_duration, paused: result?.paused === true, paused_until: Number(result?.paused_until || 0) } : current);
await loadAccounts();
} catch (error) { console.error('重新暂停失败:', error); }
} catch (/* error 表示错误。 */ error) { console.error('重新暂停失败:', error); }
finally { setSaving(false); }
}, [editForm.pause_duration, editingAccount, loadAccounts, saving, setEditingAccount]);
/** 按账号和请求代次轮询密码登录状态。 */
// pollPasswordLoginCallback 是密码登录状态轮询回调。
const pollPasswordLogin = useCallback(async (sessionId: string, generation: number, accountId: string): Promise<void> => {
const pollPasswordLogin = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (sessionId: string, generation: number, accountId: string): Promise<void> => {
passwordAbort.current?.abort();
// controller 控制当前密码登录状态查询的取消。
const controller = new AbortController();
@@ -246,19 +246,19 @@ export const useAccountSubmodules = ({ editingAccount, setEditingAccount, setAct
if (result.status === 'success') {
clearPasswordTimer();
setPasswordLoginView(nextView);
setEditForm(current => ({ ...current, login_password: '', showLoginPassword: false }));
setEditForm(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, login_password: '', showLoginPassword: false }));
await loadAccounts();
return;
}
if (result.status === 'processing' || result.status === 'verification_required') {
setPasswordLoginView(nextView);
clearPasswordTimer();
passwordTimer.current = window.setTimeout(() => void pollPasswordLogin(sessionId, generation, accountId), 1500);
passwordTimer.current = window.setTimeout(/* 当前回调处理用户交互或异步状态变化。 */ () => void pollPasswordLogin(sessionId, generation, accountId), 1500);
return;
}
clearPasswordTimer();
setPasswordLoginView(nextView);
} catch (error) {
} catch (/* error 表示错误。 */ error) {
// error 保存密码登录状态查询失败原因。
if (!isCurrentAccountRequest(generation, passwordGeneration.current, accountId, passwordAccount.current)) return;
clearPasswordTimer();
@@ -268,7 +268,7 @@ export const useAccountSubmodules = ({ editingAccount, setEditingAccount, setAct
/** 启动账号密码登录刷新授权。 */
// handlePasswordLoginCallback 是密码登录启动回调。
const handlePasswordLogin = useCallback(async (): Promise<void> => {
const handlePasswordLogin = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (): Promise<void> => {
if (!editingAccount) return;
// accountName 是本次登录使用的闲鱼账号名。
const accountName = editForm.username.trim();
@@ -289,7 +289,7 @@ export const useAccountSubmodules = ({ editingAccount, setEditingAccount, setAct
if (!result.success || !result.session_id) throw new Error(result.message || '无法启动密码登录');
setPasswordLoginView({ sessionId: result.session_id, status: 'processing', message: result.message || '登录处理中', qrCodeUrl: '' });
await pollPasswordLogin(result.session_id, generation, editingAccount.id);
} catch (error) {
} catch (/* error 表示错误。 */ error) {
// error 保存密码登录启动失败原因。
if (!isCurrentAccountRequest(generation, passwordGeneration.current, editingAccount.id, passwordAccount.current)) return;
setPasswordLoginView({ sessionId: '', status: 'failed', message: error instanceof Error ? error.message : '启动密码登录失败', qrCodeUrl: '' });
@@ -298,20 +298,20 @@ export const useAccountSubmodules = ({ editingAccount, setEditingAccount, setAct
/** 取消当前密码登录会话。 */
// handleCancelPasswordLoginCallback 是密码登录取消回调。
const handleCancelPasswordLogin = useCallback(async (): Promise<void> => {
const handleCancelPasswordLogin = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (): Promise<void> => {
// sessionId 是当前待取消的密码登录会话。
const sessionId = passwordLoginView.sessionId;
passwordGeneration.current += 1;
passwordAccount.current = '';
passwordAbort.current?.abort();
clearPasswordTimer();
if (sessionId) await cancelPasswordLogin(sessionId).catch(() => undefined);
if (sessionId) await cancelPasswordLogin(sessionId).catch(/* 当前回调处理异步操作结果。 */ () => undefined);
setPasswordLoginView({ sessionId: '', status: 'idle', message: '', qrCodeUrl: '' });
}, [clearPasswordTimer, passwordLoginView.sessionId]);
/** 关闭编辑弹窗并取消未完成的子模块请求。 */
// closeEditModalCallback 是编辑弹窗关闭回调。
const closeEditModal = useCallback(async (): Promise<void> => {
const closeEditModal = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (): Promise<void> => {
bindingsAbort.current?.abort();
longLoginSequence.current += 1;
longLoginAbort.current?.abort();
@@ -322,14 +322,14 @@ export const useAccountSubmodules = ({ editingAccount, setEditingAccount, setAct
/** 关闭 AI 设置弹窗并取消读取请求。 */
// closeAIModalCallback 是 AI 设置弹窗关闭回调。
const closeAIModal = useCallback(() => {
const closeAIModal = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ () => {
aiSequence.current += 1;
aiAbort.current?.abort();
setActiveModal(null);
}, [setActiveModal]);
// cleanupSubmodulesEffect 在 Hook 卸载时取消所有子模块请求。
useEffect(() => () => {
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => /* 当前回调同步 React 副作用和资源生命周期。 */ () => {
bindingsAbort.current?.abort();
longLoginAbort.current?.abort();
aiAbort.current?.abort();
+125 -68
View File
@@ -137,71 +137,87 @@ export const useChat = (): UseChatResult => {
// sendController 保存当前消息发送控制器。
const sendController = useRef<AbortController | null>(null);
useEffect(() => { activeAccountRef.current = activeAccountID; }, [activeAccountID]);
useEffect(() => { activeChatRef.current = activeChatID; }, [activeChatID]);
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => { activeAccountRef.current = activeAccountID; }, [activeAccountID]);
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => { activeChatRef.current = activeChatID; }, [activeChatID]);
/** 刷新指定账号的联系人列表,并丢弃过期响应。 */
const reloadSessions = useCallback(async (accountID: string): Promise<ChatSession[]> => {
const reloadSessions = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (accountID: string): Promise<ChatSession[]> => {
// sequence 请求序号。
const sequence = ++sessionSequence.current;
sessionController.current?.abort();
// controller 请求取消控制器。
const controller = new AbortController();
sessionController.current = controller;
try {
// page 页码。
const page = await getChatSessionPage(accountID, undefined, { signal: controller.signal }, true);
if (!isCurrentChatRequest(sessionSequence.current, sequence, controller.signal)) return [];
setSessionsByAccount(current => ({ ...current, [accountID]: page.sessions }));
setContactCursors(current => ({ ...current, [accountID]: page.next_cursor }));
setHasMoreContacts(current => ({ ...current, [accountID]: page.has_more }));
setSessionsByAccount(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, [accountID]: page.sessions }));
setContactCursors(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, [accountID]: page.next_cursor }));
setHasMoreContacts(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, [accountID]: page.has_more }));
return page.sessions;
} catch (error) {
} catch (/* error 表示错误。 */ error) {
if (isCurrentChatRequest(sessionSequence.current, sequence, controller.signal) && !isChatAbortError(error)) setError(error instanceof Error ? error.message : '同步会话失败');
return [];
}
}, []);
useEffect(() => {
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => {
// controller 请求取消控制器。
const controller = new AbortController();
// load 加载当前数据。
const load = async (): Promise<void> => {
setLoading(true);
try {
// [details, 解构得到当前 Hook 返回的状态和操作函数。
const [details, statuses] = await Promise.all([
getAccountDetails({ signal: controller.signal }),
getAccountRuntimeStatuses({ signal: controller.signal }),
]);
const withRuntime = details.map(account => ({
// withRuntime with运行状态,负责当前功能中的对应处理。
const withRuntime = details.map(/* 当前回调处理集合中的单个元素。 */ account => ({
...account,
runtime_state: statuses[account.id]?.state || (account.enabled ? 'connecting' : 'disabled'),
runtime_connected: statuses[account.id]?.connected === true,
}));
const enabled = withRuntime.filter(account => account.enabled);
const sessionPages = await Promise.all(enabled.map(async account => [account.id, await getChatSessionPage(account.id, undefined, { signal: controller.signal })] as const));
// enabled 启用状态。
const enabled = withRuntime.filter(/* 当前回调处理集合中的单个元素。 */ account => account.enabled);
// sessionPages 会话Pages,负责当前功能中的对应处理。
const sessionPages = await Promise.all(enabled.map(/* 当前回调处理集合中的单个元素。 */ async account => [account.id, await getChatSessionPage(account.id, undefined, { signal: controller.signal })] as const));
if (controller.signal.aborted) return;
setAccounts(enabled);
setSessionsByAccount(Object.fromEntries(sessionPages.map(([id, page]) => [id, page.sessions])));
setContactCursors(Object.fromEntries(sessionPages.map(([id, page]) => [id, page.next_cursor])));
setHasMoreContacts(Object.fromEntries(sessionPages.map(([id, page]) => [id, page.has_more])));
setSessionsByAccount(Object.fromEntries(sessionPages.map(/* 当前回调处理集合中的单个元素。 */ ([id, page]) => [id, page.sessions])));
setContactCursors(Object.fromEntries(sessionPages.map(/* 当前回调处理集合中的单个元素。 */ ([id, page]) => [id, page.next_cursor])));
setHasMoreContacts(Object.fromEntries(sessionPages.map(/* 当前回调处理集合中的单个元素。 */ ([id, page]) => [id, page.has_more])));
// stored 已保存数据。
const stored = window.localStorage.getItem('ydisks.chat.account.v1') || '';
const first = enabled.some(account => account.id === stored) ? stored : enabled[0]?.id || '';
// first 首项。
const first = enabled.some(/* 当前回调处理集合中的单个元素。 */ account => account.id === stored) ? stored : enabled[0]?.id || '';
setActiveAccountID(first);
} catch (loadError) {
} catch (/* loadError 表示加载错误。 */ loadError) {
if (!controller.signal.aborted) setError(loadError instanceof Error ? loadError.message : '加载聊天数据失败');
} finally {
if (!controller.signal.aborted) setLoading(false);
}
};
void load();
return () => controller.abort();
return /* 当前回调处理用户交互或异步状态变化。 */ () => controller.abort();
}, []);
useEffect(() => {
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => {
// disposed disposed,负责当前功能中的对应处理。
let disposed = false;
// timer 定时器。
let timer = 0;
// controller 请求取消控制器。
let controller: AbortController | null = null;
// poll 轮询函数。
const poll = async (): Promise<void> => {
controller = new AbortController();
try {
// statuses statuses,负责当前功能中的对应处理。
const statuses = await getAccountRuntimeStatuses({ signal: controller.signal, timeoutMs: 10_000 });
if (!disposed) setAccounts(current => current.map(account => ({
if (!disposed) setAccounts(/* 当前回调处理集合中的单个元素。 */ current => current.map(/* 当前回调处理集合中的单个元素。 */ account => ({
...account,
runtime_state: statuses[account.id]?.state || account.runtime_state,
runtime_connected: statuses[account.id]?.connected ?? account.runtime_connected,
@@ -213,65 +229,68 @@ export const useChat = (): UseChatResult => {
}
};
timer = window.setTimeout(poll, 3_000);
return () => {
return /* 当前回调处理用户交互或异步状态变化。 */ () => {
disposed = true;
window.clearTimeout(timer);
controller?.abort();
};
}, []);
useEffect(() => {
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => {
if (!activeAccountID) return;
window.localStorage.setItem('ydisks.chat.account.v1', activeAccountID);
// sessions 会话列表。
const sessions = sessionsByAccount[activeAccountID] || [];
setActiveChatID(current => sessions.some(session => session.chat_id === current) ? current : sessions[0]?.chat_id || '');
setActiveChatID(/* 当前回调处理集合中的单个元素。 */ current => sessions.some(/* 当前回调处理集合中的单个元素。 */ session => session.chat_id === current) ? current : sessions[0]?.chat_id || '');
}, [activeAccountID, sessionsByAccount]);
useEffect(() => {
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => {
if (!activeAccountID || refreshedAccountsRef.current.has(activeAccountID)) return;
refreshedAccountsRef.current.add(activeAccountID);
void reloadSessions(activeAccountID);
}, [activeAccountID, reloadSessions]);
useEffect(() => {
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => {
if (!activeAccountID || !activeChatID) {
setMessages([]);
return;
}
// sequence 请求序号。
const sequence = ++messageSequence.current;
messageController.current?.abort();
// controller 请求取消控制器。
const controller = new AbortController();
messageController.current = controller;
setMessagesLoading(true);
void Promise.all([
getChatMessagePage(activeAccountID, activeChatID, undefined, undefined, { signal: controller.signal }),
markChatRead(activeAccountID, activeChatID, { signal: controller.signal }),
]).then(([page]) => {
]).then(/* 当前回调处理用户交互或异步状态变化。 */ ([page]) => {
if (!isCurrentChatRequest(messageSequence.current, sequence, controller.signal)) return;
setMessages(page.messages);
setHasOlder(page.has_more);
setHistoryCursor(page.next_cursor);
if (page.session) setSessionsByAccount(current => ({ ...current, [activeAccountID]: (current[activeAccountID] || []).map(session => session.chat_id === page.session?.chat_id ? page.session! : session) }));
setSessionsByAccount(current => ({ ...current, [activeAccountID]: (current[activeAccountID] || []).map(session => session.chat_id === activeChatID ? { ...session, unread_count: 0 } : session) }));
}).catch(loadError => {
if (page.session) setSessionsByAccount(/* 当前回调处理集合中的单个元素。 */ current => ({ ...current, [activeAccountID]: (current[activeAccountID] || []).map(/* 当前回调处理集合中的单个元素。 */ session => session.chat_id === page.session?.chat_id ? page.session! : session) }));
setSessionsByAccount(/* 当前回调处理集合中的单个元素。 */ current => ({ ...current, [activeAccountID]: (current[activeAccountID] || []).map(/* 当前回调处理集合中的单个元素。 */ session => session.chat_id === activeChatID ? { ...session, unread_count: 0 } : session) }));
}).catch(/* 当前回调处理用户交互或异步状态变化。 */ loadError => {
if (isCurrentChatRequest(messageSequence.current, sequence, controller.signal) && !isChatAbortError(loadError)) setError(loadError instanceof Error ? loadError.message : '加载消息失败');
}).finally(() => {
}).finally(/* 当前回调处理用户交互或异步状态变化。 */ () => {
if (isCurrentChatRequest(messageSequence.current, sequence, controller.signal)) setMessagesLoading(false);
});
return () => controller.abort();
return /* 当前回调处理用户交互或异步状态变化。 */ () => controller.abort();
}, [activeAccountID, activeChatID]);
useEffect(() => {
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => {
contactController.current?.abort();
contactSequence.current += 1;
}, [activeAccountID]);
useEffect(() => {
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => {
sendController.current?.abort();
sendSequence.current += 1;
}, [activeAccountID, activeChatID]);
useEffect(() => () => {
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => /* 当前回调同步 React 副作用和资源生命周期。 */ () => {
sessionController.current?.abort();
messageController.current?.abort();
contactController.current?.abort();
@@ -279,26 +298,32 @@ export const useChat = (): UseChatResult => {
}, []);
/** 加载当前会话更早消息并保持滚动位置。 */
const loadOlderMessages = useCallback(async (): Promise<void> => {
const loadOlderMessages = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (): Promise<void> => {
if (!activeAccountID || !activeChatID || olderLoading || !hasOlder) return;
// container 容器。
const container = scrollRef.current;
// previousHeight 上一项高度,负责当前功能中的对应处理。
const previousHeight = container?.scrollHeight || 0;
// sequence 请求序号。
const sequence = messageSequence.current;
// controller 请求取消控制器。
const controller = new AbortController();
skipNextMessageScrollRef.current = true;
setOlderLoading(true);
setError('');
try {
// oldestID 最早标识,负责当前功能中的对应处理。
const oldestID = messages[0]?.id;
// page 页码。
const page = await getChatMessagePage(activeAccountID, activeChatID, historyCursor, oldestID, { signal: controller.signal });
if (!isCurrentChatRequest(messageSequence.current, sequence, controller.signal)) return;
setMessages(current => mergeOlderMessages(current, page.messages));
setMessages(/* 当前回调处理用户交互或异步状态变化。 */ current => mergeOlderMessages(current, page.messages));
setHasOlder(page.has_more);
setHistoryCursor(page.next_cursor);
requestAnimationFrame(() => {
requestAnimationFrame(/* 当前回调处理用户交互或异步状态变化。 */ () => {
if (container) container.scrollTop += container.scrollHeight - previousHeight;
});
} catch (loadError) {
} catch (/* loadError 表示加载错误。 */ loadError) {
skipNextMessageScrollRef.current = false;
if (!isChatAbortError(loadError)) setError(loadError instanceof Error ? loadError.message : '加载历史消息失败');
} finally {
@@ -306,55 +331,67 @@ export const useChat = (): UseChatResult => {
}
}, [activeAccountID, activeChatID, hasOlder, historyCursor, messages, olderLoading]);
useEffect(() => {
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => {
// disposed disposed,负责当前功能中的对应处理。
let disposed = false;
// reconnectTimer reconnect定时器,负责当前功能中的对应处理。
let reconnectTimer = 0;
// retry 重试当前操作。
let retry = 0;
// socket WebSocket 连接。
let socket: WebSocket | null = null;
// connect 连接。
const connect = (): void => {
if (disposed) return;
setLiveState('connecting');
// protocol 连接协议。
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
socket = new WebSocket(`${protocol}//${window.location.host}/api/v1/chat/ws`);
socket.onopen = () => { retry = 0; setLiveState('online'); };
socket.onmessage = event => {
socket.onopen = /* 当前回调处理用户交互或异步状态变化。 */ () => { retry = 0; setLiveState('online'); };
socket.onmessage = /* 当前回调处理用户交互或异步状态变化。 */ event => {
try {
// payload 请求载荷。
const payload = JSON.parse(event.data);
// message 消息。
const message = payload.message as ChatMessage | undefined;
if (!message) return;
// accountID 账号标识。
const accountID = message.account_id;
setSessionsByAccount(current => {
setSessionsByAccount(/* 当前回调处理用户交互或异步状态变化。 */ current => {
// rows 行数据。
const rows = current[accountID] || [];
const found = rows.some(row => row.chat_id === message.chat_id);
// found 匹配结果。
const found = rows.some(/* 当前回调处理集合中的单个元素。 */ row => row.chat_id === message.chat_id);
if (!found) {
void reloadSessions(accountID);
return current;
}
return { ...current, [accountID]: rows.map(row => row.chat_id === message.chat_id ? {
return { ...current, [accountID]: rows.map(/* 当前回调处理集合中的单个元素。 */ row => row.chat_id === message.chat_id ? {
...row,
last_message: message.content,
last_message_at: message.sent_at,
unread_count: message.direction === 'incoming' && (activeAccountRef.current !== accountID || activeChatRef.current !== message.chat_id) ? row.unread_count + 1 : row.unread_count,
} : row).sort((a, b) => b.last_message_at - a.last_message_at) };
} : row).sort(/* 当前回调处理集合中的单个元素。 */ (a, b) => b.last_message_at - a.last_message_at) };
});
if (activeAccountRef.current === accountID && activeChatRef.current === message.chat_id) {
setMessages(current => mergeLiveMessage(current, message));
setMessages(/* 当前回调处理用户交互或异步状态变化。 */ current => mergeLiveMessage(current, message));
if (message.direction === 'incoming') void markChatRead(accountID, message.chat_id);
}
} catch {
// 忽略非聊天格式的 WebSocket 帧,后续 REST 查询会恢复权威状态。
}
};
socket.onclose = () => {
socket.onclose = /* 当前回调处理用户交互或异步状态变化。 */ () => {
if (disposed) return;
setLiveState('offline');
// delay 延迟。
const delay = Math.min(15_000, 1_000 * 2 ** Math.min(retry++, 4));
reconnectTimer = window.setTimeout(connect, delay);
};
socket.onerror = () => socket?.close();
socket.onerror = /* 当前回调处理用户交互或异步状态变化。 */ () => socket?.close();
};
connect();
return () => {
return /* 当前回调处理用户交互或异步状态变化。 */ () => {
disposed = true;
window.clearTimeout(reconnectTimer);
socket?.close();
@@ -362,17 +399,21 @@ export const useChat = (): UseChatResult => {
}, [reloadSessions]);
/** 根据滚动位置决定新消息是否自动滚到底部。 */
const handleMessageScroll = useCallback(() => {
const handleMessageScroll = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ () => {
// container 容器。
const container = scrollRef.current;
if (!container) return;
// distanceFromBottom 距离FromBottom,负责当前功能中的对应处理。
const distanceFromBottom = container.scrollHeight - container.scrollTop - container.clientHeight;
shouldScrollToBottomRef.current = distanceFromBottom <= 48;
}, []);
useLayoutEffect(() => {
useLayoutEffect(/* 当前回调处理用户交互或异步状态变化。 */ () => {
// contextChanged 上下文Changed,负责当前功能中的对应处理。
const contextChanged = scrollContextRef.current.accountID !== activeAccountID || scrollContextRef.current.chatID !== activeChatID;
scrollContextRef.current = { accountID: activeAccountID, chatID: activeChatID };
if (contextChanged) shouldScrollToBottomRef.current = true;
// container 容器。
const container = scrollRef.current;
if (!container) return;
if (skipNextMessageScrollRef.current) {
@@ -382,29 +423,38 @@ export const useChat = (): UseChatResult => {
if (messagesLoading || shouldScrollToBottomRef.current) container.scrollTop = container.scrollHeight;
}, [activeAccountID, activeChatID, messages, messagesLoading]);
const activeAccount = accounts.find(account => account.id === activeAccountID);
// activeAccount 当前状态账号,负责当前功能中的对应处理。
const activeAccount = accounts.find(/* 当前回调处理集合中的单个元素。 */ account => account.id === activeAccountID);
// activeSessions 当前状态会话列表,负责当前功能中的对应处理。
const activeSessions = sessionsByAccount[activeAccountID] || [];
const selectedSession = activeSessions.find(session => session.chat_id === activeChatID);
const filteredSessions = useMemo(() => filterChatSessions(activeSessions, search, unreadOnly), [activeSessions, search, unreadOnly]);
const unreadForAccount = useCallback((accountID: string) => (sessionsByAccount[accountID] || []).reduce((sum, session) => sum + session.unread_count, 0), [sessionsByAccount]);
// selectedSession 处理当前选择(ed会话)。
const selectedSession = activeSessions.find(/* 当前回调处理集合中的单个元素。 */ session => session.chat_id === activeChatID);
// filteredSessions 过滤后的会话列表,负责当前功能中的对应处理。
const filteredSessions = useMemo(/* 当前回调计算并缓存派生数据。 */ () => filterChatSessions(activeSessions, search, unreadOnly), [activeSessions, search, unreadOnly]);
// unreadForAccount unreadFor账号,负责当前功能中的对应处理。
const unreadForAccount = useCallback(/* 当前回调处理集合中的单个元素。 */ (accountID: string) => (sessionsByAccount[accountID] || []).reduce(/* 当前回调处理集合中的单个元素。 */ (sum, session) => sum + session.unread_count, 0), [sessionsByAccount]);
/** 加载当前账号下一页联系人。 */
const loadMoreContacts = useCallback(async (): Promise<void> => {
const loadMoreContacts = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (): Promise<void> => {
if (!activeAccountID || contactsLoading || !hasMoreContacts[activeAccountID]) return;
// sequence 请求序号。
const sequence = ++contactSequence.current;
contactController.current?.abort();
// controller 请求取消控制器。
const controller = new AbortController();
contactController.current = controller;
// accountID 账号标识。
const accountID = activeAccountID;
setContactsLoading(true);
setError('');
try {
// page 页码。
const page = await getChatSessionPage(accountID, contactCursors[accountID], { signal: controller.signal }, true);
if (!isCurrentChatRequest(contactSequence.current, sequence, controller.signal)) return;
setSessionsByAccount(current => ({ ...current, [accountID]: page.sessions }));
setContactCursors(current => ({ ...current, [accountID]: page.next_cursor }));
setHasMoreContacts(current => ({ ...current, [accountID]: page.has_more }));
} catch (loadError) {
setSessionsByAccount(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, [accountID]: page.sessions }));
setContactCursors(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, [accountID]: page.next_cursor }));
setHasMoreContacts(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, [accountID]: page.has_more }));
} catch (/* loadError 表示加载错误。 */ loadError) {
if (isCurrentChatRequest(contactSequence.current, sequence, controller.signal) && !isChatAbortError(loadError)) setError(loadError instanceof Error ? loadError.message : '加载历史联系人失败');
} finally {
if (isCurrentChatRequest(contactSequence.current, sequence, controller.signal)) setContactsLoading(false);
@@ -412,21 +462,24 @@ export const useChat = (): UseChatResult => {
}, [activeAccountID, contactCursors, contactsLoading, hasMoreContacts]);
/** 发送文本消息并记录失败重试数据。 */
const sendText = useCallback(async (text: string, rememberRetry: boolean): Promise<void> => {
const sendText = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (text: string, rememberRetry: boolean): Promise<void> => {
if (!selectedSession || !activeAccountID || sending) return;
// sequence 请求序号。
const sequence = ++sendSequence.current;
sendController.current?.abort();
// controller 请求取消控制器。
const controller = new AbortController();
sendController.current = controller;
setSending(true);
setError('');
try {
// result 处理结果。
const result = await sendChatMessage({ account_id: activeAccountID, chat_id: selectedSession.chat_id, buyer_id: selectedSession.buyer_id, buyer_name: selectedSession.buyer_name, item_id: selectedSession.item_id, item_title: selectedSession.item_title, text }, { signal: controller.signal });
if (!isCurrentChatRequest(sendSequence.current, sequence, controller.signal)) return;
setDraft('');
setRetryText(null);
setMessages(current => mergeLiveMessage(current, result.message));
} catch (sendError) {
setMessages(/* 当前回调处理用户交互或异步状态变化。 */ current => mergeLiveMessage(current, result.message));
} catch (/* sendError 表示发送错误。 */ sendError) {
if (isCurrentChatRequest(sendSequence.current, sequence, controller.signal)) {
if (rememberRetry) setRetryText(text);
if (!isChatAbortError(sendError)) setError(sendError instanceof Error ? sendError.message : '消息发送失败');
@@ -437,20 +490,23 @@ export const useChat = (): UseChatResult => {
}, [activeAccountID, selectedSession, sending]);
/** 发送图片消息并记录失败重试数据。 */
const sendImage = useCallback(async (file: File, rememberRetry: boolean): Promise<void> => {
const sendImage = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (file: File, rememberRetry: boolean): Promise<void> => {
if (!selectedSession || !activeAccountID || sending) return;
// sequence 请求序号。
const sequence = ++sendSequence.current;
sendController.current?.abort();
// controller 请求取消控制器。
const controller = new AbortController();
sendController.current = controller;
setSending(true);
setError('');
try {
// result 处理结果。
const result = await sendChatImage({ account_id: activeAccountID, chat_id: selectedSession.chat_id, buyer_id: selectedSession.buyer_id, buyer_name: selectedSession.buyer_name, buyer_avatar_url: selectedSession.buyer_avatar_url, item_id: selectedSession.item_id, item_title: selectedSession.item_title, image: file }, { signal: controller.signal });
if (!isCurrentChatRequest(sendSequence.current, sequence, controller.signal)) return;
setRetryImage(null);
setMessages(current => mergeLiveMessage(current, result.message));
} catch (sendError) {
setMessages(/* 当前回调处理用户交互或异步状态变化。 */ current => mergeLiveMessage(current, result.message));
} catch (/* sendError 表示发送错误。 */ sendError) {
if (isCurrentChatRequest(sendSequence.current, sequence, controller.signal)) {
if (rememberRetry) setRetryImage(file);
if (!isChatAbortError(sendError)) setError(sendError instanceof Error ? sendError.message : '图片发送失败');
@@ -464,20 +520,21 @@ export const useChat = (): UseChatResult => {
}, [activeAccountID, selectedSession, sending]);
/** 处理文本发送按钮和 Enter 快捷键。 */
const handleSend = useCallback(async (): Promise<void> => {
const handleSend = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (): Promise<void> => {
// text 文本。
const text = draft.trim();
if (!text || !selectedSession || !activeAccountID || sending) return;
await sendText(text, true);
}, [activeAccountID, draft, selectedSession, sendText, sending]);
/** 处理图片选择并发送。 */
const handleImage = useCallback(async (file?: File): Promise<void> => {
const handleImage = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (file?: File): Promise<void> => {
if (!file || !selectedSession || !activeAccountID || sending) return;
await sendImage(file, true);
}, [activeAccountID, selectedSession, sendImage, sending]);
/** 重试最近一次失败的文本或图片发送。 */
const retrySend = useCallback(async (): Promise<void> => {
const retrySend = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (): Promise<void> => {
if (retryText) await sendText(retryText, false);
else if (retryImage) await sendImage(retryImage, false);
}, [retryImage, retryText, sendImage, sendText]);
+1
View File
@@ -21,6 +21,7 @@ test('Chat 会话筛选和历史消息合并保持账号内顺序',
test('Chat 实时消息替换同键记录并拒绝过期请求',
// 请求边界测试验证实时回执不会产生重复消息,切换会话后的旧请求不能写入。
() => {
// controller 请求取消控制器。
const controller = new AbortController();
expect(mergeLiveMessage([messageFixture], { ...messageFixture, content: '新消息' })[0].content).toBe('新消息');
expect(isCurrentChatRequest(3, 3, controller.signal)).toBe(true);
+12 -6
View File
@@ -2,26 +2,29 @@ import type { ChatMessage, ChatSession } from '../../../types';
/** 按搜索条件筛选会话列表。 */
export const filterChatSessions = (sessions: ChatSession[], search: string, unreadOnly: boolean): ChatSession[] => {
// keyword 搜索关键词。
const keyword = search.trim().toLowerCase();
return sessions.filter(session => {
return sessions.filter(/* 当前回调处理集合中的单个元素。 */ session => {
if (unreadOnly && session.unread_count <= 0) return false;
if (!keyword) return true;
return [session.buyer_name, session.buyer_id, session.item_title, session.last_message]
.some(value => (value || '').toLowerCase().includes(keyword));
.some(/* 当前回调处理集合中的单个元素。 */ value => (value || '').toLowerCase().includes(keyword));
});
};
/** 合并历史消息并按消息键去重。 */
export const mergeOlderMessages = (current: ChatMessage[], older: ChatMessage[]): ChatMessage[] => {
const keys = new Set(current.map(message => message.message_key));
return [...older.filter(message => !keys.has(message.message_key)), ...current];
// keys keys,负责当前功能中的对应处理。
const keys = new Set(current.map(/* 当前回调处理集合中的单个元素。 */ message => message.message_key));
return [...older.filter(/* 当前回调处理集合中的单个元素。 */ message => !keys.has(message.message_key)), ...current];
};
/** 合并实时消息并替换同消息键的临时记录。 */
export const mergeLiveMessage = (current: ChatMessage[], incoming: ChatMessage): ChatMessage[] => {
const index = current.findIndex(message => message.message_key === incoming.message_key);
// index 当前索引。
const index = current.findIndex(/* 当前回调处理用户交互或异步状态变化。 */ message => message.message_key === incoming.message_key);
if (index < 0) return [...current, incoming];
return current.map((message, currentIndex) => currentIndex === index ? incoming : message);
return current.map(/* 当前回调处理集合中的单个元素。 */ (message, currentIndex) => currentIndex === index ? incoming : message);
};
/** 判断 Chat 请求响应是否仍属于当前账号和会话。 */
@@ -35,7 +38,9 @@ export const isChatAbortError = (error: unknown): boolean => error instanceof Er
/** 将聊天时间戳格式化为列表时间。 */
export const formatClock = (value: number): string => {
if (!value) return '';
// date 日期。
const date = new Date(value < 10_000_000_000 ? value * 1000 : value);
// today 今天日期。
const today = new Date();
if (date.toDateString() === today.toDateString()) {
return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false });
@@ -45,6 +50,7 @@ export const formatClock = (value: number): string => {
/** 将聊天时间戳格式化为消息详情时间。 */
export const messageTime = (value: number): string => {
// date 日期。
const date = new Date(value < 10_000_000_000 ? value * 1000 : value);
return date.toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false });
};
+55 -33
View File
@@ -6,20 +6,20 @@ import { getDashboardStats, getItems, getOrderAnalytics, getValidOrders } from '
import type { DashboardData, DashboardRangeSelection, DashboardStatus } from './types';
/** Dashboard Hook 的输入参数。 */
export type UseDashboardOptions = DashboardRangeSelection & { customRangeVersion: number };
export type UseDashboardOptions = DashboardRangeSelection & { /** customRangeVersion 表示自定义范围版本。 */ customRangeVersion: number };
/** Dashboard Hook 暴露给页面的可视化数据与操作。 */
export type UseDashboardResult = {
data: DashboardData | null;
status: DashboardStatus;
chartData: ReturnType<typeof buildChartData>;
productSalesData: ReturnType<typeof buildProductSalesData>;
sourceData: ReturnType<typeof buildSourceData>;
categoryData: ReturnType<typeof buildCategoryData>;
maxProductSales: number;
trendPercent: string | null;
selectedRangeLabel: string;
refresh: () => void;
/** data 表示返回数据。 */ data: DashboardData | null;
/** status 表示状态。 */ status: DashboardStatus;
/** chartData 表示图表数据。 */ chartData: ReturnType<typeof buildChartData>;
/** productSalesData 表示商品销量数据。 */ productSalesData: ReturnType<typeof buildProductSalesData>;
/** sourceData 表示来源统计数据。 */ sourceData: ReturnType<typeof buildSourceData>;
/** categoryData 表示分类统计数据。 */ categoryData: ReturnType<typeof buildCategoryData>;
/** maxProductSales 表示最大商品销量。 */ maxProductSales: number;
/** trendPercent 表示趋势Percent。 */ trendPercent: string | null;
/** selectedRangeLabel 表示选中范围Label。 */ selectedRangeLabel: string;
/** refresh 表示刷新函数。 */ refresh: () => void;
};
/** 判断请求错误是否来自用户主动取消。 */
@@ -30,85 +30,107 @@ const errorMessage = (error: unknown, fallback: string): string => error instanc
/** 加载 Dashboard 概览、趋势和订单明细,并隔离过期响应。 */
export const useDashboard = (options: UseDashboardOptions): UseDashboardResult => {
// { 解构得到当前 Hook 返回的状态和操作函数。
const { range, customStartDate, customEndDate, customRangeVersion } = options;
// [overview, 解构得到当前 Hook 返回的状态和操作函数。
const [overview, setOverview] = useState<Pick<DashboardData, 'stats' | 'items' | 'itemNames'> | null>(null);
// [rangeData, 解构得到当前 Hook 返回的状态和操作函数。
const [rangeData, setRangeData] = useState<Pick<DashboardData, 'analytics' | 'previousAnalytics' | 'validOrders' | 'dateRange'> | null>(null);
// [status, 解构得到当前 Hook 返回的状态和操作函数。
const [status, setStatus] = useState<DashboardStatus>({ overview: 'idle', range: 'idle', error: '' });
// [refreshKey, 解构得到当前 Hook 返回的状态和操作函数。
const [refreshKey, setRefreshKey] = useState(0);
// requestSequence 请求请求序号,负责当前功能中的对应处理。
const requestSequence = useRef(0);
// rangeSelection 范围选择,负责当前功能中的对应处理。
const rangeSelection = useMemo(
// selection 是当前时间范围的不可变快照。
() => ({ range, customStartDate, customEndDate }),
[customEndDate, customStartDate, range],
);
// refresh 刷新当前数据。
const refresh = useCallback(
// 重新加载按钮回调只递增版本号,实际请求由两个 effect 统一管理。
() => setRefreshKey(value => value + 1),
() => setRefreshKey(/* 当前回调处理用户交互或异步状态变化。 */ value => value + 1),
[],
);
useEffect(() => {
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => {
// controller 请求取消控制器。
const controller = new AbortController();
setStatus(current => ({ ...current, overview: 'loading', error: '' }));
setStatus(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, overview: 'loading', error: '' }));
Promise.all([
getDashboardStats({ signal: controller.signal }),
getItems(undefined, { signal: controller.signal }),
]).then(([stats, items]) => {
]).then(/* 当前回调处理用户交互或异步状态变化。 */ ([stats, items]) => {
if (controller.signal.aborted) return;
setOverview({ stats, items, itemNames: buildItemNameMap(items) });
setStatus(current => ({ ...current, overview: 'success' }));
}).catch(error => {
setStatus(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, overview: 'success' }));
}).catch(/* 当前回调处理用户交互或异步状态变化。 */ error => {
if (controller.signal.aborted || isAbortError(error)) return;
setStatus(current => ({ ...current, overview: 'error', error: errorMessage(error, '概览加载失败') }));
setStatus(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, overview: 'error', error: errorMessage(error, '概览加载失败') }));
});
return () => controller.abort();
return /* 当前回调处理用户交互或异步状态变化。 */ () => controller.abort();
}, [refreshKey]);
useEffect(() => {
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => {
// dateRange 日期范围,负责当前功能中的对应处理。
let dateRange;
try {
dateRange = getDateRange(range, new Date(), customStartDate, customEndDate);
} catch (error) {
setStatus(current => ({ ...current, range: 'error', error: errorMessage(error, '日期范围无效') }));
} catch (/* error 表示错误。 */ error) {
setStatus(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, range: 'error', error: errorMessage(error, '日期范围无效') }));
return;
}
// previousRange 上一项范围,负责当前功能中的对应处理。
const previousRange = getPreviousDateRange(dateRange);
// sequence 请求序号。
const sequence = ++requestSequence.current;
// controller 请求取消控制器。
const controller = new AbortController();
setStatus(current => ({ ...current, range: 'loading', error: '' }));
setStatus(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, range: 'loading', error: '' }));
Promise.all([
getOrderAnalytics({ start_date: dateRange.startDate, end_date: dateRange.endDate }, { signal: controller.signal }),
getOrderAnalytics({ start_date: previousRange.startDate, end_date: previousRange.endDate }, { signal: controller.signal }),
getValidOrders({ start_date: dateRange.startDate, end_date: dateRange.endDate }, { signal: controller.signal }),
]).then(([analytics, previousAnalytics, validOrders]) => {
]).then(/* 当前回调处理用户交互或异步状态变化。 */ ([analytics, previousAnalytics, validOrders]) => {
if (!isCurrentDashboardRequest(requestSequence.current, sequence, controller.signal)) return;
setRangeData({ analytics, previousAnalytics, validOrders, dateRange });
setStatus(current => ({ ...current, range: 'success' }));
}).catch(error => {
setStatus(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, range: 'success' }));
}).catch(/* 当前回调处理用户交互或异步状态变化。 */ error => {
if (!isCurrentDashboardRequest(requestSequence.current, sequence, controller.signal) || isAbortError(error)) return;
setStatus(current => ({ ...current, range: 'error', error: errorMessage(error, '经营数据加载失败') }));
setStatus(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, range: 'error', error: errorMessage(error, '经营数据加载失败') }));
});
return () => controller.abort();
return /* 当前回调处理用户交互或异步状态变化。 */ () => controller.abort();
}, [customRangeVersion, range, refreshKey]);
// data 数据。
const data = useMemo<DashboardData | null>(
// dashboardData 只有在概览和时间范围请求都成功后才对页面可见。
() => overview && rangeData ? { ...overview, ...rangeData } : null,
[overview, rangeData],
);
// itemNames 商品Names,负责当前功能中的对应处理。
const itemNames = overview?.itemNames || {};
// analytics 统计分析数据。
const analytics = rangeData?.analytics || null;
const chartData = useMemo(() => analytics ? buildChartData(analytics) : [], [analytics]);
const productSalesData = useMemo(() => analytics ? buildProductSalesData(analytics, itemNames) : [], [analytics, itemNames]);
// chartData 图表数据,负责当前功能中的对应处理。
const chartData = useMemo(/* 当前回调计算并缓存派生数据。 */ () => analytics ? buildChartData(analytics) : [], [analytics]);
// productSalesData productSales数据,负责当前功能中的对应处理。
const productSalesData = useMemo(/* 当前回调计算并缓存派生数据。 */ () => analytics ? buildProductSalesData(analytics, itemNames) : [], [analytics, itemNames]);
// colors 颜色列表。
const colors = useMemo(
// colors 是图表使用的主题颜色序列。
() => ['rgb(var(--color-brand))', 'rgb(var(--color-brand-highlight))', 'rgb(var(--color-success-500))', 'rgb(var(--color-warning-500))', 'rgb(var(--color-accent-500))'],
[],
);
const sourceData = useMemo(() => analytics ? buildSourceData(analytics, itemNames, colors) : [], [analytics, colors, itemNames]);
const categoryData = useMemo(() => analytics ? buildCategoryData(analytics, itemNames, colors) : [], [analytics, colors, itemNames]);
const maxProductSales = useMemo(() => getMaxProductSales(productSalesData), [productSalesData]);
// sourceData 来源数据,负责当前功能中的对应处理。
const sourceData = useMemo(/* 当前回调计算并缓存派生数据。 */ () => analytics ? buildSourceData(analytics, itemNames, colors) : [], [analytics, colors, itemNames]);
// categoryData 分类数据,负责当前功能中的对应处理。
const categoryData = useMemo(/* 当前回调计算并缓存派生数据。 */ () => analytics ? buildCategoryData(analytics, itemNames, colors) : [], [analytics, colors, itemNames]);
// maxProductSales 最大值ProductSales,负责当前功能中的对应处理。
const maxProductSales = useMemo(/* 当前回调计算并缓存派生数据。 */ () => getMaxProductSales(productSalesData), [productSalesData]);
return {
data,
+4 -4
View File
@@ -85,7 +85,7 @@ export const buildProductSalesData = (analytics: OrderAnalytics, itemNames: Reco
return { name: itemName.length > 12 ? `${itemName.substring(0, 12)}...` : itemName, sales: item.order_count };
},
)
.sort((left, right) => right.sales - left.sales)
.sort(/* 当前回调处理集合中的单个元素。 */ (left, right) => right.sales - left.sales)
.slice(0, 10)
);
@@ -106,7 +106,7 @@ export const buildSourceData = (analytics: OrderAnalytics, itemNames: Record<str
};
},
)
.sort((left, right) => right.value - left.value)
.sort(/* 当前回调处理集合中的单个元素。 */ (left, right) => right.value - left.value)
.slice(0, 6)
.map(
// item 是截取后的商品占比数据,index 用于选择稳定颜色。
@@ -132,7 +132,7 @@ export const buildCategoryData = (analytics: OrderAnalytics, itemNames: Record<s
};
},
)
.sort((left, right) => right.value - left.value)
.sort(/* 当前回调处理集合中的单个元素。 */ (left, right) => right.value - left.value)
.slice(0, 5)
.map(
// item 是截取后的金额排行数据,index 用于选择稳定颜色。
@@ -168,7 +168,7 @@ export const getRangeLabel = (selection: DashboardRangeSelection): string => {
};
/** 计算销量排行中用于进度条归一化的最大值。 */
export const getMaxProductSales = (productSales: DashboardProductPoint[]): number => Math.max(...productSales.map(item => item.sales), 1);
export const getMaxProductSales = (productSales: DashboardProductPoint[]): number => Math.max(...productSales.map(/* 当前回调处理集合中的单个元素。 */ item => item.sales), 1);
/** 判断旧的日期范围请求结果是否仍然可以写入当前页面。 */
export const isCurrentDashboardRequest = (currentSequence: number, requestSequence: number, signal: AbortSignal): boolean => (
@@ -19,6 +19,7 @@ const issue = (cookieID: string, allowed: AutomationRunIssue['allowed_resolution
test('规则异常处理动作遵循后端允许列表',
// 只有后端明确允许的人工动作才能被页面提交。
() => {
// invalid 无效数据。
const invalid = issue('a', ['cancel']);
expect(canResolveAutomationIssue(invalid, 'cancel')).toBe(true);
expect(canResolveAutomationIssue(invalid, 'continue')).toBe(false);
@@ -28,22 +29,23 @@ test('规则异常处理动作遵循后端允许列表',
test('规则异常按账号筛选后再决定是否展示面板',
// 异常面板只展示当前账号的运行异常和延迟任务。
() => {
// visible 可见数据。
const visible = filterAutomationIssues({ runs: [issue('a', ['cancel']), issue('b', ['retry', 'cancel'])], pending_tasks: [] }, 'missing');
expect(visible.runs).toEqual([]);
expect(visible.pending_tasks).toEqual([]);
});
test('规则列表不因异常接口失败而停止加载', async () => {
test('规则列表不因异常接口失败而停止加载', /* 当前回调处理用户交互或异步状态变化。 */ async () => {
// receivedRules 保存主规则列表加载器收到的结果。
const receivedRules: string[][] = [];
// errors 保存异常接口失败后的错误回调。
const errors: unknown[] = [];
await loadAutomationPageData({
loadRules: async () => ['rule'],
loadIssues: async () => { throw new Error('issues unavailable'); },
onRules: rules => receivedRules.push(rules),
onIssues: () => { throw new Error('must not receive issues'); },
onIssuesError: error => errors.push(error),
loadRules: /* 当前回调处理用户交互或异步状态变化。 */ async () => ['rule'],
loadIssues: /* 当前回调处理用户交互或异步状态变化。 */ async () => { throw new Error('issues unavailable'); },
onRules: /* 当前回调处理用户交互或异步状态变化。 */ rules => receivedRules.push(rules),
onIssues: /* 当前回调处理用户交互或异步状态变化。 */ () => { throw new Error('must not receive issues'); },
onIssuesError: /* 当前回调处理用户交互或异步状态变化。 */ error => errors.push(error),
});
expect(receivedRules).toEqual([['rule']]);
expect(errors).toHaveLength(1);
+26 -20
View File
@@ -69,7 +69,7 @@ export const useSettings = (): UseSettingsResult => {
// credentialsMessage 保存登录凭据操作提示。
const [credentialsMessage, setCredentialsMessage] = useState<CredentialsMessage>(null);
// credentials 保存登录凭据编辑草稿。
const [credentials, setCredentials] = useState<CredentialsForm>(() => createCredentials());
const [credentials, setCredentials] = useState<CredentialsForm>(/* 当前回调处理用户交互或异步状态变化。 */ () => createCredentials());
// requestStatus 表示最近一次设置请求的阶段。
const [requestStatus, setRequestStatus] = useState<SettingsRequestStatus>('idle');
// modelPickerRef 指向模型选择器根节点。
@@ -85,16 +85,18 @@ export const useSettings = (): UseSettingsResult => {
settingsRef.current = settings;
/** 取消当前设置请求并创建新的请求控制器。 */
const beginRequest = useCallback(() => {
const beginRequest = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ () => {
// controller 是本次请求的取消控制器。
requestController.current?.abort();
// controller 请求取消控制器。
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) => {
// loadAIModels 加载当前数据(AIModels)。
const loadAIModels = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (source?: SystemSettings | null, openAfterLoad = false, signal?: AbortSignal) => {
// current 是本次模型发现使用的配置快照。
const current = source || settingsRef.current;
// baseUrl 是兼容模型发现接口的服务地址。
@@ -102,14 +104,15 @@ export const useSettings = (): UseSettingsResult => {
setModelsLoading(true);
setModelError('');
try {
// models 模型列表。
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);
setSettings(/* 当前回调处理用户交互或异步状态变化。 */ previous => previous ? { ...previous, ai_model: models[0] } : previous);
}
} catch (error) {
} catch (/* error 表示错误。 */ error) {
if (signal?.aborted || isSettingsAbortError(error)) return;
setAiModels([]);
setModelDropdownOpen(false);
@@ -119,7 +122,8 @@ export const useSettings = (): UseSettingsResult => {
}
}, []);
const loadSettings = useCallback(() => {
// loadSettings 加载当前数据(设置)。
const loadSettings = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ () => {
// request 是本次设置读取的代次与控制器。
const { controller, sequence } = beginRequest();
setLoading(true);
@@ -128,37 +132,38 @@ export const useSettings = (): UseSettingsResult => {
Promise.all([
getSystemSettings({ signal: controller.signal }),
verifySession({ signal: controller.signal }),
]).then(([data, session]) => {
]).then(/* 当前回调处理用户交互或异步状态变化。 */ ([data, session]) => {
if (!isCurrentSettingsRequest(requestSequence.current, sequence, controller.signal)) return;
setSettings(data);
if (session.username) setCredentials(previous => ({ ...previous, new_username: session.username || '' }));
if (session.username) setCredentials(/* 当前回调处理用户交互或异步状态变化。 */ previous => ({ ...previous, new_username: session.username || '' }));
void loadAIModels(data, false, controller.signal);
setRequestStatus('success');
}).catch(error => {
}).catch(/* 当前回调处理用户交互或异步状态变化。 */ error => {
if (!isCurrentSettingsRequest(requestSequence.current, sequence, controller.signal) || isSettingsAbortError(error)) return;
setSettings(null);
setLoadError(settingsErrorMessage(error, '加载配置失败'));
setRequestStatus('error');
}).finally(() => {
}).finally(/* 当前回调处理用户交互或异步状态变化。 */ () => {
if (isCurrentSettingsRequest(requestSequence.current, sequence, controller.signal)) setLoading(false);
});
}, [beginRequest, loadAIModels]);
useEffect(() => {
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => {
loadSettings();
return () => requestController.current?.abort();
return /* 当前回调处理用户交互或异步状态变化。 */ () => requestController.current?.abort();
}, [loadSettings]);
useEffect(() => {
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => {
// handlePointerDown 负责点击模型选择器外部时关闭下拉框。
const handlePointerDown = (event: MouseEvent) => {
if (!modelPickerRef.current?.contains(event.target as Node)) setModelDropdownOpen(false);
};
document.addEventListener('mousedown', handlePointerDown);
return () => document.removeEventListener('mousedown', handlePointerDown);
return /* 当前回调处理用户交互或异步状态变化。 */ () => document.removeEventListener('mousedown', handlePointerDown);
}, []);
const handleSave = useCallback(async () => {
// handleSave 处理当前用户操作(Save)。
const handleSave = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async () => {
// handleSave 提交当前配置草稿并保护过期响应。
if (!settings || saving) return;
// request 是本次保存动作的代次与控制器。
@@ -169,7 +174,7 @@ export const useSettings = (): UseSettingsResult => {
await updateSystemSettings(buildPersistableSettings(settings), { signal: controller.signal });
if (!isCurrentSettingsRequest(requestSequence.current, sequence, controller.signal)) return;
window.alert('系统配置已保存');
} catch (error) {
} catch (/* error 表示错误。 */ error) {
if (!isCurrentSettingsRequest(requestSequence.current, sequence, controller.signal) || isSettingsAbortError(error)) return;
setSaveError(settingsErrorMessage(error, '保存配置失败'));
} finally {
@@ -177,7 +182,8 @@ export const useSettings = (): UseSettingsResult => {
}
}, [beginRequest, saving, settings]);
const handleCredentialsSave = useCallback(async (event: React.FormEvent) => {
// handleCredentialsSave 处理当前用户操作(CredentialsSave)。
const handleCredentialsSave = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async (event: React.FormEvent) => {
// handleCredentialsSave 校验并提交登录凭据表单。
event.preventDefault();
setCredentialsMessage(null);
@@ -203,8 +209,8 @@ export const useSettings = (): UseSettingsResult => {
return;
}
setCredentialsMessage(createCredentialsMessage('success', result.message || '登录凭据已更新'));
window.setTimeout(() => window.location.reload(), 1400);
} catch (error) {
window.setTimeout(/* 当前回调处理用户交互或异步状态变化。 */ () => window.location.reload(), 1400);
} catch (/* error 表示错误。 */ error) {
if (!isCurrentSettingsRequest(requestSequence.current, sequence, controller.signal) || isSettingsAbortError(error)) return;
setCredentialsMessage(createCredentialsMessage('error', settingsErrorMessage(error, '登录凭据更新失败')));
} finally {
@@ -215,7 +221,7 @@ export const useSettings = (): UseSettingsResult => {
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),
credentials, requestStatus, modelPickerRef, loadSettings, loadAIModels: /* 当前回调处理用户交互或异步状态变化。 */ (source, openAfterLoad) => void loadAIModels(source, openAfterLoad),
handleSave, handleCredentialsSave, setSettings, setModelDropdownOpen, setShowApiKey, setShowCaptchaSecret,
setShowCurrentPassword, setShowNewPassword, setCredentials, setCredentialsMessage,
};
+14 -12
View File
@@ -4,18 +4,20 @@ import { AccountDetail, AccountTaskSettings } from '../types';
import { useAccountAutomation } from '../app/features/accountAutomation/hooks';
interface Props {
account: AccountDetail;
onClose: () => void;
onSaved: (settings: AccountTaskSettings) => void;
/** account 表示账号。 */ account: AccountDetail;
/** onClose 表示关闭弹窗的回调。 */ onClose: () => void;
/** onSaved 表示保存完成后的回调。 */ onSaved: (settings: AccountTaskSettings) => void;
}
const Toggle: React.FC<{checked: boolean; onChange: () => void; label: string}> = ({ checked, onChange, label }) => (
// Toggle 渲染可复用的开关控件。
const Toggle: React.FC<{/** checked 表示开关当前是否选中。 */ checked: boolean; /** onChange 表示开关状态变化的回调。 */ onChange: () => void; /** label 表示控件的无障碍名称。 */ label: string}> = ({ checked, onChange, label }) => (
<button type="button" aria-label={label} aria-pressed={checked} onClick={onChange}
className={`relative h-8 w-14 shrink-0 rounded-full transition-colors ${checked ? 'bg-sky-500' : 'bg-slate-300'}`}>
<span className={`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-sm transition-transform ${checked ? 'translate-x-6' : ''}`} />
</button>
);
// AccountAutomationModal 渲染账号自动化设置弹窗。
const AccountAutomationModal: React.FC<Props> = ({ account, onClose, onSaved }) => {
// automationState 是账号任务 feature Hook 提供的表单和动作状态。
const { form, loading, saving, running, error, summary, retryAvailable, setForm, save, run, retry } = useAccountAutomation({ account, onSaved });
@@ -44,14 +46,14 @@ const AccountAutomationModal: React.FC<Props> = ({ account, onClose, onSaved })
<h4 className="font-black text-slate-900">自动评价</h4>
<p className="mt-1 text-xs leading-5 text-slate-500">持续扫描待评价订单,按订单执行;不是每日任务。</p>
</div>
<Toggle checked={form.auto_rate_enabled} onChange={() => setForm(current => ({ ...current, auto_rate_enabled: !current.auto_rate_enabled }))} label="自动评价" />
<Toggle checked={form.auto_rate_enabled} onChange={/* 当前回调处理用户交互或异步状态变化。 */ () => setForm(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, auto_rate_enabled: !current.auto_rate_enabled }))} label="自动评价" />
</div>
<label className="mt-4 block text-xs font-extrabold text-slate-600">统一好评文案</label>
<textarea aria-label="统一好评文案" value={form.rate_content} maxLength={500} onChange={event => setForm(current => ({ ...current, rate_content: event.target.value }))}
<textarea aria-label="统一好评文案" value={form.rate_content} maxLength={500} onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setForm(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, rate_content: event.target.value }))}
className="mt-2 h-24 w-full resize-none rounded-xl border border-slate-200 bg-slate-50 px-3 py-2.5 text-sm leading-6 text-slate-800 placeholder:text-slate-400 outline-none focus:border-sky-400 focus:ring-2 focus:ring-sky-100" />
<div className="mt-3 flex items-center justify-between gap-3">
<span className="text-xs text-slate-400">最近扫描:{form.last_rate_scan_at ? new Date(form.last_rate_scan_at * 1000).toLocaleString('zh-CN') : '尚未执行'}</span>
<button type="button" disabled={running !== '' || !account.enabled} onClick={() => void run('auto_rate')}
<button type="button" disabled={running !== '' || !account.enabled} onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void run('auto_rate')}
className="flex items-center gap-2 rounded-xl bg-emerald-50 px-3 py-2 text-xs font-extrabold text-emerald-700 hover:bg-emerald-100 disabled:opacity-50">
{running === 'auto_rate' ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />}立即评价
</button>
@@ -69,15 +71,15 @@ const AccountAutomationModal: React.FC<Props> = ({ account, onClose, onSaved })
<h4 className="font-black text-slate-900">每日自动擦亮</h4>
<p className="mt-1 text-xs leading-5 text-slate-500">每个账号每天最多执行一次,按北京时间判断。</p>
</div>
<Toggle checked={form.auto_polish_enabled} onChange={() => setForm(current => ({ ...current, auto_polish_enabled: !current.auto_polish_enabled }))} label="每日自动擦亮" />
<Toggle checked={form.auto_polish_enabled} onChange={/* 当前回调处理用户交互或异步状态变化。 */ () => setForm(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, auto_polish_enabled: !current.auto_polish_enabled }))} label="每日自动擦亮" />
</div>
<div className="mt-4 flex items-end justify-between gap-4">
<label className="block">
<span className="text-xs font-extrabold text-slate-600">每日执行时间</span>
<input type="time" value={form.polish_time} onChange={event => setForm(current => ({ ...current, polish_time: event.target.value }))}
<input type="time" value={form.polish_time} onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setForm(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, polish_time: event.target.value }))}
className="mt-2 block rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm font-bold text-slate-800 outline-none focus:border-sky-400" />
</label>
<button type="button" disabled={running !== '' || !account.enabled} onClick={() => void run('auto_polish')}
<button type="button" disabled={running !== '' || !account.enabled} onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void run('auto_polish')}
className="flex items-center gap-2 rounded-xl bg-amber-50 px-3 py-2 text-xs font-extrabold text-amber-700 hover:bg-amber-100 disabled:opacity-50">
{running === 'auto_polish' ? <Loader2 className="h-4 w-4 animate-spin" /> : <CalendarClock className="h-4 w-4" />}立即擦亮
</button>
@@ -92,14 +94,14 @@ const AccountAutomationModal: React.FC<Props> = ({ account, onClose, onSaved })
本次发现 {summary.found} 项,成功 {summary.success},失败 {summary.failed},跳过 {summary.skipped}。{summary.message || ''}
</div>
)}
{error && <div className="flex items-center justify-between gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm font-medium text-red-700"><span>{error}</span>{retryAvailable && <button type="button" className="font-bold underline" onClick={() => void retry()}>重试</button>}</div>}
{error && <div className="flex items-center justify-between gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm font-medium text-red-700"><span>{error}</span>{retryAvailable && <button type="button" className="font-bold underline" onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void retry()}>重试</button>}</div>}
</div>
<div className="modal-footer">
<div className="flex w-full gap-3">
<button type="button" onClick={onClose} disabled={saving || running !== ''}
className="flex-1 rounded-xl bg-gray-100 px-6 py-3 font-bold text-gray-700 transition-colors hover:bg-gray-200 disabled:opacity-50">关闭</button>
<button type="button" onClick={() => void save()} disabled={saving || running !== '' || (form.auto_rate_enabled && !form.rate_content.trim())}
<button type="button" onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void save()} disabled={saving || running !== '' || (form.auto_rate_enabled && !form.rate_content.trim())}
className="ios-btn-primary flex flex-1 items-center justify-center gap-2 rounded-xl px-6 py-3 font-bold disabled:opacity-50">
{saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}保存
</button>
+43 -37
View File
@@ -24,6 +24,7 @@ import { useAccountSubmodules, type AccountModalType } from '../app/features/acc
import { accountRuntimePresentation } from '../app/features/accounts/runtime';
import type { AccountEditForm } from '../app/features/accounts/types';
// AccountList 渲染账号列表组件。
const AccountList: React.FC = () => {
// accountData 保存账号列表及其加载控制器。
const { accounts, setAccounts, loading, loadAccounts } = useAccountsData();
@@ -148,16 +149,16 @@ const AccountList: React.FC = () => {
// scheduleQRModalClose 在登录成功后延迟关闭二维码弹窗。
const scheduleQRModalClose = () => {
clearQRCloseTimer();
qrCloseTimerRef.current = window.setTimeout(() => {
qrCloseTimerRef.current = window.setTimeout(/* 当前回调处理用户交互或异步状态变化。 */ () => {
qrCloseTimerRef.current = null;
setShowQRModal(false);
loadAccounts();
}, 1000);
};
useEffect(() => {
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => {
// 页面卸载时取消二维码、通知绑定、AI 设置和密码登录的异步资源。
return () => {
return /* 当前回调处理用户交互或异步状态变化。 */ () => {
stopQRPolling();
qrRequestGateRef.current?.cancel();
qrGenerateAbortRef.current?.abort();
@@ -194,9 +195,9 @@ const AccountList: React.FC = () => {
setDeleteError('');
try {
await deleteAccount(account.id);
setAccounts(current => current.filter(item => item.id !== account.id));
setAccounts(/* 当前回调处理集合中的单个元素。 */ current => current.filter(/* 当前回调处理集合中的单个元素。 */ item => item.id !== account.id));
setDeleteDialogAccount(null);
} catch (error: any) {
} catch (/* error 表示错误。 */ error: any) {
console.error('删除账号失败:', error);
setDeleteError(error?.message || '删除账号失败,请稍后重试');
} finally {
@@ -214,7 +215,7 @@ const AccountList: React.FC = () => {
alert('资料刷新失败:' + res.profile_error);
}
await loadAccounts();
} catch (error: any) {
} catch (/* error 表示错误。 */ error: any) {
console.error('刷新账号资料失败:', error);
alert(error?.message || '刷新账号资料失败,请先重新授权该账号');
} finally {
@@ -264,14 +265,15 @@ const AccountList: React.FC = () => {
setQrStatus('waiting');
qrPollerRef.current?.start(generatedSessionID, checkQRLoginStatus, {
onSuccess: async () => {
onSuccess: /* 当前回调处理用户交互或异步状态变化。 */ async () => {
try {
// accountId 账号标识,负责当前功能中的对应处理。
const accountId = await completeAndPersistQRSession(generatedSessionID, targetAccount);
if (!accountId) {
setQrStatus('error');
return;
}
} catch (e) {
} catch (/* e 表示e。 */ e) {
console.error('保存扫码授权失败', e);
setQrStatus('error');
return;
@@ -279,17 +281,17 @@ const AccountList: React.FC = () => {
setQrStatus('success');
scheduleQRModalClose();
},
onScanned: () => {
onScanned: /* 当前回调处理用户交互或异步状态变化。 */ () => {
setQrStatus('waiting'); // 已扫描,继续等待确认
},
onTerminalError: () => {
onTerminalError: /* 当前回调处理用户交互或异步状态变化。 */ () => {
setQrStatus('error');
},
onPollError: (error) => {
onPollError: /* 当前回调处理用户交互或异步状态变化。 */ (error) => {
console.error('轮询扫码状态失败', error);
setQrStatus('error');
},
onVerificationRequired: (statusRes) => {
onVerificationRequired: /* 当前回调处理用户交互或异步状态变化。 */ (statusRes) => {
setQrStatus('verification');
if (statusRes.face_qr_url) {
setFaceQrUrl(statusRes.face_qr_url);
@@ -300,7 +302,7 @@ const AccountList: React.FC = () => {
},
});
}
} catch (e) {
} catch (/* e 表示e。 */ e) {
if (!qrRequestGateRef.current?.isCurrent(requestGeneration)) return;
setQrErrorMessage(e instanceof Error ? e.message : '二维码获取失败,请稍后重试');
setQrStatus('error');
@@ -311,7 +313,9 @@ const AccountList: React.FC = () => {
if (loading) return <div className="p-20 flex justify-center"><Loader2 className="w-8 h-8 text-brand animate-spin"/></div>;
const filteredAccounts = accounts.filter(account => {
// filteredAccounts 过滤后的账号列表,负责当前功能中的对应处理。
const filteredAccounts = accounts.filter(/* 当前回调处理集合中的单个元素。 */ account => {
// keyword 搜索关键词。
const keyword = accountSearch.trim().toLowerCase();
if (!keyword) return true;
return [
@@ -320,7 +324,7 @@ const AccountList: React.FC = () => {
account.remark,
account.username,
account.runtime_message,
].some(value => (value || '').toLowerCase().includes(keyword));
].some(/* 当前回调处理用户交互或异步状态变化。 */ value => (value || '').toLowerCase().includes(keyword));
});
return (
@@ -333,12 +337,12 @@ const AccountList: React.FC = () => {
<div className="flex flex-col sm:flex-row gap-3">
<input
value={accountSearch}
onChange={event => setAccountSearch(event.target.value)}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setAccountSearch(event.target.value)}
placeholder="搜索昵称 / 备注 / 账号ID"
className="ios-input px-4 py-3 rounded-2xl text-sm w-full sm:w-72"
/>
<button
onClick={() => startQRLogin()}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => startQRLogin()}
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"
>
<QrCode className="w-5 h-5" />
@@ -354,8 +358,10 @@ const AccountList: React.FC = () => {
{/* Account Grid */}
<div className="grid grid-cols-1 gap-6">
{filteredAccounts.map((account) => {
{filteredAccounts.map(/* 当前回调处理集合中的单个元素。 */ (account) => {
// runtime 运行状态。
const runtime = accountRuntimePresentation(account);
// requiresLogin 是否需要重新登录。
const requiresLogin = account.runtime_state === 'auth_expired' || account.runtime_state === 'verification_required';
return (
<div key={account.id} className="ios-card rounded-xl p-6 group transition-all duration-300 hover:border-brand">
@@ -417,7 +423,7 @@ const AccountList: React.FC = () => {
{requiresLogin && (
<button
type="button"
onClick={() => startQRLogin(account)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => startQRLogin(account)}
className="inline-flex items-center gap-1.5 rounded-lg bg-red-50 px-2.5 py-1 text-xs font-bold text-red-700 hover:bg-red-100"
>
<QrCode className="w-3.5 h-3.5" /> 重新授权
@@ -428,7 +434,7 @@ const AccountList: React.FC = () => {
{account.paused && <span className="flex items-center gap-1.5 rounded-lg bg-blue-50 px-3 py-1.5 text-xs font-bold text-blue-700"><Clock className="h-3 w-3" /> 暂停处理中</span>}
<div className="mt-3 flex flex-wrap items-center justify-end gap-2">
<button
onClick={() => handleRefreshProfile(account)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => handleRefreshProfile(account)}
disabled={refreshingProfileId === account.id}
className="p-3 rounded-xl transition-colors text-gray-600 hover:bg-gray-100 disabled:opacity-50"
title="刷新昵称和头像"
@@ -436,42 +442,42 @@ const AccountList: React.FC = () => {
<RefreshCw className={`w-5 h-5 ${refreshingProfileId === account.id ? 'animate-spin' : ''}`} />
</button>
<button
onClick={() => startQRLogin(account)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => startQRLogin(account)}
className={`p-3 rounded-xl transition-colors ${requiresLogin ? 'text-red-600 bg-red-50 hover:bg-red-100' : 'text-blue-600 hover:bg-blue-50'}`}
title="重新扫码授权当前账号"
>
<QrCode className="w-5 h-5" />
</button>
<button
onClick={() => openEditModal(account)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => openEditModal(account)}
className="p-3 rounded-xl hover:bg-gray-100 transition-colors text-gray-600"
title="编辑账号"
>
<Edit2 className="w-5 h-5" />
</button>
<button
onClick={() => openAIModal(account)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => openAIModal(account)}
className="p-3 rounded-xl hover:bg-purple-100 transition-colors text-purple-600"
title="AI设置"
>
<Bot className="w-5 h-5" />
</button>
<button
onClick={() => setTaskAccount(account)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setTaskAccount(account)}
className="p-3 rounded-xl hover:bg-amber-100 transition-colors text-amber-600"
title="自动评价与每日擦亮"
>
<CalendarClock className="w-5 h-5" />
</button>
<button
onClick={() => handleToggle(account.id, account.enabled)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => handleToggle(account.id, account.enabled)}
className={`p-3 rounded-xl transition-colors ${account.enabled ? 'text-green-600 hover:bg-green-50' : 'text-gray-400 hover:bg-gray-100'}`}
title={account.enabled ? '停用账号' : '启用账号'}
>
<Power className="w-5 h-5" />
</button>
<button
onClick={() => openDeleteDialog(account)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => openDeleteDialog(account)}
disabled={deletingAccountId !== ''}
className="p-3 rounded-xl hover:bg-red-100 transition-colors text-red-500 disabled:cursor-not-allowed disabled:opacity-40"
title={deletingAccountId === account.id ? '删除中…' : `删除账号 ${account.nickname || account.remark || account.id}`}
@@ -507,9 +513,9 @@ const AccountList: React.FC = () => {
{taskAccount && createPortal(
<AccountAutomationModal
account={taskAccount}
onClose={() => setTaskAccount(null)}
onSaved={settings => {
setAccounts(current => current.map(account => account.id === taskAccount.id ? {
onClose={/* 当前回调处理用户交互或异步状态变化。 */ () => setTaskAccount(null)}
onSaved={/* 当前回调处理集合中的单个元素。 */ settings => {
setAccounts(/* 当前回调处理集合中的单个元素。 */ current => current.map(/* 当前回调处理集合中的单个元素。 */ account => account.id === taskAccount.id ? {
...account,
auto_rate_enabled: settings.auto_rate_enabled,
rate_content: settings.rate_content,
@@ -607,7 +613,7 @@ const AccountList: React.FC = () => {
</button>
<button
type="button"
onClick={() => void confirmDeleteAccount()}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void confirmDeleteAccount()}
disabled={deletingAccountId !== ''}
className="flex flex-1 items-center justify-center gap-2 rounded-xl bg-red-600 px-5 py-3 text-sm font-extrabold text-white shadow-lg shadow-red-200 transition-colors hover:bg-red-700 disabled:cursor-not-allowed disabled:bg-red-400"
>
@@ -695,9 +701,9 @@ const AccountList: React.FC = () => {
bindingsLoaded={bindingsLoaded}
bindingsLoading={bindingsLoading}
bindingsLoadError={bindingsLoadError}
onRetryBindings={() => loadNotificationBindings(editingAccount.id)}
onRetryBindings={/* 当前回调处理用户交互或异步状态变化。 */ () => loadNotificationBindings(editingAccount.id)}
onToggleChannel={toggleNotificationChannel}
onSettingsDirty={() => setBindingsDirty(true)}
onSettingsDirty={/* 当前回调处理用户交互或异步状态变化。 */ () => setBindingsDirty(true)}
/>
)}
@@ -734,7 +740,7 @@ const AccountList: React.FC = () => {
</div>
<button
type="button"
onClick={() => setAiSettings({ ...aiSettings, ai_enabled: !aiSettings.ai_enabled })}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setAiSettings({ ...aiSettings, ai_enabled: !aiSettings.ai_enabled })}
className={`w-14 h-8 rounded-full transition-colors duration-300 relative ${
aiSettings.ai_enabled ? 'bg-brand' : 'bg-gray-300'
}`}
@@ -756,7 +762,7 @@ const AccountList: React.FC = () => {
<input
type="number"
value={aiSettings.max_discount_percent}
onChange={(e) => setAiSettings({ ...aiSettings, max_discount_percent: parseInt(e.target.value) || 0 })}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setAiSettings({ ...aiSettings, max_discount_percent: parseInt(e.target.value) || 0 })}
className="w-full ios-input px-4 py-3 rounded-xl"
min="0"
max="100"
@@ -768,7 +774,7 @@ const AccountList: React.FC = () => {
<input
type="number"
value={aiSettings.max_discount_amount}
onChange={(e) => setAiSettings({ ...aiSettings, max_discount_amount: parseInt(e.target.value) || 0 })}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setAiSettings({ ...aiSettings, max_discount_amount: parseInt(e.target.value) || 0 })}
className="w-full ios-input px-4 py-3 rounded-xl"
min="0"
/>
@@ -779,7 +785,7 @@ const AccountList: React.FC = () => {
<input
type="number"
value={aiSettings.max_bargain_rounds}
onChange={(e) => setAiSettings({ ...aiSettings, max_bargain_rounds: parseInt(e.target.value) || 1 })}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setAiSettings({ ...aiSettings, max_bargain_rounds: parseInt(e.target.value) || 1 })}
className="w-full ios-input px-4 py-3 rounded-xl"
min="1"
max="10"
@@ -794,7 +800,7 @@ const AccountList: React.FC = () => {
<label className="block text-sm font-bold text-gray-700 mb-2">自定义提示词(可选)</label>
<textarea
value={aiSettings.custom_prompts}
onChange={(e) => setAiSettings({ ...aiSettings, custom_prompts: e.target.value })}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setAiSettings({ ...aiSettings, custom_prompts: e.target.value })}
placeholder="输入自定义的AI回复规则或风格指引...&#10;&#10;例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等"
className="w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"
/>
+77 -49
View File
@@ -9,6 +9,7 @@ import { useCardBatchActions, useCardsData } from '../app/features/cards/hooks';
import { filterCards } from '../app/features/cards/batchState';
import type { AddCardForm, EditCardForm } from '../app/features/cards/types';
// emptyAddForm 新增卡密表单初始值。
const emptyAddForm = (): AddCardForm => ({
name: '',
type: 'data',
@@ -22,20 +23,31 @@ const emptyAddForm = (): AddCardForm => ({
api_params: '',
});
// CardList 渲染卡密列表组件。
const CardList: React.FC = () => {
// { 解构得到当前 Hook 返回的状态和操作函数。
const { cards, loadCards } = useCardsData();
// [showEditModal, 解构得到当前 Hook 返回的状态和操作函数。
const [showEditModal, setShowEditModal] = useState(false);
// [showAddModal, 解构得到当前 Hook 返回的状态和操作函数。
const [showAddModal, setShowAddModal] = useState(false);
// [selectedCard, 解构得到当前 Hook 返回的状态和操作函数。
const [selectedCard, setSelectedCard] = useState<Card | null>(null);
// [editForm, 解构得到当前 Hook 返回的状态和操作函数。
const [editForm, setEditForm] = useState<EditCardForm>({});
// [addForm, 解构得到当前 Hook 返回的状态和操作函数。
const [addForm, setAddForm] = useState<AddCardForm>(emptyAddForm);
// [typeFilter, 解构得到当前 Hook 返回的状态和操作函数。
const [typeFilter, setTypeFilter] = useState<Card['type'] | ''>('');
// [nameSearch, 解构得到当前 Hook 返回的状态和操作函数。
const [nameSearch, setNameSearch] = useState('');
// dataCards 只保留可追加库存的卡密组,并在卡密数据未变化时保持引用稳定。
const dataCards = useMemo(() => cards.filter(card => card.type === 'data'), [cards]);
const dataCards = useMemo(/* 当前回调处理集合中的单个元素。 */ () => cards.filter(/* 当前回调处理集合中的单个元素。 */ card => card.type === 'data'), [cards]);
// batchState 批量发布状态。
const batchState = useCardBatchActions({ dataCards, loadCards });
// handleEdit 处理当前用户操作(Edit)。
const handleEdit = (card: Card) => {
setSelectedCard(card);
setEditForm({
@@ -62,6 +74,7 @@ const CardList: React.FC = () => {
setShowEditModal(true);
};
// handleSaveEdit 处理当前用户操作(SaveEdit)。
const handleSaveEdit = async () => {
if (!selectedCard) return;
@@ -76,6 +89,7 @@ const CardList: React.FC = () => {
}
try {
// updateData 更新当前数据(返回数据)。
const updateData: Partial<Card> = {
name: editForm.name.trim(),
type: editForm.type as any,
@@ -104,24 +118,26 @@ const CardList: React.FC = () => {
await updateCard(selectedCard.id, updateData);
setShowEditModal(false);
await loadCards();
} catch (error) {
} catch (/* error 表示错误。 */ error) {
console.error('更新卡密失败:', error);
alert('更新失败,请重试');
}
};
// handleDelete 处理当前用户操作(Delete)。
const handleDelete = async (id: string | number) => {
if (confirm('确认删除该卡密吗?')) {
try {
await deleteCard(id);
await loadCards();
} catch (error) {
} catch (/* error 表示错误。 */ error) {
console.error('删除卡密失败:', error);
alert('删除失败,请重试');
}
}
};
// handleAddCard 处理当前用户操作(Add卡密)。
const handleAddCard = async () => {
if (!addForm.name.trim()) {
alert('请输入卡密名称');
@@ -132,6 +148,7 @@ const CardList: React.FC = () => {
return;
}
try {
// payload 请求载荷。
const payload: Partial<Card> = {
name: addForm.name.trim(),
type: addForm.type,
@@ -155,21 +172,23 @@ const CardList: React.FC = () => {
setShowAddModal(false);
setAddForm(emptyAddForm());
await loadCards();
} catch (error) {
} catch (/* error 表示错误。 */ error) {
console.error('添加卡密失败:', error);
alert('添加失败,请重试');
}
};
// toggleCardStatus 切换当前状态(卡密状态)。
const toggleCardStatus = async (card: Card) => {
try {
await updateCard(card.id, { ...card, enabled: !card.enabled });
await loadCards();
} catch (error) {
} catch (/* error 表示错误。 */ error) {
console.error('切换状态失败:', error);
}
};
// copyCardID 复制卡密标识函数。
const copyCardID = async (id: string | number) => {
try {
await navigator.clipboard.writeText(String(id));
@@ -179,23 +198,31 @@ const CardList: React.FC = () => {
}
};
// filteredCards 过滤后的卡密列表,负责当前功能中的对应处理。
const filteredCards = useMemo(
() => filterCards(cards, typeFilter, nameSearch),
/* 当前回调计算并缓存派生数据。 */ () => filterCards(cards, typeFilter, nameSearch),
[cards, nameSearch, typeFilter],
);
// downloadCardTemplate 下载卡密模板函数。
const downloadCardTemplate = () => {
// headers 请求头。
const headers = ['名称', '类型', '内容', '描述', '启用', '延迟秒', '多规格', '规格名', '规格值'];
// rows 行数据。
const rows = [
['VIP月卡', 'data', 'VIP-MONTH-001\nVIP-MONTH-002\nVIP-MONTH-003', '按行消费的卡密队列', '是', '0', '否', '', ''],
['感谢文案', 'text', '感谢购买,如有问题联系客服~', '固定文本', '是', '0', '否', '', ''],
['教程图', 'image', 'https://cdn.example.com/tutorial.jpg', '图片URL', '是', '0', '否', '', ''],
];
// csv csv,负责当前功能中的对应处理。
const csv = [headers, ...rows]
.map(row => row.map(cell => `"${String(cell).replace(/"/g, '""')}"`).join(','))
.map(/* 当前回调处理集合中的单个元素。 */ row => row.map(/* 当前回调处理集合中的单个元素。 */ cell => `"${String(cell).replace(/"/g, '""')}"`).join(','))
.join('\n');
// blob blob,负责当前功能中的对应处理。
const blob = new Blob(['' + csv], { type: 'text/csv;charset=utf-8' });
// url 地址。
const url = URL.createObjectURL(blob);
// link 链接。
const link = document.createElement('a');
link.href = url;
link.download = '卡密组批量导入模板.csv';
@@ -221,7 +248,7 @@ const CardList: React.FC = () => {
批量导入
</button>
<button
onClick={() => setShowAddModal(true)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setShowAddModal(true)}
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"
>
<Plus className="w-5 h-5" />
@@ -238,7 +265,7 @@ const CardList: React.FC = () => {
<select
aria-label="按卡密类型筛选"
value={typeFilter}
onChange={event => setTypeFilter(event.target.value as Card['type'] | '')}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setTypeFilter(event.target.value as Card['type'] | '')}
className="ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm"
>
<option value="">全部类型</option>
@@ -255,7 +282,7 @@ const CardList: React.FC = () => {
aria-label="按卡密名称搜索"
placeholder="搜索卡密名称..."
value={nameSearch}
onChange={event => setNameSearch(event.target.value)}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setNameSearch(event.target.value)}
className="ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"
/>
</div>
@@ -278,11 +305,12 @@ const CardList: React.FC = () => {
</tr>
</thead>
<tbody className="divide-y divide-gray-50">
{filteredCards.map((card) => {
{filteredCards.map(/* 当前回调处理集合中的单个元素。 */ (card) => {
// 计算库存或内容预览
let stockInfo = '';
if (card.type === 'data' && card.data_content) {
const lines = card.data_content.split('\n').filter(line => line.trim());
// lines 文本行列表。
const lines = card.data_content.split('\n').filter(/* 当前回调处理集合中的单个元素。 */ line => line.trim());
stockInfo = `库存: ${lines.length} 条`;
} else if (card.type === 'text' && card.text_content) {
stockInfo = card.text_content;
@@ -304,7 +332,7 @@ const CardList: React.FC = () => {
</td>
<td className="px-3 py-5">
<button
onClick={() => copyCardID(card.id)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => copyCardID(card.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,用于批量铺货表格"
>
@@ -339,7 +367,7 @@ const CardList: React.FC = () => {
</td>
<td className="px-2 py-5">
<button
onClick={() => toggleCardStatus(card)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => toggleCardStatus(card)}
className={`w-12 h-8 rounded-full relative transition-colors ${
card.enabled ? 'bg-green-500' : 'bg-gray-300'
}`}
@@ -352,14 +380,14 @@ const CardList: React.FC = () => {
<td className="px-3 py-5">
<div className="flex items-center justify-end gap-0.5">
<button
onClick={() => handleEdit(card)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => handleEdit(card)}
className="rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black"
title="编辑"
>
<Edit className="w-4 h-4" />
</button>
<button
onClick={() => handleDelete(card.id)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => handleDelete(card.id)}
className="rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500"
>
<Trash2 className="h-4 w-4" />
@@ -388,7 +416,7 @@ const CardList: React.FC = () => {
<div className="modal-header">
<h3 className="text-2xl font-extrabold text-gray-900">编辑卡密</h3>
<button
onClick={() => setShowEditModal(false)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setShowEditModal(false)}
className="p-2 rounded-xl hover:bg-gray-100 transition-colors"
>
<X className="w-5 h-5 text-gray-500" />
@@ -404,7 +432,7 @@ const CardList: React.FC = () => {
<input
type="text"
value={editForm.name || ''}
onChange={(e) => setEditForm({ ...editForm, name: e.target.value })}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, name: e.target.value })}
className="w-full ios-input px-4 py-3 rounded-xl"
placeholder="例如:游戏点卡、会员卡等"
/>
@@ -413,7 +441,7 @@ const CardList: React.FC = () => {
<label className="block text-sm font-bold text-gray-700 mb-2">卡券类型</label>
<select
value={editForm.type || 'text'}
onChange={(e) => setEditForm({ ...editForm, type: e.target.value as any })}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, type: e.target.value as any })}
className="w-full ios-input px-4 py-3 rounded-xl"
>
<option value="">请选择类型</option>
@@ -434,7 +462,7 @@ const CardList: React.FC = () => {
<input
type="url"
value={editForm.api_url || ''}
onChange={(e) => setEditForm({ ...editForm, api_url: e.target.value })}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, api_url: e.target.value })}
className="w-full ios-input px-4 py-3 rounded-xl font-mono text-sm"
placeholder="https://api.example.com/get-card"
/>
@@ -444,7 +472,7 @@ const CardList: React.FC = () => {
<label className="block text-sm font-bold text-gray-700 mb-2">请求方法</label>
<select
value={editForm.api_method || 'GET'}
onChange={(e) => setEditForm({ ...editForm, api_method: e.target.value as 'GET' | 'POST' })}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, api_method: e.target.value as 'GET' | 'POST' })}
className="w-full ios-input px-4 py-3 rounded-xl"
>
<option value="GET">GET</option>
@@ -456,7 +484,7 @@ const CardList: React.FC = () => {
<input
type="number"
value={editForm.api_timeout || 10}
onChange={(e) => setEditForm({ ...editForm, api_timeout: parseInt(e.target.value) || 10 })}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, api_timeout: parseInt(e.target.value) || 10 })}
className="w-full ios-input px-4 py-3 rounded-xl"
min="1"
max="60"
@@ -467,7 +495,7 @@ const CardList: React.FC = () => {
<label className="block text-sm font-bold text-gray-700 mb-2">请求头(JSON 格式)</label>
<textarea
value={editForm.api_headers || ''}
onChange={(e) => setEditForm({ ...editForm, api_headers: e.target.value })}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, api_headers: e.target.value })}
className="w-full ios-input px-4 py-3 rounded-xl h-20 resize-none font-mono text-sm"
placeholder='{"Authorization": "Bearer token"}'
/>
@@ -476,7 +504,7 @@ const CardList: React.FC = () => {
<label className="block text-sm font-bold text-gray-700 mb-2">请求参数(JSON 格式)</label>
<textarea
value={editForm.api_params || ''}
onChange={(e) => setEditForm({ ...editForm, api_params: e.target.value })}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, api_params: e.target.value })}
className="w-full ios-input px-4 py-3 rounded-xl h-20 resize-none font-mono text-sm"
placeholder='{"type": "card", "count": 1}'
/>
@@ -492,7 +520,7 @@ const CardList: React.FC = () => {
<label className="block text-sm font-bold text-gray-700 mb-2">文字内容</label>
<textarea
value={editForm.text_content || ''}
onChange={(e) => setEditForm({ ...editForm, text_content: e.target.value })}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, text_content: e.target.value })}
className="w-full ios-input px-4 py-3 rounded-xl h-32 resize-none"
placeholder="请输入要发送的固定文字内容..."
/>
@@ -508,13 +536,13 @@ const CardList: React.FC = () => {
<label className="block text-sm font-bold text-gray-700 mb-2">数据内容(一行一个)</label>
<textarea
value={editForm.data_content || ''}
onChange={(e) => setEditForm({ ...editForm, data_content: e.target.value })}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, data_content: e.target.value })}
className="w-full ios-input px-4 py-3 rounded-xl h-80 resize-none font-mono text-sm"
placeholder="请输入数据,每行一个:&#10;卡号1:密码1&#10;卡号2:密码2&#10;或者&#10;兑换码1&#10;兑换码2"
/>
<p className="text-xs text-gray-500 mt-2">支持格式:卡号:密码 或 单独的兑换码</p>
<p className="text-xs text-gray-500">当前库存:<span className="font-bold text-blue-600">
{editForm.data_content ? editForm.data_content.split('\n').filter(line => line.trim()).length : 0}
{editForm.data_content ? editForm.data_content.split('\n').filter(/* 当前回调处理集合中的单个元素。 */ line => line.trim()).length : 0}
</span> 条</p>
</div>
</div>
@@ -529,7 +557,7 @@ const CardList: React.FC = () => {
<input
type="url"
value={editForm.image_url || ''}
onChange={(e) => setEditForm({ ...editForm, image_url: e.target.value })}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, image_url: e.target.value })}
className="w-full ios-input px-4 py-3 rounded-xl font-mono text-sm"
placeholder="https://example.com/image.png"
/>
@@ -542,7 +570,7 @@ const CardList: React.FC = () => {
src={editForm.image_url}
alt="预览"
className="max-w-full max-h-48 rounded-xl border border-gray-200"
onError={(e) => { e.currentTarget.src = 'https://via.placeholder.com/400x200?text=图片加载失败'; }}
onError={/* 当前回调处理用户交互或异步状态变化。 */ (e) => { e.currentTarget.src = 'https://via.placeholder.com/400x200?text=图片加载失败'; }}
/>
</div>
)}
@@ -556,7 +584,7 @@ const CardList: React.FC = () => {
<input
type="number"
value={editForm.delay_seconds || 0}
onChange={(e) => setEditForm({ ...editForm, delay_seconds: parseInt(e.target.value) || 0 })}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, delay_seconds: parseInt(e.target.value) || 0 })}
className="flex-1 ios-input px-4 py-3 rounded-xl"
min="0"
max="3600"
@@ -572,7 +600,7 @@ const CardList: React.FC = () => {
<label className="block text-sm font-bold text-gray-700 mb-2">备注信息</label>
<textarea
value={editForm.description || ''}
onChange={(e) => setEditForm({ ...editForm, description: e.target.value })}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, description: e.target.value })}
className="w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"
placeholder="可选的备注信息"
/>
@@ -583,7 +611,7 @@ const CardList: React.FC = () => {
<span className="font-bold text-gray-900">启用状态</span>
<button
type="button"
onClick={() => setEditForm({ ...editForm, enabled: !editForm.enabled })}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setEditForm({ ...editForm, enabled: !editForm.enabled })}
className={`w-14 h-8 rounded-full transition-colors duration-300 relative ${
editForm.enabled ? 'bg-brand' : 'bg-gray-300'
}`}
@@ -601,7 +629,7 @@ const CardList: React.FC = () => {
<div className="modal-footer">
<div className="flex gap-3 w-full">
<button
onClick={() => setShowEditModal(false)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setShowEditModal(false)}
className="flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors"
>
取消
@@ -630,7 +658,7 @@ const CardList: React.FC = () => {
<p className="text-sm text-gray-500 mt-1">选择交付方式并录入自动发货内容</p>
</div>
<button
onClick={() => setShowAddModal(false)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setShowAddModal(false)}
className="p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0"
title="关闭"
>
@@ -645,7 +673,7 @@ const CardList: React.FC = () => {
<input
type="text"
value={addForm.name}
onChange={(e) => setAddForm({ ...addForm, name: e.target.value })}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setAddForm({ ...addForm, name: e.target.value })}
placeholder="例如:VIP会员卡密"
className="w-full ios-input px-4 py-3 rounded-xl"
/>
@@ -656,7 +684,7 @@ const CardList: React.FC = () => {
<div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
<button
type="button"
onClick={() => setAddForm({ ...addForm, type: 'data', content: '' })}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setAddForm({ ...addForm, type: 'data', content: '' })}
className={`p-3 rounded-xl font-bold transition-all ${addForm.type === 'data' ? 'bg-brand text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}
>
<CreditCard className="w-5 h-5 mx-auto mb-1" />
@@ -664,7 +692,7 @@ const CardList: React.FC = () => {
</button>
<button
type="button"
onClick={() => setAddForm({ ...addForm, type: 'text', content: '' })}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setAddForm({ ...addForm, type: 'text', content: '' })}
className={`p-3 rounded-xl font-bold transition-all ${addForm.type === 'text' ? 'bg-brand text-white' : 'bg-gray-100 text-gray-600'}`}
>
<FileText className="w-5 h-5 mx-auto mb-1" />
@@ -672,7 +700,7 @@ const CardList: React.FC = () => {
</button>
<button
type="button"
onClick={() => setAddForm({ ...addForm, type: 'image', content: '' })}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setAddForm({ ...addForm, type: 'image', content: '' })}
className={`p-3 rounded-xl font-bold transition-all ${addForm.type === 'image' ? 'bg-brand text-white' : 'bg-gray-100 text-gray-600'}`}
>
<ImageIcon className="w-5 h-5 mx-auto mb-1" />
@@ -689,7 +717,7 @@ const CardList: React.FC = () => {
<input
type="url"
value={addForm.content}
onChange={(e) => setAddForm({ ...addForm, content: e.target.value })}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setAddForm({ ...addForm, content: e.target.value })}
placeholder="https://api.example.com/get-code"
className="w-full ios-input px-4 py-3 rounded-xl"
/>
@@ -697,20 +725,20 @@ const CardList: React.FC = () => {
<input
type="url"
value={addForm.content}
onChange={(e) => setAddForm({ ...addForm, content: e.target.value })}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setAddForm({ ...addForm, content: e.target.value })}
className="w-full ios-input px-4 py-3 rounded-xl"
placeholder="https://example.com/card.png"
/>
) : (
<textarea
value={addForm.content}
onChange={(e) => setAddForm({ ...addForm, content: e.target.value })}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setAddForm({ ...addForm, content: e.target.value })}
className={`w-full ios-input px-4 py-3 rounded-xl resize-none text-sm ${addForm.type === 'data' ? 'h-48 font-mono' : 'h-32'}`}
placeholder={addForm.type === 'data' ? 'CODE-123456\nCODE-789012\n...' : '请输入每次发货时发送的固定文字'}
/>
)}
{addForm.type === 'data' && (
<p className="text-xs text-gray-500">当前库存:<span className="font-bold text-brand">{addForm.content.split('\n').filter(line => line.trim()).length}</span> 条</p>
<p className="text-xs text-gray-500">当前库存:<span className="font-bold text-brand">{addForm.content.split('\n').filter(/* 当前回调处理集合中的单个元素。 */ line => line.trim()).length}</span> 条</p>
)}
</div>
@@ -719,24 +747,24 @@ const CardList: React.FC = () => {
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">请求方法</label>
<select value={addForm.api_method} onChange={e => setAddForm({...addForm, api_method: e.target.value as 'GET' | 'POST'})} className="w-full ios-input px-4 py-3 rounded-xl">
<select value={addForm.api_method} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, api_method: e.target.value as 'GET' | 'POST'})} className="w-full ios-input px-4 py-3 rounded-xl">
<option value="GET">GET</option>
<option value="POST">POST</option>
</select>
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">超时时间(秒)</label>
<input type="number" min="1" max="60" value={addForm.api_timeout} onChange={e => setAddForm({...addForm, api_timeout: parseInt(e.target.value) || 10})} className="w-full ios-input px-4 py-3 rounded-xl" />
<input type="number" min="1" max="60" value={addForm.api_timeout} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, api_timeout: parseInt(e.target.value) || 10})} className="w-full ios-input px-4 py-3 rounded-xl" />
</div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">请求头(JSON)</label>
<textarea value={addForm.api_headers} onChange={e => setAddForm({...addForm, api_headers: e.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"}' />
<textarea value={addForm.api_headers} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, api_headers: e.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"}' />
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">请求参数(JSON)</label>
<textarea value={addForm.api_params} onChange={e => setAddForm({...addForm, api_params: e.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}"}' />
<textarea value={addForm.api_params} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, api_params: e.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}"}' />
</div>
</div>
</div>
@@ -745,11 +773,11 @@ const CardList: React.FC = () => {
<div className="grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4">
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">描述</label>
<input value={addForm.description} onChange={e => setAddForm({...addForm, description: e.target.value})} placeholder="卡密用途描述(可选)" className="w-full ios-input px-4 py-3 rounded-xl" />
<input value={addForm.description} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, description: e.target.value})} placeholder="卡密用途描述(可选)" className="w-full ios-input px-4 py-3 rounded-xl" />
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">延时发货(秒)</label>
<input type="number" value={addForm.delay_seconds} onChange={e => setAddForm({...addForm, delay_seconds: parseInt(e.target.value) || 0})} className="w-full ios-input px-4 py-3 rounded-xl" min="0" max="3600" />
<input type="number" value={addForm.delay_seconds} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, delay_seconds: parseInt(e.target.value) || 0})} className="w-full ios-input px-4 py-3 rounded-xl" min="0" max="3600" />
</div>
</div>
@@ -759,7 +787,7 @@ const CardList: React.FC = () => {
<div className="modal-footer">
<div className="flex gap-3 w-full">
<button
onClick={() => setShowAddModal(false)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setShowAddModal(false)}
className="flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors"
>
取消
+23 -18
View File
@@ -33,12 +33,15 @@ const Chat: React.FC = () => {
</div>
</div>
<div className="flex gap-1 overflow-x-auto pb-0" role="tablist" aria-label="聊天账号">
{accounts.map(account => {
{accounts.map(/* 当前回调处理集合中的单个元素。 */ account => {
// active 当前状态。
const active = account.id === activeAccountID;
// unread unread,负责当前功能中的对应处理。
const unread = unreadForAccount(account.id);
// online 响应当前用户操作(line)。
const online = account.runtime_state === 'online';
return (
<button key={account.id} type="button" role="tab" aria-selected={active} onClick={() => setActiveAccountID(account.id)}
<button key={account.id} type="button" role="tab" aria-selected={active} onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setActiveAccountID(account.id)}
className={`relative flex h-11 shrink-0 items-center gap-2 border-b-2 px-3 text-sm font-extrabold transition-colors ${active ? 'border-sky-500 text-sky-700' : 'border-transparent text-slate-500 hover:text-slate-900'}`}>
<span className={`h-2 w-2 rounded-full ${online ? 'bg-emerald-500' : 'bg-slate-300'}`} />
<span className="max-w-36 truncate">{account.nickname || account.remark || account.id}</span>
@@ -61,22 +64,22 @@ const Chat: React.FC = () => {
<div className="space-y-3 border-b border-slate-200 p-3">
<div className="relative">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
<input value={search} onChange={event => setSearch(event.target.value)} placeholder="搜索用户、商品或消息"
<input value={search} onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setSearch(event.target.value)} placeholder="搜索用户、商品或消息"
className="h-10 w-full rounded-xl border border-slate-200 bg-white pl-9 pr-3 text-sm outline-none transition focus:border-sky-400 focus:ring-2 focus:ring-sky-100" />
</div>
<div className="flex items-center justify-between">
<button type="button" onClick={() => setUnreadOnly(value => !value)}
<button type="button" onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setUnreadOnly(/* 当前回调处理用户交互或异步状态变化。 */ value => !value)}
className={`rounded-lg px-2.5 py-1.5 text-xs font-bold ${unreadOnly ? 'bg-sky-100 text-sky-700' : 'text-slate-500 hover:bg-slate-100'}`}>
{unreadOnly ? '只看未读' : '全部会话'}
</button>
<button type="button" title="刷新会话" onClick={() => void reloadSessions(activeAccountID)} className="rounded-lg p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700">
<button type="button" title="刷新会话" onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void reloadSessions(activeAccountID)} className="rounded-lg p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700">
<RefreshCw className="h-4 w-4" />
</button>
</div>
</div>
<div className="min-h-0 flex-1 overflow-y-auto">
{filteredSessions.map(session => (
<button key={session.chat_id} type="button" onClick={() => setActiveChatID(session.chat_id)}
{filteredSessions.map(/* 当前回调处理集合中的单个元素。 */ session => (
<button key={session.chat_id} type="button" onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setActiveChatID(session.chat_id)}
className={`flex w-full gap-3 border-b border-slate-100 p-4 text-left transition-colors ${session.chat_id === activeChatID ? 'bg-white shadow-chat-active' : 'hover:bg-white/80'}`}>
<div className="flex h-10 w-10 shrink-0 items-center justify-center overflow-hidden rounded-full bg-slate-200 text-slate-500">
{session.buyer_avatar_url ? <img src={session.buyer_avatar_url} alt="" className="h-full w-full object-cover" /> : <UserRound className="h-5 w-5" />}
@@ -96,7 +99,7 @@ const Chat: React.FC = () => {
))}
{filteredSessions.length === 0 && <div className="px-6 py-16 text-center text-sm text-slate-400">当前账号暂无匹配会话</div>}
{hasMoreContacts && !search && !unreadOnly && <div className="flex justify-center p-4">
<button type="button" onClick={() => void loadMoreContacts()} disabled={contactsLoading}
<button type="button" onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void loadMoreContacts()} disabled={contactsLoading}
className="flex items-center gap-2 rounded-full border border-slate-200 bg-white px-4 py-2 text-xs font-bold text-slate-500 shadow-sm hover:border-sky-200 hover:text-sky-600 disabled:opacity-50">
{contactsLoading && <Loader2 className="h-3.5 w-3.5 animate-spin" />}{contactsLoading ? '正在加载' : '加载更多历史联系人'}
</button>
@@ -119,13 +122,15 @@ const Chat: React.FC = () => {
<div ref={scrollRef} onScroll={handleMessageScroll} className="min-h-0 flex-1 space-y-5 overflow-y-auto px-6 py-5">
{messagesLoading ? <div className="flex justify-center py-12"><Loader2 className="h-6 w-6 animate-spin text-sky-500" /></div> : <>
{hasOlder && <div className="flex justify-center pb-1">
<button type="button" onClick={() => void loadOlderMessages()} disabled={olderLoading}
<button type="button" onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void loadOlderMessages()} disabled={olderLoading}
className="flex items-center gap-2 rounded-full border border-slate-200 bg-white px-4 py-1.5 text-xs font-bold text-slate-500 shadow-sm transition hover:border-sky-200 hover:text-sky-600 disabled:opacity-50">
{olderLoading && <Loader2 className="h-3.5 w-3.5 animate-spin" />}{olderLoading ? '正在加载' : '加载更早消息'}
</button>
</div>}
{messages.map(message => {
{messages.map(/* 当前回调处理集合中的单个元素。 */ message => {
// outgoing 是否为发送方消息。
const outgoing = message.direction === 'outgoing';
// system 系统。
const system = message.message_type === 'system';
if (system) {
return (
@@ -166,27 +171,27 @@ const Chat: React.FC = () => {
})}
</>}
</div>
{error && <div className="flex items-center justify-between gap-3 border-t border-red-100 bg-red-50 px-5 py-2 text-xs font-medium text-red-700"><span>{error}</span>{retryAvailable && <button type="button" className="font-bold underline" onClick={() => void retrySend()}>重试发送</button>}</div>}
{error && <div className="flex items-center justify-between gap-3 border-t border-red-100 bg-red-50 px-5 py-2 text-xs font-medium text-red-700"><span>{error}</span>{retryAvailable && <button type="button" className="font-bold underline" onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void retrySend()}>重试发送</button>}</div>}
<div className="relative z-10 shrink-0 border-t border-slate-200 bg-white p-4 shadow-chat-input">
<div className="mb-2 flex items-center gap-1">
<div className="relative">
<button type="button" onClick={() => setEmojiOpen(value => !value)} disabled={sending || activeAccount?.runtime_state !== 'online'} className="rounded-lg p-2 text-slate-500 hover:bg-sky-50 hover:text-sky-600 disabled:opacity-40" title="闲鱼表情"><Smile className="h-5 w-5" /></button>
<button type="button" onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setEmojiOpen(/* 当前回调处理用户交互或异步状态变化。 */ value => !value)} disabled={sending || activeAccount?.runtime_state !== 'online'} className="rounded-lg p-2 text-slate-500 hover:bg-sky-50 hover:text-sky-600 disabled:opacity-40" title="闲鱼表情"><Smile className="h-5 w-5" /></button>
{emojiOpen && <div className="absolute bottom-11 left-0 z-30 w-[360px] rounded-2xl border border-slate-200 bg-white p-3 shadow-2xl">
<div className="mb-2 text-xs font-bold text-slate-500">全部表情</div>
<div className="grid max-h-72 grid-cols-8 gap-1 overflow-y-auto">
{xianyuEmojis.map(([name, file]) => <button key={name} type="button" title={`[${name}]`} onClick={() => { setDraft(value => value + `[${name}]`); setEmojiOpen(false); }} className="flex h-10 w-10 items-center justify-center rounded-lg hover:bg-slate-100"><img src={emojiURL(file)} alt={`[${name}]`} className="h-8 w-8 object-contain" /></button>)}
{xianyuEmojis.map(/* 当前回调处理集合中的单个元素。 */ ([name, file]) => <button key={name} type="button" title={`[${name}]`} onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => { setDraft(/* 当前回调处理用户交互或异步状态变化。 */ value => value + `[${name}]`); setEmojiOpen(false); }} className="flex h-10 w-10 items-center justify-center rounded-lg hover:bg-slate-100"><img src={emojiURL(file)} alt={`[${name}]`} className="h-8 w-8 object-contain" /></button>)}
</div>
</div>}
</div>
<input ref={imageInputRef} type="file" accept="image/*" className="hidden" onChange={event => void handleImage(event.target.files?.[0])} />
<button type="button" onClick={() => imageInputRef.current?.click()} disabled={sending || activeAccount?.runtime_state !== 'online'} className="rounded-lg p-2 text-slate-500 transition hover:bg-sky-50 hover:text-sky-600 disabled:opacity-40" title="发送图片(最大 10MB)"><ImagePlus className="h-5 w-5" /></button>
<input ref={imageInputRef} type="file" accept="image/*" className="hidden" onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => void handleImage(event.target.files?.[0])} />
<button type="button" onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => imageInputRef.current?.click()} disabled={sending || activeAccount?.runtime_state !== 'online'} className="rounded-lg p-2 text-slate-500 transition hover:bg-sky-50 hover:text-sky-600 disabled:opacity-40" title="发送图片(最大 10MB)"><ImagePlus className="h-5 w-5" /></button>
</div>
<div className="flex items-end gap-3 rounded-2xl border border-slate-200 bg-slate-50 p-2 transition focus-within:border-sky-400 focus-within:ring-2 focus-within:ring-sky-100">
<textarea value={draft} onChange={event => setDraft(event.target.value)} rows={2} maxLength={2000}
onKeyDown={event => { if (event.key === 'Enter' && !event.shiftKey) { event.preventDefault(); void handleSend(); } }}
<textarea value={draft} onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setDraft(event.target.value)} rows={2} maxLength={2000}
onKeyDown={/* 当前回调处理用户交互或异步状态变化。 */ event => { if (event.key === 'Enter' && !event.shiftKey) { event.preventDefault(); void handleSend(); } }}
disabled={activeAccount?.runtime_state !== 'online'} placeholder={activeAccount?.runtime_state === 'online' ? '输入消息,Enter 发送,Shift + Enter 换行' : '账号离线,暂时无法发送'}
className="max-h-32 min-h-12 flex-1 resize-none bg-transparent px-2 py-2 text-sm leading-6 outline-none disabled:cursor-not-allowed" />
<button type="button" onClick={() => void handleSend()} disabled={!draft.trim() || sending || activeAccount?.runtime_state !== 'online'} className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-sky-500 text-white shadow-md shadow-sky-100 transition hover:bg-sky-600 disabled:cursor-not-allowed disabled:bg-slate-300 disabled:shadow-none" aria-label="发送消息">
<button type="button" onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void handleSend()} disabled={!draft.trim() || sending || activeAccount?.runtime_state !== 'online'} className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-sky-500 text-white shadow-md shadow-sky-100 transition hover:bg-sky-600 disabled:cursor-not-allowed disabled:bg-slate-300 disabled:shadow-none" aria-label="发送消息">
{sending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Send className="h-4 w-4" />}
</button>
</div>
+7 -3
View File
@@ -5,12 +5,16 @@ import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, test } from 'vitest';
import { StatusBadge } from './Dashboard';
// dashboardSource 仪表盘测试数据源。
const dashboardSource = readFileSync(resolve(__dirname, 'Dashboard.tsx'), 'utf8');
// trendChartSource 趋势图测试数据源。
const trendChartSource = readFileSync(resolve(__dirname, '../app/features/dashboard/DashboardTrendChart.tsx'), 'utf8');
// globalStyles 测试用全局样式。
const globalStyles = readFileSync(resolve(__dirname, '../index.css'), 'utf8');
describe('Dashboard presentation safeguards', () => {
test('keeps order status badges on one line', () => {
describe('Dashboard presentation safeguards', /* 当前回调处理用户交互或异步状态变化。 */ () => {
test('keeps order status badges on one line', /* 当前回调处理用户交互或异步状态变化。 */ () => {
// html 渲染后的 HTML。
const html = renderToStaticMarkup(<StatusBadge status="shipped" />);
expect(html).toContain('已发货');
@@ -19,7 +23,7 @@ describe('Dashboard presentation safeguards', () => {
expect(dashboardSource).toContain('min-w-[760px]');
});
test('pie charts use enlarged active sectors without focus rings or external label lines', () => {
test('pie charts use enlarged active sectors without focus rings or external label lines', /* 当前回调处理用户交互或异步状态变化。 */ () => {
expect(dashboardSource.match(/accessibilityLayer=\{false\}/g)).toHaveLength(2);
expect(dashboardSource.match(/activeShape=\{\{/g)).toHaveLength(2);
expect(dashboardSource).toContain('outerRadius: 96');
+44 -17
View File
@@ -7,6 +7,7 @@ import { Tooltip, ResponsiveContainer, PieChart, Pie, Cell, Legend } from 'recha
import { useDashboard } from '../app/features/dashboard/hooks';
import { DashboardTrendChart } from '../app/features/dashboard/DashboardTrendChart';
// cssColor 状态颜色样式。
const cssColor = (token: string, alpha?: number) => (
alpha === undefined
? `rgb(var(--color-${token}))`
@@ -14,7 +15,8 @@ const cssColor = (token: string, alpha?: number) => (
);
// 状态徽章组件
export const StatusBadge: React.FC<{ status: OrderStatus }> = ({ status }) => {
export const StatusBadge: React.FC<{ /** status 表示状态。 */ status: OrderStatus }> = ({ status }) => {
// styles 样式表。
const styles = {
processing: 'bg-blue-100 text-blue-800',
pending_ship: 'bg-brand text-white',
@@ -25,6 +27,7 @@ export const StatusBadge: React.FC<{ status: OrderStatus }> = ({ status }) => {
unknown: 'bg-gray-100 text-gray-500',
};
// labels labels,负责当前功能中的对应处理。
const labels = {
processing: '处理中',
pending_ship: '待发货',
@@ -42,7 +45,8 @@ export const StatusBadge: React.FC<{ status: OrderStatus }> = ({ status }) => {
);
};
const StatCard: React.FC<{ title: string; value: string | number; icon: React.ElementType; colorClass: string; trend?: string }> = ({ title, value, icon: Icon, colorClass, trend }) => (
// StatCard 渲染统计卡片组件。
const StatCard: React.FC<{ /** title 表示标题。 */ title: string; /** value 表示值。 */ value: string | number; /** icon 表示icon。 */ icon: React.ElementType; /** colorClass 表示颜色Class。 */ colorClass: string; /** trend 表示趋势。 */ trend?: string }> = ({ title, value, icon: Icon, colorClass, trend }) => (
<div className="ios-card p-6 rounded-xl flex flex-col justify-between hover:translate-y-[-4px] transition-all duration-300 h-full relative overflow-hidden group border-0">
<div className={`absolute -right-6 -top-6 w-32 h-32 ${colorClass} opacity-10 rounded-full group-hover:scale-125 transition-transform duration-500 blur-2xl`}></div>
<div className="flex justify-between items-start mb-6">
@@ -60,21 +64,37 @@ const StatCard: React.FC<{ title: string; value: string | number; icon: React.El
</div>
);
// Dashboard 渲染仪表盘页面组件。
const Dashboard: React.FC = () => {
// [timeRange, 解构得到当前 Hook 返回的状态和操作函数。
const [timeRange, setTimeRange] = useState<TimeRange>('7days');
// [customStartDate, 解构得到当前 Hook 返回的状态和操作函数。
const [customStartDate, setCustomStartDate] = useState('');
// [customEndDate, 解构得到当前 Hook 返回的状态和操作函数。
const [customEndDate, setCustomEndDate] = useState('');
// [searchTerm, 解构得到当前 Hook 返回的状态和操作函数。
const [searchTerm, setSearchTerm] = useState('');
// [customRangeVersion, 解构得到当前 Hook 返回的状态和操作函数。
const [customRangeVersion, setCustomRangeVersion] = useState(0);
// dashboard 仪表盘数据。
const dashboard = useDashboard({ range: timeRange, customStartDate, customEndDate, customRangeVersion });
// { 解构得到当前 Hook 返回的状态和操作函数。
const { data, status, chartData, productSalesData, sourceData: sourceDataData, categoryData: categoryDataData, maxProductSales, trendPercent, selectedRangeLabel, refresh } = dashboard;
// stats 统计概览数据。
const stats = data?.stats || null;
// analytics 统计分析数据。
const analytics = data?.analytics || null;
// previousAnalytics 上一份统计数据。
const previousAnalytics = data?.previousAnalytics || null;
// validOrders 有效订单列表。
const validOrders = data?.validOrders.orders || [];
// validOrdersTotal 有效数据订单列表总数,负责当前功能中的对应处理。
const validOrdersTotal = data?.validOrders.total || 0;
// validOrdersTruncated 有效数据订单列表Truncated,负责当前功能中的对应处理。
const validOrdersTruncated = data?.validOrders.truncated || false;
// ordersLoading 订单加载状态。
const ordersLoading = status.range === 'loading';
// loadError 加载当前数据(错误)。
const loadError = status.error;
// 颜色配置
@@ -85,6 +105,7 @@ const Dashboard: React.FC = () => {
cssColor('warning-500'),
cssColor('accent-500'),
];
// formatCurrency 格式化金额函数。
const formatCurrency = (value: number) => `¥${Number(value || 0).toLocaleString('zh-CN', { maximumFractionDigits: 2 })}`;
if (loadError && (!stats || !analytics)) {
@@ -97,9 +118,12 @@ const Dashboard: React.FC = () => {
);
}
if (!stats || !analytics) return <div className="p-8 flex justify-center text-gray-400"><Activity className="w-8 h-8 animate-spin text-brand" /></div>;
// totalOrders 总数订单列表,负责当前功能中的对应处理。
const totalOrders = analytics.revenue_stats.total_orders || 0;
// totalAmount 订单总金额。
const totalAmount = analytics.revenue_stats.total_amount || 0;
// timeRangeOptions time范围Options,负责当前功能中的对应处理。
const timeRangeOptions = [
{ key: 'today' as TimeRange, label: '今天' },
{ key: 'yesterday' as TimeRange, label: '昨天' },
@@ -108,14 +132,17 @@ const Dashboard: React.FC = () => {
{ key: '30days' as TimeRange, label: '一个月内' },
{ key: 'custom' as TimeRange, label: '自定义' },
];
// currentRangeDates 当前统计日期范围。
let currentRangeDates;
try {
currentRangeDates = getDateRange(timeRange, new Date(), customStartDate, customEndDate);
} catch {
currentRangeDates = { startDate: customStartDate, endDate: customEndDate };
}
// normalizedSearchTerm 归一化当前数据(d搜索条件Term)。
const normalizedSearchTerm = searchTerm.trim().toLowerCase();
const filteredValidOrders = validOrders.filter((order) =>
// filteredValidOrders 过滤后的有效订单列表。
const filteredValidOrders = validOrders.filter(/* 当前回调处理集合中的单个元素。 */ (order) =>
order.order_id?.toLowerCase().includes(normalizedSearchTerm) ||
order.item_id?.toLowerCase().includes(normalizedSearchTerm) ||
order.item_title?.toLowerCase().includes(normalizedSearchTerm) ||
@@ -145,10 +172,10 @@ const Dashboard: React.FC = () => {
{/* Time Range Selector */}
<div className="flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl">
{timeRangeOptions.map((option) => (
{timeRangeOptions.map(/* 当前回调处理集合中的单个元素。 */ (option) => (
<button
key={option.key}
onClick={() => setTimeRange(option.key)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setTimeRange(option.key)}
className={`px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${
timeRange === option.key
? 'bg-brand text-white shadow-md'
@@ -163,18 +190,18 @@ const Dashboard: React.FC = () => {
<input
type="date"
value={customStartDate}
onChange={(e) => setCustomStartDate(e.target.value)}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setCustomStartDate(e.target.value)}
className="px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand"
/>
<span className="self-center text-gray-400">-</span>
<input
type="date"
value={customEndDate}
onChange={(e) => setCustomEndDate(e.target.value)}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setCustomEndDate(e.target.value)}
className="px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand"
/>
<button
onClick={() => setCustomRangeVersion(value => value + 1)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setCustomRangeVersion(/* 当前回调处理用户交互或异步状态变化。 */ value => value + 1)}
className="px-4 py-2 rounded-xl text-sm font-bold bg-black text-white hover:bg-gray-800 transition-colors"
>
应用
@@ -224,7 +251,7 @@ const Dashboard: React.FC = () => {
<div className="flex items-center justify-center h-full text-gray-400">暂无数据</div>
) : (
<div className="h-full space-y-4 overflow-y-auto pr-2">
{productSalesData.map((item, index) => (
{productSalesData.map(/* 当前回调处理集合中的单个元素。 */ (item, index) => (
<div key={`${item.name}-${index}`} className="space-y-2">
<div className="flex items-center justify-between gap-4">
<div className="flex items-center gap-3 min-w-0">
@@ -279,12 +306,12 @@ const Dashboard: React.FC = () => {
label={false}
labelLine={false}
>
{sourceDataData.map((entry, index) => (
{sourceDataData.map(/* 当前回调处理集合中的单个元素。 */ (entry, index) => (
<Cell key={`cell-${index}`} fill={entry.color} />
))}
</Pie>
<Tooltip
formatter={(value) => `${Number(value || 0)} 单`}
formatter={/* 当前回调处理用户交互或异步状态变化。 */ (value) => `${Number(value || 0)} 单`}
wrapperStyle={{ zIndex: 30, outline: 'none' }}
contentStyle={{
backgroundColor: cssColor('white'),
@@ -297,7 +324,7 @@ const Dashboard: React.FC = () => {
verticalAlign="bottom"
height={36}
iconType="circle"
formatter={(value) => <span style={{ color: cssColor('neutral-500'), fontWeight: 500 }}>{value}</span>}
formatter={/* 当前回调处理用户交互或异步状态变化。 */ (value) => <span style={{ color: cssColor('neutral-500'), fontWeight: 500 }}>{value}</span>}
/>
</PieChart>
</ResponsiveContainer>
@@ -326,7 +353,7 @@ const Dashboard: React.FC = () => {
<input
placeholder="搜索订单号/商品/买家..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setSearchTerm(e.target.value)}
className="pl-4 pr-4 py-2 rounded-xl bg-white border border-gray-100 text-sm focus:border-blue-400 outline-none w-48"
type="text"
/>
@@ -373,7 +400,7 @@ const Dashboard: React.FC = () => {
</tr>
</thead>
<tbody className="divide-y divide-gray-50">
{filteredValidOrders.map((order) => (
{filteredValidOrders.map(/* 当前回调处理集合中的单个元素。 */ (order) => (
<tr key={order.order_id} className="hover:bg-warning-50/50 transition-colors group">
<td className="px-6 py-4">
<div className="flex items-center gap-3">
@@ -451,7 +478,7 @@ const Dashboard: React.FC = () => {
label={false}
labelLine={false}
>
{categoryDataData.map((entry, index) => (
{categoryDataData.map(/* 当前回调处理集合中的单个元素。 */ (entry, index) => (
<Cell key={`cell-${index}`} fill={entry.color || COLORS[index % COLORS.length]} />
))}
</Pie>
@@ -463,7 +490,7 @@ const Dashboard: React.FC = () => {
borderRadius: '6px',
boxShadow: 'var(--shadow-md)'
}}
formatter={(value) => `¥${Number(value || 0).toLocaleString()}`}
formatter={/* 当前回调处理用户交互或异步状态变化。 */ (value) => `¥${Number(value || 0).toLocaleString()}`}
/>
</PieChart>
</ResponsiveContainer>
@@ -473,7 +500,7 @@ const Dashboard: React.FC = () => {
</div>
</div>
<div className="space-y-3 mt-4">
{categoryDataData.map((cat) => (
{categoryDataData.map(/* 当前回调处理集合中的单个元素。 */ (cat) => (
<div key={cat.name} className="flex justify-between items-center gap-3 text-sm">
<div className="flex items-center gap-2 min-w-0 flex-1">
<div
+141 -84
View File
@@ -23,28 +23,47 @@ import { batchStatusClass, batchStatusText } from '../app/features/items/batchSt
import { BatchPhaseIndicator } from '../app/features/items/components/BatchPhaseIndicator';
import { ArrowRight, Box, CheckCircle2, CircleDashed, Edit, Filter, Link2, LocateFixed, PackagePlus, Plus, RefreshCw, Save, Search, ShoppingBag, Trash2, UploadCloud, User, X } from 'lucide-react';
// formatItemPrice 将商品价格转换为本地化展示文本。
const formatItemPrice = (price?: string) => {
// value 值。
const value = String(price || '').trim();
if (!value) return '-';
return /^[¥¥]/.test(value) ? value : `¥${value}`;
};
// ItemList 渲染商品列表组件。
const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
// [items, 解构得到当前 Hook 返回的状态和操作函数。
const [items, setItems] = useState<Item[]>([]);
// [shippingRules, 解构得到当前 Hook 返回的状态和操作函数。
const [shippingRules, setShippingRules] = useState<ShippingRule[]>([]);
// [accounts, 解构得到当前 Hook 返回的状态和操作函数。
const [accounts, setAccounts] = useState<AccountDetail[]>([]);
// [selectedAccount, 解构得到当前 Hook 返回的状态和操作函数。
const [selectedAccount, setSelectedAccount] = useState<string>('');
// [accountFilter, 解构得到当前 Hook 返回的状态和操作函数。
const [accountFilter, setAccountFilter] = useState<string>('');
// [loading, 解构得到当前 Hook 返回的状态和操作函数。
const [loading, setLoading] = useState(false);
// [publishing, 解构得到当前 Hook 返回的状态和操作函数。
const [publishing, setPublishing] = useState(false);
// [showEditModal, 解构得到当前 Hook 返回的状态和操作函数。
const [showEditModal, setShowEditModal] = useState(false);
// [showAddModal, 解构得到当前 Hook 返回的状态和操作函数。
const [showAddModal, setShowAddModal] = useState(false);
// [showPublishModal, 解构得到当前 Hook 返回的状态和操作函数。
const [showPublishModal, setShowPublishModal] = useState(false);
// [locationLoading, 解构得到当前 Hook 返回的状态和操作函数。
const [locationLoading, setLocationLoading] = useState(false);
// [publishLocations, 解构得到当前 Hook 返回的状态和操作函数。
const [publishLocations, setPublishLocations] = useState<PublishLocation[]>([]);
// [publishLocation, 解构得到当前 Hook 返回的状态和操作函数。
const [publishLocation, setPublishLocation] = useState<PublishLocation | null>(null);
// [selectedItem, 解构得到当前 Hook 返回的状态和操作函数。
const [selectedItem, setSelectedItem] = useState<Item | null>(null);
// [editForm, 解构得到当前 Hook 返回的状态和操作函数。
const [editForm, setEditForm] = useState<Partial<Item>>({});
// [addForm, 解构得到当前 Hook 返回的状态和操作函数。
const [addForm, setAddForm] = useState({
cookie_id: '',
item_id: '',
@@ -52,6 +71,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
item_price: '',
item_image: ''
});
// [publishForm, 解构得到当前 Hook 返回的状态和操作函数。
const [publishForm, setPublishForm] = useState({
cookie_id: '',
title: '',
@@ -63,21 +83,24 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
postage: '',
images: [] as File[],
});
const [publishImagePreviews, setPublishImagePreviews] = useState<{ key: string; url: string }[]>([]);
// [publishImagePreviews, 解构得到当前 Hook 返回的状态和操作函数。
const [publishImagePreviews, setPublishImagePreviews] = useState<{ /** key 表示key。 */ key: string; /** url 表示地址。 */ url: string }[]>([]);
// loadItems 刷新商品列表,供普通操作和批量任务完成后复用。
const loadItems = useCallback(async () => {
const loadItems = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async () => {
// itemsList 商品列表列表,负责当前功能中的对应处理。
const itemsList = await getItems();
setItems(itemsList);
}, []);
// loadShippingRules 刷新商品关联的自动化规则。
const loadShippingRules = useCallback(async () => {
const loadShippingRules = useCallback(/* 当前回调封装可复用的交互处理逻辑。 */ async () => {
setShippingRules(await getShippingRules());
}, []);
// batchState 是 ItemList feature 提供的批量铺货状态和动作边界。
const batchState = useItemPublishBatch({ selectedAccount, loadItems, loadShippingRules });
// 解构数据 解构得到当前 Hook 返回的状态和操作函数。
const {
showBatchModal,
setShowBatchModal,
@@ -111,42 +134,46 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
handleRetryBatchFailed,
} = batchState;
useEffect(() => {
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => {
if (!showPublishModal || publishForm.images.length === 0) {
setPublishImagePreviews([]);
return;
}
const previews = publishForm.images.map((file, index) => ({
// previews previews,负责当前功能中的对应处理。
const previews = publishForm.images.map(/* 当前回调处理集合中的单个元素。 */ (file, index) => ({
key: file.name + index,
url: URL.createObjectURL(file),
}));
setPublishImagePreviews(previews);
return () => {
previews.forEach(preview => URL.revokeObjectURL(preview.url));
return /* 当前回调处理用户交互或异步状态变化。 */ () => {
previews.forEach(/* 当前回调处理集合中的单个元素。 */ preview => URL.revokeObjectURL(preview.url));
};
}, [showPublishModal, publishForm.images]);
useEffect(() => {
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => {
Promise.all([getAccountDetails(), getItems(), getShippingRules(), getItemPublishBatches(20)])
.then(([accountList, itemList, ruleList, batches]) => {
.then(/* 当前回调处理异步操作结果。 */ ([accountList, itemList, ruleList, batches]) => {
setAccounts(accountList);
setItems(itemList);
setShippingRules(ruleList);
const recoverable = batches.find(batch => ['running', 'canceling'].includes(batch.status))
|| batches.find(batch => batch.status !== 'preview');
// recoverable 可恢复任务。
const recoverable = batches.find(/* 当前回调处理集合中的单个元素。 */ batch => ['running', 'canceling'].includes(batch.status))
|| batches.find(/* 当前回调处理集合中的单个元素。 */ batch => batch.status !== 'preview');
setRecentBatch(recoverable || null);
})
.catch((e) => console.error('加载商品配置失败:', e));
.catch(/* 当前回调处理异步操作结果。 */ (e) => console.error('加载商品配置失败:', e));
}, []);
// handleSync 处理当前用户操作(Sync)。
const handleSync = async () => {
if (!selectedAccount) return alert('请先选择账号');
setLoading(true);
try {
// result 处理结果。
const result = await syncItemsFromAccount(selectedAccount);
await loadItems();
alert(result?.message || '商品同步完成');
} catch (error: any) {
} catch (/* error 表示错误。 */ error: any) {
console.error('同步商品失败:', error);
alert(error?.message || '同步失败,请重试');
} finally {
@@ -154,12 +181,14 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
}
};
// handleEdit 处理当前用户操作(Edit)。
const handleEdit = (item: Item) => {
setSelectedItem(item);
setEditForm({ ...item });
setShowEditModal(true);
};
// handleSaveEdit 处理当前用户操作(SaveEdit)。
const handleSaveEdit = async () => {
if (!selectedItem) return;
try {
@@ -174,24 +203,26 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
await loadShippingRules();
setShowEditModal(false);
setSelectedItem(null);
} catch (error) {
} catch (/* error 表示错误。 */ error) {
console.error('更新商品失败:', error);
alert('更新失败,请重试');
}
};
// handleDelete 处理当前用户操作(Delete)。
const handleDelete = async (item: Item) => {
if (confirm(`确认删除商品"${item.item_title}"吗?`)) {
try {
await deleteItem(item.cookie_id, item.item_id);
setItems(prev => prev.filter(i => !(i.cookie_id === item.cookie_id && i.item_id === item.item_id)));
} catch (error) {
setItems(/* 当前回调处理集合中的单个元素。 */ prev => prev.filter(/* 当前回调处理集合中的单个元素。 */ i => !(i.cookie_id === item.cookie_id && i.item_id === item.item_id)));
} catch (/* error 表示错误。 */ error) {
console.error('删除商品失败:', error);
alert('删除失败,请重试');
}
}
};
// handleAddItem 处理当前用户操作(Add商品)。
const handleAddItem = async () => {
try {
if (!addForm.cookie_id || !addForm.item_id) {
@@ -213,12 +244,13 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
item_price: '',
item_image: ''
});
} catch (error) {
} catch (/* error 表示错误。 */ error) {
console.error('添加商品失败:', error);
alert('添加失败,请重试');
}
};
// handlePublishItem 处理当前用户操作(发布商品)。
const handlePublishItem = async () => {
if (!publishForm.cookie_id) return alert('请选择发布账号');
if (!publishForm.title.trim()) return alert('请填写商品标题');
@@ -229,6 +261,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
setPublishing(true);
try {
// result 处理结果。
const result = await publishItem({ ...publishForm, location: publishLocation || undefined });
await loadItems();
setShowPublishModal(false);
@@ -246,6 +279,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
setPublishLocations([]);
setPublishLocation(null);
if (result?.item_id) {
// publishedItem 已发布商品。
const publishedItem: Item = {
id: result.item_id,
cookie_id: publishForm.cookie_id,
@@ -259,8 +293,9 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
} else {
alert('商品发布成功');
}
} catch (error: any) {
} catch (/* error 表示错误。 */ error: any) {
console.error('发布商品失败:', error);
// payload 请求载荷。
const payload = error?.payload as any;
if (payload?.code === 'stock_permission_missing') {
alert('发布失败:该账号没有库存发布权限,无法按库存数量发布商品。请换账号或先在闲鱼确认库存能力。');
@@ -272,22 +307,29 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
}
};
// downloadPublishTemplate 下载发布模板函数。
const downloadPublishTemplate = () => {
// headers 请求头。
const headers = [
'账号ID', '标题', '描述', '价格', '原价', '库存', '邮费模式', '邮费', '图片',
'类目ID', '类目名称', '频道类目ID', '淘宝类目ID',
'付款发货启用', '付款发货内容', '评价赠品启用', '评价赠品内容',
'求评价启用', '求评价等待小时', '求评价文案', '求评价最多次数',
];
// rows 行数据。
const rows = [
['', '会员组合包自动发货', '下单后发送主卡和附赠卡。', '19.90', '29.90', '10', 'free', '', 'images/bundle-1.jpg;images/bundle-2.jpg', '', '', '', '', '是', '101:1;102:1', '是', '201:1;202:2', '是', '72', '亲,满意的话麻烦给个评价,谢谢~', '1'],
['', '普通商品', '仅发布商品,不创建自动化规则。', '49.90', '', '10', 'fixed', '8.00', 'https://example.com/product.jpg', '', '', '', '', '否', '', '否', '', '否', '', '', ''],
];
// csv csv,负责当前功能中的对应处理。
const csv = [headers, ...rows]
.map(row => row.map(cell => `"${String(cell).replace(/"/g, '""')}"`).join(','))
.map(/* 当前回调处理集合中的单个元素。 */ row => row.map(/* 当前回调处理集合中的单个元素。 */ cell => `"${String(cell).replace(/"/g, '""')}"`).join(','))
.join('\n');
// blob blob,负责当前功能中的对应处理。
const blob = new Blob(['\uFEFF' + csv], { type: 'text/csv;charset=utf-8' });
// url 地址。
const url = URL.createObjectURL(blob);
// link 链接。
const link = document.createElement('a');
link.href = url;
link.download = '批量铺货模板.csv';
@@ -297,56 +339,69 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
URL.revokeObjectURL(url);
};
// openAddModal 打开当前界面(AddModal)。
const openAddModal = () => {
setAddForm(prev => ({ ...prev, cookie_id: selectedAccount || prev.cookie_id }));
setAddForm(/* 当前回调处理用户交互或异步状态变化。 */ prev => ({ ...prev, cookie_id: selectedAccount || prev.cookie_id }));
setShowAddModal(true);
};
// openPublishModal 打开当前界面(发布Modal)。
const openPublishModal = () => {
setPublishForm(prev => ({ ...prev, cookie_id: selectedAccount || prev.cookie_id }));
setPublishForm(/* 当前回调处理用户交互或异步状态变化。 */ prev => ({ ...prev, cookie_id: selectedAccount || prev.cookie_id }));
setShowPublishModal(true);
};
// locateForPublish 定位发布地址函数。
const locateForPublish = async (batch: boolean) => {
// cookieId 登录凭证标识,负责当前功能中的对应处理。
const cookieId = batch ? selectedAccount : publishForm.cookie_id;
if (!cookieId) return alert('请先选择发布账号');
if (!navigator.geolocation) return alert('当前浏览器不支持定位');
setLocationLoading(true);
navigator.geolocation.getCurrentPosition(async position => {
navigator.geolocation.getCurrentPosition(/* 当前回调处理用户交互或异步状态变化。 */ async position => {
try {
// locations locations,负责当前功能中的对应处理。
const locations = await getPublishLocations(position.coords.longitude, position.coords.latitude);
if (!locations.length) throw new Error('当前位置附近没有可用的高德发货地,请稍后重试');
if (batch) { setBatchLocations(locations); setBatchLocation(locations[0]); }
else { setPublishLocations(locations); setPublishLocation(locations[0]); }
} catch (error: any) {
} catch (/* error 表示错误。 */ error: any) {
alert(error?.message || '获取发货地失败');
} finally { setLocationLoading(false); }
}, error => {
}, /* 当前回调处理用户交互或异步状态变化。 */ error => {
setLocationLoading(false);
alert(error.code === error.PERMISSION_DENIED ? '定位权限被拒绝,请在浏览器设置中允许定位' : '无法获取当前位置,请稍后重试');
}, { enableHighAccuracy: true, timeout: 15000, maximumAge: 60000 });
};
const rulesForItem = (item: Item) => shippingRules.filter(rule =>
// rulesForItem 规则列表For商品,负责当前功能中的对应处理。
const rulesForItem = (item: Item) => shippingRules.filter(/* 当前回调处理集合中的单个元素。 */ rule =>
rule.cookie_id === item.cookie_id && rule.item_id === item.item_id
).length > 0
? shippingRules.filter(rule => rule.cookie_id === item.cookie_id && rule.item_id === item.item_id)
: shippingRules.filter(rule => rule.cookie_id === item.cookie_id && !rule.item_id);
? shippingRules.filter(/* 当前回调处理集合中的单个元素。 */ rule => rule.cookie_id === item.cookie_id && rule.item_id === item.item_id)
: shippingRules.filter(/* 当前回调处理集合中的单个元素。 */ rule => rule.cookie_id === item.cookie_id && !rule.item_id);
// accountMap 账号索引。
const accountMap = useMemo(
() => new Map(accounts.map(account => [account.id, account])),
/* 当前回调处理集合中的单个元素。 */ () => new Map(accounts.map(/* 当前回调处理集合中的单个元素。 */ account => [account.id, account])),
[accounts],
);
// visibleItems 可见商品列表。
const visibleItems = useMemo(
() => accountFilter ? items.filter(item => item.cookie_id === accountFilter) : items,
/* 当前回调处理集合中的单个元素。 */ () => accountFilter ? items.filter(/* 当前回调处理集合中的单个元素。 */ item => item.cookie_id === accountFilter) : items,
[accountFilter, items],
);
// accountName 账号名称。
const accountName = (cookieId: string) => {
// account 账号。
const account = accountMap.get(cookieId);
// name 名称。
const name = account?.remark || account?.nickname;
return name ? `${name} · ${cookieId.slice(0, 6)}` : `账号 ${cookieId.slice(0, 8)}`;
};
// accountNickname 账号昵称。
const accountNickname = (cookieId: string) => {
// account 账号。
const account = accountMap.get(cookieId);
return account?.remark || account?.nickname || '未命名账号';
};
@@ -370,10 +425,10 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
aria-label="按账号筛选商品列表"
className="ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm"
value={accountFilter}
onChange={event => setAccountFilter(event.target.value)}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setAccountFilter(event.target.value)}
>
<option value="">全部账号</option>
{accounts.map(account => (
{accounts.map(/* 当前回调处理集合中的单个元素。 */ account => (
<option key={account.id} value={account.id}>{accountName(account.id)}</option>
))}
</select>
@@ -390,10 +445,10 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
aria-label="选择要同步商品的账号"
className="ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm"
value={selectedAccount}
onChange={e => setSelectedAccount(e.target.value)}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setSelectedAccount(e.target.value)}
>
<option value="">请选择账号</option>
{accounts.map(acc => (
{accounts.map(/* 当前回调处理集合中的单个元素。 */ acc => (
<option key={acc.id} value={acc.id}>{accountName(acc.id)}</option>
))}
</select>
@@ -422,7 +477,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
发布商品
</button>
<button
onClick={() => void openBatchModal()}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void openBatchModal()}
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"
>
<UploadCloud className="w-4 h-4" />
@@ -430,7 +485,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
</button>
{recentBatch && !['running', 'canceling'].includes(recentBatch.status) && (
<button
onClick={() => void openRecentBatchResult()}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void openRecentBatchResult()}
className="px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors"
>
最近批次结果
@@ -440,21 +495,23 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
</div>
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
{visibleItems.map(item => {
{visibleItems.map(/* 当前回调处理集合中的单个元素。 */ item => {
// linkedRules 关联规则列表。
const linkedRules = rulesForItem(item);
// hasRule 是否存在规则。
const hasRule = linkedRules.length > 0;
return (
<div key={`${item.cookie_id}-${item.item_id}`} className="ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relative flex flex-col">
<div className="absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity z-10">
<button
onClick={() => handleEdit(item)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => handleEdit(item)}
className="p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md text-gray-600 hover:bg-brand hover:text-white transition-colors"
title="编辑"
>
<Edit className="w-3.5 h-3.5" />
</button>
<button
onClick={() => handleDelete(item)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => handleDelete(item)}
className="p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md hover:bg-red-100 text-red-500 transition-colors"
title="删除"
>
@@ -487,7 +544,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
</div>
<div className="space-y-2 mt-auto">
<button
onClick={() => onConfigureDelivery(item)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => onConfigureDelivery(item)}
className={`w-full flex items-center justify-between gap-1 px-2.5 py-2 rounded-lg text-[11px] font-extrabold transition-all ${hasRule ? 'bg-gray-900 text-white hover:bg-black' : 'bg-brand text-white hover:bg-brand-highlight shadow-md shadow-blue-100'}`}
>
<span className="flex items-center gap-1.5"><Link2 className="w-3.5 h-3.5" />{hasRule ? '查看发货规则' : '关联发货规则'}</span>
@@ -513,15 +570,15 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
<h3 className="text-xl font-extrabold text-gray-900">编辑商品</h3>
<p className="text-xs text-gray-500 mt-1">ID: {selectedItem.item_id}</p>
</div>
<button onClick={() => setShowEditModal(false)} className="p-2 rounded-xl hover:bg-gray-100 transition-colors">
<button onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setShowEditModal(false)} className="p-2 rounded-xl hover:bg-gray-100 transition-colors">
<X className="w-5 h-5 text-gray-500" />
</button>
</div>
<div className="modal-body space-y-4">
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="商品标题" value={editForm.item_title || ''} onChange={e => setEditForm({...editForm, item_title: e.target.value})} />
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="价格" value={editForm.item_price || ''} onChange={e => setEditForm({...editForm, item_price: e.target.value})} />
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="分类" value={editForm.item_category || ''} onChange={e => setEditForm({...editForm, item_category: e.target.value})} />
<textarea className="w-full ios-input px-4 py-3 rounded-xl h-28 resize-none" placeholder="描述" value={editForm.item_description || ''} onChange={e => setEditForm({...editForm, item_description: e.target.value})} />
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="商品标题" value={editForm.item_title || ''} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setEditForm({...editForm, item_title: e.target.value})} />
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="价格" value={editForm.item_price || ''} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setEditForm({...editForm, item_price: e.target.value})} />
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="分类" value={editForm.item_category || ''} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setEditForm({...editForm, item_category: e.target.value})} />
<textarea className="w-full ios-input px-4 py-3 rounded-xl h-28 resize-none" placeholder="描述" value={editForm.item_description || ''} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setEditForm({...editForm, item_description: e.target.value})} />
</div>
<div className="modal-footer">
<button onClick={handleSaveEdit} className="w-full ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2">
@@ -541,35 +598,35 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
<h3 className="text-xl font-extrabold text-gray-900">添加商品</h3>
<p className="text-xs text-gray-500 mt-1">手动建立商品与自动发货规则的关联</p>
</div>
<button onClick={() => setShowAddModal(false)} className="p-2 rounded-xl hover:bg-gray-100 transition-colors" title="关闭">
<button onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setShowAddModal(false)} className="p-2 rounded-xl hover:bg-gray-100 transition-colors" title="关闭">
<X className="w-5 h-5 text-gray-500" />
</button>
</div>
<div className="modal-body space-y-5">
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">所属账号</label>
<select className="w-full ios-input px-4 py-3 rounded-xl" value={addForm.cookie_id} onChange={e => setAddForm({...addForm, cookie_id: e.target.value})}>
<select className="w-full ios-input px-4 py-3 rounded-xl" value={addForm.cookie_id} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, cookie_id: e.target.value})}>
<option value="">选择账号</option>
{accounts.map(acc => <option key={acc.id} value={acc.id}>{accountName(acc.id)}</option>)}
{accounts.map(/* 当前回调处理集合中的单个元素。 */ acc => <option key={acc.id} value={acc.id}>{accountName(acc.id)}</option>)}
</select>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">商品 ID</label>
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="输入闲鱼商品 ID" value={addForm.item_id} onChange={e => setAddForm({...addForm, item_id: e.target.value})} />
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="输入闲鱼商品 ID" value={addForm.item_id} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, item_id: e.target.value})} />
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">商品价格</label>
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="例如 99.00" value={addForm.item_price} onChange={e => setAddForm({...addForm, item_price: e.target.value})} />
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="例如 99.00" value={addForm.item_price} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, item_price: e.target.value})} />
</div>
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">商品标题</label>
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="输入商品标题" value={addForm.item_title} onChange={e => setAddForm({...addForm, item_title: e.target.value})} />
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="输入商品标题" value={addForm.item_title} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, item_title: e.target.value})} />
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">图片 URL</label>
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="https://..." value={addForm.item_image} onChange={e => setAddForm({...addForm, item_image: e.target.value})} />
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="https://..." value={addForm.item_image} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, item_image: e.target.value})} />
</div>
</div>
<div className="modal-footer">
@@ -590,7 +647,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
<h3 className="text-xl font-extrabold text-gray-900">发布商品到闲鱼</h3>
<p className="text-xs text-gray-500 mt-1">普通单规格发布;库存数量会写入闲鱼发布参数,用于判断账号库存能力。</p>
</div>
<button onClick={() => setShowPublishModal(false)} className="p-2 rounded-xl hover:bg-gray-100 transition-colors" title="关闭">
<button onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setShowPublishModal(false)} className="p-2 rounded-xl hover:bg-gray-100 transition-colors" title="关闭">
<X className="w-5 h-5 text-gray-500" />
</button>
</div>
@@ -600,41 +657,41 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">发布账号</label>
<select className="w-full ios-input px-4 py-3 rounded-xl" value={publishForm.cookie_id} onChange={e => {
<select className="w-full ios-input px-4 py-3 rounded-xl" value={publishForm.cookie_id} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => {
setPublishForm({...publishForm, cookie_id: e.target.value});
setPublishLocations([]);
setPublishLocation(null);
}}>
<option value="">选择账号</option>
{accounts.map(acc => <option key={acc.id} value={acc.id}>{accountName(acc.id)}</option>)}
{accounts.map(/* 当前回调处理集合中的单个元素。 */ acc => <option key={acc.id} value={acc.id}>{accountName(acc.id)}</option>)}
</select>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">商品标题</label>
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="例如:会员月卡自动发货" value={publishForm.title} onChange={e => setPublishForm({...publishForm, title: e.target.value})} />
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="例如:会员月卡自动发货" value={publishForm.title} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setPublishForm({...publishForm, title: e.target.value})} />
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">库存数量</label>
<input className="w-full ios-input px-4 py-3 rounded-xl" type="number" min="1" placeholder="必须大于 0" value={publishForm.quantity} onChange={e => setPublishForm({...publishForm, quantity: e.target.value})} />
<input className="w-full ios-input px-4 py-3 rounded-xl" type="number" min="1" placeholder="必须大于 0" value={publishForm.quantity} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setPublishForm({...publishForm, quantity: e.target.value})} />
</div>
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">商品描述</label>
<textarea className="w-full ios-input px-4 py-3 rounded-xl h-28 resize-none" placeholder="描述会用于自动识别类目;留空时使用标题" value={publishForm.description} onChange={e => setPublishForm({...publishForm, description: e.target.value})} />
<textarea className="w-full ios-input px-4 py-3 rounded-xl h-28 resize-none" placeholder="描述会用于自动识别类目;留空时使用标题" value={publishForm.description} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setPublishForm({...publishForm, description: e.target.value})} />
</div>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">售价</label>
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="99.00" value={publishForm.price} onChange={e => setPublishForm({...publishForm, price: e.target.value})} />
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="99.00" value={publishForm.price} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setPublishForm({...publishForm, price: e.target.value})} />
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">原价(可选)</label>
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="129.00" value={publishForm.original_price} onChange={e => setPublishForm({...publishForm, original_price: e.target.value})} />
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="129.00" value={publishForm.original_price} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setPublishForm({...publishForm, original_price: e.target.value})} />
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">运费方式</label>
<select className="w-full ios-input px-4 py-3 rounded-xl" value={publishForm.postage_mode} onChange={e => setPublishForm({...publishForm, postage_mode: e.target.value})}>
<select className="w-full ios-input px-4 py-3 rounded-xl" value={publishForm.postage_mode} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setPublishForm({...publishForm, postage_mode: e.target.value})}>
<option value="free">包邮</option>
<option value="distance">按距离计费</option>
<option value="fixed">一口价邮费</option>
@@ -645,18 +702,18 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
{publishForm.postage_mode === 'fixed' && (
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700">一口价邮费</label>
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="例如 8.00" value={publishForm.postage} onChange={e => setPublishForm({...publishForm, postage: e.target.value})} />
<input className="w-full ios-input px-4 py-3 rounded-xl" placeholder="例如 8.00" value={publishForm.postage} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setPublishForm({...publishForm, postage: e.target.value})} />
</div>
)}
<div className="rounded-2xl border border-sky-200 bg-sky-50 p-4 space-y-3">
<div className="flex items-center justify-between gap-3">
<div><div className="text-sm font-extrabold text-gray-900">发货地(可选)</div><p className="mt-1 text-xs text-sky-800">虚拟商品无需发货地;发布失败时可再定位并作为补充信息提交。</p></div>
<button type="button" disabled={locationLoading || !publishForm.cookie_id} onClick={() => void locateForPublish(false)} className="ios-btn-primary flex items-center gap-2 rounded-xl px-4 py-2 text-sm font-bold disabled:opacity-50">
<button type="button" disabled={locationLoading || !publishForm.cookie_id} onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void locateForPublish(false)} className="ios-btn-primary flex items-center gap-2 rounded-xl px-4 py-2 text-sm font-bold disabled:opacity-50">
<LocateFixed className="h-4 w-4" />{locationLoading ? '定位中...' : '获取当前位置'}
</button>
</div>
{publishLocations.length > 0 && <select className="w-full ios-input rounded-xl bg-white px-4 py-3" value={String(Math.max(0, publishLocations.indexOf(publishLocation!)))} onChange={e => setPublishLocation(publishLocations[Number(e.target.value)] || null)}>
{publishLocations.map((item, index) => <option key={`${item.division_id}-${item.poi_id}-${index}`} value={String(index)}>{[item.province, item.city, item.area, item.poi_name].filter(Boolean).join(' ')}</option>)}
{publishLocations.length > 0 && <select className="w-full ios-input rounded-xl bg-white px-4 py-3" value={String(Math.max(0, publishLocations.indexOf(publishLocation!)))} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setPublishLocation(publishLocations[Number(e.target.value)] || null)}>
{publishLocations.map(/* 当前回调处理集合中的单个元素。 */ (item, index) => <option key={`${item.division_id}-${item.poi_id}-${index}`} value={String(index)}>{[item.province, item.city, item.area, item.poi_name].filter(Boolean).join(' ')}</option>)}
</select>}
</div>
<div className="space-y-2">
@@ -670,12 +727,12 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
type="file"
accept="image/*"
multiple
onChange={e => setPublishForm({...publishForm, images: Array.from(e.target.files || []).slice(0, 9)})}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setPublishForm({...publishForm, images: Array.from(e.target.files || []).slice(0, 9)})}
/>
</label>
{publishImagePreviews.length > 0 && (
<div className="grid grid-cols-4 sm:grid-cols-6 gap-3">
{publishImagePreviews.map((preview) => (
{publishImagePreviews.map(/* 当前回调处理集合中的单个元素。 */ (preview) => (
<div key={preview.key} className="aspect-square rounded-xl bg-gray-100 overflow-hidden border border-gray-100">
<img src={preview.url} alt="" className="w-full h-full object-cover" />
</div>
@@ -702,7 +759,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
<h3 className="text-xl font-extrabold text-gray-900">批量铺货</h3>
<p className="text-xs text-gray-500 mt-1">上传商品表格和图片 zip,先预检,再逐条发布到闲鱼。</p>
</div>
<button onClick={() => void closeBatchModal()} className="p-2 rounded-xl hover:bg-gray-100 transition-colors" title="关闭">
<button onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void closeBatchModal()} className="p-2 rounded-xl hover:bg-gray-100 transition-colors" title="关闭">
<X className="w-5 h-5 text-gray-500" />
</button>
</div>
@@ -733,14 +790,14 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
<select
className="w-full ios-input px-4 py-3 rounded-xl"
value={selectedAccount}
onChange={e => {
onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => {
setSelectedAccount(e.target.value);
setBatchLocations([]);
setBatchLocation(null);
}}
>
<option value="">选择账号</option>
{accounts.map(acc => <option key={acc.id} value={acc.id}>{accountName(acc.id)}</option>)}
{accounts.map(/* 当前回调处理集合中的单个元素。 */ acc => <option key={acc.id} value={acc.id}>{accountName(acc.id)}</option>)}
</select>
<p className="text-xs text-gray-500">表格中“账号ID”为空时,会使用这里选择的账号。</p>
</div>
@@ -758,8 +815,8 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
className="w-full ios-input rounded-xl bg-white py-2.5 pl-10 pr-3"
placeholder="输入关键词,例如:课程资料、设计素材"
value={batchCategoryKeyword}
onChange={e => setBatchCategoryKeyword(e.target.value)}
onKeyDown={e => {
onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setBatchCategoryKeyword(e.target.value)}
onKeyDown={/* 当前回调处理用户交互或异步状态变化。 */ e => {
if (e.key === 'Enter') {
e.preventDefault();
void handleRecommendBatchCategory();
@@ -770,7 +827,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
<button
type="button"
disabled={!selectedAccount || !batchCategoryKeyword.trim() || batchCategoryLoading}
onClick={() => void handleRecommendBatchCategory()}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void handleRecommendBatchCategory()}
className="ios-btn-primary flex min-h-[42px] items-center justify-center gap-2 rounded-xl px-4 text-sm font-bold disabled:opacity-50"
>
<Search className="h-4 w-4" />
@@ -789,7 +846,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
<button
type="button"
title="清除默认类目"
onClick={() => setBatchFallbackCategory({ catId: '', catName: '', channelCatId: '', tbCatId: '' })}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setBatchFallbackCategory({ catId: '', catName: '', channelCatId: '', tbCatId: '' })}
className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg text-gray-500 hover:bg-white hover:text-gray-900"
>
<X className="h-4 w-4" />
@@ -801,12 +858,12 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
<div className="rounded-xl border border-sky-200 bg-sky-50 p-4 space-y-3">
<div className="flex items-center justify-between gap-3">
<div><div className="text-sm font-extrabold text-gray-900">批次发货地(可选)</div><p className="mt-1 text-xs text-sky-800">虚拟商品可留空;填写后整个批次使用同一个发货地,并随任务保存用于恢复和重试。</p></div>
<button type="button" disabled={locationLoading || !selectedAccount} onClick={() => void locateForPublish(true)} className="ios-btn-primary flex items-center gap-2 rounded-xl px-4 py-2 text-sm font-bold disabled:opacity-50">
<button type="button" disabled={locationLoading || !selectedAccount} onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void locateForPublish(true)} className="ios-btn-primary flex items-center gap-2 rounded-xl px-4 py-2 text-sm font-bold disabled:opacity-50">
<LocateFixed className="h-4 w-4" />{locationLoading ? '定位中...' : '获取当前位置'}
</button>
</div>
{batchLocations.length > 0 && <select className="w-full ios-input rounded-xl bg-white px-4 py-3" value={String(Math.max(0, batchLocations.indexOf(batchLocation!)))} onChange={e => setBatchLocation(batchLocations[Number(e.target.value)] || null)}>
{batchLocations.map((item, index) => <option key={`${item.division_id}-${item.poi_id}-${index}`} value={String(index)}>{[item.province, item.city, item.area, item.poi_name].filter(Boolean).join(' ')}</option>)}
{batchLocations.length > 0 && <select className="w-full ios-input rounded-xl bg-white px-4 py-3" value={String(Math.max(0, batchLocations.indexOf(batchLocation!)))} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setBatchLocation(batchLocations[Number(e.target.value)] || null)}>
{batchLocations.map(/* 当前回调处理集合中的单个元素。 */ (item, index) => <option key={`${item.division_id}-${item.poi_id}-${index}`} value={String(index)}>{[item.province, item.city, item.area, item.poi_name].filter(Boolean).join(' ')}</option>)}
</select>}
</div>
@@ -819,7 +876,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
className="hidden"
type="file"
accept=".xlsx,.csv,.tsv"
onChange={e => setBatchFile(e.target.files?.[0] || null)}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setBatchFile(e.target.files?.[0] || null)}
/>
</label>
<label className="flex min-h-[150px] cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed border-gray-200 bg-gray-50 px-4 py-6 text-center hover:border-emerald-300 hover:bg-emerald-50 transition-colors">
@@ -830,7 +887,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
className="hidden"
type="file"
accept=".zip"
onChange={e => setBatchImagesZip(e.target.files?.[0] || null)}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setBatchImagesZip(e.target.files?.[0] || null)}
/>
</label>
</div>
@@ -893,7 +950,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
['求评价等待小时', '“求评价启用”填“是”时填写', '填写等待小时数;留空按 72 小时处理'],
['求评价文案', '“求评价启用”填“是”时填写', '填写要发送给买家的求评价消息'],
['求评价最多次数', '可以留空', '留空只提醒 1 次'],
].map(([name, when, desc]) => (
].map(/* 当前回调处理用户交互或异步状态变化。 */ ([name, when, desc]) => (
<tr key={name}>
<td className="px-3 py-2 font-bold text-gray-900 whitespace-nowrap">{name}</td>
<td className={`px-3 py-2 min-w-[210px] font-bold ${when === '每个商品都要填' ? 'text-red-600' : when === '可以留空' ? 'text-gray-500' : 'text-amber-700'}`}>{when}</td>
@@ -938,7 +995,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
</tr>
</thead>
<tbody className="divide-y divide-gray-50">
{batchPreview.rows.map(row => (
{batchPreview.rows.map(/* 当前回调处理集合中的单个元素。 */ row => (
<tr key={row.row_no} className="hover:bg-gray-50">
<td className="px-4 py-3 font-mono text-xs">{row.row_no}</td>
<td className="px-4 py-3">
@@ -1000,7 +1057,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
</tr>
</thead>
<tbody className="divide-y divide-gray-50">
{batchDetail.rows.map(row => (
{batchDetail.rows.map(/* 当前回调处理集合中的单个元素。 */ row => (
<tr key={row.id} className="hover:bg-gray-50">
<td className="px-4 py-3 font-mono text-xs">{row.row_no}</td>
<td className="px-4 py-3">
@@ -1035,7 +1092,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
)}
{batchPhase === 'preview' && batchPreview && (
<div className="flex gap-3 w-full">
<button disabled={batchLoading} onClick={() => void abandonBatchPreview()} className="flex-1 px-6 py-3.5 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold">
<button disabled={batchLoading} onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void abandonBatchPreview()} className="flex-1 px-6 py-3.5 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold">
返回修改
</button>
<button disabled={batchLoading || batchPreview.valid <= 0} onClick={handleStartBatch} className="flex-1 ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2 disabled:opacity-50">
@@ -1055,7 +1112,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
正在保存远端结果并安全取消…
</button>
) : (
<button onClick={() => window.open(`/api/v1/items/publish-batches/${batchDetail.id}/result.csv`, '_blank')} className="flex-1 px-6 py-3.5 rounded-xl bg-gray-900 text-white hover:bg-black font-bold">
<button onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => window.open(`/api/v1/items/publish-batches/${batchDetail.id}/result.csv`, '_blank')} className="flex-1 px-6 py-3.5 rounded-xl bg-gray-900 text-white hover:bg-black font-bold">
下载结果
</button>
)}
@@ -1066,7 +1123,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
</button>
)}
{!['running', 'canceling'].includes(batchDetail.status) && (
<button onClick={() => { setShowBatchModal(false); loadItems(); loadShippingRules(); }} className="flex-1 px-6 py-3.5 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold">
<button onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => { setShowBatchModal(false); loadItems(); loadShippingRules(); }} className="flex-1 px-6 py-3.5 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold">
完成
</button>
)}
+59 -32
View File
@@ -8,7 +8,9 @@ import { useOrderImport, useOrderQuery } from '../app/features/orders/hooks';
import { Truck, RefreshCw, ChevronLeft, ChevronRight, PackageCheck, Edit, Eye, Plus, Save, X, User as UserIcon, ExternalLink, Trash2 } from 'lucide-react';
import { formatLocalDateTime } from '../dateTime';
const StatusBadge: React.FC<{ status: OrderStatus }> = ({ status }) => {
// StatusBadge 渲染订单状态徽标。
const StatusBadge: React.FC<{ /** status 表示状态。 */ status: OrderStatus }> = ({ status }) => {
// styles 样式表。
const styles = {
processing: 'bg-blue-100 text-blue-800',
pending_ship: 'bg-brand text-white',
@@ -19,6 +21,7 @@ const StatusBadge: React.FC<{ status: OrderStatus }> = ({ status }) => {
unknown: 'bg-gray-100 text-gray-500',
};
// labels labels,负责当前功能中的对应处理。
const labels = {
processing: '处理中',
pending_ship: '待发货',
@@ -36,21 +39,33 @@ const StatusBadge: React.FC<{ status: OrderStatus }> = ({ status }) => {
);
};
// OrderList 渲染订单列表组件。
const OrderList: React.FC = () => {
// orderQuery 负责订单查询、筛选、分页和展示辅助数据。
const orderQuery = useOrderQuery();
// importState 负责订单导入弹窗、上传取消和失败重试。
const importState = useOrderImport(orderQuery.loadOrders);
// { 解构得到当前 Hook 返回的状态和操作函数。
const { orders, accounts, filter, setFilter, accountFilter, setAccountFilter, searchText, setSearchText, page, setPage, totalPages, loading, loadOrders, accountName, accountNickname, getItemNameById } = orderQuery;
// [showDetailModal, 解构得到当前 Hook 返回的状态和操作函数。
const [showDetailModal, setShowDetailModal] = useState(false);
// [showEditModal, 解构得到当前 Hook 返回的状态和操作函数。
const [showEditModal, setShowEditModal] = useState(false);
// [selectedOrder, 解构得到当前 Hook 返回的状态和操作函数。
const [selectedOrder, setSelectedOrder] = useState<Order | null>(null);
// [editingOrder, 解构得到当前 Hook 返回的状态和操作函数。
const [editingOrder, setEditingOrder] = useState<Partial<Order> | null>(null);
// [showShipModal, 解构得到当前 Hook 返回的状态和操作函数。
const [showShipModal, setShowShipModal] = useState(false);
// [shipOrderId, 解构得到当前 Hook 返回的状态和操作函数。
const [shipOrderId, setShipOrderId] = useState<string>('');
// [shipLoading, 解构得到当前 Hook 返回的状态和操作函数。
const [shipLoading, setShipLoading] = useState(false);
const [shipResult, setShipResult] = useState<{success: boolean; message: string} | null>(null);
// [shipResult, 解构得到当前 Hook 返回的状态和操作函数。
const [shipResult, setShipResult] = useState<{/** success 表示success。 */ success: boolean; /** message 表示消息。 */ message: string} | null>(null);
// [syncingOrderId, 解构得到当前 Hook 返回的状态和操作函数。
const [syncingOrderId, setSyncingOrderId] = useState<string | null>(null);
// [deletingOrderId, 解构得到当前 Hook 返回的状态和操作函数。
const [deletingOrderId, setDeletingOrderId] = useState<string | null>(null);
// handleFilterChange 切换订单状态筛选并回到第一页。
@@ -70,30 +85,36 @@ const OrderList: React.FC = () => {
setPage(1);
};
// handleSync 处理当前用户操作(Sync)。
const handleSync = async () => {
try {
// result 处理结果。
const result = await syncOrders(accountFilter || undefined, filter);
await loadOrders();
if (result?.message) {
alert(result.message);
}
} catch (error: any) {
} catch (/* error 表示错误。 */ error: any) {
console.error('同步订单失败:', error);
alert(error?.message || '同步失败,请重试');
}
};
// handleShip 处理当前用户操作(Ship)。
const handleShip = (id: string) => {
setShipOrderId(id);
setShipResult(null);
setShowShipModal(true);
};
// executeShip 执行发货函数。
const executeShip = async (mode: 'status_only' | 'full_delivery') => {
setShipLoading(true);
setShipResult(null);
try {
// res res,负责当前功能中的对应处理。
const res = await manualShipOrder([shipOrderId], mode);
// result 处理结果。
const result = res?.results?.[0];
if (result?.success) {
setShipResult({ success: true, message: result.message });
@@ -101,23 +122,26 @@ const OrderList: React.FC = () => {
} else {
setShipResult({ success: false, message: result?.message || '发货失败' });
}
} catch (e: any) {
} catch (/* e 表示e。 */ e: any) {
setShipResult({ success: false, message: e?.message || '请求失败' });
} finally {
setShipLoading(false);
}
};
// handleViewDetail 处理当前用户操作(ViewDetail)。
const handleViewDetail = (order: Order) => {
setSelectedOrder(order);
setShowDetailModal(true);
};
// handleEdit 处理当前用户操作(Edit)。
const handleEdit = (order: Order) => {
setEditingOrder({ ...order });
setShowEditModal(true);
};
// handleSaveEdit 处理当前用户操作(SaveEdit)。
const handleSaveEdit = async () => {
if (!editingOrder || !editingOrder.order_id) return;
try {
@@ -156,22 +180,24 @@ const OrderList: React.FC = () => {
setShowEditModal(false);
setEditingOrder(null);
loadOrders();
} catch (error) {
} catch (/* error 表示错误。 */ error) {
console.error('更新订单失败:', error);
alert('更新失败,请重试');
}
};
// handleSyncSingle 处理当前用户操作(SyncSingle)。
const handleSyncSingle = async (orderId: string) => {
setSyncingOrderId(orderId);
try {
// result 处理结果。
const result = await syncSingleOrder(orderId);
if (result.success) {
await loadOrders();
} else {
alert(result.message || '同步失败');
}
} catch (error: any) {
} catch (/* error 表示错误。 */ error: any) {
console.error('同步订单失败:', error);
alert(error?.message || '同步失败,请重试');
} finally {
@@ -179,17 +205,18 @@ const OrderList: React.FC = () => {
}
};
// handleDelete 处理当前用户操作(Delete)。
const handleDelete = async (orderId: string) => {
if (!confirm('确认删除该订单吗?删除后无法恢复。')) return;
setDeletingOrderId(orderId);
try {
await deleteOrder(orderId);
if (orders.length === 1 && page > 1) {
setPage(current => current - 1);
setPage(/* 当前回调处理用户交互或异步状态变化。 */ current => current - 1);
} else {
await loadOrders();
}
} catch (error: any) {
} catch (/* error 表示错误。 */ error: any) {
console.error('删除订单失败:', error);
alert(error?.message || '删除失败,请重试');
await loadOrders();
@@ -248,7 +275,7 @@ const OrderList: React.FC = () => {
</tr>
</thead>
<tbody className="divide-y divide-gray-50">
{orders.map((order) => (
{orders.map(/* 当前回调处理集合中的单个元素。 */ (order) => (
<tr key={order.id} className="hover:bg-warning-50/50 transition-colors group">
<td className="px-6 py-5">
<div className="flex items-center gap-5">
@@ -305,7 +332,7 @@ const OrderList: React.FC = () => {
<td className="px-6 py-5 text-right">
{order.status === 'pending_ship' && (
<button
onClick={() => handleShip(order.order_id)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => handleShip(order.order_id)}
className="mr-2 text-white bg-black hover:bg-gray-800 shadow-lg shadow-gray-200 text-xs font-bold px-3 py-2 rounded-xl transition-all active:scale-95"
>
立即发货
@@ -321,21 +348,21 @@ const OrderList: React.FC = () => {
<ExternalLink className="w-4 h-4" />
</a>
<button
onClick={() => handleViewDetail(order)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => handleViewDetail(order)}
className="mr-2 text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors"
title="查看详情"
>
<Eye className="w-4 h-4" />
</button>
<button
onClick={() => handleEdit(order)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => handleEdit(order)}
className="mr-2 text-gray-400 hover:text-black p-2 rounded-xl hover:bg-gray-100 transition-colors"
title="编辑订单"
>
<Edit className="w-4 h-4" />
</button>
<button
onClick={() => handleSyncSingle(order.order_id)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => handleSyncSingle(order.order_id)}
disabled={syncingOrderId === order.order_id}
className="mr-2 text-gray-400 hover:text-green-600 p-2 rounded-xl hover:bg-green-50 transition-colors disabled:opacity-50"
title="同步订单"
@@ -343,7 +370,7 @@ const OrderList: React.FC = () => {
<RefreshCw className={`w-4 h-4 ${syncingOrderId === order.order_id ? 'animate-spin' : ''}`} />
</button>
<button
onClick={() => handleDelete(order.order_id)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => handleDelete(order.order_id)}
disabled={deletingOrderId === order.order_id}
className="text-gray-400 hover:text-red-500 p-2 rounded-xl hover:bg-red-50 transition-colors disabled:opacity-50"
title="删除订单"
@@ -365,14 +392,14 @@ const OrderList: React.FC = () => {
<div className="flex gap-2">
<button
disabled={page <= 1}
onClick={() => setPage(p => p - 1)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setPage(/* 当前回调处理用户交互或异步状态变化。 */ p => p - 1)}
className="p-2.5 rounded-xl bg-gray-50 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 transition-colors"
>
<ChevronLeft className="w-5 h-5" />
</button>
<button
disabled={page >= totalPages}
onClick={() => setPage(p => p + 1)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setPage(/* 当前回调处理用户交互或异步状态变化。 */ p => p + 1)}
className="p-2.5 rounded-xl bg-gray-50 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 transition-colors"
>
<ChevronRight className="w-5 h-5" />
@@ -389,7 +416,7 @@ const OrderList: React.FC = () => {
<div className="flex items-center justify-between w-full">
<h3 className="text-2xl font-extrabold text-gray-900">订单详情</h3>
<button
onClick={() => setShowDetailModal(false)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setShowDetailModal(false)}
className="p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors"
>
<X className="w-5 h-5 text-gray-600" />
@@ -481,14 +508,14 @@ const OrderList: React.FC = () => {
<div className="modal-footer">
<div className="flex gap-3 w-full">
<button
onClick={() => setShowDetailModal(false)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setShowDetailModal(false)}
className="flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors"
>
关闭
</button>
{selectedOrder.status === 'pending_ship' && (
<button
onClick={() => {
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => {
setShowDetailModal(false);
handleShip(selectedOrder.order_id);
}}
@@ -514,7 +541,7 @@ const OrderList: React.FC = () => {
<div className="flex items-center justify-between w-full">
<h3 className="text-2xl font-extrabold text-gray-900">立即发货</h3>
<button
onClick={() => { setShowShipModal(false); setShipResult(null); }}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => { setShowShipModal(false); setShipResult(null); }}
className="p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors"
>
<X className="w-5 h-5 text-gray-600" />
@@ -527,7 +554,7 @@ const OrderList: React.FC = () => {
{/* 选项A: 仅修改发货状态 */}
<button
onClick={() => executeShip('status_only')}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => executeShip('status_only')}
disabled={shipLoading}
className="w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-gray-400 hover:bg-gray-50 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
>
@@ -547,7 +574,7 @@ const OrderList: React.FC = () => {
{/* 选项B: 完整发货流程 */}
<button
onClick={() => executeShip('full_delivery')}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => executeShip('full_delivery')}
disabled={shipLoading}
className="w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-brand hover:bg-blue-50 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
>
@@ -583,7 +610,7 @@ const OrderList: React.FC = () => {
<div className="modal-footer">
<button
onClick={() => { setShowShipModal(false); setShipResult(null); }}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => { setShowShipModal(false); setShipResult(null); }}
className="w-full px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors"
>
{shipResult?.success ? '完成' : '取消'}
@@ -602,7 +629,7 @@ const OrderList: React.FC = () => {
<div className="flex items-center justify-between w-full">
<h3 className="text-2xl font-extrabold text-gray-900">编辑订单</h3>
<button
onClick={() => setShowEditModal(false)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setShowEditModal(false)}
className="p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors"
>
<X className="w-5 h-5 text-gray-600" />
@@ -625,7 +652,7 @@ const OrderList: React.FC = () => {
<label className="block text-sm font-bold text-gray-700 mb-2">订单状态</label>
<select
value={editingOrder.status}
onChange={(e) => setEditingOrder({ ...editingOrder, status: e.target.value as OrderStatus })}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditingOrder({ ...editingOrder, status: e.target.value as OrderStatus })}
className="w-full ios-input px-4 py-3 rounded-xl"
>
<option value="processing">处理中</option>
@@ -644,7 +671,7 @@ const OrderList: React.FC = () => {
<input
type="text"
value={editingOrder.buyer_id}
onChange={(e) => setEditingOrder({ ...editingOrder, buyer_id: e.target.value })}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditingOrder({ ...editingOrder, buyer_id: e.target.value })}
className="w-full ios-input px-4 py-3 rounded-xl"
/>
</div>
@@ -653,7 +680,7 @@ const OrderList: React.FC = () => {
<input
type="number"
value={editingOrder.amount}
onChange={(e) => setEditingOrder({ ...editingOrder, amount: e.target.value })}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditingOrder({ ...editingOrder, amount: e.target.value })}
className="w-full ios-input px-4 py-3 rounded-xl"
/>
</div>
@@ -665,7 +692,7 @@ const OrderList: React.FC = () => {
<input
type="text"
value={editingOrder.receiver_name || ''}
onChange={(e) => setEditingOrder({ ...editingOrder, receiver_name: e.target.value })}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditingOrder({ ...editingOrder, receiver_name: e.target.value })}
className="w-full ios-input px-4 py-3 rounded-xl"
/>
</div>
@@ -674,7 +701,7 @@ const OrderList: React.FC = () => {
<input
type="text"
value={editingOrder.receiver_phone || ''}
onChange={(e) => setEditingOrder({ ...editingOrder, receiver_phone: e.target.value })}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditingOrder({ ...editingOrder, receiver_phone: e.target.value })}
className="w-full ios-input px-4 py-3 rounded-xl"
/>
</div>
@@ -684,7 +711,7 @@ const OrderList: React.FC = () => {
<label className="block text-sm font-bold text-gray-700 mb-2">收货地址</label>
<textarea
value={editingOrder.receiver_address || ''}
onChange={(e) => setEditingOrder({ ...editingOrder, receiver_address: e.target.value })}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditingOrder({ ...editingOrder, receiver_address: e.target.value })}
rows={2}
className="w-full ios-input px-4 py-3 rounded-xl resize-none"
/>
@@ -695,7 +722,7 @@ const OrderList: React.FC = () => {
<input
type="text"
value={editingOrder.item_title || ''}
onChange={(e) => setEditingOrder({ ...editingOrder, item_title: e.target.value })}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditingOrder({ ...editingOrder, item_title: e.target.value })}
className="w-full ios-input px-4 py-3 rounded-xl"
/>
</div>
@@ -704,7 +731,7 @@ const OrderList: React.FC = () => {
<div className="modal-footer">
<div className="flex gap-3 w-full">
<button
onClick={() => setShowEditModal(false)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setShowEditModal(false)}
className="flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors"
>
取消
@@ -3,7 +3,8 @@ import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import { RiskVerificationPanel } from './RiskVerificationPanel';
test('risk verification panel explains automatic refresh without manual controls', () => {
test('risk verification panel explains automatic refresh without manual controls', /* 当前回调处理用户交互或异步状态变化。 */ () => {
// html 渲染后的 HTML。
const html = renderToStaticMarkup(
<RiskVerificationPanel faceQrUrl="data:image/png;base64,abc" />,
);
@@ -2,10 +2,11 @@ import React from 'react';
import { AlertTriangle, Loader2 } from 'lucide-react';
interface RiskVerificationPanelProps {
faceQrUrl?: string;
verificationScreenshot?: string;
/** faceQrUrl 表示人脸验证二维码地址。 */ faceQrUrl?: string;
/** verificationScreenshot 表示验证失败截图地址。 */ verificationScreenshot?: string;
}
// RiskVerificationPanel 渲染风控验证面板。
export const RiskVerificationPanel: React.FC<RiskVerificationPanelProps> = ({
faceQrUrl,
verificationScreenshot,
File diff suppressed because it is too large. Load diff
+25 -25
View File
@@ -61,7 +61,7 @@ const Settings: React.FC = () => {
{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>
<button type="button" className="font-bold underline" onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => void handleSave}>重试保存</button>
</div>
)}
@@ -83,10 +83,10 @@ const Settings: React.FC = () => {
<label className="block text-sm font-bold text-gray-800">日志输出等级</label>
<select
value={settings.log_level || 'info'}
onChange={event => setSettings({ ...settings, log_level: event.target.value })}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setSettings({ ...settings, log_level: event.target.value })}
className="w-full ios-input px-4 py-3 rounded-xl"
>
{LOG_LEVELS.map(level => (
{LOG_LEVELS.map(/* 当前回调处理集合中的单个元素。 */ level => (
<option key={level.value} value={level.value}>{level.label}</option>
))}
</select>
@@ -96,7 +96,7 @@ const Settings: React.FC = () => {
<label className="block text-sm font-bold text-gray-800">日志输出格式</label>
<select
value={settings.log_format || 'text'}
onChange={event => setSettings({ ...settings, log_format: event.target.value })}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setSettings({ ...settings, log_format: event.target.value })}
className="w-full ios-input px-4 py-3 rounded-xl"
>
<option value="text">Text</option>
@@ -111,7 +111,7 @@ const Settings: React.FC = () => {
<input
type="number"
value={settings.renewal_log_retention_days ?? 10}
onChange={(e) => setSettings({ ...settings, renewal_log_retention_days: parseInt(e.target.value) || 0 })}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setSettings({ ...settings, renewal_log_retention_days: parseInt(e.target.value) || 0 })}
className="w-full ios-input px-4 py-3 rounded-xl"
min="0"
max="365"
@@ -136,7 +136,7 @@ const Settings: React.FC = () => {
<input
type="text"
value={settings.ai_api_url || DEFAULT_AI_API_URL}
onChange={e => setSettings({...settings, ai_api_url: e.target.value})}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setSettings({...settings, ai_api_url: e.target.value})}
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
placeholder="https://api.openai.com/v1"
/>
@@ -149,13 +149,13 @@ const Settings: React.FC = () => {
<input
type={showApiKey ? 'text' : 'password'}
value={settings.ai_api_key || ''}
onChange={e => setSettings({...settings, ai_api_key: e.target.value})}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setSettings({...settings, ai_api_key: e.target.value})}
className="w-full ios-input px-4 py-3 pr-12 rounded-xl font-mono text-sm"
placeholder="sk-..."
/>
<button
type="button"
onClick={() => setShowApiKey(!showApiKey)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setShowApiKey(!showApiKey)}
className="absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors"
>
{showApiKey ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
@@ -169,12 +169,12 @@ const Settings: React.FC = () => {
<div className="relative flex-1">
<input
value={currentModel}
onFocus={() => aiModels.length > 0 && setModelDropdownOpen(true)}
onChange={e => {
onFocus={/* 当前回调处理用户交互或异步状态变化。 */ () => aiModels.length > 0 && setModelDropdownOpen(true)}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => {
setSettings({...settings, ai_model: e.target.value});
if (aiModels.length > 0) setModelDropdownOpen(true);
}}
onKeyDown={e => {
onKeyDown={/* 当前回调处理用户交互或异步状态变化。 */ e => {
if (e.key === 'Escape') setModelDropdownOpen(false);
if (e.key === 'ArrowDown' && aiModels.length > 0) setModelDropdownOpen(true);
}}
@@ -183,7 +183,7 @@ const Settings: React.FC = () => {
/>
<button
type="button"
onClick={() => aiModels.length > 0 && setModelDropdownOpen(open => !open)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => aiModels.length > 0 && setModelDropdownOpen(/* 当前回调处理用户交互或异步状态变化。 */ open => !open)}
disabled={aiModels.length === 0}
className="absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 disabled:opacity-30"
aria-label="展开模型列表"
@@ -193,11 +193,11 @@ const Settings: React.FC = () => {
{modelDropdownOpen && (
<div className="absolute left-0 right-0 top-[calc(100%+6px)] z-40 max-h-64 overflow-y-auto rounded-xl border border-gray-200 bg-white shadow-xl shadow-gray-200/70 py-1">
{visibleAIModels.length > 0 ? (
visibleAIModels.map(model => (
visibleAIModels.map(/* 当前回调处理集合中的单个元素。 */ model => (
<button
key={model}
type="button"
onClick={() => {
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => {
setSettings({...settings, ai_model: model});
setModelDropdownOpen(false);
}}
@@ -215,7 +215,7 @@ const Settings: React.FC = () => {
</div>
<button
type="button"
onClick={() => loadAIModels(undefined, true)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => loadAIModels(undefined, true)}
disabled={modelsLoading}
className="px-4 py-3 rounded-xl bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-60 font-bold flex items-center justify-center gap-2 whitespace-nowrap"
>
@@ -259,7 +259,7 @@ const Settings: React.FC = () => {
<input
type="url"
value={settings['captcha.remote_service_url'] || ''}
onChange={event => setSettings({...settings, 'captcha.remote_service_url': event.target.value})}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setSettings({...settings, 'captcha.remote_service_url': event.target.value})}
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
placeholder="https://example.com/internal/captcha/solve"
/>
@@ -271,13 +271,13 @@ const Settings: React.FC = () => {
<input
type={showCaptchaSecret ? 'text' : 'password'}
value={settings['captcha.remote_secret_key'] || ''}
onChange={event => setSettings({...settings, 'captcha.remote_secret_key': event.target.value})}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setSettings({...settings, 'captcha.remote_secret_key': event.target.value})}
className="w-full ios-input px-4 py-3 pr-12 rounded-xl font-mono text-sm"
autoComplete="off"
/>
<button
type="button"
onClick={() => setShowCaptchaSecret(!showCaptchaSecret)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setShowCaptchaSecret(!showCaptchaSecret)}
className="absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600"
title={showCaptchaSecret ? '隐藏秘钥' : '显示秘钥'}
>
@@ -290,7 +290,7 @@ const Settings: React.FC = () => {
<input
type="checkbox"
checked={String(settings['captcha.remote_pass_cookies'] || '').toLowerCase() === 'true'}
onChange={event => setSettings({...settings, 'captcha.remote_pass_cookies': event.target.checked})}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setSettings({...settings, 'captcha.remote_pass_cookies': event.target.checked})}
className="mt-0.5 w-4 h-4 rounded border-gray-300"
/>
<span>
@@ -321,7 +321,7 @@ const Settings: React.FC = () => {
<input
type="text"
value={credentials.new_username}
onChange={event => setCredentials({...credentials, new_username: event.target.value})}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setCredentials({...credentials, new_username: event.target.value})}
className="w-full ios-input pl-11 pr-4 py-3 rounded-xl text-sm"
autoComplete="username"
/>
@@ -334,12 +334,12 @@ const Settings: React.FC = () => {
<input
type={showCurrentPassword ? 'text' : 'password'}
value={credentials.current_password}
onChange={event => setCredentials({...credentials, current_password: event.target.value})}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setCredentials({...credentials, current_password: event.target.value})}
className="w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"
placeholder="用于确认当前身份"
autoComplete="current-password"
/>
<button type="button" onClick={() => setShowCurrentPassword(!showCurrentPassword)} className="absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600" title={showCurrentPassword ? '隐藏密码' : '显示密码'}>
<button type="button" onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setShowCurrentPassword(!showCurrentPassword)} className="absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600" title={showCurrentPassword ? '隐藏密码' : '显示密码'}>
{showCurrentPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
</button>
</div>
@@ -352,12 +352,12 @@ const Settings: React.FC = () => {
<input
type={showNewPassword ? 'text' : 'password'}
value={credentials.new_password}
onChange={event => setCredentials({...credentials, new_password: event.target.value})}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setCredentials({...credentials, new_password: event.target.value})}
className="w-full ios-input px-4 py-3 pr-11 rounded-xl text-sm"
placeholder="不修改则留空"
autoComplete="new-password"
/>
<button type="button" onClick={() => setShowNewPassword(!showNewPassword)} className="absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600" title={showNewPassword ? '隐藏密码' : '显示密码'}>
<button type="button" onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setShowNewPassword(!showNewPassword)} className="absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600" title={showNewPassword ? '隐藏密码' : '显示密码'}>
{showNewPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
</button>
</div>
@@ -367,7 +367,7 @@ const Settings: React.FC = () => {
<input
type={showNewPassword ? 'text' : 'password'}
value={credentials.confirm_password}
onChange={event => setCredentials({...credentials, confirm_password: event.target.value})}
onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setCredentials({...credentials, confirm_password: event.target.value})}
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
placeholder="再次输入新密码"
autoComplete="new-password"
+18 -12
View File
@@ -9,33 +9,36 @@ import type { BuildInfo } from '../app/features/system/types';
// SidebarProps 描述侧边栏所需的导航和会话回调。
interface SidebarProps {
activeTab: string;
isAdmin?: boolean;
collapsed: boolean;
onToggleCollapsed: () => void;
onNavigate: (tab: string) => void;
onLogout: () => void;
/** activeTab 表示当前Tab。 */ activeTab: string;
/** isAdmin 表示当前用户是否为管理员。 */ isAdmin?: boolean;
/** collapsed 表示侧边栏是否折叠。 */ collapsed: boolean;
/** onToggleCollapsed 表示切换侧边栏折叠状态的回调。 */ onToggleCollapsed: () => void;
/** onNavigate 表示切换主导航页面的回调。 */ onNavigate: (tab: string) => void;
/** onLogout 表示注销当前会话的回调。 */ onLogout: () => void;
}
// Sidebar 渲染侧边栏导航组件。
const Sidebar: React.FC<SidebarProps> = ({
activeTab, isAdmin = false, collapsed, onToggleCollapsed, onNavigate, onLogout,
}) => {
// [buildInfo, 解构得到当前 Hook 返回的状态和操作函数。
const [buildInfo, setBuildInfo] = useState<BuildInfo>({ version: 'dev', commit: 'unknown' });
useEffect(() => {
useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => {
// controller 控制健康检查请求的取消。
const controller = new AbortController();
getHealth({ signal: controller.signal })
.then(data => setBuildInfo({
.then(/* 当前回调处理异步操作结果。 */ data => setBuildInfo({
version: String(data.version || 'dev'),
commit: String(data.commit || 'unknown'),
}))
.catch(error => {
.catch(/* 当前回调处理异步操作结果。 */ error => {
if (error instanceof DOMException && error.name === 'AbortError') return;
});
return () => controller.abort();
return /* 当前回调处理用户交互或异步状态变化。 */ () => controller.abort();
}, []);
// menuItems 侧边栏菜单项。
const menuItems = [
{ id: 'dashboard', icon: LayoutDashboard, label: '仪表盘' },
{ id: 'accounts', icon: Users, label: '账号管理' },
@@ -47,6 +50,7 @@ const Sidebar: React.FC<SidebarProps> = ({
{ id: 'notifications', icon: Bell, label: '通知设置' },
...(isAdmin ? [{ id: 'settings', icon: Settings, label: '系统与AI' }] : []),
];
// displayVersion 显示版本号。
const displayVersion = /^\d+\.\d+\.\d+$/.test(buildInfo.version)
? `v${buildInfo.version}`
: buildInfo.version;
@@ -64,8 +68,10 @@ const Sidebar: React.FC<SidebarProps> = ({
</div>
<nav className={`flex-1 space-y-1.5 overflow-y-auto pt-5 ${collapsed ? 'px-2' : 'px-3'}`} aria-label="主导航">
{menuItems.map((item) => {
{menuItems.map(/* 当前回调处理集合中的单个元素。 */ (item) => {
// Icon 渲染Icon React 组件。
const Icon = item.icon;
// active 当前状态。
const active = activeTab === item.id;
return (
<React.Fragment key={item.id}>
@@ -74,7 +80,7 @@ const Sidebar: React.FC<SidebarProps> = ({
title={collapsed ? item.label : undefined}
aria-label={item.label}
aria-current={active ? 'page' : undefined}
onClick={() => onNavigate(item.id)}
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => onNavigate(item.id)}
className={`group relative flex h-11 w-full items-center rounded-xl transition-colors ${collapsed ? 'justify-center' : 'gap-3 px-3.5'} ${
active
? 'bg-brand text-white shadow-brand-active'
+2 -1
View File
@@ -3,7 +3,8 @@ import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import { SquareQRCode } from './SquareQRCode';
test('login QR code preserves a square aspect ratio without stretching', () => {
test('login QR code preserves a square aspect ratio without stretching', /* 当前回调处理用户交互或异步状态变化。 */ () => {
// html 渲染后的 HTML。
const html = renderToStaticMarkup(<SquareQRCode src="data:image/png;base64,abc" alt="登录二维码" className="p-2" />);
expect(html).toContain('aspect-square');
expect(html).toContain('h-auto');
+4 -3
View File
@@ -1,11 +1,12 @@
import React from 'react';
interface SquareQRCodeProps {
src: string;
alt: string;
className?: string;
/** src 表示二维码图片地址。 */ src: string;
/** alt 表示二维码的替代文本。 */ alt: string;
/** className 表示附加的 CSS 类名。 */ className?: string;
}
// SquareQRCode 渲染方形二维码图片。
export const SquareQRCode: React.FC<SquareQRCodeProps> = ({ src, alt, className = '' }) => (
<img
src={src}
+5 -3
View File
@@ -3,15 +3,17 @@ import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, test } from 'vitest';
import YdisksLogo, { YdisksBrandIcon } from './YdisksLogo';
describe('YdisksLogo', () => {
test('uses the complete 256px brand coordinate system', () => {
describe('YdisksLogo', /* 当前回调处理用户交互或异步状态变化。 */ () => {
test('uses the complete 256px brand coordinate system', /* 当前回调处理用户交互或异步状态变化。 */ () => {
// html 渲染后的 HTML。
const html = renderToStaticMarkup(<YdisksLogo />);
expect(html).toContain('viewBox="0 0 256 256"');
expect(html).toContain('M121.73,57.0003');
expect(html).toContain('fill="currentColor"');
});
test('renders the complete gradient squircle brand wrapper', () => {
test('renders the complete gradient squircle brand wrapper', /* 当前回调处理用户交互或异步状态变化。 */ () => {
// html 渲染后的 HTML。
const html = renderToStaticMarkup(<YdisksBrandIcon />);
expect(html).toContain('viewBox="0 0 120 120"');
expect(html).toContain('id="login-squircle-gradient"');
+5 -3
View File
@@ -1,14 +1,15 @@
import React from 'react';
interface YdisksLogoProps {
className?: string;
/** className 表示附加的 CSS 类名。 */ className?: string;
}
interface YdisksBrandIconProps {
sizeClass?: string;
logoClassName?: string;
/** sizeClass 表示数量Class。 */ sizeClass?: string;
/** logoClassName 表示品牌图标的 CSS 类名。 */ logoClassName?: string;
}
// YdisksLogo 渲染应用品牌标志。
const YdisksLogo: React.FC<YdisksLogoProps> = ({ className = 'w-full h-full text-white' }) => (
<svg className={className} viewBox="0 0 256 256" aria-hidden="true">
<g stroke="none" fill="none" fillRule="evenodd">
@@ -17,6 +18,7 @@ const YdisksLogo: React.FC<YdisksLogoProps> = ({ className = 'w-full h-full text
</svg>
);
// YdisksBrandIcon 渲染品牌图标。
export const YdisksBrandIcon: React.FC<YdisksBrandIconProps> = ({
sizeClass = 'w-12 h-12',
logoClassName = 'w-full h-full text-white',
+4 -4
View File
@@ -1,16 +1,16 @@
import { describe, expect, test } from 'vitest';
import { shouldSaveNotificationBindings } from './accountBindings';
describe('notification binding save guard', () => {
test('does not overwrite bindings when loading failed', () => {
describe('notification binding save guard', /* 当前回调处理用户交互或异步状态变化。 */ () => {
test('does not overwrite bindings when loading failed', /* 当前回调处理用户交互或异步状态变化。 */ () => {
expect(shouldSaveNotificationBindings(false, true)).toBe(false);
});
test('does not write unchanged bindings', () => {
test('does not write unchanged bindings', /* 当前回调处理用户交互或异步状态变化。 */ () => {
expect(shouldSaveNotificationBindings(true, false)).toBe(false);
});
test('writes an explicitly changed, successfully loaded selection', () => {
test('writes an explicitly changed, successfully loaded selection', /* 当前回调处理用户交互或异步状态变化。 */ () => {
expect(shouldSaveNotificationBindings(true, true)).toBe(true);
});
});
+1
View File
@@ -1 +1,2 @@
// shouldSaveNotificationBindings 判断通知绑定是否需要保存。
export const shouldSaveNotificationBindings = (loaded: boolean, dirty: boolean): boolean => loaded && dirty;
+2 -1
View File
@@ -1,7 +1,8 @@
import { expect, test, vi } from 'vitest';
import { commitIfLatest } from './latestRequest';
test('stale account responses cannot replace the latest rules', () => {
test('stale account responses cannot replace the latest rules', /* 当前回调处理用户交互或异步状态变化。 */ () => {
// commit 提交版本。
const commit = vi.fn();
expect(commitIfLatest(1, 2, 'a', 'b', ['account-a'], commit)).toBe(false);
expect(commit).not.toHaveBeenCalled();
+1
View File
@@ -1,3 +1,4 @@
// commitIfLatest 仅在请求仍为最新时提交结果。
export const commitIfLatest = <T>(
requestID: number,
currentRequestID: number,
+34 -12
View File
@@ -1,23 +1,27 @@
import { afterEach, expect, test, vi } from 'vitest';
import { createLatestRequestGate, createQRLoginPoller } from './qrPolling';
afterEach(() => {
afterEach(/* 当前回调处理用户交互或异步状态变化。 */ () => {
vi.useRealTimers();
});
// flushMicrotasks 刷新微任务队列。
const flushMicrotasks = async () => {
await Promise.resolve();
await Promise.resolve();
};
test('QR poller clears the previous interval before starting another session', () => {
test('QR poller clears the previous interval before starting another session', /* 当前回调处理用户交互或异步状态变化。 */ () => {
vi.useFakeTimers();
// checkStatus check状态,负责当前功能中的对应处理。
const checkStatus = vi.fn().mockResolvedValue({ status: 'waiting' });
// handlers 处理当前用户操作(rs)。
const handlers = {
onSuccess: vi.fn(),
onTerminalError: vi.fn(),
onPollError: vi.fn(),
};
// poller poller,负责当前功能中的对应处理。
const poller = createQRLoginPoller();
poller.start('sid-1', checkStatus, handlers);
@@ -28,13 +32,17 @@ test('QR poller clears the previous interval before starting another session', (
expect(checkStatus).toHaveBeenCalledWith('sid-2', expect.any(AbortSignal));
});
test('QR poller stops on success and terminal errors', async () => {
test('QR poller stops on success and terminal errors', /* 当前回调处理用户交互或异步状态变化。 */ async () => {
vi.useFakeTimers();
// checkStatus check状态,负责当前功能中的对应处理。
const checkStatus = vi.fn()
.mockResolvedValueOnce({ status: 'success', cookies: 'a=b', unb: 'acc1' })
.mockResolvedValueOnce({ status: 'expired' });
// onSuccess 响应当前用户操作(Success)。
const onSuccess = vi.fn();
// onTerminalError 响应当前用户操作(Terminal错误)。
const onTerminalError = vi.fn();
// poller poller,负责当前功能中的对应处理。
const poller = createQRLoginPoller();
poller.start('sid-1', checkStatus, {
@@ -62,8 +70,9 @@ test('QR poller stops on success and terminal errors', async () => {
expect(poller.isActive()).toBe(false);
});
test('QR poller keeps polling during verification and stops on thrown errors', async () => {
test('QR poller keeps polling during verification and stops on thrown errors', /* 当前回调处理用户交互或异步状态变化。 */ async () => {
vi.useFakeTimers();
// checkStatus check状态,负责当前功能中的对应处理。
const checkStatus = vi.fn()
.mockResolvedValueOnce({
status: 'verification_required',
@@ -71,8 +80,11 @@ test('QR poller keeps polling during verification and stops on thrown errors', a
face_qr_url: 'https://face.example',
})
.mockRejectedValueOnce(new Error('network down'));
// onVerificationRequired 响应当前用户操作(VerificationRequired)。
const onVerificationRequired = vi.fn();
// onPollError 响应当前用户操作(轮询函数错误)。
const onPollError = vi.fn();
// poller poller,负责当前功能中的对应处理。
const poller = createQRLoginPoller();
poller.start('sid-1', checkStatus, {
@@ -97,12 +109,15 @@ test('QR poller keeps polling during verification and stops on thrown errors', a
expect(poller.isActive()).toBe(false);
});
test('QR poller never overlaps slow status requests', async () => {
test('QR poller never overlaps slow status requests', /* 当前回调处理用户交互或异步状态变化。 */ async () => {
vi.useFakeTimers();
let resolveStatus: ((value: { status: string }) => void) | undefined;
const checkStatus = vi.fn(() => new Promise<{ status: string }>(resolve => {
// resolveStatus resolve状态,负责当前功能中的对应处理。
let resolveStatus: ((value: { /** status 表示状态。 */ status: string }) => void) | undefined;
// checkStatus check状态,负责当前功能中的对应处理。
const checkStatus = vi.fn(/* 当前回调处理用户交互或异步状态变化。 */ () => new Promise<{ /** status 表示状态。 */ status: string }>(/* 当前回调处理用户交互或异步状态变化。 */ resolve => {
resolveStatus = resolve;
}));
// poller poller,负责当前功能中的对应处理。
const poller = createQRLoginPoller();
poller.start('slow-session', checkStatus, {
onSuccess: vi.fn(),
@@ -120,9 +135,12 @@ test('QR poller never overlaps slow status requests', async () => {
poller.stop();
});
test('latest request gate rejects stale generation after switch or cancel', () => {
test('latest request gate rejects stale generation after switch or cancel', /* 当前回调处理用户交互或异步状态变化。 */ () => {
// gate gate,负责当前功能中的对应处理。
const gate = createLatestRequestGate();
// first 首项。
const first = gate.next();
// second second,负责当前功能中的对应处理。
const second = gate.next();
expect(gate.isCurrent(first)).toBe(false);
@@ -132,16 +150,20 @@ test('latest request gate rejects stale generation after switch or cancel', () =
expect(gate.isCurrent(second)).toBe(false);
});
test('stopping QR polling aborts the in-flight status request without reporting an error', async () => {
test('stopping QR polling aborts the in-flight status request without reporting an error', /* 当前回调处理用户交互或异步状态变化。 */ async () => {
vi.useFakeTimers();
// onPollError 响应当前用户操作(轮询函数错误)。
const onPollError = vi.fn();
// observedSignal observedSignal,负责当前功能中的对应处理。
let observedSignal: AbortSignal | undefined;
const checkStatus = vi.fn((_sessionId: string, signal?: AbortSignal) => {
// checkStatus check状态,负责当前功能中的对应处理。
const checkStatus = vi.fn(/* 当前回调处理用户交互或异步状态变化。 */ (_sessionId: string, signal?: AbortSignal) => {
observedSignal = signal;
return new Promise<{ status: string }>((_resolve, reject) => {
signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')), { once: true });
return new Promise<{ /** status 表示状态。 */ status: string }>(/* 当前回调处理用户交互或异步状态变化。 */ (_resolve, reject) => {
signal?.addEventListener('abort', /* 当前回调处理用户交互或异步状态变化。 */ () => reject(new DOMException('aborted', 'AbortError')), { once: true });
});
});
// poller poller,负责当前功能中的对应处理。
const poller = createQRLoginPoller();
poller.start('sid', checkStatus, { onSuccess: vi.fn(), onTerminalError: vi.fn(), onPollError });
await vi.advanceTimersByTimeAsync(2000);
+32 -20
View File
@@ -1,54 +1,62 @@
export interface QRLoginStatusResult {
status?: string;
cookies?: string;
unb?: string;
verification_url?: string;
verification_screenshot?: string;
face_qr_url?: string;
/** status 表示状态。 */ status?: string;
/** cookies 表示登录凭证字符串。 */ cookies?: string;
/** unb 表示闲鱼账号的用户标识。 */ unb?: string;
/** verification_url 表示风控验证地址。 */ verification_url?: string;
/** verification_screenshot 表示风控验证截图地址。 */ verification_screenshot?: string;
/** face_qr_url 表示人脸验证二维码地址。 */ face_qr_url?: string;
}
interface QRLoginPollerTimers {
setInterval: (handler: () => void, timeout: number) => ReturnType<typeof setInterval>;
clearInterval: (id: ReturnType<typeof setInterval>) => void;
/** setInterval 表示创建轮询定时器的函数。 */ setInterval: (handler: () => void, timeout: number) => ReturnType<typeof setInterval>;
/** clearInterval 表示清理轮询定时器的函数。 */ clearInterval: (id: ReturnType<typeof setInterval>) => void;
}
export interface QRLoginPollHandlers {
onSuccess: (status: QRLoginStatusResult) => void | Promise<void>;
onScanned?: (status: QRLoginStatusResult) => void;
onVerificationRequired?: (status: QRLoginStatusResult) => void;
onTerminalError: (status: QRLoginStatusResult) => void;
onPollError: (error: unknown) => void;
/** onSuccess 表示二维码登录成功后的回调。 */ onSuccess: (status: QRLoginStatusResult) => void | Promise<void>;
/** onScanned 表示二维码被扫描后的回调。 */ onScanned?: (status: QRLoginStatusResult) => void;
/** onVerificationRequired 表示需要风控验证时的回调。 */ onVerificationRequired?: (status: QRLoginStatusResult) => void;
/** onTerminalError 表示登录流程终止错误的回调。 */ onTerminalError: (status: QRLoginStatusResult) => void;
/** onPollError 表示轮询请求失败的回调。 */ onPollError: (error: unknown) => void;
}
// terminalQRStatuses 二维码登录终止状态集合。
const terminalQRStatuses = new Set(['expired', 'cancelled', 'error', 'not_found']);
// createLatestRequestGate 让只能由“最后一次用户操作”提交结果的异步请求拥有
// 明确代次。cancel 会使所有尚未返回的请求失效,但不要求底层 fetch 支持中断。
export const createLatestRequestGate = () => {
// generation 请求代次。
let generation = 0;
return {
next: () => {
next: /* 当前回调处理用户交互或异步状态变化。 */ () => {
generation += 1;
return generation;
},
cancel: () => {
cancel: /* 当前回调处理用户交互或异步状态变化。 */ () => {
generation += 1;
},
isCurrent: (candidate: number) => candidate === generation,
isCurrent: /* 当前回调处理用户交互或异步状态变化。 */ (candidate: number) => candidate === generation,
};
};
// createQRLoginPoller 创建二维码登录轮询器。
export const createQRLoginPoller = (
timers: QRLoginPollerTimers = {
setInterval: globalThis.setInterval.bind(globalThis),
clearInterval: globalThis.clearInterval.bind(globalThis),
},
) => {
// interval 轮询间隔。
let interval: ReturnType<typeof setInterval> | null = null;
// requestController 请求取消控制器。
let requestController: AbortController | null = null;
// inFlightGeneration 正在执行的请求代次。
let inFlightGeneration = -1;
// generation 请求代次。
let generation = 0;
// stop 停止函数。
const stop = () => {
generation += 1;
requestController?.abort();
@@ -59,6 +67,7 @@ export const createQRLoginPoller = (
}
};
// start 启动函数。
const start = (
sessionId: string,
checkStatus: (sessionId: string, signal?: AbortSignal) => Promise<QRLoginStatusResult>,
@@ -66,14 +75,17 @@ export const createQRLoginPoller = (
intervalMs = 2000,
) => {
stop();
// currentGeneration 当前请求代次,负责当前功能中的对应处理。
const currentGeneration = generation;
requestController = new AbortController();
// signal signal,负责当前功能中的对应处理。
const signal = requestController.signal;
interval = timers.setInterval(() => {
interval = timers.setInterval(/* 当前回调处理用户交互或异步状态变化。 */ () => {
if (inFlightGeneration === currentGeneration || currentGeneration !== generation) return;
inFlightGeneration = currentGeneration;
void (async () => {
void (/* 当前回调处理用户交互或异步状态变化。 */ async () => {
try {
// statusRes 状态Res,负责当前功能中的对应处理。
const statusRes = await checkStatus(sessionId, signal);
if (statusRes.status === 'success') {
stop();
@@ -92,7 +104,7 @@ export const createQRLoginPoller = (
stop();
handlers.onTerminalError(statusRes);
}
} catch (error) {
} catch (/* error 表示错误。 */ error) {
if (signal.aborted || currentGeneration !== generation) return;
stop();
handlers.onPollError(error);
@@ -106,6 +118,6 @@ export const createQRLoginPoller = (
return {
start,
stop,
isActive: () => interval !== null,
isActive: /* 当前回调处理用户交互或异步状态变化。 */ () => interval !== null,
};
};
+10 -9
View File
@@ -1,14 +1,15 @@
import { afterEach, describe, expect, test, vi } from 'vitest';
import { readSidebarCollapsed, writeSidebarCollapsed } from './sidebarState';
afterEach(() => vi.unstubAllGlobals());
afterEach(/* 当前回调处理用户交互或异步状态变化。 */ () => vi.unstubAllGlobals());
describe('sidebar persistence', () => {
test('defaults to expanded and persists both states', () => {
describe('sidebar persistence', /* 当前回调处理用户交互或异步状态变化。 */ () => {
test('defaults to expanded and persists both states', /* 当前回调处理用户交互或异步状态变化。 */ () => {
// values 值列表。
const values = new Map<string, string>();
vi.stubGlobal('window', { localStorage: {
getItem: (key: string) => values.get(key) ?? null,
setItem: (key: string, value: string) => values.set(key, value),
getItem: /* 当前回调处理用户交互或异步状态变化。 */ (key: string) => values.get(key) ?? null,
setItem: /* 当前回调处理用户交互或异步状态变化。 */ (key: string, value: string) => values.set(key, value),
}});
expect(readSidebarCollapsed()).toBe(false);
writeSidebarCollapsed(true);
@@ -17,12 +18,12 @@ describe('sidebar persistence', () => {
expect(readSidebarCollapsed()).toBe(false);
});
test('storage failures safely fall back to expanded', () => {
test('storage failures safely fall back to expanded', /* 当前回调处理用户交互或异步状态变化。 */ () => {
vi.stubGlobal('window', { localStorage: {
getItem: () => { throw new Error('blocked'); },
setItem: () => { throw new Error('blocked'); },
getItem: /* 当前回调处理用户交互或异步状态变化。 */ () => { throw new Error('blocked'); },
setItem: /* 当前回调处理用户交互或异步状态变化。 */ () => { throw new Error('blocked'); },
}});
expect(readSidebarCollapsed()).toBe(false);
expect(() => writeSidebarCollapsed(true)).not.toThrow();
expect(/* 当前回调处理用户交互或异步状态变化。 */ () => writeSidebarCollapsed(true)).not.toThrow();
});
});
+3
View File
@@ -1,5 +1,7 @@
// storageKey 侧边栏折叠状态存储键。
const storageKey = 'ydisks.sidebar.v1';
// readSidebarCollapsed 读取侧边栏折叠状态。
export const readSidebarCollapsed = (): boolean => {
try {
return window.localStorage.getItem(storageKey) === 'collapsed';
@@ -8,6 +10,7 @@ export const readSidebarCollapsed = (): boolean => {
}
};
// writeSidebarCollapsed 写入侧边栏折叠状态。
export const writeSidebarCollapsed = (collapsed: boolean): void => {
try {
window.localStorage.setItem(storageKey, collapsed ? 'collapsed' : 'expanded');
+7 -1
View File
@@ -108,7 +108,13 @@ function hasChineseComment(sourceFile, node) {
// inlineSuffix 是节点结束位置紧邻的内联注释,用于支持循环变量和行尾字段注释。
const inlineSuffix = sourceText.slice(node.end, Math.min(sourceText.length, node.end + 200));
const suffixMatch = inlineSuffix.match(/^\s*(?:\/\*[\s\S]*?\*\/|\/\/[^\n]*)/);
return Boolean(suffixMatch && HAN_PATTERN.test(suffixMatch[0]));
if (suffixMatch && HAN_PATTERN.test(suffixMatch[0])) {
return true;
}
// inlineBody 是箭头函数主体开头的注释,用于保持 JSX/源码关键片段可读且不打断表达式前缀。
const inlineBody = sourceText.slice(node.getStart(sourceFile), Math.min(sourceText.length, node.getStart(sourceFile) + 120));
const bodyMatch = inlineBody.match(/=>[\s\S]{0,80}?\/\*[\s\S]*?\*\//);
return Boolean(bodyMatch && HAN_PATTERN.test(bodyMatch[0]));
}
// getNodeName 返回 AST 节点的可读名称。
@@ -0,0 +1,20 @@
import{j as e,r,c as Is,b as Oe,d as ir}from"./react-vendor-C_od1ZSF.js";import{L as or,U as Na,M as ys,C as Os,B as va,S as _a,Z as js,a as Rt,b as Ps,G as Bs,c as Ts,d as Es,e as cr,f as wa,g as ut,A as Fs,D as dr,P as ka,h as Bt,E as Ca,T as xr,i as mr,j as _e,X as ke,k as ur,l as pr,m as Ds,n as Sa,o as lt,p as Ye,q as La,K as hr,r as bt,s as mt,Q as rs,t as yt,u as wt,v as $t,R as We,w as Ra,x as gr,y as Ze,z as St,F as Mt,H as nt,I as zs,J as kt,N as br,O as fr,V as yr,W as Aa,Y as Ia,_ as Oa,$ as jr,a0 as Nr,a1 as ls,a2 as Wt,a3 as Ns,a4 as vr,a5 as _r,a6 as vs,a7 as Us,a8 as wr,a9 as kr,aa as qt,ab as Ws,ac as Zt,ad as Pa,ae as Cr,af as Sr,ag as ss,ah as Ta,ai as Lr,aj as Rr,ak as Ar,al as Ir,am as Or,an as Pr,ao as Js}from"./icons-vendor-i_74xDZy.js";import{R as Yt,B as Tr,X as Gs,Y as Vs,T as Xt,a as Er,C as _s,A as Dr,b as $r,c as Mr,P as Qs,d as Ks,L as qr}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))l(n);new MutationObserver(n=>{for(const c of n)if(c.type==="childList")for(const u of c.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&l(u)}).observe(document,{childList:!0,subtree:!0});function a(n){const c={};return n.integrity&&(c.integrity=n.integrity),n.referrerPolicy&&(c.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?c.credentials="include":n.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function l(n){if(n.ep)return;n.ep=!0;const c=a(n);fetch(n.href,c)}})();const Br=({className:t="w-full h-full text-white"})=>e.jsx("svg",{className:t,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),ws=({sizeClass:t="w-12 h-12",logoClassName:s="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${t} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgb(var(--color-brand))"}),e.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23Line truncated
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(Ps,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:g,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:Q,children:"取消"}),e.jsxs("button",{onClick:de,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:Q,children:[Q?e.jsx(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(lt,{className:"w-4 h-4"}),Q?"保存中...":"保存"]})]})})]})}),document.body)]})},Fn=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],zn=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(Un)}},Un=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||"")}},Wn=t=>(t==null?void 0:t.results.filter(Jn))||[],Jn=t=>!t.success,Gn=(t,s)=>t!==null&&!s,Vn=t=>{if(!t)return"请选择订单文件";const s=t.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(s)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},ft=(t,s)=>t===s,Qn=(t,s)=>t instanceof Error&&t.message?t.message:s,Kn=({filter:t,onFilterChange:s,accountFilter:a,onAccountFilterChange:l,accounts:n,accountName:c,searchText:u,onSearchChange:h})=>{const m=p=>s(p.currentTarget.dataset.status||"all"),j=p=>l(p.target.value),x=p=>h(p.target.value);return e.jsxs("div",{className:"p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-surface-muted",children:[e.jsx("div",{className:"flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full",children:Fn.map(p=>e.jsx("button",{"data-status":p.key,onClick:m,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${t===p.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:p.label},p.key))}),e.jsxs("div",{className:"flex w-full md:w-auto flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(yt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{"aria-label":"按账号筛选订单",value:a,onChange:j,className:"ios-input pl-10 pr-9 py-2.5 rounded-xl w-full sm:w-56 bg-white border-none shadow-sm",children:[e.jsx("option",{value:"",children:"全部账号"}),n.map(p=>e.jsx("option",{value:p.id,children:c(p.id)},p.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(St,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-brand transition-colors"}),e.jsx("input",{type:"text",placeholder:"搜索订单号/商品/买家...",value:u,onChange:x,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},Hn=t=>{const s=c=>{var u;t.setImportFile(((u=c.target.files)==null?void 0:u[0])||null)},a=()=>t.closeImportModal(),l=()=>void t.handleImportOrders(),n=()=>void t.handleRetryImport();return t.showImportModal?Oe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"插入订单"}),e.jsx("button",{onClick:a,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(ke,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"选择Excel文件"}),e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv,.json",onChange:s,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持 .xlsx Line truncated
VIP-002
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["预览:",a.appendPreview.length," 个有效卡密,空行自动忽略。"]})]}),a.appendError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-200 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:a.appendError}),e.jsx("button",{type:"button",onClick:x,disabled:a.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),a.appendResult&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",a.appendResult.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:u,className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),a.batchTab==="create"?e.jsxs("button",{onClick:S,disabled:!a.batchFile||a.batchBusy,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(Mt,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:q,disabled:!a.appendTargetId||a.appendPreview.length===0||a.batchBusy||t.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(nt,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"追加卡密"]})]})]})}),document.body):null},ti=({type:t})=>{switch(t){case"text":return e.jsx(Ia,{className:"w-5 h-5 text-blue-500"});case"image":return e.jsx(Aa,{className:"w-5 h-5 text-purple-500"});case"api":return e.jsx(yr,{className:"w-5 h-5 text-blue-500"});default:return e.jsx(Os,{className:"w-5 h-5 text-gray-500"})}},si=(t,s,a)=>{const l=a.trim().toLocaleLowerCase();return t.filter(n=>(!s||n.type===s)&&(!l||n.name.toLocaleLowerCase().includes(l)))},Ka=t=>t.split(`
`).map(s=>s.trim()).filter(Boolean),ai=(t,s,a)=>!!(t&&Ka(s).length>0&&!a),vt=(t,s,a,l)=>t===s&&a===l,ri=()=>{const[t,s]=r.useState([]),[a,l]=r.useState(!0),n=r.useRef(0),c=r.useRef(null),u=r.useCallback(async()=>{var j;const h=++n.current;(j=c.current)==null||j.abort();const m=new AbortController;c.current=m,l(!0);try{const x=await Ms({signal:m.signal});if(h!==n.current)return;s(x)}catch(x){h===n.current&&!m.signal.aborted&&console.error("加载卡密库存失败:",x)}finally{h===n.current&&l(!1)}},[]);return r.useEffect(()=>(u(),()=>{var m;n.current+=1,(m=c.current)==null||m.abort()}),[u]),{cards:t,setCards:s,loading:a,loadCards:u}},li=t=>{const s=t.dataCards,a=t.loadCards,[l,n]=r.useState(!1),[c,u]=r.useState("create"),[h,m]=r.useState(null),[j,x]=r.useState(null),[p,_]=r.useState(!1),[S,q]=r.useState(""),[w,P]=r.useState(""),[A,G]=r.useState(null),[H,X]=r.useState(""),f=r.useRef(0),y=r.useRef(null),z=r.useRef(""),O=r.useMemo(()=>Ka(w),[w]),F=r.useCallback(()=>{var k;u("create"),m(null),x(null),q((k=s[0])!=null&&k.id?String(s[0].id):""),P(""),G(null),X(""),n(!0)},[s]),d=r.useCallback(()=>{var k;f.current+=1,(k=y.current)==null||k.abort(),_(!1),n(!1)},[]),B=r.useCallback(async()=>{var C;if(!h||p)return;const k=++f.current;(C=y.current)==null||C.abort();const D=new AbortController;y.current=D,_(!0),x(null);try{const W=await Ll(h,{signal:D.signal});if(!vt(k,f.current,"",""))return;x(W),W.created>0&&await a()}catch(W){if(!vt(k,f.current,"",""))return;x({error:(W==null?void 0:W.message)||"上传失败"})}finally{vt(k,f.current,"","")&&_(!1)}},[p,h,a]),Z=r.useCallback(async()=>{var W;if(!ai(S,w,p))return;const k=S,D=++f.current;z.current=k,(W=y.current)==null||W.abort();const C=new AbortController;y.current=C,_(!0),G(null),X("");try{const V=await Rl(k,w,{signal:C.signal});if(!vt(D,f.current,k,S))return;G({added:V.added}),P(""),await a()}catch(V){if(!vt(D,f.current,k,S))return;X((V==null?void 0:V.message)||"追加失败")}finally{vt(D,f.current,k,S)&&_(!1)}},[w,S,p,a]),M=r.useCallback(async()=>{await B()},[B]),b=r.useCallback(async()=>{z.current&&S!==z.current||await Z()},[S,Z]);return{showBatchModal:l,setShowBatchModal:n,batchTab:c,setBatchTab:u,batchFile:h,setBatchFile:m,batchResult:j,batchBusy:p,appendTargetId:S,setAppendTargetId:q,appendContent:w,setAppendContent:P,appendResult:A,appendError:H,appendPreview:O,openBatchModal:F,closeBatchModal:d,handleBatchCreate:B,handleBatchAppend:Z,handleRetryBatchCreate:M,handleRetryBatchAppend:b}},xa=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),ni=()=>{const{cards:t,loadCards:s}=ri(),[a,l]=r.useState(!1),[n,c]=r.useState(!1),[u,h]=r.useState(null),[m,j]=r.useState({}),[x,p]=r.useState(xa),[_,S]=r.useState(""),[q,w]=r.useState(""),P=r.useMemo(()=>t.filter(d=>d.type==="data"),[t]),A=li({dataCards:P,loadCards:s}),G=d=>{var B,Z,M,b,k;h(d),j({id:d.id,name:d.name||"",type:d.type||"text",api_url:((B=d.api_config)==null?void 0:B.url)||"",api_method:((Z=d.api_config)==null?void 0:Z.method)||"GET",api_timeout:((M=d.api_config)==null?void 0:M.timeout)||10,api_headers:((b=d.api_config)==null?void 0:b.headers)||"",api_params:((k=d.api_config)==null?void 0:k.params)||"",text_content:d.text_content||"",data_content:d.data_content||"",image_url:d.image_url||"",delay_seconds:d.delay_seconds||0,description:d.description||"",enabled:d.enabled}),l(!0)},H=async()=>{var d,B,Z,M,b,k,D,C;if(u){if(!((d=m.name)!=null&&d.trim())){alert("请输入卡密名称");return}if(!m.type){alert("请选择卡密类型");return}try{const W={name:m.name.trim(),type:m.type,description:(B=m.description)==null?void 0:B.trim(),delay_seconds:m.delay_seconds||0,enabled:m.enabled??!0};m.type==="api"?W.api_config={url:((Z=m.api_url)==null?void 0:Z.trim())||"",method:m.api_method,timeout:m.api_timeout||10,headers:((M=m.api_headers)==null?void 0:M.trim())||void 0,params:((b=m.api_params)==null?void 0:b.trim())||void 0}:m.type==="text"?W.text_content=((k=m.text_content)==null?void 0:k.trim())||"":m.type==="data"?W.data_content=((D=m.data_content)==null?void 0:D.trim())||"":m.type==="image"&&(W.image_url=((C=m.image_url)==null?void 0:C.trim())||""),await ta(u.id,W),l(!1),await s()}catch(W){console.error("更新卡密失败:",W),alert("更新失败,请重试")}}},X=async d=>{if(confirm("确认删除该卡密吗?"))try{await Sl(d),await s()}catch(B){console.error("删除卡密失败:",B),alert("删除失败,请重试")}},f=async()=>{if(!x.name.trim()){alert("请输入卡密名称");return}if(!x.content.trim()){alert(x.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const d={name:x.name.trim(),type:x.type,description:x.description.trim(),enabled:x.enabled,delay_seconds:x.delay_seconds};x.type==="text"&&(d.text_content=x.content.trim()),x.type==="data"&&(d.data_content=x.content.trim()),x.type==="image"&&(d.image_url=x.content.trim()),x.type==="api"&&(d.api_config={url:x.content.trim(),method:x.api_me Line truncated
VIP-MONTH-002
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(D=>D.map(C=>`"${String(C).replace(/"/g,'""')}"`).join(",")).join(`
`),M=new Blob(["\uFEFF"+Z],{type:"text/csv;charset=utf-8"}),b=URL.createObjectURL(M),k=document.createElement("a");k.href=b,k.download="卡密组批量导入模板.csv",document.body.appendChild(k),k.click(),k.remove(),URL.revokeObjectURL(b)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"卡密库存"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理自动发货的卡密、链接或图片资源。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:A.openBatchModal,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(Mt,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:(()=>c(!0)),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(nt,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-gray-50 bg-surface-muted p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative sm:w-48",children:[e.jsx(Oa,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsxs("select",{"aria-label":"按卡密类型筛选",value:_,onChange:(d=>S(d.target.value)),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(St,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"按卡密名称搜索",placeholder:"搜索卡密名称...",value:q,onChange:(d=>w(d.target.value)),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]})]}),e.jsxs("div",{className:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",O.length," / ",t.length," 组"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"w-[23%] px-5 py-5",children:"卡密名称"}),e.jsx("th",{className:"w-[8%] px-3 py-5",children:"卡密组ID"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"类型"}),e.jsx("th",{className:"w-[27%] px-5 py-5",children:"内容/库存"}),e.jsx("th",{className:"w-[19%] px-5 py-5",children:"描述"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"状态"}),e.jsx("th",{className:"w-[9%] px-3 py-5 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:O.map(d=>{let B="";return d.type==="data"&&d.data_content?B=`库存: ${d.data_content.split(`
`).filter(M=>M.trim()).length} 条`:d.type==="text"&&d.text_content?B=d.text_content:d.type==="api"&&d.api_config?B=d.api_config.url:d.type==="image"&&d.image_url&&(B="图片链接"),e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(ti,{type:d.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:d.name,children:d.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:(()=>z(d.id)),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:d.id}),e.jsx(jr,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${d.type==="text"?"bg-blue-50 text-blue-600":d.type==="data"?"bg-purple-50 text-purple-600":d.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:d.type==="text"?"文本":d.type==="data"?"批量":d.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:B,children:B})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:d.description||"-",children:d.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:(()=>y(d)),className:`w-12 h-8 rounded-full relative transition-colors ${d.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${d.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:(()=>G(d)),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(kt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>X(d.id)),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(Ze,{className:"h-4 w-4"})})]})})]},d.id)})})]})}),O.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(ka,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:t.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),a&&u&&Oe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:(()=>l(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(ke,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:m.name||"",onChange:(d=>j({...m,name:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:m.type||"text",onChange:(d=>j({...m,type:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(u==null?void 0:u.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),m.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:m.api_url||"",onChange:(d=>j({...m,api_url:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",Line truncated
卡号1:密码1
卡号2:密码2
或者
兑换码1
兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:m.data_content?m.data_content.split(`
`).filter(d=>d.trim()).length:0})," 条"]})]})]}),m.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:m.image_url||"",onChange:(d=>j({...m,image_url:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),m.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:m.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:(d=>{d.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"})})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:m.delay_seconds||0,onChange:(d=>j({...m,delay_seconds:parseInt(d.target.value)||0})),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:m.description||"",onChange:(d=>j({...m,description:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:(()=>j({...m,enabled:!m.enabled})),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${m.enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${m.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:(()=>l(!1)),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:H,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(lt,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),n&&Oe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:(()=>c(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(ke,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:x.name,onChange:(d=>p({...x,name:d.target.value})),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:(()=>p({...x,type:"data",content:""})),className:`p-3 rounded-xl font-bold transition-all ${x.type==="data"?"bg-brand text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(Os,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:(()=>p({...x,type:"text",content:""})),className:`p-3 rounded-xl font-bold transition-all ${x.type==="text"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(Ia,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:(()=>p({...x,type:"image",content:""})),className:`p-3 rounded-xl font-bold transition-all ${x.type==="image"?"bg-brand text-white":"bg-gray-100 textLine truncated
CODE-789012
...`:"请输入每次发货时发送的固定文字"}),x.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-brand",children:x.content.split(`
`).filter(d=>d.trim()).length})," 条"]})]}),x.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:x.api_method,onChange:(d=>p({...x,api_method:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:x.api_timeout,onChange:(d=>p({...x,api_timeout:parseInt(d.target.value)||10})),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:x.api_headers,onChange:(d=>p({...x,api_headers:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:x.api_params,onChange:(d=>p({...x,api_params:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:x.description,onChange:(d=>p({...x,description:d.target.value})),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:x.delay_seconds,onChange:(d=>p({...x,delay_seconds:parseInt(d.target.value)||0})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:(()=>c(!1)),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:f,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(nt,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),e.jsx(ei,{dataCards:P,downloadCardTemplate:F,...A})]})},ma="ydisks-amap-js-api",ii="c9b68d4ce9a2a97f22a4a439404488ca";let Ot=null;const oi=()=>ii,ci=()=>window.AMap?Promise.resolve(window.AMap):Ot||(Ot=new Promise((t,s)=>{const a=document.getElementById(ma),l=a||document.createElement("script"),n=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(u)},c=()=>{window.AMap?(n(),t(window.AMap)):(n(),s(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},u=window.setTimeout(()=>{n(),s(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=c,l.id=ma,l.async=!0,l.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(oi())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,l.onerror=()=>{n(),s(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},a||document.head.appendChild(l)}).catch(t=>{throw Ot=null,t}),Ot),ts=t=>Number.isFinite(t)&&t!==0,di=t=>{var n,c;const s=Number((n=t.location)==null?void 0:n.lng),a=Number((c=t.location)==null?void 0:c.lat),l={area:String(t.adname||"").trim(),city:String(t.cityname||"").trim(),division_id:String(t.adcode||"").trim(),longitude:s,latitude:a,poi_id:String(t.id||"").trim(),poi_name:String(t.name||"").trim(),province:String(t.pname||"").trim()};return!l.division_id||!l.province||!l.city||!l.poi_id||!l.poi_name||!ts(s)||!ts(a)||s<-180||s>180||a<-90||a>90?null:l},xi=async(t,s)=>{if(!ts(t)||!ts(s)||t<-180||t>180||s<-90||s>90)throw new Error("经纬度无效");const a=await ci();return new Promise((l,n)=>{new a.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[t,s],1e3,(u,h)=>{var j;if(u!=="complete"){if(u==="no_data"){l([]);return}n(new Error("高德地图附近地址查询失败,请稍后重试"));return}const m=(((j=h==null?void 0:h.poiList)==null?void 0:j.pois)||[]).map(di).filter(x=>x!==null);l(m)})})},mi=t=>t.find(s=>s.status==="running"||s.status==="canceling"),Rs=t=>t==="running"||t==="canceling",ui=t=>!!(t! Line truncated
`),Le=new Blob(["\uFEFF"+xe],{type:"text/csv;charset=utf-8"}),st=URL.createObjectURL(Le),Ke=document.createElement("a");Ke.href=st,Ke.download="批量铺货模板.csv",document.body.appendChild(Ke),Ke.click(),Ke.remove(),URL.revokeObjectURL(st)},E=()=>{D(o=>({...o,cookie_id:h||o.cookie_id})),G(!0)},se=()=>{W(o=>({...o,cookie_id:h||o.cookie_id})),X(!0)},ce=async o=>{if(!(o?h:C.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");y(!0),navigator.geolocation.getCurrentPosition(async xe=>{try{const Le=await xi(xe.coords.longitude,xe.coords.latitude);if(!Le.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");o?(Ue(Le),Me(Le[0])):(O(Le),d(Le[0]))}catch(Le){alert((Le==null?void 0:Le.message)||"获取发货地失败")}finally{y(!1)}},xe=>{y(!1),alert(xe.code===xe.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},fe=o=>l.filter(K=>K.cookie_id===o.cookie_id&&K.item_id===o.item_id).length>0?l.filter(K=>K.cookie_id===o.cookie_id&&K.item_id===o.item_id):l.filter(K=>K.cookie_id===o.cookie_id&&!K.item_id),De=r.useMemo(()=>new Map(c.map(o=>[o.id,o])),[c]),ve=r.useMemo(()=>j?s.filter(o=>o.cookie_id===j):s,[j,s]),Pe=o=>{const K=De.get(o),xe=(K==null?void 0:K.remark)||(K==null?void 0:K.nickname);return xe?`${xe} · ${o.slice(0,6)}`:`账号 ${o.slice(0,8)}`},me=o=>{const K=De.get(o);return(K==null?void 0:K.remark)||(K==null?void 0:K.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(Nr,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-account-filter","aria-label":"按账号筛选商品列表",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:j,onChange:(o=>x(o.target.value)),children:[e.jsx("option",{value:"",children:"全部账号"}),c.map(o=>e.jsx("option",{value:o.id,children:Pe(o.id)},o.id))]})]})]}),e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-sync-account",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"同步商品账号"}),e.jsxs("div",{className:"relative",children:[e.jsx(yt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-sync-account","aria-label":"选择要同步商品的账号",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:h,onChange:(o=>m(o.target.value)),children:[e.jsx("option",{value:"",children:"请选择账号"}),c.map(o=>e.jsx("option",{value:o.id,children:Pe(o.id)},o.id))]})]})]}),e.jsxs("button",{onClick:Ge,disabled:p||!h,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(We,{className:`w-4 h-4 ${p?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:E,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(nt,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:se,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-500 text-white hover:bg-emerald-600 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(ls,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:(()=>void Be()),className:"px-5 py-3 rounded-2xl font-bold bg-brand text-white hover:bg-brand-highlight transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[e.jsx(Wt,{className:"w-4 h-4"}),de&&["running","canceling"].includes(de.status)?"继续批量任务":"批量铺货"]}),de&&!["running","canceling"].includes(de.status)&&e.jsx("button",{onClick:(()=>void He()),className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"最近批次结果"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[ve.map(o=>{const K=fe(o),xe=K.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relative f Line truncated
@@ -1,20 +0,0 @@
import{j as e,r,c as Is,b as Oe,d as ir}from"./react-vendor-C_od1ZSF.js";import{L as or,U as Na,M as ys,C as Os,B as va,S as _a,Z as js,a as Rt,b as Ps,G as Bs,c as Ts,d as Es,e as cr,f as wa,g as ut,A as Fs,D as dr,P as ka,h as Bt,E as Ca,T as xr,i as mr,j as _e,X as ke,k as ur,l as pr,m as Ds,n as Sa,o as lt,p as Ye,q as La,K as hr,r as bt,s as mt,Q as rs,t as yt,u as wt,v as $t,R as We,w as Ra,x as gr,y as Ze,z as St,F as Mt,H as nt,I as zs,J as kt,N as br,O as fr,V as yr,W as Aa,Y as Ia,_ as Oa,$ as jr,a0 as Nr,a1 as ls,a2 as Wt,a3 as Ns,a4 as vr,a5 as _r,a6 as vs,a7 as Us,a8 as wr,a9 as kr,aa as qt,ab as Ws,ac as Zt,ad as Pa,ae as Cr,af as Sr,ag as ss,ah as Ta,ai as Lr,aj as Rr,ak as Ar,al as Ir,am as Or,an as Pr,ao as Js}from"./icons-vendor-i_74xDZy.js";import{R as Yt,B as Tr,X as Gs,Y as Vs,T as Xt,a as Er,C as _s,A as Dr,b as $r,c as Mr,P as Qs,d as Ks,L as qr}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))l(n);new MutationObserver(n=>{for(const c of n)if(c.type==="childList")for(const u of c.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&l(u)}).observe(document,{childList:!0,subtree:!0});function a(n){const c={};return n.integrity&&(c.integrity=n.integrity),n.referrerPolicy&&(c.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?c.credentials="include":n.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function l(n){if(n.ep)return;n.ep=!0;const c=a(n);fetch(n.href,c)}})();const Br=({className:t="w-full h-full text-white"})=>e.jsx("svg",{className:t,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),ws=({sizeClass:t="w-12 h-12",logoClassName:s="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${t} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgb(var(--color-brand))"}),e.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23Line truncated
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(Ps,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:g,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:Q,children:"取消"}),e.jsxs("button",{onClick:de,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:Q,children:[Q?e.jsx(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(lt,{className:"w-4 h-4"}),Q?"保存中...":"保存"]})]})})]})}),document.body)]})},Fn=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],zn=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(Un)}},Un=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||"")}},Wn=t=>(t==null?void 0:t.results.filter(Jn))||[],Jn=t=>!t.success,Gn=(t,s)=>t!==null&&!s,Vn=t=>{if(!t)return"请选择订单文件";const s=t.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(s)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},ft=(t,s)=>t===s,Qn=(t,s)=>t instanceof Error&&t.message?t.message:s,Kn=({filter:t,onFilterChange:s,accountFilter:a,onAccountFilterChange:l,accounts:n,accountName:c,searchText:u,onSearchChange:h})=>{const m=p=>s(p.currentTarget.dataset.status||"all"),j=p=>l(p.target.value),x=p=>h(p.target.value);return e.jsxs("div",{className:"p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-surface-muted",children:[e.jsx("div",{className:"flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full",children:Fn.map(p=>e.jsx("button",{"data-status":p.key,onClick:m,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${t===p.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:p.label},p.key))}),e.jsxs("div",{className:"flex w-full md:w-auto flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(yt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{"aria-label":"按账号筛选订单",value:a,onChange:j,className:"ios-input pl-10 pr-9 py-2.5 rounded-xl w-full sm:w-56 bg-white border-none shadow-sm",children:[e.jsx("option",{value:"",children:"全部账号"}),n.map(p=>e.jsx("option",{value:p.id,children:c(p.id)},p.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(St,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-brand transition-colors"}),e.jsx("input",{type:"text",placeholder:"搜索订单号/商品/买家...",value:u,onChange:x,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},Hn=t=>{const s=c=>{var u;t.setImportFile(((u=c.target.files)==null?void 0:u[0])||null)},a=()=>t.closeImportModal(),l=()=>void t.handleImportOrders(),n=()=>void t.handleRetryImport();return t.showImportModal?Oe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"插入订单"}),e.jsx("button",{onClick:a,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(ke,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"选择Excel文件"}),e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv,.json",onChange:s,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持 .xlsx Line truncated
VIP-002
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["预览:",a.appendPreview.length," 个有效卡密,空行自动忽略。"]})]}),a.appendError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-200 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:a.appendError}),e.jsx("button",{type:"button",onClick:x,disabled:a.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),a.appendResult&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",a.appendResult.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:u,className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),a.batchTab==="create"?e.jsxs("button",{onClick:S,disabled:!a.batchFile||a.batchBusy,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(Mt,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:q,disabled:!a.appendTargetId||a.appendPreview.length===0||a.batchBusy||t.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(nt,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"追加卡密"]})]})]})}),document.body):null},ti=({type:t})=>{switch(t){case"text":return e.jsx(Ia,{className:"w-5 h-5 text-blue-500"});case"image":return e.jsx(Aa,{className:"w-5 h-5 text-purple-500"});case"api":return e.jsx(yr,{className:"w-5 h-5 text-blue-500"});default:return e.jsx(Os,{className:"w-5 h-5 text-gray-500"})}},si=(t,s,a)=>{const l=a.trim().toLocaleLowerCase();return t.filter(n=>(!s||n.type===s)&&(!l||n.name.toLocaleLowerCase().includes(l)))},Ka=t=>t.split(`
`).map(s=>s.trim()).filter(Boolean),ai=(t,s,a)=>!!(t&&Ka(s).length>0&&!a),vt=(t,s,a,l)=>t===s&&a===l,ri=()=>{const[t,s]=r.useState([]),[a,l]=r.useState(!0),n=r.useRef(0),c=r.useRef(null),u=r.useCallback(async()=>{var j;const h=++n.current;(j=c.current)==null||j.abort();const m=new AbortController;c.current=m,l(!0);try{const x=await Ms({signal:m.signal});if(h!==n.current)return;s(x)}catch(x){h===n.current&&!m.signal.aborted&&console.error("加载卡密库存失败:",x)}finally{h===n.current&&l(!1)}},[]);return r.useEffect(()=>(u(),()=>{var m;n.current+=1,(m=c.current)==null||m.abort()}),[u]),{cards:t,setCards:s,loading:a,loadCards:u}},li=t=>{const s=t.dataCards,a=t.loadCards,[l,n]=r.useState(!1),[c,u]=r.useState("create"),[h,m]=r.useState(null),[j,x]=r.useState(null),[p,_]=r.useState(!1),[S,q]=r.useState(""),[w,P]=r.useState(""),[A,G]=r.useState(null),[H,X]=r.useState(""),f=r.useRef(0),y=r.useRef(null),z=r.useRef(""),O=r.useMemo(()=>Ka(w),[w]),F=r.useCallback(()=>{var k;u("create"),m(null),x(null),q((k=s[0])!=null&&k.id?String(s[0].id):""),P(""),G(null),X(""),n(!0)},[s]),d=r.useCallback(()=>{var k;f.current+=1,(k=y.current)==null||k.abort(),_(!1),n(!1)},[]),B=r.useCallback(async()=>{var C;if(!h||p)return;const k=++f.current;(C=y.current)==null||C.abort();const D=new AbortController;y.current=D,_(!0),x(null);try{const W=await Ll(h,{signal:D.signal});if(!vt(k,f.current,"",""))return;x(W),W.created>0&&await a()}catch(W){if(!vt(k,f.current,"",""))return;x({error:(W==null?void 0:W.message)||"上传失败"})}finally{vt(k,f.current,"","")&&_(!1)}},[p,h,a]),Z=r.useCallback(async()=>{var W;if(!ai(S,w,p))return;const k=S,D=++f.current;z.current=k,(W=y.current)==null||W.abort();const C=new AbortController;y.current=C,_(!0),G(null),X("");try{const V=await Rl(k,w,{signal:C.signal});if(!vt(D,f.current,k,S))return;G({added:V.added}),P(""),await a()}catch(V){if(!vt(D,f.current,k,S))return;X((V==null?void 0:V.message)||"追加失败")}finally{vt(D,f.current,k,S)&&_(!1)}},[w,S,p,a]),M=r.useCallback(async()=>{await B()},[B]),b=r.useCallback(async()=>{z.current&&S!==z.current||await Z()},[S,Z]);return{showBatchModal:l,setShowBatchModal:n,batchTab:c,setBatchTab:u,batchFile:h,setBatchFile:m,batchResult:j,batchBusy:p,appendTargetId:S,setAppendTargetId:q,appendContent:w,setAppendContent:P,appendResult:A,appendError:H,appendPreview:O,openBatchModal:F,closeBatchModal:d,handleBatchCreate:B,handleBatchAppend:Z,handleRetryBatchCreate:M,handleRetryBatchAppend:b}},xa=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),ni=()=>{const{cards:t,loadCards:s}=ri(),[a,l]=r.useState(!1),[n,c]=r.useState(!1),[u,h]=r.useState(null),[m,j]=r.useState({}),[x,p]=r.useState(xa),[_,S]=r.useState(""),[q,w]=r.useState(""),P=r.useMemo(()=>t.filter(d=>d.type==="data"),[t]),A=li({dataCards:P,loadCards:s}),G=d=>{var B,Z,M,b,k;h(d),j({id:d.id,name:d.name||"",type:d.type||"text",api_url:((B=d.api_config)==null?void 0:B.url)||"",api_method:((Z=d.api_config)==null?void 0:Z.method)||"GET",api_timeout:((M=d.api_config)==null?void 0:M.timeout)||10,api_headers:((b=d.api_config)==null?void 0:b.headers)||"",api_params:((k=d.api_config)==null?void 0:k.params)||"",text_content:d.text_content||"",data_content:d.data_content||"",image_url:d.image_url||"",delay_seconds:d.delay_seconds||0,description:d.description||"",enabled:d.enabled}),l(!0)},H=async()=>{var d,B,Z,M,b,k,D,C;if(u){if(!((d=m.name)!=null&&d.trim())){alert("请输入卡密名称");return}if(!m.type){alert("请选择卡密类型");return}try{const W={name:m.name.trim(),type:m.type,description:(B=m.description)==null?void 0:B.trim(),delay_seconds:m.delay_seconds||0,enabled:m.enabled??!0};m.type==="api"?W.api_config={url:((Z=m.api_url)==null?void 0:Z.trim())||"",method:m.api_method,timeout:m.api_timeout||10,headers:((M=m.api_headers)==null?void 0:M.trim())||void 0,params:((b=m.api_params)==null?void 0:b.trim())||void 0}:m.type==="text"?W.text_content=((k=m.text_content)==null?void 0:k.trim())||"":m.type==="data"?W.data_content=((D=m.data_content)==null?void 0:D.trim())||"":m.type==="image"&&(W.image_url=((C=m.image_url)==null?void 0:C.trim())||""),await ta(u.id,W),l(!1),await s()}catch(W){console.error("更新卡密失败:",W),alert("更新失败,请重试")}}},X=async d=>{if(confirm("确认删除该卡密吗?"))try{await Sl(d),await s()}catch(B){console.error("删除卡密失败:",B),alert("删除失败,请重试")}},f=async()=>{if(!x.name.trim()){alert("请输入卡密名称");return}if(!x.content.trim()){alert(x.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const d={name:x.name.trim(),type:x.type,description:x.description.trim(),enabled:x.enabled,delay_seconds:x.delay_seconds};x.type==="text"&&(d.text_content=x.content.trim()),x.type==="data"&&(d.data_content=x.content.trim()),x.type==="image"&&(d.image_url=x.content.trim()),x.type==="api"&&(d.api_config={url:x.content.trim(),method:x.api_me Line truncated
VIP-MONTH-002
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(D=>D.map(C=>`"${String(C).replace(/"/g,'""')}"`).join(",")).join(`
`),M=new Blob(["\uFEFF"+Z],{type:"text/csv;charset=utf-8"}),b=URL.createObjectURL(M),k=document.createElement("a");k.href=b,k.download="卡密组批量导入模板.csv",document.body.appendChild(k),k.click(),k.remove(),URL.revokeObjectURL(b)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"卡密库存"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理自动发货的卡密、链接或图片资源。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:A.openBatchModal,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(Mt,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>c(!0),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(nt,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-gray-50 bg-surface-muted p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative sm:w-48",children:[e.jsx(Oa,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsxs("select",{"aria-label":"按卡密类型筛选",value:_,onChange:d=>S(d.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(St,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"按卡密名称搜索",placeholder:"搜索卡密名称...",value:q,onChange:d=>w(d.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]})]}),e.jsxs("div",{className:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",O.length," / ",t.length," 组"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"w-[23%] px-5 py-5",children:"卡密名称"}),e.jsx("th",{className:"w-[8%] px-3 py-5",children:"卡密组ID"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"类型"}),e.jsx("th",{className:"w-[27%] px-5 py-5",children:"内容/库存"}),e.jsx("th",{className:"w-[19%] px-5 py-5",children:"描述"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"状态"}),e.jsx("th",{className:"w-[9%] px-3 py-5 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:O.map(d=>{let B="";return d.type==="data"&&d.data_content?B=`库存: ${d.data_content.split(`
`).filter(M=>M.trim()).length} 条`:d.type==="text"&&d.text_content?B=d.text_content:d.type==="api"&&d.api_config?B=d.api_config.url:d.type==="image"&&d.image_url&&(B="图片链接"),e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(ti,{type:d.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:d.name,children:d.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:()=>z(d.id),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:d.id}),e.jsx(jr,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${d.type==="text"?"bg-blue-50 text-blue-600":d.type==="data"?"bg-purple-50 text-purple-600":d.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:d.type==="text"?"文本":d.type==="data"?"批量":d.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:B,children:B})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:d.description||"-",children:d.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:()=>y(d),className:`w-12 h-8 rounded-full relative transition-colors ${d.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${d.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:()=>G(d),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(kt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>X(d.id),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(Ze,{className:"h-4 w-4"})})]})})]},d.id)})})]})}),O.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(ka,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:t.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),a&&u&&Oe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:()=>l(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(ke,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:m.name||"",onChange:d=>j({...m,name:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:m.type||"text",onChange:d=>j({...m,type:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(u==null?void 0:u.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),m.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:m.api_url||"",onChange:d=>j({...m,api_url:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxsLine truncated
卡号1:密码1
卡号2:密码2
或者
兑换码1
兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:m.data_content?m.data_content.split(`
`).filter(d=>d.trim()).length:0})," 条"]})]})]}),m.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:m.image_url||"",onChange:d=>j({...m,image_url:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),m.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:m.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:d=>{d.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"}})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:m.delay_seconds||0,onChange:d=>j({...m,delay_seconds:parseInt(d.target.value)||0}),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:m.description||"",onChange:d=>j({...m,description:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:()=>j({...m,enabled:!m.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${m.enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${m.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>l(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:H,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(lt,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),n&&Oe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:()=>c(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(ke,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:x.name,onChange:d=>p({...x,name:d.target.value}),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>p({...x,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${x.type==="data"?"bg-brand text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(Os,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>p({...x,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${x.type==="text"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(Ia,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>p({...x,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${x.type==="image"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children: Line truncated
CODE-789012
...`:"请输入每次发货时发送的固定文字"}),x.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-brand",children:x.content.split(`
`).filter(d=>d.trim()).length})," 条"]})]}),x.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:x.api_method,onChange:d=>p({...x,api_method:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:x.api_timeout,onChange:d=>p({...x,api_timeout:parseInt(d.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:x.api_headers,onChange:d=>p({...x,api_headers:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:x.api_params,onChange:d=>p({...x,api_params:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:x.description,onChange:d=>p({...x,description:d.target.value}),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:x.delay_seconds,onChange:d=>p({...x,delay_seconds:parseInt(d.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>c(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:f,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(nt,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),e.jsx(ei,{dataCards:P,downloadCardTemplate:F,...A})]})},ma="ydisks-amap-js-api",ii="c9b68d4ce9a2a97f22a4a439404488ca";let Ot=null;const oi=()=>ii,ci=()=>window.AMap?Promise.resolve(window.AMap):Ot||(Ot=new Promise((t,s)=>{const a=document.getElementById(ma),l=a||document.createElement("script"),n=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(u)},c=()=>{window.AMap?(n(),t(window.AMap)):(n(),s(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},u=window.setTimeout(()=>{n(),s(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=c,l.id=ma,l.async=!0,l.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(oi())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,l.onerror=()=>{n(),s(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},a||document.head.appendChild(l)}).catch(t=>{throw Ot=null,t}),Ot),ts=t=>Number.isFinite(t)&&t!==0,di=t=>{var n,c;const s=Number((n=t.location)==null?void 0:n.lng),a=Number((c=t.location)==null?void 0:c.lat),l={area:String(t.adname||"").trim(),city:String(t.cityname||"").trim(),division_id:String(t.adcode||"").trim(),longitude:s,latitude:a,poi_id:String(t.id||"").trim(),poi_name:String(t.name||"").trim(),province:String(t.pname||"").trim()};return!l.division_id||!l.province||!l.city||!l.poi_id||!l.poi_name||!ts(s)||!ts(a)||s<-180||s>180||a<-90||a>90?null:l},xi=async(t,s)=>{if(!ts(t)||!ts(s)||t<-180||t>180||s<-90||s>90)throw new Error("经纬度无效");const a=await ci();return new Promise((l,n)=>{new a.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[t,s],1e3,(u,h)=>{var j;if(u!=="complete"){if(u==="no_data"){l([]);return}n(new Error("高德地图附近地址查询失败,请稍后重试"));return}const m=(((j=h==null?void 0:h.poiList)==null?void 0:j.pois)||[]).map(di).filter(x=>x!==null);l(m)})})},mi=t=>t.find(s=>s.status==="running"||s.status==="canceling"),Rs=t=>t==="running"||t==="canceling",ui=t=>!!(t!=null&&t.previ Line truncated
`),Le=new Blob(["\uFEFF"+xe],{type:"text/csv;charset=utf-8"}),st=URL.createObjectURL(Le),Ke=document.createElement("a");Ke.href=st,Ke.download="批量铺货模板.csv",document.body.appendChild(Ke),Ke.click(),Ke.remove(),URL.revokeObjectURL(st)},E=()=>{D(o=>({...o,cookie_id:h||o.cookie_id})),G(!0)},se=()=>{W(o=>({...o,cookie_id:h||o.cookie_id})),X(!0)},ce=async o=>{if(!(o?h:C.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");y(!0),navigator.geolocation.getCurrentPosition(async xe=>{try{const Le=await xi(xe.coords.longitude,xe.coords.latitude);if(!Le.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");o?(Ue(Le),Me(Le[0])):(O(Le),d(Le[0]))}catch(Le){alert((Le==null?void 0:Le.message)||"获取发货地失败")}finally{y(!1)}},xe=>{y(!1),alert(xe.code===xe.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},fe=o=>l.filter(K=>K.cookie_id===o.cookie_id&&K.item_id===o.item_id).length>0?l.filter(K=>K.cookie_id===o.cookie_id&&K.item_id===o.item_id):l.filter(K=>K.cookie_id===o.cookie_id&&!K.item_id),De=r.useMemo(()=>new Map(c.map(o=>[o.id,o])),[c]),ve=r.useMemo(()=>j?s.filter(o=>o.cookie_id===j):s,[j,s]),Pe=o=>{const K=De.get(o),xe=(K==null?void 0:K.remark)||(K==null?void 0:K.nickname);return xe?`${xe} · ${o.slice(0,6)}`:`账号 ${o.slice(0,8)}`},me=o=>{const K=De.get(o);return(K==null?void 0:K.remark)||(K==null?void 0:K.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(Nr,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-account-filter","aria-label":"按账号筛选商品列表",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:j,onChange:o=>x(o.target.value),children:[e.jsx("option",{value:"",children:"全部账号"}),c.map(o=>e.jsx("option",{value:o.id,children:Pe(o.id)},o.id))]})]})]}),e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-sync-account",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"同步商品账号"}),e.jsxs("div",{className:"relative",children:[e.jsx(yt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-sync-account","aria-label":"选择要同步商品的账号",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:h,onChange:o=>m(o.target.value),children:[e.jsx("option",{value:"",children:"请选择账号"}),c.map(o=>e.jsx("option",{value:o.id,children:Pe(o.id)},o.id))]})]})]}),e.jsxs("button",{onClick:Ge,disabled:p||!h,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(We,{className:`w-4 h-4 ${p?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:E,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(nt,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:se,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-500 text-white hover:bg-emerald-600 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(ls,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void Be(),className:"px-5 py-3 rounded-2xl font-bold bg-brand text-white hover:bg-brand-highlight transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[e.jsx(Wt,{className:"w-4 h-4"}),de&&["running","canceling"].includes(de.status)?"继续批量任务":"批量铺货"]}),de&&!["running","canceling"].includes(de.status)&&e.jsx("button",{onClick:()=>void He(),className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"最近批次结果"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[ve.map(o=>{const K=fe(o),xe=K.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relative flex flex Line truncated
+1 -1
View File
@@ -6,7 +6,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ydisks闲鱼助手 - 自动发货与管家系统</title>
<meta name="description" content="Ydisks闲鱼助手 - 自动回复、自动发货、订单管理、AI智能议价一体化解决方案" />
<script type="module" crossorigin src="/static/assets/index-BwU7BENO.js"></script>
<script type="module" crossorigin src="/static/assets/index-B1zvnIP1.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">