contact_form.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. package crontask
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/google/uuid"
  6. "github.com/zeromicro/go-zero/core/logx"
  7. "strconv"
  8. "time"
  9. "wechat-api/ent/contact"
  10. "wechat-api/ent/contactfield"
  11. "wechat-api/ent/contactfieldtemplate"
  12. "wechat-api/ent/custom_types"
  13. "wechat-api/ent/predicate"
  14. "wechat-api/ent/usagedetail"
  15. "wechat-api/internal/types"
  16. "wechat-api/internal/utils/compapi"
  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, 4, 6))
  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. yesterdayEnd := time.Now().Truncate(24 * time.Hour)
  117. yesterdayStart := yesterdayEnd.AddDate(0, 0, -1)
  118. predicates = append(predicates, usagedetail.CreatedAtGTE(yesterdayStart))
  119. predicates = append(predicates, usagedetail.CreatedAtLT(yesterdayEnd))
  120. logx.Info("yesterdayEnd: ", yesterdayEnd)
  121. logx.Info("yesterdayStart: ", yesterdayStart)
  122. //todayStart := time.Now().AddDate(0, 0, 0).Truncate(24 * time.Hour)
  123. //todayEnd := todayStart.Add(24 * time.Hour)
  124. //predicates = append(predicates, usagedetail.CreatedAtGTE(todayStart))
  125. //predicates = append(predicates, usagedetail.CreatedAtLT(todayEnd))
  126. data, err := l.svcCtx.DB.UsageDetail.Query().Where(predicates...).All(l.ctx)
  127. logx.Info("usageDetails: ", data)
  128. if err != nil {
  129. return
  130. }
  131. for _, u := range data {
  132. if _, ok := contactFieldTemplates[u.BotID]; !ok {
  133. c, _ := l.svcCtx.DB.ContactFieldTemplate.Query().Where(contactfieldtemplate.OrganizationID(u.OrganizationID)).First(l.ctx)
  134. if c != nil {
  135. contactFieldTemplates[u.BotID] = c.Template
  136. } else {
  137. contactFieldTemplates[u.BotID] = nil
  138. }
  139. }
  140. if contactFieldTemplates[u.BotID] == nil {
  141. continue
  142. }
  143. if _, ok := usageDetails[u.BotID]; !ok {
  144. usageDetails[u.BotID] = make(map[string]string)
  145. }
  146. usageDetails[u.BotID][u.ReceiverID] += fmt.Sprintf("用户:%s\n机器人:%s\n", u.Request, u.Response)
  147. }
  148. logx.Info("contactFieldTemplates: ", contactFieldTemplates)
  149. logx.Info("usageDetails: ", usageDetails)
  150. for botID, template := range contactFieldTemplates {
  151. if template == nil {
  152. template = contactBasicFieldTemplates
  153. } else {
  154. template = append(template, contactBasicFieldTemplates...)
  155. }
  156. for receiverID, messages := range usageDetails[botID] {
  157. result, _ := l.openaiRequest(messages, template)
  158. logx.Info("result: ", result)
  159. if result == nil {
  160. continue
  161. }
  162. _ = l.UpdateContactFields(botID, receiverID, result)
  163. }
  164. }
  165. }
  166. func (l *CronTask) openaiRequest(messages string, template []custom_types.ContactFieldTemplate) ([]ResponseItem, error) {
  167. formData := ConvertFormData(template)
  168. jsonBytes, err := json.Marshal(formData)
  169. if err != nil {
  170. return nil, err
  171. }
  172. jsonStr := string(jsonBytes)
  173. req := &types.CompApiReq{
  174. types.CompCtlReq{
  175. "form",
  176. "",
  177. false,
  178. "",
  179. },
  180. types.StdCompApiReq{
  181. "gpt-4o",
  182. []types.StdCompMessage{},
  183. false,
  184. nil,
  185. },
  186. types.FastGptSpecReq{
  187. "",
  188. "",
  189. "",
  190. false,
  191. map[string]string{
  192. "form_data": jsonStr,
  193. "chat_history": messages,
  194. "external_id": uuid.New().String(),
  195. },
  196. },
  197. }
  198. resp, err := compapi.NewClient(l.ctx, compapi.WithApiBase("http://new-api.gkscrm.com/v1/"),
  199. compapi.WithApiKey("sk-wwttAtdLcTfeF7F2Eb9d3592Bd4c487f8e8fA544D6C4BbA9")).
  200. Chat(req)
  201. if err == nil && resp != nil && len(resp.Choices) > 0 {
  202. //logx.Info("resp.Choices: ", resp.Choices[0].Message.Content)
  203. var items []ResponseItem
  204. err = json.Unmarshal([]byte(resp.Choices[0].Message.Content), &items)
  205. if err != nil {
  206. return nil, err
  207. }
  208. return items, nil
  209. } else if resp != nil && len(resp.Choices) == 0 {
  210. return nil, err
  211. }
  212. //url := "https://toolsapi-debug.gkscrm.com/call_center/form/extract"
  213. //bodyData := map[string]interface{}{
  214. // "form_data": ConvertFormData(template),
  215. // "chat_history": messages,
  216. // "external_id": uuid.New().String(),
  217. //}
  218. //logx.Info("bodyData: %+v", bodyData)
  219. //bodyBytes, err := json.Marshal(bodyData)
  220. //if err != nil {
  221. // return nil, err
  222. //}
  223. //
  224. //req, err := http.NewRequest("POST", url, bytes.NewBuffer(bodyBytes))
  225. //if err != nil {
  226. // return nil, err
  227. //}
  228. //req.Header.Set("Content-Type", "application/json")
  229. //req.Header.Set("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIn0.ZS9jnsLPCnmc8L_lu4yaQFp34vwWF1mHlHSBYrY5JVs")
  230. //
  231. //client := &http.Client{}
  232. //resp, err := client.Do(req)
  233. //if err != nil || resp == nil || resp.Body == nil {
  234. // logx.Error("read body error: ", err)
  235. // return nil, err
  236. //}
  237. //
  238. //logx.Info("err: ", err)
  239. //if err != nil {
  240. // return nil, err
  241. //}
  242. //defer resp.Body.Close()
  243. //
  244. //if resp.StatusCode != http.StatusOK {
  245. // return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
  246. //}
  247. //
  248. ////var result []ResponseItem
  249. //var fullResp struct {
  250. // Data []ResponseItem `json:"data"`
  251. //}
  252. //err = json.NewDecoder(resp.Body).Decode(&fullResp)
  253. //if err != nil {
  254. // return nil, err
  255. //}
  256. //
  257. //return fullResp.Data, nil
  258. return nil, err
  259. }
  260. func (l *CronTask) UpdateContactFields(botID string, receiverID string, fields []ResponseItem) error {
  261. basic_ids := []string{"sex", "phone", "name", "age", "area", "birthday", "birtharea", "idcard_no", "title"}
  262. c, _ := l.svcCtx.DB.Contact.Query().Where(contact.WxWxidEQ(botID), contact.WxidEQ(receiverID)).First(l.ctx)
  263. if c == nil {
  264. return fmt.Errorf("Contact not find")
  265. }
  266. for _, field := range fields {
  267. if contains(basic_ids, field.DataIndex) {
  268. if len(field.Value) == 0 {
  269. continue
  270. }
  271. value := 0
  272. if field.DataIndex == "sex" && c.Sex == 0 {
  273. if field.Value[0] == "男" {
  274. value = 1
  275. } else if field.Value[0] == "女" {
  276. value = 2
  277. }
  278. _, err := l.svcCtx.DB.Contact.Update().
  279. Where(contact.WxidEQ(receiverID)).
  280. SetSex(value).
  281. Save(l.ctx)
  282. if err != nil {
  283. continue
  284. }
  285. } else if field.DataIndex == "phone" && c.Phone == "" {
  286. _, err := l.svcCtx.DB.Contact.Update().
  287. Where(contact.WxidEQ(receiverID)).
  288. SetPhone(field.Value[0]).
  289. Save(l.ctx)
  290. if err != nil {
  291. continue
  292. }
  293. } else if field.DataIndex == "name" && c.Cname == "" {
  294. _, err := l.svcCtx.DB.Contact.Update().
  295. Where(contact.WxidEQ(receiverID)).
  296. SetCname(field.Value[0]).
  297. Save(l.ctx)
  298. if err != nil {
  299. continue
  300. }
  301. } else if field.DataIndex == "age" && c.Cage == 0 {
  302. num, err := strconv.Atoi(field.Value[0])
  303. if err != nil {
  304. continue
  305. }
  306. _, err = l.svcCtx.DB.Contact.Update().
  307. Where(contact.WxidEQ(receiverID)).
  308. SetCage(num).
  309. Save(l.ctx)
  310. if err != nil {
  311. continue
  312. }
  313. } else if field.DataIndex == "area" && c.Carea == "" {
  314. _, err := l.svcCtx.DB.Contact.Update().
  315. Where(contact.WxidEQ(receiverID)).
  316. SetCarea(field.Value[0]).
  317. Save(l.ctx)
  318. if err != nil {
  319. continue
  320. }
  321. } else if field.DataIndex == "birthday" && c.Cbirthday == "" {
  322. _, err := l.svcCtx.DB.Contact.Update().
  323. Where(contact.WxidEQ(receiverID)).
  324. SetCbirthday(field.Value[0]).
  325. Save(l.ctx)
  326. if err != nil {
  327. continue
  328. }
  329. } else if field.DataIndex == "birtharea" && c.Cbirtharea == "" {
  330. _, err := l.svcCtx.DB.Contact.Update().
  331. Where(contact.WxidEQ(receiverID)).
  332. SetCbirtharea(field.Value[0]).
  333. Save(l.ctx)
  334. if err != nil {
  335. continue
  336. }
  337. } else if field.DataIndex == "idcard_no" && c.CidcardNo == "" {
  338. _, err := l.svcCtx.DB.Contact.Update().
  339. Where(contact.WxidEQ(receiverID)).
  340. SetCidcardNo(field.Value[0]).
  341. Save(l.ctx)
  342. if err != nil {
  343. continue
  344. }
  345. } else if field.DataIndex == "title" && c.Ctitle == "" {
  346. _, err := l.svcCtx.DB.Contact.Update().
  347. Where(contact.WxidEQ(receiverID)).
  348. SetCtitle(field.Value[0]).
  349. Save(l.ctx)
  350. if err != nil {
  351. continue
  352. }
  353. }
  354. } else {
  355. f, _ := l.svcCtx.DB.ContactField.Query().Where(contactfield.ContactID(c.ID), contactfield.FormID(field.DataIndex)).First(l.ctx)
  356. if f == nil {
  357. if field.Value != nil && len(field.Value) > 0 && field.Value[0] != "" {
  358. _, err := l.svcCtx.DB.ContactField.Create().
  359. SetContactID(c.ID).
  360. SetFormID(field.DataIndex).
  361. SetValue(field.Value).
  362. Save(l.ctx)
  363. if err != nil {
  364. continue
  365. }
  366. }
  367. } else {
  368. if field.Value != nil {
  369. if len(field.Value) == 0 || field.Value[0] == "" {
  370. continue
  371. }
  372. _, err := l.svcCtx.DB.ContactField.UpdateOneID(f.ID).
  373. SetValue(field.Value).
  374. Save(l.ctx)
  375. if err != nil {
  376. continue
  377. }
  378. }
  379. }
  380. }
  381. }
  382. return nil
  383. }
  384. func ConvertFormData(input []custom_types.ContactFieldTemplate) []FormData {
  385. result := make([]FormData, len(input))
  386. for i, item := range input {
  387. options := make([]FieldPropsOptions, len(item.Options))
  388. for j, opt := range item.Options {
  389. options[j] = FieldPropsOptions{
  390. Label: *opt.Label,
  391. Value: *opt.Value,
  392. }
  393. }
  394. result[i] = FormData{
  395. Title: *item.Label,
  396. DataIndex: *item.Id,
  397. ValueType: *item.Type,
  398. FieldProps: FieldProps{
  399. Options: options,
  400. },
  401. }
  402. }
  403. return result
  404. }
  405. func contains(strs []string, target string) bool {
  406. for _, s := range strs {
  407. if s == target {
  408. return true
  409. }
  410. }
  411. return false
  412. }