猪群管理聚合服务 增加调栏管理

This commit is contained in:
2025-10-05 17:30:39 +08:00
parent 6d080d250d
commit 01327eb8d2
10 changed files with 350 additions and 33 deletions

View File

@@ -0,0 +1,19 @@
package models
import (
"time"
"gorm.io/gorm"
)
// PigTransferLog 记录了每一次猪只数量在猪栏间的变动事件。
// 它作为事件溯源的基础,用于推算任意时间点猪栏的猪只数量。
type PigTransferLog struct {
gorm.Model
TransferTime time.Time `json:"transfer_time"` // 迁移发生时间
PigBatchID uint `json:"pig_batch_id"` // 关联的猪群ID
PenID uint `json:"pen_id"` // 发生变动的猪栏ID
Quantity int `json:"quantity"` // 变动数量(正数表示增加,负数表示减少)
Type string `json:"type"` // 变动类型 (e.g., "群内调栏", "跨群调栏", "销售", "死亡", "新购入")
CorrelationID string `json:"correlation_id"` // 用于关联一次完整操作(如一次调栏会产生两条日志)
}

View File

@@ -0,0 +1,46 @@
package repository
import (
"git.huangwc.com/pig/pig-farm-controller/internal/infra/models"
"gorm.io/gorm"
)
// PenRepository 定义了与猪栏模型相关的数据库操作接口。
type PenRepository interface {
GetPenByIDTx(tx *gorm.DB, penID uint) (*models.Pen, error)
GetPensByBatchIDTx(tx *gorm.DB, batchID uint) ([]*models.Pen, error)
UpdatePenFieldsTx(tx *gorm.DB, penID uint, updates map[string]interface{}) error
}
// penRepository 是 PenRepository 接口的 gorm 实现。
type penRepository struct {
db *gorm.DB
}
// NewPenRepository 创建一个新的 PenRepository 实例。
func NewPenRepository(db *gorm.DB) PenRepository {
return &penRepository{db: db}
}
// GetPenByIDTx 在指定的事务中通过ID获取单个猪栏信息。
func (r *penRepository) GetPenByIDTx(tx *gorm.DB, penID uint) (*models.Pen, error) {
var pen models.Pen
if err := tx.First(&pen, penID).Error; err != nil {
return nil, err
}
return &pen, nil
}
// GetPensByBatchIDTx 在指定的事务中,获取一个猪群当前关联的所有猪栏。
func (r *penRepository) GetPensByBatchIDTx(tx *gorm.DB, batchID uint) ([]*models.Pen, error) {
var pens []*models.Pen
if err := tx.Where("pig_batch_id = ?", batchID).Find(&pens).Error; err != nil {
return nil, err
}
return pens, nil
}
// UpdatePenFieldsTx 在指定的事务中,更新一个猪栏的指定字段。
func (r *penRepository) UpdatePenFieldsTx(tx *gorm.DB, penID uint, updates map[string]interface{}) error {
return tx.Model(&models.Pen{}).Where("id = ?", penID).Updates(updates).Error
}

View File

@@ -9,6 +9,7 @@ import (
type PigBatchRepository interface {
CreatePigBatch(batch *models.PigBatch) (*models.PigBatch, error)
GetPigBatchByID(id uint) (*models.PigBatch, error)
GetPigBatchByIDTx(tx *gorm.DB, id uint) (*models.PigBatch, error)
// UpdatePigBatch 更新一个猪批次,返回更新后的批次、受影响的行数和错误
UpdatePigBatch(batch *models.PigBatch) (*models.PigBatch, int64, error)
// DeletePigBatch 根据ID删除一个猪批次返回受影响的行数和错误
@@ -83,3 +84,12 @@ func (r *gormPigBatchRepository) ListPigBatches(isActive *bool) ([]*models.PigBa
}
return batches, nil
}
// GetPigBatchByIDTx 在指定的事务中通过ID获取单个猪批次
func (r *gormPigBatchRepository) GetPigBatchByIDTx(tx *gorm.DB, id uint) (*models.PigBatch, error) {
var batch models.PigBatch
if err := tx.First(&batch, id).Error; err != nil {
return nil, err
}
return &batch, nil
}