Let users email personal reports on demand
Magent CI/CD / verify (push) Successful in 11m6s
Magent CI/CD / deploy-prod (push) Skipped
Magent CI/CD / deploy-beta (push) Successful in 1m40s

This commit is contained in:
2026-09-10 16:15:39 +12:00
parent 6e473fd0a7
commit b286ca3c42
13 changed files with 261 additions and 36 deletions
@@ -0,0 +1,60 @@
'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<Preference | null>(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 <section className="stats-panel report-email-panel" aria-label="Email your report">
<div className="stats-panel-heading"><h2>Email yourself this report</h2><a href="/profile#monthly-recaps">Email preferences</a></div>
<p>Choose a month above, including the current month so far, then send its viewing and request summary to your confirmed profile email.</p>
{data?.can_send ? <p><strong>{data.email}</strong> · One report email every five minutes.</p> : data && <p>{data.state === 'enabled' ? data.detail : 'Confirm your profile email in Email preferences first. You can choose on-demand delivery without automatic monthly emails.'}</p>}
<button type="button" disabled={busy || !data?.can_send} onClick={() => void send()}>{busy ? 'Queueing report…' : 'Email this report'}</button>
{notice && <p role="status">{notice}</p>}
{error && <p role="alert">{error}</p>}
{!!data?.deliveries.length && <details><summary>Recent report emails</summary><ul>{data.deliveries.map((item) => <li key={item.id}><strong>{item.month}</strong> · {item.state === 'sent' ? 'Accepted by mail server' : item.state} {item.detail || 'Waiting for delivery'}</li>)}</ul></details>}
</section>
}