package api import ( "bytes" "context" "encoding/json" "fmt" "io/ioutil" "log" "net/http" "os" "reflect" "strconv" "strings" "time" "tmr-watch/conf/setting" "tmr-watch/http/handle/restful" "tmr-watch/pkg/app" "tmr-watch/pkg/e" "tmr-watch/pkg/logging" // "../../routers/api/gm" // "../../routers/api/sap" // "../../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,(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 } // 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() // udFeedSync(pastureinfo) // //圣牧自动同步前天有进行中的任务 // manualUdData(pastureinfo) // gm.GmUdSync(pastureinfo.Pastureid, pastureinfo.Werks) // xdmy := cron.New() // err = xdmy.AddFunc("0 30 8 * * *", func() { // // //现代牧业sap同步 // // sap.SyncMaterialOutbound() // // // 光明ud同步 // // fmt.Println(time.Now()) // gm.GmUdSync(pastureinfo.Pastureid, pastureinfo.Werks) // }) // xdmy.Start() // InitMqttClient() } 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() fmt.Println(feedcode, fname, fclassid) 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 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,softccount)VALUES(?,?,?,?) // ON DUPLICATE KEY UPDATE softccount = ? ` // _, err = tx.SQL(insertSql, pastureid, barName, barId, cowCount, cowCount).Execute() fmt.Println(barCode) _, err = tx.SQL(`update feedp fp set fp.softccount = ? where (select bcode from bar where id = fp.barid ) = ? `, cowCount, barName).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 // }` dataStr := `{ "msg_type_id": 0, "pasture_id": %s, "service_id": %d, "sys_name": "tmrWatch", "miniprogram": { "appid": "wx9ab2b5b25701da0a", "pagepath": "pages/login/login" }, "target": %s, "keys": [ "thing5", "thing2", "thing16", "thing36", "thing45" ], "content": %s }` targetStr, _ := json.Marshal(target) contentStr, _ := json.Marshal(content) 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) return } 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 ,round(d1.actualweightminus,2)actualweightminus, round(d1.lweight,2) lweight, if(d1.actualweightminus <= d1.lweight,ROUND(d1.actualweightminus/d1.lweight* 100,2),ROUND(d1.lweight/d1.actualweightminus* 100,2) ) as accuracy from downloadplandtl1 d1 join downloadedplan d on d.id = d1.pid 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 } if _, ok := plandtl1["errorvalue"]; !ok { continue } errorvalue, _ := strconv.ParseFloat(plandtl1["errorvalue"].(string), 64) if _, ok := plandtl1["feedallowratio"]; ok { if plandtl1["feedallowratio"].(float64) < errorvalue { var sendList []interface{} // sendStr := fmt.Sprintf("操作编号:%v\n牧场:%s\nTMR名称:%v\n描述:%v\n饲料名称:%v\n计划重量(kg):%v\n实际重量(kg):%v\n误差值(kg):%v\n准确率(%%):%v", // plandtl1["projname"], pastureName, plandtl1["tmrtname"], plandtl1["remark"], plandtl1["fname"], plandtl1["lweight"], plandtl1["actualweightminus"], plandtl1["errorvalue"], plandtl1["accuracy"]) sendMap1 := make(map[string]interface{}, 0) sendMap1["value"] = fmt.Sprintf("%v%s", plandtl1["projname"], "混料准确率异常") sendList = append(sendList, sendMap1) sendMap2 := make(map[string]interface{}, 0) sendMap2["value"] = fmt.Sprintf("%v-%v", plandtl1["tmrtname"], plandtl1["fname"]) sendList = append(sendList, sendMap2) sendMap3 := make(map[string]interface{}, 0) sendMap3["value"] = fmt.Sprintf("计划%v,实际%v", plandtl1["lweight"], plandtl1["actualweightminus"]) sendList = append(sendList, sendMap3) sendMap4 := make(map[string]interface{}, 0) sendMap4["value"] = fmt.Sprintf("误差值%v,准确率%v", plandtl1["errorvalue"], plandtl1["accuracy"]) sendList = append(sendList, sendMap4) sendMap5 := make(map[string]interface{}, 0) sendMap5["value"] = pastureName sendList = append(sendList, sendMap5) wxPush(target, sendList, pastureId, serviceId) } } plandtl1SlIdMap["planid"] = append(plandtl1SlIdMap["planid"], plandtl1["id"].(int64)) _, err := tx2.SQL(" update downloadplandtl1_log set plandtl1 = ? where id = ? and type = 0 ", plandtl1["id"], data["id"]).Execute() if err != nil { 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 ,round(d2.actualweightminus,2)actualweightminus,round(d2.lweight,2) lweight, if(d2.actualweightminus <= d2.lweight,ROUND(d2.actualweightminus/d2.lweight* 100,2),ROUND(d2.lweight/d2.actualweightminus* 100,2) ) as accuracy from downloadplandtl2 d2 join downloadedplan d on d.id = d2.pid 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 _, ok := plandtl1["allowratio"]; ok { if float64(plandtl1["allowratio"].(int64)) < errorvalue && float64(plandtl1["allowratio"].(int64)) != 0 { fmt.Println(plandtl1, "推送") var sendList []interface{} // sendStr := fmt.Sprintf("操作编号:%v\n牧场:%s\nTMR名称:%v\n描述:%v\n栏舍名称:%v\n计划重量(kg):%v\n实际重量(kg):%v\n误差值(kg):%v\n准确率(%%):%v", // plandtl1["projname"], pastureName, plandtl1["tmrtname"], plandtl1["remark"], plandtl1["fname"], plandtl1["lweight"], plandtl1["actualweightminus"], plandtl1["errorvalue"], plandtl1["accuracy"]) // sendMap1 := make(map[string]interface{}, 0) // sendMap1["value"] = "撒料准确率异常" // sendMap1["color"] = "#173177" // sendList = append(sendList, sendMap1) sendMap1 := make(map[string]interface{}, 0) sendMap1["value"] = fmt.Sprintf("%v%s", plandtl1["projname"], "撒料准确率异常") sendList = append(sendList, sendMap1) sendMap2 := make(map[string]interface{}, 0) sendMap2["value"] = fmt.Sprintf("%v-%v", plandtl1["tmrtname"], plandtl1["fname"]) sendList = append(sendList, sendMap2) sendMap3 := make(map[string]interface{}, 0) sendMap3["value"] = fmt.Sprintf("计划%v,实际%v", plandtl1["lweight"], plandtl1["actualweightminus"]) sendList = append(sendList, sendMap3) sendMap4 := make(map[string]interface{}, 0) sendMap4["value"] = fmt.Sprintf("误差值%v,准确率%v", plandtl1["errorvalue"], plandtl1["accuracy"]) sendList = append(sendList, sendMap4) sendMap5 := make(map[string]interface{}, 0) sendMap5["value"] = pastureName sendList = append(sendList, sendMap5) wxPush(target, sendList, pastureId, serviceId) } } if _, ok := plandtl1["id"]; ok { if _, ok := data["id"]; ok { fmt.Println(plandtl1["id"]) plandtl1SlIdMap["planid"] = append(plandtl1SlIdMap["planid"], plandtl1["id"].(int64)) _, err := tx2.SQL(" update downloadplandtl1_log set plandtl1 = ? where id = ? and type = 1 ", plandtl1["id"], data["id"]).Execute() if err != nil { logs.Error("processAnalysisEarlyWarning-error-8:", err) return } } } } } } } } 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 { logging.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 in (3,4)") up.Where("automatic = 1") err = up.Find(&upList) if err != nil { logging.Error("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 { logging.Error("manualUdData-error-3: ", err) continue } if len(data) > 0 { databyte, err := json.Marshal(data) if err != nil { logging.Error("manualUdData-error-4: ", err) continue } exist, err := tx.SQL(`select * from saplog where pastureId = ? and msgtype = ? and date_format(dataDate ,'%Y-%m-%d') = ? `, pastureinfo.Pastureid, item.Datatype, now).Exist() if exist { continue } tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url) values(?,?,?,?,?,now(),?,?,?)`, pastureinfo.Pastureid, string(databyte), "", "", "", item.Datatype, now, "https://wdc.unidairy.cn/copartner_uploads/") var method string UDPostPush1(fmt.Sprintf(item.Package, string(databyte), len(data)), method) } // } } } }) c.Start() c1 := cron.New() c1.AddFunc("01 18 * * *", func() { udFeedpSync(pastureinfo) }) c1.Start() c2 := cron.New() c2.AddFunc("30 11 * * *", func() { udFeedpSync(pastureinfo) }) c2.Start() c3 := cron.New() c3.AddFunc("59 23 * * *", func() { udFeedpSync(pastureinfo) udFeedSync(pastureinfo) }) c3.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 ifnull(de.deviation,0) deviation,round(de.lweight,2) lweight ,de.fname,de.processtime,de.stirdelay,d.tmrtname, d.projname, CONCAT(d.templetname,projname) as name , d.datacaptureno,(select pasture_name from pasture where pastureid = ?) as pasturename,round(de.actualweightminus,2) actualweightminus from downloadplandtl1_exec de join downloadedplan d on de.pid = d.id where de.pid = ? and de.sort = ? `, pastureId, data["planid"], data["sort"]).Query().List() if err != nil { logs.Error("abnormalMixingDelay-error-2:", err) return } for _, plan := range planList { fmt.Println(plan["processtime"]) fmt.Println(fmt.Sprintf("%s %v", time.Now().Format("2006-01-02"), plan["processtime"]), local) showTime, _ := time.Parse("2006-01-02 15:04:05", fmt.Sprintf("%s %v", time.Now().Format("2006-01-02"), plan["processtime"])) nowTime, _ := time.Parse("2006-01-02 15:04:05", fmt.Sprintf("%s 00:00:00", time.Now().Format("2006-01-02"))) // showTime, _ := time.ParseInLocation("2006-01-02 15:04:05", fmt.Sprintf("%s %v", time.Now().Format("2006-01-02"), plan["processtime"]), local) // nowTime, _ := time.ParseInLocation("2006-01-02 15:04:05", fmt.Sprintf("%s 00:00:00", time.Now().Format("2006-01-02")), local) if (showTime.Unix()-nowTime.Unix())/60 < plan["stirdelay"].(int64)-plan["deviation"].(int64) || (showTime.Unix()-nowTime.Unix())/60 > plan["stirdelay"].(int64)+plan["deviation"].(int64) { var sendList []interface{} // sendStr := fmt.Sprintf("操作编号:%v\n牧场:%s\nTMR名称:%v\n描述:%v\n饲料名称:%v\n计划重量(kg):%v\n实际重量(kg):%v\n过程时间:%v", // plan["projname"], plan["pasturename"], plan["tmrtname"], plan["name"], plan["fname"], plan["lweight"], plan["actualweightminus"], plan["processtime"]) sendMap1 := make(map[string]interface{}, 0) sendMap1["value"] = fmt.Sprintf("%s%v", "混料搅拌延时异常", plan["projname"]) // sendMap1["color"] = "#173177" sendList = append(sendList, sendMap1) sendMap4 := make(map[string]interface{}, 0) sendMap4["value"] = fmt.Sprintf("%v-%v", plan["tmrtname"], plan["fname"]) // sendMap4["color"] = "#173177" sendList = append(sendList, sendMap4) sendMap2 := make(map[string]interface{}, 0) sendMap2["value"] = fmt.Sprintf("计划%v,实际%v", plan["lweight"], plan["actualweightminus"]) // sendMap2["color"] = "#173177" sendList = append(sendList, sendMap2) sendMap5 := make(map[string]interface{}, 0) sendMap5["value"] = fmt.Sprintf("过程时间:%v", plan["processtime"]) // sendMap5["color"] = "#173177" sendList = append(sendList, sendMap5) sendMap3 := make(map[string]interface{}, 0) sendMap3["value"] = plan["pasturename"] // sendMap3["color"] = "#173177" sendList = append(sendList, sendMap3) wxPush(target, sendList, pastureId, serviceId) } _, err := tx2.SQL(` update downloadplandtl1_log set abnormalMixingDelay = 1 where id = ? `, data["id"]).Execute() 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, round(sum(de.lweight),2) lweight,round(sum(de.actualweightminus),2) actualweightminus , round(if(sum(de.lweight) < sum(de.actualweightminus),sum(de.lweight)/sum(de.actualweightminus) *100, sum(de.actualweightminus)/sum(de.lweight) *100),2) as accurate, ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) correct, IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0)),0) correctcount, 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 round(sum(de.lweight),2) lweight,round(sum(de.actualweightminus),2) actualweightminus , round(if(sum(de.lweight) < sum(de.actualweightminus),sum(de.lweight)/sum(de.actualweightminus) *100, sum(de.actualweightminus)/sum(de.lweight) *100),2) as accurate, ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) correct, IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0)),0) correctcount, 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.theoryweightfd.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