Add costs to each row in yearly usage API

This will replace the manual calculation in Admin [^1] for SMS and
also in API [^2] for letters.

Doing the calculation here also means we correctly attribute free
allowance to the earliest rows in the billing table - Admin doesn't
know when a given rate was applied so can't do this with the data
currently returned from the API.

Since the calculation now depends on annual billing, we need to
change all the tests to make sure a suitable row exists.

Note about "OVER" clause
========================

Using "rows=" ("ROWS BETWEEN") makes more sense than "range=" as
we want the remainder to be incremental within each group in a
"GROUP BY" clause, as well as between groups i.e

  # ROWS BETWEEN (arbitrary numbers to illustrate)
  date=2021-04-03, units=3, cost=3.29
  date=2021-04-03, units=2, cost=4.17
  date=2021-04-04, units=2, cost=5.10

  vs.

  # RANGE BETWEEN
  date=2021-04-03, units=3, cost=4.17
  date=2021-04-03, units=2, cost=4.17
  date=2021-04-04, units=2, cost=5.10

See [^3] for more details and examples.

[^1]: https://github.com/alphagov/notifications-admin/blob/master/app/templates/views/usage.html#L60
[^2]: 072c3b2079/app/billing/billing_schemas.py (L37)
[^3]: https://learnsql.com/blog/difference-between-rows-range-window-functions/
This commit is contained in:
Ben Thorner
2022-04-20 17:14:17 +01:00
parent 0af791e417
commit 106da583ea
4 changed files with 67 additions and 1 deletions

View File

@@ -185,6 +185,7 @@ def set_up_yearly_data():
sms_template = create_template(service=service, template_type="sms")
email_template = create_template(service=service, template_type="email")
letter_template = create_template(service=service, template_type="letter")
for month in range(1, 13):
mon = str(month).zfill(2)
for day in range(1, monthrange(2016, month)[1] + 1):
@@ -205,6 +206,8 @@ def set_up_yearly_data():
rate=0.33,
postage='second')
start_date, end_date = get_month_start_and_end_date_in_utc(datetime(2016, int(mon), 1))
create_annual_billing(service_id=service.id, free_sms_fragment_limit=4, financial_year_start=2016)
return service
@@ -246,15 +249,18 @@ def test_get_yearly_billing_usage_summary_from_ft_billing(admin_request, notify_
assert json_response[0]['chargeable_units'] == 275
assert json_response[0]['rate'] == 0
assert json_response[0]['letter_total'] == 0
assert json_response[0]['cost'] == 0
assert json_response[1]['notification_type'] == 'letter'
assert json_response[1]['billing_units'] == 275
assert json_response[1]['chargeable_units'] == 275
assert json_response[1]['rate'] == 0.33
assert json_response[1]['letter_total'] == 90.75
assert json_response[1]['cost'] == 90.75
assert json_response[2]['notification_type'] == 'sms'
assert json_response[2]['billing_units'] == 825
assert json_response[2]['chargeable_units'] == 825
assert json_response[2]['rate'] == 0.0162
assert json_response[2]['letter_total'] == 0
assert json_response[2]['cost'] == 13.3002