mirror of
https://github.com/TheRealOwenRees/chess-endgame-trainer.git
synced 2026-11-18 11:42:07 +00:00
Compare commits
14
Commits
bd8be4d10d
...
eaf72a7686
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eaf72a7686
|
||
|
|
924a3e08dc
|
||
|
|
b54fb0a6d7
|
||
|
|
46bc27f614
|
||
|
|
f2d886d602
|
||
|
|
64a9210580
|
||
|
|
5c8d2494b6
|
||
|
|
1003ec203a
|
||
|
|
f9340fb57b
|
||
|
|
c71f465487 | ||
|
|
f5efcde5ca
|
||
|
|
bf176ebd42
|
||
|
|
785e403370
|
||
|
|
b17f346b25 |
@@ -64,6 +64,12 @@ _Avoid_: Permission, access level
|
|||||||
A user's subscription tier — `free` or `premium` — independent of their role.
|
A user's subscription tier — `free` or `premium` — independent of their role.
|
||||||
_Avoid_: Tier, subscription, membership
|
_Avoid_: Tier, subscription, membership
|
||||||
|
|
||||||
|
**Mailing list**:
|
||||||
|
Email addresses that opted in to occasional product updates, collected from the
|
||||||
|
landing-page form or the registration checkbox; a subscriber need not have an
|
||||||
|
account.
|
||||||
|
_Avoid_: Newsletter, subscription (reserved for the premium plan)
|
||||||
|
|
||||||
## Play
|
## Play
|
||||||
|
|
||||||
**Winning side**:
|
**Winning side**:
|
||||||
|
|||||||
@@ -20,9 +20,11 @@
|
|||||||
@import "./components/_icon.css";
|
@import "./components/_icon.css";
|
||||||
@import "./components/_button.css";
|
@import "./components/_button.css";
|
||||||
@import "./components/_learning-strip.css";
|
@import "./components/_learning-strip.css";
|
||||||
|
@import "./components/_mailing-list.css";
|
||||||
@import "./components/_board.css";
|
@import "./components/_board.css";
|
||||||
@import "./components/_promotion.css";
|
@import "./components/_promotion.css";
|
||||||
@import "./pages/_legal.css";
|
@import "./pages/_legal.css";
|
||||||
|
@import "./pages/_error.css";
|
||||||
|
|
||||||
@source "../css";
|
@source "../css";
|
||||||
@source "../js";
|
@source "../js";
|
||||||
|
|||||||
@@ -34,6 +34,16 @@ h1, h2 { font-family: 'DM Serif Display', serif; font-weight: 400; letter-spacin
|
|||||||
h1 { max-width: 590px; font-size: clamp(56px, 6vw, 87px); line-height: .93; }
|
h1 { max-width: 590px; font-size: clamp(56px, 6vw, 87px); line-height: .93; }
|
||||||
h1 em { color: var(--color-coral); font-weight: 400; }
|
h1 em { color: var(--color-coral); font-weight: 400; }
|
||||||
|
|
||||||
|
.settings-header {
|
||||||
|
font-size: 3rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-subtitle {
|
||||||
|
font-size: 1rem;;
|
||||||
|
color: var(--color-base-content);
|
||||||
|
opacity: 0.7;
|
||||||
|
}
|
||||||
|
|
||||||
@media (max-width: 650px) {
|
@media (max-width: 650px) {
|
||||||
h1 { font-size: clamp(51px, 15vw, 68px); }
|
h1 { font-size: clamp(51px, 15vw, 68px); }
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
.mailing-list {
|
||||||
|
width: min(1180px, calc(100% - 48px));
|
||||||
|
margin: 0 auto 110px;
|
||||||
|
padding: 56px 60px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 48px;
|
||||||
|
border-radius: 16px;
|
||||||
|
background: var(--color-deep);
|
||||||
|
color: var(--color-on-deep);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mailing-list-copy { max-width: 480px; }
|
||||||
|
.mailing-list-copy .section-kicker { color: var(--color-on-deep-muted); }
|
||||||
|
.mailing-list-copy h2 { font-size: clamp(32px, 3.4vw, 46px); line-height: 1; }
|
||||||
|
.mailing-list-copy p { margin-top: 16px; color: var(--color-on-deep-muted); font-size: 14px; line-height: 1.65; }
|
||||||
|
|
||||||
|
.mailing-list-form { width: min(420px, 100%); flex-shrink: 0; }
|
||||||
|
.mailing-list-form label { display: block; margin-bottom: 8px; color: var(--color-on-deep-faint); font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: .11em; }
|
||||||
|
.mailing-list-row { display: flex; gap: 10px; }
|
||||||
|
.mailing-list-row input { flex: 1; min-width: 0; padding: 15px 17px; border: 1px solid rgba(255, 255, 255, .22); border-radius: 8px; background: rgba(255, 255, 255, .1); color: var(--color-on-deep); font-size: 14px; }
|
||||||
|
.mailing-list-row input::placeholder { color: var(--color-on-deep-faint); }
|
||||||
|
.mailing-list-row input:focus { border-color: transparent; outline: 2px solid var(--color-coral); outline-offset: 2px; }
|
||||||
|
.mailing-list-row .primary-button { white-space: nowrap; }
|
||||||
|
|
||||||
|
@media (max-width: 900px) {
|
||||||
|
.mailing-list { flex-direction: column; align-items: flex-start; gap: 30px; }
|
||||||
|
.mailing-list-form { width: 100%; }
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 650px) {
|
||||||
|
.mailing-list { width: calc(100% - 36px); margin-bottom: 80px; padding: 40px 24px; }
|
||||||
|
.mailing-list-row { flex-direction: column; }
|
||||||
|
.mailing-list-row .primary-button { justify-content: center; }
|
||||||
|
}
|
||||||
@@ -14,7 +14,12 @@
|
|||||||
.nav-links a { transition: opacity .2s; }
|
.nav-links a { transition: opacity .2s; }
|
||||||
.nav-links a:hover { opacity: .55; }
|
.nav-links a:hover { opacity: .55; }
|
||||||
.nav-links a.nav-cta:hover { opacity: 1; }
|
.nav-links a.nav-cta:hover { opacity: 1; }
|
||||||
.nav-user { color: var(--color-muted); font-weight: 500; }
|
.nav-user-menu { position: relative; }
|
||||||
|
.nav-user-menu summary { display: flex; align-items: center; gap: 6px; list-style: none; cursor: pointer; color: var(--color-muted); font-weight: 500; }
|
||||||
|
.nav-user-menu summary::-webkit-details-marker { display: none; }
|
||||||
|
.nav-user-menu summary::after { content: "▾"; font-size: 10px; }
|
||||||
|
.nav-user-menu-panel { position: absolute; right: 0; top: calc(100% + 14px); z-index: 20; display: grid; gap: 12px; min-width: 170px; padding: 16px; border-radius: 10px; background: var(--color-canvas-raised); box-shadow: 0 18px 40px rgba(23,53,45,.15); }
|
||||||
|
html[data-theme="dark"] .nav-user-menu-panel { box-shadow: 0 18px 40px rgba(0, 0, 0, .45); }
|
||||||
.nav-cta, .primary-button, .light-button {
|
.nav-cta, .primary-button, .light-button {
|
||||||
display: inline-flex; align-items: center; justify-content: center; gap: 13px;
|
display: inline-flex; align-items: center; justify-content: center; gap: 13px;
|
||||||
border-radius: 999px; font-weight: 600; transition: transform .2s, background .2s;
|
border-radius: 999px; font-weight: 600; transition: transform .2s, background .2s;
|
||||||
@@ -37,5 +42,6 @@
|
|||||||
.nav-links.open { display: flex; }
|
.nav-links.open { display: flex; }
|
||||||
.nav-cta { width: 100%; }
|
.nav-cta { width: 100%; }
|
||||||
.nav-links { display: none; position: absolute; top: 65px; left: 0; right: 0; padding: 24px; flex-direction: column; align-items: stretch; gap: 22px; border-radius: 10px; background: var(--color-canvas-raised); box-shadow: 0 18px 40px rgba(23,53,45,.15); }
|
.nav-links { display: none; position: absolute; top: 65px; left: 0; right: 0; padding: 24px; flex-direction: column; align-items: stretch; gap: 22px; border-radius: 10px; background: var(--color-canvas-raised); box-shadow: 0 18px 40px rgba(23,53,45,.15); }
|
||||||
|
.nav-user-menu-panel { position: static; min-width: 0; padding: 12px 0 0; background: transparent; box-shadow: none; }
|
||||||
html[data-theme="dark"] .nav-links { box-shadow: 0 18px 40px rgba(0, 0, 0, .45); }
|
html[data-theme="dark"] .nav-links { box-shadow: 0 18px 40px rgba(0, 0, 0, .45); }
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
.error-page {
|
||||||
|
width: min(760px, calc(100% - 48px));
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 100px 0 130px;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-code {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
min-width: 68px;
|
||||||
|
padding: 7px 16px;
|
||||||
|
border: 1px solid var(--color-hairline);
|
||||||
|
border-radius: 999px;
|
||||||
|
color: var(--color-coral-text);
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 700;
|
||||||
|
letter-spacing: .16em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-page h1 {
|
||||||
|
max-width: 640px;
|
||||||
|
margin: 28px auto 0;
|
||||||
|
font-size: clamp(40px, 5.5vw, 60px);
|
||||||
|
line-height: 1.02;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-page p {
|
||||||
|
max-width: 48ch;
|
||||||
|
margin: 18px auto 0;
|
||||||
|
color: var(--color-muted);
|
||||||
|
font-size: 16px;
|
||||||
|
line-height: 1.7;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-page .error-hint {
|
||||||
|
margin-top: 10px;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-actions {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
margin-top: 34px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 650px) {
|
||||||
|
.error-page {
|
||||||
|
width: calc(100% - 36px);
|
||||||
|
padding: 64px 0 90px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-page h1 {
|
||||||
|
font-size: clamp(34px, 10vw, 44px);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,11 @@
|
|||||||
const WRAP = ".nav-wrap";
|
const WRAP = ".nav-wrap";
|
||||||
const TOGGLE = ".menu-button";
|
const TOGGLE = ".menu-button";
|
||||||
const LINKS = ".nav-links";
|
const LINKS = ".nav-links";
|
||||||
|
const USER_MENU = ".nav-user-menu";
|
||||||
|
|
||||||
|
const closeUserMenus = () => {
|
||||||
|
document.querySelectorAll(`${USER_MENU}[open]`).forEach((menu) => menu.removeAttribute("open"));
|
||||||
|
};
|
||||||
|
|
||||||
const setOpen = (open) => {
|
const setOpen = (open) => {
|
||||||
const wrap = document.querySelector(WRAP);
|
const wrap = document.querySelector(WRAP);
|
||||||
@@ -26,6 +31,16 @@ document.addEventListener("click", (event) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (target.closest(`${USER_MENU} a`)) {
|
||||||
|
closeUserMenus();
|
||||||
|
setOpen(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!target.closest(USER_MENU)) {
|
||||||
|
closeUserMenus();
|
||||||
|
}
|
||||||
|
|
||||||
if (target.closest(`${LINKS} a`)) {
|
if (target.closest(`${LINKS} a`)) {
|
||||||
setOpen(false);
|
setOpen(false);
|
||||||
return;
|
return;
|
||||||
@@ -39,6 +54,7 @@ document.addEventListener("click", (event) => {
|
|||||||
document.addEventListener("keydown", (event) => {
|
document.addEventListener("keydown", (event) => {
|
||||||
if (event.key === "Escape") {
|
if (event.key === "Escape") {
|
||||||
setOpen(false);
|
setOpen(false);
|
||||||
|
closeUserMenus();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Eight-or-more-piece endgames are trained from engine-sourced corridors that hand off to the tablebase at seven
|
# Eight-or-more-piece endgames are trained from engine-sourced corridors that hand off to the tablebase at seven
|
||||||
|
|
||||||
_Status: proposed. Extends ADR-0005: the ≤7-piece source split stands; this adds a source for 8+._
|
_Status: accepted. Extends ADR-0005: the ≤7-piece source split stands; this adds a source for 8+._
|
||||||
|
|
||||||
Syzygy stops at seven pieces and there is no tablebase for eight or more. To
|
Syzygy stops at seven pieces and there is no tablebase for eight or more. To
|
||||||
train such endgames without pretending to a completeness they lack, each 8+
|
train such endgames without pretending to a completeness they lack, each 8+
|
||||||
|
|||||||
@@ -332,6 +332,22 @@ defmodule Chesstrainer.Accounts do
|
|||||||
Repo.one(query)
|
Repo.one(query)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
Returns the number of users with at least one valid session token.
|
||||||
|
|
||||||
|
Session tokens stay valid for `UserToken.session_validity_in_days/0` days, so
|
||||||
|
this counts users who logged in during that window, not necessarily users who
|
||||||
|
are connected right now. A user with multiple sessions counts once.
|
||||||
|
"""
|
||||||
|
def count_logged_in_users do
|
||||||
|
days = UserToken.session_validity_in_days()
|
||||||
|
|
||||||
|
UserToken
|
||||||
|
|> where([t], t.context == "session" and t.inserted_at > ago(^days, "day"))
|
||||||
|
|> select([t], count(t.user_id, :distinct))
|
||||||
|
|> Repo.one()
|
||||||
|
end
|
||||||
|
|
||||||
@doc ~S"""
|
@doc ~S"""
|
||||||
Delivers the update email instructions to the given user.
|
Delivers the update email instructions to the given user.
|
||||||
|
|
||||||
|
|||||||
@@ -30,4 +30,13 @@ defmodule Chesstrainer.Accounts.Scope do
|
|||||||
end
|
end
|
||||||
|
|
||||||
def for_user(nil), do: nil
|
def for_user(nil), do: nil
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
True when the scope belongs to a premium user.
|
||||||
|
|
||||||
|
`for_user/1` returns `nil` for anonymous visitors, so the catch-all covers
|
||||||
|
both nil scopes and free plans.
|
||||||
|
"""
|
||||||
|
def premium?(%__MODULE__{user: %User{plan: :premium}}), do: true
|
||||||
|
def premium?(_scope), do: false
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ defmodule Chesstrainer.Accounts.User do
|
|||||||
field :rating_deviation, :float, default: 350.0
|
field :rating_deviation, :float, default: 350.0
|
||||||
field :confirmed_at, :utc_datetime
|
field :confirmed_at, :utc_datetime
|
||||||
field :authenticated_at, :utc_datetime, virtual: true
|
field :authenticated_at, :utc_datetime, virtual: true
|
||||||
|
field :mailing_list, :boolean, virtual: true, default: false
|
||||||
|
|
||||||
timestamps(type: :utc_datetime)
|
timestamps(type: :utc_datetime)
|
||||||
end
|
end
|
||||||
@@ -34,7 +35,7 @@ defmodule Chesstrainer.Accounts.User do
|
|||||||
"""
|
"""
|
||||||
def registration_changeset(user, attrs, opts \\ []) do
|
def registration_changeset(user, attrs, opts \\ []) do
|
||||||
user
|
user
|
||||||
|> cast(attrs, [:email, :username, :password])
|
|> cast(attrs, [:email, :username, :password, :mailing_list])
|
||||||
|> validate_email(opts)
|
|> validate_email(opts)
|
||||||
|> validate_username(opts)
|
|> validate_username(opts)
|
||||||
|> validate_confirmation(:password, message: "does not match password")
|
|> validate_confirmation(:password, message: "does not match password")
|
||||||
|
|||||||
@@ -48,6 +48,9 @@ defmodule Chesstrainer.Accounts.UserToken do
|
|||||||
{token, %UserToken{token: token, context: "session", user_id: user.id, authenticated_at: dt}}
|
{token, %UserToken{token: token, context: "session", user_id: user.id, authenticated_at: dt}}
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@doc "How long a session token stays valid, in days."
|
||||||
|
def session_validity_in_days, do: @session_validity_in_days
|
||||||
|
|
||||||
@doc """
|
@doc """
|
||||||
Checks if the token is valid and returns its underlying lookup query.
|
Checks if the token is valid and returns its underlying lookup query.
|
||||||
|
|
||||||
|
|||||||
@@ -70,6 +70,39 @@ defmodule Chesstrainer.Attempts do
|
|||||||
|> Repo.one()
|
|> Repo.one()
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
Aggregated attempt totals for `user_id`.
|
||||||
|
|
||||||
|
Returns a map with `:attempts`, `:solved`, `:failed` and `:endgames` (the
|
||||||
|
number of distinct puzzles tried).
|
||||||
|
"""
|
||||||
|
def stats_for_user(user_id) do
|
||||||
|
Attempt
|
||||||
|
|> where([a], a.user_id == ^user_id)
|
||||||
|
|> select([a], %{
|
||||||
|
attempts: count(a.id),
|
||||||
|
solved: filter(count(a.id), a.outcome == :solved),
|
||||||
|
failed: filter(count(a.id), a.outcome == :failed),
|
||||||
|
endgames: count(a.endgame_id, :distinct)
|
||||||
|
})
|
||||||
|
|> Repo.one()
|
||||||
|
end
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
The attempts of `user_id`, newest first, with each endgame preloaded.
|
||||||
|
|
||||||
|
Pass `limit: n` to cap the history (the profile page shows a recent window;
|
||||||
|
exports pass no limit).
|
||||||
|
"""
|
||||||
|
def list_attempts_for_user(user_id, opts \\ []) do
|
||||||
|
Attempt
|
||||||
|
|> where([a], a.user_id == ^user_id)
|
||||||
|
|> order_by([a], desc: a.inserted_at)
|
||||||
|
|> maybe_limit(Keyword.get(opts, :limit))
|
||||||
|
|> preload(:endgame)
|
||||||
|
|> Repo.all()
|
||||||
|
end
|
||||||
|
|
||||||
@doc """
|
@doc """
|
||||||
The distinct endgame ids `user_id` has attempted in the last `days` days.
|
The distinct endgame ids `user_id` has attempted in the last `days` days.
|
||||||
|
|
||||||
@@ -87,4 +120,7 @@ defmodule Chesstrainer.Attempts do
|
|||||||
end
|
end
|
||||||
|
|
||||||
defp rated(query), do: where(query, [a], not is_nil(a.rated_at))
|
defp rated(query), do: where(query, [a], not is_nil(a.rated_at))
|
||||||
|
|
||||||
|
defp maybe_limit(query, nil), do: query
|
||||||
|
defp maybe_limit(query, limit) when is_integer(limit), do: limit(query, ^limit)
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -0,0 +1,142 @@
|
|||||||
|
defmodule Chesstrainer.MailingList do
|
||||||
|
@moduledoc """
|
||||||
|
The marketing mailing list.
|
||||||
|
|
||||||
|
Addresses arrive from the signup form on the landing page and from the
|
||||||
|
opt-in checkbox on registration. A subscriber is only active once their
|
||||||
|
address is confirmed: the landing-page form sends a confirmation email, while
|
||||||
|
the registration checkbox relies on the account-confirmation email and is
|
||||||
|
confirmed when the user's account is. A subscriber created from the landing
|
||||||
|
page has no user; one created from registration is linked to the user so
|
||||||
|
deleting the account also removes their address.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import Ecto.Query, warn: false
|
||||||
|
|
||||||
|
alias Chesstrainer.Accounts.User
|
||||||
|
alias Chesstrainer.MailingList.Subscriber
|
||||||
|
alias Chesstrainer.Repo
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
Requests a subscription from the landing-page form.
|
||||||
|
|
||||||
|
Returns `{:ok, :confirmation_required}` for a new or still-unconfirmed
|
||||||
|
address, so the caller can send a confirmation email, and
|
||||||
|
`{:ok, :already_subscribed}` for an address that has already confirmed.
|
||||||
|
|
||||||
|
iex> subscribe("player@example.com")
|
||||||
|
{:ok, :confirmation_required}
|
||||||
|
|
||||||
|
iex> confirm("player@example.com")
|
||||||
|
{:ok, %Subscriber{}}
|
||||||
|
|
||||||
|
iex> subscribe("player@example.com")
|
||||||
|
{:ok, :already_subscribed}
|
||||||
|
"""
|
||||||
|
def subscribe(email, opts \\ []) when is_binary(email) do
|
||||||
|
changeset =
|
||||||
|
%Subscriber{source: Keyword.get(opts, :source, :home)}
|
||||||
|
|> Subscriber.changeset(%{email: email})
|
||||||
|
|
||||||
|
if changeset.valid? do
|
||||||
|
email = Ecto.Changeset.get_field(changeset, :email)
|
||||||
|
|
||||||
|
case Repo.get_by(Subscriber, email: email) do
|
||||||
|
%Subscriber{confirmed_at: confirmed_at} when not is_nil(confirmed_at) ->
|
||||||
|
{:ok, :already_subscribed}
|
||||||
|
|
||||||
|
%Subscriber{} ->
|
||||||
|
{:ok, :confirmation_required}
|
||||||
|
|
||||||
|
nil ->
|
||||||
|
insert_subscription(changeset, email)
|
||||||
|
end
|
||||||
|
else
|
||||||
|
{:error, changeset}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
Records a newly registered user's mailing-list opt-in.
|
||||||
|
|
||||||
|
The subscriber stays unconfirmed until the account itself is confirmed. If
|
||||||
|
the address was already subscribed anonymously, the existing row is linked to
|
||||||
|
the user and re-sourced so the account deletion cascade removes it.
|
||||||
|
"""
|
||||||
|
def subscribe_user(%User{} = user) do
|
||||||
|
%Subscriber{source: :registration, user_id: user.id}
|
||||||
|
|> Subscriber.changeset(%{email: user.email})
|
||||||
|
|> Repo.insert(
|
||||||
|
on_conflict: {:replace, [:user_id, :source, :updated_at]},
|
||||||
|
conflict_target: :email
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
Confirms a subscription by email address.
|
||||||
|
|
||||||
|
Returns `{:error, :not_found}` when the address is not on the list.
|
||||||
|
"""
|
||||||
|
def confirm(email) when is_binary(email) do
|
||||||
|
case Repo.get_by(Subscriber, email: String.trim(email)) do
|
||||||
|
nil ->
|
||||||
|
{:error, :not_found}
|
||||||
|
|
||||||
|
%Subscriber{confirmed_at: nil} = subscriber ->
|
||||||
|
subscriber
|
||||||
|
|> Ecto.Changeset.change(confirmed_at: DateTime.utc_now(:second))
|
||||||
|
|> Repo.update()
|
||||||
|
|
||||||
|
%Subscriber{} = subscriber ->
|
||||||
|
{:ok, subscriber}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
Confirms the subscription linked to a user whose account was just confirmed.
|
||||||
|
|
||||||
|
Registration opt-ins use the account-confirmation email as their proof of
|
||||||
|
address ownership, so this is called from the account confirmation flow.
|
||||||
|
"""
|
||||||
|
def confirm_user_subscription(%User{} = user) do
|
||||||
|
now = DateTime.utc_now(:second)
|
||||||
|
|
||||||
|
Subscriber
|
||||||
|
|> where([s], s.user_id == ^user.id and is_nil(s.confirmed_at))
|
||||||
|
|> Repo.update_all(set: [confirmed_at: now, updated_at: now])
|
||||||
|
end
|
||||||
|
|
||||||
|
@doc "Returns the number of confirmed addresses on the mailing list."
|
||||||
|
def count_confirmed_subscribers do
|
||||||
|
Subscriber
|
||||||
|
|> where([s], not is_nil(s.confirmed_at))
|
||||||
|
|> Repo.aggregate(:count)
|
||||||
|
end
|
||||||
|
|
||||||
|
defp insert_subscription(changeset, email) do
|
||||||
|
case Repo.insert(changeset) do
|
||||||
|
{:ok, _subscriber} ->
|
||||||
|
{:ok, :confirmation_required}
|
||||||
|
|
||||||
|
{:error, changeset} ->
|
||||||
|
# A concurrent request may have inserted the address between the read
|
||||||
|
# above and this insert; the unique constraint decides, so re-read it.
|
||||||
|
if email_taken?(changeset) do
|
||||||
|
case Repo.get_by(Subscriber, email: email) do
|
||||||
|
%Subscriber{confirmed_at: nil} -> {:ok, :confirmation_required}
|
||||||
|
%Subscriber{} -> {:ok, :already_subscribed}
|
||||||
|
nil -> {:error, changeset}
|
||||||
|
end
|
||||||
|
else
|
||||||
|
{:error, changeset}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp email_taken?(changeset) do
|
||||||
|
Enum.any?(changeset.errors, fn
|
||||||
|
{:email, {_message, opts}} -> opts[:constraint] == :unique
|
||||||
|
_other -> false
|
||||||
|
end)
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
defmodule Chesstrainer.MailingList.Notifier do
|
||||||
|
@moduledoc """
|
||||||
|
Emails for the mailing list.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import Swoosh.Email
|
||||||
|
|
||||||
|
alias Chesstrainer.Branding
|
||||||
|
alias Chesstrainer.Mailer
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
Delivers the confirmation email for a mailing-list subscription.
|
||||||
|
"""
|
||||||
|
def deliver_confirmation_instructions(email, url) do
|
||||||
|
deliver(email, "Confirm your mailing list subscription", """
|
||||||
|
|
||||||
|
==============================
|
||||||
|
|
||||||
|
Hi #{email},
|
||||||
|
|
||||||
|
You asked to receive occasional endgame tips and site news from
|
||||||
|
#{Branding.name()}. Confirm your subscription by visiting the URL below:
|
||||||
|
|
||||||
|
#{url}
|
||||||
|
|
||||||
|
If you didn't ask for this, ignore this email and we won't add you.
|
||||||
|
|
||||||
|
==============================
|
||||||
|
""")
|
||||||
|
end
|
||||||
|
|
||||||
|
defp deliver(recipient, subject, body) do
|
||||||
|
email =
|
||||||
|
new()
|
||||||
|
|> to(recipient)
|
||||||
|
|> from({Branding.name(), Branding.support_email()})
|
||||||
|
|> subject(subject)
|
||||||
|
|> text_body(body)
|
||||||
|
|
||||||
|
with {:ok, _metadata} <- Mailer.deliver(email) do
|
||||||
|
{:ok, email}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
defmodule Chesstrainer.MailingList.Subscriber do
|
||||||
|
use Ecto.Schema
|
||||||
|
import Ecto.Changeset
|
||||||
|
|
||||||
|
alias Chesstrainer.Accounts.User
|
||||||
|
|
||||||
|
@primary_key {:id, :binary_id, autogenerate: true}
|
||||||
|
@foreign_key_type :binary_id
|
||||||
|
schema "mailing_list_subscribers" do
|
||||||
|
field :email, :string
|
||||||
|
field :source, Ecto.Enum, values: [:home, :registration], default: :home
|
||||||
|
field :confirmed_at, :utc_datetime
|
||||||
|
belongs_to :user, User
|
||||||
|
|
||||||
|
timestamps(type: :utc_datetime)
|
||||||
|
end
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
A changeset for subscribing an email address.
|
||||||
|
|
||||||
|
`:source` and `:user_id` are programmatic: the context sets them on the
|
||||||
|
struct, never from user-supplied params.
|
||||||
|
"""
|
||||||
|
def changeset(subscriber, attrs) do
|
||||||
|
subscriber
|
||||||
|
|> cast(attrs, [:email])
|
||||||
|
|> update_change(:email, &String.trim/1)
|
||||||
|
|> validate_required([:email])
|
||||||
|
|> validate_format(:email, ~r/^[^@,;\s]+@[^@,;\s]+$/,
|
||||||
|
message: "must have the @ sign and no spaces"
|
||||||
|
)
|
||||||
|
|> validate_length(:email, max: 160)
|
||||||
|
|> unique_constraint(:email)
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -17,7 +17,7 @@ defmodule ChesstrainerWeb do
|
|||||||
those modules here.
|
those modules here.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def static_paths, do: ~w(assets fonts images favicon.ico robots.txt)
|
def static_paths, do: ~w(assets fonts images favicon.ico)
|
||||||
|
|
||||||
def router do
|
def router do
|
||||||
quote do
|
quote do
|
||||||
@@ -88,6 +88,8 @@ defmodule ChesstrainerWeb do
|
|||||||
import ChesstrainerWeb.CoreComponents
|
import ChesstrainerWeb.CoreComponents
|
||||||
# Landing-page primitives (pill buttons, marketing icons)
|
# Landing-page primitives (pill buttons, marketing icons)
|
||||||
import ChesstrainerWeb.LandingComponents
|
import ChesstrainerWeb.LandingComponents
|
||||||
|
# Rating gauge and explainer
|
||||||
|
import ChesstrainerWeb.RatingComponents
|
||||||
|
|
||||||
# Common modules used in templates
|
# Common modules used in templates
|
||||||
alias Phoenix.LiveView.JS
|
alias Phoenix.LiveView.JS
|
||||||
|
|||||||
@@ -8,7 +8,15 @@ defmodule ChesstrainerWeb.Board.BoardComponent do
|
|||||||
|
|
||||||
attr :game, :map, required: true
|
attr :game, :map, required: true
|
||||||
|
|
||||||
attr :myself, :any, required: true
|
attr :myself, :any, default: nil
|
||||||
|
|
||||||
|
attr :interactive, :boolean,
|
||||||
|
default: true,
|
||||||
|
doc: "emit square-click events (only useful inside a board LiveView)"
|
||||||
|
|
||||||
|
attr :class, :string,
|
||||||
|
default: "w-[388px] mt-6",
|
||||||
|
doc: "sizing and spacing for the board wrapper"
|
||||||
|
|
||||||
def board(assigns) do
|
def board(assigns) do
|
||||||
files_list = [:a, :b, :c, :d, :e, :f, :g, :h]
|
files_list = [:a, :b, :c, :d, :e, :f, :g, :h]
|
||||||
@@ -32,7 +40,7 @@ defmodule ChesstrainerWeb.Board.BoardComponent do
|
|||||||
)
|
)
|
||||||
|
|
||||||
~H"""
|
~H"""
|
||||||
<div class="w-[388px] m-auto left-0 right-0 mt-6">
|
<div class={["m-auto left-0 right-0", @class]}>
|
||||||
<div class="border border-2 border-zinc-700 grid grid-rows-8 grid-cols-8">
|
<div class="border border-2 border-zinc-700 grid grid-rows-8 grid-cols-8">
|
||||||
<%= for rank <- @ranks do %>
|
<%= for rank <- @ranks do %>
|
||||||
<%= for file <- @files do %>
|
<%= for file <- @files do %>
|
||||||
@@ -45,6 +53,7 @@ defmodule ChesstrainerWeb.Board.BoardComponent do
|
|||||||
files_list={@files_list}
|
files_list={@files_list}
|
||||||
move_from_square={@game.move_from_square}
|
move_from_square={@game.move_from_square}
|
||||||
myself={@myself}
|
myself={@myself}
|
||||||
|
interactive={@interactive}
|
||||||
/>
|
/>
|
||||||
<% end %>
|
<% end %>
|
||||||
<% end %>
|
<% end %>
|
||||||
|
|||||||
@@ -10,7 +10,8 @@ defmodule ChesstrainerWeb.Board.SquareComponent do
|
|||||||
attr :piece, :any, default: nil
|
attr :piece, :any, default: nil
|
||||||
attr :files_list, :list, required: true
|
attr :files_list, :list, required: true
|
||||||
attr :move_from_square, :any, default: nil
|
attr :move_from_square, :any, default: nil
|
||||||
attr :myself, :any, required: true
|
attr :myself, :any, default: nil
|
||||||
|
attr :interactive, :boolean, default: true
|
||||||
|
|
||||||
def square(assigns) do
|
def square(assigns) do
|
||||||
current_square = {assigns.file, assigns.rank}
|
current_square = {assigns.file, assigns.rank}
|
||||||
@@ -22,20 +23,20 @@ defmodule ChesstrainerWeb.Board.SquareComponent do
|
|||||||
~H"""
|
~H"""
|
||||||
<div
|
<div
|
||||||
class={[
|
class={[
|
||||||
"w-12 h-12 flex items-center justify-center",
|
"w-full aspect-square flex items-center justify-center",
|
||||||
background(
|
background(
|
||||||
Enum.find_index(@files_list, fn f -> f == @file end),
|
Enum.find_index(@files_list, fn f -> f == @file end),
|
||||||
@rank - 1
|
@rank - 1
|
||||||
),
|
),
|
||||||
highlight_square(@highlight_square)
|
highlight_square(@highlight_square)
|
||||||
]}
|
]}
|
||||||
phx-click="square-click"
|
phx-click={@interactive && "square-click"}
|
||||||
phx-value-file={@file}
|
phx-value-file={@interactive && @file}
|
||||||
phx-value-rank={@rank}
|
phx-value-rank={@interactive && @rank}
|
||||||
phx-value-type="move"
|
phx-value-type={@interactive && "move"}
|
||||||
phx-target={@myself}
|
phx-target={@interactive && @myself}
|
||||||
>
|
>
|
||||||
<.piece piece={@piece} class="w-10 h-10" />
|
<.piece piece={@piece} class="w-[83%] h-[83%]" />
|
||||||
</div>
|
</div>
|
||||||
"""
|
"""
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -8,6 +8,8 @@ defmodule ChesstrainerWeb.LandingComponents do
|
|||||||
"""
|
"""
|
||||||
use Phoenix.Component
|
use Phoenix.Component
|
||||||
|
|
||||||
|
import Phoenix.Controller, only: [get_csrf_token: 0]
|
||||||
|
|
||||||
alias Chesstrainer.FEN
|
alias Chesstrainer.FEN
|
||||||
alias Chesstrainer.Themes
|
alias Chesstrainer.Themes
|
||||||
|
|
||||||
@@ -70,6 +72,43 @@ defmodule ChesstrainerWeb.LandingComponents do
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
Renders the mailing-list signup band.
|
||||||
|
|
||||||
|
The form posts to `POST /mailing-list` and the controller redirects back to
|
||||||
|
the `#mailing-list` anchor with a flash. Keeping it a plain form means the
|
||||||
|
landing page needs no LiveView to collect an address.
|
||||||
|
"""
|
||||||
|
def mailing_list_signup(assigns) do
|
||||||
|
~H"""
|
||||||
|
<section class="mailing-list" id="mailing-list">
|
||||||
|
<div class="mailing-list-copy">
|
||||||
|
<span class="section-kicker">Mailing list</span>
|
||||||
|
<h2>One good endgame idea, now and then.</h2>
|
||||||
|
<p>
|
||||||
|
Occasional emails about new puzzles and features. We'll ask you to confirm your address first.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form action="/mailing-list" method="post" id="mailing-list-form" class="mailing-list-form">
|
||||||
|
<input type="hidden" name="_csrf_token" value={get_csrf_token()} />
|
||||||
|
<label for="mailing-list-email">Email address</label>
|
||||||
|
<div class="mailing-list-row">
|
||||||
|
<input
|
||||||
|
id="mailing-list-email"
|
||||||
|
type="email"
|
||||||
|
name="subscriber[email]"
|
||||||
|
placeholder="you@example.com"
|
||||||
|
autocomplete="email"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<.pill_button variant={:primary} type="submit">Join the list</.pill_button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
"""
|
||||||
|
end
|
||||||
|
|
||||||
@doc """
|
@doc """
|
||||||
Renders a static board preview for the landing page.
|
Renders a static board preview for the landing page.
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ defmodule ChesstrainerWeb.Layouts do
|
|||||||
use ChesstrainerWeb, :html
|
use ChesstrainerWeb, :html
|
||||||
|
|
||||||
alias Chesstrainer.Accounts.Role
|
alias Chesstrainer.Accounts.Role
|
||||||
|
alias Chesstrainer.Accounts.Scope
|
||||||
|
|
||||||
# Embed all files in layouts/* within this module.
|
# Embed all files in layouts/* within this module.
|
||||||
# The default root.html.heex file contains the HTML
|
# The default root.html.heex file contains the HTML
|
||||||
@@ -66,6 +67,7 @@ defmodule ChesstrainerWeb.Layouts do
|
|||||||
assigns
|
assigns
|
||||||
|> assign(:nav_links, nav_links(assigns.current_scope))
|
|> assign(:nav_links, nav_links(assigns.current_scope))
|
||||||
|> assign(:start_href, start_href(assigns.current_scope))
|
|> assign(:start_href, start_href(assigns.current_scope))
|
||||||
|
|> assign(:user, signed_in_user(assigns.current_scope))
|
||||||
|
|
||||||
~H"""
|
~H"""
|
||||||
<header>
|
<header>
|
||||||
@@ -91,11 +93,22 @@ defmodule ChesstrainerWeb.Layouts do
|
|||||||
|
|
||||||
<div class="nav-links" id="nav-links">
|
<div class="nav-links" id="nav-links">
|
||||||
<%= for link <- @nav_links do %>
|
<%= for link <- @nav_links do %>
|
||||||
<%= if link[:kind] == :text do %>
|
<.link href={link.href}>{link.label}</.link>
|
||||||
<span class="nav-user">{link.label}</span>
|
|
||||||
<% else %>
|
|
||||||
<.link href={link.href} method={link[:method]}>{link.label}</.link>
|
|
||||||
<% end %>
|
<% end %>
|
||||||
|
|
||||||
|
<%= if @user do %>
|
||||||
|
<details class="nav-user-menu">
|
||||||
|
<summary>{@user.username}</summary>
|
||||||
|
<div class="nav-user-menu-panel">
|
||||||
|
<.link navigate={~p"/users/profile"}>Account</.link>
|
||||||
|
<.link navigate={~p"/users/profile/settings"}>Settings</.link>
|
||||||
|
<.link navigate={~p"/users/profile/data"}>Data</.link>
|
||||||
|
<.link href={~p"/users/log-out"} method="delete">Log out</.link>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
<% else %>
|
||||||
|
<.link href={~p"/users/log-in"}>Log in</.link>
|
||||||
|
<.link href={~p"/users/register"}>Register</.link>
|
||||||
<% end %>
|
<% end %>
|
||||||
|
|
||||||
<.pill_button variant={:nav} href={@start_href}>
|
<.pill_button variant={:nav} href={@start_href}>
|
||||||
@@ -110,7 +123,7 @@ defmodule ChesstrainerWeb.Layouts do
|
|||||||
|
|
||||||
defp nav_links(scope) do
|
defp nav_links(scope) do
|
||||||
marketing =
|
marketing =
|
||||||
if premium?(scope) do
|
if Scope.premium?(scope) do
|
||||||
[
|
[
|
||||||
%{label: "Puzzle Search", href: "/endgames"}
|
%{label: "Puzzle Search", href: "/endgames"}
|
||||||
]
|
]
|
||||||
@@ -125,30 +138,15 @@ defmodule ChesstrainerWeb.Layouts do
|
|||||||
[]
|
[]
|
||||||
end
|
end
|
||||||
|
|
||||||
account =
|
marketing ++ admin
|
||||||
case scope do
|
|
||||||
%{user: %{username: username}} ->
|
|
||||||
[
|
|
||||||
%{label: "Settings", href: ~p"/users/settings"},
|
|
||||||
%{label: "Log out", href: ~p"/users/log-out", method: "delete"},
|
|
||||||
%{label: username, kind: :text}
|
|
||||||
]
|
|
||||||
|
|
||||||
_ ->
|
|
||||||
[
|
|
||||||
%{label: "Log in", href: ~p"/users/log-in"},
|
|
||||||
%{label: "Register", href: ~p"/users/register"}
|
|
||||||
]
|
|
||||||
end
|
end
|
||||||
|
|
||||||
marketing ++ admin ++ account
|
defp signed_in_user(%{user: %{username: _} = user}), do: user
|
||||||
end
|
defp signed_in_user(_scope), do: nil
|
||||||
|
|
||||||
defp admin?(%{user: %{role: role}}), do: Role.admin?(role)
|
defp admin?(%{user: %{role: role}}), do: Role.admin?(role)
|
||||||
defp admin?(_scope), do: false
|
defp admin?(_scope), do: false
|
||||||
|
|
||||||
defp premium?(scope), do: match?(%{user: %{plan: :premium}}, scope)
|
|
||||||
|
|
||||||
# Signed-in users start a puzzle session; visitors browse the public list.
|
# Signed-in users start a puzzle session; visitors browse the public list.
|
||||||
defp start_href(%{user: %{}}), do: ~p"/train"
|
defp start_href(%{user: %{}}), do: ~p"/train"
|
||||||
defp start_href(_scope), do: ~p"/guest-train"
|
defp start_href(_scope), do: ~p"/guest-train"
|
||||||
@@ -239,9 +237,10 @@ defmodule ChesstrainerWeb.Layouts do
|
|||||||
@doc """
|
@doc """
|
||||||
Provides the system / light / dark colour-mode switch.
|
Provides the system / light / dark colour-mode switch.
|
||||||
|
|
||||||
The click handling and `aria-checked` syncing live in the script in
|
The click handling and `aria-checked` syncing live in `theme_script.html.heex`,
|
||||||
`root.html.heex`, which runs before paint and also on pages without LiveView
|
which runs before paint and also on pages without LiveView (the landing page
|
||||||
(the landing page uses the marketing bundle).
|
uses the marketing bundle). Error pages include it explicitly because they do
|
||||||
|
not render through the root layout.
|
||||||
"""
|
"""
|
||||||
def colour_mode_toggle(assigns) do
|
def colour_mode_toggle(assigns) do
|
||||||
~H"""
|
~H"""
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8" />
|
<meta charset="utf-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<meta :if={assigns[:noindex]} name="robots" content="noindex" />
|
||||||
|
|
||||||
<meta name="csrf-token" content={get_csrf_token()} />
|
<meta name="csrf-token" content={get_csrf_token()} />
|
||||||
<.live_title
|
<.live_title
|
||||||
@@ -63,79 +64,7 @@
|
|||||||
src={assigns[:js_entry] || ~p"/assets/js/app.js"}
|
src={assigns[:js_entry] || ~p"/assets/js/app.js"}
|
||||||
>
|
>
|
||||||
</script>
|
</script>
|
||||||
<script>
|
<Layouts.theme_script />
|
||||||
(() => {
|
|
||||||
const systemMode = () => matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
|
|
||||||
|
|
||||||
const storedMode = () => {
|
|
||||||
try { return localStorage.getItem("phx:theme"); } catch (_) { return null; }
|
|
||||||
};
|
|
||||||
|
|
||||||
const persistMode = (mode) => {
|
|
||||||
try {
|
|
||||||
if (mode === "system") localStorage.removeItem("phx:theme");
|
|
||||||
else localStorage.setItem("phx:theme", mode);
|
|
||||||
} catch (_) {
|
|
||||||
// Storage can be blocked (private modes, embedded browsers); the
|
|
||||||
// mode still applies for this page load.
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const selectedMode = () => {
|
|
||||||
const source = document.documentElement.getAttribute("data-theme-source");
|
|
||||||
return source === "system" ? "system" : document.documentElement.getAttribute("data-theme");
|
|
||||||
};
|
|
||||||
|
|
||||||
const syncChecked = () => {
|
|
||||||
document.querySelectorAll("[data-phx-theme]").forEach((button) => {
|
|
||||||
button.setAttribute("aria-checked", String(button.dataset.phxTheme === selectedMode()));
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const setMode = (mode) => {
|
|
||||||
if (mode !== "system" && mode !== "light" && mode !== "dark") return;
|
|
||||||
|
|
||||||
if (mode === "system") {
|
|
||||||
persistMode("system");
|
|
||||||
document.documentElement.setAttribute("data-theme", systemMode());
|
|
||||||
document.documentElement.setAttribute("data-theme-source", "system");
|
|
||||||
} else {
|
|
||||||
persistMode(mode);
|
|
||||||
document.documentElement.setAttribute("data-theme", mode);
|
|
||||||
document.documentElement.setAttribute("data-theme-source", "user");
|
|
||||||
}
|
|
||||||
|
|
||||||
syncChecked();
|
|
||||||
};
|
|
||||||
|
|
||||||
if (!document.documentElement.hasAttribute("data-theme")) {
|
|
||||||
setMode(storedMode() || "system");
|
|
||||||
}
|
|
||||||
|
|
||||||
document.addEventListener("DOMContentLoaded", syncChecked);
|
|
||||||
|
|
||||||
// Plain DOM so the switch also works on controller-rendered pages
|
|
||||||
// (the landing page ships no LiveView runtime).
|
|
||||||
document.addEventListener("click", (event) => {
|
|
||||||
const button = event.target instanceof Element && event.target.closest("[data-phx-theme]");
|
|
||||||
if (button) setMode(button.dataset.phxTheme);
|
|
||||||
});
|
|
||||||
|
|
||||||
window.addEventListener("storage", (event) => {
|
|
||||||
if (event.key === "phx:theme") setMode(event.newValue || "system");
|
|
||||||
});
|
|
||||||
|
|
||||||
window.addEventListener("phx:set-theme", (event) => {
|
|
||||||
setMode(event.target?.dataset?.phxTheme);
|
|
||||||
});
|
|
||||||
|
|
||||||
matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => {
|
|
||||||
if (document.documentElement.getAttribute("data-theme-source") === "system") {
|
|
||||||
document.documentElement.setAttribute("data-theme", systemMode());
|
|
||||||
}
|
|
||||||
});
|
|
||||||
})();
|
|
||||||
</script>
|
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<Layouts.navbar current_scope={@current_scope} />
|
<Layouts.navbar current_scope={@current_scope} />
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
<script>
|
||||||
|
(() => {
|
||||||
|
const systemMode = () => matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
|
||||||
|
|
||||||
|
const storedMode = () => {
|
||||||
|
try { return localStorage.getItem("phx:theme"); } catch (_) { return null; }
|
||||||
|
};
|
||||||
|
|
||||||
|
const persistMode = (mode) => {
|
||||||
|
try {
|
||||||
|
if (mode === "system") localStorage.removeItem("phx:theme");
|
||||||
|
else localStorage.setItem("phx:theme", mode);
|
||||||
|
} catch (_) {
|
||||||
|
// Storage can be blocked (private modes, embedded browsers); the
|
||||||
|
// mode still applies for this page load.
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const selectedMode = () => {
|
||||||
|
const source = document.documentElement.getAttribute("data-theme-source");
|
||||||
|
return source === "system" ? "system" : document.documentElement.getAttribute("data-theme");
|
||||||
|
};
|
||||||
|
|
||||||
|
const syncChecked = () => {
|
||||||
|
document.querySelectorAll("[data-phx-theme]").forEach((button) => {
|
||||||
|
button.setAttribute("aria-checked", String(button.dataset.phxTheme === selectedMode()));
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const setMode = (mode) => {
|
||||||
|
if (mode !== "system" && mode !== "light" && mode !== "dark") return;
|
||||||
|
|
||||||
|
if (mode === "system") {
|
||||||
|
persistMode("system");
|
||||||
|
document.documentElement.setAttribute("data-theme", systemMode());
|
||||||
|
document.documentElement.setAttribute("data-theme-source", "system");
|
||||||
|
} else {
|
||||||
|
persistMode(mode);
|
||||||
|
document.documentElement.setAttribute("data-theme", mode);
|
||||||
|
document.documentElement.setAttribute("data-theme-source", "user");
|
||||||
|
}
|
||||||
|
|
||||||
|
syncChecked();
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!document.documentElement.hasAttribute("data-theme")) {
|
||||||
|
setMode(storedMode() || "system");
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener("DOMContentLoaded", syncChecked);
|
||||||
|
|
||||||
|
// Plain DOM so the switch also works on controller-rendered pages
|
||||||
|
// (the landing page ships no LiveView runtime).
|
||||||
|
document.addEventListener("click", (event) => {
|
||||||
|
const button = event.target instanceof Element && event.target.closest("[data-phx-theme]");
|
||||||
|
if (button) setMode(button.dataset.phxTheme);
|
||||||
|
});
|
||||||
|
|
||||||
|
window.addEventListener("storage", (event) => {
|
||||||
|
if (event.key === "phx:theme") setMode(event.newValue || "system");
|
||||||
|
});
|
||||||
|
|
||||||
|
window.addEventListener("phx:set-theme", (event) => {
|
||||||
|
setMode(event.target?.dataset?.phxTheme);
|
||||||
|
});
|
||||||
|
|
||||||
|
matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => {
|
||||||
|
if (document.documentElement.getAttribute("data-theme-source") === "system") {
|
||||||
|
document.documentElement.setAttribute("data-theme", systemMode());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
@@ -28,6 +28,7 @@ defmodule ChesstrainerWeb.PlayComponents do
|
|||||||
def play_surface(assigns) do
|
def play_surface(assigns) do
|
||||||
~H"""
|
~H"""
|
||||||
<div class="flex gap-2 bg-base-200 p-4 rounded-xl shadow-inner">
|
<div class="flex gap-2 bg-base-200 p-4 rounded-xl shadow-inner">
|
||||||
|
<div class="w-100 flex flex-col gap-2">
|
||||||
<div
|
<div
|
||||||
id="endgame-board"
|
id="endgame-board"
|
||||||
phx-hook="ChessBoard"
|
phx-hook="ChessBoard"
|
||||||
@@ -37,11 +38,102 @@ defmodule ChesstrainerWeb.PlayComponents do
|
|||||||
>
|
>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="w-48 h-100 flex flex-col gap-3">
|
<div :if={@reviewing} id="review-controls" class="flex items-center gap-2">
|
||||||
|
<.button
|
||||||
|
id="review-start"
|
||||||
|
phx-click="review_start"
|
||||||
|
disabled={@review_index <= 0}
|
||||||
|
title="Back to start"
|
||||||
|
>
|
||||||
|
{"<<"}
|
||||||
|
</.button>
|
||||||
|
<.button
|
||||||
|
id="review-prev"
|
||||||
|
phx-click="review_prev"
|
||||||
|
disabled={@review_index <= 0}
|
||||||
|
title="Previous position"
|
||||||
|
>
|
||||||
|
←
|
||||||
|
</.button>
|
||||||
|
<.button
|
||||||
|
id="review-next"
|
||||||
|
phx-click="review_next"
|
||||||
|
disabled={@review_index >= length(@line)}
|
||||||
|
title="Next position"
|
||||||
|
>
|
||||||
|
→
|
||||||
|
</.button>
|
||||||
|
<.button
|
||||||
|
id="review-end"
|
||||||
|
phx-click="review_end"
|
||||||
|
disabled={@review_index >= length(@line)}
|
||||||
|
title="Go to end"
|
||||||
|
>
|
||||||
|
{">>"}
|
||||||
|
</.button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex flex-wrap gap-2">
|
||||||
|
<.button
|
||||||
|
:if={(@reviewing and @review_tablebase) && PlayCore.best_move_text(@review_tablebase)}
|
||||||
|
phx-click="play_best_line"
|
||||||
|
disabled={@awaiting_best_line}
|
||||||
|
>
|
||||||
|
Play best line
|
||||||
|
</.button>
|
||||||
|
<.button :if={@reviewing and @line != @plies} phx-click="back_to_game">
|
||||||
|
Back to game
|
||||||
|
</.button>
|
||||||
|
<.button
|
||||||
|
:if={@status in [:solved, :failed] and not @reviewing}
|
||||||
|
phx-click="review"
|
||||||
|
>
|
||||||
|
<.icon name="hero-eye" /> Review
|
||||||
|
</.button>
|
||||||
|
<.button phx-click="reset" variant="primary">
|
||||||
|
<.icon name="hero-arrow-path" />
|
||||||
|
{if @status in [:solved, :failed], do: "Try again", else: "Reset"}
|
||||||
|
</.button>
|
||||||
|
<.button
|
||||||
|
:if={@session and @status in [:solved, :failed]}
|
||||||
|
id="next-puzzle-button"
|
||||||
|
phx-click="next_puzzle"
|
||||||
|
variant="primary"
|
||||||
|
>
|
||||||
|
Next puzzle
|
||||||
|
</.button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="relative w-48">
|
||||||
|
<div class="absolute inset-0 flex flex-col gap-3">
|
||||||
|
<%= if @reviewing do %>
|
||||||
|
<div
|
||||||
|
id="best-move-panel"
|
||||||
|
class="flex-1 min-h-0 overflow-y-auto rounded-lg bg-canvas-raised p-3 text-sm"
|
||||||
|
>
|
||||||
|
<%= cond do %>
|
||||||
|
<% @review_blocked -> %>
|
||||||
|
<p class="text-muted">Best move unavailable here</p>
|
||||||
|
<p class="text-muted">{@review_blocked}</p>
|
||||||
|
<% @review_tablebase -> %>
|
||||||
|
<p class="text-muted font-semibold mb-1">Best move:</p>
|
||||||
|
<p class="text-success-text">{PlayCore.best_move_text(@review_tablebase) || "—"}</p>
|
||||||
|
<%= if played_ply = played_ply_at(@line, @review_index) do %>
|
||||||
|
<p class={["mt-1", grade_class(played_ply.grade)]}>Played: {played_ply.san}</p>
|
||||||
|
<% end %>
|
||||||
|
<.tablebase_options tablebase={@review_tablebase} />
|
||||||
|
<% true -> %>
|
||||||
|
<p class="text-muted">No best move.</p>
|
||||||
|
<% end %>
|
||||||
|
</div>
|
||||||
|
<% else %>
|
||||||
<div class="rounded-lg bg-canvas-raised p-3 text-sm">
|
<div class="rounded-lg bg-canvas-raised p-3 text-sm">
|
||||||
<p class="flex items-center justify-between gap-2 font-semibold">
|
<p class="flex items-center justify-between gap-2 font-semibold">
|
||||||
<span>{turn_label(@status, @awaiting_reply)}</span>
|
<span>{turn_label(@status, @awaiting_reply)}</span>
|
||||||
<span class="text-xs font-normal text-muted">You play {colour_name(@endgame.color)}</span>
|
<span class="text-xs font-normal text-muted">
|
||||||
|
You play {colour_name(@endgame.color)}
|
||||||
|
</span>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -94,23 +186,10 @@ defmodule ChesstrainerWeb.PlayComponents do
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div :if={@reviewing} id="best-move-panel" class="rounded-lg bg-canvas-raised p-3 text-sm">
|
<div
|
||||||
<%= cond do %>
|
id="move-list"
|
||||||
<% @review_blocked -> %>
|
class="flex-1 min-h-0 flex flex-col bg-canvas-raised rounded-lg p-3"
|
||||||
<p class="text-muted">Best move unavailable here</p>
|
>
|
||||||
<p class="text-muted">{@review_blocked}</p>
|
|
||||||
<% @review_tablebase -> %>
|
|
||||||
<p class="text-muted font-semibold mb-1">Best move:</p>
|
|
||||||
<p class="text-success-text">{PlayCore.best_move_text(@review_tablebase) || "—"}</p>
|
|
||||||
<%= if played_ply = played_ply_at(@line, @review_index) do %>
|
|
||||||
<p class={["mt-1", grade_class(played_ply.grade)]}>Played: {played_ply.san}</p>
|
|
||||||
<% end %>
|
|
||||||
<% true -> %>
|
|
||||||
<p class="text-muted">No best move.</p>
|
|
||||||
<% end %>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div id="move-list" class="flex-1 min-h-0 flex flex-col bg-canvas-raised rounded-lg p-3">
|
|
||||||
<% plies = display_plies(@reviewing, @line, @plies) %>
|
<% plies = display_plies(@reviewing, @line, @plies) %>
|
||||||
<p class="text-sm text-muted font-semibold mb-2">Moves:</p>
|
<p class="text-sm text-muted font-semibold mb-2">Moves:</p>
|
||||||
<div class="flex-1 overflow-y-auto">
|
<div class="flex-1 overflow-y-auto">
|
||||||
@@ -143,45 +222,74 @@ defmodule ChesstrainerWeb.PlayComponents do
|
|||||||
<% end %>
|
<% end %>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<% end %>
|
||||||
<div class="flex flex-wrap gap-2">
|
|
||||||
<.button
|
|
||||||
:if={@status in [:solved, :failed] and not @reviewing}
|
|
||||||
phx-click="review"
|
|
||||||
>
|
|
||||||
<.icon name="hero-eye" /> Review
|
|
||||||
</.button>
|
|
||||||
<.button phx-click="reset" variant="primary">
|
|
||||||
<.icon name="hero-arrow-path" />
|
|
||||||
{if @status in [:solved, :failed], do: "Try again", else: "Reset"}
|
|
||||||
</.button>
|
|
||||||
<.button
|
|
||||||
:if={@session and @status in [:solved, :failed] and not @reviewing}
|
|
||||||
id="next-puzzle-button"
|
|
||||||
phx-click="next_puzzle"
|
|
||||||
variant="primary"
|
|
||||||
>
|
|
||||||
Next puzzle
|
|
||||||
</.button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div :if={@reviewing} id="review-controls" class="flex flex-wrap gap-2">
|
|
||||||
<.button phx-click="review_prev" disabled={@review_index <= 0}>←</.button>
|
|
||||||
<.button phx-click="review_next" disabled={@review_index >= length(@line)}>→</.button>
|
|
||||||
<.button
|
|
||||||
:if={@review_tablebase && PlayCore.best_move_text(@review_tablebase)}
|
|
||||||
phx-click="play_best_line"
|
|
||||||
disabled={@awaiting_best_line}
|
|
||||||
>
|
|
||||||
Play best line
|
|
||||||
</.button>
|
|
||||||
<.button :if={@line != @plies} phx-click="back_to_game">Back to game</.button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
"""
|
"""
|
||||||
end
|
end
|
||||||
|
|
||||||
|
attr :tablebase, :any, required: true
|
||||||
|
|
||||||
|
# The reviewed position's moves grouped like lichess's tablebase explorer:
|
||||||
|
# each heading is the outcome for the side to move, one table per outcome.
|
||||||
|
defp tablebase_options(assigns) do
|
||||||
|
assigns = assign(assigns, :groups, tablebase_groups(assigns.tablebase))
|
||||||
|
|
||||||
|
~H"""
|
||||||
|
<div :if={@groups != []} class="mt-3 border-t border-base-200 pt-2">
|
||||||
|
<p class="text-muted font-semibold mb-1">Tablebase</p>
|
||||||
|
<div :for={{label, class, moves} <- @groups} class="mt-2 first:mt-0">
|
||||||
|
<p class={["text-xs font-semibold", class]}>{label}</p>
|
||||||
|
<table class="w-full text-left text-xs font-mono">
|
||||||
|
<tbody>
|
||||||
|
<tr
|
||||||
|
:for={move <- moves}
|
||||||
|
phx-click="review_move"
|
||||||
|
phx-value-uci={move.uci}
|
||||||
|
class="cursor-pointer hover:bg-base-200"
|
||||||
|
title={"Play #{move.san}"}
|
||||||
|
>
|
||||||
|
<td class={["py-0.5 pr-2", class]}>{move.san}</td>
|
||||||
|
<td class="py-0.5 text-right text-muted" title="Distance to zeroing (DTZ)">
|
||||||
|
{dtz_text(move)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
"""
|
||||||
|
end
|
||||||
|
|
||||||
|
defp tablebase_groups(%{moves: moves}) when is_list(moves) do
|
||||||
|
[
|
||||||
|
{"Winning", "text-success-text", :win},
|
||||||
|
{"Drawn", "text-muted", :draw},
|
||||||
|
{"Losing", "text-error", :loss},
|
||||||
|
{"Unknown", "text-muted", :unknown}
|
||||||
|
]
|
||||||
|
|> Enum.flat_map(fn {label, class, outcome} ->
|
||||||
|
case Enum.filter(moves, &(mover_outcome(&1.category) == outcome)) do
|
||||||
|
[] -> []
|
||||||
|
moves -> [{label, class, moves}]
|
||||||
|
end
|
||||||
|
end)
|
||||||
|
end
|
||||||
|
|
||||||
|
defp tablebase_groups(_tablebase), do: []
|
||||||
|
|
||||||
|
# A move's category is the outcome for the side to move *after* the move, so
|
||||||
|
# the mover's outcome is its flip.
|
||||||
|
defp mover_outcome(:loss), do: :win
|
||||||
|
defp mover_outcome(:win), do: :loss
|
||||||
|
defp mover_outcome(:draw), do: :draw
|
||||||
|
defp mover_outcome(_), do: :unknown
|
||||||
|
|
||||||
|
defp dtz_text(%{dtz: nil}), do: ""
|
||||||
|
|
||||||
|
defp dtz_text(%{dtz: dtz}), do: "DTZ #{abs(dtz)}"
|
||||||
|
|
||||||
attr :ply, :map, required: true
|
attr :ply, :map, required: true
|
||||||
attr :reviewing, :boolean, required: true
|
attr :reviewing, :boolean, required: true
|
||||||
attr :review_index, :integer, required: true
|
attr :review_index, :integer, required: true
|
||||||
@@ -242,15 +350,17 @@ defmodule ChesstrainerWeb.PlayComponents do
|
|||||||
|
|
||||||
defp played_ply_at(line, review_index) do
|
defp played_ply_at(line, review_index) do
|
||||||
case Enum.at(line, review_index) do
|
case Enum.at(line, review_index) do
|
||||||
%{best_line: true} -> nil
|
%{analysis: true} -> nil
|
||||||
ply -> ply
|
ply -> ply
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
defp ply_class(%{best_line: true}), do: "text-info italic"
|
defp ply_class(%{best_line: true}), do: "text-info italic"
|
||||||
|
defp ply_class(%{analysis: true}), do: "text-info"
|
||||||
defp ply_class(ply), do: grade_class(ply.grade)
|
defp ply_class(ply), do: grade_class(ply.grade)
|
||||||
|
|
||||||
defp ply_title(%{best_line: true}, _result), do: "Best line"
|
defp ply_title(%{best_line: true}, _result), do: "Best line"
|
||||||
|
defp ply_title(%{analysis: true}, _result), do: "Tablebase move"
|
||||||
defp ply_title(ply, result), do: grade_label(ply.grade, result)
|
defp ply_title(ply, result), do: grade_label(ply.grade, result)
|
||||||
|
|
||||||
defp grade_class(:optimal), do: "text-success-text"
|
defp grade_class(:optimal), do: "text-success-text"
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
defmodule ChesstrainerWeb.RatingComponents do
|
||||||
|
@moduledoc """
|
||||||
|
Visual guide to a user's rating.
|
||||||
|
|
||||||
|
Places the rating on a fixed scale and shades the range the true rating is
|
||||||
|
likely to sit in, derived from the rating deviation (rating ± 2×RD). The
|
||||||
|
band is intentionally wide for a new or returning player: it narrows as
|
||||||
|
rated attempts accumulate, which is exactly what the deviation measures.
|
||||||
|
"""
|
||||||
|
|
||||||
|
use Phoenix.Component
|
||||||
|
|
||||||
|
# Glicko ratings are conventionally shown on a 0–3000 scale. The default
|
||||||
|
# rating is 1500 and the deviation is capped at 350, so 500–3000 keeps the
|
||||||
|
# useful range readable without letting a stray value push the marker off.
|
||||||
|
@scale_min 500
|
||||||
|
@scale_max 3000
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
Renders the rating gauge with its confidence band and explainer.
|
||||||
|
"""
|
||||||
|
attr :rating, :float, required: true
|
||||||
|
attr :deviation, :float, default: nil
|
||||||
|
attr :id, :string, default: "rating-guide"
|
||||||
|
|
||||||
|
def rating_guide(assigns) do
|
||||||
|
low = assigns.deviation && assigns.rating - 2 * assigns.deviation
|
||||||
|
high = assigns.deviation && assigns.rating + 2 * assigns.deviation
|
||||||
|
|
||||||
|
assigns =
|
||||||
|
assign(assigns,
|
||||||
|
low: low,
|
||||||
|
high: high,
|
||||||
|
scale_min: @scale_min,
|
||||||
|
scale_max: @scale_max,
|
||||||
|
marker_pct: pct(assigns.rating),
|
||||||
|
band_left: low && pct(low),
|
||||||
|
band_width: low && pct(high) - pct(low),
|
||||||
|
label: aria_label(assigns.rating, low, high)
|
||||||
|
)
|
||||||
|
|
||||||
|
~H"""
|
||||||
|
<section id={@id} class="rounded-lg bg-canvas-raised p-3 text-sm">
|
||||||
|
<div class="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1">
|
||||||
|
<p class="font-semibold">Your rating: {round(@rating)}</p>
|
||||||
|
<p :if={@low} id={"#{@id}-range"} class="text-xs text-muted">
|
||||||
|
likely {round(@low)}–{round(@high)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="relative mt-3 h-2 rounded-full bg-base-300" role="img" aria-label={@label}>
|
||||||
|
<div
|
||||||
|
:if={@low}
|
||||||
|
class="absolute inset-y-0 rounded-full bg-primary/30"
|
||||||
|
style={"left: #{@band_left}%; width: #{@band_width}%"}
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
class="absolute -top-1 h-4 w-0.5 -translate-x-1/2 rounded-full bg-primary"
|
||||||
|
style={"left: #{@marker_pct}%"}
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mt-1 flex justify-between text-[10px] text-muted">
|
||||||
|
<span>{@scale_min}</span>
|
||||||
|
<span>{@scale_max}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p class="mt-2 text-xs text-muted">
|
||||||
|
Your rating estimates how well you solve endgames. It moves after each
|
||||||
|
rated attempt — solving a harder puzzle gains more, and replaying the
|
||||||
|
same puzzle within a week does not count. The shaded band is the range
|
||||||
|
your true rating is likely to sit in (±2 rating deviations); it narrows
|
||||||
|
as you play.
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
"""
|
||||||
|
end
|
||||||
|
|
||||||
|
# Position on the gauge as a percentage, clamped to the drawn scale.
|
||||||
|
defp pct(value) do
|
||||||
|
clamped = value |> max(@scale_min) |> min(@scale_max)
|
||||||
|
Float.round((clamped - @scale_min) / (@scale_max - @scale_min) * 100, 1)
|
||||||
|
end
|
||||||
|
|
||||||
|
defp aria_label(rating, nil, nil) do
|
||||||
|
"Rating #{round(rating)} on a #{@scale_min} to #{@scale_max} scale"
|
||||||
|
end
|
||||||
|
|
||||||
|
defp aria_label(rating, low, high) do
|
||||||
|
"Rating #{round(rating)}, likely between #{round(low)} and #{round(high)}, " <>
|
||||||
|
"on a #{@scale_min} to #{@scale_max} scale"
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -3,21 +3,50 @@ defmodule ChesstrainerWeb.ErrorHTML do
|
|||||||
This module is invoked by your endpoint in case of errors on HTML requests.
|
This module is invoked by your endpoint in case of errors on HTML requests.
|
||||||
|
|
||||||
See config/config.exs.
|
See config/config.exs.
|
||||||
|
|
||||||
|
Error templates are rendered outside the root layout, so `404.html.heex` and
|
||||||
|
`500.html.heex` each render a complete document. They share the body markup
|
||||||
|
through `error_page/1`, which the catch-all 404 route also uses.
|
||||||
"""
|
"""
|
||||||
use ChesstrainerWeb, :html
|
use ChesstrainerWeb, :html
|
||||||
|
|
||||||
# If you want to customize your error pages,
|
alias Chesstrainer.Accounts.Scope
|
||||||
# uncomment the embed_templates/1 call below
|
|
||||||
# and add pages to the error directory:
|
|
||||||
#
|
|
||||||
# * lib/chesstrainer_web/controllers/error_html/404.html.heex
|
|
||||||
# * lib/chesstrainer_web/controllers/error_html/500.html.heex
|
|
||||||
#
|
|
||||||
# embed_templates "error_html/*"
|
|
||||||
|
|
||||||
# The default is to render a plain text page based on
|
embed_templates "error_html/*"
|
||||||
# the template name. For example, "404.html" becomes
|
|
||||||
# "Not Found".
|
@doc """
|
||||||
|
The body shared by the standalone error pages and the catch-all 404 route.
|
||||||
|
|
||||||
|
Rendered inside the root layout by `PageController.not_found/2`, and directly
|
||||||
|
by the `ErrorHTML` templates, which bypass layouts.
|
||||||
|
"""
|
||||||
|
attr :status, :integer, required: true
|
||||||
|
attr :title, :string, required: true
|
||||||
|
attr :message, :string, required: true
|
||||||
|
attr :hint, :string, default: nil
|
||||||
|
attr :current_scope, :map, default: nil
|
||||||
|
|
||||||
|
def error_page(assigns) do
|
||||||
|
~H"""
|
||||||
|
<main class="error-page">
|
||||||
|
<span class="error-code">{@status}</span>
|
||||||
|
<h1>{@title}</h1>
|
||||||
|
<p>{@message}</p>
|
||||||
|
<p :if={@hint} class="error-hint">{@hint}</p>
|
||||||
|
|
||||||
|
<div class="error-actions">
|
||||||
|
<.pill_button variant={:primary} href={~p"/"}>
|
||||||
|
Back to home <.icon_arrow />
|
||||||
|
</.pill_button>
|
||||||
|
<.pill_button :if={Scope.premium?(@current_scope)} variant={:light} href={~p"/endgames"}>
|
||||||
|
Browse puzzles
|
||||||
|
</.pill_button>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
"""
|
||||||
|
end
|
||||||
|
|
||||||
|
# Statuses without a template keep the previous plain-text behaviour.
|
||||||
def render(template, _assigns) do
|
def render(template, _assigns) do
|
||||||
Phoenix.Controller.status_message_from_template(template)
|
Phoenix.Controller.status_message_from_template(template)
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<meta name="robots" content="noindex" />
|
||||||
|
<title>{Branding.title("Page not found")}</title>
|
||||||
|
|
||||||
|
<link phx-track-static rel="stylesheet" href={~p"/assets/css/app.css"} />
|
||||||
|
<link
|
||||||
|
rel="preload"
|
||||||
|
href="/fonts/dm-sans-variable.woff2"
|
||||||
|
as="font"
|
||||||
|
type="font/woff2"
|
||||||
|
crossorigin
|
||||||
|
/>
|
||||||
|
<link
|
||||||
|
rel="preload"
|
||||||
|
href="/fonts/dm-serif-display.woff2"
|
||||||
|
as="font"
|
||||||
|
type="font/woff2"
|
||||||
|
crossorigin
|
||||||
|
/>
|
||||||
|
|
||||||
|
<script defer phx-track-static type="text/javascript" src={~p"/assets/js/marketing.js"}>
|
||||||
|
</script>
|
||||||
|
<Layouts.theme_script />
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<Layouts.navbar current_scope={assigns[:current_scope]} />
|
||||||
|
|
||||||
|
<.error_page
|
||||||
|
status={404}
|
||||||
|
title="This page isn't on the board"
|
||||||
|
message="The page you were looking for moved, or never existed. Check the address, or head back to the trainer."
|
||||||
|
current_scope={assigns[:current_scope]}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Layouts.footer />
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<meta name="robots" content="noindex" />
|
||||||
|
<title>{Branding.title("Something went wrong")}</title>
|
||||||
|
|
||||||
|
<link phx-track-static rel="stylesheet" href={~p"/assets/css/app.css"} />
|
||||||
|
<link
|
||||||
|
rel="preload"
|
||||||
|
href="/fonts/dm-sans-variable.woff2"
|
||||||
|
as="font"
|
||||||
|
type="font/woff2"
|
||||||
|
crossorigin
|
||||||
|
/>
|
||||||
|
<link
|
||||||
|
rel="preload"
|
||||||
|
href="/fonts/dm-serif-display.woff2"
|
||||||
|
as="font"
|
||||||
|
type="font/woff2"
|
||||||
|
crossorigin
|
||||||
|
/>
|
||||||
|
|
||||||
|
<script defer phx-track-static type="text/javascript" src={~p"/assets/js/marketing.js"}>
|
||||||
|
</script>
|
||||||
|
<Layouts.theme_script />
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<Layouts.navbar current_scope={assigns[:current_scope]} />
|
||||||
|
|
||||||
|
<.error_page
|
||||||
|
status={500}
|
||||||
|
title="Something went wrong"
|
||||||
|
message="An unexpected error stopped this page from loading. It's on us, not you — please try again in a moment."
|
||||||
|
hint={"If it keeps happening, email #{Branding.support_email()}."}
|
||||||
|
current_scope={assigns[:current_scope]}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Layouts.footer />
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -12,6 +12,14 @@ defmodule ChesstrainerWeb.ErrorJSON do
|
|||||||
# %{errors: %{detail: "Internal Server Error"}}
|
# %{errors: %{detail: "Internal Server Error"}}
|
||||||
# end
|
# end
|
||||||
|
|
||||||
|
def render("404.json", _assigns) do
|
||||||
|
%{errors: %{detail: "Not Found"}}
|
||||||
|
end
|
||||||
|
|
||||||
|
def render("500.json", _assigns) do
|
||||||
|
%{errors: %{detail: "Internal Server Error"}}
|
||||||
|
end
|
||||||
|
|
||||||
# By default, Phoenix returns the status message from
|
# By default, Phoenix returns the status message from
|
||||||
# the template name. For example, "404.json" becomes
|
# the template name. For example, "404.json" becomes
|
||||||
# "Not Found".
|
# "Not Found".
|
||||||
|
|||||||
@@ -0,0 +1,89 @@
|
|||||||
|
defmodule ChesstrainerWeb.MailingListController do
|
||||||
|
use ChesstrainerWeb, :controller
|
||||||
|
|
||||||
|
alias Chesstrainer.MailingList
|
||||||
|
alias Chesstrainer.MailingList.Notifier
|
||||||
|
|
||||||
|
@return_to "/#mailing-list"
|
||||||
|
@token_salt "mailing_list_confirm"
|
||||||
|
@token_max_age 7 * 24 * 60 * 60
|
||||||
|
|
||||||
|
def create(conn, %{"subscriber" => %{"email" => email}}) when is_binary(email) do
|
||||||
|
email = String.trim(email)
|
||||||
|
|
||||||
|
case MailingList.subscribe(email) do
|
||||||
|
{:ok, :already_subscribed} ->
|
||||||
|
conn
|
||||||
|
|> put_flash(:info, "You're already on the mailing list.")
|
||||||
|
|> redirect(to: @return_to)
|
||||||
|
|
||||||
|
{:ok, :confirmation_required} ->
|
||||||
|
case send_confirmation(email) do
|
||||||
|
:ok ->
|
||||||
|
conn
|
||||||
|
|> put_flash(:info, "Check your inbox to confirm your subscription.")
|
||||||
|
|> redirect(to: @return_to)
|
||||||
|
|
||||||
|
:error ->
|
||||||
|
conn
|
||||||
|
|> put_flash(:error, "We couldn't send the confirmation email. Please try again.")
|
||||||
|
|> redirect(to: @return_to)
|
||||||
|
end
|
||||||
|
|
||||||
|
{:error, %Ecto.Changeset{}} ->
|
||||||
|
conn
|
||||||
|
|> put_flash(:error, "Enter a valid email address.")
|
||||||
|
|> redirect(to: @return_to)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def create(conn, _params) do
|
||||||
|
conn
|
||||||
|
|> put_flash(:error, "Enter a valid email address.")
|
||||||
|
|> redirect(to: @return_to)
|
||||||
|
end
|
||||||
|
|
||||||
|
def confirm(conn, %{"token" => token}) do
|
||||||
|
case Phoenix.Token.verify(
|
||||||
|
ChesstrainerWeb.Endpoint,
|
||||||
|
@token_salt,
|
||||||
|
token,
|
||||||
|
max_age: @token_max_age
|
||||||
|
) do
|
||||||
|
{:ok, email} ->
|
||||||
|
confirm_subscription(conn, email)
|
||||||
|
|
||||||
|
{:error, _reason} ->
|
||||||
|
conn
|
||||||
|
|> put_flash(:error, "That confirmation link is invalid or has expired.")
|
||||||
|
|> redirect(to: @return_to)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp confirm_subscription(conn, email) do
|
||||||
|
case MailingList.confirm(email) do
|
||||||
|
{:ok, _subscriber} ->
|
||||||
|
conn
|
||||||
|
|> put_flash(:info, "Your mailing list subscription is confirmed.")
|
||||||
|
|> redirect(to: @return_to)
|
||||||
|
|
||||||
|
{:error, :not_found} ->
|
||||||
|
conn
|
||||||
|
|> put_flash(
|
||||||
|
:error,
|
||||||
|
"That address is no longer on the mailing list. Please sign up again."
|
||||||
|
)
|
||||||
|
|> redirect(to: @return_to)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp send_confirmation(email) do
|
||||||
|
token = Phoenix.Token.sign(ChesstrainerWeb.Endpoint, @token_salt, email)
|
||||||
|
url = url(~p"/mailing-list/confirm/#{token}")
|
||||||
|
|
||||||
|
case Notifier.deliver_confirmation_instructions(email, url) do
|
||||||
|
{:ok, _email} -> :ok
|
||||||
|
{:error, _reason} -> :error
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
defmodule ChesstrainerWeb.PageController do
|
defmodule ChesstrainerWeb.PageController do
|
||||||
use ChesstrainerWeb, :controller
|
use ChesstrainerWeb, :controller
|
||||||
|
|
||||||
|
alias Chesstrainer.Accounts
|
||||||
alias Chesstrainer.Attempts
|
alias Chesstrainer.Attempts
|
||||||
alias Chesstrainer.Branding
|
alias Chesstrainer.Branding
|
||||||
alias Chesstrainer.DailyPuzzles
|
alias Chesstrainer.DailyPuzzles
|
||||||
@@ -23,6 +24,7 @@ defmodule ChesstrainerWeb.PageController do
|
|||||||
active_endgame: DailyPuzzles.today(),
|
active_endgame: DailyPuzzles.today(),
|
||||||
puzzle_count: Endgames.count_endgames(),
|
puzzle_count: Endgames.count_endgames(),
|
||||||
user_count: Attempts.count_users_with_attempts(),
|
user_count: Attempts.count_users_with_attempts(),
|
||||||
|
logged_in_count: Accounts.count_logged_in_users(),
|
||||||
today: Date.utc_today()
|
today: Date.utc_today()
|
||||||
)
|
)
|
||||||
end
|
end
|
||||||
@@ -49,4 +51,14 @@ defmodule ChesstrainerWeb.PageController do
|
|||||||
|> assign(:canonical_url, current_url(conn))
|
|> assign(:canonical_url, current_url(conn))
|
||||||
|> render(:terms_conditions)
|
|> render(:terms_conditions)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def not_found(conn, _params) do
|
||||||
|
conn
|
||||||
|
|> put_status(:not_found)
|
||||||
|
|> assign(:js_entry, ~p"/assets/js/marketing.js")
|
||||||
|
|> assign(:page_title, Branding.title("Page not found"))
|
||||||
|
|> assign(:title_suffix, "")
|
||||||
|
|> assign(:noindex, true)
|
||||||
|
|> render(:not_found)
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -23,7 +23,7 @@
|
|||||||
<i>♜</i>
|
<i>♜</i>
|
||||||
</span>
|
</span>
|
||||||
<span>
|
<span>
|
||||||
<strong>{count_label(@user_count)}</strong> players training
|
<strong>{count_label(@logged_in_count)}</strong> players training
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -37,17 +37,13 @@
|
|||||||
|
|
||||||
<section class="learning-strip" id="method">
|
<section class="learning-strip" id="method">
|
||||||
<p>Built for the part of chess that decides everything.</p>
|
<p>Built for the part of chess that decides everything.</p>
|
||||||
<div class="stat">
|
|
||||||
<strong>10</strong>
|
|
||||||
<span>minutes a day</span>
|
|
||||||
</div>
|
|
||||||
<div class="stat">
|
<div class="stat">
|
||||||
<strong>{count_label(@puzzle_count)}</strong>
|
<strong>{count_label(@puzzle_count)}</strong>
|
||||||
<span>puzzles</span>
|
<span>puzzles</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="stat">
|
<div class="stat">
|
||||||
<strong>3.2×</strong>
|
<strong>{@user_count}</strong>
|
||||||
<span>faster pattern recall</span>
|
<span>Players improving their endgame</span>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@@ -75,6 +71,8 @@
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<.mailing_list_signup />
|
||||||
|
|
||||||
<%!-- <section class="progress-banner" id="progress">
|
<%!-- <section class="progress-banner" id="progress">
|
||||||
<div>
|
<div>
|
||||||
<span class="section-kicker">A calmer way to improve</span>
|
<span class="section-kicker">A calmer way to improve</span>
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<Layouts.flash_group flash={@flash} />
|
||||||
|
|
||||||
|
<ChesstrainerWeb.ErrorHTML.error_page
|
||||||
|
status={404}
|
||||||
|
title="This page isn't on the board"
|
||||||
|
message="The page you were looking for moved, or never existed. Check the address, or head back to the trainer."
|
||||||
|
current_scope={@current_scope}
|
||||||
|
/>
|
||||||
@@ -24,6 +24,13 @@
|
|||||||
We record the puzzles you attempt and whether you solved them, so we can
|
We record the puzzles you attempt and whether you solved them, so we can
|
||||||
show your progress and keep the daily puzzle meaningful.
|
show your progress and keep the daily puzzle meaningful.
|
||||||
</li>
|
</li>
|
||||||
|
<li>
|
||||||
|
<strong>Mailing list email.</strong>
|
||||||
|
If you join the mailing list — using the form on the home page or the
|
||||||
|
checkbox when registering — we store your email address and where you
|
||||||
|
signed up, so we can send you occasional updates. You can ask to be
|
||||||
|
removed at any time.
|
||||||
|
</li>
|
||||||
<li>
|
<li>
|
||||||
<strong>Technical data.</strong>
|
<strong>Technical data.</strong>
|
||||||
Our hosting and server infrastructure may keep standard request logs
|
Our hosting and server infrastructure may keep standard request logs
|
||||||
@@ -58,6 +65,7 @@
|
|||||||
<li>To create and secure your account and sign you in.</li>
|
<li>To create and secure your account and sign you in.</li>
|
||||||
<li>To run the trainer and remember your progress.</li>
|
<li>To run the trainer and remember your progress.</li>
|
||||||
<li>To send service emails, such as confirmation and password reset links.</li>
|
<li>To send service emails, such as confirmation and password reset links.</li>
|
||||||
|
<li>To send occasional endgame tips and site news, if you opted in.</li>
|
||||||
<li>To keep the site available, prevent abuse, and fix faults.</li>
|
<li>To keep the site available, prevent abuse, and fix faults.</li>
|
||||||
<li>To respond when you ask for help.</li>
|
<li>To respond when you ask for help.</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
defmodule ChesstrainerWeb.RobotsController do
|
||||||
|
@moduledoc """
|
||||||
|
Serves `/robots.txt` with a sitemap URL that follows the deployment's host.
|
||||||
|
|
||||||
|
Built at runtime from the endpoint configuration rather than checked in as a
|
||||||
|
static file, so the sitemap stays correct across environments.
|
||||||
|
"""
|
||||||
|
|
||||||
|
use ChesstrainerWeb, :controller
|
||||||
|
|
||||||
|
def index(conn, _params) do
|
||||||
|
body = """
|
||||||
|
User-agent: *
|
||||||
|
Allow: /
|
||||||
|
|
||||||
|
Sitemap: #{url(conn, ~p"/sitemap.xml")}
|
||||||
|
"""
|
||||||
|
|
||||||
|
conn
|
||||||
|
|> put_resp_content_type("text/plain")
|
||||||
|
|> send_resp(200, body)
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
defmodule ChesstrainerWeb.SitemapController do
|
||||||
|
@moduledoc """
|
||||||
|
Generates `/sitemap.xml` for the indexable public pages.
|
||||||
|
|
||||||
|
Endgame play pages are deliberately left out: there are tens of thousands of
|
||||||
|
them and they render the same interactive surface with only the position
|
||||||
|
differing, so listing them all would be index bloat. Revisit that if public
|
||||||
|
browse pages (by Key or theme) exist and are worth ranking.
|
||||||
|
"""
|
||||||
|
|
||||||
|
use ChesstrainerWeb, :controller
|
||||||
|
|
||||||
|
def index(conn, _params) do
|
||||||
|
urls = [
|
||||||
|
url(conn, ~p"/"),
|
||||||
|
url(conn, ~p"/privacy"),
|
||||||
|
url(conn, ~p"/terms-conditions")
|
||||||
|
]
|
||||||
|
|
||||||
|
conn
|
||||||
|
|> put_resp_content_type("application/xml")
|
||||||
|
|> send_resp(200, render_sitemap(urls))
|
||||||
|
end
|
||||||
|
|
||||||
|
defp render_sitemap(urls) do
|
||||||
|
entries = Enum.map_join(urls, &" <url><loc>#{escape(&1)}</loc></url>\n")
|
||||||
|
|
||||||
|
"""
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
||||||
|
#{entries}</urlset>
|
||||||
|
"""
|
||||||
|
end
|
||||||
|
|
||||||
|
# Templates escape automatically; this response is built as a plain string,
|
||||||
|
# so XML-significant characters must be escaped here.
|
||||||
|
defp escape(value) do
|
||||||
|
value
|
||||||
|
|> String.replace("&", "&")
|
||||||
|
|> String.replace("<", "<")
|
||||||
|
|> String.replace(">", ">")
|
||||||
|
|> String.replace("\"", """)
|
||||||
|
|> String.replace("'", "'")
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -2,10 +2,13 @@ defmodule ChesstrainerWeb.UserConfirmationController do
|
|||||||
use ChesstrainerWeb, :controller
|
use ChesstrainerWeb, :controller
|
||||||
|
|
||||||
alias Chesstrainer.Accounts
|
alias Chesstrainer.Accounts
|
||||||
|
alias Chesstrainer.MailingList
|
||||||
|
|
||||||
def edit(conn, %{"token" => token}) do
|
def edit(conn, %{"token" => token}) do
|
||||||
case Accounts.confirm_user(token) do
|
case Accounts.confirm_user(token) do
|
||||||
{:ok, _user} ->
|
{:ok, user} ->
|
||||||
|
MailingList.confirm_user_subscription(user)
|
||||||
|
|
||||||
conn
|
conn
|
||||||
|> put_flash(:info, "User confirmed successfully.")
|
|> put_flash(:info, "User confirmed successfully.")
|
||||||
|> redirect(to: ~p"/users/log-in")
|
|> redirect(to: ~p"/users/log-in")
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
defmodule ChesstrainerWeb.UserDataController do
|
||||||
|
use ChesstrainerWeb, :controller
|
||||||
|
|
||||||
|
alias Chesstrainer.Attempts
|
||||||
|
|
||||||
|
@user_columns ~w(user_username user_email user_rating user_rating_deviation user_plan user_joined_at)
|
||||||
|
@attempt_columns ~w(played_at puzzle public_code color result outcome rated_at)
|
||||||
|
@columns @user_columns ++ @attempt_columns
|
||||||
|
|
||||||
|
def export(conn, %{"format" => format}) when format in ["csv", "json"] do
|
||||||
|
user = conn.assigns.current_scope.user
|
||||||
|
attempts = Attempts.list_attempts_for_user(user.id)
|
||||||
|
filename = "lucid-chess-data-#{Date.utc_today()}.#{format}"
|
||||||
|
|
||||||
|
conn
|
||||||
|
|> put_resp_content_type(content_type(format))
|
||||||
|
|> put_resp_header("content-disposition", ~s(attachment; filename="#{filename}"))
|
||||||
|
|> send_resp(200, body(format, user, attempts))
|
||||||
|
end
|
||||||
|
|
||||||
|
def export(conn, _params), do: send_resp(conn, 404, "Unknown export format")
|
||||||
|
|
||||||
|
defp body("csv", user, attempts), do: to_csv(user, attempts)
|
||||||
|
|
||||||
|
defp body("json", user, attempts) do
|
||||||
|
%{user: user_map(user), attempts: Enum.map(attempts, &attempt_map/1)}
|
||||||
|
|> Jason.encode!(pretty: true)
|
||||||
|
end
|
||||||
|
|
||||||
|
defp user_map(user) do
|
||||||
|
%{
|
||||||
|
username: user.username,
|
||||||
|
email: user.email,
|
||||||
|
rating: user.rating,
|
||||||
|
rating_deviation: user.rating_deviation,
|
||||||
|
plan: user.plan,
|
||||||
|
joined_at: DateTime.to_iso8601(user.inserted_at)
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
defp attempt_map(attempt) do
|
||||||
|
%{
|
||||||
|
played_at: DateTime.to_iso8601(attempt.inserted_at),
|
||||||
|
puzzle: attempt.endgame.key,
|
||||||
|
public_code: attempt.endgame.public_code,
|
||||||
|
color: attempt.endgame.color,
|
||||||
|
result: attempt.endgame.result,
|
||||||
|
outcome: attempt.outcome,
|
||||||
|
rated_at: attempt.rated_at && DateTime.to_iso8601(attempt.rated_at)
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
defp to_csv(user, attempts) do
|
||||||
|
rows =
|
||||||
|
case attempts do
|
||||||
|
[] -> [user_row(user) ++ empty_attempt_row()]
|
||||||
|
attempts -> Enum.map(attempts, &(user_row(user) ++ attempt_row(&1)))
|
||||||
|
end
|
||||||
|
|
||||||
|
[@columns | rows]
|
||||||
|
|> Enum.map_join("\n", fn row -> Enum.map_join(row, ",", &csv_field/1) end)
|
||||||
|
|> Kernel.<>("\n")
|
||||||
|
end
|
||||||
|
|
||||||
|
defp user_row(user) do
|
||||||
|
[
|
||||||
|
user.username,
|
||||||
|
user.email,
|
||||||
|
user.rating,
|
||||||
|
user.rating_deviation,
|
||||||
|
user.plan,
|
||||||
|
DateTime.to_iso8601(user.inserted_at)
|
||||||
|
]
|
||||||
|
end
|
||||||
|
|
||||||
|
defp attempt_row(attempt) do
|
||||||
|
[
|
||||||
|
DateTime.to_iso8601(attempt.inserted_at),
|
||||||
|
attempt.endgame.key,
|
||||||
|
attempt.endgame.public_code,
|
||||||
|
attempt.endgame.color,
|
||||||
|
attempt.endgame.result,
|
||||||
|
attempt.outcome,
|
||||||
|
attempt.rated_at && DateTime.to_iso8601(attempt.rated_at)
|
||||||
|
]
|
||||||
|
end
|
||||||
|
|
||||||
|
defp empty_attempt_row, do: List.duplicate(nil, length(@attempt_columns))
|
||||||
|
|
||||||
|
defp csv_field(nil), do: ""
|
||||||
|
|
||||||
|
defp csv_field(value) do
|
||||||
|
value = to_string(value)
|
||||||
|
|
||||||
|
if String.contains?(value, [",", "\"", "\n"]) do
|
||||||
|
~s("#{String.replace(value, "\"", "\"\"")}")
|
||||||
|
else
|
||||||
|
value
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp content_type("csv"), do: "text/csv"
|
||||||
|
defp content_type("json"), do: "application/json"
|
||||||
|
end
|
||||||
@@ -50,7 +50,7 @@ defmodule ChesstrainerWeb.UserSessionController do
|
|||||||
user = Accounts.get_user_by_login_and_password(login, password)
|
user = Accounts.get_user_by_login_and_password(login, password)
|
||||||
|
|
||||||
conn
|
conn
|
||||||
|> put_session(:user_return_to, ~p"/users/settings")
|
|> put_session(:user_return_to, ~p"/users/profile")
|
||||||
|> put_flash(:info, "Password updated successfully!")
|
|> put_flash(:info, "Password updated successfully!")
|
||||||
|> UserAuth.log_in_user(user, user_params)
|
|> UserAuth.log_in_user(user, user_params)
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ defmodule ChesstrainerWeb.EndgameLive.Form do
|
|||||||
alias Chesstrainer.Endgames
|
alias Chesstrainer.Endgames
|
||||||
alias Chesstrainer.Endgames.Endgame
|
alias Chesstrainer.Endgames.Endgame
|
||||||
|
|
||||||
|
import ChesstrainerWeb.Board.BoardComponent
|
||||||
|
|
||||||
@impl true
|
@impl true
|
||||||
def render(assigns) do
|
def render(assigns) do
|
||||||
~H"""
|
~H"""
|
||||||
@@ -73,6 +75,8 @@ defmodule ChesstrainerWeb.EndgameLive.Form do
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<.form for={@form} id="endgame-form" phx-change="validate" phx-submit="save">
|
<.form for={@form} id="endgame-form" phx-change="validate" phx-submit="save">
|
||||||
|
<div class="flex flex-col gap-6 sm:flex-row sm:items-start">
|
||||||
|
<div class="min-w-0 flex-1">
|
||||||
<.input field={@form[:fen]} type="text" label="Fen" disabled={@live_action == :edit} />
|
<.input field={@form[:fen]} type="text" label="Fen" disabled={@live_action == :edit} />
|
||||||
<.input field={@form[:color]} type="text" label="Color" disabled />
|
<.input field={@form[:color]} type="text" label="Color" disabled />
|
||||||
<.input
|
<.input
|
||||||
@@ -93,6 +97,14 @@ defmodule ChesstrainerWeb.EndgameLive.Form do
|
|||||||
]}
|
]}
|
||||||
label="Result"
|
label="Result"
|
||||||
/>
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div :if={@preview_game} id="endgame-preview-board" class="sm:w-64 sm:shrink-0">
|
||||||
|
<span class="mb-1 block text-sm font-medium text-base-content">Current position</span>
|
||||||
|
<.board game={@preview_game} class="w-full mt-2" interactive={false} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<footer>
|
<footer>
|
||||||
<.button phx-disable-with="Saving..." variant="primary">Save Endgame</.button>
|
<.button phx-disable-with="Saving..." variant="primary">Save Endgame</.button>
|
||||||
<.button navigate={return_path(@return_to, @endgame)}>Cancel</.button>
|
<.button navigate={return_path(@return_to, @endgame)}>Cancel</.button>
|
||||||
@@ -119,6 +131,7 @@ defmodule ChesstrainerWeb.EndgameLive.Form do
|
|||||||
socket
|
socket
|
||||||
|> assign(:page_title, "Edit Endgame")
|
|> assign(:page_title, "Edit Endgame")
|
||||||
|> assign(:endgame, endgame)
|
|> assign(:endgame, endgame)
|
||||||
|
|> assign(:preview_game, preview_game(endgame.fen))
|
||||||
|> assign(:selected_themes, endgame.themes)
|
|> assign(:selected_themes, endgame.themes)
|
||||||
|> assign(:theme_query, "")
|
|> assign(:theme_query, "")
|
||||||
|> assign(:theme_results, [])
|
|> assign(:theme_results, [])
|
||||||
@@ -132,6 +145,7 @@ defmodule ChesstrainerWeb.EndgameLive.Form do
|
|||||||
socket
|
socket
|
||||||
|> assign(:page_title, "New Endgame")
|
|> assign(:page_title, "New Endgame")
|
||||||
|> assign(:endgame, endgame)
|
|> assign(:endgame, endgame)
|
||||||
|
|> assign(:preview_game, preview_game(endgame.fen))
|
||||||
|> assign(:selected_themes, [])
|
|> assign(:selected_themes, [])
|
||||||
|> assign(:theme_query, "")
|
|> assign(:theme_query, "")
|
||||||
|> assign(:theme_results, [])
|
|> assign(:theme_results, [])
|
||||||
@@ -171,7 +185,11 @@ defmodule ChesstrainerWeb.EndgameLive.Form do
|
|||||||
|> Endgames.change_endgame(endgame_params)
|
|> Endgames.change_endgame(endgame_params)
|
||||||
|> Ecto.Changeset.put_change(:color, color)
|
|> Ecto.Changeset.put_change(:color, color)
|
||||||
|
|
||||||
{:noreply, assign(socket, form: to_form(changeset, action: :validate))}
|
{:noreply,
|
||||||
|
assign(socket,
|
||||||
|
form: to_form(changeset, action: :validate),
|
||||||
|
preview_game: preview_game(fen)
|
||||||
|
)}
|
||||||
end
|
end
|
||||||
|
|
||||||
def handle_event("save", %{"endgame" => endgame_params}, socket) do
|
def handle_event("save", %{"endgame" => endgame_params}, socket) do
|
||||||
@@ -257,6 +275,22 @@ defmodule ChesstrainerWeb.EndgameLive.Form do
|
|||||||
|
|
||||||
defp rating_display(%Phoenix.HTML.FormField{value: value}), do: value
|
defp rating_display(%Phoenix.HTML.FormField{value: value}), do: value
|
||||||
|
|
||||||
|
# Shows the position as the admin types a FEN; hidden while the FEN is invalid or blank.
|
||||||
|
# Parses directly rather than through Game.game_from_fen/2 so keystrokes never probe a tablebase.
|
||||||
|
defp preview_game(fen) when is_binary(fen) do
|
||||||
|
case Chex.Parser.FEN.parse(fen) do
|
||||||
|
{:ok, game} ->
|
||||||
|
%{board: game.board, orientation: game.active_color, move_from_square: nil}
|
||||||
|
|
||||||
|
_ ->
|
||||||
|
nil
|
||||||
|
end
|
||||||
|
rescue
|
||||||
|
MatchError -> nil
|
||||||
|
end
|
||||||
|
|
||||||
|
defp preview_game(_fen), do: nil
|
||||||
|
|
||||||
defp return_path("index", _endgame), do: ~p"/admin/endgames"
|
defp return_path("index", _endgame), do: ~p"/admin/endgames"
|
||||||
defp return_path("show", endgame), do: ~p"/admin/endgames/#{endgame.id}"
|
defp return_path("show", endgame), do: ~p"/admin/endgames/#{endgame.id}"
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -167,6 +167,12 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
|
|||||||
def handle_event("review_step", %{"index" => index}, socket),
|
def handle_event("review_step", %{"index" => index}, socket),
|
||||||
do: PlayCore.review_step(socket, index)
|
do: PlayCore.review_step(socket, index)
|
||||||
|
|
||||||
|
def handle_event("review_start", _params, socket), do: PlayCore.review_start(socket)
|
||||||
|
|
||||||
|
def handle_event("review_end", _params, socket), do: PlayCore.review_end(socket)
|
||||||
|
|
||||||
|
def handle_event("review_move", params, socket), do: PlayCore.review_move(socket, params)
|
||||||
|
|
||||||
def handle_event("play_best_line", _params, socket), do: PlayCore.play_best_line(socket)
|
def handle_event("play_best_line", _params, socket), do: PlayCore.play_best_line(socket)
|
||||||
|
|
||||||
def handle_event("best_line_move_applied", params, socket),
|
def handle_event("best_line_move_applied", params, socket),
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ defmodule ChesstrainerWeb.EndgameLive.Index do
|
|||||||
phx-submit="endgame_search"
|
phx-submit="endgame_search"
|
||||||
class="mb-6 flex items-end gap-2"
|
class="mb-6 flex items-end gap-2"
|
||||||
>
|
>
|
||||||
<div class="flex-1">
|
<div class="flex-1 [&>div]:mb-0">
|
||||||
<.input
|
<.input
|
||||||
field={@search_form[:query]}
|
field={@search_form[:query]}
|
||||||
type="text"
|
type="text"
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
defmodule ChesstrainerWeb.EndgameLive.Play do
|
defmodule ChesstrainerWeb.EndgameLive.Play do
|
||||||
use ChesstrainerWeb, :live_view
|
use ChesstrainerWeb, :live_view
|
||||||
|
|
||||||
|
alias Chesstrainer.Accounts.Scope
|
||||||
alias Chesstrainer.Endgames
|
alias Chesstrainer.Endgames
|
||||||
alias ChesstrainerWeb.EndgameLive.PlayCore
|
alias ChesstrainerWeb.EndgameLive.PlayCore
|
||||||
alias ChesstrainerWeb.PlayComponents
|
alias ChesstrainerWeb.PlayComponents
|
||||||
@@ -9,15 +10,15 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
|
|||||||
def render(assigns) do
|
def render(assigns) do
|
||||||
~H"""
|
~H"""
|
||||||
<Layouts.app flash={@flash}>
|
<Layouts.app flash={@flash}>
|
||||||
<.header>
|
<header class="flex flex-wrap items-start justify-between gap-4 pb-4">
|
||||||
Play endgame {@endgame.key}
|
<div>
|
||||||
<:subtitle>
|
<h1 class="settings-header">Play endgame {@endgame.key}</h1>
|
||||||
|
<p class="settings-subtitle mt-4">
|
||||||
{@endgame.color |> Atom.to_string() |> String.capitalize()} to move · Rating: {round(
|
{@endgame.color |> Atom.to_string() |> String.capitalize()} to move · Rating: {round(
|
||||||
@endgame.rating
|
@endgame.rating
|
||||||
)} · Attempts: {@endgame.times_attempted ||
|
)} · Attempts: {@endgame.times_attempted ||
|
||||||
0} · Solved: {@endgame.times_solved || 0}<span :if={@user_rating}> · Your rating: {round(
|
0} · Solved: {@endgame.times_solved || 0}
|
||||||
@user_rating
|
</p>
|
||||||
)}</span>
|
|
||||||
<p class="text-xs text-muted flex items-center mt-1">
|
<p class="text-xs text-muted flex items-center mt-1">
|
||||||
<span>FEN: {@endgame.fen}</span>
|
<span>FEN: {@endgame.fen}</span>
|
||||||
<button
|
<button
|
||||||
@@ -30,13 +31,16 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
|
|||||||
<.icon name="hero-document-duplicate" class="w-3.5 h-3.5" />
|
<.icon name="hero-document-duplicate" class="w-3.5 h-3.5" />
|
||||||
</button>
|
</button>
|
||||||
</p>
|
</p>
|
||||||
</:subtitle>
|
</div>
|
||||||
<:actions>
|
<div class="flex flex-none gap-2">
|
||||||
<.button navigate={~p"/endgames"}>
|
<.button :if={Scope.premium?(@current_scope)} navigate={~p"/endgames"}>
|
||||||
<.icon name="hero-arrow-left" /> Back to endgames
|
<.icon name="hero-arrow-left" /> Back to endgames
|
||||||
</.button>
|
</.button>
|
||||||
</:actions>
|
<.button :if={!Scope.premium?(@current_scope)} navigate={~p"/"}>
|
||||||
</.header>
|
<.icon name="hero-arrow-left" /> Back home
|
||||||
|
</.button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
<PlayComponents.play_surface
|
<PlayComponents.play_surface
|
||||||
endgame={@endgame}
|
endgame={@endgame}
|
||||||
@@ -53,6 +57,10 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
|
|||||||
last_grade={@last_grade}
|
last_grade={@last_grade}
|
||||||
awaiting_best_line={@awaiting_best_line}
|
awaiting_best_line={@awaiting_best_line}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<div :if={@user_rating} class="mb-4">
|
||||||
|
<.rating_guide rating={@user_rating} deviation={@user_deviation} />
|
||||||
|
</div>
|
||||||
</Layouts.app>
|
</Layouts.app>
|
||||||
"""
|
"""
|
||||||
end
|
end
|
||||||
@@ -85,6 +93,12 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
|
|||||||
def handle_event("review_step", %{"index" => index}, socket),
|
def handle_event("review_step", %{"index" => index}, socket),
|
||||||
do: PlayCore.review_step(socket, index)
|
do: PlayCore.review_step(socket, index)
|
||||||
|
|
||||||
|
def handle_event("review_start", _params, socket), do: PlayCore.review_start(socket)
|
||||||
|
|
||||||
|
def handle_event("review_end", _params, socket), do: PlayCore.review_end(socket)
|
||||||
|
|
||||||
|
def handle_event("review_move", params, socket), do: PlayCore.review_move(socket, params)
|
||||||
|
|
||||||
def handle_event("play_best_line", _params, socket), do: PlayCore.play_best_line(socket)
|
def handle_event("play_best_line", _params, socket), do: PlayCore.play_best_line(socket)
|
||||||
|
|
||||||
def handle_event("best_line_move_applied", params, socket),
|
def handle_event("best_line_move_applied", params, socket),
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|
|||||||
|> assign(:page_title, Keyword.get(opts, :page_title, "Play endgame"))
|
|> assign(:page_title, Keyword.get(opts, :page_title, "Play endgame"))
|
||||||
|> assign(:endgame, endgame)
|
|> assign(:endgame, endgame)
|
||||||
|> assign_new(:user_rating, fn -> user_rating(socket.assigns.current_scope) end)
|
|> assign_new(:user_rating, fn -> user_rating(socket.assigns.current_scope) end)
|
||||||
|
|> assign_new(:user_deviation, fn -> user_deviation(socket.assigns.current_scope) end)
|
||||||
|> assign(:fen, endgame.fen)
|
|> assign(:fen, endgame.fen)
|
||||||
|> assign(:tablebase, nil)
|
|> assign(:tablebase, nil)
|
||||||
|> assign(:status, :loading)
|
|> assign(:status, :loading)
|
||||||
@@ -46,7 +47,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|
|||||||
|> assign(:review_tablebase, nil)
|
|> assign(:review_tablebase, nil)
|
||||||
|> assign(:review_blocked, nil)
|
|> assign(:review_blocked, nil)
|
||||||
|> assign(:awaiting_best_line, false)
|
|> assign(:awaiting_best_line, false)
|
||||||
|> assign(:pending_best_move, nil)
|
|> assign(:pending_move, nil)
|
||||||
|> assign(:last_san, "None yet")
|
|> assign(:last_san, "None yet")
|
||||||
|> assign(:last_from_to, "None yet")
|
|> assign(:last_from_to, "None yet")
|
||||||
|> assign(:last_grade, nil)
|
|> assign(:last_grade, nil)
|
||||||
@@ -135,7 +136,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|
|||||||
|> assign(:review_tablebase, nil)
|
|> assign(:review_tablebase, nil)
|
||||||
|> assign(:review_blocked, nil)
|
|> assign(:review_blocked, nil)
|
||||||
|> assign(:awaiting_best_line, false)
|
|> assign(:awaiting_best_line, false)
|
||||||
|> assign(:pending_best_move, nil)
|
|> assign(:pending_move, nil)
|
||||||
|> assign(:last_san, "None yet")
|
|> assign(:last_san, "None yet")
|
||||||
|> assign(:last_from_to, "None yet")
|
|> assign(:last_from_to, "None yet")
|
||||||
|> assign(:last_grade, nil)
|
|> assign(:last_grade, nil)
|
||||||
@@ -162,6 +163,10 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|
|||||||
|
|
||||||
def review_next(socket), do: step_review(socket, 1)
|
def review_next(socket), do: step_review(socket, 1)
|
||||||
|
|
||||||
|
def review_start(socket), do: review_step(socket, 0)
|
||||||
|
|
||||||
|
def review_end(socket), do: review_step(socket, length(socket.assigns.line))
|
||||||
|
|
||||||
def review_step(socket, index) do
|
def review_step(socket, index) do
|
||||||
if socket.assigns.reviewing do
|
if socket.assigns.reviewing do
|
||||||
last = length(socket.assigns.line)
|
last = length(socket.assigns.line)
|
||||||
@@ -177,21 +182,41 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|
|||||||
with true <- socket.assigns.reviewing,
|
with true <- socket.assigns.reviewing,
|
||||||
%Tablebase{} = tablebase <- socket.assigns.review_tablebase,
|
%Tablebase{} = tablebase <- socket.assigns.review_tablebase,
|
||||||
%Tablebase.Move{} = move <- pick_best_move(tablebase) do
|
%Tablebase.Move{} = move <- pick_best_move(tablebase) do
|
||||||
# Branch the review line at the current position, then play one best move.
|
play_review_move(socket, move, true)
|
||||||
{:noreply,
|
|
||||||
socket
|
|
||||||
|> assign(:line, Enum.take(socket.assigns.line, socket.assigns.review_index))
|
|
||||||
|> assign(:awaiting_best_line, true)
|
|
||||||
|> assign(:pending_best_move, move)
|
|
||||||
|> push_event("best_line_move", reply_payload(move))}
|
|
||||||
else
|
else
|
||||||
_ -> {:noreply, socket}
|
_ -> {:noreply, socket}
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
Plays one tablebase move from the reviewed position, branching the line.
|
||||||
|
|
||||||
|
The move comes from a `phx-value-uci` on the tablebase table.
|
||||||
|
"""
|
||||||
|
def review_move(socket, %{"uci" => uci}) do
|
||||||
|
with true <- socket.assigns.reviewing,
|
||||||
|
%Tablebase{} = tablebase <- socket.assigns.review_tablebase,
|
||||||
|
%Tablebase.Move{} = move <- find_move_by_uci(tablebase, uci) do
|
||||||
|
play_review_move(socket, move, false)
|
||||||
|
else
|
||||||
|
_ -> {:noreply, socket}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
# Branch the review line at the current position, then ask the board to play
|
||||||
|
# the move; `best_line_move_applied/2` appends it once chess.js confirms it.
|
||||||
|
defp play_review_move(socket, move, best_line?) do
|
||||||
|
{:noreply,
|
||||||
|
socket
|
||||||
|
|> assign(:line, Enum.take(socket.assigns.line, socket.assigns.review_index))
|
||||||
|
|> assign(:awaiting_best_line, true)
|
||||||
|
|> assign(:pending_move, %{move: move, best_line: best_line?})
|
||||||
|
|> push_event("best_line_move", reply_payload(move))}
|
||||||
|
end
|
||||||
|
|
||||||
def best_line_move_applied(socket, %{"fen" => fen}) do
|
def best_line_move_applied(socket, %{"fen" => fen}) do
|
||||||
if socket.assigns.awaiting_best_line do
|
if socket.assigns.awaiting_best_line do
|
||||||
move = socket.assigns.pending_best_move
|
%{move: move, best_line: best_line?} = socket.assigns.pending_move
|
||||||
|
|
||||||
line =
|
line =
|
||||||
socket.assigns.line ++
|
socket.assigns.line ++
|
||||||
@@ -201,7 +226,8 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|
|||||||
san: move.san,
|
san: move.san,
|
||||||
fen_after: fen,
|
fen_after: fen,
|
||||||
grade: nil,
|
grade: nil,
|
||||||
best_line: true
|
analysis: true,
|
||||||
|
best_line: best_line?
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -209,7 +235,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|
|||||||
socket
|
socket
|
||||||
|> assign(:line, line)
|
|> assign(:line, line)
|
||||||
|> assign(:awaiting_best_line, false)
|
|> assign(:awaiting_best_line, false)
|
||||||
|> assign(:pending_best_move, nil)
|
|> assign(:pending_move, nil)
|
||||||
|> set_review_index(length(line))
|
|> set_review_index(length(line))
|
||||||
|
|
||||||
{:noreply, push_review_position(socket)}
|
{:noreply, push_review_position(socket)}
|
||||||
@@ -416,6 +442,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|
|||||||
socket
|
socket
|
||||||
|> assign(:endgame, endgame)
|
|> assign(:endgame, endgame)
|
||||||
|> assign(:user_rating, user.rating)
|
|> assign(:user_rating, user.rating)
|
||||||
|
|> assign(:user_deviation, user.rating_deviation)
|
||||||
|> assign(:last_rating_delta, delta)
|
|> assign(:last_rating_delta, delta)
|
||||||
|
|
||||||
{:skipped, _attempt} ->
|
{:skipped, _attempt} ->
|
||||||
@@ -435,6 +462,9 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|
|||||||
defp user_rating(%{user: %{rating: rating}}), do: rating
|
defp user_rating(%{user: %{rating: rating}}), do: rating
|
||||||
defp user_rating(_), do: nil
|
defp user_rating(_), do: nil
|
||||||
|
|
||||||
|
defp user_deviation(%{user: %{rating_deviation: deviation}}), do: deviation
|
||||||
|
defp user_deviation(_), do: nil
|
||||||
|
|
||||||
defp pick_best_move(tablebase), do: tablebase |> best_moves() |> List.first()
|
defp pick_best_move(tablebase), do: tablebase |> best_moves() |> List.first()
|
||||||
|
|
||||||
defp best_moves(%Tablebase{moves: moves} = tablebase) when is_list(moves) do
|
defp best_moves(%Tablebase{moves: moves} = tablebase) when is_list(moves) do
|
||||||
@@ -489,6 +519,12 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|
|||||||
|
|
||||||
defp find_move(_tablebase, _from, _to, _promotion), do: nil
|
defp find_move(_tablebase, _from, _to, _promotion), do: nil
|
||||||
|
|
||||||
|
defp find_move_by_uci(%Tablebase{moves: moves}, uci) when is_list(moves) do
|
||||||
|
Enum.find(moves, &(&1.uci == uci))
|
||||||
|
end
|
||||||
|
|
||||||
|
defp find_move_by_uci(_tablebase, _uci), do: nil
|
||||||
|
|
||||||
# Compare only the board and side to move: chess.js may normalise the rest
|
# Compare only the board and side to move: chess.js may normalise the rest
|
||||||
# (castling/en-passant/halfmove/fullmove) differently from the stored FEN.
|
# (castling/en-passant/halfmove/fullmove) differently from the stored FEN.
|
||||||
defp same_position?(fen_a, fen_b), do: position_key(fen_a) == position_key(fen_b)
|
defp same_position?(fen_a, fen_b), do: position_key(fen_a) == position_key(fen_b)
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
|
|||||||
|
|
||||||
use ChesstrainerWeb, :live_view
|
use ChesstrainerWeb, :live_view
|
||||||
|
|
||||||
|
alias Chesstrainer.Accounts.Scope
|
||||||
alias Chesstrainer.Puzzles
|
alias Chesstrainer.Puzzles
|
||||||
alias ChesstrainerWeb.EndgameLive.PlayCore
|
alias ChesstrainerWeb.EndgameLive.PlayCore
|
||||||
alias ChesstrainerWeb.PlayComponents
|
alias ChesstrainerWeb.PlayComponents
|
||||||
@@ -31,7 +32,7 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
|
|||||||
<.icon name="hero-x-mark" /> Stop session
|
<.icon name="hero-x-mark" /> Stop session
|
||||||
</.button>
|
</.button>
|
||||||
<.button
|
<.button
|
||||||
:if={premium?(@current_scope)}
|
:if={Scope.premium?(@current_scope)}
|
||||||
id="puzzle-search"
|
id="puzzle-search"
|
||||||
navigate={~p"/endgames"}
|
navigate={~p"/endgames"}
|
||||||
>
|
>
|
||||||
@@ -133,7 +134,7 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
|
|||||||
<div>
|
<div>
|
||||||
<h2 class="text-lg font-semibold">Choose a difficulty</h2>
|
<h2 class="text-lg font-semibold">Choose a difficulty</h2>
|
||||||
<p class="mt-1 text-sm text-muted">
|
<p class="mt-1 text-sm text-muted">
|
||||||
Your rating: {round(@user_rating)} · bands of ±{Puzzles.band_width()}
|
Difficulty bands are ±{Puzzles.band_width()} around your rating.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<.link
|
<.link
|
||||||
@@ -145,6 +146,9 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
|
|||||||
<.icon name="hero-x-mark" class="size-5" />
|
<.icon name="hero-x-mark" class="size-5" />
|
||||||
</.link>
|
</.link>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="mt-4">
|
||||||
|
<.rating_guide rating={@user_rating} deviation={@user_deviation} />
|
||||||
|
</div>
|
||||||
<div class="mt-4 grid gap-2">
|
<div class="mt-4 grid gap-2">
|
||||||
<%= for {difficulty, label, description} <- difficulty_options(@user_rating) do %>
|
<%= for {difficulty, label, description} <- difficulty_options(@user_rating) do %>
|
||||||
<.button
|
<.button
|
||||||
@@ -178,7 +182,8 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
|
|||||||
|> assign(:last_session, nil)
|
|> assign(:last_session, nil)
|
||||||
|> assign(:puzzle_started_mono, nil)
|
|> assign(:puzzle_started_mono, nil)
|
||||||
|> assign(:puzzle_counted, false)
|
|> assign(:puzzle_counted, false)
|
||||||
|> assign(:user_rating, socket.assigns.current_scope.user.rating)}
|
|> assign(:user_rating, socket.assigns.current_scope.user.rating)
|
||||||
|
|> assign(:user_deviation, socket.assigns.current_scope.user.rating_deviation)}
|
||||||
end
|
end
|
||||||
|
|
||||||
@impl true
|
@impl true
|
||||||
@@ -269,6 +274,12 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
|
|||||||
def handle_event("review_step", %{"index" => index}, socket),
|
def handle_event("review_step", %{"index" => index}, socket),
|
||||||
do: PlayCore.review_step(socket, index)
|
do: PlayCore.review_step(socket, index)
|
||||||
|
|
||||||
|
def handle_event("review_start", _params, socket), do: PlayCore.review_start(socket)
|
||||||
|
|
||||||
|
def handle_event("review_end", _params, socket), do: PlayCore.review_end(socket)
|
||||||
|
|
||||||
|
def handle_event("review_move", params, socket), do: PlayCore.review_move(socket, params)
|
||||||
|
|
||||||
def handle_event("play_best_line", _params, socket), do: PlayCore.play_best_line(socket)
|
def handle_event("play_best_line", _params, socket), do: PlayCore.play_best_line(socket)
|
||||||
|
|
||||||
def handle_event("best_line_move_applied", params, socket),
|
def handle_event("best_line_move_applied", params, socket),
|
||||||
@@ -304,9 +315,6 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
|
|||||||
%{user | rating: socket.assigns.user_rating || user.rating}
|
%{user | rating: socket.assigns.user_rating || user.rating}
|
||||||
end
|
end
|
||||||
|
|
||||||
defp premium?(%{user: %{plan: :premium}}), do: true
|
|
||||||
defp premium?(_scope), do: false
|
|
||||||
|
|
||||||
defp summarise(session, rating) do
|
defp summarise(session, rating) do
|
||||||
%{
|
%{
|
||||||
difficulty: session.difficulty,
|
difficulty: session.difficulty,
|
||||||
|
|||||||
@@ -0,0 +1,394 @@
|
|||||||
|
defmodule ChesstrainerWeb.UserLive.Profile do
|
||||||
|
use ChesstrainerWeb, :live_view
|
||||||
|
|
||||||
|
alias Chesstrainer.Accounts
|
||||||
|
alias Chesstrainer.Accounts.Scope
|
||||||
|
alias Chesstrainer.Attempts
|
||||||
|
|
||||||
|
@recent_attempts 25
|
||||||
|
|
||||||
|
@tabs [
|
||||||
|
%{id: :account, label: "Account", path: "/users/profile"},
|
||||||
|
%{id: :settings, label: "Settings", path: "/users/profile/settings"},
|
||||||
|
%{id: :data, label: "Data", path: "/users/profile/data"}
|
||||||
|
]
|
||||||
|
|
||||||
|
@impl true
|
||||||
|
def render(assigns) do
|
||||||
|
~H"""
|
||||||
|
<Layouts.app flash={@flash} current_scope={@current_scope}>
|
||||||
|
<.header>
|
||||||
|
Profile
|
||||||
|
<:subtitle>Manage your account, site settings and training data.</:subtitle>
|
||||||
|
</.header>
|
||||||
|
|
||||||
|
<nav id="profile-tabs" class="flex gap-1 border-b border-base-300" aria-label="Profile sections">
|
||||||
|
<.link
|
||||||
|
:for={tab <- @tabs}
|
||||||
|
id={"profile-tab-#{tab.id}"}
|
||||||
|
patch={tab.path}
|
||||||
|
class={[
|
||||||
|
"border-b-2 -mb-px px-3 py-2 text-sm font-semibold",
|
||||||
|
if(@live_action == tab.id,
|
||||||
|
do: "border-primary text-primary",
|
||||||
|
else: "border-transparent text-base-content/60 hover:text-base-content"
|
||||||
|
)
|
||||||
|
]}
|
||||||
|
aria-current={@live_action == tab.id && "page"}
|
||||||
|
>
|
||||||
|
{tab.label}
|
||||||
|
</.link>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<%= case @live_action do %>
|
||||||
|
<% :account -> %>
|
||||||
|
<section id="profile-summary" class="space-y-2 rounded-lg border border-base-300 p-4">
|
||||||
|
<p class="text-sm text-base-content/60">Signed in as</p>
|
||||||
|
<p class="text-lg font-semibold">{@current_scope.user.username}</p>
|
||||||
|
<p class="text-sm">{@current_scope.user.email}</p>
|
||||||
|
<p class="text-sm text-base-content/60">
|
||||||
|
Rating:
|
||||||
|
<span class="font-semibold text-base-content">{round(@current_scope.user.rating)}</span>
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section id="email-settings" class="space-y-4">
|
||||||
|
<h2 class="settings-header">Change email</h2>
|
||||||
|
<p class="settings-subtitle">We will send a confirmation link to the new address.</p>
|
||||||
|
|
||||||
|
<.form
|
||||||
|
for={@email_form}
|
||||||
|
id="email_form"
|
||||||
|
phx-submit="update_email"
|
||||||
|
phx-change="validate_email"
|
||||||
|
>
|
||||||
|
<.input
|
||||||
|
field={@email_form[:email]}
|
||||||
|
type="email"
|
||||||
|
label="Email"
|
||||||
|
autocomplete="username"
|
||||||
|
spellcheck="false"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<.button variant="primary" phx-disable-with="Changing...">Change Email</.button>
|
||||||
|
</.form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<hr class="my-6 border-base-200" />
|
||||||
|
|
||||||
|
<section id="password-settings" class="space-y-4">
|
||||||
|
<h2 class="settings-header">Change password</h2>
|
||||||
|
<p class="settings-subtitle">Choose a new password for this account.</p>
|
||||||
|
|
||||||
|
<.form
|
||||||
|
for={@password_form}
|
||||||
|
id="password_form"
|
||||||
|
action={~p"/users/update-password"}
|
||||||
|
method="post"
|
||||||
|
phx-change="validate_password"
|
||||||
|
phx-submit="update_password"
|
||||||
|
phx-trigger-action={@trigger_submit}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
name={@password_form[:email].name}
|
||||||
|
type="hidden"
|
||||||
|
id="hidden_user_email"
|
||||||
|
spellcheck="false"
|
||||||
|
value={@current_email}
|
||||||
|
/>
|
||||||
|
<.input
|
||||||
|
field={@password_form[:password]}
|
||||||
|
type="password"
|
||||||
|
label="New password"
|
||||||
|
autocomplete="new-password"
|
||||||
|
spellcheck="false"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<.input
|
||||||
|
field={@password_form[:password_confirmation]}
|
||||||
|
type="password"
|
||||||
|
label="Confirm new password"
|
||||||
|
autocomplete="new-password"
|
||||||
|
spellcheck="false"
|
||||||
|
/>
|
||||||
|
<.button variant="primary" phx-disable-with="Saving...">
|
||||||
|
Save Password
|
||||||
|
</.button>
|
||||||
|
</.form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<hr class="my-6 border-base-200" />
|
||||||
|
|
||||||
|
<section id="delete_account" class="space-y-4">
|
||||||
|
<h2 class="settings-header">Delete account</h2>
|
||||||
|
<p class="settings-subtitle">This action is permanent and cannot be undone.</p>
|
||||||
|
|
||||||
|
<p class="text-sm text-base-content/70">
|
||||||
|
Deleting your account permanently removes your profile, rating and training history.
|
||||||
|
Nothing can be recovered.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<.button
|
||||||
|
id="delete_account_button"
|
||||||
|
variant="danger"
|
||||||
|
phx-click="delete_account"
|
||||||
|
data-confirm="This permanently deletes your account and all of your data. Nothing can be recovered. Are you sure?"
|
||||||
|
>
|
||||||
|
Delete my account
|
||||||
|
</.button>
|
||||||
|
</section>
|
||||||
|
<% :settings -> %>
|
||||||
|
<%!-- Keep section for when board themes are added etc --%>
|
||||||
|
<%!-- <section id="appearance-settings" class="space-y-4 rounded-lg border border-base-300 p-4">
|
||||||
|
<.header>
|
||||||
|
Appearance
|
||||||
|
<:subtitle>Choose how the site looks on this device.</:subtitle>
|
||||||
|
</.header>
|
||||||
|
<Layouts.colour_mode_toggle />
|
||||||
|
</section> --%>
|
||||||
|
|
||||||
|
<section id="membership-settings" class="space-y-2 rounded-lg border border-base-300 p-4">
|
||||||
|
<h2 class="settings-header">Membership</h2>
|
||||||
|
<p class="settings-subtitle">Your current plan.</p>
|
||||||
|
<p class="text-sm">
|
||||||
|
You are on the <strong>{plan_label(@current_scope)}</strong> plan.
|
||||||
|
</p>
|
||||||
|
<p class="text-sm text-base-content/70">
|
||||||
|
Premium membership is not available yet. When it arrives it will add session
|
||||||
|
analytics, weak-theme reports and the full puzzle search.
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<p id="settings-empty-state" class="text-sm text-base-content/60">
|
||||||
|
More site settings will appear here as they become available.
|
||||||
|
</p>
|
||||||
|
<% :data -> %>
|
||||||
|
<section id="training-stats" class="space-y-4 rounded-lg border border-base-300 p-4">
|
||||||
|
<h2 class="settings-header">Progress</h2>
|
||||||
|
<p class="settings-subtitle">Your score and solve history across every puzzle.</p>
|
||||||
|
<dl class="grid grid-cols-2 gap-3 sm:grid-cols-4">
|
||||||
|
<.stat label="Rating" value={round(@current_scope.user.rating)} />
|
||||||
|
<.stat label="Attempts" value={@stats.attempts} />
|
||||||
|
<.stat label="Solved" value={@stats.solved} />
|
||||||
|
<.stat label="Solve rate" value={"#{@stats.solve_rate}%"} />
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section id="data-export" class="space-y-4 rounded-lg border border-base-300 p-4">
|
||||||
|
<h2 class="settings-header">Export your data</h2>
|
||||||
|
<p class="settings-subtitle">Download your profile details and every recorded attempt.</p>
|
||||||
|
<div class="flex flex-wrap gap-3">
|
||||||
|
<.button id="export-csv" href={~p"/users/profile/export/csv"}>
|
||||||
|
<.icon name="hero-arrow-down-tray" class="w-4 h-4" /> Download CSV
|
||||||
|
</.button>
|
||||||
|
<.button id="export-json" href={~p"/users/profile/export/json"}>
|
||||||
|
<.icon name="hero-arrow-down-tray" class="w-4 h-4" /> Download JSON
|
||||||
|
</.button>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section id="attempt-history" class="space-y-4 rounded-lg border border-base-300 p-4">
|
||||||
|
<h2 class="settings-header">Recent attempts</h2>
|
||||||
|
<p class="settings-subtitle">The last {@recent_attempts} puzzles you finished.</p>
|
||||||
|
<table :if={@attempts != []} class="w-full text-left text-sm">
|
||||||
|
<thead class="border-b border-base-300 text-base-content/60">
|
||||||
|
<tr>
|
||||||
|
<th class="py-2">Played</th>
|
||||||
|
<th class="py-2">Puzzle</th>
|
||||||
|
<th class="py-2">Outcome</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr
|
||||||
|
:for={attempt <- @attempts}
|
||||||
|
id={"attempt-#{attempt.id}"}
|
||||||
|
class="border-b border-base-200"
|
||||||
|
>
|
||||||
|
<td class="py-2">{Calendar.strftime(attempt.inserted_at, "%d %b %Y")}</td>
|
||||||
|
<td class="py-2">
|
||||||
|
<.link
|
||||||
|
navigate={~p"/endgames/#{attempt.endgame.public_code}/play"}
|
||||||
|
class="font-semibold"
|
||||||
|
>
|
||||||
|
{attempt.endgame.key}
|
||||||
|
</.link>
|
||||||
|
</td>
|
||||||
|
<td class="py-2 capitalize">{attempt.outcome}</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<p :if={@attempts == []} class="text-sm text-base-content/70">
|
||||||
|
No attempts yet. Play a puzzle to start building your history.
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section id="premium-data" class="space-y-2 rounded-lg border border-base-300 p-4">
|
||||||
|
<h2 class="settings-header">Premium Insights</h2>
|
||||||
|
<p class="settings-subtitle">Deeper training analytics, once Premium is available.</p>
|
||||||
|
<ul class="list-inside list-disc text-sm text-base-content/70">
|
||||||
|
<li>Session-by-session performance</li>
|
||||||
|
<li>Failed puzzles and weak themes</li>
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
<% end %>
|
||||||
|
</Layouts.app>
|
||||||
|
"""
|
||||||
|
end
|
||||||
|
|
||||||
|
@impl true
|
||||||
|
def mount(%{"token" => token}, _session, socket) do
|
||||||
|
socket =
|
||||||
|
case Accounts.update_user_email(socket.assigns.current_scope.user, token) do
|
||||||
|
{:ok, _user} ->
|
||||||
|
put_flash(socket, :info, "Email changed successfully.")
|
||||||
|
|
||||||
|
{:error, _} ->
|
||||||
|
put_flash(socket, :error, "Email change link is invalid or it has expired.")
|
||||||
|
end
|
||||||
|
|
||||||
|
{:ok, push_navigate(socket, to: ~p"/users/profile")}
|
||||||
|
end
|
||||||
|
|
||||||
|
def mount(_params, _session, socket) do
|
||||||
|
{:ok,
|
||||||
|
socket
|
||||||
|
|> assign(:page_title, "Profile")
|
||||||
|
|> assign(:tabs, @tabs)
|
||||||
|
|> assign(:recent_attempts, @recent_attempts)}
|
||||||
|
end
|
||||||
|
|
||||||
|
@impl true
|
||||||
|
def handle_params(_params, _uri, socket) do
|
||||||
|
socket = load_section(socket)
|
||||||
|
|
||||||
|
if socket.assigns.live_action == :account and not sudo_mode?(socket) do
|
||||||
|
{:noreply,
|
||||||
|
socket
|
||||||
|
|> put_flash(:error, "You must re-authenticate to access this page.")
|
||||||
|
|> redirect(to: ~p"/users/log-in")}
|
||||||
|
else
|
||||||
|
{:noreply, socket}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
@impl true
|
||||||
|
def handle_event("validate_email", params, socket) do
|
||||||
|
%{"user" => user_params} = params
|
||||||
|
|
||||||
|
email_form =
|
||||||
|
socket.assigns.current_scope.user
|
||||||
|
|> Accounts.change_user_email(user_params, validate_unique: false)
|
||||||
|
|> Map.put(:action, :validate)
|
||||||
|
|> to_form()
|
||||||
|
|
||||||
|
{:noreply, assign(socket, email_form: email_form)}
|
||||||
|
end
|
||||||
|
|
||||||
|
def handle_event("update_email", params, socket) do
|
||||||
|
%{"user" => user_params} = params
|
||||||
|
user = socket.assigns.current_scope.user
|
||||||
|
true = Accounts.sudo_mode?(user)
|
||||||
|
|
||||||
|
case Accounts.change_user_email(user, user_params) do
|
||||||
|
%{valid?: true} = changeset ->
|
||||||
|
Accounts.deliver_user_update_email_instructions(
|
||||||
|
Ecto.Changeset.apply_action!(changeset, :insert),
|
||||||
|
user.email,
|
||||||
|
&url(~p"/users/settings/confirm-email/#{&1}")
|
||||||
|
)
|
||||||
|
|
||||||
|
info = "A link to confirm your email change has been sent to the new address."
|
||||||
|
{:noreply, socket |> put_flash(:info, info)}
|
||||||
|
|
||||||
|
changeset ->
|
||||||
|
{:noreply, assign(socket, :email_form, to_form(changeset, action: :insert))}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def handle_event("validate_password", params, socket) do
|
||||||
|
%{"user" => user_params} = params
|
||||||
|
|
||||||
|
password_form =
|
||||||
|
socket.assigns.current_scope.user
|
||||||
|
|> Accounts.change_user_password(user_params, hash_password: false)
|
||||||
|
|> Map.put(:action, :validate)
|
||||||
|
|> to_form()
|
||||||
|
|
||||||
|
{:noreply, assign(socket, password_form: password_form)}
|
||||||
|
end
|
||||||
|
|
||||||
|
def handle_event("update_password", params, socket) do
|
||||||
|
%{"user" => user_params} = params
|
||||||
|
user = socket.assigns.current_scope.user
|
||||||
|
true = Accounts.sudo_mode?(user)
|
||||||
|
|
||||||
|
case Accounts.change_user_password(user, user_params) do
|
||||||
|
%{valid?: true} = changeset ->
|
||||||
|
{:noreply, assign(socket, trigger_submit: true, password_form: to_form(changeset))}
|
||||||
|
|
||||||
|
changeset ->
|
||||||
|
{:noreply, assign(socket, password_form: to_form(changeset, action: :insert))}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def handle_event("delete_account", _params, socket) do
|
||||||
|
user = socket.assigns.current_scope.user
|
||||||
|
true = Accounts.sudo_mode?(user)
|
||||||
|
|
||||||
|
{:ok, _user} = Accounts.delete_user(user)
|
||||||
|
|
||||||
|
{:noreply,
|
||||||
|
socket
|
||||||
|
|> put_flash(:info, "Your account has been deleted.")
|
||||||
|
|> redirect(to: ~p"/")}
|
||||||
|
end
|
||||||
|
|
||||||
|
defp load_section(socket) do
|
||||||
|
case socket.assigns.live_action do
|
||||||
|
:account -> assign_account(socket)
|
||||||
|
:data -> assign_data(socket)
|
||||||
|
_ -> socket
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp assign_account(socket) do
|
||||||
|
user = socket.assigns.current_scope.user
|
||||||
|
email_changeset = Accounts.change_user_email(user, %{}, validate_unique: false)
|
||||||
|
password_changeset = Accounts.change_user_password(user, %{}, hash_password: false)
|
||||||
|
|
||||||
|
socket
|
||||||
|
|> assign(:current_email, user.email)
|
||||||
|
|> assign(:email_form, to_form(email_changeset))
|
||||||
|
|> assign(:password_form, to_form(password_changeset))
|
||||||
|
|> assign(:trigger_submit, false)
|
||||||
|
end
|
||||||
|
|
||||||
|
defp assign_data(socket) do
|
||||||
|
user = socket.assigns.current_scope.user
|
||||||
|
stats = Attempts.stats_for_user(user.id)
|
||||||
|
solve_rate = if stats.attempts > 0, do: round(stats.solved * 100 / stats.attempts), else: 0
|
||||||
|
|
||||||
|
socket
|
||||||
|
|> assign(:stats, Map.put(stats, :solve_rate, solve_rate))
|
||||||
|
|> assign(:attempts, Attempts.list_attempts_for_user(user.id, limit: @recent_attempts))
|
||||||
|
end
|
||||||
|
|
||||||
|
defp sudo_mode?(socket) do
|
||||||
|
Accounts.sudo_mode?(socket.assigns.current_scope.user, -10)
|
||||||
|
end
|
||||||
|
|
||||||
|
defp plan_label(scope), do: if(Scope.premium?(scope), do: "Premium", else: "Free")
|
||||||
|
|
||||||
|
attr :label, :string, required: true
|
||||||
|
attr :value, :any, required: true
|
||||||
|
|
||||||
|
defp stat(assigns) do
|
||||||
|
~H"""
|
||||||
|
<div class="rounded-lg border border-base-300 p-3">
|
||||||
|
<dt class="text-xs uppercase tracking-wide text-base-content/60">{@label}</dt>
|
||||||
|
<dd class="text-xl font-semibold">{@value}</dd>
|
||||||
|
</div>
|
||||||
|
"""
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -3,6 +3,7 @@ defmodule ChesstrainerWeb.UserLive.Registration do
|
|||||||
|
|
||||||
alias Chesstrainer.Accounts
|
alias Chesstrainer.Accounts
|
||||||
alias Chesstrainer.Accounts.User
|
alias Chesstrainer.Accounts.User
|
||||||
|
alias Chesstrainer.MailingList
|
||||||
|
|
||||||
@impl true
|
@impl true
|
||||||
def render(assigns) do
|
def render(assigns) do
|
||||||
@@ -56,6 +57,11 @@ defmodule ChesstrainerWeb.UserLive.Registration do
|
|||||||
spellcheck="false"
|
spellcheck="false"
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
|
<.input
|
||||||
|
field={@form[:mailing_list]}
|
||||||
|
type="checkbox"
|
||||||
|
label="Send me occasional endgame tips and site news by email"
|
||||||
|
/>
|
||||||
|
|
||||||
<.button phx-disable-with="Creating account..." variant="primary" class="w-full">
|
<.button phx-disable-with="Creating account..." variant="primary" class="w-full">
|
||||||
Create an account
|
Create an account
|
||||||
@@ -82,6 +88,8 @@ defmodule ChesstrainerWeb.UserLive.Registration do
|
|||||||
def handle_event("save", %{"user" => user_params}, socket) do
|
def handle_event("save", %{"user" => user_params}, socket) do
|
||||||
case Accounts.register_user(user_params) do
|
case Accounts.register_user(user_params) do
|
||||||
{:ok, user} ->
|
{:ok, user} ->
|
||||||
|
if user.mailing_list, do: MailingList.subscribe_user(user)
|
||||||
|
|
||||||
{:ok, _} =
|
{:ok, _} =
|
||||||
Accounts.deliver_user_confirmation_instructions(
|
Accounts.deliver_user_confirmation_instructions(
|
||||||
user,
|
user,
|
||||||
|
|||||||
@@ -1,195 +0,0 @@
|
|||||||
defmodule ChesstrainerWeb.UserLive.Settings do
|
|
||||||
use ChesstrainerWeb, :live_view
|
|
||||||
|
|
||||||
on_mount {ChesstrainerWeb.UserAuth, :require_sudo_mode}
|
|
||||||
|
|
||||||
alias Chesstrainer.Accounts
|
|
||||||
|
|
||||||
@impl true
|
|
||||||
def render(assigns) do
|
|
||||||
~H"""
|
|
||||||
<Layouts.app flash={@flash} current_scope={@current_scope}>
|
|
||||||
<div class="text-center">
|
|
||||||
<.header>
|
|
||||||
Account Settings
|
|
||||||
<:subtitle>Manage your account email address and password settings</:subtitle>
|
|
||||||
</.header>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<.form for={@email_form} id="email_form" phx-submit="update_email" phx-change="validate_email">
|
|
||||||
<.input
|
|
||||||
field={@email_form[:email]}
|
|
||||||
type="email"
|
|
||||||
label="Email"
|
|
||||||
autocomplete="username"
|
|
||||||
spellcheck="false"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
<.button variant="primary" phx-disable-with="Changing...">Change Email</.button>
|
|
||||||
</.form>
|
|
||||||
|
|
||||||
<hr class="my-6 border-base-200" />
|
|
||||||
|
|
||||||
<.form
|
|
||||||
for={@password_form}
|
|
||||||
id="password_form"
|
|
||||||
action={~p"/users/update-password"}
|
|
||||||
method="post"
|
|
||||||
phx-change="validate_password"
|
|
||||||
phx-submit="update_password"
|
|
||||||
phx-trigger-action={@trigger_submit}
|
|
||||||
>
|
|
||||||
<input
|
|
||||||
name={@password_form[:email].name}
|
|
||||||
type="hidden"
|
|
||||||
id="hidden_user_email"
|
|
||||||
spellcheck="false"
|
|
||||||
value={@current_email}
|
|
||||||
/>
|
|
||||||
<.input
|
|
||||||
field={@password_form[:password]}
|
|
||||||
type="password"
|
|
||||||
label="New password"
|
|
||||||
autocomplete="new-password"
|
|
||||||
spellcheck="false"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
<.input
|
|
||||||
field={@password_form[:password_confirmation]}
|
|
||||||
type="password"
|
|
||||||
label="Confirm new password"
|
|
||||||
autocomplete="new-password"
|
|
||||||
spellcheck="false"
|
|
||||||
/>
|
|
||||||
<.button variant="primary" phx-disable-with="Saving...">
|
|
||||||
Save Password
|
|
||||||
</.button>
|
|
||||||
</.form>
|
|
||||||
|
|
||||||
<hr class="my-6 border-base-200" />
|
|
||||||
|
|
||||||
<section id="delete_account" class="space-y-4">
|
|
||||||
<.header>
|
|
||||||
Delete account
|
|
||||||
<:subtitle>This action is permanent and cannot be undone.</:subtitle>
|
|
||||||
</.header>
|
|
||||||
|
|
||||||
<p class="text-sm text-base-content/70">
|
|
||||||
Deleting your account permanently removes your profile, rating and training history.
|
|
||||||
Nothing can be recovered.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<.button
|
|
||||||
id="delete_account_button"
|
|
||||||
variant="danger"
|
|
||||||
phx-click="delete_account"
|
|
||||||
data-confirm="This permanently deletes your account and all of your data. Nothing can be recovered. Are you sure?"
|
|
||||||
>
|
|
||||||
Delete my account
|
|
||||||
</.button>
|
|
||||||
</section>
|
|
||||||
</Layouts.app>
|
|
||||||
"""
|
|
||||||
end
|
|
||||||
|
|
||||||
@impl true
|
|
||||||
def mount(%{"token" => token}, _session, socket) do
|
|
||||||
socket =
|
|
||||||
case Accounts.update_user_email(socket.assigns.current_scope.user, token) do
|
|
||||||
{:ok, _user} ->
|
|
||||||
put_flash(socket, :info, "Email changed successfully.")
|
|
||||||
|
|
||||||
{:error, _} ->
|
|
||||||
put_flash(socket, :error, "Email change link is invalid or it has expired.")
|
|
||||||
end
|
|
||||||
|
|
||||||
{:ok, push_navigate(socket, to: ~p"/users/settings")}
|
|
||||||
end
|
|
||||||
|
|
||||||
def mount(_params, _session, socket) do
|
|
||||||
user = socket.assigns.current_scope.user
|
|
||||||
email_changeset = Accounts.change_user_email(user, %{}, validate_unique: false)
|
|
||||||
password_changeset = Accounts.change_user_password(user, %{}, hash_password: false)
|
|
||||||
|
|
||||||
socket =
|
|
||||||
socket
|
|
||||||
|> assign(:current_email, user.email)
|
|
||||||
|> assign(:email_form, to_form(email_changeset))
|
|
||||||
|> assign(:password_form, to_form(password_changeset))
|
|
||||||
|> assign(:trigger_submit, false)
|
|
||||||
|
|
||||||
{:ok, socket}
|
|
||||||
end
|
|
||||||
|
|
||||||
@impl true
|
|
||||||
def handle_event("validate_email", params, socket) do
|
|
||||||
%{"user" => user_params} = params
|
|
||||||
|
|
||||||
email_form =
|
|
||||||
socket.assigns.current_scope.user
|
|
||||||
|> Accounts.change_user_email(user_params, validate_unique: false)
|
|
||||||
|> Map.put(:action, :validate)
|
|
||||||
|> to_form()
|
|
||||||
|
|
||||||
{:noreply, assign(socket, email_form: email_form)}
|
|
||||||
end
|
|
||||||
|
|
||||||
def handle_event("update_email", params, socket) do
|
|
||||||
%{"user" => user_params} = params
|
|
||||||
user = socket.assigns.current_scope.user
|
|
||||||
true = Accounts.sudo_mode?(user)
|
|
||||||
|
|
||||||
case Accounts.change_user_email(user, user_params) do
|
|
||||||
%{valid?: true} = changeset ->
|
|
||||||
Accounts.deliver_user_update_email_instructions(
|
|
||||||
Ecto.Changeset.apply_action!(changeset, :insert),
|
|
||||||
user.email,
|
|
||||||
&url(~p"/users/settings/confirm-email/#{&1}")
|
|
||||||
)
|
|
||||||
|
|
||||||
info = "A link to confirm your email change has been sent to the new address."
|
|
||||||
{:noreply, socket |> put_flash(:info, info)}
|
|
||||||
|
|
||||||
changeset ->
|
|
||||||
{:noreply, assign(socket, :email_form, to_form(changeset, action: :insert))}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def handle_event("validate_password", params, socket) do
|
|
||||||
%{"user" => user_params} = params
|
|
||||||
|
|
||||||
password_form =
|
|
||||||
socket.assigns.current_scope.user
|
|
||||||
|> Accounts.change_user_password(user_params, hash_password: false)
|
|
||||||
|> Map.put(:action, :validate)
|
|
||||||
|> to_form()
|
|
||||||
|
|
||||||
{:noreply, assign(socket, password_form: password_form)}
|
|
||||||
end
|
|
||||||
|
|
||||||
def handle_event("update_password", params, socket) do
|
|
||||||
%{"user" => user_params} = params
|
|
||||||
user = socket.assigns.current_scope.user
|
|
||||||
true = Accounts.sudo_mode?(user)
|
|
||||||
|
|
||||||
case Accounts.change_user_password(user, user_params) do
|
|
||||||
%{valid?: true} = changeset ->
|
|
||||||
{:noreply, assign(socket, trigger_submit: true, password_form: to_form(changeset))}
|
|
||||||
|
|
||||||
changeset ->
|
|
||||||
{:noreply, assign(socket, password_form: to_form(changeset, action: :insert))}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def handle_event("delete_account", _params, socket) do
|
|
||||||
user = socket.assigns.current_scope.user
|
|
||||||
true = Accounts.sudo_mode?(user)
|
|
||||||
|
|
||||||
{:ok, _user} = Accounts.delete_user(user)
|
|
||||||
|
|
||||||
{:noreply,
|
|
||||||
socket
|
|
||||||
|> put_flash(:info, "Your account has been deleted.")
|
|
||||||
|> redirect(to: ~p"/")}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
defmodule ChesstrainerWeb.Plugs.NoIndex do
|
||||||
|
@moduledoc """
|
||||||
|
Tells crawlers not to index the response.
|
||||||
|
|
||||||
|
Uses the `X-Robots-Tag` header rather than a `<meta name="robots">` tag: it
|
||||||
|
survives redirects and authentication failures, and covers LiveView pages
|
||||||
|
without every template having to assign `:noindex`.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import Plug.Conn
|
||||||
|
|
||||||
|
def init(opts), do: opts
|
||||||
|
|
||||||
|
def call(conn, _opts) do
|
||||||
|
put_resp_header(conn, "x-robots-tag", "noindex, nofollow")
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -17,16 +17,27 @@ defmodule ChesstrainerWeb.Router do
|
|||||||
plug :accepts, ["json"]
|
plug :accepts, ["json"]
|
||||||
end
|
end
|
||||||
|
|
||||||
|
# Crawler files are plain text and XML, so they must not negotiate HTML.
|
||||||
|
pipeline :seo do
|
||||||
|
end
|
||||||
|
|
||||||
|
# Never let search engines index private or authenticated areas.
|
||||||
|
pipeline :noindex do
|
||||||
|
plug ChesstrainerWeb.Plugs.NoIndex
|
||||||
|
end
|
||||||
|
|
||||||
scope "/", ChesstrainerWeb do
|
scope "/", ChesstrainerWeb do
|
||||||
pipe_through :browser
|
pipe_through :browser
|
||||||
|
|
||||||
get "/", PageController, :home
|
get "/", PageController, :home
|
||||||
get "/privacy", PageController, :privacy
|
get "/privacy", PageController, :privacy
|
||||||
get "/terms-conditions", PageController, :terms_conditions
|
get "/terms-conditions", PageController, :terms_conditions
|
||||||
|
post "/mailing-list", MailingListController, :create
|
||||||
|
get "/mailing-list/confirm/:token", MailingListController, :confirm
|
||||||
end
|
end
|
||||||
|
|
||||||
scope "/admin", ChesstrainerWeb do
|
scope "/admin", ChesstrainerWeb do
|
||||||
pipe_through [:browser, :require_admin_user]
|
pipe_through [:browser, :noindex, :require_admin_user]
|
||||||
|
|
||||||
live_session :endgames,
|
live_session :endgames,
|
||||||
on_mount: [{ChesstrainerWeb.UserAuth, :require_admin}] do
|
on_mount: [{ChesstrainerWeb.UserAuth, :require_admin}] do
|
||||||
@@ -68,11 +79,16 @@ defmodule ChesstrainerWeb.Router do
|
|||||||
on_mount: [{ChesstrainerWeb.UserAuth, :require_authenticated}] do
|
on_mount: [{ChesstrainerWeb.UserAuth, :require_authenticated}] do
|
||||||
live "/endgames", EndgameLive.PlayerIndex, :index
|
live "/endgames", EndgameLive.PlayerIndex, :index
|
||||||
live "/train", EndgameLive.Train, :train
|
live "/train", EndgameLive.Train, :train
|
||||||
live "/users/settings", UserLive.Settings, :edit
|
live "/users/profile", UserLive.Profile, :account
|
||||||
live "/users/settings/confirm-email/:token", UserLive.Settings, :confirm_email
|
live "/users/profile/settings", UserLive.Profile, :settings
|
||||||
|
live "/users/profile/data", UserLive.Profile, :data
|
||||||
|
# Legacy settings URL; keep old links and emails working.
|
||||||
|
live "/users/settings", UserLive.Profile, :account
|
||||||
|
live "/users/settings/confirm-email/:token", UserLive.Profile, :confirm_email
|
||||||
end
|
end
|
||||||
|
|
||||||
post "/users/update-password", UserSessionController, :update_password
|
post "/users/update-password", UserSessionController, :update_password
|
||||||
|
get "/users/profile/export/:format", UserDataController, :export
|
||||||
end
|
end
|
||||||
|
|
||||||
scope "/", ChesstrainerWeb do
|
scope "/", ChesstrainerWeb do
|
||||||
@@ -93,4 +109,21 @@ defmodule ChesstrainerWeb.Router do
|
|||||||
post "/users/log-in", UserSessionController, :create
|
post "/users/log-in", UserSessionController, :create
|
||||||
delete "/users/log-out", UserSessionController, :delete
|
delete "/users/log-out", UserSessionController, :delete
|
||||||
end
|
end
|
||||||
|
|
||||||
|
# Crawler files live outside the catch-all so they are real responses, not
|
||||||
|
# the branded 404 page.
|
||||||
|
scope "/", ChesstrainerWeb do
|
||||||
|
pipe_through :seo
|
||||||
|
|
||||||
|
get "/robots.txt", RobotsController, :index
|
||||||
|
get "/sitemap.xml", SitemapController, :index
|
||||||
|
end
|
||||||
|
|
||||||
|
# Keep this last: routes match in definition order. It gives unmatched paths a
|
||||||
|
# branded 404 page with the site chrome instead of Phoenix's bare status page.
|
||||||
|
scope "/", ChesstrainerWeb do
|
||||||
|
pipe_through :browser
|
||||||
|
|
||||||
|
match :*, "/*path", PageController, :not_found
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -283,9 +283,9 @@ defmodule ChesstrainerWeb.UserAuth do
|
|||||||
end
|
end
|
||||||
|
|
||||||
@doc "Returns the path to redirect to after log in."
|
@doc "Returns the path to redirect to after log in."
|
||||||
# the user was already logged in, redirect to settings
|
# the user was already logged in, redirect to their profile
|
||||||
def signed_in_path(%Plug.Conn{assigns: %{current_scope: %Scope{user: %Accounts.User{}}}}) do
|
def signed_in_path(%Plug.Conn{assigns: %{current_scope: %Scope{user: %Accounts.User{}}}}) do
|
||||||
~p"/users/settings"
|
~p"/users/profile"
|
||||||
end
|
end
|
||||||
|
|
||||||
def signed_in_path(_), do: ~p"/"
|
def signed_in_path(_), do: ~p"/"
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
defmodule Chesstrainer.Repo.Migrations.CreateMailingListSubscribers do
|
||||||
|
use Ecto.Migration
|
||||||
|
|
||||||
|
def change do
|
||||||
|
create table(:mailing_list_subscribers, primary_key: false) do
|
||||||
|
add :id, :binary_id, primary_key: true
|
||||||
|
add :email, :citext, null: false
|
||||||
|
add :source, :string, null: false, default: "home"
|
||||||
|
add :confirmed_at, :utc_datetime
|
||||||
|
add :user_id, references(:users, type: :binary_id, on_delete: :delete_all)
|
||||||
|
|
||||||
|
timestamps(type: :utc_datetime)
|
||||||
|
end
|
||||||
|
|
||||||
|
create unique_index(:mailing_list_subscribers, [:email])
|
||||||
|
create index(:mailing_list_subscribers, [:user_id])
|
||||||
|
end
|
||||||
|
end
|
||||||
+55
-15
@@ -19,35 +19,42 @@ alias Chesstrainer.Repo
|
|||||||
alias Chesstrainer.Endgames.Endgame
|
alias Chesstrainer.Endgames.Endgame
|
||||||
alias Chesstrainer.Themes.Theme
|
alias Chesstrainer.Themes.Theme
|
||||||
alias Chesstrainer.Repo.Seeds.Endgames
|
alias Chesstrainer.Repo.Seeds.Endgames
|
||||||
alias Chesstrainer.Repo.Seeds.Themes
|
alias Chesstrainer.Repo.Seeds.Themes, as: SeedThemes
|
||||||
|
|
||||||
now = DateTime.utc_now() |> DateTime.truncate(:second)
|
now = DateTime.utc_now() |> DateTime.truncate(:second)
|
||||||
|
|
||||||
IO.puts("🌱 Seeding basic endgames into DB...")
|
# Seed maps may list `themes: ["Lucena", ...]`. Names are matched to seeded
|
||||||
|
# themes case-insensitively, and names missing from seeds/themes.ex are created.
|
||||||
endgames = Endgames.all()
|
endgames =
|
||||||
|
Enum.map(Endgames.all(), fn endgame ->
|
||||||
Repo.insert_all(
|
{theme_names, attrs} = Map.pop(endgame, :themes, [])
|
||||||
Endgame,
|
fen = Chesstrainer.FEN.normalize(attrs.fen)
|
||||||
Enum.map(endgames, fn endgame ->
|
|
||||||
fen = Chesstrainer.FEN.normalize(endgame.fen)
|
|
||||||
{:ok, key} = Chesstrainer.Key.from_fen(fen)
|
{:ok, key} = Chesstrainer.Key.from_fen(fen)
|
||||||
|
|
||||||
endgame
|
themes =
|
||||||
|
theme_names
|
||||||
|
|> Enum.map(&String.trim/1)
|
||||||
|
|> Enum.reject(&(&1 == ""))
|
||||||
|
|> Enum.uniq_by(&String.downcase/1)
|
||||||
|
|
||||||
|
row =
|
||||||
|
attrs
|
||||||
|> Map.put(:fen, fen)
|
|> Map.put(:fen, fen)
|
||||||
|> Map.put(:id, Ecto.UUID.generate())
|
|> Map.put(:id, Ecto.UUID.generate())
|
||||||
|> Map.put(:public_code, Endgame.generate_public_code())
|
|> Map.put(:public_code, Endgame.generate_public_code())
|
||||||
|> Map.put(:key, key)
|
|> Map.put(:key, key)
|
||||||
|> Map.merge(%{inserted_at: now, updated_at: now})
|
|> Map.merge(%{inserted_at: now, updated_at: now})
|
||||||
end),
|
|
||||||
on_conflict: :nothing
|
|
||||||
)
|
|
||||||
|
|
||||||
IO.puts("✅ Done seeding endgames.")
|
%{fen: fen, themes: themes, row: row}
|
||||||
|
end)
|
||||||
|
|
||||||
IO.puts("🌱 Seeding endgame themes into DB...")
|
IO.puts("🌱 Seeding endgame themes into DB...")
|
||||||
|
|
||||||
theme_names = Themes.all()
|
theme_names =
|
||||||
|
(SeedThemes.all() ++ Enum.flat_map(endgames, & &1.themes))
|
||||||
|
|> Enum.map(&String.trim/1)
|
||||||
|
|> Enum.reject(&(&1 == ""))
|
||||||
|
|> Enum.uniq_by(&String.downcase/1)
|
||||||
|
|
||||||
Repo.insert_all(
|
Repo.insert_all(
|
||||||
Theme,
|
Theme,
|
||||||
@@ -57,4 +64,37 @@ Repo.insert_all(
|
|||||||
on_conflict: :nothing
|
on_conflict: :nothing
|
||||||
)
|
)
|
||||||
|
|
||||||
|
theme_id_by_name =
|
||||||
|
Theme
|
||||||
|
|> Repo.all()
|
||||||
|
|> Enum.filter(&(&1.category == :endgame))
|
||||||
|
|> Map.new(&{String.downcase(&1.name), &1.id})
|
||||||
|
|
||||||
IO.puts("✅ Done seeding endgame themes.")
|
IO.puts("✅ Done seeding endgame themes.")
|
||||||
|
|
||||||
|
IO.puts("🌱 Seeding basic endgames into DB...")
|
||||||
|
|
||||||
|
Repo.insert_all(Endgame, Enum.map(endgames, & &1.row), on_conflict: :nothing)
|
||||||
|
|
||||||
|
endgame_id_by_fen =
|
||||||
|
Endgame
|
||||||
|
|> Repo.all()
|
||||||
|
|> Map.new(&{&1.fen, &1.id})
|
||||||
|
|
||||||
|
links =
|
||||||
|
Enum.flat_map(endgames, fn %{fen: fen, themes: themes} ->
|
||||||
|
endgame_id = Map.fetch!(endgame_id_by_fen, fen)
|
||||||
|
|
||||||
|
Enum.map(themes, fn name ->
|
||||||
|
%{
|
||||||
|
endgame_id: Ecto.UUID.dump!(endgame_id),
|
||||||
|
theme_id: Map.fetch!(theme_id_by_name, String.downcase(name))
|
||||||
|
}
|
||||||
|
end)
|
||||||
|
end)
|
||||||
|
|
||||||
|
if links != [] do
|
||||||
|
Repo.insert_all("endgames_themes", links, on_conflict: :nothing)
|
||||||
|
end
|
||||||
|
|
||||||
|
IO.puts("✅ Done seeding endgames.")
|
||||||
|
|||||||
@@ -6,7 +6,8 @@ defmodule Chesstrainer.Repo.Seeds.Endgames.Win do
|
|||||||
color: :white,
|
color: :white,
|
||||||
message: "Rook vs king endgame",
|
message: "Rook vs king endgame",
|
||||||
notes: "Basic rook endgame",
|
notes: "Basic rook endgame",
|
||||||
result: :win
|
result: :win,
|
||||||
|
themes: ["rook endgame"]
|
||||||
},
|
},
|
||||||
%{
|
%{
|
||||||
fen: "8/8/8/1P4p1/5k2/5p2/P6K/8 b - - 0 0",
|
fen: "8/8/8/1P4p1/5k2/5p2/P6K/8 b - - 0 0",
|
||||||
@@ -22,11 +23,6 @@ defmodule Chesstrainer.Repo.Seeds.Endgames.Win do
|
|||||||
fen: "8/7p/6p1/8/k7/8/2K3P1/8 b - - 0 0",
|
fen: "8/7p/6p1/8/k7/8/2K3P1/8 b - - 0 0",
|
||||||
color: :black,
|
color: :black,
|
||||||
result: :win
|
result: :win
|
||||||
},
|
|
||||||
%{
|
|
||||||
fen: "R7/8/8/6p1/4k3/3rPp1P/8/6K1 b - - 0 1",
|
|
||||||
color: :black,
|
|
||||||
result: :win
|
|
||||||
},
|
},
|
||||||
%{
|
%{
|
||||||
fen: "8/8/7k/8/8/8/5q2/3B2RK b - - 0 1",
|
fen: "8/8/7k/8/8/8/5q2/3B2RK b - - 0 1",
|
||||||
@@ -53,6 +49,66 @@ defmodule Chesstrainer.Repo.Seeds.Endgames.Win do
|
|||||||
color: :white,
|
color: :white,
|
||||||
result: :win
|
result: :win
|
||||||
},
|
},
|
||||||
|
%{
|
||||||
|
fen: "K7/P2k4/8/8/8/8/r7/6R1 w - - 0 1",
|
||||||
|
color: :white,
|
||||||
|
result: :win,
|
||||||
|
themes: ["Lucena"]
|
||||||
|
},
|
||||||
|
%{
|
||||||
|
fen: "6K1/4k1P1/8/8/8/8/2r5/1R6 w - - 0 1",
|
||||||
|
color: :white,
|
||||||
|
result: :win,
|
||||||
|
themes: ["Lucena"]
|
||||||
|
},
|
||||||
|
%{
|
||||||
|
fen: "5K2/3k1P2/8/8/8/8/6r1/5R2 w - - 0 1",
|
||||||
|
color: :white,
|
||||||
|
result: :win,
|
||||||
|
themes: ["Lucena"]
|
||||||
|
},
|
||||||
|
%{
|
||||||
|
fen: "3K4/3P2k1/8/8/8/8/2r5/5R2 w - - 0 1",
|
||||||
|
color: :white,
|
||||||
|
result: :win,
|
||||||
|
themes: ["Lucena"]
|
||||||
|
},
|
||||||
|
%{
|
||||||
|
fen: "2K5/2P1k3/8/8/8/8/1r6/R7 w - - 0 1",
|
||||||
|
color: :white,
|
||||||
|
result: :win,
|
||||||
|
themes: ["Lucena"]
|
||||||
|
},
|
||||||
|
%{
|
||||||
|
fen: "7K/2k4P/8/8/8/8/7r/3R4 w - - 0 1",
|
||||||
|
color: :white,
|
||||||
|
result: :win,
|
||||||
|
themes: ["Lucena"]
|
||||||
|
},
|
||||||
|
%{
|
||||||
|
fen: "7K/3k3P/8/8/8/8/7r/4R3 w - - 0 1",
|
||||||
|
color: :white,
|
||||||
|
result: :win,
|
||||||
|
themes: ["Lucena"]
|
||||||
|
},
|
||||||
|
%{
|
||||||
|
fen: "7K/4k2P/8/8/8/8/7r/5R2 w - - 0 1",
|
||||||
|
color: :white,
|
||||||
|
result: :draw,
|
||||||
|
themes: ["Lucena"]
|
||||||
|
},
|
||||||
|
%{
|
||||||
|
fen: "K7/P4k2/8/8/8/8/r7/4R3 w - - 0 1",
|
||||||
|
color: :white,
|
||||||
|
result: :win,
|
||||||
|
themes: ["Lucena"]
|
||||||
|
},
|
||||||
|
%{
|
||||||
|
fen: "K7/P3k3/8/8/8/8/r7/6R1 w - - 0 1",
|
||||||
|
color: :white,
|
||||||
|
result: :win,
|
||||||
|
themes: ["Lucena"]
|
||||||
|
},
|
||||||
]
|
]
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
defmodule Chesstrainer.Repo.Seeds.Themes do
|
defmodule Chesstrainer.Repo.Seeds.Themes do
|
||||||
|
# Endgame seed maps may also reference themes with `themes: ["Lucena", ...]`;
|
||||||
|
# names missing from this list are created when the seeds run.
|
||||||
def all do
|
def all do
|
||||||
[
|
[
|
||||||
"mate in 2",
|
"mate in 2",
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
# See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file
|
|
||||||
#
|
|
||||||
# To ban all spiders from the entire site uncomment the next two lines:
|
|
||||||
# User-agent: *
|
|
||||||
# Disallow: /
|
|
||||||
@@ -583,6 +583,25 @@ defmodule Chesstrainer.AccountsTest do
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
describe "count_logged_in_users/0" do
|
||||||
|
test "counts distinct users with a valid session token" do
|
||||||
|
user = user_fixture()
|
||||||
|
_ = Accounts.generate_user_session_token(user)
|
||||||
|
_ = Accounts.generate_user_session_token(user)
|
||||||
|
_other = Accounts.generate_user_session_token(user_fixture())
|
||||||
|
|
||||||
|
assert Accounts.count_logged_in_users() == 2
|
||||||
|
end
|
||||||
|
|
||||||
|
test "ignores expired session tokens" do
|
||||||
|
user = user_fixture()
|
||||||
|
user_token = Accounts.generate_user_session_token(user)
|
||||||
|
offset_user_token(user_token, -15, :day)
|
||||||
|
|
||||||
|
assert Accounts.count_logged_in_users() == 0
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
describe "delete_user/1" do
|
describe "delete_user/1" do
|
||||||
test "deletes the user and their session tokens" do
|
test "deletes the user and their session tokens" do
|
||||||
user = user_fixture()
|
user = user_fixture()
|
||||||
|
|||||||
@@ -59,6 +59,65 @@ defmodule Chesstrainer.AttemptsTest do
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
describe "stats_for_user/1" do
|
||||||
|
test "summarises attempts, outcomes and distinct puzzles" do
|
||||||
|
user = user_fixture()
|
||||||
|
first = endgame_fixture()
|
||||||
|
second = endgame_fixture()
|
||||||
|
|
||||||
|
{:ok, _} = Attempts.record_attempt(Scope.for_user(user), first, :solved)
|
||||||
|
{:ok, _} = Attempts.record_attempt(Scope.for_user(user), first, :failed)
|
||||||
|
{:ok, _} = Attempts.record_attempt(Scope.for_user(user), second, :solved)
|
||||||
|
|
||||||
|
assert %{attempts: 3, solved: 2, failed: 1, endgames: 2} =
|
||||||
|
Attempts.stats_for_user(user.id)
|
||||||
|
end
|
||||||
|
|
||||||
|
test "returns zeroes for a user with no attempts" do
|
||||||
|
user = user_fixture()
|
||||||
|
|
||||||
|
assert %{attempts: 0, solved: 0, failed: 0, endgames: 0} =
|
||||||
|
Attempts.stats_for_user(user.id)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe "list_attempts_for_user/2" do
|
||||||
|
test "returns the user's attempts newest first with endgames preloaded" do
|
||||||
|
user = user_fixture()
|
||||||
|
first = endgame_fixture(fen: "8/8/3k4/8/8/3K1Q2/8/8 w - - 0 1")
|
||||||
|
second = endgame_fixture(fen: "8/8/3k4/8/8/3K1R2/8/8 w - - 0 1")
|
||||||
|
{:ok, first_attempt} = Attempts.record_attempt(Scope.for_user(user), first, :solved)
|
||||||
|
{:ok, second_attempt} = Attempts.record_attempt(Scope.for_user(user), second, :failed)
|
||||||
|
|
||||||
|
# Attempts within the same second would otherwise tie on `inserted_at`.
|
||||||
|
Repo.update_all(from(a in Attempt, where: a.id == ^first_attempt.id),
|
||||||
|
set: [inserted_at: ~N[2026-01-01 00:00:00]]
|
||||||
|
)
|
||||||
|
|
||||||
|
Repo.update_all(from(a in Attempt, where: a.id == ^second_attempt.id),
|
||||||
|
set: [inserted_at: ~N[2026-01-02 00:00:00]]
|
||||||
|
)
|
||||||
|
|
||||||
|
attempts = Attempts.list_attempts_for_user(user.id)
|
||||||
|
|
||||||
|
assert Enum.map(attempts, & &1.id) == [second_attempt.id, first_attempt.id]
|
||||||
|
assert Enum.all?(attempts, &match?(%Chesstrainer.Endgames.Endgame{}, &1.endgame))
|
||||||
|
end
|
||||||
|
|
||||||
|
test "excludes other users and honours the limit" do
|
||||||
|
user = user_fixture()
|
||||||
|
other = user_fixture()
|
||||||
|
endgame = endgame_fixture()
|
||||||
|
|
||||||
|
{:ok, _} = Attempts.record_attempt(Scope.for_user(user), endgame, :solved)
|
||||||
|
{:ok, _} = Attempts.record_attempt(Scope.for_user(user), endgame, :failed)
|
||||||
|
{:ok, _} = Attempts.record_attempt(Scope.for_user(other), endgame, :solved)
|
||||||
|
|
||||||
|
assert length(Attempts.list_attempts_for_user(user.id)) == 2
|
||||||
|
assert length(Attempts.list_attempts_for_user(user.id, limit: 1)) == 1
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
describe "cascade" do
|
describe "cascade" do
|
||||||
test "deleting a user removes their attempts" do
|
test "deleting a user removes their attempts" do
|
||||||
user = user_fixture()
|
user = user_fixture()
|
||||||
|
|||||||
@@ -0,0 +1,130 @@
|
|||||||
|
defmodule Chesstrainer.MailingListTest do
|
||||||
|
use Chesstrainer.DataCase, async: true
|
||||||
|
|
||||||
|
import Chesstrainer.AccountsFixtures
|
||||||
|
|
||||||
|
alias Chesstrainer.Accounts
|
||||||
|
alias Chesstrainer.MailingList
|
||||||
|
alias Chesstrainer.MailingList.Subscriber
|
||||||
|
|
||||||
|
describe "subscribe/2" do
|
||||||
|
test "requests confirmation for a new address from the landing page" do
|
||||||
|
assert {:ok, :confirmation_required} = MailingList.subscribe("player@example.com")
|
||||||
|
|
||||||
|
subscriber = Repo.get_by(Subscriber, email: "player@example.com")
|
||||||
|
assert subscriber.source == :home
|
||||||
|
assert subscriber.user_id == nil
|
||||||
|
assert subscriber.confirmed_at == nil
|
||||||
|
assert MailingList.count_confirmed_subscribers() == 0
|
||||||
|
end
|
||||||
|
|
||||||
|
test "trims surrounding whitespace" do
|
||||||
|
assert {:ok, :confirmation_required} = MailingList.subscribe(" player@example.com ")
|
||||||
|
|
||||||
|
assert %Subscriber{email: "player@example.com"} =
|
||||||
|
Repo.get_by(Subscriber, email: "player@example.com")
|
||||||
|
end
|
||||||
|
|
||||||
|
test "asks again instead of duplicating an unconfirmed address" do
|
||||||
|
assert {:ok, :confirmation_required} = MailingList.subscribe("player@example.com")
|
||||||
|
assert {:ok, :confirmation_required} = MailingList.subscribe("Player@Example.com")
|
||||||
|
assert Repo.aggregate(Subscriber, :count) == 1
|
||||||
|
end
|
||||||
|
|
||||||
|
test "reports an address that is already confirmed" do
|
||||||
|
{:ok, :confirmation_required} = MailingList.subscribe("player@example.com")
|
||||||
|
{:ok, _subscriber} = MailingList.confirm("player@example.com")
|
||||||
|
|
||||||
|
assert {:ok, :already_subscribed} = MailingList.subscribe("Player@Example.com")
|
||||||
|
assert MailingList.count_confirmed_subscribers() == 1
|
||||||
|
end
|
||||||
|
|
||||||
|
test "rejects an invalid address" do
|
||||||
|
assert {:error, changeset} = MailingList.subscribe("not an email")
|
||||||
|
assert %{email: ["must have the @ sign and no spaces"]} = errors_on(changeset)
|
||||||
|
assert Repo.aggregate(Subscriber, :count) == 0
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe "confirm/1" do
|
||||||
|
test "confirms a pending subscription" do
|
||||||
|
{:ok, :confirmation_required} = MailingList.subscribe("player@example.com")
|
||||||
|
|
||||||
|
assert {:ok, %Subscriber{} = subscriber} = MailingList.confirm("player@example.com")
|
||||||
|
assert subscriber.confirmed_at
|
||||||
|
assert MailingList.count_confirmed_subscribers() == 1
|
||||||
|
end
|
||||||
|
|
||||||
|
test "is idempotent" do
|
||||||
|
{:ok, :confirmation_required} = MailingList.subscribe("player@example.com")
|
||||||
|
{:ok, confirmed} = MailingList.confirm("player@example.com")
|
||||||
|
|
||||||
|
assert {:ok, %Subscriber{confirmed_at: confirmed_at}} =
|
||||||
|
MailingList.confirm("player@example.com")
|
||||||
|
|
||||||
|
assert confirmed_at == confirmed.confirmed_at
|
||||||
|
end
|
||||||
|
|
||||||
|
test "returns not found for an unknown address" do
|
||||||
|
assert {:error, :not_found} = MailingList.confirm("nobody@example.com")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe "subscribe_user/1" do
|
||||||
|
test "links an unconfirmed subscription to the user" do
|
||||||
|
user = user_fixture()
|
||||||
|
|
||||||
|
assert {:ok, %Subscriber{} = subscriber} = MailingList.subscribe_user(user)
|
||||||
|
|
||||||
|
assert subscriber.email == user.email
|
||||||
|
assert subscriber.source == :registration
|
||||||
|
assert subscriber.user_id == user.id
|
||||||
|
assert subscriber.confirmed_at == nil
|
||||||
|
end
|
||||||
|
|
||||||
|
test "upgrades an anonymous subscription with the same address" do
|
||||||
|
user = user_fixture()
|
||||||
|
{:ok, :confirmation_required} = MailingList.subscribe(user.email)
|
||||||
|
|
||||||
|
assert {:ok, %Subscriber{}} = MailingList.subscribe_user(user)
|
||||||
|
|
||||||
|
assert Repo.aggregate(Subscriber, :count) == 1
|
||||||
|
|
||||||
|
subscriber = Repo.get_by(Subscriber, email: user.email)
|
||||||
|
assert subscriber.user_id == user.id
|
||||||
|
assert subscriber.source == :registration
|
||||||
|
end
|
||||||
|
|
||||||
|
test "deleting the user removes their linked subscription" do
|
||||||
|
user = user_fixture()
|
||||||
|
{:ok, _} = MailingList.subscribe_user(user)
|
||||||
|
|
||||||
|
assert {:ok, _} = Accounts.delete_user(user)
|
||||||
|
assert Repo.aggregate(Subscriber, :count) == 0
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe "confirm_user_subscription/1" do
|
||||||
|
test "confirms the subscription linked to the user" do
|
||||||
|
user = user_fixture()
|
||||||
|
{:ok, _} = MailingList.subscribe_user(user)
|
||||||
|
|
||||||
|
MailingList.confirm_user_subscription(user)
|
||||||
|
|
||||||
|
assert %Subscriber{confirmed_at: confirmed_at} =
|
||||||
|
Repo.get_by(Subscriber, user_id: user.id)
|
||||||
|
|
||||||
|
assert confirmed_at
|
||||||
|
end
|
||||||
|
|
||||||
|
test "leaves anonymous subscriptions alone" do
|
||||||
|
{:ok, :confirmation_required} = MailingList.subscribe("player@example.com")
|
||||||
|
user = user_fixture()
|
||||||
|
|
||||||
|
MailingList.confirm_user_subscription(user)
|
||||||
|
|
||||||
|
assert %Subscriber{confirmed_at: nil} =
|
||||||
|
Repo.get_by(Subscriber, email: "player@example.com")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -3,6 +3,8 @@ defmodule Chesstrainer.SeedsTest do
|
|||||||
|
|
||||||
alias Chesstrainer.FEN
|
alias Chesstrainer.FEN
|
||||||
|
|
||||||
|
Code.require_file("../../priv/repo/seeds/endgames/win.ex", __DIR__)
|
||||||
|
Code.require_file("../../priv/repo/seeds/endgames/draw.ex", __DIR__)
|
||||||
Code.require_file("../../priv/repo/seeds/endgames.ex", __DIR__)
|
Code.require_file("../../priv/repo/seeds/endgames.ex", __DIR__)
|
||||||
|
|
||||||
describe "seed endgames" do
|
describe "seed endgames" do
|
||||||
|
|||||||
@@ -59,6 +59,27 @@ defmodule ChesstrainerWeb.AdminGatingTest do
|
|||||||
assert html_response(conn, 200)
|
assert html_response(conn, 200)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
test "admin routes are marked noindex for crawlers", %{conn: conn} do
|
||||||
|
conn = get(conn, ~p"/admin/endgames")
|
||||||
|
|
||||||
|
assert get_resp_header(conn, "x-robots-tag") == ["noindex, nofollow"]
|
||||||
|
|
||||||
|
{:ok, admin} = Accounts.update_user_role(user_fixture(), :admin)
|
||||||
|
|
||||||
|
conn =
|
||||||
|
build_conn()
|
||||||
|
|> log_in_user(admin)
|
||||||
|
|> get(~p"/admin/endgames")
|
||||||
|
|
||||||
|
assert get_resp_header(conn, "x-robots-tag") == ["noindex, nofollow"]
|
||||||
|
end
|
||||||
|
|
||||||
|
test "public pages are not marked noindex", %{conn: conn} do
|
||||||
|
conn = get(conn, ~p"/")
|
||||||
|
|
||||||
|
assert get_resp_header(conn, "x-robots-tag") == []
|
||||||
|
end
|
||||||
|
|
||||||
test "the navbar hides the Admin link from members", %{conn: conn} do
|
test "the navbar hides the Admin link from members", %{conn: conn} do
|
||||||
conn =
|
conn =
|
||||||
conn
|
conn
|
||||||
|
|||||||
@@ -3,8 +3,33 @@ defmodule ChesstrainerWeb.LayoutsTest do
|
|||||||
|
|
||||||
import Phoenix.LiveViewTest
|
import Phoenix.LiveViewTest
|
||||||
|
|
||||||
|
alias Chesstrainer.Accounts.Scope
|
||||||
|
alias Chesstrainer.Accounts.User
|
||||||
alias ChesstrainerWeb.Layouts
|
alias ChesstrainerWeb.Layouts
|
||||||
|
|
||||||
|
describe "navbar/1" do
|
||||||
|
test "signed-in users get a profile menu" do
|
||||||
|
scope = Scope.for_user(%User{username: "alice"})
|
||||||
|
|
||||||
|
html = render_component(&Layouts.navbar/1, %{current_scope: scope})
|
||||||
|
|
||||||
|
assert html =~ "alice"
|
||||||
|
assert html =~ ~s(class="nav-user-menu")
|
||||||
|
assert html =~ ~p"/users/profile"
|
||||||
|
assert html =~ ~p"/users/profile/settings"
|
||||||
|
assert html =~ ~p"/users/profile/data"
|
||||||
|
assert html =~ ~p"/users/log-out"
|
||||||
|
end
|
||||||
|
|
||||||
|
test "guests get log in and register links" do
|
||||||
|
html = render_component(&Layouts.navbar/1, %{current_scope: nil})
|
||||||
|
|
||||||
|
assert html =~ ~p"/users/log-in"
|
||||||
|
assert html =~ ~p"/users/register"
|
||||||
|
refute html =~ ~s(class="nav-user-menu")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
describe "colour_mode_toggle/1" do
|
describe "colour_mode_toggle/1" do
|
||||||
test "renders all three modes as a labelled radiogroup" do
|
test "renders all three modes as a labelled radiogroup" do
|
||||||
html = render_component(&Layouts.colour_mode_toggle/1, %{})
|
html = render_component(&Layouts.colour_mode_toggle/1, %{})
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
defmodule ChesstrainerWeb.RatingComponentsTest do
|
||||||
|
use ChesstrainerWeb.ConnCase, async: true
|
||||||
|
|
||||||
|
import Phoenix.LiveViewTest
|
||||||
|
|
||||||
|
alias ChesstrainerWeb.RatingComponents
|
||||||
|
|
||||||
|
test "shows the rating and the ±2 deviation confidence band" do
|
||||||
|
html = render_component(&RatingComponents.rating_guide/1, %{rating: 1500.0, deviation: 100.0})
|
||||||
|
|
||||||
|
assert html =~ "Your rating: 1500"
|
||||||
|
assert html =~ "likely 1300–1700"
|
||||||
|
assert html =~ "left: 40.0%"
|
||||||
|
assert html =~ "left: 32.0%"
|
||||||
|
assert html =~ "width: 16.0%"
|
||||||
|
assert html =~ "Rating 1500, likely between 1300 and 1700"
|
||||||
|
end
|
||||||
|
|
||||||
|
test "omits the band when the deviation is unknown" do
|
||||||
|
html = render_component(&RatingComponents.rating_guide/1, %{rating: 1500.0, deviation: nil})
|
||||||
|
|
||||||
|
assert html =~ "Your rating: 1500"
|
||||||
|
refute html =~ ~s(id="rating-guide-range")
|
||||||
|
refute html =~ "bg-primary/30"
|
||||||
|
assert html =~ "Rating 1500 on a 500 to 3000 scale"
|
||||||
|
end
|
||||||
|
|
||||||
|
test "clamps the marker to the drawn scale" do
|
||||||
|
low = render_component(&RatingComponents.rating_guide/1, %{rating: 100.0, deviation: nil})
|
||||||
|
high = render_component(&RatingComponents.rating_guide/1, %{rating: 4000.0, deviation: nil})
|
||||||
|
|
||||||
|
assert low =~ "left: 0.0%"
|
||||||
|
assert high =~ "left: 100.0%"
|
||||||
|
end
|
||||||
|
|
||||||
|
test "accepts a custom id for the gauge" do
|
||||||
|
html =
|
||||||
|
render_component(&RatingComponents.rating_guide/1, %{
|
||||||
|
rating: 1500.0,
|
||||||
|
deviation: 100.0,
|
||||||
|
id: "session-rating"
|
||||||
|
})
|
||||||
|
|
||||||
|
assert html =~ ~s(id="session-rating")
|
||||||
|
assert html =~ ~s(id="session-rating-range")
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -1,15 +1,50 @@
|
|||||||
defmodule ChesstrainerWeb.ErrorHTMLTest do
|
defmodule ChesstrainerWeb.ErrorHTMLTest do
|
||||||
use ChesstrainerWeb.ConnCase, async: true
|
use ExUnit.Case, async: true
|
||||||
|
|
||||||
# Bring render_to_string/4 for testing custom views
|
alias Chesstrainer.Accounts.Scope
|
||||||
import Phoenix.Template, only: [render_to_string: 4]
|
alias Chesstrainer.Accounts.User
|
||||||
|
alias Chesstrainer.Branding
|
||||||
|
alias ChesstrainerWeb.ErrorHTML
|
||||||
|
|
||||||
test "renders 404.html" do
|
defp render(template, scope \\ nil) do
|
||||||
assert render_to_string(ChesstrainerWeb.ErrorHTML, "404", "html", []) == "Not Found"
|
Phoenix.Template.render_to_string(ErrorHTML, template, "html", %{current_scope: scope})
|
||||||
end
|
end
|
||||||
|
|
||||||
test "renders 500.html" do
|
test "404 renders a complete document with the site chrome" do
|
||||||
assert render_to_string(ChesstrainerWeb.ErrorHTML, "500", "html", []) ==
|
html = render("404")
|
||||||
"Internal Server Error"
|
|
||||||
|
assert html =~ "<!DOCTYPE html>"
|
||||||
|
assert html =~ "<title>#{Branding.title("Page not found")}</title>"
|
||||||
|
assert html =~ ~s(class="error-code">404</span>)
|
||||||
|
assert html =~ "The page you were looking for moved"
|
||||||
|
assert html =~ ~s(class="site-footer")
|
||||||
|
assert html =~ "/assets/js/marketing.js"
|
||||||
|
refute html =~ ~s(name="csrf-token")
|
||||||
|
end
|
||||||
|
|
||||||
|
test "500 renders a complete document and the support address" do
|
||||||
|
html = render("500")
|
||||||
|
|
||||||
|
assert html =~ "<title>#{Branding.title("Something went wrong")}</title>"
|
||||||
|
assert html =~ ~s(class="error-code">500</span>)
|
||||||
|
assert html =~ "An unexpected error stopped this page"
|
||||||
|
assert html =~ Branding.support_email()
|
||||||
|
assert html =~ ~s(class="site-footer")
|
||||||
|
end
|
||||||
|
|
||||||
|
test "hides the puzzles link from guests and free users" do
|
||||||
|
refute render("404") =~ "Browse puzzles"
|
||||||
|
refute render("404", Scope.for_user(%User{plan: :free})) =~ "Browse puzzles"
|
||||||
|
end
|
||||||
|
|
||||||
|
test "shows the puzzles link to premium users" do
|
||||||
|
html = render("404", Scope.for_user(%User{plan: :premium}))
|
||||||
|
|
||||||
|
assert html =~ "Browse puzzles"
|
||||||
|
assert html =~ ~s(href="/endgames")
|
||||||
|
end
|
||||||
|
|
||||||
|
test "unknown statuses fall back to the plain status message" do
|
||||||
|
assert ErrorHTML.render("503.html", %{}) == "Service Unavailable"
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -0,0 +1,110 @@
|
|||||||
|
defmodule ChesstrainerWeb.MailingListControllerTest do
|
||||||
|
use ChesstrainerWeb.ConnCase, async: true
|
||||||
|
|
||||||
|
alias Chesstrainer.MailingList.Subscriber
|
||||||
|
alias Chesstrainer.Repo
|
||||||
|
|
||||||
|
@salt "mailing_list_confirm"
|
||||||
|
|
||||||
|
describe "POST /mailing-list" do
|
||||||
|
test "sends a confirmation email for a new address", %{conn: conn} do
|
||||||
|
conn = post(conn, ~p"/mailing-list", subscriber: %{email: "player@example.com"})
|
||||||
|
|
||||||
|
assert redirected_to(conn) == "/#mailing-list"
|
||||||
|
assert Phoenix.Flash.get(conn.assigns.flash, :info) =~ "Check your inbox"
|
||||||
|
assert %Subscriber{confirmed_at: nil} = Repo.get_by(Subscriber, email: "player@example.com")
|
||||||
|
|
||||||
|
assert_received {:email, email}
|
||||||
|
assert email.subject == "Confirm your mailing list subscription"
|
||||||
|
assert email.text_body =~ "/mailing-list/confirm/"
|
||||||
|
end
|
||||||
|
|
||||||
|
test "resends confirmation for an address that has not confirmed yet", %{conn: conn} do
|
||||||
|
post(conn, ~p"/mailing-list", subscriber: %{email: "player@example.com"})
|
||||||
|
assert_received {:email, _email}
|
||||||
|
|
||||||
|
conn = post(build_conn(), ~p"/mailing-list", subscriber: %{email: "player@example.com"})
|
||||||
|
|
||||||
|
assert Phoenix.Flash.get(conn.assigns.flash, :info) =~ "Check your inbox"
|
||||||
|
assert_received {:email, _email}
|
||||||
|
assert Repo.aggregate(Subscriber, :count) == 1
|
||||||
|
end
|
||||||
|
|
||||||
|
test "does not email an address that has already confirmed", %{conn: conn} do
|
||||||
|
post(conn, ~p"/mailing-list", subscriber: %{email: "player@example.com"})
|
||||||
|
assert_received {:email, email}
|
||||||
|
get(build_conn(), "/mailing-list/confirm/#{extract_token(email)}")
|
||||||
|
|
||||||
|
conn = post(build_conn(), ~p"/mailing-list", subscriber: %{email: "player@example.com"})
|
||||||
|
|
||||||
|
assert Phoenix.Flash.get(conn.assigns.flash, :info) =~ "already on the mailing list"
|
||||||
|
refute_received {:email, _email}
|
||||||
|
end
|
||||||
|
|
||||||
|
test "reports an invalid address", %{conn: conn} do
|
||||||
|
conn = post(conn, ~p"/mailing-list", subscriber: %{email: "not an email"})
|
||||||
|
|
||||||
|
assert redirected_to(conn) == "/#mailing-list"
|
||||||
|
assert Phoenix.Flash.get(conn.assigns.flash, :error) =~ "valid email address"
|
||||||
|
refute_received {:email, _email}
|
||||||
|
assert Repo.aggregate(Subscriber, :count) == 0
|
||||||
|
end
|
||||||
|
|
||||||
|
test "reports a missing email", %{conn: conn} do
|
||||||
|
conn = post(conn, ~p"/mailing-list", %{})
|
||||||
|
|
||||||
|
assert redirected_to(conn) == "/#mailing-list"
|
||||||
|
assert Phoenix.Flash.get(conn.assigns.flash, :error) =~ "valid email address"
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe "GET /mailing-list/confirm/:token" do
|
||||||
|
test "confirms the subscription from the emailed link", %{conn: conn} do
|
||||||
|
post(conn, ~p"/mailing-list", subscriber: %{email: "player@example.com"})
|
||||||
|
assert_received {:email, email}
|
||||||
|
|
||||||
|
conn = get(build_conn(), "/mailing-list/confirm/#{extract_token(email)}")
|
||||||
|
|
||||||
|
assert Phoenix.Flash.get(conn.assigns.flash, :info) =~ "subscription is confirmed"
|
||||||
|
assert redirected_to(conn) == "/#mailing-list"
|
||||||
|
|
||||||
|
assert %Subscriber{confirmed_at: confirmed_at} =
|
||||||
|
Repo.get_by(Subscriber, email: "player@example.com")
|
||||||
|
|
||||||
|
assert confirmed_at
|
||||||
|
end
|
||||||
|
|
||||||
|
test "rejects an invalid token", %{conn: conn} do
|
||||||
|
conn = get(conn, "/mailing-list/confirm/oops")
|
||||||
|
|
||||||
|
assert Phoenix.Flash.get(conn.assigns.flash, :error) =~ "invalid or has expired"
|
||||||
|
assert redirected_to(conn) == "/#mailing-list"
|
||||||
|
end
|
||||||
|
|
||||||
|
test "rejects an expired token", %{conn: conn} do
|
||||||
|
signed_at = System.system_time(:second) - 8 * 24 * 60 * 60
|
||||||
|
|
||||||
|
token =
|
||||||
|
Phoenix.Token.sign(ChesstrainerWeb.Endpoint, @salt, "player@example.com",
|
||||||
|
signed_at: signed_at
|
||||||
|
)
|
||||||
|
|
||||||
|
conn = get(conn, "/mailing-list/confirm/#{token}")
|
||||||
|
|
||||||
|
assert Phoenix.Flash.get(conn.assigns.flash, :error) =~ "invalid or has expired"
|
||||||
|
end
|
||||||
|
|
||||||
|
test "reports an address that is no longer on the list", %{conn: conn} do
|
||||||
|
token = Phoenix.Token.sign(ChesstrainerWeb.Endpoint, @salt, "nobody@example.com")
|
||||||
|
|
||||||
|
conn = get(conn, "/mailing-list/confirm/#{token}")
|
||||||
|
|
||||||
|
assert Phoenix.Flash.get(conn.assigns.flash, :error) =~ "no longer on the mailing list"
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp extract_token(email) do
|
||||||
|
[_, token] = Regex.run(~r{/mailing-list/confirm/(\S+)}, email.text_body)
|
||||||
|
token
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -4,6 +4,7 @@ defmodule ChesstrainerWeb.PageControllerTest do
|
|||||||
import Chesstrainer.AccountsFixtures
|
import Chesstrainer.AccountsFixtures
|
||||||
import Chesstrainer.EndgamesFixtures
|
import Chesstrainer.EndgamesFixtures
|
||||||
|
|
||||||
|
alias Chesstrainer.Accounts
|
||||||
alias Chesstrainer.Accounts.Scope
|
alias Chesstrainer.Accounts.Scope
|
||||||
alias Chesstrainer.Attempts
|
alias Chesstrainer.Attempts
|
||||||
alias Chesstrainer.Branding
|
alias Chesstrainer.Branding
|
||||||
@@ -158,10 +159,9 @@ defmodule ChesstrainerWeb.PageControllerTest do
|
|||||||
assert html =~ ~s(content="Test Brand")
|
assert html =~ ~s(content="Test Brand")
|
||||||
end
|
end
|
||||||
|
|
||||||
test "hero shows the number of players with at least one attempt", %{conn: conn} do
|
test "hero shows the number of users with a valid session", %{conn: conn} do
|
||||||
user = user_fixture()
|
user = user_fixture()
|
||||||
endgame = endgame_fixture()
|
_token = Accounts.generate_user_session_token(user)
|
||||||
{:ok, _} = Attempts.record_attempt(Scope.for_user(user), endgame, :solved)
|
|
||||||
|
|
||||||
html = conn |> get(~p"/") |> html_response(200)
|
html = conn |> get(~p"/") |> html_response(200)
|
||||||
document = LazyHTML.from_document(html)
|
document = LazyHTML.from_document(html)
|
||||||
@@ -169,22 +169,49 @@ defmodule ChesstrainerWeb.PageControllerTest do
|
|||||||
assert LazyHTML.text(LazyHTML.query(document, ".rating-note strong")) == "1"
|
assert LazyHTML.text(LazyHTML.query(document, ".rating-note strong")) == "1"
|
||||||
end
|
end
|
||||||
|
|
||||||
|
test "hero does not count users who have only trained", %{conn: conn} do
|
||||||
|
user = user_fixture()
|
||||||
|
endgame = endgame_fixture()
|
||||||
|
{:ok, _} = Attempts.record_attempt(Scope.for_user(user), endgame, :solved)
|
||||||
|
|
||||||
|
html = conn |> get(~p"/") |> html_response(200)
|
||||||
|
document = LazyHTML.from_document(html)
|
||||||
|
|
||||||
|
assert LazyHTML.text(LazyHTML.query(document, ".rating-note strong")) == "0"
|
||||||
|
end
|
||||||
|
|
||||||
|
test "renders the mailing list signup form", %{conn: conn} do
|
||||||
|
html = conn |> get(~p"/") |> html_response(200)
|
||||||
|
document = LazyHTML.from_document(html)
|
||||||
|
|
||||||
|
form = LazyHTML.query(document, "#mailing-list-form")
|
||||||
|
assert LazyHTML.attribute(form, "action") == ["/mailing-list"]
|
||||||
|
assert LazyHTML.attribute(form, "method") == ["post"]
|
||||||
|
|
||||||
|
input = LazyHTML.query(document, "#mailing-list-email")
|
||||||
|
assert LazyHTML.attribute(input, "type") == ["email"]
|
||||||
|
assert LazyHTML.attribute(input, "name") == ["subscriber[email]"]
|
||||||
|
|
||||||
|
assert html =~ "Join the list"
|
||||||
|
assert html =~ ~s(name="_csrf_token")
|
||||||
|
end
|
||||||
|
|
||||||
test "guest navbar links to log in and register", %{conn: conn} do
|
test "guest navbar links to log in and register", %{conn: conn} do
|
||||||
html = conn |> get(~p"/") |> html_response(200)
|
html = conn |> get(~p"/") |> html_response(200)
|
||||||
|
|
||||||
assert html =~ ~p"/users/log-in"
|
assert html =~ ~p"/users/log-in"
|
||||||
assert html =~ ~p"/users/register"
|
assert html =~ ~p"/users/register"
|
||||||
refute html =~ ~p"/users/settings"
|
refute html =~ ~p"/users/profile"
|
||||||
end
|
end
|
||||||
|
|
||||||
test "signed-in navbar links to settings and log out", %{conn: conn} do
|
test "signed-in navbar links to the profile and log out", %{conn: conn} do
|
||||||
html =
|
html =
|
||||||
conn
|
conn
|
||||||
|> log_in_user(user_fixture())
|
|> log_in_user(user_fixture())
|
||||||
|> get(~p"/")
|
|> get(~p"/")
|
||||||
|> html_response(200)
|
|> html_response(200)
|
||||||
|
|
||||||
assert html =~ ~p"/users/settings"
|
assert html =~ ~p"/users/profile"
|
||||||
assert html =~ ~p"/users/log-out"
|
assert html =~ ~p"/users/log-out"
|
||||||
refute html =~ ~p"/users/register"
|
refute html =~ ~p"/users/register"
|
||||||
end
|
end
|
||||||
@@ -211,11 +238,10 @@ defmodule ChesstrainerWeb.PageControllerTest do
|
|||||||
|
|
||||||
assert LazyHTML.text(LazyHTML.query(document, ".board-topline")) =~ "White"
|
assert LazyHTML.text(LazyHTML.query(document, ".board-topline")) =~ "White"
|
||||||
assert html =~ "Try today's puzzle"
|
assert html =~ "Try today's puzzle"
|
||||||
assert html =~ "Begin with the basics"
|
|
||||||
assert html =~ "<span>puzzles</span>"
|
assert html =~ "<span>puzzles</span>"
|
||||||
end
|
end
|
||||||
|
|
||||||
test "hero and progress CTAs link to the daily puzzle", %{conn: conn} do
|
test "hero CTA links to the daily puzzle", %{conn: conn} do
|
||||||
curated!()
|
curated!()
|
||||||
daily = DailyPuzzles.today()
|
daily = DailyPuzzles.today()
|
||||||
|
|
||||||
@@ -225,10 +251,6 @@ defmodule ChesstrainerWeb.PageControllerTest do
|
|||||||
|
|
||||||
assert LazyHTML.attribute(LazyHTML.query(document, ".hero-actions a"), "href") == [play_path]
|
assert LazyHTML.attribute(LazyHTML.query(document, ".hero-actions a"), "href") == [play_path]
|
||||||
|
|
||||||
assert LazyHTML.attribute(LazyHTML.query(document, ".progress-banner a"), "href") == [
|
|
||||||
play_path
|
|
||||||
]
|
|
||||||
|
|
||||||
refute html =~ "/endgames//play"
|
refute html =~ "/endgames//play"
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -258,9 +280,34 @@ defmodule ChesstrainerWeb.PageControllerTest do
|
|||||||
assert LazyHTML.attribute(LazyHTML.query(document, ".hero-actions a"), "href") == [
|
assert LazyHTML.attribute(LazyHTML.query(document, ".hero-actions a"), "href") == [
|
||||||
"/endgames"
|
"/endgames"
|
||||||
]
|
]
|
||||||
|
end
|
||||||
|
|
||||||
assert LazyHTML.attribute(LazyHTML.query(document, ".progress-banner a"), "href") == [
|
test "unknown routes render the branded 404 page", %{conn: conn} do
|
||||||
"/endgames"
|
html = conn |> get("/this-page-does-not-exist") |> html_response(404)
|
||||||
]
|
document = LazyHTML.from_document(html)
|
||||||
|
|
||||||
|
assert LazyHTML.text(LazyHTML.query(document, "title")) == Branding.title("Page not found")
|
||||||
|
assert LazyHTML.text(LazyHTML.query(document, ".error-code")) == "404"
|
||||||
|
assert html =~ "The page you were looking for moved"
|
||||||
|
refute html =~ "Browse puzzles"
|
||||||
|
assert html =~ ~s(class="site-footer")
|
||||||
|
assert html =~ "/assets/js/marketing.js"
|
||||||
|
assert html =~ ~s(name="robots")
|
||||||
|
end
|
||||||
|
|
||||||
|
test "premium users see the puzzles link on the 404 page", %{conn: conn} do
|
||||||
|
{:ok, user} =
|
||||||
|
user_fixture()
|
||||||
|
|> Ecto.Changeset.change(plan: :premium)
|
||||||
|
|> Chesstrainer.Repo.update()
|
||||||
|
|
||||||
|
html =
|
||||||
|
conn
|
||||||
|
|> log_in_user(user)
|
||||||
|
|> get("/this-page-does-not-exist")
|
||||||
|
|> html_response(404)
|
||||||
|
|
||||||
|
assert html =~ "Browse puzzles"
|
||||||
|
assert html =~ ~s(href="/endgames")
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
defmodule ChesstrainerWeb.RobotsControllerTest do
|
||||||
|
use ChesstrainerWeb.ConnCase, async: true
|
||||||
|
|
||||||
|
alias ChesstrainerWeb.Endpoint
|
||||||
|
|
||||||
|
describe "GET /robots.txt" do
|
||||||
|
test "allows crawlers and points at the sitemap", %{conn: conn} do
|
||||||
|
body = conn |> get(~p"/robots.txt") |> response(200)
|
||||||
|
|
||||||
|
assert body =~ "User-agent: *"
|
||||||
|
assert body =~ "Allow: /"
|
||||||
|
assert body =~ "Sitemap: #{Endpoint.url()}/sitemap.xml"
|
||||||
|
end
|
||||||
|
|
||||||
|
test "is served as plain text", %{conn: conn} do
|
||||||
|
conn = get(conn, ~p"/robots.txt")
|
||||||
|
|
||||||
|
assert [content_type] = get_resp_header(conn, "content-type")
|
||||||
|
assert content_type =~ "text/plain"
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
defmodule ChesstrainerWeb.SitemapControllerTest do
|
||||||
|
use ChesstrainerWeb.ConnCase, async: true
|
||||||
|
|
||||||
|
alias ChesstrainerWeb.Endpoint
|
||||||
|
|
||||||
|
describe "GET /sitemap.xml" do
|
||||||
|
test "lists only the public marketing pages", %{conn: conn} do
|
||||||
|
body = conn |> get(~p"/sitemap.xml") |> response(200)
|
||||||
|
base_url = Endpoint.url()
|
||||||
|
|
||||||
|
assert body =~ ~s(<?xml version="1.0" encoding="UTF-8"?>)
|
||||||
|
assert body =~ ~s(<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">)
|
||||||
|
assert body =~ "<loc>#{base_url}/</loc>"
|
||||||
|
assert body =~ "<loc>#{base_url}/privacy</loc>"
|
||||||
|
assert body =~ "<loc>#{base_url}/terms-conditions</loc>"
|
||||||
|
assert length(:binary.matches(body, "<url>")) == 3
|
||||||
|
end
|
||||||
|
|
||||||
|
test "is served as XML", %{conn: conn} do
|
||||||
|
conn = get(conn, ~p"/sitemap.xml")
|
||||||
|
|
||||||
|
assert [content_type] = get_resp_header(conn, "content-type")
|
||||||
|
assert content_type =~ "application/xml"
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -5,6 +5,8 @@ defmodule ChesstrainerWeb.UserConfirmationControllerTest do
|
|||||||
|
|
||||||
alias Chesstrainer.Accounts
|
alias Chesstrainer.Accounts
|
||||||
alias Chesstrainer.Accounts.User
|
alias Chesstrainer.Accounts.User
|
||||||
|
alias Chesstrainer.MailingList
|
||||||
|
alias Chesstrainer.MailingList.Subscriber
|
||||||
alias Chesstrainer.Repo
|
alias Chesstrainer.Repo
|
||||||
|
|
||||||
setup do
|
setup do
|
||||||
@@ -33,5 +35,21 @@ defmodule ChesstrainerWeb.UserConfirmationControllerTest do
|
|||||||
|
|
||||||
assert redirected_to(conn) == ~p"/users/register"
|
assert redirected_to(conn) == ~p"/users/register"
|
||||||
end
|
end
|
||||||
|
|
||||||
|
test "confirms a linked mailing-list opt-in", %{conn: conn, user: user} do
|
||||||
|
{:ok, _subscriber} = MailingList.subscribe_user(user)
|
||||||
|
|
||||||
|
token =
|
||||||
|
extract_user_token(fn url ->
|
||||||
|
Accounts.deliver_user_confirmation_instructions(user, url)
|
||||||
|
end)
|
||||||
|
|
||||||
|
get(conn, ~p"/users/confirm/#{token}")
|
||||||
|
|
||||||
|
assert %Subscriber{confirmed_at: confirmed_at} =
|
||||||
|
Repo.get_by(Subscriber, user_id: user.id)
|
||||||
|
|
||||||
|
assert confirmed_at
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -0,0 +1,111 @@
|
|||||||
|
defmodule ChesstrainerWeb.UserDataControllerTest do
|
||||||
|
use ChesstrainerWeb.ConnCase, async: true
|
||||||
|
|
||||||
|
import Chesstrainer.AccountsFixtures
|
||||||
|
import Chesstrainer.EndgamesFixtures
|
||||||
|
|
||||||
|
alias Chesstrainer.Accounts.Scope
|
||||||
|
alias Chesstrainer.Attempts
|
||||||
|
|
||||||
|
setup %{conn: conn} do
|
||||||
|
user = user_fixture()
|
||||||
|
endgame = endgame_fixture()
|
||||||
|
{:ok, _attempt} = Attempts.record_attempt(Scope.for_user(user), endgame, :solved)
|
||||||
|
|
||||||
|
%{conn: log_in_user(conn, user), user: user, endgame: endgame}
|
||||||
|
end
|
||||||
|
|
||||||
|
test "redirects anonymous visitors to log in" do
|
||||||
|
conn = build_conn() |> get(~p"/users/profile/export/csv")
|
||||||
|
|
||||||
|
assert redirected_to(conn) == ~p"/users/log-in"
|
||||||
|
end
|
||||||
|
|
||||||
|
test "downloads the user details and attempts as CSV", %{
|
||||||
|
conn: conn,
|
||||||
|
user: user,
|
||||||
|
endgame: endgame
|
||||||
|
} do
|
||||||
|
conn = get(conn, ~p"/users/profile/export/csv")
|
||||||
|
|
||||||
|
assert response(conn, 200) =~
|
||||||
|
"user_username,user_email,user_rating,user_rating_deviation,user_plan,user_joined_at," <>
|
||||||
|
"played_at,puzzle,public_code,color,result,outcome,rated_at"
|
||||||
|
|
||||||
|
assert response(conn, 200) =~ user.username
|
||||||
|
assert response(conn, 200) =~ user.email
|
||||||
|
assert response(conn, 200) =~ to_string(user.rating)
|
||||||
|
assert response(conn, 200) =~ endgame.key
|
||||||
|
assert response(conn, 200) =~ "solved"
|
||||||
|
|
||||||
|
assert get_resp_header(conn, "content-type") == ["text/csv; charset=utf-8"]
|
||||||
|
|
||||||
|
assert get_resp_header(conn, "content-disposition") == [
|
||||||
|
~s(attachment; filename="lucid-chess-data-#{Date.utc_today()}.csv")
|
||||||
|
]
|
||||||
|
end
|
||||||
|
|
||||||
|
test "downloads the user details and attempts as JSON", %{
|
||||||
|
conn: conn,
|
||||||
|
user: user,
|
||||||
|
endgame: endgame
|
||||||
|
} do
|
||||||
|
conn = get(conn, ~p"/users/profile/export/json")
|
||||||
|
|
||||||
|
body = Jason.decode!(response(conn, 200))
|
||||||
|
|
||||||
|
assert %{
|
||||||
|
"user" => %{
|
||||||
|
"username" => username,
|
||||||
|
"email" => email,
|
||||||
|
"rating" => 1500.0,
|
||||||
|
"rating_deviation" => 350.0,
|
||||||
|
"plan" => "free",
|
||||||
|
"joined_at" => joined_at
|
||||||
|
},
|
||||||
|
"attempts" => [
|
||||||
|
%{
|
||||||
|
"puzzle" => puzzle,
|
||||||
|
"public_code" => public_code,
|
||||||
|
"color" => "white",
|
||||||
|
"result" => "win",
|
||||||
|
"outcome" => "solved",
|
||||||
|
"rated_at" => nil
|
||||||
|
}
|
||||||
|
]
|
||||||
|
} = body
|
||||||
|
|
||||||
|
assert username == user.username
|
||||||
|
assert email == user.email
|
||||||
|
assert is_binary(joined_at)
|
||||||
|
assert puzzle == endgame.key
|
||||||
|
assert public_code == endgame.public_code
|
||||||
|
|
||||||
|
assert get_resp_header(conn, "content-type") == ["application/json; charset=utf-8"]
|
||||||
|
end
|
||||||
|
|
||||||
|
test "includes user details when there are no attempts", %{conn: conn} do
|
||||||
|
user = user_fixture()
|
||||||
|
conn = log_in_user(conn, user) |> get(~p"/users/profile/export/csv")
|
||||||
|
|
||||||
|
[header, row] =
|
||||||
|
conn
|
||||||
|
|> response(200)
|
||||||
|
|> String.trim_trailing("\n")
|
||||||
|
|> String.split("\n")
|
||||||
|
|
||||||
|
assert header =~ "user_username"
|
||||||
|
assert row =~ user.username
|
||||||
|
assert row =~ user.email
|
||||||
|
end
|
||||||
|
|
||||||
|
test "only exports the signed-in user's attempts", %{conn: conn} do
|
||||||
|
other = user_fixture()
|
||||||
|
other_endgame = endgame_fixture(fen: "8/8/3k4/8/8/3K1R2/8/8 w - - 0 1")
|
||||||
|
{:ok, _} = Attempts.record_attempt(Scope.for_user(other), other_endgame, :failed)
|
||||||
|
|
||||||
|
body = conn |> get(~p"/users/profile/export/json") |> response(200)
|
||||||
|
|
||||||
|
refute body =~ other_endgame.public_code
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -22,7 +22,7 @@ defmodule ChesstrainerWeb.UserSessionControllerTest do
|
|||||||
conn = get(conn, ~p"/")
|
conn = get(conn, ~p"/")
|
||||||
response = html_response(conn, 200)
|
response = html_response(conn, 200)
|
||||||
assert response =~ user.username
|
assert response =~ user.username
|
||||||
assert response =~ ~p"/users/settings"
|
assert response =~ ~p"/users/profile"
|
||||||
assert response =~ ~p"/users/log-out"
|
assert response =~ ~p"/users/log-out"
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|||||||
@@ -46,6 +46,37 @@ defmodule ChesstrainerWeb.EndgameLive.FormTest do
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
describe "position preview" do
|
||||||
|
test "shows the board once the FEN is valid", %{conn: conn} do
|
||||||
|
{:ok, view, _html} = live(conn, ~p"/admin/endgames/new")
|
||||||
|
|
||||||
|
refute has_element?(view, "#endgame-preview-board")
|
||||||
|
|
||||||
|
view
|
||||||
|
|> form("#endgame-form", endgame: %{fen: @fen})
|
||||||
|
|> render_change()
|
||||||
|
|
||||||
|
assert has_element?(view, "#endgame-preview-board")
|
||||||
|
assert has_element?(view, "#endgame-preview-board img[src='/images/pieces/white/rook.svg']")
|
||||||
|
end
|
||||||
|
|
||||||
|
test "hides the board when the FEN is invalid", %{conn: conn} do
|
||||||
|
{:ok, view, _html} = live(conn, ~p"/admin/endgames/new")
|
||||||
|
|
||||||
|
view
|
||||||
|
|> form("#endgame-form", endgame: %{fen: @fen})
|
||||||
|
|> render_change()
|
||||||
|
|
||||||
|
assert has_element?(view, "#endgame-preview-board")
|
||||||
|
|
||||||
|
view
|
||||||
|
|> form("#endgame-form", endgame: %{fen: "not a fen"})
|
||||||
|
|> render_change()
|
||||||
|
|
||||||
|
refute has_element?(view, "#endgame-preview-board")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
test "creates an endgame with staged themes", %{conn: conn} do
|
test "creates an endgame with staged themes", %{conn: conn} do
|
||||||
theme = theme_fixture(%{name: "Lucena"})
|
theme = theme_fixture(%{name: "Lucena"})
|
||||||
|
|
||||||
|
|||||||
@@ -80,7 +80,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
|
|||||||
|
|
||||||
# Plays one optimal move, applies the opponent's reply, then a losing move,
|
# Plays one optimal move, applies the opponent's reply, then a losing move,
|
||||||
# leaving a three-ply failed attempt to review.
|
# leaving a three-ply failed attempt to review.
|
||||||
defp seeded_attempt(conn) do
|
defp seeded_attempt(conn, start_moves \\ grading_moves()) do
|
||||||
endgame = endgame_fixture()
|
endgame = endgame_fixture()
|
||||||
|
|
||||||
# The tablebase cache is keyed by position (clocks ignored), so these must
|
# The tablebase cache is keyed by position (clocks ignored), so these must
|
||||||
@@ -91,7 +91,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
|
|||||||
reply = %Tablebase.Move{uci: "e8e7", san: "Ke7", category: :loss, dtz: -3}
|
reply = %Tablebase.Move{uci: "e8e7", san: "Ke7", category: :loss, dtz: -3}
|
||||||
losing_reply = %Tablebase.Move{uci: "e8e7", san: "Ke7", category: :draw, dtz: 0}
|
losing_reply = %Tablebase.Move{uci: "e8e7", san: "Ke7", category: :draw, dtz: 0}
|
||||||
|
|
||||||
seed_tablebase(endgame.fen, moves: grading_moves())
|
seed_tablebase(endgame.fen, moves: start_moves)
|
||||||
seed_tablebase(after_first, category: :loss, moves: [reply])
|
seed_tablebase(after_first, category: :loss, moves: [reply])
|
||||||
seed_tablebase(after_reply, category: :win, moves: grading_moves())
|
seed_tablebase(after_reply, category: :win, moves: grading_moves())
|
||||||
seed_tablebase(after_losing, category: :draw, moves: [losing_reply])
|
seed_tablebase(after_losing, category: :draw, moves: [losing_reply])
|
||||||
@@ -211,6 +211,50 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
describe "back link" do
|
||||||
|
test "points home for an anonymous visitor", %{conn: conn} do
|
||||||
|
endgame = endgame_fixture()
|
||||||
|
seed_tablebase(endgame.fen)
|
||||||
|
|
||||||
|
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
|
||||||
|
|
||||||
|
assert has_element?(view, ~s{a[href="/"]}, "Back home")
|
||||||
|
refute has_element?(view, ~s{a[href="/endgames"]})
|
||||||
|
end
|
||||||
|
|
||||||
|
test "points home for a signed-in free user", %{conn: conn} do
|
||||||
|
user = Chesstrainer.AccountsFixtures.user_fixture()
|
||||||
|
endgame = endgame_fixture()
|
||||||
|
seed_tablebase(endgame.fen)
|
||||||
|
|
||||||
|
{:ok, view, _html} =
|
||||||
|
conn
|
||||||
|
|> log_in_user(user)
|
||||||
|
|> live(~p"/endgames/#{endgame.public_code}/play")
|
||||||
|
|
||||||
|
assert has_element?(view, ~s{a[href="/"]}, "Back home")
|
||||||
|
refute has_element?(view, ~s{a[href="/endgames"]})
|
||||||
|
end
|
||||||
|
|
||||||
|
test "points to the endgame index for a premium user", %{conn: conn} do
|
||||||
|
{:ok, user} =
|
||||||
|
Chesstrainer.AccountsFixtures.user_fixture()
|
||||||
|
|> Ecto.Changeset.change(plan: :premium)
|
||||||
|
|> Repo.update()
|
||||||
|
|
||||||
|
endgame = endgame_fixture()
|
||||||
|
seed_tablebase(endgame.fen)
|
||||||
|
|
||||||
|
{:ok, view, _html} =
|
||||||
|
conn
|
||||||
|
|> log_in_user(user)
|
||||||
|
|> live(~p"/endgames/#{endgame.public_code}/play")
|
||||||
|
|
||||||
|
assert has_element?(view, ~s{a[href="/endgames"]}, "Back to endgames")
|
||||||
|
refute has_element?(view, ~s{a[href="/"]}, "Back home")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
describe "tablebase availability" do
|
describe "tablebase availability" do
|
||||||
test "blocks the attempt when the tablebase is cooling down", %{conn: conn} do
|
test "blocks the attempt when the tablebase is cooling down", %{conn: conn} do
|
||||||
# Six pieces routes to Lichess, so the cooldown applies (five or fewer
|
# Six pieces routes to Lichess, so the cooldown applies (five or fewer
|
||||||
@@ -457,6 +501,22 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
|
|||||||
assert attempt.outcome == :solved
|
assert attempt.outcome == :solved
|
||||||
end
|
end
|
||||||
|
|
||||||
|
test "shows a rating guide with the deviation band", %{conn: conn, user: user} do
|
||||||
|
endgame = endgame_fixture()
|
||||||
|
seed_tablebase(endgame.fen)
|
||||||
|
|
||||||
|
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
|
||||||
|
|
||||||
|
assert has_element?(view, "#rating-guide")
|
||||||
|
|
||||||
|
html = render(view)
|
||||||
|
low = round(user.rating - 2 * user.rating_deviation)
|
||||||
|
high = round(user.rating + 2 * user.rating_deviation)
|
||||||
|
|
||||||
|
assert html =~ "Your rating: #{round(user.rating)}"
|
||||||
|
assert html =~ "likely #{low}–#{high}"
|
||||||
|
end
|
||||||
|
|
||||||
test "records a failed attempt for the signed-in user", %{conn: conn, user: user} do
|
test "records a failed attempt for the signed-in user", %{conn: conn, user: user} do
|
||||||
endgame = endgame_fixture()
|
endgame = endgame_fixture()
|
||||||
seed_tablebase(endgame.fen, moves: grading_moves())
|
seed_tablebase(endgame.fen, moves: grading_moves())
|
||||||
@@ -791,20 +851,35 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
|
|||||||
assert back == fens.after_first
|
assert back == fens.after_first
|
||||||
end
|
end
|
||||||
|
|
||||||
test "clicking a ply jumps to its position", %{conn: conn} do
|
test "hides the result panels and move list while reviewing", %{conn: conn} do
|
||||||
|
{view, _fens} = seeded_attempt(conn)
|
||||||
|
|
||||||
|
view |> element("button", "Review") |> render_click()
|
||||||
|
|
||||||
|
assert has_element?(view, "#best-move-panel")
|
||||||
|
refute has_element?(view, "#move-list")
|
||||||
|
refute render(view) =~ "Failed"
|
||||||
|
refute render(view) =~ "Solved!"
|
||||||
|
end
|
||||||
|
|
||||||
|
test "jumps to the start and end of the reviewed line", %{conn: conn} do
|
||||||
{view, fens} = seeded_attempt(conn)
|
{view, fens} = seeded_attempt(conn)
|
||||||
|
|
||||||
view |> element("button", "Review") |> render_click()
|
view |> element("button", "Review") |> render_click()
|
||||||
|
|
||||||
%{proxy: {ref, _topic, _}} = view
|
%{proxy: {ref, _topic, _}} = view
|
||||||
|
assert_receive {^ref, {:push_event, "review_position", %{fen: after_losing}}}, 100
|
||||||
|
assert after_losing == fens.after_losing
|
||||||
|
|
||||||
# Consume the position pushed on entering review.
|
view |> element("#review-start") |> render_click()
|
||||||
assert_receive {^ref, {:push_event, "review_position", _payload}}, 100
|
|
||||||
|
|
||||||
view |> element("button", "Ke7") |> render_click()
|
assert_receive {^ref, {:push_event, "review_position", %{fen: start}}}, 100
|
||||||
|
assert start == fens.start
|
||||||
|
|
||||||
assert_receive {^ref, {:push_event, "review_position", %{fen: fen}}}, 100
|
view |> element("#review-end") |> render_click()
|
||||||
assert fen == fens.after_reply
|
|
||||||
|
assert_receive {^ref, {:push_event, "review_position", %{fen: at_end}}}, 100
|
||||||
|
assert at_end == fens.after_losing
|
||||||
end
|
end
|
||||||
|
|
||||||
test "try again exits review and starts a fresh attempt", %{conn: conn} do
|
test "try again exits review and starts a fresh attempt", %{conn: conn} do
|
||||||
@@ -857,6 +932,56 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
|
|||||||
assert panel =~ "Played: Qd4"
|
assert panel =~ "Played: Qd4"
|
||||||
end
|
end
|
||||||
|
|
||||||
|
test "groups tablebase moves by outcome during review", %{conn: conn} do
|
||||||
|
start_moves = [
|
||||||
|
%Tablebase.Move{uci: "d1d7", san: "Qd7+", category: :loss, dtz: -1},
|
||||||
|
%Tablebase.Move{uci: "d1d4", san: "Qd4", category: :draw, dtz: 0},
|
||||||
|
%Tablebase.Move{uci: "d1d8", san: "Qd8", category: :win, dtz: 5}
|
||||||
|
]
|
||||||
|
|
||||||
|
{view, _fens} = seeded_attempt(conn, start_moves)
|
||||||
|
|
||||||
|
view |> element("button", "Review") |> render_click()
|
||||||
|
render_hook(view, "review_step", %{"index" => "0"})
|
||||||
|
|
||||||
|
panel = view |> element("#best-move-panel") |> render()
|
||||||
|
|
||||||
|
assert panel =~ ~r/Winning.*Qd7\+.*Drawn.*Qd4.*Losing.*Qd8/s
|
||||||
|
assert panel =~ "DTZ 1"
|
||||||
|
assert panel =~ "DTZ 5"
|
||||||
|
end
|
||||||
|
|
||||||
|
test "clicking a tablebase move plays it from the reviewed position", %{conn: conn} do
|
||||||
|
{view, _fens} = seeded_attempt(conn)
|
||||||
|
|
||||||
|
view |> element("button", "Review") |> render_click()
|
||||||
|
render_hook(view, "review_step", %{"index" => "2"})
|
||||||
|
|
||||||
|
%{proxy: {ref, _topic, _}} = view
|
||||||
|
assert_receive {^ref, {:push_event, "review_position", _}}, 100
|
||||||
|
assert_receive {^ref, {:push_event, "review_position", _}}, 100
|
||||||
|
|
||||||
|
view |> element("#best-move-panel tr[phx-value-uci='d1d5']") |> render_click()
|
||||||
|
|
||||||
|
assert_receive {^ref, {:push_event, "best_line_move", %{from: "d1", to: "d5"}}}, 100
|
||||||
|
|
||||||
|
best_after = "8/8/8/8/8/8/8/6K1 b - - 1 1"
|
||||||
|
|
||||||
|
seed_tablebase(best_after,
|
||||||
|
category: :draw,
|
||||||
|
moves: [%Tablebase.Move{uci: "g1g2", san: "Kg2", category: :draw, dtz: 0}]
|
||||||
|
)
|
||||||
|
|
||||||
|
render_hook(view, "best_line_move_applied", %{"fen" => best_after})
|
||||||
|
|
||||||
|
assert_receive {^ref, {:push_event, "review_position", %{fen: ^best_after}}}, 100
|
||||||
|
|
||||||
|
panel = view |> element("#best-move-panel") |> render()
|
||||||
|
assert panel =~ "Kg2"
|
||||||
|
assert has_element?(view, "button", "Back to game")
|
||||||
|
refute has_element?(view, "#move-list")
|
||||||
|
end
|
||||||
|
|
||||||
test "summarises the failing move and the best alternative", %{conn: conn} do
|
test "summarises the failing move and the best alternative", %{conn: conn} do
|
||||||
{view, _fens} = seeded_attempt(conn)
|
{view, _fens} = seeded_attempt(conn)
|
||||||
|
|
||||||
@@ -864,7 +989,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
|
|||||||
end
|
end
|
||||||
|
|
||||||
test "play best line branches and steps the optimal continuation", %{conn: conn} do
|
test "play best line branches and steps the optimal continuation", %{conn: conn} do
|
||||||
{view, _fens} = seeded_attempt(conn)
|
{view, fens} = seeded_attempt(conn)
|
||||||
|
|
||||||
view |> element("button", "Review") |> render_click()
|
view |> element("button", "Review") |> render_click()
|
||||||
render_hook(view, "review_prev", %{})
|
render_hook(view, "review_prev", %{})
|
||||||
@@ -878,20 +1003,25 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
|
|||||||
assert_receive {^ref, {:push_event, "best_line_move", %{from: "d1", to: "d7"}}}, 100
|
assert_receive {^ref, {:push_event, "best_line_move", %{from: "d1", to: "d7"}}}, 100
|
||||||
|
|
||||||
best_after = "8/8/8/8/8/8/8/8 w - - 2 1"
|
best_after = "8/8/8/8/8/8/8/8 w - - 2 1"
|
||||||
seed_tablebase(best_after, category: :draw, moves: [])
|
|
||||||
|
seed_tablebase(best_after,
|
||||||
|
category: :draw,
|
||||||
|
moves: [%Tablebase.Move{uci: "d8d7", san: "Qd7", category: :draw, dtz: 0}]
|
||||||
|
)
|
||||||
|
|
||||||
render_hook(view, "best_line_move_applied", %{"fen" => best_after})
|
render_hook(view, "best_line_move_applied", %{"fen" => best_after})
|
||||||
|
|
||||||
assert_receive {^ref, {:push_event, "review_position", %{fen: ^best_after}}}, 100
|
assert_receive {^ref, {:push_event, "review_position", %{fen: ^best_after}}}, 100
|
||||||
|
|
||||||
moves = view |> element("#move-list") |> render()
|
panel = view |> element("#best-move-panel") |> render()
|
||||||
refute moves =~ "Qd4"
|
assert panel =~ "Qd7"
|
||||||
assert moves =~ "Qd7+"
|
assert has_element?(view, "button", "Back to game")
|
||||||
assert moves =~ ~s(title="Best line")
|
|
||||||
|
|
||||||
view |> element("button", "Back to game") |> render_click()
|
view |> element("button", "Back to game") |> render_click()
|
||||||
|
|
||||||
moves = view |> element("#move-list") |> render()
|
assert_receive {^ref, {:push_event, "review_position", %{fen: fen}}}, 100
|
||||||
assert moves =~ "Qd4"
|
assert fen == fens.after_losing
|
||||||
|
refute has_element?(view, "button", "Back to game")
|
||||||
end
|
end
|
||||||
|
|
||||||
test "degrades gracefully and reuses played-position snapshots", %{conn: conn} do
|
test "degrades gracefully and reuses played-position snapshots", %{conn: conn} do
|
||||||
|
|||||||
@@ -67,6 +67,6 @@ defmodule ChesstrainerWeb.EndgameLive.PlayerIndexTest do
|
|||||||
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
|
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
|
||||||
|
|
||||||
assert has_element?(view, "#endgame-board")
|
assert has_element?(view, "#endgame-board")
|
||||||
assert has_element?(view, ~s{a[href="/endgames"]})
|
assert has_element?(view, ~s{a[href="/"]})
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -89,6 +89,7 @@ defmodule ChesstrainerWeb.EndgameLive.TrainTest do
|
|||||||
assert has_element?(view, "#close-difficulty[href='/']")
|
assert has_element?(view, "#close-difficulty[href='/']")
|
||||||
assert has_element?(view, "a", "Cancel")
|
assert has_element?(view, "a", "Cancel")
|
||||||
refute has_element?(view, "#puzzle-search")
|
refute has_element?(view, "#puzzle-search")
|
||||||
|
assert has_element?(view, "#rating-guide")
|
||||||
assert render(view) =~ "Choose a difficulty"
|
assert render(view) =~ "Choose a difficulty"
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -147,6 +148,7 @@ defmodule ChesstrainerWeb.EndgameLive.TrainTest do
|
|||||||
assert is_float(assigns.last_rating_delta)
|
assert is_float(assigns.last_rating_delta)
|
||||||
assert assigns.last_rating_delta > 0
|
assert assigns.last_rating_delta > 0
|
||||||
assert assigns.user_rating > 1500.0
|
assert assigns.user_rating > 1500.0
|
||||||
|
assert assigns.user_deviation < 350.0
|
||||||
end
|
end
|
||||||
|
|
||||||
test "loads a different puzzle on next", %{conn: conn} do
|
test "loads a different puzzle on next", %{conn: conn} do
|
||||||
@@ -161,6 +163,22 @@ defmodule ChesstrainerWeb.EndgameLive.TrainTest do
|
|||||||
assert Enum.any?(endgames, &(&1.id == second.id))
|
assert Enum.any?(endgames, &(&1.id == second.id))
|
||||||
end
|
end
|
||||||
|
|
||||||
|
test "keeps next puzzle available while reviewing", %{conn: conn} do
|
||||||
|
{view, endgames} = start_medium_session(conn, 2)
|
||||||
|
first = :sys.get_state(view.pid).socket.assigns.endgame
|
||||||
|
|
||||||
|
solve_current(view)
|
||||||
|
view |> element("button", "Review") |> render_click()
|
||||||
|
|
||||||
|
assert has_element?(view, "#next-puzzle-button")
|
||||||
|
view |> element("#next-puzzle-button") |> render_click()
|
||||||
|
|
||||||
|
second = :sys.get_state(view.pid).socket.assigns.endgame
|
||||||
|
assert second.id != first.id
|
||||||
|
assert Enum.any?(endgames, &(&1.id == second.id))
|
||||||
|
refute :sys.get_state(view.pid).socket.assigns.reviewing
|
||||||
|
end
|
||||||
|
|
||||||
test "a retry does not count toward the average again", %{conn: conn} do
|
test "a retry does not count toward the average again", %{conn: conn} do
|
||||||
{view, [_endgame]} = start_medium_session(conn, 1)
|
{view, [_endgame]} = start_medium_session(conn, 1)
|
||||||
|
|
||||||
|
|||||||
+76
-20
@@ -1,23 +1,79 @@
|
|||||||
defmodule ChesstrainerWeb.UserLive.SettingsTest do
|
defmodule ChesstrainerWeb.UserLive.ProfileTest do
|
||||||
use ChesstrainerWeb.ConnCase, async: true
|
use ChesstrainerWeb.ConnCase, async: true
|
||||||
|
|
||||||
alias Chesstrainer.Accounts
|
alias Chesstrainer.Accounts
|
||||||
|
alias Chesstrainer.Accounts.Scope
|
||||||
|
alias Chesstrainer.Attempts
|
||||||
import Phoenix.LiveViewTest
|
import Phoenix.LiveViewTest
|
||||||
import Chesstrainer.AccountsFixtures
|
import Chesstrainer.AccountsFixtures
|
||||||
|
import Chesstrainer.EndgamesFixtures
|
||||||
|
|
||||||
describe "Settings page" do
|
describe "profile sections" do
|
||||||
test "renders settings page", %{conn: conn} do
|
setup %{conn: conn} do
|
||||||
|
user = user_fixture()
|
||||||
|
%{conn: log_in_user(conn, user), user: user}
|
||||||
|
end
|
||||||
|
|
||||||
|
test "links to the account, settings and data tabs", %{conn: conn} do
|
||||||
|
{:ok, view, _html} = live(conn, ~p"/users/profile")
|
||||||
|
|
||||||
|
assert has_element?(view, "#profile-tabs")
|
||||||
|
assert has_element?(view, ~s{a#profile-tab-account[href="/users/profile"]})
|
||||||
|
assert has_element?(view, ~s{a#profile-tab-settings[href="/users/profile/settings"]})
|
||||||
|
assert has_element?(view, ~s{a#profile-tab-data[href="/users/profile/data"]})
|
||||||
|
end
|
||||||
|
|
||||||
|
test "settings tab shows the current plan", %{conn: conn} do
|
||||||
|
{:ok, view, html} = live(conn, ~p"/users/profile/settings")
|
||||||
|
|
||||||
|
assert has_element?(view, "#membership-settings")
|
||||||
|
assert html =~ "Free"
|
||||||
|
end
|
||||||
|
|
||||||
|
test "data tab shows progress, export links and recent attempts", %{conn: conn, user: user} do
|
||||||
|
endgame = endgame_fixture()
|
||||||
|
{:ok, _attempt} = Attempts.record_attempt(Scope.for_user(user), endgame, :solved)
|
||||||
|
|
||||||
|
{:ok, view, html} = live(conn, ~p"/users/profile/data")
|
||||||
|
|
||||||
|
assert has_element?(view, "#training-stats")
|
||||||
|
assert html =~ "100%"
|
||||||
|
assert html =~ endgame.key
|
||||||
|
assert has_element?(view, ~s{a#export-csv[href="/users/profile/export/csv"]})
|
||||||
|
assert has_element?(view, ~s{a#export-json[href="/users/profile/export/json"]})
|
||||||
|
end
|
||||||
|
|
||||||
|
test "data tab shows an empty state without attempts", %{conn: conn} do
|
||||||
|
{:ok, view, _html} = live(conn, ~p"/users/profile/data")
|
||||||
|
|
||||||
|
assert render(view) =~ "No attempts yet"
|
||||||
|
end
|
||||||
|
|
||||||
|
test "data tab does not require sudo mode", %{conn: conn, user: user} do
|
||||||
|
conn =
|
||||||
|
log_in_user(conn, user,
|
||||||
|
token_authenticated_at: DateTime.add(DateTime.utc_now(:second), -11, :minute)
|
||||||
|
)
|
||||||
|
|
||||||
|
{:ok, view, _html} = live(conn, ~p"/users/profile/data")
|
||||||
|
|
||||||
|
assert has_element?(view, "#training-stats")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe "Account tab" do
|
||||||
|
test "renders the account forms", %{conn: conn} do
|
||||||
{:ok, _lv, html} =
|
{:ok, _lv, html} =
|
||||||
conn
|
conn
|
||||||
|> log_in_user(user_fixture())
|
|> log_in_user(user_fixture())
|
||||||
|> live(~p"/users/settings")
|
|> live(~p"/users/profile")
|
||||||
|
|
||||||
assert html =~ "Change Email"
|
assert html =~ "Change Email"
|
||||||
assert html =~ "Save Password"
|
assert html =~ "Save Password"
|
||||||
end
|
end
|
||||||
|
|
||||||
test "redirects if user is not logged in", %{conn: conn} do
|
test "redirects if user is not logged in", %{conn: conn} do
|
||||||
assert {:error, redirect} = live(conn, ~p"/users/settings")
|
assert {:error, redirect} = live(conn, ~p"/users/profile")
|
||||||
|
|
||||||
assert {:redirect, %{to: path, flash: flash}} = redirect
|
assert {:redirect, %{to: path, flash: flash}} = redirect
|
||||||
assert path == ~p"/users/log-in"
|
assert path == ~p"/users/log-in"
|
||||||
@@ -30,7 +86,7 @@ defmodule ChesstrainerWeb.UserLive.SettingsTest do
|
|||||||
|> log_in_user(user_fixture(),
|
|> log_in_user(user_fixture(),
|
||||||
token_authenticated_at: DateTime.add(DateTime.utc_now(:second), -11, :minute)
|
token_authenticated_at: DateTime.add(DateTime.utc_now(:second), -11, :minute)
|
||||||
)
|
)
|
||||||
|> live(~p"/users/settings")
|
|> live(~p"/users/profile")
|
||||||
|> follow_redirect(conn, ~p"/users/log-in")
|
|> follow_redirect(conn, ~p"/users/log-in")
|
||||||
|
|
||||||
assert conn.resp_body =~ "You must re-authenticate to access this page."
|
assert conn.resp_body =~ "You must re-authenticate to access this page."
|
||||||
@@ -46,7 +102,7 @@ defmodule ChesstrainerWeb.UserLive.SettingsTest do
|
|||||||
test "updates the user email", %{conn: conn, user: user} do
|
test "updates the user email", %{conn: conn, user: user} do
|
||||||
new_email = unique_user_email()
|
new_email = unique_user_email()
|
||||||
|
|
||||||
{:ok, lv, _html} = live(conn, ~p"/users/settings")
|
{:ok, lv, _html} = live(conn, ~p"/users/profile")
|
||||||
|
|
||||||
result =
|
result =
|
||||||
lv
|
lv
|
||||||
@@ -60,7 +116,7 @@ defmodule ChesstrainerWeb.UserLive.SettingsTest do
|
|||||||
end
|
end
|
||||||
|
|
||||||
test "renders errors with invalid data (phx-change)", %{conn: conn} do
|
test "renders errors with invalid data (phx-change)", %{conn: conn} do
|
||||||
{:ok, lv, _html} = live(conn, ~p"/users/settings")
|
{:ok, lv, _html} = live(conn, ~p"/users/profile")
|
||||||
|
|
||||||
result =
|
result =
|
||||||
lv
|
lv
|
||||||
@@ -75,7 +131,7 @@ defmodule ChesstrainerWeb.UserLive.SettingsTest do
|
|||||||
end
|
end
|
||||||
|
|
||||||
test "renders errors with invalid data (phx-submit)", %{conn: conn, user: user} do
|
test "renders errors with invalid data (phx-submit)", %{conn: conn, user: user} do
|
||||||
{:ok, lv, _html} = live(conn, ~p"/users/settings")
|
{:ok, lv, _html} = live(conn, ~p"/users/profile")
|
||||||
|
|
||||||
result =
|
result =
|
||||||
lv
|
lv
|
||||||
@@ -98,7 +154,7 @@ defmodule ChesstrainerWeb.UserLive.SettingsTest do
|
|||||||
test "updates the user password", %{conn: conn, user: user} do
|
test "updates the user password", %{conn: conn, user: user} do
|
||||||
new_password = valid_user_password()
|
new_password = valid_user_password()
|
||||||
|
|
||||||
{:ok, lv, _html} = live(conn, ~p"/users/settings")
|
{:ok, lv, _html} = live(conn, ~p"/users/profile")
|
||||||
|
|
||||||
form =
|
form =
|
||||||
form(lv, "#password_form", %{
|
form(lv, "#password_form", %{
|
||||||
@@ -113,7 +169,7 @@ defmodule ChesstrainerWeb.UserLive.SettingsTest do
|
|||||||
|
|
||||||
new_password_conn = follow_trigger_action(form, conn)
|
new_password_conn = follow_trigger_action(form, conn)
|
||||||
|
|
||||||
assert redirected_to(new_password_conn) == ~p"/users/settings"
|
assert redirected_to(new_password_conn) == ~p"/users/profile"
|
||||||
|
|
||||||
assert get_session(new_password_conn, :user_token) != get_session(conn, :user_token)
|
assert get_session(new_password_conn, :user_token) != get_session(conn, :user_token)
|
||||||
|
|
||||||
@@ -124,7 +180,7 @@ defmodule ChesstrainerWeb.UserLive.SettingsTest do
|
|||||||
end
|
end
|
||||||
|
|
||||||
test "renders errors with invalid data (phx-change)", %{conn: conn} do
|
test "renders errors with invalid data (phx-change)", %{conn: conn} do
|
||||||
{:ok, lv, _html} = live(conn, ~p"/users/settings")
|
{:ok, lv, _html} = live(conn, ~p"/users/profile")
|
||||||
|
|
||||||
result =
|
result =
|
||||||
lv
|
lv
|
||||||
@@ -142,7 +198,7 @@ defmodule ChesstrainerWeb.UserLive.SettingsTest do
|
|||||||
end
|
end
|
||||||
|
|
||||||
test "renders errors with invalid data (phx-submit)", %{conn: conn} do
|
test "renders errors with invalid data (phx-submit)", %{conn: conn} do
|
||||||
{:ok, lv, _html} = live(conn, ~p"/users/settings")
|
{:ok, lv, _html} = live(conn, ~p"/users/profile")
|
||||||
|
|
||||||
result =
|
result =
|
||||||
lv
|
lv
|
||||||
@@ -167,7 +223,7 @@ defmodule ChesstrainerWeb.UserLive.SettingsTest do
|
|||||||
end
|
end
|
||||||
|
|
||||||
test "renders the permanent deletion warning", %{conn: conn} do
|
test "renders the permanent deletion warning", %{conn: conn} do
|
||||||
{:ok, _lv, html} = live(conn, ~p"/users/settings")
|
{:ok, _lv, html} = live(conn, ~p"/users/profile")
|
||||||
|
|
||||||
assert html =~ "Delete account"
|
assert html =~ "Delete account"
|
||||||
assert html =~ "permanent and cannot be undone"
|
assert html =~ "permanent and cannot be undone"
|
||||||
@@ -175,7 +231,7 @@ defmodule ChesstrainerWeb.UserLive.SettingsTest do
|
|||||||
end
|
end
|
||||||
|
|
||||||
test "deletes the user and redirects home", %{conn: conn, user: user} do
|
test "deletes the user and redirects home", %{conn: conn, user: user} do
|
||||||
{:ok, lv, _html} = live(conn, ~p"/users/settings")
|
{:ok, lv, _html} = live(conn, ~p"/users/profile")
|
||||||
|
|
||||||
assert {:error, {:redirect, %{to: "/"}}} =
|
assert {:error, {:redirect, %{to: "/"}}} =
|
||||||
result = lv |> element("#delete_account_button") |> render_click()
|
result = lv |> element("#delete_account_button") |> render_click()
|
||||||
@@ -187,11 +243,11 @@ defmodule ChesstrainerWeb.UserLive.SettingsTest do
|
|||||||
end
|
end
|
||||||
|
|
||||||
test "logs the deleted user out", %{conn: conn, user: user} do
|
test "logs the deleted user out", %{conn: conn, user: user} do
|
||||||
{:ok, lv, _html} = live(conn, ~p"/users/settings")
|
{:ok, lv, _html} = live(conn, ~p"/users/profile")
|
||||||
|
|
||||||
lv |> element("#delete_account_button") |> render_click()
|
lv |> element("#delete_account_button") |> render_click()
|
||||||
|
|
||||||
assert {:error, redirect} = live(conn, ~p"/users/settings")
|
assert {:error, redirect} = live(conn, ~p"/users/profile")
|
||||||
assert {:redirect, %{to: path}} = redirect
|
assert {:redirect, %{to: path}} = redirect
|
||||||
assert path == ~p"/users/log-in"
|
assert path == ~p"/users/log-in"
|
||||||
refute Accounts.get_user_by_email(user.email)
|
refute Accounts.get_user_by_email(user.email)
|
||||||
@@ -215,7 +271,7 @@ defmodule ChesstrainerWeb.UserLive.SettingsTest do
|
|||||||
{:error, redirect} = live(conn, ~p"/users/settings/confirm-email/#{token}")
|
{:error, redirect} = live(conn, ~p"/users/settings/confirm-email/#{token}")
|
||||||
|
|
||||||
assert {:live_redirect, %{to: path, flash: flash}} = redirect
|
assert {:live_redirect, %{to: path, flash: flash}} = redirect
|
||||||
assert path == ~p"/users/settings"
|
assert path == ~p"/users/profile"
|
||||||
assert %{"info" => message} = flash
|
assert %{"info" => message} = flash
|
||||||
assert message == "Email changed successfully."
|
assert message == "Email changed successfully."
|
||||||
refute Accounts.get_user_by_email(user.email)
|
refute Accounts.get_user_by_email(user.email)
|
||||||
@@ -224,7 +280,7 @@ defmodule ChesstrainerWeb.UserLive.SettingsTest do
|
|||||||
# use confirm token again
|
# use confirm token again
|
||||||
{:error, redirect} = live(conn, ~p"/users/settings/confirm-email/#{token}")
|
{:error, redirect} = live(conn, ~p"/users/settings/confirm-email/#{token}")
|
||||||
assert {:live_redirect, %{to: path, flash: flash}} = redirect
|
assert {:live_redirect, %{to: path, flash: flash}} = redirect
|
||||||
assert path == ~p"/users/settings"
|
assert path == ~p"/users/profile"
|
||||||
assert %{"error" => message} = flash
|
assert %{"error" => message} = flash
|
||||||
assert message == "Email change link is invalid or it has expired."
|
assert message == "Email change link is invalid or it has expired."
|
||||||
end
|
end
|
||||||
@@ -232,7 +288,7 @@ defmodule ChesstrainerWeb.UserLive.SettingsTest do
|
|||||||
test "does not update email with invalid token", %{conn: conn, user: user} do
|
test "does not update email with invalid token", %{conn: conn, user: user} do
|
||||||
{:error, redirect} = live(conn, ~p"/users/settings/confirm-email/oops")
|
{:error, redirect} = live(conn, ~p"/users/settings/confirm-email/oops")
|
||||||
assert {:live_redirect, %{to: path, flash: flash}} = redirect
|
assert {:live_redirect, %{to: path, flash: flash}} = redirect
|
||||||
assert path == ~p"/users/settings"
|
assert path == ~p"/users/profile"
|
||||||
assert %{"error" => message} = flash
|
assert %{"error" => message} = flash
|
||||||
assert message == "Email change link is invalid or it has expired."
|
assert message == "Email change link is invalid or it has expired."
|
||||||
assert Accounts.get_user_by_email(user.email)
|
assert Accounts.get_user_by_email(user.email)
|
||||||
@@ -5,6 +5,8 @@ defmodule ChesstrainerWeb.UserLive.RegistrationTest do
|
|||||||
import Chesstrainer.AccountsFixtures
|
import Chesstrainer.AccountsFixtures
|
||||||
import Swoosh.TestAssertions
|
import Swoosh.TestAssertions
|
||||||
|
|
||||||
|
alias Chesstrainer.MailingList.Subscriber
|
||||||
|
|
||||||
describe "Registration page" do
|
describe "Registration page" do
|
||||||
test "renders registration page", %{conn: conn} do
|
test "renders registration page", %{conn: conn} do
|
||||||
{:ok, _lv, html} = live(conn, ~p"/users/register")
|
{:ok, _lv, html} = live(conn, ~p"/users/register")
|
||||||
@@ -34,6 +36,16 @@ defmodule ChesstrainerWeb.UserLive.RegistrationTest do
|
|||||||
assert result =~ "Register"
|
assert result =~ "Register"
|
||||||
assert result =~ "must have the @ sign and no spaces"
|
assert result =~ "must have the @ sign and no spaces"
|
||||||
end
|
end
|
||||||
|
|
||||||
|
test "renders the mailing list opt-in unchecked", %{conn: conn} do
|
||||||
|
{:ok, lv, html} = live(conn, ~p"/users/register")
|
||||||
|
|
||||||
|
assert html =~ "Send me occasional endgame tips and site news by email"
|
||||||
|
|
||||||
|
refute lv
|
||||||
|
|> element("#registration_form input[name=\"user[mailing_list]\"][checked]")
|
||||||
|
|> has_element?()
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
describe "register user" do
|
describe "register user" do
|
||||||
@@ -63,6 +75,45 @@ defmodule ChesstrainerWeb.UserLive.RegistrationTest do
|
|||||||
assert_email_sent(subject: "Confirmation instructions")
|
assert_email_sent(subject: "Confirmation instructions")
|
||||||
end
|
end
|
||||||
|
|
||||||
|
test "subscribes to the mailing list when the box is checked", %{conn: conn} do
|
||||||
|
{:ok, lv, _html} = live(conn, ~p"/users/register")
|
||||||
|
|
||||||
|
email = unique_user_email()
|
||||||
|
|
||||||
|
lv
|
||||||
|
|> form("#registration_form",
|
||||||
|
user: %{
|
||||||
|
"username" => unique_username(),
|
||||||
|
"email" => email,
|
||||||
|
"password" => valid_user_password(),
|
||||||
|
"password_confirmation" => valid_user_password(),
|
||||||
|
"mailing_list" => "true"
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|> render_submit()
|
||||||
|
|
||||||
|
subscriber = Chesstrainer.Repo.get_by(Subscriber, email: email)
|
||||||
|
assert subscriber
|
||||||
|
assert subscriber.confirmed_at == nil
|
||||||
|
end
|
||||||
|
|
||||||
|
test "does not subscribe when the box is unchecked", %{conn: conn} do
|
||||||
|
{:ok, lv, _html} = live(conn, ~p"/users/register")
|
||||||
|
|
||||||
|
lv
|
||||||
|
|> form("#registration_form",
|
||||||
|
user: %{
|
||||||
|
"username" => unique_username(),
|
||||||
|
"email" => unique_user_email(),
|
||||||
|
"password" => valid_user_password(),
|
||||||
|
"password_confirmation" => valid_user_password()
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|> render_submit()
|
||||||
|
|
||||||
|
assert Chesstrainer.Repo.aggregate(Subscriber, :count) == 0
|
||||||
|
end
|
||||||
|
|
||||||
test "renders errors for duplicated email", %{conn: conn} do
|
test "renders errors for duplicated email", %{conn: conn} do
|
||||||
{:ok, lv, _html} = live(conn, ~p"/users/register")
|
{:ok, lv, _html} = live(conn, ~p"/users/register")
|
||||||
|
|
||||||
|
|||||||
@@ -74,13 +74,13 @@ defmodule ChesstrainerWeb.UserAuthTest do
|
|||||||
assert max_age == @remember_me_cookie_max_age
|
assert max_age == @remember_me_cookie_max_age
|
||||||
end
|
end
|
||||||
|
|
||||||
test "redirects to settings when user is already logged in", %{conn: conn, user: user} do
|
test "redirects to the profile when user is already logged in", %{conn: conn, user: user} do
|
||||||
conn =
|
conn =
|
||||||
conn
|
conn
|
||||||
|> assign(:current_scope, Scope.for_user(user))
|
|> assign(:current_scope, Scope.for_user(user))
|
||||||
|> UserAuth.log_in_user(user)
|
|> UserAuth.log_in_user(user)
|
||||||
|
|
||||||
assert redirected_to(conn) == ~p"/users/settings"
|
assert redirected_to(conn) == ~p"/users/profile"
|
||||||
end
|
end
|
||||||
|
|
||||||
test "writes a cookie if remember_me was set in previous session", %{conn: conn, user: user} do
|
test "writes a cookie if remember_me was set in previous session", %{conn: conn, user: user} do
|
||||||
|
|||||||
Reference in New Issue
Block a user