scheduled.go 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659
  1. package api
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "io/ioutil"
  8. "log"
  9. "net/http"
  10. "os"
  11. "reflect"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "../../pkg/app"
  16. "../../pkg/e"
  17. "../../pkg/logging"
  18. "../../pkg/setting"
  19. "../../routers/restful"
  20. "github.com/Anderson-Lu/gofasion/gofasion"
  21. "github.com/astaxie/beego/logs"
  22. "github.com/gin-gonic/gin"
  23. "github.com/robfig/cron"
  24. "github.com/xormplus/xorm"
  25. )
  26. func CronScheduled(ctx context.Context) {
  27. tx := restful.Engine.NewSession()
  28. defer tx.Close()
  29. pastureinfo := new(udPastureInfo)
  30. err := tx.SQL(`select column_default as pastureid from information_schema.COLUMNS
  31. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  32. if err != nil {
  33. logs.Error(err)
  34. return
  35. }
  36. // duetimecst, _ := time.ParseInLocation("15:04:05", "00:10:00", time.Local)
  37. // duetimecst1, _ := time.ParseInLocation("15:04:05", "00:00:00", time.Local)
  38. // spec := fmt.Sprintf("@every %v", duetimecst.Sub(duetimecst1))
  39. // c := cron.New()
  40. // c.AddFunc(spec, func() {
  41. // tx1 := restful.Engine.NewSession()
  42. // defer tx1.Close()
  43. // exist, err := tx1.Table("notice").Where("status = 1").And("content = ? ", "downloadedplan_log").Exist()
  44. // if err != nil {
  45. // logs.Error("CronScheduled-error-1:", err)
  46. // return
  47. // }
  48. // if exist {
  49. // _, err := tx.SQL(`update notice set status = 0 where content = ? `, "downloadedplan_log").Execute()
  50. // if err != nil {
  51. // logs.Error("CronScheduled-error-2:", err)
  52. // return
  53. // }
  54. // Scheduled(ctx, tx1, pastureinfo)
  55. // }
  56. // })
  57. // c.Start()
  58. //消息提醒
  59. duetimecst2, _ := time.ParseInLocation("15:04:05", "00:01:00", time.Local)
  60. duetimecst3, _ := time.ParseInLocation("15:04:05", "00:00:00", time.Local)
  61. spec1 := fmt.Sprintf("@every %v", duetimecst2.Sub(duetimecst3))
  62. downloadplandtl1 := cron.New()
  63. downloadplandtl1.AddFunc(spec1, func() {
  64. dataList, err := tx.SQL(` select user,function,id from remind where pastureid = ? `, pastureinfo.Pastureid).Query().List()
  65. if err != nil {
  66. logs.Error("CronScheduled-error-3:", err)
  67. return
  68. }
  69. for _, data := range dataList {
  70. var openIdList []string
  71. if _, ok := data["user"]; ok {
  72. openIdList = strings.Split(data["user"].(string), ",")
  73. }
  74. if data["function"].(string) == "processAnalysisEarlyWarning" {
  75. if len(openIdList) > 0 {
  76. processAnalysisEarlyWarning(openIdList, pastureinfo.Pastureid, data["id"].(int64))
  77. }
  78. } else if data["function"].(string) == "abnormalMixingDelay" {
  79. if len(openIdList) > 0 {
  80. abnormalMixingDelay(openIdList, pastureinfo.Pastureid, data["id"].(int64))
  81. }
  82. } else if data["function"].(string) == "endOfShift" {
  83. if len(openIdList) > 0 {
  84. endOfShift(openIdList, pastureinfo.Pastureid, data["id"].(int64))
  85. }
  86. } else if data["function"].(string) == "plansToComplete" {
  87. if len(openIdList) > 0 {
  88. plansToComplete(openIdList, pastureinfo.Pastureid, data["id"].(int64))
  89. }
  90. }
  91. }
  92. })
  93. downloadplandtl1.Start()
  94. dayCron := cron.New()
  95. dayCron.AddFunc("30 23 * * *", func() {
  96. dataList, err := tx.SQL(` select user,function,id from remind where pastureid = ? and function = ? `, pastureinfo.Pastureid, "inventoryWarning").Query().List()
  97. if err != nil {
  98. logs.Error("CronScheduled-error-5:", err)
  99. return
  100. }
  101. for _, data := range dataList {
  102. var openIdList []string
  103. if _, ok := data["user"]; ok {
  104. openIdList = strings.Split(data["user"].(string), ",")
  105. }
  106. if data["function"].(string) == "inventoryWarning" {
  107. if len(openIdList) > 0 {
  108. inventoryWarning(openIdList, pastureinfo.Pastureid, data["id"].(int64))
  109. }
  110. }
  111. }
  112. })
  113. dayCron.Start()
  114. // //圣牧自动同步前天有进行中的任务
  115. manualUdData(pastureinfo)
  116. }
  117. type ScheduledInfo struct {
  118. Id int64 `xorm:"id"`
  119. Sname string `xorm:"sname"`
  120. Action int64 `xorm:"action"`
  121. Childid int64 `xorm:"childid"`
  122. Times string `xorm:"times"`
  123. Enable string `xorm:"enable"`
  124. }
  125. type ScheduledUpInfo struct {
  126. Id int64 `xorm:"id"`
  127. Company string `xorm:"company"`
  128. Addres string `xorm:"addres"`
  129. Datatype int64 `xorm:"datatype"`
  130. Package string `xorm:"Package"`
  131. Datasql string `xorm:"datasql"`
  132. Automatic int64 `xorm:"automatic"`
  133. Manual int64 `xorm:"manual"`
  134. Targetdata string `xorm:"targetdata"`
  135. }
  136. type ScheduledDownInfo struct {
  137. Id int64 `xorm:"id"`
  138. Datatype int64 `xorm:"datatype"`
  139. Addres string `xorm:"addres"`
  140. Adressparam string `xorm:"adressparam"`
  141. Targetdata string `xorm:"targetdata"`
  142. Manual int64 `xorm:"manual"`
  143. Methods string `xorm:"methods"`
  144. }
  145. type ScheduledDownChildInfo struct {
  146. Id int64 `xorm:"id"`
  147. Parentid int64 `xorm:"parentid"`
  148. Fieldname string `xorm:"fieldname"`
  149. Checksql string `xorm:"checksql"`
  150. Dosql string `xorm:"dosql"`
  151. }
  152. func Scheduled(ctx context.Context, tx *xorm.Session, pastureinfo *udPastureInfo) {
  153. times := new(ScheduledInfo)
  154. err := tx.SQL(" select times from scheduled where action = 0 group by times").GetFirst(times).Error
  155. if err != nil {
  156. logs.Error(err)
  157. return
  158. }
  159. if times.Times == "0" {
  160. downloadedplanLogList, err := tx.SQL(` select id from downloadedplan_log where date = date_format(now(),'%Y-%m-%d') `).Query().List()
  161. if err != nil {
  162. logs.Error(err)
  163. return
  164. }
  165. ids := []string{}
  166. for _, item := range downloadedplanLogList {
  167. ids = append(ids, strconv.FormatInt(item["id"].(int64), 10))
  168. }
  169. fmt.Println(ids, time.Now())
  170. err = UpdatePush(ctx, tx, true, ids, pastureinfo, "", time.Now().Format("2006-01-02"))
  171. if err != nil {
  172. return
  173. }
  174. } else if times.Times == "1" {
  175. 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()
  176. if err != nil {
  177. logs.Error(err)
  178. return
  179. }
  180. for _, item := range downloadedplanLogList {
  181. count, err := tx.SQL(` select count(1) from downloadedplan where pastureid = ? and mydate = date_format(now(),'%Y-%m-%d')
  182. and iscompleted = 0 and times = ? and enable = 1 `,
  183. pastureinfo.Pastureid, item["times"]).Count()
  184. if err != nil {
  185. logs.Error(err)
  186. return
  187. }
  188. if count == 0 {
  189. //推送
  190. downloadedplanLogList, err := tx.SQL(` select id from downloadedplan_log where date = date_format(now(),'%Y-%m-%d')
  191. and times = ? `, item["times"]).Query().List()
  192. if err != nil {
  193. logs.Error(err)
  194. return
  195. }
  196. ids := []string{}
  197. for _, item := range downloadedplanLogList {
  198. ids = append(ids, strconv.FormatInt(item["id"].(int64), 10))
  199. }
  200. err = UpdatePush(ctx, tx, true, ids, pastureinfo, "", time.Now().Format("2006-01-02"))
  201. if err != nil {
  202. return
  203. }
  204. }
  205. }
  206. } else if times.Times == "2" {
  207. 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 ",
  208. pastureinfo.Pastureid).Count()
  209. if err != nil {
  210. logs.Error(err)
  211. return
  212. }
  213. if count == 0 {
  214. //推送
  215. downloadedplanLogList, err := tx.SQL(` select id from downloadedplan_log where date = date_format(now(),'%Y-%m-%d') `).Query().List()
  216. if err != nil {
  217. logs.Error(err)
  218. return
  219. }
  220. ids := []string{}
  221. for _, item := range downloadedplanLogList {
  222. ids = append(ids, strconv.FormatInt(item["id"].(int64), 10))
  223. }
  224. err = UpdatePush(ctx, tx, true, ids, pastureinfo, "", time.Now().Format("2006-01-02"))
  225. if err != nil {
  226. return
  227. }
  228. }
  229. }
  230. }
  231. func UpdateScheduledStatus(c *gin.Context) {
  232. appG := app.Gin{C: c}
  233. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  234. fsion := gofasion.NewFasion(string(dataByte))
  235. idList := fsion.Get("id").Array()
  236. automatic := fsion.Get("automatic").ValueStr()
  237. manual := fsion.Get("manual").ValueStr()
  238. company := fsion.Get("company").ValueStr()
  239. //type 0 上传,1 下载
  240. typee := fsion.Get("type").ValueStr()
  241. ids := []string{}
  242. for _, item := range idList {
  243. ids = append(ids, item.ValueStr())
  244. }
  245. tx := restful.Engine.NewSession()
  246. defer tx.Close()
  247. tx.Begin()
  248. sqlstr := ""
  249. sqlstr1 := ""
  250. // var args []interface{}
  251. if typee == "0" {
  252. if len(ids) > 0 {
  253. sqlstr = `update scheduled s join scheduled_up su on su.id = s.childid set `
  254. sqlstr1 = `update scheduled s join scheduled_up su on su.id = s.childid set `
  255. if automatic != "" {
  256. sqlstr += " su.automatic = 1 "
  257. sqlstr1 += " su.automatic = 0 "
  258. } else if manual != "" {
  259. sqlstr += " su.manual = 1 "
  260. sqlstr1 += " su.manual = 0 "
  261. }
  262. id := strings.Join(ids, ",")
  263. sqlstr += fmt.Sprintf(" where s.id in (%s) and s.action = 0 and su.company = '%s' ", id, company)
  264. sqlstr1 += fmt.Sprintf(" where s.id not in (%s) and s.action = 0 and su.company ='%s' ", id, company)
  265. } else {
  266. sqlstr = `update scheduled s join scheduled_up su on su.id = s.childid set `
  267. if automatic != "" {
  268. sqlstr += " su.automatic = 0 "
  269. } else if manual != "" {
  270. sqlstr += " su.manual = 0 "
  271. }
  272. sqlstr += fmt.Sprintf(" where s.action = 0 and su.company = '%s' ", company)
  273. }
  274. } else {
  275. if len(ids) > 0 {
  276. sqlstr = `update scheduled s join scheduled_down sd on sd.id = s.childid set `
  277. sqlstr1 = `update scheduled s join scheduled_down sd on sd.id = s.childid set `
  278. sqlstr += " sd.manual = 1 "
  279. sqlstr1 += " sd.manual = 0 "
  280. id := strings.Join(ids, ",")
  281. sqlstr += fmt.Sprintf(" where s.id in (%s) and s.action = 1 and sd.company = '%s' ", id, company)
  282. sqlstr1 += fmt.Sprintf(" where s.id not in (%s) and s.action = 1 and sd.company = '%s' ", id, company)
  283. } else {
  284. sqlstr = `update scheduled s join scheduled_down sd on sd.id = s.childid set `
  285. sqlstr += " sd.manual = 0 "
  286. sqlstr += fmt.Sprintf(" where s.action = 1 and sd.company = '%s' ", company)
  287. }
  288. }
  289. _, err := tx.SQL(sqlstr).Execute()
  290. if err != nil {
  291. log.Println("UpdateScheduledStatus-error-1: ", err)
  292. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  293. tx.Rollback()
  294. }
  295. if len(sqlstr1) > 0 {
  296. _, err = tx.SQL(sqlstr1).Execute()
  297. if err != nil {
  298. log.Println("UpdateScheduledStatus-error-2: ", err)
  299. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  300. tx.Rollback()
  301. }
  302. }
  303. err = tx.Commit()
  304. if err != nil {
  305. log.Println("UpdateScheduledStatus-error-3: ", err)
  306. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  307. tx.Rollback()
  308. }
  309. appG.Response(http.StatusOK, e.SUCCESS, true)
  310. }
  311. func SynchronizeNow(c *gin.Context) {
  312. appG := app.Gin{C: c}
  313. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  314. fsion := gofasion.NewFasion(string(dataByte))
  315. company := fsion.Get("company").ValueStr()
  316. date := fsion.Get("date").ValueStr()
  317. tx := restful.Engine.NewSession()
  318. defer tx.Close()
  319. pastureinfo := new(udPastureInfo)
  320. err := tx.SQL(`select column_default as pastureid from information_schema.COLUMNS
  321. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  322. if err != nil {
  323. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  324. return
  325. }
  326. dataList, err := tx.SQL(`select id from downloadedplan where mydate = date_format(?,'%Y-%m-%d') `, date).Query().List()
  327. if err != nil {
  328. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  329. return
  330. }
  331. var idList []string
  332. for _, data := range dataList {
  333. idList = append(idList, strconv.FormatInt(data["id"].(int64), 10))
  334. }
  335. err = UpdatePush(c, tx, false, idList, pastureinfo, company, date)
  336. if err != nil {
  337. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  338. return
  339. }
  340. UpdateDown(c, tx, nil, pastureinfo, company)
  341. if err != nil {
  342. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  343. return
  344. }
  345. appG.Response(http.StatusOK, e.SUCCESS, true)
  346. }
  347. func UpdatePush(ctx context.Context, tx *xorm.Session, auto bool, idList []string, pastureinfo *udPastureInfo, company, date string) error {
  348. upList := make([]*ScheduledUpInfo, 0)
  349. up := tx.Table("scheduled_up")
  350. if company != "" {
  351. up.Where("company = ? ", company)
  352. }
  353. if auto {
  354. up.Where("automatic = 1")
  355. } else {
  356. up.Where("manual = 1")
  357. }
  358. err := up.Find(&upList)
  359. if err != nil {
  360. log.Println("UpdataPush-error-1: ", err)
  361. return err
  362. }
  363. for _, item := range upList {
  364. if item.Datasql != "" {
  365. if item.Datatype == 3 || item.Datatype == 4 {
  366. targetdataList := strings.Split(item.Targetdata, ",")
  367. var args []interface{}
  368. for _, targetdata := range targetdataList {
  369. if targetdata == "pastureid" {
  370. args = append(args, pastureinfo.Pastureid)
  371. } else if targetdata == "idlist" {
  372. // args = append(args, strings.Join(idList, ","))
  373. item.Datasql = strings.ReplaceAll(item.Datasql, "idlist", strings.Join(idList, ","))
  374. } else if targetdata == "date" {
  375. args = append(args, date)
  376. }
  377. }
  378. data, err := tx.SQL(item.Datasql, args...).Query().List()
  379. if err != nil {
  380. log.Println("UpdataPush-error-2: ", err)
  381. continue
  382. }
  383. if len(data) > 0 {
  384. databyte, err := json.Marshal(data)
  385. if err != nil {
  386. log.Println("UpdataPush-error-3: ", err)
  387. continue
  388. }
  389. var method string
  390. // if item.Datatype == 4 {
  391. // continue
  392. // method = "uploadnewdiliverdata"
  393. // }
  394. UDPostPush1(fmt.Sprintf(item.Package, string(databyte), len(data)), method)
  395. }
  396. if len(idList) > 0 {
  397. _, err := tx.SQL(fmt.Sprintf(" update downloadedplan_log set status = 1 where id in (%s)", strings.Join(idList, ","))).Execute()
  398. if err != nil {
  399. log.Println("UpdataPush-error-4: ", err)
  400. continue
  401. }
  402. }
  403. } else {
  404. targetdataList := strings.Split(item.Targetdata, ",")
  405. var args []interface{}
  406. for _, targetdata := range targetdataList {
  407. if targetdata == "pastureid" {
  408. args = append(args, pastureinfo.Pastureid)
  409. } else if targetdata == "idlist" {
  410. // args = append(args, strings.Join(idList, ","))
  411. item.Datasql = strings.ReplaceAll(item.Datasql, "idlist", strings.Join(idList, ","))
  412. }
  413. }
  414. data, err := tx.SQL(item.Datasql, args...).Query().List()
  415. if err != nil {
  416. log.Println("UpdataPush-error-5: ", err)
  417. // return err
  418. }
  419. if len(data) > 0 {
  420. databyte, err := json.Marshal(data)
  421. if err != nil {
  422. log.Println("UpdataPush-error-6: ", err)
  423. // return err
  424. continue
  425. }
  426. // d, err := OpenFile("a.txt")
  427. // d.WriteString()
  428. // UDPostPush(fmt.Sprintf(item.Package, string(databyte), len(data)), "application/json")
  429. UDPostPush1(fmt.Sprintf(item.Package, string(databyte), len(data)), "")
  430. }
  431. }
  432. }
  433. }
  434. return nil
  435. }
  436. // OpenFile 判断文件是否存在 存在则OpenFile 不存在则Create
  437. func OpenFile(filename string) (*os.File, error) {
  438. if _, err := os.Stat(filename); os.IsNotExist(err) {
  439. fmt.Println("文件不存在")
  440. return os.Create(filename) //创建文件
  441. }
  442. fmt.Println("文件存在")
  443. return os.OpenFile(filename, os.O_APPEND, 0666) //打开文件
  444. }
  445. func UpdateDown(ctx context.Context, tx *xorm.Session, idList []string, pastureinfo *udPastureInfo, company string) error {
  446. downList := make([]*ScheduledDownInfo, 0)
  447. down := tx.Table("scheduled_down")
  448. if company != "" {
  449. down.Where("company = ? ", company)
  450. }
  451. down.Where("manual = 1")
  452. err := down.Find(&downList)
  453. if err != nil {
  454. log.Println("UpdateDown-error-1: ", err)
  455. return err
  456. }
  457. for _, item := range downList {
  458. list := httpGetMC(item.Addres, item.Targetdata)
  459. if item.Methods != "" {
  460. s := ScheduledDown{}
  461. value := reflect.ValueOf(&s)
  462. f := value.MethodByName(item.Methods)
  463. f.Call([]reflect.Value{reflect.ValueOf(pastureinfo.Pastureid), reflect.ValueOf(list)})
  464. // value := reflect.ValueOf(&s)
  465. // f := value.MethodByName("Ccaa")
  466. // f.Call([]reflect.Value{reflect.ValueOf(list)})
  467. } else {
  468. childList := make([]*ScheduledDownChildInfo, 0)
  469. child := tx.Table("scheduled_down")
  470. child.Where("parentid = ? ", item.Id)
  471. err = child.Find(&childList)
  472. if err != nil {
  473. log.Println("UpdateDown-error-2: ", err)
  474. return err
  475. }
  476. if len(childList) > 0 {
  477. tx.Begin()
  478. for _, c := range childList {
  479. fieldnames := strings.Split(c.Fieldname, ",")
  480. for _, data := range list {
  481. var args []interface{}
  482. dataMap := data.(map[string]interface{})
  483. for _, fieldname := range fieldnames {
  484. args = append(args, dataMap[fieldname])
  485. }
  486. _, err = tx.SQL(c.Dosql, args...).Execute()
  487. if err != nil {
  488. tx.Rollback()
  489. log.Println("UpdateDown-error-3: ", err)
  490. return err
  491. }
  492. }
  493. }
  494. err := tx.Commit()
  495. if err != nil {
  496. tx.Rollback()
  497. log.Println("UpdateDown-error-4: ", err)
  498. return err
  499. }
  500. }
  501. }
  502. }
  503. return nil
  504. }
  505. func httpGetMC(url, targetdata string) []interface{} {
  506. // url := fmt.Sprintf("https://wdc.unidairy.cn/copartner_downloads/?farmId=%s&method=%s", farmId, method)
  507. res, err := http.Get(url)
  508. if err != nil {
  509. return nil
  510. }
  511. robots, err := ioutil.ReadAll(res.Body)
  512. res.Body.Close()
  513. if err != nil {
  514. return nil
  515. }
  516. var data map[string][]interface{}
  517. json.Unmarshal(robots, &data)
  518. return data[targetdata]
  519. }
  520. type ScheduledDown struct {
  521. }
  522. func (h *ScheduledDown) SyncFeed(pastureid string, feedList []interface{}) {
  523. tx := restful.Engine.NewSession()
  524. defer tx.Close()
  525. err := tx.Begin()
  526. if err != nil {
  527. tx.Rollback()
  528. logs.Error("syncFeed-error-1:", err)
  529. return
  530. }
  531. for _, f := range feedList {
  532. feed := f.(map[string]interface{})
  533. var feedcode, fname, fclass, fclassid, dry interface{}
  534. if _, ok := feed["feedcode"]; ok {
  535. feedcode = feed["feedcode"]
  536. }
  537. if _, ok := feed["feedname"]; ok {
  538. fname = feed["feedname"]
  539. }
  540. if _, ok := feed["feedclass"]; ok {
  541. fclass = feed["feedclass"]
  542. }
  543. if _, ok := feed["drymatter"]; ok {
  544. dry = feed["drymatter"]
  545. }
  546. fclassExist, err := tx.SQL(" select id from feedclass where pastureid = ? and fcname = ?", pastureid, fclass).Exist()
  547. if err != nil {
  548. tx.Rollback()
  549. logs.Error("syncFeed-error-2:", err)
  550. return
  551. }
  552. if fclassExist {
  553. fclassDataList, err := tx.SQL(" select id from feedclass where pastureid = ? and fcname = ?", pastureid, fclass).QueryString()
  554. if err != nil {
  555. tx.Rollback()
  556. logs.Error("syncFeed-error-3:", err)
  557. return
  558. }
  559. for _, fclassData := range fclassDataList {
  560. fclassid = fclassData["id"]
  561. }
  562. } else {
  563. ids, err := setting.SnowIds.NextId()
  564. if err != nil {
  565. ids = time.Now().UnixNano()
  566. logging.Info("create SnowIds err", err)
  567. }
  568. _, 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 =? ))",
  569. ids, pastureid, fclass, fclass, fclass, ids, pastureid).Execute()
  570. if err != nil {
  571. tx.Rollback()
  572. logs.Error("syncFeed-error-4:", err)
  573. return
  574. }
  575. fclassid = ids
  576. }
  577. ids, err := setting.SnowIds.NextId()
  578. if err != nil {
  579. ids = time.Now().UnixNano()
  580. logging.Info("create SnowIds err", err)
  581. }
  582. insertSql := `insert into feed(id,pastureid,feedcode,fname,fclassid,fclass,dry)VALUES(?,?,?,?,?,?,?)
  583. ON DUPLICATE KEY UPDATE fname = ? ,dry = ? `
  584. _, err = tx.SQL(insertSql, ids, pastureid, feedcode, fname, fclassid, fclass, dry, fname, dry).Execute()
  585. if err != nil {
  586. tx.Rollback()
  587. logs.Error("syncFeed-error-5:", err)
  588. return
  589. }
  590. }
  591. err = tx.Commit()
  592. if err != nil {
  593. tx.Rollback()
  594. logs.Error("syncFeed-error-6:", err)
  595. return
  596. }
  597. return
  598. }
  599. func (h *ScheduledDown) SyncFeedp(pastureid string, feedpList []interface{}) error {
  600. tx := restful.Engine.NewSession()
  601. defer tx.Close()
  602. err := tx.Begin()
  603. if err != nil {
  604. logs.Error("syncFeedp-error-1:", err)
  605. return err
  606. }
  607. for _, f := range feedpList {
  608. feedp := f.(map[string]interface{})
  609. var barName, barCode, feedtempletCode, barId interface{}
  610. var ftId, tname interface{}
  611. var cowCount interface{}
  612. if _, ok := feedp["barname"]; ok {
  613. barName = feedp["barname"]
  614. }
  615. if _, ok := feedp["barcode"]; ok {
  616. barCode = feedp["barcode"]
  617. }
  618. if _, ok := feedp["cowcount"]; ok {
  619. cowCount = feedp["cowcount"]
  620. }
  621. if _, ok := feedp["feedtempletcode"]; ok {
  622. feedtempletCode = feedp["feedtempletCode"]
  623. }
  624. barCount, err := tx.SQL(" select count(1) from bar where pastureid = ? and bcode = ? ", pastureid, barCode).Count()
  625. if err != nil {
  626. tx.Rollback()
  627. logs.Error("syncFeedp-error-2:", err)
  628. return err
  629. }
  630. if barCount > 0 {
  631. barDataList, err := tx.SQL(" select id from bar where pastureid = ? and bcode = ?", pastureid, barCode).QueryString()
  632. if err != nil {
  633. tx.Rollback()
  634. logs.Error("syncFeedp-error-3:", err)
  635. return err
  636. }
  637. for _, barData := range barDataList {
  638. barId = barData["id"]
  639. }
  640. } else {
  641. barReq, err := tx.SQL("insert into bar(pastureid,bname,bcode)VALUES(?,?,?)", pastureid, barName, barCode).Execute()
  642. if err != nil {
  643. tx.Rollback()
  644. logs.Error("syncFeedp-error-4:", err)
  645. return err
  646. }
  647. id, err := barReq.LastInsertId()
  648. if err != nil {
  649. tx.Rollback()
  650. logs.Error("syncFeedp-error-5:", err)
  651. return err
  652. }
  653. barId = strconv.FormatInt(id, 10)
  654. }
  655. if feedtempletCode != "" {
  656. feedtempletDataList, err := tx.SQL(" select id,tname from feedtemplet where pastureid = ? and tcode = ?", pastureid, feedtempletCode).QueryString()
  657. if err != nil {
  658. tx.Rollback()
  659. logs.Error("syncFeedp-error-6:", err)
  660. return err
  661. }
  662. for _, feedtemplet := range feedtempletDataList {
  663. ftId = feedtemplet
  664. tname = feedtemplet
  665. }
  666. }
  667. insertSql := `insert into feedp(pastureid,barname,barid,ccount,ftid,ftname)VALUES(?,?,?,?,?,?)
  668. ON DUPLICATE KEY UPDATE ccount = ? ,ftid = ? ,ftname = ? `
  669. _, err = tx.SQL(insertSql, pastureid, barName, barId, cowCount, ftId, tname, cowCount, ftId, tname).Execute()
  670. if err != nil {
  671. tx.Rollback()
  672. logs.Error("syncFeedp-error-7:", err)
  673. return err
  674. }
  675. }
  676. err = tx.Commit()
  677. if err != nil {
  678. tx.Rollback()
  679. logs.Error("syncFeedp-error-8:", err)
  680. return err
  681. }
  682. return nil
  683. }
  684. func wxPush(target []string, content []interface{}, pastureId string, serviceId int64) {
  685. url := "http://tmrwatch.cn/notice/message"
  686. dataStr := `{
  687. "pasture_id":%s,
  688. "service_id":%d,
  689. "sys_name": "tmrWatch",
  690. "target": %s,
  691. "miniprogram": {
  692. "appid": "wx9ab2b5b25701da0a",
  693. "pagepath": "pages/login/login"
  694. },
  695. "keys": [
  696. "first",
  697. "keyword1",
  698. "keyword2",
  699. "remark"
  700. ],
  701. "content":%s
  702. }`
  703. targetStr, _ := json.Marshal(target)
  704. contentStr, _ := json.Marshal(content)
  705. dataStr = fmt.Sprintf(dataStr, pastureId, serviceId, string(targetStr), string(contentStr))
  706. fmt.Println(dataStr)
  707. var jsonStr = []byte(dataStr)
  708. req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
  709. req.Header.Set("Content-Type", "application/json")
  710. client := &http.Client{}
  711. resp, err := client.Do(req)
  712. if err != nil {
  713. logs.Error(err)
  714. }
  715. defer resp.Body.Close()
  716. }
  717. func UDPostPush1(data, method string) {
  718. url := "https://wdc.unidairy.cn/copartner_uploads/"
  719. // 超时时间:5秒
  720. var jsonStr = []byte(data)
  721. req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
  722. fmt.Println(string(jsonStr))
  723. req.Header.Set("Content-Type", "application/json")
  724. client := &http.Client{}
  725. resp, err := client.Do(req)
  726. if err != nil {
  727. logs.Error(err)
  728. }
  729. defer resp.Body.Close()
  730. body, _ := ioutil.ReadAll(resp.Body)
  731. fmt.Println("response Body:", string(body))
  732. logging.Info("response Body:", string(body))
  733. }
  734. func processAnalysisEarlyWarning(target []string, pastureId string, serviceId int64) {
  735. tx2 := restful.Engine.NewSession()
  736. defer tx2.Close()
  737. exist, err := tx2.Table("notice").Where("status = 1").And("content = ? ", "downloadplandtl1").Exist()
  738. if err != nil {
  739. logs.Error("processAnalysisEarlyWarning-error-1:", err)
  740. return
  741. }
  742. if exist {
  743. _, err := tx2.SQL(`update notice set status = 0 where content = ? `, "downloadplandtl1").Execute()
  744. if err != nil {
  745. logs.Error("processAnalysisEarlyWarning-error-2:", err)
  746. return
  747. }
  748. dataList, err := tx2.SQL("select * from downloadplandtl1_log where date = date_format(now(),'%Y-%m-%d') ").Query().List()
  749. if err != nil {
  750. logs.Error("processAnalysisEarlyWarning-error-3:", err)
  751. return
  752. }
  753. plandtl1SlIdMap := make(map[string][]int64, 0)
  754. // plandtl1HlIdMap := make(map[string][]string, 0)
  755. for _, data := range dataList {
  756. if data["type"].(int64) == 0 && data["plandtl1"] != nil {
  757. plandtl1SlIdMap["planid"] = append(plandtl1SlIdMap["planid"], data["plandtl1"].(int64))
  758. } else if data["type"].(int64) == 1 && data["plandtl1"] != nil {
  759. plandtl1SlIdMap["slplanid"] = append(plandtl1SlIdMap["slplanid"], data["plandtl1"].(int64))
  760. }
  761. }
  762. pastureList, err := tx2.SQL("select pasture_name from pasture where pastureid = ? ", pastureId).Query().List()
  763. if err != nil {
  764. logs.Error("processAnalysisEarlyWarning-error-4:", err)
  765. return
  766. }
  767. var pastureName string
  768. for _, pasture := range pastureList {
  769. pastureName = pasture["pasture_name"].(string)
  770. }
  771. for _, data := range dataList {
  772. if data["type"].(int64) == 0 {
  773. 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,
  774. if(d1.actualweightminus <= d1.lweight,ROUND(d1.actualweightminus/d1.lweight* 100,2),ROUND(d1.lweight/d1.actualweightminus* 100,2) ) as accuracy from
  775. downloadplandtl1 d1
  776. join downloadedplan d on d.id = d1.pid
  777. where d1.pid = ? and d1.sort = ? and d1.pastureid = ? and d1.intime is not null and d1.type = 0 `,
  778. data["planid"], data["sort"], data["pastureid"]).Query().List()
  779. if err != nil {
  780. logs.Error("processAnalysisEarlyWarning-error-5:", err)
  781. return
  782. }
  783. for _, plandtl1 := range plandtl1List {
  784. idexist := false
  785. //防止同顺序饲料多次推送
  786. for _, plandtl1Id := range plandtl1SlIdMap["planid"] {
  787. if plandtl1Id == plandtl1["id"].(int64) {
  788. idexist = true
  789. break
  790. }
  791. }
  792. if idexist {
  793. continue
  794. }
  795. errorvalue, _ := strconv.ParseFloat(plandtl1["errorvalue"].(string), 64)
  796. if plandtl1["feedallowratio"].(float64) < errorvalue {
  797. var sendList []interface{}
  798. sendStr := fmt.Sprintf("操作编号:%v\n牧场:%s\nTMR名称:%v\n描述:%v\n饲料名称:%v\n计划重量(kg):%v\n实际重量(kg):%v\n误差值(kg):%v\n准确率(%%):%v",
  799. plandtl1["projname"], pastureName, plandtl1["tmrtname"], plandtl1["remark"], plandtl1["fname"], plandtl1["lweight"], plandtl1["actualweightminus"], plandtl1["errorvalue"], plandtl1["accuracy"])
  800. sendMap1 := make(map[string]interface{}, 0)
  801. sendMap1["value"] = "混料准确率异常"
  802. sendMap1["color"] = "#173177"
  803. sendList = append(sendList, sendMap1)
  804. sendMap4 := make(map[string]interface{}, 0)
  805. sendMap4["value"] = sendStr
  806. sendMap4["color"] = "#173177"
  807. sendList = append(sendList, sendMap4)
  808. sendMap2 := make(map[string]interface{}, 0)
  809. sendMap2["value"] = plandtl1["intime"]
  810. sendMap2["color"] = "#173177"
  811. sendList = append(sendList, sendMap2)
  812. sendMap5 := make(map[string]interface{}, 0)
  813. sendMap5["value"] = "无备注"
  814. sendMap5["color"] = "#173177"
  815. sendList = append(sendList, sendMap5)
  816. wxPush(target, sendList, pastureId, serviceId)
  817. }
  818. plandtl1SlIdMap["planid"] = append(plandtl1SlIdMap["planid"], plandtl1["id"].(int64))
  819. _, err := tx2.SQL(" update downloadplandtl1_log set plandtl1 = ? where id = ? and type = 0 ", plandtl1["id"], data["id"]).Execute()
  820. if err != nil {
  821. logs.Error("processAnalysisEarlyWarning-error-6:", err)
  822. return
  823. }
  824. }
  825. } else {
  826. 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,
  827. if(d2.actualweightminus <= d2.lweight,ROUND(d2.actualweightminus/d2.lweight* 100,2),ROUND(d2.lweight/d2.actualweightminus* 100,2) ) as accuracy
  828. from downloadplandtl2 d2
  829. join downloadedplan d on d.id = d2.pid
  830. where d2.pid = ? and d2.sort = ? and d2.pastureid = ? and d2.intime is not null and d2.type = 0 `,
  831. data["planid"], data["sort"], data["pastureid"]).Query().List()
  832. // Where(" pid = ? ", data["planid"]).And("sort = ? ", data["sort"]).And(" pastureid = ? ", data["pastureid"]).And(" intime is not null").And("type = 0 ").Query().List()
  833. if err != nil {
  834. logs.Error("processAnalysisEarlyWarning-error-7:", err)
  835. return
  836. }
  837. for _, plandtl1 := range plandtl1List {
  838. idexist := false
  839. //防止同顺序饲料多次推送
  840. for _, plandtl1Id := range plandtl1SlIdMap["slplanid"] {
  841. if plandtl1Id == plandtl1["id"].(int64) {
  842. idexist = true
  843. break
  844. }
  845. }
  846. if idexist {
  847. continue
  848. }
  849. errorvalue, _ := strconv.ParseFloat(plandtl1["errorvalue"].(string), 64)
  850. if float64(plandtl1["allowratio"].(int64)) < errorvalue && float64(plandtl1["allowratio"].(int64)) != 0 {
  851. fmt.Println(plandtl1, "推送")
  852. var sendList []interface{}
  853. sendStr := fmt.Sprintf("操作编号:%v\n牧场:%s\nTMR名称:%v\n描述:%v\n栏舍名称:%v\n计划重量(kg):%v\n实际重量(kg):%v\n误差值(kg):%v\n准确率(%%):%v",
  854. plandtl1["projname"], pastureName, plandtl1["tmrtname"], plandtl1["remark"], plandtl1["fname"], plandtl1["lweight"], plandtl1["actualweightminus"], plandtl1["errorvalue"], plandtl1["accuracy"])
  855. sendMap1 := make(map[string]interface{}, 0)
  856. sendMap1["value"] = "撒料准确率异常"
  857. sendMap1["color"] = "#173177"
  858. sendList = append(sendList, sendMap1)
  859. sendMap4 := make(map[string]interface{}, 0)
  860. sendMap4["value"] = sendStr
  861. sendMap4["color"] = "#173177"
  862. sendList = append(sendList, sendMap4)
  863. sendMap2 := make(map[string]interface{}, 0)
  864. sendMap2["value"] = plandtl1["intime"]
  865. sendMap2["color"] = "#173177"
  866. sendList = append(sendList, sendMap2)
  867. sendMap5 := make(map[string]interface{}, 0)
  868. sendMap5["value"] = "无备注"
  869. sendMap5["color"] = "#173177"
  870. sendList = append(sendList, sendMap5)
  871. wxPush(target, sendList, pastureId, serviceId)
  872. }
  873. plandtl1SlIdMap["planid"] = append(plandtl1SlIdMap["planid"], plandtl1["id"].(int64))
  874. _, err := tx2.SQL(" update downloadplandtl1_log set plandtl1 = ? where id = ? and type = 1 ", plandtl1["id"], data["id"]).Execute()
  875. if err != nil {
  876. logs.Error("processAnalysisEarlyWarning-error-8:", err)
  877. return
  878. }
  879. }
  880. }
  881. }
  882. }
  883. }
  884. func manualUdData(pastureinfo *udPastureInfo) {
  885. c := cron.New()
  886. c.AddFunc("10 06 * * *", func() {
  887. tx := restful.Engine.NewSession()
  888. defer tx.Close()
  889. now := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
  890. // now := "2023-02-22"
  891. dataList, err := tx.SQL(" select id from downloadedplan where mydate = ? ", now).QueryString()
  892. if err != nil {
  893. logs.Error("manualUdData-error-1:", err)
  894. return
  895. }
  896. var idList []string
  897. for _, data := range dataList {
  898. idList = append(idList, data["id"])
  899. }
  900. upList := make([]*ScheduledUpInfo, 0)
  901. up := tx.Table("scheduled_up")
  902. up.Where("company = ? ", "ud")
  903. up.Where("datatype = 4")
  904. up.Where("automatic = 1")
  905. err = up.Find(&upList)
  906. if err != nil {
  907. log.Println("manualUdData-error-2: ", err)
  908. return
  909. }
  910. for _, item := range upList {
  911. if item.Datasql != "" {
  912. if item.Datatype == 4 {
  913. targetdataList := strings.Split(item.Targetdata, ",")
  914. var args []interface{}
  915. for _, targetdata := range targetdataList {
  916. if targetdata == "pastureid" {
  917. args = append(args, pastureinfo.Pastureid)
  918. } else if targetdata == "idlist" {
  919. item.Datasql = strings.ReplaceAll(item.Datasql, "idlist", strings.Join(idList, ","))
  920. } else if targetdata == "date" {
  921. args = append(args, now)
  922. }
  923. }
  924. data, err := tx.SQL(item.Datasql, args...).Query().List()
  925. if err != nil {
  926. log.Println("manualUdData-error-3: ", err)
  927. continue
  928. }
  929. if len(data) > 0 {
  930. databyte, err := json.Marshal(data)
  931. if err != nil {
  932. log.Println("manualUdData-error-4: ", err)
  933. continue
  934. }
  935. var method string
  936. UDPostPush1(fmt.Sprintf(item.Package, string(databyte), len(data)), method)
  937. }
  938. }
  939. }
  940. }
  941. })
  942. c.Start()
  943. }
  944. func abnormalMixingDelay(target []string, pastureId string, serviceId int64) {
  945. tx2 := restful.Engine.NewSession()
  946. defer tx2.Close()
  947. now := time.Now().Format("2006-01-02")
  948. 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()
  949. if err != nil {
  950. logs.Error("abnormalMixingDelay-error-1:", err)
  951. return
  952. }
  953. if len(dataList) <= 0 {
  954. return
  955. }
  956. local, _ := time.LoadLocation("Asia/Shanghai")
  957. for _, data := range dataList {
  958. 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 ,
  959. d.datacaptureno,(select pasture_name from pasture where pastureid = ?) as pasturename,de.actualweightminus from downloadplandtl1_exec de
  960. join downloadedplan d on de.pid = d.id where de.pid = ? and de.sort = ? `, pastureId, data["planid"], data["sort"]).Query().List()
  961. if err != nil {
  962. logs.Error("abnormalMixingDelay-error-2:", err)
  963. return
  964. }
  965. for _, plan := range planList {
  966. showTime, _ := time.ParseInLocation("2006-01-02 15:04:05", fmt.Sprintf("%s %s", time.Now().Format("2006-01-02"), plan["processtime"]), local)
  967. nowTime, _ := time.ParseInLocation("2006-01-02 15:04:05", fmt.Sprintf("%s 00:00:00", time.Now().Format("2006-01-02")), local)
  968. if (showTime.Unix()-nowTime.Unix())/60 < plan["stirdelay"].(int64)-plan["deviation"].(int64) || (showTime.Unix()-nowTime.Unix())/60 > plan["stirdelay"].(int64)+plan["deviation"].(int64) {
  969. var sendList []interface{}
  970. sendStr := fmt.Sprintf("操作编号:%v\n牧场:%s\nTMR名称:%v\n描述:%v\n饲料名称:%v\n计划重量(kg):%v\n实际重量(kg):%v\n过程时间:%v",
  971. plan["projname"], plan["pasturename"], plan["tmrtname"], plan["name"], plan["fname"], plan["lweight"], plan["actualweightminus"], plan["processtime"])
  972. sendMap1 := make(map[string]interface{}, 0)
  973. sendMap1["value"] = "混料搅拌延时异常"
  974. sendMap1["color"] = "#173177"
  975. sendList = append(sendList, sendMap1)
  976. sendMap4 := make(map[string]interface{}, 0)
  977. sendMap4["value"] = sendStr
  978. sendMap4["color"] = "#173177"
  979. sendList = append(sendList, sendMap4)
  980. sendMap2 := make(map[string]interface{}, 0)
  981. sendMap2["value"] = plan["processtime"]
  982. sendMap2["color"] = "#173177"
  983. sendList = append(sendList, sendMap2)
  984. sendMap5 := make(map[string]interface{}, 0)
  985. sendMap5["value"] = "无备注"
  986. sendMap5["color"] = "#173177"
  987. sendList = append(sendList, sendMap5)
  988. wxPush(target, sendList, pastureId, serviceId)
  989. }
  990. _, err := tx2.SQL(` update downloadplandtl1_log set abnormalMixingDelay = 1 where id = ? `, data["id"]).Execute()
  991. if err != nil {
  992. logs.Error("abnormalMixingDelay-error-3:", err)
  993. return
  994. }
  995. }
  996. }
  997. }
  998. func endOfShift(target []string, pastureId string, serviceId int64) {
  999. tx := restful.Engine.NewSession()
  1000. defer tx.Close()
  1001. now := time.Now().Format("2006-01-02")
  1002. logList, err := tx.SQL(` select times from downloadedplan_log where date = ? and classes = 0 group by times `, now).Query().List()
  1003. if err != nil {
  1004. logs.Error("endOfShift-error-1:", err)
  1005. return
  1006. }
  1007. for _, item := range logList {
  1008. exist, err := tx.SQL(` select id from downloadedplan where mydate = ? and times = ? and iscompleted = 0 and enable = 1 `, now, item["times"]).Exist()
  1009. if err != nil {
  1010. logs.Error("endOfShift-error-2:", err)
  1011. return
  1012. }
  1013. if !exist {
  1014. hlList, err := tx.SQL(` select ( select count(1) from downloadedplan where times = d.times and mydate = d.mydate ) as cltrains,
  1015. sum(de.lweight)lweight,sum(de.actualweightminus)actualweightminus ,
  1016. 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,
  1017. ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) correct,
  1018. IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0)),0) correctcount,
  1019. 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
  1020. from downloadedplan d
  1021. join downloadplandtl1_exec de on de.pid = d.id
  1022. where d.times = ? and d.mydate = ? and lpplantype in(0,1) group by d.times`, item["times"], now).Query().List()
  1023. if err != nil {
  1024. logs.Error("endOfShift-error-3:", err)
  1025. return
  1026. }
  1027. slList, err := tx.SQL(` select sum(de.lweight)lweight,sum(de.actualweightminus)actualweightminus ,
  1028. 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,
  1029. ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) correct,
  1030. IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0)),0) correctcount,
  1031. 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
  1032. from downloadedplan d
  1033. join downloadplandtl2 de on de.pid = d.id
  1034. where d.times = ? and d.mydate = ? and lpplantype in(0,2) group by d.times `, item["times"], now).Query().List()
  1035. if err != nil {
  1036. logs.Error("endOfShift-error-4:", err)
  1037. return
  1038. }
  1039. data := make(map[string]interface{})
  1040. for _, hl := range hlList {
  1041. data["cltrains"] = hl["cltrains"]
  1042. // data["hllweight"] = hl["lweight"]
  1043. data["hlactualweightminus"] = hl["actualweightminus"]
  1044. data["hlaccurate"] = hl["accurate"]
  1045. data["hlcorrect"] = hl["correct"]
  1046. data["hlcorrectcount"] = hl["correctcount"]
  1047. // data["hlprocesstime"] = util.TimeTransformation(hl["processtime"].(int64))
  1048. data["hlwcz"] = hl["wcz"]
  1049. }
  1050. for _, sl := range slList {
  1051. // data["sllweight"] = sl["lweight"]
  1052. data["slactualweightminus"] = sl["actualweightminus"]
  1053. data["slaccurate"] = sl["accurate"]
  1054. data["slcorrect"] = sl["correct"]
  1055. data["slcorrectcount"] = sl["correctcount"]
  1056. // data["slprocesstime"] = util.TimeTransformation(sl["processtime"].(int64))
  1057. data["slwcz"] = sl["wcz"]
  1058. }
  1059. 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",
  1060. item["times"], data["cltrains"], data["hlactualweightminus"], data["hlwcz"], data["hlaccurate"], data["hlcorrect"], data["hlcorrectcount"],
  1061. data["slactualweightminus"], data["slwcz"], data["slaccurate"], data["slcorrect"], data["slcorrectcount"])
  1062. var sendList []interface{}
  1063. sendMap1 := make(map[string]interface{}, 0)
  1064. sendMap1["value"] = "班次完成"
  1065. sendMap1["color"] = "#173177"
  1066. sendList = append(sendList, sendMap1)
  1067. sendMap4 := make(map[string]interface{}, 0)
  1068. sendMap4["value"] = sendStr
  1069. sendMap4["color"] = "#173177"
  1070. sendList = append(sendList, sendMap4)
  1071. sendMap2 := make(map[string]interface{}, 0)
  1072. // sendMap2["value"] = plan["processtime"]
  1073. sendMap2["value"] = time.Now().Format("2006-01-02 15:04:05")
  1074. sendMap2["color"] = "#173177"
  1075. sendList = append(sendList, sendMap2)
  1076. sendMap5 := make(map[string]interface{}, 0)
  1077. sendMap5["value"] = "无备注"
  1078. sendMap5["color"] = "#173177"
  1079. sendList = append(sendList, sendMap5)
  1080. wxPush(target, sendList, pastureId, serviceId)
  1081. _, err = tx.SQL(` update downloadedplan_log set classes = 1 where date = ? and times = ? `, now, item["times"]).Execute()
  1082. if err != nil {
  1083. logs.Error("endOfShift-error-5:", err)
  1084. return
  1085. }
  1086. }
  1087. }
  1088. }
  1089. func plansToComplete(target []string, pastureId string, serviceId int64) {
  1090. tx := restful.Engine.NewSession()
  1091. defer tx.Close()
  1092. now := time.Now()
  1093. exist, err := tx.SQL(` select id from downloadedplan_log where date = ? and dailyplan = 0 `, now).Exist()
  1094. if err != nil {
  1095. logs.Error("plansToComplete-error-1:", err)
  1096. return
  1097. }
  1098. if exist {
  1099. downloadedplanExist, err := tx.SQL(` select id from downloadedplan where mydate = ? and iscompleted = 0 and enable = 1 `, now).Exist()
  1100. if err != nil {
  1101. logs.Error("plansToComplete-error-2:", err)
  1102. return
  1103. }
  1104. if !downloadedplanExist {
  1105. 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,
  1106. sum(de.lweight)lweight,sum(de.actualweightminus)actualweightminus ,
  1107. 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,
  1108. ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) correct,
  1109. IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0)),0) correctcount,
  1110. 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
  1111. from downloadedplan d
  1112. join downloadplandtl1_exec de on de.pid = d.id
  1113. where d.mydate = ? and lpplantype in(0,1) group by d.mydate`, now, now).Query().List()
  1114. if err != nil {
  1115. logs.Error("plansToComplete-error-3:", err)
  1116. return
  1117. }
  1118. slList, err := tx.SQL(` select sum(de.lweight)lweight,sum(de.actualweightminus)actualweightminus ,
  1119. 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,
  1120. ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) correct,
  1121. IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0)),0) correctcount,
  1122. 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
  1123. from downloadedplan d
  1124. join downloadplandtl2 de on de.pid = d.id
  1125. where d.mydate = ? and lpplantype in(0,2) group by d.mydate `, now).Query().List()
  1126. if err != nil {
  1127. logs.Error("plansToComplete-error-4:", err)
  1128. return
  1129. }
  1130. data := make(map[string]interface{})
  1131. for _, hl := range hlList {
  1132. data["timescount"] = hl["timescount"]
  1133. data["cltrains"] = hl["cltrains"]
  1134. data["hllweight"] = hl["lweight"]
  1135. data["hlactualweightminus"] = hl["actualweightminus"]
  1136. data["hlaccurate"] = hl["accurate"]
  1137. data["hlcorrect"] = hl["correct"]
  1138. data["hlcorrectcount"] = hl["correctcount"]
  1139. data["hlwcz"] = hl["wcz"]
  1140. }
  1141. for _, sl := range slList {
  1142. data["sllweight"] = sl["lweight"]
  1143. data["slactualweightminus"] = sl["actualweightminus"]
  1144. data["slaccurate"] = sl["accurate"]
  1145. data["slcorrect"] = sl["correct"]
  1146. data["slcorrectcount"] = sl["correctcount"]
  1147. data["slwcz"] = sl["wcz"]
  1148. }
  1149. 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",
  1150. data["timescount"], data["cltrains"], data["hlactualweightminus"], data["hlwcz"], data["hlaccurate"], data["hlcorrect"], data["hlcorrectcount"],
  1151. data["slactualweightminus"], data["slwcz"], data["slaccurate"], data["slcorrect"], data["slcorrectcount"])
  1152. var sendList []interface{}
  1153. sendMap1 := make(map[string]interface{}, 0)
  1154. sendMap1["value"] = "每日计划完成"
  1155. sendMap1["color"] = "#173177"
  1156. sendList = append(sendList, sendMap1)
  1157. sendMap4 := make(map[string]interface{}, 0)
  1158. sendMap4["value"] = sendStr
  1159. sendMap4["color"] = "#173177"
  1160. sendList = append(sendList, sendMap4)
  1161. sendMap2 := make(map[string]interface{}, 0)
  1162. // sendMap2["value"] = plan["processtime"]
  1163. sendMap2["value"] = time.Now().Format("2006-01-02 15:04:05")
  1164. sendMap2["color"] = "#173177"
  1165. sendList = append(sendList, sendMap2)
  1166. sendMap5 := make(map[string]interface{}, 0)
  1167. sendMap5["value"] = "无备注"
  1168. sendMap5["color"] = "#173177"
  1169. sendList = append(sendList, sendMap5)
  1170. wxPush(target, sendList, pastureId, serviceId)
  1171. _, err = tx.SQL(` update downloadedplan_log set dailyplan = 1 where date = ? `, now).Execute()
  1172. if err != nil {
  1173. logs.Error("plansToComplete-error-5:", err)
  1174. return
  1175. }
  1176. }
  1177. }
  1178. }
  1179. func AddFormulaIssued(c *gin.Context) {
  1180. appG := app.Gin{C: c}
  1181. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1182. tempval_ := make(map[string]interface{})
  1183. tempCommon := make(map[string]interface{})
  1184. tempval := make([]map[string]interface{}, 0)
  1185. err := json.Unmarshal(dataByte, &tempval_)
  1186. logging.Info("AddFormulaIssued ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1187. if err != nil {
  1188. } else {
  1189. if v, ok := tempval_["data"].([]interface{}); ok {
  1190. for _, Tvalue := range v {
  1191. if v1, ok := Tvalue.(map[string]interface{}); ok {
  1192. tempval = append(tempval, v1)
  1193. }
  1194. }
  1195. }
  1196. tx := restful.Engine.NewSession()
  1197. err := tx.Begin()
  1198. if err != nil {
  1199. logging.Error("tx.Begin 事务启动失败__error:", err)
  1200. }
  1201. defer func() {
  1202. switch {
  1203. case err != nil:
  1204. if tx != nil {
  1205. tx.Rollback()
  1206. }
  1207. default:
  1208. if tx != nil {
  1209. err = tx.Commit()
  1210. }
  1211. }
  1212. if tx != nil {
  1213. tx.Close()
  1214. }
  1215. }()
  1216. if err == nil {
  1217. if tempv, exists := c.Get("jwt_username"); exists {
  1218. tempCommon["jwt_username"] = tempv.(string)
  1219. }
  1220. for _, paramvalue := range tempval {
  1221. if _, ok := paramvalue["resultname"]; !ok {
  1222. paramvalue["resultname"] = paramvalue["name"]
  1223. }
  1224. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  1225. if err != nil {
  1226. logging.Error("AddFormulaIssued error-1:", err)
  1227. break
  1228. }
  1229. }
  1230. if err == nil {
  1231. var temid, jtpastureid, tcode, tname, ccname, fttype string
  1232. for _, tem := range tempval {
  1233. if tem["name"].(string) == "insertSpotList" {
  1234. for _, item := range tem["resultmaps"].(map[string]interface{})["list"].([]interface{}) {
  1235. itemmap := item.(map[string]interface{})
  1236. jtpastureid = itemmap["pastureid"].(string)
  1237. temid = itemmap["id"].(string)
  1238. }
  1239. }
  1240. }
  1241. feedtempletList, err := tx.SQL(` select tname,tcode,id,ccname,fttype from feedtemplet where id = ? and pastureid = ? `, temid, jtpastureid).Query().List()
  1242. if err != nil {
  1243. logs.Error("AddFormulaIssued-error-2:", err)
  1244. return
  1245. }
  1246. for _, feedtemplet := range feedtempletList {
  1247. tcode = feedtemplet["tcode"].(string)
  1248. tname = feedtemplet["tname"].(string)
  1249. ccname = feedtemplet["ccname"].(string)
  1250. fttype = feedtemplet["fttype"].(string)
  1251. }
  1252. for _, tem := range tempval {
  1253. if tem["name"].(string) == "insertSpotList2" {
  1254. for _, item := range tem["resultmaps"].(map[string]interface{})["list"].([]interface{}) {
  1255. itemmap := item.(map[string]interface{})
  1256. dataList, err := tx.SQL(` select user,function,id,service_id from remind where pastureid = ? and function = ? `, itemmap["id"], "formulaIssued").Query().List()
  1257. if err != nil {
  1258. logs.Error("AddFormulaIssued-error-3:", err)
  1259. return
  1260. }
  1261. for _, data := range dataList {
  1262. var openIdList []string
  1263. if _, ok := data["user"]; ok {
  1264. openIdList = strings.Split(data["user"].(string), ",")
  1265. }
  1266. var sendList []interface{}
  1267. sendStr := fmt.Sprintf("配方名称:%v\n配方编码:%s\n牲畜类别:%v\n配方类型:%v",
  1268. tname, tcode, ccname, fttype)
  1269. sendMap1 := make(map[string]interface{}, 0)
  1270. sendMap1["value"] = "混料准确率异常"
  1271. sendMap1["color"] = "#173177"
  1272. sendList = append(sendList, sendMap1)
  1273. sendMap4 := make(map[string]interface{}, 0)
  1274. sendMap4["value"] = sendStr
  1275. sendMap4["color"] = "#173177"
  1276. sendList = append(sendList, sendMap4)
  1277. sendMap2 := make(map[string]interface{}, 0)
  1278. sendMap2["value"] = time.Now().Format("2006-01-02 15:04:05")
  1279. sendMap2["color"] = "#173177"
  1280. sendList = append(sendList, sendMap2)
  1281. sendMap5 := make(map[string]interface{}, 0)
  1282. sendMap5["value"] = "无备注"
  1283. sendMap5["color"] = "#173177"
  1284. sendList = append(sendList, sendMap5)
  1285. wxPush(openIdList, sendList, itemmap["id"].(string), data["service_id"].(int64))
  1286. }
  1287. }
  1288. break
  1289. }
  1290. }
  1291. if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
  1292. appG.Response(http.StatusOK, e.SUCCESS, tempval)
  1293. } else {
  1294. appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
  1295. }
  1296. } else {
  1297. msg := geterrmsg(err.Error())
  1298. appG.Response(http.StatusOK, e.ERROR, msg)
  1299. }
  1300. }
  1301. }
  1302. if err != nil {
  1303. msg := geterrmsg(err.Error())
  1304. appG.Response(http.StatusOK, e.ERROR, msg)
  1305. appG.Response(http.StatusOK, 200, nil)
  1306. }
  1307. }
  1308. func AddBigInventory(c *gin.Context) {
  1309. appG := app.Gin{C: c}
  1310. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1311. tempval_ := make(map[string]interface{})
  1312. tempCommon := make(map[string]interface{})
  1313. tempval := make([]map[string]interface{}, 0)
  1314. err := json.Unmarshal(dataByte, &tempval_)
  1315. logging.Info("AddBigInventory ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1316. if err != nil {
  1317. } else {
  1318. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  1319. tempCommon = v
  1320. }
  1321. if v, ok := tempval_["data"].([]interface{}); ok {
  1322. for _, Tvalue := range v {
  1323. if v1, ok := Tvalue.(map[string]interface{}); ok {
  1324. tempval = append(tempval, v1)
  1325. }
  1326. }
  1327. }
  1328. tx := restful.Engine.NewSession()
  1329. err := tx.Begin()
  1330. if err != nil {
  1331. logging.Error("tx.Begin 事务启动失败__error:", err)
  1332. }
  1333. defer func() {
  1334. switch {
  1335. case err != nil:
  1336. if tx != nil {
  1337. tx.Rollback()
  1338. }
  1339. default:
  1340. if tx != nil {
  1341. err = tx.Commit()
  1342. }
  1343. }
  1344. if tx != nil {
  1345. tx.Close()
  1346. }
  1347. }()
  1348. if err == nil {
  1349. if tempv, exists := c.Get("jwt_username"); exists {
  1350. tempCommon["jwt_username"] = tempv.(string)
  1351. }
  1352. for _, paramvalue := range tempval {
  1353. if _, ok := paramvalue["resultname"]; !ok {
  1354. paramvalue["resultname"] = paramvalue["name"]
  1355. }
  1356. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  1357. if err != nil {
  1358. logging.Error("AddBigInventory error-1:", err)
  1359. break
  1360. }
  1361. }
  1362. if err == nil {
  1363. var pastureid, date string
  1364. for _, tem := range tempval {
  1365. if tem["name"].(string) == "insertBigInventory" {
  1366. parammaps := tem["parammaps"].(map[string]interface{})
  1367. pastureid = parammaps["pastureid"].(string)
  1368. date = parammaps["inventorydate"].(string)
  1369. }
  1370. }
  1371. feedinventoryList, err := tx.SQL(`SELECT
  1372. remark,DATE_FORMAT(inventorydate, '%Y-%m-%d') inventorydate,createuser,
  1373. TRIM(f.id) id,
  1374. TRIM(f.pastureid) pastureid,
  1375. 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,
  1376. 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 ,
  1377. 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
  1378. FROM
  1379. feedinventory f
  1380. WHERE f.pastureid = ? and f.inventorydate=? `, pastureid, date).Query().List()
  1381. if err != nil {
  1382. logs.Error("AddBigInventory-error-2:", err)
  1383. return
  1384. }
  1385. dataList, err := tx.SQL(` select user,function,id,service_id from remind where pastureid = ? and function = ? `, pastureid, "formulaIssued").Query().List()
  1386. if err != nil {
  1387. logs.Error("AddBigInventory-error-3:", err)
  1388. return
  1389. }
  1390. for _, data := range dataList {
  1391. var openIdList []string
  1392. if _, ok := data["user"]; ok {
  1393. openIdList = strings.Split(data["user"].(string), ",")
  1394. }
  1395. var createuser, lessWeight, moreWeight, differWeight interface{}
  1396. for _, f := range feedinventoryList {
  1397. createuser = f["createuser"]
  1398. lessWeight = f["lessWeight"]
  1399. moreWeight = f["moreWeight"]
  1400. differWeight = f["differWeight"]
  1401. }
  1402. var sendList []interface{}
  1403. sendStr := fmt.Sprintf("盘点人:%v\n盘盈库存(kg):%v\n盘亏库存(kg):%v\n盈亏净值(kg):%v",
  1404. createuser, moreWeight, lessWeight, differWeight)
  1405. sendMap1 := make(map[string]interface{}, 0)
  1406. sendMap1["value"] = "库存盘点"
  1407. sendMap1["color"] = "#173177"
  1408. sendList = append(sendList, sendMap1)
  1409. sendMap4 := make(map[string]interface{}, 0)
  1410. sendMap4["value"] = sendStr
  1411. sendMap4["color"] = "#173177"
  1412. sendList = append(sendList, sendMap4)
  1413. sendMap2 := make(map[string]interface{}, 0)
  1414. sendMap2["value"] = time.Now().Format("2006-01-02 15:04:05")
  1415. sendMap2["color"] = "#173177"
  1416. sendList = append(sendList, sendMap2)
  1417. sendMap5 := make(map[string]interface{}, 0)
  1418. sendMap5["value"] = "无备注"
  1419. sendMap5["color"] = "#173177"
  1420. sendList = append(sendList, sendMap5)
  1421. wxPush(openIdList, sendList, pastureid, data["service_id"].(int64))
  1422. }
  1423. if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
  1424. appG.Response(http.StatusOK, e.SUCCESS, tempval)
  1425. } else {
  1426. appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
  1427. }
  1428. } else {
  1429. msg := geterrmsg(err.Error())
  1430. appG.Response(http.StatusOK, e.ERROR, msg)
  1431. }
  1432. }
  1433. }
  1434. if err != nil {
  1435. msg := geterrmsg(err.Error())
  1436. appG.Response(http.StatusOK, e.ERROR, msg)
  1437. }
  1438. }
  1439. func inventoryWarning(target []string, pastureId string, serviceId int64) {
  1440. tx := restful.Engine.NewSession()
  1441. defer tx.Close()
  1442. feedstorageList, err := tx.SQL(`
  1443. SELECT
  1444. (select fname from feed where pastureid =fs.pastureid and id = fs.feedid ) feedname,
  1445. fs.stockweight,round(fs.lweight,2) avgweight, if (fs.stockweight<=0,0, FLOOR(fs.stockweight/fs.lweight)) ldays,
  1446. TRIM(fs.feedid) feedid,
  1447. TRIM(fs.pastureid) pastureid,
  1448. DATE_FORMAT((select max(date) from fswarnhis where pastureid = fs.pastureid and feedid = fs.feedid ), '%Y-%m-%d') lastdate
  1449. FROM (SELECT fs.pushstatus,
  1450. fs.id,
  1451. fs.feedname,fs.stockweight,
  1452. fs.feedid feedid,
  1453. fs.pastureid pastureid,DATE_FORMAT(NOW(), '%Y-%m-%d') lastdate,
  1454. (SELECT SUM(d.lweight)/7 lweight FROM downloadplandtl1 d WHERE d.pastureid = fs.pastureid
  1455. AND date >= DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -7 DAY), '%Y-%m-%d')
  1456. AND date <DATE_FORMAT(NOW(), '%Y-%m-%d') AND d.fid = fs.feedid) lweight
  1457. FROM feedstorage fs) fs
  1458. WHERE fs.pastureid=? AND fs.stockweight< fs.lweight*(SELECT inforvalue FROM sysopt WHERE sysopt.pastureid = fs.pastureid
  1459. AND inforname = 'repertoryWarn')
  1460. ORDER BY ldays ,stockweight `).Query().List()
  1461. if err != nil {
  1462. logs.Error("inventoryWarning-error-1:", err)
  1463. return
  1464. }
  1465. for _, f := range feedstorageList {
  1466. var sendList []interface{}
  1467. sendStr := fmt.Sprintf("饲料名称:%v\n库存量(kg):%s\n近7天平均计划量:%v\n剩余使用天数:%v",
  1468. f["feedname"], f["stockweight"], f["lweight"], f["ldays"])
  1469. sendMap1 := make(map[string]interface{}, 0)
  1470. sendMap1["value"] = "库存预警"
  1471. sendMap1["color"] = "#173177"
  1472. sendList = append(sendList, sendMap1)
  1473. sendMap4 := make(map[string]interface{}, 0)
  1474. sendMap4["value"] = sendStr
  1475. sendMap4["color"] = "#173177"
  1476. sendList = append(sendList, sendMap4)
  1477. sendMap2 := make(map[string]interface{}, 0)
  1478. sendMap2["value"] = time.Now().Format("2006-01-02 15:04:05")
  1479. sendMap2["color"] = "#173177"
  1480. sendList = append(sendList, sendMap2)
  1481. sendMap5 := make(map[string]interface{}, 0)
  1482. sendMap5["value"] = "无备注"
  1483. sendMap5["color"] = "#173177"
  1484. sendList = append(sendList, sendMap5)
  1485. wxPush(target, sendList, pastureId, serviceId)
  1486. }
  1487. }