瀏覽代碼

develop: new code

Yi 1 年之前
父節點
當前提交
6ceb3056ce
共有 6 個文件被更改,包括 381 次插入6 次删除
  1. 18 2
      http/handle/api/ops.go
  2. 2 2
      http/handle/api/scheduled.go
  3. 2 1
      http/handle/api/udsync.go
  4. 349 0
      http/handle/gm/udservice.go
  5. 9 0
      http/routers/app_api.go
  6. 1 1
      pkg/logger/logrus/log.go

+ 18 - 2
http/handle/api/ops.go

@@ -3196,9 +3196,9 @@ func UpdateFTdetail(c *gin.Context) {
 
 						weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
 						oldweight, _ := strconv.ParseFloat(old["weight"].(string), 64)
-						if weight > oldweight {
+						/*if weight > oldweight {
 							return
-						}
+						}*/
 
 						var w float64
 						var status int
@@ -7462,6 +7462,22 @@ func ThiGetDataByName(c *gin.Context) {
 	}
 }
 
+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
+	err := udFeedpSync(pastureinfo)
+	if err != nil {
+		appG.Response(http.StatusOK, e.ERROR, err.Error())
+		return
+	}
+	appG.Response(http.StatusOK, e.SUCCESS, true)
+}
+
 // func ToggleCcount(c *gin.Context) {
 // 	appG := app.Gin{C: c}
 // 	dataByte, _ := ioutil.ReadAll(c.Request.Body)

+ 2 - 2
http/handle/api/scheduled.go

@@ -745,8 +745,8 @@ func (h *ScheduledDown) SyncFeedp(pastureid string, feedpList []interface{}) err
 		// 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()
+		fmt.Println(barCode)
+		_, err = tx.SQL(`update feedp fp set fp.softccount = ? where  (select bcode from bar where id = fp.id ) = ? `, cowCount, barName).Execute()
 		if err != nil {
 			tx.Rollback()
 			logs.Error("syncFeedp-error-7:", err)

+ 2 - 1
http/handle/api/udsync.go

@@ -24,7 +24,7 @@ func UDSync() {
 	defer tx.Close()
 
 	pastureinfo := new(udPastureInfo)
-	err := tx.SQL(`select token,pastureid  from pasture  p join ( select column_default   from    information_schema.COLUMNS 
+	err := tx.SQL(`select token,pastureid,werks from pasture  p join ( select column_default   from    information_schema.COLUMNS 
 		WHERE table_name = 'recweight' AND table_schema = 'tmrwatch2' AND column_name = 'pastureid') pas  
 		where p.pastureid = pas.column_default`).GetFirst(pastureinfo).Error
 	if err != nil {
@@ -362,6 +362,7 @@ func syncFeedtemplet(pastureid string, feedtempletList []map[string]interface{})
 type udPastureInfo struct {
 	Token     string `xorm:"token"`
 	Pastureid string `xorm:"pastureid"`
+	Werks     string `xorm:"werks"`
 }
 
 func httpGet(farmId, method string) []interface{} {

+ 349 - 0
http/handle/gm/udservice.go

@@ -0,0 +1,349 @@
+package gm
+
+import (
+	"bytes"
+	"encoding/json"
+	"fmt"
+	"io/ioutil"
+	"net/http"
+	"time"
+	"tmr-watch/conf/setting"
+	"tmr-watch/http/handle/restful"
+	"tmr-watch/pkg/logging"
+
+	"github.com/astaxie/beego/logs"
+	"github.com/xormplus/xorm"
+)
+
+func GmUdSync(pastureId, farmId string) {
+	fmt.Println(111)
+}
+
+func UdBarSync(pastureId, farmId string) {
+	url := fmt.Sprintf("http://172.16.86.95:8080/copartner_downloads?equipmentId=48ffa4de-7870-4b18-a052-9f8d3a46089a&farmId=%s&method=downloadpen", farmId)
+	barByte := getPull(url)
+
+	barMap := make(map[string]interface{})
+	json.Unmarshal(barByte, &barMap)
+
+	tx := restful.Engine.NewSession()
+	defer tx.Close()
+	tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url)
+	values(?,?,?,?,?,now(),?,now(),?)`, pastureId, "", string(barByte), "", "", 3, url)
+
+	for _, item := range barMap["msg"].([]interface{}) {
+		bar := item.(map[string]interface{})
+		barname := bar["barname"].(string) + "_ud"
+		barExist, _ := tx.SQL(` select count(1) from bar where bcode = ? `, bar["barcode"]).Exist()
+		tx.Exec(`insert into bar(pastureid,bcode,bname)values(?,?,?)   ON DUPLICATE KEY UPDATE  bname = ? `, pastureId, bar["barcode"], barname, barname)
+		_, _ = tx.Exec(`insert into feedp(pastureid,barid,barname,softccount,ccount)values(?,(select id from bar where bcode=  ? and pastureId = ? ),?,?,?)
+		 ON DUPLICATE KEY UPDATE  softccount = ? `,
+			pastureId, bar["barcode"], pastureId, barname, bar["cowcount"], bar["cowcount"], bar["cowcount"])
+		// fmt.Println(err)
+		if !barExist {
+			tx.Exec(`insert into fpdetail(pastureId,barid,weight,ptsrate,times,barname) values(?,(select id from bar where bcode=  ? and pastureId = ? ),0,0,?,?)`,
+				pastureId, bar["barcode"], 1, barname)
+			tx.Exec(`insert into fpdetail(pastureId,barid,weight,ptsrate,times,barname) values(?,(select id from bar where bcode=  ? and pastureId = ? ),0,0,?,?)`,
+				pastureId, bar["barcode"], 2, barname)
+			tx.Exec(`insert into fpdetail(pastureId,barid,weight,ptsrate,times,barname) values(?,(select id from bar where bcode=  ? and pastureId = ? ),0,0,?,?)`,
+				pastureId, bar["barcode"], 3, barname)
+			tx.Exec(`insert into fpdetail(pastureId,barid,weight,ptsrate,times,barname) values(?,(select id from bar where bcode=  ? and pastureId = ? ),0,0,?,?)`,
+				pastureId, bar["barcode"], 4, barname)
+			tx.Exec(`insert into fpdetail(pastureId,barid,weight,ptsrate,times,barname) values(?,(select id from bar where bcode=  ? and pastureId = ? ),0,0,?,?)`,
+				pastureId, bar["barcode"], 5, barname)
+			tx.Exec(`insert into fpdetail(pastureId,barid,weight,ptsrate,times,barname) values(?,(select id from bar where bcode=  ? and pastureId = ? ),0,0,?,?)`,
+				pastureId, bar["barcode"], 6, barname)
+		}
+	}
+
+}
+
+func UdFeedSync(pastureId, farmId string) {
+	url := fmt.Sprintf("http://172.16.86.95:8080/copartner_downloads?equipmentId=48ffa4de-7870-4b18-a052-9f8d3a46089a&farmId=%s&method=downloadmaterial", farmId)
+	feedByte := getPull(url)
+
+	tx := restful.Engine.NewSession()
+	defer tx.Close()
+	tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url)
+	values(?,?,?,?,?,now(),?,now(),?)`, pastureId, "", string(feedByte), "", "", 3, url)
+
+	feedMap := make(map[string]interface{})
+	json.Unmarshal(feedByte, &feedMap)
+
+	for _, item := range feedMap["msg"].([]interface{}) {
+		fmt.Println(item)
+		feed := item.(map[string]interface{})
+		feedname := feed["feedname"].(string) + "_ud"
+		feedClassExist, _ := tx.SQL(` select count(1) from feedclass where fccode = ? and pastureId = ? `, feed["feedclass"], pastureId).Exist()
+
+		if !feedClassExist {
+			tx.Exec(`insert into feedclass(pastureId,fcname,fccode,bigfeedclassname,sort) values(?,?,?,?,(select max(sort) 1 from feedclass where pastureId = ? and fccode = ? ))`,
+				pastureId, feed["feedclass"], feed["feedclass"], feed["feedclass"], pastureId, feed["feedclass"])
+		}
+		ids, err := setting.SnowIds.NextId()
+		if err != nil {
+			ids = time.Now().UnixNano()
+			logging.Info("create SnowIds err", err)
+		}
+		_, err = tx.Exec(`insert into feed(id,pastureId,feedcode,fname,fclassid,fclass) values(?,?,?,?,(select id from feedclass where fccode = ? and pastureId = ? ),?)
+		ON DUPLICATE KEY UPDATE fname = ? `,
+			ids, pastureId, feed["feedcode"], feedname, feed["feedclass"], pastureId, feed["feedclass"], feedname)
+	}
+}
+
+func getPull(url string) []byte {
+	// 创建一个HTTP客户端
+	client := &http.Client{}
+	// 创建一个GET请求
+	req, err := http.NewRequest("GET", url, nil)
+	if err != nil {
+		fmt.Println("创建请求时发生错误:", err)
+		return nil
+	}
+
+	// 发送请求
+	resp, err := client.Do(req)
+	if err != nil {
+		fmt.Println("发送请求时发生错误:", err)
+		return nil
+	}
+	defer resp.Body.Close()
+	// 读取响应内容
+	body, err := ioutil.ReadAll(resp.Body)
+	if err != nil {
+		fmt.Println("读取响应时发生错误:", err)
+		return nil
+	}
+
+	// 打印响应内容
+	//fmt.Println(string(body))
+
+	return body
+}
+
+//搅拌
+func UdUtirPush(pastureId, farmId string) error {
+	tx := restful.Engine.NewSession()
+	defer tx.Close()
+	now := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
+	dataList, err := tx.SQL(`select d1.date loadDate,d.times loadShift,d.datacaptureno  tmrNo,ft.id recipeId,ft.ccname,d1.feedcode,d1.fname,f.fclass,
+	f.dry * d1.actualweightminus  dmPct,d1.sort mixNo,d1.feedallowratio allowableError ,d1.lweight expWeight,d1.actualweightminus actualWeight,d1.begintime startTime,
+	d1.intime endTime, d.tmrtname tmrName , d.pid id ,ftd.sort premixFeedSort ,
+	 (select feedcode from feed where id = ftd.fid) premixFeedId,ftd.fname  premixFeedName,
+	ftd.fweight / (select sum(fweight)  from ftdetaildate  where  date =  d1.date and ftid = d1.fid ) *  d1.actualweightminus premixFeedWeight
+
+	from downloadplandtl1  d1 join  downloadedplan d on d.id = d1.pid
+	left join feedtempletdate ft  on ft.id = d.tempid  and ft.date = d1.date
+	left join feed f on f.feedcode  = d1.feedcode
+	left join ftdetaildate  ftd  on  ftd.date =  d1.date and ftd.ftid = d1.fid
+	where d1.date = ?`, now).Query().List()
+	if err != nil {
+		logging.Error(err)
+		return err
+	}
+
+	dataByte, _ := json.Marshal(&dataList)
+
+	reqJson := `{
+    "reqMethod": "PARTY",
+    "param": {
+        "code": "1",
+        "method": "uploadadddata",
+        "resultData": %s,
+        "farmId": %s,
+        "rowCount": %d,
+        "errMessage": ""
+    },
+    "regCode": "cpt180511",
+    "command": "3d6e4752",
+    "apiId": "getCptData"
+}`
+	reqJson = fmt.Sprintf(reqJson, string(dataByte), farmId, len(dataList))
+	postPush(reqJson, 0, tx, pastureId)
+	fmt.Println(reqJson)
+	return nil
+}
+
+func UdMaterialIssuePush(pastureId, farmId string) error {
+	tx := restful.Engine.NewSession()
+	defer tx.Close()
+	now := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
+	dataList, err := tx.SQL(`SELECT  dd.feedsort feedSort, dd.feedcode feedId,dd.fname feedName,
+	d.id,IFNULL(ft.id,d2.feedtempletid ) recipeId,
+	IFNULL(d.templetName,d2.feedtempletName ) recipeName,
+	date_format(d.mydate,'%Y-%m-%d') as dropDate,ifnull((select sort from downloadedplan where pid=d.pid and lpplanType !=d.lpplanType and mydate=d.mydate),d.sort) as tmrNo,
+	d.Times as dropShift,b.bcode as penId,d2.Fname as penName,fp.CCOUNT as cowCount, d2.SORT as feedingNo,
+ifnull(ROUND(d2.lweight * (dd.actualweightminus/ (select sum(actualweightminus) from downloadplandtl1 where pid = dd.pid and type = 0) ),2) ,0)as expWeight,
+	ifnull(d2.ActualWeightMinus,0) as actualWeight, ifnull(date_format(timestamp(d2.InTime,CONCAT('-',d2.processTime)),'%Y-%m-%d %H:%i:%s'),d.mydate) as startTime,
+	ifnull(date_format(d2.InTime,'%Y-%m-%d %H:%i:%s'),d.mydate) as endTime,ifnull((SELECT dr.driver FROM dutyrecord dr
+WHERE dr.pastureid = d.pastureid AND dr.eqid = d.tmrid AND dr.times= d.times  AND dr.operatetime <=d.mydate
+ORDER BY dr.operatetime DESC LIMIT 1),"") as tmrName ,d.tmrtname equipmentId ,
+dd.fname,
+  ifnull(TRIM(if(( select sum(dd2.actualweightminus) from downloadplandtl2 dd2 where dd2.pid = d2.pid) >0 ,   ROUND( d2.actualweightminus/( select sum(dd2.actualweightminus) from downloadplandtl2 dd2 where dd2.pid = d2.pid) * (dd.actualweightminus ),2), ROUND( d2.lweight/( select sum(dd2.lweight) from downloadplandtl2 dd2 where dd2.pid = d2.pid) * (dd.actualweightminus ),2))),0) feedWeight
+
+	,ftd.sort premixFeedSort ,
+	 (select feedcode from feed where id = ftd.fid) premixFeedId,ftd.fname  premixFeedName,
+	ftd.fweight / (select sum(fweight)  from ftdetaildate  where  date =  dd.date and ftid = dd.fid ) *  dd.actualweightminus premixFeedWeight
+
+	from  downloadedplan d
+	LEFT JOIN downloadplandtl2 d2 on d.id=d2.PID
+	LEFT JOIN (select dd.pid as lppid,dd1.* from downloadedplan dd join downloadplandtl1  dd1 on dd1.pid = dd.id and dd1.type = 0
+		where dd.mydate= date_format(?,'%Y-%m-%d')  and dd.lpplanType in (0,1) ) dd on dd.lppid = d.pid
+
+	LEFT JOIN feedp fp on d2.FBarID=fp.barid
+	left join bar b on fp.barid = b.id and d.pastureid = b.pastureid
+	left JOIN feedtemplet ft on d.tempid=ft.id
+		left join ftdetaildate  ftd  on  ftd.date =  dd.date and ftd.ftid = dd.fid
+
+	where d.mydate= date_format(?,'%Y-%m-%d')  and d.lpplanType!=1 and d.pastureid = ?   and dd.fname is not null  order by tmrno `, now, now, pastureId).Query().List()
+	if err != nil {
+		logging.Error(err)
+		return err
+	}
+
+	dataByte, _ := json.Marshal(&dataList)
+
+	reqJson := `{
+    "reqMethod": "PARTY",
+    "param": {
+        "code": "1",
+        "method": "uploaddiliverdata",
+        "resultData": %s,
+        "farmId": %s,
+        "rowCount": %d,
+        "errMessage": ""
+    },
+    "regCode": "cpt180511",
+    "command": "3d6e4752",
+    "apiId": "getCptData"
+}`
+	reqJson = fmt.Sprintf(reqJson, string(dataByte), farmId, len(dataList))
+	//  '0饲喂  1剩料  2原料  3栏舍  4配方 5栏舍牛头数 6库存',
+	postPush(reqJson, 0, tx, pastureId)
+	return nil
+}
+
+func UdBarFeedRemainPush(pastureId, farmId string) error {
+	tx := restful.Engine.NewSession()
+	defer tx.Close()
+	now := time.Now().AddDate(0, 0, 0).Format("2006-01-02")
+	dataList, err := tx.SQL(`SELECT
+	'' startTime,
+	'' endTime,
+	br.RemainDate AS overplusDate,
+	 b.bcode AS penId,
+	b.BNAME AS penName,
+	br.Remain AS actualWeight
+FROM
+	barfeedremain br
+	LEFT JOIN feedp fp ON br.barid = fp.id
+	left join bar b on b.id = fp.barid
+WHERE
+	date_format( RemainDate, '%Y-%m-%d' ) =? `, now).Query().List()
+	if err != nil {
+		logging.Error(err)
+		return err
+	}
+
+	dataByte, _ := json.Marshal(&dataList)
+
+	reqJson := `{
+    "reqMethod": "PARTY",
+    "param": {
+        "code": "1",
+        "method": "uploadoverplusdata",
+        "resultData": %s,
+        "farmId": %s,
+        "rowCount": %d,
+        "errMessage": ""
+    },
+    "regCode": "cpt180511",
+    "command": "3d6e4752",
+    "apiId": "getCptData"
+}`
+	reqJson = fmt.Sprintf(reqJson, string(dataByte), farmId, len(dataList))
+	//  '0饲喂  1剩料  2原料  3栏舍  4配方 5栏舍牛头数 6库存',
+	postPush(reqJson, 1, tx, pastureId)
+	return nil
+}
+
+// method:
+// 配方 getfeedtempletinfo
+// 搅拌数据 uploadadddata
+// 撒料数据 uploaddiliverdata
+// 剩料 uploadoverplusdata
+func UdFeedtempletPush(pastureId, farmId string) error {
+	tx := restful.Engine.NewSession()
+	defer tx.Close()
+
+	dataList, err := tx.SQL(`SELECT
+	ft.ID AS recipeId,
+	ft.TNAME AS recipeName,
+	ifnull( f.feedcode, f.id ) AS ingId,
+	f.FNAME AS ingName,
+	round( f.dry * ftd.FWEIGHT, 2 ) AS dmQty,
+	ftd.FWEIGHT AS afQty,
+	ftd.SORT AS mixNo,
+	round( f.Uprice * ftd.FWEIGHT, 2 ) AS recipeCost,
+	fc.FCNAME AS ingType,
+	f.AllowRatio AS allowableError 
+FROM
+	feedtemplet ft
+	LEFT JOIN ftdetail ftd ON ft.id = ftd.FTID
+	LEFT JOIN feed f ON ftd.FID = f.id
+	LEFT JOIN feedclass fc ON f.FCLASS = fc.id 
+WHERE
+	ft.ENABLE = 1 
+	AND ft.isDelete != 1 `).Query().List()
+	if err != nil {
+		logging.Error(err)
+		return err
+	}
+
+	dataByte, _ := json.Marshal(&dataList)
+
+	reqJson := `{
+    "reqMethod": "PARTY",
+    "param": {
+        "code": "1",
+        "method": "getfeedtempletinfo",
+        "resultData": %s,
+        "farmId": %s,
+        "rowCount": %d,
+        "errMessage": ""
+    },
+    "regCode": "cpt180511",
+    "command": "3d6e4752",
+    "apiId": "getCptData"
+}`
+	reqJson = fmt.Sprintf(reqJson, string(dataByte), farmId, len(dataList))
+	postPush(reqJson, 4, tx, pastureId)
+	return nil
+}
+
+func postPush(data string, msgtype int, tx *xorm.Session, pastureId string) {
+	url := "http://dev.unidairy.cn:8011/copartner_uploads/"
+	var jsonStr = []byte(data)
+	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
+	if err != nil {
+		logs.Error(err)
+		// return nil
+	}
+
+	// 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
+	}
+
+	defer resp.Body.Close()
+	body, _ := ioutil.ReadAll(resp.Body)
+	fmt.Println(string(body))
+	fmt.Println("11111111111111", time.Now())
+	tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url)
+	values(?,?,?,?,?,now(),?,now(),?)`, pastureId, data, string(body), "", "", msgtype, url)
+}

+ 9 - 0
http/routers/app_api.go

@@ -200,6 +200,15 @@ func AppAPI(opts ...func(engine *gin.Engine)) func(s *gin.Engine) {
 			apiV1.POST("/dailydata/edit", api.UpdateDailyData)
 			apiV1.POST("/formulastatistics", api.GetFormulaStatistics)
 
+			apiV1.POST("/sap/feed", sap.SyncSapFeed)
+
+			apiV1.POST("/sap/bar", sap.SyncSapBar)
+
+			apiV1.POST("/sap/material", sap.MaterialOutbound)
+
+			apiV1.POST("/feedbackup/check", api.CheckFeedTrgaddress)
+
+			apiV1.POST("/ud/feedp/sync", api.UdFeedpSync)
 		}
 
 		//不需要登录验证的接口

+ 1 - 1
pkg/logger/logrus/log.go

@@ -2,11 +2,11 @@ package logrus
 
 import (
 	"fmt"
-	"kpt-tmr-group/pkg/tool"
 	"path"
 	"runtime"
 	"time"
 
+	"gitee.com/xuyiping_admin/pkg/tool"
 	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
 	"github.com/sirupsen/logrus"
 )