File size: 2,255 Bytes
c27e67a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
defmodule Plausible.Workers.SendTrialNotifications do
  @moduledoc """
  Job sending trial end notification emails.
  """
  use Plausible.Repo

  use Oban.Worker,
    queue: :trial_notification_emails,
    max_attempts: 1

  alias Plausible.Teams

  @impl Oban.Worker
  def perform(_job) do
    teams =
      Repo.all(
        from t in Teams.Team,
          inner_join: o in assoc(t, :owners),
          left_join: bm in assoc(t, :billing_members),
          left_join: s in assoc(t, :subscription),
          where: not is_nil(t.trial_expiry_date),
          where: is_nil(s.id),
          order_by: t.inserted_at,
          preload: [owners: o, billing_members: bm]
      )
      |> Enum.filter(&Teams.has_active_sites?/1)

    for team <- teams do
      recipients = team.owners ++ team.billing_members

      case Date.diff(team.trial_expiry_date, Date.utc_today()) do
        7 ->
          send_one_week_reminder(recipients, team)

        1 ->
          send_tomorrow_reminder(recipients, team)

        0 ->
          send_today_reminder(recipients, team)

        -1 ->
          send_over_reminder(recipients, team)

        _ ->
          nil
      end
    end

    :ok
  end

  defp send_one_week_reminder(users, team) do
    for user <- users do
      PlausibleWeb.Email.trial_one_week_reminder(user, team)
      |> Plausible.Mailer.send()
    end
  end

  defp send_tomorrow_reminder(users, team) do
    usage = Plausible.Teams.Billing.usage_cycle(team, :last_30_days)
    suggested_volume = Plausible.Billing.Plans.suggest_volume(team, usage.total)

    for user <- users do
      PlausibleWeb.Email.trial_ending_tomorrow_email(user, team, usage, suggested_volume)
      |> Plausible.Mailer.send()
    end
  end

  defp send_today_reminder(users, team) do
    usage = Plausible.Teams.Billing.usage_cycle(team, :last_30_days)
    suggested_volume = Plausible.Billing.Plans.suggest_volume(team, usage.total)

    for user <- users do
      PlausibleWeb.Email.trial_ending_today_email(user, team, usage, suggested_volume)
      |> Plausible.Mailer.send()
    end
  end

  defp send_over_reminder(users, team) do
    for user <- users do
      PlausibleWeb.Email.trial_over_email(user, team)
      |> Plausible.Mailer.send()
    end
  end
end