From 6f420cf06631cb4f8272066040bacbb6581c5b2a Mon Sep 17 00:00:00 2001 From: Leo Hemsted Date: Thu, 29 Aug 2019 17:59:31 +0100 Subject: [PATCH] explicitly join tables from service, join organisation, the free_allowance_remainder subquery and the ft_billing table. Being explicit reduces confusion about what tables we're joining and how we're constraining those joins also remove references to AnnualBilling since we've already got the free sms allowance from the free_allowance_remainder subquery --- app/dao/fact_billing_dao.py | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/app/dao/fact_billing_dao.py b/app/dao/fact_billing_dao.py index 422d0db2f..219b130c2 100644 --- a/app/dao/fact_billing_dao.py +++ b/app/dao/fact_billing_dao.py @@ -64,11 +64,13 @@ def fetch_sms_free_allowance_remainder(start_date): def fetch_sms_billing_for_all_services(start_date, end_date): # ASSUMPTION: AnnualBilling has been populated for year. - billing_year = get_financial_year_for_datetime(start_date) free_allowance_remainder = fetch_sms_free_allowance_remainder(start_date).subquery() sms_billable_units = func.sum(FactBilling.billable_units * FactBilling.rate_multiplier) - sms_remainder = func.coalesce(free_allowance_remainder.c.sms_remainder, AnnualBilling.free_sms_fragment_limit) + sms_remainder = func.coalesce( + free_allowance_remainder.c.sms_remainder, + free_allowance_remainder.c.free_sms_fragment_limit + ) chargeable_sms = func.greatest(sms_billable_units - sms_remainder, 0) sms_cost = chargeable_sms * FactBilling.rate @@ -77,30 +79,30 @@ def fetch_sms_billing_for_all_services(start_date, end_date): Organisation.id.label('organisation_id'), Service.name.label("service_name"), FactBilling.service_id.label("service_id"), - AnnualBilling.free_sms_fragment_limit, + free_allowance_remainder.c.free_sms_fragment_limit, FactBilling.rate.label('sms_rate'), sms_remainder.label("sms_remainder"), sms_billable_units.label('sms_billable_units'), chargeable_sms.label("chargeable_billable_sms"), sms_cost.label('sms_cost'), - ).join( - Service.annual_billing, + ).select_from( + Service ).outerjoin( free_allowance_remainder, Service.id == free_allowance_remainder.c.service_id ).outerjoin( - Organisation, Service.organisation_id == Organisation.id + Service.organisation + ).join( + FactBilling, FactBilling.service_id == Service.id, ).filter( - FactBilling.service_id == Service.id, FactBilling.bst_date >= start_date, FactBilling.bst_date <= end_date, FactBilling.notification_type == SMS_TYPE, - AnnualBilling.financial_year_start == billing_year, ).group_by( Organisation.name, Organisation.id, FactBilling.service_id, Service.name, - AnnualBilling.free_sms_fragment_limit, + free_allowance_remainder.c.free_sms_fragment_limit, free_allowance_remainder.c.sms_remainder, FactBilling.rate, ).order_by(