scheduled.go 60 KB

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