// Copyright: © 2026 TWWIM UG. All rights reserved. (www.twwim.com) /** * TanStack Query hook for the operator's own availability state. * * - useOperatorAvailability(): query for the current persisted flag, fetched * once on mount (no polling — the user is the only writer). * - useSetOperatorAvailability(): mutation that PATCHes the new value and * refreshes the query plus the members list (other dashboards in the same * tenant see the change next time they re-render). * * Limitation: ADMIN/MANAGER/WORKER hit a 403 from the API and the query * surfaces as `error`. The toggle component renders a neutral pill in that * case — useful for tenants where the chat operator role isn't yet assigned. */ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { operatorAvailabilityApi } from '@/infrastructure/http/api/operator-availability/api'; import type { OperatorAvailabilityRequest, OperatorAvailabilityResponse, } from '@archer/api-interface'; const KEY = ['operator', 'availability'] as const; export function useOperatorAvailability() { return useQuery({ queryKey: KEY, queryFn: () => operatorAvailabilityApi.get(), // No automatic refetch — the operator is the only writer of this flag. // Tab focus refetch still applies (a colleague who toggled in another // browser tab will be picked up when this tab regains focus). refetchOnWindowFocus: true, staleTime: 30_000, retry: (failureCount, err: any) => { // 403 = caller is not an OPERATOR — don't pound the endpoint. const status = err?.status ?? err?.response?.status; if (status === 403 || status === 401) return false; return failureCount < 2; }, }); } export function useSetOperatorAvailability() { const qc = useQueryClient(); return useMutation({ mutationFn: (payload) => operatorAvailabilityApi.set(payload), onSuccess: (snapshot) => { qc.setQueryData(KEY, snapshot); // Teammates list shows availability dots — invalidate so a fresh fetch // brings the new state in. Keys live under ['company', 'members', …] // and we want any variant to refresh. qc.invalidateQueries({ queryKey: ['company', 'members'] }); }, }); }