소스 검색

sameTime: 同期优化

Yi 6 달 전
부모
커밋
2b74ec7b4c

+ 1 - 1
config/app.develop.yaml

@@ -16,7 +16,7 @@ redis_setting:
   cache_redis:
     addr: '47.92.95.119:6389'
     db: 11
-    requirepass: ""
+    requirepass: "root"
     expiry: 120
 
 jwt_secret: "sUd7j%UfJMt59ywh"

+ 2 - 2
config/app.test.yaml

@@ -15,7 +15,7 @@ redis_setting:
   cache_redis:
     addr: 47.92.95.119:6389'
     db: 0
-    requirepass: ""
+    requirepass: "root"
     expiry: 120
 
 jwt_secret: "sUd7j%UfJMt59ywh"
@@ -25,7 +25,7 @@ side_work_setting:
   asynq_setting:
     redis:
       addr: '47.92.95.119:6389'
-      db: 16
+      db: 0
       pool_size: 10
     concurrency: 5
     queues:

+ 1 - 1
go.mod

@@ -3,7 +3,7 @@ module kpt-pasture
 go 1.17
 
 require (
-	gitee.com/xuyiping_admin/go_proto v0.0.0-20240912072215-f7745ae5f7be
+	gitee.com/xuyiping_admin/go_proto v0.0.0-20240913094501-2c3f16e7b53a
 	gitee.com/xuyiping_admin/pkg v0.0.0-20231218082641-aac597b8a015
 	github.com/dgrijalva/jwt-go v3.2.0+incompatible
 	github.com/eko/gocache v1.1.0

+ 12 - 0
go.sum

@@ -70,6 +70,18 @@ gitee.com/xuyiping_admin/go_proto v0.0.0-20240912053920-4574bdb15216 h1:NWizM8am
 gitee.com/xuyiping_admin/go_proto v0.0.0-20240912053920-4574bdb15216/go.mod h1:BKrFW6YLDectlQcQk3FYKBeXvjEiodAKJ5rq7O/QiPE=
 gitee.com/xuyiping_admin/go_proto v0.0.0-20240912072215-f7745ae5f7be h1:c8X60ELEPuwUbjNCQ/ensGzX8vwLa8Bxi2kjUjjp9RA=
 gitee.com/xuyiping_admin/go_proto v0.0.0-20240912072215-f7745ae5f7be/go.mod h1:BKrFW6YLDectlQcQk3FYKBeXvjEiodAKJ5rq7O/QiPE=
+gitee.com/xuyiping_admin/go_proto v0.0.0-20240912094449-3403561dafd5 h1:1ER5K/jBvlGwG9DtVSS6qznJTBqoWpibxYIliWm6Hvw=
+gitee.com/xuyiping_admin/go_proto v0.0.0-20240912094449-3403561dafd5/go.mod h1:BKrFW6YLDectlQcQk3FYKBeXvjEiodAKJ5rq7O/QiPE=
+gitee.com/xuyiping_admin/go_proto v0.0.0-20240913035809-c17813bb52a4 h1:Ngcrr5pqJuVMzOpJL/DDgJJG2Ifp2ddDqJqfpKl5dtA=
+gitee.com/xuyiping_admin/go_proto v0.0.0-20240913035809-c17813bb52a4/go.mod h1:BKrFW6YLDectlQcQk3FYKBeXvjEiodAKJ5rq7O/QiPE=
+gitee.com/xuyiping_admin/go_proto v0.0.0-20240913052245-91b5dc33dc1f h1:Wd3IIMuvUUuLb05hDvYEP09674GJQ20RWZEUbOHpTkg=
+gitee.com/xuyiping_admin/go_proto v0.0.0-20240913052245-91b5dc33dc1f/go.mod h1:BKrFW6YLDectlQcQk3FYKBeXvjEiodAKJ5rq7O/QiPE=
+gitee.com/xuyiping_admin/go_proto v0.0.0-20240913064049-b55eee13d8e3 h1:dWEcyM7ST22AD4n+XYdZ/VPvl/+SYJK+KrrPrAxZUKA=
+gitee.com/xuyiping_admin/go_proto v0.0.0-20240913064049-b55eee13d8e3/go.mod h1:BKrFW6YLDectlQcQk3FYKBeXvjEiodAKJ5rq7O/QiPE=
+gitee.com/xuyiping_admin/go_proto v0.0.0-20240913070925-6c67b84f42fc h1:o8U7cViR7ZmfFOSNBcjVNQXxFRK7PVVo1Sf5NsBP0Ns=
+gitee.com/xuyiping_admin/go_proto v0.0.0-20240913070925-6c67b84f42fc/go.mod h1:BKrFW6YLDectlQcQk3FYKBeXvjEiodAKJ5rq7O/QiPE=
+gitee.com/xuyiping_admin/go_proto v0.0.0-20240913094501-2c3f16e7b53a h1:piTgQ0Z1UJ87ti12F1gUOtglzW92pFy0afPoFSLn+ns=
+gitee.com/xuyiping_admin/go_proto v0.0.0-20240913094501-2c3f16e7b53a/go.mod h1:BKrFW6YLDectlQcQk3FYKBeXvjEiodAKJ5rq7O/QiPE=
 gitee.com/xuyiping_admin/pkg v0.0.0-20231218082641-aac597b8a015 h1:dfb5dRd57L2HKjdwLT93UFmPYFPOmEl56gtZmqcNnaE=
 gitee.com/xuyiping_admin/pkg v0.0.0-20231218082641-aac597b8a015/go.mod h1:Fk4GYI/v0IK3XFrm1Gn+VkgCz5Y7mfswD5hsTJYOG6A=
 github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=

+ 24 - 1
http/handler/work/calendar.go

@@ -12,7 +12,7 @@ import (
 )
 
 func CalendarList(c *gin.Context) {
-	var req pasturePb.WorkOrderCalendarRequest
+	var req pasturePb.CalendarRequest
 	if err := ginutil.BindProto(c, &req); err != nil {
 		apierr.AbortBadRequest(c, http.StatusBadRequest, err)
 		return
@@ -33,3 +33,26 @@ func CalendarList(c *gin.Context) {
 	}
 	ginutil.JSONResp(c, res)
 }
+
+func CalendarTableDetail(c *gin.Context) {
+	var req pasturePb.CalendarTableRequest
+	if err := ginutil.BindProto(c, &req); err != nil {
+		apierr.AbortBadRequest(c, http.StatusBadRequest, err)
+		return
+	}
+
+	if err := valid.ValidateStruct(&req,
+		valid.Field(&req.CalendarType, valid.Required),
+		valid.Field(&req.Start, valid.Required),
+	); err != nil {
+		apierr.AbortBadRequest(c, http.StatusBadRequest, err)
+		return
+	}
+
+	res, err := middleware.Dependency(c).StoreEventHub.OpsService.CalendarTableDetail(c, &req)
+	if err != nil {
+		apierr.ClassifiedAbort(c, err)
+		return
+	}
+	c.JSON(http.StatusOK, res)
+}

+ 1 - 0
http/route/work_order.go

@@ -19,6 +19,7 @@ func WorkOrderAPI(opts ...func(engine *gin.Engine)) func(s *gin.Engine) {
 		workRoute.GET("/user/order/list/:status", work.UserOrderList)
 
 		workRoute.POST("/calendar/list", work.CalendarList)
+		workRoute.GET("/calendar/detail", work.CalendarTableDetail)
 
 	}
 }

+ 87 - 0
model/calendar.go

@@ -0,0 +1,87 @@
+package model
+
+import (
+	"fmt"
+	"time"
+
+	pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
+)
+
+type Calendar struct {
+	Id           int64                       `json:"id"`
+	Name         string                      `json:"name"`
+	CalendarType pasturePb.CalendarType_Kind `json:"calendarType"`
+	Count        int32                       `json:"count"`
+	ShowDay      string                      `json:"showDay"`
+	IsShow       pasturePb.IsShow_Kind       `json:"isShow"`
+	Backup       string                      `json:"backup"`
+	CreatedAt    int64                       `json:"createdAt"`
+	UpdatedAt    int64                       `json:"updatedAt"`
+}
+
+func (w *Calendar) TableName() string {
+	return "calendar"
+}
+
+func NewCalendar(name string, calendarType pasturePb.CalendarType_Kind, count int32) *Calendar {
+	return &Calendar{
+		Name:         name,
+		Count:        count,
+		CalendarType: calendarType,
+		ShowDay:      time.Now().Format(LayoutDate2),
+		IsShow:       pasturePb.IsShow_Ok,
+	}
+}
+
+var CalendarTypeColorMap = map[pasturePb.CalendarType_Kind]string{
+	pasturePb.CalendarType_Immunisation:    "#85c1e9",
+	pasturePb.CalendarType_PG:              "#48C9B0",
+	pasturePb.CalendarType_RnGH:            "#d35400",
+	pasturePb.CalendarType_Pregnancy_Check: "#8E44AD",
+	pasturePb.CalendarType_WorkOrder:       "#5d6d7e",
+	pasturePb.CalendarType_Treatment:       "#c0392b",
+}
+
+type CalendarSlice []*Calendar
+
+func (c CalendarSlice) ToPB() []*pasturePb.Calendar {
+	res := make([]*pasturePb.Calendar, len(c))
+	for i, v := range c {
+		res[i] = &pasturePb.Calendar{
+			Id:            int32(v.Id),
+			Title:         fmt.Sprintf("%s - %d", v.Name, v.Count),
+			GroupId:       v.CalendarType,
+			Count:         v.Count,
+			Start:         v.ShowDay,
+			Color:         CalendarTypeColorMap[v.CalendarType],
+			ExtendedProps: v.Backup,
+		}
+	}
+	return res
+}
+
+type SameTimeHeader struct {
+	Id          string `json:"id"`
+	CowId       string `json:"cowId"`
+	BreedStatus string `json:"breedStatus"`
+	PenName     string `json:"penName"`
+	Lact        string `json:"lact"`
+	CalvingAge  string `json:"calvingAge"`
+	AbortionAge string `json:"abortionAge"`
+	DayAge      string `json:"dayAge"`
+	Status      string `json:"status"`
+	ExecType    string `json:"execType"`
+}
+
+type SameTimeBody struct {
+	Id          int64                      `json:"id"`
+	CowId       int64                      `json:"cowId"`
+	BreedStatus pasturePb.BreedStatus_Kind `json:"breedStatus"`
+	PenName     string                     `json:"penName"`
+	Lact        int32                      `json:"lact"`
+	CalvingAge  int32                      `json:"calvingAge"`
+	AbortionAge int32                      `json:"abortionAge"`
+	DayAge      int32                      `json:"dayAge"`
+	Status      pasturePb.IsShow_Kind      `json:"status"`
+	ExecType    string                     `json:"execType"` // todo 执行类型定义成枚举???
+}

+ 36 - 35
model/cow.go

@@ -11,42 +11,43 @@ import (
 type Cow struct {
 	Id                  int64                      `json:"id"`
 	Sex                 pasturePb.Genders_Kind     `json:"sex"`
-	NeckRingNumber      string                     `json:"neck_ring_number"`
-	EarNumber           string                     `json:"ear_number"`
-	EarOldNumber        string                     `json:"ear_old_number"`
-	PenId               int64                      `json:"pen_id"`
+	NeckRingNumber      string                     `json:"neckRingNumber"`
+	EarNumber           string                     `json:"earNumber"`
+	EarOldNumber        string                     `json:"earOldNumber"`
+	PenId               int64                      `json:"penId"`
 	Lact                int32                      `json:"lact"`
-	DayAge              int32                      `json:"day_age"`
-	CalvingAge          int64                      `json:"calving_age"`
-	PregnancyAge        int64                      `json:"pregnancy_age"` // 怀孕天数 孕检结果有阳性更新,产犊后至0
-	AdmissionAge        int64                      `json:"admission_age"`
-	CowType             pasturePb.CowType_Kind     `json:"cow_type"`
-	BreedStatus         pasturePb.BreedStatus_Kind `json:"breed_status"`
-	CowKind             pasturePb.CowKind_Kind     `json:"cow_kind"`
-	BirthWeight         int64                      `json:"birth_weight"`
-	CurrentWeight       int64                      `json:"current_weight"`
-	SourceId            pasturePb.CowSource_Kind   `json:"source_id"`
-	FatherId            int64                      `json:"father_id"`
-	MotherId            int64                      `json:"mother_id"`
-	IsRemove            pasturePb.IsShow_Kind      `json:"is_remove"`
-	IsPregnant          pasturePb.IsShow_Kind      `json:"is_pregnant"`
-	IsHealth            pasturePb.IsShow_Kind      `json:"is_health"`
-	WeaningAt           int64                      `json:"weaning_at"`
-	CalvingAt           int64                      `json:"calving_at"`
-	BirthAt             int64                      `json:"birth_at"`
-	AdmissionAt         int64                      `json:"admission_at"`
-	FirstMatingAt       int64                      `json:"first_mating_at"`
-	LastEstrusAt        int64                      `json:"last_estrus_at"`
-	LastCalvingAt       int64                      `json:"last_calving_at"`
-	LastMatingAt        int64                      `json:"last_mating_at"`
-	LastBullId          int64                      `json:"last_bull_id"`
-	LastPregnantCheckAt int64                      `json:"last_pregnant_check_at"`
-	LastDryMilkAt       int64                      `json:"last_dry_milk_at"`
-	LastSecondWeight    int64                      `json:"last_second_weight"`
-	LastSecondWeightAt  int64                      `json:"last_second_weight_at"`
-	LastWeightAt        int64                      `json:"last_weight_at"`
-	CreatedAt           int64                      `json:"created_at"`
-	UpdatedAt           int64                      `json:"updated_at"`
+	DayAge              int32                      `json:"dayAge"`
+	CalvingAge          int64                      `json:"calvingAge"`
+	PregnancyAge        int64                      `json:"pregnancyAge"` // 怀孕天数 孕检结果有阳性更新,产犊后至0
+	AdmissionAge        int64                      `json:"admissionAge"`
+	CowType             pasturePb.CowType_Kind     `json:"cowType"`
+	BreedStatus         pasturePb.BreedStatus_Kind `json:"breedStatus"`
+	CowKind             pasturePb.CowKind_Kind     `json:"cowKind"`
+	BirthWeight         int64                      `json:"birthWeight"`
+	CurrentWeight       int64                      `json:"currentWeight"`
+	SourceId            pasturePb.CowSource_Kind   `json:"sourceId"`
+	FatherId            int64                      `json:"fatherId"`
+	MotherId            int64                      `json:"motherId"`
+	IsRemove            pasturePb.IsShow_Kind      `json:"isRemove"`
+	IsPregnant          pasturePb.IsShow_Kind      `json:"isPregnant"`
+	IsHealth            pasturePb.IsShow_Kind      `json:"isHealth"`
+	WeaningAt           int64                      `json:"weaningAt"`
+	CalvingAt           int64                      `json:"calvingAt"`
+	BirthAt             int64                      `json:"birthAti"`
+	AdmissionAt         int64                      `json:"admissionAt"`
+	FirstMatingAt       int64                      `json:"firstMatingAt"`
+	LastEstrusAt        int64                      `json:"lastEstrusAt"`
+	LastCalvingAt       int64                      `json:"lastCalvingAt"`
+	LastMatingAt        int64                      `json:"lastMatingAt"`
+	LastBullId          int64                      `json:"lastBullId"`
+	LastPregnantCheckAt int64                      `json:"lastPregnantCheckAt"`
+	LastDryMilkAt       int64                      `json:"lastDryMilkAt"`
+	LastSecondWeight    int64                      `json:"lastSecondWeight"`
+	LastSecondWeightAt  int64                      `json:"lastSecondWeightAt"`
+	LastAbortionAt      int64                      `json:"lastAbortionAt"`
+	LastWeightAt        int64                      `json:"lastWeightAt"`
+	CreatedAt           int64                      `json:"createdAt"`
+	UpdatedAt           int64                      `json:"updatedAt"`
 }
 
 func (c *Cow) TableName() string {

+ 0 - 46
model/event_same_time.go

@@ -1,46 +0,0 @@
-package model
-
-import pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
-
-type EventSameTime struct {
-	Id               int64                       `json:"id"`
-	CowId            int64                       `json:"cowId"`
-	Lact             int32                       `json:"lact"`
-	DayAge           int32                       `json:"dayAge"`
-	CalvingAge       int64                       `json:"calvingAge"`
-	SameTimeId       int64                       `json:"sameTimeId"`
-	SameTimeType     pasturePb.SameTimeType_Kind `json:"sameTimeType"`
-	SameTimeTypeName string                      `json:"sameTimeTypeName"`
-	DrugsId          int64                       `json:"drugsId"`
-	DrugsName        string                      `json:"drugsName"`
-	Unit             pasturePb.Unit_Kind         `json:"unit"`
-	Usage            int32                       `json:"usage"`
-	Remarks          string                      `json:"remarks"`
-	StallNumberId    int64                       `json:"stallNumberId"`
-	OperationId      int64                       `json:"operation_id"`
-	CreatedAt        int64                       `json:"created_at"`
-	UpdatedAt        int64                       `json:"updated_at"`
-}
-
-func (e *EventSameTime) TableName() string {
-	return "event_same_time"
-}
-
-func NewEventSameTime(cow *Cow, req *pasturePb.EventSameTime, drugs *Drugs) *EventSameTime {
-	eventSameTime := &EventSameTime{
-		CowId:            cow.Id,
-		CalvingAge:       cow.CalvingAge,
-		SameTimeId:       int64(req.SameTimeId),
-		SameTimeType:     req.SameTimeType,
-		SameTimeTypeName: req.SameTimeTypeName,
-		Remarks:          req.Remarks,
-	}
-
-	if drugs != nil && drugs.Id > 0 {
-		eventSameTime.DrugsId = drugs.Id
-		eventSameTime.DrugsName = drugs.Name
-		eventSameTime.Unit = drugs.Unit
-		eventSameTime.Usage = req.Usage
-	}
-	return eventSameTime
-}

+ 35 - 31
model/immunization_plan.go

@@ -5,17 +5,18 @@ import (
 )
 
 type ImmunizationPlan struct {
-	Id                 int64                                 `json:"id"`
-	Name               string                                `json:"name"`
-	CowType            pasturePb.CowType_Kind                `json:"cowType"`
-	Conditions         pasturePb.ImmunizationConditions_Kind `json:"conditions"`
-	Value              int64                                 `json:"value"`
-	IsShow             pasturePb.IsShow_Kind                 `json:"isShow"`
-	ImmunizationPlanId int64                                 `json:"immunizationPlanId"`
-	OperationId        int64                                 `json:"operationId"`
-	OperationName      string                                `json:"operationName"`
-	CreatedAt          int64                                 `json:"createdAt"`
-	UpdatedAt          int64                                 `json:"updatedAt"`
+	Id                   int64                                 `json:"id"`
+	Name                 string                                `json:"name"`
+	CowType              pasturePb.CowType_Kind                `json:"cowType"`
+	Conditions           pasturePb.ImmunizationConditions_Kind `json:"conditions"`
+	Value                int64                                 `json:"value"`
+	IsShow               pasturePb.IsShow_Kind                 `json:"isShow"`
+	ImmunizationPlanId   int64                                 `json:"immunizationPlanId"`
+	ImmunizationPlanName string                                `json:"immunizationPlanName"`
+	OperationId          int64                                 `json:"operationId"`
+	OperationName        string                                `json:"operationName"`
+	CreatedAt            int64                                 `json:"createdAt"`
+	UpdatedAt            int64                                 `json:"updatedAt"`
 }
 
 func (i *ImmunizationPlan) TableName() string {
@@ -24,14 +25,15 @@ func (i *ImmunizationPlan) TableName() string {
 
 func NewImmunizationPlan(systemUser *SystemUser, req *pasturePb.ImmunizationRequest) *ImmunizationPlan {
 	return &ImmunizationPlan{
-		Name:               req.Name,
-		CowType:            req.CowType,
-		Conditions:         req.Conditions,
-		Value:              int64(req.Value),
-		ImmunizationPlanId: int64(req.ImmunizationPlanId),
-		IsShow:             req.IsShow,
-		OperationId:        systemUser.Id,
-		OperationName:      systemUser.Name,
+		Name:                 req.Name,
+		CowType:              req.CowType,
+		Conditions:           req.Conditions,
+		Value:                int64(req.Value),
+		ImmunizationPlanId:   int64(req.ImmunizationPlanId),
+		ImmunizationPlanName: req.ImmunizationPlanName,
+		IsShow:               req.IsShow,
+		OperationId:          systemUser.Id,
+		OperationName:        systemUser.Name,
 	}
 }
 
@@ -54,18 +56,20 @@ func (i ImmunizationPlanSlice) ToPB(cowTypeOptions []*pasturePb.ConfigOptionsLis
 			conditionsName = cd.Label
 		}
 		res[d] = &pasturePb.ImmunizationRequest{
-			Id:             int32(v.Id),
-			Name:           v.Name,
-			CowType:        v.CowType,
-			CowTypeName:    cowTypeName,
-			Conditions:     v.Conditions,
-			ConditionsName: conditionsName,
-			Value:          int32(v.Value),
-			IsShow:         v.IsShow,
-			OperationId:    int32(v.OperationId),
-			OperationName:  v.OperationName,
-			CreatedAt:      int32(v.CreatedAt),
-			UpdatedAt:      int32(v.UpdatedAt),
+			Id:                   int32(v.Id),
+			Name:                 v.Name,
+			CowType:              v.CowType,
+			CowTypeName:          cowTypeName,
+			Conditions:           v.Conditions,
+			ConditionsName:       conditionsName,
+			Value:                int32(v.Value),
+			IsShow:               v.IsShow,
+			ImmunizationPlanId:   int32(v.ImmunizationPlanId),
+			ImmunizationPlanName: v.ImmunizationPlanName,
+			OperationId:          int32(v.OperationId),
+			OperationName:        v.OperationName,
+			CreatedAt:            int32(v.CreatedAt),
+			UpdatedAt:            int32(v.UpdatedAt),
 		}
 	}
 	return res

+ 15 - 15
model/same_time.go

@@ -10,19 +10,19 @@ import (
 )
 
 type SameTime struct {
-	Id                  int64                  `json:"id"`
-	Name                string                 `json:"name"`
-	WeekType            pasturePb.Week_Kind    `json:"weekType"`
-	CowType             pasturePb.CowType_Kind `json:"cowType"`
-	IsShow              pasturePb.IsShow_Kind  `json:"isShow"`
-	IsDelete            pasturePb.IsShow_Kind  `json:"isDelete"`
-	PostpartumDaysStart int32                  `json:"postpartumDaysStart"`
-	PostpartumDaysEnd   int32                  `json:"postpartumDaysEnd"`
-	CollateNodes        string                 `json:"collateNodes"`
-	Remarks             string                 `json:"remarks"`
-	OperationId         int64                  `json:"operationId"`
-	CreatedAt           int64                  `json:"createdAt"`
-	UpdatedAt           int64                  `json:"updatedAt"`
+	Id                  int64                          `json:"id"`
+	Name                string                         `json:"name"`
+	WeekType            pasturePb.Week_Kind            `json:"weekType"`
+	CowType             pasturePb.SameTimeCowType_Kind `json:"cowType"`
+	IsShow              pasturePb.IsShow_Kind          `json:"isShow"`
+	IsDelete            pasturePb.IsShow_Kind          `json:"isDelete"`
+	PostpartumDaysStart int32                          `json:"postpartumDaysStart"`
+	PostpartumDaysEnd   int32                          `json:"postpartumDaysEnd"`
+	CollateNodes        string                         `json:"collateNodes"`
+	Remarks             string                         `json:"remarks"`
+	OperationId         int64                          `json:"operationId"`
+	CreatedAt           int64                          `json:"createdAt"`
+	UpdatedAt           int64                          `json:"updatedAt"`
 }
 
 func (e *SameTime) TableName() string {
@@ -52,7 +52,7 @@ type SameTimeSlice []*SameTime
 
 func (e SameTimeSlice) ToPB(
 	weekMap map[pasturePb.Week_Kind]string,
-	cowTypeMap map[pasturePb.CowType_Kind]string,
+	sameTimeCowTypeMap map[pasturePb.SameTimeCowType_Kind]string,
 	systemUserList []*SystemUser,
 ) []*pasturePb.SearchSameTimeList {
 	res := make([]*pasturePb.SearchSameTimeList, len(e))
@@ -75,7 +75,7 @@ func (e SameTimeSlice) ToPB(
 			WeekType:            v.WeekType,
 			WeekName:            weekMap[v.WeekType],
 			CowType:             v.CowType,
-			CowTypeName:         cowTypeMap[v.CowType],
+			CowTypeName:         sameTimeCowTypeMap[v.CowType],
 			IsShow:              v.IsShow,
 			PostpartumDaysStart: v.PostpartumDaysStart,
 			PostpartumDaysEnd:   v.PostpartumDaysEnd,

+ 22 - 20
model/same_time_cow.go

@@ -1,33 +1,35 @@
 package model
 
-import (
-	"time"
-
-	pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
-)
+import pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
 
 type SameTimeCow struct {
-	Id               int64                         `json:"id"`
-	CowId            int64                         `json:"cowId"`
-	SameTimeId       int64                         `json:"sameTimeId"`
-	Status           pasturePb.SameTimeStatus_Kind `json:"status"`
-	NextSameTimeType pasturePb.SameTimeType_Kind   `json:"nextSameTimeType"`
-	NextSameTimeAt   int64                         `json:"nextSameTimeAt"`
-	StartAt          int64                         `json:"startAt"`
-	EndAt            int64                         `json:"endAt"`
-	CreatedAt        int64                         `json:"createdAt"`
-	UpdatedAt        int64                         `json:"updatedAt"`
+	Id             int64                         `json:"id"`
+	SameTimeId     int64                         `json:"sameTimeId"`
+	CowId          int64                         `json:"cowId"`
+	Lact           int32                         `json:"lact"`
+	SameTimeStatus pasturePb.SameTimeStatus_Kind `json:"sameTimeStatus"`
+	CreatedAt      int64                         `json:"createdAt"`
+	UpdatedAt      int64                         `json:"updatedAt"`
 }
 
 func (s *SameTimeCow) TableName() string {
 	return "same_time_cow"
 }
 
-func NewSameTimeCow(cowId, sameTimeId int64) *SameTimeCow {
+func NewSameTimeCow(cow *Cow, sameTime *SameTime) *SameTimeCow {
 	return &SameTimeCow{
-		CowId:      cowId,
-		SameTimeId: sameTimeId,
-		Status:     pasturePb.SameTimeStatus_No_Start,
-		StartAt:    time.Now().Unix(),
+		SameTimeId:     sameTime.Id,
+		CowId:          cow.Id,
+		Lact:           cow.Lact,
+		SameTimeStatus: pasturePb.SameTimeStatus_No_Start,
+	}
+}
+
+func NewSameTimeCowList(cowList []*Cow, sameTime *SameTime) []*SameTimeCow {
+	sameTimeCowList := make([]*SameTimeCow, 0)
+	for _, cow := range cowList {
+		sameTimeCowList = append(sameTimeCowList, NewSameTimeCow(cow, sameTime))
+
 	}
+	return sameTimeCowList
 }

+ 47 - 0
model/same_time_cow_list.go

@@ -0,0 +1,47 @@
+package model
+
+import (
+	pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
+)
+
+type SameTimeCowDetail struct {
+	Id            int64                       `json:"id"`
+	CowId         int64                       `json:"cowId"`
+	Lact          int32                       `json:"lact"`
+	PenId         int64                       `json:"penId"`
+	SameTimeId    int64                       `json:"sameTimeId"`
+	SameTimeType  pasturePb.SameTimeType_Kind `json:"sameTimeType"`
+	PlanDay       string                      `json:"planDay"`
+	EndDay        string                      `json:"endDay"`
+	RealityDay    string                      `json:"realityDay"`
+	Status        pasturePb.IsShow_Kind       `json:"status"`
+	DrugsId       int64                       `json:"drugsId"`
+	Unit          pasturePb.Unit_Kind         `json:"unit"`
+	Usage         int32                       `json:"usage"`
+	OperationId   int64                       `json:"operationId"`
+	OperationName string                      `json:"operationName"`
+	CreatedAt     int64                       `json:"createdAt"`
+	UpdatedAt     int64                       `json:"updatedAt"`
+}
+
+func (s *SameTimeCowDetail) TableName() string {
+	return "same_time_cow_detail"
+}
+
+func NewSameTimeCowDetailList(cowList []*Cow, sameTimeId int64, planTime string, sameTimeType pasturePb.SameTimeType_Kind) []*SameTimeCowDetail {
+	res := make([]*SameTimeCowDetail, len(cowList))
+	for i, cow := range cowList {
+		res[i] = &SameTimeCowDetail{
+			CowId:        cow.Id,
+			Lact:         cow.Lact,
+			PenId:        cow.PenId,
+			SameTimeId:   sameTimeId,
+			SameTimeType: sameTimeType,
+			Status:       pasturePb.IsShow_No,
+			PlanDay:      planTime,
+			EndDay:       planTime,
+		}
+	}
+
+	return res
+}

+ 0 - 50
model/work_order_calendar.go

@@ -1,50 +0,0 @@
-package model
-
-import (
-	"time"
-
-	pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
-)
-
-type WorkOrderCalendar struct {
-	Id           int64                       `json:"id"`
-	Name         string                      `json:"name"`
-	CalendarType pasturePb.CalendarType_Kind `json:"calendarType"`
-	Count        int32                       `json:"count"`
-	ShowDay      string                      `json:"showDay"`
-	IsShow       pasturePb.IsShow_Kind       `json:"isShow"`
-	Backup       string                      `json:"backup"`
-	CreatedAt    int64                       `json:"createdAt"`
-	UpdatedAt    int64                       `json:"updatedAt"`
-}
-
-func (w *WorkOrderCalendar) TableName() string {
-	return "work_order_calendar"
-}
-
-func NewWorkOrderCalendar(name string, calendarType pasturePb.CalendarType_Kind, count int32) *WorkOrderCalendar {
-	return &WorkOrderCalendar{
-		Name:         name,
-		Count:        count,
-		CalendarType: calendarType,
-		ShowDay:      time.Now().Format(LayoutDate2),
-		IsShow:       pasturePb.IsShow_Ok,
-	}
-}
-
-type WorkOrderCalendarSlice []*WorkOrderCalendar
-
-func (w WorkOrderCalendarSlice) ToPB() []*pasturePb.WorkOrderCalendar {
-	res := make([]*pasturePb.WorkOrderCalendar, len(w))
-	for i, v := range w {
-		res[i] = &pasturePb.WorkOrderCalendar{
-			Id:           int32(v.Id),
-			Name:         v.Name,
-			CalendarType: v.CalendarType,
-			Count:        v.Count,
-			ShowDay:      v.ShowDay,
-			Backup:       v.Backup,
-		}
-	}
-	return res
-}

+ 6 - 2
model/work_order_master.go

@@ -4,6 +4,9 @@ import (
 	"encoding/json"
 	"fmt"
 
+	"gitee.com/xuyiping_admin/pkg/logger/zaplog"
+	"go.uber.org/zap"
+
 	"kpt-pasture/config"
 	"kpt-pasture/http/util"
 	"strconv"
@@ -113,8 +116,9 @@ func NewTaskWorkOrderPayload(id int64, execTime time.Duration) *asynq.Task {
 		WorkOrderId: id,
 	})
 	processAt := time.Now().Add(execTime).Unix()
-
-	return asynq.NewTask(fmt.Sprintf("%s:%s", config.Options().FarmName, TaskWorkOrder), payload, NewTaskWorkOrderOption(processAt)...)
+	// todo 测试用
+	zaplog.Info("NewTaskWorkOrderPayload", zap.Any("config", config.Options()))
+	return asynq.NewTask(fmt.Sprintf("xdmy1:%s", TaskWorkOrder), payload, NewTaskWorkOrderOption(processAt)...)
 }
 
 type WorkOrderMasterSlice []*WorkOrderMaster

+ 59 - 0
module/backend/calendar.go

@@ -0,0 +1,59 @@
+package backend
+
+import (
+	"context"
+	"kpt-pasture/model"
+	"net/http"
+	"time"
+
+	pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
+	"gitee.com/xuyiping_admin/pkg/xerr"
+)
+
+func (s *StoreEntry) CalendarList(ctx context.Context, req *pasturePb.CalendarRequest) (*pasturePb.CalendarResponse, error) {
+	calendarList := make([]*model.Calendar, 0)
+	if err := s.DB.Model(&model.Calendar{}).
+		Where("show_day >= ?", req.ShowStartDay).
+		Where("show_day <= ?", req.ShowEndDay).
+		Where("is_show = ?", pasturePb.IsShow_Ok).
+		Find(&calendarList).Error; err != nil {
+		return nil, xerr.WithStack(err)
+	}
+	return &pasturePb.CalendarResponse{
+		Code:    http.StatusOK,
+		Message: "ok",
+		Data:    model.CalendarSlice(calendarList).ToPB(),
+	}, nil
+}
+
+func (s *StoreEntry) CalendarTableDetail(ctx context.Context, req *pasturePb.CalendarTableRequest) (interface{}, error) {
+
+	if req.Start != time.Now().Format(model.LayoutDate2) {
+		return nil, xerr.New("参数错误")
+	}
+
+	newCalendar := &model.Calendar{}
+	if err := s.DB.Model(&model.Calendar{}).
+		Where("calendar_type = ?", req.CalendarType).
+		Where("show_day = ?", req.Start).
+		Where("is_show = ?", pasturePb.IsShow_Ok).
+		First(newCalendar).Error; err != nil {
+		return nil, xerr.WithStack(err)
+	}
+
+	if newCalendar.Id == 0 {
+		return nil, xerr.New("不存在该日历数据")
+	}
+
+	switch newCalendar.CalendarType {
+	case pasturePb.CalendarType_Immunisation:
+	case pasturePb.CalendarType_PG:
+	case pasturePb.CalendarType_RnGH:
+	case pasturePb.CalendarType_Pregnancy_Check:
+	case pasturePb.CalendarType_WorkOrder:
+	case pasturePb.CalendarType_Weaning:
+	case pasturePb.CalendarType_Treatment:
+	}
+
+	return nil, nil
+}

+ 15 - 6
module/backend/config_data.go

@@ -14,11 +14,11 @@ func (s *StoreEntry) BarnTypeEnumList() []*pasturePb.ConfigOptionsList {
 	barnTypeList := make([]*pasturePb.ConfigOptionsList, 0)
 	barnTypeList = append(barnTypeList, &pasturePb.ConfigOptionsList{
 		Value:    int32(pasturePb.PenType_Lactating_Calves),
-		Label:    "哺乳牛舍",
+		Label:    "哺乳牛舍",
 		Disabled: true,
 	}, &pasturePb.ConfigOptionsList{
 		Value:    int32(pasturePb.PenType_Weaned_Calves),
-		Label:    "断奶牛舍",
+		Label:    "断奶牛舍",
 		Disabled: true,
 	}, &pasturePb.ConfigOptionsList{
 		Value:    int32(pasturePb.PenType_Youth),
@@ -48,7 +48,12 @@ func (s *StoreEntry) BarnTypeEnumList() []*pasturePb.ConfigOptionsList {
 		Value:    int32(pasturePb.PenType_Eliminate),
 		Label:    "淘汰牛舍",
 		Disabled: true,
+	}, &pasturePb.ConfigOptionsList{
+		Value:    int32(pasturePb.PenType_Segregate),
+		Label:    "隔离牛舍",
+		Disabled: true,
 	})
+
 	return barnTypeList
 }
 
@@ -167,14 +172,14 @@ func (s *StoreEntry) CowTypeEnumList() []*pasturePb.ConfigOptionsList {
 	return cowTypeList
 }
 
-func (s *StoreEntry) SemeTimeCowTypeEnumList() []*pasturePb.ConfigOptionsList {
+func (s *StoreEntry) SameTimeCowTypeEnumList() []*pasturePb.ConfigOptionsList {
 	cowTypeList := make([]*pasturePb.ConfigOptionsList, 0)
 	cowTypeList = append(cowTypeList, &pasturePb.ConfigOptionsList{
-		Value:    int32(pasturePb.CowType_Reserve_Calf),
-		Label:    "后备牛",
+		Value:    int32(pasturePb.SameTimeCowType_Empty),
+		Label:    "空怀牛",
 		Disabled: true,
 	}, &pasturePb.ConfigOptionsList{
-		Value:    int32(pasturePb.CowType_Breeding_Calf),
+		Value:    int32(pasturePb.SameTimeCowType_Breeding_Calf),
 		Label:    "种母牛",
 		Disabled: true,
 	})
@@ -742,6 +747,10 @@ func CalendarTypeEnumList() []*pasturePb.ConfigOptionsList {
 		Value:    int32(pasturePb.CalendarType_Treatment),
 		Label:    "治疗",
 		Disabled: true,
+	}, &pasturePb.ConfigOptionsList{
+		Value:    int32(pasturePb.CalendarType_Mating),
+		Label:    "配种",
+		Disabled: true,
 	})
 	return configOptions
 }

+ 8 - 0
module/backend/enum_map.go

@@ -114,6 +114,14 @@ func (s *StoreEntry) WorkOrderPriorityMap() map[pasturePb.Priority_Kind]string {
 	return res
 }
 
+func (s *StoreEntry) SameTimeCowTypeMap() map[pasturePb.SameTimeCowType_Kind]string {
+	res := make(map[pasturePb.SameTimeCowType_Kind]string)
+	for _, v := range s.SameTimeCowTypeEnumList() {
+		res[pasturePb.SameTimeCowType_Kind(v.Value)] = v.Label
+	}
+	return res
+}
+
 func CalendarTypeMap() map[pasturePb.CalendarType_Kind]string {
 	res := make(map[pasturePb.CalendarType_Kind]string)
 	for _, v := range CalendarTypeEnumList() {

+ 1 - 1
module/backend/enum_options.go

@@ -150,7 +150,7 @@ func (s *StoreEntry) SystemBaseConfigOptions(ctx context.Context, optionsName st
 		"frozenSemenType":        s.FrozenSemenTypeEnumList,
 		"week":                   s.WeekEnumList,
 		"month":                  s.MonthEnumList,
-		"sameTimeCowType":        s.SemeTimeCowTypeEnumList,
+		"sameTimeCowType":        s.SameTimeCowTypeEnumList,
 		"sameTimeType":           s.SameTimeTypeEnumList,
 		"immunizationCowType":    s.ImmunizationCowTypeEnumList,
 		"workOrderFrequency":     s.WorkOrderFrequencyEnumList,

+ 7 - 24
module/backend/event_breed.go

@@ -9,9 +9,6 @@ import (
 	"strings"
 	"time"
 
-	"gitee.com/xuyiping_admin/pkg/logger/zaplog"
-	"go.uber.org/zap"
-
 	pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
 	"gitee.com/xuyiping_admin/pkg/xerr"
 	"gorm.io/gorm"
@@ -487,12 +484,11 @@ func (s *StoreEntry) FrozenSemenCreate(ctx context.Context, req *pasturePb.Searc
 }
 
 func (s *StoreEntry) SameTimeCreate(ctx context.Context, req *pasturePb.EventSameTime) error {
-	sameTime, err := s.GetSameTimeById(ctx, int64(req.SameTimeId))
+	/*sameTime, err := s.GetSameTimeById(ctx, int64(req.SameTimeId))
 	if err != nil {
 		return xerr.WithStack(err)
 	}
 
-	zaplog.Info("SameTimeCreate", zap.Any("sameTime", sameTime), zap.Any("req", req))
 	cowList, err := s.ParseCowIds(ctx, req.CowId)
 	if err != nil {
 		return xerr.WithStack(err)
@@ -500,28 +496,15 @@ func (s *StoreEntry) SameTimeCreate(ctx context.Context, req *pasturePb.EventSam
 
 	drugs := &model.Drugs{}
 	if req.DrugsId > 0 {
-		drugs, err = s.GetDrugsById(ctx, int64(req.DrugsId))
-		if err != nil {
-			zaplog.Error("SameTimeCreate", zap.Any("GetDrugsById", err), zap.Any("req", req))
+		if drugs, err = s.GetDrugsById(ctx, int64(req.DrugsId)); err != nil {
+			return xerr.WithStack(err)
 		}
 	}
 
+	newSameTimeCowList := model.NewSameTimeCowList(cowList, sameTime)
+
 	if err = s.DB.Transaction(func(tx *gorm.DB) error {
-		eventSameTimeList := make([]*model.EventSameTime, 0)
-		for _, cow := range cowList {
-			eventSameTimeList = append(eventSameTimeList, model.NewEventSameTime(cow, req, drugs))
-			// sameTimeCow 不存在时创建
-			if err = tx.Where("same_time_id = ? ", sameTime.Id).
-				Where("cow_id = ?", cow.Id).
-				Where("lact = ?", cow.Lact).
-				First(new(model.SameTimeCow)).Error; err != nil {
-				if errors.Is(err, gorm.ErrRecordNotFound) {
-					if err = tx.Create(model.NewSameTimeCow(cow.Id, sameTime.Id)).Error; err != nil {
-						return xerr.WithStack(err)
-					}
-				}
-			}
-		}
+
 		if err = tx.Create(eventSameTimeList).Error; err != nil {
 			return xerr.WithStack(err)
 		}
@@ -529,7 +512,7 @@ func (s *StoreEntry) SameTimeCreate(ctx context.Context, req *pasturePb.EventSam
 		return nil
 	}); err != nil {
 		return xerr.WithStack(err)
-	}
+	}*/
 
 	return nil
 }

+ 2 - 1
module/backend/interface.go

@@ -198,5 +198,6 @@ type WorkService interface {
 	OrderIsShow(ctx context.Context, id int64) error
 	UserWorkOrderList(ctx context.Context, workOrderStatus pasturePb.WorkOrderStatus_Kind, pagination *pasturePb.PaginationModel) (*pasturePb.UserWorkOrderResponse, error)
 
-	CalendarList(ctx context.Context, req *pasturePb.WorkOrderCalendarRequest) (*pasturePb.WorkOrderCalendarResponse, error)
+	CalendarList(ctx context.Context, req *pasturePb.CalendarRequest) (*pasturePb.CalendarResponse, error)
+	CalendarTableDetail(ctx context.Context, req *pasturePb.CalendarTableRequest) (interface{}, error)
 }

+ 20 - 10
module/backend/prescription.go

@@ -52,13 +52,13 @@ func (s *StoreEntry) SearchSameTimeList(ctx context.Context, req *pasturePb.Sear
 	}
 
 	weekMap := s.WeekMap()
-	cowTypeMap := s.CowTypeMap()
+	sameTimeCowTypeMap := s.SameTimeCowTypeMap()
 	systemUser, _ := s.SystemUserList(ctx)
 	return &pasturePb.SameTimeResponse{
 		Code:    http.StatusOK,
 		Message: "ok",
 		Data: &pasturePb.SearchSameTimeData{
-			List:     model.SameTimeSlice(semeTimeList).ToPB(weekMap, cowTypeMap, systemUser),
+			List:     model.SameTimeSlice(semeTimeList).ToPB(weekMap, sameTimeCowTypeMap, systemUser),
 			Total:    int32(count),
 			PageSize: pagination.PageSize,
 			Page:     pagination.Page,
@@ -367,6 +367,15 @@ func (s *StoreEntry) CreatedOrUpdateImmunization(ctx context.Context, req *pastu
 		err          error
 		systemUser   *model.SystemUser
 	)
+
+	if req.ImmunizationPlanId > 0 {
+		otherImmunization, err := s.GetImmunizationById(ctx, int64(req.ImmunizationPlanId))
+		if err != nil {
+			return xerr.WithStack(err)
+		}
+		req.ImmunizationPlanName = otherImmunization.Name
+	}
+
 	if req.Id > 0 {
 		immunization, err = s.GetImmunizationById(ctx, int64(req.Id))
 		if err != nil {
@@ -381,14 +390,15 @@ func (s *StoreEntry) CreatedOrUpdateImmunization(ctx context.Context, req *pastu
 	if err = s.DB.Model(&model.ImmunizationPlan{}).Where(map[string]interface{}{
 		"id": req.Id,
 	}).Assign(map[string]interface{}{
-		"name":                 immunization.Name,
-		"cow_type":             immunization.CowType,
-		"conditions":           immunization.Conditions,
-		"value":                immunization.Value,
-		"immunization_plan_id": immunization.ImmunizationPlanId,
-		"is_show":              immunization.IsShow,
-		"operation_id":         immunization.OperationId,
-		"operation_name":       immunization.OperationName,
+		"name":                   immunization.Name,
+		"cow_type":               immunization.CowType,
+		"conditions":             immunization.Conditions,
+		"value":                  immunization.Value,
+		"immunization_plan_id":   immunization.ImmunizationPlanId,
+		"immunization_plan_name": immunization.ImmunizationPlanName,
+		"is_show":                immunization.IsShow,
+		"operation_id":           immunization.OperationId,
+		"operation_name":         immunization.OperationName,
 	}).FirstOrCreate(&model.ImmunizationPlan{}).Error; err != nil {
 		return xerr.WithStack(err)
 	}

+ 0 - 16
module/backend/work.go

@@ -285,19 +285,3 @@ func (s *StoreEntry) UserWorkOrderList(ctx context.Context, workOrderStatus past
 		},
 	}, nil
 }
-
-func (s *StoreEntry) CalendarList(ctx context.Context, req *pasturePb.WorkOrderCalendarRequest) (*pasturePb.WorkOrderCalendarResponse, error) {
-	calendarList := make([]*model.WorkOrderCalendar, 0)
-	if err := s.DB.Model(&model.WorkOrderCalendar{}).
-		Where("show_day >= ?", req.ShowStartDay).
-		Where("show_day <= ?", req.ShowEndDay).
-		Where("is_show = ?", pasturePb.IsShow_Ok).
-		Find(&calendarList).Error; err != nil {
-		return nil, xerr.WithStack(err)
-	}
-	return &pasturePb.WorkOrderCalendarResponse{
-		Code:    http.StatusOK,
-		Message: "ok",
-		Data:    model.WorkOrderCalendarSlice(calendarList).ToPB(),
-	}, nil
-}

+ 92 - 14
module/crontab/cow_cron.go

@@ -1,8 +1,10 @@
 package crontab
 
 import (
+	"context"
 	"fmt"
 	"kpt-pasture/model"
+	"kpt-pasture/util"
 	"time"
 
 	pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
@@ -11,6 +13,35 @@ import (
 	"go.uber.org/zap"
 )
 
+const (
+	UpdateCowInfo    = "UpdateCowInfo"
+	ImmunizationPlan = "ImmunizationPlan"
+	SameTimePlan     = "SameTimePlan"
+)
+
+// GenerateAsynqWorkOrder 异步生成工作单
+func (e *Entry) GenerateAsynqWorkOrder() error {
+	workOrderList := make([]*model.WorkOrderMaster, 0)
+	if err := e.DB.Where("is_show = ?", pasturePb.IsShow_Ok).Find(&workOrderList).Error; err != nil {
+		return err
+	}
+	for _, workOrder := range workOrderList {
+		timeUnix, err := util.ConvertParseLocalUnix(workOrder.ExecTime)
+		if timeUnix <= 0 || err != nil {
+			zaplog.Error("crontab", zap.Any("GenerateWorkOrder", err), zap.Any("execTime", workOrder.ExecTime))
+			continue
+		}
+		execTime := time.Now().Unix() - timeUnix
+
+		task := model.NewTaskWorkOrderPayload(workOrder.Id, time.Duration(execTime)*time.Second)
+		zaplog.Info("GenerateWorkOrder", zap.Any("workOrder", workOrder), zap.Any("task", task))
+		if _, err = e.AsynqClient.CtxEnqueue(context.Background(), task); err != nil {
+			zaplog.Error("PushMessage CtxEnqueue", zap.Any("Err", err))
+		}
+	}
+	return nil
+}
+
 // UpdateCowInfo 牛只基本信息维护
 func (e *Entry) UpdateCowInfo() error {
 	cowList := make([]*model.Cow, 0)
@@ -18,9 +49,12 @@ func (e *Entry) UpdateCowInfo() error {
 		return err
 	}
 
-	if ok := e.CreateCrontabLog("ImmunizationPlan"); !ok {
+	if ok := e.IsExistCrontabLog(UpdateCowInfo); !ok {
 		return nil
 	}
+	defer func() {
+		e.CreateCrontabLog(UpdateCowInfo)
+	}()
 
 	for _, cow := range cowList {
 		dayAge := cow.GetDayAge()
@@ -41,7 +75,7 @@ func (e *Entry) UpdateCowInfo() error {
 
 // ImmunizationPlan 免疫计划,生成工作单
 func (e *Entry) ImmunizationPlan() error {
-	if ok := e.CreateCrontabLog("ImmunizationPlan"); !ok {
+	if ok := e.IsExistCrontabLog(ImmunizationPlan); !ok {
 		return nil
 	}
 
@@ -52,7 +86,13 @@ func (e *Entry) ImmunizationPlan() error {
 
 	var todayCount int32 = 0
 	defer func() {
+		var count int64 = 0
+		if err := e.DB.Model(new(model.ImmunizationPlanCow)).Where("status = ?", pasturePb.IsShow_Ok).Count(&count).Error; err != nil {
+			zaplog.Error("Crontab", zap.Any("ImmunizationPlanDefer", err))
+		}
+		todayCount += int32(count)
 		e.CreatedWorkOrderCalendar(pasturePb.CalendarType_Immunisation, todayCount)
+		e.CreateCrontabLog(ImmunizationPlan)
 	}()
 
 	for _, plan := range planList {
@@ -100,12 +140,13 @@ func (e *Entry) ImmunizationPlan() error {
 			zaplog.Error("ImmunizationPlan", zap.Any("CreateImmunizationPlanCow", err), zap.Any("plan", plan), zap.Any("cowList", cowList))
 		}
 	}
+
 	return nil
 }
 
 // SameTimePlan 同期计划,生成工作单
 func (e *Entry) SameTimePlan() error {
-	if ok := e.CreateCrontabLog("ImmunizationPlan"); !ok {
+	if ok := e.IsExistCrontabLog(SameTimePlan); !ok {
 		return nil
 	}
 
@@ -114,32 +155,69 @@ func (e *Entry) SameTimePlan() error {
 		return xerr.WithStack(err)
 	}
 
-	pref := e.DB.Select("id").
-		Where("is_remove = ?", pasturePb.IsShow_Ok).
-		Where("is_pregnant = ?", pasturePb.IsShow_No)
-
+	// 更新日历里面的数据
 	var todayCount int32 = 0
 	defer func() {
 		e.CreatedWorkOrderCalendar(pasturePb.CalendarType_Immunisation, todayCount)
+		e.CreateCrontabLog(SameTimePlan)
 	}()
 
-	for _, plan := range sameTimeList {
+	currWeek := time.Now().Weekday()
+	for _, sameTime := range sameTimeList {
+		if sameTime == nil {
+			continue
+		}
+
+		if time.Weekday(sameTime.WeekType) != currWeek {
+			continue
+		}
+
 		cowList := make([]*model.Cow, 0)
-		pref.Where("calving_age >= ?", plan.PostpartumDaysStart).
-			Where("calving_age <= ?", plan.PostpartumDaysEnd)
+		pref := e.DB.Where("is_remove = ?", pasturePb.IsShow_Ok)
+
+		if sameTime.CowType == pasturePb.SameTimeCowType_Breeding_Calf {
+			pref.Where("calving_age >= ?", sameTime.PostpartumDaysStart).
+				Where("calving_age <= ?", sameTime.PostpartumDaysEnd).
+				Where("is_pregnant = ?", pasturePb.IsShow_No)
+		}
+
+		if sameTime.CowType == pasturePb.SameTimeCowType_Empty {
+			pref.Where(
+				e.DB.Where("breed_status = ?", pasturePb.BreedStatus_Empty).
+					Or("breed_status = ?", pasturePb.BreedStatus_Abort),
+			).Where("s_pregnant = ?", pasturePb.IsShow_No)
+		}
+
 		if err := pref.Find(&cowList).Error; err != nil {
-			zaplog.Error("crontab", zap.Any("SameTimePlan", err), zap.Any("plan", plan))
+			zaplog.Error("crontab", zap.Any("SameTimePlan", err), zap.Any("plan", sameTime))
 			return xerr.WithStack(err)
 		}
 
 		if len(cowList) <= 0 {
 			continue
 		}
-		todayCount += int32(len(cowList))
-		if err := e.GenerateCalendarBySameTimePlan(cowList, plan); err != nil {
-			zaplog.Error("crontab", zap.Any("GenerateCalendarBySameTimePlan", err), zap.Any("cowList", cowList), zap.Any("plan", plan))
+
+		currCount, err := e.GenerateCalendarBySameTimePlan(cowList, sameTime)
+		if err != nil {
+			zaplog.Error("crontab",
+				zap.Any("GenerateCalendarBySameTimePlan", err),
+				zap.Any("cowList", cowList),
+				zap.Any("plan", sameTime),
+			)
 			continue
 		}
+		todayCount += currCount
 	}
 	return nil
 }
+
+// PregnancyCheck 妊娠期检查
+func (e *Entry) PregnancyCheck() error {
+
+	return nil
+}
+
+// DiseaseCheck 疾病检查
+func (e *Entry) DiseaseCheck() error {
+	return nil
+}

+ 38 - 14
module/crontab/other.go

@@ -1,7 +1,6 @@
 package crontab
 
 import (
-	"errors"
 	"kpt-pasture/model"
 	"kpt-pasture/module/backend"
 	"time"
@@ -10,29 +9,54 @@ import (
 	"go.uber.org/zap"
 
 	pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
-
-	"gorm.io/gorm"
 )
 
-// CreateCrontabLog 生成日志记录
-func (e *Entry) CreateCrontabLog(name string) bool {
+// IsExistCrontabLog 定时任务今日是否已经执行过
+func (e *Entry) IsExistCrontabLog(name string) bool {
 	currDateTime := time.Now().Format(model.LayoutDate2)
-	newCronLog := &model.CronLog{}
-	if err := e.DB.Where("name = ?", name).
-		Where("date = ?", currDateTime).First(newCronLog).Error; err != nil {
-		if errors.Is(err, gorm.ErrRecordNotFound) {
-			e.DB.Create(model.NewCronLog(name))
-			return true
-		}
+	var count int64 = 0
+	if err := e.DB.Model(&model.CronLog{}).Where("name = ?", name).
+		Where("date = ?", currDateTime).Count(&count).Error; err != nil {
+		zaplog.Error("CreateCrontabLog", zap.Any("err", err), zap.String("name", name))
+		return false
+	}
+	if count > 0 {
+		return true
 	}
 	return false
 }
 
+func (e *Entry) CreateCrontabLog(name string) {
+	crontabLog := model.NewCronLog(name)
+	if err := e.DB.Model(&model.CronLog{}).Create(crontabLog).Error; err != nil {
+		zaplog.Error("CreateCrontabLog", zap.Any("err", err), zap.String("name", name))
+	}
+}
+
 // CreatedWorkOrderCalendar 创建当天工单日历记录
 func (e *Entry) CreatedWorkOrderCalendar(calendarType pasturePb.CalendarType_Kind, count int32) {
 	calendarTypeName := backend.CalendarTypeMap()[calendarType]
-	workOrderCalendar := model.NewWorkOrderCalendar(calendarTypeName, calendarType, count)
-	if err := e.DB.Model(&model.WorkOrderCalendar{}).Create(workOrderCalendar).Error; err != nil {
+	workOrderCalendar := model.NewCalendar(calendarTypeName, calendarType, count)
+	if err := e.DB.Model(&model.Calendar{}).Create(workOrderCalendar).Error; err != nil {
 		zaplog.Error("CreatedWorkOrderCalendar", zap.Any("err", err), zap.Any("workOrderCalendar", workOrderCalendar))
 	}
 }
+
+func (e *Entry) IsExistSameTimeCow(cow *model.Cow, sameTime *model.SameTime) bool {
+	var count int64 = 0
+	if err := e.DB.Model(&model.SameTimeCow{}).
+		Where("cow_id = ?", cow.Id).
+		Where("lact = ?", cow.Lact).
+		Where("same_time_id = ?", sameTime.Id).
+		Where("status != ?", pasturePb.SameTimeStatus_End).
+		Count(&count).Error; err != nil {
+		zaplog.Error("IsExistSameTimeCow", zap.Any("err", err), zap.Any("cow", cow), zap.Any("sameTime", sameTime))
+		return false
+	}
+
+	if count > 0 {
+		return true
+	}
+	return false
+
+}

+ 49 - 91
module/crontab/work_cron.go

@@ -1,12 +1,9 @@
 package crontab
 
 import (
-	"context"
 	"encoding/json"
-	"errors"
 	"kpt-pasture/model"
 	"kpt-pasture/module/backend"
-	"kpt-pasture/util"
 	"time"
 
 	"gorm.io/gorm"
@@ -19,46 +16,23 @@ import (
 	pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
 )
 
-// GenerateAsynqWorkOrder 异步生成工作单
-func (e *Entry) GenerateAsynqWorkOrder() error {
-	workOrderList := make([]*model.WorkOrderMaster, 0)
-	if err := e.DB.Where("is_show = ?", pasturePb.IsShow_Ok).Find(&workOrderList).Error; err != nil {
-		return err
-	}
-	for _, workOrder := range workOrderList {
-		timeUnix, err := util.ConvertParseLocalUnix(workOrder.ExecTime)
-		if timeUnix <= 0 || err != nil {
-			zaplog.Error("crontab", zap.Any("GenerateWorkOrder", err), zap.Any("execTime", workOrder.ExecTime))
-			continue
-		}
-		execTime := time.Now().Unix() - timeUnix
-
-		task := model.NewTaskWorkOrderPayload(workOrder.Id, time.Duration(execTime)*time.Second)
-		zaplog.Info("GenerateWorkOrder", zap.Any("workOrder", workOrder), zap.Any("task", task))
-		if _, err = e.AsynqClient.CtxEnqueue(context.Background(), task); err != nil {
-			zaplog.Error("PushMessage CtxEnqueue", zap.Any("Err", err))
-		}
-	}
-	return nil
-}
-
-// GenerateCalendarBySameTimePlan 生成同期计划工作单
-func (e *Entry) GenerateCalendarBySameTimePlan(cowList []*model.Cow, sameTime *model.SameTime) error {
+// GenerateCalendarBySameTimePlan 生成同期计划的牛只
+func (e *Entry) GenerateCalendarBySameTimePlan(cowList []*model.Cow, sameTime *model.SameTime) (int32, error) {
 	if len(cowList) <= 0 {
-		return nil
+		return 0, nil
 	}
 
-	cowSameTimeList := make([]*model.SameTimeCow, 0)
+	newCowList := make([]*model.Cow, 0)
 	for _, cow := range cowList {
-		newCowSameTime, err := e.createNewCowSameTime(cow, sameTime)
-		if err != nil {
-			zaplog.Error("crontab", zap.Any("GenerateCalendarBySameTimePlan", err), zap.Any("cow", cow))
+		if ok := e.IsExistSameTimeCow(cow, sameTime); ok {
+			zaplog.Info("GenerateCalendarBySameTimePlan", zap.Any("sameTime", sameTime), zap.Any("cow", cow))
+			continue
 		}
-		cowSameTimeList = append(cowSameTimeList, newCowSameTime)
+		newCowList = append(newCowList, cow)
 	}
 
-	calendarName := backend.CalendarTypeMap()[pasturePb.CalendarType_Immunisation]
-	workOrderCalendarList := make([]*model.WorkOrderCalendar, 0)
+	calendarList := make([]*model.Calendar, 0)
+	newSameTimeCowDetailList := make([]*model.SameTimeCowDetail, 0)
 	if len(sameTime.CollateNodes) > 0 {
 		collateNodes := make([]*pasturePb.CollateNode, 0)
 		var _ = json.Unmarshal([]byte(sameTime.CollateNodes), &collateNodes)
@@ -69,69 +43,59 @@ func (e *Entry) GenerateCalendarBySameTimePlan(cowList []*model.Cow, sameTime *m
 				showDay = nowTime.Add(time.Hour * 24 * time.Duration(collateNode.NextNodeDay)).Format(model.LayoutDate2)
 			}
 
-			histCount := e.GetTowardSameTimeCowSum(sameTime.Id, showDay)
-			workOrderCalendarList = append(workOrderCalendarList, &model.WorkOrderCalendar{
+			calendarName := backend.CalendarTypeMap()[pasturePb.CalendarType_PG]
+			calendarType := pasturePb.CalendarType_PG
+			if collateNode.SameTimeType == pasturePb.SameTimeType_RnGH {
+				calendarName = backend.CalendarTypeMap()[pasturePb.CalendarType_RnGH]
+				calendarType = pasturePb.CalendarType_RnGH
+			}
+
+			if collateNode.SameTimeType == pasturePb.SameTimeType_TAI {
+				calendarName = backend.CalendarTypeMap()[pasturePb.CalendarType_Mating]
+				calendarType = pasturePb.CalendarType_Mating
+			}
+
+			histCount := e.GetTowardSameTimeCowSum(sameTime.Id, collateNode.SameTimeType)
+			calendarList = append(calendarList, &model.Calendar{
 				Name:         calendarName,
-				CalendarType: pasturePb.CalendarType_Immunisation,
-				Count:        int32(len(cowSameTimeList)) + int32(histCount),
+				CalendarType: calendarType,
+				Count:        int32(len(newCowList)) + int32(histCount),
 				ShowDay:      showDay,
 				IsShow:       pasturePb.IsShow_Ok,
 			})
+			newSameTimeCowDetailList = append(
+				newSameTimeCowDetailList,
+				model.NewSameTimeCowDetailList(newCowList, sameTime.Id, showDay, collateNode.SameTimeType)...,
+			)
 		}
 	}
 
+	newSameTimeCowList := model.NewSameTimeCowList(newCowList, sameTime)
+
 	if err := e.DB.Transaction(func(tx *gorm.DB) error {
-		// 创建新的牛只同期计划详情
-		if err := tx.Create(cowSameTimeList).Error; err != nil {
+		// 创建牛只同期日历表
+		if err := tx.Create(calendarList).Error; err != nil {
 			return xerr.WithStack(err)
 		}
-		for _, v := range workOrderCalendarList {
-			if err := tx.Model(&model.WorkOrderCalendar{}).Where(map[string]interface{}{
-				"calendar_type": v.CalendarType,
-				"show_day":      v.ShowDay,
-			}).Assign(map[string]interface{}{
-				"name":          v.Name,
-				"calendar_type": v.CalendarType,
-				"count":         v.Count,
-				"show_day":      v.ShowDay,
-				"is_show":       v.IsShow,
-			}).FirstOrCreate(&model.Pen{}).Error; err != nil {
-				return xerr.WithStack(err)
-			}
+
+		// 创建牛只同期总表
+		if err := tx.Create(newSameTimeCowList).Error; err != nil {
+			return xerr.WithStack(err)
 		}
 
+		if err := tx.Create(newSameTimeCowDetailList).Error; err != nil {
+			return xerr.WithStack(err)
+		}
 		return nil
 	}); err != nil {
-		return xerr.WithStack(err)
+		return 0, xerr.WithStack(err)
 	}
 
-	return nil
+	return int32(len(newCowList)), nil
 }
 
-func (e *Entry) createNewCowSameTime(cow *model.Cow, sameTime *model.SameTime) (*model.SameTimeCow, error) {
-	cowSameTime := &model.SameTimeCow{}
-	if err := e.DB.Where("cow_id = ?", cow.Id).
-		Where("lact = ?", cow.Lact).
-		Where("same_time_id = ?", sameTime.Id).
-		First(cowSameTime).Error; err != nil {
-		if errors.Is(err, gorm.ErrRecordNotFound) {
-			return &model.SameTimeCow{
-				CowId:      cow.Id,
-				SameTimeId: sameTime.Id,
-				Status:     pasturePb.SameTimeStatus_No_Start,
-				StartAt:    time.Now().Unix(),
-				EndAt:      0,
-			}, nil
-		} else {
-			zaplog.Error("crontab", zap.Error(err), zap.Any("GenerateCalendarBySameTimePlan", "error"), zap.Any("cow", cow.Id), zap.Any("lact", cow.Lact))
-			return nil, xerr.WithStack(err)
-		}
-	}
-	return cowSameTime, nil
-}
-
-func (e *Entry) getWorkOrderCalendar(name string) []*model.WorkOrderCalendar {
-	res := make([]*model.WorkOrderCalendar, 0)
+func (e *Entry) getWorkOrderCalendar(name string) []*model.Calendar {
+	res := make([]*model.Calendar, 0)
 	if err := e.DB.Where("name = ?", name).
 		Where("is_show = ?", pasturePb.IsShow_Ok).
 		Find(&res).Error; err != nil {
@@ -141,20 +105,14 @@ func (e *Entry) getWorkOrderCalendar(name string) []*model.WorkOrderCalendar {
 }
 
 // GetTowardSameTimeCowSum 获取历史未打激素牛只总数量
-func (e *Entry) GetTowardSameTimeCowSum(sameTimeId int64, showDay string) int64 {
+func (e *Entry) GetTowardSameTimeCowSum(sameTimeId int64, sameTimeType pasturePb.SameTimeType_Kind) int64 {
 	res := int64(0)
-	if err := e.DB.Model(&model.SameTimeCow{}).
-		Where("status = ?", pasturePb.IsShow_Ok).
+	if err := e.DB.Model(&model.SameTimeCowDetail{}).
+		Where("status = ?", pasturePb.IsShow_No).
 		Where("same_time_id = ?", sameTimeId).
-		Where("show_day = ?", showDay).
+		Where("same_time_type = ?", sameTimeType).
 		Count(&res).Error; err != nil {
 		zaplog.Error("GetTowardSameTimeCowSum", zap.Any("err", err))
 	}
 	return res
 }
-
-// PregnancyCheck 妊娠期检查
-func (e *Entry) PregnancyCheck() error {
-
-	return nil
-}