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
+91
View File
@@ -7,6 +7,7 @@ import (
"knowledge-governance/internal/dobotaiops"
"knowledge-governance/internal/qawemail"
"net/http"
"strconv"
"time"
)
@@ -20,6 +21,96 @@ type weeklyMailStore interface {
TestSend(context.Context, string) (string, error)
SaveDashboardImage(context.Context, string, []byte) error
SendDue(context.Context, time.Time) (qawemail.DueResult, error)
PreviewSend(context.Context, string, int64, string, time.Time) (qawemail.SendPreview, error)
SendManual(context.Context, string, int64, string, string, time.Time) (qawemail.ManualResult, error)
}
// weeklyMailSendError names the rule that refused a manual resend. Anything SMTP-related is
// reported by the handler itself, so an unmet precondition never looks like a mail failure.
func weeklyMailSendError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, qawemail.ErrNotCurrent):
writeJSON(w, http.StatusConflict, map[string]string{"error": "该周周报未确认,或确认后正文/版本已变化;请先确认当前版本再补发"})
case errors.Is(err, qawemail.ErrFutureWeek):
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "不能补发未来周"})
case errors.Is(err, qawemail.ErrSlotPending):
writeJSON(w, http.StatusConflict, map[string]string{"error": "本周尚未到达设定的发送时点,暂不能补发"})
case errors.Is(err, qawemail.ErrNotConfigured):
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "未配置邮件服务器、发件人或收件人,无法补发"})
case errors.Is(err, qawemail.ErrSendInFlight):
writeJSON(w, http.StatusConflict, map[string]string{"error": "该周该版本有一次发送结果未知(记录停在发送中),为避免重复投递未重发;请先核对已发出的邮件"})
case errors.Is(err, qawemail.ErrNoPassword):
writeJSON(w, http.StatusConflict, map[string]string{"error": "SMTP 授权码缺失或无法解密,无法补发"})
case errors.Is(err, qawemail.ErrInvalid):
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "补发参数无效:需要精确的周、已确认版本与正文 hash"})
default:
weeklyMailError(w, err)
}
}
// qaWeeklyMailSendPreview lets the confirmation dialog show the exact week, revision and
// distribution this send would use — the same settings the send path reads.
func qaWeeklyMailSendPreview(w http.ResponseWriter, r *http.Request, c Config) {
if !authorizeQAOps(w, r) {
return
}
store, ok := c.QAWeeklyMail.(weeklyMailStore)
if !ok {
weeklyMailError(w, qawemail.ErrUnavailable)
return
}
query := r.URL.Query()
revision, err := strconv.ParseInt(query.Get("revision"), 10, 64)
if err != nil {
weeklyMailSendError(w, qawemail.ErrInvalid)
return
}
preview, err := store.PreviewSend(r.Context(), r.PathValue("week"), revision, query.Get("body_sha256"), time.Now())
if err != nil {
weeklyMailSendError(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"data": preview})
}
// qaWeeklyMailSend is the formal resend: admin only, bound to the live confirmation, and the same
// render/claim path as the automatic slot. It is not a test send and never targets the review box.
func qaWeeklyMailSend(w http.ResponseWriter, r *http.Request, c Config) {
if !authorizeQAOps(w, r) || !authorizeQAIntent(w, r, "qa-weekly-mail") {
return
}
identity, ok := sessionFrom(r.Context())
if !ok || identity.Role != "admin" {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "仅管理员可正式补发周报"})
return
}
store, found := c.QAWeeklyMail.(weeklyMailStore)
if !found {
weeklyMailError(w, qawemail.ErrUnavailable)
return
}
var request struct {
Revision int64 `json:"revision"`
BodySHA256 string `json:"body_sha256"`
}
if decodeQualityJSON(w, r, &request) != nil {
weeklyMailError(w, qawemail.ErrInvalid)
return
}
result, err := store.SendManual(r.Context(), r.PathValue("week"), request.Revision, request.BodySHA256, identity.Username, time.Now())
if err != nil {
weeklyMailSendError(w, err)
return
}
if result.Status == "failed" {
reason := result.Reason
if len(reason) > 300 {
reason = reason[:300]
}
writeJSON(w, http.StatusBadGateway, map[string]string{"error": "正式补发未送达:" + reason})
return
}
writeJSON(w, http.StatusOK, map[string]any{"data": result})
}
func weeklyMailError(w http.ResponseWriter, err error) {
+186
View File
@@ -0,0 +1,186 @@
package httpapi
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"knowledge-governance/internal/qawemail"
)
type fakeWeeklyMailStore struct {
preview qawemail.SendPreview
previewErr error
result qawemail.ManualResult
sendErr error
calls int
lastWeek string
lastRev int64
lastHash string
lastActor string
}
func (f *fakeWeeklyMailStore) ReadSettings(context.Context) (qawemail.Settings, error) {
return qawemail.Settings{}, nil
}
func (f *fakeWeeklyMailStore) SaveSettings(context.Context, string, qawemail.SettingsInput) (qawemail.Settings, error) {
return qawemail.Settings{}, nil
}
func (f *fakeWeeklyMailStore) Confirm(context.Context, string, string) (qawemail.Confirmation, error) {
return qawemail.Confirmation{}, nil
}
func (f *fakeWeeklyMailStore) Unconfirm(context.Context, string) error { return nil }
func (f *fakeWeeklyMailStore) ReadConfirmation(context.Context, string) (*qawemail.Confirmation, error) {
return nil, nil
}
func (f *fakeWeeklyMailStore) Sends(context.Context, string) ([]qawemail.Send, error) {
return nil, nil
}
func (f *fakeWeeklyMailStore) TestSend(context.Context, string) (string, error) { return "", nil }
func (f *fakeWeeklyMailStore) SaveDashboardImage(context.Context, string, []byte) error {
return nil
}
func (f *fakeWeeklyMailStore) SendDue(context.Context, time.Time) (qawemail.DueResult, error) {
return qawemail.DueResult{}, nil
}
func (f *fakeWeeklyMailStore) PreviewSend(_ context.Context, week string, revision int64, hash string, _ time.Time) (qawemail.SendPreview, error) {
f.lastWeek, f.lastRev, f.lastHash = week, revision, hash
if f.previewErr != nil {
return qawemail.SendPreview{}, f.previewErr
}
out := f.preview
out.Week, out.Revision, out.BodySHA256 = week, revision, hash
return out, nil
}
func (f *fakeWeeklyMailStore) SendManual(_ context.Context, week string, revision int64, hash, actor string, _ time.Time) (qawemail.ManualResult, error) {
f.calls++
f.lastWeek, f.lastRev, f.lastHash, f.lastActor = week, revision, hash, actor
if f.sendErr != nil {
return qawemail.ManualResult{}, f.sendErr
}
out := f.result
out.Week, out.Revision = week, revision
return out, nil
}
func weeklyMailSendRequest(t *testing.T, role, body string, withIntent bool) *http.Request {
t.Helper()
request := httptest.NewRequest(http.MethodPost, "/api/v1/qa-ops/master/weekly-mail/send/2026-W45", strings.NewReader(body))
request.SetPathValue("week", "2026-W45")
request = request.WithContext(context.WithValue(request.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: role}))
if withIntent {
request.Header.Set("X-Governance-Action", "qa-weekly-mail")
}
return request
}
// 正式补发是管理员动作:普通角色与缺少同源意图都必须被挡在 SMTP 之前。
func TestWeeklyMailFormalSendRequiresAdminAndIntent(t *testing.T) {
store := &fakeWeeklyMailStore{result: qawemail.ManualResult{Status: "sent", MessageID: "<m@example.com>"}}
config := Config{QAWeeklyMail: store}
body := `{"revision":16,"body_sha256":"` + strings.Repeat("a", 64) + `"}`
recorder := httptest.NewRecorder()
qaWeeklyMailSend(recorder, weeklyMailSendRequest(t, "engineer", body, true), config)
if recorder.Code != http.StatusForbidden {
t.Fatalf("非管理员必须 403,status=%d body=%s", recorder.Code, recorder.Body.String())
}
recorder = httptest.NewRecorder()
qaWeeklyMailSend(recorder, weeklyMailSendRequest(t, roleAdmin, body, false), config)
if recorder.Code != http.StatusForbidden {
t.Fatalf("缺少同源操作意图必须 403,status=%d body=%s", recorder.Code, recorder.Body.String())
}
if store.calls != 0 {
t.Fatalf("被拒请求不得调用发送:calls=%d", store.calls)
}
}
// 成功补发必须把 week/版本/hash/操作人原样交给 store,并回传真实 message_id 与收件人数。
func TestWeeklyMailFormalSendPassesExactRevisionAndReturnsReceipt(t *testing.T) {
store := &fakeWeeklyMailStore{result: qawemail.ManualResult{Status: "sent", MessageID: "<real@example.com>", Recipients: 119, Cc: 8}}
config := Config{QAWeeklyMail: store}
hash := strings.Repeat("b", 64)
recorder := httptest.NewRecorder()
qaWeeklyMailSend(recorder, weeklyMailSendRequest(t, roleAdmin, `{"revision":16,"body_sha256":"`+hash+`"}`, true), config)
if recorder.Code != http.StatusOK {
t.Fatalf("管理员补发应成功,status=%d body=%s", recorder.Code, recorder.Body.String())
}
if store.lastWeek != "2026-W45" || store.lastRev != 16 || store.lastHash != hash || store.lastActor != "tester" {
t.Fatalf("补发参数没有精确传递:week=%q rev=%d hash=%q actor=%q", store.lastWeek, store.lastRev, store.lastHash, store.lastActor)
}
var payload struct {
Data qawemail.ManualResult `json:"data"`
}
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if payload.Data.MessageID != "<real@example.com>" || payload.Data.Recipients != 119 || payload.Data.Cc != 8 {
t.Fatalf("响应必须带回真实发送凭据与正式收件人数:%+v", payload.Data)
}
}
// 前置条件不满足必须给出具体原因,而不是冒充 SMTP 失败。
func TestWeeklyMailFormalSendExplainsRefusalsInsteadOfSMTPFailure(t *testing.T) {
cases := []struct {
name string
err error
status int
contains string
}{
{"future", qawemail.ErrFutureWeek, http.StatusBadRequest, "未来周"},
{"slot", qawemail.ErrSlotPending, http.StatusConflict, "尚未到达设定的发送时点"},
{"stale", qawemail.ErrNotCurrent, http.StatusConflict, "正文/版本已变化"},
{"inflight", qawemail.ErrSendInFlight, http.StatusConflict, "结果未知"},
{"nopassword", qawemail.ErrNoPassword, http.StatusConflict, "授权码"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
store := &fakeWeeklyMailStore{sendErr: tc.err}
recorder := httptest.NewRecorder()
qaWeeklyMailSend(recorder, weeklyMailSendRequest(t, roleAdmin, `{"revision":16,"body_sha256":"`+strings.Repeat("c", 64)+`"}`, true), Config{QAWeeklyMail: store})
if recorder.Code != tc.status || !strings.Contains(recorder.Body.String(), tc.contains) {
t.Fatalf("%s 应 %d 且说明原因 %q,status=%d body=%s", tc.name, tc.status, tc.contains, recorder.Code, recorder.Body.String())
}
})
}
}
// SMTP 真实失败:必须 502 且带上真实原因,绝不能回“已发送”。
func TestWeeklyMailFormalSendReportsDeliveryFailure(t *testing.T) {
store := &fakeWeeklyMailStore{result: qawemail.ManualResult{Status: "failed", Reason: "发送失败:smtp 登录失败: 535"}}
recorder := httptest.NewRecorder()
qaWeeklyMailSend(recorder, weeklyMailSendRequest(t, roleAdmin, `{"revision":16,"body_sha256":"`+strings.Repeat("d", 64)+`"}`, true), Config{QAWeeklyMail: store})
if recorder.Code != http.StatusBadGateway || !strings.Contains(recorder.Body.String(), "535") {
t.Fatalf("未送达必须 502 并带真实原因,status=%d body=%s", recorder.Code, recorder.Body.String())
}
}
// 补发前预览必须给出真实 week/版本/收件人数,用于确认框;预览本身不投递。
func TestWeeklyMailSendPreviewShowsExactDistribution(t *testing.T) {
store := &fakeWeeklyMailStore{preview: qawemail.SendPreview{Status: "ready", Recipients: 119, Cc: 8}}
hash := strings.Repeat("e", 64)
request := httptest.NewRequest(http.MethodGet, "/api/v1/qa-ops/master/weekly-mail/send/2026-W45?revision=16&body_sha256="+hash, nil)
request.SetPathValue("week", "2026-W45")
request = request.WithContext(context.WithValue(request.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin}))
recorder := httptest.NewRecorder()
qaWeeklyMailSendPreview(recorder, request, Config{QAWeeklyMail: store})
if recorder.Code != http.StatusOK {
t.Fatalf("预览应成功,status=%d body=%s", recorder.Code, recorder.Body.String())
}
var payload struct {
Data qawemail.SendPreview `json:"data"`
}
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if payload.Data.Recipients != 119 || payload.Data.Cc != 8 || payload.Data.Revision != 16 || payload.Data.Status != "ready" {
t.Fatalf("预览必须给出正式收件人数与版本:%+v", payload.Data)
}
if store.calls != 0 {
t.Fatal("预览不得触发发送")
}
}
+2
View File
@@ -282,6 +282,8 @@ func NewHandler(config Config) (http.Handler, error) {
mux.HandleFunc("DELETE /api/v1/qa-ops/master/weekly-mail/confirmations/{week}", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailConfirm(w, r, config) })
mux.HandleFunc("GET /api/v1/qa-ops/master/weekly-mail/sends", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailSends(w, r, config) })
mux.HandleFunc("POST /api/v1/qa-ops/master/weekly-mail/test", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailTest(w, r, config) })
mux.HandleFunc("GET /api/v1/qa-ops/master/weekly-mail/send/{week}", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailSendPreview(w, r, config) })
mux.HandleFunc("POST /api/v1/qa-ops/master/weekly-mail/send/{week}", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailSend(w, r, config) })
mux.HandleFunc("POST /api/v1/qa-ops/master/weekly-mail/confirmations/{week}/image", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailImage(w, r, config) })
mux.HandleFunc("GET /api/v1/qa-ops/master/field-options", func(w http.ResponseWriter, r *http.Request) { qaMasterFieldOptions(w, r, config) })
mux.HandleFunc("POST /api/v1/qa-ops/master/records/{id}/fields", func(w http.ResponseWriter, r *http.Request) { qaMasterFieldPatch(w, r, config) })