feat: filtro de grupo en cobros con cuotas pendientes por grupo

- El listado de grupos devuelve `unpaidPaymentsCount` (PENDING y OVERDUE).
- Cobros: nuevo selector de grupo (GroupFilter) junto a los filtros de estado;
  con un grupo filtrado no se repite su nombre en cada card.
- Sheet: entra deslizando desde abajo en mobile (salvo reduced motion).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jose Selesan
2026-11-02 14:59:33 -03:00
parent b6f22ae67d
commit d397e9663c
12 changed files with 326 additions and 34 deletions

View File

@@ -21,13 +21,15 @@ type ListGroupsDeps = {
now?: Date;
};
const OCCUPANCY_COUNT_INCLUDE = {
const LIST_COUNT_INCLUDE = {
_count: {
select: {
// Group members. No status filter, same as the detail page counts.
attendees: true,
// Waitlist: the ones still waiting for a spot (the reviewed ones drop out).
waitlist: { where: { status: 'PENDING' as const } },
// Payments still to collect: the ones pending and the overdue ones.
payments: { where: { status: { in: ['PENDING' as const, 'OVERDUE' as const] } } },
},
},
} satisfies Prisma.GroupInclude;
@@ -49,7 +51,7 @@ export class ListGroups {
// time zone (or the server's if it doesn't come along).
const records: GroupListRecord[] = await db.group.findMany({
where,
include: OCCUPANCY_COUNT_INCLUDE,
include: LIST_COUNT_INCLUDE,
});
const timeZone = query.timeZone ?? DEFAULT_TIME_ZONE;

View File

@@ -26,9 +26,10 @@ export type GroupRecord = {
/* The listing adds the occupancy counters to each group so the card can show
them without asking for one endpoint per group. They come from the `_count` of
the same query: all the members (same as the detail page counts) and only the
waitlist entries still waiting for a spot (PENDING). */
waitlist entries still waiting for a spot (PENDING), plus the payments still
to collect (PENDING and OVERDUE). */
export type GroupListRecord = GroupRecord & {
_count?: { attendees: number; waitlist: number };
_count?: { attendees: number; waitlist: number; payments?: number };
};
export function toGroupDto(record: GroupRecord): GroupDto {
@@ -56,6 +57,7 @@ export function toGroupListItemDto(record: GroupListRecord): GroupListItem {
...toGroupDto(record),
attendeesCount: record._count?.attendees ?? 0,
waitlistCount: record._count?.waitlist ?? 0,
unpaidPaymentsCount: record._count?.payments ?? 0,
};
}

View File

@@ -61,7 +61,7 @@ describe('groups routes', () => {
it('lists groups scoped to the current user', async () => {
prisma.group.findMany.mockResolvedValue([
{ ...group, _count: { attendees: 4, waitlist: 1 } },
{ ...group, _count: { attendees: 4, waitlist: 1, payments: 3 } },
]);
prisma.group.count.mockResolvedValue(1);
@@ -76,6 +76,7 @@ describe('groups routes', () => {
updatedAt: group.updatedAt.toISOString(),
attendeesCount: 4,
waitlistCount: 1,
unpaidPaymentsCount: 3,
},
],
pagination: { page: 1, pageSize: 10, total: 1, totalPages: 1 },
@@ -89,7 +90,11 @@ describe('groups routes', () => {
where,
include: {
_count: {
select: { attendees: true, waitlist: { where: { status: 'PENDING' } } },
select: {
attendees: true,
waitlist: { where: { status: 'PENDING' } },
payments: { where: { status: { in: ['PENDING', 'OVERDUE'] } } },
},
},
},
});

View File

@@ -12,7 +12,8 @@ export type SheetProps = {
}
/* Bottom sheet on mobile (anchored to the bottom edge, above the home
indicator) and a centered dialog from `sm` up. Escape and the backdrop close
indicator, sliding up unless reduced motion is on) and a centered dialog
from `sm` up. Escape and the backdrop close
it; focus moves into the panel on open and goes back where it was on close. */
export function Sheet({ isOpen, onClose, title, description, children, className }: SheetProps) {
const titleId = useId()
@@ -50,7 +51,7 @@ export function Sheet({ isOpen, onClose, title, description, children, className
ref={panelRef}
tabIndex={-1}
className={cn(
'relative max-h-[90dvh] w-full overflow-y-auto rounded-t-2xl border border-border bg-surface p-5 pb-[calc(1.25rem+env(safe-area-inset-bottom))] shadow-2xl outline-none animate-fade-in sm:max-w-md sm:rounded-2xl sm:pb-5',
'relative max-h-[90dvh] w-full overflow-y-auto rounded-t-2xl border border-border bg-surface p-5 pb-[calc(1.25rem+env(safe-area-inset-bottom))] shadow-2xl outline-none animate-sheet-up motion-reduce:animate-fade-in sm:animate-fade-in sm:max-w-md sm:rounded-2xl sm:pb-5',
className,
)}
>

View File

@@ -0,0 +1,19 @@
import { Link } from '@tanstack/react-router'
import { Plus } from 'lucide-react'
import { cn } from '../../lib/utils'
/* Pie del selector de grupos de Cobros: lleva al alta de grupo. */
export function CreateGroupLink({ compact = false }: { compact?: boolean }) {
return (
<Link
to="/groups/new"
className={cn(
'flex items-center gap-2 rounded-xl px-3 text-sm font-medium text-accent-fg hover:bg-primary-soft',
compact ? 'min-h-10' : 'min-h-11',
)}
>
<Plus className="size-4" aria-hidden="true" />
Crear un grupo nuevo
</Link>
)
}

View File

@@ -0,0 +1,116 @@
import { ChevronDown, Users } from 'lucide-react'
import { useCallback, useEffect, useRef, useState } from 'react'
import { Sheet } from '../../components/ui'
import { cn } from '../../lib/utils'
import { CreateGroupLink } from './CreateGroupLink'
import { GroupOptionList } from './GroupOptionList'
import { usePayments } from './PaymentsProvider'
/* Mismo corte que la fila de filtros: debajo de `lg` la fila scrollea en
horizontal y un popover absoluto quedaría recortado, así que ahí va el sheet. */
const DESKTOP_QUERY = '(min-width: 1024px)'
function useIsDesktop() {
const [isDesktop, setIsDesktop] = useState(() => window.matchMedia(DESKTOP_QUERY).matches)
useEffect(() => {
const media = window.matchMedia(DESKTOP_QUERY)
const handleChange = () => setIsDesktop(media.matches)
media.addEventListener('change', handleChange)
return () => media.removeEventListener('change', handleChange)
}, [])
return isDesktop
}
/* Chip de grupo de la fila de filtros de Cobros: bottom sheet en mobile y
dropdown anclado al chip en desktop. */
export function GroupFilter() {
const { groups, groupId, setGroupId } = usePayments()
const [isOpen, setIsOpen] = useState(false)
const isDesktop = useIsDesktop()
const rootRef = useRef<HTMLDivElement>(null)
const chipRef = useRef<HTMLButtonElement>(null)
const selected = groups.find((group) => group.id === groupId)
// Estable: el `Sheet` vuelve a correr su efecto (y mueve el foco) si cambia `onClose`.
const close = useCallback(() => setIsOpen(false), [])
// El dropdown cierra con clic afuera y con Escape; el sheet resuelve ambos solo.
useEffect(() => {
if (!isOpen || !isDesktop) return
const handlePointerDown = (event: PointerEvent) => {
if (!rootRef.current?.contains(event.target as Node)) setIsOpen(false)
}
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key !== 'Escape') return
setIsOpen(false)
chipRef.current?.focus()
}
document.addEventListener('pointerdown', handlePointerDown)
document.addEventListener('keydown', handleKeyDown)
return () => {
document.removeEventListener('pointerdown', handlePointerDown)
document.removeEventListener('keydown', handleKeyDown)
}
}, [isOpen, isDesktop])
const handleSelect = (next: string | null) => {
setIsOpen(false)
// En mobile el `Sheet` devuelve el foco al chip al cerrarse.
if (isDesktop) chipRef.current?.focus()
if (next !== groupId) setGroupId(next)
}
const list = (
<GroupOptionList groups={groups} selectedId={groupId} onSelect={handleSelect} compact={isDesktop} />
)
return (
<div ref={rootRef} className="relative shrink-0">
<button
ref={chipRef}
type="button"
aria-haspopup="listbox"
aria-expanded={isOpen}
aria-label={`Grupo: ${selected?.name ?? 'Todos los grupos'}`}
onClick={() => setIsOpen((open) => !open)}
className={cn(
'flex items-center gap-1.5 rounded-full border px-3.5 py-1.5 text-sm font-medium transition-colors',
isOpen
? 'border-accent bg-accent-soft text-accent-fg'
: 'border-border bg-surface text-primary hover:border-accent/50',
selected && 'font-semibold',
)}
>
<Users className="size-4 shrink-0" aria-hidden="true" />
<span className="max-w-[12rem] truncate">{selected?.name ?? 'Todos los grupos'}</span>
<ChevronDown
className={cn(
'size-4 shrink-0 transition-transform motion-reduce:transition-none',
isOpen && 'rotate-180',
)}
aria-hidden="true"
/>
</button>
{isDesktop ? (
isOpen ? (
<div className="absolute left-0 top-full z-40 mt-1.5 w-80 animate-fade-in rounded-xl border border-border bg-surface p-1.5 shadow-lg">
<p className="px-2.5 py-1.5 text-xs font-medium text-foreground/50">Grupos</p>
<div className="max-h-80 overflow-y-auto">{list}</div>
<div className="mt-1.5 border-t border-border pt-1.5">
<CreateGroupLink compact />
</div>
</div>
) : null
) : (
<Sheet isOpen={isOpen} onClose={close} title="Elegir grupo">
{list}
<div className="mt-3 border-t border-border pt-2">
<CreateGroupLink />
</div>
</Sheet>
)}
</div>
)
}

View File

@@ -0,0 +1,147 @@
import type { GroupListItem } from '@gruperly/shared'
import { Check, LayoutGrid } from 'lucide-react'
import { useEffect, useRef, useState, type KeyboardEvent } from 'react'
import { Avatar, Badge } from '../../components/ui'
import { formatPrice } from '../../lib/format'
import { cn } from '../../lib/utils'
type GroupOptionListProps = {
groups: GroupListItem[]
selectedId: string | null
onSelect: (groupId: string | null) => void
/** Versión del dropdown de desktop: filas y avatares más chicos. */
compact?: boolean
}
type Option = {
id: string | null
name: string
subtitle: string
unpaid: number
}
function plural(count: number, singular: string, pluralForm: string): string {
return `${count} ${count === 1 ? singular : pluralForm}`
}
function groupSubtitle(group: GroupListItem): string {
const members = plural(group.attendeesCount, 'miembro', 'miembros')
if (group.price == null) return members
const unit = group.billingType === 'PER_CLASS' ? '/clase' : '/mes'
return `${members} · ${formatPrice(group.price)}${unit}`
}
/* Lista de grupos del filtro de Cobros, compartida por el bottom sheet y el
dropdown. Foco "roving": la opción activa es la única tabulable y las flechas
mueven el foco real, así el lector de pantalla lee cada opción. */
export function GroupOptionList({ groups, selectedId, onSelect, compact = false }: GroupOptionListProps) {
const options: Option[] = [
{
id: null,
name: 'Todos los grupos',
subtitle: plural(groups.length, 'grupo', 'grupos'),
unpaid: groups.reduce((sum, group) => sum + group.unpaidPaymentsCount, 0),
},
...groups.map((group) => ({
id: group.id,
name: group.name,
subtitle: groupSubtitle(group),
unpaid: group.unpaidPaymentsCount,
})),
]
const selectedIndex = Math.max(
0,
options.findIndex((option) => option.id === selectedId),
)
const [activeIndex, setActiveIndex] = useState(selectedIndex)
const optionRefs = useRef<(HTMLLIElement | null)[]>([])
// Al abrir, el foco va a la opción elegida. Un frame después: el `Sheet`
// enfoca su panel en su propio efecto, que corre después de este.
useEffect(() => {
const frame = requestAnimationFrame(() => {
optionRefs.current[selectedIndex]?.focus()
})
return () => cancelAnimationFrame(frame)
// Solo al montar: después el foco lo mueve el teclado.
}, [])
const moveTo = (index: number) => {
setActiveIndex(index)
optionRefs.current[index]?.focus()
}
const handleKeyDown = (event: KeyboardEvent) => {
const last = options.length - 1
if (event.key === 'ArrowDown') {
event.preventDefault()
moveTo(Math.min(activeIndex + 1, last))
} else if (event.key === 'ArrowUp') {
event.preventDefault()
moveTo(Math.max(activeIndex - 1, 0))
} else if (event.key === 'Home') {
event.preventDefault()
moveTo(0)
} else if (event.key === 'End') {
event.preventDefault()
moveTo(last)
} else if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault()
onSelect(options[activeIndex]?.id ?? null)
}
}
return (
<ul role="listbox" aria-label="Grupos" onKeyDown={handleKeyDown} className="space-y-0.5">
{options.map((option, index) => {
const isSelected = option.id === selectedId
return (
<li
key={option.id ?? 'all'}
ref={(node) => {
optionRefs.current[index] = node
}}
role="option"
aria-selected={isSelected}
tabIndex={index === activeIndex ? 0 : -1}
onClick={() => onSelect(option.id)}
onFocus={() => setActiveIndex(index)}
className={cn(
'flex cursor-pointer items-center gap-3 rounded-xl px-3 outline-none transition-colors hover:bg-primary-soft focus-visible:bg-primary-soft focus-visible:ring-2 focus-visible:ring-accent/30',
compact ? 'min-h-11 py-1.5' : 'min-h-14 py-2',
isSelected && 'bg-accent-soft hover:bg-accent-soft focus-visible:bg-accent-soft',
)}
>
{option.id === null ? (
<span
className={cn(
'flex shrink-0 items-center justify-center rounded-xl bg-primary-soft text-primary',
compact ? 'size-8' : 'size-9',
)}
aria-hidden="true"
>
<LayoutGrid className="size-4" />
</span>
) : (
<Avatar name={option.name} aria-hidden="true" className={cn(compact && 'size-8 text-xs')} />
)}
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-semibold text-primary">{option.name}</span>
<span className="block truncate text-xs text-foreground/60">{option.subtitle}</span>
</span>
{option.unpaid > 0 ? (
<Badge variant="neutral" aria-label={plural(option.unpaid, 'cobro pendiente', 'cobros pendientes')}>
{option.unpaid}
</Badge>
) : null}
<Check
className={cn('size-4 shrink-0 text-accent', !isSelected && 'invisible')}
aria-hidden="true"
/>
</li>
)
})}
</ul>
)
}

View File

@@ -8,11 +8,13 @@ import { paymentDateLabel, paymentPeriodLabel, PAYMENT_STATUS_BADGE } from './co
type PaymentRowProps = {
payment: PaymentDto
/** Con un grupo filtrado el nombre del grupo sobra en cada card. */
showGroup: boolean
isRenewing: boolean
onRenew: (paymentId: string) => void
}
export function PaymentRow({ payment, isRenewing, onRenew }: PaymentRowProps) {
export function PaymentRow({ payment, showGroup, isRenewing, onRenew }: PaymentRowProps) {
const [copied, setCopied] = useState(false)
const canCopy = Boolean(payment.checkoutUrl)
const canRenew = !payment.checkoutUrl || payment.status === 'CANCELLED'
@@ -34,7 +36,9 @@ export function PaymentRow({ payment, isRenewing, onRenew }: PaymentRowProps) {
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-semibold text-primary">
{payment.attendeeName}
{showGroup ? (
<span className="ml-2 font-normal text-foreground/60">{payment.groupName}</span>
) : null}
</p>
<p className="mt-1 flex flex-wrap items-center gap-x-2 text-sm">
<span className="font-medium text-primary">

View File

@@ -1,4 +1,4 @@
import type { PaymentDto, PaymentQuery, PaymentStatus } from '@gruperly/shared'
import type { GroupListItem, PaymentDto, PaymentQuery, PaymentStatus } from '@gruperly/shared'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import type { ReactNode } from 'react'
import { createContext, useContext, useMemo, useState } from 'react'
@@ -29,7 +29,7 @@ type PaymentsContextValue = {
retry: () => void
renew: (paymentId: string) => void
isRenewing: (paymentId: string) => boolean
groups: { id: string; name: string }[]
groups: GroupListItem[]
}
const PaymentsContext = createContext<PaymentsContextValue | null>(null)

View File

@@ -2,6 +2,7 @@ import type { PaymentStatus } from '@gruperly/shared'
import { ChevronLeft, ChevronRight, Loader2, Wallet } from 'lucide-react'
import { Button } from '../../components/ui'
import { cn } from '../../lib/utils'
import { GroupFilter } from './GroupFilter'
import { PaymentRow } from './PaymentRow'
import { ReportedPaymentsSection } from './ReportedPaymentsSection'
import { usePayments } from './PaymentsProvider'
@@ -25,14 +26,12 @@ export function PaymentsView() {
isError,
errorMessage,
groupId,
setGroupId,
status,
setStatus,
setPage,
retry,
renew,
isRenewing,
groups,
} = usePayments()
return (
@@ -46,25 +45,12 @@ export function PaymentsView() {
<ReportedPaymentsSection />
{/* Filtros: el grupo primera (cada cobro cuelga de un grupo) y el estado. */}
<div className="mt-5 space-y-3">
<label className="block">
<span className="mb-1.5 block text-sm font-medium text-primary">Grupo</span>
<select
value={groupId ?? ''}
onChange={(event) => setGroupId(event.target.value || null)}
className="h-10 w-full rounded-xl border border-border bg-surface px-3 text-base text-primary sm:text-sm focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30"
>
<option value="">Todos los grupos</option>
{groups.map((group) => (
<option key={group.id} value={group.id}>
{group.name}
</option>
))}
</select>
</label>
<div role="tablist" aria-label="Filtrar por estado" className="flex gap-2 overflow-x-auto">
{/* Filtros: el grupo primero (cada cobro cuelga de un grupo), un divisor
y el estado. En mobile la fila scrollea; en desktop hace wrap. */}
<div className="mt-5 flex items-center gap-2 overflow-x-auto lg:flex-wrap lg:overflow-visible">
<GroupFilter />
<span className="h-6 w-px shrink-0 bg-border" aria-hidden="true" />
<div role="tablist" aria-label="Filtrar por estado" className="flex gap-2 lg:flex-wrap">
{STATUS_FILTERS.map((filter) => {
const isActive = status === filter.value
return (
@@ -123,6 +109,7 @@ export function PaymentsView() {
<PaymentRow
key={payment.id}
payment={payment}
showGroup={groupId === null}
isRenewing={isRenewing(payment.id)}
onRenew={renew}
/>

View File

@@ -92,12 +92,18 @@
/* Animations */
--animate-fade-in: fade-in 0.2s ease-out;
--animate-step-enter: step-enter 0.35s cubic-bezier(0.22, 1, 0.36, 1) both;
--animate-sheet-up: sheet-up 0.25s cubic-bezier(0.22, 1, 0.36, 1) both;
@keyframes fade-in {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes sheet-up {
from { transform: translateY(100%); }
to { transform: translateY(0); }
}
@keyframes step-enter {
from {
opacity: 0;

View File

@@ -52,10 +52,13 @@ export type InviteTokenResult = z.output<typeof InviteTokenResultSchema>;
the card shows them: `attendeesCount` are the group's members (all of them,
same as the detail page counts) and `waitlistCount` those on the waitlist
waiting for a spot (PENDING). The pre-registrations list is a different
thing and does not belong here. */
thing and does not belong here. `unpaidPaymentsCount` are the group's
payments still to collect (PENDING and OVERDUE), shown by the group filter
of the payments screen. */
export const GroupListItemSchema = GroupDtoSchema.extend({
attendeesCount: z.number().int().min(0),
waitlistCount: z.number().int().min(0),
unpaidPaymentsCount: z.number().int().min(0),
});
export type GroupListItem = z.output<typeof GroupListItemSchema>;