contact_form.go 12 KB

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