feat/improve-ui #11

Merged
jselesan merged 5 commits from feat/improve-ui into development 2026-10-28 18:40:22 +00:00
32 changed files with 730 additions and 440 deletions
Showing only changes of commit 90f31290d4 - Show all commits

View File

@@ -39,8 +39,21 @@ export class GetAttendeeHistory {
return err(notFoundResourceProblem('Attendee', attendeeId));
}
// Same effective join date as the risk rule (`toMemberAttendance`): an
// attendee loaded after their first classes were already recorded starts
// at that first class, not at `createdAt`. Otherwise this screen said
// "1 de 3 clases" while the group list said "1 de 5" for the same person.
const firstAttendance = await db.attendance.findFirst({
where: { attendeeId },
orderBy: { classSession: { startsAt: 'asc' } },
select: { classSession: { select: { startsAt: true } } },
});
const firstClassAt = firstAttendance?.classSession.startsAt;
const since =
firstClassAt && firstClassAt < attendee.createdAt ? firstClassAt : attendee.createdAt;
const sessions = await db.classSession.findMany({
where: { groupId, startsAt: { gte: attendee.createdAt } },
where: { groupId, startsAt: { gte: since } },
orderBy: { startsAt: 'desc' },
take: HISTORY_SESSIONS_LIMIT,
select: { id: true, startsAt: true },

View File

@@ -16,6 +16,7 @@ const db = {
},
attendance: {
findMany: mock(),
findFirst: mock(),
},
slotRelease: {
count: mock(),
@@ -251,6 +252,29 @@ describe('analytics routes', () => {
});
});
it('arranca en la primera clase registrada si es anterior al alta', async () => {
// Loaded on 1/10 with classes already marked since 20/9: the history
// starts at the first one, as the risk rule and the group list count it.
prisma.group.findUnique.mockResolvedValue(makeGroup());
prisma.attendee.findFirst.mockResolvedValue({
id: 'a-1',
fullName: 'Ana Pérez',
createdAt: new Date('2026-10-01T00:00:00.000Z'),
});
prisma.attendance.findFirst.mockResolvedValueOnce({
classSession: { startsAt: new Date('2026-09-20T10:00:00.000Z') },
});
prisma.classSession.findMany.mockResolvedValue([]);
await makeApp({ id: userId }).request('/groups/group-1/attendees/a-1/history');
expect(prisma.classSession.findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: { groupId: 'group-1', startsAt: { gte: new Date('2026-09-20T10:00:00.000Z') } },
}),
);
});
it('devuelve 404 si el alumno no pertenece al grupo', async () => {
prisma.group.findUnique.mockResolvedValue(makeGroup());
prisma.attendee.findFirst.mockResolvedValue(null);

View File

@@ -18,7 +18,12 @@ export function Header() {
<Breadcrumb />
</div>
<div className="flex items-center gap-2">
<ThemeToggle />
{/* On mobile the theme lives only in Ajustes → Apariencia: in the
header it took the space next to the avatar for something you
change once. On desktop there is room for the shortcut. */}
<div className="hidden lg:block">
<ThemeToggle />
</div>
<UserMenu />
</div>
</div>

View File

@@ -1,4 +1,4 @@
import { useForm } from 'react-hook-form'
import { type DefaultValues, useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import type { BillingType, CountryCode, CreateFirstGroup, WeekDay } from '@gruperly/shared'
import { CreateFirstGroupSchema, DEFAULT_COUNTRY } from '@gruperly/shared'
@@ -30,12 +30,14 @@ export function GroupForm({
onSubmit,
onBack,
}: GroupFormProps) {
const defaultValues: CreateFirstGroup = {
// The price starts empty on purpose: a pre-filled $0 got submitted as is and
// the group ended up unable to charge. The capacity starts at a typical
// class size instead of 1, which had to be overwritten every time.
const defaultValues: DefaultValues<CreateFirstGroup> = {
name: '',
days: [],
time: '09:00',
capacity: 1,
price: 0,
capacity: 10,
billingType: 'MONTHLY',
dueDay: 1,
country,
@@ -77,6 +79,7 @@ export function GroupForm({
<Label htmlFor="name">Nombre del grupo</Label>
<Input
id="name"
autoFocus
placeholder="Ej: Yoga Vinyasa · Nivel 1"
invalid={!!errors.name}
{...register('name')}
@@ -150,7 +153,7 @@ export function GroupForm({
inputMode="decimal"
min={0}
step="0.01"
placeholder="0.00"
placeholder="Por alumno"
className="pl-7"
invalid={!!errors.price}
{...register('price', { valueAsNumber: true })}

View File

@@ -1,8 +1,10 @@
import type { GroupAutomationsDto } from '@gruperly/shared'
import { Link } from '@tanstack/react-router'
import { MessageCircle } from 'lucide-react'
import { ChevronDown, MessageCircle } from 'lucide-react'
import { useState } from 'react'
import { Badge, Switch } from '../../../components/ui'
import { hasPlanFeature, useBillingStatus } from '../../billing'
import { cn } from '../../../lib/utils'
import { automationBlockedReason, useWhatsappStatus, WEEKLY_SEND_LABEL } from '../../whatsapp'
import { useGroupDetail } from './GroupDetailProvider'
@@ -32,26 +34,56 @@ const AUTOMATIONS: readonly Automation[] = [
* Los envíos automáticos por WhatsApp del grupo. Solo el dueño los cambia: los
* mensajes salen de su número. Se pueden apagar siempre; prenderlos exige un
* WhatsApp vinculado y el mensaje aprobado.
*
* Arranca plegado cuando no hay ninguno prendido: desplegado ocupaba media
* pantalla en mobile antes de llegar a la lista de miembros, que es lo que se
* viene a ver. La fila plegada ya dice el estado ("Apagados", "1 activo").
*/
export function GroupAutomationsCard() {
const { group, updateAutomations, isUpdatingAutomations, isGroupOwner } = useGroupDetail()
const whatsappQuery = useWhatsappStatus({ enabled: isGroupOwner })
const billingQuery = useBillingStatus({ enabled: isGroupOwner })
// `null` until the owner touches it: the default follows the data, which may
// arrive after the first render.
const [expandedByUser, setExpandedByUser] = useState<boolean | null>(null)
if (!group || !isGroupOwner) return null
const includedInPlan = hasPlanFeature(billingQuery.data, 'whatsappAutomations')
const activeCount = AUTOMATIONS.filter((automation) => group[automation.key]).length
const expanded = expandedByUser ?? activeCount > 0
const summary =
activeCount === 0 ? 'Apagados' : activeCount === 1 ? '1 activo' : `${activeCount} activos`
return (
<section className="rounded-xl border border-border bg-surface">
<header className="flex items-start gap-3 px-4 pt-3">
<button
type="button"
onClick={() => setExpandedByUser(!expanded)}
aria-expanded={expanded}
aria-controls="group-automations"
className="flex w-full items-center gap-3 rounded-xl px-4 py-3 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
<span className="rounded-lg bg-success-soft p-2">
<MessageCircle className="size-4 text-success" />
</span>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<h2 className="text-sm font-semibold text-primary">Mensajes automáticos por WhatsApp</h2>
<span className="min-w-0 flex-1">
<span className="flex items-center gap-2">
<span className="text-sm font-semibold text-primary">Mensajes automáticos</span>
{includedInPlan ? null : <Badge variant="info">Pro</Badge>}
</div>
<p className="text-xs text-foreground/50">
</span>
<span className="block text-xs text-foreground/50">WhatsApp · {summary}</span>
</span>
<ChevronDown
className={cn(
'size-4 shrink-0 text-foreground/40 transition-transform',
expanded && 'rotate-180',
)}
aria-hidden="true"
/>
</button>
{expanded ? (
<div id="group-automations" className="border-t border-border">
<p className="px-4 pt-3 text-xs text-foreground/50">
{WEEKLY_SEND_LABEL}
{includedInPlan ? null : (
<>
@@ -63,46 +95,46 @@ export function GroupAutomationsCard() {
</>
)}
</p>
</div>
</header>
<ul className="divide-y divide-border">
{AUTOMATIONS.map((automation) => {
const checked = group[automation.key]
const blocked = automationBlockedReason(whatsappQuery.data, automation.kind)
const hintId = `automation-${automation.key}-hint`
return (
<li key={automation.key} className="flex items-start gap-3 px-4 py-3">
<div className="min-w-0 flex-1">
<p className="text-sm text-primary">{automation.title}</p>
<p id={hintId} className="text-xs text-foreground/50">
{automation.description}
{blocked && !checked ? (
<>
{' '}
<span className="text-warning">{blocked}</span>{' '}
{whatsappQuery.data?.status !== 'active' ? (
<Link to="/settings" className="font-medium text-accent-fg underline">
Ir a Ajustes
</Link>
<ul className="divide-y divide-border">
{AUTOMATIONS.map((automation) => {
const checked = group[automation.key]
const blocked = automationBlockedReason(whatsappQuery.data, automation.kind)
const hintId = `automation-${automation.key}-hint`
return (
<li key={automation.key} className="flex items-start gap-3 px-4 py-3">
<div className="min-w-0 flex-1">
<p className="text-sm text-primary">{automation.title}</p>
<p id={hintId} className="text-xs text-foreground/50">
{automation.description}
{blocked && !checked ? (
<>
{' '}
<span className="text-warning">{blocked}</span>{' '}
{whatsappQuery.data?.status !== 'active' ? (
<Link to="/settings" className="font-medium text-accent-fg underline">
Ir a Ajustes
</Link>
) : null}
</>
) : null}
</>
) : null}
</p>
</div>
<Switch
checked={checked}
disabled={
isUpdatingAutomations || (!checked && (blocked !== null || !includedInPlan))
}
aria-label={automation.title}
aria-describedby={hintId}
onCheckedChange={(next) => updateAutomations({ [automation.key]: next })}
/>
</li>
)
})}
</ul>
</p>
</div>
<Switch
checked={checked}
disabled={
isUpdatingAutomations || (!checked && (blocked !== null || !includedInPlan))
}
aria-label={automation.title}
aria-describedby={hintId}
onCheckedChange={(next) => updateAutomations({ [automation.key]: next })}
/>
</li>
)
})}
</ul>
</div>
) : null}
</section>
)
}

View File

@@ -88,11 +88,16 @@ export function GroupHeader({ onCharge }: { onCharge?: () => void }) {
</LargeTitle>
{hasGroup ? (
// A single row on mobile: the primary takes the leftover width and the two
// supporting actions collapse into 44px icons. At sm+ they get their text
// back because there is plenty of width and the label makes the
// destination clearer.
<div className="mt-4 flex items-center gap-2.5 sm:mt-5 sm:justify-end">
// On mobile the primary takes its own row and the supporting actions go
// below as three equal buttons with their label: as bare 44px icons
// nobody could tell "Cobrar" from "Estadísticas". At sm+ everything goes
// back to a single row aligned to the right.
<div
className={cn(
'mt-4 grid gap-2 sm:mt-5 sm:flex sm:items-center sm:justify-end sm:gap-2.5',
isEmptyGroup ? 'grid-cols-2' : 'grid-cols-3',
)}
>
{!isEmptyGroup ? (
// One primary per screen: "Agregar" heads the hierarchy and the
// supporting actions sit beside it, in outline.
@@ -101,7 +106,7 @@ export function GroupHeader({ onCharge }: { onCharge?: () => void }) {
onClick={() =>
void navigate({ to: '/groups/$groupId/attendees/new', params: { groupId } })
}
className="h-11 flex-1 justify-center sm:flex-none sm:w-auto"
className="col-span-3 h-11 justify-center sm:w-auto"
>
<UserPlus className="size-4" />
<span>Agregar miembro</span>
@@ -110,41 +115,29 @@ export function GroupHeader({ onCharge }: { onCharge?: () => void }) {
<Button
variant="outline"
onClick={() => void navigate({ to: '/groups/$groupId/analytics', params: { groupId } })}
aria-label="Estadísticas"
className={cn(
'h-11 shrink-0 justify-center border-border',
// On an empty group it is the header's only action: it takes the
// whole row.
isEmptyGroup && 'w-full sm:w-auto',
!isEmptyGroup && 'w-11 sm:w-auto sm:px-4',
)}
className={SECONDARY_ACTION_CLASS_NAME}
>
<BarChart3 className="size-4 text-accent" />
<span className="hidden sm:inline">Estadísticas</span>
<BarChart3 className="size-4 shrink-0 text-accent" />
<span className="truncate">Estadísticas</span>
</Button>
<Button
variant="outline"
onClick={onCharge}
disabled={group?.price == null}
aria-label="Cobrar período"
title={group?.price == null ? 'Definí el precio del grupo para poder cobrar' : undefined}
className={cn(
'h-11 shrink-0 justify-center border-border',
!isEmptyGroup && 'w-11 sm:w-auto sm:px-4',
)}
className={SECONDARY_ACTION_CLASS_NAME}
>
<Wallet className="size-4 text-accent" />
<span className="hidden sm:inline">Cobrar</span>
<Wallet className="size-4 shrink-0 text-accent" />
<span className="truncate">Cobrar</span>
</Button>
{!isEmptyGroup ? (
<Button
variant="outline"
onClick={openInviteModal}
aria-label="Compartir enlace"
className="h-11 w-11 shrink-0 justify-center border-border sm:w-auto sm:px-4"
className={SECONDARY_ACTION_CLASS_NAME}
>
<Share2 className="size-4 text-accent" />
<span className="hidden sm:inline">Compartir</span>
<Share2 className="size-4 shrink-0 text-accent" />
<span className="truncate">Compartir</span>
</Button>
) : null}
</div>
@@ -152,3 +145,8 @@ export function GroupHeader({ onCharge }: { onCharge?: () => void }) {
</div>
)
}
// Icon over label on mobile: side by side, "Estadísticas" didn't fit a third of
// a 402px row.
const SECONDARY_ACTION_CLASS_NAME =
'h-14 min-w-0 flex-col justify-center gap-1 border-border px-1 text-xs sm:h-11 sm:w-auto sm:flex-row sm:gap-1.5 sm:px-4 sm:text-sm'

View File

@@ -1,5 +1,5 @@
import { Link } from '@tanstack/react-router'
import { Fingerprint } from 'lucide-react'
import { ChevronRight, Fingerprint } from 'lucide-react'
import { Button } from '../../components/ui'
import { signOut } from '../../lib/auth-client'
import { PlanSettingsCard } from '../billing'
@@ -34,6 +34,7 @@ export function SettingsView() {
<p className="text-sm font-medium text-primary">Seguridad</p>
<p className="text-xs text-foreground/50">Contraseña y passkeys</p>
</div>
<ChevronRight className="size-4 text-foreground/40" />
</Link>
</div>