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

pyfreebill.CarrierCIDNormalizationRulesAdmin   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 9
Duplicated Lines 0 %
Metric Value
wmc 2
dl 0
loc 9
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
A CarrierCIDNormalizationRulesAdmin.has_change_permission() 0 5 2
1
# -*- coding: utf-8 -*-
2
# Copyright 2013 Mathias WOLFF
3
# This file is part of pyfreebilling.
4
#
5
# pyfreebilling is free software: you can redistribute it and/or modify
6
# it under the terms of the GNU General Public License as published by
7
# the Free Software Foundation, either version 3 of the License, or
8
# (at your option) any later version.
9
#
10
# pyfreebilling is distributed in the hope that it will be useful,
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
# GNU General Public License for more details.
14
#
15
# You should have received a copy of the GNU General Public License
16
# along with pyfreebilling.  If not, see <http://www.gnu.org/licenses/>
17
18
from django.contrib import admin
19
from django.contrib import messages
20
from django.contrib.contenttypes import generic
21
from django.contrib.comments.models import Comment
22
from django.contrib.admin.models import LogEntry, ADDITION, CHANGE, DELETION
23
from django.utils.html import escape
24
from django.core.urlresolvers import reverse
25
from django.contrib.admin.views.main import ChangeList
26
from django.forms.models import BaseInlineFormSet
27
from django.template import Context, loader
28
from django.utils.safestring import mark_safe
29
from django.conf import settings
30
from django.utils.translation import ugettext_lazy as _
31
32
from datetime import date
33
import datetime
34
35
from yawdadmin import admin_site
36
from yawdadmin.admin import SortableModelAdmin
37
38
from import_export.admin import ImportExportMixin, ExportMixin, ImportMixin
39
from import_export.formats import base_formats
40
41
from switch import esl
42
43
from pyfreebill.models import *
44
from pyfreebill.forms import CustomerRateCardsAdminForm, CompanyAdminForm, CustomerRatesAdminForm, ProviderRatesAdminForm, ProviderTariffAdminForm, RateCardAdminForm, CustomerDirectoryAdminForm
45
from pyfreebill.resources import CDRResourceExtra, CalleridPrefixResource
46
47
48
APP_LABEL = _('CDR report')
49
50
DEFAULT_FORMATS = (base_formats.CSV, )
51
52
53 View Code Duplication
def sofiaupdate(modeladmin, request, queryset):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
54
    """ generate new sofia xml config file """
55
    try:
56
        t = loader.get_template('xml/sofia.conf.xml')
57
    except IOError:
58
        messages.error(request,
59
                       """sofia config xml file update failed. Can not load
60
                       template file !""")
61
    sipprofiles = SipProfile.objects.all()
62
    accounts = Company.objects.filter(supplier_enabled=True)
63
    c = Context({"sipprofiles": sipprofiles, "accounts": accounts})
64
    try:
65
        f = open('/usr/local/freeswitch/conf/autoload_configs/sofia.conf.xml',
66
                 'w')
67
        try:
68
            f.write(t.render(c))
69
            f.close()
70
            try:
71
                fs = esl.getReloadGateway()
72
                messages.success(request, "FS successfully reload")
73
            except IOError:
74
                messages.error(request, """customer sip config xml file update
75
                    failed. FS ACL update failed ! Try manually -- %s""" % fs)
76
        finally:
77
            #f.close()
78
            messages.success(request, "sofia config xml file update success")
79
    except IOError:
80
        messages.error(request, """sofia config xml file update failed. Can
81
            not create file !""")
82
sofiaupdate.short_description = _(u"update sofia config xml file")
83
84
85 View Code Duplication
def directoryupdate(modeladmin, request, queryset):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
86
    """ generate new directory xml config file """
87
    try:
88
        t = loader.get_template('xml/directory.conf.xml')
89
    except IOError:
90
        messages.error(request, """customer sip config xml file update failed.
91
            Can not load template file !""")
92
    customerdirectorys = CustomerDirectory.objects.filter(company__customer_enabled__exact=True, enabled=True)
93
    accounts = Company.objects.filter(customer_enabled=True)
94
    c = Context({"customerdirectorys": customerdirectorys,
95
                 "accounts": accounts})
96
    try:
97
        f = open('/usr/local/freeswitch/conf/directory/default.xml', 'w')
98
        try:
99
            f.write(t.render(c))
100
            f.close()
101
            try:
102
                fs = esl.getReloadACL()
103
                messages.success(request, "FS successfully reload")
104
            except IOError:
105
                messages.error(request, """customer sip config xml file update
106
                    failed. FS ACL update failed ! Try manually - %s""" % fs)
107
        finally:
108
            #f.close()
109
            messages.success(request, """customer sip config xml file update
110
                success""")
111
    except IOError:
112
        messages.error(request, """customer sip config xml file update failed.
113
            Can not create file !""")
114
directoryupdate.short_description = _(u"update customer sip config xml file")
115
116
117 View Code Duplication
def aclupdate(modeladmin, request, queryset):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
118
    """ generate new ACL xml config file """
119
    try:
120
        t = loader.get_template('xml/acl.conf.xml')
121
    except IOError:
122
        messages.error(request, """ACL config xml file update failed. Can
123
            not load template file !""")
124
    acllists = AclLists.objects.all()
125
    aclnodes = AclNodes.objects.all()
126
    c = Context({"acllists": acllists, "aclnodes": aclnodes})
127
    try:
128
        f = open('/usr/local/freeswitch/conf/autoload_configs/acl.conf.xml',
129
                 'w')
130
        try:
131
            f.write(t.render(c))
132
            f.close()
133
            try:
134
                fs = esl.getReloadACL()
135
                messages.success(request, "FS successfully reload")
136
            except IOError:
137
                messages.error(request, """ACL config xml file update failed.
138
                    FS ACL update failed ! Try manually--- %s""" % fs)
139
        finally:
140
            messages.success(request, "ACL config xml file update success")
141
    except IOError:
142
        messages.error(request, """ACL xml file update failed. Can not
143
            create file !""")
144
aclupdate.short_description = _(u"update ACL config xml file")
145
146
admin.site.add_action(directoryupdate, _(u"""generate customer sip
147
    configuration file"""))
148
admin.site.add_action(sofiaupdate, _(u"generate sofia configuration file"))
149
admin.site.add_action(aclupdate, _(u"generate acl configuration file"))
150
151
# Company - Contatcs
152
153
154
class EmailAddressInline(generic.GenericTabularInline):
155
    model = EmailAddress
156
    extra = 0
157
    collapse = True
158
159
160
class PhoneNumberInline(generic.GenericTabularInline):
161
    model = PhoneNumber
162
    extra = 0
163
    collapse = True
164
    title_icon = 'fa-phone-square'
165
166
167
class InstantMessengerInline(generic.GenericTabularInline):
168
    model = InstantMessenger
169
    extra = 0
170
    collapse = True
171
172
173
class WebSiteInline(generic.GenericTabularInline):
174
    model = WebSite
175
    extra = 0
176
    collapse = True
177
178
179
class StreetAddressInline(generic.GenericStackedInline):
180
    model = StreetAddress
181
    extra = 0
182
    collapse = True
183
    modal = True
184
185
186
class SpecialDateInline(generic.GenericStackedInline):
187
    model = SpecialDate
188
    extra = 0
189
    collapse = True
190
191
192
class CommentInline(generic.GenericStackedInline):
193
    model = Comment
194
    ct_fk_field = 'object_pk'
195
    extra = 0
196
    collapse = True
197
198
199
class CustomerRateCardsInline(admin.StackedInline):
200
    model = CustomerRateCards
201
    description = 'select the Ratecards affected to customer account. Order is important !'
202
    form = CustomerRateCardsAdminForm
203
    max_num = 3
204
    extra = 0
205
    modal = True
206
    # sortable = True
207
    # sortable_order_field = 'priority'
208
209
210
class CompanyAdmin(admin.ModelAdmin):
211
    inlines = [
212
        CustomerRateCardsInline,
213
        PhoneNumberInline,
214
        EmailAddressInline,
215
        InstantMessengerInline,
216
        WebSiteInline,
217
        StreetAddressInline,
218
        SpecialDateInline,
219
        CommentInline,
220
    ]
221
    form = CompanyAdminForm
222
    affix = True
223
    save_on_top = True
224
    title_icon = 'fa-group'
225
226
    search_fields = ['^name', ]
227
    prepopulated_fields = {'slug': ('name',)}
228
    readonly_fields = ('customer_balance', 'supplier_balance', 'vat_number_validated')
229
    fieldsets = (
230
        ('General', {
231
            'fields': (('name', 'nickname'),
232
                       ('slug', 'about'),
233
                       'account_number',
234
                       ('vat', 'vat_number'),
235
                       'vat_number_validated',
236
                       ('swift_bic', 'iban')),
237
            'description': 'General company informations'
238
        }),
239
        ('Customer settings', {
240
            'fields': ('customer_enabled',
241
                       ('max_calls', 'calls_per_second'),
242
                       'billing_cycle',
243
                       ('prepaid', 'credit_limit'),
244
                       ('customer_balance', 'cb_currency')),
245
        }),
246
        ('Customer alerts', {
247
            'fields': ('low_credit_alert',
248
                       'email_alert',
249
                       'low_credit_alert_sent',
250
                       'account_blocked_alert_sent'),
251
            'classes': ('collapsed',),
252
            'description': 'All the customer alert parameters'
253
        }),
254
        ('Provider settings', {
255
            'fields': ('supplier_enabled',
256
                       'supplier_balance'),
257
            'classes': ('collapsed',),
258
            'description': 'If this company is your provider, this is right place to manage its parameters'
259
        }),
260
    )
261
262
    def get_customer_enabled_display(self, obj):
263
        if obj.customer_enabled:
264
            return mark_safe('<span class="label label-success"><i class="icon-thumbs-up"></i> YES</span>')
265
        return mark_safe('<span class="label label-danger"><i class="icon-thumbs-down"></i> NO</span>')
266
    get_customer_enabled_display.short_description = 'Customer'
267
    get_customer_enabled_display.admin_order_field = 'customer_enabled'
268
269
    def get_supplier_enabled_display(self, obj):
270
        if obj.supplier_enabled:
271
            return mark_safe('<span class="label label-success"><i class="icon-thumbs-up"></i> YES</span>')
272
        return mark_safe('<span class="label label-danger"><i class="icon-thumbs-down"></i> NO</span>')
273
    get_supplier_enabled_display.short_description = 'Provider'
274
    get_supplier_enabled_display.admin_order_field = 'provider_enabled'
275
    
276
    def get_prepaid_display(self, obj):
277
        if obj.prepaid:
278
            return mark_safe('<span class="label label-success"><i class="icon-thumbs-up"></i> YES</span>')
279
        return mark_safe('<span class="label label-danger"><i class="icon-thumbs-down"></i> NO</span>')
280
    get_prepaid_display.short_description = 'Prepaid'
281
    get_prepaid_display.admin_order_field = 'prepaid'
282
    
283
    def get_vat_display(self, obj):
284
        if obj.vat:
285
            return mark_safe('<span class="label label-info"><i class="icon-thumbs-up"></i> YES</span>')
286
        return mark_safe('<span class="label label-danger"><i class="icon-thumbs-down"></i> NO</span>')
287
    get_vat_display.short_description = 'VAT'
288
    get_vat_display.admin_order_field = 'vat'
289
290
    def get_vat_number_validated_display(self, obj):
291
        if obj.vat_number_validated:
292
            return mark_safe('<span class="label label-info"><i class="icon-thumbs-up"></i> YES</span>')
293
        return mark_safe('<span class="label label-danger"><i class="icon-thumbs-down"></i> NO</span>')
294
    get_vat_number_validated_display.short_description = 'VIES'
295
    get_vat_number_validated_display.admin_order_field = 'vies'
296
297
    def has_add_permission(self, request, obj=None):
298
        if request.user.is_superuser:
299
            return True
300
        else:
301
            return False
302
303
    def has_delete_permission(self, request, obj=None):
304
        if request.user.is_superuser:
305
            return True
306
        else:
307
            return False
308
309
    def get_actions(self, request):
310
        if request.user.is_superuser:
311
            actions = super(CompanyAdmin, self).get_actions(request)
312
            if 'delete_selected' in actions:
313
                del actions['delete_selected']
314
            return actions
315
        return
316
317
    def changelist_view(self, request, extra_context=None):
318
        if request.user.is_superuser:
319
            self.list_display_links = ['name', ]
320
            return super(CompanyAdmin, self).changelist_view(request, extra_context=None)
321
        else:
322
            self.list_display_links = ['None', ]
323
            return super(CompanyAdmin, self).changelist_view(request, extra_context=None)
324
325
    def get_list_display(self, request):
326
        if request.user.is_superuser:
327
            return ('name',
328
                    'get_prepaid_display',
329
                    'get_vat_display',
330
                    'get_vat_number_validated_display',
331
                    'get_customer_enabled_display',
332
                    'customer_balance',
333
                    'cb_currency',
334
                    'get_supplier_enabled_display',
335
                    'supplier_balance',
336
                    'balance_history')
337
        else:
338
            return ('name',
339
                    'get_prepaid_display',
340
                    'get_customer_enabled_display',
341
                    'customer_balance')
342
343
#     def get_list_filter(self, request):
344
#         if request.user.is_superuser:
345
#             #return ('name',)
346
#             return ['prepaid', 'customer_enabled', 'supplier_enabled']
347
#         else:
348
#             return []
349
350
    def get_readonly_fields(self, request, obj=None):
351
        if request.user.is_superuser:
352
            return ['customer_balance',
353
                    'supplier_balance',
354
                    'low_credit_alert_sent',
355
                    'account_blocked_alert_sent']
356
        else:
357
            return ['name',
358
                    'prepaid',
359
                    'customer_enabled',
360
                    'customer_balance',
361
                    'vat_number',
362
                    'max_calls',
363
                    'billing_cycle']
364
365
    def get_form(self, request, obj=None, **kwargs):
366
        self.exclude = []
367
        if not request.user.is_superuser:
368
            self.exclude.append('supplier_enabled')
369
            self.exclude.append('supplier_balance')
370
            self.exclude.append('vat')
371
            self.exclude.append('nickname')
372
            self.exclude.append('slug')
373
            self.exclude.append('about')
374
375
        return super(CompanyAdmin, self).get_form(request, obj, **kwargs)
376
377
    def queryset(self, request):
378
        user = getattr(request, 'user', None)
379
        qs = super(CompanyAdmin, self).queryset(request)
380
        if user.is_superuser:
381
            return qs
382
        else:
383
            usercompany = Person.objects.get(user=user)
384
        return qs.filter(name=usercompany.company)
385
386
387
class PersonAdmin(admin.ModelAdmin):
388
    inlines = [
389
        PhoneNumberInline,
390
        EmailAddressInline,
391
        InstantMessengerInline,
392
        WebSiteInline,
393
        StreetAddressInline,
394
        SpecialDateInline,
395
        CommentInline,
396
    ]
397
398
    list_display_links = ('first_name',
399
                          'last_name')
400
    list_display = ('first_name',
401
                    'last_name',
402
                    'company')
403
    list_filter = ('company', )
404
    ordering = ('last_name',
405
                'first_name')
406
    search_fields = ['^first_name',
407
                     '^last_name',
408
                     '^company__name']
409
    prepopulated_fields = {'slug': ('first_name', 'last_name')}
410
411
    def has_change_permission(self, request, obj=None):
412
        if request.user.is_superuser:
413
            return True
414
        else:
415
            return False
416
417
418
class GroupAdmin(admin.ModelAdmin):
419
    list_display_links = ('name', )
420
    list_display = ('name',
421
                    'date_modified')
422
    ordering = ('-date_modified',
423
                'name')
424
    search_fields = ['^name',
425
                     '^about']
426
    prepopulated_fields = {'slug': ('name',)}
427
428
    def has_change_permission(self, request, obj=None):
429
        if request.user.is_superuser:
430
            return True
431
        else:
432
            return False
433
434
435
class CompanyBalanceHistoryAdmin(admin.ModelAdmin):
436
    list_display_links = ('company', )
437
    list_display = ('company',
438
                    'amount_debited',
439
                    'amount_refund',
440
                    'customer_balance',
441
                    'supplier_balance',
442
                    'operation_type',
443
                    'reference',
444
                    'date_modified')
445
    ordering = ('-date_modified',
446
                'company')
447
    search_fields = ['^company__name',
448
                     '^reference']
449
450
    def save_model(self, request, obj, form, change):
451
        if change:
452
            messages.info(request, "No need to update balance")
453
        else:
454
            company = form.cleaned_data['company']
455
            amount_debited = form.cleaned_data['amount_debited']
456
            amount_refund = form.cleaned_data['amount_refund']
457
            if form.cleaned_data['operation_type'] == "customer":
458
                balance = Company.objects.get(pk=company.id)
459
                balance.customer_balance = balance.customer_balance - amount_debited + amount_refund
460
                balance.save()
461
                obj.customer_balance = balance.customer_balance
462
            elif form.cleaned_data['operation_type'] == "supplier":
463
                balance = Company.objects.get(pk=company.id)
464
                balance.supplier_balance = balance.supplier_balance - amount_debited + amount_refund
465
                balance.save()
466
                obj.supplier_balance = balance.supplier_balance
467
            else:
468
                pass
469
            messages.success(request, "balance updated")
470
        obj.save()
471
472
    fieldsets = (
473
        ('General', {
474
            'fields': ('company',
475
                       'operation_type',
476
                       'reference',
477
                       'description')}),
478
        ('Amount', {
479
            'fields': ('amount_debited',
480
                       'amount_refund')}),
481
        ('Balances', {
482
            'fields': ('customer_balance',
483
                       'supplier_balance')}),
484
    )
485
486
    def get_list_filter(self, request):
487
        if request.user.is_superuser:
488
            return ['company', 'operation_type']
489
        else:
490
            return []
491
            
492
    def has_change_permission(self, request, obj=None):
493
        if request.user.is_superuser:
494
            return True
495
        else:
496
            return False
497
498
    def has_delete_permission(self, request, obj=None):
499
        return False
500
501
    def get_actions(self, request):
502
        if request.user.is_superuser:
503
            return
504
        else:
505
            return
506
507
    def get_readonly_fields(self, request, obj=None):
508
        if obj:  # This is the case when obj is already created. it's an edit
509
            return ['company',
510
                    'amount_debited',
511
                    'amount_refund',
512
                    'customer_balance',
513
                    'supplier_balance',
514
                    'operation_type']
515
        else:
516
            return ['customer_balance', 'supplier_balance']
517
518
# CallerID prefix list
519
520
521
class CalleridPrefixAdmin(ImportMixin, admin.ModelAdmin):
522
    list_display = ['calleridprefixlist',
523
                    'prefix',
524
                    'date_added',
525
                    'date_modified']
526
    ordering = ('calleridprefixlist',
527
                'prefix')
528
    list_filter = ('calleridprefixlist', )
529
    search_fields = ('^prefix', )
530
    resource_class = CalleridPrefixResource
531
532
    def has_change_permission(self, request, obj=None):
533
        if request.user.is_superuser:
534
            return True
535
        else:
536
            return False
537
538
    def get_import_formats(self):
539
        format_csv = DEFAULT_FORMATS
540
        return [f for f in format_csv if f().can_import()]
541
542
543
class CalleridPrefixListAdmin(admin.ModelAdmin):
544
    list_display = ['name',
545
                    'description',
546
                    'prefix',
547
                    'date_added',
548
                    'date_modified']
549
    ordering = ('name', )
550
    list_filter = ['name', ]
551
    search_fields = ('^name',
552
                     'description')
553
554
    def has_change_permission(self, request, obj=None):
555
        if request.user.is_superuser:
556
            return True
557
        else:
558
            return False
559
560
# Provider Rates
561
562
563
class ProviderRatesFormSet(BaseInlineFormSet):
564
565
    def get_queryset(self):
566
        qs = super(ProviderRatesFormSet, self).get_queryset()
567
        return qs[:40]
568
569
570
class ProviderRatesInline(admin.TabularInline):
571
    model = ProviderRates
572
    formset = ProviderRatesFormSet
573
    max_count = 40
574
    extra = 1
575
576
577 View Code Duplication
class ProviderTariffAdmin(admin.ModelAdmin):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
578
    list_display = ['id',
579
                    'name',
580
                    'carrier',
581
                    'currency',
582
                    'prefix',
583
                    'quality',
584
                    'reliability',
585
                    'date_start',
586
                    'date_end',
587
                    'get_boolean_display',
588
                    'rates']
589
    ordering = ['name', ]
590
    readonly_fields = ['id', ]
591
    form = ProviderTariffAdminForm
592
593
    def get_boolean_display(self, obj):
594
        if obj.enabled:
595
            return mark_safe('<span class="label label-success"><i class="icon-thumbs-up"></i> YES</span>')
596
        return mark_safe('<span class="label label-warning"><i class="icon-thumbs-down"></i> NO</span>')
597
    get_boolean_display.short_description = 'Enabled'
598
    get_boolean_display.admin_order_field = 'enabled'
599
600
    def has_change_permission(self, request, obj=None):
601
        if request.user.is_superuser:
602
            return True
603
        else:
604
            return False
605
606
607 View Code Duplication
class ProviderRatesAdmin(ImportExportMixin, admin.ModelAdmin):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
608
    list_display = ['provider_tariff',
609
                    'destination',
610
                    'digits',
611
                    'cost_rate',
612
                    'block_min_duration',
613
                    'init_block',
614
                    'date_start',
615
                    'date_end',
616
                    'get_boolean_display',
617
                    'date_added',
618
                    'date_modified']
619
    ordering = ['provider_tariff',
620
                'digits']
621
    list_filter = ['provider_tariff',
622
                   'enabled',
623
                   'destination']
624
    search_fields = ['^digits',
625
                     'date_start',
626
                     'date_end',
627
                     '^destination']
628
    actions = ['make_enabled',
629
               'make_disabled']
630
    form = ProviderRatesAdminForm
631
    
632
    def get_boolean_display(self, obj):
633
        if obj.enabled:
634
            return mark_safe('<span class="label label-success"><i class="icon-thumbs-up"></i> YES</span>')
635
        return mark_safe('<span class="label label-warning"><i class="icon-thumbs-down"></i> NO</span>')
636
    get_boolean_display.short_description = 'Enabled'
637
    get_boolean_display.admin_order_field = 'enabled'
638
639
    def has_change_permission(self, request, obj=None):
640
        if request.user.is_superuser:
641
            return True
642
        else:
643
            return False
644
645
    def make_enabled(self, request, queryset):
646
        rows_updated = queryset.update(enabled=True)
647
        if rows_updated == 1:
648
            message_bit = "1 item was"
649
        else:
650
            message_bit = "%s items were" % rows_updated
651
        self.message_user(request, "%s successfully marked as enabled." % message_bit)
652
    make_enabled.short_description = _(u"mark selected items as enabled")
653
654
    def make_disabled(self, request, queryset):
655
        rows_updated = queryset.update(enabled=False)
656
        if rows_updated == 1:
657
            message_bit = "1 item was"
658
        else:
659
            message_bit = "%s items were" % rows_updated
660
        self.message_user(request, "%s successfully marked as disabled." % message_bit)
661
    make_disabled.short_description = _(u"mark selected items as disabled")
662
663
    def get_import_formats(self):
664
        format_csv = DEFAULT_FORMATS
665
        return [f for f in format_csv if f().can_import()]
666
667
    def get_export_formats(self):
668
        format_csv = DEFAULT_FORMATS
669
        return [f for f in format_csv if f().can_export()]
670
671
# LCR
672
673
674
class LCRProvidersInline(admin.TabularInline):
675
    model = LCRProviders
676
#    formset = LCRProvidersFormSet
677
#    fields = ('rates',)
678
    extra = 0
679
680
681
class LCRGroupAdmin(admin.ModelAdmin):
682
    list_display = ['name', 'description', 'lcrtype']
683
    ordering = ('name', 'lcrtype')
684
    list_filter = ('lcrtype',)
685
    inlines = [
686
        LCRProvidersInline,
687
    ]
688
689
    def has_change_permission(self, request, obj=None):
690
        if request.user.is_superuser:
691
            return True
692
        else:
693
            return False
694
695
696
class LCRProvidersAdmin(admin.ModelAdmin):
697
    list_display = ['lcr', 'provider_tariff', 'rates']
698
    list_filter = ('lcr',)
699
700
    def has_change_permission(self, request, obj=None):
701
        if request.user.is_superuser:
702
            return True
703
        else:
704
            return False
705
706
# Customer Rates
707
708
709
class CustomerRatesFormSet(BaseInlineFormSet):
710
    def get_queryset(self):
711
        qs = super(CustomerRatesFormSet, self).get_queryset()
712
        return qs[:40]
713
714
715
class CustomerRatesInline(admin.TabularInline):
716
    model = CustomerRates
717
    #formset = CustomerRatesFormSet
718
    max_num = 40
719
    extra = 1
720
721
722 View Code Duplication
class CustomerRatesAdmin(ImportExportMixin, admin.ModelAdmin):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
723
    list_display = ['id',
724
                    'ratecard',
725
                    'destination',
726
                    'prefix',
727
                    'rate',
728
                    'block_min_duration',
729
                    'init_block',
730
                    'date_start',
731
                    'date_end',
732
                    'get_boolean_display',
733
                    'date_added',
734
                    'date_modified']
735
    ordering = ['ratecard',
736
                'prefix']
737
    list_filter = ['ratecard',
738
                   'enabled',
739
                   'destination']
740
    search_fields = ['^prefix',
741
                     'date_start',
742
                     'date_end',
743
                     '^destination']
744
    actions = ['make_enabled', 'make_disabled']
745
    readonly_fields = ['id', ]
746
    form = CustomerRatesAdminForm
747
748
    def get_boolean_display(self, obj):
749
        if obj.enabled:
750
            return mark_safe('<span class="label label-success"><i class="icon-thumbs-up"></i> YES</span>')
751
        return mark_safe('<span class="label label-warning"><i class="icon-thumbs-down"></i> NO</span>')
752
    get_boolean_display.short_description = 'Enabled'
753
    get_boolean_display.admin_order_field = 'enabled'
754
    
755
    def has_change_permission(self, request, obj=None):
756
        if request.user.is_superuser:
757
            return True
758
        else:
759
            return False
760
761
    def make_enabled(self, request, queryset):
762
        rows_updated = queryset.update(enabled=True)
763
        if rows_updated == 1:
764
            message_bit = "1 item was"
765
        else:
766
            message_bit = "%s items were" % rows_updated
767
        self.message_user(request,
768
                          "%s successfully marked as enabled." % message_bit)
769
    make_enabled.short_description = _(u"mark selected items as enabled")
770
771
    def make_disabled(self, request, queryset):
772
        rows_updated = queryset.update(enabled=False)
773
        if rows_updated == 1:
774
            message_bit = "1 item was"
775
        else:
776
            message_bit = "%s items were" % rows_updated
777
        self.message_user(request,
778
                          "%s successfully marked as disabled." % message_bit)
779
    make_disabled.short_description = _(u"mark selected items as disabled")
780
781
    def get_import_formats(self):
782
        format_csv = DEFAULT_FORMATS
783
        return [f for f in format_csv if f().can_import()]
784
785
    def get_export_formats(self):
786
        format_csv = DEFAULT_FORMATS
787
        return [f for f in format_csv if f().can_export()]
788
789
790 View Code Duplication
class RateCardAdmin(admin.ModelAdmin):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
791
    list_display = ['id',
792
                    'name',
793
                    'currency',
794
                    'lcrgroup',
795
                    'lcr',
796
                    'get_boolean_display',
797
                    'rates',
798
                    'callerid_filter',
799
                    'callerid_list']
800
    ordering = ['name', 'enabled', 'lcrgroup']
801
    list_filter = ['enabled', 'lcrgroup']
802
    search_fields = ['description', '^name']
803
    form = RateCardAdminForm
804
#     inlines = [
805
#         CustomerRatesInline,
806
#     ]
807
808
    def has_change_permission(self, request, obj=None):
809
        if request.user.is_superuser:
810
            return True
811
        else:
812
            return False
813
            
814
    def get_boolean_display(self, obj):
815
        if obj.enabled:
816
            return mark_safe('<span class="label label-success"><i class="icon-thumbs-up"></i> YES</span>')
817
        return mark_safe('<span class="label label-warning"><i class="icon-thumbs-down"></i> NO</span>')
818
    get_boolean_display.short_description = 'Enabled'
819
    get_boolean_display.admin_order_field = 'enabled'
820
821
822
class CustomerRateCardsAdmin(SortableModelAdmin):
823
    list_display = ['company',
824
                    'ratecard',
825
                    'tech_prefix',
826
                    'priority',
827
                    'description']
828
    ordering = ['company', ]
829
    raw_id_fields = ('ratecard',)
830
    list_filter = ['ratecard', 'company']
831
    search_fields = ['^company__company', ]
832
    form = form = CustomerRateCardsAdminForm
833
834
    def has_change_permission(self, request, obj=None):
835
        if request.user.is_superuser:
836
            return True
837
        else:
838
            return False
839
840
# CustomerDirectory
841
842
843
class CustomerDirectoryAdmin(admin.ModelAdmin):
844
    list_display = ['company',
845
                    'get_registration_display',
846
                    'name',
847
                    'sip_ip',
848
                    'max_calls',
849
                    'calls_per_second',
850
                    'get_enabled_display',
851
                    'get_fake_ring_display',
852
                    'get_cli_debug_display']
853
    ordering = ['company', 'enabled']
854
    list_filter = ['enabled', ]
855
    #list_editable = ['max_calls', 'calls_per_second']
856
    search_filter = ['^sip_ip', '^company', '^name']
857
    exclude = ['vmd', ]
858
    form = CustomerDirectoryAdminForm
859
    actions = [directoryupdate]
860
    save_on_top = True
861
    affix = True
862
    fieldsets = (
863
        ('General', {
864
            'fields': (('company',
865
                        'enabled'),
866
                       ('name',
867
                        'registration'),
868
                       'max_calls',
869
                       'calls_per_second',
870
                       'codecs'),
871
            'description': 'General sip account informations'
872
        }),
873
        ('Registration settings', {
874
            'fields': (('password',
875
                        'multiple_registrations'),
876
                       'log_auth_failures'),
877
            'classes': ('collapsed',),
878
            'description': 'If registration, you must set a password'
879
        }),
880
        ('IP Settings', {
881
            'fields': (('sip_ip',
882
                        'sip_port'),
883
                       'rtp_ip'),
884
            'classes': ('collapsed',),
885
            'description': 'If no registration, SIP IP CIDR is needed'
886
        }),
887
        ('Description', {
888
            'fields': ('description',),
889
            'classes': ('collapsed',),
890
            'description': 'description informations'
891
        }),
892
        ('Advanced settings', {
893
            'fields': (('outbound_caller_id_name',
894
                        'outbound_caller_id_number'),
895
                       'ignore_early_media',
896
                       'fake_ring',
897
                       'cli_debug'),
898
            'classes': ('collapsed',),
899
            'description': 'Advanced parameters'
900
        }),
901
    )
902
903
    def get_registration_display(self, obj):
904
        if obj.registration:
905
            return mark_safe('<span class="label label-warning"><i class="icon-ok-sign"></i> Registration</span>')
906
        return mark_safe('<span class="label label-info"><i class="icon-minus-sign"></i> IP Auth</span>')
907
    get_registration_display.short_description = 'Registration'
908
    get_registration_display.admin_order_field = 'registration'
909
910
    def get_enabled_display(self, obj):
911
        if obj.enabled:
912
            return mark_safe('<span class="label label-success"><i class="icon-thumbs-up"></i> YES</span>')
913
        return mark_safe('<span class="label label-danger"><i class="icon-thumbs-down"></i> NO</span>')
914
    get_enabled_display.short_description = 'Enabled'
915
    get_enabled_display.admin_order_field = 'enabled'
916
917
    def get_fake_ring_display(self, obj):
918
        if obj.fake_ring:
919
            return mark_safe('<span class="label label-info"><i class="icon-thumbs-up"></i> YES</span>')
920
        return mark_safe('<span class="label label-danger"><i class="icon-thumbs-down"></i> NO</span>')
921
    get_fake_ring_display.short_description = 'Fake ring'
922
    get_fake_ring_display.admin_order_field = 'fake_ring'
923
    
924
    def get_cli_debug_display(self, obj):
925
        if obj.cli_debug:
926
            return mark_safe('<span class="label label-warning"><i class="icon-thumbs-up"></i> YES</span>')
927
        return mark_safe('<span class="label label-danger"><i class="icon-thumbs-down"></i> NO</span>')
928
    get_cli_debug_display.short_description = 'cli_debug'
929
    get_cli_debug_display.admin_order_field = 'cli_debug'
930
    
931
    def has_change_permission(self, request, obj=None):
932
        if request.user.is_superuser:
933
            return True
934
        else:
935
            return False
936
937
# VoipSwitch
938
939
940
class VoipSwitchAdmin(admin.ModelAdmin):
941
    list_display = ['name',
942
                    'ip',
943
                    'date_added',
944
                    'date_modified']
945
    ordering = ['name', ]
946
947
    def has_change_permission(self, request, obj=None):
948
        if request.user.is_superuser:
949
            return True
950
        else:
951
            return False
952
953
# SofiaGateway
954
955
956
class SofiaGatewayAdmin(admin.ModelAdmin):
957
    list_display = ['name',
958
                    'sip_profile',
959
                    'company',
960
                    'channels',
961
                    'proxy',
962
                    'get_enabled_display',
963
                    'get_register_display',
964
                    'date_added',
965
                    'date_modified']
966
    ordering = ['company',
967
                'name',
968
                'proxy']
969
    list_filter = ['company',
970
                   'proxy',
971
                   'enabled',
972
                   'sip_profile']
973
    search_fields = ['^company__name',
974
                     'proxy']
975
    actions = [sofiaupdate]
976
    
977
    def get_enabled_display(self, obj):
978
        if obj.enabled:
979
            return mark_safe('<span class="label label-success"><i class="icon-thumbs-up"></i> YES</span>')
980
        return mark_safe('<span class="label label-danger"><i class="icon-thumbs-down"></i> NO</span>')
981
    get_enabled_display.short_description = 'Enabled'
982
    get_enabled_display.admin_order_field = 'enabled'
983
984
    def get_register_display(self, obj):
985
        if obj.register:
986
            return mark_safe('<span class="label label-info"><i class="icon-thumbs-up"></i> ON</span>')
987
        return mark_safe('<span class="label label-danger"><i class="icon-thumbs-down"></i> OFF</span>')
988
    get_register_display.short_description = 'Register'
989
    get_register_display.admin_order_field = 'register'
990
991
    def has_change_permission(self, request, obj=None):
992
        if request.user.is_superuser:
993
            return True
994
        else:
995
            return False
996
997
998
class SipProfileAdmin(admin.ModelAdmin):
999
    list_display = ['name',
1000
                    'ext_sip_ip',
1001
                    'sip_ip',
1002
                    'sip_port',
1003
                    'auth_calls',
1004
                    'apply_inbound_acl',
1005
                    'disable_register',
1006
                    'log_auth_failures',
1007
                    'disable_transcoding',
1008
                    'date_modified']
1009
    ordering = ['name', ]
1010
    list_filter = ['sip_port', ]
1011
    search_fields = ['^name', ]
1012
    affix = True
1013
    fieldsets = (
1014
        ('Basic settings', {
1015
            'fields': (('name', 'sip_port'),
1016
                       ('sip_ip', 'rtp_ip'),
1017
                       ('ext_sip_ip', 'ext_rtp_ip')),
1018
            'description': 'General sip profile informations'
1019
        }),
1020
        # ('Media Related Options', {
1021
        #     'fields': (''),
1022
        #     'classes': ('collapsed',),
1023
        #     'description': 'Manage Media Related Options'
1024
        # }),
1025
        ('Codecs Related Options', {
1026
            'fields': ('disable_transcoding',
1027
                       ('inbound_codec_prefs', 'outbound_codec_prefs')),
1028
            'classes': ('collapsed',),
1029
            'description': 'Manage Codecs Related Options'
1030
        }),
1031
        ('NAT', {
1032
            'fields': ('aggressive_nat_detection',
1033
                       'NDLB_rec_in_nat_reg_c',
1034
                       'NDLB_force_rport',
1035
                       'NDLB_broken_auth_hash'),
1036
            'classes': ('collapsed',),
1037
            'description': 'NAT management'
1038
        }),
1039
        ('DTMF Related options', {
1040
            'fields': ('pass_rfc2833',),
1041
            'classes': ('collapsed',),
1042
            'description': 'DTMF management'
1043
        }),
1044
        ('SIP Related Options', {
1045
            'fields': (('enable_timer', 'session_timeout')),
1046
            'classes': ('collapsed',),
1047
            'description': 'Manage SIP Related Options'
1048
        }),
1049
        ('RTP Related Options', {
1050
            'fields': ('rtp_rewrite_timestamps',),
1051
            'classes': ('collapsed',),
1052
            'description': 'Manage RTP Related Options'
1053
        }),
1054
        ('Authentification Authorization', {
1055
            'fields': ('apply_inbound_acl',
1056
                       'auth_calls',
1057
                       'log_auth_failures'),
1058
            'classes': ('collapsed',),
1059
            'description': 'Authentification Authorization management'
1060
        }),
1061
        ('Registration', {
1062
            'fields': ('disable_register',
1063
                       'accept_blind_reg'),
1064
            'classes': ('collapsed',),
1065
            'description': 'Registration settings management'
1066
        }),
1067
        ('Others', {
1068
            'fields': ('user_agent',),
1069
            'classes': ('collapsed',),
1070
            'description': 'Others parameters'
1071
        }),
1072
    )
1073
1074
    def has_change_permission(self, request, obj=None):
1075
        if request.user.is_superuser:
1076
            return True
1077
        else:
1078
            return False
1079
1080
# AclLists
1081
1082
1083
class AclNodesAdminInline(admin.ModelAdmin):
1084
    list_display = ('company', 'cidr', 'policy', 'list')
1085
1086
1087
class AclListsAdmin(admin.ModelAdmin):
1088
    list_display = ('acl_name', 'default_policy')
1089
    ordering = ['acl_name', 'default_policy']
1090
    list_filter = ['default_policy', ]
1091
    inlines = [AclNodesAdminInline, ]
1092
1093
    def has_change_permission(self, request, obj=None):
1094
        if request.user.is_superuser:
1095
            return True
1096
        else:
1097
            return False
1098
1099
# AclNodes
1100
1101
1102
class AclNodesAdmin(admin.ModelAdmin):
1103
    list_display = ('company', 'cidr', 'policy', 'list')
1104
    ordering = ['company', 'policy', 'cidr']
1105
    list_filter = ['company', 'list']
1106
    search_fields = ['cidr', ]
1107
1108
    def has_change_permission(self, request, obj=None):
1109
        if request.user.is_superuser:
1110
            return True
1111
        else:
1112
            return False
1113
1114
# Hangup Cause
1115
1116
1117
class HangupCauseAdmin(ImportExportMixin, admin.ModelAdmin):
1118
    list_display = ('id', 'code', 'enumeration', 'cause', 'description')
1119
    search_fields = ('code', 'enumeration')
1120
1121
    def has_change_permission(self, request, obj=None):
1122
        if request.user.is_superuser:
1123
            return True
1124
        else:
1125
            return False
1126
1127
# CDR
1128
1129
1130
class TotalAveragesChangeList(ChangeList):
1131
1132
    def get_min_duration(self, sec_duration):
1133
        if sec_duration:
1134
            min = int(sec_duration / 60)
1135
            sec = int(sec_duration % 60)
1136
        else:
1137
            min = 0
1138
            sec = 0
1139
        return "%02d:%02d" % (min, sec)
1140
1141
    def get_results(self, *args, **kwargs):
1142
        super(TotalAveragesChangeList, self).get_results(*args, **kwargs)
1143
        self.total_sell_total = 0
1144
        self.total_cost_total = 0
1145
        try:
1146
            q = self.result_list.aggregate(total_sell_sum=Sum('total_sell'),
1147
                                           total_cost_sum=Sum('total_cost'),
1148
                                           effective_duration_sum=Sum('effective_duration'),
1149
                                           effective_duration_avg=Avg('effective_duration'))
1150
        except:
1151
            self.total_effective_duration = 0
1152
            self.total_cost_total = 0
1153
            self.total_sell_total = 0
1154
            self.avg_effective_duration = 0
1155
            self.margin = 0
1156
            return
1157
        self.total_effective_duration = q['effective_duration_sum']
1158
        self.total_cost_total = q['total_cost_sum']
1159
        self.total_sell_total = q['total_sell_sum']
1160
        self.avg_effective_duration = q['effective_duration_avg']
1161
        try:
1162
            self.margin = self.total_sell_total - self.total_cost_total
1163
        except:
1164
            self.margin = 0
1165
        self.min_avg_effective_duration = self.get_min_duration(q['effective_duration_avg'])
1166
        self.min_total_effective_duration = self.get_min_duration(q['effective_duration_sum'])
1167
1168
1169
class CDRAdmin(ExportMixin, admin.ModelAdmin):
1170
    search_fields = ['^prefix',
1171
                     '^destination_number',
1172
                     '^customer__name',
1173
                     '^cost_destination',
1174
                     '^sell_destination']
1175
    list_filter = ('start_stamp',)
1176
#    date_hierarchy = 'start_stamp'
1177
    change_list_template = 'admin/pyfreebill/cdr/change_list.html'
1178
    resource_class = CDRResourceExtra
1179
    fieldsets = (
1180
        ('General', {
1181
            'fields': ('customer',
1182
                       'start_stamp',
1183
                       'destination_number',
1184
                       ('min_effective_duration', 'billsec'),
1185
                       ('sell_destination', 'cost_destination'),
1186
                       'switchname')
1187
        }),
1188
        ('Advanced date / duration infos', {
1189
            'classes': ('collapse',),
1190
            'fields': (('answered_stamp',
1191
                        'end_stamp',
1192
                        'duration',
1193
                        'effectiv_duration'))
1194
        }),
1195
        ('Financial infos', {
1196
            'fields': (('total_cost', 'cost_rate'),
1197
                       ('total_sell', 'rate'),
1198
                       ('init_block', 'block_min_duration'))
1199
        }),
1200
        ('LCR infos', {
1201
            'classes': ('collapse',),
1202
            'fields': ('prefix',
1203
                       ('ratecard_id', 'lcr_group_id'),
1204
                       ('lcr_carrier_id', 'gateway'))
1205
        }),
1206
        ('Call detailed infos', {
1207
            'classes': ('collapse',),
1208
            'fields': ('caller_id_number',
1209
                       ('hangup_cause',
1210
                        'hangup_cause_q850',
1211
                        'hangup_disposition',
1212
                        'sip_hangup_cause'),
1213
                       ('read_codec', 'write_codec'),
1214
                       'sip_user_agent',
1215
                       'customer_ip',
1216
                       ('uuid', 'bleg_uuid', 'chan_name', 'country'))
1217
        }),
1218
    )
1219
1220
    def has_add_permission(self, request, obj=None):
1221
        return False
1222
1223
    def has_delete_permission(self, request, obj=None):
1224
        return False
1225
1226
    def get_actions(self, request):
1227
        if request.user.is_superuser:
1228
            return
1229
        else:
1230
            return
1231
1232
    def get_changelist(self, request, **kwargs):
1233
        return TotalAveragesChangeList
1234
1235
    def changelist_view(self, request, extra_context=None):
1236
        if request.user.is_superuser:
1237
            self.list_display_links = ['start_stamp', ]
1238
            return super(CDRAdmin, self).changelist_view(request,
1239
                                                         extra_context=None)
1240
        else:
1241
            self.list_display_links = ['None', ]
1242
            return super(CDRAdmin, self).changelist_view(request,
1243
                                                         extra_context=None)
1244
1245
    def get_ordering(self, request):
1246
        if request.user.is_superuser:
1247
            return ['-start_stamp', ]
1248
        else:
1249
            return ['-start_stamp', ]
1250
1251
    def get_list_display(self, request):
1252
        if request.user.is_superuser:
1253
            return ['start_stamp',
1254
                    'customer',
1255
                    'sell_destination',
1256
                    'destination_number',
1257
                    'min_effective_duration',
1258
                    'hangup_cause_colored',
1259
                    'lcr_carrier_id',
1260
                    'cost_rate',
1261
                    'rate',
1262
                    'prefix',
1263
                    'ratecard_id',
1264
                    'switchname']
1265
        else:
1266
            return ['start_stamp',
1267
                    'customer',
1268
                    'customer_ip',
1269
                    'sell_destination',
1270
                    'destination_number',
1271
                    'min_effective_duration',
1272
                    'hangup_cause',
1273
                    'rate',
1274
                    'total_sell']
1275
1276
    def get_list_filter(self, request):
1277
        if request.user.is_superuser:
1278
            return ['start_stamp', 'customer', 'lcr_carrier_id', 'ratecard_id']
1279
        else:
1280
            return ['start_stamp', 'sell_destination']
1281
1282
    def get_readonly_fields(self, request, obj=None):
1283
        if request.user.is_superuser:
1284
            return ['customer_ip',
1285
                    'customer',
1286
                    'caller_id_number',
1287
                    'destination_number',
1288
                    'start_stamp',
1289
                    'answered_stamp',
1290
                    'end_stamp',
1291
                    'duration',
1292
                    'min_effective_duration',
1293
                    'billsec',
1294
                    'hangup_cause',
1295
                    'hangup_cause_q850',
1296
                    'gateway',
1297
                    'lcr_carrier_id',
1298
                    'prefix',
1299
                    'country',
1300
                    'cost_rate',
1301
                    'total_cost',
1302
                    'total_sell',
1303
                    'rate',
1304
                    'init_block',
1305
                    'block_min_duration',
1306
                    'ratecard_id',
1307
                    'lcr_group_id',
1308
                    'uuid',
1309
                    'bleg_uuid',
1310
                    'chan_name',
1311
                    'read_codec',
1312
                    'write_codec',
1313
                    'sip_user_agent',
1314
                    'hangup_disposition',
1315
                    'effectiv_duration',
1316
                    'sip_hangup_cause',
1317
                    'sell_destination',
1318
                    'cost_destination',
1319
                    'switchname']
1320
        else:
1321
            return ['start_stamp',
1322
                    'customer',
1323
                    'customer_ip',
1324
                    'sell_destination',
1325
                    'destination_number',
1326
                    'min_effective_duration',
1327
                    'hangup_cause',
1328
                    'rate',
1329
                    'total_sell']
1330
1331
    def get_form(self, request, obj=None, **kwargs):
1332
        self.exclude = ['effectiv_duration',
1333
                        'effective_duration',
1334
                        'sip_rtp_rxstat',
1335
                        'sip_rtp_txstat',
1336
                        'switch_ipv4']
1337
        if not request.user.is_superuser:
1338
            self.exclude.append('cost_rate')
1339
            self.exclude.append('total_cost')
1340
            self.exclude.append('gateway')
1341
            self.exclude.append('switchname')
1342
            self.exclude.append('lcr_carrier_id')
1343
            self.exclude.append('lcr_group_id')
1344
            self.exclude.append('cost_destination')
1345
        return super(CDRAdmin, self).get_form(request, obj, **kwargs)
1346
1347
    def queryset(self, request):
1348
        today_c = date.today() - datetime.timedelta(days=settings.PFB_NB_CUST_CDR)
1349
        today_a = date.today() - datetime.timedelta(days=settings.PFB_NB_ADMIN_CDR)
1350
        user = getattr(request, 'user', None)
1351
        qs = super(CDRAdmin, self).queryset(request)
1352
        # add .prefetch_related('content_type') for reduce queries
1353
        if user.is_superuser:
1354
            return qs.filter(start_stamp__gte=today_a)
1355
        else:
1356
            usercompany = Person.objects.get(user=user)
1357
        return qs.filter(customer=usercompany.company).filter(start_stamp__gte=today_c).filter(effective_duration__gt="0")
1358
1359
    def get_export_formats(self):
1360
        format_csv = DEFAULT_FORMATS
1361
        return [f for f in format_csv if f().can_export()]
1362
1363
1364
class CarrierNormalizationRulesAdmin(admin.ModelAdmin):
1365
    list_display = ('company', 'prefix', 'remove_prefix', 'add_prefix')
1366
    ordering = ('company', 'prefix')
1367
    search_fields = ('^prefix',)
1368
1369
    def has_change_permission(self, request, obj=None):
1370
        if request.user.is_superuser:
1371
            return True
1372
        else:
1373
            return False
1374
1375
1376
class CustomerNormalizationRulesAdmin(admin.ModelAdmin):
1377
    list_display = ('company', 'prefix', 'remove_prefix', 'add_prefix')
1378
    ordering = ('company', 'prefix')
1379
    search_fields = ('^prefix',)
1380
1381
    def has_change_permission(self, request, obj=None):
1382
        if request.user.is_superuser:
1383
            return True
1384
        else:
1385
            return False
1386
1387
1388
class CarrierCIDNormalizationRulesAdmin(admin.ModelAdmin):
1389
    list_display = ('company', 'prefix', 'remove_prefix', 'add_prefix')
1390
    ordering = ('company',)
1391
1392
    def has_change_permission(self, request, obj=None):
1393
        if request.user.is_superuser:
1394
            return True
1395
        else:
1396
            return False
1397
1398
1399
class CustomerCIDNormalizationRulesAdmin(admin.ModelAdmin):
1400
    list_display = ('company', 'prefix', 'remove_prefix', 'add_prefix')
1401
    ordering = ('company',)
1402
1403
    def has_change_permission(self, request, obj=None):
1404
        if request.user.is_superuser:
1405
            return True
1406
        else:
1407
            return False
1408
1409
1410
class DestinationNumberRulesAdmin(admin.ModelAdmin):
1411
    list_display = ('prefix', 'format_num', 'description')
1412
    ordering = ('prefix',)
1413
1414
    def has_change_permission(self, request, obj=None):
1415
        if request.user.is_superuser:
1416
            return True
1417
        else:
1418
            return False
1419
1420
1421
class DimCustomerDestinationAdmin(admin.ModelAdmin):
1422
    list_display = ('date', 'customer', 'destination', 'total_calls', 'success_calls', 'total_duration', 'avg_duration', 'max_duration', 'min_duration', 'total_sell', 'total_cost')
1423
    readonly_fields = ('date', 'customer', 'destination', 'total_calls', 'success_calls', 'total_duration', 'avg_duration', 'max_duration', 'min_duration', 'total_sell', 'total_cost')
1424
    list_filter = ('date', 'customer', 'destination')
1425
    ordering = ('-date', 'customer', 'destination')
1426
1427
    def has_add_permission(self, request, obj=None):
1428
        return False
1429
1430
    def has_delete_permission(self, request, obj=None):
1431
        return False
1432
1433
1434
class DimProviderDestinationAdmin(admin.ModelAdmin):
1435
    list_display = ('date', 'provider', 'destination', 'total_calls', 'success_calls', 'total_duration', 'avg_duration', 'max_duration', 'min_duration', 'total_sell', 'total_cost')
1436
    readonly_fields = ('date', 'provider', 'destination', 'total_calls', 'success_calls', 'total_duration', 'avg_duration', 'max_duration', 'min_duration', 'total_sell', 'total_cost')
1437
    list_filter = ('date', 'provider', 'destination')
1438
    ordering = ('-date', 'provider', 'destination')
1439
#    list_display = ('get_day_stats',)
1440
1441
    def has_add_permission(self, request, obj=None):
1442
        return False
1443
1444
    def has_delete_permission(self, request, obj=None):
1445
        return False
1446
1447
1448
class LogEntryAdmin(admin.ModelAdmin):
1449
    """ based on djangosnippets.org/snippets/2484/ """
1450
    date_hierarchy = 'action_time'
1451
    readonly_fields = LogEntry._meta.get_all_field_names() + \
1452
        ['object_link', 'action_description']
1453
    list_filter = [
1454
        'user',
1455
        'content_type',
1456
        'action_flag'
1457
    ]
1458
    search_fields = [
1459
        'object_repr',
1460
        'change_message'
1461
    ]
1462
    list_display = [
1463
        'action_time',
1464
        'user',
1465
        'content_type',
1466
        'object_link',
1467
        'action_flag',
1468
        'action_description',
1469
        'change_message',
1470
    ]
1471
1472
    def has_add_permission(self, request):
1473
        return False
1474
1475
    def has_change_permission(self, request, obj=None):
1476
        return request.user.is_superuser and request.method != 'POST'
1477
1478
    def has_delete_permission(self, request, obj=None):
1479
        return False
1480
1481
    def object_link(self, obj):
1482
        if obj.action_flag == DELETION:
1483
            link = escape(obj.object_repr)
1484
        else:
1485
            ct = obj.content_type
1486
            link = u'<a href="%s">%s</a>' % (
1487
                reverse('admin:%s_%s_change' % (ct.app_label, ct.model), args=[obj.object_id]),
1488
                escape(obj.object_repr),
1489
            )
1490
        return link
1491
    object_link.allow_tags = True
1492
    object_link.admin_order_field = 'object_repr'
1493
    object_link.short_description = u'object'
1494
1495
    def action_description(self, obj):
1496
        action_names = {
1497
            ADDITION: 'Addition',
1498
            DELETION: 'Deletion',
1499
            CHANGE: 'Change',
1500
        }
1501
        return action_names[obj.action_flag]
1502
    action_description.short_description = 'Action'
1503
1504
#    admin.site.disable_action('delete_selected')
1505
1506
#----------------------------------------
1507
# register
1508
#----------------------------------------
1509
admin_site.register(Company, CompanyAdmin)
1510
admin_site.register(Person, PersonAdmin)
1511
admin_site.register(Group, GroupAdmin)
1512
admin_site.register(CompanyBalanceHistory, CompanyBalanceHistoryAdmin)
1513
admin_site.register(CalleridPrefix, CalleridPrefixAdmin)
1514
admin_site.register(CalleridPrefixList, CalleridPrefixListAdmin)
1515
admin_site.register(ProviderTariff, ProviderTariffAdmin)
1516
admin_site.register(ProviderRates, ProviderRatesAdmin)
1517
admin_site.register(LCRGroup, LCRGroupAdmin)
1518
#admin.site.register(LCRProviders, LCRProvidersAdmin)
1519
admin_site.register(RateCard, RateCardAdmin)
1520
admin_site.register(CustomerRates, CustomerRatesAdmin)
1521
admin_site.register(CustomerRateCards, CustomerRateCardsAdmin)
1522
admin_site.register(CustomerDirectory, CustomerDirectoryAdmin)
1523
#admin_site.register(AclLists, AclListsAdmin)
1524
#admin.site.register(AclNodes, AclNodesAdmin)
1525
#admin.site.register(VoipSwitch, VoipSwitchAdmin)
1526
admin_site.register(SipProfile, SipProfileAdmin)
1527
admin_site.register(SofiaGateway, SofiaGatewayAdmin)
1528
#admin.site.register(HangupCause, HangupCauseAdmin)
1529
admin_site.register(CDR, CDRAdmin)
1530
admin_site.register(CarrierNormalizationRules, CarrierNormalizationRulesAdmin)
1531
admin_site.register(CustomerNormalizationRules,
1532
                    CustomerNormalizationRulesAdmin)
1533
admin_site.register(CarrierCIDNormalizationRules,
1534
                    CarrierCIDNormalizationRulesAdmin)
1535
admin_site.register(CustomerCIDNormalizationRules,
1536
                    CustomerCIDNormalizationRulesAdmin)
1537
admin_site.register(DestinationNumberRules, DestinationNumberRulesAdmin)
1538
#admin.site.register(DimCustomerHangupcause, DimCustomerHangupcauseAdmin)
1539
#admin.site.register(DimCustomerSipHangupcause, DimCustomerSipHangupcauseAdmin)
1540
#admin.site.register(DimProviderHangupcause, DimProviderHangupcauseAdmin)
1541
#admin.site.register(DimProviderSipHangupcause, DimProviderSipHangupcauseAdmin)
1542
admin_site.register(DimCustomerDestination, DimCustomerDestinationAdmin)
1543
admin_site.register(DimProviderDestination, DimProviderDestinationAdmin)
1544
admin_site.register(LogEntry, LogEntryAdmin)
1545