scheduled.go 62 KB

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