jobutil.go 42 KB

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