Skip to content

Commit

Permalink
query refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
papistacoding committed Jan 13, 2025
1 parent 7bfbd83 commit c4b1d4c
Show file tree
Hide file tree
Showing 13 changed files with 208 additions and 200 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@ import BillingSettings from '@/components/pages/protected/organization/billing/b
import { pageStyles } from '../general-settings/page.styles'
import { useOrganization } from '@/hooks/useOrganization'
import { LoaderCircle } from 'lucide-react'
import { useGetOrganizationBillingQuery } from '@repo/codegen/src/schema'

const OrganizationContent = () => {
const { wrapper } = pageStyles()
const { currentOrg } = useOrganization()
const { currentOrgId } = useOrganization()
const [data] = useGetOrganizationBillingQuery({ pause: !currentOrgId, variables: { organizationId: currentOrgId } })

if (!currentOrg) {
if (data.fetching) {
return (
<div className="w-100 flex justify-center">
<LoaderCircle className="animate-spin" size={20} />
Expand All @@ -21,7 +23,7 @@ const OrganizationContent = () => {

return (
<>
{currentOrg?.personalOrg ? (
{data.data?.organization.personalOrg ? (
<div className={`flex items-center justify-center min-h-[50vh] text-center`}>
<h2 className="text-xl w-full max-w-2xl">
You're currently logged into your personal organization - you can switch into another organization you are a member of, or create an organization to use paid features of the Openlane
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
'use client'
import React, { useEffect, useRef, useState } from 'react'
import { useLoadScript } from '@react-google-maps/api'
import { Data, useLoadScript } from '@react-google-maps/api'
import { Button } from '@repo/ui/button'
import { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@repo/ui/dialog'
import { Input } from '@repo/ui/input'
import { Label } from '@repo/ui/label'
import { useUpdateOrganizationMutation } from '@repo/codegen/src/schema'
import { useGetOrganizationSettingQuery, useUpdateOrganizationMutation } from '@repo/codegen/src/schema'
import { useOrganization } from '@/hooks/useOrganization'
import useClickOutside from '@/hooks/useClickOutside'

const libraries: any = ['places']

const BillingContactDialog = () => {
const { currentOrgId, currentOrg } = useOrganization()
const { currentOrgId } = useOrganization()
const [setting] = useGetOrganizationSettingQuery({ pause: !currentOrgId, variables: { organizationId: currentOrgId } })
const [{ fetching: isSubmitting }, updateOrg] = useUpdateOrganizationMutation()
const wrapperRef = useClickOutside(() => setShowPredictions(false))
const { isLoaded } = useLoadScript({
Expand Down Expand Up @@ -105,13 +106,14 @@ const BillingContactDialog = () => {
}

useEffect(() => {
if (!currentOrg) {
if (!setting.data) {
return
}
setAddress(currentOrg?.setting?.billingAddress)
setFullName(currentOrg?.setting?.billingContact || '')
setAddress(setting.data.organization.setting?.billingAddress)

setFullName(setting.data.organization.setting?.billingContact || '')
return () => {}
}, [currentOrg])
}, [setting])

return (
<Dialog aria-describedby={undefined}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,23 @@ import { Input } from '@repo/ui/input'
import { Label } from '@repo/ui/label'
import React, { useEffect, useState } from 'react'
import { useOrganization } from '@/hooks/useOrganization'
import { useUpdateOrganizationMutation } from '@repo/codegen/src/schema'
import { useGetOrganizationSettingQuery, useUpdateOrganizationMutation } from '@repo/codegen/src/schema'
import { useToast } from '@repo/ui/use-toast'

const BillingEmailDialog = () => {
const { currentOrg, currentOrgId } = useOrganization()
const { currentOrgId } = useOrganization()
const [emailInput, setEmailInput] = useState('')
const [isOpen, setIsOpen] = useState(false)
const [{ fetching: isSubmitting }, updateOrg] = useUpdateOrganizationMutation()
const { toast } = useToast()

const [settingData] = useGetOrganizationSettingQuery({ pause: !currentOrgId, variables: { organizationId: currentOrgId } })

useEffect(() => {
if (isOpen) {
setEmailInput(currentOrg?.setting?.billingEmail || '')
setEmailInput(settingData.data?.organization.setting?.billingEmail || '')
}
}, [currentOrg, isOpen])
}, [settingData, isOpen])

const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,18 @@ import BillingContactDialog from './billing-contract-dialog'
import { useOrganization } from '@/hooks/useOrganization'
import { billingSettingsStyles } from './billing-settings.styles'
import { cn } from '@repo/ui/lib/utils'
import { useUpdateOrganizationMutation } from '@repo/codegen/src/schema'
import { useGetOrganizationSettingQuery, useUpdateOrganizationMutation } from '@repo/codegen/src/schema'

const BillingSettings: React.FC = () => {
const { panel, section, sectionContent, sectionTitle, emailText, paragraph, switchContainer, text } = billingSettingsStyles()
const { currentOrg, currentOrgId } = useOrganization()
const { currentOrgId } = useOrganization()
const [settingData] = useGetOrganizationSettingQuery({ pause: !currentOrgId, variables: { organizationId: currentOrgId } })
const [{ fetching: isSubmitting }, updateOrg] = useUpdateOrganizationMutation()
const billingAddress = settingData.data?.organization.setting?.billingAddress
const formattedAddress = [billingAddress?.line1, billingAddress?.city, billingAddress?.postalCode].filter(Boolean).join(', ')
const email = settingData.data?.organization.setting?.billingEmail || ''

const billingAddress = currentOrg?.setting?.billingAddress || {}
const formattedAddress = [billingAddress.line1, billingAddress.city, billingAddress.postalCode].filter(Boolean).join(', ')
const email = currentOrg?.setting?.billingEmail || ''

const [notificationsEnabled, setNotificationsEnabled] = useState<boolean>(currentOrg?.setting?.billingNotificationsEnabled || false)
const [notificationsEnabled, setNotificationsEnabled] = useState<boolean>(settingData.data?.organization.setting?.billingNotificationsEnabled || false)

const onToggleNotifications = async (checked: boolean) => {
setNotificationsEnabled(checked)
Expand Down Expand Up @@ -50,7 +50,7 @@ const BillingSettings: React.FC = () => {
<p className={cn(paragraph())}>
{formattedAddress}
<br />
{`${currentOrg?.setting?.billingAddress.country || ''}`}
{`${settingData.data?.organization.setting?.billingAddress?.country || ''}`}
</p>
</div>
<BillingContactDialog />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,21 @@ import { Badge } from '@repo/ui/badge'
import { formatDistanceToNowStrict, parseISO, isBefore } from 'date-fns'
import { CircleCheck, ExternalLink } from 'lucide-react'
import { useOrganization } from '@/hooks/useOrganization'
import { useGetOrganizationBillingQuery } from '@repo/codegen/src/schema'

const PricingPlan = () => {
const { currentOrg } = useOrganization()
const { currentOrgId } = useOrganization()

const [data] = useGetOrganizationBillingQuery({ pause: !currentOrgId, variables: { organizationId: currentOrgId } })

const subscription = data.data?.organization.orgSubscriptions?.[0] ?? {}

const subscription = currentOrg?.orgSubscriptions?.[0] ?? {}
// @ts-ignore TODO: MISSING TYPES FROM CODEGEN
const { expiresAt, subscriptionURL, active, productTier, productPrice = {}, features = [] } = subscription
const { amount: price, interval: priceInterval } = productPrice

const formattedExpiresDate = useMemo(() => {
if (!expiresAt || !active) return 'Expired'
if (!expiresAt && !active) return 'Expired'

try {
const expirationDate = parseISO(expiresAt)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
'use client'
import { useUpdateOrganizationMutation } from '@repo/codegen/src/schema'
import { useGetBillingEmailQuery, useUpdateOrganizationMutation } from '@repo/codegen/src/schema'
import { Input, InputRow } from '@repo/ui/input'
import { Panel, PanelHeader } from '@repo/ui/panel'
import { useForm } from 'react-hook-form'
Expand All @@ -14,8 +14,10 @@ import { useOrganization } from '@/hooks/useOrganization'
const OrganizationEmailForm = () => {
const [isSuccess, setIsSuccess] = useState(false)
const [{ fetching: isSubmitting }, updateOrg] = useUpdateOrganizationMutation()
const { currentOrg, currentOrgId } = useOrganization()
const { currentOrgId } = useOrganization()

const [setting] = useGetBillingEmailQuery({ pause: !currentOrgId, variables: { organizationId: currentOrgId } })
const billingEmail = setting.data?.organization.setting?.billingEmail
const formSchema = z.object({
email: z.string().email({ message: 'Invalid email address' }),
})
Expand All @@ -28,12 +30,12 @@ const OrganizationEmailForm = () => {
})

useEffect(() => {
if (currentOrg) {
if (billingEmail) {
form.reset({
email: currentOrg.setting?.billingEmail ?? undefined,
email: billingEmail ?? undefined,
})
}
}, [currentOrg])
}, [billingEmail])

const updateOrganization = async ({ email }: { email: string }) => {
await updateOrg({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,13 @@ import { z } from 'zod'
import { Button } from '@repo/ui/button'
import { useEffect, useState } from 'react'
import { RESET_SUCCESS_STATE_MS } from '@/constants'
import { useOrganization } from '@/hooks/useOrganization'

const OrganizationNameForm = () => {
const [isSuccess, setIsSuccess] = useState(false)
const [{ fetching: isSubmitting }, updateOrg] = useUpdateOrganizationMutation()
const { data: sessionData } = useSession()
const currentOrgId = sessionData?.user.activeOrganizationId
const [allOrgs] = useGetAllOrganizationsQuery({ pause: !sessionData })
const currentOrganization = allOrgs.data?.organizations.edges?.filter((org) => org?.node?.id === currentOrgId)[0]?.node
const { currentOrgId, allOrgs } = useOrganization()
const currentOrganization = allOrgs.filter((org) => org?.node?.id === currentOrgId)[0]?.node

const formSchema = z.object({
displayName: z.string().min(2, {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ interface AvatarUploadProps extends AvatarUploadVariants {

const AvatarUpload = ({ className }: AvatarUploadProps) => {
const { toast } = useToast()
const { currentOrg } = useOrganization()
const { allOrgs, currentOrgId } = useOrganization()

const [isCroppingModalOpen, setIsCroppingModalOpen] = useState(false)
const [crop, setCrop] = useState({ x: 0, y: 0 })
Expand All @@ -36,11 +36,12 @@ const AvatarUpload = ({ className }: AvatarUploadProps) => {
</>
)

const selectedOrg = allOrgs.filter((org) => org?.node?.id === currentOrgId).map((org) => org?.node)[0] || null

useEffect(() => {
if (currentOrg?.avatarRemoteURL) {
setAvatarUrl(currentOrg?.avatarRemoteURL)
}
}, [currentOrg])
const avatarRemoteURL = selectedOrg?.avatarRemoteURL
setAvatarUrl(avatarRemoteURL || null)
}, [selectedOrg])

const onDrop = useCallback((acceptedFiles: FileWithPath[]) => {
const file = acceptedFiles[0]
Expand Down Expand Up @@ -97,7 +98,7 @@ const AvatarUpload = ({ className }: AvatarUploadProps) => {
<div className={avatarPreview()}>
<Avatar variant="extra-large">
{avatarUrl && <AvatarImage src={avatarUrl} />}
<AvatarFallback>{currentOrg?.name?.substring(0, 2)}</AvatarFallback>
<AvatarFallback>{selectedOrg?.name?.substring(0, 2)}</AvatarFallback>
</Avatar>
</div>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { useSession } from 'next-auth/react'
import { switchOrganization } from '@/lib/user'
import { Loading } from '../loading/loading'
import { useOrganization } from '@/hooks/useOrganization'
import { useGetAllOrganizationMembersQuery } from '@repo/codegen/src/schema'

export const OrganizationSelector = () => {
const { data: sessionData, update: updateSession } = useSession()
Expand All @@ -25,8 +26,11 @@ export const OrganizationSelector = () => {
currentOrgName: '',
})

const { currentOrgId, allOrgs: orgs, currentOrg } = useOrganization()
const { currentOrgId } = useOrganization()

const [{ data: organizationsData, fetching, error }] = useGetAllOrganizationMembersQuery()
const orgs = organizationsData?.organizations?.edges ?? []
const currentOrg = orgs.filter((org) => org?.node?.id === currentOrgId)[0]?.node
const { container, logoWrapper, organizationLabel, organizationDropdown, allOrganizationsLink, popoverContent, searchWrapper, orgWrapper, orgInfo, orgTitle, orgSelect } =
organizationSelectorStyles()

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Panel, PanelHeader } from '@repo/ui/panel'
import { existingOrganizationsStyles } from './existing-organizations.styles'
import { useGetAllOrganizationsQuery } from '@repo/codegen/src/schema'
import { useGetAllOrganizationMembersQuery, useGetOrganizationMembersQuery } from '@repo/codegen/src/schema'
import { Avatar, AvatarFallback } from '@repo/ui/avatar'
import { Button } from '@repo/ui/button'
import { Tag } from '@repo/ui/tag'
Expand All @@ -11,19 +11,18 @@ import { useRouter } from 'next/navigation'
export const ExistingOrganizations = () => {
const { data: sessionData, update: updateSession } = useSession()
const currentOrg = sessionData?.user.activeOrganizationId
const { container, orgWrapper, orgInfo, orgSelect, orgTitle } =
existingOrganizationsStyles()
const [{ data, fetching, error }] = useGetAllOrganizationsQuery({
pause: !sessionData,
})

const { container, orgWrapper, orgInfo, orgSelect, orgTitle } = existingOrganizationsStyles()

const [{ data: organizations, fetching, error }] = useGetAllOrganizationMembersQuery()

const { push } = useRouter()

if (!data || fetching || error) {
if (!organizations || fetching || error) {
return null
}

const orgs =
data.organizations.edges?.filter((org) => !org?.node?.personalOrg) || []
const orgs = organizations?.organizations.edges?.filter((org) => !org?.node?.personalOrg) || []

if (orgs.length === 0) {
return null
Expand Down Expand Up @@ -62,9 +61,7 @@ export const ExistingOrganizations = () => {
<div key={org?.node?.id} className={`${orgWrapper()} group`}>
<div>
<Avatar variant="large">
<AvatarFallback>
{org?.node?.displayName.substring(0, 2)}
</AvatarFallback>
<AvatarFallback>{org?.node?.displayName.substring(0, 2)}</AvatarFallback>
</Avatar>
</div>
<div className={orgInfo()}>
Expand All @@ -73,11 +70,7 @@ export const ExistingOrganizations = () => {
</div>
{currentOrg !== org?.node?.id && (
<div className={orgSelect()}>
<Button
variant="filled"
size="md"
onClick={() => handleOrganizationSwitch(org?.node?.id)}
>
<Button variant="filled" size="md" onClick={() => handleOrganizationSwitch(org?.node?.id)}>
Select
</Button>
</div>
Expand Down
9 changes: 3 additions & 6 deletions apps/console/src/hooks/useOrganization.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,16 @@
import { useGetAllOrganizationsQuery } from '@repo/codegen/src/schema'
import { useSession } from 'next-auth/react'
import { useMemo } from 'react'

export const useOrganization = () => {
const { data: sessionData, status } = useSession()
const currentOrgId = useMemo(() => sessionData?.user?.activeOrganizationId, [sessionData])
const currentOrgId = sessionData?.user?.activeOrganizationId

const [allOrgs] = useGetAllOrganizationsQuery({
pause: status === 'loading' || !sessionData,
})
const organizations = allOrgs?.data?.organizations?.edges || []

const currentOrg = useMemo(() => {
return organizations.find((org) => org?.node?.id === currentOrgId)?.node
}, [organizations, currentOrgId])
// const currentOrg = organizations.find((org) => org?.node?.id === currentOrgId)?.node

return { currentOrgId, allOrgs: allOrgs?.data?.organizations?.edges || [], currentOrg }
return { currentOrgId, allOrgs: organizations }
}
Loading

0 comments on commit c4b1d4c

Please sign in to comment.