555bc6ff56
build / build (push) Successful in 1m6s
看板图只能由浏览器渲染,改为确认动作内自动生成并上传,不再要求另点按钮;只在已附图时提供重新生成。
384 lines
14 KiB
TypeScript
384 lines
14 KiB
TypeScript
import { useCallback, useEffect, useState } from 'react'
|
||
import { useOptionalAuth } from './auth'
|
||
import { QADashboardView } from './QADashboard'
|
||
import { fetchQADashboard } from './qaDashboardData'
|
||
import { createDashboardPNG } from './qaDashboardExport'
|
||
import { qaDateTimeToISO, qaWeekQueryRange } from './qaWeeks'
|
||
import {
|
||
confirmWeeklyMail,
|
||
fetchWeeklyMailConfirmation,
|
||
fetchWeeklyMailSends,
|
||
fetchWeeklyMailSettings,
|
||
saveWeeklyMailSettings,
|
||
sendWeeklyMailTest,
|
||
uploadWeeklyMailImage,
|
||
weeklyMailWeekdayLabels,
|
||
} from './qaWeeklyMail'
|
||
import type { WeeklyMailConfirmation, WeeklyMailSend, WeeklyMailSettings } from './qaWeeklyMail'
|
||
import './qaWeeklyMail.css'
|
||
|
||
const stamp = (value: string) => (value ? new Date(value).toLocaleString('zh-CN', { hour12: false }) : '—')
|
||
|
||
export function QAWeeklyMail({ week, busy }: { week: string; busy: boolean }) {
|
||
const auth = useOptionalAuth()
|
||
const admin = auth?.identity?.role === 'admin'
|
||
const [confirmation, setConfirmation] = useState<WeeklyMailConfirmation | null>(null)
|
||
const [settings, setSettings] = useState<WeeklyMailSettings | null>(null)
|
||
const [sends, setSends] = useState<WeeklyMailSend[]>([])
|
||
const [error, setError] = useState('')
|
||
const [notice, setNotice] = useState('')
|
||
const [working, setWorking] = useState(false)
|
||
const [editing, setEditing] = useState(false)
|
||
const [testing, setTesting] = useState(false)
|
||
const [capture, setCapture] = useState(false)
|
||
const [attaching, setAttaching] = useState(false)
|
||
|
||
const reload = useCallback(async () => {
|
||
setError('')
|
||
try {
|
||
const [nextConfirmation, nextSends, nextSettings] = await Promise.all([
|
||
fetchWeeklyMailConfirmation(week),
|
||
fetchWeeklyMailSends(week),
|
||
admin ? fetchWeeklyMailSettings() : Promise.resolve(null),
|
||
])
|
||
setConfirmation(nextConfirmation)
|
||
setSends(nextSends)
|
||
if (nextSettings) setSettings(nextSettings)
|
||
} catch (reason) {
|
||
setError(reason instanceof Error ? reason.message : '周报邮件状态读取失败')
|
||
}
|
||
}, [week, admin])
|
||
|
||
useEffect(() => {
|
||
void reload()
|
||
}, [reload])
|
||
|
||
const toggleConfirm = async (confirm: boolean) => {
|
||
if (working) return
|
||
setWorking(true)
|
||
setError('')
|
||
setNotice('')
|
||
try {
|
||
const next = await confirmWeeklyMail(week, confirm)
|
||
setConfirmation(next)
|
||
setNotice(confirm ? '已确认本周周报;到设定时间会自动发送,正文改动后需重新确认' : '已取消确认,不会自动发送')
|
||
setSends(await fetchWeeklyMailSends(week))
|
||
// The chart can only be rendered by the browser, so it is generated and attached
|
||
// the moment the operator confirms — no separate step for the common path.
|
||
if (confirm && next?.current) {
|
||
setNotice('已确认本周周报;正在生成并附上统计看板图片…')
|
||
setAttaching(true)
|
||
setCapture(true)
|
||
}
|
||
} catch (reason) {
|
||
setError(reason instanceof Error ? reason.message : '确认失败')
|
||
} finally {
|
||
setWorking(false)
|
||
}
|
||
}
|
||
|
||
const testSend = async () => {
|
||
if (testing) return
|
||
setTesting(true)
|
||
setError('')
|
||
setNotice('')
|
||
try {
|
||
const id = await sendWeeklyMailTest(week)
|
||
setNotice(`测试邮件已发出(${id});成功后不影响正式发送记录`)
|
||
} catch (reason) {
|
||
setError(reason instanceof Error ? reason.message : '测试发送失败')
|
||
} finally {
|
||
setTesting(false)
|
||
}
|
||
}
|
||
const attachDashboard = () => {
|
||
if (attaching || !confirmation) return
|
||
setError('')
|
||
setNotice('')
|
||
setAttaching(true)
|
||
setCapture(true)
|
||
}
|
||
const uploadCaptured = async (png: Blob) => {
|
||
try {
|
||
const bytes = await uploadWeeklyMailImage(week, png)
|
||
setNotice(`已附上统计看板图片(${Math.round(bytes / 1024)} KB),发送时放在正文末尾`)
|
||
await reload()
|
||
} catch (reason) {
|
||
setError(reason instanceof Error ? reason.message : '附图上传失败')
|
||
} finally {
|
||
setCapture(false)
|
||
setAttaching(false)
|
||
}
|
||
}
|
||
const failCaptured = (reason: unknown) => {
|
||
setError(reason instanceof Error ? reason.message : '看板图片生成失败')
|
||
setCapture(false)
|
||
setAttaching(false)
|
||
}
|
||
const stale = confirmation !== null && !confirmation.current
|
||
return (
|
||
<section className="qa-weekly-mail" aria-label="周报自动发送">
|
||
<header>
|
||
<h4>自动发送</h4>
|
||
<span className="qa-weekly-mail-state" data-state={!confirmation ? 'none' : stale ? 'stale' : 'confirmed'}>
|
||
{!confirmation
|
||
? '未确认'
|
||
: stale
|
||
? `已过期(确认于第${confirmation.draft_revision}版,正文已改,需重新确认)`
|
||
: `已确认 · 第${confirmation.draft_revision}版 · ${stamp(confirmation.confirmed_at)} · ${confirmation.confirmed_by}`}
|
||
</span>
|
||
<div className="qa-weekly-mail-actions">
|
||
{confirmation ? (
|
||
<button type="button" disabled={working || busy} onClick={() => void toggleConfirm(false)}>
|
||
取消确认
|
||
</button>
|
||
) : (
|
||
<button type="button" disabled={working || busy} onClick={() => void toggleConfirm(true)}>
|
||
确认本周周报
|
||
</button>
|
||
)}
|
||
{admin ? (
|
||
<>
|
||
<button type="button" disabled={working || testing} onClick={() => void testSend()}>
|
||
{testing ? '正在发送测试…' : '发送测试邮件'}
|
||
</button>
|
||
{confirmation?.has_image && !stale ? (
|
||
<button type="button" disabled={working || attaching} onClick={attachDashboard}>
|
||
{attaching ? '正在生成图片…' : '重新生成看板图片'}
|
||
</button>
|
||
) : null}
|
||
<button type="button" disabled={working} onClick={() => setEditing(!editing)}>
|
||
{editing ? '收起发送设置' : '发送设置'}
|
||
</button>
|
||
</>
|
||
) : null}
|
||
</div>
|
||
</header>
|
||
{error ? (
|
||
<p role="alert" className="error-banner">
|
||
{error}
|
||
</p>
|
||
) : null}
|
||
{notice ? <p role="status">{notice}</p> : null}
|
||
{settings ? (
|
||
<p className="qa-weekly-mail-summary">
|
||
{settings.enabled ? '自动发送已启用' : '自动发送未启用'} ·{' '}
|
||
{settings.host ? `${settings.host}:${settings.port}` : '未配置邮件服务器'} ·{' '}
|
||
{settings.recipients.length ? `${settings.recipients.length} 位收件人` : '未配置收件人'} ·{' '}
|
||
{weeklyMailWeekdayLabels[settings.weekday - 1] ?? '—'} {String(settings.hour).padStart(2, '0')}:00(北京时间)
|
||
{settings.has_password ? '' : ' · 未保存授权码'}
|
||
</p>
|
||
) : null}
|
||
{editing && settings ? (
|
||
<SettingsForm
|
||
settings={settings}
|
||
onSaved={(next) => {
|
||
setSettings(next)
|
||
setEditing(false)
|
||
setNotice('发送设置已保存')
|
||
}}
|
||
/>
|
||
) : null}
|
||
{capture ? <DashboardCapture week={week} onDone={uploadCaptured} onError={failCaptured} /> : null}
|
||
{sends.length ? (
|
||
<ul className="qa-weekly-mail-sends">
|
||
{sends.map((send) => (
|
||
<li key={send.week + ':' + send.draft_revision} data-status={send.status}>
|
||
{send.week} · 第{send.draft_revision}版 ·{' '}
|
||
{{ sending: '发送中', sent: '已发送', failed: '发送失败' }[send.status]} · {stamp(send.updated_at)}
|
||
{send.last_error ? ` · ${send.last_error}` : ''}
|
||
</li>
|
||
))}
|
||
</ul>
|
||
) : null}
|
||
</section>
|
||
)
|
||
}
|
||
|
||
function SettingsForm({
|
||
settings,
|
||
onSaved,
|
||
}: {
|
||
settings: WeeklyMailSettings
|
||
onSaved: (next: WeeklyMailSettings) => void
|
||
}) {
|
||
const [host, setHost] = useState(settings.host)
|
||
const [port, setPort] = useState(String(settings.port))
|
||
const [username, setUsername] = useState(settings.username)
|
||
const [password, setPassword] = useState('')
|
||
const [clearPassword, setClearPassword] = useState(false)
|
||
const [from, setFrom] = useState(settings.from)
|
||
const [recipients, setRecipients] = useState(settings.recipients.join('\n'))
|
||
const [cc, setCc] = useState(settings.cc_recipients.join('\n'))
|
||
const [review, setReview] = useState(settings.review_address)
|
||
const [weekday, setWeekday] = useState(settings.weekday)
|
||
const [hour, setHour] = useState(String(settings.hour))
|
||
const [enabled, setEnabled] = useState(settings.enabled)
|
||
const [error, setError] = useState('')
|
||
const [saving, setSaving] = useState(false)
|
||
|
||
const submit = async () => {
|
||
setSaving(true)
|
||
setError('')
|
||
try {
|
||
const next = await saveWeeklyMailSettings(settings.revision, {
|
||
host: host.trim(),
|
||
port: Number(port),
|
||
username: username.trim(),
|
||
password,
|
||
clear_password: clearPassword,
|
||
from: from.trim(),
|
||
recipients: splitAddresses(recipients),
|
||
cc_recipients: splitAddresses(cc),
|
||
review_address: review.trim(),
|
||
weekday,
|
||
hour: Number(hour),
|
||
enabled,
|
||
})
|
||
setPassword('')
|
||
onSaved(next)
|
||
} catch (reason) {
|
||
setError(reason instanceof Error ? reason.message : '保存失败')
|
||
} finally {
|
||
setSaving(false)
|
||
}
|
||
}
|
||
|
||
return (
|
||
<div className="qa-weekly-mail-form">
|
||
<label>
|
||
邮件服务器
|
||
<input value={host} onChange={(e) => setHost(e.target.value)} placeholder="smtp.example.com" />
|
||
</label>
|
||
<label>
|
||
端口
|
||
<input value={port} onChange={(e) => setPort(e.target.value)} inputMode="numeric" placeholder="465" />
|
||
</label>
|
||
<label>
|
||
账号
|
||
<input value={username} onChange={(e) => setUsername(e.target.value)} placeholder="kb@example.com" />
|
||
</label>
|
||
<label>
|
||
授权码
|
||
<input
|
||
type="password"
|
||
value={password}
|
||
onChange={(e) => {
|
||
setPassword(e.target.value)
|
||
setClearPassword(false)
|
||
}}
|
||
placeholder={settings.has_password ? '已保存,留空保持不变' : '首次配置需填写'}
|
||
autoComplete="new-password"
|
||
/>
|
||
</label>
|
||
{settings.has_password ? (
|
||
<label className="qa-weekly-mail-inline">
|
||
<input type="checkbox" checked={clearPassword} onChange={(e) => setClearPassword(e.target.checked)} />
|
||
清除已保存授权码
|
||
</label>
|
||
) : null}
|
||
<label>
|
||
发件地址
|
||
<input value={from} onChange={(e) => setFrom(e.target.value)} placeholder="kb@example.com" />
|
||
</label>
|
||
<label className="qa-weekly-mail-wide">
|
||
主送(每行一个)
|
||
<textarea rows={3} value={recipients} onChange={(e) => setRecipients(e.target.value)} />
|
||
</label>
|
||
<label className="qa-weekly-mail-wide">
|
||
抄送(每行一个,可留空)
|
||
<textarea rows={2} value={cc} onChange={(e) => setCc(e.target.value)} />
|
||
</label>
|
||
<label>
|
||
测试/审核邮箱
|
||
<input
|
||
value={review}
|
||
onChange={(e) => setReview(e.target.value)}
|
||
placeholder="只用于发送测试,不参与正式发送"
|
||
/>
|
||
</label>
|
||
<label>
|
||
发送日
|
||
<select value={weekday} onChange={(e) => setWeekday(Number(e.target.value))}>
|
||
{weeklyMailWeekdayLabels.map((label, index) => (
|
||
<option key={label} value={index + 1}>
|
||
{label}
|
||
</option>
|
||
))}
|
||
</select>
|
||
</label>
|
||
<label>
|
||
发送小时(北京时间)
|
||
<input value={hour} onChange={(e) => setHour(e.target.value)} inputMode="numeric" />
|
||
</label>
|
||
<label className="qa-weekly-mail-inline">
|
||
<input type="checkbox" checked={enabled} onChange={(e) => setEnabled(e.target.checked)} />
|
||
启用自动发送
|
||
</label>
|
||
<div className="qa-weekly-mail-submit">
|
||
<button type="button" disabled={saving} onClick={() => void submit()}>
|
||
{saving ? '保存中…' : '保存发送设置'}
|
||
</button>
|
||
<small>只在已确认、且该周已结束后发送一次;正文改动后确认失效。</small>
|
||
</div>
|
||
{error ? (
|
||
<p role="alert" className="error-banner">
|
||
{error}
|
||
</p>
|
||
) : null}
|
||
</div>
|
||
)
|
||
}
|
||
|
||
const splitAddresses = (value: string) =>
|
||
value
|
||
.split(/[\n,,;;]/)
|
||
.map((item) => item.trim())
|
||
.filter(Boolean)
|
||
|
||
// The chart is rendered off-screen from the same read-only dashboard data and
|
||
// attached to the confirmation, so the mail always shows what the operator saw.
|
||
function DashboardCapture({
|
||
week,
|
||
onDone,
|
||
onError,
|
||
}: {
|
||
week: string
|
||
onDone: (png: Blob) => void
|
||
onError: (reason: unknown) => void
|
||
}) {
|
||
const [data, setData] = useState<Awaited<ReturnType<typeof fetchQADashboard>> | null>(null)
|
||
const [error, setError] = useState('')
|
||
useEffect(() => {
|
||
const range = qaWeekQueryRange(Number(week.slice(0, 4)), Number(week.slice(6)))
|
||
void fetchQADashboard({
|
||
start: qaDateTimeToISO(range.start),
|
||
end: qaDateTimeToISO(range.end),
|
||
keyword: '',
|
||
cursor: '',
|
||
})
|
||
.then(setData)
|
||
.catch((reason) => {
|
||
setError(reason instanceof Error ? reason.message : '看板读取失败')
|
||
onError(reason)
|
||
})
|
||
}, [week, onError])
|
||
useEffect(() => {
|
||
if (!data) return
|
||
const timer = window.setTimeout(() => {
|
||
const svg = document.querySelector<SVGSVGElement>('#qa-dashboard-capture svg')
|
||
if (!svg) {
|
||
onError(new Error('看板尚未渲染完成,请重试'))
|
||
return
|
||
}
|
||
void createDashboardPNG(svg).then(onDone).catch(onError)
|
||
}, 600)
|
||
return () => window.clearTimeout(timer)
|
||
}, [data, onDone, onError])
|
||
return (
|
||
<div id="qa-dashboard-capture" aria-hidden="true" style={{ position: 'fixed', left: -10000, top: 0, width: 1280 }}>
|
||
<QADashboardView data={data} loading={!data && !error} error={error} onRetry={() => {}} />
|
||
</div>
|
||
)
|
||
}
|