diff --git a/lib/app_api/captures/capture.ex b/lib/app_api/captures/capture.ex index 68685b7..9dc5b25 100644 --- a/lib/app_api/captures/capture.ex +++ b/lib/app_api/captures/capture.ex @@ -28,20 +28,22 @@ defmodule AppApi.Captures.Capture do end defp parse_tags(params) do - (params["tags"] || "") - |> String.split(",") - |> Enum.map(&String.trim/1) - |> Enum.reject(&(&1 == "")) - |> insert_and_get_all() + tags = + (params["tags"] || "") + |> String.split(",") + |> Enum.map(&String.trim/1) + |> Enum.reject(&(&1 == "")) + + insert_and_get_all(tags, params["id_person"]) end - defp insert_and_get_all([]) do + defp insert_and_get_all([], _id_person) do [] end - defp insert_and_get_all(names) do - maps = Enum.map(names, &%{text: &1}) + defp insert_and_get_all(tags, id_person) do + maps = Enum.map(tags, &%{text: &1, id_person: id_person}) Repo.insert_all(Tag, maps, on_conflict: :nothing) - Repo.all(from t in Tag, where: t.name in ^names) + Repo.all(from t in Tag, where: t.name in ^tags) end end diff --git a/lib/app_api/tags.ex b/lib/app_api/tags.ex new file mode 100644 index 0000000..9299811 --- /dev/null +++ b/lib/app_api/tags.ex @@ -0,0 +1,58 @@ +defmodule AppApi.Tags do + @moduledoc """ + The Tags context. + """ + + import Ecto.Query, warn: false + alias AppApi.Repo + + alias AppApi.Tags.Tag + + @doc """ + Returns the list of tags. + + ## Examples + + iex> list_tags() + [%Tag{}, ...] + + """ + def list_tags do + Repo.all(Tag) + end + + @doc """ + Returns the list of tags created by a person + i.e. default tags + """ + def get_tags_by_id_person(id_person) do + query = + from t in Tag, + where: t.id_person == ^id_person, + order_by: [asc: t.text] + + Repo.all(query) + end + + @doc """ + Returns the list of tags where the person is not defined + i.e. default tags + """ + def get_default_tags() do + query = + from t in Tag, + where: is_nil(t.id_person), + order_by: [asc: t.text] + + Repo.all(query) + end + + @doc """ + Creates a tag. + """ + def create_tag(attrs \\ %{}) do + %Tag{} + |> Tag.changeset(attrs) + |> Repo.insert!() + end +end diff --git a/lib/app_api/tags/tag.ex b/lib/app_api/tags/tag.ex index d3f9831..9d61a03 100644 --- a/lib/app_api/tags/tag.ex +++ b/lib/app_api/tags/tag.ex @@ -1,7 +1,6 @@ defmodule AppApi.Tags.Tag do use Ecto.Schema import Ecto.Changeset - alias AppApi.Captures.Capture schema "tags" do field :text, :string diff --git a/priv/repo/seeds.exs b/priv/repo/seeds.exs index 94a2689..1761cd9 100644 --- a/priv/repo/seeds.exs +++ b/priv/repo/seeds.exs @@ -9,3 +9,8 @@ # # We recommend using the bang functions (`insert!`, `update!` # and so on) as they will fail if something goes wrong. + +alias AppApi.Tags + +Tags.create_tag(%{text: "note", id_person: nil}) +Tags.create_tag(%{text: "task", id_person: nil})