diff --git a/GLOSSARY.md b/GLOSSARY.md index ffdb50a..90b7884 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -64,6 +64,12 @@ _Avoid_: Permission, access level A user's subscription tier — `free` or `premium` — independent of their role. _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 **Winning side**: diff --git a/assets/css/app.css b/assets/css/app.css index 9abf639..ef97a05 100644 --- a/assets/css/app.css +++ b/assets/css/app.css @@ -20,6 +20,7 @@ @import "./components/_icon.css"; @import "./components/_button.css"; @import "./components/_learning-strip.css"; +@import "./components/_mailing-list.css"; @import "./components/_board.css"; @import "./components/_promotion.css"; @import "./pages/_legal.css"; diff --git a/assets/css/components/_mailing-list.css b/assets/css/components/_mailing-list.css new file mode 100644 index 0000000..70119d3 --- /dev/null +++ b/assets/css/components/_mailing-list.css @@ -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; } +} diff --git a/lib/chesstrainer/accounts/user.ex b/lib/chesstrainer/accounts/user.ex index 0de131e..97eb410 100644 --- a/lib/chesstrainer/accounts/user.ex +++ b/lib/chesstrainer/accounts/user.ex @@ -15,6 +15,7 @@ defmodule Chesstrainer.Accounts.User do field :rating_deviation, :float, default: 350.0 field :confirmed_at, :utc_datetime field :authenticated_at, :utc_datetime, virtual: true + field :mailing_list, :boolean, virtual: true, default: false timestamps(type: :utc_datetime) end @@ -34,7 +35,7 @@ defmodule Chesstrainer.Accounts.User do """ def registration_changeset(user, attrs, opts \\ []) do user - |> cast(attrs, [:email, :username, :password]) + |> cast(attrs, [:email, :username, :password, :mailing_list]) |> validate_email(opts) |> validate_username(opts) |> validate_confirmation(:password, message: "does not match password") diff --git a/lib/chesstrainer/mailing_list.ex b/lib/chesstrainer/mailing_list.ex new file mode 100644 index 0000000..ce41637 --- /dev/null +++ b/lib/chesstrainer/mailing_list.ex @@ -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 diff --git a/lib/chesstrainer/mailing_list/notifier.ex b/lib/chesstrainer/mailing_list/notifier.ex new file mode 100644 index 0000000..f7430e8 --- /dev/null +++ b/lib/chesstrainer/mailing_list/notifier.ex @@ -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 diff --git a/lib/chesstrainer/mailing_list/subscriber.ex b/lib/chesstrainer/mailing_list/subscriber.ex new file mode 100644 index 0000000..8c57b18 --- /dev/null +++ b/lib/chesstrainer/mailing_list/subscriber.ex @@ -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 diff --git a/lib/chesstrainer_web/components/landing_components.ex b/lib/chesstrainer_web/components/landing_components.ex index 96eda76..7eb38f5 100644 --- a/lib/chesstrainer_web/components/landing_components.ex +++ b/lib/chesstrainer_web/components/landing_components.ex @@ -8,6 +8,8 @@ defmodule ChesstrainerWeb.LandingComponents do """ use Phoenix.Component + import Phoenix.Controller, only: [get_csrf_token: 0] + alias Chesstrainer.FEN alias Chesstrainer.Themes @@ -70,6 +72,43 @@ defmodule ChesstrainerWeb.LandingComponents do 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""" +
+
+ Mailing list +

One good endgame idea, now and then.

+

+ Occasional emails about new puzzles and features. We'll ask you to confirm your address first. +

+
+ +
+ + +
+ + <.pill_button variant={:primary} type="submit">Join the list +
+
+
+ """ + end + @doc """ Renders a static board preview for the landing page. diff --git a/lib/chesstrainer_web/controllers/mailing_list_controller.ex b/lib/chesstrainer_web/controllers/mailing_list_controller.ex new file mode 100644 index 0000000..2a9b10b --- /dev/null +++ b/lib/chesstrainer_web/controllers/mailing_list_controller.ex @@ -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 diff --git a/lib/chesstrainer_web/controllers/page_html/home.html.heex b/lib/chesstrainer_web/controllers/page_html/home.html.heex index d151c41..8f78792 100644 --- a/lib/chesstrainer_web/controllers/page_html/home.html.heex +++ b/lib/chesstrainer_web/controllers/page_html/home.html.heex @@ -71,6 +71,8 @@ + <.mailing_list_signup /> + <%!--
A calmer way to improve diff --git a/lib/chesstrainer_web/controllers/page_html/privacy.html.heex b/lib/chesstrainer_web/controllers/page_html/privacy.html.heex index 2703a44..e865cc2 100644 --- a/lib/chesstrainer_web/controllers/page_html/privacy.html.heex +++ b/lib/chesstrainer_web/controllers/page_html/privacy.html.heex @@ -24,6 +24,13 @@ We record the puzzles you attempt and whether you solved them, so we can show your progress and keep the daily puzzle meaningful. +
  • + Mailing list email. + 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. +
  • Technical data. Our hosting and server infrastructure may keep standard request logs @@ -58,6 +65,7 @@
  • To create and secure your account and sign you in.
  • To run the trainer and remember your progress.
  • To send service emails, such as confirmation and password reset links.
  • +
  • To send occasional endgame tips and site news, if you opted in.
  • To keep the site available, prevent abuse, and fix faults.
  • To respond when you ask for help.
  • diff --git a/lib/chesstrainer_web/controllers/user_confirmation_controller.ex b/lib/chesstrainer_web/controllers/user_confirmation_controller.ex index 2787865..a4aba73 100644 --- a/lib/chesstrainer_web/controllers/user_confirmation_controller.ex +++ b/lib/chesstrainer_web/controllers/user_confirmation_controller.ex @@ -2,10 +2,13 @@ defmodule ChesstrainerWeb.UserConfirmationController do use ChesstrainerWeb, :controller alias Chesstrainer.Accounts + alias Chesstrainer.MailingList def edit(conn, %{"token" => token}) do case Accounts.confirm_user(token) do - {:ok, _user} -> + {:ok, user} -> + MailingList.confirm_user_subscription(user) + conn |> put_flash(:info, "User confirmed successfully.") |> redirect(to: ~p"/users/log-in") diff --git a/lib/chesstrainer_web/live/user_live/registration.ex b/lib/chesstrainer_web/live/user_live/registration.ex index c183856..85b926c 100644 --- a/lib/chesstrainer_web/live/user_live/registration.ex +++ b/lib/chesstrainer_web/live/user_live/registration.ex @@ -3,6 +3,7 @@ defmodule ChesstrainerWeb.UserLive.Registration do alias Chesstrainer.Accounts alias Chesstrainer.Accounts.User + alias Chesstrainer.MailingList @impl true def render(assigns) do @@ -56,6 +57,11 @@ defmodule ChesstrainerWeb.UserLive.Registration do spellcheck="false" 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"> Create an account @@ -82,6 +88,8 @@ defmodule ChesstrainerWeb.UserLive.Registration do def handle_event("save", %{"user" => user_params}, socket) do case Accounts.register_user(user_params) do {:ok, user} -> + if user.mailing_list, do: MailingList.subscribe_user(user) + {:ok, _} = Accounts.deliver_user_confirmation_instructions( user, diff --git a/lib/chesstrainer_web/router.ex b/lib/chesstrainer_web/router.ex index 218eff2..6e9c1c0 100644 --- a/lib/chesstrainer_web/router.ex +++ b/lib/chesstrainer_web/router.ex @@ -23,6 +23,8 @@ defmodule ChesstrainerWeb.Router do get "/", PageController, :home get "/privacy", PageController, :privacy get "/terms-conditions", PageController, :terms_conditions + post "/mailing-list", MailingListController, :create + get "/mailing-list/confirm/:token", MailingListController, :confirm end scope "/admin", ChesstrainerWeb do diff --git a/priv/repo/migrations/20261106211731_create_mailing_list_subscribers.exs b/priv/repo/migrations/20261106211731_create_mailing_list_subscribers.exs new file mode 100644 index 0000000..3122a7c --- /dev/null +++ b/priv/repo/migrations/20261106211731_create_mailing_list_subscribers.exs @@ -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 diff --git a/test/chesstrainer/mailing_list_test.exs b/test/chesstrainer/mailing_list_test.exs new file mode 100644 index 0000000..0776a97 --- /dev/null +++ b/test/chesstrainer/mailing_list_test.exs @@ -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 diff --git a/test/chesstrainer_web/controllers/mailing_list_controller_test.exs b/test/chesstrainer_web/controllers/mailing_list_controller_test.exs new file mode 100644 index 0000000..57591ef --- /dev/null +++ b/test/chesstrainer_web/controllers/mailing_list_controller_test.exs @@ -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 diff --git a/test/chesstrainer_web/controllers/page_controller_test.exs b/test/chesstrainer_web/controllers/page_controller_test.exs index 33697ac..bbf2135 100644 --- a/test/chesstrainer_web/controllers/page_controller_test.exs +++ b/test/chesstrainer_web/controllers/page_controller_test.exs @@ -180,6 +180,22 @@ defmodule ChesstrainerWeb.PageControllerTest do 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 html = conn |> get(~p"/") |> html_response(200) diff --git a/test/chesstrainer_web/controllers/user_confirmation_controller_test.exs b/test/chesstrainer_web/controllers/user_confirmation_controller_test.exs index 471d648..bdeb2c2 100644 --- a/test/chesstrainer_web/controllers/user_confirmation_controller_test.exs +++ b/test/chesstrainer_web/controllers/user_confirmation_controller_test.exs @@ -5,6 +5,8 @@ defmodule ChesstrainerWeb.UserConfirmationControllerTest do alias Chesstrainer.Accounts alias Chesstrainer.Accounts.User + alias Chesstrainer.MailingList + alias Chesstrainer.MailingList.Subscriber alias Chesstrainer.Repo setup do @@ -33,5 +35,21 @@ defmodule ChesstrainerWeb.UserConfirmationControllerTest do assert redirected_to(conn) == ~p"/users/register" 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 diff --git a/test/chesstrainer_web/live/user_live/registration_test.exs b/test/chesstrainer_web/live/user_live/registration_test.exs index 7ab4535..7b6fda3 100644 --- a/test/chesstrainer_web/live/user_live/registration_test.exs +++ b/test/chesstrainer_web/live/user_live/registration_test.exs @@ -5,6 +5,8 @@ defmodule ChesstrainerWeb.UserLive.RegistrationTest do import Chesstrainer.AccountsFixtures import Swoosh.TestAssertions + alias Chesstrainer.MailingList.Subscriber + describe "Registration page" do test "renders registration page", %{conn: conn} do {:ok, _lv, html} = live(conn, ~p"/users/register") @@ -34,6 +36,16 @@ defmodule ChesstrainerWeb.UserLive.RegistrationTest do assert result =~ "Register" assert result =~ "must have the @ sign and no spaces" 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 describe "register user" do @@ -63,6 +75,45 @@ defmodule ChesstrainerWeb.UserLive.RegistrationTest do assert_email_sent(subject: "Confirmation instructions") 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 {:ok, lv, _html} = live(conn, ~p"/users/register")