scheduled.go 79 KB

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