File size: 10,522 Bytes
a21c316 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 | import { create } from 'zustand';
import { Account } from '../types/account';
import * as accountService from '../services/accountService';
interface AccountState {
accounts: Account[];
currentAccount: Account | null;
loading: boolean;
error: string | null;
// Actions
fetchAccounts: () => Promise<void>;
fetchCurrentAccount: () => Promise<void>;
addAccount: (email: string, refreshToken: string) => Promise<void>;
deleteAccount: (accountId: string) => Promise<void>;
deleteAccounts: (accountIds: string[]) => Promise<void>;
switchAccount: (accountId: string) => Promise<void>;
refreshQuota: (accountId: string) => Promise<void>;
refreshAllQuotas: () => Promise<accountService.RefreshStats>;
reorderAccounts: (accountIds: string[]) => Promise<void>;
// 新增 actions
startOAuthLogin: () => Promise<void>;
completeOAuthLogin: () => Promise<void>;
cancelOAuthLogin: () => Promise<void>;
importV1Accounts: () => Promise<void>;
importFromDb: () => Promise<void>;
importFromCustomDb: (path: string) => Promise<void>;
syncAccountFromDb: () => Promise<void>;
toggleProxyStatus: (accountId: string, enable: boolean, reason?: string) => Promise<void>;
warmUpAccounts: () => Promise<string>;
warmUpAccount: (accountId: string) => Promise<string>;
updateAccountLabel: (accountId: string, label: string) => Promise<void>;
}
export const useAccountStore = create<AccountState>((set, get) => ({
accounts: [],
currentAccount: null,
loading: false,
error: null,
fetchAccounts: async () => {
set({ loading: true, error: null });
try {
console.log('[Store] Fetching accounts...');
const accounts = await accountService.listAccounts();
set({ accounts, loading: false });
} catch (error) {
console.error('[Store] Fetch accounts failed:', error);
set({ error: String(error), loading: false });
}
},
fetchCurrentAccount: async () => {
set({ loading: true, error: null });
try {
const account = await accountService.getCurrentAccount();
set({ currentAccount: account, loading: false });
} catch (error) {
set({ error: String(error), loading: false });
}
},
addAccount: async (email: string, refreshToken: string) => {
set({ loading: true, error: null });
try {
await accountService.addAccount(email, refreshToken);
await get().fetchAccounts();
set({ loading: false });
} catch (error) {
set({ error: String(error), loading: false });
throw error;
}
},
deleteAccount: async (accountId: string) => {
set({ loading: true, error: null });
try {
await accountService.deleteAccount(accountId);
await Promise.all([
get().fetchAccounts(),
get().fetchCurrentAccount()
]);
set({ loading: false });
} catch (error) {
set({ error: String(error), loading: false });
throw error;
}
},
deleteAccounts: async (accountIds: string[]) => {
set({ loading: true, error: null });
try {
await accountService.deleteAccounts(accountIds);
await Promise.all([
get().fetchAccounts(),
get().fetchCurrentAccount()
]);
set({ loading: false });
} catch (error) {
set({ error: String(error), loading: false });
throw error;
}
},
switchAccount: async (accountId: string) => {
set({ loading: true, error: null });
try {
await accountService.switchAccount(accountId);
await get().fetchCurrentAccount();
set({ loading: false });
} catch (error) {
set({ error: String(error), loading: false });
throw error;
}
},
refreshQuota: async (accountId: string) => {
set({ loading: true, error: null });
try {
await accountService.fetchAccountQuota(accountId);
await get().fetchAccounts();
set({ loading: false });
} catch (error) {
set({ error: String(error), loading: false });
throw error;
}
},
refreshAllQuotas: async () => {
set({ loading: true, error: null });
try {
const stats = await accountService.refreshAllQuotas();
await get().fetchAccounts();
set({ loading: false });
return stats;
} catch (error) {
set({ error: String(error), loading: false });
throw error;
}
},
/**
* 重新排序账号列表
* 采用乐观更新策略:先更新本地状态再调用后端持久化,以提供流畅的拖拽体验
*/
reorderAccounts: async (accountIds: string[]) => {
const { accounts } = get();
// 创建 ID 到账号的映射
const accountMap = new Map(accounts.map(acc => [acc.id, acc]));
// 按新顺序重建账号数组
const reorderedAccounts = accountIds
.map(id => accountMap.get(id))
.filter((acc): acc is Account => acc !== undefined);
// 添加未在新顺序中的账号(保持原有顺序)
const remainingAccounts = accounts.filter(acc => !accountIds.includes(acc.id));
const finalAccounts = [...reorderedAccounts, ...remainingAccounts];
// 乐观更新本地状态
set({ accounts: finalAccounts });
try {
await accountService.reorderAccounts(accountIds);
} catch (error) {
// 后端失败时回滚到原始顺序
console.error('[AccountStore] Reorder accounts failed:', error);
set({ accounts });
throw error;
}
},
startOAuthLogin: async () => {
set({ loading: true, error: null });
try {
await accountService.startOAuthLogin();
await get().fetchAccounts();
set({ loading: false });
} catch (error) {
set({ error: String(error), loading: false });
throw error;
}
},
completeOAuthLogin: async () => {
set({ loading: true, error: null });
try {
await accountService.completeOAuthLogin();
await get().fetchAccounts();
set({ loading: false });
} catch (error) {
set({ error: String(error), loading: false });
throw error;
}
},
cancelOAuthLogin: async () => {
try {
await accountService.cancelOAuthLogin();
set({ loading: false, error: null });
} catch (error) {
console.error('[Store] Cancel OAuth failed:', error);
}
},
importV1Accounts: async () => {
set({ loading: true, error: null });
try {
await accountService.importV1Accounts();
await get().fetchAccounts();
set({ loading: false });
} catch (error) {
set({ error: String(error), loading: false });
throw error;
}
},
importFromDb: async () => {
set({ loading: true, error: null });
try {
await accountService.importFromDb();
await Promise.all([
get().fetchAccounts(),
get().fetchCurrentAccount()
]);
set({ loading: false });
} catch (error) {
set({ error: String(error), loading: false });
throw error;
}
},
importFromCustomDb: async (path: string) => {
set({ loading: true, error: null });
try {
await accountService.importFromCustomDb(path);
await Promise.all([
get().fetchAccounts(),
get().fetchCurrentAccount()
]);
set({ loading: false });
} catch (error) {
set({ error: String(error), loading: false });
throw error;
}
},
syncAccountFromDb: async () => {
try {
const syncedAccount = await accountService.syncAccountFromDb();
if (syncedAccount) {
console.log('[AccountStore] Account synced from DB:', syncedAccount.email);
await get().fetchAccounts();
set({ currentAccount: syncedAccount });
}
} catch (error) {
console.error('[AccountStore] Sync from DB failed:', error);
}
},
toggleProxyStatus: async (accountId: string, enable: boolean, reason?: string) => {
try {
await accountService.toggleProxyStatus(accountId, enable, reason);
await get().fetchAccounts();
} catch (error) {
console.error('[AccountStore] Toggle proxy status failed:', error);
throw error;
}
},
warmUpAccounts: async () => {
set({ loading: true, error: null });
try {
const result = await accountService.warmUpAllAccounts();
set({ loading: false });
return result;
} catch (error) {
set({ error: String(error), loading: false });
throw error;
} finally {
await get().fetchAccounts();
}
},
warmUpAccount: async (accountId: string) => {
set({ loading: true, error: null });
try {
const result = await accountService.warmUpAccount(accountId);
set({ loading: false });
return result;
} catch (error) {
set({ error: String(error), loading: false });
throw error;
} finally {
await get().fetchAccounts();
}
},
updateAccountLabel: async (accountId: string, label: string) => {
try {
await accountService.updateAccountLabel(accountId, label);
// 乐观更新本地状态
const { accounts } = get();
const updatedAccounts = accounts.map(acc =>
acc.id === accountId ? { ...acc, custom_label: label || undefined } : acc
);
set({ accounts: updatedAccounts });
} catch (error) {
console.error('[AccountStore] Update label failed:', error);
throw error;
}
},
}));
|