feat: keep table binding messages out of QA

This commit is contained in:
姚章浩
2026-08-13 12:55:00 +08:00
parent 2d9490f424
commit 5036071ac2
4 changed files with 108 additions and 15 deletions
+1 -1
View File
@@ -14,7 +14,7 @@ func (r *dingTalkSettingsRouter) Handle(ctx context.Context, m dingtalk.Settings
if r == nil || r.controller == nil {
return false, "", nil
}
if _, ok := settings.ParseCommand(m.Text); !ok {
if !r.controller.ShouldHandle(ctx, m.TenantKey, m.StaffID, m.Text) {
return false, "", nil
}
out, err := r.controller.Handle(ctx, settings.SettingInput{TenantKey: m.TenantKey, Channel: m.Channel, StaffID: m.StaffID, UnionID: m.UnionID, DisplayName: m.DisplayName, Department: m.Department, Text: m.Text, ConversationType: m.ConversationType, ConversationID: m.ConversationID, ConversationTitle: m.ConversationTitle})
+53 -13
View File
@@ -17,12 +17,19 @@ type BootstrapCandidate struct {
TenantKey, Code, StaffID, UnionID, DisplayName, Department string
DetectedAt time.Time
}
type SettingSession struct {
TenantKey, StaffID, ConversationID, ConversationType, PendingAction string
ExpiresAt time.Time
}
type SettingInput struct{ TenantKey, Channel, StaffID, UnionID, DisplayName, Department, Text, ConversationType, ConversationID, ConversationTitle string }
type ControllerRepository interface {
IsAdministrator(context.Context, string, string) (bool, error)
SetPreference(context.Context, string, string, string, string) error
SaveBinding(context.Context, ResourceBinding) error
DetectBootstrapCandidate(context.Context, BootstrapCandidate) error
GetSettingSession(context.Context, string, string) (SettingSession, bool, error)
SaveSettingSession(context.Context, SettingSession) error
DeleteSettingSession(context.Context, string, string) error
}
type Controller struct {
repo ControllerRepository
@@ -32,25 +39,51 @@ type Controller struct {
func NewController(repo ControllerRepository) *Controller {
return &Controller{repo: repo, now: time.Now}
}
func (c *Controller) ShouldHandle(ctx context.Context, tenant, staff, text string) bool {
if _, ok := ParseCommand(text); ok {
return true
}
if c == nil || c.repo == nil {
return false
}
s, ok, err := c.repo.GetSettingSession(ctx, tenant, staff)
return err == nil && ok && s.ExpiresAt.After(c.now())
}
func (c *Controller) Handle(ctx context.Context, in SettingInput) (string, error) {
if c == nil || c.repo == nil {
return "", errors.New("settings repository is required")
}
cmd, ok := ParseCommand(in.Text)
if !ok {
return "", nil
cmd, explicit := ParseCommand(in.Text)
var action string
var args []string
if explicit {
args = cmd.Args
} else {
s, ok, err := c.repo.GetSettingSession(ctx, in.TenantKey, in.StaffID)
if err != nil {
return "", err
}
if !ok || !s.ExpiresAt.After(c.now()) {
return "", nil
}
if strings.TrimSpace(in.Text) == "取消" {
_ = c.repo.DeleteSettingSession(ctx, in.TenantKey, in.StaffID)
return "已取消设置。", nil
}
action = s.PendingAction
args = []string{action, strings.TrimSpace(in.Text)}
}
if len(cmd.Args) == 1 && len(cmd.Args[0]) == 6 && allDigits(cmd.Args[0]) {
if explicit && len(args) == 1 && len(args[0]) == 6 && allDigits(args[0]) {
if strings.TrimSpace(in.ConversationType) != "direct" {
return "管理员绑定码只能私聊机器人使用。", nil
}
err := c.repo.DetectBootstrapCandidate(ctx, BootstrapCandidate{TenantKey: in.TenantKey, Code: cmd.Args[0], StaffID: in.StaffID, UnionID: in.UnionID, DisplayName: in.DisplayName, Department: in.Department, DetectedAt: c.now()})
err := c.repo.DetectBootstrapCandidate(ctx, BootstrapCandidate{TenantKey: in.TenantKey, Code: args[0], StaffID: in.StaffID, UnionID: in.UnionID, DisplayName: in.DisplayName, Department: in.Department, DetectedAt: c.now()})
if err != nil {
return "", err
}
return "身份已验证,请回到后台确认首位管理员。", nil
}
if len(cmd.Args) == 0 {
if explicit && len(args) == 0 {
admin, err := c.repo.IsAdministrator(ctx, in.TenantKey, in.StaffID)
if err != nil {
return "", err
@@ -60,15 +93,17 @@ func (c *Controller) Handle(ctx context.Context, in SettingInput) (string, error
}
return "⚙️ 我的设置:/setting language <auto|zh-CN|en|ja|ko|es>", nil
}
action := strings.ToLower(cmd.Args[0])
if action == "" {
action = strings.ToLower(args[0])
}
if action == "language" {
if len(cmd.Args) != 2 || !validLocale(cmd.Args[1]) {
if len(args) != 2 || !validLocale(args[1]) {
return "可选语言:auto、zh-CN、en、ja、ko、es。", nil
}
if err := c.repo.SetPreference(ctx, in.TenantKey, defaultChannel(in.Channel), in.StaffID, cmd.Args[1]); err != nil {
if err := c.repo.SetPreference(ctx, in.TenantKey, defaultChannel(in.Channel), in.StaffID, args[1]); err != nil {
return "", err
}
return "✅ 回答语言已设置为 " + cmd.Args[1] + "。", nil
return "✅ 回答语言已设置为 " + args[1] + "。", nil
}
admin, err := c.repo.IsAdministrator(ctx, in.TenantKey, in.StaffID)
if err != nil {
@@ -87,16 +122,21 @@ func (c *Controller) Handle(ctx context.Context, in SettingInput) (string, error
return "✅ 当前群已保存为技术支持群(待后台验证)。", nil
}
case "question", "faq":
if len(cmd.Args) != 2 {
return "请在命令后发送钉钉AI表格链接。", nil
if len(args) != 2 {
err = c.repo.SaveSettingSession(ctx, SettingSession{TenantKey: in.TenantKey, StaffID: in.StaffID, ConversationID: in.ConversationID, ConversationType: in.ConversationType, PendingAction: action, ExpiresAt: c.now().Add(10 * time.Minute)})
if err != nil {
return "", err
}
return "请在10分钟内发送钉钉AI表格中的任意记录链接,发送“取消”退出。", nil
}
link, e := ParseNotableLink(cmd.Args[1])
link, e := ParseNotableLink(args[1])
if e != nil {
return "AI表格链接无法识别。", nil
}
kind := action + "_table"
err = c.repo.SaveBinding(ctx, ResourceBinding{Kind: kind, TenantKey: in.TenantKey, BaseID: link.BaseID, SheetID: link.SheetID, ViewID: link.ViewID, OperatorID: in.UnionID, CreatedByStaffID: in.StaffID})
if err == nil {
_ = c.repo.DeleteSettingSession(ctx, in.TenantKey, in.StaffID)
return fmt.Sprintf("✅ %s已解析并保存为待验证配置。", map[string]string{"question": "问题AI表格", "faq": "FAQ表格"}[action]), nil
}
default:
+38 -1
View File
@@ -2,6 +2,7 @@ package settings
import (
"context"
"strings"
"testing"
"time"
)
@@ -11,10 +12,11 @@ type memoryRepo struct {
prefs map[string]string
bindings map[string]ResourceBinding
candidate BootstrapCandidate
sessions map[string]SettingSession
}
func newMemoryRepo() *memoryRepo {
return &memoryRepo{admins: map[string]bool{}, prefs: map[string]string{}, bindings: map[string]ResourceBinding{}}
return &memoryRepo{admins: map[string]bool{}, prefs: map[string]string{}, bindings: map[string]ResourceBinding{}, sessions: map[string]SettingSession{}}
}
func (r *memoryRepo) IsAdministrator(_ context.Context, tenant, staff string) (bool, error) {
return r.admins[tenant+"/"+staff], nil
@@ -31,6 +33,19 @@ func (r *memoryRepo) DetectBootstrapCandidate(_ context.Context, c BootstrapCand
r.candidate = c
return nil
}
func (r *memoryRepo) GetSettingSession(_ context.Context, tenant, staff string) (SettingSession, bool, error) {
s, ok := r.sessions[tenant+"/"+staff]
return s, ok, nil
}
func (r *memoryRepo) SaveSettingSession(_ context.Context, s SettingSession) error {
r.sessions[s.TenantKey+"/"+s.StaffID] = s
return nil
}
func (r *memoryRepo) DeleteSettingSession(_ context.Context, tenant, staff string) error {
delete(r.sessions, tenant+"/"+staff)
return nil
}
func TestControllerLanguageForOrdinaryUser(t *testing.T) {
r := newMemoryRepo()
c := NewController(r)
@@ -77,6 +92,28 @@ func TestControllerParsesAdminQuestionTable(t *testing.T) {
t.Fatalf("binding=%+v", r.bindings)
}
}
func TestControllerAcceptsTableLinkInNextMessage(t *testing.T) {
r := newMemoryRepo()
r.admins["t/a"] = true
c := NewController(r)
out, err := c.Handle(context.Background(), SettingInput{TenantKey: "t", Channel: "dingtalk", StaffID: "a", Text: "/setting question", ConversationType: "direct"})
if err != nil || !strings.Contains(out, "链接") {
t.Fatalf("out=%q err=%v", out, err)
}
if !c.ShouldHandle(context.Background(), "t", "a", "https://alidocs.dingtalk.com/i/nodes/base?sheetId=sheet&viewId=view") {
t.Fatal("active setting session must intercept next message")
}
_, err = c.Handle(context.Background(), SettingInput{TenantKey: "t", Channel: "dingtalk", StaffID: "a", UnionID: "union", Text: "https://alidocs.dingtalk.com/i/nodes/base?sheetId=sheet&viewId=view", ConversationType: "direct"})
if err != nil {
t.Fatal(err)
}
if r.bindings["question_table"].BaseID != "base" {
t.Fatalf("binding=%+v", r.bindings)
}
if _, ok := r.sessions["t/a"]; ok {
t.Fatal("setting session must be cleared")
}
}
func TestControllerDetectsBootstrapCandidate(t *testing.T) {
r := newMemoryRepo()
c := NewController(r)
+16
View File
@@ -45,6 +45,22 @@ func (r *SettingsRepository) GetPreference(ctx context.Context, tenant, channel,
}
return locale, err
}
func (r *SettingsRepository) GetSettingSession(ctx context.Context, tenant, staff string) (settings.SettingSession, bool, error) {
var session settings.SettingSession
err := r.store.pool.QueryRow(ctx, `SELECT tenant_key,staff_id,conversation_id,conversation_type,pending_action,expires_at FROM setting_sessions WHERE tenant_key=$1 AND staff_id=$2 AND expires_at>NOW()`, tenant, staff).Scan(&session.TenantKey, &session.StaffID, &session.ConversationID, &session.ConversationType, &session.PendingAction, &session.ExpiresAt)
if errors.Is(err, pgx.ErrNoRows) {
return settings.SettingSession{}, false, nil
}
return session, err == nil, err
}
func (r *SettingsRepository) SaveSettingSession(ctx context.Context, session settings.SettingSession) error {
_, err := r.store.pool.Exec(ctx, `INSERT INTO setting_sessions(tenant_key,staff_id,conversation_id,conversation_type,current_step,pending_action,draft_config,expires_at) VALUES($1,$2,$3,$4,'waiting_input',$5,'{}'::JSONB,$6) ON CONFLICT(tenant_key,staff_id) DO UPDATE SET conversation_id=EXCLUDED.conversation_id,conversation_type=EXCLUDED.conversation_type,current_step='waiting_input',pending_action=EXCLUDED.pending_action,draft_config='{}'::JSONB,expires_at=EXCLUDED.expires_at,updated_at=NOW()`, session.TenantKey, session.StaffID, session.ConversationID, session.ConversationType, session.PendingAction, session.ExpiresAt)
return err
}
func (r *SettingsRepository) DeleteSettingSession(ctx context.Context, tenant, staff string) error {
_, err := r.store.pool.Exec(ctx, `DELETE FROM setting_sessions WHERE tenant_key=$1 AND staff_id=$2`, tenant, staff)
return err
}
func (r *SettingsRepository) SaveBinding(ctx context.Context, b settings.ResourceBinding) error {
payload, err := json.Marshal(map[string]string{"conversation_id": b.ConversationID, "conversation_title": b.ConversationTitle, "base_id": b.BaseID, "sheet_id": b.SheetID, "view_id": b.ViewID, "operator_id": b.OperatorID})
if err != nil {