ListFeedUsageRecords

This commit is contained in:
2025-10-18 16:08:46 +08:00
parent eb0786ca27
commit 4c6843afb4
4 changed files with 183 additions and 0 deletions

View File

@@ -26,10 +26,21 @@ type RawMaterialStockLogListOptions struct {
OrderBy string // 例如 "happened_at asc"
}
// FeedUsageRecordListOptions 定义了查询饲料使用记录时的可选参数
type FeedUsageRecordListOptions struct {
PenID *uint
FeedFormulaID *uint
OperatorID *uint
StartTime *time.Time // 基于 recorded_at 字段
EndTime *time.Time // 基于 recorded_at 字段
OrderBy string // 例如 "recorded_at asc"
}
// RawMaterialRepository 定义了与原料相关的数据库操作接口
type RawMaterialRepository interface {
ListRawMaterialPurchases(opts RawMaterialPurchaseListOptions, page, pageSize int) ([]models.RawMaterialPurchase, int64, error)
ListRawMaterialStockLogs(opts RawMaterialStockLogListOptions, page, pageSize int) ([]models.RawMaterialStockLog, int64, error)
ListFeedUsageRecords(opts FeedUsageRecordListOptions, page, pageSize int) ([]models.FeedUsageRecord, int64, error)
}
// gormRawMaterialRepository 是 RawMaterialRepository 的 GORM 实现
@@ -124,3 +135,46 @@ func (r *gormRawMaterialRepository) ListRawMaterialStockLogs(opts RawMaterialSto
return results, total, err
}
// ListFeedUsageRecords 实现了分页和过滤查询饲料使用记录的功能
func (r *gormRawMaterialRepository) ListFeedUsageRecords(opts FeedUsageRecordListOptions, page, pageSize int) ([]models.FeedUsageRecord, int64, error) {
if page <= 0 || pageSize <= 0 {
return nil, 0, ErrInvalidPagination
}
var results []models.FeedUsageRecord
var total int64
query := r.db.Model(&models.FeedUsageRecord{})
if opts.PenID != nil {
query = query.Where("pen_id = ?", *opts.PenID)
}
if opts.FeedFormulaID != nil {
query = query.Where("feed_formula_id = ?", *opts.FeedFormulaID)
}
if opts.OperatorID != nil {
query = query.Where("operator_id = ?", *opts.OperatorID)
}
if opts.StartTime != nil {
query = query.Where("recorded_at >= ?", *opts.StartTime)
}
if opts.EndTime != nil {
query = query.Where("recorded_at <= ?", *opts.EndTime)
}
if err := query.Count(&total).Error; err != nil {
return nil, 0, err
}
orderBy := "recorded_at DESC"
if opts.OrderBy != "" {
orderBy = opts.OrderBy
}
query = query.Order(orderBy).Preload("Pen").Preload("FeedFormula")
offset := (page - 1) * pageSize
err := query.Limit(pageSize).Offset(offset).Find(&results).Error
return results, total, err
}