feat(BE-#270): Project flock period change to project_flock_kandangs

This commit is contained in:
ragilap
2025-11-18 12:26:54 +07:00
parent 02cc082d67
commit c2b60c1aff
15 changed files with 330 additions and 156 deletions
@@ -7,6 +7,7 @@ import (
"gitlab.com/mbugroup/lti-api.git/internal/common/repository"
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
"gitlab.com/mbugroup/lti-api.git/internal/utils"
"github.com/gofiber/fiber/v2"
"gorm.io/gorm"
)
@@ -115,9 +116,41 @@ func (r *KandangRepositoryImpl) UpsertProjectFlockKandang(ctx context.Context, p
Where("project_flock_id = ? AND kandang_id = ?", projectFlockID, kandangID).
First(&link).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
var project entity.ProjectFlock
if err := r.db.WithContext(ctx).
Select("id, location_id").
First(&project, projectFlockID).Error; err != nil {
return err
}
var kandang entity.Kandang
if err := r.db.WithContext(ctx).
Select("id, location_id").
First(&kandang, kandangID).Error; err != nil {
return err
}
if kandang.LocationId != project.LocationId {
return fiber.NewError(fiber.StatusBadRequest, "Kandang tidak berada pada lokasi yang sama dengan project flock")
}
// Determine project's period from existing pivot rows so the new kandang
// shares the same period.
var period int
if err := r.db.WithContext(ctx).
Table("project_flock_kandangs").
Where("project_flock_id = ?", projectFlockID).
Select("COALESCE(MAX(period), 0)").
Scan(&period).Error; err != nil {
return err
}
if period <= 0 {
period = 1
}
link = entity.ProjectFlockKandang{
ProjectFlockId: projectFlockID,
KandangId: kandangID,
Period: period,
}
return r.db.WithContext(ctx).Create(&link).Error
}