scheduled.go 62 KB

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