Advertisement
Guest User

Untitled

a guest
May 23rd, 2017
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.17 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. from functools import update_wrapper
  3. from django.conf.urls import url
  4. from django.contrib import admin
  5. from django.utils import timezone
  6. import hashlib
  7. from django.contrib import messages
  8. from .models import Users, App_types, Teams, account_types, Configuration
  9. from actions import export_as_csv_action
  10. from django.http import HttpResponse, HttpResponseRedirect
  11. from django.template import RequestContext
  12. from django.shortcuts import render
  13. from .forms import NameForm
  14. from django.core.mail import send_mail
  15. import datetime
  16.  
  17.  
  18. class taxidrivers_Admin(admin.ModelAdmin):
  19.     change_list_template = 'change_list.html'
  20.     quick_add_template = 'quick_driver_add.html'
  21.     list_display = ('get_code_id', 'get_driver_name','is_active', 'last_update', 'position', 'speed', 'account_type', 'latency', 'client', 'client_version', 'driver_state', 'expiration_date')
  22.     search_fields = ('name', 'surname', 'code_id')
  23.     list_filter = ('last_update','account_type', 'driver_state', 'client', 'client_version','entry_date','expiration_date')
  24.     actions = ['activate_pro','activate_basic']
  25.     #fieldsets = (
  26.     #    (None, {
  27.     #        'fields': ('name', 'surname', 'last_update', 'position')
  28.     #    }),
  29.     #    ('Advanced options', {
  30.     #        'classes': ('collapse',),
  31.     #        'fields': ('speed', 'latency'),
  32.     #    }),
  33.     #)
  34.     #filter_horizontal = ('client',)
  35.     def get_code_id(self, obj):
  36.         if obj.code_id == -1:
  37.             id = -1
  38.         else:
  39.             id = obj.code_id + 200
  40.         return id
  41.     get_code_id.short_description = 'CODE ID' # Set the Header label of the results in list
  42.     get_code_id.admin_order_field = 'code_id'
  43.     def is_expired(self, obj):
  44.         if obj.expiration_date > timezone.now():
  45.             return True
  46.         else:
  47.             return False
  48.     is_expired.short_description = 'Expired'  
  49.     is_expired.boolean = True
  50.  
  51.     def get_driver_name(self, obj):
  52.         return u'%s %s ' % (obj.surname, obj.name)
  53.     get_driver_name.short_description = 'Driver Name' # Set the Header label of the results in list
  54.     get_driver_name.admin_order_field = 'surname' # If the get_code_id expression is complex this variable tells which property to use for sorting
  55.  
  56.     def is_active(self, obj):
  57.         if obj.code_id == -1:
  58.             return False
  59.         else:
  60.             return True
  61.     is_active.boolean = True
  62.  
  63.     def get_urls(self):
  64.         def wrap(view):
  65.             def wrapper(*args, **kwargs):
  66.                 return self.admin_site.admin_view(view)(*args, **kwargs)
  67.             wrapper.model_admin = self
  68.             return update_wrapper(wrapper, view)
  69.  
  70.         urls = super(taxidrivers_Admin,self).get_urls()
  71.  
  72.         info = self.model._meta.app_label, self.model._meta.model_name
  73.  
  74.         my_urls = [            
  75.             url(r'^quick_add_driver/$', wrap(self.quick_add_driver), name='%s_%s_quick_add_driver' % info),
  76.             url(r'^download_as_xls/$', self.download_as_xls_view),            
  77.         ]
  78.         return my_urls + urls
  79.        
  80.     def quick_add_driver(self, request):    
  81.         if request.method == 'POST':
  82.             # create a form instance and populate it with data from the request:
  83.             form = NameForm(request.POST)
  84.             # check whether it's valid:
  85.             if form.is_valid():
  86.                 driver = form.save(commit=False)
  87.                 all_drivers = Users.objects.order_by('code_id').all()
  88.                 tmp_code_id = 0
  89.                
  90.                 for e in all_drivers:
  91.                     if(e.code_id == -1):
  92.                         continue
  93.                     if(tmp_code_id == e.code_id):
  94.                         tmp_code_id += 1
  95.                     else:
  96.                         driver.code_id = tmp_code_id
  97.                         break  
  98.                        
  99.                 m = hashlib.md5()
  100.                 m.update(driver.real_password)
  101.                 driver.password = m.hexdigest()
  102.                 driver.save()
  103.                 send_email(form.data['client'], driver, 'ACTIVATE')
  104.                 if '_save' in form.data:
  105.                     return HttpResponseRedirect('../')
  106.                 elif '_addanother' in form.data:
  107.                     form = NameForm()
  108.                 elif '_continue' in form.data:
  109.                     form = form
  110.                 # process the data in form.cleaned_data as required
  111.                 # ...
  112.                 # redirect to a new URL:
  113.                 #return HttpResponseRedirect('../')
  114.  
  115.         # if a GET (or any other method) we'll create a blank form
  116.         else:
  117.             form = NameForm()
  118.  
  119.         context = {'title': 'Add TaxiDriver',
  120.                     'opts': Users._meta,
  121.                     'change': False,
  122.                     'add': True,
  123.                     'obj': None,
  124.                     'is_popup': False,
  125.                     'save_as': True,
  126.                     'has_delete_permission': False,
  127.                     'has_add_permission': True,
  128.                     'has_change_permission': True,
  129.                     'form': form,
  130.                     }
  131.  
  132.         return render(request, self.quick_add_template, context)
  133.  
  134.     def activate_basic(self, request, queryset):
  135.         all_drivers = Users.objects.order_by('code_id').all()
  136.         for td in queryset:
  137.             if td.code_id == -1:
  138.                 tmp_code_id = 0
  139.  
  140.                 for e in all_drivers:
  141.                     if e.code_id == -1:
  142.                         continue
  143.                     if tmp_code_id == e.code_id:
  144.                         tmp_code_id += 1
  145.                     else:
  146.                         td.code_id = tmp_code_id
  147.                         break
  148.                 td.client = App_types.objects.get(pk=0)  # For Basic
  149.                 td.expiration_date = datetime.datetime.now() + datetime.timedelta(days=35)  # Activate for 35 days
  150.                 td.save()
  151.                 send_email('0', td, 'ACTIVATE')
  152.             else:
  153.                 messages.add_message(request, messages.WARNING, 'TaxiDriver (%s) %s %s is already active' % (td.code_id + 200, td.name, td.surname))
  154.                 return
  155.  
  156.         self.message_user(request, "TaxiDrivers Successfully activated as BASIC")
  157.             # queryset.update(status='p')
  158.  
  159.     activate_basic.short_description = "Activate TaxiDrivers for BASIC"
  160.  
  161.     def activate_pro(self, request, queryset):
  162.         all_drivers = Users.objects.order_by('code_id').all()
  163.  
  164.         for td in queryset:
  165.             if td.code_id == -1:
  166.                 tmp_code_id = 0
  167.  
  168.                 for e in all_drivers:
  169.                     if e.code_id == -1:
  170.                         continue
  171.                     if tmp_code_id == e.code_id:
  172.                         tmp_code_id += 1
  173.                     else:
  174.                         td.code_id = tmp_code_id
  175.                         break
  176.                 td.client = App_types.objects.get(pk=1)  # For PRO
  177.                 td.expiration_date = datetime.datetime.now() + datetime.timedelta(days=35)  # Activate for 35 days
  178.                 td.save()
  179.                 send_email('1', td, 'ACTIVATE')
  180.             else:
  181.                 messages.add_message(request, messages.WARNING, 'TaxiDriver (%s) %s %s is already active' % (td.code_id + 200, td.name, td.surname))
  182.                 return
  183.         self.message_user(request, "TaxiDrivers Successfully activated as PRO")
  184.  
  185.     activate_pro.short_description = "Activate TaxiDrivers for PRO"
  186.  
  187.     def download_as_xls_view(self, request):
  188.         """Generates an xls file
  189.        """
  190.  
  191.         response = HttpResponse(mimetype='application/ms-excel')
  192.         response['Content-Disposition'] = \
  193.             'attachment; filename=Report.xls'
  194.         # do something
  195.         return response
  196.  
  197.  
  198. def send_email(client_type, driver, action):
  199.     mail_addresses = []
  200.     if action == 'NEW':
  201.         title = u'Νέος Οδηγός'
  202.     if action == 'ACTIVATE':
  203.         title = u'Ενεργοποίηση Οδηγού'
  204.     if client_type == '0':
  205.         title += u' Basic (%s %s) ' % (driver.surname, driver.name)
  206.         link = u'\n\nLink Taxiplus Basic: http://basic.taxiplus.gr'
  207.     elif client_type == '1':
  208.         title += u' Pro (%s %s) ' % (driver.surname, driver.name)
  209.         link = u'\n\nLink Taxiplus Pro: http://pro.taxiplus.gr'
  210.     elif client_type == '2':
  211.         title = u'Νέος Χρήστης Contacts (%s %s) ' % (driver.surname, driver.name)
  212.         link = u'\n\nLink Taxiplus Contacts: http://api.taxiplus.gr/updates/TaxiplusContacts.apk'
  213.     elif client_type == '3':
  214.         title = u'Νέος Πελάτης (%s %s) ' % (driver.surname, driver.name)
  215.         link = u'\n\nLink Taxiplus Customer: http://api.taxiplus.gr/updates/TaxiplusCustomer.apk'
  216.  
  217.     body = u'Στοιχεία Οδηγού:\n------------------------------\nΌνομα: %s\nΕπώνυμο: %s\nΟμάδα: %s\nUsername: %s\nPassword: %s\n\n%s\n\n\nΜε εκτίμηση,\nTaxiplus Team' % (driver.name, driver.surname, driver.team.team_name, driver.username, driver.real_password, link)
  218.  
  219.     su_email = Users.objects.get(pk=0).email.split(',')[0].split(':')[1].strip()
  220.     mail_addresses.append(su_email)  # Get the email address of the SU of the system
  221.     taxiplus_support_mail = Configuration.objects.get(parameter='TAXIPLUS_SUPPORT_EMAIL').value.strip()
  222.     mail_addresses.append(taxiplus_support_mail)  # Get the email address of TAXIPLUS_SUPPORT
  223.  
  224.     # Send Mail to Team Leader
  225.     team_leader_mail = Users.objects.get(pk=Teams.objects.get(pk=driver.team.id).leader.id).email.split(',')[0].split(':')[1].strip()  # Get the email address of the team leader of the driver
  226.     if team_leader_mail != taxiplus_support_mail:
  227.         mail_addresses.append(team_leader_mail)
  228.  
  229.     driver_email = driver.email.split(',')[0].split(':')[1].strip()
  230.     if driver_email:
  231.         mail_addresses.append(driver_email)  # Add the email address of the driver
  232.  
  233.     send_mail(
  234.         title,
  235.         body,
  236.         'support@taxiplus.gr',
  237.         mail_addresses,
  238.         fail_silently=False,
  239.     )
  240.  
  241.  
  242. admin.site.register(Users, taxidrivers_Admin)
  243. admin.site.register(App_types)
  244. admin.site.register(Teams)
  245. admin.site.register(account_types)
  246. admin.site.register(Configuration)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement