diff --git a/lib/plausible_web/controllers/unsubscribe_controller.ex b/lib/plausible_web/controllers/unsubscribe_controller.ex index f8eff5fee..eb38813b8 100644 --- a/lib/plausible_web/controllers/unsubscribe_controller.ex +++ b/lib/plausible_web/controllers/unsubscribe_controller.ex @@ -5,10 +5,13 @@ defmodule PlausibleWeb.UnsubscribeController do def weekly_report(conn, %{"website" => website, "email" => email}) do site = Repo.get_by(Plausible.Site, domain: website) + weekly_report = site && Repo.get_by(WeeklyReport, site_id: site.id) - Repo.get_by(WeeklyReport, site_id: site.id) - |> WeeklyReport.remove_recipient(email) - |> Repo.update!() + if weekly_report do + weekly_report + |> WeeklyReport.remove_recipient(email) + |> Repo.update!() + end conn |> assign(:skip_plausible_tracking, true) @@ -21,10 +24,13 @@ defmodule PlausibleWeb.UnsubscribeController do def monthly_report(conn, %{"website" => website, "email" => email}) do site = Repo.get_by(Plausible.Site, domain: website) + monthly_report = site && Repo.get_by(MonthlyReport, site_id: site.id) - Repo.get_by(MonthlyReport, site_id: site.id) - |> MonthlyReport.remove_recipient(email) - |> Repo.update!() + if monthly_report do + monthly_report + |> MonthlyReport.remove_recipient(email) + |> Repo.update!() + end conn |> assign(:skip_plausible_tracking, true) diff --git a/test/plausible_web/controllers/unsubscribe_controller_test.exs b/test/plausible_web/controllers/unsubscribe_controller_test.exs index 20eb77979..56f1afc67 100644 --- a/test/plausible_web/controllers/unsubscribe_controller_test.exs +++ b/test/plausible_web/controllers/unsubscribe_controller_test.exs @@ -15,6 +15,13 @@ defmodule PlausibleWeb.UnsubscribeControllerTest do report = Repo.get_by(Plausible.Site.WeeklyReport, site_id: site.id) assert report.recipients == [] end + + test "renders success if site or weekly report does not exist in the database", %{conn: conn} do + conn = + get(conn, "/sites/nonexistent.com/weekly-report/unsubscribe?email=recipient@email.com") + + assert html_response(conn, 200) =~ "Unsubscribe successful" + end end describe "GET /sites/:website/monthly-report/unsubscribe" do @@ -30,5 +37,12 @@ defmodule PlausibleWeb.UnsubscribeControllerTest do report = Repo.get_by(Plausible.Site.MonthlyReport, site_id: site.id) assert report.recipients == [] end + + test "renders success if site or weekly report does not exist in the database", %{conn: conn} do + conn = + get(conn, "/sites/nonexistent.com/monthly-report/unsubscribe?email=recipient@email.com") + + assert html_response(conn, 200) =~ "Unsubscribe successful" + end end end