Add .cost() to notification model

In the V2 API, the GET response for an individual notification
returns a 'cost' value, which we can get by multiplying the
billable units by the per-message rate of the supplier who
sent the message.
Any notifications with billable units > 0 but without a
corresponding `ProviderRates` entry will blow up the application,
so make sure you've got one.
This commit is contained in:
Paul Craig
2016-11-18 15:09:15 +00:00
parent 1345c94f4b
commit fddb1653ac
4 changed files with 58 additions and 8 deletions

View File

@@ -5,7 +5,7 @@ from sqlalchemy.dialects.postgresql import (
UUID,
JSON
)
from sqlalchemy import UniqueConstraint, and_
from sqlalchemy import UniqueConstraint, and_, desc
from sqlalchemy.orm import foreign, remote
from notifications_utils.recipients import (
validate_email_address,
@@ -538,6 +538,21 @@ class Notification(db.Model):
if personalisation:
self._personalisation = encryption.encrypt(personalisation)
def cost(self):
if not self.sent_by or self.billable_units == 0:
return 0
provider_rate = db.session.query(
ProviderRates
).join(ProviderDetails).filter(
ProviderDetails.identifier == self.sent_by,
ProviderRates.provider_id == ProviderDetails.id
).order_by(
desc(ProviderRates.valid_from)
).limit(1).one()
return provider_rate.rate * self.billable_units
class NotificationHistory(db.Model):
__tablename__ = 'notification_history'