feat: un miembro puede pertenecer a más de un grupo
- Nuevo modelo `Person` (`people`): contacto y notas por profe, con teléfono único (índice parcial `people_owner_phone_key`). `Attendee` pasa a ser la membresía (`group_id` + `person_id`, único por grupo). - La cuenta de la app de alumnos se vincula a la persona (`student_account_people`): una sola cuenta ve todos sus grupos. - Migración unifica attendees del mismo profe y teléfono, y fusiona sus cuentas de alumno (conserva la usada más recientemente). - `POST /groups/:gid/attendees/:aid/add-to-group` y `GET /people/lookup` para detectar personas existentes al cargar; el alta responde `409 person_exists` y acepta `personId`. Bulk, lista de espera y preinscripciones vinculan solas. - El límite del plan cuenta personas con al menos un grupo activo. - Web: "Agregar a otro grupo", sección "También está en" en la ficha y aviso "Ya tenés a esta persona" en el alta individual. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useId, useRef, useState } from 'react'
|
||||
import type { KeyboardEvent, RefObject } from 'react'
|
||||
import { Ellipsis, MoveRight, Pause, Pencil, UserMinus } from 'lucide-react'
|
||||
import { Ellipsis, MoveRight, Pause, Pencil, UserMinus, UserPlus } from 'lucide-react'
|
||||
import { useToast } from '../../components/ui'
|
||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||
|
||||
@@ -15,7 +15,7 @@ export function AttendeeActionsMenu({
|
||||
* when it closes. */
|
||||
triggerRef: RefObject<HTMLButtonElement | null>
|
||||
}) {
|
||||
const { beginContactEdit, openRemoveDialog, openChangeGroupDialog } = useAttendeeDetail()
|
||||
const { beginContactEdit, openRemoveDialog, openChangeGroupDialog, openAddToGroupDialog } = useAttendeeDetail()
|
||||
const toast = useToast()
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
const menuRef = useRef<HTMLDivElement>(null)
|
||||
@@ -112,6 +112,18 @@ export function AttendeeActionsMenu({
|
||||
<MoveRight className="size-4 shrink-0 text-secondary" aria-hidden="true" />
|
||||
Cambiar de grupo
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
className={ITEM_CLASS}
|
||||
onClick={() => {
|
||||
close()
|
||||
openAddToGroupDialog()
|
||||
}}
|
||||
>
|
||||
<UserPlus className="size-4 shrink-0 text-secondary" aria-hidden="true" />
|
||||
Agregar a otro grupo
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
|
||||
@@ -6,6 +6,8 @@ type AttendeeContactFormProps = {
|
||||
phone: string
|
||||
email: string
|
||||
error: string | null
|
||||
/** Aviso cuando la persona está en otros grupos: el cambio aplica en todos. */
|
||||
sharedNote?: string | null
|
||||
isSaving: boolean
|
||||
onPhoneChange: (value: string) => void
|
||||
onEmailChange: (value: string) => void
|
||||
@@ -17,6 +19,7 @@ export function AttendeeContactForm({
|
||||
phone,
|
||||
email,
|
||||
error,
|
||||
sharedNote,
|
||||
isSaving,
|
||||
onPhoneChange,
|
||||
onEmailChange,
|
||||
@@ -46,6 +49,7 @@ export function AttendeeContactForm({
|
||||
aria-describedby={error ? 'contact-error' : undefined}
|
||||
/>
|
||||
</ContactInput>
|
||||
{sharedNote ? <p className="text-xs text-secondary">{sharedNote}</p> : null}
|
||||
{error ? (
|
||||
<p id="contact-error" role="alert" className="text-sm text-danger-fg">
|
||||
{error}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Mail, Phone } from 'lucide-react'
|
||||
import { ApiError } from '../../lib/api'
|
||||
import { formatPhoneDisplay } from '../../lib/format'
|
||||
import { cn } from '../../lib/utils'
|
||||
import { AttendeeContactForm } from './AttendeeContactForm'
|
||||
@@ -43,8 +44,12 @@ export function AttendeeContactSection() {
|
||||
try {
|
||||
await saveAttendee({ phone, email })
|
||||
endContactEdit()
|
||||
} catch {
|
||||
setError('No pudimos guardar los cambios. Revisá tu conexión e intentá de nuevo.')
|
||||
} catch (err) {
|
||||
setError(
|
||||
err instanceof ApiError && err.problem?.code === 'person_phone_taken'
|
||||
? 'Ese teléfono ya es de otra persona que tenés registrada.'
|
||||
: 'No pudimos guardar los cambios. Revisá tu conexión e intentá de nuevo.',
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,6 +74,11 @@ export function AttendeeContactSection() {
|
||||
phone={phone}
|
||||
email={email}
|
||||
error={error}
|
||||
sharedNote={
|
||||
attendee.otherGroups.length > 0
|
||||
? 'El cambio se aplica en todos sus grupos.'
|
||||
: null
|
||||
}
|
||||
isSaving={isUpdatingAttendee}
|
||||
onPhoneChange={(value) => {
|
||||
setPhone(value)
|
||||
|
||||
@@ -11,6 +11,7 @@ import type {
|
||||
} from '@gruperly/shared'
|
||||
import { useToast } from '../../components/ui'
|
||||
import {
|
||||
addAttendeeToGroup,
|
||||
ApiError,
|
||||
getAttendeeHistory,
|
||||
getGroup,
|
||||
@@ -44,16 +45,22 @@ type AttendeeDetailContextValue = {
|
||||
closeRemoveDialog: () => void
|
||||
confirmRemoveAttendee: (promoteFromWaitlist: boolean) => void
|
||||
isSubmittingRemoval: boolean
|
||||
isChangeGroupDialogOpen: boolean
|
||||
/** Qué diálogo de grupo está abierto: "Cambiar de grupo" o "Agregar a otro grupo". */
|
||||
groupDialogMode: GroupDialogMode | null
|
||||
openChangeGroupDialog: () => void
|
||||
closeChangeGroupDialog: () => void
|
||||
openAddToGroupDialog: () => void
|
||||
closeGroupDialog: () => void
|
||||
/** Grupos del profe (incluye el actual); se piden al abrir el diálogo. */
|
||||
groups: GroupListItem[]
|
||||
groupsPending: boolean
|
||||
moveToGroup: (targetGroupId: string) => void
|
||||
isMovingAttendee: boolean
|
||||
addToGroup: (targetGroupId: string) => void
|
||||
isAddingToGroup: boolean
|
||||
}
|
||||
|
||||
export type GroupDialogMode = 'move' | 'add'
|
||||
|
||||
const AttendeeDetailContext = createContext<AttendeeDetailContextValue | null>(null)
|
||||
|
||||
export function AttendeeDetailProvider({
|
||||
@@ -69,7 +76,7 @@ export function AttendeeDetailProvider({
|
||||
const queryClient = useQueryClient()
|
||||
const toast = useToast()
|
||||
const [isRemoveDialogOpen, setIsRemoveDialogOpen] = useState(false)
|
||||
const [isChangeGroupDialogOpen, setIsChangeGroupDialogOpen] = useState(false)
|
||||
const [groupDialogMode, setGroupDialogMode] = useState<GroupDialogMode | null>(null)
|
||||
const [isEditingContact, setIsEditingContact] = useState(false)
|
||||
|
||||
const groupQuery = useQuery({
|
||||
@@ -91,7 +98,9 @@ export function AttendeeDetailProvider({
|
||||
['group-attendee', groupId, attendeeId],
|
||||
(current) => (current ? { ...current, ...updated } : current),
|
||||
)
|
||||
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
||||
// Los datos son de la persona: cambian también en sus otros grupos.
|
||||
void queryClient.invalidateQueries({ queryKey: ['group-attendees'] })
|
||||
void queryClient.invalidateQueries({ queryKey: ['group-attendee'] })
|
||||
},
|
||||
})
|
||||
|
||||
@@ -127,7 +136,7 @@ export function AttendeeDetailProvider({
|
||||
const groupsQuery = useQuery({
|
||||
queryKey: ['groups'],
|
||||
queryFn: getGroups,
|
||||
enabled: isChangeGroupDialogOpen,
|
||||
enabled: groupDialogMode !== null,
|
||||
})
|
||||
const groups = groupsQuery.data?.data ?? []
|
||||
|
||||
@@ -142,7 +151,7 @@ export function AttendeeDetailProvider({
|
||||
}
|
||||
void queryClient.invalidateQueries({ queryKey: ['groups'] })
|
||||
void queryClient.invalidateQueries({ queryKey: ['attention'] })
|
||||
setIsChangeGroupDialogOpen(false)
|
||||
setGroupDialogMode(null)
|
||||
// La ficha vive bajo el grupo: pasa a la URL del grupo nuevo sin dejar la
|
||||
// vieja en el historial (ya no existe).
|
||||
void navigate({
|
||||
@@ -156,13 +165,38 @@ export function AttendeeDetailProvider({
|
||||
if (code === 'group_capacity_reached') {
|
||||
toast.error('Ese grupo alcanzó su cupo. Elegí otro o liberá un lugar primero.')
|
||||
} else if (code === 'attendee_already_registered') {
|
||||
toast.error('En ese grupo ya hay un miembro con el mismo teléfono.')
|
||||
toast.error('Esta persona ya es miembro de ese grupo.')
|
||||
} else {
|
||||
toast.error(err.message || 'No se pudo cambiar de grupo.')
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
const addToGroupMutation = useMutation({
|
||||
mutationFn: (targetGroupId: string) => addAttendeeToGroup(groupId, attendeeId, targetGroupId),
|
||||
onSuccess: (added, targetGroupId) => {
|
||||
const targetName = groups.find((group) => group.id === targetGroupId)?.name ?? 'otro grupo'
|
||||
toast.success(`${added.fullName} ahora también está en ${targetName}.`)
|
||||
void queryClient.invalidateQueries({ queryKey: ['group-attendees', targetGroupId] })
|
||||
void queryClient.invalidateQueries({ queryKey: ['group', targetGroupId] })
|
||||
// "También está en" de esta ficha (y la de sus otros grupos).
|
||||
void queryClient.invalidateQueries({ queryKey: ['group-attendee'] })
|
||||
void queryClient.invalidateQueries({ queryKey: ['groups'] })
|
||||
void queryClient.invalidateQueries({ queryKey: ['attention'] })
|
||||
setGroupDialogMode(null)
|
||||
},
|
||||
onError: (err: Error) => {
|
||||
const code = err instanceof ApiError ? err.problem?.code : undefined
|
||||
if (code === 'group_capacity_reached') {
|
||||
toast.error('Ese grupo alcanzó su cupo. Elegí otro o liberá un lugar primero.')
|
||||
} else if (code === 'attendee_already_registered') {
|
||||
toast.error('Esta persona ya es miembro de ese grupo.')
|
||||
} else {
|
||||
toast.error(err.message || 'No se pudo agregar al grupo.')
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
const value: AttendeeDetailContextValue = {
|
||||
groupId,
|
||||
groupName: groupQuery.data?.name,
|
||||
@@ -190,13 +224,16 @@ export function AttendeeDetailProvider({
|
||||
removeAttendee({ attendee: attendeeQuery.data, promoteFromWaitlist })
|
||||
},
|
||||
isSubmittingRemoval: isRemovingAttendee,
|
||||
isChangeGroupDialogOpen,
|
||||
openChangeGroupDialog: () => setIsChangeGroupDialogOpen(true),
|
||||
closeChangeGroupDialog: () => setIsChangeGroupDialogOpen(false),
|
||||
groupDialogMode,
|
||||
openChangeGroupDialog: () => setGroupDialogMode('move'),
|
||||
openAddToGroupDialog: () => setGroupDialogMode('add'),
|
||||
closeGroupDialog: () => setGroupDialogMode(null),
|
||||
groups,
|
||||
groupsPending: groupsQuery.isPending,
|
||||
moveToGroup: (targetGroupId) => moveMutation.mutate(targetGroupId),
|
||||
isMovingAttendee: moveMutation.isPending,
|
||||
addToGroup: (targetGroupId) => addToGroupMutation.mutate(targetGroupId),
|
||||
isAddingToGroup: addToGroupMutation.isPending,
|
||||
}
|
||||
|
||||
return <AttendeeDetailContext.Provider value={value}>{children}</AttendeeDetailContext.Provider>
|
||||
|
||||
@@ -10,6 +10,7 @@ import { AttendeeContactActions } from './AttendeeContactActions'
|
||||
import { AttendeeContactSection } from './AttendeeContactSection'
|
||||
import { AttendeeNotesSection } from './AttendeeNotesSection'
|
||||
import { AttendeePaymentsSection } from './AttendeePaymentsSection'
|
||||
import { OtherGroupsSection } from './OtherGroupsSection'
|
||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||
import { ChangeGroupDialog } from './ChangeGroupDialog'
|
||||
import { ConfirmRemoveAttendeeDialog } from './ConfirmRemoveAttendeeDialog'
|
||||
@@ -88,6 +89,7 @@ export function AttendeeDetailView() {
|
||||
|
||||
<div className="mt-6">
|
||||
<AttendeeContactSection />
|
||||
<OtherGroupsSection />
|
||||
<StudentAccessSection />
|
||||
<AttendeePaymentsSection />
|
||||
<AttendeeAttendanceSection />
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react'
|
||||
import type { RefObject } from 'react'
|
||||
import type { GroupListItem } from '@gruperly/shared'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { CalendarX, History, Loader2, MoveRight, Wallet } from 'lucide-react'
|
||||
import { CalendarCheck, CalendarX, History, Loader2, MoveRight, UserPlus, Wallet } from 'lucide-react'
|
||||
import { Button, Modal } from '../../components/ui'
|
||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||
|
||||
@@ -12,6 +12,9 @@ function isFull(group: GroupListItem): boolean {
|
||||
return group.capacity != null && group.attendeesCount >= group.capacity
|
||||
}
|
||||
|
||||
/* "Cambiar de grupo" (sale de este y entra al otro) y "Agregar a otro grupo"
|
||||
(queda en los dos) comparten el selector de destino; cambian el texto, las
|
||||
consecuencias y la acción. */
|
||||
export function ChangeGroupDialog({
|
||||
returnFocusRef,
|
||||
}: {
|
||||
@@ -24,18 +27,22 @@ export function ChangeGroupDialog({
|
||||
groupName,
|
||||
groups,
|
||||
groupsPending,
|
||||
isChangeGroupDialogOpen,
|
||||
closeChangeGroupDialog,
|
||||
groupDialogMode,
|
||||
closeGroupDialog,
|
||||
moveToGroup,
|
||||
isMovingAttendee,
|
||||
addToGroup,
|
||||
isAddingToGroup,
|
||||
} = useAttendeeDetail()
|
||||
const isOpen = groupDialogMode !== null
|
||||
const isAdd = groupDialogMode === 'add'
|
||||
|
||||
const [targetGroupId, setTargetGroupId] = useState('')
|
||||
const wasOpen = useRef(false)
|
||||
|
||||
// Cada apertura arranca sin destino elegido; al cerrar, el foco vuelve al "⋯".
|
||||
useEffect(() => {
|
||||
if (isChangeGroupDialogOpen) {
|
||||
if (isOpen) {
|
||||
wasOpen.current = true
|
||||
setTargetGroupId('')
|
||||
return
|
||||
@@ -43,36 +50,62 @@ export function ChangeGroupDialog({
|
||||
if (!wasOpen.current) return
|
||||
wasOpen.current = false
|
||||
returnFocusRef.current?.focus()
|
||||
}, [isChangeGroupDialogOpen, returnFocusRef])
|
||||
}, [isOpen, returnFocusRef])
|
||||
|
||||
if (!attendee) return null
|
||||
|
||||
const otherGroups = groups.filter((group) => group.id !== groupId)
|
||||
// Fuera el grupo actual y los grupos donde ya está. Al agregar, una baja
|
||||
// anterior (DROPPED) se puede reactivar; al mover, no (sería otra membresía).
|
||||
const blocked = new Set(
|
||||
attendee.otherGroups
|
||||
.filter((membership) => !isAdd || membership.status !== 'DROPPED')
|
||||
.map((membership) => membership.groupId),
|
||||
)
|
||||
const otherGroups = groups.filter((group) => group.id !== groupId && !blocked.has(group.id))
|
||||
const currentName = groupName ?? 'el grupo actual'
|
||||
const isSubmitting = isAdd ? isAddingToGroup : isMovingAttendee
|
||||
|
||||
const consequences: Consequence[] = [
|
||||
{
|
||||
key: 'historial',
|
||||
icon: History,
|
||||
text: 'Conserva su historial, sus cuotas y su acceso a la app de alumnos.',
|
||||
},
|
||||
{
|
||||
key: 'cuotas',
|
||||
icon: Wallet,
|
||||
text: `Las cuotas pendientes de ${currentName} siguen vigentes.`,
|
||||
},
|
||||
{
|
||||
key: 'faltas',
|
||||
icon: CalendarX,
|
||||
text: `Se cancelan las faltas avisadas para clases futuras de ${currentName}.`,
|
||||
},
|
||||
]
|
||||
const consequences: Consequence[] = isAdd
|
||||
? [
|
||||
{
|
||||
key: 'sigue',
|
||||
icon: CalendarCheck,
|
||||
text: `Sigue en ${currentName}: va a estar en los dos grupos.`,
|
||||
},
|
||||
{
|
||||
key: 'datos',
|
||||
icon: History,
|
||||
text: 'Comparte el contacto, las notas y el acceso a la app de alumnos.',
|
||||
},
|
||||
{
|
||||
key: 'cuotas',
|
||||
icon: Wallet,
|
||||
text: 'La asistencia y las cuotas se llevan por separado en cada grupo.',
|
||||
},
|
||||
]
|
||||
: [
|
||||
{
|
||||
key: 'historial',
|
||||
icon: History,
|
||||
text: 'Conserva su historial, sus cuotas y su acceso a la app de alumnos.',
|
||||
},
|
||||
{
|
||||
key: 'cuotas',
|
||||
icon: Wallet,
|
||||
text: `Las cuotas pendientes de ${currentName} siguen vigentes.`,
|
||||
},
|
||||
{
|
||||
key: 'faltas',
|
||||
icon: CalendarX,
|
||||
text: `Se cancelan las faltas avisadas para clases futuras de ${currentName}.`,
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<Modal
|
||||
isOpen={isChangeGroupDialogOpen}
|
||||
onClose={closeChangeGroupDialog}
|
||||
title="Cambiar de grupo"
|
||||
isOpen={isOpen}
|
||||
onClose={closeGroupDialog}
|
||||
title={isAdd ? 'Agregar a otro grupo' : 'Cambiar de grupo'}
|
||||
description={`${attendee.fullName}${groupName ? ` · ${groupName}` : ''}`}
|
||||
maxWidth="sm"
|
||||
>
|
||||
@@ -83,11 +116,15 @@ export function ChangeGroupDialog({
|
||||
</div>
|
||||
) : otherGroups.length === 0 ? (
|
||||
<p className="rounded-xl border border-border bg-primary-soft/30 px-4 py-3 text-sm text-foreground/70">
|
||||
No tenés otros grupos. Creá uno para poder mover a este miembro.
|
||||
{groups.length > 1
|
||||
? 'Ya es miembro de todos tus otros grupos.'
|
||||
: `No tenés otros grupos. Creá uno para poder ${isAdd ? 'agregar' : 'mover'} a este miembro.`}
|
||||
</p>
|
||||
) : (
|
||||
<label className="block">
|
||||
<span className="mb-1.5 block text-sm font-medium text-primary">Mover a</span>
|
||||
<span className="mb-1.5 block text-sm font-medium text-primary">
|
||||
{isAdd ? 'Agregar a' : 'Mover a'}
|
||||
</span>
|
||||
<select
|
||||
autoFocus
|
||||
value={targetGroupId}
|
||||
@@ -120,21 +157,23 @@ export function ChangeGroupDialog({
|
||||
</ul>
|
||||
|
||||
<div className="flex flex-col-reverse gap-2.5 border-t border-border pt-3 sm:flex-row sm:justify-end">
|
||||
<Button variant="ghost" onClick={closeChangeGroupDialog}>
|
||||
<Button variant="ghost" onClick={closeGroupDialog}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={() => moveToGroup(targetGroupId)}
|
||||
disabled={!targetGroupId || isMovingAttendee}
|
||||
onClick={() => (isAdd ? addToGroup(targetGroupId) : moveToGroup(targetGroupId))}
|
||||
disabled={!targetGroupId || isSubmitting}
|
||||
className="gap-2"
|
||||
>
|
||||
{isMovingAttendee ? (
|
||||
{isSubmitting ? (
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
) : isAdd ? (
|
||||
<UserPlus className="size-4" />
|
||||
) : (
|
||||
<MoveRight className="size-4" />
|
||||
)}
|
||||
<span>Cambiar de grupo</span>
|
||||
<span>{isAdd ? 'Agregar' : 'Cambiar de grupo'}</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
49
apps/web/src/features/attendee-detail/OtherGroupsSection.tsx
Normal file
49
apps/web/src/features/attendee-detail/OtherGroupsSection.tsx
Normal file
@@ -0,0 +1,49 @@
|
||||
import { Link } from '@tanstack/react-router'
|
||||
import { ChevronRight, Users } from 'lucide-react'
|
||||
import type { PersonMembership } from '@gruperly/shared'
|
||||
import { Badge, type BadgeVariant } from '../../components/ui'
|
||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||
import { Section } from './Section'
|
||||
|
||||
type StatusBadge = { label: string; variant: BadgeVariant }
|
||||
|
||||
const STATUS_BADGE: Record<PersonMembership['status'], StatusBadge | null> = {
|
||||
ACTIVE: null,
|
||||
PAUSED: { label: 'En pausa', variant: 'warning' },
|
||||
DROPPED: { label: 'Dado de baja', variant: 'neutral' },
|
||||
}
|
||||
|
||||
/* La misma persona en otros grupos del profe: cada fila abre su ficha en ese
|
||||
grupo (asistencia y cuotas son de cada grupo; el contacto es compartido). */
|
||||
export function OtherGroupsSection() {
|
||||
const { attendee } = useAttendeeDetail()
|
||||
if (!attendee || attendee.otherGroups.length === 0) return null
|
||||
|
||||
return (
|
||||
<Section title="También está en">
|
||||
<ul className="divide-y divide-border/60">
|
||||
{attendee.otherGroups.map((membership) => {
|
||||
const badge = STATUS_BADGE[membership.status]
|
||||
return (
|
||||
<li key={membership.attendeeId}>
|
||||
<Link
|
||||
to="/groups/$groupId/attendees/$attendeeId"
|
||||
params={{ groupId: membership.groupId, attendeeId: membership.attendeeId }}
|
||||
className="flex min-h-14 items-center gap-3 rounded-lg px-3 py-2 transition-colors hover:bg-primary-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
||||
>
|
||||
<Users className="size-4 shrink-0 text-secondary" aria-hidden="true" />
|
||||
<span className="min-w-0 flex-1 truncate text-sm text-primary">{membership.groupName}</span>
|
||||
{badge ? (
|
||||
<Badge variant={badge.variant} className="text-[11px]">
|
||||
{badge.label}
|
||||
</Badge>
|
||||
) : null}
|
||||
<ChevronRight className="size-4 shrink-0 text-secondary" aria-hidden="true" />
|
||||
</Link>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
</Section>
|
||||
)
|
||||
}
|
||||
@@ -123,6 +123,9 @@ export function AddAttendeeProvider({ groupId, children }: { groupId: string; ch
|
||||
toast.info(result.message)
|
||||
}
|
||||
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
||||
// Si era alguien de otro grupo, su ficha allá ahora lo muestra también acá.
|
||||
void queryClient.invalidateQueries({ queryKey: ['group-attendee'] })
|
||||
void queryClient.invalidateQueries({ queryKey: ['person-lookup'] })
|
||||
goBackToGroup()
|
||||
}
|
||||
|
||||
@@ -135,6 +138,13 @@ export function AddAttendeeProvider({ groupId, children }: { groupId: string; ch
|
||||
setIsCapacityModalOpen(true)
|
||||
return
|
||||
}
|
||||
// El aviso del formulario no llegó a mostrarse (o alguien la cargó recién):
|
||||
// refresca la búsqueda para que aparezca la opción de agregar a esa persona.
|
||||
if (err instanceof ApiError && err.problem?.code === 'person_exists') {
|
||||
void queryClient.invalidateQueries({ queryKey: ['person-lookup', groupId] })
|
||||
toast.info('Ya tenés registrada a una persona con este teléfono. Podés agregarla a este grupo.')
|
||||
return
|
||||
}
|
||||
toast.error(err.message || 'Error al agregar miembro.')
|
||||
},
|
||||
})
|
||||
|
||||
71
apps/web/src/features/groups/add/ExistingPersonNotice.tsx
Normal file
71
apps/web/src/features/groups/add/ExistingPersonNotice.tsx
Normal file
@@ -0,0 +1,71 @@
|
||||
import { UserCheck } from 'lucide-react'
|
||||
import type { PersonSummary } from '@gruperly/shared'
|
||||
import { Button } from '../../../components/ui'
|
||||
|
||||
type ExistingPersonNoticeProps = {
|
||||
person: PersonSummary
|
||||
/** La persona ya es miembro (no dado de baja) del grupo al que se está agregando. */
|
||||
alreadyInGroup: boolean
|
||||
isLinked: boolean
|
||||
onLink: () => void
|
||||
onUnlink: () => void
|
||||
onChangePhone: () => void
|
||||
}
|
||||
|
||||
/* El teléfono ya es de alguien que el profe tiene en otro grupo: en vez de
|
||||
crear un duplicado, ofrece sumar a esa misma persona. */
|
||||
export function ExistingPersonNotice({
|
||||
person,
|
||||
alreadyInGroup,
|
||||
isLinked,
|
||||
onLink,
|
||||
onUnlink,
|
||||
onChangePhone,
|
||||
}: ExistingPersonNoticeProps) {
|
||||
const groupNames = person.groups.map((group) => group.groupName).join(', ')
|
||||
|
||||
if (alreadyInGroup) {
|
||||
return (
|
||||
<div role="alert" className="mt-2 rounded-xl bg-danger-soft px-3 py-2.5 text-sm text-danger-fg">
|
||||
{person.fullName} ya es miembro de este grupo.
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div role="status" className="mt-2 rounded-xl border border-border bg-accent-soft/40 px-3 py-3 text-sm text-primary">
|
||||
<div className="flex items-start gap-2.5">
|
||||
<UserCheck className="mt-0.5 size-4 shrink-0 text-accent-fg" aria-hidden="true" />
|
||||
<p className="min-w-0">
|
||||
{isLinked ? (
|
||||
<>
|
||||
Vas a agregar a <strong>{person.fullName}</strong> a este grupo. Sus datos de contacto
|
||||
y notas son los mismos que en sus otros grupos.
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
Ya tenés a <strong>{person.fullName}</strong> con este teléfono
|
||||
{groupNames ? ` (en ${groupNames})` : ''}. ¿Es la misma persona?
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="mt-2.5 flex flex-wrap justify-end gap-2">
|
||||
{isLinked ? (
|
||||
<Button variant="ghost" onClick={onUnlink} size="sm">
|
||||
No es esta persona
|
||||
</Button>
|
||||
) : (
|
||||
<>
|
||||
<Button variant="ghost" onClick={onChangePhone} size="sm">
|
||||
Usar otro teléfono
|
||||
</Button>
|
||||
<Button variant="primary" onClick={onLink} size="sm">
|
||||
Sí, agregarla
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,19 +1,47 @@
|
||||
import { useState } from 'react'
|
||||
import { useRef, useState } from 'react'
|
||||
import { Check, Loader2 } from 'lucide-react'
|
||||
import { Button, Input, Label, useToast } from '../../../components/ui'
|
||||
import { useAddAttendee } from './AddAttendeeProvider'
|
||||
import { ExistingPersonNotice } from './ExistingPersonNotice'
|
||||
import { usePersonLookup } from './usePersonLookup'
|
||||
|
||||
export function QuickAddForm() {
|
||||
const { submitQuickAttendee, isSubmittingAttendee, cancelAddAttendee } = useAddAttendee()
|
||||
const { groupId, submitQuickAttendee, isSubmittingAttendee, cancelAddAttendee } = useAddAttendee()
|
||||
const toast = useToast()
|
||||
const [firstName, setFirstName] = useState('')
|
||||
const [lastName, setLastName] = useState('')
|
||||
const [phone, setPhone] = useState('')
|
||||
const [email, setEmail] = useState('')
|
||||
const [notes, setNotes] = useState('')
|
||||
const phoneRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
// El teléfono identifica a la persona: si ya la tenés en otro grupo, se suma
|
||||
// esa misma persona (con sus datos) en vez de crear un duplicado.
|
||||
const { person: existingPerson } = usePersonLookup(groupId, phone)
|
||||
const [linkedPersonId, setLinkedPersonId] = useState<string | null>(null)
|
||||
const linkedPerson = existingPerson && existingPerson.id === linkedPersonId ? existingPerson : null
|
||||
const alreadyInGroup = Boolean(
|
||||
existingPerson?.groups.some((group) => group.groupId === groupId && group.status !== 'DROPPED'),
|
||||
)
|
||||
// Con el teléfono de alguien que ya existe solo se puede vincular.
|
||||
const mustLink = Boolean(existingPerson) && !linkedPerson
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (alreadyInGroup) return
|
||||
if (linkedPerson) {
|
||||
submitQuickAttendee({
|
||||
firstName: linkedPerson.fullName,
|
||||
lastName: '',
|
||||
phone: phone.trim(),
|
||||
personId: linkedPerson.id,
|
||||
})
|
||||
return
|
||||
}
|
||||
if (mustLink) {
|
||||
toast.info('Ese teléfono ya es de una persona registrada: agregala o usá otro teléfono.')
|
||||
return
|
||||
}
|
||||
if (!firstName.trim() || !phone.trim()) {
|
||||
toast.error('Nombre y teléfono son obligatorios.')
|
||||
return
|
||||
@@ -33,7 +61,9 @@ export function QuickAddForm() {
|
||||
setPhone('')
|
||||
setEmail('')
|
||||
setNotes('')
|
||||
setLinkedPersonId(null)
|
||||
}
|
||||
const isLinked = Boolean(linkedPerson)
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||
@@ -44,8 +74,9 @@ export function QuickAddForm() {
|
||||
<Input
|
||||
id="quick-first-name"
|
||||
placeholder="Ej. Lucas"
|
||||
value={firstName}
|
||||
value={linkedPerson ? linkedPerson.fullName : firstName}
|
||||
onChange={(e) => setFirstName(e.target.value)}
|
||||
disabled={isLinked}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
@@ -56,8 +87,9 @@ export function QuickAddForm() {
|
||||
<Input
|
||||
id="quick-last-name"
|
||||
placeholder="Ej. González"
|
||||
value={lastName}
|
||||
value={isLinked ? '' : lastName}
|
||||
onChange={(e) => setLastName(e.target.value)}
|
||||
disabled={isLinked}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -69,13 +101,31 @@ export function QuickAddForm() {
|
||||
<Input
|
||||
id="quick-phone"
|
||||
placeholder="Ej. +54 9 11 2345-6789"
|
||||
ref={phoneRef}
|
||||
value={phone}
|
||||
onChange={(e) => setPhone(e.target.value)}
|
||||
onChange={(e) => {
|
||||
setPhone(e.target.value)
|
||||
setLinkedPersonId(null)
|
||||
}}
|
||||
required
|
||||
/>
|
||||
<p className="mt-1 text-[11px] text-foreground/50">
|
||||
Usado para contacto y validación de duplicados.
|
||||
</p>
|
||||
{existingPerson ? (
|
||||
<ExistingPersonNotice
|
||||
person={existingPerson}
|
||||
alreadyInGroup={alreadyInGroup}
|
||||
isLinked={isLinked}
|
||||
onLink={() => setLinkedPersonId(existingPerson.id)}
|
||||
onUnlink={() => setLinkedPersonId(null)}
|
||||
onChangePhone={() => {
|
||||
phoneRef.current?.focus()
|
||||
phoneRef.current?.select()
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<p className="mt-1 text-[11px] text-foreground/50">
|
||||
Usado para contacto y validación de duplicados.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
@@ -86,8 +136,9 @@ export function QuickAddForm() {
|
||||
id="quick-email"
|
||||
type="email"
|
||||
placeholder="alumno@ejemplo.com"
|
||||
value={email}
|
||||
value={linkedPerson ? (linkedPerson.email ?? '') : email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
disabled={isLinked}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -100,6 +151,7 @@ export function QuickAddForm() {
|
||||
placeholder="Ej. Nivel intermedio, trae materiales propios"
|
||||
value={notes}
|
||||
onChange={(e) => setNotes(e.target.value)}
|
||||
disabled={isLinked}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -117,7 +169,7 @@ export function QuickAddForm() {
|
||||
<Button
|
||||
variant="primary"
|
||||
type="submit"
|
||||
disabled={isSubmittingAttendee}
|
||||
disabled={isSubmittingAttendee || alreadyInGroup}
|
||||
className="w-full sm:w-auto"
|
||||
>
|
||||
{isSubmittingAttendee ? <Loader2 className="size-4 animate-spin" /> : <Check className="size-4" />}
|
||||
|
||||
29
apps/web/src/features/groups/add/usePersonLookup.ts
Normal file
29
apps/web/src/features/groups/add/usePersonLookup.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { lookupPerson } from '../../../lib/api'
|
||||
|
||||
const DEBOUNCE_MS = 400
|
||||
const MIN_DIGITS = 6
|
||||
|
||||
/* Mientras el profe escribe el teléfono: ¿ya es de una persona que tiene en
|
||||
otro grupo? Espera a que deje de tipear para no pedir en cada tecla. */
|
||||
export function usePersonLookup(groupId: string, phone: string) {
|
||||
const [debouncedPhone, setDebouncedPhone] = useState(phone.trim())
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => setDebouncedPhone(phone.trim()), DEBOUNCE_MS)
|
||||
return () => clearTimeout(timer)
|
||||
}, [phone])
|
||||
|
||||
const enabled = Boolean(groupId) && debouncedPhone.replace(/\D/g, '').length >= MIN_DIGITS
|
||||
const query = useQuery({
|
||||
queryKey: ['person-lookup', groupId, debouncedPhone],
|
||||
queryFn: () => lookupPerson(groupId, debouncedPhone),
|
||||
enabled,
|
||||
staleTime: 30_000,
|
||||
})
|
||||
|
||||
// Mientras el valor tipeado no coincide con el consultado, no hay veredicto.
|
||||
const settled = enabled && debouncedPhone === phone.trim()
|
||||
return { person: settled ? (query.data ?? null) : null }
|
||||
}
|
||||
Reference in New Issue
Block a user