everything.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  1. package main
  2. import (
  3. "app.yhyue.com/moapp/jybase/redis"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/gogf/gf/util/gconv"
  7. "log"
  8. "net/url"
  9. "strings"
  10. "time"
  11. "app.yhyue.com/moapp/jybase/mail"
  12. "github.com/tealeg/xlsx"
  13. "app.yhyue.com/moapp/jybase/date"
  14. dates "app.yhyue.com/moapp/jybase/date"
  15. "app.yhyue.com/moapp/jybase/mongodb"
  16. "app.yhyue.com/moapp/jybase/common"
  17. )
  18. // 渠道定时任务
  19. func everythingSync() {
  20. lastEverythingTime := cfg.LastEverythingTime
  21. codeArr := []string{}
  22. if len(UserChannel) > 0 {
  23. for i, _ := range UserChannel {
  24. codeArr = append(codeArr, fmt.Sprintf(`"%s"`, i))
  25. }
  26. }
  27. sql := fmt.Sprintf(`select * from user_source where channel_code in (%s) and create_time > "%s" order by create_time asc`, strings.Join(codeArr, ","), lastEverythingTime)
  28. log.Println("三方渠道数据定时任务开始", sql)
  29. data := ThirdParty.SelectBySql(sql)
  30. if data != nil && *data != nil && len(*data) > 0 {
  31. everythingSyncHandle(data, true)
  32. }
  33. sql = fmt.Sprintf(`select * from user_source where channel_code in (%s) and ishandle=1 order by create_time asc`, strings.Join(codeArr, ","))
  34. log.Println("三方渠道数据定时任务开始1", sql)
  35. data = ThirdParty.SelectBySql(sql)
  36. if data != nil && *data != nil && len(*data) > 0 {
  37. everythingSyncHandle(data, false)
  38. }
  39. log.Println("三方渠道数据定时任务结束")
  40. }
  41. func everythingSyncHandle(data *[]map[string]interface{}, isUpdate bool) {
  42. nowTime := time.Now().Format(dates.Date_Full_Layout)
  43. for _, v := range *data {
  44. id := gconv.Int64(v["id"])
  45. channel_code := gconv.String(v["channel_code"])
  46. changeMap := UserChannel[channel_code]
  47. channeName := changeMap["name"]
  48. channelCode := changeMap["clueCode"]
  49. user_id := common.ObjToString(v["user_id"])
  50. position_id := common.Int64All(v["position_id"])
  51. phone := common.ObjToString(v["phone"])
  52. state := common.IntAll(v["state"])
  53. user_mold, is_assign, is_transfer, last_login_time, registe_time, mailbox, source, clueId, order_type := 4, 0, 0, "", "", "", "", int64(0), ""
  54. owner, sales_lead_phone, sales_ent_name, sales_position, sales_dep, data_request, sales_leads_source := "", "", "", "", "", "", ""
  55. cData := TiDb.FindOne("dwd_f_crm_clue_info", map[string]interface{}{"phone": phone}, "", "")
  56. if cData != nil {
  57. is_assign = common.IntAll((*cData)["is_assign"])
  58. is_transfer = common.IntAll((*cData)["is_transfer"])
  59. clueId = common.Int64All((*cData)["id"])
  60. }
  61. udata := TiDb.FindOne("dwd_f_userbase_baseinfo", map[string]interface{}{"userid": user_id}, "", "")
  62. if udata != nil {
  63. userSource := common.ObjToString((*udata)["source"])
  64. if userSource == "0102" {
  65. continue
  66. }
  67. }
  68. //
  69. /*cuData := TiDbData.FindOne("customer", map[string]interface{}{"phone": phone}, "", "")
  70. if cuData != nil {
  71. owner = common.ObjToString((*cuData)["owner"])
  72. unique_id = common.ObjToString((*cuData)["unique_id"])
  73. belongTo = common.ObjToString((*cuData)["belongTo"])
  74. }*/
  75. vData := TiDb.FindOne("dwd_f_userbase_visit_info", map[string]interface{}{"userid": user_id}, "", "")
  76. if vData != nil {
  77. last_login_time = common.ObjToString((*vData)["date"])
  78. }
  79. dData := Mysql.Find("dataexport_order", map[string]interface{}{"user_id": user_id}, "", "", -1, -1)
  80. if dData != nil && len(*dData) > 0 {
  81. pMap := map[string]string{}
  82. pArr := []string{}
  83. for _, v := range *dData {
  84. product_type := common.ObjToString(v["product_type"])
  85. pMap[product_type] = "1"
  86. }
  87. for k := range pMap {
  88. pArr = append(pArr, k)
  89. }
  90. if len(pArr) > 0 {
  91. order_type = strings.Join(pArr, ",")
  92. }
  93. }
  94. uData, ok := Mgo.FindOne("user", map[string]interface{}{"_id": mongodb.StringTOBsonId(user_id)})
  95. if ok && uData != nil {
  96. l_registedate := common.Int64All((*uData)["l_registedate"])
  97. registe_time = time.Unix(l_registedate, 0).Format(dates.Date_Full_Layout)
  98. }
  99. if uData == nil || len(*uData) == 0 {
  100. ThirdParty.Update("", map[string]interface{}{
  101. "id": id,
  102. }, map[string]interface{}{
  103. "ishandle": 1,
  104. })
  105. continue
  106. }
  107. sData, oks := Mgo.Find("saleLeads", map[string]interface{}{"userid": user_id}, `{"_id":-1}`, nil, false, 0, 1)
  108. if oks && sData != nil {
  109. if len(*sData) > 0 {
  110. sDatas := (*sData)[0]
  111. sales_lead_phone = common.ObjToString(sDatas["phone"])
  112. sales_position = common.ObjToString(sDatas["position"])
  113. sales_ent_name = common.ObjToString(sDatas["company"])
  114. sales_dep = common.ObjToString(sDatas["branch"])
  115. if sales_dep == "" {
  116. sales_dep = common.ObjToString(sDatas["department"])
  117. }
  118. data_request = common.ObjToString(sDatas["data_requirement"])
  119. mailbox = common.ObjToString(sDatas["mail"])
  120. source = common.ObjToString(sDatas["interest"])
  121. }
  122. }
  123. if state == 1 {
  124. sales_leads_source = fmt.Sprintf("%s登录", channeName)
  125. if is_assign == 1 || is_transfer == 1 || owner != "" {
  126. user_mold = 1
  127. } else {
  128. user_mold = 2
  129. }
  130. } else if state == 2 {
  131. sales_leads_source = fmt.Sprintf("%s注册", channeName)
  132. if is_assign == 1 || is_transfer == 1 || owner != "" {
  133. user_mold = 3
  134. } else {
  135. user_mold = 4
  136. }
  137. }
  138. if ThirdParty.Count("user_channel_info", map[string]interface{}{"user_id": user_id}) > 0 {
  139. ThirdParty.Update("user_channel_info", map[string]interface{}{"user_id": user_id}, map[string]interface{}{
  140. "user_mold": user_mold,
  141. "last_login_time": common.If(last_login_time != "", last_login_time, nil),
  142. "sales_lead_phone": sales_lead_phone,
  143. "sales_ent_name": sales_ent_name,
  144. "sales_position": sales_position,
  145. "sales_dep": sales_dep,
  146. "sales_leads_source": sales_leads_source,
  147. "mailbox": mailbox,
  148. "order_type": order_type,
  149. "data_request": data_request,
  150. "source": source,
  151. "update_time": nowTime,
  152. })
  153. } else {
  154. ThirdParty.Insert("user_channel_info", map[string]interface{}{
  155. "user_id": user_id,
  156. "registe_time": registe_time,
  157. "phone": phone,
  158. "user_mold": user_mold,
  159. "last_login_time": common.If(last_login_time != "", last_login_time, nil),
  160. "sales_lead_phone": sales_lead_phone,
  161. "sales_ent_name": sales_ent_name,
  162. "sales_position": sales_position,
  163. "sales_dep": sales_dep,
  164. "sales_leads_source": sales_leads_source,
  165. "order_type": order_type,
  166. "mailbox": mailbox,
  167. "data_request": data_request,
  168. "source": source,
  169. "update_time": nowTime,
  170. })
  171. }
  172. if clueId > 0 && is_assign != 1 && is_transfer != 1 {
  173. TiDb.Update("dwd_f_userbase_baseinfo", map[string]interface{}{"userid": user_id}, map[string]interface{}{"belong_to": channelCode})
  174. TiDb.Update("dwd_f_crm_clue_info", map[string]interface{}{"phone": phone}, map[string]interface{}{"is_assign": -1})
  175. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  176. "clue_id": clueId,
  177. "position_id": common.If(position_id > 0, position_id, -1),
  178. "change_type": "退出公海",
  179. "new_value": fmt.Sprintf("通过合作渠道%s", channeName) + fmt.Sprint(common.If(user_mold == 1 || user_mold == 2, "登录", "注册")),
  180. "createtime": nowTime,
  181. "BCPCID": common.GetRandom(32),
  182. "operator_id": -1,
  183. })
  184. }
  185. ThirdParty.Update("", map[string]interface{}{
  186. "id": id,
  187. }, map[string]interface{}{
  188. "ishandle": 0,
  189. })
  190. }
  191. if isUpdate {
  192. cfg.LastEverythingTime = common.ObjToString((*data)[len(*data)-1]["create_time"])
  193. common.WriteSysConfig(&cfg)
  194. }
  195. }
  196. func saveEverything(user_id, phone, item, sourceName, sourceCode, belongTo string) bool {
  197. changeMap := UserChannel[belongTo]
  198. changeName := gconv.String(changeMap["name"])
  199. nowTime, isOk := time.Now().Format(dates.Date_Full_Layout), false
  200. user_mold, is_assign, is_transfer, last_login_time, registe_time, mailbox, source, order_type, sales_leads_source := 4, 0, 0, "", "", "", "", "", ""
  201. owner, sales_lead_phone, sales_ent_name, sales_position, sales_dep, data_request, clueId, position_id := "", "", "", "", "", "", int64(0), int64(0)
  202. cData := TiDb.FindOne("dwd_f_crm_clue_info", map[string]interface{}{"phone": phone}, "", "")
  203. if cData != nil {
  204. is_assign = common.IntAll((*cData)["is_assign"])
  205. is_transfer = common.IntAll((*cData)["is_transfer"])
  206. clueId = common.Int64All((*cData)["is_transfer"])
  207. position_id = common.Int64All((*cData)["position_id"])
  208. }
  209. cuData := TiDbData.FindOne("customer", map[string]interface{}{"phone": phone}, "", "")
  210. if cuData != nil {
  211. owner = common.ObjToString((*cuData)["owner"])
  212. }
  213. dData := Mysql.Find("dataexport_order", map[string]interface{}{"user_id": user_id}, "", "", -1, -1)
  214. if dData != nil && len(*dData) > 0 {
  215. pMap := map[string]string{}
  216. pArr := []string{}
  217. for _, v := range *dData {
  218. product_type := common.ObjToString(v["product_type"])
  219. pMap[product_type] = "1"
  220. }
  221. for k := range pMap {
  222. pArr = append(pArr, k)
  223. }
  224. if len(pArr) > 0 {
  225. order_type = strings.Join(pArr, ",")
  226. }
  227. }
  228. vData := TiDb.FindOne("dwd_f_userbase_visit_info", map[string]interface{}{"userid": user_id}, "", "")
  229. if vData != nil {
  230. last_login_time = common.ObjToString((*vData)["date"])
  231. }
  232. uData, ok := Mgo.FindOne("user", map[string]interface{}{"_id": mongodb.StringTOBsonId(user_id)})
  233. if ok && uData != nil {
  234. l_registedate := common.Int64All((*uData)["l_registedate"])
  235. registe_time = time.Unix(l_registedate, 0).Format(dates.Date_Full_Layout)
  236. }
  237. if item == "orders" {
  238. sales_leads_source = "订单未支付"
  239. } else if item == "users" || item == "xcxusers" {
  240. return false
  241. } else if item == "saleLeads" {
  242. sales_leads_source = sourceName
  243. } else {
  244. sales_leads_source = "用户留资"
  245. }
  246. query := map[string]interface{}{"userid": user_id}
  247. if sourceCode != "" {
  248. query["source"] = sourceCode
  249. }
  250. sData, oks := Mgo.Find("saleLeads", query, `{"_id":-1}`, nil, false, 0, 1)
  251. if oks && sData != nil {
  252. if len(*sData) > 0 {
  253. sDatas := (*sData)[0]
  254. sales_lead_phone = common.ObjToString(sDatas["phone"])
  255. sales_position = common.ObjToString(sDatas["position"])
  256. sales_ent_name = common.ObjToString(sDatas["company"])
  257. sales_dep = common.ObjToString(sDatas["branch"])
  258. if sales_dep == "" {
  259. sales_dep = common.ObjToString(sDatas["department"])
  260. }
  261. data_request = common.ObjToString(sDatas["data_requirement"])
  262. mailbox = common.ObjToString(sDatas["mail"])
  263. source = common.ObjToString(sDatas["interest"])
  264. }
  265. }
  266. if is_assign == 1 || is_transfer == 1 || owner != "" {
  267. user_mold = 1
  268. } else {
  269. user_mold = 2
  270. }
  271. /*if owner == "" && unique_id != "" && belongTo == "市场部" {
  272. token := getToken()
  273. if token != "" {
  274. sss := url.QueryEscape("合作渠道一切都好")
  275. urls := `https://a1.7x24cc.com/commonInte?flag=1008&account=N000000029739&accessToken=` + token + `&cusObj={"unique_id":"` + unique_id + `","empNo":"8049","owner":"8049","source":"` + sss + `"}&dbType=0001`
  276. bs, err := doGet(urls)
  277. if err != nil {
  278. log.Println("调用接口失败", unique_id, err)
  279. }
  280. resMap := common.StringToMap(string(bs))
  281. if resMap["success"] != nil && resMap["success"].(bool) {
  282. ok := TiDbData.Update("customer", map[string]interface{}{"unique_id": unique_id}, map[string]interface{}{"empNo": "8049", "owner": "8049", "source": "合作渠道一切都好"})
  283. if ok {
  284. log.Println("更新成功", unique_id)
  285. } else {
  286. log.Println("更新失败", unique_id)
  287. }
  288. } else {
  289. log.Println("调用接口失败!!", unique_id)
  290. }
  291. }
  292. }*/
  293. if ThirdParty.Count("user_channel_info", map[string]interface{}{"user_id": user_id}) > 0 {
  294. ThirdParty.Update("user_channel_info", map[string]interface{}{"user_id": user_id}, map[string]interface{}{
  295. "user_mold": user_mold,
  296. "last_login_time": common.If(last_login_time != "", last_login_time, nil),
  297. "sales_lead_phone": sales_lead_phone,
  298. "sales_ent_name": sales_ent_name,
  299. "sales_position": sales_position,
  300. "sales_dep": sales_dep,
  301. "sales_leads_source": sales_leads_source,
  302. "mailbox": mailbox,
  303. "data_request": data_request,
  304. "source": source,
  305. "order_type": order_type,
  306. "update_time": nowTime,
  307. })
  308. } else {
  309. ThirdParty.Insert("user_channel_info", map[string]interface{}{
  310. "user_id": user_id,
  311. "registe_time": registe_time,
  312. "phone": phone,
  313. "user_mold": user_mold,
  314. "last_login_time": common.If(last_login_time != "", last_login_time, nil),
  315. "sales_lead_phone": sales_lead_phone,
  316. "sales_ent_name": sales_ent_name,
  317. "sales_position": sales_position,
  318. "sales_dep": sales_dep,
  319. "sales_leads_source": sales_leads_source,
  320. "mailbox": mailbox,
  321. "data_request": data_request,
  322. "order_type": order_type,
  323. "source": source,
  324. "update_time": nowTime,
  325. })
  326. }
  327. if clueId > 0 && is_assign != 1 && is_transfer != 1 {
  328. TiDb.Update("dwd_f_crm_clue_info", map[string]interface{}{"phone": phone}, map[string]interface{}{"is_assign": -1})
  329. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  330. "clue_id": clueId,
  331. "position_id": common.If(position_id > 0, position_id, -1),
  332. "change_type": "退出公海",
  333. "new_value": fmt.Sprintf("通过合作渠道%s登录", changeName),
  334. "createtime": nowTime,
  335. "BCPCID": common.GetRandom(32),
  336. "operator_id": -1,
  337. })
  338. } else if is_assign == 1 || is_transfer == 1 {
  339. isOk = true
  340. }
  341. return isOk
  342. }
  343. // 大客户线索-发邮件
  344. func bigCustomer() {
  345. runOk := getRunOk()
  346. if !runOk {
  347. log.Println("不是工作日,任务暂停")
  348. return
  349. }
  350. log.Println("大客户线索定时任务开始")
  351. dataArr := []map[string]interface{}{}
  352. filterArr := []string{"-pc", "-app", "-wx", "-h5"}
  353. sourceMap := map[string]map[string]interface{}{} //根据留资维表:tidb/Jianyu_subjectdb/d_saleleads_code
  354. saleSource := TiDb.SelectBySql(`SELECT source,name,appoint_email FROM d_saleleads_code WHERE department LIKE '%大客户%' AND is_delete = 1`)
  355. if saleSource != nil && len(*saleSource) > 0 {
  356. for _, v := range *saleSource {
  357. saleSourceMap := v
  358. source := common.ObjToString(v["source"])
  359. name := common.ObjToString(v["name"])
  360. for _, s := range filterArr {
  361. name = strings.ReplaceAll(name, s, "")
  362. }
  363. saleSourceMap["name"] = name
  364. sourceMap[source] = saleSourceMap
  365. }
  366. }
  367. nowTime := time.Now().Format(date.Date_Full_Layout)
  368. bigSaleTime := cfg.BigSaleTime
  369. bigOrderTime := cfg.BigOrderTime
  370. if bigSaleTime == 0 {
  371. bigSaleTime = time.Now().Unix()
  372. }
  373. if bigOrderTime == "" {
  374. bigOrderTime = nowTime
  375. }
  376. data := FindBatchData("dk")
  377. saleleadsData, ok := Mgo.Find("saleLeads", map[string]interface{}{"createtime": map[string]interface{}{"$gt": bigSaleTime}}, `{"phone":1,"createtime":1}`, nil, false, -1, -1)
  378. if ok && saleleadsData != nil && len(*saleleadsData) > 0 {
  379. for _, v := range *saleleadsData {
  380. sources := common.ObjToString(v["source"])
  381. userid := common.ObjToString(v["userid"])
  382. uid := ""
  383. if !mongodb.IsObjectIdHex(userid) {
  384. userMapping := TiDb.FindOne("dwd_f_userbase_id_mapping", map[string]interface{}{"position_id": userid}, "", "")
  385. if userMapping != nil && len(*userMapping) > 0 {
  386. userid = common.ObjToString((*userMapping)["userid"])
  387. uid = common.ObjToString((*userMapping)["uid"])
  388. }
  389. } else {
  390. userMapping := TiDb.FindOne("dwd_f_userbase_id_mapping", map[string]interface{}{"userid": userid}, "", "")
  391. if userMapping != nil && len(*userMapping) > 0 {
  392. userid = common.ObjToString((*userMapping)["userid"])
  393. uid = common.ObjToString((*userMapping)["uid"])
  394. }
  395. }
  396. if sourceMap[sources] != nil {
  397. sourceData := sourceMap[sources]
  398. source := sourceData["name"]
  399. phone := common.ObjToString(v["phone"])
  400. if IsInternal(phone) {
  401. continue
  402. }
  403. key := fmt.Sprintf("%s_%s", source, phone)
  404. if _, ok := data[key]; ok {
  405. continue
  406. }
  407. data[key] = true
  408. company := common.ObjToString(v["company"])
  409. job := common.ObjToString(v["position"])
  410. username := common.ObjToString(v["name"])
  411. email := common.ObjToString(v["mail"])
  412. interest := common.ObjToString(v["interest"])
  413. data_requirement := common.ObjToString(v["data_requirement"])
  414. belongTo, usernickname := "大客户", ""
  415. userData := TiDb.FindOne("dwd_f_userbase_baseinfo", map[string]interface{}{"uid": uid}, "", "")
  416. if userData != nil {
  417. usernickname = common.ObjToString((*userData)["nickname"])
  418. bt := common.ObjToString((*userData)["belong_to"])
  419. if strings.HasPrefix(bt, "03") || bt == "0102" {
  420. continue
  421. }
  422. }
  423. dataArr = append(dataArr, map[string]interface{}{
  424. "createTime": nowTime,
  425. "lastUpdateTime": nowTime,
  426. "uid": uid,
  427. "userid": userid,
  428. "username": username,
  429. "usernickname": usernickname,
  430. "company": company,
  431. "job": job,
  432. "phone": phone,
  433. "email": email,
  434. "source": source,
  435. "belongTo": belongTo,
  436. "interest": interest,
  437. "data_requirement": data_requirement,
  438. "appoint_email": sourceData["appoint_email"],
  439. })
  440. }
  441. if gconv.Int64(v["createtime"]) > bigSaleTime {
  442. bigSaleTime = gconv.Int64(v["createtime"])
  443. }
  444. }
  445. }
  446. cfg.BigSaleTime = bigSaleTime
  447. orderData := Mysql.SelectBySql(`SELECT * FROM dataexport_order WHERE create_time > "` + bigOrderTime + `" AND (product_type = '历史数据' or product_type = '数据流量包') AND order_status IN (0,1) AND salesperson IS NULL AND is_backstage_order = 0`)
  448. if orderData != nil && len(*orderData) > 0 {
  449. for _, v := range *orderData {
  450. bigOrderTime = gconv.Time(gconv.String(v["create_time"])).Format(date.Date_Full_Layout)
  451. phone := common.ObjToString(v["user_phone"])
  452. order_status := common.IntAll(v["order_status"])
  453. product_type := common.ObjToString(v["product_type"])
  454. orderUserId := gconv.String(v["user_id"])
  455. query := map[string]interface{}{}
  456. if !mongodb.IsObjectIdHex(orderUserId) {
  457. userMapping := TiDb.FindOne("dwd_f_userbase_id_mapping", map[string]interface{}{"position_id": orderUserId}, "", "")
  458. if userMapping != nil && len(*userMapping) > 0 {
  459. uid := common.ObjToString((*userMapping)["uid"])
  460. query["uid"] = uid
  461. }
  462. } else {
  463. query["userid"] = orderUserId
  464. }
  465. userData := TiDb.FindOne("dwd_f_userbase_baseinfo", query, "", "")
  466. username, usernickname, userid, uid, source, payorderinfo, unpayorderinfo := "", "", "", "", "", "", ""
  467. if userData != nil {
  468. if phone == "" {
  469. phone = common.ObjToString((*userData)["phone"])
  470. }
  471. if IsInternal(phone) {
  472. continue
  473. }
  474. username = common.ObjToString((*userData)["name"])
  475. usernickname = common.ObjToString((*userData)["nickname"])
  476. uid = common.ObjToString((*userData)["uid"])
  477. userid = common.ObjToString((*userData)["userid"])
  478. bt := common.ObjToString((*userData)["belong_to"])
  479. if strings.HasPrefix(bt, "03") || bt == "0102" {
  480. continue
  481. }
  482. }
  483. if product_type == "历史数据" {
  484. if order_status == 0 {
  485. source = "线上历史数据导出未支付订单"
  486. unpayorderinfo = "历史数据"
  487. } else {
  488. source = "线上历史数据导出已支付订单"
  489. payorderinfo = "历史数据" + fmt.Sprint(common.IntAll(v["pay_money"])/100)
  490. }
  491. } else {
  492. if order_status == 0 {
  493. source = "线上数据流量包未支付订单"
  494. unpayorderinfo = "数据流量包"
  495. } else {
  496. source = "线上数据流量包已支付订单"
  497. payorderinfo = "数据流量包" + fmt.Sprint(common.IntAll(v["pay_money"])/100)
  498. }
  499. }
  500. key := fmt.Sprintf("%s_%s", source, phone)
  501. if _, ok := data[key]; ok {
  502. continue
  503. }
  504. data[key] = true
  505. dataArr = append(dataArr, map[string]interface{}{
  506. "createTime": nowTime,
  507. "lastUpdateTime": nowTime,
  508. "phone": phone,
  509. "username": username,
  510. "usernickname": usernickname,
  511. "uid": uid,
  512. "userid": userid,
  513. "company": v["company_name"],
  514. "email": v["user_mail"],
  515. "belongTo": "大客户",
  516. "source": source,
  517. "data_count": v["data_count"],
  518. "unpayorderinfo": unpayorderinfo,
  519. "payorderinfo": payorderinfo, //增加客户需求
  520. "appoint_email": "",
  521. })
  522. }
  523. cfg.BigOrderTime = bigOrderTime
  524. }
  525. saveDataToRedis(data, "dk")
  526. xlsxArr := []string{"用户昵称", "姓名", "公司名称", "职位", "联系人电话", "购买条数", "用户邮箱", "已支付订单信息", "未支付订单类型", "销售线索来源", "具体来源", "数据需求"}
  527. if len(dataArr) > 0 {
  528. bigArr := map[string][]map[string]interface{}{}
  529. for _, v := range dataArr {
  530. minemail := ""
  531. if gconv.String(v["appoint_email"]) == "" {
  532. minemail, _ = EmailSelect("dk")
  533. } else {
  534. minemail = gconv.String(v["appoint_email"])
  535. }
  536. bigArr[minemail] = append(bigArr[minemail], v)
  537. }
  538. for k, vb := range bigArr {
  539. batch := FindBatch("dk")
  540. fileName, detailName := time.Now().Format(date.Date_Short_Layout)+"-"+batch+"大客户销售线索", ""
  541. xf := xlsx.NewFile()
  542. style := xlsx.NewStyle()
  543. style.Font.Size = 12
  544. style.Font.Bold = true
  545. style.Alignment.Vertical = "center"
  546. style.Alignment.Horizontal = "center"
  547. detailName = time.Now().Format(date.Date_Short_Layout) + "数据详情请查看附件"
  548. sh, _ := xf.AddSheet("线索数据")
  549. row1 := sh.AddRow()
  550. for _, x := range xlsxArr {
  551. cell := row1.AddCell()
  552. cell.SetString(x)
  553. cell.SetStyle(style)
  554. }
  555. for _, v := range vb {
  556. row := sh.AddRow()
  557. row.AddCell().SetString(common.ObjToString(v["usernickname"]))
  558. row.AddCell().SetString(common.ObjToString(v["username"]))
  559. row.AddCell().SetString(common.ObjToString(v["company"]))
  560. row.AddCell().SetString(common.ObjToString(v["job"]))
  561. row.AddCell().SetString(common.ObjToString(v["phone"]))
  562. row.AddCell().SetValue(common.IntAll(v["data_count"]))
  563. row.AddCell().SetString(common.ObjToString(v["email"]))
  564. row.AddCell().SetString(common.ObjToString(v["payorderinfo"]))
  565. row.AddCell().SetString(common.ObjToString(v["unpayorderinfo"]))
  566. row.AddCell().SetString(common.ObjToString(v["source"]))
  567. row.AddCell().SetString(common.ObjToString(v["interest"]))
  568. row.AddCell().SetString(common.ObjToString(v["data_requirement"]))
  569. //增加客户需求
  570. }
  571. email := k
  572. //email = "wanghao@jianyu360.com"
  573. dir := "./xlsx/dk/" + fileName + ".xlsx"
  574. err := xf.Save(dir)
  575. if err != nil {
  576. log.Println("xls error", err, dir)
  577. } else {
  578. status := mail.GSendMail_q("剑鱼标讯", email, "", "", fileName, detailName, dir, fileName+".xlsx", &Gmail)
  579. if status {
  580. log.Println("send mail success", fileName, email)
  581. }
  582. }
  583. }
  584. }
  585. common.WriteSysConfig(&cfg)
  586. log.Println("大客户线索定时任务结束")
  587. }
  588. func IsInternal(phone string) bool {
  589. if DataAnalysisService.Count("dwd_f_userbase_insider", map[string]interface{}{
  590. "mobile": phone,
  591. }) > 0 {
  592. return true
  593. }
  594. return false
  595. }
  596. func eventReg() {
  597. lastEventRegTime := cfg.LastEventRegTime
  598. sql := fmt.Sprintf(`select * from exhibition_sign_up where is_del = 0 and update_time > "%s" order by update_time asc`, lastEventRegTime)
  599. log.Println("活动报名表定时任务开始", sql)
  600. data := Jyactivities.SelectBySql(sql)
  601. if data != nil && *data != nil && len(*data) > 0 {
  602. for _, v := range *data {
  603. ok1, ok2, _ := FormatData(v, "eventReg")
  604. if !ok1 {
  605. common.WriteSysConfig(&cfg)
  606. log.Println("线索卡点", "eventReg", v, lastEventRegTime)
  607. } else {
  608. if !ok2 {
  609. log.Println("用户分配已达上限", "eventReg", v, lastEventRegTime)
  610. common.WriteSysConfig(&cfg)
  611. }
  612. }
  613. cfg.LastEventRegTime = common.ObjToString(v["update_time"])
  614. }
  615. }
  616. common.WriteSysConfig(&cfg)
  617. log.Println("活动报名表定时任务结束")
  618. }
  619. func saveHlyj(belong_to, item, phone, name, sourceName, cluename, position, nowTime string, isGroup, isCommerce int) {
  620. if strings.HasPrefix(belong_to, "02") && item == "eventReg" {
  621. saveMap := map[string]interface{}{
  622. "unique_id": phone,
  623. "phone": phone,
  624. "username": name,
  625. "source": sourceName,
  626. "status999": "status5",
  627. "company": cluename,
  628. "job": position,
  629. "belongTo": "市场部",
  630. "createTime": nowTime,
  631. "lastUpdateTime": nowTime,
  632. }
  633. token := getToken()
  634. updateData := map[string]interface{}{
  635. "dbType": "0001",
  636. "customerList": []map[string]interface{}{saveMap},
  637. }
  638. dataByte, _ := json.Marshal(&updateData)
  639. url := `https://a1.7x24cc.com/commonInte?flag=1007&account=N000000029739&accessToken=` + token + `&json=` + url.QueryEscape(string(dataByte))
  640. bs, err := doGet(url)
  641. if err != nil {
  642. log.Println("调用接口失败")
  643. } else {
  644. resMap := common.StringToMap(string(bs))
  645. if resMap["success"] != nil && resMap["success"].(bool) {
  646. saveMap["company_nature"] = isGroup
  647. saveMap["company_verification"] = isCommerce
  648. TiDbData.Insert("customer", saveMap)
  649. } else {
  650. log.Println("新增线索失败")
  651. }
  652. }
  653. }
  654. }
  655. func FindBatch(moudle string) string {
  656. now := time.Now().Format("2006-01-02")
  657. key := fmt.Sprintf("batch_%s_%s", now, moudle)
  658. yesterday := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
  659. yesterdayKey := fmt.Sprintf("batch_%s_%s", yesterday, moudle)
  660. if ok, _ := redis.Exists("newother", yesterdayKey); ok {
  661. //删除之前数据
  662. redis.Del("newother", yesterdayKey)
  663. }
  664. batch := redis.Incr("newother", key)
  665. return fmt.Sprintf("%04d", batch)
  666. }
  667. func FindBatchData(moudle string) map[string]interface{} {
  668. now := time.Now().Format("2006-01-02")
  669. //数据提取
  670. keyContent := fmt.Sprintf("data_%s_%s", now, moudle)
  671. data := redis.Get("newother", keyContent)
  672. if data == nil {
  673. return make(map[string]interface{})
  674. } else {
  675. return gconv.Map(data)
  676. }
  677. }
  678. // 咨询组线索
  679. func AdvisoryCommittee() {
  680. if !isRunning() {
  681. log.Println("不是工作日,任务暂停")
  682. return
  683. }
  684. log.Println("咨询部线索定时任务开始")
  685. sourceMap := buildSourceMap("咨询组")
  686. nowTime := time.Now().Format(date.Date_Full_Layout)
  687. startTime := getCommitteeTime(cfg.AdvisoryCommitteeTime)
  688. dataArr, endtime := processLeads("zx", startTime, sourceMap, nowTime)
  689. cfg.AdvisoryCommitteeTime = endtime
  690. exportToExcel(dataArr, "咨询服务销售线索", "zx")
  691. log.Println("咨询部线索定时任务结束")
  692. common.WriteSysConfig(&cfg)
  693. }
  694. // 运营部线索
  695. func SelectionDepartment() {
  696. if !isRunning() {
  697. log.Println("不是工作日,任务暂停")
  698. return
  699. }
  700. log.Println("运营部线索定时任务开始")
  701. sourceMap := buildSourceMap("运营部")
  702. nowTime := time.Now().Format(date.Date_Full_Layout)
  703. startTime := getCommitteeTime(cfg.SelectionDepartmentTime)
  704. dataArr, endtime := processLeads("yy", startTime, sourceMap, nowTime)
  705. cfg.SelectionDepartmentTime = endtime
  706. exportToExcel(dataArr, "运营部销售线索", "yy")
  707. log.Println("运营部线索定时任务结束")
  708. common.WriteSysConfig(&cfg)
  709. }
  710. // 市场部线索
  711. func MarketCustomer() {
  712. if !isRunning() {
  713. log.Println("不是工作日,任务暂停")
  714. return
  715. }
  716. log.Println("市场部线索定时任务开始")
  717. sourceMap := buildSourceMap("市场组")
  718. nowTime := time.Now().Format(date.Date_Full_Layout)
  719. startTime := getCommitteeTime(cfg.MarketSaleTime)
  720. dataArr, endtime := processLeads("sc", startTime, sourceMap, nowTime)
  721. cfg.MarketSaleTime = endtime
  722. exportToExcel(dataArr, "商务合作销售线索", "sc")
  723. common.WriteSysConfig(&cfg)
  724. log.Println("市场部线索定时任务结束")
  725. }
  726. // 判断是否在工作日
  727. func isRunning() bool {
  728. return getRunOk()
  729. }
  730. // 从数据库构建来源映射
  731. func buildSourceMap(department string) map[string]map[string]interface{} {
  732. sourceMap := map[string]map[string]interface{}{}
  733. saleSource := TiDb.SelectBySql(fmt.Sprintf(`SELECT source,name,appoint_email FROM d_saleleads_code WHERE department LIKE '%%%s%%' AND is_delete = 1`, department))
  734. if saleSource != nil {
  735. for _, v := range *saleSource {
  736. source := common.ObjToString(v["source"])
  737. name := common.ObjToString(v["name"])
  738. name = filterSourceName(name)
  739. appointEmail := common.ObjToString(v["appoint_email"])
  740. sourceMap[source] = map[string]interface{}{
  741. "name": name,
  742. "appointEmail": appointEmail,
  743. }
  744. }
  745. }
  746. return sourceMap
  747. }
  748. // 过滤来源名称
  749. func filterSourceName(name string) string {
  750. filterArr := []string{"-pc", "-app", "-wx", "-h5"}
  751. for _, s := range filterArr {
  752. name = strings.ReplaceAll(name, s, "")
  753. }
  754. return name
  755. }
  756. // 获取最后一条数据时间
  757. func getCommitteeTime(cfgTime int64) int64 {
  758. if cfgTime == 0 {
  759. return time.Now().Unix()
  760. }
  761. return cfgTime
  762. }
  763. // 处理线索
  764. func processLeads(batch string, committeeTime int64, sourceMap map[string]map[string]interface{}, nowTime string) ([]map[string]interface{}, int64) {
  765. dataArr := []map[string]interface{}{}
  766. endtime := int64(0)
  767. saleleadsData, ok := Mgo.Find("saleLeads", map[string]interface{}{"createtime": map[string]interface{}{"$gt": committeeTime}}, `{"phone":1,"createtime":1}`, nil, false, -1, -1)
  768. //saleleadsData, ok := Mgo.Find("saleLeads", map[string]interface{}{"createtime": committeeTime}, `{"phone":1,"createtime":1}`, nil, false, -1, -1)
  769. if ok && saleleadsData != nil {
  770. data := FindBatchData(batch)
  771. for _, v := range *saleleadsData {
  772. lead := map[string]interface{}{}
  773. lead, endtime = processLead(v, sourceMap, nowTime, committeeTime, data)
  774. if lead != nil {
  775. dataArr = append(dataArr, lead)
  776. }
  777. }
  778. saveDataToRedis(data, batch)
  779. }
  780. return dataArr, endtime
  781. }
  782. // 处理单个线索
  783. func processLead(v map[string]interface{}, sourceMap map[string]map[string]interface{}, nowTime string, committeeTime int64, data map[string]interface{}) (map[string]interface{}, int64) {
  784. sources := common.ObjToString(v["source"])
  785. // 更新委员会时间
  786. if gconv.Int64(v["createtime"]) > committeeTime {
  787. committeeTime = gconv.Int64(v["createtime"])
  788. }
  789. sourceData, exist := sourceMap[sources]
  790. if !exist {
  791. return nil, committeeTime
  792. }
  793. phone := common.ObjToString(v["phone"])
  794. if IsInternal(phone) {
  795. return nil, committeeTime
  796. }
  797. // 获取用户信息
  798. userData := getUserData(v)
  799. if userData == nil || isUserInBlackList(userData) {
  800. return nil, committeeTime
  801. }
  802. key := fmt.Sprintf("%s_%s_%s", sourceMap[sources], phone, common.ObjToString(v["interest"]))
  803. if _, exists := data[key]; exists {
  804. return nil, committeeTime
  805. }
  806. data[key] = true
  807. return map[string]interface{}{
  808. "createTime": nowTime,
  809. "createtime": v["createtime"],
  810. "username": common.ObjToString(v["name"]),
  811. "company": common.ObjToString(v["company"]),
  812. "phone": phone,
  813. "source": gconv.String(sourceData["name"]),
  814. "belongTo": "咨询组/市场组", // 根据需要修改
  815. "interest": common.ObjToString(v["interest"]),
  816. "data_requirement": common.ObjToString(v["data_requirement"]),
  817. "branch": v["branch"],
  818. "job": v["position"],
  819. "email": common.ObjToString(v["mail"]),
  820. "appointEmail": gconv.String(sourceData["appointEmail"]),
  821. }, committeeTime
  822. }
  823. // 获取用户数据
  824. func getUserData(v map[string]interface{}) map[string]interface{} {
  825. userid := common.ObjToString(v["userid"])
  826. userMapping := &map[string]interface{}{}
  827. if !mongodb.IsObjectIdHex(userid) {
  828. userMapping = TiDb.FindOne("dwd_f_userbase_id_mapping", map[string]interface{}{"position_id": userid}, "", "")
  829. } else {
  830. userMapping = TiDb.FindOne("dwd_f_userbase_id_mapping", map[string]interface{}{"userid": userid}, "", "")
  831. }
  832. if userMapping != nil && len(*userMapping) > 0 {
  833. return *userMapping
  834. }
  835. return nil
  836. }
  837. // 判断用户是否在黑名单
  838. func isUserInBlackList(userData map[string]interface{}) bool {
  839. bt := common.ObjToString(userData["belong_to"])
  840. return strings.HasPrefix(bt, "03") || bt == "0102"
  841. }
  842. // 判断是否是安博会线索
  843. func isABHLead(lead map[string]interface{}) bool {
  844. s_sourceid := common.ObjToString(lead["s_sourceid"])
  845. return s_sourceid == db.Sourceid
  846. }
  847. // 导出到 Excel
  848. func exportToExcel(dataArr []map[string]interface{}, title, batch string) {
  849. if len(dataArr) == 0 {
  850. return
  851. }
  852. bigArr := map[string][]map[string]interface{}{}
  853. for _, v := range dataArr {
  854. appointEmail := gconv.String(v["appointEmail"])
  855. if appointEmail == "" {
  856. appointEmail, _ = EmailSelect(batch)
  857. }
  858. bigArr[appointEmail] = append(bigArr[appointEmail], v)
  859. }
  860. for email, arr := range bigArr {
  861. data := FindBatch(batch)
  862. xlsxArr := []string{"姓名", "联系方式", "职位", "部门", "邮箱", "公司名称", "咨询需求", "销售线索来源", "具体来源", "留资时间"}
  863. fileName, detailName := fmt.Sprintf("%s %s-%s", title, time.Now().Format(date.Date_Short_Layout), data), "今日新增销售线索,请查收附件,及时跟进。"
  864. xf := xlsx.NewFile()
  865. style := xlsx.NewStyle()
  866. style.Font.Size = 12
  867. style.Font.Bold = true
  868. style.Alignment.Vertical = "center"
  869. style.Alignment.Horizontal = "center"
  870. sh, _ := xf.AddSheet("线索数据")
  871. row1 := sh.AddRow()
  872. for _, x := range xlsxArr {
  873. cell := row1.AddCell()
  874. cell.SetString(x)
  875. cell.SetStyle(style)
  876. }
  877. for _, v := range arr {
  878. row := sh.AddRow()
  879. row.AddCell().SetString(common.ObjToString(v["username"]))
  880. row.AddCell().SetString(common.ObjToString(v["phone"]))
  881. row.AddCell().SetString(common.ObjToString(v["job"]))
  882. row.AddCell().SetString(common.ObjToString(v["branch"]))
  883. row.AddCell().SetString(common.ObjToString(v["email"]))
  884. row.AddCell().SetString(common.ObjToString(v["company"]))
  885. row.AddCell().SetString(common.ObjToString(v["data_requirement"]))
  886. row.AddCell().SetString(common.ObjToString(v["source"]))
  887. row.AddCell().SetString(common.ObjToString(v["interest"]))
  888. row.AddCell().SetString(gconv.Time(gconv.Int64(v["createtime"])).Format(date.Date_Full_Layout))
  889. }
  890. dir := fmt.Sprintf("./xlsx/%s/%s.xlsx", batch, fileName)
  891. if err := xf.Save(dir); err != nil {
  892. log.Println("xls error", err, dir)
  893. return
  894. }
  895. sendEmail(fileName, detailName, dir, email)
  896. }
  897. }
  898. // 发送邮件
  899. func sendEmail(fileName, detailName, dir, email string) {
  900. gmail := &mail.GmailAuth{
  901. SmtpHost: db.Mail.SmtpHost,
  902. SmtpPort: db.Mail.SmtpPort,
  903. User: db.Mail.User,
  904. Pwd: db.Mail.Pwd,
  905. }
  906. if status := mail.GSendMail_q("剑鱼标讯", email, "", "", fileName, detailName, dir, fileName+".xlsx", gmail); status {
  907. log.Println("send mail success", fileName, email)
  908. }
  909. }
  910. // 保存数据到 Redis
  911. func saveDataToRedis(data map[string]interface{}, batch string) {
  912. keyContent := fmt.Sprintf("data_%s_%s", time.Now().Format("2006-01-02"), batch)
  913. redis.Put("newother", keyContent, data, 86400)
  914. }
  915. // 邮箱选择处理
  916. func EmailSelect(batch string) (string, string) {
  917. name := ""
  918. minemail := ""
  919. bigData := TiDb.SelectBySql("select * from dwd_f_crm_clue_big_autodraw_record where type =? ", batch)
  920. if bigData != nil && len(*bigData) > 0 {
  921. mincount := common.IntAll((*bigData)[0]["count"])
  922. for _, vv := range *bigData {
  923. vcount := common.IntAll(vv["count"])
  924. vemail := common.ObjToString(vv["email"])
  925. vName := common.ObjToString(vv["name"])
  926. if vcount <= mincount {
  927. mincount = vcount
  928. minemail = vemail
  929. name = vName
  930. }
  931. }
  932. }
  933. TiDb.UpdateOrDeleteBySql(`update dwd_f_crm_clue_big_autodraw_record set count = count + 1 where name = ? and type=?`, name, batch)
  934. return minemail, name
  935. }