Skip to content

Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.

[Team Deletions] Rest of the owl (#6612)

Adam986b0c89e96a
diff --git a/.github/workflows/all-checks-pass.yml b/.github/workflows/all-checks-pass.yml
index a60e266727..feb9b8c3fe 100644
--- a/.github/workflows/all-checks-pass.yml
+++ b/.github/workflows/all-checks-pass.yml
@@ -11,6 +11,6 @@ jobs:
checks: read
steps:
- name: GitHub Checks
- uses: poseidon/wait-for-status-checks@899c768d191b56eef585c18f8558da19e1f3e707 # v0.6.0
+ uses: poseidon/wait-for-status-checks@e7e24423722c5b8e97a6dd5848827d2a412f812d # v0.7.0
with:
token: ${{ secrets.GITHUB_TOKEN }}
diff --git a/config/runtime.exs b/config/runtime.exs
index baad4e198a..a723cc361c 100644
--- a/config/runtime.exs
+++ b/config/runtime.exs
@@ -846,8 +846,18 @@ cloud_cron = [
{"0 15 * * *", Plausible.Workers.NotifyAnnualRenewal},
# Every midnight
{"0 0 * * *", Plausible.Workers.LockSites},
+ # Daily at 6, ahead of ScanInactiveTeams - restarts the notice cycle for
+ # any lapsed snoozes so they're immediately eligible again same-day
+ {"0 6 * * *", Plausible.Workers.UnsnoozeTeamDeletions},
+ # Daily at 7, ahead of AcceptTrafficUntil/SendTrialNotifications
+ {"0 7 * * *", Plausible.Workers.ScanInactiveTeams},
# Daily at 8
{"0 8 * * *", Plausible.Workers.AcceptTrafficUntil},
+ # Weekdays at 9, after AcceptTrafficUntil - no deletion notices go out on
+ # weekends; anything due Sat/Sun is simply picked up on Monday instead
+ {"0 9 * * 1-5", Plausible.Workers.SendDeletionNotifications},
+ # Daily at 10, after SendDeletionNotifications
+ {"0 10 * * *", Plausible.Workers.ExecuteTeamDeletions},
# Every Tuesday, 3:00 UTC
{"0 3 * * TUE", Plausible.Workers.ClickhouseCleanSites},
# Daily at 5:00 UTC
@@ -881,6 +891,10 @@ cloud_queues = [
check_usage: 1,
notify_annual_renewal: 1,
lock_sites: 1,
+ scan_inactive_teams: 1,
+ unsnooze_team_deletions: 1,
+ deletion_notification_emails: 1,
+ execute_team_deletions: 1,
legacy_time_on_page_cutoff: 1,
purge_cdn_cache: 1,
sso_domain_ownership_verification: 32,
diff --git a/extra/lib/plausible/customer_support/resource/team.ex b/extra/lib/plausible/customer_support/resource/team.ex
index d812932377..9e94162618 100644
--- a/extra/lib/plausible/customer_support/resource/team.ex
+++ b/extra/lib/plausible/customer_support/resource/team.ex
@@ -24,7 +24,7 @@ defmodule Plausible.CustomerSupport.Resource.Team do
left_lateral_join: s in subquery(Teams.last_subscription_join_query()),
on: true,
order_by: [desc: :id],
- preload: [owners: o, subscription: s]
+ preload: [:team_deletion_schedule, owners: o, subscription: s]
)
Plausible.Repo.all(q)
@@ -39,7 +39,7 @@ defmodule Plausible.CustomerSupport.Resource.Team do
as: :team,
inner_join: o in assoc(t, :owners),
where: t.identifier == ^input,
- preload: [owners: o]
+ preload: [:team_deletion_schedule, owners: o]
)
else
from(t in Plausible.Teams.Team,
@@ -56,7 +56,7 @@ defmodule Plausible.CustomerSupport.Resource.Team do
desc: fragment("?.email = ?", o, ^input),
asc: t.name
],
- preload: [owners: o]
+ preload: [:team_deletion_schedule, owners: o]
)
end
diff --git a/extra/lib/plausible_web/live/customer_support/components/search_result.ex b/extra/lib/plausible_web/live/customer_support/components/search_result.ex
index 5cb2c00a63..bdc0ca66a1 100644
--- a/extra/lib/plausible_web/live/customer_support/components/search_result.ex
+++ b/extra/lib/plausible_web/live/customer_support/components/search_result.ex
@@ -33,6 +33,13 @@ defmodule PlausibleWeb.CustomerSupport.Components.SearchResult do
>
$
</span>
+ <span
+ :if={@resource.object.team_deletion_schedule}
+ class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-red-100 text-red-800"
+ title="Deletion pending"
+ >
+ 🧨
+ </span>
</div>
<hr class="mt-4 mb-4 flex-grow border-t border-gray-200 dark:border-gray-600" />
diff --git a/extra/lib/plausible_web/live/customer_support/team/components/overview.ex b/extra/lib/plausible_web/live/customer_support/team/components/overview.ex
index 3fd1866cec..b840703db1 100644
--- a/extra/lib/plausible_web/live/customer_support/team/components/overview.ex
+++ b/extra/lib/plausible_web/live/customer_support/team/components/overview.ex
@@ -5,16 +5,28 @@ defmodule PlausibleWeb.CustomerSupport.Team.Components.Overview do
use PlausibleWeb, :live_component
import PlausibleWeb.CustomerSupport.Live
+ alias Plausible.TeamDeletionSchedule
+ alias Plausible.TeamDeletionSchedules
+
def update(%{team: team}, socket) do
changeset = Plausible.Teams.Team.crm_changeset(team, %{})
form = to_form(changeset)
+ schedule = TeamDeletionSchedules.active_schedule_for_team(team)
+ snooze_form = schedule && to_form(TeamDeletionSchedule.crm_changeset(schedule, %{}))
- {:ok, assign(socket, team: team, form: form)}
+ {:ok, assign(socket, team: team, form: form, schedule: schedule, snooze_form: snooze_form)}
end
def render(assigns) do
~H"""
<div class="mt-8">
+ <.deletion_schedule
+ :if={@schedule}
+ schedule={@schedule}
+ snooze_form={@snooze_form}
+ myself={@myself}
+ />
+
<.form :let={f} for={@form} phx-submit="save-team" phx-target={@myself}>
<.input field={f[:trial_expiry_date]} type="date" label="Trial Expiry Date" />
<.input field={f[:accept_traffic_until]} type="date" label="Accept traffic Until" />
@@ -45,13 +57,98 @@ defmodule PlausibleWeb.CustomerSupport.Team.Components.Overview do
"""
end
+ attr :schedule, :any, required: true
+ attr :snooze_form, :any, required: true
+ attr :myself, :any, required: true
+
+ defp deletion_schedule(assigns) do
+ ~H"""
+ <div class="mb-6">
+ <.notice theme={notice_theme(@schedule.status)} title="Deletion scheduled">
+ {deletion_sentence(@schedule)}
+
+ <div :if={@schedule.status == :snoozed} class="mt-3">
+ <p class="text-sm text-gray-600 dark:text-gray-400">
+ Snoozed until
+ <strong>{@schedule.snoozed_until}</strong><span :if={@schedule.snooze_note}> — "{@schedule.snooze_note}"</span>.
+ </p>
+
+ <.button
+ class="mt-2"
+ phx-click="unsnooze-schedule"
+ phx-target={@myself}
+ data-confirm="Resume the deletion schedule now? This restarts the notice cycle."
+ >
+ Unsnooze
+ </.button>
+ </div>
+
+ <.form
+ :let={f}
+ :if={@schedule.status != :snoozed}
+ for={@snooze_form}
+ phx-submit="snooze-schedule"
+ phx-target={@myself}
+ class="mt-3 flex items-end gap-x-4"
+ >
+ <.input field={f[:snoozed_until]} type="date" label="Snooze until" />
+ <.input field={f[:snooze_note]} type="text" label="Note (optional)" />
+ <.button type="submit">Snooze</.button>
+ </.form>
+ </.notice>
+ </div>
+ """
+ end
+
+ defp notice_theme(:snoozed), do: :gray
+ defp notice_theme(_), do: :yellow
+
+ defp deletion_sentence(schedule) do
+ category =
+ case schedule.category do
+ :expired_trial -> "expired trial"
+ :churned_subscription -> "churned subscription"
+ end
+
+ status_detail =
+ case schedule.status do
+ :scheduled ->
+ "Pending. First notice due #{schedule.first_notice_due_date}."
+
+ :first_notice_sent ->
+ "First notice sent #{format_dt(schedule.first_notice_sent_at)}."
+
+ :reminder_sent ->
+ "Reminder sent #{format_dt(schedule.reminder_sent_at)}."
+
+ :snoozed ->
+ "Snoozed."
+
+ :cancelled ->
+ "Cancelled."
+
+ :completed ->
+ "Completed."
+ end
+
+ "#{String.capitalize(category)}. Stats deletion on #{schedule.deletion_date}. #{status_detail}"
+ end
+
+ defp format_dt(nil), do: "N/A"
+ defp format_dt(%NaiveDateTime{} = dt), do: NaiveDateTime.to_date(dt) |> Date.to_string()
+
def handle_event("save-team", %{"team" => params}, socket) do
changeset = Plausible.Teams.Team.crm_changeset(socket.assigns.team, params)
case Plausible.Repo.update(changeset) do
{:ok, team} ->
+ # Prolonging trial_expiry_date (or otherwise making the team
+ # eligible again) cancels any pending deletion schedule.
+ TeamDeletionSchedules.cancel_for_team(team)
+ schedule = TeamDeletionSchedules.active_schedule_for_team(team)
+
success("Team saved")
- {:noreply, assign(socket, team: team, form: to_form(changeset))}
+ {:noreply, assign(socket, team: team, form: to_form(changeset), schedule: schedule)}
{:error, changeset} ->
failure("Error saving team: #{inspect(changeset.errors)}")
@@ -71,4 +168,37 @@ defmodule PlausibleWeb.CustomerSupport.Team.Components.Overview do
{:noreply, socket}
end
end
+
+ def handle_event("snooze-schedule", %{"team_deletion_schedule" => params}, socket) do
+ changeset = TeamDeletionSchedule.crm_changeset(socket.assigns.schedule, params)
+
+ if changeset.valid? do
+ until_date = Ecto.Changeset.get_change(changeset, :snoozed_until)
+ note = Ecto.Changeset.get_change(changeset, :snooze_note)
+
+ case TeamDeletionSchedules.snooze(socket.assigns.schedule, until_date, note: note) do
+ {:ok, schedule} ->
+ success("Deletion snoozed until #{until_date}")
+ {:noreply, assign(socket, schedule: schedule)}
+
+ {:error, {:invalid_transition, _, _}} ->
+ failure("Could not snooze - schedule is no longer in a snoozable state")
+ {:noreply, socket}
+ end
+ else
+ {:noreply, assign(socket, snooze_form: to_form(%{changeset | action: :validate}))}
+ end
+ end
+
+ def handle_event("unsnooze-schedule", _params, socket) do
+ case TeamDeletionSchedules.unsnooze(socket.assigns.schedule) do
+ {:ok, schedule} ->
+ success("Deletion schedule resumed")
+ {:noreply, assign(socket, schedule: schedule)}
+
+ {:error, {:invalid_transition, _, _}} ->
+ failure("Could not resume - schedule is not currently snoozed")
+ {:noreply, socket}
+ end
+ end
end
diff --git a/lib/plausible/billing/billing.ex b/lib/plausible/billing/billing.ex
index 5d94823851..88859273e0 100644
--- a/lib/plausible/billing/billing.ex
+++ b/lib/plausible/billing/billing.ex
@@ -9,6 +9,7 @@ defmodule Plausible.Billing do
alias Plausible.Auth
alias Plausible.Billing.Subscription
+ alias Plausible.TeamDeletionSchedules
alias Plausible.Teams
defmacro allowed_roles(), do: [:owner, :billing]
@@ -148,6 +149,7 @@ defmodule Plausible.Billing do
|> Repo.preload(:team)
Plausible.Teams.update_accept_traffic_until(subscription.team)
+ TeamDeletionSchedules.cancel_for_team(subscription.team)
subscription
end
@@ -253,6 +255,7 @@ defmodule Plausible.Billing do
|> Plausible.Teams.remove_grace_period()
|> Plausible.Teams.maybe_reset_next_upgrade_override()
|> tap(&Plausible.Billing.SiteLocker.update_for/1)
+ |> tap(&TeamDeletionSchedules.cancel_for_team/1)
|> maybe_adjust_api_key_limits()
end
diff --git a/lib/plausible/pending_stats_deletion.ex b/lib/plausible/pending_stats_deletion.ex
index 9cedc6433f..751675f4a5 100644
--- a/lib/plausible/pending_stats_deletion.ex
+++ b/lib/plausible/pending_stats_deletion.ex
@@ -5,7 +5,7 @@ defmodule Plausible.PendingStatsDeletion do
use Ecto.Schema
- @reasons [:user_request]
+ @reasons [:user_request, :expired_trial, :churned_subscription]
@type t() :: %__MODULE__{}
diff --git a/lib/plausible/site/removal.ex b/lib/plausible/site/removal.ex
index 931503e272..e340096943 100644
--- a/lib/plausible/site/removal.ex
+++ b/lib/plausible/site/removal.ex
@@ -12,10 +12,12 @@ defmodule Plausible.Site.Removal do
@spec run(Plausible.Site.t(), Keyword.t()) :: {:ok, map()}
def run(site, opts \\ []) do
+ reason = Keyword.get(opts, :reason, :user_request)
+
Repo.transaction(fn ->
site = Repo.preload(site, :team)
- {:ok, pending_stats_deletion} = PendingStatsDeletions.store(site)
+ {:ok, pending_stats_deletion} = PendingStatsDeletions.store(site, reason)
result = Repo.delete_all(from(s in Plausible.Site, where: s.domain == ^site.domain))
diff --git a/lib/plausible/team_deletion_schedule.ex b/lib/plausible/team_deletion_schedule.ex
new file mode 100644
index 0000000000..2051e88727
--- /dev/null
+++ b/lib/plausible/team_deletion_schedule.ex
@@ -0,0 +1,66 @@
+defmodule Plausible.TeamDeletionSchedule do
+ @moduledoc """
+ Schema for tracking the notify-delete lifecycle of teams whose trial
+ or subscription has expired, ahead of their stats being removed.
+ """
+
+ use Ecto.Schema
+
+ import Ecto.Changeset
+
+ @categories [:expired_trial, :churned_subscription]
+ @statuses [:scheduled, :first_notice_sent, :reminder_sent, :completed, :cancelled, :snoozed]
+
+ # Indicate permanent end of schedule lifecycle
+ @terminal_statuses [:cancelled, :completed]
+
+ @type t() :: %__MODULE__{}
+
+ schema "team_deletion_schedules" do
+ belongs_to :team, Plausible.Teams.Team
+
+ field :category, Ecto.Enum, values: @categories
+ field :expiry_date, :date
+ field :deletion_date, :date
+ field :is_backlog, :boolean, default: false
+ field :status, Ecto.Enum, values: @statuses, default: :scheduled
+ field :first_notice_due_date, :date
+ field :first_notice_sent_at, :naive_datetime
+ field :reminder_sent_at, :naive_datetime
+ field :snoozed_until, :date
+ field :snooze_note, :string
+
+ timestamps()
+ end
+
+ @spec categories() :: [atom()]
+ def categories, do: @categories
+
+ @spec statuses() :: [atom()]
+ def statuses, do: @statuses
+
+ @spec terminal_statuses() :: [atom()]
+ def terminal_statuses, do: @terminal_statuses
+
+ @spec active_statuses() :: [atom()]
+ def active_statuses, do: @statuses -- @terminal_statuses
+
+ @doc """
+ Validates staff submitted snooze input from the CRM - snoozed_until is
+ required and must be in the future. Doesn't touch status, the actual
+ transition happens via Plausible.TeamDeletionSchedules.snooze/3.
+ """
+ @spec crm_changeset(t(), map()) :: Ecto.Changeset.t()
+ def crm_changeset(schedule, params) do
+ schedule
+ |> cast(params, [:snoozed_until, :snooze_note])
+ |> validate_required([:snoozed_until])
+ |> validate_change(:snoozed_until, fn field, date ->
+ if Date.after?(date, Date.utc_today()) do
+ []
+ else
+ [{field, "must be in the future"}]
+ end
+ end)
+ end
+end
diff --git a/lib/plausible/team_deletion_schedules.ex b/lib/plausible/team_deletion_schedules.ex
new file mode 100644
index 0000000000..300bff8f7d
--- /dev/null
+++ b/lib/plausible/team_deletion_schedules.ex
@@ -0,0 +1,379 @@
+defmodule Plausible.TeamDeletionSchedules do
+ @moduledoc """
+ Context for scheduling inactive teams deletion (trial expired or subscription
+ churned).
+ """
+
+ import Ecto.Query
+
+ require Plausible.Billing.Subscription.Status
+
+ alias Plausible.Billing.Subscription
+ alias Plausible.Billing.Subscriptions
+ alias Plausible.Repo
+ alias Plausible.Site
+ alias Plausible.TeamDeletionSchedule
+ alias Plausible.Teams
+ alias Plausible.Teams.DeletionSchedule
+
+ @doc """
+ Finds newly eligible teams (expired trial/churned subscription) and
+ schedules each for the deletion pipeline. Reactivation is handled
+ via billing (Paddle) handlers.
+ """
+ @spec sync_eligible(Date.t()) :: non_neg_integer()
+ def sync_eligible(today \\ Date.utc_today()) do
+ candidates =
+ Repo.all(
+ from(t in Teams.Team,
+ as: :team,
+ left_lateral_join: s in subquery(Teams.last_subscription_join_query()),
+ on: true,
+ left_join: ep in assoc(t, :enterprise_plan),
+ where: is_nil(ep.id),
+ where: exists(from(s in Site.regular(), where: s.team_id == parent_as(:team).id)),
+ where: ^eligible_category?(today),
+ where:
+ not exists(
+ from(sch in TeamDeletionSchedule,
+ where: sch.team_id == parent_as(:team).id,
+ where: sch.status in ^TeamDeletionSchedule.active_statuses()
+ )
+ ),
+ select: %{
+ team_id: t.id,
+ has_subscription?: not is_nil(s.id),
+ trial_expiry_date: t.trial_expiry_date,
+ next_bill_date: s.next_bill_date
+ }
+ )
+ )
+
+ now = NaiveDateTime.utc_now(:second)
+ rows = Enum.map(candidates, &build_schedule_row(&1, today, now))
+
+ {count, _} =
+ Repo.insert_all(TeamDeletionSchedule, rows,
+ on_conflict: :nothing,
+ conflict_target: {:unsafe_fragment, terminal_statuses_index_predicate()}
+ )
+
+ count
+ end
+
+ @doc """
+ Cancels any pending deletion schedule for a team that's no longer
+ eligible for it - either its subscription became active, or (for a
+ schedule based on an expired trial) its trial_expiry_date got prolonged
+ past today, e.g. by staff via the CRM.
+ """
+ @spec cancel_for_team(Teams.Team.t()) :: :no_schedule | :ok
+ def cancel_for_team(team) do
+ team = Teams.with_subscription(team)
+
+ if should_cancel?(team) do
+ cancel_active_schedule(team.id)
+ else
+ :no_schedule
+ end
+ end
+
+ defp should_cancel?(%{subscription: nil} = team) do
+ # Teams.on_trial?/1 treats a cleared trial_expiry_date as "not on
+ # trial", but here a cleared date means there's no trial-based justification
+ # for the schedule at all, so it should cancel too.
+ Teams.on_trial?(team) or is_nil(team.trial_expiry_date)
+ end
+
+ defp should_cancel?(team) do
+ Subscriptions.active?(team.subscription)
+ end
+
+ @doc """
+ Schedules due for their first notice - still scheduled and
+ past their first_notice_due_date.
+ """
+ @spec due_for_first_notice(Date.t()) :: [TeamDeletionSchedule.t()]
+ def due_for_first_notice(today \\ Date.utc_today()) do
+ Repo.all(
+ from(sch in TeamDeletionSchedule,
+ inner_join: t in assoc(sch, :team),
+ where: sch.status == :scheduled,
+ where: sch.first_notice_due_date <= ^today,
+ preload: [team: {t, [:owners, :billing_members]}]
+ )
+ )
+ end
+
+ @doc """
+ Schedules due for the reminder: first notice already sent.
+ Applies to backlog rows too.
+ """
+ @spec due_for_reminder(Date.t()) :: [TeamDeletionSchedule.t()]
+ def due_for_reminder(today \\ Date.utc_today()) do
+ reminder_threshold = Date.add(today, DeletionSchedule.reminder_before_deletion_days())
+
+ Repo.all(
+ from(sch in TeamDeletionSchedule,
+ inner_join: t in assoc(sch, :team),
+ where: sch.status == :first_notice_sent,
+ where: sch.deletion_date <= ^reminder_threshold,
+ preload: [team: {t, [:owners, :billing_members]}]
+ )
+ )
+ end
+
+ @doc """
+ Schedules ready for deletion: reminder already sent, past their
+ deletion_date.
+ """
+ @spec due_for_deletion(Date.t()) :: [TeamDeletionSchedule.t()]
+ def due_for_deletion(today \\ Date.utc_today()) do
+ Repo.all(
+ from(sch in TeamDeletionSchedule,
+ inner_join: t in assoc(sch, :team),
+ where: sch.status == :reminder_sent,
+ where: sch.deletion_date <= ^today,
+ preload: [team: t]
+ )
+ )
+ end
+
+ @doc """
+ Schedules whose snooze has lapsed: still snoozed, past their
+ snoozed_until date.
+ """
+ @spec due_for_unsnooze(Date.t()) :: [TeamDeletionSchedule.t()]
+ def due_for_unsnooze(today \\ Date.utc_today()) do
+ Repo.all(
+ from(sch in TeamDeletionSchedule,
+ where: sch.status == :snoozed,
+ where: sch.snoozed_until <= ^today
+ )
+ )
+ end
+
+ @doc """
+ Get the team's current active (non-terminal) deletion schedule, if any
+ """
+ @spec active_schedule_for_team(Teams.Team.t()) :: TeamDeletionSchedule.t() | nil
+ def active_schedule_for_team(team) do
+ team.id
+ |> active_schedule_query()
+ |> Repo.one()
+ end
+
+ @doc """
+ Pending, non-backlog expired trial schedules for the
+ given team ids, keyed by `team_id`
+ """
+ @spec pending_steady_state_trials_by_team_id([pos_integer()]) :: %{
+ pos_integer() => TeamDeletionSchedule.t()
+ }
+ def pending_steady_state_trials_by_team_id([]), do: %{}
+
+ def pending_steady_state_trials_by_team_id(team_ids) do
+ TeamDeletionSchedule
+ |> where([sch], sch.team_id in ^team_ids)
+ |> where([sch], sch.category == :expired_trial)
+ |> where([sch], sch.status == :scheduled)
+ |> where([sch], sch.is_backlog == false)
+ |> Repo.all()
+ |> Map.new(&{&1.team_id, &1})
+ end
+
+ @type transition_result ::
+ {:ok, TeamDeletionSchedule.t()} | {:error, {:invalid_transition, atom(), atom()}}
+
+ @transitions %{
+ scheduled: [:first_notice_sent, :cancelled, :snoozed],
+ first_notice_sent: [:reminder_sent, :cancelled, :snoozed],
+ reminder_sent: [:completed, :cancelled, :snoozed],
+ snoozed: [:cancelled, :scheduled],
+ completed: [],
+ cancelled: []
+ }
+
+ @spec transitions() :: %{atom() => [atom()]}
+ def transitions, do: @transitions
+
+ @spec mark_first_notice_sent(TeamDeletionSchedule.t(), keyword()) :: transition_result
+ def mark_first_notice_sent(schedule, opts \\ [])
+
+ def mark_first_notice_sent(%TeamDeletionSchedule{is_backlog: true} = schedule, opts) do
+ now = Keyword.get(opts, :now, NaiveDateTime.utc_now(:second))
+
+ transition(
+ schedule,
+ :first_notice_sent,
+ %{first_notice_sent_at: now, deletion_date: DeletionSchedule.backlog_deletion_date(now)},
+ opts
+ )
+ end
+
+ def mark_first_notice_sent(%TeamDeletionSchedule{is_backlog: false} = schedule, opts) do
+ now = Keyword.get(opts, :now, NaiveDateTime.utc_now(:second))
+ transition(schedule, :first_notice_sent, %{first_notice_sent_at: now}, opts)
+ end
+
+ @spec mark_reminder_sent(TeamDeletionSchedule.t(), keyword()) :: transition_result
+ def mark_reminder_sent(schedule, opts \\ []) do
+ now = Keyword.get(opts, :now, NaiveDateTime.utc_now(:second))
+ transition(schedule, :reminder_sent, %{reminder_sent_at: now}, opts)
+ end
+
+ @spec mark_completed(TeamDeletionSchedule.t(), keyword()) :: transition_result
+ def mark_completed(schedule, opts \\ []) do
+ transition(schedule, :completed, %{}, opts)
+ end
+
+ @spec cancel(TeamDeletionSchedule.t(), keyword()) :: transition_result
+ def cancel(schedule, opts \\ []) do
+ transition(schedule, :cancelled, %{}, opts)
+ end
+
+ @spec snooze(TeamDeletionSchedule.t(), Date.t(), keyword()) :: transition_result
+ def snooze(schedule, until_date, opts \\ []) do
+ note = Keyword.get(opts, :note)
+ transition(schedule, :snoozed, %{snoozed_until: until_date, snooze_note: note}, opts)
+ end
+
+ @doc """
+ Unsnoozes a schedule once its snooze has lapsed without the team
+ resubscribing. Restarts the notice cycle from scratch
+ """
+ @spec unsnooze(TeamDeletionSchedule.t(), keyword()) :: transition_result
+ def unsnooze(schedule, opts \\ []) do
+ today = Keyword.get(opts, :today, Date.utc_today())
+
+ transition(
+ schedule,
+ :scheduled,
+ %{
+ is_backlog: true,
+ first_notice_due_date: today,
+ first_notice_sent_at: nil,
+ reminder_sent_at: nil,
+ snoozed_until: nil,
+ snooze_note: nil
+ },
+ opts
+ )
+ end
+
+ @valid_transitions for {from, tos} <- @transitions, to <- tos, do: {from, to}
+
+ defp transition(%TeamDeletionSchedule{status: from} = schedule, to, extra_changes, _opts)
+ when {from, to} in @valid_transitions do
+ updated =
+ schedule
+ |> Ecto.Changeset.change(Map.put(extra_changes, :status, to))
+ |> Repo.update!()
+
+ {:ok, updated}
+ end
+
+ defp transition(%TeamDeletionSchedule{status: from, team_id: team_id}, to, _extra_changes, opts) do
+ report_if_invalid? = Keyword.get(opts, :report_if_invalid?, false)
+
+ if report_if_invalid? do
+ Sentry.capture_message("Invalid team deletion schedule transition",
+ extra: %{from: from, to: to, team_id: team_id}
+ )
+ end
+
+ {:error, {:invalid_transition, from, to}}
+ end
+
+ defp cancel_active_schedule(team_id) do
+ {:ok, result} =
+ Repo.transact(fn ->
+ case active_schedule_for(team_id) do
+ nil -> {:ok, :no_schedule}
+ schedule -> {:ok, cancel_result(schedule)}
+ end
+ end)
+
+ result
+ end
+
+ defp cancel_result(schedule) do
+ case cancel(schedule) do
+ {:ok, _} -> :ok
+ {:error, _} -> :no_schedule
+ end
+ end
+
+ defp active_schedule_for(team_id) do
+ team_id
+ |> active_schedule_query()
+ |> lock("FOR UPDATE")
+ |> Repo.one()
+ end
+
+ defp active_schedule_query(team_id) do
+ TeamDeletionSchedule
+ |> where([sch], sch.team_id == ^team_id)
+ |> where([sch], sch.status in ^TeamDeletionSchedule.active_statuses())
+ end
+
+ defp eligible_category?(today) do
+ dynamic(^expired_trial?(today) or ^churned_subscription?(today))
+ end
+
+ defp expired_trial?(today) do
+ dynamic(
+ [t, s],
+ is_nil(s.id) and not is_nil(t.trial_expiry_date) and t.trial_expiry_date < ^today
+ )
+ end
+
+ defp churned_subscription?(today) do
+ dynamic(
+ [_t, s],
+ not is_nil(s.id) and
+ s.status in [^Subscription.Status.deleted(), ^Subscription.Status.paused()] and
+ s.paddle_plan_id != "free_10k" and s.next_bill_date < ^today
+ )
+ end
+
+ defp terminal_statuses_index_predicate do
+ values = Enum.map_join(TeamDeletionSchedule.terminal_statuses(), ", ", &"'#{&1}'")
+ "(team_id) WHERE status NOT IN (#{values})"
+ end
+
+ defp build_schedule_row(candidate, today, now) do
+ {category, expiry_date} =
+ if candidate.has_subscription? do
+ {:churned_subscription, candidate.next_bill_date}
+ else
+ {:expired_trial, candidate.trial_expiry_date}
+ end
+
+ deletion_date = DeletionSchedule.deletion_date(category, expiry_date)
+ steady_state_first_notice_due_date = DeletionSchedule.first_notice_due_date(deletion_date)
+ backlog? = Date.before?(steady_state_first_notice_due_date, today)
+
+ first_notice_due_date =
+ if backlog? do
+ # Spread backlog rows across the release window rather than piling
+ # them all onto the day they're first discovered.
+ offset = rem(candidate.team_id, DeletionSchedule.backlog_release_window_days())
+ Date.add(today, offset)
+ else
+ steady_state_first_notice_due_date
+ end
+
+ %{
+ team_id: candidate.team_id,
+ category: category,
+ expiry_date: expiry_date,
+ deletion_date: deletion_date,
+ first_notice_due_date: first_notice_due_date,
+ is_backlog: backlog?,
+ status: :scheduled,
+ inserted_at: now,
+ updated_at: now
+ }
+ end
+end
diff --git a/lib/plausible/teams/deletion_schedule.ex b/lib/plausible/teams/deletion_schedule.ex
new file mode 100644
index 0000000000..ce18bb8e64
--- /dev/null
+++ b/lib/plausible/teams/deletion_schedule.ex
@@ -0,0 +1,49 @@
+defmodule Plausible.Teams.DeletionSchedule do
+ @moduledoc """
+ Inactive team deletion schedule
+ """
+
+ @trial_deletion_offset_days 60
+ @subscription_deletion_offset_days 180
+
+ @first_notice_before_deletion_days 30
+ @reminder_before_deletion_days 5
+
+ @backlog_deletion_offset_days 30
+ @backlog_release_window_days 60
+
+ # how many domains to include in notifications
+ @notification_site_list_limit 3
+
+ def trial_deletion_offset_days, do: @trial_deletion_offset_days
+ def subscription_deletion_offset_days, do: @subscription_deletion_offset_days
+ def first_notice_before_deletion_days, do: @first_notice_before_deletion_days
+ def reminder_before_deletion_days, do: @reminder_before_deletion_days
+ def backlog_deletion_offset_days, do: @backlog_deletion_offset_days
+ def backlog_release_window_days, do: @backlog_release_window_days
+ def notification_site_list_limit, do: @notification_site_list_limit
+
+ @spec deletion_offset_days(:expired_trial | :churned_subscription) :: pos_integer()
+ def deletion_offset_days(:expired_trial), do: @trial_deletion_offset_days
+ def deletion_offset_days(:churned_subscription), do: @subscription_deletion_offset_days
+
+ @spec deletion_date(:expired_trial | :churned_subscription, Date.t()) :: Date.t()
+ def deletion_date(category, expiry_date) do
+ Date.add(expiry_date, deletion_offset_days(category))
+ end
+
+ @spec first_notice_due_date(Date.t()) :: Date.t()
+ def first_notice_due_date(deletion_date),
+ do: Date.add(deletion_date, -@first_notice_before_deletion_days)
+
+ @spec reminder_due_date(Date.t()) :: Date.t()
+ def reminder_due_date(deletion_date),
+ do: Date.add(deletion_date, -@reminder_before_deletion_days)
+
+ @spec backlog_deletion_date(NaiveDateTime.t()) :: Date.t()
+ def backlog_deletion_date(first_notice_sent_at) do
+ first_notice_sent_at
+ |> NaiveDateTime.to_date()
+ |> Date.add(@backlog_deletion_offset_days)
+ end
+end
diff --git a/lib/plausible/teams/team.ex b/lib/plausible/teams/team.ex
index 0f4608b9e8..86e08967c8 100644
--- a/lib/plausible/teams/team.ex
+++ b/lib/plausible/teams/team.ex
@@ -73,6 +73,9 @@ defmodule Plausible.Teams.Team do
has_one :subscription, Plausible.Billing.Subscription
has_one :enterprise_plan, Plausible.Billing.EnterprisePlan
+ has_one :team_deletion_schedule, Plausible.TeamDeletionSchedule,
+ where: [status: {:in, Plausible.TeamDeletionSchedule.active_statuses()}]
+
on_ee do
has_one :sso_integration, Plausible.Auth.SSO.Integration
end
diff --git a/lib/plausible/telemetry/plausible_metrics.ex b/lib/plausible/telemetry/plausible_metrics.ex
index 524e94f941..11f741a878 100644
--- a/lib/plausible/telemetry/plausible_metrics.ex
+++ b/lib/plausible/telemetry/plausible_metrics.ex
@@ -240,6 +240,35 @@ defmodule Plausible.PromEx.Plugins.PlausibleMetrics do
event_name: Plausible.Workers.ClickhouseCleanSites.telemetry_partitions_event(),
measurement: :count,
tags: [:table]
+ ),
+ last_value(
+ metric_prefix ++ [:scan_inactive_teams, :run, :created_count],
+ event_name: Plausible.Workers.ScanInactiveTeams.telemetry_run_event(),
+ measurement: :created
+ ),
+ last_value(
+ metric_prefix ++ [:unsnooze_team_deletions, :run, :count],
+ event_name: Plausible.Workers.UnsnoozeTeamDeletions.telemetry_run_event(),
+ measurement: :count
+ ),
+ counter(
+ metric_prefix ++ [:send_deletion_notifications, :run, :total],
+ event_name: Plausible.Workers.SendDeletionNotifications.telemetry_run_event(),
+ tags: [:stage, :outcome, :category]
+ ),
+ counter(
+ metric_prefix ++ [:execute_team_deletions, :run, :total],
+ event_name: Plausible.Workers.ExecuteTeamDeletions.telemetry_run_event(),
+ tags: [:outcome, :category]
+ ),
+ distribution(
+ metric_prefix ++ [:execute_team_deletions, :sites_deleted],
+ event_name: Plausible.Workers.ExecuteTeamDeletions.telemetry_sites_deleted_event(),
+ reporter_options: [
+ buckets: [1, 2, 5, 10, 25, 50, 100, 250, 500, 1_000]
+ ],
+ measurement: :count,
+ tags: [:category]
)
]
|> Enum.concat(persistor_metrics(metric_prefix))
diff --git a/lib/plausible_web/email.ex b/lib/plausible_web/email.ex
index 466831ec51..788af7d641 100644
--- a/lib/plausible_web/email.ex
+++ b/lib/plausible_web/email.ex
@@ -556,11 +556,12 @@ defmodule PlausibleWeb.Email do
|> render("approaching_accept_traffic_until.html",
time: "next week",
user: %{email: notification.email, name: notification.name},
- team: notification.team
+ team: notification.team,
+ deletion_date: nil
)
end
- def approaching_accept_traffic_until_tomorrow(notification) do
+ def approaching_accept_traffic_until_tomorrow(notification, deletion_date \\ nil) do
base_email()
|> to(notification.email)
|> tag("drop-traffic-warning-final")
@@ -568,7 +569,41 @@ defmodule PlausibleWeb.Email do
|> render("approaching_accept_traffic_until.html",
time: "tomorrow",
user: %{email: notification.email, name: notification.name},
- team: notification.team
+ team: notification.team,
+ deletion_date: deletion_date
+ )
+ end
+
+ def deletion_full_notice_email(user, team, schedule, sites_summary) do
+ days = Plausible.Teams.DeletionSchedule.first_notice_before_deletion_days()
+
+ base_email()
+ |> to(user)
+ |> tag("deletion-full-notice")
+ |> subject("Your Plausible dashboards and stats will be deleted in #{days} days")
+ |> render("deletion_full_notice_email.html",
+ user: user,
+ team: team,
+ category: schedule.category,
+ deletion_date: schedule.deletion_date,
+ sites_summary: sites_summary
+ )
+ end
+
+ def deletion_reminder_email(user, team, schedule, sites_summary) do
+ days = Plausible.Teams.DeletionSchedule.reminder_before_deletion_days()
+
+ base_email()
+ |> to(user)
+ |> tag("deletion-reminder")
+ |> subject(
+ "Final notice: your Plausible dashboards and stats will be deleted in #{days} days"
+ )
+ |> render("deletion_reminder_email.html",
+ user: user,
+ team: team,
+ deletion_date: schedule.deletion_date,
+ sites_summary: sites_summary
)
end
diff --git a/lib/plausible_web/templates/email/approaching_accept_traffic_until.html.heex b/lib/plausible_web/templates/email/approaching_accept_traffic_until.html.heex
index 1afe2c13a7..a42a8956c2 100644
--- a/lib/plausible_web/templates/email/approaching_accept_traffic_until.html.heex
+++ b/lib/plausible_web/templates/email/approaching_accept_traffic_until.html.heex
@@ -1,9 +1,17 @@
-Your sites are still sending us data, but your account is no longer active. We'll stop counting your stats {@time}.
+Your sites are still sending us data, but your account is no longer active. We'll stop counting new stats {@time}.
<br /><br />
-We're writing because we think losing your privacy-first analytics is a bad trade, not just an admin notice. Without Plausible, you're likely back to Google Analytics: cookie banners, complex reports, and your visitors' data going to Google.
+We're writing because we think losing your privacy-first analytics is a bad trade, not just an admin notice. Without Plausible, you're likely back to Google Analytics: cookie banners, complex reports and your visitors' data going to Google.
<br /><br />
-Plausible is still the same thing it was when you signed up. Lightweight. No cookies. No personal data. One clear dashboard. EU-hosted infrastructure. We're a small independent team and subscriptions are what keeps us running.
+Plausible is still the same thing it was when you signed up. Lightweight. No cookies. No personal data. One clear dashboard. EU-hosted infrastructure. We're a small independent team and subscriptions are what keep us running.
<br /><br />
If you'd like to keep counting your stats without tracking your visitors, <a href={plausible_url() <> "?__team=#{@team.identifier}"}>start a Plausible subscription</a>.
+<%= if @deletion_date do %>
+ <br /><br />
+ If you don't subscribe, we'll permanently delete your Plausible dashboards and all their stats on {date_format(
+ @deletion_date
+ )}. This cannot be undone. <br /><br /> If you don't plan to subscribe,
+ <a href="https://plausible.io/docs/export-stats">export your stats</a>
+ before then.
+<% end %>
<br /><br />
Not sure it's the right fit? Just reply to this email and we'll help you figure it out.
diff --git a/lib/plausible_web/templates/email/deletion_full_notice_email.html.heex b/lib/plausible_web/templates/email/deletion_full_notice_email.html.heex
new file mode 100644
index 0000000000..a08d2b3379
--- /dev/null
+++ b/lib/plausible_web/templates/email/deletion_full_notice_email.html.heex
@@ -0,0 +1,20 @@
+<%= if @category == :expired_trial do %>
+ Your Plausible trial ended a while ago and your account has remained inactive since then.
+<% else %>
+ Your Plausible subscription lapsed a while ago and your account has remained inactive since then.
+<% end %>
+<br /><br />
+We don't believe analytics companies should keep website analytics data indefinitely after an account becomes inactive. That's why we'll permanently delete the Plausible dashboards and stats for your
+<strong>{@team.name}</strong>
+team on {date_format(@deletion_date)}. This cannot be undone.
+<%= if @sites_summary.domains != [] do %>
+ <br /><br /> This covers {domains_list(@sites_summary.domains, @sites_summary.more_count)}.
+<% end %>
+<br /><br />
+Plausible is still the simple, privacy-first alternative to Google Analytics you signed up for. No cookies. No personal data. One clear dashboard. Independent and EU-hosted.
+<br /><br />
+<a href={choose_plan_url(@team)}>Subscribe</a>
+before {date_format(@deletion_date)} to keep your dashboards and historical stats. <br /><br />
+If you don't plan to subscribe,
+<a href="https://plausible.io/docs/export-stats">export your stats</a>
+before then. <br /><br /> If you have any questions, just reply to this email and we'll help.
diff --git a/lib/plausible_web/templates/email/deletion_reminder_email.html.heex b/lib/plausible_web/templates/email/deletion_reminder_email.html.heex
new file mode 100644
index 0000000000..ad51c4c81e
--- /dev/null
+++ b/lib/plausible_web/templates/email/deletion_reminder_email.html.heex
@@ -0,0 +1,12 @@
+This is your final reminder. We'll permanently delete the Plausible dashboards and stats for your
+<strong>{@team.name}</strong>
+team on {date_format(@deletion_date)}.
+<%= if @sites_summary.domains != [] do %>
+ <br /><br /> This covers {domains_list(@sites_summary.domains, @sites_summary.more_count)}.
+<% end %>
+<br /><br /> This cannot be undone. <br /><br />
+<a href={choose_plan_url(@team)}>Subscribe</a>
+before {date_format(@deletion_date)} to keep your dashboards and historical stats. <br /><br />
+If you don't plan to subscribe,
+<a href="https://plausible.io/docs/export-stats">export your stats</a>
+before then. <br /><br /> If you have any questions, just reply to this email and we'll help.
diff --git a/lib/plausible_web/views/email_view.ex b/lib/plausible_web/views/email_view.ex
index 8806a9fec0..d9d41c8830 100644
--- a/lib/plausible_web/views/email_view.ex
+++ b/lib/plausible_web/views/email_view.ex
@@ -32,6 +32,17 @@ defmodule PlausibleWeb.EmailView do
Calendar.strftime(date, "%-d %b %Y")
end
+ def domains_list(domains, 0) do
+ Enum.join(domains, ", ")
+ end
+
+ def domains_list(domains, more_count) do
+ Enum.join(domains, ", ") <> " (and #{more_count} more #{pluralize_site(more_count)})"
+ end
+
+ defp pluralize_site(1), do: "site"
+ defp pluralize_site(_), do: "sites"
+
def sentry_link(trace_id, dsn \\ Sentry.Config.dsn()) do
search_query = URI.encode_query(%{query: trace_id})
path = "/organizations/sentry/issues/"
diff --git a/lib/workers/accept_traffic_until_notification.ex b/lib/workers/accept_traffic_until_notification.ex
index 698e795736..92ccff8587 100644
--- a/lib/workers/accept_traffic_until_notification.ex
+++ b/lib/workers/accept_traffic_until_notification.ex
@@ -5,6 +5,8 @@ defmodule Plausible.Workers.AcceptTrafficUntil do
- their sites still receive traffic (i.e. have stats for yesterday)
- `site.accept_traffic_until` is approaching either tomorrow or exactly in 7 days
+ If there's steady state team deletion pending, a notice is included.
+
Users having no sites or sites that receive no traffic, won't be notified.
We make a tiny effort here to make sure we send the same notification at most once a day.
"""
@@ -13,6 +15,7 @@ defmodule Plausible.Workers.AcceptTrafficUntil do
alias Plausible.Repo
alias Plausible.ClickhouseRepo
+ alias Plausible.TeamDeletionSchedules
def dry_run(date) do
perform(nil, date, true)
@@ -48,27 +51,20 @@ defmodule Plausible.Workers.AcceptTrafficUntil do
group_by: [u.id, t.id]
)
+ pending_trial_schedules_by_team_id =
+ notifications
+ |> Enum.filter(&(Date.compare(&1.deadline, tomorrow) == :eq))
+ |> Enum.map(& &1.team.id)
+ |> Enum.uniq()
+ |> TeamDeletionSchedules.pending_steady_state_trials_by_team_id()
+
for notification <- notifications do
case {has_stats?(notification.site_ids, today), notification.deadline} do
{true, ^tomorrow} ->
- if dry_run? do
- IO.puts("Will send final notification to #{notification.email}")
- else
- notification
- |> store_sent(today)
- |> PlausibleWeb.Email.approaching_accept_traffic_until_tomorrow()
- |> Plausible.Mailer.send()
- end
+ send_final_notice(notification, pending_trial_schedules_by_team_id, today, dry_run?)
{true, ^next_week} ->
- if dry_run? do
- IO.puts("Will send weekly notification to #{notification.email}")
- else
- notification
- |> store_sent(today)
- |> PlausibleWeb.Email.approaching_accept_traffic_until()
- |> Plausible.Mailer.send()
- end
+ send_weekly_notice(notification, today, dry_run?)
_ ->
nil
@@ -78,6 +74,39 @@ defmodule Plausible.Workers.AcceptTrafficUntil do
{:ok, Enum.count(notifications)}
end
+ defp send_final_notice(notification, _pending_by_team_id, _today, true = _dry_run?) do
+ IO.puts("Will send final notification to #{notification.email}")
+ end
+
+ defp send_final_notice(notification, pending_trial_schedules_by_team_id, today, false) do
+ deletion_date =
+ if schedule = Map.get(pending_trial_schedules_by_team_id, notification.team.id) do
+ # Advance the schedule before composing/sending the email,
+ # so a crash right after this point can never leave it stuck at :scheduled
+ # while the customer has already been told the deletion date.
+ case TeamDeletionSchedules.mark_first_notice_sent(schedule, report_if_invalid?: true) do
+ {:ok, updated} -> updated.deletion_date
+ {:error, _} -> nil
+ end
+ end
+
+ notification
+ |> store_sent(today)
+ |> PlausibleWeb.Email.approaching_accept_traffic_until_tomorrow(deletion_date)
+ |> Plausible.Mailer.send()
+ end
+
+ defp send_weekly_notice(notification, _today, true = _dry_run?) do
+ IO.puts("Will send weekly notification to #{notification.email}")
+ end
+
+ defp send_weekly_notice(notification, today, false) do
+ notification
+ |> store_sent(today)
+ |> PlausibleWeb.Email.approaching_accept_traffic_until()
+ |> Plausible.Mailer.send()
+ end
+
defp has_stats?(site_ids, today) do
ago_2d = Date.add(today, -2)
diff --git a/lib/workers/execute_team_deletions.ex b/lib/workers/execute_team_deletions.ex
new file mode 100644
index 0000000000..9da6d3bb76
--- /dev/null
+++ b/lib/workers/execute_team_deletions.ex
@@ -0,0 +1,64 @@
+defmodule Plausible.Workers.ExecuteTeamDeletions do
+ @moduledoc """
+ Executes deletions for schedules whose reminder has been sent and whose
+ deletion_date has arrived: deletes the team's sites (and queues their
+ stats for removal) - the team itself and its settings/subscription
+ history are left intact. Marks the schedule completed.
+
+ Re-checks each team's subscription right before acting, via
+ `cancel_for_team` - so a just-reactivated team doesn't have its sites
+ deleted.
+ """
+
+ use Oban.Worker, queue: :execute_team_deletions, max_attempts: 1
+
+ alias Plausible.Repo
+ alias Plausible.TeamDeletionSchedules
+ alias Plausible.Teams
+
+ @spec telemetry_run_event() :: [atom()]
+ def telemetry_run_event(), do: [:plausible, :execute_team_deletions, :run]
+
+ @spec telemetry_sites_deleted_event() :: [atom()]
+ def telemetry_sites_deleted_event(), do: [:plausible, :execute_team_deletions, :sites_deleted]
+
+ @impl Oban.Worker
+ def perform(_job, today \\ Date.utc_today()) do
+ for schedule <- TeamDeletionSchedules.due_for_deletion(today) do
+ team = schedule.team
+
+ if TeamDeletionSchedules.cancel_for_team(team) == :no_schedule do
+ execute(schedule, team)
+ else
+ report(schedule, :cancelled)
+ end
+ end
+
+ :ok
+ end
+
+ defp execute(schedule, team) do
+ Repo.transaction(fn ->
+ sites = Teams.owned_sites(team)
+
+ for site <- sites do
+ Plausible.Site.Removal.run(site, reason: schedule.category)
+ end
+
+ TeamDeletionSchedules.mark_completed(schedule, report_if_invalid?: true)
+
+ report(schedule, :executed)
+
+ :telemetry.execute(telemetry_sites_deleted_event(), %{count: length(sites)}, %{
+ category: schedule.category
+ })
+ end)
+ end
+
+ defp report(schedule, outcome) do
+ :telemetry.execute(telemetry_run_event(), %{count: 1}, %{
+ outcome: outcome,
+ category: schedule.category
+ })
+ end
+end
diff --git a/lib/workers/scan_inactive_teams.ex b/lib/workers/scan_inactive_teams.ex
new file mode 100644
index 0000000000..eb05721713
--- /dev/null
+++ b/lib/workers/scan_inactive_teams.ex
@@ -0,0 +1,24 @@
+defmodule Plausible.Workers.ScanInactiveTeams do
+ @moduledoc """
+ Finds teams whose trial or subscription has expired and schedules them
+ for the stats deletion pipeline. Reactivation is handled
+ separately and immediately, via `Plausible.TeamDeletionSchedules.cancel_for_team/1`
+ called from `Plausible.Billing`'s webhook handlers.
+ """
+
+ use Oban.Worker, queue: :scan_inactive_teams
+
+ alias Plausible.TeamDeletionSchedules
+
+ @spec telemetry_run_event() :: [atom()]
+ def telemetry_run_event(), do: [:plausible, :scan_inactive_teams, :run]
+
+ @impl Oban.Worker
+ def perform(_job) do
+ created = TeamDeletionSchedules.sync_eligible()
+
+ :telemetry.execute(telemetry_run_event(), %{created: created})
+
+ :ok
+ end
+end
diff --git a/lib/workers/send_deletion_notifications.ex b/lib/workers/send_deletion_notifications.ex
new file mode 100644
index 0000000000..bc4ccedd5c
--- /dev/null
+++ b/lib/workers/send_deletion_notifications.ex
@@ -0,0 +1,108 @@
+defmodule Plausible.Workers.SendDeletionNotifications do
+ @moduledoc """
+ Sends the deletion pipeline reminder notices
+ (backlog trials, and all churned subscriptions) - steady state
+ teams get notified via AcceptTrafficUntil
+
+ Re-checks each team's subscription right before firing, via
+ `cancel_for_team` - so that just reactivated team, doesn't get notified.
+ """
+
+ use Oban.Worker, queue: :deletion_notification_emails, max_attempts: 1
+
+ alias Plausible.TeamDeletionSchedules
+ alias Plausible.Teams
+ alias Plausible.Teams.DeletionSchedule
+
+ @spec telemetry_run_event() :: [atom()]
+ def telemetry_run_event(), do: [:plausible, :send_deletion_notifications, :run]
+
+ @impl Oban.Worker
+ def perform(_job, today \\ Date.utc_today()) do
+ # Anchor to `today`
+ now = NaiveDateTime.new!(today, ~T[00:00:00])
+
+ send_first_notices(today, now)
+ send_reminders(today, now)
+
+ :ok
+ end
+
+ defp send_first_notices(today, now) do
+ for schedule <- TeamDeletionSchedules.due_for_first_notice(today) do
+ send_first_notice(schedule, now)
+ end
+ end
+
+ defp send_first_notice(schedule, now) do
+ team = schedule.team
+
+ if TeamDeletionSchedules.cancel_for_team(team) == :no_schedule do
+ # Finalize the schedule (which, for backlog rows, anchors deletion_date
+ # to `now`) before composing the email, so the date we tell the
+ # customer matches the date we actually persist.
+ case TeamDeletionSchedules.mark_first_notice_sent(schedule,
+ now: now,
+ report_if_invalid?: true
+ ) do
+ {:ok, schedule} ->
+ summary = sites_summary(team)
+
+ for recipient <- team.owners ++ team.billing_members do
+ recipient
+ |> PlausibleWeb.Email.deletion_full_notice_email(team, schedule, summary)
+ |> Plausible.Mailer.send()
+ end
+
+ report(schedule, :first_notice, :sent)
+
+ {:error, _} ->
+ :ok
+ end
+ else
+ report(schedule, :first_notice, :cancelled)
+ end
+ end
+
+ defp send_reminders(today, now) do
+ for schedule <- TeamDeletionSchedules.due_for_reminder(today) do
+ send_reminder(schedule, now)
+ end
+ end
+
+ defp send_reminder(schedule, now) do
+ team = schedule.team
+
+ if TeamDeletionSchedules.cancel_for_team(team) == :no_schedule do
+ summary = sites_summary(team)
+
+ for recipient <- team.owners ++ team.billing_members do
+ recipient
+ |> PlausibleWeb.Email.deletion_reminder_email(team, schedule, summary)
+ |> Plausible.Mailer.send()
+ end
+
+ TeamDeletionSchedules.mark_reminder_sent(schedule, now: now, report_if_invalid?: true)
+ report(schedule, :reminder, :sent)
+ else
+ report(schedule, :reminder, :cancelled)
+ end
+ end
+
+ defp report(schedule, stage, outcome) do
+ :telemetry.execute(telemetry_run_event(), %{count: 1}, %{
+ stage: stage,
+ outcome: outcome,
+ category: schedule.category
+ })
+ end
+
+ @spec sites_summary(Teams.Team.t()) :: %{domains: [String.t()], more_count: non_neg_integer()}
+ def sites_summary(team) do
+ limit = DeletionSchedule.notification_site_list_limit()
+ domains = team |> Teams.owned_sites(limit) |> Enum.map(& &1.domain)
+ total = Teams.owned_sites_count(team)
+
+ %{domains: domains, more_count: max(total - length(domains), 0)}
+ end
+end
diff --git a/lib/workers/unsnooze_team_deletions.ex b/lib/workers/unsnooze_team_deletions.ex
new file mode 100644
index 0000000000..9f4c25031d
--- /dev/null
+++ b/lib/workers/unsnooze_team_deletions.ex
@@ -0,0 +1,26 @@
+defmodule Plausible.Workers.UnsnoozeTeamDeletions do
+ @moduledoc """
+ Restarts the notice cycle for schedules whose snooze has lapsed: still
+ `:snoozed`, past their `snoozed_until` date.
+ """
+
+ use Oban.Worker, queue: :unsnooze_team_deletions, max_attempts: 1
+
+ alias Plausible.TeamDeletionSchedules
+
+ @spec telemetry_run_event() :: [atom()]
+ def telemetry_run_event(), do: [:plausible, :unsnooze_team_deletions, :run]
+
+ @impl Oban.Worker
+ def perform(_job, today \\ Date.utc_today()) do
+ due = TeamDeletionSchedules.due_for_unsnooze(today)
+
+ for schedule <- due do
+ TeamDeletionSchedules.unsnooze(schedule, today: today, report_if_invalid?: true)
+ end
+
+ :telemetry.execute(telemetry_run_event(), %{count: length(due)})
+
+ :ok
+ end
+end
diff --git a/test/plausible/billing/billing_test.exs b/test/plausible/billing/billing_test.exs
index a53815b798..92bf4de6c0 100644
--- a/test/plausible/billing/billing_test.exs
+++ b/test/plausible/billing/billing_test.exs
@@ -436,6 +436,39 @@ defmodule Plausible.BillingTest do
refute Repo.reload!(team).locked
end
+ test "cancels a pending team deletion schedule if subscription is changed from past_due to active" do
+ user = new_user()
+ subscribe_to_growth_plan(user, status: Subscription.Status.past_due())
+ team = team_of(user)
+ schedule = insert(:team_deletion_schedule, team: team, status: :first_notice_sent)
+
+ @subscription_updated_params
+ |> Map.merge(%{
+ "subscription_id" => subscription_of(user).paddle_subscription_id,
+ "passthrough" => "ee:true;user:#{user.id};team:#{team.id}",
+ "old_status" => "past_due"
+ })
+ |> Billing.subscription_updated()
+
+ assert Repo.reload!(schedule).status == :cancelled
+ end
+
+ test "does not cancel a pending team deletion schedule if the update doesn't make the subscription active" do
+ user = new_user()
+ subscribe_to_growth_plan(user, status: Subscription.Status.past_due())
+ team = team_of(user)
+ schedule = insert(:team_deletion_schedule, team: team, status: :first_notice_sent)
+
+ %{@subscription_updated_params | "old_status" => "past_due", "status" => "paused"}
+ |> Map.merge(%{
+ "subscription_id" => subscription_of(user).paddle_subscription_id,
+ "passthrough" => "ee:true;user:#{user.id};team:#{team.id}"
+ })
+ |> Billing.subscription_updated()
+
+ assert Repo.reload!(schedule).status == :first_notice_sent
+ end
+
@tag :ee_only
test "updates accept_traffic_until" do
user = new_user() |> subscribe_to_growth_plan()
@@ -642,6 +675,19 @@ defmodule Plausible.BillingTest do
assert res == {:ok, nil}
end
+
+ test "cancels a pending team deletion schedule" do
+ user = new_user() |> subscribe_to_growth_plan()
+ team = team_of(user)
+ schedule = insert(:team_deletion_schedule, team: team, status: :first_notice_sent)
+
+ Billing.subscription_payment_succeeded(%{
+ "alert_name" => "subscription_payment_succeeded",
+ "subscription_id" => subscription_of(user).paddle_subscription_id
+ })
+
+ assert Repo.reload!(schedule).status == :cancelled
+ end
end
describe "change_plan" do
diff --git a/test/plausible/site/site_removal_test.exs b/test/plausible/site/site_removal_test.exs
index 11f7cfa15f..2aff9340de 100644
--- a/test/plausible/site/site_removal_test.exs
+++ b/test/plausible/site/site_removal_test.exs
@@ -40,6 +40,15 @@ defmodule Plausible.Site.SiteRemovalTest do
assert Repo.get_by(PendingStatsDeletion, site_id: site.id)
end
+ test "site deletion accepts an explicit reason for the pending stats deletion" do
+ site = new_site()
+
+ assert {:ok, context} = Removal.run(site, reason: :expired_trial)
+
+ assert context.pending_stats_deletion.reason == :expired_trial
+ assert Repo.get_by(PendingStatsDeletion, site_id: site.id, reason: :expired_trial)
+ end
+
test "site deletion prunes team guest memberships" do
owner = new_user()
site = new_site(owner: owner)
diff --git a/test/plausible/team_deletion_schedule_test.exs b/test/plausible/team_deletion_schedule_test.exs
new file mode 100644
index 0000000000..8903e2281c
--- /dev/null
+++ b/test/plausible/team_deletion_schedule_test.exs
@@ -0,0 +1,280 @@
+defmodule Plausible.TeamDeletionScheduleTest do
+ use Plausible.DataCase, async: true
+
+ on_ee do
+ alias Plausible.TeamDeletionSchedule
+
+ describe "schema" do
+ test "inserts a valid schedule with expected defaults" do
+ team = insert(:team)
+ today = Date.utc_today()
+ deletion_date = Date.shift(today, day: 60)
+
+ assert {:ok, schedule} =
+ %TeamDeletionSchedule{
+ team_id: team.id,
+ category: :expired_trial,
+ expiry_date: today,
+ deletion_date: deletion_date,
+ first_notice_due_date: Date.shift(deletion_date, day: -30)
+ }
+ |> Repo.insert()
+
+ assert schedule.status == :scheduled
+ assert schedule.is_backlog == false
+ assert is_nil(schedule.first_notice_sent_at)
+ assert is_nil(schedule.reminder_sent_at)
+ assert is_nil(schedule.snoozed_until)
+ end
+
+ test "accepts both categories" do
+ team1 = insert(:team)
+ team2 = insert(:team)
+ today = Date.utc_today()
+
+ assert {:ok, %{category: :expired_trial}} =
+ Repo.insert(%TeamDeletionSchedule{
+ team_id: team1.id,
+ category: :expired_trial,
+ expiry_date: today,
+ deletion_date: Date.shift(today, day: 60),
+ first_notice_due_date: Date.shift(today, day: 30)
+ })
+
+ assert {:ok, %{category: :churned_subscription}} =
+ Repo.insert(%TeamDeletionSchedule{
+ team_id: team2.id,
+ category: :churned_subscription,
+ expiry_date: today,
+ deletion_date: Date.shift(today, day: 180),
+ first_notice_due_date: Date.shift(today, day: 150)
+ })
+ end
+
+ test "rejects an invalid category" do
+ team = insert(:team)
+ today = Date.utc_today()
+
+ assert_raise Ecto.ChangeError, fn ->
+ Repo.insert(%TeamDeletionSchedule{
+ team_id: team.id,
+ category: :not_a_real_category,
+ expiry_date: today,
+ deletion_date: today,
+ first_notice_due_date: today
+ })
+ end
+ end
+
+ test "rejects an invalid status" do
+ team = insert(:team)
+ today = Date.utc_today()
+
+ assert_raise Ecto.ChangeError, fn ->
+ Repo.insert(%TeamDeletionSchedule{
+ team_id: team.id,
+ category: :expired_trial,
+ status: :not_a_real_status,
+ expiry_date: today,
+ deletion_date: today,
+ first_notice_due_date: today
+ })
+ end
+ end
+
+ test "categories/0 and statuses/0 expose the valid enum values" do
+ assert TeamDeletionSchedule.categories() == [:expired_trial, :churned_subscription]
+
+ assert TeamDeletionSchedule.statuses() == [
+ :scheduled,
+ :first_notice_sent,
+ :reminder_sent,
+ :completed,
+ :cancelled,
+ :snoozed
+ ]
+ end
+
+ test "terminal_statuses/0 and active_statuses/0 partition statuses/0" do
+ terminal = TeamDeletionSchedule.terminal_statuses()
+ active = TeamDeletionSchedule.active_statuses()
+
+ assert Enum.sort(terminal ++ active) == Enum.sort(TeamDeletionSchedule.statuses())
+ end
+ end
+
+ describe "crm_changeset/2" do
+ test "is valid for a snoozed_until date in the future" do
+ schedule = insert(:team_deletion_schedule, status: :reminder_sent)
+ until_date = Date.shift(Date.utc_today(), day: 1)
+
+ changeset =
+ TeamDeletionSchedule.crm_changeset(schedule, %{
+ "snoozed_until" => Date.to_iso8601(until_date),
+ "snooze_note" => "customer asked for time"
+ })
+
+ assert changeset.valid?
+ assert Ecto.Changeset.get_change(changeset, :snoozed_until) == until_date
+ assert Ecto.Changeset.get_change(changeset, :snooze_note) == "customer asked for time"
+ end
+
+ test "does not require a note" do
+ schedule = insert(:team_deletion_schedule, status: :reminder_sent)
+ until_date = Date.shift(Date.utc_today(), day: 1)
+
+ changeset =
+ TeamDeletionSchedule.crm_changeset(schedule, %{
+ "snoozed_until" => Date.to_iso8601(until_date)
+ })
+
+ assert changeset.valid?
+ end
+
+ test "requires snoozed_until" do
+ schedule = insert(:team_deletion_schedule, status: :reminder_sent)
+
+ changeset = TeamDeletionSchedule.crm_changeset(schedule, %{})
+
+ refute changeset.valid?
+ assert {"can't be blank", _} = changeset.errors[:snoozed_until]
+ end
+
+ test "rejects a snoozed_until of today" do
+ schedule = insert(:team_deletion_schedule, status: :reminder_sent)
+
+ changeset =
+ TeamDeletionSchedule.crm_changeset(schedule, %{
+ "snoozed_until" => Date.to_iso8601(Date.utc_today())
+ })
+
+ refute changeset.valid?
+ assert {"must be in the future", _} = changeset.errors[:snoozed_until]
+ end
+
+ test "rejects a snoozed_until in the past" do
+ schedule = insert(:team_deletion_schedule, status: :reminder_sent)
+
+ changeset =
+ TeamDeletionSchedule.crm_changeset(schedule, %{
+ "snoozed_until" => Date.to_iso8601(Date.shift(Date.utc_today(), day: -1))
+ })
+
+ refute changeset.valid?
+ assert {"must be in the future", _} = changeset.errors[:snoozed_until]
+ end
+
+ test "does not touch status" do
+ schedule = insert(:team_deletion_schedule, status: :reminder_sent)
+ until_date = Date.shift(Date.utc_today(), day: 1)
+
+ changeset =
+ TeamDeletionSchedule.crm_changeset(schedule, %{
+ "snoozed_until" => Date.to_iso8601(until_date)
+ })
+
+ refute Ecto.Changeset.get_change(changeset, :status)
+ end
+ end
+
+ describe "team_id foreign key" do
+ test "deleting the team cascades to the schedule" do
+ schedule = insert(:team_deletion_schedule)
+
+ Repo.delete!(schedule.team)
+
+ refute Repo.get(TeamDeletionSchedule, schedule.id)
+ end
+
+ test "rejects a schedule for a non-existent team" do
+ today = Date.utc_today()
+
+ assert_raise Ecto.ConstraintError, fn ->
+ Repo.insert!(%TeamDeletionSchedule{
+ team_id: -1,
+ category: :expired_trial,
+ expiry_date: today,
+ deletion_date: today,
+ first_notice_due_date: today
+ })
+ end
+ end
+ end
+
+ describe "one_active_schedule_per_team index" do
+ test "rejects a second active schedule for the same team" do
+ team = insert(:team)
+ today = Date.utc_today()
+
+ base = %{
+ team_id: team.id,
+ category: :expired_trial,
+ expiry_date: today,
+ deletion_date: Date.shift(today, day: 60),
+ first_notice_due_date: Date.shift(today, day: 30)
+ }
+
+ assert {:ok, _} = Repo.insert(struct(TeamDeletionSchedule, base))
+
+ assert_raise Ecto.ConstraintError, fn ->
+ Repo.insert!(struct(TeamDeletionSchedule, Map.put(base, :status, :first_notice_sent)))
+ end
+ end
+
+ test "allows a new schedule once the previous one is cancelled" do
+ team = insert(:team)
+ today = Date.utc_today()
+
+ base = %{
+ team_id: team.id,
+ category: :expired_trial,
+ expiry_date: today,
+ deletion_date: Date.shift(today, day: 60),
+ first_notice_due_date: Date.shift(today, day: 30)
+ }
+
+ assert {:ok, _} =
+ struct(TeamDeletionSchedule, Map.put(base, :status, :cancelled))
+ |> Repo.insert()
+
+ assert {:ok, _} = Repo.insert(struct(TeamDeletionSchedule, base))
+ end
+
+ test "allows a new schedule once the previous one is completed" do
+ team = insert(:team)
+ today = Date.utc_today()
+
+ base = %{
+ team_id: team.id,
+ category: :churned_subscription,
+ expiry_date: today,
+ deletion_date: Date.shift(today, day: 180),
+ first_notice_due_date: Date.shift(today, day: 150)
+ }
+
+ assert {:ok, _} =
+ struct(TeamDeletionSchedule, Map.put(base, :status, :completed))
+ |> Repo.insert()
+
+ assert {:ok, _} = Repo.insert(struct(TeamDeletionSchedule, base))
+ end
+
+ test "allows active schedules for different teams" do
+ team1 = insert(:team)
+ team2 = insert(:team)
+ today = Date.utc_today()
+
+ for team <- [team1, team2] do
+ assert {:ok, _} =
+ Repo.insert(%TeamDeletionSchedule{
+ team_id: team.id,
+ category: :expired_trial,
+ expiry_date: today,
+ deletion_date: Date.shift(today, day: 60),
+ first_notice_due_date: Date.shift(today, day: 30)
+ })
+ end
+ end
+ end
+ end
+end
diff --git a/test/plausible/team_deletion_schedules_test.exs b/test/plausible/team_deletion_schedules_test.exs
new file mode 100644
index 0000000000..4a61b47aac
--- /dev/null
+++ b/test/plausible/team_deletion_schedules_test.exs
@@ -0,0 +1,843 @@
+defmodule Plausible.TeamDeletionSchedulesTest do
+ use Plausible.DataCase, async: true
+
+ on_ee do
+ require Plausible.Billing.Subscription.Status
+
+ alias Plausible.Billing.Subscription
+ alias Plausible.TeamDeletionSchedule
+ alias Plausible.TeamDeletionSchedules
+
+ @today ~D[2026-08-20]
+
+ describe "sync_eligible/1 - expired trials" do
+ test "schedules a team whose trial expired with no subscription" do
+ team = insert(:team, trial_expiry_date: Date.shift(@today, day: -1))
+ new_site(team: team)
+
+ assert TeamDeletionSchedules.sync_eligible(@today) == 1
+
+ schedule = Repo.get_by!(TeamDeletionSchedule, team_id: team.id)
+ assert schedule.category == :expired_trial
+ assert schedule.expiry_date == team.trial_expiry_date
+ assert schedule.deletion_date == Date.shift(team.trial_expiry_date, day: 60)
+ assert schedule.status == :scheduled
+ end
+
+ test "does not schedule a team whose trial has not expired yet" do
+ insert(:team, trial_expiry_date: Date.shift(@today, day: 1))
+
+ assert TeamDeletionSchedules.sync_eligible(@today) == 0
+ assert Repo.aggregate(TeamDeletionSchedule, :count) == 0
+ end
+
+ test "does not schedule a team whose trial expires today" do
+ insert(:team, trial_expiry_date: @today)
+
+ assert TeamDeletionSchedules.sync_eligible(@today) == 0
+ end
+
+ test "marks a long-expired trial as backlog, spread across the release window" do
+ team = insert(:team, trial_expiry_date: Date.shift(@today, day: -400))
+ new_site(team: team)
+
+ assert TeamDeletionSchedules.sync_eligible(@today) == 1
+
+ schedule = Repo.get_by!(TeamDeletionSchedule, team_id: team.id)
+ window = Plausible.Teams.DeletionSchedule.backlog_release_window_days()
+
+ assert schedule.is_backlog
+ assert schedule.first_notice_due_date == Date.add(@today, rem(team.id, window))
+ end
+
+ test "spreads multiple backlog rows across the release window based on team_id" do
+ teams =
+ for _ <- 1..5 do
+ team = insert(:team, trial_expiry_date: Date.shift(@today, day: -400))
+ new_site(team: team)
+ team
+ end
+
+ assert TeamDeletionSchedules.sync_eligible(@today) == 5
+
+ window = Plausible.Teams.DeletionSchedule.backlog_release_window_days()
+
+ due_dates =
+ for team <- teams do
+ schedule = Repo.get_by!(TeamDeletionSchedule, team_id: team.id)
+ assert schedule.first_notice_due_date == Date.add(@today, rem(team.id, window))
+ schedule.first_notice_due_date
+ end
+
+ assert length(Enum.uniq(due_dates)) > 1
+ end
+
+ test "does not mark a recently-expired trial as backlog" do
+ team = insert(:team, trial_expiry_date: Date.shift(@today, day: -1))
+ new_site(team: team)
+
+ assert TeamDeletionSchedules.sync_eligible(@today) == 1
+
+ schedule = Repo.get_by!(TeamDeletionSchedule, team_id: team.id)
+ refute schedule.is_backlog
+ assert schedule.first_notice_due_date == Date.shift(team.trial_expiry_date, day: 30)
+ end
+
+ test "does not schedule a team with an expired trial but no sites" do
+ insert(:team, trial_expiry_date: Date.shift(@today, day: -1))
+
+ assert TeamDeletionSchedules.sync_eligible(@today) == 0
+ end
+ end
+
+ describe "sync_eligible/1 - churned subscriptions" do
+ test "schedules a team with a deleted subscription past its paid period" do
+ team = insert(:team)
+ new_site(team: team)
+
+ insert(:subscription,
+ team: team,
+ status: Subscription.Status.deleted(),
+ next_bill_date: Date.shift(@today, day: -1)
+ )
+
+ assert TeamDeletionSchedules.sync_eligible(@today) == 1
+
+ schedule = Repo.get_by!(TeamDeletionSchedule, team_id: team.id)
+ assert schedule.category == :churned_subscription
+ assert schedule.deletion_date == Date.shift(schedule.expiry_date, day: 180)
+ end
+
+ test "schedules a team with a paused subscription past its paid period" do
+ team = insert(:team)
+ new_site(team: team)
+
+ insert(:subscription,
+ team: team,
+ status: Subscription.Status.paused(),
+ next_bill_date: Date.shift(@today, day: -1)
+ )
+
+ assert TeamDeletionSchedules.sync_eligible(@today) == 1
+
+ assert Repo.get_by(TeamDeletionSchedule,
+ team_id: team.id,
+ category: :churned_subscription
+ )
+ end
+
+ test "does not schedule a churned subscription team with no sites" do
+ team = insert(:team)
+
+ insert(:subscription,
+ team: team,
+ status: Subscription.Status.deleted(),
+ next_bill_date: Date.shift(@today, day: -1)
+ )
+
+ assert TeamDeletionSchedules.sync_eligible(@today) == 0
+ end
+
+ test "does not schedule a subscription whose paid period ends today" do
+ team = insert(:team)
+
+ insert(:subscription,
+ team: team,
+ status: Subscription.Status.deleted(),
+ next_bill_date: @today
+ )
+
+ assert TeamDeletionSchedules.sync_eligible(@today) == 0
+ end
+
+ test "does not schedule a team whose deleted subscription hasn't lapsed yet" do
+ team = insert(:team)
+
+ insert(:subscription,
+ team: team,
+ status: Subscription.Status.deleted(),
+ next_bill_date: Date.shift(@today, day: 1)
+ )
+
+ assert TeamDeletionSchedules.sync_eligible(@today) == 0
+ end
+
+ test "does not schedule a team with an active subscription" do
+ team = insert(:team)
+
+ insert(:subscription,
+ team: team,
+ status: Subscription.Status.active(),
+ next_bill_date: Date.shift(@today, day: 30)
+ )
+
+ assert TeamDeletionSchedules.sync_eligible(@today) == 0
+ end
+
+ test "does not schedule a team with a past_due subscription" do
+ team = insert(:team)
+
+ insert(:subscription,
+ team: team,
+ status: Subscription.Status.past_due(),
+ next_bill_date: Date.shift(@today, day: -10)
+ )
+
+ assert TeamDeletionSchedules.sync_eligible(@today) == 0
+ end
+
+ test "never schedules a free_10k plan even if marked deleted" do
+ team = insert(:team)
+
+ insert(:subscription,
+ team: team,
+ status: Subscription.Status.deleted(),
+ paddle_plan_id: "free_10k",
+ next_bill_date: Date.shift(@today, day: -400)
+ )
+
+ assert TeamDeletionSchedules.sync_eligible(@today) == 0
+ end
+ end
+
+ describe "sync_eligible/1 - permanent exclusions" do
+ test "excludes enterprise teams even with an expired trial" do
+ team = insert(:team, trial_expiry_date: Date.shift(@today, day: -1))
+ insert(:enterprise_plan, team: team)
+
+ assert TeamDeletionSchedules.sync_eligible(@today) == 0
+ end
+ end
+
+ describe "sync_eligible/1 - idempotency" do
+ test "does not create a duplicate schedule on a second run" do
+ team = insert(:team, trial_expiry_date: Date.shift(@today, day: -1))
+ new_site(team: team)
+
+ assert TeamDeletionSchedules.sync_eligible(@today) == 1
+ assert TeamDeletionSchedules.sync_eligible(@today) == 0
+
+ assert Repo.aggregate(TeamDeletionSchedule, :count) == 1
+ end
+
+ test "does not schedule a team that already has an active schedule" do
+ team = insert(:team, trial_expiry_date: Date.shift(@today, day: -1))
+ insert(:team_deletion_schedule, team: team, status: :first_notice_sent)
+
+ assert TeamDeletionSchedules.sync_eligible(@today) == 0
+ end
+
+ test "does not re-schedule a completed team with no sites left to delete" do
+ team = insert(:team, trial_expiry_date: Date.shift(@today, day: -1))
+ insert(:team_deletion_schedule, team: team, status: :completed)
+
+ assert TeamDeletionSchedules.sync_eligible(@today) == 0
+ end
+
+ test "re-schedules a completed team if it still has sites (e.g. a partial deletion retry)" do
+ team = insert(:team, trial_expiry_date: Date.shift(@today, day: -1))
+ new_site(team: team)
+ insert(:team_deletion_schedule, team: team, status: :completed)
+
+ assert TeamDeletionSchedules.sync_eligible(@today) == 1
+ end
+ end
+
+ describe "cancel_for_team/1" do
+ test "cancels an active schedule when the team has an active subscription" do
+ team = insert(:team)
+ schedule = insert(:team_deletion_schedule, team: team, status: :scheduled)
+ insert(:subscription, team: team, status: Subscription.Status.active())
+
+ assert TeamDeletionSchedules.cancel_for_team(team) == :ok
+ assert Repo.reload(schedule).status == :cancelled
+ end
+
+ test "cancels an active schedule for a deleted subscription still within its paid period" do
+ team = insert(:team)
+ schedule = insert(:team_deletion_schedule, team: team, status: :first_notice_sent)
+
+ insert(:subscription,
+ team: team,
+ status: Subscription.Status.deleted(),
+ next_bill_date: Date.shift(Date.utc_today(), day: 10)
+ )
+
+ assert TeamDeletionSchedules.cancel_for_team(team) == :ok
+ assert Repo.reload(schedule).status == :cancelled
+ end
+
+ test "does not cancel when the team has no subscription and its trial is still expired" do
+ team = insert(:team, trial_expiry_date: Date.shift(Date.utc_today(), day: -1))
+ schedule = insert(:team_deletion_schedule, team: team, status: :scheduled)
+
+ assert TeamDeletionSchedules.cancel_for_team(team) == :no_schedule
+ assert Repo.reload(schedule).status == :scheduled
+ end
+
+ test "cancels when the team has no subscription but its trial is no longer expired" do
+ team = insert(:team, trial_expiry_date: Date.shift(Date.utc_today(), day: 30))
+ schedule = insert(:team_deletion_schedule, team: team, status: :scheduled)
+
+ assert TeamDeletionSchedules.cancel_for_team(team) == :ok
+ assert Repo.reload(schedule).status == :cancelled
+ end
+
+ test "cancels when the team's trial_expiry_date is today (no longer counts as expired)" do
+ team = insert(:team, trial_expiry_date: Date.utc_today())
+ schedule = insert(:team_deletion_schedule, team: team, status: :scheduled)
+
+ assert TeamDeletionSchedules.cancel_for_team(team) == :ok
+ assert Repo.reload(schedule).status == :cancelled
+ end
+
+ test "cancels when the team has no subscription and no trial_expiry_date at all" do
+ team = insert(:team, trial_expiry_date: nil)
+ schedule = insert(:team_deletion_schedule, team: team, status: :scheduled)
+
+ assert TeamDeletionSchedules.cancel_for_team(team) == :ok
+ assert Repo.reload(schedule).status == :cancelled
+ end
+
+ test "does not cancel for a paused subscription" do
+ team = insert(:team)
+ schedule = insert(:team_deletion_schedule, team: team, status: :scheduled)
+ insert(:subscription, team: team, status: Subscription.Status.paused())
+
+ assert TeamDeletionSchedules.cancel_for_team(team) == :no_schedule
+ assert Repo.reload(schedule).status == :scheduled
+ end
+
+ test "does not cancel for a deleted subscription past its paid period" do
+ team = insert(:team)
+ schedule = insert(:team_deletion_schedule, team: team, status: :scheduled)
+
+ insert(:subscription,
+ team: team,
+ status: Subscription.Status.deleted(),
+ next_bill_date: Date.shift(Date.utc_today(), day: -1)
+ )
+
+ assert TeamDeletionSchedules.cancel_for_team(team) == :no_schedule
+ assert Repo.reload(schedule).status == :scheduled
+ end
+
+ test "leaves an already-cancelled or already-completed schedule untouched" do
+ team1 = insert(:team)
+ team2 = insert(:team)
+ cancelled = insert(:team_deletion_schedule, team: team1, status: :cancelled)
+ completed = insert(:team_deletion_schedule, team: team2, status: :completed)
+
+ insert(:subscription, team: team1, status: Subscription.Status.active())
+ insert(:subscription, team: team2, status: Subscription.Status.active())
+
+ assert TeamDeletionSchedules.cancel_for_team(team1) == :no_schedule
+ assert TeamDeletionSchedules.cancel_for_team(team2) == :no_schedule
+ assert Repo.reload(cancelled).status == :cancelled
+ assert Repo.reload(completed).status == :completed
+ end
+
+ test "is a no-op for a team with no schedule at all" do
+ team = insert(:team)
+ insert(:subscription, team: team, status: Subscription.Status.active())
+
+ assert TeamDeletionSchedules.cancel_for_team(team) == :no_schedule
+ end
+ end
+
+ describe "active_schedule_for_team/1" do
+ test "returns the team's active schedule" do
+ team = insert(:team)
+ schedule = insert(:team_deletion_schedule, team: team, status: :reminder_sent)
+
+ assert result = TeamDeletionSchedules.active_schedule_for_team(team)
+ assert result.id == schedule.id
+ end
+
+ test "returns nil for a team with no schedule at all" do
+ team = insert(:team)
+
+ assert TeamDeletionSchedules.active_schedule_for_team(team) == nil
+ end
+
+ test "returns nil when the team's only schedule is terminal" do
+ team = insert(:team)
+ insert(:team_deletion_schedule, team: team, status: :cancelled)
+
+ assert TeamDeletionSchedules.active_schedule_for_team(team) == nil
+ end
+
+ test "does not return another team's schedule" do
+ team = insert(:team)
+ other_team = insert(:team)
+ insert(:team_deletion_schedule, team: other_team, status: :scheduled)
+
+ assert TeamDeletionSchedules.active_schedule_for_team(team) == nil
+ end
+ end
+
+ describe "transitions/0" do
+ test "matches the schema's known statuses" do
+ transitions = TeamDeletionSchedules.transitions()
+
+ assert Map.keys(transitions) |> Enum.sort() == Enum.sort(TeamDeletionSchedule.statuses())
+
+ for {_from, targets} <- transitions, target <- targets do
+ assert target in TeamDeletionSchedule.statuses()
+ end
+ end
+ end
+
+ describe "mark_first_notice_sent/2" do
+ test "sends the first notice for a steady-state schedule, keeping its deletion_date" do
+ schedule =
+ insert(:team_deletion_schedule,
+ status: :scheduled,
+ is_backlog: false,
+ deletion_date: ~D[2026-10-19]
+ )
+
+ now = ~N[2026-08-20 10:00:00]
+
+ assert {:ok, updated} = TeamDeletionSchedules.mark_first_notice_sent(schedule, now: now)
+ assert updated.status == :first_notice_sent
+ assert updated.first_notice_sent_at == now
+ assert updated.deletion_date == ~D[2026-10-19]
+ end
+
+ test "sends the first notice for a backlog schedule, anchoring deletion_date to now" do
+ schedule =
+ insert(:team_deletion_schedule,
+ status: :scheduled,
+ is_backlog: true,
+ deletion_date: ~D[2026-01-01]
+ )
+
+ now = ~N[2026-08-20 10:00:00]
+
+ assert {:ok, updated} = TeamDeletionSchedules.mark_first_notice_sent(schedule, now: now)
+ assert updated.status == :first_notice_sent
+ assert updated.first_notice_sent_at == now
+
+ assert updated.deletion_date ==
+ Plausible.Teams.DeletionSchedule.backlog_deletion_date(now)
+ end
+
+ test "rejects any status other than :scheduled" do
+ for status <- TeamDeletionSchedule.statuses() -- [:scheduled] do
+ schedule = insert(:team_deletion_schedule, status: status)
+
+ assert TeamDeletionSchedules.mark_first_notice_sent(schedule,
+ now: ~N[2026-08-20 10:00:00]
+ ) ==
+ {:error, {:invalid_transition, status, :first_notice_sent}}
+ end
+ end
+ end
+
+ describe "mark_reminder_sent/2" do
+ test "sends the reminder for a schedule that already sent its first notice" do
+ schedule = insert(:team_deletion_schedule, status: :first_notice_sent)
+ now = ~N[2026-08-20 10:00:00]
+
+ assert {:ok, updated} = TeamDeletionSchedules.mark_reminder_sent(schedule, now: now)
+ assert updated.status == :reminder_sent
+ assert updated.reminder_sent_at == now
+ end
+
+ test "rejects any status other than :first_notice_sent" do
+ for status <- TeamDeletionSchedule.statuses() -- [:first_notice_sent] do
+ schedule = insert(:team_deletion_schedule, status: status)
+
+ assert TeamDeletionSchedules.mark_reminder_sent(schedule, now: ~N[2026-08-20 10:00:00]) ==
+ {:error, {:invalid_transition, status, :reminder_sent}}
+ end
+ end
+ end
+
+ describe "mark_completed/1" do
+ test "completes a schedule that already sent its reminder" do
+ schedule = insert(:team_deletion_schedule, status: :reminder_sent)
+
+ assert {:ok, updated} = TeamDeletionSchedules.mark_completed(schedule)
+ assert updated.status == :completed
+ end
+
+ test "rejects any status other than :reminder_sent" do
+ for status <- TeamDeletionSchedule.statuses() -- [:reminder_sent] do
+ schedule = insert(:team_deletion_schedule, status: status)
+
+ assert TeamDeletionSchedules.mark_completed(schedule) ==
+ {:error, {:invalid_transition, status, :completed}}
+ end
+ end
+ end
+
+ describe "cancel/1" do
+ test "cancels a schedule from any active status" do
+ for status <- [:scheduled, :first_notice_sent, :reminder_sent, :snoozed] do
+ schedule = insert(:team_deletion_schedule, status: status)
+
+ assert {:ok, updated} = TeamDeletionSchedules.cancel(schedule)
+ assert updated.status == :cancelled
+ end
+ end
+
+ test "rejects an already-terminal status" do
+ for status <- [:completed, :cancelled] do
+ schedule = insert(:team_deletion_schedule, status: status)
+
+ assert TeamDeletionSchedules.cancel(schedule) ==
+ {:error, {:invalid_transition, status, :cancelled}}
+ end
+ end
+ end
+
+ describe "snooze/3" do
+ test "snoozes a schedule from any active, not-yet-snoozed status" do
+ for status <- [:scheduled, :first_notice_sent, :reminder_sent] do
+ schedule = insert(:team_deletion_schedule, status: status)
+
+ assert {:ok, updated} =
+ TeamDeletionSchedules.snooze(schedule, ~D[2026-09-20],
+ note: "customer asked for time"
+ )
+
+ assert updated.status == :snoozed
+ assert updated.snoozed_until == ~D[2026-09-20]
+ assert updated.snooze_note == "customer asked for time"
+ end
+ end
+
+ test "defaults the note to nil" do
+ schedule = insert(:team_deletion_schedule, status: :scheduled)
+
+ assert {:ok, updated} = TeamDeletionSchedules.snooze(schedule, ~D[2026-09-20])
+ assert updated.snooze_note == nil
+ end
+
+ test "rejects an already-snoozed or terminal status" do
+ for status <- [:snoozed, :completed, :cancelled] do
+ schedule = insert(:team_deletion_schedule, status: status)
+
+ assert TeamDeletionSchedules.snooze(schedule, ~D[2026-09-20]) ==
+ {:error, {:invalid_transition, status, :snoozed}}
+ end
+ end
+ end
+
+ describe "unsnooze/2" do
+ test "restarts a snoozed schedule as a fresh backlog row due today" do
+ schedule =
+ insert(:team_deletion_schedule,
+ status: :snoozed,
+ is_backlog: false,
+ snoozed_until: ~D[2026-09-20],
+ snooze_note: "customer asked for time",
+ first_notice_sent_at: ~N[2026-07-01 10:00:00],
+ reminder_sent_at: ~N[2026-07-20 10:00:00]
+ )
+
+ today = ~D[2026-08-20]
+
+ assert {:ok, updated} = TeamDeletionSchedules.unsnooze(schedule, today: today)
+ assert updated.status == :scheduled
+ assert updated.is_backlog
+ assert updated.first_notice_due_date == today
+ assert updated.first_notice_sent_at == nil
+ assert updated.reminder_sent_at == nil
+ assert updated.snoozed_until == nil
+ assert updated.snooze_note == nil
+ end
+
+ test "rejects any status other than :snoozed" do
+ for status <- TeamDeletionSchedule.statuses() -- [:snoozed] do
+ schedule = insert(:team_deletion_schedule, status: status)
+
+ assert TeamDeletionSchedules.unsnooze(schedule, today: ~D[2026-08-20]) ==
+ {:error, {:invalid_transition, status, :scheduled}}
+ end
+ end
+ end
+
+ describe "report_if_invalid? option" do
+ setup do
+ Plausible.Test.Support.Sentry.setup(self())
+ :ok
+ end
+
+ test "does not report to Sentry by default" do
+ schedule = insert(:team_deletion_schedule, status: :completed)
+
+ assert TeamDeletionSchedules.cancel(schedule) ==
+ {:error, {:invalid_transition, :completed, :cancelled}}
+
+ assert [] = Sentry.Test.pop_sentry_reports()
+ end
+
+ test "reports an invalid transition to Sentry when set" do
+ schedule = insert(:team_deletion_schedule, status: :completed)
+
+ assert TeamDeletionSchedules.cancel(schedule, report_if_invalid?: true) ==
+ {:error, {:invalid_transition, :completed, :cancelled}}
+
+ assert [report] = Sentry.Test.pop_sentry_reports()
+ assert report.message.formatted == "Invalid team deletion schedule transition"
+ assert report.extra.from == :completed
+ assert report.extra.to == :cancelled
+ assert report.extra.team_id == schedule.team_id
+ end
+
+ test "does not report a successful transition even when set" do
+ schedule = insert(:team_deletion_schedule, status: :scheduled)
+
+ assert {:ok, _} = TeamDeletionSchedules.cancel(schedule, report_if_invalid?: true)
+
+ assert [] = Sentry.Test.pop_sentry_reports()
+ end
+ end
+
+ describe "due_for_first_notice/1" do
+ test "returns a scheduled row whose first_notice_due_date has arrived" do
+ owner = new_user()
+ new_site(owner: owner)
+
+ schedule =
+ insert(:team_deletion_schedule,
+ team: team_of(owner),
+ status: :scheduled,
+ first_notice_due_date: @today
+ )
+
+ [due] = TeamDeletionSchedules.due_for_first_notice(@today)
+ assert due.id == schedule.id
+ assert [%Plausible.Auth.User{}] = due.team.owners
+ end
+
+ test "returns a row whose first_notice_due_date is overdue (missed run catch-up)" do
+ schedule =
+ insert(:team_deletion_schedule,
+ status: :scheduled,
+ first_notice_due_date: Date.shift(@today, day: -3)
+ )
+
+ assert [%{id: id}] = TeamDeletionSchedules.due_for_first_notice(@today)
+ assert id == schedule.id
+ end
+
+ test "does not return a row whose first_notice_due_date is still in the future" do
+ insert(:team_deletion_schedule, status: :scheduled, first_notice_due_date: @today)
+
+ assert TeamDeletionSchedules.due_for_first_notice(Date.shift(@today, day: -1)) == []
+ end
+
+ test "does not return a row that already had its first notice sent" do
+ insert(:team_deletion_schedule,
+ status: :first_notice_sent,
+ first_notice_due_date: @today
+ )
+
+ assert TeamDeletionSchedules.due_for_first_notice(@today) == []
+ end
+
+ test "does not return a currently-snoozed row" do
+ insert(:team_deletion_schedule,
+ status: :snoozed,
+ first_notice_due_date: @today,
+ snoozed_until: Date.shift(@today, day: 1)
+ )
+
+ assert TeamDeletionSchedules.due_for_first_notice(@today) == []
+ end
+
+ test "returns a row whose snooze has already lapsed" do
+ schedule =
+ insert(:team_deletion_schedule,
+ status: :scheduled,
+ first_notice_due_date: @today,
+ snoozed_until: Date.shift(@today, day: -1)
+ )
+
+ assert [%{id: id}] = TeamDeletionSchedules.due_for_first_notice(@today)
+ assert id == schedule.id
+ end
+ end
+
+ describe "due_for_reminder/1" do
+ test "returns a first_notice_sent row within 5 days of its deletion_date" do
+ schedule =
+ insert(:team_deletion_schedule,
+ status: :first_notice_sent,
+ deletion_date: Date.shift(@today, day: 5)
+ )
+
+ assert [%{id: id}] = TeamDeletionSchedules.due_for_reminder(@today)
+ assert id == schedule.id
+ end
+
+ test "does not return a row whose deletion_date is more than 5 days out" do
+ insert(:team_deletion_schedule,
+ status: :first_notice_sent,
+ deletion_date: Date.shift(@today, day: 6)
+ )
+
+ assert TeamDeletionSchedules.due_for_reminder(@today) == []
+ end
+
+ test "does not return a scheduled (not yet first-notified) row" do
+ insert(:team_deletion_schedule,
+ status: :scheduled,
+ deletion_date: Date.shift(@today, day: 5)
+ )
+
+ assert TeamDeletionSchedules.due_for_reminder(@today) == []
+ end
+
+ test "does not return a currently-snoozed row" do
+ insert(:team_deletion_schedule,
+ status: :snoozed,
+ deletion_date: Date.shift(@today, day: 5),
+ snoozed_until: Date.shift(@today, day: 1)
+ )
+
+ assert TeamDeletionSchedules.due_for_reminder(@today) == []
+ end
+ end
+
+ describe "due_for_deletion/1" do
+ test "returns a reminder_sent row whose deletion_date has arrived" do
+ schedule =
+ insert(:team_deletion_schedule,
+ status: :reminder_sent,
+ deletion_date: @today
+ )
+
+ assert [%{id: id}] = TeamDeletionSchedules.due_for_deletion(@today)
+ assert id == schedule.id
+ end
+
+ test "returns a row whose deletion_date is overdue (missed run catch-up)" do
+ schedule =
+ insert(:team_deletion_schedule,
+ status: :reminder_sent,
+ deletion_date: Date.shift(@today, day: -3)
+ )
+
+ assert [%{id: id}] = TeamDeletionSchedules.due_for_deletion(@today)
+ assert id == schedule.id
+ end
+
+ test "does not return a row whose deletion_date is still in the future" do
+ insert(:team_deletion_schedule, status: :reminder_sent, deletion_date: @today)
+
+ assert TeamDeletionSchedules.due_for_deletion(Date.shift(@today, day: -1)) == []
+ end
+
+ test "does not return a row that hasn't had its reminder sent yet" do
+ insert(:team_deletion_schedule, status: :first_notice_sent, deletion_date: @today)
+
+ assert TeamDeletionSchedules.due_for_deletion(@today) == []
+ end
+ end
+
+ describe "due_for_unsnooze/1" do
+ test "returns a snoozed row whose snoozed_until has arrived" do
+ schedule =
+ insert(:team_deletion_schedule, status: :snoozed, snoozed_until: @today)
+
+ assert [%{id: id}] = TeamDeletionSchedules.due_for_unsnooze(@today)
+ assert id == schedule.id
+ end
+
+ test "returns a row whose snoozed_until is overdue (missed run catch-up)" do
+ schedule =
+ insert(:team_deletion_schedule,
+ status: :snoozed,
+ snoozed_until: Date.shift(@today, day: -3)
+ )
+
+ assert [%{id: id}] = TeamDeletionSchedules.due_for_unsnooze(@today)
+ assert id == schedule.id
+ end
+
+ test "does not return a row whose snoozed_until is still in the future" do
+ insert(:team_deletion_schedule,
+ status: :snoozed,
+ snoozed_until: Date.shift(@today, day: 1)
+ )
+
+ assert TeamDeletionSchedules.due_for_unsnooze(@today) == []
+ end
+
+ test "does not return a row that isn't snoozed" do
+ insert(:team_deletion_schedule, status: :reminder_sent, deletion_date: @today)
+
+ assert TeamDeletionSchedules.due_for_unsnooze(@today) == []
+ end
+ end
+
+ describe "pending_steady_state_trials_by_team_id/1" do
+ test "returns a scheduled, non-backlog expired_trial schedule keyed by team_id" do
+ team = insert(:team)
+
+ schedule =
+ insert(:team_deletion_schedule,
+ team: team,
+ category: :expired_trial,
+ status: :scheduled,
+ is_backlog: false
+ )
+
+ team_id = team.id
+
+ assert %{^team_id => result} =
+ TeamDeletionSchedules.pending_steady_state_trials_by_team_id([team.id])
+
+ assert result.id == schedule.id
+ end
+
+ test "excludes a backlog trial schedule" do
+ team = insert(:team)
+
+ insert(:team_deletion_schedule,
+ team: team,
+ category: :expired_trial,
+ status: :scheduled,
+ is_backlog: true
+ )
+
+ assert TeamDeletionSchedules.pending_steady_state_trials_by_team_id([team.id]) == %{}
+ end
+
+ test "excludes a churned_subscription schedule" do
+ team = insert(:team)
+
+ insert(:team_deletion_schedule,
+ team: team,
+ category: :churned_subscription,
+ status: :scheduled,
+ is_backlog: false
+ )
+
+ assert TeamDeletionSchedules.pending_steady_state_trials_by_team_id([team.id]) == %{}
+ end
+
+ test "excludes a schedule whose first notice was already sent" do
+ team = insert(:team)
+
+ insert(:team_deletion_schedule,
+ team: team,
+ category: :expired_trial,
+ status: :first_notice_sent,
+ is_backlog: false
+ )
+
+ assert TeamDeletionSchedules.pending_steady_state_trials_by_team_id([team.id]) == %{}
+ end
+
+ test "returns an empty map without querying for an empty list of team ids" do
+ assert TeamDeletionSchedules.pending_steady_state_trials_by_team_id([]) == %{}
+ end
+ end
+ end
+end
diff --git a/test/plausible/teams/deletion_schedule_test.exs b/test/plausible/teams/deletion_schedule_test.exs
new file mode 100644
index 0000000000..f3beb1d722
--- /dev/null
+++ b/test/plausible/teams/deletion_schedule_test.exs
@@ -0,0 +1,68 @@
+defmodule Plausible.Teams.DeletionScheduleTest do
+ use ExUnit.Case, async: true
+
+ use Plausible
+
+ on_ee do
+ alias Plausible.Teams.DeletionSchedule
+
+ describe "deletion_offset_days/1" do
+ test "returns the trial offset for :expired_trial" do
+ assert DeletionSchedule.deletion_offset_days(:expired_trial) == 60
+ end
+
+ test "returns the subscription offset for :churned_subscription" do
+ assert DeletionSchedule.deletion_offset_days(:churned_subscription) == 180
+ end
+ end
+
+ describe "deletion_date/2" do
+ test "adds the trial offset to the expiry date" do
+ assert DeletionSchedule.deletion_date(:expired_trial, ~D[2026-01-01]) == ~D[2026-03-02]
+ end
+
+ test "adds the subscription offset to the expiry date" do
+ assert DeletionSchedule.deletion_date(:churned_subscription, ~D[2026-01-01]) ==
+ ~D[2026-06-30]
+ end
+ end
+
+ describe "first_notice_due_date/1" do
+ test "is 30 days before the deletion date" do
+ assert DeletionSchedule.first_notice_due_date(~D[2026-03-02]) == ~D[2026-01-31]
+ end
+ end
+
+ describe "reminder_due_date/1" do
+ test "is 5 days before the deletion date" do
+ assert DeletionSchedule.reminder_due_date(~D[2026-03-02]) == ~D[2026-02-25]
+ end
+ end
+
+ describe "backlog_deletion_date/1" do
+ test "is anchored to when the first notice was actually sent, not a planned date" do
+ assert DeletionSchedule.backlog_deletion_date(~N[2026-08-20 10:00:00]) == ~D[2026-09-19]
+ end
+
+ test "slides forward if the notice went out later than originally planned" do
+ on_time = DeletionSchedule.backlog_deletion_date(~N[2026-08-20 10:00:00])
+ delayed = DeletionSchedule.backlog_deletion_date(~N[2026-08-25 10:00:00])
+
+ assert Date.diff(delayed, on_time) == 5
+ end
+
+ test "reminder_due_date/1 applies uniformly on top of it (no separate backlog variant needed)" do
+ first_notice_sent_at = ~N[2026-08-20 10:00:00]
+ deletion_date = DeletionSchedule.backlog_deletion_date(first_notice_sent_at)
+
+ assert DeletionSchedule.reminder_due_date(deletion_date) == ~D[2026-09-14]
+ end
+ end
+
+ describe "notification_site_list_limit/0" do
+ test "returns the configured cap" do
+ assert DeletionSchedule.notification_site_list_limit() == 3
+ end
+ end
+ end
+end
diff --git a/test/plausible_web/email_test.exs b/test/plausible_web/email_test.exs
index b177440a00..ef565025d3 100644
--- a/test/plausible_web/email_test.exs
+++ b/test/plausible_web/email_test.exs
@@ -356,7 +356,7 @@ defmodule PlausibleWeb.EmailTest do
assert body =~ "Hey John,"
assert body =~
- "Your sites are still sending us data, but your account is no longer active. We'll stop counting your stats next week."
+ "Your sites are still sending us data, but your account is no longer active. We'll stop counting new stats next week."
end
test "renders final warning" do
@@ -379,7 +379,151 @@ defmodule PlausibleWeb.EmailTest do
assert body =~ plausible_link(team: team, label: "start a Plausible subscription")
assert body =~
- "Your sites are still sending us data, but your account is no longer active. We'll stop counting your stats tomorrow."
+ "Your sites are still sending us data, but your account is no longer active. We'll stop counting new stats tomorrow."
+ end
+
+ test "final warning does not mention deletion when no deletion_date is given" do
+ user = build(:user, id: 123, name: "John Doe")
+ team = build(:team, identifier: Ecto.UUID.generate())
+
+ notification = %{
+ id: user.id,
+ email: user.email,
+ deadline: Date.add(Date.utc_today(), 1),
+ site_ids: [1, 2, 3],
+ name: user.name,
+ team: team
+ }
+
+ %{html_body: body} =
+ PlausibleWeb.Email.approaching_accept_traffic_until_tomorrow(notification)
+
+ refute body =~ "permanently delete"
+ end
+
+ test "final warning mentions the deletion date when given" do
+ user = build(:user, id: 123, name: "John Doe")
+ team = build(:team, identifier: Ecto.UUID.generate())
+
+ notification = %{
+ id: user.id,
+ email: user.email,
+ deadline: Date.add(Date.utc_today(), 1),
+ site_ids: [1, 2, 3],
+ name: user.name,
+ team: team
+ }
+
+ deletion_date = ~D[2026-10-19]
+
+ %{html_body: body} =
+ PlausibleWeb.Email.approaching_accept_traffic_until_tomorrow(notification, deletion_date)
+
+ assert body =~
+ "If you don't subscribe, we'll permanently delete your Plausible dashboards and all their stats on #{PlausibleWeb.EmailView.date_format(deletion_date)}. This cannot be undone."
+
+ assert body =~ ~s|<a href="https://plausible.io/docs/export-stats">export your stats</a>|
+ end
+ end
+
+ describe "deletion_full_notice_email/4" do
+ test "renders trial copy for an expired_trial schedule" do
+ user = build(:user, id: 123, name: "John Doe")
+ team = build(:team, identifier: Ecto.UUID.generate(), name: "My Team")
+
+ schedule =
+ build(:team_deletion_schedule, category: :expired_trial, deletion_date: ~D[2026-10-19])
+
+ sites_summary = %{domains: ["a.example.com", "b.example.com"], more_count: 0}
+
+ %{html_body: body, subject: subject} =
+ PlausibleWeb.Email.deletion_full_notice_email(user, team, schedule, sites_summary)
+
+ assert body =~ PlausibleWeb.EmailView.choose_plan_url(team)
+ assert body =~ ~s|<a href="https://plausible.io/docs/export-stats">export your stats</a>|
+
+ body = text(body)
+
+ days = Plausible.Teams.DeletionSchedule.first_notice_before_deletion_days()
+ assert subject == "Your Plausible dashboards and stats will be deleted in #{days} days"
+ assert body =~ "Your Plausible trial ended a while ago"
+ refute body =~ "subscription lapsed"
+
+ assert body =~
+ "we'll permanently delete the Plausible dashboards and stats for your My Team team on 19 Oct 2026. This cannot be undone."
+
+ assert body =~ "This covers a.example.com, b.example.com."
+ end
+
+ test "renders subscription copy for a churned_subscription schedule" do
+ user = build(:user, id: 123, name: "John Doe")
+ team = build(:team, identifier: Ecto.UUID.generate())
+
+ schedule =
+ build(:team_deletion_schedule,
+ category: :churned_subscription,
+ deletion_date: ~D[2026-10-19]
+ )
+
+ sites_summary = %{domains: [], more_count: 0}
+
+ %{html_body: body} =
+ PlausibleWeb.Email.deletion_full_notice_email(user, team, schedule, sites_summary)
+
+ assert body =~ "Your Plausible subscription lapsed a while ago"
+ refute body =~ "trial ended"
+ end
+
+ test "caps the listed domains and mentions how many more there are" do
+ user = build(:user, id: 123, name: "John Doe")
+ team = build(:team, identifier: Ecto.UUID.generate())
+ schedule = build(:team_deletion_schedule, deletion_date: ~D[2026-10-19])
+ sites_summary = %{domains: ["a.example.com", "b.example.com"], more_count: 7}
+
+ %{html_body: body} =
+ PlausibleWeb.Email.deletion_full_notice_email(user, team, schedule, sites_summary)
+
+ assert body =~ "This covers a.example.com, b.example.com (and 7 more sites)."
+ end
+
+ test "omits the site list entirely when there are no domains to show" do
+ user = build(:user, id: 123, name: "John Doe")
+ team = build(:team, identifier: Ecto.UUID.generate())
+ schedule = build(:team_deletion_schedule, deletion_date: ~D[2026-10-19])
+ sites_summary = %{domains: [], more_count: 0}
+
+ %{html_body: body} =
+ PlausibleWeb.Email.deletion_full_notice_email(user, team, schedule, sites_summary)
+
+ refute body =~ "This covers"
+ end
+ end
+
+ describe "deletion_reminder_email/4" do
+ test "renders the deletion date, site list, and subscribe link" do
+ user = build(:user, id: 123, name: "John Doe")
+ team = build(:team, identifier: Ecto.UUID.generate(), name: "My Team")
+ schedule = build(:team_deletion_schedule, deletion_date: ~D[2026-10-19])
+ sites_summary = %{domains: ["a.example.com"], more_count: 3}
+
+ %{html_body: body, subject: subject} =
+ PlausibleWeb.Email.deletion_reminder_email(user, team, schedule, sites_summary)
+
+ assert body =~ PlausibleWeb.EmailView.choose_plan_url(team)
+ assert body =~ ~s|<a href="https://plausible.io/docs/export-stats">export your stats</a>|
+
+ body = text(body)
+
+ days = Plausible.Teams.DeletionSchedule.reminder_before_deletion_days()
+
+ assert subject ==
+ "Final notice: your Plausible dashboards and stats will be deleted in #{days} days"
+
+ assert body =~
+ "We'll permanently delete the Plausible dashboards and stats for your My Team team on 19 Oct 2026."
+
+ assert body =~ "This covers a.example.com (and 3 more sites)."
+ assert body =~ "This cannot be undone."
end
end
diff --git a/test/plausible_web/live/customer_support/teams_test.exs b/test/plausible_web/live/customer_support/teams_test.exs
index 214be799ff..fdf4fcd13d 100644
--- a/test/plausible_web/live/customer_support/teams_test.exs
+++ b/test/plausible_web/live/customer_support/teams_test.exs
@@ -154,11 +154,160 @@ defmodule PlausibleWeb.Live.CustomerSupport.TeamsTest do
assert text_of_attr(html, "#team_accept_traffic_until", "value") == "2029-01-15"
end
+ test "prolonging trial_expiry_date cancels a pending expired-trial deletion schedule", %{
+ conn: conn,
+ user: user
+ } do
+ team = team_of(user)
+
+ schedule =
+ insert(:team_deletion_schedule,
+ team: team,
+ category: :expired_trial,
+ status: :scheduled,
+ deletion_date: ~D[2026-10-19]
+ )
+
+ {:ok, lv, html} = live(conn, open_team(team.id))
+
+ assert text(html) =~ "Deletion scheduled"
+
+ lv
+ |> element(~s|form[phx-submit="save-team"]|)
+ |> render_submit(%{"team" => %{"trial_expiry_date" => "2029-01-01"}})
+
+ html = render(lv)
+ refute text(html) =~ "Deletion scheduled"
+
+ assert Plausible.Repo.reload!(schedule).status == :cancelled
+ end
+
test "404", %{conn: conn} do
assert_raise Ecto.NoResultsError, fn ->
{:ok, _lv, _html} = live(conn, open_team(9999))
end
end
+
+ test "does not show a deletion schedule section when there is none", %{
+ conn: conn,
+ user: user
+ } do
+ team = team_of(user)
+
+ {:ok, _lv, html} = live(conn, open_team(team.id))
+
+ refute text(html) =~ "Deletion scheduled"
+ end
+
+ test "shows an active deletion schedule and allows snoozing it", %{
+ conn: conn,
+ user: user
+ } do
+ team = team_of(user)
+
+ schedule =
+ insert(:team_deletion_schedule,
+ team: team,
+ status: :reminder_sent,
+ deletion_date: ~D[2026-10-19]
+ )
+
+ {:ok, lv, html} = live(conn, open_team(team.id))
+
+ assert text(html) =~ "Deletion scheduled"
+ assert element_exists?(html, ~s|form[phx-submit="snooze-schedule"]|)
+
+ lv
+ |> element(~s|form[phx-submit="snooze-schedule"]|)
+ |> render_submit(%{
+ "team_deletion_schedule" => %{
+ "snoozed_until" => "2026-09-20",
+ "snooze_note" => "give them time"
+ }
+ })
+
+ html = render(lv)
+ assert text(html) =~ "Snoozed until 2026-09-20"
+ assert text(html) =~ "give them time"
+
+ updated = Plausible.Repo.reload!(schedule)
+ assert updated.status == :snoozed
+ assert updated.snoozed_until == ~D[2026-09-20]
+ assert updated.snooze_note == "give them time"
+ end
+
+ test "rejects a snooze date that isn't in the future", %{conn: conn, user: user} do
+ team = team_of(user)
+
+ schedule =
+ insert(:team_deletion_schedule,
+ team: team,
+ status: :reminder_sent,
+ deletion_date: ~D[2026-10-19]
+ )
+
+ {:ok, lv, _html} = live(conn, open_team(team.id))
+
+ today_iso = Date.to_iso8601(Date.utc_today())
+
+ html =
+ lv
+ |> element(~s|form[phx-submit="snooze-schedule"]|)
+ |> render_submit(%{"team_deletion_schedule" => %{"snoozed_until" => today_iso}})
+
+ assert text(html) =~ "must be in the future"
+ assert element_exists?(html, ~s|form[phx-submit="snooze-schedule"]|)
+
+ assert Plausible.Repo.reload!(schedule).status == :reminder_sent
+ end
+
+ test "rejects a blank snooze date", %{conn: conn, user: user} do
+ team = team_of(user)
+
+ schedule =
+ insert(:team_deletion_schedule,
+ team: team,
+ status: :reminder_sent,
+ deletion_date: ~D[2026-10-19]
+ )
+
+ {:ok, lv, _html} = live(conn, open_team(team.id))
+
+ html =
+ lv
+ |> element(~s|form[phx-submit="snooze-schedule"]|)
+ |> render_submit(%{"team_deletion_schedule" => %{"snoozed_until" => ""}})
+
+ assert text(html) =~ "can't be blank"
+ assert Plausible.Repo.reload!(schedule).status == :reminder_sent
+ end
+
+ test "allows unsnoozing a snoozed schedule", %{conn: conn, user: user} do
+ team = team_of(user)
+
+ schedule =
+ insert(:team_deletion_schedule,
+ team: team,
+ status: :snoozed,
+ snoozed_until: ~D[2026-09-20],
+ snooze_note: "customer asked for time",
+ deletion_date: ~D[2026-10-19]
+ )
+
+ {:ok, lv, html} = live(conn, open_team(team.id))
+
+ assert text(html) =~ "Snoozed until"
+ assert element_exists?(html, ~s|button[phx-click="unsnooze-schedule"]|)
+
+ lv |> element(~s|button[phx-click="unsnooze-schedule"]|) |> render_click()
+
+ html = render(lv)
+ assert element_exists?(html, ~s|form[phx-submit="snooze-schedule"]|)
+
+ updated = Plausible.Repo.reload!(schedule)
+ assert updated.status == :scheduled
+ assert updated.is_backlog
+ end
end
describe "sites" do
diff --git a/test/plausible_web/live/customer_support_test.exs b/test/plausible_web/live/customer_support_test.exs
index ff65980336..05f8c77676 100644
--- a/test/plausible_web/live/customer_support_test.exs
+++ b/test/plausible_web/live/customer_support_test.exs
@@ -42,6 +42,33 @@ defmodule PlausibleWeb.Live.CustomerSupportTest do
refute_search_result(resp, "site", consolidated_site.id)
end
+ test "shows a pending-deletion badge for a team with an active schedule", %{
+ conn: conn,
+ user: user
+ } do
+ team = team_of(user)
+ insert(:team_deletion_schedule, team: team, status: :scheduled)
+
+ conn = get(conn, @cs_index)
+ resp = html_response(conn, 200)
+
+ assert text_of_element(resp, ~s|a[data-test-type="team"][data-test-id="#{team.id}"]|) =~
+ "🧨"
+ end
+
+ test "does not show a pending-deletion badge for a team without one", %{
+ conn: conn,
+ user: user
+ } do
+ team = team_of(user)
+
+ conn = get(conn, @cs_index)
+ resp = html_response(conn, 200)
+
+ refute text_of_element(resp, ~s|a[data-test-type="team"][data-test-id="#{team.id}"]|) =~
+ "🧨"
+ end
+
test "filters as you type", %{conn: conn, site: site, user: user} do
site2 = new_site(owner: user, domain: "hello.example.com")
{:ok, lv, _html} = live(conn, @cs_index)
diff --git a/test/support/factory.ex b/test/support/factory.ex
index 66d9ff45b3..2be18eff06 100644
--- a/test/support/factory.ex
+++ b/test/support/factory.ex
@@ -112,6 +112,19 @@ defmodule Plausible.Factory do
}
end
+ def team_deletion_schedule_factory do
+ today = Date.utc_today()
+ deletion_date = Date.shift(today, day: 60)
+
+ %Plausible.TeamDeletionSchedule{
+ team: build(:team),
+ category: :expired_trial,
+ expiry_date: today,
+ deletion_date: deletion_date,
+ first_notice_due_date: Date.shift(deletion_date, day: -30)
+ }
+ end
+
def ch_session_factory do
hostname = sequence(:domain, &"example-#{&1}.com")
diff --git a/test/workers/accept_traffic_until_test.exs b/test/workers/accept_traffic_until_test.exs
index 3450ddd007..e5ce568a5a 100644
--- a/test/workers/accept_traffic_until_test.exs
+++ b/test/workers/accept_traffic_until_test.exs
@@ -4,6 +4,8 @@ defmodule Plausible.Workers.AcceptTrafficUntilTest do
alias Plausible.Workers.AcceptTrafficUntil
+ import ExUnit.CaptureIO
+
@moduletag :ee_only
test "does not send any notifications when sites have no stats" do
@@ -63,6 +65,102 @@ defmodule Plausible.Workers.AcceptTrafficUntilTest do
assert_final_notification(user.email)
end
+ test "tomorrow: augments the email with the deletion date and marks the schedule notified" do
+ tomorrow = Date.utc_today() |> Date.add(+1)
+ user = new_user(team: [accept_traffic_until: tomorrow])
+ team = team_of(user)
+
+ new_site(owner: user) |> populate_stats([build(:pageview)])
+
+ schedule = insert(:team_deletion_schedule, team: team, deletion_date: ~D[2026-10-19])
+
+ {:ok, 1} = AcceptTrafficUntil.perform(nil)
+
+ assert_email_delivered_with(
+ to: [nil: user.email],
+ html_body:
+ ~r/permanently delete your Plausible dashboards and all their stats on 19 Oct 2026/
+ )
+
+ assert Repo.reload!(schedule).status == :first_notice_sent
+ assert Repo.reload!(schedule).first_notice_sent_at
+ end
+
+ test "tomorrow: marks every pending schedule in a multi-team batch" do
+ tomorrow = Date.utc_today() |> Date.add(+1)
+
+ users_and_schedules =
+ for n <- 1..3 do
+ user = new_user(team: [accept_traffic_until: tomorrow])
+ team = team_of(user)
+ new_site(owner: user) |> populate_stats([build(:pageview)])
+
+ schedule =
+ insert(:team_deletion_schedule, team: team, deletion_date: Date.add(tomorrow, n))
+
+ {user, schedule}
+ end
+
+ {:ok, 3} = AcceptTrafficUntil.perform(nil)
+
+ for {user, schedule} <- users_and_schedules do
+ updated = Repo.reload!(schedule)
+ assert updated.status == :first_notice_sent
+ assert updated.first_notice_sent_at
+
+ assert_email_delivered_with(
+ to: [nil: user.email],
+ html_body:
+ ~r/permanently delete your Plausible dashboards and all their stats on #{PlausibleWeb.EmailView.date_format(updated.deletion_date)}/
+ )
+ end
+ end
+
+ test "tomorrow: does not augment or mark anything when there is no pending trial schedule" do
+ tomorrow = Date.utc_today() |> Date.add(+1)
+ user = new_user(team: [accept_traffic_until: tomorrow])
+
+ new_site(owner: user) |> populate_stats([build(:pageview)])
+
+ {:ok, 1} = AcceptTrafficUntil.perform(nil)
+
+ assert_receive {:delivered_email, email}
+ assert email.to == [nil: user.email]
+ refute email.html_body =~ "permanently delete"
+ end
+
+ test "tomorrow: ignores a backlog trial schedule (not yet spread out for sending)" do
+ tomorrow = Date.utc_today() |> Date.add(+1)
+ user = new_user(team: [accept_traffic_until: tomorrow])
+ team = team_of(user)
+
+ new_site(owner: user) |> populate_stats([build(:pageview)])
+
+ schedule = insert(:team_deletion_schedule, team: team, is_backlog: true)
+
+ {:ok, 1} = AcceptTrafficUntil.perform(nil)
+
+ assert_receive {:delivered_email, email}
+ refute email.html_body =~ "permanently delete"
+ assert Repo.reload!(schedule).status == :scheduled
+ end
+
+ test "tomorrow: dry_run does not mark the schedule as notified" do
+ tomorrow = Date.utc_today() |> Date.add(+1)
+ user = new_user(team: [accept_traffic_until: tomorrow])
+ team = team_of(user)
+
+ new_site(owner: user) |> populate_stats([build(:pageview)])
+
+ schedule = insert(:team_deletion_schedule, team: team)
+
+ assert capture_io(fn ->
+ {:ok, 1} = AcceptTrafficUntil.dry_run(Date.utc_today())
+ end) == "Will send final notification to #{user.email}\n"
+
+ assert Repo.reload!(schedule).status == :scheduled
+ end
+
test "next week: sends one e-mail" do
next_week = Date.utc_today() |> Date.add(+7)
user = new_user(team: [accept_traffic_until: next_week])
diff --git a/test/workers/execute_team_deletions_test.exs b/test/workers/execute_team_deletions_test.exs
new file mode 100644
index 0000000000..0ecb50839b
--- /dev/null
+++ b/test/workers/execute_team_deletions_test.exs
@@ -0,0 +1,236 @@
+defmodule Plausible.Workers.ExecuteTeamDeletionsTest do
+ use Plausible.DataCase, async: true
+
+ on_ee do
+ require Plausible.Billing.Subscription.Status
+
+ alias Plausible.Billing.Subscription
+ alias Plausible.PendingStatsDeletion
+ alias Plausible.Workers.ExecuteTeamDeletions
+
+ @today ~D[2026-08-20]
+
+ test "deletes the team's site and marks the schedule completed, keeping the team intact" do
+ owner = new_user()
+ site = new_site(owner: owner)
+ team = team_of(owner) |> Plausible.Teams.Team.end_trial() |> Repo.update!()
+
+ schedule =
+ insert(:team_deletion_schedule,
+ team: team,
+ status: :reminder_sent,
+ deletion_date: @today
+ )
+
+ assert :ok = ExecuteTeamDeletions.perform(nil, @today)
+
+ refute Repo.reload(site)
+ assert Repo.reload(team)
+ assert Repo.reload!(schedule).status == :completed
+ end
+
+ test "deletes every site owned by the team" do
+ owner = new_user()
+ site_a = new_site(owner: owner)
+ team = team_of(owner) |> Plausible.Teams.Team.end_trial() |> Repo.update!()
+ site_b = new_site(team: team)
+
+ insert(:team_deletion_schedule, team: team, status: :reminder_sent, deletion_date: @today)
+
+ assert :ok = ExecuteTeamDeletions.perform(nil, @today)
+
+ refute Repo.reload(site_a)
+ refute Repo.reload(site_b)
+ assert Repo.reload(team)
+ end
+
+ test "does not touch the team's settings or subscription history" do
+ owner = new_user()
+ new_site(owner: owner)
+ team = team_of(owner)
+
+ subscription =
+ insert(:subscription,
+ team: team,
+ status: Subscription.Status.deleted(),
+ next_bill_date: Date.shift(@today, day: -400)
+ )
+
+ insert(:team_deletion_schedule, team: team, status: :reminder_sent, deletion_date: @today)
+
+ assert :ok = ExecuteTeamDeletions.perform(nil, @today)
+
+ reloaded_team = Repo.reload(team)
+ assert reloaded_team
+ assert reloaded_team.name == team.name
+ assert Repo.reload(subscription)
+ end
+
+ test "passes the schedule's category through as the pending stats deletion reason (expired_trial)" do
+ owner = new_user()
+ site = new_site(owner: owner)
+ team = team_of(owner) |> Plausible.Teams.Team.end_trial() |> Repo.update!()
+
+ insert(:team_deletion_schedule,
+ team: team,
+ category: :expired_trial,
+ status: :reminder_sent,
+ deletion_date: @today
+ )
+
+ assert :ok = ExecuteTeamDeletions.perform(nil, @today)
+
+ assert Repo.get_by(PendingStatsDeletion, site_id: site.id).reason == :expired_trial
+ end
+
+ test "passes the schedule's category through as the pending stats deletion reason (churned_subscription)" do
+ owner = new_user()
+ site = new_site(owner: owner)
+ team = team_of(owner)
+
+ insert(:subscription,
+ team: team,
+ status: Subscription.Status.deleted(),
+ next_bill_date: Date.shift(@today, day: -400)
+ )
+
+ insert(:team_deletion_schedule,
+ team: team,
+ category: :churned_subscription,
+ status: :reminder_sent,
+ deletion_date: @today
+ )
+
+ assert :ok = ExecuteTeamDeletions.perform(nil, @today)
+
+ assert Repo.get_by(PendingStatsDeletion, site_id: site.id).reason == :churned_subscription
+ end
+
+ test "does not touch a row whose deletion_date hasn't arrived" do
+ owner = new_user()
+ site = new_site(owner: owner)
+ team = team_of(owner)
+
+ schedule =
+ insert(:team_deletion_schedule,
+ team: team,
+ status: :reminder_sent,
+ deletion_date: Date.shift(@today, day: 1)
+ )
+
+ assert :ok = ExecuteTeamDeletions.perform(nil, @today)
+
+ assert Repo.reload(team)
+ assert Repo.reload(site)
+ assert Repo.reload!(schedule).status == :reminder_sent
+ end
+
+ test "does not touch a row that hasn't had its reminder sent yet" do
+ owner = new_user()
+ site = new_site(owner: owner)
+ team = team_of(owner)
+
+ schedule =
+ insert(:team_deletion_schedule,
+ team: team,
+ status: :first_notice_sent,
+ deletion_date: @today
+ )
+
+ assert :ok = ExecuteTeamDeletions.perform(nil, @today)
+
+ assert Repo.reload(team)
+ assert Repo.reload(site)
+ assert Repo.reload!(schedule).status == :first_notice_sent
+ end
+
+ test "cancels instead of deleting when the team has reactivated since the last scan" do
+ owner = new_user()
+ site = new_site(owner: owner)
+ team = team_of(owner)
+
+ schedule =
+ insert(:team_deletion_schedule,
+ team: team,
+ status: :reminder_sent,
+ deletion_date: @today
+ )
+
+ insert(:subscription, team: team, status: Subscription.Status.active())
+
+ assert :ok = ExecuteTeamDeletions.perform(nil, @today)
+
+ assert Repo.reload(team)
+ assert Repo.reload(site)
+ assert Repo.reload!(schedule).status == :cancelled
+ end
+
+ test "emits telemetry for an executed deletion, tagged by category, with a sites_deleted count",
+ %{test: test} do
+ test_pid = self()
+ telemetry_run = ExecuteTeamDeletions.telemetry_run_event()
+ telemetry_sites_deleted = ExecuteTeamDeletions.telemetry_sites_deleted_event()
+
+ :telemetry.attach_many(
+ "#{test}-telemetry-handler",
+ [telemetry_run, telemetry_sites_deleted],
+ fn event, measurements, metadata, _ ->
+ send(test_pid, {:telemetry_handled, event, measurements, metadata})
+ end,
+ %{}
+ )
+
+ owner = new_user()
+ new_site(owner: owner)
+ team = team_of(owner) |> Plausible.Teams.Team.end_trial() |> Repo.update!()
+ new_site(team: team)
+
+ insert(:team_deletion_schedule,
+ team: team,
+ category: :expired_trial,
+ status: :reminder_sent,
+ deletion_date: @today
+ )
+
+ assert :ok = ExecuteTeamDeletions.perform(nil, @today)
+
+ assert_receive {:telemetry_handled, ^telemetry_run, %{count: 1},
+ %{outcome: :executed, category: :expired_trial}}
+
+ assert_receive {:telemetry_handled, ^telemetry_sites_deleted, %{count: 2},
+ %{category: :expired_trial}}
+ end
+
+ test "emits telemetry for a cancelled schedule, without a sites_deleted event", %{test: test} do
+ test_pid = self()
+ telemetry_run = ExecuteTeamDeletions.telemetry_run_event()
+
+ :telemetry.attach(
+ "#{test}-telemetry-handler",
+ telemetry_run,
+ fn event, measurements, metadata, _ ->
+ send(test_pid, {:telemetry_handled, event, measurements, metadata})
+ end,
+ %{}
+ )
+
+ owner = new_user()
+ new_site(owner: owner)
+ team = team_of(owner)
+
+ insert(:team_deletion_schedule,
+ team: team,
+ category: :churned_subscription,
+ status: :reminder_sent,
+ deletion_date: @today
+ )
+
+ insert(:subscription, team: team, status: Subscription.Status.active())
+
+ assert :ok = ExecuteTeamDeletions.perform(nil, @today)
+
+ assert_receive {:telemetry_handled, ^telemetry_run, %{count: 1},
+ %{outcome: :cancelled, category: :churned_subscription}}
+ end
+ end
+end
diff --git a/test/workers/scan_inactive_teams_test.exs b/test/workers/scan_inactive_teams_test.exs
new file mode 100644
index 0000000000..4c5849542b
--- /dev/null
+++ b/test/workers/scan_inactive_teams_test.exs
@@ -0,0 +1,56 @@
+defmodule Plausible.Workers.ScanInactiveTeamsTest do
+ use Plausible.DataCase, async: true
+
+ alias Plausible.TeamDeletionSchedule
+ alias Plausible.Workers.ScanInactiveTeams
+
+ test "schedules a team whose trial has expired" do
+ team = insert(:team, trial_expiry_date: Date.shift(Date.utc_today(), day: -1))
+ new_site(team: team)
+
+ ScanInactiveTeams.perform(nil)
+
+ schedule = Repo.get_by!(TeamDeletionSchedule, team_id: team.id)
+ assert schedule.category == :expired_trial
+ assert schedule.status == :scheduled
+ end
+
+ test "does not schedule a team still on an active trial" do
+ insert(:team, trial_expiry_date: Date.shift(Date.utc_today(), day: 1))
+
+ ScanInactiveTeams.perform(nil)
+
+ assert Repo.aggregate(TeamDeletionSchedule, :count) == 0
+ end
+
+ test "is idempotent across repeated runs" do
+ team = insert(:team, trial_expiry_date: Date.shift(Date.utc_today(), day: -1))
+ new_site(team: team)
+
+ ScanInactiveTeams.perform(nil)
+ ScanInactiveTeams.perform(nil)
+
+ assert Repo.aggregate(TeamDeletionSchedule, :count) == 1
+ end
+
+ test "emits telemetry with the number of newly-scheduled teams", %{test: test} do
+ test_pid = self()
+ telemetry_run = ScanInactiveTeams.telemetry_run_event()
+
+ :telemetry.attach(
+ "#{test}-telemetry-handler",
+ telemetry_run,
+ fn event, measurements, metadata, _ ->
+ send(test_pid, {:telemetry_handled, event, measurements, metadata})
+ end,
+ %{}
+ )
+
+ team = insert(:team, trial_expiry_date: Date.shift(Date.utc_today(), day: -1))
+ new_site(team: team)
+
+ ScanInactiveTeams.perform(nil)
+
+ assert_receive {:telemetry_handled, ^telemetry_run, %{created: 1}, %{}}
+ end
+end
diff --git a/test/workers/send_deletion_notifications_test.exs b/test/workers/send_deletion_notifications_test.exs
new file mode 100644
index 0000000000..200991952c
--- /dev/null
+++ b/test/workers/send_deletion_notifications_test.exs
@@ -0,0 +1,345 @@
+defmodule Plausible.Workers.SendDeletionNotificationsTest do
+ use Plausible.DataCase, async: true
+
+ on_ee do
+ use Bamboo.Test
+
+ require Plausible.Billing.Subscription.Status
+
+ alias Plausible.Billing.Subscription
+ alias Plausible.Workers.SendDeletionNotifications
+
+ @today ~D[2026-08-20]
+
+ describe "first notices" do
+ test "sends the full notice email to owners and billing members" do
+ owner = new_user()
+ new_site(owner: owner)
+ team = team_of(owner)
+
+ insert(:team_membership, team: team, user: build(:user), role: :billing)
+
+ insert(:subscription,
+ team: team,
+ status: Subscription.Status.deleted(),
+ next_bill_date: Date.shift(@today, day: -400)
+ )
+
+ schedule =
+ insert(:team_deletion_schedule,
+ team: team,
+ category: :churned_subscription,
+ status: :scheduled,
+ first_notice_due_date: @today,
+ deletion_date: ~D[2026-10-19]
+ )
+
+ SendDeletionNotifications.perform(nil, @today)
+
+ team = Repo.preload(team, [:owners, :billing_members])
+ recipients = team.owners ++ team.billing_members
+
+ assert length(recipients) == 2
+
+ for recipient <- recipients do
+ assert_email_delivered_with(
+ to: [{recipient.name, recipient.email}],
+ subject: "Your Plausible dashboards and stats will be deleted in 30 days"
+ )
+ end
+
+ assert Repo.reload!(schedule).status == :first_notice_sent
+ assert Repo.reload!(schedule).first_notice_sent_at
+ end
+
+ test "finalizes a backlog row's deletion_date anchored to when the notice actually sends" do
+ owner = new_user()
+ new_site(owner: owner)
+ team = team_of(owner) |> Plausible.Teams.Team.end_trial() |> Repo.update!()
+
+ schedule =
+ insert(:team_deletion_schedule,
+ team: team,
+ category: :expired_trial,
+ status: :scheduled,
+ is_backlog: true,
+ first_notice_due_date: @today,
+ deletion_date: ~D[2024-01-01]
+ )
+
+ SendDeletionNotifications.perform(nil, @today)
+
+ updated = Repo.reload!(schedule)
+ assert updated.status == :first_notice_sent
+ assert updated.deletion_date == Date.shift(@today, day: 30)
+ end
+
+ test "sends the backlog first notice email with the finalized deletion date, not the stale placeholder" do
+ owner = new_user()
+ new_site(owner: owner)
+ team = team_of(owner) |> Plausible.Teams.Team.end_trial() |> Repo.update!()
+
+ insert(:team_deletion_schedule,
+ team: team,
+ category: :expired_trial,
+ status: :scheduled,
+ is_backlog: true,
+ first_notice_due_date: @today,
+ deletion_date: ~D[2024-01-01]
+ )
+
+ SendDeletionNotifications.perform(nil, @today)
+
+ finalized_date = Date.shift(@today, day: 30)
+
+ assert_email_delivered_with(
+ to: [{owner.name, owner.email}],
+ html_body: ~r/#{Regex.escape(PlausibleWeb.EmailView.date_format(finalized_date))}/
+ )
+
+ refute_email_delivered_with(
+ html_body: ~r/#{Regex.escape(PlausibleWeb.EmailView.date_format(~D[2024-01-01]))}/
+ )
+ end
+
+ test "does not touch a row whose first_notice_due_date hasn't arrived" do
+ owner = new_user()
+ new_site(owner: owner)
+ team = team_of(owner)
+
+ schedule =
+ insert(:team_deletion_schedule,
+ team: team,
+ status: :scheduled,
+ first_notice_due_date: Date.shift(@today, day: 1)
+ )
+
+ SendDeletionNotifications.perform(nil, @today)
+
+ refute_email_delivered_with(
+ subject: "Your Plausible dashboards and stats will be deleted in 30 days"
+ )
+
+ assert Repo.reload!(schedule).status == :scheduled
+ end
+
+ test "cancels instead of sending when the team has reactivated since the last scan" do
+ owner = new_user()
+ new_site(owner: owner)
+ team = team_of(owner)
+
+ schedule =
+ insert(:team_deletion_schedule,
+ team: team,
+ status: :scheduled,
+ first_notice_due_date: @today
+ )
+
+ insert(:subscription, team: team, status: Subscription.Status.active())
+
+ SendDeletionNotifications.perform(nil, @today)
+
+ refute_email_delivered_with(
+ subject: "Your Plausible dashboards and stats will be deleted in 30 days"
+ )
+
+ assert Repo.reload!(schedule).status == :cancelled
+ end
+ end
+
+ describe "reminders" do
+ test "sends the reminder email and advances status" do
+ owner = new_user()
+ new_site(owner: owner)
+ team = team_of(owner) |> Plausible.Teams.Team.end_trial() |> Repo.update!()
+
+ schedule =
+ insert(:team_deletion_schedule,
+ team: team,
+ status: :first_notice_sent,
+ deletion_date: Date.shift(@today, day: 3)
+ )
+
+ SendDeletionNotifications.perform(nil, @today)
+
+ assert_email_delivered_with(
+ to: [{owner.name, owner.email}],
+ subject: "Final notice: your Plausible dashboards and stats will be deleted in 5 days"
+ )
+
+ updated = Repo.reload!(schedule)
+ assert updated.status == :reminder_sent
+ assert updated.reminder_sent_at
+ end
+
+ test "does not touch a row whose deletion_date is still more than 5 days out" do
+ owner = new_user()
+ new_site(owner: owner)
+ team = team_of(owner)
+
+ schedule =
+ insert(:team_deletion_schedule,
+ team: team,
+ status: :first_notice_sent,
+ deletion_date: Date.shift(@today, day: 6)
+ )
+
+ SendDeletionNotifications.perform(nil, @today)
+
+ refute_email_delivered_with(
+ subject: "Final notice: your Plausible dashboards and stats will be deleted in 5 days"
+ )
+
+ assert Repo.reload!(schedule).status == :first_notice_sent
+ end
+
+ test "cancels instead of sending when the team has reactivated since the last scan" do
+ owner = new_user()
+ new_site(owner: owner)
+ team = team_of(owner)
+
+ schedule =
+ insert(:team_deletion_schedule,
+ team: team,
+ status: :first_notice_sent,
+ deletion_date: Date.shift(@today, day: 3)
+ )
+
+ insert(:subscription, team: team, status: Subscription.Status.active())
+
+ SendDeletionNotifications.perform(nil, @today)
+
+ refute_email_delivered_with(
+ subject: "Final notice: your Plausible dashboards and stats will be deleted in 5 days"
+ )
+
+ assert Repo.reload!(schedule).status == :cancelled
+ end
+ end
+
+ describe "telemetry" do
+ setup %{test: test} do
+ test_pid = self()
+ telemetry_run = SendDeletionNotifications.telemetry_run_event()
+
+ :telemetry.attach(
+ "#{test}-telemetry-handler",
+ telemetry_run,
+ fn event, measurements, metadata, _ ->
+ send(test_pid, {:telemetry_handled, event, measurements, metadata})
+ end,
+ %{}
+ )
+
+ %{telemetry_run: telemetry_run}
+ end
+
+ test "emits a :sent first notice event", %{telemetry_run: telemetry_run} do
+ owner = new_user()
+ new_site(owner: owner)
+ team = team_of(owner) |> Plausible.Teams.Team.end_trial() |> Repo.update!()
+
+ insert(:team_deletion_schedule,
+ team: team,
+ category: :churned_subscription,
+ status: :scheduled,
+ first_notice_due_date: @today
+ )
+
+ SendDeletionNotifications.perform(nil, @today)
+
+ assert_receive {:telemetry_handled, ^telemetry_run, %{count: 1},
+ %{stage: :first_notice, outcome: :sent, category: :churned_subscription}}
+ end
+
+ test "emits a :cancelled first notice event when the team has reactivated", %{
+ telemetry_run: telemetry_run
+ } do
+ owner = new_user()
+ new_site(owner: owner)
+ team = team_of(owner)
+
+ insert(:team_deletion_schedule,
+ team: team,
+ category: :expired_trial,
+ status: :scheduled,
+ first_notice_due_date: @today
+ )
+
+ insert(:subscription, team: team, status: Subscription.Status.active())
+
+ SendDeletionNotifications.perform(nil, @today)
+
+ assert_receive {:telemetry_handled, ^telemetry_run, %{count: 1},
+ %{stage: :first_notice, outcome: :cancelled, category: :expired_trial}}
+ end
+
+ test "emits a :sent reminder event", %{telemetry_run: telemetry_run} do
+ owner = new_user()
+ new_site(owner: owner)
+ team = team_of(owner) |> Plausible.Teams.Team.end_trial() |> Repo.update!()
+
+ insert(:team_deletion_schedule,
+ team: team,
+ category: :churned_subscription,
+ status: :first_notice_sent,
+ deletion_date: Date.shift(@today, day: 3)
+ )
+
+ SendDeletionNotifications.perform(nil, @today)
+
+ assert_receive {:telemetry_handled, ^telemetry_run, %{count: 1},
+ %{stage: :reminder, outcome: :sent, category: :churned_subscription}}
+ end
+
+ test "emits a :cancelled reminder event when the team has reactivated", %{
+ telemetry_run: telemetry_run
+ } do
+ owner = new_user()
+ new_site(owner: owner)
+ team = team_of(owner)
+
+ insert(:team_deletion_schedule,
+ team: team,
+ category: :expired_trial,
+ status: :first_notice_sent,
+ deletion_date: Date.shift(@today, day: 3)
+ )
+
+ insert(:subscription, team: team, status: Subscription.Status.active())
+
+ SendDeletionNotifications.perform(nil, @today)
+
+ assert_receive {:telemetry_handled, ^telemetry_run, %{count: 1},
+ %{stage: :reminder, outcome: :cancelled, category: :expired_trial}}
+ end
+ end
+
+ describe "sites_summary/1" do
+ test "returns every domain uncapped when the team has few sites" do
+ owner = new_user()
+ new_site(owner: owner)
+ new_site(owner: owner)
+ team = team_of(owner)
+
+ summary = SendDeletionNotifications.sites_summary(team)
+
+ assert length(summary.domains) == 2
+ assert summary.more_count == 0
+ end
+
+ test "caps the domain list and reports how many more sites exist" do
+ owner = new_user()
+
+ for _ <- 1..13, do: new_site(owner: owner)
+
+ team = team_of(owner)
+
+ summary = SendDeletionNotifications.sites_summary(team)
+
+ assert length(summary.domains) == 3
+ assert summary.more_count == 10
+ end
+ end
+ end
+end
diff --git a/test/workers/unsnooze_team_deletions_test.exs b/test/workers/unsnooze_team_deletions_test.exs
new file mode 100644
index 0000000000..1ba2ab4c19
--- /dev/null
+++ b/test/workers/unsnooze_team_deletions_test.exs
@@ -0,0 +1,87 @@
+defmodule Plausible.Workers.UnsnoozeTeamDeletionsTest do
+ use Plausible.DataCase, async: true
+
+ on_ee do
+ alias Plausible.Workers.UnsnoozeTeamDeletions
+
+ @today ~D[2026-08-20]
+
+ test "restarts the notice cycle for a schedule whose snooze has lapsed" do
+ schedule =
+ insert(:team_deletion_schedule,
+ status: :snoozed,
+ is_backlog: false,
+ snoozed_until: @today,
+ snooze_note: "customer asked for time",
+ first_notice_sent_at: ~N[2026-07-01 10:00:00],
+ reminder_sent_at: ~N[2026-07-20 10:00:00]
+ )
+
+ assert :ok = UnsnoozeTeamDeletions.perform(nil, @today)
+
+ updated = Repo.reload!(schedule)
+ assert updated.status == :scheduled
+ assert updated.is_backlog
+ assert updated.first_notice_due_date == @today
+ assert updated.first_notice_sent_at == nil
+ assert updated.reminder_sent_at == nil
+ assert updated.snoozed_until == nil
+ assert updated.snooze_note == nil
+ end
+
+ test "restarts a schedule whose snooze is overdue (missed run catch-up)" do
+ schedule =
+ insert(:team_deletion_schedule,
+ status: :snoozed,
+ snoozed_until: Date.shift(@today, day: -3)
+ )
+
+ assert :ok = UnsnoozeTeamDeletions.perform(nil, @today)
+
+ assert Repo.reload!(schedule).status == :scheduled
+ end
+
+ test "does not touch a row whose snooze hasn't lapsed yet" do
+ schedule =
+ insert(:team_deletion_schedule,
+ status: :snoozed,
+ snoozed_until: Date.shift(@today, day: 1)
+ )
+
+ assert :ok = UnsnoozeTeamDeletions.perform(nil, @today)
+
+ updated = Repo.reload!(schedule)
+ assert updated.status == :snoozed
+ assert updated.snoozed_until == Date.shift(@today, day: 1)
+ end
+
+ test "does not touch a row that isn't snoozed" do
+ schedule = insert(:team_deletion_schedule, status: :reminder_sent, deletion_date: @today)
+
+ assert :ok = UnsnoozeTeamDeletions.perform(nil, @today)
+
+ assert Repo.reload!(schedule).status == :reminder_sent
+ end
+
+ test "emits telemetry with the number of unsnoozed schedules", %{test: test} do
+ test_pid = self()
+ telemetry_run = UnsnoozeTeamDeletions.telemetry_run_event()
+
+ :telemetry.attach(
+ "#{test}-telemetry-handler",
+ telemetry_run,
+ fn event, measurements, metadata, _ ->
+ send(test_pid, {:telemetry_handled, event, measurements, metadata})
+ end,
+ %{}
+ )
+
+ insert(:team_deletion_schedule, status: :snoozed, snoozed_until: @today)
+ insert(:team_deletion_schedule, status: :snoozed, snoozed_until: Date.shift(@today, day: 1))
+
+ assert :ok = UnsnoozeTeamDeletions.perform(nil, @today)
+
+ assert_receive {:telemetry_handled, ^telemetry_run, %{count: 1}, %{}}
+ end
+ end
+end