kc.go 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071
  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.filter as productFilter,TIMESTAMPDIFF(DAY, b.service_starttime, b.service_endtime) as difference
  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["autoUpdate"])
  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 `
  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. log.Println("后台订单线索定时任务开始")
  532. lastOrderClueId := cfg.LastOrderClueId
  533. nowTime := time.Now().Format(date.Date_Full_Layout)
  534. product_type_str2 := `"大会员","企业商机管理","VIP订阅"`
  535. sql := fmt.Sprintf(`select a.*,b.product_type as productType ,b.service_starttime,b.service_endtime,b.filter AS productFilter from dataexport_order a
  536. INNER JOIN jy_order_detail b on a.order_code=b.order_code
  537. and b.update_time>="%s" AND a.user_phone NOT LIKE "%s" and a.user_id !=""
  538. 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)
  539. data := Mysql.SelectBySql(sql)
  540. if data != nil && *data != nil && len(*data) > 0 {
  541. for _, v := range *data {
  542. payMoney := common.IntAll(v["pay_money"])
  543. orderCode := gconv.String(v["order_code"])
  544. saleDep, _, salesperson := FindSaleRecord(orderCode)
  545. userPhone := gconv.String(v["user_phone"])
  546. createperson := gconv.String(v["create_person"])
  547. userId, uId, cluename, seatNumber, positionId, trailstatus, clueId := gconv.String(v["user_id"]), "", "", "", int64(0), "", int64(0)
  548. if saleDep != "" {
  549. //销售部
  550. query := map[string]interface{}{}
  551. source := ""
  552. if !mongodb.IsObjectIdHex(userId) {
  553. userMapping := TiDb.FindOne("dwd_f_userbase_id_mapping", map[string]interface{}{"position_id": userId}, "", "")
  554. if userMapping != nil && len(*userMapping) > 0 {
  555. userId = gconv.String((*userMapping)["userid"])
  556. } else {
  557. log.Println("后台订单--未查询到 ", userPhone)
  558. break
  559. }
  560. }
  561. query["userid"] = userId
  562. userInfo := TiDb.FindOne("dwd_f_userbase_baseinfo", query, "", "")
  563. if userInfo != nil && len(*userInfo) > 0 {
  564. uId = gconv.String((*userInfo)["uid"])
  565. source = gconv.String((*userInfo)["source"])
  566. } else {
  567. log.Println("后台订单--未查询到 ", query, userPhone)
  568. break
  569. }
  570. is_assign := 1
  571. mailContent := ""
  572. cluename = gconv.String(v["company_name"])
  573. mailContent = fmt.Sprintf("%s(%s)", cluename, userPhone)
  574. if cluename == "" {
  575. cluename = userPhone
  576. mailContent = userPhone
  577. }
  578. if payMoney > 0 {
  579. trailstatus = "08"
  580. } else {
  581. trailstatus = "01"
  582. }
  583. isGroup, isCommerce := GetCompanyType(cluename, uId) //判断是否集团公司、工商库
  584. clueData := TiDb.FindOne("dwd_f_crm_clue_info", map[string]interface{}{"uid": uId}, "", "")
  585. if clueData == nil || len(*clueData) == 0 {
  586. log.Println("saleDep", saleDep)
  587. if saleDep == "销售部" {
  588. //撞单
  589. log.Println("销售部订单", saleDep)
  590. if strings.Contains(salesperson, ",") {
  591. log.Println("销售部撞单 ", salesperson)
  592. if salesperson == "" {
  593. salesperson = createperson
  594. }
  595. }
  596. log.Println("销售部订单salesperson", salesperson)
  597. saleData := TiDb.FindOne("dwd_f_crm_personnel_management", map[string]interface{}{"name": salesperson}, "", "")
  598. if saleData != nil {
  599. seatNumber = gconv.String((*saleData)["seat_number"])
  600. positionId = common.Int64All((*saleData)["position_id"])
  601. }
  602. if IsFreeze(source, payMoney, gconv.String(positionId), trailstatus) {
  603. //线索需要冻结
  604. is_assign = -3
  605. }
  606. clueId = TiDb.Insert("dwd_f_crm_clue_info", map[string]interface{}{
  607. "userid": userId,
  608. "uid": uId,
  609. "seatNumber": seatNumber,
  610. "position_id": positionId,
  611. "is_assign": is_assign,
  612. "comeintime": nowTime,
  613. "createtime": nowTime,
  614. "updatetime": nowTime,
  615. "cluename": cluename,
  616. "top_cluetype": "4",
  617. "sub_cluetype": "154",
  618. "trailstatus": trailstatus,
  619. "name": userPhone,
  620. "phone": userPhone,
  621. "comeinsource_private": 2,
  622. "is_task": 0,
  623. "taskstatus": 0,
  624. "company_nature": isGroup,
  625. "company_verification": isCommerce,
  626. "FREEZE_TIME": nowTime,
  627. })
  628. } else if saleDep == "市场部" {
  629. log.Println("市场部订单", saleDep)
  630. clueId = TiDb.Insert("dwd_f_crm_clue_info", map[string]interface{}{
  631. "userid": userId,
  632. "uid": uId,
  633. "is_assign": -2,
  634. "createtime": nowTime,
  635. "updatetime": nowTime,
  636. "cluename": cluename,
  637. "top_cluetype": "4",
  638. "sub_cluetype": "154",
  639. "trailstatus": trailstatus,
  640. "name": userPhone,
  641. "phone": userPhone,
  642. "is_task": 0,
  643. "taskstatus": 0,
  644. "company_nature": isGroup,
  645. "company_verification": isCommerce,
  646. "FREEZE_TIME": nowTime,
  647. })
  648. }
  649. if clueId > 0 {
  650. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  651. "clue_id": clueId,
  652. "position_id": common.If(positionId > 0, positionId, -1),
  653. "change_type": "创建线索",
  654. "new_value": "系统自动创建",
  655. "createtime": nowTime,
  656. "BCPCID": common.GetRandom(32),
  657. "operator_id": -1,
  658. })
  659. if is_assign == -3 {
  660. //新增冻结记录
  661. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  662. "clue_id": clueId,
  663. "position_id": positionId,
  664. "change_type": "线索冻结",
  665. "new_value": "销售人员私海已达上限",
  666. "createtime": nowTime,
  667. "BCPCID": common.GetRandom(32),
  668. "operator_id": -1,
  669. })
  670. //移交失败发送消息
  671. if IsFreeze(source, payMoney, gconv.String(positionId), trailstatus) {
  672. //发送邮件信息
  673. OrderCreateFail(positionId, mailContent)
  674. }
  675. }
  676. }
  677. }
  678. }
  679. cfg.LastOrderClueId = gconv.String(v["autoUpdate"])
  680. }
  681. }
  682. common.WriteSysConfig(&cfg)
  683. log.Println("后台订单线索定时任务结束")
  684. }
  685. func refundAuto() {
  686. log.Println("自动移交销售定时任务开始")
  687. findNowTime := time.Now().AddDate(0, 0, -db.ExpirationPeriod).Format(date.Date_Full_Layout)
  688. nowTime := time.Now().Format(date.Date_Full_Layout)
  689. mailData := map[string][]map[string]interface{}{}
  690. salesEmailData := map[int64][]map[string]interface{}{}
  691. TiDb.SelectByBath(100, func(l *[]map[string]interface{}) bool {
  692. for _, v := range *l {
  693. cluename, company_nature, company_verification, uid, phone, userName, oldSaleId, oldsaleName := "", 0, 0, "", "", "", int64(0), ""
  694. saleId, newSeatNumber, newPerson := int64(0), "", ""
  695. clueId := common.Int64All(v["clue_id"])
  696. company_name := gconv.String(v["company_name"])
  697. name := gconv.String(v["name"])
  698. kcposition_id := common.Int64All(v["position_id"])
  699. isRenewalProtection := common.IntAll(v["is_renewal_protection"])
  700. clueData := TiDb.FindOne("dwd_f_crm_clue_info", map[string]interface{}{"id": clueId}, "name,phone,company_nature,company_verification,cluename,userid,position_id,uid", "")
  701. if clueData != nil && len(*clueData) > 0 {
  702. uid = gconv.String((*clueData)["uid"])
  703. saleId, newPerson, newSeatNumber = FindPositionIdClueId(uid)
  704. oldSaleId = common.Int64All((*clueData)["position_id"])
  705. oldPersonData := FindPersonOne(oldSaleId)
  706. if oldSaleId != 0 {
  707. oldsaleName = gconv.String(oldPersonData["name"])
  708. }
  709. cluename = gconv.String((*clueData)["cluename"])
  710. userName = gconv.String((*clueData)["name"])
  711. company_nature = common.IntAll((*clueData)["company_nature"])
  712. company_verification = common.IntAll((*clueData)["company_verification"])
  713. phone = gconv.String((*clueData)["phone"])
  714. }
  715. personArr := getUserIdToUid(uid)
  716. productArr, _ := KcProduct()
  717. if len(productArr) == 0 || len(personArr) == 0 {
  718. log.Println("查询不到进客成商品类型或查询不到用户信息")
  719. continue
  720. }
  721. //查询即将到期数据
  722. if isRenewalProtection == 0 {
  723. 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, ","))
  724. _, vipEndDateStr := getOrderData(sqlStr)
  725. if vipEndDateStr != "" {
  726. endDate := time.Now().AddDate(0, 0, -db.ExpirationPeriod+3).Unix()
  727. startDate := time.Now().AddDate(0, 0, -db.ExpirationPeriod+2).Unix()
  728. vipEndDate, _ := time.ParseInLocation(time.DateTime, vipEndDateStr, time.Local)
  729. log.Println(vipEndDate.Unix() > startDate, vipEndDate.Unix() < endDate)
  730. log.Println(vipEndDate.Unix(), startDate, endDate)
  731. if vipEndDate.Unix() > startDate && vipEndDate.Unix() < endDate {
  732. //即将到期
  733. mailData[name] = append(mailData[name], map[string]interface{}{
  734. "company_name": company_name,
  735. "phone": phone,
  736. "userName": userName,
  737. "remrk": "3天后即将移交",
  738. "reason": "成交客户续费失败",
  739. })
  740. continue
  741. }
  742. }
  743. }
  744. isFull := false
  745. isAllRefund := false
  746. 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, ","))
  747. myOrders, _ := getOrderData(orderSql)
  748. if myOrders != nil || len(myOrders) > 0 {
  749. refundCount := 0
  750. for _, v := range myOrders {
  751. if common.IntAll(v["refund_status"]) == 1 {
  752. refundCount++
  753. }
  754. }
  755. if len(myOrders) > 0 && len(myOrders) == refundCount {
  756. isAllRefund = true
  757. }
  758. }
  759. if isAllRefund {
  760. //全退款了
  761. 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)
  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. "new_value": "成交客户申请退款",
  767. "createtime": nowTime,
  768. "BCPCID": common.GetRandom(32),
  769. "operator_id": -1,
  770. })
  771. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  772. "clue_id": clueId,
  773. "position_id": common.If(kcposition_id > 0, kcposition_id, -1),
  774. "change_field": "trailstatus",
  775. "change_type": "基本信息变更",
  776. "old_value": "成交客户",
  777. "new_value": "商机线索",
  778. "createtime": nowTime,
  779. "BCPCID": common.GetRandom(32),
  780. "operator_id": -1,
  781. })
  782. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  783. "clue_id": clueId,
  784. "position_id": common.If(kcposition_id > 0, kcposition_id, -1),
  785. "change_type": "客户成功经理",
  786. "change_field": "position_id",
  787. "old_value": name,
  788. "new_value": "/",
  789. "createtime": nowTime,
  790. "BCPCID": common.GetRandom(32),
  791. "operator_id": -1,
  792. })
  793. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  794. "clue_id": clueId,
  795. "position_id": common.If(kcposition_id > 0, kcposition_id, -1),
  796. "change_type": "移交销售",
  797. "new_value": "成交客户申请退款",
  798. "createtime": nowTime,
  799. "BCPCID": common.GetRandom(32),
  800. "operator_id": -1,
  801. })
  802. mailData[name] = append(mailData[name], map[string]interface{}{
  803. "company_name": company_name,
  804. "phone": phone,
  805. "userName": userName,
  806. "remrk": "已移交",
  807. "reason": "成交客户申请退款",
  808. })
  809. TiDb.UpdateOrDeleteBySql(`UPDATE dwd_f_csm_customer_info SET is_transfer=1 WHERE clue_id = ?`, clueId)
  810. } else {
  811. 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)
  812. order1 := Mysql.SelectBySql(order1Sql)
  813. if order1 == nil || len(*order1) == 0 {
  814. isOk := false
  815. order3Sql := fmt.Sprintf(`select a.* , b.product_type AS productType,b.service_starttime,b.service_endtime ,b.filter AS productFilter
  816. from dataexport_order a INNER JOIN jy_order_detail b
  817. on a.order_code=b.order_code and a.user_id in (%s) and b.product_type in (%s)
  818. and order_status = 1 and b.service_endtime<"%s" ORDER BY b.service_endtime desc `,
  819. strings.Join(personArr, ","), strings.Join(productArr, ","), findNowTime)
  820. _, vip_endtime := getOrderData(order3Sql)
  821. if vip_endtime != "" {
  822. //获取最后一个订单信息
  823. if isRenewalProtection == 1 {
  824. vip_endtimes, _ := time.ParseInLocation(date.Date_Full_Layout, vip_endtime, time.Local)
  825. //查询申请保护时间
  826. renewalTime := time.Now()
  827. timeData := TiDb.SelectBySql(`select max(createtime) as createtime from dwd_f_crm_clue_change_record where clue_id = ? and change_type="申请续费保护"`, clueId)
  828. if timeData != nil && len(*timeData) > 0 {
  829. if gconv.String(gconv.String((*timeData)[0]["createtime"])) != "" {
  830. renewalTime, _ = time.ParseInLocation(date.Date_Full_Layout, gconv.String((*timeData)[0]["createtime"]), time.Local)
  831. }
  832. }
  833. renewalInt := renewalTime.Unix()
  834. log.Println("申请保护期时间", clueId, renewalInt)
  835. log.Println("申请保护期时间222", time.Now().Unix()-vip_endtimes.Unix(), (db.HandoverCycle-1)*86400, (db.HandoverCycle)*86400)
  836. //查看服务到期时间
  837. if renewalInt != 0 && renewalInt < db.CustomerTime {
  838. //三个月
  839. if time.Now().Unix()-vip_endtimes.Unix() < 3*30*86400 {
  840. isOk = true
  841. }
  842. } else if (db.HandoverCycle-5)*86400 < time.Now().Unix()-vip_endtimes.Unix() && time.Now().Unix()-vip_endtimes.Unix() < (db.HandoverCycle-4)*86400 {
  843. //提前一天提示
  844. mailData[name] = append(mailData[name], map[string]interface{}{
  845. "company_name": company_name,
  846. "phone": phone,
  847. "userName": userName,
  848. "remrk": "3天后即将移交",
  849. "reason": "成交客户续费失败",
  850. })
  851. isOk = true
  852. } else if time.Now().Unix()-vip_endtimes.Unix() < db.HandoverCycle*86400 {
  853. isOk = true
  854. }
  855. }
  856. }
  857. if !isOk {
  858. //全到期了
  859. if saleId > 0 {
  860. saleData := TiDb.FindOne("dwd_f_crm_personnel_management", map[string]interface{}{"position_id": saleId, "resign": 0}, "", "")
  861. if saleData != nil && len(*saleData) > 0 {
  862. //该销售人没有变更
  863. } else {
  864. if company_nature == 0 && company_verification == 1 && cluename != "" {
  865. adata := TiDb.Find("dwd_f_crm_clue_info", map[string]interface{}{"cluename": cluename, "is_assign": 1}, "seatNumber,position_id", "", -1, -1)
  866. if adata != nil && len(*adata) > 0 {
  867. isOks := false
  868. for _, vv := range *adata {
  869. position_ids := common.Int64All(vv["position_id"])
  870. newSeatNumber = gconv.String(vv["seatNumber"])
  871. saleDatas := TiDb.FindOne("dwd_f_crm_personnel_management", map[string]interface{}{"position_id": position_ids, "resign": 0}, "", "")
  872. if saleDatas != nil && len(*saleDatas) > 0 {
  873. saleId = position_ids
  874. newPerson = gconv.String((*saleDatas)["name"])
  875. isOks = true
  876. break
  877. }
  878. }
  879. if !isOks {
  880. 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)
  881. if len(*sdata) == 0 {
  882. 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)
  883. }
  884. if sdata != nil && len(*sdata) > 0 {
  885. saleId = common.Int64All((*sdata)[0]["position_id"])
  886. newSeatNumber = gconv.String((*sdata)[0]["seat_number"])
  887. newPerson = gconv.String((*sdata)[0]["name"])
  888. }
  889. }
  890. }
  891. } else {
  892. sdata := &[]map[string]interface{}{}
  893. //查看当前是否属于一部三部
  894. userData := FindPersonOne(saleId)
  895. if userData != nil {
  896. deptName := gconv.String(userData["dept_name"])
  897. if strings.Contains(deptName, "一部") {
  898. 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)
  899. if len(*sdata) == 0 {
  900. 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)
  901. }
  902. } else if strings.Contains(deptName, "三部") {
  903. 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)
  904. }
  905. }
  906. if sdata != nil && len(*sdata) > 0 {
  907. saleId = common.Int64All((*sdata)[0]["position_id"])
  908. newSeatNumber = gconv.String((*sdata)[0]["seat_number"])
  909. newPerson = gconv.String((*sdata)[0]["name"])
  910. }
  911. }
  912. }
  913. }
  914. if kcposition_id > 0 {
  915. mailData[name] = append(mailData[name], map[string]interface{}{
  916. "company_name": company_name,
  917. "phone": phone,
  918. "userName": userName,
  919. "remrk": "已移交",
  920. "reason": "成交客户续费失败",
  921. })
  922. }
  923. isFull = FindUpperLimit(gconv.String(saleId), "", false)
  924. if saleId > 0 {
  925. salesEmailData[saleId] = append(salesEmailData[saleId], map[string]interface{}{
  926. "company_name": company_name,
  927. "phone": phone,
  928. "userName": userName,
  929. "remrk": "已移交",
  930. "reason": "成交客户续费失败",
  931. "cluename": cluename,
  932. })
  933. if saleId != oldSaleId {
  934. //新增个人员变更
  935. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  936. "clue_id": clueId,
  937. "position_id": saleId,
  938. "change_field": "position_id",
  939. "change_type": "所属人变更",
  940. "old_value": common.If(oldsaleName != "", oldsaleName, "/"),
  941. "new_value": common.If(newPerson != "", newPerson, "/"),
  942. "createtime": nowTime,
  943. "BCPCID": common.GetRandom(32),
  944. "operator_id": -1,
  945. })
  946. if isFull {
  947. 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)
  948. } else {
  949. 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)
  950. }
  951. } else {
  952. if isFull {
  953. 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)
  954. } else {
  955. 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)
  956. }
  957. }
  958. } else if saleId == 0 {
  959. //找不到人
  960. 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)
  961. if oldSaleId != 0 {
  962. //新增个人员变更
  963. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  964. "clue_id": clueId,
  965. "position_id": saleId,
  966. "change_field": "position_id",
  967. "change_type": "所属人变更",
  968. "old_value": common.If(oldsaleName != "", oldsaleName, "/"),
  969. "new_value": common.If(newPerson != "", newPerson, "/"),
  970. "createtime": nowTime,
  971. "BCPCID": common.GetRandom(32),
  972. "operator_id": -1,
  973. "SHUOMING": "业绩归属查不到人",
  974. })
  975. //再做一个记录变更
  976. }
  977. }
  978. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  979. "clue_id": clueId,
  980. "position_id": common.If(kcposition_id > 0, kcposition_id, -1),
  981. "change_type": "基本信息变更",
  982. "old_value": "成交客户",
  983. "change_field": "trailstatus",
  984. "new_value": "商机线索",
  985. "createtime": nowTime,
  986. "BCPCID": common.GetRandom(32),
  987. "operator_id": -1,
  988. })
  989. if saleId > 0 {
  990. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  991. "clue_id": clueId,
  992. "position_id": saleId,
  993. "change_type": "加入任务车",
  994. "new_value": "线索自动分配-其他-成交客户续约失败",
  995. "createtime": nowTime,
  996. "BCPCID": common.GetRandom(32),
  997. "operator_id": -1,
  998. })
  999. }
  1000. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  1001. "clue_id": clueId,
  1002. "position_id": common.If(kcposition_id > 0, kcposition_id, -1),
  1003. "change_type": "客户成功经理",
  1004. "change_field": "position_id",
  1005. "old_value": name,
  1006. "new_value": "/",
  1007. "createtime": nowTime,
  1008. "BCPCID": common.GetRandom(32),
  1009. "operator_id": -1,
  1010. })
  1011. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  1012. "clue_id": clueId,
  1013. "position_id": saleId,
  1014. "change_type": "移交销售",
  1015. "new_value": "成交客户续费失败,到期自动移交",
  1016. "createtime": nowTime,
  1017. "BCPCID": common.GetRandom(32),
  1018. "operator_id": -1,
  1019. })
  1020. TiDb.UpdateOrDeleteBySql(`UPDATE dwd_f_csm_customer_info SET is_transfer=1 WHERE clue_id = ?`, clueId)
  1021. if isFull {
  1022. //新增冻结记录
  1023. TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
  1024. "clue_id": clueId,
  1025. "position_id": saleId,
  1026. "change_type": "线索冻结",
  1027. "new_value": "销售人员私海已达上限",
  1028. "createtime": nowTime,
  1029. "BCPCID": common.GetRandom(32),
  1030. "operator_id": -1,
  1031. })
  1032. //发送邮件
  1033. mailContent := ""
  1034. if cluename != "" {
  1035. if phone != "" {
  1036. if cluename == phone {
  1037. mailContent = phone
  1038. } else {
  1039. mailContent = fmt.Sprintf("%s(%s)", cluename, phone)
  1040. }
  1041. } else {
  1042. mailContent = cluename
  1043. }
  1044. } else {
  1045. mailContent = phone
  1046. }
  1047. HandOverFail(saleId, mailContent)
  1048. }
  1049. }
  1050. }
  1051. }
  1052. }
  1053. return true
  1054. }, `select ent_id,clue_id,position_id,name,is_renewal_protection,company_name from dwd_f_csm_customer_info where is_transfer = 0`)
  1055. //}, `select ent_id,clue_id,position_id,name,is_renewal_protection,company_name from dwd_f_csm_customer_info where id =570010`)
  1056. //移交电销提醒
  1057. for i, v := range mailData {
  1058. ExitKcSend(i, v)
  1059. }
  1060. //移交电销销售提醒
  1061. for i, v := range salesEmailData {
  1062. ExitKcSaleSend(i, v)
  1063. }
  1064. log.Println("自动移交销售定时任务结束")
  1065. }
  1066. // 查找一部三部人员信息 返回人员信息 以及管理员信息
  1067. func FindDeptAdmin(positionId int64) (map[string]interface{}, map[string]interface{}, map[string]interface{}) {
  1068. //先判断那个部门的
  1069. userData1 := TiDb.SelectBySql(`SELECT
  1070. a.position_id,
  1071. a.name,
  1072. b.seat_number,
  1073. b.role_id,
  1074. a.bi_pcode,
  1075. a.dept_name,
  1076. a.resign
  1077. FROM
  1078. (SELECT *
  1079. FROM dwd_d_crm_department_level_succbi u1
  1080. WHERE id = (
  1081. SELECT MAX(id)
  1082. FROM dwd_d_crm_department_level_succbi u2
  1083. WHERE u1.position_id = u2.position_id
  1084. )
  1085. ORDER BY id desc) a
  1086. INNER JOIN (SELECT *
  1087. FROM dwd_f_crm_personnel_management u1
  1088. WHERE id = (
  1089. SELECT MAX(id)
  1090. FROM dwd_f_crm_personnel_management u2
  1091. WHERE u1.position_id = u2.position_id
  1092. )
  1093. ORDER BY id desc) b ON a.dept_name LIKE "%销售一部%"
  1094. AND a.position_id = b.position_id`)
  1095. userData3 := TiDb.SelectBySql(`SELECT
  1096. a.position_id,
  1097. a.name,
  1098. b.seat_number,
  1099. b.role_id,
  1100. a.bi_pcode,
  1101. a.dept_name,
  1102. a.resign
  1103. FROM
  1104. (SELECT *
  1105. FROM dwd_d_crm_department_level_succbi u1
  1106. WHERE id = (
  1107. SELECT MAX(id)
  1108. FROM dwd_d_crm_department_level_succbi u2
  1109. WHERE u1.position_id = u2.position_id
  1110. )
  1111. ORDER BY id desc) a
  1112. INNER JOIN (SELECT *
  1113. FROM dwd_f_crm_personnel_management u1
  1114. WHERE id = (
  1115. SELECT MAX(id)
  1116. FROM dwd_f_crm_personnel_management u2
  1117. WHERE u1.position_id = u2.position_id
  1118. )
  1119. ORDER BY id desc) b ON
  1120. a.dept_name LIKE "%销售三部"
  1121. AND a.position_id = b.position_id`)
  1122. if userData3 == nil || len(*userData3) == 0 || userData1 == nil || len(*userData1) == 0 {
  1123. log.Println("找不到一部三部员工信息")
  1124. return nil, nil, nil
  1125. }
  1126. //一部高级管理员信息
  1127. seniorAdmin1 := map[string]interface{}{}
  1128. //三部高级管理员信息
  1129. seniorAdmin3 := map[string]interface{}{}
  1130. //一部管理员信息
  1131. admin1 := map[string]map[string]interface{}{}
  1132. //返回当前人信息
  1133. admin := map[string]interface{}{}
  1134. for _, v := range *userData3 {
  1135. v["type"] = 3
  1136. id := gconv.Int64(v["position_id"])
  1137. roleId := gconv.Int64(v["role_id"])
  1138. resign := gconv.Int64(v["resign"])
  1139. if id == positionId && resign == 0 {
  1140. admin = v
  1141. }
  1142. if roleId == 8 {
  1143. v["orderStatus"] = 2
  1144. seniorAdmin3 = v
  1145. }
  1146. }
  1147. for _, v := range *userData1 {
  1148. v["type"] = 1
  1149. id := gconv.Int64(v["position_id"])
  1150. roleId := gconv.Int64(v["role_id"])
  1151. dept_name := gconv.String(v["dept_name"])
  1152. resign := gconv.Int64(v["resign"])
  1153. if id == positionId && resign == 0 {
  1154. admin = v
  1155. }
  1156. if roleId == 8 {
  1157. v["orderStatus"] = 2
  1158. seniorAdmin1 = v
  1159. } else if roleId == 3 {
  1160. admin1[dept_name] = v
  1161. }
  1162. }
  1163. //查看当前人属于哪个部门
  1164. if admin == nil {
  1165. //当前人不属于电销部的
  1166. admin = *(TiDb.FindOne("dwd_f_crm_personnel_management", map[string]interface{}{
  1167. "position_id": positionId,
  1168. "resign": 1,
  1169. }, "name", ""))
  1170. }
  1171. positiontype := gconv.Int64(admin["type"])
  1172. deptName := gconv.String(admin["dept_name"])
  1173. switch positiontype {
  1174. case 1:
  1175. roleId := gconv.Int64(admin["role_id"])
  1176. if roleId == 3 {
  1177. return admin, nil, seniorAdmin1
  1178. }
  1179. return admin, admin1[deptName], seniorAdmin1
  1180. case 3:
  1181. return admin, nil, seniorAdmin3
  1182. default:
  1183. return admin, nil, nil
  1184. }
  1185. }
  1186. // 邮箱获取
  1187. func GetMail(personName string) (string, string) {
  1188. data := Mysql.SelectBySql(`select name,mail,img from entniche_user where ent_id =?`, db.EntId)
  1189. if data == nil || len(*data) == 0 {
  1190. return "", ""
  1191. }
  1192. for _, m := range *data {
  1193. name := gconv.String(m["name"])
  1194. if name == personName {
  1195. //
  1196. return gconv.String(m["mail"]), gconv.String(m["img"])
  1197. }
  1198. }
  1199. return "", ""
  1200. }
  1201. // 退客成进销售 销售收邮件
  1202. func ExitKcSaleSend(positionId int64, infoList []map[string]interface{}) {
  1203. to := SaleMail(positionId)
  1204. //退出客成 即将退出客成信息 销售信息编辑
  1205. gmail := &mail.GmailAuth{
  1206. SmtpHost: db.Mail.SmtpHost,
  1207. SmtpPort: db.Mail.SmtpPort,
  1208. User: db.Mail.User,
  1209. Pwd: db.Mail.Pwd,
  1210. }
  1211. //正文拼接
  1212. startStr := `<html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport"content="width=device-width, initial-scale=1.0">
  1213. <style>table{width:100%;border-collapse:collapse}th,td{border:1px solid#000;padding:8px;text-align:left}th{background-color:#f2f2f2}</style></head>
  1214. <body><p>以下客户已从或即将从客成系统退出,并移交销售跟进,请收悉,客户明细如下:</p>
  1215. <table><thead><tr><th>序号</th><th>线索名称</th><th>联系人</th><th>姓名</th><th>移交状态</th></tr></thead><tbody>`
  1216. for i, v := range infoList {
  1217. 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"]))
  1218. }
  1219. endStr := `</tbody></table><p></body></html>`
  1220. startStr += endStr
  1221. if to != "" {
  1222. status := mail.GSendMail_q("剑鱼标讯", to, "", "", "成交客户续费失败移交销售通知", startStr, "", "", gmail)
  1223. if status {
  1224. log.Println("客成发邮件 send mail success", startStr, to)
  1225. }
  1226. }
  1227. }
  1228. // 客成人员变更发邮件
  1229. func CustomerChange() {
  1230. personMap := map[int64]string{}
  1231. 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)
  1232. if personData != nil && len(*personData) > 0 {
  1233. for _, v := range *personData {
  1234. personMap[gconv.Int64(v["position_id"])] = gconv.String(v["name"])
  1235. }
  1236. }
  1237. startTime := cfg.LastKcChangeTime
  1238. if startTime == "" {
  1239. startTime = time.Now().Format(time.DateTime)
  1240. }
  1241. customMap1 := map[string][]map[string]interface{}{}
  1242. customMap2 := map[string][]map[string]interface{}{}
  1243. saleMap := map[int64][]map[string]interface{}{}
  1244. saleNobodyCustomMapMap := map[int64][]map[string]interface{}{}
  1245. TiDb.SelectByBath(100, func(l *[]map[string]interface{}) bool {
  1246. for _, v := range *l {
  1247. startTime = gconv.String(v["createtime"])
  1248. data := CustomerChangeHandle(v)
  1249. oldPerson := gconv.String(data["oldPerson"])
  1250. newPerson := gconv.String(data["newPerson"])
  1251. positionId := gconv.Int64(data["positionId"])
  1252. operatorId := gconv.Int64(data["operatorId"])
  1253. if oldPerson == "/" {
  1254. data["oldPerson"] = "-"
  1255. }
  1256. if positionId > 0 {
  1257. data["positionName"] = personMap[positionId]
  1258. }
  1259. if operatorId > 0 {
  1260. //手动分配 客成收邮件
  1261. data["operatorName"] = personMap[operatorId]
  1262. if newPerson != "" && newPerson != "/" {
  1263. customMap2[newPerson] = append(customMap2[newPerson], data)
  1264. }
  1265. if oldPerson != "" && oldPerson != "/" {
  1266. customMap1[oldPerson] = append(customMap1[oldPerson], data)
  1267. }
  1268. } else {
  1269. //自动分配 销售收邮件
  1270. if (oldPerson == "" || oldPerson == "/") && newPerson != "" && newPerson != "/" && positionId > 0 {
  1271. //之前没有可成人员
  1272. saleNobodyCustomMapMap[positionId] = append(saleNobodyCustomMapMap[positionId], data)
  1273. } else if newPerson != "" && newPerson != "/" && oldPerson != "" && oldPerson != "/" && positionId > 0 {
  1274. //之前有客成
  1275. saleMap[positionId] = append(saleMap[positionId], data)
  1276. }
  1277. }
  1278. }
  1279. return true
  1280. }, `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)
  1281. //}, `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)
  1282. if len(customMap1) > 0 {
  1283. ChangeSendKc(customMap1, 1)
  1284. }
  1285. if len(customMap2) > 0 {
  1286. ChangeSendKc(customMap2, 2)
  1287. }
  1288. if len(saleMap) > 0 {
  1289. ChangeSendSale(saleMap, 2)
  1290. }
  1291. if len(saleNobodyCustomMapMap) > 0 {
  1292. ChangeSendSale(saleNobodyCustomMapMap, 1)
  1293. }
  1294. log.Println("11111", startTime)
  1295. cfg.LastKcChangeTime = startTime
  1296. common.WriteSysConfig(&cfg)
  1297. }
  1298. // 客户成功经理变更邮件提醒客成人员
  1299. func ChangeSendKc(data map[string][]map[string]interface{}, personType int64) {
  1300. for name, v := range data {
  1301. to, _ := GetMail(name)
  1302. //正文拼接
  1303. 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>
  1304. <table><thead><tr><th>序号</th><th>公司名称</th><th>联系人</th><th>姓名</th><th>变更前客户经理</th><th>变更后客户经理</th><th>操作人</th></tr></thead><tbody>`
  1305. for i, v := range v {
  1306. 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"]))
  1307. }
  1308. endStr := `</tbody></table><p></body></html>`
  1309. startStr += endStr
  1310. if to != "" {
  1311. status := mail.GSendMail_q("剑鱼标讯", to, "", "", gconv.String(common.If(personType == 2, "您有新的客户,请及时跟进处理", "您的客户已转至其他客户成功经理负责")), startStr, "", "", &Gmail)
  1312. if status {
  1313. log.Println("客成发邮件 send mail success", startStr, to, "")
  1314. }
  1315. }
  1316. }
  1317. }
  1318. func ChangeSendSale(data map[int64][]map[string]interface{}, personType int64) {
  1319. log.Println("客成人员变更", personType, data)
  1320. if personType == 1 {
  1321. //客户成功经理从空变成有人
  1322. for _, v := range data {
  1323. for _, v1 := range v {
  1324. positionId := gconv.Int64(v1["positionId"])
  1325. to := SaleMail(positionId)
  1326. _, img := GetMail(gconv.String(v1["newPerson"]))
  1327. //抄送人查询
  1328. 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>
  1329. <p>销售人员"%s"成交的客户已成功移交至客成,线索名称:%s,姓名:%s,手机号:%s,负责客户成功经理:%s</p>
  1330. <p>请引导客户添加客户成功经理企业微信:</p><div class='clear'>%s</div>`
  1331. 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), ""))
  1332. if to != "" {
  1333. status := mail.GSendMail_q("剑鱼标讯", to, "", "", "成交客户已成功移交客成", endStr, "", "", &Gmail)
  1334. if status {
  1335. log.Println("客成发邮件 send mail success", endStr, to, "")
  1336. }
  1337. }
  1338. }
  1339. }
  1340. return
  1341. }
  1342. //客户成功经理从A变成了B
  1343. for positionId, v := range data {
  1344. to := SaleMail(positionId)
  1345. //正文拼接
  1346. 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>客户明细如下:
  1347. </p><table><thead><tr><th>序号</th><th>线索名称</th><th>联系人</th><th>姓名</th><th>变更前客户经理</th><th>变更后客户经理</th><th>销售人员</th></tr></thead><tbody>`
  1348. for i, v := range v {
  1349. 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>`,
  1350. 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"]))
  1351. }
  1352. endStr := `</tbody></table><p></body></html>`
  1353. startStr += endStr
  1354. if to != "" {
  1355. status := mail.GSendMail_q("剑鱼标讯", to, "", "", "成交客户负责客户成功经理变更", startStr, "", "", &Gmail)
  1356. if status {
  1357. log.Println("客成发邮件 send mail success", startStr, to, "")
  1358. }
  1359. }
  1360. }
  1361. }
  1362. // 客成人员变更基本信息获取
  1363. func CustomerChangeHandle(data map[string]interface{}) map[string]interface{} {
  1364. clueId := gconv.Int64(data["clue_id"])
  1365. oldPerson := gconv.String(data["old_value"])
  1366. newPerson := gconv.String(data["new_value"])
  1367. operatorId := gconv.Int64(data["operator_id"])
  1368. companyName := ""
  1369. phone := ""
  1370. userName := ""
  1371. clueName := ""
  1372. clueData := TiDb.FindOne("dwd_f_crm_clue_info", map[string]interface{}{
  1373. "id": clueId,
  1374. }, "", "")
  1375. if clueData == nil || len(*clueData) == 0 {
  1376. return nil
  1377. }
  1378. uid := gconv.String((*clueData)["uid"])
  1379. phone = gconv.String((*clueData)["phone"])
  1380. userName = gconv.String((*clueData)["name"])
  1381. //positionId := gconv.Int64((*clueData)["position_id"])
  1382. positionId, _, _ := FindPositionIdClueId(uid)
  1383. clueName = gconv.String((*clueData)["cluename"])
  1384. customData := TiDb.FindOne("dwd_f_csm_customer_info", map[string]interface{}{
  1385. "clue_id": clueId,
  1386. }, "", "")
  1387. if customData != nil || len(*customData) != 0 {
  1388. companyName = gconv.String((*customData)["company_name"])
  1389. }
  1390. return map[string]interface{}{
  1391. "oldPerson": oldPerson,
  1392. "newPerson": newPerson,
  1393. "operatorId": operatorId,
  1394. "phone": phone,
  1395. "userName": userName,
  1396. "positionId": positionId,
  1397. "clueName": clueName,
  1398. "companyName": companyName,
  1399. }
  1400. }
  1401. // 查找订单实际业绩归属
  1402. func FindPositionIdClueId(uid string) (int64, string, string) {
  1403. personArr := getUserIdToUid(uid)
  1404. productArr, _ := KcProduct()
  1405. querySql := fmt.Sprintf(` SELECT
  1406. d.saler_name as salesperson ,c.position_id,f.dept_name,c.seat_number,b.product_type as productType,b.filter
  1407. FROM
  1408. jianyu.dataexport_order a INNER JOIN jianyu.jy_order_detail b on
  1409. a.order_code=b.order_code and a.user_id in (%s)
  1410. AND (
  1411. b.final_price > 0
  1412. OR (
  1413. b.final_price = 0
  1414. AND ( a.zero_type= "分期付款权益补充" OR a.zero_type= "原订单不支持开通多项权益" OR a.zero_type= "权益码兑换" )))
  1415. AND a.order_status = 1 and a.user_phone not like "%s"
  1416. AND ( a.refund_status != 1 OR a.refund_status IS NULL )
  1417. AND b.service_starttime < "2099-01-01"
  1418. AND b.product_type IN (%s )
  1419. AND ( b.service_type != 4 or b.service_type is NULL OR ( b.service_type = 4 AND DATEDIFF( b.service_starttime, b.service_endtime )> 90 ) )
  1420. inner JOIN jianyu.order_sale_record d on b.order_code=d.ordercode and d.state=1
  1421. INNER JOIN jianyu.entniche_user e on d.ent_userId = e.id
  1422. INNER JOIN dwd_f_crm_personnel_management c on c.ent_id =? and e.name=c.name
  1423. inner join dwd_d_crm_department_level_succbi f on c.position_id=f.position_id
  1424. ORDER BY
  1425. b.service_endtime desc ,b.final_price DESC `, strings.Join(personArr, ","), "9%", strings.Join(productArr, ","))
  1426. clueData := TiDb.SelectBySql(querySql, db.EntId)
  1427. if clueData == nil || len(*clueData) == 0 {
  1428. return 0, "", ""
  1429. }
  1430. for _, m := range *clueData {
  1431. productType := gconv.String(m["productType"])
  1432. if productType == "大会员" {
  1433. level := gconv.Int(m["service_type"])
  1434. if level == 4 {
  1435. continue
  1436. }
  1437. }
  1438. deptName := gconv.String(m["dept_name"])
  1439. if strings.Contains(deptName, "一部") || strings.Contains(deptName, "三部") {
  1440. return gconv.Int64(m["position_id"]), gconv.String(m["salesperson"]), gconv.String(m["seat_number"])
  1441. }
  1442. }
  1443. return 0, "", ""
  1444. }
  1445. func refundAutoHistory() {
  1446. data := TiDb.Find("dwd_f_crm_clue_autodraw_record", nil, "", "", -1, -1)
  1447. if data != nil {
  1448. for _, v := range *data {
  1449. seatNumber := gconv.String(v["seatNumber"])
  1450. adata := TiDb.Find("dwd_f_crm_personnel_management", map[string]interface{}{"seat_number": seatNumber}, "", "", -1, -1)
  1451. if adata != nil {
  1452. for _, vv := range *adata {
  1453. if common.IntAll(vv["resign"]) == 0 {
  1454. position_id := common.Int64All(vv["position_id"])
  1455. TiDb.Update("dwd_f_crm_clue_autodraw_record", map[string]interface{}{"seatNumber": seatNumber}, map[string]interface{}{"position_id": position_id})
  1456. break
  1457. }
  1458. }
  1459. }
  1460. }
  1461. }
  1462. }
  1463. func IsFreeze(source string, pay_money int, positionId, trailstatus string) bool {
  1464. log.Println(source, pay_money == 0, FindUpperLimit(gconv.String(
  1465. positionId), "", false), trailstatus)
  1466. if source == "0104" && pay_money == 0 && FindUpperLimit(gconv.String(
  1467. positionId), "", false) {
  1468. return true
  1469. } else if source == "0104" && pay_money > 0 && trailstatus == "08" && FindUpperLimit(gconv.String(
  1470. positionId), "", false) {
  1471. return true
  1472. }
  1473. return false
  1474. }
  1475. // 业绩归属查询
  1476. func FindSaleRecord(orderCode string) (dept string, positionId int64, position string) {
  1477. recordList := Mysql.SelectBySql(`
  1478. SELECT DISTINCT
  1479. a.saler_dept,
  1480. a.saler_name,
  1481. b.phone
  1482. FROM
  1483. order_sale_record a
  1484. INNER JOIN entniche_user b
  1485. on
  1486. a.ordercode = ? and a.ent_userId = b.id
  1487. ORDER BY
  1488. a.state,
  1489. a.money desc
  1490. `, orderCode)
  1491. if recordList != nil && len(*recordList) > 0 {
  1492. saler_dept := gconv.String((*recordList)[0]["saler_dept"])
  1493. if strings.Contains(saler_dept, "销售") {
  1494. saler_dept = "销售部"
  1495. } else if strings.Contains(saler_dept, "市场") {
  1496. saler_dept = "市场部"
  1497. } else if strings.Contains(saler_dept, "客户成功") {
  1498. saler_dept = "客户成功组"
  1499. } else {
  1500. saler_dept = ""
  1501. }
  1502. positionid := PhoneToPositionId(gconv.String((*recordList)[0]["phone"]))
  1503. if positionid > 0 {
  1504. return saler_dept, positionid, gconv.String((*recordList)[0]["saler_name"])
  1505. }
  1506. }
  1507. return "", int64(0), ""
  1508. }
  1509. func PhoneToPositionId(phone string) int64 {
  1510. positionId := int64(0)
  1511. data := Base.SelectBySql(`SELECT
  1512. b.id
  1513. FROM
  1514. base_user a
  1515. INNER JOIN base_position b ON a.phone = ?
  1516. AND a.id = b.user_id
  1517. AND b.ent_id = 25917`, phone)
  1518. if data != nil && len(*data) > 0 {
  1519. positionId = gconv.Int64((*data)[0]["id"])
  1520. }
  1521. return positionId
  1522. }
  1523. func kcClue(userId, uId, seatNumber, cluename, top_cluetype, sub_cluetype,
  1524. name, phone, position, sourceCode, industry, follow_project_area,
  1525. role, item, subname, topname, remark, demand, department, departments, saleName, source string, positionId int64, isGroup, isCommerce int, keywords []string) bool {
  1526. clueId, uodateId1, uodateId2, uodateId3, uodateId4, uodateId5 := int64(0), int64(0), int64(0), int64(0), int64(0), int64(0)
  1527. nowTime := time.Now().Format("2006-01-02 15:04:05")
  1528. nowTimes := time.Unix(time.Now().Unix()+3600*12, 0).Format("2006-01-02 15:04:05")
  1529. if TiDb.ExecTx("保存线索", func(tx *sql.Tx) bool {
  1530. clueId = TiDb.InsertByTx(tx, "dwd_f_crm_clue_info", map[string]interface{}{
  1531. "userid": userId,
  1532. "uid": uId,
  1533. "seatNumber": seatNumber,
  1534. "position_id": positionId,
  1535. "is_assign": common.If(positionId > 0, 1, 0),
  1536. "comeintime": nowTime,
  1537. "createtime": nowTime,
  1538. "updatetime": nowTime,
  1539. "cluename": cluename,
  1540. "top_cluetype": top_cluetype,
  1541. "sub_cluetype": sub_cluetype,
  1542. "trailstatus": "01",
  1543. "name": name,
  1544. "phone": phone,
  1545. "position": position,
  1546. "department": common.If(sourceCode == "app_xzcyh", departments, department),
  1547. "industry": industry,
  1548. "follow_project_area": follow_project_area,
  1549. "role": role,
  1550. "comeinsource_private": 2,
  1551. "is_task": 1,
  1552. "task_time": nowTime,
  1553. "tasktime": common.If(item == "users", nowTimes, nowTime),
  1554. "taskstatus": 0,
  1555. "tasksource": "线索自动分配" + "-" + topname + "-" + subname,
  1556. "business_scope": common.If(sourceCode == "app_xzcyh", keywords, nil),
  1557. "company_nature": isGroup,
  1558. "company_verification": isCommerce,
  1559. "remark": remark,
  1560. "customer_demand": demand,
  1561. "FREEZE_TIME": nowTime,
  1562. "label": 1,
  1563. "labelChangeTime": time.Now().Format("2006-01-02"),
  1564. })
  1565. uodateId1 = TiDb.InsertByTx(tx, "dwd_f_crm_clue_change_record", map[string]interface{}{
  1566. "clue_id": clueId,
  1567. "position_id": positionId,
  1568. "change_type": "创建线索",
  1569. "new_value": "系统自动创建",
  1570. "createtime": nowTime,
  1571. "BCPCID": common.GetRandom(32),
  1572. "operator_id": -1,
  1573. })
  1574. uodateId2 = TiDb.InsertByTx(tx, "dwd_f_crm_clue_change_record", map[string]interface{}{
  1575. "clue_id": clueId,
  1576. "position_id": positionId,
  1577. "change_field": "position_id",
  1578. "change_type": "所属人变更",
  1579. "old_value": "/",
  1580. "new_value": saleName,
  1581. "createtime": nowTime,
  1582. "BCPCID": common.GetRandom(32),
  1583. "operator_id": -1,
  1584. })
  1585. uodateId3 = TiDb.InsertByTx(tx, "dwd_f_crm_clue_change_record", map[string]interface{}{
  1586. "clue_id": clueId,
  1587. "position_id": positionId,
  1588. "change_field": "trailstatus",
  1589. "change_type": "基本信息变更",
  1590. "old_value": "商机线索",
  1591. "new_value": "新增",
  1592. "createtime": nowTime,
  1593. "BCPCID": common.GetRandom(32),
  1594. "operator_id": -1,
  1595. })
  1596. uodateId5 = TiDb.InsertByTx(tx, "dwd_f_crm_clue_change_record", map[string]interface{}{
  1597. "clue_id": clueId,
  1598. "position_id": positionId,
  1599. "change_field": "top_cluetype",
  1600. "change_type": "基本信息变更",
  1601. "old_value": "/",
  1602. "new_value": topname,
  1603. "createtime": nowTime,
  1604. "BCPCID": common.GetRandom(32),
  1605. "operator_id": -1,
  1606. })
  1607. uodateId5 = TiDb.InsertByTx(tx, "dwd_f_crm_clue_change_record", map[string]interface{}{
  1608. "clue_id": clueId,
  1609. "position_id": positionId,
  1610. "change_field": "sub_cluetype", //222
  1611. "change_type": "基本信息变更",
  1612. "old_value": "/",
  1613. "new_value": subname,
  1614. "createtime": nowTime,
  1615. "BCPCID": common.GetRandom(32),
  1616. "operator_id": -1,
  1617. })
  1618. return clueId > -1 && uodateId1 > -1 && uodateId2 > -1 && uodateId3 > -1 && uodateId4 > -1 && uodateId5 > -1
  1619. }) {
  1620. log.Println("线索分配成功")
  1621. if TiDb.Count("dwd_f_userbase_contacts", map[string]interface{}{"phone": phone}) == 0 {
  1622. TiDb.Insert("dwd_f_userbase_contacts", map[string]interface{}{
  1623. "status": 1,
  1624. "is_delete": 1,
  1625. "createtime": nowTime,
  1626. "updatetime": nowTime,
  1627. "phone": phone,
  1628. "baseinfo_id": uId,
  1629. "SOURCE": source,
  1630. })
  1631. }
  1632. return true
  1633. }
  1634. return false
  1635. }
  1636. type OrderInfo struct {
  1637. Id int64
  1638. UserId string
  1639. CompanyName string
  1640. ProductType string
  1641. OrderCode string
  1642. PayMoney float64
  1643. ReturnMoney float64
  1644. UserPhone string
  1645. StartEnd string
  1646. DisKcName string
  1647. UserName string
  1648. SeriveList []string
  1649. SaleName string
  1650. }
  1651. // 客成发送邮箱
  1652. func KcSend(orderCode, personName string) {
  1653. log.Println("客成发邮件", orderCode)
  1654. orderInfo := KcOrderFormat(orderCode)
  1655. if orderInfo != nil {
  1656. tableAppend := ""
  1657. if len(orderInfo.SeriveList) > 0 {
  1658. tableAppend = fmt.Sprintf(db.KeCheng.Mail.ServiceList, strings.Join(orderInfo.SeriveList, ","))
  1659. }
  1660. if orderInfo.ReturnMoney > 0 {
  1661. tableAppend += fmt.Sprintf(db.KeCheng.Mail.ReturnMoney, orderInfo.ReturnMoney)
  1662. }
  1663. table := ""
  1664. orderInfo.DisKcName = personName
  1665. 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)
  1666. 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`)
  1667. 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)
  1668. adminMailStr := ""
  1669. if adminData != nil && len(*adminData) > 0 {
  1670. adminMailStr = gconv.String((*adminData)[0]["mail"])
  1671. }
  1672. //发送邮件
  1673. if personName == "" {
  1674. if adminData != nil && len(*adminData) > 0 {
  1675. //发送给管理员
  1676. if adminMailStr != "" {
  1677. gmail := &mail.GmailAuth{
  1678. SmtpHost: db.Mail.SmtpHost,
  1679. SmtpPort: db.Mail.SmtpPort,
  1680. User: db.Mail.User,
  1681. Pwd: db.Mail.Pwd,
  1682. }
  1683. status := mail.GSendMail_q("剑鱼标讯", adminMailStr, "", "", db.KeCheng.Title, fmt.Sprintf(db.KeCheng.Mail.Content, table), "", "", gmail)
  1684. if status {
  1685. log.Println("客成发邮件 send mail success", table, adminMailStr)
  1686. }
  1687. }
  1688. }
  1689. return
  1690. }
  1691. //当事人 管理员发送
  1692. if deptData != nil && len(*deptData) > 0 {
  1693. mailStr := gconv.String((*deptData)[0]["mail"])
  1694. if mailStr != "" || adminMailStr != "" {
  1695. if mailStr == adminMailStr {
  1696. adminMailStr = ""
  1697. }
  1698. gmail := &mail.GmailAuth{
  1699. SmtpHost: db.Mail.SmtpHost,
  1700. SmtpPort: db.Mail.SmtpPort,
  1701. User: db.Mail.User,
  1702. Pwd: db.Mail.Pwd,
  1703. }
  1704. status := true
  1705. if mailStr == "" {
  1706. status = mail.GSendMail_q("剑鱼标讯", adminMailStr, "", "", db.KeCheng.Title, fmt.Sprintf(db.KeCheng.Mail.Content, table), "", "", gmail)
  1707. } else {
  1708. status = mail.GSendMail_q("剑鱼标讯", mailStr, adminMailStr, "", db.KeCheng.Title, fmt.Sprintf(db.KeCheng.Mail.Content, table), "", "", gmail)
  1709. }
  1710. if status {
  1711. log.Println("客成发邮件 send mail success", table, mailStr, adminMailStr)
  1712. }
  1713. }
  1714. }
  1715. }
  1716. }
  1717. func ExitKcSend(personName string, infoList []map[string]interface{}) {
  1718. //退出客成 即将退出客成信息
  1719. 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)
  1720. 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`)
  1721. if personName == "" {
  1722. //没有客成人员
  1723. adminMailStr := ""
  1724. if adminData != nil && len(*adminData) > 0 {
  1725. adminMailStr = gconv.String((*adminData)[0]["mail"])
  1726. }
  1727. if adminMailStr != "" {
  1728. gmail := &mail.GmailAuth{
  1729. SmtpHost: db.Mail.SmtpHost,
  1730. SmtpPort: db.Mail.SmtpPort,
  1731. User: db.Mail.User,
  1732. Pwd: db.Mail.Pwd,
  1733. }
  1734. //正文拼接
  1735. 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>`
  1736. for i, v := range infoList {
  1737. 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"]))
  1738. }
  1739. endStr := `</tbody></table><p></body></html>`
  1740. startStr += endStr
  1741. status := mail.GSendMail_q("剑鱼标讯", adminMailStr, "", "", "客户退出客成系统通知", startStr, "", "", gmail)
  1742. if status {
  1743. log.Println("客成发邮件 send mail success", startStr, adminMailStr)
  1744. }
  1745. }
  1746. return
  1747. }
  1748. if deptData != nil && len(*deptData) > 0 {
  1749. mailStr := gconv.String((*deptData)[0]["mail"])
  1750. adminMailStr := ""
  1751. if adminData != nil && len(*adminData) > 0 {
  1752. adminMailStr = gconv.String((*adminData)[0]["mail"])
  1753. }
  1754. if mailStr != "" || adminMailStr != "" {
  1755. if mailStr == adminMailStr {
  1756. adminMailStr = ""
  1757. }
  1758. gmail := &mail.GmailAuth{
  1759. SmtpHost: db.Mail.SmtpHost,
  1760. SmtpPort: db.Mail.SmtpPort,
  1761. User: db.Mail.User,
  1762. Pwd: db.Mail.Pwd,
  1763. }
  1764. //正文拼接
  1765. 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>`
  1766. for i, v := range infoList {
  1767. 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"]))
  1768. }
  1769. endStr := `</tbody></table><p></body></html>`
  1770. startStr += endStr
  1771. status := true
  1772. if mailStr == "" {
  1773. status = mail.GSendMail_q("剑鱼标讯", adminMailStr, "", "", "客户退出客成系统通知", startStr, "", "", gmail)
  1774. } else {
  1775. status = mail.GSendMail_q("剑鱼标讯", mailStr, adminMailStr, "", "客户退出客成系统通知", startStr, "", "", gmail)
  1776. }
  1777. if status {
  1778. log.Println("客成发邮件 send mail success", startStr, mailStr)
  1779. }
  1780. }
  1781. }
  1782. }
  1783. // 客成邮件 订单信息初始化
  1784. func KcOrderFormat(orderCode string) *OrderInfo {
  1785. productArr, _ := KcProduct()
  1786. bigmemberService := map[int64]string{}
  1787. Mysql.SelectByBath(1, func(l *[]map[string]interface{}) bool {
  1788. bigmemberService[common.Int64All((*l)[0]["id"])] = gconv.String((*l)[0]["s_name"])
  1789. return true
  1790. }, `select id,s_name from jianyu.bigmember_service`)
  1791. orderData := Mysql.SelectBySql(fmt.Sprintf(`
  1792. SELECT
  1793. d.*,
  1794. SUM( c.return_money ) AS return_money
  1795. FROM
  1796. (
  1797. SELECT
  1798. a.order_code,
  1799. a.pay_money,
  1800. a.user_phone,
  1801. b.service_starttime,
  1802. b.service_endtime,
  1803. b.product_type,
  1804. a.filter,
  1805. a.user_id,
  1806. a.ent_id,
  1807. a.company_name,
  1808. a.create_person,
  1809. b.filter AS productFilter,
  1810. TIMESTAMPDIFF( DAY, b.service_starttime, b.service_endtime ) AS difference
  1811. FROM
  1812. jianyu.dataexport_order a
  1813. INNER JOIN jy_order_detail b ON a.order_code = "%s"
  1814. AND a.order_code = b.order_code
  1815. AND a.order_status = 1
  1816. AND b.product_type IN ( %s )
  1817. ORDER BY
  1818. difference DESC LIMIT 1
  1819. ) d
  1820. LEFT JOIN return_money_record c ON d.order_code = c.order_code
  1821. `, orderCode, strings.Join(productArr, ",")))
  1822. data := &OrderInfo{}
  1823. if orderData != nil && len(*orderData) > 0 {
  1824. orderData := (*orderData)[0]
  1825. id := common.Int64All(orderData["id"])
  1826. user_phone := gconv.String(orderData["user_phone"])
  1827. user_id := gconv.String(orderData["user_id"])
  1828. product_type := gconv.String(orderData["product_type"])
  1829. serviceList := []string{}
  1830. if product_type == "大会员" {
  1831. product_type_name, _, level := GetOrderProduct(product_type, gconv.String(orderData["productFilter"]))
  1832. product_type = product_type_name
  1833. if level == 0 {
  1834. for _, serversId := range strings.Split(gconv.String(gconv.Map(orderData["serversId"])), ",") {
  1835. if serviceName := bigmemberService[common.Int64All(serversId)]; serviceName != "" {
  1836. serviceList = append(serviceList, serviceName)
  1837. }
  1838. }
  1839. }
  1840. }
  1841. //联系人姓名
  1842. sqlStr := `SELECT
  1843. a.phone,
  1844. b.NAME AS bname
  1845. FROM
  1846. dwd_f_userbase_contacts a
  1847. INNER JOIN dwd_f_crm_clue_info b ON ( a.phone = ? AND a.baseinfo_id = b.uid )
  1848. LEFT JOIN dwd_f_csm_customer_info c ON ( b.id = c.clue_id)`
  1849. userName := ""
  1850. if user_phone != "" {
  1851. userData := TiDb.SelectBySql(sqlStr, user_phone)
  1852. if userData != nil && len(*userData) > 0 {
  1853. userName = gconv.String((*userData)[0]["bname"])
  1854. }
  1855. }
  1856. data = &OrderInfo{
  1857. Id: id,
  1858. CompanyName: gconv.String(orderData["company_name"]),
  1859. UserId: user_id,
  1860. ProductType: product_type,
  1861. OrderCode: orderCode,
  1862. PayMoney: common.Float64All(orderData["pay_money"]) / 100,
  1863. ReturnMoney: common.Float64All(orderData["return_money"]) / 100,
  1864. UserPhone: user_phone,
  1865. StartEnd: fmt.Sprintf("%s--%s", strings.Split(gconv.String(orderData["service_starttime"]), " ")[0], strings.Split(gconv.String(orderData["service_endtime"]), " ")[0]),
  1866. SeriveList: serviceList,
  1867. SaleName: gconv.String(orderData["create_person"]),
  1868. UserName: userName,
  1869. }
  1870. }
  1871. return data
  1872. }
  1873. func SaleMail(positionId int64) string {
  1874. person, admin, seniorAdmin := FindDeptAdmin(positionId)
  1875. personMail := ""
  1876. adminMail := ""
  1877. seniorAdminMail := ""
  1878. if person != nil {
  1879. personMail, _ = GetMail(gconv.String(person["name"]))
  1880. }
  1881. if admin != nil {
  1882. adminMail, _ = GetMail(gconv.String(admin["name"]))
  1883. }
  1884. if seniorAdmin != nil {
  1885. seniorAdminMail, _ = GetMail(gconv.String(seniorAdmin["name"]))
  1886. }
  1887. to, cc := "", ""
  1888. if personMail != "" {
  1889. to = personMail
  1890. if adminMail != "" && seniorAdminMail != "" {
  1891. if to != adminMail {
  1892. if to != seniorAdminMail {
  1893. cc = fmt.Sprintf("%s,%s", adminMail, seniorAdminMail)
  1894. }
  1895. } else {
  1896. if to != seniorAdminMail {
  1897. cc = seniorAdminMail
  1898. }
  1899. }
  1900. } else if seniorAdminMail != "" && to != seniorAdminMail {
  1901. cc = seniorAdminMail
  1902. }
  1903. } else {
  1904. if adminMail != "" {
  1905. to = adminMail
  1906. if seniorAdminMail != "" && to != seniorAdminMail {
  1907. cc = seniorAdminMail
  1908. }
  1909. } else {
  1910. to = seniorAdminMail
  1911. }
  1912. }
  1913. if to != "" && cc != "" {
  1914. to = fmt.Sprintf("%s|%s", to, cc)
  1915. }
  1916. return to
  1917. }
  1918. func FindPersonOne(positionId int64) map[string]interface{} {
  1919. personData := TiDb.SelectBySql(`SELECT
  1920. b.name,
  1921. b.position_id,
  1922. b.seat_number,
  1923. b.role_id,
  1924. a.dept_name
  1925. FROM
  1926. dwd_d_crm_department_level_succbi a
  1927. INNER JOIN dwd_f_crm_personnel_management b ON a.position_id = ?
  1928. AND a.position_id = b.position_id`, positionId)
  1929. if personData == nil || len(*personData) == 0 {
  1930. return nil
  1931. }
  1932. return (*personData)[0]
  1933. }
  1934. // 进客成商品查询
  1935. func KcProduct() ([]string, map[string]bool) {
  1936. var strArr []string
  1937. strMap := map[string]bool{}
  1938. productData := Mysql.SelectBySql(`SELECT id ,
  1939. CONCAT( '"', class_name,'"' ) as product
  1940. FROM
  1941. jy_product_class
  1942. WHERE
  1943. s_service = 1`)
  1944. if productData == nil && len(*productData) == 0 {
  1945. return strArr, strMap
  1946. }
  1947. for _, m := range *productData {
  1948. strMap[gconv.String(m["product"])] = true
  1949. strArr = append(strArr, gconv.String(m["product"]))
  1950. }
  1951. return strArr, strMap
  1952. }
  1953. func GetOrderProduct(productType string, file string) (string, int64, int64) {
  1954. fileJson := gconv.Map(file)
  1955. if fileJson == nil || len(fileJson) == 0 {
  1956. return "", 0, 0
  1957. }
  1958. productName := ""
  1959. level := int64(0)
  1960. switch productType {
  1961. case "大会员":
  1962. level = gconv.Int64(fileJson["comboId"])
  1963. if level == 0 {
  1964. level = gconv.Int64(fileJson["level"])
  1965. }
  1966. switch level {
  1967. case 0:
  1968. productName = "大会员自定义"
  1969. case 30190:
  1970. productName = "大会员商机版2.0(单省版)"
  1971. case 6:
  1972. productName = "大会员商机版2.0"
  1973. case 7:
  1974. productName = "大会员专家版2.0"
  1975. }
  1976. default:
  1977. productName = productType
  1978. }
  1979. productData := TiDb.FindOne("dwd_d_csm_product_access_code", map[string]interface{}{
  1980. "name": productName,
  1981. }, "", "")
  1982. if productData == nil || len(*productData) == 0 {
  1983. return productName, 0, level
  1984. }
  1985. return productName, gconv.Int64((*productData)["code"]), level
  1986. }
  1987. func GetTimeDifference(timeStr1, timeStr2 string) int {
  1988. // 解析时间字符串
  1989. t1, err1 := time.Parse(time.DateTime, timeStr1)
  1990. t2, err2 := time.Parse(time.DateTime, timeStr2)
  1991. if err1 != nil || err2 != nil {
  1992. fmt.Println("时间格式错误:", err1, err2)
  1993. return 0
  1994. }
  1995. // 计算时间差
  1996. daysDiff := gconv.Int(t2.Sub(t1).Hours() / 24)
  1997. fmt.Printf("两个时间相差 %.0f 天\n", daysDiff)
  1998. return daysDiff
  1999. }
  2000. func getOrderData(sql string) (map[string]map[string]interface{}, string) {
  2001. data := Mysql.SelectBySql(sql)
  2002. orderMap := map[string]map[string]interface{}{}
  2003. lastEndTime := ""
  2004. for _, v := range *data {
  2005. orderCode := gconv.String(v["order_code"])
  2006. product_type := gconv.String(v["productType"])
  2007. vip_starttime := gconv.String(v["service_starttime"])
  2008. vip_endtime := gconv.String(v["service_endtime"])
  2009. //判断一下服务周期
  2010. difference := GetTimeDifference(vip_starttime, vip_endtime)
  2011. _, productInt64, _ := GetOrderProduct(product_type, gconv.String(v["productFilter"]))
  2012. if productInt64 == 0 {
  2013. continue
  2014. }
  2015. if _, exists := orderMap[orderCode]; exists {
  2016. //判断服务周期
  2017. data := orderMap[orderCode]
  2018. //商品类型获取
  2019. oldDifference := gconv.Int(data["difference"])
  2020. if oldDifference >= difference {
  2021. //需要更换
  2022. lastEndTime = vip_endtime
  2023. v["difference"] = difference
  2024. v["product"] = productInt64
  2025. v["service_endtime"] = vip_endtime
  2026. v["service_starttime"] = vip_starttime
  2027. v["product_type"] = product_type
  2028. orderMap[orderCode] = v
  2029. }
  2030. } else {
  2031. lastEndTime = vip_endtime
  2032. v["difference"] = difference
  2033. v["product"] = productInt64
  2034. v["product_type"] = product_type
  2035. orderMap[orderCode] = v
  2036. }
  2037. }
  2038. return orderMap, lastEndTime
  2039. }