Completed
Push — master ( da0207...5a5796 )
by Mathias
01:37
created

csv_view()   D

Complexity

Conditions 9

Size

Total Lines 50

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 50
rs 4
cc 9
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
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, Person, CompanyBalanceHistory, CDR, CustomerDirectory
43
44
from customerportal.forms import CDRSearchForm
45
46
47
@login_required
48
def csv_view(request, *args, **kwargs):
49
    day = kwargs['day']
50
    month = kwargs['month']
51
    daymonth = None
52
53
    qs = CDR.objects.values('customer__name',
54
        'caller_id_number',
55
        'destination_number',
56
        'start_stamp',
57
        'billsec',
58
        'prefix',
59
        'sell_destination',
60
        'rate',
61
        'init_block',
62
        'block_min_duration',
63
        'total_sell',
64
        'customer_ip',
65
        'sip_user_agent'
66
    )
67
68
    try:
69
        usercompany = Person.objects.get(user=request.user)
70
        company = get_object_or_404(Company, name=usercompany.company)
71
        qs = qs.filter(customer=company.pk).exclude(effective_duration="0").order_by('-start_stamp')
72
    except Person.DoesNotExist:
73
            messages.error(request, _(u"""This user is not linked to a customer !"""))
74
75
    if day and int(day) < 8 and int(day) > 0:
76
        day = int(day)
77
        start_date = datetime.date.today() - datetime.timedelta(days=int(day))
78
        end_date = start_date + datetime.timedelta(days=1)
79
        daymonth = 'OK'
80
81
    if month and int(month) < 4 and int(month) > 0:
82
        month = int(month)
83
        dm = datetime.date.today()
84
        start_date = datetime.date(dm.year, dm.month, 1) - relativedelta(months=int(month))
85
        end_date = start_date + relativedelta(months=1)
86
        end_date = end_date - datetime.timedelta(days=1)
87
        daymonth = 'OK'
88
89
    if daymonth:
90
        qs = qs.filter(start_stamp__range=(start_date, end_date))
91
    else:
92
        qs.none()
93
    # import pdb; pdb.set_trace()
94
    return render_to_csv_response(qs,
95
        append_datestamp=True,
96
        field_header_map={'customer__name': 'Customer'})
97
98
99
class Template404View(LoginRequiredMixin, TemplateView):
100
    template_name = 'customer/404.html'
101
102
103
class Template500View(LoginRequiredMixin, TemplateView):
104
    template_name = 'customer/500.html'
105
106
class ListExportCustView(LoginRequiredMixin, TemplateView):
107
    template_name = 'customer/report.html'
108
109
    def get_context_data(self, **kwargs):
110
        context = super(ListExportCustView, self).get_context_data(**kwargs)
111
        context['day_1'] = datetime.date.today() - datetime.timedelta(days=1)
112
        context['day_2'] = datetime.date.today() - datetime.timedelta(days=2)
113
        context['day_3'] = datetime.date.today() - datetime.timedelta(days=3)
114
        context['day_4'] = datetime.date.today() - datetime.timedelta(days=4)
115
        context['day_5'] = datetime.date.today() - datetime.timedelta(days=5)
116
        context['day_6'] = datetime.date.today() - datetime.timedelta(days=6)
117
        context['day_7'] = datetime.date.today() - datetime.timedelta(days=7)
118
        dm = datetime.date.today()
119
        context['month_1'] = datetime.date(dm.year, dm.month, 1)- relativedelta(months=1)
120
        context['month_2'] = datetime.date(dm.year, dm.month, 1)- relativedelta(months=2)
121
        context['month_3'] = datetime.date(dm.year, dm.month, 1)- relativedelta(months=3)
122
        return context
123
124
class HomePageCustView(LoginRequiredMixin, TemplateView):
125
    template_name = 'customer/home.html'
126
127
    def get_context_data(self, **kwargs):
128
        context = super(HomePageCustView, self).get_context_data(**kwargs)
129
        messages.info(self.request, _(u'Wellcome'))
130
        try:
131
            usercompany = Person.objects.get(user=self.request.user)
132
            try:
133
                context['company'] = Company.objects.get(name=usercompany.company)
134
                if context['company'].low_credit_alert > context['company'].customer_balance:
135
                    messages.warning(self.request, _(u'ALERT : Low balance (credit alert level : %s)') % context['company'].low_credit_alert)
136
                if context['company'].account_blocked_alert_sent:
137
                    messages.error(self.request, _(u'ALERT : Account blocked - no remaining credit - Please make an urgent payment'))
138
            except Company.DoesNotExist:
139
                pass
140
        except Person.DoesNotExist:
141
            messages.error(self.request, _(u"""This user is not linked to a customer !"""))
142
143
        # integrer panneau contact et stats
144
        # integrer facture
145
        # integrer prestation
146
        return context
147
148
149
class StatsCustView(LoginRequiredMixin, TemplateView):
150
	template_name = 'customer/stats.html'
151
152
153
class SipAccountCustView(LoginRequiredMixin, ListView):
154
    template_name = 'customer/sip_account.html'
155
    context_object_name = 'sipaccount'
156
    paginate_by = 10
157
    model = CustomerDirectory
158
159 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...
160
        qs = super(SipAccountCustView, self).get_queryset()
161
        try:
162
            self.usercompany = Person.objects.get(user=self.request.user)
163
            self.company = get_object_or_404(Company, name=self.usercompany.company)
164
            return CustomerDirectory.objects.filter(company=self.company.pk).order_by('id')
165
        except Person.DoesNotExist:
166
            messages.error(self.request, _(u"""This user is not linked to a customer !"""))
167
        return qs.none()
168
169
170
class CdrReportCustView(LoginRequiredMixin, FormMixin, ListView):
171
    template_name = 'customer/cdr_view.html'
172
    context_object_name = 'Cdr'
173
#    form_class = CDRSearchForm
174
    paginate_by = 30
175
    model = CDR
176
177
    def get_queryset(self):
178
        qs = super(CdrReportCustView, self).get_queryset()
179
        try:
180
            self.usercompany = Person.objects.get(user=self.request.user)
181
            self.company = get_object_or_404(Company, name=self.usercompany.company)
182
            qs = qs.filter(customer=self.company.pk).exclude(effective_duration="0").order_by('-start_stamp')
183
        except Person.DoesNotExist:
184
            messages.error(self.request, _(u"""This user is not linked to a customer !"""))
185
186
        # set start_date and end_date
187
        end_date = datetime.date.today() + datetime.timedelta(days=1)
188
        start_date = end_date - datetime.timedelta(days=30)
189
190
        #First print
191
192
    	# Get the q GET parameter
193
    	# date from and to and check value
194
    	start_d = {'y': [], 'm': [], 'd': [], 'h': [], 'min': [], 'status': True}
195
    	end_d = {'y': [], 'm': [], 'd': [], 'h': [], 'min': [],'status': True}
196
    	li = ['y', 'm', 'd', 'h', 'min']
197
        for i in li:
198
            start_d[str(i)] = self.request.GET.get("from_" + str(i))
199
            if start_d[str(i)] and start_d[str(i)].isnumeric():
200
                start_d[str(i)] = int(start_d[str(i)])
201
            else:
202
                start_d['status'] = False
203
            end_d[str(i)] = self.request.GET.get("to_" + str(i))
204
            if end_d[str(i)] and end_d[str(i)].isnumeric():
205
                end_d[str(i)] = int(end_d[str(i)])
206
            else:
207
                end_d['status'] = False
208
        # dest num
209
        dest_num = self.request.GET.get("dest_num")
210
        if start_d['status']:
211
            start_date = datetime.datetime(start_d['y'], start_d['m'], start_d['d'], start_d['h'], start_d['min'])
212
        if end_d['status']:
213
            end_date = datetime.datetime(end_d['y'], end_d['m'], end_d['d'], end_d['h'], end_d['min'])
214
        if start_date and end_date:
215
            qs = qs.filter(start_stamp__range=(start_date, end_date))
216
217
        if dest_num and dest_num.isnumeric():
218
            qs = qs.filter(destination_number__startswith=dest_num)
219
220
        # test if get succes or not
221
        if start_d['status'] or end_d['status'] or dest_num:
222
            return qs
223
        return qs.none()
224
225
226
class BalanceHistoryCustView(LoginRequiredMixin, ListView):
227
    template_name = 'customer/balance.html'
228
    model = CompanyBalanceHistory
229
    context_object_name = 'CustomerBalance'
230
    paginate_by = 10
231
232 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...
233
        qs = super(BalanceHistoryCustView, self).get_queryset()
234
        try:
235
            self.usercompany = Person.objects.get(user=self.request.user)
236
            self.company = get_object_or_404(Company, name=self.usercompany.company)
237
            return CompanyBalanceHistory.objects.filter(company=self.company.pk).filter(operation_type='customer').order_by('-date_modified')
238
        except Person.DoesNotExist:
239
            messages.error(self.request, _(u"""This user is not linked to a customer !"""))
240
        return qs.none()
241
242
    def get_context_data(self, **kwargs):
243
        context = super(BalanceHistoryCustView, self).get_context_data(**kwargs)
244
        try:
245
            self.usercompany = Person.objects.get(user=self.request.user)
246
            context['company'] = get_object_or_404(Company, name=self.usercompany.company)
247
            return context
248
        except Person.DoesNotExist:
249
            messages.error(self.request, _(u"""This user is not linked to a customer !"""))
250
        return context
251
252
253
class ProfileCustView(LoginRequiredMixin, TemplateView):
254
    template_name = 'customer/home.html'
255
256
    def get_context_data(self, **kwargs):
257
        context = super(HomePageCustView, self).get_context_data(**kwargs)
258
        messages.info(self.request, 'Your profile')
259
        return context