123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361 |
- 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
- b.update_time asc ,
- 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", "140500841645")
- 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"]))
- productInt64 = 2
- 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(orderMap[orderCode])
- 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"])
- productName := gconv.String(data["product_type"])
- 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.Int64All(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)
- cluename = gconv.String(data["company_name"])
- if cluename == "" {
- cluename = phone
- }
- 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"
- }
- 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 {
- AddClueChange(clueId, gconv.Int64(common.If(position_id > 0, position_id, -1)), "", "创建线索", "", "系统自动创建", nowTime, common.GetRandom(32), "", "")
- clueData = TiDb.FindOne("dwd_f_crm_clue_info", map[string]interface{}{"uid": uId}, "", "")
- if clueData == nil || len(*clueData) == 0 {
- return 0
- }
- } else {
- return 0
- }
- }
- isTransfer := gconv.Int64((*clueData)["is_transfer"])
- //cluename = gconv.String((*clueData)["cluename"])
- clueId = common.Int64All((*clueData)["id"])
- starttime := gconv.String(data["service_starttime"])
- endtime := gconv.String(data["service_endtime"])
- //product_type := gconv.String(data["product_type"])
- product, company_name := gconv.Int64(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,
- "account_type": 1,
- "company_name": company_name,
- }
- k := KcTransferRequest{
- KcEntId: entId,
- HostUID: uId,
- HostClueId: clueId,
- KcBuySubject: buy_subject,
- KcCompanyName: company_name,
- KcStartTime: starttime,
- KcEndTime: endtime,
- NowTime: nowTime,
- KcProduct: product,
- KcProductName: productName,
- HostClueName: cluename,
- }
- if TiDb.Count("dwd_f_csm_customer_info", map[string]interface{}{"clue_id": clueId}) > 0 {
- customData := TiDb.FindOne("dwd_f_csm_customer_info", map[string]interface{}{"clue_id": clueId}, "", "")
- if customData != nil && len(*customData) > 0 {
- isUpdate := true
- // 获取客户数据
- customId := gconv.Int64((*customData)["id"])
- // 自动分配客户给销售或部门
- customerPositionId, customerName := cAutoDraw(gconv.Int(entId), orderPositionId, salesperson, saleDep, customData, company_name)
- log.Println("移交客户positionId", customerPositionId, customerName, saleDep, orderPositionId, salesperson, true)
- // 创建客户转移请求结构体
- k.KcID = customId
- k.KcName = customerName
- k.KcPositionId = customerPositionId
- if isTransfer == 0 {
- // 非转移客户,直接更新账号信息
- isUpdate = false
- k.KcAccountNumberUpdate(customData, clueData, orderCode, false, isUpdate, isTransfer)
- } else {
- // 转移客户处理
- if clueData == nil || len(*clueData) == 0 {
- // 之前没有线索的情况(理论上不应出现)
- } else {
- // 检查原线索名称是否是手机号
- if ValidatePhone(cluename) {
- // 原线索是手机号
- if gconv.Int64(entId) > 0 {
- // 新客户是企业,需要将线索名称替换为企业名称
- isUpdate = true
- k.KcAccountNumberUpdate(customData, clueData, orderCode, false, isUpdate, isTransfer)
- } else {
- // 新客户是个人,保持原样
- isUpdate = false
- k.KcAccountNumberUpdate(customData, clueData, orderCode, false, isUpdate, isTransfer)
- }
- }
- }
- }
- }
- } else {
- customerPositionId, customerName := cAutoDraw(gconv.Int(entId), orderPositionId, salesperson, saleDep, nil, company_name)
- log.Println("移交客成positionId", customerPositionId, customerName, saleDep, orderPositionId, salesperson, false)
- customId := TiDb.Insert("dwd_f_csm_customer_info", saveMap)
- if customId > 0 {
- k.KcID = customId
- k.KcName = customerName
- k.KcPositionId = customerPositionId
- k.KcAccountNumberUpdate(&saveMap, clueData, orderCode, true, false, isTransfer)
- }
- }
- return status
- }
- // 客成人员查询
- func cAutoDraw(entId int, orderPositionId int64, salesperson, saleDep string, customData *map[string]interface{}, company_name string) (positionId int64, name string) {
- if customData != nil {
- //查看一下之前有没有人
- positionId = common.Int64All((*customData)["position_id"])
- if positionId != 0 {
- name = gconv.String((*customData)["name"])
- return
- }
- }
- 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
- }
- //个人的话随机分
- if entId == 0 {
- positionId, name = getKCperson(data)
- return
- }
- //看其他公司上边有没有客成人员 有的话新分给这个人
- customerData := TiDb.Find("dwd_f_csm_customer_info", map[string]interface{}{"company_name": company_name}, "", "", -1, -1)
- if customerData != nil && len(*customerData) > 0 {
- for _, v := range *customerData {
- positionid := common.Int64All(v["position_id"])
- if positionid != 0 {
- name = gconv.String(v["name"])
- return
- }
- }
- }
- //没有的话看下业绩归属
- if saleDep == "客户成功部" {
- positionId = orderPositionId
- name = salesperson
- return
- }
- //随机分配
- positionId, name = getKCperson(data)
- return
- }
- // 获取客成里边最少的一个人
- func getKCperson(data *[]map[string]interface{}) (positionId int64, name string) {
- if data != nil && len(*data) > 0 {
- sql := `select a.name,a.count,b.position_id 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 *countData {
- //判断是否有新员工
- isOk := false
- for _, vv := range *data {
- 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{}{
- "name": name,
- }, "", "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"])
- positionId = gconv.Int64(v["position_id"])
- } else {
- if common.Int64All(v["count"]) <= res {
- res = common.Int64All(v["count"])
- name = gconv.String(v["name"])
- positionId = gconv.Int64(v["position_id"])
- }
- }
- countres++
- }
- }
- }
- 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"
- //新增任务车
- AddClueChange(clueId, positionId, "", "加入任务车", "", "未盘点", nowTime, common.GetRandom(32), "", "")
- } else if inventory_way != 1 && training_way == 1 {
- tasksources = "3"
- //新增任务车
- AddClueChange(clueId, positionId, "", "加入任务车", "", "未培训", nowTime, common.GetRandom(32), "", "")
- }
- 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() {
- log.Println("后台订单线索定时任务开始")
- 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,a.personPhone,a.personName,a.ent_id 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)
- //sql := "select a.*,b.product_type as productType ,b.service_starttime,b.service_endtime,b.filter AS productFilter,b.update_time,a.personPhone,a.personName,a.ent_id from dataexport_order a INNER JOIN jy_order_detail b on a.order_code=b.order_code where a.order_code = '115223989825'"
- data := Mysql.SelectBySql(sql)
- log.Println("后台订单线索定时任务", len(*data))
- if data != nil && *data != nil && len(*data) > 0 {
- for _, v := range *data {
- user_id := gconv.String(v["user_id"])
- 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"])
- personPhone := gconv.String(v["personPhone"]) //联系人手机号
- personName := gconv.String(v["personName"])
- entId := gconv.Int64(v["ent_id"])
- addUser := []map[string]string{}
- if user_id == "" {
- userData := Base.SelectBySql("SELECT b.id FROM base_user a LEFT JOIN base_position b ON a.id= b.user_id WHERE a.phone = ? AND b.ent_id = ?", userPhone, entId)
- if userData == nil || len(*userData) == 0 {
- log.Printf("未查询用户positionId,订单编号:%s,手机号:%s", orderCode, userPhone)
- continue
- }
- user_id = gconv.String((*userData)[0]["id"])
- }
- if userPhone == personPhone {
- addUser = append(addUser, map[string]string{"phone": userPhone, "name": userPhone, "type": "采购人", "user_id": user_id})
- } else {
- //查询联系人user_id
- personPositionId := int64(0)
- ssql := fmt.Sprintf("SELECT b.id FROM base_user a LEFT JOIN base_position b ON a.id= b.user_id WHERE a.phone = '%s' AND b.ent_id = %d", personPhone, entId)
- log.Println("查询订单联系人职位id sql", ssql)
- personData := Base.SelectBySql(ssql)
- if personData != nil && len(*personData) > 0 {
- personPositionId = gconv.Int64((*personData)[0]["id"])
- addUser = append(addUser, map[string]string{"phone": personPhone, "name": personName, "type": "采购人", "user_id": gconv.String(personPositionId)})
- }
- addUser = append(addUser, map[string]string{"phone": userPhone, "name": userPhone, "type": "使用人", "user_id": user_id})
- }
- //撞单
- log.Println("销售部订单", saleDep)
- if strings.Contains(salesperson, ",") {
- log.Println("销售部撞单 ", salesperson)
- if salesperson == "" {
- salesperson = createperson
- }
- }
- log.Println("销售部订单salesperson", salesperson)
- seatNumber, positionId := "", int64(0)
- 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"])
- }
- for _, vv := range addUser {
- userId, uId, cluename, trailstatus, clueId, phone := gconv.String(vv["user_id"]), "", "", "", int64(0), ""
- if saleDep != "" {
- //销售部
- phone = vv["phone"]
- query := map[string]interface{}{}
- source := ""
- if !mongodb.IsObjectIdHex(userId) {
- userMapping := TiDb.FindOne("data_service.user_system", map[string]interface{}{"position_id": userId}, "", "")
- if userMapping != nil && len(*userMapping) > 0 {
- userId = gconv.String((*userMapping)["userid"])
- } else {
- log.Println("后台订单--未查询到 ", phone)
- 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, phone)
- break
- }
- is_assign := 1
- mailContent := ""
- cluename = gconv.String(v["company_name"])
- mailContent = fmt.Sprintf("%s(%s)", cluename, phone)
- if cluename == "" {
- cluename = phone
- mailContent = phone
- }
- if payMoney > 0 {
- trailstatus = "08"
- } else {
- trailstatus = "01"
- }
- isGroup, isCommerce := GetCompanyType(cluename, uId) //判断是否集团公司、工商库
- if IsFreeze(source, payMoney, gconv.String(positionId), trailstatus) {
- //线索需要冻结
- is_assign = -3
- }
- 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 == "销售部" {
- 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": phone,
- "phone": phone,
- "comeinsource_private": 2,
- "is_task": 0,
- "taskstatus": 0,
- "company_nature": isGroup,
- "company_verification": isCommerce,
- "FREEZE_TIME": nowTime,
- "contact_type": vv["type"],
- })
- } 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": phone,
- "phone": phone,
- "is_task": 0,
- "taskstatus": 0,
- "company_nature": isGroup,
- "company_verification": isCommerce,
- "FREEZE_TIME": nowTime,
- "contact_type": vv["type"],
- })
- }
- if clueId > 0 {
- AddClueChange(clueId, gconv.Int64(common.If(positionId > 0, positionId, -1)), "", "创建线索", "", "系统自动创建", nowTime, common.GetRandom(32), "", "")
- if is_assign == -3 {
- //新增冻结记录
- AddClueChange(clueId, positionId, "", "线索冻结", "", "销售人员私海已达上限", nowTime, common.GetRandom(32), "", "")
- //移交失败发送消息
- 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 {
- mainUserPower, _ := GetPersonIdentityPower(uid, common.IntAll(v["account_type"]), common.Int64All(v["ent_id"]), "")
- if mainUserPower == nil { //移出客成
- //全退款了
- 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)
- //新增变更记录
- AddClueChange(clueId, gconv.Int64(common.If(kcposition_id > 0, kcposition_id, -1)), "", "退回公海", "", "成交客户申请退款", nowTime, common.GetRandom(32), "", "")
- //新增变更记录
- AddClueChange(clueId, gconv.Int64(common.If(kcposition_id > 0, kcposition_id, -1)), "trailstatus", "基本信息变更", "成交客户", "商机线索", nowTime, common.GetRandom(32), "", "")
- //新增变更记录
- AddClueChange(clueId, gconv.Int64(common.If(kcposition_id > 0, kcposition_id, -1)), "position_id", "客户成功经理", name, "/", nowTime, common.GetRandom(32), "", "")
- //新增变更记录y
- AddClueChange(clueId, gconv.Int64(common.If(kcposition_id > 0, kcposition_id, -1)), "", "移交销售", "", "成交客户申请退款", nowTime, common.GetRandom(32), "", "")
- TiDb.UpdateOrDeleteBySql(`UPDATE dwd_f_csm_customer_info SET is_transfer=1,account_type = NULL WHERE clue_id = ?`, clueId)
- } else { //主账号在其他身份下存在子账号或移交客成的免费账号
- entId := common.Int64All(mainUserPower["entId"])
- mainCusData := common.ObjToMap(mainUserPower["customer"])
- mainCompanyName := common.InterfaceToStr((*mainCusData)["company_name"])
- isGroup, isCommerce := GetCompanyTypeByClueId(mainCompanyName, common.Int64All((*mainCusData)["clue_id"]))
- SubAndFreeAccountUpdate(*mainCusData, entId, clueId, common.IntAll(mainUserPower["newAccountType"]), isGroup, isCommerce, common.InterfaceToStr(v["name"]))
- }
- //处理子账号及免费账号
- SubAndFreeAccountToDx(gconv.Int64(v["id"]), 2)
- mailData[name] = append(mailData[name], map[string]interface{}{
- "company_name": company_name,
- "phone": phone,
- "userName": userName,
- "remrk": "已移交",
- "reason": "成交客户申请退款",
- })
- } 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)
- //查询主账号下是否存在其他身份的会员权益 755非集团公司
- mainUserPower, _ := GetPersonIdentityPower(uid, common.IntAll(v["account_type"]), common.Int64All(v["ent_id"]), "")
- if mainUserPower == nil { //err == nil || err !=nil 移交电销
- 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 {
- //新增个人员变更
- //新增变更记录
- AddClueChange(clueId, saleId, "position_id", "所属人变更", gconv.String(common.If(oldsaleName != "", oldsaleName, "/")), gconv.String(common.If(newPerson != "", newPerson, "/")), nowTime, common.GetRandom(32), "", "")
- 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 {
- //新增变更记录
- AddClueChange(clueId, saleId, "position_id", "所属人变更", gconv.String(common.If(oldsaleName != "", oldsaleName, "/")), gconv.String(common.If(newPerson != "", newPerson, "/")), nowTime, common.GetRandom(32), "", "")
- }
- }
- //新增变更记录
- AddClueChange(clueId, gconv.Int64(common.If(kcposition_id > 0, kcposition_id, -1)), "trailstatus", "基本信息变更", "成交客户", "商机线索", nowTime, common.GetRandom(32), "", "")
- if saleId > 0 {
- //新增任务车
- AddClueChange(clueId, saleId, "", "加入任务车", "", "线索自动分配-其他-成交客户续约失败", nowTime, common.GetRandom(32), "", "")
- }
- AddClueChange(clueId, gconv.Int64(common.If(kcposition_id > 0, kcposition_id, -1)), "position_id", "客户成功经理", name, "/", nowTime, common.GetRandom(32), "", "")
- AddClueChange(clueId, saleId, "", "移交销售", "", "成交客户续费失败,到期自动移交", nowTime, common.GetRandom(32), "", "")
- TiDb.UpdateOrDeleteBySql(`UPDATE dwd_f_csm_customer_info SET is_transfer=1 WHERE clue_id = ?`, clueId)
- if isFull {
- //新增冻结记录
- AddClueChange(clueId, saleId, "", "线索冻结", "", "销售人员私海已达上限", nowTime, common.GetRandom(32), "", "")
- //发送邮件
- 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)
- }
- } else { //主账号在其他身份下有会员权益, 更新客成企业信息、更新线索名称
- entId := common.Int64All(mainUserPower["entId"])
- mainCusData := common.ObjToMap(mainUserPower["customer"])
- //cusId := common.Int64All((*mainCusData)["id"])
- mainCompanyName := common.InterfaceToStr((*mainCusData)["company_name"])
- isGroup, isCommerce := GetCompanyTypeByClueId(mainCompanyName, common.Int64All((*mainCusData)["clue_id"]))
- SubAndFreeAccountUpdate(*mainCusData, entId, clueId, common.IntAll(mainUserPower["newAccountType"]), isGroup, isCommerce, common.InterfaceToStr(v["name"]))
- }
- //处理子账号、免费账号
- SubAndFreeAccountToDx(common.Int64All(v["id"]), 1)
- }
- }
- }
- }
- return true
- }, `select id,ent_id,clue_id,position_id,name,is_renewal_protection,company_name,account_type from dwd_f_csm_customer_info where is_transfer = 0 and account_type = 1`)
- //}, `select id,ent_id,clue_id,position_id,name,is_renewal_protection,company_name,account_type from dwd_f_csm_customer_info where clue_id =1893222`)
- //移交电销提醒
- 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 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, updateId1, updateId2, updateId3, updateId4, updateId5 := 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"),
- })
- updateId1 = AddClueChange(clueId, positionId, "", "创建线索", "", "系统自动创建", nowTime, common.GetRandom(32), "", "")
- updateId2 = AddClueChange(clueId, positionId, "position_id", "所属人变更", "", saleName, nowTime, common.GetRandom(32), "", "")
- updateId3 = AddClueChange(clueId, positionId, "trailstatus", "基本信息变更", "商机线索", "新增", nowTime, common.GetRandom(32), "", "")
- updateId4 = AddClueChange(clueId, positionId, "top_cluetype", "基本信息变更", "/", topname, nowTime, common.GetRandom(32), "", "")
- updateId5 = AddClueChange(clueId, positionId, "sub_cluetype", "基本信息变更", "/", subname, nowTime, common.GetRandom(32), "", "")
- return clueId > -1 && updateId1 > -1 && updateId2 > -1 && updateId3 > -1 && updateId4 > -1 && updateId5 > -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 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
- }
- t1, _ := time.Parse(time.DateTime, lastEndTime)
- t2, _ := time.Parse(time.DateTime, vip_endtime)
- //判断服务周期
- if t2.Unix() > t1.Unix() {
- lastEndTime = vip_endtime
- }
- if _, exists := orderMap[orderCode]; exists {
- data := orderMap[orderCode]
- //商品类型获取
- oldDifference := gconv.Int(data["difference"])
- if difference >= oldDifference {
- //需要更换
- 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 {
- v["difference"] = difference
- v["product"] = productInt64
- v["product_type"] = product_type
- orderMap[orderCode] = v
- }
- }
- return orderMap, lastEndTime
- }
- type KcTransferRequest struct {
- //主账号信息
- HostClueName string
- HostClueId int64
- HostUID string // 用户唯一标识
- // 基础信息
- ClueType int64 // 线索类型(1:个人,2:企业,3:子账号等)
- UserList []interface{} // 用户列表(使用具体类型替代interface{})
- NowTime string
- SendUserMailMap map[string]map[string]interface{}
- LogPrefix string
- IsDelete bool
- //主账号下边人信息
- SecondaryAccountType int64
- SecondaryPersonUid string
- SecondaryUserName string
- SecondaryUserPhone string
- SecondaryClueId int64
- SecondaryClueName string
- //客成信息
- KcID int64 // 自定义业务ID
- KcBuySubject int64 // 购买主体
- KcName string // 新客成经理姓名
- KcOldName string //老客成经理姓名
- KcCompanyName string // 公司名称
- KcStartTime string
- KcEndTime string
- KcProduct int64
- KcProductName string
- KcEntId interface{}
- KcPositionId int64 // 职位ID
- }
- // OtherKcTransfer 处理客成移交逻辑
- func (k *KcTransferRequest) OtherKcTransfer() {
- // 初始化日志前缀
- k.LogPrefix = fmt.Sprintf("[客成移交] uid:%s, kcName:%s, company:%s", k.HostUID, k.KcName, k.KcCompanyName)
- if gconv.Int64(k.KcEntId) == 0 {
- k.handlePersonalAccount()
- } else {
- k.handleEnterpriseAccount()
- }
- if !isGroupCompany(k.KcCompanyName) {
- if gconv.Int64(k.KcEntId) > 0 && k.KcCompanyName != "" {
- k.handleOtherClues()
- }
- }
- //发邮件处理
- userMailList := []map[string]interface{}{}
- for _, v := range k.SendUserMailMap {
- userMailList = append(userMailList, v)
- }
- if len(userMailList) > 0 {
- data := map[int64][]map[string]interface{}{}
- data[k.KcPositionId] = userMailList
- log.Println("需要发送邮件的人")
- log.Println(data)
- //KcClueTransfer(data)
- }
- }
- // handlePersonalAccount 处理个人账号移交
- func (k *KcTransferRequest) handlePersonalAccount() {
- userData := TiDb.FindOne("data_service.user_system", map[string]interface{}{
- "status": 1,
- "uid": k.HostUID,
- }, "", "createtime DESC")
- if userData == nil || len(*userData) == 0 {
- log.Printf("%s - 查询不到用户信息\n", k.LogPrefix)
- return
- }
- mongoId := gconv.String((*userData)["userid"])
- childAccount, _ := Mgo.Find("user", map[string]interface{}{"s_member_mainid": mongoId, "i_member_sub_status": 1, "i_member_status": map[string]interface{}{"$gt": 0}}, "", `"_id":1`, false, -1, -1)
- if childAccount == nil || len(*childAccount) == 0 {
- log.Printf("%s - 子账号查询不到, mongoId:%s\n", k.LogPrefix, mongoId)
- return
- }
- log.Printf("%s - 找到子账号, 数量:%v\n", k.LogPrefix, len(*childAccount))
- childIds := make([]interface{}, 0, len(*childAccount))
- for _, v := range *childAccount {
- childIds = append(childIds, mongodb.BsonIdToSId(v["_id"]))
- }
- k.ClueType = 21
- k.UserList = childIds
- k.addKcClue()
- }
- // handleEnterpriseAccount
- func (k *KcTransferRequest) handleEnterpriseAccount() {
- log.Println("处理企业账号移交:", k.LogPrefix)
- entData := Mysql.Find("entniche_user", map[string]interface{}{"ent_id": k.KcEntId}, "", "", -1, -1)
- if entData == nil || len(*entData) == 0 {
- log.Printf("%s - 企业账号不存在, entId:%v\n", k.LogPrefix, k.KcEntId)
- return
- }
- entMap := make(map[int64]map[string]interface{})
- for _, v := range *entData {
- id := gconv.Int64(v["id"])
- entMap[id] = v
- }
- noPowerList := []interface{}{}
- powerList := k.classifyEnterpriseUsers(entMap)
- if len(powerList) > 0 {
- k.ClueType = 22
- k.UserList = powerList
- k.addKcClue()
- }
- if len(entMap) > 0 {
- for k := range entMap {
- noPowerList = append(noPowerList, k)
- }
- k.ClueType = 3
- k.UserList = noPowerList
- k.addKcClue()
- }
- }
- // classifyEnterpriseUsers 分类企业用户权限
- func (k *KcTransferRequest) classifyEnterpriseUsers(entMap map[int64]map[string]interface{}) []interface{} {
- log.Println("分类企业用户权限:", k.LogPrefix)
- powerList := make([]interface{}, 0)
- switch k.KcProductName {
- case "商机管理":
- sql := fmt.Sprintf(`SELECT b.* FROM entniche_info a
- INNER JOIN entniche_user b ON a.id=%v AND a.id = b.ent_id
- AND a.status = 1 AND a.enddate > UNIX_TIMESTAMP() AND b.power =1`, k.KcEntId)
- powerData := Mysql.SelectBySql(sql)
- if powerData != nil && len(*powerData) > 0 {
- for _, v := range *powerData {
- entUserId := gconv.Int64(v["id"])
- if _, exists := entMap[entUserId]; exists {
- powerList = append(powerList, entUserId)
- delete(entMap, entUserId)
- }
- }
- }
- case "大会员":
- powerData, _ := Mgo.Find("ent_user", map[string]interface{}{
- "i_member_status": map[string]interface{}{"$gt": 0},
- }, "", "", false, -1, -1)
- if powerData != nil && len(*powerData) > 0 {
- for _, v := range *powerData {
- entUserId := gconv.Int64(v["i_userid"])
- if _, exists := entMap[entUserId]; exists {
- powerList = append(powerList, entUserId)
- delete(entMap, entUserId)
- }
- }
- }
- }
- return powerList
- }
- // isGroupCompany 检查是否为集团公司
- func isGroupCompany(companyName string) bool {
- count := TiDb.CountBySql(`SELECT count(1) FROM group_company_name WHERE company_name=?`, companyName)
- return count > 0
- }
- // handleOtherClues 处理其他相关线索
- func (k *KcTransferRequest) handleOtherClues() {
- sql := fmt.Sprintf(`SELECT c.* FROM dwd_f_crm_clue_info c
- INNER JOIN data_service.user_system d ON c.cluename = "%s" AND c.is_transfer=0
- AND c.uid = d.uid AND d.STATUS = 1
- WHERE NOT EXISTS (
- SELECT 1 FROM data_service.user_system b
- WHERE b.uid = c.uid %s AND b.STATUS = 1
- )`, k.KcCompanyName, common.If(gconv.Int64(k.KcEntId) == 0, "", fmt.Sprintf(` AND b.ent_id = %v`, gconv.Int64(k.KcEntId))))
- otherData := TiDb.SelectBySql(sql)
- if otherData == nil || len(*otherData) == 0 {
- return
- }
- otherList := make([]interface{}, 0, len(*otherData))
- for _, v := range *otherData {
- otherList = append(otherList, gconv.Int64(v["id"]))
- }
- k.ClueType = 4
- k.UserList = otherList
- k.addKcClue()
- }
- // addKcClue 添加客成线索
- func (k *KcTransferRequest) addKcClue() {
- for _, userId := range k.UserList {
- uid, err := getUserIdByClueType(k.ClueType, userId, k.KcEntId)
- if err != nil {
- log.Printf("获取用户ID失败: %v, clueType:%d, userId:%v\n", err, k.ClueType, userId)
- continue
- }
- if uid == k.HostUID {
- continue
- }
- clueData, err := getClueData(k.ClueType, uid, userId)
- if err != nil {
- log.Printf("获取线索数据失败: %v\n", err)
- continue
- }
- k.SecondaryUserName = gconv.String((*clueData)["name"])
- k.SecondaryUserPhone = gconv.String((*clueData)["phone"])
- k.SecondaryClueId = gconv.Int64((*clueData)["id"])
- k.HostUID = gconv.String((*clueData)["uid"])
- k.SecondaryClueName = gconv.String((*clueData)["cluename"])
- // 处理客户数据
- k.handleCustomerData()
- }
- }
- // getUserIdByClueType 根据线索类型获取用户ID
- func getUserIdByClueType(clueType int64, userId interface{}, entId interface{}) (string, error) {
- switch clueType {
- case 21: // 子账号
- userData := TiDb.FindOne("data_service.user_system", map[string]interface{}{
- "uid": userId,
- "status": 1,
- "type": 0,
- }, "", "")
- if userData == nil || len(*userData) == 0 {
- return "", fmt.Errorf("个人用户不存在: %v", userId)
- }
- return gconv.String((*userData)["uid"]), nil
- case 3, 22: // 企业账号
- userData := TiDb.FindOne("data_service.user_system", map[string]interface{}{
- "ent_user_id": userId,
- "status": 1,
- "ent_id": entId,
- }, "", "")
- if userData == nil || len(*userData) == 0 {
- return "", fmt.Errorf("企业用户不存在: %v", userId)
- }
- return gconv.String((*userData)["uid"]), nil
- default:
- return "", nil
- }
- }
- // getClueData 获取线索数据
- func getClueData(clueType int64, uid string, userId interface{}) (*map[string]interface{}, error) {
- var query map[string]interface{}
- if clueType == 21 || clueType == 22 || clueType == 3 {
- query = map[string]interface{}{"uid": uid}
- } else {
- query = map[string]interface{}{"id": userId}
- }
- clueData := TiDb.FindOne("dwd_f_crm_clue_info", query, "", "")
- if clueData == nil || len(*clueData) == 0 {
- return nil, fmt.Errorf("线索不存在, clueType:%d, uid:%s, userId:%v", clueType, uid, userId)
- }
- return clueData, nil
- }
- func GetClueTypeName(clueType int64) (reason string) {
- switch clueType {
- case 21, 22:
- reason = "子账号移交"
- case 3:
- reason = "企业组织架构免费账户"
- case 4:
- reason = "非集团公司成交客户关联线索"
- }
- return
- }
- // handleCustomerData 处理客户数据
- func (k *KcTransferRequest) handleCustomerData() {
- customData := TiDb.FindOne("dwd_f_csm_customer_info", map[string]interface{}{"clue_id": k.SecondaryClueId}, "", "")
- var oldKcName string
- if customData == nil || len(*customData) == 0 {
- var accountType int64
- // 新增客户
- switch k.ClueType {
- case 21, 22, 2:
- accountType = 2
- case 3:
- accountType = 3
- case 4:
- accountType = 4
- }
- reason := GetClueTypeName(accountType)
- k.saveCustomerInfo(accountType)
- if k.SendUserMailMap == nil {
- k.SendUserMailMap = map[string]map[string]interface{}{}
- }
- k.SendUserMailMap[k.SecondaryPersonUid] = map[string]interface{}{
- "clueName": k.HostClueName,
- "userName": k.SecondaryUserPhone,
- "phone": k.SecondaryUserPhone,
- "reason": reason,
- }
- // 添加变更记录
- k.addChangeRecords(accountType)
- } else {
- // 更新客户信息
- oldKcName = gconv.String((*customData)["name"])
- oldClueType := gconv.Int64((*customData)["account_type"])
- k.KcOldName = oldKcName
- isTransfer := gconv.Int64((*customData)["is_transfer"])
- // 检查是否需要跳过更新
- isUpdate, newAccountType := shouldSkipUpdate(k.ClueType, isTransfer, oldClueType, k.IsDelete)
- if isUpdate {
- return
- }
- reason := GetClueTypeName(newAccountType)
- if k.SendUserMailMap == nil {
- k.SendUserMailMap = make(map[string]map[string]interface{}) // 如果 nil,则初始化
- }
- k.SendUserMailMap[k.SecondaryPersonUid] = map[string]interface{}{
- "clueName": k.HostClueName,
- "userName": k.SecondaryUserName,
- "phone": k.SecondaryUserPhone,
- "reason": reason,
- }
- k.updateCustomerInfo(newAccountType)
- // 添加变更记录
- k.addChangeRecords(newAccountType)
- }
- }
- // saveCustomerInfo 保存客户信息
- func (k *KcTransferRequest) saveCustomerInfo(accountType int64) {
- saveMap := map[string]interface{}{
- "clue_id": k.SecondaryClueId,
- "transfertime": k.NowTime,
- "service_starttime": k.KcStartTime,
- "service_endtime": k.KcEndTime,
- "ent_id": k.KcEntId,
- "is_task": 0,
- "tasktime": k.NowTime,
- "taskstatus": 0,
- "tasksource": "1",
- "is_admin": 0,
- "product_access": k.KcProduct,
- "buy_subject": k.KcBuySubject,
- "relationship_building_way": 1,
- "inventory_way": 1,
- "training_way": 1,
- "is_pre_sales_training": 0,
- "service_stage": 1,
- "company_name": k.KcCompanyName,
- "position_id": k.KcPositionId,
- "name": k.KcName,
- "is_transfer": 0,
- "account_type": accountType,
- "primary_id": k.KcID,
- }
- if id := TiDb.Insert("dwd_f_csm_customer_info", saveMap); id < 0 {
- log.Printf("保存客户信息失败: %v, clueId:%s\n")
- return
- }
- }
- // updateCustomerInfo 更新客户信息
- func (k *KcTransferRequest) updateCustomerInfo(newAccountType int64) {
- updateMap := map[string]interface{}{
- "is_transfer": 0,
- "is_renewal_protection": 0,
- "product_access": k.KcProduct,
- "buy_subject": k.KcBuySubject,
- "transfertime": k.NowTime,
- "service_starttime": k.KcStartTime,
- "service_endtime": k.KcEndTime,
- "ent_id": k.KcEntId,
- "company_name": k.KcCompanyName,
- "name": k.KcName,
- "position_id": k.KcPositionId,
- "primary_id": k.KcID,
- "account_type": newAccountType,
- "relationship_building_way": 1,
- "tasksource": 0,
- "inventory_way": 1,
- "training_way": 1,
- "is_pre_sales_training": 0,
- "service_stage": 1,
- "is_task": 0,
- }
- if ok := TiDb.Update("dwd_f_csm_customer_info", map[string]interface{}{"clue_id": k.SecondaryClueId}, updateMap); !ok {
- log.Printf("更新客户信息失败: %v, clueId:%s\n", k.SecondaryClueId)
- }
- }
- // shouldSkipUpdate 判断是否需要跳过更新
- func shouldSkipUpdate(clueType, isTransfer, oldClueType int64, IsDelete bool) (bool, int64) {
- newAccountType := int64(0)
- if isTransfer == 0 {
- //当前值 已经在客成了
- if IsDelete {
- return false, clueType
- } else {
- switch oldClueType {
- case 1, 2:
- return true, 0
- case 3:
- if clueType == 21 || clueType == 22 || clueType == 2 {
- return false, 2
- } else {
- return true, 0
- }
- case 4:
- if clueType == 21 || clueType == 22 || clueType == 2 {
- return false, 2
- } else if clueType == 3 {
- return false, 3
- }
- }
- }
- return true, 0
- } else {
- switch clueType {
- case 21, 22, 2:
- newAccountType = 2
- case 3:
- newAccountType = 3
- case 4:
- newAccountType = 4
- }
- return false, newAccountType
- }
- }
- // addChangeRecords 添加变更记录
- func (k *KcTransferRequest) addChangeRecords(accountType int64) {
- // 修改线索名称
- if k.SecondaryClueName != k.KcCompanyName {
- updateClueName(k.SecondaryClueId, k.KcCompanyName, k.NowTime, k.SecondaryPersonUid)
- addClueNameChangeRecord(k.ClueType, k.SecondaryClueId, k.KcCompanyName, k.KcCompanyName, k.KcPositionId, k.NowTime)
- }
- //线索移交客成变更
- //线索移交
- updateClueTransfer(k.SecondaryClueId, k.NowTime)
- // 添加移交记录
- description := ""
- switch accountType {
- case 2:
- description = "子账号"
- case 3:
- description = "企业下免费用户"
- case 4:
- description = "关联线索"
- }
- AddClueChange(k.SecondaryClueId, k.KcPositionId, "", "成交客户移交", "", "移交至客户成功组", k.NowTime, common.GetRandom(32), description, "")
- if k.KcOldName != k.KcName {
- // 添加客户成功经理变更记录
- AddClueChange(k.SecondaryClueId, k.KcPositionId, "position_id", "客户成功经理", gconv.String(common.If(k.KcOldName == "", "/", k.KcOldName)), k.KcName, k.NowTime, common.GetRandom(32), "", "")
- }
- }
- // updateClueName 更新线索名称
- func updateClueName(clueId int64, companyName, nowTime, uid string) {
- isGroup, isCommerce := GetCompanyType(companyName, uid)
- //线索名称、移交状态、
- TiDb.Update("dwd_f_crm_clue_info", map[string]interface{}{"id": clueId}, map[string]interface{}{
- "cluename": companyName,
- "updatetime": nowTime,
- "company_nature": isGroup,
- "company_verification": isCommerce,
- })
- }
- // addClueNameChangeRecord 添加线索名称变更记录
- func addClueNameChangeRecord(clueType, clueId int64, oldName, newName string, kcPositionId int64, nowTime string) {
- description := ""
- switch clueType {
- case 21, 22:
- description = "与订单公司名称保持一致"
- case 3:
- description = "与主账号线索名称保持一致"
- case 51:
- description = "主账号公司信息变更"
- case 5:
- description = "订单公司信息变更"
- }
- //新增变更记录
- AddClueChange(clueId, kcPositionId, "cluename", "基本信息变更", oldName, newName, nowTime, common.GetRandom(32), "", description)
- }
- func updateClueTransfer(clueId int64, nowTime string) {
- TiDb.Update("dwd_f_crm_clue_info", map[string]interface{}{"id": clueId}, map[string]interface{}{
- "is_transfer": 1,
- "updatetime": nowTime,
- })
- }
- // 客成新增变更记录
- func AddClueChange(clueId, positionId int64, changeField, changeType, old_value, new_value, nowTime, BCPCID, description, change_reason string) int64 {
- return TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
- "clue_id": clueId,
- "position_id": positionId,
- "change_field": changeField,
- "change_type": changeType,
- "old_value": old_value,
- "new_value": new_value,
- "createtime": nowTime,
- "BCPCID": BCPCID,
- "operator_id": -1,
- "SHUOMING": description,
- "change_reason": change_reason,
- })
- }
- // 主账号信息修改
- func (k *KcTransferRequest) KcAccountNumberUpdate(customData, clueData *map[string]interface{}, orderCode string, isNew, isUpdate bool, is_transfer int64) {
- //需要进客成
- if !isNew {
- updateMap := map[string]interface{}{
- "is_transfer": 0,
- "is_renewal_protection": 0,
- "product_access": k.KcProduct,
- "buy_subject": k.KcBuySubject,
- "transfertime": k.NowTime,
- "service_starttime": k.KcStartTime,
- "service_endtime": k.KcEndTime,
- "ent_id": k.KcEntId,
- "company_name": k.KcCompanyName,
- "name": k.KcName,
- "position_id": k.KcPositionId,
- "account_type": 1,
- "primary_id": nil,
- }
- if is_transfer == 1 || k.KcPositionId != gconv.Int64((*customData)["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": k.HostClueId}, updateMap)
- //判断是否需要做线索名称变成
- TiDb.Update("dwd_f_crm_clue_info", map[string]interface{}{"id": k.HostClueId}, map[string]interface{}{"is_transfer": 1, "updatetime": k.NowTime, "cluename": k.KcCompanyName})
- oldClueName := gconv.String((*clueData)["cluename"])
- if oldClueName != k.KcCompanyName && k.KcCompanyName != "" {
- //线索名称修改
- updateClueName(k.HostClueId, k.KcCompanyName, k.NowTime, gconv.String((*clueData)["uid"]))
- addClueNameChangeRecord(5, k.HostClueId, oldClueName, k.KcCompanyName, k.KcPositionId, k.NowTime)
- }
- }
- if k.KcPositionId > 0 {
- // 添加移交记录
- AddClueChange(k.HostClueId, k.KcPositionId, "", "成交客户移交", "", "移交至客户成功组", k.NowTime, common.GetRandom(32), "主账号", "")
- if is_transfer == 1 || k.KcPositionId != gconv.Int64((*customData)["position_id"]) {
- // 添加客户成功经理变更记录
- AddClueChange(k.HostClueId, k.KcPositionId, "position_id", "客户成功经理", gconv.String(common.If(k.KcOldName == "", "/", k.KcOldName)), k.KcName, k.NowTime, common.GetRandom(32), "", "")
- //新增任务车
- AddClueChange(k.HostClueId, k.KcPositionId, "", "加入任务车", "", "未建联", k.NowTime, common.GetRandom(32), "", "")
- }
- if k.KcPositionId != gconv.Int64((*customData)["position_id"]) {
- if k.KcName == db.KeCheng.Admin {
- TiDb.UpdateOrDeleteBySql(`update dwd_f_csm_customer_autodraw_record set count = count + 2 where name = ?`, k.KcName)
- } else {
- TiDb.UpdateOrDeleteBySql(`update dwd_f_csm_customer_autodraw_record set count = count + 1 where name = ?`, k.KcName)
- }
- }
- }
- KcSend(orderCode, k.KcName)
- TiDb.Update("dwd_f_crm_clue_info",
- map[string]interface{}{"id": k.HostClueId}, map[string]interface{}{"is_transfer": 1, "updatetime": k.NowTime})
- k.OtherKcTransfer()
- if isUpdate {
- //需要替换
- customList := TiDb.SelectBySql(`select * from dwd_f_csm_customer_info where primary_id = ? and account_type in (2,3,4)`, k.KcID)
- for _, v := range *customList {
- clueId := gconv.Int64(v["clue_id"])
- clueData := TiDb.FindOne("dwd_f_crm_clue_info", map[string]interface{}{
- "id": clueId,
- }, "", "")
- if clueData == nil || len(*clueData) == 0 {
- continue
- }
- cluename := gconv.String((*clueData)["cluename"])
- //查看名称是否需要修改
- if cluename == k.HostClueName {
- continue
- }
- //线索名称修改
- updateClueName(clueId, k.KcCompanyName, k.NowTime, gconv.String((*clueData)["uid"]))
- addClueNameChangeRecord(51, clueId, cluename, k.KcCompanyName, k.KcPositionId, k.NowTime)
- }
- }
- }
- // 企业操作客成处理
- func EntOperateHandle() {
- nowTime := time.Now().Format(date.Date_Full_Layout)
- Mysql.SelectByBath(100, func(l *[]map[string]interface{}) bool {
- for _, v := range *l {
- userData := &map[string]interface{}{}
- entId := gconv.Int64(v["entId"])
- entUserId := gconv.String(v["entUserId"])
- operate := gconv.Int(v["operate"])
- number := gconv.Int64(v["number"])
- number++
- if number == 80 {
- Mysql.Update("ent_operate_record", map[string]interface{}{
- "entUserId": entUserId,
- "isUse": 0,
- }, map[string]interface{}{
- "isUse": 1,
- })
- continue
- }
- if entId != 0 {
- userData = TiDb.FindOne("data_service.user_system", map[string]interface{}{
- "ent_user_id": entUserId,
- "ent_id": entId,
- "status": 1,
- }, "", "")
- } else {
- userData = TiDb.FindOne("data_service.user_system", map[string]interface{}{
- "userid": entUserId,
- "status": 1,
- }, "", "")
- }
- if userData == nil || len(*userData) == 0 {
- log.Println("用户信息查询不到:", entId, entUserId)
- //没有归集需要等一等
- Mysql.Update("ent_operate_record", map[string]interface{}{
- "entUserId": entUserId,
- "isUse": 0,
- }, map[string]interface{}{
- "number": number,
- })
- continue
- }
- uid := gconv.String((*userData)["uid"])
- //客成信息查询
- clueData := TiDb.FindOne("dwd_f_crm_clue_info", map[string]interface{}{
- "uid": uid,
- }, "", "")
- if clueData == nil || len(*clueData) == 0 {
- log.Println("企业操作线索不存在:", uid)
- Mysql.Update("ent_operate_record", map[string]interface{}{
- "entUserId": entUserId,
- "isUse": 0,
- }, map[string]interface{}{
- "number": number,
- })
- continue
- }
- clueId := gconv.Int64((*clueData)["id"])
- customData := TiDb.FindOne("dwd_f_csm_customer_info", map[string]interface{}{
- "clue_id": clueId,
- }, "", "")
- isCreate := false
- isTransfer := false
- oldClueType := int64(0)
- minEntry, _ := GetPersonIdentityPower(uid, gconv.Int(common.If(operate > 0, 51, 52)), entId, gconv.String((*clueData)["cluename"]))
- //minEntry, _ := GetPersonIdentityPower(uid, gconv.Int(common.If(operate > 0, 51, 52)), entId, "2222")
- newClueType := int64(0)
- if minEntry != nil {
- newClueType = gconv.Int64(minEntry["newAccountType"])
- }
- if customData != nil && len(*customData) > 0 {
- isCreate = true
- oldClueType = gconv.Int64((*customData)["account_type"])
- if gconv.Int64((*customData)["is_transfer"]) == 0 {
- isTransfer = true
- }
- }
- if !isTransfer && minEntry == nil {
- //之前不在客成 没有权限 不需要处理
- Mysql.Update("ent_operate_record", map[string]interface{}{
- "entUserId": entUserId,
- "isUse": 0,
- }, map[string]interface{}{
- "isUse": 1,
- })
- continue
- }
- custom := gconv.Map(minEntry["customer"])
- k := KcTransferRequest{
- ClueType: newClueType,
- KcEntId: common.If(entId == 0, entUserId, entId),
- UserList: []interface{}{entUserId},
- NowTime: nowTime,
- LogPrefix: fmt.Sprintf("[企业操作客成移交] uid:%s, kcName:%s, company:%s", uid, gconv.String(custom["name"]), gconv.String(custom["company_name"])),
- SecondaryClueId: clueId,
- SecondaryPersonUid: uid,
- SecondaryUserName: gconv.String((*clueData)["name"]),
- SecondaryUserPhone: gconv.String((*clueData)["phone"]),
- SendUserMailMap: nil,
- SecondaryClueName: gconv.String((*clueData)["cluename"]),
- }
- if customData != nil && len(*customData) > 0 {
- k.KcOldName = gconv.String((*customData)["name"])
- //k.SecondaryAccountType = gconv.Int64((*customData)["account_type"])
- }
- if minEntry != nil {
- k.KcName = gconv.String(custom["name"])
- k.KcID = gconv.Int64(custom["id"])
- k.KcBuySubject = gconv.Int64(custom["buy_subject"])
- k.KcCompanyName = gconv.String(custom["company_name"])
- k.KcPositionId = gconv.Int64(custom["position_id"])
- k.KcStartTime = gconv.String(custom["service_starttime"])
- k.KcEndTime = gconv.String(custom["service_endtime"])
- k.KcProduct = gconv.Int64(custom["product_access"])
- }
- switch operate {
- case 2, 1, 3:
- if minEntry == nil {
- Mysql.Update("ent_operate_record", map[string]interface{}{
- "entUserId": entUserId,
- "isUse": 0,
- }, map[string]interface{}{
- "isUse": 1,
- })
- continue
- }
- //查看是否创建
- if isCreate {
- if isTransfer {
- //在客成
- if newClueType < oldClueType {
- //做修改
- k.ClueType = newClueType
- k.handleCustomerData()
- }
- } else {
- //不在客成
- //做新增
- k.ClueType = newClueType
- k.handleCustomerData()
- }
- } else {
- //走新增
- k.ClueType = newClueType
- k.handleCustomerData()
- }
- case -1, -2, -3:
- isPower := false
- if operate == -1 {
- //企业删人
- //看看之前有没有权限
- if Mgo.Count("ent_user", map[string]interface{}{
- "i_member_status": map[string]interface{}{"$gt": 0},
- "i_entid": entId,
- "i_userid": gconv.Int64(entUserId),
- }) > 0 {
- isPower = true
- }
- }
- //删除权限
- if isCreate && isTransfer {
- if newClueType == 0 {
- //查询不到其他权限
- //走退出
- productName := GetProductName(gconv.Int64((*customData)["product_access"]))
- changeReason := ""
- switch operate {
- case -1:
- if isPower {
- changeReason = fmt.Sprintf("%s权限被企业删除", productName)
- } else {
- changeReason = "被企业移出组织架构(集团公司客户),关联线索移交销售"
- }
- case -2:
- productName := GetProductName(gconv.Int64((*customData)["product_access"]))
- changeReason = fmt.Sprintf("%s权限被企业删除", productName)
- case -3:
- productName, _ := GetSubAccountProduct(entUserId)
- changeReason = fmt.Sprintf("%s权限被企业删除", productName)
- }
- kcToOpenSeaUpdate(clueId, gconv.Int64((*customData)["position_id"]), oldClueType, changeReason)
- if isPower {
- //需要重新进课程
- FormatData(map[string]interface{}{
- "belong_to": "0100",
- "source": "0101",
- "uid": uid,
- "phone": "phone",
- }, "powerdDele")
- }
- } else {
- //已创建 在客成可继续处理 其他不需要操作
- if newClueType >= oldClueType {
- //需要更换一个客成信息 或级别下降
- k.ClueType = newClueType
- k.IsDelete = true
- k.handleCustomerData()
- }
- }
- } else {
- Mysql.Update("ent_operate_record", map[string]interface{}{
- "entUserId": entUserId,
- "isUse": 0,
- }, map[string]interface{}{
- "isUse": 1,
- })
- }
- }
- Mysql.Update("ent_operate_record", map[string]interface{}{
- "entUserId": entUserId,
- "isUse": 0,
- }, map[string]interface{}{
- "isUse": 1,
- })
- }
- return true
- }, `SELECT e.*
- FROM ent_operate_record e
- INNER JOIN (
- SELECT entUserId, MAX(createTime) as max_createTime
- FROM ent_operate_record
- WHERE isUse = 0 AND number < 80
- GROUP BY entUserId
- ) latest ON e.entUserId = latest.entUserId AND e.createTime = latest.max_createTime
- WHERE e.isUse = 0 AND e.number < 80
- ORDER BY e.createTime DESC`)
- }
- // 获取商品名称
- func GetProductName(product int64) string {
- productMap := TiDb.FindOne("dwd_d_csm_product_access_code", map[string]interface{}{
- "code": product,
- }, "", "")
- if productMap == nil || len(*productMap) == 0 {
- return ""
- }
- productName := gconv.String((*productMap)["name"])
- return productName
- }
- var level_map = map[int]string{
- 1: "专家版",
- 2: "智慧版",
- 3: "商机版",
- 4: "试用版",
- 5: "自定义",
- 6: "商机版2.0",
- 7: "专家版2.0",
- }
- // 获取子账号商品信息
- func GetSubAccountProduct(userId string) (string, int) {
- rMap, _ := Mgo.FindById("user", userId, `{"s_phone":1,"s_m_phone":1}`)
- if rMap == nil || len(*rMap) == 0 {
- return "", 0
- }
- combo := gconv.Int((*rMap)["i_member_status"])
- if combo < 0 {
- combo = -combo
- }
- return level_map[combo], combo
- }
|