jobutil.go 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241
  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", "新增线索", "主动咨询客服留资客户", cluename, 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", "新增线索", "主动咨询客服留资客户", cluename, 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", "新增线索", "主动咨询客服留资客户", cluename, 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", "新增线索", "主动咨询客服留资客户", cluename, 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. cdata := TiDb.SelectBySql(`select position_id,MAX(trail_time) as trail_time,max(last_ring_time) as last_ring_time,seatNumber,count(id) as count from dwd_f_crm_clue_info where cluename=? and is_assign =1 GROUP BY position_id `, cluename)
  954. if cdata != nil && len(*cdata) > 0 { //找到了公司有人在跟进
  955. isOk = true
  956. pdata := TiDb.SelectBySql(`select * from dwd_f_crm_personnel_management where seat_number is not null and seat_number != ""`)
  957. if pdata == nil {
  958. positionId = 0
  959. seatNumber = ""
  960. saleName = ""
  961. return
  962. }
  963. saleData = *pdata
  964. cdataNew := []map[string]interface{}{}
  965. if len(*cdata) > 1 {
  966. //可能有多个人跟进
  967. personMap := map[int64]bool{}
  968. for _, m := range *cdata {
  969. positionid := gconv.Int64(m["position_id"])
  970. for _, v := range *pdata {
  971. resign := common.IntAll(v["resign"])
  972. if positionid == common.Int64All(v["position_id"]) {
  973. if resign == 0 {
  974. if !FindUpperLimit(gconv.String(positionId), mode, true) {
  975. personMap[positionid] = true
  976. m["saleName"] = common.ObjToString(v["name"])
  977. cdataNew = append(cdataNew, m)
  978. }
  979. }
  980. }
  981. }
  982. }
  983. //查询是否都有没有离职
  984. if len(personMap) != 0 && len(cdataNew) > 0 {
  985. layout := "2006-01-02 15:04:05"
  986. //有人没有离职
  987. data := map[string]interface{}{}
  988. trailTime := int64(0)
  989. for _, m := range cdataNew {
  990. currentTime := int64(0)
  991. if gconv.String(m["trail_time"]) == "" {
  992. continue
  993. }
  994. t, _ := time.Parse(layout, gconv.String(m["trail_time"]))
  995. currentTime = t.Unix()
  996. if currentTime > trailTime {
  997. trailTime = currentTime
  998. data = m
  999. }
  1000. }
  1001. if trailTime == 0 {
  1002. //需要查看通话记录
  1003. lastRingTime := int64(0)
  1004. for _, m := range cdataNew {
  1005. currentTime := int64(0)
  1006. if gconv.String(m["last_ring_time"]) == "" {
  1007. continue
  1008. }
  1009. t, _ := time.Parse(layout, gconv.String(m["last_ring_time"]))
  1010. currentTime = t.Unix()
  1011. if currentTime > lastRingTime {
  1012. lastRingTime = currentTime
  1013. data = m
  1014. }
  1015. }
  1016. if lastRingTime != 0 {
  1017. positionId = common.Int64All(data["position_id"])
  1018. noticePositionId = positionId
  1019. seatNumber = common.ObjToString(data["seatNumber"])
  1020. saleName = common.ObjToString(data["saleName"])
  1021. return
  1022. } else {
  1023. count := 0
  1024. for i, v := range cdataNew {
  1025. if i == 0 {
  1026. count = gconv.Int(v["count"])
  1027. data = v
  1028. } else {
  1029. if count < gconv.Int(v["count"]) {
  1030. count = gconv.Int(v["count"])
  1031. data = v
  1032. }
  1033. }
  1034. }
  1035. //
  1036. positionId = common.Int64All(data["position_id"])
  1037. noticePositionId = positionId
  1038. saleName = common.ObjToString(data["saleName"])
  1039. seatNumber = common.ObjToString(data["seatNumber"])
  1040. return
  1041. }
  1042. } else {
  1043. positionId = common.Int64All(data["position_id"])
  1044. noticePositionId = positionId
  1045. seatNumber = common.ObjToString(data["seatNumber"])
  1046. saleName = common.ObjToString(data["saleName"])
  1047. return
  1048. }
  1049. }
  1050. } else {
  1051. //只有一人跟进
  1052. //(1)该销售人员未离职,则继续分配给该销售人员(保持现状);
  1053. //该销售人员已离职,则随机分配
  1054. positionId = common.Int64All((*cdata)[0]["position_id"])
  1055. noticePositionId = positionId
  1056. seatNumber = common.ObjToString((*cdata)[0]["seatNumber"])
  1057. for _, v := range *pdata {
  1058. resign := common.IntAll(v["resign"])
  1059. if positionId == common.Int64All(v["position_id"]) {
  1060. if resign == 0 {
  1061. if FindUpperLimit(gconv.String(positionId), mode, true) {
  1062. isFreeze = true
  1063. positionId = 0
  1064. seatNumber = ""
  1065. saleName = ""
  1066. break
  1067. } else {
  1068. saleName = common.ObjToString(v["name"])
  1069. return
  1070. }
  1071. }
  1072. }
  1073. }
  1074. }
  1075. }
  1076. }
  1077. }
  1078. query := `select * from dwd_f_crm_personnel_management where assign_type = 1 and`
  1079. if mode == "A" {
  1080. query += ` assign_level like "%A%"`
  1081. } else if mode == "B" {
  1082. query += ` assign_level like "%B%"`
  1083. } else {
  1084. query += ` assign_level like "%C%"`
  1085. }
  1086. data := TiDb.SelectBySql(query)
  1087. if data != nil && len(*data) > 0 {
  1088. saleData = *data
  1089. sql := "select * from dwd_f_crm_clue_autodraw_record where clue_level = ?"
  1090. countData := TiDb.SelectBySql(sql, mode)
  1091. if countData != nil && len(*countData) > 0 {
  1092. for _, v := range *data {
  1093. isOk := false //判断是否有新员工
  1094. for _, vv := range *countData {
  1095. if common.Int64All(v["position_id"]) == common.Int64All(vv["position_id"]) {
  1096. if common.IntAll(v["resign"]) == 0 {
  1097. vv["status"] = 1
  1098. } else {
  1099. vv["status"] = 2
  1100. }
  1101. isOk = true
  1102. }
  1103. }
  1104. if !isOk { //有新员工直接分给新员工
  1105. positionId = common.Int64All(v["position_id"])
  1106. saleName = common.ObjToString(v["name"])
  1107. log.Println("新员工, ", positionId, saleName)
  1108. rData := TiDb.FindOne("dwd_f_crm_clue_autodraw_record", map[string]interface{}{"clue_level": mode}, "", "count desc")
  1109. TiDb.Insert("dwd_f_crm_clue_autodraw_record", map[string]interface{}{
  1110. "position_id": positionId,
  1111. "clue_level": mode,
  1112. "count": common.Int64All((*rData)["count"]),
  1113. })
  1114. break
  1115. }
  1116. }
  1117. if positionId == 0 {
  1118. res := int64(0)
  1119. countres := 0
  1120. for _, v := range *countData {
  1121. if common.IntAll(v["status"]) == 1 {
  1122. if FindUpperLimit(gconv.String(v["position_id"]), mode, false) {
  1123. continue
  1124. }
  1125. if countres == 0 {
  1126. res = common.Int64All(v["count"])
  1127. positionId = common.Int64All(v["position_id"])
  1128. } else {
  1129. if common.Int64All(v["count"]) <= res {
  1130. res = common.Int64All(v["count"])
  1131. positionId = common.Int64All(v["position_id"])
  1132. }
  1133. }
  1134. countres++
  1135. }
  1136. }
  1137. log.Println(444, res)
  1138. }
  1139. } else {
  1140. for _, kv := range *data {
  1141. positionId1 := gconv.String(kv["position_id"])
  1142. if !FindUpperLimit(positionId1, "", false) {
  1143. positionId = common.Int64All(kv["position_id"])
  1144. saleName = common.ObjToString(kv["name"])
  1145. rData := TiDb.FindOne("dwd_f_crm_clue_autodraw_record", map[string]interface{}{"clue_level": mode}, "", "count desc")
  1146. if rData != nil && len(*rData) > 0 {
  1147. TiDb.Insert("dwd_f_crm_clue_autodraw_record", map[string]interface{}{
  1148. "position_id": positionId,
  1149. "clue_level": mode,
  1150. "count": common.Int64All((*rData)["count"]),
  1151. })
  1152. } else {
  1153. TiDb.Insert("dwd_f_crm_clue_autodraw_record", map[string]interface{}{
  1154. "position_id": positionId,
  1155. "clue_level": mode,
  1156. "count": 0,
  1157. })
  1158. }
  1159. break
  1160. }
  1161. }
  1162. }
  1163. for _, v := range *data {
  1164. if positionId == common.Int64All(v["position_id"]) {
  1165. seatNumber = common.ObjToString(v["seat_number"])
  1166. saleName = common.ObjToString(v["name"])
  1167. }
  1168. }
  1169. }
  1170. return
  1171. }
  1172. func getPositionId(phone string) (positionId int64) {
  1173. userData, ok := Mgo.FindOne("user", map[string]interface{}{"s_phone": phone})
  1174. if ok && userData != nil && len(*userData) > 0 {
  1175. userId := common.Int64All((*userData)["base_user_id"])
  1176. positionData := Base.FindOne("base_position", map[string]interface{}{"type": 1, "ent_id": 25917, "user_id": userId}, "", "") //TODO ent_id
  1177. if positionData != nil && len(*positionData) > 0 {
  1178. positionId = common.Int64All((*positionData)["id"])
  1179. }
  1180. }
  1181. return
  1182. }
  1183. func GetCompanyType(companyName string) (int, int) {
  1184. //是否是集团
  1185. isGroup, isCommerce := 0, 0
  1186. if c := TiDb.CountBySql(`select count(1) from group_company_name where company_name=?`, companyName); c > 0 {
  1187. isGroup = 1
  1188. }
  1189. //是否在工商库
  1190. if c := MgoQyxy.Count("qyxy_std", map[string]interface{}{"company_name": companyName, "company_type": map[string]interface{}{"$ne": "个体工商户"}}); c > 0 {
  1191. isCommerce = 1
  1192. }
  1193. return isGroup, isCommerce
  1194. }
  1195. // 查询是否达上限
  1196. func FindUpperLimit(positionId string, level string, isAdd bool) bool {
  1197. if positionId == "" {
  1198. return false
  1199. }
  1200. isFull := false
  1201. 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
  1202. if isFull && isAdd && level != "" {
  1203. TiDb.UpdateOrDeleteBySql(`update dwd_f_crm_clue_autodraw_record set count = count + 1 where position_id = ? and clue_level = ?`, positionId, level)
  1204. }
  1205. return isFull
  1206. }
  1207. func getSeatNumberPositionId(seatNumber string) (positionId int64) {
  1208. saleData := TiDb.FindOne("dwd_f_crm_personnel_management", map[string]interface{}{"seat_number": seatNumber}, "", "")
  1209. if saleData != nil && len(*saleData) > 0 {
  1210. positionId = common.Int64All((*saleData)["position_id"])
  1211. }
  1212. return
  1213. }