fix user update role and department

This commit is contained in:
efrilm
2025-10-03 13:40:49 +07:00
parent 89d6d8df5e
commit d8942fa918
5 changed files with 51 additions and 9 deletions
+6
View File
@@ -136,6 +136,12 @@ func (p *UserProcessorImpl) UpdateUser(ctx context.Context, id uuid.UUID, req *c
}
}
if req.Role != nil {
if err := p.userRoleProc.ReplaceUserRole(ctx, updated.ID, *req.Role); err != nil {
return nil, fmt.Errorf("failed to assign role to user: %w", err)
}
}
// Update departments if provided
if req.DepartmentIDs != nil {
departments := make([]entities.Department, len(*req.DepartmentIDs))
+34
View File
@@ -15,6 +15,7 @@ type UserRoleProcessor interface {
RemoveRoleFromUser(ctx context.Context, userID, roleID uuid.UUID) error
GetUserRoles(ctx context.Context, userID uuid.UUID) ([]entities.Role, error)
HasRole(ctx context.Context, userID uuid.UUID, roleCode string) (bool, error)
ReplaceUserRole(ctx context.Context, userID, roleID uuid.UUID) error
}
type UserRoleProcessorImpl struct {
@@ -94,4 +95,37 @@ func (p *UserRoleProcessorImpl) HasRole(ctx context.Context, userID uuid.UUID, r
}
return count > 0, nil
}
func (p *UserRoleProcessorImpl) ReplaceUserRole(ctx context.Context, userID uuid.UUID, roleID uuid.UUID) error {
return p.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
// Delete old role
if err := tx.Where("user_id = ?", userID).
Delete(&UserRoleEntry{}).Error; err != nil {
return err
}
// Check if new role already exists
var existingEntry UserRoleEntry
err := tx.Where("user_id = ?", userID).
First(&existingEntry).Error
if err == nil {
// Role already assigned
return nil
}
if err != gorm.ErrRecordNotFound {
return err
}
// Assign new role
newEntry := UserRoleEntry{
UserID: userID,
RoleID: roleID,
AssignedAt: time.Now(),
}
return tx.Create(&newEntry).Error
})
}