kc.go 81 KB

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