scheduled.go 79 KB

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