FIX[BE]: if project flocs deleted kandangs reset to non_active and add filter get all project_flock by area,kandangs,period and location

This commit is contained in:
ragilap
2025-10-19 23:24:56 +07:00
parent c9b4b3008e
commit f15e0d62e3
13 changed files with 663 additions and 51 deletions
+40
View File
@@ -378,6 +378,9 @@ func seedKandangs(tx *gorm.DB, createdBy uint, locations map[string]uint, users
if err := tx.Create(&kandang).Error; err != nil {
return nil, err
}
if err := syncPivotRelation(tx, projectFlockID, kandang.Id, createdBy); err != nil {
return nil, err
}
} else if err != nil {
return nil, err
} else {
@@ -394,6 +397,9 @@ func seedKandangs(tx *gorm.DB, createdBy uint, locations map[string]uint, users
if err := tx.Model(&entity.Kandang{}).Where("id = ?", kandang.Id).Updates(updates).Error; err != nil {
return nil, err
}
if err := syncPivotRelation(tx, projectFlockID, kandang.Id, createdBy); err != nil {
return nil, err
}
}
result[seed.Name] = kandang.Id
}
@@ -401,6 +407,40 @@ func seedKandangs(tx *gorm.DB, createdBy uint, locations map[string]uint, users
return result, nil
}
func syncPivotRelation(tx *gorm.DB, projectFlockID *uint, kandangID uint, createdBy uint) error {
if err := detachActivePivot(tx, kandangID); err != nil {
return err
}
if projectFlockID == nil {
return nil
}
return ensureActivePivot(tx, *projectFlockID, kandangID, createdBy)
}
func detachActivePivot(tx *gorm.DB, kandangID uint) error {
return tx.Model(&entity.ProjectFlockKandang{}).
Where("kandang_id = ? AND detached_at IS NULL", kandangID).
Updates(map[string]any{"detached_at": time.Now()}).Error
}
func ensureActivePivot(tx *gorm.DB, projectFlockID, kandangID, createdBy uint) error {
var pivot entity.ProjectFlockKandang
err := tx.Where("project_flock_id = ? AND kandang_id = ? AND detached_at IS NULL", projectFlockID, kandangID).
First(&pivot).Error
if err == nil {
return nil
}
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return err
}
newRecord := entity.ProjectFlockKandang{
ProjectFlockId: projectFlockID,
KandangId: kandangID,
CreatedBy: createdBy,
}
return tx.Create(&newRecord).Error
}
func seedWarehouses(tx *gorm.DB, createdBy uint, areas map[string]uint, locations map[string]uint, kandangs map[string]uint) error {
seeds := []struct {
Name string