'use client' import { useEffect, useRef, useState } from 'react' import { authFetch, getApiBase } from '../../lib/auth' type Delivery = { id: string; month: string; state: string; detail: string } type Preference = { email: string | null; can_send: boolean; state: string; detail: string; deliveries: Delivery[] } export default function EmailReportControl({ month }: { month: string }) { const [data, setData] = useState(null) const [busy, setBusy] = useState(false) const [notice, setNotice] = useState('') const [error, setError] = useState('') const [revision, setRevision] = useState(0) const request = useRef<{ month: string; id: string } | null>(null) const pending = data?.deliveries.some((item) => ['queued', 'preparing', 'sending', 'retry'].includes(item.state)) ?? false useEffect(() => { const abort = new AbortController() void authFetch(`${getApiBase()}/profile/email-recaps`, { signal: abort.signal }).then(async (response) => { if (!response.ok) throw new Error('Could not load your report email preferences. Refresh to try again.') const result = await response.json() if (!abort.signal.aborted) setData(result) }).catch((err: Error) => { if (!abort.signal.aborted) setError(err.message) }) return () => abort.abort() }, [revision]) useEffect(() => { if (!pending) return const timer = window.setInterval(() => setRevision((value) => value + 1), 10000) return () => window.clearInterval(timer) }, [pending]) const send = async () => { if (busy || !data?.can_send) return setBusy(true); setError(''); setNotice('') if (request.current?.month !== month) request.current = { month, id: crypto.randomUUID() } try { const response = await authFetch(`${getApiBase()}/profile/email-recaps/send`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ month, request_id: request.current.id }), }) const result = await response.json().catch(() => ({})) if (!response.ok) throw new Error(typeof result.detail === 'string' ? result.detail : 'Could not queue your report. Try again.') setNotice(result.message); request.current = null setRevision((value) => value + 1) } catch (err) { setError(err instanceof Error ? err.message : 'Could not queue your report.') } finally { setBusy(false) } } return

Email yourself this report

Email preferences

Choose a month above, including the current month so far, then send its viewing and request summary to your confirmed profile email.

{data?.can_send ?

{data.email} · One report email every five minutes.

: data &&

{data.state === 'enabled' ? data.detail : 'Confirm your profile email in Email preferences first. You can choose on-demand delivery without automatic monthly emails.'}

} {notice &&

{notice}

} {error &&

{error}

} {!!data?.deliveries.length &&
Recent report emails
    {data.deliveries.map((item) =>
  • {item.month} · {item.state === 'sent' ? 'Accepted by mail server' : item.state} — {item.detail || 'Waiting for delivery'}
  • )}
}
}