scheduled.go 60 KB

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