class TasksController < ApplicationController before_action :require_current_project! before_action :set_task, only: %i[show edit update destroy complete] before_action :load_form_data, only: %i[new create edit update] def index @page_title = "Task" tasks = tasks_for_current_project @overdue_tasks = tasks.overdue.includes(:organization, :contact, :assigned_user).ordered @today_tasks = tasks.due_today.includes(:organization, :contact, :assigned_user).ordered @upcoming_tasks = tasks.upcoming(30).includes(:organization, :contact, :assigned_user).ordered @completed_tasks = tasks.completed.includes(:organization).order(completed_at: :desc).limit(20) end def show redirect_to @task.organization end def new @page_title = "Nuovo task" @task = Task.new( organization_id: params[:organization_id], opportunity_id: params[:opportunity_id], contact_id: params[:contact_id], assigned_user: current_user, due_at: 1.day.from_now.change(hour: 10), priority: "normal", task_type: params[:task_type].presence || "follow_up" ) end def create @task = Task.new(task_params) if @task.save redirect_to(@task.organization || tasks_path, notice: "Task creato.") else render :new, status: :unprocessable_entity end end def edit @page_title = "Modifica task" end def update if @task.update(task_params) redirect_to @task.organization, notice: "Task aggiornato." else render :edit, status: :unprocessable_entity end end def destroy org = @task.organization @task.destroy! redirect_to org, notice: "Task eliminato." end def complete if @task.complete!(user: current_user) redirect_back fallback_location: today_path, notice: "Task completato." else redirect_back fallback_location: today_path, alert: "Il task non può essere completato." end end private def set_task @task = Task.find(params[:id]) end def load_form_data @organizations = organizations_for_current_project.order(:name) @users = User.active.order(:first_name) end def task_params params.require(:task).permit( :title, :description, :organization_id, :contact_id, :opportunity_id, :assigned_user_id, :due_at, :priority, :task_type, :status ) end end