scheduled.go 79 KB

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