scheduled.go 79 KB

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