bones73k/lib/bones73k_web/live/property_live/index.ex

91 lines
2.4 KiB
Elixir
Raw Normal View History

2021-02-24 07:49:39 -05:00
defmodule Bones73kWeb.PropertyLive.Index do
use Bones73kWeb, :live_view
2020-09-14 12:22:25 -04:00
2021-02-24 07:49:39 -05:00
alias Bones73k.Properties
alias Bones73k.Properties.Property
alias Bones73kWeb.Roles
2020-09-14 12:22:25 -04:00
@impl true
2020-09-14 19:45:56 -04:00
def mount(_params, session, socket) do
socket = assign_defaults(socket, session)
{:ok, assign(socket, :properties, [])}
2020-09-14 12:22:25 -04:00
end
@impl true
def handle_params(params, _url, socket) do
current_user = socket.assigns.current_user
live_action = socket.assigns.live_action
property = property_from_params(params)
if Roles.can?(current_user, property, live_action) do
socket
|> assign(:properties, list_properties())
|> assign(:modal_return_to, Routes.property_index_path(socket, :index))
|> apply_action(live_action, params)
|> live_noreply()
else
socket
|> put_flash(:error, "Unauthorised")
|> redirect(to: "/")
|> live_noreply()
end
2020-09-14 12:22:25 -04:00
end
defp apply_action(socket, :edit, %{"id" => id}) do
socket
|> assign(:page_title, "Edit Property")
|> assign(:property, Properties.get_property!(id))
end
defp apply_action(socket, :new, _params) do
socket
|> assign(:page_title, "New Property")
|> assign(:property, %Property{})
end
defp apply_action(socket, :index, _params) do
socket
|> assign(:page_title, "Listing Properties")
|> assign(:property, nil)
end
@impl true
def handle_event("delete", %{"id" => id}, socket) do
current_user = socket.assigns.current_user
2020-09-14 12:22:25 -04:00
property = Properties.get_property!(id)
2021-02-24 07:49:39 -05:00
if Bones73kWeb.Roles.can?(current_user, property, :delete) do
property = Properties.get_property!(id)
{:ok, _} = Properties.delete_property(property)
{:noreply, assign(socket, :properties, list_properties())}
else
{:noreply,
socket
|> put_flash(:error, "Unauthorised")
|> redirect(to: "/")}
end
2020-09-14 12:22:25 -04:00
end
@impl true
def handle_info({:close_modal, _}, %{assigns: %{modal_return_to: to}} = socket) do
socket |> copy_flash() |> push_patch(to: to) |> live_noreply()
end
@impl true
def handle_info({:put_flash_message, {flash_type, msg}}, socket) do
socket |> put_flash(flash_type, msg) |> live_noreply()
end
defp property_from_params(params)
defp property_from_params(%{"id" => id}),
do: Properties.get_property!(id)
defp property_from_params(_params), do: %Property{}
2020-09-14 12:22:25 -04:00
defp list_properties do
Properties.list_properties()
end
end