jobutil.go 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904
  1. package main
  2. import (
  3. "app.yhyue.com/moapp/jybase/mail"
  4. "app.yhyue.com/moapp/jybase/redis"
  5. "fmt"
  6. "github.com/tealeg/xlsx"
  7. "log"
  8. "math"
  9. "strings"
  10. "time"
  11. "github.com/gogf/gf/v2/util/gconv"
  12. "app.yhyue.com/moapp/jybase/common"
  13. "app.yhyue.com/moapp/jybase/date"
  14. "app.yhyue.com/moapp/jybase/mongodb"
  15. )
  16. // 电销工单生成
  17. func rderAcceptance() {
  18. sql := fmt.Sprintf(`select * from order_acceptance where is_clue=2 and is_delete=1 order by propose_time `)
  19. //sql := fmt.Sprintf(`select * from order_acceptance where is_clue=2 and is_delete=1 and id = 333 order by propose_time `)
  20. data := WorkOrder.SelectBySql(sql)
  21. if data != nil && len(*data) > 0 {
  22. for _, v := range *data {
  23. acceptance_no := gconv.String(v["acceptance_no"])
  24. childrenArr := WorkOrder.Find("order_acceptance_children", map[string]interface{}{
  25. "acceptance_no": acceptance_no,
  26. }, "", "", -1, -1)
  27. if childrenArr != nil && len(*childrenArr) > 0 {
  28. company := ""
  29. phone := ""
  30. demand := ""
  31. name := ""
  32. product := ""
  33. for _, v1 := range *childrenArr {
  34. if gconv.String(v1["field_name"]) == "公司名称" {
  35. company = gconv.String(v1["field_value"])
  36. }
  37. if gconv.String(v1["field_name"]) == "联系方式num" {
  38. phone = gconv.String(v1["field_value"])
  39. }
  40. if gconv.String(v1["field_name"]) == "客户姓名" {
  41. name = gconv.String(v1["field_value"])
  42. }
  43. if gconv.String(v1["field_name"]) == "客户需求" {
  44. demand = gconv.String(v1["field_value"])
  45. }
  46. if gconv.String(v1["field_name"]) == "咨询产品" {
  47. product = gconv.String(v1["field_value"])
  48. }
  49. }
  50. if !WorkDataHandle(company, phone, demand, name, product, v) {
  51. log.Println("工单创建失败")
  52. }
  53. }
  54. }
  55. }
  56. }
  57. func WorkDataHandle(company, phone, demand, name, product string, acceptanceData map[string]interface{}) bool {
  58. uId := ""
  59. query := map[string]interface{}{}
  60. contactsData := TiDb.SelectBySql("select * from dwd_f_userbase_contacts where phone = ? and is_delete = 1", phone)
  61. if contactsData != nil && len(*contactsData) > 0 {
  62. if common.ObjToString((*contactsData)[0]["baseinfo_id"]) != "" {
  63. uId = common.ObjToString((*contactsData)[0]["baseinfo_id"])
  64. query["uid"] = uId
  65. }
  66. }
  67. if uId == "" {
  68. log.Println("用户信息不存在")
  69. return false
  70. }
  71. cluename := company
  72. if cluename == "" {
  73. cluename = phone //没有线索名,手机号代替
  74. }
  75. ok, data, saleData := false, map[string]interface{}{}, []map[string]interface{}{}
  76. isGroup, isCommerce := GetCompanyType(cluename, uId)
  77. uCount, _ := TiDb.FindOne("dwd_f_crm_clue_info", map[string]interface{}{"uid": uId}, "", ""), true //查当前线索是否已存在
  78. if uCount != nil && len(*uCount) > 0 {
  79. isUpdate := gconv.Int64((*uCount)["is_artificially_modified"])
  80. if isUpdate == 1 {
  81. cluename = ""
  82. }
  83. clueId := gconv.Int64((*uCount)["id"])
  84. positionId := gconv.Int64((*uCount)["position_id"])
  85. trailstatus := gconv.String((*uCount)["trailstatus"])
  86. IS_TRANSFER := gconv.Int64((*uCount)["IS_TRANSFER"])
  87. if IS_TRANSFER == 1 {
  88. //客成处理
  89. //客成
  90. //生成客成数据
  91. customerMap := TiDb.FindOne("dwd_f_csm_customer_info", map[string]interface{}{
  92. "clue_id": clueId,
  93. }, "position_id,name", "")
  94. if customerMap != nil && len(*customerMap) > 0 {
  95. //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)
  96. 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)
  97. data = map[string]interface{}{
  98. "type": "kc",
  99. "position_id": (*customerMap)["position_id"],
  100. "name": (*customerMap)["name"],
  101. }
  102. } else {
  103. log.Println("查询不到客成数据", clueId, uId)
  104. return false
  105. }
  106. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  107. "clue_id": clueId,
  108. "position_id": (*customerMap)["position_id"],
  109. "change_type": "加入任务车",
  110. "new_value": "咨询客服转客成",
  111. "createtime": time.Now().Format(date.Date_Full_Layout),
  112. "BCPCID": common.GetRandom(32),
  113. "operator_id": -1,
  114. })
  115. } else {
  116. if positionId == 0 {
  117. //线索变更
  118. ok, data, saleData = FindPosition(0, "", gconv.String(acceptanceData["creator_time"]))
  119. if !ok {
  120. log.Println(positionId, "用户查询失败")
  121. return false
  122. }
  123. 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)
  124. } else {
  125. ok, data, saleData = FindPosition(positionId, trailstatus, gconv.String(acceptanceData["creator_time"]))
  126. if !ok {
  127. log.Println(positionId, "用户查询失败")
  128. return false
  129. }
  130. if gconv.Int64(data["position_id"]) == positionId {
  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, false, demand)
  132. } else {
  133. 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)
  134. }
  135. }
  136. }
  137. } else {
  138. //新增线索
  139. ok, data, _ = FindPosition(0, "", gconv.String(acceptanceData["creator_time"]))
  140. if !ok {
  141. return false
  142. }
  143. 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)
  144. }
  145. //工单生成
  146. ok1 := AddOrderWork(acceptanceData, data, product, phone, company)
  147. log.Println("工单创建", ok1, gconv.String(acceptanceData["acceptance_no"]))
  148. return true
  149. }
  150. func AddOrderWork(acceptanceData map[string]interface{}, userData map[string]interface{}, product, phone, company string) bool {
  151. nowTime := time.Now().Format(date.Date_Full_Layout)
  152. work_order_no := fmt.Sprintf("GD%s%s", time.Now().Format(date.Date_yyyyMMdd), FindNumber("gd"))
  153. productArr := []string{}
  154. for _, v := range strings.Split(product, ",") {
  155. switch ProductMap[v] {
  156. case "dk":
  157. continue
  158. default:
  159. productArr = append(productArr, v)
  160. }
  161. }
  162. two_type := "dx"
  163. if gconv.String(userData["type"]) == "kc" {
  164. two_type = "kc"
  165. }
  166. personMap := GetPerson(gconv.String(userData["position_id"]))
  167. if personMap == nil || len(personMap) == 0 {
  168. return false
  169. }
  170. orderWorkMap := map[string]interface{}{
  171. "work_order_no": work_order_no,
  172. "acceptance_no": gconv.String(acceptanceData["acceptance_no"]),
  173. "type": strings.Join(productArr, ","),
  174. "status": common.If(gconv.Int64(userData["orderStatus"]) == 0, 2, 1),
  175. "initiator_name": gconv.String(acceptanceData["creator_name"]),
  176. "initiator_position_id": gconv.String(acceptanceData["initiator_position_id"]),
  177. "current_name": common.If(gconv.Int64(userData["orderStatus"]) == 0, nil, userData["name"]),
  178. "current_position_id": common.If(gconv.Int64(userData["orderStatus"]) == 0, nil, userData["position_id"]),
  179. "history_name": common.If(gconv.Int64(userData["orderStatus"]) == 0, userData["name"], nil),
  180. "history_postion_id": common.If(gconv.Int64(userData["orderStatus"]) == 0, userData["position_id"], nil),
  181. "is_delete": 1,
  182. "creator_name": gconv.String(acceptanceData["creator_name"]),
  183. "creator_position_id": gconv.String(acceptanceData["creator_position_id"]),
  184. "creator_time": nowTime,
  185. "two_type": two_type,
  186. "department_no": gconv.String(personMap["deptId"]),
  187. "department_name": gconv.String(personMap["deptName"]),
  188. "update_time": common.If(gconv.Int64(userData["orderStatus"]) == 0, nowTime, nil),
  189. }
  190. ok3 := WorkOrder.Insert("order_work", orderWorkMap)
  191. if ok3 > 0 {
  192. status := 2
  193. if WorkOrder.Count("order_work", map[string]interface{}{
  194. "status": 1,
  195. "acceptance_no": gconv.String(acceptanceData["acceptance_no"]),
  196. }) > 0 {
  197. status = 1
  198. }
  199. WorkOrder.Update("order_acceptance", map[string]interface{}{
  200. "id": acceptanceData["id"],
  201. }, map[string]interface{}{
  202. "is_clue": 3,
  203. "status": status,
  204. "over_time": common.If(status == 1, nil, nowTime),
  205. })
  206. //日志添加
  207. approvalRecordMap := map[string]interface{}{
  208. "work_order_no": work_order_no,
  209. "status": common.If(gconv.Int64(userData["orderStatus"]) == 0, 3, 1),
  210. "new_status": common.If(gconv.Int64(userData["orderStatus"]) == 0, 2, nil),
  211. "handle_name": userData["name"],
  212. "handle_position_id": userData["position_id"],
  213. "handle_dept_id": gconv.String(personMap["deptId"]),
  214. "handle_dept_name": gconv.String(personMap["deptName"]),
  215. "creator_name": gconv.String(acceptanceData["creator_name"]),
  216. "creator_position_id": gconv.String(acceptanceData["initiator_position_id"]),
  217. "is_delete": 1,
  218. "creator_time": nowTime,
  219. "handle_time": common.If(gconv.Int64(userData["orderStatus"]) == 0, nowTime, nil),
  220. "update_name": common.If(gconv.Int64(userData["orderStatus"]) == 0, userData["name"], nil),
  221. "update_position_id": common.If(gconv.Int64(userData["orderStatus"]) == 0, userData["position_id"], nil),
  222. "update_time": common.If(gconv.Int64(userData["orderStatus"]) == 0, nowTime, nil),
  223. }
  224. WorkOrder.Insert("approval_record", approvalRecordMap)
  225. WorkMail(personMap,
  226. strings.Join(productArr, ","),
  227. gconv.Int64(common.If(gconv.Int64(userData["orderStatus"]) == 0, 2, 1)),
  228. gconv.String(personMap["name"]),
  229. gconv.String(acceptanceData["creator_name"]),
  230. nowTime,
  231. work_order_no,
  232. phone,
  233. company)
  234. return true
  235. }
  236. return false
  237. }
  238. // 本级以及上级管理员查询
  239. func GetPerson(positionId string) map[string]interface{} {
  240. person := map[string]interface{}{}
  241. positionArrMap := Base.SelectBySql(fmt.Sprintf(`select a.phone,b.id,b.ent_id from
  242. base_user a
  243. INNER JOIN base_position b
  244. on b.id=%s and b.user_id=a.id and b.type=1`,
  245. positionId))
  246. if positionArrMap == nil || len(*positionArrMap) == 0 {
  247. return map[string]interface{}{}
  248. }
  249. phone := gconv.String((*positionArrMap)[0]["phone"])
  250. entId := gconv.String((*positionArrMap)[0]["ent_id"])
  251. entUserArrMap := Mysql.SelectBySql(fmt.Sprintf(`SELECT
  252. a.name as name,a.mail as mail,b.dept_id as deptId,a.phone ,c.name as deptName
  253. FROM
  254. entniche_user a
  255. INNER JOIN entniche_department_user b ON a.ent_id =%s
  256. AND a.phone IN %s
  257. and a.id=b.user_id
  258. inner join entniche_department c on b.dept_id=c.id
  259. `, entId, fmt.Sprintf("(%s)", phone)))
  260. //商机管理员
  261. if entUserArrMap == nil || len(*entUserArrMap) == 0 {
  262. return map[string]interface{}{}
  263. }
  264. deptId := gconv.Int64((*entUserArrMap)[0]["deptId"])
  265. person = map[string]interface{}{
  266. "name": gconv.String((*entUserArrMap)[0]["name"]),
  267. "mail": gconv.String((*entUserArrMap)[0]["mail"]),
  268. "phone": gconv.String((*entUserArrMap)[0]["phone"]),
  269. "deptId": gconv.String((*entUserArrMap)[0]["deptId"]),
  270. "deptName": gconv.String((*entUserArrMap)[0]["deptName"]),
  271. }
  272. //本部门管理员查询
  273. depthMap := Mysql.SelectBySql(`SELECT
  274. c.name as name,c.mail as mail
  275. FROM
  276. entniche_department_user a
  277. INNER JOIN entniche_user_role b ON a.dept_id = ?
  278. AND a.user_id = b.user_id
  279. AND b.role_id !=""
  280. INNER JOIN entniche_user c ON a.user_id = c.id`, deptId)
  281. if depthMap != nil && len(*depthMap) > 0 {
  282. person["deptPersonName"] = gconv.String((*depthMap)[0]["name"])
  283. person["deptPersonMail"] = gconv.String((*depthMap)[0]["mail"])
  284. }
  285. //商机管理员查询
  286. superiorDepthMap := Mysql.SelectBySql(`SELECT
  287. c.*
  288. FROM
  289. entniche_department d
  290. INNER JOIN entniche_department_user a ON d.id = ?
  291. AND d.pid = a.dept_id
  292. INNER JOIN entniche_user_role b ON a.user_id = b.user_id
  293. AND b.role_id !=""
  294. INNER JOIN entniche_user c ON a.user_id = c.id`, deptId)
  295. if superiorDepthMap != nil && len(*superiorDepthMap) > 0 {
  296. person["superiorDepthPersonName"] = gconv.String((*superiorDepthMap)[0]["name"])
  297. person["superiorDepthPersonMail"] = gconv.String((*superiorDepthMap)[0]["mail"])
  298. }
  299. return person
  300. }
  301. // 编号查询
  302. func FindNumber(moudle string) string {
  303. today := time.Now().Format("2006-01-02")
  304. yesterday := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
  305. key := fmt.Sprintf("%s_%s", today, moudle)
  306. yesterdayKey := fmt.Sprintf("%s_%s", yesterday, moudle)
  307. if ok, _ := redis.Exists("newother", yesterdayKey); ok {
  308. //删除之前数据
  309. redis.Del("newother", yesterdayKey)
  310. }
  311. count := redis.Incr("newother", key)
  312. log.Println("编号获取", moudle, fmt.Sprintf("%04d", count))
  313. return fmt.Sprintf("%04d", count)
  314. }
  315. // 人员查询
  316. func GetAllocation(proportion1, proportion3 float64, deptCount1, deptCount3 int64, administrators1, administrators3 map[string]interface{}, creatorTime string) map[string]interface{} {
  317. log.Println("分配比例查询", proportion1, proportion3, deptCount1, deptCount3)
  318. if deptCount1 == 0 {
  319. return administrators1
  320. }
  321. if deptCount3 == 0 {
  322. return administrators3
  323. }
  324. nowAllocationRatio := math.Round(gconv.Float64(deptCount1 / deptCount3))
  325. if cfg.AllocationRatio == 0 {
  326. //重新计算
  327. cfg.AllocationRatio = math.Round(proportion1 / proportion3)
  328. cfg.AllocationTime = creatorTime
  329. common.WriteSysConfig(&cfg)
  330. log.Println("新增计算比例", cfg.AllocationRatio)
  331. return administrators1
  332. } else {
  333. if nowAllocationRatio == cfg.AllocationRatio {
  334. //重新计算
  335. cfg.AllocationRatio = math.Round(proportion1 / proportion3)
  336. cfg.AllocationTime = creatorTime
  337. common.WriteSysConfig(&cfg)
  338. return administrators1
  339. }
  340. }
  341. if nowAllocationRatio > cfg.AllocationRatio {
  342. return administrators3
  343. } else {
  344. return administrators1
  345. }
  346. //达到比例也重新计算
  347. }
  348. func FindPosition(positionId int64, trailstatus, creatorTime string) (bool, map[string]interface{}, []map[string]interface{}) {
  349. allData := []map[string]interface{}{}
  350. //查询两个部门高级管理员
  351. //查询两个部门所有人员标识
  352. //电销三部
  353. userData1 := TiDb.SelectBySql(`SELECT
  354. a.position_id,
  355. a.name,
  356. b.seat_number,
  357. b.role_id,
  358. a.bi_pcode,
  359. a.dept_name
  360. FROM
  361. dwd_d_crm_department_level_succbi a
  362. INNER JOIN dwd_f_crm_personnel_management b ON a.resign = 0 and b.resign = 0
  363. AND a.dept_name LIKE "%电销部%"
  364. AND a.position_id = b.position_id`)
  365. userData3 := TiDb.SelectBySql(`SELECT
  366. a.position_id,
  367. a.name,
  368. b.seat_number,
  369. b.role_id,
  370. a.bi_pcode,
  371. a.dept_name
  372. FROM
  373. dwd_d_crm_department_level_succbi a
  374. INNER JOIN dwd_f_crm_personnel_management b ON a.resign = 0 and b.resign = 0
  375. AND a.resign = 0
  376. AND a.dept_name LIKE "%销售三部"
  377. AND a.position_id = b.position_id`)
  378. if userData3 == nil || len(*userData3) == 0 || userData1 == nil || len(*userData1) == 0 {
  379. return false, map[string]interface{}{}, allData
  380. }
  381. //一部管理员信息
  382. administrators1 := map[string]interface{}{}
  383. //三部管理员信息
  384. administrators3 := map[string]interface{}{}
  385. //返回当前人信息
  386. administrators := map[string]interface{}{}
  387. //电销一部
  388. deptNameMap1 := map[string]interface{}{}
  389. deptNameMap3 := map[string]interface{}{}
  390. proportion1 := float64(0)
  391. proportion3 := float64(0)
  392. for _, v := range *userData3 {
  393. v["type"] = 3
  394. id := gconv.Int64(v["position_id"])
  395. roleId := gconv.Int64(v["role_id"])
  396. if id == positionId {
  397. administrators = v
  398. }
  399. if roleId == 8 {
  400. v["orderStatus"] = 2
  401. administrators3 = v
  402. } else if roleId == 3 {
  403. proportion3 += 0.5
  404. } else {
  405. proportion3 += 1
  406. }
  407. deptNameMap3[gconv.String(v["bi_pcode"])] = true
  408. allData = append(allData, v)
  409. }
  410. for _, v := range *userData1 {
  411. v["type"] = 1
  412. id := gconv.Int64(v["position_id"])
  413. roleId := gconv.Int64(v["role_id"])
  414. if id == positionId {
  415. administrators = v
  416. }
  417. if roleId == 8 {
  418. v["orderStatus"] = 2
  419. administrators1 = v
  420. } else if roleId == 3 {
  421. proportion1 += 0.5
  422. } else {
  423. proportion1 += 1
  424. }
  425. deptNameMap1[gconv.String(v["bi_pcode"])] = true
  426. allData = append(allData, v)
  427. }
  428. if positionId != 0 {
  429. if administrators == nil || len(administrators) == 0 {
  430. return false, map[string]interface{}{}, allData
  431. }
  432. positiontype := gconv.Int64(administrators["type"])
  433. if trailstatus == "01" {
  434. switch positiontype {
  435. case 1:
  436. //找他上级
  437. administrators = administrators1
  438. case 3:
  439. //找他上级
  440. administrators = administrators3
  441. }
  442. return true, administrators, allData
  443. } else {
  444. return true, administrators, allData
  445. }
  446. }
  447. //按照比例分配选择一部还是三部
  448. //一部查询
  449. deptCount1 := CalculateProportion(deptNameMap1)
  450. //三部查询
  451. deptCount3 := CalculateProportion(deptNameMap3)
  452. return true, GetAllocation(proportion1, proportion3, deptCount1, deptCount3, administrators1, administrators3, creatorTime), allData
  453. log.Println("电销信息获取失败", positionId)
  454. return false, map[string]interface{}{}, allData
  455. }
  456. func CalculateProportion(deptNameMap map[string]interface{}) int64 {
  457. deptNameStr := ""
  458. for k := range deptNameMap {
  459. if deptNameStr == "" {
  460. deptNameStr = k
  461. } else {
  462. deptNameStr = fmt.Sprintf("%s,%s", deptNameStr, k)
  463. }
  464. }
  465. if deptNameStr == "" {
  466. return int64(0)
  467. }
  468. count := int64(0)
  469. sql := fmt.Sprintf(`SELECT
  470. sum(1) as count
  471. FROM
  472. order_work a
  473. INNER JOIN approval_record b ON a.creator_time >= "%s"
  474. AND FIND_IN_SET( a.department_no , "%s")
  475. AND a.work_order_no = b.work_order_no
  476. and (b.new_status!= 1 or b.new_status is null )
  477. `, cfg.AllocationTime, deptNameStr)
  478. data := WorkOrder.SelectBySql(sql)
  479. if data != nil && len(*data) > 0 {
  480. count = gconv.Int64((*data)[0]["count"])
  481. }
  482. return count
  483. }
  484. // 未支付订单 30分钟一次
  485. func orders() {
  486. //一个小时未支付进入线索 A
  487. log.Println("未支付订单定时任务开始")
  488. lastOrderId := cfg.LastOrderId
  489. selectTimeStart := time.Unix(time.Now().Unix()-7200, 0).Format(date.Date_Full_Layout)
  490. selectTimeEnd := time.Unix(time.Now().Unix()-3600, 0).Format(date.Date_Full_Layout)
  491. sql := fmt.Sprintf(`select * from dataexport_order where create_time <= "%s" and create_time >= "%s" and id > %s`, selectTimeEnd, selectTimeStart, fmt.Sprint(lastOrderId))
  492. //sql := fmt.Sprintf(`select * from dataexport_order where id=260265`)
  493. data := Mysql.SelectBySql(sql)
  494. if data != nil && *data != nil && len(*data) > 0 {
  495. for _, v := range *data {
  496. order_status := common.IntAll(v["order_status"])
  497. is_backstage_order := common.IntAll(v["is_backstage_order"])
  498. product_type_str1 := `"大会员","VIP订阅","数据流量包","历史数据"`
  499. product_type := common.ObjToString(v["product_type"])
  500. if order_status == 0 && is_backstage_order == 0 && strings.Contains(product_type_str1, product_type) {
  501. ok1, ok2, _ := FormatData(v, "orders")
  502. if !ok1 {
  503. common.WriteSysConfig(&cfg)
  504. log.Println("线索卡点", "orders", v, selectTimeEnd, selectTimeStart)
  505. } else {
  506. if !ok2 {
  507. log.Println("用户分配已达上限", "orders", v, selectTimeEnd, selectTimeStart)
  508. common.WriteSysConfig(&cfg)
  509. }
  510. }
  511. }
  512. cfg.LastOrderId = common.IntAll(v["id"])
  513. }
  514. }
  515. common.WriteSysConfig(&cfg)
  516. log.Println("未支付订单定时任务结束")
  517. }
  518. func readClue() {
  519. log.Println("读表进线索定时任务开始")
  520. lastReadClueTime := cfg.LastReadClueTime
  521. sql := fmt.Sprintf(`select * from clue_info where updatetime > "%s" order by updatetime asc`, fmt.Sprint(lastReadClueTime))
  522. data := TiDb.SelectBySql(sql)
  523. if data != nil && *data != nil && len(*data) > 0 {
  524. for _, v := range *data {
  525. ok1, ok2, _ := FormatData(v, "readClue")
  526. if !ok1 {
  527. common.WriteSysConfig(&cfg)
  528. log.Println("线索卡点", "readClue", v, lastReadClueTime)
  529. } else {
  530. if !ok2 {
  531. log.Println("用户分配已达上限", "readClue", v, lastReadClueTime)
  532. common.WriteSysConfig(&cfg)
  533. }
  534. }
  535. cfg.LastReadClueTime = common.ObjToString(v["updatetime"])
  536. }
  537. }
  538. common.WriteSysConfig(&cfg)
  539. log.Println("读表进线索定时任务结束")
  540. }
  541. // 新注册用户 5分钟一次
  542. func users() {
  543. //判断节假日
  544. runOk := getRunOk()
  545. if !runOk {
  546. log.Println("不是工作日,任务暂停")
  547. return
  548. }
  549. //新用户注册后5分钟内进入线索 C
  550. log.Println("新注册用户定时任务开始")
  551. selectTimeEnd := cfg.LastUserId
  552. sql := fmt.Sprintf(`select * from dwd_f_userbase_baseinfo where createtime > "%s" and (s_platform != 'xcx' or s_platform is NULL) and source = "0101" and status != 2 order by createtime asc`, selectTimeEnd)
  553. data := TiDb.SelectBySql(sql)
  554. abhList := []map[string]interface{}{}
  555. if data != nil && *data != nil && len(*data) > 0 {
  556. for k, v := range *data {
  557. //判断用户是否有小程序切使用过剑鱼其他产品
  558. createtime := common.ObjToString(v["createtime"])
  559. ok1, ok2, ok3 := FormatData(v, "users")
  560. if !ok3 {
  561. cfg.LastUserId = createtime
  562. //安博会数据
  563. abhList = append(abhList, v)
  564. continue
  565. }
  566. if !ok1 {
  567. log.Println("线索卡点", "users", v, selectTimeEnd)
  568. } else {
  569. if !ok2 {
  570. log.Println("用户分配已达上限", "users", v, selectTimeEnd)
  571. }
  572. }
  573. if k == len(*data)-1 {
  574. cfg.LastUserId = createtime
  575. }
  576. }
  577. if len(abhList) > 0 {
  578. //安博会发邮件高翔
  579. ABHEmail("user", abhList)
  580. }
  581. }
  582. common.WriteSysConfig(&cfg)
  583. selectXcxTimeEnd := cfg.LastXcxUserId
  584. xcxSql := fmt.Sprintf(`SELECT DISTINCT
  585. aa.mgo_id as userId,
  586. cc.code as industry ,
  587. aa.phone,
  588. IF
  589. ( aa.phone_time IS NULL, aa.create_time, aa.phone_time ) as time
  590. FROM
  591. debris_product.miniprogram_user aa
  592. INNER JOIN debris_product.miniprogram bb ON (
  593. aa.phone <> ''
  594. AND
  595. IF
  596. ( aa.phone_time IS NULL, aa.create_time, aa.phone_time ) > '%s'
  597. AND aa.miniprogram_code = bb.CODE
  598. )
  599. INNER JOIN debris_product.industry cc ON ( bb.industry_code = cc.CODE )
  600. WHERE
  601. NOT EXISTS (
  602. SELECT
  603. 1
  604. FROM
  605. debris_product.miniprogram_user a
  606. INNER JOIN debris_product.miniprogram b ON (
  607. aa.unionid = a.unionid
  608. AND aa.miniprogram_code = a.miniprogram_code
  609. AND aa.id != a.id
  610. AND
  611. IF
  612. ( a.phone_time IS NULL, a.create_time, a.phone_time ) <= '%s'
  613. AND a.miniprogram_code = b.CODE
  614. )
  615. INNER JOIN debris_product.miniprogram_user c ON ( a.unionid = c.unionid AND b.CODE = c.miniprogram_code ))
  616. ORDER BY time
  617. `, selectXcxTimeEnd, selectXcxTimeEnd)
  618. xcxData := debrisProductMysql.SelectBySql(xcxSql)
  619. log.Println("11122", selectXcxTimeEnd, xcxData)
  620. if xcxData != nil && *xcxData != nil && len(*xcxData) > 0 {
  621. afList := []map[string]interface{}{}
  622. for k, v := range *xcxData {
  623. //判断用户是否有小程序切使用过剑鱼其他产品
  624. //判断uid
  625. uId := ""
  626. for i := 0; i < 10; i++ {
  627. phone := common.ObjToString(v["phone"])
  628. contactsData := TiDb.SelectBySql("select * from dwd_f_userbase_contacts where phone = ? and is_delete = 1", phone)
  629. if contactsData != nil && len(*contactsData) > 0 {
  630. if common.ObjToString((*contactsData)[0]["baseinfo_id"]) != "" {
  631. uId = common.ObjToString((*contactsData)[0]["baseinfo_id"])
  632. }
  633. }
  634. if uId == "" {
  635. time.Sleep(1 * time.Minute)
  636. } else {
  637. break
  638. }
  639. }
  640. updatetime := common.ObjToString(v["time"])
  641. if uId == "" {
  642. cfg.LastXcxUserId = updatetime
  643. continue
  644. }
  645. ok1, ok2, _ := FormatData(v, "xcxusers")
  646. /*if !ok3 {
  647. //首次使用"安防"小程序新注册用户
  648. afList = append(afList, v)
  649. cfg.LastXcxUserId = updatetime
  650. continue
  651. }*/
  652. if !ok1 {
  653. common.WriteSysConfig(&cfg)
  654. log.Println("小程序用户分配线索卡点", "xcxusers", v, selectXcxTimeEnd)
  655. } else {
  656. if !ok2 {
  657. log.Println("小程序用户分配已达上限", "xcxusers", v, selectXcxTimeEnd)
  658. common.WriteSysConfig(&cfg)
  659. }
  660. }
  661. if k == len(*xcxData)-1 {
  662. cfg.LastXcxUserId = updatetime
  663. }
  664. }
  665. if len(afList) > 0 {
  666. //发邮件给张文福
  667. AFEmail(afList)
  668. }
  669. }
  670. common.WriteSysConfig(&cfg)
  671. log.Println("新注册用户定时任务结束")
  672. }
  673. // 留资 5分钟一次
  674. func saleLeads() {
  675. //判断节假日
  676. runOk := getRunOk()
  677. if !runOk {
  678. log.Println("不是工作日,任务暂停")
  679. return
  680. }
  681. //留资后5分钟内进入线索
  682. //分为免费留资和付费留资 付费B 免费C
  683. log.Println("用户留资定时任务开始")
  684. session := Mgo.GetMgoConn()
  685. lastId := cfg.LastId
  686. abhList := []map[string]interface{}{}
  687. defer func() {
  688. Mgo.DestoryMongoConn(session)
  689. }()
  690. query := map[string]interface{}{}
  691. if lastId != "" {
  692. query["_id"] = map[string]interface{}{"$gt": mongodb.StringTOBsonId(lastId)}
  693. }
  694. log.Println("query :", query)
  695. iter := session.DB(db.Mgo.DbName).C("saleLeads").Find(&query).Sort("_id").Iter()
  696. thisData := map[string]interface{}{}
  697. for {
  698. if !iter.Next(&thisData) {
  699. break
  700. }
  701. sourceCode := common.ObjToString(thisData["source"])
  702. if sourceCode == "" {
  703. log.Println("留资没有source", thisData)
  704. continue
  705. }
  706. //
  707. filterArr := []string{"-pc", "-app", "-wx", "-h5"}
  708. sourceMap := map[string]string{}
  709. saleSource := TiDb.SelectBySql(`SELECT source,name FROM d_saleleads_code WHERE (department LIKE '%大客户%' or department LIKE '%市场组%' or department LIKE '%咨询组%' or department LIKE '%运营部%') AND is_delete = 1`)
  710. if saleSource != nil && len(*saleSource) > 0 {
  711. for _, v := range *saleSource {
  712. source := common.ObjToString(v["source"])
  713. name := common.ObjToString(v["name"])
  714. for _, s := range filterArr {
  715. name = strings.ReplaceAll(name, s, "")
  716. }
  717. sourceMap[source] = name
  718. }
  719. }
  720. if sourceMap[sourceCode] != "" {
  721. continue
  722. }
  723. ok1, ok2, ok3 := FormatData(thisData, "saleLeads")
  724. if !ok3 {
  725. cfg.LastId = mongodb.BsonIdToSId(thisData["_id"])
  726. //安博会数据
  727. abhList = append(abhList, thisData)
  728. continue
  729. }
  730. if !ok1 {
  731. log.Println("线索卡点", "saleLeads", thisData, lastId)
  732. } else {
  733. if !ok2 {
  734. log.Println("用户分配已达上限", "saleLeads", thisData, lastId)
  735. }
  736. }
  737. cfg.LastId = mongodb.BsonIdToSId(thisData["_id"])
  738. }
  739. if len(abhList) > 0 {
  740. //安博会发邮件高翔
  741. ABHEmail("saleLeads", abhList)
  742. }
  743. common.WriteSysConfig(&cfg)
  744. log.Println("用户留资定时任务结束")
  745. }
  746. func userbase() {
  747. log.Println("userbase定时任务开始")
  748. timeUnix := time.Now().Unix()
  749. selectTimeStart := time.Unix(timeUnix-1800, 0).Format("2006-01-02 15:04:05")
  750. selectTimeEnd := time.Unix(timeUnix, 0).Format("2006-01-02 15:04:05")
  751. sql := fmt.Sprintf(`SELECT
  752. a.phone,b.uid,a.baseinfo_id,b.l_registedate,a.createtime,b.id,b.userid
  753. FROM
  754. dwd_f_userbase_contacts a
  755. INNER JOIN dwd_f_userbase_baseinfo b ON
  756. b.status= 1
  757. and (b.s_platform != 'xcx' or b.s_platform is NULL)
  758. AND a.phone = b.phone and a.baseinfo_id= b.uid and a.source ="0101"
  759. and a.phone is not NULL
  760. and a.createtime >="%s"
  761. and a.createtime <"%s"
  762. and a.is_delete=1
  763. ORDER BY a.createtime `, selectTimeStart, selectTimeEnd)
  764. data := TiDb.SelectBySql(sql)
  765. if data != nil && *data != nil && len(*data) > 0 {
  766. for _, v := range *data {
  767. phone := common.ObjToString(v["phone"])
  768. uId := common.ObjToString(v["uid"])
  769. userId := common.ObjToString(v["userid"])
  770. registedate := common.ObjToString(v["l_registedate"])
  771. name := common.ObjToString(v["name"])
  772. nowTime := time.Now().Format(date.Date_Full_Layout)
  773. layout := "2006-01-02 15:04:05"
  774. createtime := gconv.String(v["createtime"])
  775. createtimeInt64, _ := time.Parse(layout, createtime)
  776. registedateInt64, _ := time.Parse(layout, registedate)
  777. count := TiDb.CountBySql("select count(1) as count from dwd_f_crm_clue_info where uid = ?", uId)
  778. if createtimeInt64.Unix()-registedateInt64.Unix() < int64(db.RegTimes)*86400 {
  779. if count == 0 {
  780. //注册少于7天、走新增
  781. data := TiDb.FindOne("dwd_f_userbase_baseinfo", map[string]interface{}{
  782. "id": gconv.Int64(v["id"]),
  783. }, "", "")
  784. if data != nil && len(*data) > 0 {
  785. ok1, ok2, _ := FormatData(v, "users")
  786. if !ok1 {
  787. log.Println("线索卡点", "userbase uid", v, uId)
  788. } else {
  789. if !ok2 {
  790. log.Println("用户分配已达上限", "userbase uid", v, uId)
  791. }
  792. }
  793. }
  794. }
  795. continue
  796. }
  797. registedates, _ := time.Parse(date.Date_Full_Layout, registedate)
  798. log.Println("userbase uid 线索数量 ", count)
  799. log.Println("userbase uid 注册时间 ", registedates)
  800. if count == 0 {
  801. clueId := int64(0)
  802. sql := fmt.Sprintf(`select * from freeClubSign where mogUserId="%s" and sub_again_date > "%s" `, userId, selectTimeEnd)
  803. data := BiService.SelectBySql(sql)
  804. if len(*data) > 0 && userId != "" {
  805. clueId = TiDb.Insert("dwd_f_crm_clue_info", map[string]interface{}{
  806. "userid": userId,
  807. "uid": uId,
  808. "is_assign": 0,
  809. "comeintime": nowTime,
  810. "createtime": nowTime,
  811. "updatetime": nowTime,
  812. "cluename": phone,
  813. "top_cluetype": "532",
  814. "sub_cluetype": "670",
  815. "trailstatus": "01",
  816. "name": name,
  817. "phone": phone,
  818. "comeintime_open": nowTime,
  819. "comeinsource_open": 1,
  820. "FREEZE_TIME": nowTime,
  821. })
  822. } else {
  823. clueId = TiDb.Insert("dwd_f_crm_clue_info", map[string]interface{}{
  824. "userid": userId,
  825. "uid": uId,
  826. "is_assign": 0,
  827. "comeintime": nowTime,
  828. "createtime": nowTime,
  829. "updatetime": nowTime,
  830. "cluename": phone,
  831. "top_cluetype": "532",
  832. "sub_cluetype": "475",
  833. "trailstatus": "01",
  834. "name": name,
  835. "phone": phone,
  836. "comeintime_open": nowTime,
  837. "comeinsource_open": 1,
  838. "FREEZE_TIME": nowTime,
  839. })
  840. }
  841. if clueId > 0 {
  842. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  843. "clue_id": clueId,
  844. "position_id": -1,
  845. "change_type": "创建线索",
  846. "new_value": "系统自动创建",
  847. "createtime": nowTime,
  848. "BCPCID": common.GetRandom(32),
  849. "operator_id": -1,
  850. })
  851. }
  852. }
  853. }
  854. }
  855. log.Println("userbase定时任务结束")
  856. }
  857. func getRunOk() bool {
  858. currentTime, runOk := time.Now(), false
  859. if currentTime.Weekday() == time.Sunday {
  860. isok := false
  861. for k, v := range DateMap {
  862. if currentTime.Format(date.Date_Short_Layout) == k && v == 2 {
  863. isok = true
  864. }
  865. }
  866. if isok {
  867. runOk = true
  868. }
  869. } else {
  870. isok := true
  871. for k, v := range DateMap {
  872. if currentTime.Format(date.Date_Short_Layout) == k && v == 1 {
  873. isok = false
  874. }
  875. }
  876. if isok {
  877. runOk = true
  878. }
  879. }
  880. return runOk
  881. }
  882. func getAreaCode(userId string) (code string) {
  883. followData := Base.Find("follow_project_monitor", map[string]interface{}{"s_userid": userId}, "", "", -1, -1)
  884. sidArr := []string{}
  885. if followData != nil && len(*followData) > 0 {
  886. for _, v := range *followData {
  887. infoId := common.ObjToString(v["s_id"])
  888. sidArr = append(sidArr, infoId)
  889. }
  890. }
  891. if len(sidArr) > 0 {
  892. query := `{"query": {"bool": {"must": [{"terms": {"_id": ["%s"]}}],"must_not": [],"should": []}}}`
  893. query = fmt.Sprintf(query, strings.Join(sidArr, `","`))
  894. biddingData := Es.Get("bidding", "bidding", query)
  895. if biddingData != nil && len(*biddingData) > 0 {
  896. codeMap := map[string]string{}
  897. codeArr := []string{}
  898. for _, v := range *biddingData {
  899. area := common.ObjToString(v["area"])
  900. address := common.ObjToString(v["city"])
  901. if address == "" {
  902. address = area
  903. }
  904. codeMap[address] = AreaCode[address]
  905. }
  906. if len(codeMap) > 0 {
  907. for _, v := range codeMap {
  908. codeArr = append(codeArr, v)
  909. }
  910. }
  911. if len(codeArr) > 0 {
  912. code = strings.Join(codeArr, ",")
  913. }
  914. }
  915. }
  916. log.Println("code ", code)
  917. return
  918. }
  919. func getClueType(item string, data map[string]interface{}, sourceCode string, sourceId int64) (pcode, code, level, topname, subname string) {
  920. if item == "orders" {
  921. productType := common.ObjToString(data["product_type"])
  922. pcode = "1"
  923. level = "A"
  924. topname = "提交订单未支付"
  925. if productType == "VIP订阅" {
  926. code = "6"
  927. subname = "超级订阅"
  928. } else if productType == "大会员" {
  929. code = "7"
  930. subname = "大会员"
  931. } else if productType == "数据流量包" {
  932. code = "8"
  933. subname = "数据流量包"
  934. } else if productType == "历史数据" {
  935. code = "9"
  936. subname = "数据自助导出"
  937. }
  938. } else if item == "users" {
  939. pcode = "4"
  940. code = "154"
  941. level = "C"
  942. topname = "新增注册"
  943. subname = "新增注册用户"
  944. } else if item == "message" {
  945. pcode = "532"
  946. code = "477"
  947. level = "B"
  948. topname = "其他"
  949. subname = "机器人客服主动咨询"
  950. } else if item == "readClue" {
  951. level = "A"
  952. topname = "超级订阅临期用户"
  953. pcode = "614"
  954. if sourceId == 1 {
  955. code = "615"
  956. subname = "60天后到期"
  957. } else if sourceId == 2 {
  958. code = "616"
  959. subname = "45天后到期"
  960. } else if sourceId == 3 {
  961. code = "617"
  962. subname = "15天后到期"
  963. } else {
  964. code = "618"
  965. subname = "7天后到期"
  966. }
  967. } else if item == "allocation" {
  968. pcode = "532"
  969. code = "671"
  970. level = "D"
  971. pcodeData := TiDb.FindOne("dwd_d_crm_cluetype_code", map[string]interface{}{"code": pcode}, "", "")
  972. if pcodeData != nil && len(*pcodeData) > 0 {
  973. topname = common.ObjToString((*pcodeData)["name"])
  974. }
  975. pcodeData = TiDb.FindOne("dwd_d_crm_cluetype_code", map[string]interface{}{"code": code}, "", "")
  976. if pcodeData != nil && len(*pcodeData) > 0 {
  977. subname = common.ObjToString((*pcodeData)["name"])
  978. }
  979. } else if item == "rebind" {
  980. pcode = "532"
  981. code = "670"
  982. level = "D"
  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. pcodeData = TiDb.FindOne("dwd_d_crm_cluetype_code", map[string]interface{}{"code": code}, "", "")
  988. if pcodeData != nil && len(*pcodeData) > 0 {
  989. subname = common.ObjToString((*pcodeData)["name"])
  990. }
  991. } else if item == "invite" {
  992. codeData := TiDb.FindOne("dwd_d_crm_cluetype_code", map[string]interface{}{"code": sourceCode}, "", "")
  993. if codeData != nil && len(*codeData) > 0 {
  994. pcode = common.ObjToString((*codeData)["pcode"])
  995. code = common.ObjToString((*codeData)["code"])
  996. level = common.ObjToString((*codeData)["clue_level"])
  997. subname = common.ObjToString((*codeData)["name"])
  998. pcodeData := TiDb.FindOne("dwd_d_crm_cluetype_code", map[string]interface{}{"code": pcode}, "", "")
  999. if pcodeData != nil && len(*pcodeData) > 0 {
  1000. topname = common.ObjToString((*pcodeData)["name"])
  1001. }
  1002. }
  1003. } else {
  1004. if sourceCode != "" {
  1005. codeData := TiDb.FindOne("dwd_d_crm_cluetype_code", map[string]interface{}{"source": sourceCode}, "", "")
  1006. if codeData != nil && len(*codeData) > 0 {
  1007. pcode = common.ObjToString((*codeData)["pcode"])
  1008. code = common.ObjToString((*codeData)["code"])
  1009. level = common.ObjToString((*codeData)["clue_level"])
  1010. subname = common.ObjToString((*codeData)["name"])
  1011. pcodeData := TiDb.FindOne("dwd_d_crm_cluetype_code", map[string]interface{}{"code": pcode}, "", "")
  1012. if pcodeData != nil && len(*pcodeData) > 0 {
  1013. topname = common.ObjToString((*pcodeData)["name"])
  1014. }
  1015. }
  1016. }
  1017. }
  1018. return
  1019. }
  1020. // 获取自动分配的人
  1021. func autoDraw(mode, cluename, phone string, isGroup, isCommerce int) (positionId int64, seatNumber, saleName string, saleData []map[string]interface{}, isOk, isFreeze bool, noticePositionId int64) {
  1022. isOk = false
  1023. isFreeze = false
  1024. if TiDb.Count("dwd_f_crm_clue_info", map[string]interface{}{"phone": phone, "is_assign": 1}) == 0 { //线索没销售进入,有销售走分配次数最少的逻辑
  1025. if isGroup == 0 && isCommerce == 1 && cluename != "" { //非集团在工商库线索名不为空
  1026. //cdata := TiDb.Find("dwd_f_crm_clue_info", map[string]interface{}{"cluename": cluename, "is_assign": 1}, "", "", -1, -1)
  1027. 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)
  1028. if cdata != nil && len(*cdata) > 0 { //找到了公司有人在跟进
  1029. isOk = true
  1030. pdata := TiDb.SelectBySql(`select * from dwd_f_crm_personnel_management where seat_number is not null and seat_number != ""`)
  1031. if pdata == nil {
  1032. positionId = 0
  1033. seatNumber = ""
  1034. saleName = ""
  1035. return
  1036. }
  1037. saleData = *pdata
  1038. cdataNew := []map[string]interface{}{}
  1039. if len(*cdata) > 1 {
  1040. //可能有多个人跟进
  1041. personMap := map[int64]bool{}
  1042. upperLimitPersonMap := map[int64]bool{}
  1043. upperLimitCdataNew := []map[string]interface{}{}
  1044. upperLimitCount := 0
  1045. isFull := false
  1046. for _, m := range *cdata {
  1047. positionid1 := gconv.Int64(m["position_id"])
  1048. for _, v := range *pdata {
  1049. resign := common.IntAll(v["resign"])
  1050. assign_type := common.IntAll(v["assign_type"])
  1051. role_id := common.IntAll(v["role_id"])
  1052. if positionid1 == common.Int64All(v["position_id"]) {
  1053. if resign == 0 && (assign_type == 1 || role_id == 8) {
  1054. if !FindUpperLimit(gconv.String(positionid1), mode, true) {
  1055. personMap[positionid1] = true
  1056. m["saleName"] = common.ObjToString(v["name"])
  1057. cdataNew = append(cdataNew, m)
  1058. } else {
  1059. upperLimitCount++
  1060. upperLimitPersonMap[positionid1] = true
  1061. m["saleName"] = common.ObjToString(v["name"])
  1062. upperLimitCdataNew = append(upperLimitCdataNew, m)
  1063. }
  1064. }
  1065. }
  1066. }
  1067. }
  1068. if len(cdataNew) == 0 && len(upperLimitCdataNew) > 0 {
  1069. //没有达上限的人数为0 全部都是达上限的
  1070. personMap = upperLimitPersonMap
  1071. cdataNew = upperLimitCdataNew
  1072. isFull = true
  1073. }
  1074. //查询是否都有没有离职
  1075. if len(personMap) != 0 && len(cdataNew) > 0 {
  1076. layout := "2006-01-02 15:04:05"
  1077. //有人没有离职
  1078. data := map[string]interface{}{}
  1079. trailTime := int64(0)
  1080. for _, m := range cdataNew {
  1081. currentTime := int64(0)
  1082. if gconv.String(m["trail_time"]) == "" {
  1083. continue
  1084. }
  1085. t, _ := time.Parse(layout, gconv.String(m["trail_time"]))
  1086. currentTime = t.Unix()
  1087. if currentTime > trailTime {
  1088. trailTime = currentTime
  1089. data = m
  1090. }
  1091. }
  1092. if trailTime == 0 {
  1093. //需要查看通话记录
  1094. lastRingTime := int64(0)
  1095. for _, m := range cdataNew {
  1096. currentTime := int64(0)
  1097. if gconv.String(m["last_ring_time"]) == "" {
  1098. continue
  1099. }
  1100. t, _ := time.Parse(layout, gconv.String(m["last_ring_time"]))
  1101. currentTime = t.Unix()
  1102. if currentTime > lastRingTime {
  1103. lastRingTime = currentTime
  1104. data = m
  1105. }
  1106. }
  1107. if lastRingTime != 0 {
  1108. positionId = common.Int64All(data["position_id"])
  1109. noticePositionId = positionId
  1110. seatNumber = common.ObjToString(data["seatNumber"])
  1111. saleName = common.ObjToString(data["saleName"])
  1112. if isFull {
  1113. isFreeze = true
  1114. noticePositionId = positionId
  1115. positionId = 0
  1116. seatNumber = ""
  1117. saleName = ""
  1118. }
  1119. return
  1120. } else {
  1121. count := 0
  1122. //线索数量判断
  1123. for i, v := range cdataNew {
  1124. if i == 0 {
  1125. count = gconv.Int(v["count"])
  1126. data = v
  1127. } else {
  1128. if count < gconv.Int(v["count"]) {
  1129. count = gconv.Int(v["count"])
  1130. data = v
  1131. }
  1132. }
  1133. }
  1134. positionId = common.Int64All(data["position_id"])
  1135. noticePositionId = positionId
  1136. saleName = common.ObjToString(data["saleName"])
  1137. seatNumber = common.ObjToString(data["seatNumber"])
  1138. if isFull {
  1139. isFreeze = true
  1140. noticePositionId = positionId
  1141. positionId = 0
  1142. seatNumber = ""
  1143. saleName = ""
  1144. }
  1145. return
  1146. }
  1147. } else {
  1148. positionId = common.Int64All(data["position_id"])
  1149. noticePositionId = positionId
  1150. seatNumber = common.ObjToString(data["seatNumber"])
  1151. saleName = common.ObjToString(data["saleName"])
  1152. if isFull {
  1153. isFreeze = true
  1154. noticePositionId = positionId
  1155. positionId = 0
  1156. seatNumber = ""
  1157. saleName = ""
  1158. }
  1159. return
  1160. }
  1161. }
  1162. } else {
  1163. //只有一人跟进
  1164. //(1)该销售人员未离职,则继续分配给该销售人员(保持现状);
  1165. //该销售人员已离职,则随机分配
  1166. positionId = common.Int64All((*cdata)[0]["position_id"])
  1167. noticePositionId = positionId
  1168. seatNumber = common.ObjToString((*cdata)[0]["seatNumber"])
  1169. for _, v := range *pdata {
  1170. resign := common.IntAll(v["resign"])
  1171. assign_type := common.IntAll(v["assign_type"])
  1172. role_id := common.IntAll(v["role_id"])
  1173. if positionId == common.Int64All(v["position_id"]) {
  1174. if resign == 0 && (assign_type == 1 || role_id == 8) {
  1175. if FindUpperLimit(gconv.String(positionId), mode, true) {
  1176. isFreeze = true
  1177. positionId = 0
  1178. seatNumber = ""
  1179. saleName = ""
  1180. break
  1181. } else {
  1182. saleName = common.ObjToString(v["name"])
  1183. return
  1184. }
  1185. }
  1186. }
  1187. }
  1188. }
  1189. }
  1190. }
  1191. }
  1192. positionId = 0
  1193. seatNumber = ""
  1194. saleName = ""
  1195. query := `select * from dwd_f_crm_personnel_management where assign_type = 1 and`
  1196. if mode == "A" {
  1197. query += ` assign_level like "%A%"`
  1198. } else if mode == "B" {
  1199. query += ` assign_level like "%B%"`
  1200. } else if mode == "D" {
  1201. query += ` assign_level like "%D%"`
  1202. } else if mode == "C" {
  1203. query += ` assign_level like "%C%"`
  1204. } else if mode == "S" {
  1205. query += ` assign_level like "%S%"`
  1206. }
  1207. data := TiDb.SelectBySql(query)
  1208. if data != nil && len(*data) > 0 {
  1209. saleData = *data
  1210. sql := "select * from dwd_f_crm_clue_autodraw_record where clue_level = ?"
  1211. countData := TiDb.SelectBySql(sql, mode)
  1212. if countData != nil && len(*countData) > 0 {
  1213. for _, v := range *data {
  1214. isOk := false //判断是否有新员工
  1215. for _, vv := range *countData {
  1216. if common.Int64All(v["position_id"]) == common.Int64All(vv["position_id"]) {
  1217. if common.IntAll(v["resign"]) == 0 {
  1218. vv["status"] = 1
  1219. } else {
  1220. vv["status"] = 2
  1221. }
  1222. isOk = true
  1223. }
  1224. }
  1225. if !isOk { //有新员工直接分给新员工
  1226. positionId = common.Int64All(v["position_id"])
  1227. saleName = common.ObjToString(v["name"])
  1228. log.Println("新员工, ", positionId, saleName)
  1229. rData := TiDb.FindOne("dwd_f_crm_clue_autodraw_record", map[string]interface{}{"clue_level": mode}, "", "count desc")
  1230. TiDb.Insert("dwd_f_crm_clue_autodraw_record", map[string]interface{}{
  1231. "position_id": positionId,
  1232. "clue_level": mode,
  1233. "count": common.Int64All((*rData)["count"]),
  1234. })
  1235. break
  1236. }
  1237. }
  1238. if positionId == 0 {
  1239. res := int64(0)
  1240. countres := 0
  1241. for _, v := range *countData {
  1242. if common.IntAll(v["status"]) == 1 {
  1243. if FindUpperLimit(gconv.String(v["position_id"]), mode, false) {
  1244. continue
  1245. }
  1246. if countres == 0 {
  1247. res = common.Int64All(v["count"])
  1248. positionId = common.Int64All(v["position_id"])
  1249. } else {
  1250. if common.Int64All(v["count"]) <= res {
  1251. res = common.Int64All(v["count"])
  1252. positionId = common.Int64All(v["position_id"])
  1253. }
  1254. }
  1255. countres++
  1256. }
  1257. }
  1258. log.Println(444, res)
  1259. }
  1260. } else {
  1261. for _, kv := range *data {
  1262. positionId1 := gconv.String(kv["position_id"])
  1263. if !FindUpperLimit(positionId1, "", false) {
  1264. positionId = common.Int64All(kv["position_id"])
  1265. saleName = common.ObjToString(kv["name"])
  1266. rData := TiDb.FindOne("dwd_f_crm_clue_autodraw_record", map[string]interface{}{"clue_level": mode}, "", "count desc")
  1267. if rData != nil && len(*rData) > 0 {
  1268. TiDb.Insert("dwd_f_crm_clue_autodraw_record", map[string]interface{}{
  1269. "position_id": positionId,
  1270. "clue_level": mode,
  1271. "count": common.Int64All((*rData)["count"]),
  1272. })
  1273. } else {
  1274. TiDb.Insert("dwd_f_crm_clue_autodraw_record", map[string]interface{}{
  1275. "position_id": positionId,
  1276. "clue_level": mode,
  1277. "count": 0,
  1278. })
  1279. }
  1280. break
  1281. }
  1282. }
  1283. }
  1284. for _, v := range *data {
  1285. if positionId == common.Int64All(v["position_id"]) {
  1286. seatNumber = common.ObjToString(v["seat_number"])
  1287. saleName = common.ObjToString(v["name"])
  1288. }
  1289. }
  1290. }
  1291. return
  1292. }
  1293. func getPositionId(phone string) (positionId int64) {
  1294. userData, ok := Mgo.FindOne("user", map[string]interface{}{"s_phone": phone})
  1295. if ok && userData != nil && len(*userData) > 0 {
  1296. userId := common.Int64All((*userData)["base_user_id"])
  1297. positionData := Base.FindOne("base_position", map[string]interface{}{"type": 1, "ent_id": 25917, "user_id": userId}, "", "") //TODO ent_id
  1298. if positionData != nil && len(*positionData) > 0 {
  1299. positionId = common.Int64All((*positionData)["id"])
  1300. }
  1301. }
  1302. return
  1303. }
  1304. func GetCompanyType(companyName string, uId string) (int, int) {
  1305. isGroup, isCommerce := 0, 0
  1306. uCount := TiDb.FindOne("dwd_f_crm_clue_info", map[string]interface{}{"uid": uId}, "", "")
  1307. if uCount != nil && len(*uCount) > 0 {
  1308. isUpdate := gconv.Int64((*uCount)["is_artificially_modified"])
  1309. if isUpdate == 1 {
  1310. companyName = gconv.String((*uCount)["cluename"])
  1311. }
  1312. if companyName == "" {
  1313. companyName = gconv.String((*uCount)["cluename"])
  1314. }
  1315. }
  1316. if companyName == "" {
  1317. return isGroup, isCommerce
  1318. }
  1319. //是否是集团
  1320. if c := TiDb.CountBySql(`select count(1) from group_company_name where company_name=?`, companyName); c > 0 {
  1321. isGroup = 1
  1322. }
  1323. //是否在工商库
  1324. if companyName != "" {
  1325. if c := MgoQyxy.Count("qyxy_std", map[string]interface{}{"company_name": companyName, "company_type": map[string]interface{}{"$ne": "个体工商户"}}); c > 0 {
  1326. isCommerce = 1
  1327. }
  1328. }
  1329. return isGroup, isCommerce
  1330. }
  1331. // 查询是否达上限
  1332. func FindUpperLimit(positionId string, level string, isAdd bool) bool {
  1333. if positionId == "" {
  1334. return false
  1335. }
  1336. 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
  1337. if isFull && isAdd && level != "" {
  1338. TiDb.UpdateOrDeleteBySql(`update dwd_f_crm_clue_autodraw_record set count = count + 1 where position_id = ? and clue_level = ?`, positionId, level)
  1339. }
  1340. return isFull
  1341. }
  1342. func getSeatNumberPositionId(seatNumber string) (positionId int64) {
  1343. saleData := TiDb.FindOne("dwd_f_crm_personnel_management", map[string]interface{}{"seat_number": seatNumber}, "", "")
  1344. if saleData != nil && len(*saleData) > 0 {
  1345. positionId = common.Int64All((*saleData)["position_id"])
  1346. }
  1347. return
  1348. }
  1349. // 重新关注用户处理
  1350. func rebind() {
  1351. log.Println("重新关注用户处理开始")
  1352. //判断节假日
  1353. runOk := getRunOk()
  1354. if !runOk {
  1355. log.Println("不是工作日,任务暂停")
  1356. return
  1357. }
  1358. rebindTimeEnd := cfg.RebindTime
  1359. sql := fmt.Sprintf(`select * from freeClubSign where sub_again_date > "%s" order by sub_again_date asc`, rebindTimeEnd)
  1360. data := BiService.SelectBySql(sql)
  1361. if data != nil && *data != nil && len(*data) > 0 {
  1362. for _, v := range *data {
  1363. rebindTimeEnd = common.ObjToString(v["sub_again_date"])
  1364. registedates, _ := time.Parse(date.Date_Full_Layout, gconv.String(v["register_time"]))
  1365. if time.Now().Unix()-registedates.Unix() > int64(db.RegTimes)*86400 {
  1366. ok1, ok2, _ := FormatData(v, "rebind")
  1367. if !ok1 {
  1368. log.Println("线索卡点", "allocation", v, rebindTimeEnd)
  1369. } else {
  1370. if !ok2 {
  1371. log.Println("用户分配已达上限", "allocation", v, rebindTimeEnd)
  1372. }
  1373. }
  1374. }
  1375. }
  1376. cfg.RebindTime = rebindTimeEnd
  1377. common.WriteSysConfig(&cfg)
  1378. }
  1379. log.Println("重新关注用户处理结束")
  1380. }
  1381. // 活跃用户处理
  1382. func activeUsers() {
  1383. log.Println("活跃用户处理开始")
  1384. //判断节假日
  1385. runOk := getRunOk()
  1386. if !runOk {
  1387. log.Println("不是工作日,任务暂停")
  1388. return
  1389. }
  1390. //活跃用户查询
  1391. activeTimeEnd := cfg.ActiveTime
  1392. sql := fmt.Sprintf(`select * from freeClubSign where act_again_date > "%s" order by act_again_date asc`, activeTimeEnd)
  1393. data := BiService.SelectBySql(sql)
  1394. if data != nil && *data != nil && len(*data) > 0 {
  1395. for _, v := range *data {
  1396. activeTimeEnd = common.ObjToString(v["act_again_date"])
  1397. ok1, ok2, _ := FormatData(v, "allocation")
  1398. log.Println(v, "allocation", ok1, ok2)
  1399. if !ok1 {
  1400. log.Println("线索卡点", "allocation", v, activeTimeEnd)
  1401. } else {
  1402. if !ok2 {
  1403. log.Println("用户分配已达上限", "allocation", v, activeTimeEnd)
  1404. }
  1405. }
  1406. }
  1407. cfg.ActiveTime = activeTimeEnd
  1408. common.WriteSysConfig(&cfg)
  1409. }
  1410. log.Println("活跃用户处理结束")
  1411. }
  1412. // 安博会邮件
  1413. /*func ABHEmail(source string, data []map[string]interface{}) {
  1414. fileName, detailName, email, dir := "", "", "", ""
  1415. var err error
  1416. switch source {
  1417. case "user":
  1418. xlsxArr := []string{"姓名", "联系方式", "邮箱", "公司名称", "咨询需求", "销售线索来源", "具体来源", "留资时间"}
  1419. batch := FindBatch("abh")
  1420. fileName, detailName = "安博会用户注册销售线索 "+time.Now().Format(date.Date_Short_Layout)+"-"+batch, ""
  1421. xf := xlsx.NewFile()
  1422. style := xlsx.NewStyle()
  1423. style.Font.Size = 12
  1424. style.Font.Bold = true
  1425. style.Alignment.Vertical = "center"
  1426. style.Alignment.Horizontal = "center"
  1427. detailName = "今日新增安博会销售线索,请查收附件,及时跟进。"
  1428. sh, _ := xf.AddSheet("线索数据")
  1429. row1 := sh.AddRow()
  1430. for _, x := range xlsxArr {
  1431. cell := row1.AddCell()
  1432. cell.SetString(x)
  1433. cell.SetStyle(style)
  1434. }
  1435. for _, v := range data {
  1436. row := sh.AddRow()
  1437. row.AddCell().SetString(common.ObjToString(v["name"]))
  1438. row.AddCell().SetString(common.ObjToString(v["phone"]))
  1439. row.AddCell().SetString(common.ObjToString(v["email"]))
  1440. row.AddCell().SetString(common.ObjToString(v["company_name"]))
  1441. row.AddCell().SetString("")
  1442. row.AddCell().SetString("")
  1443. row.AddCell().SetString("安博会用户注册")
  1444. row.AddCell().SetString(gconv.Time(gconv.Int64(v["createtime"])).Format(date.Date_Full_Layout))
  1445. //增加客户需求
  1446. }
  1447. dir = "./xlsx/abh/" + fileName + ".xlsx"
  1448. err = xf.Save(dir)
  1449. case "saleLeads":
  1450. xlsxArr := []string{"用户昵称", "姓名", "公司名称", "职位", "联系人电话", "购买条数", "用户邮箱", "已支付订单信息", "未支付订单类型", "销售线索来源", "具体来源", "数据需求"}
  1451. batch := FindBatch("abh")
  1452. fileName, detailName = time.Now().Format(date.Date_Short_Layout)+"-"+batch+"安博会电销销售线索", ""
  1453. xf := xlsx.NewFile()
  1454. style := xlsx.NewStyle()
  1455. style.Font.Size = 12
  1456. style.Font.Bold = true
  1457. style.Alignment.Vertical = "center"
  1458. style.Alignment.Horizontal = "center"
  1459. detailName = "今日新增安博会销售线索,请查收附件,及时跟进。"
  1460. sh, _ := xf.AddSheet("线索数据")
  1461. row1 := sh.AddRow()
  1462. for _, x := range xlsxArr {
  1463. cell := row1.AddCell()
  1464. cell.SetString(x)
  1465. cell.SetStyle(style)
  1466. }
  1467. filterArr := []string{"-pc", "-app", "-wx", "-h5"}
  1468. sourceMap := map[string]string{} //根据留资维表:tidb/Jianyu_subjectdb/d_saleleads_code
  1469. saleSource := TiDb.SelectBySql(`SELECT source,name FROM d_saleleads_code WHERE is_delete = 1`)
  1470. if saleSource != nil && len(*saleSource) > 0 {
  1471. for _, v := range *saleSource {
  1472. source := common.ObjToString(v["source"])
  1473. name := common.ObjToString(v["name"])
  1474. for _, s := range filterArr {
  1475. name = strings.ReplaceAll(name, s, "")
  1476. }
  1477. sourceMap[source] = name
  1478. }
  1479. }
  1480. for _, v := range data {
  1481. sources := common.ObjToString(v["source"])
  1482. interest := common.ObjToString(v["interest"])
  1483. row := sh.AddRow()
  1484. row.AddCell().SetString(common.ObjToString(v["usernickname"]))
  1485. row.AddCell().SetString(common.ObjToString(v["name"]))
  1486. row.AddCell().SetString(common.ObjToString(v["company"]))
  1487. row.AddCell().SetString(common.ObjToString(v["position"]))
  1488. row.AddCell().SetString(common.ObjToString(v["phone"]))
  1489. row.AddCell().SetValue(0)
  1490. row.AddCell().SetString(common.ObjToString(v["email"]))
  1491. row.AddCell().SetString("")
  1492. row.AddCell().SetString("")
  1493. row.AddCell().SetString(sourceMap[sources])
  1494. row.AddCell().SetString(interest)
  1495. row.AddCell().SetString(common.ObjToString(v["data_requirement"]))
  1496. //增加客户需求
  1497. }
  1498. dir = "./xlsx/abh/" + fileName + ".xlsx"
  1499. err = xf.Save(dir)
  1500. case "big":
  1501. xlsxArr := []string{"用户昵称", "姓名", "公司名称", "职位", "联系人电话", "购买条数", "用户邮箱", "已支付订单信息", "未支付订单类型", "销售线索来源", "具体来源", "数据需求"}
  1502. batch := FindBatch("abh")
  1503. fileName, detailName = time.Now().Format(date.Date_Short_Layout)+"-"+batch+"安博会大客户销售线索", ""
  1504. xf := xlsx.NewFile()
  1505. style := xlsx.NewStyle()
  1506. style.Font.Size = 12
  1507. style.Font.Bold = true
  1508. style.Alignment.Vertical = "center"
  1509. style.Alignment.Horizontal = "center"
  1510. detailName = "今日新增安博会销售线索,请查收附件,及时跟进。"
  1511. sh, _ := xf.AddSheet("线索数据")
  1512. row1 := sh.AddRow()
  1513. for _, x := range xlsxArr {
  1514. cell := row1.AddCell()
  1515. cell.SetString(x)
  1516. cell.SetStyle(style)
  1517. }
  1518. for _, v := range data {
  1519. row := sh.AddRow()
  1520. row.AddCell().SetString(common.ObjToString(v["usernickname"]))
  1521. row.AddCell().SetString(common.ObjToString(v["username"]))
  1522. row.AddCell().SetString(common.ObjToString(v["company"]))
  1523. row.AddCell().SetString(common.ObjToString(v["job"]))
  1524. row.AddCell().SetString(common.ObjToString(v["phone"]))
  1525. row.AddCell().SetValue(common.IntAll(v["data_count"]))
  1526. row.AddCell().SetString(common.ObjToString(v["email"]))
  1527. row.AddCell().SetString(common.ObjToString(v["payorderinfo"]))
  1528. row.AddCell().SetString(common.ObjToString(v["unpayorderinfo"]))
  1529. row.AddCell().SetString(common.ObjToString(v["source"]))
  1530. row.AddCell().SetString(common.ObjToString(v["interest"]))
  1531. row.AddCell().SetString(common.ObjToString(v["data_requirement"]))
  1532. //增加客户需求
  1533. }
  1534. dir = "./xlsx/abh/" + fileName + ".xlsx"
  1535. err = xf.Save(dir)
  1536. case "advisory":
  1537. xlsxArr := []string{"姓名", "联系方式", "邮箱", "公司名称", "咨询需求", "销售线索来源", "具体来源", "留资时间"}
  1538. //排序:首先按照“联系方式”排序,即同1个用户的留资放在一起,其次按照留资时间正序排序。
  1539. batch := FindBatch("abh")
  1540. fileName, detailName = "安博会咨询服务销售线索 "+time.Now().Format(date.Date_Short_Layout)+"-"+batch, ""
  1541. xf := xlsx.NewFile()
  1542. style := xlsx.NewStyle()
  1543. style.Font.Size = 12
  1544. style.Font.Bold = true
  1545. style.Alignment.Vertical = "center"
  1546. style.Alignment.Horizontal = "center"
  1547. detailName = "今日新增安博会销售线索,请查收附件,及时跟进。"
  1548. sh, _ := xf.AddSheet("线索数据")
  1549. row1 := sh.AddRow()
  1550. for _, x := range xlsxArr {
  1551. cell := row1.AddCell()
  1552. cell.SetString(x)
  1553. cell.SetStyle(style)
  1554. }
  1555. for _, v := range data {
  1556. row := sh.AddRow()
  1557. row.AddCell().SetString(common.ObjToString(v["username"]))
  1558. row.AddCell().SetString(common.ObjToString(v["phone"]))
  1559. row.AddCell().SetString(common.ObjToString(v["email"]))
  1560. row.AddCell().SetString(common.ObjToString(v["company"]))
  1561. row.AddCell().SetString(common.ObjToString(v["data_requirement"]))
  1562. row.AddCell().SetString(common.ObjToString(v["source"]))
  1563. row.AddCell().SetString(common.ObjToString(v["interest"]))
  1564. row.AddCell().SetString(gconv.Time(gconv.Int64(v["createtime"])).Format(date.Date_Full_Layout))
  1565. }
  1566. dir = "./xlsx/abh/" + fileName + ".xlsx"
  1567. err = xf.Save(dir)
  1568. case "market":
  1569. xlsxArr := []string{"姓名", "联系人电话", "公司名称", "职位", "部门", "销售线索来源", "留资时间"}
  1570. batch := FindBatch("abh")
  1571. fileName, detailName = "安博会商务合作销售线索 "+time.Now().Format(date.Date_Short_Layout)+"-"+batch, ""
  1572. xf := xlsx.NewFile()
  1573. style := xlsx.NewStyle()
  1574. style.Font.Size = 12
  1575. style.Font.Bold = true
  1576. style.Alignment.Vertical = "center"
  1577. style.Alignment.Horizontal = "center"
  1578. detailName = "今日新增安博会销售线索,请查收附件,及时跟进。"
  1579. sh, _ := xf.AddSheet("线索数据")
  1580. row1 := sh.AddRow()
  1581. for _, x := range xlsxArr {
  1582. cell := row1.AddCell()
  1583. cell.SetString(x)
  1584. cell.SetStyle(style)
  1585. }
  1586. for _, v := range data {
  1587. row := sh.AddRow()
  1588. row.AddCell().SetString(common.ObjToString(v["username"]))
  1589. row.AddCell().SetString(common.ObjToString(v["phone"]))
  1590. row.AddCell().SetString(common.ObjToString(v["company"]))
  1591. row.AddCell().SetString(common.ObjToString(v["job"]))
  1592. row.AddCell().SetString(common.ObjToString(v["branch"]))
  1593. row.AddCell().SetString(common.ObjToString(v["source"]))
  1594. row.AddCell().SetString(gconv.Time(gconv.Int64(v["createtime"])).Format(date.Date_Full_Layout))
  1595. //增加客户需求
  1596. }
  1597. dir = "./xlsx/abh/" + fileName + ".xlsx"
  1598. err = xf.Save(dir)
  1599. }
  1600. email = db.AbhEmail
  1601. if err != nil {
  1602. log.Println("xls error", err, dir)
  1603. } else {
  1604. gmail := &mail.GmailAuth{
  1605. SmtpHost: "smtp.exmail.qq.com",
  1606. SmtpPort: 465,
  1607. User: "public03@topnet.net.cn",
  1608. Pwd: "ue9Rg9Sf4CVtdm5a",
  1609. }
  1610. status := mail.GSendMail_q("剑鱼标讯", email, "", "", fileName, detailName, dir, fileName+".xlsx", gmail)
  1611. if status {
  1612. log.Println("send mail success", fileName, email)
  1613. }
  1614. }
  1615. }*/
  1616. // 安防邮件
  1617. func AFEmail(data []map[string]interface{}) {
  1618. xlsxArr := []string{"姓名", "联系方式", "邮箱", "公司名称", "咨询需求", "销售线索来源", "具体来源", "留资时间"}
  1619. batch := FindBatch("af")
  1620. fileName, detailName := "安防销售线索 "+time.Now().Format(date.Date_Short_Layout)+"-"+batch, ""
  1621. xf := xlsx.NewFile()
  1622. style := xlsx.NewStyle()
  1623. style.Font.Size = 12
  1624. style.Font.Bold = true
  1625. style.Alignment.Vertical = "center"
  1626. style.Alignment.Horizontal = "center"
  1627. detailName = "今日新增安防销售线索,请查收附件,及时跟进。"
  1628. sh, _ := xf.AddSheet("线索数据")
  1629. row1 := sh.AddRow()
  1630. for _, x := range xlsxArr {
  1631. cell := row1.AddCell()
  1632. cell.SetString(x)
  1633. cell.SetStyle(style)
  1634. }
  1635. for _, v := range data {
  1636. row := sh.AddRow()
  1637. row.AddCell().SetString(common.ObjToString(v["name"]))
  1638. row.AddCell().SetString(common.ObjToString(v["phone"]))
  1639. row.AddCell().SetString(common.ObjToString(v["email"]))
  1640. row.AddCell().SetString(common.ObjToString(v["company_name"]))
  1641. row.AddCell().SetString("")
  1642. row.AddCell().SetString("")
  1643. row.AddCell().SetString("首次使用安防新注册")
  1644. row.AddCell().SetString(gconv.String(v["time"]))
  1645. //增加客户需求
  1646. }
  1647. email := db.AfEmail
  1648. dir := "./xlsx/af/" + fileName + ".xlsx"
  1649. err := xf.Save(dir)
  1650. if err != nil {
  1651. log.Println("xls error", err, dir)
  1652. } else {
  1653. gmail := &mail.GmailAuth{
  1654. SmtpHost: db.Mail.SmtpHost,
  1655. SmtpPort: db.Mail.SmtpPort,
  1656. User: db.Mail.User,
  1657. Pwd: db.Mail.Pwd,
  1658. }
  1659. status := mail.GSendMail_q("剑鱼标讯", email, "", "", fileName, detailName, dir, "", gmail)
  1660. if status {
  1661. log.Println("send mail success", fileName, email)
  1662. }
  1663. }
  1664. }
  1665. func ABHEmail(source string, data []map[string]interface{}) {
  1666. var fileName, detailName, dir string
  1667. var err error
  1668. xlsxArr, detailName := getExcelHeaderAndDetail(source)
  1669. batch := FindBatch("abh")
  1670. fileName = fmt.Sprintf("%s %s-%s", getFileNamePrefix(source), time.Now().Format(date.Date_Short_Layout), batch)
  1671. xf := xlsx.NewFile()
  1672. style := createExcelStyle()
  1673. sh, _ := xf.AddSheet("线索数据")
  1674. addHeaderRow(sh, xlsxArr, style)
  1675. switch source {
  1676. case "user":
  1677. err = populateUserData(sh, data)
  1678. case "saleLeads", "big":
  1679. err = populateSaleLeadData(sh, data)
  1680. case "advisory":
  1681. err = populateAdvisoryData(sh, data)
  1682. case "market", "selection":
  1683. err = populateMarketData(sh, data)
  1684. }
  1685. if err == nil {
  1686. dir = fmt.Sprintf("./xlsx/abh/%s.xlsx", fileName)
  1687. err = xf.Save(dir)
  1688. }
  1689. sendEmailIfSuccessful(err, fileName, detailName, dir)
  1690. }
  1691. func getExcelHeaderAndDetail(source string) ([]string, string) {
  1692. switch source {
  1693. case "user":
  1694. return []string{"姓名", "联系方式", "邮箱", "公司名称", "咨询需求", "销售线索来源", "具体来源", "留资时间"}, "今日新增安博会销售线索,请查收附件,及时跟进。"
  1695. case "saleLeads":
  1696. return []string{"用户昵称", "姓名", "公司名称", "职位", "联系人电话", "购买条数", "用户邮箱", "已支付订单信息", "未支付订单类型", "销售线索来源", "具体来源", "数据需求"}, "今日新增安博会销售线索,请查收附件,及时跟进。"
  1697. case "big":
  1698. return []string{"用户昵称", "姓名", "公司名称", "职位", "联系人电话", "购买条数", "用户邮箱", "已支付订单信息", "未支付订单类型", "销售线索来源", "具体来源", "数据需求"}, "今日新增安博会销售线索,请查收附件,及时跟进。"
  1699. case "advisory":
  1700. return []string{"姓名", "联系方式", "邮箱", "公司名称", "咨询需求", "销售线索来源", "具体来源", "留资时间"}, "今日新增安博会销售线索,请查收附件,及时跟进。"
  1701. case "market":
  1702. return []string{"姓名", "联系人电话", "公司名称", "职位", "部门", "销售线索来源", "留资时间"}, "今日新增安博会销售线索,请查收附件,及时跟进。"
  1703. case "selection":
  1704. return []string{"姓名", "联系人电话", "公司名称", "职位", "部门", "销售线索来源", "留资时间"}, "今日新增安博会销售线索,请查收附件,及时跟进。"
  1705. default:
  1706. return nil, ""
  1707. }
  1708. }
  1709. func getFileNamePrefix(source string) string {
  1710. switch source {
  1711. case "user":
  1712. return "安博会用户注册销售线索"
  1713. case "saleLeads":
  1714. return "安博会电销销售线索"
  1715. case "big":
  1716. return "安博会大客户销售线索"
  1717. case "advisory":
  1718. return "安博会咨询服务销售线索"
  1719. case "market":
  1720. return "安博会商务合作销售线索"
  1721. default:
  1722. return "未知线索"
  1723. }
  1724. }
  1725. func createExcelStyle() *xlsx.Style {
  1726. style := xlsx.NewStyle()
  1727. style.Font.Size = 12
  1728. style.Font.Bold = true
  1729. style.Alignment.Vertical = "center"
  1730. style.Alignment.Horizontal = "center"
  1731. return style
  1732. }
  1733. func addHeaderRow(sh *xlsx.Sheet, headers []string, style *xlsx.Style) {
  1734. row := sh.AddRow()
  1735. for _, header := range headers {
  1736. cell := row.AddCell()
  1737. cell.SetString(header)
  1738. cell.SetStyle(style)
  1739. }
  1740. }
  1741. func populateUserData(sh *xlsx.Sheet, data []map[string]interface{}) error {
  1742. for _, v := range data {
  1743. row := sh.AddRow()
  1744. row.AddCell().SetString(common.ObjToString(v["name"]))
  1745. row.AddCell().SetString(common.ObjToString(v["phone"]))
  1746. row.AddCell().SetString(common.ObjToString(v["email"]))
  1747. row.AddCell().SetString(common.ObjToString(v["company_name"]))
  1748. row.AddCell().SetString("")
  1749. row.AddCell().SetString("")
  1750. row.AddCell().SetString("安博会用户注册")
  1751. row.AddCell().SetString(gconv.Time(gconv.Int64(v["createtime"])).Format(date.Date_Full_Layout))
  1752. }
  1753. return nil
  1754. }
  1755. func populateSaleLeadData(sh *xlsx.Sheet, data []map[string]interface{}) error {
  1756. sourceMap := buildSourceMap("运营部")
  1757. for _, v := range data {
  1758. row := sh.AddRow()
  1759. row.AddCell().SetString(common.ObjToString(v["usernickname"]))
  1760. row.AddCell().SetString(common.ObjToString(v["name"]))
  1761. row.AddCell().SetString(common.ObjToString(v["company"]))
  1762. row.AddCell().SetString(common.ObjToString(v["position"]))
  1763. row.AddCell().SetString(common.ObjToString(v["phone"]))
  1764. row.AddCell().SetValue(0)
  1765. row.AddCell().SetString(common.ObjToString(v["email"]))
  1766. row.AddCell().SetString("")
  1767. row.AddCell().SetString("")
  1768. row.AddCell().SetString(sourceMap[common.ObjToString(v["source"])])
  1769. row.AddCell().SetString(common.ObjToString(v["interest"]))
  1770. row.AddCell().SetString(common.ObjToString(v["data_requirement"]))
  1771. }
  1772. return nil
  1773. }
  1774. func populateAdvisoryData(sh *xlsx.Sheet, data []map[string]interface{}) error {
  1775. for _, v := range data {
  1776. row := sh.AddRow()
  1777. row.AddCell().SetString(common.ObjToString(v["username"]))
  1778. row.AddCell().SetString(common.ObjToString(v["phone"]))
  1779. row.AddCell().SetString(common.ObjToString(v["email"]))
  1780. row.AddCell().SetString(common.ObjToString(v["company"]))
  1781. row.AddCell().SetString(common.ObjToString(v["data_requirement"]))
  1782. row.AddCell().SetString(common.ObjToString(v["source"]))
  1783. row.AddCell().SetString(common.ObjToString(v["interest"]))
  1784. row.AddCell().SetString(gconv.Time(gconv.Int64(v["createtime"])).Format(date.Date_Full_Layout))
  1785. }
  1786. return nil
  1787. }
  1788. func populateMarketData(sh *xlsx.Sheet, data []map[string]interface{}) error {
  1789. for _, v := range data {
  1790. row := sh.AddRow()
  1791. row.AddCell().SetString(common.ObjToString(v["username"]))
  1792. row.AddCell().SetString(common.ObjToString(v["phone"]))
  1793. row.AddCell().SetString(common.ObjToString(v["company"]))
  1794. row.AddCell().SetString(common.ObjToString(v["job"]))
  1795. row.AddCell().SetString(common.ObjToString(v["branch"]))
  1796. row.AddCell().SetString(common.ObjToString(v["source"]))
  1797. row.AddCell().SetString(gconv.Time(gconv.Int64(v["createtime"])).Format(date.Date_Full_Layout))
  1798. }
  1799. return nil
  1800. }
  1801. func sendEmailIfSuccessful(err error, fileName, detailName, dir string) {
  1802. if err != nil {
  1803. log.Println("xls error", err, dir)
  1804. return
  1805. }
  1806. email := db.AbhEmail
  1807. gmail := &mail.GmailAuth{
  1808. SmtpHost: db.Mail.SmtpHost,
  1809. SmtpPort: db.Mail.SmtpPort,
  1810. User: db.Mail.User,
  1811. Pwd: db.Mail.Pwd,
  1812. }
  1813. status := mail.GSendMail_q("剑鱼标讯", email, "", "", fileName, detailName, dir, fileName+".xlsx", gmail)
  1814. if status {
  1815. log.Println("send mail success", fileName, email)
  1816. }
  1817. }
  1818. func inviteUser() {
  1819. log.Println("邀请用户处理开始")
  1820. //判断节假日
  1821. runOk := getRunOk()
  1822. if !runOk {
  1823. log.Println("不是工作日,任务暂停")
  1824. return
  1825. }
  1826. rebindTimeEnd := cfg.InviteTime
  1827. sql := fmt.Sprintf(`select * from user_statistics where createTime > "%s" order by createTime asc`, rebindTimeEnd)
  1828. //sql := fmt.Sprintf(`select * from user_statistics where createTime = "%s" order by createTime asc`, rebindTimeEnd)
  1829. data := BiService.SelectBySql(sql)
  1830. if data != nil && *data != nil && len(*data) > 0 {
  1831. for _, v := range *data {
  1832. rebindTimeEnd = common.ObjToString(v["createTime"])
  1833. event := gconv.Int64(v["event"])
  1834. switch event {
  1835. case 1:
  1836. v["sourceCode"] = "736"
  1837. case 2:
  1838. v["sourceCode"] = "737"
  1839. case 3:
  1840. v["sourceCode"] = "738"
  1841. }
  1842. v["user_id"] = gconv.String(v["userId"])
  1843. ok1, ok2, _ := FormatData(v, "invite")
  1844. if !ok1 {
  1845. log.Println("线索卡点", "invite", v, rebindTimeEnd)
  1846. } else {
  1847. if !ok2 {
  1848. log.Println("用户分配已达上限", "invite", v, rebindTimeEnd)
  1849. }
  1850. }
  1851. }
  1852. cfg.InviteTime = rebindTimeEnd
  1853. common.WriteSysConfig(&cfg)
  1854. }
  1855. log.Println("邀请用户处理结束")
  1856. }