scheduled.go 62 KB

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