ultisuite-client/lib/stores/account-store.ts
2026-05-25 13:52:40 +02:00

67 lines
2.0 KiB
TypeScript

'use client'
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
import { useQueryClient } from '@tanstack/react-query'
import { useAuthStore } from '@/lib/api/auth-store'
import { useMailAccounts } from '@/lib/api/hooks/use-mail-queries'
import { debouncedPersistJSONStorage } from '@/lib/stores/debounced-json-storage'
import type { ApiMailAccount } from '@/lib/api/types'
type AccountStoreState = {
activeAccountId: string | null
otherAccountsExpanded: boolean
}
type AccountStoreActions = {
setActiveAccountId: (id: string | null) => void
setOtherAccountsExpanded: (expanded: boolean) => void
toggleOtherAccountsExpanded: () => void
}
export const useAccountStore = create<AccountStoreState & AccountStoreActions>()(
persist(
(set) => ({
activeAccountId: null,
otherAccountsExpanded: true,
setActiveAccountId: (id) => set({ activeAccountId: id }),
setOtherAccountsExpanded: (expanded) =>
set({ otherAccountsExpanded: expanded }),
toggleOtherAccountsExpanded: () =>
set((s) => ({ otherAccountsExpanded: !s.otherAccountsExpanded })),
}),
{
name: 'ultimail-accounts',
storage: debouncedPersistJSONStorage,
partialize: (s) => ({
activeAccountId: s.activeAccountId,
otherAccountsExpanded: s.otherAccountsExpanded,
}),
},
),
)
export function useActiveAccount(): ApiMailAccount | null {
const activeAccountId = useAccountStore((s) => s.activeAccountId)
const { data: accounts } = useMailAccounts()
return accounts?.find((a) => a.id === activeAccountId) ?? accounts?.[0] ?? null
}
export function useSignOutAll() {
const queryClient = useQueryClient()
return async () => {
await fetch("/api/auth/logout", { method: "POST", credentials: "include" })
if (typeof window !== "undefined") {
localStorage.removeItem("ultimail-auth")
}
useAuthStore.getState().logout()
queryClient.clear()
useAccountStore.setState({ activeAccountId: null, otherAccountsExpanded: true })
window.location.href = "/login"
}
}