Răsfoiți Sursa

Merge branch 'dev1.1' of http://192.168.3.207:8080/dataservice/datatools into dev1.1

zhangxinlei1996 2 ani în urmă
părinte
comite
0d654bcab8
11 a modificat fișierele cu 436 adăugiri și 58 ștergeri
  1. 110 0
      clueSync/autoTask.go
  2. 4 0
      clueSync/config.go
  3. 1 1
      clueSync/config.json
  4. 58 20
      clueSync/job.go
  5. 15 0
      clueSync/main.go
  6. 178 0
      clueSync/subscribeAll.go
  7. 2 0
      csrSync/config.go
  8. 6 4
      csrSync/config.json
  9. 1 1
      csrSync/go.mod
  10. 54 26
      csrSync/job.go
  11. 7 6
      csrSync/main.go

+ 110 - 0
clueSync/autoTask.go

@@ -0,0 +1,110 @@
+package main
+
+import (
+	"log"
+	"time"
+
+	"app.yhyue.com/moapp/jybase/common"
+	"app.yhyue.com/moapp/jybase/date"
+)
+
+func autoTask() {
+	log.Println("超时未跟进定时任务开始")
+	t := time.Now()
+	nowTime := time.Now().Format(date.Date_Full_Layout)
+	for trailstatus, nexttime := range map[string]interface{}{
+		"07": t.AddDate(0, 0, -5), //待签署客户
+		"06": t.AddDate(0, 0, -3), //高意向客户
+		"05": t.AddDate(0, 0, -5), //意向客户
+		"04": t.AddDate(0, 0, -7), //潜在客户
+	} {
+		sql := `SELECT a.clue_id,a.position_id,a.seatNumber,a.out_task_status FROM dwd_f_crm_private_sea a 
+				LEFT JOIN dwd_f_crm_clue_info b ON a.clue_id=b.id 
+				WHERE b.trailstatus =?`
+		argsSelect := []interface{}{trailstatus}
+		intime := ""
+		sql += " AND a.comeintime <?"
+		nt, _ := nexttime.(time.Time)
+		intime = nt.Format(date.Date_Short_Layout) + " 00:00:00"
+		argsSelect = append(argsSelect, intime)
+		log.Println(sql)
+		log.Println(argsSelect)
+		//
+		TiDb.SelectByBath(100, func(l *[]map[string]interface{}) bool {
+			for _, v := range *l {
+				clueId := common.Int64All(v["clue_id"])
+				position_id := common.Int64All(v["position_id"])
+				out_task_status := common.IntAll(v["out_task_status"])
+				args2 := []interface{}{clueId}
+				//获取跟进内容
+				sql1 := `select COUNT(1) FROM dwd_f_crm_trail_content WHERE clue_id =?;`
+				sql2 := `SELECT COUNT(1) FROM dwd_f_crm_trail_content WHERE clue_id =? `
+				if intime != "" {
+					sql2 += ` and createtime > ?`
+					args2 = append(args2, intime)
+				}
+				//保留未跟进线索
+				if c1, c2 := TiDb.CountBySql(sql1, clueId), TiDb.CountBySql(sql2, args2...); (c1 != 0 && c2 > 0) || out_task_status == 1 {
+					log.Println("不满足线索过滤", clueId)
+					continue
+				}
+				if TiDb.Update("dwd_f_crm_private_sea", map[string]interface{}{"clue_id": clueId}, map[string]interface{}{
+					"is_task":    1,
+					"task_time":  nowTime,
+					"tasktime":   time.Now().Format(date.Date_Short_Layout) + " 10:00:00",
+					"taskstatus": 0,
+					"tasksource": "超时未跟进自动加车",
+				}) {
+					TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
+						"clue_id":     clueId,
+						"position_id": position_id,
+						"change_type": "加入任务车",
+						"new_value":   "超时未跟进自动加车",
+						"createtime":  nowTime,
+						"BCPCID":      common.GetRandom(32),
+						"operator_id": -1,
+					})
+				}
+			}
+			return true
+		}, sql, argsSelect...)
+	}
+	log.Println("超时未跟进定时任务结束")
+}
+
+func autoTasks() {
+	log.Println("按照跟进时间提前一天进入任务车定时任务开始")
+	nowTime2 := time.Now().Format(date.Date_Full_Layout)
+	nextTime := time.Now().AddDate(0, 0, 1).Format(date.Date_Full_Layout)
+	TiDb.SelectByBath(100, func(l *[]map[string]interface{}) bool {
+		for _, v := range *l {
+			clueId := common.Int64All(v["clue_id"])
+			position_id := common.Int64All(v["position_id"])
+			out_task_status := common.IntAll(v["out_task_status"])
+			if out_task_status != 1 {
+				if TiDb.Update("dwd_f_crm_private_sea", map[string]interface{}{"clue_id": clueId}, map[string]interface{}{
+					"is_task":    1,
+					"task_time":  nowTime2,
+					"tasktime":   nowTime2,
+					"taskstatus": 0,
+					"tasksource": "即将到达下次跟进时间",
+				}) {
+					TiDb.Insert("dwd_f_crm_clue_change_record", map[string]interface{}{
+						"clue_id":     clueId,
+						"position_id": position_id,
+						"change_type": "加入任务车",
+						"new_value":   "即将到达下次跟进时间",
+						"createtime":  nowTime2,
+						"BCPCID":      common.GetRandom(32),
+						"operator_id": -1,
+					})
+				}
+			}
+		}
+		return true
+	}, `SELECT a.clue_id,a.position_id,a.seatNumber,a.out_task_status FROM dwd_f_crm_private_sea a 
+				LEFT JOIN dwd_f_crm_clue_info b ON a.clue_id=b.id 
+				LEFT JOIN dwd_f_crm_trail_content c ON c.clue_id=b.id 
+				WHERE c.next_time >= "`+nowTime2+`" and c.next_time <= "`+nextTime+`"`)
+	log.Println("按照跟进时间提前一天进入任务车定时任务结束")
+}

+ 4 - 0
clueSync/config.go

@@ -14,6 +14,7 @@ type (
 		CornExp4        string `json:"cornexp4"`
 		CornExp5        string `json:"cornexp5"`
 		CornExp6        string `json:"cornexp6"`
+		CornExp7        string `json:"cornexp7"`
 		LastOrderId     int    `json:"lastOrderId"`
 		LastUserId      string `json:"lastUserId"`
 		LastId          string `json:"lastId"`
@@ -71,13 +72,16 @@ type (
 )
 
 var AreaCode = map[string]string{}
+var CodeArea = map[string]string{}
 
 func InitArea() {
 	info := TiDb.Find("d_area_code", nil, "", "", -1, -1)
 	if info != nil && len(*info) > 0 {
 		for _, m := range *info {
 			AreaCode[common.ObjToString(m["name"])] = common.ObjToString(m["code"])
+			CodeArea[common.ObjToString(m["code"])] = common.ObjToString(m["name"])
 		}
 	}
 	log.Println("AreaCodeLen ", len(AreaCode))
+	log.Println("CodeAreaLen ", len(CodeArea))
 }

+ 1 - 1
clueSync/config.json

@@ -1 +1 @@
-{"cornexp1":"0 */30 * * * ?","cornexp2":"0 */10 * * * ?","cornexp3":"0 */5 * * * ?","cornexp4":"0 0 0 */1 * ? ","cornexp5":"0 */5 * * * ?","cornexp6":"0 */10 * * * ?","lastOrderId":172508,"lastUserId":"644101e58b6d74a60a09aec7","lastId":"6440faf7bd4ea1862af84c56","lastOrderTime":"2023-04-25 00:00:00","lastUserTime":"2023-04-25 00:00:00","lastSubscribeId":"64473e36c572141d78ec7a03","countLimit":1000,"tiDb":{"host":"192.168.3.149","port":4000,"database":"jianyu_subjectdb_test","user":"root","password":"Tibi#20211222","poolsize":20,"maxidle":40,"maxleft":40},"baseService":{"host":"192.168.3.217","port":4000,"database":"base_service","user":"root","password":"=PDT49#80Z!RVv52_z","poolsize":20,"maxidle":40,"maxleft":40},"mysql":{"host":"192.168.3.149","port":3306,"database":"jianyu","user":"root","password":"Topnet123","poolsize":20,"maxidle":40,"maxleft":40},"mgo":{"address":"192.168.3.206:27080","dbName":"qfw","dbSize":20},"mgoLog":{"address":"192.168.3.206:27090","dbName":"qfw","dbSize":20,"user":"admin","password":"123456"},"es":{"address":"http://192.168.3.206:9800","dbSize":20}}
+{"cornexp1":"0 */30 * * * ?","cornexp2":"0 */10 * * * ?","cornexp3":"0 */5 * * * ?","cornexp4":"0 0 0 */1 * ? ","cornexp5":"0 */5 * * * ?","cornexp6":"0 */10 * * * ?","cornexp7":"","lastOrderId":172508,"lastUserId":"644101e58b6d74a60a09aec7","lastId":"6440faf7bd4ea1862af84c56","lastOrderTime":"2023-04-25 00:00:00","lastUserTime":"2023-04-25 00:00:00","lastSubscribeId":"64473e36c572141d78ec7a03","countLimit":1000,"tiDb":{"host":"192.168.3.149","port":4000,"database":"jianyu_subjectdb_test","user":"root","password":"Tibi#20211222","poolsize":20,"maxidle":40,"maxleft":40},"baseService":{"host":"192.168.3.217","port":4000,"database":"base_service","user":"root","password":"=PDT49#80Z!RVv52_z","poolsize":20,"maxidle":40,"maxleft":40},"mysql":{"host":"192.168.3.149","port":3306,"database":"jianyu","user":"root","password":"Topnet123","poolsize":20,"maxidle":40,"maxleft":40},"mgo":{"address":"192.168.3.206:27080","dbName":"qfw","dbSize":20},"mgoLog":{"address":"192.168.3.206:27090","dbName":"qfw","dbSize":20,"user":"admin","password":"123456"},"es":{"address":"http://192.168.3.206:9800","dbSize":20}}

+ 58 - 20
clueSync/job.go

@@ -4,6 +4,7 @@ import (
 	"database/sql"
 	"fmt"
 	"log"
+	"strings"
 	"time"
 
 	"app.yhyue.com/moapp/jybase/common"
@@ -293,26 +294,35 @@ func SaveClue(item, userId, uId, top_cluetype, sub_cluetype, topname, subname, c
 
 func UpdateClue(data map[string]interface{}, saleData []map[string]interface{}, item, userId, uId, top_cluetype, sub_cluetype, topname, subname, cluename, name, saleName, phone, position, department, industry, follow_project_area, role, seatNumber string, positionId int64) {
 	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")
+	nowTimes := time.Unix(time.Now().Unix()+3600*12, 0).Format("2006-01-02 15:04:05")
 	//trailstatus = 无意向 为变更线索状态
 	//没有变更所属人查任务车,有车不变
 	trailstatus := common.ObjToString(data["trailstatus"])
 	clueId := common.Int64All(data["id"])
 	is_assign := common.IntAll(data["is_assign"])
-	oldsaleName, oldTaskTime, taskTime := "", "", ""
+	oldsaleName, oldTaskTime, taskTime, is_task, taskstatus := "", "", "", 0, 0
 	//已在任务车的判断任务时间
 	privateData := TiDb.FindOne("dwd_f_crm_private_sea", map[string]interface{}{"clue_id": clueId}, "", "")
 	if privateData != nil && len(*privateData) > 0 {
 		oldTaskTime = common.ObjToString((*privateData)["tasktime"])
+		is_task = common.IntAll(data["is_task"])
+		taskstatus = common.IntAll(data["taskstatus"])
 	}
-	if oldTaskTime != "" {
-		t1, err := time.Parse("2006-01-02 15:04:05", oldTaskTime)
-		if err == nil && time.Now().Before(t1) {
-			taskTime = nowTime
-		} else {
-			taskTime = oldTaskTime
+	if taskstatus == 1 || is_task == 0 {
+		taskTime = common.ObjToString(common.If(item != "users", nowTime, nowTimes))
+	} else {
+		if is_task == 1 {
+			if oldTaskTime != "" {
+				t1, err := time.Parse("2006-01-02 15:04:05", oldTaskTime)
+				if err == nil && time.Now().Before(t1) {
+					taskTime = nowTime
+				} else {
+					taskTime = oldTaskTime
+				}
+			}
 		}
 	}
+
 	clueUpdateData := map[string]interface{}{
 		"is_assign":    1,
 		"updatetime":   nowTime,
@@ -533,13 +543,23 @@ func UpdateClue(data map[string]interface{}, saleData []map[string]interface{},
 				})
 			}
 			if old_follow_project_area != follow_project_area {
+				old_area, old_area_arr := "", []string{}
+				new_area, new_area_arr := "", []string{}
+				for _, v := range strings.Split(old_follow_project_area, ",") {
+					old_area_arr = append(old_area_arr, CodeArea[v])
+				}
+				for _, v := range strings.Split(follow_project_area, ",") {
+					new_area_arr = append(new_area_arr, CodeArea[v])
+				}
+				old_area = strings.Join(old_area_arr, ",")
+				new_area = strings.Join(new_area_arr, ",")
 				updateId10 = TiDb.InsertByTx(tx, "dwd_f_crm_clue_change_record", map[string]interface{}{
 					"clue_id":      clueId,
 					"position_id":  common.If(trailstatus == "00" || trailstatus == "01", positionId, common.Int64All(data["position_id"])),
 					"change_field": "follow_project_area",
 					"change_type":  "基本信息变更",
-					"old_value":    common.If(old_follow_project_area != "", old_follow_project_area, "/"),
-					"new_value":    common.If(follow_project_area != "", follow_project_area, "/"),
+					"old_value":    common.If(old_area != "", old_area, "/"),
+					"new_value":    common.If(new_area != "", new_area, "/"),
 					"createtime":   nowTime,
 					"BCPCID":       BCPCID,
 					"operator_id":  -1,
@@ -602,22 +622,40 @@ func UpdateClue(data map[string]interface{}, saleData []map[string]interface{},
 }
 
 func getAreaCode(userId string) (code string) {
-	followData := Base.FindOne("follow_project_monitor", map[string]interface{}{"s_userid": userId}, "", "")
+	followData := Base.Find("follow_project_monitor", map[string]interface{}{"s_userid": userId}, "", "", -1, -1)
+	sidArr := []string{}
 	if followData != nil && len(*followData) > 0 {
-		infoId := common.ObjToString((*followData)["s_id"])
-		biddingData := Es.GetByIdField("bidding", "bidding", infoId, "")
+		for _, v := range *followData {
+			infoId := common.ObjToString(v["s_id"])
+			sidArr = append(sidArr, infoId)
+		}
+	}
+	if len(sidArr) > 0 {
+		query := `{"query": {"bool": {"must": [{"terms": {"_id": ["%s"]}}],"must_not": [],"should": []}}}`
+		query = fmt.Sprintf(query, strings.Join(sidArr, `","`))
+		biddingData := Es.Get("bidding", "bidding", query)
 		if biddingData != nil && len(*biddingData) > 0 {
-			area := common.ObjToString((*biddingData)["area"])
-			address := common.ObjToString((*biddingData)["city"])
-			if address == "" {
-				address = area
+			codeMap := map[string]string{}
+			codeArr := []string{}
+			for _, v := range *biddingData {
+				area := common.ObjToString(v["area"])
+				address := common.ObjToString(v["city"])
+				if address == "" {
+					address = area
+				}
+				codeMap[address] = AreaCode[address]
+			}
+			if len(codeMap) > 0 {
+				for _, v := range codeMap {
+					codeArr = append(codeArr, v)
+				}
 			}
-			areaData := TiDb.FindOne("d_area_code", map[string]interface{}{"name": address}, "", "")
-			if areaData != nil && len(*areaData) > 0 {
-				code = common.ObjToString((*areaData)["code"])
+			if len(codeArr) > 0 {
+				code = strings.Join(codeArr, ",")
 			}
 		}
 	}
+	log.Println("code ", code)
 	return
 }
 

+ 15 - 0
clueSync/main.go

@@ -107,6 +107,15 @@ func main() {
 			subscribeAddSync()
 		})
 		f.Start()
+		//自动进入任务车 1天一次
+		autoTask()
+		autoTasks()
+		g := cron.New()
+		g.AddFunc(cfg.CornExp7, func() {
+			autoTask()
+			autoTasks()
+		})
+		g.Start()
 		select {}
 	} else if *mode == 2 {
 		users()
@@ -133,5 +142,11 @@ func main() {
 		})
 		e.Start()
 		select {}
+	} else if *mode == 8 {
+		subscribeAllSync()
+	} else if *mode == 9 {
+		autoTask()
+	} else if *mode == 10 {
+		getAreaCode("6447753fb4f3c077da9d5336")
 	}
 }

+ 178 - 0
clueSync/subscribeAll.go

@@ -0,0 +1,178 @@
+package main
+
+import (
+	"strings"
+	"time"
+
+	"log"
+
+	"app.yhyue.com/moapp/jybase/common"
+	"app.yhyue.com/moapp/jybase/mongodb"
+)
+
+func subscribeAllSync() {
+	log.Println("订阅全量数据任务开始")
+	session := Mgo.GetMgoConn()
+	defer func() {
+		Mgo.DestoryMongoConn(session)
+	}()
+	query := map[string]interface{}{}
+	iter := session.DB(cfg.Mgo.DbName).C("user").Find(&query).Sort("_id").Iter()
+	thisData := map[string]interface{}{}
+
+	for {
+		if !iter.Next(&thisData) {
+			break
+		}
+		FormatSubscribeAllData(thisData)
+	}
+	log.Println("订阅全量数据任务结束")
+}
+
+func FormatSubscribeAllData(data map[string]interface{}) {
+	stype, types := "", ""
+	userId := mongodb.BsonIdToSId(data["_id"])
+	areaCodes := ""
+	keywords := ""
+	keyArrs := []string{}
+	if data["o_member_jy"] != nil {
+		stype = "大会员订阅"
+		types = "o_member_jy"
+	} else {
+		if data["o_vipjy"] != nil {
+			stype = "超级订阅"
+			types = "o_vipjy"
+		} else {
+			if data["o_jy"] != nil {
+				stype = "免费订阅"
+				types = "o_jy"
+			}
+		}
+	}
+	if types != "" {
+		if jy, ok := data[types].(map[string]interface{}); ok {
+			if types == "o_jy" {
+				//
+				if area, oks := jy["o_area"].(map[string]interface{}); oks {
+					areaArr := []string{}
+					for k, _ := range area {
+						areaArr = append(areaArr, AreaCode[k])
+					}
+					if len(area) == 0 {
+						areaArr = append(areaArr, AreaCode["全国"])
+					}
+					areaCodes = strings.Join(areaArr, ",")
+				}
+				//
+				akey, aok := jy["a_key"].([]map[string]interface{})
+				if !aok {
+					akeys, _ := jy["a_key"].([]interface{})
+					akey = common.ObjArrToMapArr(akeys)
+				}
+				for _, v := range akey {
+					keysArr, asok := v["key"].([]string)
+					if !asok {
+						keysArr_s, _ := v["key"].([]interface{})
+						keysArr = common.ObjArrToStringArr(keysArr_s)
+					}
+					for _, key := range keysArr {
+						keyArrs = append(keyArrs, key)
+					}
+				}
+			} else if types == "o_vipjy" {
+				if area, oks := jy["area"].(map[string]interface{}); oks {
+					areaArr := []string{}
+					for k, _ := range area {
+						areaArr = append(areaArr, AreaCode[k])
+					}
+					if len(area) == 0 {
+						areaArr = append(areaArr, AreaCode["全国"])
+					}
+					areaCodes = strings.Join(areaArr, ",")
+				}
+				items, aok := jy["items"].([]map[string]interface{})
+				if !aok {
+					itemss, _ := jy["items"].([]interface{})
+					items = common.ObjArrToMapArr(itemss)
+				}
+				for _, v := range items {
+					akey, iok := v["a_key"].([]map[string]interface{})
+					if !iok {
+						akeys, _ := v["a_key"].([]interface{})
+						akey = common.ObjArrToMapArr(akeys)
+					}
+					for _, v := range akey {
+						keysArr, asok := v["key"].([]string)
+						if !asok {
+							keysArr_s, _ := v["key"].([]interface{})
+							keysArr = common.ObjArrToStringArr(keysArr_s)
+						}
+						for _, key := range keysArr {
+							keyArrs = append(keyArrs, key)
+						}
+					}
+				}
+			} else {
+				if area, oks := jy["o_area"].(map[string]interface{}); oks {
+					areaArr := []string{}
+					for k, _ := range area {
+						areaArr = append(areaArr, AreaCode[k])
+					}
+					if len(area) == 0 {
+						areaArr = append(areaArr, AreaCode["全国"])
+					}
+					areaCodes = strings.Join(areaArr, ",")
+				}
+				if jy["o_area"] == nil {
+					areaCodes = AreaCode["全国"]
+				}
+				items, aok := jy["a_items"].([]map[string]interface{})
+				if !aok {
+					itemss, _ := jy["a_items"].([]interface{})
+					items = common.ObjArrToMapArr(itemss)
+				}
+				for _, v := range items {
+					akey, iok := v["a_key"].([]map[string]interface{})
+					if !iok {
+						akeys, _ := v["a_key"].([]interface{})
+						akey = common.ObjArrToMapArr(akeys)
+					}
+					for _, v := range akey {
+						keysArr, asok := v["key"].([]string)
+						if !asok {
+							keysArr_s, _ := v["key"].([]interface{})
+							keysArr = common.ObjArrToStringArr(keysArr_s)
+						}
+						for _, key := range keysArr {
+							keyArrs = append(keyArrs, key)
+						}
+					}
+				}
+			}
+			if len(keyArrs) > 0 {
+				keywords = strings.Join(keyArrs, ",")
+			}
+		}
+		start := time.Now().Format("2006-01-02") + " 00:00:00"
+		end := time.Now().Format("2006-01-02") + " 23:59:59"
+		nowTime := time.Now().Format("2006-01-02 15:04:05")
+		subscribeData := TiDb.SelectBySql(`select * from dwd_f_userbase_subscribe_info where userid = "` + userId + `" and updatetime >= "` + start + `" and updatetime <= "` + end + `"`)
+		if subscribeData != nil && len(*subscribeData) > 0 {
+			TiDb.Update("dwd_f_userbase_subscribe_info", map[string]interface{}{"id": common.IntAll((*subscribeData)[0]["id"])}, map[string]interface{}{
+				"updatetime":         nowTime,
+				"subscribe_areas":    areaCodes,
+				"subscribe_keywords": keywords,
+				"member_type":        stype,
+				"userid":             userId,
+			})
+		} else {
+			TiDb.Insert("dwd_f_userbase_subscribe_info", map[string]interface{}{
+				"userid":             userId,
+				"updatetime":         nowTime,
+				"subscribe_areas":    areaCodes,
+				"subscribe_keywords": keywords,
+				"member_type":        stype,
+			})
+		}
+	}
+}

+ 2 - 0
csrSync/config.go

@@ -3,6 +3,8 @@ package main
 type (
 	Config struct {
 		CornExp1 string `json:"cornexp1"`
+		KeyId    string `json:"keyId"`
+		Key      string `json:"key"`
 		TiDb     struct {
 			Host        string `json:"host"`
 			Port        int    `json:"port"`

+ 6 - 4
csrSync/config.json

@@ -1,7 +1,9 @@
 {
 	"cornexp1": "0 */30 * * * ?",
+	"keyId": "AKIDAE8pMkyGJ6qRvERchZCiCdzDmETSCqIb",
+	"key": "MUQ8aorfEXbQWfo2FH5jCUddT9ufK2jG",
 	"tiDb": {
-		"host": "127.0.0.1",
+		"host": "192.168.3.149",
 		"port": 4000,
 		"database": "Call_Accounting",
 		"user": "root",
@@ -11,9 +13,9 @@
 		"maxleft": 40
 	},
 	"bath": 100,
-	"chan": 5,
-	"pollCount": 5,
+	"chan": 10,
+	"pollCount": 6,
 	"waitingTime": 60,
 	"doingTime": 60,
-	"voiceRecordId": 1
+	"voiceRecordId": 1163472
 }

+ 1 - 1
csrSync/go.mod

@@ -1,4 +1,4 @@
-module clueSync
+module csrSync
 
 go 1.14
 

+ 54 - 26
csrSync/job.go

@@ -1,26 +1,29 @@
 package main
 
 import (
-	util "app.yhyue.com/moapp/jybase/common"
 	"fmt"
-	monitor "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/asr/v20190614"
+	"log"
+	"time"
+
+	util "app.yhyue.com/moapp/jybase/common"
+	asr "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/asr/v20190614"
 	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
 	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
 	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
-	"log"
-	"time"
 )
 
+var client *asr.Client
+
 func job() {
 	log.Println("语音识别定时任务开始")
 	credential := common.NewCredential(
-		"keyid",
-		"key",
+		cfg.KeyId,
+		cfg.Key,
 	)
 	cpf := profile.NewClientProfile()
-	cpf.HttpProfile.Endpoint = "monitor.tencentcloudapi.com"
-	client, _ = monitor.NewClient(credential, "ap-shanghai", cpf)
-	sql := `SELECT id,MonitorFilename FROM voice_record WHERE %s MonitorFilename <> '' AND  ISNULL(callText) ORDER  BY createTime DESC `
+	cpf.HttpProfile.Endpoint = "asr.tencentcloudapi.com"
+	client, _ = asr.NewClient(credential, "ap-guangzhou", cpf)
+	sql := `SELECT id,MonitorFilename FROM voice_record WHERE %s MonitorFilename <> '' AND CallTimeLength > 0 AND ISNULL(callText) ORDER BY createTime DESC `
 	addSql := ``
 	if cfg.VoiceRecordId > 0 {
 		addSql = fmt.Sprintf("id > %d  AND ", cfg.VoiceRecordId)
@@ -38,37 +41,41 @@ func job() {
 		return true
 	}, sql) // 需要加where进行增量
 	log.Println("语音识别定时任务结束,id:", cfg.VoiceRecordId)
+	util.WriteSysConfig(&cfg)
 }
 
 // FormatData 获取TaskId 并获取录音识别结果
 func FormatData(data map[string]interface{}) {
+	log.Println("开始 ", data["id"])
 	defer util.Catch()
-	request := monitor.NewCreateRecTaskRequest()
+	request := asr.NewCreateRecTaskRequest()
 	request.EngineModelType = common.StringPtr("8k_zh")
 	request.ChannelNum = common.Uint64Ptr(1)
-	request.SourceType = common.Uint64Ptr(0)
+	request.SpeakerDiarization = common.Int64Ptr(1)
+	request.SpeakerNumber = common.Int64Ptr(2)
 	request.ResTextFormat = common.Uint64Ptr(0)
+	request.SourceType = common.Uint64Ptr(0)
 	request.Url = common.StringPtr(util.ObjToString(data["MonitorFilename"]))
+
 	response, err := client.CreateRecTask(request)
 	if _, ok := err.(*errors.TencentCloudSDKError); ok {
 		<-ch
 		fmt.Printf("An API error has returned: %s", err)
 		return
 	}
-	if err != nil {
-		<-ch
-		panic(err)
-		return
-	}
+	fmt.Printf("结果======%s", response.ToJsonString())
 	var (
 		recordId = util.Int64All(data["id"])
 		pollTime = map[int64]int{}
 		//获取 response.Response.Data.TaskId
 		//查询第二个接口: 查询任务结果  需要轮询
-		taskId   = response.Response.Data.TaskId
-		requests = monitor.NewDescribeTaskStatusRequest()
+		taskId = response.Response.Data.TaskId
 	)
-	requests.TaskId = taskId
+	if taskId == nil {
+		return
+	}
+	// requests := asr.NewDescribeTaskStatusRequest()
+	// requests.TaskId = taskId
 L:
 	for {
 		if pollTime[recordId] > cfg.PollCount {
@@ -76,11 +83,15 @@ L:
 			break L
 		}
 		pollTime[recordId] += 1
-		r, errs := client.DescribeTaskStatus(requests)
-		log.Println(r, errs)
-		if errs != nil {
-			log.Println("根据taskId 请求语音识别结果异常:", errs.Error())
-			break L
+		requestss := asr.NewDescribeTaskStatusRequest()
+		log.Println("任务id ", *taskId)
+		requestss.TaskId = taskId
+		r, errs := client.DescribeTaskStatus(requestss)
+		log.Println("查询结果======", r.ToJsonString(), errs)
+		if _, oks := errs.(*errors.TencentCloudSDKError); oks {
+			fmt.Printf("An API error has returned: %s", errs)
+			time.Sleep(time.Duration(cfg.WaitingTime) * time.Second)
+			continue L
 		}
 		switch *r.Response.Data.StatusStr {
 		case "success":
@@ -94,9 +105,26 @@ L:
 			time.Sleep(time.Duration(cfg.DoingTime) * time.Second)
 			continue L
 		case "failed":
-			if updateVoiceRecord(*r.Response.Data.ErrorMsg, recordId) {
-				break L
+			log.Println("转换失败,再次转换")
+			requestsss := asr.NewCreateRecTaskRequest()
+			requestsss.EngineModelType = common.StringPtr("8k_zh")
+			requestsss.ChannelNum = common.Uint64Ptr(1)
+			requestsss.SpeakerDiarization = common.Int64Ptr(1)
+			requestsss.SpeakerNumber = common.Int64Ptr(2)
+			requestsss.ResTextFormat = common.Uint64Ptr(0)
+			requestsss.SourceType = common.Uint64Ptr(0)
+			requestsss.Url = common.StringPtr(util.ObjToString(data["MonitorFilename"]))
+
+			responses, errss := client.CreateRecTask(requestsss)
+			if _, ok := errss.(*errors.TencentCloudSDKError); ok {
+				<-ch
+				fmt.Printf("An API error has returned: %s", errss)
+				return
 			}
+			taskId = responses.Response.Data.TaskId
+			log.Println("任务id ", *taskId)
+			time.Sleep(time.Duration(cfg.WaitingTime) * time.Second)
+			continue L
 		}
 	}
 	<-ch

+ 7 - 6
csrSync/main.go

@@ -3,7 +3,6 @@ package main
 import (
 	"flag"
 	"fmt"
-	monitor "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/asr/v20190614"
 	"log"
 
 	"app.yhyue.com/moapp/jybase/common"
@@ -12,11 +11,10 @@ import (
 )
 
 var (
-	cfg    = new(Config)
-	TiDb   *mysql.Mysql
-	mode   = flag.Int("m", 1, "")
-	client *monitor.Client
-	ch     chan bool
+	cfg  = new(Config)
+	TiDb *mysql.Mysql
+	mode = flag.Int("m", 1, "")
+	ch   chan bool
 )
 
 func main() {
@@ -43,5 +41,8 @@ func main() {
 		})
 		a.Start()
 		select {}
+	} else if *mode == 2 {
+		job()
+		select {}
 	}
 }