scheduled.go 80 KB

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