class UsersController < ApplicationController before_action :require_admin before_action :set_user, only: %i[edit update destroy] before_action :load_projects, only: %i[new create edit update] def index @page_title = "Utenti" @users = User.includes(user_projects: :project).order(:first_name, :last_name) end def new @page_title = "Nuovo utente" @user = User.new(role: "user", active: true) end def create @page_title = "Nuovo utente" @user = User.new(user_params) if @user.save sync_user_projects!(@user, params[:project_ids]) unless @user.admin? redirect_to users_path, notice: "Utente creato." else render :new, status: :unprocessable_entity end end def edit @page_title = "Modifica utente" end def update @page_title = "Modifica utente" attrs = user_params attrs.delete(:password) if attrs[:password].blank? attrs.delete(:password_confirmation) if attrs[:password].blank? attrs[:active] = ActiveModel::Type::Boolean.new.cast(attrs[:active]) if attrs.key?(:active) if @user.update(attrs) sync_user_projects!(@user, params[:project_ids]) if !@user.admin? && params.key?(:project_ids) notice = if @user.saved_change_to_active? @user.active? ? "#{@user.full_name} riabilitato." : "#{@user.full_name} disabilitato." else "Utente aggiornato." end redirect_to users_path, notice: notice else render :edit, status: :unprocessable_entity end end def destroy if @user == current_user redirect_to users_path, alert: "Non puoi eliminare il tuo account." and return end unless @user.can_be_destroyed? redirect_to users_path, alert: "Non puoi eliminare l'unico amministratore attivo." and return end name = @user.full_name @user.destroy! redirect_to users_path, notice: "#{name} eliminato." end private def set_user @user = User.find(params[:id]) end def load_projects @projects = Project.ordered end def user_params params.require(:user).permit(:email, :first_name, :last_name, :role, :password, :password_confirmation, :active) end def sync_user_projects!(user, selected_ids) selected_ids = Array(selected_ids).map(&:presence).compact.map(&:to_i) Project.find_each do |project| up = user.user_projects.find_or_initialize_by(project: project) up.enabled = selected_ids.include?(project.id) up.save! end end end