feat: add DingTalk answer feedback workflow

This commit is contained in:
姚章浩
2026-07-21 15:23:57 +08:00
parent f0d3d5b50d
commit 38560c5f41
19 changed files with 1450 additions and 36 deletions
+125
View File
@@ -0,0 +1,125 @@
package feedback
import (
"context"
"crypto/rand"
"errors"
"fmt"
"strings"
)
// Service handles answer feedback domain logic. It validates incoming
// commands, normalizes fields, generates cryptographically random IDs,
// and delegates persistence to a Repository.
type Service struct {
tenantKey string
channel string
repo Repository
gen IDGenerator
}
// NewService creates a feedback Service. It rejects empty tenant, empty
// channel, and nil repo. An optional IDGenerator can be provided for
// deterministic testing; if nil, a crypto/rand UUIDv4 generator is used.
func NewService(tenantKey, channel string, repo Repository, gen ...IDGenerator) (*Service, error) {
if strings.TrimSpace(tenantKey) == "" {
return nil, errors.New("tenant_key must not be empty")
}
if strings.TrimSpace(channel) == "" {
return nil, errors.New("channel must not be empty")
}
if repo == nil {
return nil, errors.New("repository must not be nil")
}
if len(gen) > 1 {
return nil, errors.New("at most one IDGenerator allowed")
}
var idGen IDGenerator
if len(gen) == 1 {
idGen = gen[0]
} else {
idGen = &defaultIDGenerator{}
}
if idGen == nil {
return nil, errors.New("IDGenerator must not be nil")
}
return &Service{
tenantKey: strings.TrimSpace(tenantKey),
channel: strings.TrimSpace(channel),
repo: repo,
gen: idGen,
}, nil
}
// defaultIDGenerator produces UUIDv4-style 128-bit random IDs.
type defaultIDGenerator struct{}
func (g *defaultIDGenerator) Generate() (string, error) {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return "", err
}
b[6] = (b[6] & 0x0f) | 0x40 // version 4
b[8] = (b[8] & 0x3f) | 0x80 // variant 8-9-a-b
return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x",
b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil
}
// Apply validates and processes a feedback Command. It trims inputs,
// validates allowed values, normalizes reason codes, generates IDs,
// and delegates to the Repository.
func (s *Service) Apply(ctx context.Context, cmd Command) (Result, error) {
cmd.ExternalActorID = strings.TrimSpace(cmd.ExternalActorID)
cmd.OutTrackID = strings.TrimSpace(cmd.OutTrackID)
cmd.Value = strings.TrimSpace(cmd.Value)
cmd.ReasonCode = strings.TrimSpace(cmd.ReasonCode)
cmd.Source = strings.TrimSpace(cmd.Source)
if cmd.ExternalActorID == "" || len(cmd.ExternalActorID) > 256 {
return Result{}, fmt.Errorf("%w: external actor ID", ErrInvalidCommand)
}
if cmd.OutTrackID == "" || len(cmd.OutTrackID) > 256 {
return Result{}, fmt.Errorf("%w: outTrackID", ErrInvalidCommand)
}
if cmd.Value != ValueUp && cmd.Value != ValueDown {
return Result{}, fmt.Errorf("%w: value", ErrInvalidCommand)
}
if cmd.Source != SourceDingTalkCard {
return Result{}, fmt.Errorf("%w: source", ErrInvalidCommand)
}
if cmd.Value == ValueUp {
cmd.ReasonCode = ReasonEmpty
} else if !validReason(cmd.ReasonCode) {
return Result{}, fmt.Errorf("%w: reason code", ErrInvalidCommand)
}
feedbackID, err := s.gen.Generate()
if err != nil {
return Result{}, fmt.Errorf("generate feedback ID: %w", err)
}
if strings.TrimSpace(feedbackID) == "" {
return Result{}, errors.New("generate feedback ID: empty ID")
}
actorID, err := s.gen.Generate()
if err != nil {
return Result{}, fmt.Errorf("generate actor ID: %w", err)
}
if strings.TrimSpace(actorID) == "" {
return Result{}, errors.New("generate actor ID: empty ID")
}
return s.repo.RecordFeedback(ctx, Record{
ID: feedbackID, TenantKey: s.tenantKey, Channel: s.channel, ActorID: actorID,
ExternalActorID: cmd.ExternalActorID, OutTrackID: cmd.OutTrackID,
Value: cmd.Value, ReasonCode: cmd.ReasonCode, Source: cmd.Source,
})
}
func validReason(reason string) bool {
switch reason {
case ReasonEmpty, ReasonIncorrect, ReasonNotResolved, ReasonIrrelevant, ReasonUnclear, ReasonOutdated, ReasonOther:
return true
default:
return false
}
}
+189
View File
@@ -0,0 +1,189 @@
package feedback_test
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/feedback"
)
type stubRepo struct {
calls int
lastRecord feedback.Record
result feedback.Result
err error
}
func (s *stubRepo) RecordFeedback(_ context.Context, record feedback.Record) (feedback.Result, error) {
s.calls++
s.lastRecord = record
return s.result, s.err
}
type sequenceGenerator struct {
ids []string
errs map[int]error
calls int
}
func (g *sequenceGenerator) Generate() (string, error) {
index := g.calls
g.calls++
if err := g.errs[index]; err != nil {
return "", err
}
if index >= len(g.ids) {
return "", errors.New("no id configured")
}
return g.ids[index], nil
}
func TestNewServiceValidation(t *testing.T) {
repo := &stubRepo{}
gen := &sequenceGenerator{ids: []string{"a", "b"}, errs: map[int]error{}}
for _, tc := range []struct {
name string
tenant string
channel string
repo feedback.Repository
gens []feedback.IDGenerator
}{
{name: "empty tenant", channel: "dingtalk", repo: repo},
{name: "empty channel", tenant: "tenant", repo: repo},
{name: "nil repository", tenant: "tenant", channel: "dingtalk"},
{name: "nil generator", tenant: "tenant", channel: "dingtalk", repo: repo, gens: []feedback.IDGenerator{nil}},
{name: "too many generators", tenant: "tenant", channel: "dingtalk", repo: repo, gens: []feedback.IDGenerator{gen, gen}},
} {
t.Run(tc.name, func(t *testing.T) {
if _, err := feedback.NewService(tc.tenant, tc.channel, tc.repo, tc.gens...); err == nil {
t.Fatal("expected constructor error")
}
})
}
}
func TestApplyUpUsesServerScopeTrimsAndClearsReason(t *testing.T) {
repo := &stubRepo{result: feedback.Result{Created: true, Value: feedback.ValueUp}}
gen := &sequenceGenerator{ids: []string{"feedback-id", "actor-id"}, errs: map[int]error{}}
service, err := feedback.NewService(" tenant-a ", " dingtalk ", repo, gen)
if err != nil {
t.Fatal(err)
}
result, err := service.Apply(context.Background(), feedback.Command{
ExternalActorID: " user-a ", OutTrackID: " track-a ", Value: feedback.ValueUp,
ReasonCode: feedback.ReasonIncorrect, Source: feedback.SourceDingTalkCard,
})
if err != nil {
t.Fatal(err)
}
if !result.Created || repo.calls != 1 || gen.calls != 2 {
t.Fatalf("result=%+v repo_calls=%d gen_calls=%d", result, repo.calls, gen.calls)
}
got := repo.lastRecord
if got.ID != "feedback-id" || got.ActorID != "actor-id" || got.TenantKey != "tenant-a" || got.Channel != "dingtalk" || got.ExternalActorID != "user-a" || got.OutTrackID != "track-a" || got.Value != feedback.ValueUp || got.ReasonCode != "" || got.Source != feedback.SourceDingTalkCard {
t.Fatalf("record=%+v", got)
}
}
func TestApplyDownAcceptsEveryReasonAndEmpty(t *testing.T) {
reasons := []string{
feedback.ReasonEmpty, feedback.ReasonIncorrect, feedback.ReasonNotResolved,
feedback.ReasonIrrelevant, feedback.ReasonUnclear, feedback.ReasonOutdated, feedback.ReasonOther,
}
for _, reason := range reasons {
t.Run("reason_"+reason, func(t *testing.T) {
repo := &stubRepo{result: feedback.Result{Changed: true, Value: feedback.ValueDown, ReasonCode: reason}}
gen := &sequenceGenerator{ids: []string{"feedback-id", "actor-id"}, errs: map[int]error{}}
service, _ := feedback.NewService("tenant", "dingtalk", repo, gen)
result, err := service.Apply(context.Background(), feedback.Command{
ExternalActorID: "user", OutTrackID: "track", Value: feedback.ValueDown,
ReasonCode: " " + reason + " ", Source: feedback.SourceDingTalkCard,
})
if err != nil {
t.Fatal(err)
}
if repo.lastRecord.ReasonCode != reason || result.ReasonCode != reason {
t.Fatalf("record=%+v result=%+v", repo.lastRecord, result)
}
})
}
}
func TestApplyRejectsInvalidCommandsBeforeGeneratingIDs(t *testing.T) {
tooLong := strings.Repeat("x", 257)
for _, tc := range []struct {
name string
cmd feedback.Command
}{
{name: "empty actor", cmd: feedback.Command{OutTrackID: "track", Value: feedback.ValueUp, Source: feedback.SourceDingTalkCard}},
{name: "empty track", cmd: feedback.Command{ExternalActorID: "user", Value: feedback.ValueUp, Source: feedback.SourceDingTalkCard}},
{name: "long actor", cmd: feedback.Command{ExternalActorID: tooLong, OutTrackID: "track", Value: feedback.ValueUp, Source: feedback.SourceDingTalkCard}},
{name: "long track", cmd: feedback.Command{ExternalActorID: "user", OutTrackID: tooLong, Value: feedback.ValueUp, Source: feedback.SourceDingTalkCard}},
{name: "invalid value", cmd: feedback.Command{ExternalActorID: "user", OutTrackID: "track", Value: "maybe", Source: feedback.SourceDingTalkCard}},
{name: "invalid source", cmd: feedback.Command{ExternalActorID: "user", OutTrackID: "track", Value: feedback.ValueUp, Source: "web"}},
{name: "invalid down reason", cmd: feedback.Command{ExternalActorID: "user", OutTrackID: "track", Value: feedback.ValueDown, ReasonCode: "secret", Source: feedback.SourceDingTalkCard}},
} {
t.Run(tc.name, func(t *testing.T) {
repo := &stubRepo{}
gen := &sequenceGenerator{ids: []string{"feedback-id", "actor-id"}, errs: map[int]error{}}
service, _ := feedback.NewService("tenant", "dingtalk", repo, gen)
if _, err := service.Apply(context.Background(), tc.cmd); !errors.Is(err, feedback.ErrInvalidCommand) {
t.Fatalf("error=%v", err)
}
if repo.calls != 0 || gen.calls != 0 {
t.Fatalf("repo_calls=%d gen_calls=%d", repo.calls, gen.calls)
}
})
}
}
func TestApplyIDFailureNeverCallsRepository(t *testing.T) {
idErr := errors.New("entropy unavailable")
for _, failureIndex := range []int{0, 1} {
t.Run(string(rune('0'+failureIndex)), func(t *testing.T) {
repo := &stubRepo{}
gen := &sequenceGenerator{ids: []string{"feedback-id", "actor-id"}, errs: map[int]error{failureIndex: idErr}}
service, _ := feedback.NewService("tenant", "dingtalk", repo, gen)
_, err := service.Apply(context.Background(), feedback.Command{ExternalActorID: "user", OutTrackID: "track", Value: feedback.ValueUp, Source: feedback.SourceDingTalkCard})
if !errors.Is(err, idErr) || repo.calls != 0 {
t.Fatalf("error=%v repo_calls=%d", err, repo.calls)
}
})
}
}
func TestApplyPassesThroughRepositoryResultAndError(t *testing.T) {
repoErr := errors.New("repository failed")
for _, tc := range []struct {
name string
result feedback.Result
err error
}{
{name: "replayed", result: feedback.Result{Replayed: true, Value: feedback.ValueDown, ReasonCode: feedback.ReasonUnclear}},
{name: "error", err: repoErr},
} {
t.Run(tc.name, func(t *testing.T) {
repo := &stubRepo{result: tc.result, err: tc.err}
gen := &sequenceGenerator{ids: []string{"feedback-id", "actor-id"}, errs: map[int]error{}}
service, _ := feedback.NewService("tenant", "dingtalk", repo, gen)
result, err := service.Apply(context.Background(), feedback.Command{ExternalActorID: "user", OutTrackID: "track", Value: feedback.ValueDown, ReasonCode: feedback.ReasonUnclear, Source: feedback.SourceDingTalkCard})
if !errors.Is(err, tc.err) || result != tc.result {
t.Fatalf("result=%+v error=%v", result, err)
}
})
}
}
func TestRecordCannotBeSerializedIntoExternalJSON(t *testing.T) {
record := feedback.Record{ID: "feedback-id", TenantKey: "tenant", Channel: "dingtalk", ActorID: "actor-id", ExternalActorID: "user", OutTrackID: "provider-track", Value: feedback.ValueDown, ReasonCode: feedback.ReasonOther, Source: feedback.SourceDingTalkCard}
encoded, err := json.Marshal(record)
if err != nil {
t.Fatal(err)
}
if string(encoded) != "{}" {
t.Fatalf("internal record must not be JSON-exposable: %s", encoded)
}
}
+87
View File
@@ -0,0 +1,87 @@
// Package feedback implements the domain logic for answer feedback
// (B2 DingTalk card callback). It validates and normalizes incoming
// feedback commands, generates cryptographically random IDs, and
// delegates persistence to a Repository.
//
// The package is intentionally free of any webhook, token, raw-callback,
// content, or extension columns — those belong to the channel layer.
package feedback
import (
"context"
"errors"
)
var (
ErrInvalidCommand = errors.New("invalid feedback command")
ErrTargetNotFound = errors.New("feedback target not found")
)
// Value constants for feedback.
const (
ValueUp = "up"
ValueDown = "down"
)
// ReasonCode constants for down feedback.
const (
ReasonEmpty = ""
ReasonIncorrect = "incorrect"
ReasonNotResolved = "not_resolved"
ReasonIrrelevant = "irrelevant"
ReasonUnclear = "unclear"
ReasonOutdated = "outdated"
ReasonOther = "other"
)
// Source constants.
const (
SourceDingTalkCard = "dingtalk_card"
)
// Command represents a feedback action from an external channel.
// Only the caller-provided fields are exposed; tenant, channel, turn,
// and message are fixed by the Service and never accepted from callers.
type Command struct {
ExternalActorID string // external actor identifier (required)
OutTrackID string // outbound tracking/answer identifier (required)
Value string // "up" or "down"
ReasonCode string // optional reason for "down"
Source string // must be "dingtalk_card"
}
// Record is the full domain object passed to the Repository for persistence.
// It contains the fixed tenant/channel, cryptographically random IDs, and
// the normalized command fields.
type Record struct {
ID string `json:"-"`
TenantKey string `json:"-"`
Channel string `json:"-"`
ActorID string `json:"-"`
Value string `json:"-"`
ReasonCode string `json:"-"`
Source string `json:"-"`
ExternalActorID string `json:"-"`
OutTrackID string `json:"-"`
}
// Result reports the outcome of a RecordFeedback call.
// Exactly one of Created, Changed, or Replayed is true.
type Result struct {
Created bool
Changed bool
Replayed bool
Value string
ReasonCode string
}
// Repository persists feedback records.
type Repository interface {
RecordFeedback(ctx context.Context, r Record) (Result, error)
}
// IDGenerator produces unique IDs. The default implementation uses
// crypto/rand to produce UUIDv4-style strings.
type IDGenerator interface {
Generate() (string, error)
}