feat: add DingTalk answer feedback workflow
This commit is contained in:
@@ -19,12 +19,21 @@ const listAuditTurnsSQL = `SELECT
|
||||
COALESCE(a.external_actor_id,''),COALESCE(rm.actor_name_snapshot,''),
|
||||
LEFT(t.question,200),LEFT(t.answer,200),
|
||||
CASE WHEN jsonb_typeof(t.references_json)='array' THEN jsonb_array_length(t.references_json) ELSE 0 END,
|
||||
COALESCE(am.status,''),COALESCE(am.delivery_method,'')
|
||||
COALESCE(am.status,''),COALESCE(am.delivery_method,''),
|
||||
COALESCE(fc.up_count,0),COALESCE(fc.down_count,0),COALESCE(fc.unresolved_count,0)
|
||||
FROM turns t
|
||||
LEFT JOIN messages rm ON rm.id=t.request_message_id AND rm.tenant_key=t.tenant_key AND rm.channel=t.channel
|
||||
LEFT JOIN messages am ON am.id=t.answer_message_id AND am.tenant_key=t.tenant_key AND am.channel=t.channel
|
||||
LEFT JOIN channel_conversations c ON c.id=rm.conversation_id AND c.tenant_key=t.tenant_key AND c.channel=t.channel
|
||||
LEFT JOIN channel_actors a ON a.id=rm.actor_id AND a.tenant_key=t.tenant_key AND a.channel=t.channel
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT
|
||||
(COUNT(*) FILTER (WHERE af.value='up'))::int AS up_count,
|
||||
(COUNT(*) FILTER (WHERE af.value='down'))::int AS down_count,
|
||||
(COUNT(*) FILTER (WHERE af.value='down' AND af.reason_code=''))::int AS unresolved_count
|
||||
FROM answer_feedback af
|
||||
WHERE af.tenant_key=t.tenant_key AND af.channel=t.channel AND af.turn_id=t.id
|
||||
) fc ON TRUE
|
||||
WHERE t.tenant_key=$1
|
||||
AND ($2='' OR t.channel=$2)
|
||||
AND ($3='' OR t.status=$3)
|
||||
@@ -38,12 +47,25 @@ const getAuditTurnSQL = `SELECT
|
||||
COALESCE(a.external_actor_id,''),COALESCE(rm.actor_name_snapshot,''),
|
||||
t.question,t.answer,t.references_json,t.media_json,
|
||||
COALESCE(rm.id,''),COALESCE(rm.direction,''),COALESCE(rm.role,''),COALESCE(rm.message_type,''),COALESCE(rm.status,''),COALESCE(rm.actor_name_snapshot,''),rm.created_at,
|
||||
COALESCE(am.id,''),COALESCE(am.direction,''),COALESCE(am.role,''),COALESCE(am.message_type,''),COALESCE(am.status,''),am.created_at,am.delivered_at,COALESCE(am.delivery_method,''),COALESCE(am.failure_code,'')
|
||||
COALESCE(am.id,''),COALESCE(am.direction,''),COALESCE(am.role,''),COALESCE(am.message_type,''),COALESCE(am.status,''),am.created_at,am.delivered_at,COALESCE(am.delivery_method,''),COALESCE(am.failure_code,''),
|
||||
COALESCE(ff.feedback_json,'[]'::jsonb)
|
||||
FROM turns t
|
||||
LEFT JOIN messages rm ON rm.id=t.request_message_id AND rm.tenant_key=t.tenant_key AND rm.channel=t.channel
|
||||
LEFT JOIN messages am ON am.id=t.answer_message_id AND am.tenant_key=t.tenant_key AND am.channel=t.channel
|
||||
LEFT JOIN channel_conversations c ON c.id=rm.conversation_id AND c.tenant_key=t.tenant_key AND c.channel=t.channel
|
||||
LEFT JOIN channel_actors a ON a.id=rm.actor_id AND a.tenant_key=t.tenant_key AND a.channel=t.channel
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT jsonb_agg(jsonb_build_object(
|
||||
'actor_external_id',fa.external_actor_id,
|
||||
'actor_display_name',fa.display_name,
|
||||
'value',af.value,
|
||||
'reason_code',af.reason_code,
|
||||
'updated_at',af.updated_at
|
||||
) ORDER BY af.updated_at DESC,af.id DESC) AS feedback_json
|
||||
FROM answer_feedback af
|
||||
JOIN channel_actors fa ON fa.id=af.actor_id AND fa.tenant_key=af.tenant_key AND fa.channel=af.channel
|
||||
WHERE af.tenant_key=t.tenant_key AND af.channel=t.channel AND af.turn_id=t.id
|
||||
) ff ON TRUE
|
||||
WHERE t.tenant_key=$1 AND t.id=$2`
|
||||
|
||||
func (s *Store) ListTurns(ctx context.Context, tenantKey string, query audit.ListQuery) ([]audit.TurnSummary, error) {
|
||||
@@ -66,6 +88,7 @@ func (s *Store) ListTurns(ctx context.Context, tenantKey string, query audit.Lis
|
||||
&item.ActorExternalID, &item.ActorDisplayName,
|
||||
&item.QuestionSummary, &item.AnswerSummary, &item.ReferenceCount,
|
||||
&item.AnswerDeliveryStatus, &item.AnswerDeliveryMethod,
|
||||
&item.FeedbackUpCount, &item.FeedbackDownCount, &item.FeedbackUnresolvedCount,
|
||||
); err != nil {
|
||||
return nil, fmt.Errorf("scan audit turn summary: %w", err)
|
||||
}
|
||||
@@ -81,7 +104,7 @@ func (s *Store) ListTurns(ctx context.Context, tenantKey string, query audit.Lis
|
||||
func (s *Store) GetTurn(ctx context.Context, tenantKey, turnID string) (audit.TurnDetail, error) {
|
||||
var detail audit.TurnDetail
|
||||
var status string
|
||||
var referencesJSON, mediaJSON []byte
|
||||
var referencesJSON, mediaJSON, feedbackJSON []byte
|
||||
var request audit.MessageMeta
|
||||
var answer audit.MessageMeta
|
||||
var requestCreated, answerCreated, deliveredAt *time.Time
|
||||
@@ -92,6 +115,7 @@ func (s *Store) GetTurn(ctx context.Context, tenantKey, turnID string) (audit.Tu
|
||||
&detail.Question, &detail.Answer, &referencesJSON, &mediaJSON,
|
||||
&request.ID, &request.Direction, &request.Role, &request.MessageType, &request.Status, &request.ActorName, &requestCreated,
|
||||
&answer.ID, &answer.Direction, &answer.Role, &answer.MessageType, &answer.Status, &answerCreated, &deliveredAt, &answer.DeliveryMethod, &answer.FailureCode,
|
||||
&feedbackJSON,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return audit.TurnDetail{}, audit.ErrNotFound
|
||||
@@ -117,6 +141,9 @@ func (s *Store) GetTurn(ctx context.Context, tenantKey, turnID string) (audit.Tu
|
||||
}
|
||||
}
|
||||
detail.Media = safeAuditMedia(media)
|
||||
if err := json.Unmarshal(feedbackJSON, &detail.Feedback); err != nil {
|
||||
return audit.TurnDetail{}, fmt.Errorf("decode audit feedback: %w", err)
|
||||
}
|
||||
|
||||
if request.ID != "" {
|
||||
if requestCreated != nil {
|
||||
|
||||
@@ -48,6 +48,29 @@ func TestAuditDetailSQLTenantSafeAndExcludesForbiddenData(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuditFeedbackProjectionIsTenantChannelScoped(t *testing.T) {
|
||||
listSQL := strings.ToUpper(listAuditTurnsSQL)
|
||||
for _, want := range []string{
|
||||
"FROM ANSWER_FEEDBACK AF", "AF.TENANT_KEY=T.TENANT_KEY", "AF.CHANNEL=T.CHANNEL", "AF.TURN_ID=T.ID",
|
||||
"COUNT(*) FILTER (WHERE AF.VALUE='UP')", "COUNT(*) FILTER (WHERE AF.VALUE='DOWN')",
|
||||
"AF.VALUE='DOWN' AND AF.REASON_CODE=''",
|
||||
} {
|
||||
if !strings.Contains(listSQL, want) {
|
||||
t.Errorf("list feedback projection missing %q", want)
|
||||
}
|
||||
}
|
||||
detailSQL := strings.ToUpper(getAuditTurnSQL)
|
||||
for _, want := range []string{
|
||||
"JSONB_AGG", "FROM ANSWER_FEEDBACK AF", "JOIN CHANNEL_ACTORS FA",
|
||||
"AF.TENANT_KEY=T.TENANT_KEY", "AF.CHANNEL=T.CHANNEL", "AF.TURN_ID=T.ID",
|
||||
"FA.TENANT_KEY=AF.TENANT_KEY", "FA.CHANNEL=AF.CHANNEL",
|
||||
} {
|
||||
if !strings.Contains(detailSQL, want) {
|
||||
t.Errorf("detail feedback projection missing %q", want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSafeAuditReferencesDropContentAndRaw(t *testing.T) {
|
||||
references := []core.Reference{{
|
||||
ID: "ref-1", KnowledgeID: "kb-1", KnowledgeTitle: "Manual", Score: 0.9,
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/feedback"
|
||||
)
|
||||
|
||||
const findFeedbackAnswerSQL = `SELECT m.id,t.id
|
||||
FROM messages m
|
||||
JOIN turns t ON t.id=m.correlation_id AND t.tenant_key=m.tenant_key AND t.channel=m.channel AND t.answer_message_id=m.id
|
||||
WHERE m.tenant_key=$1 AND m.channel=$2 AND m.provider_message_id=$3
|
||||
AND m.direction='outbound' AND m.role='assistant' AND m.status='sent' AND m.delivery_method='card'
|
||||
AND t.status='succeeded'`
|
||||
|
||||
const upsertFeedbackActorSQL = `INSERT INTO channel_actors
|
||||
(id,tenant_key,channel,external_actor_id,actor_type,display_name)
|
||||
VALUES($1,$2,$3,$4,'user','')
|
||||
ON CONFLICT (tenant_key,channel,external_actor_id) DO UPDATE SET
|
||||
updated_at=channel_actors.updated_at
|
||||
RETURNING id`
|
||||
|
||||
const findFeedbackStateSQL = `SELECT id,value,reason_code
|
||||
FROM answer_feedback
|
||||
WHERE tenant_key=$1 AND channel=$2 AND answer_message_id=$3 AND actor_id=$4
|
||||
FOR UPDATE`
|
||||
|
||||
const insertFeedbackStateSQL = `INSERT INTO answer_feedback
|
||||
(id,tenant_key,channel,answer_message_id,turn_id,actor_id,value,reason_code,source)
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)`
|
||||
|
||||
const updateFeedbackStateSQL = `UPDATE answer_feedback
|
||||
SET value=$1,reason_code=$2,source=$3,updated_at=NOW()
|
||||
WHERE id=$4 AND tenant_key=$5 AND channel=$6 AND answer_message_id=$7 AND actor_id=$8`
|
||||
|
||||
func (s *Store) RecordFeedback(ctx context.Context, record feedback.Record) (feedback.Result, error) {
|
||||
if err := validateFeedbackRecord(record); err != nil {
|
||||
return feedback.Result{}, err
|
||||
}
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return feedback.Result{}, fmt.Errorf("begin feedback transaction: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
var answerMessageID, turnID string
|
||||
err = tx.QueryRow(ctx, findFeedbackAnswerSQL, record.TenantKey, record.Channel, record.OutTrackID).Scan(&answerMessageID, &turnID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return feedback.Result{}, feedback.ErrTargetNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return feedback.Result{}, fmt.Errorf("find feedback answer: %w", err)
|
||||
}
|
||||
|
||||
lockKey := feedbackLockKey(record.TenantKey, record.Channel, answerMessageID, record.ExternalActorID)
|
||||
if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, lockKey); err != nil {
|
||||
return feedback.Result{}, fmt.Errorf("lock feedback state: %w", err)
|
||||
}
|
||||
|
||||
if err = tx.QueryRow(ctx, upsertFeedbackActorSQL,
|
||||
record.ActorID, record.TenantKey, record.Channel, record.ExternalActorID,
|
||||
).Scan(&record.ActorID); err != nil {
|
||||
return feedback.Result{}, fmt.Errorf("resolve feedback actor: %w", err)
|
||||
}
|
||||
|
||||
var existingID, existingValue, existingReason string
|
||||
err = tx.QueryRow(ctx, findFeedbackStateSQL,
|
||||
record.TenantKey, record.Channel, answerMessageID, record.ActorID,
|
||||
).Scan(&existingID, &existingValue, &existingReason)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
command, insertErr := tx.Exec(ctx, insertFeedbackStateSQL,
|
||||
record.ID, record.TenantKey, record.Channel, answerMessageID, turnID,
|
||||
record.ActorID, record.Value, record.ReasonCode, record.Source,
|
||||
)
|
||||
if insertErr != nil {
|
||||
return feedback.Result{}, fmt.Errorf("insert feedback state: %w", insertErr)
|
||||
}
|
||||
if command.RowsAffected() != 1 {
|
||||
return feedback.Result{}, errors.New("insert feedback state affected unexpected rows")
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return feedback.Result{}, fmt.Errorf("commit feedback create: %w", err)
|
||||
}
|
||||
return feedback.Result{Created: true, Value: record.Value, ReasonCode: record.ReasonCode}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return feedback.Result{}, fmt.Errorf("find feedback state: %w", err)
|
||||
}
|
||||
|
||||
if sameFeedbackState(existingValue, existingReason, record.Value, record.ReasonCode) {
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return feedback.Result{}, fmt.Errorf("commit feedback replay: %w", err)
|
||||
}
|
||||
return feedback.Result{Replayed: true, Value: existingValue, ReasonCode: existingReason}, nil
|
||||
}
|
||||
|
||||
command, err := tx.Exec(ctx, updateFeedbackStateSQL,
|
||||
record.Value, record.ReasonCode, record.Source, existingID,
|
||||
record.TenantKey, record.Channel, answerMessageID, record.ActorID,
|
||||
)
|
||||
if err != nil {
|
||||
return feedback.Result{}, fmt.Errorf("update feedback state: %w", err)
|
||||
}
|
||||
if command.RowsAffected() != 1 {
|
||||
return feedback.Result{}, errors.New("update feedback state affected unexpected rows")
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return feedback.Result{}, fmt.Errorf("commit feedback change: %w", err)
|
||||
}
|
||||
return feedback.Result{Changed: true, Value: record.Value, ReasonCode: record.ReasonCode}, nil
|
||||
}
|
||||
|
||||
func validateFeedbackRecord(record feedback.Record) error {
|
||||
if record.ID == "" || record.ActorID == "" || record.TenantKey == "" || record.Channel == "" ||
|
||||
record.ExternalActorID == "" || record.OutTrackID == "" || record.Source != feedback.SourceDingTalkCard {
|
||||
return feedback.ErrInvalidCommand
|
||||
}
|
||||
if record.Value != feedback.ValueUp && record.Value != feedback.ValueDown {
|
||||
return feedback.ErrInvalidCommand
|
||||
}
|
||||
if record.Value == feedback.ValueUp && record.ReasonCode != "" {
|
||||
return feedback.ErrInvalidCommand
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func feedbackLockKey(parts ...string) string {
|
||||
key := ""
|
||||
for _, part := range parts {
|
||||
key += fmt.Sprintf("%d:%s|", len(part), part)
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
func sameFeedbackState(existingValue, existingReason, value, reason string) bool {
|
||||
return existingValue == value && existingReason == reason
|
||||
}
|
||||
|
||||
var _ feedback.Repository = (*Store)(nil)
|
||||
@@ -0,0 +1,77 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/feedback"
|
||||
)
|
||||
|
||||
func TestFeedbackAnswerLookupRequiresExactDeliveredCard(t *testing.T) {
|
||||
sql := strings.ToUpper(findFeedbackAnswerSQL)
|
||||
for _, fragment := range []string{
|
||||
"FROM MESSAGES M", "JOIN TURNS T", "T.TENANT_KEY=M.TENANT_KEY", "T.CHANNEL=M.CHANNEL",
|
||||
"T.ANSWER_MESSAGE_ID=M.ID", "M.TENANT_KEY=$1", "M.CHANNEL=$2", "M.PROVIDER_MESSAGE_ID=$3",
|
||||
"M.DIRECTION='OUTBOUND'", "M.ROLE='ASSISTANT'", "M.STATUS='SENT'", "M.DELIVERY_METHOD='CARD'",
|
||||
"T.STATUS='SUCCEEDED'",
|
||||
} {
|
||||
if !strings.Contains(sql, fragment) {
|
||||
t.Errorf("answer lookup missing %q", fragment)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFeedbackActorAndStateSQLAreTenantChannelSafe(t *testing.T) {
|
||||
actor := strings.ToUpper(upsertFeedbackActorSQL)
|
||||
for _, fragment := range []string{
|
||||
"INSERT INTO CHANNEL_ACTORS", "TENANT_KEY", "CHANNEL", "EXTERNAL_ACTOR_ID",
|
||||
"ON CONFLICT (TENANT_KEY,CHANNEL,EXTERNAL_ACTOR_ID)", "RETURNING ID",
|
||||
} {
|
||||
if !strings.Contains(actor, fragment) {
|
||||
t.Errorf("actor upsert missing %q", fragment)
|
||||
}
|
||||
}
|
||||
lookup := strings.ToUpper(findFeedbackStateSQL)
|
||||
for _, fragment := range []string{"TENANT_KEY=$1", "CHANNEL=$2", "ANSWER_MESSAGE_ID=$3", "ACTOR_ID=$4", "FOR UPDATE"} {
|
||||
if !strings.Contains(lookup, fragment) {
|
||||
t.Errorf("feedback lookup missing %q", fragment)
|
||||
}
|
||||
}
|
||||
update := strings.ToUpper(updateFeedbackStateSQL)
|
||||
for _, fragment := range []string{"VALUE=$1", "REASON_CODE=$2", "SOURCE=$3", "UPDATED_AT=NOW()", "ID=$4", "TENANT_KEY=$5", "CHANNEL=$6", "ANSWER_MESSAGE_ID=$7", "ACTOR_ID=$8"} {
|
||||
if !strings.Contains(update, fragment) {
|
||||
t.Errorf("feedback update missing %q", fragment)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFeedbackStoreUsesShortSerializedTransaction(t *testing.T) {
|
||||
data, err := os.ReadFile("feedback.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
source := strings.ToUpper(string(data))
|
||||
for _, fragment := range []string{"BEGINTX", "PG_ADVISORY_XACT_LOCK", "ROLLBACK", "COMMIT"} {
|
||||
if !strings.Contains(source, fragment) {
|
||||
t.Errorf("feedback store missing transaction fragment %q", fragment)
|
||||
}
|
||||
}
|
||||
for _, forbidden := range []string{"SESSIONWEBHOOK", "ACCESS_TOKEN", "RAW_CALLBACK", "RAW_PAYLOAD", "CORP_ID", "EXTENSION"} {
|
||||
if strings.Contains(source, forbidden) {
|
||||
t.Errorf("feedback store contains forbidden %q", forbidden)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSameFeedbackState(t *testing.T) {
|
||||
if !sameFeedbackState(feedback.ValueDown, feedback.ReasonUnclear, feedback.ValueDown, feedback.ReasonUnclear) {
|
||||
t.Fatal("identical feedback must be replayed")
|
||||
}
|
||||
if sameFeedbackState(feedback.ValueDown, feedback.ReasonUnclear, feedback.ValueDown, feedback.ReasonOther) {
|
||||
t.Fatal("reason change must be a state change")
|
||||
}
|
||||
if sameFeedbackState(feedback.ValueDown, "", feedback.ValueUp, "") {
|
||||
t.Fatal("value change must be a state change")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user