58 lines
1.7 KiB
Python
58 lines
1.7 KiB
Python
from django.utils import timezone
|
|
from django.db import transaction
|
|
from django.db.models import Q
|
|
|
|
from uncloud.selectors import filter_for_when
|
|
from uncloud.models import UncloudProvider
|
|
from .models import *
|
|
|
|
def get_payments_for_user(user):
|
|
payments = [ payment.amount for payment in Payment.objects.filter(owner=user) ]
|
|
|
|
return sum(payments)
|
|
|
|
def get_spendings_for_user(user):
|
|
orders = Order.objects.filter(owner=user)
|
|
|
|
amount = 0
|
|
for order in orders:
|
|
amount += order.one_time_price
|
|
amount += order.recurring_price * order.count_used(when=timezone.now())
|
|
|
|
return amount
|
|
|
|
@transaction.atomic
|
|
def get_balance_for_user(user):
|
|
return get_payments_for_user(user) - get_spendings_for_user(user)
|
|
|
|
def get_billing_address_for_user(user):
|
|
return BillingAddress.objects.get(owner=user, active=True)
|
|
|
|
def get_vat_rate(billing_address, when=None):
|
|
"""
|
|
Returns the VAT rate for business to customer.
|
|
|
|
B2B is always 0% with the exception of trading within the own country
|
|
"""
|
|
|
|
country = billing_address.country
|
|
|
|
# Need to have a provider country
|
|
uncloud_provider = filter_for_when(UncloudProvider.objects.all()).get()
|
|
vatrate = filter_for_when(VATRate.objects.filter(territory_codes=country), when).first()
|
|
|
|
# By default we charge VAT. This affects:
|
|
# - Same country sales (VAT applied)
|
|
# - B2C to EU (VAT applied)
|
|
rate = vatrate.rate
|
|
|
|
# Exception: if...
|
|
# - the billing_address is in EU,
|
|
# - the vat_number has been set
|
|
# - the vat_number has been verified
|
|
# Then we do not charge VAT
|
|
|
|
if uncloud_provider.country != country and billing_address.vat_number and billing_address.vat_number_verified:
|
|
rate = 0
|
|
|
|
return rate
|