contact_form.go 13 KB

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