calendar.go 23 KB

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