Completed
Push — master ( aface4...d5d1bb )
by Mathias
02:27
created

ListRatesCustView   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 62
Duplicated Lines 40.32 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 9
c 1
b 0
f 0
dl 25
loc 62
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A get_context_data() 16 16 2
C get_queryset() 9 37 7

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
# Copyright 2013 Mathias WOLFF
2
# This file is part of pyfreebilling.
3
#
4
# pyfreebilling is free software: you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation, either version 3 of the License, or
7
# (at your option) any later version.
8
#
9
# pyfreebilling is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13
#
14
# You should have received a copy of the GNU General Public License
15
# along with pyfreebilling.  If not, see <http://www.gnu.org/licenses/>
16
17
# -*- coding: utf-8 -*-
18
19
from __future__ import unicode_literals
20
from django.core.files.storage import default_storage
21
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
22
from django.db.models.fields.files import FieldFile
23
from django.views.generic import FormView, ListView, View, CreateView
24
from django.views.generic.base import TemplateView
25
from django.views.generic.edit import FormMixin
26
from django.contrib import messages
27
from django.contrib.auth.views import login
28
from django.contrib.auth.decorators import login_required
29
from django.shortcuts import get_object_or_404
30
from django.http import HttpResponse
31
from django.utils.translation import ugettext_lazy as _
32
33
from braces.views import LoginRequiredMixin
34
35
from djqscsv import render_to_csv_response
36
37
import datetime
38
import calendar
39
40
from dateutil.relativedelta import relativedelta
41
42
from pyfreebill.models import Company,\
43
    Person,\
44
    CompanyBalanceHistory,\
45
    CDR,\
46
    CustomerDirectory,\
47
    CustomerRates,\
48
    CustomerRateCards,\
49
    Person
50
51
from customerportal.forms import CDRSearchForm, RatesForm
52
53
54
class CreateUserView(CreateView):
55
    template_name = "customer/register.html"
56
    model = Person
57
58
59
@login_required
60
def rates_csv_view(request, *args, **kwargs):
61
    ratecard = kwargs['ratecard']
62
63
    qs = CustomerRates.objects.values(
64
        'destination',
65
        'prefix',
66
        'rate',
67
        'block_min_duration',
68
        'minimal_time',
69
        'init_block')
70
71
    try:
72
        usercompany = Person.objects.get(user=request.user)
73
        company = get_object_or_404(Company, name=usercompany.company)
74
        rc = CustomerRateCards.objects.filter(
75
            company=company.pk)\
76
            .filter(ratecard__enabled=True)\
77
            .order_by('priority')
78
        qs = qs.filter(ratecard__pk=ratecard)
79
    except Person.DoesNotExist:
80
            messages.error(request,
81
                           _(u"""This user is not linked to a customer !"""))
82
83
    if ratecard and int(ratecard) and ratecard in rc:
84
        ratecard = int(ratecard)
85
        qs = qs.filter(ratecard__pk=ratecard)
86
    else:
87
        qs.none()
88
    return render_to_csv_response(qs,
89
                                  append_datestamp=True)
90
91
92
@login_required
93
def csv_view(request, *args, **kwargs):
94
    day = kwargs['day']
95
    month = kwargs['month']
96
    daymonth = None
97
98
    qs = CDR.objects.values('customer__name',
99
                            'caller_id_number',
100
                            'destination_number',
101
                            'start_stamp',
102
                            'billsec',
103
                            'prefix',
104
                            'sell_destination',
105
                            'rate',
106
                            'init_block',
107
                            'block_min_duration',
108
                            'total_sell',
109
                            'customer_ip',
110
                            'sip_user_agent'
111
                            )
112
113
    try:
114
        usercompany = Person.objects.get(user=request.user)
115
        company = get_object_or_404(Company, name=usercompany.company)
116
        qs = qs.filter(customer=company.pk)\
117
               .exclude(effective_duration="0")\
118
               .order_by('-start_stamp')
119
    except Person.DoesNotExist:
120
            messages.error(request,
121
                           _(u"""This user is not linked to a customer !"""))
122
123
    if day and int(day) < 8 and int(day) > 0:
124
        day = int(day)
125
        start_date = datetime.date.today() - datetime.timedelta(days=int(day))
126
        end_date = start_date + datetime.timedelta(days=1)
127
        daymonth = 'OK'
128
129
    if month and int(month) < 4 and int(month) > 0:
130
        month = int(month)
131
        dm = datetime.date.today()
132
        start_date = datetime.date(dm.year, dm.month, 1) - relativedelta(months=int(month))
133
        end_date = start_date + relativedelta(months=1)
134
        end_date = end_date - datetime.timedelta(days=1)
135
        daymonth = 'OK'
136
137
    if daymonth:
138
        qs = qs.filter(start_stamp__range=(start_date, end_date))
139
    else:
140
        qs.none()
141
    # import pdb; pdb.set_trace()
142
    return render_to_csv_response(qs,
143
                                  append_datestamp=True,
144
                                  field_header_map={'customer__name': 'Customer'})
145
146
147
class Template404View(LoginRequiredMixin, TemplateView):
148
    template_name = 'customer/404.html'
149
150
151
class Template500View(LoginRequiredMixin, TemplateView):
152
    template_name = 'customer/500.html'
153
154
155
class ListExportCustView(LoginRequiredMixin, TemplateView):
156
    template_name = 'customer/report.html'
157
158
    def get_context_data(self, **kwargs):
159 View Code Duplication
        context = super(ListExportCustView, self).get_context_data(**kwargs)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
160
        context['day_1'] = datetime.date.today() - datetime.timedelta(days=1)
161
        context['day_2'] = datetime.date.today() - datetime.timedelta(days=2)
162
        context['day_3'] = datetime.date.today() - datetime.timedelta(days=3)
163
        context['day_4'] = datetime.date.today() - datetime.timedelta(days=4)
164
        context['day_5'] = datetime.date.today() - datetime.timedelta(days=5)
165
        context['day_6'] = datetime.date.today() - datetime.timedelta(days=6)
166
        context['day_7'] = datetime.date.today() - datetime.timedelta(days=7)
167
        dm = datetime.date.today()
168
        context['month_1'] = datetime.date(dm.year, dm.month, 1) - relativedelta(months=1)
169
        context['month_2'] = datetime.date(dm.year, dm.month, 1) - relativedelta(months=2)
170
        context['month_3'] = datetime.date(dm.year, dm.month, 1) - relativedelta(months=3)
171
        return context
172
173
174
class HomePageCustView(LoginRequiredMixin, TemplateView):
175
    template_name = 'customer/home.html'
176
177
    def get_context_data(self, **kwargs):
178
        context = super(HomePageCustView, self).get_context_data(**kwargs)
179
        messages.info(self.request, _(u'Wellcome'))
180
        try:
181
            usercompany = Person.objects.get(user=self.request.user)
182
            try:
183
                context['company'] = Company.objects.get(name=usercompany.company)
184
                if context['company'].low_credit_alert > context['company'].customer_balance:
185
                    messages.warning(self.request,
186
                                     _(u'ALERT : Low balance (credit alert level : %s)') % context['company'].low_credit_alert)
187
                if context['company'].account_blocked_alert_sent:
188
                    messages.error(self.request,
189
                                   _(u'ALERT : Account blocked - no remaining credit - Please make an urgent payment'))
190
            except Company.DoesNotExist:
191
                pass
192
        except Person.DoesNotExist:
193
            messages.error(self.request,
194
                           _(u"""This user is not linked to a customer !"""))
195
196
        # integrer panneau contact et stats
197
        # integrer facture
198
        # integrer prestation
199
        return context
200
201
202
class ListRatesCustView(LoginRequiredMixin, FormMixin, ListView):
203
    template_name = 'customer/rates.html'
204
    rates_form = RatesForm()
205
206
    context_object_name = 'Rate'
207
    paginate_by = 30
208
    model = CustomerRates
209
210
    def get_queryset(self):
211
        qs = super(ListRatesCustView, self).get_queryset()
212
        try:
213
            self.usercompany = Person.objects.get(user=self.request.user)
214
            self.company = get_object_or_404(Company,
215
                                             name=self.usercompany.company)
216
            self.rc = CustomerRateCards.objects.filter(
217
                company=self.company.pk)\
218
                .filter(ratecard__enabled=True)\
219
                .order_by('priority')
220
            qs = qs.filter(enabled=True).order_by('destination')
221
        except Person.DoesNotExist:
222
            messages.error(self.request,
223
                           _(u"""This user is not linked to a customer !"""))
224
        # ratecard
225
        if self.request.GET.get("ratecard") and self.request.GET.get("ratecard") in self.rc:
226
            ratecard = self.request.GET.get("ratecard")
227
        else:
228
            self.rc = CustomerRateCards.objects.filter(
229
                company=self.company.pk)\
230
                .filter(ratecard__enabled=True)\
231
                .order_by('priority')
232 View Code Duplication
            ratecard = self.rc[0].id
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
233
            # import pdb; pdb.set_trace()
234
        destination = self.request.GET.get("destination")
235
        prefix = self.request.GET.get("prefix")
236
237
        if ratecard:  # and ratecard.isnumeric():
238
            qs = qs.filter(ratecard__pk=ratecard)
239
            if destination:
240
                qs = qs.filter(destination__contains=destination)
241
            if prefix:
242
                qs = qs.filter(prefix__startswith=prefix)
243
            # import pdb; pdb.set_trace()
244
            return qs
245
246
        return qs.none()
247
248 View Code Duplication
    def get_context_data(self, **kwargs):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
249
        context = super(ListRatesCustView, self).get_context_data(**kwargs)
250
        try:
251
            self.usercompany = Person.objects.get(user=self.request.user)
252
            self.company = get_object_or_404(Company,
253
                                             name=self.usercompany.company)
254
            context['ratecards'] = CustomerRateCards.objects.filter(
255
                company=self.company.pk)\
256
                .filter(ratecard__enabled=True)\
257
                .order_by('priority')
258
            # import pdb; pdb.set_trace()
259
            return context
260
        except Person.DoesNotExist:
261
            messages.error(self.request,
262
                           _(u"""This user is not linked to a customer !"""))
263
        return context
264
265
266
class StatsCustView(LoginRequiredMixin, TemplateView):
267
    template_name = 'customer/stats.html'
268
269
270
class SipAccountCustView(LoginRequiredMixin, ListView):
271
    template_name = 'customer/sip_account.html'
272
    context_object_name = 'sipaccount'
273
    paginate_by = 10
274
    model = CustomerDirectory
275
276 View Code Duplication
    def get_queryset(self):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
277
        qs = super(SipAccountCustView, self).get_queryset()
278
        try:
279
            self.usercompany = Person.objects.get(user=self.request.user)
280
            self.company = get_object_or_404(Company,
281
                                             name=self.usercompany.company)
282
            return CustomerDirectory.objects.filter(company=self.company.pk)\
283
                                            .order_by('id')
284
        except Person.DoesNotExist:
285
            messages.error(self.request,
286
                           _(u"""This user is not linked to a customer !"""))
287
        return qs.none()
288
289
290
class CdrReportCustView(LoginRequiredMixin, FormMixin, ListView):
291
    template_name = 'customer/cdr_view.html'
292
    context_object_name = 'Cdr'
293
#    form_class = CDRSearchForm
294
    paginate_by = 30
295
    model = CDR
296
297
    def get_queryset(self):
298
        qs = super(CdrReportCustView, self).get_queryset()
299
        try:
300
            self.usercompany = Person.objects.get(user=self.request.user)
301
            self.company = get_object_or_404(Company,
302
                                             name=self.usercompany.company)
303
            qs = qs.filter(customer=self.company.pk)\
304
                   .exclude(effective_duration="0")\
305
                   .order_by('-start_stamp')
306
        except Person.DoesNotExist:
307
            messages.error(self.request,
308
                           _(u"""This user is not linked to a customer !"""))
309
310
        # set start_date and end_date
311
        end_date = datetime.date.today() + datetime.timedelta(days=1)
312
        start_date = end_date - datetime.timedelta(days=30)
313
314
    	start_d = {'y': [], 'm': [], 'd': [], 'h': [], 'min': [], 'status': True}
315
    	end_d = {'y': [], 'm': [], 'd': [], 'h': [], 'min': [],'status': True}
316
    	li = ['y', 'm', 'd', 'h', 'min']
317
        for i in li:
318
            start_d[str(i)] = self.request.GET.get("from_" + str(i))
319
            if start_d[str(i)] and start_d[str(i)].isnumeric():
320
                start_d[str(i)] = int(start_d[str(i)])
321
            else:
322
                start_d['status'] = False
323
            end_d[str(i)] = self.request.GET.get("to_" + str(i))
324
            if end_d[str(i)] and end_d[str(i)].isnumeric():
325
                end_d[str(i)] = int(end_d[str(i)])
326
            else:
327
                end_d['status'] = False
328
        # dest num
329
        dest_num = self.request.GET.get("dest_num")
330
        if start_d['status']:
331
            start_date = datetime.datetime(start_d['y'], start_d['m'], start_d['d'], start_d['h'], start_d['min'])
332
        if end_d['status']:
333
            end_date = datetime.datetime(end_d['y'], end_d['m'], end_d['d'], end_d['h'], end_d['min'])
334
        if start_date and end_date:
335
            qs = qs.filter(start_stamp__range=(start_date, end_date))
336
337
        if dest_num and dest_num.isnumeric():
338
            qs = qs.filter(destination_number__startswith=dest_num)
339
340
        # test if get succes or not
341
        if start_d['status'] or end_d['status'] or dest_num:
342
            return qs
343
        return qs.none()
344
345
346
class BalanceHistoryCustView(LoginRequiredMixin, ListView):
347
    template_name = 'customer/balance.html'
348
    model = CompanyBalanceHistory
349
    context_object_name = 'CustomerBalance'
350
    paginate_by = 10
351
352 View Code Duplication
    def get_queryset(self):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
353
        qs = super(BalanceHistoryCustView, self).get_queryset()
354
        try:
355
            self.usercompany = Person.objects.get(user=self.request.user)
356
            self.company = get_object_or_404(Company, name=self.usercompany.company)
357
            return CompanyBalanceHistory.objects.filter(company=self.company.pk)\
358
                                                .filter(operation_type='customer')\
359
                                                .order_by('-date_modified')
360
        except Person.DoesNotExist:
361
            messages.error(self.request, _(u"""This user is not linked to a customer !"""))
362
        return qs.none()
363
364
    def get_context_data(self, **kwargs):
365
        context = super(BalanceHistoryCustView, self).get_context_data(**kwargs)
366
        try:
367
            self.usercompany = Person.objects.get(user=self.request.user)
368
            context['company'] = get_object_or_404(Company, name=self.usercompany.company)
369
            return context
370
        except Person.DoesNotExist:
371
            messages.error(self.request, _(u"""This user is not linked to a customer !"""))
372
        return context
373
374
375
class ProfileCustView(LoginRequiredMixin, TemplateView):
376
    template_name = 'customer/home.html'
377
378
    def get_context_data(self, **kwargs):
379
        context = super(HomePageCustView, self).get_context_data(**kwargs)
380
        messages.info(self.request, 'Your profile')
381
        return context
382