Prechádzať zdrojové kódy

release: tmr集团1.0版本

Yi 1 rok pred
rodič
commit
a5b7c8c9cf

BIN
dist.zip


+ 4 - 2
http/handle/api/lpplandtl.go

@@ -41,11 +41,12 @@ func GetLpplandtl(c *gin.Context) {
 		fpdetail.ptsid,
 		fpdetail.times,
 		fpdetail.cowcount,
-		fpdetail.ccountradio
+		fpdetail.ccountradio,ifnull(tmr.volume,0)volume
 		FROM
 		  lpplandtl1
 		inner join  fpdetail
 		on  lpplandtl1.fpdid= fpdetail.id and lpplandtl1.pastureid = fpdetail.pastureid
+		left join tmr on tmr.id =lpplandtl1.tmrid
 		WHERE lpplandtl1.pastureid = ?   and lpplandtl1.lweight>0 and lpplandtl1.lppid = ?
 		`
 	// sqlStr += " and times = ? "
@@ -91,11 +92,12 @@ func GetLpplandtlDay(c *gin.Context) {
 		fpdetail.ptsid,
 		fpdetail.times,
 		fpdetail.cowcount,
-		fpdetail.ccountradio
+		fpdetail.ccountradio,ifnull(tmr.volume,0)volume
 		FROM
 		  lpplandtl1date as lpplandtl1
 		inner join  fpdetail
 		on  lpplandtl1.fpdid= fpdetail.id and lpplandtl1.pastureid = fpdetail.pastureid
+		left join tmr on tmr.id =lpplandtl1.tmrid
 		WHERE lpplandtl1.pastureid = ?   and lpplandtl1.lweight>0 and lpplandtl1.lppid = ? and lpplandtl1.date = ?
 		`
 	// sqlStr += " and times = ? "

+ 853 - 70
http/handle/api/ops.go

@@ -1490,6 +1490,18 @@ func ExecDataByConfig(c *gin.Context) {
 				tempCommon["jwt_username"] = tempv.(string)
 			}
 
+			for _, paramvalue := range tempval {
+				fmt.Println(paramvalue["name"])
+				if paramvalue["name"].(string) == "updateBigFP" {
+					err = updateLpplandtlInfo(tx, paramvalue["parammaps"].(map[string]interface{}))
+					if err != nil {
+						msg := geterrmsg(err.Error())
+						appG.Response(http.StatusOK, e.ERROR, msg)
+						return
+					}
+				}
+			}
+
 			for _, paramvalue := range tempval {
 				if _, ok := paramvalue["resultname"]; !ok {
 					paramvalue["resultname"] = paramvalue["name"]
@@ -2995,7 +3007,7 @@ func UpdateFTdetail(c *gin.Context) {
 
 	fsion := gofasion.NewFasion(string(dataByte))
 	// parammaps := fsion.Get("parammaps")
-	createdate := fsion.Get("createdate").ValueStr()
+	createdate := time.Now().Format("2006-01-02 15:04:05")
 	err := json.Unmarshal(dataByte, &tempval_)
 	if err != nil {
 		appG.Response(http.StatusOK, e.ERROR, false)
@@ -3184,13 +3196,13 @@ func UpdateFTdetail(c *gin.Context) {
 
 						weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
 						oldweight, _ := strconv.ParseFloat(old["weight"].(string), 64)
+						if weight > oldweight {
+							return
+						}
 
 						var w float64
 						var status int
 
-						if fpd["barname"].(string) == "D1" {
-							fmt.Println("1")
-						}
 						if weight < oldweight {
 							if weight >= 0 {
 								return
@@ -3336,10 +3348,10 @@ func UpdateFTdetail(c *gin.Context) {
 		// if oldFpd["id"].(int64) == newFpd["id"].(int64) && oldFpd["times"].(int64) == newFpd["times"].(int64) {
 		// 	if oldFpd["tratio"].(string) != newFpd["tratio"].(string) || oldFpd["weight"].(string) != newFpd["weight"].(string) {
 		// go func() {
-		_, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
-					 values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
+		_, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate,userId)
+					 values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
 			newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
-			newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
+			newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now, fsion.Get("userId").ValueStr()).Execute()
 		if err != nil {
 			logs.Error(err)
 			appG.Response(http.StatusOK, e.ERROR, false)
@@ -3358,13 +3370,13 @@ func UpdateFTdetail(c *gin.Context) {
 		// if oldLpplandtl1["lweight"] != newLpplandtl1["lweight"] {
 		// go func() {
 		_, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
-						background,cowcount,ccountradio,lweighthis,createdate)
-					values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
+						background,cowcount,ccountradio,lweighthis,createdate,userId)
+					values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
 			newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
 			newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
 			newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
 			newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
-			newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
+			newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
 		if err != nil {
 			logs.Error(err)
 			appG.Response(http.StatusOK, e.ERROR, false)
@@ -3383,13 +3395,13 @@ func UpdateFTdetail(c *gin.Context) {
 		// 	oldFeedp["ftweight"].(string) != newFeedp["ftweight"].(string) {
 		// go func() {
 		_, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
-					ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
-				values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
+					ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate,userId)
+				values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
 			newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
 			newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
 			newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
 			newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
-			newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
+			newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now, fsion.Get("userId").ValueStr()).Execute()
 		if err != nil {
 			logs.Error(err)
 			appG.Response(http.StatusOK, e.ERROR, false)
@@ -3433,7 +3445,7 @@ func UpdateFpdetailBar(c *gin.Context) {
 	tx := restful.Engine.NewSession()
 	tx.Begin()
 
-	fpdList, err := tx.SQL(` select  id,ifnull(ROUND((1-ptsrate)*weight,2),"") weight,ptuse  from fpdetail where pastureid = ?  and barid = ? order by times `,
+	fpdList, err := tx.SQL(` select  id,ifnull(ROUND((1-ptsrate)*weight,2),"") weight,ptuse  from fpdetail where pastureid = ?  and barid = (select barid from feedp where id = ? )  order by times `,
 		pastureid, id).Query().List()
 	if err != nil {
 		logs.Error(err)
@@ -3484,13 +3496,15 @@ func UpdateFpdetailBar(c *gin.Context) {
 							return
 						}
 					} else {
-						_, err := tx.SQL(` update   lpplandtl1 set lweight = ? where id = ? `, lppland["lweight"].(float64)-weight, lppland["id"]).Execute()
-						if err != nil {
-							tx.Rollback()
-							logs.Error(err)
-							appG.Response(http.StatusOK, e.ERROR, false)
-							return
-						}
+
+						// _, err := tx.SQL(` update   lpplandtl1 set lweight = ?-? where id = ? `, lppland["lweight"], weight, lppland["id"]).Execute()
+						// _, err := tx.SQL(` update   lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
+						// if err != nil {
+						// 	tx.Rollback()
+						// 	logs.Error(err)
+						// 	appG.Response(http.StatusOK, e.ERROR, false)
+						// 	return
+						// }
 						weight = 0
 						break
 					}
@@ -3508,13 +3522,13 @@ func UpdateFpdetailBar(c *gin.Context) {
 		ftmap["ptsid"] = list.Get("ptsid").ValueStr()
 		// fmt.Println(ftmap)
 
-		fpdDataList, err := tx.SQL(`select * from (SELECT TRIM(id) id,times,tratio,ifnull(ROUND(ptsrate*weight,2)-ptsuse,"") weight,TRIM(barid) barid,TRIM(pastureid) pastureid,TRIM(ptid) ptid,TRIM(ptsid ) ptsid ,
+		fpdDataList, err := tx.SQL(`select * from (SELECT TRIM(id) id,times,tratio,ifnull(ROUND(ptsrate*weight,2)-ptsuse,"") weight,TRIM(barid) barid,TRIM(pastureid) pastureid,TRIM(ptid) ptid,TRIM(-1 ) ptsid ,
 			(select bname  from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,0 AS fttype,cowcount,ccountradio,1 isfill  FROM fpdetail
-			WHERE fpdetail.pastureid = ?   and barid = ? and  times = ?
+			WHERE fpdetail.pastureid = ?   and barid =(select barid from feedp where id = ? )  and  times = ?
 			UNION
 			SELECT TRIM(id) id,times,tratio,ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,"") weight,TRIM(barid) barid,TRIM(pastureid) pastureid,TRIM(ptid) ptid,TRIM(ptsid ) ptsid ,
 			(select bname  from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,1 AS fttype,cowcount,ccountradio,0 isfill  FROM fpdetail
-			WHERE fpdetail.pastureid = ?  and barid = ? and  times = ? ) t
+			WHERE fpdetail.pastureid = ?  and barid = (select barid from feedp where id = ? )  and  times = ? ) t
 			order by t.barname,t.times`, pastureid, id, ftmap["times"], pastureid, id, ftmap["times"]).Query().List()
 		// fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
 		if err != nil {
@@ -3546,7 +3560,7 @@ func UpdateFpdetailBar(c *gin.Context) {
 
 				var w float64
 				var status int
-
+				fmt.Println(ftmap["new"].(float64), ftmap["old"].(float64))
 				if ftmap["new"].(float64) < ftmap["old"].(float64) {
 					if weight >= 0 {
 						continue
@@ -3554,7 +3568,8 @@ func UpdateFpdetailBar(c *gin.Context) {
 					w = weight
 					status = 0
 				} else {
-					if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
+					// continue
+					if weight <= 0 {
 						continue
 					}
 					w = weight
@@ -3653,13 +3668,13 @@ func UpdateFpdetailBar(c *gin.Context) {
 
 	for _, newLpplandtl1 := range newLpplandtl1List {
 		_, err := tx.SQL(` insert into lpplandtl1history(pastureid,lppid,barid,barname,fpdid,fttype,lweight,sort,tmrid,tmrname,
-						background,cowcount,ccountradio,lweighthis,createdate)
-					values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
+						background,cowcount,ccountradio,lweighthis,createdate,userId)
+					values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
 			newLpplandtl1["pastureid"], newLpplandtl1["lppid"], newLpplandtl1["barid"],
 			newLpplandtl1["barname"], newLpplandtl1["fpdid"], newLpplandtl1["fttype"],
 			newLpplandtl1["lweight"], newLpplandtl1["sort"], newLpplandtl1["tmrid"],
 			newLpplandtl1["tmrname"], newLpplandtl1["background"], newLpplandtl1["cowcount"],
-			newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now).Execute()
+			newLpplandtl1["ccountradio"], newLpplandtl1["lweighthis"], now, fsion.Get("userId").ValueStr()).Execute()
 		if err != nil {
 			logs.Error(err)
 			appG.Response(http.StatusOK, e.ERROR, false)
@@ -3667,33 +3682,6 @@ func UpdateFpdetailBar(c *gin.Context) {
 		}
 	}
 
-	// for _, newFpd := range newFpdDataList {
-	// 	_, err := tx.SQL(` insert into fpdetailhistory(pastureid,barid,barname,times,tratio,weight,ptsrate,cowcount,ccountradio,ptid,ptsid,ptuse,ptsuse,supplement,createdate)
-	// 				 values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, newFpd["pastureid"], newFpd["barid"], newFpd["barname"], newFpd["times"],
-	// 		newFpd["tratio"], newFpd["weight"], newFpd["ptsrate"], newFpd["cowcount"], newFpd["ccountradio"],
-	// 		newFpd["ptid"], newFpd["ptsid"], newFpd["ptuse"], newFpd["ptsuse"], newFpd["supplement"], now).Execute()
-	// 	if err != nil {
-	// 		logs.Error(err)
-	// 		appG.Response(http.StatusOK, e.ERROR, false)
-	// 		return
-	// 	}
-	// }
-	// for _, newFeedp := range newFeedpList {
-	// 	_, err := tx.SQL(` insert into feedphistory(pastureid,barname,barid,softccount,ccount,ratio,ccountratio,ftid,
-	// 				ftname,ptsfid,ptsfname,feedweight,ftweight,supplyweight,owner,createdate)
-	// 			values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
-	// 		newFeedp["pastureid"], newFeedp["barname"], newFeedp["barid"],
-	// 		newFeedp["softccount"], newFeedp["ccount"], newFeedp["ratio"],
-	// 		newFeedp["ccountratio"], newFeedp["ftid"], newFeedp["ftname"],
-	// 		newFeedp["ptsfid"], newFeedp["ptsfname"], newFeedp["feedweight"],
-	// 		newFeedp["ftweight"], newFeedp["supplyweight"], newFeedp["owner"], now).Execute()
-	// 	if err != nil {
-	// 		logs.Error(err)
-	// 		appG.Response(http.StatusOK, e.ERROR, false)
-	// 		return
-	// 	}
-	// }
-
 	appG.Response(http.StatusOK, e.SUCCESS, true)
 }
 
@@ -3840,7 +3828,7 @@ func AddFtdry(c *gin.Context) {
 		}
 
 		var actweight float64
-		actweightList, err := tx.SQL(`select ROUND(avg(actweight),2) as actweight  from ftdry  
+		actweightList, err := tx.SQL(`select ifnull(ROUND(avg(actweight),2),0) as actweight  from ftdry  
 	where barid in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ?))  
 	and operatetime  = (select date_format(operatetime ,'%Y-%m-%d') from ftdry 
 	where barid  in ( select barid from feedp where ftid in ( select ftid from feedp where barid = ? and pastureid = ? )) 
@@ -4333,10 +4321,19 @@ func FpdImportExcel(c *gin.Context) {
 				if _, ok := outentry["第三班比例(%)"]; ok {
 					dataexcel["3"] = outentry["第三班比例(%)"]
 				}
+
 				if _, ok := outentry["第四班比例(%)"]; ok {
 					dataexcel["4"] = outentry["第四班比例(%)"]
 				}
 
+				if _, ok := outentry["第五班比例(%)"]; ok {
+					dataexcel["5"] = outentry["第四班比例(%)"]
+				}
+
+				if _, ok := outentry["第六班比例(%)"]; ok {
+					dataexcel["6"] = outentry["第六班比例(%)"]
+				}
+
 				existbar, err := tx.SQL(` select id from  bar where bname = ?  and pastureid = ?  `, dataexcel["barname"], pastureid).Exist()
 				if err != nil {
 					logs.Error(err)
@@ -4354,6 +4351,7 @@ func FpdImportExcel(c *gin.Context) {
 					return
 				}
 				if !ftexist {
+					fmt.Println(dataexcel["barname"], pastureid, dataexcel["ftname"])
 					tx.SQL(` delete from lpplandtl1 where barname = ? and pastureid = ?  `, dataexcel["barname"], pastureid).Exist()
 					if err != nil {
 						logs.Error(err)
@@ -4417,12 +4415,13 @@ func FpdImportExcel(c *gin.Context) {
 					return
 				}
 
-				exist1, err := tx.SQL(` select id from  fpdetail where barname = ?  and pastureid = ?  `, dataexcel["barname"], pastureid).Exist()
+				exist1, err := tx.SQL(` select id from  fpdetail where barname = ?  and pastureid = ? and times = 1 `, dataexcel["barname"], pastureid).Exist()
 				if err != nil {
 					logs.Error(err)
 					appG.Response(http.StatusInternalServerError, e.ERROR, false)
 					return
 				}
+
 				if !exist1 {
 					_, err := tx.SQL(` insert into  fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where  bname = ? and pastureid = ? ),?,1,0,0,0,-1,-1) `,
 						pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
@@ -4431,7 +4430,14 @@ func FpdImportExcel(c *gin.Context) {
 						appG.Response(http.StatusInternalServerError, e.ERROR, false)
 						return
 					}
-
+				}
+				exist2, err := tx.SQL(` select id from  fpdetail where barname = ?  and pastureid = ? and times = 2 `, dataexcel["barname"], pastureid).Exist()
+				if err != nil {
+					logs.Error(err)
+					appG.Response(http.StatusInternalServerError, e.ERROR, false)
+					return
+				}
+				if !exist2 {
 					_, err = tx.SQL(` insert into  fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where  bname = ? and pastureid = ? ),?,2,0,0,0,-1,-1) `,
 						pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
 					if err != nil {
@@ -4439,7 +4445,15 @@ func FpdImportExcel(c *gin.Context) {
 						appG.Response(http.StatusInternalServerError, e.ERROR, false)
 						return
 					}
+				}
 
+				exist3, err := tx.SQL(` select id from  fpdetail where barname = ?  and pastureid = ? and times =3 `, dataexcel["barname"], pastureid).Exist()
+				if err != nil {
+					logs.Error(err)
+					appG.Response(http.StatusInternalServerError, e.ERROR, false)
+					return
+				}
+				if !exist3 {
 					_, err = tx.SQL(` insert into  fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where  bname = ? and pastureid = ? ),?,3,0,0,0,-1,-1) `,
 						pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
 					if err != nil {
@@ -4447,7 +4461,14 @@ func FpdImportExcel(c *gin.Context) {
 						appG.Response(http.StatusInternalServerError, e.ERROR, false)
 						return
 					}
-
+				}
+				exist4, err := tx.SQL(` select id from  fpdetail where barname = ?  and pastureid = ? and times = 4 `, dataexcel["barname"], pastureid).Exist()
+				if err != nil {
+					logs.Error(err)
+					appG.Response(http.StatusInternalServerError, e.ERROR, false)
+					return
+				}
+				if !exist4 {
 					_, err = tx.SQL(` insert into  fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where  bname = ? and pastureid = ? ),?,4,0,0,0,-1,-1) `,
 						pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
 					if err != nil {
@@ -4456,6 +4477,36 @@ func FpdImportExcel(c *gin.Context) {
 						return
 					}
 				}
+				exist5, err := tx.SQL(` select id from  fpdetail where barname = ?  and pastureid = ? and times = 5 `, dataexcel["barname"], pastureid).Exist()
+				if err != nil {
+					logs.Error(err)
+					appG.Response(http.StatusInternalServerError, e.ERROR, false)
+					return
+				}
+				if !exist5 {
+					_, err = tx.SQL(` insert into  fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where  bname = ? and pastureid = ? ),?,5,0,0,0,-1,-1) `,
+						pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
+					if err != nil {
+						logs.Error(err)
+						appG.Response(http.StatusInternalServerError, e.ERROR, false)
+						return
+					}
+				}
+				exist6, err := tx.SQL(` select id from  fpdetail where barname = ?  and pastureid = ? and times = 6 `, dataexcel["barname"], pastureid).Exist()
+				if err != nil {
+					logs.Error(err)
+					appG.Response(http.StatusInternalServerError, e.ERROR, false)
+					return
+				}
+				if !exist6 {
+					_, err = tx.SQL(` insert into  fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where  bname = ? and pastureid = ? ),?,6,0,0,0,-1,-1) `,
+						pastureid, dataexcel["barname"], pastureid, dataexcel["barname"]).Execute()
+					if err != nil {
+						logs.Error(err)
+						appG.Response(http.StatusInternalServerError, e.ERROR, false)
+						return
+					}
+				}
 
 				upFpdSql := ` update fpdetail set  tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail 
 				where  ftid = (select  id from feedtemplet  where tname = ? and pastureid = ?  )) *  (?*(?*0.01))) ,cowcount = ? ,
@@ -4470,10 +4521,7 @@ func FpdImportExcel(c *gin.Context) {
 					appG.Response(http.StatusInternalServerError, e.ERROR, false)
 					return
 				}
-				// upFpdSql := ` update fpdetail set  tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
-				// where  ftid = (select  id from feedtemplet  where tname = ? and pastureid = ?  )) *  (?*(?*0.01))) ,cowcount = ? ,
-				// ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? )   where barname = ?
-				//   and pastureid = ? and times = ?`
+
 				var fpdargs2 []interface{}
 				fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
 					dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
@@ -4501,6 +4549,26 @@ func FpdImportExcel(c *gin.Context) {
 					appG.Response(http.StatusInternalServerError, e.ERROR, false)
 					return
 				}
+
+				var fpdargs5 []interface{}
+				fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
+					dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
+					dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
+				_, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
+				if err != nil {
+					appG.Response(http.StatusInternalServerError, e.ERROR, false)
+					return
+				}
+
+				var fpdargs6 []interface{}
+				fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
+					dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
+					dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
+				_, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
+				if err != nil {
+					appG.Response(http.StatusInternalServerError, e.ERROR, false)
+					return
+				}
 				// _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ?  and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
 
 				newList, err := tx.SQL(` select  ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,"") fweight,id,ptid,weight,times from fpdetail where barname = ? and  pastureid = ? `, dataexcel["barname"], pastureid).Query().List()
@@ -4567,7 +4635,7 @@ func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) erro
 	defer tx.Close()
 	tx.Begin()
 
-	fpdList, err := tx.SQL(` select  id,ifnull(ROUND((1-ptsrate)*weight,2),"") weight,ptuse,times  from fpdetail where pastureid = ?  and barname = ? order by times `,
+	fpdList, err := tx.SQL(` select  id,ifnull(ROUND((1-ifnull(ptsrate,0))*weight,2),"") weight,ptuse,times  from fpdetail where pastureid = ?  and barname = ? order by times `,
 		pastureid, barname).Query().List()
 	if err != nil {
 		logs.Error(err)
@@ -4575,7 +4643,7 @@ func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) erro
 
 	for _, fpd := range fpdList {
 
-		lpplandList, err := tx.SQL(` select  lppland.id,lppland.lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid 
+		lpplandList, err := tx.SQL(` select  lppland.id,ifnull(lppland.lweight,0) lweight from lpplandtl1 lppland join lpplan lpp on lpp.id = lppland.lppid 
 where lppland.pastureid = ?  and lppland.fpdid = ? and lpp.times = ?  order by lpp.sort desc  `,
 			pastureid, fpd["id"], fpd["times"]).Query().List()
 		if err != nil {
@@ -5205,7 +5273,7 @@ func GetFeedpHistory(c *gin.Context) {
 	defer tx.Close()
 
 	feedpList, err := tx.SQL(` select barid,barname,ccount,ratio,ccountratio,ftid,ftname, 
-	DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s')  as createdate    from  feedphistory  where barname = ?
+	DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s')  as createdate,(select empname from user where id = feedphistory.userId)empname    from  feedphistory  where barname = ?
 	and  createdate between ? and ?  order by createdate desc `, bar, startDate, endDate).Query().List()
 	if err != nil {
 		logs.Error(err)
@@ -5213,7 +5281,8 @@ func GetFeedpHistory(c *gin.Context) {
 		return
 	}
 
-	fpdList, err := tx.SQL(` select times,tratio,weight,  DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s')  as createdate  from  fpdetailhistory  where barname = ?
+	fpdList, err := tx.SQL(` select times,tratio,weight,  DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s')  as createdate,
+	 (select empname from user where id = fpdetailhistory.userId)empname    from  fpdetailhistory  where barname = ?
 	and  createdate between ? and ?  order by createdate desc, times asc`, bar, startDate, endDate).Query().List()
 	if err != nil {
 		logs.Error(err)
@@ -5465,7 +5534,8 @@ func UpdateRemind(c *gin.Context) {
 	noticeMsgtype.PushTime = parammaps.Get("push_time").ValueStr()
 	noticeMsgtype.IntervalTime = parammaps.Get("interval_time").ValueInt64()
 	noticeMsgtype.PushLimit = parammaps.Get("push_limit").ValueInt64()
-	noticeMsgtype.TemplateId = parammaps.Get("template_id").ValueStr()
+	// noticeMsgtype.TemplateId = parammaps.Get("template_id").ValueStr()
+	noticeMsgtype.TemplateId = "1_zBqvbzD-edg0b-O5OD1kAEMefygikcmBZACSiwX0w"
 	// noticeMsgtype. = parammaps.Get("roles_id").ValueStr()
 	noticeMsgtype.DateType = parammaps.Get("date_type").ValueInt64()
 	noticeMsgtype.CycleType = parammaps.Get("cycle_type").ValueInt64()
@@ -5736,7 +5806,7 @@ func GetFeedtempletHistory(c *gin.Context) {
 	tx := restful.Engine.NewSession()
 	defer tx.Close()
 
-	ftList, err := tx.SQL(` select *,DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate1 from feedtemplethistory  where createdate between ? and ? 
+	ftList, err := tx.SQL(` select *,DATE_FORMAT(createdate,'%Y-%m-%d %H:%i:%s') as createdate1,(select empname from user where id = feedtemplethistory.userId) empname from feedtemplethistory  where createdate between ? and ? 
 	and id = ? and pastureid = ? order by createdate desc `,
 		start, end, ftid, pastureid).Query().List()
 	if err != nil {
@@ -5757,6 +5827,7 @@ func GetFeedtempletHistory(c *gin.Context) {
 	for i, ft := range ftList {
 		fithisList, err := tx.SQL(` select fit.Eweight,fit.weight,fit.name as fname,
 		ifnull(fit.feedgroup,( select ft.feedgroup from ftdetail  ft where  ft.ftid = fit.fitid and fit.name = ft.fname )) as feedgroup,
+		(select empname from user where id = fit.userId) empname,
 		
 		ifnull(fit.autosecond ,( select ft.autosecond from ftdetail  ft where  ft.ftid = fit.fitid and fit.name = ft.fname )) as autosecond from  fit_history fit 
 		where fit.fitid = ? 
@@ -5843,6 +5914,7 @@ func GetFeedtempletHistory(c *gin.Context) {
 				data := make(map[string]interface{})
 				data["feedgroup"] = fit["feedgroup"]
 				data["fname"] = fit["fname"]
+				data["empname"] = fit["empname"]
 				if fit["Eweight"] != nil {
 					if fit["Eweight"].(string) != fit["weight"].(string) {
 						data["fweight"] = fmt.Sprintf("%v/%v", fit["Eweight"], fit["weight"])
@@ -6991,3 +7063,714 @@ func GetFormulaStatistics(c *gin.Context) {
 	resp["data2"] = data2
 	appG.Response(http.StatusOK, e.SUCCESS, resp)
 }
+
+func GetPlanData(c *gin.Context) {
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+
+	fsion := gofasion.NewFasion(string(dataByte))
+	sqlnamestr := fsion.Get("name").ValueStr()
+	sqlnamestr1 := fsion.Get("name1").ValueStr()
+	offset := fsion.Get("offset").ValueDefaultInt(0)
+	pagecount := fsion.Get("plancount").ValueDefaultInt(0)
+	returntype := fsion.Get("returntype").ValueDefaultStr("map")
+	month := fsion.Get("month").ValueDefaultStr("map")
+	logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
+	tx := restful.Engine.NewSession()
+	err := tx.Begin()
+	defer func() {
+		switch {
+		case err != nil:
+			if tx != nil {
+				tx.Rollback()
+			}
+		default:
+			if tx != nil {
+				err = tx.Commit()
+			}
+		}
+		if tx != nil {
+			tx.Close()
+		}
+	}()
+
+	sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
+	sql1, p1 := restful.GetSqlByNameDBT(sqlnamestr1, tx)
+	if sql != "" {
+		s_params := make([]interface{}, 0)
+		if fsion.HasKey("parammaps") {
+			parammaps := fsion.Get("parammaps")
+			paramslist := strings.Split(p, ",")
+			if len(paramslist) > 0 && p != "" {
+				for _, value := range paramslist {
+					if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
+						if tempv, exists := c.Get("jwt_username"); exists {
+							s_params = append(s_params, tempv.(string))
+						} else {
+							s_params = append(s_params, "")
+						}
+					} else {
+						s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
+					}
+				}
+			}
+
+		}
+
+		queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
+		if err != nil {
+			appG.Response(http.StatusOK, e.ERROR, err.Error())
+
+		} else {
+			paramslist1 := strings.Split(p1, ",")
+
+			for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
+				s_params1 := make([]interface{}, 0)
+				if len(paramslist1) > 0 && p1 != "" {
+					for _, v := range paramslist1 {
+						s_params1 = append(s_params1, value[strings.ToLower(strings.Trim(v, " "))])
+					}
+				}
+				arr, _ := tx.SQL(sql1, s_params1...).Query().List() //获取
+				for _, item := range arr {
+					trgaddressList := []string{}
+					if _, ok := item["trgaddress"]; ok {
+						trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
+						for _, str := range trgaddressList1 {
+							if str != "" {
+								trgaddressList = append(trgaddressList, str)
+							}
+						}
+					}
+					item["trgaddressList"] = trgaddressList
+				}
+				queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["arrList"] = arr
+			}
+			// var wg sync.WaitGroup
+			// for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
+			// 	wg.Add(1)
+			// 	go func(value map[string]interface{}) {
+			// 		defer wg.Done()
+			// 		_, err = tx.SQL(`update downloadedplan set  havebutton = 1 where id = ? and pastureid = ? `, value["projuctid"], value["pastureid"]).Execute()
+			// 	}(value)
+			// }
+			// wg.Wait()
+			appG.Response(http.StatusOK, e.SUCCESS, queryData)
+		}
+	} else {
+		appG.Response(http.StatusOK, e.SUCCESS, nil)
+	}
+}
+
+func PostPlanData(c *gin.Context) {
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	fsion := gofasion.NewFasion(string(dataByte))
+	logging.Info("PostRJSBData  err: ", string(dataByte))
+
+	s_params := make([]interface{}, 0)
+	tx := restful.Engine.NewSession()
+	err := tx.Begin()
+	defer func() {
+		switch {
+		case err != nil:
+			if tx != nil {
+				tx.Rollback()
+			}
+		default:
+			if tx != nil {
+				err = tx.Commit()
+			}
+		}
+		if tx != nil {
+			tx.Close()
+		}
+	}()
+	sql, p := restful.GetSqlByNameDBT("updatedownloadedplanYJ", tx)
+	sql1, p1 := restful.GetSqlByNameDBT("updated1YJ", tx)
+	sql2, p2 := restful.GetSqlByNameDBT("updated1execYJ", tx)
+	sql3, p3 := restful.GetSqlByNameDBT("updated2YJ", tx)
+	if !fsion.HasKey("parammaps") {
+		appG.Response(http.StatusOK, e.ERROR, "参数解析失败")
+		return
+	}
+	parammaps := fsion.Get("parammaps")
+
+	paramslist := strings.Split(p, ",")
+	if len(paramslist) > 0 && p != "" {
+		for _, value := range paramslist {
+			s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
+		}
+	}
+	_, err = tx.SQL(sql, s_params...).Execute()
+	if err != nil {
+		logging.Error("PostRJSBData  err: ", err)
+		msg := geterrmsg(err.Error())
+		appG.Response(http.StatusOK, e.ERROR, msg)
+		return
+	}
+
+	s_params = make([]interface{}, 0)
+	paramslist = strings.Split(p1, ",")
+	if len(paramslist) > 0 && p1 != "" {
+		for _, value := range paramslist {
+			// if value == "ID" {
+			// 	id := parammaps.Get("ID").ValueStr()
+			// 	pastureid := parammaps.Get("pastureid").ValueStr()
+			// 	datalist, err := tx.SQL(`select d2.id as id from downloadplandtl1 d1 join downloadplandtl1_exec  d2 on d1.id = d2.id  where d1.pid =  (select pid  from downloadplandtl1 where id =  ? and pastureid = ? )  and
+			// 	d1.sort = (select sort  from downloadplandtl1 where id =  ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
+			// 	if err != nil {
+			// 		logging.Error("PostRJSBData  err: ", err)
+			// 		msg := geterrmsg(err.Error())
+			// 		appG.Response(http.StatusOK, e.ERROR, msg)
+			// 		return
+			// 	}
+
+			// 	for _, item := range datalist {
+			// 		id = item["id"]
+			// 	}
+			// 	s_params = append(s_params, id)
+			// } else {
+			// 	s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
+			// }
+			s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
+		}
+	}
+	_, err = tx.SQL(sql1, s_params...).Execute()
+	if err != nil {
+		logging.Error("PostRJSBData1  err: ", err)
+		msg := geterrmsg(err.Error())
+		appG.Response(http.StatusOK, e.ERROR, msg)
+		return
+	}
+	s_params = make([]interface{}, 0)
+
+	paramslist = strings.Split(p2, ",")
+	if len(paramslist) > 0 && p2 != "" {
+		for _, value := range paramslist {
+
+			if value == "ID" {
+				id := parammaps.Get("ID").ValueStr()
+				pastureid := parammaps.Get("pastureid").ValueStr()
+				datalist, err := tx.SQL(`select d2.id as id from downloadplandtl1 d1 join downloadplandtl1_exec  d2 on d1.id = d2.id  where d1.pid =  (select pid  from downloadplandtl1 where id =  ? and pastureid = ? )  and 
+				d1.sort = (select sort  from downloadplandtl1 where id =  ? and pastureid = ? )`, id, pastureid, id, pastureid).QueryString()
+				if err != nil {
+					logging.Error("PostRJSBData  err: ", err)
+					msg := geterrmsg(err.Error())
+					appG.Response(http.StatusOK, e.ERROR, msg)
+					return
+				}
+
+				for _, item := range datalist {
+					id = item["id"]
+				}
+				s_params = append(s_params, id)
+			} else {
+				s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
+			}
+
+		}
+	}
+
+	_, err = tx.SQL(sql2, s_params...).Execute()
+	if err != nil {
+		logging.Error("PostRJSBData2  err: ", err)
+		msg := geterrmsg(err.Error())
+		appG.Response(http.StatusOK, e.ERROR, msg)
+		return
+	}
+	s_params = make([]interface{}, 0)
+
+	paramslist = strings.Split(p3, ",")
+	if len(paramslist) > 0 && p3 != "" {
+		for _, value := range paramslist {
+			s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
+		}
+	}
+	_, err = tx.SQL(sql3, s_params...).Execute()
+	if err != nil {
+		logging.Error("PostRJSBData3  err: ", err)
+		msg := geterrmsg(err.Error())
+		appG.Response(http.StatusOK, e.ERROR, msg)
+		return
+	}
+	appG.Response(http.StatusOK, e.SUCCESS, "ok")
+}
+
+func CheckFeedTrgaddress(c *gin.Context) {
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	fsion := gofasion.NewFasion(string(dataByte))
+	fclassid := fsion.Get("fclassid").ValueStr()
+	feedId := fsion.Get("feedId").ValueStr()
+	backup1 := fsion.Get("backup1").ValueStr()
+
+	backup1List := strings.Split(backup1, ",")
+	tx := restful.Engine.NewSession()
+	defer tx.Close()
+
+	// if backup1 != "" {
+	feedList, _ := tx.SQL(` select id,fname,ifnull(backup1,'') backup1 from feed where fclassid = ? and (id != ? or ? = '' ) `, fclassid, feedId, feedId).QueryString()
+	for _, feed := range feedList {
+		if feed["backup1"] == "" {
+			continue
+		}
+		feedbackupList := strings.Split(feed["backup1"], ",")
+		for _, feedbackup := range feedbackupList {
+
+			for _, backup := range backup1List {
+				if feedbackup == backup {
+					appG.Response(http.StatusOK, e.ERROR, fmt.Sprintf("数据:%s 在饲料:%s已被使用!", backup, feed["fname"]))
+					return
+				}
+			}
+		}
+	}
+	// }
+	appG.Response(http.StatusOK, e.SUCCESS, "ok")
+}
+
+func ThiGetDataByName(c *gin.Context) {
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	fsion := gofasion.NewFasion(string(dataByte))
+	sqlnamestr := fsion.Get("name").ValueStr()
+	offset := fsion.Get("offset").ValueDefaultInt(0)
+	pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
+	returntype := fsion.Get("returntype").ValueDefaultStr("map")
+
+	tx := restful.Engine.NewSession()
+	err := tx.Begin()
+	defer func() {
+		switch {
+		case err != nil:
+			logging.Error("tx.Begin 事务启动失败__error:", err)
+			if tx != nil {
+				tx.Rollback()
+			}
+		default:
+			if tx != nil {
+				err = tx.Commit()
+			}
+		}
+		if tx != nil {
+			tx.Close()
+		}
+	}()
+
+	sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
+	if sql != "" {
+		s_params := make([]interface{}, 0)
+		if fsion.HasKey("parammaps") {
+			parammaps := fsion.Get("parammaps")
+			if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
+				logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
+			}
+
+			paramslist := strings.Split(p, ",")
+			if len(paramslist) > 0 && p != "" {
+				for _, value := range paramslist {
+					if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
+						if tempv, exists := c.Get("jwt_username"); exists {
+							s_params = append(s_params, tempv.(string))
+						} else {
+							s_params = append(s_params, "")
+						}
+					} else {
+						s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
+					}
+				}
+			}
+		} else if fsion.HasKey("params") {
+			params := fsion.Get("params").Array()
+			logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
+			for _, v_params := range params {
+				s_params = append(s_params, v_params.ValueStr())
+			}
+		}
+		if returntype == "xlsx" {
+			var xlsxfile *xlsx.File
+			xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
+			//c.File("c:/dd.xlsx")
+			c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
+			c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
+			c.Header("Content-Transfer-Encoding", "binary")
+			_ = xlsxfile.Write(c.Writer)
+
+		} else {
+			if sqlnamestr == "getHomepageStr" {
+				parammaps := fsion.Get("parammaps")
+				pastureid := parammaps.Get("pastureid").ValueStr()
+				var montimeList []float64
+				var montime float64
+				var wg sync.WaitGroup
+
+				now := time.Now()
+				for i := 0; i < 30; i++ {
+					wg.Add(1)
+					nowstr := now.AddDate(0, 0, -i).Format("2006-01-02")
+					go func(nowstr string) {
+						defer wg.Done()
+						sqlstr := `select ifnull( getSLtimeDiffSINGEL ( ?, ? ), 0.0 ) as montime`
+						slTimeList, _ := restful.QueryByMap(sqlstr, 0, 0, []interface{}{pastureid, nowstr})
+						m, _ := strconv.ParseFloat(slTimeList.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"].(string), 64)
+						montimeList = append(montimeList, m)
+					}(nowstr)
+				}
+
+				queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
+				if err != nil {
+					logging.Error("GetDataByName  err: ", err)
+					msg := geterrmsg(err.Error())
+					appG.Response(http.StatusOK, e.ERROR, msg)
+				}
+
+				wg.Wait()
+				for _, m := range montimeList {
+					montime += m
+				}
+				queryData.(map[string]interface{})["list"].([]map[string]interface{})[0]["montime"] = Decimal(montime / 30)
+
+				appG.Response(http.StatusOK, e.SUCCESS, queryData)
+				return
+			}
+			queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
+			if err != nil {
+				logging.Error("GetDataByName  err: ", err)
+				msg := geterrmsg(err.Error())
+				appG.Response(http.StatusOK, e.ERROR, msg)
+			} else {
+				if sqlnamestr == "getFeedTrgaddressList" {
+					for _, item := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) {
+						trgaddressList1 := strings.Split(item["trgaddress"].(string), ",")
+						trgaddressList := []string{}
+						for _, str := range trgaddressList1 {
+							if str != "" {
+								trgaddressList = append(trgaddressList, str)
+							}
+						}
+
+						item["trgaddressList"] = trgaddressList
+					}
+				}
+				appG.Response(http.StatusOK, e.SUCCESS, queryData)
+			}
+		}
+
+	} else {
+		appG.Response(http.StatusOK, e.SUCCESS, nil)
+	}
+}
+
+// func ToggleCcount(c *gin.Context) {
+// 	appG := app.Gin{C: c}
+// 	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+// 	fsion := gofasion.NewFasion(string(dataByte))
+// 	// 0 实际 1 软件
+// 	status := fsion.Get("status").ValueDefaultInt64(0)
+// 	pastureId := fsion.Get("pastureId").ValueStr()
+
+// 	tx := restful.Engine.NewSession()
+// 	err := tx.Begin()
+// 	defer func() {
+// 		switch {
+// 		case err != nil:
+// 			logging.Error("tx.Begin 事务启动失败__error:", err)
+// 			if tx != nil {
+// 				tx.Rollback()
+// 			}
+// 		default:
+// 			if tx != nil {
+// 				err = tx.Commit()
+// 			}
+// 		}
+// 		if tx != nil {
+// 			tx.Close()
+// 		}
+// 	}()
+
+// 	barList, err := tx.SQL(`select * from bar where pastureId = ? `, pastureId).Query().List()
+// 	if err != nil {
+// 		logs.Error(err)
+// 		appG.Response(http.StatusInternalServerError, e.ERROR, false)
+// 		return
+// 	}
+// 	for _, bar := range barList {
+// 		exist, err := tx.SQL(` select id from  feedp where barname = ?  and pastureid = ?  `, bar["bname"], pastureId).Exist()
+// 		if err != nil {
+// 			logs.Error(err)
+// 			appG.Response(http.StatusInternalServerError, e.ERROR, false)
+// 			return
+// 		}
+// 		if !exist {
+// 			_, err := tx.SQL(` insert into  feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where  bname = ? and pastureid = ? ),?,?) `,
+// 				pastureId, bar["bname"], pastureId, bar["bname"], 0).Execute()
+// 			if err != nil {
+// 				logs.Error(err)
+// 				appG.Response(http.StatusInternalServerError, e.ERROR, false)
+// 				return
+// 			}
+// 		}
+// 	}
+
+// 	if status == 0 {
+// tx.Exec(`update feedp set ccount = actualcount `)
+// 	}else{
+// 		tx.Exec(`update feedp set ccount = softccount `)
+// 	}
+
+// 	feedpList, err := tx.SQL(`select * from feedp where pastureId = ? `, pastureId).Query().List()
+// 	if err != nil {
+// 		logs.Error(err)
+// 		appG.Response(http.StatusInternalServerError, e.ERROR, false)
+// 		return
+// 	}
+
+// 	for _, feedpData  :=range feedpList{
+// 		var feedpargs []interface{}
+// 		upFeedpSql := `update  feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01)  `
+// 		feedpargs = append(feedpargs, feedpData["ccount"], feedpData["ratio"], feedpData["ccount"], feedpData["ratio"])
+// 		if _, ok := feedpData["ftname"]; ok {
+// 			feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ftname"])
+// 			upFeedpSql += ` , ftid = (select id from feedtemplet where tname = ? and pastureid = ? ),ftname = ? `
+
+// 			upFeedpSql += `,ftweight = (select sum(fweight) fweight from ftdetail
+// 		where  ftid = (select  id from feedtemplet  where tname = ? and pastureid = ?  )) *  (?*(?*0.01)) `
+// 			feedpargs = append(feedpargs, feedpData["ftname"], pastureid, feedpData["ccount"], feedpData["ratio"])
+// 		} else {
+// 			upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
+// 		}
+
+// 		if _, ok := feedpData["ptsfname"]; ok {
+// 			feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ptsfname"])
+// 			upFeedpSql += ` , ptsfid = (select id from feedtemplet where tname = ? and pastureid = ? ),ptsfname = ? `
+
+// 			upFeedpSql += `,supplyweight = (select sum(fweight) fweight from ftdetail
+// 		where  ftid = (select  id from feedtemplet  where tname = ? and pastureid = ?  )) *  (?*(?*0.01))`
+// 			feedpargs = append(feedpargs, feedpData["ptsfname"], pastureid, feedpData["ccount"], feedpData["ratio"])
+// 		} else {
+// 			upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0  `
+// 		}
+// 		upFeedpSql += " where barname = ?  and pastureid = ?  "
+// 		feedpargs = append(feedpargs, feedpData["barname"], pastureid)
+// 		_, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
+// 		if err != nil {
+// 			logs.Error(err)
+// 			appG.Response(http.StatusInternalServerError, e.ERROR, false)
+// 			return
+// 		}
+
+// 		exist1, err := tx.SQL(` select id from  fpdetail where barname = ?  and pastureid = ? and times = 1 `, feedpData["barname"], pastureid).Exist()
+// 		if err != nil {
+// 			logs.Error(err)
+// 			appG.Response(http.StatusInternalServerError, e.ERROR, false)
+// 			return
+// 		}
+
+// 		if !exist1 {
+// 			_, err := tx.SQL(` insert into  fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where  bname = ? and pastureid = ? ),?,1,0,0,0,-1,-1) `,
+// 				pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
+// 			if err != nil {
+// 				logs.Error(err)
+// 				appG.Response(http.StatusInternalServerError, e.ERROR, false)
+// 				return
+// 			}
+// 		}
+// 		exist2, err := tx.SQL(` select id from  fpdetail where barname = ?  and pastureid = ? and times = 2 `, feedpData["barname"], pastureid).Exist()
+// 		if err != nil {
+// 			logs.Error(err)
+// 			appG.Response(http.StatusInternalServerError, e.ERROR, false)
+// 			return
+// 		}
+// 		if !exist2 {
+// 			_, err = tx.SQL(` insert into  fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where  bname = ? and pastureid = ? ),?,2,0,0,0,-1,-1) `,
+// 				pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
+// 			if err != nil {
+// 				logs.Error(err)
+// 				appG.Response(http.StatusInternalServerError, e.ERROR, false)
+// 				return
+// 			}
+// 		}
+
+// 		exist3, err := tx.SQL(` select id from  fpdetail where barname = ?  and pastureid = ? and times =3 `, feedpData["barname"], pastureid).Exist()
+// 		if err != nil {
+// 			logs.Error(err)
+// 			appG.Response(http.StatusInternalServerError, e.ERROR, false)
+// 			return
+// 		}
+// 		if !exist3 {
+// 			_, err = tx.SQL(` insert into  fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where  bname = ? and pastureid = ? ),?,3,0,0,0,-1,-1) `,
+// 				pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
+// 			if err != nil {
+// 				logs.Error(err)
+// 				appG.Response(http.StatusInternalServerError, e.ERROR, false)
+// 				return
+// 			}
+// 		}
+// 		exist4, err := tx.SQL(` select id from  fpdetail where barname = ?  and pastureid = ? and times = 4 `, feedpData["barname"], pastureid).Exist()
+// 		if err != nil {
+// 			logs.Error(err)
+// 			appG.Response(http.StatusInternalServerError, e.ERROR, false)
+// 			return
+// 		}
+// 		if !exist4 {
+// 			_, err = tx.SQL(` insert into  fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where  bname = ? and pastureid = ? ),?,4,0,0,0,-1,-1) `,
+// 				pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
+// 			if err != nil {
+// 				logs.Error(err)
+// 				appG.Response(http.StatusInternalServerError, e.ERROR, false)
+// 				return
+// 			}
+// 		}
+// 		exist5, err := tx.SQL(` select id from  fpdetail where barname = ?  and pastureid = ? and times = 5 `, feedpData["barname"], pastureid).Exist()
+// 		if err != nil {
+// 			logs.Error(err)
+// 			appG.Response(http.StatusInternalServerError, e.ERROR, false)
+// 			return
+// 		}
+// 		if !exist5 {
+// 			_, err = tx.SQL(` insert into  fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where  bname = ? and pastureid = ? ),?,5,0,0,0,-1,-1) `,
+// 				pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
+// 			if err != nil {
+// 				logs.Error(err)
+// 				appG.Response(http.StatusInternalServerError, e.ERROR, false)
+// 				return
+// 			}
+// 		}
+// 		exist6, err := tx.SQL(` select id from  fpdetail where barname = ?  and pastureid = ? and times = 6 `, feedpData["barname"], pastureid).Exist()
+// 		if err != nil {
+// 			logs.Error(err)
+// 			appG.Response(http.StatusInternalServerError, e.ERROR, false)
+// 			return
+// 		}
+// 		if !exist6 {
+// 			_, err = tx.SQL(` insert into  fpdetail(pastureid,barid,barname,times,ptuse,ptsuse,ptsrate,ptsid,ptid)values(?,(select id from bar where  bname = ? and pastureid = ? ),?,6,0,0,0,-1,-1) `,
+// 				pastureid, feedpData["barname"], pastureid, feedpData["barname"]).Execute()
+// 			if err != nil {
+// 				logs.Error(err)
+// 				appG.Response(http.StatusInternalServerError, e.ERROR, false)
+// 				return
+// 			}
+// 		}
+
+// 		upFpdSql := ` update fpdetail set  tratio = ? ,weight = (? *0.01) * ((select sum(fweight) fweight from ftdetail
+// 		where  ftid = (select  id from feedtemplet  where tname = ? and pastureid = ?  )) *  (?*(?*0.01))) ,cowcount = ? ,
+// 		ccountradio= ?,ptid= (select id from feedtemplet where tname = ? and pastureid = ? )   where barname = ?
+// 		and pastureid = ? and times = ?`
+// 		var fpdargs1 []interface{}
+// 		fpdargs1 = append(fpdargs1, dataexcel["1"], dataexcel["1"], dataexcel["ftname"], pastureid,
+// 			dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
+// 			dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 1)
+// 		_, err = tx.SQL(upFpdSql, fpdargs1...).Execute()
+// 		if err != nil {
+// 			appG.Response(http.StatusInternalServerError, e.ERROR, false)
+// 			return
+// 		}
+
+// 		var fpdargs2 []interface{}
+// 		fpdargs2 = append(fpdargs2, dataexcel["2"], dataexcel["2"], dataexcel["ftname"], pastureid,
+// 			dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
+// 			dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 2)
+// 		_, err = tx.SQL(upFpdSql, fpdargs2...).Execute()
+// 		if err != nil {
+// 			appG.Response(http.StatusInternalServerError, e.ERROR, false)
+// 			return
+// 		}
+// 		var fpdargs3 []interface{}
+// 		fpdargs3 = append(fpdargs3, dataexcel["3"], dataexcel["3"], dataexcel["ftname"], pastureid,
+// 			dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
+// 			dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 3)
+// 		_, err = tx.SQL(upFpdSql, fpdargs3...).Execute()
+// 		if err != nil {
+// 			appG.Response(http.StatusInternalServerError, e.ERROR, false)
+// 			return
+// 		}
+// 		var fpdargs4 []interface{}
+// 		fpdargs4 = append(fpdargs4, dataexcel["4"], dataexcel["4"], dataexcel["ftname"], pastureid,
+// 			dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
+// 			dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 4)
+// 		_, err = tx.SQL(upFpdSql, fpdargs4...).Execute()
+// 		if err != nil {
+// 			appG.Response(http.StatusInternalServerError, e.ERROR, false)
+// 			return
+// 		}
+
+// 		var fpdargs5 []interface{}
+// 		fpdargs5 = append(fpdargs5, dataexcel["5"], dataexcel["5"], dataexcel["ftname"], pastureid,
+// 			dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
+// 			dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 5)
+// 		_, err = tx.SQL(upFpdSql, fpdargs5...).Execute()
+// 		if err != nil {
+// 			appG.Response(http.StatusInternalServerError, e.ERROR, false)
+// 			return
+// 		}
+
+// 		var fpdargs6 []interface{}
+// 		fpdargs6 = append(fpdargs6, dataexcel["6"], dataexcel["6"], dataexcel["ftname"], pastureid,
+// 			dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"],
+// 			dataexcel["ftname"], pastureid, dataexcel["barname"], pastureid, 6)
+// 		_, err = tx.SQL(upFpdSql, fpdargs6...).Execute()
+// 		if err != nil {
+// 			appG.Response(http.StatusInternalServerError, e.ERROR, false)
+// 			return
+// 		}
+// 		// _, err = tx.SQL(`call updateLPPbyFPChange(?,( select id from feedp where barname = ?  and pastureid = ?))`, pastureid, dataexcel["barname"], pastureid).Execute()
+
+// 		newList, err := tx.SQL(` select  ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,"") fweight,id,ptid,weight,times from fpdetail where barname = ? and  pastureid = ? `, dataexcel["barname"], pastureid).Query().List()
+// 		if err != nil {
+// 			appG.Response(http.StatusInternalServerError, e.ERROR, false)
+// 			return
+// 		}
+// 		// oldFpdList, err := tx.SQL(` select  fpd.id,fpd.barname,fpd.weight,fpd.times,fp.ftweight,fp.supplyweight  from fpdetail fpd
+// 		// join feedp fp on fp.barid = fpd.barid and fpd.pastureid = fp.pastureid where fpd.pastureid = ?`, pastureid).Query().List()
+// 		upFpdetailList := make([]*upFpdetail, 0)
+// 		for _, newfpd := range newList {
+// 			for _, oldfpd := range oldFpdList {
+// 				if oldfpd["id"].(int64) == newfpd["id"].(int64) {
+// 					var oldweight, newweight float64
+// 					if oldfpd["weight"] != nil {
+// 						oldweight, _ = strconv.ParseFloat(oldfpd["weight"].(string), 64)
+// 					}
+// 					if newfpd["weight"] != nil {
+// 						newweight, _ = strconv.ParseFloat(newfpd["weight"].(string), 64)
+// 					}
+// 					fweight, _ := strconv.ParseFloat(newfpd["fweight"].(string), 64)
+// 					upFpdetailList = append(upFpdetailList, &upFpdetail{
+// 						Old:     oldweight,
+// 						New:     newweight,
+// 						Times:   newfpd["times"].(int64),
+// 						Ptid:    newfpd["ptid"].(int64),
+// 						Fweight: fweight,
+// 						Id:      oldfpd["id"].(int64),
+// 					})
+// 					break
+// 				}
+// 			}
+// 		}
+
+// 		updateFpdetailByBar(pastureId, feedpData["barname"].(string), upFpdetailList)
+// 	}
+
+// 	appG.Response(http.StatusOK, e.SUCCESS, nil)
+// }
+
+func updateLpplandtlInfo(tx *xorm.Session, data map[string]interface{}) error {
+	feedpList, err := tx.SQL(`select id,concat(ftid)ftid ,pastureId,barid from feedp  where id = ?  `, data["id"]).Query().List()
+	if err != nil {
+		return err
+	}
+	for _, item := range feedpList {
+		// if item["ftid"].(string) != data["ftid"].(string) {
+		_, err = tx.SQL(` delete from lpplandtl1  where barid = ?  and  ? != ?`, item["barid"], item["ftid"], data["ftid"]).Execute()
+		if err != nil {
+			return err
+		}
+		_, err = tx.SQL(` UPDATE fpdetail SET ptuse=0,ptsuse=0
+			WHERE pastureid=?    and find_in_set(barid,?) and  ? != ?  `, item["pastureId"], item["barid"], item["ftid"], data["ftid"]).Execute()
+		if err != nil {
+			return err
+		}
+		// }
+	}
+	return nil
+}

+ 335 - 237
http/handle/api/scheduled.go

@@ -128,8 +128,16 @@ func CronScheduled(ctx context.Context) {
 	})
 	dayCron.Start()
 
+	//
 	// //圣牧自动同步前天有进行中的任务
-	manualUdData(pastureinfo)
+	// manualUdData(pastureinfo)
+
+	// xdmy := cron.New()
+	// dayCron.AddFunc("50 04 * * *", func() {
+	// 	sap.SyncMaterialOutbound()
+	// })
+	// xdmy.Start()
+
 }
 
 type ScheduledInfo struct {
@@ -468,7 +476,7 @@ func UpdatePush(ctx context.Context, tx *xorm.Session, auto bool, idList []strin
 					}
 					// d, err := OpenFile("a.txt")
 					// d.WriteString()
-					// UDPostPush(fmt.Sprintf(item.Package, string(databyte), len(data)), "application/json")
+					UDPostPush(fmt.Sprintf(item.Package, string(databyte), len(data)), "application/json")
 					UDPostPush1(fmt.Sprintf(item.Package, string(databyte), len(data)), "")
 				}
 			}
@@ -672,8 +680,8 @@ func (h *ScheduledDown) SyncFeedp(pastureid string, feedpList []interface{}) err
 
 	for _, f := range feedpList {
 		feedp := f.(map[string]interface{})
-		var barName, barCode, feedtempletCode, barId interface{}
-		var ftId, tname interface{}
+		var barName, barCode interface{}
+		// var ftId, tname interface{}
 		var cowCount interface{}
 		if _, ok := feedp["barname"]; ok {
 			barName = feedp["barname"]
@@ -684,59 +692,61 @@ func (h *ScheduledDown) SyncFeedp(pastureid string, feedpList []interface{}) err
 		if _, ok := feedp["cowcount"]; ok {
 			cowCount = feedp["cowcount"]
 		}
-		if _, ok := feedp["feedtempletcode"]; ok {
-			feedtempletCode = feedp["feedtempletCode"]
-		}
-
-		barCount, err := tx.SQL(" select count(1) from bar where pastureid = ? and bcode = ? ", pastureid, barCode).Count()
-		if err != nil {
-			tx.Rollback()
-			logs.Error("syncFeedp-error-2:", err)
-			return err
-		}
-		if barCount > 0 {
-			barDataList, err := tx.SQL(" select id from bar where pastureid = ? and bcode = ?", pastureid, barCode).QueryString()
-			if err != nil {
-				tx.Rollback()
-				logs.Error("syncFeedp-error-3:", err)
-				return err
-			}
-			for _, barData := range barDataList {
-				barId = barData["id"]
-			}
-		} else {
-			barReq, err := tx.SQL("insert into bar(pastureid,bname,bcode)VALUES(?,?,?)", pastureid, barName, barCode).Execute()
-			if err != nil {
-				tx.Rollback()
-				logs.Error("syncFeedp-error-4:", err)
-				return err
-			}
-			id, err := barReq.LastInsertId()
-			if err != nil {
-				tx.Rollback()
-				logs.Error("syncFeedp-error-5:", err)
-				return err
-			}
-
-			barId = strconv.FormatInt(id, 10)
-		}
-
-		if feedtempletCode != "" {
-			feedtempletDataList, err := tx.SQL(" select id,tname from feedtemplet where pastureid = ? and tcode = ?", pastureid, feedtempletCode).QueryString()
-			if err != nil {
-				tx.Rollback()
-				logs.Error("syncFeedp-error-6:", err)
-				return err
-			}
-			for _, feedtemplet := range feedtempletDataList {
-				ftId = feedtemplet
-				tname = feedtemplet
-			}
-		}
-
-		insertSql := `insert into feedp(pastureid,barname,barid,ccount,ftid,ftname)VALUES(?,?,?,?,?,?) 
-		ON DUPLICATE KEY UPDATE ccount = ? ,ftid = ? ,ftname = ? `
-		_, err = tx.SQL(insertSql, pastureid, barName, barId, cowCount, ftId, tname, cowCount, ftId, tname).Execute()
+		// if _, ok := feedp["feedtempletcode"]; ok {
+		// 	feedtempletCode = feedp["feedtempletCode"]
+		// }
+
+		// barCount, err := tx.SQL(" select count(1) from bar where pastureid = ? and bcode = ? ", pastureid, barCode).Count()
+		// if err != nil {
+		// 	tx.Rollback()
+		// 	logs.Error("syncFeedp-error-2:", err)
+		// 	return err
+		// }
+		// if barCount > 0 {
+		// 	barDataList, err := tx.SQL(" select id from bar where pastureid = ? and bcode = ?", pastureid, barCode).QueryString()
+		// 	if err != nil {
+		// 		tx.Rollback()
+		// 		logs.Error("syncFeedp-error-3:", err)
+		// 		return err
+		// 	}
+		// 	for _, barData := range barDataList {
+		// 		barId = barData["id"]
+		// 	}
+		// } else {
+		// 	barReq, err := tx.SQL("insert into bar(pastureid,bname,bcode)VALUES(?,?,?)", pastureid, barName, barCode).Execute()
+		// 	if err != nil {
+		// 		tx.Rollback()
+		// 		logs.Error("syncFeedp-error-4:", err)
+		// 		return err
+		// 	}
+		// 	id, err := barReq.LastInsertId()
+		// 	if err != nil {
+		// 		tx.Rollback()
+		// 		logs.Error("syncFeedp-error-5:", err)
+		// 		return err
+		// 	}
+
+		// 	barId = strconv.FormatInt(id, 10)
+		// }
+
+		// if feedtempletCode != "" {
+		// 	feedtempletDataList, err := tx.SQL(" select id,tname from feedtemplet where pastureid = ? and tcode = ?", pastureid, feedtempletCode).QueryString()
+		// 	if err != nil {
+		// 		tx.Rollback()
+		// 		logs.Error("syncFeedp-error-6:", err)
+		// 		return err
+		// 	}
+		// 	for _, feedtemplet := range feedtempletDataList {
+		// 		ftId = feedtemplet
+		// 		tname = feedtemplet
+		// 	}
+		// }
+
+		// insertSql := `insert into feedp(pastureid,barname,barid,softccount)VALUES(?,?,?,?)
+		// ON DUPLICATE KEY UPDATE softccount = ?  `
+		// _, err = tx.SQL(insertSql, pastureid, barName, barId, cowCount, cowCount).Execute()
+		fmt.Println(barName)
+		_, err = tx.SQL(`update feedp fp set fp.softccount = ? where  (select bcode from bar where id = fp.id ) = ? `, cowCount, barCode).Execute()
 		if err != nil {
 			tx.Rollback()
 			logs.Error("syncFeedp-error-7:", err)
@@ -757,23 +767,44 @@ func (h *ScheduledDown) SyncFeedp(pastureid string, feedpList []interface{}) err
 func wxPush(target []string, content []interface{}, pastureId string, serviceId int64) {
 	url := "http://tmrwatch.cn/notice/message"
 
+	// dataStr := `{
+	// 	"pasture_id":%s,
+	// 	"service_id":%d,
+	// 	"sys_name": "tmrWatch",
+	// 	"target": %s,
+	// 	"miniprogram": {
+	// 		"appid": "wx9ab2b5b25701da0a",
+	// 		"pagepath": "pages/login/login"
+	// 	},
+	// 	"keys": [
+	// 		"first",
+	// 		"keyword1",
+	// 		"keyword2",
+	// 		"remark"
+	// 	],
+	// 	"content":%s
+	// }`
+
 	dataStr := `{
-		"pasture_id":%s,
-		"service_id":%d,
-		"sys_name": "tmrWatch",
-		"target": %s,
-		"miniprogram": {
-			"appid": "wx9ab2b5b25701da0a",
-			"pagepath": "pages/login/login"
-		},
-		"keys": [
-			"first",
-			"keyword1",
-			"keyword2",
-			"remark"
-		],
-		"content":%s
-	}`
+		  "msg_type_id": 0,
+		  "pasture_id": %s,
+		  "service_id": %d,
+		  "sys_name": "tmrWatch",
+		
+		  "miniprogram": {
+		    "appid": "wx9ab2b5b25701da0a",
+		    "pagepath": "pages/login/login"
+		  },
+		  "target": %s,
+		  "keys": [
+		    "thing5",
+		    "thing2",
+		    "thing16",
+		    "thing36",
+		    "thing45"
+		  ],
+		  "content": %s
+		}`
 
 	targetStr, _ := json.Marshal(target)
 	contentStr, _ := json.Marshal(content)
@@ -787,6 +818,7 @@ func wxPush(target []string, content []interface{}, pastureId string, serviceId
 	resp, err := client.Do(req)
 	if err != nil {
 		logs.Error(err)
+		return
 	}
 
 	defer resp.Body.Close()
@@ -810,30 +842,6 @@ func UDPostPush1(data, method string) {
 	body, _ := ioutil.ReadAll(resp.Body)
 	fmt.Println("response Body:", string(body))
 
-	// file, err := os.Create("example.txt")
-	// if err != nil {
-	// 	fmt.Println(err)
-	// 	return
-	// }
-	// defer file.Close()
-
-	// // 创建一个写入器并将其与文件关联
-	// writer := bufio.NewWriter(file)
-
-	// // 将字符串写入缓冲区
-	// // str := "Hello, world!"
-	// _, err = writer.WriteString(data)
-	// if err != nil {
-	// 	fmt.Println(err)
-	// 	return
-	// }
-
-	// // 刷新缓冲区,确保所有数据都已成功写入文件
-	// err = writer.Flush()
-	// if err != nil {
-	// 	fmt.Println(err)
-	// 	return
-	// }
 	logging.Info("response Body:", string(body))
 }
 
@@ -881,7 +889,8 @@ func processAnalysisEarlyWarning(target []string, pastureId string, serviceId in
 
 		for _, data := range dataList {
 			if data["type"].(int64) == 0 {
-				plandtl1List, err := tx2.SQL(`select d.remark,d.projname,d1.fname,d.tmrtname,DATE_FORMAT(d1.intime, '%Y-%m-%d %H:%i:%S') as intime,d1.id,d1.feedallowratio,abs(d1.actualweightminus -d1.lweight ) errorvalue ,d1.actualweightminus,d1.lweight,
+				plandtl1List, err := tx2.SQL(`select d.remark,d.projname,d1.fname,d.tmrtname,DATE_FORMAT(d1.intime, '%Y-%m-%d %H:%i:%S') as intime,d1.id,d1.feedallowratio,abs(d1.actualweightminus -d1.lweight ) errorvalue ,round(d1.actualweightminus,2)actualweightminus,
+				round(d1.lweight,2) lweight,
 					if(d1.actualweightminus <= d1.lweight,ROUND(d1.actualweightminus/d1.lweight* 100,2),ROUND(d1.lweight/d1.actualweightminus* 100,2) ) as accuracy  from
 					downloadplandtl1 d1
 					join downloadedplan d on d.id = d1.pid
@@ -906,34 +915,41 @@ func processAnalysisEarlyWarning(target []string, pastureId string, serviceId in
 						continue
 					}
 
-					errorvalue, _ := strconv.ParseFloat(plandtl1["errorvalue"].(string), 64)
-					if plandtl1["feedallowratio"].(float64) < errorvalue {
-						var sendList []interface{}
-						sendStr := fmt.Sprintf("操作编号:%v\n牧场:%s\nTMR名称:%v\n描述:%v\n饲料名称:%v\n计划重量(kg):%v\n实际重量(kg):%v\n误差值(kg):%v\n准确率(%%):%v",
-							plandtl1["projname"], pastureName, plandtl1["tmrtname"], plandtl1["remark"], plandtl1["fname"], plandtl1["lweight"], plandtl1["actualweightminus"], plandtl1["errorvalue"], plandtl1["accuracy"])
-
-						sendMap1 := make(map[string]interface{}, 0)
-						sendMap1["value"] = "混料准确率异常"
-						sendMap1["color"] = "#173177"
-						sendList = append(sendList, sendMap1)
-
-						sendMap4 := make(map[string]interface{}, 0)
-						sendMap4["value"] = sendStr
-						sendMap4["color"] = "#173177"
-						sendList = append(sendList, sendMap4)
-
-						sendMap2 := make(map[string]interface{}, 0)
-						sendMap2["value"] = plandtl1["intime"]
-						sendMap2["color"] = "#173177"
-						sendList = append(sendList, sendMap2)
-
-						sendMap5 := make(map[string]interface{}, 0)
-						sendMap5["value"] = "无备注"
-						sendMap5["color"] = "#173177"
-						sendList = append(sendList, sendMap5)
-						wxPush(target, sendList, pastureId, serviceId)
+					if _, ok := plandtl1["errorvalue"]; !ok {
+						continue
 					}
+					errorvalue, _ := strconv.ParseFloat(plandtl1["errorvalue"].(string), 64)
+					if _, ok := plandtl1["feedallowratio"]; ok {
+
+						if plandtl1["feedallowratio"].(float64) < errorvalue {
+							var sendList []interface{}
+							// sendStr := fmt.Sprintf("操作编号:%v\n牧场:%s\nTMR名称:%v\n描述:%v\n饲料名称:%v\n计划重量(kg):%v\n实际重量(kg):%v\n误差值(kg):%v\n准确率(%%):%v",
+							// 	plandtl1["projname"], pastureName, plandtl1["tmrtname"], plandtl1["remark"], plandtl1["fname"], plandtl1["lweight"], plandtl1["actualweightminus"], plandtl1["errorvalue"], plandtl1["accuracy"])
+
+							sendMap1 := make(map[string]interface{}, 0)
+							sendMap1["value"] = fmt.Sprintf("%v%s", plandtl1["projname"], "混料准确率异常")
+							sendList = append(sendList, sendMap1)
+
+							sendMap2 := make(map[string]interface{}, 0)
+							sendMap2["value"] = fmt.Sprintf("%v-%v", plandtl1["tmrtname"], plandtl1["fname"])
+							sendList = append(sendList, sendMap2)
+
+							sendMap3 := make(map[string]interface{}, 0)
+							sendMap3["value"] = fmt.Sprintf("计划%v,实际%v", plandtl1["lweight"], plandtl1["actualweightminus"])
+							sendList = append(sendList, sendMap3)
 
+							sendMap4 := make(map[string]interface{}, 0)
+							sendMap4["value"] = fmt.Sprintf("误差值%v,准确率%v", plandtl1["errorvalue"], plandtl1["accuracy"])
+							sendList = append(sendList, sendMap4)
+
+							sendMap5 := make(map[string]interface{}, 0)
+							sendMap5["value"] = pastureName
+							sendList = append(sendList, sendMap5)
+
+							wxPush(target, sendList, pastureId, serviceId)
+						}
+
+					}
 					plandtl1SlIdMap["planid"] = append(plandtl1SlIdMap["planid"], plandtl1["id"].(int64))
 					_, err := tx2.SQL(" update downloadplandtl1_log set plandtl1 = ? where id = ?  and type =  0 ", plandtl1["id"], data["id"]).Execute()
 					if err != nil {
@@ -942,7 +958,7 @@ func processAnalysisEarlyWarning(target []string, pastureId string, serviceId in
 					}
 				}
 			} else {
-				plandtl1List, err := tx2.SQL(`select  d.remark,d2.id,d.projname,d2.fname,d.tmrtname,d2.id,ifnull(d2.allowratio,0) allowratio ,abs(d2.actualweightminus -d2.lweight ) errorvalue ,DATE_FORMAT(d2.intime, '%Y-%m-%d %H:%i:%S') as intime ,d2.actualweightminus,d2.lweight,
+				plandtl1List, err := tx2.SQL(`select  d.remark,d2.id,d.projname,d2.fname,d.tmrtname,d2.id,ifnull(d2.allowratio,0) allowratio ,abs(d2.actualweightminus -d2.lweight ) errorvalue ,DATE_FORMAT(d2.intime, '%Y-%m-%d %H:%i:%S') as intime ,round(d2.actualweightminus,2)actualweightminus,round(d2.lweight,2) lweight,
 					if(d2.actualweightminus <= d2.lweight,ROUND(d2.actualweightminus/d2.lweight* 100,2),ROUND(d2.lweight/d2.actualweightminus* 100,2) ) as accuracy
 				 from 	downloadplandtl2 d2
 					join downloadedplan d on d.id = d2.pid
@@ -969,39 +985,51 @@ func processAnalysisEarlyWarning(target []string, pastureId string, serviceId in
 					}
 
 					errorvalue, _ := strconv.ParseFloat(plandtl1["errorvalue"].(string), 64)
-					if float64(plandtl1["allowratio"].(int64)) < errorvalue && float64(plandtl1["allowratio"].(int64)) != 0 {
-						fmt.Println(plandtl1, "推送")
-
-						var sendList []interface{}
-						sendStr := fmt.Sprintf("操作编号:%v\n牧场:%s\nTMR名称:%v\n描述:%v\n栏舍名称:%v\n计划重量(kg):%v\n实际重量(kg):%v\n误差值(kg):%v\n准确率(%%):%v",
-							plandtl1["projname"], pastureName, plandtl1["tmrtname"], plandtl1["remark"], plandtl1["fname"], plandtl1["lweight"], plandtl1["actualweightminus"], plandtl1["errorvalue"], plandtl1["accuracy"])
-						sendMap1 := make(map[string]interface{}, 0)
-						sendMap1["value"] = "撒料准确率异常"
-						sendMap1["color"] = "#173177"
-						sendList = append(sendList, sendMap1)
-
-						sendMap4 := make(map[string]interface{}, 0)
-						sendMap4["value"] = sendStr
-						sendMap4["color"] = "#173177"
-						sendList = append(sendList, sendMap4)
-
-						sendMap2 := make(map[string]interface{}, 0)
-						sendMap2["value"] = plandtl1["intime"]
-						sendMap2["color"] = "#173177"
-						sendList = append(sendList, sendMap2)
-						sendMap5 := make(map[string]interface{}, 0)
-						sendMap5["value"] = "无备注"
-						sendMap5["color"] = "#173177"
-						sendList = append(sendList, sendMap5)
-
-						wxPush(target, sendList, pastureId, serviceId)
+					if _, ok := plandtl1["allowratio"]; ok {
+
+						if float64(plandtl1["allowratio"].(int64)) < errorvalue && float64(plandtl1["allowratio"].(int64)) != 0 {
+							fmt.Println(plandtl1, "推送")
+
+							var sendList []interface{}
+							// sendStr := fmt.Sprintf("操作编号:%v\n牧场:%s\nTMR名称:%v\n描述:%v\n栏舍名称:%v\n计划重量(kg):%v\n实际重量(kg):%v\n误差值(kg):%v\n准确率(%%):%v",
+							// 	plandtl1["projname"], pastureName, plandtl1["tmrtname"], plandtl1["remark"], plandtl1["fname"], plandtl1["lweight"], plandtl1["actualweightminus"], plandtl1["errorvalue"], plandtl1["accuracy"])
+							// sendMap1 := make(map[string]interface{}, 0)
+							// sendMap1["value"] = "撒料准确率异常"
+							// sendMap1["color"] = "#173177"
+							// sendList = append(sendList, sendMap1)
+							sendMap1 := make(map[string]interface{}, 0)
+							sendMap1["value"] = fmt.Sprintf("%v%s", plandtl1["projname"], "撒料准确率异常")
+							sendList = append(sendList, sendMap1)
+
+							sendMap2 := make(map[string]interface{}, 0)
+							sendMap2["value"] = fmt.Sprintf("%v-%v", plandtl1["tmrtname"], plandtl1["fname"])
+							sendList = append(sendList, sendMap2)
+
+							sendMap3 := make(map[string]interface{}, 0)
+							sendMap3["value"] = fmt.Sprintf("计划%v,实际%v", plandtl1["lweight"], plandtl1["actualweightminus"])
+							sendList = append(sendList, sendMap3)
+
+							sendMap4 := make(map[string]interface{}, 0)
+							sendMap4["value"] = fmt.Sprintf("误差值%v,准确率%v", plandtl1["errorvalue"], plandtl1["accuracy"])
+							sendList = append(sendList, sendMap4)
+
+							sendMap5 := make(map[string]interface{}, 0)
+							sendMap5["value"] = pastureName
+							sendList = append(sendList, sendMap5)
+
+							wxPush(target, sendList, pastureId, serviceId)
+						}
 					}
-
-					plandtl1SlIdMap["planid"] = append(plandtl1SlIdMap["planid"], plandtl1["id"].(int64))
-					_, err := tx2.SQL(" update downloadplandtl1_log set plandtl1 = ? where id = ? and type = 1 ", plandtl1["id"], data["id"]).Execute()
-					if err != nil {
-						logs.Error("processAnalysisEarlyWarning-error-8:", err)
-						return
+					if _, ok := plandtl1["id"]; ok {
+						if _, ok := data["id"]; ok {
+							fmt.Println(plandtl1["id"])
+							plandtl1SlIdMap["planid"] = append(plandtl1SlIdMap["planid"], plandtl1["id"].(int64))
+							_, err := tx2.SQL(" update downloadplandtl1_log set plandtl1 = ? where id = ? and type = 1 ", plandtl1["id"], data["id"]).Execute()
+							if err != nil {
+								logs.Error("processAnalysisEarlyWarning-error-8:", err)
+								return
+							}
+						}
 					}
 
 				}
@@ -1073,6 +1101,25 @@ func manualUdData(pastureinfo *udPastureInfo) {
 		}
 	})
 	c.Start()
+
+	c1 := cron.New()
+	c1.AddFunc("01 18 * * *", func() {
+		udFeedpSync(pastureinfo)
+	})
+	c1.Start()
+
+	c2 := cron.New()
+	c2.AddFunc("30 11 * * *", func() {
+		udFeedpSync(pastureinfo)
+	})
+	c2.Start()
+
+	c3 := cron.New()
+	c3.AddFunc("59 23 * * *", func() {
+		udFeedpSync(pastureinfo)
+	})
+	c3.Start()
+
 }
 
 func abnormalMixingDelay(target []string, pastureId string, serviceId int64) {
@@ -1089,8 +1136,8 @@ func abnormalMixingDelay(target []string, pastureId string, serviceId int64) {
 	}
 	local, _ := time.LoadLocation("Asia/Shanghai")
 	for _, data := range dataList {
-		planList, err := tx2.SQL(`select  de.deviation,de.lweight,de.fname,de.processtime,de.stirdelay,d.tmrtname, d.projname, CONCAT(d.templetname,projname) as name ,
-		d.datacaptureno,(select pasture_name from  pasture   where pastureid = ?) as pasturename,de.actualweightminus  from downloadplandtl1_exec  de 
+		planList, err := tx2.SQL(`select  ifnull(de.deviation,0) deviation,round(de.lweight,2) lweight ,de.fname,de.processtime,de.stirdelay,d.tmrtname, d.projname, CONCAT(d.templetname,projname) as name ,
+		d.datacaptureno,(select pasture_name from  pasture   where pastureid = ?) as pasturename,round(de.actualweightminus,2) actualweightminus  from downloadplandtl1_exec  de 
 		join downloadedplan  d  on de.pid = d.id   where de.pid = ? and de.sort = ? `, pastureId, data["planid"], data["sort"]).Query().List()
 		if err != nil {
 			logs.Error("abnormalMixingDelay-error-2:", err)
@@ -1098,33 +1145,42 @@ func abnormalMixingDelay(target []string, pastureId string, serviceId int64) {
 		}
 
 		for _, plan := range planList {
-			showTime, _ := time.ParseInLocation("2006-01-02 15:04:05", fmt.Sprintf("%s %s", time.Now().Format("2006-01-02"), plan["processtime"]), local)
-			nowTime, _ := time.ParseInLocation("2006-01-02 15:04:05", fmt.Sprintf("%s 00:00:00", time.Now().Format("2006-01-02")), local)
+			fmt.Println(plan["processtime"])
+			fmt.Println(fmt.Sprintf("%s %v", time.Now().Format("2006-01-02"), plan["processtime"]), local)
+			showTime, _ := time.Parse("2006-01-02 15:04:05", fmt.Sprintf("%s %v", time.Now().Format("2006-01-02"), plan["processtime"]))
+			nowTime, _ := time.Parse("2006-01-02 15:04:05", fmt.Sprintf("%s 00:00:00", time.Now().Format("2006-01-02")))
+			// showTime, _ := time.ParseInLocation("2006-01-02 15:04:05", fmt.Sprintf("%s %v", time.Now().Format("2006-01-02"), plan["processtime"]), local)
+			// nowTime, _ := time.ParseInLocation("2006-01-02 15:04:05", fmt.Sprintf("%s 00:00:00", time.Now().Format("2006-01-02")), local)
 
 			if (showTime.Unix()-nowTime.Unix())/60 < plan["stirdelay"].(int64)-plan["deviation"].(int64) || (showTime.Unix()-nowTime.Unix())/60 > plan["stirdelay"].(int64)+plan["deviation"].(int64) {
 				var sendList []interface{}
-				sendStr := fmt.Sprintf("操作编号:%v\n牧场:%s\nTMR名称:%v\n描述:%v\n饲料名称:%v\n计划重量(kg):%v\n实际重量(kg):%v\n过程时间:%v",
-					plan["projname"], plan["pasturename"], plan["tmrtname"], plan["name"], plan["fname"], plan["lweight"], plan["actualweightminus"], plan["processtime"])
+				// sendStr := fmt.Sprintf("操作编号:%v\n牧场:%s\nTMR名称:%v\n描述:%v\n饲料名称:%v\n计划重量(kg):%v\n实际重量(kg):%v\n过程时间:%v",
+				// plan["projname"], plan["pasturename"], plan["tmrtname"], plan["name"], plan["fname"], plan["lweight"], plan["actualweightminus"], plan["processtime"])
 
 				sendMap1 := make(map[string]interface{}, 0)
-				sendMap1["value"] = "混料搅拌延时异常"
-				sendMap1["color"] = "#173177"
+				sendMap1["value"] = fmt.Sprintf("%s%v", "混料搅拌延时异常", plan["projname"])
+				// sendMap1["color"] = "#173177"
 				sendList = append(sendList, sendMap1)
 
 				sendMap4 := make(map[string]interface{}, 0)
-				sendMap4["value"] = sendStr
-				sendMap4["color"] = "#173177"
+				sendMap4["value"] = fmt.Sprintf("%v-%v", plan["tmrtname"], plan["fname"])
+				// sendMap4["color"] = "#173177"
 				sendList = append(sendList, sendMap4)
 
 				sendMap2 := make(map[string]interface{}, 0)
-				sendMap2["value"] = plan["processtime"]
-				sendMap2["color"] = "#173177"
+				sendMap2["value"] = fmt.Sprintf("计划%v,实际%v", plan["lweight"], plan["actualweightminus"])
+				// sendMap2["color"] = "#173177"
 				sendList = append(sendList, sendMap2)
 				sendMap5 := make(map[string]interface{}, 0)
-				sendMap5["value"] = "无备注"
-				sendMap5["color"] = "#173177"
+				sendMap5["value"] = fmt.Sprintf("过程时间:%v", plan["processtime"])
+				// sendMap5["color"] = "#173177"
 				sendList = append(sendList, sendMap5)
 
+				sendMap3 := make(map[string]interface{}, 0)
+				sendMap3["value"] = plan["pasturename"]
+				// sendMap3["color"] = "#173177"
+				sendList = append(sendList, sendMap3)
+
 				wxPush(target, sendList, pastureId, serviceId)
 			}
 			_, err := tx2.SQL(` update downloadplandtl1_log set abnormalMixingDelay = 1 where id = ? `, data["id"]).Execute()
@@ -1155,7 +1211,7 @@ func endOfShift(target []string, pastureId string, serviceId int64) {
 
 		if !exist {
 			hlList, err := tx.SQL(` select ( select count(1) from downloadedplan where times = d.times and mydate = d.mydate ) as cltrains,
-			sum(de.lweight)lweight,sum(de.actualweightminus)actualweightminus  ,
+			round(sum(de.lweight),2) lweight,round(sum(de.actualweightminus),2) actualweightminus  ,
 			round(if(sum(de.lweight) < sum(de.actualweightminus),sum(de.lweight)/sum(de.actualweightminus) *100, sum(de.actualweightminus)/sum(de.lweight) *100),2)  as accurate,
 			ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) correct,
 			IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0)),0) correctcount,
@@ -1168,7 +1224,7 @@ func endOfShift(target []string, pastureId string, serviceId int64) {
 				return
 			}
 
-			slList, err := tx.SQL(` select sum(de.lweight)lweight,sum(de.actualweightminus)actualweightminus  ,
+			slList, err := tx.SQL(` select round(sum(de.lweight),2) lweight,round(sum(de.actualweightminus),2) actualweightminus  ,
 			round(if(sum(de.lweight) < sum(de.actualweightminus),sum(de.lweight)/sum(de.actualweightminus) *100, sum(de.actualweightminus)/sum(de.lweight) *100),2)  as accurate,
 			ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) correct,
 			IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0)),0) correctcount,
@@ -1541,73 +1597,73 @@ func AddBigInventory(c *gin.Context) {
 			}
 			if err == nil {
 
-				var pastureid, date string
-				for _, tem := range tempval {
-					if tem["name"].(string) == "insertBigInventory" {
-						parammaps := tem["parammaps"].(map[string]interface{})
-						pastureid = parammaps["pastureid"].(string)
-						date = parammaps["inventorydate"].(string)
-					}
-				}
+				// var pastureid, date string
+				// for _, tem := range tempval {
+				// 	if tem["name"].(string) == "insertBigInventory" {
+				// 		parammaps := tem["parammaps"].(map[string]interface{})
+				// 		pastureid = parammaps["pastureid"].(string)
+				// 		date = parammaps["inventorydate"].(string)
+				// 	}
+				// }
 
-				feedinventoryList, err := tx.SQL(`SELECT
-				remark,DATE_FORMAT(inventorydate, '%Y-%m-%d') inventorydate,createuser,
-				TRIM(f.id) id,
-				TRIM(f.pastureid) pastureid,
-				ifnull(round((select sum(theoryweight-factweight) from feedinventorydetail fd where fd.pastureid and fd.invid = f.id and fd.theoryweight>fd.factweight) ,2),0) lessWeight,
-				ifnull(round((select sum(factweight-theoryweight) from feedinventorydetail fd where fd.pastureid and fd.invid = f.id and fd.theoryweight<fd.factweight),2),0)  moreWeight ,
-				ifnull(round((select sum(factweight-theoryweight) from feedinventorydetail fd where fd.pastureid and fd.invid = f.id and fd.theoryweight<>fd.factweight) ,2),0)  differWeight
-				FROM
-				  feedinventory f
-				WHERE f.pastureid = ?  and f.inventorydate=? `, pastureid, date).Query().List()
-				if err != nil {
-					logs.Error("AddBigInventory-error-2:", err)
-					return
-				}
+				// feedinventoryList, err := tx.SQL(`SELECT
+				// remark,DATE_FORMAT(inventorydate, '%Y-%m-%d') inventorydate,createuser,
+				// TRIM(f.id) id,
+				// TRIM(f.pastureid) pastureid,
+				// ifnull(round((select sum(theoryweight-factweight) from feedinventorydetail fd where fd.pastureid and fd.invid = f.id and fd.theoryweight>fd.factweight) ,2),0) lessWeight,
+				// ifnull(round((select sum(factweight-theoryweight) from feedinventorydetail fd where fd.pastureid and fd.invid = f.id and fd.theoryweight<fd.factweight),2),0)  moreWeight ,
+				// ifnull(round((select sum(factweight-theoryweight) from feedinventorydetail fd where fd.pastureid and fd.invid = f.id and fd.theoryweight<>fd.factweight) ,2),0)  differWeight
+				// FROM
+				//   feedinventory f
+				// WHERE f.pastureid = ?  and f.inventorydate=? `, pastureid, date).Query().List()
+				// if err != nil {
+				// 	logs.Error("AddBigInventory-error-2:", err)
+				// 	return
+				// }
 
-				dataList, err := tx.SQL(` select user,function,id,service_id from remind where pastureid = ? and function = ? `, pastureid, "formulaIssued").Query().List()
-				if err != nil {
-					logs.Error("AddBigInventory-error-3:", err)
-					return
-				}
+				// dataList, err := tx.SQL(` select user,function,id,service_id from remind where pastureid = ? and function = ? `, pastureid, "formulaIssued").Query().List()
+				// if err != nil {
+				// 	logs.Error("AddBigInventory-error-3:", err)
+				// 	return
+				// }
 
-				for _, data := range dataList {
-					var openIdList []string
-					if _, ok := data["user"]; ok {
-						openIdList = strings.Split(data["user"].(string), ",")
-					}
-					var createuser, lessWeight, moreWeight, differWeight interface{}
-					for _, f := range feedinventoryList {
-						createuser = f["createuser"]
-						lessWeight = f["lessWeight"]
-						moreWeight = f["moreWeight"]
-						differWeight = f["differWeight"]
-					}
-					var sendList []interface{}
-					sendStr := fmt.Sprintf("盘点人:%v\n盘盈库存(kg):%v\n盘亏库存(kg):%v\n盈亏净值(kg):%v",
-						createuser, moreWeight, lessWeight, differWeight)
-					sendMap1 := make(map[string]interface{}, 0)
-					sendMap1["value"] = "库存盘点"
-					sendMap1["color"] = "#173177"
-					sendList = append(sendList, sendMap1)
-
-					sendMap4 := make(map[string]interface{}, 0)
-					sendMap4["value"] = sendStr
-					sendMap4["color"] = "#173177"
-					sendList = append(sendList, sendMap4)
-
-					sendMap2 := make(map[string]interface{}, 0)
-					sendMap2["value"] = time.Now().Format("2006-01-02 15:04:05")
-					sendMap2["color"] = "#173177"
-					sendList = append(sendList, sendMap2)
-
-					sendMap5 := make(map[string]interface{}, 0)
-					sendMap5["value"] = "无备注"
-					sendMap5["color"] = "#173177"
-					sendList = append(sendList, sendMap5)
-
-					wxPush(openIdList, sendList, pastureid, data["service_id"].(int64))
-				}
+				// for _, data := range dataList {
+				// 	var openIdList []string
+				// 	if _, ok := data["user"]; ok {
+				// 		openIdList = strings.Split(data["user"].(string), ",")
+				// 	}
+				// 	var createuser, lessWeight, moreWeight, differWeight interface{}
+				// 	for _, f := range feedinventoryList {
+				// 		createuser = f["createuser"]
+				// 		lessWeight = f["lessWeight"]
+				// 		moreWeight = f["moreWeight"]
+				// 		differWeight = f["differWeight"]
+				// 	}
+				// 	var sendList []interface{}
+				// 	sendStr := fmt.Sprintf("盘点人:%v\n盘盈库存(kg):%v\n盘亏库存(kg):%v\n盈亏净值(kg):%v",
+				// 		createuser, moreWeight, lessWeight, differWeight)
+				// 	sendMap1 := make(map[string]interface{}, 0)
+				// 	sendMap1["value"] = "库存盘点"
+				// 	sendMap1["color"] = "#173177"
+				// 	sendList = append(sendList, sendMap1)
+
+				// 	sendMap4 := make(map[string]interface{}, 0)
+				// 	sendMap4["value"] = sendStr
+				// 	sendMap4["color"] = "#173177"
+				// 	sendList = append(sendList, sendMap4)
+
+				// 	sendMap2 := make(map[string]interface{}, 0)
+				// 	sendMap2["value"] = time.Now().Format("2006-01-02 15:04:05")
+				// 	sendMap2["color"] = "#173177"
+				// 	sendList = append(sendList, sendMap2)
+
+				// 	sendMap5 := make(map[string]interface{}, 0)
+				// 	sendMap5["value"] = "无备注"
+				// 	sendMap5["color"] = "#173177"
+				// 	sendList = append(sendList, sendMap5)
+
+				// 	wxPush(openIdList, sendList, pastureid, data["service_id"].(int64))
+				// }
 				if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
 					appG.Response(http.StatusOK, e.SUCCESS, tempval)
 				} else {
@@ -1680,5 +1736,47 @@ func inventoryWarning(target []string, pastureId string, serviceId int64) {
 		sendList = append(sendList, sendMap5)
 		wxPush(target, sendList, pastureId, serviceId)
 	}
+}
 
+func udFeedpSync(pastureinfo *udPastureInfo) error {
+	tx := restful.Engine.NewSession()
+	defer tx.Close()
+
+	downList := make([]*ScheduledDownInfo, 0)
+	down := tx.Table("scheduled_down")
+
+	down.Where("company = ? ", "ud")
+	down.Where("methods = ? ", "SyncFeedp")
+	err := down.Find(&downList)
+	if err != nil {
+		log.Println("UpdateDown-error-1: ", err)
+		return err
+	}
+
+	for _, item := range downList {
+		list := httpGetMC(item.Addres, item.Targetdata)
+		if item.Methods != "" {
+			s := ScheduledDown{}
+			value := reflect.ValueOf(&s)
+			f := value.MethodByName(item.Methods)
+			f.Call([]reflect.Value{reflect.ValueOf(pastureinfo.Pastureid), reflect.ValueOf(list)})
+
+		}
+
+	}
+	return nil
 }
+
+// func UdFeedpSync(c *gin.Context) {
+// 	appG := app.Gin{C: c}
+// 	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+// 	fsion := gofasion.NewFasion(string(dataByte))
+// 	pastureId := fsion.Get("pastureId").ValueStr()
+
+// 	pastureinfo := new(udPastureInfo)
+// 	pastureinfo.Pastureid = pastureId
+// 	udFeedpSync(pastureinfo)
+
+// 	appG.Response(http.StatusOK, e.SUCCESS, true)
+// 	return
+// }

+ 35 - 11
http/handle/api/spillage.go

@@ -772,13 +772,13 @@ func GetSpillage(c *gin.Context) {
 	data := make(map[string]interface{})
 
 	if refresh == 0 || refresh == 2 {
-		sqlStr := `SELECT trim(feedp.pastureid) pastureid,barname,trim(barid) barid,trim(ftid) arrid,1 as type,? as times,ft.tname ftname,ft.tcolor  background,0 isfill FROM feedp 
+		sqlStr := `SELECT isnull(ft.volume) volume,trim(feedp.pastureid) pastureid,barname,trim(barid) barid,trim(ftid) arrid,1 as type,? as times,ft.tname ftname,ft.tcolor  background,0 isfill FROM feedp 
 		inner join  feedtemplet ft
 	on ft.id = feedp.ftid and  ft.pastureid=?
 	WHERE feedp.pastureid = ?  %s
 	GROUP BY feedp.ftid
 	UNION
-	SELECT trim(feedp.pastureid) pastureid,barname,barid,trim(ptsfid) arrid,0 as type,? as times,ft.tname ptsfname ,ft.tcolor  background,1 isfill  FROM feedp
+	SELECT isnull(ft.volume) volume,trim(feedp.pastureid) pastureid,barname,barid,trim(ptsfid) arrid,0 as type,? as times,ft.tname ptsfname ,ft.tcolor  background,1 isfill  FROM feedp
 	inner join  feedtemplet ft
 	on ft.id = feedp.ptsfid and  ft.pastureid=?
 	WHERE feedp.pastureid = ?  %s and  (SELECT inforvalue FROM sysopt WHERE sysopt.pastureid=feedp.pastureid AND sysopt.inforname= 'isEnableSupplyFeed') = 1
@@ -838,8 +838,8 @@ func GetSpillage(c *gin.Context) {
 	}
 
 	if refresh == 0 || refresh == 1 {
-		sqlstr := `SELECT
-		ifnull((select eqcode from tmr where pastureid =lpplan.pastureid and id = lpplan.tmrid ),lpplan.tmrname) tmrname,trim(tmrid) tmrid,sort,sel,
+		sqlstr := `   SELECT
+		ifnull((select eqcode from tmr where pastureid =lpplan.pastureid and id = lpplan.tmrid ),lpplan.tmrname) tmrname,trim(tmrid) tmrid,sort,sel,times timesInt,
 		CASE times
 		WHEN 1 THEN
 		'第一班'
@@ -849,6 +849,10 @@ func GetSpillage(c *gin.Context) {
 	'第三班'
 	WHEN 4 THEN
 	'第四班'
+	WHEN 5 THEN
+	'第五班'
+	WHEN 6 THEN
+	'第六班'
 	END timesstr,issplit,
 	times,display,begintime,
 	(select tname from feedtemplet where pastureid =lpplan.pastureid and id = lpplan.ftid ) ftname,sumcowcount,
@@ -860,8 +864,12 @@ func GetSpillage(c *gin.Context) {
 	TRIM(ftid) ftid,
 	TRIM(id) id,
 	TRIM(id) lppid,
-	TRIM(pastureid) pastureid
-	
+	TRIM(pastureid) pastureid,ifnull((select volume from tmr where id  = lpplan.tmrid ),0) tmrvolume,
+	 (ifnull((select inforvalue from sysopt  where pastureid = lpplan.pastureid  and inforname = 'tmrUpper'),0)/100 *ifnull((select volume from tmr where id  = lpplan.tmrid ),0)) maxVolume,
+	 (ifnull((select inforvalue from sysopt  where pastureid = lpplan.pastureid  and inforname = 'tmrUnder'),0)/100 *ifnull((select volume from tmr where id  = lpplan.tmrid ),0)) minVolume, 
+	ifnull((select volume from feedtemplet where id = lpplan.ftid ),0) ftvolume,
+	(select inforvalue from sysopt  where pastureid = lpplan.pastureid  and inforname = 'tmrUpper') tmrUpper,
+(select inforvalue from sysopt  where pastureid = lpplan.pastureid  and inforname = 'tmrUnder') tmrUnder
 	FROM
 	  lpplan
 	WHERE pastureid = ?   and times <= (SELECT sysopt.inforvalue  FROM sysopt 
@@ -884,7 +892,7 @@ func GetSpillage(c *gin.Context) {
 		fpdetail.ptsid,
 		fpdetail.times,
 		fpdetail.cowcount,
-		fpdetail.ccountradio
+		fpdetail.ccountradio,ifnull((select volume from tmr where id = lpplandtl1.tmrid ),0) tmrvolume
 		FROM
 		  lpplandtl1
 		inner join  fpdetail
@@ -899,7 +907,11 @@ func GetSpillage(c *gin.Context) {
 			arrsql += " and times = ? "
 			args = append(args, times)
 		}
-		sqlstr += "ORDER BY  times,lpplan.sort"
+		// 		maxVolume,
+		// minVolume,
+
+		sqlstr = fmt.Sprintf("select  qq.*,if(qq.sumweight/qq.ftvolume >= qq.minVolume and qq.sumweight/qq.ftvolume <= qq.maxVolume,'正常',if(qq.sumweight/qq.ftvolume < qq.minVolume,concat('低于',qq.tmrUnder,'%%','(',qq.minVolume,'L',')'),concat('高于',qq.tmrUpper,'%%','(',qq.maxVolume,'L',')'))  ) volumeStatusStr,if(qq.sumweight/qq.ftvolume >= qq.minVolume and qq.sumweight/qq.ftvolume <= qq.maxVolume,0,if(qq.sumweight/qq.ftvolume < qq.minVolume,1,2)  ) volumeStatus  from ( %s ) qq", sqlstr)
+		sqlstr += " ORDER BY  qq.timesInt,qq.sort"
 		session := tx.SQL(sqlstr, args...)
 		lppList, err := session.Query().List()
 		if err != nil {
@@ -1381,7 +1393,7 @@ GROUP BY fpd.ptsid`
 		sqlstr := `SELECT
 		lpplan.date,
 		-- ifnull((select eqcode from tmr where pastureid =lpplan.pastureid and id = lpplan.tmrid ),lpplan.tmrname) 
-		lpplan.tmrname tmrname,trim(lpplan.tmrid) tmrid,lpplan.sort,lpplan.sel,
+		lpplan.tmrname tmrname,trim(lpplan.tmrid) tmrid,lpplan.sort,lpplan.sel,times timesInt,
 		CASE lpplan.times
 		WHEN 1 THEN
 		'第一班'
@@ -1391,6 +1403,10 @@ GROUP BY fpd.ptsid`
 		'第三班'
 		WHEN 4 THEN
 		'第四班'
+		WHEN 5 THEN
+		'第五班'
+		WHEN 6 THEN
+		'第六班'
 		END timesstr,issplit,
 		lpplan.times,display,begintime,
 		(select tname from feedtemplet where pastureid =lpplan.pastureid and id = lpplan.ftid ) ftname,sumcowcount,
@@ -1400,7 +1416,13 @@ GROUP BY fpd.ptsid`
 		TRIM(lpplan.id) id,
 		TRIM(lpplan.id) lppid,
 		TRIM(lpplan.pastureid) pastureid,
-		ifnull(dpl.havebutton,0) as havebutton
+		ifnull(dpl.havebutton,0) as havebutton,
+		ifnull((select volume from tmr where id  = lpplan.tmrid ),0) tmrvolume,
+		(ifnull((select inforvalue from sysopt  where pastureid = lpplan.pastureid  and inforname = 'tmrUpper'),0)/100 *ifnull((select volume from tmr where id  = lpplan.tmrid ),0)) maxVolume,
+		(ifnull((select inforvalue from sysopt  where pastureid = lpplan.pastureid  and inforname = 'tmrUnder'),0)/100 *ifnull((select volume from tmr where id  = lpplan.tmrid ),0)) minVolume, 
+	   ifnull((select volume from feedtemplet where id = lpplan.ftid ),0) ftvolume,
+	   (select inforvalue from sysopt  where pastureid = lpplan.pastureid  and inforname = 'tmrUpper') tmrUpper,
+   (select inforvalue from sysopt  where pastureid = lpplan.pastureid  and inforname = 'tmrUnder') tmrUnder
 		FROM
 		  lpplandate lpplan
 			left join downloadedplan dpl on dpl.pid = lpplan.id  and  DATE_FORMAT(dpl.mydate,'%Y-%m-%e') = lpplan.date
@@ -1440,7 +1462,9 @@ GROUP BY fpd.ptsid`
 			args = append(args, times)
 		}
 
-		sqlstr += " group by lpplan.id  ORDER BY  times,lpplan.sort"
+		sqlstr += " group by lpplan.id "
+		sqlstr = fmt.Sprintf("select  qq.*,if(qq.sumweight/qq.ftvolume >= qq.minVolume and qq.sumweight/qq.ftvolume <= qq.maxVolume,'正常',if(qq.sumweight/qq.ftvolume < qq.minVolume,concat('低于',qq.tmrUnder,'%%','(',qq.minVolume,'L',')'),concat('高于',qq.tmrUpper,'%%','(',qq.maxVolume,'L',')'))  ) volumeStatusStr,if(qq.sumweight/qq.ftvolume >= qq.minVolume and qq.sumweight/qq.ftvolume <= qq.maxVolume,0,if(qq.sumweight/qq.ftvolume < qq.minVolume,1,2)  ) volumeStatus  from ( %s ) qq", sqlstr)
+		sqlstr += " ORDER BY  qq.timesInt,qq.sort "
 		session := tx.SQL(sqlstr, args...)
 		lppList, err := session.Query().List()
 		if err != nil {

+ 21 - 21
http/handle/api/udsync.go

@@ -167,8 +167,8 @@ func syncFeedp(pastureid string, feedpList []interface{}) error {
 
 	for _, f := range feedpList {
 		feedp := f.(map[string]interface{})
-		var barName, barCode, feedtempletCode, barId interface{}
-		var ftId, tname interface{}
+		var barName, barCode, barId interface{}
+		// var ftId, tname interface{}
 		var cowCount interface{}
 		if _, ok := feedp["barname"]; ok {
 			barName = feedp["barname"]
@@ -179,9 +179,9 @@ func syncFeedp(pastureid string, feedpList []interface{}) error {
 		if _, ok := feedp["cowcount"]; ok {
 			cowCount = feedp["cowcount"]
 		}
-		if _, ok := feedp["feedtempletcode"]; ok {
-			feedtempletCode = feedp["feedtempletCode"]
-		}
+		// if _, ok := feedp["feedtempletcode"]; ok {
+		// 	feedtempletCode = feedp["feedtempletCode"]
+		// }
 
 		barCount, err := tx.SQL(" select count(1) from bar where pastureid = ? and bcode = ? ", pastureid, barCode).Count()
 		if err != nil {
@@ -216,22 +216,22 @@ func syncFeedp(pastureid string, feedpList []interface{}) error {
 			barId = strconv.FormatInt(id, 10)
 		}
 
-		if feedtempletCode != "" {
-			feedtempletDataList, err := tx.SQL(" select id,tname from feedtemplet where pastureid = ? and tcode = ?", pastureid, feedtempletCode).QueryString()
-			if err != nil {
-				tx.Rollback()
-				logs.Error("syncFeedp-error-6:", err)
-				return err
-			}
-			for _, feedtemplet := range feedtempletDataList {
-				ftId = feedtemplet
-				tname = feedtemplet
-			}
-		}
-
-		insertSql := `insert into feedp(pastureid,barname,barid,ccount,ftid,ftname)VALUES(?,?,?,?,?,?) 
-		ON DUPLICATE KEY UPDATE ccount = ? ,ftid = ? ,ftname = ? `
-		_, err = tx.SQL(insertSql, pastureid, barName, barId, cowCount, ftId, tname, cowCount, ftId, tname).Execute()
+		// if feedtempletCode != "" {
+		// 	feedtempletDataList, err := tx.SQL(" select id,tname from feedtemplet where pastureid = ? and tcode = ?", pastureid, feedtempletCode).QueryString()
+		// 	if err != nil {
+		// 		tx.Rollback()
+		// 		logs.Error("syncFeedp-error-6:", err)
+		// 		return err
+		// 	}
+		// 	for _, feedtemplet := range feedtempletDataList {
+		// 		ftId = feedtemplet
+		// 		tname = feedtemplet
+		// 	}
+		// }
+
+		insertSql := `insert into feedp(pastureid,barname,barid,softccount)VALUES(?,?,?,?) 
+		ON DUPLICATE KEY UPDATE softccount = ? `
+		_, err = tx.SQL(insertSql, pastureid, barName, barId, cowCount, cowCount).Execute()
 		if err != nil {
 			tx.Rollback()
 			logs.Error("syncFeedp-error-7:", err)

+ 1 - 1
http/handle/api/upload.go

@@ -758,7 +758,7 @@ func GetBarfeedremainExcel(c *gin.Context) {
 	cell.SetStyle(style)
 	cell = row.AddCell()
 
-	cell.SetValue("班次(第一班,第二班,第三班)")
+	cell.SetValue("班次(第一班/第二班/第三班)")
 	cell.SetStyle(style)
 	cell = row.AddCell()
 

+ 225 - 66
http/handle/sap/sap.go

@@ -2,7 +2,6 @@ package sap
 
 import (
 	"bytes"
-	"context"
 	"encoding/json"
 	"fmt"
 	"io/ioutil"
@@ -14,41 +13,79 @@ import (
 	"tmr-watch/pkg/app"
 	"tmr-watch/pkg/e"
 
+	"github.com/Anderson-Lu/gofasion/gofasion"
 	"github.com/astaxie/beego/logs"
 	"github.com/gin-gonic/gin"
+	"github.com/xormplus/xorm"
 )
 
-func SyncSapBar(ctx context.Context) {
+func SyncMaterialOutbound() error {
 	tx := restful.Engine.NewSession()
 	defer tx.Close()
 
-	year := time.Now().Year()
+	pastureinfo := new(udPastureInfo)
+	err := tx.SQL(`select column_default  as pastureid   from    information_schema.COLUMNS
+	WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
+	if err != nil {
+		logs.Error(err)
+		return err
+	}
+	materialOutbound(pastureinfo.Pastureid, time.Now().AddDate(0, 0, -1).Format("2006-01-02"))
+	return nil
+}
+
+func SyncSapBar(c *gin.Context) {
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	fsion := gofasion.NewFasion(string(dataByte))
+	start := fsion.Get("startTime").ValueStr()
+	end := fsion.Get("endTime").ValueStr()
+	pastureId := fsion.Get("pastureId").ValueStr()
+
+	tx := restful.Engine.NewSession()
+	defer tx.Close()
+
+	pastureinfo := new(udPastureInfo)
+	err := tx.SQL(`select * from pasture where pastureid = ?`, pastureId).GetFirst(pastureinfo).Error
+	if err != nil {
+		logs.Error(err)
+		return
+	}
+
+	// year := time.Now().Year()
 	data := `{
-		"DEST": {
-		  "DEST_ID": "TMRWATCH",
-		  "BUSS_TP": "CO005"
-		},
 		"DATA": {
-		  "DIDAT": "%d0101",
-		  "DITIM": "%d1231",
-		  "WERKS": "M001",
-		  "TCHSNO": [ ],
-		  "TFCWTS": [ ],
-		  "TCHSTY": [ ]
+			"DIDAT": "%s",
+			"DITIM": "%s",
+			"WERKS": "%s"
+		},
+		"DEST": {
+			"DEST_ID": "TMRWATCH",
+			"BUSS_TP": "CO005"
 		}
 	}`
+
+	startTime, _ := time.ParseInLocation("2006-01-02", start, time.Local)
+	endTime, _ := time.ParseInLocation("2006-01-02", end, time.Local)
+
 	url := "http://192.168.61.117/SAPP0/Feed/CO005/QueryCowsheds"
-	data = fmt.Sprintf(data, year, year)
-	respmap := postPush(url, data)
+	data = fmt.Sprintf(data, startTime.Format("20060102"), endTime.Format("20060102"), pastureinfo.Werks)
+	respmap, _ := postPush(url, data, 3, tx, pastureId)
 	if respmap != nil {
 		if _, ok := respmap.(map[string]interface{})["ZTCO_001"]; ok {
 			for _, item := range respmap.(map[string]interface{})["ZTCO_001"].([]interface{}) {
 				barMap := item.(map[string]interface{})
-				_, err := tx.SQL(` insert into bar(pastureid,bcode,bname,sort,sapid,class,classid,scopeherd,scopeherdid)
-				values(?,?,?,(select max(sort)+1  from bar b where b.pastureid = ? ),?,( select name from barclass where pastureid = ? and code = ?),( select id from barclass where pastureid = ? and code = ?),(select name from scopeherd where code = ? ),
-				(select id from scopeherd where code = ? ))
-				ON DUPLICATE KEY UPDATE bname = ? ,bcode = ? `, 1, barMap["CHSTX"], barMap["CHSTX"], 1, barMap["CHSNO"], 1, barMap["CHSTX"], 1, barMap["CHSTX"],
-					barMap["FCWTS"], barMap["FCWTS"], barMap["CHSTX"], barMap["CHSTX"]).Execute()
+				_, err := tx.SQL(` insert into bar(pastureid,bcode,bname,sort,class,classcode,cattle,cattlecode,sapcode)
+				values(?,?,?,(select max(sort)+1  from bar b where b.pastureid = ? ),
+				(select distName  from dist where distCode = ? and distType = '牛舍类型' ),?,
+				(select distName  from dist where distCode = ?  and distType = '牛群类别'),?,?)
+				ON DUPLICATE KEY UPDATE bname = ? ,
+				class = (select distName  from dist where distCode = ?  and distType = '牛舍类型' ) ,classcode = ?,
+				cattle = (select distName  from dist where distCode = ? and distType = '牛群类别' ) ,cattlecode = ?
+				 `,
+					pastureId, barMap["CHSNO"], fmt.Sprintf("%v_sap", barMap["CHSTX"]), pastureId, barMap["CHSTY"], barMap["CHSTY"],
+					barMap["FCWTS"], barMap["FCWTS"], barMap["CHSNO"],
+					fmt.Sprintf("%v_sap", barMap["CHSTX"]), barMap["CHSTY"], barMap["CHSTY"], barMap["FCWTS"], barMap["FCWTS"]).Execute()
 				if err != nil {
 					logs.Error(err)
 					return
@@ -56,42 +93,126 @@ func SyncSapBar(ctx context.Context) {
 			}
 		}
 	}
+
+	appG.Response(http.StatusOK, e.SUCCESS, true)
 }
 
 type udPastureInfo struct {
-	Token     string `xorm:"token"`
+	Werks     string `xorm:"werks"`
 	Pastureid string `xorm:"pastureid"`
 }
 
 func MaterialOutbound(c *gin.Context) {
 	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	fsion := gofasion.NewFasion(string(dataByte))
+	pastureId := fsion.Get("pastureid").ValueStr()
+	date := fsion.Get("date").ValueStr()
+
+	materialOutbound(pastureId, date)
+	appG.Response(http.StatusOK, e.SUCCESS, true)
+}
+
+func materialOutbound(pastureId, date string) error {
 
 	tx := restful.Engine.NewSession()
 	defer tx.Close()
-
 	pastureinfo := new(udPastureInfo)
-	err := tx.SQL(`select column_default  as pastureid   from    information_schema.COLUMNS
-	WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
+	err := tx.SQL(`select * from pasture where pastureid = ?`, pastureId).GetFirst(pastureinfo).Error
 	if err != nil {
 		logs.Error(err)
-		return
+		return err
 	}
 
-	dataList, err := tx.SQL(`	select d1.fname as MAKTX,d2.fname as CHSTX, round( d1.actualweightminus * (d2.lweight / (select sum(lweight) from  downloadplandtl2  where pid = d2.pid )),2) as MENGE,b.sapid 	
-	,bc.code as FCWTS
-	from  downloadedplan d  
- JOIN downloadplandtl2 d2 on d2.pid in ( select id from downloadedplan where pid = d.pid and mydate = d.mydate) and d2.type = 0    
-	join downloadplandtl1 d1 on  d1.pid = d.id  
+	dataList, err := tx.SQL(`		SELECT 
+	tem.sort ZEILE,
+	tem.feedname MAKTX,
+	ifnull(ROUND(if(tem.lweight<0,0,tem.lweight),(select  inforvalue from sysopt  where inforname="decimalPlaces" and pastureid =? )),0)lweight,
+	ifnull(ROUND(tem.actualweightminus,(select  inforvalue from sysopt  where inforname="decimalPlaces" and pastureid = ?)),0) MENGE
+	,tem.bname CHSTX,tem.sapcode CHSNO,tem.cattle FCWTS,tem.MATNR,tem.sapGoods LGORT
+
+	 FROM (
+	 
+	 
+	 
+	(SELECT 
+	d2.type,
+	 d2.fname,IFNULL(ftd.fname,d1.fname ) feedname,
+	SUM(
+	  d2.lweight/(SELECT SUM(lweight) FROM downloadplandtl2  d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
+	  d1.lweight*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid and ftd2.date= ftp.date  ))
+	 )lweight,
+	d1.sort sort,
+		  SUM(
+		 if ( (SELECT SUM(actualweightminus) FROM downloadplandtl2  d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date) > 0 ,
+	  d2.actualweightminus/(SELECT SUM(actualweightminus) FROM downloadplandtl2  d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
+	  d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid and ftd2.date= ftp.date )),
+		
+		 d2.lweight/(SELECT SUM(lweight) FROM downloadplandtl2  d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
+	  d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetail ftd2 WHERE ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid ))
+		)
+	 )actualweightminus,b.sort as d2sort,b.bname,b.sapcode, b.cattlecode ,f.sapCode MATNR,f.sapGoods ,(select cattle from feedtemplet where id = d.tempid) cattle
+	 
+	 FROM 
+	downloadedplan d
+	
+	JOIN downloadplandtl2 d2
+	ON d.pastureid = d2.pastureid AND d2.pid = d.id   and d2.type = 0
+	JOIN downloadplandtl1 d1
+	ON d.pastureid = d1.pastureid AND d1.flpid = d2.flpid AND d1.type = 0 AND d2.date = d1.date
+	LEFT JOIN ftdetaildate ftd ON  ftd.pastureid =d1.pastureid AND ftd.ftid = d1.fid AND d1.feedcode = '-1' AND ftd.date = d.mydate AND ftd.version = d.tversion
+	left join bar b  on b.pastureid =d1.pastureid and b.id = d2.fbarid 
+	left join feed f on f.id = d1.fid
+	left join feedtempletdate ftp  on ftp.id = d.tempid  AND ftp.date = ftd.date
+	
+
+	WHERE d.pastureid = ? AND  d.mydate = ? and d1.feedcode  != -1   and  b.sapCode is not null  and  f.sapCode is not null 
+	GROUP BY d2.fbarid,IFNULL(ftd.fname,d1.fname )
+	HAVING d2.type = 0  order by b.sort,d2.fbarid)
 	
--- 	join feed  f on f.feedcode = d1.feedcode and f.pastureid = d.pastureid
-join bar  b on b.id = d2.fbarid  and b.pastureid = d.pastureid
-left join barclass bc on bc.id = b.classid 
-	where d.mydate = ? and d.lpplantype <> 2 	 and d.pastureid = ?
- order by d.id `, "2022-06-24", pastureinfo.Pastureid).Query().List()
+	UNION
+	
+		(SELECT 
+	d2.type,
+	 d2.fname,IFNULL(ftd.fname,d1.fname ) feedname,
+	SUM(
+	  d2.lweight/(SELECT SUM(lweight) FROM downloadplandtl2  d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
+	  d1.lweight*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid and ftd2.date= ftp.date ))
+	 )lweight,
+	d1.sort sort,
+		  SUM(
+		 if ( (SELECT SUM(actualweightminus) FROM downloadplandtl2  d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date) > 0 ,
+	  d2.actualweightminus/(SELECT SUM(actualweightminus) FROM downloadplandtl2  d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
+	  d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid and ftd2.date= ftp.date  )),
+		
+		 d2.lweight/(SELECT SUM(lweight) FROM downloadplandtl2  d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
+	  d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetail ftd2 WHERE ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid ))
+		)
+	 )actualweightminus,b.sort as d2sort,b.bname,b.sapcode, b.cattlecode ,f.sapCode MATNR,f.sapGoods ,(select cattle from feedtemplet where id = d.tempid) cattle
+	 
+	 FROM 
+	downloadedplan d
+	
+	JOIN downloadplandtl2 d2
+	ON d.pastureid = d2.pastureid AND d2.pid = d.id   and d2.type = 0
+	JOIN downloadplandtl1 d1
+	ON d.pastureid = d1.pastureid AND d1.flpid = d2.flpid AND d1.type = 0 AND d2.date = d1.date
+-- 	LEFT JOIN ftdetaildate ftd ON  ftd.pastureid =d1.pastureid AND ftd.ftid = d1.fid AND d1.feedcode = '-1' AND ftd.date = d.mydate AND ftd.version = d.tversion
+	left join bar b  on b.pastureid =d1.pastureid and b.id = d2.fbarid 
+	
+	left join feedtempletdate ftp  on ftp.id = d1.fid  and ftp.date = ?
+	left join ftdetaildate ftd on  ftd.ftid = ftp.id   and ftd.date = ?
+left join feed f on f.id = ftd.fid
+	WHERE d.pastureid = ? AND  d.mydate = ? and d1.feedcode  = -1   and  b.sapCode is not null  and  f.sapCode is not null 
+	GROUP BY d2.fbarid,IFNULL(ftd.fname,d1.fname )
+	HAVING d2.type = 0  order by b.sort,d2.fbarid)
+	
+	) tem
+	
+	ORDER BY tem.d2sort,tem.feedname   `, pastureId, pastureId, pastureId, date, date, date, pastureId, date).Query().List()
 	if err != nil {
 		logs.Error(err)
-		appG.Response(http.StatusInternalServerError, e.ERROR, false)
-		return
+		return err
 	}
 
 	data := `{
@@ -106,47 +227,71 @@ left join barclass bc on bc.id = b.classid
 		}
 	  }`
 	databyte, _ := json.Marshal(dataList)
-	data = fmt.Sprintf(data, time.Now().Format("20060102"), "0001", string(databyte))
-	url := "http://192.168.61.117/SAPP0/Feed/MM016/StockOut"
-	postPush(url, data)
 
-	appG.Response(http.StatusOK, e.SUCCESS, true)
+	now, _ := time.ParseInLocation("2006-01-02", date, time.Local)
+
+	data = fmt.Sprintf(data, now.Format("20060102"), pastureinfo.Werks, string(databyte))
+	url := "http://192.168.61.117/SAPP0/Feed/MM016/StockOut"
+	postPush(url, data, 0, tx, pastureId)
+	return nil
+	// appG.Response(http.StatusOK, e.SUCCESS, true)
 }
 
-func postPush(url, data string) interface{} {
+func postPush(url, data string, msgtype int, tx *xorm.Session, pastureId string) (interface{}, bool) {
 	var jsonStr = []byte(data)
 	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
 	if err != nil {
 		logs.Error(err)
-		return nil
+		// return nil
 	}
 
-	req.SetBasicAuth("zinf_TMR", "zinf_TMR@1234")
+	// req.SetBasicAuth("zinf_TMR", "zinf_TMR@1234")  测试线密码
+	req.SetBasicAuth("zinf_TMR", "$C2Cj$\\Uv#")
 	req.Header.Set("Content-Type", "application/json")
 	client := &http.Client{}
 	resp, err := client.Do(req)
 	if err != nil {
 		logs.Error(err)
-		return nil
+		// return nil
 	}
-
+	fmt.Println(resp.Body)
 	defer resp.Body.Close()
 	body, _ := ioutil.ReadAll(resp.Body)
-
 	var respData map[string]interface{}
+	tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url)
+	values(?,?,?,?,?,now(),?,now(),?)`, pastureId, data, string(body), "", "", msgtype, url)
+
 	err = json.Unmarshal(body, &respData)
 	if err != nil {
 		logs.Error(err)
-		return nil
+		// return nil
 	}
+
 	if _, ok := respData["DATA"]; ok {
-		return respData["DATA"]
+		if msgtype == 3 {
+			if _, ok := respData["ZTCO_001"]; !ok {
+				return respData["DATA"], false
+			}
+			return respData["DATA"], true
+		}
+		if _, ok := respData["DATA"]; !ok {
+			return respData["DATA"], false
+		}
+		return respData["DATA"], true
 	} else {
-		return nil
+		return respData["DATA"], false
 	}
 }
 
-func SyncSapFeed(ctx context.Context) {
+func SyncSapFeed(c *gin.Context) {
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	fsion := gofasion.NewFasion(string(dataByte))
+	start := fsion.Get("startTime").ValueStr()
+	end := fsion.Get("endTime").ValueStr()
+	mtart := fsion.Get("mtart").ValueStr()
+	pastureId := fsion.Get("pastureId").ValueStr()
+
 	tx := restful.Engine.NewSession()
 	defer tx.Close()
 
@@ -156,28 +301,42 @@ func SyncSapFeed(ctx context.Context) {
 			"BUSS_TP": "MM002"
 		},
 		"DATA": {
-			"BUDAT_B": "20220819",
-			"BUDAT_E": "20220819",
+			"BUDAT_B": "%s",
+			"BUDAT_E": "%s",
 			"TMTART": {
-				"MATNR": "XD01"
+				"MTART": "%s"
 				
 			},
 			"TMATKL": []
 		}
 	}`
 
-	url := "http://192.168.61.117/SAPP0/Common/MM002/QueryMaterial/"
-	respmap := postPush(url, data)
-
-	for _, item := range respmap.(map[string]interface{})["TMARA"].([]interface{}) {
-		sapMap := item.(map[string]interface{})
-		fmt.Println(sapMap)
-		_, err := tx.SQL(` replace into  feed_sap(MATNR,MTART,MATKL,MAKTX,MEINS,UMREZ,MEINH,UMREN,ZMINC,ZGUIG,LVORM,LAEDA)values(?,?,?,?,?,?,?,?,?,?,?,?)`,
-			sapMap["MATNR"], sapMap["MTART"], sapMap["MATKL"], sapMap["MAKTX"], sapMap["MEINS"], sapMap["UMREZ"], sapMap["MEINH"],
-			sapMap["UMREN"], sapMap["ZMINC"], sapMap["ZGUIG"], sapMap["LVORM"], sapMap["LAEDA"]).Execute()
-		if err != nil {
-			logs.Error(err)
-			return
+	startTime, _ := time.ParseInLocation("2006-01-02", start, time.Local)
+	endTime, _ := time.ParseInLocation("2006-01-02", end, time.Local)
+	data = fmt.Sprintf(data, startTime.Format("20060102"), endTime.Format("20060102"), mtart)
+	// "https://app.modernfarming.cn:7443/sap/Common/MM002/QueryMaterial/"
+	// http://192.168.61.117/SAPP0/Common/MM002/QueryMaterial
+	url := "http://192.168.61.117/SAPP0/Common/MM002/QueryMaterial"
+	respmap, success := postPush(url, data, 2, tx, pastureId)
+
+	// var a interface{} = nil
+	fmt.Println(respmap, success)
+	if success == false {
+		appG.Response(http.StatusOK, e.SUCCESS, true)
+	} else {
+		for _, item := range respmap.(map[string]interface{})["TMARA"].([]interface{}) {
+			sapMap := item.(map[string]interface{})
+			// fmt.Println(item)
+			_, err := tx.SQL(` replace into  feed_sap(MATNR,MTART,MATKL,MAKTX,MEINS,UMREZ,MEINH,UMREN,ZMINC,ZGUIG,LVORM,LAEDA)values(?,?,?,?,?,?,?,?,?,?,?,?)`,
+				sapMap["MATNR"], sapMap["MTART"], sapMap["MATKL"], sapMap["MAKTX"], sapMap["MEINS"], sapMap["UMREZ"], sapMap["MEINH"],
+				sapMap["UMREN"], sapMap["ZMINC"], sapMap["ZGUIG"], sapMap["LVORM"], sapMap["LAEDA"]).Execute()
+			if err != nil {
+				logs.Error(err)
+				return
+			}
 		}
+		appG.Response(http.StatusOK, e.SUCCESS, true)
 	}
+
+	// return
 }

+ 2 - 2
http/routers/root.go

@@ -19,8 +19,8 @@ func Root(opts ...func(engine *gin.Engine)) func(s *gin.Engine) {
 			middleware.CORS(),
 			gzip.Gzip(gzip.DefaultCompression),
 			middleware.Pagination(),
-			gin.Logger(),
-			gin.Recovery(),
+			middleware.GinLogger(),
+			middleware.GinRecovery(true),
 		)
 	}
 }

+ 1 - 0
middleware/inject/inject.go

@@ -3,6 +3,7 @@ package inject
 /*
 import (
 	"runtime"
+
 	"tmr-watch/conf/setting"
 	"tmr-watch/service/bll"
 

+ 107 - 0
middleware/log.go

@@ -0,0 +1,107 @@
+package middleware
+
+import (
+	"bytes"
+	"io/ioutil"
+
+	"net"
+	"net/http"
+	"net/http/httputil"
+	"os"
+	"runtime/debug"
+	"strings"
+	"time"
+
+	"gitee.com/xuyiping_admin/pkg/logger/zaplog"
+	"github.com/gin-gonic/gin"
+	"go.uber.org/zap"
+)
+
+type responseBodyWriter struct {
+	gin.ResponseWriter
+	body *bytes.Buffer
+}
+
+func (r responseBodyWriter) Write(b []byte) (int, error) {
+	r.body.Write(b)
+	return r.ResponseWriter.Write(b)
+}
+
+// GinLogger 接管gin框架默认的日志
+func GinLogger() gin.HandlerFunc {
+	return func(c *gin.Context) {
+		// 获取 response 内容
+		w := &responseBodyWriter{body: &bytes.Buffer{}, ResponseWriter: c.Writer}
+		c.Writer = w
+
+		var requestBody []byte
+		if c.Request.Body != nil {
+			requestBody, _ = ioutil.ReadAll(c.Request.Body)
+			c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(requestBody))
+		}
+		start := time.Now()
+		c.Next()
+		cost := time.Since(start)
+
+		logFields := []zap.Field{
+			zap.Int("status", c.Writer.Status()),
+			zap.String("request", c.Request.Method+" "+c.Request.URL.String()),
+			zap.String("query", c.Request.URL.RawQuery),
+			zap.String("ip", c.ClientIP()),
+			zap.String("user-agent", c.Request.UserAgent()),
+			zap.String("errors", c.Errors.ByType(gin.ErrorTypePrivate).String()),
+			zap.String("time", cost.String()),
+			zap.String("x-request-id", c.Request.Header.Get("X-Request-Id")),
+		}
+		logFields = append(logFields, zap.String("Request body", string(requestBody)))
+		logFields = append(logFields, zap.String("Response body", w.body.String()))
+		zaplog.Info("Http-Access-Log", logFields...)
+	}
+}
+
+// GinRecovery recover掉我的项目可能呈现的panic
+func GinRecovery(stack bool) gin.HandlerFunc {
+	return func(c *gin.Context) {
+		defer func() {
+			if err := recover(); err != nil {
+				// Check for a broken connection, as it is not really a
+				// condition that warrants a panic stack trace.
+				var brokenPipe bool
+				if ne, ok := err.(*net.OpError); ok {
+					if se, ok := ne.Err.(*os.SyscallError); ok {
+						if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") {
+							brokenPipe = true
+						}
+					}
+				}
+
+				httpRequest, _ := httputil.DumpRequest(c.Request, false)
+				if brokenPipe {
+					zaplog.Error(c.Request.URL.Path,
+						zap.Any("error", err),
+						zap.String("request", string(httpRequest)),
+					)
+					// If the connection is dead, we can't write a status to it.
+					c.Error(err.(error)) // nolint: errcheck
+					c.Abort()
+					return
+				}
+
+				if stack {
+					zaplog.Error("[Recovery from panic]",
+						zap.Any("error", err),
+						zap.String("request", string(httpRequest)),
+						zap.String("stack", string(debug.Stack())),
+					)
+				} else {
+					zaplog.Error("[Recovery from panic]",
+						zap.Any("error", err),
+						zap.String("request", string(httpRequest)),
+					)
+				}
+				c.AbortWithStatus(http.StatusInternalServerError)
+			}
+		}()
+		c.Next()
+	}
+}

+ 220 - 0
migration/haiyuan.sql

@@ -0,0 +1,220 @@
+CREATE TABLE `dist` (
+  `id` INT(11) NOT NULL AUTO_INCREMENT,
+  `distType` VARCHAR(30) DEFAULT NULL,
+  `distName` VARCHAR(50) DEFAULT NULL,
+  `distCode` VARCHAR(50) DEFAULT NULL,
+  `remark` VARCHAR(50) DEFAULT NULL,
+  PRIMARY KEY (`id`) USING BTREE
+) ENGINE=INNODB AUTO_INCREMENT=321 DEFAULT CHARSET=utf8mb3 ROW_FORMAT=COMPACT;
+
+
+CREATE TABLE `bar_sap` (
+  `id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '栏舍id',
+  `pastureid` BIGINT(20) NOT NULL COMMENT '牧场id',
+  `bcode` VARCHAR(50) DEFAULT NULL COMMENT '栏舍编号',
+  `bname` VARCHAR(200) NOT NULL COMMENT '栏舍名称',
+  `allowratio` INT(11) DEFAULT 0 COMMENT '允许误差数',
+  `autozone` INT(11) DEFAULT 0 COMMENT '跳转重量域(kg)',
+  `autosecond` INT(4) DEFAULT 0 COMMENT '跳转延时值',
+  `autosecondname` VARCHAR(50) DEFAULT NULL COMMENT '跳转延时名称',
+  `isstart` TINYINT(1) DEFAULT 1 COMMENT '确认开始',
+  `begintag` INT(11) DEFAULT NULL,
+  `endtag` INT(11) DEFAULT NULL,
+  `sort` INT(11) DEFAULT 0 COMMENT '排序',
+  `enable` TINYINT(1) DEFAULT 1 COMMENT '是否启用',
+  `isdelete` TINYINT(1) DEFAULT 0 COMMENT '是否删除(0为未删除,1为伪删除)',
+  `backup1` VARCHAR(255) DEFAULT NULL COMMENT '备用1',
+  `backup2` VARCHAR(255) DEFAULT NULL COMMENT '备用2',
+  `AUFNR` VARCHAR(50) DEFAULT NULL COMMENT 'sap牛群订单行号',
+  `class` VARCHAR(50) DEFAULT NULL COMMENT '牛舍类型',
+  `classcode` VARCHAR(50) DEFAULT NULL COMMENT '牛舍类型编码',
+  `cattle` VARCHAR(50) DEFAULT NULL COMMENT '牛群',
+  `cattlecode` VARCHAR(50) DEFAULT NULL COMMENT '牛群编码',
+  `sapCode` VARCHAR(50) DEFAULT NULL,
+  PRIMARY KEY (`id`,`pastureid`) USING BTREE,
+  UNIQUE KEY `bar_bname` (`bname`,`pastureid`) USING BTREE,
+  UNIQUE KEY `bar_bcode` (`bcode`,`pastureid`) USING BTREE,
+  UNIQUE KEY `pastureid` (`pastureid`,`sapCode`)
+) ENGINE=INNODB AUTO_INCREMENT=4354454795596596571 DEFAULT CHARSET=utf8mb3 ROW_FORMAT=DYNAMIC COMMENT='栏舍';
+
+CREATE TABLE `cattleorder` (
+  `AUFNR` VARCHAR(20) NOT NULL COMMENT '订单号',
+  `KTEXT` VARCHAR(50) DEFAULT NULL COMMENT '订单描述',
+  `ZNZLX` VARCHAR(50) DEFAULT NULL COMMENT '牛只类型 A-母犊牛 B-母育成牛 C-母青年牛 D-母泌乳牛 E-母干奶牛 F-公牛',
+  `AUART` VARCHAR(50) DEFAULT NULL COMMENT '订单类型编码',
+  `AUTXT` VARCHAR(50) DEFAULT NULL COMMENT '订单类型名称',
+  `BUKRS` VARCHAR(50) DEFAULT NULL COMMENT '公司代码',
+  `BUTXT` VARCHAR(50) DEFAULT NULL COMMENT '公司代码名称',
+  PRIMARY KEY (`AUFNR`)
+) ENGINE=INNODB DEFAULT CHARSET=utf8mb3;
+
+
+CREATE TABLE `feed_sap` (
+  `id` BIGINT(20) NOT NULL AUTO_INCREMENT,
+  `MATNR` VARCHAR(50) DEFAULT NULL COMMENT '物料号',
+  `MTART` VARCHAR(50) DEFAULT NULL COMMENT '物料类型',
+  `MATKL` VARCHAR(50) DEFAULT NULL COMMENT '物料组',
+  `MAKTX` VARCHAR(50) DEFAULT NULL COMMENT '物料描述',
+  `MEINS` VARCHAR(50) DEFAULT NULL COMMENT '基本计量单位',
+  `UMREZ` VARCHAR(50) DEFAULT NULL COMMENT '基本计量单位数量',
+  `MEINH` VARCHAR(50) DEFAULT NULL COMMENT '转换单位',
+  `UMREN` VARCHAR(50) DEFAULT NULL COMMENT '转换单位数量',
+  `ZMINC` VARCHAR(50) DEFAULT NULL COMMENT '物料名称',
+  `ZGUIG` VARCHAR(50) DEFAULT NULL COMMENT '规格型号',
+  `LVORM` VARCHAR(50) DEFAULT NULL COMMENT '物料删除标记',
+  `LAEDA` VARCHAR(50) DEFAULT NULL COMMENT '修改日期',
+  PRIMARY KEY (`id`)
+) ENGINE=INNODB AUTO_INCREMENT=1156 DEFAULT CHARSET=utf8mb3;
+
+
+
+  CREATE TABLE `saplog` (
+    `id` BIGINT(20) NOT NULL AUTO_INCREMENT,
+    `pastureId` VARCHAR(20) DEFAULT NULL,
+    `request` LONGTEXT DEFAULT NULL,
+    `response` LONGTEXT DEFAULT NULL,
+    `status` VARCHAR(20) DEFAULT NULL,
+    `msgtext` VARCHAR(255) DEFAULT NULL,
+    `url` VARCHAR(255) DEFAULT NULL,
+    `createTime` DATETIME DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(),
+    `msgtype` INT(1) DEFAULT NULL COMMENT '0饲喂  1剩料  2原料  3栏舍  4配方 5栏舍牛头数 6库存',
+    `dataDate` VARCHAR(20) DEFAULT NULL COMMENT '数据日期',
+    PRIMARY KEY (`id`)
+  ) ENGINE=INNODB AUTO_INCREMENT=2039 DEFAULT CHARSET=utf8mb3;
+	
+	
+	
+	
+	ALTER TABLE `tmr` 
+ADD COLUMN `gps` VARCHAR(50) NULL;
+
+
+
+ALTER TABLE `tmr` 
+ADD INDEX(`pastureid`, `gps`);
+
+
+
+
+
+
+
+
+
+
+
+
+  ALTER TABLE `pasture` 
+  ADD COLUMN `werks` VARCHAR(30) NULL  ;
+
+  ALTER TABLE `bar` 
+  ADD COLUMN `AUFNR` VARCHAR(50) NULL COMMENT 'sap牛群订单行号';
+
+  ALTER TABLE `bar` 
+  ADD COLUMN `class` VARCHAR(50) NULL COMMENT '牛舍类型' AFTER `AUFNR`,
+  ADD COLUMN `classcode` VARCHAR(50) NULL COMMENT '牛舍类型编码' AFTER `class`,
+  ADD COLUMN `cattle` VARCHAR(50) NULL COMMENT '牛群' AFTER `classcode`,
+  ADD COLUMN `cattlecode` VARCHAR(50) NULL COMMENT '牛群编码' AFTER `cattle`;
+
+
+  ALTER TABLE `bar` 
+  ADD COLUMN `sapCode` VARCHAR(50) NULL AFTER `cattlecode`;
+
+
+
+  
+  ALTER TABLE `feed` 
+  ADD COLUMN 	`sapMtart` BIGINT(20) DEFAULT NULL COMMENT 'sap编码',
+  ADD COLUMN  `sapGewei` VARCHAR(20) DEFAULT NULL COMMENT 'sap单位',
+  ADD COLUMN   `sapLGPRO` VARCHAR(20) DEFAULT NULL COMMENT 'sap牧场编码',
+  ADD COLUMN  `sapCHARG` VARCHAR(20) DEFAULT NULL,
+  ADD COLUMN  `sapCode` VARCHAR(20) DEFAULT NULL;
+
+
+  ALTER TABLE `feed` 
+  MODIFY COLUMN `sapCode` VARCHAR(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT 'sap编码' AFTER `sapCHARG`,
+  ADD COLUMN `sapMaterialtype` VARCHAR(50) NULL COMMENT 'sap物料类型' AFTER `sapCode`,
+  ADD COLUMN `sapGoods` VARCHAR(50) NULL COMMENT 'sap货位' AFTER `sapMaterialtype`;
+
+
+  ALTER TABLE `feedtemplet` 
+  ADD COLUMN `cattle` VARCHAR(30) NULL COMMENT '牛群类别' AFTER `backup2`;
+	
+	  ALTER TABLE `feedtemplet` 
+  ADD COLUMN 
+	`volume` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '容积';
+	
+		  ALTER TABLE `tmr` 
+  ADD COLUMN 
+	`volume` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '容积';
+	
+	
+			  ALTER TABLE `feedtemplethistory` 
+  ADD COLUMN 
+	`volume` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '容积';
+	
+	
+		
+			  ALTER TABLE `feedtempletdate` 
+  ADD COLUMN 
+	`volume` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '容积';
+
+
+
+
+
+			  ALTER TABLE `feedtemplethistory` 
+  ADD COLUMN 
+`userId` VARCHAR(30) DEFAULT NULL COMMENT '修改用户';
+		
+			  ALTER TABLE `feedtempletdate` 
+  ADD COLUMN 
+`userId` VARCHAR(30) DEFAULT NULL COMMENT '修改用户';
+
+
+
+ALTER TABLE `feedphistory` 
+  ADD COLUMN 
+`userId` VARCHAR(30) DEFAULT NULL COMMENT '修改用户';
+
+
+
+ALTER TABLE `fpdetailhistory` 
+  ADD COLUMN 
+`userId` VARCHAR(30) DEFAULT NULL COMMENT '修改用户';
+
+
+
+ALTER TABLE `lpplandtl1history` 
+  ADD COLUMN 
+`userId` VARCHAR(30) DEFAULT NULL COMMENT '修改用户';
+
+
+ALTER TABLE `fit_history` 
+  ADD COLUMN 
+`userId` VARCHAR(30) DEFAULT NULL COMMENT '修改用户';
+
+
+
+ALTER TABLE `downloadedplan` 
+  ADD COLUMN 
+`driverId` BIGINT(20) DEFAULT NULL COMMENT '驾驶员';
+
+
+CREATE TABLE `remind` (
+  `id` BIGINT(20) NOT NULL AUTO_INCREMENT,
+  `message` VARCHAR(100) DEFAULT NULL,
+  `trigger` VARCHAR(100) DEFAULT NULL COMMENT '触发',
+  `pastureid` INT(11) NOT NULL,
+  `user` LONGTEXT NOT NULL,
+  `function` VARCHAR(100) DEFAULT NULL,
+  `service_id` INT(3) DEFAULT NULL COMMENT '返回得类型id',
+  PRIMARY KEY (`id`,`pastureid`) USING BTREE
+) ENGINE=INNODB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4;
+
+
+
+
+
+
+

+ 149 - 0
migration/update.sql

@@ -0,0 +1,149 @@
+ALTER TABLE `tmrwatch2`.`tmr` 
+ADD COLUMN `gps` varchar(50) NULL AFTER `lastinorout`;
+
+
+ALTER TABLE `tmrwatch2`.`downloadedplan` 
+ADD COLUMN `driverId` bigint NOT NULL DEFAULT 0 COMMENT '驾驶员' ;
+
+ALTER TABLE `tmrwatch2`.`tmr` 
+ADD INDEX(`pastureid`, `gps`);
+
+
+
+
+
+
+
+
+
+
+
+
+  ALTER TABLE `tmrwatch2`.`pasture` 
+  ADD COLUMN `werks` varchar(30) NULL AFTER `isgroups`;
+
+  ALTER TABLE `tmrwatch2`.`bar` 
+  ADD COLUMN `AUFNR` varchar(50) NULL COMMENT 'sap牛群订单行号' AFTER `backup2`;
+
+  ALTER TABLE `tmrwatch2`.`bar` 
+  ADD COLUMN `class` varchar(50) NULL COMMENT '牛舍类型' AFTER `AUFNR`,
+  ADD COLUMN `classcode` varchar(50) NULL COMMENT '牛舍类型编码' AFTER `class`,
+  ADD COLUMN `cattle` varchar(50) NULL COMMENT '牛群' AFTER `classcode`,
+  ADD COLUMN `cattlecode` varchar(50) NULL COMMENT '牛群编码' AFTER `cattle`;
+
+
+  ALTER TABLE `tmrwatch2`.`bar` 
+  ADD COLUMN `sapCode` varchar(50) NULL AFTER `cattlecode`;
+
+
+
+  
+  ALTER TABLE `tmrwatch2`.`feed` 
+  ADD COLUMN 	`sapMtart` bigint(20) DEFAULT NULL COMMENT 'sap编码',
+  ADD COLUMN  `sapGewei` varchar(20) DEFAULT NULL COMMENT 'sap单位',
+  ADD COLUMN   `sapLGPRO` varchar(20) DEFAULT NULL COMMENT 'sap牧场编码',
+  ADD COLUMN  `sapCHARG` varchar(20) DEFAULT NULL,
+  ADD COLUMN  `sapCode` varchar(20) DEFAULT NULL;
+
+
+  ALTER TABLE `tmrwatch2`.`feed` 
+  MODIFY COLUMN `sapCode` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT 'sap编码' AFTER `sapCHARG`,
+  ADD COLUMN `sapMaterialtype` varchar(50) NULL COMMENT 'sap物料类型' AFTER `sapCode`,
+  ADD COLUMN `sapGoods` varchar(50) NULL COMMENT 'sap货位' AFTER `sapMaterialtype`;
+
+
+  ALTER TABLE `tmrwatch2`.`feedtemplet` 
+  ADD COLUMN `cattle` varchar(30) NULL COMMENT '牛群类别' AFTER `backup2`;
+
+
+  CREATE TABLE `saplog` (
+    `id` bigint(20) NOT NULL AUTO_INCREMENT,
+    `pastureId` varchar(20) DEFAULT NULL,
+    `request` longtext DEFAULT NULL,
+    `response` longtext DEFAULT NULL,
+    `status` varchar(20) DEFAULT NULL,
+    `msgtext` varchar(255) DEFAULT NULL,
+    `url` varchar(255) DEFAULT NULL,
+    `createTime` datetime DEFAULT NULL ON UPDATE current_timestamp(),
+    `msgtype` int(1) DEFAULT NULL COMMENT '0饲喂  1剩料  2原料  3栏舍  4配方 5栏舍牛头数 6库存',
+    `dataDate` varchar(20) DEFAULT NULL COMMENT '数据日期',
+    PRIMARY KEY (`id`)
+  ) ENGINE=InnoDB AUTO_INCREMENT=2039 DEFAULT CHARSET=utf8mb3;
+	
+	
+	
+	CREATE TABLE `dist` (
+  `id` int(11) NOT NULL AUTO_INCREMENT,
+  `distType` varchar(30) DEFAULT NULL,
+  `distName` varchar(50) DEFAULT NULL,
+  `distCode` varchar(50) DEFAULT NULL,
+  `remark` varchar(50) DEFAULT NULL,
+  PRIMARY KEY (`id`) USING BTREE
+) ENGINE=InnoDB AUTO_INCREMENT=321 DEFAULT CHARSET=utf8mb3 ROW_FORMAT=COMPACT;
+
+
+CREATE TABLE `cattleorder` (
+  `AUFNR` varchar(20) NOT NULL COMMENT '订单号',
+  `KTEXT` varchar(50) DEFAULT NULL COMMENT '订单描述',
+  `ZNZLX` varchar(50) DEFAULT NULL COMMENT '牛只类型 A-母犊牛 B-母育成牛 C-母青年牛 D-母泌乳牛 E-母干奶牛 F-公牛',
+  `AUART` varchar(50) DEFAULT NULL COMMENT '订单类型编码',
+  `AUTXT` varchar(50) DEFAULT NULL COMMENT '订单类型名称',
+  `BUKRS` varchar(50) DEFAULT NULL COMMENT '公司代码',
+  `BUTXT` varchar(50) DEFAULT NULL COMMENT '公司代码名称',
+  PRIMARY KEY (`AUFNR`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
+
+
+
+
+
+
+
+
+
+
+
+
+
+	
+	  ALTER TABLE `feedtemplet` 
+  ADD COLUMN 
+	`volume` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '容积';
+	
+		  ALTER TABLE `tmr` 
+  ADD COLUMN 
+	`volume` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '容积';
+	
+	
+			  ALTER TABLE `feedtemplethistory` 
+  ADD COLUMN 
+	`volume` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '容积';
+	
+	
+		
+			  ALTER TABLE `feedtempletdate` 
+  ADD COLUMN 
+	`volume` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '容积';
+
+
+
+
+
+
+ALTER TABLE `tmrwatch2`.`feedtemplethistory` 
+ADD COLUMN `userId` varchar(30) NULL COMMENT '修改用户' AFTER `volume`;
+
+ALTER TABLE `tmrwatch2`.`fpdetailhistory` 
+ADD COLUMN `userId` varchar(30) NULL COMMENT '修改用户' AFTER `createdate`;
+
+ALTER TABLE `tmrwatch2`.`feedphistory` 
+ADD COLUMN `userId` varchar(30) NULL COMMENT '修改用户' AFTER `createdate`;
+
+ALTER TABLE `tmrwatch2`.`lpplandtl1history` 
+ADD COLUMN `userId` varchar(30) NULL COMMENT '修改用户' AFTER `createdate`;
+
+ALTER TABLE `tmrwatch2`.`fit_history` 
+ADD COLUMN `userId` varchar(30) NULL AFTER `feedgroup`;
+
+
+