Kaynağa Gözat

sameTime: 同期和日历优化

Yi 6 ay önce
ebeveyn
işleme
efcabb0188

+ 1 - 13
cmd/consumer.go

@@ -13,22 +13,10 @@ import (
 var ConsumerCmd = &cobra.Command{
 	Use:   "consumer",
 	Short: "start consumer",
-	PersistentPreRun: func(cmd *cobra.Command, args []string) {
-
-	},
-}
-
-func init() {
-	ConsumerCmd.AddCommand(workOrder)
-}
-
-var workOrder = &cobra.Command{
-	Use:   "workOrder",
-	Short: "kpt pasture work order",
 	Run: func(cmd *cobra.Command, args []string) {
 		srv := dep.DIAsynqWorkOrder()
 		if err := srv.Server.Run(srv.Mux); err != nil {
-			zaplog.Error("eventWorkflow", zap.Any("err", err))
+			zaplog.Error("consumer", zap.Any("err", err))
 		}
 	},
 }

+ 0 - 2
cmd/root.go

@@ -11,8 +11,6 @@ var RootCmd = &cobra.Command{
 	Short: "科湃腾牛群系统",
 }
 
-// Execute adds all child commands to the root command and sets flags appropriately.
-// This is called by main.main(). It only needs to happen once to the rootCmd.
 func Execute() {
 	err := RootCmd.Execute()
 	if err != nil {

+ 5 - 6
config/app.develop.yaml

@@ -20,7 +20,6 @@ redis_setting:
     expiry: 120
 
 jwt_secret: "sUd7j%UfJMt59ywh"
-cache_key_suffix: "gmym"
 
 side_work_setting:
   asynq_setting:
@@ -31,12 +30,12 @@ side_work_setting:
       password: "root"
     concurrency: 5
     queues:
-      workflow: 20
+      workOrder: 20
       low: 10
       default: 5
 cron:
   crontab_start_run: false
-  update_cow_info: "0 * * * * ?"
-  generate_work_order: "0 0 22 * * ?"
-  immunization_plan: "0 * * * * ?"
-  same_Time_plan: "0 */1 * * * ?"
+  update_cow_info: "0 0/5 * * * ?"
+  generate_work_order: "0 0/2 * * * ?"
+  immunization_plan: "0 0/1 * * * ?"
+  same_Time_plan: "0 0/1 * * * ?"

+ 2 - 3
config/app.go

@@ -21,7 +21,7 @@ var (
 
 // AppConfig store all configuration options
 type AppConfig struct {
-	FarmName       string `json:"farm_name"`
+	FarmName       string `yaml:"farm_name"`
 	AppName        string `yaml:"app_name"`
 	AppEnv         string `yaml:"app_environment"`
 	Debug          bool   `yaml:"debug" env:"APP_DEBUG"`
@@ -41,8 +41,7 @@ type AppConfig struct {
 
 	// asynq 相关配置
 	SideWorkSetting SideWorkSetting `yaml:"side_work_setting"`
-
-	CronSetting CronSetting `json:"cron_setting" yaml:"cron"`
+	CronSetting     CronSetting     `json:"cron_setting" yaml:"cron"`
 }
 
 type CronSetting struct {

+ 1 - 1
config/app.test.yaml

@@ -29,7 +29,7 @@ side_work_setting:
       pool_size: 10
     concurrency: 5
     queues:
-      workflow: 20
+      workOrder: 20
       low: 10
       default: 5
 cron:

+ 6 - 2
dep/di_asynq.go

@@ -1,6 +1,7 @@
 package dep
 
 import (
+	"fmt"
 	"kpt-pasture/config"
 	"kpt-pasture/model"
 	"kpt-pasture/module/consumer"
@@ -22,8 +23,11 @@ func DIAsynqWorkOrder() (out *asynqsvc.Server) {
 
 // AsynqWorkOrder 相关消费
 func AsynqWorkOrder(dep AsyncDependency) *asynqsvc.Server {
-	srv := asynqsvc.NewServer(config.Options())
-	srv.Mux.HandleFunc(model.TaskWorkOrder, dep.WorkOrder.DayWorkOrder) // 工单
+	cfg := config.Options()
+	srv := asynqsvc.NewServer(cfg)
+	pref := cfg.FarmName
+	pattern := fmt.Sprintf("%s:%s", pref, model.TaskWorkOrder)
+	srv.Mux.HandleFunc(pattern, dep.WorkOrder.DayWorkOrder) // 工单
 	return srv
 }
 

+ 1 - 0
dep/di_crontab.go

@@ -40,6 +40,7 @@ type CrontabDependency struct {
 func EntryCrontab(dependency CrontabDependency) *cron.Crontab {
 	cfg := config.Options()
 	cs := cfg.CronSetting
+
 	newCrontab := cron.NewCrontab(DataCenterCrontabCounterVec)
 	err := newCrontab.Bind("UpdateCowInfo", cs.UpdateCowInfo, dependency.CrontabHub.UpdateCowInfo)
 	if err != nil {

+ 13 - 0
docker-compose.yml

@@ -29,3 +29,16 @@ services:
       - APP_ENVIRONMENT=production
       - PASTURE_WORK_DIR=/app/kpt-pasture
     command: [ "/app/kpt-pasture/kptPasture","http" ]
+  kpt-pasture-consumer:
+    privileged: true
+    container_name: xdmy001_kpt_pasture_consumer
+    restart: always
+    image: registry.cn-hangzhou.aliyuncs.com/kpt-event/kpt-pasture:test
+    volumes:
+      - /var/logger/kpt-pasture/:/app/kpt-pasture/logger
+      - /etc/localtime:/etc/localtime
+      - /data/docker-compose/kpt-pasture/config:/app/kpt-pasture/config
+    environment:
+      - APP_ENVIRONMENT=production
+      - PASTURE_WORK_DIR=/app/kpt-pasture
+    command: [ "/app/kpt-pasture/kptPasture","consumer" ]

+ 1 - 1
go.mod

@@ -3,7 +3,7 @@ module kpt-pasture
 go 1.17
 
 require (
-	gitee.com/xuyiping_admin/go_proto v0.0.0-20240913094501-2c3f16e7b53a
+	gitee.com/xuyiping_admin/go_proto v0.0.0-20240914085632-2dbb719d5eb9
 	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

+ 2 - 0
go.sum

@@ -82,6 +82,8 @@ gitee.com/xuyiping_admin/go_proto v0.0.0-20240913070925-6c67b84f42fc h1:o8U7cViR
 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/go_proto v0.0.0-20240914085632-2dbb719d5eb9 h1:/irLE00XZY5K9/FryWMEDlPnwDSEn8y4jQn/bepnCQ0=
+gitee.com/xuyiping_admin/go_proto v0.0.0-20240914085632-2dbb719d5eb9/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=

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

@@ -49,7 +49,13 @@ func CalendarTableDetail(c *gin.Context) {
 		return
 	}
 
-	res, err := middleware.Dependency(c).StoreEventHub.OpsService.CalendarTableDetail(c, &req)
+	pagination := &pasturePb.PaginationModel{
+		Page:       int32(c.GetInt(middleware.Page)),
+		PageSize:   int32(c.GetInt(middleware.PageSize)),
+		PageOffset: int32(c.GetInt(middleware.PageOffset)),
+	}
+
+	res, err := middleware.Dependency(c).StoreEventHub.OpsService.CalendarTableDetail(c, &req, pagination)
 	if err != nil {
 		apierr.ClassifiedAbort(c, err)
 		return

+ 1 - 1
http/route/work_order.go

@@ -19,7 +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)
+		workRoute.POST("/calendar/detail", work.CalendarTableDetail)
 
 	}
 }

+ 10 - 22
model/calendar.go

@@ -60,28 +60,16 @@ func (c CalendarSlice) ToPB() []*pasturePb.Calendar {
 	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 CalendarResponse struct {
+	Code    int32         `json:"code"`
+	Message string        `json:"message"`
+	Data    *CalendarData `json:"data"`
 }
 
-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 执行类型定义成枚举???
+type CalendarData struct {
+	Total    int32       `json:"total"`
+	Page     int32       `json:"page"`
+	PageSize int32       `json:"pageSize"`
+	Header   interface{} `json:"header"`
+	List     interface{} `json:"data"`
 }

+ 19 - 0
model/immunization_plan_cow.go

@@ -45,3 +45,22 @@ func NewImmunizationPlanCowList(cowList []*Cow, immunizationPlan *ImmunizationPl
 	}
 	return immunizationPlanCowList
 }
+
+type ImmunizationPlanCowSlice []*ImmunizationPlanCow
+
+type ImmunizationCalendarHeader struct {
+	Id                   string `json:"id"`
+	CowId                string `json:"cowId"`
+	PlanStartTime        string `json:"planStartTime"`
+	ImmunizationPlanId   string `json:"immunizationPlanId"`
+	ImmunizationPlanName string `json:"immunizationPlanName"`
+	Status               string `json:"status"`
+}
+
+func (I ImmunizationPlanCowSlice) ToPB() []*ImmunizationPlanCow {
+	res := make([]*ImmunizationPlanCow, len(I))
+	for i, v := range I {
+		res[i] = v
+	}
+	return res
+}

+ 26 - 0
model/same_time_cow_list.go

@@ -45,3 +45,29 @@ func NewSameTimeCowDetailList(cowList []*Cow, sameTimeId int64, planTime string,
 
 	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 执行类型定义成枚举???
+}

+ 5 - 6
model/work_order_master.go

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

+ 90 - 10
module/backend/calendar.go

@@ -26,12 +26,15 @@ func (s *StoreEntry) CalendarList(ctx context.Context, req *pasturePb.CalendarRe
 	}, nil
 }
 
-func (s *StoreEntry) CalendarTableDetail(ctx context.Context, req *pasturePb.CalendarTableRequest) (interface{}, error) {
+func (s *StoreEntry) CalendarTableDetail(
+	ctx context.Context,
+	req *pasturePb.CalendarTableRequest,
+	pagination *pasturePb.PaginationModel,
+) (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).
@@ -45,15 +48,92 @@ func (s *StoreEntry) CalendarTableDetail(ctx context.Context, req *pasturePb.Cal
 		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 s.getCalendarCowList(ctx, req.CalendarType, req.Start, pagination), nil
+}
+
+func (s *StoreEntry) getCalendarCowList(
+	ctx context.Context,
+	calendarType pasturePb.CalendarType_Kind,
+	startDate string,
+	pagination *pasturePb.PaginationModel) (*model.CalendarResponse, error) {
+	switch calendarType {
+	case pasturePb.CalendarType_Immunisation: // 免疫
+		return s.ImmunisationCowList(ctx, startDate, pagination)
+	case pasturePb.CalendarType_PG: // 同期PG
+		return s.PGCowList(ctx, startDate, pagination)
+	case pasturePb.CalendarType_RnGH: // 同期RnGH
+		return s.RnGHCowList(ctx, startDate, pagination)
+	case pasturePb.CalendarType_Pregnancy_Check: // 孕检
+		return s.PregnancyCheckCowList(ctx, startDate, pagination)
+	case pasturePb.CalendarType_WorkOrder: // 工作单
+		return s.WorkOrderCowList(ctx, startDate, pagination)
+	case pasturePb.CalendarType_Weaning: // 断奶
+		return s.WeaningCowList(ctx, startDate, pagination)
+	case pasturePb.CalendarType_Treatment: // 治疗
+		return s.TreatmentCowList(ctx, startDate, pagination)
+	case pasturePb.CalendarType_Mating: // 配种
+		return s.MatingCowList(ctx, startDate, pagination)
+	default:
+		return nil, xerr.New("不支持的日历类型")
+	}
+}
+
+func (s *StoreEntry) ImmunisationCowList(ctx context.Context, dateTime string, pagination *pasturePb.PaginationModel) (*model.CalendarResponse, error) {
+	immunizationPlanCowList := make([]*model.ImmunizationPlanCow, 0)
+	count := int64(0)
+	if err := s.DB.Model(&model.ImmunizationPlanCow{}).
+		Where("plan_start_time <= ?", dateTime).
+		Where("status = ?", pasturePb.IsShow_No).
+		Order("id desc").Count(&count).Limit(int(pagination.PageSize)).Offset(int(pagination.PageOffset)).
+		Find(&immunizationPlanCowList).Error; err != nil {
+		return nil, xerr.WithStack(err)
 	}
 
+	return &model.CalendarResponse{
+		Code:    http.StatusOK,
+		Message: "ok",
+		Data: &model.CalendarData{
+			Total:    int32(count),
+			Page:     pagination.Page,
+			PageSize: pagination.PageSize,
+			Header: model.ImmunizationCalendarHeader{
+				Id:                   "id",
+				CowId:                "cowId",
+				PlanStartTime:        "planStartTime",
+				ImmunizationPlanId:   "immunizationPlanId",
+				ImmunizationPlanName: "immunizationPlanName",
+				Status:               "status",
+			},
+			List: model.ImmunizationPlanCowSlice(immunizationPlanCowList).ToPB(),
+		},
+	}, nil
+
+}
+
+func (s *StoreEntry) PGCowList(ctx context.Context, dateTime string, pagination *pasturePb.PaginationModel) (*model.CalendarResponse, error) {
+	return nil, nil
+}
+
+func (s *StoreEntry) RnGHCowList(ctx context.Context, dateTime string, pagination *pasturePb.PaginationModel) (*model.CalendarResponse, error) {
+	return nil, nil
+}
+
+func (s *StoreEntry) PregnancyCheckCowList(ctx context.Context, dateTime string, pagination *pasturePb.PaginationModel) (*model.CalendarResponse, error) {
+	return nil, nil
+}
+
+func (s *StoreEntry) WorkOrderCowList(ctx context.Context, dateTime string, pagination *pasturePb.PaginationModel) (*model.CalendarResponse, error) {
+	return nil, nil
+}
+
+func (s *StoreEntry) WeaningCowList(ctx context.Context, dateTime string, pagination *pasturePb.PaginationModel) (*model.CalendarResponse, error) {
+	return nil, nil
+}
+
+func (s *StoreEntry) TreatmentCowList(ctx context.Context, dateTime string, pagination *pasturePb.PaginationModel) (*model.CalendarResponse, error) {
+	return nil, nil
+}
+
+func (s *StoreEntry) MatingCowList(ctx context.Context, dateTime string, pagination *pasturePb.PaginationModel) (*model.CalendarResponse, error) {
 	return nil, nil
 }

+ 0 - 5
module/backend/event_breed.go

@@ -500,19 +500,14 @@ func (s *StoreEntry) SameTimeCreate(ctx context.Context, req *pasturePb.EventSam
 			return xerr.WithStack(err)
 		}
 	}
-
 	newSameTimeCowList := model.NewSameTimeCowList(cowList, sameTime)
-
 	if err = s.DB.Transaction(func(tx *gorm.DB) error {
-
 		if err = tx.Create(eventSameTimeList).Error; err != nil {
 			return xerr.WithStack(err)
 		}
-
 		return nil
 	}); err != nil {
 		return xerr.WithStack(err)
 	}*/
-
 	return nil
 }

+ 1 - 1
module/backend/interface.go

@@ -199,5 +199,5 @@ type WorkService interface {
 	UserWorkOrderList(ctx context.Context, workOrderStatus pasturePb.WorkOrderStatus_Kind, pagination *pasturePb.PaginationModel) (*pasturePb.UserWorkOrderResponse, error)
 
 	CalendarList(ctx context.Context, req *pasturePb.CalendarRequest) (*pasturePb.CalendarResponse, error)
-	CalendarTableDetail(ctx context.Context, req *pasturePb.CalendarTableRequest) (interface{}, error)
+	CalendarTableDetail(ctx context.Context, req *pasturePb.CalendarTableRequest, pagination *pasturePb.PaginationModel) (interface{}, error)
 }

+ 5 - 2
module/backend/work.go

@@ -103,7 +103,7 @@ func (s *StoreEntry) OrderCreateOrUpdate(ctx context.Context, req *pasturePb.Wor
 				"exec_persons":      newWorkOrderMaster.ExecPersons,
 				"exec_person_names": newWorkOrderMaster.ExecPersonNames,
 				"week_month_value":  newWorkOrderMaster.WeekMonthValue,
-				"remark":            newWorkOrderMaster.Remarks,
+				"remarks":           newWorkOrderMaster.Remarks,
 				"photos":            newWorkOrderMaster.Photos,
 			}).Error; err != nil {
 				return xerr.WithStack(err)
@@ -229,7 +229,10 @@ func (s *StoreEntry) SendAsynqWorkOrder(ctx context.Context, workOrder *model.Wo
 	}
 
 	execTime := time.Now().Unix() - timeUnix
-	if _, err := s.AsynqClient.CtxEnqueue(ctx, model.NewTaskWorkOrderPayload(workOrder.Id, time.Duration(execTime)*time.Second)); err != nil {
+	if _, err := s.AsynqClient.CtxEnqueue(
+		ctx,
+		model.NewTaskWorkOrderPayload(workOrder.Id, time.Duration(execTime)*time.Second),
+	); err != nil {
 		zaplog.Error("PushMessage CtxEnqueue", zap.Any("Err", err))
 	}
 }

+ 1 - 1
module/consumer/consumer.go

@@ -52,6 +52,6 @@ func (entry *Entry) DayWorkOrder(ctx context.Context, t *asynq.Task) error {
 	if err := entry.DB.Create(workOrderSubList).Error; err != nil {
 		zaplog.Error("consumer", zap.Any("mark", "DayWorkOrder"), zap.Any("NewWorkOrderSub", err))
 	}
-
+	zaplog.Error("consumer", zap.Any("DayWorkOrder", "success"))
 	return nil
 }

+ 19 - 14
module/crontab/cow_cron.go

@@ -17,10 +17,17 @@ const (
 	UpdateCowInfo    = "UpdateCowInfo"
 	ImmunizationPlan = "ImmunizationPlan"
 	SameTimePlan     = "SameTimePlan"
+	WorkOrderMaster  = "WorkOrderMaster"
 )
 
 // GenerateAsynqWorkOrder 异步生成工作单
 func (e *Entry) GenerateAsynqWorkOrder() error {
+	if ok := e.IsExistCrontabLog(WorkOrderMaster); ok {
+		return nil
+	}
+	defer func() {
+		e.CreateCrontabLog(WorkOrderMaster)
+	}()
 	workOrderList := make([]*model.WorkOrderMaster, 0)
 	if err := e.DB.Where("is_show = ?", pasturePb.IsShow_Ok).Find(&workOrderList).Error; err != nil {
 		return err
@@ -34,7 +41,6 @@ func (e *Entry) GenerateAsynqWorkOrder() error {
 		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))
 		}
@@ -48,14 +54,12 @@ func (e *Entry) UpdateCowInfo() error {
 	if err := e.DB.Where("is_remove = ?", pasturePb.IsShow_Ok).Find(&cowList).Error; err != nil {
 		return err
 	}
-
-	if ok := e.IsExistCrontabLog(UpdateCowInfo); !ok {
+	if ok := e.IsExistCrontabLog(UpdateCowInfo); ok {
 		return nil
 	}
 	defer func() {
 		e.CreateCrontabLog(UpdateCowInfo)
 	}()
-
 	for _, cow := range cowList {
 		dayAge := cow.GetDayAge()
 		calvingAge := cow.GetCalvingAge()
@@ -75,15 +79,13 @@ func (e *Entry) UpdateCowInfo() error {
 
 // ImmunizationPlan 免疫计划,生成工作单
 func (e *Entry) ImmunizationPlan() error {
-	if ok := e.IsExistCrontabLog(ImmunizationPlan); !ok {
+	if ok := e.IsExistCrontabLog(ImmunizationPlan); ok {
 		return nil
 	}
-
 	planList := make([]*model.ImmunizationPlan, 0)
 	if err := e.DB.Where("is_show = ?", pasturePb.IsShow_Ok).Find(&planList).Error; err != nil {
 		return xerr.WithStack(err)
 	}
-
 	var todayCount int32 = 0
 	defer func() {
 		var count int64 = 0
@@ -91,7 +93,9 @@ func (e *Entry) ImmunizationPlan() error {
 			zaplog.Error("Crontab", zap.Any("ImmunizationPlanDefer", err))
 		}
 		todayCount += int32(count)
-		e.CreatedWorkOrderCalendar(pasturePb.CalendarType_Immunisation, todayCount)
+		if todayCount > 0 {
+			e.CreatedCalendar(pasturePb.CalendarType_Immunisation, todayCount)
+		}
 		e.CreateCrontabLog(ImmunizationPlan)
 	}()
 
@@ -102,7 +106,7 @@ func (e *Entry) ImmunizationPlan() error {
 		cowList := make([]*model.Cow, 0)
 		pref := e.DB.Table(fmt.Sprintf("%s as a", new(model.ImmunizationPlan).TableName())).
 			Select("a.*").
-			Where("a.is_remove = ?", pasturePb.IsShow_Ok)
+			Where("a.is_show = ?", pasturePb.IsShow_Ok)
 		if plan.CowType > 0 {
 			pref.Where("a.cow_type = ?", plan.CowType)
 		}
@@ -140,13 +144,13 @@ func (e *Entry) ImmunizationPlan() error {
 			zaplog.Error("ImmunizationPlan", zap.Any("CreateImmunizationPlanCow", err), zap.Any("plan", plan), zap.Any("cowList", cowList))
 		}
 	}
-
+	zaplog.Info("ImmunizationPlan", zap.Any("todayCount", todayCount))
 	return nil
 }
 
 // SameTimePlan 同期计划,生成工作单
 func (e *Entry) SameTimePlan() error {
-	if ok := e.IsExistCrontabLog(SameTimePlan); !ok {
+	if ok := e.IsExistCrontabLog(SameTimePlan); ok {
 		return nil
 	}
 
@@ -158,7 +162,9 @@ func (e *Entry) SameTimePlan() error {
 	// 更新日历里面的数据
 	var todayCount int32 = 0
 	defer func() {
-		e.CreatedWorkOrderCalendar(pasturePb.CalendarType_Immunisation, todayCount)
+		if todayCount > 0 {
+			e.CreatedCalendar(pasturePb.CalendarType_Immunisation, todayCount)
+		}
 		e.CreateCrontabLog(SameTimePlan)
 	}()
 
@@ -185,7 +191,7 @@ func (e *Entry) SameTimePlan() error {
 			pref.Where(
 				e.DB.Where("breed_status = ?", pasturePb.BreedStatus_Empty).
 					Or("breed_status = ?", pasturePb.BreedStatus_Abort),
-			).Where("s_pregnant = ?", pasturePb.IsShow_No)
+			).Where("is_pregnant = ?", pasturePb.IsShow_No)
 		}
 
 		if err := pref.Find(&cowList).Error; err != nil {
@@ -213,7 +219,6 @@ func (e *Entry) SameTimePlan() error {
 
 // PregnancyCheck 妊娠期检查
 func (e *Entry) PregnancyCheck() error {
-
 	return nil
 }
 

+ 20 - 6
module/crontab/other.go

@@ -33,12 +33,26 @@ func (e *Entry) CreateCrontabLog(name string) {
 	}
 }
 
-// CreatedWorkOrderCalendar 创建当天工单日历记录
-func (e *Entry) CreatedWorkOrderCalendar(calendarType pasturePb.CalendarType_Kind, count int32) {
+// CreatedCalendar 创建当天工单日历记录
+func (e *Entry) CreatedCalendar(calendarType pasturePb.CalendarType_Kind, count int32) {
 	calendarTypeName := backend.CalendarTypeMap()[calendarType]
-	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))
+	newCalendar := model.NewCalendar(calendarTypeName, calendarType, count)
+
+	historyCalendar := &model.Calendar{}
+	if err := e.DB.Model(&model.Calendar{}).Where("calendar_type = ?", calendarType).
+		Where("show_day = ?", time.Now().Format(model.LayoutDate2)).First(historyCalendar).Error; err != nil {
+		zaplog.Error("CreatedCalendar", zap.Any("err", err), zap.Any("historyCalendar", historyCalendar))
+	}
+	if historyCalendar.Id <= 0 {
+		if err := e.DB.Model(&model.Calendar{}).Create(newCalendar).Error; err != nil {
+			zaplog.Error("CreatedCalendar", zap.Any("err", err), zap.Any("workOrderCalendar", newCalendar))
+		}
+		return
+	}
+
+	if err := e.DB.Model(&model.Calendar{}).Where("id = ?", historyCalendar.Id).
+		Update("count", count).Error; err != nil {
+		zaplog.Error("CreatedCalendar", zap.Any("err", err), zap.Any("historyCalendar", historyCalendar))
 	}
 }
 
@@ -48,7 +62,7 @@ func (e *Entry) IsExistSameTimeCow(cow *model.Cow, sameTime *model.SameTime) boo
 		Where("cow_id = ?", cow.Id).
 		Where("lact = ?", cow.Lact).
 		Where("same_time_id = ?", sameTime.Id).
-		Where("status != ?", pasturePb.SameTimeStatus_End).
+		Where("same_time_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