scheduled.go 79 KB

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