Fakultas Ilmu Komputer UI

product.py 7.87 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
from api import exceptions as api_exceptions
from api import models, paginations
from api import permissions as api_permissions
from api import serializers as api_serializers
from django.db.models import deletion
from django.utils.translation import gettext_lazy as _
from django_filters import rest_framework
from rest_framework import filters as rest_framework_filters
from rest_framework import generics
from rest_framework import permissions as rest_framework_permissions
from rest_framework import response, status


class CategoryList(generics.ListCreateAPIView):
    filter_backends = [
        rest_framework.DjangoFilterBackend,
        rest_framework_filters.OrderingFilter,
        rest_framework_filters.SearchFilter,
    ]
    filterset_fields = ['name']
    ordering_fields = ['name']
    pagination_class = paginations.SmallResultsSetPagination
    permission_classes = [
        api_permissions.IsAdminUserOrReadOnly,
        rest_framework_permissions.IsAuthenticated,
    ]
    queryset = models.Category.objects.all()
    search_fields = ['name']
    serializer_class = api_serializers.CategorySerializer


class CategoryDetail(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = [
        api_permissions.IsAdminUserOrReadOnly,
        rest_framework_permissions.IsAuthenticated,
    ]
    queryset = models.Category.objects.all()
    serializer_class = api_serializers.CategorySerializer

    def destroy(self, request, *_args, **_kwargs):
        instance = self.get_object()
        try:
            instance.delete()
        except deletion.ProtectedError:
            raise api_exceptions.IntegrityError(_(
                'Cannot delete category due to integrity error.'
            ))
        return response.Response(status=status.HTTP_204_NO_CONTENT)


class SubcategoryList(generics.ListCreateAPIView):
    filter_backends = [
        rest_framework.DjangoFilterBackend,
        rest_framework_filters.OrderingFilter,
        rest_framework_filters.SearchFilter,
    ]
    filterset_fields = ['name', 'category']
    ordering_fields = ['name']
    pagination_class = paginations.SmallResultsSetPagination
    permission_classes = [
        api_permissions.IsAdminUserOrReadOnly,
        rest_framework_permissions.IsAuthenticated,
    ]
    queryset = models.Subcategory.objects.all()
    search_fields = ['name']
    serializer_class = api_serializers.SubcategorySerializer


class SubcategoryDetail(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = [
        api_permissions.IsAdminUserOrReadOnly,
        rest_framework_permissions.IsAuthenticated,
    ]
    queryset = models.Subcategory.objects.all()
    serializer_class = api_serializers.SubcategorySerializer

    def destroy(self, request, *_args, **_kwargs):
        instance = self.get_object()
        try:
            instance.delete()
        except deletion.ProtectedError:
            raise api_exceptions.IntegrityError(_(
                'Cannot delete subcategory due to integrity error.'
            ))
        return response.Response(status=status.HTTP_204_NO_CONTENT)


class ProductList(generics.ListCreateAPIView):
    filter_backends = [
        rest_framework.DjangoFilterBackend,
        rest_framework_filters.OrderingFilter,
        rest_framework_filters.SearchFilter,
    ]
    filterset_fields = ['code', 'subcategory', 'subcategory__category']
    ordering_fields = ['name', 'price', 'stock']
    pagination_class = paginations.SmallResultsSetPagination
    permission_classes = [
        api_permissions.IsAdminUserOrReadOnly,
        rest_framework_permissions.IsAuthenticated,
    ]
    queryset = models.Product.objects.all()
    search_fields = ['code', 'name']
    serializer_class = api_serializers.ProductSerializer

    def post(self, request, _format=None):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        validated_image = None
        try:
            validated_image = serializer.validated_data['image']
        except KeyError:
            pass
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
        if serializer.validated_data['preorder']:
            product = models.Product.objects.create(
                name=serializer.validated_data['name'],
                description=serializer.validated_data['description'],
                price=serializer.validated_data['price'],
                modal=serializer.validated_data['modal'],
                subcategory=models.Subcategory.objects.get(name=serializer.validated_data['subcategory']),
                total_profit=0,
                unit=serializer.validated_data['unit'],
                image=validated_image,
                preorder=serializer.validated_data['preorder'],
                preorder_duration=serializer.validated_data['preorder_duration'],
            )
        else:
            product = models.Product.objects.create(
                name=serializer.validated_data['name'],
                description=serializer.validated_data['description'],
                price=serializer.validated_data['price'],
                stock=serializer.validated_data['stock'],
                modal=serializer.validated_data['modal'],
                subcategory=models.Subcategory.objects.get(name=serializer.validated_data['subcategory']),
                total_profit=0,
                unit=serializer.validated_data['unit'],
                image=validated_image,
            )
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
        product.profit = (product.price - product.modal)
        product.save()
        return response.Response(
            {'id': product.id},
            status=status.HTTP_201_CREATED
        )


class ProductDetail(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = [
        api_permissions.IsAdminUserOrReadOnly,
        rest_framework_permissions.IsAuthenticated,
    ]
    queryset = models.Product.objects.all()
    serializer_class = api_serializers.ProductSerializer

    def get_serializer(self, *args, **kwargs):
        # leave this intact
        serializer_class = self.get_serializer_class()
        kwargs["context"] = self.get_serializer_context()

        if (self.request != None):
            if (self.request.data.get("price") != None) and (self.request.data.get("modal") != None):
                draft_request_data = self.request.data.copy()
                profit = int(self.request.data['price']) - \
                    int(self.request.data['modal'])
                new_profit = {'profit': profit}
                draft_request_data.update(new_profit)
                kwargs["data"] = draft_request_data
                return serializer_class(*args, **kwargs)
            else:
                if (self.request.data.get("price") != None):

                    instance = self.get_object()
                    draft_request_data = self.request.data.copy()
                    profit = int(
                        self.request.data['price'])-int(instance.modal)
                    new_profit = {'profit': profit}
                    draft_request_data.update(new_profit)

                    kwargs["data"] = draft_request_data
                    return serializer_class(*args, **kwargs)
                elif (self.request.data.get("modal") != None):
                    instance = self.get_object()
                    draft_request_data = self.request.data.copy()
                    profit = int(instance.price) - \
                        int(self.request.data['modal'])
                    new_profit = {'profit': profit}
                    draft_request_data.update(new_profit)

                    kwargs["data"] = draft_request_data
                    return serializer_class(*args, **kwargs)

        return serializer_class(*args, **kwargs)

    def partial_update(self, request, *args, **kwargs):
        instance = self.get_object()

        serializer = self.get_serializer(
            instance, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)

        return super().partial_update(request, *args, **kwargs)  # pylint: disable=no-member