95 lines
3.0 KiB
Python
95 lines
3.0 KiB
Python
import logging
|
|
|
|
from django.shortcuts import get_object_or_404
|
|
from rest_framework import status
|
|
from rest_framework.permissions import IsAuthenticated
|
|
from rest_framework.response import Response
|
|
from rest_framework.views import APIView
|
|
|
|
from communications import comments_helpers
|
|
from communications.models import Message
|
|
|
|
from ..serializers import (
|
|
AttendanceRecordCommentSerializer,
|
|
)
|
|
from ..support import _records_visible_to
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class AttendanceRecordCommentsAPIView(APIView):
|
|
serializer_class = AttendanceRecordCommentSerializer
|
|
permission_classes = [IsAuthenticated]
|
|
|
|
def get_record(self, request, record_id):
|
|
return get_object_or_404(_records_visible_to(request.user), pk=record_id)
|
|
|
|
@staticmethod
|
|
def serialize_message(record, message):
|
|
payload = {
|
|
"id": message.id,
|
|
"record": record.id,
|
|
"author": message.author,
|
|
"text": message.content,
|
|
"created_at": message.created_at,
|
|
}
|
|
return AttendanceRecordCommentSerializer(payload).data
|
|
|
|
def get(self, request, record_id):
|
|
record = self.get_record(request, record_id)
|
|
messages = comments_helpers.get_comments(record)
|
|
return Response(
|
|
[self.serialize_message(record, message) for message in messages]
|
|
)
|
|
|
|
def post(self, request, record_id):
|
|
record = self.get_record(request, record_id)
|
|
serializer = AttendanceRecordCommentSerializer(data=request.data)
|
|
serializer.is_valid(raise_exception=True)
|
|
|
|
message = comments_helpers.create_comment(
|
|
obj=record,
|
|
author=request.user,
|
|
content=serializer.validated_data["text"].strip(),
|
|
)
|
|
|
|
return Response(
|
|
self.serialize_message(record, message),
|
|
status=status.HTTP_201_CREATED,
|
|
)
|
|
|
|
|
|
class AttendanceRecordCommentDetailAPIView(APIView):
|
|
serializer_class = AttendanceRecordCommentSerializer
|
|
permission_classes = [IsAuthenticated]
|
|
|
|
def delete(self, request, record_id, comment_id):
|
|
record = get_object_or_404(_records_visible_to(request.user), pk=record_id)
|
|
chat = comments_helpers.get_comments_chat_if_exists(record)
|
|
if chat is None:
|
|
return Response(
|
|
{"detail": "Comment not found"},
|
|
status=status.HTTP_404_NOT_FOUND,
|
|
)
|
|
|
|
try:
|
|
message = Message.objects.get(id=comment_id, chat=chat)
|
|
except Message.DoesNotExist:
|
|
return Response(
|
|
{"detail": "Comment not found"},
|
|
status=status.HTTP_404_NOT_FOUND,
|
|
)
|
|
|
|
if message.author != request.user:
|
|
return Response(
|
|
{"detail": "You don't have permission to delete this comment"},
|
|
status=status.HTTP_403_FORBIDDEN,
|
|
)
|
|
|
|
comments_helpers.delete_comment(
|
|
message=message,
|
|
deleted_by=request.user,
|
|
soft_delete=True,
|
|
)
|
|
return Response(status=status.HTTP_204_NO_CONTENT)
|