scheduled.go 60 KB

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