def save(self, **kwargs): super().save(**kwargs) document = Document.objects.get(id=self.instance.id) request = self.context['request'] attachments_to_be_removed = request.data.get( 'attachments_to_be_removed') if attachments_to_be_removed: DocumentService.delete_attachments( document_id=document.id, attachment_ids=attachments_to_be_removed) files = request.data.get('attachments') if files: for file in files: DocumentFileAttachment.objects.create( document=document, create_user=document.create_user, **file) if 'record_numbers' in request.data: record_numbers_dict = { record_number.get('id'): record_number for record_number in request.data.get('record_numbers') if record_number } for attachment in document.attachments: attachment.record_number = \ record_numbers_dict[attachment.id].get('value') attachment.save() if document.status.status in ['Draft', 'Submitted']: comment = request.data.get('comment') if comment and comment.strip(): document_comment = DocumentComment.objects.filter( document=document).first() if document_comment: document_comment.comment = comment document_comment.update_timestamp = datetime.now() document_comment.update_user = request.user document_comment.save() else: DocumentComment.objects.create( document=document, comment=comment, create_user=request.user, create_timestamp=datetime.now(), privileged_access=False) return document
def destroy(self): """ Delete function to mark the document as cancelled. Also, sets the file attachments as removed (including sending a request to minio to delete the actual files) """ document = self.instance if document.status not in DocumentStatus.objects.filter( status__in=["Draft", "Security Scan Failed"]): raise serializers.ValidationError( {'readOnly': "Cannot delete a submission that's not a draft."}) attachments_to_be_removed = DocumentFileAttachment.objects.filter( document=document, is_removed=False).values_list('id') if attachments_to_be_removed: DocumentService.delete_attachments( document_id=document.id, attachment_ids=attachments_to_be_removed) document.status = DocumentStatus.objects.get(status="Cancelled") document.save()