mirror of
https://github.com/TheRealOwenRees/chess-endgame-trainer.git
synced 2026-11-18 11:42:07 +00:00
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:
@@ -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.
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@ defmodule Chesstrainer.Themes do
|
||||
"""
|
||||
|
||||
import Ecto.Query, warn: false
|
||||
alias Chesstrainer.Accounts.Policy
|
||||
alias Chesstrainer.Accounts.Scope
|
||||
alias Chesstrainer.Repo
|
||||
|
||||
alias Chesstrainer.Themes.Theme
|
||||
@@ -74,9 +76,26 @@ defmodule Chesstrainer.Themes do
|
||||
"""
|
||||
def get_theme!(id), do: Repo.get!(Theme, id)
|
||||
|
||||
@doc """
|
||||
Gets a single endgame theme by its slug.
|
||||
|
||||
Returns `nil` when no endgame theme has that slug.
|
||||
"""
|
||||
def get_theme_by_slug(slug) when is_binary(slug) do
|
||||
Repo.one(
|
||||
from t in Theme,
|
||||
where: t.slug == ^slug and t.category == :endgame,
|
||||
limit: 1
|
||||
)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Creates a theme.
|
||||
|
||||
This is the unscoped path used by internal callers such as seeds, fixtures and
|
||||
the admin picker, which are already behind an authorization check. Prefer
|
||||
`create_theme/2` wherever a scope is available.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> create_theme(%{field: value})
|
||||
@@ -92,6 +111,21 @@ defmodule Chesstrainer.Themes do
|
||||
|> Repo.insert()
|
||||
end
|
||||
|
||||
@doc """
|
||||
Creates a theme on behalf of an administrator.
|
||||
|
||||
Members cannot introduce new theme names; their contribution path is a
|
||||
suggestion, which a moderator reviews. Returns `{:error, :unauthorized}`
|
||||
for a scope that cannot manage themes.
|
||||
"""
|
||||
def create_theme(%Scope{} = scope, attrs) do
|
||||
if Policy.can?(scope, :manage_themes) do
|
||||
create_theme(attrs)
|
||||
else
|
||||
{:error, :unauthorized}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Updates a theme.
|
||||
|
||||
@@ -160,20 +194,70 @@ defmodule Chesstrainer.Themes do
|
||||
@doc """
|
||||
Finds a theme by name (trimmed and case-insensitive) for a category, creating it
|
||||
if it does not exist.
|
||||
|
||||
Options:
|
||||
|
||||
* `:kind` - the kind for a newly created theme; defaults to `:technique`
|
||||
|
||||
This is the picker's helper and is expected to run behind an admin check.
|
||||
"""
|
||||
def get_or_create(name, category) when is_binary(name) do
|
||||
def get_or_create(name, category, opts \\ []) when is_binary(name) do
|
||||
name = String.trim(name)
|
||||
|
||||
if name == "" do
|
||||
{:error, :blank_name}
|
||||
else
|
||||
case find_by_name(name, category) do
|
||||
nil -> create_theme(%{name: name, category: category})
|
||||
theme -> {:ok, theme}
|
||||
nil ->
|
||||
create_theme(%{
|
||||
name: name,
|
||||
category: category,
|
||||
kind: Keyword.get(opts, :kind, :technique)
|
||||
})
|
||||
|
||||
theme ->
|
||||
{:ok, theme}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Replaces the derived theme links for one endgame.
|
||||
|
||||
Only links whose source is `derived` are removed, so curated and
|
||||
community-approved links survive every derivation pass. Links that are
|
||||
already present are left alone, which makes the operation idempotent.
|
||||
"""
|
||||
@spec sync_derived_themes(Ecto.UUID.t(), [term()]) :: :ok
|
||||
def sync_derived_themes(endgame_id, theme_ids) do
|
||||
now = DateTime.utc_now() |> DateTime.truncate(:second)
|
||||
|
||||
Repo.transaction(fn ->
|
||||
Repo.delete_all(
|
||||
from l in "endgames_themes",
|
||||
where: l.endgame_id == type(^endgame_id, :binary_id) and l.source == "derived"
|
||||
)
|
||||
|
||||
rows =
|
||||
theme_ids
|
||||
|> Enum.uniq()
|
||||
|> Enum.map(fn theme_id ->
|
||||
%{
|
||||
endgame_id: Ecto.UUID.dump!(endgame_id),
|
||||
theme_id: theme_id,
|
||||
source: "derived",
|
||||
inserted_at: now
|
||||
}
|
||||
end)
|
||||
|
||||
if rows != [] do
|
||||
Repo.insert_all("endgames_themes", rows, on_conflict: :nothing)
|
||||
end
|
||||
end)
|
||||
|
||||
:ok
|
||||
end
|
||||
|
||||
defp find_by_name(name, category) do
|
||||
downcased = String.downcase(name)
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user