Files
chess-endgame-trainer/lib/chesstrainer/attempts.ex
T
owenrees 55d2e2a913 add puzzle training sessions with difficulty and ratings
- /train starts an ephemeral session by choosing easy/medium/hard, banded
  relative to the user's current rating (band width configurable)
- session timer, average per-puzzle time, net rating gain and per-puzzle delta
- next puzzle, plus review and retry reused from the play surface
- explicit stop/start: stopping returns to the difficulty picker
- puzzle rating shown once a puzzle completes, and a side-to-move indicator
- extract the play logic/markup into shared PlayCore and PlayComponents so the
  standalone play view and sessions share one implementation
- sticky footer; glossary entries for Difficulty and Session; ADR 0009
2026-11-05 15:44:11 +01:00

80 lines
2.2 KiB
Elixir

defmodule Chesstrainer.Attempts do
@moduledoc """
The Attempts context: a per-user history of finished playthroughs.
"""
import Ecto.Query, warn: false
alias Chesstrainer.Repo
alias Chesstrainer.Accounts.{Scope, User}
alias Chesstrainer.Endgames.Endgame
alias Chesstrainer.Attempts.Attempt
@doc """
Records a finished attempt for the signed-in user in `scope`.
Anonymous scopes record nothing and return `:ignored`.
"""
def record_attempt(nil, _endgame, _outcome), do: :ignored
def record_attempt(%Scope{user: nil}, _endgame, _outcome), do: :ignored
def record_attempt(%Scope{user: %User{} = user}, %Endgame{} = endgame, outcome)
when outcome in [:solved, :failed] do
%Attempt{user_id: user.id, endgame_id: endgame.id}
|> Attempt.changeset(%{outcome: outcome})
|> Repo.insert()
end
@doc """
The timestamp of the most recent rated attempt for a user/endgame pair, or nil.
"""
def last_rated_at(user_id, endgame_id) do
Attempt
|> where([a], a.user_id == ^user_id and a.endgame_id == ^endgame_id)
|> rated()
|> select([a], max(a.rated_at))
|> Repo.one()
end
@doc """
The timestamp of the most recent rated attempt for a user, or nil.
"""
def last_rated_at_for_user(user_id) do
Attempt
|> where([a], a.user_id == ^user_id)
|> rated()
|> select([a], max(a.rated_at))
|> Repo.one()
end
@doc """
The timestamp of the most recent rated attempt on an endgame, or nil.
"""
def last_rated_at_for_endgame(endgame_id) do
Attempt
|> where([a], a.endgame_id == ^endgame_id)
|> rated()
|> select([a], max(a.rated_at))
|> Repo.one()
end
@doc """
The distinct endgame ids `user_id` has attempted in the last `days` days.
Used by puzzle selection to prefer fresh puzzles; a retry still counts as an
attempt, even though the rating window leaves it unrated.
"""
def recent_endgame_ids(user_id, days \\ 30) do
cutoff = DateTime.add(DateTime.utc_now(), -days, :day)
Attempt
|> where([a], a.user_id == ^user_id and a.inserted_at >= ^cutoff)
|> distinct(true)
|> select([a], a.endgame_id)
|> Repo.all()
end
defp rated(query), do: where(query, [a], not is_nil(a.rated_at))
end