scheduled.go 61 KB

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