scheduled.go 61 KB

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