analysis_other.go 16 KB

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