diff --git a/compensation/models.py b/compensation/models.py index 51f3ffc..006a463 100644 --- a/compensation/models.py +++ b/compensation/models.py @@ -355,6 +355,17 @@ class EcoAccount(AbstractCompensation): return ret_msgs + def get_documents(self) -> QuerySet: + """ Getter for all documents of an EcoAccount + + Returns: + docs (QuerySet): The queryset of all documents + """ + docs = EcoAccountDocument.objects.filter( + instance=self + ) + return docs + class EcoAccountDocument(AbstractDocument): """ @@ -370,6 +381,35 @@ class EcoAccountDocument(AbstractDocument): max_length=1000, ) + 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: + + """ + acc_docs = self.instance.get_documents() + + folder_path = None + if acc_docs.count() == 1: + # The only file left for this eco account 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) + class EcoAccountDeduction(BaseResource): """