contact_form.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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. "strconv"
  10. "time"
  11. "wechat-api/ent/contact"
  12. "wechat-api/ent/contactfield"
  13. "wechat-api/ent/contactfieldtemplate"
  14. "wechat-api/ent/custom_types"
  15. "wechat-api/ent/predicate"
  16. "wechat-api/ent/usagedetail"
  17. )
  18. type ResponseItem struct {
  19. DataIndex string `json:"dataIndex"`
  20. Value []string `json:"value"`
  21. }
  22. type FieldPropsOptions struct {
  23. Label string `json:"label"`
  24. Value string `json:"value"`
  25. }
  26. type FieldProps struct {
  27. Options []FieldPropsOptions `json:"options"`
  28. }
  29. type FormData struct {
  30. Title string `json:"title"`
  31. DataIndex string `json:"dataIndex"`
  32. ValueType string `json:"valueType"`
  33. FieldProps FieldProps `json:"fieldProps"`
  34. }
  35. func (l *CronTask) analyze() {
  36. usageDetails := make(map[string]map[string]string)
  37. contactFieldTemplates := make(map[string][]custom_types.ContactFieldTemplate)
  38. template_type_text := "text"
  39. template_type_radio := "radio"
  40. template_type_date := "date"
  41. template_sex_id := "sex"
  42. template_sex_label := "性别"
  43. template_sex_options_man_label := "男"
  44. template_sex_options_man_value := "男"
  45. template_sex_options_woman_label := "女"
  46. template_sex_options_woman_value := "男"
  47. template_phone_id := "phone"
  48. template_phone_label := "手机号"
  49. template_name_id := "name"
  50. template_name_label := "姓名"
  51. template_age_id := "age"
  52. template_age_label := "年龄(以字符串形式返回阿拉伯数字)"
  53. template_area_id := "area"
  54. template_area_label := "地区"
  55. template_birthday_id := "birthday"
  56. template_birthday_label := "出生日期"
  57. template_birtharea_id := "birtharea"
  58. template_birtharea_label := "出生地"
  59. template_idcard_no_id := "idcard_no"
  60. template_idcard_no_label := "身份证号"
  61. template_title_id := "title"
  62. template_title_label := "称呼"
  63. contactBasicFieldTemplates := []custom_types.ContactFieldTemplate{
  64. {
  65. Label: &template_sex_label,
  66. Id: &template_sex_id,
  67. Type: &template_type_radio,
  68. Options: []custom_types.ContactFieldTemplateOptions{
  69. {
  70. Label: &template_sex_options_man_label,
  71. Value: &template_sex_options_man_value,
  72. }, {
  73. Label: &template_sex_options_woman_label,
  74. Value: &template_sex_options_woman_value,
  75. },
  76. },
  77. }, {
  78. Label: &template_phone_label,
  79. Id: &template_phone_id,
  80. Type: &template_type_text,
  81. }, {
  82. Label: &template_name_label,
  83. Id: &template_name_id,
  84. Type: &template_type_text,
  85. }, {
  86. Label: &template_age_label,
  87. Id: &template_age_id,
  88. Type: &template_type_text,
  89. }, {
  90. Label: &template_area_label,
  91. Id: &template_area_id,
  92. Type: &template_type_text,
  93. }, {
  94. Label: &template_birthday_label,
  95. Id: &template_birthday_id,
  96. Type: &template_type_date,
  97. }, {
  98. Label: &template_birtharea_label,
  99. Id: &template_birtharea_id,
  100. Type: &template_type_text,
  101. }, {
  102. Label: &template_idcard_no_label,
  103. Id: &template_idcard_no_id,
  104. Type: &template_type_text,
  105. }, {
  106. Label: &template_title_label,
  107. Id: &template_title_id,
  108. Type: &template_type_text,
  109. },
  110. }
  111. var predicates []predicate.UsageDetail
  112. predicates = append(predicates, usagedetail.TypeIn(1, 3))
  113. predicates = append(predicates, usagedetail.AppIn(1, 3, 4, 5))
  114. yesterdayStart := time.Now().AddDate(0, 0, -1).Truncate(24 * time.Hour)
  115. yesterdayEnd := yesterdayStart.Add(24 * time.Hour)
  116. predicates = append(predicates, usagedetail.CreatedAtGTE(yesterdayStart))
  117. predicates = append(predicates, usagedetail.CreatedAtLT(yesterdayEnd))
  118. //todayStart := time.Now().AddDate(0, 0, 0).Truncate(24 * time.Hour)
  119. //todayEnd := todayStart.Add(24 * time.Hour)
  120. //predicates = append(predicates, usagedetail.CreatedAtGTE(todayStart))
  121. //predicates = append(predicates, usagedetail.CreatedAtLT(todayEnd))
  122. data, err := l.svcCtx.DB.UsageDetail.Query().Where(predicates...).All(l.ctx)
  123. logx.Info("usageDetails: ", data)
  124. if err != nil {
  125. return
  126. }
  127. for _, u := range data {
  128. if _, ok := contactFieldTemplates[u.BotID]; !ok {
  129. c, _ := l.svcCtx.DB.ContactFieldTemplate.Query().Where(contactfieldtemplate.OrganizationID(u.OrganizationID)).First(l.ctx)
  130. if c != nil {
  131. contactFieldTemplates[u.BotID] = c.Template
  132. } else {
  133. contactFieldTemplates[u.BotID] = nil
  134. }
  135. }
  136. if contactFieldTemplates[u.BotID] == nil {
  137. continue
  138. }
  139. if _, ok := usageDetails[u.BotID]; !ok {
  140. usageDetails[u.BotID] = make(map[string]string)
  141. }
  142. usageDetails[u.BotID][u.ReceiverID] += fmt.Sprintf("用户:%s\n机器人:%s\n", u.Request, u.Response)
  143. }
  144. logx.Info("contactFieldTemplates: ", contactFieldTemplates)
  145. logx.Info("usageDetails: ", usageDetails)
  146. for botID, template := range contactFieldTemplates {
  147. if template == nil {
  148. template = contactBasicFieldTemplates
  149. } else {
  150. template = append(template, contactBasicFieldTemplates...)
  151. }
  152. for receiverID, messages := range usageDetails[botID] {
  153. result, _ := openaiRequest(messages, template)
  154. logx.Info("result: ", result)
  155. if result == nil {
  156. continue
  157. }
  158. _ = l.UpdateContactFields(botID, receiverID, result)
  159. }
  160. }
  161. }
  162. func openaiRequest(messages string, template []custom_types.ContactFieldTemplate) ([]ResponseItem, error) {
  163. url := "https://toolsapi-debug.gkscrm.com/call_center/form/extract"
  164. bodyData := map[string]interface{}{
  165. "form_data": ConvertFormData(template),
  166. "chat_history": messages,
  167. "external_id": uuid.New().String(),
  168. }
  169. logx.Info("bodyData: %+v", bodyData)
  170. bodyBytes, err := json.Marshal(bodyData)
  171. if err != nil {
  172. return nil, err
  173. }
  174. req, err := http.NewRequest("POST", url, bytes.NewBuffer(bodyBytes))
  175. if err != nil {
  176. return nil, err
  177. }
  178. req.Header.Set("Content-Type", "application/json")
  179. req.Header.Set("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIn0.ZS9jnsLPCnmc8L_lu4yaQFp34vwWF1mHlHSBYrY5JVs")
  180. client := &http.Client{}
  181. resp, err := client.Do(req)
  182. if err != nil || resp == nil || resp.Body == nil {
  183. logx.Error("read body error: ", err)
  184. return nil, err
  185. }
  186. logx.Info("err: ", err)
  187. if err != nil {
  188. return nil, err
  189. }
  190. defer resp.Body.Close()
  191. if resp.StatusCode != http.StatusOK {
  192. return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
  193. }
  194. //var result []ResponseItem
  195. var fullResp struct {
  196. Data []ResponseItem `json:"data"`
  197. }
  198. err = json.NewDecoder(resp.Body).Decode(&fullResp)
  199. if err != nil {
  200. return nil, err
  201. }
  202. return fullResp.Data, nil
  203. }
  204. func (l *CronTask) UpdateContactFields(botID string, receiverID string, fields []ResponseItem) error {
  205. basic_ids := []string{"sex", "phone", "name", "age", "area", "birthday", "birtharea", "idcard_no", "title"}
  206. c, _ := l.svcCtx.DB.Contact.Query().Where(contact.WxWxidEQ(botID), contact.WxidEQ(receiverID)).First(l.ctx)
  207. if c == nil {
  208. return fmt.Errorf("Contact not find")
  209. }
  210. for _, field := range fields {
  211. if contains(basic_ids, field.DataIndex) {
  212. if len(field.Value) == 0 {
  213. continue
  214. }
  215. value := 0
  216. if field.DataIndex == "sex" && c.Sex == 0 {
  217. if field.Value[0] == "男" {
  218. value = 1
  219. } else if field.Value[0] == "女" {
  220. value = 2
  221. }
  222. _, err := l.svcCtx.DB.Contact.Update().
  223. Where(contact.WxidEQ(receiverID)).
  224. SetSex(value).
  225. Save(l.ctx)
  226. if err != nil {
  227. continue
  228. }
  229. } else if field.DataIndex == "phone" && c.Phone == "" {
  230. _, err := l.svcCtx.DB.Contact.Update().
  231. Where(contact.WxidEQ(receiverID)).
  232. SetPhone(field.Value[0]).
  233. Save(l.ctx)
  234. if err != nil {
  235. continue
  236. }
  237. } else if field.DataIndex == "name" && c.Cname == "" {
  238. _, err := l.svcCtx.DB.Contact.Update().
  239. Where(contact.WxidEQ(receiverID)).
  240. SetCname(field.Value[0]).
  241. Save(l.ctx)
  242. if err != nil {
  243. continue
  244. }
  245. } else if field.DataIndex == "age" && c.Cage == 0 {
  246. num, err := strconv.Atoi(field.Value[0])
  247. if err != nil {
  248. continue
  249. }
  250. _, err = l.svcCtx.DB.Contact.Update().
  251. Where(contact.WxidEQ(receiverID)).
  252. SetCage(num).
  253. Save(l.ctx)
  254. if err != nil {
  255. continue
  256. }
  257. } else if field.DataIndex == "area" && c.Carea == "" {
  258. _, err := l.svcCtx.DB.Contact.Update().
  259. Where(contact.WxidEQ(receiverID)).
  260. SetCarea(field.Value[0]).
  261. Save(l.ctx)
  262. if err != nil {
  263. continue
  264. }
  265. } else if field.DataIndex == "birthday" && c.Cbirthday == "" {
  266. _, err := l.svcCtx.DB.Contact.Update().
  267. Where(contact.WxidEQ(receiverID)).
  268. SetCbirthday(field.Value[0]).
  269. Save(l.ctx)
  270. if err != nil {
  271. continue
  272. }
  273. } else if field.DataIndex == "birtharea" && c.Cbirtharea == "" {
  274. _, err := l.svcCtx.DB.Contact.Update().
  275. Where(contact.WxidEQ(receiverID)).
  276. SetCbirtharea(field.Value[0]).
  277. Save(l.ctx)
  278. if err != nil {
  279. continue
  280. }
  281. } else if field.DataIndex == "idcard_no" && c.CidcardNo == "" {
  282. _, err := l.svcCtx.DB.Contact.Update().
  283. Where(contact.WxidEQ(receiverID)).
  284. SetCidcardNo(field.Value[0]).
  285. Save(l.ctx)
  286. if err != nil {
  287. continue
  288. }
  289. } else if field.DataIndex == "title" && c.Ctitle == "" {
  290. _, err := l.svcCtx.DB.Contact.Update().
  291. Where(contact.WxidEQ(receiverID)).
  292. SetCtitle(field.Value[0]).
  293. Save(l.ctx)
  294. if err != nil {
  295. continue
  296. }
  297. }
  298. } else {
  299. f, _ := l.svcCtx.DB.ContactField.Query().Where(contactfield.ContactID(c.ID), contactfield.FormID(field.DataIndex)).First(l.ctx)
  300. if f == nil {
  301. if field.Value != nil && len(field.Value) > 0 && field.Value[0] != "" {
  302. _, err := l.svcCtx.DB.ContactField.Create().
  303. SetContactID(c.ID).
  304. SetFormID(field.DataIndex).
  305. SetValue(field.Value).
  306. Save(l.ctx)
  307. if err != nil {
  308. continue
  309. }
  310. }
  311. } else {
  312. if field.Value != nil {
  313. if len(field.Value) == 0 || field.Value[0] == "" {
  314. continue
  315. }
  316. _, err := l.svcCtx.DB.ContactField.UpdateOneID(f.ID).
  317. SetValue(field.Value).
  318. Save(l.ctx)
  319. if err != nil {
  320. continue
  321. }
  322. }
  323. }
  324. }
  325. }
  326. return nil
  327. }
  328. func ConvertFormData(input []custom_types.ContactFieldTemplate) []FormData {
  329. result := make([]FormData, len(input))
  330. for i, item := range input {
  331. options := make([]FieldPropsOptions, len(item.Options))
  332. for j, opt := range item.Options {
  333. options[j] = FieldPropsOptions{
  334. Label: *opt.Label,
  335. Value: *opt.Value,
  336. }
  337. }
  338. result[i] = FormData{
  339. Title: *item.Label,
  340. DataIndex: *item.Id,
  341. ValueType: *item.Type,
  342. FieldProps: FieldProps{
  343. Options: options,
  344. },
  345. }
  346. }
  347. return result
  348. }
  349. func contains(strs []string, target string) bool {
  350. for _, s := range strs {
  351. if s == target {
  352. return true
  353. }
  354. }
  355. return false
  356. }