kc.go 68 KB

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