2020-10-08 17:54:04 +00:00
|
|
|
import logging
|
|
|
|
import datetime
|
2021-01-17 14:53:30 +00:00
|
|
|
|
2020-10-08 17:54:04 +00:00
|
|
|
from math import ceil
|
|
|
|
from calendar import monthrange
|
|
|
|
from decimal import Decimal
|
|
|
|
|
2021-01-17 14:53:30 +00:00
|
|
|
from django.conf import settings
|
2020-02-27 10:21:38 +00:00
|
|
|
from django.contrib.auth import get_user_model
|
2020-05-08 08:56:03 +00:00
|
|
|
from django.core.validators import MinValueValidator
|
2021-01-17 14:53:30 +00:00
|
|
|
from django.db import models
|
|
|
|
from django.utils.translation import gettext_lazy as _
|
2020-02-29 08:08:30 +00:00
|
|
|
from django.utils import timezone
|
2021-01-17 14:53:30 +00:00
|
|
|
|
|
|
|
# Verify whether or not to use them here
|
2020-05-01 22:16:29 +00:00
|
|
|
from django.core.exceptions import ObjectDoesNotExist, ValidationError
|
2020-03-18 13:53:26 +00:00
|
|
|
|
2020-12-09 19:22:33 +00:00
|
|
|
from uncloud import AMOUNT_DECIMALS, AMOUNT_MAX_DIGITS
|
2020-10-11 20:32:08 +00:00
|
|
|
from uncloud.models import UncloudAddress
|
2021-01-17 14:53:30 +00:00
|
|
|
from .services import *
|
2020-03-04 09:55:12 +00:00
|
|
|
|
|
|
|
# Used to generate bill due dates.
|
2020-06-21 14:08:00 +00:00
|
|
|
BILL_PAYMENT_DELAY=datetime.timedelta(days=10)
|
2020-03-04 09:55:12 +00:00
|
|
|
|
2020-03-09 10:30:31 +00:00
|
|
|
# Initialize logger.
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2020-06-21 14:08:00 +00:00
|
|
|
def default_payment_delay():
|
|
|
|
return timezone.now() + BILL_PAYMENT_DELAY
|
|
|
|
|
2020-09-28 19:34:24 +00:00
|
|
|
class Currency(models.TextChoices):
|
|
|
|
"""
|
2020-10-06 22:54:56 +00:00
|
|
|
Possible currencies to be billed
|
2020-09-28 19:34:24 +00:00
|
|
|
"""
|
|
|
|
CHF = 'CHF', _('Swiss Franc')
|
2020-12-29 00:43:33 +00:00
|
|
|
# EUR = 'EUR', _('Euro')
|
|
|
|
# USD = 'USD', _('US Dollar')
|
2020-09-28 19:34:24 +00:00
|
|
|
|
2020-03-04 08:39:18 +00:00
|
|
|
|
2020-10-06 22:54:56 +00:00
|
|
|
###
|
|
|
|
# Stripe
|
|
|
|
|
2020-03-04 08:39:18 +00:00
|
|
|
class StripeCustomer(models.Model):
|
|
|
|
owner = models.OneToOneField( get_user_model(),
|
|
|
|
primary_key=True,
|
|
|
|
on_delete=models.CASCADE)
|
|
|
|
stripe_id = models.CharField(max_length=32)
|
|
|
|
|
2020-12-25 09:31:42 +00:00
|
|
|
def __str__(self):
|
|
|
|
return self.owner.username
|
2020-10-06 22:54:56 +00:00
|
|
|
|
2020-12-28 22:35:34 +00:00
|
|
|
|
|
|
|
class StripeCreditCard(models.Model):
|
2020-12-29 00:43:33 +00:00
|
|
|
owner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
|
2020-12-28 22:35:34 +00:00
|
|
|
|
|
|
|
card_name = models.CharField(null=False, max_length=128, default="My credit card")
|
|
|
|
card_id = models.CharField(null=False, max_length=32)
|
|
|
|
last4 = models.CharField(null=False, max_length=4)
|
|
|
|
brand = models.CharField(null=False, max_length=64)
|
|
|
|
expiry_date = models.DateField(null=False)
|
2020-12-29 00:43:33 +00:00
|
|
|
active = models.BooleanField(default=False)
|
2020-12-28 22:35:34 +00:00
|
|
|
|
2020-12-29 00:43:33 +00:00
|
|
|
class Meta:
|
|
|
|
constraints = [
|
|
|
|
models.UniqueConstraint(fields=['owner'],
|
2021-01-17 14:53:30 +00:00
|
|
|
condition=models.Q(active=True),
|
2020-12-29 00:43:33 +00:00
|
|
|
name='one_active_card_per_user')
|
|
|
|
]
|
2020-12-28 22:35:34 +00:00
|
|
|
|
|
|
|
|
2020-12-29 00:43:33 +00:00
|
|
|
def __str__(self):
|
|
|
|
return f"{self.card_name}: {self.brand} {self.last4} ({self.expiry_date})"
|
2020-03-03 08:13:04 +00:00
|
|
|
|
|
|
|
class Payment(models.Model):
|
2020-12-29 00:43:33 +00:00
|
|
|
owner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
|
2020-03-03 08:13:04 +00:00
|
|
|
|
|
|
|
amount = models.DecimalField(
|
|
|
|
max_digits=AMOUNT_MAX_DIGITS,
|
|
|
|
decimal_places=AMOUNT_DECIMALS,
|
|
|
|
validators=[MinValueValidator(0)])
|
|
|
|
|
|
|
|
source = models.CharField(max_length=256,
|
|
|
|
choices = (
|
|
|
|
('wire', 'Wire Transfer'),
|
|
|
|
('stripe', 'Stripe'),
|
|
|
|
('voucher', 'Voucher'),
|
|
|
|
('referral', 'Referral'),
|
2021-01-17 14:53:30 +00:00
|
|
|
))
|
2020-03-03 08:13:04 +00:00
|
|
|
|
2020-12-29 00:43:33 +00:00
|
|
|
timestamp = models.DateTimeField(default=timezone.now)
|
2020-03-04 09:55:12 +00:00
|
|
|
|
2020-12-29 00:43:33 +00:00
|
|
|
currency = models.CharField(max_length=32, choices=Currency.choices, default=Currency.CHF)
|
2020-03-04 09:55:12 +00:00
|
|
|
|
2020-12-29 00:43:33 +00:00
|
|
|
external_reference = models.CharField(max_length=256, default="", null=True, blank=True)
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return f"{self.amount}{self.currency} from {self.owner} via {self.source} on {self.timestamp}"
|
|
|
|
|
|
|
|
###
|
|
|
|
# Payments and Payment Methods.
|
2020-03-04 09:55:12 +00:00
|
|
|
|
2020-05-23 21:08:59 +00:00
|
|
|
|
2020-03-03 08:13:04 +00:00
|
|
|
class PaymentMethod(models.Model):
|
2021-01-17 14:53:30 +00:00
|
|
|
"""
|
|
|
|
Not sure if this is still in use
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
2020-03-03 08:13:04 +00:00
|
|
|
owner = models.ForeignKey(get_user_model(),
|
|
|
|
on_delete=models.CASCADE,
|
|
|
|
editable=False)
|
|
|
|
source = models.CharField(max_length=256,
|
|
|
|
choices = (
|
|
|
|
('stripe', 'Stripe'),
|
|
|
|
('unknown', 'Unknown'),
|
|
|
|
),
|
|
|
|
default='stripe')
|
|
|
|
description = models.TextField()
|
2020-03-05 14:19:25 +00:00
|
|
|
primary = models.BooleanField(default=False, editable=False)
|
2020-03-03 08:13:04 +00:00
|
|
|
|
|
|
|
# Only used for "Stripe" source
|
2020-03-05 09:23:34 +00:00
|
|
|
stripe_payment_method_id = models.CharField(max_length=32, blank=True, null=True)
|
|
|
|
stripe_setup_intent_id = models.CharField(max_length=32, blank=True, null=True)
|
2020-03-03 08:13:04 +00:00
|
|
|
|
2020-03-05 09:23:34 +00:00
|
|
|
@property
|
|
|
|
def active(self):
|
|
|
|
if self.source == 'stripe' and self.stripe_payment_method_id != None:
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
return False
|
2020-03-03 15:55:56 +00:00
|
|
|
|
2020-03-03 08:13:04 +00:00
|
|
|
def charge(self, amount):
|
2020-03-05 10:03:47 +00:00
|
|
|
if not self.active:
|
|
|
|
raise Exception('This payment method is inactive.')
|
|
|
|
|
2020-03-05 10:13:04 +00:00
|
|
|
if amount < 0: # Make sure we don't charge negative amount by errors...
|
2020-03-05 10:03:47 +00:00
|
|
|
raise Exception('Cannot charge negative amount.')
|
|
|
|
|
|
|
|
if self.source == 'stripe':
|
|
|
|
stripe_customer = StripeCustomer.objects.get(owner=self.owner).stripe_id
|
|
|
|
stripe_payment = uncloud_pay.stripe.charge_customer(
|
|
|
|
amount, stripe_customer, self.stripe_payment_method_id)
|
2020-03-05 10:13:04 +00:00
|
|
|
if 'paid' in stripe_payment and stripe_payment['paid'] == False:
|
|
|
|
raise Exception(stripe_payment['error'])
|
|
|
|
else:
|
|
|
|
payment = Payment.objects.create(
|
|
|
|
owner=self.owner, source=self.source, amount=amount)
|
2020-03-05 10:03:47 +00:00
|
|
|
|
|
|
|
return payment
|
2020-03-03 08:13:04 +00:00
|
|
|
else:
|
2020-03-05 10:03:47 +00:00
|
|
|
raise Exception('This payment method is unsupported/cannot be charged.')
|
2020-03-03 08:13:04 +00:00
|
|
|
|
2020-03-05 14:19:25 +00:00
|
|
|
def set_as_primary_for(self, user):
|
|
|
|
methods = PaymentMethod.objects.filter(owner=user, primary=True)
|
|
|
|
for method in methods:
|
|
|
|
print(method)
|
|
|
|
method.primary = False
|
|
|
|
method.save()
|
|
|
|
|
|
|
|
self.primary = True
|
|
|
|
self.save()
|
2020-03-04 08:39:18 +00:00
|
|
|
|
|
|
|
def get_primary_for(user):
|
|
|
|
methods = PaymentMethod.objects.filter(owner=user)
|
|
|
|
for method in methods:
|
|
|
|
# Do we want to do something with non-primary method?
|
2020-03-05 10:03:47 +00:00
|
|
|
if method.active and method.primary:
|
2020-03-04 08:39:18 +00:00
|
|
|
return method
|
|
|
|
|
|
|
|
return None
|
|
|
|
|
2020-03-03 08:13:04 +00:00
|
|
|
class Meta:
|
2020-03-05 10:03:47 +00:00
|
|
|
# TODO: limit to one primary method per user.
|
|
|
|
# unique_together is no good since it won't allow more than one
|
|
|
|
# non-primary method.
|
2020-03-05 09:23:34 +00:00
|
|
|
pass
|
2020-03-03 08:13:04 +00:00
|
|
|
|
2020-10-06 13:46:22 +00:00
|
|
|
# See https://docs.djangoproject.com/en/dev/ref/models/fields/#field-choices-enum-types
|
2020-11-15 14:43:11 +00:00
|
|
|
class RecurringPeriodDefaultChoices(models.IntegerChoices):
|
2020-10-06 13:46:22 +00:00
|
|
|
"""
|
|
|
|
This is an old class and being superseeded by the database model below
|
|
|
|
"""
|
|
|
|
PER_365D = 365*24*3600, _('Per 365 days')
|
|
|
|
PER_30D = 30*24*3600, _('Per 30 days')
|
|
|
|
PER_WEEK = 7*24*3600, _('Per Week')
|
|
|
|
PER_DAY = 24*3600, _('Per Day')
|
|
|
|
PER_HOUR = 3600, _('Per Hour')
|
|
|
|
PER_MINUTE = 60, _('Per Minute')
|
|
|
|
PER_SECOND = 1, _('Per Second')
|
|
|
|
ONE_TIME = 0, _('Onetime')
|
|
|
|
|
|
|
|
# RecurringPeriods
|
|
|
|
class RecurringPeriod(models.Model):
|
|
|
|
"""
|
|
|
|
Available recurring periods.
|
|
|
|
By default seeded from RecurringPeriodChoices
|
|
|
|
"""
|
|
|
|
|
|
|
|
name = models.CharField(max_length=100, unique=True)
|
|
|
|
duration_seconds = models.IntegerField(unique=True)
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def populate_db_defaults(cls):
|
2020-11-15 14:43:11 +00:00
|
|
|
for (seconds, name) in RecurringPeriodDefaultChoices.choices:
|
2020-10-06 13:46:22 +00:00
|
|
|
obj, created = cls.objects.get_or_create(name=name,
|
|
|
|
defaults={ 'duration_seconds': seconds })
|
|
|
|
|
2020-10-06 16:53:13 +00:00
|
|
|
@staticmethod
|
|
|
|
def secs_to_name(secs):
|
|
|
|
name = ""
|
|
|
|
days = 0
|
|
|
|
hours = 0
|
|
|
|
|
|
|
|
if secs > 24*3600:
|
|
|
|
days = secs // (24*3600)
|
|
|
|
secs -= (days*24*3600)
|
|
|
|
|
|
|
|
if secs > 3600:
|
|
|
|
hours = secs // 3600
|
|
|
|
secs -= hours*3600
|
|
|
|
|
|
|
|
return f"{days} days {hours} hours {secs} seconds"
|
|
|
|
|
2020-10-06 13:46:22 +00:00
|
|
|
def __str__(self):
|
2020-10-06 16:53:13 +00:00
|
|
|
duration = self.secs_to_name(self.duration_seconds)
|
|
|
|
|
|
|
|
return f"{self.name} ({duration})"
|
|
|
|
|
|
|
|
|
2020-03-03 08:13:04 +00:00
|
|
|
###
|
2020-03-05 09:27:33 +00:00
|
|
|
# Bills.
|
2020-03-03 08:13:04 +00:00
|
|
|
|
2020-10-25 12:52:36 +00:00
|
|
|
class BillingAddress(UncloudAddress):
|
2020-04-18 06:30:45 +00:00
|
|
|
owner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
|
|
|
|
vat_number = models.CharField(max_length=100, default="", blank=True)
|
2020-06-21 12:35:12 +00:00
|
|
|
active = models.BooleanField(default=False)
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
constraints = [
|
|
|
|
models.UniqueConstraint(fields=['owner'],
|
2021-01-17 14:53:30 +00:00
|
|
|
condition=models.Q(active=True),
|
2020-06-21 12:35:12 +00:00
|
|
|
name='one_active_billing_address_per_user')
|
|
|
|
]
|
2020-04-18 06:30:45 +00:00
|
|
|
|
2020-10-08 17:54:04 +00:00
|
|
|
@classmethod
|
|
|
|
def populate_db_defaults(cls):
|
|
|
|
"""
|
|
|
|
Ensure we have at least one billing address that is associated with the uncloud-admin.
|
|
|
|
|
|
|
|
This way we are sure that an UncloudProvider can be created.
|
|
|
|
|
|
|
|
Cannot use get_or_create as that looks for exactly one.
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
owner = get_user_model().objects.get(username=settings.UNCLOUD_ADMIN_NAME)
|
|
|
|
billing_address = cls.objects.filter(owner=owner).first()
|
|
|
|
|
|
|
|
if not billing_address:
|
|
|
|
billing_address = cls.objects.create(owner=owner,
|
|
|
|
organization="uncloud admins",
|
2021-01-17 14:53:30 +00:00
|
|
|
full_name="Uncloud Admin",
|
2020-10-08 17:54:04 +00:00
|
|
|
street="Uncloudstreet. 42",
|
|
|
|
city="Luchsingen",
|
|
|
|
postal_code="8775",
|
|
|
|
country="CH",
|
|
|
|
active=True)
|
|
|
|
|
2020-04-18 06:30:45 +00:00
|
|
|
def __str__(self):
|
2020-06-21 11:46:54 +00:00
|
|
|
return "{} - {}, {}, {} {}, {}".format(
|
|
|
|
self.owner,
|
2020-10-25 12:52:36 +00:00
|
|
|
self.full_name, self.street, self.postal_code, self.city,
|
2020-06-21 11:46:54 +00:00
|
|
|
self.country)
|
|
|
|
|
|
|
|
###
|
|
|
|
# VAT
|
2020-04-18 06:30:45 +00:00
|
|
|
|
2020-04-18 09:43:55 +00:00
|
|
|
class VATRate(models.Model):
|
2020-08-04 09:26:42 +00:00
|
|
|
starting_date = models.DateField(blank=True, null=True)
|
|
|
|
ending_date = models.DateField(blank=True, null=True)
|
2020-04-18 09:43:55 +00:00
|
|
|
territory_codes = models.TextField(blank=True, default='')
|
|
|
|
currency_code = models.CharField(max_length=10)
|
|
|
|
rate = models.FloatField()
|
|
|
|
rate_type = models.TextField(blank=True, default='')
|
|
|
|
description = models.TextField(blank=True, default='')
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def get_for_country(country_code):
|
|
|
|
vat_rate = None
|
|
|
|
try:
|
|
|
|
vat_rate = VATRate.objects.get(
|
|
|
|
territory_codes=country_code, start_date__isnull=False, stop_date=None
|
|
|
|
)
|
|
|
|
return vat_rate.rate
|
|
|
|
except VATRate.DoesNotExist as dne:
|
|
|
|
logger.debug(str(dne))
|
|
|
|
logger.debug("Did not find VAT rate for %s, returning 0" % country_code)
|
|
|
|
return 0
|
2020-04-18 06:30:45 +00:00
|
|
|
|
2020-10-08 17:54:04 +00:00
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return f"{self.territory_codes}: {self.starting_date} - {self.ending_date}: {self.rate_type}"
|
|
|
|
|
2020-09-28 19:34:24 +00:00
|
|
|
###
|
|
|
|
# Products
|
|
|
|
|
2020-10-11 20:32:08 +00:00
|
|
|
class Product(models.Model):
|
2020-09-28 19:34:24 +00:00
|
|
|
"""
|
|
|
|
A product is something a user can order. To record the pricing, we
|
|
|
|
create order that define a state in time.
|
|
|
|
|
|
|
|
A product can have *one* one_time_order and/or *one*
|
|
|
|
recurring_order.
|
|
|
|
|
|
|
|
If either of them needs to be updated, a new order of the same
|
|
|
|
type will be created and links to the previous order.
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
2020-10-06 16:53:13 +00:00
|
|
|
name = models.CharField(max_length=256, unique=True)
|
2020-09-28 19:34:24 +00:00
|
|
|
description = models.CharField(max_length=1024)
|
|
|
|
config = models.JSONField()
|
2020-10-06 16:53:13 +00:00
|
|
|
recurring_periods = models.ManyToManyField(RecurringPeriod, through='ProductToRecurringPeriod')
|
|
|
|
currency = models.CharField(max_length=32, choices=Currency.choices, default=Currency.CHF)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def default_recurring_period(self):
|
2020-10-06 17:21:37 +00:00
|
|
|
"""
|
|
|
|
Return the default recurring Period
|
|
|
|
"""
|
|
|
|
return self.recurring_periods.get(producttorecurringperiod__is_default=True)
|
2020-10-06 13:46:22 +00:00
|
|
|
|
2020-10-06 16:53:13 +00:00
|
|
|
@classmethod
|
|
|
|
def populate_db_defaults(cls):
|
|
|
|
recurring_period = RecurringPeriod.objects.get(name="Per 30 days")
|
|
|
|
|
|
|
|
obj, created = cls.objects.get_or_create(name="Dual Stack Virtual Machine v1",
|
|
|
|
description="A standard virtual machine",
|
|
|
|
currency=Currency.CHF,
|
|
|
|
config={
|
|
|
|
'features': {
|
|
|
|
'cores':
|
|
|
|
{ 'min': 1,
|
|
|
|
'max': 48,
|
|
|
|
'one_time_price_per_unit': 0,
|
|
|
|
'recurring_price_per_unit': 3
|
|
|
|
},
|
|
|
|
'ram_gb':
|
|
|
|
{ 'min': 1,
|
|
|
|
'max': 256,
|
|
|
|
'one_time_price_per_unit': 0,
|
|
|
|
'recurring_price_per_unit': 4
|
|
|
|
},
|
|
|
|
'ssd_gb':
|
2020-10-06 21:14:32 +00:00
|
|
|
{ 'min': 10,
|
2020-10-06 16:53:13 +00:00
|
|
|
'one_time_price_per_unit': 0,
|
2020-10-06 21:14:32 +00:00
|
|
|
'recurring_price_per_unit': 0.35
|
2020-10-06 16:53:13 +00:00
|
|
|
},
|
|
|
|
'hdd_gb':
|
|
|
|
{ 'min': 0,
|
|
|
|
'one_time_price_per_unit': 0,
|
|
|
|
'recurring_price_per_unit': 15/1000
|
|
|
|
},
|
2020-10-06 22:54:56 +00:00
|
|
|
'additional_ipv4_address':
|
|
|
|
{ 'min': 0,
|
|
|
|
'one_time_price_per_unit': 0,
|
|
|
|
'recurring_price_per_unit': 8
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
obj.recurring_periods.add(recurring_period, through_defaults= { 'is_default': True })
|
|
|
|
|
|
|
|
obj, created = cls.objects.get_or_create(name="Dual Stack Virtual Machine v2",
|
|
|
|
description="A standard virtual machine",
|
|
|
|
currency=Currency.CHF,
|
|
|
|
config={
|
|
|
|
'features': {
|
|
|
|
'base':
|
|
|
|
{ 'min': 1,
|
|
|
|
'max': 1,
|
|
|
|
'one_time_price_per_unit': 0,
|
|
|
|
'recurring_price_per_unit': 1
|
|
|
|
},
|
|
|
|
'cores':
|
|
|
|
{ 'min': 1,
|
|
|
|
'max': 48,
|
|
|
|
'one_time_price_per_unit': 0,
|
|
|
|
'recurring_price_per_unit': 3
|
|
|
|
},
|
|
|
|
'ram_gb':
|
|
|
|
{ 'min': 1,
|
|
|
|
'max': 256,
|
|
|
|
'one_time_price_per_unit': 0,
|
|
|
|
'recurring_price_per_unit': 4
|
|
|
|
},
|
|
|
|
'ssd_gb':
|
|
|
|
{ 'min': 10,
|
|
|
|
'one_time_price_per_unit': 0,
|
|
|
|
'recurring_price_per_unit': 0.35
|
|
|
|
},
|
|
|
|
'hdd_gb':
|
|
|
|
{ 'min': 0,
|
|
|
|
'one_time_price_per_unit': 0,
|
|
|
|
'recurring_price_per_unit': 15/1000
|
|
|
|
},
|
|
|
|
'additional_ipv4_address':
|
|
|
|
{ 'min': 0,
|
|
|
|
'one_time_price_per_unit': 0,
|
|
|
|
'recurring_price_per_unit': 9
|
|
|
|
},
|
2020-10-06 16:53:13 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
obj.recurring_periods.add(recurring_period, through_defaults= { 'is_default': True })
|
2020-10-06 13:46:22 +00:00
|
|
|
|
2020-10-25 21:43:34 +00:00
|
|
|
obj, created = cls.objects.get_or_create(name="reverse DNS",
|
|
|
|
description="Reverse DNS network",
|
|
|
|
currency=Currency.CHF,
|
|
|
|
config={
|
|
|
|
'parameters': [
|
|
|
|
'network'
|
|
|
|
]
|
|
|
|
})
|
|
|
|
obj.recurring_periods.add(recurring_period, through_defaults= { 'is_default': True })
|
|
|
|
|
2020-10-06 13:46:22 +00:00
|
|
|
|
2020-10-06 16:53:13 +00:00
|
|
|
def __str__(self):
|
|
|
|
return f"{self.name} - {self.description}"
|
2020-09-28 19:34:24 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def recurring_orders(self):
|
2020-11-15 14:43:11 +00:00
|
|
|
return self.orders.order_by('id').exclude(recurring_period=RecurringPeriod.objects.get(name="ONE_TIME"))
|
2020-09-28 19:34:24 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def last_recurring_order(self):
|
|
|
|
return self.recurring_orders.last()
|
|
|
|
|
|
|
|
@property
|
|
|
|
def one_time_orders(self):
|
2020-11-15 14:43:11 +00:00
|
|
|
return self.orders.order_by('id').filter(recurring_period=RecurringPeriod.objects.get(name="ONE_TIME"))
|
2020-09-28 19:34:24 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def last_one_time_order(self):
|
|
|
|
return self.one_time_orders.last()
|
|
|
|
|
|
|
|
def create_order(self, when_to_start=None, recurring_period=None):
|
|
|
|
billing_address = BillingAddress.get_address_for(self.owner)
|
|
|
|
|
|
|
|
if not billing_address:
|
|
|
|
raise ValidationError("Cannot order without a billing address")
|
|
|
|
|
|
|
|
if not when_to_start:
|
|
|
|
when_to_start = timezone.now()
|
|
|
|
|
|
|
|
if not recurring_period:
|
|
|
|
recurring_period = self.default_recurring_period
|
|
|
|
|
|
|
|
|
|
|
|
# Create one time order if we did not create one already
|
|
|
|
if self.one_time_price > 0 and not self.last_one_time_order:
|
|
|
|
one_time_order = Order.objects.create(owner=self.owner,
|
|
|
|
billing_address=billing_address,
|
|
|
|
starting_date=when_to_start,
|
|
|
|
price=self.one_time_price,
|
2020-11-15 14:43:11 +00:00
|
|
|
recurring_period=RecurringPeriod.objects.get(name="ONE_TIME"),
|
2020-09-28 19:34:24 +00:00
|
|
|
description=str(self))
|
|
|
|
self.orders.add(one_time_order)
|
|
|
|
else:
|
|
|
|
one_time_order = None
|
|
|
|
|
2020-11-15 14:43:11 +00:00
|
|
|
if recurring_period != RecurringPeriod.objects.get(name="ONE_TIME"):
|
2020-09-28 19:34:24 +00:00
|
|
|
if one_time_order:
|
|
|
|
recurring_order = Order.objects.create(owner=self.owner,
|
|
|
|
billing_address=billing_address,
|
|
|
|
starting_date=when_to_start,
|
|
|
|
price=self.recurring_price,
|
|
|
|
recurring_period=recurring_period,
|
|
|
|
depends_on=one_time_order,
|
|
|
|
description=str(self))
|
|
|
|
else:
|
|
|
|
recurring_order = Order.objects.create(owner=self.owner,
|
|
|
|
billing_address=billing_address,
|
|
|
|
starting_date=when_to_start,
|
|
|
|
price=self.recurring_price,
|
|
|
|
recurring_period=recurring_period,
|
|
|
|
description=str(self))
|
|
|
|
self.orders.add(recurring_order)
|
|
|
|
|
|
|
|
|
|
|
|
# FIXME: this could/should be part of Order (?)
|
|
|
|
def create_or_update_recurring_order(self, when_to_start=None, recurring_period=None):
|
|
|
|
if not self.recurring_price:
|
|
|
|
return
|
|
|
|
|
|
|
|
if not recurring_period:
|
|
|
|
recurring_period = self.default_recurring_period
|
|
|
|
|
|
|
|
if not when_to_start:
|
|
|
|
when_to_start = timezone.now()
|
|
|
|
|
|
|
|
if self.last_recurring_order:
|
|
|
|
if self.recurring_price < self.last_recurring_order.price:
|
|
|
|
|
|
|
|
if when_to_start < self.last_recurring_order.next_cancel_or_downgrade_date:
|
|
|
|
when_to_start = start_after(self.last_recurring_order.next_cancel_or_downgrade_date)
|
|
|
|
|
|
|
|
when_to_end = end_before(when_to_start)
|
|
|
|
|
|
|
|
new_order = Order.objects.create(owner=self.owner,
|
|
|
|
billing_address=self.last_recurring_order.billing_address,
|
|
|
|
starting_date=when_to_start,
|
|
|
|
price=self.recurring_price,
|
|
|
|
recurring_period=recurring_period,
|
|
|
|
description=str(self),
|
|
|
|
replaces=self.last_recurring_order)
|
|
|
|
|
|
|
|
self.last_recurring_order.replace_with(new_order)
|
|
|
|
self.orders.add(new_order)
|
|
|
|
else:
|
|
|
|
self.create_order(when_to_start, recurring_period)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def is_recurring(self):
|
|
|
|
return self.recurring_price > 0
|
|
|
|
|
|
|
|
@property
|
|
|
|
def billing_address(self):
|
|
|
|
return self.order.billing_address
|
|
|
|
|
|
|
|
def discounted_price_by_period(self, requested_period):
|
|
|
|
"""
|
|
|
|
Each product has a standard recurring period for which
|
|
|
|
we define a pricing. I.e. VPN is usually year, VM is usually monthly.
|
|
|
|
|
|
|
|
The user can opt-in to use a different period, which influences the price:
|
|
|
|
The longer a user commits, the higher the discount.
|
|
|
|
|
|
|
|
Products can also be limited in the available periods. For instance
|
|
|
|
a VPN only makes sense to be bought for at least one day.
|
|
|
|
|
|
|
|
Rules are as follows:
|
|
|
|
|
|
|
|
given a standard recurring period of ..., changing to ... modifies price ...
|
|
|
|
|
|
|
|
|
|
|
|
# One month for free if buying / year, compared to a month: about 8.33% discount
|
|
|
|
per_year -> per_month -> /11
|
|
|
|
per_month -> per_year -> *11
|
|
|
|
|
|
|
|
# Month has 30.42 days on average. About 7.9% discount to go monthly
|
|
|
|
per_month -> per_day -> /28
|
|
|
|
per_day -> per_month -> *28
|
|
|
|
|
|
|
|
# Day has 24h, give one for free
|
|
|
|
per_day -> per_hour -> /23
|
|
|
|
per_hour -> per_day -> /23
|
|
|
|
|
|
|
|
|
|
|
|
Examples
|
|
|
|
|
|
|
|
VPN @ 120CHF/y becomes
|
|
|
|
- 10.91 CHF/month (130.91 CHF/year)
|
|
|
|
- 0.39 CHF/day (142.21 CHF/year)
|
|
|
|
|
|
|
|
VM @ 15 CHF/month becomes
|
|
|
|
- 165 CHF/month (13.75 CHF/month)
|
|
|
|
- 0.54 CHF/day (16.30 CHF/month)
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
2020-10-06 22:54:56 +00:00
|
|
|
# FIXME: This logic needs to be phased out / replaced by product specific (?)
|
|
|
|
# proportions. Maybe using the RecurringPeriod table to link the possible discounts/add ups
|
2020-09-28 19:34:24 +00:00
|
|
|
|
|
|
|
if self.default_recurring_period == RecurringPeriod.PER_365D:
|
|
|
|
if requested_period == RecurringPeriod.PER_365D:
|
|
|
|
return self.recurring_price
|
|
|
|
if requested_period == RecurringPeriod.PER_30D:
|
|
|
|
return self.recurring_price/11.
|
|
|
|
if requested_period == RecurringPeriod.PER_DAY:
|
|
|
|
return self.recurring_price/11./28.
|
|
|
|
|
|
|
|
elif self.default_recurring_period == RecurringPeriod.PER_30D:
|
|
|
|
if requested_period == RecurringPeriod.PER_365D:
|
|
|
|
return self.recurring_price*11
|
|
|
|
if requested_period == RecurringPeriod.PER_30D:
|
|
|
|
return self.recurring_price
|
|
|
|
if requested_period == RecurringPeriod.PER_DAY:
|
|
|
|
return self.recurring_price/28.
|
|
|
|
|
|
|
|
elif self.default_recurring_period == RecurringPeriod.PER_DAY:
|
|
|
|
if requested_period == RecurringPeriod.PER_365D:
|
|
|
|
return self.recurring_price*11*28
|
|
|
|
if requested_period == RecurringPeriod.PER_30D:
|
|
|
|
return self.recurring_price*28
|
|
|
|
if requested_period == RecurringPeriod.PER_DAY:
|
|
|
|
return self.recurring_price
|
|
|
|
else:
|
|
|
|
# FIXME: use the right type of exception here!
|
|
|
|
raise Exception("Did not implement the discounter for this case")
|
|
|
|
|
|
|
|
|
|
|
|
def save(self, *args, **kwargs):
|
|
|
|
# try:
|
|
|
|
# ba = BillingAddress.get_address_for(self.owner)
|
|
|
|
# except BillingAddress.DoesNotExist:
|
|
|
|
# raise ValidationError("User does not have a billing address")
|
|
|
|
|
|
|
|
# if not ba.active:
|
|
|
|
# raise ValidationError("User does not have an active billing address")
|
|
|
|
|
|
|
|
|
|
|
|
# Verify the required JSON fields
|
|
|
|
|
|
|
|
super().save(*args, **kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
|
2020-03-03 08:13:04 +00:00
|
|
|
###
|
|
|
|
# Orders.
|
|
|
|
|
2020-02-27 10:21:38 +00:00
|
|
|
class Order(models.Model):
|
2020-05-24 11:45:03 +00:00
|
|
|
"""
|
|
|
|
Order are assumed IMMUTABLE and used as SOURCE OF TRUST for generating
|
|
|
|
bills. Do **NOT** mutate then!
|
2020-09-03 14:38:51 +00:00
|
|
|
|
|
|
|
An one time order is "closed" (does not need to be billed anymore)
|
|
|
|
if it has one bill record. Having more than one is a programming
|
|
|
|
error.
|
|
|
|
|
|
|
|
A recurring order is closed if it has been replaced
|
|
|
|
(replaces__isnull=False) AND the ending_date is set AND it was
|
|
|
|
billed the last time it needed to be billed (how to check the last
|
|
|
|
item?)
|
|
|
|
|
|
|
|
BOTH are closed, if they are ended/closed AND have been fully
|
|
|
|
charged.
|
|
|
|
|
|
|
|
Fully charged == fully billed: sum_of_order_usage == sum_of_bill_records
|
|
|
|
|
2020-05-24 11:45:03 +00:00
|
|
|
"""
|
|
|
|
|
2020-02-27 10:21:38 +00:00
|
|
|
owner = models.ForeignKey(get_user_model(),
|
|
|
|
on_delete=models.CASCADE,
|
2020-06-21 12:35:12 +00:00
|
|
|
editable=True)
|
|
|
|
|
|
|
|
billing_address = models.ForeignKey(BillingAddress,
|
|
|
|
on_delete=models.CASCADE)
|
2020-08-01 16:27:12 +00:00
|
|
|
|
2020-05-07 10:08:18 +00:00
|
|
|
description = models.TextField()
|
2020-02-27 10:21:38 +00:00
|
|
|
|
2020-09-28 19:34:24 +00:00
|
|
|
product = models.ForeignKey(Product, blank=False, null=False, on_delete=models.CASCADE)
|
|
|
|
config = models.JSONField()
|
|
|
|
|
2020-05-02 20:48:05 +00:00
|
|
|
creation_date = models.DateTimeField(auto_now_add=True)
|
|
|
|
starting_date = models.DateTimeField(default=timezone.now)
|
2020-08-01 16:27:12 +00:00
|
|
|
ending_date = models.DateTimeField(blank=True, null=True)
|
2020-05-02 20:48:05 +00:00
|
|
|
|
2020-10-06 16:53:13 +00:00
|
|
|
recurring_period = models.ForeignKey(RecurringPeriod,
|
|
|
|
on_delete=models.CASCADE,
|
|
|
|
editable=True)
|
2020-05-02 20:48:05 +00:00
|
|
|
|
2020-09-28 19:59:35 +00:00
|
|
|
one_time_price = models.DecimalField(default=0.0,
|
2020-08-08 19:54:44 +00:00
|
|
|
max_digits=AMOUNT_MAX_DIGITS,
|
|
|
|
decimal_places=AMOUNT_DECIMALS,
|
|
|
|
validators=[MinValueValidator(0)])
|
2020-05-02 20:48:05 +00:00
|
|
|
|
2020-09-28 19:59:35 +00:00
|
|
|
recurring_price = models.DecimalField(default=0.0,
|
|
|
|
max_digits=AMOUNT_MAX_DIGITS,
|
|
|
|
decimal_places=AMOUNT_DECIMALS,
|
|
|
|
validators=[MinValueValidator(0)])
|
|
|
|
|
|
|
|
currency = models.CharField(max_length=32, choices=Currency.choices, default=Currency.CHF)
|
|
|
|
|
2020-08-01 16:27:12 +00:00
|
|
|
replaces = models.ForeignKey('self',
|
|
|
|
related_name='replaced_by',
|
2020-08-09 08:14:31 +00:00
|
|
|
on_delete=models.CASCADE,
|
2020-08-01 16:27:12 +00:00
|
|
|
blank=True,
|
|
|
|
null=True)
|
2020-05-08 14:47:32 +00:00
|
|
|
|
|
|
|
depends_on = models.ForeignKey('self',
|
2020-08-01 16:27:12 +00:00
|
|
|
related_name='parent_of',
|
2020-08-09 08:14:31 +00:00
|
|
|
on_delete=models.CASCADE,
|
2020-08-01 16:27:12 +00:00
|
|
|
blank=True,
|
|
|
|
null=True)
|
2020-05-08 14:47:32 +00:00
|
|
|
|
2020-09-28 21:16:17 +00:00
|
|
|
should_be_billed = models.BooleanField(default=True)
|
|
|
|
|
2020-08-09 08:14:31 +00:00
|
|
|
@property
|
|
|
|
def earliest_ending_date(self):
|
|
|
|
"""
|
|
|
|
Recurring orders cannot end before finishing at least one recurring period.
|
|
|
|
|
|
|
|
One time orders have a recurring period of 0, so this work universally
|
|
|
|
"""
|
|
|
|
|
2020-10-06 21:14:32 +00:00
|
|
|
return self.starting_date + datetime.timedelta(seconds=self.recurring_period.duration_seconds)
|
2020-08-09 08:14:31 +00:00
|
|
|
|
2020-10-06 22:54:56 +00:00
|
|
|
|
|
|
|
def next_cancel_or_downgrade_date(self, until_when=None):
|
2020-08-27 20:00:54 +00:00
|
|
|
"""
|
|
|
|
Return the next proper ending date after n times the
|
2020-09-28 18:44:50 +00:00
|
|
|
recurring_period, where n is an integer that applies for downgrading
|
|
|
|
or cancelling.
|
2020-08-27 20:00:54 +00:00
|
|
|
"""
|
|
|
|
|
2020-10-06 22:54:56 +00:00
|
|
|
if not until_when:
|
|
|
|
until_when = timezone.now()
|
|
|
|
|
|
|
|
if until_when < self.starting_date:
|
|
|
|
raise ValidationError("Cannot end before start of start of order")
|
2020-08-27 20:00:54 +00:00
|
|
|
|
2020-10-06 22:54:56 +00:00
|
|
|
if self.recurring_period.duration_seconds > 0:
|
|
|
|
delta = until_when - self.starting_date
|
2020-08-27 20:00:54 +00:00
|
|
|
|
2020-10-06 22:54:56 +00:00
|
|
|
num_times = ceil(delta.total_seconds() / self.recurring_period.duration_seconds)
|
|
|
|
|
|
|
|
next_date = self.starting_date + datetime.timedelta(seconds=num_times * self.recurring_period.duration_seconds)
|
2020-08-27 20:00:54 +00:00
|
|
|
else:
|
|
|
|
next_date = self.starting_date
|
|
|
|
|
|
|
|
return next_date
|
2020-08-09 08:14:31 +00:00
|
|
|
|
2020-09-08 22:35:55 +00:00
|
|
|
def get_ending_date_for_bill(self, bill):
|
2020-09-03 15:16:18 +00:00
|
|
|
"""
|
|
|
|
Determine the ending date given a specific bill
|
|
|
|
"""
|
|
|
|
|
2020-10-06 22:54:56 +00:00
|
|
|
# If the order is quit, charge the final amount / finish (????)
|
|
|
|
# Probably not a good idea -- FIXME :continue until usual
|
2020-09-08 22:35:55 +00:00
|
|
|
if self.ending_date:
|
|
|
|
this_ending_date = self.ending_date
|
2020-09-03 15:16:18 +00:00
|
|
|
else:
|
2020-10-06 22:54:56 +00:00
|
|
|
if self.next_cancel_or_downgrade_date(bill.ending_date) > bill.ending_date:
|
|
|
|
this_ending_date = self.next_cancel_or_downgrade_date(bill.ending_date)
|
2020-09-03 15:16:18 +00:00
|
|
|
else:
|
|
|
|
this_ending_date = bill.ending_date
|
|
|
|
|
|
|
|
return this_ending_date
|
|
|
|
|
|
|
|
|
2020-06-21 12:35:12 +00:00
|
|
|
@property
|
|
|
|
def count_billed(self):
|
|
|
|
"""
|
|
|
|
How many times this order was billed so far.
|
|
|
|
This logic is mainly thought to be for recurring bills, but also works for one time bills
|
|
|
|
"""
|
|
|
|
|
2020-06-21 14:42:55 +00:00
|
|
|
return sum([ br.quantity for br in self.bill_records.all() ])
|
2020-06-21 12:35:12 +00:00
|
|
|
|
2020-09-03 14:38:51 +00:00
|
|
|
def count_used(self, when=None):
|
|
|
|
"""
|
|
|
|
How many times this order was billed so far.
|
|
|
|
This logic is mainly thought to be for recurring bills, but also works for one time bills
|
|
|
|
"""
|
|
|
|
|
|
|
|
if self.is_one_time:
|
|
|
|
return 1
|
|
|
|
|
|
|
|
if not when:
|
|
|
|
when = timezone.now()
|
|
|
|
|
|
|
|
# Cannot be used after it ended
|
|
|
|
if self.ending_date and when > self.ending_date:
|
|
|
|
when = self.ending_date
|
|
|
|
|
|
|
|
return (when - self.starting_date) / self.default_recurring_period
|
|
|
|
|
|
|
|
@property
|
2020-09-03 15:16:18 +00:00
|
|
|
def all_usage_billed(self, when=None):
|
2020-09-03 14:38:51 +00:00
|
|
|
"""
|
|
|
|
Returns true if this order does not need any further billing
|
|
|
|
ever. In other words: is this order "closed"?
|
|
|
|
"""
|
|
|
|
|
2020-09-03 15:16:18 +00:00
|
|
|
if self.count_billed == self.count_used(when):
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
return False
|
|
|
|
|
|
|
|
@property
|
|
|
|
def is_closed(self):
|
|
|
|
if self.all_usage_billed and self.ending_date:
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
return False
|
2020-09-03 14:38:51 +00:00
|
|
|
|
2020-05-23 19:32:56 +00:00
|
|
|
@property
|
|
|
|
def is_recurring(self):
|
2020-11-15 14:43:11 +00:00
|
|
|
return not self.recurring_period == RecurringPeriod.objects.get(name="ONE_TIME")
|
2020-08-04 09:26:42 +00:00
|
|
|
|
2020-08-08 20:20:49 +00:00
|
|
|
@property
|
|
|
|
def is_one_time(self):
|
|
|
|
return not self.is_recurring
|
|
|
|
|
2020-08-09 10:34:25 +00:00
|
|
|
def replace_with(self, new_order):
|
|
|
|
new_order.replaces = self
|
2020-09-03 14:38:51 +00:00
|
|
|
self.ending_date = end_before(new_order.starting_date)
|
2020-08-09 10:34:25 +00:00
|
|
|
self.save()
|
|
|
|
|
2020-10-06 13:46:22 +00:00
|
|
|
def update_order(self, config, starting_date=None):
|
|
|
|
"""
|
|
|
|
Updating an order means creating a new order and reference the previous order
|
|
|
|
"""
|
|
|
|
|
|
|
|
if not starting_date:
|
|
|
|
starting_date = timezone.now()
|
|
|
|
|
|
|
|
new_order = self.__class__(owner=self.owner,
|
|
|
|
billing_address=self.billing_address,
|
2020-10-06 21:14:32 +00:00
|
|
|
description=self.description,
|
2020-10-06 13:46:22 +00:00
|
|
|
product=self.product,
|
2020-10-06 21:14:32 +00:00
|
|
|
config=config,
|
2020-10-06 13:46:22 +00:00
|
|
|
starting_date=starting_date,
|
2020-10-06 21:14:32 +00:00
|
|
|
currency=self.currency
|
|
|
|
)
|
2020-10-06 13:46:22 +00:00
|
|
|
|
2020-10-06 21:14:32 +00:00
|
|
|
(new_order.one_time_price, new_order.recurring_price, new_order.config) = new_order.calculate_prices_and_config()
|
2020-10-06 13:46:22 +00:00
|
|
|
|
2020-11-15 14:43:11 +00:00
|
|
|
|
|
|
|
|
2020-10-06 13:46:22 +00:00
|
|
|
new_order.replaces = self
|
|
|
|
new_order.save()
|
|
|
|
|
|
|
|
self.ending_date = end_before(new_order.starting_date)
|
|
|
|
self.save()
|
|
|
|
|
2020-10-06 21:14:32 +00:00
|
|
|
return new_order
|
2020-05-02 20:48:05 +00:00
|
|
|
|
2020-09-08 22:35:55 +00:00
|
|
|
|
|
|
|
def create_bill_record(self, bill):
|
|
|
|
br = None
|
|
|
|
|
2020-10-06 22:54:56 +00:00
|
|
|
# Note: check for != 0 not > 0, as we allow discounts to be expressed with < 0
|
2020-09-28 21:16:17 +00:00
|
|
|
if self.one_time_price != 0 and self.billrecord_set.count() == 0:
|
|
|
|
br = BillRecord.objects.create(bill=bill,
|
|
|
|
order=self,
|
|
|
|
starting_date=self.starting_date,
|
|
|
|
ending_date=self.starting_date,
|
|
|
|
is_recurring_record=False)
|
|
|
|
|
|
|
|
if self.recurring_price != 0:
|
|
|
|
br = BillRecord.objects.filter(bill=bill, order=self, is_recurring_record=True).first()
|
|
|
|
|
2020-09-08 22:35:55 +00:00
|
|
|
if br:
|
|
|
|
self.update_bill_record_for_recurring_order(br, bill)
|
|
|
|
else:
|
|
|
|
br = self.create_new_bill_record_for_recurring_order(bill)
|
|
|
|
|
|
|
|
return br
|
|
|
|
|
|
|
|
def update_bill_record_for_recurring_order(self,
|
|
|
|
bill_record,
|
|
|
|
bill):
|
|
|
|
"""
|
|
|
|
Possibly update a bill record according to the information in the bill
|
|
|
|
"""
|
|
|
|
|
|
|
|
# If the order has an ending date set, we might need to adjust the bill_record
|
|
|
|
if self.ending_date:
|
|
|
|
if bill_record_for_this_bill.ending_date != self.ending_date:
|
|
|
|
bill_record_for_this_bill.ending_date = self.ending_date
|
|
|
|
|
|
|
|
else:
|
|
|
|
# recurring, not terminated, should go until at least end of bill
|
|
|
|
if bill_record_for_this_bill.ending_date < bill.ending_date:
|
|
|
|
bill_record_for_this_bill.ending_date = bill.ending_date
|
|
|
|
|
|
|
|
bill_record_for_this_bill.save()
|
|
|
|
|
|
|
|
def create_new_bill_record_for_recurring_order(self, bill):
|
|
|
|
"""
|
|
|
|
Create a new bill record
|
|
|
|
"""
|
|
|
|
|
2020-09-28 21:16:17 +00:00
|
|
|
last_bill_record = BillRecord.objects.filter(order=self, is_recurring_record=True).order_by('id').last()
|
2020-09-08 22:35:55 +00:00
|
|
|
|
|
|
|
starting_date=self.starting_date
|
|
|
|
|
|
|
|
if last_bill_record:
|
|
|
|
# We already charged beyond the end of this bill's period
|
|
|
|
if last_bill_record.ending_date >= bill.ending_date:
|
|
|
|
return
|
|
|
|
|
|
|
|
# This order is terminated or replaced
|
|
|
|
if self.ending_date:
|
|
|
|
# And the last bill record already covered us -> nothing to be done anymore
|
|
|
|
if last_bill_record.ending_date == self.ending_date:
|
|
|
|
return
|
|
|
|
|
|
|
|
starting_date = start_after(last_bill_record.ending_date)
|
|
|
|
|
|
|
|
ending_date = self.get_ending_date_for_bill(bill)
|
|
|
|
|
|
|
|
return BillRecord.objects.create(bill=bill,
|
2020-09-28 21:16:17 +00:00
|
|
|
order=self,
|
|
|
|
starting_date=starting_date,
|
|
|
|
ending_date=ending_date,
|
|
|
|
is_recurring_record=True)
|
|
|
|
|
2020-10-06 21:14:32 +00:00
|
|
|
def calculate_prices_and_config(self):
|
2020-09-28 19:59:35 +00:00
|
|
|
one_time_price = 0
|
|
|
|
recurring_price = 0
|
|
|
|
|
2020-10-06 21:14:32 +00:00
|
|
|
if self.config:
|
|
|
|
config = self.config
|
|
|
|
|
|
|
|
if 'features' not in self.config:
|
|
|
|
self.config['features'] = {}
|
|
|
|
|
|
|
|
else:
|
|
|
|
config = {
|
|
|
|
'features': {}
|
|
|
|
}
|
|
|
|
|
|
|
|
# FIXME: adjust prices to the selected recurring_period to the
|
2020-09-28 19:59:35 +00:00
|
|
|
|
|
|
|
if 'features' in self.product.config:
|
|
|
|
for feature in self.product.config['features']:
|
|
|
|
|
2020-10-06 16:53:13 +00:00
|
|
|
# Set min to 0 if not specified
|
|
|
|
min_val = self.product.config['features'][feature].get('min', 0)
|
|
|
|
|
|
|
|
# We might not even have 'features' cannot use .get() on it
|
|
|
|
try:
|
|
|
|
value = self.config['features'][feature]
|
2020-10-06 21:14:32 +00:00
|
|
|
except (KeyError, TypeError):
|
2020-10-06 16:53:13 +00:00
|
|
|
value = self.product.config['features'][feature]['min']
|
|
|
|
|
|
|
|
# Set max to current value if not specified
|
|
|
|
max_val = self.product.config['features'][feature].get('max', value)
|
|
|
|
|
2020-10-06 21:14:32 +00:00
|
|
|
|
2020-10-06 16:53:13 +00:00
|
|
|
if value < min_val or value > max_val:
|
|
|
|
raise ValidationError(f"Feature '{feature}' must be at least {min_val} and at maximum {max_val}. Value is: {value}")
|
|
|
|
|
|
|
|
one_time_price += self.product.config['features'][feature]['one_time_price_per_unit'] * value
|
|
|
|
recurring_price += self.product.config['features'][feature]['recurring_price_per_unit'] * value
|
2020-10-06 21:14:32 +00:00
|
|
|
config['features'][feature] = value
|
2020-09-28 19:59:35 +00:00
|
|
|
|
2020-10-06 21:14:32 +00:00
|
|
|
return (one_time_price, recurring_price, config)
|
2020-09-28 19:59:35 +00:00
|
|
|
|
2020-10-25 21:43:34 +00:00
|
|
|
def check_parameters(self):
|
|
|
|
if 'parameters' in self.product.config:
|
|
|
|
for parameter in self.product.config['parameters']:
|
|
|
|
if not parameter in self.config['parameters']:
|
|
|
|
raise ValidationError(f"Required parameter '{parameter}' is missing.")
|
|
|
|
|
|
|
|
|
2020-10-06 13:46:22 +00:00
|
|
|
def save(self, *args, **kwargs):
|
|
|
|
# Calculate the price of the order when we create it
|
2020-09-28 19:59:35 +00:00
|
|
|
# IMMUTABLE fields -- need to create new order to modify them
|
|
|
|
# However this is not enforced here...
|
|
|
|
if self._state.adding:
|
2020-10-06 21:14:32 +00:00
|
|
|
(self.one_time_price, self.recurring_price, self.config) = self.calculate_prices_and_config()
|
2020-09-28 19:59:35 +00:00
|
|
|
|
2020-10-06 17:21:37 +00:00
|
|
|
if self.recurring_period_id is None:
|
2020-10-06 16:53:13 +00:00
|
|
|
self.recurring_period = self.product.default_recurring_period
|
|
|
|
|
2020-10-06 21:14:32 +00:00
|
|
|
try:
|
|
|
|
prod_period = self.product.recurring_periods.get(producttorecurringperiod__recurring_period=self.recurring_period)
|
|
|
|
except ObjectDoesNotExist:
|
|
|
|
raise ValidationError(f"Recurring Period {self.recurring_period} not allowed for product {self.product}")
|
|
|
|
|
2020-10-25 21:43:34 +00:00
|
|
|
self.check_parameters()
|
|
|
|
|
2020-10-06 21:14:32 +00:00
|
|
|
if self.ending_date and self.ending_date < self.starting_date:
|
|
|
|
raise ValidationError("End date cannot be before starting date")
|
|
|
|
|
|
|
|
|
2020-09-28 19:59:35 +00:00
|
|
|
super().save(*args, **kwargs)
|
|
|
|
|
|
|
|
|
2020-08-09 08:14:31 +00:00
|
|
|
def __str__(self):
|
2020-10-11 15:45:25 +00:00
|
|
|
try:
|
|
|
|
conf = " ".join([ f"{key}:{val}" for key,val in self.config['features'].items() if val != 0 ])
|
|
|
|
except KeyError:
|
|
|
|
conf = ""
|
|
|
|
|
|
|
|
return f"Order {self.id}: {self.description} {conf}"
|
2020-06-21 11:46:54 +00:00
|
|
|
|
2020-06-21 14:08:00 +00:00
|
|
|
class Bill(models.Model):
|
2020-08-09 08:14:31 +00:00
|
|
|
"""
|
|
|
|
A bill is a representation of usage at a specific time
|
|
|
|
"""
|
2020-06-21 11:46:54 +00:00
|
|
|
owner = models.ForeignKey(get_user_model(),
|
|
|
|
on_delete=models.CASCADE)
|
|
|
|
|
|
|
|
creation_date = models.DateTimeField(auto_now_add=True)
|
2020-06-21 14:08:00 +00:00
|
|
|
starting_date = models.DateTimeField(default=start_of_this_month)
|
2020-08-04 09:26:42 +00:00
|
|
|
ending_date = models.DateTimeField()
|
2020-06-21 14:08:00 +00:00
|
|
|
due_date = models.DateField(default=default_payment_delay)
|
2020-08-09 08:14:31 +00:00
|
|
|
|
2020-08-09 10:34:25 +00:00
|
|
|
|
|
|
|
billing_address = models.ForeignKey(BillingAddress,
|
|
|
|
on_delete=models.CASCADE,
|
|
|
|
editable=True,
|
|
|
|
null=False)
|
2020-10-06 22:54:56 +00:00
|
|
|
|
2020-08-09 10:34:25 +00:00
|
|
|
# FIXME: editable=True -> is in the admin, but also editable in DRF
|
2020-10-06 22:54:56 +00:00
|
|
|
# Maybe filter fields in the serializer?
|
2020-08-09 10:34:25 +00:00
|
|
|
|
2020-08-08 22:37:27 +00:00
|
|
|
is_final = models.BooleanField(default=False)
|
2020-06-21 11:46:54 +00:00
|
|
|
|
2020-06-21 14:08:00 +00:00
|
|
|
class Meta:
|
|
|
|
constraints = [
|
|
|
|
models.UniqueConstraint(fields=['owner',
|
|
|
|
'starting_date',
|
|
|
|
'ending_date' ],
|
|
|
|
name='one_bill_per_month_per_user')
|
|
|
|
]
|
|
|
|
|
2020-08-09 10:34:25 +00:00
|
|
|
def close(self):
|
|
|
|
"""
|
|
|
|
Close/finish a bill
|
|
|
|
"""
|
|
|
|
|
|
|
|
self.is_final = True
|
|
|
|
self.save()
|
2020-08-09 08:14:31 +00:00
|
|
|
|
2020-08-08 19:54:44 +00:00
|
|
|
@property
|
|
|
|
def sum(self):
|
2020-08-08 20:31:43 +00:00
|
|
|
bill_records = BillRecord.objects.filter(bill=self)
|
|
|
|
return sum([ br.sum for br in bill_records ])
|
2020-08-08 19:54:44 +00:00
|
|
|
|
2020-10-11 20:32:08 +00:00
|
|
|
@property
|
|
|
|
def vat_rate(self):
|
|
|
|
"""
|
|
|
|
Handling VAT is a tricky business - thus we only implement the cases
|
|
|
|
that we clearly now and leave it open to fellow developers to implement
|
|
|
|
correct handling for other cases.
|
|
|
|
|
|
|
|
Case CH:
|
|
|
|
|
|
|
|
- If the customer is in .ch -> apply standard rate
|
|
|
|
- If the customer is in EU AND private -> apply country specific rate
|
|
|
|
- If the customer is in EU AND business -> do not apply VAT
|
|
|
|
- If the customer is outside EU and outside CH -> do not apply VAT
|
|
|
|
"""
|
|
|
|
|
2020-10-25 12:52:36 +00:00
|
|
|
provider = UncloudProvider.objects.get()
|
|
|
|
|
|
|
|
# Assume always VAT inside the country
|
2020-10-25 20:00:30 +00:00
|
|
|
if provider.country == self.billing_address.country:
|
2020-10-25 12:52:36 +00:00
|
|
|
vat_rate = VATRate.objects.get(country=provider.country,
|
|
|
|
when=self.ending_date)
|
|
|
|
elif self.billing_address.country in EU:
|
|
|
|
# FIXME: need to check for validated vat number
|
|
|
|
if self.billing_address.vat_number:
|
|
|
|
return 0
|
|
|
|
else:
|
|
|
|
return VATRate.objects.get(country=self.biling_address.country,
|
|
|
|
when=self.ending_date)
|
|
|
|
else: # non-EU, non-national
|
|
|
|
return 0
|
2020-10-11 20:32:08 +00:00
|
|
|
|
|
|
|
|
2020-08-09 12:38:10 +00:00
|
|
|
@classmethod
|
|
|
|
def create_bills_for_all_users(cls):
|
|
|
|
"""
|
2020-09-08 22:35:55 +00:00
|
|
|
Create next bill for each user
|
2020-08-09 12:38:10 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
for owner in get_user_model().objects.all():
|
|
|
|
cls.create_next_bills_for_user(owner)
|
2020-08-04 09:26:42 +00:00
|
|
|
|
|
|
|
@classmethod
|
2020-08-09 10:34:25 +00:00
|
|
|
def create_next_bills_for_user(cls, owner, ending_date=None):
|
|
|
|
"""
|
|
|
|
Create one bill per billing address, as the VAT rates might be different
|
|
|
|
for each address
|
|
|
|
"""
|
|
|
|
|
|
|
|
bills = []
|
|
|
|
|
|
|
|
for billing_address in BillingAddress.objects.filter(owner=owner):
|
2020-09-08 22:35:55 +00:00
|
|
|
bills.append(cls.create_next_bill_for_user_address(billing_address, ending_date))
|
2020-08-09 10:34:25 +00:00
|
|
|
|
|
|
|
return bills
|
|
|
|
|
|
|
|
@classmethod
|
2020-10-06 21:14:32 +00:00
|
|
|
def create_next_bill_for_user_address(cls, billing_address, ending_date=None):
|
|
|
|
"""
|
|
|
|
Create the next bill for a specific billing address of a user
|
|
|
|
"""
|
|
|
|
|
|
|
|
owner = billing_address.owner
|
|
|
|
|
|
|
|
all_orders = Order.objects.filter(owner=owner,
|
|
|
|
billing_address=billing_address).order_by('id')
|
|
|
|
|
|
|
|
bill = cls.get_or_create_bill(billing_address, ending_date=ending_date)
|
|
|
|
|
|
|
|
for order in all_orders:
|
|
|
|
order.create_bill_record(bill)
|
|
|
|
|
|
|
|
return bill
|
|
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def get_or_create_bill(cls, billing_address, ending_date=None):
|
2020-10-06 22:54:56 +00:00
|
|
|
"""
|
|
|
|
Get / reuse last bill if it is not yet closed
|
|
|
|
|
|
|
|
Create bill, if there is no bill or if bill is closed.
|
|
|
|
"""
|
|
|
|
|
2020-09-08 22:35:55 +00:00
|
|
|
last_bill = cls.objects.filter(billing_address=billing_address).order_by('id').last()
|
2020-09-02 14:02:28 +00:00
|
|
|
|
2020-09-08 22:35:55 +00:00
|
|
|
all_orders = Order.objects.filter(billing_address=billing_address).order_by('id')
|
|
|
|
first_order = all_orders.first()
|
2020-09-02 14:02:28 +00:00
|
|
|
|
2020-09-08 22:35:55 +00:00
|
|
|
bill = None
|
2020-09-02 14:02:28 +00:00
|
|
|
|
2020-09-08 22:35:55 +00:00
|
|
|
# Get date & bill from previous bill, if it exists
|
|
|
|
if last_bill:
|
|
|
|
if not last_bill.is_final:
|
|
|
|
bill = last_bill
|
|
|
|
starting_date = last_bill.starting_date
|
|
|
|
ending_date = bill.ending_date
|
2020-09-02 14:02:28 +00:00
|
|
|
else:
|
2020-09-08 22:35:55 +00:00
|
|
|
starting_date = last_bill.ending_date + datetime.timedelta(seconds=1)
|
|
|
|
else:
|
|
|
|
# Might be an idea to make this the start of the month, too
|
|
|
|
if first_order:
|
|
|
|
starting_date = first_order.starting_date
|
|
|
|
else:
|
|
|
|
starting_date = timezone.now()
|
2020-09-02 14:02:28 +00:00
|
|
|
|
2020-09-08 22:35:55 +00:00
|
|
|
if not ending_date:
|
|
|
|
ending_date = end_of_month(starting_date)
|
2020-09-02 14:02:28 +00:00
|
|
|
|
2020-09-08 22:35:55 +00:00
|
|
|
if not bill:
|
|
|
|
bill = cls.objects.create(
|
|
|
|
owner=billing_address.owner,
|
|
|
|
starting_date=starting_date,
|
|
|
|
ending_date=ending_date,
|
|
|
|
billing_address=billing_address)
|
2020-09-02 14:02:28 +00:00
|
|
|
|
|
|
|
|
2020-09-08 22:35:55 +00:00
|
|
|
return bill
|
2020-09-02 14:02:28 +00:00
|
|
|
|
2020-10-06 22:54:56 +00:00
|
|
|
def __str__(self):
|
2021-01-17 14:53:30 +00:00
|
|
|
return f"{self.owner}-{self.id}"
|
2020-08-08 19:54:44 +00:00
|
|
|
|
2020-06-21 11:46:54 +00:00
|
|
|
|
|
|
|
class BillRecord(models.Model):
|
|
|
|
"""
|
|
|
|
Entry of a bill, dynamically generated from an order.
|
|
|
|
"""
|
|
|
|
|
|
|
|
bill = models.ForeignKey(Bill, on_delete=models.CASCADE)
|
|
|
|
order = models.ForeignKey(Order, on_delete=models.CASCADE)
|
|
|
|
|
|
|
|
creation_date = models.DateTimeField(auto_now_add=True)
|
|
|
|
starting_date = models.DateTimeField()
|
|
|
|
ending_date = models.DateTimeField()
|
|
|
|
|
2020-09-28 21:16:17 +00:00
|
|
|
is_recurring_record = models.BooleanField(blank=False, null=False)
|
|
|
|
|
2020-08-08 20:31:43 +00:00
|
|
|
@property
|
2020-08-08 20:20:49 +00:00
|
|
|
def quantity(self):
|
|
|
|
""" Determine the quantity by the duration"""
|
2020-09-28 21:16:17 +00:00
|
|
|
if not self.is_recurring_record:
|
2020-08-08 19:54:44 +00:00
|
|
|
return 1
|
|
|
|
|
|
|
|
record_delta = self.ending_date - self.starting_date
|
|
|
|
|
2020-10-06 21:14:32 +00:00
|
|
|
return record_delta.total_seconds()/self.order.recurring_period.duration_seconds
|
2020-08-08 19:54:44 +00:00
|
|
|
|
2020-08-08 20:31:43 +00:00
|
|
|
@property
|
2020-08-08 19:54:44 +00:00
|
|
|
def sum(self):
|
2020-09-28 21:16:17 +00:00
|
|
|
if self.is_recurring_record:
|
|
|
|
return self.order.recurring_price * Decimal(self.quantity)
|
|
|
|
else:
|
|
|
|
return self.order.one_time_price
|
2020-08-08 19:54:44 +00:00
|
|
|
|
2020-10-25 12:52:36 +00:00
|
|
|
@property
|
|
|
|
def price(self):
|
|
|
|
if self.is_recurring_record:
|
|
|
|
return self.order.recurring_price
|
|
|
|
else:
|
|
|
|
return self.order.one_time_price
|
|
|
|
|
2020-06-21 11:46:54 +00:00
|
|
|
def __str__(self):
|
2020-09-28 21:16:17 +00:00
|
|
|
if self.is_recurring_record:
|
|
|
|
bill_line = f"{self.starting_date} - {self.ending_date}: {self.quantity} x {self.order}"
|
|
|
|
else:
|
|
|
|
bill_line = f"{self.starting_date}: {self.order}"
|
|
|
|
|
|
|
|
return bill_line
|
2020-06-21 11:46:54 +00:00
|
|
|
|
2020-08-09 09:02:45 +00:00
|
|
|
def save(self, *args, **kwargs):
|
|
|
|
if self.ending_date < self.starting_date:
|
|
|
|
raise ValidationError("End date cannot be before starting date")
|
|
|
|
|
|
|
|
super().save(*args, **kwargs)
|
|
|
|
|
2020-04-13 09:54:41 +00:00
|
|
|
|
2020-10-06 16:53:13 +00:00
|
|
|
class ProductToRecurringPeriod(models.Model):
|
|
|
|
"""
|
2020-10-06 22:54:56 +00:00
|
|
|
Intermediate manytomany mapping class that allows storing the default recurring period
|
|
|
|
for a product
|
2020-10-06 16:53:13 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
recurring_period = models.ForeignKey(RecurringPeriod, on_delete=models.CASCADE)
|
|
|
|
product = models.ForeignKey(Product, on_delete=models.CASCADE)
|
|
|
|
|
|
|
|
is_default = models.BooleanField(default=False)
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
constraints = [
|
|
|
|
models.UniqueConstraint(fields=['product'],
|
2021-01-17 14:53:30 +00:00
|
|
|
condition=models.Q(is_default=True),
|
2020-10-06 17:21:37 +00:00
|
|
|
name='one_default_recurring_period_per_product'),
|
|
|
|
models.UniqueConstraint(fields=['product', 'recurring_period'],
|
|
|
|
name='recurring_period_once_per_product')
|
2020-10-06 16:53:13 +00:00
|
|
|
]
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return f"{self.product} - {self.recurring_period} (default: {self.is_default})"
|
2020-12-28 22:35:34 +00:00
|
|
|
|
|
|
|
|
|
|
|
class Membership(models.Model):
|
|
|
|
owner = models.ForeignKey(get_user_model(),
|
|
|
|
on_delete=models.CASCADE)
|
|
|
|
|
|
|
|
starting_date = models.DateField(blank=True, null=True)
|
|
|
|
ending_date = models.DateField(blank=True, null=True)
|
|
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def user_has_membership(user, when):
|
|
|
|
"""
|
|
|
|
Return true if user has membership at a point of time,
|
|
|
|
return false if that is not the case
|
|
|
|
"""
|
|
|
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
# cls.objects.filter(owner=user,
|
|
|
|
# starting_date)
|