import { useQueries } from '@tanstack/react-query' import { groupBy, keyBy, uniqBy } from 'lodash' import { useMemo } from 'react' import { ApiResource, PlansResource } from '../../types' import { ApiClient, useApiClient } from '../use_api_client' export type PlanListItem = | { type: 'header'; title: string } | { type: 'plan'; value: number; name: string } export function useTeamPlans({ teamIds }: { teamIds: number[] }) { const apiClient = useApiClient() const planQueries = useQueries({ queries: teamIds.map(teamId => ({ queryKey: ['plansForTeam', teamId], queryFn: () => fetchTeamPlans(apiClient, teamId), initialData: NULL_RESPONSE, retry: false, })), }) const [planIndex, flatPlanOptions] = useMemo(() => { const planOptions = planQueries.flatMap(({ data }) => data?.data.plans).filter(p => !!p) const uniqPlanOptions = uniqBy(planOptions, 'value') const groupedPlanOptions = groupBy(uniqPlanOptions, 'group') const options = Object.entries(groupedPlanOptions).reduce( (acc, [title, plans]): PlanListItem[] => [ ...acc, { type: 'header', title }, ...plans.map(({ value, name }): PlanListItem => ({ type: 'plan', value, name })), ], [] ) return [keyBy(uniqPlanOptions, 'value'), options] }, [planQueries]) return { planOptions: flatPlanOptions, isFetching: planQueries.some(({ isFetching }) => isFetching), isError: planQueries.some(({ isError }) => isError), findPlan: (id: number | undefined) => id && planIndex[id], } } const NULL_RESPONSE = { data: { id: 0, plans: [], type: 'Chat' }, links: {}, meta: {} } function fetchTeamPlans(apiClient: ApiClient, teamId: number) { return apiClient.services.get>({ url: '/chat', data: { team_id: teamId, fields: { Chat: ['plans'], }, }, }) }