analysis_other.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. package backend
  2. import (
  3. "context"
  4. "fmt"
  5. "kpt-pasture/model"
  6. "kpt-pasture/util"
  7. "net/http"
  8. "gorm.io/gorm"
  9. pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
  10. "gitee.com/xuyiping_admin/pkg/xerr"
  11. )
  12. // PregnancyReport 孕检报告
  13. func (s *StoreEntry) PregnancyReport(ctx context.Context, req *pasturePb.PregnancyReportRequest, pagination *pasturePb.PaginationModel) (*pasturePb.PregnancyReportResponse, error) {
  14. startDayUnix := util.TimeParseLocalUnix(req.StartDayTime)
  15. endDayUnix := util.TimeParseLocalEndUnix(req.EndDayTime)
  16. if startDayUnix > endDayUnix || startDayUnix == 0 || endDayUnix == 0 {
  17. return nil, xerr.Custom("开始时间不能大于结束时间")
  18. }
  19. eventPregnantCheckList := make([]*model.EventPregnantCheck, 0)
  20. pref := s.DB.Model(new(model.EventPregnantCheck)).Where("status = ?", pasturePb.IsShow_Ok).Where("cow_type = ?", req.CowType)
  21. if startDayUnix > 0 && endDayUnix > 0 && endDayUnix >= startDayUnix {
  22. pref = pref.Where("create_time BETWEEN ? AND ?", startDayUnix, endDayUnix)
  23. }
  24. if req.PregnantCheckResult > 0 {
  25. pref = pref.Where("pregnant_check_result = ?", req.PregnantCheckResult)
  26. }
  27. var count int64 = 0
  28. if err := pref.Count(&count).
  29. Limit(int(pagination.PageSize)).
  30. Offset(int(pagination.PageOffset)).
  31. Order("id desc").
  32. Find(&eventPregnantCheckList).Error; err != nil {
  33. return nil, xerr.WithStack(err)
  34. }
  35. pregnantCheckResultMap := s.PregnantCheckResultMap()
  36. pregnantCheckMethodMap := s.PregnantCheckMethodMap()
  37. return &pasturePb.PregnancyReportResponse{
  38. Code: http.StatusOK,
  39. Msg: "ok",
  40. Data: &pasturePb.PregnancyReportData{
  41. List: model.EventPregnantCheckSlice(eventPregnantCheckList).ToPB3(pregnantCheckResultMap, pregnantCheckMethodMap),
  42. Total: int32(count),
  43. PageSize: pagination.PageSize,
  44. Page: pagination.Page,
  45. },
  46. }, nil
  47. }
  48. // CalvingReport 产犊报告
  49. func (s *StoreEntry) CalvingReport(ctx context.Context, req *pasturePb.CalvingReportRequest) (*pasturePb.CalvingReportResponse, error) {
  50. lastDayOfMonth, err := util.GetLastDayOfMonth(req.EndDayTime)
  51. if err != nil {
  52. return nil, xerr.WithStack(err)
  53. }
  54. endDayTimeUnix := util.TimeParseLocalEndUnix(lastDayOfMonth)
  55. startDayTimeUnix := util.TimeParseLocalUnix(fmt.Sprintf("%s-01", req.StartDayTime))
  56. if startDayTimeUnix == 0 || endDayTimeUnix == 0 || endDayTimeUnix <= startDayTimeUnix {
  57. return nil, xerr.Custom("开始时间不能大于结束时间")
  58. }
  59. eventCalving1 := make([]*pasturePb.CalvingReportTable, 0)
  60. pref1 := s.DB.Model(new(model.EventCalving)).
  61. Select(fmt.Sprint(`DATE_FORMAT(FROM_UNIXTIME(reality_day), '%Y-%m') AS statistic_method,cow_kind,`)+fmt.Sprintf(
  62. `SUM(child_number) AS totalCount,
  63. SUM(CASE WHEN child_number > 1 THEN child_number ELSE 0 END) AS twins,
  64. SUM(CASE WHEN pregnancy_age <= %d THEN 1 ELSE 0 END) AS premature_labor_count,
  65. SUM(CASE WHEN pregnancy_age >= %d THEN 1 ELSE 0 END) AS late_labor_count,
  66. count(*) as total_count`, req.PrematureLabor, req.LateLabor),
  67. ).Where("status = ?", pasturePb.IsShow_Ok).
  68. Where("reality_day BETWEEN ? AND ? ", startDayTimeUnix, endDayTimeUnix)
  69. if req.AnalysisMethod > 0 {
  70. switch req.AnalysisMethod {
  71. case pasturePb.CalvingAnalysisMethod_Months:
  72. pref1.Group("statistic_method").Order("statistic_method")
  73. case pasturePb.CalvingAnalysisMethod_CowKind:
  74. pref1.Group("cow_kind").Order("cow_kind")
  75. }
  76. }
  77. if err = pref1.Find(&eventCalving1).Error; err != nil {
  78. return nil, xerr.WithStack(err)
  79. }
  80. eventCalving2 := make([]*pasturePb.CalvingReportTable, 0)
  81. pref2 := s.DB.Model(new(model.CalvingCalf)).
  82. Select(fmt.Sprint(`DATE_FORMAT(FROM_UNIXTIME(birth_at), '%Y-%m') AS statistic_method, cow_kind,
  83. SUM(CASE WHEN sex = 1 THEN 1 ELSE 0 END) AS bulls,
  84. SUM(CASE WHEN sex = 2 THEN 1 ELSE 0 END) AS cows,
  85. SUM(CASE WHEN is_live = 1 THEN 1 ELSE 0 END) AS survive_count,
  86. SUM(CASE WHEN is_live = 2 THEN 1 ELSE 0 END) AS die_count,
  87. SUM(CASE WHEN is_live = 2 AND sex = 1 THEN 1 ELSE 0 END) AS bulls_die_count,
  88. SUM(CASE WHEN is_live = 2 AND sex = 2 THEN 1 ELSE 0 END) AS cows_die_count,
  89. SUM(CASE WHEN is_adoption = 1 THEN 1 ELSE 0 END) AS adopt_count`)).
  90. Where("birth_at BETWEEN ? AND ?", startDayTimeUnix, endDayTimeUnix)
  91. if req.AnalysisMethod > 0 {
  92. switch req.AnalysisMethod {
  93. case pasturePb.CalvingAnalysisMethod_Months:
  94. pref2.Group("statistic_method").Order("statistic_method")
  95. case pasturePb.CalvingAnalysisMethod_CowKind:
  96. pref2.Group("cow_kind").Order("cow_kind")
  97. }
  98. }
  99. if err = pref2.Find(&eventCalving2).Error; err != nil {
  100. return nil, xerr.WithStack(err)
  101. }
  102. // 合并数据集
  103. for _, v1 := range eventCalving1 {
  104. for _, v2 := range eventCalving2 {
  105. if v1.StatisticMethod != v2.StatisticMethod && v1.CowKind != v2.CowKind {
  106. continue
  107. }
  108. v1.Bulls = v2.Bulls
  109. v1.Cows = v2.Cows
  110. v1.SurviveCount = v2.SurviveCount
  111. v1.DieCount = v2.DieCount
  112. v1.BullsDieCount = v2.BullsDieCount
  113. v1.CowsDieCount = v2.CowsDieCount
  114. v1.AdoptCount = v2.AdoptCount
  115. }
  116. }
  117. cowKindMap := s.CowKindMap()
  118. for _, v := range eventCalving1 {
  119. if req.AnalysisMethod == pasturePb.CalvingAnalysisMethod_CowKind {
  120. v.StatisticMethod = cowKindMap[v.CowKind]
  121. }
  122. if v.TotalCount > 0 {
  123. v.TwinsRate = float32(util.RoundToTwoDecimals(float64(v.Twins) / float64(v.TotalCount) * 100))
  124. v.CowsRate = float32(util.RoundToTwoDecimals(float64(v.Cows) / float64(v.TotalCount) * 100))
  125. v.DieRate = float32(util.RoundToTwoDecimals(float64(v.DieCount) / float64(v.TotalCount) * 100))
  126. v.BullsRate = float32(util.RoundToTwoDecimals(float64(v.Bulls) / float64(v.TotalCount) * 100))
  127. v.SurviveRate = float32(util.RoundToTwoDecimals(float64(v.SurviveCount) / float64(v.TotalCount) * 100))
  128. }
  129. if v.Bulls > 0 {
  130. v.BullsDieRate = float32(util.RoundToTwoDecimals(float64(v.BullsDieCount) / float64(v.Bulls) * 100))
  131. }
  132. if v.Cows > 0 {
  133. v.CowsDieRate = float32(util.RoundToTwoDecimals(float64(v.CowsDieCount) / float64(v.Cows) * 100))
  134. }
  135. v.NormalLaborCount = v.TotalCount - (v.PrematureLaborCount + v.LateLaborCount)
  136. if v.NormalLaborCount <= 0 {
  137. v.NormalLaborCount = 0
  138. }
  139. }
  140. return &pasturePb.CalvingReportResponse{
  141. Code: http.StatusOK,
  142. Msg: "ok",
  143. Data: &pasturePb.CalvingReportData{
  144. List: eventCalving1,
  145. Total: int32(len(eventCalving1)),
  146. },
  147. }, nil
  148. }
  149. // DiseaseCureReport 疾病治愈率报告
  150. func (s *StoreEntry) DiseaseCureReport(ctx context.Context, req *pasturePb.DiseaseCureRateRequest) (*pasturePb.DiseaseCureRateResponse, error) {
  151. lastDayOfMonth, err := util.GetLastDayOfMonth(req.EndDayTime)
  152. if err != nil {
  153. return nil, xerr.WithStack(err)
  154. }
  155. endDayTimeUnix := util.TimeParseLocalEndUnix(lastDayOfMonth)
  156. startDayTimeUnix := util.TimeParseLocalUnix(fmt.Sprintf("%s-01", req.StartDayTime))
  157. if startDayTimeUnix == 0 || endDayTimeUnix == 0 || endDayTimeUnix <= startDayTimeUnix {
  158. return nil, xerr.Custom("开始时间不能大于结束时间")
  159. }
  160. diseaseCureRateList1 := make([]*pasturePb.DiseaseCureRateList, 0)
  161. diseaseCureRateList2 := make([]*pasturePb.DiseaseCureRateList, 0)
  162. pref1, err := s.query1(ctx, req.CowType, startDayTimeUnix, endDayTimeUnix)
  163. if err != nil {
  164. return nil, xerr.WithStack(err)
  165. }
  166. pref2, err := s.query2(ctx, startDayTimeUnix, endDayTimeUnix)
  167. if err != nil {
  168. return nil, xerr.WithStack(err)
  169. }
  170. switch req.AnalysisMethod {
  171. case pasturePb.DiseaseAnalysisMethod_Months:
  172. pref1.Where("diagnosed_at > 0").Group("months").Order("months")
  173. pref2.Where("treatment_at > 0").Group("months").Order("months")
  174. case pasturePb.DiseaseAnalysisMethod_Disease_Category:
  175. pref1.Where("disease_type > 0").Group("disease_type").Order("disease_type")
  176. pref2.Where("disease_type > 0").Group("disease_type").Order("disease_type")
  177. case pasturePb.DiseaseAnalysisMethod_Disease:
  178. pref1.Where("diagnose_id > 0").Group("diagnose_id").Order("diagnose_id")
  179. pref2.Where("disease_id > 0").Group("disease_id").Order("disease_id")
  180. case pasturePb.DiseaseAnalysisMethod_Operator:
  181. pref1.Where("diagnose_operation_id > 0").Group("diagnose_operation_id").Order("diagnose_operation_id")
  182. pref2.Where("operation_id > 0").Group("operation_id").Order("operation_id")
  183. default:
  184. return nil, xerr.Custom("错误的统计方式")
  185. }
  186. if err = pref1.Find(&diseaseCureRateList1).Error; err != nil {
  187. return nil, xerr.WithStack(err)
  188. }
  189. if err = pref2.Find(&diseaseCureRateList2).Error; err != nil {
  190. return nil, xerr.WithStack(err)
  191. }
  192. // 处理数据
  193. processDiseaseCureRateList(diseaseCureRateList1, diseaseCureRateList2, req.AnalysisMethod)
  194. chart := &pasturePb.DiseaseCureRateChart{
  195. Headers: make([]string, 0),
  196. DiseaseCureCount: make([]int32, 0),
  197. DiseaseCureRate: make([]float32, 0),
  198. DiseaseCount: make([]int32, 0),
  199. }
  200. for _, v := range diseaseCureRateList1 {
  201. switch req.AnalysisMethod {
  202. case pasturePb.DiseaseAnalysisMethod_Months:
  203. v.StatisticMethod = v.Months
  204. case pasturePb.DiseaseAnalysisMethod_Disease_Category:
  205. diseaseTypeMap := s.DiseaseTypeMap()
  206. v.StatisticMethod = diseaseTypeMap[v.DiseaseType]
  207. case pasturePb.DiseaseAnalysisMethod_Disease:
  208. v.StatisticMethod = v.DiseaseName
  209. case pasturePb.DiseaseAnalysisMethod_Operator:
  210. v.StatisticMethod = v.OperationName
  211. case pasturePb.DiseaseAnalysisMethod_Prescription:
  212. v.StatisticMethod = v.PrescriptionName
  213. }
  214. chart.Headers = append(chart.Headers, v.StatisticMethod)
  215. chart.DiseaseCureCount = append(chart.DiseaseCureCount, v.DiseaseTreatmentCount)
  216. diseaseCureRate := float32(0)
  217. if v.DiseaseTreatmentCount > 0 {
  218. diseaseCureRate = float32(util.RoundToTwoDecimals(float64(v.DiseaseCureCount) / float64(v.DiseaseCount) * 100))
  219. }
  220. chart.DiseaseCureRate = append(chart.DiseaseCureRate, diseaseCureRate)
  221. chart.DiseaseCount = append(chart.DiseaseCount, v.DiseaseCount)
  222. }
  223. return &pasturePb.DiseaseCureRateResponse{
  224. Code: http.StatusOK,
  225. Msg: "ok",
  226. Data: &pasturePb.DiseaseCureRateData{
  227. List: diseaseCureRateList1,
  228. Chart: chart,
  229. },
  230. }, nil
  231. }
  232. func (s *StoreEntry) query1(ctx context.Context, cowType pasturePb.CowType_Kind, startDayTimeUnix, endDayTimeUnix int64) (*gorm.DB, error) {
  233. pref := s.DB.Model(new(model.EventCowDisease)).
  234. Select(
  235. `DATE_FORMAT(FROM_UNIXTIME(diagnosed_at), '%Y-%m') AS months,
  236. diagnose_id as disease_id,
  237. diagnose_name as disease_name,
  238. diagnose_operation_id as operation_id,
  239. diagnose_operation_name as operation_name,
  240. disease_type,
  241. COUNT(DISTINCT CASE WHEN health_status = ? THEN cow_id END) AS disease_treatment_count, -- 治疗头数
  242. COUNT(DISTINCT CASE WHEN health_status = ? AND curable_at > 0 THEN cow_id END) AS disease_cure_count, -- 治愈头数
  243. COUNT(DISTINCT CASE WHEN diagnosed_result = ? THEN cow_id END) AS disease_count, -- 发病数
  244. COUNT(DISTINCT CASE WHEN health_status IN (?, ?) THEN cow_id END) AS die_out_count, -- 死淘数
  245. COUNT(DISTINCT CASE
  246. WHEN health_status = ?
  247. AND TIMESTAMPDIFF(DAY, FROM_UNIXTIME(disease_at), FROM_UNIXTIME(curable_at)) <= 7
  248. THEN cow_id
  249. END) AS seven_cure_count, -- 7天内治愈头数
  250. COUNT(DISTINCT CASE
  251. WHEN health_status = ?
  252. AND TIMESTAMPDIFF(DAY, FROM_UNIXTIME(disease_at), FROM_UNIXTIME(curable_at)) <= 14
  253. THEN cow_id
  254. END) AS seventeen_cure_count, -- 14天内治愈头数
  255. COUNT(DISTINCT CASE
  256. WHEN health_status = ?
  257. AND TIMESTAMPDIFF(DAY, FROM_UNIXTIME(disease_at), FROM_UNIXTIME(curable_at)) <= 30
  258. THEN cow_id
  259. END) AS thirty_cure_count -- 30天内治愈头数
  260. `,
  261. pasturePb.HealthStatus_Treatment, pasturePb.HealthStatus_Curable, pasturePb.IsShow_Ok, pasturePb.HealthStatus_Out,
  262. pasturePb.HealthStatus_Dead, pasturePb.HealthStatus_Curable, pasturePb.HealthStatus_Curable, pasturePb.HealthStatus_Curable,
  263. ).
  264. Where("diagnosed_result = ?", pasturePb.IsShow_Ok).
  265. Where("diagnosed_at BETWEEN ? AND ?", startDayTimeUnix, endDayTimeUnix)
  266. if cowType > 0 {
  267. pref.Where("cow_type = ?", cowType)
  268. }
  269. return pref, nil
  270. }
  271. func (s *StoreEntry) query2(ctx context.Context, startDayTimeUnix, endDayTimeUnix int64) (*gorm.DB, error) {
  272. pref := s.DB.Model(new(model.EventCowTreatment)).
  273. Select(`
  274. DATE_FORMAT(FROM_UNIXTIME(treatment_at), '%Y-%m') AS months,
  275. disease_id,
  276. disease_name,
  277. disease_type,
  278. prescription_id,
  279. prescription_name,
  280. operation_id,
  281. operation_name,
  282. COUNT(DISTINCT cow_id) AS disease_treatment_count`,
  283. ).Where("treatment_at BETWEEN ? AND ?", startDayTimeUnix, endDayTimeUnix)
  284. return pref, nil
  285. }
  286. // 构建哈希表
  287. func buildMap(list []*pasturePb.DiseaseCureRateList, method pasturePb.DiseaseAnalysisMethod_Kind) map[interface{}]*pasturePb.DiseaseCureRateList {
  288. m := make(map[interface{}]*pasturePb.DiseaseCureRateList)
  289. for _, v := range list {
  290. var key interface{}
  291. switch method {
  292. case pasturePb.DiseaseAnalysisMethod_Months:
  293. key = v.Months
  294. case pasturePb.DiseaseAnalysisMethod_Disease_Category:
  295. key = v.DiseaseType
  296. case pasturePb.DiseaseAnalysisMethod_Disease:
  297. key = v.DiseaseId
  298. case pasturePb.DiseaseAnalysisMethod_Operator:
  299. key = v.OperationId
  300. case pasturePb.DiseaseAnalysisMethod_Prescription:
  301. key = v.PrescriptionId
  302. }
  303. m[key] = v
  304. }
  305. return m
  306. }
  307. // 更新 DiseaseTreatmentCount
  308. func updateDiseaseTreatmentCount(v1 *pasturePb.DiseaseCureRateList, v2 *pasturePb.DiseaseCureRateList) {
  309. v1.DiseaseTreatmentCount = v2.DiseaseTreatmentCount
  310. }
  311. // 主逻辑
  312. func processDiseaseCureRateList(diseaseCureRateList1, diseaseCureRateList2 []*pasturePb.DiseaseCureRateList, analysisMethod pasturePb.DiseaseAnalysisMethod_Kind) {
  313. if len(diseaseCureRateList1) == 0 || len(diseaseCureRateList2) == 0 {
  314. return
  315. }
  316. map2 := buildMap(diseaseCureRateList2, analysisMethod)
  317. for i := range diseaseCureRateList1 {
  318. v1 := diseaseCureRateList1[i]
  319. var key interface{}
  320. switch analysisMethod {
  321. case pasturePb.DiseaseAnalysisMethod_Months:
  322. key = v1.Months
  323. case pasturePb.DiseaseAnalysisMethod_Disease_Category:
  324. key = v1.DiseaseType
  325. case pasturePb.DiseaseAnalysisMethod_Disease:
  326. key = v1.DiseaseId
  327. case pasturePb.DiseaseAnalysisMethod_Operator:
  328. key = v1.OperationId
  329. case pasturePb.DiseaseAnalysisMethod_Prescription:
  330. key = v1.PrescriptionId
  331. default:
  332. continue // 处理无效的 AnalysisMethod
  333. }
  334. if v2, ok := map2[key]; ok {
  335. updateDiseaseTreatmentCount(v1, v2)
  336. }
  337. }
  338. }
  339. func (s *StoreEntry) SaleCowReport(ctx context.Context, req *pasturePb.SaleCowReportRequest) (*pasturePb.SaleCowReportResponse, error) {
  340. lastDayOfMonth, err := util.GetLastDayOfMonth(req.EndDay)
  341. if err != nil {
  342. return nil, xerr.WithStack(err)
  343. }
  344. endDayTimeUnix := util.TimeParseLocalEndUnix(lastDayOfMonth)
  345. startDayTimeUnix := util.TimeParseLocalUnix(fmt.Sprintf("%s-01", req.StartDay))
  346. if startDayTimeUnix == 0 || endDayTimeUnix == 0 || endDayTimeUnix <= startDayTimeUnix {
  347. return nil, xerr.Custom("开始时间不能大于结束时间")
  348. }
  349. list := make([]*pasturePb.SaleCowReportList, 0)
  350. pref := s.DB.Model(new(model.EventSale)).
  351. Select(
  352. `SUM(sale_cow_count) AS sale_all_count,
  353. SUM(sale_all_amount) AS sale_all_amount,
  354. SUM(sale_cow_count) AS sale_all_count,
  355. SUM(sale_all_weight) AS sale_all_weight`,
  356. ).Where("sale_at BETWEEN ? AND ?", startDayTimeUnix, endDayTimeUnix)
  357. if req.AnalysisMethod == pasturePb.SaleCowAnalysisMethod_Months {
  358. pref.Select(`DATE_FORMAT(FROM_UNIXTIME(sale_at), '%Y-%m') AS statisticMethod`)
  359. }
  360. if req.AnalysisMethod == pasturePb.SaleCowAnalysisMethod_Dealer {
  361. pref.Select(`dealer_name as statisticMethod`)
  362. }
  363. if err = pref.Group("statisticMethod").Order("statisticMethod ASC").Find(&list).Error; err != nil {
  364. return nil, xerr.WithStack(err)
  365. }
  366. chart := &pasturePb.SaleCowReportChart{
  367. Headers: make([]string, 0),
  368. SaleMount: make([]float32, 0),
  369. SaleWeight: make([]float32, 0),
  370. SaleCount: make([]int32, 0),
  371. AverageSaleWeight: make([]float32, 0),
  372. }
  373. for i, v := range list {
  374. if v.SaleAllCount > 0 && v.SaleAllWeight > 0 {
  375. v.SaleAvgWeight = float32(util.RoundToTwoDecimals(float64(v.SaleAllWeight / float32(v.SaleAllCount))))
  376. }
  377. chart.Headers = append(chart.Headers, v.StatisticMethod)
  378. chart.SaleMount = append(chart.SaleMount, v.SaleAllMount)
  379. chart.SaleWeight = append(chart.SaleWeight, v.SaleAllWeight)
  380. chart.SaleCount = append(chart.SaleCount, v.SaleAllCount)
  381. chart.AverageSaleWeight = append(chart.AverageSaleWeight, v.SaleAvgWeight)
  382. v.Id = int32(i)
  383. }
  384. return &pasturePb.SaleCowReportResponse{
  385. Code: http.StatusOK,
  386. Msg: "ok",
  387. Data: &pasturePb.SaleCowReportData{
  388. Chart: chart,
  389. List: list,
  390. Total: int32(len(list)),
  391. },
  392. }, err
  393. }