-
Notifications
You must be signed in to change notification settings - Fork 102
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(DailyUsage): Add daily_usages:fill_daily_usage task
- Loading branch information
1 parent
d65061c
commit c420967
Showing
2 changed files
with
60 additions
and
13 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
# frozen_string_literal: true | ||
|
||
namespace :daily_usages do | ||
desc "Fill past daily usage" | ||
task :fill_history, [:organization_id] => :environment do |_task, args| | ||
abort "Missing organization_id\n\n" unless args[:organization_id] | ||
|
||
organization = Organization.find(args[:organization_id]) | ||
|
||
subscriptions = organization.subscriptions | ||
.where(status: [:active, :terminated]) | ||
.where("started_at >= ?", 4.month.ago) | ||
|
||
subscriptions.find_each do |subscription| | ||
from = subscription.started_at.to_date | ||
to = (subscription.terminated_at || Time.current).to_date | ||
|
||
from..to.each do |date| | ||
datetime = date + 5.minutes | ||
|
||
Timecop.freeze(datetime) do | ||
usage = Invoices::CustomerUsageService.call( | ||
customer: subscription.customer, | ||
subscription: subscription, | ||
apply_taxes: false, | ||
with_cache: false | ||
).raise_if_error!.usage | ||
|
||
DailyUsage.create!( | ||
organization:, | ||
customer: subscription.customer, | ||
subscription:, | ||
external_subscription_id: subscription.external_id, | ||
usage: usage, | ||
from_datetime: usage.from_datetime, | ||
to_datetime: usage.to_datetime, | ||
refreshed_at: date | ||
) | ||
end | ||
end | ||
end | ||
end | ||
end |