123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659 |
- package api
- import (
- "bytes"
- "context"
- "encoding/json"
- "fmt"
- "io/ioutil"
- "log"
- "net/http"
- "os"
- "reflect"
- "strconv"
- "strings"
- "time"
- "../../pkg/app"
- "../../pkg/e"
- "../../pkg/logging"
- "../../pkg/setting"
- "../../routers/restful"
- "github.com/Anderson-Lu/gofasion/gofasion"
- "github.com/astaxie/beego/logs"
- "github.com/gin-gonic/gin"
- "github.com/robfig/cron"
- "github.com/xormplus/xorm"
- )
- func CronScheduled(ctx context.Context) {
- 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
- if err != nil {
- logs.Error(err)
- return
- }
- // duetimecst, _ := time.ParseInLocation("15:04:05", "00:10:00", time.Local)
- // duetimecst1, _ := time.ParseInLocation("15:04:05", "00:00:00", time.Local)
- // spec := fmt.Sprintf("@every %v", duetimecst.Sub(duetimecst1))
- // c := cron.New()
- // c.AddFunc(spec, func() {
- // tx1 := restful.Engine.NewSession()
- // defer tx1.Close()
- // exist, err := tx1.Table("notice").Where("status = 1").And("content = ? ", "downloadedplan_log").Exist()
- // if err != nil {
- // logs.Error("CronScheduled-error-1:", err)
- // return
- // }
- // if exist {
- // _, err := tx.SQL(`update notice set status = 0 where content = ? `, "downloadedplan_log").Execute()
- // if err != nil {
- // logs.Error("CronScheduled-error-2:", err)
- // return
- // }
- // Scheduled(ctx, tx1, pastureinfo)
- // }
- // })
- // c.Start()
- //消息提醒
- duetimecst2, _ := time.ParseInLocation("15:04:05", "00:01:00", time.Local)
- duetimecst3, _ := time.ParseInLocation("15:04:05", "00:00:00", time.Local)
- spec1 := fmt.Sprintf("@every %v", duetimecst2.Sub(duetimecst3))
- downloadplandtl1 := cron.New()
- downloadplandtl1.AddFunc(spec1, func() {
- dataList, err := tx.SQL(` select user,function,id from remind where pastureid = ? `, pastureinfo.Pastureid).Query().List()
- if err != nil {
- logs.Error("CronScheduled-error-3:", err)
- return
- }
- for _, data := range dataList {
- var openIdList []string
- if _, ok := data["user"]; ok {
- openIdList = strings.Split(data["user"].(string), ",")
- }
- if data["function"].(string) == "processAnalysisEarlyWarning" {
- if len(openIdList) > 0 {
- processAnalysisEarlyWarning(openIdList, pastureinfo.Pastureid, data["id"].(int64))
- }
- } else if data["function"].(string) == "abnormalMixingDelay" {
- if len(openIdList) > 0 {
- abnormalMixingDelay(openIdList, pastureinfo.Pastureid, data["id"].(int64))
- }
- } else if data["function"].(string) == "endOfShift" {
- if len(openIdList) > 0 {
- endOfShift(openIdList, pastureinfo.Pastureid, data["id"].(int64))
- }
- } else if data["function"].(string) == "plansToComplete" {
- if len(openIdList) > 0 {
- plansToComplete(openIdList, pastureinfo.Pastureid, data["id"].(int64))
- }
- }
- }
- })
- downloadplandtl1.Start()
- dayCron := cron.New()
- dayCron.AddFunc("30 23 * * *", func() {
- dataList, err := tx.SQL(` select user,function,id from remind where pastureid = ? and function = ? `, pastureinfo.Pastureid, "inventoryWarning").Query().List()
- if err != nil {
- logs.Error("CronScheduled-error-5:", err)
- return
- }
- for _, data := range dataList {
- var openIdList []string
- if _, ok := data["user"]; ok {
- openIdList = strings.Split(data["user"].(string), ",")
- }
- if data["function"].(string) == "inventoryWarning" {
- if len(openIdList) > 0 {
- inventoryWarning(openIdList, pastureinfo.Pastureid, data["id"].(int64))
- }
- }
- }
- })
- dayCron.Start()
- // //圣牧自动同步前天有进行中的任务
- manualUdData(pastureinfo)
- }
- type ScheduledInfo struct {
- Id int64 `xorm:"id"`
- Sname string `xorm:"sname"`
- Action int64 `xorm:"action"`
- Childid int64 `xorm:"childid"`
- Times string `xorm:"times"`
- Enable string `xorm:"enable"`
- }
- type ScheduledUpInfo struct {
- Id int64 `xorm:"id"`
- Company string `xorm:"company"`
- Addres string `xorm:"addres"`
- Datatype int64 `xorm:"datatype"`
- Package string `xorm:"Package"`
- Datasql string `xorm:"datasql"`
- Automatic int64 `xorm:"automatic"`
- Manual int64 `xorm:"manual"`
- Targetdata string `xorm:"targetdata"`
- }
- type ScheduledDownInfo struct {
- Id int64 `xorm:"id"`
- Datatype int64 `xorm:"datatype"`
- Addres string `xorm:"addres"`
- Adressparam string `xorm:"adressparam"`
- Targetdata string `xorm:"targetdata"`
- Manual int64 `xorm:"manual"`
- Methods string `xorm:"methods"`
- }
- type ScheduledDownChildInfo struct {
- Id int64 `xorm:"id"`
- Parentid int64 `xorm:"parentid"`
- Fieldname string `xorm:"fieldname"`
- Checksql string `xorm:"checksql"`
- Dosql string `xorm:"dosql"`
- }
- func Scheduled(ctx context.Context, tx *xorm.Session, pastureinfo *udPastureInfo) {
- times := new(ScheduledInfo)
- err := tx.SQL(" select times from scheduled where action = 0 group by times").GetFirst(times).Error
- if err != nil {
- logs.Error(err)
- return
- }
- if times.Times == "0" {
- downloadedplanLogList, err := tx.SQL(` select id from downloadedplan_log where date = date_format(now(),'%Y-%m-%d') `).Query().List()
- if err != nil {
- logs.Error(err)
- return
- }
- ids := []string{}
- for _, item := range downloadedplanLogList {
- ids = append(ids, strconv.FormatInt(item["id"].(int64), 10))
- }
- fmt.Println(ids, time.Now())
- err = UpdatePush(ctx, tx, true, ids, pastureinfo, "", time.Now().Format("2006-01-02"))
- if err != nil {
- return
- }
- } else if times.Times == "1" {
- downloadedplanLogList, err := tx.SQL(` select times from downloadedplan_log where date = date_format(now(),'%Y-%m-%d') and status = 0 group by times`).Query().List()
- if err != nil {
- logs.Error(err)
- return
- }
- for _, item := range downloadedplanLogList {
- count, err := tx.SQL(` select count(1) from downloadedplan where pastureid = ? and mydate = date_format(now(),'%Y-%m-%d')
- and iscompleted = 0 and times = ? and enable = 1 `,
- pastureinfo.Pastureid, item["times"]).Count()
- if err != nil {
- logs.Error(err)
- return
- }
- if count == 0 {
- //推送
- downloadedplanLogList, err := tx.SQL(` select id from downloadedplan_log where date = date_format(now(),'%Y-%m-%d')
- and times = ? `, item["times"]).Query().List()
- if err != nil {
- logs.Error(err)
- return
- }
- ids := []string{}
- for _, item := range downloadedplanLogList {
- ids = append(ids, strconv.FormatInt(item["id"].(int64), 10))
- }
- err = UpdatePush(ctx, tx, true, ids, pastureinfo, "", time.Now().Format("2006-01-02"))
- if err != nil {
- return
- }
- }
- }
- } else if times.Times == "2" {
- count, err := tx.SQL(" select count(1) from downloadedplan where pastureid = ? and mydate = date_format(now(),'%Y-%m-%d') and iscompleted = 0 and enable = 1 ",
- pastureinfo.Pastureid).Count()
- if err != nil {
- logs.Error(err)
- return
- }
- if count == 0 {
- //推送
- downloadedplanLogList, err := tx.SQL(` select id from downloadedplan_log where date = date_format(now(),'%Y-%m-%d') `).Query().List()
- if err != nil {
- logs.Error(err)
- return
- }
- ids := []string{}
- for _, item := range downloadedplanLogList {
- ids = append(ids, strconv.FormatInt(item["id"].(int64), 10))
- }
- err = UpdatePush(ctx, tx, true, ids, pastureinfo, "", time.Now().Format("2006-01-02"))
- if err != nil {
- return
- }
- }
- }
- }
- func UpdateScheduledStatus(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- idList := fsion.Get("id").Array()
- automatic := fsion.Get("automatic").ValueStr()
- manual := fsion.Get("manual").ValueStr()
- company := fsion.Get("company").ValueStr()
- //type 0 上传,1 下载
- typee := fsion.Get("type").ValueStr()
- ids := []string{}
- for _, item := range idList {
- ids = append(ids, item.ValueStr())
- }
- tx := restful.Engine.NewSession()
- defer tx.Close()
- tx.Begin()
- sqlstr := ""
- sqlstr1 := ""
- // var args []interface{}
- if typee == "0" {
- if len(ids) > 0 {
- sqlstr = `update scheduled s join scheduled_up su on su.id = s.childid set `
- sqlstr1 = `update scheduled s join scheduled_up su on su.id = s.childid set `
- if automatic != "" {
- sqlstr += " su.automatic = 1 "
- sqlstr1 += " su.automatic = 0 "
- } else if manual != "" {
- sqlstr += " su.manual = 1 "
- sqlstr1 += " su.manual = 0 "
- }
- id := strings.Join(ids, ",")
- sqlstr += fmt.Sprintf(" where s.id in (%s) and s.action = 0 and su.company = '%s' ", id, company)
- sqlstr1 += fmt.Sprintf(" where s.id not in (%s) and s.action = 0 and su.company ='%s' ", id, company)
- } else {
- sqlstr = `update scheduled s join scheduled_up su on su.id = s.childid set `
- if automatic != "" {
- sqlstr += " su.automatic = 0 "
- } else if manual != "" {
- sqlstr += " su.manual = 0 "
- }
- sqlstr += fmt.Sprintf(" where s.action = 0 and su.company = '%s' ", company)
- }
- } else {
- if len(ids) > 0 {
- sqlstr = `update scheduled s join scheduled_down sd on sd.id = s.childid set `
- sqlstr1 = `update scheduled s join scheduled_down sd on sd.id = s.childid set `
- sqlstr += " sd.manual = 1 "
- sqlstr1 += " sd.manual = 0 "
- id := strings.Join(ids, ",")
- sqlstr += fmt.Sprintf(" where s.id in (%s) and s.action = 1 and sd.company = '%s' ", id, company)
- sqlstr1 += fmt.Sprintf(" where s.id not in (%s) and s.action = 1 and sd.company = '%s' ", id, company)
- } else {
- sqlstr = `update scheduled s join scheduled_down sd on sd.id = s.childid set `
- sqlstr += " sd.manual = 0 "
- sqlstr += fmt.Sprintf(" where s.action = 1 and sd.company = '%s' ", company)
- }
- }
- _, err := tx.SQL(sqlstr).Execute()
- if err != nil {
- log.Println("UpdateScheduledStatus-error-1: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- tx.Rollback()
- }
- if len(sqlstr1) > 0 {
- _, err = tx.SQL(sqlstr1).Execute()
- if err != nil {
- log.Println("UpdateScheduledStatus-error-2: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- tx.Rollback()
- }
- }
- err = tx.Commit()
- if err != nil {
- log.Println("UpdateScheduledStatus-error-3: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, err)
- tx.Rollback()
- }
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func SynchronizeNow(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- company := fsion.Get("company").ValueStr()
- date := fsion.Get("date").ValueStr()
- 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
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- dataList, err := tx.SQL(`select id from downloadedplan where mydate = date_format(?,'%Y-%m-%d') `, date).Query().List()
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- var idList []string
- for _, data := range dataList {
- idList = append(idList, strconv.FormatInt(data["id"].(int64), 10))
- }
- err = UpdatePush(c, tx, false, idList, pastureinfo, company, date)
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- UpdateDown(c, tx, nil, pastureinfo, company)
- if err != nil {
- appG.Response(http.StatusInternalServerError, e.ERROR, false)
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func UpdatePush(ctx context.Context, tx *xorm.Session, auto bool, idList []string, pastureinfo *udPastureInfo, company, date string) error {
- upList := make([]*ScheduledUpInfo, 0)
- up := tx.Table("scheduled_up")
- if company != "" {
- up.Where("company = ? ", company)
- }
- if auto {
- up.Where("automatic = 1")
- } else {
- up.Where("manual = 1")
- }
- err := up.Find(&upList)
- if err != nil {
- log.Println("UpdataPush-error-1: ", err)
- return err
- }
- for _, item := range upList {
- if item.Datasql != "" {
- if item.Datatype == 3 || item.Datatype == 4 {
- targetdataList := strings.Split(item.Targetdata, ",")
- var args []interface{}
- for _, targetdata := range targetdataList {
- if targetdata == "pastureid" {
- args = append(args, pastureinfo.Pastureid)
- } else if targetdata == "idlist" {
- // args = append(args, strings.Join(idList, ","))
- item.Datasql = strings.ReplaceAll(item.Datasql, "idlist", strings.Join(idList, ","))
- } else if targetdata == "date" {
- args = append(args, date)
- }
- }
- data, err := tx.SQL(item.Datasql, args...).Query().List()
- if err != nil {
- log.Println("UpdataPush-error-2: ", err)
- continue
- }
- if len(data) > 0 {
- databyte, err := json.Marshal(data)
- if err != nil {
- log.Println("UpdataPush-error-3: ", err)
- continue
- }
- var method string
- // if item.Datatype == 4 {
- // continue
- // method = "uploadnewdiliverdata"
- // }
- UDPostPush1(fmt.Sprintf(item.Package, string(databyte), len(data)), method)
- }
- if len(idList) > 0 {
- _, err := tx.SQL(fmt.Sprintf(" update downloadedplan_log set status = 1 where id in (%s)", strings.Join(idList, ","))).Execute()
- if err != nil {
- log.Println("UpdataPush-error-4: ", err)
- continue
- }
- }
- } else {
- targetdataList := strings.Split(item.Targetdata, ",")
- var args []interface{}
- for _, targetdata := range targetdataList {
- if targetdata == "pastureid" {
- args = append(args, pastureinfo.Pastureid)
- } else if targetdata == "idlist" {
- // args = append(args, strings.Join(idList, ","))
- item.Datasql = strings.ReplaceAll(item.Datasql, "idlist", strings.Join(idList, ","))
- }
- }
- data, err := tx.SQL(item.Datasql, args...).Query().List()
- if err != nil {
- log.Println("UpdataPush-error-5: ", err)
- // return err
- }
- if len(data) > 0 {
- databyte, err := json.Marshal(data)
- if err != nil {
- log.Println("UpdataPush-error-6: ", err)
- // return err
- continue
- }
- // d, err := OpenFile("a.txt")
- // d.WriteString()
- // UDPostPush(fmt.Sprintf(item.Package, string(databyte), len(data)), "application/json")
- UDPostPush1(fmt.Sprintf(item.Package, string(databyte), len(data)), "")
- }
- }
- }
- }
- return nil
- }
- // OpenFile 判断文件是否存在 存在则OpenFile 不存在则Create
- func OpenFile(filename string) (*os.File, error) {
- if _, err := os.Stat(filename); os.IsNotExist(err) {
- fmt.Println("文件不存在")
- return os.Create(filename) //创建文件
- }
- fmt.Println("文件存在")
- return os.OpenFile(filename, os.O_APPEND, 0666) //打开文件
- }
- func UpdateDown(ctx context.Context, tx *xorm.Session, idList []string, pastureinfo *udPastureInfo, company string) error {
- downList := make([]*ScheduledDownInfo, 0)
- down := tx.Table("scheduled_down")
- if company != "" {
- down.Where("company = ? ", company)
- }
- down.Where("manual = 1")
- 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)})
- // value := reflect.ValueOf(&s)
- // f := value.MethodByName("Ccaa")
- // f.Call([]reflect.Value{reflect.ValueOf(list)})
- } else {
- childList := make([]*ScheduledDownChildInfo, 0)
- child := tx.Table("scheduled_down")
- child.Where("parentid = ? ", item.Id)
- err = child.Find(&childList)
- if err != nil {
- log.Println("UpdateDown-error-2: ", err)
- return err
- }
- if len(childList) > 0 {
- tx.Begin()
- for _, c := range childList {
- fieldnames := strings.Split(c.Fieldname, ",")
- for _, data := range list {
- var args []interface{}
- dataMap := data.(map[string]interface{})
- for _, fieldname := range fieldnames {
- args = append(args, dataMap[fieldname])
- }
- _, err = tx.SQL(c.Dosql, args...).Execute()
- if err != nil {
- tx.Rollback()
- log.Println("UpdateDown-error-3: ", err)
- return err
- }
- }
- }
- err := tx.Commit()
- if err != nil {
- tx.Rollback()
- log.Println("UpdateDown-error-4: ", err)
- return err
- }
- }
- }
- }
- return nil
- }
- func httpGetMC(url, targetdata string) []interface{} {
- // url := fmt.Sprintf("https://wdc.unidairy.cn/copartner_downloads/?farmId=%s&method=%s", farmId, method)
- res, err := http.Get(url)
- if err != nil {
- return nil
- }
- robots, err := ioutil.ReadAll(res.Body)
- res.Body.Close()
- if err != nil {
- return nil
- }
- var data map[string][]interface{}
- json.Unmarshal(robots, &data)
- return data[targetdata]
- }
- type ScheduledDown struct {
- }
- func (h *ScheduledDown) SyncFeed(pastureid string, feedList []interface{}) {
- tx := restful.Engine.NewSession()
- defer tx.Close()
- err := tx.Begin()
- if err != nil {
- tx.Rollback()
- logs.Error("syncFeed-error-1:", err)
- return
- }
- for _, f := range feedList {
- feed := f.(map[string]interface{})
- var feedcode, fname, fclass, fclassid, dry interface{}
- if _, ok := feed["feedcode"]; ok {
- feedcode = feed["feedcode"]
- }
- if _, ok := feed["feedname"]; ok {
- fname = feed["feedname"]
- }
- if _, ok := feed["feedclass"]; ok {
- fclass = feed["feedclass"]
- }
- if _, ok := feed["drymatter"]; ok {
- dry = feed["drymatter"]
- }
- fclassExist, err := tx.SQL(" select id from feedclass where pastureid = ? and fcname = ?", pastureid, fclass).Exist()
- if err != nil {
- tx.Rollback()
- logs.Error("syncFeed-error-2:", err)
- return
- }
- if fclassExist {
- fclassDataList, err := tx.SQL(" select id from feedclass where pastureid = ? and fcname = ?", pastureid, fclass).QueryString()
- if err != nil {
- tx.Rollback()
- logs.Error("syncFeed-error-3:", err)
- return
- }
- for _, fclassData := range fclassDataList {
- fclassid = fclassData["id"]
- }
- } else {
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- logging.Info("create SnowIds err", err)
- }
- _, err = tx.SQL("insert into feedclass(id,pastureid,fccode,fcname,bigfeedclassname,bigfeedclassid,sort)VALUES(?,?,?,?,?,?,(select ifnull(max(f.sort),0) +1 from feedclass f where f.pastureid =? ))",
- ids, pastureid, fclass, fclass, fclass, ids, pastureid).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error("syncFeed-error-4:", err)
- return
- }
- fclassid = ids
- }
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- logging.Info("create SnowIds err", err)
- }
- insertSql := `insert into feed(id,pastureid,feedcode,fname,fclassid,fclass,dry)VALUES(?,?,?,?,?,?,?)
- ON DUPLICATE KEY UPDATE fname = ? ,dry = ? `
- _, err = tx.SQL(insertSql, ids, pastureid, feedcode, fname, fclassid, fclass, dry, fname, dry).Execute()
- if err != nil {
- tx.Rollback()
- logs.Error("syncFeed-error-5:", err)
- return
- }
- }
- err = tx.Commit()
- if err != nil {
- tx.Rollback()
- logs.Error("syncFeed-error-6:", err)
- return
- }
- return
- }
- func (h *ScheduledDown) SyncFeedp(pastureid string, feedpList []interface{}) error {
- tx := restful.Engine.NewSession()
- defer tx.Close()
- err := tx.Begin()
- if err != nil {
- logs.Error("syncFeedp-error-1:", err)
- return err
- }
- for _, f := range feedpList {
- feedp := f.(map[string]interface{})
- var barName, barCode, feedtempletCode, barId interface{}
- var ftId, tname interface{}
- var cowCount interface{}
- if _, ok := feedp["barname"]; ok {
- barName = feedp["barname"]
- }
- if _, ok := feedp["barcode"]; ok {
- barCode = feedp["barcode"]
- }
- 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 err != nil {
- tx.Rollback()
- logs.Error("syncFeedp-error-7:", err)
- return err
- }
- }
- err = tx.Commit()
- if err != nil {
- tx.Rollback()
- logs.Error("syncFeedp-error-8:", err)
- return err
- }
- return nil
- }
- 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
- }`
- targetStr, _ := json.Marshal(target)
- contentStr, _ := json.Marshal(content)
- dataStr = fmt.Sprintf(dataStr, pastureId, serviceId, string(targetStr), string(contentStr))
- fmt.Println(dataStr)
- var jsonStr = []byte(dataStr)
- req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
- req.Header.Set("Content-Type", "application/json")
- client := &http.Client{}
- resp, err := client.Do(req)
- if err != nil {
- logs.Error(err)
- }
- defer resp.Body.Close()
- }
- func UDPostPush1(data, method string) {
- url := "https://wdc.unidairy.cn/copartner_uploads/"
- // 超时时间:5秒
- var jsonStr = []byte(data)
- req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
- fmt.Println(string(jsonStr))
- req.Header.Set("Content-Type", "application/json")
- client := &http.Client{}
- resp, err := client.Do(req)
- if err != nil {
- logs.Error(err)
- }
- defer resp.Body.Close()
- body, _ := ioutil.ReadAll(resp.Body)
- fmt.Println("response Body:", string(body))
- logging.Info("response Body:", string(body))
- }
- func processAnalysisEarlyWarning(target []string, pastureId string, serviceId int64) {
- tx2 := restful.Engine.NewSession()
- defer tx2.Close()
- exist, err := tx2.Table("notice").Where("status = 1").And("content = ? ", "downloadplandtl1").Exist()
- if err != nil {
- logs.Error("processAnalysisEarlyWarning-error-1:", err)
- return
- }
- if exist {
- _, err := tx2.SQL(`update notice set status = 0 where content = ? `, "downloadplandtl1").Execute()
- if err != nil {
- logs.Error("processAnalysisEarlyWarning-error-2:", err)
- return
- }
- dataList, err := tx2.SQL("select * from downloadplandtl1_log where date = date_format(now(),'%Y-%m-%d') ").Query().List()
- if err != nil {
- logs.Error("processAnalysisEarlyWarning-error-3:", err)
- return
- }
- plandtl1SlIdMap := make(map[string][]int64, 0)
- // plandtl1HlIdMap := make(map[string][]string, 0)
- for _, data := range dataList {
- if data["type"].(int64) == 0 && data["plandtl1"] != nil {
- plandtl1SlIdMap["planid"] = append(plandtl1SlIdMap["planid"], data["plandtl1"].(int64))
- } else if data["type"].(int64) == 1 && data["plandtl1"] != nil {
- plandtl1SlIdMap["slplanid"] = append(plandtl1SlIdMap["slplanid"], data["plandtl1"].(int64))
- }
- }
- pastureList, err := tx2.SQL("select pasture_name from pasture where pastureid = ? ", pastureId).Query().List()
- if err != nil {
- logs.Error("processAnalysisEarlyWarning-error-4:", err)
- return
- }
- var pastureName string
- for _, pasture := range pastureList {
- pastureName = pasture["pasture_name"].(string)
- }
- 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,
- 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
- where d1.pid = ? and d1.sort = ? and d1.pastureid = ? and d1.intime is not null and d1.type = 0 `,
- data["planid"], data["sort"], data["pastureid"]).Query().List()
- if err != nil {
- logs.Error("processAnalysisEarlyWarning-error-5:", err)
- return
- }
- for _, plandtl1 := range plandtl1List {
- idexist := false
- //防止同顺序饲料多次推送
- for _, plandtl1Id := range plandtl1SlIdMap["planid"] {
- if plandtl1Id == plandtl1["id"].(int64) {
- idexist = true
- break
- }
- }
- if idexist {
- 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)
- }
- 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 {
- logs.Error("processAnalysisEarlyWarning-error-6:", err)
- return
- }
- }
- } 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,
- 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
- where d2.pid = ? and d2.sort = ? and d2.pastureid = ? and d2.intime is not null and d2.type = 0 `,
- data["planid"], data["sort"], data["pastureid"]).Query().List()
- // Where(" pid = ? ", data["planid"]).And("sort = ? ", data["sort"]).And(" pastureid = ? ", data["pastureid"]).And(" intime is not null").And("type = 0 ").Query().List()
- if err != nil {
- logs.Error("processAnalysisEarlyWarning-error-7:", err)
- return
- }
- for _, plandtl1 := range plandtl1List {
- idexist := false
- //防止同顺序饲料多次推送
- for _, plandtl1Id := range plandtl1SlIdMap["slplanid"] {
- if plandtl1Id == plandtl1["id"].(int64) {
- idexist = true
- break
- }
- }
- if idexist {
- continue
- }
- 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)
- }
- 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
- }
- }
- }
- }
- }
- }
- func manualUdData(pastureinfo *udPastureInfo) {
- c := cron.New()
- c.AddFunc("10 06 * * *", func() {
- tx := restful.Engine.NewSession()
- defer tx.Close()
- now := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
- // now := "2023-02-22"
- dataList, err := tx.SQL(" select id from downloadedplan where mydate = ? ", now).QueryString()
- if err != nil {
- logs.Error("manualUdData-error-1:", err)
- return
- }
- var idList []string
- for _, data := range dataList {
- idList = append(idList, data["id"])
- }
- upList := make([]*ScheduledUpInfo, 0)
- up := tx.Table("scheduled_up")
- up.Where("company = ? ", "ud")
- up.Where("datatype = 4")
- up.Where("automatic = 1")
- err = up.Find(&upList)
- if err != nil {
- log.Println("manualUdData-error-2: ", err)
- return
- }
- for _, item := range upList {
- if item.Datasql != "" {
- if item.Datatype == 4 {
- targetdataList := strings.Split(item.Targetdata, ",")
- var args []interface{}
- for _, targetdata := range targetdataList {
- if targetdata == "pastureid" {
- args = append(args, pastureinfo.Pastureid)
- } else if targetdata == "idlist" {
- item.Datasql = strings.ReplaceAll(item.Datasql, "idlist", strings.Join(idList, ","))
- } else if targetdata == "date" {
- args = append(args, now)
- }
- }
- data, err := tx.SQL(item.Datasql, args...).Query().List()
- if err != nil {
- log.Println("manualUdData-error-3: ", err)
- continue
- }
- if len(data) > 0 {
- databyte, err := json.Marshal(data)
- if err != nil {
- log.Println("manualUdData-error-4: ", err)
- continue
- }
- var method string
- UDPostPush1(fmt.Sprintf(item.Package, string(databyte), len(data)), method)
- }
- }
- }
- }
- })
- c.Start()
- }
- func abnormalMixingDelay(target []string, pastureId string, serviceId int64) {
- tx2 := restful.Engine.NewSession()
- defer tx2.Close()
- now := time.Now().Format("2006-01-02")
- dataList, err := tx2.SQL(` select id,planid,sort from downloadplandtl1_log where abnormalMixingDelay = 0 and type = 0 and pastureid = ? and date = ? `, pastureId, now).Query().List()
- if err != nil {
- logs.Error("abnormalMixingDelay-error-1:", err)
- return
- }
- if len(dataList) <= 0 {
- return
- }
- 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
- 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)
- return
- }
- 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)
- 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"])
- 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"] = plan["processtime"]
- 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)
- }
- _, err := tx2.SQL(` update downloadplandtl1_log set abnormalMixingDelay = 1 where id = ? `, data["id"]).Execute()
- if err != nil {
- logs.Error("abnormalMixingDelay-error-3:", err)
- return
- }
- }
- }
- }
- func endOfShift(target []string, pastureId string, serviceId int64) {
- tx := restful.Engine.NewSession()
- defer tx.Close()
- now := time.Now().Format("2006-01-02")
- logList, err := tx.SQL(` select times from downloadedplan_log where date = ? and classes = 0 group by times `, now).Query().List()
- if err != nil {
- logs.Error("endOfShift-error-1:", err)
- return
- }
- for _, item := range logList {
- exist, err := tx.SQL(` select id from downloadedplan where mydate = ? and times = ? and iscompleted = 0 and enable = 1 `, now, item["times"]).Exist()
- if err != nil {
- logs.Error("endOfShift-error-2:", err)
- return
- }
- 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(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,
- round( sum(UNIX_TIMESTAMP(concat("2022-01-01 ", de.processtime)) - UNIX_TIMESTAMP("2022-01-01 00:00:00") ),0) processtime ,abs(sum(de.actualweightminus)-sum(de.lweight)) as wcz
- from downloadedplan d
- join downloadplandtl1_exec de on de.pid = d.id
- where d.times = ? and d.mydate = ? and lpplantype in(0,1) group by d.times`, item["times"], now).Query().List()
- if err != nil {
- logs.Error("endOfShift-error-3:", err)
- return
- }
- slList, err := tx.SQL(` select sum(de.lweight)lweight,sum(de.actualweightminus)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,
- round( sum(UNIX_TIMESTAMP(concat("2022-01-01 ", de.processtime)) - UNIX_TIMESTAMP("2022-01-01 00:00:00") ),0) processtime ,abs(sum(de.actualweightminus)-sum(de.lweight)) as wcz
- from downloadedplan d
- join downloadplandtl2 de on de.pid = d.id
- where d.times = ? and d.mydate = ? and lpplantype in(0,2) group by d.times `, item["times"], now).Query().List()
- if err != nil {
- logs.Error("endOfShift-error-4:", err)
- return
- }
- data := make(map[string]interface{})
- for _, hl := range hlList {
- data["cltrains"] = hl["cltrains"]
- // data["hllweight"] = hl["lweight"]
- data["hlactualweightminus"] = hl["actualweightminus"]
- data["hlaccurate"] = hl["accurate"]
- data["hlcorrect"] = hl["correct"]
- data["hlcorrectcount"] = hl["correctcount"]
- // data["hlprocesstime"] = util.TimeTransformation(hl["processtime"].(int64))
- data["hlwcz"] = hl["wcz"]
- }
- for _, sl := range slList {
- // data["sllweight"] = sl["lweight"]
- data["slactualweightminus"] = sl["actualweightminus"]
- data["slaccurate"] = sl["accurate"]
- data["slcorrect"] = sl["correct"]
- data["slcorrectcount"] = sl["correctcount"]
- // data["slprocesstime"] = util.TimeTransformation(sl["processtime"].(int64))
- data["slwcz"] = sl["wcz"]
- }
- sendStr := fmt.Sprintf("班次:%v\n车次数:%v\n实际混料(kg):%v\n混料误差值(kg):%v\n混料准确率:%v\n混料正确数:%v\n混料正确率:%v\n实际撒料(kg):%v\n撒料误差值(kg):%v\n撒料准确率:%v\n撒料正确数:%v\n撒料正确率:%v",
- item["times"], data["cltrains"], data["hlactualweightminus"], data["hlwcz"], data["hlaccurate"], data["hlcorrect"], data["hlcorrectcount"],
- data["slactualweightminus"], data["slwcz"], data["slaccurate"], data["slcorrect"], data["slcorrectcount"])
- var sendList []interface{}
- 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"] = plan["processtime"]
- 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(target, sendList, pastureId, serviceId)
- _, err = tx.SQL(` update downloadedplan_log set classes = 1 where date = ? and times = ? `, now, item["times"]).Execute()
- if err != nil {
- logs.Error("endOfShift-error-5:", err)
- return
- }
- }
- }
- }
- func plansToComplete(target []string, pastureId string, serviceId int64) {
- tx := restful.Engine.NewSession()
- defer tx.Close()
- now := time.Now()
- exist, err := tx.SQL(` select id from downloadedplan_log where date = ? and dailyplan = 0 `, now).Exist()
- if err != nil {
- logs.Error("plansToComplete-error-1:", err)
- return
- }
- if exist {
- downloadedplanExist, err := tx.SQL(` select id from downloadedplan where mydate = ? and iscompleted = 0 and enable = 1 `, now).Exist()
- if err != nil {
- logs.Error("plansToComplete-error-2:", err)
- return
- }
- if !downloadedplanExist {
- hlList, err := tx.SQL(` select (select count(a.id) from ( select id from downloadedplan where mydate = ? GROUP BY times) as a ) as timescount ,( select count(1) from downloadedplan where times = d.times and mydate = d.mydate ) as cltrains,
- sum(de.lweight)lweight,sum(de.actualweightminus)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,
- round( sum(UNIX_TIMESTAMP(concat("2022-01-01 ", de.processtime)) - UNIX_TIMESTAMP("2022-01-01 00:00:00") ),0) processtime ,abs(sum(de.actualweightminus)-sum(de.lweight)) as wcz
- from downloadedplan d
- join downloadplandtl1_exec de on de.pid = d.id
- where d.mydate = ? and lpplantype in(0,1) group by d.mydate`, now, now).Query().List()
- if err != nil {
- logs.Error("plansToComplete-error-3:", err)
- return
- }
- slList, err := tx.SQL(` select sum(de.lweight)lweight,sum(de.actualweightminus)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,
- round( sum(UNIX_TIMESTAMP(concat("2022-01-01 ", de.processtime)) - UNIX_TIMESTAMP("2022-01-01 00:00:00") ),0) processtime ,abs(sum(de.actualweightminus)-sum(de.lweight)) as wcz
- from downloadedplan d
- join downloadplandtl2 de on de.pid = d.id
- where d.mydate = ? and lpplantype in(0,2) group by d.mydate `, now).Query().List()
- if err != nil {
- logs.Error("plansToComplete-error-4:", err)
- return
- }
- data := make(map[string]interface{})
- for _, hl := range hlList {
- data["timescount"] = hl["timescount"]
- data["cltrains"] = hl["cltrains"]
- data["hllweight"] = hl["lweight"]
- data["hlactualweightminus"] = hl["actualweightminus"]
- data["hlaccurate"] = hl["accurate"]
- data["hlcorrect"] = hl["correct"]
- data["hlcorrectcount"] = hl["correctcount"]
- data["hlwcz"] = hl["wcz"]
- }
- for _, sl := range slList {
- data["sllweight"] = sl["lweight"]
- data["slactualweightminus"] = sl["actualweightminus"]
- data["slaccurate"] = sl["accurate"]
- data["slcorrect"] = sl["correct"]
- data["slcorrectcount"] = sl["correctcount"]
- data["slwcz"] = sl["wcz"]
- }
- sendStr := fmt.Sprintf("班次数:%v\n车次数:\n实际混料(kg):%v\n混料误差值(kg):%v\n混料准确率:%v\n混料正确数:%v\n混料正确率:%v\n混料完成时间:%v\n实际撒料(kg):%v\n撒料误差值(kg):%v\n撒料准确率:%v\n撒料正确数:%v\n撒料正确率:%v",
- data["timescount"], data["cltrains"], data["hlactualweightminus"], data["hlwcz"], data["hlaccurate"], data["hlcorrect"], data["hlcorrectcount"],
- data["slactualweightminus"], data["slwcz"], data["slaccurate"], data["slcorrect"], data["slcorrectcount"])
- var sendList []interface{}
- 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"] = plan["processtime"]
- 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(target, sendList, pastureId, serviceId)
- _, err = tx.SQL(` update downloadedplan_log set dailyplan = 1 where date = ? `, now).Execute()
- if err != nil {
- logs.Error("plansToComplete-error-5:", err)
- return
- }
- }
- }
- }
- func AddFormulaIssued(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- tempval_ := make(map[string]interface{})
- tempCommon := make(map[string]interface{})
- tempval := make([]map[string]interface{}, 0)
- err := json.Unmarshal(dataByte, &tempval_)
- logging.Info("AddFormulaIssued ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
- if err != nil {
- } else {
- if v, ok := tempval_["data"].([]interface{}); ok {
- for _, Tvalue := range v {
- if v1, ok := Tvalue.(map[string]interface{}); ok {
- tempval = append(tempval, v1)
- }
- }
- }
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- if err != nil {
- logging.Error("tx.Begin 事务启动失败__error:", err)
- }
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- if err == nil {
- if tempv, exists := c.Get("jwt_username"); exists {
- tempCommon["jwt_username"] = tempv.(string)
- }
- for _, paramvalue := range tempval {
- if _, ok := paramvalue["resultname"]; !ok {
- paramvalue["resultname"] = paramvalue["name"]
- }
- _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
- if err != nil {
- logging.Error("AddFormulaIssued error-1:", err)
- break
- }
- }
- if err == nil {
- var temid, jtpastureid, tcode, tname, ccname, fttype string
- for _, tem := range tempval {
- if tem["name"].(string) == "insertSpotList" {
- for _, item := range tem["resultmaps"].(map[string]interface{})["list"].([]interface{}) {
- itemmap := item.(map[string]interface{})
- jtpastureid = itemmap["pastureid"].(string)
- temid = itemmap["id"].(string)
- }
- }
- }
- feedtempletList, err := tx.SQL(` select tname,tcode,id,ccname,fttype from feedtemplet where id = ? and pastureid = ? `, temid, jtpastureid).Query().List()
- if err != nil {
- logs.Error("AddFormulaIssued-error-2:", err)
- return
- }
- for _, feedtemplet := range feedtempletList {
- tcode = feedtemplet["tcode"].(string)
- tname = feedtemplet["tname"].(string)
- ccname = feedtemplet["ccname"].(string)
- fttype = feedtemplet["fttype"].(string)
- }
- for _, tem := range tempval {
- if tem["name"].(string) == "insertSpotList2" {
- for _, item := range tem["resultmaps"].(map[string]interface{})["list"].([]interface{}) {
- itemmap := item.(map[string]interface{})
- dataList, err := tx.SQL(` select user,function,id,service_id from remind where pastureid = ? and function = ? `, itemmap["id"], "formulaIssued").Query().List()
- if err != nil {
- logs.Error("AddFormulaIssued-error-3:", err)
- return
- }
- for _, data := range dataList {
- var openIdList []string
- if _, ok := data["user"]; ok {
- openIdList = strings.Split(data["user"].(string), ",")
- }
- var sendList []interface{}
- sendStr := fmt.Sprintf("配方名称:%v\n配方编码:%s\n牲畜类别:%v\n配方类型:%v",
- tname, tcode, ccname, fttype)
- 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, itemmap["id"].(string), data["service_id"].(int64))
- }
- }
- break
- }
- }
- if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
- appG.Response(http.StatusOK, e.SUCCESS, tempval)
- } else {
- appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
- }
- } else {
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- }
- }
- }
- if err != nil {
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- appG.Response(http.StatusOK, 200, nil)
- }
- }
- func AddBigInventory(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- tempval_ := make(map[string]interface{})
- tempCommon := make(map[string]interface{})
- tempval := make([]map[string]interface{}, 0)
- err := json.Unmarshal(dataByte, &tempval_)
- logging.Info("AddBigInventory ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
- if err != nil {
- } else {
- if v, ok := tempval_["common"].(map[string]interface{}); ok {
- tempCommon = v
- }
- if v, ok := tempval_["data"].([]interface{}); ok {
- for _, Tvalue := range v {
- if v1, ok := Tvalue.(map[string]interface{}); ok {
- tempval = append(tempval, v1)
- }
- }
- }
- tx := restful.Engine.NewSession()
- err := tx.Begin()
- if err != nil {
- logging.Error("tx.Begin 事务启动失败__error:", err)
- }
- defer func() {
- switch {
- case err != nil:
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- if tx != nil {
- tx.Close()
- }
- }()
- if err == nil {
- if tempv, exists := c.Get("jwt_username"); exists {
- tempCommon["jwt_username"] = tempv.(string)
- }
- for _, paramvalue := range tempval {
- if _, ok := paramvalue["resultname"]; !ok {
- paramvalue["resultname"] = paramvalue["name"]
- }
- _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
- if err != nil {
- logging.Error("AddBigInventory error-1:", err)
- break
- }
- }
- 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)
- }
- }
- 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
- }
- 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 {
- appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
- }
- } else {
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- }
- }
- }
- if err != nil {
- msg := geterrmsg(err.Error())
- appG.Response(http.StatusOK, e.ERROR, msg)
- }
- }
- func inventoryWarning(target []string, pastureId string, serviceId int64) {
- tx := restful.Engine.NewSession()
- defer tx.Close()
- feedstorageList, err := tx.SQL(`
- SELECT
- (select fname from feed where pastureid =fs.pastureid and id = fs.feedid ) feedname,
- fs.stockweight,round(fs.lweight,2) avgweight, if (fs.stockweight<=0,0, FLOOR(fs.stockweight/fs.lweight)) ldays,
- TRIM(fs.feedid) feedid,
- TRIM(fs.pastureid) pastureid,
- DATE_FORMAT((select max(date) from fswarnhis where pastureid = fs.pastureid and feedid = fs.feedid ), '%Y-%m-%d') lastdate
- FROM (SELECT fs.pushstatus,
- fs.id,
- fs.feedname,fs.stockweight,
- fs.feedid feedid,
- fs.pastureid pastureid,DATE_FORMAT(NOW(), '%Y-%m-%d') lastdate,
- (SELECT SUM(d.lweight)/7 lweight FROM downloadplandtl1 d WHERE d.pastureid = fs.pastureid
- AND date >= DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -7 DAY), '%Y-%m-%d')
- AND date <DATE_FORMAT(NOW(), '%Y-%m-%d') AND d.fid = fs.feedid) lweight
- FROM feedstorage fs) fs
- WHERE fs.pastureid=? AND fs.stockweight< fs.lweight*(SELECT inforvalue FROM sysopt WHERE sysopt.pastureid = fs.pastureid
- AND inforname = 'repertoryWarn')
- ORDER BY ldays ,stockweight `).Query().List()
- if err != nil {
- logs.Error("inventoryWarning-error-1:", err)
- return
- }
- for _, f := range feedstorageList {
- var sendList []interface{}
- sendStr := fmt.Sprintf("饲料名称:%v\n库存量(kg):%s\n近7天平均计划量:%v\n剩余使用天数:%v",
- f["feedname"], f["stockweight"], f["lweight"], f["ldays"])
- 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(target, sendList, pastureId, serviceId)
- }
- }
|