Implement ending/replacing date logic

This commit is contained in:
Nico Schottelius 2020-08-27 22:00:54 +02:00
commit 18f9a3848a
2 changed files with 49 additions and 5 deletions

View file

@ -57,6 +57,10 @@ def end_before(a_date):
""" Return suitable datetimefield for ending just before a_date """
return a_date - datetime.timedelta(seconds=1)
def start_after(a_date):
""" Return suitable datetimefield for starting just after a_date """
return a_date + datetime.timedelta(seconds=1)
def default_payment_delay():
return timezone.now() + BILL_PAYMENT_DELAY
@ -333,6 +337,24 @@ class Order(models.Model):
return self.starting_date + datetime.timedelta(seconds=self.recurring_period)
@property
def next_ending_date(self):
"""
Return the next proper ending date after n times the
recurring_period, where n is an integer.
"""
if self.recurring_period > 0:
now = timezone.now()
delta = now - self.starting_date
num_times = math.ceil(delta.total_seconds() / self.recurring_period)
next_date = self.starting_date + datetime.timedelta(seconds= num_times * self.recurring_period)
else:
next_date = self.starting_date
return next_date
@property
def count_billed(self):
@ -698,7 +720,6 @@ class Product(UncloudModel):
def create_or_update_recurring_order(self, when_to_start=None, recurring_period=None):
if not self.recurring_price:
return
@ -709,6 +730,13 @@ class Product(UncloudModel):
when_to_start = timezone.now()
if self.last_recurring_order:
# If the new order is less in value than the previous
# order, the previous order needs to be finished first
if self.recurring_price < self.last_recurring_order.price:
if when_to_start < self.last_recurring_order.next_ending_date:
when_to_start = start_after(self.last_recurring_order.next_ending_date)
when_to_end = end_before(when_to_start)
new_order = Order.objects.create(owner=self.owner,