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