jobutil.go 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086
  1. package main
  2. import (
  3. "app.yhyue.com/moapp/jybase/redis"
  4. "fmt"
  5. "log"
  6. "strings"
  7. "time"
  8. "github.com/gogf/gf/v2/util/gconv"
  9. "app.yhyue.com/moapp/jybase/common"
  10. "app.yhyue.com/moapp/jybase/date"
  11. "app.yhyue.com/moapp/jybase/mongodb"
  12. )
  13. // 电销工单生成
  14. func rderAcceptance() {
  15. sql := fmt.Sprintf(`select * from order_acceptance where is_clue=2 and is_delete=1 order by propose_time `)
  16. data := WorkOrder.SelectBySql(sql)
  17. if data != nil && len(*data) > 0 {
  18. for _, v := range *data {
  19. acceptance_no := gconv.String(v["acceptance_no"])
  20. childrenArr := WorkOrder.Find("order_acceptance_children", map[string]interface{}{
  21. "acceptance_no": acceptance_no,
  22. }, "", "", -1, -1)
  23. if childrenArr != nil && len(*childrenArr) > 0 {
  24. company := ""
  25. phone := ""
  26. demand := ""
  27. name := ""
  28. product := ""
  29. for _, v1 := range *childrenArr {
  30. if gconv.String(v1["field_name"]) == "公司名称" {
  31. company = gconv.String(v1["field_value"])
  32. }
  33. if gconv.String(v1["field_name"]) == "联系方式num" {
  34. phone = gconv.String(v1["field_value"])
  35. }
  36. if gconv.String(v1["field_name"]) == "客户姓名" {
  37. name = gconv.String(v1["field_value"])
  38. }
  39. if gconv.String(v1["field_name"]) == "客户需求" {
  40. demand = gconv.String(v1["field_value"])
  41. }
  42. if gconv.String(v1["field_name"]) == "咨询产品" {
  43. product = gconv.String(v1["field_value"])
  44. }
  45. }
  46. if !WorkDataHandle(company, phone, demand, name, product, v) {
  47. log.Println("工单创建失败")
  48. }
  49. }
  50. }
  51. }
  52. }
  53. func WorkDataHandle(company, phone, demand, name, product string, acceptanceData map[string]interface{}) bool {
  54. uId := ""
  55. query := map[string]interface{}{}
  56. contactsData := TiDb.SelectBySql("select * from dwd_f_userbase_contacts where phone = ? and is_delete = 1", phone)
  57. if contactsData != nil && len(*contactsData) > 0 {
  58. if common.ObjToString((*contactsData)[0]["baseinfo_id"]) != "" {
  59. uId = common.ObjToString((*contactsData)[0]["baseinfo_id"])
  60. query["uid"] = uId
  61. }
  62. }
  63. if uId == "" {
  64. log.Println("用户信息不存在")
  65. return false
  66. }
  67. cluename := company
  68. if cluename == "" {
  69. cluename = phone //没有线索名,手机号代替
  70. }
  71. ok, data, saleData := false, map[string]interface{}{}, []map[string]interface{}{}
  72. isGroup, isCommerce := GetCompanyType(cluename)
  73. uCount, _ := TiDb.FindOne("dwd_f_crm_clue_info", map[string]interface{}{"uid": uId}, "", ""), true //查当前线索是否已存在
  74. if uCount != nil && len(*uCount) > 0 {
  75. clueId := gconv.Int64((*uCount)["id"])
  76. positionId := gconv.Int64((*uCount)["position_id"])
  77. if positionId == 0 {
  78. //线索变更
  79. ok, data, saleData = FindPosition(positionId, "", false)
  80. if !ok {
  81. log.Println(positionId, "用户查询失败")
  82. return false
  83. }
  84. UpdateClue(*uCount, saleData, "", "", uId, "5", "169", "新增线索", "主动咨询客服留资客户", company, name, gconv.String(data["name"]), phone, "", "", "", "", "", "", gconv.String(data["seat_number"]), "", gconv.Int64(data["position_id"]), "", "", "", []string{}, "", isGroup, isCommerce, true, demand)
  85. } else {
  86. trailstatus := gconv.String((*uCount)["trailstatus"])
  87. IS_TRANSFER := gconv.Int64((*uCount)["IS_TRANSFER"])
  88. if IS_TRANSFER == 1 {
  89. //客成处理
  90. //客成
  91. //生成客成数据
  92. customerMap := TiDb.FindOne("dwd_f_csm_customer_info", map[string]interface{}{
  93. "clue_id": clueId,
  94. }, "position_id", "")
  95. if customerMap != nil && len(*customerMap) > 0 {
  96. UpdateClue(*uCount, saleData, "", "", uId, "5", "169", "新增线索", "主动咨询客服留资客户", company, name, gconv.String((*uCount)["name"]), phone, "", "", "", "", "", "", gconv.String((*uCount)["seat_number"]), "", gconv.Int64((*uCount)["position_id"]), "", "", "", []string{}, "", isGroup, isCommerce, true, demand)
  97. data = map[string]interface{}{
  98. "type": "kc",
  99. "position_id": (*customerMap)["position_id"],
  100. "name": (*customerMap)["name"],
  101. }
  102. } else {
  103. log.Println("查询不到客成数据", clueId, uId)
  104. return false
  105. }
  106. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  107. "clue_id": clueId,
  108. "position_id": (*customerMap)["position_id"],
  109. "change_type": "加入任务车",
  110. "new_value": "咨询客服转客成",
  111. "createtime": time.Now().Format(date.Date_Full_Layout),
  112. "BCPCID": common.GetRandom(32),
  113. "operator_id": -1,
  114. })
  115. }
  116. if trailstatus == "01" || trailstatus == "03" || trailstatus == "04" {
  117. //变更销售员
  118. ok, data, saleData = FindPosition(positionId, "", false)
  119. if !ok {
  120. log.Println(positionId, "用户查询失败")
  121. return false
  122. }
  123. UpdateClue(*uCount, saleData, "", "", uId, "5", "169", "新增线索", "主动咨询客服留资客户", company, name, gconv.String(data["name"]), phone, "", "", "", "", "", "", gconv.String(data["seat_number"]), "", gconv.Int64(data["position_id"]), "", "", "", []string{}, "", isGroup, isCommerce, true, demand)
  124. } else {
  125. //线索变更
  126. ok, data, saleData = FindPosition(positionId, trailstatus, false)
  127. if !ok {
  128. log.Println(positionId, "用户查询失败")
  129. return false
  130. }
  131. UpdateClue(*uCount, saleData, "", "", uId, "5", "169", "新增线索", "主动咨询客服留资客户", company, name, gconv.String(data["name"]), phone, "", "", "", "", "", "", gconv.String(data["seat_number"]), "", gconv.Int64(data["position_id"]), "", "", "", []string{}, "", isGroup, isCommerce, true, demand)
  132. }
  133. }
  134. } else {
  135. //新增线索
  136. ok, data, _ = FindPosition(0, "", false)
  137. if !ok {
  138. return false
  139. }
  140. SaveClue("", "", uId, "5", "169", "", "", cluename, name, gconv.String(data["name"]), phone, "", "", "", "", "", "", gconv.String(data["seat_number"]), gconv.Int64(data["position_id"]), "", "", "", []string{}, "", isGroup, isCommerce, false, demand)
  141. }
  142. //工单生成
  143. ok1 := AddOrderWork(acceptanceData, data, product, phone, company)
  144. log.Println("工单创建", ok1, gconv.String(acceptanceData["acceptance_no"]))
  145. return true
  146. }
  147. func AddOrderWork(acceptanceData map[string]interface{}, userData map[string]interface{}, product, phone, company string) bool {
  148. nowTime := time.Now().Format(date.Date_Full_Layout)
  149. work_order_no := fmt.Sprintf("GD%s%s", time.Now().Format(date.Date_yyyyMMdd), FindNumber("gd"))
  150. productArr := []string{}
  151. for _, v := range strings.Split(product, ",") {
  152. switch ProductMap[v] {
  153. case "dk":
  154. continue
  155. default:
  156. productArr = append(productArr, v)
  157. }
  158. }
  159. two_type := "dx"
  160. if gconv.String(userData["type"]) == "kc" {
  161. two_type = "kc"
  162. }
  163. personMap := GetPerson(gconv.String(userData["position_id"]))
  164. if personMap == nil || len(personMap) == 0 {
  165. return false
  166. }
  167. orderWorkMap := map[string]interface{}{
  168. "work_order_no": work_order_no,
  169. "acceptance_no": gconv.String(acceptanceData["acceptance_no"]),
  170. "type": strings.Join(productArr, ","),
  171. "status": common.If(gconv.Int64(userData["orderStatus"]) == 0, 2, 1),
  172. "initiator_name": gconv.String(acceptanceData["creator_name"]),
  173. "initiator_position_id": gconv.String(acceptanceData["initiator_position_id"]),
  174. "current_name": userData["name"],
  175. "current_position_id": userData["position_id"],
  176. "is_delete": 1,
  177. "creator_name": gconv.String(acceptanceData["creator_name"]),
  178. "creator_position_id": gconv.String(acceptanceData["creator_position_id"]),
  179. "creator_time": nowTime,
  180. "two_type": two_type,
  181. "department_no": gconv.String(personMap["deptId"]),
  182. "department_name": gconv.String(personMap["deptName"]),
  183. }
  184. ok3 := WorkOrder.Insert("order_work", orderWorkMap)
  185. if ok3 > 0 {
  186. WorkOrder.Update("order_acceptance", map[string]interface{}{
  187. "id": acceptanceData["id"],
  188. }, map[string]interface{}{
  189. "is_clue": 3,
  190. })
  191. //发送邮件
  192. //日志添加
  193. approvalRecordMap := map[string]interface{}{
  194. "work_order_no": work_order_no,
  195. "status": common.If(gconv.Int64(userData["orderStatus"]) == 0, 2, 1),
  196. "handle_name": userData["name"],
  197. "handle_position_id": userData["position_id"],
  198. "handle_dept_id": gconv.String(personMap["deptId"]),
  199. "handle_dept_name": gconv.String(personMap["deptName"]),
  200. "creator_name": gconv.String(acceptanceData["creator_name"]),
  201. "creator_position_id": gconv.String(acceptanceData["initiator_position_id"]),
  202. "is_delete": 1,
  203. "creator_time": nowTime,
  204. }
  205. WorkOrder.Insert("approval_record", approvalRecordMap)
  206. WorkMail(personMap,
  207. strings.Join(productArr, ","),
  208. gconv.Int64(common.If(gconv.Int64(userData["orderStatus"]) == 0, 1, 2)),
  209. gconv.String(personMap["name"]),
  210. gconv.String(acceptanceData["creator_name"]),
  211. nowTime,
  212. gconv.String(acceptanceData["acceptance_no"]),
  213. phone,
  214. company)
  215. return true
  216. }
  217. return false
  218. }
  219. // 本级以及上级管理员查询
  220. func GetPerson(positionId string) map[string]interface{} {
  221. person := map[string]interface{}{}
  222. positionArrMap := Base.SelectBySql(fmt.Sprintf(`select a.phone,b.id,b.ent_id from
  223. base_user a
  224. INNER JOIN base_position b
  225. on b.id=%s and b.user_id=a.id and b.type=1`,
  226. positionId))
  227. if positionArrMap == nil || len(*positionArrMap) == 0 {
  228. return map[string]interface{}{}
  229. }
  230. phone := gconv.String((*positionArrMap)[0]["phone"])
  231. entId := gconv.String((*positionArrMap)[0]["ent_id"])
  232. entUserArrMap := Mysql.SelectBySql(fmt.Sprintf(`SELECT
  233. a.name as name,a.mail as mail,b.dept_id as deptId,a.phone ,c.name as deptName
  234. FROM
  235. entniche_user a
  236. INNER JOIN entniche_department_user b ON a.ent_id =%s
  237. AND a.phone IN %s
  238. and a.id=b.user_id
  239. inner join entniche_department c on b.dept_id=c.id
  240. `, entId, fmt.Sprintf("(%s)", phone)))
  241. //商机管理员
  242. if entUserArrMap == nil || len(*entUserArrMap) == 0 {
  243. return map[string]interface{}{}
  244. }
  245. deptId := gconv.Int64((*entUserArrMap)[0]["deptId"])
  246. person = map[string]interface{}{
  247. "name": gconv.String((*entUserArrMap)[0]["name"]),
  248. "mail": gconv.String((*entUserArrMap)[0]["mail"]),
  249. "phone": gconv.String((*entUserArrMap)[0]["phone"]),
  250. "deptId": gconv.String((*entUserArrMap)[0]["deptId"]),
  251. "deptName": gconv.String((*entUserArrMap)[0]["deptName"]),
  252. }
  253. //本部门管理员查询
  254. depthMap := Mysql.SelectBySql(`SELECT
  255. c.name as name,c.mail as mail
  256. FROM
  257. entniche_department_user a
  258. INNER JOIN entniche_user_role b ON a.dept_id = ?
  259. AND a.user_id = b.user_id
  260. AND b.role_id !=""
  261. INNER JOIN entniche_user c ON a.user_id = c.id`, deptId)
  262. if depthMap != nil && len(*depthMap) > 0 {
  263. person["deptPersonName"] = gconv.String((*depthMap)[0]["name"])
  264. person["deptPersonMail"] = gconv.String((*depthMap)[0]["mail"])
  265. }
  266. //商机管理员查询
  267. superiorDepthMap := Mysql.SelectBySql(`SELECT
  268. c.*
  269. FROM
  270. entniche_department d
  271. INNER JOIN entniche_department_user a ON d.id = ?
  272. AND d.pid = a.dept_id
  273. INNER JOIN entniche_user_role b ON a.user_id = b.user_id
  274. AND b.role_id !=""
  275. INNER JOIN entniche_user c ON a.user_id = c.id`, deptId)
  276. if superiorDepthMap != nil && len(*superiorDepthMap) > 0 {
  277. person["superiorDepthPersonName"] = gconv.String((*superiorDepthMap)[0]["name"])
  278. person["superiorDepthPersonMail"] = gconv.String((*superiorDepthMap)[0]["mail"])
  279. }
  280. return person
  281. }
  282. // 编号查询
  283. func FindNumber(moudle string) string {
  284. today := time.Now().Format("2006-01-02")
  285. yesterday := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
  286. key := fmt.Sprintf("%s_%s", today, moudle)
  287. yesterdayKey := fmt.Sprintf("%s_%s", yesterday, moudle)
  288. if ok, _ := redis.Exists("newother", yesterdayKey); ok {
  289. //删除之前数据
  290. redis.Del("newother", yesterdayKey)
  291. }
  292. count := redis.Incr("newother", key)
  293. log.Println("编号获取", moudle, fmt.Sprintf("%04d", count))
  294. return fmt.Sprintf("%04d", count)
  295. }
  296. // 人员查询
  297. func FindPosition(positionId int64, trailstatus string, full bool) (bool, map[string]interface{}, []map[string]interface{}) {
  298. allData := []map[string]interface{}{}
  299. //查询是否满了
  300. if positionId != 0 {
  301. if FindUpperLimit(gconv.String(positionId), "", false) {
  302. full = true
  303. }
  304. }
  305. //查询两个部门高级管理员
  306. //查询两个部门所有人员标识
  307. //电销三部
  308. userData1 := TiDb.SelectBySql(`SELECT
  309. a.position_id,
  310. a.name,
  311. b.seat_number
  312. FROM
  313. dwd_d_crm_department_level_succbi a
  314. INNER JOIN dwd_f_crm_personnel_management b ON a.resign = 0
  315. AND a.ent_id = 25917
  316. AND a.dept_name LIKE "%电销部%"
  317. AND a.position_id = b.position_id`)
  318. userData3 := TiDb.SelectBySql(`SELECT
  319. a.position_id,
  320. a.name,
  321. b.seat_number
  322. FROM
  323. dwd_d_crm_department_level_succbi a
  324. INNER JOIN dwd_f_crm_personnel_management b ON a.resign = 0
  325. AND a.ent_id = 25917
  326. AND a.resign = 0
  327. AND a.dept_name LIKE "%销售三部"
  328. AND a.position_id = b.position_id`)
  329. if userData3 == nil || len(*userData3) == 0 || userData1 == nil || len(*userData1) == 0 {
  330. return false, map[string]interface{}{}, allData
  331. }
  332. //一部管理员信息
  333. administrators1 := map[string]interface{}{}
  334. //三部管理员信息
  335. administrators3 := map[string]interface{}{}
  336. //返回当前人信息
  337. administrators := map[string]interface{}{}
  338. //电销一部
  339. positionIdArr1 := []string{}
  340. positionIdArr3 := []string{}
  341. proportion1 := float64(0)
  342. proportion3 := float64(0)
  343. for _, v := range *userData3 {
  344. v["type"] = 3
  345. personName := gconv.String(v["name"])
  346. id := gconv.Int64(v["position_id"])
  347. if id == positionId && !full {
  348. if personName == "孙鹏" {
  349. v["orderStatus"] = 2
  350. }
  351. administrators = v
  352. }
  353. if personName == "孙鹏" {
  354. v["orderStatus"] = 2
  355. administrators3 = v
  356. proportion3 += 0.5
  357. } else {
  358. proportion3 += 1
  359. }
  360. positionIdArr3 = append(positionIdArr3, gconv.String(id))
  361. allData = append(allData, v)
  362. }
  363. for _, v := range *userData1 {
  364. v["type"] = 1
  365. personName := gconv.String(v["name"])
  366. id := gconv.Int64(v["position_id"])
  367. if id == positionId && !full {
  368. if personName == "沈炳毅" {
  369. v["orderStatus"] = 2
  370. }
  371. administrators = v
  372. }
  373. if personName == "沈炳毅" {
  374. v["orderStatus"] = 2
  375. administrators1 = v
  376. proportion1 += 0.5
  377. } else {
  378. proportion1 += 1
  379. }
  380. positionIdArr1 = append(positionIdArr1, gconv.String(id))
  381. allData = append(allData, v)
  382. }
  383. if positionId != 0 {
  384. if administrators == nil || len(administrators) == 0 {
  385. return false, map[string]interface{}{}, allData
  386. }
  387. positiontype := gconv.Int64(administrators["type"])
  388. if full {
  389. switch positiontype {
  390. case 1:
  391. if trailstatus == "01" || trailstatus == "03" || trailstatus == "04" {
  392. //找他上级
  393. positionId1 := gconv.String(administrators1["position_id"])
  394. administrators = administrators1
  395. if FindUpperLimit(positionId1, "", false) {
  396. return false, map[string]interface{}{}, allData
  397. }
  398. }
  399. case 3:
  400. if trailstatus == "01" || trailstatus == "03" || trailstatus == "04" {
  401. //找他上级
  402. positionId1 := gconv.String(administrators3["position_id"])
  403. administrators = administrators3
  404. if FindUpperLimit(positionId1, "", false) {
  405. return false, map[string]interface{}{}, allData
  406. }
  407. }
  408. }
  409. } else {
  410. return true, administrators, allData
  411. }
  412. }
  413. //按照比例分配选择一部还是三部
  414. //一部查询
  415. deptCount1 := CalculateProportion(strings.Join(positionIdArr1, ","))
  416. //三部查询
  417. deptCount3 := CalculateProportion(strings.Join(positionIdArr3, ","))
  418. if deptCount1 == 0 {
  419. return true, administrators1, allData
  420. }
  421. if deptCount3 == 0 {
  422. return true, administrators3, allData
  423. }
  424. if deptCount1/deptCount3 > proportion1/proportion3 {
  425. return true, administrators3, allData
  426. } else {
  427. return true, administrators1, allData
  428. }
  429. log.Println("电销信息获取失败", positionId)
  430. return false, map[string]interface{}{}, allData
  431. }
  432. func CalculateProportion(positionIsStr string) float64 {
  433. createtime := time.Time{}
  434. now := time.Now()
  435. weekday := int(now.Weekday())
  436. if weekday == 0 { // 如果是周日,则将其视为本周的最后一天
  437. weekday = 7
  438. }
  439. switch cfg.LoopType {
  440. case 1: //周
  441. createtime = now.AddDate(0, 0, -weekday+1)
  442. case 2: //月
  443. createtime = time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.Local)
  444. }
  445. count := float64(0)
  446. sql := `SELECT
  447. sum(1) as count
  448. FROM
  449. order_work
  450. WHERE
  451. FIND_IN_SET(current_position_id ,?)
  452. AND is_delete=1
  453. and creator_time>?`
  454. data := WorkOrder.SelectBySql(sql, positionIsStr, createtime.Format("2006-01-02"))
  455. if data != nil && len(*data) > 0 {
  456. count = gconv.Float64((*data)[0]["count"])
  457. }
  458. return count
  459. }
  460. // 未支付订单 30分钟一次
  461. func orders() {
  462. //一个小时未支付进入线索 A
  463. log.Println("未支付订单定时任务开始")
  464. lastOrderId := cfg.LastOrderId
  465. selectTimeStart := time.Unix(time.Now().Unix()-7200, 0).Format(date.Date_Full_Layout)
  466. selectTimeEnd := time.Unix(time.Now().Unix()-3600, 0).Format(date.Date_Full_Layout)
  467. sql := fmt.Sprintf(`select * from dataexport_order where create_time <= "%s" and create_time >= "%s" and id > %s`, selectTimeEnd, selectTimeStart, fmt.Sprint(lastOrderId))
  468. data := Mysql.SelectBySql(sql)
  469. if data != nil && *data != nil && len(*data) > 0 {
  470. for _, v := range *data {
  471. order_status := common.IntAll(v["order_status"])
  472. is_backstage_order := common.IntAll(v["is_backstage_order"])
  473. product_type_str1 := `"大会员","VIP订阅","数据流量包","历史数据"`
  474. product_type := common.ObjToString(v["product_type"])
  475. if order_status == 0 && is_backstage_order == 0 && strings.Contains(product_type_str1, product_type) {
  476. ok1, ok2 := FormatData(v, "orders")
  477. if !ok1 {
  478. common.WriteSysConfig(&cfg)
  479. log.Println("线索卡点", "orders", v, selectTimeEnd, selectTimeStart)
  480. break
  481. } else {
  482. if !ok2 {
  483. log.Println("用户分配已达上限", "orders", v, selectTimeEnd, selectTimeStart)
  484. common.WriteSysConfig(&cfg)
  485. break
  486. }
  487. }
  488. }
  489. cfg.LastOrderId = common.IntAll(v["id"])
  490. }
  491. }
  492. common.WriteSysConfig(&cfg)
  493. log.Println("未支付订单定时任务结束")
  494. }
  495. func readClue() {
  496. log.Println("读表进线索定时任务开始")
  497. lastReadClueTime := cfg.LastReadClueTime
  498. sql := fmt.Sprintf(`select * from clue_info where updatetime > "%s" order by updatetime asc`, fmt.Sprint(lastReadClueTime))
  499. data := TiDb.SelectBySql(sql)
  500. if data != nil && *data != nil && len(*data) > 0 {
  501. for _, v := range *data {
  502. ok1, ok2 := FormatData(v, "readClue")
  503. if !ok1 {
  504. common.WriteSysConfig(&cfg)
  505. log.Println("线索卡点", "readClue", v, lastReadClueTime)
  506. break
  507. } else {
  508. if !ok2 {
  509. log.Println("用户分配已达上限", "readClue", v, lastReadClueTime)
  510. common.WriteSysConfig(&cfg)
  511. break
  512. }
  513. }
  514. cfg.LastReadClueTime = common.ObjToString(v["updatetime"])
  515. }
  516. }
  517. common.WriteSysConfig(&cfg)
  518. log.Println("读表进线索定时任务结束")
  519. }
  520. // 新注册用户 5分钟一次
  521. func users() {
  522. //判断节假日
  523. runOk := getRunOk()
  524. if !runOk {
  525. log.Println("不是工作日,任务暂停")
  526. return
  527. }
  528. //新用户注册后5分钟内进入线索 C
  529. log.Println("新注册用户定时任务开始")
  530. selectTimeEnd := cfg.LastUserId
  531. sql := fmt.Sprintf(`select * from dwd_f_userbase_baseinfo where createtime > "%s" and source = "0101" and status != 2`, selectTimeEnd)
  532. data := TiDb.SelectBySql(sql)
  533. if data != nil && *data != nil && len(*data) > 0 {
  534. for k, v := range *data {
  535. createtime := common.ObjToString(v["createtime"])
  536. ok1, ok2 := FormatData(v, "users")
  537. if !ok1 {
  538. common.WriteSysConfig(&cfg)
  539. log.Println("线索卡点", "users", v, selectTimeEnd)
  540. break
  541. } else {
  542. if !ok2 {
  543. log.Println("用户分配已达上限", "users", v, selectTimeEnd)
  544. common.WriteSysConfig(&cfg)
  545. break
  546. }
  547. }
  548. if k == len(*data)-1 {
  549. cfg.LastUserId = createtime
  550. }
  551. }
  552. }
  553. common.WriteSysConfig(&cfg)
  554. log.Println("新注册用户定时任务结束")
  555. }
  556. // 留资 5分钟一次
  557. func saleLeads() {
  558. //判断节假日
  559. runOk := getRunOk()
  560. if !runOk {
  561. log.Println("不是工作日,任务暂停")
  562. return
  563. }
  564. //留资后5分钟内进入线索
  565. //分为免费留资和付费留资 付费B 免费C
  566. log.Println("用户留资定时任务开始")
  567. session := Mgo.GetMgoConn()
  568. lastId := cfg.LastId
  569. defer func() {
  570. Mgo.DestoryMongoConn(session)
  571. }()
  572. query := map[string]interface{}{}
  573. if lastId != "" {
  574. query["_id"] = map[string]interface{}{"$gt": mongodb.StringTOBsonId(lastId)}
  575. }
  576. log.Println("query :", query)
  577. iter := session.DB(cfg.Mgo.DbName).C("saleLeads").Find(&query).Sort("_id").Iter()
  578. thisData := map[string]interface{}{}
  579. for {
  580. if !iter.Next(&thisData) {
  581. break
  582. }
  583. sourceCode := common.ObjToString(thisData["source"])
  584. if sourceCode == "" {
  585. log.Println("留资没有source", thisData)
  586. continue
  587. }
  588. //
  589. filterArr := []string{"-pc", "-app", "-wx", "-h5"}
  590. sourceMap := map[string]string{}
  591. saleSource := TiDb.SelectBySql(`SELECT source,name FROM d_saleleads_code WHERE (department LIKE '%大客户%' or department LIKE '%市场组%') AND is_delete = 1`)
  592. if saleSource != nil && len(*saleSource) > 0 {
  593. for _, v := range *saleSource {
  594. source := common.ObjToString(v["source"])
  595. name := common.ObjToString(v["name"])
  596. for _, s := range filterArr {
  597. name = strings.ReplaceAll(name, s, "")
  598. }
  599. sourceMap[source] = name
  600. }
  601. }
  602. if sourceMap[sourceCode] != "" {
  603. continue
  604. }
  605. ok1, ok2 := FormatData(thisData, "saleLeads")
  606. if !ok1 {
  607. common.WriteSysConfig(&cfg)
  608. log.Println("线索卡点", "saleLeads", thisData, lastId)
  609. break
  610. } else {
  611. if !ok2 {
  612. log.Println("用户分配已达上限", "saleLeads", thisData, lastId)
  613. common.WriteSysConfig(&cfg)
  614. break
  615. }
  616. }
  617. cfg.LastId = mongodb.BsonIdToSId(thisData["_id"])
  618. }
  619. common.WriteSysConfig(&cfg)
  620. log.Println("用户留资定时任务结束")
  621. }
  622. func userbase() {
  623. log.Println("userbase定时任务开始")
  624. selectTimeEnd := time.Unix(time.Now().Unix()-1800, 0).Format("2006-01-02 15:04:05")
  625. sql := fmt.Sprintf(`select * from dwd_f_userbase_baseinfo where updatetime > "%s" and source != "0105" and source != "0104" and source != "0103" and source != "0102"`, selectTimeEnd)
  626. //sql := fmt.Sprintf(`select * from dwd_f_userbase_baseinfo where id='11927183'`)
  627. data := TiDb.SelectBySql(sql)
  628. if data != nil && *data != nil && len(*data) > 0 {
  629. for _, v := range *data {
  630. phone := common.ObjToString(v["phone"])
  631. uId := common.ObjToString(v["uid"])
  632. userId := common.ObjToString(v["userid"])
  633. registedate := common.ObjToString(v["l_registedate"])
  634. name := common.ObjToString(v["name"])
  635. nowTime := time.Now().Format(date.Date_Full_Layout)
  636. source := common.ObjToString(v["source"])
  637. if phone != "" {
  638. contactsData := TiDb.SelectBySql("select * from dwd_f_userbase_contacts where phone = ? and is_delete = 1", phone)
  639. if contactsData == nil || len(*contactsData) == 0 {
  640. contactsData2 := TiDb.SelectBySql("select * from dwd_f_userbase_contacts where baseinfo_id = ? and is_delete = 1", uId)
  641. if contactsData2 != nil && len(*contactsData2) > 0 {
  642. log.Println("userbase uid不为空 新增通讯录", uId)
  643. TiDb.Insert("dwd_f_userbase_contacts", map[string]interface{}{
  644. "status": 1,
  645. "is_delete": 1,
  646. "createtime": nowTime,
  647. "updatetime": nowTime,
  648. "phone": phone,
  649. "baseinfo_id": uId,
  650. "SOURCE": source,
  651. })
  652. } else {
  653. registedates, _ := time.Parse(date.Date_Full_Layout, registedate)
  654. count := TiDb.CountBySql("select count(1) as count from dwd_f_crm_clue_info where uid = ?", uId)
  655. log.Println("userbase uid 线索数量 ", count)
  656. log.Println("userbase uid 注册时间 ", registedates)
  657. if time.Now().Unix()-registedates.Unix() > int64(cfg.RegTimes)*86400 {
  658. if count == 0 {
  659. // TiDb.Insert("dwd_f_crm_open_sea", map[string]interface{}{
  660. // "clue_id": clueId,
  661. // "comeintime": nowTime,
  662. // "comeinsource": 2,
  663. // })
  664. clueId := TiDb.Insert("dwd_f_crm_clue_info", map[string]interface{}{
  665. "userid": userId,
  666. "uid": uId,
  667. "is_assign": 0,
  668. "comeintime": nowTime,
  669. "createtime": nowTime,
  670. "updatetime": nowTime,
  671. "cluename": phone,
  672. "top_cluetype": "532",
  673. "sub_cluetype": "475",
  674. "trailstatus": "01",
  675. "name": name,
  676. "phone": phone,
  677. "comeintime_open": nowTime,
  678. "comeinsource_open": 1,
  679. "FREEZE_TIME": nowTime,
  680. })
  681. if clueId > 0 {
  682. TiDb.Insert("dwd_f_userbase_contacts", map[string]interface{}{
  683. "status": 1,
  684. "is_delete": 1,
  685. "createtime": nowTime,
  686. "updatetime": nowTime,
  687. "phone": phone,
  688. "baseinfo_id": uId,
  689. "SOURCE": source,
  690. })
  691. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  692. "clue_id": clueId,
  693. "position_id": -1,
  694. "change_type": "创建线索",
  695. "new_value": "系统自动创建",
  696. "createtime": nowTime,
  697. "BCPCID": common.GetRandom(32),
  698. "operator_id": -1,
  699. })
  700. }
  701. } else {
  702. TiDb.Insert("dwd_f_userbase_contacts", map[string]interface{}{
  703. "status": 1,
  704. "is_delete": 1,
  705. "createtime": nowTime,
  706. "updatetime": nowTime,
  707. "phone": phone,
  708. "baseinfo_id": uId,
  709. "SOURCE": source,
  710. })
  711. }
  712. } else {
  713. if count == 0 {
  714. ok1, ok2 := FormatData(v, "users")
  715. if !ok1 {
  716. common.WriteSysConfig(&cfg)
  717. log.Println("线索卡点", "userbase uid", v, uId)
  718. break
  719. } else {
  720. if !ok2 {
  721. log.Println("用户分配已达上限", "userbase uid", v, uId)
  722. common.WriteSysConfig(&cfg)
  723. break
  724. }
  725. }
  726. } else {
  727. TiDb.Insert("dwd_f_userbase_contacts", map[string]interface{}{
  728. "status": 1,
  729. "is_delete": 1,
  730. "createtime": nowTime,
  731. "updatetime": nowTime,
  732. "phone": phone,
  733. "baseinfo_id": uId,
  734. "SOURCE": source,
  735. })
  736. }
  737. }
  738. }
  739. }
  740. }
  741. }
  742. }
  743. log.Println("userbase定时任务结束")
  744. }
  745. func getRunOk() bool {
  746. currentTime, runOk := time.Now(), false
  747. if currentTime.Weekday() == time.Sunday {
  748. isok := false
  749. for k, v := range DateMap {
  750. if currentTime.Format(date.Date_Short_Layout) == k && v == 2 {
  751. isok = true
  752. }
  753. }
  754. if isok {
  755. runOk = true
  756. }
  757. } else {
  758. isok := true
  759. for k, v := range DateMap {
  760. if currentTime.Format(date.Date_Short_Layout) == k && v == 1 {
  761. isok = false
  762. }
  763. }
  764. if isok {
  765. runOk = true
  766. }
  767. }
  768. return runOk
  769. }
  770. func getAreaCode(userId string) (code string) {
  771. followData := Base.Find("follow_project_monitor", map[string]interface{}{"s_userid": userId}, "", "", -1, -1)
  772. sidArr := []string{}
  773. if followData != nil && len(*followData) > 0 {
  774. for _, v := range *followData {
  775. infoId := common.ObjToString(v["s_id"])
  776. sidArr = append(sidArr, infoId)
  777. }
  778. }
  779. if len(sidArr) > 0 {
  780. query := `{"query": {"bool": {"must": [{"terms": {"_id": ["%s"]}}],"must_not": [],"should": []}}}`
  781. query = fmt.Sprintf(query, strings.Join(sidArr, `","`))
  782. biddingData := Es.Get("bidding", "bidding", query)
  783. if biddingData != nil && len(*biddingData) > 0 {
  784. codeMap := map[string]string{}
  785. codeArr := []string{}
  786. for _, v := range *biddingData {
  787. area := common.ObjToString(v["area"])
  788. address := common.ObjToString(v["city"])
  789. if address == "" {
  790. address = area
  791. }
  792. codeMap[address] = AreaCode[address]
  793. }
  794. if len(codeMap) > 0 {
  795. for _, v := range codeMap {
  796. codeArr = append(codeArr, v)
  797. }
  798. }
  799. if len(codeArr) > 0 {
  800. code = strings.Join(codeArr, ",")
  801. }
  802. }
  803. }
  804. log.Println("code ", code)
  805. return
  806. }
  807. func getClueType(item string, data map[string]interface{}, sourceCode string, sourceId int64) (pcode, code, level, topname, subname string) {
  808. if item == "orders" {
  809. productType := common.ObjToString(data["product_type"])
  810. pcode = "1"
  811. level = "A"
  812. topname = "提交订单未支付"
  813. if productType == "VIP订阅" {
  814. code = "6"
  815. subname = "超级订阅"
  816. } else if productType == "大会员" {
  817. code = "7"
  818. subname = "大会员"
  819. } else if productType == "数据流量包" {
  820. code = "8"
  821. subname = "数据流量包"
  822. } else if productType == "历史数据" {
  823. code = "9"
  824. subname = "数据自助导出"
  825. }
  826. } else if item == "users" {
  827. pcode = "4"
  828. code = "154"
  829. level = "C"
  830. topname = "新增注册"
  831. subname = "新增注册用户"
  832. } else if item == "message" {
  833. pcode = "532"
  834. code = "477"
  835. level = "B"
  836. topname = "其他"
  837. subname = "机器人客服主动咨询"
  838. } else if item == "readClue" {
  839. level = "A"
  840. topname = "超级订阅临期用户"
  841. pcode = "614"
  842. if sourceId == 1 {
  843. code = "615"
  844. subname = "60天后到期"
  845. } else if sourceId == 2 {
  846. code = "616"
  847. subname = "45天后到期"
  848. } else if sourceId == 3 {
  849. code = "617"
  850. subname = "15天后到期"
  851. } else {
  852. code = "618"
  853. subname = "7天后到期"
  854. }
  855. } else {
  856. if sourceCode != "" {
  857. codeData := TiDb.FindOne("dwd_d_crm_cluetype_code", map[string]interface{}{"source": sourceCode}, "", "")
  858. if codeData != nil && len(*codeData) > 0 {
  859. pcode = common.ObjToString((*codeData)["pcode"])
  860. code = common.ObjToString((*codeData)["code"])
  861. level = common.ObjToString((*codeData)["clue_level"])
  862. subname = common.ObjToString((*codeData)["name"])
  863. pcodeData := TiDb.FindOne("dwd_d_crm_cluetype_code", map[string]interface{}{"code": pcode}, "", "")
  864. if pcodeData != nil && len(*pcodeData) > 0 {
  865. topname = common.ObjToString((*pcodeData)["name"])
  866. }
  867. }
  868. }
  869. }
  870. return
  871. }
  872. // 获取自动分配的人
  873. func autoDraw(mode, cluename, phone string, isGroup, isCommerce int) (positionId int64, seatNumber, saleName string, saleData []map[string]interface{}, isOk, isFreeze bool, noticePositionId int64) {
  874. isOk = false
  875. isFreeze = false
  876. if TiDb.Count("dwd_f_crm_clue_info", map[string]interface{}{"phone": phone, "is_assign": 1}) == 0 { //线索没销售进入,有销售走分配次数最少的逻辑
  877. if isGroup == 0 && isCommerce == 1 && cluename != "" { //非集团在工商库线索名不为空
  878. cdata := TiDb.FindOne("dwd_f_crm_clue_info", map[string]interface{}{"cluename": cluename, "is_assign": 1}, "", "")
  879. if cdata != nil && len(*cdata) > 0 { //找到了公司有人在跟进
  880. isOk = true
  881. positionId = common.Int64All((*cdata)["position_id"])
  882. noticePositionId = positionId
  883. seatNumber = common.ObjToString((*cdata)["seatNumber"])
  884. log.Println("positionId seatNumber ", positionId, seatNumber)
  885. if positionId > 0 {
  886. pdata := TiDb.SelectBySql(`select * from dwd_f_crm_personnel_management where seat_number is not null and seat_number != ""`)
  887. if pdata != nil {
  888. saleData = *pdata
  889. for _, v := range *pdata {
  890. resign := common.IntAll(v["resign"])
  891. if positionId == common.Int64All(v["position_id"]) {
  892. if resign == 1 { //离职分配,找到的销售离职了,分给组员,没离职就给他
  893. sdata := TiDb.SelectBySql(`SELECT b.name,b.position_id,b.seat_number from dwd_d_crm_department_level_succbi a INNER JOIN dwd_f_crm_personnel_management b on a.position_id = b.position_id where a.bi_pcode = (SELECT bi_pcode from dwd_d_crm_department_level_succbi where position_id = ?) and b.role_id = 3`, positionId)
  894. if sdata != nil && len(*sdata) > 0 {
  895. for _, m := range *sdata {
  896. if !FindUpperLimit(gconv.String(positionId), mode, true) {
  897. positionId = common.Int64All(m["position_id"])
  898. noticePositionId = positionId
  899. seatNumber = common.ObjToString(m["seat_number"])
  900. saleName = common.ObjToString(m["name"])
  901. return
  902. }
  903. }
  904. isFreeze = true
  905. positionId = 0
  906. seatNumber = ""
  907. saleName = ""
  908. return
  909. }
  910. } else {
  911. if FindUpperLimit(gconv.String(positionId), mode, true) {
  912. isFreeze = true
  913. }
  914. saleName = common.ObjToString(v["name"])
  915. }
  916. }
  917. }
  918. }
  919. if isFreeze {
  920. positionId = 0
  921. seatNumber = ""
  922. saleName = ""
  923. }
  924. return
  925. }
  926. }
  927. }
  928. }
  929. query := `select * from dwd_f_crm_personnel_management where assign_type = 1 and`
  930. if mode == "A" {
  931. query += ` assign_level like "%A%"`
  932. } else if mode == "B" {
  933. query += ` assign_level like "%B%"`
  934. } else {
  935. query += ` assign_level like "%C%"`
  936. }
  937. data := TiDb.SelectBySql(query)
  938. if data != nil && len(*data) > 0 {
  939. saleData = *data
  940. sql := "select * from dwd_f_crm_clue_autodraw_record where clue_level = ?"
  941. countData := TiDb.SelectBySql(sql, mode)
  942. if countData != nil && len(*countData) > 0 {
  943. for _, v := range *data {
  944. isOk := false //判断是否有新员工
  945. for _, vv := range *countData {
  946. if common.Int64All(v["position_id"]) == common.Int64All(vv["position_id"]) {
  947. if common.IntAll(v["resign"]) == 0 {
  948. vv["status"] = 1
  949. } else {
  950. vv["status"] = 2
  951. }
  952. isOk = true
  953. }
  954. }
  955. if !isOk { //有新员工直接分给新员工
  956. positionId = common.Int64All(v["position_id"])
  957. saleName = common.ObjToString(v["name"])
  958. log.Println("新员工, ", positionId, saleName)
  959. rData := TiDb.FindOne("dwd_f_crm_clue_autodraw_record", map[string]interface{}{"clue_level": mode}, "", "count desc")
  960. TiDb.Insert("dwd_f_crm_clue_autodraw_record", map[string]interface{}{
  961. "position_id": positionId,
  962. "clue_level": mode,
  963. "count": common.Int64All((*rData)["count"]),
  964. })
  965. break
  966. }
  967. }
  968. if positionId == 0 {
  969. res := int64(0)
  970. countres := 0
  971. for _, v := range *countData {
  972. if common.IntAll(v["status"]) == 1 {
  973. if FindUpperLimit(gconv.String(v["position_id"]), mode, false) {
  974. continue
  975. }
  976. if countres == 0 {
  977. res = common.Int64All(v["count"])
  978. positionId = common.Int64All(v["position_id"])
  979. } else {
  980. if common.Int64All(v["count"]) <= res {
  981. res = common.Int64All(v["count"])
  982. positionId = common.Int64All(v["position_id"])
  983. }
  984. }
  985. countres++
  986. }
  987. }
  988. log.Println(444, res)
  989. }
  990. } else {
  991. for _, kv := range *data {
  992. positionId1 := gconv.String(kv["position_id"])
  993. if !FindUpperLimit(positionId1, "", false) {
  994. positionId = common.Int64All(kv["position_id"])
  995. saleName = common.ObjToString(kv["name"])
  996. rData := TiDb.FindOne("dwd_f_crm_clue_autodraw_record", map[string]interface{}{"clue_level": mode}, "", "count desc")
  997. if rData != nil && len(*rData) > 0 {
  998. TiDb.Insert("dwd_f_crm_clue_autodraw_record", map[string]interface{}{
  999. "position_id": positionId,
  1000. "clue_level": mode,
  1001. "count": common.Int64All((*rData)["count"]),
  1002. })
  1003. } else {
  1004. TiDb.Insert("dwd_f_crm_clue_autodraw_record", map[string]interface{}{
  1005. "position_id": positionId,
  1006. "clue_level": mode,
  1007. "count": 0,
  1008. })
  1009. }
  1010. break
  1011. }
  1012. }
  1013. }
  1014. for _, v := range *data {
  1015. if positionId == common.Int64All(v["position_id"]) {
  1016. seatNumber = common.ObjToString(v["seat_number"])
  1017. saleName = common.ObjToString(v["name"])
  1018. }
  1019. }
  1020. }
  1021. return
  1022. }
  1023. func getPositionId(phone string) (positionId int64) {
  1024. userData, ok := Mgo.FindOne("user", map[string]interface{}{"s_phone": phone})
  1025. if ok && userData != nil && len(*userData) > 0 {
  1026. userId := common.Int64All((*userData)["base_user_id"])
  1027. positionData := Base.FindOne("base_position", map[string]interface{}{"type": 1, "ent_id": 25917, "user_id": userId}, "", "") //TODO ent_id
  1028. if positionData != nil && len(*positionData) > 0 {
  1029. positionId = common.Int64All((*positionData)["id"])
  1030. }
  1031. }
  1032. return
  1033. }
  1034. func GetCompanyType(companyName string) (int, int) {
  1035. //是否是集团
  1036. isGroup, isCommerce := 0, 0
  1037. if c := TiDb.CountBySql(`select count(1) from group_company_name where company_name=?`, companyName); c > 0 {
  1038. isGroup = 1
  1039. }
  1040. //是否在工商库
  1041. if c := MgoQyxy.Count("qyxy_std", map[string]interface{}{"company_name": companyName, "company_type": map[string]interface{}{"$ne": "个体工商户"}}); c > 0 {
  1042. isCommerce = 1
  1043. }
  1044. return isGroup, isCommerce
  1045. }
  1046. // 查询是否达上限
  1047. func FindUpperLimit(positionId string, level string, isAdd bool) bool {
  1048. if positionId == "" {
  1049. return false
  1050. }
  1051. isFull := false
  1052. isFull = TiDb.CountBySql(`select count(1) from dwd_f_crm_clue_info where position_id=? and is_assign=1 and trailstatus != '08' `, positionId) >= cfg.AllocationCap
  1053. if isFull && isAdd && level != "" {
  1054. TiDb.UpdateOrDeleteBySql(`update dwd_f_crm_clue_autodraw_record set count = count + 1 where position_id = ? and clue_level = ?`, positionId, level)
  1055. }
  1056. return isFull
  1057. }
  1058. func getSeatNumberPositionId(seatNumber string) (positionId int64) {
  1059. saleData := TiDb.FindOne("dwd_f_crm_personnel_management", map[string]interface{}{"seat_number": seatNumber}, "", "")
  1060. if saleData != nil && len(*saleData) > 0 {
  1061. positionId = common.Int64All((*saleData)["position_id"])
  1062. }
  1063. return
  1064. }