From 822fb652ffaea9088e31f87ad1abf5a8b4fdc3ff Mon Sep 17 00:00:00 2001 From: hermes Date: Mon, 26 Oct 2026 15:59:06 +0800 Subject: [PATCH] =?UTF-8?q?feat(qa):=20=E5=91=A8=E6=8A=A5=E9=82=AE?= =?UTF-8?q?=E4=BB=B6=E5=8C=BA=E5=88=86=E4=B8=BB=E9=80=81=E6=8A=84=E9=80=81?= =?UTF-8?q?=E5=B9=B6=E9=99=84=E7=BB=9F=E8=AE=A1=E7=9C=8B=E6=9D=BF=E5=9B=BE?= =?UTF-8?q?=E7=89=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 设置新增抄送列表,MIME 增加 Cc 头、envelope 同时投递主送与抄送,同一地址不得同时出现在两边。 确认后可保存统计看板 PNG(multipart/related + cid),发送时放在正文末尾内联显示;正文改动使确认失效后不再使用旧图。 --- api/openapi.yaml | 1 + internal/httpapi/qa_weekly_mail.go | 39 +++++ internal/httpapi/server.go | 1 + .../migrations/000061_weekly_mail_cc.down.sql | 1 + .../migrations/000061_weekly_mail_cc.up.sql | 2 + ...00062_weekly_mail_dashboard_image.down.sql | 3 + .../000062_weekly_mail_dashboard_image.up.sql | 4 + internal/platform/postgres/migrations_test.go | 4 +- internal/qawemail/store.go | 145 +++++++++++++++--- internal/qawemail/store_test.go | 27 ++++ web/src/QAWeeklyMail.tsx | 100 +++++++++++- web/src/qaWeeklyMail.test.tsx | 1 + web/src/qaWeeklyMail.ts | 22 +++ 13 files changed, 325 insertions(+), 25 deletions(-) create mode 100644 internal/platform/postgres/migrations/000061_weekly_mail_cc.down.sql create mode 100644 internal/platform/postgres/migrations/000061_weekly_mail_cc.up.sql create mode 100644 internal/platform/postgres/migrations/000062_weekly_mail_dashboard_image.down.sql create mode 100644 internal/platform/postgres/migrations/000062_weekly_mail_dashboard_image.up.sql diff --git a/api/openapi.yaml b/api/openapi.yaml index 5faf4e1..984454f 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -52,6 +52,7 @@ "/api/v1/qa-ops/master/weekly-mail/confirmations/{week}": {"get":{"operationId":"getQAWeeklyMailConfirmation","tags":["QA operations"],"summary":"读取该周是否已确认自动发送;current=false表示确认后正文已被修改,需要重新确认","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}}],"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可修改发送设置"},"409":{"description":"发送设置已被其他管理员修改"},"503":{"description":"邮件设置存储不可用,未标记为已发送"}}},"post":{"operationId":"confirmQAWeeklyMail","tags":["QA operations"],"summary":"确认本周周报可自动发送,绑定当前草稿版本与正文哈希;后续改动使确认失效,不发送改动后的正文","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-mail"}}],"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可修改发送设置"},"409":{"description":"发送设置已被其他管理员修改"},"503":{"description":"邮件设置存储不可用,未标记为已发送"}}},"delete":{"operationId":"unconfirmQAWeeklyMail","tags":["QA operations"],"summary":"取消该周的自动发送确认","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-mail"}}],"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可修改发送设置"},"409":{"description":"发送设置已被其他管理员修改"},"503":{"description":"邮件设置存储不可用,未标记为已发送"}}}}, "/api/v1/qa-ops/master/weekly-mail/sends": {"get":{"operationId":"listQAWeeklyMailSends","tags":["QA operations"],"summary":"读取周报邮件发送记录:周次、草稿版本、发送中/已发送/失败及错误摘要,不返回正文或收件人","parameters":[{"name":"week","in":"query","required":false,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}}],"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可修改发送设置"},"409":{"description":"发送设置已被其他管理员修改"},"503":{"description":"邮件设置存储不可用,未标记为已发送"}}}}, "/api/v1/qa-ops/master/weekly-mail/test": {"post":{"operationId":"sendQAWeeklyMailTest","tags":["QA operations"],"summary":"管理员用当前已保存的邮件设置立即发送一封测试邮件,正文取该周已保存草稿;不写入发送记录、不改变确认状态、不把该周标记为已发送","parameters":[{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-mail"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["week"],"properties":{"week":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}}}}}},"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可测试发送"},"502":{"description":"SMTP 拒绝或不可达,返回脱敏原因"},"503":{"description":"邮件设置存储不可用"}}}}, + "/api/v1/qa-ops/master/weekly-mail/confirmations/{week}/image": {"post":{"operationId":"saveQAWeeklyMailImage","tags":["QA operations"],"summary":"管理员保存该周确认对应的统计看板 PNG;发送时作为内嵌图片(cid)放在正文末尾,正文改动使确认失效后不再使用旧图","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-mail"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["png_base64"],"properties":{"png_base64":{"type":"string","maxLength":12000000}}}}}},"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可上传"},"429":{"description":"请求过快"},"503":{"description":"邮件设置存储不可用"}}}}, "/api/v1/qa-ops/departments/statistics": { "post": { "operationId": "qaDepartmentStatistics", diff --git a/internal/httpapi/qa_weekly_mail.go b/internal/httpapi/qa_weekly_mail.go index 544f9e9..f3b1e46 100644 --- a/internal/httpapi/qa_weekly_mail.go +++ b/internal/httpapi/qa_weekly_mail.go @@ -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)}}) +} diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index 7512ec7..f6ed705 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -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) }) diff --git a/internal/platform/postgres/migrations/000061_weekly_mail_cc.down.sql b/internal/platform/postgres/migrations/000061_weekly_mail_cc.down.sql new file mode 100644 index 0000000..b67d533 --- /dev/null +++ b/internal/platform/postgres/migrations/000061_weekly_mail_cc.down.sql @@ -0,0 +1 @@ +alter table qa_weekly_email_settings drop column if exists cc_recipients; diff --git a/internal/platform/postgres/migrations/000061_weekly_mail_cc.up.sql b/internal/platform/postgres/migrations/000061_weekly_mail_cc.up.sql new file mode 100644 index 0000000..3a69db5 --- /dev/null +++ b/internal/platform/postgres/migrations/000061_weekly_mail_cc.up.sql @@ -0,0 +1,2 @@ +-- 主送与抄送分开:抄送只影响收件头与 envelope,不影响发送规则。 +alter table qa_weekly_email_settings add column if not exists cc_recipients text[] not null default '{}'; \ No newline at end of file diff --git a/internal/platform/postgres/migrations/000062_weekly_mail_dashboard_image.down.sql b/internal/platform/postgres/migrations/000062_weekly_mail_dashboard_image.down.sql new file mode 100644 index 0000000..9242294 --- /dev/null +++ b/internal/platform/postgres/migrations/000062_weekly_mail_dashboard_image.down.sql @@ -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; diff --git a/internal/platform/postgres/migrations/000062_weekly_mail_dashboard_image.up.sql b/internal/platform/postgres/migrations/000062_weekly_mail_dashboard_image.up.sql new file mode 100644 index 0000000..a678d99 --- /dev/null +++ b/internal/platform/postgres/migrations/000062_weekly_mail_dashboard_image.up.sql @@ -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; diff --git a/internal/platform/postgres/migrations_test.go b/internal/platform/postgres/migrations_test.go index 7080c99..c38dfc7 100644 --- a/internal/platform/postgres/migrations_test.go +++ b/internal/platform/postgres/migrations_test.go @@ -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]) diff --git a/internal/qawemail/store.go b/internal/qawemail/store.go index 8f6a3dd..c944d08 100644 --- a/internal/qawemail/store.go +++ b/internal/qawemail/store.go @@ -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, ¤tRevision, ¤tMarkdown) + Scan(&out.Week, &out.DraftRevision, &out.BodySHA256, &out.ConfirmedBy, &out.ConfirmedAt, ¤tRevision, ¤tMarkdown, &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 := `

统计看板

` + + `

问题统计看板

` + *html = strings.Replace(*html, "", footer+"", 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() } diff --git a/internal/qawemail/store_test.go b/internal/qawemail/store_test.go index afe5f04..56ad3bd 100644 --- a/internal/qawemail/store_test.go +++ b/internal/qawemail/store_test.go @@ -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, "", `

`, 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}}}, "", "BOUND") + for _, want := range []string{"Cc: b@example.com", "multipart/related", "multipart/alternative", "Content-ID: ", "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") + } +} diff --git a/web/src/QAWeeklyMail.tsx b/web/src/QAWeeklyMail.tsx index 06e1789..fec5f80 100644 --- a/web/src/QAWeeklyMail.tsx +++ b/web/src/QAWeeklyMail.tsx @@ -1,5 +1,9 @@ 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, @@ -7,6 +11,7 @@ import { fetchWeeklyMailSettings, saveWeeklyMailSettings, sendWeeklyMailTest, + uploadWeeklyMailImage, weeklyMailWeekdayLabels, } from './qaWeeklyMail' import type { WeeklyMailConfirmation, WeeklyMailSend, WeeklyMailSettings } from './qaWeeklyMail' @@ -25,6 +30,8 @@ export function QAWeeklyMail({ week, busy }: { week: string; busy: boolean }) { 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('') @@ -77,6 +84,30 @@ export function QAWeeklyMail({ week, busy }: { week: string; busy: boolean }) { 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 (
@@ -104,6 +135,9 @@ export function QAWeeklyMail({ week, busy }: { week: string; busy: boolean }) { + @@ -136,6 +170,7 @@ export function QAWeeklyMail({ week, busy }: { week: string; busy: boolean }) { }} /> ) : null} + {capture ? : null} {sends.length ? (
    {sends.map((send) => ( @@ -165,6 +200,7 @@ function SettingsForm({ 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 [weekday, setWeekday] = useState(settings.weekday) const [hour, setHour] = useState(String(settings.hour)) const [enabled, setEnabled] = useState(settings.enabled) @@ -182,10 +218,8 @@ function SettingsForm({ password, clear_password: clearPassword, from: from.trim(), - recipients: recipients - .split(/[\n,,;;]/) - .map((item) => item.trim()) - .filter(Boolean), + recipients: splitAddresses(recipients), + cc_recipients: splitAddresses(cc), weekday, hour: Number(hour), enabled, @@ -237,9 +271,13 @@ function SettingsForm({ setFrom(e.target.value)} placeholder="kb@example.com" />