contact_form.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. package crontask
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/google/uuid"
  7. "github.com/zeromicro/go-zero/core/logx"
  8. "net/http"
  9. "time"
  10. "wechat-api/ent/contact"
  11. "wechat-api/ent/contactfield"
  12. "wechat-api/ent/contactfieldtemplate"
  13. "wechat-api/ent/custom_types"
  14. "wechat-api/ent/predicate"
  15. "wechat-api/ent/usagedetail"
  16. )
  17. type ResponseItem struct {
  18. DataIndex string `json:"dataIndex"`
  19. Value []string `json:"value"`
  20. }
  21. type FieldPropsOptions struct {
  22. Label string `json:"label"`
  23. Value string `json:"value"`
  24. }
  25. type FieldProps struct {
  26. Options []FieldPropsOptions `json:"options"`
  27. }
  28. type FormData struct {
  29. Title string `json:"title"`
  30. DataIndex string `json:"dataIndex"`
  31. ValueType string `json:"valueType"`
  32. FieldProps FieldProps `json:"fieldProps"`
  33. }
  34. func (l *CronTask) analyze() {
  35. usageDetails := make(map[string]map[string]string)
  36. contactFieldTemplates := make(map[string][]custom_types.ContactFieldTemplate)
  37. var predicates []predicate.UsageDetail
  38. predicates = append(predicates, usagedetail.TypeIn(1, 3))
  39. predicates = append(predicates, usagedetail.AppIn(1, 3, 4, 5))
  40. //yesterdayStart := time.Now().AddDate(0, 0, -1).Truncate(24 * time.Hour)
  41. //yesterdayEnd := yesterdayStart.Add(24 * time.Hour)
  42. //predicates = append(predicates, usagedetail.CreatedAtGTE(yesterdayStart))
  43. //predicates = append(predicates, usagedetail.CreatedAtLT(yesterdayEnd))
  44. todayStart := time.Now().AddDate(0, 0, 0).Truncate(24 * time.Hour)
  45. todayEnd := todayStart.Add(24 * time.Hour)
  46. predicates = append(predicates, usagedetail.CreatedAtGTE(todayStart))
  47. predicates = append(predicates, usagedetail.CreatedAtLT(todayEnd))
  48. data, err := l.svcCtx.DB.UsageDetail.Query().Where(predicates...).All(l.ctx)
  49. logx.Info("usageDetails: ", data)
  50. if err != nil {
  51. return
  52. }
  53. for _, u := range data {
  54. if _, ok := contactFieldTemplates[u.BotID]; !ok {
  55. c, _ := l.svcCtx.DB.ContactFieldTemplate.Query().Where(contactfieldtemplate.OrganizationID(u.OrganizationID)).First(l.ctx)
  56. if c != nil {
  57. contactFieldTemplates[u.BotID] = c.Template
  58. } else {
  59. contactFieldTemplates[u.BotID] = nil
  60. }
  61. }
  62. if contactFieldTemplates[u.BotID] == nil {
  63. continue
  64. }
  65. if _, ok := usageDetails[u.BotID]; !ok {
  66. usageDetails[u.BotID] = make(map[string]string)
  67. }
  68. usageDetails[u.BotID][u.ReceiverID] += fmt.Sprintf("用户:%s\n机器人:%s\n", u.Request, u.Response)
  69. }
  70. logx.Info("contactFieldTemplates: ", contactFieldTemplates)
  71. logx.Info("usageDetails: ", usageDetails)
  72. for botID, template := range contactFieldTemplates {
  73. if template == nil {
  74. continue
  75. }
  76. for receiverID, messages := range usageDetails[botID] {
  77. result, _ := openaiRequest(messages, template)
  78. logx.Info("result: ", result)
  79. if result == nil {
  80. continue
  81. }
  82. _ = l.UpdateContactFields(botID, receiverID, result)
  83. }
  84. }
  85. }
  86. func openaiRequest(messages string, template []custom_types.ContactFieldTemplate) ([]ResponseItem, error) {
  87. url := "https://toolsapi-debug.gkscrm.com/call_center/form/extract"
  88. bodyData := map[string]interface{}{
  89. "form_data": ConvertFormData(template),
  90. "chat_history": messages,
  91. "external_id": uuid.New().String(),
  92. }
  93. logx.Infof("bodyData: %+v", bodyData)
  94. bodyBytes, err := json.Marshal(bodyData)
  95. if err != nil {
  96. return nil, err
  97. }
  98. req, err := http.NewRequest("POST", url, bytes.NewBuffer(bodyBytes))
  99. if err != nil {
  100. return nil, err
  101. }
  102. req.Header.Set("Content-Type", "application/json")
  103. req.Header.Set("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIn0.ZS9jnsLPCnmc8L_lu4yaQFp34vwWF1mHlHSBYrY5JVs")
  104. client := &http.Client{}
  105. resp, err := client.Do(req)
  106. if err != nil || resp == nil || resp.Body == nil {
  107. logx.Error("read body error: ", err)
  108. return nil, err
  109. }
  110. logx.Info("err: ", err)
  111. if err != nil {
  112. return nil, err
  113. }
  114. defer resp.Body.Close()
  115. if resp.StatusCode != http.StatusOK {
  116. return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
  117. }
  118. //var result []ResponseItem
  119. var fullResp struct {
  120. Data []ResponseItem `json:"data"`
  121. }
  122. err = json.NewDecoder(resp.Body).Decode(&fullResp)
  123. if err != nil {
  124. return nil, err
  125. }
  126. return fullResp.Data, nil
  127. }
  128. func (l *CronTask) UpdateContactFields(botID string, receiverID string, fields []ResponseItem) error {
  129. logx.Infof("botID: ", botID)
  130. logx.Infof("receiverID: ", receiverID)
  131. logx.Infof("fields: ", fields)
  132. c, _ := l.svcCtx.DB.Contact.Query().Where(contact.WxWxidEQ(botID), contact.WxidEQ(receiverID)).First(l.ctx)
  133. logx.Infof("c: ", c)
  134. if c == nil {
  135. return fmt.Errorf("Contact not find")
  136. }
  137. for _, field := range fields {
  138. f, _ := l.svcCtx.DB.ContactField.Query().Where(contactfield.ContactID(c.ID), contactfield.FormID(field.DataIndex)).First(l.ctx)
  139. if f == nil {
  140. if field.Value != nil && len(field.Value) > 0 {
  141. _, err := l.svcCtx.DB.ContactField.Create().
  142. SetContactID(c.ID).
  143. SetFormID(field.DataIndex).
  144. SetValue(field.Value).
  145. Save(l.ctx)
  146. if err != nil {
  147. return err
  148. }
  149. }
  150. } else {
  151. if field.Value != nil {
  152. if len(field.Value) == 0 {
  153. field.Value = []string{""}
  154. }
  155. _, err := l.svcCtx.DB.ContactField.UpdateOneID(f.ID).
  156. SetValue(field.Value).
  157. Save(l.ctx)
  158. if err != nil {
  159. return err
  160. }
  161. }
  162. }
  163. }
  164. return nil
  165. }
  166. func ConvertFormData(input []custom_types.ContactFieldTemplate) []FormData {
  167. result := make([]FormData, len(input))
  168. for i, item := range input {
  169. options := make([]FieldPropsOptions, len(item.Options))
  170. for j, opt := range item.Options {
  171. options[j] = FieldPropsOptions{
  172. Label: *opt.Label,
  173. Value: *opt.Value,
  174. }
  175. }
  176. result[i] = FormData{
  177. Title: *item.Label,
  178. DataIndex: *item.Id,
  179. ValueType: *item.Type,
  180. FieldProps: FieldProps{
  181. Options: options,
  182. },
  183. }
  184. }
  185. return result
  186. }