设置新增抄送列表,MIME 增加 Cc 头、envelope 同时投递主送与抄送,同一地址不得同时出现在两边。 确认后可保存统计看板 PNG(multipart/related + cid),发送时放在正文末尾内联显示;正文改动使确认失效后不再使用旧图。
This commit is contained in:
@@ -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",
|
||||
|
||||
@@ -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)}})
|
||||
}
|
||||
|
||||
@@ -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
@@ -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 := `<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()
|
||||
}
|
||||
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 (
|
||||
<section className="qa-weekly-mail" aria-label="周报自动发送">
|
||||
@@ -104,6 +135,9 @@ export function QAWeeklyMail({ week, busy }: { week: string; busy: boolean }) {
|
||||
<button type="button" disabled={working || testing} onClick={() => void testSend()}>
|
||||
{testing ? '正在发送测试…' : '发送测试邮件'}
|
||||
</button>
|
||||
<button type="button" disabled={working || attaching || !confirmation || stale} onClick={attachDashboard}>
|
||||
{attaching ? '正在生成图片…' : confirmation?.has_image ? '重新附看板图片' : '附上统计看板图片'}
|
||||
</button>
|
||||
<button type="button" disabled={working} onClick={() => setEditing(!editing)}>
|
||||
{editing ? '收起发送设置' : '发送设置'}
|
||||
</button>
|
||||
@@ -136,6 +170,7 @@ export function QAWeeklyMail({ week, busy }: { week: string; busy: boolean }) {
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
{capture ? <DashboardCapture week={week} onDone={uploadCaptured} onError={failCaptured} /> : null}
|
||||
{sends.length ? (
|
||||
<ul className="qa-weekly-mail-sends">
|
||||
{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({
|
||||
<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>
|
||||
发送日
|
||||
<select value={weekday} onChange={(e) => setWeekday(Number(e.target.value))}>
|
||||
@@ -272,3 +310,55 @@ function SettingsForm({
|
||||
</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>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ const settings = {
|
||||
username: 'kb@example.com',
|
||||
from: 'kb@example.com',
|
||||
recipients: ['a@example.com'],
|
||||
cc_recipients: [],
|
||||
weekday: 1,
|
||||
hour: 9,
|
||||
enabled: true,
|
||||
|
||||
@@ -6,6 +6,7 @@ export interface WeeklyMailSettings {
|
||||
username: string
|
||||
from: string
|
||||
recipients: string[]
|
||||
cc_recipients: string[]
|
||||
weekday: number
|
||||
hour: number
|
||||
enabled: boolean
|
||||
@@ -17,6 +18,7 @@ export interface WeeklyMailSettings {
|
||||
|
||||
export interface WeeklyMailConfirmation {
|
||||
week: string
|
||||
has_image: boolean
|
||||
draft_revision: number
|
||||
body_sha256: string
|
||||
confirmed_by: string
|
||||
@@ -45,6 +47,8 @@ export function parseWeeklyMailSettings(value: unknown): WeeklyMailSettings {
|
||||
const v = obj(value)
|
||||
const recipients = v.recipients === null ? [] : v.recipients
|
||||
if (!Array.isArray(recipients) || recipients.some((item) => typeof item !== 'string')) return bad()
|
||||
const cc = v.cc_recipients === null || v.cc_recipients === undefined ? [] : v.cc_recipients
|
||||
if (!Array.isArray(cc) || cc.some((item) => typeof item !== 'string')) return bad()
|
||||
if (typeof v.enabled !== 'boolean' || typeof v.has_password !== 'boolean') return bad()
|
||||
const weekday = num(v.weekday),
|
||||
hour = num(v.hour),
|
||||
@@ -56,6 +60,7 @@ export function parseWeeklyMailSettings(value: unknown): WeeklyMailSettings {
|
||||
username: str(v.username),
|
||||
from: str(v.from),
|
||||
recipients: recipients as string[],
|
||||
cc_recipients: cc as string[],
|
||||
weekday,
|
||||
hour,
|
||||
enabled: v.enabled,
|
||||
@@ -77,6 +82,7 @@ export function parseWeeklyMailConfirmation(value: unknown, week: string): Weekl
|
||||
confirmed_by: str(v.confirmed_by),
|
||||
confirmed_at: str(v.confirmed_at),
|
||||
current: v.current,
|
||||
has_image: v.has_image === true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,6 +129,7 @@ export async function saveWeeklyMailSettings(
|
||||
clear_password: form.clear_password,
|
||||
from: form.from,
|
||||
recipients: form.recipients,
|
||||
cc_recipients: form.cc_recipients,
|
||||
weekday: form.weekday,
|
||||
hour: form.hour,
|
||||
enabled: form.enabled,
|
||||
@@ -162,3 +169,18 @@ export async function sendWeeklyMailTest(week: string): Promise<string> {
|
||||
if (typeof payload.message_id !== 'string' || !payload.message_id) bad()
|
||||
return payload.message_id
|
||||
}
|
||||
|
||||
export async function uploadWeeklyMailImage(week: string, png: Blob): Promise<number> {
|
||||
const buffer = await png.arrayBuffer()
|
||||
let binary = ''
|
||||
const bytes = new Uint8Array(buffer)
|
||||
for (let index = 0; index < bytes.length; index += 0x8000)
|
||||
binary += String.fromCharCode(...bytes.subarray(index, index + 0x8000))
|
||||
const payload = (await getPayload(endpoint('confirmations', week) + '/image', undefined, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify({ png_base64: btoa(binary) }),
|
||||
})) as { bytes: number }
|
||||
if (typeof payload.bytes !== 'number' || payload.bytes <= 0) bad()
|
||||
return payload.bytes
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user