scheduled.go 61 KB

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