Files
pig-farm-controller/internal/infra/repository/medication_repository.go
2025-10-18 16:22:59 +08:00

81 lines
2.3 KiB
Go

package repository
import (
"time"
"git.huangwc.com/pig/pig-farm-controller/internal/infra/models"
"gorm.io/gorm"
)
// MedicationLogListOptions 定义了查询用药记录时的可选参数
type MedicationLogListOptions struct {
PigBatchID *uint
MedicationID *uint
Reason *models.MedicationReasonType
OperatorID *uint
StartTime *time.Time // 基于 happened_at 字段
EndTime *time.Time // 基于 happened_at 字段
OrderBy string // 例如 "happened_at asc"
}
// MedicationRepository 定义了与药品相关的数据库操作接口
type MedicationRepository interface {
ListMedicationLogs(opts MedicationLogListOptions, page, pageSize int) ([]models.MedicationLog, int64, error)
}
// gormMedicationRepository 是 MedicationRepository 的 GORM 实现
type gormMedicationRepository struct {
db *gorm.DB
}
// NewGormMedicationRepository 创建一个新的 MedicationRepository GORM 实现
func NewGormMedicationRepository(db *gorm.DB) MedicationRepository {
return &gormMedicationRepository{db: db}
}
// ListMedicationLogs 实现了分页和过滤查询用药记录的功能
func (r *gormMedicationRepository) ListMedicationLogs(opts MedicationLogListOptions, page, pageSize int) ([]models.MedicationLog, int64, error) {
if page <= 0 || pageSize <= 0 {
return nil, 0, ErrInvalidPagination
}
var results []models.MedicationLog
var total int64
query := r.db.Model(&models.MedicationLog{})
if opts.PigBatchID != nil {
query = query.Where("pig_batch_id = ?", *opts.PigBatchID)
}
if opts.MedicationID != nil {
query = query.Where("medication_id = ?", *opts.MedicationID)
}
if opts.Reason != nil {
query = query.Where("reason = ?", *opts.Reason)
}
if opts.OperatorID != nil {
query = query.Where("operator_id = ?", *opts.OperatorID)
}
if opts.StartTime != nil {
query = query.Where("happened_at >= ?", *opts.StartTime)
}
if opts.EndTime != nil {
query = query.Where("happened_at <= ?", *opts.EndTime)
}
if err := query.Count(&total).Error; err != nil {
return nil, 0, err
}
orderBy := "happened_at DESC"
if opts.OrderBy != "" {
orderBy = opts.OrderBy
}
query = query.Order(orderBy).Preload("Medication")
offset := (page - 1) * pageSize
err := query.Limit(pageSize).Offset(offset).Find(&results).Error
return results, total, err
}