Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sign the pdf #150

Merged
merged 2 commits into from
Jan 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions backend/donations/models/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,26 @@ def select_public_storage():
return storages["public"]


def ngo_directory_path(subdir, instance, filename) -> str:
ngo_code: str = hashlib.sha1(f"ngo-{instance.pk}-{settings.SECRET_KEY}".encode()).hexdigest()
def _id_code(prefix: str, id: int) -> str:
return hashlib.sha1(f"{prefix}-{id}-{settings.SECRET_KEY}".encode()).hexdigest()[:10]


def ngo_directory_path(subdir, instance, filename) -> str:
# file will be uploaded to MEDIA_ROOT/ngo-<id>-<hash>/<subdir>/<filename>
return "ngo-{0}-{1}/{2}/{3}".format(instance.pk, ngo_code[:10], subdir, filename)
return "ngo-{0}-{1}/{2}/{3}".format(instance.pk, _id_code("ngo", instance.pk), subdir, filename)


def year_directory_path(subdir, instance, filename) -> str:
timestamp = timezone.now()
return "{0}/{1}/{2}/{3}".format(subdir, timestamp.date().year, instance.pk, filename)
return "{0}/ngo-{1}-{2}/{3}/{4}_{5}_{6}".format(
timestamp.date().year,
instance.ngo.pk,
_id_code("ngo", instance.pk),
subdir,
instance.pk,
_id_code("donor", instance.pk),
filename,
)


def ngo_slug_validator(value):
Expand Down Expand Up @@ -239,7 +249,7 @@ class Donor(models.Model):
verbose_name=_("PDF file"),
blank=True,
null=False,
upload_to=partial(year_directory_path, "documents"),
upload_to=partial(year_directory_path, "forms"),
)

date_created = models.DateTimeField(verbose_name=_("date created"), db_index=True, auto_now_add=timezone.now)
Expand Down
4 changes: 2 additions & 2 deletions backend/donations/pdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import os
import tempfile
from datetime import datetime
from io import BytesIO, StringIO
from io import BytesIO
from typing import Dict

from pypdf import PdfReader, PdfWriter
Expand Down Expand Up @@ -241,7 +241,7 @@ def create_pdf(person: Dict, ong: Dict):


def add_signature(pdf, image):
pdf_string = StringIO(pdf)
pdf_string = BytesIO(pdf)
existing_pdf = PdfReader(pdf_string)

packet = tempfile.TemporaryFile(mode="w+b")
Expand Down
83 changes: 60 additions & 23 deletions backend/donations/views/ngo.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import re
from datetime import date
from hashlib import sha1
from urllib.parse import urlparse

from django.conf import settings
Expand All @@ -12,7 +11,7 @@

from .base import BaseHandler
from ..models.main import Donor, Ngo
from ..pdf import create_pdf
from ..pdf import create_pdf, add_signature


class DonationSucces(BaseHandler):
Expand Down Expand Up @@ -58,25 +57,75 @@ def get(self, request, ngo_url):
class FormSignature(BaseHandler):
template_name = "signature.html"

def get_context_data(self, ngo_url, **kwargs):
context = super().get_context_data(**kwargs)

def get_ngo_and_donor(self, request, ngo_url):
ngo_url = ngo_url.lower().strip()
try:
ngo = Ngo.objects.get(slug=ngo_url)
except Ngo.DoesNotExist:
ngo = None
raise Http404

context["ngo"] = ngo
return context
try:
donor_id = int(request.session.get("donor_id", 0))
except ValueError:
donor_id = 0

if not donor_id:
return False

try:
donor = Donor.objects.get(id=donor_id)
except Donor.DoesNotExist:
request.session.pop("donor_id", None)
return False

self.ngo = ngo
self.donor = donor
return True

def get(self, request, ngo_url):
context = self.get_context_data(ngo_url)
if not self.get_ngo_and_donor(request, ngo_url):
return redirect(reverse("twopercent", kwargs={"ngo_url": ngo_url}))

if not request.session.get("signature_required", False):
return redirect(reverse("twopercent", kwargs={"ngo_url": ngo_url}))

context = {
"ngo": self.ngo,
"title": "Donație - semnătura",
"donor": self.donor,
}

return render(self.request, self.template_name, context)

def post(self, request, ngo_url):
# context = self.get_context_data(ngo_url)
if not self.get_ngo_and_donor(request, ngo_url):
return redirect(reverse("twopercent", kwargs={"ngo_url": ngo_url}))

signature_image = request.POST.get("signature", None)

if not signature_image:
return redirect(reverse("ngo-twopercent-signature", kwargs={"ngo_url": ngo_url}))

# add the image to the PDF
with self.donor.pdf_file.open("rb") as pdf:
new_pdf = add_signature(pdf.read(), signature_image)

# delete the unsigned pdf
self.donor.pdf_file.delete()
self.donor.pdf_file = None

self.donor.pdf_file.save("declaratia_completata.pdf", File(new_pdf))
new_pdf.close()

# # TODO: Send email
# self.send_email("signed-form", self.donor)
# self.send_email("ngo-signed-form", self.donor, self.ngo)

request.session.pop("signature_required", None)
self.donor.has_signed = True
# TODO: Get rid of pdf_url
self.donor.pdf_url = self.donor.pdf_file.url
self.donor.save()

return redirect(reverse("ngo-twopercent-success", kwargs={"ngo_url": ngo_url}))

Expand Down Expand Up @@ -257,19 +306,7 @@ def get_post_value(arg, add_to_error_list=True):
# self.return_error(errors)
# return

# TODO
# the user's folder name, it's just his md5 hashed db id
# user_folder = security.hash_password('123', "md5")
user_folder = "123123"

# a way to create unique file names
# get the local time in iso format
# run that through SHA1 hash
# output a hex string
filename = "{0}/{1}/{2}.pdf".format(
settings.USER_FORMS, str(user_folder), sha1(timezone.now().isoformat().encode("utf8")).hexdigest()
)

filename = "filled_form.pdf"
pdf = create_pdf(donor_dict, ngo_data)

# create the donor and save it
Expand Down
2 changes: 1 addition & 1 deletion backend/templates/v1/succes.html
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

<div class="row">
<div class="col-xs-12 col-md-8 col-md-offset-2 text-center">
<a href="{{ donor.pdf_url }}" class="btn btn-primary btn-lg ngo-form-url" download="Formular_donatie_2%.pdf" target="_blank">
<a href="{{ donor.pdf_file.url }}" class="btn btn-primary btn-lg ngo-form-url" download="Formular_donatie_2%.pdf" target="_blank">
Descarcă formularul tău
</a>
</div>
Expand Down
Loading