Usage DAO can now return rates and billable amount, alongside units.

This commit is contained in:
Martyn Inglis
2017-05-24 08:56:59 +01:00
parent 0bb289a1f2
commit 9dd6041944
2 changed files with 242 additions and 29 deletions

View File

@@ -157,20 +157,66 @@ def rate_multiplier():
@statsd(namespace="dao")
def get_total_billable_units_for_sent_sms_notifications_in_date_range(start_date, end_date, service_id):
rates = get_rates_for_year(start_date, end_date, SMS_TYPE)
print(rates)
result = db.session.query(
func.sum(
NotificationHistory.billable_units * func.coalesce(NotificationHistory.rate_multiplier, 1)
).label('billable_units')
).filter(
NotificationHistory.service_id == service_id,
NotificationHistory.notification_type == 'sms',
NotificationHistory.created_at >= start_date,
NotificationHistory.created_at <= end_date,
NotificationHistory.status.in_(NOTIFICATION_STATUS_TYPES_BILLABLE)
)
if result.scalar():
return int(result.scalar())
return 0
billable_units = 0
total_cost = 0.0
rate_boundaries = discover_rate_bounds_for_billing_query(start_date, end_date)
for rate_boundary in rate_boundaries:
result = db.session.query(
func.sum(
NotificationHistory.billable_units * func.coalesce(NotificationHistory.rate_multiplier, 1)
).label('billable_units')
).filter(
NotificationHistory.service_id == service_id,
NotificationHistory.notification_type == 'sms',
NotificationHistory.created_at >= rate_boundary['start_date'],
NotificationHistory.created_at < rate_boundary['end_date'],
NotificationHistory.status.in_(NOTIFICATION_STATUS_TYPES_BILLABLE)
)
billable_units_by_rate_boundry = result.scalar()
if billable_units_by_rate_boundry:
billable_units += int(billable_units_by_rate_boundry)vi end_date
total_cost += int(billable_units_by_rate_boundry) * rate_boundary['rate']
return billable_units, total_cost
def discover_rate_bounds_for_billing_query(start_date, end_date):
bounds = []
rates = get_rates_for_year(start_date, end_date, SMS_TYPE)
def current_valid_from(index):
return rates[index].valid_from
def next_valid_from(index):
return rates[index + 1].valid_from
def current_rate(index):
return rates[index].rate
def append_rate(rate_start_date, rate_end_date, rate):
bounds.append({
'start_date': rate_start_date,
'end_date': rate_end_date,
'rate': rate
})
if len(rates) == 1:
append_rate(start_date, end_date, current_rate(0))
return bounds
for i in range(len(rates)):
# first boundary
if i == 0:
append_rate(start_date, next_valid_from(i), current_rate(i))
# last boundary
elif i == (len(rates) - 1):
append_rate(current_valid_from(i), end_date, current_rate(i))
# other boundaries
else:
append_rate(current_valid_from(i), next_valid_from(i), current_rate(i))
return bounds