group_pasture.go 9.4 KB

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