contact_form.go 13 KB

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