diff --git a/lib/wish/wishlist.ex b/lib/wish/wishlist.ex index d53be3a..b550900 100644 --- a/lib/wish/wishlist.ex +++ b/lib/wish/wishlist.ex @@ -101,4 +101,19 @@ defmodule Wish.Wishlist do def change_item(%Item{} = item, attrs \\ %{}) do Item.changeset(item, attrs) end + + @doc """ + Toggles the "received" state of an item. + + ## Examples + + iex> toggle_received(item) + {:ok, %Item{}} + + """ + + def toggle_received(%Item{} = item) do + Item.toggle_received_changeset(item) + |> Repo.update() + end end diff --git a/lib/wish/wishlist/item.ex b/lib/wish/wishlist/item.ex index 45b211e..341c38b 100644 --- a/lib/wish/wishlist/item.ex +++ b/lib/wish/wishlist/item.ex @@ -19,4 +19,9 @@ defmodule Wish.Wishlist.Item do |> cast(attrs, [:title, :description, :url, :received, :desire, :image_url]) |> validate_required([:url]) end + + def toggle_received_changeset(item) do + new_state = !item.received + change(item, received: new_state) + end end diff --git a/lib/wish_web/live/home_live/details.ex b/lib/wish_web/live/home_live/details.ex index 948ed1e..3c7c562 100644 --- a/lib/wish_web/live/home_live/details.ex +++ b/lib/wish_web/live/home_live/details.ex @@ -3,13 +3,28 @@ defmodule WishWeb.HomeLive.Details do alias Wish.Wishlist + @impl true def mount(_params, _session, socket) do {:ok, socket} end + @impl true def handle_params(%{"id" => id}, _, socket) do {:noreply, socket |> assign(:item, Wishlist.get_item!(id))} end + + @impl true + def handle_event("toggle_received", %{"id" => id}, socket) do + item = Wishlist.get_item!(id) + + case Wishlist.toggle_received(item) do + {:ok, updated_item} -> + {:noreply, assign(socket, :item, updated_item)} + + {:error, _} -> + {:noreply, socket} + end + end end diff --git a/lib/wish_web/live/home_live/details.html.heex b/lib/wish_web/live/home_live/details.html.heex index f0f9d1d..297cad8 100644 --- a/lib/wish_web/live/home_live/details.html.heex +++ b/lib/wish_web/live/home_live/details.html.heex @@ -8,3 +8,7 @@