diff --git a/uncloud/uncloud_pay/models.py b/uncloud/uncloud_pay/models.py index 24cc858..4e5770a 100644 --- a/uncloud/uncloud_pay/models.py +++ b/uncloud/uncloud_pay/models.py @@ -8,6 +8,7 @@ from math import ceil from datetime import timedelta from calendar import monthrange +from decimal import Decimal import uuid # Define DecimalField properties, used to represent amounts of money. @@ -113,7 +114,7 @@ class Bill(models.Model): @property def total(self): - return reduce(lambda acc, record: acc + record.amount(), self.records, 0) + return reduce(lambda acc, record: acc + record.amount, self.records, 0) @property def final(self): @@ -133,7 +134,8 @@ class BillRecord(): self.recurring_period = order_record.recurring_period self.description = order_record.description - def amount(self): + @property + def recurring_count(self): # Compute billing delta. billed_until = self.bill.ending_date if self.order.ending_date != None and self.order.ending_date < self.order.ending_date: @@ -166,21 +168,23 @@ class BillRecord(): (_, days_in_month) = monthrange( self.bill.starting_date.year, self.bill.starting_date.month) - adjusted_recurring_price = self.recurring_price / days_in_month - amount = adjusted_recurring_price * days + return Decimal(days / days_in_month) elif self.recurring_period == RecurringPeriod.PER_DAY: days = ceil(billed_delta / timedelta(days=1)) - amount = self.recurring_price * days + return Decimal(days) elif self.recurring_period == RecurringPeriod.PER_HOUR: hours = ceil(billed_delta / timedelta(hours=1)) - amount = self.recurring_price * hours + return Decimal(hours) elif self.recurring_period == RecurringPeriod.PER_SECOND: seconds = ceil(billed_delta / timedelta(seconds=1)) - amount = self.recurring_price * seconds + return Decimal(seconds) else: raise Exception('Unsupported recurring period: {}.'. format(record.recurring_period)) + @property + def amount(self): + amount = self.recurring_count * self.recurring_price if self.order.starting_date > self.bill.starting_date: amount += self.setup_fee diff --git a/uncloud/uncloud_pay/serializers.py b/uncloud/uncloud_pay/serializers.py index fcbaf73..051b882 100644 --- a/uncloud/uncloud_pay/serializers.py +++ b/uncloud/uncloud_pay/serializers.py @@ -96,6 +96,7 @@ class BillRecordSerializer(serializers.Serializer): description = serializers.CharField() recurring_period = serializers.CharField() recurring_price = serializers.DecimalField(max_digits=10, decimal_places=2) + recurring_count = serializers.DecimalField(max_digits=10, decimal_places=2) setup_fee = serializers.DecimalField(max_digits=10, decimal_places=2) amount = serializers.DecimalField(max_digits=10, decimal_places=2)