feat: prevent deletion of roles with assigned users
This commit is contained in:
parent
954fc4261a
commit
b638a54bd6
5 changed files with 89 additions and 30 deletions
|
|
@ -62,25 +62,40 @@ defmodule MvWeb.RoleLive.Index do
|
|||
@impl true
|
||||
def handle_event("delete", %{"id" => id}, socket) do
|
||||
{:ok, role} = Authorization.get_role(id)
|
||||
user_count = get_user_count(role, socket.assigns.user_counts)
|
||||
|
||||
case Authorization.destroy_role(role) do
|
||||
:ok ->
|
||||
updated_roles = Enum.reject(socket.assigns.roles, &(&1.id == id))
|
||||
if user_count > 0 do
|
||||
{:noreply,
|
||||
put_flash(
|
||||
socket,
|
||||
:error,
|
||||
gettext(
|
||||
"Cannot delete role. %{count} user(s) are still assigned to this role. Please assign them to another role first.",
|
||||
count: user_count
|
||||
)
|
||||
)}
|
||||
else
|
||||
case Authorization.destroy_role(role) do
|
||||
:ok ->
|
||||
updated_roles = Enum.reject(socket.assigns.roles, &(&1.id == id))
|
||||
updated_counts = Map.delete(socket.assigns.user_counts, id)
|
||||
|
||||
{:noreply,
|
||||
socket
|
||||
|> assign(:roles, updated_roles)
|
||||
|> put_flash(:info, gettext("Role deleted successfully"))}
|
||||
{:noreply,
|
||||
socket
|
||||
|> assign(:roles, updated_roles)
|
||||
|> assign(:user_counts, updated_counts)
|
||||
|> put_flash(:info, gettext("Role deleted successfully"))}
|
||||
|
||||
{:error, error} ->
|
||||
error_message = format_error(error)
|
||||
{:error, error} ->
|
||||
error_message = format_error(error)
|
||||
|
||||
{:noreply,
|
||||
put_flash(
|
||||
socket,
|
||||
:error,
|
||||
gettext("Failed to delete role: %{error}", error: error_message)
|
||||
)}
|
||||
{:noreply,
|
||||
put_flash(
|
||||
socket,
|
||||
:error,
|
||||
gettext("Failed to delete role: %{error}", error: error_message)
|
||||
)}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue