scheduled.go 78 KB

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