feat(qa): 周报邮件区分主送抄送并附统计看板图片
build / build (push) Successful in 1m21s

设置新增抄送列表,MIME 增加 Cc 头、envelope 同时投递主送与抄送,同一地址不得同时出现在两边。
确认后可保存统计看板 PNG(multipart/related + cid),发送时放在正文末尾内联显示;正文改动使确认失效后不再使用旧图。
This commit is contained in:
hermes
2026-10-26 15:59:06 +08:00
parent 600e9a2dc2
commit 822fb652ff
13 changed files with 325 additions and 25 deletions
+39
View File
@@ -2,6 +2,7 @@ package httpapi
import (
"context"
"encoding/base64"
"errors"
"knowledge-governance/internal/dobotaiops"
"knowledge-governance/internal/qawemail"
@@ -17,6 +18,7 @@ type weeklyMailStore interface {
ReadConfirmation(context.Context, string) (*qawemail.Confirmation, error)
Sends(context.Context, string) ([]qawemail.Send, error)
TestSend(context.Context, string) (string, error)
SaveDashboardImage(context.Context, string, []byte) error
SendDue(context.Context, time.Time) (qawemail.DueResult, error)
}
@@ -172,3 +174,40 @@ func qaWeeklyMailTest(w http.ResponseWriter, r *http.Request, c Config) {
}
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"sent": true, "week": request.Week, "message_id": messageID}})
}
func qaWeeklyMailImage(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 {
PNGBase64 string `json:"png_base64"`
}
if decodeQualityJSON(w, r, &request) != nil {
weeklyMailError(w, qawemail.ErrInvalid)
return
}
png, err := base64.StdEncoding.DecodeString(request.PNGBase64)
if err != nil || len(png) < 8 || len(png) > 8<<20 {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "图片无效或超过 8MB"})
return
}
if err := store.SaveDashboardImage(r.Context(), r.PathValue("week"), png); err != nil {
if errors.Is(err, qawemail.ErrInvalid) {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "请先确认本周周报,再附上统计看板图片"})
return
}
weeklyMailError(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"saved": true, "bytes": len(png)}})
}
+1
View File
@@ -211,6 +211,7 @@ 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("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) })
mux.HandleFunc("GET /api/v1/qa-ops/master/records", func(w http.ResponseWriter, r *http.Request) { withQAMaster(w, r, config, listQAOpsRecords) })
@@ -0,0 +1 @@
alter table qa_weekly_email_settings drop column if exists cc_recipients;
@@ -0,0 +1,2 @@
-- 主送与抄送分开:抄送只影响收件头与 envelope,不影响发送规则。
alter table qa_weekly_email_settings add column if not exists cc_recipients text[] not null default '{}';
@@ -0,0 +1,3 @@
alter table qa_weekly_confirmations drop column if exists dashboard_saved_at;
alter table qa_weekly_confirmations drop column if exists dashboard_sha256;
alter table qa_weekly_confirmations drop column if exists dashboard_png;
@@ -0,0 +1,4 @@
-- 周报邮件附图:确认时保存当时导出的看板 PNG,发送时作为内嵌图片放在正文之后。
alter table qa_weekly_confirmations add column if not exists dashboard_png bytea;
alter table qa_weekly_confirmations add column if not exists dashboard_sha256 text not null default '';
alter table qa_weekly_confirmations add column if not exists dashboard_saved_at timestamptz;
@@ -11,8 +11,8 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
if err != nil {
t.Fatalf("loadMigrations() error = %v", err)
}
if len(migrations) != 60 {
t.Fatalf("migration count = %d, want 60", len(migrations))
if len(migrations) != 62 {
t.Fatalf("migration count = %d, want 62", len(migrations))
}
if migrations[0].Version != 1 || !strings.Contains(migrations[0].UpSQL, "CREATE TABLE IF NOT EXISTS jobs") {
t.Fatalf("migration 1 = %#v", migrations[0])
+127 -18
View File
@@ -38,6 +38,7 @@ type Settings struct {
Username string `json:"username"`
From string `json:"from"`
Recipients []string `json:"recipients"`
Cc []string `json:"cc_recipients"`
Weekday int `json:"weekday"`
Hour int `json:"hour"`
Enabled bool `json:"enabled"`
@@ -56,6 +57,7 @@ type SettingsInput struct {
ClearPassword bool `json:"clear_password"`
From string `json:"from"`
Recipients []string `json:"recipients"`
Cc []string `json:"cc_recipients"`
Weekday int `json:"weekday"`
Hour int `json:"hour"`
Enabled bool `json:"enabled"`
@@ -63,6 +65,7 @@ type SettingsInput struct {
type Confirmation struct {
Week string `json:"week"`
HasImage bool `json:"has_image"`
DraftRevision int64 `json:"draft_revision"`
BodySHA256 string `json:"body_sha256"`
ConfirmedBy string `json:"confirmed_by"`
@@ -79,12 +82,23 @@ type Send struct {
UpdatedAt time.Time `json:"updated_at"`
}
// InlineImage is embedded with a Content-ID so clients show it inside the body
// instead of as a detached attachment.
type InlineImage struct {
Name string
ContentType string
CID string
Bytes []byte
}
type Message struct {
To []string
Cc []string
From string
Subject string
HTML string
Text string
Images []InlineImage
}
// Mailer is the only outbound dependency; tests substitute it to prove the exact wire payload.
@@ -193,6 +207,20 @@ func normalize(input SettingsInput) (SettingsInput, error) {
recipients = append(recipients, address)
}
input.Recipients = recipients
cc := make([]string, 0, len(input.Cc))
for _, raw := range input.Cc {
address := strings.TrimSpace(raw)
if address == "" {
continue
}
// A copy that is also a primary recipient would receive the mail twice.
if !validAddress(address) || seen[strings.ToLower(address)] {
return input, ErrInvalid
}
seen[strings.ToLower(address)] = true
cc = append(cc, address)
}
input.Cc = cc
if input.Host != "" && !strings.Contains(input.Host, " ") && !strings.Contains(input.Host, "/") {
if _, err := net.LookupHost(input.Host); err != nil {
// A host that does not resolve yet stays a validation error, not a silent no-op.
@@ -217,13 +245,13 @@ func normalize(input SettingsInput) (SettingsInput, error) {
}
func (s *Store) ReadSettings(ctx context.Context) (Settings, error) {
out := Settings{Port: 465, Weekday: 1, Hour: 9, Recipients: []string{}}
out := Settings{Port: 465, Weekday: 1, Hour: 9, Recipients: []string{}, Cc: []string{}}
if !s.valid() {
return out, ErrUnavailable
}
var sealed []byte
err := s.pool.QueryRow(ctx, `SELECT smtp_host,smtp_port,smtp_username,smtp_password_sealed,from_address,recipients,send_weekday,send_hour,enabled,revision,updated_by,updated_at FROM qa_weekly_email_settings WHERE tenant_key=$1`, s.tenant).
Scan(&out.Host, &out.Port, &out.Username, &sealed, &out.From, &out.Recipients, &out.Weekday, &out.Hour, &out.Enabled, &out.Revision, &out.UpdatedBy, &out.UpdatedAt)
err := s.pool.QueryRow(ctx, `SELECT smtp_host,smtp_port,smtp_username,smtp_password_sealed,from_address,recipients,cc_recipients,send_weekday,send_hour,enabled,revision,updated_by,updated_at FROM qa_weekly_email_settings WHERE tenant_key=$1`, s.tenant).
Scan(&out.Host, &out.Port, &out.Username, &sealed, &out.From, &out.Recipients, &out.Cc, &out.Weekday, &out.Hour, &out.Enabled, &out.Revision, &out.UpdatedBy, &out.UpdatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return out, nil
}
@@ -233,6 +261,9 @@ func (s *Store) ReadSettings(ctx context.Context) (Settings, error) {
if out.Recipients == nil {
out.Recipients = []string{}
}
if out.Cc == nil {
out.Cc = []string{}
}
out.HasPassword = len(sealed) > 0
return out, nil
}
@@ -273,10 +304,10 @@ func (s *Store) SaveSettings(ctx context.Context, actor string, input SettingsIn
return Settings{}, err
}
}
if _, err = tx.Exec(ctx, `INSERT INTO qa_weekly_email_settings(tenant_key,smtp_host,smtp_port,smtp_username,smtp_password_sealed,from_address,recipients,send_weekday,send_hour,enabled,revision,updated_by,updated_at)
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,now())
ON CONFLICT (tenant_key) DO UPDATE SET smtp_host=excluded.smtp_host,smtp_port=excluded.smtp_port,smtp_username=excluded.smtp_username,smtp_password_sealed=excluded.smtp_password_sealed,from_address=excluded.from_address,recipients=excluded.recipients,send_weekday=excluded.send_weekday,send_hour=excluded.send_hour,enabled=excluded.enabled,revision=excluded.revision,updated_by=excluded.updated_by,updated_at=now()`,
s.tenant, normalized.Host, normalized.Port, normalized.Username, sealed, normalized.From, normalized.Recipients, normalized.Weekday, normalized.Hour, normalized.Enabled, next, actor); err != nil {
if _, err = tx.Exec(ctx, `INSERT INTO qa_weekly_email_settings(tenant_key,smtp_host,smtp_port,smtp_username,smtp_password_sealed,from_address,recipients,cc_recipients,send_weekday,send_hour,enabled,revision,updated_by,updated_at)
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,now())
ON CONFLICT (tenant_key) DO UPDATE SET smtp_host=excluded.smtp_host,smtp_port=excluded.smtp_port,smtp_username=excluded.smtp_username,smtp_password_sealed=excluded.smtp_password_sealed,from_address=excluded.from_address,recipients=excluded.recipients,cc_recipients=excluded.cc_recipients,send_weekday=excluded.send_weekday,send_hour=excluded.send_hour,enabled=excluded.enabled,revision=excluded.revision,updated_by=excluded.updated_by,updated_at=now()`,
s.tenant, normalized.Host, normalized.Port, normalized.Username, sealed, normalized.From, normalized.Recipients, normalized.Cc, normalized.Weekday, normalized.Hour, normalized.Enabled, next, actor); err != nil {
return Settings{}, ErrUnavailable
}
if err = tx.Commit(ctx); err != nil {
@@ -339,10 +370,10 @@ func (s *Store) ReadConfirmation(ctx context.Context, week string) (*Confirmatio
var out Confirmation
var currentRevision int64
var currentMarkdown string
err := s.pool.QueryRow(ctx, `SELECT c.week,c.draft_revision,c.body_sha256,c.confirmed_by,c.confirmed_at,d.revision,d.markdown
err := s.pool.QueryRow(ctx, `SELECT c.week,c.draft_revision,c.body_sha256,c.confirmed_by,c.confirmed_at,d.revision,d.markdown,c.dashboard_png IS NOT NULL
FROM qa_weekly_confirmations c LEFT JOIN qa_ops_weekly_drafts d ON d.tenant_key=c.tenant_key AND d.week=c.week
WHERE c.tenant_key=$1 AND c.week=$2`, s.tenant, week).
Scan(&out.Week, &out.DraftRevision, &out.BodySHA256, &out.ConfirmedBy, &out.ConfirmedAt, &currentRevision, &currentMarkdown)
Scan(&out.Week, &out.DraftRevision, &out.BodySHA256, &out.ConfirmedBy, &out.ConfirmedAt, &currentRevision, &currentMarkdown, &out.HasImage)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
@@ -473,6 +504,39 @@ func (s *Store) SendDue(ctx context.Context, now time.Time) (DueResult, error) {
return DueResult{State: "nothing_confirmed", Reason: "没有已确认且已结束的周报"}, nil
}
// SaveDashboardImage stores the dashboard PNG that belongs to the currently confirmed revision,
// so a later body edit (which invalidates the confirmation) never mails a stale chart.
func (s *Store) SaveDashboardImage(ctx context.Context, week string, png []byte) error {
if !s.valid() || strings.TrimSpace(week) == "" || len(png) < 8 || len(png) > 8<<20 {
return ErrInvalid
}
if string(png[:8]) != "\x89PNG\r\n\x1a\n" {
return ErrInvalid
}
sum := sha256.Sum256(png)
tag, err := s.pool.Exec(ctx, `UPDATE qa_weekly_confirmations SET dashboard_png=$2,dashboard_sha256=$3,dashboard_saved_at=now()
WHERE tenant_key=$1 AND week=$4`, s.tenant, png, hex.EncodeToString(sum[:]), week)
if err != nil {
return ErrUnavailable
}
if tag.RowsAffected() == 0 {
return ErrInvalid
}
return nil
}
func (s *Store) dashboardImage(ctx context.Context, week string) ([]byte, error) {
var png []byte
err := s.pool.QueryRow(ctx, `SELECT dashboard_png FROM qa_weekly_confirmations WHERE tenant_key=$1 AND week=$2`, s.tenant, week).Scan(&png)
if errors.Is(err, pgx.ErrNoRows) || len(png) == 0 {
return nil, nil
}
if err != nil {
return nil, ErrUnavailable
}
return png, nil
}
// TestSend mails a saved weekly body right now so an operator can verify the mailbox
// before any scheduled run. It never writes a send receipt and never marks a week as sent.
func (s *Store) TestSend(ctx context.Context, week string) (string, error) {
@@ -501,8 +565,12 @@ func (s *Store) TestSend(ctx context.Context, week string) (string, error) {
return "", ErrInvalid
}
html, text := renderReport(markdown)
images, err := s.inlineImages(ctx, week, &html)
if err != nil {
return "", err
}
return s.mailer.Send(ctx, SMTPConfig{Host: settings.Host, Port: settings.Port, Username: settings.Username, Password: password},
Message{To: settings.Recipients, From: settings.From, Subject: fmt.Sprintf("知识库周报 %s(测试发送)", week), HTML: html, Text: text})
Message{To: settings.Recipients, Cc: settings.Cc, From: settings.From, Subject: fmt.Sprintf("知识库周报 %s(测试发送)", week), HTML: html, Text: text, Images: images})
}
func (s *Store) send(ctx context.Context, settings Settings, week string, revision int64, markdown string, now time.Time) (DueResult, error) {
@@ -511,6 +579,10 @@ func (s *Store) send(ctx context.Context, settings Settings, week string, revisi
return DueResult{State: "blocked", Week: week, Reason: "SMTP 密码未配置或无法解密"}, nil
}
html, text := renderReport(markdown)
images, err := s.inlineImages(ctx, week, &html)
if err != nil {
return DueResult{}, err
}
subject := fmt.Sprintf("知识库周报 %s", week)
var sendID string
err = s.pool.QueryRow(ctx, `INSERT INTO qa_weekly_email_sends(tenant_key,week,draft_revision,body_sha256,status,attempts,created_at,updated_at)
@@ -522,7 +594,7 @@ func (s *Store) send(ctx context.Context, settings Settings, week string, revisi
return DueResult{}, ErrUnavailable
}
messageID, sendErr := s.mailer.Send(ctx, SMTPConfig{Host: settings.Host, Port: settings.Port, Username: settings.Username, Password: password},
Message{To: settings.Recipients, From: settings.From, Subject: subject, HTML: html, Text: text})
Message{To: settings.Recipients, Cc: settings.Cc, From: settings.From, Subject: subject, HTML: html, Text: text, Images: images})
if sendErr != nil {
reason := sendErr.Error()
if len(reason) > 400 {
@@ -537,6 +609,20 @@ func (s *Store) send(ctx context.Context, settings Settings, week string, revisi
return DueResult{State: "sent", Week: week, SentAt: now}, nil
}
const dashboardImageCID = "weekly-dashboard@knowledge-governance"
// inlineImages appends the confirmed dashboard chart to the end of the HTML body.
func (s *Store) inlineImages(ctx context.Context, week string, html *string) ([]InlineImage, error) {
png, err := s.dashboardImage(ctx, week)
if err != nil || len(png) == 0 {
return nil, err
}
footer := `<h2 style="font-size:17px;margin-top:24px;color:#17324d">统计看板</h2>` +
`<p><img src="cid:` + dashboardImageCID + `" alt="问题统计看板" style="max-width:100%;height:auto;border:1px solid #e5e7eb;border-radius:8px"></p>`
*html = strings.Replace(*html, "</body>", footer+"</body>", 1)
return []InlineImage{{Name: "dashboard.png", ContentType: "image/png", CID: dashboardImageCID, Bytes: png}}, nil
}
func (s *Store) password(ctx context.Context, revision int64) (string, error) {
var sealed []byte
if err := s.pool.QueryRow(ctx, `SELECT smtp_password_sealed FROM qa_weekly_email_settings WHERE tenant_key=$1`, s.tenant).Scan(&sealed); err != nil {
@@ -600,7 +686,7 @@ func (SMTPMailer) Send(ctx context.Context, cfg SMTPConfig, msg Message) (string
if err := client.Mail(msg.From); err != nil {
return "", fmt.Errorf("smtp MAIL FROM 被拒: %w", err)
}
for _, to := range msg.To {
for _, to := range append(append([]string{}, msg.To...), msg.Cc...) {
if err := client.Rcpt(to); err != nil {
return "", fmt.Errorf("smtp RCPT 被拒: %w", err)
}
@@ -638,16 +724,39 @@ func buildMIME(msg Message, messageID, boundary string) string {
var body strings.Builder
body.WriteString("From: " + msg.From + "\r\n")
body.WriteString("To: " + strings.Join(msg.To, ", ") + "\r\n")
if len(msg.Cc) > 0 {
body.WriteString("Cc: " + strings.Join(msg.Cc, ", ") + "\r\n")
}
body.WriteString("Subject: " + mimeSubject(msg.Subject) + "\r\n")
body.WriteString("Date: " + time.Now().Format(time.RFC1123Z) + "\r\n")
body.WriteString("Message-ID: " + messageID + "\r\n")
body.WriteString("MIME-Version: 1.0\r\n")
body.WriteString("Content-Type: multipart/alternative; boundary=\"" + boundary + "\"\r\n\r\n")
body.WriteString("--" + boundary + "\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: base64\r\n\r\n")
body.WriteString(base64Lines(msg.Text))
body.WriteString("\r\n--" + boundary + "\r\nContent-Type: text/html; charset=UTF-8\r\nContent-Transfer-Encoding: base64\r\n\r\n")
body.WriteString(base64Lines(msg.HTML))
body.WriteString("\r\n--" + boundary + "--\r\n")
alternative := func(w *strings.Builder) {
w.WriteString("--" + boundary + "\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: base64\r\n\r\n")
w.WriteString(base64Lines(msg.Text))
w.WriteString("\r\n--" + boundary + "\r\nContent-Type: text/html; charset=UTF-8\r\nContent-Transfer-Encoding: base64\r\n\r\n")
w.WriteString(base64Lines(msg.HTML))
w.WriteString("\r\n--" + boundary + "--\r\n")
}
if len(msg.Images) == 0 {
body.WriteString("Content-Type: multipart/alternative; boundary=\"" + boundary + "\"\r\n\r\n")
alternative(&body)
return body.String()
}
// Images live in a multipart/related wrapper so "cid:" references render inline,
// after the text and HTML alternatives.
related := boundary + "-related"
body.WriteString("Content-Type: multipart/related; boundary=\"" + related + "\"; type=\"multipart/alternative\"\r\n\r\n")
body.WriteString("--" + related + "\r\nContent-Type: multipart/alternative; boundary=\"" + boundary + "\"\r\n\r\n")
alternative(&body)
for _, image := range msg.Images {
body.WriteString("--" + related + "\r\nContent-Type: " + image.ContentType + "; name=\"" + image.Name + "\"\r\n")
body.WriteString("Content-Transfer-Encoding: base64\r\nContent-ID: <" + image.CID + ">\r\n")
body.WriteString("Content-Disposition: inline; filename=\"" + image.Name + "\"\r\n\r\n")
body.WriteString(base64Lines(string(image.Bytes)))
body.WriteString("\r\n")
}
body.WriteString("--" + related + "--\r\n")
return body.String()
}
+27
View File
@@ -92,3 +92,30 @@ func TestMailerRefusesPlaintextServersWithoutSTARTTLS(t *testing.T) {
t.Fatal("a server that cannot encrypt must be refused rather than sent in clear")
}
}
func TestNormalizeRejectsACopyThatIsAlsoAPrimaryRecipient(t *testing.T) {
_, err := normalize(SettingsInput{Host: "smtp.example.com", From: "kb@example.com", Recipients: []string{"a@example.com"}, Cc: []string{"A@example.com"}, Enabled: true})
if err != ErrInvalid {
t.Fatal("a person in both To and Cc would receive the report twice")
}
good, err := normalize(SettingsInput{Host: "smtp.example.com", From: "kb@example.com", Recipients: []string{"a@example.com"}, Cc: []string{"b@example.com", "c@example.com"}, Enabled: true})
if err != nil || len(good.Cc) != 2 {
t.Fatalf("valid cc list rejected: %+v %v", good.Cc, err)
}
}
func TestBuildMIMEPlacesTheChartAfterTheBodyAsAnInlineImage(t *testing.T) {
html, text := renderReport("# 周报\n\n正确率:90.66%\n")
png := []byte("\x89PNG\r\n\x1a\nfixture-bytes")
html = strings.Replace(html, "</body>", `<p><img src="cid:weekly-dashboard@knowledge-governance"></p></body>`, 1)
raw := buildMIME(Message{From: "kb@example.com", To: []string{"a@example.com"}, Cc: []string{"b@example.com"}, Subject: "周报", HTML: html, Text: text,
Images: []InlineImage{{Name: "dashboard.png", ContentType: "image/png", CID: "weekly-dashboard@knowledge-governance", Bytes: png}}}, "<id@example.com>", "BOUND")
for _, want := range []string{"Cc: b@example.com", "multipart/related", "multipart/alternative", "Content-ID: <weekly-dashboard@knowledge-governance>", "Content-Disposition: inline; filename=\"dashboard.png\"", "image/png"} {
if !strings.Contains(raw, want) {
t.Fatalf("MIME payload missing %q", want)
}
}
if !strings.Contains(html, "cid:weekly-dashboard@knowledge-governance") {
t.Fatal("html body must reference the inline cid")
}
}