Skip to content

Commit

Permalink
Merge branch 'feature/1062-send-document-to-openzaak' into develop
Browse files Browse the repository at this point in the history
  • Loading branch information
alextreme committed Feb 5, 2023
2 parents 93bb85b + 1f617b5 commit 6afd9d4
Show file tree
Hide file tree
Showing 5 changed files with 389 additions and 38 deletions.
54 changes: 47 additions & 7 deletions src/open_inwoner/accounts/views/cases.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

from open_inwoner.openzaak.api_models import Zaak
from open_inwoner.openzaak.cases import (
connect_case_with_document,
fetch_case_information_objects,
fetch_case_information_objects_for_case_and_info,
fetch_case_roles,
Expand All @@ -32,6 +33,7 @@
download_document,
fetch_single_information_object_url,
fetch_single_information_object_uuid,
upload_document,
)
from open_inwoner.openzaak.models import (
OpenZaakConfig,
Expand Down Expand Up @@ -407,21 +409,59 @@ def get_form_kwargs(self):
kwargs["case"] = self.case
return kwargs

def handle_document_upload(self, request, form):
cleaned_data = form.cleaned_data

file = cleaned_data["file"]
title = cleaned_data["title"]
user_choice = cleaned_data["type"].id
source_organization = self.case.bronorganisatie

created_document = upload_document(
request.user, file, title, user_choice, source_organization
)

# we don't receive a status code like 201, so we try to validate upload
# by checking for the created url
if created_document and created_document.get("url"):
created_relationship = connect_case_with_document(
self.case.url, created_document["url"]
)

# successful upload and connection to zaak
if created_relationship and created_relationship.get("url"):
self.log_user_action(
request.user,
_("Document was uploaded for {case}: {filename}").format(
case=self.case.identificatie,
filename=file.name,
),
)

messages.add_message(
request,
messages.SUCCESS,
_(f"{file.name} has been successfully uploaded"),
)
return HttpResponseRedirect(self.get_success_url())

# fail uploading the document or connecting it to the zaak
messages.add_message(
request,
messages.ERROR,
_(f"An error occured while uploading file {file.name}"),
)
return self.form_invalid(form)

def get_success_url(self) -> str:
return self.request.get_full_path()

def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
file = request.FILES["file"]

if form.is_valid():
messages.add_message(
self.request,
messages.SUCCESS,
_(f"{file.name} has been successfully uploaded."),
)
return HttpResponseRedirect(self.get_success_url())
return self.handle_document_upload(request, form)
else:
return self.form_invalid(form)

Expand Down
19 changes: 19 additions & 0 deletions src/open_inwoner/openzaak/cases.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,3 +280,22 @@ def fetch_single_result(result_url: str) -> Optional[Resultaat]:
result = factory(Resultaat, response)

return result


def connect_case_with_document(case_url: str, document_url: str) -> dict:
client = build_client("zaak")
if client is None:
return

try:
response = client.create(
"zaakinformatieobject", {"zaak": case_url, "informatieobject": document_url}
)
except RequestException as e:
logger.exception("exception while making request", exc_info=e)
return
except ClientError as e:
logger.exception("exception while making request", exc_info=e)
return

return response
48 changes: 47 additions & 1 deletion src/open_inwoner/openzaak/documents.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import base64
import logging
from datetime import date
from typing import Optional

from django.conf import settings
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.utils.functional import SimpleLazyObject

import requests
from requests import HTTPError, RequestException, Response
Expand All @@ -10,8 +14,12 @@

from open_inwoner.openzaak.api_models import InformatieObject
from open_inwoner.openzaak.clients import build_client
from open_inwoner.openzaak.models import OpenZaakConfig
from open_inwoner.openzaak.models import (
OpenZaakConfig,
ZaakTypeInformatieObjectTypeConfig,
)

from .api_models import Zaak
from .utils import cache as cache_result

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -87,3 +95,41 @@ def download_document(url: str) -> Optional[Response]:
logger.exception("exception while making request", exc_info=e)
else:
return res


def upload_document(
user: SimpleLazyObject,
file: InMemoryUploadedFile,
title: str,
user_choice: int,
source_organization: str,
) -> dict:

client = build_client("document")
if client is None:
return

document_body = {
"bronorganisatie": source_organization,
"creatiedatum": date.today().strftime("%Y-%m-%d"),
"titel": title,
"auteur": user.get_full_name(),
"inhoud": base64.b64encode(file.read()).decode("utf-8"),
"bestandsomvang": file.size,
"bestandsnaam": file.name,
"taal": "nld",
"informatieobjecttype": ZaakTypeInformatieObjectTypeConfig.objects.get(
id=user_choice
).informatieobjecttype_url,
}

try:
response = client.create("enkelvoudiginformatieobject", document_body)
except RequestException as e:
logger.exception("exception while making request", exc_info=e)
return
except ClientError as e:
logger.exception("exception while making request", exc_info=e)
return

return response
124 changes: 99 additions & 25 deletions src/open_inwoner/openzaak/tests/test_case_detail.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,18 @@ def setUpTestData(cls):
bestandsnaam="document.txt",
bestandsomvang=123,
)
cls.uploaded_informatie_object = generate_oas_component(
"drc",
"schemas/EnkelvoudigInformatieObject",
uuid="85079ba3-554a-450f-b963-2ce20b176c90",
url=cls.zaak_informatie_object["informatieobject"],
inhoud=f"{DOCUMENTEN_ROOT}enkelvoudiginformatieobjecten/85079ba3-554a-450f-b963-2ce20b176c90/download",
informatieobjecttype=cls.informatie_object_type["url"],
status="definitief",
vertrouwelijkheidaanduiding=VertrouwelijkheidsAanduidingen.openbaar,
bestandsnaam="upload.txt",
bestandsomvang=123,
)

cls.zaak_informatie_object_invisible = generate_oas_component(
"zrc",
Expand Down Expand Up @@ -287,6 +299,11 @@ def _setUpMocks(self, m):
]:
m.get(resource["url"], json=resource)

m.post(
f"{ZAKEN_ROOT}zaakinformatieobjecten",
status_code=201,
json=self.zaak_informatie_object,
)
m.get(
f"{ZAKEN_ROOT}zaakinformatieobjecten?zaak={self.zaak['url']}",
json=[self.zaak_informatie_object, self.zaak_informatie_object_invisible],
Expand All @@ -310,6 +327,11 @@ def _setUpMocks(self, m):
f"{CATALOGI_ROOT}statustypen?zaaktype={self.zaaktype['url']}",
json=paginated_response([self.status_type_new, self.status_type_finish]),
)
m.post(
f"{DOCUMENTEN_ROOT}enkelvoudiginformatieobjecten",
status_code=201,
json=self.uploaded_informatie_object,
)
m.get(
f"{CATALOGI_ROOT}zaaktype-informatieobjecttypen?zaaktype={self.zaaktype['url']}&richting=inkomend",
json=paginated_response([self.zaaktype_informatie_object_type]),
Expand Down Expand Up @@ -549,7 +571,7 @@ def test_upload_form_is_not_rendered_when_no_information_object_types_exist(

self.assertNotIn("document-upload", response.forms)

def test_upload_file_flow_succeeds(self, m):
def test_successful_document_upload_flow(self, m):
self._setUpMocks(m)

zaak_type_config = ZaakTypeConfigFactory(
Expand All @@ -562,33 +584,25 @@ def test_upload_file_flow_succeeds(self, m):
document_upload_enabled=True,
)

response = self.app.get(
reverse(
"accounts:case_status",
kwargs={"object_id": self.zaak["uuid"]},
),
user=self.user,
)
response = self.app.get(self.case_detail_url, user=self.user)
form = response.forms["document-upload"]
form["title"] = "readme"
form["title"] = "uploaded file"
form["type"] = zaak_type_iotc.id
form["file"] = Upload("readme.xlsx", b"data", "application/vnd.ms-excel")
form["file"] = Upload("upload.txt", b"data", "text/plain")
form_response = form.submit()

messages = list(form_response.follow().context["messages"])
redirect = form_response.follow()
redirect_messages = list(redirect.context["messages"])

self.assertRedirects(
form_response,
reverse(
"accounts:case_status",
kwargs={"object_id": self.zaak["uuid"]},
),
)
self.assertRedirects(form_response, self.case_detail_url)
self.assertEqual(
messages[0].message, _("readme.xlsx has been successfully uploaded.")
redirect_messages[0].message,
_(
f"{self.uploaded_informatie_object['bestandsnaam']} has been successfully uploaded"
),
)

def test_upload_file_flow_fails_with_invalid_extension(self, m):
def test_upload_file_flow_fails_with_invalid_file_extension(self, m):
self._setUpMocks(m)

zaak_type_config = ZaakTypeConfigFactory(
Expand All @@ -609,9 +623,9 @@ def test_upload_file_flow_fails_with_invalid_extension(self, m):
user=self.user,
)
form = response.forms["document-upload"]
form["title"] = "readme"
form["title"] = "uploaded file"
form["type"] = zaak_type_iotc.id
form["file"] = Upload("readme.xml", b"data", "application/vnd.ms-excel")
form["file"] = Upload("upload.xml", b"data", "application/xml")
form_response = form.submit()

self.assertEqual(
Expand All @@ -623,7 +637,7 @@ def test_upload_file_flow_fails_with_invalid_extension(self, m):
},
)

def test_upload_larger_file_fails(self, m):
def test_upload_with_larger_file_size_fails(self, m):
self._setUpMocks(m)

zaak_type_config = ZaakTypeConfigFactory(
Expand All @@ -649,9 +663,9 @@ def test_upload_larger_file_fails(self, m):
)
form = response.forms["document-upload"]

form["title"] = "readme"
form["title"] = "uploaded file"
form["type"] = zaak_type_iotc.id
form["file"] = Upload("readme.xlsx", b"data", "application/vnd.ms-excel")
form["file"] = Upload("upload.txt", b"data", "text/plain")
form_response = form.submit()

self.config.refresh_from_db()
Expand Down Expand Up @@ -751,3 +765,63 @@ def test_external_upload_section_is_not_rendered_when_upload_disabled_and_no_url
self.assertNotContains(
response, _("By clicking the button below you can upload a document.")
)

def test_request_error_in_uploading_document_shows_proper_message(self, m):
self._setUpMocks(m)

zaak_type_config = ZaakTypeConfigFactory(
identificatie=self.zaaktype["identificatie"]
)
ZaakTypeInformatieObjectTypeConfigFactory(
zaaktype_config=zaak_type_config,
informatieobjecttype_url=self.informatie_object["url"],
zaaktype_uuids=[self.zaaktype["uuid"]],
document_upload_enabled=True,
)

m.post(f"{DOCUMENTEN_ROOT}enkelvoudiginformatieobjecten", status_code=500)

response = self.app.get(self.case_detail_url, user=self.user)
form = response.forms["document-upload"]
form["title"] = "uploaded file"
form["file"] = Upload("upload.txt", b"data", "text/plain")
form_response = form.submit()

form_response_messages = list(form_response.context["messages"])

self.assertEqual(
form_response_messages[0].message,
_(
f"An error occured while uploading file {self.uploaded_informatie_object['bestandsnaam']}"
),
)

def test_request_error_in_connecting_doc_with_zaak_shows_proper_message(self, m):
self._setUpMocks(m)

zaak_type_config = ZaakTypeConfigFactory(
identificatie=self.zaaktype["identificatie"]
)
ZaakTypeInformatieObjectTypeConfigFactory(
zaaktype_config=zaak_type_config,
informatieobjecttype_url=self.informatie_object["url"],
zaaktype_uuids=[self.zaaktype["uuid"]],
document_upload_enabled=True,
)

m.post(f"{ZAKEN_ROOT}zaakinformatieobjecten", status_code=500)

response = self.app.get(self.case_detail_url, user=self.user)
form = response.forms["document-upload"]
form["title"] = "A title"
form["file"] = Upload("upload.txt", b"data", "text/plain")
form_response = form.submit()

form_response_messages = list(form_response.context["messages"])

self.assertEqual(
form_response_messages[0].message,
_(
f"An error occured while uploading file {self.uploaded_informatie_object['bestandsnaam']}"
),
)
Loading

0 comments on commit 6afd9d4

Please sign in to comment.