exmr/lib/exmr_web/live/exam_live/index.ex
Vladimir Rubin 1ccab387a9
Some checks failed
Build and Push Docker Image / Build and Push Image (push) Waiting to run
Checks / check (push) Has been cancelled
fix: wrong day of the week + calendar not updating
2024-12-23 19:45:10 +02:00

91 lines
2.2 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])
|> assign(events: Enum.group_by(Exams.list_exams(), & &1.date))
{: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)
|> 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
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