scheduled.go 60 KB

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