mirror of
https://github.com/TheRealOwenRees/chess-endgame-trainer.git
synced 2026-11-18 03:32:06 +00:00
Compare commits
4
Commits
7209923de7
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2759b34296 | ||
|
|
e6f08e0ca6 | ||
|
|
946fc38756 | ||
|
|
80cb033077 |
@@ -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 """
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -111,8 +111,13 @@ defmodule Chesstrainer.Endgames do
|
||||
@doc """
|
||||
Returns `{key, count}` groups for endgames matching the filters, sorted by key.
|
||||
|
||||
Filters is a map with optional `:themes` (a list of theme ids; an endgame must
|
||||
carry any one of them) and `:key` (an exact Key).
|
||||
Filters is a map with optional:
|
||||
|
||||
* `:themes` - a list of theme ids; an endgame must carry any one of them
|
||||
* `:key` - an exact Key
|
||||
* `:with_theme` - `{theme_id, source}`; only endgames linked to the theme
|
||||
with that source
|
||||
* `:without_theme` - a theme id; only endgames not linked to the theme at all
|
||||
"""
|
||||
def list_key_groups(filters \\ %{}) do
|
||||
Endgame
|
||||
@@ -125,20 +130,31 @@ defmodule Chesstrainer.Endgames do
|
||||
|
||||
@doc """
|
||||
Returns the endgames for one Key, matching the filters, with themes preloaded.
|
||||
|
||||
Accepts `:limit` and `:offset` options for paginating large Key groups.
|
||||
"""
|
||||
def list_endgames_for_key(key, filters \\ %{}) do
|
||||
def list_endgames_for_key(key, filters \\ %{}, opts \\ []) do
|
||||
skip = Keyword.get(opts, :offset, 0)
|
||||
|
||||
Endgame
|
||||
|> apply_filters(filters)
|
||||
|> where([e], e.key == ^key)
|
||||
|> preload(:themes)
|
||||
|> order_by([e], asc: e.fen)
|
||||
|> order_by([e], asc: e.fen, asc: e.id)
|
||||
|> limit_query(Keyword.get(opts, :limit))
|
||||
|> offset(^skip)
|
||||
|> Repo.all()
|
||||
end
|
||||
|
||||
defp limit_query(query, nil), do: query
|
||||
defp limit_query(query, limit), do: limit(query, ^limit)
|
||||
|
||||
defp apply_filters(query, filters) do
|
||||
query
|
||||
|> filter_themes(Map.get(filters, :themes, []))
|
||||
|> filter_key(Map.get(filters, :key))
|
||||
|> filter_with_theme(Map.get(filters, :with_theme))
|
||||
|> filter_without_theme(Map.get(filters, :without_theme))
|
||||
end
|
||||
|
||||
defp filter_themes(query, []), do: query
|
||||
@@ -156,6 +172,30 @@ defmodule Chesstrainer.Endgames do
|
||||
defp filter_key(query, key) when key in [nil, ""], do: query
|
||||
defp filter_key(query, key), do: where(query, [e], e.key == ^key)
|
||||
|
||||
defp filter_with_theme(query, nil), do: query
|
||||
|
||||
defp filter_with_theme(query, {theme_id, source}) do
|
||||
endgame_ids =
|
||||
from(t in "endgames_themes",
|
||||
where: t.theme_id == ^theme_id and t.source == ^to_string(source),
|
||||
select: t.endgame_id
|
||||
)
|
||||
|
||||
where(query, [e], e.id in subquery(endgame_ids))
|
||||
end
|
||||
|
||||
defp filter_without_theme(query, nil), do: query
|
||||
|
||||
defp filter_without_theme(query, theme_id) do
|
||||
endgame_ids =
|
||||
from(t in "endgames_themes",
|
||||
where: t.theme_id == ^theme_id,
|
||||
select: t.endgame_id
|
||||
)
|
||||
|
||||
where(query, [e], e.id not in subquery(endgame_ids))
|
||||
end
|
||||
|
||||
@doc """
|
||||
Gets a single endgame.
|
||||
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
defmodule Chesstrainer.Endgames.MaterialThemes do
|
||||
@moduledoc """
|
||||
Derives each endgame's material family from its canonical Key.
|
||||
|
||||
Every endgame belongs to exactly one family, so the themes behave as a
|
||||
partition: selecting several in a filter produces their union, never an
|
||||
ambiguous intersection. A lone king against heavy or pawn material is split
|
||||
out because those positions teach a specific technique — basic mate or
|
||||
promotion — rather than a general material class.
|
||||
|
||||
Families are derived, never judged. They are stored with source `derived`, so
|
||||
a refresh replaces them without touching curated or community themes.
|
||||
Positions with no legal content (`K v K`) and rows without a Key are skipped.
|
||||
"""
|
||||
|
||||
import Ecto.Query, warn: false
|
||||
|
||||
alias Chesstrainer.Endgames.Endgame
|
||||
alias Chesstrainer.Repo
|
||||
alias Chesstrainer.Themes
|
||||
|
||||
@families [
|
||||
basic_mate: %{
|
||||
name: "basic mate",
|
||||
description:
|
||||
"A lone king against the queen or a rook, with no pawns: the puzzle is about delivering mate."
|
||||
},
|
||||
king_and_pawn: %{
|
||||
name: "king and pawn",
|
||||
description:
|
||||
"A lone king against king and pawns: the puzzle is about promotion, or holding the draw."
|
||||
},
|
||||
bare_king_other: %{
|
||||
name: "bare king other",
|
||||
description:
|
||||
"A lone king against minor pieces, or against pawns and pieces: usually a technique exercise with little counterplay."
|
||||
},
|
||||
queen_and_pawn: %{
|
||||
name: "queen and pawn",
|
||||
description: "Queens and pawns on the board."
|
||||
},
|
||||
queen_endgame: %{
|
||||
name: "queen endgame",
|
||||
description: "Queens on the board, with no pawns."
|
||||
},
|
||||
rook_and_pawn: %{
|
||||
name: "rook and pawn",
|
||||
description: "Rooks and pawns, with no queens."
|
||||
},
|
||||
rook_endgame: %{
|
||||
name: "rook endgame",
|
||||
description: "Rooks, with no queens and no pawns."
|
||||
},
|
||||
minor_piece_and_pawn: %{
|
||||
name: "minor piece and pawn",
|
||||
description: "Bishops and knights with pawns, with no queens or rooks."
|
||||
},
|
||||
minor_piece_endgame: %{
|
||||
name: "minor piece endgame",
|
||||
description: "Bishops and knights, with no queens, rooks or pawns."
|
||||
},
|
||||
pawn_endgame: %{
|
||||
name: "pawn endgame",
|
||||
description: "Kings and pawns only."
|
||||
}
|
||||
]
|
||||
|
||||
@type family ::
|
||||
:basic_mate
|
||||
| :king_and_pawn
|
||||
| :bare_king_other
|
||||
| :queen_and_pawn
|
||||
| :queen_endgame
|
||||
| :rook_and_pawn
|
||||
| :rook_endgame
|
||||
| :minor_piece_and_pawn
|
||||
| :minor_piece_endgame
|
||||
| :pawn_endgame
|
||||
|
||||
@doc "The material families, in a stable order."
|
||||
def families, do: @families
|
||||
|
||||
@doc """
|
||||
Returns the material family for a Key.
|
||||
|
||||
Returns `:kings_only` for `"K v K"` and `:unknown` when the Key is missing or
|
||||
not shaped like `"<side> v <side>"`.
|
||||
"""
|
||||
@spec family(String.t() | nil) :: family() | :kings_only | :unknown
|
||||
def family(key) when is_binary(key) do
|
||||
case String.split(key, " v ") do
|
||||
[a, b] ->
|
||||
cond do
|
||||
bare?(a) and bare?(b) -> :kings_only
|
||||
bare?(a) -> bare_king_family(counts(b))
|
||||
bare?(b) -> bare_king_family(counts(a))
|
||||
true -> material_family(merge(counts(a), counts(b)))
|
||||
end
|
||||
|
||||
_ ->
|
||||
:unknown
|
||||
end
|
||||
end
|
||||
|
||||
def family(_key), do: :unknown
|
||||
|
||||
@doc """
|
||||
Creates or corrects the material themes, keyed by family.
|
||||
|
||||
An existing theme with the same name is reused and its kind and description
|
||||
are corrected, so a theme seeded as a technique becomes a material theme
|
||||
without losing its existing links.
|
||||
"""
|
||||
@spec ensure_themes() :: %{family() => Chesstrainer.Themes.Theme.t()}
|
||||
def ensure_themes do
|
||||
Map.new(@families, fn {family, attrs} ->
|
||||
{:ok, theme} = Themes.get_or_create(attrs.name, "endgame", kind: :material)
|
||||
{family, ensure_material_theme(theme, attrs)}
|
||||
end)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Refreshes every endgame's derived material theme.
|
||||
|
||||
Returns the number of endgames tagged, the number skipped (kings only or no
|
||||
Key) and the number of material themes. Re-running is idempotent.
|
||||
"""
|
||||
@spec derive() :: %{
|
||||
tagged: non_neg_integer(),
|
||||
skipped: non_neg_integer(),
|
||||
themes: non_neg_integer()
|
||||
}
|
||||
def derive do
|
||||
themes = ensure_themes()
|
||||
material_ids = Enum.map(themes, fn {_family, theme} -> theme.id end)
|
||||
|
||||
{links, skipped} =
|
||||
Endgame
|
||||
|> select([e], {e.id, e.key})
|
||||
|> Repo.all()
|
||||
|> Enum.reduce({[], 0}, fn {id, key}, {links, skipped} ->
|
||||
case family(key) do
|
||||
family when family in [:kings_only, :unknown] ->
|
||||
{links, skipped + 1}
|
||||
|
||||
family ->
|
||||
{[{id, Map.fetch!(themes, family).id} | links], skipped}
|
||||
end
|
||||
end)
|
||||
|
||||
:ok = Themes.replace_theme_links(material_ids, links)
|
||||
|
||||
%{tagged: length(links), skipped: skipped, themes: map_size(themes)}
|
||||
end
|
||||
|
||||
defp ensure_material_theme(theme, attrs) do
|
||||
if theme.kind == :material and (theme.description || "") == attrs.description do
|
||||
theme
|
||||
else
|
||||
{:ok, updated} =
|
||||
Themes.update_theme(theme, %{kind: :material, description: attrs.description})
|
||||
|
||||
updated
|
||||
end
|
||||
end
|
||||
|
||||
defp bare?(side), do: side == "K"
|
||||
|
||||
defp bare_king_family(counts) do
|
||||
cond do
|
||||
count(counts, "P") == 0 and (count(counts, "Q") > 0 or count(counts, "R") > 0) ->
|
||||
:basic_mate
|
||||
|
||||
count(counts, "P") > 0 and count(counts, "Q") == 0 and count(counts, "R") == 0 ->
|
||||
:king_and_pawn
|
||||
|
||||
true ->
|
||||
:bare_king_other
|
||||
end
|
||||
end
|
||||
|
||||
defp material_family(counts) do
|
||||
cond do
|
||||
count(counts, "Q") > 0 and count(counts, "P") > 0 ->
|
||||
:queen_and_pawn
|
||||
|
||||
count(counts, "Q") > 0 ->
|
||||
:queen_endgame
|
||||
|
||||
count(counts, "R") > 0 and count(counts, "P") > 0 ->
|
||||
:rook_and_pawn
|
||||
|
||||
count(counts, "R") > 0 ->
|
||||
:rook_endgame
|
||||
|
||||
count(counts, "B") + count(counts, "N") > 0 and count(counts, "P") > 0 ->
|
||||
:minor_piece_and_pawn
|
||||
|
||||
count(counts, "B") + count(counts, "N") > 0 ->
|
||||
:minor_piece_endgame
|
||||
|
||||
count(counts, "P") > 0 ->
|
||||
:pawn_endgame
|
||||
|
||||
true ->
|
||||
:kings_only
|
||||
end
|
||||
end
|
||||
|
||||
defp counts(side), do: Enum.frequencies(String.graphemes(side))
|
||||
|
||||
defp merge(left, right), do: Map.merge(left, right, fn _piece, a, b -> a + b end)
|
||||
|
||||
defp count(counts, piece), do: Map.get(counts, piece, 0)
|
||||
end
|
||||
@@ -0,0 +1,198 @@
|
||||
defmodule Chesstrainer.Endgames.MotifThemes do
|
||||
@moduledoc """
|
||||
Derives objective motif themes by probing each endgame's position.
|
||||
|
||||
Motifs describe the kind of problem, independent of the material family: an
|
||||
endgame can be a rook endgame and an only-move puzzle at the same time. Every
|
||||
motif is proved from the local Syzygy tables — one probe returns the root WDL,
|
||||
the DTZ and every legal move with its own WDL — so nothing here is a guess and
|
||||
nothing calls the remote backend.
|
||||
|
||||
Motif links are recorded as `derived` and refreshed as a whole. Material
|
||||
families, curated links and community links are untouched because the refresh
|
||||
is scoped to the motif themes.
|
||||
|
||||
Loss endgames are skipped: only-move is undefined when every move loses, and
|
||||
the library no longer contains them.
|
||||
"""
|
||||
|
||||
import Ecto.Query, warn: false
|
||||
|
||||
alias Chesstrainer.Endgames.Endgame
|
||||
alias Chesstrainer.Endgames.Tablebase
|
||||
alias Chesstrainer.Endgames.Tablebase.Backend.Fathom, as: FathomBackend
|
||||
alias Chesstrainer.Repo
|
||||
alias Chesstrainer.Themes
|
||||
|
||||
@motifs [
|
||||
only_move: %{
|
||||
name: "only move",
|
||||
description:
|
||||
"Exactly one legal move keeps the result, so the puzzle is about finding the single accurate move."
|
||||
},
|
||||
underpromotion: %{
|
||||
name: "underpromotion",
|
||||
description:
|
||||
"The result can only be preserved by promoting to a rook, bishop or knight; promoting to a queen does not work."
|
||||
},
|
||||
fifty_move_draw: %{
|
||||
name: "50-move draw",
|
||||
description:
|
||||
"The result turns on the fifty-move rule: the win needs more moves than the halfmove clock allows, so the defender can claim a draw."
|
||||
}
|
||||
]
|
||||
|
||||
@type motif :: :only_move | :underpromotion | :fifty_move_draw
|
||||
|
||||
@doc "The motif themes, in a stable order."
|
||||
def motifs, do: @motifs
|
||||
|
||||
@doc """
|
||||
Returns the motifs for one probed position.
|
||||
|
||||
`moves` are Fathom move tuples `{wdl, from, to, promotes, ep, dtz}` and carry
|
||||
the mover's perspective, so they are compared with the root WDL directly.
|
||||
`halfmove_clock` comes from the FEN; the probe itself runs with `rule50 = 0`.
|
||||
"""
|
||||
@spec motifs_for(atom(), integer() | nil, [tuple()], non_neg_integer()) :: [motif()]
|
||||
def motifs_for(wdl, dtz, moves, halfmove_clock) do
|
||||
outcome = Tablebase.normalize_wdl(wdl)
|
||||
|
||||
preserving =
|
||||
Enum.filter(moves, fn {move_wdl, _from, _to, _promotes, _ep, _dtz} ->
|
||||
Tablebase.normalize_wdl(move_wdl) == outcome
|
||||
end)
|
||||
|
||||
[]
|
||||
|> maybe_only_move(outcome, moves, preserving)
|
||||
|> maybe_underpromotion(preserving)
|
||||
|> maybe_fifty_move(wdl, dtz, halfmove_clock)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Creates or corrects the motif themes, keyed by motif.
|
||||
|
||||
An existing theme with the same name is reused and its kind and description
|
||||
are corrected, so a theme seeded as a technique becomes a motif without
|
||||
losing its existing links.
|
||||
"""
|
||||
@spec ensure_themes() :: %{motif() => Chesstrainer.Themes.Theme.t()}
|
||||
def ensure_themes do
|
||||
Map.new(@motifs, fn {motif, attrs} ->
|
||||
{:ok, theme} = Themes.get_or_create(attrs.name, "endgame", kind: :motif)
|
||||
{motif, ensure_motif_theme(theme, attrs)}
|
||||
end)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Refreshes every endgame's derived motif links.
|
||||
|
||||
Returns the number of links written, the number of endgames skipped because
|
||||
the local tables could not answer them, and a count per motif. Re-running is
|
||||
idempotent.
|
||||
"""
|
||||
@spec derive() :: %{
|
||||
links: non_neg_integer(),
|
||||
skipped: non_neg_integer(),
|
||||
by_motif: %{motif() => non_neg_integer()},
|
||||
themes: non_neg_integer()
|
||||
}
|
||||
def derive do
|
||||
themes = ensure_themes()
|
||||
motif_ids = Enum.map(themes, fn {_motif, theme} -> theme.id end)
|
||||
|
||||
initial_counts = Map.new(@motifs, fn {motif, _attrs} -> {motif, 0} end)
|
||||
|
||||
{links, skipped, by_motif} =
|
||||
Endgame
|
||||
|> where([e], e.result in [:win, :draw])
|
||||
|> select([e], {e.id, e.fen})
|
||||
|> Repo.all()
|
||||
|> Enum.reduce({[], 0, initial_counts}, fn {id, fen}, {links, skipped, counts} ->
|
||||
case probe(fen) do
|
||||
{:ok, %{wdl: wdl, dtz: dtz, moves: moves}} ->
|
||||
motifs = motifs_for(wdl, dtz, moves, halfmove_clock(fen))
|
||||
|
||||
links =
|
||||
Enum.reduce(motifs, links, fn motif, acc ->
|
||||
[{id, Map.fetch!(themes, motif).id} | acc]
|
||||
end)
|
||||
|
||||
counts =
|
||||
Enum.reduce(motifs, counts, fn motif, acc ->
|
||||
Map.update!(acc, motif, &(&1 + 1))
|
||||
end)
|
||||
|
||||
{links, skipped, counts}
|
||||
|
||||
{:error, _reason} ->
|
||||
{links, skipped + 1, counts}
|
||||
end
|
||||
end)
|
||||
|
||||
:ok = Themes.replace_theme_links(motif_ids, links)
|
||||
|
||||
%{links: length(links), skipped: skipped, by_motif: by_motif, themes: map_size(themes)}
|
||||
end
|
||||
|
||||
defp ensure_motif_theme(theme, attrs) do
|
||||
if theme.kind == :motif and (theme.description || "") == attrs.description do
|
||||
theme
|
||||
else
|
||||
{:ok, updated} =
|
||||
Themes.update_theme(theme, %{kind: :motif, description: attrs.description})
|
||||
|
||||
updated
|
||||
end
|
||||
end
|
||||
|
||||
defp probe(fen), do: probe_module().probe_local_detail(fen)
|
||||
|
||||
defp probe_module do
|
||||
Application.get_env(:chesstrainer, :motif_probe, FathomBackend)
|
||||
end
|
||||
|
||||
defp maybe_only_move(acc, outcome, moves, preserving) do
|
||||
if outcome in [:win, :draw] and length(moves) > 1 and length(preserving) == 1 do
|
||||
[:only_move | acc]
|
||||
else
|
||||
acc
|
||||
end
|
||||
end
|
||||
|
||||
defp maybe_underpromotion(acc, preserving) do
|
||||
underpromotes? =
|
||||
Enum.any?(preserving, fn {_wdl, _from, _to, promotes, _ep, _dtz} ->
|
||||
promotes in [2, 3, 4]
|
||||
end)
|
||||
|
||||
queen_promotes? =
|
||||
Enum.any?(preserving, fn {_wdl, _from, _to, promotes, _ep, _dtz} ->
|
||||
promotes == 1
|
||||
end)
|
||||
|
||||
if underpromotes? and not queen_promotes?, do: [:underpromotion | acc], else: acc
|
||||
end
|
||||
|
||||
defp maybe_fifty_move(acc, wdl, dtz, halfmove_clock) do
|
||||
table_draw? = wdl in [:cursed_win, :blessed_loss]
|
||||
|
||||
clock_exhausted? =
|
||||
wdl == :win and is_integer(dtz) and dtz > 100 - halfmove_clock
|
||||
|
||||
if table_draw? or clock_exhausted?, do: [:fifty_move_draw | acc], else: acc
|
||||
end
|
||||
|
||||
defp halfmove_clock(fen) do
|
||||
case String.split(fen, " ") do
|
||||
[_board, _active, _castling, _ep, clock, _fullmove] ->
|
||||
case Integer.parse(clock) do
|
||||
{value, _rest} -> value
|
||||
:error -> 0
|
||||
end
|
||||
|
||||
_ ->
|
||||
0
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -80,6 +80,38 @@ defmodule Chesstrainer.Endgames.Tablebase.Backend.Fathom do
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Probes the local tablebase and returns the raw root outcome and move list.
|
||||
|
||||
Unlike `probe_result_local/1`, this keeps the per-move tuples and the raw WDL
|
||||
atom, including `:cursed_win` and `:blessed_loss`, which the motif derivation
|
||||
needs. It never falls back to the remote backend or consults the cache.
|
||||
|
||||
Returns `{:error, :unsupported}` when the local files cannot answer the
|
||||
position, including a partial tablebase set where Fathom reports `:failed`.
|
||||
"""
|
||||
@spec probe_local_detail(String.t()) ::
|
||||
{:ok, %{wdl: atom(), dtz: integer(), moves: [tuple()]}}
|
||||
| {:error, :not_configured | :terminal | :unsupported}
|
||||
def probe_local_detail(fen) do
|
||||
with {:ok, largest} <- Local.check(),
|
||||
pieces when is_integer(pieces) <- FEN.piece_count(fen),
|
||||
true <- pieces <= largest || {:error, :unsupported},
|
||||
{:ok, {root, moves}} <- Nif.probe(fen) do
|
||||
case root do
|
||||
:failed -> {:error, :unsupported}
|
||||
:checkmate -> {:error, :terminal}
|
||||
:stalemate -> {:error, :terminal}
|
||||
{wdl, _from, _to, _promotes, _ep, dtz} -> {:ok, %{wdl: wdl, dtz: dtz, moves: moves}}
|
||||
end
|
||||
else
|
||||
{:error, :not_configured} = error -> error
|
||||
{:error, :unsupported} = error -> error
|
||||
{:error, _reason} -> {:error, :unsupported}
|
||||
nil -> {:error, :unsupported}
|
||||
end
|
||||
end
|
||||
|
||||
defp fallback(fen) do
|
||||
(Application.get_env(:chesstrainer, :tablebase_fallback) || Lichess).probe(fen)
|
||||
end
|
||||
|
||||
@@ -18,6 +18,28 @@ defmodule Chesstrainer.Release do
|
||||
{:ok, _, _} = Ecto.Migrator.with_repo(repo, &Ecto.Migrator.run(&1, :down, to: version))
|
||||
end
|
||||
|
||||
@doc """
|
||||
Derives material family themes for the whole library.
|
||||
|
||||
Runs in the release without starting the web application: `with_repo/2`
|
||||
starts just the repository, which is all the derivation needs.
|
||||
"""
|
||||
def derive_material, do: with_repo(&Chesstrainer.Endgames.MaterialThemes.derive/0)
|
||||
|
||||
@doc """
|
||||
Derives motif themes from the local tablebase for the whole library.
|
||||
"""
|
||||
def derive_motifs, do: with_repo(&Chesstrainer.Endgames.MotifThemes.derive/0)
|
||||
|
||||
defp with_repo(fun) do
|
||||
load_app()
|
||||
|
||||
for repo <- repos() do
|
||||
{:ok, result, _} = Ecto.Migrator.with_repo(repo, fn _repo -> fun.() end)
|
||||
result
|
||||
end
|
||||
end
|
||||
|
||||
defp repos do
|
||||
Application.fetch_env!(@app, :ecto_repos)
|
||||
end
|
||||
|
||||
+184
-3
@@ -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,167 @@ 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 every link to `scoped_theme_ids` with the derived links in `links`.
|
||||
|
||||
This is for themes that are objectively derived: the pass owns its themes
|
||||
entirely, so a link's previous source is irrelevant and every link is
|
||||
rewritten as `derived`. Links to themes outside `scoped_theme_ids` — curated
|
||||
or community — are untouched.
|
||||
|
||||
The operation is a full refresh for the given themes, so it can move an
|
||||
endgame between families when a rule changes. `links` is a list of
|
||||
`{endgame_id, theme_id}` pairs.
|
||||
"""
|
||||
@spec replace_theme_links([term()], [{Ecto.UUID.t(), term()}]) :: :ok
|
||||
def replace_theme_links(scoped_theme_ids, links) when is_list(links) do
|
||||
now = DateTime.utc_now() |> DateTime.truncate(:second)
|
||||
|
||||
Repo.transaction(fn ->
|
||||
if scoped_theme_ids != [] do
|
||||
Repo.delete_all(
|
||||
from l in "endgames_themes",
|
||||
where: l.theme_id in ^scoped_theme_ids
|
||||
)
|
||||
end
|
||||
|
||||
links
|
||||
|> Enum.map(fn {endgame_id, theme_id} ->
|
||||
%{
|
||||
endgame_id: Ecto.UUID.dump!(endgame_id),
|
||||
theme_id: theme_id,
|
||||
source: "derived",
|
||||
inserted_at: now
|
||||
}
|
||||
end)
|
||||
|> Enum.chunk_every(5_000)
|
||||
|> Enum.each(fn rows ->
|
||||
Repo.insert_all("endgames_themes", rows, on_conflict: :nothing)
|
||||
end)
|
||||
end)
|
||||
|
||||
:ok
|
||||
end
|
||||
|
||||
@link_sources [:curated, :community]
|
||||
|
||||
@doc """
|
||||
Links `theme` to many endgames at once with the given source.
|
||||
|
||||
Defaults to `:curated`, which is what the admin tagging workspace writes.
|
||||
Existing links are left alone, so re-applying is safe. Returns the number of
|
||||
endgames the link was attempted for.
|
||||
"""
|
||||
@spec tag_endgames(Theme.t(), [Ecto.UUID.t()], :curated | :community) ::
|
||||
{:ok, non_neg_integer()}
|
||||
def tag_endgames(%Theme{id: theme_id}, endgame_ids, source \\ :curated)
|
||||
when is_list(endgame_ids) and source in @link_sources do
|
||||
now = DateTime.utc_now() |> DateTime.truncate(:second)
|
||||
|
||||
endgame_ids
|
||||
|> Enum.uniq()
|
||||
|> Enum.map(fn endgame_id ->
|
||||
%{
|
||||
endgame_id: Ecto.UUID.dump!(endgame_id),
|
||||
theme_id: theme_id,
|
||||
source: to_string(source),
|
||||
inserted_at: now
|
||||
}
|
||||
end)
|
||||
|> Enum.chunk_every(5_000)
|
||||
|> Enum.each(fn rows ->
|
||||
Repo.insert_all("endgames_themes", rows, on_conflict: :nothing)
|
||||
end)
|
||||
|
||||
{:ok, length(Enum.uniq(endgame_ids))}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Removes a link from `theme` to one endgame, but only if it has the given
|
||||
source.
|
||||
|
||||
The tagging workspace removes `:curated` links only, so a derived or
|
||||
community link can never be deleted by hand. Returns the number removed.
|
||||
"""
|
||||
@spec untag_endgame(Theme.t(), Ecto.UUID.t(), :curated | :community) ::
|
||||
{:ok, non_neg_integer()}
|
||||
def untag_endgame(%Theme{id: theme_id}, endgame_id, source \\ :curated)
|
||||
when source in @link_sources do
|
||||
{count, _} =
|
||||
Repo.delete_all(
|
||||
from l in "endgames_themes",
|
||||
where:
|
||||
l.theme_id == ^theme_id and l.endgame_id == type(^endgame_id, :binary_id) and
|
||||
l.source == ^to_string(source)
|
||||
)
|
||||
|
||||
{:ok, count}
|
||||
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)
|
||||
|
||||
|
||||
@@ -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,26 +71,36 @@ 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">
|
||||
<.link
|
||||
:if={theme.category == :endgame and theme.kind == :technique}
|
||||
navigate={~p"/admin/themes/#{theme.id}/tag"}
|
||||
>
|
||||
Tag
|
||||
</.link>
|
||||
<.link navigate={~p"/admin/themes/#{theme.id}/edit"}>Edit</.link>
|
||||
<.link
|
||||
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 +164,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
|
||||
|
||||
@@ -0,0 +1,460 @@
|
||||
defmodule ChesstrainerWeb.Admin.ThemeLive.Tag do
|
||||
@moduledoc """
|
||||
Workspace for applying a technique theme to endgames by family.
|
||||
|
||||
Candidates are grouped by Key so an admin tags a whole family rather than
|
||||
individual rows. Boards are previews only; nothing here starts a puzzle.
|
||||
Only technique themes can be tagged, because material themes are derived and
|
||||
a hand-made link would be erased by the next refresh.
|
||||
"""
|
||||
|
||||
use ChesstrainerWeb, :live_view
|
||||
|
||||
alias Chesstrainer.Endgames
|
||||
alias Chesstrainer.Game
|
||||
alias Chesstrainer.Themes
|
||||
|
||||
import ChesstrainerWeb.Board.BoardComponent
|
||||
|
||||
@page_size 24
|
||||
|
||||
@impl true
|
||||
def render(assigns) do
|
||||
~H"""
|
||||
<Layouts.app flash={@flash} wide>
|
||||
<Layouts.admin_nav current_scope={@current_scope} />
|
||||
|
||||
<.header>
|
||||
Tag “{@theme.name}”
|
||||
<:subtitle>
|
||||
Pick a family, preview the positions and apply the theme in bulk. The links are
|
||||
recorded as curated, so derivation never overwrites them.
|
||||
</:subtitle>
|
||||
<:actions>
|
||||
<.button navigate={~p"/admin/themes"}>
|
||||
<.icon name="hero-arrow-left" /> All themes
|
||||
</.button>
|
||||
</:actions>
|
||||
</.header>
|
||||
|
||||
<.form
|
||||
for={@theme_form}
|
||||
id="theme-workspace-form"
|
||||
phx-change="select_theme"
|
||||
class="mb-6 max-w-md"
|
||||
>
|
||||
<.input
|
||||
field={@theme_form[:theme_id]}
|
||||
type="select"
|
||||
label="Technique theme"
|
||||
options={@theme_options}
|
||||
/>
|
||||
</.form>
|
||||
|
||||
<div class="mb-6 flex flex-wrap gap-6 text-sm">
|
||||
<span>
|
||||
<span class="font-semibold" id="tagged-count">{@tagged_count}</span> tagged
|
||||
</span>
|
||||
<span>
|
||||
<span class="font-semibold" id="candidate-count">{@candidate_count}</span> candidates
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
:if={MapSet.size(@selected) > 0}
|
||||
id="selection-bar"
|
||||
class="sticky top-0 z-10 mb-6 flex flex-wrap items-center gap-3 rounded-lg border border-primary/30 bg-base-100 p-3 text-sm"
|
||||
>
|
||||
<span class="font-semibold">{MapSet.size(@selected)} selected</span>
|
||||
<button
|
||||
type="button"
|
||||
id="apply-theme"
|
||||
phx-click="apply"
|
||||
class="font-semibold text-primary-text"
|
||||
>
|
||||
Apply “{@theme.name}”
|
||||
</button>
|
||||
<button type="button" phx-click="clear_selection" class="text-base-content/70">
|
||||
Clear selection
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<section class="mb-12">
|
||||
<h2 class="mb-3 text-lg font-semibold">Candidates</h2>
|
||||
<p :if={@candidate_groups == []} class="text-base-content/70">
|
||||
Every endgame already carries this theme.
|
||||
</p>
|
||||
|
||||
<table :if={@candidate_groups != []} class={table_class()}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Key</th>
|
||||
<th>Endgames</th>
|
||||
<th><span class="sr-only">Actions</span></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr :for={{key, count} <- @candidate_groups} id={"candidates-#{group_id(key)}"}>
|
||||
<td class="font-mono">{key}</td>
|
||||
<td>{count}</td>
|
||||
<td class="w-0">
|
||||
<button
|
||||
type="button"
|
||||
id={"toggle-candidates-#{group_id(key)}"}
|
||||
phx-click="toggle_group"
|
||||
phx-value-key={key}
|
||||
phx-value-view="candidates"
|
||||
class="font-semibold text-primary-text"
|
||||
>
|
||||
{open_label(@open, key, "candidates")}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<.group_panel
|
||||
:if={@open && @open.view == "candidates"}
|
||||
view="candidates"
|
||||
group={@open.key}
|
||||
items={@items}
|
||||
selected={@selected}
|
||||
page={@page}
|
||||
pages={@pages}
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2 class="mb-3 text-lg font-semibold">Curated links</h2>
|
||||
<p :if={@tagged_groups == []} class="text-base-content/70">
|
||||
No endgame carries this theme yet.
|
||||
</p>
|
||||
|
||||
<table :if={@tagged_groups != []} class={table_class()}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Key</th>
|
||||
<th>Endgames</th>
|
||||
<th><span class="sr-only">Actions</span></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr :for={{key, count} <- @tagged_groups} id={"tagged-#{group_id(key)}"}>
|
||||
<td class="font-mono">{key}</td>
|
||||
<td>{count}</td>
|
||||
<td class="w-0">
|
||||
<button
|
||||
type="button"
|
||||
id={"toggle-tagged-#{group_id(key)}"}
|
||||
phx-click="toggle_group"
|
||||
phx-value-key={key}
|
||||
phx-value-view="tagged"
|
||||
class="font-semibold text-primary-text"
|
||||
>
|
||||
{open_label(@open, key, "tagged")}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<.group_panel
|
||||
:if={@open && @open.view == "tagged"}
|
||||
view="tagged"
|
||||
group={@open.key}
|
||||
items={@items}
|
||||
selected={@selected}
|
||||
page={@page}
|
||||
pages={@pages}
|
||||
/>
|
||||
</section>
|
||||
</Layouts.app>
|
||||
"""
|
||||
end
|
||||
|
||||
attr :view, :string, required: true
|
||||
attr :group, :string, required: true
|
||||
attr :items, :list, required: true
|
||||
attr :selected, :any, required: true
|
||||
attr :page, :integer, required: true
|
||||
attr :pages, :integer, required: true
|
||||
|
||||
defp group_panel(assigns) do
|
||||
~H"""
|
||||
<div id="group-panel" class="mt-4">
|
||||
<div :if={@view == "candidates"} class="mb-3 flex gap-3 text-sm">
|
||||
<button
|
||||
type="button"
|
||||
id="select-page"
|
||||
phx-click="select_page"
|
||||
class="font-semibold text-primary-text"
|
||||
>
|
||||
Select this page
|
||||
</button>
|
||||
<span class="text-base-content/60">{@group}</span>
|
||||
</div>
|
||||
|
||||
<p :if={@items == []} class="text-base-content/70">No endgames on this page.</p>
|
||||
|
||||
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||
<div
|
||||
:for={endgame <- @items}
|
||||
id={"endgame-#{endgame.id}"}
|
||||
class="rounded-lg border border-base-300 p-3"
|
||||
>
|
||||
<.board
|
||||
game={endgame.game}
|
||||
myself={nil}
|
||||
interactive={false}
|
||||
class="mb-2 w-full max-w-[240px]"
|
||||
/>
|
||||
<p class="break-all font-mono text-xs text-base-content/60">{endgame.fen}</p>
|
||||
|
||||
<label :if={@view == "candidates"} class="mt-2 flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
id={"select-#{endgame.id}"}
|
||||
checked={MapSet.member?(@selected, endgame.id)}
|
||||
phx-click="toggle_select"
|
||||
phx-value-id={endgame.id}
|
||||
/> Select
|
||||
</label>
|
||||
|
||||
<button
|
||||
:if={@view == "tagged"}
|
||||
type="button"
|
||||
id={"remove-#{endgame.id}"}
|
||||
phx-click="remove"
|
||||
phx-value-id={endgame.id}
|
||||
class="mt-2 text-sm font-semibold text-error"
|
||||
>
|
||||
Remove
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div :if={@pages > 1} class="mt-4 flex items-center gap-3 text-sm">
|
||||
<button
|
||||
type="button"
|
||||
phx-click="page"
|
||||
phx-value-page={@page - 1}
|
||||
disabled={@page <= 1}
|
||||
class="font-semibold disabled:opacity-40"
|
||||
>
|
||||
Previous
|
||||
</button>
|
||||
<span>Page {@page} of {@pages}</span>
|
||||
<button
|
||||
type="button"
|
||||
phx-click="page"
|
||||
phx-value-page={@page + 1}
|
||||
disabled={@page >= @pages}
|
||||
class="font-semibold disabled:opacity-40"
|
||||
>
|
||||
Next
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
"""
|
||||
end
|
||||
|
||||
@impl true
|
||||
def mount(%{"id" => id}, _session, socket) do
|
||||
theme = Themes.get_theme!(id)
|
||||
|
||||
if theme.category == :endgame and theme.kind == :technique do
|
||||
{:ok,
|
||||
socket
|
||||
|> assign(:page_title, "Tag #{theme.name}")
|
||||
|> assign(:theme, theme)
|
||||
|> assign(:selected, MapSet.new())
|
||||
|> assign(:open, nil)
|
||||
|> assign(:items, [])
|
||||
|> assign(:page, 1)
|
||||
|> assign(:pages, 1)
|
||||
|> assign_theme_options()
|
||||
|> load_counts()}
|
||||
else
|
||||
{:ok,
|
||||
socket
|
||||
|> put_flash(
|
||||
:error,
|
||||
"Only technique themes can be tagged by hand; material themes are derived."
|
||||
)
|
||||
|> push_navigate(to: ~p"/admin/themes")}
|
||||
end
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_event("select_theme", %{"theme_id" => id}, socket) do
|
||||
if to_string(socket.assigns.theme.id) == id do
|
||||
{:noreply, socket}
|
||||
else
|
||||
{:noreply, push_navigate(socket, to: ~p"/admin/themes/#{id}/tag")}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_event("toggle_group", %{"key" => key, "view" => view}, socket) do
|
||||
case socket.assigns.open do
|
||||
%{key: ^key, view: ^view} ->
|
||||
{:noreply, assign(socket, open: nil, items: [], page: 1, pages: 1)}
|
||||
|
||||
_ ->
|
||||
{:noreply, open_group(socket, key, view, 1)}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_event("page", %{"page" => page}, socket) do
|
||||
case socket.assigns.open do
|
||||
nil ->
|
||||
{:noreply, socket}
|
||||
|
||||
%{key: key, view: view} ->
|
||||
{:noreply, open_group(socket, key, view, parse_page(page))}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_event("toggle_select", %{"id" => id}, socket) do
|
||||
selected =
|
||||
if MapSet.member?(socket.assigns.selected, id) do
|
||||
MapSet.delete(socket.assigns.selected, id)
|
||||
else
|
||||
MapSet.put(socket.assigns.selected, id)
|
||||
end
|
||||
|
||||
{:noreply, assign(socket, :selected, selected)}
|
||||
end
|
||||
|
||||
def handle_event("select_page", _params, socket) do
|
||||
page_ids = Enum.map(socket.assigns.items, & &1.id)
|
||||
selected = Enum.reduce(page_ids, socket.assigns.selected, &MapSet.put(&2, &1))
|
||||
{:noreply, assign(socket, :selected, selected)}
|
||||
end
|
||||
|
||||
def handle_event("clear_selection", _params, socket) do
|
||||
{:noreply, assign(socket, :selected, MapSet.new())}
|
||||
end
|
||||
|
||||
def handle_event("apply", _params, socket) do
|
||||
selected = MapSet.to_list(socket.assigns.selected)
|
||||
|
||||
if selected == [] do
|
||||
{:noreply, put_flash(socket, :error, "Select at least one endgame.")}
|
||||
else
|
||||
{:ok, count} = Themes.tag_endgames(socket.assigns.theme, selected, :curated)
|
||||
|
||||
{:noreply,
|
||||
socket
|
||||
|> put_flash(:info, "Tagged #{count} endgame(s) with “#{socket.assigns.theme.name}”.")
|
||||
|> assign(:selected, MapSet.new())
|
||||
|> assign(open: nil, items: [], page: 1, pages: 1)
|
||||
|> load_counts()}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_event("remove", %{"id" => id}, socket) do
|
||||
{:ok, removed} = Themes.untag_endgame(socket.assigns.theme, id, :curated)
|
||||
|
||||
socket =
|
||||
socket
|
||||
|> put_flash(:info, removal_message(removed, socket.assigns.theme))
|
||||
|> load_counts()
|
||||
|> refresh_open()
|
||||
|
||||
{:noreply, socket}
|
||||
end
|
||||
|
||||
defp removal_message(0, theme), do: "That endgame had no curated “#{theme.name}” link."
|
||||
defp removal_message(_, theme), do: "Removed “#{theme.name}” from the endgame."
|
||||
|
||||
defp refresh_open(%{assigns: %{open: nil}} = socket), do: socket
|
||||
|
||||
defp refresh_open(%{assigns: %{open: %{key: key, view: view}, page: page}} = socket) do
|
||||
open_group(socket, key, view, page)
|
||||
end
|
||||
|
||||
defp open_group(socket, key, view, page) do
|
||||
count = group_count(socket, key, view)
|
||||
pages = max(ceil_div(count, @page_size), 1)
|
||||
page = page |> max(1) |> min(pages)
|
||||
|
||||
endgames =
|
||||
Endgames.list_endgames_for_key(key, filters_for(socket.assigns.theme, view),
|
||||
limit: @page_size,
|
||||
offset: (page - 1) * @page_size
|
||||
)
|
||||
|> Enum.map(&Map.put(&1, :game, board_game(&1.fen)))
|
||||
|
||||
assign(socket,
|
||||
open: %{key: key, view: view},
|
||||
items: endgames,
|
||||
page: page,
|
||||
pages: pages
|
||||
)
|
||||
end
|
||||
|
||||
defp filters_for(%{id: theme_id}, "tagged"), do: %{with_theme: {theme_id, :curated}}
|
||||
defp filters_for(%{id: theme_id}, "candidates"), do: %{without_theme: theme_id}
|
||||
|
||||
defp group_count(socket, key, view) do
|
||||
groups =
|
||||
if view == "tagged", do: socket.assigns.tagged_groups, else: socket.assigns.candidate_groups
|
||||
|
||||
Enum.find_value(groups, 0, fn
|
||||
{^key, count} -> count
|
||||
_ -> nil
|
||||
end)
|
||||
end
|
||||
|
||||
defp parse_page(page) when is_integer(page), do: page
|
||||
|
||||
defp parse_page(page) when is_binary(page) do
|
||||
case Integer.parse(page) do
|
||||
{value, _} -> value
|
||||
:error -> 1
|
||||
end
|
||||
end
|
||||
|
||||
defp ceil_div(0, _), do: 0
|
||||
defp ceil_div(count, size), do: div(count + size - 1, size)
|
||||
|
||||
defp load_counts(socket) do
|
||||
theme = socket.assigns.theme
|
||||
tagged = Endgames.list_key_groups(%{with_theme: {theme.id, :curated}})
|
||||
candidates = Endgames.list_key_groups(%{without_theme: theme.id})
|
||||
|
||||
assign(socket,
|
||||
tagged_groups: tagged,
|
||||
candidate_groups: candidates,
|
||||
tagged_count: total(tagged),
|
||||
candidate_count: total(candidates)
|
||||
)
|
||||
end
|
||||
|
||||
defp total(groups), do: Enum.reduce(groups, 0, fn {_key, count}, acc -> acc + count end)
|
||||
|
||||
defp assign_theme_options(socket) do
|
||||
options =
|
||||
Themes.list_themes()
|
||||
|> Enum.filter(&(&1.category == :endgame and &1.kind == :technique))
|
||||
|> Enum.sort_by(& &1.name)
|
||||
|> Enum.map(&{&1.name, &1.id})
|
||||
|
||||
assign(socket,
|
||||
theme_options: options,
|
||||
theme_form: to_form(%{"theme_id" => to_string(socket.assigns.theme.id)})
|
||||
)
|
||||
end
|
||||
|
||||
defp board_game(fen) do
|
||||
case Game.game_from_fen(fen, :endgame) do
|
||||
{:ok, game} -> game
|
||||
{:error, :invalid_fen, game} -> game
|
||||
end
|
||||
end
|
||||
|
||||
defp open_label(%{key: key, view: view}, key, view), do: "Hide"
|
||||
defp open_label(_open, _key, _view), do: "Show"
|
||||
|
||||
defp group_id(key), do: String.replace(key, ~r/[^A-Za-z0-9]+/, "-")
|
||||
end
|
||||
@@ -55,6 +55,7 @@ defmodule ChesstrainerWeb.Router do
|
||||
live "/themes", Admin.ThemeLive.Index, :index
|
||||
live "/themes/new", Admin.ThemeLive.Form, :new
|
||||
live "/themes/:id/edit", Admin.ThemeLive.Form, :edit
|
||||
live "/themes/:id/tag", Admin.ThemeLive.Tag, :tag
|
||||
|
||||
live "/users", Admin.UserLive.Index, :index
|
||||
live "/users/new", Admin.UserLive.New, :new
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
defmodule Mix.Tasks.Themes.DeriveMaterial do
|
||||
use Mix.Task
|
||||
|
||||
@shortdoc "Tags every endgame with its material family theme"
|
||||
|
||||
@moduledoc """
|
||||
Derives each endgame's material family from its Key and stores the result as
|
||||
a derived theme.
|
||||
|
||||
mix themes.derive_material
|
||||
|
||||
Every endgame belongs to exactly one family, so the themes partition the
|
||||
library. Re-running is idempotent: only derived links are replaced, and
|
||||
curated or community links are untouched.
|
||||
|
||||
Positions that are kings only, or that have no Key, are reported as skipped.
|
||||
"""
|
||||
|
||||
@impl Mix.Task
|
||||
def run(_args) do
|
||||
Mix.Task.run("app.start")
|
||||
|
||||
%{tagged: tagged, skipped: skipped, themes: themes} =
|
||||
Chesstrainer.Endgames.MaterialThemes.derive()
|
||||
|
||||
Mix.shell().info(
|
||||
"Material themes: #{themes} themes, #{tagged} endgames tagged, " <>
|
||||
"#{skipped} skipped (kings only or no Key)."
|
||||
)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,32 @@
|
||||
defmodule Mix.Tasks.Themes.DeriveMotifs do
|
||||
use Mix.Task
|
||||
|
||||
@shortdoc "Tags every endgame with its tablebase-proved motifs"
|
||||
|
||||
@moduledoc """
|
||||
Derives only-move, underpromotion and 50-move-draw motifs from the local
|
||||
Syzygy tablebase.
|
||||
|
||||
mix themes.derive_motifs
|
||||
|
||||
The pass never calls the remote tablebase. Positions the local files cannot
|
||||
answer are skipped and reported. Re-running is idempotent: only links to the
|
||||
motif themes are replaced, so material, curated and community links survive.
|
||||
"""
|
||||
|
||||
@impl Mix.Task
|
||||
def run(_args) do
|
||||
Mix.Task.run("app.start")
|
||||
|
||||
%{links: links, skipped: skipped, by_motif: by_motif, themes: themes} =
|
||||
Chesstrainer.Endgames.MotifThemes.derive()
|
||||
|
||||
Mix.shell().info(
|
||||
"Motif themes: #{themes} themes, #{links} link(s) written, #{skipped} endgame(s) skipped."
|
||||
)
|
||||
|
||||
for {motif, count} <- Enum.sort(by_motif) do
|
||||
Mix.shell().info(" #{motif}: #{count}")
|
||||
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
@@ -59,7 +59,14 @@ theme_names =
|
||||
Repo.insert_all(
|
||||
Theme,
|
||||
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),
|
||||
on_conflict: :nothing
|
||||
)
|
||||
|
||||
@@ -6,8 +6,7 @@ defmodule Chesstrainer.Repo.Seeds.Endgames.Win do
|
||||
color: :white,
|
||||
message: "Rook vs king endgame",
|
||||
notes: "Basic rook endgame",
|
||||
result: :win,
|
||||
themes: ["rook endgame"]
|
||||
result: :win
|
||||
},
|
||||
%{
|
||||
fen: "8/8/8/1P4p1/5k2/5p2/P6K/8 b - - 0 0",
|
||||
|
||||
@@ -8,6 +8,10 @@ defmodule Chesstrainer.Repo.Seeds.Themes do
|
||||
"Lucena",
|
||||
"Philidor",
|
||||
"opposition",
|
||||
"key squares",
|
||||
"triangulation",
|
||||
"shouldering",
|
||||
"king activity",
|
||||
"promotion",
|
||||
"stalemate"
|
||||
]
|
||||
|
||||
@@ -276,6 +276,21 @@ defmodule Chesstrainer.AccountsTest do
|
||||
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
|
||||
test "validates the authenticated_at time" do
|
||||
now = DateTime.utc_now()
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
defmodule Chesstrainer.Endgames.MaterialThemesTest do
|
||||
use Chesstrainer.DataCase
|
||||
|
||||
import Ecto.Query
|
||||
|
||||
alias Chesstrainer.Endgames
|
||||
alias Chesstrainer.Endgames.MaterialThemes
|
||||
alias Chesstrainer.Repo
|
||||
alias Chesstrainer.Themes
|
||||
|
||||
@kr_v_k "8/8/3k4/8/8/3K1R2/8/8 w - - 0 1"
|
||||
@kp_v_k "8/8/3k4/8/8/3KP3/8/8 w - - 0 1"
|
||||
@kbn_v_k "8/8/3k4/8/8/3KBN2/8/8 w - - 0 1"
|
||||
@krp_v_k "8/8/3k4/8/8/3KR2P/8/8 w - - 0 1"
|
||||
@kp_v_kp "4k3/8/8/8/8/4p3/4P3/4K3 w - - 0 1"
|
||||
@kq_v_kp "8/8/3k4/8/8/3K1Q1p/8/8 w - - 0 1"
|
||||
@kq_v_kq "3q4/8/3k4/8/8/3K1Q2/8/8 w - - 0 1"
|
||||
@kn_v_kp "8/8/3k4/8/8/3KN2p/8/8 w - - 0 1"
|
||||
@kb_v_kb "8/8/3k1b2/8/8/3K1B2/8/8 w - - 0 1"
|
||||
@krp_v_kr "8/8/3k4/8/8/3KR2P/8/5r2 w - - 0 1"
|
||||
@kr_v_kr "8/8/3k4/8/8/3K1R2/8/5r2 b - - 0 1"
|
||||
@k_v_k "8/8/3k4/8/8/3K4/8/8 w - - 0 1"
|
||||
|
||||
describe "family/1" do
|
||||
test "classifies a lone king against heavy or pawn material" do
|
||||
assert MaterialThemes.family("KQ v K") == :basic_mate
|
||||
assert MaterialThemes.family("KR v K") == :basic_mate
|
||||
assert MaterialThemes.family("KP v K") == :king_and_pawn
|
||||
assert MaterialThemes.family("KPP v K") == :king_and_pawn
|
||||
assert MaterialThemes.family("KBN v K") == :bare_king_other
|
||||
assert MaterialThemes.family("KRP v K") == :bare_king_other
|
||||
end
|
||||
|
||||
test "classifies material presence into one family" do
|
||||
assert MaterialThemes.family("KP v KP") == :pawn_endgame
|
||||
assert MaterialThemes.family("KQ v KP") == :queen_and_pawn
|
||||
assert MaterialThemes.family("KQ v KQ") == :queen_endgame
|
||||
assert MaterialThemes.family("KRP v KR") == :rook_and_pawn
|
||||
assert MaterialThemes.family("KR v KR") == :rook_endgame
|
||||
assert MaterialThemes.family("KN v KP") == :minor_piece_and_pawn
|
||||
assert MaterialThemes.family("KB v KB") == :minor_piece_endgame
|
||||
end
|
||||
|
||||
test "flags content-free and malformed keys" do
|
||||
assert MaterialThemes.family("K v K") == :kings_only
|
||||
assert MaterialThemes.family(nil) == :unknown
|
||||
assert MaterialThemes.family("not a key") == :unknown
|
||||
end
|
||||
end
|
||||
|
||||
describe "derive/0" do
|
||||
test "creates every material family as a material theme" do
|
||||
MaterialThemes.derive()
|
||||
|
||||
themes = Themes.list_themes()
|
||||
|
||||
assert length(themes) == length(MaterialThemes.families())
|
||||
assert Enum.all?(themes, &(&1.kind == :material))
|
||||
assert Enum.all?(themes, &(&1.description not in [nil, ""]))
|
||||
end
|
||||
|
||||
test "tags every endgame with exactly one family" do
|
||||
pawn = create_endgame!(@kp_v_kp)
|
||||
rook = create_endgame!(@kr_v_kr)
|
||||
rook_and_pawn = create_endgame!(@krp_v_kr)
|
||||
queen_and_pawn = create_endgame!(@kq_v_kp)
|
||||
queen = create_endgame!(@kq_v_kq)
|
||||
minor_and_pawn = create_endgame!(@kn_v_kp)
|
||||
minor = create_endgame!(@kb_v_kb)
|
||||
mate = create_endgame!(@kr_v_k)
|
||||
promotion = create_endgame!(@kp_v_k)
|
||||
bare_minor = create_endgame!(@kbn_v_k)
|
||||
bare_other = create_endgame!(@krp_v_k)
|
||||
kings_only = create_endgame!(@k_v_k)
|
||||
|
||||
assert %{tagged: 11, skipped: 1} = MaterialThemes.derive()
|
||||
|
||||
assert ["pawn endgame"] = theme_names(pawn)
|
||||
assert ["rook endgame"] = theme_names(rook)
|
||||
assert ["rook and pawn"] = theme_names(rook_and_pawn)
|
||||
assert ["queen and pawn"] = theme_names(queen_and_pawn)
|
||||
assert ["queen endgame"] = theme_names(queen)
|
||||
assert ["minor piece and pawn"] = theme_names(minor_and_pawn)
|
||||
assert ["minor piece endgame"] = theme_names(minor)
|
||||
assert ["basic mate"] = theme_names(mate)
|
||||
assert ["king and pawn"] = theme_names(promotion)
|
||||
assert ["bare king other"] = theme_names(bare_minor)
|
||||
assert ["bare king other"] = theme_names(bare_other)
|
||||
assert [] = theme_names(kings_only)
|
||||
end
|
||||
|
||||
test "corrects an existing technique theme and claims its links as derived" do
|
||||
{:ok, existing} = Themes.create_theme(%{name: "rook endgame", category: :endgame})
|
||||
endgame = create_endgame!(@kr_v_kr, [existing])
|
||||
|
||||
MaterialThemes.derive()
|
||||
|
||||
theme = Themes.get_theme!(existing.id)
|
||||
assert theme.kind == :material
|
||||
assert theme.description =~ "Rooks"
|
||||
|
||||
assert [{theme_id, "derived"}] = link_rows(endgame.id)
|
||||
assert theme_id == existing.id
|
||||
end
|
||||
|
||||
test "removes a curated link to a material theme that contradicts the family" do
|
||||
{:ok, rook} = Themes.create_theme(%{name: "rook endgame", category: :endgame})
|
||||
mate = create_endgame!(@kr_v_k, [rook])
|
||||
|
||||
MaterialThemes.derive()
|
||||
|
||||
assert ["basic mate"] = theme_names(mate)
|
||||
end
|
||||
|
||||
test "is idempotent" do
|
||||
endgame = create_endgame!(@kq_v_kp)
|
||||
|
||||
MaterialThemes.derive()
|
||||
first = link_rows(endgame.id)
|
||||
MaterialThemes.derive()
|
||||
|
||||
assert link_rows(endgame.id) == first
|
||||
assert length(first) == 1
|
||||
end
|
||||
|
||||
test "leaves curated and community links to other themes alone" do
|
||||
{:ok, lucena} = Themes.create_theme(%{name: "Lucena", category: :endgame})
|
||||
endgame = create_endgame!(@kr_v_kr)
|
||||
insert_link(endgame.id, lucena.id, "community")
|
||||
|
||||
MaterialThemes.derive()
|
||||
|
||||
rows = link_rows(endgame.id)
|
||||
assert {lucena.id, "community"} in rows
|
||||
assert length(rows) == 2
|
||||
end
|
||||
end
|
||||
|
||||
defp create_endgame!(fen, themes \\ []) do
|
||||
{:ok, endgame} =
|
||||
Endgames.create_endgame(%{fen: fen, color: :white, result: :win, rating: 1500}, themes)
|
||||
|
||||
endgame
|
||||
end
|
||||
|
||||
defp theme_names(endgame) do
|
||||
endgame
|
||||
|> Map.fetch!(:id)
|
||||
|> link_rows()
|
||||
|> Enum.map(fn {theme_id, _source} -> Themes.get_theme!(theme_id).name end)
|
||||
|> Enum.sort()
|
||||
end
|
||||
|
||||
defp link_rows(endgame_id) do
|
||||
Repo.all(
|
||||
from l in "endgames_themes",
|
||||
where: l.endgame_id == type(^endgame_id, :binary_id),
|
||||
select: {l.theme_id, l.source},
|
||||
order_by: l.theme_id
|
||||
)
|
||||
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
|
||||
@@ -0,0 +1,170 @@
|
||||
defmodule Chesstrainer.Endgames.MotifThemesTest.Stub do
|
||||
@moduledoc false
|
||||
|
||||
def probe_local_detail(fen), do: Map.fetch!(Process.get(:motif_stub), fen)
|
||||
end
|
||||
|
||||
defmodule Chesstrainer.Endgames.MotifThemesTest do
|
||||
use Chesstrainer.DataCase
|
||||
|
||||
import Ecto.Query
|
||||
|
||||
alias Chesstrainer.Endgames
|
||||
alias Chesstrainer.Endgames.MotifThemes
|
||||
alias Chesstrainer.Repo
|
||||
alias Chesstrainer.Themes
|
||||
|
||||
setup do
|
||||
previous = Application.get_env(:chesstrainer, :motif_probe)
|
||||
Application.put_env(:chesstrainer, :motif_probe, __MODULE__.Stub)
|
||||
|
||||
on_exit(fn ->
|
||||
if previous,
|
||||
do: Application.put_env(:chesstrainer, :motif_probe, previous),
|
||||
else: Application.delete_env(:chesstrainer, :motif_probe)
|
||||
end)
|
||||
|
||||
:ok
|
||||
end
|
||||
|
||||
describe "motifs_for/4" do
|
||||
test "detects an only move for wins and draws" do
|
||||
assert [:only_move] = MotifThemes.motifs_for(:win, 5, [move(:win), move(:draw)], 0)
|
||||
|
||||
assert [:only_move] =
|
||||
MotifThemes.motifs_for(:draw, 5, [move(:draw), move(:loss), move(:loss)], 0)
|
||||
end
|
||||
|
||||
test "does not report an only move when several moves preserve the result" do
|
||||
assert [] = MotifThemes.motifs_for(:win, 5, [move(:win), move(:win)], 0)
|
||||
end
|
||||
|
||||
test "does not report an only move for a forced single move or a lost position" do
|
||||
assert [] = MotifThemes.motifs_for(:win, 5, [move(:win)], 0)
|
||||
assert [] = MotifThemes.motifs_for(:loss, 5, [move(:loss), move(:loss)], 0)
|
||||
end
|
||||
|
||||
test "requires an underpromotion while no queen promotion preserves the result" do
|
||||
assert [:underpromotion] =
|
||||
MotifThemes.motifs_for(:win, 5, [move(:win, 4), move(:win), move(:draw, 1)], 0)
|
||||
|
||||
assert [] = MotifThemes.motifs_for(:win, 5, [move(:win, 4), move(:win, 1)], 0)
|
||||
assert [] = MotifThemes.motifs_for(:win, 5, [move(:draw, 4), move(:win), move(:win)], 0)
|
||||
end
|
||||
|
||||
test "detects the 50-move rule from the raw WDL" do
|
||||
assert [:fifty_move_draw] =
|
||||
MotifThemes.motifs_for(:cursed_win, 120, [move(:cursed_win)], 0)
|
||||
|
||||
assert [:fifty_move_draw] =
|
||||
MotifThemes.motifs_for(:blessed_loss, 120, [move(:blessed_loss)], 0)
|
||||
end
|
||||
|
||||
test "detects the 50-move rule when the clock runs out before the next zeroing move" do
|
||||
assert [:fifty_move_draw] = MotifThemes.motifs_for(:win, 60, [move(:win)], 50)
|
||||
assert [] = MotifThemes.motifs_for(:win, 40, [move(:win)], 50)
|
||||
assert [] = MotifThemes.motifs_for(:win, 100, [move(:win)], 0)
|
||||
end
|
||||
|
||||
test "a position can carry several motifs" do
|
||||
assert [:underpromotion, :only_move] =
|
||||
MotifThemes.motifs_for(:win, 5, [move(:win, 4), move(:draw)], 0)
|
||||
end
|
||||
end
|
||||
|
||||
describe "derive/0" do
|
||||
@win_fen "8/8/3k4/8/8/3K1R2/8/8 w - - 0 1"
|
||||
@draw_fen "4k3/8/8/8/8/4p3/4P3/4K3 w - - 0 1"
|
||||
@loss_fen "8/8/3k4/8/8/3K4/8/6q1 w - - 0 1"
|
||||
|
||||
test "links the motifs reported for each endgame and skips losses" do
|
||||
win = create_endgame!(@win_fen, :win)
|
||||
draw = create_endgame!(@draw_fen, :draw)
|
||||
loss = create_endgame!(@loss_fen, :loss)
|
||||
|
||||
stub(%{
|
||||
win.fen => {:ok, %{wdl: :win, dtz: 5, moves: [move(:win), move(:draw)]}},
|
||||
draw.fen => {:ok, %{wdl: :cursed_win, dtz: 120, moves: [move(:cursed_win)]}}
|
||||
})
|
||||
|
||||
assert %{links: 2, skipped: 0, themes: 3} = MotifThemes.derive()
|
||||
|
||||
assert theme_names(win) == ["only move"]
|
||||
assert theme_names(draw) == ["50-move draw"]
|
||||
assert theme_names(loss) == []
|
||||
|
||||
assert Enum.all?(Themes.list_themes(), &(&1.kind == :motif))
|
||||
assert Enum.all?(Themes.list_themes(), &(&1.description not in [nil, ""]))
|
||||
end
|
||||
|
||||
test "reports endgames the local tables cannot answer" do
|
||||
endgame = create_endgame!(@win_fen, :win)
|
||||
stub(%{endgame.fen => {:error, :unsupported}})
|
||||
|
||||
assert %{links: 0, skipped: 1} = MotifThemes.derive()
|
||||
assert theme_names(endgame) == []
|
||||
end
|
||||
|
||||
test "is idempotent and leaves material, curated and community links alone" do
|
||||
win = create_endgame!(@win_fen, :win)
|
||||
stub(%{win.fen => {:ok, %{wdl: :win, dtz: 5, moves: [move(:win), move(:draw)]}}})
|
||||
|
||||
{:ok, lucena} = Themes.create_theme(%{name: "Lucena", category: :endgame})
|
||||
|
||||
{:ok, rook_endgame} =
|
||||
Themes.create_theme(%{name: "rook endgame", kind: :material, category: :endgame})
|
||||
|
||||
{:ok, _} = Themes.tag_endgames(lucena, [win.id], :curated)
|
||||
:ok = Themes.sync_derived_themes(win.id, [rook_endgame.id])
|
||||
|
||||
MotifThemes.derive()
|
||||
first = link_rows(win.id)
|
||||
MotifThemes.derive()
|
||||
|
||||
assert link_rows(win.id) == first
|
||||
assert {lucena.id, "curated"} in first
|
||||
assert {rook_endgame.id, "derived"} in first
|
||||
assert length(first) == 3
|
||||
end
|
||||
|
||||
test "corrects an existing technique theme into a motif theme" do
|
||||
{:ok, existing} = Themes.create_theme(%{name: "only move", category: :endgame})
|
||||
endgame = create_endgame!(@win_fen, :win)
|
||||
stub(%{endgame.fen => {:ok, %{wdl: :win, dtz: 5, moves: [move(:win), move(:draw)]}}})
|
||||
|
||||
MotifThemes.derive()
|
||||
|
||||
theme = Themes.get_theme!(existing.id)
|
||||
assert theme.kind == :motif
|
||||
assert theme.description =~ "Exactly one legal move"
|
||||
end
|
||||
end
|
||||
|
||||
defp stub(responses), do: Process.put(:motif_stub, responses)
|
||||
|
||||
defp move(wdl, promotes \\ 0, dtz \\ 0), do: {wdl, 0, 0, promotes, 0, dtz}
|
||||
|
||||
defp create_endgame!(fen, result) do
|
||||
{:ok, endgame} =
|
||||
Endgames.create_endgame(%{fen: fen, color: :white, result: result, rating: 1500})
|
||||
|
||||
endgame
|
||||
end
|
||||
|
||||
defp theme_names(endgame) do
|
||||
endgame
|
||||
|> Map.fetch!(:id)
|
||||
|> link_rows()
|
||||
|> Enum.map(fn {theme_id, _source} -> Themes.get_theme!(theme_id).name end)
|
||||
|> Enum.sort()
|
||||
end
|
||||
|
||||
defp link_rows(endgame_id) do
|
||||
Repo.all(
|
||||
from l in "endgames_themes",
|
||||
where: l.endgame_id == type(^endgame_id, :binary_id),
|
||||
select: {l.theme_id, l.source},
|
||||
order_by: l.theme_id
|
||||
)
|
||||
end
|
||||
end
|
||||
@@ -6,6 +6,11 @@ defmodule Chesstrainer.Endgames.Tablebase.Backend.FathomTest.Stub do
|
||||
def probe(_fen), do: {:ok, %Tablebase{category: :draw, checkmate: false, moves: []}}
|
||||
end
|
||||
|
||||
defmodule Chesstrainer.Endgames.Tablebase.Backend.FathomTest.ExplodingFallback do
|
||||
@moduledoc false
|
||||
def probe(_fen), do: raise("the remote tablebase must not be called")
|
||||
end
|
||||
|
||||
defmodule Chesstrainer.Endgames.Tablebase.Backend.FathomTest do
|
||||
# Not async: the local backend reads app config and Fathom keeps global state.
|
||||
use ExUnit.Case, async: false
|
||||
@@ -18,6 +23,7 @@ defmodule Chesstrainer.Endgames.Tablebase.Backend.FathomTest do
|
||||
|
||||
@krk "4k3/8/8/8/8/8/8/R3K3 w - - 0 1"
|
||||
@mate "7k/6Q1/5K2/8/8/8/8/8 b - - 0 1"
|
||||
@kpk "8/8/3k4/8/8/3KP3/8/8 w - - 0 1"
|
||||
|
||||
test "probes a KRvK position locally" do
|
||||
assert {:ok, %Tablebase{} = tablebase} = FathomBackend.probe(@krk)
|
||||
@@ -82,4 +88,37 @@ defmodule Chesstrainer.Endgames.Tablebase.Backend.FathomTest do
|
||||
assert {:ok, %Tablebase{category: :draw}} = FathomBackend.probe(@krk)
|
||||
end
|
||||
end
|
||||
|
||||
describe "probe_local_detail/1" do
|
||||
test "returns the raw root WDL, DTZ and every legal move" do
|
||||
assert {:ok, %{wdl: :win, dtz: dtz, moves: moves}} =
|
||||
FathomBackend.probe_local_detail(@krk)
|
||||
|
||||
assert is_integer(dtz)
|
||||
assert length(moves) == 15
|
||||
assert Enum.all?(moves, &(elem(&1, 0) in [:win, :cursed_win, :draw, :blessed_loss, :loss]))
|
||||
end
|
||||
|
||||
test "returns terminal for a finished position" do
|
||||
assert {:error, :terminal} = FathomBackend.probe_local_detail(@mate)
|
||||
end
|
||||
|
||||
test "returns unsupported when the local files cannot answer the position" do
|
||||
assert {:error, :unsupported} = FathomBackend.probe_local_detail(@kpk)
|
||||
end
|
||||
|
||||
test "never calls the remote backend" do
|
||||
previous = Application.get_env(:chesstrainer, :tablebase_fallback)
|
||||
|
||||
on_exit(fn ->
|
||||
if previous,
|
||||
do: Application.put_env(:chesstrainer, :tablebase_fallback, previous),
|
||||
else: Application.delete_env(:chesstrainer, :tablebase_fallback)
|
||||
end)
|
||||
|
||||
Application.put_env(:chesstrainer, :tablebase_fallback, __MODULE__.ExplodingFallback)
|
||||
|
||||
assert {:error, :unsupported} = FathomBackend.probe_local_detail(@kpk)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
defmodule Chesstrainer.EndgamesTest do
|
||||
use Chesstrainer.DataCase
|
||||
|
||||
import Chesstrainer.EndgamesFixtures
|
||||
|
||||
alias Chesstrainer.Endgames
|
||||
alias Chesstrainer.Endgames.Endgame
|
||||
alias Chesstrainer.Themes
|
||||
@@ -387,4 +389,30 @@ defmodule Chesstrainer.EndgamesTest do
|
||||
assert Endgames.curated_endgames() == []
|
||||
end
|
||||
end
|
||||
|
||||
describe "theme filters and pagination" do
|
||||
test "groups endgames by whether they carry a theme" do
|
||||
{:ok, theme} = Themes.create_theme(%{name: "Lucena", category: :endgame})
|
||||
tagged = create_endgame!(@kr)
|
||||
create_endgame!(@kq)
|
||||
{:ok, _} = Endgames.update_endgame(tagged, %{}, [theme])
|
||||
|
||||
assert Endgames.list_key_groups(%{with_theme: {theme.id, :curated}}) == [{"KR v K", 1}]
|
||||
assert Endgames.list_key_groups(%{without_theme: theme.id}) == [{"KQ v K", 1}]
|
||||
end
|
||||
|
||||
test "paginates the endgames in one key group" do
|
||||
endgames = for _ <- 1..3, do: endgame_fixture()
|
||||
|
||||
first = Endgames.list_endgames_for_key("K v K", %{}, limit: 2, offset: 0)
|
||||
second = Endgames.list_endgames_for_key("K v K", %{}, limit: 2, offset: 2)
|
||||
|
||||
assert length(first) == 2
|
||||
assert length(second) == 1
|
||||
|
||||
ids = Enum.map(first ++ second, & &1.id)
|
||||
assert Enum.sort(ids) == Enum.sort(Enum.map(endgames, & &1.id))
|
||||
assert length(Enum.uniq(ids)) == 3
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,13 +1,21 @@
|
||||
defmodule Chesstrainer.ThemesTest do
|
||||
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
|
||||
|
||||
describe "themes" do
|
||||
alias Chesstrainer.Themes.Theme
|
||||
|
||||
import Chesstrainer.ThemesFixtures
|
||||
|
||||
@invalid_attrs %{name: nil, category: nil}
|
||||
|
||||
test "list_themes/0 returns all themes" do
|
||||
@@ -76,4 +84,200 @@ defmodule Chesstrainer.ThemesTest do
|
||||
assert changeset.errors[:name]
|
||||
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
|
||||
|
||||
describe "tag_endgames/3 and untag_endgame/3" do
|
||||
test "adds curated links without duplicating them" do
|
||||
theme = theme_fixture()
|
||||
first = endgame_fixture()
|
||||
second = endgame_fixture()
|
||||
|
||||
assert {:ok, 2} = Themes.tag_endgames(theme, [first.id, second.id])
|
||||
assert {:ok, 2} = Themes.tag_endgames(theme, [first.id, second.id])
|
||||
|
||||
assert link_sources(first.id) == %{theme.id => "curated"}
|
||||
assert link_sources(second.id) == %{theme.id => "curated"}
|
||||
end
|
||||
|
||||
test "never overwrites a derived link" do
|
||||
theme = theme_fixture()
|
||||
endgame = endgame_fixture()
|
||||
|
||||
:ok = Themes.sync_derived_themes(endgame.id, [theme.id])
|
||||
|
||||
assert {:ok, 1} = Themes.tag_endgames(theme, [endgame.id])
|
||||
assert link_sources(endgame.id) == %{theme.id => "derived"}
|
||||
end
|
||||
|
||||
test "removes only the requested source" do
|
||||
theme = theme_fixture()
|
||||
curated = endgame_fixture()
|
||||
community = endgame_fixture()
|
||||
|
||||
{:ok, _} = Themes.tag_endgames(theme, [curated.id], :curated)
|
||||
{:ok, _} = Themes.tag_endgames(theme, [community.id], :community)
|
||||
|
||||
assert {:ok, 1} = Themes.untag_endgame(theme, curated.id, :curated)
|
||||
assert link_sources(curated.id) == %{}
|
||||
assert link_sources(community.id) == %{theme.id => "community"}
|
||||
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
|
||||
|
||||
@@ -17,7 +17,30 @@ defmodule ChesstrainerWeb.Admin.ThemeLive.FormTest do
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
|
||||
test "lists themes with their usage count", %{conn: conn} do
|
||||
used_theme = theme_fixture(%{name: "Lucena"})
|
||||
test "lists themes with their kind and coverage", %{conn: conn} do
|
||||
used_theme = theme_fixture(%{name: "Lucena", kind: :technique})
|
||||
unused_theme = theme_fixture(%{name: "Philidor"})
|
||||
endgame = endgame_fixture()
|
||||
{: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")
|
||||
|
||||
assert has_element?(view, "#theme-#{used_theme.id}")
|
||||
assert has_element?(view, "#theme-usage-#{used_theme.id}", "1 endgame")
|
||||
assert has_element?(view, "#theme-usage-#{unused_theme.id}", "0 endgames")
|
||||
assert has_element?(view, "#theme-#{used_theme.id}", "technique")
|
||||
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
|
||||
|
||||
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")
|
||||
|
||||
assert html =~ "Used by 1 endgame"
|
||||
assert html =~ "Used by 1 of 1 endgame"
|
||||
assert html =~ "The endgames will be kept"
|
||||
|
||||
view |> element("#theme-#{theme.id} a", "Delete") |> render_click()
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
defmodule ChesstrainerWeb.Admin.ThemeLive.TagTest do
|
||||
use ChesstrainerWeb.ConnCase
|
||||
|
||||
import Ecto.Query
|
||||
import Phoenix.LiveViewTest
|
||||
|
||||
import Chesstrainer.AccountsFixtures
|
||||
import Chesstrainer.ThemesFixtures
|
||||
|
||||
alias Chesstrainer.Endgames
|
||||
alias Chesstrainer.Repo
|
||||
alias Chesstrainer.Themes
|
||||
|
||||
setup :register_and_log_in_admin
|
||||
|
||||
@kp_v_kp_1 "4k3/8/8/8/8/4p3/4P3/4K3 w - - 0 1"
|
||||
@kp_v_kp_2 "3k4/8/8/8/8/4p3/4P3/4K3 w - - 0 1"
|
||||
@kr_v_kr "8/8/3k4/8/8/3K1R2/8/5r2 b - - 0 1"
|
||||
|
||||
test "lists candidate groups with counts and previews boards", %{conn: conn} do
|
||||
theme = technique_theme()
|
||||
kp_1 = create_endgame!(@kp_v_kp_1)
|
||||
kp_2 = create_endgame!(@kp_v_kp_2)
|
||||
kr = create_endgame!(@kr_v_kr)
|
||||
|
||||
{:ok, view, _html} = live(conn, ~p"/admin/themes/#{theme.id}/tag")
|
||||
|
||||
assert has_element?(view, "#candidate-count", "3")
|
||||
assert has_element?(view, "#candidates-KP-v-KP", "2")
|
||||
|
||||
view |> element("#toggle-candidates-KP-v-KP") |> render_click()
|
||||
|
||||
assert has_element?(view, "#endgame-#{kp_1.id}")
|
||||
assert has_element?(view, "#endgame-#{kp_2.id}")
|
||||
refute has_element?(view, "#endgame-#{kr.id}")
|
||||
assert render(view) =~ "Chess position"
|
||||
end
|
||||
|
||||
test "applies the theme in bulk and updates coverage", %{conn: conn} do
|
||||
theme = technique_theme()
|
||||
kp_1 = create_endgame!(@kp_v_kp_1)
|
||||
kp_2 = create_endgame!(@kp_v_kp_2)
|
||||
_kr = create_endgame!(@kr_v_kr)
|
||||
|
||||
{:ok, view, _html} = live(conn, ~p"/admin/themes/#{theme.id}/tag")
|
||||
|
||||
view |> element("#toggle-candidates-KP-v-KP") |> render_click()
|
||||
view |> element("#select-#{kp_1.id}") |> render_click()
|
||||
view |> element("#select-#{kp_2.id}") |> render_click()
|
||||
view |> element("#apply-theme") |> render_click()
|
||||
|
||||
assert render(view) =~ "Tagged 2 endgame(s)"
|
||||
assert has_element?(view, "#tagged-count", "2")
|
||||
assert has_element?(view, "#candidate-count", "1")
|
||||
|
||||
assert Enum.sort(curated_endgame_ids(theme)) == Enum.sort([kp_1.id, kp_2.id])
|
||||
|
||||
{:ok, _index, html} = live(conn, ~p"/admin/themes")
|
||||
assert html =~ "2 of 3 endgames"
|
||||
end
|
||||
|
||||
test "removes a curated link but leaves a community link alone", %{conn: conn} do
|
||||
theme = technique_theme()
|
||||
curated = create_endgame!(@kp_v_kp_1)
|
||||
community = create_endgame!(@kr_v_kr)
|
||||
|
||||
{:ok, _} = Themes.tag_endgames(theme, [curated.id], :curated)
|
||||
{:ok, _} = Themes.tag_endgames(theme, [community.id], :community)
|
||||
|
||||
{:ok, view, _html} = live(conn, ~p"/admin/themes/#{theme.id}/tag")
|
||||
|
||||
view |> element("#toggle-tagged-KP-v-KP") |> render_click()
|
||||
view |> element("#remove-#{curated.id}") |> render_click()
|
||||
|
||||
assert render(view) =~ "Removed"
|
||||
assert curated_endgame_ids(theme) == []
|
||||
|
||||
assert {Ecto.UUID.dump!(community.id), "community"} in link_rows(theme.id)
|
||||
end
|
||||
|
||||
test "refuses a material theme", %{conn: conn} do
|
||||
{:ok, theme} =
|
||||
Themes.create_theme(%{name: "Rook endgame", kind: :material, category: :endgame})
|
||||
|
||||
assert {:error, {:live_redirect, %{to: "/admin/themes"}}} =
|
||||
live(conn, ~p"/admin/themes/#{theme.id}/tag")
|
||||
end
|
||||
|
||||
test "switching the theme navigates to its workspace", %{conn: conn} do
|
||||
first = technique_theme(%{name: "Lucena"})
|
||||
second = technique_theme(%{name: "Philidor"})
|
||||
|
||||
{:ok, view, _html} = live(conn, ~p"/admin/themes/#{first.id}/tag")
|
||||
|
||||
assert {:error, {:live_redirect, %{to: path}}} =
|
||||
view
|
||||
|> form("#theme-workspace-form", %{theme_id: to_string(second.id)})
|
||||
|> render_change()
|
||||
|
||||
assert path == "/admin/themes/#{second.id}/tag"
|
||||
end
|
||||
|
||||
test "members cannot open the workspace", %{conn: conn} do
|
||||
theme = technique_theme()
|
||||
conn = log_in_user(conn, user_fixture())
|
||||
|
||||
assert redirected_to(get(conn, ~p"/admin/themes/#{theme.id}/tag")) == ~p"/"
|
||||
end
|
||||
|
||||
defp technique_theme(attrs \\ %{}) do
|
||||
attrs =
|
||||
Map.merge(
|
||||
%{name: unique_theme_name(), kind: :technique, category: :endgame},
|
||||
attrs
|
||||
)
|
||||
|
||||
{:ok, theme} = Themes.create_theme(attrs)
|
||||
theme
|
||||
end
|
||||
|
||||
defp create_endgame!(fen) do
|
||||
{:ok, endgame} =
|
||||
Endgames.create_endgame(%{fen: fen, color: :white, result: :win, rating: 1500})
|
||||
|
||||
endgame
|
||||
end
|
||||
|
||||
defp curated_endgame_ids(theme) do
|
||||
Repo.all(
|
||||
from l in "endgames_themes",
|
||||
where: l.theme_id == ^theme.id and l.source == "curated",
|
||||
select: l.endgame_id
|
||||
)
|
||||
|> Enum.map(&Ecto.UUID.load!/1)
|
||||
end
|
||||
|
||||
defp link_rows(theme_id) do
|
||||
Repo.all(
|
||||
from l in "endgames_themes",
|
||||
where: l.theme_id == ^theme_id,
|
||||
select: {l.endgame_id, l.source}
|
||||
)
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user