diff --git a/admin/src/lib/format.test.ts b/admin/src/lib/format.test.ts new file mode 100644 index 0000000..0d310c0 --- /dev/null +++ b/admin/src/lib/format.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from 'vitest' +import { formatBytes, formatDate } from './format' + +describe('formatBytes', () => { + it.each([ + [0, '0 B'], + [512, '512 B'], + [1023, '1023 B'], + [1024, '1.0 KB'], + [1536, '1.5 KB'], + [10 * 1024, '10 KB'], + [1024 * 1024, '1.0 MB'], + [25 * 1024 * 1024, '25 MB'], + ])('%d -> %s', (n, want) => expect(formatBytes(n)).toBe(want)) +}) + +describe('formatDate', () => { + it('formats ISO dates in UTC, minute precision', () => { + expect(formatDate('2030-01-02T03:04:05Z')).toBe('2030-01-02 03:04 UTC') + expect(formatDate('2030-01-02T23:59:59+02:00')).toBe('2030-01-02 21:59 UTC') + }) + it('returns the input for something that is not a date', () => { + expect(formatDate('garbage')).toBe('garbage') + }) +}) diff --git a/admin/src/lib/format.ts b/admin/src/lib/format.ts new file mode 100644 index 0000000..7b69c59 --- /dev/null +++ b/admin/src/lib/format.ts @@ -0,0 +1,16 @@ +const KB = 1024 +const MB = 1024 * KB + +/** 1536 -> "1.5 KB". One decimal below 10, none above. */ +export function formatBytes(n: number): string { + if (n < KB) return `${n} B` + const [value, unit] = n < MB ? [n / KB, 'KB'] : [n / MB, 'MB'] + return `${value < 10 ? value.toFixed(1) : Math.round(value)} ${unit}` +} + +/** ISO timestamp -> "2030-01-02 03:04 UTC". Unparseable input is returned as is. */ +export function formatDate(iso: string): string { + const d = new Date(iso) + if (Number.isNaN(d.getTime())) return iso + return `${d.toISOString().slice(0, 16).replace('T', ' ')} UTC` +} diff --git a/admin/src/tabs/HeldTab.test.tsx b/admin/src/tabs/HeldTab.test.tsx new file mode 100644 index 0000000..6758144 --- /dev/null +++ b/admin/src/tabs/HeldTab.test.tsx @@ -0,0 +1,115 @@ +import { screen, waitFor, within } from '@testing-library/react' +import { describe, expect, it } from 'vitest' +import type { Held } from '@/lib/api' +import { aList, installFakeApi, newState } from '@/test/fakeApi' +import { renderApp } from '@/test/render' + +const held = (id: number, over: Partial = {}): Held => ({ + id, + sender: `s${id}@example.com`, + subject: `Subject ${id}`, + size: 2048, + created_at: '2030-01-02T03:04:05Z', + ...over, +}) + +async function setup(items: Held[], list = aList({ id: 1, post_policy: 'moderated' })) { + const state = installFakeApi(newState({ lists: [list], held: { [list.id]: items } })) + const ctx = renderApp(`/lists/${list.id}/held`, { token: 'good' }) + await screen.findByRole('heading', { name: /held messages/i, level: 2 }) + return { ...ctx, state } +} + +describe('held tab', () => { + it('shows each waiting message', async () => { + await setup([held(1), held(2, { subject: '', size: 100 })]) + const one = (await screen.findByText('Subject 1')).closest('tr')! + expect(within(one).getByText('s1@example.com')).toBeInTheDocument() + expect(within(one).getByText('2.0 KB')).toBeInTheDocument() + expect(within(one).getByText('2030-01-02 03:04 UTC')).toBeInTheDocument() + expect(screen.getByText('(no subject)')).toBeInTheDocument() + }) + + it('says nothing is waiting', async () => { + await setup([]) + expect(await screen.findByText(/nothing is waiting/i)).toBeInTheDocument() + }) + + it('explains how messages get held when posting is not moderated', async () => { + await setup([], aList({ id: 1, post_policy: 'members' })) + expect(await screen.findByText(/set posting to moderated/i)).toBeInTheDocument() + }) + + it('does not nag about the policy when the list is moderated', async () => { + await setup([]) + await screen.findByText(/nothing is waiting/i) + expect(screen.queryByText(/set posting to moderated/i)).not.toBeInTheDocument() + }) + + it('approves a message: it is sent and leaves the queue', async () => { + const { user, state } = await setup([held(1), held(2)]) + const row = (await screen.findByText('Subject 1')).closest('tr')! + await user.click(within(row).getByRole('button', { name: /approve/i })) + await waitFor(() => expect(screen.queryByText('Subject 1')).not.toBeInTheDocument()) + expect(screen.getByText('Subject 2')).toBeInTheDocument() + expect(state.calls).toContain('POST /held/1/approve') + expect(state.held[1].map((h) => h.id)).toEqual([2]) + expect(await screen.findByText(/message approved/i)).toBeInTheDocument() + }) + + it('keeps the message and shows the error when approving fails', async () => { + const { user, state } = await setup([held(1)]) + state.fail['POST /held/1/approve'] = { status: 500, error: 'relay unreachable' } + await user.click(within((await screen.findByText('Subject 1')).closest('tr')!).getByRole('button', { name: /approve/i })) + expect(await screen.findByRole('alert')).toHaveTextContent('relay unreachable') + expect(screen.getByText('Subject 1')).toBeInTheDocument() + expect(state.held[1]).toHaveLength(1) + }) + + it('reports a delivery that is not configured', async () => { + const { user, state } = await setup([held(1)]) + state.fail['POST /held/1/approve'] = { status: 501, error: 'delivery is not configured' } + await user.click(within((await screen.findByText('Subject 1')).closest('tr')!).getByRole('button', { name: /approve/i })) + expect(await screen.findByRole('alert')).toHaveTextContent('delivery is not configured') + }) + + describe('discarding', () => { + async function open() { + const ctx = await setup([held(1), held(2)]) + await ctx.user.click(within((await screen.findByText('Subject 1')).closest('tr')!).getByRole('button', { name: /discard/i })) + return { ...ctx, dialog: await screen.findByRole('alertdialog') } + } + + it('confirms first; cancel keeps the message', async () => { + const { user, state, dialog } = await open() + expect(dialog).toHaveTextContent('Subject 1') + await user.click(within(dialog).getByRole('button', { name: /cancel/i })) + await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()) + expect(state.held[1]).toHaveLength(2) + }) + + it('discards without sending anything', async () => { + const { user, state, dialog } = await open() + await user.click(within(dialog).getByRole('button', { name: /^discard$/i })) + await waitFor(() => expect(screen.queryByText('Subject 1')).not.toBeInTheDocument()) + expect(state.calls).toContain('DELETE /held/1') + expect(state.calls).not.toContain('POST /held/1/approve') + expect(state.held[1].map((h) => h.id)).toEqual([2]) + }) + + it('shows a server error inside the dialog', async () => { + const { user, state, dialog } = await open() + state.fail['DELETE /held/1'] = { status: 500, error: 'locked' } + await user.click(within(dialog).getByRole('button', { name: /^discard$/i })) + expect(await within(dialog).findByRole('alert')).toHaveTextContent('locked') + expect(state.held[1]).toHaveLength(2) + }) + }) + + it('updates the badge on the tab when the queue changes', async () => { + const { user } = await setup([held(1), held(2)]) + expect(await screen.findByRole('tab', { name: /^held\s*2$/i })).toBeInTheDocument() + await user.click(within((await screen.findByText('Subject 1')).closest('tr')!).getByRole('button', { name: /approve/i })) + expect(await screen.findByRole('tab', { name: /^held\s*1$/i })).toBeInTheDocument() + }) +}) diff --git a/admin/src/tabs/HeldTab.tsx b/admin/src/tabs/HeldTab.tsx index 3424afd..2abf69d 100644 --- a/admin/src/tabs/HeldTab.tsx +++ b/admin/src/tabs/HeldTab.tsx @@ -1,3 +1,138 @@ +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { useState } 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 { Button } from '@/components/ui/button' +import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table' +import { api, type Held, type List } from '@/lib/api' +import { formatBytes, formatDate } from '@/lib/format' + export function HeldTab() { - return

Held

+ const list = useOutletContext() + const queryClient = useQueryClient() + const key = ['held', list.id] + const held = useQuery({ queryKey: key, queryFn: () => api.held.list(list.id) }) + const [discarding, setDiscarding] = useState(null) + const [error, setError] = useState(null) + + const approve = useMutation({ + mutationFn: (h: Held) => api.held.approve(h.id), + onSuccess: async () => { + setError(null) + await queryClient.invalidateQueries({ queryKey: key }) + // An approved post is delivered and archived. + await queryClient.invalidateQueries({ queryKey: ['archive', list.id] }) + toast.success('Message approved and sent') + }, + onError: (e: Error) => setError(e.message), + }) + + const items = held.data ?? [] + return ( +
+

Held messages

+ {error && ( +

+ {error} +

+ )} + {held.isPending &&

Loading…

} + {held.isError &&

{held.error.message}

} + {held.data && items.length === 0 && ( +
+

Nothing is waiting for approval.

+ {list.post_policy !== 'moderated' && ( +

Messages are held only when you set Posting to moderated in Settings.

+ )} +
+ )} + {items.length > 0 && ( + + + + Subject + From + Received + Size + Actions + + + + {items.map((h) => ( + + {h.subject || '(no subject)'} + {h.sender} + {formatDate(h.created_at)} + {formatBytes(h.size)} + + + + + + ))} + +
+ )} + setDiscarding(null)} /> +
+ ) +} + +function DiscardDialog({ listId, held, onClose }: { listId: number; held: Held | null; onClose: () => void }) { + const queryClient = useQueryClient() + const [error, setError] = useState(null) + const discard = useMutation({ + mutationFn: (h: Held) => api.held.discard(h.id), + onSuccess: async () => { + await queryClient.invalidateQueries({ queryKey: ['held', listId] }) + toast.success('Message discarded') + onClose() + }, + onError: (e: Error) => setError(e.message), + }) + + return ( + { + if (!open) { + setError(null) + onClose() + } + }} + > + + + Discard this message? + + “{held?.subject || '(no subject)'}” from {held?.sender} will be deleted and not sent to anyone. + + + {error && ( +

+ {error} +

+ )} + + Cancel + + +
+
+ ) }