kc.go 74 KB

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