jobutil.go 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917
  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)
  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. data := Mysql.SelectBySql(sql)
  493. if data != nil && *data != nil && len(*data) > 0 {
  494. for _, v := range *data {
  495. order_status := common.IntAll(v["order_status"])
  496. is_backstage_order := common.IntAll(v["is_backstage_order"])
  497. product_type_str1 := `"大会员","VIP订阅","数据流量包","历史数据"`
  498. product_type := common.ObjToString(v["product_type"])
  499. if order_status == 0 && is_backstage_order == 0 && strings.Contains(product_type_str1, product_type) {
  500. ok1, ok2, _ := FormatData(v, "orders")
  501. if !ok1 {
  502. common.WriteSysConfig(&cfg)
  503. log.Println("线索卡点", "orders", v, selectTimeEnd, selectTimeStart)
  504. } else {
  505. if !ok2 {
  506. log.Println("用户分配已达上限", "orders", v, selectTimeEnd, selectTimeStart)
  507. common.WriteSysConfig(&cfg)
  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. } else {
  529. if !ok2 {
  530. log.Println("用户分配已达上限", "readClue", v, lastReadClueTime)
  531. common.WriteSysConfig(&cfg)
  532. }
  533. }
  534. cfg.LastReadClueTime = common.ObjToString(v["updatetime"])
  535. }
  536. }
  537. common.WriteSysConfig(&cfg)
  538. log.Println("读表进线索定时任务结束")
  539. }
  540. // 新注册用户 5分钟一次
  541. func users() {
  542. //判断节假日
  543. runOk := getRunOk()
  544. if !runOk {
  545. log.Println("不是工作日,任务暂停")
  546. return
  547. }
  548. //新用户注册后5分钟内进入线索 C
  549. log.Println("新注册用户定时任务开始")
  550. selectTimeEnd := cfg.LastUserId
  551. 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)
  552. data := TiDb.SelectBySql(sql)
  553. abhList := []map[string]interface{}{}
  554. if data != nil && *data != nil && len(*data) > 0 {
  555. for k, v := range *data {
  556. //判断用户是否有小程序切使用过剑鱼其他产品
  557. createtime := common.ObjToString(v["createtime"])
  558. ok1, ok2, ok3 := FormatData(v, "users")
  559. if !ok3 {
  560. cfg.LastUserId = createtime
  561. //安博会数据
  562. abhList = append(abhList, v)
  563. continue
  564. }
  565. if !ok1 {
  566. log.Println("线索卡点", "users", v, selectTimeEnd)
  567. } else {
  568. if !ok2 {
  569. log.Println("用户分配已达上限", "users", v, selectTimeEnd)
  570. }
  571. }
  572. if k == len(*data)-1 {
  573. cfg.LastUserId = createtime
  574. }
  575. }
  576. if len(abhList) > 0 {
  577. //安博会发邮件高翔
  578. ABHEmail("user", abhList)
  579. }
  580. }
  581. common.WriteSysConfig(&cfg)
  582. selectXcxTimeEnd := cfg.LastXcxUserId
  583. xcxSql := fmt.Sprintf(`SELECT DISTINCT
  584. aa.mgo_id as userId,
  585. cc.NAME as industry ,
  586. aa.phone,
  587. IF
  588. ( aa.phone_time IS NULL, aa.create_time, aa.phone_time ) as time
  589. FROM
  590. debris_product.miniprogram_user aa
  591. INNER JOIN debris_product.miniprogram bb ON (
  592. aa.phone <> ''
  593. AND
  594. IF
  595. ( aa.phone_time IS NULL, aa.create_time, aa.phone_time ) > '%s'
  596. AND aa.miniprogram_code = bb.CODE
  597. )
  598. INNER JOIN debris_product.industry cc ON ( bb.industry_code = cc.CODE )
  599. WHERE
  600. NOT EXISTS (
  601. SELECT
  602. 1
  603. FROM
  604. debris_product.miniprogram_user a
  605. INNER JOIN debris_product.miniprogram b ON (
  606. aa.unionid = a.unionid
  607. AND aa.miniprogram_code = a.miniprogram_code
  608. AND aa.id != a.id
  609. AND
  610. IF
  611. ( a.phone_time IS NULL, a.create_time, a.phone_time ) <= '%s'
  612. AND a.miniprogram_code = b.CODE
  613. )
  614. INNER JOIN debris_product.miniprogram_user c ON ( a.unionid = c.unionid AND b.CODE = c.miniprogram_code ))
  615. ORDER BY time
  616. `, selectXcxTimeEnd, selectXcxTimeEnd)
  617. xcxData := debrisProductMysql.SelectBySql(xcxSql)
  618. log.Println("11122", selectXcxTimeEnd, xcxData)
  619. if xcxData != nil && *xcxData != nil && len(*xcxData) > 0 {
  620. afList := []map[string]interface{}{}
  621. for k, v := range *xcxData {
  622. //判断用户是否有小程序切使用过剑鱼其他产品
  623. //判断uid
  624. uId := ""
  625. for i := 0; i < 10; i++ {
  626. phone := common.ObjToString(v["phone"])
  627. contactsData := TiDb.SelectBySql("select * from dwd_f_userbase_contacts where phone = ? and is_delete = 1", phone)
  628. if contactsData != nil && len(*contactsData) > 0 {
  629. if common.ObjToString((*contactsData)[0]["baseinfo_id"]) != "" {
  630. uId = common.ObjToString((*contactsData)[0]["baseinfo_id"])
  631. }
  632. }
  633. if uId == "" {
  634. time.Sleep(1 * time.Minute)
  635. } else {
  636. break
  637. }
  638. }
  639. updatetime := common.ObjToString(v["time"])
  640. if uId == "" {
  641. cfg.LastXcxUserId = updatetime
  642. continue
  643. }
  644. ok1, ok2, _ := FormatData(v, "xcxusers")
  645. /*if !ok3 {
  646. //首次使用"安防"小程序新注册用户
  647. afList = append(afList, v)
  648. cfg.LastXcxUserId = updatetime
  649. continue
  650. }*/
  651. if !ok1 {
  652. common.WriteSysConfig(&cfg)
  653. log.Println("小程序用户分配线索卡点", "xcxusers", v, selectXcxTimeEnd)
  654. } else {
  655. if !ok2 {
  656. log.Println("小程序用户分配已达上限", "xcxusers", v, selectXcxTimeEnd)
  657. common.WriteSysConfig(&cfg)
  658. }
  659. }
  660. if k == len(*xcxData)-1 {
  661. cfg.LastXcxUserId = updatetime
  662. }
  663. }
  664. if len(afList) > 0 {
  665. //发邮件给张文福
  666. AFEmail(afList)
  667. }
  668. }
  669. common.WriteSysConfig(&cfg)
  670. log.Println("新注册用户定时任务结束")
  671. }
  672. // 留资 5分钟一次
  673. func saleLeads() {
  674. //判断节假日
  675. runOk := getRunOk()
  676. if !runOk {
  677. log.Println("不是工作日,任务暂停")
  678. return
  679. }
  680. //留资后5分钟内进入线索
  681. //分为免费留资和付费留资 付费B 免费C
  682. log.Println("用户留资定时任务开始")
  683. session := Mgo.GetMgoConn()
  684. lastId := cfg.LastId
  685. abhList := []map[string]interface{}{}
  686. defer func() {
  687. Mgo.DestoryMongoConn(session)
  688. }()
  689. query := map[string]interface{}{}
  690. if lastId != "" {
  691. query["_id"] = map[string]interface{}{"$gt": mongodb.StringTOBsonId(lastId)}
  692. }
  693. log.Println("query :", query)
  694. iter := session.DB(db.Mgo.DbName).C("saleLeads").Find(&query).Sort("_id").Iter()
  695. thisData := map[string]interface{}{}
  696. for {
  697. if !iter.Next(&thisData) {
  698. break
  699. }
  700. sourceCode := common.ObjToString(thisData["source"])
  701. if sourceCode == "" {
  702. log.Println("留资没有source", thisData)
  703. continue
  704. }
  705. //
  706. filterArr := []string{"-pc", "-app", "-wx", "-h5"}
  707. sourceMap := map[string]string{}
  708. 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`)
  709. if saleSource != nil && len(*saleSource) > 0 {
  710. for _, v := range *saleSource {
  711. source := common.ObjToString(v["source"])
  712. name := common.ObjToString(v["name"])
  713. for _, s := range filterArr {
  714. name = strings.ReplaceAll(name, s, "")
  715. }
  716. sourceMap[source] = name
  717. }
  718. }
  719. if sourceMap[sourceCode] != "" {
  720. continue
  721. }
  722. ok1, ok2, ok3 := FormatData(thisData, "saleLeads")
  723. if !ok3 {
  724. cfg.LastId = mongodb.BsonIdToSId(thisData["_id"])
  725. //安博会数据
  726. abhList = append(abhList, thisData)
  727. continue
  728. }
  729. if !ok1 {
  730. log.Println("线索卡点", "saleLeads", thisData, lastId)
  731. } else {
  732. if !ok2 {
  733. log.Println("用户分配已达上限", "saleLeads", thisData, lastId)
  734. }
  735. }
  736. cfg.LastId = mongodb.BsonIdToSId(thisData["_id"])
  737. }
  738. if len(abhList) > 0 {
  739. //安博会发邮件高翔
  740. ABHEmail("saleLeads", abhList)
  741. }
  742. common.WriteSysConfig(&cfg)
  743. log.Println("用户留资定时任务结束")
  744. }
  745. func userbase() {
  746. log.Println("userbase定时任务开始")
  747. timeUnix := time.Now().Unix()
  748. selectTimeStart := time.Unix(timeUnix-1800, 0).Format("2006-01-02 15:04:05")
  749. selectTimeEnd := time.Unix(timeUnix, 0).Format("2006-01-02 15:04:05")
  750. sql := fmt.Sprintf(`SELECT
  751. a.phone,b.uid,a.baseinfo_id,b.l_registedate,a.createtime,b.id,b.userid
  752. FROM
  753. dwd_f_userbase_contacts a
  754. INNER JOIN dwd_f_userbase_baseinfo b ON
  755. b.status= 1
  756. AND a.phone = b.phone and a.baseinfo_id= b.uid and a.source ="0101"
  757. and a.phone is not NULL
  758. and a.createtime >="%s"
  759. and a.createtime <"%s"
  760. and a.is_delete=1
  761. ORDER BY a.createtime `, selectTimeStart, selectTimeEnd)
  762. data := TiDb.SelectBySql(sql)
  763. if data != nil && *data != nil && len(*data) > 0 {
  764. for _, v := range *data {
  765. phone := common.ObjToString(v["phone"])
  766. uId := common.ObjToString(v["uid"])
  767. userId := common.ObjToString(v["userid"])
  768. registedate := common.ObjToString(v["l_registedate"])
  769. name := common.ObjToString(v["name"])
  770. nowTime := time.Now().Format(date.Date_Full_Layout)
  771. layout := "2006-01-02 15:04:05"
  772. createtime := gconv.String(v["createtime"])
  773. createtimeInt64, _ := time.Parse(layout, createtime)
  774. registedateInt64, _ := time.Parse(layout, registedate)
  775. count := TiDb.CountBySql("select count(1) as count from dwd_f_crm_clue_info where uid = ?", uId)
  776. if createtimeInt64.Unix()-registedateInt64.Unix() < int64(db.RegTimes)*86400 {
  777. if count == 0 {
  778. //注册少于7天、走新增
  779. data := TiDb.FindOne("dwd_f_userbase_baseinfo", map[string]interface{}{
  780. "id": gconv.Int64(v["id"]),
  781. }, "", "")
  782. if data != nil && len(*data) > 0 {
  783. ok1, ok2, _ := FormatData(v, "users")
  784. if !ok1 {
  785. log.Println("线索卡点", "userbase uid", v, uId)
  786. } else {
  787. if !ok2 {
  788. log.Println("用户分配已达上限", "userbase uid", v, uId)
  789. }
  790. }
  791. }
  792. }
  793. continue
  794. }
  795. registedates, _ := time.Parse(date.Date_Full_Layout, registedate)
  796. log.Println("userbase uid 线索数量 ", count)
  797. log.Println("userbase uid 注册时间 ", registedates)
  798. if count == 0 {
  799. clueId := int64(0)
  800. sql := fmt.Sprintf(`select * from freeClubSign where mogUserId="%s" and sub_again_date > "%s" `, userId, selectTimeEnd)
  801. data := BiService.SelectBySql(sql)
  802. if len(*data) > 0 && userId != "" {
  803. clueId = TiDb.Insert("dwd_f_crm_clue_info", map[string]interface{}{
  804. "userid": userId,
  805. "uid": uId,
  806. "is_assign": 0,
  807. "comeintime": nowTime,
  808. "createtime": nowTime,
  809. "updatetime": nowTime,
  810. "cluename": phone,
  811. "top_cluetype": "532",
  812. "sub_cluetype": "670",
  813. "trailstatus": "01",
  814. "name": name,
  815. "phone": phone,
  816. "comeintime_open": nowTime,
  817. "comeinsource_open": 1,
  818. "FREEZE_TIME": nowTime,
  819. })
  820. } else {
  821. clueId = TiDb.Insert("dwd_f_crm_clue_info", map[string]interface{}{
  822. "userid": userId,
  823. "uid": uId,
  824. "is_assign": 0,
  825. "comeintime": nowTime,
  826. "createtime": nowTime,
  827. "updatetime": nowTime,
  828. "cluename": phone,
  829. "top_cluetype": "532",
  830. "sub_cluetype": "475",
  831. "trailstatus": "01",
  832. "name": name,
  833. "phone": phone,
  834. "comeintime_open": nowTime,
  835. "comeinsource_open": 1,
  836. "FREEZE_TIME": nowTime,
  837. })
  838. }
  839. if clueId > 0 {
  840. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  841. "clue_id": clueId,
  842. "position_id": -1,
  843. "change_type": "创建线索",
  844. "new_value": "系统自动创建",
  845. "createtime": nowTime,
  846. "BCPCID": common.GetRandom(32),
  847. "operator_id": -1,
  848. })
  849. }
  850. }
  851. }
  852. }
  853. log.Println("userbase定时任务结束")
  854. }
  855. func getRunOk() bool {
  856. currentTime, runOk := time.Now(), false
  857. if currentTime.Weekday() == time.Sunday {
  858. isok := false
  859. for k, v := range DateMap {
  860. if currentTime.Format(date.Date_Short_Layout) == k && v == 2 {
  861. isok = true
  862. }
  863. }
  864. if isok {
  865. runOk = true
  866. }
  867. } else {
  868. isok := true
  869. for k, v := range DateMap {
  870. if currentTime.Format(date.Date_Short_Layout) == k && v == 1 {
  871. isok = false
  872. }
  873. }
  874. if isok {
  875. runOk = true
  876. }
  877. }
  878. return runOk
  879. }
  880. func getAreaCode(userId string) (code string) {
  881. followData := Base.Find("follow_project_monitor", map[string]interface{}{"s_userid": userId}, "", "", -1, -1)
  882. sidArr := []string{}
  883. if followData != nil && len(*followData) > 0 {
  884. for _, v := range *followData {
  885. infoId := common.ObjToString(v["s_id"])
  886. sidArr = append(sidArr, infoId)
  887. }
  888. }
  889. if len(sidArr) > 0 {
  890. query := `{"query": {"bool": {"must": [{"terms": {"_id": ["%s"]}}],"must_not": [],"should": []}}}`
  891. query = fmt.Sprintf(query, strings.Join(sidArr, `","`))
  892. biddingData := Es.Get("bidding", "bidding", query)
  893. if biddingData != nil && len(*biddingData) > 0 {
  894. codeMap := map[string]string{}
  895. codeArr := []string{}
  896. for _, v := range *biddingData {
  897. area := common.ObjToString(v["area"])
  898. address := common.ObjToString(v["city"])
  899. if address == "" {
  900. address = area
  901. }
  902. codeMap[address] = AreaCode[address]
  903. }
  904. if len(codeMap) > 0 {
  905. for _, v := range codeMap {
  906. codeArr = append(codeArr, v)
  907. }
  908. }
  909. if len(codeArr) > 0 {
  910. code = strings.Join(codeArr, ",")
  911. }
  912. }
  913. }
  914. log.Println("code ", code)
  915. return
  916. }
  917. func getClueType(item string, data map[string]interface{}, sourceCode string, sourceId int64) (pcode, code, level, topname, subname string) {
  918. if item == "orders" {
  919. productType := common.ObjToString(data["product_type"])
  920. pcode = "1"
  921. level = "A"
  922. topname = "提交订单未支付"
  923. if productType == "VIP订阅" {
  924. code = "6"
  925. subname = "超级订阅"
  926. } else if productType == "大会员" {
  927. code = "7"
  928. subname = "大会员"
  929. } else if productType == "数据流量包" {
  930. code = "8"
  931. subname = "数据流量包"
  932. } else if productType == "历史数据" {
  933. code = "9"
  934. subname = "数据自助导出"
  935. }
  936. } else if item == "users" {
  937. pcode = "4"
  938. code = "154"
  939. level = "C"
  940. topname = "新增注册"
  941. subname = "新增注册用户"
  942. } else if item == "message" {
  943. pcode = "532"
  944. code = "477"
  945. level = "B"
  946. topname = "其他"
  947. subname = "机器人客服主动咨询"
  948. } else if item == "readClue" {
  949. level = "A"
  950. topname = "超级订阅临期用户"
  951. pcode = "614"
  952. if sourceId == 1 {
  953. code = "615"
  954. subname = "60天后到期"
  955. } else if sourceId == 2 {
  956. code = "616"
  957. subname = "45天后到期"
  958. } else if sourceId == 3 {
  959. code = "617"
  960. subname = "15天后到期"
  961. } else {
  962. code = "618"
  963. subname = "7天后到期"
  964. }
  965. } else if item == "xcxusers" {
  966. level = "S"
  967. pcode = "532"
  968. code = "477"
  969. topname = "其他"
  970. switch sourceCode {
  971. case "环境采购":
  972. pcode = "532"
  973. code = "696"
  974. subname = `首次使用“环境”小程序`
  975. case "物业":
  976. pcode = "532"
  977. code = "693"
  978. subname = `首次使用“物业”小程序`
  979. case "印务商机":
  980. pcode = "532"
  981. code = "697"
  982. subname = `首次使用“印务”小程序`
  983. case "家具":
  984. pcode = "532"
  985. code = "695"
  986. subname = `首次使用“家具”小程序`
  987. case "车辆租赁":
  988. pcode = "532"
  989. code = "694"
  990. subname = `首次使用“车辆”小程序`
  991. case "安防":
  992. pcode = "532"
  993. code = "701"
  994. subname = `首次使用“安防”小程序`
  995. }
  996. } else if item == "allocation" {
  997. pcode = "532"
  998. code = "671"
  999. level = "D"
  1000. pcodeData := TiDb.FindOne("dwd_d_crm_cluetype_code", map[string]interface{}{"code": pcode}, "", "")
  1001. if pcodeData != nil && len(*pcodeData) > 0 {
  1002. topname = common.ObjToString((*pcodeData)["name"])
  1003. }
  1004. pcodeData = TiDb.FindOne("dwd_d_crm_cluetype_code", map[string]interface{}{"code": code}, "", "")
  1005. if pcodeData != nil && len(*pcodeData) > 0 {
  1006. subname = common.ObjToString((*pcodeData)["name"])
  1007. }
  1008. } else if item == "rebind" {
  1009. pcode = "532"
  1010. code = "670"
  1011. level = "D"
  1012. pcodeData := TiDb.FindOne("dwd_d_crm_cluetype_code", map[string]interface{}{"code": pcode}, "", "")
  1013. if pcodeData != nil && len(*pcodeData) > 0 {
  1014. topname = common.ObjToString((*pcodeData)["name"])
  1015. }
  1016. pcodeData = TiDb.FindOne("dwd_d_crm_cluetype_code", map[string]interface{}{"code": code}, "", "")
  1017. if pcodeData != nil && len(*pcodeData) > 0 {
  1018. subname = common.ObjToString((*pcodeData)["name"])
  1019. }
  1020. } else if item == "invite" {
  1021. codeData := TiDb.FindOne("dwd_d_crm_cluetype_code", map[string]interface{}{"code": sourceCode}, "", "")
  1022. if codeData != nil && len(*codeData) > 0 {
  1023. pcode = common.ObjToString((*codeData)["pcode"])
  1024. code = common.ObjToString((*codeData)["code"])
  1025. level = common.ObjToString((*codeData)["clue_level"])
  1026. subname = common.ObjToString((*codeData)["name"])
  1027. pcodeData := TiDb.FindOne("dwd_d_crm_cluetype_code", map[string]interface{}{"code": pcode}, "", "")
  1028. if pcodeData != nil && len(*pcodeData) > 0 {
  1029. topname = common.ObjToString((*pcodeData)["name"])
  1030. }
  1031. }
  1032. } else {
  1033. if sourceCode != "" {
  1034. codeData := TiDb.FindOne("dwd_d_crm_cluetype_code", map[string]interface{}{"source": sourceCode}, "", "")
  1035. if codeData != nil && len(*codeData) > 0 {
  1036. pcode = common.ObjToString((*codeData)["pcode"])
  1037. code = common.ObjToString((*codeData)["code"])
  1038. level = common.ObjToString((*codeData)["clue_level"])
  1039. subname = common.ObjToString((*codeData)["name"])
  1040. pcodeData := TiDb.FindOne("dwd_d_crm_cluetype_code", map[string]interface{}{"code": pcode}, "", "")
  1041. if pcodeData != nil && len(*pcodeData) > 0 {
  1042. topname = common.ObjToString((*pcodeData)["name"])
  1043. }
  1044. }
  1045. }
  1046. }
  1047. return
  1048. }
  1049. // 获取自动分配的人
  1050. func autoDraw(mode, cluename, phone string, isGroup, isCommerce int) (positionId int64, seatNumber, saleName string, saleData []map[string]interface{}, isOk, isFreeze bool, noticePositionId int64) {
  1051. isOk = false
  1052. isFreeze = false
  1053. if TiDb.Count("dwd_f_crm_clue_info", map[string]interface{}{"phone": phone, "is_assign": 1}) == 0 { //线索没销售进入,有销售走分配次数最少的逻辑
  1054. if isGroup == 0 && isCommerce == 1 && cluename != "" { //非集团在工商库线索名不为空
  1055. //cdata := TiDb.Find("dwd_f_crm_clue_info", map[string]interface{}{"cluename": cluename, "is_assign": 1}, "", "", -1, -1)
  1056. 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)
  1057. if cdata != nil && len(*cdata) > 0 { //找到了公司有人在跟进
  1058. isOk = true
  1059. pdata := TiDb.SelectBySql(`select * from dwd_f_crm_personnel_management where seat_number is not null and seat_number != ""`)
  1060. if pdata == nil {
  1061. positionId = 0
  1062. seatNumber = ""
  1063. saleName = ""
  1064. return
  1065. }
  1066. saleData = *pdata
  1067. cdataNew := []map[string]interface{}{}
  1068. if len(*cdata) > 1 {
  1069. //可能有多个人跟进
  1070. personMap := map[int64]bool{}
  1071. upperLimitPersonMap := map[int64]bool{}
  1072. upperLimitCdataNew := []map[string]interface{}{}
  1073. upperLimitCount := 0
  1074. isFull := false
  1075. for _, m := range *cdata {
  1076. positionid1 := gconv.Int64(m["position_id"])
  1077. for _, v := range *pdata {
  1078. resign := common.IntAll(v["resign"])
  1079. assign_type := common.IntAll(v["assign_type"])
  1080. role_id := common.IntAll(v["role_id"])
  1081. if positionid1 == common.Int64All(v["position_id"]) {
  1082. if resign == 0 && (assign_type == 1 || role_id == 8) {
  1083. if !FindUpperLimit(gconv.String(positionid1), mode, true) {
  1084. personMap[positionid1] = true
  1085. m["saleName"] = common.ObjToString(v["name"])
  1086. cdataNew = append(cdataNew, m)
  1087. } else {
  1088. upperLimitCount++
  1089. upperLimitPersonMap[positionid1] = true
  1090. m["saleName"] = common.ObjToString(v["name"])
  1091. upperLimitCdataNew = append(upperLimitCdataNew, m)
  1092. }
  1093. }
  1094. }
  1095. }
  1096. }
  1097. if len(cdataNew) == 0 && len(upperLimitCdataNew) > 0 {
  1098. //没有达上限的人数为0 全部都是达上限的
  1099. personMap = upperLimitPersonMap
  1100. cdataNew = upperLimitCdataNew
  1101. isFull = true
  1102. }
  1103. //查询是否都有没有离职
  1104. if len(personMap) != 0 && len(cdataNew) > 0 {
  1105. layout := "2006-01-02 15:04:05"
  1106. //有人没有离职
  1107. data := map[string]interface{}{}
  1108. trailTime := int64(0)
  1109. for _, m := range cdataNew {
  1110. currentTime := int64(0)
  1111. if gconv.String(m["trail_time"]) == "" {
  1112. continue
  1113. }
  1114. t, _ := time.Parse(layout, gconv.String(m["trail_time"]))
  1115. currentTime = t.Unix()
  1116. if currentTime > trailTime {
  1117. trailTime = currentTime
  1118. data = m
  1119. }
  1120. }
  1121. if trailTime == 0 {
  1122. //需要查看通话记录
  1123. lastRingTime := int64(0)
  1124. for _, m := range cdataNew {
  1125. currentTime := int64(0)
  1126. if gconv.String(m["last_ring_time"]) == "" {
  1127. continue
  1128. }
  1129. t, _ := time.Parse(layout, gconv.String(m["last_ring_time"]))
  1130. currentTime = t.Unix()
  1131. if currentTime > lastRingTime {
  1132. lastRingTime = currentTime
  1133. data = m
  1134. }
  1135. }
  1136. if lastRingTime != 0 {
  1137. positionId = common.Int64All(data["position_id"])
  1138. noticePositionId = positionId
  1139. seatNumber = common.ObjToString(data["seatNumber"])
  1140. saleName = common.ObjToString(data["saleName"])
  1141. if isFull {
  1142. isFreeze = true
  1143. noticePositionId = positionId
  1144. positionId = 0
  1145. seatNumber = ""
  1146. saleName = ""
  1147. }
  1148. return
  1149. } else {
  1150. count := 0
  1151. //线索数量判断
  1152. for i, v := range cdataNew {
  1153. if i == 0 {
  1154. count = gconv.Int(v["count"])
  1155. data = v
  1156. } else {
  1157. if count < gconv.Int(v["count"]) {
  1158. count = gconv.Int(v["count"])
  1159. data = v
  1160. }
  1161. }
  1162. }
  1163. positionId = common.Int64All(data["position_id"])
  1164. noticePositionId = positionId
  1165. saleName = common.ObjToString(data["saleName"])
  1166. seatNumber = common.ObjToString(data["seatNumber"])
  1167. if isFull {
  1168. isFreeze = true
  1169. noticePositionId = positionId
  1170. positionId = 0
  1171. seatNumber = ""
  1172. saleName = ""
  1173. }
  1174. return
  1175. }
  1176. } else {
  1177. positionId = common.Int64All(data["position_id"])
  1178. noticePositionId = positionId
  1179. seatNumber = common.ObjToString(data["seatNumber"])
  1180. saleName = common.ObjToString(data["saleName"])
  1181. if isFull {
  1182. isFreeze = true
  1183. noticePositionId = positionId
  1184. positionId = 0
  1185. seatNumber = ""
  1186. saleName = ""
  1187. }
  1188. return
  1189. }
  1190. }
  1191. } else {
  1192. //只有一人跟进
  1193. //(1)该销售人员未离职,则继续分配给该销售人员(保持现状);
  1194. //该销售人员已离职,则随机分配
  1195. positionId = common.Int64All((*cdata)[0]["position_id"])
  1196. noticePositionId = positionId
  1197. seatNumber = common.ObjToString((*cdata)[0]["seatNumber"])
  1198. for _, v := range *pdata {
  1199. resign := common.IntAll(v["resign"])
  1200. assign_type := common.IntAll(v["assign_type"])
  1201. role_id := common.IntAll(v["role_id"])
  1202. if positionId == common.Int64All(v["position_id"]) {
  1203. if resign == 0 && (assign_type == 1 || role_id == 8) {
  1204. if FindUpperLimit(gconv.String(positionId), mode, true) {
  1205. isFreeze = true
  1206. positionId = 0
  1207. seatNumber = ""
  1208. saleName = ""
  1209. break
  1210. } else {
  1211. saleName = common.ObjToString(v["name"])
  1212. return
  1213. }
  1214. }
  1215. }
  1216. }
  1217. }
  1218. }
  1219. }
  1220. }
  1221. positionId = 0
  1222. seatNumber = ""
  1223. saleName = ""
  1224. query := `select * from dwd_f_crm_personnel_management where assign_type = 1 and`
  1225. if mode == "A" {
  1226. query += ` assign_level like "%A%"`
  1227. } else if mode == "B" {
  1228. query += ` assign_level like "%B%"`
  1229. } else if mode == "D" {
  1230. query += ` assign_level like "%D%"`
  1231. } else if mode == "C" {
  1232. query += ` assign_level like "%C%"`
  1233. } else if mode == "S" {
  1234. query += ` assign_level like "%S%"`
  1235. }
  1236. data := TiDb.SelectBySql(query)
  1237. if data != nil && len(*data) > 0 {
  1238. saleData = *data
  1239. sql := "select * from dwd_f_crm_clue_autodraw_record where clue_level = ?"
  1240. countData := TiDb.SelectBySql(sql, mode)
  1241. if countData != nil && len(*countData) > 0 {
  1242. for _, v := range *data {
  1243. isOk := false //判断是否有新员工
  1244. for _, vv := range *countData {
  1245. if common.Int64All(v["position_id"]) == common.Int64All(vv["position_id"]) {
  1246. if common.IntAll(v["resign"]) == 0 {
  1247. vv["status"] = 1
  1248. } else {
  1249. vv["status"] = 2
  1250. }
  1251. isOk = true
  1252. }
  1253. }
  1254. if !isOk { //有新员工直接分给新员工
  1255. positionId = common.Int64All(v["position_id"])
  1256. saleName = common.ObjToString(v["name"])
  1257. log.Println("新员工, ", positionId, saleName)
  1258. rData := TiDb.FindOne("dwd_f_crm_clue_autodraw_record", map[string]interface{}{"clue_level": mode}, "", "count desc")
  1259. TiDb.Insert("dwd_f_crm_clue_autodraw_record", map[string]interface{}{
  1260. "position_id": positionId,
  1261. "clue_level": mode,
  1262. "count": common.Int64All((*rData)["count"]),
  1263. })
  1264. break
  1265. }
  1266. }
  1267. if positionId == 0 {
  1268. res := int64(0)
  1269. countres := 0
  1270. for _, v := range *countData {
  1271. if common.IntAll(v["status"]) == 1 {
  1272. if FindUpperLimit(gconv.String(v["position_id"]), mode, false) {
  1273. continue
  1274. }
  1275. if countres == 0 {
  1276. res = common.Int64All(v["count"])
  1277. positionId = common.Int64All(v["position_id"])
  1278. } else {
  1279. if common.Int64All(v["count"]) <= res {
  1280. res = common.Int64All(v["count"])
  1281. positionId = common.Int64All(v["position_id"])
  1282. }
  1283. }
  1284. countres++
  1285. }
  1286. }
  1287. log.Println(444, res)
  1288. }
  1289. } else {
  1290. for _, kv := range *data {
  1291. positionId1 := gconv.String(kv["position_id"])
  1292. if !FindUpperLimit(positionId1, "", false) {
  1293. positionId = common.Int64All(kv["position_id"])
  1294. saleName = common.ObjToString(kv["name"])
  1295. rData := TiDb.FindOne("dwd_f_crm_clue_autodraw_record", map[string]interface{}{"clue_level": mode}, "", "count desc")
  1296. if rData != nil && len(*rData) > 0 {
  1297. TiDb.Insert("dwd_f_crm_clue_autodraw_record", map[string]interface{}{
  1298. "position_id": positionId,
  1299. "clue_level": mode,
  1300. "count": common.Int64All((*rData)["count"]),
  1301. })
  1302. } else {
  1303. TiDb.Insert("dwd_f_crm_clue_autodraw_record", map[string]interface{}{
  1304. "position_id": positionId,
  1305. "clue_level": mode,
  1306. "count": 0,
  1307. })
  1308. }
  1309. break
  1310. }
  1311. }
  1312. }
  1313. for _, v := range *data {
  1314. if positionId == common.Int64All(v["position_id"]) {
  1315. seatNumber = common.ObjToString(v["seat_number"])
  1316. saleName = common.ObjToString(v["name"])
  1317. }
  1318. }
  1319. }
  1320. return
  1321. }
  1322. func getPositionId(phone string) (positionId int64) {
  1323. userData, ok := Mgo.FindOne("user", map[string]interface{}{"s_phone": phone})
  1324. if ok && userData != nil && len(*userData) > 0 {
  1325. userId := common.Int64All((*userData)["base_user_id"])
  1326. positionData := Base.FindOne("base_position", map[string]interface{}{"type": 1, "ent_id": 25917, "user_id": userId}, "", "") //TODO ent_id
  1327. if positionData != nil && len(*positionData) > 0 {
  1328. positionId = common.Int64All((*positionData)["id"])
  1329. }
  1330. }
  1331. return
  1332. }
  1333. func GetCompanyType(companyName string) (int, int) {
  1334. //是否是集团
  1335. isGroup, isCommerce := 0, 0
  1336. if c := TiDb.CountBySql(`select count(1) from group_company_name where company_name=?`, companyName); c > 0 {
  1337. isGroup = 1
  1338. }
  1339. //是否在工商库
  1340. if c := MgoQyxy.Count("qyxy_std", map[string]interface{}{"company_name": companyName, "company_type": map[string]interface{}{"$ne": "个体工商户"}}); c > 0 {
  1341. isCommerce = 1
  1342. }
  1343. return isGroup, isCommerce
  1344. }
  1345. // 查询是否达上限
  1346. func FindUpperLimit(positionId string, level string, isAdd bool) bool {
  1347. if positionId == "" {
  1348. return false
  1349. }
  1350. 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
  1351. if isFull && isAdd && level != "" {
  1352. TiDb.UpdateOrDeleteBySql(`update dwd_f_crm_clue_autodraw_record set count = count + 1 where position_id = ? and clue_level = ?`, positionId, level)
  1353. }
  1354. return isFull
  1355. }
  1356. func getSeatNumberPositionId(seatNumber string) (positionId int64) {
  1357. saleData := TiDb.FindOne("dwd_f_crm_personnel_management", map[string]interface{}{"seat_number": seatNumber}, "", "")
  1358. if saleData != nil && len(*saleData) > 0 {
  1359. positionId = common.Int64All((*saleData)["position_id"])
  1360. }
  1361. return
  1362. }
  1363. // 重新关注用户处理
  1364. func rebind() {
  1365. log.Println("重新关注用户处理开始")
  1366. //判断节假日
  1367. runOk := getRunOk()
  1368. if !runOk {
  1369. log.Println("不是工作日,任务暂停")
  1370. return
  1371. }
  1372. rebindTimeEnd := cfg.RebindTime
  1373. sql := fmt.Sprintf(`select * from freeClubSign where sub_again_date > "%s" order by sub_again_date asc`, rebindTimeEnd)
  1374. data := BiService.SelectBySql(sql)
  1375. if data != nil && *data != nil && len(*data) > 0 {
  1376. for _, v := range *data {
  1377. rebindTimeEnd = common.ObjToString(v["sub_again_date"])
  1378. registedates, _ := time.Parse(date.Date_Full_Layout, gconv.String(v["register_time"]))
  1379. if time.Now().Unix()-registedates.Unix() > int64(db.RegTimes)*86400 {
  1380. ok1, ok2, _ := FormatData(v, "rebind")
  1381. if !ok1 {
  1382. log.Println("线索卡点", "allocation", v, rebindTimeEnd)
  1383. } else {
  1384. if !ok2 {
  1385. log.Println("用户分配已达上限", "allocation", v, rebindTimeEnd)
  1386. }
  1387. }
  1388. }
  1389. }
  1390. cfg.RebindTime = rebindTimeEnd
  1391. common.WriteSysConfig(&cfg)
  1392. }
  1393. log.Println("重新关注用户处理结束")
  1394. }
  1395. // 活跃用户处理
  1396. func activeUsers() {
  1397. log.Println("活跃用户处理开始")
  1398. //判断节假日
  1399. runOk := getRunOk()
  1400. if !runOk {
  1401. log.Println("不是工作日,任务暂停")
  1402. return
  1403. }
  1404. //活跃用户查询
  1405. activeTimeEnd := cfg.ActiveTime
  1406. sql := fmt.Sprintf(`select * from freeClubSign where act_again_date > "%s" order by act_again_date asc`, activeTimeEnd)
  1407. data := BiService.SelectBySql(sql)
  1408. if data != nil && *data != nil && len(*data) > 0 {
  1409. for _, v := range *data {
  1410. activeTimeEnd = common.ObjToString(v["act_again_date"])
  1411. ok1, ok2, _ := FormatData(v, "allocation")
  1412. log.Println(v, "allocation", ok1, ok2)
  1413. if !ok1 {
  1414. log.Println("线索卡点", "allocation", v, activeTimeEnd)
  1415. } else {
  1416. if !ok2 {
  1417. log.Println("用户分配已达上限", "allocation", v, activeTimeEnd)
  1418. }
  1419. }
  1420. }
  1421. cfg.ActiveTime = activeTimeEnd
  1422. common.WriteSysConfig(&cfg)
  1423. }
  1424. log.Println("活跃用户处理结束")
  1425. }
  1426. // 安博会邮件
  1427. /*func ABHEmail(source string, data []map[string]interface{}) {
  1428. fileName, detailName, email, dir := "", "", "", ""
  1429. var err error
  1430. switch source {
  1431. case "user":
  1432. xlsxArr := []string{"姓名", "联系方式", "邮箱", "公司名称", "咨询需求", "销售线索来源", "具体来源", "留资时间"}
  1433. batch := FindBatch("abh")
  1434. fileName, detailName = "安博会用户注册销售线索 "+time.Now().Format(date.Date_Short_Layout)+"-"+batch, ""
  1435. xf := xlsx.NewFile()
  1436. style := xlsx.NewStyle()
  1437. style.Font.Size = 12
  1438. style.Font.Bold = true
  1439. style.Alignment.Vertical = "center"
  1440. style.Alignment.Horizontal = "center"
  1441. detailName = "今日新增安博会销售线索,请查收附件,及时跟进。"
  1442. sh, _ := xf.AddSheet("线索数据")
  1443. row1 := sh.AddRow()
  1444. for _, x := range xlsxArr {
  1445. cell := row1.AddCell()
  1446. cell.SetString(x)
  1447. cell.SetStyle(style)
  1448. }
  1449. for _, v := range data {
  1450. row := sh.AddRow()
  1451. row.AddCell().SetString(common.ObjToString(v["name"]))
  1452. row.AddCell().SetString(common.ObjToString(v["phone"]))
  1453. row.AddCell().SetString(common.ObjToString(v["email"]))
  1454. row.AddCell().SetString(common.ObjToString(v["company_name"]))
  1455. row.AddCell().SetString("")
  1456. row.AddCell().SetString("")
  1457. row.AddCell().SetString("安博会用户注册")
  1458. row.AddCell().SetString(gconv.Time(gconv.Int64(v["createtime"])).Format(date.Date_Full_Layout))
  1459. //增加客户需求
  1460. }
  1461. dir = "./xlsx/abh/" + fileName + ".xlsx"
  1462. err = xf.Save(dir)
  1463. case "saleLeads":
  1464. xlsxArr := []string{"用户昵称", "姓名", "公司名称", "职位", "联系人电话", "购买条数", "用户邮箱", "已支付订单信息", "未支付订单类型", "销售线索来源", "具体来源", "数据需求"}
  1465. batch := FindBatch("abh")
  1466. fileName, detailName = time.Now().Format(date.Date_Short_Layout)+"-"+batch+"安博会电销销售线索", ""
  1467. xf := xlsx.NewFile()
  1468. style := xlsx.NewStyle()
  1469. style.Font.Size = 12
  1470. style.Font.Bold = true
  1471. style.Alignment.Vertical = "center"
  1472. style.Alignment.Horizontal = "center"
  1473. detailName = "今日新增安博会销售线索,请查收附件,及时跟进。"
  1474. sh, _ := xf.AddSheet("线索数据")
  1475. row1 := sh.AddRow()
  1476. for _, x := range xlsxArr {
  1477. cell := row1.AddCell()
  1478. cell.SetString(x)
  1479. cell.SetStyle(style)
  1480. }
  1481. filterArr := []string{"-pc", "-app", "-wx", "-h5"}
  1482. sourceMap := map[string]string{} //根据留资维表:tidb/Jianyu_subjectdb/d_saleleads_code
  1483. saleSource := TiDb.SelectBySql(`SELECT source,name FROM d_saleleads_code WHERE is_delete = 1`)
  1484. if saleSource != nil && len(*saleSource) > 0 {
  1485. for _, v := range *saleSource {
  1486. source := common.ObjToString(v["source"])
  1487. name := common.ObjToString(v["name"])
  1488. for _, s := range filterArr {
  1489. name = strings.ReplaceAll(name, s, "")
  1490. }
  1491. sourceMap[source] = name
  1492. }
  1493. }
  1494. for _, v := range data {
  1495. sources := common.ObjToString(v["source"])
  1496. interest := common.ObjToString(v["interest"])
  1497. row := sh.AddRow()
  1498. row.AddCell().SetString(common.ObjToString(v["usernickname"]))
  1499. row.AddCell().SetString(common.ObjToString(v["name"]))
  1500. row.AddCell().SetString(common.ObjToString(v["company"]))
  1501. row.AddCell().SetString(common.ObjToString(v["position"]))
  1502. row.AddCell().SetString(common.ObjToString(v["phone"]))
  1503. row.AddCell().SetValue(0)
  1504. row.AddCell().SetString(common.ObjToString(v["email"]))
  1505. row.AddCell().SetString("")
  1506. row.AddCell().SetString("")
  1507. row.AddCell().SetString(sourceMap[sources])
  1508. row.AddCell().SetString(interest)
  1509. row.AddCell().SetString(common.ObjToString(v["data_requirement"]))
  1510. //增加客户需求
  1511. }
  1512. dir = "./xlsx/abh/" + fileName + ".xlsx"
  1513. err = xf.Save(dir)
  1514. case "big":
  1515. xlsxArr := []string{"用户昵称", "姓名", "公司名称", "职位", "联系人电话", "购买条数", "用户邮箱", "已支付订单信息", "未支付订单类型", "销售线索来源", "具体来源", "数据需求"}
  1516. batch := FindBatch("abh")
  1517. fileName, detailName = time.Now().Format(date.Date_Short_Layout)+"-"+batch+"安博会大客户销售线索", ""
  1518. xf := xlsx.NewFile()
  1519. style := xlsx.NewStyle()
  1520. style.Font.Size = 12
  1521. style.Font.Bold = true
  1522. style.Alignment.Vertical = "center"
  1523. style.Alignment.Horizontal = "center"
  1524. detailName = "今日新增安博会销售线索,请查收附件,及时跟进。"
  1525. sh, _ := xf.AddSheet("线索数据")
  1526. row1 := sh.AddRow()
  1527. for _, x := range xlsxArr {
  1528. cell := row1.AddCell()
  1529. cell.SetString(x)
  1530. cell.SetStyle(style)
  1531. }
  1532. for _, v := range data {
  1533. row := sh.AddRow()
  1534. row.AddCell().SetString(common.ObjToString(v["usernickname"]))
  1535. row.AddCell().SetString(common.ObjToString(v["username"]))
  1536. row.AddCell().SetString(common.ObjToString(v["company"]))
  1537. row.AddCell().SetString(common.ObjToString(v["job"]))
  1538. row.AddCell().SetString(common.ObjToString(v["phone"]))
  1539. row.AddCell().SetValue(common.IntAll(v["data_count"]))
  1540. row.AddCell().SetString(common.ObjToString(v["email"]))
  1541. row.AddCell().SetString(common.ObjToString(v["payorderinfo"]))
  1542. row.AddCell().SetString(common.ObjToString(v["unpayorderinfo"]))
  1543. row.AddCell().SetString(common.ObjToString(v["source"]))
  1544. row.AddCell().SetString(common.ObjToString(v["interest"]))
  1545. row.AddCell().SetString(common.ObjToString(v["data_requirement"]))
  1546. //增加客户需求
  1547. }
  1548. dir = "./xlsx/abh/" + fileName + ".xlsx"
  1549. err = xf.Save(dir)
  1550. case "advisory":
  1551. xlsxArr := []string{"姓名", "联系方式", "邮箱", "公司名称", "咨询需求", "销售线索来源", "具体来源", "留资时间"}
  1552. //排序:首先按照“联系方式”排序,即同1个用户的留资放在一起,其次按照留资时间正序排序。
  1553. batch := FindBatch("abh")
  1554. fileName, detailName = "安博会咨询服务销售线索 "+time.Now().Format(date.Date_Short_Layout)+"-"+batch, ""
  1555. xf := xlsx.NewFile()
  1556. style := xlsx.NewStyle()
  1557. style.Font.Size = 12
  1558. style.Font.Bold = true
  1559. style.Alignment.Vertical = "center"
  1560. style.Alignment.Horizontal = "center"
  1561. detailName = "今日新增安博会销售线索,请查收附件,及时跟进。"
  1562. sh, _ := xf.AddSheet("线索数据")
  1563. row1 := sh.AddRow()
  1564. for _, x := range xlsxArr {
  1565. cell := row1.AddCell()
  1566. cell.SetString(x)
  1567. cell.SetStyle(style)
  1568. }
  1569. for _, v := range data {
  1570. row := sh.AddRow()
  1571. row.AddCell().SetString(common.ObjToString(v["username"]))
  1572. row.AddCell().SetString(common.ObjToString(v["phone"]))
  1573. row.AddCell().SetString(common.ObjToString(v["email"]))
  1574. row.AddCell().SetString(common.ObjToString(v["company"]))
  1575. row.AddCell().SetString(common.ObjToString(v["data_requirement"]))
  1576. row.AddCell().SetString(common.ObjToString(v["source"]))
  1577. row.AddCell().SetString(common.ObjToString(v["interest"]))
  1578. row.AddCell().SetString(gconv.Time(gconv.Int64(v["createtime"])).Format(date.Date_Full_Layout))
  1579. }
  1580. dir = "./xlsx/abh/" + fileName + ".xlsx"
  1581. err = xf.Save(dir)
  1582. case "market":
  1583. xlsxArr := []string{"姓名", "联系人电话", "公司名称", "职位", "部门", "销售线索来源", "留资时间"}
  1584. batch := FindBatch("abh")
  1585. fileName, detailName = "安博会商务合作销售线索 "+time.Now().Format(date.Date_Short_Layout)+"-"+batch, ""
  1586. xf := xlsx.NewFile()
  1587. style := xlsx.NewStyle()
  1588. style.Font.Size = 12
  1589. style.Font.Bold = true
  1590. style.Alignment.Vertical = "center"
  1591. style.Alignment.Horizontal = "center"
  1592. detailName = "今日新增安博会销售线索,请查收附件,及时跟进。"
  1593. sh, _ := xf.AddSheet("线索数据")
  1594. row1 := sh.AddRow()
  1595. for _, x := range xlsxArr {
  1596. cell := row1.AddCell()
  1597. cell.SetString(x)
  1598. cell.SetStyle(style)
  1599. }
  1600. for _, v := range data {
  1601. row := sh.AddRow()
  1602. row.AddCell().SetString(common.ObjToString(v["username"]))
  1603. row.AddCell().SetString(common.ObjToString(v["phone"]))
  1604. row.AddCell().SetString(common.ObjToString(v["company"]))
  1605. row.AddCell().SetString(common.ObjToString(v["job"]))
  1606. row.AddCell().SetString(common.ObjToString(v["branch"]))
  1607. row.AddCell().SetString(common.ObjToString(v["source"]))
  1608. row.AddCell().SetString(gconv.Time(gconv.Int64(v["createtime"])).Format(date.Date_Full_Layout))
  1609. //增加客户需求
  1610. }
  1611. dir = "./xlsx/abh/" + fileName + ".xlsx"
  1612. err = xf.Save(dir)
  1613. }
  1614. email = db.AbhEmail
  1615. if err != nil {
  1616. log.Println("xls error", err, dir)
  1617. } else {
  1618. gmail := &mail.GmailAuth{
  1619. SmtpHost: "smtp.exmail.qq.com",
  1620. SmtpPort: 465,
  1621. User: "public03@topnet.net.cn",
  1622. Pwd: "ue9Rg9Sf4CVtdm5a",
  1623. }
  1624. status := mail.GSendMail_q("剑鱼标讯", email, "", "", fileName, detailName, dir, fileName+".xlsx", gmail)
  1625. if status {
  1626. log.Println("send mail success", fileName, email)
  1627. }
  1628. }
  1629. }*/
  1630. // 安防邮件
  1631. func AFEmail(data []map[string]interface{}) {
  1632. xlsxArr := []string{"姓名", "联系方式", "邮箱", "公司名称", "咨询需求", "销售线索来源", "具体来源", "留资时间"}
  1633. batch := FindBatch("af")
  1634. fileName, detailName := "安防销售线索 "+time.Now().Format(date.Date_Short_Layout)+"-"+batch, ""
  1635. xf := xlsx.NewFile()
  1636. style := xlsx.NewStyle()
  1637. style.Font.Size = 12
  1638. style.Font.Bold = true
  1639. style.Alignment.Vertical = "center"
  1640. style.Alignment.Horizontal = "center"
  1641. detailName = "今日新增安防销售线索,请查收附件,及时跟进。"
  1642. sh, _ := xf.AddSheet("线索数据")
  1643. row1 := sh.AddRow()
  1644. for _, x := range xlsxArr {
  1645. cell := row1.AddCell()
  1646. cell.SetString(x)
  1647. cell.SetStyle(style)
  1648. }
  1649. for _, v := range data {
  1650. row := sh.AddRow()
  1651. row.AddCell().SetString(common.ObjToString(v["name"]))
  1652. row.AddCell().SetString(common.ObjToString(v["phone"]))
  1653. row.AddCell().SetString(common.ObjToString(v["email"]))
  1654. row.AddCell().SetString(common.ObjToString(v["company_name"]))
  1655. row.AddCell().SetString("")
  1656. row.AddCell().SetString("")
  1657. row.AddCell().SetString("首次使用安防新注册")
  1658. row.AddCell().SetString(gconv.String(v["time"]))
  1659. //增加客户需求
  1660. }
  1661. email := db.AfEmail
  1662. dir := "./xlsx/af/" + fileName + ".xlsx"
  1663. err := xf.Save(dir)
  1664. if err != nil {
  1665. log.Println("xls error", err, dir)
  1666. } else {
  1667. gmail := &mail.GmailAuth{
  1668. SmtpHost: "smtp.exmail.qq.com",
  1669. SmtpPort: 465,
  1670. User: "public03@topnet.net.cn",
  1671. Pwd: "ue9Rg9Sf4CVtdm5a",
  1672. }
  1673. status := mail.GSendMail_q("剑鱼标讯", email, "", "", fileName, detailName, dir, fileName+".xlsx", gmail)
  1674. if status {
  1675. log.Println("send mail success", fileName, email)
  1676. }
  1677. }
  1678. }
  1679. func ABHEmail(source string, data []map[string]interface{}) {
  1680. var fileName, detailName, dir string
  1681. var err error
  1682. xlsxArr, detailName := getExcelHeaderAndDetail(source)
  1683. batch := FindBatch("abh")
  1684. fileName = fmt.Sprintf("%s %s-%s", getFileNamePrefix(source), time.Now().Format(date.Date_Short_Layout), batch)
  1685. xf := xlsx.NewFile()
  1686. style := createExcelStyle()
  1687. sh, _ := xf.AddSheet("线索数据")
  1688. addHeaderRow(sh, xlsxArr, style)
  1689. switch source {
  1690. case "user":
  1691. err = populateUserData(sh, data)
  1692. case "saleLeads", "big":
  1693. err = populateSaleLeadData(sh, data)
  1694. case "advisory":
  1695. err = populateAdvisoryData(sh, data)
  1696. case "market", "selection":
  1697. err = populateMarketData(sh, data)
  1698. }
  1699. if err == nil {
  1700. dir = fmt.Sprintf("./xlsx/abh/%s.xlsx", fileName)
  1701. err = xf.Save(dir)
  1702. }
  1703. sendEmailIfSuccessful(err, fileName, detailName, dir)
  1704. }
  1705. func getExcelHeaderAndDetail(source string) ([]string, string) {
  1706. switch source {
  1707. case "user":
  1708. return []string{"姓名", "联系方式", "邮箱", "公司名称", "咨询需求", "销售线索来源", "具体来源", "留资时间"}, "今日新增安博会销售线索,请查收附件,及时跟进。"
  1709. case "saleLeads":
  1710. return []string{"用户昵称", "姓名", "公司名称", "职位", "联系人电话", "购买条数", "用户邮箱", "已支付订单信息", "未支付订单类型", "销售线索来源", "具体来源", "数据需求"}, "今日新增安博会销售线索,请查收附件,及时跟进。"
  1711. case "big":
  1712. return []string{"用户昵称", "姓名", "公司名称", "职位", "联系人电话", "购买条数", "用户邮箱", "已支付订单信息", "未支付订单类型", "销售线索来源", "具体来源", "数据需求"}, "今日新增安博会销售线索,请查收附件,及时跟进。"
  1713. case "advisory":
  1714. return []string{"姓名", "联系方式", "邮箱", "公司名称", "咨询需求", "销售线索来源", "具体来源", "留资时间"}, "今日新增安博会销售线索,请查收附件,及时跟进。"
  1715. case "market":
  1716. return []string{"姓名", "联系人电话", "公司名称", "职位", "部门", "销售线索来源", "留资时间"}, "今日新增安博会销售线索,请查收附件,及时跟进。"
  1717. case "selection":
  1718. return []string{"姓名", "联系人电话", "公司名称", "职位", "部门", "销售线索来源", "留资时间"}, "今日新增安博会销售线索,请查收附件,及时跟进。"
  1719. default:
  1720. return nil, ""
  1721. }
  1722. }
  1723. func getFileNamePrefix(source string) string {
  1724. switch source {
  1725. case "user":
  1726. return "安博会用户注册销售线索"
  1727. case "saleLeads":
  1728. return "安博会电销销售线索"
  1729. case "big":
  1730. return "安博会大客户销售线索"
  1731. case "advisory":
  1732. return "安博会咨询服务销售线索"
  1733. case "market":
  1734. return "安博会商务合作销售线索"
  1735. default:
  1736. return "未知线索"
  1737. }
  1738. }
  1739. func createExcelStyle() *xlsx.Style {
  1740. style := xlsx.NewStyle()
  1741. style.Font.Size = 12
  1742. style.Font.Bold = true
  1743. style.Alignment.Vertical = "center"
  1744. style.Alignment.Horizontal = "center"
  1745. return style
  1746. }
  1747. func addHeaderRow(sh *xlsx.Sheet, headers []string, style *xlsx.Style) {
  1748. row := sh.AddRow()
  1749. for _, header := range headers {
  1750. cell := row.AddCell()
  1751. cell.SetString(header)
  1752. cell.SetStyle(style)
  1753. }
  1754. }
  1755. func populateUserData(sh *xlsx.Sheet, data []map[string]interface{}) error {
  1756. for _, v := range data {
  1757. row := sh.AddRow()
  1758. row.AddCell().SetString(common.ObjToString(v["name"]))
  1759. row.AddCell().SetString(common.ObjToString(v["phone"]))
  1760. row.AddCell().SetString(common.ObjToString(v["email"]))
  1761. row.AddCell().SetString(common.ObjToString(v["company_name"]))
  1762. row.AddCell().SetString("")
  1763. row.AddCell().SetString("")
  1764. row.AddCell().SetString("安博会用户注册")
  1765. row.AddCell().SetString(gconv.Time(gconv.Int64(v["createtime"])).Format(date.Date_Full_Layout))
  1766. }
  1767. return nil
  1768. }
  1769. func populateSaleLeadData(sh *xlsx.Sheet, data []map[string]interface{}) error {
  1770. sourceMap := buildSourceMap("运营部")
  1771. for _, v := range data {
  1772. row := sh.AddRow()
  1773. row.AddCell().SetString(common.ObjToString(v["usernickname"]))
  1774. row.AddCell().SetString(common.ObjToString(v["name"]))
  1775. row.AddCell().SetString(common.ObjToString(v["company"]))
  1776. row.AddCell().SetString(common.ObjToString(v["position"]))
  1777. row.AddCell().SetString(common.ObjToString(v["phone"]))
  1778. row.AddCell().SetValue(0)
  1779. row.AddCell().SetString(common.ObjToString(v["email"]))
  1780. row.AddCell().SetString("")
  1781. row.AddCell().SetString("")
  1782. row.AddCell().SetString(sourceMap[common.ObjToString(v["source"])])
  1783. row.AddCell().SetString(common.ObjToString(v["interest"]))
  1784. row.AddCell().SetString(common.ObjToString(v["data_requirement"]))
  1785. }
  1786. return nil
  1787. }
  1788. func populateAdvisoryData(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["email"]))
  1794. row.AddCell().SetString(common.ObjToString(v["company"]))
  1795. row.AddCell().SetString(common.ObjToString(v["data_requirement"]))
  1796. row.AddCell().SetString(common.ObjToString(v["source"]))
  1797. row.AddCell().SetString(common.ObjToString(v["interest"]))
  1798. row.AddCell().SetString(gconv.Time(gconv.Int64(v["createtime"])).Format(date.Date_Full_Layout))
  1799. }
  1800. return nil
  1801. }
  1802. func populateMarketData(sh *xlsx.Sheet, data []map[string]interface{}) error {
  1803. for _, v := range data {
  1804. row := sh.AddRow()
  1805. row.AddCell().SetString(common.ObjToString(v["username"]))
  1806. row.AddCell().SetString(common.ObjToString(v["phone"]))
  1807. row.AddCell().SetString(common.ObjToString(v["company"]))
  1808. row.AddCell().SetString(common.ObjToString(v["job"]))
  1809. row.AddCell().SetString(common.ObjToString(v["branch"]))
  1810. row.AddCell().SetString(common.ObjToString(v["source"]))
  1811. row.AddCell().SetString(gconv.Time(gconv.Int64(v["createtime"])).Format(date.Date_Full_Layout))
  1812. }
  1813. return nil
  1814. }
  1815. func sendEmailIfSuccessful(err error, fileName, detailName, dir string) {
  1816. if err != nil {
  1817. log.Println("xls error", err, dir)
  1818. return
  1819. }
  1820. email := db.AbhEmail
  1821. gmail := &mail.GmailAuth{
  1822. SmtpHost: "smtp.exmail.qq.com",
  1823. SmtpPort: 465,
  1824. User: "public03@topnet.net.cn",
  1825. Pwd: "ue9Rg9Sf4CVtdm5a",
  1826. }
  1827. status := mail.GSendMail_q("剑鱼标讯", email, "", "", fileName, detailName, dir, fileName+".xlsx", gmail)
  1828. if status {
  1829. log.Println("send mail success", fileName, email)
  1830. }
  1831. }
  1832. func inviteUser() {
  1833. log.Println("邀请用户处理开始")
  1834. //判断节假日
  1835. runOk := getRunOk()
  1836. if !runOk {
  1837. log.Println("不是工作日,任务暂停")
  1838. return
  1839. }
  1840. rebindTimeEnd := cfg.InviteTime
  1841. sql := fmt.Sprintf(`select * from user_statistics where createTime > "%s" order by createTime asc`, rebindTimeEnd)
  1842. //sql := fmt.Sprintf(`select * from user_statistics where createTime = "%s" order by createTime asc`, rebindTimeEnd)
  1843. data := BiService.SelectBySql(sql)
  1844. if data != nil && *data != nil && len(*data) > 0 {
  1845. for _, v := range *data {
  1846. rebindTimeEnd = common.ObjToString(v["createTime"])
  1847. event := gconv.Int64(v["event"])
  1848. switch event {
  1849. case 1:
  1850. v["sourceCode"] = "736"
  1851. case 2:
  1852. v["sourceCode"] = "737"
  1853. case 3:
  1854. v["sourceCode"] = "738"
  1855. }
  1856. v["user_id"] = gconv.String(v["userId"])
  1857. ok1, ok2, _ := FormatData(v, "invite")
  1858. if !ok1 {
  1859. log.Println("线索卡点", "invite", v, rebindTimeEnd)
  1860. } else {
  1861. if !ok2 {
  1862. log.Println("用户分配已达上限", "invite", v, rebindTimeEnd)
  1863. }
  1864. }
  1865. }
  1866. cfg.InviteTime = rebindTimeEnd
  1867. common.WriteSysConfig(&cfg)
  1868. }
  1869. log.Println("邀请用户处理结束")
  1870. }