scheduled.go 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372
  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/restful"
  20. "github.com/Anderson-Lu/gofasion/gofasion"
  21. "github.com/astaxie/beego/logs"
  22. "github.com/gin-gonic/gin"
  23. "github.com/robfig/cron"
  24. "github.com/xormplus/xorm"
  25. )
  26. func CronScheduled(ctx context.Context) {
  27. tx := restful.Engine.NewSession()
  28. defer tx.Close()
  29. pastureinfo := new(udPastureInfo)
  30. err := tx.SQL(`select column_default as pastureid from information_schema.COLUMNS
  31. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  32. if err != nil {
  33. logs.Error(err)
  34. return
  35. }
  36. duetimecst, _ := time.ParseInLocation("15:04:05", "00:10:00", time.Local)
  37. duetimecst1, _ := time.ParseInLocation("15:04:05", "00:00:00", time.Local)
  38. spec := fmt.Sprintf("@every %v", duetimecst.Sub(duetimecst1))
  39. c := cron.New()
  40. c.AddFunc(spec, func() {
  41. tx1 := restful.Engine.NewSession()
  42. defer tx1.Close()
  43. exist, err := tx1.Table("notice").Where("status = 1").And("content = ? ", "downloadedplan_log").Exist()
  44. if err != nil {
  45. logs.Error("CronScheduled-error-1:", err)
  46. return
  47. }
  48. if exist {
  49. _, err := tx.SQL(`update notice set status = 0 where content = ? `, "downloadedplan_log").Execute()
  50. if err != nil {
  51. logs.Error("CronScheduled-error-2:", err)
  52. return
  53. }
  54. Scheduled(ctx, tx1, pastureinfo)
  55. }
  56. })
  57. c.Start()
  58. duetimecst2, _ := time.ParseInLocation("15:04:05", "00:01:00", time.Local)
  59. duetimecst3, _ := time.ParseInLocation("15:04:05", "00:00:00", time.Local)
  60. spec1 := fmt.Sprintf("@every %v", duetimecst2.Sub(duetimecst3))
  61. downloadplandtl1 := cron.New()
  62. downloadplandtl1.AddFunc(spec1, func() {
  63. dataList, err := tx.SQL(` select user,function,id from remind where pastureid = ? `, pastureinfo.Pastureid).Query().List()
  64. if err != nil {
  65. logs.Error("CronScheduled-error-3:", err)
  66. return
  67. }
  68. for _, data := range dataList {
  69. if data["function"].(string) == "processAnalysisEarlyWarning" {
  70. // user := strings.Split(data["user"].(string), ",")
  71. if len(data["user"].(string)) > 0 {
  72. var userids string
  73. for _, str := range strings.Split(data["user"].(string), ",") {
  74. if len(userids) <= 0 {
  75. userids = fmt.Sprintf("'%s'", str)
  76. } else {
  77. userids += fmt.Sprintf(",'%s'", str)
  78. }
  79. }
  80. sql := fmt.Sprintf(` select openid from user_wx where pastureid = ? and userid in(%s)`, userids)
  81. openidList, err := tx.SQL(sql, pastureinfo.Pastureid).Query().List()
  82. // openidList, err := tx.Table("user_wx").Where(" pastureid = ? ", pastureinfo.Pastureid).And("userid in (?)", data["user"].(string)).Query().List()
  83. if err != nil {
  84. logs.Error("CronScheduled-error-4:", err)
  85. return
  86. }
  87. var openIdList []string
  88. for _, open := range openidList {
  89. if open["openid"] != nil {
  90. openIdList = append(openIdList, open["openid"].(string))
  91. }
  92. }
  93. if len(openIdList) > 0 {
  94. processAnalysisEarlyWarning(openIdList, pastureinfo.Pastureid, data["id"].(int64))
  95. }
  96. }
  97. } else if data["function"].(string) == "abnormalMixingDelay" {
  98. if data["user"] != nil {
  99. var userids string
  100. for _, str := range strings.Split(data["user"].(string), ",") {
  101. if len(userids) <= 0 {
  102. userids = fmt.Sprintf("'%s'", str)
  103. } else {
  104. userids += fmt.Sprintf(",'%s'", str)
  105. }
  106. }
  107. sql := fmt.Sprintf(` select openid from user_wx where pastureid = ? and userid in(%s)`, userids)
  108. openidList, err := tx.SQL(sql, pastureinfo.Pastureid).Query().List()
  109. // openidList, err := tx.Table("user_wx").Where(" pastureid = ? ", pastureinfo.Pastureid).And("userid in (?)", data["user"].(string)).Query().List()
  110. if err != nil {
  111. logs.Error("CronScheduled-error-4:", err)
  112. return
  113. }
  114. var openIdList []string
  115. for _, open := range openidList {
  116. if open["openid"] != nil {
  117. openIdList = append(openIdList, open["openid"].(string))
  118. }
  119. }
  120. if len(openIdList) > 0 {
  121. abnormalMixingDelay(openIdList, pastureinfo.Pastureid, data["id"].(int64))
  122. }
  123. }
  124. } else if data["function"].(string) == "endOfShift" {
  125. if data["user"] != nil {
  126. var userids string
  127. for _, str := range strings.Split(data["user"].(string), ",") {
  128. if len(userids) <= 0 {
  129. userids = fmt.Sprintf("'%s'", str)
  130. } else {
  131. userids += fmt.Sprintf(",'%s'", str)
  132. }
  133. }
  134. sql := fmt.Sprintf(` select openid from user_wx where pastureid = ? and userid in(%s)`, userids)
  135. openidList, err := tx.SQL(sql, pastureinfo.Pastureid).Query().List()
  136. // openidList, err := tx.Table("user_wx").Where(" pastureid = ? ", pastureinfo.Pastureid).And("userid in (?)", data["user"].(string)).Query().List()
  137. if err != nil {
  138. logs.Error("CronScheduled-error-4:", err)
  139. return
  140. }
  141. var openIdList []string
  142. for _, open := range openidList {
  143. if open["openid"] != nil {
  144. openIdList = append(openIdList, open["openid"].(string))
  145. }
  146. }
  147. if len(openIdList) > 0 {
  148. endOfShift(openIdList, pastureinfo.Pastureid, data["id"].(int64))
  149. }
  150. }
  151. } else if data["function"].(string) == "plansToComplete" {
  152. if data["user"] != nil {
  153. var userids string
  154. for _, str := range strings.Split(data["user"].(string), ",") {
  155. if len(userids) <= 0 {
  156. userids = fmt.Sprintf("'%s'", str)
  157. } else {
  158. userids += fmt.Sprintf(",'%s'", str)
  159. }
  160. }
  161. sql := fmt.Sprintf(` select openid from user_wx where pastureid = ? and userid in(%s)`, userids)
  162. openidList, err := tx.SQL(sql, pastureinfo.Pastureid).Query().List()
  163. // openidList, err := tx.Table("user_wx").Where(" pastureid = ? ", pastureinfo.Pastureid).And("userid in (?)", data["user"].(string)).Query().List()
  164. if err != nil {
  165. logs.Error("CronScheduled-error-4:", err)
  166. return
  167. }
  168. var openIdList []string
  169. for _, open := range openidList {
  170. if open["openid"] != nil {
  171. openIdList = append(openIdList, open["openid"].(string))
  172. }
  173. }
  174. if len(openIdList) > 0 {
  175. plansToComplete(openIdList, pastureinfo.Pastureid, data["id"].(int64))
  176. }
  177. }
  178. }
  179. }
  180. })
  181. downloadplandtl1.Start()
  182. //自动同步前天有进行中的任务
  183. manualUdData(pastureinfo)
  184. }
  185. type ScheduledInfo struct {
  186. Id int64 `xorm:"id"`
  187. Sname string `xorm:"sname"`
  188. Action int64 `xorm:"action"`
  189. Childid int64 `xorm:"childid"`
  190. Times string `xorm:"times"`
  191. Enable string `xorm:"enable"`
  192. }
  193. type ScheduledUpInfo struct {
  194. Id int64 `xorm:"id"`
  195. Company string `xorm:"company"`
  196. Addres string `xorm:"addres"`
  197. Datatype int64 `xorm:"datatype"`
  198. Package string `xorm:"Package"`
  199. Datasql string `xorm:"datasql"`
  200. Automatic int64 `xorm:"automatic"`
  201. Manual int64 `xorm:"manual"`
  202. Targetdata string `xorm:"targetdata"`
  203. }
  204. type ScheduledDownInfo struct {
  205. Id int64 `xorm:"id"`
  206. Datatype int64 `xorm:"datatype"`
  207. Addres string `xorm:"addres"`
  208. Adressparam string `xorm:"adressparam"`
  209. Targetdata string `xorm:"targetdata"`
  210. Manual int64 `xorm:"manual"`
  211. Methods string `xorm:"methods"`
  212. }
  213. type ScheduledDownChildInfo struct {
  214. Id int64 `xorm:"id"`
  215. Parentid int64 `xorm:"parentid"`
  216. Fieldname string `xorm:"fieldname"`
  217. Checksql string `xorm:"checksql"`
  218. Dosql string `xorm:"dosql"`
  219. }
  220. func Scheduled(ctx context.Context, tx *xorm.Session, pastureinfo *udPastureInfo) {
  221. times := new(ScheduledInfo)
  222. err := tx.SQL(" select times from scheduled where action = 0 group by times").GetFirst(times).Error
  223. if err != nil {
  224. logs.Error(err)
  225. return
  226. }
  227. if times.Times == "0" {
  228. downloadedplanLogList, err := tx.SQL(` select id from downloadedplan_log where date = date_format(now(),'%Y-%m-%d') `).Query().List()
  229. if err != nil {
  230. logs.Error(err)
  231. return
  232. }
  233. ids := []string{}
  234. for _, item := range downloadedplanLogList {
  235. ids = append(ids, strconv.FormatInt(item["id"].(int64), 10))
  236. }
  237. fmt.Println(ids, time.Now())
  238. err = UpdatePush(ctx, tx, true, ids, pastureinfo, "", time.Now().Format("2006-01-02"))
  239. if err != nil {
  240. return
  241. }
  242. } else if times.Times == "1" {
  243. 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()
  244. if err != nil {
  245. logs.Error(err)
  246. return
  247. }
  248. for _, item := range downloadedplanLogList {
  249. count, err := tx.SQL(` select count(1) from downloadedplan where pastureid = ? and mydate = date_format(now(),'%Y-%m-%d')
  250. and iscompleted = 0 and times = ? and enable = 1 `,
  251. pastureinfo.Pastureid, item["times"]).Count()
  252. if err != nil {
  253. logs.Error(err)
  254. return
  255. }
  256. if count == 0 {
  257. //推送
  258. downloadedplanLogList, err := tx.SQL(` select id from downloadedplan_log where date = date_format(now(),'%Y-%m-%d')
  259. and times = ? `, item["times"]).Query().List()
  260. if err != nil {
  261. logs.Error(err)
  262. return
  263. }
  264. ids := []string{}
  265. for _, item := range downloadedplanLogList {
  266. ids = append(ids, strconv.FormatInt(item["id"].(int64), 10))
  267. }
  268. err = UpdatePush(ctx, tx, true, ids, pastureinfo, "", time.Now().Format("2006-01-02"))
  269. if err != nil {
  270. return
  271. }
  272. }
  273. }
  274. } else if times.Times == "2" {
  275. 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 ",
  276. pastureinfo.Pastureid).Count()
  277. if err != nil {
  278. logs.Error(err)
  279. return
  280. }
  281. if count == 0 {
  282. //推送
  283. downloadedplanLogList, err := tx.SQL(` select id from downloadedplan_log where date = date_format(now(),'%Y-%m-%d') `).Query().List()
  284. if err != nil {
  285. logs.Error(err)
  286. return
  287. }
  288. ids := []string{}
  289. for _, item := range downloadedplanLogList {
  290. ids = append(ids, strconv.FormatInt(item["id"].(int64), 10))
  291. }
  292. err = UpdatePush(ctx, tx, true, ids, pastureinfo, "", time.Now().Format("2006-01-02"))
  293. if err != nil {
  294. return
  295. }
  296. }
  297. }
  298. }
  299. func UpdateScheduledStatus(c *gin.Context) {
  300. appG := app.Gin{C: c}
  301. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  302. fsion := gofasion.NewFasion(string(dataByte))
  303. idList := fsion.Get("id").Array()
  304. automatic := fsion.Get("automatic").ValueStr()
  305. manual := fsion.Get("manual").ValueStr()
  306. company := fsion.Get("company").ValueStr()
  307. //type 0 上传,1 下载
  308. typee := fsion.Get("type").ValueStr()
  309. ids := []string{}
  310. for _, item := range idList {
  311. ids = append(ids, item.ValueStr())
  312. }
  313. tx := restful.Engine.NewSession()
  314. defer tx.Close()
  315. tx.Begin()
  316. sqlstr := ""
  317. sqlstr1 := ""
  318. // var args []interface{}
  319. if typee == "0" {
  320. if len(ids) > 0 {
  321. sqlstr = `update scheduled s join scheduled_up su on su.id = s.childid set `
  322. sqlstr1 = `update scheduled s join scheduled_up su on su.id = s.childid set `
  323. if automatic != "" {
  324. sqlstr += " su.automatic = 1 "
  325. sqlstr1 += " su.automatic = 0 "
  326. } else if manual != "" {
  327. sqlstr += " su.manual = 1 "
  328. sqlstr1 += " su.manual = 0 "
  329. }
  330. id := strings.Join(ids, ",")
  331. sqlstr += fmt.Sprintf(" where s.id in (%s) and s.action = 0 and su.company = '%s' ", id, company)
  332. sqlstr1 += fmt.Sprintf(" where s.id not in (%s) and s.action = 0 and su.company ='%s' ", id, company)
  333. } else {
  334. sqlstr = `update scheduled s join scheduled_up su on su.id = s.childid set `
  335. if automatic != "" {
  336. sqlstr += " su.automatic = 0 "
  337. } else if manual != "" {
  338. sqlstr += " su.manual = 0 "
  339. }
  340. sqlstr += fmt.Sprintf(" where s.action = 0 and su.company = '%s' ", company)
  341. }
  342. } else {
  343. if len(ids) > 0 {
  344. sqlstr = `update scheduled s join scheduled_down sd on sd.id = s.childid set `
  345. sqlstr1 = `update scheduled s join scheduled_down sd on sd.id = s.childid set `
  346. sqlstr += " sd.manual = 1 "
  347. sqlstr1 += " sd.manual = 0 "
  348. id := strings.Join(ids, ",")
  349. sqlstr += fmt.Sprintf(" where s.id in (%s) and s.action = 1 and sd.company = '%s' ", id, company)
  350. sqlstr1 += fmt.Sprintf(" where s.id not in (%s) and s.action = 1 and sd.company = '%s' ", id, company)
  351. } else {
  352. sqlstr = `update scheduled s join scheduled_down sd on sd.id = s.childid set `
  353. sqlstr += " sd.manual = 0 "
  354. sqlstr += fmt.Sprintf(" where s.action = 1 and sd.company = '%s' ", company)
  355. }
  356. }
  357. _, err := tx.SQL(sqlstr).Execute()
  358. if err != nil {
  359. log.Println("UpdateScheduledStatus-error-1: ", err)
  360. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  361. tx.Rollback()
  362. }
  363. if len(sqlstr1) > 0 {
  364. _, err = tx.SQL(sqlstr1).Execute()
  365. if err != nil {
  366. log.Println("UpdateScheduledStatus-error-2: ", err)
  367. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  368. tx.Rollback()
  369. }
  370. }
  371. err = tx.Commit()
  372. if err != nil {
  373. log.Println("UpdateScheduledStatus-error-3: ", err)
  374. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  375. tx.Rollback()
  376. }
  377. appG.Response(http.StatusOK, e.SUCCESS, true)
  378. }
  379. func SynchronizeNow(c *gin.Context) {
  380. appG := app.Gin{C: c}
  381. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  382. fsion := gofasion.NewFasion(string(dataByte))
  383. company := fsion.Get("company").ValueStr()
  384. date := fsion.Get("date").ValueStr()
  385. tx := restful.Engine.NewSession()
  386. defer tx.Close()
  387. pastureinfo := new(udPastureInfo)
  388. err := tx.SQL(`select column_default as pastureid from information_schema.COLUMNS
  389. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  390. if err != nil {
  391. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  392. return
  393. }
  394. dataList, err := tx.SQL(`select id from downloadedplan_log where date = date_format(?,'%Y-%m-%d') `, date).Query().List()
  395. if err != nil {
  396. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  397. return
  398. }
  399. var idList []string
  400. for _, data := range dataList {
  401. idList = append(idList, strconv.FormatInt(data["id"].(int64), 10))
  402. }
  403. err = UpdatePush(c, tx, false, idList, pastureinfo, company, date)
  404. if err != nil {
  405. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  406. return
  407. }
  408. UpdateDown(c, tx, nil, pastureinfo, company)
  409. if err != nil {
  410. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  411. return
  412. }
  413. appG.Response(http.StatusOK, e.SUCCESS, true)
  414. }
  415. func UpdatePush(ctx context.Context, tx *xorm.Session, auto bool, idList []string, pastureinfo *udPastureInfo, company, date string) error {
  416. upList := make([]*ScheduledUpInfo, 0)
  417. up := tx.Table("scheduled_up")
  418. if company != "" {
  419. up.Where("company = ? ", company)
  420. }
  421. if auto {
  422. up.Where("automatic = 1")
  423. } else {
  424. up.Where("manual = 1")
  425. }
  426. err := up.Find(&upList)
  427. if err != nil {
  428. log.Println("UpdataPush-error-1: ", err)
  429. return err
  430. }
  431. for _, item := range upList {
  432. if item.Datasql != "" {
  433. if item.Datatype == 3 || item.Datatype == 4 {
  434. targetdataList := strings.Split(item.Targetdata, ",")
  435. var args []interface{}
  436. for _, targetdata := range targetdataList {
  437. if targetdata == "pastureid" {
  438. args = append(args, pastureinfo.Pastureid)
  439. } else if targetdata == "idlist" {
  440. // args = append(args, strings.Join(idList, ","))
  441. item.Datasql = strings.ReplaceAll(item.Datasql, "idlist", strings.Join(idList, ","))
  442. } else if targetdata == "date" {
  443. args = append(args, date)
  444. }
  445. }
  446. fmt.Println(item.Datasql)
  447. data, err := tx.SQL(item.Datasql, args...).Query().List()
  448. if err != nil {
  449. log.Println("UpdataPush-error-2: ", err)
  450. continue
  451. }
  452. if len(data) > 0 {
  453. databyte, err := json.Marshal(data)
  454. if err != nil {
  455. log.Println("UpdataPush-error-3: ", err)
  456. continue
  457. }
  458. var method string
  459. if item.Datatype == 4 {
  460. method = "uploadnewdiliverdata"
  461. }
  462. UDPostPush1(fmt.Sprintf(item.Package, string(databyte), len(data)), method)
  463. }
  464. if len(idList) > 0 {
  465. _, err := tx.SQL(fmt.Sprintf(" update downloadedplan_log set status = 1 where id in (%s)", strings.Join(idList, ","))).Execute()
  466. if err != nil {
  467. log.Println("UpdataPush-error-4: ", err)
  468. continue
  469. }
  470. }
  471. } else {
  472. targetdataList := strings.Split(item.Targetdata, ",")
  473. var args []interface{}
  474. for _, targetdata := range targetdataList {
  475. if targetdata == "pastureid" {
  476. args = append(args, pastureinfo.Pastureid)
  477. } else if targetdata == "idlist" {
  478. // args = append(args, strings.Join(idList, ","))
  479. item.Datasql = strings.ReplaceAll(item.Datasql, "idlist", strings.Join(idList, ","))
  480. }
  481. }
  482. data, err := tx.SQL(item.Datasql, args...).Query().List()
  483. if err != nil {
  484. log.Println("UpdataPush-error-5: ", err)
  485. // return err
  486. }
  487. if len(data) > 0 {
  488. databyte, err := json.Marshal(data)
  489. if err != nil {
  490. log.Println("UpdataPush-error-6: ", err)
  491. // return err
  492. continue
  493. }
  494. // d, err := OpenFile("a.txt")
  495. // d.WriteString()
  496. // UDPostPush(fmt.Sprintf(item.Package, string(databyte), len(data)), "application/json")
  497. UDPostPush1(fmt.Sprintf(item.Package, string(databyte), len(data)), "")
  498. }
  499. }
  500. }
  501. }
  502. return nil
  503. }
  504. // OpenFile 判断文件是否存在 存在则OpenFile 不存在则Create
  505. func OpenFile(filename string) (*os.File, error) {
  506. if _, err := os.Stat(filename); os.IsNotExist(err) {
  507. fmt.Println("文件不存在")
  508. return os.Create(filename) //创建文件
  509. }
  510. fmt.Println("文件存在")
  511. return os.OpenFile(filename, os.O_APPEND, 0666) //打开文件
  512. }
  513. func UpdateDown(ctx context.Context, tx *xorm.Session, idList []string, pastureinfo *udPastureInfo, company string) error {
  514. downList := make([]*ScheduledDownInfo, 0)
  515. down := tx.Table("scheduled_down")
  516. if company != "" {
  517. down.Where("company = ? ", company)
  518. }
  519. down.Where("manual = 1")
  520. err := down.Find(&downList)
  521. if err != nil {
  522. log.Println("UpdateDown-error-1: ", err)
  523. return err
  524. }
  525. for _, item := range downList {
  526. list := httpGetMC(item.Addres, item.Targetdata)
  527. if item.Methods != "" {
  528. s := ScheduledDown{}
  529. value := reflect.ValueOf(&s)
  530. f := value.MethodByName(item.Methods)
  531. f.Call([]reflect.Value{reflect.ValueOf(pastureinfo.Pastureid), reflect.ValueOf(list)})
  532. // value := reflect.ValueOf(&s)
  533. // f := value.MethodByName("Ccaa")
  534. // f.Call([]reflect.Value{reflect.ValueOf(list)})
  535. } else {
  536. childList := make([]*ScheduledDownChildInfo, 0)
  537. child := tx.Table("scheduled_down")
  538. child.Where("parentid = ? ", item.Id)
  539. err = child.Find(&childList)
  540. if err != nil {
  541. log.Println("UpdateDown-error-2: ", err)
  542. return err
  543. }
  544. if len(childList) > 0 {
  545. tx.Begin()
  546. for _, c := range childList {
  547. fieldnames := strings.Split(c.Fieldname, ",")
  548. for _, data := range list {
  549. var args []interface{}
  550. dataMap := data.(map[string]interface{})
  551. for _, fieldname := range fieldnames {
  552. args = append(args, dataMap[fieldname])
  553. }
  554. _, err = tx.SQL(c.Dosql, args...).Execute()
  555. if err != nil {
  556. tx.Rollback()
  557. log.Println("UpdateDown-error-3: ", err)
  558. return err
  559. }
  560. }
  561. }
  562. err := tx.Commit()
  563. if err != nil {
  564. tx.Rollback()
  565. log.Println("UpdateDown-error-4: ", err)
  566. return err
  567. }
  568. }
  569. }
  570. }
  571. return nil
  572. }
  573. func httpGetMC(url, targetdata string) []interface{} {
  574. // url := fmt.Sprintf("https://wdc.unidairy.cn/copartner_downloads/?farmId=%s&method=%s", farmId, method)
  575. res, err := http.Get(url)
  576. if err != nil {
  577. return nil
  578. }
  579. robots, err := ioutil.ReadAll(res.Body)
  580. res.Body.Close()
  581. if err != nil {
  582. return nil
  583. }
  584. var data map[string][]interface{}
  585. json.Unmarshal(robots, &data)
  586. return data[targetdata]
  587. }
  588. type ScheduledDown struct {
  589. }
  590. func (h *ScheduledDown) SyncFeed(pastureid string, feedList []interface{}) {
  591. tx := restful.Engine.NewSession()
  592. defer tx.Close()
  593. err := tx.Begin()
  594. if err != nil {
  595. tx.Rollback()
  596. logs.Error("syncFeed-error-1:", err)
  597. return
  598. }
  599. for _, f := range feedList {
  600. feed := f.(map[string]interface{})
  601. var feedcode, fname, fclass, fclassid, dry interface{}
  602. if _, ok := feed["feedcode"]; ok {
  603. feedcode = feed["feedcode"]
  604. }
  605. if _, ok := feed["feedname"]; ok {
  606. fname = feed["feedname"]
  607. }
  608. if _, ok := feed["feedclass"]; ok {
  609. fclass = feed["feedclass"]
  610. }
  611. if _, ok := feed["drymatter"]; ok {
  612. dry = feed["drymatter"]
  613. }
  614. fclassExist, err := tx.SQL(" select id from feedclass where pastureid = ? and fcname = ?", pastureid, fclass).Exist()
  615. if err != nil {
  616. tx.Rollback()
  617. logs.Error("syncFeed-error-2:", err)
  618. return
  619. }
  620. if fclassExist {
  621. fclassDataList, err := tx.SQL(" select id from feedclass where pastureid = ? and fcname = ?", pastureid, fclass).QueryString()
  622. if err != nil {
  623. tx.Rollback()
  624. logs.Error("syncFeed-error-3:", err)
  625. return
  626. }
  627. for _, fclassData := range fclassDataList {
  628. fclassid = fclassData["id"]
  629. }
  630. } else {
  631. ids, err := setting.SnowIds.NextId()
  632. if err != nil {
  633. ids = time.Now().UnixNano()
  634. logging.Info("create SnowIds err", err)
  635. }
  636. _, 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 =? ))",
  637. ids, pastureid, fclass, fclass, fclass, ids, pastureid).Execute()
  638. if err != nil {
  639. tx.Rollback()
  640. logs.Error("syncFeed-error-4:", err)
  641. return
  642. }
  643. fclassid = ids
  644. }
  645. ids, err := setting.SnowIds.NextId()
  646. if err != nil {
  647. ids = time.Now().UnixNano()
  648. logging.Info("create SnowIds err", err)
  649. }
  650. insertSql := `insert into feed(id,pastureid,feedcode,fname,fclassid,fclass,dry)VALUES(?,?,?,?,?,?,?)
  651. ON DUPLICATE KEY UPDATE fname = ? ,dry = ? `
  652. _, err = tx.SQL(insertSql, ids, pastureid, feedcode, fname, fclassid, fclass, dry, fname, dry).Execute()
  653. if err != nil {
  654. tx.Rollback()
  655. logs.Error("syncFeed-error-5:", err)
  656. return
  657. }
  658. }
  659. err = tx.Commit()
  660. if err != nil {
  661. tx.Rollback()
  662. logs.Error("syncFeed-error-6:", err)
  663. return
  664. }
  665. return
  666. }
  667. func (h *ScheduledDown) SyncFeedp(pastureid string, feedpList []interface{}) error {
  668. tx := restful.Engine.NewSession()
  669. defer tx.Close()
  670. err := tx.Begin()
  671. if err != nil {
  672. logs.Error("syncFeedp-error-1:", err)
  673. return err
  674. }
  675. for _, f := range feedpList {
  676. feedp := f.(map[string]interface{})
  677. var barName, barCode, feedtempletCode, barId interface{}
  678. var ftId, tname interface{}
  679. var cowCount interface{}
  680. if _, ok := feedp["barname"]; ok {
  681. barName = feedp["barname"]
  682. }
  683. if _, ok := feedp["barcode"]; ok {
  684. barCode = feedp["barcode"]
  685. }
  686. if _, ok := feedp["cowcount"]; ok {
  687. cowCount = feedp["cowcount"]
  688. }
  689. if _, ok := feedp["feedtempletcode"]; ok {
  690. feedtempletCode = feedp["feedtempletCode"]
  691. }
  692. barCount, err := tx.SQL(" select count(1) from bar where pastureid = ? and bcode = ? ", pastureid, barCode).Count()
  693. if err != nil {
  694. tx.Rollback()
  695. logs.Error("syncFeedp-error-2:", err)
  696. return err
  697. }
  698. if barCount > 0 {
  699. barDataList, err := tx.SQL(" select id from bar where pastureid = ? and bcode = ?", pastureid, barCode).QueryString()
  700. if err != nil {
  701. tx.Rollback()
  702. logs.Error("syncFeedp-error-3:", err)
  703. return err
  704. }
  705. for _, barData := range barDataList {
  706. barId = barData["id"]
  707. }
  708. } else {
  709. barReq, err := tx.SQL("insert into bar(pastureid,bname,bcode)VALUES(?,?,?)", pastureid, barName, barCode).Execute()
  710. if err != nil {
  711. tx.Rollback()
  712. logs.Error("syncFeedp-error-4:", err)
  713. return err
  714. }
  715. id, err := barReq.LastInsertId()
  716. if err != nil {
  717. tx.Rollback()
  718. logs.Error("syncFeedp-error-5:", err)
  719. return err
  720. }
  721. barId = strconv.FormatInt(id, 10)
  722. }
  723. if feedtempletCode != "" {
  724. feedtempletDataList, err := tx.SQL(" select id,tname from feedtemplet where pastureid = ? and tcode = ?", pastureid, feedtempletCode).QueryString()
  725. if err != nil {
  726. tx.Rollback()
  727. logs.Error("syncFeedp-error-6:", err)
  728. return err
  729. }
  730. for _, feedtemplet := range feedtempletDataList {
  731. ftId = feedtemplet
  732. tname = feedtemplet
  733. }
  734. }
  735. insertSql := `insert into feedp(pastureid,barname,barid,ccount,ftid,ftname)VALUES(?,?,?,?,?,?)
  736. ON DUPLICATE KEY UPDATE ccount = ? ,ftid = ? ,ftname = ? `
  737. _, err = tx.SQL(insertSql, pastureid, barName, barId, cowCount, ftId, tname, cowCount, ftId, tname).Execute()
  738. if err != nil {
  739. tx.Rollback()
  740. logs.Error("syncFeedp-error-7:", err)
  741. return err
  742. }
  743. }
  744. err = tx.Commit()
  745. if err != nil {
  746. tx.Rollback()
  747. logs.Error("syncFeedp-error-8:", err)
  748. return err
  749. }
  750. return nil
  751. }
  752. func wxPush(target []string, content []interface{}, pastureId string, serviceId int64) {
  753. url := "http://tmrwatch.cn/notice/message"
  754. dataStr := `{
  755. "pasture_id":%s,
  756. "service_id":%d,
  757. "sys_name": "tmrWatch_test",
  758. "target": %s,
  759. "miniprogram": {
  760. "appid": "wx9ab2b5b25701da0a",
  761. "pagepath": "pages/login/login"
  762. },
  763. "keys": [
  764. "first",
  765. "keyword1",
  766. "keyword2",
  767. "remark"
  768. ],
  769. "content":%s
  770. }`
  771. targetStr, _ := json.Marshal(target)
  772. contentStr, _ := json.Marshal(content)
  773. dataStr = fmt.Sprintf(dataStr, pastureId, serviceId, string(targetStr), string(contentStr))
  774. var jsonStr = []byte(dataStr)
  775. req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
  776. req.Header.Set("Content-Type", "application/json")
  777. client := &http.Client{}
  778. resp, err := client.Do(req)
  779. if err != nil {
  780. logs.Error(err)
  781. }
  782. defer resp.Body.Close()
  783. body, _ := ioutil.ReadAll(resp.Body)
  784. fmt.Println(dataStr)
  785. logs.Info("response Body:", string(body), "fasong")
  786. }
  787. func UDPostPush1(data, method string) {
  788. url := "https://wdc.unidairy.cn/copartner_uploads/"
  789. // 超时时间:5秒
  790. fmt.Println(url, data)
  791. var jsonStr = []byte(data)
  792. req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
  793. req.Header.Set("Content-Type", "application/json")
  794. client := &http.Client{}
  795. resp, err := client.Do(req)
  796. if err != nil {
  797. logs.Error(err)
  798. }
  799. defer resp.Body.Close()
  800. body, _ := ioutil.ReadAll(resp.Body)
  801. fmt.Println("response Body:", string(body))
  802. }
  803. func processAnalysisEarlyWarning(target []string, pastureId string, serviceId int64) {
  804. tx2 := restful.Engine.NewSession()
  805. defer tx2.Close()
  806. exist, err := tx2.Table("notice").Where("status = 1").And("content = ? ", "downloadplandtl1").Exist()
  807. if err != nil {
  808. logs.Error("CronScheduled-error-4:", err)
  809. return
  810. }
  811. if exist {
  812. _, err := tx2.SQL(`update notice set status = 0 where content = ? `, "downloadplandtl1").Execute()
  813. if err != nil {
  814. logs.Error("CronScheduled-error-5:", err)
  815. return
  816. }
  817. dataList, err := tx2.SQL("select * from downloadplandtl1_log where date = date_format(now(),'%Y-%m-%d') ").Query().List()
  818. if err != nil {
  819. logs.Error("CronScheduled-error-6:", err)
  820. return
  821. }
  822. plandtl1SlIdMap := make(map[string][]int64, 0)
  823. // plandtl1HlIdMap := make(map[string][]string, 0)
  824. for _, data := range dataList {
  825. if data["type"].(int64) == 0 && data["plandtl1"] != nil {
  826. plandtl1SlIdMap["planid"] = append(plandtl1SlIdMap["planid"], data["plandtl1"].(int64))
  827. } else if data["type"].(int64) == 1 && data["plandtl1"] != nil {
  828. plandtl1SlIdMap["slplanid"] = append(plandtl1SlIdMap["slplanid"], data["plandtl1"].(int64))
  829. }
  830. }
  831. pastureList, err := tx2.SQL("select pasture_name from pasture where pastureid = ? ", pastureId).Query().List()
  832. if err != nil {
  833. logs.Error("CronScheduled-error-6:", err)
  834. return
  835. }
  836. var pastureName string
  837. for _, pasture := range pastureList {
  838. pastureName = pasture["pasture_name"].(string)
  839. }
  840. for _, data := range dataList {
  841. if data["type"].(int64) == 0 {
  842. plandtl1List, err := tx2.SQL(`select d.remark,d.projname,d1.fname,d.tmrtname,DATE_FORMAT(d1.intime, '%Y-%m-%d %H:%i:%S') as intime,d1.id,d1.feedallowratio,abs(d1.actualweightminus -d1.lweight ) errorvalue ,d1.actualweightminus,d1.lweight,
  843. if(d1.actualweightminus <= d1.lweight,ROUND(d1.actualweightminus/d1.lweight* 100,2),ROUND(d1.lweight/d1.actualweightminus* 100,2) ) as accuracy from
  844. downloadplandtl1 d1
  845. join downloadedplan d on d.id = d1.pid
  846. where d1.pid = ? and d1.sort = ? and d1.pastureid = ? and d1.intime is not null and d1.type = 0 `,
  847. data["planid"], data["sort"], data["pastureid"]).Query().List()
  848. if err != nil {
  849. logs.Error("CronScheduled-error-7:", err)
  850. return
  851. }
  852. for _, plandtl1 := range plandtl1List {
  853. idexist := false
  854. //防止同顺序饲料多次推送
  855. for _, plandtl1Id := range plandtl1SlIdMap["planid"] {
  856. if plandtl1Id == plandtl1["id"].(int64) {
  857. idexist = true
  858. break
  859. }
  860. }
  861. if idexist {
  862. continue
  863. }
  864. errorvalue, _ := strconv.ParseFloat(plandtl1["errorvalue"].(string), 64)
  865. if plandtl1["feedallowratio"].(float64) < errorvalue {
  866. // if plandtl1["feedallowratio"].(float64) < plandtl1["errorvalue"].(float64) {
  867. fmt.Println(plandtl1, "推送")
  868. // target := []string{"13916925233"}
  869. var sendList []interface{}
  870. sendStr := fmt.Sprintf("操作编号:%v\n牧场:%s\nTMR名称:%v\n描述:%v\n饲料名称:%v\n计划重量(kg):%v\n实际重量(kg):%v\n误差值(kg):%v\n准确率(%%):%v",
  871. plandtl1["projname"], pastureName, plandtl1["tmrtname"], plandtl1["remark"], plandtl1["fname"], plandtl1["lweight"], plandtl1["actualweightminus"], plandtl1["errorvalue"], plandtl1["accuracy"])
  872. // content = append(content, "混料", plandtl1["begintime"], "kpt", sendStr, "搅拌预警")
  873. sendMap1 := make(map[string]interface{}, 0)
  874. sendMap1["value"] = "混料准确率异常"
  875. sendMap1["color"] = "#173177"
  876. sendList = append(sendList, sendMap1)
  877. sendMap4 := make(map[string]interface{}, 0)
  878. sendMap4["value"] = sendStr
  879. sendMap4["color"] = "#173177"
  880. sendList = append(sendList, sendMap4)
  881. sendMap2 := make(map[string]interface{}, 0)
  882. sendMap2["value"] = plandtl1["intime"]
  883. sendMap2["color"] = "#173177"
  884. sendList = append(sendList, sendMap2)
  885. // sendMap3 := make(map[string]interface{}, 0)
  886. // sendMap3["value"] = "kpt"
  887. // sendMap3["color"] = "#173177"
  888. // sendList = append(sendList, sendMap3)
  889. sendMap5 := make(map[string]interface{}, 0)
  890. sendMap5["value"] = "无备注"
  891. sendMap5["color"] = "#173177"
  892. sendList = append(sendList, sendMap5)
  893. wxPush(target, sendList, pastureId, serviceId)
  894. }
  895. plandtl1SlIdMap["planid"] = append(plandtl1SlIdMap["planid"], plandtl1["id"].(int64))
  896. _, err := tx2.SQL(" update downloadplandtl1_log set plandtl1 = ? where id = ? and type = 0 ", plandtl1["id"], data["id"]).Execute()
  897. if err != nil {
  898. logs.Error("CronScheduled-error-8:", err)
  899. return
  900. }
  901. }
  902. } else {
  903. plandtl1List, err := tx2.SQL(`select d.remark,d2.id,d.projname,d2.fname,d.tmrtname,d2.id,ifnull(d2.allowratio,0) allowratio ,abs(d2.actualweightminus -d2.lweight ) errorvalue ,DATE_FORMAT(d2.intime, '%Y-%m-%d %H:%i:%S') as intime ,d2.actualweightminus,d2.lweight,
  904. if(d2.actualweightminus <= d2.lweight,ROUND(d2.actualweightminus/d2.lweight* 100,2),ROUND(d2.lweight/d2.actualweightminus* 100,2) ) as accuracy
  905. from downloadplandtl2 d2
  906. join downloadedplan d on d.id = d2.pid
  907. where d2.pid = ? and d2.sort = ? and d2.pastureid = ? and d2.intime is not null and d2.type = 0 `,
  908. data["planid"], data["sort"], data["pastureid"]).Query().List()
  909. // Where(" pid = ? ", data["planid"]).And("sort = ? ", data["sort"]).And(" pastureid = ? ", data["pastureid"]).And(" intime is not null").And("type = 0 ").Query().List()
  910. if err != nil {
  911. logs.Error("CronScheduled-error-7:", err)
  912. return
  913. }
  914. for _, plandtl1 := range plandtl1List {
  915. idexist := false
  916. //防止同顺序饲料多次推送
  917. for _, plandtl1Id := range plandtl1SlIdMap["slplanid"] {
  918. if plandtl1Id == plandtl1["id"].(int64) {
  919. idexist = true
  920. break
  921. }
  922. }
  923. if idexist {
  924. continue
  925. }
  926. errorvalue, _ := strconv.ParseFloat(plandtl1["errorvalue"].(string), 64)
  927. if float64(plandtl1["allowratio"].(int64)) < errorvalue && float64(plandtl1["allowratio"].(int64)) != 0 {
  928. fmt.Println(plandtl1, "推送")
  929. // target := []string{"13916925233"}
  930. // var content []interface{}
  931. var sendList []interface{}
  932. sendStr := fmt.Sprintf("操作编号:%v\n牧场:%s\nTMR名称:%v\n描述:%v\n栏舍名称:%v\n计划重量(kg):%v\n实际重量(kg):%v\n误差值(kg):%v\n准确率(%%):%v",
  933. plandtl1["projname"], pastureName, plandtl1["tmrtname"], plandtl1["remark"], plandtl1["fname"], plandtl1["lweight"], plandtl1["actualweightminus"], plandtl1["errorvalue"], plandtl1["accuracy"])
  934. sendMap1 := make(map[string]interface{}, 0)
  935. sendMap1["value"] = "撒料准确率异常"
  936. sendMap1["color"] = "#173177"
  937. sendList = append(sendList, sendMap1)
  938. sendMap4 := make(map[string]interface{}, 0)
  939. sendMap4["value"] = sendStr
  940. sendMap4["color"] = "#173177"
  941. sendList = append(sendList, sendMap4)
  942. sendMap2 := make(map[string]interface{}, 0)
  943. sendMap2["value"] = plandtl1["intime"]
  944. sendMap2["color"] = "#173177"
  945. sendList = append(sendList, sendMap2)
  946. sendMap5 := make(map[string]interface{}, 0)
  947. sendMap5["value"] = "无备注"
  948. sendMap5["color"] = "#173177"
  949. sendList = append(sendList, sendMap5)
  950. wxPush(target, sendList, pastureId, serviceId)
  951. }
  952. plandtl1SlIdMap["planid"] = append(plandtl1SlIdMap["planid"], plandtl1["id"].(int64))
  953. _, err := tx2.SQL(" update downloadplandtl1_log set plandtl1 = ? where id = ? and type = 1 ", plandtl1["id"], data["id"]).Execute()
  954. if err != nil {
  955. logs.Error("CronScheduled-error-8:", err)
  956. return
  957. }
  958. }
  959. }
  960. }
  961. }
  962. }
  963. func manualUdData(pastureinfo *udPastureInfo) {
  964. c := cron.New()
  965. c.AddFunc("10 02 * * *", func() {
  966. // fmt.Println(time.Now())
  967. tx := restful.Engine.NewSession()
  968. defer tx.Close()
  969. now := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
  970. exist, err := tx.SQL(" select id from downloadedplan where mydate = ? and enable = 1 and iscompleted = 0 ", now).Exist()
  971. if err != nil {
  972. logs.Error("manualUdData-error-1:", err)
  973. return
  974. }
  975. if exist {
  976. dataList, err := tx.SQL(" select id from downloadedplan where mydate = ? ", now).QueryString()
  977. if err != nil {
  978. logs.Error("manualUdData-error-1:", err)
  979. return
  980. }
  981. var idList []string
  982. for _, data := range dataList {
  983. idList = append(idList, data["id"])
  984. }
  985. UpdatePush(context.Background(), tx, true, idList, pastureinfo, "", now)
  986. }
  987. })
  988. c.Start()
  989. }
  990. func abnormalMixingDelay(target []string, pastureId string, serviceId int64) {
  991. tx2 := restful.Engine.NewSession()
  992. defer tx2.Close()
  993. // time.Now().Format("2006-01-02")
  994. dataList, err := tx2.SQL(` select id,planid,sort from downloadplandtl1_log where abnormalMixingDelay = 0 and type = 0 and pastureid = ? and date = ? `, pastureId, "2022-06-24").Query().List()
  995. if err != nil {
  996. logs.Error("abnormalMixingDelay-error-1:", err)
  997. return
  998. }
  999. if len(dataList) <= 0 {
  1000. return
  1001. }
  1002. local, _ := time.LoadLocation("Asia/Shanghai")
  1003. for _, data := range dataList {
  1004. planList, err := tx2.SQL(`select de.deviation,de.lweight,de.fname,de.processtime,de.stirdelay,d.tmrtname, d.projname, CONCAT(d.templetname,projname) as name ,
  1005. d.datacaptureno,(select pasture_name from pasture where pastureid = ?) as pasturename,de.actualweightminus from downloadplandtl1_exec de
  1006. join downloadedplan d on de.pid = d.id where de.pid = ? and de.sort = ? `, pastureId, data["planid"], data["sort"]).Query().List()
  1007. if err != nil {
  1008. logs.Error("abnormalMixingDelay-error-1:", err)
  1009. return
  1010. }
  1011. for _, plan := range planList {
  1012. // if plan["stirdelay"].(int64) > 0 {
  1013. showTime, _ := time.ParseInLocation("2006-01-02 15:04:05", fmt.Sprintf("%s %s", time.Now().Format("2006-01-02"), plan["processtime"]), local)
  1014. nowTime, _ := time.ParseInLocation("2006-01-02 15:04:05", fmt.Sprintf("%s 00:00:00", time.Now().Format("2006-01-02")), local)
  1015. if (showTime.Unix()-nowTime.Unix())/60 < plan["stirdelay"].(int64)-plan["deviation"].(int64) || (showTime.Unix()-nowTime.Unix())/60 > plan["stirdelay"].(int64)+plan["deviation"].(int64) {
  1016. var sendList []interface{}
  1017. sendStr := fmt.Sprintf("操作编号:%v\n牧场:%s\nTMR名称:%v\n描述:%v\n饲料名称:%v\n计划重量(kg):%v\n实际重量(kg):%v\n过程时间:%v",
  1018. plan["projname"], plan["pasturename"], plan["tmrtname"], plan["name"], plan["fname"], plan["lweight"], plan["actualweightminus"], plan["processtime"])
  1019. sendMap1 := make(map[string]interface{}, 0)
  1020. sendMap1["value"] = "混料搅拌延时异常"
  1021. sendMap1["color"] = "#173177"
  1022. sendList = append(sendList, sendMap1)
  1023. sendMap4 := make(map[string]interface{}, 0)
  1024. sendMap4["value"] = sendStr
  1025. sendMap4["color"] = "#173177"
  1026. sendList = append(sendList, sendMap4)
  1027. sendMap2 := make(map[string]interface{}, 0)
  1028. sendMap2["value"] = plan["processtime"]
  1029. sendMap2["color"] = "#173177"
  1030. sendList = append(sendList, sendMap2)
  1031. sendMap5 := make(map[string]interface{}, 0)
  1032. sendMap5["value"] = "无备注"
  1033. sendMap5["color"] = "#173177"
  1034. sendList = append(sendList, sendMap5)
  1035. wxPush(target, sendList, pastureId, serviceId)
  1036. }
  1037. // }
  1038. _, err := tx2.SQL(` update downloadplandtl1_log set abnormalMixingDelay = 1 where id = ? `, data["id"]).Execute()
  1039. if err != nil {
  1040. logs.Error("abnormalMixingDelay-error-2:", err)
  1041. return
  1042. }
  1043. }
  1044. }
  1045. }
  1046. func endOfShift(target []string, pastureId string, serviceId int64) {
  1047. tx := restful.Engine.NewSession()
  1048. defer tx.Close()
  1049. // time.Now().Format("2006-01-02")
  1050. logList, err := tx.SQL(` select times from downloadedplan_log where date = ? and classes = 0 group by times `, "2022-06-24").Query().List()
  1051. if err != nil {
  1052. logs.Error("endOfShift-error-1:", err)
  1053. return
  1054. }
  1055. for _, item := range logList {
  1056. exist, err := tx.SQL(` select id from downloadedplan where mydate = ? and times = ? and iscompleted = 0 and enable = 1 `, "2022-06-24", item["times"]).Exist()
  1057. if err != nil {
  1058. logs.Error("endOfShift-error-2:", err)
  1059. return
  1060. }
  1061. if !exist {
  1062. hlList, err := tx.SQL(` select ( select count(1) from downloadedplan where times = d.times and mydate = d.mydate ) as cltrains,
  1063. sum(de.lweight)lweight,sum(de.actualweightminus)actualweightminus ,
  1064. 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,
  1065. ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) correct,
  1066. IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0)),0) correctcount,
  1067. 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
  1068. from downloadedplan d
  1069. join downloadplandtl1_exec de on de.pid = d.id
  1070. where d.times = ? and d.mydate = ? and lpplantype in(0,1) group by d.times`, item["times"], "2022-06-24").Query().List()
  1071. if err != nil {
  1072. logs.Error("endOfShift-error-3:", err)
  1073. return
  1074. }
  1075. slList, err := tx.SQL(` select sum(de.lweight)lweight,sum(de.actualweightminus)actualweightminus ,
  1076. 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,
  1077. ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) correct,
  1078. IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0)),0) correctcount,
  1079. 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
  1080. from downloadedplan d
  1081. join downloadplandtl2 de on de.pid = d.id
  1082. where d.times = ? and d.mydate = ? and lpplantype in(0,2) group by d.times `, item["times"], "2022-06-24").Query().List()
  1083. if err != nil {
  1084. logs.Error("endOfShift-error-4:", err)
  1085. return
  1086. }
  1087. data := make(map[string]interface{})
  1088. for _, hl := range hlList {
  1089. data["cltrains"] = hl["cltrains"]
  1090. // data["hllweight"] = hl["lweight"]
  1091. data["hlactualweightminus"] = hl["actualweightminus"]
  1092. data["hlaccurate"] = hl["accurate"]
  1093. data["hlcorrect"] = hl["correct"]
  1094. data["hlcorrectcount"] = hl["correctcount"]
  1095. // data["hlprocesstime"] = util.TimeTransformation(hl["processtime"].(int64))
  1096. data["hlwcz"] = hl["wcz"]
  1097. }
  1098. for _, sl := range slList {
  1099. // data["sllweight"] = sl["lweight"]
  1100. data["slactualweightminus"] = sl["actualweightminus"]
  1101. data["slaccurate"] = sl["accurate"]
  1102. data["slcorrect"] = sl["correct"]
  1103. data["slcorrectcount"] = sl["correctcount"]
  1104. // data["slprocesstime"] = util.TimeTransformation(sl["processtime"].(int64))
  1105. data["slwcz"] = sl["wcz"]
  1106. }
  1107. 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",
  1108. item["times"], data["cltrains"], data["hlactualweightminus"], data["hlwcz"], data["hlaccurate"], data["hlcorrect"], data["hlcorrectcount"],
  1109. data["slactualweightminus"], data["slwcz"], data["slaccurate"], data["slcorrect"], data["slcorrectcount"])
  1110. var sendList []interface{}
  1111. sendMap1 := make(map[string]interface{}, 0)
  1112. sendMap1["value"] = "班次完成"
  1113. sendMap1["color"] = "#173177"
  1114. sendList = append(sendList, sendMap1)
  1115. sendMap4 := make(map[string]interface{}, 0)
  1116. sendMap4["value"] = sendStr
  1117. sendMap4["color"] = "#173177"
  1118. sendList = append(sendList, sendMap4)
  1119. sendMap2 := make(map[string]interface{}, 0)
  1120. // sendMap2["value"] = plan["processtime"]
  1121. sendMap2["value"] = time.Now().Format("2006-01-02 15:04:05")
  1122. sendMap2["color"] = "#173177"
  1123. sendList = append(sendList, sendMap2)
  1124. sendMap5 := make(map[string]interface{}, 0)
  1125. sendMap5["value"] = "无备注"
  1126. sendMap5["color"] = "#173177"
  1127. sendList = append(sendList, sendMap5)
  1128. wxPush(target, sendList, pastureId, serviceId)
  1129. _, err = tx.SQL(` update downloadedplan_log set classes = 1 where date = ? and times = ? `, "2022-06-24", item["times"]).Execute()
  1130. if err != nil {
  1131. logs.Error("endOfShift-error-5:", err)
  1132. return
  1133. }
  1134. }
  1135. }
  1136. }
  1137. func plansToComplete(target []string, pastureId string, serviceId int64) {
  1138. tx := restful.Engine.NewSession()
  1139. defer tx.Close()
  1140. exist, err := tx.SQL(` select id from downloadedplan_log where date = ? and dailyplan = 0 `, "2022-06-24").Exist()
  1141. if err != nil {
  1142. logs.Error("plansToComplete-error-1:", err)
  1143. return
  1144. }
  1145. if exist {
  1146. downloadedplanExist, err := tx.SQL(` select id from downloadedplan where mydate = ? and iscompleted = 0 and enable = 1 `, "2022-06-24").Exist()
  1147. if err != nil {
  1148. logs.Error("plansToComplete-error-2:", err)
  1149. return
  1150. }
  1151. if !downloadedplanExist {
  1152. 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,
  1153. sum(de.lweight)lweight,sum(de.actualweightminus)actualweightminus ,
  1154. 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,
  1155. ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) correct,
  1156. IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0)),0) correctcount,
  1157. 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
  1158. from downloadedplan d
  1159. join downloadplandtl1_exec de on de.pid = d.id
  1160. where d.mydate = ? and lpplantype in(0,1) group by d.mydate`, "2022-06-24", "2022-06-24").Query().List()
  1161. if err != nil {
  1162. logs.Error("plansToComplete-error-3:", err)
  1163. return
  1164. }
  1165. slList, err := tx.SQL(` select sum(de.lweight)lweight,sum(de.actualweightminus)actualweightminus ,
  1166. 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,
  1167. ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) correct,
  1168. IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0)),0) correctcount,
  1169. 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
  1170. from downloadedplan d
  1171. join downloadplandtl2 de on de.pid = d.id
  1172. where d.mydate = ? and lpplantype in(0,2) group by d.mydate `, "2022-06-24").Query().List()
  1173. if err != nil {
  1174. logs.Error("plansToComplete-error-4:", err)
  1175. return
  1176. }
  1177. data := make(map[string]interface{})
  1178. for _, hl := range hlList {
  1179. data["timescount"] = hl["timescount"]
  1180. data["cltrains"] = hl["cltrains"]
  1181. data["hllweight"] = hl["lweight"]
  1182. data["hlactualweightminus"] = hl["actualweightminus"]
  1183. data["hlaccurate"] = hl["accurate"]
  1184. data["hlcorrect"] = hl["correct"]
  1185. data["hlcorrectcount"] = hl["correctcount"]
  1186. // data["hlprocesstime"] = util.TimeTransformation(hl["processtime"].(int64))
  1187. data["hlwcz"] = hl["wcz"]
  1188. }
  1189. for _, sl := range slList {
  1190. data["sllweight"] = sl["lweight"]
  1191. data["slactualweightminus"] = sl["actualweightminus"]
  1192. data["slaccurate"] = sl["accurate"]
  1193. data["slcorrect"] = sl["correct"]
  1194. data["slcorrectcount"] = sl["correctcount"]
  1195. // data["slprocesstime"] = util.TimeTransformation(sl["processtime"].(int64))
  1196. data["slwcz"] = sl["wcz"]
  1197. }
  1198. 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",
  1199. data["timescount"], data["cltrains"], data["hlactualweightminus"], data["hlwcz"], data["hlaccurate"], data["hlcorrect"], data["hlcorrectcount"],
  1200. data["slactualweightminus"], data["slwcz"], data["slaccurate"], data["slcorrect"], data["slcorrectcount"])
  1201. var sendList []interface{}
  1202. sendMap1 := make(map[string]interface{}, 0)
  1203. sendMap1["value"] = "每日计划完成"
  1204. sendMap1["color"] = "#173177"
  1205. sendList = append(sendList, sendMap1)
  1206. sendMap4 := make(map[string]interface{}, 0)
  1207. sendMap4["value"] = sendStr
  1208. sendMap4["color"] = "#173177"
  1209. sendList = append(sendList, sendMap4)
  1210. sendMap2 := make(map[string]interface{}, 0)
  1211. // sendMap2["value"] = plan["processtime"]
  1212. sendMap2["value"] = time.Now().Format("2006-01-02 15:04:05")
  1213. sendMap2["color"] = "#173177"
  1214. sendList = append(sendList, sendMap2)
  1215. sendMap5 := make(map[string]interface{}, 0)
  1216. sendMap5["value"] = "无备注"
  1217. sendMap5["color"] = "#173177"
  1218. sendList = append(sendList, sendMap5)
  1219. wxPush(target, sendList, pastureId, serviceId)
  1220. _, err = tx.SQL(` update downloadedplan_log set dailyplan = 1 where date = ? `, "2022-06-24").Execute()
  1221. if err != nil {
  1222. logs.Error("plansToComplete-error-5:", err)
  1223. return
  1224. }
  1225. }
  1226. }
  1227. }