89 lines
2.1 KiB
Elixir
89 lines
2.1 KiB
Elixir
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")
|
|
|> assign(:live_action, :index)
|
|
|> assign(exam: %{})
|
|
|> assign(events: Enum.group_by(Exams.list_exams(), & &1.date))
|
|
|> assign(current_month: Date.utc_today())
|
|
|
|
{:ok, socket}
|
|
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"))
|
|
|> 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])
|
|
|
|
{:noreply, socket}
|
|
end
|
|
|
|
@impl true
|
|
def handle_event("remove", %{"id" => id}, socket) do
|
|
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)
|
|
|
|
{: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
|
|
|
|
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)
|
|
end
|
|
end
|