You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
62 lines
1.8 KiB
Elixir
62 lines
1.8 KiB
Elixir
|
6 years ago
|
defmodule Plausible.Workers.CheckUsage do
|
||
|
|
use Plausible.Repo
|
||
|
|
use Oban.Worker, queue: :check_usage
|
||
|
|
|
||
|
|
defmacro yesterday() do
|
||
|
|
quote do
|
||
|
|
fragment("now() - INTERVAL '1 day'")
|
||
|
|
end
|
||
|
|
end
|
||
|
|
|
||
|
|
defmacro last_day_of_month(day) do
|
||
|
|
quote do
|
||
|
|
fragment(
|
||
|
|
"(date_trunc('month', ?::date) + interval '1 month' - interval '1 day')::date",
|
||
|
|
unquote(day)
|
||
|
|
)
|
||
|
|
end
|
||
|
|
end
|
||
|
|
|
||
|
|
defmacro day_of_month(date) do
|
||
|
|
quote do
|
||
|
|
fragment("EXTRACT(day from ?::date)", unquote(date))
|
||
|
|
end
|
||
|
|
end
|
||
|
|
|
||
|
|
defmacro least(left, right) do
|
||
|
|
quote do
|
||
|
|
fragment("least(?, ?)", unquote(left), unquote(right))
|
||
|
|
end
|
||
|
|
end
|
||
|
|
|
||
|
|
@impl Oban.Worker
|
||
|
|
def perform(_args, _job, billing_mod \\ Plausible.Billing) do
|
||
|
|
yesterday = Timex.today() |> Timex.shift(days: -1)
|
||
|
|
|
||
|
|
active_subscribers =
|
||
|
|
Repo.all(
|
||
|
|
from u in Plausible.Auth.User,
|
||
|
|
join: s in Plausible.Billing.Subscription,
|
||
|
|
on: s.user_id == u.id,
|
||
|
|
where: s.status == "active",
|
||
|
|
# Accounts for situations like last_bill_date==2021-01-31 AND today==2021-03-01. Since February never reaches the 31st day, the account is checked on 2021-03-01.
|
||
|
|
where:
|
||
|
|
least(day_of_month(s.last_bill_date), day_of_month(last_day_of_month(^yesterday))) ==
|
||
|
|
day_of_month(^yesterday),
|
||
|
|
preload: [subscription: s]
|
||
|
|
)
|
||
|
|
|
||
|
|
for subscriber <- active_subscribers do
|
||
|
|
allowance = Plausible.Billing.Plans.allowance(subscriber.subscription)
|
||
|
|
{last_last_month, last_month} = billing_mod.last_two_billing_months_usage(subscriber)
|
||
|
|
|
||
|
|
if last_last_month > allowance && last_month > allowance do
|
||
|
|
template = PlausibleWeb.Email.over_limit_email(subscriber, last_month)
|
||
|
|
Plausible.Mailer.send_email(template)
|
||
|
|
end
|
||
|
|
end
|
||
|
|
|
||
|
|
:ok
|
||
|
|
end
|
||
|
|
end
|