kc.go 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075
  1. package main
  2. import (
  3. "app.yhyue.com/moapp/jybase/mail"
  4. "app.yhyue.com/moapp/jybase/redis"
  5. "database/sql"
  6. "fmt"
  7. "log"
  8. "strings"
  9. "time"
  10. "github.com/gogf/gf/v2/util/gconv"
  11. "app.yhyue.com/moapp/jybase/common"
  12. "app.yhyue.com/moapp/jybase/date"
  13. "app.yhyue.com/moapp/jybase/mongodb"
  14. )
  15. func kcSync() {
  16. log.Println("客户成功系统移交定时任务开始")
  17. //商品查询
  18. productArr, _ := KcProduct()
  19. if len(productArr) == 0 {
  20. log.Println("查询不到进客成商品类型")
  21. return
  22. }
  23. sql := `SELECT
  24. a.*,b.product_type,b.service_starttime,b.service_endtime,b.service_type,b.filter as productFilter,TIMESTAMPDIFF(DAY, b.service_starttime, b.service_endtime) as difference,b.update_time
  25. FROM
  26. dataexport_order a
  27. INNER JOIN jy_order_detail b ON a.order_code = b.order_code
  28. and b.product_type in (%s)
  29. AND (
  30. a.pay_money > 0
  31. OR (
  32. a.pay_money = 0
  33. AND ( a.zero_type = "分期付款权益补充" OR a.zero_type = "原订单不支持开通多项权益" OR a.zero_type = "权益码兑换" )))
  34. AND a.user_phone NOT LIKE "%s"
  35. and a.user_id !=""
  36. AND a.order_status = 1
  37. AND ( a.refund_status != 1 OR a.refund_status IS NULL )
  38. AND b.service_starttime < "2099-01-01" AND b.service_endtime > now()
  39. AND b.update_time > "%s"
  40. ORDER BY
  41. a.order_code ASC,
  42. difference desc ,
  43. b.final_price DESC `
  44. sql = fmt.Sprintf(sql, strings.Join(productArr, ","), "9%", cfg.LastkcTime)
  45. //sql = fmt.Sprintf(sql, strings.Join(productArr, ","), "9%", "2025-01-02", "103557341197")
  46. data := Mysql.SelectBySql(sql)
  47. fmt.Println("客成查询到的数量:", len(*data))
  48. customList := gconv.Strings(redis.Get("newother", "customList"))
  49. if data != nil && *data != nil && len(*data) > 0 {
  50. orderMap := map[string]map[string]interface{}{}
  51. for _, v := range *data {
  52. orderCode := gconv.String(v["order_code"])
  53. productType := gconv.String(v["product_type"])
  54. vipStarttime := gconv.String(v["service_starttime"])
  55. vipEndtime := gconv.String(v["service_endtime"])
  56. service_type := gconv.Int64(v["service_type"])
  57. difference := gconv.Int(v["difference"])
  58. if (service_type != 4) || (service_type == 4 && difference > 95) {
  59. isExit := false
  60. for _, v := range customList {
  61. if v == orderCode {
  62. isExit = true
  63. continue
  64. }
  65. }
  66. if isExit {
  67. continue
  68. }
  69. //判断一下服务周期
  70. _, productInt64, _ := GetOrderProduct(productType, gconv.String(v["productFilter"]))
  71. if productInt64 == 0 {
  72. continue
  73. }
  74. if _, exists := orderMap[orderCode]; exists {
  75. //判断服务周期
  76. data := orderMap[orderCode]
  77. //商品类型获取
  78. oldDifference := gconv.Int(data["difference"])
  79. if oldDifference < difference {
  80. //需要更换
  81. v["difference"] = difference
  82. v["product"] = productInt64
  83. v["service_endtime"] = vipEndtime
  84. v["service_starttime"] = vipStarttime
  85. orderMap[orderCode] = v
  86. }
  87. } else {
  88. v["difference"] = difference
  89. v["product"] = productInt64
  90. orderMap[orderCode] = v
  91. }
  92. }
  93. }
  94. for _, v := range *data {
  95. orderCode := gconv.String(v["order_code"])
  96. if _, exists := orderMap[orderCode]; exists {
  97. status := kcJob(v)
  98. log.Println("订单进客成打印", orderCode, status)
  99. if status == 0 {
  100. break
  101. }
  102. cfg.LastkcTime = gconv.String(v["update_time"])
  103. customList = append(customList, orderCode)
  104. delete(orderMap, orderCode)
  105. }
  106. }
  107. }
  108. redis.Put("newother", "customList", customList, 0)
  109. common.WriteSysConfig(&cfg)
  110. log.Println("客户成功系统移交定时任务结束")
  111. }
  112. func kcJob(data map[string]interface{}) int {
  113. nowTime := time.Now().Format(date.Date_Full_Layout)
  114. uId, entId, clueId, saveMap, status := "", gconv.String(data["ent_id"]), int64(0), map[string]interface{}{}, 1
  115. userId, cluename, phone := "", "", ""
  116. phone = gconv.String(data["user_phone"])
  117. uId, userId = GetUidToUserId(gconv.String(data["user_id"]), "")
  118. log.Println("用户信息获取", data["user_id"], uId, userId)
  119. if uId == "" {
  120. log.Println("移交客成缺少基本信息,缺少用户信息", uId)
  121. return 0
  122. }
  123. buy_subject := common.IntAll(data["buy_subject"])
  124. if buy_subject == 1 || buy_subject == 0 {
  125. entId = gconv.String(data["user_id"])
  126. }
  127. clueData := TiDb.FindOne("dwd_f_crm_clue_info", map[string]interface{}{"uid": uId}, "", "")
  128. orderCode := gconv.String(data["order_code"])
  129. saleDep, orderPositionId, salesperson := FindSaleRecord(orderCode)
  130. log.Println(data["order_code"], saleDep, orderPositionId, salesperson)
  131. if clueData == nil || len(*clueData) == 0 {
  132. if saleDep == "销售部" || saleDep == "市场部" {
  133. log.Println("移交客成缺少基本信息", uId)
  134. return 0
  135. }
  136. //原始订单获取
  137. position_id := int64(0)
  138. seatNumber := ""
  139. if saleDep == "客户成功部" {
  140. //新增线索
  141. position_id = 0
  142. } else {
  143. position_id = orderPositionId
  144. //其他信息
  145. seatNumber = "0000"
  146. }
  147. cluename = gconv.String(data["company_name"])
  148. if cluename == "" {
  149. cluename = phone
  150. }
  151. trailstatus := "08"
  152. isGroup, isCommerce := GetCompanyType(cluename, uId) //判断是否集团公司、工商库
  153. clueId = TiDb.Insert("dwd_f_crm_clue_info", map[string]interface{}{
  154. "userid": userId,
  155. "uid": uId,
  156. "is_assign": common.If(position_id > 0, 1, 0),
  157. "createtime": nowTime,
  158. "updatetime": nowTime,
  159. "cluename": cluename,
  160. "seatNumber": seatNumber,
  161. "position_id": position_id,
  162. "top_cluetype": "4",
  163. "sub_cluetype": "154",
  164. "trailstatus": trailstatus,
  165. "name": phone,
  166. "phone": phone,
  167. "is_task": 0,
  168. "taskstatus": 0,
  169. "company_nature": isGroup,
  170. "company_verification": isCommerce,
  171. "FREEZE_TIME": nowTime,
  172. "label": common.If(position_id > 0, 1, nil),
  173. })
  174. if clueId > 0 {
  175. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  176. "clue_id": clueId,
  177. "position_id": common.If(position_id > 0, position_id, -1),
  178. "change_type": "创建线索",
  179. "new_value": "系统自动创建",
  180. "createtime": nowTime,
  181. "BCPCID": common.GetRandom(32),
  182. "operator_id": -1,
  183. })
  184. clueData = TiDb.FindOne("dwd_f_crm_clue_info", map[string]interface{}{"uid": uId}, "", "")
  185. if clueData == nil || len(*clueData) == 0 {
  186. return 0
  187. }
  188. } else {
  189. return 0
  190. }
  191. }
  192. clueId = common.Int64All((*clueData)["id"])
  193. starttime := gconv.String(data["service_starttime"])
  194. endtime := gconv.String(data["service_endtime"])
  195. //product_type := gconv.String(data["product_type"])
  196. userName := gconv.String((*clueData)["name"])
  197. product, company_name := gconv.String(data["product"]), gconv.String(data["company_name"])
  198. //同一公司名称(以客户详情-组织机构-公司名称)下的线索需分配给同1人
  199. saveMap = map[string]interface{}{
  200. "clue_id": clueId,
  201. "transfertime": nowTime,
  202. "service_starttime": starttime,
  203. "service_endtime": endtime,
  204. "ent_id": entId,
  205. "is_task": 1,
  206. "tasktime": nowTime,
  207. "taskstatus": 0,
  208. "tasksource": "1",
  209. "is_admin": 1,
  210. "product_access": product,
  211. "buy_subject": buy_subject,
  212. "relationship_building_way": 1,
  213. "inventory_way": 1,
  214. "training_way": 1,
  215. "is_pre_sales_training": 0,
  216. "service_stage": 1,
  217. "company_name": company_name,
  218. }
  219. if TiDb.Count("dwd_f_csm_customer_info", map[string]interface{}{"clue_id": clueId}) > 0 {
  220. csmdata := TiDb.FindOne("dwd_f_csm_customer_info", map[string]interface{}{"clue_id": clueId}, "", "")
  221. if csmdata != nil && len(*csmdata) > 0 {
  222. id := gconv.Int64((*csmdata)["id"])
  223. log.Println(1111111, id, orderCode)
  224. //'已移交销售,0移交客成 1移交销售',
  225. is_transfer := gconv.Int64((*csmdata)["is_transfer"])
  226. customerPositionId, customerName := cAutoDraw(0, orderPositionId, salesperson, saleDep, true, csmdata)
  227. log.Println("移交客成positionId", customerPositionId, customerName, saleDep, orderPositionId, salesperson, true)
  228. oldName := gconv.String((*csmdata)["name"])
  229. updateMap := map[string]interface{}{
  230. "is_transfer": 0,
  231. "is_renewal_protection": 0,
  232. "product_access": product,
  233. "buy_subject": buy_subject,
  234. "transfertime": nowTime,
  235. "service_starttime": starttime,
  236. "service_endtime": endtime,
  237. "ent_id": entId,
  238. "company_name": company_name,
  239. "name": customerName,
  240. "position_id": customerPositionId,
  241. }
  242. if is_transfer == 1 || customerPositionId != gconv.Int64((*csmdata)["position_id"]) {
  243. //重新进去
  244. updateMap["relationship_building_way"] = 1
  245. updateMap["tasksource"] = "1"
  246. updateMap["inventory_way"] = 1
  247. updateMap["training_way"] = 1
  248. updateMap["is_pre_sales_training"] = 0
  249. updateMap["service_stage"] = 1
  250. updateMap["is_task"] = 1
  251. }
  252. TiDb.Update("dwd_f_csm_customer_info", map[string]interface{}{"clue_id": clueId}, updateMap)
  253. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  254. "clue_id": clueId,
  255. "position_id": customerPositionId,
  256. "change_type": "成交客户移交",
  257. "new_value": "移交至客户成功组",
  258. "createtime": nowTime,
  259. "BCPCID": common.GetRandom(32),
  260. "operator_id": -1,
  261. })
  262. if customerPositionId > 0 && (is_transfer == 1 || customerPositionId != gconv.Int64((*csmdata)["position_id"])) {
  263. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  264. "clue_id": clueId,
  265. "position_id": customerPositionId,
  266. "change_field": "position_id",
  267. "change_type": "客户成功经理",
  268. "old_value": common.If(oldName != customerName, oldName, common.If(oldName == "", "/", oldName)),
  269. "new_value": customerName,
  270. "createtime": nowTime,
  271. "BCPCID": common.GetRandom(32),
  272. "operator_id": -1,
  273. })
  274. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  275. "clue_id": clueId,
  276. "position_id": customerPositionId,
  277. "change_type": "加入任务车",
  278. "new_value": "未建联",
  279. "createtime": nowTime,
  280. "BCPCID": common.GetRandom(32),
  281. "operator_id": -1,
  282. })
  283. }
  284. if is_transfer == 1 || customerPositionId != gconv.Int64((*csmdata)["position_id"]) {
  285. if customerName == db.KeCheng.Admin {
  286. TiDb.UpdateOrDeleteBySql(`update dwd_f_csm_customer_autodraw_record set count = count + 2 where name = ?`, customerName)
  287. } else {
  288. TiDb.UpdateOrDeleteBySql(`update dwd_f_csm_customer_autodraw_record set count = count + 1 where name = ?`, customerName)
  289. }
  290. }
  291. KcSend(orderCode, customerName)
  292. TiDb.Update("dwd_f_crm_clue_info", map[string]interface{}{"id": clueId}, map[string]interface{}{"is_transfer": 1, "updatetime": nowTime, "name": userName})
  293. }
  294. } else {
  295. customerPositionId, customerName := cAutoDraw(gconv.Int(entId), orderPositionId, salesperson, saleDep, false, nil)
  296. log.Println("移交客成positionId", customerPositionId, customerName, saleDep, orderPositionId, salesperson, false)
  297. cId, ok, updateId1, updateId2, updateId3 := int64(0), false, int64(0), int64(0), int64(0)
  298. if TiDb.ExecTx("保存客户", func(tx *sql.Tx) bool {
  299. saveMap["position_id"] = customerPositionId
  300. saveMap["name"] = customerName
  301. cId = TiDb.InsertByTx(tx, "dwd_f_csm_customer_info", saveMap)
  302. ok = TiDb.UpdateByTx(tx, "dwd_f_crm_clue_info", map[string]interface{}{"id": clueId}, map[string]interface{}{"is_transfer": 1, "updatetime": nowTime, "name": userName})
  303. if customerPositionId > 0 {
  304. updateId1 = TiDb.InsertByTx(tx, "dwd_f_crm_clue_change_record", map[string]interface{}{
  305. "clue_id": clueId,
  306. "position_id": customerPositionId,
  307. "change_type": "加入任务车",
  308. "new_value": "未建联",
  309. "createtime": nowTime,
  310. "BCPCID": common.GetRandom(32),
  311. "operator_id": -1,
  312. })
  313. updateId3 = TiDb.InsertByTx(tx, "dwd_f_crm_clue_change_record", map[string]interface{}{
  314. "clue_id": clueId,
  315. "position_id": customerPositionId,
  316. "change_field": "position_id",
  317. "change_type": "客户成功经理",
  318. "old_value": "/",
  319. "new_value": customerName,
  320. "createtime": nowTime,
  321. "BCPCID": common.GetRandom(32),
  322. "operator_id": -1,
  323. })
  324. }
  325. KcSend(orderCode, customerName)
  326. updateId2 = TiDb.InsertByTx(tx, "dwd_f_crm_clue_change_record", map[string]interface{}{
  327. "clue_id": clueId,
  328. "position_id": customerPositionId,
  329. "change_type": "成交客户移交",
  330. "new_value": "移交至客户成功组",
  331. "createtime": nowTime,
  332. "BCPCID": common.GetRandom(32),
  333. "operator_id": -1,
  334. })
  335. return cId > -1 && ok && updateId1 > -1 && updateId2 > -1 && updateId3 > -1
  336. }) {
  337. if customerName == db.KeCheng.Admin {
  338. TiDb.UpdateOrDeleteBySql(`update dwd_f_csm_customer_autodraw_record set count = count + 2 where name = ?`, customerName)
  339. } else {
  340. TiDb.UpdateOrDeleteBySql(`update dwd_f_csm_customer_autodraw_record set count = count + 1 where name = ?`, customerName)
  341. }
  342. log.Println("保存客户成功")
  343. } else {
  344. log.Println("保存客户失败!!!", clueId, cId, ok, updateId1, updateId2, updateId3, " 用户信息 ", customerName, customerPositionId, uId)
  345. }
  346. }
  347. return status
  348. }
  349. func cAutoDraw(entId int, orderPositionId int64, salesperson, saleDep string, isExist bool, csmdata *map[string]interface{}) (positionId int64, name string) {
  350. query := `SELECT name,position_id FROM dwd_d_crm_department_level_succbi WHERE bi_pcode = (SELECT bi_code FROM dwd_d_crm_department_level_succbi WHERE name = "客户成功部" and resign=0 and ent_id=?) and resign = 0 and position_id is not null `
  351. data := TiDb.SelectBySql(query, db.EntId)
  352. if data == nil || len(*data) == 0 {
  353. return
  354. }
  355. positionId, name = findKcOldPerson(entId, orderPositionId, salesperson, saleDep, isExist, csmdata, data)
  356. if positionId == 0 {
  357. positionId, name = findKcNewPerson(entId, data)
  358. }
  359. return
  360. }
  361. func findKcOldPerson(entId int, orderPositionId int64, salesperson, saleDep string, isExist bool, csmdata *map[string]interface{}, data *[]map[string]interface{}) (positionId int64, name string) {
  362. //判断是否需要新增客成数据
  363. if isExist {
  364. //用户存在客成数据
  365. positionid := common.Int64All((*csmdata)["position_id"])
  366. if positionid != 0 {
  367. //以前没有,需要找一个新的
  368. for _, v := range *data {
  369. deptPositionId := gconv.Int64(v["position_id"])
  370. if deptPositionId == positionid {
  371. positionId = positionid
  372. name = gconv.String((*csmdata)["name"])
  373. return
  374. }
  375. }
  376. }
  377. //原始用户已离职 查看订单是否有合适的订单
  378. if saleDep == "客户成功部" {
  379. positionId = orderPositionId
  380. name = salesperson
  381. return
  382. }
  383. }
  384. //客成数据不存在的时候
  385. //查找企业有没有其他信息
  386. if entId > 0 {
  387. entdata := TiDb.Find("dwd_f_csm_customer_info", map[string]interface{}{"ent_id": entId}, "", "", -1, -1)
  388. if entdata != nil && len(*entdata) > 0 {
  389. for _, v := range *entdata {
  390. positionid := common.Int64All(v["position_id"])
  391. name = gconv.String(v["name"])
  392. for _, v := range *data {
  393. deptPositionId := gconv.Int64(v["position_id"])
  394. if deptPositionId == positionId {
  395. positionId = positionid
  396. name = gconv.String((*csmdata)["name"])
  397. return
  398. }
  399. }
  400. }
  401. }
  402. //原始用户已离职 或者没有查找相关企业客成信息 以订单信息为主
  403. if saleDep == "客户成功部" {
  404. positionId = orderPositionId
  405. name = salesperson
  406. }
  407. return
  408. //没有相同企业的客成信息
  409. } else {
  410. //没有人 分配给自己
  411. if saleDep == "客户成功部" {
  412. positionId = orderPositionId
  413. name = salesperson
  414. return
  415. }
  416. return
  417. }
  418. }
  419. func findKcNewPerson(entId int, data *[]map[string]interface{}) (positionId int64, name string) {
  420. if entId > 0 {
  421. entdata := TiDb.FindOne("dwd_f_csm_customer_info", map[string]interface{}{"ent_id": entId}, "", "")
  422. if entdata != nil && len(*entdata) > 0 {
  423. positionId = common.Int64All((*entdata)["position_id"])
  424. name = gconv.String((*entdata)["name"])
  425. return
  426. }
  427. }
  428. sql := `select a.name,a.count from dwd_f_csm_customer_autodraw_record a INNER JOIN dwd_d_crm_department_level_succbi b on b.ent_id=? and (a.name = b.name) and b.resign = 0`
  429. countData := TiDb.SelectBySql(sql, db.EntId)
  430. if countData != nil && len(*countData) > 0 {
  431. for _, v := range *data {
  432. //判断是否有新员工
  433. isOk := false
  434. for _, vv := range *countData {
  435. if gconv.String(v["name"]) == gconv.String(vv["name"]) {
  436. isOk = true
  437. }
  438. }
  439. //有新员工直接分给新员工
  440. if !isOk {
  441. name = gconv.String(v["name"])
  442. rData := TiDb.FindOne("dwd_f_csm_customer_autodraw_record", map[string]interface{}{}, "", "count desc")
  443. TiDb.Insert("dwd_f_csm_customer_autodraw_record", map[string]interface{}{
  444. "name": name,
  445. "count": common.Int64All((*rData)["count"]),
  446. })
  447. break
  448. }
  449. }
  450. res := int64(0)
  451. countres := 0
  452. for _, v := range *countData {
  453. if countres == 0 {
  454. res = common.Int64All(v["count"])
  455. name = gconv.String(v["name"])
  456. } else {
  457. if common.Int64All(v["count"]) <= res {
  458. res = common.Int64All(v["count"])
  459. name = gconv.String(v["name"])
  460. }
  461. }
  462. countres++
  463. }
  464. }
  465. for _, v := range *data {
  466. if name == gconv.String(v["name"]) {
  467. positionId = common.Int64All(v["position_id"])
  468. }
  469. }
  470. return
  471. }
  472. func kcAuto() {
  473. log.Println("客户成功系统自动进入任务车定时任务开始")
  474. nowTime := time.Now().Format(date.Date_Full_Layout)
  475. sql := `select * from dwd_f_csm_customer_info where ((relationship_building_way != 1 and inventory_way = 1) or (inventory_way != 1 and training_way = 1)) and is_task = 0`
  476. data := TiDb.SelectBySql(sql)
  477. if data != nil && *data != nil && len(*data) > 0 {
  478. for _, v := range *data {
  479. relationship_building_way := common.IntAll(v["relationship_building_way"])
  480. inventory_way := common.IntAll(v["inventory_way"])
  481. training_way := common.IntAll(v["training_way"])
  482. positionId := common.Int64All(v["position_id"])
  483. clueId := common.Int64All(v["clue_id"])
  484. tasksource, tasksources := gconv.String(v["tasksource"]), ""
  485. taskstatus := common.IntAll(v["taskstatus"])
  486. if relationship_building_way != 1 && inventory_way == 1 {
  487. tasksources = "2"
  488. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  489. "clue_id": clueId,
  490. "position_id": positionId,
  491. "change_type": "加入任务车",
  492. "new_value": "未盘点",
  493. "createtime": nowTime,
  494. "BCPCID": common.GetRandom(32),
  495. "operator_id": -1,
  496. })
  497. } else if inventory_way != 1 && training_way == 1 {
  498. tasksources = "3"
  499. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  500. "clue_id": clueId,
  501. "position_id": positionId,
  502. "change_type": "加入任务车",
  503. "new_value": "未培训",
  504. "createtime": nowTime,
  505. "BCPCID": common.GetRandom(32),
  506. "operator_id": -1,
  507. })
  508. }
  509. if taskstatus == 1 {
  510. tasksource = tasksources
  511. } else {
  512. if tasksource != "" {
  513. if !strings.Contains(tasksource, tasksources) {
  514. tasksource += "," + tasksources
  515. }
  516. } else {
  517. tasksource = tasksources
  518. }
  519. }
  520. TiDb.Update("dwd_f_csm_customer_info", map[string]interface{}{"clue_id": clueId}, map[string]interface{}{
  521. "tasksource": tasksource,
  522. "tasktime": nowTime,
  523. "is_task": 1,
  524. "taskstatus": 0,
  525. })
  526. }
  527. }
  528. log.Println("客户成功系统进入任务车定时任务结束")
  529. }
  530. func ordersClue() {
  531. lastOrderClueId := cfg.LastOrderClueId
  532. nowTime := time.Now().Format(date.Date_Full_Layout)
  533. product_type_str2 := `"大会员","企业商机管理","VIP订阅"`
  534. sql := fmt.Sprintf(`select a.*,b.product_type as productType ,b.service_starttime,b.service_endtime,b.filter AS productFilter,b.update_time from dataexport_order a
  535. INNER JOIN jy_order_detail b on a.order_code=b.order_code
  536. and b.update_time>="%s" AND a.user_phone NOT LIKE "%s" and a.user_id !=""
  537. and b.product_type in (%s) and a.order_status = 1 and a.is_backstage_order = 1 order by b.update_time asc`, lastOrderClueId, "9%", product_type_str2)
  538. log.Println("后台订单线索定时任务", sql)
  539. data := Mysql.SelectBySql(sql)
  540. log.Println("后台订单线索定时任务", len(*data))
  541. if data != nil && *data != nil && len(*data) > 0 {
  542. for _, v := range *data {
  543. payMoney := common.IntAll(v["pay_money"])
  544. orderCode := gconv.String(v["order_code"])
  545. saleDep, _, salesperson := FindSaleRecord(orderCode)
  546. userPhone := gconv.String(v["user_phone"])
  547. createperson := gconv.String(v["create_person"])
  548. userId, uId, cluename, seatNumber, positionId, trailstatus, clueId := gconv.String(v["user_id"]), "", "", "", int64(0), "", int64(0)
  549. if saleDep != "" {
  550. //销售部
  551. query := map[string]interface{}{}
  552. source := ""
  553. if !mongodb.IsObjectIdHex(userId) {
  554. userMapping := TiDb.FindOne("dwd_f_userbase_id_mapping", map[string]interface{}{"position_id": userId}, "", "")
  555. if userMapping != nil && len(*userMapping) > 0 {
  556. userId = gconv.String((*userMapping)["userid"])
  557. } else {
  558. log.Println("后台订单--未查询到 ", userPhone)
  559. break
  560. }
  561. }
  562. query["userid"] = userId
  563. userInfo := TiDb.FindOne("dwd_f_userbase_baseinfo", query, "", "")
  564. if userInfo != nil && len(*userInfo) > 0 {
  565. uId = gconv.String((*userInfo)["uid"])
  566. source = gconv.String((*userInfo)["source"])
  567. } else {
  568. log.Println("后台订单--未查询到 ", query, userPhone)
  569. break
  570. }
  571. is_assign := 1
  572. mailContent := ""
  573. cluename = gconv.String(v["company_name"])
  574. mailContent = fmt.Sprintf("%s(%s)", cluename, userPhone)
  575. if cluename == "" {
  576. cluename = userPhone
  577. mailContent = userPhone
  578. }
  579. if payMoney > 0 {
  580. trailstatus = "08"
  581. } else {
  582. trailstatus = "01"
  583. }
  584. isGroup, isCommerce := GetCompanyType(cluename, uId) //判断是否集团公司、工商库
  585. clueData := TiDb.FindOne("dwd_f_crm_clue_info", map[string]interface{}{"uid": uId}, "", "")
  586. if clueData == nil || len(*clueData) == 0 {
  587. log.Println("saleDep", saleDep)
  588. if saleDep == "销售部" {
  589. //撞单
  590. log.Println("销售部订单", saleDep)
  591. if strings.Contains(salesperson, ",") {
  592. log.Println("销售部撞单 ", salesperson)
  593. if salesperson == "" {
  594. salesperson = createperson
  595. }
  596. }
  597. log.Println("销售部订单salesperson", salesperson)
  598. saleData := TiDb.FindOne("dwd_f_crm_personnel_management", map[string]interface{}{"name": salesperson}, "", "")
  599. if saleData != nil {
  600. seatNumber = gconv.String((*saleData)["seat_number"])
  601. positionId = common.Int64All((*saleData)["position_id"])
  602. }
  603. if IsFreeze(source, payMoney, gconv.String(positionId), trailstatus) {
  604. //线索需要冻结
  605. is_assign = -3
  606. }
  607. clueId = TiDb.Insert("dwd_f_crm_clue_info", map[string]interface{}{
  608. "userid": userId,
  609. "uid": uId,
  610. "seatNumber": seatNumber,
  611. "position_id": positionId,
  612. "is_assign": is_assign,
  613. "comeintime": nowTime,
  614. "createtime": nowTime,
  615. "updatetime": nowTime,
  616. "cluename": cluename,
  617. "top_cluetype": "4",
  618. "sub_cluetype": "154",
  619. "trailstatus": trailstatus,
  620. "name": userPhone,
  621. "phone": userPhone,
  622. "comeinsource_private": 2,
  623. "is_task": 0,
  624. "taskstatus": 0,
  625. "company_nature": isGroup,
  626. "company_verification": isCommerce,
  627. "FREEZE_TIME": nowTime,
  628. })
  629. } else if saleDep == "市场部" {
  630. log.Println("市场部订单", saleDep)
  631. clueId = TiDb.Insert("dwd_f_crm_clue_info", map[string]interface{}{
  632. "userid": userId,
  633. "uid": uId,
  634. "is_assign": -2,
  635. "createtime": nowTime,
  636. "updatetime": nowTime,
  637. "cluename": cluename,
  638. "top_cluetype": "4",
  639. "sub_cluetype": "154",
  640. "trailstatus": trailstatus,
  641. "name": userPhone,
  642. "phone": userPhone,
  643. "is_task": 0,
  644. "taskstatus": 0,
  645. "company_nature": isGroup,
  646. "company_verification": isCommerce,
  647. "FREEZE_TIME": nowTime,
  648. })
  649. }
  650. if clueId > 0 {
  651. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  652. "clue_id": clueId,
  653. "position_id": common.If(positionId > 0, positionId, -1),
  654. "change_type": "创建线索",
  655. "new_value": "系统自动创建",
  656. "createtime": nowTime,
  657. "BCPCID": common.GetRandom(32),
  658. "operator_id": -1,
  659. })
  660. if is_assign == -3 {
  661. //新增冻结记录
  662. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  663. "clue_id": clueId,
  664. "position_id": positionId,
  665. "change_type": "线索冻结",
  666. "new_value": "销售人员私海已达上限",
  667. "createtime": nowTime,
  668. "BCPCID": common.GetRandom(32),
  669. "operator_id": -1,
  670. })
  671. //移交失败发送消息
  672. if IsFreeze(source, payMoney, gconv.String(positionId), trailstatus) {
  673. //发送邮件信息
  674. OrderCreateFail(positionId, mailContent)
  675. }
  676. }
  677. }
  678. }
  679. }
  680. cfg.LastOrderClueId = gconv.String(v["update_time"])
  681. }
  682. }
  683. common.WriteSysConfig(&cfg)
  684. log.Println("后台订单线索定时任务结束")
  685. }
  686. func refundAuto() {
  687. log.Println("自动移交销售定时任务开始")
  688. findNowTime := time.Now().AddDate(0, 0, -db.ExpirationPeriod).Format(date.Date_Full_Layout)
  689. nowTime := time.Now().Format(date.Date_Full_Layout)
  690. mailData := map[string][]map[string]interface{}{}
  691. salesEmailData := map[int64][]map[string]interface{}{}
  692. TiDb.SelectByBath(100, func(l *[]map[string]interface{}) bool {
  693. for _, v := range *l {
  694. cluename, company_nature, company_verification, uid, phone, userName, oldSaleId, oldsaleName := "", 0, 0, "", "", "", int64(0), ""
  695. saleId, newSeatNumber, newPerson := int64(0), "", ""
  696. clueId := common.Int64All(v["clue_id"])
  697. company_name := gconv.String(v["company_name"])
  698. name := gconv.String(v["name"])
  699. kcposition_id := common.Int64All(v["position_id"])
  700. isRenewalProtection := common.IntAll(v["is_renewal_protection"])
  701. clueData := TiDb.FindOne("dwd_f_crm_clue_info", map[string]interface{}{"id": clueId}, "name,phone,company_nature,company_verification,cluename,userid,position_id,uid", "")
  702. if clueData != nil && len(*clueData) > 0 {
  703. uid = gconv.String((*clueData)["uid"])
  704. saleId, newPerson, newSeatNumber = FindPositionIdClueId(uid)
  705. oldSaleId = common.Int64All((*clueData)["position_id"])
  706. oldPersonData := FindPersonOne(oldSaleId)
  707. if oldSaleId != 0 {
  708. oldsaleName = gconv.String(oldPersonData["name"])
  709. }
  710. cluename = gconv.String((*clueData)["cluename"])
  711. userName = gconv.String((*clueData)["name"])
  712. company_nature = common.IntAll((*clueData)["company_nature"])
  713. company_verification = common.IntAll((*clueData)["company_verification"])
  714. phone = gconv.String((*clueData)["phone"])
  715. }
  716. personArr := getUserIdToUid(uid)
  717. productArr, _ := KcProduct()
  718. if len(productArr) == 0 || len(personArr) == 0 {
  719. log.Println("查询不到进客成商品类型或查询不到用户信息")
  720. continue
  721. }
  722. //查询即将到期数据
  723. if isRenewalProtection == 0 {
  724. sqlStr := fmt.Sprintf(`select a.*,b.product_type as productType,b.service_starttime,b.service_endtime,b.filter AS productFilter from dataexport_order a INNER JOIN jy_order_detail b on a.order_code=b.order_code and a.user_id in (%s) and b.product_type in (%s) ORDER BY b.service_endtime desc `, strings.Join(personArr, ","), strings.Join(productArr, ","))
  725. _, vipEndDateStr := getOrderData(sqlStr)
  726. if vipEndDateStr != "" {
  727. endDate := time.Now().AddDate(0, 0, -db.ExpirationPeriod+3).Unix()
  728. startDate := time.Now().AddDate(0, 0, -db.ExpirationPeriod+2).Unix()
  729. vipEndDate, _ := time.ParseInLocation(time.DateTime, vipEndDateStr, time.Local)
  730. log.Println(vipEndDate.Unix() > startDate, vipEndDate.Unix() < endDate)
  731. log.Println(vipEndDate.Unix(), startDate, endDate)
  732. if vipEndDate.Unix() > startDate && vipEndDate.Unix() < endDate {
  733. //即将到期
  734. mailData[name] = append(mailData[name], map[string]interface{}{
  735. "company_name": company_name,
  736. "phone": phone,
  737. "userName": userName,
  738. "remrk": "3天后即将移交",
  739. "reason": "成交客户续费失败",
  740. })
  741. continue
  742. }
  743. }
  744. }
  745. isFull := false
  746. isAllRefund := false
  747. orderSql := fmt.Sprintf(` select a.*,b.product_type as productType,b.service_starttime,b.service_endtime,b.filter AS productFilter from dataexport_order a INNER JOIN jy_order_detail b on a.order_code=b.order_code and a.user_id in (%s) and b.product_type in (%s) and order_status = 1 ORDER BY b.service_endtime desc `, strings.Join(personArr, ","), strings.Join(productArr, ","))
  748. myOrders, _ := getOrderData(orderSql)
  749. if myOrders != nil || len(myOrders) > 0 {
  750. refundCount := 0
  751. for _, v := range myOrders {
  752. if common.IntAll(v["refund_status"]) == 1 {
  753. refundCount++
  754. }
  755. }
  756. if len(myOrders) > 0 && len(myOrders) == refundCount {
  757. isAllRefund = true
  758. }
  759. }
  760. if isAllRefund {
  761. //全退款了
  762. TiDb.UpdateOrDeleteBySql(`UPDATE dwd_f_crm_clue_info SET is_unfollow=0,is_assign=0,trailstatus="01",position_id=null,seatNumber=null,updatetime=?,comeintime_open=?,comeinsource_open=1,level_open=3,next_trail_time=null,is_task=null,tasktime=null,taskstatus=null,comeinsource_private=null,tasksource=null,is_transfer=0 WHERE id = ?`, nowTime, nowTime, clueId)
  763. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  764. "clue_id": clueId,
  765. "position_id": common.If(kcposition_id > 0, kcposition_id, -1),
  766. "change_type": "退回公海",
  767. "new_value": "成交客户申请退款",
  768. "createtime": nowTime,
  769. "BCPCID": common.GetRandom(32),
  770. "operator_id": -1,
  771. })
  772. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  773. "clue_id": clueId,
  774. "position_id": common.If(kcposition_id > 0, kcposition_id, -1),
  775. "change_field": "trailstatus",
  776. "change_type": "基本信息变更",
  777. "old_value": "成交客户",
  778. "new_value": "商机线索",
  779. "createtime": nowTime,
  780. "BCPCID": common.GetRandom(32),
  781. "operator_id": -1,
  782. })
  783. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  784. "clue_id": clueId,
  785. "position_id": common.If(kcposition_id > 0, kcposition_id, -1),
  786. "change_type": "客户成功经理",
  787. "change_field": "position_id",
  788. "old_value": name,
  789. "new_value": "/",
  790. "createtime": nowTime,
  791. "BCPCID": common.GetRandom(32),
  792. "operator_id": -1,
  793. })
  794. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  795. "clue_id": clueId,
  796. "position_id": common.If(kcposition_id > 0, kcposition_id, -1),
  797. "change_type": "移交销售",
  798. "new_value": "成交客户申请退款",
  799. "createtime": nowTime,
  800. "BCPCID": common.GetRandom(32),
  801. "operator_id": -1,
  802. })
  803. mailData[name] = append(mailData[name], map[string]interface{}{
  804. "company_name": company_name,
  805. "phone": phone,
  806. "userName": userName,
  807. "remrk": "已移交",
  808. "reason": "成交客户申请退款",
  809. })
  810. TiDb.UpdateOrDeleteBySql(`UPDATE dwd_f_csm_customer_info SET is_transfer=1 WHERE clue_id = ?`, clueId)
  811. } else {
  812. log.Println("客成到期处理")
  813. order1Sql := fmt.Sprintf(`select a.id from dataexport_order a INNER JOIN jy_order_detail b on a.order_code=b.order_code and a.user_id in (%s) and b.product_type in (%s) and order_status = 1 and b.service_endtime>"%s" ORDER BY b.service_endtime desc `, strings.Join(personArr, ","), strings.Join(productArr, ","), findNowTime)
  814. log.Println("有效订单查询", order1Sql)
  815. order1 := Mysql.SelectBySql(order1Sql)
  816. if order1 == nil || len(*order1) == 0 {
  817. isOk := false
  818. order3Sql := fmt.Sprintf(`select a.* , b.product_type AS productType,b.service_starttime,b.service_endtime ,b.filter AS productFilter
  819. from dataexport_order a INNER JOIN jy_order_detail b
  820. on a.order_code=b.order_code and a.user_id in (%s) and b.product_type in (%s)
  821. and order_status = 1 and b.service_endtime<"%s" ORDER BY b.service_endtime desc `,
  822. strings.Join(personArr, ","), strings.Join(productArr, ","), findNowTime)
  823. log.Println("有效订单查询1", order3Sql)
  824. _, vip_endtime := getOrderData(order3Sql)
  825. if vip_endtime != "" {
  826. //获取最后一个订单信息
  827. if isRenewalProtection == 1 {
  828. vip_endtimes, _ := time.ParseInLocation(date.Date_Full_Layout, vip_endtime, time.Local)
  829. //查询申请保护时间
  830. renewalTime := time.Now()
  831. timeData := TiDb.SelectBySql(`select max(createtime) as createtime from dwd_f_crm_clue_change_record where clue_id = ? and change_type="申请续费保护"`, clueId)
  832. if timeData != nil && len(*timeData) > 0 {
  833. if gconv.String(gconv.String((*timeData)[0]["createtime"])) != "" {
  834. renewalTime, _ = time.ParseInLocation(date.Date_Full_Layout, gconv.String((*timeData)[0]["createtime"]), time.Local)
  835. }
  836. }
  837. renewalInt := renewalTime.Unix()
  838. log.Println("申请保护期时间", clueId, renewalInt)
  839. log.Println("申请保护期时间222", time.Now().Unix()-vip_endtimes.Unix(), (db.HandoverCycle-1)*86400, (db.HandoverCycle)*86400)
  840. //查看服务到期时间
  841. if renewalInt != 0 && renewalInt < db.CustomerTime {
  842. //三个月
  843. if time.Now().Unix()-vip_endtimes.Unix() < 3*30*86400 {
  844. isOk = true
  845. }
  846. } else if (db.HandoverCycle-5)*86400 < time.Now().Unix()-vip_endtimes.Unix() && time.Now().Unix()-vip_endtimes.Unix() < (db.HandoverCycle-4)*86400 {
  847. //提前一天提示
  848. mailData[name] = append(mailData[name], map[string]interface{}{
  849. "company_name": company_name,
  850. "phone": phone,
  851. "userName": userName,
  852. "remrk": "3天后即将移交",
  853. "reason": "成交客户续费失败",
  854. })
  855. isOk = true
  856. } else if time.Now().Unix()-vip_endtimes.Unix() < db.HandoverCycle*86400 {
  857. isOk = true
  858. }
  859. }
  860. }
  861. if !isOk {
  862. //全到期了
  863. if saleId > 0 {
  864. saleData := TiDb.FindOne("dwd_f_crm_personnel_management", map[string]interface{}{"position_id": saleId, "resign": 0}, "", "")
  865. if saleData != nil && len(*saleData) > 0 {
  866. //该销售人没有变更
  867. } else {
  868. if company_nature == 0 && company_verification == 1 && cluename != "" {
  869. adata := TiDb.Find("dwd_f_crm_clue_info", map[string]interface{}{"cluename": cluename, "is_assign": 1}, "seatNumber,position_id", "", -1, -1)
  870. if adata != nil && len(*adata) > 0 {
  871. isOks := false
  872. for _, vv := range *adata {
  873. position_ids := common.Int64All(vv["position_id"])
  874. newSeatNumber = gconv.String(vv["seatNumber"])
  875. saleDatas := TiDb.FindOne("dwd_f_crm_personnel_management", map[string]interface{}{"position_id": position_ids, "resign": 0}, "", "")
  876. if saleDatas != nil && len(*saleDatas) > 0 {
  877. saleId = position_ids
  878. newPerson = gconv.String((*saleDatas)["name"])
  879. isOks = true
  880. break
  881. }
  882. }
  883. if !isOks {
  884. sdata := TiDb.SelectBySql(`SELECT b.name,b.position_id,b.seat_number from dwd_d_crm_department_level_succbi a INNER JOIN dwd_f_crm_personnel_management b on a.position_id = b.position_id where a.bi_pcode = (SELECT bi_pcode from dwd_d_crm_department_level_succbi where position_id = ?) and b.role_id = 3`, saleId)
  885. if len(*sdata) == 0 {
  886. sdata = TiDb.SelectBySql(`SELECT b.name,b.position_id,b.seat_number from dwd_d_crm_department_level_succbi a INNER JOIN dwd_f_crm_personnel_management b on a.position_id = b.position_id where a.bi_pcode = (SELECT bi_pcode from dwd_d_crm_department_level_succbi where position_id = ?) and b.role_id = 8`, saleId)
  887. }
  888. if sdata != nil && len(*sdata) > 0 {
  889. saleId = common.Int64All((*sdata)[0]["position_id"])
  890. newSeatNumber = gconv.String((*sdata)[0]["seat_number"])
  891. newPerson = gconv.String((*sdata)[0]["name"])
  892. }
  893. }
  894. }
  895. } else {
  896. sdata := &[]map[string]interface{}{}
  897. //查看当前是否属于一部三部
  898. userData := FindPersonOne(saleId)
  899. if userData != nil {
  900. deptName := gconv.String(userData["dept_name"])
  901. if strings.Contains(deptName, "一部") {
  902. sdata = TiDb.SelectBySql(`SELECT b.name,b.position_id,b.seat_number from dwd_d_crm_department_level_succbi a INNER JOIN dwd_f_crm_personnel_management b on a.position_id = b.position_id where a.bi_pcode = (SELECT bi_pcode from dwd_d_crm_department_level_succbi where position_id = ?) and b.role_id = 3`, saleId)
  903. if len(*sdata) == 0 {
  904. sdata = TiDb.SelectBySql(`SELECT b.name,b.position_id,b.seat_number from dwd_d_crm_department_level_succbi a INNER JOIN dwd_f_crm_personnel_management b on a.position_id = b.position_id where a.bi_pcode = (SELECT bi_pcode from dwd_d_crm_department_level_succbi where position_id = ?) and b.role_id = 8`, saleId)
  905. }
  906. } else if strings.Contains(deptName, "三部") {
  907. sdata = TiDb.SelectBySql(`SELECT b.name,b.position_id,b.seat_number from dwd_d_crm_department_level_succbi a INNER JOIN dwd_f_crm_personnel_management b on a.position_id = b.position_id where a.bi_pcode = (SELECT bi_pcode from dwd_d_crm_department_level_succbi where position_id = ?) and b.role_id = 8`, saleId)
  908. }
  909. }
  910. if sdata != nil && len(*sdata) > 0 {
  911. saleId = common.Int64All((*sdata)[0]["position_id"])
  912. newSeatNumber = gconv.String((*sdata)[0]["seat_number"])
  913. newPerson = gconv.String((*sdata)[0]["name"])
  914. }
  915. }
  916. }
  917. }
  918. if kcposition_id > 0 {
  919. mailData[name] = append(mailData[name], map[string]interface{}{
  920. "company_name": company_name,
  921. "phone": phone,
  922. "userName": userName,
  923. "remrk": "已移交",
  924. "reason": "成交客户续费失败",
  925. })
  926. }
  927. isFull = FindUpperLimit(gconv.String(saleId), "", false)
  928. if saleId > 0 {
  929. salesEmailData[saleId] = append(salesEmailData[saleId], map[string]interface{}{
  930. "company_name": company_name,
  931. "phone": phone,
  932. "userName": userName,
  933. "remrk": "已移交",
  934. "reason": "成交客户续费失败",
  935. "cluename": cluename,
  936. })
  937. if saleId != oldSaleId {
  938. //新增个人员变更
  939. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  940. "clue_id": clueId,
  941. "position_id": saleId,
  942. "change_field": "position_id",
  943. "change_type": "所属人变更",
  944. "old_value": common.If(oldsaleName != "", oldsaleName, "/"),
  945. "new_value": common.If(newPerson != "", newPerson, "/"),
  946. "createtime": nowTime,
  947. "BCPCID": common.GetRandom(32),
  948. "operator_id": -1,
  949. })
  950. if isFull {
  951. TiDb.UpdateOrDeleteBySql(`UPDATE dwd_f_crm_clue_info SET is_unfollow=0,updatetime=?,trailstatus="01",position_id=?,seatNumber=?,is_task=1,tasktime=?,top_cluetype="532",sub_cluetype="537",taskstatus=0,tasksource="其他-成交客户续约失败",is_transfer=0,is_assign=-3,FREEZE_TIME=? WHERE id = ?`, nowTime, saleId, newSeatNumber, nowTime, nowTime, clueId)
  952. } else {
  953. TiDb.UpdateOrDeleteBySql(`UPDATE dwd_f_crm_clue_info SET is_unfollow=0,updatetime=?,trailstatus="01",position_id=?,seatNumber=?,is_task=1,tasktime=?,top_cluetype="532",sub_cluetype="537",taskstatus=0,tasksource="其他-成交客户续约失败",is_transfer=0,is_assign=1 WHERE id = ?`, nowTime, saleId, newSeatNumber, nowTime, clueId)
  954. }
  955. } else {
  956. if isFull {
  957. TiDb.UpdateOrDeleteBySql(`UPDATE dwd_f_crm_clue_info SET is_unfollow=0,updatetime=?,trailstatus="01",top_cluetype="532",sub_cluetype="537",is_transfer=0,is_assign=-3,FREEZE_TIME=? WHERE id = ?`, nowTime, nowTime, clueId)
  958. } else {
  959. TiDb.UpdateOrDeleteBySql(`UPDATE dwd_f_crm_clue_info SET is_unfollow=0,updatetime=?,trailstatus="01",top_cluetype="532",sub_cluetype="537",is_transfer=0,is_assign=1 WHERE id = ?`, nowTime, clueId)
  960. }
  961. }
  962. } else if saleId == 0 {
  963. //找不到人
  964. TiDb.UpdateOrDeleteBySql(`UPDATE dwd_f_crm_clue_info SET is_unfollow=0,updatetime=?,trailstatus="01",position_id=0,seatNumber="",is_task=1,tasktime=?,top_cluetype="532",sub_cluetype="537",taskstatus=0,tasksource="其他-成交客户续约失败",is_transfer=0,is_assign=0 WHERE id = ?`, nowTime, nowTime, clueId)
  965. if oldSaleId != 0 {
  966. //新增个人员变更
  967. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  968. "clue_id": clueId,
  969. "position_id": saleId,
  970. "change_field": "position_id",
  971. "change_type": "所属人变更",
  972. "old_value": common.If(oldsaleName != "", oldsaleName, "/"),
  973. "new_value": common.If(newPerson != "", newPerson, "/"),
  974. "createtime": nowTime,
  975. "BCPCID": common.GetRandom(32),
  976. "operator_id": -1,
  977. "SHUOMING": "业绩归属查不到人",
  978. })
  979. //再做一个记录变更
  980. }
  981. }
  982. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  983. "clue_id": clueId,
  984. "position_id": common.If(kcposition_id > 0, kcposition_id, -1),
  985. "change_type": "基本信息变更",
  986. "old_value": "成交客户",
  987. "change_field": "trailstatus",
  988. "new_value": "商机线索",
  989. "createtime": nowTime,
  990. "BCPCID": common.GetRandom(32),
  991. "operator_id": -1,
  992. })
  993. if saleId > 0 {
  994. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  995. "clue_id": clueId,
  996. "position_id": saleId,
  997. "change_type": "加入任务车",
  998. "new_value": "线索自动分配-其他-成交客户续约失败",
  999. "createtime": nowTime,
  1000. "BCPCID": common.GetRandom(32),
  1001. "operator_id": -1,
  1002. })
  1003. }
  1004. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  1005. "clue_id": clueId,
  1006. "position_id": common.If(kcposition_id > 0, kcposition_id, -1),
  1007. "change_type": "客户成功经理",
  1008. "change_field": "position_id",
  1009. "old_value": name,
  1010. "new_value": "/",
  1011. "createtime": nowTime,
  1012. "BCPCID": common.GetRandom(32),
  1013. "operator_id": -1,
  1014. })
  1015. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  1016. "clue_id": clueId,
  1017. "position_id": saleId,
  1018. "change_type": "移交销售",
  1019. "new_value": "成交客户续费失败,到期自动移交",
  1020. "createtime": nowTime,
  1021. "BCPCID": common.GetRandom(32),
  1022. "operator_id": -1,
  1023. })
  1024. TiDb.UpdateOrDeleteBySql(`UPDATE dwd_f_csm_customer_info SET is_transfer=1 WHERE clue_id = ?`, clueId)
  1025. if isFull {
  1026. //新增冻结记录
  1027. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  1028. "clue_id": clueId,
  1029. "position_id": saleId,
  1030. "change_type": "线索冻结",
  1031. "new_value": "销售人员私海已达上限",
  1032. "createtime": nowTime,
  1033. "BCPCID": common.GetRandom(32),
  1034. "operator_id": -1,
  1035. })
  1036. //发送邮件
  1037. mailContent := ""
  1038. if cluename != "" {
  1039. if phone != "" {
  1040. if cluename == phone {
  1041. mailContent = phone
  1042. } else {
  1043. mailContent = fmt.Sprintf("%s(%s)", cluename, phone)
  1044. }
  1045. } else {
  1046. mailContent = cluename
  1047. }
  1048. } else {
  1049. mailContent = phone
  1050. }
  1051. HandOverFail(saleId, mailContent)
  1052. }
  1053. }
  1054. }
  1055. }
  1056. }
  1057. return true
  1058. }, `select ent_id,clue_id,position_id,name,is_renewal_protection,company_name from dwd_f_csm_customer_info where is_transfer = 0`)
  1059. //}, `select ent_id,clue_id,position_id,name,is_renewal_protection,company_name from dwd_f_csm_customer_info where clue_id =1892234`)
  1060. //移交电销提醒
  1061. for i, v := range mailData {
  1062. ExitKcSend(i, v)
  1063. }
  1064. //移交电销销售提醒
  1065. for i, v := range salesEmailData {
  1066. ExitKcSaleSend(i, v)
  1067. }
  1068. log.Println("自动移交销售定时任务结束")
  1069. }
  1070. // 查找一部三部人员信息 返回人员信息 以及管理员信息
  1071. func FindDeptAdmin(positionId int64) (map[string]interface{}, map[string]interface{}, map[string]interface{}) {
  1072. //先判断那个部门的
  1073. userData1 := TiDb.SelectBySql(`SELECT
  1074. a.position_id,
  1075. a.name,
  1076. b.seat_number,
  1077. b.role_id,
  1078. a.bi_pcode,
  1079. a.dept_name,
  1080. a.resign
  1081. FROM
  1082. (SELECT *
  1083. FROM dwd_d_crm_department_level_succbi u1
  1084. WHERE id = (
  1085. SELECT MAX(id)
  1086. FROM dwd_d_crm_department_level_succbi u2
  1087. WHERE u1.position_id = u2.position_id
  1088. )
  1089. ORDER BY id desc) a
  1090. INNER JOIN (SELECT *
  1091. FROM dwd_f_crm_personnel_management u1
  1092. WHERE id = (
  1093. SELECT MAX(id)
  1094. FROM dwd_f_crm_personnel_management u2
  1095. WHERE u1.position_id = u2.position_id
  1096. )
  1097. ORDER BY id desc) b ON a.dept_name LIKE "%销售一部%"
  1098. AND a.position_id = b.position_id`)
  1099. userData3 := TiDb.SelectBySql(`SELECT
  1100. a.position_id,
  1101. a.name,
  1102. b.seat_number,
  1103. b.role_id,
  1104. a.bi_pcode,
  1105. a.dept_name,
  1106. a.resign
  1107. FROM
  1108. (SELECT *
  1109. FROM dwd_d_crm_department_level_succbi u1
  1110. WHERE id = (
  1111. SELECT MAX(id)
  1112. FROM dwd_d_crm_department_level_succbi u2
  1113. WHERE u1.position_id = u2.position_id
  1114. )
  1115. ORDER BY id desc) a
  1116. INNER JOIN (SELECT *
  1117. FROM dwd_f_crm_personnel_management u1
  1118. WHERE id = (
  1119. SELECT MAX(id)
  1120. FROM dwd_f_crm_personnel_management u2
  1121. WHERE u1.position_id = u2.position_id
  1122. )
  1123. ORDER BY id desc) b ON
  1124. a.dept_name LIKE "%销售三部"
  1125. AND a.position_id = b.position_id`)
  1126. if userData3 == nil || len(*userData3) == 0 || userData1 == nil || len(*userData1) == 0 {
  1127. log.Println("找不到一部三部员工信息")
  1128. return nil, nil, nil
  1129. }
  1130. //一部高级管理员信息
  1131. seniorAdmin1 := map[string]interface{}{}
  1132. //三部高级管理员信息
  1133. seniorAdmin3 := map[string]interface{}{}
  1134. //一部管理员信息
  1135. admin1 := map[string]map[string]interface{}{}
  1136. //返回当前人信息
  1137. admin := map[string]interface{}{}
  1138. for _, v := range *userData3 {
  1139. v["type"] = 3
  1140. id := gconv.Int64(v["position_id"])
  1141. roleId := gconv.Int64(v["role_id"])
  1142. resign := gconv.Int64(v["resign"])
  1143. if id == positionId && resign == 0 {
  1144. admin = v
  1145. }
  1146. if roleId == 8 {
  1147. v["orderStatus"] = 2
  1148. seniorAdmin3 = v
  1149. }
  1150. }
  1151. for _, v := range *userData1 {
  1152. v["type"] = 1
  1153. id := gconv.Int64(v["position_id"])
  1154. roleId := gconv.Int64(v["role_id"])
  1155. dept_name := gconv.String(v["dept_name"])
  1156. resign := gconv.Int64(v["resign"])
  1157. if id == positionId && resign == 0 {
  1158. admin = v
  1159. }
  1160. if roleId == 8 {
  1161. v["orderStatus"] = 2
  1162. seniorAdmin1 = v
  1163. } else if roleId == 3 {
  1164. admin1[dept_name] = v
  1165. }
  1166. }
  1167. //查看当前人属于哪个部门
  1168. if admin == nil {
  1169. //当前人不属于电销部的
  1170. admin = *(TiDb.FindOne("dwd_f_crm_personnel_management", map[string]interface{}{
  1171. "position_id": positionId,
  1172. "resign": 1,
  1173. }, "name", ""))
  1174. }
  1175. positiontype := gconv.Int64(admin["type"])
  1176. deptName := gconv.String(admin["dept_name"])
  1177. switch positiontype {
  1178. case 1:
  1179. roleId := gconv.Int64(admin["role_id"])
  1180. if roleId == 3 {
  1181. return admin, nil, seniorAdmin1
  1182. }
  1183. return admin, admin1[deptName], seniorAdmin1
  1184. case 3:
  1185. return admin, nil, seniorAdmin3
  1186. default:
  1187. return admin, nil, nil
  1188. }
  1189. }
  1190. // 邮箱获取
  1191. func GetMail(personName string) (string, string) {
  1192. data := Mysql.SelectBySql(`select name,mail,img from entniche_user where ent_id =?`, db.EntId)
  1193. if data == nil || len(*data) == 0 {
  1194. return "", ""
  1195. }
  1196. for _, m := range *data {
  1197. name := gconv.String(m["name"])
  1198. if name == personName {
  1199. //
  1200. return gconv.String(m["mail"]), gconv.String(m["img"])
  1201. }
  1202. }
  1203. return "", ""
  1204. }
  1205. // 退客成进销售 销售收邮件
  1206. func ExitKcSaleSend(positionId int64, infoList []map[string]interface{}) {
  1207. to := SaleMail(positionId)
  1208. //退出客成 即将退出客成信息 销售信息编辑
  1209. gmail := &mail.GmailAuth{
  1210. SmtpHost: db.Mail.SmtpHost,
  1211. SmtpPort: db.Mail.SmtpPort,
  1212. User: db.Mail.User,
  1213. Pwd: db.Mail.Pwd,
  1214. }
  1215. //正文拼接
  1216. startStr := `<html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport"content="width=device-width, initial-scale=1.0">
  1217. <style>table{width:100%;border-collapse:collapse}th,td{border:1px solid#000;padding:8px;text-align:left}th{background-color:#f2f2f2}</style></head>
  1218. <body><p>以下客户已从或即将从客成系统退出,并移交销售跟进,请收悉,客户明细如下:</p>
  1219. <table><thead><tr><th>序号</th><th>线索名称</th><th>联系人</th><th>姓名</th><th>移交状态</th></tr></thead><tbody>`
  1220. for i, v := range infoList {
  1221. startStr += fmt.Sprintf(`<tr><td>%d</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>`, i+1, gconv.String(v["cluename"]), gconv.String(v["phone"]), gconv.String(v["userName"]), gconv.String(v["remrk"]))
  1222. }
  1223. endStr := `</tbody></table><p></body></html>`
  1224. startStr += endStr
  1225. if to != "" {
  1226. status := mail.GSendMail_q("剑鱼标讯", to, "", "", "成交客户续费失败移交销售通知", startStr, "", "", gmail)
  1227. if status {
  1228. log.Println("客成发邮件 send mail success", startStr, to)
  1229. }
  1230. }
  1231. }
  1232. // 客成人员变更发邮件
  1233. func CustomerChange() {
  1234. personMap := map[int64]string{}
  1235. personData := TiDb.SelectBySql(`select name,position_id from dwd_d_crm_department_level_succbi where ent_id=? and resign=0 and position_id>0`, db.EntId)
  1236. if personData != nil && len(*personData) > 0 {
  1237. for _, v := range *personData {
  1238. personMap[gconv.Int64(v["position_id"])] = gconv.String(v["name"])
  1239. }
  1240. }
  1241. startTime := cfg.LastKcChangeTime
  1242. if startTime == "" {
  1243. startTime = time.Now().Format(time.DateTime)
  1244. }
  1245. customMap1 := map[string][]map[string]interface{}{}
  1246. customMap2 := map[string][]map[string]interface{}{}
  1247. saleMap := map[int64][]map[string]interface{}{}
  1248. saleNobodyCustomMapMap := map[int64][]map[string]interface{}{}
  1249. TiDb.SelectByBath(100, func(l *[]map[string]interface{}) bool {
  1250. for _, v := range *l {
  1251. startTime = gconv.String(v["createtime"])
  1252. data := CustomerChangeHandle(v)
  1253. oldPerson := gconv.String(data["oldPerson"])
  1254. newPerson := gconv.String(data["newPerson"])
  1255. positionId := gconv.Int64(data["positionId"])
  1256. operatorId := gconv.Int64(data["operatorId"])
  1257. if oldPerson == "/" {
  1258. data["oldPerson"] = "-"
  1259. }
  1260. if positionId > 0 {
  1261. data["positionName"] = personMap[positionId]
  1262. }
  1263. if operatorId > 0 {
  1264. //手动分配 客成收邮件
  1265. data["operatorName"] = personMap[operatorId]
  1266. if newPerson != "" && newPerson != "/" {
  1267. customMap2[newPerson] = append(customMap2[newPerson], data)
  1268. }
  1269. if oldPerson != "" && oldPerson != "/" {
  1270. customMap1[oldPerson] = append(customMap1[oldPerson], data)
  1271. }
  1272. } else {
  1273. //自动分配 销售收邮件
  1274. if (oldPerson == "" || oldPerson == "/") && newPerson != "" && newPerson != "/" && positionId > 0 {
  1275. //之前没有可成人员
  1276. saleNobodyCustomMapMap[positionId] = append(saleNobodyCustomMapMap[positionId], data)
  1277. } else if newPerson != "" && newPerson != "/" && oldPerson != "" && oldPerson != "/" && positionId > 0 {
  1278. //之前有客成
  1279. saleMap[positionId] = append(saleMap[positionId], data)
  1280. }
  1281. }
  1282. }
  1283. return true
  1284. }, `select operator_id, clue_id,position_id,old_value,new_value,createtime from dwd_f_crm_clue_change_record where createtime>? and change_type="客户成功经理" order by createtime`, startTime)
  1285. //}, `select operator_id, clue_id,position_id,old_value,new_value,createtime from dwd_f_crm_clue_change_record where id=? order by createtime`, 22170775)
  1286. if len(customMap1) > 0 {
  1287. ChangeSendKc(customMap1, 1)
  1288. }
  1289. if len(customMap2) > 0 {
  1290. ChangeSendKc(customMap2, 2)
  1291. }
  1292. if len(saleMap) > 0 {
  1293. ChangeSendSale(saleMap, 2)
  1294. }
  1295. if len(saleNobodyCustomMapMap) > 0 {
  1296. ChangeSendSale(saleNobodyCustomMapMap, 1)
  1297. }
  1298. log.Println("11111", startTime)
  1299. cfg.LastKcChangeTime = startTime
  1300. common.WriteSysConfig(&cfg)
  1301. }
  1302. // 客户成功经理变更邮件提醒客成人员
  1303. func ChangeSendKc(data map[string][]map[string]interface{}, personType int64) {
  1304. for name, v := range data {
  1305. to, _ := GetMail(name)
  1306. //正文拼接
  1307. startStr := `<html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport"content="width=device-width, initial-scale=1.0"><style>table{width:100%;border-collapse:collapse}th,td{border:1px solid#000;padding:8px;text-align:left}th{background-color:#f2f2f2}</style></head><body><p></p>
  1308. <table><thead><tr><th>序号</th><th>公司名称</th><th>联系人</th><th>姓名</th><th>变更前客户经理</th><th>变更后客户经理</th><th>操作人</th></tr></thead><tbody>`
  1309. for i, v := range v {
  1310. startStr += fmt.Sprintf(`<tr><td>%d</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>`, i+1, gconv.String(v["companyName"]), gconv.String(v["phone"]), gconv.String(v["userName"]), gconv.String(v["oldPerson"]), gconv.String(v["newPerson"]), gconv.String(v["operatorName"]))
  1311. }
  1312. endStr := `</tbody></table><p></body></html>`
  1313. startStr += endStr
  1314. if to != "" {
  1315. status := mail.GSendMail_q("剑鱼标讯", to, "", "", gconv.String(common.If(personType == 2, "您有新的客户,请及时跟进处理", "您的客户已转至其他客户成功经理负责")), startStr, "", "", &Gmail)
  1316. if status {
  1317. log.Println("客成发邮件 send mail success", startStr, to, "")
  1318. }
  1319. }
  1320. }
  1321. }
  1322. func ChangeSendSale(data map[int64][]map[string]interface{}, personType int64) {
  1323. log.Println("客成人员变更", personType, data)
  1324. if personType == 1 {
  1325. //客户成功经理从空变成有人
  1326. for _, v := range data {
  1327. for _, v1 := range v {
  1328. positionId := gconv.Int64(v1["positionId"])
  1329. to := SaleMail(positionId)
  1330. _, img := GetMail(gconv.String(v1["newPerson"]))
  1331. //抄送人查询
  1332. startStr := `<style> *,body,html{margin:10px;font-family:tahoma,arial,'Hiragino Sans GB','Microsoft YaHei',宋体,ans-serif;font-size:16px;}p{margin:15px;font-size:18px;}table{background-color: rgb(244, 244, 249);padding:5px 15px;border:solid 1px #ddd;margin: 20px 0px 20px 50px;vertical-align:top;display:inline-block;}.tit{width:120px;}td{padding: 5px;}.clear{clear: both;}</style>
  1333. <p>销售人员"%s"成交的客户已成功移交至客成,线索名称:%s,姓名:%s,手机号:%s,负责客户成功经理:%s</p>
  1334. <p>请引导客户添加客户成功经理企业微信:</p><div class='clear'>%s</div>`
  1335. endStr := fmt.Sprintf(startStr, gconv.String(v1["positionName"]), gconv.String(v1["clueName"]), gconv.String(v1["userName"]), gconv.String(v1["phone"]), gconv.String(v1["newPerson"]), common.If(img != "", fmt.Sprintf(`<img width="300" height="450" src="%s">`, img), ""))
  1336. if to != "" {
  1337. status := mail.GSendMail_q("剑鱼标讯", to, "", "", "成交客户已成功移交客成", endStr, "", "", &Gmail)
  1338. if status {
  1339. log.Println("客成发邮件 send mail success", endStr, to, "")
  1340. }
  1341. }
  1342. }
  1343. }
  1344. return
  1345. }
  1346. //客户成功经理从A变成了B
  1347. for positionId, v := range data {
  1348. to := SaleMail(positionId)
  1349. //正文拼接
  1350. startStr := `<html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport"content="width=device-width, initial-scale=1.0"><style>table{width:100%;border-collapse:collapse}th,td{border:1px solid#000;padding:8px;text-align:left}th{background-color:#f2f2f2}</style></head><body><p>客户明细如下:
  1351. </p><table><thead><tr><th>序号</th><th>线索名称</th><th>联系人</th><th>姓名</th><th>变更前客户经理</th><th>变更后客户经理</th><th>销售人员</th></tr></thead><tbody>`
  1352. for i, v := range v {
  1353. startStr += fmt.Sprintf(`<tr><td>%d</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>`,
  1354. i+1, gconv.String(v["clueName"]), gconv.String(v["phone"]), gconv.String(v["userName"]), gconv.String(v["oldPerson"]), gconv.String(v["newPerson"]), gconv.String(v["positionName"]))
  1355. }
  1356. endStr := `</tbody></table><p></body></html>`
  1357. startStr += endStr
  1358. if to != "" {
  1359. status := mail.GSendMail_q("剑鱼标讯", to, "", "", "成交客户负责客户成功经理变更", startStr, "", "", &Gmail)
  1360. if status {
  1361. log.Println("客成发邮件 send mail success", startStr, to, "")
  1362. }
  1363. }
  1364. }
  1365. }
  1366. // 客成人员变更基本信息获取
  1367. func CustomerChangeHandle(data map[string]interface{}) map[string]interface{} {
  1368. clueId := gconv.Int64(data["clue_id"])
  1369. oldPerson := gconv.String(data["old_value"])
  1370. newPerson := gconv.String(data["new_value"])
  1371. operatorId := gconv.Int64(data["operator_id"])
  1372. companyName := ""
  1373. phone := ""
  1374. userName := ""
  1375. clueName := ""
  1376. clueData := TiDb.FindOne("dwd_f_crm_clue_info", map[string]interface{}{
  1377. "id": clueId,
  1378. }, "", "")
  1379. if clueData == nil || len(*clueData) == 0 {
  1380. return nil
  1381. }
  1382. uid := gconv.String((*clueData)["uid"])
  1383. phone = gconv.String((*clueData)["phone"])
  1384. userName = gconv.String((*clueData)["name"])
  1385. //positionId := gconv.Int64((*clueData)["position_id"])
  1386. positionId, _, _ := FindPositionIdClueId(uid)
  1387. clueName = gconv.String((*clueData)["cluename"])
  1388. customData := TiDb.FindOne("dwd_f_csm_customer_info", map[string]interface{}{
  1389. "clue_id": clueId,
  1390. }, "", "")
  1391. if customData != nil || len(*customData) != 0 {
  1392. companyName = gconv.String((*customData)["company_name"])
  1393. }
  1394. return map[string]interface{}{
  1395. "oldPerson": oldPerson,
  1396. "newPerson": newPerson,
  1397. "operatorId": operatorId,
  1398. "phone": phone,
  1399. "userName": userName,
  1400. "positionId": positionId,
  1401. "clueName": clueName,
  1402. "companyName": companyName,
  1403. }
  1404. }
  1405. // 查找订单实际业绩归属
  1406. func FindPositionIdClueId(uid string) (int64, string, string) {
  1407. personArr := getUserIdToUid(uid)
  1408. productArr, _ := KcProduct()
  1409. querySql := fmt.Sprintf(` SELECT
  1410. d.saler_name as salesperson ,c.position_id,f.dept_name,c.seat_number,b.product_type as productType,b.filter
  1411. FROM
  1412. jianyu.dataexport_order a INNER JOIN jianyu.jy_order_detail b on
  1413. a.order_code=b.order_code and a.user_id in (%s)
  1414. AND (
  1415. b.final_price > 0
  1416. OR (
  1417. b.final_price = 0
  1418. AND ( a.zero_type= "分期付款权益补充" OR a.zero_type= "原订单不支持开通多项权益" OR a.zero_type= "权益码兑换" )))
  1419. AND a.order_status = 1 and a.user_phone not like "%s"
  1420. AND ( a.refund_status != 1 OR a.refund_status IS NULL )
  1421. AND b.service_starttime < "2099-01-01"
  1422. AND b.product_type IN (%s )
  1423. AND ( b.service_type != 4 or b.service_type is NULL OR ( b.service_type = 4 AND TIMESTAMPDIFF(DAY, b.service_starttime, b.service_endtime )> 90 ) )
  1424. inner JOIN jianyu.order_sale_record d on b.order_code=d.ordercode and d.state=1
  1425. INNER JOIN jianyu.entniche_user e on d.ent_userId = e.id
  1426. INNER JOIN dwd_f_crm_personnel_management c on c.ent_id =? and e.name=c.name
  1427. inner join dwd_d_crm_department_level_succbi f on c.position_id=f.position_id
  1428. ORDER BY
  1429. b.service_endtime desc ,b.final_price DESC `, strings.Join(personArr, ","), "9%", strings.Join(productArr, ","))
  1430. log.Println("业绩归属查询:", querySql)
  1431. clueData := TiDb.SelectBySql(querySql, db.EntId)
  1432. if clueData == nil || len(*clueData) == 0 {
  1433. return 0, "", ""
  1434. }
  1435. for _, m := range *clueData {
  1436. productType := gconv.String(m["productType"])
  1437. if productType == "大会员" {
  1438. level := gconv.Int(m["service_type"])
  1439. if level == 4 {
  1440. continue
  1441. }
  1442. }
  1443. deptName := gconv.String(m["dept_name"])
  1444. if strings.Contains(deptName, "一部") || strings.Contains(deptName, "三部") {
  1445. return gconv.Int64(m["position_id"]), gconv.String(m["salesperson"]), gconv.String(m["seat_number"])
  1446. }
  1447. }
  1448. return 0, "", ""
  1449. }
  1450. func refundAutoHistory() {
  1451. data := TiDb.Find("dwd_f_crm_clue_autodraw_record", nil, "", "", -1, -1)
  1452. if data != nil {
  1453. for _, v := range *data {
  1454. seatNumber := gconv.String(v["seatNumber"])
  1455. adata := TiDb.Find("dwd_f_crm_personnel_management", map[string]interface{}{"seat_number": seatNumber}, "", "", -1, -1)
  1456. if adata != nil {
  1457. for _, vv := range *adata {
  1458. if common.IntAll(vv["resign"]) == 0 {
  1459. position_id := common.Int64All(vv["position_id"])
  1460. TiDb.Update("dwd_f_crm_clue_autodraw_record", map[string]interface{}{"seatNumber": seatNumber}, map[string]interface{}{"position_id": position_id})
  1461. break
  1462. }
  1463. }
  1464. }
  1465. }
  1466. }
  1467. }
  1468. func IsFreeze(source string, pay_money int, positionId, trailstatus string) bool {
  1469. log.Println(source, pay_money == 0, FindUpperLimit(gconv.String(
  1470. positionId), "", false), trailstatus)
  1471. if source == "0104" && pay_money == 0 && FindUpperLimit(gconv.String(
  1472. positionId), "", false) {
  1473. return true
  1474. } else if source == "0104" && pay_money > 0 && trailstatus == "08" && FindUpperLimit(gconv.String(
  1475. positionId), "", false) {
  1476. return true
  1477. }
  1478. return false
  1479. }
  1480. // 业绩归属查询
  1481. func FindSaleRecord(orderCode string) (dept string, positionId int64, position string) {
  1482. recordList := Mysql.SelectBySql(`
  1483. SELECT DISTINCT
  1484. a.saler_dept,
  1485. a.saler_name,
  1486. b.phone
  1487. FROM
  1488. order_sale_record a
  1489. INNER JOIN entniche_user b
  1490. on
  1491. a.ordercode = ? and a.ent_userId = b.id
  1492. ORDER BY
  1493. a.state,
  1494. a.money desc
  1495. `, orderCode)
  1496. if recordList != nil && len(*recordList) > 0 {
  1497. saler_dept := gconv.String((*recordList)[0]["saler_dept"])
  1498. if strings.Contains(saler_dept, "销售") {
  1499. saler_dept = "销售部"
  1500. } else if strings.Contains(saler_dept, "市场") {
  1501. saler_dept = "市场部"
  1502. } else if strings.Contains(saler_dept, "客户成功") && !strings.Contains(saler_dept, "客服") {
  1503. saler_dept = "客户成功部"
  1504. } else {
  1505. saler_dept = ""
  1506. }
  1507. positionid := PhoneToPositionId(gconv.String((*recordList)[0]["phone"]))
  1508. if positionid > 0 {
  1509. return saler_dept, positionid, gconv.String((*recordList)[0]["saler_name"])
  1510. }
  1511. }
  1512. return "", int64(0), ""
  1513. }
  1514. func PhoneToPositionId(phone string) int64 {
  1515. positionId := int64(0)
  1516. data := Base.SelectBySql(`SELECT
  1517. b.id
  1518. FROM
  1519. base_user a
  1520. INNER JOIN base_position b ON a.phone = ?
  1521. AND a.id = b.user_id
  1522. AND b.ent_id = 25917`, phone)
  1523. if data != nil && len(*data) > 0 {
  1524. positionId = gconv.Int64((*data)[0]["id"])
  1525. }
  1526. return positionId
  1527. }
  1528. func kcClue(userId, uId, seatNumber, cluename, top_cluetype, sub_cluetype,
  1529. name, phone, position, sourceCode, industry, follow_project_area,
  1530. role, item, subname, topname, remark, demand, department, departments, saleName, source string, positionId int64, isGroup, isCommerce int, keywords []string) bool {
  1531. clueId, uodateId1, uodateId2, uodateId3, uodateId4, uodateId5 := int64(0), int64(0), int64(0), int64(0), int64(0), int64(0)
  1532. nowTime := time.Now().Format("2006-01-02 15:04:05")
  1533. nowTimes := time.Unix(time.Now().Unix()+3600*12, 0).Format("2006-01-02 15:04:05")
  1534. if TiDb.ExecTx("保存线索", func(tx *sql.Tx) bool {
  1535. clueId = TiDb.InsertByTx(tx, "dwd_f_crm_clue_info", map[string]interface{}{
  1536. "userid": userId,
  1537. "uid": uId,
  1538. "seatNumber": seatNumber,
  1539. "position_id": positionId,
  1540. "is_assign": common.If(positionId > 0, 1, 0),
  1541. "comeintime": nowTime,
  1542. "createtime": nowTime,
  1543. "updatetime": nowTime,
  1544. "cluename": cluename,
  1545. "top_cluetype": top_cluetype,
  1546. "sub_cluetype": sub_cluetype,
  1547. "trailstatus": "01",
  1548. "name": name,
  1549. "phone": phone,
  1550. "position": position,
  1551. "department": common.If(sourceCode == "app_xzcyh", departments, department),
  1552. "industry": industry,
  1553. "follow_project_area": follow_project_area,
  1554. "role": role,
  1555. "comeinsource_private": 2,
  1556. "is_task": 1,
  1557. "task_time": nowTime,
  1558. "tasktime": common.If(item == "users", nowTimes, nowTime),
  1559. "taskstatus": 0,
  1560. "tasksource": "线索自动分配" + "-" + topname + "-" + subname,
  1561. "business_scope": common.If(sourceCode == "app_xzcyh", keywords, nil),
  1562. "company_nature": isGroup,
  1563. "company_verification": isCommerce,
  1564. "remark": remark,
  1565. "customer_demand": demand,
  1566. "FREEZE_TIME": nowTime,
  1567. "label": 1,
  1568. "labelChangeTime": time.Now().Format("2006-01-02"),
  1569. })
  1570. uodateId1 = TiDb.InsertByTx(tx, "dwd_f_crm_clue_change_record", map[string]interface{}{
  1571. "clue_id": clueId,
  1572. "position_id": positionId,
  1573. "change_type": "创建线索",
  1574. "new_value": "系统自动创建",
  1575. "createtime": nowTime,
  1576. "BCPCID": common.GetRandom(32),
  1577. "operator_id": -1,
  1578. })
  1579. uodateId2 = TiDb.InsertByTx(tx, "dwd_f_crm_clue_change_record", map[string]interface{}{
  1580. "clue_id": clueId,
  1581. "position_id": positionId,
  1582. "change_field": "position_id",
  1583. "change_type": "所属人变更",
  1584. "old_value": "/",
  1585. "new_value": saleName,
  1586. "createtime": nowTime,
  1587. "BCPCID": common.GetRandom(32),
  1588. "operator_id": -1,
  1589. })
  1590. uodateId3 = TiDb.InsertByTx(tx, "dwd_f_crm_clue_change_record", map[string]interface{}{
  1591. "clue_id": clueId,
  1592. "position_id": positionId,
  1593. "change_field": "trailstatus",
  1594. "change_type": "基本信息变更",
  1595. "old_value": "商机线索",
  1596. "new_value": "新增",
  1597. "createtime": nowTime,
  1598. "BCPCID": common.GetRandom(32),
  1599. "operator_id": -1,
  1600. })
  1601. uodateId5 = TiDb.InsertByTx(tx, "dwd_f_crm_clue_change_record", map[string]interface{}{
  1602. "clue_id": clueId,
  1603. "position_id": positionId,
  1604. "change_field": "top_cluetype",
  1605. "change_type": "基本信息变更",
  1606. "old_value": "/",
  1607. "new_value": topname,
  1608. "createtime": nowTime,
  1609. "BCPCID": common.GetRandom(32),
  1610. "operator_id": -1,
  1611. })
  1612. uodateId5 = TiDb.InsertByTx(tx, "dwd_f_crm_clue_change_record", map[string]interface{}{
  1613. "clue_id": clueId,
  1614. "position_id": positionId,
  1615. "change_field": "sub_cluetype", //222
  1616. "change_type": "基本信息变更",
  1617. "old_value": "/",
  1618. "new_value": subname,
  1619. "createtime": nowTime,
  1620. "BCPCID": common.GetRandom(32),
  1621. "operator_id": -1,
  1622. })
  1623. return clueId > -1 && uodateId1 > -1 && uodateId2 > -1 && uodateId3 > -1 && uodateId4 > -1 && uodateId5 > -1
  1624. }) {
  1625. log.Println("线索分配成功")
  1626. if TiDb.Count("dwd_f_userbase_contacts", map[string]interface{}{"phone": phone}) == 0 {
  1627. TiDb.Insert("dwd_f_userbase_contacts", map[string]interface{}{
  1628. "status": 1,
  1629. "is_delete": 1,
  1630. "createtime": nowTime,
  1631. "updatetime": nowTime,
  1632. "phone": phone,
  1633. "baseinfo_id": uId,
  1634. "SOURCE": source,
  1635. })
  1636. }
  1637. return true
  1638. }
  1639. return false
  1640. }
  1641. type OrderInfo struct {
  1642. Id int64
  1643. UserId string
  1644. CompanyName string
  1645. ProductType string
  1646. OrderCode string
  1647. PayMoney float64
  1648. ReturnMoney float64
  1649. UserPhone string
  1650. StartEnd string
  1651. DisKcName string
  1652. UserName string
  1653. SeriveList []string
  1654. SaleName string
  1655. }
  1656. // 客成发送邮箱
  1657. func KcSend(orderCode, personName string) {
  1658. log.Println("客成发邮件", orderCode)
  1659. orderInfo := KcOrderFormat(orderCode)
  1660. if orderInfo != nil {
  1661. tableAppend := ""
  1662. if len(orderInfo.SeriveList) > 0 {
  1663. tableAppend = fmt.Sprintf(db.KeCheng.Mail.ServiceList, strings.Join(orderInfo.SeriveList, ","))
  1664. }
  1665. if orderInfo.ReturnMoney > 0 {
  1666. tableAppend += fmt.Sprintf(db.KeCheng.Mail.ReturnMoney, orderInfo.ReturnMoney)
  1667. }
  1668. table := ""
  1669. orderInfo.DisKcName = personName
  1670. deptData := Mysql.SelectBySql("select b.mail from jianyu.entniche_department_user a inner join jianyu.entniche_user b on a.dept_id=? and a.user_id=b.id and b.name=? ", db.KeCheng.DeptId, personName)
  1671. adminData := Mysql.SelectBySql(` select c.mail from entniche_department_user a INNER JOIN entniche_user_role b on a.dept_id=59005 and a.user_id = b.user_id and b.role_id=2 INNER JOIN entniche_user c on a.user_id=c.id`)
  1672. table += fmt.Sprintf(db.KeCheng.Mail.Table, orderInfo.ProductType, orderInfo.CompanyName, orderInfo.UserPhone, orderInfo.UserName, orderInfo.OrderCode, orderInfo.PayMoney, orderInfo.StartEnd, orderInfo.DisKcName, orderInfo.SaleName, tableAppend)
  1673. adminMailStr := ""
  1674. if adminData != nil && len(*adminData) > 0 {
  1675. adminMailStr = gconv.String((*adminData)[0]["mail"])
  1676. }
  1677. //发送邮件
  1678. if personName == "" {
  1679. if adminData != nil && len(*adminData) > 0 {
  1680. //发送给管理员
  1681. if adminMailStr != "" {
  1682. gmail := &mail.GmailAuth{
  1683. SmtpHost: db.Mail.SmtpHost,
  1684. SmtpPort: db.Mail.SmtpPort,
  1685. User: db.Mail.User,
  1686. Pwd: db.Mail.Pwd,
  1687. }
  1688. status := mail.GSendMail_q("剑鱼标讯", adminMailStr, "", "", db.KeCheng.Title, fmt.Sprintf(db.KeCheng.Mail.Content, table), "", "", gmail)
  1689. if status {
  1690. log.Println("客成发邮件 send mail success", table, adminMailStr)
  1691. }
  1692. }
  1693. }
  1694. return
  1695. }
  1696. //当事人 管理员发送
  1697. if deptData != nil && len(*deptData) > 0 {
  1698. mailStr := gconv.String((*deptData)[0]["mail"])
  1699. if mailStr != "" || adminMailStr != "" {
  1700. if mailStr == adminMailStr {
  1701. adminMailStr = ""
  1702. }
  1703. gmail := &mail.GmailAuth{
  1704. SmtpHost: db.Mail.SmtpHost,
  1705. SmtpPort: db.Mail.SmtpPort,
  1706. User: db.Mail.User,
  1707. Pwd: db.Mail.Pwd,
  1708. }
  1709. status := true
  1710. if mailStr == "" {
  1711. status = mail.GSendMail_q("剑鱼标讯", adminMailStr, "", "", db.KeCheng.Title, fmt.Sprintf(db.KeCheng.Mail.Content, table), "", "", gmail)
  1712. } else {
  1713. status = mail.GSendMail_q("剑鱼标讯", mailStr, adminMailStr, "", db.KeCheng.Title, fmt.Sprintf(db.KeCheng.Mail.Content, table), "", "", gmail)
  1714. }
  1715. if status {
  1716. log.Println("客成发邮件 send mail success", table, mailStr, adminMailStr)
  1717. }
  1718. }
  1719. }
  1720. }
  1721. }
  1722. func ExitKcSend(personName string, infoList []map[string]interface{}) {
  1723. //退出客成 即将退出客成信息
  1724. deptData := Mysql.SelectBySql("select b.mail from jianyu.entniche_department_user a inner join jianyu.entniche_user b on a.dept_id=? and a.user_id=b.id and b.name=? ", db.KeCheng.DeptId, personName)
  1725. adminData := Mysql.SelectBySql(` select c.mail from entniche_department_user a INNER JOIN entniche_user_role b on a.dept_id=59005 and a.user_id = b.user_id and b.role_id=2 INNER JOIN entniche_user c on a.user_id=c.id`)
  1726. if personName == "" {
  1727. //没有客成人员
  1728. adminMailStr := ""
  1729. if adminData != nil && len(*adminData) > 0 {
  1730. adminMailStr = gconv.String((*adminData)[0]["mail"])
  1731. }
  1732. if adminMailStr != "" {
  1733. gmail := &mail.GmailAuth{
  1734. SmtpHost: db.Mail.SmtpHost,
  1735. SmtpPort: db.Mail.SmtpPort,
  1736. User: db.Mail.User,
  1737. Pwd: db.Mail.Pwd,
  1738. }
  1739. //正文拼接
  1740. startStr := `<html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport"content="width=device-width, initial-scale=1.0"><style>table{width:100%;border-collapse:collapse}th,td{border:1px solid#000;padding:8px;text-align:left}th{background-color:#f2f2f2}</style></head><body><p>以下客户已从或即将从客成系统退出,并移交销售跟进,请收悉,客户明细如下:</p><table><thead><tr><th>序号</th><th>公司名称</th><th>联系人</th><th>姓名</th><th>移交状态</th><th>移交销售原因</th></tr></thead><tbody>`
  1741. for i, v := range infoList {
  1742. startStr += fmt.Sprintf(`<tr><td>%d</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>`, i+1, gconv.String(v["company_name"]), gconv.String(v["phone"]), gconv.String(v["userName"]), gconv.String(v["remrk"]), gconv.String(v["reason"]))
  1743. }
  1744. endStr := `</tbody></table><p></body></html>`
  1745. startStr += endStr
  1746. status := mail.GSendMail_q("剑鱼标讯", adminMailStr, "", "", "客户退出客成系统通知", startStr, "", "", gmail)
  1747. if status {
  1748. log.Println("客成发邮件 send mail success", startStr, adminMailStr)
  1749. }
  1750. }
  1751. return
  1752. }
  1753. if deptData != nil && len(*deptData) > 0 {
  1754. mailStr := gconv.String((*deptData)[0]["mail"])
  1755. adminMailStr := ""
  1756. if adminData != nil && len(*adminData) > 0 {
  1757. adminMailStr = gconv.String((*adminData)[0]["mail"])
  1758. }
  1759. if mailStr != "" || adminMailStr != "" {
  1760. if mailStr == adminMailStr {
  1761. adminMailStr = ""
  1762. }
  1763. gmail := &mail.GmailAuth{
  1764. SmtpHost: db.Mail.SmtpHost,
  1765. SmtpPort: db.Mail.SmtpPort,
  1766. User: db.Mail.User,
  1767. Pwd: db.Mail.Pwd,
  1768. }
  1769. //正文拼接
  1770. startStr := `<html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport"content="width=device-width, initial-scale=1.0"><style>table{width:100%;border-collapse:collapse}th,td{border:1px solid#000;padding:8px;text-align:left}th{background-color:#f2f2f2}</style></head><body><p>以下客户已从或即将从客成系统退出,并移交销售跟进,请收悉,客户明细如下:</p><table><thead><tr><th>序号</th><th>公司名称</th><th>联系人</th><th>姓名</th><th>移交状态</th><th>移交销售原因</th></tr></thead><tbody>`
  1771. for i, v := range infoList {
  1772. startStr += fmt.Sprintf(`<tr><td>%d</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>`, i+1, gconv.String(v["company_name"]), gconv.String(v["phone"]), gconv.String(v["userName"]), gconv.String(v["remrk"]), gconv.String(v["reason"]))
  1773. }
  1774. endStr := `</tbody></table><p></body></html>`
  1775. startStr += endStr
  1776. status := true
  1777. if mailStr == "" {
  1778. status = mail.GSendMail_q("剑鱼标讯", adminMailStr, "", "", "客户退出客成系统通知", startStr, "", "", gmail)
  1779. } else {
  1780. status = mail.GSendMail_q("剑鱼标讯", mailStr, adminMailStr, "", "客户退出客成系统通知", startStr, "", "", gmail)
  1781. }
  1782. if status {
  1783. log.Println("客成发邮件 send mail success", startStr, mailStr)
  1784. }
  1785. }
  1786. }
  1787. }
  1788. // 客成邮件 订单信息初始化
  1789. func KcOrderFormat(orderCode string) *OrderInfo {
  1790. productArr, _ := KcProduct()
  1791. bigmemberService := map[int64]string{}
  1792. Mysql.SelectByBath(1, func(l *[]map[string]interface{}) bool {
  1793. bigmemberService[common.Int64All((*l)[0]["id"])] = gconv.String((*l)[0]["s_name"])
  1794. return true
  1795. }, `select id,s_name from jianyu.bigmember_service`)
  1796. orderData := Mysql.SelectBySql(fmt.Sprintf(`
  1797. SELECT
  1798. d.*,
  1799. SUM( c.return_money ) AS return_money
  1800. FROM
  1801. (
  1802. SELECT
  1803. a.order_code,
  1804. a.pay_money,
  1805. a.user_phone,
  1806. b.service_starttime,
  1807. b.service_endtime,
  1808. b.product_type,
  1809. a.filter,
  1810. a.user_id,
  1811. a.ent_id,
  1812. a.company_name,
  1813. a.create_person,
  1814. b.filter AS productFilter,
  1815. TIMESTAMPDIFF( DAY, b.service_starttime, b.service_endtime ) AS difference
  1816. FROM
  1817. jianyu.dataexport_order a
  1818. INNER JOIN jy_order_detail b ON a.order_code = "%s"
  1819. AND a.order_code = b.order_code
  1820. AND a.order_status = 1
  1821. AND b.product_type IN ( %s )
  1822. ORDER BY
  1823. difference DESC LIMIT 1
  1824. ) d
  1825. LEFT JOIN return_money_record c ON d.order_code = c.order_code
  1826. `, orderCode, strings.Join(productArr, ",")))
  1827. data := &OrderInfo{}
  1828. if orderData != nil && len(*orderData) > 0 {
  1829. orderData := (*orderData)[0]
  1830. id := common.Int64All(orderData["id"])
  1831. user_phone := gconv.String(orderData["user_phone"])
  1832. user_id := gconv.String(orderData["user_id"])
  1833. product_type := gconv.String(orderData["product_type"])
  1834. serviceList := []string{}
  1835. if product_type == "大会员" {
  1836. product_type_name, _, level := GetOrderProduct(product_type, gconv.String(orderData["productFilter"]))
  1837. product_type = product_type_name
  1838. if level == 0 {
  1839. for _, serversId := range strings.Split(gconv.String(gconv.Map(orderData["serversId"])), ",") {
  1840. if serviceName := bigmemberService[common.Int64All(serversId)]; serviceName != "" {
  1841. serviceList = append(serviceList, serviceName)
  1842. }
  1843. }
  1844. }
  1845. }
  1846. //联系人姓名
  1847. sqlStr := `SELECT
  1848. a.phone,
  1849. b.NAME AS bname
  1850. FROM
  1851. dwd_f_userbase_contacts a
  1852. INNER JOIN dwd_f_crm_clue_info b ON ( a.phone = ? AND a.baseinfo_id = b.uid )
  1853. LEFT JOIN dwd_f_csm_customer_info c ON ( b.id = c.clue_id)`
  1854. userName := ""
  1855. if user_phone != "" {
  1856. userData := TiDb.SelectBySql(sqlStr, user_phone)
  1857. if userData != nil && len(*userData) > 0 {
  1858. userName = gconv.String((*userData)[0]["bname"])
  1859. }
  1860. }
  1861. data = &OrderInfo{
  1862. Id: id,
  1863. CompanyName: gconv.String(orderData["company_name"]),
  1864. UserId: user_id,
  1865. ProductType: product_type,
  1866. OrderCode: orderCode,
  1867. PayMoney: common.Float64All(orderData["pay_money"]) / 100,
  1868. ReturnMoney: common.Float64All(orderData["return_money"]) / 100,
  1869. UserPhone: user_phone,
  1870. StartEnd: fmt.Sprintf("%s--%s", strings.Split(gconv.String(orderData["service_starttime"]), " ")[0], strings.Split(gconv.String(orderData["service_endtime"]), " ")[0]),
  1871. SeriveList: serviceList,
  1872. SaleName: gconv.String(orderData["create_person"]),
  1873. UserName: userName,
  1874. }
  1875. }
  1876. return data
  1877. }
  1878. func SaleMail(positionId int64) string {
  1879. person, admin, seniorAdmin := FindDeptAdmin(positionId)
  1880. personMail := ""
  1881. adminMail := ""
  1882. seniorAdminMail := ""
  1883. if person != nil {
  1884. personMail, _ = GetMail(gconv.String(person["name"]))
  1885. }
  1886. if admin != nil {
  1887. adminMail, _ = GetMail(gconv.String(admin["name"]))
  1888. }
  1889. if seniorAdmin != nil {
  1890. seniorAdminMail, _ = GetMail(gconv.String(seniorAdmin["name"]))
  1891. }
  1892. to, cc := "", ""
  1893. if personMail != "" {
  1894. to = personMail
  1895. if adminMail != "" && seniorAdminMail != "" {
  1896. if to != adminMail {
  1897. if to != seniorAdminMail {
  1898. cc = fmt.Sprintf("%s,%s", adminMail, seniorAdminMail)
  1899. }
  1900. } else {
  1901. if to != seniorAdminMail {
  1902. cc = seniorAdminMail
  1903. }
  1904. }
  1905. } else if seniorAdminMail != "" && to != seniorAdminMail {
  1906. cc = seniorAdminMail
  1907. }
  1908. } else {
  1909. if adminMail != "" {
  1910. to = adminMail
  1911. if seniorAdminMail != "" && to != seniorAdminMail {
  1912. cc = seniorAdminMail
  1913. }
  1914. } else {
  1915. to = seniorAdminMail
  1916. }
  1917. }
  1918. if to != "" && cc != "" {
  1919. to = fmt.Sprintf("%s|%s", to, cc)
  1920. }
  1921. return to
  1922. }
  1923. func FindPersonOne(positionId int64) map[string]interface{} {
  1924. personData := TiDb.SelectBySql(`SELECT
  1925. b.name,
  1926. b.position_id,
  1927. b.seat_number,
  1928. b.role_id,
  1929. a.dept_name
  1930. FROM
  1931. dwd_d_crm_department_level_succbi a
  1932. INNER JOIN dwd_f_crm_personnel_management b ON a.position_id = ?
  1933. AND a.position_id = b.position_id`, positionId)
  1934. if personData == nil || len(*personData) == 0 {
  1935. return nil
  1936. }
  1937. return (*personData)[0]
  1938. }
  1939. // 进客成商品查询
  1940. func KcProduct() ([]string, map[string]bool) {
  1941. var strArr []string
  1942. strMap := map[string]bool{}
  1943. productData := Mysql.SelectBySql(`SELECT id ,
  1944. CONCAT( '"', class_name,'"' ) as product
  1945. FROM
  1946. jy_product_class
  1947. WHERE
  1948. s_service = 1`)
  1949. if productData == nil && len(*productData) == 0 {
  1950. return strArr, strMap
  1951. }
  1952. for _, m := range *productData {
  1953. strMap[gconv.String(m["product"])] = true
  1954. strArr = append(strArr, gconv.String(m["product"]))
  1955. }
  1956. return strArr, strMap
  1957. }
  1958. func GetOrderProduct(productType string, file string) (string, int64, int64) {
  1959. fileJson := gconv.Map(file)
  1960. if fileJson == nil || len(fileJson) == 0 {
  1961. return "", 0, 0
  1962. }
  1963. productName := ""
  1964. level := int64(0)
  1965. switch productType {
  1966. case "大会员":
  1967. level = gconv.Int64(fileJson["comboId"])
  1968. if level == 0 {
  1969. level = gconv.Int64(fileJson["level"])
  1970. }
  1971. switch level {
  1972. case 0:
  1973. productName = "大会员自定义"
  1974. case 30190:
  1975. productName = "大会员商机版2.0(单省版)"
  1976. case 6:
  1977. productName = "大会员商机版2.0"
  1978. case 7:
  1979. productName = "大会员专家版2.0"
  1980. }
  1981. default:
  1982. productName = productType
  1983. }
  1984. productData := TiDb.FindOne("dwd_d_csm_product_access_code", map[string]interface{}{
  1985. "name": productName,
  1986. }, "", "")
  1987. if productData == nil || len(*productData) == 0 {
  1988. return productName, 0, level
  1989. }
  1990. return productName, gconv.Int64((*productData)["code"]), level
  1991. }
  1992. func GetTimeDifference(timeStr1, timeStr2 string) int {
  1993. // 解析时间字符串
  1994. t1, err1 := time.Parse(time.DateTime, timeStr1)
  1995. t2, err2 := time.Parse(time.DateTime, timeStr2)
  1996. if err1 != nil || err2 != nil {
  1997. fmt.Println("时间格式错误:", err1, err2)
  1998. return 0
  1999. }
  2000. // 计算时间差
  2001. daysDiff := gconv.Int(t2.Sub(t1).Hours() / 24)
  2002. fmt.Printf("两个时间相差 %.0f 天\n", daysDiff)
  2003. return daysDiff
  2004. }
  2005. func getOrderData(sql string) (map[string]map[string]interface{}, string) {
  2006. data := Mysql.SelectBySql(sql)
  2007. orderMap := map[string]map[string]interface{}{}
  2008. lastEndTime := ""
  2009. for _, v := range *data {
  2010. orderCode := gconv.String(v["order_code"])
  2011. product_type := gconv.String(v["productType"])
  2012. vip_starttime := gconv.String(v["service_starttime"])
  2013. vip_endtime := gconv.String(v["service_endtime"])
  2014. //判断一下服务周期
  2015. difference := GetTimeDifference(vip_starttime, vip_endtime)
  2016. _, productInt64, _ := GetOrderProduct(product_type, gconv.String(v["productFilter"]))
  2017. if productInt64 == 0 {
  2018. continue
  2019. }
  2020. if _, exists := orderMap[orderCode]; exists {
  2021. //判断服务周期
  2022. data := orderMap[orderCode]
  2023. //商品类型获取
  2024. oldDifference := gconv.Int(data["difference"])
  2025. if oldDifference >= difference {
  2026. //需要更换
  2027. lastEndTime = vip_endtime
  2028. v["difference"] = difference
  2029. v["product"] = productInt64
  2030. v["service_endtime"] = vip_endtime
  2031. v["service_starttime"] = vip_starttime
  2032. v["product_type"] = product_type
  2033. orderMap[orderCode] = v
  2034. }
  2035. } else {
  2036. lastEndTime = vip_endtime
  2037. v["difference"] = difference
  2038. v["product"] = productInt64
  2039. v["product_type"] = product_type
  2040. orderMap[orderCode] = v
  2041. }
  2042. }
  2043. return orderMap, lastEndTime
  2044. }