实现按原料是否有库存筛选
This commit is contained in:
@@ -31,6 +31,7 @@ type ListCurrentStockRequest struct {
|
||||
PageSize int `json:"page_size" query:"page_size"` // 每页数量
|
||||
RawMaterialName *string `json:"raw_material_name" query:"raw_material_name"` // 按原料名称模糊查询
|
||||
OrderBy string `json:"order_by" query:"order_by"` // 排序字段, 例如 "stock DESC"
|
||||
HasStock *bool `json:"has_stock" query:"has_stock"` // 只查询有库存的原料
|
||||
}
|
||||
|
||||
// ListCurrentStockResponse 是获取当前库存列表的响应结构
|
||||
|
||||
@@ -75,8 +75,9 @@ func (s *inventoryServiceImpl) ListCurrentStock(ctx context.Context, req *dto.Li
|
||||
|
||||
// 1. 获取分页的原料列表
|
||||
rawMatOpts := repository.RawMaterialListOptions{
|
||||
Name: req.RawMaterialName,
|
||||
OrderBy: req.OrderBy, // 注意:这里的排序可能需要调整,比如按原料名排序
|
||||
Name: req.RawMaterialName,
|
||||
OrderBy: req.OrderBy, // 注意:这里的排序可能需要调整,比如按原料名排序
|
||||
HasStock: req.HasStock,
|
||||
}
|
||||
rawMaterials, total, err := s.rawMatRepo.ListRawMaterials(serviceCtx, rawMatOpts, req.Page, req.PageSize)
|
||||
if err != nil {
|
||||
|
||||
@@ -18,6 +18,7 @@ type RawMaterialListOptions struct {
|
||||
NutrientName *string
|
||||
MinReferencePrice *float32 // 参考价格最小值
|
||||
MaxReferencePrice *float32 // 参考价格最大值
|
||||
HasStock *bool // 是否只查询有库存的原料
|
||||
OrderBy string
|
||||
}
|
||||
|
||||
@@ -122,6 +123,22 @@ func (r *gormRawMaterialRepository) ListRawMaterials(ctx context.Context, opts R
|
||||
db = db.Where("reference_price <= ?", *opts.MaxReferencePrice)
|
||||
}
|
||||
|
||||
// 筛选有库存的原料
|
||||
if opts.HasStock != nil && *opts.HasStock {
|
||||
// 内部子查询:生成带有 rn 的结果集,GORM 会自动为 models.RawMaterialStockLog 添加 deleted_at IS NULL
|
||||
rankedLogsQuery := r.db.Model(&models.RawMaterialStockLog{}).
|
||||
Select("raw_material_id, after_quantity, ROW_NUMBER() OVER(PARTITION BY raw_material_id ORDER BY happened_at DESC, id DESC) as rn")
|
||||
|
||||
// 外部子查询:从 ranked_logs 中筛选 rn=1 且 after_quantity > 0 的 raw_material_id
|
||||
// GORM 会将 rankedLogsQuery 作为一个子查询嵌入到 FROM 子句中
|
||||
latestStockLogSubQuery := r.db.Table("(?) as ranked_logs", rankedLogsQuery).
|
||||
Select("raw_material_id").
|
||||
Where("rn = 1 AND after_quantity > 0")
|
||||
|
||||
// 将这个子查询直接应用到主查询的 WHERE id IN (?) 条件中
|
||||
db = db.Where("id IN (?)", latestStockLogSubQuery)
|
||||
}
|
||||
|
||||
// 首先计算总数
|
||||
if err := db.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
|
||||
Reference in New Issue
Block a user