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