exmr/lib/exmr_web/live/exam_live/index.ex

92 lines
2.2 KiB
Elixir
Raw Permalink Normal View History

2024-11-14 23:33:29 +02:00
defmodule ExmrWeb.ExamLive.Index do
use ExmrWeb, :live_view
alias Exmr.Exams
alias Exmr.Exams.Exam
@impl true
def mount(_params, _session, socket) do
socket =
socket
|> assign(:exams, Exams.list_exams())
|> assign(:sort_by, "date")
2024-11-27 18:02:28 +02:00
|> assign(:live_action, :index)
|> assign(exam: %{})
2024-12-22 22:52:30 +02:00
|> assign(events: Enum.group_by(Exams.list_exams(), & &1.date))
|> assign(current_month: Date.utc_today())
{:ok, socket}
2024-11-14 23:33:29 +02:00
end
@impl true
def handle_params(params, _url, socket) do
{:noreply, apply_action(socket, socket.assigns.live_action, params)}
end
defp apply_action(socket, :edit, %{"id" => id}) do
socket
|> assign(:page_title, "Edit Exam")
|> assign(:exam, Exams.get_exam!(id))
end
defp apply_action(socket, :new, _params) do
socket
|> assign(:page_title, gettext("New Exam"))
2024-11-14 23:33:29 +02:00
|> assign(:exam, %Exam{})
end
defp apply_action(socket, :index, _params) do
socket
|> assign(:page_title, "Listing Exams")
|> assign(:exam, nil)
end
@impl true
def handle_info({ExmrWeb.ExamLive.FormComponent, {:saved, exam}}, socket) do
socket =
socket
|> assign(:exams, [exam | socket.assigns.exams])
|> assign(events: Enum.group_by(Exams.list_exams(), & &1.date))
{:noreply, socket}
2024-11-14 23:33:29 +02:00
end
@impl true
def handle_event("remove", %{"id" => id}, socket) do
2024-11-14 23:33:29 +02:00
exam = Exams.get_exam!(id)
{:ok, _} = Exams.delete_exam(exam)
socket =
socket
|> update(:exams, fn exams ->
Enum.reject(exams, fn l -> l.id == exam.id end)
end)
|> assign(events: Enum.group_by(Exams.list_exams(), & &1.date))
{:noreply, socket}
end
def handle_event("sort", %{"by" => sort_by}, socket) do
exams = sort_items(socket.assigns.exams, sort_by)
{:noreply, assign(socket, exams: exams, sort_by: sort_by)}
end
2024-11-27 18:02:28 +02:00
def handle_event("edit", %{"id" => id}, socket) do
exam = Exams.get_exam!(id)
socket =
socket
|> assign(live_action: :edit, exam: exam)
{:noreply, socket}
end
defp sort_items(items, "subject") do
Enum.sort_by(items, & &1.subject)
end
defp sort_items(items, "date") do
Enum.sort_by(items, & &1.date, &Date.before?/2)
2024-11-14 23:33:29 +02:00
end
end