scheduled.go 61 KB

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