group_pasture.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. package model
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. "strings"
  9. "time"
  10. operationPb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/operation"
  11. "gitee.com/xuyiping_admin/pkg/logger/zaplog"
  12. "gitee.com/xuyiping_admin/pkg/tool"
  13. "gitee.com/xuyiping_admin/pkg/xerr"
  14. "go.uber.org/zap"
  15. )
  16. const (
  17. InitManagerPassword = "123456"
  18. UrlDataByName = "authdata/GetDataByName"
  19. UrlReportForm = "authdata/GetReportform"
  20. UrlSummary = "authdata/summary"
  21. UrlProcess = "authdata/processAnalysist"
  22. UrlFeedTemplateHistory = "authdata/feedtemplet/history"
  23. UrlBarnHistory = "authdata/feedp/history"
  24. UrlSpillageAllHistory = "authdata/spillageall/history"
  25. )
  26. const (
  27. FeedFormulaDistributeUrl = "pasture/feed_formula/distribute"
  28. FeedFormulaCancelDistributeUrl = "pasture/feed_formula/cancel/distribute"
  29. FeedFormulaIsModifyUrl = "pasture/feed_formula/is_modify"
  30. FeedFormulaAsyncUrl = "pasture/feed_formula/async"
  31. FeedFormulaDetailListAsyncUrl = "pasture/feed_formula/detail_list"
  32. FeedAsyncUrl = "pasture/feed/async"
  33. DashboardAccuracyUrl = "pasture/dashboard/accuracy_data"
  34. DashboardExecTimeUrl = "pasture/dashboard/process_analysis"
  35. DashboardSprinkleFeedTimeUrl = "pasture/dashboard/sprinkle_statistics"
  36. PastureAccountDistributionURl = "pasture/account/distribute"
  37. ForageCategoryDistributionURl = "pasture/forage_category/distribute"
  38. CattleCategoryDistributionURl = "pasture/cattle_category/distribute"
  39. CattleCategoryDeleteURl = "pasture/cattle_category/delete"
  40. ForageCategoryDeleteURl = "pasture/cattle_category/delete"
  41. FeedUsageURl = "pasture/feed/usage"
  42. FeedFormulaVersionUpdateUrl = "pasture/feed_formula/version"
  43. )
  44. var (
  45. UrlChart = map[string]string{
  46. "mr": "authdata/chart/feedEffMR", // 饲喂效率-效率统计 mr 泌乳牛干物质采食量
  47. "sl": "authdata/chart/feedEffSL", // 饲喂效率-效率统计 sl 牛栏剩料率
  48. "hl": "authdata/chart/feedEffHL", // 饲喂效率-效率统计 hl 混料时间统计
  49. "zh": "authdata/chart/feedEffZH", // 饲喂效率-效率统计 zh 转化率
  50. "cbft": "authdata/chart/feedEffCBFT", // 饲喂效率-效率统计 cbft 成本分析
  51. "jh": "authdata/chart/accuracyAllJH", // 准确性分析-汇总统计-计划统计
  52. "ft": "authdata/chart/accuracyAllFT", // 准确性分析-汇总统计-配方准确率
  53. "nq": "authdata/chart/accuracyAllNQ", // 准确性分析-汇总统计-牛群准确率
  54. "cc": "authdata/chart/accuracyAllCC", // 准确性分析-汇总统计-车辆准确率(重量)
  55. "allhl": "authdata/chart/accuracyAllHL", // 准确性分析-汇总统计-混料统计
  56. "qx": "authdata/chart/accuracyAllQX", // 准确性分析-汇总统计-混料计划取消次数
  57. "ls": "authdata/chart/accuracyAllLS", // 准确性分析-汇总统计-栏舍撒料时间统计
  58. }
  59. )
  60. type GroupPasture struct {
  61. Id int64 `json:"id,omitempty"`
  62. Name string `json:"name,omitempty"`
  63. PastureId int64 `json:"pasture_id"`
  64. Account string `json:"account,omitempty"`
  65. Password string `json:"password"`
  66. ManagerUser string `json:"manager_user"`
  67. ManagerPhone string `json:"manager_phone"`
  68. Domain string `json:"domain"`
  69. Extranet string `json:"extranet"`
  70. Intranet string `json:"intranet"`
  71. IsShow operationPb.IsShow_Kind `json:"is_show,omitempty"`
  72. IsDelete operationPb.IsShow_Kind `json:"is_delete,omitempty"`
  73. IsDistribution operationPb.IsShow_Kind `json:"is_distribution"`
  74. Address string `json:"address"`
  75. CreatedAt int64 `json:"created_at,omitempty"`
  76. UpdatedAt int64 `json:"updated_at,omitempty"`
  77. }
  78. func (g *GroupPasture) TableName() string {
  79. return "group_pasture"
  80. }
  81. // GetPastureId 获取牧场id
  82. func (g *GroupPasture) GetPastureId() int64 {
  83. if g.PastureId > 0 {
  84. return g.PastureId
  85. }
  86. return g.Id
  87. }
  88. type PastureTokenRequest struct {
  89. UserName string `json:"username"`
  90. Password string `json:"password"`
  91. }
  92. type PastureTokenResponse struct {
  93. Code int32 `json:"code"`
  94. Msg string `json:"msg"`
  95. Data *PastureTokenData `json:"data"`
  96. }
  97. type PastureTokenData struct {
  98. Token string `json:"token"`
  99. }
  100. func NewGroupPasture(req *operationPb.AddPastureRequest) *GroupPasture {
  101. groupPasture := &GroupPasture{
  102. Name: req.Name,
  103. PastureId: int64(req.PastureId),
  104. Account: req.Account,
  105. Password: tool.Md5String(InitManagerPassword),
  106. ManagerUser: req.ManagerUser,
  107. ManagerPhone: req.ManagerPhone,
  108. IsShow: operationPb.IsShow_OK,
  109. IsDelete: operationPb.IsShow_OK,
  110. Address: req.Address,
  111. Domain: req.Domain,
  112. IsDistribution: operationPb.IsShow_NO,
  113. }
  114. return groupPasture
  115. }
  116. type PastureClient struct {
  117. Token string `json:"token"`
  118. Detail *GroupPasture `json:"detail"`
  119. authClient *http.Client
  120. }
  121. func NewPastureClient(g *GroupPasture) *PastureClient {
  122. return &PastureClient{
  123. Detail: g,
  124. authClient: &http.Client{
  125. Timeout: time.Duration(5) * time.Second,
  126. },
  127. }
  128. }
  129. func (p *PastureClient) doRequest(req *http.Request) ([]byte, error) {
  130. resp, err := p.authClient.Do(req)
  131. if err != nil {
  132. zaplog.Error("PastureClient", zap.Any("authClient.Do", err))
  133. return nil, xerr.WithStack(err)
  134. }
  135. defer resp.Body.Close()
  136. b, err := ioutil.ReadAll(resp.Body)
  137. if err != nil {
  138. zaplog.Error("PastureClient", zap.Any("ioutil.ReadAll", err))
  139. return nil, xerr.WithStack(err)
  140. }
  141. if resp.StatusCode != http.StatusOK {
  142. if len(b) > 0 {
  143. return nil, xerr.Customf("err:%v,body:%s", err, string(b))
  144. } else {
  145. return nil, xerr.Customf("err:%v", err)
  146. }
  147. }
  148. return b, nil
  149. }
  150. func (p *PastureClient) DoGet(url string) ([]byte, error) {
  151. // 获取token
  152. if err := p.GetToken(); err != nil {
  153. zaplog.Error("PastureClient", zap.Any("DoGet GetToken Err", err), zap.Any("detail", p.Detail))
  154. return nil, xerr.WithStack(err)
  155. }
  156. req, err := http.NewRequest(http.MethodGet, url, nil)
  157. if err != nil {
  158. zaplog.Error("PastureClient", zap.Any("DoGet", err))
  159. return nil, err
  160. }
  161. req.Header.Add("Accept", "application/json")
  162. req.Header.Add("token", p.Token)
  163. req.Header.Add("Content-Type", "application/json")
  164. req.Header.Add("pasture_id", fmt.Sprintf("%d", p.Detail.PastureId))
  165. return p.doRequest(req)
  166. }
  167. func (p *PastureClient) DoPost(url string, body interface{}) ([]byte, error) {
  168. b, err := json.Marshal(body)
  169. if err != nil {
  170. zaplog.Error("PastureClient", zap.Any("DoPost-Marshal", err))
  171. return nil, xerr.WithStack(err)
  172. }
  173. // 获取token
  174. if !strings.Contains(url, PastureAccountDistributionURl) {
  175. if err = p.GetToken(); err != nil {
  176. zaplog.Error("PastureClient", zap.Any("DoPost GetToken Err", err), zap.Any("detail", p.Detail))
  177. return nil, xerr.WithStack(err)
  178. }
  179. }
  180. req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(b))
  181. if err != nil {
  182. zaplog.Error("PastureClient", zap.Any("NewRequest", err))
  183. return nil, xerr.WithStack(err)
  184. }
  185. req.Header.Add("Accept", "application/json")
  186. req.Header.Add("token", p.Token)
  187. req.Header.Add("Content-Type", "application/json")
  188. req.Header.Add("pasture_id", fmt.Sprintf("%d", p.Detail.PastureId))
  189. return p.doRequest(req)
  190. }
  191. func (p *PastureClient) GetToken() error {
  192. url := fmt.Sprintf("%s/%s", p.Detail.Domain, "auth")
  193. body := &PastureTokenRequest{
  194. UserName: p.Detail.Account,
  195. Password: p.Detail.Password,
  196. }
  197. b, err := json.Marshal(body)
  198. if err != nil {
  199. return xerr.WithStack(err)
  200. }
  201. req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(b))
  202. if err != nil {
  203. zaplog.Error("PastureClient", zap.Any("GetToken", err))
  204. return xerr.WithStack(err)
  205. }
  206. req.Header.Add("Accept", "application/json")
  207. req.Header.Add("Content-Type", "application/json")
  208. result, err := p.doRequest(req)
  209. if err != nil {
  210. zaplog.Error("PastureClient", zap.Any("GetToken-doRequest", err))
  211. return xerr.WithStack(err)
  212. }
  213. response := &PastureTokenResponse{}
  214. if err = json.Unmarshal(result, response); err != nil {
  215. zaplog.Error("PastureClient", zap.String("GetToken", string(result)))
  216. return xerr.WithStack(err)
  217. }
  218. if response.Code != http.StatusOK || response.Data == nil || response.Data.Token == "" {
  219. zaplog.Error("PastureClient", zap.Any("response", response))
  220. return xerr.Customf("获取牧场端token失败 Err:%s", err)
  221. }
  222. p.Token = response.Data.Token
  223. return nil
  224. }
  225. type GroupPastureSlice []*GroupPasture
  226. func (g GroupPastureSlice) ToPB() []*operationPb.AddPastureRequest {
  227. res := make([]*operationPb.AddPastureRequest, len(g))
  228. for i, v := range g {
  229. res[i] = &operationPb.AddPastureRequest{
  230. Id: int32(v.Id),
  231. Name: v.Name,
  232. Account: v.Account,
  233. ManagerUser: v.ManagerUser,
  234. ManagerPhone: v.ManagerPhone,
  235. Address: v.Address,
  236. Domain: v.Domain,
  237. IsShow: v.IsShow,
  238. CreatedAt: int32(v.CreatedAt),
  239. CreatedAtFormat: time.Unix(v.CreatedAt, 0).Format(LayoutTime),
  240. PastureId: int32(v.PastureId),
  241. }
  242. }
  243. return res
  244. }
  245. func (g *GroupPasture) ToPb() *operationPb.AddPastureRequest {
  246. return &operationPb.AddPastureRequest{
  247. Id: int32(g.Id),
  248. Name: g.Name,
  249. ManagerUser: g.ManagerUser,
  250. ManagerPhone: g.ManagerPhone,
  251. Address: g.Address,
  252. IsShow: g.IsShow,
  253. CreatedAt: int32(g.CreatedAt),
  254. }
  255. }