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() |> Repo.update()
end 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 ## Admin user management
@doc """ @doc """
+11
View File
@@ -55,6 +55,17 @@ defmodule Chesstrainer.Accounts.User do
|> validate_required([:role]) |> validate_required([:role])
end 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 """ @doc """
A user changeset for an admin-created invitation. 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 import Ecto.Query, warn: false
alias Chesstrainer.Accounts.Policy
alias Chesstrainer.Accounts.Scope
alias Chesstrainer.Repo alias Chesstrainer.Repo
alias Chesstrainer.Themes.Theme alias Chesstrainer.Themes.Theme
@@ -74,9 +76,26 @@ defmodule Chesstrainer.Themes do
""" """
def get_theme!(id), do: Repo.get!(Theme, id) 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 """ @doc """
Creates a theme. 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 ## Examples
iex> create_theme(%{field: value}) iex> create_theme(%{field: value})
@@ -92,6 +111,21 @@ defmodule Chesstrainer.Themes do
|> Repo.insert() |> Repo.insert()
end 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 """ @doc """
Updates a theme. Updates a theme.
@@ -160,20 +194,70 @@ defmodule Chesstrainer.Themes do
@doc """ @doc """
Finds a theme by name (trimmed and case-insensitive) for a category, creating it Finds a theme by name (trimmed and case-insensitive) for a category, creating it
if it does not exist. 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) name = String.trim(name)
if name == "" do if name == "" do
{:error, :blank_name} {:error, :blank_name}
else else
case find_by_name(name, category) do case find_by_name(name, category) do
nil -> create_theme(%{name: name, category: category}) nil ->
theme -> {:ok, theme} create_theme(%{
name: name,
category: category,
kind: Keyword.get(opts, :kind, :technique)
})
theme ->
{:ok, theme}
end end
end 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 defp find_by_name(name, category) do
downcased = String.downcase(name) downcased = String.downcase(name)
+83 -6
View File
@@ -1,29 +1,106 @@
defmodule Chesstrainer.Themes.Theme do 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 use Ecto.Schema
import Ecto.Changeset import Ecto.Changeset
@type t :: %__MODULE__{} @type t :: %__MODULE__{}
@kinds [material: "material", motif: "motif", technique: "technique"]
schema "themes" do schema "themes" do
field :name, :string 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"] field :category, Ecto.Enum, values: [endgame: "endgame", opening: "opening", tactic: "tactic"]
timestamps(type: :utc_datetime) timestamps(type: :utc_datetime)
end 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 @doc false
def changeset(theme, attrs) do def changeset(theme, attrs) do
theme theme
|> cast(attrs, [:name, :category]) |> cast(attrs, [:name, :slug, :description, :kind, :category])
|> update_change(:name, fn |> update_change(:name, &trim/1)
name when is_binary(name) -> String.trim(name) |> update_change(:description, &trim/1)
name -> name |> put_slug()
end) |> validate_required([:name, :slug, :kind, :category])
|> validate_required([:name, :category])
|> validate_length(:name, min: 1, max: 60) |> 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, |> unique_constraint(:name,
name: :themes_name_category_lower_index, name: :themes_name_category_lower_index,
message: "already exists" message: "already exists"
) )
|> unique_constraint(:slug, message: "is already taken")
|> check_constraint(:kind, name: :themes_kind_in_allowed)
end 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 end
@@ -11,6 +11,12 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.Form do
{"Tactic", "tactic"} {"Tactic", "tactic"}
] ]
@kind_options [
{"Technique", "technique"},
{"Motif", "motif"},
{"Material", "material"}
]
@impl true @impl true
def render(assigns) do def render(assigns) do
~H""" ~H"""
@@ -21,18 +27,31 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.Form do
{@page_title} {@page_title}
<:subtitle> <:subtitle>
Themes group endgames for filtering. Names must be unique within a category, 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> </:subtitle>
</.header> </.header>
<.form for={@form} id="theme-form" phx-change="validate" phx-submit="save"> <.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[:name]} type="text" label="Name" autocomplete="off" required />
<.input
field={@form[:kind]}
type="select"
label="Kind"
options={@kind_options}
/>
<.input <.input
field={@form[:category]} field={@form[:category]}
type="select" type="select"
label="Category" label="Category"
options={@category_options} options={@category_options}
/> />
<.input
field={@form[:description]}
type="textarea"
label="Description"
rows="3"
/>
<footer> <footer>
<.button phx-disable-with="Saving..." variant="primary">Save theme</.button> <.button phx-disable-with="Saving..." variant="primary">Save theme</.button>
@@ -54,6 +73,7 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.Form do
socket socket
|> assign(:page_title, "New theme") |> assign(:page_title, "New theme")
|> assign(:theme, theme) |> assign(:theme, theme)
|> assign(:kind_options, @kind_options)
|> assign(:category_options, @category_options) |> assign(:category_options, @category_options)
|> assign(:form, to_form(Themes.change_theme(theme))) |> assign(:form, to_form(Themes.change_theme(theme)))
end end
@@ -64,6 +84,7 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.Form do
socket socket
|> assign(:page_title, "Edit theme") |> assign(:page_title, "Edit theme")
|> assign(:theme, theme) |> assign(:theme, theme)
|> assign(:kind_options, @kind_options)
|> assign(:category_options, @category_options) |> assign(:category_options, @category_options)
|> assign(:form, to_form(Themes.change_theme(theme))) |> assign(:form, to_form(Themes.change_theme(theme)))
end end
@@ -87,13 +108,16 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.Form do
end end
defp save_theme(socket, :new, theme_params) do 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} -> {:ok, _theme} ->
{:noreply, {:noreply,
socket socket
|> put_flash(:info, "Theme created successfully.") |> put_flash(:info, "Theme created successfully.")
|> push_navigate(to: ~p"/admin/themes")} |> push_navigate(to: ~p"/admin/themes")}
{:error, :unauthorized} ->
{:noreply, put_flash(socket, :error, "You are not authorized to manage themes.")}
{:error, %Ecto.Changeset{} = changeset} -> {:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, :form, to_form(changeset, action: :insert))} {:noreply, assign(socket, :form, to_form(changeset, action: :insert))}
end end
@@ -2,6 +2,7 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.Index do
use ChesstrainerWeb, :live_view use ChesstrainerWeb, :live_view
alias Chesstrainer.Accounts.Policy alias Chesstrainer.Accounts.Policy
alias Chesstrainer.Endgames
alias Chesstrainer.Themes alias Chesstrainer.Themes
@category_options [ @category_options [
@@ -20,7 +21,8 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.Index do
<.header> <.header>
Themes Themes
<:subtitle> <: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. it from every endgame and leaves the endgames intact.
</:subtitle> </:subtitle>
<:actions> <:actions>
@@ -69,17 +71,21 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.Index do
<thead> <thead>
<tr> <tr>
<th>Name</th> <th>Name</th>
<th>Kind</th>
<th>Category</th> <th>Category</th>
<th>Used by</th> <th>Coverage</th>
<th><span class="sr-only">Actions</span></th> <th><span class="sr-only">Actions</span></th>
</tr> </tr>
</thead> </thead>
<tbody id="themes"> <tbody id="themes">
<tr :for={{theme, usage_count} <- @themes} id={"theme-#{theme.id}"}> <tr :for={{theme, usage_count} <- @themes} id={"theme-#{theme.id}"}>
<td>{theme.name}</td> <td>{theme.name}</td>
<td>{theme.kind}</td>
<td>{theme.category}</td> <td>{theme.category}</td>
<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>
<td class="w-0 font-semibold"> <td class="w-0 font-semibold">
<div class="flex gap-4"> <div class="flex gap-4">
@@ -88,7 +94,7 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.Index do
phx-click="delete" phx-click="delete"
phx-value-id={theme.id} phx-value-id={theme.id}
data-confirm={ 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." "The endgames will be kept and simply detached."
} }
> >
@@ -152,9 +158,10 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.Index do
category: socket.assigns.category category: socket.assigns.category
) )
assign(socket, :themes, themes) assign(socket, themes: themes, total_endgames: Endgames.count_endgames())
end end
defp usage_label(1), do: "1 endgame" defp coverage_label(count, total) do
defp usage_label(count), do: "#{count} endgames" "#{count} of #{total} #{if total == 1, do: "endgame", else: "endgames"}"
end
end end
@@ -0,0 +1,90 @@
defmodule Chesstrainer.Repo.Migrations.ThemeProvenanceKindsAndCoverage do
use Ecto.Migration
import Ecto.Query
def up do
alter table(:themes) do
add :slug, :string
add :description, :string
add :kind, :string, null: false, default: "technique"
end
alter table(:endgames_themes) do
add :source, :string, null: false, default: "curated"
add :inserted_at, :utc_datetime, null: false, default: fragment("now()")
end
flush()
backfill_slugs()
alter table(:themes) do
modify :slug, :string, null: false
end
create unique_index(:themes, [:slug])
create constraint(:themes, :kind_in_allowed,
check: "kind in ('material', 'motif', 'technique')"
)
create constraint(:endgames_themes, :source_in_allowed,
check: "source in ('derived', 'curated', 'community')"
)
end
def down do
drop constraint(:endgames_themes, :source_in_allowed)
drop constraint(:themes, :kind_in_allowed)
drop unique_index(:themes, [:slug])
alter table(:endgames_themes) do
remove :inserted_at
remove :source
end
alter table(:themes) do
remove :kind
remove :description
remove :slug
end
end
# Themes were created without a slug, so every existing row needs one before
# the column can become mandatory. Names are unique per category but not
# globally, so collisions get a numeric suffix.
defp backfill_slugs do
themes = repo().all(from(t in "themes", select: {t.id, t.name}))
Enum.reduce(themes, MapSet.new(), fn {id, name}, used ->
slug = unique_slug(slugify(name), used)
repo().update_all(from(t in "themes", where: t.id == ^id), set: [slug: slug])
MapSet.put(used, slug)
end)
end
defp unique_slug(base, used) do
if MapSet.member?(used, base) do
Enum.find_value(2..1_000, base, fn suffix ->
candidate = "#{base}-#{suffix}"
if MapSet.member?(used, candidate), do: nil, else: candidate
end)
else
base
end
end
defp 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
end
+8 -1
View File
@@ -59,7 +59,14 @@ theme_names =
Repo.insert_all( Repo.insert_all(
Theme, Theme,
Enum.map(theme_names, fn name -> Enum.map(theme_names, fn name ->
%{name: name, category: :endgame, inserted_at: now, updated_at: now} %{
name: name,
slug: Theme.slugify(name),
kind: :technique,
category: :endgame,
inserted_at: now,
updated_at: now
}
end), end),
on_conflict: :nothing on_conflict: :nothing
) )
+15
View File
@@ -276,6 +276,21 @@ defmodule Chesstrainer.AccountsTest do
end end
end end
describe "update_user_plan/2" do
test "changes the user's plan" do
user = user_fixture()
assert {:ok, %User{plan: :premium}} = Accounts.update_user_plan(user, :premium)
end
test "rejects a plan that is not in the enum" do
user = user_fixture()
assert {:error, changeset} = Accounts.update_user_plan(user, :platinum)
assert %{plan: ["is invalid"]} = errors_on(changeset)
end
end
describe "sudo_mode?/2" do describe "sudo_mode?/2" do
test "validates the authenticated_at time" do test "validates the authenticated_at time" do
now = DateTime.utc_now() now = DateTime.utc_now()
+169 -2
View File
@@ -1,13 +1,21 @@
defmodule Chesstrainer.ThemesTest do defmodule Chesstrainer.ThemesTest do
use Chesstrainer.DataCase use Chesstrainer.DataCase
import Ecto.Query
import Chesstrainer.AccountsFixtures
import Chesstrainer.EndgamesFixtures
import Chesstrainer.ThemesFixtures
alias Chesstrainer.Accounts
alias Chesstrainer.Accounts.Scope
alias Chesstrainer.Endgames
alias Chesstrainer.Repo
alias Chesstrainer.Themes alias Chesstrainer.Themes
describe "themes" do describe "themes" do
alias Chesstrainer.Themes.Theme alias Chesstrainer.Themes.Theme
import Chesstrainer.ThemesFixtures
@invalid_attrs %{name: nil, category: nil} @invalid_attrs %{name: nil, category: nil}
test "list_themes/0 returns all themes" do test "list_themes/0 returns all themes" do
@@ -76,4 +84,163 @@ defmodule Chesstrainer.ThemesTest do
assert changeset.errors[:name] assert changeset.errors[:name]
end end
end end
describe "theme identity" do
test "generates a slug from the name" do
assert {:ok, theme} = Themes.create_theme(%{name: " Mate in 2! ", category: :endgame})
assert theme.slug == "mate-in-2"
end
test "normalises an explicit slug" do
assert {:ok, theme} =
Themes.create_theme(%{
name: "Lucena",
slug: " Lucena-Position ",
category: :endgame
})
assert theme.slug == "lucena-position"
end
test "keeps the slug stable when the name changes" do
theme = theme_fixture(%{name: "Lucena"})
assert {:ok, updated} = Themes.update_theme(theme, %{name: "Lucena position"})
assert updated.slug == "lucena"
end
test "rejects a slug that is already taken, even in another category" do
assert {:ok, _theme} = Themes.create_theme(%{name: "Lucena", category: :endgame})
assert {:error, changeset} = Themes.create_theme(%{name: "Lucena", category: :tactic})
assert changeset.errors[:slug]
end
test "defaults the kind to technique" do
assert {:ok, theme} = Themes.create_theme(%{name: "Opposition", category: :endgame})
assert theme.kind == :technique
end
test "accepts a material kind" do
assert {:ok, theme} =
Themes.create_theme(%{
name: "Rook endgame",
kind: :material,
category: :endgame
})
assert theme.kind == :material
end
test "rejects an unknown kind" do
assert {:error, changeset} =
Themes.create_theme(%{
name: "Zugzwang",
kind: :bogus,
category: :endgame
})
assert changeset.errors[:kind]
end
test "get_theme_by_slug/1 finds an endgame theme and ignores other categories" do
theme = theme_fixture(%{name: "Philidor"})
tactic = theme_fixture(%{name: "Philidor's pin", category: :tactic})
assert Themes.get_theme_by_slug("philidor").id == theme.id
assert Themes.get_theme_by_slug(tactic.slug) == nil
assert Themes.get_theme_by_slug("unknown") == nil
end
end
describe "create_theme/2 authorization" do
test "an admin scope may create a theme" do
{:ok, admin} = Accounts.update_user_role(user_fixture(), :admin)
scope = Scope.for_user(admin)
assert {:ok, %Themes.Theme{}} =
Themes.create_theme(scope, %{name: "Opposition", category: :endgame})
end
test "a member scope cannot create a theme" do
scope = user_scope_fixture()
assert {:error, :unauthorized} =
Themes.create_theme(scope, %{name: "Opposition", category: :endgame})
assert Themes.list_themes() == []
end
end
describe "theme link provenance" do
test "links created from the endgame context default to curated" do
theme = theme_fixture()
endgame = endgame_fixture()
assert {:ok, _endgame} = Endgames.update_endgame(endgame, %{}, [theme])
assert [%{theme_id: theme_id, source: "curated"}] = link_rows(endgame.id)
assert theme_id == theme.id
end
test "sync_derived_themes/2 adds derived links and leaves curated and community links alone" do
curated = theme_fixture(%{name: "Lucena"})
community = theme_fixture(%{name: "Philidor"})
derived = theme_fixture(%{name: "Rook endgame"})
endgame = endgame_fixture()
{:ok, _} = Endgames.update_endgame(endgame, %{}, [curated])
insert_link(endgame.id, community.id, "community")
assert :ok = Themes.sync_derived_themes(endgame.id, [derived.id, curated.id])
sources = link_sources(endgame.id)
assert sources[curated.id] == "curated"
assert sources[community.id] == "community"
assert sources[derived.id] == "derived"
end
test "sync_derived_themes/2 replaces only its own derived links" do
curated = theme_fixture(%{name: "Lucena"})
old_derived = theme_fixture(%{name: "Rook endgame"})
new_derived = theme_fixture(%{name: "Two pawns"})
endgame = endgame_fixture()
{:ok, _} = Endgames.update_endgame(endgame, %{}, [curated])
Themes.sync_derived_themes(endgame.id, [old_derived.id])
assert :ok = Themes.sync_derived_themes(endgame.id, [new_derived.id])
sources = link_sources(endgame.id)
assert sources[curated.id] == "curated"
refute Map.has_key?(sources, old_derived.id)
assert sources[new_derived.id] == "derived"
end
end
defp link_rows(endgame_id) do
Repo.all(
from l in "endgames_themes",
where: l.endgame_id == type(^endgame_id, :binary_id),
select: %{theme_id: l.theme_id, source: l.source},
order_by: l.theme_id
)
end
defp link_sources(endgame_id) do
endgame_id
|> link_rows()
|> Map.new(&{&1.theme_id, &1.source})
end
defp insert_link(endgame_id, theme_id, source) do
Repo.insert_all("endgames_themes", [
%{
endgame_id: Ecto.UUID.dump!(endgame_id),
theme_id: theme_id,
source: source,
inserted_at: DateTime.utc_now() |> DateTime.truncate(:second)
}
])
end
end end
@@ -17,7 +17,30 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.FormTest do
assert_redirect(view, ~p"/admin/themes") assert_redirect(view, ~p"/admin/themes")
assert [%{name: "Lucena", category: :endgame}] = Themes.search("Lucena", "endgame") assert [%{name: "Lucena", slug: "lucena", kind: :technique, category: :endgame}] =
Themes.search("Lucena", "endgame")
end
test "creates a theme with a kind and description", %{conn: conn} do
{:ok, view, _html} = live(conn, ~p"/admin/themes/new")
view
|> form("#theme-form",
theme: %{
name: "Rook endgame",
kind: "material",
category: "endgame",
description: "Positions where a rook and pawn face a rook."
}
)
|> render_submit()
assert_redirect(view, ~p"/admin/themes")
assert [theme] = Themes.search("Rook endgame", "endgame")
assert theme.slug == "rook-endgame"
assert theme.kind == :material
assert theme.description == "Positions where a rook and pawn face a rook."
end end
test "renames and recategorises a theme", %{conn: conn} do test "renames and recategorises a theme", %{conn: conn} do
@@ -11,8 +11,8 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.IndexTest do
setup :register_and_log_in_admin setup :register_and_log_in_admin
test "lists themes with their usage count", %{conn: conn} do test "lists themes with their kind and coverage", %{conn: conn} do
used_theme = theme_fixture(%{name: "Lucena"}) used_theme = theme_fixture(%{name: "Lucena", kind: :technique})
unused_theme = theme_fixture(%{name: "Philidor"}) unused_theme = theme_fixture(%{name: "Philidor"})
endgame = endgame_fixture() endgame = endgame_fixture()
{:ok, _} = Endgames.update_endgame(endgame, %{}, [used_theme]) {:ok, _} = Endgames.update_endgame(endgame, %{}, [used_theme])
@@ -20,8 +20,9 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.IndexTest do
{:ok, view, _html} = live(conn, ~p"/admin/themes") {:ok, view, _html} = live(conn, ~p"/admin/themes")
assert has_element?(view, "#theme-#{used_theme.id}") assert has_element?(view, "#theme-#{used_theme.id}")
assert has_element?(view, "#theme-usage-#{used_theme.id}", "1 endgame") assert has_element?(view, "#theme-#{used_theme.id}", "technique")
assert has_element?(view, "#theme-usage-#{unused_theme.id}", "0 endgames") assert has_element?(view, "#theme-usage-#{used_theme.id}", "1 of 1 endgame")
assert has_element?(view, "#theme-usage-#{unused_theme.id}", "0 of 1 endgame")
end end
test "filters by name and category", %{conn: conn} do test "filters by name and category", %{conn: conn} do
@@ -57,7 +58,7 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.IndexTest do
{:ok, view, html} = live(conn, ~p"/admin/themes") {:ok, view, html} = live(conn, ~p"/admin/themes")
assert html =~ "Used by 1 endgame" assert html =~ "Used by 1 of 1 endgame"
assert html =~ "The endgames will be kept" assert html =~ "The endgames will be kept"
view |> element("#theme-#{theme.id} a", "Delete") |> render_click() view |> element("#theme-#{theme.id} a", "Delete") |> render_click()