contact_form.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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("todayStart: ", todayStart)
  50. logx.Info("todayEnd: ", todayEnd)
  51. logx.Info("usageDetails: ", data)
  52. if err != nil {
  53. return
  54. }
  55. for _, u := range data {
  56. if _, ok := contactFieldTemplates[u.BotID]; !ok {
  57. c, _ := l.svcCtx.DB.ContactFieldTemplate.Query().Where(contactfieldtemplate.OrganizationID(u.OrganizationID)).First(l.ctx)
  58. if c != nil {
  59. contactFieldTemplates[u.BotID] = c.Template
  60. } else {
  61. contactFieldTemplates[u.BotID] = nil
  62. }
  63. }
  64. if contactFieldTemplates[u.BotID] == nil {
  65. continue
  66. }
  67. if _, ok := usageDetails[u.BotID]; !ok {
  68. usageDetails[u.BotID] = make(map[string]string)
  69. }
  70. usageDetails[u.BotID][u.ReceiverID] += fmt.Sprintf("用户:%s\n机器人:%s\n", u.Request, u.Response)
  71. }
  72. logx.Info("contactFieldTemplates: ", contactFieldTemplates)
  73. logx.Info("usageDetails: ", usageDetails)
  74. for botID, template := range contactFieldTemplates {
  75. if template == nil {
  76. continue
  77. }
  78. for receiverID, messages := range usageDetails[botID] {
  79. result, _ := openaiRequest(messages, template)
  80. logx.Info("result: ", result)
  81. if result == nil {
  82. continue
  83. }
  84. _ = l.UpdateContactFields(botID, receiverID, result)
  85. }
  86. }
  87. }
  88. func openaiRequest(messages string, template []custom_types.ContactFieldTemplate) ([]ResponseItem, error) {
  89. url := "https://toolsapi-debug.gkscrm.com/call_center/form/extract"
  90. bodyData := map[string]interface{}{
  91. "form_data": ConvertFormData(template),
  92. "chat_history": messages,
  93. "external_id": uuid.New().String(),
  94. }
  95. logx.Infof("bodyData: %+v", bodyData)
  96. bodyBytes, err := json.Marshal(bodyData)
  97. if err != nil {
  98. return nil, err
  99. }
  100. req, err := http.NewRequest("POST", url, bytes.NewBuffer(bodyBytes))
  101. if err != nil {
  102. return nil, err
  103. }
  104. req.Header.Set("Content-Type", "application/json")
  105. req.Header.Set("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIn0.ZS9jnsLPCnmc8L_lu4yaQFp34vwWF1mHlHSBYrY5JVs")
  106. client := &http.Client{}
  107. resp, err := client.Do(req)
  108. if err != nil || resp == nil || resp.Body == nil {
  109. logx.Error("read body error: ", err)
  110. return nil, err
  111. }
  112. logx.Info("err: ", err)
  113. if err != nil {
  114. return nil, err
  115. }
  116. defer resp.Body.Close()
  117. if resp.StatusCode != http.StatusOK {
  118. return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
  119. }
  120. //var result []ResponseItem
  121. var fullResp struct {
  122. Data []ResponseItem `json:"data"`
  123. }
  124. err = json.NewDecoder(resp.Body).Decode(&fullResp)
  125. if err != nil {
  126. return nil, err
  127. }
  128. return fullResp.Data, nil
  129. }
  130. func (l *CronTask) UpdateContactFields(botID string, receiverID string, fields []ResponseItem) error {
  131. logx.Infof("botID: ", botID)
  132. logx.Infof("receiverID: ", receiverID)
  133. logx.Infof("fields: ", fields)
  134. c, _ := l.svcCtx.DB.Contact.Query().Where(contact.WxWxidEQ(botID), contact.WxidEQ(receiverID)).First(l.ctx)
  135. logx.Infof("c: ", c)
  136. if c == nil {
  137. return fmt.Errorf("Contact not find")
  138. }
  139. for _, field := range fields {
  140. f, _ := l.svcCtx.DB.ContactField.Query().Where(contactfield.ContactID(c.ID), contactfield.FormID(field.DataIndex)).First(l.ctx)
  141. if f == nil {
  142. if field.Value != nil && len(field.Value) > 0 {
  143. _, err := l.svcCtx.DB.ContactField.Create().
  144. SetContactID(c.ID).
  145. SetFormID(field.DataIndex).
  146. SetValue(field.Value).
  147. Save(l.ctx)
  148. if err != nil {
  149. return err
  150. }
  151. }
  152. } else {
  153. if field.Value != nil {
  154. if len(field.Value) == 0 {
  155. field.Value = []string{""}
  156. }
  157. _, err := l.svcCtx.DB.ContactField.UpdateOneID(f.ID).
  158. SetValue(field.Value).
  159. Save(l.ctx)
  160. if err != nil {
  161. return err
  162. }
  163. }
  164. }
  165. }
  166. return nil
  167. }
  168. func ConvertFormData(input []custom_types.ContactFieldTemplate) []FormData {
  169. result := make([]FormData, len(input))
  170. for i, item := range input {
  171. options := make([]FieldPropsOptions, len(item.Options))
  172. for j, opt := range item.Options {
  173. options[j] = FieldPropsOptions{
  174. Label: *opt.Label,
  175. Value: *opt.Value,
  176. }
  177. }
  178. result[i] = FormData{
  179. Title: *item.Label,
  180. DataIndex: *item.Id,
  181. ValueType: *item.Type,
  182. FieldProps: FieldProps{
  183. Options: options,
  184. },
  185. }
  186. }
  187. return result
  188. }