Add theme slugs, kinds and link provenance (#192)

* add function for upgrading a user's plan in interactive Elixir

* Add theme slugs, kinds and link provenance

Themes gain a stable slug, an optional description and a kind so the app can
tell material, motif and technique labels apart. Slugs are generated from the
name on first save and keep their value when the theme is renamed, so links to
a theme stay valid.

Endgame-to-theme links now record their source (derived, curated or community)
and creation time. Existing links are backfilled as curated. A derived pass can
therefore replace only its own links, leaving human work untouched.

The admin index shows each theme's kind and its coverage across the library.
Creating a theme name requires the manage_themes capability, and members get an
unauthorized error instead, ahead of the suggestion flow.

Closes #185
This commit is contained in:
2026-11-17 20:46:43 +01:00
committed by GitHub
parent 7209923de7
commit 80cb033077
12 changed files with 545 additions and 27 deletions
+12
View File
@@ -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 """
+11
View File
@@ -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.
+87 -3
View File
@@ -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)
+83 -6
View File
@@ -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
@@ -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.
</:subtitle>
</.header>
<.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"
/>
<footer>
<.button phx-disable-with="Saving..." variant="primary">Save theme</.button>
@@ -54,6 +73,7 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.Form do
socket
|> assign(:page_title, "New theme")
|> assign(:theme, theme)
|> assign(:kind_options, @kind_options)
|> assign(:category_options, @category_options)
|> assign(:form, to_form(Themes.change_theme(theme)))
end
@@ -64,6 +84,7 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.Form do
socket
|> assign(:page_title, "Edit theme")
|> assign(:theme, theme)
|> assign(:kind_options, @kind_options)
|> assign(:category_options, @category_options)
|> assign(:form, to_form(Themes.change_theme(theme)))
end
@@ -87,13 +108,16 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.Form do
end
defp save_theme(socket, :new, theme_params) do
case Themes.create_theme(theme_params) do
case Themes.create_theme(socket.assigns.current_scope, theme_params) do
{:ok, _theme} ->
{:noreply,
socket
|> put_flash(:info, "Theme created successfully.")
|> push_navigate(to: ~p"/admin/themes")}
{:error, :unauthorized} ->
{:noreply, put_flash(socket, :error, "You are not authorized to manage themes.")}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, :form, to_form(changeset, action: :insert))}
end
@@ -2,6 +2,7 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.Index do
use ChesstrainerWeb, :live_view
alias Chesstrainer.Accounts.Policy
alias Chesstrainer.Endgames
alias Chesstrainer.Themes
@category_options [
@@ -20,7 +21,8 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.Index do
<.header>
Themes
<:subtitle>
Themes group endgames for filtering and puzzle selection. Deleting a theme detaches
Themes group endgames for filtering and puzzle selection. Coverage shows how
many endgames carry a theme out of the whole library. Deleting a theme detaches
it from every endgame and leaves the endgames intact.
</:subtitle>
<:actions>
@@ -69,17 +71,21 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.Index do
<thead>
<tr>
<th>Name</th>
<th>Kind</th>
<th>Category</th>
<th>Used by</th>
<th>Coverage</th>
<th><span class="sr-only">Actions</span></th>
</tr>
</thead>
<tbody id="themes">
<tr :for={{theme, usage_count} <- @themes} id={"theme-#{theme.id}"}>
<td>{theme.name}</td>
<td>{theme.kind}</td>
<td>{theme.category}</td>
<td>
<span id={"theme-usage-#{theme.id}"}>{usage_label(usage_count)}</span>
<span id={"theme-usage-#{theme.id}"}>
{coverage_label(usage_count, @total_endgames)}
</span>
</td>
<td class="w-0 font-semibold">
<div class="flex gap-4">
@@ -88,7 +94,7 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.Index do
phx-click="delete"
phx-value-id={theme.id}
data-confirm={
"Delete #{theme.name}? Used by #{usage_label(usage_count)}. " <>
"Delete #{theme.name}? Used by #{coverage_label(usage_count, @total_endgames)}. " <>
"The endgames will be kept and simply detached."
}
>
@@ -152,9 +158,10 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.Index do
category: socket.assigns.category
)
assign(socket, :themes, themes)
assign(socket, themes: themes, total_endgames: Endgames.count_endgames())
end
defp usage_label(1), do: "1 endgame"
defp usage_label(count), do: "#{count} endgames"
defp coverage_label(count, total) do
"#{count} of #{total} #{if total == 1, do: "endgame", else: "endgames"}"
end
end