jobutil.go 48 KB

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