oncall-engine/engine/apps/api/views/shift_swap.py
Joey Orlando 2576954b51
add shifts property to shift swap request response schema + finalize slack message layout (#2712)
# What this PR does

- drop `GET /api/internal/v1/shift_swaps/<id>/shifts` endpoint in favour
of adding a `shifts` property to the response schema for all shift swap
endpoints (expect `GET /api/internal/v1/shift_swaps` (ie. list all))
- Update the Slack message layout:

<img width="590" alt="Screenshot 2023-08-01 at 17 28 44"
src="https://github.com/grafana/oncall/assets/9406895/84a51614-5dd6-48ec-ae81-fef4bc32fec9">

**Note**: about the highlighted lines. This is a small issue w/ the
`ShiftSwapRequest.shifts` method. @matiasb is already helping out here 🙏

**Other stuff**
- adds some type hints related to the code I was working around with
- slightly refactor `apps.slack.utils.format_datetime_to_slack` to make
it more generic for the use case in this PR

## Checklist

- [x] Unit, integration, and e2e (if applicable) tests updated
- [x] Documentation added (or `pr:no public docs` PR label added if not
required)
- [x] `CHANGELOG.md` updated (or `pr:no changelog` PR label added if not
required)
2023-08-01 14:21:02 -04:00

105 lines
4.6 KiB
Python

import logging
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.serializers import BaseSerializer
from rest_framework.viewsets import ModelViewSet
from apps.api.permissions import AuthenticatedRequest, IsOwner, RBACPermission
from apps.api.serializers.shift_swap import ShiftSwapRequestListSerializer, ShiftSwapRequestSerializer
from apps.auth_token.auth import PluginAuthentication
from apps.mobile_app.auth import MobileAppAuthTokenAuthentication
from apps.schedules import exceptions
from apps.schedules.models import ShiftSwapRequest
from apps.schedules.tasks.shift_swaps import create_shift_swap_request_message, update_shift_swap_request_message
from common.api_helpers.exceptions import BadRequest
from common.api_helpers.mixins import PublicPrimaryKeyMixin
from common.api_helpers.paginators import FiftyPageSizePaginator
from common.insight_log import EntityEvent, write_resource_insight_log
logger = logging.getLogger(__name__)
class ShiftSwapViewSet(PublicPrimaryKeyMixin[ShiftSwapRequest], ModelViewSet):
authentication_classes = (MobileAppAuthTokenAuthentication, PluginAuthentication)
permission_classes = (IsAuthenticated, RBACPermission)
rbac_permissions = {
# TODO: add note to public documentation about these permissions also giving access to shift swaps
# unless we want to make a separate resource type for them?
"metadata": [RBACPermission.Permissions.SCHEDULES_READ],
"list": [RBACPermission.Permissions.SCHEDULES_READ],
"retrieve": [RBACPermission.Permissions.SCHEDULES_READ],
"create": [RBACPermission.Permissions.SCHEDULES_WRITE],
"update": [RBACPermission.Permissions.SCHEDULES_WRITE],
"partial_update": [RBACPermission.Permissions.SCHEDULES_WRITE],
"destroy": [RBACPermission.Permissions.SCHEDULES_WRITE],
"take": [RBACPermission.Permissions.SCHEDULES_WRITE],
}
is_beneficiary = IsOwner(ownership_field="beneficiary")
rbac_object_permissions = {
is_beneficiary: [
"update",
"partial_update",
"destroy",
],
}
model = ShiftSwapRequest
serializer_class = ShiftSwapRequestSerializer
pagination_class = FiftyPageSizePaginator
def get_serializer_class(self):
return ShiftSwapRequestListSerializer if self.action == "list" else super().get_serializer_class()
def get_queryset(self):
queryset = ShiftSwapRequest.objects.filter(schedule__organization=self.request.auth.organization)
return self.serializer_class.setup_eager_loading(queryset)
def perform_destroy(self, instance: ShiftSwapRequest) -> None:
# TODO: should we allow deleting a taken request?
super().perform_destroy(instance)
write_resource_insight_log(instance=instance, author=self.request.user, event=EntityEvent.DELETED)
update_shift_swap_request_message.apply_async((instance.pk,))
def perform_create(self, serializer: BaseSerializer[ShiftSwapRequest]) -> None:
beneficiary = self.request.user
shift_swap_request = serializer.save(beneficiary=beneficiary)
write_resource_insight_log(instance=shift_swap_request, author=beneficiary, event=EntityEvent.CREATED)
create_shift_swap_request_message.apply_async((shift_swap_request.pk,))
def perform_update(self, serializer: BaseSerializer[ShiftSwapRequest]) -> None:
prev_state = serializer.instance.insight_logs_serialized
serializer.save()
shift_swap_request = serializer.instance
write_resource_insight_log(
instance=shift_swap_request,
author=self.request.user,
event=EntityEvent.UPDATED,
prev_state=prev_state,
new_state=shift_swap_request.insight_logs_serialized,
)
update_shift_swap_request_message.apply_async((shift_swap_request.pk,))
@action(methods=["post"], detail=True)
def take(self, request: AuthenticatedRequest, pk: str) -> Response:
shift_swap = self.get_object()
try:
shift_swap.take(request.user)
except exceptions.ShiftSwapRequestNotOpenForTaking:
raise BadRequest(detail="The shift swap request is not in a state which allows it to be taken")
except exceptions.BeneficiaryCannotTakeOwnShiftSwapRequest:
raise BadRequest(detail="A shift swap request cannot be created and taken by the same user")
return Response(ShiftSwapRequestSerializer(shift_swap).data, status=status.HTTP_200_OK)