scheduled.go 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301
  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/gm"
  17. "tmr-watch/http/handle/jpud"
  18. "tmr-watch/http/handle/restful"
  19. "tmr-watch/http/handle/sap"
  20. "tmr-watch/http/handle/ymy"
  21. "tmr-watch/pkg/app"
  22. "tmr-watch/pkg/e"
  23. "tmr-watch/pkg/logging"
  24. // "../../routers/api/gm"
  25. // "../../routers/api/sap"
  26. // "../../routers/restful"
  27. "github.com/Anderson-Lu/gofasion/gofasion"
  28. "github.com/astaxie/beego/logs"
  29. "github.com/gin-gonic/gin"
  30. "github.com/robfig/cron"
  31. "github.com/xormplus/xorm"
  32. )
  33. func CronScheduled(ctx context.Context) {
  34. tx := restful.Engine.NewSession()
  35. defer tx.Close()
  36. pastureinfo := new(udPastureInfo)
  37. err := tx.SQL(`select column_default as pastureid,(select werks from pasture where pastureid = column_default) werks from information_schema.COLUMNS
  38. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  39. if err != nil {
  40. logs.Error(err)
  41. return
  42. }
  43. // duetimecst, _ := time.ParseInLocation("15:04:05", "00:10:00", time.Local)
  44. // duetimecst1, _ := time.ParseInLocation("15:04:05", "00:00:00", time.Local)
  45. // spec := fmt.Sprintf("@every %v", duetimecst.Sub(duetimecst1))
  46. // c := cron.New()
  47. // c.AddFunc(spec, func() {
  48. // tx1 := restful.Engine.NewSession()
  49. // defer tx1.Close()
  50. // exist, err := tx1.Table("notice").Where("status = 1").And("content = ? ", "downloadedplan_log").Exist()
  51. // if err != nil {
  52. // logs.Error("CronScheduled-error-1:", err)
  53. // return
  54. // }
  55. // if exist {
  56. // _, err := tx.SQL(`update notice set status = 0 where content = ? `, "downloadedplan_log").Execute()
  57. // if err != nil {
  58. // logs.Error("CronScheduled-error-2:", err)
  59. // return
  60. // }
  61. // Scheduled(ctx, tx1, pastureinfo)
  62. // }
  63. // })
  64. // c.Start()
  65. //消息提醒
  66. duetimecst2, _ := time.ParseInLocation("15:04:05", "00:01:00", time.Local)
  67. duetimecst3, _ := time.ParseInLocation("15:04:05", "00:00:00", time.Local)
  68. spec1 := fmt.Sprintf("@every %v", duetimecst2.Sub(duetimecst3))
  69. downloadplandtl1 := cron.New()
  70. downloadplandtl1.AddFunc(spec1, func() {
  71. dataList, err := tx.SQL(` select user,function,id from remind where pastureid = ? `, pastureinfo.Pastureid).Query().List()
  72. if err != nil {
  73. logs.Error("CronScheduled-error-3:", err)
  74. return
  75. }
  76. for _, data := range dataList {
  77. var openIdList []string
  78. if _, ok := data["user"]; ok {
  79. openIdList = strings.Split(data["user"].(string), ",")
  80. }
  81. if data["function"].(string) == "processAnalysisEarlyWarning" {
  82. if len(openIdList) > 0 {
  83. processAnalysisEarlyWarning(openIdList, pastureinfo.Pastureid, data["id"].(int64))
  84. }
  85. } else if data["function"].(string) == "abnormalMixingDelay" {
  86. if len(openIdList) > 0 {
  87. abnormalMixingDelay(openIdList, pastureinfo.Pastureid, data["id"].(int64))
  88. }
  89. } else if data["function"].(string) == "endOfShift" {
  90. if len(openIdList) > 0 {
  91. endOfShift(openIdList, pastureinfo.Pastureid, data["id"].(int64))
  92. }
  93. } else if data["function"].(string) == "plansToComplete" {
  94. if len(openIdList) > 0 {
  95. plansToComplete(openIdList, pastureinfo.Pastureid, data["id"].(int64))
  96. }
  97. }
  98. }
  99. })
  100. downloadplandtl1.Start()
  101. dayCron := cron.New()
  102. dayCron.AddFunc("30 23 * * *", func() {
  103. dataList, err := tx.SQL(` select user,function,id from remind where pastureid = ? and function = ? `, pastureinfo.Pastureid, "inventoryWarning").Query().List()
  104. if err != nil {
  105. logs.Error("CronScheduled-error-5:", err)
  106. return
  107. }
  108. for _, data := range dataList {
  109. var openIdList []string
  110. if _, ok := data["user"]; ok {
  111. openIdList = strings.Split(data["user"].(string), ",")
  112. }
  113. if data["function"].(string) == "inventoryWarning" {
  114. if len(openIdList) > 0 {
  115. inventoryWarning(openIdList, pastureinfo.Pastureid, data["id"].(int64))
  116. }
  117. }
  118. }
  119. })
  120. dayCron.Start()
  121. // 0 无同步 1 圣牧 2 现代牧业 3 新希望 4 乐源 5 光明ud 6 多语言京鹏ud 7 一牧云
  122. if setting.ServerSetting.SyncStatus == 1 {
  123. // 圣牧
  124. manualUdData(pastureinfo)
  125. InitMqttClient()
  126. } else if setting.ServerSetting.SyncStatus == 2 {
  127. xdmy := cron.New()
  128. err = xdmy.AddFunc("0 05 7 * * *", func() {
  129. // 现代牧业sap同步
  130. sap.SyncMaterialOutbound()
  131. sap.SyncSurplusOutbound()
  132. sap.SyncLeftoverEntry()
  133. // sap.SyncWasteuse()
  134. })
  135. xdmy.Start()
  136. InitMqttClient()
  137. } else if setting.ServerSetting.SyncStatus == 3 {
  138. duetimecst4, _ := time.ParseInLocation("15:04:05", "00:01:00", time.Local)
  139. duetimecst5, _ := time.ParseInLocation("15:04:05", "00:00:00", time.Local)
  140. spec2 := fmt.Sprintf("@every %v", duetimecst4.Sub(duetimecst5))
  141. xxw := cron.New()
  142. xxw.AddFunc(spec2, func() {
  143. XxwFeedtemplet(pastureinfo.Pastureid)
  144. xxwFeedpSync(pastureinfo.Pastureid)
  145. })
  146. xxw.Start()
  147. } else if setting.ServerSetting.SyncStatus == 4 {
  148. duetimecst4, _ := time.ParseInLocation("15:04:05", "00:01:00", time.Local)
  149. duetimecst5, _ := time.ParseInLocation("15:04:05", "00:00:00", time.Local)
  150. spec2 := fmt.Sprintf("@every %v", duetimecst4.Sub(duetimecst5))
  151. ly := cron.New()
  152. ly.AddFunc(spec2, func() {
  153. XxwFeedtemplet(pastureinfo.Pastureid)
  154. xxwFeedpSync(pastureinfo.Pastureid)
  155. })
  156. ly.Start()
  157. } else if setting.ServerSetting.SyncStatus == 5 {
  158. gmud := cron.New()
  159. err = gmud.AddFunc("0 05 7 * * *", func() {
  160. gm.GmUdSync(pastureinfo.Pastureid, pastureinfo.Werks)
  161. })
  162. gmud.Start()
  163. } else if setting.ServerSetting.SyncStatus == 6 {
  164. jp := cron.New()
  165. err = jp.AddFunc("0 05 7 * * *", func() {
  166. jpud.JPUDUdSync(pastureinfo.Pastureid, pastureinfo.Werks)
  167. })
  168. jp.Start()
  169. } else if setting.ServerSetting.SyncStatus == 7 {
  170. c := cron.New()
  171. err = c.AddFunc("0 05 7 * * *", func() {
  172. ymy.YmyCron(pastureinfo.Werks, pastureinfo.Pastureid)
  173. })
  174. c.Start()
  175. } else if setting.ServerSetting.SyncStatus == 8 {
  176. InitMqttClient()
  177. }
  178. // manualUdData(pastureinfo)
  179. // ymy.YmyCron(pastureinfo.Werks, pastureinfo.Pastureid)
  180. // //圣牧自动同步前天有进行中的任务
  181. // manualUdData(pastureinfo)
  182. // gm.GmUdSync(pastureinfo.Pastureid, pastureinfo.Werks)
  183. // jpud.UdBarSync(pastureinfo.Pastureid, pastureinfo.Werks)
  184. // jpud.UdFeedSync(pastureinfo.Pastureid, pastureinfo.Werks)
  185. // xdmy := cron.New()
  186. // err = xdmy.AddFunc("0 05 7 * * *", func() {
  187. // // // // //现代牧业sap同步
  188. // sap.SyncMaterialOutbound()
  189. // sap.SyncSurplusOutbound()
  190. // sap.SyncLeftoverEntry()
  191. // sap.SyncWasteuse()
  192. // // // // // 光明ud同步
  193. // // // fmt.Println(time.Now())
  194. // // gm.GmUdSync(pastureinfo.Pastureid, pastureinfo.Werks)
  195. // // jpud.JPUDUdSync(pastureinfo.Pastureid, pastureinfo.Werks)
  196. // })
  197. // xdmy.Start()
  198. // InitMqttClient()
  199. // yq.YqCron()
  200. //新希望配方同步定时任务
  201. // duetimecst4, _ := time.ParseInLocation("15:04:05", "00:01:00", time.Local)
  202. // duetimecst5, _ := time.ParseInLocation("15:04:05", "00:00:00", time.Local)
  203. // spec2 := fmt.Sprintf("@every %v", duetimecst4.Sub(duetimecst5))
  204. // xxw := cron.New()
  205. // xxw.AddFunc(spec2, func() {
  206. // XxwFeedtemplet(pastureinfo.Pastureid)
  207. // xxwFeedpSync(pastureinfo.Pastureid)
  208. // // windows指定要删除文件的目录
  209. // })
  210. // xxw.Start()
  211. }
  212. type ScheduledInfo struct {
  213. Id int64 `xorm:"id"`
  214. Sname string `xorm:"sname"`
  215. Action int64 `xorm:"action"`
  216. Childid int64 `xorm:"childid"`
  217. Times string `xorm:"times"`
  218. Enable string `xorm:"enable"`
  219. }
  220. type ScheduledUpInfo struct {
  221. Id int64 `xorm:"id"`
  222. Company string `xorm:"company"`
  223. Addres string `xorm:"addres"`
  224. Datatype int64 `xorm:"datatype"`
  225. Package string `xorm:"Package"`
  226. Datasql string `xorm:"datasql"`
  227. Automatic int64 `xorm:"automatic"`
  228. Manual int64 `xorm:"manual"`
  229. Targetdata string `xorm:"targetdata"`
  230. }
  231. type ScheduledDownInfo struct {
  232. Id int64 `xorm:"id"`
  233. Datatype int64 `xorm:"datatype"`
  234. Addres string `xorm:"addres"`
  235. Adressparam string `xorm:"adressparam"`
  236. Targetdata string `xorm:"targetdata"`
  237. Manual int64 `xorm:"manual"`
  238. Methods string `xorm:"methods"`
  239. }
  240. type ScheduledDownChildInfo struct {
  241. Id int64 `xorm:"id"`
  242. Parentid int64 `xorm:"parentid"`
  243. Fieldname string `xorm:"fieldname"`
  244. Checksql string `xorm:"checksql"`
  245. Dosql string `xorm:"dosql"`
  246. }
  247. func Scheduled(ctx context.Context, tx *xorm.Session, pastureinfo *udPastureInfo) {
  248. times := new(ScheduledInfo)
  249. err := tx.SQL(" select times from scheduled where action = 0 group by times").GetFirst(times).Error
  250. if err != nil {
  251. logs.Error(err)
  252. return
  253. }
  254. if times.Times == "0" {
  255. downloadedplanLogList, err := tx.SQL(` select id from downloadedplan_log where date = date_format(now(),'%Y-%m-%d') `).Query().List()
  256. if err != nil {
  257. logs.Error(err)
  258. return
  259. }
  260. ids := []string{}
  261. for _, item := range downloadedplanLogList {
  262. ids = append(ids, strconv.FormatInt(item["id"].(int64), 10))
  263. }
  264. fmt.Println(ids, time.Now())
  265. err = UpdatePush(ctx, tx, true, ids, pastureinfo, "", time.Now().Format("2006-01-02"))
  266. if err != nil {
  267. return
  268. }
  269. } else if times.Times == "1" {
  270. 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()
  271. if err != nil {
  272. logs.Error(err)
  273. return
  274. }
  275. for _, item := range downloadedplanLogList {
  276. count, err := tx.SQL(` select count(1) from downloadedplan where pastureid = ? and mydate = date_format(now(),'%Y-%m-%d')
  277. and iscompleted = 0 and times = ? and enable = 1 `,
  278. pastureinfo.Pastureid, item["times"]).Count()
  279. if err != nil {
  280. logs.Error(err)
  281. return
  282. }
  283. if count == 0 {
  284. //推送
  285. downloadedplanLogList, err := tx.SQL(` select id from downloadedplan_log where date = date_format(now(),'%Y-%m-%d')
  286. and times = ? `, item["times"]).Query().List()
  287. if err != nil {
  288. logs.Error(err)
  289. return
  290. }
  291. ids := []string{}
  292. for _, item := range downloadedplanLogList {
  293. ids = append(ids, strconv.FormatInt(item["id"].(int64), 10))
  294. }
  295. err = UpdatePush(ctx, tx, true, ids, pastureinfo, "", time.Now().Format("2006-01-02"))
  296. if err != nil {
  297. return
  298. }
  299. }
  300. }
  301. } else if times.Times == "2" {
  302. 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 ",
  303. pastureinfo.Pastureid).Count()
  304. if err != nil {
  305. logs.Error(err)
  306. return
  307. }
  308. if count == 0 {
  309. //推送
  310. downloadedplanLogList, err := tx.SQL(` select id from downloadedplan_log where date = date_format(now(),'%Y-%m-%d') `).Query().List()
  311. if err != nil {
  312. logs.Error(err)
  313. return
  314. }
  315. ids := []string{}
  316. for _, item := range downloadedplanLogList {
  317. ids = append(ids, strconv.FormatInt(item["id"].(int64), 10))
  318. }
  319. err = UpdatePush(ctx, tx, true, ids, pastureinfo, "", time.Now().Format("2006-01-02"))
  320. if err != nil {
  321. return
  322. }
  323. }
  324. }
  325. }
  326. func UpdateScheduledStatus(c *gin.Context) {
  327. appG := app.Gin{C: c}
  328. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  329. fsion := gofasion.NewFasion(string(dataByte))
  330. idList := fsion.Get("id").Array()
  331. automatic := fsion.Get("automatic").ValueStr()
  332. manual := fsion.Get("manual").ValueStr()
  333. company := fsion.Get("company").ValueStr()
  334. //type 0 上传,1 下载
  335. typee := fsion.Get("type").ValueStr()
  336. ids := []string{}
  337. for _, item := range idList {
  338. ids = append(ids, item.ValueStr())
  339. }
  340. tx := restful.Engine.NewSession()
  341. defer tx.Close()
  342. tx.Begin()
  343. sqlstr := ""
  344. sqlstr1 := ""
  345. // var args []interface{}
  346. if typee == "0" {
  347. if len(ids) > 0 {
  348. sqlstr = `update scheduled s join scheduled_up su on su.id = s.childid set `
  349. sqlstr1 = `update scheduled s join scheduled_up su on su.id = s.childid set `
  350. if automatic != "" {
  351. sqlstr += " su.automatic = 1 "
  352. sqlstr1 += " su.automatic = 0 "
  353. } else if manual != "" {
  354. sqlstr += " su.manual = 1 "
  355. sqlstr1 += " su.manual = 0 "
  356. }
  357. id := strings.Join(ids, ",")
  358. sqlstr += fmt.Sprintf(" where s.id in (%s) and s.action = 0 and su.company = '%s' ", id, company)
  359. sqlstr1 += fmt.Sprintf(" where s.id not in (%s) and s.action = 0 and su.company ='%s' ", id, company)
  360. } else {
  361. sqlstr = `update scheduled s join scheduled_up su on su.id = s.childid set `
  362. if automatic != "" {
  363. sqlstr += " su.automatic = 0 "
  364. } else if manual != "" {
  365. sqlstr += " su.manual = 0 "
  366. }
  367. sqlstr += fmt.Sprintf(" where s.action = 0 and su.company = '%s' ", company)
  368. }
  369. } else {
  370. if len(ids) > 0 {
  371. sqlstr = `update scheduled s join scheduled_down sd on sd.id = s.childid set `
  372. sqlstr1 = `update scheduled s join scheduled_down sd on sd.id = s.childid set `
  373. sqlstr += " sd.manual = 1 "
  374. sqlstr1 += " sd.manual = 0 "
  375. id := strings.Join(ids, ",")
  376. sqlstr += fmt.Sprintf(" where s.id in (%s) and s.action = 1 and sd.company = '%s' ", id, company)
  377. sqlstr1 += fmt.Sprintf(" where s.id not in (%s) and s.action = 1 and sd.company = '%s' ", id, company)
  378. } else {
  379. sqlstr = `update scheduled s join scheduled_down sd on sd.id = s.childid set `
  380. sqlstr += " sd.manual = 0 "
  381. sqlstr += fmt.Sprintf(" where s.action = 1 and sd.company = '%s' ", company)
  382. }
  383. }
  384. _, err := tx.SQL(sqlstr).Execute()
  385. if err != nil {
  386. log.Println("UpdateScheduledStatus-error-1: ", err)
  387. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  388. tx.Rollback()
  389. }
  390. if len(sqlstr1) > 0 {
  391. _, err = tx.SQL(sqlstr1).Execute()
  392. if err != nil {
  393. log.Println("UpdateScheduledStatus-error-2: ", err)
  394. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  395. tx.Rollback()
  396. }
  397. }
  398. err = tx.Commit()
  399. if err != nil {
  400. log.Println("UpdateScheduledStatus-error-3: ", err)
  401. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  402. tx.Rollback()
  403. }
  404. appG.Response(http.StatusOK, e.SUCCESS, true)
  405. }
  406. func SynchronizeNow(c *gin.Context) {
  407. appG := app.Gin{C: c}
  408. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  409. fsion := gofasion.NewFasion(string(dataByte))
  410. company := fsion.Get("company").ValueStr()
  411. date := fsion.Get("date").ValueStr()
  412. tx := restful.Engine.NewSession()
  413. defer tx.Close()
  414. pastureinfo := new(udPastureInfo)
  415. err := tx.SQL(`select column_default as pastureid from information_schema.COLUMNS
  416. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  417. if err != nil {
  418. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  419. return
  420. }
  421. dataList, err := tx.SQL(`select id from downloadedplan where mydate = date_format(?,'%Y-%m-%d') `, date).Query().List()
  422. if err != nil {
  423. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  424. return
  425. }
  426. var idList []string
  427. for _, data := range dataList {
  428. idList = append(idList, strconv.FormatInt(data["id"].(int64), 10))
  429. }
  430. err = UpdatePush(c, tx, false, idList, pastureinfo, company, date)
  431. if err != nil {
  432. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  433. return
  434. }
  435. UpdateDown(c, tx, nil, pastureinfo, company)
  436. if err != nil {
  437. appG.Response(http.StatusInternalServerError, e.ERROR, false)
  438. return
  439. }
  440. appG.Response(http.StatusOK, e.SUCCESS, true)
  441. }
  442. func UpdatePush(ctx context.Context, tx *xorm.Session, auto bool, idList []string, pastureinfo *udPastureInfo, company, date string) error {
  443. upList := make([]*ScheduledUpInfo, 0)
  444. up := tx.Table("scheduled_up")
  445. if company != "" {
  446. up.Where("company = ? ", company)
  447. }
  448. if auto {
  449. up.Where("automatic = 1")
  450. } else {
  451. up.Where("manual = 1")
  452. }
  453. err := up.Find(&upList)
  454. if err != nil {
  455. log.Println("UpdataPush-error-1: ", err)
  456. return err
  457. }
  458. for _, item := range upList {
  459. if item.Datasql != "" {
  460. if item.Datatype == 3 || item.Datatype == 4 {
  461. targetdataList := strings.Split(item.Targetdata, ",")
  462. var args []interface{}
  463. for _, targetdata := range targetdataList {
  464. if targetdata == "pastureid" {
  465. args = append(args, pastureinfo.Pastureid)
  466. } else if targetdata == "idlist" {
  467. // args = append(args, strings.Join(idList, ","))
  468. item.Datasql = strings.ReplaceAll(item.Datasql, "idlist", strings.Join(idList, ","))
  469. } else if targetdata == "date" {
  470. args = append(args, date)
  471. }
  472. }
  473. data, err := tx.SQL(item.Datasql, args...).Query().List()
  474. if err != nil {
  475. log.Println("UpdataPush-error-2: ", err)
  476. continue
  477. }
  478. if len(data) > 0 {
  479. databyte, err := json.Marshal(data)
  480. if err != nil {
  481. log.Println("UpdataPush-error-3: ", err)
  482. continue
  483. }
  484. var method string
  485. // if item.Datatype == 4 {
  486. // continue
  487. // method = "uploadnewdiliverdata"
  488. // }
  489. UDPostPush1(fmt.Sprintf(item.Package, string(databyte), len(data)), method)
  490. }
  491. if len(idList) > 0 {
  492. _, err := tx.SQL(fmt.Sprintf(" update downloadedplan_log set status = 1 where id in (%s)", strings.Join(idList, ","))).Execute()
  493. if err != nil {
  494. log.Println("UpdataPush-error-4: ", err)
  495. continue
  496. }
  497. }
  498. } else {
  499. targetdataList := strings.Split(item.Targetdata, ",")
  500. var args []interface{}
  501. for _, targetdata := range targetdataList {
  502. if targetdata == "pastureid" {
  503. args = append(args, pastureinfo.Pastureid)
  504. } else if targetdata == "idlist" {
  505. // args = append(args, strings.Join(idList, ","))
  506. item.Datasql = strings.ReplaceAll(item.Datasql, "idlist", strings.Join(idList, ","))
  507. }
  508. }
  509. data, err := tx.SQL(item.Datasql, args...).Query().List()
  510. if err != nil {
  511. log.Println("UpdataPush-error-5: ", err)
  512. // return err
  513. }
  514. if len(data) > 0 {
  515. databyte, err := json.Marshal(data)
  516. if err != nil {
  517. log.Println("UpdataPush-error-6: ", err)
  518. // return err
  519. continue
  520. }
  521. // d, err := OpenFile("a.txt")
  522. // d.WriteString()
  523. UDPostPush(fmt.Sprintf(item.Package, string(databyte), len(data)), "application/json")
  524. UDPostPush1(fmt.Sprintf(item.Package, string(databyte), len(data)), "")
  525. }
  526. }
  527. }
  528. }
  529. return nil
  530. }
  531. // OpenFile 判断文件是否存在 存在则OpenFile 不存在则Create
  532. func OpenFile(filename string) (*os.File, error) {
  533. if _, err := os.Stat(filename); os.IsNotExist(err) {
  534. fmt.Println("文件不存在")
  535. return os.Create(filename) //创建文件
  536. }
  537. fmt.Println("文件存在")
  538. return os.OpenFile(filename, os.O_APPEND, 0666) //打开文件
  539. }
  540. func UpdateDown(ctx context.Context, tx *xorm.Session, idList []string, pastureinfo *udPastureInfo, company string) error {
  541. downList := make([]*ScheduledDownInfo, 0)
  542. down := tx.Table("scheduled_down")
  543. if company != "" {
  544. down.Where("company = ? ", company)
  545. }
  546. down.Where("manual = 1")
  547. err := down.Find(&downList)
  548. if err != nil {
  549. log.Println("UpdateDown-error-1: ", err)
  550. return err
  551. }
  552. for _, item := range downList {
  553. list := httpGetMC(item.Addres, item.Targetdata)
  554. if item.Methods != "" {
  555. s := ScheduledDown{}
  556. value := reflect.ValueOf(&s)
  557. f := value.MethodByName(item.Methods)
  558. f.Call([]reflect.Value{reflect.ValueOf(pastureinfo.Pastureid), reflect.ValueOf(list)})
  559. // value := reflect.ValueOf(&s)
  560. // f := value.MethodByName("Ccaa")
  561. // f.Call([]reflect.Value{reflect.ValueOf(list)})
  562. } else {
  563. childList := make([]*ScheduledDownChildInfo, 0)
  564. child := tx.Table("scheduled_down")
  565. child.Where("parentid = ? ", item.Id)
  566. err = child.Find(&childList)
  567. if err != nil {
  568. log.Println("UpdateDown-error-2: ", err)
  569. return err
  570. }
  571. if len(childList) > 0 {
  572. tx.Begin()
  573. for _, c := range childList {
  574. fieldnames := strings.Split(c.Fieldname, ",")
  575. for _, data := range list {
  576. var args []interface{}
  577. dataMap := data.(map[string]interface{})
  578. for _, fieldname := range fieldnames {
  579. args = append(args, dataMap[fieldname])
  580. }
  581. _, err = tx.SQL(c.Dosql, args...).Execute()
  582. if err != nil {
  583. tx.Rollback()
  584. log.Println("UpdateDown-error-3: ", err)
  585. return err
  586. }
  587. }
  588. }
  589. err := tx.Commit()
  590. if err != nil {
  591. tx.Rollback()
  592. log.Println("UpdateDown-error-4: ", err)
  593. return err
  594. }
  595. }
  596. }
  597. }
  598. return nil
  599. }
  600. func httpGetMC(url, targetdata string) []interface{} {
  601. // url := fmt.Sprintf("https://wdc.unidairy.cn/copartner_downloads/?farmId=%s&method=%s", farmId, method)
  602. res, err := http.Get(url)
  603. if err != nil {
  604. return nil
  605. }
  606. robots, err := ioutil.ReadAll(res.Body)
  607. res.Body.Close()
  608. if err != nil {
  609. return nil
  610. }
  611. var data map[string][]interface{}
  612. json.Unmarshal(robots, &data)
  613. return data[targetdata]
  614. }
  615. type ScheduledDown struct {
  616. }
  617. func (h *ScheduledDown) SyncFeed(pastureid string, feedList []interface{}) {
  618. tx := restful.Engine.NewSession()
  619. defer tx.Close()
  620. err := tx.Begin()
  621. if err != nil {
  622. tx.Rollback()
  623. logs.Error("syncFeed-error-1:", err)
  624. return
  625. }
  626. for _, f := range feedList {
  627. feed := f.(map[string]interface{})
  628. var feedcode, fname, fclass, fclassid, dry interface{}
  629. if _, ok := feed["feedcode"]; ok {
  630. feedcode = feed["feedcode"]
  631. }
  632. if _, ok := feed["feedname"]; ok {
  633. fname = feed["feedname"]
  634. }
  635. if _, ok := feed["feedclass"]; ok {
  636. fclass = feed["feedclass"]
  637. }
  638. if _, ok := feed["drymatter"]; ok {
  639. dry = feed["drymatter"]
  640. }
  641. fclassExist, err := tx.SQL(" select id from feedclass where pastureid = ? and fcname = ?", pastureid, fclass).Exist()
  642. if err != nil {
  643. tx.Rollback()
  644. logs.Error("syncFeed-error-2:", err)
  645. return
  646. }
  647. if fclassExist {
  648. fclassDataList, err := tx.SQL(" select id from feedclass where pastureid = ? and fcname = ?", pastureid, fclass).QueryString()
  649. if err != nil {
  650. tx.Rollback()
  651. logs.Error("syncFeed-error-3:", err)
  652. return
  653. }
  654. for _, fclassData := range fclassDataList {
  655. fclassid = fclassData["id"]
  656. }
  657. } else {
  658. ids, err := setting.SnowIds.NextId()
  659. if err != nil {
  660. ids = time.Now().UnixNano()
  661. logging.Info("create SnowIds err", err)
  662. }
  663. _, 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 =? ))",
  664. ids, pastureid, fclass, fclass, fclass, ids, pastureid).Execute()
  665. if err != nil {
  666. tx.Rollback()
  667. logs.Error("syncFeed-error-4:", err)
  668. return
  669. }
  670. fclassid = ids
  671. }
  672. ids, err := setting.SnowIds.NextId()
  673. if err != nil {
  674. ids = time.Now().UnixNano()
  675. logging.Info("create SnowIds err", err)
  676. }
  677. insertSql := `insert into feed(id,pastureid,feedcode,fname,fclassid,fclass,dry)VALUES(?,?,?,?,?,?,?)
  678. ON DUPLICATE KEY UPDATE fname = ? ,dry = ? `
  679. _, err = tx.SQL(insertSql, ids, pastureid, feedcode, fname, fclassid, fclass, dry, fname, dry).Execute()
  680. fmt.Println(feedcode, fname, fclassid)
  681. if err != nil {
  682. tx.Rollback()
  683. logs.Error("syncFeed-error-5:", err)
  684. return
  685. }
  686. }
  687. err = tx.Commit()
  688. if err != nil {
  689. tx.Rollback()
  690. logs.Error("syncFeed-error-6:", err)
  691. return
  692. }
  693. return
  694. }
  695. func (h *ScheduledDown) SyncFeedp(pastureid string, feedpList []interface{}) error {
  696. tx := restful.Engine.NewSession()
  697. defer tx.Close()
  698. err := tx.Begin()
  699. if err != nil {
  700. logs.Error("syncFeedp-error-1:", err)
  701. return err
  702. }
  703. for _, f := range feedpList {
  704. feedp := f.(map[string]interface{})
  705. var barName, barCode interface{}
  706. // var ftId, tname interface{}
  707. var cowCount interface{}
  708. if _, ok := feedp["barname"]; ok {
  709. barName = feedp["barname"]
  710. }
  711. if _, ok := feedp["barcode"]; ok {
  712. barCode = feedp["barcode"]
  713. }
  714. if _, ok := feedp["cowcount"]; ok {
  715. cowCount = feedp["cowcount"]
  716. }
  717. // if _, ok := feedp["feedtempletcode"]; ok {
  718. // feedtempletCode = feedp["feedtempletCode"]
  719. // }
  720. // barCount, err := tx.SQL(" select count(1) from bar where pastureid = ? and bcode = ? ", pastureid, barCode).Count()
  721. // if err != nil {
  722. // tx.Rollback()
  723. // logs.Error("syncFeedp-error-2:", err)
  724. // return err
  725. // }
  726. // if barCount > 0 {
  727. // barDataList, err := tx.SQL(" select id from bar where pastureid = ? and bcode = ?", pastureid, barCode).QueryString()
  728. // if err != nil {
  729. // tx.Rollback()
  730. // logs.Error("syncFeedp-error-3:", err)
  731. // return err
  732. // }
  733. // for _, barData := range barDataList {
  734. // barId = barData["id"]
  735. // }
  736. // } else {
  737. // barReq, err := tx.SQL("insert into bar(pastureid,bname,bcode)VALUES(?,?,?)", pastureid, barName, barCode).Execute()
  738. // if err != nil {
  739. // tx.Rollback()
  740. // logs.Error("syncFeedp-error-4:", err)
  741. // return err
  742. // }
  743. // id, err := barReq.LastInsertId()
  744. // if err != nil {
  745. // tx.Rollback()
  746. // logs.Error("syncFeedp-error-5:", err)
  747. // return err
  748. // }
  749. // barId = strconv.FormatInt(id, 10)
  750. // }
  751. // if feedtempletCode != "" {
  752. // feedtempletDataList, err := tx.SQL(" select id,tname from feedtemplet where pastureid = ? and tcode = ?", pastureid, feedtempletCode).QueryString()
  753. // if err != nil {
  754. // tx.Rollback()
  755. // logs.Error("syncFeedp-error-6:", err)
  756. // return err
  757. // }
  758. // for _, feedtemplet := range feedtempletDataList {
  759. // ftId = feedtemplet
  760. // tname = feedtemplet
  761. // }
  762. // }
  763. // insertSql := `insert into feedp(pastureid,barname,barid,softccount)VALUES(?,?,?,?)
  764. // ON DUPLICATE KEY UPDATE softccount = ? `
  765. // _, err = tx.SQL(insertSql, pastureid, barName, barId, cowCount, cowCount).Execute()
  766. fmt.Println(barCode)
  767. _, err = tx.SQL(`update feedp fp set fp.softccount = ? where (select bcode from bar where id = fp.barid ) = ? `, cowCount, barName).Execute()
  768. if err != nil {
  769. tx.Rollback()
  770. logs.Error("syncFeedp-error-7:", err)
  771. return err
  772. }
  773. }
  774. err = tx.Commit()
  775. if err != nil {
  776. tx.Rollback()
  777. logs.Error("syncFeedp-error-8:", err)
  778. return err
  779. }
  780. return nil
  781. }
  782. func wxPush(target []string, content []interface{}, pastureId string, serviceId int64) {
  783. url := "http://tmrwatch.cn/notice/message"
  784. // dataStr := `{
  785. // "pasture_id":%s,
  786. // "service_id":%d,
  787. // "sys_name": "tmrWatch",
  788. // "target": %s,
  789. // "miniprogram": {
  790. // "appid": "wx9ab2b5b25701da0a",
  791. // "pagepath": "pages/login/login"
  792. // },
  793. // "keys": [
  794. // "first",
  795. // "keyword1",
  796. // "keyword2",
  797. // "remark"
  798. // ],
  799. // "content":%s
  800. // }`
  801. dataStr := `{
  802. "msg_type_id": 0,
  803. "pasture_id": %s,
  804. "service_id": %d,
  805. "sys_name": "tmrWatch",
  806. "miniprogram": {
  807. "appid": "wx9ab2b5b25701da0a",
  808. "pagepath": "pages/login/login"
  809. },
  810. "target": %s,
  811. "keys": [
  812. "thing5",
  813. "thing2",
  814. "thing16",
  815. "thing36",
  816. "thing45"
  817. ],
  818. "content": %s
  819. }`
  820. targetStr, _ := json.Marshal(target)
  821. contentStr, _ := json.Marshal(content)
  822. dataStr = fmt.Sprintf(dataStr, pastureId, serviceId, string(targetStr), string(contentStr))
  823. fmt.Println(dataStr)
  824. var jsonStr = []byte(dataStr)
  825. req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
  826. req.Header.Set("Content-Type", "application/json")
  827. client := &http.Client{}
  828. resp, err := client.Do(req)
  829. if err != nil {
  830. logs.Error(err)
  831. return
  832. }
  833. defer resp.Body.Close()
  834. }
  835. func UDPostPush1(data, method string) {
  836. url := "https://wdc.unidairy.cn/copartner_uploads/"
  837. // 超时时间:5秒
  838. var jsonStr = []byte(data)
  839. req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
  840. fmt.Println(string(jsonStr))
  841. req.Header.Set("Content-Type", "application/json")
  842. client := &http.Client{}
  843. resp, err := client.Do(req)
  844. if err != nil {
  845. logs.Error(err)
  846. }
  847. defer resp.Body.Close()
  848. body, _ := ioutil.ReadAll(resp.Body)
  849. fmt.Println("response Body:", string(body))
  850. logging.Info("response Body:", string(body))
  851. }
  852. func processAnalysisEarlyWarning(target []string, pastureId string, serviceId int64) {
  853. tx2 := restful.Engine.NewSession()
  854. defer tx2.Close()
  855. exist, err := tx2.Table("notice").Where("status = 1").And("content = ? ", "downloadplandtl1").Exist()
  856. if err != nil {
  857. logs.Error("processAnalysisEarlyWarning-error-1:", err)
  858. return
  859. }
  860. if exist {
  861. _, err := tx2.SQL(`update notice set status = 0 where content = ? `, "downloadplandtl1").Execute()
  862. if err != nil {
  863. logs.Error("processAnalysisEarlyWarning-error-2:", err)
  864. return
  865. }
  866. dataList, err := tx2.SQL("select * from downloadplandtl1_log where date = date_format(now(),'%Y-%m-%d') ").Query().List()
  867. if err != nil {
  868. logs.Error("processAnalysisEarlyWarning-error-3:", err)
  869. return
  870. }
  871. plandtl1SlIdMap := make(map[string][]int64, 0)
  872. // plandtl1HlIdMap := make(map[string][]string, 0)
  873. for _, data := range dataList {
  874. if data["type"].(int64) == 0 && data["plandtl1"] != nil {
  875. plandtl1SlIdMap["planid"] = append(plandtl1SlIdMap["planid"], data["plandtl1"].(int64))
  876. } else if data["type"].(int64) == 1 && data["plandtl1"] != nil {
  877. plandtl1SlIdMap["slplanid"] = append(plandtl1SlIdMap["slplanid"], data["plandtl1"].(int64))
  878. }
  879. }
  880. pastureList, err := tx2.SQL("select pasture_name from pasture where pastureid = ? ", pastureId).Query().List()
  881. if err != nil {
  882. logs.Error("processAnalysisEarlyWarning-error-4:", err)
  883. return
  884. }
  885. var pastureName string
  886. for _, pasture := range pastureList {
  887. pastureName = pasture["pasture_name"].(string)
  888. }
  889. for _, data := range dataList {
  890. if data["type"].(int64) == 0 {
  891. 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,
  892. round(d1.lweight,2) lweight,
  893. if(d1.actualweightminus <= d1.lweight,ROUND(d1.actualweightminus/d1.lweight* 100,2),ROUND(d1.lweight/d1.actualweightminus* 100,2) ) as accuracy from
  894. downloadplandtl1 d1
  895. join downloadedplan d on d.id = d1.pid
  896. where d1.pid = ? and d1.sort = ? and d1.pastureid = ? and d1.intime is not null and d1.type = 0 `,
  897. data["planid"], data["sort"], data["pastureid"]).Query().List()
  898. if err != nil {
  899. logs.Error("processAnalysisEarlyWarning-error-5:", err)
  900. return
  901. }
  902. for _, plandtl1 := range plandtl1List {
  903. idexist := false
  904. //防止同顺序饲料多次推送
  905. for _, plandtl1Id := range plandtl1SlIdMap["planid"] {
  906. if plandtl1Id == plandtl1["id"].(int64) {
  907. idexist = true
  908. break
  909. }
  910. }
  911. if idexist {
  912. continue
  913. }
  914. if _, ok := plandtl1["errorvalue"]; !ok {
  915. continue
  916. }
  917. errorvalue, _ := strconv.ParseFloat(plandtl1["errorvalue"].(string), 64)
  918. if _, ok := plandtl1["feedallowratio"]; ok {
  919. if plandtl1["feedallowratio"].(float64) < errorvalue {
  920. var sendList []interface{}
  921. // sendStr := fmt.Sprintf("操作编号:%v\n牧场:%s\nTMR名称:%v\n描述:%v\n饲料名称:%v\n计划重量(kg):%v\n实际重量(kg):%v\n误差值(kg):%v\n准确率(%%):%v",
  922. // plandtl1["projname"], pastureName, plandtl1["tmrtname"], plandtl1["remark"], plandtl1["fname"], plandtl1["lweight"], plandtl1["actualweightminus"], plandtl1["errorvalue"], plandtl1["accuracy"])
  923. sendMap1 := make(map[string]interface{}, 0)
  924. sendMap1["value"] = fmt.Sprintf("%v%s", plandtl1["projname"], "混料准确率异常")
  925. sendList = append(sendList, sendMap1)
  926. sendMap2 := make(map[string]interface{}, 0)
  927. sendMap2["value"] = fmt.Sprintf("%v-%v", plandtl1["tmrtname"], plandtl1["fname"])
  928. sendList = append(sendList, sendMap2)
  929. sendMap3 := make(map[string]interface{}, 0)
  930. sendMap3["value"] = fmt.Sprintf("计划%v,实际%v", plandtl1["lweight"], plandtl1["actualweightminus"])
  931. sendList = append(sendList, sendMap3)
  932. sendMap4 := make(map[string]interface{}, 0)
  933. sendMap4["value"] = fmt.Sprintf("误差值%v,准确率%v", plandtl1["errorvalue"], plandtl1["accuracy"])
  934. sendList = append(sendList, sendMap4)
  935. sendMap5 := make(map[string]interface{}, 0)
  936. sendMap5["value"] = pastureName
  937. sendList = append(sendList, sendMap5)
  938. wxPush(target, sendList, pastureId, serviceId)
  939. }
  940. }
  941. plandtl1SlIdMap["planid"] = append(plandtl1SlIdMap["planid"], plandtl1["id"].(int64))
  942. _, err := tx2.SQL(" update downloadplandtl1_log set plandtl1 = ? where id = ? and type = 0 ", plandtl1["id"], data["id"]).Execute()
  943. if err != nil {
  944. logs.Error("processAnalysisEarlyWarning-error-6:", err)
  945. return
  946. }
  947. }
  948. } else {
  949. 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,
  950. if(d2.actualweightminus <= d2.lweight,ROUND(d2.actualweightminus/d2.lweight* 100,2),ROUND(d2.lweight/d2.actualweightminus* 100,2) ) as accuracy
  951. from downloadplandtl2 d2
  952. join downloadedplan d on d.id = d2.pid
  953. where d2.pid = ? and d2.sort = ? and d2.pastureid = ? and d2.intime is not null and d2.type = 0 `,
  954. data["planid"], data["sort"], data["pastureid"]).Query().List()
  955. // Where(" pid = ? ", data["planid"]).And("sort = ? ", data["sort"]).And(" pastureid = ? ", data["pastureid"]).And(" intime is not null").And("type = 0 ").Query().List()
  956. if err != nil {
  957. logs.Error("processAnalysisEarlyWarning-error-7:", err)
  958. return
  959. }
  960. for _, plandtl1 := range plandtl1List {
  961. idexist := false
  962. //防止同顺序饲料多次推送
  963. for _, plandtl1Id := range plandtl1SlIdMap["slplanid"] {
  964. if plandtl1Id == plandtl1["id"].(int64) {
  965. idexist = true
  966. break
  967. }
  968. }
  969. if idexist {
  970. continue
  971. }
  972. errorvalue, _ := strconv.ParseFloat(plandtl1["errorvalue"].(string), 64)
  973. if _, ok := plandtl1["allowratio"]; ok {
  974. if float64(plandtl1["allowratio"].(int64)) < errorvalue && float64(plandtl1["allowratio"].(int64)) != 0 {
  975. fmt.Println(plandtl1, "推送")
  976. var sendList []interface{}
  977. // sendStr := fmt.Sprintf("操作编号:%v\n牧场:%s\nTMR名称:%v\n描述:%v\n栏舍名称:%v\n计划重量(kg):%v\n实际重量(kg):%v\n误差值(kg):%v\n准确率(%%):%v",
  978. // plandtl1["projname"], pastureName, plandtl1["tmrtname"], plandtl1["remark"], plandtl1["fname"], plandtl1["lweight"], plandtl1["actualweightminus"], plandtl1["errorvalue"], plandtl1["accuracy"])
  979. // sendMap1 := make(map[string]interface{}, 0)
  980. // sendMap1["value"] = "撒料准确率异常"
  981. // sendMap1["color"] = "#173177"
  982. // sendList = append(sendList, sendMap1)
  983. sendMap1 := make(map[string]interface{}, 0)
  984. sendMap1["value"] = fmt.Sprintf("%v%s", plandtl1["projname"], "撒料准确率异常")
  985. sendList = append(sendList, sendMap1)
  986. sendMap2 := make(map[string]interface{}, 0)
  987. sendMap2["value"] = fmt.Sprintf("%v-%v", plandtl1["tmrtname"], plandtl1["fname"])
  988. sendList = append(sendList, sendMap2)
  989. sendMap3 := make(map[string]interface{}, 0)
  990. sendMap3["value"] = fmt.Sprintf("计划%v,实际%v", plandtl1["lweight"], plandtl1["actualweightminus"])
  991. sendList = append(sendList, sendMap3)
  992. sendMap4 := make(map[string]interface{}, 0)
  993. sendMap4["value"] = fmt.Sprintf("误差值%v,准确率%v", plandtl1["errorvalue"], plandtl1["accuracy"])
  994. sendList = append(sendList, sendMap4)
  995. sendMap5 := make(map[string]interface{}, 0)
  996. sendMap5["value"] = pastureName
  997. sendList = append(sendList, sendMap5)
  998. wxPush(target, sendList, pastureId, serviceId)
  999. }
  1000. }
  1001. if _, ok := plandtl1["id"]; ok {
  1002. if _, ok := data["id"]; ok {
  1003. fmt.Println(plandtl1["id"])
  1004. plandtl1SlIdMap["planid"] = append(plandtl1SlIdMap["planid"], plandtl1["id"].(int64))
  1005. _, err := tx2.SQL(" update downloadplandtl1_log set plandtl1 = ? where id = ? and type = 1 ", plandtl1["id"], data["id"]).Execute()
  1006. if err != nil {
  1007. logs.Error("processAnalysisEarlyWarning-error-8:", err)
  1008. return
  1009. }
  1010. }
  1011. }
  1012. }
  1013. }
  1014. }
  1015. }
  1016. }
  1017. func manualUdData(pastureinfo *udPastureInfo) {
  1018. c := cron.New()
  1019. c.AddFunc("10 06 * * *", func() {
  1020. tx := restful.Engine.NewSession()
  1021. defer tx.Close()
  1022. now := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
  1023. // now := "2023-02-22"
  1024. dataList, err := tx.SQL(" select id from downloadedplan where mydate = ? ", now).QueryString()
  1025. if err != nil {
  1026. logging.Error("manualUdData-error-1:", err)
  1027. return
  1028. }
  1029. var idList []string
  1030. for _, data := range dataList {
  1031. idList = append(idList, data["id"])
  1032. }
  1033. upList := make([]*ScheduledUpInfo, 0)
  1034. up := tx.Table("scheduled_up")
  1035. up.Where("company = ? ", "ud")
  1036. up.Where("datatype in (3,4,1)")
  1037. up.Where("automatic = 1")
  1038. err = up.Find(&upList)
  1039. if err != nil {
  1040. logging.Error("manualUdData-error-2: ", err)
  1041. return
  1042. }
  1043. for _, item := range upList {
  1044. if item.Datasql != "" {
  1045. // if item.Datatype == 4 {
  1046. targetdataList := strings.Split(item.Targetdata, ",")
  1047. var args []interface{}
  1048. for _, targetdata := range targetdataList {
  1049. if targetdata == "pastureid" {
  1050. args = append(args, pastureinfo.Pastureid)
  1051. } else if targetdata == "idlist" {
  1052. item.Datasql = strings.ReplaceAll(item.Datasql, "idlist", strings.Join(idList, ","))
  1053. } else if targetdata == "date" {
  1054. args = append(args, now)
  1055. }
  1056. }
  1057. data, err := tx.SQL(item.Datasql, args...).Query().List()
  1058. if err != nil {
  1059. logging.Error("manualUdData-error-3: ", err)
  1060. continue
  1061. }
  1062. if len(data) > 0 {
  1063. databyte, err := json.Marshal(data)
  1064. if err != nil {
  1065. logging.Error("manualUdData-error-4: ", err)
  1066. continue
  1067. }
  1068. exist, err := tx.SQL(`select * from saplog where pastureId = ? and msgtype = ? and date_format(dataDate ,'%Y-%m-%d') = ? `,
  1069. pastureinfo.Pastureid, item.Datatype, now).Exist()
  1070. if exist {
  1071. continue
  1072. }
  1073. tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url)
  1074. values(?,?,?,?,?,now(),?,?,?)`, pastureinfo.Pastureid, string(databyte), "", "", "", item.Datatype, now, "https://wdc.unidairy.cn/copartner_uploads/")
  1075. var method string
  1076. UDPostPush1(fmt.Sprintf(item.Package, string(databyte), len(data)), method)
  1077. }
  1078. // }
  1079. }
  1080. }
  1081. })
  1082. c.Start()
  1083. c1 := cron.New()
  1084. c1.AddFunc("01 18 * * *", func() {
  1085. udFeedpSync(pastureinfo)
  1086. })
  1087. c1.Start()
  1088. c2 := cron.New()
  1089. c2.AddFunc("30 11 * * *", func() {
  1090. udFeedpSync(pastureinfo)
  1091. })
  1092. c2.Start()
  1093. c3 := cron.New()
  1094. c3.AddFunc("59 23 * * *", func() {
  1095. udFeedpSync(pastureinfo)
  1096. udFeedSync(pastureinfo)
  1097. })
  1098. c3.Start()
  1099. }
  1100. func abnormalMixingDelay(target []string, pastureId string, serviceId int64) {
  1101. tx2 := restful.Engine.NewSession()
  1102. defer tx2.Close()
  1103. now := time.Now().Format("2006-01-02")
  1104. 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()
  1105. if err != nil {
  1106. logs.Error("abnormalMixingDelay-error-1:", err)
  1107. return
  1108. }
  1109. if len(dataList) <= 0 {
  1110. return
  1111. }
  1112. local, _ := time.LoadLocation("Asia/Shanghai")
  1113. for _, data := range dataList {
  1114. 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 ,
  1115. d.datacaptureno,(select pasture_name from pasture where pastureid = ?) as pasturename,round(de.actualweightminus,2) actualweightminus from downloadplandtl1_exec de
  1116. join downloadedplan d on de.pid = d.id where de.pid = ? and de.sort = ? `, pastureId, data["planid"], data["sort"]).Query().List()
  1117. if err != nil {
  1118. logs.Error("abnormalMixingDelay-error-2:", err)
  1119. return
  1120. }
  1121. for _, plan := range planList {
  1122. fmt.Println(plan["processtime"])
  1123. fmt.Println(fmt.Sprintf("%s %v", time.Now().Format("2006-01-02"), plan["processtime"]), local)
  1124. showTime, _ := time.Parse("2006-01-02 15:04:05", fmt.Sprintf("%s %v", time.Now().Format("2006-01-02"), plan["processtime"]))
  1125. nowTime, _ := time.Parse("2006-01-02 15:04:05", fmt.Sprintf("%s 00:00:00", time.Now().Format("2006-01-02")))
  1126. // showTime, _ := time.ParseInLocation("2006-01-02 15:04:05", fmt.Sprintf("%s %v", time.Now().Format("2006-01-02"), plan["processtime"]), local)
  1127. // nowTime, _ := time.ParseInLocation("2006-01-02 15:04:05", fmt.Sprintf("%s 00:00:00", time.Now().Format("2006-01-02")), local)
  1128. if (showTime.Unix()-nowTime.Unix())/60 < plan["stirdelay"].(int64)-plan["deviation"].(int64) || (showTime.Unix()-nowTime.Unix())/60 > plan["stirdelay"].(int64)+plan["deviation"].(int64) {
  1129. var sendList []interface{}
  1130. // sendStr := fmt.Sprintf("操作编号:%v\n牧场:%s\nTMR名称:%v\n描述:%v\n饲料名称:%v\n计划重量(kg):%v\n实际重量(kg):%v\n过程时间:%v",
  1131. // plan["projname"], plan["pasturename"], plan["tmrtname"], plan["name"], plan["fname"], plan["lweight"], plan["actualweightminus"], plan["processtime"])
  1132. sendMap1 := make(map[string]interface{}, 0)
  1133. sendMap1["value"] = fmt.Sprintf("%s%v", "混料搅拌延时异常", plan["projname"])
  1134. // sendMap1["color"] = "#173177"
  1135. sendList = append(sendList, sendMap1)
  1136. sendMap4 := make(map[string]interface{}, 0)
  1137. sendMap4["value"] = fmt.Sprintf("%v-%v", plan["tmrtname"], plan["fname"])
  1138. // sendMap4["color"] = "#173177"
  1139. sendList = append(sendList, sendMap4)
  1140. sendMap2 := make(map[string]interface{}, 0)
  1141. sendMap2["value"] = fmt.Sprintf("计划%v,实际%v", plan["lweight"], plan["actualweightminus"])
  1142. // sendMap2["color"] = "#173177"
  1143. sendList = append(sendList, sendMap2)
  1144. sendMap5 := make(map[string]interface{}, 0)
  1145. sendMap5["value"] = fmt.Sprintf("过程时间:%v", plan["processtime"])
  1146. // sendMap5["color"] = "#173177"
  1147. sendList = append(sendList, sendMap5)
  1148. sendMap3 := make(map[string]interface{}, 0)
  1149. sendMap3["value"] = plan["pasturename"]
  1150. // sendMap3["color"] = "#173177"
  1151. sendList = append(sendList, sendMap3)
  1152. wxPush(target, sendList, pastureId, serviceId)
  1153. }
  1154. _, err := tx2.SQL(` update downloadplandtl1_log set abnormalMixingDelay = 1 where id = ? `, data["id"]).Execute()
  1155. if err != nil {
  1156. logs.Error("abnormalMixingDelay-error-3:", err)
  1157. return
  1158. }
  1159. }
  1160. }
  1161. }
  1162. func endOfShift(target []string, pastureId string, serviceId int64) {
  1163. tx := restful.Engine.NewSession()
  1164. defer tx.Close()
  1165. now := time.Now().Format("2006-01-02")
  1166. logList, err := tx.SQL(` select times from downloadedplan_log where date = ? and classes = 0 group by times `, now).Query().List()
  1167. if err != nil {
  1168. logs.Error("endOfShift-error-1:", err)
  1169. return
  1170. }
  1171. for _, item := range logList {
  1172. exist, err := tx.SQL(` select id from downloadedplan where mydate = ? and times = ? and iscompleted = 0 and enable = 1 `, now, item["times"]).Exist()
  1173. if err != nil {
  1174. logs.Error("endOfShift-error-2:", err)
  1175. return
  1176. }
  1177. if !exist {
  1178. hlList, err := tx.SQL(` select ( select count(1) from downloadedplan where times = d.times and mydate = d.mydate ) as cltrains,
  1179. round(sum(de.lweight),2) lweight,round(sum(de.actualweightminus),2) actualweightminus ,
  1180. 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,
  1181. ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) correct,
  1182. IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0)),0) correctcount,
  1183. 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
  1184. from downloadedplan d
  1185. join downloadplandtl1_exec de on de.pid = d.id
  1186. where d.times = ? and d.mydate = ? and lpplantype in(0,1) group by d.times`, item["times"], now).Query().List()
  1187. if err != nil {
  1188. logs.Error("endOfShift-error-3:", err)
  1189. return
  1190. }
  1191. slList, err := tx.SQL(` select round(sum(de.lweight),2) lweight,round(sum(de.actualweightminus),2) actualweightminus ,
  1192. round(if(sum(de.lweight) < sum(de.actualweightminus),sum(de.lweight)/sum(de.actualweightminus) *100, sum(de.actualweightminus)/sum(de.lweight) *100),2) as accurate,
  1193. ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) correct,
  1194. IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0)),0) correctcount,
  1195. round( sum(UNIX_TIMESTAMP(concat("2022-01-01 ", de.processtime)) - UNIX_TIMESTAMP("2022-01-01 00:00:00") ),0) processtime ,abs(sum(de.actualweightminus)-sum(de.lweight)) as wcz
  1196. from downloadedplan d
  1197. join downloadplandtl2 de on de.pid = d.id
  1198. where d.times = ? and d.mydate = ? and lpplantype in(0,2) group by d.times `, item["times"], now).Query().List()
  1199. if err != nil {
  1200. logs.Error("endOfShift-error-4:", err)
  1201. return
  1202. }
  1203. data := make(map[string]interface{})
  1204. for _, hl := range hlList {
  1205. data["cltrains"] = hl["cltrains"]
  1206. // data["hllweight"] = hl["lweight"]
  1207. data["hlactualweightminus"] = hl["actualweightminus"]
  1208. data["hlaccurate"] = hl["accurate"]
  1209. data["hlcorrect"] = hl["correct"]
  1210. data["hlcorrectcount"] = hl["correctcount"]
  1211. // data["hlprocesstime"] = util.TimeTransformation(hl["processtime"].(int64))
  1212. data["hlwcz"] = hl["wcz"]
  1213. }
  1214. for _, sl := range slList {
  1215. // data["sllweight"] = sl["lweight"]
  1216. data["slactualweightminus"] = sl["actualweightminus"]
  1217. data["slaccurate"] = sl["accurate"]
  1218. data["slcorrect"] = sl["correct"]
  1219. data["slcorrectcount"] = sl["correctcount"]
  1220. // data["slprocesstime"] = util.TimeTransformation(sl["processtime"].(int64))
  1221. data["slwcz"] = sl["wcz"]
  1222. }
  1223. 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",
  1224. item["times"], data["cltrains"], data["hlactualweightminus"], data["hlwcz"], data["hlaccurate"], data["hlcorrect"], data["hlcorrectcount"],
  1225. data["slactualweightminus"], data["slwcz"], data["slaccurate"], data["slcorrect"], data["slcorrectcount"])
  1226. var sendList []interface{}
  1227. sendMap1 := make(map[string]interface{}, 0)
  1228. sendMap1["value"] = "班次完成"
  1229. sendMap1["color"] = "#173177"
  1230. sendList = append(sendList, sendMap1)
  1231. sendMap4 := make(map[string]interface{}, 0)
  1232. sendMap4["value"] = sendStr
  1233. sendMap4["color"] = "#173177"
  1234. sendList = append(sendList, sendMap4)
  1235. sendMap2 := make(map[string]interface{}, 0)
  1236. // sendMap2["value"] = plan["processtime"]
  1237. sendMap2["value"] = time.Now().Format("2006-01-02 15:04:05")
  1238. sendMap2["color"] = "#173177"
  1239. sendList = append(sendList, sendMap2)
  1240. sendMap5 := make(map[string]interface{}, 0)
  1241. sendMap5["value"] = "无备注"
  1242. sendMap5["color"] = "#173177"
  1243. sendList = append(sendList, sendMap5)
  1244. wxPush(target, sendList, pastureId, serviceId)
  1245. _, err = tx.SQL(` update downloadedplan_log set classes = 1 where date = ? and times = ? `, now, item["times"]).Execute()
  1246. if err != nil {
  1247. logs.Error("endOfShift-error-5:", err)
  1248. return
  1249. }
  1250. }
  1251. }
  1252. }
  1253. func plansToComplete(target []string, pastureId string, serviceId int64) {
  1254. tx := restful.Engine.NewSession()
  1255. defer tx.Close()
  1256. now := time.Now()
  1257. exist, err := tx.SQL(` select id from downloadedplan_log where date = ? and dailyplan = 0 `, now).Exist()
  1258. if err != nil {
  1259. logs.Error("plansToComplete-error-1:", err)
  1260. return
  1261. }
  1262. if exist {
  1263. downloadedplanExist, err := tx.SQL(` select id from downloadedplan where mydate = ? and iscompleted = 0 and enable = 1 `, now).Exist()
  1264. if err != nil {
  1265. logs.Error("plansToComplete-error-2:", err)
  1266. return
  1267. }
  1268. if !downloadedplanExist {
  1269. 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,
  1270. sum(de.lweight)lweight,sum(de.actualweightminus)actualweightminus ,
  1271. 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,
  1272. ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) correct,
  1273. IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0)),0) correctcount,
  1274. 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
  1275. from downloadedplan d
  1276. join downloadplandtl1_exec de on de.pid = d.id
  1277. where d.mydate = ? and lpplantype in(0,1) group by d.mydate`, now, now).Query().List()
  1278. if err != nil {
  1279. logs.Error("plansToComplete-error-3:", err)
  1280. return
  1281. }
  1282. slList, err := tx.SQL(` select sum(de.lweight)lweight,sum(de.actualweightminus)actualweightminus ,
  1283. 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,
  1284. ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) correct,
  1285. IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0)),0) correctcount,
  1286. 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
  1287. from downloadedplan d
  1288. join downloadplandtl2 de on de.pid = d.id
  1289. where d.mydate = ? and lpplantype in(0,2) group by d.mydate `, now).Query().List()
  1290. if err != nil {
  1291. logs.Error("plansToComplete-error-4:", err)
  1292. return
  1293. }
  1294. data := make(map[string]interface{})
  1295. for _, hl := range hlList {
  1296. data["timescount"] = hl["timescount"]
  1297. data["cltrains"] = hl["cltrains"]
  1298. data["hllweight"] = hl["lweight"]
  1299. data["hlactualweightminus"] = hl["actualweightminus"]
  1300. data["hlaccurate"] = hl["accurate"]
  1301. data["hlcorrect"] = hl["correct"]
  1302. data["hlcorrectcount"] = hl["correctcount"]
  1303. data["hlwcz"] = hl["wcz"]
  1304. }
  1305. for _, sl := range slList {
  1306. data["sllweight"] = sl["lweight"]
  1307. data["slactualweightminus"] = sl["actualweightminus"]
  1308. data["slaccurate"] = sl["accurate"]
  1309. data["slcorrect"] = sl["correct"]
  1310. data["slcorrectcount"] = sl["correctcount"]
  1311. data["slwcz"] = sl["wcz"]
  1312. }
  1313. 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",
  1314. data["timescount"], data["cltrains"], data["hlactualweightminus"], data["hlwcz"], data["hlaccurate"], data["hlcorrect"], data["hlcorrectcount"],
  1315. data["slactualweightminus"], data["slwcz"], data["slaccurate"], data["slcorrect"], data["slcorrectcount"])
  1316. var sendList []interface{}
  1317. sendMap1 := make(map[string]interface{}, 0)
  1318. sendMap1["value"] = "每日计划完成"
  1319. sendMap1["color"] = "#173177"
  1320. sendList = append(sendList, sendMap1)
  1321. sendMap4 := make(map[string]interface{}, 0)
  1322. sendMap4["value"] = sendStr
  1323. sendMap4["color"] = "#173177"
  1324. sendList = append(sendList, sendMap4)
  1325. sendMap2 := make(map[string]interface{}, 0)
  1326. // sendMap2["value"] = plan["processtime"]
  1327. sendMap2["value"] = time.Now().Format("2006-01-02 15:04:05")
  1328. sendMap2["color"] = "#173177"
  1329. sendList = append(sendList, sendMap2)
  1330. sendMap5 := make(map[string]interface{}, 0)
  1331. sendMap5["value"] = "无备注"
  1332. sendMap5["color"] = "#173177"
  1333. sendList = append(sendList, sendMap5)
  1334. wxPush(target, sendList, pastureId, serviceId)
  1335. _, err = tx.SQL(` update downloadedplan_log set dailyplan = 1 where date = ? `, now).Execute()
  1336. if err != nil {
  1337. logs.Error("plansToComplete-error-5:", err)
  1338. return
  1339. }
  1340. }
  1341. }
  1342. }
  1343. func AddFormulaIssued(c *gin.Context) {
  1344. appG := app.Gin{C: c}
  1345. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1346. tempval_ := make(map[string]interface{})
  1347. tempCommon := make(map[string]interface{})
  1348. tempval := make([]map[string]interface{}, 0)
  1349. err := json.Unmarshal(dataByte, &tempval_)
  1350. logging.Info("AddFormulaIssued ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1351. if err != nil {
  1352. } else {
  1353. if v, ok := tempval_["data"].([]interface{}); ok {
  1354. for _, Tvalue := range v {
  1355. if v1, ok := Tvalue.(map[string]interface{}); ok {
  1356. tempval = append(tempval, v1)
  1357. }
  1358. }
  1359. }
  1360. tx := restful.Engine.NewSession()
  1361. err := tx.Begin()
  1362. if err != nil {
  1363. logging.Error("tx.Begin 事务启动失败__error:", err)
  1364. }
  1365. defer func() {
  1366. switch {
  1367. case err != nil:
  1368. if tx != nil {
  1369. tx.Rollback()
  1370. }
  1371. default:
  1372. if tx != nil {
  1373. err = tx.Commit()
  1374. }
  1375. }
  1376. if tx != nil {
  1377. tx.Close()
  1378. }
  1379. }()
  1380. if err == nil {
  1381. if tempv, exists := c.Get("jwt_username"); exists {
  1382. tempCommon["jwt_username"] = tempv.(string)
  1383. }
  1384. for _, paramvalue := range tempval {
  1385. if _, ok := paramvalue["resultname"]; !ok {
  1386. paramvalue["resultname"] = paramvalue["name"]
  1387. }
  1388. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  1389. if err != nil {
  1390. logging.Error("AddFormulaIssued error-1:", err)
  1391. break
  1392. }
  1393. }
  1394. if err == nil {
  1395. var temid, jtpastureid, tcode, tname, ccname, fttype string
  1396. for _, tem := range tempval {
  1397. if tem["name"].(string) == "insertSpotList" {
  1398. for _, item := range tem["resultmaps"].(map[string]interface{})["list"].([]interface{}) {
  1399. itemmap := item.(map[string]interface{})
  1400. jtpastureid = itemmap["pastureid"].(string)
  1401. temid = itemmap["id"].(string)
  1402. }
  1403. }
  1404. }
  1405. feedtempletList, err := tx.SQL(` select tname,tcode,id,ccname,fttype from feedtemplet where id = ? and pastureid = ? `, temid, jtpastureid).Query().List()
  1406. if err != nil {
  1407. logs.Error("AddFormulaIssued-error-2:", err)
  1408. return
  1409. }
  1410. for _, feedtemplet := range feedtempletList {
  1411. tcode = feedtemplet["tcode"].(string)
  1412. tname = feedtemplet["tname"].(string)
  1413. ccname = feedtemplet["ccname"].(string)
  1414. fttype = feedtemplet["fttype"].(string)
  1415. }
  1416. for _, tem := range tempval {
  1417. if tem["name"].(string) == "insertSpotList2" {
  1418. for _, item := range tem["resultmaps"].(map[string]interface{})["list"].([]interface{}) {
  1419. itemmap := item.(map[string]interface{})
  1420. dataList, err := tx.SQL(` select user,function,id,service_id from remind where pastureid = ? and function = ? `, itemmap["id"], "formulaIssued").Query().List()
  1421. if err != nil {
  1422. logs.Error("AddFormulaIssued-error-3:", err)
  1423. return
  1424. }
  1425. for _, data := range dataList {
  1426. var openIdList []string
  1427. if _, ok := data["user"]; ok {
  1428. openIdList = strings.Split(data["user"].(string), ",")
  1429. }
  1430. var sendList []interface{}
  1431. sendStr := fmt.Sprintf("配方名称:%v\n配方编码:%s\n牲畜类别:%v\n配方类型:%v",
  1432. tname, tcode, ccname, fttype)
  1433. sendMap1 := make(map[string]interface{}, 0)
  1434. sendMap1["value"] = "混料准确率异常"
  1435. sendMap1["color"] = "#173177"
  1436. sendList = append(sendList, sendMap1)
  1437. sendMap4 := make(map[string]interface{}, 0)
  1438. sendMap4["value"] = sendStr
  1439. sendMap4["color"] = "#173177"
  1440. sendList = append(sendList, sendMap4)
  1441. sendMap2 := make(map[string]interface{}, 0)
  1442. sendMap2["value"] = time.Now().Format("2006-01-02 15:04:05")
  1443. sendMap2["color"] = "#173177"
  1444. sendList = append(sendList, sendMap2)
  1445. sendMap5 := make(map[string]interface{}, 0)
  1446. sendMap5["value"] = "无备注"
  1447. sendMap5["color"] = "#173177"
  1448. sendList = append(sendList, sendMap5)
  1449. wxPush(openIdList, sendList, itemmap["id"].(string), data["service_id"].(int64))
  1450. }
  1451. }
  1452. break
  1453. }
  1454. }
  1455. if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
  1456. appG.Response(http.StatusOK, e.SUCCESS, tempval)
  1457. } else {
  1458. appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
  1459. }
  1460. } else {
  1461. msg := geterrmsg(err.Error())
  1462. appG.Response(http.StatusOK, e.ERROR, msg)
  1463. }
  1464. }
  1465. }
  1466. if err != nil {
  1467. msg := geterrmsg(err.Error())
  1468. appG.Response(http.StatusOK, e.ERROR, msg)
  1469. appG.Response(http.StatusOK, 200, nil)
  1470. }
  1471. }
  1472. func AddBigInventory(c *gin.Context) {
  1473. appG := app.Gin{C: c}
  1474. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1475. tempval_ := make(map[string]interface{})
  1476. tempCommon := make(map[string]interface{})
  1477. tempval := make([]map[string]interface{}, 0)
  1478. err := json.Unmarshal(dataByte, &tempval_)
  1479. logging.Info("AddBigInventory ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
  1480. if err != nil {
  1481. } else {
  1482. if v, ok := tempval_["common"].(map[string]interface{}); ok {
  1483. tempCommon = v
  1484. }
  1485. if v, ok := tempval_["data"].([]interface{}); ok {
  1486. for _, Tvalue := range v {
  1487. if v1, ok := Tvalue.(map[string]interface{}); ok {
  1488. tempval = append(tempval, v1)
  1489. }
  1490. }
  1491. }
  1492. tx := restful.Engine.NewSession()
  1493. err := tx.Begin()
  1494. if err != nil {
  1495. logging.Error("tx.Begin 事务启动失败__error:", err)
  1496. }
  1497. defer func() {
  1498. switch {
  1499. case err != nil:
  1500. if tx != nil {
  1501. tx.Rollback()
  1502. }
  1503. default:
  1504. if tx != nil {
  1505. err = tx.Commit()
  1506. }
  1507. }
  1508. if tx != nil {
  1509. tx.Close()
  1510. }
  1511. }()
  1512. if err == nil {
  1513. if tempv, exists := c.Get("jwt_username"); exists {
  1514. tempCommon["jwt_username"] = tempv.(string)
  1515. }
  1516. for _, paramvalue := range tempval {
  1517. if _, ok := paramvalue["resultname"]; !ok {
  1518. paramvalue["resultname"] = paramvalue["name"]
  1519. }
  1520. _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
  1521. if err != nil {
  1522. logging.Error("AddBigInventory error-1:", err)
  1523. break
  1524. }
  1525. }
  1526. if err == nil {
  1527. // var pastureid, date string
  1528. // for _, tem := range tempval {
  1529. // if tem["name"].(string) == "insertBigInventory" {
  1530. // parammaps := tem["parammaps"].(map[string]interface{})
  1531. // pastureid = parammaps["pastureid"].(string)
  1532. // date = parammaps["inventorydate"].(string)
  1533. // }
  1534. // }
  1535. // feedinventoryList, err := tx.SQL(`SELECT
  1536. // remark,DATE_FORMAT(inventorydate, '%Y-%m-%d') inventorydate,createuser,
  1537. // TRIM(f.id) id,
  1538. // TRIM(f.pastureid) pastureid,
  1539. // 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,
  1540. // 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 ,
  1541. // 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
  1542. // FROM
  1543. // feedinventory f
  1544. // WHERE f.pastureid = ? and f.inventorydate=? `, pastureid, date).Query().List()
  1545. // if err != nil {
  1546. // logs.Error("AddBigInventory-error-2:", err)
  1547. // return
  1548. // }
  1549. // dataList, err := tx.SQL(` select user,function,id,service_id from remind where pastureid = ? and function = ? `, pastureid, "formulaIssued").Query().List()
  1550. // if err != nil {
  1551. // logs.Error("AddBigInventory-error-3:", err)
  1552. // return
  1553. // }
  1554. // for _, data := range dataList {
  1555. // var openIdList []string
  1556. // if _, ok := data["user"]; ok {
  1557. // openIdList = strings.Split(data["user"].(string), ",")
  1558. // }
  1559. // var createuser, lessWeight, moreWeight, differWeight interface{}
  1560. // for _, f := range feedinventoryList {
  1561. // createuser = f["createuser"]
  1562. // lessWeight = f["lessWeight"]
  1563. // moreWeight = f["moreWeight"]
  1564. // differWeight = f["differWeight"]
  1565. // }
  1566. // var sendList []interface{}
  1567. // sendStr := fmt.Sprintf("盘点人:%v\n盘盈库存(kg):%v\n盘亏库存(kg):%v\n盈亏净值(kg):%v",
  1568. // createuser, moreWeight, lessWeight, differWeight)
  1569. // sendMap1 := make(map[string]interface{}, 0)
  1570. // sendMap1["value"] = "库存盘点"
  1571. // sendMap1["color"] = "#173177"
  1572. // sendList = append(sendList, sendMap1)
  1573. // sendMap4 := make(map[string]interface{}, 0)
  1574. // sendMap4["value"] = sendStr
  1575. // sendMap4["color"] = "#173177"
  1576. // sendList = append(sendList, sendMap4)
  1577. // sendMap2 := make(map[string]interface{}, 0)
  1578. // sendMap2["value"] = time.Now().Format("2006-01-02 15:04:05")
  1579. // sendMap2["color"] = "#173177"
  1580. // sendList = append(sendList, sendMap2)
  1581. // sendMap5 := make(map[string]interface{}, 0)
  1582. // sendMap5["value"] = "无备注"
  1583. // sendMap5["color"] = "#173177"
  1584. // sendList = append(sendList, sendMap5)
  1585. // wxPush(openIdList, sendList, pastureid, data["service_id"].(int64))
  1586. // }
  1587. if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
  1588. appG.Response(http.StatusOK, e.SUCCESS, tempval)
  1589. } else {
  1590. appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
  1591. }
  1592. } else {
  1593. msg := geterrmsg(err.Error())
  1594. appG.Response(http.StatusOK, e.ERROR, msg)
  1595. }
  1596. }
  1597. }
  1598. if err != nil {
  1599. msg := geterrmsg(err.Error())
  1600. appG.Response(http.StatusOK, e.ERROR, msg)
  1601. }
  1602. }
  1603. func inventoryWarning(target []string, pastureId string, serviceId int64) {
  1604. tx := restful.Engine.NewSession()
  1605. defer tx.Close()
  1606. feedstorageList, err := tx.SQL(`
  1607. SELECT
  1608. (select fname from feed where pastureid =fs.pastureid and id = fs.feedid ) feedname,
  1609. fs.stockweight,round(fs.lweight,2) avgweight, if (fs.stockweight<=0,0, FLOOR(fs.stockweight/fs.lweight)) ldays,
  1610. TRIM(fs.feedid) feedid,
  1611. TRIM(fs.pastureid) pastureid,
  1612. DATE_FORMAT((select max(date) from fswarnhis where pastureid = fs.pastureid and feedid = fs.feedid ), '%Y-%m-%d') lastdate
  1613. FROM (SELECT fs.pushstatus,
  1614. fs.id,
  1615. fs.feedname,fs.stockweight,
  1616. fs.feedid feedid,
  1617. fs.pastureid pastureid,DATE_FORMAT(NOW(), '%Y-%m-%d') lastdate,
  1618. (SELECT SUM(d.lweight)/7 lweight FROM downloadplandtl1 d WHERE d.pastureid = fs.pastureid
  1619. AND date >= DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -7 DAY), '%Y-%m-%d')
  1620. AND date <DATE_FORMAT(NOW(), '%Y-%m-%d') AND d.fid = fs.feedid) lweight
  1621. FROM feedstorage fs) fs
  1622. WHERE fs.pastureid=? AND fs.stockweight< fs.lweight*(SELECT inforvalue FROM sysopt WHERE sysopt.pastureid = fs.pastureid
  1623. AND inforname = 'repertoryWarn')
  1624. ORDER BY ldays ,stockweight `).Query().List()
  1625. if err != nil {
  1626. logs.Error("inventoryWarning-error-1:", err)
  1627. return
  1628. }
  1629. for _, f := range feedstorageList {
  1630. var sendList []interface{}
  1631. sendStr := fmt.Sprintf("饲料名称:%v\n库存量(kg):%s\n近7天平均计划量:%v\n剩余使用天数:%v",
  1632. f["feedname"], f["stockweight"], f["lweight"], f["ldays"])
  1633. sendMap1 := make(map[string]interface{}, 0)
  1634. sendMap1["value"] = "库存预警"
  1635. sendMap1["color"] = "#173177"
  1636. sendList = append(sendList, sendMap1)
  1637. sendMap4 := make(map[string]interface{}, 0)
  1638. sendMap4["value"] = sendStr
  1639. sendMap4["color"] = "#173177"
  1640. sendList = append(sendList, sendMap4)
  1641. sendMap2 := make(map[string]interface{}, 0)
  1642. sendMap2["value"] = time.Now().Format("2006-01-02 15:04:05")
  1643. sendMap2["color"] = "#173177"
  1644. sendList = append(sendList, sendMap2)
  1645. sendMap5 := make(map[string]interface{}, 0)
  1646. sendMap5["value"] = "无备注"
  1647. sendMap5["color"] = "#173177"
  1648. sendList = append(sendList, sendMap5)
  1649. wxPush(target, sendList, pastureId, serviceId)
  1650. }
  1651. }
  1652. func udFeedpSync(pastureinfo *udPastureInfo) error {
  1653. tx := restful.Engine.NewSession()
  1654. defer tx.Close()
  1655. downList := make([]*ScheduledDownInfo, 0)
  1656. down := tx.Table("scheduled_down")
  1657. down.Where("company = ? ", "ud")
  1658. down.Where("methods = ? ", "SyncFeedp")
  1659. err := down.Find(&downList)
  1660. if err != nil {
  1661. log.Println("UpdateDown-error-1: ", err)
  1662. return err
  1663. }
  1664. for _, item := range downList {
  1665. list := httpGetMC(item.Addres, item.Targetdata)
  1666. if item.Methods != "" {
  1667. s := ScheduledDown{}
  1668. value := reflect.ValueOf(&s)
  1669. f := value.MethodByName(item.Methods)
  1670. f.Call([]reflect.Value{reflect.ValueOf(pastureinfo.Pastureid), reflect.ValueOf(list)})
  1671. }
  1672. }
  1673. return nil
  1674. }
  1675. func UdFeedpSync(c *gin.Context) {
  1676. appG := app.Gin{C: c}
  1677. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1678. fsion := gofasion.NewFasion(string(dataByte))
  1679. pastureId := fsion.Get("pastureId").ValueStr()
  1680. // pastureinfo := new(udPastureInfo)
  1681. // pastureinfo.Pastureid = pastureId
  1682. // udFeedpSync(pastureinfo)
  1683. pastureinfo := new(udPastureInfo)
  1684. pastureinfo.Pastureid = pastureId
  1685. err := udFeedpSync(pastureinfo)
  1686. if err != nil {
  1687. appG.Response(http.StatusOK, e.ERROR, err.Error())
  1688. return
  1689. }
  1690. appG.Response(http.StatusOK, e.SUCCESS, true)
  1691. // return
  1692. }
  1693. func udFeedSync(pastureinfo *udPastureInfo) error {
  1694. tx := restful.Engine.NewSession()
  1695. defer tx.Close()
  1696. downList := make([]*ScheduledDownInfo, 0)
  1697. down := tx.Table("scheduled_down")
  1698. down.Where("company = ? ", "ud")
  1699. down.Where("methods = ? ", "SyncFeed")
  1700. err := down.Find(&downList)
  1701. if err != nil {
  1702. log.Println("UpdateDown-error-1: ", err)
  1703. return err
  1704. }
  1705. for _, item := range downList {
  1706. list := httpGetMC(item.Addres, item.Targetdata)
  1707. if item.Methods != "" {
  1708. s := ScheduledDown{}
  1709. value := reflect.ValueOf(&s)
  1710. f := value.MethodByName(item.Methods)
  1711. f.Call([]reflect.Value{reflect.ValueOf(pastureinfo.Pastureid), reflect.ValueOf(list)})
  1712. }
  1713. }
  1714. return nil
  1715. }
  1716. func XxwFeedtemplet(pastureId string) {
  1717. tx := restful.Engine.NewSession()
  1718. defer tx.Close()
  1719. count, _ := tx.SQL(`select count(1) from notice where content = 'xxwFeedtemplet' and status = 1 `).Count()
  1720. // fmt.Println(count)
  1721. // count = 1
  1722. // pastureId = "1725428057"
  1723. if count == 1 {
  1724. tx.Exec(` delete from ftdetail_sync `)
  1725. tx.Exec(` INSERT INTO ftdetail_sync (
  1726. id,
  1727. pastureid,
  1728. ftid,
  1729. fid,
  1730. fname,
  1731. lweight,
  1732. fweight,
  1733. islockcount,
  1734. isfg,
  1735. sort,
  1736. feedgroup,
  1737. preftid,
  1738. autosecond,
  1739. autosecondname,
  1740. splitftpreid,
  1741. deviation,
  1742. is_show
  1743. ) SELECT
  1744. id,
  1745. pastureid,
  1746. ftid,
  1747. fid,
  1748. fname,
  1749. lweight,
  1750. fweight,
  1751. islockcount,
  1752. isfg,
  1753. sort,
  1754. feedgroup,
  1755. preftid,
  1756. ifnull(autosecond,0),
  1757. autosecondname,
  1758. splitftpreid,
  1759. deviation,
  1760. is_show
  1761. FROM
  1762. ftdetail`)
  1763. ftList, err := tx.SQL(` SELECT
  1764. IFNULL(recipeId, '') AS recipeId,
  1765. IFNULL(fodderId, '') AS fodderId,
  1766. sum(IFNULL(autoWeight, '')) AS autoWeight,
  1767. IFNULL(fodderName, '') AS fodderName,
  1768. IFNULL(orderNum, '') AS orderNum,
  1769. IFNULL(mergerFodderId, '') AS mergerFodderId,
  1770. IFNULL(mergerFodderName, '') AS mergerFodderName
  1771. FROM
  1772. xxw_feedtemplet group by recipeId,mergerFodderId`).QueryString()
  1773. if err != nil {
  1774. log.Println("XxwFeedtemplet-error-1: ", err)
  1775. return
  1776. }
  1777. dataList, err := tx.SQL(` SELECT
  1778. IFNULL(recipeId, '') AS recipeId,
  1779. IFNULL(fodderId, '') AS fodderId,
  1780. IFNULL(fodderName, '') AS fodderName,
  1781. IFNULL(autoWeight, '') AS autoWeight,
  1782. IFNULL(orderNum, '') AS orderNum,
  1783. IFNULL(mergerFodderId, '') AS mergerFodderId,
  1784. IFNULL(mergerFodderName, '') AS mergerFodderName
  1785. FROM
  1786. xxw_feedtemplet `).QueryString()
  1787. if err != nil {
  1788. log.Println("XxwFeedtemplet-error-1: ", err)
  1789. return
  1790. }
  1791. // for _, item := range ftList {
  1792. tx.Exec(` delete from ftdetail where ftid in(select id from feedtemplet where xxwTempletCode is not null ) `)
  1793. // }
  1794. for _, item := range ftList {
  1795. ids, err := setting.SnowIds.NextId()
  1796. if err != nil {
  1797. ids = time.Now().UnixNano()
  1798. logging.Info("create SnowIds err", err)
  1799. }
  1800. /*
  1801. if item["mergerFodderId"] == "" {
  1802. _, err = tx.Exec("insert into feedtemplet(id,pastureid,ccid,tcode,tname,fttypeid,fttype,xxwTempletCode) "+
  1803. "values(?,?,(select id from cowclass where pastureid = ? limit 1),?,?,1,'饲喂配方',?) "+
  1804. " ON DUPLICATE KEY UPDATE owner ='丰顿下发' ", ids, pastureId, pastureId, item["recipeId"], item["recipeId"], item["recipeId"])
  1805. if err != nil {
  1806. log.Println("XxwFeedtemplet-error-2: ", err)
  1807. return
  1808. }
  1809. }
  1810. */
  1811. // /*
  1812. if item["mergerFodderId"] == "" {
  1813. _, err = tx.Exec("insert into feedtemplet(id,pastureid,ccid,tcode,tname,fttypeid,fttype,xxwTempletCode) "+
  1814. "values(?,?,(select id from cowclass where pastureid = ? limit 1),?,?,1,'饲喂配方',?) "+
  1815. " ON DUPLICATE KEY UPDATE owner ='丰顿下发' ", ids, pastureId, pastureId, item["recipeId"],
  1816. item["recipeId"], item["recipeId"])
  1817. if err != nil {
  1818. log.Println("XxwFeedtemplet-error-2: ", err)
  1819. return
  1820. }
  1821. _, err = tx.Exec(` update feedtemplet f set tcode = (select if(left((select max(tcode) from
  1822. feedtemplet where pastureid = ?),8) = (select DATE_FORMAT(now(),"%Y%m%d")),
  1823. (select max(tcode)+1 from feedtemplet where pastureid = ?),
  1824. (select concat(DATE_FORMAT(now(),"%Y%m%d"),"001"))))
  1825. where xxwTempletCode = ? and tcode is null `, pastureId, pastureId, item["recipeId"])
  1826. if err != nil {
  1827. log.Println("XxwFeedtemplet-error-3: ", err)
  1828. return
  1829. }
  1830. // */
  1831. } else {
  1832. _, err = tx.Exec(`insert into feedtemplet(id,pastureid,ccid,tname,fttypeid,fttype,xxwTempletCode)
  1833. values(?,?,(select id from cowclass where pastureid = ? limit 1),?,2,'预混配方',?)
  1834. ON DUPLICATE KEY UPDATE owner ='丰顿下发' `, ids, pastureId, pastureId,
  1835. item["mergerFodderName"]+item["recipeId"], item["mergerFodderId"])
  1836. if err != nil {
  1837. log.Println("XxwFeedtemplet-error-3: ", err)
  1838. return
  1839. }
  1840. _, err = tx.Exec(` update feedtemplet f set tcode = (select if(left((select max(tcode) from
  1841. feedtemplet where pastureid = ?),8) = (select DATE_FORMAT(now(),"%Y%m%d")),
  1842. (select max(tcode)+1 from feedtemplet where pastureid = ?),
  1843. (select concat(DATE_FORMAT(now(),"%Y%m%d"),"001"))))
  1844. where xxwTempletCode = ? and tcode is null `, pastureId, pastureId, item["mergerFodderId"])
  1845. if err != nil {
  1846. log.Println("XxwFeedtemplet-error-3: ", err)
  1847. return
  1848. }
  1849. tx.Exec(` update feedtemplet f set ccname = (select classname from cowclass where id = f.ccid )
  1850. where xxwTempletCode = ? and tcode is null `, item["mergerFodderId"])
  1851. ids, err := setting.SnowIds.NextId()
  1852. if err != nil {
  1853. ids = time.Now().UnixNano()
  1854. logging.Info("create SnowIds err", err)
  1855. }
  1856. _, err = tx.Exec(`insert into ftdetail(id,pastureid,ftid,fid,fname,fweight,sort,autosecond,autosecondname,feedgroup,preftid,version)
  1857. values(?,?,(select id from feedtemplet where pastureid=? and xxwTempletCode=? limit 1),
  1858. (select id from feedtemplet where pastureid=? and xxwTempletCode=? limit 1) ,?,?,?,0,'',?,
  1859. (select id from feedtemplet where pastureid=? and xxwTempletCode =? limit 1),
  1860. (select version from feedtemplet where pastureid=? and xxwTempletCode=? limit 1)) `,
  1861. ids, pastureId, pastureId, item["recipeId"], pastureId, item["mergerFodderId"], item["mergerFodderName"]+item["recipeId"], item["autoWeight"],
  1862. item["orderNum"], item["mergerFodderName"], pastureId, item["mergerFodderId"], pastureId, item["recipeId"])
  1863. if err != nil {
  1864. log.Println("XxwFeedtemplet-error-4: ", err)
  1865. return
  1866. }
  1867. }
  1868. }
  1869. for _, item := range dataList {
  1870. ids, err := setting.SnowIds.NextId()
  1871. if err != nil {
  1872. ids = time.Now().UnixNano()
  1873. logging.Info("create SnowIds err", err)
  1874. }
  1875. if item["mergerFodderId"] == "" {
  1876. _, err = tx.Exec("insert into ftdetail(id,pastureid,ftid,fid,fname,fweight,sort,autosecond,autosecondname,feedgroup,version) "+
  1877. " values(?,?,(select id from feedtemplet where pastureid=? and xxwTempletCode=? limit 1),"+
  1878. " (select id from feed where pastureid=? and xxwFeedCode=? limit 1) ,?,?,?,0,'',?,(select version from feedtemplet where pastureid=? and xxwTempletCode=? limit 1)) ",
  1879. ids, pastureId, pastureId, item["recipeId"], pastureId, item["fodderId"], item["fodderName"], item["autoWeight"],
  1880. item["orderNum"], item["fodderName"], pastureId, item["recipeId"])
  1881. if err != nil {
  1882. log.Println(item)
  1883. log.Println("XxwFeedtemplet-error-5: ", err)
  1884. return
  1885. }
  1886. } else {
  1887. // /*
  1888. _, err = tx.Exec("insert into ftdetail(id,pastureid,ftid,fid,fname,fweight,sort,autosecond,autosecondname,feedgroup,version) "+
  1889. " values(?,?,(select id from feedtemplet where pastureid=? and xxwTempletCode=? limit 1),"+
  1890. " (select id from feed where pastureid=? and xxwFeedCode=? limit 1) ,?,?,?,0,'',?,(select version from feedtemplet where pastureid=? and xxwTempletCode=? limit 1)) ON DUPLICATE KEY UPDATE pastureid = ? ",
  1891. ids, pastureId, pastureId, item["mergerFodderId"], pastureId, item["fodderId"], item["fodderName"], item["autoWeight"],
  1892. item["orderNum"], item["fodderName"], pastureId, item["mergerFodderId"], pastureId)
  1893. if err != nil {
  1894. log.Println("XxwFeedtemplet-error-6: ", err)
  1895. return
  1896. }
  1897. // */
  1898. /*
  1899. _, err = tx.Exec("insert into ftdetail(id,pastureid,ftid,fid,fname,fweight,sort,autosecond,autosecondname,feedgroup,version) "+
  1900. " values(?,?,(select id from feedtemplet where pastureid=? and xxwTempletCode=? limit 1),"+
  1901. " (select id from feed where pastureid=? and xxwFeedCode=? limit 1) ,?,?,?,0,'',?,(select version from feedtemplet where pastureid=? and xxwTempletCode=? limit 1)) ",
  1902. ids, pastureId, pastureId, item["recipeId"], pastureId, item["fodderId"], item["fodderName"], item["autoWeight"],
  1903. item["orderNum"], item["mergerFodderName"], pastureId, item["recipeId"])
  1904. if err != nil {
  1905. log.Println("XxwFeedtemplet-error-7: ", err)
  1906. return
  1907. }
  1908. */
  1909. }
  1910. }
  1911. tx.Exec(`update ftdetail f set autosecond = (select autosecond from ftdetail_sync where ftid = f.ftid and fid = f.fid ) ,
  1912. autosecondname = (select autosecondname from ftdetail_sync where ftid = f.ftid and fid = f.fid ) `)
  1913. feedingList, err := tx.SQL(` SELECT
  1914. IFNULL(recipeId, '') AS recipeId
  1915. FROM
  1916. xxw_feedtemplet group by recipeId`).QueryString()
  1917. if err != nil {
  1918. log.Println("XxwFeedtemplet-error-1: ", err)
  1919. return
  1920. }
  1921. tx.Exec(` UPDATE notice SET status = 0 WHERE content = 'xxwFeedtemplet' `)
  1922. for _, feeding := range feedingList {
  1923. values1, _ := tx.SQL(`select b.bname barname, ifnull(ccount,0) ccount,ifnull(ratio,0) ratio,ftname,ptsfname,
  1924. ifnull((select tratio from fpdetail where barid = fp.barid and times = 1 ),0) as '1' ,
  1925. ifnull((select tratio from fpdetail where barid = fp.barid and times = 2
  1926. ),0) as '2' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 3
  1927. ),0) as '3' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 4
  1928. ),0) as '4' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 5
  1929. ),0) as '5' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 6
  1930. ),0) as '6' from feedp fp join bar b on b.id = fp.barid
  1931. join feedtemplet ft on ft.id = fp.ftid where ft.xxwTempletCode = ? `, feeding["recipeId"]).QueryString()
  1932. fmt.Println(feeding["recipeId"])
  1933. FpdBatchEditGrfd(pastureId, values1)
  1934. }
  1935. }
  1936. }
  1937. func xxwFeedpSync(pastureId string) {
  1938. tx := restful.Engine.NewSession()
  1939. defer tx.Close()
  1940. count, _ := tx.SQL(`select count(1) from notice where content = 'xxwBarCcount' and status = 1 `).Count()
  1941. if count == 1 {
  1942. tx.Exec(` UPDATE notice SET status = 0 WHERE content = 'xxwBarCcount' `)
  1943. values1, err := tx.SQL(`select b.bname barname, ifnull(ccount,0) ccount,ifnull(ratio,0) ratio,ftname,ptsfname,
  1944. ifnull((select tratio from fpdetail where barid = fp.barid and times = 1 ),0) as '1',
  1945. ifnull((select tratio from fpdetail where barid = fp.barid and times = 2
  1946. ),0) as '2' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 3
  1947. ),0) as '3' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 4
  1948. ),0) as '4' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 5
  1949. ),0) as '5' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 6
  1950. ),0) as '6' from feedp fp join bar b on b.id = fp.barid
  1951. join feedtemplet ft on ft.id = fp.ftid
  1952. where b.pastureid = ? and fp.ccount > 0 and fp.ftid >0 `, pastureId).QueryString()
  1953. fmt.Println(err)
  1954. FpdBatchEditGrfd(pastureId, values1)
  1955. }
  1956. }
  1957. func LYFDSync(c *gin.Context) {
  1958. appG := app.Gin{C: c}
  1959. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  1960. fsion := gofasion.NewFasion(string(dataByte))
  1961. method := fsion.Get("method").ValueStr()
  1962. finalData := fsion.Get("finalDate").Array()
  1963. fmt.Println(method)
  1964. tx := restful.Engine.NewSession()
  1965. defer tx.Close()
  1966. pastureinfo := new(udPastureInfo)
  1967. err := tx.SQL(`select column_default as pastureid,(select werks from pasture where pastureid = column_default) werks from information_schema.COLUMNS
  1968. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  1969. if err != nil {
  1970. logs.Error(err)
  1971. return
  1972. }
  1973. if method == "getPubBars" {
  1974. //牛舍,牛头数同步
  1975. getPubBars(finalData, tx, pastureinfo.Pastureid)
  1976. } else if method == "getMaterial" {
  1977. getMaterial(finalData, tx, pastureinfo.Pastureid)
  1978. } else if method == "getMaterialInfo" {
  1979. getMaterialInfo(finalData, tx, pastureinfo.Pastureid)
  1980. } else if method == "getTFeedRecipesKind" {
  1981. getTFeedRecipesKind(finalData, tx, pastureinfo.Pastureid)
  1982. }
  1983. appG.Response(http.StatusOK, e.SUCCESS, nil)
  1984. }
  1985. func getPubBars(finalData []*gofasion.Fasion, tx *xorm.Session, pastureId string) {
  1986. for _, f := range finalData {
  1987. barName := f.Get("barName").ValueStr()
  1988. barGroup := f.Get("barGroup").ValueStr()
  1989. ccount := f.Get("counts").ValueStr()
  1990. _, err := tx.Exec(`insert into bar(pastureid,bcode,bname,xxwBarCode)values(?,?,?,?) ON DUPLICATE KEY UPDATE bname = ? `, pastureId, barGroup,
  1991. barName, barGroup, barName)
  1992. // INSERT INTO `tmrwatch5`.`feedp` (`pastureid`, `barname`, `barid`, `softccount`, `ccount`) VALUES (1, '1', 1, 0, 1)
  1993. fmt.Println(err)
  1994. _, err = tx.Exec(`insert into feedp(pastureid, barname, barid, softccount,ccount,xxwBarCode)
  1995. values(?,?,(select id from bar where bcode = ? and pastureId = ? ),?,?,?)
  1996. ON DUPLICATE KEY UPDATE barname = ?,ccount = ? `, pastureId, barName,
  1997. barGroup, pastureId, 0,
  1998. ccount, barGroup, barName, ccount)
  1999. fmt.Println(err)
  2000. values1, err := tx.SQL(`select b.bname barname, ifnull(ccount,0) ccount,ifnull(ratio,0) ratio,ftname,ptsfname,
  2001. ifnull((select tratio from fpdetail where barid = fp.barid and times = 1 ),0) as '1',
  2002. ifnull((select tratio from fpdetail where barid = fp.barid and times = 2
  2003. ),0) as '2' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 3
  2004. ),0) as '3' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 4
  2005. ),0) as '4' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 5
  2006. ),0) as '5' ,ifnull((select tratio from fpdetail where barid = fp.barid and times = 6
  2007. ),0) as '6' from feedp fp join bar b on b.id = fp.barid
  2008. join feedtemplet ft on ft.id = fp.ftid
  2009. where b.pastureid = ? and fp.ccount > 0 and fp.ftid >0 and b.bcode = ? `, pastureId, barGroup).QueryString()
  2010. fmt.Println(err)
  2011. if len(values1) != 0 {
  2012. FpdBatchEditGrfd(pastureId, values1)
  2013. }
  2014. }
  2015. }
  2016. func getMaterial(finalData []*gofasion.Fasion, tx *xorm.Session, pastureId string) {
  2017. for _, f := range finalData {
  2018. ids, err := setting.SnowIds.NextId()
  2019. if err != nil {
  2020. ids = time.Now().UnixNano()
  2021. logging.Info("create SnowIds err", err)
  2022. }
  2023. feedclassName := f.Get("feedclassName").ValueStr()
  2024. _, err = tx.SQL(`insert into feedclass(id,pastureid,fccode,fcname,bigfeedclassname,bigfeedclassid,sort,backup1)
  2025. vALUES(?,?,?,?,?,?,(select ifnull(max(f.sort),0) +1 from feedclass f where f.pastureid =? ),?)
  2026. ON DUPLICATE KEY UPDATE backup1 = '丰顿' `,
  2027. ids, pastureId, f.Get("feedclassid").ValueStr(), feedclassName, feedclassName, ids, pastureId, "丰顿").Execute()
  2028. if err != nil {
  2029. logs.Error("getMaterial-error-1:", err)
  2030. return
  2031. }
  2032. }
  2033. }
  2034. func getMaterialInfo(finalData []*gofasion.Fasion, tx *xorm.Session, pastureId string) {
  2035. for _, f := range finalData {
  2036. feedclassid := f.Get("feedclassid").ValueStr()
  2037. _, err := tx.Exec(` insert into feed(pastureid,fclass,fclassid,feedcode,fname,allowratio,uprice,xxwFeedCode)
  2038. values(?,?,(select id from feedclass where fcname = ? and pastureid = ? ),?,?,?,?,?) ON DUPLICATE KEY UPDATE source = '丰顿' `,
  2039. pastureId, f.Get("feedclassName").ValueStr(), f.Get("feedclassName").ValueStr(), pastureId,
  2040. feedclassid, f.Get("fodderName").ValueStr(), f.Get("autoWeight").ValueStr(),
  2041. f.Get("standardPrice").ValueStr(), feedclassid)
  2042. fmt.Println(err)
  2043. }
  2044. }
  2045. func getTFeedRecipesKind(finalData []*gofasion.Fasion, tx *xorm.Session, pastureId string) {
  2046. for _, f := range finalData {
  2047. ids, err := setting.SnowIds.NextId()
  2048. if err != nil {
  2049. ids = time.Now().UnixNano()
  2050. logging.Info("create SnowIds err", err)
  2051. }
  2052. recipeobjNAME := f.Get("recipeobjNAME").ValueStr()
  2053. _, err = tx.Exec(` insert into cowclass(id,pastureId,classcode,classname,parentid,parentname,sort)
  2054. values(?,?,?,?,?,?,(select ifnull(max(f.sort),0) +1 from cowclass f where f.pastureid =? ) ) ON DUPLICATE KEY UPDATE classname = ?`,
  2055. ids, pastureId, recipeobjNAME, recipeobjNAME, ids,
  2056. recipeobjNAME, pastureId, recipeobjNAME)
  2057. if err != nil {
  2058. logs.Error(err)
  2059. return
  2060. }
  2061. }
  2062. }