conversation_service.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. package service
  2. import (
  3. "errors"
  4. "strings"
  5. "time"
  6. "github.com/2930134478/AI-CS/backend/models"
  7. "github.com/2930134478/AI-CS/backend/repository"
  8. "gorm.io/gorm"
  9. )
  10. // ConversationService 负责会话领域的业务编排。
  11. type ConversationService struct {
  12. conversations *repository.ConversationRepository
  13. messages *repository.MessageRepository
  14. aiConfigRepo *repository.AIConfigRepository // 用于验证 AI 配置
  15. userRepo *repository.UserRepository // 用于查询用户设置
  16. }
  17. // NewConversationService 创建 ConversationService 实例。
  18. func NewConversationService(
  19. conversations *repository.ConversationRepository,
  20. messages *repository.MessageRepository,
  21. aiConfigRepo *repository.AIConfigRepository,
  22. userRepo *repository.UserRepository,
  23. ) *ConversationService {
  24. return &ConversationService{
  25. conversations: conversations,
  26. messages: messages,
  27. aiConfigRepo: aiConfigRepo,
  28. userRepo: userRepo,
  29. }
  30. }
  31. // InitConversation 为访客创建或恢复会话。
  32. func (s *ConversationService) InitConversation(input InitConversationInput) (*InitConversationResult, error) {
  33. var (
  34. conv *models.Conversation
  35. err error
  36. )
  37. conv, err = s.conversations.FindOpenByVisitorID(input.VisitorID)
  38. isNewConversation := false
  39. if err != nil {
  40. if errors.Is(err, gorm.ErrRecordNotFound) {
  41. now := time.Now()
  42. chatMode := input.ChatMode
  43. if chatMode == "" {
  44. chatMode = "human" // 默认人工客服
  45. }
  46. // 如果是 AI 模式,验证 AI 配置
  47. var aiConfigID *uint
  48. if chatMode == "ai" {
  49. if input.AIConfigID == nil || *input.AIConfigID == 0 {
  50. return nil, errors.New("AI 模式需要选择模型配置")
  51. }
  52. // 验证配置是否存在且开放
  53. config, err := s.aiConfigRepo.GetByID(*input.AIConfigID)
  54. if err != nil {
  55. return nil, errors.New("模型配置不存在")
  56. }
  57. if !config.IsPublic {
  58. return nil, errors.New("该模型未开放给访客使用")
  59. }
  60. if !config.IsActive {
  61. return nil, errors.New("该模型配置已禁用")
  62. }
  63. aiConfigID = input.AIConfigID
  64. }
  65. conv = &models.Conversation{
  66. VisitorID: input.VisitorID,
  67. Status: "open",
  68. Website: input.Website,
  69. Referrer: input.Referrer,
  70. Browser: input.Browser,
  71. OS: input.OS,
  72. Language: input.Language,
  73. IPAddress: input.IPAddress,
  74. LastSeenAt: &now,
  75. ChatMode: chatMode,
  76. AIConfigID: aiConfigID,
  77. }
  78. if err := s.conversations.Create(conv); err != nil {
  79. return nil, err
  80. }
  81. isNewConversation = true
  82. } else {
  83. return nil, err
  84. }
  85. } else {
  86. // 恢复已存在的对话
  87. now := time.Now()
  88. updates := map[string]interface{}{
  89. "last_seen_at": &now,
  90. }
  91. // 更新访客信息(如果之前没有)
  92. if input.Website != "" && conv.Website == "" {
  93. updates["website"] = input.Website
  94. }
  95. if input.Referrer != "" && conv.Referrer == "" {
  96. updates["referrer"] = input.Referrer
  97. }
  98. if input.Browser != "" && conv.Browser == "" {
  99. updates["browser"] = input.Browser
  100. }
  101. if input.OS != "" && conv.OS == "" {
  102. updates["os"] = input.OS
  103. }
  104. if input.Language != "" && conv.Language == "" {
  105. updates["language"] = input.Language
  106. }
  107. if input.IPAddress != "" && conv.IPAddress == "" {
  108. updates["ip_address"] = input.IPAddress
  109. }
  110. // 重要:如果用户选择了新的 ChatMode,更新对话模式
  111. // 这样访客可以在人工客服和 AI 客服之间切换
  112. if input.ChatMode != "" && input.ChatMode != conv.ChatMode {
  113. chatMode := input.ChatMode
  114. updates["chat_mode"] = chatMode
  115. // 如果是 AI 模式,验证并更新 AI 配置
  116. if chatMode == "ai" {
  117. if input.AIConfigID == nil || *input.AIConfigID == 0 {
  118. return nil, errors.New("AI 模式需要选择模型配置")
  119. }
  120. // 验证配置是否存在且开放
  121. config, err := s.aiConfigRepo.GetByID(*input.AIConfigID)
  122. if err != nil {
  123. return nil, errors.New("模型配置不存在")
  124. }
  125. if !config.IsPublic {
  126. return nil, errors.New("该模型未开放给访客使用")
  127. }
  128. if !config.IsActive {
  129. return nil, errors.New("该模型配置已禁用")
  130. }
  131. updates["ai_config_id"] = input.AIConfigID
  132. } else {
  133. // 切换到人工客服模式,清除 AI 配置
  134. updates["ai_config_id"] = nil
  135. }
  136. }
  137. if err := s.conversations.UpdateFields(conv.ID, updates); err != nil {
  138. return nil, err
  139. }
  140. // 重新获取更新后的对话信息
  141. conv, err = s.conversations.GetByID(conv.ID)
  142. if err != nil {
  143. return nil, err
  144. }
  145. }
  146. if isNewConversation {
  147. now := time.Now()
  148. chatMode := input.ChatMode
  149. if chatMode == "" {
  150. chatMode = "human" // 默认人工模式
  151. }
  152. message := &models.Message{
  153. ConversationID: conv.ID,
  154. SenderID: 0,
  155. SenderIsAgent: false,
  156. Content: "Visitor opened the page",
  157. MessageType: "system_message",
  158. ChatMode: chatMode, // 记录系统消息发送时的对话模式
  159. IsRead: true,
  160. ReadAt: &now,
  161. }
  162. if input.Website != "" {
  163. message.Content += " [" + input.Website + "]"
  164. }
  165. if err := s.messages.Create(message); err != nil {
  166. return nil, err
  167. }
  168. if input.Referrer != "" {
  169. readTime := time.Now()
  170. chatMode := input.ChatMode
  171. if chatMode == "" {
  172. chatMode = "human" // 默认人工模式
  173. }
  174. referrerMsg := &models.Message{
  175. ConversationID: conv.ID,
  176. SenderID: 0,
  177. SenderIsAgent: false,
  178. Content: "Visitor came from [" + input.Referrer + "]",
  179. MessageType: "system_message",
  180. ChatMode: chatMode, // 记录系统消息发送时的对话模式
  181. IsRead: true,
  182. ReadAt: &readTime,
  183. }
  184. if err := s.messages.Create(referrerMsg); err != nil {
  185. return nil, err
  186. }
  187. }
  188. }
  189. return &InitConversationResult{
  190. ConversationID: conv.ID,
  191. Status: conv.Status,
  192. }, nil
  193. }
  194. // UpdateConversationContact 更新访客的联系信息(邮箱、电话、备注)。
  195. func (s *ConversationService) UpdateConversationContact(input UpdateConversationContactInput) (*ConversationDetail, error) {
  196. if _, err := s.conversations.GetByID(input.ConversationID); err != nil {
  197. if errors.Is(err, gorm.ErrRecordNotFound) {
  198. return nil, ErrConversationNotFound
  199. }
  200. return nil, err
  201. }
  202. updates := map[string]interface{}{}
  203. if input.Email != nil {
  204. updates["email"] = strings.TrimSpace(*input.Email)
  205. }
  206. if input.Phone != nil {
  207. updates["phone"] = strings.TrimSpace(*input.Phone)
  208. }
  209. if input.Notes != nil {
  210. updates["notes"] = strings.TrimSpace(*input.Notes)
  211. }
  212. if err := s.conversations.UpdateFields(input.ConversationID, updates); err != nil {
  213. return nil, err
  214. }
  215. // UpdateConversationContact 不传递 userID,因为更新联系信息时不需要检查参与状态
  216. return s.GetConversationDetail(input.ConversationID, 0)
  217. }
  218. func (s *ConversationService) buildSummary(conv models.Conversation, userID uint) (ConversationSummary, error) {
  219. var lastSeen *time.Time
  220. if conv.LastSeenAt != nil {
  221. lastSeen = conv.LastSeenAt
  222. }
  223. // 检查当前用户是否参与过该会话(是否发送过消息)
  224. hasParticipated := false
  225. if userID > 0 {
  226. if participated, err := s.messages.HasAgentParticipated(conv.ID, userID); err == nil {
  227. hasParticipated = participated
  228. }
  229. // 错误时静默处理,不影响流程
  230. }
  231. summary := ConversationSummary{
  232. ID: conv.ID,
  233. VisitorID: conv.VisitorID,
  234. AgentID: conv.AgentID,
  235. Status: conv.Status,
  236. CreatedAt: conv.CreatedAt,
  237. UpdatedAt: conv.UpdatedAt,
  238. LastSeenAt: lastSeen, // 添加 last_seen_at 字段
  239. HasParticipated: hasParticipated, // 当前用户是否参与过该会话
  240. }
  241. if message, err := s.messages.LatestByConversationID(conv.ID); err == nil && message != nil {
  242. var readAt *time.Time
  243. if message.ReadAt != nil {
  244. readAt = message.ReadAt
  245. }
  246. summary.LastMessage = &LastMessageSummary{
  247. ID: message.ID,
  248. Content: message.Content,
  249. SenderIsAgent: message.SenderIsAgent,
  250. MessageType: message.MessageType,
  251. IsRead: message.IsRead,
  252. ReadAt: readAt,
  253. CreatedAt: message.CreatedAt,
  254. }
  255. }
  256. if count, err := s.messages.CountUnreadBySender(conv.ID, false); err == nil {
  257. summary.UnreadCount = count
  258. }
  259. return summary, nil
  260. }
  261. // ListConversations 返回当前活跃会话的摘要信息。
  262. // userID: 当前登录的客服ID(可选,如果为0则使用默认过滤规则)
  263. // 过滤规则:
  264. // 1. 默认不显示 ChatMode == "ai" 的对话
  265. // 2. 如果 userID > 0 且该用户的 ReceiveAIConversations == false,则不显示 AI 对话
  266. // 3. 只显示 ChatMode == "human" 且存在访客消息的对话(访客切换到人工并发送消息后)
  267. func (s *ConversationService) ListConversations(userID uint) ([]ConversationSummary, error) {
  268. conversations, err := s.conversations.ListActive()
  269. if err != nil {
  270. return nil, err
  271. }
  272. result := make([]ConversationSummary, 0, len(conversations))
  273. for _, conv := range conversations {
  274. // 过滤规则 1: 默认不显示 AI 对话
  275. // 只有在会话页面手动开启"显示 AI 对话"时才显示
  276. if conv.ChatMode == "ai" {
  277. continue
  278. }
  279. // 过滤规则 2: 如果是人工对话,检查是否有访客发送的消息
  280. // 只有当访客切换到人工并发送消息后,才显示在列表中
  281. if conv.ChatMode == "human" {
  282. hasVisitorMessage, err := s.messages.HasVisitorMessageInHumanMode(conv.ID)
  283. if err != nil {
  284. // 如果查询失败,为了安全起见,不显示该对话
  285. continue
  286. }
  287. if !hasVisitorMessage {
  288. // 没有访客消息,不显示(访客只是切换了模式,但还没发送消息)
  289. continue
  290. }
  291. }
  292. // 通过过滤,添加到结果列表
  293. summary, err := s.buildSummary(conv, userID)
  294. if err != nil {
  295. continue // 如果构建摘要失败,跳过该对话
  296. }
  297. result = append(result, summary)
  298. }
  299. return result, nil
  300. }
  301. // GetConversationDetail 获取指定会话的详细信息。
  302. func (s *ConversationService) GetConversationDetail(id uint, userID uint) (*ConversationDetail, error) {
  303. conv, err := s.conversations.GetByID(id)
  304. if err != nil {
  305. return nil, err
  306. }
  307. summary, err := s.buildSummary(*conv, userID)
  308. if err != nil {
  309. return nil, err
  310. }
  311. var lastSeen *time.Time
  312. if conv.LastSeenAt != nil {
  313. lastSeen = conv.LastSeenAt
  314. }
  315. return &ConversationDetail{
  316. ConversationSummary: summary,
  317. Website: conv.Website,
  318. Referrer: conv.Referrer,
  319. Browser: conv.Browser,
  320. OS: conv.OS,
  321. Language: conv.Language,
  322. IPAddress: conv.IPAddress,
  323. Location: conv.Location,
  324. Email: conv.Email,
  325. Phone: conv.Phone,
  326. Notes: conv.Notes,
  327. LastSeen: lastSeen,
  328. }, nil
  329. }
  330. // SearchConversations 根据关键字检索会话摘要。
  331. // userID: 当前登录的客服ID(可选,用于检查参与状态)
  332. func (s *ConversationService) SearchConversations(query string, userID uint) ([]ConversationSummary, error) {
  333. pattern := "%" + query + "%"
  334. idSet := map[uint]struct{}{}
  335. if ids, err := s.messages.FindConversationIDsByContent(pattern); err == nil {
  336. for _, id := range ids {
  337. idSet[id] = struct{}{}
  338. }
  339. } else {
  340. return nil, err
  341. }
  342. if convs, err := s.conversations.SearchByIDOrVisitorLike(pattern); err == nil {
  343. for _, conv := range convs {
  344. idSet[conv.ID] = struct{}{}
  345. }
  346. } else {
  347. return nil, err
  348. }
  349. if len(idSet) == 0 {
  350. return []ConversationSummary{}, nil
  351. }
  352. ids := make([]uint, 0, len(idSet))
  353. for id := range idSet {
  354. ids = append(ids, id)
  355. }
  356. conversations, err := s.conversations.ListByIDs(ids)
  357. if err != nil {
  358. return nil, err
  359. }
  360. result := make([]ConversationSummary, 0, len(conversations))
  361. for _, conv := range conversations {
  362. summary, err := s.buildSummary(conv, userID)
  363. if err != nil {
  364. return nil, err
  365. }
  366. result = append(result, summary)
  367. }
  368. return result, nil
  369. }
  370. // UpdateVisitorOnlineStatus 更新访客在线状态和最后活跃时间。
  371. // 当 isOnline 为 true 时,更新 last_seen_at 为当前时间,并确保状态为 "open"。
  372. // 当 isOnline 为 false 时,仅更新 last_seen_at 为当前时间,不改变状态。
  373. func (s *ConversationService) UpdateVisitorOnlineStatus(conversationID uint, isOnline bool) error {
  374. now := time.Now()
  375. updates := map[string]interface{}{
  376. "last_seen_at": &now,
  377. }
  378. // 如果标记为在线,确保状态为 "open"(但不要将已关闭的会话重新打开)
  379. if isOnline {
  380. conv, err := s.conversations.GetByID(conversationID)
  381. if err != nil {
  382. return err
  383. }
  384. // 只有当前状态不是 "closed" 时,才更新为 "open"
  385. if conv.Status != "closed" {
  386. updates["status"] = "open"
  387. }
  388. }
  389. return s.conversations.UpdateFields(conversationID, updates)
  390. }
  391. // UpdateLastSeenAt 更新访客的最后活跃时间。
  392. func (s *ConversationService) UpdateLastSeenAt(conversationID uint) error {
  393. now := time.Now()
  394. return s.conversations.UpdateFields(conversationID, map[string]interface{}{
  395. "last_seen_at": &now,
  396. })
  397. }