Skip to content

Commit

Permalink
Adds possibility to download a PDF for a télédéclaration
Browse files Browse the repository at this point in the history
  • Loading branch information
alemangui committed Aug 31, 2021
1 parent 5824d2d commit cbde7b3
Show file tree
Hide file tree
Showing 7 changed files with 211 additions and 6 deletions.
81 changes: 81 additions & 0 deletions api/templates/teledeclaration_pdf.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
{% load static %}
<html>
<head>
<style>
@font-face {
font-family: 'Marianne';
src: url({% static '../../web/static/fonts/Marianne-Regular.ttf' %}) format('truetype');
}
@font-face {
font-family: 'Marianne-Bold';
src: url({% static '../../web/static/fonts/Marianne-Bold.ttf' %}) format('truetype');
}
@font-face {
font-family: 'Marianne-ExtraBold';
src: url({% static '../../web/static/fonts/Marianne-ExtraBold.ttf' %}) format('truetype');
}
body {
font-family: 'Marianne', Arial, Helvetica, sans-serif;
}
h1 {
font-family: 'Marianne-ExtraBold';
font-size: 24px;
margin: 32px 0px 16px 0px;
}
h2 {
font-family: 'Marianne-Bold';
font-size: 16px;
margin: 16px 0px;
}
h3 {
font-family: 'Marianne-Bold';
}
li span {
font-family: 'Marianne-Bold';
}
p, li {
margin: 16px 0px;
}
.image-container {
background-color:#0c7f46;
padding: 16px;
}
</style>
</head>
<body>
<div class="image-container">
<img src="{% static '../../web/static/images/logo_transparent_white.png' %}" alt="ma cantine" height="30" width="142" />
</div>
<h1>Justificatif pour télédéclaration {{ year }}</h1>
<h2>Cantine {{ canteen_name }} (SIRET {{ siret }})</h2>
<h3>Télédéclaration faite le {{ date|date:"l m F Y" }} par {{ applicant }}</h3>

<p>
Conformément à l’article 24 de la loi EGAlim, chaque établissement est tenu de
renseigner et transmettre à l’administration ses données, notamment en termes
d’approvisionnement sur l’année civile passée.
</p>
<p>
Pour l'année {{ year }}, les données suivantes ont été télédéclarées le
{{ date|date:"l m F Y" }} via la plateforme numérique ma cantine :
</p>
<ul>
<li>
<span>Valeur totale en HT des achats alimentaires</span> : {{ value_total_ht|floatformat:2 }} €
</li>
<li>
<span>Valeur en HT des achats alimentaires en Bio</span> : {{ value_bio_ht|floatformat:2 }} €
</li>
<li>
<span>Valeur en HT d'autres produits de qualité et durables</span> : {{ value_sustainable_ht|floatformat:2 }} €
</li>
<li>
<span>Valeur en HT des produits issus du commerce équitable</span> : {{ value_fair_trade_ht|floatformat:2 }} €
</li>
</ul>

<hr />

En savoir plus de la loi EGAlim : https://ma-cantine.beta.gouv.fr/
</body>
</html>
7 changes: 6 additions & 1 deletion api/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from api.views import BlogPostsView, SectorListView, ChangePasswordView, BlogPostView
from api.views import AddManagerView, RemoveManagerView, PublishedCanteenSingleView
from api.views import ImportDiagnosticsView, TeledeclarationCreateView
from api.views import TeledeclarationCancelView
from api.views import TeledeclarationCancelView, TeledeclarationPdfView


urlpatterns = {
Expand Down Expand Up @@ -75,6 +75,11 @@
TeledeclarationCancelView.as_view(),
name="teledeclaration_cancel",
),
path(
"teledeclaration/<int:pk>/document.pdf",
TeledeclarationPdfView.as_view(),
name="teledeclaration_pdf",
),
}

urlpatterns = format_suffix_patterns(urlpatterns)
1 change: 1 addition & 0 deletions api/views/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,5 @@
from .teledeclaration import ( # noqa: F401
TeledeclarationCreateView,
TeledeclarationCancelView,
TeledeclarationPdfView,
)
108 changes: 106 additions & 2 deletions api/views/teledeclaration.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
import logging
from django.http import JsonResponse
import os
from django.http import JsonResponse, HttpResponse
from django.core.exceptions import ValidationError as DjangoValidationError
from django.template.loader import get_template
from django.contrib.staticfiles import finders
from django.conf import settings
from rest_framework import status, permissions
from rest_framework.views import APIView
from rest_framework.exceptions import ValidationError, PermissionDenied
from django.core.exceptions import ValidationError as DjangoValidationError
from xhtml2pdf import pisa
from data.models import Diagnostic, Teledeclaration
from api.serializers import FullDiagnosticSerializer
from .utils import camelize
Expand Down Expand Up @@ -82,3 +87,102 @@ def post(self, request):

except Teledeclaration.DoesNotExist:
raise ValidationError("La télédéclaration specifiée n'existe pas")


class TeledeclarationPdfView(APIView):
"""
This view returns a PDF for proof of teledeclaration
"""

permission_classes = [permissions.IsAuthenticated]

def get(self, request, *args, **kwargs):

try:
teledeclaration_id = kwargs.get("pk")

if not teledeclaration_id:
raise ValidationError("teledeclarationId manquant")

teledeclaration = Teledeclaration.objects.get(pk=teledeclaration_id)
if request.user not in teledeclaration.canteen.managers.all():
raise PermissionDenied()

if (
teledeclaration.status
!= Teledeclaration.TeledeclarationStatus.SUBMITTED
):
raise ValidationError(
"La télédéclaration n'est pas validée par l'utilisateur"
)

response = HttpResponse(content_type="application/pdf")
filename = f"teledeclaration-{teledeclaration.year}.pdf"
response["Content-Disposition"] = f'attachment; filename="{filename}"'
template = get_template("teledeclaration_pdf.html")
context = {
"year": teledeclaration.year,
"canteen_name": teledeclaration.fields["canteen"]["name"],
"siret": teledeclaration.fields["canteen"]["siret"],
"date": teledeclaration.creation_date,
"applicant": teledeclaration.fields["applicant"]["name"],
"value_total_ht": teledeclaration.fields["teledeclaration"][
"value_total_ht"
],
"value_bio_ht": teledeclaration.fields["teledeclaration"][
"value_bio_ht"
],
"value_sustainable_ht": teledeclaration.fields["teledeclaration"][
"value_sustainable_ht"
],
"value_fair_trade_ht": teledeclaration.fields["teledeclaration"][
"value_fair_trade_ht"
],
}
html = template.render(context)
pisa_status = pisa.CreatePDF(
html, dest=response, link_callback=TeledeclarationPdfView.link_callback
)

if pisa_status.err:
logger.error(
f"Error while generating PDF for teledeclaration {teledeclaration.id}"
)
logger.error(pisa_status.err)
return HttpResponse("An error ocurred", status=500)

return response

except Teledeclaration.DoesNotExist:
raise ValidationError("La télédéclaration specifiée n'existe pas")

@staticmethod
def link_callback(uri, rel):
"""
Convert HTML URIs to absolute system paths so xhtml2pdf can access those
resources
https://xhtml2pdf.readthedocs.io/en/latest/usage.html#using-xhtml2pdf-in-django
"""
result = finders.find(uri)
if result:
if not isinstance(result, (list, tuple)):
result = [result]
result = list(os.path.realpath(path) for path in result)
path = result[0]
else:
sUrl = settings.STATIC_URL
sRoot = settings.STATIC_ROOT
mUrl = settings.MEDIA_URL
mRoot = settings.MEDIA_ROOT

if uri.startswith(mUrl):
path = os.path.join(mRoot, uri.replace(mUrl, ""))
elif uri.startswith(sUrl):
path = os.path.join(sRoot, uri.replace(sUrl, ""))
else:
return uri

# make sure that file exists
if not os.path.isfile(path):
raise Exception("media URI must start with {} or {}".format(sUrl, mUrl))
return path
8 changes: 7 additions & 1 deletion frontend/src/views/DiagnosticEditor/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,13 @@
border="left"
elevation="1"
>
Ce diagnostic a été télédéclaré {{ timeAgo(this.diagnostic.teledeclaration.creationDate, true) }}
<p class="mb-2">
Ce diagnostic a été télédéclaré {{ timeAgo(diagnostic.teledeclaration.creationDate, true) }}.
</p>
<a :href="`/api/v1/teledeclaration/${diagnostic.teledeclaration.id}/document.pdf`" download>
<v-icon small>mdi-download-box-outline</v-icon>
Télécharger mon justificatif.
</a>
</v-alert>

<v-col cols="12" class="mb-8 mt-3">
Expand Down
12 changes: 10 additions & 2 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
arabic-reshaper==2.1.3
asgiref==3.3.4
astroid==2.5.6
attrs==21.2.0
boto3==1.18.28
botocore==1.21.28
boto3==1.18.29
botocore==1.21.29
certifi==2020.12.5
chardet==4.0.0
charset-normalizer==2.0.4
Expand All @@ -20,7 +21,9 @@ djangorestframework-camel-case==1.2.0
drf-base64==2.0
factory-boy==3.2.0
Faker==8.8.0
future==0.18.2
html2text==2020.1.16
html5lib==1.1
idna==2.10
iniconfig==1.1.1
isort==5.8.0
Expand All @@ -37,11 +40,14 @@ pylint==2.8.3
pylint-django==2.4.4
pylint-plugin-utils==0.6
pyparsing==2.4.7
PyPDF2==1.26.0
pytest==6.2.4
pytest-django==4.4.0
python-bidi==0.4.2
python-dateutil==2.8.2
python-dotenv==0.19.0
pytz==2021.1
reportlab==3.6.1
requests==2.26.0
s3transfer==0.5.0
sentry-sdk==1.3.1
Expand All @@ -51,4 +57,6 @@ sqlparse==0.4.1
text-unidecode==1.3
toml==0.10.2
urllib3==1.26.4
webencodings==0.5.1
wrapt==1.12.1
xhtml2pdf==0.2.5
Binary file added web/static/images/logo_transparent_white.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit cbde7b3

Please sign in to comment.