scheduled.go 56 KB

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