阶段七:完成AccountList子模块收口与页面组合边界
This commit is contained in:
1 parent
867ced6849
commit
448713735f
11 files changed
+847
-1107
No files matched your search
@@ -26,6 +26,15 @@ test('账号切换后只接受当前请求代次和账号的响应',
|
||||
expect(isCurrentAccountRequest(2, 2, 'account-1', 'account-2')).toBe(false);
|
||||
});
|
||||
|
||||
test('编辑子模块共享同一账号边界,旧绑定、AI 和密码登录响应全部失效',
|
||||
// 三类异步子模块都使用相同的代次与账号判定,防止旧弹窗响应污染新账号。
|
||||
() => {
|
||||
const currentGeneration = 4;
|
||||
const currentAccountId = 'account-4';
|
||||
expect(isCurrentAccountRequest(3, currentGeneration, 'account-3', currentAccountId)).toBe(false);
|
||||
expect(isCurrentAccountRequest(currentGeneration, currentGeneration, currentAccountId, currentAccountId)).toBe(true);
|
||||
});
|
||||
|
||||
test('暂停时长未变化时不会重复启动已结束的暂停',
|
||||
// 相同的时长只保留当前状态,不自动重新提交暂停请求。
|
||||
() => {
|
||||
|
||||
@@ -0,0 +1,347 @@
|
||||
import { useCallback, useEffect, useRef, useState, type Dispatch, type SetStateAction } from 'react';
|
||||
import type { AccountDetail, AIReplySettings, NotificationChannel } from '../../../types';
|
||||
import { cancelPasswordLogin, checkPasswordLoginStatus, getAccountAISettings, getAccountBindings, getLongLoginSettings, getNotificationChannels, passwordLogin, setLongLoginSettings, updateAccountAISettings, updateAccountPauseDuration, updateAccountSettings } from './api';
|
||||
import { buildAccountLoginInfoUpdate, isCurrentAccountRequest, passwordLoginViewFromStatus, shouldUpdateAccountPause } from './state';
|
||||
import type { AccountEditForm, LongLoginState, PasswordLoginView } from './types';
|
||||
import { shouldSaveNotificationBindings } from '../../../components/accountBindings';
|
||||
|
||||
/** AccountList 当前编辑弹窗类型。 */
|
||||
export type AccountModalType = 'edit' | 'ai-settings' | null;
|
||||
|
||||
/** AccountList 子模块 Hook 的输入。 */
|
||||
export type AccountSubmoduleOptions = {
|
||||
/** 当前编辑账号。 */
|
||||
editingAccount: AccountDetail | null;
|
||||
/** 写入当前编辑账号。 */
|
||||
setEditingAccount: Dispatch<SetStateAction<AccountDetail | null>>;
|
||||
/** 当前编辑弹窗类型。 */
|
||||
setActiveModal: Dispatch<SetStateAction<AccountModalType>>;
|
||||
/** 当前编辑表单。 */
|
||||
editForm: AccountEditForm;
|
||||
/** 更新编辑表单。 */
|
||||
setEditForm: Dispatch<SetStateAction<AccountEditForm>>;
|
||||
/** 刷新账号列表。 */
|
||||
loadAccounts: () => Promise<void>;
|
||||
};
|
||||
|
||||
/** 账号编辑、AI、通知绑定和密码登录子模块共享状态。 */
|
||||
export const useAccountSubmodules = ({ editingAccount, setEditingAccount, setActiveModal, editForm, setEditForm, loadAccounts }: AccountSubmoduleOptions) => {
|
||||
// longLogin 保存官方长登录设置状态。
|
||||
const [longLogin, setLongLogin] = useState<LongLoginState>({ loading: false, saving: false, canOpen: false, enabled: false, error: '' });
|
||||
// notifChannels 保存可供账号绑定的通知渠道。
|
||||
const [notifChannels, setNotifChannels] = useState<NotificationChannel[]>([]);
|
||||
// selectedChannelIds 保存当前选中的通知渠道。
|
||||
const [selectedChannelIds, setSelectedChannelIds] = useState<number[]>([]);
|
||||
// bindingsLoaded 表示绑定关系是否成功加载。
|
||||
const [bindingsLoaded, setBindingsLoaded] = useState(false);
|
||||
// bindingsLoading 表示通知绑定请求是否进行中。
|
||||
const [bindingsLoading, setBindingsLoading] = useState(false);
|
||||
// bindingsDirty 表示用户是否修改过通知绑定。
|
||||
const [bindingsDirty, setBindingsDirty] = useState(false);
|
||||
// bindingsLoadError 保存通知绑定加载错误。
|
||||
const [bindingsLoadError, setBindingsLoadError] = useState('');
|
||||
// aiSettings 保存账号 AI 编辑草稿。
|
||||
const [aiSettings, setAiSettings] = useState<AIReplySettings>({ ai_enabled: false, max_discount_percent: 10, max_discount_amount: 100, max_bargain_rounds: 3, custom_prompts: '' });
|
||||
// saving 表示编辑、AI 或暂停动作是否正在保存。
|
||||
const [saving, setSaving] = useState(false);
|
||||
// passwordLoginView 保存密码登录刷新授权状态。
|
||||
const [passwordLoginView, setPasswordLoginView] = useState<PasswordLoginView>({ sessionId: '', status: 'idle', message: '', qrCodeUrl: '' });
|
||||
// bindingsSequence 隔离账号切换后的绑定响应。
|
||||
const bindingsSequence = useRef(0);
|
||||
// bindingsAbort 保存通知绑定请求控制器。
|
||||
const bindingsAbort = useRef<AbortController | null>(null);
|
||||
// longLoginSequence 隔离账号切换后的长登录响应。
|
||||
const longLoginSequence = useRef(0);
|
||||
// longLoginAbort 保存长登录状态读取控制器。
|
||||
const longLoginAbort = useRef<AbortController | null>(null);
|
||||
// aiSequence 隔离账号切换后的 AI 响应。
|
||||
const aiSequence = useRef(0);
|
||||
// aiAbort 保存 AI 查询控制器。
|
||||
const aiAbort = useRef<AbortController | null>(null);
|
||||
// passwordGeneration 隔离密码登录轮询响应。
|
||||
const passwordGeneration = useRef(0);
|
||||
// passwordAccount 保存密码登录所属账号。
|
||||
const passwordAccount = useRef('');
|
||||
// passwordAbort 保存密码登录状态查询控制器。
|
||||
const passwordAbort = useRef<AbortController | null>(null);
|
||||
// passwordTimer 保存下一次密码登录轮询定时器。
|
||||
const passwordTimer = useRef<number | null>(null);
|
||||
|
||||
/** 清理密码登录轮询定时器。 */
|
||||
// clearPasswordTimerCallback 是 React 稳定的定时器清理函数。
|
||||
const clearPasswordTimer = useCallback(() => {
|
||||
if (passwordTimer.current !== null) {
|
||||
window.clearTimeout(passwordTimer.current);
|
||||
passwordTimer.current = null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
/** 加载当前账号通知渠道和绑定关系,并隔离过期响应。 */
|
||||
// loadNotificationBindingsCallback 是通知绑定加载回调。
|
||||
const loadNotificationBindings = useCallback(async (accountId: string): Promise<void> => {
|
||||
// sequence 是通知绑定请求的递增代次。
|
||||
const sequence = ++bindingsSequence.current;
|
||||
bindingsAbort.current?.abort();
|
||||
// controller 控制当前通知绑定请求的取消。
|
||||
const controller = new AbortController();
|
||||
bindingsAbort.current = controller;
|
||||
setBindingsLoading(true);
|
||||
setBindingsLoaded(false);
|
||||
setBindingsDirty(false);
|
||||
setBindingsLoadError('');
|
||||
// bindingResults 保存通知渠道和账号绑定的并行结果。
|
||||
const [channelsResult, bindingsResult] = await Promise.allSettled([
|
||||
getNotificationChannels({ signal: controller.signal }),
|
||||
getAccountBindings(accountId, { signal: controller.signal }),
|
||||
]);
|
||||
if (!isCurrentAccountRequest(sequence, bindingsSequence.current, accountId, accountId)) return;
|
||||
if (channelsResult.status === 'fulfilled') setNotifChannels(channelsResult.value.data || []);
|
||||
else { setNotifChannels([]); setBindingsLoadError('通知渠道列表加载失败,请重试'); }
|
||||
if (bindingsResult.status === 'fulfilled') { setSelectedChannelIds(bindingsResult.value || []); setBindingsLoaded(true); }
|
||||
else { setSelectedChannelIds([]); setBindingsLoadError('通知绑定加载失败;本次保存不会修改现有绑定'); }
|
||||
setBindingsLoading(false);
|
||||
}, []);
|
||||
|
||||
/** 切换一个通知渠道绑定。 */
|
||||
// toggleNotificationChannelCallback 是通知渠道切换回调。
|
||||
const toggleNotificationChannel = useCallback((channelId: number) => {
|
||||
setSelectedChannelIds(current => current.includes(channelId) ? current.filter(id => id !== channelId) : [...current, channelId]);
|
||||
setBindingsDirty(true);
|
||||
}, []);
|
||||
|
||||
/** 打开账号编辑弹窗并并行读取绑定和长登录状态。 */
|
||||
// openEditModalCallback 是账号编辑弹窗打开回调。
|
||||
const openEditModal = useCallback(async (account: AccountDetail): Promise<void> => {
|
||||
// longLoginRequest 是当前长登录读取请求代次。
|
||||
const longLoginRequest = ++longLoginSequence.current;
|
||||
longLoginAbort.current?.abort();
|
||||
// longLoginController 控制当前长登录读取请求的取消。
|
||||
const longLoginController = new AbortController();
|
||||
longLoginAbort.current = longLoginController;
|
||||
passwordGeneration.current += 1;
|
||||
passwordAccount.current = account.id;
|
||||
passwordAbort.current?.abort();
|
||||
clearPasswordTimer();
|
||||
setPasswordLoginView({ sessionId: '', status: 'idle', message: '', qrCodeUrl: '' });
|
||||
setEditingAccount(account);
|
||||
setEditForm({ remark: account.remark || account.note || '', cookie: account.cookie || account.value || '', auto_confirm: account.auto_confirm || false, pause_duration: account.pause_duration || 0, username: account.username || '', login_password: account.login_password || '', show_browser: account.show_browser || false, showLoginPassword: false, clear_password: false });
|
||||
setActiveModal('edit');
|
||||
setLongLogin({ loading: true, saving: false, canOpen: false, enabled: false, error: '' });
|
||||
// longLoginResult 保存长登录设置读取结果。
|
||||
const [, longLoginResult] = await Promise.allSettled([loadNotificationBindings(account.id), getLongLoginSettings(account.id, { signal: longLoginController.signal })]);
|
||||
if (longLoginRequest !== longLoginSequence.current) return;
|
||||
if (longLoginResult.status === 'fulfilled') setLongLogin({ loading: false, saving: false, canOpen: longLoginResult.value.can_open_long_login, enabled: longLoginResult.value.enabled, error: '' });
|
||||
else setLongLogin({ loading: false, saving: false, canOpen: false, enabled: false, error: '无法读取闲鱼保存登录信息状态' });
|
||||
}, [clearPasswordTimer, loadNotificationBindings, setActiveModal, setEditForm, setEditingAccount]);
|
||||
|
||||
/** 切换官方长登录设置。 */
|
||||
// handleLongLoginToggleCallback 是长登录设置切换回调。
|
||||
const handleLongLoginToggle = useCallback(async (): Promise<void> => {
|
||||
if (!editingAccount || longLogin.loading || longLogin.saving || !longLogin.canOpen) return;
|
||||
// enabled 是本次准备提交的长登录开关值。
|
||||
const enabled = !longLogin.enabled;
|
||||
setLongLogin(current => ({ ...current, saving: true, error: '' }));
|
||||
try {
|
||||
// result 保存长登录设置接口返回值。
|
||||
const result = await setLongLoginSettings(editingAccount.id, enabled);
|
||||
setLongLogin({ loading: false, saving: false, canOpen: result.can_open_long_login, enabled: result.enabled, error: '' });
|
||||
} catch (error) {
|
||||
// error 保存长登录设置保存失败原因。
|
||||
setLongLogin(current => ({ ...current, saving: false, error: error instanceof Error ? error.message : '保存登录信息设置失败' }));
|
||||
}
|
||||
}, [editingAccount, longLogin]);
|
||||
|
||||
/** 打开 AI 设置并隔离过期账号响应。 */
|
||||
// openAIModalCallback 是 AI 设置弹窗打开回调。
|
||||
const openAIModal = useCallback(async (account: AccountDetail): Promise<void> => {
|
||||
// sequence 是 AI 设置请求的递增代次。
|
||||
const sequence = ++aiSequence.current;
|
||||
aiAbort.current?.abort();
|
||||
// controller 控制当前 AI 设置请求的取消。
|
||||
const controller = new AbortController();
|
||||
aiAbort.current = controller;
|
||||
setEditingAccount(account);
|
||||
setActiveModal('ai-settings');
|
||||
setSaving(true);
|
||||
try {
|
||||
// settings 保存当前账号的 AI 设置。
|
||||
const settings = await getAccountAISettings(account.id, { signal: controller.signal });
|
||||
if (!isCurrentAccountRequest(sequence, aiSequence.current, account.id, account.id)) return;
|
||||
setAiSettings({ ai_enabled: settings.ai_enabled ?? false, max_discount_percent: settings.max_discount_percent ?? 10, max_discount_amount: settings.max_discount_amount ?? 100, max_bargain_rounds: settings.max_bargain_rounds ?? 3, custom_prompts: settings.custom_prompts ?? '' });
|
||||
} catch (error) {
|
||||
// error 保存 AI 设置读取失败原因。
|
||||
if (isCurrentAccountRequest(sequence, aiSequence.current, account.id, account.id)) console.error('加载 AI 设置失败:', error);
|
||||
} finally {
|
||||
if (isCurrentAccountRequest(sequence, aiSequence.current, account.id, account.id)) setSaving(false);
|
||||
}
|
||||
}, [setActiveModal, setEditingAccount]);
|
||||
|
||||
/** 保存 AI 设置并刷新账号列表。 */
|
||||
// handleSaveAISettingsCallback 是 AI 设置保存回调。
|
||||
const handleSaveAISettings = useCallback(async (): Promise<void> => {
|
||||
if (!editingAccount || saving) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
await updateAccountAISettings(editingAccount.id, aiSettings);
|
||||
setActiveModal(null);
|
||||
await loadAccounts();
|
||||
} catch (error) {
|
||||
// error 保存 AI 设置保存失败原因。
|
||||
console.error('更新 AI 设置失败:', error);
|
||||
} finally { setSaving(false); }
|
||||
}, [aiSettings, editingAccount, loadAccounts, saving, setActiveModal]);
|
||||
|
||||
/** 保存账号编辑表单和通知绑定。 */
|
||||
// handleSaveEditCallback 是账号编辑表单保存回调。
|
||||
const handleSaveEdit = useCallback(async (): Promise<void> => {
|
||||
if (!editingAccount || saving) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
// payload 保存需要提交的账号编辑补丁。
|
||||
const payload: Parameters<typeof updateAccountSettings>[1] = {};
|
||||
if (editForm.remark !== (editingAccount.remark || editingAccount.note || '')) payload.remark = editForm.remark;
|
||||
if (editForm.cookie && editForm.cookie !== (editingAccount.cookie || editingAccount.value || '')) payload.cookie = editForm.cookie;
|
||||
if (editForm.auto_confirm !== editingAccount.auto_confirm) payload.auto_confirm = editForm.auto_confirm;
|
||||
if (shouldUpdateAccountPause(editForm.pause_duration, editingAccount)) payload.pause_duration = editForm.pause_duration;
|
||||
// loginInfo 保存登录字段变更补丁。
|
||||
const loginInfo = buildAccountLoginInfoUpdate(editingAccount, editForm);
|
||||
if (loginInfo) Object.assign(payload, loginInfo);
|
||||
if (shouldSaveNotificationBindings(bindingsLoaded, bindingsDirty)) payload.channel_ids = selectedChannelIds;
|
||||
if (Object.keys(payload).length > 0) await updateAccountSettings(editingAccount.id, payload);
|
||||
setActiveModal(null);
|
||||
await loadAccounts();
|
||||
} catch (error) {
|
||||
// error 保存账号编辑保存失败原因。
|
||||
console.error('更新账号失败:', error);
|
||||
} finally { setSaving(false); }
|
||||
}, [bindingsDirty, bindingsLoaded, editForm, editingAccount, loadAccounts, selectedChannelIds, saving, setActiveModal]);
|
||||
|
||||
/** 按当前暂停时长重新暂停账号。 */
|
||||
// handleRestartPauseCallback 是重新暂停账号回调。
|
||||
const handleRestartPause = useCallback(async (): Promise<void> => {
|
||||
if (!editingAccount || editForm.pause_duration <= 0 || saving) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
// result 保存重新暂停接口返回的账号状态。
|
||||
const result = await updateAccountPauseDuration(editingAccount.id, editForm.pause_duration);
|
||||
setEditingAccount(current => current ? { ...current, pause_duration: editForm.pause_duration, paused: result?.paused === true, paused_until: Number(result?.paused_until || 0) } : current);
|
||||
await loadAccounts();
|
||||
} catch (error) { console.error('重新暂停失败:', error); }
|
||||
finally { setSaving(false); }
|
||||
}, [editForm.pause_duration, editingAccount, loadAccounts, saving, setEditingAccount]);
|
||||
|
||||
/** 按账号和请求代次轮询密码登录状态。 */
|
||||
// pollPasswordLoginCallback 是密码登录状态轮询回调。
|
||||
const pollPasswordLogin = useCallback(async (sessionId: string, generation: number, accountId: string): Promise<void> => {
|
||||
passwordAbort.current?.abort();
|
||||
// controller 控制当前密码登录状态查询的取消。
|
||||
const controller = new AbortController();
|
||||
passwordAbort.current = controller;
|
||||
try {
|
||||
// result 保存后端返回的密码登录状态。
|
||||
const result = await checkPasswordLoginStatus(sessionId, controller.signal);
|
||||
if (!isCurrentAccountRequest(generation, passwordGeneration.current, accountId, passwordAccount.current)) return;
|
||||
// nextView 是面向编辑弹窗展示的状态。
|
||||
const nextView = { ...passwordLoginViewFromStatus(result), sessionId };
|
||||
if (result.status === 'success') {
|
||||
clearPasswordTimer();
|
||||
setPasswordLoginView(nextView);
|
||||
setEditForm(current => ({ ...current, login_password: '', showLoginPassword: false }));
|
||||
await loadAccounts();
|
||||
return;
|
||||
}
|
||||
if (result.status === 'processing' || result.status === 'verification_required') {
|
||||
setPasswordLoginView(nextView);
|
||||
clearPasswordTimer();
|
||||
passwordTimer.current = window.setTimeout(() => void pollPasswordLogin(sessionId, generation, accountId), 1500);
|
||||
return;
|
||||
}
|
||||
clearPasswordTimer();
|
||||
setPasswordLoginView(nextView);
|
||||
} catch (error) {
|
||||
// error 保存密码登录状态查询失败原因。
|
||||
if (!isCurrentAccountRequest(generation, passwordGeneration.current, accountId, passwordAccount.current)) return;
|
||||
clearPasswordTimer();
|
||||
setPasswordLoginView({ sessionId, status: 'failed', message: error instanceof Error ? error.message : '查询密码登录状态失败', qrCodeUrl: '' });
|
||||
}
|
||||
}, [clearPasswordTimer, loadAccounts, setEditForm]);
|
||||
|
||||
/** 启动账号密码登录刷新授权。 */
|
||||
// handlePasswordLoginCallback 是密码登录启动回调。
|
||||
const handlePasswordLogin = useCallback(async (): Promise<void> => {
|
||||
if (!editingAccount) return;
|
||||
// accountName 是本次登录使用的闲鱼账号名。
|
||||
const accountName = editForm.username.trim();
|
||||
if (!accountName || !editForm.login_password) return;
|
||||
clearPasswordTimer();
|
||||
passwordAbort.current?.abort();
|
||||
// generation 是本次密码登录请求的递增代次。
|
||||
const generation = ++passwordGeneration.current;
|
||||
passwordAccount.current = editingAccount.id;
|
||||
// startController 控制密码登录启动请求的取消。
|
||||
const startController = new AbortController();
|
||||
passwordAbort.current = startController;
|
||||
setPasswordLoginView({ sessionId: '', status: 'processing', message: '正在启动密码登录…', qrCodeUrl: '' });
|
||||
try {
|
||||
// result 保存密码登录启动接口返回值。
|
||||
const result = await passwordLogin({ account_id: editingAccount.id, account: accountName, password: editForm.login_password, show_browser: editForm.show_browser }, { signal: startController.signal });
|
||||
if (!isCurrentAccountRequest(generation, passwordGeneration.current, editingAccount.id, passwordAccount.current)) return;
|
||||
if (!result.success || !result.session_id) throw new Error(result.message || '无法启动密码登录');
|
||||
setPasswordLoginView({ sessionId: result.session_id, status: 'processing', message: result.message || '登录处理中', qrCodeUrl: '' });
|
||||
await pollPasswordLogin(result.session_id, generation, editingAccount.id);
|
||||
} catch (error) {
|
||||
// error 保存密码登录启动失败原因。
|
||||
if (!isCurrentAccountRequest(generation, passwordGeneration.current, editingAccount.id, passwordAccount.current)) return;
|
||||
setPasswordLoginView({ sessionId: '', status: 'failed', message: error instanceof Error ? error.message : '启动密码登录失败', qrCodeUrl: '' });
|
||||
}
|
||||
}, [clearPasswordTimer, editForm.login_password, editForm.show_browser, editForm.username, editingAccount, pollPasswordLogin]);
|
||||
|
||||
/** 取消当前密码登录会话。 */
|
||||
// handleCancelPasswordLoginCallback 是密码登录取消回调。
|
||||
const handleCancelPasswordLogin = useCallback(async (): Promise<void> => {
|
||||
// sessionId 是当前待取消的密码登录会话。
|
||||
const sessionId = passwordLoginView.sessionId;
|
||||
passwordGeneration.current += 1;
|
||||
passwordAccount.current = '';
|
||||
passwordAbort.current?.abort();
|
||||
clearPasswordTimer();
|
||||
if (sessionId) await cancelPasswordLogin(sessionId).catch(() => undefined);
|
||||
setPasswordLoginView({ sessionId: '', status: 'idle', message: '', qrCodeUrl: '' });
|
||||
}, [clearPasswordTimer, passwordLoginView.sessionId]);
|
||||
|
||||
/** 关闭编辑弹窗并取消未完成的子模块请求。 */
|
||||
// closeEditModalCallback 是编辑弹窗关闭回调。
|
||||
const closeEditModal = useCallback(async (): Promise<void> => {
|
||||
bindingsAbort.current?.abort();
|
||||
longLoginSequence.current += 1;
|
||||
longLoginAbort.current?.abort();
|
||||
aiAbort.current?.abort();
|
||||
if (passwordLoginView.status === 'processing' || passwordLoginView.status === 'verification_required') await handleCancelPasswordLogin();
|
||||
setActiveModal(null);
|
||||
}, [handleCancelPasswordLogin, passwordLoginView.status, setActiveModal]);
|
||||
|
||||
/** 关闭 AI 设置弹窗并取消读取请求。 */
|
||||
// closeAIModalCallback 是 AI 设置弹窗关闭回调。
|
||||
const closeAIModal = useCallback(() => {
|
||||
aiSequence.current += 1;
|
||||
aiAbort.current?.abort();
|
||||
setActiveModal(null);
|
||||
}, [setActiveModal]);
|
||||
|
||||
// cleanupSubmodulesEffect 在 Hook 卸载时取消所有子模块请求。
|
||||
useEffect(() => () => {
|
||||
bindingsAbort.current?.abort();
|
||||
longLoginAbort.current?.abort();
|
||||
aiAbort.current?.abort();
|
||||
passwordAbort.current?.abort();
|
||||
clearPasswordTimer();
|
||||
}, [clearPasswordTimer]);
|
||||
|
||||
return {
|
||||
longLogin, notifChannels, selectedChannelIds, bindingsLoaded, bindingsLoading, bindingsDirty, bindingsLoadError,
|
||||
aiSettings, saving, passwordLoginView, setAiSettings, setBindingsDirty, setEditForm, openEditModal,
|
||||
closeEditModal, openAIModal, closeAIModal, loadNotificationBindings, toggleNotificationChannel,
|
||||
handleLongLoginToggle, handleSaveAISettings, handleSaveEdit, handleRestartPause, handlePasswordLogin,
|
||||
handleCancelPasswordLogin,
|
||||
};
|
||||
};
|
||||
@@ -1,71 +1,65 @@
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { AccountDetail, AIReplySettings, NotificationChannel } from '../types';
|
||||
import { AccountDetail } from '../types';
|
||||
import {
|
||||
updateAccountStatus,
|
||||
deleteAccount,
|
||||
generateQRLogin,
|
||||
checkQRLoginStatus,
|
||||
completeQRVerification,
|
||||
updateAccountPauseDuration,
|
||||
refreshAccountProfile,
|
||||
updateAccountSettings,
|
||||
passwordLogin,
|
||||
checkPasswordLoginStatus,
|
||||
cancelPasswordLogin,
|
||||
updateAccountAISettings,
|
||||
getAccountAISettings,
|
||||
getNotificationChannels,
|
||||
getAccountBindings,
|
||||
getLongLoginSettings,
|
||||
setLongLoginSettings,
|
||||
} from '../app/features/accounts/api';
|
||||
import {
|
||||
Power, Edit2, Trash2, QrCode, X, Check, Loader2,
|
||||
RefreshCw, Save, User, Clock, MessageCircle,
|
||||
Bot, Settings, AlertCircle, CalendarClock, Sparkles
|
||||
} from 'lucide-react';
|
||||
import { buildAccountLoginInfoUpdate, isCurrentAccountRequest, passwordLoginViewFromStatus, shouldUpdateAccountPause } from '../app/features/accounts/state';
|
||||
import { shouldSaveNotificationBindings } from './accountBindings';
|
||||
import { createLatestRequestGate, createQRLoginPoller } from './qrPolling';
|
||||
import { RiskVerificationPanel } from './RiskVerificationPanel';
|
||||
import { SquareQRCode } from './SquareQRCode';
|
||||
import AccountAutomationModal from './AccountAutomationModal';
|
||||
import { AccountEditModal } from '../app/features/accounts/components/AccountEditModal';
|
||||
import { useAccountsData } from '../app/features/accounts/hooks';
|
||||
import { useAccountSubmodules, type AccountModalType } from '../app/features/accounts/submoduleHooks';
|
||||
import { accountRuntimePresentation } from '../app/features/accounts/runtime';
|
||||
import type { AccountEditForm, LongLoginState, PasswordLoginView } from '../app/features/accounts/types';
|
||||
|
||||
type ModalType = 'edit' | 'ai-settings' | null;
|
||||
import type { AccountEditForm } from '../app/features/accounts/types';
|
||||
|
||||
const AccountList: React.FC = () => {
|
||||
// accountData 保存账号列表及其加载控制器。
|
||||
const { accounts, setAccounts, loading, loadAccounts } = useAccountsData();
|
||||
// accountSearch 保存列表过滤关键词。
|
||||
const [accountSearch, setAccountSearch] = useState('');
|
||||
// refreshingProfileId 保存正在刷新资料的账号 ID。
|
||||
const [refreshingProfileId, setRefreshingProfileId] = useState<string>('');
|
||||
// deletingAccountId 保存正在删除的账号 ID。
|
||||
const [deletingAccountId, setDeletingAccountId] = useState<string>('');
|
||||
// deleteDialogAccount 保存待确认删除的账号。
|
||||
const [deleteDialogAccount, setDeleteDialogAccount] = useState<AccountDetail | null>(null);
|
||||
// deleteError 保存删除失败提示。
|
||||
const [deleteError, setDeleteError] = useState('');
|
||||
// showQRModal 表示二维码登录弹窗是否打开。
|
||||
const [showQRModal, setShowQRModal] = useState(false);
|
||||
// qrCodeUrl 保存当前二维码登录地址。
|
||||
const [qrCodeUrl, setQrCodeUrl] = useState<string>('');
|
||||
// qrStatus 保存二维码登录流程状态。
|
||||
const [qrStatus, setQrStatus] = useState<string>('pending');
|
||||
// qrErrorMessage 保存二维码登录错误说明。
|
||||
const [qrErrorMessage, setQrErrorMessage] = useState<string>('');
|
||||
// verificationScreenshot 保存风控验证截图地址。
|
||||
const [verificationScreenshot, setVerificationScreenshot] = useState<string>('');
|
||||
// faceQrUrl 保存人脸验证二维码地址。
|
||||
const [faceQrUrl, setFaceQrUrl] = useState<string>('');
|
||||
// qrReauthTarget 保存需要重新授权的目标账号。
|
||||
const [qrReauthTarget, setQrReauthTarget] = useState<AccountDetail | null>(null);
|
||||
const [activeModal, setActiveModal] = useState<ModalType>(null);
|
||||
// activeModal 保存当前打开的账号配置弹窗。
|
||||
const [activeModal, setActiveModal] = useState<AccountModalType>(null);
|
||||
// editingAccount 保存当前编辑账号。
|
||||
const [editingAccount, setEditingAccount] = useState<AccountDetail | null>(null);
|
||||
// taskAccount 保存当前打开自动化任务弹窗的账号。
|
||||
const [taskAccount, setTaskAccount] = useState<AccountDetail | null>(null);
|
||||
const [longLogin, setLongLogin] = useState<LongLoginState>({ loading: false, saving: false, canOpen: false, enabled: false, error: '' });
|
||||
|
||||
// 通知渠道绑定(编辑弹窗用)
|
||||
const [notifChannels, setNotifChannels] = useState<NotificationChannel[]>([]);
|
||||
const [selectedChannelIds, setSelectedChannelIds] = useState<number[]>([]);
|
||||
const [bindingsLoaded, setBindingsLoaded] = useState(false);
|
||||
const [bindingsLoading, setBindingsLoading] = useState(false);
|
||||
const [bindingsDirty, setBindingsDirty] = useState(false);
|
||||
const [bindingsLoadError, setBindingsLoadError] = useState('');
|
||||
|
||||
// 编辑表单状态
|
||||
// 编辑表单状态。
|
||||
// editForm 保存编辑弹窗中的账号草稿。
|
||||
const [editForm, setEditForm] = useState<AccountEditForm>({
|
||||
remark: '',
|
||||
cookie: '',
|
||||
@@ -78,37 +72,58 @@ const AccountList: React.FC = () => {
|
||||
clear_password: false,
|
||||
});
|
||||
|
||||
// AI设置表单状态
|
||||
const [aiSettings, setAiSettings] = useState<AIReplySettings>({
|
||||
ai_enabled: false,
|
||||
max_discount_percent: 10,
|
||||
max_discount_amount: 100,
|
||||
max_bargain_rounds: 3,
|
||||
custom_prompts: '',
|
||||
// accountSubmodules 集中管理编辑弹窗的长登录、通知绑定、AI 和密码登录状态。
|
||||
const accountSubmodules = useAccountSubmodules({
|
||||
editingAccount,
|
||||
setEditingAccount,
|
||||
setActiveModal,
|
||||
editForm,
|
||||
setEditForm,
|
||||
loadAccounts,
|
||||
});
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [passwordLoginView, setPasswordLoginView] = useState<PasswordLoginView>({ sessionId: '', status: 'idle', message: '', qrCodeUrl: '' });
|
||||
// submoduleHandlers 保存编辑弹窗子模块的状态和事件处理函数。
|
||||
const {
|
||||
longLogin,
|
||||
notifChannels,
|
||||
selectedChannelIds,
|
||||
bindingsLoaded,
|
||||
bindingsLoading,
|
||||
bindingsLoadError,
|
||||
aiSettings,
|
||||
saving,
|
||||
passwordLoginView,
|
||||
setAiSettings,
|
||||
setBindingsDirty,
|
||||
openEditModal,
|
||||
closeEditModal,
|
||||
openAIModal,
|
||||
closeAIModal,
|
||||
loadNotificationBindings,
|
||||
toggleNotificationChannel,
|
||||
handleLongLoginToggle,
|
||||
handleSaveAISettings,
|
||||
handleSaveEdit,
|
||||
handleRestartPause,
|
||||
handlePasswordLogin,
|
||||
handleCancelPasswordLogin,
|
||||
} = accountSubmodules;
|
||||
|
||||
// qrPollerRef 保存二维码登录状态轮询器。
|
||||
const qrPollerRef = useRef<ReturnType<typeof createQRLoginPoller> | null>(null);
|
||||
// qrRequestGateRef 隔离过期的二维码生成请求。
|
||||
const qrRequestGateRef = useRef<ReturnType<typeof createLatestRequestGate> | null>(null);
|
||||
const bindingsLoadGateRef = useRef<ReturnType<typeof createLatestRequestGate> | null>(null);
|
||||
const aiLoadGateRef = useRef<ReturnType<typeof createLatestRequestGate> | null>(null);
|
||||
const bindingsLoadAbortRef = useRef<AbortController | null>(null);
|
||||
const aiLoadAbortRef = useRef<AbortController | null>(null);
|
||||
// qrGenerateAbortRef 保存二维码生成请求控制器。
|
||||
const qrGenerateAbortRef = useRef<AbortController | null>(null);
|
||||
const passwordPollAbortRef = useRef<AbortController | null>(null);
|
||||
// qrCloseTimerRef 保存二维码弹窗延迟关闭定时器。
|
||||
const qrCloseTimerRef = useRef<number | null>(null);
|
||||
const passwordPollTimerRef = useRef<number | null>(null);
|
||||
const passwordPollGenerationRef = useRef(0);
|
||||
const passwordPollAccountRef = useRef('');
|
||||
if (qrPollerRef.current === null) {
|
||||
qrPollerRef.current = createQRLoginPoller();
|
||||
}
|
||||
if (qrRequestGateRef.current === null) {
|
||||
qrRequestGateRef.current = createLatestRequestGate();
|
||||
}
|
||||
if (bindingsLoadGateRef.current === null) bindingsLoadGateRef.current = createLatestRequestGate();
|
||||
if (aiLoadGateRef.current === null) aiLoadGateRef.current = createLatestRequestGate();
|
||||
|
||||
// clearQRCloseTimer 清理二维码弹窗延迟关闭定时器。
|
||||
const clearQRCloseTimer = () => {
|
||||
if (qrCloseTimerRef.current !== null) {
|
||||
window.clearTimeout(qrCloseTimerRef.current);
|
||||
@@ -116,17 +131,12 @@ const AccountList: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const clearPasswordPollTimer = () => {
|
||||
if (passwordPollTimerRef.current !== null) {
|
||||
window.clearTimeout(passwordPollTimerRef.current);
|
||||
passwordPollTimerRef.current = null;
|
||||
}
|
||||
};
|
||||
|
||||
// stopQRPolling 停止二维码登录状态轮询。
|
||||
const stopQRPolling = () => {
|
||||
qrPollerRef.current?.stop();
|
||||
};
|
||||
|
||||
// closeQRModal 关闭二维码登录弹窗并取消请求。
|
||||
const closeQRModal = () => {
|
||||
qrGenerateAbortRef.current?.abort();
|
||||
qrRequestGateRef.current?.cancel();
|
||||
@@ -135,6 +145,7 @@ const AccountList: React.FC = () => {
|
||||
setShowQRModal(false);
|
||||
};
|
||||
|
||||
// scheduleQRModalClose 在登录成功后延迟关闭二维码弹窗。
|
||||
const scheduleQRModalClose = () => {
|
||||
clearQRCloseTimer();
|
||||
qrCloseTimerRef.current = window.setTimeout(() => {
|
||||
@@ -149,36 +160,34 @@ const AccountList: React.FC = () => {
|
||||
return () => {
|
||||
stopQRPolling();
|
||||
qrRequestGateRef.current?.cancel();
|
||||
bindingsLoadGateRef.current?.cancel();
|
||||
aiLoadGateRef.current?.cancel();
|
||||
bindingsLoadAbortRef.current?.abort();
|
||||
aiLoadAbortRef.current?.abort();
|
||||
qrGenerateAbortRef.current?.abort();
|
||||
passwordPollAbortRef.current?.abort();
|
||||
clearQRCloseTimer();
|
||||
passwordPollGenerationRef.current += 1;
|
||||
clearPasswordPollTimer();
|
||||
};
|
||||
}, []);
|
||||
|
||||
// handleToggle 切换账号启用状态。
|
||||
const handleToggle = async (id: string, currentStatus: boolean) => {
|
||||
await updateAccountStatus(id, !currentStatus);
|
||||
loadAccounts();
|
||||
};
|
||||
|
||||
// openDeleteDialog 打开账号删除确认框。
|
||||
const openDeleteDialog = (account: AccountDetail) => {
|
||||
if (deletingAccountId) return;
|
||||
setDeleteError('');
|
||||
setDeleteDialogAccount(account);
|
||||
};
|
||||
|
||||
// closeDeleteDialog 关闭账号删除确认框。
|
||||
const closeDeleteDialog = () => {
|
||||
if (deletingAccountId) return;
|
||||
setDeleteError('');
|
||||
setDeleteDialogAccount(null);
|
||||
};
|
||||
|
||||
// confirmDeleteAccount 执行账号删除并刷新列表状态。
|
||||
const confirmDeleteAccount = async () => {
|
||||
// account 保存当前确认删除的账号。
|
||||
const account = deleteDialogAccount;
|
||||
if (!account || deletingAccountId) return;
|
||||
setDeletingAccountId(account.id);
|
||||
@@ -195,9 +204,11 @@ const AccountList: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
// handleRefreshProfile 刷新账号资料并同步列表。
|
||||
const handleRefreshProfile = async (account: AccountDetail) => {
|
||||
setRefreshingProfileId(account.id);
|
||||
try {
|
||||
// res 保存资料刷新接口返回值。
|
||||
const res = await refreshAccountProfile(account.id);
|
||||
if (res?.profile_error) {
|
||||
alert('资料刷新失败:' + res.profile_error);
|
||||
@@ -210,308 +221,9 @@ const AccountList: React.FC = () => {
|
||||
setRefreshingProfileId('');
|
||||
}
|
||||
};
|
||||
|
||||
const loadNotificationBindings = async (accountId: string) => {
|
||||
const generation = bindingsLoadGateRef.current!.next();
|
||||
bindingsLoadAbortRef.current?.abort();
|
||||
const controller = new AbortController();
|
||||
bindingsLoadAbortRef.current = controller;
|
||||
setBindingsLoading(true);
|
||||
setBindingsLoaded(false);
|
||||
setBindingsDirty(false);
|
||||
setBindingsLoadError('');
|
||||
const [channelsResult, bindingsResult] = await Promise.allSettled([
|
||||
getNotificationChannels({ signal: controller.signal }),
|
||||
getAccountBindings(accountId, { signal: controller.signal }),
|
||||
]);
|
||||
if (!bindingsLoadGateRef.current?.isCurrent(generation)) return;
|
||||
if (channelsResult.status === 'fulfilled') {
|
||||
setNotifChannels(channelsResult.value.data || []);
|
||||
} else {
|
||||
setNotifChannels([]);
|
||||
setBindingsLoadError('通知渠道列表加载失败,请重试');
|
||||
}
|
||||
if (bindingsResult.status === 'fulfilled') {
|
||||
setSelectedChannelIds(bindingsResult.value || []);
|
||||
setBindingsLoaded(true);
|
||||
} else {
|
||||
setSelectedChannelIds([]);
|
||||
setBindingsLoadError('通知绑定加载失败;本次保存不会修改现有绑定');
|
||||
}
|
||||
setBindingsLoading(false);
|
||||
};
|
||||
|
||||
// toggleNotificationChannel 使用函数式更新切换通知绑定,避免连续点击覆盖选择结果。
|
||||
const toggleNotificationChannel = (channelId: number) => {
|
||||
setSelectedChannelIds(current => current.includes(channelId)
|
||||
? current.filter(id => id !== channelId)
|
||||
: [...current, channelId]);
|
||||
};
|
||||
|
||||
const openEditModal = async (account: AccountDetail) => {
|
||||
passwordPollGenerationRef.current += 1;
|
||||
passwordPollAccountRef.current = account.id;
|
||||
passwordPollAbortRef.current?.abort();
|
||||
clearPasswordPollTimer();
|
||||
setPasswordLoginView({ sessionId: '', status: 'idle', message: '', qrCodeUrl: '' });
|
||||
setEditingAccount(account);
|
||||
setEditForm({
|
||||
remark: account.remark || account.note || '',
|
||||
cookie: account.cookie || account.value || '',
|
||||
auto_confirm: account.auto_confirm || false,
|
||||
pause_duration: account.pause_duration || 0,
|
||||
username: account.username || '',
|
||||
login_password: account.login_password || '',
|
||||
show_browser: account.show_browser || false,
|
||||
showLoginPassword: false,
|
||||
clear_password: false,
|
||||
});
|
||||
setActiveModal('edit');
|
||||
setLongLogin({ loading: true, saving: false, canOpen: false, enabled: false, error: '' });
|
||||
const [, longLoginResult] = await Promise.allSettled([
|
||||
loadNotificationBindings(account.id),
|
||||
getLongLoginSettings(account.id),
|
||||
]);
|
||||
if (longLoginResult.status === 'fulfilled') {
|
||||
setLongLogin({ loading: false, saving: false, canOpen: longLoginResult.value.can_open_long_login, enabled: longLoginResult.value.enabled, error: '' });
|
||||
} else {
|
||||
setLongLogin({ loading: false, saving: false, canOpen: false, enabled: false, error: '无法读取闲鱼保存登录信息状态' });
|
||||
}
|
||||
};
|
||||
|
||||
const handleLongLoginToggle = async () => {
|
||||
if (!editingAccount || longLogin.loading || longLogin.saving || !longLogin.canOpen) return;
|
||||
const enabled = !longLogin.enabled;
|
||||
setLongLogin(current => ({ ...current, saving: true, error: '' }));
|
||||
try {
|
||||
const result = await setLongLoginSettings(editingAccount.id, enabled);
|
||||
setLongLogin({ loading: false, saving: false, canOpen: result.can_open_long_login, enabled: result.enabled, error: '' });
|
||||
} catch (error) {
|
||||
setLongLogin(current => ({ ...current, saving: false, error: error instanceof Error ? error.message : '保存登录信息设置失败' }));
|
||||
}
|
||||
};
|
||||
|
||||
const openAIModal = async (account: AccountDetail) => {
|
||||
const generation = aiLoadGateRef.current!.next();
|
||||
aiLoadAbortRef.current?.abort();
|
||||
const controller = new AbortController();
|
||||
aiLoadAbortRef.current = controller;
|
||||
setEditingAccount(account);
|
||||
setActiveModal('ai-settings');
|
||||
setSaving(true);
|
||||
try {
|
||||
const settings = await getAccountAISettings(account.id, { signal: controller.signal });
|
||||
if (!aiLoadGateRef.current?.isCurrent(generation)) return;
|
||||
setAiSettings({
|
||||
ai_enabled: settings.ai_enabled ?? false,
|
||||
max_discount_percent: settings.max_discount_percent ?? 10,
|
||||
max_discount_amount: settings.max_discount_amount ?? 100,
|
||||
max_bargain_rounds: settings.max_bargain_rounds ?? 3,
|
||||
custom_prompts: settings.custom_prompts ?? '',
|
||||
});
|
||||
} catch (e) {
|
||||
if (aiLoadGateRef.current?.isCurrent(generation)) console.error('Failed to load AI settings:', e);
|
||||
} finally {
|
||||
if (aiLoadGateRef.current?.isCurrent(generation)) setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveEdit = async () => {
|
||||
if (!editingAccount) return;
|
||||
setSaving(true);
|
||||
|
||||
try {
|
||||
const payload: Parameters<typeof updateAccountSettings>[1] = {};
|
||||
|
||||
// 更新备注
|
||||
if (editForm.remark !== (editingAccount.remark || editingAccount.note || '')) {
|
||||
payload.remark = editForm.remark;
|
||||
}
|
||||
|
||||
// 更新Cookie
|
||||
if (editForm.cookie && editForm.cookie !== (editingAccount.cookie || editingAccount.value || '')) {
|
||||
payload.cookie = editForm.cookie;
|
||||
}
|
||||
|
||||
// 更新自动确认
|
||||
if (editForm.auto_confirm !== editingAccount.auto_confirm) {
|
||||
payload.auto_confirm = editForm.auto_confirm;
|
||||
}
|
||||
|
||||
// 更新暂停时长
|
||||
if (shouldUpdateAccountPause(editForm.pause_duration, editingAccount)) {
|
||||
payload.pause_duration = editForm.pause_duration;
|
||||
}
|
||||
|
||||
// 更新登录信息
|
||||
const loginInfo = buildAccountLoginInfoUpdate(editingAccount, editForm);
|
||||
if (loginInfo) {
|
||||
Object.assign(payload, loginInfo);
|
||||
}
|
||||
|
||||
// 只有成功加载且用户确实改动后才覆盖,避免加载失败被误解释成解绑全部。
|
||||
if (shouldSaveNotificationBindings(bindingsLoaded, bindingsDirty)) {
|
||||
payload.channel_ids = selectedChannelIds;
|
||||
}
|
||||
|
||||
if (Object.keys(payload).length > 0) await updateAccountSettings(editingAccount.id, payload);
|
||||
setActiveModal(null);
|
||||
loadAccounts();
|
||||
} catch (error) {
|
||||
console.error('更新账号失败:', error);
|
||||
alert('更新失败,请重试');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRestartPause = async () => {
|
||||
if (!editingAccount || editForm.pause_duration <= 0) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
const result = await updateAccountPauseDuration(editingAccount.id, editForm.pause_duration);
|
||||
setEditingAccount({
|
||||
...editingAccount,
|
||||
pause_duration: editForm.pause_duration,
|
||||
paused: result?.paused === true,
|
||||
paused_until: Number(result?.paused_until || 0),
|
||||
});
|
||||
await loadAccounts();
|
||||
} catch (error) {
|
||||
alert(error instanceof Error ? error.message : '重新暂停失败');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveAISettings = async () => {
|
||||
if (!editingAccount) return;
|
||||
setSaving(true);
|
||||
|
||||
try {
|
||||
await updateAccountAISettings(editingAccount.id, aiSettings);
|
||||
setActiveModal(null);
|
||||
loadAccounts();
|
||||
} catch (error) {
|
||||
console.error('更新AI设置失败:', error);
|
||||
alert('更新失败,请重试');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
// pollPasswordLogin 轮询密码登录状态,并按账号和请求代次隔离过期响应。
|
||||
const pollPasswordLogin = async (sessionId: string, generation: number, accountId: string) => {
|
||||
passwordPollAbortRef.current?.abort();
|
||||
// controller 取消上一轮仍未完成的密码登录状态请求。
|
||||
const controller = new AbortController();
|
||||
passwordPollAbortRef.current = controller;
|
||||
try {
|
||||
// result 是后端返回的当前密码登录状态。
|
||||
const result = await checkPasswordLoginStatus(sessionId, controller.signal);
|
||||
if (!isCurrentAccountRequest(generation, passwordPollGenerationRef.current, accountId, passwordPollAccountRef.current)) return;
|
||||
// nextView 是统一转换后的密码登录展示状态。
|
||||
const nextView = { ...passwordLoginViewFromStatus(result), sessionId };
|
||||
if (result.status === 'success') {
|
||||
clearPasswordPollTimer();
|
||||
setPasswordLoginView(nextView);
|
||||
setEditForm(current => ({ ...current, login_password: '', showLoginPassword: false }));
|
||||
await loadAccounts();
|
||||
return;
|
||||
}
|
||||
if (result.status === 'processing' || result.status === 'verification_required') {
|
||||
setPasswordLoginView(nextView);
|
||||
clearPasswordPollTimer();
|
||||
passwordPollTimerRef.current = window.setTimeout(
|
||||
// pollNextStatus 在短暂间隔后继续查询当前密码登录会话。
|
||||
() => void pollPasswordLogin(sessionId, generation, accountId),
|
||||
1500,
|
||||
);
|
||||
return;
|
||||
}
|
||||
clearPasswordPollTimer();
|
||||
setPasswordLoginView(nextView);
|
||||
} catch (error /* 密码登录状态查询错误 */) {
|
||||
if (!isCurrentAccountRequest(generation, passwordPollGenerationRef.current, accountId, passwordPollAccountRef.current)) return;
|
||||
clearPasswordPollTimer();
|
||||
setPasswordLoginView({
|
||||
sessionId,
|
||||
status: 'failed',
|
||||
message: error instanceof Error ? error.message : '查询密码登录状态失败',
|
||||
qrCodeUrl: '',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
const handlePasswordLogin = async () => {
|
||||
if (!editingAccount) return;
|
||||
const account = editForm.username.trim();
|
||||
if (!account || !editForm.login_password) {
|
||||
alert('请先填写登录账号和本次登录密码');
|
||||
return;
|
||||
}
|
||||
clearPasswordPollTimer();
|
||||
passwordPollAbortRef.current?.abort();
|
||||
const generation = ++passwordPollGenerationRef.current;
|
||||
passwordPollAccountRef.current = editingAccount.id;
|
||||
setPasswordLoginView({ sessionId: '', status: 'processing', message: '正在启动密码登录…', qrCodeUrl: '' });
|
||||
try {
|
||||
const result = await passwordLogin({
|
||||
account_id: editingAccount.id,
|
||||
account,
|
||||
password: editForm.login_password,
|
||||
show_browser: editForm.show_browser,
|
||||
});
|
||||
if (!isCurrentAccountRequest(generation, passwordPollGenerationRef.current, editingAccount.id, passwordPollAccountRef.current)) return;
|
||||
if (!result.success || !result.session_id) {
|
||||
throw new Error(result.message || '无法启动密码登录');
|
||||
}
|
||||
setPasswordLoginView({ sessionId: result.session_id, status: 'processing', message: result.message || '登录处理中', qrCodeUrl: '' });
|
||||
await pollPasswordLogin(result.session_id, generation, editingAccount.id);
|
||||
} catch (error) {
|
||||
if (!isCurrentAccountRequest(generation, passwordPollGenerationRef.current, editingAccount.id, passwordPollAccountRef.current)) return;
|
||||
setPasswordLoginView({
|
||||
sessionId: '',
|
||||
status: 'failed',
|
||||
message: error instanceof Error ? error.message : '启动密码登录失败',
|
||||
qrCodeUrl: '',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancelPasswordLogin = async () => {
|
||||
const sessionId = passwordLoginView.sessionId;
|
||||
passwordPollGenerationRef.current += 1;
|
||||
passwordPollAccountRef.current = '';
|
||||
passwordPollAbortRef.current?.abort();
|
||||
clearPasswordPollTimer();
|
||||
if (sessionId) {
|
||||
try {
|
||||
await cancelPasswordLogin(sessionId);
|
||||
} catch (error) {
|
||||
console.error('取消密码登录失败', error);
|
||||
}
|
||||
}
|
||||
setPasswordLoginView({ sessionId: '', status: 'idle', message: '', qrCodeUrl: '' });
|
||||
};
|
||||
|
||||
const closeEditModal = async () => {
|
||||
bindingsLoadGateRef.current?.cancel();
|
||||
bindingsLoadAbortRef.current?.abort();
|
||||
if (passwordLoginView.status === 'processing' || passwordLoginView.status === 'verification_required') {
|
||||
await handleCancelPasswordLogin();
|
||||
}
|
||||
setActiveModal(null);
|
||||
};
|
||||
|
||||
const closeAIModal = () => {
|
||||
aiLoadGateRef.current?.cancel();
|
||||
aiLoadAbortRef.current?.abort();
|
||||
setActiveModal(null);
|
||||
};
|
||||
|
||||
// completeAndPersistQRSession 完成二维码风控验证并持久化授权结果。
|
||||
const completeAndPersistQRSession = async (sessionId: string, target?: AccountDetail | null) => {
|
||||
// res 保存风控验证完成接口返回值。
|
||||
const res = await completeQRVerification(sessionId, target?.id);
|
||||
if (!res.success || !res.account_id) {
|
||||
throw new Error(res.message || '保存扫码授权失败');
|
||||
@@ -519,13 +231,17 @@ const AccountList: React.FC = () => {
|
||||
return res.account_id;
|
||||
};
|
||||
|
||||
// startQRLogin 启动二维码登录或账号重新授权流程。
|
||||
const startQRLogin = async (target?: AccountDetail) => {
|
||||
stopQRPolling();
|
||||
qrGenerateAbortRef.current?.abort();
|
||||
// controller 控制当前二维码生成请求的取消。
|
||||
const controller = new AbortController();
|
||||
qrGenerateAbortRef.current = controller;
|
||||
// requestGeneration 标识当前二维码生成请求代次。
|
||||
const requestGeneration = qrRequestGateRef.current!.next();
|
||||
clearQRCloseTimer();
|
||||
// targetAccount 保存当前二维码授权目标账号。
|
||||
const targetAccount = target || null;
|
||||
setQrReauthTarget(targetAccount);
|
||||
setShowQRModal(true);
|
||||
@@ -535,12 +251,14 @@ const AccountList: React.FC = () => {
|
||||
setVerificationScreenshot('');
|
||||
setFaceQrUrl('');
|
||||
try {
|
||||
// res 保存二维码生成接口返回值。
|
||||
const res = await generateQRLogin({ signal: controller.signal });
|
||||
if (!qrRequestGateRef.current?.isCurrent(requestGeneration)) return;
|
||||
if (!res.success || !res.qr_code_url || !res.session_id) {
|
||||
throw new Error(res.message || '闲鱼未返回可用的登录二维码');
|
||||
}
|
||||
if (res.success && res.qr_code_url && res.session_id) {
|
||||
// generatedSessionID 保存后端生成的二维码登录会话。
|
||||
const generatedSessionID = res.session_id;
|
||||
setQrCodeUrl(res.qr_code_url);
|
||||
setQrStatus('waiting');
|
||||
|
||||
@@ -177,6 +177,7 @@ describe('frontend navigation routing', () => {
|
||||
const accounts = [
|
||||
readFrontendFile('components/AccountList.tsx'),
|
||||
readFrontendFile('app/features/accounts/components/AccountEditModal.tsx'),
|
||||
readFrontendFile('app/features/accounts/submoduleHooks.ts'),
|
||||
].join('\n');
|
||||
expect(accounts).toContain('passwordLogin({');
|
||||
expect(accounts).toContain('checkPasswordLoginStatus(sessionId, controller.signal)');
|
||||
|
||||
@@ -559,6 +559,24 @@ test('password login service uses upstream-compatible routes', async () => {
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(3, '/api/v1/password-login/cancel/sid', expect.objectContaining({ method: 'DELETE' }));
|
||||
});
|
||||
|
||||
test('账号编辑子模块请求支持取消过期响应', async () => {
|
||||
// fetchMock 是验证请求取消信号透传的测试替身。
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce(jsonResponse({ can_open_long_login: true, enabled: false }))
|
||||
.mockResolvedValueOnce(jsonResponse({ ai_enabled: true }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, session_id: 'sid' }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const controller = new AbortController();
|
||||
|
||||
await getLongLoginSettings('acc1', { signal: controller.signal });
|
||||
await getAccountAISettings('acc1', { signal: controller.signal });
|
||||
await passwordLogin({ account_id: 'acc1', account: 'u', password: 'p' }, { signal: controller.signal });
|
||||
|
||||
expect(fetchMock.mock.calls[0][1].signal).toBeInstanceOf(AbortSignal);
|
||||
expect(fetchMock.mock.calls[1][1].signal).toBeInstanceOf(AbortSignal);
|
||||
expect(fetchMock.mock.calls[2][1].signal).toBeInstanceOf(AbortSignal);
|
||||
});
|
||||
|
||||
test('getShippingRules exposes buyer reviewed gift rules as automation rules', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse([{
|
||||
id: 12,
|
||||
|
||||
+14
-14
@@ -202,8 +202,8 @@ export const updateAccountAutoConfirm = async (id: string, autoConfirm: boolean)
|
||||
return put(`/api/v1/accounts/${id}/auto-confirm`, { auto_confirm: autoConfirm });
|
||||
};
|
||||
|
||||
export const updateAccountPauseDuration = async (id: string, pauseDuration: number): Promise<CookieSettingsResponse> => {
|
||||
return put(`/api/v1/accounts/${id}/pause-duration`, { pause_duration: pauseDuration });
|
||||
export const updateAccountPauseDuration = async (id: string, pauseDuration: number, options?: RequestControlOptions): Promise<CookieSettingsResponse> => {
|
||||
return put(`/api/v1/accounts/${id}/pause-duration`, { pause_duration: pauseDuration }, options);
|
||||
};
|
||||
|
||||
export const updateAccountCookie = async (id: string, value: string, loginMethod?: string): Promise<OperationResponse> => {
|
||||
@@ -222,8 +222,8 @@ export interface AccountSettingsUpdate {
|
||||
channel_ids?: number[];
|
||||
}
|
||||
|
||||
export const updateAccountSettings = async (id: string, data: AccountSettingsUpdate): Promise<CookieSettingsResponse> => {
|
||||
return put(`/api/v1/accounts/${id}/settings`, data);
|
||||
export const updateAccountSettings = async (id: string, data: AccountSettingsUpdate, options?: RequestControlOptions): Promise<CookieSettingsResponse> => {
|
||||
return put(`/api/v1/accounts/${id}/settings`, data, options);
|
||||
};
|
||||
|
||||
export interface LongLoginSettings {
|
||||
@@ -231,12 +231,12 @@ export interface LongLoginSettings {
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export const getLongLoginSettings = async (id: string): Promise<LongLoginSettings> => {
|
||||
return get(`/api/v1/accounts/${id}/long-login`);
|
||||
export const getLongLoginSettings = async (id: string, options?: RequestControlOptions): Promise<LongLoginSettings> => {
|
||||
return get(`/api/v1/accounts/${id}/long-login`, undefined, options);
|
||||
};
|
||||
|
||||
export const setLongLoginSettings = async (id: string, enabled: boolean): Promise<LongLoginSettings> => {
|
||||
return put(`/api/v1/accounts/${id}/long-login`, { enabled });
|
||||
export const setLongLoginSettings = async (id: string, enabled: boolean, options?: RequestControlOptions): Promise<LongLoginSettings> => {
|
||||
return put(`/api/v1/accounts/${id}/long-login`, { enabled }, options);
|
||||
};
|
||||
|
||||
export interface PasswordLoginStartResponse {
|
||||
@@ -264,16 +264,16 @@ export const passwordLogin = async (data: {
|
||||
account: string;
|
||||
password: string;
|
||||
show_browser?: boolean;
|
||||
}): Promise<PasswordLoginStartResponse> => {
|
||||
return post('/api/v1/password-login', data);
|
||||
}, options?: RequestControlOptions): Promise<PasswordLoginStartResponse> => {
|
||||
return post('/api/v1/password-login', data, options);
|
||||
};
|
||||
|
||||
export const checkPasswordLoginStatus = async (sessionId: string, signal?: AbortSignal): Promise<PasswordLoginStatusResponse> => {
|
||||
return get(`/api/v1/password-login/check/${sessionId}`, undefined, { signal, timeoutMs: 10_000 });
|
||||
};
|
||||
|
||||
export const cancelPasswordLogin = async (sessionId: string): Promise<ApiResponse> => {
|
||||
return del(`/api/v1/password-login/cancel/${sessionId}`);
|
||||
export const cancelPasswordLogin = async (sessionId: string, options?: RequestControlOptions): Promise<ApiResponse> => {
|
||||
return del(`/api/v1/password-login/cancel/${sessionId}`, undefined, options);
|
||||
};
|
||||
|
||||
export const refreshAccountProfile = async (id: string): Promise<CookieProfileResponse> => {
|
||||
@@ -896,7 +896,7 @@ export const getAccountAISettings = async (cookieId: string, options?: RequestCo
|
||||
return get(`/api/v1/settings/ai-reply/${cookieId}`, undefined, options);
|
||||
}
|
||||
|
||||
export const updateAccountAISettings = async (cookieId: string, settings: Partial<AIReplySettings>): Promise<OperationResponse> => {
|
||||
export const updateAccountAISettings = async (cookieId: string, settings: Partial<AIReplySettings>, options?: RequestControlOptions): Promise<OperationResponse> => {
|
||||
const payload = {
|
||||
ai_enabled: settings.ai_enabled ?? false,
|
||||
max_discount_percent: settings.max_discount_percent ?? 10,
|
||||
@@ -904,7 +904,7 @@ export const updateAccountAISettings = async (cookieId: string, settings: Partia
|
||||
max_bargain_rounds: settings.max_bargain_rounds ?? 3,
|
||||
custom_prompts: settings.custom_prompts ?? ''
|
||||
};
|
||||
return put(`/api/v1/settings/ai-reply/${cookieId}`, payload);
|
||||
return put(`/api/v1/settings/ai-reply/${cookieId}`, payload, options);
|
||||
}
|
||||
|
||||
export const fetchAIModels = async (baseUrl: string, apiKey: string = '', options?: RequestControlOptions): Promise<string[]> => {
|
||||
|
||||
Reference in new issue
Block a user