scheduled.go 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684
  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. "tmr-watch/conf/setting"
  16. "tmr-watch/http/handle/restful"
  17. "tmr-watch/pkg/app"
  18. "tmr-watch/pkg/e"
  19. "tmr-watch/pkg/logging"
  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. // file, err := os.Create("example.txt")
  733. // if err != nil {
  734. // fmt.Println(err)
  735. // return
  736. // }
  737. // defer file.Close()
  738. // // 创建一个写入器并将其与文件关联
  739. // writer := bufio.NewWriter(file)
  740. // // 将字符串写入缓冲区
  741. // // str := "Hello, world!"
  742. // _, err = writer.WriteString(data)
  743. // if err != nil {
  744. // fmt.Println(err)
  745. // return
  746. // }
  747. // // 刷新缓冲区,确保所有数据都已成功写入文件
  748. // err = writer.Flush()
  749. // if err != nil {
  750. // fmt.Println(err)
  751. // return
  752. // }
  753. logging.Info("response Body:", string(body))
  754. }
  755. func processAnalysisEarlyWarning(target []string, pastureId string, serviceId int64) {
  756. tx2 := restful.Engine.NewSession()
  757. defer tx2.Close()
  758. exist, err := tx2.Table("notice").Where("status = 1").And("content = ? ", "downloadplandtl1").Exist()
  759. if err != nil {
  760. logs.Error("processAnalysisEarlyWarning-error-1:", err)
  761. return
  762. }
  763. if exist {
  764. _, err := tx2.SQL(`update notice set status = 0 where content = ? `, "downloadplandtl1").Execute()
  765. if err != nil {
  766. logs.Error("processAnalysisEarlyWarning-error-2:", err)
  767. return
  768. }
  769. dataList, err := tx2.SQL("select * from downloadplandtl1_log where date = date_format(now(),'%Y-%m-%d') ").Query().List()
  770. if err != nil {
  771. logs.Error("processAnalysisEarlyWarning-error-3:", err)
  772. return
  773. }
  774. plandtl1SlIdMap := make(map[string][]int64, 0)
  775. // plandtl1HlIdMap := make(map[string][]string, 0)
  776. for _, data := range dataList {
  777. if data["type"].(int64) == 0 && data["plandtl1"] != nil {
  778. plandtl1SlIdMap["planid"] = append(plandtl1SlIdMap["planid"], data["plandtl1"].(int64))
  779. } else if data["type"].(int64) == 1 && data["plandtl1"] != nil {
  780. plandtl1SlIdMap["slplanid"] = append(plandtl1SlIdMap["slplanid"], data["plandtl1"].(int64))
  781. }
  782. }
  783. pastureList, err := tx2.SQL("select pasture_name from pasture where pastureid = ? ", pastureId).Query().List()
  784. if err != nil {
  785. logs.Error("processAnalysisEarlyWarning-error-4:", err)
  786. return
  787. }
  788. var pastureName string
  789. for _, pasture := range pastureList {
  790. pastureName = pasture["pasture_name"].(string)
  791. }
  792. for _, data := range dataList {
  793. if data["type"].(int64) == 0 {
  794. 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,
  795. if(d1.actualweightminus <= d1.lweight,ROUND(d1.actualweightminus/d1.lweight* 100,2),ROUND(d1.lweight/d1.actualweightminus* 100,2) ) as accuracy from
  796. downloadplandtl1 d1
  797. join downloadedplan d on d.id = d1.pid
  798. where d1.pid = ? and d1.sort = ? and d1.pastureid = ? and d1.intime is not null and d1.type = 0 `,
  799. data["planid"], data["sort"], data["pastureid"]).Query().List()
  800. if err != nil {
  801. logs.Error("processAnalysisEarlyWarning-error-5:", err)
  802. return
  803. }
  804. for _, plandtl1 := range plandtl1List {
  805. idexist := false
  806. //防止同顺序饲料多次推送
  807. for _, plandtl1Id := range plandtl1SlIdMap["planid"] {
  808. if plandtl1Id == plandtl1["id"].(int64) {
  809. idexist = true
  810. break
  811. }
  812. }
  813. if idexist {
  814. continue
  815. }
  816. errorvalue, _ := strconv.ParseFloat(plandtl1["errorvalue"].(string), 64)
  817. if plandtl1["feedallowratio"].(float64) < errorvalue {
  818. var sendList []interface{}
  819. sendStr := fmt.Sprintf("操作编号:%v\n牧场:%s\nTMR名称:%v\n描述:%v\n饲料名称:%v\n计划重量(kg):%v\n实际重量(kg):%v\n误差值(kg):%v\n准确率(%%):%v",
  820. plandtl1["projname"], pastureName, plandtl1["tmrtname"], plandtl1["remark"], plandtl1["fname"], plandtl1["lweight"], plandtl1["actualweightminus"], plandtl1["errorvalue"], plandtl1["accuracy"])
  821. sendMap1 := make(map[string]interface{}, 0)
  822. sendMap1["value"] = "混料准确率异常"
  823. sendMap1["color"] = "#173177"
  824. sendList = append(sendList, sendMap1)
  825. sendMap4 := make(map[string]interface{}, 0)
  826. sendMap4["value"] = sendStr
  827. sendMap4["color"] = "#173177"
  828. sendList = append(sendList, sendMap4)
  829. sendMap2 := make(map[string]interface{}, 0)
  830. sendMap2["value"] = plandtl1["intime"]
  831. sendMap2["color"] = "#173177"
  832. sendList = append(sendList, sendMap2)
  833. sendMap5 := make(map[string]interface{}, 0)
  834. sendMap5["value"] = "无备注"
  835. sendMap5["color"] = "#173177"
  836. sendList = append(sendList, sendMap5)
  837. wxPush(target, sendList, pastureId, serviceId)
  838. }
  839. plandtl1SlIdMap["planid"] = append(plandtl1SlIdMap["planid"], plandtl1["id"].(int64))
  840. _, err := tx2.SQL(" update downloadplandtl1_log set plandtl1 = ? where id = ? and type = 0 ", plandtl1["id"], data["id"]).Execute()
  841. if err != nil {
  842. logs.Error("processAnalysisEarlyWarning-error-6:", err)
  843. return
  844. }
  845. }
  846. } else {
  847. 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,
  848. if(d2.actualweightminus <= d2.lweight,ROUND(d2.actualweightminus/d2.lweight* 100,2),ROUND(d2.lweight/d2.actualweightminus* 100,2) ) as accuracy
  849. from downloadplandtl2 d2
  850. join downloadedplan d on d.id = d2.pid
  851. where d2.pid = ? and d2.sort = ? and d2.pastureid = ? and d2.intime is not null and d2.type = 0 `,
  852. data["planid"], data["sort"], data["pastureid"]).Query().List()
  853. // Where(" pid = ? ", data["planid"]).And("sort = ? ", data["sort"]).And(" pastureid = ? ", data["pastureid"]).And(" intime is not null").And("type = 0 ").Query().List()
  854. if err != nil {
  855. logs.Error("processAnalysisEarlyWarning-error-7:", err)
  856. return
  857. }
  858. for _, plandtl1 := range plandtl1List {
  859. idexist := false
  860. //防止同顺序饲料多次推送
  861. for _, plandtl1Id := range plandtl1SlIdMap["slplanid"] {
  862. if plandtl1Id == plandtl1["id"].(int64) {
  863. idexist = true
  864. break
  865. }
  866. }
  867. if idexist {
  868. continue
  869. }
  870. errorvalue, _ := strconv.ParseFloat(plandtl1["errorvalue"].(string), 64)
  871. if float64(plandtl1["allowratio"].(int64)) < errorvalue && float64(plandtl1["allowratio"].(int64)) != 0 {
  872. fmt.Println(plandtl1, "推送")
  873. var sendList []interface{}
  874. sendStr := fmt.Sprintf("操作编号:%v\n牧场:%s\nTMR名称:%v\n描述:%v\n栏舍名称:%v\n计划重量(kg):%v\n实际重量(kg):%v\n误差值(kg):%v\n准确率(%%):%v",
  875. plandtl1["projname"], pastureName, plandtl1["tmrtname"], plandtl1["remark"], plandtl1["fname"], plandtl1["lweight"], plandtl1["actualweightminus"], plandtl1["errorvalue"], plandtl1["accuracy"])
  876. sendMap1 := make(map[string]interface{}, 0)
  877. sendMap1["value"] = "撒料准确率异常"
  878. sendMap1["color"] = "#173177"
  879. sendList = append(sendList, sendMap1)
  880. sendMap4 := make(map[string]interface{}, 0)
  881. sendMap4["value"] = sendStr
  882. sendMap4["color"] = "#173177"
  883. sendList = append(sendList, sendMap4)
  884. sendMap2 := make(map[string]interface{}, 0)
  885. sendMap2["value"] = plandtl1["intime"]
  886. sendMap2["color"] = "#173177"
  887. sendList = append(sendList, sendMap2)
  888. sendMap5 := make(map[string]interface{}, 0)
  889. sendMap5["value"] = "无备注"
  890. sendMap5["color"] = "#173177"
  891. sendList = append(sendList, sendMap5)
  892. wxPush(target, sendList, pastureId, serviceId)
  893. }
  894. plandtl1SlIdMap["planid"] = append(plandtl1SlIdMap["planid"], plandtl1["id"].(int64))
  895. _, err := tx2.SQL(" update downloadplandtl1_log set plandtl1 = ? where id = ? and type = 1 ", plandtl1["id"], data["id"]).Execute()
  896. if err != nil {
  897. logs.Error("processAnalysisEarlyWarning-error-8:", err)
  898. return
  899. }
  900. }
  901. }
  902. }
  903. }
  904. }
  905. func manualUdData(pastureinfo *udPastureInfo) {
  906. c := cron.New()
  907. c.AddFunc("10 06 * * *", func() {
  908. tx := restful.Engine.NewSession()
  909. defer tx.Close()
  910. now := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
  911. // now := "2023-02-22"
  912. dataList, err := tx.SQL(" select id from downloadedplan where mydate = ? ", now).QueryString()
  913. if err != nil {
  914. logging.Error("manualUdData-error-1:", err)
  915. return
  916. }
  917. var idList []string
  918. for _, data := range dataList {
  919. idList = append(idList, data["id"])
  920. }
  921. upList := make([]*ScheduledUpInfo, 0)
  922. up := tx.Table("scheduled_up")
  923. up.Where("company = ? ", "ud")
  924. up.Where("datatype in (3,4)")
  925. up.Where("automatic = 1")
  926. err = up.Find(&upList)
  927. if err != nil {
  928. logging.Error("manualUdData-error-2: ", err)
  929. return
  930. }
  931. for _, item := range upList {
  932. if item.Datasql != "" {
  933. // if item.Datatype == 4 {
  934. targetdataList := strings.Split(item.Targetdata, ",")
  935. var args []interface{}
  936. for _, targetdata := range targetdataList {
  937. if targetdata == "pastureid" {
  938. args = append(args, pastureinfo.Pastureid)
  939. } else if targetdata == "idlist" {
  940. item.Datasql = strings.ReplaceAll(item.Datasql, "idlist", strings.Join(idList, ","))
  941. } else if targetdata == "date" {
  942. args = append(args, now)
  943. }
  944. }
  945. data, err := tx.SQL(item.Datasql, args...).Query().List()
  946. if err != nil {
  947. logging.Error("manualUdData-error-3: ", err)
  948. continue
  949. }
  950. if len(data) > 0 {
  951. databyte, err := json.Marshal(data)
  952. if err != nil {
  953. logging.Error("manualUdData-error-4: ", err)
  954. continue
  955. }
  956. var method string
  957. UDPostPush1(fmt.Sprintf(item.Package, string(databyte), len(data)), method)
  958. }
  959. // }
  960. }
  961. }
  962. })
  963. c.Start()
  964. }
  965. func abnormalMixingDelay(target []string, pastureId string, serviceId int64) {
  966. tx2 := restful.Engine.NewSession()
  967. defer tx2.Close()
  968. now := time.Now().Format("2006-01-02")
  969. 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()
  970. if err != nil {
  971. logs.Error("abnormalMixingDelay-error-1:", err)
  972. return
  973. }
  974. if len(dataList) <= 0 {
  975. return
  976. }
  977. local, _ := time.LoadLocation("Asia/Shanghai")
  978. for _, data := range dataList {
  979. 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 ,
  980. d.datacaptureno,(select pasture_name from pasture where pastureid = ?) as pasturename,de.actualweightminus from downloadplandtl1_exec de
  981. join downloadedplan d on de.pid = d.id where de.pid = ? and de.sort = ? `, pastureId, data["planid"], data["sort"]).Query().List()
  982. if err != nil {
  983. logs.Error("abnormalMixingDelay-error-2:", err)
  984. return
  985. }
  986. for _, plan := range planList {
  987. showTime, _ := time.ParseInLocation("2006-01-02 15:04:05", fmt.Sprintf("%s %s", time.Now().Format("2006-01-02"), plan["processtime"]), local)
  988. nowTime, _ := time.ParseInLocation("2006-01-02 15:04:05", fmt.Sprintf("%s 00:00:00", time.Now().Format("2006-01-02")), local)
  989. if (showTime.Unix()-nowTime.Unix())/60 < plan["stirdelay"].(int64)-plan["deviation"].(int64) || (showTime.Unix()-nowTime.Unix())/60 > plan["stirdelay"].(int64)+plan["deviation"].(int64) {
  990. var sendList []interface{}
  991. sendStr := fmt.Sprintf("操作编号:%v\n牧场:%s\nTMR名称:%v\n描述:%v\n饲料名称:%v\n计划重量(kg):%v\n实际重量(kg):%v\n过程时间:%v",
  992. plan["projname"], plan["pasturename"], plan["tmrtname"], plan["name"], plan["fname"], plan["lweight"], plan["actualweightminus"], plan["processtime"])
  993. sendMap1 := make(map[string]interface{}, 0)
  994. sendMap1["value"] = "混料搅拌延时异常"
  995. sendMap1["color"] = "#173177"
  996. sendList = append(sendList, sendMap1)
  997. sendMap4 := make(map[string]interface{}, 0)
  998. sendMap4["value"] = sendStr
  999. sendMap4["color"] = "#173177"
  1000. sendList = append(sendList, sendMap4)
  1001. sendMap2 := make(map[string]interface{}, 0)
  1002. sendMap2["value"] = plan["processtime"]
  1003. sendMap2["color"] = "#173177"
  1004. sendList = append(sendList, sendMap2)
  1005. sendMap5 := make(map[string]interface{}, 0)
  1006. sendMap5["value"] = "无备注"
  1007. sendMap5["color"] = "#173177"
  1008. sendList = append(sendList, sendMap5)
  1009. wxPush(target, sendList, pastureId, serviceId)
  1010. }
  1011. _, err := tx2.SQL(` update downloadplandtl1_log set abnormalMixingDelay = 1 where id = ? `, data["id"]).Execute()
  1012. if err != nil {
  1013. logs.Error("abnormalMixingDelay-error-3:", err)
  1014. return
  1015. }
  1016. }
  1017. }
  1018. }
  1019. func endOfShift(target []string, pastureId string, serviceId int64) {
  1020. tx := restful.Engine.NewSession()
  1021. defer tx.Close()
  1022. now := time.Now().Format("2006-01-02")
  1023. logList, err := tx.SQL(` select times from downloadedplan_log where date = ? and classes = 0 group by times `, now).Query().List()
  1024. if err != nil {
  1025. logs.Error("endOfShift-error-1:", err)
  1026. return
  1027. }
  1028. for _, item := range logList {
  1029. exist, err := tx.SQL(` select id from downloadedplan where mydate = ? and times = ? and iscompleted = 0 and enable = 1 `, now, item["times"]).Exist()
  1030. if err != nil {
  1031. logs.Error("endOfShift-error-2:", err)
  1032. return
  1033. }
  1034. if !exist {
  1035. hlList, err := tx.SQL(` select ( select count(1) from downloadedplan where times = d.times and mydate = d.mydate ) as cltrains,
  1036. sum(de.lweight)lweight,sum(de.actualweightminus)actualweightminus ,
  1037. 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,
  1038. ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) correct,
  1039. IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0)),0) correctcount,
  1040. 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
  1041. from downloadedplan d
  1042. join downloadplandtl1_exec de on de.pid = d.id
  1043. where d.times = ? and d.mydate = ? and lpplantype in(0,1) group by d.times`, item["times"], now).Query().List()
  1044. if err != nil {
  1045. logs.Error("endOfShift-error-3:", err)
  1046. return
  1047. }
  1048. slList, err := tx.SQL(` select sum(de.lweight)lweight,sum(de.actualweightminus)actualweightminus ,
  1049. 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,
  1050. ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) correct,
  1051. IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0)),0) correctcount,
  1052. 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
  1053. from downloadedplan d
  1054. join downloadplandtl2 de on de.pid = d.id
  1055. where d.times = ? and d.mydate = ? and lpplantype in(0,2) group by d.times `, item["times"], now).Query().List()
  1056. if err != nil {
  1057. logs.Error("endOfShift-error-4:", err)
  1058. return
  1059. }
  1060. data := make(map[string]interface{})
  1061. for _, hl := range hlList {
  1062. data["cltrains"] = hl["cltrains"]
  1063. // data["hllweight"] = hl["lweight"]
  1064. data["hlactualweightminus"] = hl["actualweightminus"]
  1065. data["hlaccurate"] = hl["accurate"]
  1066. data["hlcorrect"] = hl["correct"]
  1067. data["hlcorrectcount"] = hl["correctcount"]
  1068. // data["hlprocesstime"] = util.TimeTransformation(hl["processtime"].(int64))
  1069. data["hlwcz"] = hl["wcz"]
  1070. }
  1071. for _, sl := range slList {
  1072. // data["sllweight"] = sl["lweight"]
  1073. data["slactualweightminus"] = sl["actualweightminus"]
  1074. data["slaccurate"] = sl["accurate"]
  1075. data["slcorrect"] = sl["correct"]
  1076. data["slcorrectcount"] = sl["correctcount"]
  1077. // data["slprocesstime"] = util.TimeTransformation(sl["processtime"].(int64))
  1078. data["slwcz"] = sl["wcz"]
  1079. }
  1080. 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",
  1081. item["times"], data["cltrains"], data["hlactualweightminus"], data["hlwcz"], data["hlaccurate"], data["hlcorrect"], data["hlcorrectcount"],
  1082. data["slactualweightminus"], data["slwcz"], data["slaccurate"], data["slcorrect"], data["slcorrectcount"])
  1083. var sendList []interface{}
  1084. sendMap1 := make(map[string]interface{}, 0)
  1085. sendMap1["value"] = "班次完成"
  1086. sendMap1["color"] = "#173177"
  1087. sendList = append(sendList, sendMap1)
  1088. sendMap4 := make(map[string]interface{}, 0)
  1089. sendMap4["value"] = sendStr
  1090. sendMap4["color"] = "#173177"
  1091. sendList = append(sendList, sendMap4)
  1092. sendMap2 := make(map[string]interface{}, 0)
  1093. // sendMap2["value"] = plan["processtime"]
  1094. sendMap2["value"] = time.Now().Format("2006-01-02 15:04:05")
  1095. sendMap2["color"] = "#173177"
  1096. sendList = append(sendList, sendMap2)
  1097. sendMap5 := make(map[string]interface{}, 0)
  1098. sendMap5["value"] = "无备注"
  1099. sendMap5["color"] = "#173177"
  1100. sendList = append(sendList, sendMap5)
  1101. wxPush(target, sendList, pastureId, serviceId)
  1102. _, err = tx.SQL(` update downloadedplan_log set classes = 1 where date = ? and times = ? `, now, item["times"]).Execute()
  1103. if err != nil {
  1104. logs.Error("endOfShift-error-5:", err)
  1105. return
  1106. }
  1107. }
  1108. }
  1109. }
  1110. func plansToComplete(target []string, pastureId string, serviceId int64) {
  1111. tx := restful.Engine.NewSession()
  1112. defer tx.Close()
  1113. now := time.Now()
  1114. exist, err := tx.SQL(` select id from downloadedplan_log where date = ? and dailyplan = 0 `, now).Exist()
  1115. if err != nil {
  1116. logs.Error("plansToComplete-error-1:", err)
  1117. return
  1118. }
  1119. if exist {
  1120. downloadedplanExist, err := tx.SQL(` select id from downloadedplan where mydate = ? and iscompleted = 0 and enable = 1 `, now).Exist()
  1121. if err != nil {
  1122. logs.Error("plansToComplete-error-2:", err)
  1123. return
  1124. }
  1125. if !downloadedplanExist {
  1126. 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,
  1127. sum(de.lweight)lweight,sum(de.actualweightminus)actualweightminus ,
  1128. 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,
  1129. ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) correct,
  1130. IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0)),0) correctcount,
  1131. 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
  1132. from downloadedplan d
  1133. join downloadplandtl1_exec de on de.pid = d.id
  1134. where d.mydate = ? and lpplantype in(0,1) group by d.mydate`, now, now).Query().List()
  1135. if err != nil {
  1136. logs.Error("plansToComplete-error-3:", err)
  1137. return
  1138. }
  1139. slList, err := tx.SQL(` select sum(de.lweight)lweight,sum(de.actualweightminus)actualweightminus ,
  1140. 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,
  1141. ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) correct,
  1142. IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0)),0) correctcount,
  1143. 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
  1144. from downloadedplan d
  1145. join downloadplandtl2 de on de.pid = d.id
  1146. where d.mydate = ? and lpplantype in(0,2) group by d.mydate `, now).Query().List()
  1147. if err != nil {
  1148. logs.Error("plansToComplete-error-4:", err)
  1149. return
  1150. }
  1151. data := make(map[string]interface{})
  1152. for _, hl := range hlList {
  1153. data["timescount"] = hl["timescount"]
  1154. data["cltrains"] = hl["cltrains"]
  1155. data["hllweight"] = hl["lweight"]
  1156. data["hlactualweightminus"] = hl["actualweightminus"]
  1157. data["hlaccurate"] = hl["accurate"]
  1158. data["hlcorrect"] = hl["correct"]
  1159. data["hlcorrectcount"] = hl["correctcount"]
  1160. data["hlwcz"] = hl["wcz"]
  1161. }
  1162. for _, sl := range slList {
  1163. data["sllweight"] = sl["lweight"]
  1164. data["slactualweightminus"] = sl["actualweightminus"]
  1165. data["slaccurate"] = sl["accurate"]
  1166. data["slcorrect"] = sl["correct"]
  1167. data["slcorrectcount"] = sl["correctcount"]
  1168. data["slwcz"] = sl["wcz"]
  1169. }
  1170. 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",
  1171. data["timescount"], data["cltrains"], data["hlactualweightminus"], data["hlwcz"], data["hlaccurate"], data["hlcorrect"], data["hlcorrectcount"],
  1172. data["slactualweightminus"], data["slwcz"], data["slaccurate"], data["slcorrect"], data["slcorrectcount"])
  1173. var sendList []interface{}
  1174. sendMap1 := make(map[string]interface{}, 0)
  1175. sendMap1["value"] = "每日计划完成"
  1176. sendMap1["color"] = "#173177"
  1177. sendList = append(sendList, sendMap1)
  1178. sendMap4 := make(map[string]interface{}, 0)
  1179. sendMap4["value"] = sendStr
  1180. sendMap4["color"] = "#173177"
  1181. sendList = append(sendList, sendMap4)
  1182. sendMap2 := make(map[string]interface{}, 0)
  1183. // sendMap2["value"] = plan["processtime"]
  1184. sendMap2["value"] = time.Now().Format("2006-01-02 15:04:05")
  1185. sendMap2["color"] = "#173177"
  1186. sendList = append(sendList, sendMap2)
  1187. sendMap5 := make(map[string]interface{}, 0)
  1188. sendMap5["value"] = "无备注"
  1189. sendMap5["color"] = "#173177"
  1190. sendList = append(sendList, sendMap5)
  1191. wxPush(target, sendList, pastureId, serviceId)
  1192. _, err = tx.SQL(` update downloadedplan_log set dailyplan = 1 where date = ? `, now).Execute()
  1193. if err != nil {
  1194. logs.Error("plansToComplete-error-5:", err)
  1195. return
  1196. }
  1197. }
  1198. }
  1199. }
  1200. func AddFormulaIssued(c *gin.Context) {
  1201. appG := app.Gin{C: c}
  1202. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1203. tempval_ := make(map[string]interface{})
  1204. tempCommon := make(map[string]interface{})
  1205. tempval := make([]map[string]interface{}, 0)
  1206. err := json.Unmarshal(dataByte, &tempval_)
  1207. logging.Info("AddFormulaIssued ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1208. if err != nil {
  1209. } else {
  1210. if v, ok := tempval_["data"].([]interface{}); ok {
  1211. for _, Tvalue := range v {
  1212. if v1, ok := Tvalue.(map[string]interface{}); ok {
  1213. tempval = append(tempval, v1)
  1214. }
  1215. }
  1216. }
  1217. tx := restful.Engine.NewSession()
  1218. err := tx.Begin()
  1219. if err != nil {
  1220. logging.Error("tx.Begin 事务启动失败__error:", err)
  1221. }
  1222. defer func() {
  1223. switch {
  1224. case err != nil:
  1225. if tx != nil {
  1226. tx.Rollback()
  1227. }
  1228. default:
  1229. if tx != nil {
  1230. err = tx.Commit()
  1231. }
  1232. }
  1233. if tx != nil {
  1234. tx.Close()
  1235. }
  1236. }()
  1237. if err == nil {
  1238. if tempv, exists := c.Get("jwt_username"); exists {
  1239. tempCommon["jwt_username"] = tempv.(string)
  1240. }
  1241. for _, paramvalue := range tempval {
  1242. if _, ok := paramvalue["resultname"]; !ok {
  1243. paramvalue["resultname"] = paramvalue["name"]
  1244. }
  1245. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  1246. if err != nil {
  1247. logging.Error("AddFormulaIssued error-1:", err)
  1248. break
  1249. }
  1250. }
  1251. if err == nil {
  1252. var temid, jtpastureid, tcode, tname, ccname, fttype string
  1253. for _, tem := range tempval {
  1254. if tem["name"].(string) == "insertSpotList" {
  1255. for _, item := range tem["resultmaps"].(map[string]interface{})["list"].([]interface{}) {
  1256. itemmap := item.(map[string]interface{})
  1257. jtpastureid = itemmap["pastureid"].(string)
  1258. temid = itemmap["id"].(string)
  1259. }
  1260. }
  1261. }
  1262. feedtempletList, err := tx.SQL(` select tname,tcode,id,ccname,fttype from feedtemplet where id = ? and pastureid = ? `, temid, jtpastureid).Query().List()
  1263. if err != nil {
  1264. logs.Error("AddFormulaIssued-error-2:", err)
  1265. return
  1266. }
  1267. for _, feedtemplet := range feedtempletList {
  1268. tcode = feedtemplet["tcode"].(string)
  1269. tname = feedtemplet["tname"].(string)
  1270. ccname = feedtemplet["ccname"].(string)
  1271. fttype = feedtemplet["fttype"].(string)
  1272. }
  1273. for _, tem := range tempval {
  1274. if tem["name"].(string) == "insertSpotList2" {
  1275. for _, item := range tem["resultmaps"].(map[string]interface{})["list"].([]interface{}) {
  1276. itemmap := item.(map[string]interface{})
  1277. dataList, err := tx.SQL(` select user,function,id,service_id from remind where pastureid = ? and function = ? `, itemmap["id"], "formulaIssued").Query().List()
  1278. if err != nil {
  1279. logs.Error("AddFormulaIssued-error-3:", err)
  1280. return
  1281. }
  1282. for _, data := range dataList {
  1283. var openIdList []string
  1284. if _, ok := data["user"]; ok {
  1285. openIdList = strings.Split(data["user"].(string), ",")
  1286. }
  1287. var sendList []interface{}
  1288. sendStr := fmt.Sprintf("配方名称:%v\n配方编码:%s\n牲畜类别:%v\n配方类型:%v",
  1289. tname, tcode, ccname, fttype)
  1290. sendMap1 := make(map[string]interface{}, 0)
  1291. sendMap1["value"] = "混料准确率异常"
  1292. sendMap1["color"] = "#173177"
  1293. sendList = append(sendList, sendMap1)
  1294. sendMap4 := make(map[string]interface{}, 0)
  1295. sendMap4["value"] = sendStr
  1296. sendMap4["color"] = "#173177"
  1297. sendList = append(sendList, sendMap4)
  1298. sendMap2 := make(map[string]interface{}, 0)
  1299. sendMap2["value"] = time.Now().Format("2006-01-02 15:04:05")
  1300. sendMap2["color"] = "#173177"
  1301. sendList = append(sendList, sendMap2)
  1302. sendMap5 := make(map[string]interface{}, 0)
  1303. sendMap5["value"] = "无备注"
  1304. sendMap5["color"] = "#173177"
  1305. sendList = append(sendList, sendMap5)
  1306. wxPush(openIdList, sendList, itemmap["id"].(string), data["service_id"].(int64))
  1307. }
  1308. }
  1309. break
  1310. }
  1311. }
  1312. if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
  1313. appG.Response(http.StatusOK, e.SUCCESS, tempval)
  1314. } else {
  1315. appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
  1316. }
  1317. } else {
  1318. msg := geterrmsg(err.Error())
  1319. appG.Response(http.StatusOK, e.ERROR, msg)
  1320. }
  1321. }
  1322. }
  1323. if err != nil {
  1324. msg := geterrmsg(err.Error())
  1325. appG.Response(http.StatusOK, e.ERROR, msg)
  1326. appG.Response(http.StatusOK, 200, nil)
  1327. }
  1328. }
  1329. func AddBigInventory(c *gin.Context) {
  1330. appG := app.Gin{C: c}
  1331. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1332. tempval_ := make(map[string]interface{})
  1333. tempCommon := make(map[string]interface{})
  1334. tempval := make([]map[string]interface{}, 0)
  1335. err := json.Unmarshal(dataByte, &tempval_)
  1336. logging.Info("AddBigInventory ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1337. if err != nil {
  1338. } else {
  1339. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  1340. tempCommon = v
  1341. }
  1342. if v, ok := tempval_["data"].([]interface{}); ok {
  1343. for _, Tvalue := range v {
  1344. if v1, ok := Tvalue.(map[string]interface{}); ok {
  1345. tempval = append(tempval, v1)
  1346. }
  1347. }
  1348. }
  1349. tx := restful.Engine.NewSession()
  1350. err := tx.Begin()
  1351. if err != nil {
  1352. logging.Error("tx.Begin 事务启动失败__error:", err)
  1353. }
  1354. defer func() {
  1355. switch {
  1356. case err != nil:
  1357. if tx != nil {
  1358. tx.Rollback()
  1359. }
  1360. default:
  1361. if tx != nil {
  1362. err = tx.Commit()
  1363. }
  1364. }
  1365. if tx != nil {
  1366. tx.Close()
  1367. }
  1368. }()
  1369. if err == nil {
  1370. if tempv, exists := c.Get("jwt_username"); exists {
  1371. tempCommon["jwt_username"] = tempv.(string)
  1372. }
  1373. for _, paramvalue := range tempval {
  1374. if _, ok := paramvalue["resultname"]; !ok {
  1375. paramvalue["resultname"] = paramvalue["name"]
  1376. }
  1377. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  1378. if err != nil {
  1379. logging.Error("AddBigInventory error-1:", err)
  1380. break
  1381. }
  1382. }
  1383. if err == nil {
  1384. var pastureid, date string
  1385. for _, tem := range tempval {
  1386. if tem["name"].(string) == "insertBigInventory" {
  1387. parammaps := tem["parammaps"].(map[string]interface{})
  1388. pastureid = parammaps["pastureid"].(string)
  1389. date = parammaps["inventorydate"].(string)
  1390. }
  1391. }
  1392. feedinventoryList, err := tx.SQL(`SELECT
  1393. remark,DATE_FORMAT(inventorydate, '%Y-%m-%d') inventorydate,createuser,
  1394. TRIM(f.id) id,
  1395. TRIM(f.pastureid) pastureid,
  1396. 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,
  1397. 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 ,
  1398. 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
  1399. FROM
  1400. feedinventory f
  1401. WHERE f.pastureid = ? and f.inventorydate=? `, pastureid, date).Query().List()
  1402. if err != nil {
  1403. logs.Error("AddBigInventory-error-2:", err)
  1404. return
  1405. }
  1406. dataList, err := tx.SQL(` select user,function,id,service_id from remind where pastureid = ? and function = ? `, pastureid, "formulaIssued").Query().List()
  1407. if err != nil {
  1408. logs.Error("AddBigInventory-error-3:", err)
  1409. return
  1410. }
  1411. for _, data := range dataList {
  1412. var openIdList []string
  1413. if _, ok := data["user"]; ok {
  1414. openIdList = strings.Split(data["user"].(string), ",")
  1415. }
  1416. var createuser, lessWeight, moreWeight, differWeight interface{}
  1417. for _, f := range feedinventoryList {
  1418. createuser = f["createuser"]
  1419. lessWeight = f["lessWeight"]
  1420. moreWeight = f["moreWeight"]
  1421. differWeight = f["differWeight"]
  1422. }
  1423. var sendList []interface{}
  1424. sendStr := fmt.Sprintf("盘点人:%v\n盘盈库存(kg):%v\n盘亏库存(kg):%v\n盈亏净值(kg):%v",
  1425. createuser, moreWeight, lessWeight, differWeight)
  1426. sendMap1 := make(map[string]interface{}, 0)
  1427. sendMap1["value"] = "库存盘点"
  1428. sendMap1["color"] = "#173177"
  1429. sendList = append(sendList, sendMap1)
  1430. sendMap4 := make(map[string]interface{}, 0)
  1431. sendMap4["value"] = sendStr
  1432. sendMap4["color"] = "#173177"
  1433. sendList = append(sendList, sendMap4)
  1434. sendMap2 := make(map[string]interface{}, 0)
  1435. sendMap2["value"] = time.Now().Format("2006-01-02 15:04:05")
  1436. sendMap2["color"] = "#173177"
  1437. sendList = append(sendList, sendMap2)
  1438. sendMap5 := make(map[string]interface{}, 0)
  1439. sendMap5["value"] = "无备注"
  1440. sendMap5["color"] = "#173177"
  1441. sendList = append(sendList, sendMap5)
  1442. wxPush(openIdList, sendList, pastureid, data["service_id"].(int64))
  1443. }
  1444. if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
  1445. appG.Response(http.StatusOK, e.SUCCESS, tempval)
  1446. } else {
  1447. appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
  1448. }
  1449. } else {
  1450. msg := geterrmsg(err.Error())
  1451. appG.Response(http.StatusOK, e.ERROR, msg)
  1452. }
  1453. }
  1454. }
  1455. if err != nil {
  1456. msg := geterrmsg(err.Error())
  1457. appG.Response(http.StatusOK, e.ERROR, msg)
  1458. }
  1459. }
  1460. func inventoryWarning(target []string, pastureId string, serviceId int64) {
  1461. tx := restful.Engine.NewSession()
  1462. defer tx.Close()
  1463. feedstorageList, err := tx.SQL(`
  1464. SELECT
  1465. (select fname from feed where pastureid =fs.pastureid and id = fs.feedid ) feedname,
  1466. fs.stockweight,round(fs.lweight,2) avgweight, if (fs.stockweight<=0,0, FLOOR(fs.stockweight/fs.lweight)) ldays,
  1467. TRIM(fs.feedid) feedid,
  1468. TRIM(fs.pastureid) pastureid,
  1469. DATE_FORMAT((select max(date) from fswarnhis where pastureid = fs.pastureid and feedid = fs.feedid ), '%Y-%m-%d') lastdate
  1470. FROM (SELECT fs.pushstatus,
  1471. fs.id,
  1472. fs.feedname,fs.stockweight,
  1473. fs.feedid feedid,
  1474. fs.pastureid pastureid,DATE_FORMAT(NOW(), '%Y-%m-%d') lastdate,
  1475. (SELECT SUM(d.lweight)/7 lweight FROM downloadplandtl1 d WHERE d.pastureid = fs.pastureid
  1476. AND date >= DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -7 DAY), '%Y-%m-%d')
  1477. AND date <DATE_FORMAT(NOW(), '%Y-%m-%d') AND d.fid = fs.feedid) lweight
  1478. FROM feedstorage fs) fs
  1479. WHERE fs.pastureid=? AND fs.stockweight< fs.lweight*(SELECT inforvalue FROM sysopt WHERE sysopt.pastureid = fs.pastureid
  1480. AND inforname = 'repertoryWarn')
  1481. ORDER BY ldays ,stockweight `).Query().List()
  1482. if err != nil {
  1483. logs.Error("inventoryWarning-error-1:", err)
  1484. return
  1485. }
  1486. for _, f := range feedstorageList {
  1487. var sendList []interface{}
  1488. sendStr := fmt.Sprintf("饲料名称:%v\n库存量(kg):%s\n近7天平均计划量:%v\n剩余使用天数:%v",
  1489. f["feedname"], f["stockweight"], f["lweight"], f["ldays"])
  1490. sendMap1 := make(map[string]interface{}, 0)
  1491. sendMap1["value"] = "库存预警"
  1492. sendMap1["color"] = "#173177"
  1493. sendList = append(sendList, sendMap1)
  1494. sendMap4 := make(map[string]interface{}, 0)
  1495. sendMap4["value"] = sendStr
  1496. sendMap4["color"] = "#173177"
  1497. sendList = append(sendList, sendMap4)
  1498. sendMap2 := make(map[string]interface{}, 0)
  1499. sendMap2["value"] = time.Now().Format("2006-01-02 15:04:05")
  1500. sendMap2["color"] = "#173177"
  1501. sendList = append(sendList, sendMap2)
  1502. sendMap5 := make(map[string]interface{}, 0)
  1503. sendMap5["value"] = "无备注"
  1504. sendMap5["color"] = "#173177"
  1505. sendList = append(sendList, sendMap5)
  1506. wxPush(target, sendList, pastureId, serviceId)
  1507. }
  1508. }