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 +++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) (limited to 'app/dispatch/misc.py') 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) -- cgit v1.2.3