class ContactsController < ApplicationController before_action :require_current_project! before_action :set_contact, only: %i[show edit update destroy] before_action :load_organizations, only: %i[new create edit update] def index @page_title = "Contatti" scope = Contact.joins(:organization) .merge(organizations_for_current_project) .includes(:organization) .primary_first scope = scope.search(params[:q]) if params[:q].present? scope = scope.where(organization_id: params[:organization_id]) if params[:organization_id].present? @pagy, @contacts = pagy(scope, items: 30) respond_to do |format| format.html format.csv { send_data CsvExport.contacts(scope), filename: "contacts-#{Date.current}.csv" } end end def show @page_title = @contact.full_name end def new @page_title = "Nuovo contatto" @contact = Contact.new(organization_id: params[:organization_id], primary_contact: params[:primary].present?) end def create @contact = Contact.new(contact_params) if @contact.save redirect_to @contact.organization, notice: "Contatto creato." else render :new, status: :unprocessable_entity end end def edit @page_title = "Modifica #{@contact.full_name}" end def update if @contact.update(contact_params) redirect_to @contact.organization, notice: "Contatto aggiornato." else render :edit, status: :unprocessable_entity end end def destroy org = @contact.organization @contact.destroy! redirect_to org, notice: "Contatto eliminato." end private def set_contact @contact = Contact.find(params[:id]) end def load_organizations @organizations = organizations_for_current_project.order(:name) end def contact_params params.require(:contact).permit( :organization_id, :first_name, :last_name, :role, :email, :email_invalid, :bounced_email, :phone, :mobile, :preferred_contact_method, :notes, :primary_contact ) end end