calendar.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. package backend
  2. import (
  3. "context"
  4. "fmt"
  5. "kpt-pasture/model"
  6. "kpt-pasture/util"
  7. "net/http"
  8. "regexp"
  9. "strconv"
  10. "time"
  11. pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
  12. "gitee.com/xuyiping_admin/pkg/xerr"
  13. )
  14. // CalendarToDoList 获取日历待办列表
  15. func (s *StoreEntry) CalendarToDoList(ctx context.Context, req *pasturePb.CalendarToDoRequest, pagination *pasturePb.PaginationModel) (*pasturePb.CalendarToDoResponse, error) {
  16. userModel, err := s.GetUserModel(ctx)
  17. if err != nil {
  18. return nil, xerr.WithStack(err)
  19. }
  20. whereSql := fmt.Sprintf(" AND pasture_id = %d AND end_day <= %d ", userModel.AppPasture.Id, util.TimeParseLocalEndUnix(time.Now().Format(model.LayoutDate2)))
  21. calendarToDoList := make([]*pasturePb.CalendarToDoList, 0)
  22. sql := `SELECT a.cow_id,b.pen_name,a.calendar_type_name,DATE_FORMAT(FROM_UNIXTIME(a.plan_day), '%Y-%m-%d') AS plan_day,a.remaining_days,b.lact,b.ear_number FROM (
  23. SELECT cow_id,plan_day,'免疫' as calendar_type_name,TIMESTAMPDIFF(DAY, NOW(), FROM_UNIXTIME(end_day)) AS remaining_days FROM event_immunization_plan WHERE status = 2` + whereSql + `
  24. UNION ALL
  25. SELECT cow_id,plan_day,'同期' as calendar_type_name,TIMESTAMPDIFF(DAY, NOW(), FROM_UNIXTIME(end_day)) AS remaining_days FROM event_cow_same_time WHERE status = 2` + whereSql + `
  26. UNION ALL
  27. SELECT cow_id,plan_day,'孕检' as calendar_type_name,TIMESTAMPDIFF(DAY, NOW(), FROM_UNIXTIME(end_day)) AS remaining_days FROM event_pregnant_check WHERE status = 2` + whereSql + `
  28. UNION ALL
  29. SELECT cow_id,plan_day,'断奶' as calendar_type_name,TIMESTAMPDIFF(DAY, NOW(), FROM_UNIXTIME(end_day)) AS remaining_days FROM event_weaning WHERE status = 2` + whereSql + `
  30. UNION ALL
  31. SELECT cow_id,plan_day,'配种' as calendar_type_name,TIMESTAMPDIFF(DAY, NOW(), FROM_UNIXTIME(end_day)) AS remaining_days FROM event_mating WHERE status = 2` + whereSql + `
  32. UNION ALL
  33. SELECT cow_id,plan_day,'产犊' as calendar_type_name,TIMESTAMPDIFF(DAY, NOW(), FROM_UNIXTIME(end_day)) AS remaining_days FROM event_calving WHERE status = 2` + whereSql + `
  34. UNION ALL
  35. SELECT cow_id,disease_at as plan_day,'疾病' as calendar_type_name,0 AS remaining_days FROM event_cow_disease WHERE diagnosed_result IN (2,3) AND pasture_id = ` + fmt.Sprintf("%d", userModel.AppPasture.Id) + `
  36. ) as a JOIN cow b ON a.cow_id = b.id WHERE 1 = 1 `
  37. completeSql := fmt.Sprintf("%s ORDER BY a.plan_day DESC", sql)
  38. if err = s.DB.Raw(completeSql).Find(&calendarToDoList).Error; err != nil {
  39. return nil, err
  40. }
  41. nowTime := time.Now().Format(model.LayoutDate2)
  42. todayCompletedSql := `SELECT a.count as count,a.calendar_type_name as calendar_type_name FROM (
  43. SELECT count('cow_id') as count,'免疫' as calendar_type_name FROM event_immunization_plan WHERE status = 1 AND DATE_FORMAT(FROM_UNIXTIME(reality_day), '%Y-%m-%d') = ?
  44. UNION ALL
  45. SELECT count('cow_id') as count,'同期' as calendar_type_name FROM event_cow_same_time WHERE status = 1 AND DATE_FORMAT(FROM_UNIXTIME(reality_day), '%Y-%m-%d') = ?
  46. UNION ALL
  47. SELECT count('cow_id') as count,'孕检' as calendar_type_name FROM event_pregnant_check WHERE status = 1 AND DATE_FORMAT(FROM_UNIXTIME(reality_day), '%Y-%m-%d') = ?
  48. UNION ALL
  49. SELECT count('cow_id') as count,'断奶' as calendar_type_name FROM event_weaning WHERE status = 1 AND DATE_FORMAT(FROM_UNIXTIME(reality_day), '%Y-%m-%d') = ?
  50. UNION ALL
  51. SELECT count('cow_id') as count,'配种' as calendar_type_name FROM event_mating WHERE status = 1 AND DATE_FORMAT(FROM_UNIXTIME(reality_day), '%Y-%m-%d') = ?
  52. UNION ALL
  53. SELECT count('cow_id') as count,'产犊' as calendar_type_name FROM event_calving WHERE status = 1 AND DATE_FORMAT(FROM_UNIXTIME(reality_day), '%Y-%m-%d') = ?
  54. UNION ALL
  55. SELECT count('cow_id') as count,'疾病' as calendar_type_name FROM event_cow_disease WHERE diagnosed_result = 4 AND DATE_FORMAT(FROM_UNIXTIME(curable_at), '%Y-%m-%d') = ?
  56. ) as a `
  57. toDayCompletedList := make([]*model.TodayCompletedData, 0)
  58. if err = s.DB.Raw(todayCompletedSql, nowTime, nowTime, nowTime, nowTime, nowTime, nowTime, nowTime).Find(&toDayCompletedList).Error; err != nil {
  59. return nil, xerr.WithStack(err)
  60. }
  61. toDayCompletedCountMap := make(map[string]int32)
  62. for _, v := range toDayCompletedList {
  63. toDayCompletedCountMap[v.CalendarTypeName] = v.Count
  64. }
  65. list, total := Paginate(calendarToDoList, req, pagination)
  66. return &pasturePb.CalendarToDoResponse{
  67. Code: http.StatusOK,
  68. Msg: "ok",
  69. Data: &pasturePb.CalendarToDoData{
  70. List: list,
  71. Progress: ProgressList(calendarToDoList, toDayCompletedCountMap),
  72. Total: total,
  73. PageSize: pagination.PageSize,
  74. Page: pagination.Page,
  75. },
  76. }, nil
  77. }
  78. func (s *StoreEntry) CalendarList(ctx context.Context, req *pasturePb.CalendarRequest) (*pasturePb.CalendarResponse, error) {
  79. userModel, err := s.GetUserModel(ctx)
  80. if err != nil {
  81. return nil, xerr.WithStack(err)
  82. }
  83. calendarList := make([]*model.Calendar, 0)
  84. if err = s.DB.Model(new(model.Calendar)).
  85. Where("start_day BETWEEN ? AND ?", req.ShowStartDay, req.ShowEndDay).
  86. Where("pasture_id = ?", userModel.AppPasture.Id).
  87. Where("is_show = ?", pasturePb.IsShow_Ok).
  88. Find(&calendarList).Error; err != nil {
  89. return nil, xerr.WithStack(err)
  90. }
  91. return &pasturePb.CalendarResponse{
  92. Code: http.StatusOK,
  93. Msg: "ok",
  94. Data: model.CalendarSlice(calendarList).ToPB(),
  95. }, nil
  96. }
  97. func (s *StoreEntry) CalendarTableDetail(ctx context.Context, req *pasturePb.CalendarTableRequest, pagination *pasturePb.PaginationModel) (interface{}, error) {
  98. userModel, err := s.GetUserModel(ctx)
  99. if err != nil {
  100. return nil, xerr.WithStack(err)
  101. }
  102. newCalendar := &model.Calendar{}
  103. if err = s.DB.Model(&model.Calendar{}).
  104. Where("calendar_type = ?", req.CalendarType).
  105. Where("start_day = ?", req.Start).
  106. Where("is_show = ?", pasturePb.IsShow_Ok).
  107. Where("pasture_id = ?", userModel.AppPasture.Id).
  108. First(newCalendar).Error; err != nil {
  109. return nil, xerr.WithStack(err)
  110. }
  111. if newCalendar.Id <= 0 {
  112. return nil, xerr.New("不存在该日历数据")
  113. }
  114. return s.getCalendarCowList(ctx, req.CalendarType, req.Start, pagination, userModel.AppPasture.Id)
  115. }
  116. func (s *StoreEntry) getCalendarCowList(
  117. ctx context.Context,
  118. calendarType pasturePb.CalendarType_Kind,
  119. showDay string,
  120. pagination *pasturePb.PaginationModel,
  121. pastureId int64,
  122. ) (interface{}, error) {
  123. req := &pasturePb.ItemsRequest{EndDay: showDay, CalendarType: calendarType, PastureId: int32(pastureId)}
  124. switch calendarType {
  125. case pasturePb.CalendarType_Immunisation: // 免疫
  126. return s.ImmunisationCowList(ctx, req, pagination)
  127. case pasturePb.CalendarType_PG, pasturePb.CalendarType_RnGH: // 同期
  128. return s.SameTimeCowList(ctx, req, pagination)
  129. case pasturePb.CalendarType_Pregnancy_Check: // 孕检
  130. return s.PregnancyCheckCowList(ctx, req, pagination)
  131. case pasturePb.CalendarType_WorkOrder: // 工作单
  132. return s.WorkOrderCowList(ctx, req, pagination)
  133. case pasturePb.CalendarType_Weaning: // 断奶
  134. return s.WeaningCowList(ctx, req, pagination)
  135. case pasturePb.CalendarType_Disease: // 治疗
  136. return s.TreatmentCowList(ctx, req, pagination)
  137. case pasturePb.CalendarType_Mating: // 配种
  138. return s.MatingCowList(ctx, req, pagination)
  139. case pasturePb.CalendarType_Calving: // 产犊
  140. return s.CalvingCowList(ctx, req, pagination)
  141. default:
  142. return nil, xerr.New("不支持的日历类型")
  143. }
  144. }
  145. func (s *StoreEntry) ImmunisationCowList(ctx context.Context, req *pasturePb.ItemsRequest, pagination *pasturePb.PaginationModel) (*pasturePb.ImmunizationItemsResponse, error) {
  146. userModel, err := s.GetUserModel(ctx)
  147. if err != nil {
  148. return nil, xerr.WithStack(err)
  149. }
  150. eventImmunizationPlanList := make([]*model.EventImmunizationPlan, 0)
  151. count := int64(0)
  152. pref := s.DB.Table(fmt.Sprintf("%s as a", new(model.EventImmunizationPlan).TableName())).
  153. Select("a.id,a.cow_id,a.plan_day,a.plan_name as immunization_plan_name,b.pen_name,b.day_age,b.ear_number").
  154. Joins(fmt.Sprintf("JOIN %s AS b on a.cow_id = b.id", new(model.Cow).TableName())).
  155. Where("a.status = ?", pasturePb.IsShow_No).
  156. Where("a.pasture_id = ?", userModel.AppPasture.Id)
  157. if req.StartDay != "" && req.EndDay != "" {
  158. startTime := util.TimeParseLocalUnix(req.StartDay)
  159. endTime := util.TimeParseLocalEndUnix(req.EndDay)
  160. pref.Where("a.plan_day between ? and ?", startTime, endTime)
  161. }
  162. if req.CowId > 0 {
  163. pref.Where("a.cow_id = ?", req.CowId)
  164. }
  165. if req.ImmunizationId > 0 {
  166. pref.Where("a.plan_id = ?", req.ImmunizationId)
  167. }
  168. if req.PenId > 0 {
  169. pref.Where("b.pen_id = ?", req.PenId)
  170. }
  171. if err = pref.Count(&count).
  172. Limit(int(pagination.PageSize)).
  173. Offset(int(pagination.PageOffset)).
  174. Order("a.plan_day DESC").
  175. Find(&eventImmunizationPlanList).Error; err != nil {
  176. return nil, xerr.WithStack(err)
  177. }
  178. return &pasturePb.ImmunizationItemsResponse{
  179. Code: http.StatusOK,
  180. Msg: "ok",
  181. Data: &pasturePb.ImmunizationItemsData{
  182. Total: int32(count),
  183. Page: pagination.Page,
  184. PageSize: pagination.PageSize,
  185. Header: map[string]string{
  186. "id": "编号",
  187. "cowId": "牛号",
  188. "earNumber": "耳标号",
  189. "penName": "栏舍",
  190. "dayAge": "日龄",
  191. "planDay": "免疫时间",
  192. "immunizationPlanName": "免疫名称",
  193. },
  194. List: model.EventImmunizationPlanSlice(eventImmunizationPlanList).ToPB(),
  195. },
  196. }, nil
  197. }
  198. func (s *StoreEntry) SameTimeCowList(ctx context.Context, req *pasturePb.ItemsRequest, pagination *pasturePb.PaginationModel) (*pasturePb.SameTimeItemResponse, error) {
  199. userModel, err := s.GetUserModel(ctx)
  200. if err != nil {
  201. return nil, xerr.WithStack(err)
  202. }
  203. sameTimeBodyList := make([]*model.SameTimeItemBody, 0)
  204. count := int64(0)
  205. pref := s.DB.Table(fmt.Sprintf("%s as a", new(model.EventCowSameTime).TableName())).
  206. Select(`a.id,a.cow_id,a.ear_number,a.pen_name,a.status,a.same_time_type,b.breed_status,a.same_time_name,a.plan_day,
  207. b.cow_type,b.day_age,b.calving_age,b.abortion_age,b.last_calving_at,b.last_abortion_at,b.lact,b.pen_name,b.mating_times`).
  208. Joins("left join cow as b on a.cow_id = b.id").
  209. Where("b.admission_status = ?", pasturePb.AdmissionStatus_Admission).
  210. Where("a.pasture_id = ?", userModel.AppPasture.Id).
  211. Where("a.status = ?", pasturePb.IsShow_No)
  212. if req.EndDay != "" {
  213. dateTime := util.TimeParseLocalEndUnix(req.EndDay)
  214. pref.Where("a.plan_day <= ?", dateTime)
  215. }
  216. if req.CowType > 0 {
  217. pref.Where("b.cow_type = ?", req.CowType)
  218. }
  219. if req.SameTimeId > 0 {
  220. pref.Where("a.same_time_id = ?", req.SameTimeId)
  221. }
  222. if req.SameTimeType > 0 {
  223. pref.Where("a.same_time_type = ?", req.SameTimeType)
  224. }
  225. if err = pref.Order("a.plan_day DESC").Count(&count).
  226. Limit(int(pagination.PageSize)).
  227. Offset(int(pagination.PageOffset)).
  228. Find(&sameTimeBodyList).Error; err != nil {
  229. return nil, xerr.WithStack(err)
  230. }
  231. breedStatusMap := s.CowBreedStatusMap()
  232. penMap := s.PenMap(ctx, int64(req.PastureId))
  233. sameTimeTypeMap := s.SameTimeTypeMap()
  234. return &pasturePb.SameTimeItemResponse{
  235. Code: http.StatusOK,
  236. Msg: "ok",
  237. Data: &pasturePb.SameTimeItemsData{
  238. Total: int32(count),
  239. Page: pagination.Page,
  240. PageSize: pagination.PageSize,
  241. Header: map[string]string{
  242. "id": "编号",
  243. "cowId": "牛号",
  244. "earNumber": "耳标号",
  245. "breedStatusName": "繁殖状态",
  246. "cowTypeName": "牛只类型",
  247. "planDayAtFormat": "执行日期",
  248. "penName": "栏舍",
  249. "lact": "胎次",
  250. "calvingAge": "产后天数",
  251. "abortionAge": "流产天数",
  252. "dayAge": "日龄",
  253. "status": "状态",
  254. "sameTimeTypeName": "处理方式",
  255. "matingTimes": "本胎次配次",
  256. "calvingAtFormat": "产犊日期",
  257. "abortionAtFormat": "流产日期",
  258. "sameTimeName": "同期名称",
  259. },
  260. List: model.SameTimeBodySlice(sameTimeBodyList).ToPB(breedStatusMap, penMap, sameTimeTypeMap),
  261. },
  262. }, nil
  263. }
  264. func (s *StoreEntry) PregnancyCheckCowList(ctx context.Context, req *pasturePb.ItemsRequest, pagination *pasturePb.PaginationModel) (*pasturePb.PregnancyCheckItemsResponse, error) {
  265. userModel, err := s.GetUserModel(ctx)
  266. if err != nil {
  267. return nil, xerr.WithStack(err)
  268. }
  269. newPregnancyCheckItems := make([]*pasturePb.PregnancyCheckItems, 0)
  270. var count int64
  271. pref := s.DB.Table(fmt.Sprintf("%s as a", new(model.EventPregnantCheck).TableName())).
  272. Select(`a.id,a.cow_id,a.ear_number,a.pen_id,a.status,b.breed_status,b.pen_name,b.cow_type,
  273. CASE a.pregnant_check_name
  274. WHEN 'pregnant_check_for_first' THEN '初检'
  275. WHEN 'pregnant_check_for_second' THEN '复检'
  276. ELSE '其他'
  277. END AS check_type_name,b.day_age,b.calving_age,b.abortion_age,a.bull_id`).
  278. Joins("left join cow as b on a.cow_id = b.id").
  279. Where("b.admission_status = ?", pasturePb.AdmissionStatus_Admission).
  280. Where("a.pasture_id = ?", userModel.AppPasture.Id).
  281. Where("a.status = ?", pasturePb.IsShow_No)
  282. if req.EndDay != "" {
  283. dateTime := util.TimeParseLocalEndUnix(req.EndDay)
  284. pref.Where("a.plan_day <= ?", dateTime)
  285. }
  286. if req.PenId > 0 {
  287. pref.Where("b.pen_id = ?", req.PenId)
  288. }
  289. if req.CowType > 0 {
  290. pref.Where("a.cow_type = ?", req.CowType)
  291. }
  292. if req.PregnantCheckType > 0 {
  293. pref.Where("a.pregnant_check_name = ?", model.PregnantCheckNameValueMap[req.PregnantCheckType])
  294. }
  295. if err = pref.Order("a.plan_day DESC").
  296. Count(&count).
  297. Limit(int(pagination.PageSize)).
  298. Offset(int(pagination.PageOffset)).
  299. Find(&newPregnancyCheckItems).Error; err != nil {
  300. return nil, xerr.WithStack(err)
  301. }
  302. return &pasturePb.PregnancyCheckItemsResponse{
  303. Code: http.StatusOK,
  304. Msg: "ok",
  305. Data: &pasturePb.PregnancyCheckItemsData{
  306. Total: int32(count),
  307. Page: pagination.Page,
  308. PageSize: pagination.PageSize,
  309. Header: map[string]string{
  310. "id": "编号",
  311. "cowId": "牛号",
  312. "earNumber": "耳标号",
  313. "cowTypeName": "牛只类型",
  314. "penName": "栏舍",
  315. "lact": "胎次",
  316. "dayAge": "日龄",
  317. "planDay": "孕检日期",
  318. "checkTypeName": "孕检名称",
  319. "status": "状态",
  320. "matingTimes": "配次",
  321. "calvingAtFormat": "产检日期",
  322. "matingAtFormat": "配种日期",
  323. "matingAge": "配后天数",
  324. "bullId": "配种公牛",
  325. },
  326. List: newPregnancyCheckItems,
  327. },
  328. }, nil
  329. }
  330. func (s *StoreEntry) WeaningCowList(ctx context.Context, req *pasturePb.ItemsRequest, pagination *pasturePb.PaginationModel) (*pasturePb.WeaningItemsResponse, error) {
  331. userModel, err := s.GetUserModel(ctx)
  332. if err != nil {
  333. return nil, xerr.WithStack(err)
  334. }
  335. weaningItems := make([]*pasturePb.WeaningItems, 0)
  336. count := int64(0)
  337. pref := s.DB.Table(fmt.Sprintf("%s as a", new(model.EventWeaning).TableName())).
  338. Select(`a.id,a.cow_id,ROUND(b.current_weight / 1000,2) as current_weight,DATE_FORMAT(FROM_UNIXTIME(a.plan_day), '%Y-%m-%d') AS plan_day_format,
  339. b.day_age,b.pen_name,b.ear_number,DATE_FORMAT(FROM_UNIXTIME(b.birth_at), '%Y-%m-%d') AS birth_at_format`).
  340. Joins("left join cow as b on a.cow_id = b.id").
  341. Where("b.admission_status = ?", pasturePb.AdmissionStatus_Admission).
  342. Where("a.status = ?", pasturePb.IsShow_No).
  343. Where("a.pasture_id = ?", userModel.AppPasture.Id)
  344. if req.EndDay != "" {
  345. dateTime := util.TimeParseLocalEndUnix(req.EndDay)
  346. pref.Where("a.plan_day <= ?", dateTime)
  347. }
  348. if err = pref.Order("a.plan_day DESC").Count(&count).
  349. Limit(int(pagination.PageSize)).
  350. Offset(int(pagination.PageOffset)).
  351. Find(&weaningItems).Error; err != nil {
  352. return nil, xerr.WithStack(err)
  353. }
  354. return &pasturePb.WeaningItemsResponse{
  355. Code: http.StatusOK,
  356. Msg: "ok",
  357. Data: &pasturePb.WeaningItemsData{
  358. Total: int32(count),
  359. Page: pagination.Page,
  360. PageSize: pagination.PageSize,
  361. Header: map[string]string{
  362. "id": "编号",
  363. "cowId": "牛号",
  364. "earNumber": "耳标号",
  365. "penName": "栏舍",
  366. "dayAge": "日龄",
  367. "planDayFormat": "断奶日期",
  368. "birthAtFormat": "出生日期",
  369. "currentWeight": "体重",
  370. },
  371. List: weaningItems,
  372. },
  373. }, nil
  374. }
  375. func (s *StoreEntry) MatingCowList(ctx context.Context, req *pasturePb.ItemsRequest, pagination *pasturePb.PaginationModel) (*pasturePb.MatingItemsResponse, error) {
  376. userModel, err := s.GetUserModel(ctx)
  377. if err != nil {
  378. return nil, xerr.WithStack(err)
  379. }
  380. matingItems := make([]*pasturePb.MatingItems, 0)
  381. count := int64(0)
  382. pref := s.DB.Table(fmt.Sprintf("%s as a", new(model.EventMating).TableName())).
  383. Select(`a.id,a.cow_id,a.status,a.ear_number,
  384. CASE a.expose_estrus_type
  385. WHEN 1 THEN '脖环揭发'
  386. WHEN 2 THEN '脚环/计步器'
  387. WHEN 3 THEN '自然发情'
  388. WHEN 4 THEN '同期'
  389. ELSE '其他'
  390. END AS expose_estrus_type_name,
  391. CASE
  392. WHEN last_calving_at = 0 THEN ""
  393. ELSE DATE_FORMAT(FROM_UNIXTIME(last_calving_at), '%Y-%m-%d %H:%i:%s')
  394. END AS last_calving_at_format,
  395. b.breed_status,b.cow_type,b.pen_id,b.day_age,b.calving_age,b.abortion_age,b.pen_name`).
  396. Joins("left join cow as b on a.cow_id = b.id").
  397. Where("a.pasture_id = ?", userModel.AppPasture.Id).
  398. Where("a.status = ?", pasturePb.IsShow_No)
  399. if req.EndDay != "" {
  400. dateTime := util.TimeParseLocalEndUnix(req.EndDay)
  401. pref.Where("a.plan_day <= ?", dateTime)
  402. }
  403. if req.PenId > 0 {
  404. pref.Where("b.pen_id = ?", req.PenId)
  405. }
  406. if req.EarNumber != "" {
  407. pref.Where("a.ear_number = ?", req.EarNumber)
  408. }
  409. if err = pref.Order("a.plan_day DESC").
  410. Count(&count).
  411. Limit(int(pagination.PageSize)).
  412. Offset(int(pagination.PageOffset)).
  413. Find(&matingItems).Error; err != nil {
  414. return nil, xerr.WithStack(err)
  415. }
  416. return &pasturePb.MatingItemsResponse{
  417. Code: http.StatusOK,
  418. Msg: "ok",
  419. Data: &pasturePb.MatingItemsData{
  420. Total: int32(count),
  421. Page: pagination.Page,
  422. PageSize: pagination.PageSize,
  423. Header: map[string]string{
  424. "id": "编号",
  425. "cowId": "牛号",
  426. "earNumber": "耳标号",
  427. "breedStatusName": "繁殖状态",
  428. "cowTypeName": "牛只类型",
  429. "penName": "栏舍",
  430. "lact": "胎次",
  431. "calvingAge": "产后天数",
  432. "abortionAge": "流产天数",
  433. "dayAge": "日龄",
  434. "status": "状态",
  435. "exposeEstrusTypeName": "发情揭发方式",
  436. "lastCalvingAtFormat": "产犊日期",
  437. },
  438. List: matingItems,
  439. },
  440. }, nil
  441. }
  442. func (s *StoreEntry) CalvingCowList(ctx context.Context, req *pasturePb.ItemsRequest, pagination *pasturePb.PaginationModel) (*pasturePb.CalvingItemsResponse, error) {
  443. userModel, err := s.GetUserModel(ctx)
  444. if err != nil {
  445. return nil, xerr.WithStack(err)
  446. }
  447. calvingItems := make([]*pasturePb.CalvingItems, 0)
  448. count := int64(0)
  449. pref := s.DB.Table(fmt.Sprintf("%s as a", new(model.EventCalving).TableName())).
  450. Select(`a.id,a.cow_id,a.ear_number,a.status,b.breed_status,b.pen_id,ROUND(b.current_weight/100,2) as current_weight,DATE_FORMAT(FROM_UNIXTIME(last_mating_at), '%Y-%m-%d') AS mating_at_format,
  451. b.day_age,b.last_bull_number as bull_id,b.pen_name,DATEDIFF(NOW(),FROM_UNIXTIME(last_mating_at)) AS mating_age,DATE_FORMAT(FROM_UNIXTIME(a.plan_day), '%Y-%m-%d') AS plan_day`).
  452. Joins("left join cow as b on a.cow_id = b.id").
  453. Where("a.status = ?", pasturePb.IsShow_No).
  454. Where("b.admission_status = ?", pasturePb.AdmissionStatus_Admission).
  455. Where("a.pasture_id = ?", userModel.AppPasture.Id)
  456. if req.EndDay != "" {
  457. dateTime := util.TimeParseLocalEndUnix(req.EndDay)
  458. pref.Where("a.plan_day <= ?", dateTime)
  459. }
  460. if req.PenId > 0 {
  461. pref.Where("b.pen_id = ?", req.PenId)
  462. }
  463. if err = pref.Order("a.plan_day DESC").
  464. Count(&count).
  465. Limit(int(pagination.PageSize)).
  466. Offset(int(pagination.PageOffset)).
  467. Find(&calvingItems).Error; err != nil {
  468. return nil, xerr.WithStack(err)
  469. }
  470. breedStatusMap := s.CowBreedStatusMap()
  471. for _, v := range calvingItems {
  472. breedStatusName := ""
  473. if breedStatus, ok := breedStatusMap[v.BreedStatus]; ok {
  474. breedStatusName = breedStatus
  475. }
  476. v.BreedStatusName = breedStatusName
  477. }
  478. return &pasturePb.CalvingItemsResponse{
  479. Code: http.StatusOK,
  480. Msg: "ok",
  481. Data: &pasturePb.CalvingItemsData{
  482. Total: int32(count),
  483. Page: pagination.Page,
  484. PageSize: pagination.PageSize,
  485. Header: map[string]string{
  486. "id": "编号",
  487. "cowId": "牛号",
  488. "earNumber": "耳标号",
  489. "breedStatusName": "繁殖状态",
  490. "penName": "栏舍",
  491. "lact": "胎次",
  492. "matingAge": "配后天数",
  493. "dayAge": "日龄",
  494. "status": "是否完成",
  495. "bullId": "配种公牛号",
  496. "planDay": "预产时间",
  497. "matingAtFormat": "配种时间",
  498. "currentWeight": "体重",
  499. },
  500. List: calvingItems,
  501. },
  502. }, nil
  503. }
  504. // TreatmentCowList 治疗清单
  505. func (s *StoreEntry) TreatmentCowList(ctx context.Context, req *pasturePb.ItemsRequest, pagination *pasturePb.PaginationModel) (interface{}, error) {
  506. userModel, err := s.GetUserModel(ctx)
  507. if err != nil {
  508. return nil, xerr.WithStack(err)
  509. }
  510. diseaseItems := make([]*model.EventCowDisease, 0)
  511. count := int64(0)
  512. pref := s.DB.Table(fmt.Sprintf("%s as a", new(model.EventCowDisease).TableName())).
  513. Joins(fmt.Sprintf("JOIN %s AS b on a.cow_id = b.id", new(model.Cow).TableName())).
  514. Where("a.pasture_id = ?", userModel.AppPasture.Id).
  515. Where("a.health_status IN (?)", []pasturePb.HealthStatus_Kind{pasturePb.HealthStatus_Disease, pasturePb.HealthStatus_Treatment})
  516. if req.PenId > 0 {
  517. pref.Where("b.pen_id = ?", req.PenId)
  518. }
  519. if err = pref.Order("a.disease_at DESC").
  520. Count(&count).
  521. Limit(int(pagination.PageSize)).
  522. Offset(int(pagination.PageOffset)).
  523. Find(&diseaseItems).Error; err != nil {
  524. return nil, xerr.WithStack(err)
  525. }
  526. return &pasturePb.EventCowDiseaseResponse{
  527. Code: http.StatusOK,
  528. Msg: "ok",
  529. Data: &pasturePb.EventCowDiseaseData{
  530. List: model.EventCowDiseaseSlice(diseaseItems).ToPB(s.HealthStatusMap()),
  531. Total: int32(count),
  532. PageSize: pagination.PageSize,
  533. Page: pagination.Page,
  534. Header: map[string]string{
  535. "id": "编号",
  536. "cowId": "牛号",
  537. "earNumber": "耳标",
  538. "diagnoseName": "疾病名称",
  539. "healthStatus": "健康状态",
  540. "lastPrescriptionName": "处方名称",
  541. "treatmentDays": "治疗天数",
  542. "onsetDays": "发病天数",
  543. "penName": "栏舍名称",
  544. },
  545. },
  546. }, nil
  547. }
  548. // WorkOrderCowList 暂时不处理工单业务
  549. func (s *StoreEntry) WorkOrderCowList(ctx context.Context, req *pasturePb.ItemsRequest, pagination *pasturePb.PaginationModel) (interface{}, error) {
  550. return nil, nil
  551. }
  552. // Paginate 函数用于对切片进行分页
  553. func Paginate(slice []*pasturePb.CalendarToDoList, req *pasturePb.CalendarToDoRequest, pagination *pasturePb.PaginationModel) ([]*pasturePb.CalendarToDoList, int32) {
  554. newSlice := make([]*pasturePb.CalendarToDoList, 0)
  555. if req.CalendarType > 0 {
  556. calendarTypeName := CalendarTypeMap()[req.CalendarType]
  557. if len(calendarTypeName) > 0 {
  558. re := regexp.MustCompile(`[a-zA-Z]`) // 使用正则表达式替换匹配的字母为空字符串
  559. calendarTypeName = re.ReplaceAllString(calendarTypeName, "")
  560. for _, v := range slice {
  561. if v.CalendarTypeName != calendarTypeName {
  562. continue
  563. }
  564. newSlice = append(newSlice, v)
  565. }
  566. }
  567. } else {
  568. newSlice = append(newSlice, slice...)
  569. }
  570. if req.CowId > 0 {
  571. filteredSlice := make([]*pasturePb.CalendarToDoList, 0)
  572. for _, v := range newSlice {
  573. if v.CowId != req.CowId {
  574. continue
  575. }
  576. filteredSlice = append(filteredSlice, v)
  577. }
  578. newSlice = filteredSlice
  579. }
  580. total := int32(len(newSlice))
  581. // 计算起始索引
  582. start := (pagination.Page - 1) * pagination.PageSize
  583. // 如果起始索引超出切片长度,返回空切片
  584. if start >= int32(len(newSlice)) {
  585. return []*pasturePb.CalendarToDoList{}, total
  586. }
  587. // 计算结束索引
  588. end := start + pagination.PageSize
  589. // 如果结束索引超出切片长度,调整到切片末尾
  590. if end > int32(len(newSlice)) {
  591. end = int32(len(newSlice))
  592. }
  593. // 返回分页后的切片
  594. return newSlice[start:end], total
  595. }
  596. func ProgressList(dataList []*pasturePb.CalendarToDoList, toDayCompletedCountMap map[string]int32) map[string]*pasturePb.ProgressList {
  597. res := make(map[string]*pasturePb.ProgressList)
  598. for cn, cc := range toDayCompletedCountMap {
  599. res[cn] = &pasturePb.ProgressList{
  600. CalendarName: cn,
  601. CompletedCount: cc,
  602. }
  603. for _, d := range dataList {
  604. calendarName := CalendarTypeMap()[d.CalendarType]
  605. if calendarName != cn {
  606. continue
  607. }
  608. res[cn].CalendarTypeKind = d.CalendarType
  609. res[cn].IncompleteTotal += 1
  610. }
  611. if res[cn].IncompleteTotal > 0 && res[cn].CompletedCount > 0 {
  612. res[cn].Progress = strconv.FormatFloat(float64(res[cn].CompletedCount)/float64(res[cn].IncompleteTotal)*100, 'f', 2, 64)
  613. } else {
  614. res[cn].Progress = "0%"
  615. }
  616. }
  617. return res
  618. }