import { useQuery } from '@tanstack/react-query' import { IS_PLATFORM } from 'common' import { organizationKeys } from './keys' import { get, handleError } from '@/data/fetchers' import { FGA_PERMISSIONS, useAsyncCheckPermissionsV2 } from '@/hooks/misc/useCheckPermissionsV2' import type { StudioError } from '@/lib/errors/studio-errors' import type { UseCustomQueryOptions } from '@/types' export type OrganizationCustomerProfileVariables = { slug?: string } export async function getOrganizationCustomerProfile( { slug }: OrganizationCustomerProfileVariables, signal?: AbortSignal ) { if (!slug) throw new Error('slug is required') const { data, error } = await get(`/platform/organizations/{slug}/customer`, { params: { path: { slug, }, }, signal, }) if (error) handleError(error) return data } export type OrganizationCustomerProfileData = Awaited< ReturnType > export type OrganizationCustomerProfileError = StudioError export const useOrganizationCustomerProfileQuery = ( { slug }: OrganizationCustomerProfileVariables, { enabled = true, ...options }: UseCustomQueryOptions< OrganizationCustomerProfileData, OrganizationCustomerProfileError, TData > = {} ) => { // [Joshen] Thinking it makes sense to add this check at the RQ level - prevent // unnecessary requests, although this behaviour still needs handling on the UI const { can: canReadCustomerProfile } = useAsyncCheckPermissionsV2( FGA_PERMISSIONS.ORGANIZATION.BILLING_READ, { organizationSlug: slug, } ) return useQuery({ queryKey: organizationKeys.customerProfile(slug), queryFn: ({ signal }) => getOrganizationCustomerProfile({ slug }, signal), enabled: IS_PLATFORM && enabled && canReadCustomerProfile && typeof slug !== 'undefined', ...options, }) }