mirror of
https://gitlab.com/mbugroup/lti-api.git
synced 2026-05-20 13:31:56 +00:00
Merge branch 'feat/BE/Sprint-5' into 'feat/BE/US-159,160/marketing'
# Conflicts: # internal/modules/production/project_flocks/controllers/projectflock.controller.go # internal/modules/production/project_flocks/dto/projectflock.dto.go # internal/modules/production/project_flocks/route.go # internal/modules/production/transfer_layings/dto/transfer_laying.dto.go
This commit is contained in:
@@ -36,7 +36,8 @@ type ProjectflockService interface {
|
||||
GetAvailableDocQuantity(ctx *fiber.Ctx, kandangID uint) (float64, error)
|
||||
DeleteOne(ctx *fiber.Ctx, id uint) error
|
||||
GetProjectFlockKandangByProjectAndKandang(ctx *fiber.Ctx, projectFlockID uint, kandangID uint) (*entity.ProjectFlockKandang, float64, error)
|
||||
GetFlockPeriodSummary(ctx *fiber.Ctx, flockID uint) (*FlockPeriodSummary, error)
|
||||
GetFlockPeriodSummary(ctx *fiber.Ctx, locationID uint) ([]KandangPeriodSummary, error)
|
||||
GetProjectPeriods(ctx *fiber.Ctx, projectIDs []uint) (map[uint]int, error)
|
||||
Approval(ctx *fiber.Ctx, req *validation.Approve) ([]entity.ProjectFlock, error)
|
||||
}
|
||||
|
||||
@@ -53,9 +54,10 @@ type projectflockService struct {
|
||||
approvalWorkflow approvalutils.ApprovalWorkflowKey
|
||||
}
|
||||
|
||||
type FlockPeriodSummary struct {
|
||||
Flock entity.Flock
|
||||
NextPeriod int
|
||||
type KandangPeriodSummary struct {
|
||||
Id uint
|
||||
Name string
|
||||
Period int
|
||||
}
|
||||
|
||||
func NewProjectflockService(
|
||||
@@ -283,6 +285,11 @@ func (s *projectflockService) CreateOne(c *fiber.Ctx, req *validation.Create) (*
|
||||
if len(kandangs) != len(kandangIDs) {
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, "Some kandangs not found")
|
||||
}
|
||||
for _, kandang := range kandangs {
|
||||
if kandang.LocationId != req.LocationId {
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("Kandang %d tidak berada pada lokasi yang sama dengan project flock", kandang.Id))
|
||||
}
|
||||
}
|
||||
// larang kalau ada yg sudah terikat ke project lain
|
||||
if linked, err := s.pivotRepo().HasKandangsLinkedToOtherProject(c.Context(), kandangIDs, nil); err != nil {
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to validate kandangs linkage")
|
||||
@@ -301,22 +308,24 @@ func (s *projectflockService) CreateOne(c *fiber.Ctx, req *validation.Create) (*
|
||||
err = s.Repository.DB().WithContext(c.Context()).Transaction(func(dbTransaction *gorm.DB) error {
|
||||
projectRepo := repository.NewProjectflockRepository(dbTransaction)
|
||||
|
||||
nextSeq, err := projectRepo.GetNextSequenceForBase(c.Context(), canonicalBase)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
generatedName, seq, err := s.generateSequentialFlockName(c.Context(), projectRepo, canonicalBase, nextSeq, nil)
|
||||
// Generate unique flock name (sequential per base name, starting from 1)
|
||||
generatedName, _, err := s.generateSequentialFlockName(c.Context(), projectRepo, canonicalBase, 1, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
createBody.FlockName = generatedName
|
||||
createBody.Period = seq
|
||||
|
||||
if err := projectRepo.CreateOne(c.Context(), createBody, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := s.attachKandangs(c.Context(), dbTransaction, createBody.Id, kandangIDs); err != nil {
|
||||
// Compute period based on location history (max period in that location + 1),
|
||||
// and store it on project_flock_kandangs only.
|
||||
nextPeriod, err := s.nextLocationPeriod(c.Context(), dbTransaction, req.LocationId)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.attachKandangs(c.Context(), dbTransaction, createBody.Id, kandangIDs, nextPeriod); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -452,6 +461,15 @@ func (s projectflockService) UpdateOne(c *fiber.Ctx, req *validation.Update, id
|
||||
if len(kandangs) != len(newKandangIDs) {
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, "Some kandangs not found")
|
||||
}
|
||||
targetLocationID := existing.LocationId
|
||||
if req.LocationId != nil && *req.LocationId > 0 {
|
||||
targetLocationID = *req.LocationId
|
||||
}
|
||||
for _, kandang := range kandangs {
|
||||
if kandang.LocationId != targetLocationID {
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("Kandang %d tidak berada pada lokasi yang sama dengan project flock", kandang.Id))
|
||||
}
|
||||
}
|
||||
if linked, err := s.pivotRepo().HasKandangsLinkedToOtherProject(c.Context(), newKandangIDs, &id); err != nil {
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to validate kandangs linkage")
|
||||
} else if linked {
|
||||
@@ -477,18 +495,11 @@ func (s projectflockService) UpdateOne(c *fiber.Ctx, req *validation.Update, id
|
||||
}
|
||||
|
||||
if needFlockNameRegenerate {
|
||||
nextSeq, err := projectRepo.GetNextSequenceForBase(c.Context(), baseForGeneration)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
newName, seq, err := s.generateSequentialFlockName(c.Context(), projectRepo, baseForGeneration, nextSeq, &id)
|
||||
newName, _, err := s.generateSequentialFlockName(c.Context(), projectRepo, baseForGeneration, 1, &id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
updateBody["flock_name"] = newName
|
||||
if seq != existing.Period {
|
||||
updateBody["period"] = seq
|
||||
}
|
||||
}
|
||||
|
||||
if len(updateBody) > 0 {
|
||||
@@ -532,7 +543,19 @@ func (s projectflockService) UpdateOne(c *fiber.Ctx, req *validation.Update, id
|
||||
}
|
||||
|
||||
if len(toAttach) > 0 {
|
||||
if err := s.attachKandangs(c.Context(), dbTransaction, id, toAttach); err != nil {
|
||||
var currentPeriod int
|
||||
if err := dbTransaction.WithContext(c.Context()).
|
||||
Table("project_flock_kandangs").
|
||||
Where("project_flock_id = ?", id).
|
||||
Select("COALESCE(MAX(period), 0)").
|
||||
Scan(¤tPeriod).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if currentPeriod <= 0 {
|
||||
currentPeriod = 1
|
||||
}
|
||||
|
||||
if err := s.attachKandangs(c.Context(), dbTransaction, id, toAttach, currentPeriod); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -808,57 +831,90 @@ func (s projectflockService) GetAvailableDocQuantity(ctx *fiber.Ctx, kandangID u
|
||||
return total, nil
|
||||
}
|
||||
|
||||
func (s projectflockService) GetFlockPeriodSummary(c *fiber.Ctx, projectFlockKandangID uint) (*FlockPeriodSummary, error) {
|
||||
if projectFlockKandangID == 0 {
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, "project_flock_kandang_id is required")
|
||||
// nextLocationPeriod computes the next period number for a given location
|
||||
// based on the maximum period that has ever been used by any kandang in that location.
|
||||
func (s projectflockService) nextLocationPeriod(ctx context.Context, tx *gorm.DB, locationID uint) (int, error) {
|
||||
if locationID == 0 {
|
||||
return 0, fiber.NewError(fiber.StatusBadRequest, "location_id is required to compute period")
|
||||
}
|
||||
|
||||
pivot, err := s.pivotRepo().GetByID(c.Context(), projectFlockKandangID)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, "Project flock kandang not found")
|
||||
db := s.Repository.DB()
|
||||
if tx != nil {
|
||||
db = tx
|
||||
}
|
||||
|
||||
var maxPeriod int
|
||||
if err := db.WithContext(ctx).
|
||||
Table("project_flock_kandangs pfk").
|
||||
Joins("JOIN kandangs k ON k.id = pfk.kandang_id").
|
||||
Where("k.location_id = ?", locationID).
|
||||
Select("COALESCE(MAX(pfk.period), 0)").
|
||||
Scan(&maxPeriod).Error; err != nil {
|
||||
s.Log.Errorf("Failed to compute max period for location %d: %+v", locationID, err)
|
||||
return 0, fiber.NewError(fiber.StatusInternalServerError, "Failed to compute period for location")
|
||||
}
|
||||
|
||||
return maxPeriod + 1, nil
|
||||
}
|
||||
|
||||
func (s projectflockService) GetProjectPeriods(c *fiber.Ctx, projectIDs []uint) (map[uint]int, error) {
|
||||
if len(projectIDs) == 0 {
|
||||
return map[uint]int{}, nil
|
||||
}
|
||||
return s.pivotRepo().ProjectPeriodsByProjectIDs(c.Context(), projectIDs)
|
||||
}
|
||||
|
||||
func (s projectflockService) GetFlockPeriodSummary(c *fiber.Ctx, locationID uint) ([]KandangPeriodSummary, error) {
|
||||
if locationID == 0 {
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, "location_id is required")
|
||||
}
|
||||
|
||||
exists, err := s.Repository.LocationExists(c.Context(), locationID)
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed to fetch project_flock_kandang %d: %+v", projectFlockKandangID, err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch project flock kandang")
|
||||
s.Log.Errorf("Failed to validate location %d: %+v", locationID, err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to validate location")
|
||||
}
|
||||
if !exists {
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, "Location not found")
|
||||
}
|
||||
|
||||
var baseName string
|
||||
var referenceFlock *entity.Flock
|
||||
if pivot.ProjectFlock.Id != 0 {
|
||||
baseName = pfutils.DeriveBaseName(pivot.ProjectFlock.FlockName)
|
||||
type kandangPeriodRow struct {
|
||||
Id uint
|
||||
Name string
|
||||
LatestPeriod int
|
||||
}
|
||||
|
||||
if strings.TrimSpace(baseName) != "" {
|
||||
referenceFlock, err = s.FlockRepo.GetByName(c.Context(), baseName)
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
s.Log.Errorf("Failed to fetch flock %q: %+v", baseName, err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch flock")
|
||||
}
|
||||
var rows []kandangPeriodRow
|
||||
|
||||
db := s.Repository.DB().WithContext(c.Context())
|
||||
if err := db.
|
||||
Table("kandangs AS k").
|
||||
Select("k.id, k.name, COALESCE(MAX(pfk.period), 0) AS latest_period").
|
||||
Joins("LEFT JOIN project_flock_kandangs AS pfk ON pfk.kandang_id = k.id").
|
||||
Where("k.location_id = ?", locationID).
|
||||
Where("k.deleted_at IS NULL").
|
||||
Group("k.id, k.name").
|
||||
Order("k.id ASC").
|
||||
Scan(&rows).Error; err != nil {
|
||||
s.Log.Errorf("Failed to fetch kandang period summary for location %d: %+v", locationID, err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch kandang period summary")
|
||||
}
|
||||
|
||||
if referenceFlock == nil {
|
||||
referenceFlock = &entity.Flock{Name: pivot.ProjectFlock.FlockName}
|
||||
}
|
||||
|
||||
maxPeriod := pivot.ProjectFlock.Period
|
||||
if strings.TrimSpace(baseName) != "" {
|
||||
if headerMax, err := s.Repository.GetMaxPeriodByBaseName(c.Context(), baseName); err != nil {
|
||||
s.Log.Warnf("Unable to compute header period for base %q: %+v", baseName, err)
|
||||
} else if headerMax > maxPeriod {
|
||||
maxPeriod = headerMax
|
||||
summaries := make([]KandangPeriodSummary, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
nextPeriod := 0
|
||||
if row.LatestPeriod > 0 {
|
||||
nextPeriod = row.LatestPeriod + 1
|
||||
}
|
||||
|
||||
if pivotMax, err := s.pivotRepo().MaxPeriodByBaseName(c.Context(), baseName); err != nil {
|
||||
s.Log.Warnf("Unable to compute pivot period for base %q: %+v", baseName, err)
|
||||
} else if pivotMax > maxPeriod {
|
||||
maxPeriod = pivotMax
|
||||
}
|
||||
summaries = append(summaries, KandangPeriodSummary{
|
||||
Id: row.Id,
|
||||
Name: row.Name,
|
||||
Period: nextPeriod,
|
||||
})
|
||||
}
|
||||
|
||||
return &FlockPeriodSummary{
|
||||
Flock: *referenceFlock,
|
||||
NextPeriod: maxPeriod + 1,
|
||||
}, nil
|
||||
return summaries, nil
|
||||
}
|
||||
|
||||
func uniqueUintSlice(values []uint) []uint {
|
||||
@@ -934,7 +990,7 @@ func (s projectflockService) ensureFlockByName(ctx context.Context, actorID uint
|
||||
return newFlock, nil
|
||||
}
|
||||
|
||||
func (s projectflockService) attachKandangs(ctx context.Context, dbTransaction *gorm.DB, projectFlockID uint, kandangIDs []uint) error {
|
||||
func (s projectflockService) attachKandangs(ctx context.Context, dbTransaction *gorm.DB, projectFlockID uint, kandangIDs []uint, period int) error {
|
||||
if len(kandangIDs) == 0 {
|
||||
return nil
|
||||
}
|
||||
@@ -972,6 +1028,7 @@ func (s projectflockService) attachKandangs(ctx context.Context, dbTransaction *
|
||||
records = append(records, &entity.ProjectFlockKandang{
|
||||
ProjectFlockId: projectFlockID,
|
||||
KandangId: id,
|
||||
Period: period,
|
||||
})
|
||||
}
|
||||
if err := s.pivotRepoWithTx(dbTransaction).CreateMany(ctx, records); err != nil {
|
||||
|
||||
Reference in New Issue
Block a user