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:
@@ -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