Commit 87c51ee9b48d43e883b506e0eea810c4f8d48826

Thomas de Grivel 2022-08-02T17:48:51

show slug errors

diff --git a/lib/kmxgit/user_manager.ex b/lib/kmxgit/user_manager.ex
index 31e5910..0e16cdc 100644
--- a/lib/kmxgit/user_manager.ex
+++ b/lib/kmxgit/user_manager.ex
@@ -281,9 +281,10 @@ defmodule Kmxgit.UserManager do
   end
 
   def admin_create_user(attrs \\ %{}) do
-    %User{}
-    |> User.admin_create_user_changeset(attrs)
-    |> Repo.insert()
+    changeset = User.admin_create_user_changeset(%User{}, attrs)
+    with {:ok, user} <- Repo.insert(changeset) do
+      {:ok, user, changeset}
+    end
   end
 
   def update_user(%User{} = user, attrs) do
diff --git a/lib/kmxgit_web/controllers/page_controller.ex b/lib/kmxgit_web/controllers/page_controller.ex
index 02a97c5..6140a29 100644
--- a/lib/kmxgit_web/controllers/page_controller.ex
+++ b/lib/kmxgit_web/controllers/page_controller.ex
@@ -74,13 +74,19 @@ defmodule KmxgitWeb.PageController do
       user_params = Map.merge(params["user"], %{"is_admin" => true})
       case Repo.transaction(fn ->
             case UserManager.admin_create_user(user_params) do
-              {:ok, user} ->
+              {:ok, user, changeset} ->
                 case SlugManager.create_slug(user) do
                   {:ok, _slug} -> user
-                  {:error, changeset} -> Repo.rollback(changeset)
+                  {:error, changeset1} ->
+                    IO.inspect(changeset1)
+                    changeset
+                    |> Map.put(:action, :insert)
+                    |> Ecto.Changeset.add_error(:slug_, "is already taken", [constraint: :unique, constraint_name: "slugs_slug_index"])
+                    |> Repo.rollback()
                 end
-              {:error, changeset} ->
-                Repo.rollback(changeset)
+              {:error, changeset1} ->
+                IO.inspect(changeset1)
+                Repo.rollback(changeset1)
             end
           end) do
         {:ok, user} ->
diff --git a/lib/kmxgit_web/templates/page/new_admin.html.heex b/lib/kmxgit_web/templates/page/new_admin.html.heex
index 9c3364e..432d330 100644
--- a/lib/kmxgit_web/templates/page/new_admin.html.heex
+++ b/lib/kmxgit_web/templates/page/new_admin.html.heex
@@ -9,6 +9,12 @@
     <%= gettext "Please create an administrator account." %>
   </p>
   
+  <%= if @changeset.action do %>
+    <div class="alert alert-danger">
+      <p>Oops, something went wrong! Please check the errors below.</p>
+    </div>
+  <% end %>
+
   <%= form_for @changeset, @action, fn f -> %>
 
     <div class="mb-3">