contact_form.go 12 KB

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