Files
knowledge-governance/web/src/QAWeeklyMail.tsx
T
姚章浩 719876d039
build / build (push) Successful in 3m5s
fix(qa-weekly-mail): 修复周日发送窗口并提供正式补发
根因:SendDue 同时要求“已到配置时段”与“该周已结束(下周一00:00)”。周日23点的时段
只在周内存在,当周周报永远不满足“已结束”,于是 11/08 23:00 只报 nothing_confirmed、
11/09 00:00 又已成 not_due —— 邮件从未尝试发送,与 SMTP 凭据/网络无关。

改法(最小、不碰历史发布模块):
1. 由发送窗口反推要发的周:周日窗口发当天结束的那一周,其它工作日仍发上一完整周
   (周一09:00 语义不变)。自动发送只处理这一周,不再按“所有已结束的周”回填。
2. 认领改为只重认 failed(或首次)记录:sent 幂等返回真实 message_id;sending 视为
   结果未知,拒绝盲重发并提示核对邮箱。自动与手工共用同一条渲染/认领/投递路径,
   并发或重复点击只投递一次;失败如实写 failed,不假写 sent。
3. 新增管理员正式补发(页面按钮 + GET 预览 + POST /weekly-mail/send/{week}):精确指定
   周、已确认版本与正文 hash,必须同源操作意图;未来周拒绝,当前周须到设定时点,
   已结束周可显式补发。正文/看板图片/主送/抄送与自动发送一致,结果写入正式发送记录。
   这不是“发送测试邮件”(只发 review 地址、不登记)。

验证:真实隔离 PostgreSQL(kg-pgtest-writeset 上的独立一次性库)先 RED(旧实现真实
复现 nothing_confirmed)后 GREEN;覆盖到点前/未来周/未确认/正文变化、周一语义保持、
手工补发一次并读回 message_id、并发只投递一次、结果未知不重发、失败可重试一次。
HTTP 与前端解析用例通过;make verify 17 项全绿。
2026-11-09 00:48:33 +08:00

458 lines
17 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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,
previewWeeklyMailSend,
saveWeeklyMailSettings,
sendWeeklyMailFormal,
sendWeeklyMailTest,
uploadWeeklyMailImage,
weeklyMailWeekdayLabels,
} from './qaWeeklyMail'
import type { WeeklyMailConfirmation, WeeklyMailSend, WeeklyMailSendPreview, 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 [preparingResend, setPreparingResend] = useState(false)
const [resendConfirm, setResendConfirm] = useState<WeeklyMailSendPreview | null>(null)
const [resending, setResending] = 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 prepareResend = async () => {
if (preparingResend || !confirmation?.current) return
setPreparingResend(true)
setError('')
setNotice('')
try {
setResendConfirm(await previewWeeklyMailSend(week, confirmation.draft_revision, confirmation.body_sha256))
} catch (reason) {
setError(reason instanceof Error ? reason.message : '补发前核对失败')
} finally {
setPreparingResend(false)
}
}
const confirmResend = async () => {
if (resending || !resendConfirm) return
setResending(true)
setError('')
setNotice('')
try {
const result = await sendWeeklyMailFormal(
resendConfirm.week,
resendConfirm.draft_revision,
resendConfirm.body_sha256
)
setNotice(
result.status === 'already_sent'
? `该周第${result.draft_revision}版此前已发送(${result.message_id}),本次未重复投递`
: `已正式补发 ${result.week} 第${result.draft_revision}版给 ${result.recipients} 位收件人、${result.cc_recipients} 位抄送(${result.message_id})`
)
setResendConfirm(null)
setSends(await fetchWeeklyMailSends(week))
} catch (reason) {
setError(reason instanceof Error ? reason.message : '正式补发失败')
} finally {
setResending(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?.current ? (
<button
type="button"
disabled={working || preparingResend || resending}
onClick={() => void prepareResend()}
>
{preparingResend ? '正在核对…' : '正式补发…'}
</button>
) : null}
{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}
{resendConfirm ? (
<div className="qa-weekly-mail-confirm" role="alertdialog" aria-label="确认正式补发">
<p>
将<b>正式补发</b>《知识库周报 {resendConfirm.week}》第{resendConfirm.draft_revision}版给{' '}
{resendConfirm.recipients} 位收件人、{resendConfirm.cc_recipients} 位抄送(正式名单,不是测试邮箱),
并写入正式发送记录。
{resendConfirm.status === 'already_sent' ? '该版本已有发送记录,确认后只读回结果、不会重复投递。' : ''}
{resendConfirm.status === 'in_flight'
? '该版本上次发送结果未知,服务端会拒绝重发,请先核对已发出的邮件。'
: ''}
</p>
<div className="qa-weekly-mail-actions">
<button type="button" disabled={resending} onClick={() => void confirmResend()}>
{resending ? '正在补发…' : '确认正式补发'}
</button>
<button type="button" disabled={resending} onClick={() => setResendConfirm(null)}>
取消
</button>
</div>
</div>
) : 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}` : ''}
{send.message_id ? ` · ${send.message_id}` : ''}
</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>
)
}