package ymy import ( "bytes" "crypto/tls" "encoding/json" "fmt" "io/ioutil" "net/http" "strings" "time" "tmr-watch/conf/setting" "tmr-watch/http/handle/restful" "tmr-watch/models" "tmr-watch/pkg/logging" "github.com/astaxie/beego/logs" "github.com/xormplus/xorm" ) func YmyCron(farmId, pastureId string) { date := time.Now().AddDate(0, 0, -1).Format("2006-01-02") // date := "2025-05-11" YmyUtirPush(pastureId, farmId, date) YmyMaterialIssuePush(pastureId, farmId, date) YmySyncBar(farmId, pastureId) YmySyncFeed(pastureId) YmyFeedtempletPush(pastureId, farmId, date) } func YmySyncBar(farmId, pastureId string) { tx := restful.Engine.NewSession() defer tx.Close() reqJson := `{ "methodKey": "getFeedPenList", "param": { "farmId": "%s", "parlorType": "CPT" }, "platform": "CPT", "regCode": "cpt180511", "secret": "67a74fd5748054ac67b6fc433e9249b0"}` barPull("http://dairy.yimucloud.com/dairy/external/api", fmt.Sprintf(reqJson, farmId), 3, tx, pastureId) } func barPull(url, data string, msgtype int, tx *xorm.Session, pastureId string) { req, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(data))) if err != nil { logs.Error(err) } req.Header.Set("Content-Type", "application/json") // client := &http.Client{} tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } client := &http.Client{Transport: tr} resp, err := client.Do(req) if err != nil { logs.Error(err) return } defer resp.Body.Close() body, _ := ioutil.ReadAll(resp.Body) respData := new(models.BarResponse) json.Unmarshal(body, &respData) tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url) values(?,?,?,?,?,now(),?,now(),?)`, pastureId, data, string(body), "", "", msgtype, url) for _, v := range respData.Result { fmt.Println(v) count, _ := tx.Table("bar").Where("pastureId = ? ", pastureId).Count() tx.Exec(`insert into bar(pastureid,bcode,bname,sort)values(?,?,?,?) ON DUPLICATE KEY UPDATE bname = ? `, pastureId, v.PenId, v.PenName, count+1, v.PenName) } } func YmySyncFeed(pastureId string) { tx := restful.Engine.NewSession() defer tx.Close() reqJson := `{ "data":{ "page": "0", "size": "1000", "modifiedAfter":"2025-01-01 00:00:00", "MATERIAL_BASIC_CLASSIFICATION_CODE":"", "MATERIAL_CODE": "" }}` feedPull("http://219.151.177.119:9000/ierp/kapi/v2/iscb/route/script_cusapi_deepexi_material_query", reqJson, 2, tx, pastureId, getApiToken()) } type udPastureInfo struct { Token string `xorm:"token"` Pastureid string `xorm:"pastureid"` Werks string `xorm:"werks"` UpdateDate string `xorm:"updatedate"` } func getApiToken() string { tx := restful.Engine.NewSession() defer tx.Close() pastureinfo := new(udPastureInfo) err := tx.SQL(`SELECT (SELECT pastureid FROM pasture WHERE pastureid = column_default) pastureid, IF( TIMESTAMPDIFF(MINUTE, (SELECT updatedate FROM pasture WHERE pastureid = column_default), NOW() ) > 60, -- 110分钟 = 1小时50分钟 '', -- 超过时间返回空字符串 (SELECT token FROM pasture WHERE pastureid = column_default) -- 否则返回 pastureid ) AS token, (SELECT werks FROM pasture WHERE pastureid = column_default) AS werks, DATE_FORMAT( (SELECT updatedate FROM pasture WHERE pastureid = column_default), '%Y-%m-%d %H:%i:%s' ) AS updatedate 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 pastureinfo.Token } if pastureinfo.Token != "" { return pastureinfo.Token } reqJson := `{ "client_id": "Cosmic_deepexi_user", "client_secret": "Cosmic_zkm_deepexi_openapi@user01", "username": "dipujiekouyonghu", "accountId": "1986218827033083904", "nonce": "a42c1a91-56ad-4c6d-95d1-40bcb8b5ec89", "timestamp": "%s", "language": "zh_CN" }` reqJson = fmt.Sprintf(reqJson, time.Now().Format("2006-01-02 15:04:05")) req, err := http.NewRequest("POST", "http://219.151.177.119:9000/ierp/kapi/oauth2/getToken", bytes.NewBuffer([]byte(reqJson))) if err != nil { logs.Error(err) } req.Header.Set("Content-Type", "application/json") tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } client := &http.Client{Transport: tr} resp, err := client.Do(req) if err != nil { logs.Error(err) return pastureinfo.Token } defer resp.Body.Close() body, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(body)) token := new(models.TokenResponse) json.Unmarshal(body, &token) tx.Exec(" update pasture set token = ?,updatedate = now() where pastureid = ? ", token.Data.AccessToken, pastureinfo.Pastureid) return token.Data.AccessToken } func feedPull(url, data string, msgtype int, tx *xorm.Session, pastureId, token string) { req, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(data))) if err != nil { logs.Error(err) } req.Header.Set("Content-Type", "application/json") req.Header.Set("access_token", token) 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)) feedData := new(models.FeedResponse) json.Unmarshal(body, &feedData) for _, v := range feedData.Data.Content { feedname := v.MaterialName feedcode := v.MaterialCode feedClassExist, err := tx.Table("feedclass").Where("fccode = ? ", v.MaterialClassification).Where(" pastureId = ? ", pastureId).Exist() fmt.Println(err) if !feedClassExist { count, _ := tx.Table("feedclass").Where("pastureId = ? ", pastureId).Count() ids, err := setting.SnowIds.NextId() if err != nil { ids = time.Now().UnixNano() } _, err = tx.Exec(`insert into feedclass(id,pastureId,fcname,fccode,bigfeedclassname,sort,bigfeedclassid) values(?,?,?,?,?,?,?)`, ids, pastureId, v.MaterialClassification, v.MaterialClassification, v.MaterialClassification, count+1, ids) fmt.Println(err) } ids, err := setting.SnowIds.NextId() if err != nil { ids = time.Now().UnixNano() logging.Info("create SnowIds err", err) } tx.Exec(`insert into feed(id,pastureId,feedcode,udname,fclassid,fclass,fname) values(?,?,?,?,(select id from feedclass where fccode = ? and pastureId = ? ),?,if(char_length(?) > 7, left(?,7),?) ) ON DUPLICATE KEY UPDATE udname = ? ,fclassid = (select id from feedclass where fccode = ? and pastureId = ? ) ,fclass = ?`, ids, pastureId, feedcode, feedname, v.MaterialClassification, pastureId, v.MaterialClassification, feedname, feedname, feedname, feedname, v.MaterialClassification, pastureId, v.MaterialClassification) } tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url) values(?,?,?,?,?,now(),?,now(),?)`, pastureId, data, string(body), "", "", msgtype, url) } func YmyFeedtempletPush(pastureId, farmId, date string) error { tx := restful.Engine.NewSession() defer tx.Close() var now string if date != "" { now = date } else { now = time.Now().AddDate(0, 0, -1).Format("2006-01-02") } dataList, err := tx.SQL(`SELECT ft.tcode AS recipeId, ft.TNAME AS recipeName, ifnull(f.feedcode,f.id) AS ingId, '' AS feedCode, ifnull(f.udname,f.fname) AS ingName, round( fn.dry * ftd.FWEIGHT, 2 ) AS dmQty, ftd.FWEIGHT AS afQty, ftd.SORT AS mixNo, round( f.Uprice * ftd.FWEIGHT, 2 ) AS recipeCost, ifnull(fc.fcname,'饲料') AS ingType, f.AllowRatio AS allowableError FROM feedtempletdate ft JOIN ftdetaildate ftd ON ft.id = ftd.FTID and ft.date = ftd.date JOIN feed f ON ftd.FID = f.id left join feednur fn on fn.fid = f.id left JOIN feedclass fc ON f.fclassid = fc.id WHERE ft.ENABLE = 1 AND ft.isDelete != 1 and ft.date = ? `, now).Query().List() if err != nil { logging.Error(err) return err } dataByte, _ := json.Marshal(&dataList) reqJson := ` {"param": { "method": "getfeedtempletinfo", "resultData": %s, "farmId": "%s", "parlorType": "CPT", "account":"CPT" }, "platform": "CPT", "regCode": "cpt180511", "secret": "67a74fd5748054ac67b6fc433e9249b0", "methodKey": "pushCptData"}` reqJson = fmt.Sprintf(reqJson, string(dataByte), farmId) fmt.Println(reqJson) postPush(reqJson, 4, tx, pastureId) return nil } //搅拌 func YmyUtirPush(pastureId, farmId, date string) error { tx := restful.Engine.NewSession() defer tx.Close() var now string if date != "" { now = date } else { now = time.Now().AddDate(0, 0, -1).Format("2006-01-02") } dataList, err := tx.SQL(`select MD5(CONCAT(d.pid, d.mydate)) loadId , date_format(d1.date,'%Y-%m-%d') dropDate,date_format(d1.date,'%Y-%m-%d') loadDate,d.times loadShift,d.id tmrNo,ft.tcode recipeId,ft.ccname recipeName,ifnull(f.feedcode,d1.fid) ingId,'' feedCode ,ifnull(f.fname,ftd.fname) ingName, ifnull(ifnull(fc.fcname,(select fcname from feedclass fc1 join feed f1 on f1.fclassid = fc1.id where f1.id =ftd.fid )),'饲料') ingType, ifnull(f.dry * d1.actualweightminus,0) dmPct,d1.sort mixNo,ifnull(d1.feedallowratio,0) allowableError , if(f.fname is not null, ifnull(d1.lweight,''), ifnull(ftd.fweight / (select sum(fweight) from ftdetaildate where date = d1.date and ftid = d1.fid ) * d1.lweight,"") ) expWeight, if(f.fname is not null, ifnull(d1.actualweightminus,''),ifnull(ftd.fweight / (select sum(fweight) from ftdetaildate where date = d1.date and ftid = d1.fid ) * d1.actualweightminus,"") ) actualWeight, DATE_FORMAT(IFNULL((SELECT MAX(intime) FROM downloadplandtl1 d2 WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime -1 { bodyData := make(map[string]string) json.Unmarshal(body, &bodyData) if _, ok := bodyData["data"]; ok { tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url) values(?,?,?,?,?,now(),?,now(),?)`, pastureId, data, bodyData["data"], "", "", msgtype, url) } else { tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url) values(?,?,?,?,?,now(),?,now(),?)`, pastureId, data, string(body), "", "", msgtype, url) } } else { tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url) values(?,?,?,?,?,now(),?,now(),?)`, pastureId, data, string(body), "", "", msgtype, url) } }