fix(BE): merge conflict

This commit is contained in:
Hafizh A. Y
2025-10-21 15:11:04 +07:00
parent 55b14f5fc7
commit e4799fa2dd
8 changed files with 216 additions and 117 deletions
@@ -38,7 +38,7 @@ type projectflockService struct {
Repository repository.ProjectflockRepository
FlockRepo flockRepository.FlockRepository
KandangRepo kandangRepository.KandangRepository
PivotRepo repository.ProjectFlockKandangRepository
PivotRepo repository.ProjectFlockKandangRepository
ApprovalSvc commonSvc.ApprovalService
approvalWorkflow approvalutils.ApprovalWorkflowKey
}
@@ -62,7 +62,7 @@ func NewProjectflockService(
Repository: repo,
FlockRepo: flockRepo,
KandangRepo: kandangRepo,
PivotRepo: pivotRepo,
PivotRepo: pivotRepo,
ApprovalSvc: approvalSvc,
approvalWorkflow: utils.ApprovalWorkflowProjectFlock,
}
@@ -260,13 +260,11 @@ func (s *projectflockService) CreateOne(c *fiber.Ctx, req *validation.Create) (*
Category: string(category),
FcrId: req.FcrId,
LocationId: req.LocationId,
Period: nextPeriod,
CreatedBy: 1,
}
err = s.Repository.DB().WithContext(c.Context()).Transaction(func(tx *gorm.DB) error {
projectRepo := repository.NewProjectflockRepository(tx)
// kandangRepo := kandangRepository.NewKandangRepository(tx)
err = s.Repository.DB().WithContext(c.Context()).Transaction(func(dbTransaction *gorm.DB) error {
projectRepo := repository.NewProjectflockRepository(dbTransaction)
period, err := projectRepo.GetNextPeriodForFlock(c.Context(), req.FlockId)
if err != nil {
@@ -278,33 +276,13 @@ func (s *projectflockService) CreateOne(c *fiber.Ctx, req *validation.Create) (*
return err
}
// kandangUpdates := make([]*entity.Kandang, len(kandangs))
// for i := range kandangs {
// kandangs[i].ProjectFlockId = &createBody.Id
// kandangUpdates[i] = &kandangs[i]
// }
// if err := kandangRepo.UpdateMany(
// c.Context(),
// kandangUpdates,
// func(db *gorm.DB) *gorm.DB {
// return db.Select("project_flock_id")
// },
// ); err != nil {
// return err
// }
if err := tx.Model(&entity.Kandang{}).
Where("id IN ?", kandangIDs).
Updates(map[string]any{
"project_flock_id": createBody.Id,
"status": string(utils.KandangStatusPengajuan),
}).Error; err != nil {
if err := s.attachKandangs(c.Context(), dbTransaction, createBody.Id, kandangIDs); err != nil {
return err
}
actorID := uint(1) //TODO: Change From Auth
action := entity.ApprovalActionCreated
approvalSvcTx := commonSvc.NewApprovalService(commonRepo.NewApprovalRepository(tx))
approvalSvcTx := commonSvc.NewApprovalService(commonRepo.NewApprovalRepository(dbTransaction))
_, err = approvalSvcTx.CreateApproval(
c.Context(),
utils.ApprovalWorkflowProjectFlock,
@@ -325,17 +303,6 @@ func (s *projectflockService) CreateOne(c *fiber.Ctx, req *validation.Create) (*
return nil, err
}
if err := s.attachKandangs(c.Context(), tx, createBody.Id, kandangIDs); err != nil {
tx.Rollback()
s.Log.Errorf("Failed to attach kandangs to projectflock %d: %+v", createBody.Id, err)
return nil, err
}
if err := tx.Commit().Error; err != nil {
tx.Rollback()
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to commit transaction")
}
return s.GetOne(c, createBody.Id)
}
@@ -399,10 +366,6 @@ func (s projectflockService) UpdateOne(c *fiber.Ctx, req *validation.Update, id
Exists: relationExistsChecker[entity.Location](s.Repository.DB()),
})
}
if req.Period != nil {
updateBody["period"] = *req.Period
hasBodyChanges = true
}
if len(relationChecks) > 0 {
if err := commonSvc.EnsureRelations(c.Context(), relationChecks...); err != nil {
@@ -440,8 +403,8 @@ func (s projectflockService) UpdateOne(c *fiber.Ctx, req *validation.Update, id
return s.GetOne(c, id)
}
err = s.Repository.DB().WithContext(c.Context()).Transaction(func(tx *gorm.DB) error {
projectRepo := repository.NewProjectflockRepository(tx)
err = s.Repository.DB().WithContext(c.Context()).Transaction(func(dbTransaction *gorm.DB) error {
projectRepo := repository.NewProjectflockRepository(dbTransaction)
if len(updateBody) > 0 {
if err := projectRepo.PatchOne(c.Context(), id, updateBody, nil); err != nil {
@@ -477,26 +440,136 @@ func (s projectflockService) UpdateOne(c *fiber.Ctx, req *validation.Update, id
}
}
if len(toDetach) > 0 {
if err := s.detachKandangs(c.Context(), tx, id, toDetach, false); err != nil {
tx.Rollback()
s.Log.Errorf("Failed to detach kandangs from projectflock %d: %+v", id, err)
return nil, err
if len(toDetach) > 0 {
if err := s.detachKandangs(c.Context(), dbTransaction, id, toDetach, true); err != nil {
return err
}
}
if len(toAttach) > 0 {
if err := s.attachKandangs(c.Context(), dbTransaction, id, toAttach); err != nil {
return err
}
}
}
if len(toAttach) > 0 {
if err := s.attachKandangs(c.Context(), tx, id, toAttach); err != nil {
tx.Rollback()
s.Log.Errorf("Failed to attach kandangs to projectflock %d: %+v", id, err)
return nil, err
if hasChanges {
actorID := uint(1) //TODO: Change From Auth
approvalSvc := commonSvc.NewApprovalService(commonRepo.NewApprovalRepository(dbTransaction))
if approvalSvc != nil {
latestBeforeReset, err := approvalSvc.LatestByTarget(c.Context(), s.approvalWorkflow, id, nil)
if err != nil {
return err
}
shouldRecordUpdate := latestBeforeReset == nil ||
latestBeforeReset.StepNumber != uint16(utils.ProjectFlockStepPengajuan) ||
latestBeforeReset.Action == nil ||
(latestBeforeReset.Action != nil && *latestBeforeReset.Action != entity.ApprovalActionUpdated)
if shouldRecordUpdate {
action := entity.ApprovalActionUpdated
if _, err := approvalSvc.CreateApproval(
c.Context(),
utils.ApprovalWorkflowProjectFlock,
id,
utils.ProjectFlockStepPengajuan,
&action,
actorID,
nil,
); err != nil {
return err
}
}
}
}
return nil
})
if err != nil {
if fiberErr, ok := err.(*fiber.Error); ok {
return nil, fiberErr
}
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fiber.NewError(fiber.StatusNotFound, "Projectflock not found")
}
s.Log.Errorf("Failed to update projectflock %d: %+v", id, err)
return nil, err
}
if err := tx.Commit().Error; err != nil {
tx.Rollback()
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to commit transaction")
return s.GetOne(c, id)
}
func (s projectflockService) Approval(c *fiber.Ctx, id uint, req *validation.Approve) (*entity.ProjectFlock, error) {
if err := s.Validate.Struct(req); err != nil {
return nil, err
}
project, err := s.GetOne(c, id)
if err != nil {
s.Log.Errorf("Failed to fetch projectflock %d before approval: %+v", id, err)
return nil, err
}
actorID := uint(1) // TODO: change from auth context
var action entity.ApprovalAction
switch strings.ToUpper(strings.TrimSpace(req.Action)) {
case string(entity.ApprovalActionRejected):
action = entity.ApprovalActionRejected
case string(entity.ApprovalActionApproved):
action = entity.ApprovalActionApproved
default:
return nil, fiber.NewError(fiber.StatusBadRequest, "action must be APPROVED or REJECTED")
}
step := utils.ProjectFlockStepPengajuan
if action == entity.ApprovalActionApproved {
step = utils.ProjectFlockStepAktif
}
err = s.Repository.DB().WithContext(c.Context()).Transaction(func(dbTransaction *gorm.DB) error {
approvalSvc := commonSvc.NewApprovalService(commonRepo.NewApprovalRepository(dbTransaction))
if _, err := approvalSvc.CreateApproval(
c.Context(),
utils.ApprovalWorkflowProjectFlock,
project.Id,
step,
&action,
actorID,
req.Notes,
); err != nil {
return err
}
kandangRepoTx := kandangRepository.NewKandangRepository(dbTransaction)
switch action {
case entity.ApprovalActionApproved:
if err := kandangRepoTx.UpdateStatusByProjectFlockID(
c.Context(),
project.Id,
utils.KandangStatusActive,
); err != nil {
return err
}
case entity.ApprovalActionRejected:
if err := kandangRepoTx.UpdateStatusByProjectFlockID(
c.Context(),
project.Id,
utils.KandangStatusNonActive,
); err != nil {
return err
}
}
return nil
})
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fiber.NewError(fiber.StatusNotFound, "Projectflock not found")
}
s.Log.Errorf("Failed to record approval for projectflock %d: %+v", id, err)
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to record approval")
}
return s.GetOne(c, id)
@@ -512,24 +585,18 @@ func (s projectflockService) DeleteOne(c *fiber.Ctx, id uint) error {
return fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch project flock")
}
tx := s.Repository.DB().Begin()
if tx.Error != nil {
return fiber.NewError(fiber.StatusInternalServerError, "Failed to start transaction")
}
if len(existing.Kandangs) > 0 {
ids := make([]uint, len(existing.Kandangs))
for i, k := range existing.Kandangs {
ids[i] = k.Id
err = s.Repository.DB().WithContext(c.Context()).Transaction(func(dbTransaction *gorm.DB) error {
if len(existing.Kandangs) > 0 {
ids := make([]uint, len(existing.Kandangs))
for i, k := range existing.Kandangs {
ids[i] = k.Id
}
if err := s.detachKandangs(c.Context(), dbTransaction, id, ids, true); err != nil {
return err
}
}
if err := s.detachKandangs(c.Context(), tx, id, ids, true); err != nil {
tx.Rollback()
s.Log.Errorf("Failed to detach kandangs before deleting projectflock %d: %+v", id, err)
return err
}
}
if err := repository.NewProjectflockRepository(tx).DeleteOne(c.Context(), id); err != nil {
if err := repository.NewProjectflockRepository(dbTransaction).DeleteOne(c.Context(), id); err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return fiber.NewError(fiber.StatusNotFound, "Projectflock not found")
}
@@ -627,12 +694,12 @@ func (s projectflockService) buildOrderExpressions(sortBy, sortOrder string) []s
}
}
func (s projectflockService) attachKandangs(ctx context.Context, tx *gorm.DB, projectFlockID uint, kandangIDs []uint) error {
func (s projectflockService) attachKandangs(ctx context.Context, dbTransaction *gorm.DB, projectFlockID uint, kandangIDs []uint) error {
if len(kandangIDs) == 0 {
return nil
}
if err := tx.Model(&entity.Kandang{}).
if err := dbTransaction.Model(&entity.Kandang{}).
Where("id IN ?", kandangIDs).
Updates(map[string]any{
"project_flock_id": projectFlockID,
@@ -641,7 +708,7 @@ func (s projectflockService) attachKandangs(ctx context.Context, tx *gorm.DB, pr
return fiber.NewError(fiber.StatusInternalServerError, "Failed to update kandangs")
}
pivotRepo := s.pivotRepoWithTx(tx)
pivotRepo := s.pivotRepoWithTx(dbTransaction)
records := make([]*entity.ProjectFlockKandang, len(kandangIDs))
for i, id := range kandangIDs {
records[i] = &entity.ProjectFlockKandang{
@@ -655,7 +722,7 @@ func (s projectflockService) attachKandangs(ctx context.Context, tx *gorm.DB, pr
return nil
}
func (s projectflockService) detachKandangs(ctx context.Context, tx *gorm.DB, projectFlockID uint, kandangIDs []uint, resetStatus bool) error {
func (s projectflockService) detachKandangs(ctx context.Context, dbTransaction *gorm.DB, projectFlockID uint, kandangIDs []uint, resetStatus bool) error {
if len(kandangIDs) == 0 {
return nil
}
@@ -665,21 +732,21 @@ func (s projectflockService) detachKandangs(ctx context.Context, tx *gorm.DB, pr
updates["status"] = string(utils.KandangStatusNonActive)
}
if err := tx.Model(&entity.Kandang{}).
if err := dbTransaction.Model(&entity.Kandang{}).
Where("id IN ?", kandangIDs).
Updates(updates).Error; err != nil {
return fiber.NewError(fiber.StatusInternalServerError, "Failed to update kandangs")
}
if err := s.pivotRepoWithTx(tx).DeleteMany(ctx, projectFlockID, kandangIDs); err != nil {
if err := s.pivotRepoWithTx(dbTransaction).DeleteMany(ctx, projectFlockID, kandangIDs); err != nil {
return fiber.NewError(fiber.StatusInternalServerError, "Failed to persist project flock history")
}
return nil
}
func (s projectflockService) pivotRepoWithTx(tx *gorm.DB) repository.ProjectFlockKandangRepository {
func (s projectflockService) pivotRepoWithTx(dbTransaction *gorm.DB) repository.ProjectFlockKandangRepository {
if s.PivotRepo == nil {
return repository.NewProjectFlockKandangRepository(tx)
return repository.NewProjectFlockKandangRepository(dbTransaction)
}
return s.PivotRepo.WithTx(tx)
return s.PivotRepo.WithTx(dbTransaction)
}