fix(qa-weekly-mail): 修复周日发送窗口并提供正式补发
build / build (push) Successful in 3m5s

根因: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 项全绿。
This commit is contained in:
姚章浩
2026-11-09 00:48:33 +08:00
parent 9d445f4953
commit 719876d039
15 changed files with 1395 additions and 54 deletions
+75 -1
View File
@@ -9,12 +9,14 @@ import {
fetchWeeklyMailConfirmation,
fetchWeeklyMailSends,
fetchWeeklyMailSettings,
previewWeeklyMailSend,
saveWeeklyMailSettings,
sendWeeklyMailFormal,
sendWeeklyMailTest,
uploadWeeklyMailImage,
weeklyMailWeekdayLabels,
} from './qaWeeklyMail'
import type { WeeklyMailConfirmation, WeeklyMailSend, WeeklyMailSettings } 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 }) : '—')
@@ -32,6 +34,9 @@ export function QAWeeklyMail({ week, busy }: { week: string; busy: boolean }) {
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('')
@@ -91,6 +96,44 @@ export function QAWeeklyMail({ week, busy }: { week: string; busy: boolean }) {
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('')
@@ -142,6 +185,15 @@ export function QAWeeklyMail({ week, busy }: { week: string; busy: boolean }) {
<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 ? '正在生成图片…' : '重新生成看板图片'}
@@ -160,6 +212,27 @@ export function QAWeeklyMail({ week, busy }: { week: string; busy: boolean }) {
</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 ? '自动发送已启用' : '自动发送未启用'} ·{' '}
@@ -187,6 +260,7 @@ export function QAWeeklyMail({ week, busy }: { week: string; busy: boolean }) {
{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>
+16
View File
@@ -50,6 +50,22 @@
.qa-weekly-mail-sends li[data-status='sent'] {
color: #2d704d;
}
/* 正式补发是不可撤回的投递:与普通提示区分开,避免误点。 */
.qa-weekly-mail-confirm {
display: flex;
flex-direction: column;
gap: 8px;
padding: 10px 12px;
border: 1px solid #f0c36d;
border-radius: 8px;
background: #fffaeb;
font-size: 13px;
color: #5b3d00;
}
.qa-weekly-mail-confirm p {
margin: 0;
line-height: 1.6;
}
.qa-weekly-mail-form {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
+74 -1
View File
@@ -1,6 +1,12 @@
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, expect, it } from 'vitest'
import { parseWeeklyMailConfirmation, parseWeeklyMailSends, parseWeeklyMailSettings } from './qaWeeklyMail'
import {
parseWeeklyMailConfirmation,
parseWeeklyMailFormalResult,
parseWeeklyMailSendPreview,
parseWeeklyMailSends,
parseWeeklyMailSettings,
} from './qaWeeklyMail'
import { QAWeeklyMail } from './QAWeeklyMail'
const settings = {
@@ -72,5 +78,72 @@ it('shows the confirmation gate before any automatic send controls', () => {
expect(html).toContain('未确认')
expect(html).toContain('确认本周周报')
expect(html).not.toContain('立即发送')
expect(html).not.toContain('正式补发')
expect(html).not.toContain('发送设置')
})
describe('weekly mail formal resend contract', () => {
it('shows the real distribution and revision in the pre-send preview', () => {
const preview = parseWeeklyMailSendPreview(
{
week: '2026-W45',
draft_revision: 16,
body_sha256: 'a'.repeat(64),
recipients: 119,
cc_recipients: 8,
status: 'ready',
},
'2026-W45'
)
expect(preview).toMatchObject({ recipients: 119, cc_recipients: 8, draft_revision: 16, status: 'ready' })
expect(() => parseWeeklyMailSendPreview({ ...preview, status: 'queued' }, '2026-W45')).toThrow()
expect(() => parseWeeklyMailSendPreview({ ...preview, week: '2026-W44' }, '2026-W45')).toThrow()
})
it('never reports success without a real message id', () => {
const sent = parseWeeklyMailFormalResult(
{
week: '2026-W45',
draft_revision: 16,
status: 'sent',
message_id: '<real@example.com>',
recipients: 119,
cc_recipients: 8,
},
'2026-W45'
)
expect(sent.message_id).toBe('<real@example.com>')
expect(() =>
parseWeeklyMailFormalResult(
{ week: '2026-W45', draft_revision: 16, status: 'sent', message_id: '', recipients: 119, cc_recipients: 8 },
'2026-W45'
)
).toThrow()
expect(() =>
parseWeeklyMailFormalResult(
{
week: '2026-W45',
draft_revision: 16,
status: 'failed',
message_id: '<x@y>',
recipients: 1,
cc_recipients: 0,
},
'2026-W45'
)
).toThrow()
})
it('keeps the read-back message id on the send history', () => {
const [send] = parseWeeklyMailSends([
{
week: '2026-W45',
draft_revision: 16,
status: 'sent',
attempts: 1,
last_error: '',
message_id: '<real@example.com>',
updated_at: '2026-11-09T00:32:00+08:00',
},
])
expect(send.message_id).toBe('<real@example.com>')
})
})
+77
View File
@@ -33,9 +33,30 @@ export interface WeeklyMailSend {
status: 'sending' | 'sent' | 'failed'
attempts: number
last_error: string
message_id: string
updated_at: string
}
// 正式补发前的核对结果:确认框显示真实收件人数,而不是测试邮箱。
export interface WeeklyMailSendPreview {
week: string
draft_revision: number
body_sha256: string
recipients: number
cc_recipients: number
status: 'ready' | 'already_sent' | 'in_flight'
message_id: string
}
export interface WeeklyMailFormalResult {
week: string
draft_revision: number
status: 'sent' | 'already_sent'
message_id: string
recipients: number
cc_recipients: number
}
const bad = (): never => {
throw new Error('周报邮件响应无效,未显示或未标记为已保存')
}
@@ -99,11 +120,44 @@ export function parseWeeklyMailSends(value: unknown): WeeklyMailSend[] {
status: v.status as WeeklyMailSend['status'],
attempts: num(v.attempts),
last_error: str(v.last_error),
message_id: typeof v.message_id === 'string' ? v.message_id : '',
updated_at: str(v.updated_at),
}
})
}
export function parseWeeklyMailSendPreview(value: unknown, week: string): WeeklyMailSendPreview {
const v = obj(value)
if (v.week !== week) return bad()
if (!['ready', 'already_sent', 'in_flight'].includes(str(v.status))) return bad()
return {
week,
draft_revision: num(v.draft_revision),
body_sha256: str(v.body_sha256),
recipients: num(v.recipients),
cc_recipients: num(v.cc_recipients),
status: v.status as WeeklyMailSendPreview['status'],
message_id: typeof v.message_id === 'string' ? v.message_id : '',
}
}
export function parseWeeklyMailFormalResult(value: unknown, week: string): WeeklyMailFormalResult {
const v = obj(value)
if (v.week !== week) return bad()
if (!['sent', 'already_sent'].includes(str(v.status))) return bad()
// 没有 message_id 的“成功”是假成功:必须当作无效响应。
const messageID = str(v.message_id)
if (!messageID) return bad()
return {
week,
draft_revision: num(v.draft_revision),
status: v.status as WeeklyMailFormalResult['status'],
message_id: messageID,
recipients: num(v.recipients),
cc_recipients: num(v.cc_recipients),
}
}
const endpoint = (path: string, week?: string) =>
`/api/v1/qa-ops/master/weekly-mail/${path}${week ? '/' + encodeURIComponent(week) : ''}`
const headers = { 'Content-Type': 'application/json', 'X-Governance-Action': 'qa-weekly-mail' }
@@ -173,6 +227,29 @@ export async function sendWeeklyMailTest(week: string): Promise<string> {
return payload.message_id
}
export async function previewWeeklyMailSend(
week: string,
revision: number,
bodySHA256: string
): Promise<WeeklyMailSendPreview> {
const query = new URLSearchParams({ revision: String(revision), body_sha256: bodySHA256 }).toString()
return parseWeeklyMailSendPreview(await getPayload(endpoint('send', week) + '?' + query), week)
}
// 正式补发:用当前已确认的版本+hash 精确投递,成功后由服务端写入正式发送记录。
export async function sendWeeklyMailFormal(
week: string,
revision: number,
bodySHA256: string
): Promise<WeeklyMailFormalResult> {
const payload = await getPayload(endpoint('send', week), undefined, {
method: 'POST',
headers,
body: JSON.stringify({ revision, body_sha256: bodySHA256 }),
})
return parseWeeklyMailFormalResult(payload, week)
}
export async function uploadWeeklyMailImage(week: string, png: Blob): Promise<number> {
const buffer = await png.arrayBuffer()
let binary = ''