<commit_before>
from decimal import Decimal

try:
    import suds
except ImportError:
    suds = None

import vatnumber

from django.core.urlresolvers import reverse
from django.core.exceptions import ImproperlyConfigured
from django.shortcuts import get_object_or_404
from django.views.generic import TemplateView, FormView, RedirectView, CreateView, UpdateView
from django.db.models import Q
from django.http import Http404, HttpResponseRedirect
from django.conf import settings
from django.contrib import messages
from django.utils.translation import ugettext_lazy as _
from django.views.generic.detail import DetailView
#from django_xhtml2pdf.utils import render_to_pdf_response
from django.views.generic.edit import DeleteView, ModelFormMixin
from django.views.generic.list import ListView

#from mydjango.views import UserCreateView, UserUpdateView, UserDeleteView

from models import UserPlan, PlanQuota, PlanPricing, Plan, Order, BillingInfo
from forms import OrderForm, BillingInfoForm

# Create your views here.
from plans.forms import CreateOrderForm
from plans.models import Quota, Invoice

class PlanTableMixin(object):
    def get_plan_table(self, plan_list):
        """
        This method return a list in following order:
        [
            ( Quota1, [ Plan1Quota1, Plan2Quota1, ... , PlanNQuota1] ),
            ( Quota2, [ Plan1Quota2, Plan2Quota2, ... , PlanNQuota2] ),
            ...
            ( QuotaM, [ Plan1QuotaM, Plan2QuotaM, ... , PlanNQuotaM] ),
        ]

        This can be very easily printed as an HTML table element with quotas by row.

        Quotas are calculated based on ``plan_list``. These are all available quotas that are
        used by given plans. If any ``Plan`` does not have any of ``PlanQuota`` then value ``None``
        will be propagated to the data structure.

        """

        # Retrieve all quotas that are used by any ``Plan`` in ``plan_list``
        quota_list = Quota.objects.all().filter(planquota__plan__in=plan_list).distinct()

        # Create random access dict that for every ``Plan`` map ``Quota`` -> ``PlanQuota``
        plan_quotas_dic = {}
        for plan in plan_list:
            plan_quotas_dic[plan] = {}
            for plan_quota in plan.planquota_set.all():
                plan_quotas_dic[plan][plan_quota.quota] = plan_quota

        # Generate data structure described in method docstring, propagate ``None`` whenever
        # ``PlanQuota`` is not available for given ``Plan`` and ``Quota``
        return map(lambda quota: (quota,
                            map(lambda plan: plan_quotas_dic[plan].get(quota, None), plan_list)

            ), quota_list)



        
#class ExtendPlanView(CurrentPlanView):
#    template_name = "plans/extend.html"
#    def get_context_data(self, **kwargs):
#        context = super(ExtendPlanView, self).get_context_data(**kwargs)
#        context['pricings'] = PlanPricing.objects.select_related('pricing').filter(plan=context['userplan'])
#        context['form'] = OrderPlanForm()
#
#        return context

class UpgradePlanView(PlanTableMixin, ListView):
    template_name = "plans/upgrade.html"
    model = Plan
    context_object_name = "plan_list"

    def get_queryset(self):
        queryset = super(UpgradePlanView, self).get_queryset().prefetch_related('planpricing_set__pricing', 'planquota_set__quota')
        if self.request.user.is_authenticated():
            queryset = queryset.filter(
                            Q(available=True) & (
                                Q(customized = self.request.user) | Q(customized__isnull=True)
                                )
                            )
        else:
            queryset = queryset.filter(Q(available=True) & Q(customized__isnull=True))
        return queryset

    def get_context_data(self, **kwargs):
        context = super(UpgradePlanView, self).get_context_data(**kwargs)

        if self.request.user.is_authenticated():
            self.userplan = UserPlan.objects.select_related('plan').get(user=self.request.user)
            context['userplan'] = self.userplan
            try:
                context['current_userplan_index'] = list(self.object_list).index(self.userplan.plan)
            except ValueError:
                pass

        context['plan_table'] = self.get_plan_table(self.object_list)
        context['CURRENCY'] = settings.CURRENCY

        return context

class CurrentPlanView(UpgradePlanView):
    template_name = "plans/current.html"

    def get_queryset(self):
        return Plan.objects.filter(userplan__user=self.request.user).prefetch_related('planpricing_set__pricing', 'planquota_set__quota')<commit_msg>do not raise error, when user doesn`t assign to userplan<commit_after>
from decimal import Decimal

try:
    import suds
except ImportError:
    suds = None

import vatnumber

from django.core.urlresolvers import reverse
from django.core.exceptions import ImproperlyConfigured
from django.shortcuts import get_object_or_404
from django.views.generic import TemplateView, FormView, RedirectView, CreateView, UpdateView
from django.db.models import Q
from django.http import Http404, HttpResponseRedirect
from django.conf import settings
from django.contrib import messages
from django.utils.translation import ugettext_lazy as _
from django.views.generic.detail import DetailView
#from django_xhtml2pdf.utils import render_to_pdf_response
from django.views.generic.edit import DeleteView, ModelFormMixin
from django.views.generic.list import ListView

#from mydjango.views import UserCreateView, UserUpdateView, UserDeleteView

from models import UserPlan, PlanQuota, PlanPricing, Plan, Order, BillingInfo
from forms import OrderForm, BillingInfoForm

# Create your views here.
from plans.forms import CreateOrderForm
from plans.models import Quota, Invoice

class PlanTableMixin(object):
    def get_plan_table(self, plan_list):
        """
        This method return a list in following order:
        [
            ( Quota1, [ Plan1Quota1, Plan2Quota1, ... , PlanNQuota1] ),
            ( Quota2, [ Plan1Quota2, Plan2Quota2, ... , PlanNQuota2] ),
            ...
            ( QuotaM, [ Plan1QuotaM, Plan2QuotaM, ... , PlanNQuotaM] ),
        ]

        This can be very easily printed as an HTML table element with quotas by row.

        Quotas are calculated based on ``plan_list``. These are all available quotas that are
        used by given plans. If any ``Plan`` does not have any of ``PlanQuota`` then value ``None``
        will be propagated to the data structure.

        """

        # Retrieve all quotas that are used by any ``Plan`` in ``plan_list``
        quota_list = Quota.objects.all().filter(planquota__plan__in=plan_list).distinct()

        # Create random access dict that for every ``Plan`` map ``Quota`` -> ``PlanQuota``
        plan_quotas_dic = {}
        for plan in plan_list:
            plan_quotas_dic[plan] = {}
            for plan_quota in plan.planquota_set.all():
                plan_quotas_dic[plan][plan_quota.quota] = plan_quota

        # Generate data structure described in method docstring, propagate ``None`` whenever
        # ``PlanQuota`` is not available for given ``Plan`` and ``Quota``
        return map(lambda quota: (quota,
                            map(lambda plan: plan_quotas_dic[plan].get(quota, None), plan_list)

            ), quota_list)



        
#class ExtendPlanView(CurrentPlanView):
#    template_name = "plans/extend.html"
#    def get_context_data(self, **kwargs):
#        context = super(ExtendPlanView, self).get_context_data(**kwargs)
#        context['pricings'] = PlanPricing.objects.select_related('pricing').filter(plan=context['userplan'])
#        context['form'] = OrderPlanForm()
#
#        return context

class UpgradePlanView(PlanTableMixin, ListView):
    template_name = "plans/upgrade.html"
    model = Plan
    context_object_name = "plan_list"

    def get_queryset(self):
        queryset = super(UpgradePlanView, self).get_queryset().prefetch_related('planpricing_set__pricing', 'planquota_set__quota')
        if self.request.user.is_authenticated():
            queryset = queryset.filter(
                            Q(available=True) & (
                                Q(customized = self.request.user) | Q(customized__isnull=True)
                                )
                            )
        else:
            queryset = queryset.filter(Q(available=True) & Q(customized__isnull=True))
        return queryset

    def get_context_data(self, **kwargs):
        context = super(UpgradePlanView, self).get_context_data(**kwargs)

        if self.request.user.is_authenticated():
            try:
                self.userplan = UserPlan.objects.get(user=self.request.user).select_related('plan')
            except UserPlan.DoesNotExist:
                self.userplan = None

            context['userplan'] = self.userplan

            try:
                context['current_userplan_index'] = list(self.object_list).index(self.userplan.plan)
            except (ValueError, AttributeError):
                pass

        context['plan_table'] = self.get_plan_table(self.object_list)
        context['CURRENCY'] = settings.CURRENCY

        return context

class CurrentPlanView(UpgradePlanView):
    template_name = "plans/current.html"

    def get_queryset(self):
        return Plan.objects.filter(userplan__user=self.request.user).prefetch_related('planpricing_set__pricing', 'planquota_set__quota')
{'fraction_non_alphanumeric': 0.09414248021108179, 'fraction_numerical': 0.0044327176781002635, 'mean_word_length': 2.9698366149979054, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4960325', 'n_tokens_mistral': 2780, 'n_tokens_neox': 2700, 'n_words': 664}