mirror of
https://github.com/ubicloud/ubicloud.git
synced 2025-10-04 05:42:15 +08:00
Use Sequel::CURRENT_TIMESTAMP instead. To get the start of the month, use the date_trunc PostgreSQL function. For this to work correctly requires the latest Sequel commit, so update to that.
46 lines
1.3 KiB
Ruby
46 lines
1.3 KiB
Ruby
# frozen_string_literal: true
|
|
|
|
require "yaml"
|
|
|
|
class FreeQuota
|
|
# :nocov:
|
|
def self.freeze
|
|
free_quotas
|
|
super
|
|
end
|
|
# :nocov:
|
|
|
|
def self.free_quotas
|
|
@free_quotas ||= begin
|
|
quotas = YAML.load_file("config/free_quotas.yml")
|
|
quotas.each_with_object({}) do |item, hash|
|
|
item["billing_rate_ids"] = BillingRate.from_resource_type(item["resource_type"]).map { it["id"] }
|
|
hash[item["name"]] = item
|
|
end
|
|
end
|
|
@free_quotas
|
|
end
|
|
|
|
def self.remaining_free_quota(name, project_id)
|
|
free_quota = free_quotas[name]
|
|
used_amount = BillingRecord
|
|
.where(project_id:, billing_rate_id: free_quota["billing_rate_ids"])
|
|
.where(Sequel.pg_range(:span).overlaps(begin_of_month_till_now))
|
|
.sum(:amount) || 0
|
|
[0, free_quota["value"] - used_amount].max
|
|
end
|
|
|
|
def self.get_exhausted_projects(name)
|
|
free_quota = free_quotas[name]
|
|
BillingRecord
|
|
.where(billing_rate_id: free_quota["billing_rate_ids"])
|
|
.where(Sequel.pg_range(:span).overlaps(begin_of_month_till_now))
|
|
.group(:project_id)
|
|
.having { sum(:amount) >= free_quota["value"] }
|
|
.select(:project_id)
|
|
end
|
|
|
|
def self.begin_of_month_till_now
|
|
Sequel::Postgres::PGRange.new(Sequel.function(:date_trunc, "month", Sequel::CURRENT_TIMESTAMP), Sequel::CURRENT_TIMESTAMP, db_type: :tstzrange)
|
|
end
|
|
end
|