scheduled.go 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832
  1. package api
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "io/ioutil"
  8. "log"
  9. "net/http"
  10. "os"
  11. "reflect"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "tmr-watch/conf/setting"
  16. "tmr-watch/http/handle/restful"
  17. "tmr-watch/pkg/app"
  18. "tmr-watch/pkg/e"
  19. "tmr-watch/pkg/logging"
  20. // "../../routers/api/gm"
  21. // "../../routers/api/sap"
  22. // "../../routers/restful"
  23. "github.com/Anderson-Lu/gofasion/gofasion"
  24. "github.com/astaxie/beego/logs"
  25. "github.com/gin-gonic/gin"
  26. "github.com/robfig/cron"
  27. "github.com/xormplus/xorm"
  28. )
  29. func CronScheduled(ctx context.Context) {
  30. tx := restful.Engine.NewSession()
  31. defer tx.Close()
  32. pastureinfo := new(udPastureInfo)
  33. err := tx.SQL(`select column_default as pastureid,(select werks from pasture where pastureid = column_default) werks from information_schema.COLUMNS
  34. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  35. if err != nil {
  36. logs.Error(err)
  37. return
  38. }
  39. // duetimecst, _ := time.ParseInLocation("15:04:05", "00:10:00", time.Local)
  40. // duetimecst1, _ := time.ParseInLocation("15:04:05", "00:00:00", time.Local)
  41. // spec := fmt.Sprintf("@every %v", duetimecst.Sub(duetimecst1))
  42. // c := cron.New()
  43. // c.AddFunc(spec, func() {
  44. // tx1 := restful.Engine.NewSession()
  45. // defer tx1.Close()
  46. // exist, err := tx1.Table("notice").Where("status = 1").And("content = ? ", "downloadedplan_log").Exist()
  47. // if err != nil {
  48. // logs.Error("CronScheduled-error-1:", err)
  49. // return
  50. // }
  51. // if exist {
  52. // _, err := tx.SQL(`update notice set status = 0 where content = ? `, "downloadedplan_log").Execute()
  53. // if err != nil {
  54. // logs.Error("CronScheduled-error-2:", err)
  55. // return
  56. // }
  57. // Scheduled(ctx, tx1, pastureinfo)
  58. // }
  59. // })
  60. // c.Start()
  61. //消息提醒
  62. duetimecst2, _ := time.ParseInLocation("15:04:05", "00:01:00", time.Local)
  63. duetimecst3, _ := time.ParseInLocation("15:04:05", "00:00:00", time.Local)
  64. spec1 := fmt.Sprintf("@every %v", duetimecst2.Sub(duetimecst3))
  65. downloadplandtl1 := cron.New()
  66. downloadplandtl1.AddFunc(spec1, func() {
  67. dataList, err := tx.SQL(` select user,function,id from remind where pastureid = ? `, pastureinfo.Pastureid).Query().List()
  68. if err != nil {
  69. logs.Error("CronScheduled-error-3:", err)
  70. return
  71. }
  72. for _, data := range dataList {
  73. var openIdList []string
  74. if _, ok := data["user"]; ok {
  75. openIdList = strings.Split(data["user"].(string), ",")
  76. }
  77. if data["function"].(string) == "processAnalysisEarlyWarning" {
  78. if len(openIdList) > 0 {
  79. processAnalysisEarlyWarning(openIdList, pastureinfo.Pastureid, data["id"].(int64))
  80. }
  81. } else if data["function"].(string) == "abnormalMixingDelay" {
  82. if len(openIdList) > 0 {
  83. abnormalMixingDelay(openIdList, pastureinfo.Pastureid, data["id"].(int64))
  84. }
  85. } else if data["function"].(string) == "endOfShift" {
  86. if len(openIdList) > 0 {
  87. endOfShift(openIdList, pastureinfo.Pastureid, data["id"].(int64))
  88. }
  89. } else if data["function"].(string) == "plansToComplete" {
  90. if len(openIdList) > 0 {
  91. plansToComplete(openIdList, pastureinfo.Pastureid, data["id"].(int64))
  92. }
  93. }
  94. }
  95. })
  96. downloadplandtl1.Start()
  97. dayCron := cron.New()
  98. dayCron.AddFunc("30 23 * * *", func() {
  99. dataList, err := tx.SQL(` select user,function,id from remind where pastureid = ? and function = ? `, pastureinfo.Pastureid, "inventoryWarning").Query().List()
  100. if err != nil {
  101. logs.Error("CronScheduled-error-5:", err)
  102. return
  103. }
  104. for _, data := range dataList {
  105. var openIdList []string
  106. if _, ok := data["user"]; ok {
  107. openIdList = strings.Split(data["user"].(string), ",")
  108. }
  109. if data["function"].(string) == "inventoryWarning" {
  110. if len(openIdList) > 0 {
  111. inventoryWarning(openIdList, pastureinfo.Pastureid, data["id"].(int64))
  112. }
  113. }
  114. }
  115. })
  116. dayCron.Start()
  117. // udFeedSync(pastureinfo)
  118. // //圣牧自动同步前天有进行中的任务
  119. // manualUdData(pastureinfo)
  120. // gm.GmUdSync(pastureinfo.Pastureid, pastureinfo.Werks)
  121. // xdmy := cron.New()
  122. // err = xdmy.AddFunc("0 30 8 * * *", func() {
  123. // // //现代牧业sap同步
  124. // // sap.SyncMaterialOutbound()
  125. // // // 光明ud同步
  126. // // fmt.Println(time.Now())
  127. // gm.GmUdSync(pastureinfo.Pastureid, pastureinfo.Werks)
  128. // })
  129. // xdmy.Start()
  130. // InitMqttClient()
  131. }
  132. type ScheduledInfo struct {
  133. Id int64 `xorm:"id"`
  134. Sname string `xorm:"sname"`
  135. Action int64 `xorm:"action"`
  136. Childid int64 `xorm:"childid"`
  137. Times string `xorm:"times"`
  138. Enable string `xorm:"enable"`
  139. }
  140. type ScheduledUpInfo struct {
  141. Id int64 `xorm:"id"`
  142. Company string `xorm:"company"`
  143. Addres string `xorm:"addres"`
  144. Datatype int64 `xorm:"datatype"`
  145. Package string `xorm:"Package"`
  146. Datasql string `xorm:"datasql"`
  147. Automatic int64 `xorm:"automatic"`
  148. Manual int64 `xorm:"manual"`
  149. Targetdata string `xorm:"targetdata"`
  150. }
  151. type ScheduledDownInfo struct {
  152. Id int64 `xorm:"id"`
  153. Datatype int64 `xorm:"datatype"`
  154. Addres string `xorm:"addres"`
  155. Adressparam string `xorm:"adressparam"`
  156. Targetdata string `xorm:"targetdata"`
  157. Manual int64 `xorm:"manual"`
  158. Methods string `xorm:"methods"`
  159. }
  160. type ScheduledDownChildInfo struct {
  161. Id int64 `xorm:"id"`
  162. Parentid int64 `xorm:"parentid"`
  163. Fieldname string `xorm:"fieldname"`
  164. Checksql string `xorm:"checksql"`
  165. Dosql string `xorm:"dosql"`
  166. }
  167. func Scheduled(ctx context.Context, tx *xorm.Session, pastureinfo *udPastureInfo) {
  168. times := new(ScheduledInfo)
  169. err := tx.SQL(" select times from scheduled where action = 0 group by times").GetFirst(times).Error
  170. if err != nil {
  171. logs.Error(err)
  172. return
  173. }
  174. if times.Times == "0" {
  175. downloadedplanLogList, err := tx.SQL(` select id from downloadedplan_log where date = date_format(now(),'%Y-%m-%d') `).Query().List()
  176. if err != nil {
  177. logs.Error(err)
  178. return
  179. }
  180. ids := []string{}
  181. for _, item := range downloadedplanLogList {
  182. ids = append(ids, strconv.FormatInt(item["id"].(int64), 10))
  183. }
  184. fmt.Println(ids, time.Now())
  185. err = UpdatePush(ctx, tx, true, ids, pastureinfo, "", time.Now().Format("2006-01-02"))
  186. if err != nil {
  187. return
  188. }
  189. } else if times.Times == "1" {
  190. 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()
  191. if err != nil {
  192. logs.Error(err)
  193. return
  194. }
  195. for _, item := range downloadedplanLogList {
  196. count, err := tx.SQL(` select count(1) from downloadedplan where pastureid = ? and mydate = date_format(now(),'%Y-%m-%d')
  197. and iscompleted = 0 and times = ? and enable = 1 `,
  198. pastureinfo.Pastureid, item["times"]).Count()
  199. if err != nil {
  200. logs.Error(err)
  201. return
  202. }
  203. if count == 0 {
  204. //推送
  205. downloadedplanLogList, err := tx.SQL(` select id from downloadedplan_log where date = date_format(now(),'%Y-%m-%d')
  206. and times = ? `, item["times"]).Query().List()
  207. if err != nil {
  208. logs.Error(err)
  209. return
  210. }
  211. ids := []string{}
  212. for _, item := range downloadedplanLogList {
  213. ids = append(ids, strconv.FormatInt(item["id"].(int64), 10))
  214. }
  215. err = UpdatePush(ctx, tx, true, ids, pastureinfo, "", time.Now().Format("2006-01-02"))
  216. if err != nil {
  217. return
  218. }
  219. }
  220. }
  221. } else if times.Times == "2" {
  222. 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 ",
  223. pastureinfo.Pastureid).Count()
  224. if err != nil {
  225. logs.Error(err)
  226. return
  227. }
  228. if count == 0 {
  229. //推送
  230. downloadedplanLogList, err := tx.SQL(` select id from downloadedplan_log where date = date_format(now(),'%Y-%m-%d') `).Query().List()
  231. if err != nil {
  232. logs.Error(err)
  233. return
  234. }
  235. ids := []string{}
  236. for _, item := range downloadedplanLogList {
  237. ids = append(ids, strconv.FormatInt(item["id"].(int64), 10))
  238. }
  239. err = UpdatePush(ctx, tx, true, ids, pastureinfo, "", time.Now().Format("2006-01-02"))
  240. if err != nil {
  241. return
  242. }
  243. }
  244. }
  245. }
  246. func UpdateScheduledStatus(c *gin.Context) {
  247. appG := app.Gin{C: c}
  248. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  249. fsion := gofasion.NewFasion(string(dataByte))
  250. idList := fsion.Get("id").Array()
  251. automatic := fsion.Get("automatic").ValueStr()
  252. manual := fsion.Get("manual").ValueStr()
  253. company := fsion.Get("company").ValueStr()
  254. //type 0 上传,1 下载
  255. typee := fsion.Get("type").ValueStr()
  256. ids := []string{}
  257. for _, item := range idList {
  258. ids = append(ids, item.ValueStr())
  259. }
  260. tx := restful.Engine.NewSession()
  261. defer tx.Close()
  262. tx.Begin()
  263. sqlstr := ""
  264. sqlstr1 := ""
  265. // var args []interface{}
  266. if typee == "0" {
  267. if len(ids) > 0 {
  268. sqlstr = `update scheduled s join scheduled_up su on su.id = s.childid set `
  269. sqlstr1 = `update scheduled s join scheduled_up su on su.id = s.childid set `
  270. if automatic != "" {
  271. sqlstr += " su.automatic = 1 "
  272. sqlstr1 += " su.automatic = 0 "
  273. } else if manual != "" {
  274. sqlstr += " su.manual = 1 "
  275. sqlstr1 += " su.manual = 0 "
  276. }
  277. id := strings.Join(ids, ",")
  278. sqlstr += fmt.Sprintf(" where s.id in (%s) and s.action = 0 and su.company = '%s' ", id, company)
  279. sqlstr1 += fmt.Sprintf(" where s.id not in (%s) and s.action = 0 and su.company ='%s' ", id, company)
  280. } else {
  281. sqlstr = `update scheduled s join scheduled_up su on su.id = s.childid set `
  282. if automatic != "" {
  283. sqlstr += " su.automatic = 0 "
  284. } else if manual != "" {
  285. sqlstr += " su.manual = 0 "
  286. }
  287. sqlstr += fmt.Sprintf(" where s.action = 0 and su.company = '%s' ", company)
  288. }
  289. } else {
  290. if len(ids) > 0 {
  291. sqlstr = `update scheduled s join scheduled_down sd on sd.id = s.childid set `
  292. sqlstr1 = `update scheduled s join scheduled_down sd on sd.id = s.childid set `
  293. sqlstr += " sd.manual = 1 "
  294. sqlstr1 += " sd.manual = 0 "
  295. id := strings.Join(ids, ",")
  296. sqlstr += fmt.Sprintf(" where s.id in (%s) and s.action = 1 and sd.company = '%s' ", id, company)
  297. sqlstr1 += fmt.Sprintf(" where s.id not in (%s) and s.action = 1 and sd.company = '%s' ", id, company)
  298. } else {
  299. sqlstr = `update scheduled s join scheduled_down sd on sd.id = s.childid set `
  300. sqlstr += " sd.manual = 0 "
  301. sqlstr += fmt.Sprintf(" where s.action = 1 and sd.company = '%s' ", company)
  302. }
  303. }
  304. _, err := tx.SQL(sqlstr).Execute()
  305. if err != nil {
  306. log.Println("UpdateScheduledStatus-error-1: ", err)
  307. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  308. tx.Rollback()
  309. }
  310. if len(sqlstr1) > 0 {
  311. _, err = tx.SQL(sqlstr1).Execute()
  312. if err != nil {
  313. log.Println("UpdateScheduledStatus-error-2: ", err)
  314. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  315. tx.Rollback()
  316. }
  317. }
  318. err = tx.Commit()
  319. if err != nil {
  320. log.Println("UpdateScheduledStatus-error-3: ", err)
  321. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  322. tx.Rollback()
  323. }
  324. appG.Response(http.StatusOK, e.SUCCESS, true)
  325. }
  326. func SynchronizeNow(c *gin.Context) {
  327. appG := app.Gin{C: c}
  328. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  329. fsion := gofasion.NewFasion(string(dataByte))
  330. company := fsion.Get("company").ValueStr()
  331. date := fsion.Get("date").ValueStr()
  332. tx := restful.Engine.NewSession()
  333. defer tx.Close()
  334. pastureinfo := new(udPastureInfo)
  335. err := tx.SQL(`select column_default as pastureid from information_schema.COLUMNS
  336. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  337. if err != nil {
  338. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  339. return
  340. }
  341. dataList, err := tx.SQL(`select id from downloadedplan where mydate = date_format(?,'%Y-%m-%d') `, date).Query().List()
  342. if err != nil {
  343. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  344. return
  345. }
  346. var idList []string
  347. for _, data := range dataList {
  348. idList = append(idList, strconv.FormatInt(data["id"].(int64), 10))
  349. }
  350. err = UpdatePush(c, tx, false, idList, pastureinfo, company, date)
  351. if err != nil {
  352. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  353. return
  354. }
  355. UpdateDown(c, tx, nil, pastureinfo, company)
  356. if err != nil {
  357. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  358. return
  359. }
  360. appG.Response(http.StatusOK, e.SUCCESS, true)
  361. }
  362. func UpdatePush(ctx context.Context, tx *xorm.Session, auto bool, idList []string, pastureinfo *udPastureInfo, company, date string) error {
  363. upList := make([]*ScheduledUpInfo, 0)
  364. up := tx.Table("scheduled_up")
  365. if company != "" {
  366. up.Where("company = ? ", company)
  367. }
  368. if auto {
  369. up.Where("automatic = 1")
  370. } else {
  371. up.Where("manual = 1")
  372. }
  373. err := up.Find(&upList)
  374. if err != nil {
  375. log.Println("UpdataPush-error-1: ", err)
  376. return err
  377. }
  378. for _, item := range upList {
  379. if item.Datasql != "" {
  380. if item.Datatype == 3 || item.Datatype == 4 {
  381. targetdataList := strings.Split(item.Targetdata, ",")
  382. var args []interface{}
  383. for _, targetdata := range targetdataList {
  384. if targetdata == "pastureid" {
  385. args = append(args, pastureinfo.Pastureid)
  386. } else if targetdata == "idlist" {
  387. // args = append(args, strings.Join(idList, ","))
  388. item.Datasql = strings.ReplaceAll(item.Datasql, "idlist", strings.Join(idList, ","))
  389. } else if targetdata == "date" {
  390. args = append(args, date)
  391. }
  392. }
  393. data, err := tx.SQL(item.Datasql, args...).Query().List()
  394. if err != nil {
  395. log.Println("UpdataPush-error-2: ", err)
  396. continue
  397. }
  398. if len(data) > 0 {
  399. databyte, err := json.Marshal(data)
  400. if err != nil {
  401. log.Println("UpdataPush-error-3: ", err)
  402. continue
  403. }
  404. var method string
  405. // if item.Datatype == 4 {
  406. // continue
  407. // method = "uploadnewdiliverdata"
  408. // }
  409. UDPostPush1(fmt.Sprintf(item.Package, string(databyte), len(data)), method)
  410. }
  411. if len(idList) > 0 {
  412. _, err := tx.SQL(fmt.Sprintf(" update downloadedplan_log set status = 1 where id in (%s)", strings.Join(idList, ","))).Execute()
  413. if err != nil {
  414. log.Println("UpdataPush-error-4: ", err)
  415. continue
  416. }
  417. }
  418. } else {
  419. targetdataList := strings.Split(item.Targetdata, ",")
  420. var args []interface{}
  421. for _, targetdata := range targetdataList {
  422. if targetdata == "pastureid" {
  423. args = append(args, pastureinfo.Pastureid)
  424. } else if targetdata == "idlist" {
  425. // args = append(args, strings.Join(idList, ","))
  426. item.Datasql = strings.ReplaceAll(item.Datasql, "idlist", strings.Join(idList, ","))
  427. }
  428. }
  429. data, err := tx.SQL(item.Datasql, args...).Query().List()
  430. if err != nil {
  431. log.Println("UpdataPush-error-5: ", err)
  432. // return err
  433. }
  434. if len(data) > 0 {
  435. databyte, err := json.Marshal(data)
  436. if err != nil {
  437. log.Println("UpdataPush-error-6: ", err)
  438. // return err
  439. continue
  440. }
  441. // d, err := OpenFile("a.txt")
  442. // d.WriteString()
  443. UDPostPush(fmt.Sprintf(item.Package, string(databyte), len(data)), "application/json")
  444. UDPostPush1(fmt.Sprintf(item.Package, string(databyte), len(data)), "")
  445. }
  446. }
  447. }
  448. }
  449. return nil
  450. }
  451. // OpenFile 判断文件是否存在 存在则OpenFile 不存在则Create
  452. func OpenFile(filename string) (*os.File, error) {
  453. if _, err := os.Stat(filename); os.IsNotExist(err) {
  454. fmt.Println("文件不存在")
  455. return os.Create(filename) //创建文件
  456. }
  457. fmt.Println("文件存在")
  458. return os.OpenFile(filename, os.O_APPEND, 0666) //打开文件
  459. }
  460. func UpdateDown(ctx context.Context, tx *xorm.Session, idList []string, pastureinfo *udPastureInfo, company string) error {
  461. downList := make([]*ScheduledDownInfo, 0)
  462. down := tx.Table("scheduled_down")
  463. if company != "" {
  464. down.Where("company = ? ", company)
  465. }
  466. down.Where("manual = 1")
  467. err := down.Find(&downList)
  468. if err != nil {
  469. log.Println("UpdateDown-error-1: ", err)
  470. return err
  471. }
  472. for _, item := range downList {
  473. list := httpGetMC(item.Addres, item.Targetdata)
  474. if item.Methods != "" {
  475. s := ScheduledDown{}
  476. value := reflect.ValueOf(&s)
  477. f := value.MethodByName(item.Methods)
  478. f.Call([]reflect.Value{reflect.ValueOf(pastureinfo.Pastureid), reflect.ValueOf(list)})
  479. // value := reflect.ValueOf(&s)
  480. // f := value.MethodByName("Ccaa")
  481. // f.Call([]reflect.Value{reflect.ValueOf(list)})
  482. } else {
  483. childList := make([]*ScheduledDownChildInfo, 0)
  484. child := tx.Table("scheduled_down")
  485. child.Where("parentid = ? ", item.Id)
  486. err = child.Find(&childList)
  487. if err != nil {
  488. log.Println("UpdateDown-error-2: ", err)
  489. return err
  490. }
  491. if len(childList) > 0 {
  492. tx.Begin()
  493. for _, c := range childList {
  494. fieldnames := strings.Split(c.Fieldname, ",")
  495. for _, data := range list {
  496. var args []interface{}
  497. dataMap := data.(map[string]interface{})
  498. for _, fieldname := range fieldnames {
  499. args = append(args, dataMap[fieldname])
  500. }
  501. _, err = tx.SQL(c.Dosql, args...).Execute()
  502. if err != nil {
  503. tx.Rollback()
  504. log.Println("UpdateDown-error-3: ", err)
  505. return err
  506. }
  507. }
  508. }
  509. err := tx.Commit()
  510. if err != nil {
  511. tx.Rollback()
  512. log.Println("UpdateDown-error-4: ", err)
  513. return err
  514. }
  515. }
  516. }
  517. }
  518. return nil
  519. }
  520. func httpGetMC(url, targetdata string) []interface{} {
  521. // url := fmt.Sprintf("https://wdc.unidairy.cn/copartner_downloads/?farmId=%s&method=%s", farmId, method)
  522. res, err := http.Get(url)
  523. if err != nil {
  524. return nil
  525. }
  526. robots, err := ioutil.ReadAll(res.Body)
  527. res.Body.Close()
  528. if err != nil {
  529. return nil
  530. }
  531. var data map[string][]interface{}
  532. json.Unmarshal(robots, &data)
  533. return data[targetdata]
  534. }
  535. type ScheduledDown struct {
  536. }
  537. func (h *ScheduledDown) SyncFeed(pastureid string, feedList []interface{}) {
  538. tx := restful.Engine.NewSession()
  539. defer tx.Close()
  540. err := tx.Begin()
  541. if err != nil {
  542. tx.Rollback()
  543. logs.Error("syncFeed-error-1:", err)
  544. return
  545. }
  546. for _, f := range feedList {
  547. feed := f.(map[string]interface{})
  548. var feedcode, fname, fclass, fclassid, dry interface{}
  549. if _, ok := feed["feedcode"]; ok {
  550. feedcode = feed["feedcode"]
  551. }
  552. if _, ok := feed["feedname"]; ok {
  553. fname = feed["feedname"]
  554. }
  555. if _, ok := feed["feedclass"]; ok {
  556. fclass = feed["feedclass"]
  557. }
  558. if _, ok := feed["drymatter"]; ok {
  559. dry = feed["drymatter"]
  560. }
  561. fclassExist, err := tx.SQL(" select id from feedclass where pastureid = ? and fcname = ?", pastureid, fclass).Exist()
  562. if err != nil {
  563. tx.Rollback()
  564. logs.Error("syncFeed-error-2:", err)
  565. return
  566. }
  567. if fclassExist {
  568. fclassDataList, err := tx.SQL(" select id from feedclass where pastureid = ? and fcname = ?", pastureid, fclass).QueryString()
  569. if err != nil {
  570. tx.Rollback()
  571. logs.Error("syncFeed-error-3:", err)
  572. return
  573. }
  574. for _, fclassData := range fclassDataList {
  575. fclassid = fclassData["id"]
  576. }
  577. } else {
  578. ids, err := setting.SnowIds.NextId()
  579. if err != nil {
  580. ids = time.Now().UnixNano()
  581. logging.Info("create SnowIds err", err)
  582. }
  583. _, 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 =? ))",
  584. ids, pastureid, fclass, fclass, fclass, ids, pastureid).Execute()
  585. if err != nil {
  586. tx.Rollback()
  587. logs.Error("syncFeed-error-4:", err)
  588. return
  589. }
  590. fclassid = ids
  591. }
  592. ids, err := setting.SnowIds.NextId()
  593. if err != nil {
  594. ids = time.Now().UnixNano()
  595. logging.Info("create SnowIds err", err)
  596. }
  597. insertSql := `insert into feed(id,pastureid,feedcode,fname,fclassid,fclass,dry)VALUES(?,?,?,?,?,?,?)
  598. ON DUPLICATE KEY UPDATE fname = ? ,dry = ? `
  599. _, err = tx.SQL(insertSql, ids, pastureid, feedcode, fname, fclassid, fclass, dry, fname, dry).Execute()
  600. fmt.Println(feedcode, fname, fclassid)
  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. udFeedSync(pastureinfo)
  1017. })
  1018. c3.Start()
  1019. }
  1020. func abnormalMixingDelay(target []string, pastureId string, serviceId int64) {
  1021. tx2 := restful.Engine.NewSession()
  1022. defer tx2.Close()
  1023. now := time.Now().Format("2006-01-02")
  1024. 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()
  1025. if err != nil {
  1026. logs.Error("abnormalMixingDelay-error-1:", err)
  1027. return
  1028. }
  1029. if len(dataList) <= 0 {
  1030. return
  1031. }
  1032. local, _ := time.LoadLocation("Asia/Shanghai")
  1033. for _, data := range dataList {
  1034. 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 ,
  1035. d.datacaptureno,(select pasture_name from pasture where pastureid = ?) as pasturename,round(de.actualweightminus,2) actualweightminus from downloadplandtl1_exec de
  1036. join downloadedplan d on de.pid = d.id where de.pid = ? and de.sort = ? `, pastureId, data["planid"], data["sort"]).Query().List()
  1037. if err != nil {
  1038. logs.Error("abnormalMixingDelay-error-2:", err)
  1039. return
  1040. }
  1041. for _, plan := range planList {
  1042. fmt.Println(plan["processtime"])
  1043. fmt.Println(fmt.Sprintf("%s %v", time.Now().Format("2006-01-02"), plan["processtime"]), local)
  1044. showTime, _ := time.Parse("2006-01-02 15:04:05", fmt.Sprintf("%s %v", time.Now().Format("2006-01-02"), plan["processtime"]))
  1045. nowTime, _ := time.Parse("2006-01-02 15:04:05", fmt.Sprintf("%s 00:00:00", time.Now().Format("2006-01-02")))
  1046. // showTime, _ := time.ParseInLocation("2006-01-02 15:04:05", fmt.Sprintf("%s %v", time.Now().Format("2006-01-02"), plan["processtime"]), local)
  1047. // nowTime, _ := time.ParseInLocation("2006-01-02 15:04:05", fmt.Sprintf("%s 00:00:00", time.Now().Format("2006-01-02")), local)
  1048. if (showTime.Unix()-nowTime.Unix())/60 < plan["stirdelay"].(int64)-plan["deviation"].(int64) || (showTime.Unix()-nowTime.Unix())/60 > plan["stirdelay"].(int64)+plan["deviation"].(int64) {
  1049. var sendList []interface{}
  1050. // sendStr := fmt.Sprintf("操作编号:%v\n牧场:%s\nTMR名称:%v\n描述:%v\n饲料名称:%v\n计划重量(kg):%v\n实际重量(kg):%v\n过程时间:%v",
  1051. // plan["projname"], plan["pasturename"], plan["tmrtname"], plan["name"], plan["fname"], plan["lweight"], plan["actualweightminus"], plan["processtime"])
  1052. sendMap1 := make(map[string]interface{}, 0)
  1053. sendMap1["value"] = fmt.Sprintf("%s%v", "混料搅拌延时异常", plan["projname"])
  1054. // sendMap1["color"] = "#173177"
  1055. sendList = append(sendList, sendMap1)
  1056. sendMap4 := make(map[string]interface{}, 0)
  1057. sendMap4["value"] = fmt.Sprintf("%v-%v", plan["tmrtname"], plan["fname"])
  1058. // sendMap4["color"] = "#173177"
  1059. sendList = append(sendList, sendMap4)
  1060. sendMap2 := make(map[string]interface{}, 0)
  1061. sendMap2["value"] = fmt.Sprintf("计划%v,实际%v", plan["lweight"], plan["actualweightminus"])
  1062. // sendMap2["color"] = "#173177"
  1063. sendList = append(sendList, sendMap2)
  1064. sendMap5 := make(map[string]interface{}, 0)
  1065. sendMap5["value"] = fmt.Sprintf("过程时间:%v", plan["processtime"])
  1066. // sendMap5["color"] = "#173177"
  1067. sendList = append(sendList, sendMap5)
  1068. sendMap3 := make(map[string]interface{}, 0)
  1069. sendMap3["value"] = plan["pasturename"]
  1070. // sendMap3["color"] = "#173177"
  1071. sendList = append(sendList, sendMap3)
  1072. wxPush(target, sendList, pastureId, serviceId)
  1073. }
  1074. _, err := tx2.SQL(` update downloadplandtl1_log set abnormalMixingDelay = 1 where id = ? `, data["id"]).Execute()
  1075. if err != nil {
  1076. logs.Error("abnormalMixingDelay-error-3:", err)
  1077. return
  1078. }
  1079. }
  1080. }
  1081. }
  1082. func endOfShift(target []string, pastureId string, serviceId int64) {
  1083. tx := restful.Engine.NewSession()
  1084. defer tx.Close()
  1085. now := time.Now().Format("2006-01-02")
  1086. logList, err := tx.SQL(` select times from downloadedplan_log where date = ? and classes = 0 group by times `, now).Query().List()
  1087. if err != nil {
  1088. logs.Error("endOfShift-error-1:", err)
  1089. return
  1090. }
  1091. for _, item := range logList {
  1092. exist, err := tx.SQL(` select id from downloadedplan where mydate = ? and times = ? and iscompleted = 0 and enable = 1 `, now, item["times"]).Exist()
  1093. if err != nil {
  1094. logs.Error("endOfShift-error-2:", err)
  1095. return
  1096. }
  1097. if !exist {
  1098. hlList, err := tx.SQL(` select ( select count(1) from downloadedplan where times = d.times and mydate = d.mydate ) as cltrains,
  1099. round(sum(de.lweight),2) lweight,round(sum(de.actualweightminus),2) actualweightminus ,
  1100. 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,
  1101. ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) correct,
  1102. IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0)),0) correctcount,
  1103. 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
  1104. from downloadedplan d
  1105. join downloadplandtl1_exec de on de.pid = d.id
  1106. where d.times = ? and d.mydate = ? and lpplantype in(0,1) group by d.times`, item["times"], now).Query().List()
  1107. if err != nil {
  1108. logs.Error("endOfShift-error-3:", err)
  1109. return
  1110. }
  1111. slList, err := tx.SQL(` select round(sum(de.lweight),2) lweight,round(sum(de.actualweightminus),2) actualweightminus ,
  1112. 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,
  1113. ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) correct,
  1114. IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0)),0) correctcount,
  1115. 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
  1116. from downloadedplan d
  1117. join downloadplandtl2 de on de.pid = d.id
  1118. where d.times = ? and d.mydate = ? and lpplantype in(0,2) group by d.times `, item["times"], now).Query().List()
  1119. if err != nil {
  1120. logs.Error("endOfShift-error-4:", err)
  1121. return
  1122. }
  1123. data := make(map[string]interface{})
  1124. for _, hl := range hlList {
  1125. data["cltrains"] = hl["cltrains"]
  1126. // data["hllweight"] = hl["lweight"]
  1127. data["hlactualweightminus"] = hl["actualweightminus"]
  1128. data["hlaccurate"] = hl["accurate"]
  1129. data["hlcorrect"] = hl["correct"]
  1130. data["hlcorrectcount"] = hl["correctcount"]
  1131. // data["hlprocesstime"] = util.TimeTransformation(hl["processtime"].(int64))
  1132. data["hlwcz"] = hl["wcz"]
  1133. }
  1134. for _, sl := range slList {
  1135. // data["sllweight"] = sl["lweight"]
  1136. data["slactualweightminus"] = sl["actualweightminus"]
  1137. data["slaccurate"] = sl["accurate"]
  1138. data["slcorrect"] = sl["correct"]
  1139. data["slcorrectcount"] = sl["correctcount"]
  1140. // data["slprocesstime"] = util.TimeTransformation(sl["processtime"].(int64))
  1141. data["slwcz"] = sl["wcz"]
  1142. }
  1143. 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",
  1144. item["times"], data["cltrains"], data["hlactualweightminus"], data["hlwcz"], data["hlaccurate"], data["hlcorrect"], data["hlcorrectcount"],
  1145. data["slactualweightminus"], data["slwcz"], data["slaccurate"], data["slcorrect"], data["slcorrectcount"])
  1146. var sendList []interface{}
  1147. sendMap1 := make(map[string]interface{}, 0)
  1148. sendMap1["value"] = "班次完成"
  1149. sendMap1["color"] = "#173177"
  1150. sendList = append(sendList, sendMap1)
  1151. sendMap4 := make(map[string]interface{}, 0)
  1152. sendMap4["value"] = sendStr
  1153. sendMap4["color"] = "#173177"
  1154. sendList = append(sendList, sendMap4)
  1155. sendMap2 := make(map[string]interface{}, 0)
  1156. // sendMap2["value"] = plan["processtime"]
  1157. sendMap2["value"] = time.Now().Format("2006-01-02 15:04:05")
  1158. sendMap2["color"] = "#173177"
  1159. sendList = append(sendList, sendMap2)
  1160. sendMap5 := make(map[string]interface{}, 0)
  1161. sendMap5["value"] = "无备注"
  1162. sendMap5["color"] = "#173177"
  1163. sendList = append(sendList, sendMap5)
  1164. wxPush(target, sendList, pastureId, serviceId)
  1165. _, err = tx.SQL(` update downloadedplan_log set classes = 1 where date = ? and times = ? `, now, item["times"]).Execute()
  1166. if err != nil {
  1167. logs.Error("endOfShift-error-5:", err)
  1168. return
  1169. }
  1170. }
  1171. }
  1172. }
  1173. func plansToComplete(target []string, pastureId string, serviceId int64) {
  1174. tx := restful.Engine.NewSession()
  1175. defer tx.Close()
  1176. now := time.Now()
  1177. exist, err := tx.SQL(` select id from downloadedplan_log where date = ? and dailyplan = 0 `, now).Exist()
  1178. if err != nil {
  1179. logs.Error("plansToComplete-error-1:", err)
  1180. return
  1181. }
  1182. if exist {
  1183. downloadedplanExist, err := tx.SQL(` select id from downloadedplan where mydate = ? and iscompleted = 0 and enable = 1 `, now).Exist()
  1184. if err != nil {
  1185. logs.Error("plansToComplete-error-2:", err)
  1186. return
  1187. }
  1188. if !downloadedplanExist {
  1189. 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,
  1190. sum(de.lweight)lweight,sum(de.actualweightminus)actualweightminus ,
  1191. 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,
  1192. ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) correct,
  1193. IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0)),0) correctcount,
  1194. 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
  1195. from downloadedplan d
  1196. join downloadplandtl1_exec de on de.pid = d.id
  1197. where d.mydate = ? and lpplantype in(0,1) group by d.mydate`, now, now).Query().List()
  1198. if err != nil {
  1199. logs.Error("plansToComplete-error-3:", err)
  1200. return
  1201. }
  1202. slList, err := tx.SQL(` select sum(de.lweight)lweight,sum(de.actualweightminus)actualweightminus ,
  1203. 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,
  1204. ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) correct,
  1205. IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0)),0) correctcount,
  1206. 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
  1207. from downloadedplan d
  1208. join downloadplandtl2 de on de.pid = d.id
  1209. where d.mydate = ? and lpplantype in(0,2) group by d.mydate `, now).Query().List()
  1210. if err != nil {
  1211. logs.Error("plansToComplete-error-4:", err)
  1212. return
  1213. }
  1214. data := make(map[string]interface{})
  1215. for _, hl := range hlList {
  1216. data["timescount"] = hl["timescount"]
  1217. data["cltrains"] = hl["cltrains"]
  1218. data["hllweight"] = hl["lweight"]
  1219. data["hlactualweightminus"] = hl["actualweightminus"]
  1220. data["hlaccurate"] = hl["accurate"]
  1221. data["hlcorrect"] = hl["correct"]
  1222. data["hlcorrectcount"] = hl["correctcount"]
  1223. data["hlwcz"] = hl["wcz"]
  1224. }
  1225. for _, sl := range slList {
  1226. data["sllweight"] = sl["lweight"]
  1227. data["slactualweightminus"] = sl["actualweightminus"]
  1228. data["slaccurate"] = sl["accurate"]
  1229. data["slcorrect"] = sl["correct"]
  1230. data["slcorrectcount"] = sl["correctcount"]
  1231. data["slwcz"] = sl["wcz"]
  1232. }
  1233. 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",
  1234. data["timescount"], data["cltrains"], data["hlactualweightminus"], data["hlwcz"], data["hlaccurate"], data["hlcorrect"], data["hlcorrectcount"],
  1235. data["slactualweightminus"], data["slwcz"], data["slaccurate"], data["slcorrect"], data["slcorrectcount"])
  1236. var sendList []interface{}
  1237. sendMap1 := make(map[string]interface{}, 0)
  1238. sendMap1["value"] = "每日计划完成"
  1239. sendMap1["color"] = "#173177"
  1240. sendList = append(sendList, sendMap1)
  1241. sendMap4 := make(map[string]interface{}, 0)
  1242. sendMap4["value"] = sendStr
  1243. sendMap4["color"] = "#173177"
  1244. sendList = append(sendList, sendMap4)
  1245. sendMap2 := make(map[string]interface{}, 0)
  1246. // sendMap2["value"] = plan["processtime"]
  1247. sendMap2["value"] = time.Now().Format("2006-01-02 15:04:05")
  1248. sendMap2["color"] = "#173177"
  1249. sendList = append(sendList, sendMap2)
  1250. sendMap5 := make(map[string]interface{}, 0)
  1251. sendMap5["value"] = "无备注"
  1252. sendMap5["color"] = "#173177"
  1253. sendList = append(sendList, sendMap5)
  1254. wxPush(target, sendList, pastureId, serviceId)
  1255. _, err = tx.SQL(` update downloadedplan_log set dailyplan = 1 where date = ? `, now).Execute()
  1256. if err != nil {
  1257. logs.Error("plansToComplete-error-5:", err)
  1258. return
  1259. }
  1260. }
  1261. }
  1262. }
  1263. func AddFormulaIssued(c *gin.Context) {
  1264. appG := app.Gin{C: c}
  1265. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1266. tempval_ := make(map[string]interface{})
  1267. tempCommon := make(map[string]interface{})
  1268. tempval := make([]map[string]interface{}, 0)
  1269. err := json.Unmarshal(dataByte, &tempval_)
  1270. logging.Info("AddFormulaIssued ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1271. if err != nil {
  1272. } else {
  1273. if v, ok := tempval_["data"].([]interface{}); ok {
  1274. for _, Tvalue := range v {
  1275. if v1, ok := Tvalue.(map[string]interface{}); ok {
  1276. tempval = append(tempval, v1)
  1277. }
  1278. }
  1279. }
  1280. tx := restful.Engine.NewSession()
  1281. err := tx.Begin()
  1282. if err != nil {
  1283. logging.Error("tx.Begin 事务启动失败__error:", err)
  1284. }
  1285. defer func() {
  1286. switch {
  1287. case err != nil:
  1288. if tx != nil {
  1289. tx.Rollback()
  1290. }
  1291. default:
  1292. if tx != nil {
  1293. err = tx.Commit()
  1294. }
  1295. }
  1296. if tx != nil {
  1297. tx.Close()
  1298. }
  1299. }()
  1300. if err == nil {
  1301. if tempv, exists := c.Get("jwt_username"); exists {
  1302. tempCommon["jwt_username"] = tempv.(string)
  1303. }
  1304. for _, paramvalue := range tempval {
  1305. if _, ok := paramvalue["resultname"]; !ok {
  1306. paramvalue["resultname"] = paramvalue["name"]
  1307. }
  1308. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  1309. if err != nil {
  1310. logging.Error("AddFormulaIssued error-1:", err)
  1311. break
  1312. }
  1313. }
  1314. if err == nil {
  1315. var temid, jtpastureid, tcode, tname, ccname, fttype string
  1316. for _, tem := range tempval {
  1317. if tem["name"].(string) == "insertSpotList" {
  1318. for _, item := range tem["resultmaps"].(map[string]interface{})["list"].([]interface{}) {
  1319. itemmap := item.(map[string]interface{})
  1320. jtpastureid = itemmap["pastureid"].(string)
  1321. temid = itemmap["id"].(string)
  1322. }
  1323. }
  1324. }
  1325. feedtempletList, err := tx.SQL(` select tname,tcode,id,ccname,fttype from feedtemplet where id = ? and pastureid = ? `, temid, jtpastureid).Query().List()
  1326. if err != nil {
  1327. logs.Error("AddFormulaIssued-error-2:", err)
  1328. return
  1329. }
  1330. for _, feedtemplet := range feedtempletList {
  1331. tcode = feedtemplet["tcode"].(string)
  1332. tname = feedtemplet["tname"].(string)
  1333. ccname = feedtemplet["ccname"].(string)
  1334. fttype = feedtemplet["fttype"].(string)
  1335. }
  1336. for _, tem := range tempval {
  1337. if tem["name"].(string) == "insertSpotList2" {
  1338. for _, item := range tem["resultmaps"].(map[string]interface{})["list"].([]interface{}) {
  1339. itemmap := item.(map[string]interface{})
  1340. dataList, err := tx.SQL(` select user,function,id,service_id from remind where pastureid = ? and function = ? `, itemmap["id"], "formulaIssued").Query().List()
  1341. if err != nil {
  1342. logs.Error("AddFormulaIssued-error-3:", err)
  1343. return
  1344. }
  1345. for _, data := range dataList {
  1346. var openIdList []string
  1347. if _, ok := data["user"]; ok {
  1348. openIdList = strings.Split(data["user"].(string), ",")
  1349. }
  1350. var sendList []interface{}
  1351. sendStr := fmt.Sprintf("配方名称:%v\n配方编码:%s\n牲畜类别:%v\n配方类型:%v",
  1352. tname, tcode, ccname, fttype)
  1353. sendMap1 := make(map[string]interface{}, 0)
  1354. sendMap1["value"] = "混料准确率异常"
  1355. sendMap1["color"] = "#173177"
  1356. sendList = append(sendList, sendMap1)
  1357. sendMap4 := make(map[string]interface{}, 0)
  1358. sendMap4["value"] = sendStr
  1359. sendMap4["color"] = "#173177"
  1360. sendList = append(sendList, sendMap4)
  1361. sendMap2 := make(map[string]interface{}, 0)
  1362. sendMap2["value"] = time.Now().Format("2006-01-02 15:04:05")
  1363. sendMap2["color"] = "#173177"
  1364. sendList = append(sendList, sendMap2)
  1365. sendMap5 := make(map[string]interface{}, 0)
  1366. sendMap5["value"] = "无备注"
  1367. sendMap5["color"] = "#173177"
  1368. sendList = append(sendList, sendMap5)
  1369. wxPush(openIdList, sendList, itemmap["id"].(string), data["service_id"].(int64))
  1370. }
  1371. }
  1372. break
  1373. }
  1374. }
  1375. if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
  1376. appG.Response(http.StatusOK, e.SUCCESS, tempval)
  1377. } else {
  1378. appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
  1379. }
  1380. } else {
  1381. msg := geterrmsg(err.Error())
  1382. appG.Response(http.StatusOK, e.ERROR, msg)
  1383. }
  1384. }
  1385. }
  1386. if err != nil {
  1387. msg := geterrmsg(err.Error())
  1388. appG.Response(http.StatusOK, e.ERROR, msg)
  1389. appG.Response(http.StatusOK, 200, nil)
  1390. }
  1391. }
  1392. func AddBigInventory(c *gin.Context) {
  1393. appG := app.Gin{C: c}
  1394. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1395. tempval_ := make(map[string]interface{})
  1396. tempCommon := make(map[string]interface{})
  1397. tempval := make([]map[string]interface{}, 0)
  1398. err := json.Unmarshal(dataByte, &tempval_)
  1399. logging.Info("AddBigInventory ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1400. if err != nil {
  1401. } else {
  1402. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  1403. tempCommon = v
  1404. }
  1405. if v, ok := tempval_["data"].([]interface{}); ok {
  1406. for _, Tvalue := range v {
  1407. if v1, ok := Tvalue.(map[string]interface{}); ok {
  1408. tempval = append(tempval, v1)
  1409. }
  1410. }
  1411. }
  1412. tx := restful.Engine.NewSession()
  1413. err := tx.Begin()
  1414. if err != nil {
  1415. logging.Error("tx.Begin 事务启动失败__error:", err)
  1416. }
  1417. defer func() {
  1418. switch {
  1419. case err != nil:
  1420. if tx != nil {
  1421. tx.Rollback()
  1422. }
  1423. default:
  1424. if tx != nil {
  1425. err = tx.Commit()
  1426. }
  1427. }
  1428. if tx != nil {
  1429. tx.Close()
  1430. }
  1431. }()
  1432. if err == nil {
  1433. if tempv, exists := c.Get("jwt_username"); exists {
  1434. tempCommon["jwt_username"] = tempv.(string)
  1435. }
  1436. for _, paramvalue := range tempval {
  1437. if _, ok := paramvalue["resultname"]; !ok {
  1438. paramvalue["resultname"] = paramvalue["name"]
  1439. }
  1440. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  1441. if err != nil {
  1442. logging.Error("AddBigInventory error-1:", err)
  1443. break
  1444. }
  1445. }
  1446. if err == nil {
  1447. // var pastureid, date string
  1448. // for _, tem := range tempval {
  1449. // if tem["name"].(string) == "insertBigInventory" {
  1450. // parammaps := tem["parammaps"].(map[string]interface{})
  1451. // pastureid = parammaps["pastureid"].(string)
  1452. // date = parammaps["inventorydate"].(string)
  1453. // }
  1454. // }
  1455. // feedinventoryList, err := tx.SQL(`SELECT
  1456. // remark,DATE_FORMAT(inventorydate, '%Y-%m-%d') inventorydate,createuser,
  1457. // TRIM(f.id) id,
  1458. // TRIM(f.pastureid) pastureid,
  1459. // 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,
  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) moreWeight ,
  1461. // 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
  1462. // FROM
  1463. // feedinventory f
  1464. // WHERE f.pastureid = ? and f.inventorydate=? `, pastureid, date).Query().List()
  1465. // if err != nil {
  1466. // logs.Error("AddBigInventory-error-2:", err)
  1467. // return
  1468. // }
  1469. // dataList, err := tx.SQL(` select user,function,id,service_id from remind where pastureid = ? and function = ? `, pastureid, "formulaIssued").Query().List()
  1470. // if err != nil {
  1471. // logs.Error("AddBigInventory-error-3:", err)
  1472. // return
  1473. // }
  1474. // for _, data := range dataList {
  1475. // var openIdList []string
  1476. // if _, ok := data["user"]; ok {
  1477. // openIdList = strings.Split(data["user"].(string), ",")
  1478. // }
  1479. // var createuser, lessWeight, moreWeight, differWeight interface{}
  1480. // for _, f := range feedinventoryList {
  1481. // createuser = f["createuser"]
  1482. // lessWeight = f["lessWeight"]
  1483. // moreWeight = f["moreWeight"]
  1484. // differWeight = f["differWeight"]
  1485. // }
  1486. // var sendList []interface{}
  1487. // sendStr := fmt.Sprintf("盘点人:%v\n盘盈库存(kg):%v\n盘亏库存(kg):%v\n盈亏净值(kg):%v",
  1488. // createuser, moreWeight, lessWeight, differWeight)
  1489. // sendMap1 := make(map[string]interface{}, 0)
  1490. // sendMap1["value"] = "库存盘点"
  1491. // sendMap1["color"] = "#173177"
  1492. // sendList = append(sendList, sendMap1)
  1493. // sendMap4 := make(map[string]interface{}, 0)
  1494. // sendMap4["value"] = sendStr
  1495. // sendMap4["color"] = "#173177"
  1496. // sendList = append(sendList, sendMap4)
  1497. // sendMap2 := make(map[string]interface{}, 0)
  1498. // sendMap2["value"] = time.Now().Format("2006-01-02 15:04:05")
  1499. // sendMap2["color"] = "#173177"
  1500. // sendList = append(sendList, sendMap2)
  1501. // sendMap5 := make(map[string]interface{}, 0)
  1502. // sendMap5["value"] = "无备注"
  1503. // sendMap5["color"] = "#173177"
  1504. // sendList = append(sendList, sendMap5)
  1505. // wxPush(openIdList, sendList, pastureid, data["service_id"].(int64))
  1506. // }
  1507. if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
  1508. appG.Response(http.StatusOK, e.SUCCESS, tempval)
  1509. } else {
  1510. appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
  1511. }
  1512. } else {
  1513. msg := geterrmsg(err.Error())
  1514. appG.Response(http.StatusOK, e.ERROR, msg)
  1515. }
  1516. }
  1517. }
  1518. if err != nil {
  1519. msg := geterrmsg(err.Error())
  1520. appG.Response(http.StatusOK, e.ERROR, msg)
  1521. }
  1522. }
  1523. func inventoryWarning(target []string, pastureId string, serviceId int64) {
  1524. tx := restful.Engine.NewSession()
  1525. defer tx.Close()
  1526. feedstorageList, err := tx.SQL(`
  1527. SELECT
  1528. (select fname from feed where pastureid =fs.pastureid and id = fs.feedid ) feedname,
  1529. fs.stockweight,round(fs.lweight,2) avgweight, if (fs.stockweight<=0,0, FLOOR(fs.stockweight/fs.lweight)) ldays,
  1530. TRIM(fs.feedid) feedid,
  1531. TRIM(fs.pastureid) pastureid,
  1532. DATE_FORMAT((select max(date) from fswarnhis where pastureid = fs.pastureid and feedid = fs.feedid ), '%Y-%m-%d') lastdate
  1533. FROM (SELECT fs.pushstatus,
  1534. fs.id,
  1535. fs.feedname,fs.stockweight,
  1536. fs.feedid feedid,
  1537. fs.pastureid pastureid,DATE_FORMAT(NOW(), '%Y-%m-%d') lastdate,
  1538. (SELECT SUM(d.lweight)/7 lweight FROM downloadplandtl1 d WHERE d.pastureid = fs.pastureid
  1539. AND date >= DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -7 DAY), '%Y-%m-%d')
  1540. AND date <DATE_FORMAT(NOW(), '%Y-%m-%d') AND d.fid = fs.feedid) lweight
  1541. FROM feedstorage fs) fs
  1542. WHERE fs.pastureid=? AND fs.stockweight< fs.lweight*(SELECT inforvalue FROM sysopt WHERE sysopt.pastureid = fs.pastureid
  1543. AND inforname = 'repertoryWarn')
  1544. ORDER BY ldays ,stockweight `).Query().List()
  1545. if err != nil {
  1546. logs.Error("inventoryWarning-error-1:", err)
  1547. return
  1548. }
  1549. for _, f := range feedstorageList {
  1550. var sendList []interface{}
  1551. sendStr := fmt.Sprintf("饲料名称:%v\n库存量(kg):%s\n近7天平均计划量:%v\n剩余使用天数:%v",
  1552. f["feedname"], f["stockweight"], f["lweight"], f["ldays"])
  1553. sendMap1 := make(map[string]interface{}, 0)
  1554. sendMap1["value"] = "库存预警"
  1555. sendMap1["color"] = "#173177"
  1556. sendList = append(sendList, sendMap1)
  1557. sendMap4 := make(map[string]interface{}, 0)
  1558. sendMap4["value"] = sendStr
  1559. sendMap4["color"] = "#173177"
  1560. sendList = append(sendList, sendMap4)
  1561. sendMap2 := make(map[string]interface{}, 0)
  1562. sendMap2["value"] = time.Now().Format("2006-01-02 15:04:05")
  1563. sendMap2["color"] = "#173177"
  1564. sendList = append(sendList, sendMap2)
  1565. sendMap5 := make(map[string]interface{}, 0)
  1566. sendMap5["value"] = "无备注"
  1567. sendMap5["color"] = "#173177"
  1568. sendList = append(sendList, sendMap5)
  1569. wxPush(target, sendList, pastureId, serviceId)
  1570. }
  1571. }
  1572. func udFeedpSync(pastureinfo *udPastureInfo) error {
  1573. tx := restful.Engine.NewSession()
  1574. defer tx.Close()
  1575. downList := make([]*ScheduledDownInfo, 0)
  1576. down := tx.Table("scheduled_down")
  1577. down.Where("company = ? ", "ud")
  1578. down.Where("methods = ? ", "SyncFeedp")
  1579. err := down.Find(&downList)
  1580. if err != nil {
  1581. log.Println("UpdateDown-error-1: ", err)
  1582. return err
  1583. }
  1584. for _, item := range downList {
  1585. list := httpGetMC(item.Addres, item.Targetdata)
  1586. if item.Methods != "" {
  1587. s := ScheduledDown{}
  1588. value := reflect.ValueOf(&s)
  1589. f := value.MethodByName(item.Methods)
  1590. f.Call([]reflect.Value{reflect.ValueOf(pastureinfo.Pastureid), reflect.ValueOf(list)})
  1591. }
  1592. }
  1593. return nil
  1594. }
  1595. func UdFeedpSync(c *gin.Context) {
  1596. appG := app.Gin{C: c}
  1597. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1598. fsion := gofasion.NewFasion(string(dataByte))
  1599. pastureId := fsion.Get("pastureId").ValueStr()
  1600. // pastureinfo := new(udPastureInfo)
  1601. // pastureinfo.Pastureid = pastureId
  1602. // udFeedpSync(pastureinfo)
  1603. pastureinfo := new(udPastureInfo)
  1604. pastureinfo.Pastureid = pastureId
  1605. err := udFeedpSync(pastureinfo)
  1606. if err != nil {
  1607. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1608. return
  1609. }
  1610. appG.Response(http.StatusOK, e.SUCCESS, true)
  1611. // return
  1612. }
  1613. func udFeedSync(pastureinfo *udPastureInfo) error {
  1614. tx := restful.Engine.NewSession()
  1615. defer tx.Close()
  1616. downList := make([]*ScheduledDownInfo, 0)
  1617. down := tx.Table("scheduled_down")
  1618. down.Where("company = ? ", "ud")
  1619. down.Where("methods = ? ", "SyncFeed")
  1620. err := down.Find(&downList)
  1621. if err != nil {
  1622. log.Println("UpdateDown-error-1: ", err)
  1623. return err
  1624. }
  1625. for _, item := range downList {
  1626. list := httpGetMC(item.Addres, item.Targetdata)
  1627. if item.Methods != "" {
  1628. s := ScheduledDown{}
  1629. value := reflect.ValueOf(&s)
  1630. f := value.MethodByName(item.Methods)
  1631. f.Call([]reflect.Value{reflect.ValueOf(pastureinfo.Pastureid), reflect.ValueOf(list)})
  1632. }
  1633. }
  1634. return nil
  1635. }