scheduled.go 80 KB

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