1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225 |
- package yq
- import (
- "crypto/md5"
- "encoding/hex"
- "encoding/json"
- "fmt"
- "io/ioutil"
- "net/http"
- "strconv"
- "strings"
- "time"
- "tmr-watch/conf/setting"
- "tmr-watch/http/handle/restful"
- "tmr-watch/pkg/logging"
- "github.com/astaxie/beego/logs"
- "github.com/robfig/cron"
- "github.com/xormplus/xorm"
- )
- type udPastureInfo struct {
- Token string `xorm:"token"`
- Pastureid string `xorm:"pastureid"`
- Werks string `xorm:"werks"`
- }
- func YqCron() {
- tx := restful.Engine.NewSession()
- defer tx.Close()
- pastureinfo := new(udPastureInfo)
- err := tx.SQL(`select column_default as pastureid,(select werks from pasture where pastureid = column_default) werks 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
- }
- token := getToken()
- fmt.Println(token)
- syncBar(token, pastureinfo.Pastureid, pastureinfo.Werks)
- c := cron.New()
- c.AddFunc("0 0 1 * * *", func() {
- token := getToken()
- now := time.Now().Format("2006-01-02")
- YcFeedtempletPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
- YcFeedPush(pastureinfo.Pastureid, pastureinfo.Werks, token)
- YcPlanPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
- YcUtirPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
- YcMaterialIssuePush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
- YcBarFeedRemainPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
- syncBar(token, pastureinfo.Pastureid, pastureinfo.Werks)
- })
- c.AddFunc("0 0 6 * * *", func() {
- token := getToken()
- now := time.Now().Format("2006-01-02")
- YcPlanPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
- YcUtirPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
- YcMaterialIssuePush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
- })
- c.AddFunc("0 0 7 * * *", func() {
- token := getToken()
- now := time.Now().Format("2006-01-02")
- YcFeedtempletPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
- YcBarFeedRemainPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
- })
- c.AddFunc("0 0 12 * * *", func() {
- token := getToken()
- now := time.Now().Format("2006-01-02")
- YcPlanPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
- YcUtirPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
- YcMaterialIssuePush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
- })
- c.AddFunc("0 0 18 * * *", func() {
- token := getToken()
- now := time.Now().Format("2006-01-02")
- YcPlanPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
- YcUtirPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
- YcMaterialIssuePush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
- })
- c.AddFunc("0 0 23 * * *", func() {
- token := getToken()
- now := time.Now().Format("2006-01-02")
- YcFeedtempletPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
- YcFeedPush(pastureinfo.Pastureid, pastureinfo.Werks, token)
- YcPlanPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
- YcUtirPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
- YcMaterialIssuePush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
- YcBarFeedRemainPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
- })
- duetimecst2, _ := time.ParseInLocation("15:04:05", "00:05:00", time.Local)
- duetimecst3, _ := time.ParseInLocation("15:04:05", "00:00:00", time.Local)
- spec := fmt.Sprintf("@every %v", duetimecst2.Sub(duetimecst3))
- c.AddFunc(spec, func() {
- token := getToken()
- now := time.Now().Format("2006-01-02")
- YcUtirPush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
- YcMaterialIssuePush(pastureinfo.Pastureid, pastureinfo.Werks, now, token)
- })
- c.Start()
- // YcFeedtempletPush(pastureinfo.Pastureid, pastureinfo.Werks, "", token)
- // fmt.Println(getToken())
- // YcFeedPush(pastureinfo.Pastureid, pastureinfo.Werks, token)
- // YcPlanPush(pastureinfo.Pastureid, pastureinfo.Werks, "", token)
- // YcUtirPush(pastureinfo.Pastureid, pastureinfo.Werks, "", token)
- // YcMaterialIssuePush(pastureinfo.Pastureid, pastureinfo.Werks, "", token)
- // YcBarFeedRemainPush(pastureinfo.Pastureid, pastureinfo.Werks, "", token)
- // YcMaterialIssuePush(pastureinfo.Pastureid, pastureinfo.Werks, "", token)
- }
- func createApiSign(appId, timeStamp, apiKey, secretKey string) string {
- return getMD5Encode(fmt.Sprintf("%s#%s#%s#%s", appId, timeStamp, apiKey, secretKey))
- }
- func getMD5Encode(data string) string {
- fmt.Println(data)
- hasher := md5.New()
- hasher.Write([]byte(data))
- digest := hasher.Sum(nil)
- md5HashString := hex.EncodeToString(digest)
- return md5HashString
- }
- func getToken() string {
- appId := "6Zub5bed5Yqo55uS"
- apiKey := "3c6bbff8cf1e496eb8eb9025cd8537fh"
- secretKey := "26b5d9f63b6142de8f102afb1aa2eb7g"
- req, err := http.NewRequest("POST", "https://vmuyun.com/base-server/outSide/token", nil)
- if err != nil {
- logs.Error(err)
- }
- now := time.Now()
- nanos := now.UnixNano()
- timeStamp := fmt.Sprintf("%d", nanos/int64(time.Millisecond))
- apiSign := createApiSign(appId, timeStamp, apiKey, secretKey)
- req.Header.Set("appId", appId)
- req.Header.Set("apiKey", apiKey)
- req.Header.Set("secretKey", secretKey)
- req.Header.Set("timeStamp", timeStamp)
- req.Header.Set("apiSign", apiSign)
- client := &http.Client{}
- resp, err := client.Do(req)
- if err != nil {
- logs.Error(err)
- return ""
- }
- defer resp.Body.Close()
- body, _ := ioutil.ReadAll(resp.Body)
- data := make(map[string]string, 0)
- json.Unmarshal(body, &data)
- fmt.Println(string(body))
- if _, ok := data["data"]; ok {
- return data["data"]
- }
- return ""
- }
- func postPush(data string, msgtype int, tx *xorm.Session, pastureId, token string) {
- // jsonStr, _ := json.Marshal(data)
- url := "https://vmuyun.com/project-server/openApi/feeding/pushData"
- req, err := http.NewRequest("POST", url, strings.NewReader((data)))
- if err != nil {
- logs.Error(err)
- // return nil
- }
- // req.Header.Set("Content-Type", "application/json")
- // req.Header.Set("Content-Length", "13444")
- req.Header.Add("Authorization", token)
- // req.Header.Set("Host", "test.vmuyun.com")
- // req.Header.Set("Accept", "*/*")
- // req.Header.Set("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
- // req.Header.Add("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
- req.Header.Add("Content-Type", "application/json")
- // req.Header.Add("Accept", "*/*")
- // req.Header.Add("Host", "test.vmuyun.com")
- // req.Header.Add("Connection", "keep-alive")
- 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))
- if strings.Index(resp.Status, "200") > -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)
- }
- }
- func YcFeedtempletPush(pastureId, farmId, date, token 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,
- f.feedcode AS ingId,
- ifnull(f.udname,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 ,fc.fcname ingType
- FROM
- feedtempletdate ft
- JOIN ftdetaildate ftd ON ft.id = ftd.FTID and ft.date = ftd.date
- JOIN feed f ON ftd.FID = f.id
- 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 := `{
- "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))
- fmt.Println(reqJson)
- postPush(reqJson, 4, tx, pastureId, token)
- return nil
- }
- func YcFeedPush(pastureId, farmId, token string) error {
- tx := restful.Engine.NewSession()
- defer tx.Close()
- dataList, err := tx.SQL(`SELECT
- dry dmQty,
- sort,
- feedcode ingId,
- fname ingName,
- fclass ingType,
- allowratio allowableError
- FROM
- feed
- WHERE
- pastureId = ? `, pastureId).Query().List()
- if err != nil {
- logging.Error(err)
- return err
- }
- dataByte, _ := json.Marshal(&dataList)
- reqJson := `{
- "apiId": "getKPTData ",
- "param": {
- "farmId": "%s",
- "method":"getfeedinfo",
- "rowCount": %d,
- "resultData":%s
- }
- }`
- reqJson = fmt.Sprintf(reqJson, farmId, len(dataList), string(dataByte))
- fmt.Println(reqJson)
- postPush(reqJson, 2, tx, pastureId, token)
- return nil
- }
- func YcPlanPush(pastureId, farmId, date, token string) error {
- tx := restful.Engine.NewSession()
- defer tx.Close()
- dataList, err := tx.SQL(`SELECT
- projname planName,
- datacaptureno tmrNo,
- times loadShift,
- tempid recipeId,
- templetname recipeName,
- lweight expWeight,
- tmrtname tmrName,
- '是' STATUS,
- feedpcount cowCount,
- id planId,
- DATE_FORMAT( mydate, '%H:%i:%s' ) planTime,
- DATE_FORMAT( mydate, '%Y-%m-%d' ) planDate,
- IF( iscompleted = 1, '是', '否' ) isCompleted,
- IF(dlp.driverId != 0,(
- SELECT
- drivername
- FROM
- driver
- WHERE
- id = dlp.driverId
- ),(
- SELECT
- dr.driver
- FROM
- dutyrecord dr
- WHERE
- dr.pastureid = dlp.pastureid
- AND dr.eqid = dlp.tmrid
- AND dr.times = dlp.times
- AND dr.operatetime <= dlp.mydate
- ORDER BY
- dr.operatetime DESC
- LIMIT 1
- )) driverName
- FROM
- downloadedplan dlp
- WHERE
- havebutton = 1
- AND mydate = ? `, date).Query().List()
- if err != nil {
- logging.Error(err)
- return err
- }
- dataByte, _ := json.Marshal(&dataList)
- reqJson := `{
- "apiId": "getKPTData ",
- "param": {
- "farmId": "%s",
- "method":"getplaninfo",
- "rowCount": %d,
- "resultData":%s
- }
- }`
- reqJson = fmt.Sprintf(reqJson, farmId, len(dataList), string(dataByte))
- fmt.Println(reqJson)
- postPush(reqJson, 2, tx, pastureId, token)
- return nil
- }
- //搅拌
- func YcUtirPush(pastureId, farmId, date, token 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 date_format(d1.date,'%Y-%m-%d') dropDate,d.times loadShift,d.datacaptureno tmrNo,ft.tcode recipeId,ft.ccname recipeName,if(d1.feedcode = -1 ,d1.fid,f.feedcode) ingId,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<d1.intime)
- , (SELECT MAX(intime) FROM downloadedplan d2
- WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid)
- ), '%Y-%m-%d %H:%i:%s')
- startTime ,
- date_format(d1.intime,'%Y-%m-%d %H:%i:%s') endTime, driver.drivername tmrName ,d1.feedallowratio allowable_error
- 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 feedclass fc on fc.id = f.fclassid
- left join ftdetaildate ftd on ftd.date = d1.date and ftd.ftid = d1.fid
- join tmr t on t.id = d.tmrid
- left join driver on driver.drivercode = t.eqcode
- where d1.date = ? and d.havebutton = 1 and d1.type = 0 `, 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, token)
- fmt.Println(reqJson)
- return nil
- }
- func YcBarFeedRemainPush(pastureId, farmId, date, token 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
- date_format( remaindate, '%Y-%m-%d' ) overplusDate,
- ifnull(b.bcode,b.id) 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库存',
- fmt.Println(reqJson)
- postPush(reqJson, 1, tx, pastureId, token)
- return nil
- }
- func YcMaterialIssuePush(pastureId, farmId, date, token 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
- DATE_FORMAT(d.mydate,'%Y-%m-%d') dropDate,
- d.datacaptureno tmrNo,
- d.times dropShift,
- b.bcode penId,
- b.bname penName,
- fp.ccount cowCount,
- d2.sort feedingNo,
- d2.lweight expWeight,
- d2.actualweight actualWeight,
- if((select count(1) from downloadplandtl2 where pid = d.id and sort < d2.sort ) = 0 ,(select DATE_FORMAT(intime,'%Y-%m-%d %H:%i:%s') from downloadplandtl1 where pid = d.id order by sort desc limit 1 ),(select DATE_FORMAT(intime,'%Y-%m-%d %H:%i:%s') from downloadplandtl2 where pid = d.id and sort < d2.sort order by sort desc limit 1)) startTime,
- DATE_FORMAT(d2.intime,'%Y-%m-%d %H:%i:%s') endTime,
- d.tmrtname tmrName, driver.drivername driverName,d.id planId,1 calculation,
- ifnull((select weight from fpdetaildate where date = d2.date and barid = d2.fbarid and times = 1 ) ,0) shift1,
- ifnull( (select weight from fpdetaildate where date = d2.date and barid = d2.fbarid and times = 2 ) ,0) shift2,
- ifnull( (select weight from fpdetaildate where date = d2.date and barid = d2.fbarid and times = 3 ) ,0) shift3,
- ifnull( (select weight from fpdetaildate where date = d2.date and barid = d2.fbarid and times = 4 ) ,0) shift4,
- ifnull( (select weight from fpdetaildate where date = d2.date and barid = d2.fbarid and times = 5 ) ,0) shift5,
- ifnull( (select weight from fpdetaildate where date = d2.date and barid = d2.fbarid and times = 6 ),0) shift6,
- d.tempid recipeId,d.templetname recipeName, d.completedtime isCompleted
- FROM
- downloadedplan d
- JOIN downloadplandtl2 d2 ON d.id = d2.pid
- JOIN bar b ON d2.fbarid = b.id
- join feedp fp on fp.barid = b.id
- join tmr t on t.id = d.tmrid
- left join driver on driver.drivercode = t.eqcode where d.mydate = ? and d.havebutton = 1
- `, now).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, token)
- fmt.Println(reqJson)
- return nil
- }
- func syncBar(token, pastureid, werks string) {
- req, err := http.NewRequest("GET", "https://vmuyun.com/project-server/openApi/feeding/penList", nil)
- if err != nil {
- logs.Error(err)
- // return nil
- }
- req.Header.Set("Authorization", token)
- 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)
- data := make(map[string]interface{}, 0)
- json.Unmarshal(body, &data)
- dataList := data["data"].([]interface{})
- tx := restful.Engine.NewSession()
- defer tx.Close()
- for _, item := range dataList {
- arg := item.(map[string]interface{})
- fmt.Println(arg)
- if fmt.Sprintf("%v", arg["farmId"]) == werks {
- if _, ok := arg["sheepCount"]; !ok {
- arg["sheepCount"] = 0
- }
- _, err := tx.Exec(` insert into bar(pen,bname,bcode,pastureid)values(?,?,?,?) ON DUPLICATE KEY UPDATE pen = ? `, arg["districtName"],
- fmt.Sprintf("%v-%v-%v", arg["districtName"], arg["houseName"], arg["compartmentName"]), fmt.Sprintf("%v-%v-%v", arg["districtName"], arg["houseName"], arg["compartmentName"]), pastureid, arg["districtName"])
- fmt.Println(err)
- insertSql := `insert into feedp(pastureid,barname,barid,ccount)VALUES(?,?,(select id from bar where bname = ?),?)
- ON DUPLICATE KEY UPDATE ccount = ? ,barname = ? `
- _, err = tx.SQL(insertSql, pastureid, fmt.Sprintf("%v-%v", arg["houseName"], arg["compartmentName"]),
- fmt.Sprintf("%v-%v-%v", arg["districtName"], arg["houseName"], arg["compartmentName"]), arg["sheepCount"], arg["sheepCount"],
- fmt.Sprintf("%v-%v-%v", arg["districtName"], arg["houseName"], arg["compartmentName"])).Execute()
- fmt.Println(err)
- // tx.SQL(` select from feedp where barname = ? `)
- // barList := make([]*bar,0)
- b := new(bar)
- // b.BarName = fmt.Sprintf("%v-%v", arg["houseName"], arg["compartmentName"])
- // b.Ccount = arg["sheepCount"]
- err = tx.SQL(` select fp.barname,fp.ccount,ratio,ft.tname ftname,ifnull((select tratio from fpdetail where barid = fp.barid and times = 1 ),0) times1,
- ifnull((select tratio from fpdetail where barid = fp.barid and times = 2 ),0) times2 ,
- ifnull((select tratio from fpdetail where barid = fp.barid and times = 3 ),0) times3 ,
- ifnull((select tratio from fpdetail where barid = fp.barid and times = 4 ),0) times4 ,
- ifnull((select tratio from fpdetail where barid = fp.barid and times =5 ),0) times5 ,
- ifnull((select tratio from fpdetail where barid = fp.barid and times =6 ),0) times6
- from feedp fp join feedtemplet ft on ft.id = fp.ftid where ratio > 0 and fp.barname = ? `, fmt.Sprintf("%v-%v-%v", arg["districtName"], arg["houseName"], arg["compartmentName"])).GetFirst(b).Error
- fmt.Println(err)
- fpdBatchEdit(pastureid, b)
- // {"pastureId":"1653271339","barList":[{"barname":"14","ccount":155,"ratio":"100.00","ftname":"高产2配方",
- // "times1":"41","times2":"25","times3":"25","times4":0,"times5":0,"times6":0}]}
- }
- }
- }
- type bar struct {
- BarName string `xorm:"barname"`
- Ccount string `xorm:"ccount"`
- Ratio string `xorm:"ratio"`
- Ftname string `xorm:"ftname"`
- Times1 float64 `xorm:"times1"`
- Times2 float64 `xorm:"times2"`
- Times3 float64 `xorm:"times3"`
- Times4 float64 `xorm:"times4"`
- Times5 float64 `xorm:"times5"`
- Times6 float64 `xorm:"times6"`
- }
- func fpdBatchEdit(pastureid string, b *bar) {
- // appG := app.Gin{C: c}
- // dataByte, _ := ioutil.ReadAll(c.Request.Body)
- // fsions := gofasion.NewFasion(string(dataByte))
- // barList := fsions.Get("barList").Array()
- // pastureid := fsions.Get("pastureId").ValueStr()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- oldFpdList, err := tx.SQL(` select ifnull(ROUND((1-ptsrate)*weight,2)-ptuse,"") fweight,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()
- if err != nil {
- // appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- // for _, barFsions := range barList {
- dataexcel := make(map[string]interface{}, 0)
- dataexcel["barname"] = b.BarName
- dataexcel["ccount"] = b.Ccount
- dataexcel["ratio"] = b.Ratio
- dataexcel["ftname"] = b.Ftname
- // dataexcel["ptsfname"] = barFsions.Get("ptsfname").ValueStr()
- if dataexcel["ftname"] == "" || dataexcel["ccount"] == "0" || dataexcel["ratio"] == "0" {
- return
- }
- dataexcel["1"] = b.Times1
- dataexcel["2"] = b.Times2
- dataexcel["3"] = b.Times3
- dataexcel["4"] = b.Times4
- dataexcel["5"] = b.Times5
- dataexcel["6"] = b.Times6
- ftexist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? and ftname = ? `, dataexcel["barname"], pastureid, dataexcel["ftname"]).Exist()
- if err != nil {
- logs.Error(err)
- 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)
- return
- }
- tx.SQL(` update fpdetail set ptuse = 0 where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- return
- }
- }
- exist, err := tx.SQL(` select id from feedp where barname = ? and pastureid = ? `, dataexcel["barname"], pastureid).Exist()
- if err != nil {
- logs.Error(err)
- return
- }
- if !exist {
- _, err := tx.SQL(` insert into feedp(pastureid,barid,barname,ccount)values(?,(select id from bar where bname = ? and pastureid = ? ),?,?) `,
- pastureid, dataexcel["barname"], pastureid, dataexcel["barname"], 0).Execute()
- if err != nil {
- logs.Error(err)
- return
- }
- }
- var feedpargs []interface{}
- upFeedpSql := `update feedp set ccount = ? ,ratio = ? ,ccountratio = ?*(?*0.01) `
- feedpargs = append(feedpargs, dataexcel["ccount"], dataexcel["ratio"], dataexcel["ccount"], dataexcel["ratio"])
- if _, ok := dataexcel["ftname"]; ok {
- feedpargs = append(feedpargs, dataexcel["ftname"], pastureid, dataexcel["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, dataexcel["ftname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
- } else {
- upFeedpSql += ` , ftid = -1,ftname = '' ,ftweight = 0 `
- }
- if _, ok := dataexcel["ptsfname"]; ok {
- feedpargs = append(feedpargs, dataexcel["ptsfname"], pastureid, dataexcel["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, dataexcel["ptsfname"], pastureid, dataexcel["ccount"], dataexcel["ratio"])
- } else {
- upFeedpSql += ` , ptsfid = -1,ptsfname = '',supplyweight = 0 `
- }
- upFeedpSql += " where barname = ? and pastureid = ? "
- feedpargs = append(feedpargs, dataexcel["barname"], pastureid)
- _, err = tx.SQL(upFeedpSql, feedpargs...).Execute()
- if err != nil {
- logs.Error(err)
- return
- }
- 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)
- 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()
- if err != nil {
- logs.Error(err)
- 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)
- 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 {
- logs.Error(err)
- 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)
- 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 {
- logs.Error(err)
- 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)
- 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 {
- logs.Error(err)
- 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)
- 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)
- 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)
- 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)
- 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 {
- 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 {
- 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 {
- 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 {
- 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 {
- 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 {
- 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 {
- 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, dataexcel["barname"].(string), upFpdetailList)
- }
- type lpplandtlInfo struct {
- Id int64 `xorm:"id"`
- Pastureid int64 `xorm:"pastureid"`
- Lppid int64 `xorm:"lppid"`
- Barid int64 `xorm:"barid"`
- Barname string `xorm:"barname"`
- Fpdid int64 `xorm:"fpdid"`
- Fttype int64 `xorm:"fttype"`
- Lweight float64 `xorm:"lweight"`
- Sort int64 `xorm:"sort"`
- Tmrid int64 `xorm:"tmrid"`
- Tmrname string `xorm:"tmrname"`
- Cowcount int64 `xorm:"cowcount"`
- Ccountradio float64 `xorm:"ccountradio"`
- Background string `xorm:"background"`
- Lweighthis float64 `xorm:"lweighthis"`
- Maxweight float64 `xorm:"maxweight"`
- }
- type upFpdetail struct {
- Old float64
- New float64
- Times int64
- Ptid int64
- Fweight float64
- Id int64
- }
- func updateFpdetailByBar(pastureid, barname string, dataList []*upFpdetail) error {
- tx := restful.Engine.NewSession()
- defer tx.Close()
- tx.Begin()
- 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)
- }
- for _, fpd := range fpdList {
- 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 {
- tx.Rollback()
- logs.Error(err)
- return err
- }
- var lweight float64
- for _, lppland := range lpplandList {
- lweight1, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
- lweight += lweight1
- }
- fpdweight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
- ptuse, _ := strconv.ParseFloat(fpd["ptuse"].(string), 64)
- if fpdweight >= ptuse && lweight == ptuse {
- continue
- } else {
- if lweight <= fpdweight {
- _, err := tx.SQL(` update fpdetail set ptuse = ? where id = ? `, lweight, fpd["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return err
- }
- } else {
- weight := lweight - fpdweight
- _, err = tx.SQL(`UPDATE fpdetail SET ptuse=?
- WHERE pastureid=? AND id=?`, fpdweight, pastureid, fpd["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return err
- }
- for _, lppland := range lpplandList {
- lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
- if weight >= lpplandlweight {
- weight = weight - lpplandlweight
- _, err := tx.SQL(` delete from lpplandtl1 where id = ? `, lppland["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return err
- }
- } else {
- lpplandlweight, _ := strconv.ParseFloat(lppland["lweight"].(string), 64)
- _, err := tx.SQL(` update lpplandtl1 set lweight = ? where id = ? `, lpplandlweight-weight, lppland["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return err
- }
- weight = 0
- break
- }
- }
- }
- }
- }
- for _, list := range dataList {
- ftmap := make(map[string]interface{})
- ftmap["old"] = list.Old
- ftmap["new"] = list.New
- ftmap["times"] = list.Times
- ftmap["ptid"] = strconv.FormatInt(list.Ptid, 10)
- ftmap["ptsid"] = ""
- // fmt.Println(ftmap)
- // 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 ,
- // (select bname from bar where pastureid =fpdetail.pastureid and id = fpdetail.barid ) barname,concat(0) AS fttype,cowcount,ccountradio,1 isfill FROM fpdetail
- // WHERE fpdetail.pastureid = ? and barname = ? and times = ?
- // UNION
- fpdDataList, err := tx.SQL(`
- 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,concat(1) AS fttype,cowcount,ccountradio,0 isfill FROM fpdetail
- WHERE fpdetail.pastureid = ? and barname = ? and times = ? `, pastureid, barname, ftmap["times"]).Query().List()
- // fmt.Println(pastureid, id, ftmap["times"], pastureid, id, ftmap["times"])
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- }
- for _, fpd := range fpdDataList {
- if fpd["times"].(int64) == ftmap["times"].(int64) && (fpd["ptid"].(string) == ftmap["ptid"].(string) || fpd["ptsid"].(string) == ftmap["ptsid"].(string)) {
- // fttype := -1
- // if fpd["fttype"].(string) == "1" {
- fttype := 1
- // }
- var fweight float64
- var lweight float64
- lpplandtl1List := make([]*lpplandtlInfo, 0)
- err = tx.SQL(`select lppland.*,t.maxstirfeed maxweight from lpplan lpp
- join lpplandtl1 lppland on lpp.id = lppland.lppid
- join tmr t on t.id = lpp.tmrid
- where lppland.fpdid =?
- and lppland.fttype = ? and lpp.pastureid = ? and lpp.times = ? order by lpp.sort desc `,
- fpd["id"], fttype, pastureid, ftmap["times"]).Find(&lpplandtl1List)
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- }
- // [map[barid:4719430583171155825 barname:泌乳1-5西 ccountradio:131 cowcount:30 fttype:0 id:4828050527277810688 isfill:1 pastureid:1705635208 ptid:83
- // ptsid:-1 times:1 tratio:48.000 weight:0.00] map[barid:4719430583171155825
- // barname:泌乳1-5西 ccountradio:131 cowcount:30 fttype:1 id:4828050527277810688 isfill:0 pastureid:1705635208 ptid:83 ptsid:-1 times:1 tratio:48.000 weight:32.0
- weight, _ := strconv.ParseFloat(fpd["weight"].(string), 64)
- var w float64
- var status int
- if ftmap["new"].(float64) < ftmap["old"].(float64) && weight <= 0 {
- if weight >= 0 {
- continue
- }
- w = weight
- status = 0
- } else {
- // if weight-(ftmap["new"].(float64)-ftmap["old"].(float64)) > 0 {
- // continue
- // }
- w = weight
- status = 1
- }
- // for _, lppland := range lpplandtl1List {
- // lweight += lppland.Lweight
- // }
- for _, lppland := range lpplandtl1List {
- lpplandInfo := new(lpplandtlInfo)
- err := tx.SQL(` select ifnull(sum(lweight),0) lweight from lpplandtl1 where lppid = ? `, lppland.Lppid).GetFirst(lpplandInfo).Error
- lweight = lpplandInfo.Lweight
- if status == 1 {
- // if w <= lppland.Lweight {
- if lppland.Maxweight <= lweight {
- continue
- }
- if w+lweight <= lppland.Maxweight {
- lppland.Lweight += w
- lweight += w
- fweight += w
- w = 0
- } else {
- w = w - (lppland.Maxweight - lweight)
- n := (lppland.Maxweight - lweight)
- lppland.Lweight = lppland.Lweight + n
- lweight += n
- fweight += n
- }
- } else {
- if lppland.Lweight == 0 {
- continue
- }
- if w+lppland.Lweight >= 0 {
- lppland.Lweight = lppland.Lweight + w
- lweight = lweight + w
- fweight = fweight + w
- w = 0
- } else {
- w = w + lppland.Lweight
- lweight = lweight - lppland.Lweight
- fweight = fweight - lppland.Lweight
- lppland.Lweight = 0
- }
- }
- if lppland.Lweight > 0 {
- _, err = tx.SQL(`update lpplandtl1 set Lweight = ? where id = ? and pastureid = ?`, lppland.Lweight, lppland.Id, pastureid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return err
- }
- } else {
- _, err = tx.SQL(`delete from lpplandtl1 where id = ? and pastureid = ?`, lppland.Id, pastureid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- return err
- }
- }
- if w == 0 {
- break
- }
- }
- _, err = tx.SQL(`UPDATE fpdetail SET ptuse=IF(?=1,IF(ptuse+? <0,0,ptuse+?),ptuse),
- ptsuse=IF(?=0,IF(ptsuse+?<0,0,ptsuse+?),ptsuse)
- WHERE pastureid=? AND id=?`, fttype, fweight, fweight, fttype, fweight, fweight, pastureid, fpd["id"]).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error(err)
- }
- if w == 0 {
- break
- }
- }
- }
- }
- err = tx.Commit()
- if err != nil {
- logs.Error(err)
- tx.Rollback()
- return err
- }
- now := time.Now()
- newLpplandtl1List, err := tx.SQL(` select lppland.* from lpplandtl1 lppland where lppland.barname = ? and pastureid = ? `, barname, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- return nil
- }
- newFpdDataList, err := tx.SQL(` select * from fpdetail where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- return nil
- }
- newFeedpList, err := tx.SQL(` select * from feedp where barname = ? and pastureid = ? `, barname, pastureid).Query().List()
- if err != nil {
- logs.Error(err)
- return nil
- }
- 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(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
- 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()
- if err != nil {
- logs.Error(err)
- // appG.Response(http.StatusOK, e.ERROR, false)
- return err
- }
- }
- 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 err
- }
- }
- 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 err
- }
- }
- return nil
- }
|