feat: add DingTalk directory-backed session titles
This commit is contained in:
@@ -0,0 +1,82 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/directory"
|
||||
)
|
||||
|
||||
func (s *Store) LookupDirectoryProfile(ctx context.Context, tenantKey, staffID string) (directory.Profile, bool, error) {
|
||||
tenantKey = strings.TrimSpace(tenantKey)
|
||||
staffID = strings.TrimSpace(staffID)
|
||||
if tenantKey == "" || staffID == "" {
|
||||
return directory.Profile{}, false, errors.New("tenant and staff id are required")
|
||||
}
|
||||
var profile directory.Profile
|
||||
var departmentIDs []byte
|
||||
err := s.pool.QueryRow(ctx, `SELECT staff_id,union_id,name,nickname,job_title,department_ids,department_name,main_department_name,region,employment_status,source,synced_at
|
||||
FROM directory_profiles WHERE tenant_key=$1 AND staff_id=$2`, tenantKey, staffID).Scan(
|
||||
&profile.StaffID, &profile.UnionID, &profile.Name, &profile.Nickname, &profile.JobTitle,
|
||||
&departmentIDs, &profile.DepartmentName, &profile.MainDepartmentName, &profile.Region,
|
||||
&profile.EmploymentStatus, &profile.Source, &profile.SyncedAt,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return directory.Profile{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return directory.Profile{}, false, fmt.Errorf("lookup directory profile: %w", err)
|
||||
}
|
||||
if err := json.Unmarshal(departmentIDs, &profile.DepartmentIDs); err != nil {
|
||||
return directory.Profile{}, false, errors.New("decode directory department ids")
|
||||
}
|
||||
return profile, true, nil
|
||||
}
|
||||
|
||||
func (s *Store) UpsertDirectoryProfiles(ctx context.Context, tenantKey string, profiles []directory.Profile) error {
|
||||
tenantKey = strings.TrimSpace(tenantKey)
|
||||
if tenantKey == "" || len(profiles) == 0 {
|
||||
return errors.New("tenant and non-empty directory profiles are required")
|
||||
}
|
||||
for _, profile := range profiles {
|
||||
if strings.TrimSpace(profile.StaffID) == "" || strings.TrimSpace(profile.Name) == "" {
|
||||
return errors.New("directory profile requires staff id and name")
|
||||
}
|
||||
}
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
for _, profile := range profiles {
|
||||
departmentIDs, marshalErr := json.Marshal(profile.DepartmentIDs)
|
||||
if marshalErr != nil {
|
||||
return errors.New("encode directory department ids")
|
||||
}
|
||||
syncedAt := profile.SyncedAt
|
||||
if syncedAt.IsZero() {
|
||||
syncedAt = time.Now().UTC()
|
||||
}
|
||||
_, err = tx.Exec(ctx, `INSERT INTO directory_profiles
|
||||
(tenant_key,staff_id,union_id,name,nickname,job_title,department_ids,department_name,main_department_name,region,employment_status,source,synced_at)
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)
|
||||
ON CONFLICT (tenant_key,staff_id) DO UPDATE SET
|
||||
union_id=EXCLUDED.union_id,name=EXCLUDED.name,nickname=EXCLUDED.nickname,job_title=EXCLUDED.job_title,
|
||||
department_ids=EXCLUDED.department_ids,department_name=EXCLUDED.department_name,
|
||||
main_department_name=EXCLUDED.main_department_name,region=EXCLUDED.region,
|
||||
employment_status=EXCLUDED.employment_status,source=EXCLUDED.source,synced_at=EXCLUDED.synced_at,updated_at=NOW()`,
|
||||
tenantKey, profile.StaffID, profile.UnionID, profile.Name, profile.Nickname, profile.JobTitle,
|
||||
departmentIDs, profile.DepartmentName, profile.MainDepartmentName, profile.Region,
|
||||
profile.EmploymentStatus, profile.Source, syncedAt)
|
||||
if err != nil {
|
||||
return fmt.Errorf("upsert directory profile: %w", err)
|
||||
}
|
||||
}
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDirectoryStoreSQLContract(t *testing.T) {
|
||||
raw, err := os.ReadFile("directory.go")
|
||||
if err != nil {
|
||||
t.Fatalf("read directory.go: %v", err)
|
||||
}
|
||||
src := strings.ToUpper(string(raw))
|
||||
for _, required := range []string{
|
||||
"SELECT STAFF_ID,UNION_ID,NAME,NICKNAME,JOB_TITLE,DEPARTMENT_IDS,DEPARTMENT_NAME,MAIN_DEPARTMENT_NAME,REGION,EMPLOYMENT_STATUS,SOURCE,SYNCED_AT",
|
||||
"FROM DIRECTORY_PROFILES",
|
||||
"INSERT INTO DIRECTORY_PROFILES",
|
||||
"ON CONFLICT (TENANT_KEY,STAFF_ID) DO UPDATE",
|
||||
} {
|
||||
if !strings.Contains(src, required) {
|
||||
t.Errorf("directory.go missing SQL contract %q", required)
|
||||
}
|
||||
}
|
||||
for _, forbidden := range []string{"MOBILE", "EMAIL", "CLIENT_SECRET", "ACCESS_TOKEN", "RAW_PAYLOAD"} {
|
||||
if strings.Contains(src, forbidden) {
|
||||
t.Errorf("directory store contains forbidden sensitive field %q", forbidden)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBeginTurnStoresDirectorySnapshotsAndGroupTitle(t *testing.T) {
|
||||
raw, err := os.ReadFile("store.go")
|
||||
if err != nil {
|
||||
t.Fatalf("read store.go: %v", err)
|
||||
}
|
||||
src := strings.ToUpper(string(raw))
|
||||
for _, required := range []string{
|
||||
"DEPARTMENT_SNAPSHOT,REGION_SNAPSHOT",
|
||||
"TURN.DEPARTMENTSNAPSHOT",
|
||||
"TURN.REGIONSNAPSHOT",
|
||||
"TURN.CONVERSATIONTITLE",
|
||||
} {
|
||||
if !strings.Contains(src, required) {
|
||||
t.Errorf("store.go missing %q", required)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestStoreSessionTitleSQLContract(t *testing.T) {
|
||||
raw, err := os.ReadFile("store.go")
|
||||
if err != nil {
|
||||
t.Fatalf("read store.go: %v", err)
|
||||
}
|
||||
src := strings.ToUpper(string(raw))
|
||||
for _, required := range []string{
|
||||
"INSERT INTO SESSION_MAPPINGS",
|
||||
"DISPLAY_TITLE",
|
||||
"SELECT WEKNORA_SESSION_ID,DISPLAY_TITLE FROM SESSION_MAPPINGS",
|
||||
"UPDATE SESSION_MAPPINGS SET DISPLAY_TITLE=",
|
||||
} {
|
||||
if !strings.Contains(src, required) {
|
||||
t.Errorf("store.go missing session-title SQL contract %q", required)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(string(raw), "func (s *Store) SyncSessionTitle") {
|
||||
t.Error("Store must implement SyncSessionTitle")
|
||||
}
|
||||
}
|
||||
@@ -67,6 +67,8 @@ func (s *Store) BeginTurn(ctx context.Context, turn core.Turn) (core.Turn, bool,
|
||||
conversationTitle := ""
|
||||
if turn.ConversationType == core.ConversationDirect {
|
||||
conversationTitle = strings.TrimSpace(turn.SenderName)
|
||||
} else if turn.ConversationType == core.ConversationGroup {
|
||||
conversationTitle = strings.TrimSpace(turn.ConversationTitle)
|
||||
}
|
||||
if err = tx.QueryRow(ctx, `INSERT INTO channel_conversations
|
||||
(id,tenant_key,channel,external_conversation_id,conversation_type,title,status)
|
||||
@@ -81,13 +83,13 @@ func (s *Store) BeginTurn(ctx context.Context, turn core.Turn) (core.Turn, bool,
|
||||
|
||||
if err = tx.QueryRow(ctx, `INSERT INTO messages
|
||||
(id,tenant_key,channel,conversation_id,actor_id,external_message_id,correlation_id,
|
||||
direction,role,message_type,text_content,media_json,status,actor_name_snapshot,safe_metadata_json)
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7,'inbound','user',$8,$9,$10,'received',$11,'{}'::JSONB)
|
||||
direction,role,message_type,text_content,media_json,status,actor_name_snapshot,department_snapshot,region_snapshot,safe_metadata_json)
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7,'inbound','user',$8,$9,$10,'received',$11,$12,$13,'{}'::JSONB)
|
||||
ON CONFLICT (tenant_key,channel,external_message_id) WHERE external_message_id!=''
|
||||
DO UPDATE SET updated_at=messages.updated_at
|
||||
RETURNING id`, turn.RequestMessageID, turn.TenantKey, turn.Channel, turn.ConversationID,
|
||||
turn.ActorID, turn.ExternalMessageID, turn.ID, turn.MessageType, turn.Question, mediaJSON,
|
||||
turn.SenderName).Scan(&turn.RequestMessageID); err != nil {
|
||||
turn.SenderName, turn.DepartmentSnapshot, turn.RegionSnapshot).Scan(&turn.RequestMessageID); err != nil {
|
||||
return core.Turn{}, false, err
|
||||
}
|
||||
|
||||
@@ -137,14 +139,43 @@ func (s *Store) ResolveSession(ctx context.Context, mapping core.SessionMapping,
|
||||
return "", err
|
||||
}
|
||||
_, err = tx.Exec(ctx, `INSERT INTO session_mappings
|
||||
(session_key,tenant_key,channel,agent_id,conversation_type,external_subject_id,weknora_session_id)
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7)`, mapping.SessionKey, mapping.TenantKey, mapping.Channel, mapping.AgentID, string(mapping.ConversationType), mapping.ExternalSubjectID, sessionID)
|
||||
(session_key,tenant_key,channel,agent_id,conversation_type,external_subject_id,weknora_session_id,display_title)
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7,$8)`, mapping.SessionKey, mapping.TenantKey, mapping.Channel, mapping.AgentID, string(mapping.ConversationType), mapping.ExternalSubjectID, sessionID, mapping.DisplayTitle)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return sessionID, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (s *Store) SyncSessionTitle(ctx context.Context, mapping core.SessionMapping, title string, update core.SessionTitleUpdate) error {
|
||||
title = strings.TrimSpace(title)
|
||||
if strings.TrimSpace(mapping.SessionKey) == "" || title == "" || update == nil {
|
||||
return errors.New("session key, title and update callback are required")
|
||||
}
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, mapping.SessionKey); err != nil {
|
||||
return err
|
||||
}
|
||||
var sessionID, currentTitle string
|
||||
if err = tx.QueryRow(ctx, `SELECT weknora_session_id,display_title FROM session_mappings WHERE session_key=$1`, mapping.SessionKey).Scan(&sessionID, ¤tTitle); err != nil {
|
||||
return err
|
||||
}
|
||||
if currentTitle == title {
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
if err = update(ctx, sessionID, title); err != nil {
|
||||
return fmt.Errorf("update session title: %w", err)
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `UPDATE session_mappings SET display_title=$2,updated_at=NOW() WHERE session_key=$1`, mapping.SessionKey, title); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (s *Store) FinishTurn(ctx context.Context, turn core.Turn) error {
|
||||
references, err := json.Marshal(turn.References)
|
||||
if err != nil {
|
||||
|
||||
Reference in New Issue
Block a user