sap.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. package sap
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. "time"
  9. "tmr-watch/conf/setting"
  10. "tmr-watch/http/handle/restful"
  11. "tmr-watch/pkg/app"
  12. "tmr-watch/pkg/e"
  13. "github.com/Anderson-Lu/gofasion/gofasion"
  14. "github.com/astaxie/beego/logs"
  15. "github.com/gin-gonic/gin"
  16. "github.com/xormplus/xorm"
  17. )
  18. func SyncMaterialOutbound() error {
  19. tx := restful.Engine.NewSession()
  20. defer tx.Close()
  21. pastureinfo := new(udPastureInfo)
  22. err := tx.SQL(`select column_default as pastureid from information_schema.COLUMNS
  23. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  24. if err != nil {
  25. logs.Error(err)
  26. return err
  27. }
  28. materialOutbound(pastureinfo.Pastureid, time.Now().AddDate(0, 0, -1).Format("2006-01-02"))
  29. return nil
  30. }
  31. func SyncSapBar(c *gin.Context) {
  32. appG := app.Gin{C: c}
  33. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  34. fsion := gofasion.NewFasion(string(dataByte))
  35. start := fsion.Get("startTime").ValueStr()
  36. end := fsion.Get("endTime").ValueStr()
  37. pastureId := fsion.Get("pastureId").ValueStr()
  38. tx := restful.Engine.NewSession()
  39. defer tx.Close()
  40. pastureinfo := new(udPastureInfo)
  41. err := tx.SQL(`select * from pasture where pastureid = ?`, pastureId).GetFirst(pastureinfo).Error
  42. if err != nil {
  43. logs.Error(err)
  44. return
  45. }
  46. // year := time.Now().Year()
  47. data := `{
  48. "DATA": {
  49. "DIDAT": "%s",
  50. "DITIM": "%s",
  51. "WERKS": "%s"
  52. },
  53. "DEST": {
  54. "DEST_ID": "TMRWATCH",
  55. "BUSS_TP": "CO005"
  56. }
  57. }`
  58. startTime, _ := time.ParseInLocation("2006-01-02", start, time.Local)
  59. endTime, _ := time.ParseInLocation("2006-01-02", end, time.Local)
  60. url := "http://192.168.61.117/SAPP0/Feed/CO005/QueryCowsheds"
  61. data = fmt.Sprintf(data, startTime.Format("20060102"), endTime.Format("20060102"), pastureinfo.Werks)
  62. respmap, _ := postPush(url, data, 3, tx, pastureId)
  63. if respmap != nil {
  64. if _, ok := respmap.(map[string]interface{})["ZTCO_001"]; ok {
  65. for _, item := range respmap.(map[string]interface{})["ZTCO_001"].([]interface{}) {
  66. barMap := item.(map[string]interface{})
  67. _, err := tx.SQL(` insert into bar(pastureid,bcode,bname,sort,class,classcode,cattle,cattlecode,sapcode)
  68. values(?,?,?,(select max(sort)+1 from bar b where b.pastureid = ? ),
  69. (select distName from dist where distCode = ? and distType = '牛舍类型' ),?,
  70. (select distName from dist where distCode = ? and distType = '牛群类别'),?,?)
  71. ON DUPLICATE KEY UPDATE bname = ? ,
  72. class = (select distName from dist where distCode = ? and distType = '牛舍类型' ) ,classcode = ?,
  73. cattle = (select distName from dist where distCode = ? and distType = '牛群类别' ) ,cattlecode = ?
  74. `,
  75. pastureId, barMap["CHSNO"], fmt.Sprintf("%v_sap", barMap["CHSTX"]), pastureId, barMap["CHSTY"], barMap["CHSTY"],
  76. barMap["FCWTS"], barMap["FCWTS"], barMap["CHSNO"],
  77. fmt.Sprintf("%v_sap", barMap["CHSTX"]), barMap["CHSTY"], barMap["CHSTY"], barMap["FCWTS"], barMap["FCWTS"]).Execute()
  78. if err != nil {
  79. logs.Error(err)
  80. return
  81. }
  82. }
  83. }
  84. }
  85. appG.Response(http.StatusOK, e.SUCCESS, true)
  86. }
  87. type udPastureInfo struct {
  88. Werks string `xorm:"werks"`
  89. Pastureid string `xorm:"pastureid"`
  90. }
  91. func MaterialOutbound(c *gin.Context) {
  92. appG := app.Gin{C: c}
  93. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  94. fsion := gofasion.NewFasion(string(dataByte))
  95. pastureId := fsion.Get("pastureid").ValueStr()
  96. date := fsion.Get("date").ValueStr()
  97. materialOutbound(pastureId, date)
  98. appG.Response(http.StatusOK, e.SUCCESS, true)
  99. }
  100. func materialOutbound(pastureId, date string) error {
  101. tx := restful.Engine.NewSession()
  102. defer tx.Close()
  103. pastureinfo := new(udPastureInfo)
  104. err := tx.SQL(`select * from pasture where pastureid = ?`, pastureId).GetFirst(pastureinfo).Error
  105. if err != nil {
  106. logs.Error(err)
  107. return err
  108. }
  109. dataList, err := tx.SQL(` SELECT
  110. tem.sort ZEILE,
  111. tem.feedname MAKTX,
  112. ifnull(ROUND(if(tem.lweight<0,0,tem.lweight),(select inforvalue from sysopt where inforname="decimalPlaces" and pastureid =? )),0)lweight,
  113. ifnull(ROUND(tem.actualweightminus,(select inforvalue from sysopt where inforname="decimalPlaces" and pastureid = ?)),0) MENGE
  114. ,tem.bname CHSTX,tem.sapcode CHSNO,tem.cattle FCWTS,tem.MATNR,tem.sapGoods LGORT
  115. FROM (
  116. (SELECT
  117. d2.type,
  118. d2.fname,IFNULL(ftd.fname,d1.fname ) feedname,
  119. SUM(
  120. d2.lweight/(SELECT SUM(lweight) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  121. d1.lweight*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid and ftd2.date= ftp.date ))
  122. )lweight,
  123. d1.sort sort,
  124. SUM(
  125. if ( (SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date) > 0 ,
  126. d2.actualweightminus/(SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  127. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid and ftd2.date= ftp.date )),
  128. d2.lweight/(SELECT SUM(lweight) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  129. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetail ftd2 WHERE ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid ))
  130. )
  131. )actualweightminus,b.sort as d2sort,b.bname,b.sapcode, b.cattlecode ,f.sapCode MATNR,f.sapGoods ,(select cattle from feedtemplet where id = d.tempid) cattle
  132. FROM
  133. downloadedplan d
  134. JOIN downloadplandtl2 d2
  135. ON d.pastureid = d2.pastureid AND d2.pid = d.id and d2.type = 0
  136. JOIN downloadplandtl1 d1
  137. ON d.pastureid = d1.pastureid AND d1.flpid = d2.flpid AND d1.type = 0 AND d2.date = d1.date
  138. LEFT JOIN ftdetaildate ftd ON ftd.pastureid =d1.pastureid AND ftd.ftid = d1.fid AND d1.feedcode = '-1' AND ftd.date = d.mydate AND ftd.version = d.tversion
  139. left join bar b on b.pastureid =d1.pastureid and b.id = d2.fbarid
  140. left join feed f on f.id = d1.fid
  141. left join feedtempletdate ftp on ftp.id = d.tempid AND ftp.date = ftd.date
  142. WHERE d.pastureid = ? AND d.mydate = ? and d1.feedcode != -1 and b.sapCode is not null and f.sapCode is not null
  143. GROUP BY d2.fbarid,IFNULL(ftd.fname,d1.fname )
  144. HAVING d2.type = 0 order by b.sort,d2.fbarid)
  145. UNION
  146. (SELECT
  147. d2.type,
  148. d2.fname,IFNULL(ftd.fname,d1.fname ) feedname,
  149. SUM(
  150. d2.lweight/(SELECT SUM(lweight) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  151. d1.lweight*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid and ftd2.date= ftp.date ))
  152. )lweight,
  153. d1.sort sort,
  154. SUM(
  155. if ( (SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date) > 0 ,
  156. d2.actualweightminus/(SELECT SUM(actualweightminus) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  157. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetaildate ftd2 WHERE ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid and ftd2.date= ftp.date )),
  158. d2.lweight/(SELECT SUM(lweight) FROM downloadplandtl2 d2t WHERE d2t.pastureid = d2.pastureid AND d2t.flpid = d2.flpid AND d2t.type = 0 AND d2t.date = d2.date)*
  159. d1.actualweightminus*IF(ftd.id IS NULL,1,ftd.fweight/(SELECT SUM(ftd2.fweight) FROM ftdetail ftd2 WHERE ftd2.pastureid =d1.pastureid AND ftd2.ftid = d1.fid ))
  160. )
  161. )actualweightminus,b.sort as d2sort,b.bname,b.sapcode, b.cattlecode ,f.sapCode MATNR,f.sapGoods ,(select cattle from feedtemplet where id = d.tempid) cattle
  162. FROM
  163. downloadedplan d
  164. JOIN downloadplandtl2 d2
  165. ON d.pastureid = d2.pastureid AND d2.pid = d.id and d2.type = 0
  166. JOIN downloadplandtl1 d1
  167. ON d.pastureid = d1.pastureid AND d1.flpid = d2.flpid AND d1.type = 0 AND d2.date = d1.date
  168. -- LEFT JOIN ftdetaildate ftd ON ftd.pastureid =d1.pastureid AND ftd.ftid = d1.fid AND d1.feedcode = '-1' AND ftd.date = d.mydate AND ftd.version = d.tversion
  169. left join bar b on b.pastureid =d1.pastureid and b.id = d2.fbarid
  170. left join feedtempletdate ftp on ftp.id = d1.fid and ftp.date = ?
  171. left join ftdetaildate ftd on ftd.ftid = ftp.id and ftd.date = ?
  172. left join feed f on f.id = ftd.fid
  173. WHERE d.pastureid = ? AND d.mydate = ? and d1.feedcode = -1 and b.sapCode is not null and f.sapCode is not null
  174. GROUP BY d2.fbarid,IFNULL(ftd.fname,d1.fname )
  175. HAVING d2.type = 0 order by b.sort,d2.fbarid)
  176. ) tem
  177. ORDER BY tem.d2sort,tem.feedname `, pastureId, pastureId, pastureId, date, date, date, pastureId, date).Query().List()
  178. if err != nil {
  179. logs.Error(err)
  180. return err
  181. }
  182. data := `{
  183. "DEST": {
  184. "DEST_ID": "DFEED",
  185. "BUSS_TP": "MM016"
  186. },
  187. "DATA": {
  188. "BUDAT": "%s",
  189. "WERKS": "%s",
  190. "ITEMS": %s
  191. }
  192. }`
  193. databyte, _ := json.Marshal(dataList)
  194. now, _ := time.ParseInLocation("2006-01-02", date, time.Local)
  195. data = fmt.Sprintf(data, now.Format("20060102"), pastureinfo.Werks, string(databyte))
  196. url := "http://192.168.61.117/SAPP0/Feed/MM016/StockOut"
  197. postPush(url, data, 0, tx, pastureId)
  198. return nil
  199. // appG.Response(http.StatusOK, e.SUCCESS, true)
  200. }
  201. func postPush(url, data string, msgtype int, tx *xorm.Session, pastureId string) (interface{}, bool) {
  202. var jsonStr = []byte(data)
  203. req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
  204. if err != nil {
  205. logs.Error(err)
  206. // return nil
  207. }
  208. // req.SetBasicAuth("zinf_TMR", "zinf_TMR@1234") 测试线密码
  209. req.SetBasicAuth("zinf_TMR", "$C2Cj$\\Uv#")
  210. req.Header.Set("Content-Type", "application/json")
  211. client := &http.Client{}
  212. resp, err := client.Do(req)
  213. if err != nil {
  214. logs.Error(err)
  215. // return nil
  216. }
  217. fmt.Println(resp.Body)
  218. defer resp.Body.Close()
  219. body, _ := ioutil.ReadAll(resp.Body)
  220. var respData map[string]interface{}
  221. tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url)
  222. values(?,?,?,?,?,now(),?,now(),?)`, pastureId, data, string(body), "", "", msgtype, url)
  223. err = json.Unmarshal(body, &respData)
  224. if err != nil {
  225. logs.Error(err)
  226. // return nil
  227. }
  228. if _, ok := respData["DATA"]; ok {
  229. if msgtype == 3 {
  230. if _, ok := respData["ZTCO_001"]; !ok {
  231. return respData["DATA"], false
  232. }
  233. return respData["DATA"], true
  234. }
  235. if _, ok := respData["DATA"]; !ok {
  236. return respData["DATA"], false
  237. }
  238. return respData["DATA"], true
  239. } else {
  240. return respData["DATA"], false
  241. }
  242. }
  243. func SyncSapFeed(c *gin.Context) {
  244. appG := app.Gin{C: c}
  245. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  246. fsion := gofasion.NewFasion(string(dataByte))
  247. start := fsion.Get("startTime").ValueStr()
  248. end := fsion.Get("endTime").ValueStr()
  249. mtart := fsion.Get("mtart").ValueStr()
  250. pastureId := fsion.Get("pastureId").ValueStr()
  251. tx := restful.Engine.NewSession()
  252. defer tx.Close()
  253. data := `{
  254. "DEST": {
  255. "DEST_ID": "TMRWATCH",
  256. "BUSS_TP": "MM002"
  257. },
  258. "DATA": {
  259. "BUDAT_B": "%s",
  260. "BUDAT_E": "%s",
  261. "TMTART": {
  262. "MTART": "%s"
  263. },
  264. "TMATKL": []
  265. }
  266. }`
  267. startTime, _ := time.ParseInLocation("2006-01-02", start, time.Local)
  268. endTime, _ := time.ParseInLocation("2006-01-02", end, time.Local)
  269. data = fmt.Sprintf(data, startTime.Format("20060102"), endTime.Format("20060102"), mtart)
  270. // "https://app.modernfarming.cn:7443/sap/Common/MM002/QueryMaterial/"
  271. // http://192.168.61.117/SAPP0/Common/MM002/QueryMaterial
  272. url := "http://192.168.61.117/SAPP0/Common/MM002/QueryMaterial"
  273. respmap, success := postPush(url, data, 2, tx, pastureId)
  274. // var a interface{} = nil
  275. fmt.Println(respmap, success)
  276. if success == false {
  277. appG.Response(http.StatusOK, e.SUCCESS, true)
  278. } else {
  279. for _, item := range respmap.(map[string]interface{})["TMARA"].([]interface{}) {
  280. sapMap := item.(map[string]interface{})
  281. // fmt.Println(item)
  282. _, err := tx.SQL(` replace into feed_sap(MATNR,MTART,MATKL,MAKTX,MEINS,UMREZ,MEINH,UMREN,ZMINC,ZGUIG,LVORM,LAEDA)values(?,?,?,?,?,?,?,?,?,?,?,?)`,
  283. sapMap["MATNR"], sapMap["MTART"], sapMap["MATKL"], sapMap["MAKTX"], sapMap["MEINS"], sapMap["UMREZ"], sapMap["MEINH"],
  284. sapMap["UMREN"], sapMap["ZMINC"], sapMap["ZGUIG"], sapMap["LVORM"], sapMap["LAEDA"]).Execute()
  285. if err != nil {
  286. logs.Error(err)
  287. return
  288. }
  289. }
  290. appG.Response(http.StatusOK, e.SUCCESS, true)
  291. }
  292. // return
  293. }