From 1edc1edc9827c0d897a905f76135d777c010e191 Mon Sep 17 00:00:00 2001
From: mipel <hadunan@gmail.com>
Date: Fri, 17 Sep 2021 09:24:31 +0200
Subject: [PATCH] #18 File upload in certain folders

* removes document file folder if the last EmaDocument is removed from an Ema
---
 ema/models.py | 45 ++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 44 insertions(+), 1 deletion(-)

diff --git a/ema/models.py b/ema/models.py
index 109120f6..3c0b5c25 100644
--- a/ema/models.py
+++ b/ema/models.py
@@ -1,5 +1,8 @@
+import shutil
+
 from django.contrib.auth.models import User
 from django.db import models
+from django.db.models import QuerySet
 
 from compensation.models import AbstractCompensation
 from konova.models import AbstractDocument, generate_document_file_upload_path
@@ -86,6 +89,17 @@ class Ema(AbstractCompensation):
 
         return ret_msgs
 
+    def get_documents(self) -> QuerySet:
+        """ Getter for all documents of an EMA
+
+        Returns:
+            docs (QuerySet): The queryset of all documents
+        """
+        docs = EmaDocument.objects.filter(
+            instance=self
+        )
+        return docs
+
 
 class EmaDocument(AbstractDocument):
     """
@@ -99,4 +113,33 @@ class EmaDocument(AbstractDocument):
     file = models.FileField(
         upload_to=generate_document_file_upload_path,
         max_length=1000,
-    )
\ No newline at end of file
+    )
+
+    def delete(self, *args, **kwargs):
+        """
+        Custom delete functionality for EcoAccountDocuments.
+        Removes the folder from the file system if there are no further documents for this entry.
+
+        Args:
+            *args ():
+            **kwargs ():
+
+        Returns:
+
+        """
+        ema_docs = self.instance.get_documents()
+
+        folder_path = None
+        if ema_docs.count() == 1:
+            # The only file left for this EMA is the one which is currently processed and will be deleted
+            # Make sure that the compensation folder itself is deleted as well, not only the file
+            # Therefore take the folder path from the file path
+            folder_path = self.file.path.split("/")[:-1]
+            folder_path = "/".join(folder_path)
+
+        # Remove the file itself
+        super().delete(*args, **kwargs)
+
+        # If a folder path has been set, we need to delete the whole folder!
+        if folder_path is not None:
+            shutil.rmtree(folder_path)