cannery/lib/cannery/containers/tag.ex

67 lines
1.8 KiB
Elixir
Raw Normal View History

defmodule Cannery.Containers.Tag do
2022-01-22 21:40:29 -05:00
@moduledoc """
Tags are added to containers to help organize, and can include custom-defined
text and bg colors.
"""
2021-09-02 23:31:14 -04:00
use Ecto.Schema
import Ecto.Changeset
alias Cannery.Accounts.User
2022-01-22 21:40:29 -05:00
alias Ecto.{Changeset, UUID}
2021-09-02 23:31:14 -04:00
2022-11-09 23:33:50 -05:00
@derive {Jason.Encoder,
only: [
:id,
:name,
:bg_color,
:text_color
]}
2021-09-02 23:31:14 -04:00
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "tags" do
field :name, :string
2021-09-12 19:26:04 -04:00
field :bg_color, :string
2021-09-10 00:41:06 -04:00
field :text_color, :string
field :user_id, :binary_id
2021-09-02 23:31:14 -04:00
timestamps()
end
@type t :: %__MODULE__{
2022-01-31 20:08:01 -05:00
id: id(),
2021-09-12 19:26:04 -04:00
name: String.t(),
bg_color: String.t(),
text_color: String.t(),
2022-01-31 20:08:01 -05:00
user_id: User.id(),
2021-09-12 19:26:04 -04:00
inserted_at: NaiveDateTime.t(),
updated_at: NaiveDateTime.t()
}
@type new_tag() :: %__MODULE__{}
2022-01-31 20:08:01 -05:00
@type id() :: UUID.t()
2022-11-23 20:46:41 -05:00
@type changeset() :: Changeset.t(t() | new_tag())
2022-01-22 21:40:29 -05:00
2021-09-02 23:31:14 -04:00
@doc false
2022-11-23 20:46:41 -05:00
@spec create_changeset(new_tag(), User.t(), attrs :: map()) :: changeset()
2022-07-04 21:06:35 -04:00
def create_changeset(tag, %User{id: user_id}, attrs) do
2021-09-02 23:31:14 -04:00
tag
2022-07-04 21:06:35 -04:00
|> change(user_id: user_id)
|> cast(attrs, [:name, :bg_color, :text_color])
2023-03-19 23:46:42 -04:00
|> validate_length(:name, max: 255)
|> validate_length(:bg_color, max: 12)
|> validate_length(:text_color, max: 12)
2021-09-10 22:43:12 -04:00
|> validate_required([:name, :bg_color, :text_color, :user_id])
2021-09-02 23:31:14 -04:00
end
2022-02-09 23:21:42 -05:00
@doc false
2022-11-23 20:46:41 -05:00
@spec update_changeset(t() | new_tag(), attrs :: map()) :: changeset()
2022-02-09 23:21:42 -05:00
def update_changeset(tag, attrs) do
tag
|> cast(attrs, [:name, :bg_color, :text_color])
2023-03-19 23:46:42 -04:00
|> validate_length(:name, max: 255)
|> validate_length(:bg_color, max: 12)
|> validate_length(:text_color, max: 12)
2022-07-01 19:53:44 -04:00
|> validate_required([:name, :bg_color, :text_color])
2022-02-09 23:21:42 -05:00
end
2021-09-02 23:31:14 -04:00
end