303 lines
10 KiB
TypeScript
303 lines
10 KiB
TypeScript
import { createContext, useContext, useMemo, useState } from 'react'
|
|
import type { ReactNode } from 'react'
|
|
import { useNavigate } from '@tanstack/react-router'
|
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
|
import type {
|
|
CreateAttendee,
|
|
CreateAttendeeResult,
|
|
CreateGroupWaitlistEntry,
|
|
GroupWaitlistEntryDto,
|
|
GroupWaitlistList,
|
|
} from '@gruperly/shared'
|
|
import { useToast } from '../../../components/ui'
|
|
import {
|
|
addToGroupWaitlist,
|
|
ApiError,
|
|
bulkCreateAttendees,
|
|
createAttendee,
|
|
getGroup,
|
|
getGroupAttendees,
|
|
} from '../../../lib/api'
|
|
import type { ParsedContactRow } from '../../../lib/file-parser'
|
|
|
|
export type BulkAttendeeRow = {
|
|
firstName: string
|
|
lastName: string
|
|
fullName: string
|
|
phone: string
|
|
email?: string
|
|
notes?: string
|
|
}
|
|
|
|
export type AddAttendeeTab = 'quick' | 'bulk'
|
|
|
|
type AddAttendeeContextValue = {
|
|
groupId: string
|
|
groupName: string | undefined
|
|
groupPending: boolean
|
|
attendeesTotal: number
|
|
capacity: number | null
|
|
activeTab: AddAttendeeTab
|
|
setActiveTab: (value: AddAttendeeTab) => void
|
|
cancelAddAttendee: () => void
|
|
isCapacityModalOpen: boolean
|
|
capacityPayload: CreateAttendee | null
|
|
closeCapacityModal: () => void
|
|
isBulkCapacityModalOpen: boolean
|
|
closeBulkCapacityModal: () => void
|
|
parsedContacts: ParsedContactRow[]
|
|
setParsedContacts: (contacts: ParsedContactRow[]) => void
|
|
removeParsedContact: (id: string) => void
|
|
fileName: string | null
|
|
setFileName: (name: string | null) => void
|
|
isParsingFile: boolean
|
|
setIsParsingFile: (value: boolean) => void
|
|
isDragging: boolean
|
|
setIsDragging: (value: boolean) => void
|
|
validRowsCount: number
|
|
invalidRowsCount: number
|
|
isSubmittingAttendee: boolean
|
|
isSubmittingForcedAttendee: boolean
|
|
isSubmittingWaitlistEntry: boolean
|
|
isSubmittingBulkImport: boolean
|
|
submitQuickAttendee: (payload: CreateAttendee) => void
|
|
submitForcedAttendee: () => void
|
|
submitWaitlistEntry: () => void
|
|
requestBulkImport: () => void
|
|
confirmBulkImportOverCapacity: () => void
|
|
}
|
|
|
|
const AddAttendeeContext = createContext<AddAttendeeContextValue | null>(null)
|
|
|
|
export function AddAttendeeProvider({ groupId, children }: { groupId: string; children: ReactNode }) {
|
|
const queryClient = useQueryClient()
|
|
const toast = useToast()
|
|
const navigate = useNavigate()
|
|
|
|
const [activeTab, setActiveTab] = useState<AddAttendeeTab>('quick')
|
|
const [isCapacityModalOpen, setIsCapacityModalOpen] = useState(false)
|
|
const [pendingCapacityPayload, setPendingCapacityPayload] = useState<CreateAttendee | null>(null)
|
|
const [isBulkCapacityModalOpen, setIsBulkCapacityModalOpen] = useState(false)
|
|
const [parsedContacts, setParsedContacts] = useState<ParsedContactRow[]>([])
|
|
const [fileName, setFileName] = useState<string | null>(null)
|
|
const [isParsingFile, setIsParsingFile] = useState(false)
|
|
const [isDragging, setIsDragging] = useState(false)
|
|
|
|
// Mismas query keys que el detalle del grupo: la data ya está en caché al navegar,
|
|
// así que la página se monta sin spinner ni fetch duplicado.
|
|
const groupQuery = useQuery({
|
|
queryKey: ['group', groupId],
|
|
queryFn: () => getGroup(groupId),
|
|
enabled: Boolean(groupId),
|
|
})
|
|
|
|
const attendeesQuery = useQuery({
|
|
queryKey: ['group-attendees', groupId],
|
|
queryFn: () => getGroupAttendees(groupId, 1, 100),
|
|
enabled: Boolean(groupId),
|
|
})
|
|
|
|
const group = groupQuery.data
|
|
const attendeesTotal = attendeesQuery.data?.pagination?.total ?? 0
|
|
const capacity = group?.capacity ?? null
|
|
|
|
const goBackToGroup = () => {
|
|
void navigate({ to: '/groups/$groupId', params: { groupId } })
|
|
}
|
|
|
|
const closeCapacityFlow = () => {
|
|
setPendingCapacityPayload(null)
|
|
setIsCapacityModalOpen(false)
|
|
}
|
|
|
|
const invalidateGroupQueries = () => {
|
|
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
|
void queryClient.invalidateQueries({ queryKey: ['group-waitlist', groupId] })
|
|
void queryClient.invalidateQueries({ queryKey: ['group', groupId] })
|
|
}
|
|
|
|
const handleCreateSuccess = (result: CreateAttendeeResult) => {
|
|
if (result.outcome === 'created') {
|
|
toast.success(`Miembro ${result.attendee.fullName} agregado con éxito.`)
|
|
} else {
|
|
toast.info(result.message)
|
|
}
|
|
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
|
goBackToGroup()
|
|
}
|
|
|
|
const createAttendeeMutation = useMutation({
|
|
mutationFn: (payload: CreateAttendee) => createAttendee(groupId, payload),
|
|
onMutate: (payload) => setPendingCapacityPayload(payload),
|
|
onSuccess: handleCreateSuccess,
|
|
onError: (err: Error) => {
|
|
if (err instanceof ApiError && err.problem?.code === 'group_capacity_reached') {
|
|
setIsCapacityModalOpen(true)
|
|
return
|
|
}
|
|
toast.error(err.message || 'Error al agregar miembro.')
|
|
},
|
|
})
|
|
|
|
const createAttendeeForceMutation = useMutation({
|
|
mutationFn: (payload: CreateAttendee) => createAttendee(groupId, payload, { allowOverflow: true }),
|
|
onSuccess: handleCreateSuccess,
|
|
onError: (err: Error) => {
|
|
toast.error(err.message || 'Error al agregar miembro.')
|
|
},
|
|
})
|
|
|
|
const addToWaitlistMutation = useMutation({
|
|
mutationFn: (payload: CreateGroupWaitlistEntry) => addToGroupWaitlist(groupId, payload),
|
|
onMutate: async (payload: CreateGroupWaitlistEntry) => {
|
|
await queryClient.cancelQueries({ queryKey: ['group-waitlist', groupId] })
|
|
const previousWaitlist = queryClient.getQueryData<GroupWaitlistList>(['group-waitlist', groupId])
|
|
|
|
if (previousWaitlist) {
|
|
const optimisticEntry: GroupWaitlistEntryDto = {
|
|
id: `temp-${Date.now()}`,
|
|
groupId,
|
|
fullName: `${payload.firstName} ${payload.lastName ?? ''}`.trim(),
|
|
phone: payload.phone,
|
|
email: payload.email || null,
|
|
notes: payload.notes ?? null,
|
|
status: 'PENDING',
|
|
createdAt: new Date().toISOString(),
|
|
updatedAt: new Date().toISOString(),
|
|
}
|
|
queryClient.setQueryData<GroupWaitlistList>(['group-waitlist', groupId], {
|
|
data: [optimisticEntry, ...previousWaitlist.data],
|
|
pagination: {
|
|
...previousWaitlist.pagination,
|
|
total: previousWaitlist.pagination.total + 1,
|
|
},
|
|
})
|
|
}
|
|
|
|
return { previousWaitlist }
|
|
},
|
|
onSuccess: (entry) => {
|
|
toast.info(`${entry.fullName} fue agregado a la lista de espera del grupo.`)
|
|
invalidateGroupQueries()
|
|
goBackToGroup()
|
|
},
|
|
onError: (err: Error, _payload, context) => {
|
|
if (context?.previousWaitlist) {
|
|
queryClient.setQueryData<GroupWaitlistList>(['group-waitlist', groupId], context.previousWaitlist)
|
|
}
|
|
if (err instanceof ApiError && err.problem?.code === 'already_waitlisted') {
|
|
toast.info('Este número ya está en la lista de espera del grupo.')
|
|
} else {
|
|
toast.error(err.message || 'Error al agregar a la lista de espera.')
|
|
}
|
|
closeCapacityFlow()
|
|
},
|
|
})
|
|
|
|
const bulkImportMutation = useMutation({
|
|
mutationFn: (rows: BulkAttendeeRow[]) => bulkCreateAttendees(groupId, { attendees: rows }),
|
|
onSuccess: (res) => {
|
|
toast.success(res.message)
|
|
setParsedContacts([])
|
|
setFileName(null)
|
|
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
|
goBackToGroup()
|
|
},
|
|
onError: (err: Error) => {
|
|
toast.error(err.message || 'Error al importar miembros.')
|
|
},
|
|
})
|
|
|
|
const validRows: BulkAttendeeRow[] = useMemo(
|
|
() =>
|
|
parsedContacts
|
|
.filter((contact) => contact.isValid)
|
|
.map((contact) => ({
|
|
firstName: contact.firstName,
|
|
lastName: contact.lastName,
|
|
fullName: contact.fullName,
|
|
phone: contact.phone,
|
|
email: contact.email || undefined,
|
|
notes: contact.notes || undefined,
|
|
})),
|
|
[parsedContacts],
|
|
)
|
|
|
|
const runBulkImport = () => {
|
|
if (validRows.length === 0) {
|
|
toast.error('No hay miembros válidos para importar.')
|
|
return
|
|
}
|
|
bulkImportMutation.mutate(validRows)
|
|
}
|
|
|
|
const requestBulkImport = () => {
|
|
if (validRows.length === 0) {
|
|
toast.error('No hay miembros válidos para importar.')
|
|
return
|
|
}
|
|
if (capacity != null && attendeesTotal + validRows.length > capacity) {
|
|
setIsBulkCapacityModalOpen(true)
|
|
return
|
|
}
|
|
runBulkImport()
|
|
}
|
|
|
|
const value: AddAttendeeContextValue = {
|
|
groupId,
|
|
groupName: group?.name,
|
|
groupPending: groupQuery.isPending,
|
|
attendeesTotal,
|
|
capacity,
|
|
activeTab,
|
|
setActiveTab,
|
|
cancelAddAttendee: goBackToGroup,
|
|
isCapacityModalOpen,
|
|
capacityPayload: pendingCapacityPayload,
|
|
closeCapacityModal: closeCapacityFlow,
|
|
isBulkCapacityModalOpen,
|
|
closeBulkCapacityModal: () => setIsBulkCapacityModalOpen(false),
|
|
parsedContacts,
|
|
setParsedContacts,
|
|
removeParsedContact: (id) => setParsedContacts((prev) => prev.filter((c) => c.id !== id)),
|
|
fileName,
|
|
setFileName,
|
|
isParsingFile,
|
|
setIsParsingFile,
|
|
isDragging,
|
|
setIsDragging,
|
|
validRowsCount: validRows.length,
|
|
invalidRowsCount: parsedContacts.length - validRows.length,
|
|
isSubmittingAttendee: createAttendeeMutation.isPending,
|
|
isSubmittingForcedAttendee: createAttendeeForceMutation.isPending,
|
|
isSubmittingWaitlistEntry: addToWaitlistMutation.isPending,
|
|
isSubmittingBulkImport: bulkImportMutation.isPending,
|
|
submitQuickAttendee: (payload) => createAttendeeMutation.mutate(payload),
|
|
submitForcedAttendee: () => {
|
|
if (pendingCapacityPayload) {
|
|
createAttendeeForceMutation.mutate({ ...pendingCapacityPayload })
|
|
}
|
|
},
|
|
submitWaitlistEntry: () => {
|
|
if (pendingCapacityPayload) {
|
|
addToWaitlistMutation.mutate({ ...pendingCapacityPayload })
|
|
}
|
|
},
|
|
requestBulkImport,
|
|
confirmBulkImportOverCapacity: () => {
|
|
setIsBulkCapacityModalOpen(false)
|
|
runBulkImport()
|
|
},
|
|
}
|
|
|
|
return <AddAttendeeContext.Provider value={value}>{children}</AddAttendeeContext.Provider>
|
|
}
|
|
|
|
export function useAddAttendee() {
|
|
const context = useContext(AddAttendeeContext)
|
|
if (!context) {
|
|
throw new Error('useAddAttendee debe usarse dentro de <AddAttendeeProvider>')
|
|
}
|
|
return context
|
|
}
|