feat(qa): 周报确认后按设定时段自动发邮件
build / build (push) Successful in 1m23s

周报页新增自动发送区:管理员配置 SMTP/收件人/发送星期与小时,授权码用主密钥加密保存。
确认绑定当前草稿版本与正文哈希,正文再改则确认失效;worker 每分钟仅在启用、到点、周已结束且未发送过时发一次。
邮件同时提供渲染后的 HTML 与可读纯文本;SMTP 仅允许 TLS,拒绝明文。
迁移 000060 新增设置、确认与发送记录三张表,唯一键防重复发送。
This commit is contained in:
hermes
2026-10-26 09:49:23 +08:00
parent 1d33ff6976
commit 6816289552
18 changed files with 1550 additions and 2 deletions
+133
View File
@@ -0,0 +1,133 @@
package httpapi
import (
"context"
"errors"
"knowledge-governance/internal/dobotaiops"
"knowledge-governance/internal/qawemail"
"net/http"
"time"
)
type weeklyMailStore interface {
ReadSettings(context.Context) (qawemail.Settings, error)
SaveSettings(context.Context, string, qawemail.SettingsInput) (qawemail.Settings, error)
Confirm(context.Context, string, string) (qawemail.Confirmation, error)
Unconfirm(context.Context, string) error
ReadConfirmation(context.Context, string) (*qawemail.Confirmation, error)
Sends(context.Context, string) ([]qawemail.Send, error)
SendDue(context.Context, time.Time) (qawemail.DueResult, error)
}
func weeklyMailError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, qawemail.ErrConflict):
writeJSON(w, http.StatusConflict, map[string]string{"error": "发送设置已被其他人修改,请重新读取后再保存"})
case errors.Is(err, qawemail.ErrInvalid):
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "发送设置无效:请检查服务器、发件地址、收件人与时间"})
case errors.Is(err, qawemail.ErrUnavailable):
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "周报邮件暂不可用,请稍后重试;未标记为已发送"})
default:
qaOpsError(w, dobotaiops.ErrUnavailable)
}
}
func qaWeeklyMailSettings(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
}
switch r.Method {
case http.MethodGet:
settings, err := store.ReadSettings(r.Context())
if err != nil {
weeklyMailError(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"data": settings})
case http.MethodPost:
if !authorizeQAIntent(w, r, "qa-weekly-mail") {
return
}
if identity, ok := sessionFrom(r.Context()); !ok || identity.Role != "admin" {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "仅管理员可修改邮件发送设置"})
return
}
var input qawemail.SettingsInput
if decodeQualityJSON(w, r, &input) != nil {
weeklyMailError(w, qawemail.ErrInvalid)
return
}
identity, _ := sessionFrom(r.Context())
actor := identity.Username
settings, err := store.SaveSettings(r.Context(), actor, input)
if err != nil {
weeklyMailError(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"data": settings})
default:
w.Header().Set("Allow", "GET, POST")
writeJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "不支持的方法"})
}
}
func qaWeeklyMailConfirm(w http.ResponseWriter, r *http.Request, c Config) {
if !authorizeQAOps(w, r) || !authorizeQAIntent(w, r, "qa-weekly-mail") {
return
}
store, ok := c.QAWeeklyMail.(weeklyMailStore)
if !ok {
weeklyMailError(w, qawemail.ErrUnavailable)
return
}
week := r.PathValue("week")
switch r.Method {
case http.MethodGet:
confirmation, err := store.ReadConfirmation(r.Context(), week)
if err != nil {
weeklyMailError(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"confirmation": confirmation}})
case http.MethodPost:
identity, _ := sessionFrom(r.Context())
actor := identity.Username
confirmation, err := store.Confirm(r.Context(), week, actor)
if err != nil {
weeklyMailError(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"confirmation": confirmation}})
case http.MethodDelete:
if err := store.Unconfirm(r.Context(), week); err != nil {
weeklyMailError(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"confirmation": nil}})
default:
w.Header().Set("Allow", "GET, POST, DELETE")
writeJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "不支持的方法"})
}
}
func qaWeeklyMailSends(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
}
sends, err := store.Sends(r.Context(), r.URL.Query().Get("week"))
if err != nil {
weeklyMailError(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"sends": sends}})
}
+7
View File
@@ -111,6 +111,7 @@ type Config struct {
QAOrgSyncEnabled bool
QAOrg QAOrgStore
QAOps QAOpsReader
QAWeeklyMail any
QAOpsTenantKey string
QAOpsEnabled bool
QAOpsProblem string
@@ -203,6 +204,12 @@ func NewHandler(config Config) (http.Handler, error) {
mux.HandleFunc("GET /api/v1/qa-ops/master/weekly-drafts/{week}", func(w http.ResponseWriter, r *http.Request) { qaWeeklyDraftRead(w, r, config) })
mux.HandleFunc("POST /api/v1/qa-ops/master/weekly-drafts/{week}", func(w http.ResponseWriter, r *http.Request) { qaWeeklyDraftWrite(w, r, config, false) })
mux.HandleFunc("POST /api/v1/qa-ops/master/weekly-drafts/{week}/prefill", func(w http.ResponseWriter, r *http.Request) { qaWeeklyDraftWrite(w, r, config, true) })
mux.HandleFunc("GET /api/v1/qa-ops/master/weekly-mail/settings", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailSettings(w, r, config) })
mux.HandleFunc("POST /api/v1/qa-ops/master/weekly-mail/settings", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailSettings(w, r, config) })
mux.HandleFunc("GET /api/v1/qa-ops/master/weekly-mail/confirmations/{week}", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailConfirm(w, r, config) })
mux.HandleFunc("POST /api/v1/qa-ops/master/weekly-mail/confirmations/{week}", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailConfirm(w, r, config) })
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("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,3 @@
drop table if exists qa_weekly_email_sends;
drop table if exists qa_weekly_confirmations;
drop table if exists qa_weekly_email_settings;
@@ -0,0 +1,44 @@
-- Weekly report e-mail: operator-confirmed drafts are sent at the configured slot.
-- The SMTP password is sealed with the independently provisioned master key, never stored in clear.
create table if not exists qa_weekly_email_settings (
tenant_key text primary key,
smtp_host text not null default '',
smtp_port integer not null default 465 check (smtp_port between 1 and 65535),
smtp_username text not null default '',
smtp_password_sealed bytea,
from_address text not null default '',
recipients text[] not null default '{}',
send_weekday smallint not null default 1 check (send_weekday between 1 and 7),
send_hour smallint not null default 9 check (send_hour between 0 and 23),
enabled boolean not null default false,
revision bigint not null default 0,
updated_by text not null default '',
updated_at timestamptz not null default now()
);
create table if not exists qa_weekly_confirmations (
tenant_key text not null,
week text not null,
draft_revision bigint not null check (draft_revision > 0),
body_sha256 text not null,
confirmed_by text not null,
confirmed_at timestamptz not null default now(),
primary key (tenant_key, week)
);
create table if not exists qa_weekly_email_sends (
id uuid primary key default gen_random_uuid(),
tenant_key text not null,
week text not null,
draft_revision bigint not null,
body_sha256 text not null,
status text not null check (status in ('sending', 'sent', 'failed')),
attempts integer not null default 0,
last_error text not null default '',
message_id text not null default '',
created_at timestamptz not null default now(),
updated_at timestamptz not null default now(),
unique (tenant_key, week, draft_revision)
);
create index if not exists qa_weekly_email_sends_week_idx on qa_weekly_email_sends(tenant_key, week);
@@ -11,8 +11,8 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
if err != nil {
t.Fatalf("loadMigrations() error = %v", err)
}
if len(migrations) != 59 {
t.Fatalf("migration count = %d, want 59", len(migrations))
if len(migrations) != 60 {
t.Fatalf("migration count = %d, want 60", 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])
+636
View File
@@ -0,0 +1,636 @@
package qawemail
import (
"context"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"crypto/tls"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"net"
"net/mail"
"net/smtp"
"os"
"strings"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/extension"
)
var (
ErrUnavailable = errors.New("weekly mail store unavailable")
ErrInvalid = errors.New("weekly mail invalid input")
ErrConflict = errors.New("weekly mail settings changed")
ErrNoPassword = errors.New("weekly mail password missing")
)
// Settings never carries the SMTP password; HasPassword only says whether one is stored.
type Settings struct {
Host string `json:"host"`
Port int `json:"port"`
Username string `json:"username"`
From string `json:"from"`
Recipients []string `json:"recipients"`
Weekday int `json:"weekday"`
Hour int `json:"hour"`
Enabled bool `json:"enabled"`
HasPassword bool `json:"has_password"`
Revision int64 `json:"revision"`
UpdatedBy string `json:"updated_by"`
UpdatedAt time.Time `json:"updated_at"`
}
type SettingsInput struct {
BaseRevision int64 `json:"base_revision"`
Host string `json:"host"`
Port int `json:"port"`
Username string `json:"username"`
Password string `json:"password"`
ClearPassword bool `json:"clear_password"`
From string `json:"from"`
Recipients []string `json:"recipients"`
Weekday int `json:"weekday"`
Hour int `json:"hour"`
Enabled bool `json:"enabled"`
}
type Confirmation struct {
Week string `json:"week"`
DraftRevision int64 `json:"draft_revision"`
BodySHA256 string `json:"body_sha256"`
ConfirmedBy string `json:"confirmed_by"`
ConfirmedAt time.Time `json:"confirmed_at"`
Current bool `json:"current"`
}
type Send struct {
Week string `json:"week"`
Revision int64 `json:"draft_revision"`
Status string `json:"status"`
Attempts int `json:"attempts"`
LastError string `json:"last_error"`
UpdatedAt time.Time `json:"updated_at"`
}
type Message struct {
To []string
From string
Subject string
HTML string
Text string
}
// Mailer is the only outbound dependency; tests substitute it to prove the exact wire payload.
type Mailer interface {
Send(ctx context.Context, cfg SMTPConfig, msg Message) (string, error)
}
type SMTPConfig struct {
Host string
Port int
Username string
Password string
}
type Store struct {
pool *pgxpool.Pool
tenant string
keyFile string
mailer Mailer
now func() time.Time
}
func NewStore(pool *pgxpool.Pool, tenant, keyFile string, mailer Mailer) *Store {
if mailer == nil {
mailer = SMTPMailer{}
}
return &Store{pool: pool, tenant: tenant, keyFile: keyFile, mailer: mailer, now: time.Now}
}
func (s *Store) valid() bool {
return s != nil && s.pool != nil && strings.TrimSpace(s.tenant) != ""
}
func (s *Store) masterKey() ([]byte, error) {
info, err := os.Lstat(s.keyFile)
if err != nil || !info.Mode().IsRegular() || info.Mode().Perm() != 0o600 {
return nil, ErrUnavailable
}
raw, err := os.ReadFile(s.keyFile)
if err != nil || len(raw) != 32 {
return nil, ErrUnavailable
}
return raw, nil
}
func (s *Store) seal(secret string, revision int64) ([]byte, error) {
key, err := s.masterKey()
if err != nil {
return nil, err
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, ErrUnavailable
}
aead, err := cipher.NewGCM(block)
if err != nil {
return nil, ErrUnavailable
}
nonce := make([]byte, aead.NonceSize())
if _, err = rand.Read(nonce); err != nil {
return nil, ErrUnavailable
}
return aead.Seal(nonce, nonce, []byte(secret), []byte(fmt.Sprintf("weekly-mail:%s:%d", s.tenant, revision))), nil
}
func (s *Store) unseal(sealed []byte, revision int64) (string, error) {
if len(sealed) == 0 {
return "", ErrNoPassword
}
key, err := s.masterKey()
if err != nil {
return "", err
}
block, err := aes.NewCipher(key)
if err != nil {
return "", ErrUnavailable
}
aead, err := cipher.NewGCM(block)
if err != nil || len(sealed) < aead.NonceSize() {
return "", ErrUnavailable
}
raw, err := aead.Open(nil, sealed[:aead.NonceSize()], sealed[aead.NonceSize():], []byte(fmt.Sprintf("weekly-mail:%s:%d", s.tenant, revision)))
if err != nil {
return "", ErrUnavailable
}
return string(raw), nil
}
func validAddress(value string) bool {
parsed, err := mail.ParseAddress(strings.TrimSpace(value))
return err == nil && parsed.Address == strings.TrimSpace(value) && strings.Contains(parsed.Address, "@")
}
func normalize(input SettingsInput) (SettingsInput, error) {
input.Host = strings.TrimSpace(input.Host)
input.Username = strings.TrimSpace(input.Username)
input.From = strings.TrimSpace(input.From)
seen := map[string]bool{}
recipients := make([]string, 0, len(input.Recipients))
for _, raw := range input.Recipients {
address := strings.TrimSpace(raw)
if address == "" || !validAddress(address) || seen[strings.ToLower(address)] {
return input, ErrInvalid
}
seen[strings.ToLower(address)] = true
recipients = append(recipients, address)
}
input.Recipients = recipients
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.
return input, ErrInvalid
}
}
if input.Port == 0 {
input.Port = 465
}
if input.Weekday == 0 {
input.Weekday = 1
}
if input.Port < 1 || input.Port > 65535 || input.Weekday < 1 || input.Weekday > 7 || input.Hour < 0 || input.Hour > 23 {
return input, ErrInvalid
}
if input.Enabled {
if input.Host == "" || input.From == "" || !validAddress(input.From) || len(input.Recipients) == 0 {
return input, ErrInvalid
}
}
return input, nil
}
func (s *Store) ReadSettings(ctx context.Context) (Settings, error) {
out := Settings{Port: 465, Weekday: 1, Hour: 9}
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)
if errors.Is(err, pgx.ErrNoRows) {
return out, nil
}
if err != nil {
return Settings{}, ErrUnavailable
}
out.HasPassword = len(sealed) > 0
return out, nil
}
func (s *Store) SaveSettings(ctx context.Context, actor string, input SettingsInput) (Settings, error) {
if !s.valid() || strings.TrimSpace(actor) == "" {
return Settings{}, ErrUnavailable
}
normalized, err := normalize(input)
if err != nil {
return Settings{}, err
}
ctx, cancel := context.WithTimeout(ctx, 8*time.Second)
defer cancel()
tx, err := s.pool.Begin(ctx)
if err != nil {
return Settings{}, ErrUnavailable
}
defer tx.Rollback(context.Background())
if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,257))`, "weekly-mail:"+s.tenant); err != nil {
return Settings{}, ErrUnavailable
}
var current int64
var sealed []byte
err = tx.QueryRow(ctx, `SELECT revision,smtp_password_sealed FROM qa_weekly_email_settings WHERE tenant_key=$1 FOR UPDATE`, s.tenant).Scan(&current, &sealed)
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
return Settings{}, ErrUnavailable
}
if current != input.BaseRevision {
return Settings{}, ErrConflict
}
next := current + 1
switch {
case normalized.ClearPassword:
sealed = nil
case strings.TrimSpace(normalized.Password) != "":
if sealed, err = s.seal(normalized.Password, next); err != nil {
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 {
return Settings{}, ErrUnavailable
}
if err = tx.Commit(ctx); err != nil {
return Settings{}, ErrUnavailable
}
return s.ReadSettings(ctx)
}
func bodyHash(markdown string) string {
sum := sha256.Sum256([]byte(markdown))
return hex.EncodeToString(sum[:])
}
// Confirm binds the confirmation to the exact revision and body the operator just reviewed,
// so a later edit invalidates it instead of silently mailing changed text.
func (s *Store) Confirm(ctx context.Context, week, actor string) (Confirmation, error) {
if !s.valid() || strings.TrimSpace(actor) == "" || strings.TrimSpace(week) == "" {
return Confirmation{}, ErrUnavailable
}
ctx, cancel := context.WithTimeout(ctx, 8*time.Second)
defer cancel()
var revision int64
var markdown string
if err := s.pool.QueryRow(ctx, `SELECT revision,markdown FROM qa_ops_weekly_drafts WHERE tenant_key=$1 AND week=$2`, s.tenant, week).Scan(&revision, &markdown); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return Confirmation{}, ErrInvalid
}
return Confirmation{}, ErrUnavailable
}
if revision <= 0 || strings.TrimSpace(markdown) == "" {
return Confirmation{}, ErrInvalid
}
var out Confirmation
err := s.pool.QueryRow(ctx, `INSERT INTO qa_weekly_confirmations(tenant_key,week,draft_revision,body_sha256,confirmed_by,confirmed_at)
VALUES($1,$2,$3,$4,$5,now())
ON CONFLICT (tenant_key,week) DO UPDATE SET draft_revision=excluded.draft_revision,body_sha256=excluded.body_sha256,confirmed_by=excluded.confirmed_by,confirmed_at=now()
RETURNING week,draft_revision,body_sha256,confirmed_by,confirmed_at`, s.tenant, week, revision, bodyHash(markdown), actor).
Scan(&out.Week, &out.DraftRevision, &out.BodySHA256, &out.ConfirmedBy, &out.ConfirmedAt)
if err != nil {
return Confirmation{}, ErrUnavailable
}
out.Current = true
return out, nil
}
func (s *Store) Unconfirm(ctx context.Context, week string) error {
if !s.valid() {
return ErrUnavailable
}
if _, err := s.pool.Exec(ctx, `DELETE FROM qa_weekly_confirmations WHERE tenant_key=$1 AND week=$2`, s.tenant, week); err != nil {
return ErrUnavailable
}
return nil
}
func (s *Store) ReadConfirmation(ctx context.Context, week string) (*Confirmation, error) {
if !s.valid() {
return nil, ErrUnavailable
}
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
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)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, ErrUnavailable
}
out.Current = currentRevision == out.DraftRevision && currentMarkdown != "" && bodyHash(currentMarkdown) == out.BodySHA256
return &out, nil
}
func (s *Store) Sends(ctx context.Context, week string) ([]Send, error) {
if !s.valid() {
return nil, ErrUnavailable
}
rows, err := s.pool.Query(ctx, `SELECT week,draft_revision,status,attempts,last_error,updated_at FROM qa_weekly_email_sends WHERE tenant_key=$1 AND ($2='' OR week=$2) ORDER BY updated_at DESC LIMIT 50`, s.tenant, week)
if err != nil {
return nil, ErrUnavailable
}
defer rows.Close()
out := []Send{}
for rows.Next() {
var item Send
if err := rows.Scan(&item.Week, &item.Revision, &item.Status, &item.Attempts, &item.LastError, &item.UpdatedAt); err != nil {
return nil, ErrUnavailable
}
out = append(out, item)
}
return out, nil
}
type DueResult struct {
State string `json:"state"`
Week string `json:"week,omitempty"`
SentAt time.Time `json:"sent_at,omitempty"`
Reason string `json:"reason,omitempty"`
}
// weekStart resolves the Beijing Monday of an ISO week label; reports are due after that week closes.
func weekStart(week string) (time.Time, error) {
var year, number int
if _, err := fmt.Sscanf(week, "%4d-W%2d", &year, &number); err != nil || year < 2000 || year > 2200 || number < 1 || number > 53 {
return time.Time{}, ErrInvalid
}
location := time.FixedZone("CST", 8*3600)
jan4 := time.Date(year, 1, 4, 0, 0, 0, 0, location)
offset := (int(jan4.Weekday()) + 6) % 7
start := jan4.AddDate(0, 0, -offset+7*(number-1))
if _, got := start.ISOWeek(); got != number {
return time.Time{}, ErrInvalid
}
return start, nil
}
// slotMatches is the single definition of "the configured weekly slot is now".
func slotMatches(settings Settings, now time.Time) bool {
local := now.In(time.FixedZone("CST", 8*3600))
weekday := int(local.Weekday())
if weekday == 0 {
weekday = 7
}
return weekday == settings.Weekday && local.Hour() == settings.Hour
}
// reportClosed reports whether the ISO week is over and its report may go out.
func reportClosed(week string, now time.Time) bool {
start, err := weekStart(week)
if err != nil {
return false
}
return !now.Before(start.AddDate(0, 0, 7))
}
// SendDue mails only a confirmed, still-current, already-closed week at the configured slot.
// Every skip path returns a reason instead of pretending a message went out.
func (s *Store) SendDue(ctx context.Context, now time.Time) (DueResult, error) {
if !s.valid() {
return DueResult{}, ErrUnavailable
}
settings, err := s.ReadSettings(ctx)
if err != nil {
return DueResult{}, err
}
if !settings.Enabled {
return DueResult{State: "disabled", Reason: "未启用自动发送"}, nil
}
if !slotMatches(settings, now) {
return DueResult{State: "not_due", Reason: "未到设定发送时段"}, nil
}
rows, err := s.pool.Query(ctx, `SELECT c.week,c.draft_revision,c.body_sha256,d.revision,d.markdown
FROM qa_weekly_confirmations c JOIN qa_ops_weekly_drafts d ON d.tenant_key=c.tenant_key AND d.week=c.week
WHERE c.tenant_key=$1 ORDER BY c.week DESC`, s.tenant)
if err != nil {
return DueResult{}, ErrUnavailable
}
type candidate struct {
week string
revision int64
hash string
markdown string
}
candidates := []candidate{}
for rows.Next() {
var c candidate
var draftRevision int64
if err := rows.Scan(&c.week, &c.revision, &c.hash, &draftRevision, &c.markdown); err != nil {
rows.Close()
return DueResult{}, ErrUnavailable
}
if draftRevision != c.revision || bodyHash(c.markdown) != c.hash {
continue
}
candidates = append(candidates, c)
}
rows.Close()
for _, c := range candidates {
if !reportClosed(c.week, now) {
continue
}
var sent bool
if err := s.pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM qa_weekly_email_sends WHERE tenant_key=$1 AND week=$2 AND draft_revision=$3 AND status='sent')`, s.tenant, c.week, c.revision).Scan(&sent); err != nil {
return DueResult{}, ErrUnavailable
}
if sent {
continue
}
return s.send(ctx, settings, c.week, c.revision, c.markdown, now)
}
return DueResult{State: "nothing_confirmed", Reason: "没有已确认且已结束的周报"}, nil
}
func (s *Store) send(ctx context.Context, settings Settings, week string, revision int64, markdown string, now time.Time) (DueResult, error) {
password, err := s.password(ctx, settings.Revision)
if err != nil {
return DueResult{State: "blocked", Week: week, Reason: "SMTP 密码未配置或无法解密"}, nil
}
html, text := renderReport(markdown)
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)
VALUES($1,$2,$3,$4,'sending',1,now(),now())
ON CONFLICT (tenant_key,week,draft_revision) DO UPDATE SET status='sending',attempts=qa_weekly_email_sends.attempts+1,updated_at=now()
WHERE qa_weekly_email_sends.status<>'sent'
RETURNING id::text`, s.tenant, week, revision, bodyHash(markdown)).Scan(&sendID)
if err != nil {
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})
if sendErr != nil {
reason := sendErr.Error()
if len(reason) > 400 {
reason = reason[:400]
}
_, _ = s.pool.Exec(ctx, `UPDATE qa_weekly_email_sends SET status='failed',last_error=$2,updated_at=now() WHERE id=$1`, sendID, reason)
return DueResult{State: "failed", Week: week, Reason: "发送失败,稍后重试"}, nil
}
if _, err = s.pool.Exec(ctx, `UPDATE qa_weekly_email_sends SET status='sent',message_id=$2,last_error='',updated_at=now() WHERE id=$1`, sendID, messageID); err != nil {
return DueResult{}, ErrUnavailable
}
return DueResult{State: "sent", Week: week, SentAt: now}, 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 {
return "", ErrUnavailable
}
return s.unseal(sealed, revision)
}
func renderReport(markdown string) (string, string) {
converter := goldmark.New(goldmark.WithExtensions(extension.GFM))
var html strings.Builder
if err := converter.Convert([]byte(markdown), &html); err != nil {
html.Reset()
}
return `<!doctype html><html><head><meta charset="utf-8"><style>
body{font-family:-apple-system,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;color:#1f2937;line-height:1.7;margin:0;padding:24px;background:#fff}
h1{font-size:22px;border-bottom:2px solid #e5e7eb;padding-bottom:8px;margin-top:32px}
h2{font-size:17px;margin-top:24px;color:#17324d}
table{border-collapse:collapse}h1:first-child{margin-top:0}
</style></head><body>` + html.String() + `</body></html>`, markdown
}
// SMTPMailer speaks SMTP directly: implicit TLS on 465, STARTTLS elsewhere. Plaintext is refused.
type SMTPMailer struct{}
func (SMTPMailer) Send(ctx context.Context, cfg SMTPConfig, msg Message) (string, error) {
if cfg.Host == "" || cfg.Port <= 0 || len(msg.To) == 0 || !validAddress(msg.From) {
return "", ErrInvalid
}
address := net.JoinHostPort(cfg.Host, fmt.Sprint(cfg.Port))
dialer := &net.Dialer{Timeout: 15 * time.Second}
var conn net.Conn
var err error
if cfg.Port == 465 {
conn, err = tls.DialWithDialer(dialer, "tcp", address, &tls.Config{ServerName: cfg.Host, MinVersion: tls.VersionTLS12})
} else {
conn, err = dialer.DialContext(ctx, "tcp", address)
}
if err != nil {
return "", fmt.Errorf("smtp 连接失败: %w", err)
}
client, err := smtp.NewClient(conn, cfg.Host)
if err != nil {
conn.Close()
return "", fmt.Errorf("smtp 握手失败: %w", err)
}
defer client.Close()
if cfg.Port != 465 {
if ok, _ := client.Extension("STARTTLS"); !ok {
return "", errors.New("smtp 服务器不支持 STARTTLS,已拒绝明文发送")
}
if err := client.StartTLS(&tls.Config{ServerName: cfg.Host, MinVersion: tls.VersionTLS12}); err != nil {
return "", fmt.Errorf("smtp STARTTLS 失败: %w", err)
}
}
if cfg.Username != "" {
if err := client.Auth(smtp.PlainAuth("", cfg.Username, cfg.Password, cfg.Host)); err != nil {
return "", fmt.Errorf("smtp 登录失败: %w", err)
}
}
if err := client.Mail(msg.From); err != nil {
return "", fmt.Errorf("smtp MAIL FROM 被拒: %w", err)
}
for _, to := range msg.To {
if err := client.Rcpt(to); err != nil {
return "", fmt.Errorf("smtp RCPT 被拒: %w", err)
}
}
writer, err := client.Data()
if err != nil {
return "", fmt.Errorf("smtp DATA 被拒: %w", err)
}
messageID := fmt.Sprintf("<%s@%s>", hex.EncodeToString(randomBytes(12)), domainOf(msg.From))
boundary := hex.EncodeToString(randomBytes(10))
if _, err = writer.Write([]byte(buildMIME(msg, messageID, boundary))); err != nil {
return "", fmt.Errorf("smtp 写入失败: %w", err)
}
if err = writer.Close(); err != nil {
return "", fmt.Errorf("smtp 提交失败: %w", err)
}
_ = client.Quit()
return messageID, nil
}
func randomBytes(n int) []byte {
out := make([]byte, n)
_, _ = rand.Read(out)
return out
}
func domainOf(address string) string {
if at := strings.LastIndex(address, "@"); at >= 0 {
return address[at+1:]
}
return "localhost"
}
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")
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")
return body.String()
}
func base64Std(value string) string {
return base64.StdEncoding.EncodeToString([]byte(value))
}
func base64Lines(value string) string {
encoded := base64Std(value)
var out strings.Builder
for len(encoded) > 76 {
out.WriteString(encoded[:76] + "\r\n")
encoded = encoded[76:]
}
out.WriteString(encoded)
return out.String()
}
func mimeSubject(value string) string {
return "=?UTF-8?B?" + base64Std(value) + "?="
}
+94
View File
@@ -0,0 +1,94 @@
package qawemail
import (
"context"
"encoding/base64"
"strings"
"testing"
"time"
)
func TestSlotMatchesUsesBeijingWeekdayAndHour(t *testing.T) {
settings := Settings{Weekday: 1, Hour: 9}
// Monday 09:30 Beijing == Monday 01:30 UTC.
if !slotMatches(settings, time.Date(2026, 10, 26, 1, 30, 0, 0, time.UTC)) {
t.Fatal("Monday 09:30 Beijing must match a Monday-09 slot")
}
if slotMatches(settings, time.Date(2026, 10, 26, 2, 30, 0, 0, time.UTC)) {
t.Fatal("Monday 10:30 Beijing must not match a Monday-09 slot")
}
// Sunday 23:30 UTC is Monday 07:30 Beijing: still Monday, wrong hour.
if slotMatches(settings, time.Date(2026, 10, 25, 23, 30, 0, 0, time.UTC)) {
t.Fatal("Sunday 23:30 UTC is not the configured hour")
}
}
func TestReportClosedOnlyAfterTheISOWeekEnds(t *testing.T) {
if reportClosed("2026-W43", time.Date(2026, 10, 25, 10, 0, 0, 0, time.UTC)) {
t.Fatal("a week is not closed before its Monday boundary")
}
if !reportClosed("2026-W43", time.Date(2026, 10, 26, 1, 0, 0, 0, time.UTC)) {
t.Fatal("week 43 must be closed after Monday 00:00 Beijing")
}
if reportClosed("2026-W99", time.Now()) || reportClosed("2026-W00", time.Now()) {
t.Fatal("impossible ISO weeks must be rejected")
}
}
func TestNormalizeRefusesEnabledSettingsWithoutTransportAndBadRecipients(t *testing.T) {
if _, err := normalize(SettingsInput{Host: "", From: "", Recipients: nil, Enabled: true}); err != ErrInvalid {
t.Fatalf("enabled without host/from/recipients must be invalid, got %v", err)
}
if _, err := normalize(SettingsInput{Host: "smtp.example.com", From: "kb@example.com", Recipients: []string{"not-an-address"}, Enabled: true}); err == nil {
t.Fatal("a malformed recipient must be rejected")
}
good, err := normalize(SettingsInput{Host: "smtp.example.com", From: "kb@example.com", Recipients: []string{"a@example.com", "b@example.com"}, Enabled: true})
if err != nil || good.Port != 465 || good.Weekday != 1 || len(good.Recipients) != 2 {
t.Fatalf("defaults not applied: %+v %v", good, err)
}
duplicated := SettingsInput{Host: "smtp.example.com", From: "kb@example.com", Recipients: []string{"a@example.com", "A@example.com"}}
if _, err := normalize(duplicated); err != ErrInvalid {
t.Fatal("case-insensitive duplicate recipients must be rejected")
}
}
func TestBuildMIMEProvidesReadableTextAndHTMLWithEncodedSubject(t *testing.T) {
html, text := renderReport("# 知识库周报 2026-W43\n\n## 二、核心指标\n\n正确率:90.66%\n")
if !strings.Contains(html, "<h1>") || !strings.Contains(html, "90.66%") {
t.Fatalf("rendered weekly HTML missing structure or metrics: %s", html[:120])
}
if !strings.Contains(text, "正确率:90.66%") {
t.Fatal("plain text body must keep the readable report")
}
raw := buildMIME(Message{From: "kb@example.com", To: []string{"lead@example.com"}, Subject: "知识库周报 2026-W43", HTML: html, Text: text}, "<id@example.com>", "BOUND")
for _, want := range []string{"Content-Type: multipart/alternative", "text/plain", "text/html", "Message-ID: <id@example.com>", "Subject: =?UTF-8?B?"} {
if !strings.Contains(raw, want) {
t.Fatalf("MIME payload missing %q", want)
}
}
encoded := base64.StdEncoding.EncodeToString([]byte("知识库周报 2026-W43"))
if !strings.Contains(raw, encoded) {
t.Fatal("subject must be RFC2047-encoded so Chinese survives clients")
}
}
type fakeMailer struct {
sent []Message
configs []SMTPConfig
err error
}
func (f *fakeMailer) Send(_ context.Context, cfg SMTPConfig, msg Message) (string, error) {
f.configs = append(f.configs, cfg)
if f.err != nil {
return "", f.err
}
f.sent = append(f.sent, msg)
return "<fake@example.com>", nil
}
func TestMailerRefusesPlaintextServersWithoutSTARTTLS(t *testing.T) {
if _, err := (SMTPMailer{}).Send(context.Background(), SMTPConfig{Host: "127.0.0.1", Port: 25}, Message{From: "kb@example.com", To: []string{"a@example.com"}, Subject: "x"}); err == nil {
t.Fatal("a server that cannot encrypt must be refused rather than sent in clear")
}
}