fix user update role and department
This commit is contained in:
@@ -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))
|
||||
|
||||
@@ -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
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user