feat(admin): members tab

- Add member table with status, bounce count and client-side filter
- Add add-member form, re-enable for disabled members and confirmed removal
This commit is contained in:
tgiachi 2026-11-09 15:35:43 +01:00
commit 75a32386b2
2 changed files with 333 additions and 1 deletions

View file

@ -0,0 +1,133 @@
import { screen, waitFor, within } from '@testing-library/react'
import { describe, expect, it } from 'vitest'
import type { Member } from '@/lib/api'
import { aList, installFakeApi, newState } from '@/test/fakeApi'
import { renderApp } from '@/test/render'
const member = (address: string, over: Partial<Member> = {}): Member => ({
address,
display_name: '',
disabled: false,
bounce_count: 0,
...over,
})
async function setup(members: Member[] = []) {
const state = installFakeApi(newState({ lists: [aList({ id: 1 })], members: { 1: members } }))
const ctx = renderApp('/lists/1/members', { token: 'good' })
await screen.findByRole('heading', { name: /^members/i, level: 2 })
return { ...ctx, state }
}
describe('members tab', () => {
it('lists members with their name and status', async () => {
await setup([
member('alice@example.com', { display_name: 'Alice' }),
member('bob@example.com', { disabled: true, bounce_count: 3 }),
member('carol@example.com', { bounce_count: 1 }),
])
const alice = (await screen.findByText('alice@example.com')).closest('tr')!
expect(within(alice).getByText('Alice')).toBeInTheDocument()
expect(within(alice).getByText('Active')).toBeInTheDocument()
const bob = screen.getByText('bob@example.com').closest('tr')!
expect(within(bob).getByText(/disabled/i)).toBeInTheDocument()
expect(within(bob).getByText(/3 bounces/i)).toBeInTheDocument()
const carol = screen.getByText('carol@example.com').closest('tr')!
expect(within(carol).getByText('Active')).toBeInTheDocument()
expect(within(carol).getByText(/1 bounce$/i)).toBeInTheDocument()
expect(screen.getByRole('heading', { name: 'Members (3)', level: 2 })).toBeInTheDocument()
})
it('has an empty state', async () => {
await setup()
expect(await screen.findByText(/no members yet/i)).toBeInTheDocument()
})
it('filters the table as you type', async () => {
const { user } = await setup([member('alice@example.com', { display_name: 'Alice' }), member('bob@example.com')])
await screen.findByText('bob@example.com')
await user.type(screen.getByRole('searchbox', { name: /filter members/i }), 'ALI')
expect(screen.getByText('alice@example.com')).toBeInTheDocument()
expect(screen.queryByText('bob@example.com')).not.toBeInTheDocument()
await user.clear(screen.getByRole('searchbox', { name: /filter members/i }))
await user.type(screen.getByRole('searchbox', { name: /filter members/i }), 'zzz')
expect(await screen.findByText(/no members match/i)).toBeInTheDocument()
})
it('adds a member and clears the form', async () => {
const { user, state } = await setup([member('alice@example.com')])
await user.type(screen.getByLabelText(/email address/i), 'Dave@Example.com')
await user.type(screen.getByLabelText(/display name/i), 'Dave')
await user.click(screen.getByRole('button', { name: /add member/i }))
expect(await screen.findByText('dave@example.com')).toBeInTheDocument()
expect(state.members[1].map((m) => m.address)).toEqual(['alice@example.com', 'dave@example.com'])
expect(screen.getByLabelText(/email address/i)).toHaveValue('')
expect(screen.getByLabelText(/display name/i)).toHaveValue('')
expect(await screen.findByText(/added dave@example.com/i)).toBeInTheDocument()
})
it('asks for an address before calling the API', async () => {
const { user, state } = await setup()
await user.click(screen.getByRole('button', { name: /add member/i }))
expect(await screen.findByText(/enter an email address/i)).toBeInTheDocument()
expect(state.calls.filter((c) => c.startsWith('POST'))).toEqual([])
})
it('shows the server error for a bad address and keeps what was typed', async () => {
const { user } = await setup()
await user.type(screen.getByLabelText(/email address/i), 'not-an-address')
await user.click(screen.getByRole('button', { name: /add member/i }))
expect(await screen.findByRole('alert')).toHaveTextContent('a valid email address is required')
expect(screen.getByLabelText(/email address/i)).toHaveValue('not-an-address')
})
it('re-enables a disabled member', async () => {
const { user, state } = await setup([member('bob@example.com', { display_name: 'Bob', disabled: true, bounce_count: 3 })])
const row = (await screen.findByText('bob@example.com')).closest('tr')!
await user.click(within(row).getByRole('button', { name: /re-enable/i }))
await waitFor(() => expect(state.members[1][0].disabled).toBe(false))
expect(state.members[1][0].display_name).toBe('Bob')
expect(await screen.findByText('Active')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: /re-enable/i })).not.toBeInTheDocument()
})
it('does not offer re-enable for active members', async () => {
await setup([member('alice@example.com')])
await screen.findByText('alice@example.com')
expect(screen.queryByRole('button', { name: /re-enable/i })).not.toBeInTheDocument()
})
describe('removing', () => {
async function open() {
const ctx = await setup([member('alice@example.com'), member('a+b@example.com')])
const row = (await screen.findByText('a+b@example.com')).closest('tr')!
await ctx.user.click(within(row).getByRole('button', { name: /remove/i }))
return { ...ctx, dialog: await screen.findByRole('alertdialog') }
}
it('confirms first, naming the address; cancel keeps the member', async () => {
const { user, state, dialog } = await open()
expect(dialog).toHaveTextContent('a+b@example.com')
await user.click(within(dialog).getByRole('button', { name: /cancel/i }))
await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
expect(state.members[1]).toHaveLength(2)
})
it('removes the member, encoding the address in the URL', async () => {
const { user, state, dialog } = await open()
await user.click(within(dialog).getByRole('button', { name: /^remove$/i }))
await waitFor(() => expect(screen.queryByText('a+b@example.com')).not.toBeInTheDocument())
expect(state.members[1].map((m) => m.address)).toEqual(['alice@example.com'])
expect(state.calls).toContain('DELETE /lists/1/members/a%2Bb%40example.com')
expect(screen.getByText('alice@example.com')).toBeInTheDocument()
})
it('shows a server error inside the dialog', async () => {
const { user, state, dialog } = await open()
state.fail['DELETE /lists/1/members/a%2Bb%40example.com'] = { status: 500, error: 'locked' }
await user.click(within(dialog).getByRole('button', { name: /^remove$/i }))
expect(await within(dialog).findByRole('alert')).toHaveTextContent('locked')
expect(state.members[1]).toHaveLength(2)
})
})
})

View file

@ -1,3 +1,202 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useState, type FormEvent } from 'react'
import { useOutletContext } from 'react-router'
import { toast } from 'sonner'
import {
AlertDialog,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { api, type List, type Member } from '@/lib/api'
export function MembersTab() {
return <h2 className="text-lg font-semibold">Members</h2>
const list = useOutletContext<List>()
const queryClient = useQueryClient()
const key = ['members', list.id]
const members = useQuery({ queryKey: key, queryFn: () => api.members.list(list.id) })
const [filter, setFilter] = useState('')
const [removing, setRemoving] = useState<Member | null>(null)
const reenable = useMutation({
// Adding an address again clears the bounce state.
mutationFn: (m: Member) => api.members.add(list.id, { address: m.address, display_name: m.display_name }),
onSuccess: async (m) => {
await queryClient.invalidateQueries({ queryKey: key })
toast.success(`Re-enabled ${m.address}`)
},
onError: (e: Error) => toast.error(e.message),
})
const all = members.data ?? []
const q = filter.trim().toLowerCase()
const shown = q ? all.filter((m) => m.address.includes(q) || m.display_name.toLowerCase().includes(q)) : all
return (
<div className="space-y-6">
<h2 className="text-lg font-semibold">Members{members.data ? ` (${all.length})` : ''}</h2>
<AddMemberForm list={list} />
{members.isPending && <p className="text-muted-foreground">Loading…</p>}
{members.isError && <p role="alert" className="text-destructive">{members.error.message}</p>}
{members.data && all.length === 0 && <p className="text-muted-foreground">No members yet.</p>}
{all.length > 0 && (
<>
<Input
type="search"
aria-label="Filter members"
placeholder="Filter members"
className="max-w-xs"
value={filter}
onChange={(e) => setFilter(e.target.value)}
/>
{shown.length === 0 ? (
<p className="text-muted-foreground">No members match.</p>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>Address</TableHead>
<TableHead>Name</TableHead>
<TableHead>Status</TableHead>
<TableHead className="text-right">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{shown.map((m) => (
<TableRow key={m.address}>
<TableCell className="font-medium">{m.address}</TableCell>
<TableCell>{m.display_name}</TableCell>
<TableCell className="space-x-2">
{m.disabled ? <Badge variant="destructive">Disabled</Badge> : <Badge variant="secondary">Active</Badge>}
{m.bounce_count > 0 && (
<span className="text-sm text-muted-foreground">
{m.bounce_count} {m.bounce_count === 1 ? 'bounce' : 'bounces'}
</span>
)}
</TableCell>
<TableCell className="space-x-2 text-right">
{m.disabled && (
<Button size="sm" variant="outline" disabled={reenable.isPending} onClick={() => reenable.mutate(m)}>
Re-enable
</Button>
)}
<Button size="sm" variant="outline" onClick={() => setRemoving(m)}>
Remove
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</>
)}
<RemoveDialog list={list} member={removing} onClose={() => setRemoving(null)} />
</div>
)
}
function AddMemberForm({ list }: { list: List }) {
const queryClient = useQueryClient()
const [address, setAddress] = useState('')
const [name, setName] = useState('')
const [error, setError] = useState<string | null>(null)
const add = useMutation({
mutationFn: () => api.members.add(list.id, { address: address.trim(), display_name: name.trim() }),
onSuccess: async (m) => {
await queryClient.invalidateQueries({ queryKey: ['members', list.id] })
toast.success(`Added ${m.address}`)
setAddress('')
setName('')
setError(null)
},
onError: (e: Error) => setError(e.message),
})
function submit(e: FormEvent) {
e.preventDefault()
if (address.trim() === '') {
setError('Enter an email address')
return
}
setError(null)
add.mutate()
}
return (
<form onSubmit={submit} className="space-y-3">
<div className="flex flex-wrap items-end gap-3">
<div className="space-y-2">
<Label htmlFor="member-address">Email address</Label>
<Input id="member-address" value={address} onChange={(e) => setAddress(e.target.value)} autoComplete="off" />
</div>
<div className="space-y-2">
<Label htmlFor="member-name">Display name</Label>
<Input id="member-name" value={name} onChange={(e) => setName(e.target.value)} autoComplete="off" />
</div>
<Button type="submit" disabled={add.isPending}>
Add member
</Button>
</div>
{error && (
<p role="alert" className="text-sm text-destructive">
{error}
</p>
)}
</form>
)
}
function RemoveDialog({ list, member, onClose }: { list: List; member: Member | null; onClose: () => void }) {
const queryClient = useQueryClient()
const [error, setError] = useState<string | null>(null)
const remove = useMutation({
mutationFn: (address: string) => api.members.remove(list.id, address),
onSuccess: async (_, address) => {
await queryClient.invalidateQueries({ queryKey: ['members', list.id] })
toast.success(`Removed ${address}`)
onClose()
},
onError: (e: Error) => setError(e.message),
})
return (
<AlertDialog
open={member !== null}
onOpenChange={(open) => {
if (!open) {
setError(null)
onClose()
}
}}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Remove {member?.address}?</AlertDialogTitle>
<AlertDialogDescription>They stop receiving mail from {list.address} and can no longer post.</AlertDialogDescription>
</AlertDialogHeader>
{error && (
<p role="alert" className="text-sm text-destructive">
{error}
</p>
)}
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<Button variant="destructive" disabled={remove.isPending} onClick={() => member && remove.mutate(member.address)}>
Remove
</Button>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
)
}