From 78437d6f8afd75544a94d033ee4fb38dfe7c1914 Mon Sep 17 00:00:00 2001 From: Mitch Riedstra Date: Tue, 23 Jan 2018 18:51:57 -0500 Subject: Move paperwork download code out into a function and add ability to download paperwork for users --- app/dispatch/misc.py | 38 ++++++++++++++- .../templates/dispatch/drivers/summary.html | 3 ++ app/dispatch/urls.py | 1 + app/dispatch/views.py | 56 ++++++++-------------- 4 files changed, 62 insertions(+), 36 deletions(-) (limited to 'app/dispatch') diff --git a/app/dispatch/misc.py b/app/dispatch/misc.py index e0976bf..42b00d3 100644 --- a/app/dispatch/misc.py +++ b/app/dispatch/misc.py @@ -1,7 +1,7 @@ from django.utils import formats from datetime import datetime, timedelta from dateutil import rrule -import uuid +import uuid, tempfile, zipfile, os # Text formatted date. *sigh* def get_week_dates(date=None): @@ -41,3 +41,39 @@ def paperwork_user_directory_path(instance, filename): return 'paperwork/{:d}/'.format(instance.load.pk) + \ str(uuid.uuid4())[0:9] + filename + +def zip_attachments_for_loads(loads, pre_append, date): + td = tempfile.TemporaryDirectory() + zip_file_basename = pre_append + '-' + \ + date.strftime('%m.%d.%Y') + \ + '.zip' + zip_file_name = td.name + '/' + zip_file_basename + z = zipfile.ZipFile(zip_file_name, 'w') + + for l in loads: + for p in l.paperwork_set.all(): + + if os.path.exists(p.document.path): + try: + exp = re.compile('\.[^.]*$', re.IGNORECASE) + ext = exp.findall(p.document.path) + ext = ext[0] + except Exception as e: + print(e) + ext = '.pdf' + + desc = l.description.replace('"', '') + + # Get the name for the zip file + zipname = desc + '-' + l.user.identity.name + ext + + z.write(p.document.path, zipname) + # print(p.document) + + # Finally close off the zip file + z.close() + + + fh = open(zip_file_name, 'rb') + + return (zip_file_basename, fh) diff --git a/app/dispatch/templates/dispatch/drivers/summary.html b/app/dispatch/templates/dispatch/drivers/summary.html index 4c24fc9..82df917 100644 --- a/app/dispatch/templates/dispatch/drivers/summary.html +++ b/app/dispatch/templates/dispatch/drivers/summary.html @@ -15,6 +15,9 @@
+ {% if request.user.is_superuser %} + Download Paperwork + {% endif %} {% if can_invoice %} Generate Invoice For Listing {% else %} diff --git a/app/dispatch/urls.py b/app/dispatch/urls.py index 330dd05..046acee 100644 --- a/app/dispatch/urls.py +++ b/app/dispatch/urls.py @@ -14,6 +14,7 @@ urlpatterns = [ url(r'^drivers/summary/(?P\d+)$', views.DriverSummary.as_view(), name='driver_summary'), url(r'^drivers/view/(?P\d+)$', views.DriverDetail.as_view(), name='driver_details'), url(r'^drivers/edit/(?P\d+)$', views.DriverUpdate.as_view(), name='driver_edit'), + url(r'^drivers/download/(?P\d+)$', views.DriverDownload, name='driver_download'), url(r'^drivers/(?P\d+)/identity/(?P\d+)$', views.IdentityDetail.as_view(), name='identity_detail'), url(r'^drivers/(?P\d+)/identity/new/$', views.IdentityCreate.as_view(), name='identity_create'), diff --git a/app/dispatch/views.py b/app/dispatch/views.py index ef5bad8..f01cb31 100644 --- a/app/dispatch/views.py +++ b/app/dispatch/views.py @@ -18,8 +18,8 @@ from dispatch.forms import AddPaperworkForm, InviteForm from django.contrib.auth import get_user_model from django.contrib.auth.mixins import UserPassesTestMixin # from django.http import HttpResponseRedirect -from .misc import get_week_dates, split_loads_by_day -import re, os, tempfile, datetime, shutil, zipfile +from .misc import get_week_dates, split_loads_by_day, zip_attachments_for_loads +import re, os, tempfile, datetime User = get_user_model() @@ -156,8 +156,6 @@ class DriverSummary(UserPassesTestMixin, LoadDateSort): stats['sum'] += l.amount # Any load not up to par will break the chain - print(l) - print(l.can_invoice()) if not l.can_invoice(): context['can_invoice'] = False @@ -235,57 +233,45 @@ def CustomerDownload(request, pk): customer = Customer.objects.get(pk=pk) week_dates = get_week_dates(request.GET.get('date', None)) - td = tempfile.TemporaryDirectory() - zip_file_basename = customer.name + '-' + \ - week_dates['start_date'].strftime('%m.%d.%Y') + \ - '.zip' - zip_file_name = td.name + '/' + zip_file_basename - print(zip_file_name) - z = zipfile.ZipFile(zip_file_name, 'w') - loads = customer.load_set.filter( date__range=(week_dates['start_date'], week_dates['end_date'])) + basename, fh = zip_attachments_for_loads(loads, customer.name, week_dates['start_date']) - for l in loads: - for p in l.paperwork_set.all(): - - if os.path.exists(p.document.path): - try: - exp = re.compile('\.[^.]*$', re.IGNORECASE) - ext = exp.findall(p.document.path) - ext = ext[0] - except Exception as e: - print(e) - ext = '.pdf' - - desc = l.description.replace('"', '') + response = HttpResponse( + fh.read(), + content_type='application/force-download') - # Get the name for the zip file - zipname = desc + '-' + l.user.identity.name + ext + response['Content-Disposition'] = \ + 'attachment; filename="{}"'.format(smart_str(basename)) + response['X-Sendfile'] = smart_str(fh) - z.write(p.document.path, zipname) - # print(p.document) + print('%r' % response) + return response - # Finally close off the zip file - z.close() +def DriverDownload(request, pk): + print(dir(request)) + user = User.objects.get(pk=pk) + week_dates = get_week_dates(request.GET.get('date', None)) + loads = user.load_set.filter( + date__range=(week_dates['start_date'], + week_dates['end_date'])) - fh = open(zip_file_name, 'rb') + basename, fh = zip_attachments_for_loads(loads, user.identity.name, week_dates['start_date']) response = HttpResponse( fh.read(), content_type='application/force-download') response['Content-Disposition'] = \ - 'attachment; filename="{}"'.format(smart_str(zip_file_basename)) + 'attachment; filename="{}"'.format(smart_str(basename)) response['X-Sendfile'] = smart_str(fh) - print('%r' % response) + # print('%r' % response) return response - class CustomerUpdate(UserPassesTestMixin, UpdateView): template_name = "dispatch/companies/edit.html" model = Customer -- cgit v1.2.3