From 99e70d95c4a17bb938423c29dc3524a699c74f14 Mon Sep 17 00:00:00 2001
From: PCoder <purple.coder@yahoo.co.uk>
Date: Thu, 26 Dec 2019 13:31:15 +0530
Subject: [PATCH] VAT number validation in settings

---
 datacenterlight/utils.py                | 33 ++++++++++++++++++-------
 hosting/templates/hosting/settings.html |  7 ++++++
 hosting/views.py                        | 27 +++++++++++++++++---
 3 files changed, 54 insertions(+), 13 deletions(-)

diff --git a/datacenterlight/utils.py b/datacenterlight/utils.py
index 27179b26..6ae05d39 100644
--- a/datacenterlight/utils.py
+++ b/datacenterlight/utils.py
@@ -131,15 +131,30 @@ def check_otp(name, realm, token):
     return response.status_code
 
 
-def validate_vat_number(stripe_customer_id, billing_address_id):
-    try:
-        billing_address = BillingAddress.objects.get(id=billing_address_id)
-    except BillingAddress.DoesNotExist as dne:
-        billing_address = None
-        logger.debug("BillingAddress does not exist for %s" % billing_address_id)
-    except BillingAddress.MultipleObjectsReturned as mor:
-        logger.debug("Multiple BillingAddress exist for %s" % billing_address_id)
-        billing_address = BillingAddress.objects.filter(billing_address_id).order_by('-id').first()
+def validate_vat_number(stripe_customer_id, billing_address_id,
+                        is_user_ba=False):
+    if is_user_ba:
+        try:
+            billing_address = UserBillingAddress.objects.get(
+                id=billing_address_id)
+        except UserBillingAddress.DoesNotExist as dne:
+            billing_address = None
+            logger.debug(
+                "UserBillingAddress does not exist for %s" % billing_address_id)
+        except UserBillingAddress.MultipleObjectsReturned as mor:
+            logger.debug(
+                "Multiple UserBillingAddress exist for %s" % billing_address_id)
+            billing_address = UserBillingAddress.objects.filter(
+                id=billing_address_id).order_by('-id').first()
+    else:
+        try:
+            billing_address = BillingAddress.objects.get(id=billing_address_id)
+        except BillingAddress.DoesNotExist as dne:
+            billing_address = None
+            logger.debug("BillingAddress does not exist for %s" % billing_address_id)
+        except BillingAddress.MultipleObjectsReturned as mor:
+            logger.debug("Multiple BillingAddress exist for %s" % billing_address_id)
+            billing_address = BillingAddress.objects.filter(id=billing_address_id).order_by('-id').first()
     if billing_address is not None:
         if billing_address.vat_number_validated_on:
             return {
diff --git a/hosting/templates/hosting/settings.html b/hosting/templates/hosting/settings.html
index 3ca0eee6..915bdaa0 100644
--- a/hosting/templates/hosting/settings.html
+++ b/hosting/templates/hosting/settings.html
@@ -26,6 +26,13 @@
                         {% for field in form %}
                             {% bootstrap_field field show_label=False type='fields' bound_css_class='' %}
                         {% endfor %}
+                        {% if form.instance.vat_number %}
+                            {% if form.instance.vat_validation_status == "verified" %}
+                                        <span class="fa fa-fw fa-check-circle" aria-hidden="true" title='{% trans "Your VAT number has been verified" %}'></span>
+                            {% else %}
+                                        <span class="fa fa-fw fa-info-circle" aria-hidden="true" title='{% trans "Your VAT number is under validation. VAT will be adjusted, once the validation is complete." %}'></span>
+                            {% endif %}
+                        {% endif %}
                         <div class="form-group text-right">
                             <button type="submit" class="btn btn-vm-contact btn-wide" name="billing-form">{% trans "UPDATE" %}</button>
                         </div>
diff --git a/hosting/views.py b/hosting/views.py
index 3f89496b..943c173a 100644
--- a/hosting/views.py
+++ b/hosting/views.py
@@ -37,7 +37,9 @@ from stored_messages.settings import stored_messages_settings
 
 from datacenterlight.cms_models import DCLCalculatorPluginModel
 from datacenterlight.models import VMTemplate, VMPricing
-from datacenterlight.utils import create_vm, get_cms_integration, check_otp
+from datacenterlight.utils import (
+    create_vm, get_cms_integration, check_otp, validate_vat_number
+)
 from hosting.models import UserCardDetail
 from membership.models import CustomUser, StripeCustomer
 from opennebula_api.models import OpenNebulaManager
@@ -626,9 +628,26 @@ class SettingsView(LoginRequiredMixin, FormView):
                 billing_address_user_form = UserBillingAddressForm(
                     instance=self.request.user.billing_addresses.first(),
                     data=billing_address_data)
-                billing_address_user_form.save()
-                msg = _("Billing address updated successfully")
-                messages.add_message(request, messages.SUCCESS, msg)
+                billing_address = billing_address_user_form.save()
+                vat_number = billing_address_user_form.cleaned_data.get(
+                    'vat_number').strip()
+                if vat_number:
+                    validate_result = validate_vat_number(
+                        stripe_customer_id=request.user.stripecustomer.stripe_id,
+                        billing_address_id=billing_address.id,
+                        is_user_ba=True
+                    )
+                    if 'error' in validate_result and validate_result['error']:
+                        messages.add_message(
+                            request, messages.ERROR, validate_result["error"],
+                            extra_tags='vat_error'
+                        )
+                    else:
+                        msg = _("Billing address updated successfully")
+                        messages.add_message(request, messages.SUCCESS, msg)
+                else:
+                    msg = _("Billing address updated successfully")
+                    messages.add_message(request, messages.SUCCESS, msg)
             else:
                 token = form.cleaned_data.get('token')
                 stripe_utils = StripeUtils()