contact_form.go 12 KB

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