diff --git a/lib/chesstrainer/accounts.ex b/lib/chesstrainer/accounts.ex index a47de36..19f7dc5 100644 --- a/lib/chesstrainer/accounts.ex +++ b/lib/chesstrainer/accounts.ex @@ -168,6 +168,18 @@ defmodule Chesstrainer.Accounts do |> Repo.update() end + @doc """ + Updates a user's subscription plan. + + Plans are programmatic values; registration never casts `plan`, so a user + cannot upgrade themselves. + """ + def update_user_plan(%User{} = user, plan) do + user + |> User.plan_changeset(%{plan: plan}) + |> Repo.update() + end + ## Admin user management @doc """ diff --git a/lib/chesstrainer/accounts/user.ex b/lib/chesstrainer/accounts/user.ex index 2af41d2..06f4eb0 100644 --- a/lib/chesstrainer/accounts/user.ex +++ b/lib/chesstrainer/accounts/user.ex @@ -55,6 +55,17 @@ defmodule Chesstrainer.Accounts.User do |> validate_required([:role]) end + @doc """ + A user changeset for changing the plan. + + The plan is programmatic and must never be cast from user-supplied params. + """ + def plan_changeset(user, attrs) do + user + |> cast(attrs, [:plan]) + |> validate_required([:plan]) + end + @doc """ A user changeset for an admin-created invitation. diff --git a/lib/chesstrainer/themes.ex b/lib/chesstrainer/themes.ex index d1cc8f7..0f61a83 100644 --- a/lib/chesstrainer/themes.ex +++ b/lib/chesstrainer/themes.ex @@ -4,6 +4,8 @@ defmodule Chesstrainer.Themes do """ import Ecto.Query, warn: false + alias Chesstrainer.Accounts.Policy + alias Chesstrainer.Accounts.Scope alias Chesstrainer.Repo alias Chesstrainer.Themes.Theme @@ -74,9 +76,26 @@ defmodule Chesstrainer.Themes do """ def get_theme!(id), do: Repo.get!(Theme, id) + @doc """ + Gets a single endgame theme by its slug. + + Returns `nil` when no endgame theme has that slug. + """ + def get_theme_by_slug(slug) when is_binary(slug) do + Repo.one( + from t in Theme, + where: t.slug == ^slug and t.category == :endgame, + limit: 1 + ) + end + @doc """ Creates a theme. + This is the unscoped path used by internal callers such as seeds, fixtures and + the admin picker, which are already behind an authorization check. Prefer + `create_theme/2` wherever a scope is available. + ## Examples iex> create_theme(%{field: value}) @@ -92,6 +111,21 @@ defmodule Chesstrainer.Themes do |> Repo.insert() end + @doc """ + Creates a theme on behalf of an administrator. + + Members cannot introduce new theme names; their contribution path is a + suggestion, which a moderator reviews. Returns `{:error, :unauthorized}` + for a scope that cannot manage themes. + """ + def create_theme(%Scope{} = scope, attrs) do + if Policy.can?(scope, :manage_themes) do + create_theme(attrs) + else + {:error, :unauthorized} + end + end + @doc """ Updates a theme. @@ -160,20 +194,70 @@ defmodule Chesstrainer.Themes do @doc """ Finds a theme by name (trimmed and case-insensitive) for a category, creating it if it does not exist. + + Options: + + * `:kind` - the kind for a newly created theme; defaults to `:technique` + + This is the picker's helper and is expected to run behind an admin check. """ - def get_or_create(name, category) when is_binary(name) do + def get_or_create(name, category, opts \\ []) when is_binary(name) do name = String.trim(name) if name == "" do {:error, :blank_name} else case find_by_name(name, category) do - nil -> create_theme(%{name: name, category: category}) - theme -> {:ok, theme} + nil -> + create_theme(%{ + name: name, + category: category, + kind: Keyword.get(opts, :kind, :technique) + }) + + theme -> + {:ok, theme} end end end + @doc """ + Replaces the derived theme links for one endgame. + + Only links whose source is `derived` are removed, so curated and + community-approved links survive every derivation pass. Links that are + already present are left alone, which makes the operation idempotent. + """ + @spec sync_derived_themes(Ecto.UUID.t(), [term()]) :: :ok + def sync_derived_themes(endgame_id, theme_ids) do + now = DateTime.utc_now() |> DateTime.truncate(:second) + + Repo.transaction(fn -> + Repo.delete_all( + from l in "endgames_themes", + where: l.endgame_id == type(^endgame_id, :binary_id) and l.source == "derived" + ) + + rows = + theme_ids + |> Enum.uniq() + |> Enum.map(fn theme_id -> + %{ + endgame_id: Ecto.UUID.dump!(endgame_id), + theme_id: theme_id, + source: "derived", + inserted_at: now + } + end) + + if rows != [] do + Repo.insert_all("endgames_themes", rows, on_conflict: :nothing) + end + end) + + :ok + end + defp find_by_name(name, category) do downcased = String.downcase(name) diff --git a/lib/chesstrainer/themes/theme.ex b/lib/chesstrainer/themes/theme.ex index 78c2eb8..822d913 100644 --- a/lib/chesstrainer/themes/theme.ex +++ b/lib/chesstrainer/themes/theme.ex @@ -1,29 +1,106 @@ defmodule Chesstrainer.Themes.Theme do + @moduledoc """ + A label describing an endgame's technique or goal. + + A theme has a stable `slug` for URLs, a `kind` saying where the label comes + from — `material`, `motif` or `technique` — and an optional description. The + slug is generated from the name when the theme is first created and is then + left alone, so renaming a theme never breaks a link to it. + """ + use Ecto.Schema import Ecto.Changeset @type t :: %__MODULE__{} + @kinds [material: "material", motif: "motif", technique: "technique"] + schema "themes" do field :name, :string + field :slug, :string + field :description, :string + field :kind, Ecto.Enum, values: @kinds, default: :technique field :category, Ecto.Enum, values: [endgame: "endgame", opening: "opening", tactic: "tactic"] timestamps(type: :utc_datetime) end + @doc "The kinds a theme can have." + def kinds, do: Keyword.keys(@kinds) + + @doc """ + Turns a theme name into a URL-safe slug. + + Lowercase letters, digits and single hyphens; accents are folded, runs of + other characters collapse to one hyphen, and a blank result becomes + `"theme"`. + """ + @spec slugify(String.t() | nil) :: String.t() + def slugify(name) do + slug = + name + |> to_string() + |> :unicode.characters_to_nfd_binary() + |> String.replace(~r/[\x{0300}-\x{036F}]/u, "") + |> String.downcase() + |> String.replace(~r/[^a-z0-9]+/u, "-") + |> String.trim("-") + + if slug == "", do: "theme", else: slug + end + @doc false def changeset(theme, attrs) do theme - |> cast(attrs, [:name, :category]) - |> update_change(:name, fn - name when is_binary(name) -> String.trim(name) - name -> name - end) - |> validate_required([:name, :category]) + |> cast(attrs, [:name, :slug, :description, :kind, :category]) + |> update_change(:name, &trim/1) + |> update_change(:description, &trim/1) + |> put_slug() + |> validate_required([:name, :slug, :kind, :category]) |> validate_length(:name, min: 1, max: 60) + |> validate_length(:slug, min: 1, max: 80) + |> validate_length(:description, max: 500) + |> validate_format(:slug, ~r/\A[a-z0-9]+(?:-[a-z0-9]+)*\z/, + message: "must be lowercase letters, numbers and single hyphens" + ) |> unique_constraint(:name, name: :themes_name_category_lower_index, message: "already exists" ) + |> unique_constraint(:slug, message: "is already taken") + |> check_constraint(:kind, name: :themes_kind_in_allowed) end + + defp put_slug(changeset) do + case get_field(changeset, :slug) do + slug when is_binary(slug) -> + if String.trim(slug) == "" do + generate_slug(changeset) + else + put_change(changeset, :slug, slugify(slug)) + end + + nil -> + generate_slug(changeset) + end + end + + # A new theme starts without a name, so generating a slug from it would only + # produce the fallback. Wait until there is a name to derive from. + defp generate_slug(changeset) do + case get_field(changeset, :name) do + name when is_binary(name) -> + if String.trim(name) == "" do + changeset + else + put_change(changeset, :slug, slugify(name)) + end + + _ -> + changeset + end + end + + defp trim(value) when is_binary(value), do: String.trim(value) + defp trim(value), do: value end diff --git a/lib/chesstrainer_web/live/admin/theme_live/form.ex b/lib/chesstrainer_web/live/admin/theme_live/form.ex index 403effb..18a5a51 100644 --- a/lib/chesstrainer_web/live/admin/theme_live/form.ex +++ b/lib/chesstrainer_web/live/admin/theme_live/form.ex @@ -11,6 +11,12 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.Form do {"Tactic", "tactic"} ] + @kind_options [ + {"Technique", "technique"}, + {"Motif", "motif"}, + {"Material", "material"} + ] + @impl true def render(assigns) do ~H""" @@ -21,18 +27,31 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.Form do {@page_title} <:subtitle> Themes group endgames for filtering. Names must be unique within a category, - ignoring case. + ignoring case. The slug is generated from the name and stays fixed afterwards, + so links to a theme keep working when it is renamed. <.form for={@form} id="theme-form" phx-change="validate" phx-submit="save"> <.input field={@form[:name]} type="text" label="Name" autocomplete="off" required /> + <.input + field={@form[:kind]} + type="select" + label="Kind" + options={@kind_options} + /> <.input field={@form[:category]} type="select" label="Category" options={@category_options} /> + <.input + field={@form[:description]} + type="textarea" + label="Description" + rows="3" + />