ListPigPurchases
This commit is contained in:
@@ -1,10 +1,22 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"git.huangwc.com/pig/pig-farm-controller/internal/infra/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// PigPurchaseListOptions 定义了查询猪只采购记录时的可选参数
|
||||
type PigPurchaseListOptions struct {
|
||||
PigBatchID *uint
|
||||
Supplier *string
|
||||
OperatorID *uint
|
||||
StartTime *time.Time // 基于 purchase_date 字段
|
||||
EndTime *time.Time // 基于 purchase_date 字段
|
||||
OrderBy string // 例如 "purchase_date desc"
|
||||
}
|
||||
|
||||
// PigTradeRepository 定义了猪只交易数据持久化的接口。
|
||||
// 领域服务通过此接口与数据层交互,实现解耦。
|
||||
type PigTradeRepository interface {
|
||||
@@ -13,6 +25,9 @@ type PigTradeRepository interface {
|
||||
|
||||
// CreatePigPurchaseTx 在数据库中创建一条猪只采购记录。
|
||||
CreatePigPurchaseTx(tx *gorm.DB, purchase *models.PigPurchase) error
|
||||
|
||||
// ListPigPurchases 支持分页和过滤的猪只采购记录列表查询
|
||||
ListPigPurchases(opts PigPurchaseListOptions, page, pageSize int) ([]models.PigPurchase, int64, error)
|
||||
}
|
||||
|
||||
// gormPigTradeRepository 是 PigTradeRepository 接口的 GORM 实现。
|
||||
@@ -34,3 +49,46 @@ func (r *gormPigTradeRepository) CreatePigSaleTx(tx *gorm.DB, sale *models.PigSa
|
||||
func (r *gormPigTradeRepository) CreatePigPurchaseTx(tx *gorm.DB, purchase *models.PigPurchase) error {
|
||||
return tx.Create(purchase).Error
|
||||
}
|
||||
|
||||
// ListPigPurchases 实现了分页和过滤查询猪只采购记录的功能
|
||||
func (r *gormPigTradeRepository) ListPigPurchases(opts PigPurchaseListOptions, page, pageSize int) ([]models.PigPurchase, int64, error) {
|
||||
if page <= 0 || pageSize <= 0 {
|
||||
return nil, 0, ErrInvalidPagination
|
||||
}
|
||||
|
||||
var results []models.PigPurchase
|
||||
var total int64
|
||||
|
||||
query := r.db.Model(&models.PigPurchase{})
|
||||
|
||||
if opts.PigBatchID != nil {
|
||||
query = query.Where("pig_batch_id = ?", *opts.PigBatchID)
|
||||
}
|
||||
if opts.Supplier != nil {
|
||||
query = query.Where("supplier LIKE ?", "%"+*opts.Supplier+"%")
|
||||
}
|
||||
if opts.OperatorID != nil {
|
||||
query = query.Where("operator_id = ?", *opts.OperatorID)
|
||||
}
|
||||
if opts.StartTime != nil {
|
||||
query = query.Where("purchase_date >= ?", *opts.StartTime)
|
||||
}
|
||||
if opts.EndTime != nil {
|
||||
query = query.Where("purchase_date <= ?", *opts.EndTime)
|
||||
}
|
||||
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
orderBy := "purchase_date DESC"
|
||||
if opts.OrderBy != "" {
|
||||
orderBy = opts.OrderBy
|
||||
}
|
||||
query = query.Order(orderBy)
|
||||
|
||||
offset := (page - 1) * pageSize
|
||||
err := query.Limit(pageSize).Offset(offset).Find(&results).Error
|
||||
|
||||
return results, total, err
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user