conversation_controller.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. package controller
  2. import (
  3. "net/http"
  4. "strconv"
  5. "github.com/2930134478/AI-CS/backend/service"
  6. "github.com/2930134478/AI-CS/backend/utils"
  7. "github.com/gin-gonic/gin"
  8. )
  9. // ConversationController 负责处理会话相关的 HTTP 请求。
  10. type ConversationController struct {
  11. conversationService *service.ConversationService
  12. aiConfigService *service.AIConfigService // 用于获取开放的模型列表
  13. users *service.UserService
  14. }
  15. // NewConversationController 创建 ConversationController 实例。
  16. func NewConversationController(
  17. conversationService *service.ConversationService,
  18. aiConfigService *service.AIConfigService,
  19. users *service.UserService,
  20. ) *ConversationController {
  21. return &ConversationController{
  22. conversationService: conversationService,
  23. aiConfigService: aiConfigService,
  24. users: users,
  25. }
  26. }
  27. type initConversationRequest struct {
  28. VisitorID uint `json:"visitor_id"`
  29. Website string `json:"website"`
  30. Referrer string `json:"referrer"`
  31. Browser string `json:"browser"`
  32. OS string `json:"os"`
  33. Language string `json:"language"`
  34. ChatMode string `json:"chat_mode"` // 对话模式:human(人工客服)、ai(AI客服)
  35. AIConfigID *uint `json:"ai_config_id"` // AI 配置 ID(访客选择的模型配置,AI 模式时必需)
  36. }
  37. type updateContactRequest struct {
  38. Email *string `json:"email"`
  39. Phone *string `json:"phone"`
  40. Notes *string `json:"notes"`
  41. }
  42. // InitConversation 为访客初始化或恢复会话。
  43. func (cc *ConversationController) InitConversation(c *gin.Context) {
  44. var req initConversationRequest
  45. if err := c.ShouldBindJSON(&req); err != nil || req.VisitorID == 0 {
  46. c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数错误"})
  47. return
  48. }
  49. browser := req.Browser
  50. os := req.OS
  51. if browser == "" || os == "" {
  52. parsedBrowser, parsedOS := utils.ParseUserAgent(c.GetHeader("User-Agent"))
  53. if browser == "" {
  54. browser = parsedBrowser
  55. }
  56. if os == "" {
  57. os = parsedOS
  58. }
  59. }
  60. result, err := cc.conversationService.InitConversation(service.InitConversationInput{
  61. VisitorID: req.VisitorID,
  62. Website: req.Website,
  63. Referrer: req.Referrer,
  64. Browser: browser,
  65. OS: os,
  66. Language: req.Language,
  67. IPAddress: utils.GetClientIP(c),
  68. ChatMode: req.ChatMode,
  69. AIConfigID: req.AIConfigID,
  70. })
  71. if err != nil {
  72. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  73. return
  74. }
  75. c.JSON(http.StatusOK, gin.H{
  76. "conversation_id": result.ConversationID,
  77. "status": result.Status,
  78. })
  79. }
  80. // InitInternalConversation 为当前客服创建一条新的内部对话(知识库测试)。需要 query user_id。
  81. func (cc *ConversationController) InitInternalConversation(c *gin.Context) {
  82. if !requirePermission(c, cc.users, string(service.PermKBTest)) {
  83. return
  84. }
  85. userIDStr := c.Query("user_id")
  86. if userIDStr == "" {
  87. c.JSON(http.StatusBadRequest, gin.H{"error": "需要 user_id"})
  88. return
  89. }
  90. userID, err := strconv.ParseUint(userIDStr, 10, 32)
  91. if err != nil || userID == 0 {
  92. c.JSON(http.StatusBadRequest, gin.H{"error": "user_id 不合法"})
  93. return
  94. }
  95. result, err := cc.conversationService.InitInternalConversation(uint(userID))
  96. if err != nil {
  97. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  98. return
  99. }
  100. c.JSON(http.StatusOK, gin.H{
  101. "conversation_id": result.ConversationID,
  102. "status": result.Status,
  103. })
  104. }
  105. // GetPublicAIModels 获取所有开放的模型配置(供访客选择)。
  106. func (cc *ConversationController) GetPublicAIModels(c *gin.Context) {
  107. modelType := c.DefaultQuery("model_type", "text")
  108. models, err := cc.aiConfigService.GetPublicModels(modelType)
  109. if err != nil {
  110. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  111. return
  112. }
  113. c.JSON(http.StatusOK, gin.H{"models": models})
  114. }
  115. // UpdateContactInfo 用于更新访客的联系信息。
  116. func (cc *ConversationController) UpdateContactInfo(c *gin.Context) {
  117. id, err := parseUintParam(c, "id")
  118. if err != nil {
  119. c.JSON(http.StatusBadRequest, gin.H{"error": "会话ID不合法"})
  120. return
  121. }
  122. var req updateContactRequest
  123. if err := c.ShouldBindJSON(&req); err != nil {
  124. c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数错误"})
  125. return
  126. }
  127. if req.Email == nil && req.Phone == nil && req.Notes == nil {
  128. c.JSON(http.StatusBadRequest, gin.H{"error": "至少提供一个需要更新的字段"})
  129. return
  130. }
  131. result, err := cc.conversationService.UpdateConversationContact(service.UpdateConversationContactInput{
  132. ConversationID: uint(id),
  133. Email: req.Email,
  134. Phone: req.Phone,
  135. Notes: req.Notes,
  136. })
  137. if err != nil {
  138. if err == service.ErrConversationNotFound {
  139. c.JSON(http.StatusNotFound, gin.H{"error": "会话不存在"})
  140. } else {
  141. c.JSON(http.StatusInternalServerError, gin.H{"error": "更新失败"})
  142. }
  143. return
  144. }
  145. c.JSON(http.StatusOK, gin.H{
  146. "email": result.Email,
  147. "phone": result.Phone,
  148. "notes": result.Notes,
  149. })
  150. }
  151. // ListConversations 返回当前活跃会话的列表。type=internal 时返回该客服的内部对话(知识库测试)。
  152. func (cc *ConversationController) ListConversations(c *gin.Context) {
  153. var userID uint
  154. if userIDStr := c.Query("user_id"); userIDStr != "" {
  155. if parsed, err := strconv.ParseUint(userIDStr, 10, 32); err == nil {
  156. userID = uint(parsed)
  157. }
  158. }
  159. conversationType := c.DefaultQuery("type", "visitor")
  160. var conversations []service.ConversationSummary
  161. var err error
  162. if conversationType == "internal" {
  163. if !requirePermission(c, cc.users, string(service.PermKBTest)) {
  164. return
  165. }
  166. if userID == 0 {
  167. c.JSON(http.StatusBadRequest, gin.H{"error": "内部对话列表需要 user_id"})
  168. return
  169. }
  170. conversations, err = cc.conversationService.ListInternalConversations(userID)
  171. } else {
  172. conversations, err = cc.conversationService.ListConversations(userID)
  173. }
  174. if err != nil {
  175. c.JSON(http.StatusInternalServerError, gin.H{"error": "查询对话列表失败"})
  176. return
  177. }
  178. items := make([]gin.H, 0, len(conversations))
  179. for _, conv := range conversations {
  180. item := gin.H{
  181. "id": conv.ID,
  182. "conversation_type": conv.ConversationType,
  183. "visitor_id": conv.VisitorID,
  184. "agent_id": conv.AgentID,
  185. "status": conv.Status,
  186. "chat_mode": conv.ChatMode,
  187. "created_at": formatTimeValue(conv.CreatedAt),
  188. "updated_at": formatTimeValue(conv.UpdatedAt),
  189. "unread_count": conv.UnreadCount,
  190. "has_participated": conv.HasParticipated,
  191. }
  192. // 添加 last_seen_at 字段(用于判断在线状态)
  193. if lastSeen := formatTimePointer(conv.LastSeenAt); lastSeen != "" {
  194. item["last_seen_at"] = lastSeen
  195. }
  196. if conv.LastMessage != nil {
  197. item["last_message"] = gin.H{
  198. "id": conv.LastMessage.ID,
  199. "content": conv.LastMessage.Content,
  200. "sender_is_agent": conv.LastMessage.SenderIsAgent,
  201. "message_type": conv.LastMessage.MessageType,
  202. "is_read": conv.LastMessage.IsRead,
  203. "read_at": formatTimePointer(conv.LastMessage.ReadAt),
  204. "created_at": formatTimeValue(conv.LastMessage.CreatedAt),
  205. }
  206. }
  207. items = append(items, item)
  208. }
  209. c.JSON(http.StatusOK, items)
  210. }
  211. // GetConversationDetail 返回会话的详细信息。
  212. func (cc *ConversationController) GetConversationDetail(c *gin.Context) {
  213. id, err := parseUintParam(c, "id")
  214. if err != nil {
  215. c.JSON(http.StatusBadRequest, gin.H{"error": "会话ID不合法"})
  216. return
  217. }
  218. // 从查询参数获取 user_id(可选,用于检查参与状态)
  219. var userID uint
  220. if userIDStr := c.Query("user_id"); userIDStr != "" {
  221. // 使用 strconv 解析查询参数(不是路径参数)
  222. if parsed, err := strconv.ParseUint(userIDStr, 10, 32); err == nil {
  223. userID = uint(parsed)
  224. }
  225. }
  226. detail, err := cc.conversationService.GetConversationDetail(uint(id), userID)
  227. if err != nil {
  228. if err == service.ErrConversationNotFound {
  229. c.JSON(http.StatusNotFound, gin.H{"error": "会话不存在"})
  230. } else {
  231. c.JSON(http.StatusInternalServerError, gin.H{"error": "查询失败"})
  232. }
  233. return
  234. }
  235. response := gin.H{
  236. "id": detail.ID,
  237. "visitor_id": detail.VisitorID,
  238. "agent_id": detail.AgentID,
  239. "status": detail.Status,
  240. "website": detail.Website,
  241. "referrer": detail.Referrer,
  242. "browser": detail.Browser,
  243. "os": detail.OS,
  244. "language": detail.Language,
  245. "ip_address": detail.IPAddress,
  246. "location": detail.Location,
  247. "email": detail.Email,
  248. "phone": detail.Phone,
  249. "notes": detail.Notes,
  250. "created_at": formatTimeValue(detail.CreatedAt),
  251. "updated_at": formatTimeValue(detail.UpdatedAt),
  252. "unread_count": detail.UnreadCount,
  253. }
  254. if lastSeen := formatTimePointer(detail.LastSeen); lastSeen != "" {
  255. response["last_seen_at"] = lastSeen
  256. }
  257. if detail.LastMessage != nil {
  258. response["last_message"] = gin.H{
  259. "id": detail.LastMessage.ID,
  260. "content": detail.LastMessage.Content,
  261. "sender_is_agent": detail.LastMessage.SenderIsAgent,
  262. "message_type": detail.LastMessage.MessageType,
  263. "is_read": detail.LastMessage.IsRead,
  264. "read_at": formatTimePointer(detail.LastMessage.ReadAt),
  265. "created_at": formatTimeValue(detail.LastMessage.CreatedAt),
  266. }
  267. }
  268. c.JSON(http.StatusOK, response)
  269. }
  270. // SearchConversations 根据关键字进行会话的模糊搜索。
  271. func (cc *ConversationController) SearchConversations(c *gin.Context) {
  272. query := c.Query("q")
  273. if query == "" {
  274. c.JSON(http.StatusBadRequest, gin.H{"error": "搜索关键词不能为空"})
  275. return
  276. }
  277. // 从查询参数获取 user_id(可选,用于检查参与状态)
  278. var userID uint
  279. if userIDStr := c.Query("user_id"); userIDStr != "" {
  280. // 使用 strconv 解析查询参数(不是路径参数)
  281. if parsed, err := strconv.ParseUint(userIDStr, 10, 32); err == nil {
  282. userID = uint(parsed)
  283. }
  284. }
  285. conversations, err := cc.conversationService.SearchConversations(query, userID)
  286. if err != nil {
  287. c.JSON(http.StatusInternalServerError, gin.H{"error": "搜索失败"})
  288. return
  289. }
  290. items := make([]gin.H, 0, len(conversations))
  291. for _, conv := range conversations {
  292. item := gin.H{
  293. "id": conv.ID,
  294. "visitor_id": conv.VisitorID,
  295. "agent_id": conv.AgentID,
  296. "status": conv.Status,
  297. "created_at": formatTimeValue(conv.CreatedAt),
  298. "updated_at": formatTimeValue(conv.UpdatedAt),
  299. "unread_count": conv.UnreadCount,
  300. "has_participated": conv.HasParticipated, // 当前用户是否参与过该会话
  301. }
  302. // 添加 last_seen_at 字段(用于判断在线状态)
  303. if lastSeen := formatTimePointer(conv.LastSeenAt); lastSeen != "" {
  304. item["last_seen_at"] = lastSeen
  305. }
  306. if conv.LastMessage != nil {
  307. item["last_message"] = gin.H{
  308. "id": conv.LastMessage.ID,
  309. "content": conv.LastMessage.Content,
  310. "sender_is_agent": conv.LastMessage.SenderIsAgent,
  311. "message_type": conv.LastMessage.MessageType,
  312. "is_read": conv.LastMessage.IsRead,
  313. "read_at": formatTimePointer(conv.LastMessage.ReadAt),
  314. "created_at": formatTimeValue(conv.LastMessage.CreatedAt),
  315. }
  316. }
  317. items = append(items, item)
  318. }
  319. c.JSON(http.StatusOK, items)
  320. }