contact_form.go 13 KB

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