diff --git a/market/serializers.py b/market/serializers.py index 0e98e18..0542ce8 100644 --- a/market/serializers.py +++ b/market/serializers.py @@ -77,6 +77,12 @@ class PostCreateSerializer(ModelSerializer): ) +class PostStatusUpdateSerializer(ModelSerializer): + class Meta: + model = Post + fields = ("status",) + + class PostSerializer(ModelSerializer): product = ProductListSerializer(read_only=True) nickname = serializers.CharField(source="author.nickname") diff --git a/market/viewsets.py b/market/viewsets.py index b52c73d..51efb8e 100644 --- a/market/viewsets.py +++ b/market/viewsets.py @@ -12,7 +12,10 @@ from market.serializers import ( PostSerializer, PostCreateSerializer, PostListSerializer, + PostStatusUpdateSerializer, ) +from graph.models import Transaction +from graph.methods import create_transaction class BrandViewset(ActionBasedMixin, ModelViewSet): @@ -26,7 +29,7 @@ class ProductViewset(ActionBasedMixin, ModelViewSet): queryset = Product.objects.all().select_related("brand") serializer_class = ProductSerializer serializer_class_map = { - "posts": PostSerializer, + "posts": PostListSerializer, } permission_classes = [IsAdminUserOrReadOnly] @@ -54,12 +57,29 @@ class PostViewset(ActionBasedMixin, ModelViewSet): serializer_class_map = { "list": PostListSerializer, "create": PostCreateSerializer, + "update": PostStatusUpdateSerializer, } permission_classes = [IsAuthenticated, IsAuthorOrReadOnly] permission_classes_map = { "list": [AllowAny], "retrieve": [AllowAny], + "create": [AllowAny], } def perform_create(self, serializer): serializer.save(author=self.request.user) + + def perform_update(self, serializer): + object = self.get_object() + object_unsold = object.status == "s" or object.status == "r" + instance = serializer.instance + if object_unsold and serializer.validated_data.get("status") == "d": + create_transaction(instance) + elif ( + not object_unsold + and serializer.validated_data.get("status") == "s" + ): + Transaction.objects.filter( + price=instance.price, product=instance.product + ).delete() + return super().perform_update(serializer)