scheduled.go 62 KB

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