scheduled.go 80 KB

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