Browse Source

订单相关程序修改

WH01243 2 months ago
parent
commit
74c5dbb3aa
5 changed files with 204 additions and 222 deletions
  1. 48 45
      clueSync/everything.go
  2. 0 4
      clueSync/job.go
  3. 13 16
      clueSync/jobutil.go
  4. 140 154
      clueSync/kc.go
  5. 3 3
      clueSync/util.go

+ 48 - 45
clueSync/everything.go

@@ -61,7 +61,8 @@ func everythingSync() {
 			if vData != nil {
 				last_login_time = common.ObjToString((*vData)["date"])
 			}
-			dDataSql := fmt.Sprintf(`select b.product_type  from  dataexport_order  a   INNER JOIN   jy_order_detail   b    on   a.order_code=b.order_code and    a.user_id = ?`, user_id)
+			dDataSql := fmt.Sprintf(`select b.product_type  from  dataexport_order  a   INNER JOIN 
+             jy_order_detail   b    on   a.order_code=b.order_codeand    a.user_id = ?`, user_id)
 			dData := Mysql.SelectBySql(dDataSql)
 			if dData != nil && len(*dData) > 0 {
 				pMap := map[string]string{}
@@ -205,7 +206,8 @@ func saveEverything(user_id, phone, item, sourceName, sourceCode string) bool {
 		unique_id = common.ObjToString((*cuData)["unique_id"])
 		owner = common.ObjToString((*cuData)["owner"])
 	}*/
-	dDataSql := fmt.Sprintf(`select b.product_type  from  dataexport_order  a   INNER JOIN   jy_order_detail   b    on   a.order_code=b.order_code and    a.user_id = ?`, user_id)
+	dDataSql := fmt.Sprintf(`select b.product_type  from  dataexport_order  a   INNER JOIN  
+    jy_order_detail   b    on   a.order_code=b.order_code and    a.user_id = ?`, user_id)
 	dData := Mysql.SelectBySql(dDataSql)
 	if dData != nil && len(*dData) > 0 {
 		pMap := map[string]string{}
@@ -362,6 +364,7 @@ func bigCustomer() {
 	nowTime := time.Now().Format(date.Date_Full_Layout)
 	bigSaleTime := cfg.BigSaleTime
 	bigOrderTime := cfg.BigOrderTime
+	bigSaleTime = 0
 	if bigSaleTime == 0 {
 		bigSaleTime = time.Now().Unix()
 	}
@@ -438,8 +441,8 @@ func bigCustomer() {
 		}
 	}
 	cfg.BigSaleTime = bigSaleTime
-	orderDataSql := `select a.*,b.product_type as  productType,b.filter as  productFilter  from  dataexport_order  a   INNER JOIN   jy_order_detail   b    on
-	a.order_code=b.order_code
+	orderDataSql := `select a.*,b.product_type as  productType,b.filter as  productFilter,b.final_price  from  dataexport_order  a   INNER JOIN  
+    jy_order_detail   b    on a.order_code=b.order_code
 	and   a.create_time>?  and  b.product_type in  ("数据流量包","历史数据") and  a.order_status IN (0,1) AND a.salesperson IS NULL AND a.is_backstage_order = 0 `
 	orderData := Mysql.SelectBySql(orderDataSql, bigOrderTime)
 	if orderData != nil && len(*orderData) > 0 {
@@ -482,7 +485,7 @@ func bigCustomer() {
 					unpayorderinfo = "历史数据"
 				} else {
 					source = "线上历史数据导出已支付订单"
-					payorderinfo = "历史数据" + fmt.Sprint(common.IntAll(v["pay_money"])/100)
+					payorderinfo = "历史数据" + fmt.Sprint(common.IntAll(v["final_price"])/100)
 				}
 			} else {
 				if order_status == 0 {
@@ -490,7 +493,7 @@ func bigCustomer() {
 					unpayorderinfo = "数据流量包"
 				} else {
 					source = "线上数据流量包已支付订单"
-					payorderinfo = "数据流量包" + fmt.Sprint(common.IntAll(v["pay_money"])/100)
+					payorderinfo = "数据流量包" + fmt.Sprint(common.IntAll(v["final_price"])/100)
 				}
 			}
 			key := fmt.Sprintf("%s_%s", source, phone)
@@ -547,22 +550,22 @@ func bigCustomer() {
 			}
 			for _, v := range vb {
 				row := sh.AddRow()
-				row.AddCell().SetString(common.ObjToString(v["usernickname"]))
-				row.AddCell().SetString(common.ObjToString(v["username"]))
-				row.AddCell().SetString(common.ObjToString(v["company"]))
-				row.AddCell().SetString(common.ObjToString(v["job"]))
-				row.AddCell().SetString(common.ObjToString(v["phone"]))
-				row.AddCell().SetValue(common.IntAll(v["data_count"]))
-				row.AddCell().SetString(common.ObjToString(v["email"]))
-				row.AddCell().SetString(common.ObjToString(v["payorderinfo"]))
-				row.AddCell().SetString(common.ObjToString(v["unpayorderinfo"]))
-				row.AddCell().SetString(common.ObjToString(v["source"]))
-				row.AddCell().SetString(common.ObjToString(v["interest"]))
-				row.AddCell().SetString(common.ObjToString(v["data_requirement"]))
+				row.AddCell().SetString(gconv.String(v["usernickname"]))
+				row.AddCell().SetString(gconv.String(v["username"]))
+				row.AddCell().SetString(gconv.String(v["company"]))
+				row.AddCell().SetString(gconv.String(v["job"]))
+				row.AddCell().SetString(gconv.String(v["phone"]))
+				row.AddCell().SetValue(gconv.Int64(v["data_count"]))
+				row.AddCell().SetString(gconv.String(v["email"]))
+				row.AddCell().SetString(gconv.String(v["payorderinfo"]))
+				row.AddCell().SetString(gconv.String(v["unpayorderinfo"]))
+				row.AddCell().SetString(gconv.String(v["source"]))
+				row.AddCell().SetString(gconv.String(v["interest"]))
+				row.AddCell().SetString(gconv.String(v["data_requirement"]))
 				//增加客户需求
 			}
 			email := k
-			//email = "wanghao@jianyu360.com"
+			email = "wanghao@jianyu360.com"
 			dir := "./xlsx/dk/" + fileName + ".xlsx"
 			err := xf.Save(dir)
 			if err != nil {
@@ -606,7 +609,7 @@ func eventReg() {
 					common.WriteSysConfig(&cfg)
 				}
 			}
-			cfg.LastEventRegTime = common.ObjToString(v["update_time"])
+			cfg.LastEventRegTime = gconv.String(v["update_time"])
 		}
 	}
 	common.WriteSysConfig(&cfg)
@@ -741,10 +744,10 @@ func buildSourceMap(department string) map[string]map[string]interface{} {
 	saleSource := TiDb.SelectBySql(fmt.Sprintf(`SELECT source,name,appoint_email FROM d_saleleads_code WHERE department LIKE '%%%s%%' AND is_delete = 1`, department))
 	if saleSource != nil {
 		for _, v := range *saleSource {
-			source := common.ObjToString(v["source"])
-			name := common.ObjToString(v["name"])
+			source := gconv.String(v["source"])
+			name := gconv.String(v["name"])
 			name = filterSourceName(name)
-			appointEmail := common.ObjToString(v["appoint_email"])
+			appointEmail := gconv.String(v["appoint_email"])
 			sourceMap[source] = map[string]interface{}{
 				"name":         name,
 				"appointEmail": appointEmail,
@@ -794,7 +797,7 @@ func processLeads(batch string, committeeTime int64, sourceMap map[string]map[st
 
 // 处理单个线索
 func processLead(v map[string]interface{}, sourceMap map[string]map[string]interface{}, nowTime string, committeeTime int64, data map[string]interface{}) (map[string]interface{}, int64) {
-	sources := common.ObjToString(v["source"])
+	sources := gconv.String(v["source"])
 	// 更新委员会时间
 	if gconv.Int64(v["createtime"]) > committeeTime {
 		committeeTime = gconv.Int64(v["createtime"])
@@ -803,7 +806,7 @@ func processLead(v map[string]interface{}, sourceMap map[string]map[string]inter
 	if !exist {
 		return nil, committeeTime
 	}
-	phone := common.ObjToString(v["phone"])
+	phone := gconv.String(v["phone"])
 	if IsInternal(phone) {
 		return nil, committeeTime
 	}
@@ -812,7 +815,7 @@ func processLead(v map[string]interface{}, sourceMap map[string]map[string]inter
 	if userData == nil || isUserInBlackList(userData) {
 		return nil, committeeTime
 	}
-	key := fmt.Sprintf("%s_%s_%s", sourceMap[sources], phone, common.ObjToString(v["interest"]))
+	key := fmt.Sprintf("%s_%s_%s", sourceMap[sources], phone, gconv.String(v["interest"]))
 	if _, exists := data[key]; exists {
 		return nil, committeeTime
 	}
@@ -821,23 +824,23 @@ func processLead(v map[string]interface{}, sourceMap map[string]map[string]inter
 	return map[string]interface{}{
 		"createTime":       nowTime,
 		"createtime":       v["createtime"],
-		"username":         common.ObjToString(v["name"]),
-		"company":          common.ObjToString(v["company"]),
+		"username":         gconv.String(v["name"]),
+		"company":          gconv.String(v["company"]),
 		"phone":            phone,
 		"source":           gconv.String(sourceData["name"]),
 		"belongTo":         "咨询组/市场组", // 根据需要修改
-		"interest":         common.ObjToString(v["interest"]),
-		"data_requirement": common.ObjToString(v["data_requirement"]),
+		"interest":         gconv.String(v["interest"]),
+		"data_requirement": gconv.String(v["data_requirement"]),
 		"branch":           v["branch"],
 		"job":              v["position"],
-		"email":            common.ObjToString(v["mail"]),
+		"email":            gconv.String(v["mail"]),
 		"appointEmail":     gconv.String(sourceData["appointEmail"]),
 	}, committeeTime
 }
 
 // 获取用户数据
 func getUserData(v map[string]interface{}) map[string]interface{} {
-	userid := common.ObjToString(v["userid"])
+	userid := gconv.String(v["userid"])
 	userMapping := &map[string]interface{}{}
 	if !mongodb.IsObjectIdHex(userid) {
 		userMapping = TiDb.FindOne("dwd_f_userbase_id_mapping", map[string]interface{}{"position_id": userid}, "", "")
@@ -853,13 +856,13 @@ func getUserData(v map[string]interface{}) map[string]interface{} {
 
 // 判断用户是否在黑名单
 func isUserInBlackList(userData map[string]interface{}) bool {
-	bt := common.ObjToString(userData["belong_to"])
+	bt := gconv.String(userData["belong_to"])
 	return strings.HasPrefix(bt, "03") || bt == "0102"
 }
 
 // 判断是否是安博会线索
 func isABHLead(lead map[string]interface{}) bool {
-	s_sourceid := common.ObjToString(lead["s_sourceid"])
+	s_sourceid := gconv.String(lead["s_sourceid"])
 	return s_sourceid == db.Sourceid
 }
 
@@ -896,15 +899,15 @@ func exportToExcel(dataArr []map[string]interface{}, title, batch string) {
 
 		for _, v := range arr {
 			row := sh.AddRow()
-			row.AddCell().SetString(common.ObjToString(v["username"]))
-			row.AddCell().SetString(common.ObjToString(v["phone"]))
-			row.AddCell().SetString(common.ObjToString(v["job"]))
-			row.AddCell().SetString(common.ObjToString(v["branch"]))
-			row.AddCell().SetString(common.ObjToString(v["email"]))
-			row.AddCell().SetString(common.ObjToString(v["company"]))
-			row.AddCell().SetString(common.ObjToString(v["data_requirement"]))
-			row.AddCell().SetString(common.ObjToString(v["source"]))
-			row.AddCell().SetString(common.ObjToString(v["interest"]))
+			row.AddCell().SetString(gconv.String(v["username"]))
+			row.AddCell().SetString(gconv.String(v["phone"]))
+			row.AddCell().SetString(gconv.String(v["job"]))
+			row.AddCell().SetString(gconv.String(v["branch"]))
+			row.AddCell().SetString(gconv.String(v["email"]))
+			row.AddCell().SetString(gconv.String(v["company"]))
+			row.AddCell().SetString(gconv.String(v["data_requirement"]))
+			row.AddCell().SetString(gconv.String(v["source"]))
+			row.AddCell().SetString(gconv.String(v["interest"]))
 			row.AddCell().SetString(gconv.Time(gconv.Int64(v["createtime"])).Format(date.Date_Full_Layout))
 		}
 		dir := fmt.Sprintf("./xlsx/%s/%s.xlsx", batch, fileName)
@@ -944,8 +947,8 @@ func EmailSelect(batch string) (string, string) {
 		mincount := common.IntAll((*bigData)[0]["count"])
 		for _, vv := range *bigData {
 			vcount := common.IntAll(vv["count"])
-			vemail := common.ObjToString(vv["email"])
-			vName := common.ObjToString(vv["name"])
+			vemail := gconv.String(vv["email"])
+			vName := gconv.String(vv["name"])
 			if vcount <= mincount {
 				mincount = vcount
 				minemail = vemail

+ 0 - 4
clueSync/job.go

@@ -267,10 +267,6 @@ func FormatData(data map[string]interface{}, item string) (bool, bool, bool) {
 		//saveHlyj(belong_to, item, phone, name, sourceName, cluename, position, nowTime, isGroup, isCommerce)
 		return true, true, true
 	}
-	//安博会
-	/*if s_sourceid == db.Sourceid {
-		return true, true, false
-	}*/
 	if uId == "" { //没有进用户归集,等待进入,结束任务,放在下次继续执行
 		if isExists, _ := redis.Exists("bidx", "bidx_userId_"+userId); isExists {
 			redisInt := redis.GetInt("bidx", "bidx_userId_"+userId)

+ 13 - 16
clueSync/jobutil.go

@@ -247,7 +247,7 @@ func GetPerson(positionId string) map[string]interface{} {
 	positionArrMap := Base.SelectBySql(fmt.Sprintf(`select  a.phone,b.id,b.ent_id from  
                          base_user  a  
                              INNER JOIN   base_position  b     
-                                 on     b.id=%s  and  b.user_id=a.id and   b.type=1`,
+                                 on     b.id="%s"  and  b.user_id=a.id and   b.type=1`,
 		positionId))
 	if positionArrMap == nil || len(*positionArrMap) == 0 {
 		return map[string]interface{}{}
@@ -500,24 +500,21 @@ func orders() {
 	lastOrderId := cfg.LastOrderId
 	selectTimeStart := time.Unix(time.Now().Unix()-7200, 0).Format(date.Date_Full_Layout)
 	selectTimeEnd := time.Unix(time.Now().Unix()-3600, 0).Format(date.Date_Full_Layout)
-	dDataSql := fmt.Sprintf(`select a.*,b.product_type as productType ,b.service_starttime,b.service_endtime  from  dataexport_order  a   INNER JOIN   jy_order_detail   b    on   a.order_code=b.order_code and    a.create_time<="%s" and a.create_time>="%s" and  a.id> %s`, selectTimeEnd, selectTimeStart, gconv.String(lastOrderId))
-	data, _ := getOrderData(dDataSql)
+	product_type_str1 := `"大会员","VIP订阅","数据流量包","历史数据"`
+	DataSql := 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.create_time<="%s" and a.create_time>="%s" and b.product_type in  (%s) and a.order_status = 0 and   a.is_backstage_order = 0  and    a.id> %s`, selectTimeEnd, selectTimeStart, product_type_str1, gconv.String(lastOrderId))
+	data, _ := getOrderData(DataSql)
 	if data != nil && data != nil && len(data) > 0 {
 		for _, v := range data {
-			order_status := common.IntAll(v["order_status"])
-			is_backstage_order := common.IntAll(v["is_backstage_order"])
-			product_type_str1 := `"大会员","VIP订阅","数据流量包","历史数据"`
-			product_type := common.ObjToString(v["product_type"])
-			if order_status == 0 && is_backstage_order == 0 && strings.Contains(product_type_str1, product_type) {
-				ok1, ok2, _ := FormatData(v, "orders")
-				if !ok1 {
+			ok1, ok2, _ := FormatData(v, "orders")
+			if !ok1 {
+				common.WriteSysConfig(&cfg)
+				log.Println("线索卡点", "orders", v, selectTimeEnd, selectTimeStart)
+			} else {
+				if !ok2 {
+					log.Println("用户分配已达上限", "orders", v, selectTimeEnd, selectTimeStart)
 					common.WriteSysConfig(&cfg)
-					log.Println("线索卡点", "orders", v, selectTimeEnd, selectTimeStart)
-				} else {
-					if !ok2 {
-						log.Println("用户分配已达上限", "orders", v, selectTimeEnd, selectTimeStart)
-						common.WriteSysConfig(&cfg)
-					}
 				}
 			}
 			cfg.LastOrderId = common.IntAll(v["id"])

+ 140 - 154
clueSync/kc.go

@@ -4,7 +4,6 @@ import (
 	"app.yhyue.com/moapp/jybase/mail"
 	"app.yhyue.com/moapp/jybase/redis"
 	"database/sql"
-	"encoding/json"
 	"fmt"
 	"log"
 	"strings"
@@ -26,7 +25,7 @@ func kcSync() {
 		return
 	}
 	sql := `SELECT
-	a.*,b.product_type,b.service_starttime,b.service_endtime,b.filter as  productFilter
+	a.*,b.product_type,b.service_starttime,b.service_endtime,b.filter as  productFilter,TIMESTAMPDIFF(DAY, b.service_starttime, b.service_endtime)  as  difference
 FROM
 	dataexport_order a
 	INNER JOIN jy_order_detail b ON a.order_code = b.order_code 
@@ -35,42 +34,43 @@ FROM
 		a.pay_money > 0 
 		OR (
 			a.pay_money = 0 
-		AND ( zero_type = "分期付款补充权益" OR zero_type = "原订单不支持开通多项权益" OR zero_type = "权益码兑换" ))) 
-
-	AND a.user_phone NOT LIKE "9%" 
+	AND ( zero_type = "分期付款补充权益" OR zero_type = "原订单不支持开通多项权益" OR 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 a.autoUpdate > %s
+	AND a.autoUpdate > "%s"
 ORDER BY
 	a.autoUpdate ASC,
 	a.order_code ASC,
 	b.final_price DESC `
-	sql = fmt.Sprintf(sql, strings.Join(productArr, ","), cfg.LastkcTime)
+	sql = fmt.Sprintf(sql, strings.Join(productArr, ","), "9%", cfg.LastkcTime)
 	data := Mysql.SelectBySql(sql)
 	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"])
-			product_type := gconv.String(v["product_type"])
-			vip_starttime := gconv.String(v["service_starttime"])
-			vip_endtime := gconv.String(v["service_endtime"])
-			order_change := gconv.Int64(v["order_change"])
-			if (order_change != 0) || (order_change == 0 && TimeStrcount(vip_starttime, vip_endtime) > 95) {
+			productType := gconv.String(v["product_type"])
+			vipStarttime := gconv.String(v["service_starttime"])
+			vipEndtime := gconv.String(v["service_endtime"])
+			orderChange := gconv.Int64(v["order_change"])
+			difference := gconv.Int(v["difference"])
+			if (orderChange != 0) || (orderChange == 0 && difference > 95) {
 				isExit := false
 				for _, v := range customList {
 					if v == orderCode {
 						isExit = true
-						continue
+						//continue
 					}
 				}
 				if isExit {
-					continue
+					//continue
 				}
 				//判断一下服务周期
-				difference := GetTimeDifference(vip_starttime, vip_endtime)
-				productInt64 := GetOrderProduct(product_type, gconv.String(v["productFilter"]))
+				_, productInt64, _ := GetOrderProduct(productType, gconv.String(v["productFilter"]))
 				if productInt64 == 0 {
 					continue
 				}
@@ -83,8 +83,8 @@ ORDER BY
 						//需要更换
 						v["difference"] = difference
 						v["product"] = productInt64
-						v["service_endtime"] = vip_endtime
-						v["service_starttime"] = vip_starttime
+						v["service_endtime"] = vipEndtime
+						v["service_starttime"] = vipStarttime
 						orderMap[orderCode] = v
 					}
 				} else {
@@ -95,7 +95,6 @@ ORDER BY
 			}
 			cfg.LastkcTime = gconv.String(v["autoUpdate"])
 		}
-
 		for _, v := range *data {
 			orderCode := gconv.String(v["order_code"])
 			if _, exists := orderMap[orderCode]; exists {
@@ -196,19 +195,9 @@ func kcJob(data map[string]interface{}) int {
 	starttime := gconv.String(data["service_starttime"])
 	endtime := gconv.String(data["service_endtime"])
 	buy_subject := common.IntAll(data["buy_subject"])
-	product_type := gconv.String(data["product_type"])
+	//product_type := gconv.String(data["product_type"])
 	userName := gconv.String((*clueData)["name"])
 	product, company_name := gconv.String(data["product"]), gconv.String(data["company_name"])
-	if product_type != "大会员" {
-		powerData := TiDb.FindOne("dwd_f_data_equity_info", map[string]interface{}{"uid": uId, "product_type": "商机管理"}, "", "comeintime desc")
-		if powerData != nil {
-			starttime = gconv.String((*powerData)["starttime"])
-			endtime = gconv.String((*powerData)["endtime"])
-		} else {
-			log.Println("客成移交权限未查到--", uId)
-			return 0
-		}
-	}
 	//同一公司名称(以客户详情-组织机构-公司名称)下的线索需分配给同1人
 	saveMap = map[string]interface{}{
 		"clue_id":                   clueId,
@@ -547,64 +536,52 @@ func ordersClue() {
 	log.Println("后台订单线索定时任务开始")
 	lastOrderClueId := cfg.LastOrderClueId
 	nowTime := time.Now().Format(date.Date_Full_Layout)
-	sql := fmt.Sprintf(`select order_code,order_status,is_backstage_order,pay_money,saleDep,salesperson,user_phone,create_person,saleMoney,user_id,product_type,company_name,autoUpdate from dataexport_order where autoUpdate >= "%s" order by autoUpdate asc`, lastOrderClueId)
+	product_type_str2 := `"大会员","企业商机管理","VIP订阅"`
+	sql := 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.autoUpdate>="%s"  AND a.user_phone NOT LIKE "%s"   and   a.user_id  !=""
+    and b.product_type in  (%s) and a.order_status = 0 and   a.is_backstage_order = 1  order by a.autoUpdate asc`, lastOrderClueId, "9%", product_type_str2)
+
 	data := Mysql.SelectBySql(sql)
 	if data != nil && *data != nil && len(*data) > 0 {
 		for _, v := range *data {
-			order_status := common.IntAll(v["order_status"])
-			is_backstage_order := common.IntAll(v["is_backstage_order"])
-			pay_money := common.IntAll(v["pay_money"])
+			payMoney := common.IntAll(v["pay_money"])
 			orderCode := gconv.String(v["order_code"])
 			saleDep, _, salesperson := FindSaleRecord(orderCode)
-			user_phone := gconv.String(v["user_phone"])
+			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)
-			product_type_str2 := `"大会员","企业商机管理","VIP订阅"`
-			product_type := gconv.String(v["product_type"])
-			if order_status == 1 && is_backstage_order == 1 && saleDep != "" && !strings.HasPrefix(user_phone, "9") && strings.Contains(product_type_str2, product_type) {
+			if saleDep != "" {
 				//销售部
 				query := map[string]interface{}{}
 				source := ""
-				if product_type == "企业商机管理" {
-					query["phone"] = user_phone
-					userInfo := TiDb.FindOne("dwd_f_userbase_baseinfo", query, "", "")
-					if userInfo != nil && len(*userInfo) > 0 {
-						uId = gconv.String((*userInfo)["uid"])
-						userId = gconv.String((*userInfo)["userid"])
-						source = gconv.String((*userInfo)["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("后台订单--未查询到 ", user_phone)
+						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 {
-					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("后台订单--未查询到 ", user_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, user_phone)
-						break
-					}
+					log.Println("后台订单--未查询到 ", query, userPhone)
+					break
 				}
 				is_assign := 1
 				mailContent := ""
 				cluename = gconv.String(v["company_name"])
-				mailContent = fmt.Sprintf("%s(%s)", cluename, user_phone)
+				mailContent = fmt.Sprintf("%s(%s)", cluename, userPhone)
 				if cluename == "" {
-					cluename = user_phone
-					mailContent = user_phone
+					cluename = userPhone
+					mailContent = userPhone
 				}
-				if pay_money > 0 {
+				if payMoney > 0 {
 					trailstatus = "08"
 				} else {
 					trailstatus = "01"
@@ -628,7 +605,7 @@ func ordersClue() {
 							seatNumber = gconv.String((*saleData)["seat_number"])
 							positionId = common.Int64All((*saleData)["position_id"])
 						}
-						if IsFreeze(source, pay_money, gconv.String(positionId), trailstatus) {
+						if IsFreeze(source, payMoney, gconv.String(positionId), trailstatus) {
 							//线索需要冻结
 							is_assign = -3
 						}
@@ -645,8 +622,8 @@ func ordersClue() {
 							"top_cluetype":         "4",
 							"sub_cluetype":         "154",
 							"trailstatus":          trailstatus,
-							"name":                 user_phone,
-							"phone":                user_phone,
+							"name":                 userPhone,
+							"phone":                userPhone,
 							"comeinsource_private": 2,
 							"is_task":              0,
 							"taskstatus":           0,
@@ -666,8 +643,8 @@ func ordersClue() {
 							"top_cluetype":         "4",
 							"sub_cluetype":         "154",
 							"trailstatus":          trailstatus,
-							"name":                 user_phone,
-							"phone":                user_phone,
+							"name":                 userPhone,
+							"phone":                userPhone,
 							"is_task":              0,
 							"taskstatus":           0,
 							"company_nature":       isGroup,
@@ -697,7 +674,7 @@ func ordersClue() {
 								"operator_id": -1,
 							})
 							//移交失败发送消息
-							if IsFreeze(source, pay_money, gconv.String(positionId), trailstatus) {
+							if IsFreeze(source, payMoney, gconv.String(positionId), trailstatus) {
 								//发送邮件信息
 								OrderCreateFail(positionId, mailContent)
 							}
@@ -751,7 +728,7 @@ func refundAuto() {
 			}
 			//查询即将到期数据
 			if isRenewalProtection == 0 {
-				sqlStr := fmt.Sprintf(`select  a.*,b.product_type as productType,b.service_starttime,b.service_endtime 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, ","))
+				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()
@@ -775,7 +752,7 @@ func refundAuto() {
 			}
 			isFull := false
 			isAllRefund := false
-			orderSql := fmt.Sprintf(`  select  a.*,b.product_type as productType,b.service_starttime,b.service_endtime 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, ","))
+			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
@@ -841,10 +818,14 @@ func refundAuto() {
 				TiDb.UpdateOrDeleteBySql(`UPDATE dwd_f_csm_customer_info SET is_transfer=1 WHERE clue_id = ?`, clueId)
 			} else {
 				order1Sql := fmt.Sprintf(`select  refund_status from  dataexport_order  a   INNER JOIN   jy_order_detail   b    on   a.order_code=b.order_code and    a.user_id    in   (%s) and    b.product_type in (%s)  and   order_status = 1  and  vip_endtime>%s ORDER BY  b.service_endtime  desc  `, strings.Join(personArr, ","), strings.Join(productArr, ","), findNowTime)
-				order1, _ := getOrderData(order1Sql)
-				if order1 == nil || len(order1) == 0 {
+				order1 := Mysql.SelectBySql(order1Sql)
+				if order1 == nil || len(*order1) == 0 {
 					isOk := false
-					order3Sql := fmt.Sprintf(`select  refund_status from  dataexport_order  a   INNER JOIN   jy_order_detail   b    on   a.order_code=b.order_code and    a.user_id    in   (%s) and    b.product_type in (%s)  and   order_status = 1  and  vip_endtime<%s ORDER BY  b.service_endtime  desc  `, strings.Join(personArr, ","), strings.Join(productArr, ","), findNowTime)
+					order3Sql := fmt.Sprintf(`select  a.refund_status,	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  vip_endtime<%s ORDER BY  b.service_endtime  desc  `,
+						strings.Join(personArr, ","), strings.Join(productArr, ","), findNowTime)
 					_, vip_endtime := getOrderData(order3Sql)
 					if vip_endtime != "" {
 						//获取最后一个订单信息
@@ -1314,7 +1295,7 @@ func CustomerChange() {
 		}
 		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`, 57876741)
+	//}, `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)
 	}
@@ -1441,34 +1422,10 @@ func CustomerChangeHandle(data map[string]interface{}) map[string]interface{} {
 
 // 查找订单实际业绩归属
 func FindPositionIdClueId(uid string) (int64, string, string) {
-	/*querySql := `
-		SELECT
-			e.username as salesperson ,c.position_id,f.dept_name,c.seat_number
-		FROM
-			dwd_f_crm_clue_info a
-	INNER JOIN dwd_f_userbase_order_info b ON a.id = ?
-			AND a.uid = b.uid
-			AND (
-				b.payable_money > 0
-				OR (
-					b.payable_money = 0
-				AND ( b.filter LIKE "%分期付款补充权益%" OR b.filter LIKE "%原订单不支持开通多项权益%" OR b.filter LIKE "%权益码兑换%" )))
-			AND b.data_spec != "dhy4"
-			AND b.order_status = 1 and b.phone not   like "9%"
-			AND ( b.refund_status != 1 OR b.refund_status IS NULL )
-			AND b.vip_starttime < "2099-01-01"
-			AND b.product_type IN ( "大会员", "企业商机管理" )
-			AND ( b.order_change != 0 or  b.order_change  is  NULL OR ( b.order_change = 0 AND DATEDIFF( b.vip_endtime, b.vip_starttime )> 90 ) )
-			inner JOIN  jianyu.order_sale_record d on  b.order_code=d.ordercode and  d.state=1
-			INNER JOIN cadmin.admin_user e   on  d.saler_Id = e.id
-			INNER JOIN   dwd_f_crm_personnel_management c   on c.ent_id =?  and    e.username=c.name
-			inner  join dwd_d_crm_department_level_succbi  f  on   c.position_id=f.position_id
-		ORDER BY
-			b.vip_endtime desc ,b.payable_money DESC `*/
 	personArr := getUserIdToUid(uid)
 	productArr, _ := KcProduct()
 	querySql := fmt.Sprintf(`	SELECT
-		e.username as salesperson ,c.position_id,f.dept_name,c.seat_number,b.product_type,b.filter
+		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)  
@@ -1477,22 +1434,31 @@ func FindPositionIdClueId(uid string) (int64, string, string) {
 			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 "9%"
+		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.product_type IN (%s ) 
 		AND ( b.service_type != 4 or  b.service_type  is  NULL OR ( b.service_type = 4 AND DATEDIFF( b.service_starttime, b.service_endtime )> 90 ) ) 
 		inner JOIN  jianyu.order_sale_record d on  b.order_code=d.ordercode and  d.state=1 
-		INNER JOIN cadmin.admin_user e   on  d.saler_Id = e.id
+		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.username=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, ","), strings.Join(productArr, ","))
+		b.service_endtime desc ,b.final_price DESC ,a.state,
+			a.money desc `, strings.Join(personArr, ","), "9%", strings.Join(productArr, ","))
 	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 == "大会员" {
+			fileJson := gconv.Map(m["filter"])
+			comboId := gconv.Int(fileJson["comboId"])
+			if comboId == 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"])
@@ -1530,20 +1496,23 @@ func IsFreeze(source string, pay_money int, positionId, trailstatus string) bool
 	}
 	return false
 }
+
+// 业绩归属查询
 func FindSaleRecord(orderCode string) (dept string, positionId int64, position string) {
 	recordList := Mysql.SelectBySql(`
-			SELECT
+		SELECT DISTINCT
 			a.saler_dept,
 			a.saler_name,
-			b.phone 
+			b.phone ,	a.state,
+			a.money
 		FROM
 			order_sale_record a
-			INNER JOIN cadmin.admin_user b 
+			INNER JOIN entniche_user  b 
 		on 
-			a.ordercode = ? and  a.saler_Id = b.id 
+			a.ordercode = ? and  a.ent_userId = b.id 
 		ORDER BY
 			a.state,
-			a.money
+			a.money desc 
 	`, orderCode)
 	if recordList != nil && len(*recordList) > 0 {
 		saler_dept := gconv.String((*recordList)[0]["saler_dept"])
@@ -1710,17 +1679,7 @@ type OrderInfo struct {
 // 客成发送邮箱
 func KcSend(orderCode, personName string) {
 	log.Println("客成发邮件", orderCode)
-	bigmemberService := map[int64]string{}
-	combo := 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`)
-	Mysql.SelectByBath(1, func(l *[]map[string]interface{}) bool {
-		combo[common.Int64All((*l)[0]["id"])] = gconv.String((*l)[0]["s_name"])
-		return true
-	}, `select id,s_name from jianyu.bigmember_combo`)
-	orderInfo := KcOrderFormat(orderCode, bigmemberService, combo)
+	orderInfo := KcOrderFormat(orderCode)
 	if orderInfo != nil {
 		tableAppend := ""
 		if len(orderInfo.SeriveList) > 0 {
@@ -1851,31 +1810,57 @@ func ExitKcSend(personName string, infoList []map[string]interface{}) {
 }
 
 // 客成邮件   订单信息初始化
-func KcOrderFormat(orderCode string, bigmemberService, combo map[int64]string) *OrderInfo {
-	orderData := Mysql.SelectBySql(`SELECT a.id,a.order_code,a.pay_money,a.user_phone,a.vip_starttime,a.vip_endtime,a.product_type,a.filter,a.user_id,a.ent_id,a.company_name,a.create_person,SUM(b.return_money) AS return_money
-		FROM jianyu.dataexport_order a
-	LEFT JOIN return_money_record b ON (a.order_code=b.order_code)
-	WHERE a.order_code=? AND a.order_status=1 AND (a.product_type='大会员' OR a.product_type='大会员-子账号' or  a.product_type = "企业商机管理")
-	GROUP BY a.id ORDER BY a.autoUpdate`, orderCode)
+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
+		a.id,
+		a.order_code,
+		a.pay_money,
+		a.user_phone,
+		a.vip_starttime,
+		a.vip_endtime,
+		a.product_type,
+		a.filter,
+		a.user_id,
+		a.ent_id,
+		a.company_name,
+		a.create_person,
+		SUM( c.return_money ) AS return_money ,
+		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)
+		LEFT JOIN return_money_record c ON  a.order_code = c.order_code 
+	GROUP BY
+		a.id 
+	ORDER  BY
+		a.autoUpdate desc  ,difference desc  
+	`, orderCode, strings.Join(productArr, ",")))
 	data := &OrderInfo{}
 	if orderData != nil && len(*orderData) > 0 {
-		id := common.Int64All((*orderData)[0]["id"])
-		user_phone := gconv.String((*orderData)[0]["user_phone"])
-		user_id := gconv.String((*orderData)[0]["user_id"])
-		product_type := gconv.String((*orderData)[0]["product_type"])
+		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 filter := gconv.String((*orderData)[0]["filter"]); filter != "" {
-			filterMap := map[string]interface{}{}
-			json.Unmarshal([]byte(filter), &filterMap)
-			if level := common.Int64All(filterMap["level"]); level == 5 {
+		if product_type == "大会员" {
+			product_type_name, _, comboId := GetOrderProduct(product_type, gconv.String(orderData["filter"]))
+			if comboId == 5 {
 				product_type += "自定义版"
-				for _, serversId := range strings.Split(gconv.String(filterMap["serversId"]), ",") {
+				for _, serversId := range strings.Split(gconv.String(gconv.Map(orderData["serversId"])), ",") {
 					if serviceName := bigmemberService[common.Int64All(serversId)]; serviceName != "" {
 						serviceList = append(serviceList, serviceName)
 					}
 				}
 			} else {
-				product_type += combo[common.Int64All(filterMap["comboId"])]
+				product_type += product_type_name
 			}
 		}
 		//联系人姓名
@@ -1895,16 +1880,16 @@ func KcOrderFormat(orderCode string, bigmemberService, combo map[int64]string) *
 		}
 		data = &OrderInfo{
 			Id:          id,
-			CompanyName: gconv.String((*orderData)[0]["company_name"]),
+			CompanyName: gconv.String(orderData["company_name"]),
 			UserId:      user_id,
 			ProductType: product_type,
 			OrderCode:   orderCode,
-			PayMoney:    common.Float64All((*orderData)[0]["pay_money"]) / 100,
-			ReturnMoney: common.Float64All((*orderData)[0]["return_money"]) / 100,
+			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)[0]["vip_starttime"]), " ")[0], strings.Split(gconv.String((*orderData)[0]["vip_endtime"]), " ")[0]),
+			StartEnd:    fmt.Sprintf("%s--%s", strings.Split(gconv.String(orderData["vip_starttime"]), " ")[0], strings.Split(gconv.String(orderData["vip_endtime"]), " ")[0]),
 			SeriveList:  serviceList,
-			SaleName:    gconv.String((*orderData)[0]["create_person"]),
+			SaleName:    gconv.String(orderData["create_person"]),
 			UserName:    userName,
 		}
 	}
@@ -1975,8 +1960,8 @@ func FindPersonOne(positionId int64) map[string]interface{} {
 // 进客成商品查询
 func KcProduct() ([]string, map[string]bool) {
 	var strArr []string
-	var strMap map[string]bool
-	productData := Mysql.SelectBySql(`SELECT
+	strMap := map[string]bool{}
+	productData := Mysql.SelectBySql(`SELECT id , 
 	CONCAT( '"', class_name,'"' )  as   product   
 FROM
 	jy_product_class 
@@ -1991,15 +1976,16 @@ WHERE
 	}
 	return strArr, strMap
 }
-func GetOrderProduct(productType string, file string) int64 {
+func GetOrderProduct(productType string, file string) (string, int64, int64) {
 	fileJson := gconv.Map(file)
 	if fileJson == nil || len(fileJson) == 0 {
-		return 0
+		return "", 0, 0
 	}
 	productName := ""
+	comboId := int64(0)
 	switch productType {
 	case "大会员":
-		comboId := gconv.Int(fileJson["comboId"])
+		comboId = gconv.Int64(fileJson["comboId"])
 		// {1: "专家版", 2: "智慧版", 3: "商机版", 4: "试用版", 5: "定制版", 6: "商机版2.0", 7: "专家版2.0"}
 		switch comboId {
 		case 1:
@@ -2027,9 +2013,9 @@ func GetOrderProduct(productType string, file string) int64 {
 		"name": productName,
 	}, "", "")
 	if productData == nil || len(*productData) == 0 {
-		return 0
+		return productName, 0, comboId
 	}
-	return gconv.Int64((*productData)["code"])
+	return productName, gconv.Int64((*productData)["code"]), comboId
 }
 
 func GetTimeDifference(timeStr1, timeStr2 string) int {
@@ -2056,7 +2042,7 @@ func getOrderData(sql string) (map[string]map[string]interface{}, string) {
 		vip_endtime := gconv.String(v["service_endtime"])
 		//判断一下服务周期
 		difference := GetTimeDifference(vip_starttime, vip_endtime)
-		productInt64 := GetOrderProduct(product_type, gconv.String(v["productFilter"]))
+		_, productInt64, _ := GetOrderProduct(product_type, gconv.String(v["productFilter"]))
 		if productInt64 == 0 {
 			continue
 		}

+ 3 - 3
clueSync/util.go

@@ -61,12 +61,12 @@ func GetUidToUserId(userId string, phone string) (string, string) {
 	return uId, userId
 }
 func getUserIdToUid(uid string) []string {
-	personData := TiDb.SelectBySql(`SELECT
-	CONCAT( '"', position_id,'"' )  as   positionId   
+	personData := TiDb.SelectBySql(`SELECT  
+	GROUP_CONCAT( '"', IF(type=0,userid,position_id),'"' )  as   positionId   
 FROM
 	dwd_f_userbase_id_mapping 
 WHERE
-	uid = %s and  type=1`, uid)
+	uid = ?   `, uid)
 	if personData == nil || len(*personData) == 0 {
 		return []string{}
 	}