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