scheduled.go 78 KB

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