defmodule BloomWeb.API.CommunityController do use BloomWeb, :controller alias Bloom.{Repo, Sites, Taxonomy} alias Bloom.Taxonomy.Taxon alias BloomWeb.API.GardenJSON action_fallback BloomWeb.API.FallbackController def create(conn, %{"site_id" => site_id, "community" => attrs}) do scope = conn.assigns.current_scope with {:ok, community} <- Sites.create_community(scope, Sites.get_site!(scope, site_id), attrs) do conn |> put_status(:created) |> json(GardenJSON.community(Repo.preload(community, :plants))) end end def update(conn, %{"id" => id, "community" => attrs}) do scope = conn.assigns.current_scope with {:ok, community} <- Sites.update_community(scope, Sites.get_community!(scope, id), attrs) do json(conn, GardenJSON.community(community)) end end def delete(conn, %{"id" => id}) do scope = conn.assigns.current_scope with {:ok, _} <- Sites.delete_community(scope, Sites.get_community!(scope, id)) do send_resp(conn, :no_content, "") end end def put_plant(conn, %{"community_id" => id, "taxon_id" => taxon_id, "status" => status}) do scope = conn.assigns.current_scope community = Sites.get_community!(scope, id) with %Taxon{} = taxon <- Taxonomy.taxon(taxon_id) || {:error, :not_found}, {:ok, plant} <- Sites.put_plant(scope, community, taxon, status) do json(conn, GardenJSON.plant(plant)) end end def delete_plant(conn, %{"community_id" => id, "taxon_id" => taxon_id}) do scope = conn.assigns.current_scope :ok = Sites.remove_plant(scope, Sites.get_community!(scope, id), taxon_id) send_resp(conn, :no_content, "") end end