12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075 |
- package main
- import (
- "app.yhyue.com/moapp/jybase/mail"
- "app.yhyue.com/moapp/jybase/redis"
- "database/sql"
- "fmt"
- "log"
- "strings"
- "time"
- "github.com/gogf/gf/v2/util/gconv"
- "app.yhyue.com/moapp/jybase/common"
- "app.yhyue.com/moapp/jybase/date"
- "app.yhyue.com/moapp/jybase/mongodb"
- )
- func kcSync() {
- log.Println("客户成功系统移交定时任务开始")
- //商品查询
- productArr, _ := KcProduct()
- if len(productArr) == 0 {
- log.Println("查询不到进客成商品类型")
- return
- }
- sql := `SELECT
- 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
- FROM
- dataexport_order a
- INNER JOIN jy_order_detail b ON a.order_code = b.order_code
- and b.product_type in (%s)
- AND (
- a.pay_money > 0
- OR (
- a.pay_money = 0
- AND ( a.zero_type = "分期付款权益补充" OR a.zero_type = "原订单不支持开通多项权益" OR a.zero_type = "权益码兑换" )))
- AND a.user_phone NOT LIKE "%s"
- and a.user_id !=""
- AND a.order_status = 1
- AND ( a.refund_status != 1 OR a.refund_status IS NULL )
- AND b.service_starttime < "2099-01-01" AND b.service_endtime > now()
- AND b.update_time > "%s"
- ORDER BY
- a.order_code ASC,
- difference desc ,
- b.final_price DESC `
- sql = fmt.Sprintf(sql, strings.Join(productArr, ","), "9%", cfg.LastkcTime)
- //sql = fmt.Sprintf(sql, strings.Join(productArr, ","), "9%", "2025-01-02", "103557341197")
- data := Mysql.SelectBySql(sql)
- fmt.Println("客成查询到的数量:", len(*data))
- customList := gconv.Strings(redis.Get("newother", "customList"))
- if data != nil && *data != nil && len(*data) > 0 {
- orderMap := map[string]map[string]interface{}{}
- for _, v := range *data {
- orderCode := gconv.String(v["order_code"])
- productType := gconv.String(v["product_type"])
- vipStarttime := gconv.String(v["service_starttime"])
- vipEndtime := gconv.String(v["service_endtime"])
- service_type := gconv.Int64(v["service_type"])
- difference := gconv.Int(v["difference"])
- if (service_type != 4) || (service_type == 4 && difference > 95) {
- isExit := false
- for _, v := range customList {
- if v == orderCode {
- isExit = true
- continue
- }
- }
- if isExit {
- continue
- }
- //判断一下服务周期
- _, productInt64, _ := GetOrderProduct(productType, gconv.String(v["productFilter"]))
- if productInt64 == 0 {
- continue
- }
- if _, exists := orderMap[orderCode]; exists {
- //判断服务周期
- data := orderMap[orderCode]
- //商品类型获取
- oldDifference := gconv.Int(data["difference"])
- if oldDifference < difference {
- //需要更换
- v["difference"] = difference
- v["product"] = productInt64
- v["service_endtime"] = vipEndtime
- v["service_starttime"] = vipStarttime
- orderMap[orderCode] = v
- }
- } else {
- v["difference"] = difference
- v["product"] = productInt64
- orderMap[orderCode] = v
- }
- }
- }
- for _, v := range *data {
- orderCode := gconv.String(v["order_code"])
- if _, exists := orderMap[orderCode]; exists {
- status := kcJob(v)
- log.Println("订单进客成打印", orderCode, status)
- if status == 0 {
- break
- }
- cfg.LastkcTime = gconv.String(v["update_time"])
- customList = append(customList, orderCode)
- delete(orderMap, orderCode)
- }
- }
- }
- redis.Put("newother", "customList", customList, 0)
- common.WriteSysConfig(&cfg)
- log.Println("客户成功系统移交定时任务结束")
- }
- func kcJob(data map[string]interface{}) int {
- nowTime := time.Now().Format(date.Date_Full_Layout)
- uId, entId, clueId, saveMap, status := "", gconv.String(data["ent_id"]), int64(0), map[string]interface{}{}, 1
- userId, cluename, phone := "", "", ""
- phone = gconv.String(data["user_phone"])
- uId, userId = GetUidToUserId(gconv.String(data["user_id"]), "")
- log.Println("用户信息获取", data["user_id"], uId, userId)
- if uId == "" {
- log.Println("移交客成缺少基本信息,缺少用户信息", uId)
- return 0
- }
- buy_subject := common.IntAll(data["buy_subject"])
- if buy_subject == 1 || buy_subject == 0 {
- entId = gconv.String(data["user_id"])
- }
- clueData := TiDb.FindOne("dwd_f_crm_clue_info", map[string]interface{}{"uid": uId}, "", "")
- orderCode := gconv.String(data["order_code"])
- saleDep, orderPositionId, salesperson := FindSaleRecord(orderCode)
- log.Println(data["order_code"], saleDep, orderPositionId, salesperson)
- if clueData == nil || len(*clueData) == 0 {
- if saleDep == "销售部" || saleDep == "市场部" {
- log.Println("移交客成缺少基本信息", uId)
- return 0
- }
- //原始订单获取
- position_id := int64(0)
- seatNumber := ""
- if saleDep == "客户成功部" {
- //新增线索
- position_id = 0
- } else {
- position_id = orderPositionId
- //其他信息
- seatNumber = "0000"
- }
- cluename = gconv.String(data["company_name"])
- if cluename == "" {
- cluename = phone
- }
- trailstatus := "08"
- isGroup, isCommerce := GetCompanyType(cluename, uId) //判断是否集团公司、工商库
- clueId = TiDb.Insert("dwd_f_crm_clue_info", map[string]interface{}{
- "userid": userId,
- "uid": uId,
- "is_assign": common.If(position_id > 0, 1, 0),
- "createtime": nowTime,
- "updatetime": nowTime,
- "cluename": cluename,
- "seatNumber": seatNumber,
- "position_id": position_id,
- "top_cluetype": "4",
- "sub_cluetype": "154",
- "trailstatus": trailstatus,
- "name": phone,
- "phone": phone,
- "is_task": 0,
- "taskstatus": 0,
- "company_nature": isGroup,
- "company_verification": isCommerce,
- "FREEZE_TIME": nowTime,
- "label": common.If(position_id > 0, 1, nil),
- })
- if clueId > 0 {
- TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
- "clue_id": clueId,
- "position_id": common.If(position_id > 0, position_id, -1),
- "change_type": "创建线索",
- "new_value": "系统自动创建",
- "createtime": nowTime,
- "BCPCID": common.GetRandom(32),
- "operator_id": -1,
- })
- clueData = TiDb.FindOne("dwd_f_crm_clue_info", map[string]interface{}{"uid": uId}, "", "")
- if clueData == nil || len(*clueData) == 0 {
- return 0
- }
- } else {
- return 0
- }
- }
- clueId = common.Int64All((*clueData)["id"])
- starttime := gconv.String(data["service_starttime"])
- endtime := gconv.String(data["service_endtime"])
- //product_type := gconv.String(data["product_type"])
- userName := gconv.String((*clueData)["name"])
- product, company_name := gconv.String(data["product"]), gconv.String(data["company_name"])
- //同一公司名称(以客户详情-组织机构-公司名称)下的线索需分配给同1人
- saveMap = map[string]interface{}{
- "clue_id": clueId,
- "transfertime": nowTime,
- "service_starttime": starttime,
- "service_endtime": endtime,
- "ent_id": entId,
- "is_task": 1,
- "tasktime": nowTime,
- "taskstatus": 0,
- "tasksource": "1",
- "is_admin": 1,
- "product_access": product,
- "buy_subject": buy_subject,
- "relationship_building_way": 1,
- "inventory_way": 1,
- "training_way": 1,
- "is_pre_sales_training": 0,
- "service_stage": 1,
- "company_name": company_name,
- }
- if TiDb.Count("dwd_f_csm_customer_info", map[string]interface{}{"clue_id": clueId}) > 0 {
- csmdata := TiDb.FindOne("dwd_f_csm_customer_info", map[string]interface{}{"clue_id": clueId}, "", "")
- if csmdata != nil && len(*csmdata) > 0 {
- id := gconv.Int64((*csmdata)["id"])
- log.Println(1111111, id, orderCode)
- //'已移交销售,0移交客成 1移交销售',
- is_transfer := gconv.Int64((*csmdata)["is_transfer"])
- customerPositionId, customerName := cAutoDraw(0, orderPositionId, salesperson, saleDep, true, csmdata)
- log.Println("移交客成positionId", customerPositionId, customerName, saleDep, orderPositionId, salesperson, true)
- oldName := gconv.String((*csmdata)["name"])
- updateMap := map[string]interface{}{
- "is_transfer": 0,
- "is_renewal_protection": 0,
- "product_access": product,
- "buy_subject": buy_subject,
- "transfertime": nowTime,
- "service_starttime": starttime,
- "service_endtime": endtime,
- "ent_id": entId,
- "company_name": company_name,
- "name": customerName,
- "position_id": customerPositionId,
- }
- if is_transfer == 1 || customerPositionId != gconv.Int64((*csmdata)["position_id"]) {
- //重新进去
- updateMap["relationship_building_way"] = 1
- updateMap["tasksource"] = "1"
- updateMap["inventory_way"] = 1
- updateMap["training_way"] = 1
- updateMap["is_pre_sales_training"] = 0
- updateMap["service_stage"] = 1
- updateMap["is_task"] = 1
- }
- TiDb.Update("dwd_f_csm_customer_info", map[string]interface{}{"clue_id": clueId}, updateMap)
- TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
- "clue_id": clueId,
- "position_id": customerPositionId,
- "change_type": "成交客户移交",
- "new_value": "移交至客户成功组",
- "createtime": nowTime,
- "BCPCID": common.GetRandom(32),
- "operator_id": -1,
- })
- if customerPositionId > 0 && (is_transfer == 1 || customerPositionId != gconv.Int64((*csmdata)["position_id"])) {
- TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
- "clue_id": clueId,
- "position_id": customerPositionId,
- "change_field": "position_id",
- "change_type": "客户成功经理",
- "old_value": common.If(oldName != customerName, oldName, common.If(oldName == "", "/", oldName)),
- "new_value": customerName,
- "createtime": nowTime,
- "BCPCID": common.GetRandom(32),
- "operator_id": -1,
- })
- TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
- "clue_id": clueId,
- "position_id": customerPositionId,
- "change_type": "加入任务车",
- "new_value": "未建联",
- "createtime": nowTime,
- "BCPCID": common.GetRandom(32),
- "operator_id": -1,
- })
- }
- if is_transfer == 1 || customerPositionId != gconv.Int64((*csmdata)["position_id"]) {
- if customerName == db.KeCheng.Admin {
- TiDb.UpdateOrDeleteBySql(`update dwd_f_csm_customer_autodraw_record set count = count + 2 where name = ?`, customerName)
- } else {
- TiDb.UpdateOrDeleteBySql(`update dwd_f_csm_customer_autodraw_record set count = count + 1 where name = ?`, customerName)
- }
- }
- KcSend(orderCode, customerName)
- TiDb.Update("dwd_f_crm_clue_info", map[string]interface{}{"id": clueId}, map[string]interface{}{"is_transfer": 1, "updatetime": nowTime, "name": userName})
- }
- } else {
- customerPositionId, customerName := cAutoDraw(gconv.Int(entId), orderPositionId, salesperson, saleDep, false, nil)
- log.Println("移交客成positionId", customerPositionId, customerName, saleDep, orderPositionId, salesperson, false)
- cId, ok, updateId1, updateId2, updateId3 := int64(0), false, int64(0), int64(0), int64(0)
- if TiDb.ExecTx("保存客户", func(tx *sql.Tx) bool {
- saveMap["position_id"] = customerPositionId
- saveMap["name"] = customerName
- cId = TiDb.InsertByTx(tx, "dwd_f_csm_customer_info", saveMap)
- ok = TiDb.UpdateByTx(tx, "dwd_f_crm_clue_info", map[string]interface{}{"id": clueId}, map[string]interface{}{"is_transfer": 1, "updatetime": nowTime, "name": userName})
- if customerPositionId > 0 {
- updateId1 = TiDb.InsertByTx(tx, "dwd_f_crm_clue_change_record", map[string]interface{}{
- "clue_id": clueId,
- "position_id": customerPositionId,
- "change_type": "加入任务车",
- "new_value": "未建联",
- "createtime": nowTime,
- "BCPCID": common.GetRandom(32),
- "operator_id": -1,
- })
- updateId3 = TiDb.InsertByTx(tx, "dwd_f_crm_clue_change_record", map[string]interface{}{
- "clue_id": clueId,
- "position_id": customerPositionId,
- "change_field": "position_id",
- "change_type": "客户成功经理",
- "old_value": "/",
- "new_value": customerName,
- "createtime": nowTime,
- "BCPCID": common.GetRandom(32),
- "operator_id": -1,
- })
- }
- KcSend(orderCode, customerName)
- updateId2 = TiDb.InsertByTx(tx, "dwd_f_crm_clue_change_record", map[string]interface{}{
- "clue_id": clueId,
- "position_id": customerPositionId,
- "change_type": "成交客户移交",
- "new_value": "移交至客户成功组",
- "createtime": nowTime,
- "BCPCID": common.GetRandom(32),
- "operator_id": -1,
- })
- return cId > -1 && ok && updateId1 > -1 && updateId2 > -1 && updateId3 > -1
- }) {
- if customerName == db.KeCheng.Admin {
- TiDb.UpdateOrDeleteBySql(`update dwd_f_csm_customer_autodraw_record set count = count + 2 where name = ?`, customerName)
- } else {
- TiDb.UpdateOrDeleteBySql(`update dwd_f_csm_customer_autodraw_record set count = count + 1 where name = ?`, customerName)
- }
- log.Println("保存客户成功")
- } else {
- log.Println("保存客户失败!!!", clueId, cId, ok, updateId1, updateId2, updateId3, " 用户信息 ", customerName, customerPositionId, uId)
- }
- }
- return status
- }
- func cAutoDraw(entId int, orderPositionId int64, salesperson, saleDep string, isExist bool, csmdata *map[string]interface{}) (positionId int64, name string) {
- 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 `
- data := TiDb.SelectBySql(query, db.EntId)
- if data == nil || len(*data) == 0 {
- return
- }
- positionId, name = findKcOldPerson(entId, orderPositionId, salesperson, saleDep, isExist, csmdata, data)
- if positionId == 0 {
- positionId, name = findKcNewPerson(entId, data)
- }
- return
- }
- func findKcOldPerson(entId int, orderPositionId int64, salesperson, saleDep string, isExist bool, csmdata *map[string]interface{}, data *[]map[string]interface{}) (positionId int64, name string) {
- //判断是否需要新增客成数据
- if isExist {
- //用户存在客成数据
- positionid := common.Int64All((*csmdata)["position_id"])
- if positionid != 0 {
- //以前没有,需要找一个新的
- for _, v := range *data {
- deptPositionId := gconv.Int64(v["position_id"])
- if deptPositionId == positionid {
- positionId = positionid
- name = gconv.String((*csmdata)["name"])
- return
- }
- }
- }
- //原始用户已离职 查看订单是否有合适的订单
- if saleDep == "客户成功部" {
- positionId = orderPositionId
- name = salesperson
- return
- }
- }
- //客成数据不存在的时候
- //查找企业有没有其他信息
- if entId > 0 {
- entdata := TiDb.Find("dwd_f_csm_customer_info", map[string]interface{}{"ent_id": entId}, "", "", -1, -1)
- if entdata != nil && len(*entdata) > 0 {
- for _, v := range *entdata {
- positionid := common.Int64All(v["position_id"])
- name = gconv.String(v["name"])
- for _, v := range *data {
- deptPositionId := gconv.Int64(v["position_id"])
- if deptPositionId == positionId {
- positionId = positionid
- name = gconv.String((*csmdata)["name"])
- return
- }
- }
- }
- }
- //原始用户已离职 或者没有查找相关企业客成信息 以订单信息为主
- if saleDep == "客户成功部" {
- positionId = orderPositionId
- name = salesperson
- }
- return
- //没有相同企业的客成信息
- } else {
- //没有人 分配给自己
- if saleDep == "客户成功部" {
- positionId = orderPositionId
- name = salesperson
- return
- }
- return
- }
- }
- func findKcNewPerson(entId int, data *[]map[string]interface{}) (positionId int64, name string) {
- if entId > 0 {
- entdata := TiDb.FindOne("dwd_f_csm_customer_info", map[string]interface{}{"ent_id": entId}, "", "")
- if entdata != nil && len(*entdata) > 0 {
- positionId = common.Int64All((*entdata)["position_id"])
- name = gconv.String((*entdata)["name"])
- return
- }
- }
- 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`
- countData := TiDb.SelectBySql(sql, db.EntId)
- if countData != nil && len(*countData) > 0 {
- for _, v := range *data {
- //判断是否有新员工
- isOk := false
- for _, vv := range *countData {
- if gconv.String(v["name"]) == gconv.String(vv["name"]) {
- isOk = true
- }
- }
- //有新员工直接分给新员工
- if !isOk {
- name = gconv.String(v["name"])
- rData := TiDb.FindOne("dwd_f_csm_customer_autodraw_record", map[string]interface{}{}, "", "count desc")
- TiDb.Insert("dwd_f_csm_customer_autodraw_record", map[string]interface{}{
- "name": name,
- "count": common.Int64All((*rData)["count"]),
- })
- break
- }
- }
- res := int64(0)
- countres := 0
- for _, v := range *countData {
- if countres == 0 {
- res = common.Int64All(v["count"])
- name = gconv.String(v["name"])
- } else {
- if common.Int64All(v["count"]) <= res {
- res = common.Int64All(v["count"])
- name = gconv.String(v["name"])
- }
- }
- countres++
- }
- }
- for _, v := range *data {
- if name == gconv.String(v["name"]) {
- positionId = common.Int64All(v["position_id"])
- }
- }
- return
- }
- func kcAuto() {
- log.Println("客户成功系统自动进入任务车定时任务开始")
- nowTime := time.Now().Format(date.Date_Full_Layout)
- 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`
- data := TiDb.SelectBySql(sql)
- if data != nil && *data != nil && len(*data) > 0 {
- for _, v := range *data {
- relationship_building_way := common.IntAll(v["relationship_building_way"])
- inventory_way := common.IntAll(v["inventory_way"])
- training_way := common.IntAll(v["training_way"])
- positionId := common.Int64All(v["position_id"])
- clueId := common.Int64All(v["clue_id"])
- tasksource, tasksources := gconv.String(v["tasksource"]), ""
- taskstatus := common.IntAll(v["taskstatus"])
- if relationship_building_way != 1 && inventory_way == 1 {
- tasksources = "2"
- TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
- "clue_id": clueId,
- "position_id": positionId,
- "change_type": "加入任务车",
- "new_value": "未盘点",
- "createtime": nowTime,
- "BCPCID": common.GetRandom(32),
- "operator_id": -1,
- })
- } else if inventory_way != 1 && training_way == 1 {
- tasksources = "3"
- TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
- "clue_id": clueId,
- "position_id": positionId,
- "change_type": "加入任务车",
- "new_value": "未培训",
- "createtime": nowTime,
- "BCPCID": common.GetRandom(32),
- "operator_id": -1,
- })
- }
- if taskstatus == 1 {
- tasksource = tasksources
- } else {
- if tasksource != "" {
- if !strings.Contains(tasksource, tasksources) {
- tasksource += "," + tasksources
- }
- } else {
- tasksource = tasksources
- }
- }
- TiDb.Update("dwd_f_csm_customer_info", map[string]interface{}{"clue_id": clueId}, map[string]interface{}{
- "tasksource": tasksource,
- "tasktime": nowTime,
- "is_task": 1,
- "taskstatus": 0,
- })
- }
- }
- log.Println("客户成功系统进入任务车定时任务结束")
- }
- func ordersClue() {
- lastOrderClueId := cfg.LastOrderClueId
- nowTime := time.Now().Format(date.Date_Full_Layout)
- product_type_str2 := `"大会员","企业商机管理","VIP订阅"`
- 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
- INNER JOIN jy_order_detail b on a.order_code=b.order_code
- and b.update_time>="%s" AND a.user_phone NOT LIKE "%s" and a.user_id !=""
- 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)
- log.Println("后台订单线索定时任务", sql)
- data := Mysql.SelectBySql(sql)
- log.Println("后台订单线索定时任务", len(*data))
- if data != nil && *data != nil && len(*data) > 0 {
- for _, v := range *data {
- payMoney := common.IntAll(v["pay_money"])
- orderCode := gconv.String(v["order_code"])
- saleDep, _, salesperson := FindSaleRecord(orderCode)
- userPhone := gconv.String(v["user_phone"])
- createperson := gconv.String(v["create_person"])
- userId, uId, cluename, seatNumber, positionId, trailstatus, clueId := gconv.String(v["user_id"]), "", "", "", int64(0), "", int64(0)
- if saleDep != "" {
- //销售部
- query := map[string]interface{}{}
- source := ""
- if !mongodb.IsObjectIdHex(userId) {
- userMapping := TiDb.FindOne("dwd_f_userbase_id_mapping", map[string]interface{}{"position_id": userId}, "", "")
- if userMapping != nil && len(*userMapping) > 0 {
- userId = gconv.String((*userMapping)["userid"])
- } else {
- log.Println("后台订单--未查询到 ", userPhone)
- break
- }
- }
- query["userid"] = userId
- userInfo := TiDb.FindOne("dwd_f_userbase_baseinfo", query, "", "")
- if userInfo != nil && len(*userInfo) > 0 {
- uId = gconv.String((*userInfo)["uid"])
- source = gconv.String((*userInfo)["source"])
- } else {
- log.Println("后台订单--未查询到 ", query, userPhone)
- break
- }
- is_assign := 1
- mailContent := ""
- cluename = gconv.String(v["company_name"])
- mailContent = fmt.Sprintf("%s(%s)", cluename, userPhone)
- if cluename == "" {
- cluename = userPhone
- mailContent = userPhone
- }
- if payMoney > 0 {
- trailstatus = "08"
- } else {
- trailstatus = "01"
- }
- isGroup, isCommerce := GetCompanyType(cluename, uId) //判断是否集团公司、工商库
- clueData := TiDb.FindOne("dwd_f_crm_clue_info", map[string]interface{}{"uid": uId}, "", "")
- if clueData == nil || len(*clueData) == 0 {
- log.Println("saleDep", saleDep)
- if saleDep == "销售部" {
- //撞单
- log.Println("销售部订单", saleDep)
- if strings.Contains(salesperson, ",") {
- log.Println("销售部撞单 ", salesperson)
- if salesperson == "" {
- salesperson = createperson
- }
- }
- log.Println("销售部订单salesperson", salesperson)
- saleData := TiDb.FindOne("dwd_f_crm_personnel_management", map[string]interface{}{"name": salesperson}, "", "")
- if saleData != nil {
- seatNumber = gconv.String((*saleData)["seat_number"])
- positionId = common.Int64All((*saleData)["position_id"])
- }
- if IsFreeze(source, payMoney, gconv.String(positionId), trailstatus) {
- //线索需要冻结
- is_assign = -3
- }
- clueId = TiDb.Insert("dwd_f_crm_clue_info", map[string]interface{}{
- "userid": userId,
- "uid": uId,
- "seatNumber": seatNumber,
- "position_id": positionId,
- "is_assign": is_assign,
- "comeintime": nowTime,
- "createtime": nowTime,
- "updatetime": nowTime,
- "cluename": cluename,
- "top_cluetype": "4",
- "sub_cluetype": "154",
- "trailstatus": trailstatus,
- "name": userPhone,
- "phone": userPhone,
- "comeinsource_private": 2,
- "is_task": 0,
- "taskstatus": 0,
- "company_nature": isGroup,
- "company_verification": isCommerce,
- "FREEZE_TIME": nowTime,
- })
- } else if saleDep == "市场部" {
- log.Println("市场部订单", saleDep)
- clueId = TiDb.Insert("dwd_f_crm_clue_info", map[string]interface{}{
- "userid": userId,
- "uid": uId,
- "is_assign": -2,
- "createtime": nowTime,
- "updatetime": nowTime,
- "cluename": cluename,
- "top_cluetype": "4",
- "sub_cluetype": "154",
- "trailstatus": trailstatus,
- "name": userPhone,
- "phone": userPhone,
- "is_task": 0,
- "taskstatus": 0,
- "company_nature": isGroup,
- "company_verification": isCommerce,
- "FREEZE_TIME": nowTime,
- })
- }
- if clueId > 0 {
- TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
- "clue_id": clueId,
- "position_id": common.If(positionId > 0, positionId, -1),
- "change_type": "创建线索",
- "new_value": "系统自动创建",
- "createtime": nowTime,
- "BCPCID": common.GetRandom(32),
- "operator_id": -1,
- })
- if is_assign == -3 {
- //新增冻结记录
- TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
- "clue_id": clueId,
- "position_id": positionId,
- "change_type": "线索冻结",
- "new_value": "销售人员私海已达上限",
- "createtime": nowTime,
- "BCPCID": common.GetRandom(32),
- "operator_id": -1,
- })
- //移交失败发送消息
- if IsFreeze(source, payMoney, gconv.String(positionId), trailstatus) {
- //发送邮件信息
- OrderCreateFail(positionId, mailContent)
- }
- }
- }
- }
- }
- cfg.LastOrderClueId = gconv.String(v["update_time"])
- }
- }
- common.WriteSysConfig(&cfg)
- log.Println("后台订单线索定时任务结束")
- }
- func refundAuto() {
- log.Println("自动移交销售定时任务开始")
- findNowTime := time.Now().AddDate(0, 0, -db.ExpirationPeriod).Format(date.Date_Full_Layout)
- nowTime := time.Now().Format(date.Date_Full_Layout)
- mailData := map[string][]map[string]interface{}{}
- salesEmailData := map[int64][]map[string]interface{}{}
- TiDb.SelectByBath(100, func(l *[]map[string]interface{}) bool {
- for _, v := range *l {
- cluename, company_nature, company_verification, uid, phone, userName, oldSaleId, oldsaleName := "", 0, 0, "", "", "", int64(0), ""
- saleId, newSeatNumber, newPerson := int64(0), "", ""
- clueId := common.Int64All(v["clue_id"])
- company_name := gconv.String(v["company_name"])
- name := gconv.String(v["name"])
- kcposition_id := common.Int64All(v["position_id"])
- isRenewalProtection := common.IntAll(v["is_renewal_protection"])
- clueData := TiDb.FindOne("dwd_f_crm_clue_info", map[string]interface{}{"id": clueId}, "name,phone,company_nature,company_verification,cluename,userid,position_id,uid", "")
- if clueData != nil && len(*clueData) > 0 {
- uid = gconv.String((*clueData)["uid"])
- saleId, newPerson, newSeatNumber = FindPositionIdClueId(uid)
- oldSaleId = common.Int64All((*clueData)["position_id"])
- oldPersonData := FindPersonOne(oldSaleId)
- if oldSaleId != 0 {
- oldsaleName = gconv.String(oldPersonData["name"])
- }
- cluename = gconv.String((*clueData)["cluename"])
- userName = gconv.String((*clueData)["name"])
- company_nature = common.IntAll((*clueData)["company_nature"])
- company_verification = common.IntAll((*clueData)["company_verification"])
- phone = gconv.String((*clueData)["phone"])
- }
- personArr := getUserIdToUid(uid)
- productArr, _ := KcProduct()
- if len(productArr) == 0 || len(personArr) == 0 {
- log.Println("查询不到进客成商品类型或查询不到用户信息")
- continue
- }
- //查询即将到期数据
- if isRenewalProtection == 0 {
- 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, ","))
- _, vipEndDateStr := getOrderData(sqlStr)
- if vipEndDateStr != "" {
- endDate := time.Now().AddDate(0, 0, -db.ExpirationPeriod+3).Unix()
- startDate := time.Now().AddDate(0, 0, -db.ExpirationPeriod+2).Unix()
- vipEndDate, _ := time.ParseInLocation(time.DateTime, vipEndDateStr, time.Local)
- log.Println(vipEndDate.Unix() > startDate, vipEndDate.Unix() < endDate)
- log.Println(vipEndDate.Unix(), startDate, endDate)
- if vipEndDate.Unix() > startDate && vipEndDate.Unix() < endDate {
- //即将到期
- mailData[name] = append(mailData[name], map[string]interface{}{
- "company_name": company_name,
- "phone": phone,
- "userName": userName,
- "remrk": "3天后即将移交",
- "reason": "成交客户续费失败",
- })
- continue
- }
- }
- }
- isFull := false
- isAllRefund := false
- 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, ","))
- myOrders, _ := getOrderData(orderSql)
- if myOrders != nil || len(myOrders) > 0 {
- refundCount := 0
- for _, v := range myOrders {
- if common.IntAll(v["refund_status"]) == 1 {
- refundCount++
- }
- }
- if len(myOrders) > 0 && len(myOrders) == refundCount {
- isAllRefund = true
- }
- }
- if isAllRefund {
- //全退款了
- 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)
- TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
- "clue_id": clueId,
- "position_id": common.If(kcposition_id > 0, kcposition_id, -1),
- "change_type": "退回公海",
- "new_value": "成交客户申请退款",
- "createtime": nowTime,
- "BCPCID": common.GetRandom(32),
- "operator_id": -1,
- })
- TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
- "clue_id": clueId,
- "position_id": common.If(kcposition_id > 0, kcposition_id, -1),
- "change_field": "trailstatus",
- "change_type": "基本信息变更",
- "old_value": "成交客户",
- "new_value": "商机线索",
- "createtime": nowTime,
- "BCPCID": common.GetRandom(32),
- "operator_id": -1,
- })
- TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
- "clue_id": clueId,
- "position_id": common.If(kcposition_id > 0, kcposition_id, -1),
- "change_type": "客户成功经理",
- "change_field": "position_id",
- "old_value": name,
- "new_value": "/",
- "createtime": nowTime,
- "BCPCID": common.GetRandom(32),
- "operator_id": -1,
- })
- TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
- "clue_id": clueId,
- "position_id": common.If(kcposition_id > 0, kcposition_id, -1),
- "change_type": "移交销售",
- "new_value": "成交客户申请退款",
- "createtime": nowTime,
- "BCPCID": common.GetRandom(32),
- "operator_id": -1,
- })
- mailData[name] = append(mailData[name], map[string]interface{}{
- "company_name": company_name,
- "phone": phone,
- "userName": userName,
- "remrk": "已移交",
- "reason": "成交客户申请退款",
- })
- TiDb.UpdateOrDeleteBySql(`UPDATE dwd_f_csm_customer_info SET is_transfer=1 WHERE clue_id = ?`, clueId)
- } else {
- log.Println("客成到期处理")
- 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)
- log.Println("有效订单查询", order1Sql)
- order1 := Mysql.SelectBySql(order1Sql)
- if order1 == nil || len(*order1) == 0 {
- isOk := false
- order3Sql := 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 and b.service_endtime<"%s" ORDER BY b.service_endtime desc `,
- strings.Join(personArr, ","), strings.Join(productArr, ","), findNowTime)
- log.Println("有效订单查询1", order3Sql)
- _, vip_endtime := getOrderData(order3Sql)
- if vip_endtime != "" {
- //获取最后一个订单信息
- if isRenewalProtection == 1 {
- vip_endtimes, _ := time.ParseInLocation(date.Date_Full_Layout, vip_endtime, time.Local)
- //查询申请保护时间
- renewalTime := time.Now()
- timeData := TiDb.SelectBySql(`select max(createtime) as createtime from dwd_f_crm_clue_change_record where clue_id = ? and change_type="申请续费保护"`, clueId)
- if timeData != nil && len(*timeData) > 0 {
- if gconv.String(gconv.String((*timeData)[0]["createtime"])) != "" {
- renewalTime, _ = time.ParseInLocation(date.Date_Full_Layout, gconv.String((*timeData)[0]["createtime"]), time.Local)
- }
- }
- renewalInt := renewalTime.Unix()
- log.Println("申请保护期时间", clueId, renewalInt)
- log.Println("申请保护期时间222", time.Now().Unix()-vip_endtimes.Unix(), (db.HandoverCycle-1)*86400, (db.HandoverCycle)*86400)
- //查看服务到期时间
- if renewalInt != 0 && renewalInt < db.CustomerTime {
- //三个月
- if time.Now().Unix()-vip_endtimes.Unix() < 3*30*86400 {
- isOk = true
- }
- } else if (db.HandoverCycle-5)*86400 < time.Now().Unix()-vip_endtimes.Unix() && time.Now().Unix()-vip_endtimes.Unix() < (db.HandoverCycle-4)*86400 {
- //提前一天提示
- mailData[name] = append(mailData[name], map[string]interface{}{
- "company_name": company_name,
- "phone": phone,
- "userName": userName,
- "remrk": "3天后即将移交",
- "reason": "成交客户续费失败",
- })
- isOk = true
- } else if time.Now().Unix()-vip_endtimes.Unix() < db.HandoverCycle*86400 {
- isOk = true
- }
- }
- }
- if !isOk {
- //全到期了
- if saleId > 0 {
- saleData := TiDb.FindOne("dwd_f_crm_personnel_management", map[string]interface{}{"position_id": saleId, "resign": 0}, "", "")
- if saleData != nil && len(*saleData) > 0 {
- //该销售人没有变更
- } else {
- if company_nature == 0 && company_verification == 1 && cluename != "" {
- adata := TiDb.Find("dwd_f_crm_clue_info", map[string]interface{}{"cluename": cluename, "is_assign": 1}, "seatNumber,position_id", "", -1, -1)
- if adata != nil && len(*adata) > 0 {
- isOks := false
- for _, vv := range *adata {
- position_ids := common.Int64All(vv["position_id"])
- newSeatNumber = gconv.String(vv["seatNumber"])
- saleDatas := TiDb.FindOne("dwd_f_crm_personnel_management", map[string]interface{}{"position_id": position_ids, "resign": 0}, "", "")
- if saleDatas != nil && len(*saleDatas) > 0 {
- saleId = position_ids
- newPerson = gconv.String((*saleDatas)["name"])
- isOks = true
- break
- }
- }
- if !isOks {
- 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)
- if len(*sdata) == 0 {
- 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)
- }
- if sdata != nil && len(*sdata) > 0 {
- saleId = common.Int64All((*sdata)[0]["position_id"])
- newSeatNumber = gconv.String((*sdata)[0]["seat_number"])
- newPerson = gconv.String((*sdata)[0]["name"])
- }
- }
- }
- } else {
- sdata := &[]map[string]interface{}{}
- //查看当前是否属于一部三部
- userData := FindPersonOne(saleId)
- if userData != nil {
- deptName := gconv.String(userData["dept_name"])
- if strings.Contains(deptName, "一部") {
- 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)
- if len(*sdata) == 0 {
- 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)
- }
- } else if strings.Contains(deptName, "三部") {
- 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)
- }
- }
- if sdata != nil && len(*sdata) > 0 {
- saleId = common.Int64All((*sdata)[0]["position_id"])
- newSeatNumber = gconv.String((*sdata)[0]["seat_number"])
- newPerson = gconv.String((*sdata)[0]["name"])
- }
- }
- }
- }
- if kcposition_id > 0 {
- mailData[name] = append(mailData[name], map[string]interface{}{
- "company_name": company_name,
- "phone": phone,
- "userName": userName,
- "remrk": "已移交",
- "reason": "成交客户续费失败",
- })
- }
- isFull = FindUpperLimit(gconv.String(saleId), "", false)
- if saleId > 0 {
- salesEmailData[saleId] = append(salesEmailData[saleId], map[string]interface{}{
- "company_name": company_name,
- "phone": phone,
- "userName": userName,
- "remrk": "已移交",
- "reason": "成交客户续费失败",
- "cluename": cluename,
- })
- if saleId != oldSaleId {
- //新增个人员变更
- TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
- "clue_id": clueId,
- "position_id": saleId,
- "change_field": "position_id",
- "change_type": "所属人变更",
- "old_value": common.If(oldsaleName != "", oldsaleName, "/"),
- "new_value": common.If(newPerson != "", newPerson, "/"),
- "createtime": nowTime,
- "BCPCID": common.GetRandom(32),
- "operator_id": -1,
- })
- if isFull {
- 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)
- } else {
- 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)
- }
- } else {
- if isFull {
- 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)
- } else {
- 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)
- }
- }
- } else if saleId == 0 {
- //找不到人
- 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)
- if oldSaleId != 0 {
- //新增个人员变更
- TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
- "clue_id": clueId,
- "position_id": saleId,
- "change_field": "position_id",
- "change_type": "所属人变更",
- "old_value": common.If(oldsaleName != "", oldsaleName, "/"),
- "new_value": common.If(newPerson != "", newPerson, "/"),
- "createtime": nowTime,
- "BCPCID": common.GetRandom(32),
- "operator_id": -1,
- "SHUOMING": "业绩归属查不到人",
- })
- //再做一个记录变更
- }
- }
- TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
- "clue_id": clueId,
- "position_id": common.If(kcposition_id > 0, kcposition_id, -1),
- "change_type": "基本信息变更",
- "old_value": "成交客户",
- "change_field": "trailstatus",
- "new_value": "商机线索",
- "createtime": nowTime,
- "BCPCID": common.GetRandom(32),
- "operator_id": -1,
- })
- if saleId > 0 {
- TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
- "clue_id": clueId,
- "position_id": saleId,
- "change_type": "加入任务车",
- "new_value": "线索自动分配-其他-成交客户续约失败",
- "createtime": nowTime,
- "BCPCID": common.GetRandom(32),
- "operator_id": -1,
- })
- }
- TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
- "clue_id": clueId,
- "position_id": common.If(kcposition_id > 0, kcposition_id, -1),
- "change_type": "客户成功经理",
- "change_field": "position_id",
- "old_value": name,
- "new_value": "/",
- "createtime": nowTime,
- "BCPCID": common.GetRandom(32),
- "operator_id": -1,
- })
- TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
- "clue_id": clueId,
- "position_id": saleId,
- "change_type": "移交销售",
- "new_value": "成交客户续费失败,到期自动移交",
- "createtime": nowTime,
- "BCPCID": common.GetRandom(32),
- "operator_id": -1,
- })
- TiDb.UpdateOrDeleteBySql(`UPDATE dwd_f_csm_customer_info SET is_transfer=1 WHERE clue_id = ?`, clueId)
- if isFull {
- //新增冻结记录
- TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
- "clue_id": clueId,
- "position_id": saleId,
- "change_type": "线索冻结",
- "new_value": "销售人员私海已达上限",
- "createtime": nowTime,
- "BCPCID": common.GetRandom(32),
- "operator_id": -1,
- })
- //发送邮件
- mailContent := ""
- if cluename != "" {
- if phone != "" {
- if cluename == phone {
- mailContent = phone
- } else {
- mailContent = fmt.Sprintf("%s(%s)", cluename, phone)
- }
- } else {
- mailContent = cluename
- }
- } else {
- mailContent = phone
- }
- HandOverFail(saleId, mailContent)
- }
- }
- }
- }
- }
- return true
- }, `select ent_id,clue_id,position_id,name,is_renewal_protection,company_name from dwd_f_csm_customer_info where is_transfer = 0`)
- //}, `select ent_id,clue_id,position_id,name,is_renewal_protection,company_name from dwd_f_csm_customer_info where clue_id =1892234`)
- //移交电销提醒
- for i, v := range mailData {
- ExitKcSend(i, v)
- }
- //移交电销销售提醒
- for i, v := range salesEmailData {
- ExitKcSaleSend(i, v)
- }
- log.Println("自动移交销售定时任务结束")
- }
- // 查找一部三部人员信息 返回人员信息 以及管理员信息
- func FindDeptAdmin(positionId int64) (map[string]interface{}, map[string]interface{}, map[string]interface{}) {
- //先判断那个部门的
- userData1 := TiDb.SelectBySql(`SELECT
- a.position_id,
- a.name,
- b.seat_number,
- b.role_id,
- a.bi_pcode,
- a.dept_name,
- a.resign
- FROM
- (SELECT *
- FROM dwd_d_crm_department_level_succbi u1
- WHERE id = (
- SELECT MAX(id)
- FROM dwd_d_crm_department_level_succbi u2
- WHERE u1.position_id = u2.position_id
- )
- ORDER BY id desc) a
- INNER JOIN (SELECT *
- FROM dwd_f_crm_personnel_management u1
- WHERE id = (
- SELECT MAX(id)
- FROM dwd_f_crm_personnel_management u2
- WHERE u1.position_id = u2.position_id
- )
- ORDER BY id desc) b ON a.dept_name LIKE "%销售一部%"
- AND a.position_id = b.position_id`)
- userData3 := TiDb.SelectBySql(`SELECT
- a.position_id,
- a.name,
- b.seat_number,
- b.role_id,
- a.bi_pcode,
- a.dept_name,
- a.resign
- FROM
- (SELECT *
- FROM dwd_d_crm_department_level_succbi u1
- WHERE id = (
- SELECT MAX(id)
- FROM dwd_d_crm_department_level_succbi u2
- WHERE u1.position_id = u2.position_id
- )
- ORDER BY id desc) a
- INNER JOIN (SELECT *
- FROM dwd_f_crm_personnel_management u1
- WHERE id = (
- SELECT MAX(id)
- FROM dwd_f_crm_personnel_management u2
- WHERE u1.position_id = u2.position_id
- )
- ORDER BY id desc) b ON
- a.dept_name LIKE "%销售三部"
- AND a.position_id = b.position_id`)
- if userData3 == nil || len(*userData3) == 0 || userData1 == nil || len(*userData1) == 0 {
- log.Println("找不到一部三部员工信息")
- return nil, nil, nil
- }
- //一部高级管理员信息
- seniorAdmin1 := map[string]interface{}{}
- //三部高级管理员信息
- seniorAdmin3 := map[string]interface{}{}
- //一部管理员信息
- admin1 := map[string]map[string]interface{}{}
- //返回当前人信息
- admin := map[string]interface{}{}
- for _, v := range *userData3 {
- v["type"] = 3
- id := gconv.Int64(v["position_id"])
- roleId := gconv.Int64(v["role_id"])
- resign := gconv.Int64(v["resign"])
- if id == positionId && resign == 0 {
- admin = v
- }
- if roleId == 8 {
- v["orderStatus"] = 2
- seniorAdmin3 = v
- }
- }
- for _, v := range *userData1 {
- v["type"] = 1
- id := gconv.Int64(v["position_id"])
- roleId := gconv.Int64(v["role_id"])
- dept_name := gconv.String(v["dept_name"])
- resign := gconv.Int64(v["resign"])
- if id == positionId && resign == 0 {
- admin = v
- }
- if roleId == 8 {
- v["orderStatus"] = 2
- seniorAdmin1 = v
- } else if roleId == 3 {
- admin1[dept_name] = v
- }
- }
- //查看当前人属于哪个部门
- if admin == nil {
- //当前人不属于电销部的
- admin = *(TiDb.FindOne("dwd_f_crm_personnel_management", map[string]interface{}{
- "position_id": positionId,
- "resign": 1,
- }, "name", ""))
- }
- positiontype := gconv.Int64(admin["type"])
- deptName := gconv.String(admin["dept_name"])
- switch positiontype {
- case 1:
- roleId := gconv.Int64(admin["role_id"])
- if roleId == 3 {
- return admin, nil, seniorAdmin1
- }
- return admin, admin1[deptName], seniorAdmin1
- case 3:
- return admin, nil, seniorAdmin3
- default:
- return admin, nil, nil
- }
- }
- // 邮箱获取
- func GetMail(personName string) (string, string) {
- data := Mysql.SelectBySql(`select name,mail,img from entniche_user where ent_id =?`, db.EntId)
- if data == nil || len(*data) == 0 {
- return "", ""
- }
- for _, m := range *data {
- name := gconv.String(m["name"])
- if name == personName {
- //
- return gconv.String(m["mail"]), gconv.String(m["img"])
- }
- }
- return "", ""
- }
- // 退客成进销售 销售收邮件
- func ExitKcSaleSend(positionId int64, infoList []map[string]interface{}) {
- to := SaleMail(positionId)
- //退出客成 即将退出客成信息 销售信息编辑
- gmail := &mail.GmailAuth{
- SmtpHost: db.Mail.SmtpHost,
- SmtpPort: db.Mail.SmtpPort,
- User: db.Mail.User,
- Pwd: db.Mail.Pwd,
- }
- //正文拼接
- 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></tr></thead><tbody>`
- for i, v := range infoList {
- 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"]))
- }
- endStr := `</tbody></table><p></body></html>`
- startStr += endStr
- if to != "" {
- status := mail.GSendMail_q("剑鱼标讯", to, "", "", "成交客户续费失败移交销售通知", startStr, "", "", gmail)
- if status {
- log.Println("客成发邮件 send mail success", startStr, to)
- }
- }
- }
- // 客成人员变更发邮件
- func CustomerChange() {
- personMap := map[int64]string{}
- 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)
- if personData != nil && len(*personData) > 0 {
- for _, v := range *personData {
- personMap[gconv.Int64(v["position_id"])] = gconv.String(v["name"])
- }
- }
- startTime := cfg.LastKcChangeTime
- if startTime == "" {
- startTime = time.Now().Format(time.DateTime)
- }
- customMap1 := map[string][]map[string]interface{}{}
- customMap2 := map[string][]map[string]interface{}{}
- saleMap := map[int64][]map[string]interface{}{}
- saleNobodyCustomMapMap := map[int64][]map[string]interface{}{}
- TiDb.SelectByBath(100, func(l *[]map[string]interface{}) bool {
- for _, v := range *l {
- startTime = gconv.String(v["createtime"])
- data := CustomerChangeHandle(v)
- oldPerson := gconv.String(data["oldPerson"])
- newPerson := gconv.String(data["newPerson"])
- positionId := gconv.Int64(data["positionId"])
- operatorId := gconv.Int64(data["operatorId"])
- if oldPerson == "/" {
- data["oldPerson"] = "-"
- }
- if positionId > 0 {
- data["positionName"] = personMap[positionId]
- }
- if operatorId > 0 {
- //手动分配 客成收邮件
- data["operatorName"] = personMap[operatorId]
- if newPerson != "" && newPerson != "/" {
- customMap2[newPerson] = append(customMap2[newPerson], data)
- }
- if oldPerson != "" && oldPerson != "/" {
- customMap1[oldPerson] = append(customMap1[oldPerson], data)
- }
- } else {
- //自动分配 销售收邮件
- if (oldPerson == "" || oldPerson == "/") && newPerson != "" && newPerson != "/" && positionId > 0 {
- //之前没有可成人员
- saleNobodyCustomMapMap[positionId] = append(saleNobodyCustomMapMap[positionId], data)
- } else if newPerson != "" && newPerson != "/" && oldPerson != "" && oldPerson != "/" && positionId > 0 {
- //之前有客成
- saleMap[positionId] = append(saleMap[positionId], data)
- }
- }
- }
- return true
- }, `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)
- //}, `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)
- if len(customMap1) > 0 {
- ChangeSendKc(customMap1, 1)
- }
- if len(customMap2) > 0 {
- ChangeSendKc(customMap2, 2)
- }
- if len(saleMap) > 0 {
- ChangeSendSale(saleMap, 2)
- }
- if len(saleNobodyCustomMapMap) > 0 {
- ChangeSendSale(saleNobodyCustomMapMap, 1)
- }
- log.Println("11111", startTime)
- cfg.LastKcChangeTime = startTime
- common.WriteSysConfig(&cfg)
- }
- // 客户成功经理变更邮件提醒客成人员
- func ChangeSendKc(data map[string][]map[string]interface{}, personType int64) {
- for name, v := range data {
- to, _ := GetMail(name)
- //正文拼接
- 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><th>操作人</th></tr></thead><tbody>`
- for i, v := range v {
- 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"]))
- }
- endStr := `</tbody></table><p></body></html>`
- startStr += endStr
- if to != "" {
- status := mail.GSendMail_q("剑鱼标讯", to, "", "", gconv.String(common.If(personType == 2, "您有新的客户,请及时跟进处理", "您的客户已转至其他客户成功经理负责")), startStr, "", "", &Gmail)
- if status {
- log.Println("客成发邮件 send mail success", startStr, to, "")
- }
- }
- }
- }
- func ChangeSendSale(data map[int64][]map[string]interface{}, personType int64) {
- log.Println("客成人员变更", personType, data)
- if personType == 1 {
- //客户成功经理从空变成有人
- for _, v := range data {
- for _, v1 := range v {
- positionId := gconv.Int64(v1["positionId"])
- to := SaleMail(positionId)
- _, img := GetMail(gconv.String(v1["newPerson"]))
- //抄送人查询
- 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>
- <p>销售人员"%s"成交的客户已成功移交至客成,线索名称:%s,姓名:%s,手机号:%s,负责客户成功经理:%s</p>
- <p>请引导客户添加客户成功经理企业微信:</p><div class='clear'>%s</div>`
- 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), ""))
- if to != "" {
- status := mail.GSendMail_q("剑鱼标讯", to, "", "", "成交客户已成功移交客成", endStr, "", "", &Gmail)
- if status {
- log.Println("客成发邮件 send mail success", endStr, to, "")
- }
- }
- }
- }
- return
- }
- //客户成功经理从A变成了B
- for positionId, v := range data {
- to := SaleMail(positionId)
- //正文拼接
- 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><th>销售人员</th></tr></thead><tbody>`
- for i, v := range v {
- 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["clueName"]), gconv.String(v["phone"]), gconv.String(v["userName"]), gconv.String(v["oldPerson"]), gconv.String(v["newPerson"]), gconv.String(v["positionName"]))
- }
- endStr := `</tbody></table><p></body></html>`
- startStr += endStr
- if to != "" {
- status := mail.GSendMail_q("剑鱼标讯", to, "", "", "成交客户负责客户成功经理变更", startStr, "", "", &Gmail)
- if status {
- log.Println("客成发邮件 send mail success", startStr, to, "")
- }
- }
- }
- }
- // 客成人员变更基本信息获取
- func CustomerChangeHandle(data map[string]interface{}) map[string]interface{} {
- clueId := gconv.Int64(data["clue_id"])
- oldPerson := gconv.String(data["old_value"])
- newPerson := gconv.String(data["new_value"])
- operatorId := gconv.Int64(data["operator_id"])
- companyName := ""
- phone := ""
- userName := ""
- clueName := ""
- clueData := TiDb.FindOne("dwd_f_crm_clue_info", map[string]interface{}{
- "id": clueId,
- }, "", "")
- if clueData == nil || len(*clueData) == 0 {
- return nil
- }
- uid := gconv.String((*clueData)["uid"])
- phone = gconv.String((*clueData)["phone"])
- userName = gconv.String((*clueData)["name"])
- //positionId := gconv.Int64((*clueData)["position_id"])
- positionId, _, _ := FindPositionIdClueId(uid)
- clueName = gconv.String((*clueData)["cluename"])
- customData := TiDb.FindOne("dwd_f_csm_customer_info", map[string]interface{}{
- "clue_id": clueId,
- }, "", "")
- if customData != nil || len(*customData) != 0 {
- companyName = gconv.String((*customData)["company_name"])
- }
- return map[string]interface{}{
- "oldPerson": oldPerson,
- "newPerson": newPerson,
- "operatorId": operatorId,
- "phone": phone,
- "userName": userName,
- "positionId": positionId,
- "clueName": clueName,
- "companyName": companyName,
- }
- }
- // 查找订单实际业绩归属
- func FindPositionIdClueId(uid string) (int64, string, string) {
- personArr := getUserIdToUid(uid)
- productArr, _ := KcProduct()
- querySql := fmt.Sprintf(` SELECT
- d.saler_name as salesperson ,c.position_id,f.dept_name,c.seat_number,b.product_type as productType,b.filter
- FROM
- jianyu.dataexport_order a INNER JOIN jianyu.jy_order_detail b on
- a.order_code=b.order_code and a.user_id in (%s)
- AND (
- b.final_price > 0
- OR (
- b.final_price = 0
- AND ( a.zero_type= "分期付款权益补充" OR a.zero_type= "原订单不支持开通多项权益" OR a.zero_type= "权益码兑换" )))
- AND a.order_status = 1 and a.user_phone not like "%s"
- AND ( a.refund_status != 1 OR a.refund_status IS NULL )
- AND b.service_starttime < "2099-01-01"
- AND b.product_type IN (%s )
- 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 ) )
- inner JOIN jianyu.order_sale_record d on b.order_code=d.ordercode and d.state=1
- INNER JOIN jianyu.entniche_user e on d.ent_userId = e.id
- INNER JOIN dwd_f_crm_personnel_management c on c.ent_id =? and e.name=c.name
- inner join dwd_d_crm_department_level_succbi f on c.position_id=f.position_id
- ORDER BY
- b.service_endtime desc ,b.final_price DESC `, strings.Join(personArr, ","), "9%", strings.Join(productArr, ","))
- log.Println("业绩归属查询:", querySql)
- clueData := TiDb.SelectBySql(querySql, db.EntId)
- if clueData == nil || len(*clueData) == 0 {
- return 0, "", ""
- }
- for _, m := range *clueData {
- productType := gconv.String(m["productType"])
- if productType == "大会员" {
- level := gconv.Int(m["service_type"])
- if level == 4 {
- continue
- }
- }
- deptName := gconv.String(m["dept_name"])
- if strings.Contains(deptName, "一部") || strings.Contains(deptName, "三部") {
- return gconv.Int64(m["position_id"]), gconv.String(m["salesperson"]), gconv.String(m["seat_number"])
- }
- }
- return 0, "", ""
- }
- func refundAutoHistory() {
- data := TiDb.Find("dwd_f_crm_clue_autodraw_record", nil, "", "", -1, -1)
- if data != nil {
- for _, v := range *data {
- seatNumber := gconv.String(v["seatNumber"])
- adata := TiDb.Find("dwd_f_crm_personnel_management", map[string]interface{}{"seat_number": seatNumber}, "", "", -1, -1)
- if adata != nil {
- for _, vv := range *adata {
- if common.IntAll(vv["resign"]) == 0 {
- position_id := common.Int64All(vv["position_id"])
- TiDb.Update("dwd_f_crm_clue_autodraw_record", map[string]interface{}{"seatNumber": seatNumber}, map[string]interface{}{"position_id": position_id})
- break
- }
- }
- }
- }
- }
- }
- func IsFreeze(source string, pay_money int, positionId, trailstatus string) bool {
- log.Println(source, pay_money == 0, FindUpperLimit(gconv.String(
- positionId), "", false), trailstatus)
- if source == "0104" && pay_money == 0 && FindUpperLimit(gconv.String(
- positionId), "", false) {
- return true
- } else if source == "0104" && pay_money > 0 && trailstatus == "08" && FindUpperLimit(gconv.String(
- positionId), "", false) {
- return true
- }
- return false
- }
- // 业绩归属查询
- func FindSaleRecord(orderCode string) (dept string, positionId int64, position string) {
- recordList := Mysql.SelectBySql(`
- SELECT DISTINCT
- a.saler_dept,
- a.saler_name,
- b.phone
- FROM
- order_sale_record a
- INNER JOIN entniche_user b
- on
- a.ordercode = ? and a.ent_userId = b.id
- ORDER BY
- a.state,
- a.money desc
- `, orderCode)
- if recordList != nil && len(*recordList) > 0 {
- saler_dept := gconv.String((*recordList)[0]["saler_dept"])
- if strings.Contains(saler_dept, "销售") {
- saler_dept = "销售部"
- } else if strings.Contains(saler_dept, "市场") {
- saler_dept = "市场部"
- } else if strings.Contains(saler_dept, "客户成功") && !strings.Contains(saler_dept, "客服") {
- saler_dept = "客户成功部"
- } else {
- saler_dept = ""
- }
- positionid := PhoneToPositionId(gconv.String((*recordList)[0]["phone"]))
- if positionid > 0 {
- return saler_dept, positionid, gconv.String((*recordList)[0]["saler_name"])
- }
- }
- return "", int64(0), ""
- }
- func PhoneToPositionId(phone string) int64 {
- positionId := int64(0)
- data := Base.SelectBySql(`SELECT
- b.id
- FROM
- base_user a
- INNER JOIN base_position b ON a.phone = ?
- AND a.id = b.user_id
- AND b.ent_id = 25917`, phone)
- if data != nil && len(*data) > 0 {
- positionId = gconv.Int64((*data)[0]["id"])
- }
- return positionId
- }
- func kcClue(userId, uId, seatNumber, cluename, top_cluetype, sub_cluetype,
- name, phone, position, sourceCode, industry, follow_project_area,
- role, item, subname, topname, remark, demand, department, departments, saleName, source string, positionId int64, isGroup, isCommerce int, keywords []string) bool {
- clueId, uodateId1, uodateId2, uodateId3, uodateId4, uodateId5 := int64(0), int64(0), int64(0), int64(0), int64(0), int64(0)
- nowTime := time.Now().Format("2006-01-02 15:04:05")
- nowTimes := time.Unix(time.Now().Unix()+3600*12, 0).Format("2006-01-02 15:04:05")
- if TiDb.ExecTx("保存线索", func(tx *sql.Tx) bool {
- clueId = TiDb.InsertByTx(tx, "dwd_f_crm_clue_info", map[string]interface{}{
- "userid": userId,
- "uid": uId,
- "seatNumber": seatNumber,
- "position_id": positionId,
- "is_assign": common.If(positionId > 0, 1, 0),
- "comeintime": nowTime,
- "createtime": nowTime,
- "updatetime": nowTime,
- "cluename": cluename,
- "top_cluetype": top_cluetype,
- "sub_cluetype": sub_cluetype,
- "trailstatus": "01",
- "name": name,
- "phone": phone,
- "position": position,
- "department": common.If(sourceCode == "app_xzcyh", departments, department),
- "industry": industry,
- "follow_project_area": follow_project_area,
- "role": role,
- "comeinsource_private": 2,
- "is_task": 1,
- "task_time": nowTime,
- "tasktime": common.If(item == "users", nowTimes, nowTime),
- "taskstatus": 0,
- "tasksource": "线索自动分配" + "-" + topname + "-" + subname,
- "business_scope": common.If(sourceCode == "app_xzcyh", keywords, nil),
- "company_nature": isGroup,
- "company_verification": isCommerce,
- "remark": remark,
- "customer_demand": demand,
- "FREEZE_TIME": nowTime,
- "label": 1,
- "labelChangeTime": time.Now().Format("2006-01-02"),
- })
- uodateId1 = TiDb.InsertByTx(tx, "dwd_f_crm_clue_change_record", map[string]interface{}{
- "clue_id": clueId,
- "position_id": positionId,
- "change_type": "创建线索",
- "new_value": "系统自动创建",
- "createtime": nowTime,
- "BCPCID": common.GetRandom(32),
- "operator_id": -1,
- })
- uodateId2 = TiDb.InsertByTx(tx, "dwd_f_crm_clue_change_record", map[string]interface{}{
- "clue_id": clueId,
- "position_id": positionId,
- "change_field": "position_id",
- "change_type": "所属人变更",
- "old_value": "/",
- "new_value": saleName,
- "createtime": nowTime,
- "BCPCID": common.GetRandom(32),
- "operator_id": -1,
- })
- uodateId3 = TiDb.InsertByTx(tx, "dwd_f_crm_clue_change_record", map[string]interface{}{
- "clue_id": clueId,
- "position_id": positionId,
- "change_field": "trailstatus",
- "change_type": "基本信息变更",
- "old_value": "商机线索",
- "new_value": "新增",
- "createtime": nowTime,
- "BCPCID": common.GetRandom(32),
- "operator_id": -1,
- })
- uodateId5 = TiDb.InsertByTx(tx, "dwd_f_crm_clue_change_record", map[string]interface{}{
- "clue_id": clueId,
- "position_id": positionId,
- "change_field": "top_cluetype",
- "change_type": "基本信息变更",
- "old_value": "/",
- "new_value": topname,
- "createtime": nowTime,
- "BCPCID": common.GetRandom(32),
- "operator_id": -1,
- })
- uodateId5 = TiDb.InsertByTx(tx, "dwd_f_crm_clue_change_record", map[string]interface{}{
- "clue_id": clueId,
- "position_id": positionId,
- "change_field": "sub_cluetype", //222
- "change_type": "基本信息变更",
- "old_value": "/",
- "new_value": subname,
- "createtime": nowTime,
- "BCPCID": common.GetRandom(32),
- "operator_id": -1,
- })
- return clueId > -1 && uodateId1 > -1 && uodateId2 > -1 && uodateId3 > -1 && uodateId4 > -1 && uodateId5 > -1
- }) {
- log.Println("线索分配成功")
- if TiDb.Count("dwd_f_userbase_contacts", map[string]interface{}{"phone": phone}) == 0 {
- TiDb.Insert("dwd_f_userbase_contacts", map[string]interface{}{
- "status": 1,
- "is_delete": 1,
- "createtime": nowTime,
- "updatetime": nowTime,
- "phone": phone,
- "baseinfo_id": uId,
- "SOURCE": source,
- })
- }
- return true
- }
- return false
- }
- type OrderInfo struct {
- Id int64
- UserId string
- CompanyName string
- ProductType string
- OrderCode string
- PayMoney float64
- ReturnMoney float64
- UserPhone string
- StartEnd string
- DisKcName string
- UserName string
- SeriveList []string
- SaleName string
- }
- // 客成发送邮箱
- func KcSend(orderCode, personName string) {
- log.Println("客成发邮件", orderCode)
- orderInfo := KcOrderFormat(orderCode)
- if orderInfo != nil {
- tableAppend := ""
- if len(orderInfo.SeriveList) > 0 {
- tableAppend = fmt.Sprintf(db.KeCheng.Mail.ServiceList, strings.Join(orderInfo.SeriveList, ","))
- }
- if orderInfo.ReturnMoney > 0 {
- tableAppend += fmt.Sprintf(db.KeCheng.Mail.ReturnMoney, orderInfo.ReturnMoney)
- }
- table := ""
- orderInfo.DisKcName = personName
- 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)
- 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`)
- 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)
- adminMailStr := ""
- if adminData != nil && len(*adminData) > 0 {
- adminMailStr = gconv.String((*adminData)[0]["mail"])
- }
- //发送邮件
- if personName == "" {
- if adminData != nil && len(*adminData) > 0 {
- //发送给管理员
- if adminMailStr != "" {
- gmail := &mail.GmailAuth{
- SmtpHost: db.Mail.SmtpHost,
- SmtpPort: db.Mail.SmtpPort,
- User: db.Mail.User,
- Pwd: db.Mail.Pwd,
- }
- status := mail.GSendMail_q("剑鱼标讯", adminMailStr, "", "", db.KeCheng.Title, fmt.Sprintf(db.KeCheng.Mail.Content, table), "", "", gmail)
- if status {
- log.Println("客成发邮件 send mail success", table, adminMailStr)
- }
- }
- }
- return
- }
- //当事人 管理员发送
- if deptData != nil && len(*deptData) > 0 {
- mailStr := gconv.String((*deptData)[0]["mail"])
- if mailStr != "" || adminMailStr != "" {
- if mailStr == adminMailStr {
- adminMailStr = ""
- }
- gmail := &mail.GmailAuth{
- SmtpHost: db.Mail.SmtpHost,
- SmtpPort: db.Mail.SmtpPort,
- User: db.Mail.User,
- Pwd: db.Mail.Pwd,
- }
- status := true
- if mailStr == "" {
- status = mail.GSendMail_q("剑鱼标讯", adminMailStr, "", "", db.KeCheng.Title, fmt.Sprintf(db.KeCheng.Mail.Content, table), "", "", gmail)
- } else {
- status = mail.GSendMail_q("剑鱼标讯", mailStr, adminMailStr, "", db.KeCheng.Title, fmt.Sprintf(db.KeCheng.Mail.Content, table), "", "", gmail)
- }
- if status {
- log.Println("客成发邮件 send mail success", table, mailStr, adminMailStr)
- }
- }
- }
- }
- }
- func ExitKcSend(personName string, infoList []map[string]interface{}) {
- //退出客成 即将退出客成信息
- 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)
- 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`)
- if personName == "" {
- //没有客成人员
- adminMailStr := ""
- if adminData != nil && len(*adminData) > 0 {
- adminMailStr = gconv.String((*adminData)[0]["mail"])
- }
- if adminMailStr != "" {
- gmail := &mail.GmailAuth{
- SmtpHost: db.Mail.SmtpHost,
- SmtpPort: db.Mail.SmtpPort,
- User: db.Mail.User,
- Pwd: db.Mail.Pwd,
- }
- //正文拼接
- 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>`
- for i, v := range infoList {
- 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"]))
- }
- endStr := `</tbody></table><p></body></html>`
- startStr += endStr
- status := mail.GSendMail_q("剑鱼标讯", adminMailStr, "", "", "客户退出客成系统通知", startStr, "", "", gmail)
- if status {
- log.Println("客成发邮件 send mail success", startStr, adminMailStr)
- }
- }
- return
- }
- if deptData != nil && len(*deptData) > 0 {
- mailStr := gconv.String((*deptData)[0]["mail"])
- adminMailStr := ""
- if adminData != nil && len(*adminData) > 0 {
- adminMailStr = gconv.String((*adminData)[0]["mail"])
- }
- if mailStr != "" || adminMailStr != "" {
- if mailStr == adminMailStr {
- adminMailStr = ""
- }
- gmail := &mail.GmailAuth{
- SmtpHost: db.Mail.SmtpHost,
- SmtpPort: db.Mail.SmtpPort,
- User: db.Mail.User,
- Pwd: db.Mail.Pwd,
- }
- //正文拼接
- 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>`
- for i, v := range infoList {
- 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"]))
- }
- endStr := `</tbody></table><p></body></html>`
- startStr += endStr
- status := true
- if mailStr == "" {
- status = mail.GSendMail_q("剑鱼标讯", adminMailStr, "", "", "客户退出客成系统通知", startStr, "", "", gmail)
- } else {
- status = mail.GSendMail_q("剑鱼标讯", mailStr, adminMailStr, "", "客户退出客成系统通知", startStr, "", "", gmail)
- }
- if status {
- log.Println("客成发邮件 send mail success", startStr, mailStr)
- }
- }
- }
- }
- // 客成邮件 订单信息初始化
- func KcOrderFormat(orderCode string) *OrderInfo {
- productArr, _ := KcProduct()
- bigmemberService := map[int64]string{}
- Mysql.SelectByBath(1, func(l *[]map[string]interface{}) bool {
- bigmemberService[common.Int64All((*l)[0]["id"])] = gconv.String((*l)[0]["s_name"])
- return true
- }, `select id,s_name from jianyu.bigmember_service`)
- orderData := Mysql.SelectBySql(fmt.Sprintf(`
- SELECT
- d.*,
- SUM( c.return_money ) AS return_money
- FROM
- (
- SELECT
- a.order_code,
- a.pay_money,
- a.user_phone,
- b.service_starttime,
- b.service_endtime,
- b.product_type,
- a.filter,
- a.user_id,
- a.ent_id,
- a.company_name,
- a.create_person,
- b.filter AS productFilter,
- TIMESTAMPDIFF( DAY, b.service_starttime, b.service_endtime ) AS difference
- FROM
- jianyu.dataexport_order a
- INNER JOIN jy_order_detail b ON a.order_code = "%s"
- AND a.order_code = b.order_code
- AND a.order_status = 1
- AND b.product_type IN ( %s )
- ORDER BY
- difference DESC LIMIT 1
- ) d
- LEFT JOIN return_money_record c ON d.order_code = c.order_code
- `, orderCode, strings.Join(productArr, ",")))
- data := &OrderInfo{}
- if orderData != nil && len(*orderData) > 0 {
- orderData := (*orderData)[0]
- id := common.Int64All(orderData["id"])
- user_phone := gconv.String(orderData["user_phone"])
- user_id := gconv.String(orderData["user_id"])
- product_type := gconv.String(orderData["product_type"])
- serviceList := []string{}
- if product_type == "大会员" {
- product_type_name, _, level := GetOrderProduct(product_type, gconv.String(orderData["productFilter"]))
- product_type = product_type_name
- if level == 0 {
- for _, serversId := range strings.Split(gconv.String(gconv.Map(orderData["serversId"])), ",") {
- if serviceName := bigmemberService[common.Int64All(serversId)]; serviceName != "" {
- serviceList = append(serviceList, serviceName)
- }
- }
- }
- }
- //联系人姓名
- sqlStr := `SELECT
- a.phone,
- b.NAME AS bname
- FROM
- dwd_f_userbase_contacts a
- INNER JOIN dwd_f_crm_clue_info b ON ( a.phone = ? AND a.baseinfo_id = b.uid )
- LEFT JOIN dwd_f_csm_customer_info c ON ( b.id = c.clue_id)`
- userName := ""
- if user_phone != "" {
- userData := TiDb.SelectBySql(sqlStr, user_phone)
- if userData != nil && len(*userData) > 0 {
- userName = gconv.String((*userData)[0]["bname"])
- }
- }
- data = &OrderInfo{
- Id: id,
- CompanyName: gconv.String(orderData["company_name"]),
- UserId: user_id,
- ProductType: product_type,
- OrderCode: orderCode,
- PayMoney: common.Float64All(orderData["pay_money"]) / 100,
- ReturnMoney: common.Float64All(orderData["return_money"]) / 100,
- UserPhone: user_phone,
- StartEnd: fmt.Sprintf("%s--%s", strings.Split(gconv.String(orderData["service_starttime"]), " ")[0], strings.Split(gconv.String(orderData["service_endtime"]), " ")[0]),
- SeriveList: serviceList,
- SaleName: gconv.String(orderData["create_person"]),
- UserName: userName,
- }
- }
- return data
- }
- func SaleMail(positionId int64) string {
- person, admin, seniorAdmin := FindDeptAdmin(positionId)
- personMail := ""
- adminMail := ""
- seniorAdminMail := ""
- if person != nil {
- personMail, _ = GetMail(gconv.String(person["name"]))
- }
- if admin != nil {
- adminMail, _ = GetMail(gconv.String(admin["name"]))
- }
- if seniorAdmin != nil {
- seniorAdminMail, _ = GetMail(gconv.String(seniorAdmin["name"]))
- }
- to, cc := "", ""
- if personMail != "" {
- to = personMail
- if adminMail != "" && seniorAdminMail != "" {
- if to != adminMail {
- if to != seniorAdminMail {
- cc = fmt.Sprintf("%s,%s", adminMail, seniorAdminMail)
- }
- } else {
- if to != seniorAdminMail {
- cc = seniorAdminMail
- }
- }
- } else if seniorAdminMail != "" && to != seniorAdminMail {
- cc = seniorAdminMail
- }
- } else {
- if adminMail != "" {
- to = adminMail
- if seniorAdminMail != "" && to != seniorAdminMail {
- cc = seniorAdminMail
- }
- } else {
- to = seniorAdminMail
- }
- }
- if to != "" && cc != "" {
- to = fmt.Sprintf("%s|%s", to, cc)
- }
- return to
- }
- func FindPersonOne(positionId int64) map[string]interface{} {
- personData := TiDb.SelectBySql(`SELECT
- b.name,
- b.position_id,
- b.seat_number,
- b.role_id,
- a.dept_name
- FROM
- dwd_d_crm_department_level_succbi a
- INNER JOIN dwd_f_crm_personnel_management b ON a.position_id = ?
- AND a.position_id = b.position_id`, positionId)
- if personData == nil || len(*personData) == 0 {
- return nil
- }
- return (*personData)[0]
- }
- // 进客成商品查询
- func KcProduct() ([]string, map[string]bool) {
- var strArr []string
- strMap := map[string]bool{}
- productData := Mysql.SelectBySql(`SELECT id ,
- CONCAT( '"', class_name,'"' ) as product
- FROM
- jy_product_class
- WHERE
- s_service = 1`)
- if productData == nil && len(*productData) == 0 {
- return strArr, strMap
- }
- for _, m := range *productData {
- strMap[gconv.String(m["product"])] = true
- strArr = append(strArr, gconv.String(m["product"]))
- }
- return strArr, strMap
- }
- func GetOrderProduct(productType string, file string) (string, int64, int64) {
- fileJson := gconv.Map(file)
- if fileJson == nil || len(fileJson) == 0 {
- return "", 0, 0
- }
- productName := ""
- level := int64(0)
- switch productType {
- case "大会员":
- level = gconv.Int64(fileJson["comboId"])
- if level == 0 {
- level = gconv.Int64(fileJson["level"])
- }
- switch level {
- case 0:
- productName = "大会员自定义"
- case 30190:
- productName = "大会员商机版2.0(单省版)"
- case 6:
- productName = "大会员商机版2.0"
- case 7:
- productName = "大会员专家版2.0"
- }
- default:
- productName = productType
- }
- productData := TiDb.FindOne("dwd_d_csm_product_access_code", map[string]interface{}{
- "name": productName,
- }, "", "")
- if productData == nil || len(*productData) == 0 {
- return productName, 0, level
- }
- return productName, gconv.Int64((*productData)["code"]), level
- }
- func GetTimeDifference(timeStr1, timeStr2 string) int {
- // 解析时间字符串
- t1, err1 := time.Parse(time.DateTime, timeStr1)
- t2, err2 := time.Parse(time.DateTime, timeStr2)
- if err1 != nil || err2 != nil {
- fmt.Println("时间格式错误:", err1, err2)
- return 0
- }
- // 计算时间差
- daysDiff := gconv.Int(t2.Sub(t1).Hours() / 24)
- fmt.Printf("两个时间相差 %.0f 天\n", daysDiff)
- return daysDiff
- }
- func getOrderData(sql string) (map[string]map[string]interface{}, string) {
- data := Mysql.SelectBySql(sql)
- orderMap := map[string]map[string]interface{}{}
- lastEndTime := ""
- for _, v := range *data {
- orderCode := gconv.String(v["order_code"])
- product_type := gconv.String(v["productType"])
- vip_starttime := gconv.String(v["service_starttime"])
- vip_endtime := gconv.String(v["service_endtime"])
- //判断一下服务周期
- difference := GetTimeDifference(vip_starttime, vip_endtime)
- _, productInt64, _ := GetOrderProduct(product_type, gconv.String(v["productFilter"]))
- if productInt64 == 0 {
- continue
- }
- if _, exists := orderMap[orderCode]; exists {
- //判断服务周期
- data := orderMap[orderCode]
- //商品类型获取
- oldDifference := gconv.Int(data["difference"])
- if oldDifference >= difference {
- //需要更换
- lastEndTime = vip_endtime
- v["difference"] = difference
- v["product"] = productInt64
- v["service_endtime"] = vip_endtime
- v["service_starttime"] = vip_starttime
- v["product_type"] = product_type
- orderMap[orderCode] = v
- }
- } else {
- lastEndTime = vip_endtime
- v["difference"] = difference
- v["product"] = productInt64
- v["product_type"] = product_type
- orderMap[orderCode] = v
- }
- }
- return orderMap, lastEndTime
- }
|