ListRawMaterialPurchases
This commit is contained in:
73
internal/infra/repository/raw_material_repository.go
Normal file
73
internal/infra/repository/raw_material_repository.go
Normal file
@@ -0,0 +1,73 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"git.huangwc.com/pig/pig-farm-controller/internal/infra/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// RawMaterialPurchaseListOptions 定义了查询原料采购记录时的可选参数
|
||||
type RawMaterialPurchaseListOptions struct {
|
||||
RawMaterialID *uint
|
||||
Supplier *string
|
||||
StartTime *time.Time // 基于 purchase_date 字段
|
||||
EndTime *time.Time // 基于 purchase_date 字段
|
||||
OrderBy string // 例如 "purchase_date asc"
|
||||
}
|
||||
|
||||
// RawMaterialRepository 定义了与原料相关的数据库操作接口
|
||||
type RawMaterialRepository interface {
|
||||
// ListRawMaterialPurchases 支持分页和过滤的列表查询
|
||||
ListRawMaterialPurchases(opts RawMaterialPurchaseListOptions, page, pageSize int) ([]models.RawMaterialPurchase, int64, error)
|
||||
}
|
||||
|
||||
// gormRawMaterialRepository 是 RawMaterialRepository 的 GORM 实现
|
||||
type gormRawMaterialRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewGormRawMaterialRepository 创建一个新的 RawMaterialRepository GORM 实现实例
|
||||
func NewGormRawMaterialRepository(db *gorm.DB) RawMaterialRepository {
|
||||
return &gormRawMaterialRepository{db: db}
|
||||
}
|
||||
|
||||
// ListRawMaterialPurchases 实现了分页和过滤查询原料采购记录的功能
|
||||
func (r *gormRawMaterialRepository) ListRawMaterialPurchases(opts RawMaterialPurchaseListOptions, page, pageSize int) ([]models.RawMaterialPurchase, int64, error) {
|
||||
if page <= 0 || pageSize <= 0 {
|
||||
return nil, 0, ErrInvalidPagination
|
||||
}
|
||||
|
||||
var results []models.RawMaterialPurchase
|
||||
var total int64
|
||||
|
||||
query := r.db.Model(&models.RawMaterialPurchase{})
|
||||
|
||||
if opts.RawMaterialID != nil {
|
||||
query = query.Where("raw_material_id = ?", *opts.RawMaterialID)
|
||||
}
|
||||
if opts.Supplier != nil {
|
||||
query = query.Where("supplier LIKE ?", "%"+*opts.Supplier+"%")
|
||||
}
|
||||
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).Preload("RawMaterial")
|
||||
|
||||
offset := (page - 1) * pageSize
|
||||
err := query.Limit(pageSize).Offset(offset).Find(&results).Error
|
||||
|
||||
return results, total, err
|
||||
}
|
||||
Reference in New Issue
Block a user