Fakultas Ilmu Komputer UI

views.py 42.3 KB
Newer Older
WILLIAM GATES's avatar
WILLIAM GATES committed
1
from django import http, shortcuts
2
3
4
from django.contrib import auth
from django.db import transaction as db_transaction, utils as db_utils
from django.db.models import deletion
WILLIAM GATES's avatar
WILLIAM GATES committed
5
from django.utils import timezone
6
7
8
9
10
11
12
13
from django.utils.translation import gettext_lazy as _
from django_filters import rest_framework
from knox import views as knox_views
from rest_framework import (
    exceptions as rest_framework_exceptions, filters as rest_framework_filters, generics,
    permissions as rest_framework_permissions, response, status, views as rest_framework_views
)
from rest_framework.authtoken import serializers as authtoken_serializers
14
15
from rest_framework.decorators import api_view
from django.views.decorators.csrf import csrf_exempt
16
17
from api import (
    constants, exceptions as api_exceptions, filters as api_filters, models, paginations,
WILLIAM GATES's avatar
WILLIAM GATES committed
18
19
    permissions as api_permissions, reports_writer, schemas, serializers as api_serializers,
    utils as api_utils
20
21
)
from home_industry import utils as home_industry_utils
WILLIAM GATES's avatar
WILLIAM GATES committed
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
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
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

class AuthRegister(generics.CreateAPIView):
    permission_classes = [api_permissions.IsAnonymousUser]
    serializer_class = api_serializers.UserSerializer


class AuthCredLogin(knox_views.LoginView):
    permission_classes = [rest_framework_permissions.AllowAny]
    serializer_class = authtoken_serializers.AuthTokenSerializer

    def get_serializer(self, *args, **kwargs):
        return self.serializer_class(*args, **kwargs)

    def post(self, request, format=None): # pylint: disable=redefined-builtin
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        auth.login(request, user)
        return super().post(request, format)


class AuthPhoneNumberLogin(rest_framework_views.APIView):
    permission_classes = [rest_framework_permissions.AllowAny]
    serializer_class = api_serializers.PhoneNumberSerializer

    def get_serializer(self, *args, **kwargs):
        return self.serializer_class(*args, **kwargs)

    def post(self, request, _format=None):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = shortcuts.get_object_or_404(
            models.User,
            phone_number=serializer.validated_data['phone_number']
        )
        user.otp = api_utils.generate_otp()
        user.save()
        api_utils.send_otp(str(user.phone_number), user.otp)
        token = api_utils.generate_bearer_token(user)
        return response.Response({'token': token}, status=status.HTTP_200_OK)


class AuthOTPLogin(knox_views.LoginView):
    permission_classes = [rest_framework_permissions.AllowAny]
    serializer_class = api_serializers.OTPSerializer

    def get_serializer(self, *args, **kwargs):
        return self.serializer_class(*args, **kwargs)

    def post(self, request, format=None): # pylint: disable=redefined-builtin
        http_authorization = self.request.META.get('HTTP_AUTHORIZATION')
        username = api_utils.get_username_from_bearer_token(http_authorization)
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = shortcuts.get_object_or_404(models.User, username=username)
        if user.otp != serializer.validated_data['otp']:
            return response.Response(status=status.HTTP_400_BAD_REQUEST)
        auth.login(request, user)
        user.otp = ''
        user.save()
        return super().post(request, format)


class AuthResendOTP(rest_framework_views.APIView):
    permission_classes = [rest_framework_permissions.AllowAny]

    def post(self, request, _format=None):
        http_authorization = self.request.META.get('HTTP_AUTHORIZATION')
        username = api_utils.get_username_from_bearer_token(http_authorization)
        user = shortcuts.get_object_or_404(models.User, username=username)
        user.otp = api_utils.generate_otp()
        user.save()
        api_utils.send_otp(str(user.phone_number), user.otp)
        return response.Response(status=status.HTTP_204_NO_CONTENT)


class CartUpdate(rest_framework_views.APIView):
    permission_classes = [rest_framework_permissions.IsAuthenticated]
    serializer_class = api_serializers.CartUpdateSerializer

    def get_serializer(self, *args, **kwargs):
        return self.serializer_class(*args, **kwargs)

    def post(self, request, _format=None):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = request.user
        product = shortcuts.get_object_or_404(
            models.Product,
            id=serializer.validated_data['product']
        )
        shopping_cart = models.ShoppingCart.objects.get(user=user)
        cart_item, _created = models.CartItem.objects.get_or_create(
            product=product,
            shopping_cart=shopping_cart
        )
        if serializer.validated_data['quantity'] == 0:
            cart_item.delete()
        else:
            cart_item.quantity = serializer.validated_data['quantity']
            cart_item.save()
        return response.Response(status=status.HTTP_204_NO_CONTENT)


class CartOverview(rest_framework_views.APIView):
    permission_classes = [rest_framework_permissions.IsAuthenticated]

    def get(self, request, _format=None):
        user = request.user
        shopping_cart = models.ShoppingCart.objects.get(user=user)
        item_subtotal = sum(
            cart_item.product.price * cart_item.quantity
            for cart_item in shopping_cart.cart_items.all()
        )
        shipping_costs = api_utils.get_shipping_costs(user)
        if shipping_costs is None:
            return response.Response(
                {'item_subtotal': str(item_subtotal)},
                status=status.HTTP_200_OK
            )
        return response.Response(
            {'item_subtotal': str(item_subtotal), 'shipping_costs': str(shipping_costs)},
            status=status.HTTP_200_OK
        )


class CartCheckout(rest_framework_views.APIView):
    permission_classes = [rest_framework_permissions.IsAuthenticated]
    serializer_class = api_serializers.CartCheckoutSerializer

    def get_serializer(self, *args, **kwargs):
        return self.serializer_class(*args, **kwargs)

    def post(self, request, _format=None):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = request.user
        shipment_config = home_industry_utils.get_shipment_config()
        if user.sub_district.lower() != shipment_config.sub_district.lower():
            raise rest_framework_exceptions.ParseError(_( # pylint: disable=no-member
                'Cannot process shipment to other sub-districts other than {sub_district}.'
            ).format(sub_district=shipment_config.sub_district))
        shopping_cart = models.ShoppingCart.objects.get(user=user)
        cart_items = shopping_cart.cart_items.all()
        if not cart_items.exists():
            raise rest_framework_exceptions.ParseError(_(
                'Unable to checkout because there are no items purchased.'
            ))
        api_utils.validate_product_stock(cart_items)
WILLIAM GATES's avatar
WILLIAM GATES committed
172
173
174
        transaction_status = (
            '001' if serializer.validated_data['payment_method'] == 'TRF' else '002'
        )
175
        
176
177
178
        transaction = models.Transaction.objects.create(
            user=user,
            payment_method=serializer.validated_data['payment_method'],
WILLIAM GATES's avatar
WILLIAM GATES committed
179
            donation=serializer.validated_data['donation'],
180
            transaction_status=transaction_status,
rayhan muzakki's avatar
rayhan muzakki committed
181
182
183
184
185
186
            batch = (
            None if serializer.validated_data['payment_method'] == 'TRF'
            else models.Batch.objects.filter(
                start_date__lte=timezone.now().date(),
                end_date__gte=timezone.now().date()).first()
        )
187
        )
inez nabila's avatar
inez nabila committed
188

189
190
191
192
193
194
195
        is_success = True
        for cart_item in cart_items:
            product = cart_item.product
            if product.stock is not None:
                try:
                    with db_transaction.atomic():
                        product.stock -= cart_item.quantity
196
                        product.total_profit += cart_item.quantity*product.profit
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
                        product.save()
                except db_utils.IntegrityError:
                    is_success = False
            models.TransactionItem.objects.create(
                transaction=transaction,
                product=product,
                quantity=cart_item.quantity
            )
            cart_item.delete()
        if not is_success:
            transaction.transaction_status = '007'
            transaction.save()
            raise rest_framework_exceptions.APIException(_('Checkout failed.'))
        return response.Response({'transaction': transaction.id}, status=status.HTTP_200_OK)


class CartUploadPOP(rest_framework_views.APIView):
    permission_classes = [rest_framework_permissions.IsAuthenticated]
    serializer_class = api_serializers.CartUploadPOPSerializer

    def get_serializer(self, *args, **kwargs):
        return self.serializer_class(*args, **kwargs)

    def post(self, request, _format=None):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = request.user
WILLIAM GATES's avatar
WILLIAM GATES committed
224
225
226
227
        bank_account_transfer_destination = shortcuts.get_object_or_404(
            models.BankAccountTransferDestination,
            id=serializer.validated_data['bank_account_transfer_destination']
        )
228
229
230
231
232
233
234
235
236
237
238
239
240
241
        transaction = shortcuts.get_object_or_404(
            models.Transaction,
            id=serializer.validated_data['transaction'],
            user=user
        )
        if transaction.payment_method != 'TRF':
            raise rest_framework_exceptions.PermissionDenied(_(
                'The payment method for this transaction is not a transfer.'
            ))
        if transaction.transaction_status not in ('001', '002'):
            raise rest_framework_exceptions.PermissionDenied(_(
                'Cannot upload proof of payment at this stage.'
            ))
        transaction.proof_of_payment = serializer.validated_data['proof_of_payment']
WILLIAM GATES's avatar
WILLIAM GATES committed
242
        transaction.user_bank_name = serializer.validated_data['user_bank_name']
243
        transaction.user_bank_account_name = serializer.validated_data['user_bank_account_name']
WILLIAM GATES's avatar
WILLIAM GATES committed
244
245
        transaction.bank_account_transfer_destination = bank_account_transfer_destination
        transaction.update_bank_account_transfer_destination = True
246
        transaction.transaction_status = '002'
inez nabila's avatar
inez nabila committed
247
        transaction.batch = models.Batch.objects.filter(
inez nabila's avatar
inez nabila committed
248
            start_date__lte=timezone.now().date(),
inez nabila's avatar
inez nabila committed
249
            end_date__gte=timezone.now().date()).first()
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
        transaction.save()
        return response.Response(status=status.HTTP_204_NO_CONTENT)


class CartCompleteTransaction(rest_framework_views.APIView):
    permission_classes = [rest_framework_permissions.IsAuthenticated]
    serializer_class = api_serializers.CartCompleteOrCancelTransactionSerializer

    def get_serializer(self, *args, **kwargs):
        return self.serializer_class(*args, **kwargs)

    def post(self, request, _format=None):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        transaction = shortcuts.get_object_or_404(
            models.Transaction,
            id=serializer.validated_data['transaction'],
inez nabila's avatar
fixing    
inez nabila committed
267
            user=request.user
268
269
        )
        if transaction.transaction_status != '004':
WILLIAM GATES's avatar
WILLIAM GATES committed
270
            raise rest_framework_exceptions.PermissionDenied(_(
WILLIAM GATES's avatar
WILLIAM GATES committed
271
                'Transaction cannot be completed unless the status is "Being shipped".'
WILLIAM GATES's avatar
WILLIAM GATES committed
272
            ))
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
        transaction.transaction_status = '005'
        transaction.save()
        return response.Response(status=status.HTTP_204_NO_CONTENT)


class CartCancelTransaction(rest_framework_views.APIView):
    permission_classes = [rest_framework_permissions.IsAuthenticated]
    serializer_class = api_serializers.CartCompleteOrCancelTransactionSerializer

    def get_serializer(self, *args, **kwargs):
        return self.serializer_class(*args, **kwargs)

    def post(self, request, _format=None):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = request.user
        transaction = shortcuts.get_object_or_404(
            models.Transaction,
            id=serializer.validated_data['transaction'],
            user=user
        )
        if transaction.transaction_status not in ('001', '002'):
WILLIAM GATES's avatar
WILLIAM GATES committed
295
296
297
            raise rest_framework_exceptions.PermissionDenied(_(
                'Transaction cannot be canceled at this stage.'
            ))
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
        transaction_items = transaction.transaction_items.all()
        api_utils.return_transaction_items_to_product_stock(transaction_items)
        transaction.transaction_status = '006'
        transaction.save()
        return response.Response(status=status.HTTP_204_NO_CONTENT)


class DonationCreate(rest_framework_views.APIView):
    permission_classes = [rest_framework_permissions.IsAuthenticated]
    serializer_class = api_serializers.DonationCreateSerializer

    def get_serializer(self, *args, **kwargs):
        return self.serializer_class(*args, **kwargs)

    def post(self, request, _format=None):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = request.user
        program = shortcuts.get_object_or_404(
            models.Program,
            id=serializer.validated_data['program']
        )
WILLIAM GATES's avatar
WILLIAM GATES committed
320
        if not program.open_donation:
WILLIAM GATES's avatar
WILLIAM GATES committed
321
            raise rest_framework_exceptions.PermissionDenied(_(
WILLIAM GATES's avatar
WILLIAM GATES committed
322
                'This program is currently not accepting donations.'
WILLIAM GATES's avatar
WILLIAM GATES committed
323
            ))
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
        program_donation = None
        if serializer.validated_data['donation_type'] == 'CSH':
            bank_account_transfer_destination = shortcuts.get_object_or_404(
                models.BankAccountTransferDestination,
                id=serializer.validated_data['bank_account_transfer_destination']
            )
            program_donation = models.ProgramDonation.objects.create(
                user=user,
                program=program,
                donation_type='CSH',
                amount=serializer.validated_data['amount'],
                proof_of_bank_transfer=serializer.validated_data['proof_of_bank_transfer'],
                user_bank_name=serializer.validated_data['user_bank_name'],
                user_bank_account_name=serializer.validated_data['user_bank_account_name'],
                bank_account_transfer_destination=bank_account_transfer_destination
            )
inez nabila's avatar
inez nabila committed
340

341
        else:
342
343
            if serializer.validated_data['delivery_method'] == 'DLV':
                program_donation = models.ProgramDonation.objects.create(
inez nabila's avatar
inez nabila committed
344
345
346
347
348
349
350
351
                    user=user,
                    program=program,
                    donation_type='GDS',
                    goods_quantity=serializer.validated_data['goods_quantity'],
                    goods_description=serializer.validated_data['goods_description'],
                    delivery_method=serializer.validated_data['delivery_method'],
                    delivery_address=None
                )
352
353
354
355
356
357
358
359
360
361
            else:
                program_donation = models.ProgramDonation.objects.create(
                    user=user,
                    program=program,
                    donation_type='GDS',
                    goods_quantity=serializer.validated_data['goods_quantity'],
                    goods_description=serializer.validated_data['goods_description'],
                    delivery_method=serializer.validated_data['delivery_method'],
                    delivery_address=serializer.validated_data['delivery_address']
                )
362

363
364
365
366
367
368
        return response.Response(
            {'program_donation': program_donation.id},
            status=status.HTTP_200_OK
        )


369

370
371
372
373
374
375
376
377
378
379
380
class DonationReuploadProofOfBankTransfer(rest_framework_views.APIView):
    permission_classes = [rest_framework_permissions.IsAuthenticated]
    serializer_class = api_serializers.DonationReuploadProofOfBankTransferSerializer

    def get_serializer(self, *args, **kwargs):
        return self.serializer_class(*args, **kwargs)

    def post(self, request, _format=None):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = request.user
WILLIAM GATES's avatar
WILLIAM GATES committed
381
382
383
384
        bank_account_transfer_destination = shortcuts.get_object_or_404(
            models.BankAccountTransferDestination,
            id=serializer.validated_data['bank_account_transfer_destination']
        )
385
386
387
388
389
390
391
392
393
        program_donation = shortcuts.get_object_or_404(
            models.ProgramDonation,
            id=serializer.validated_data['program_donation'],
            user=user
        )
        if program_donation.donation_status not in ('001', '004'):
            raise rest_framework_exceptions.PermissionDenied(_(
                'Cannot reupload proof of bank transfer at this stage.'
            ))
394
395
396
397
        if program_donation.donation_type != 'CSH':
            raise rest_framework_exceptions.PermissionDenied(_(
                'Cannot proof of bank transfer foor good donation.'
            ))
WILLIAM GATES's avatar
WILLIAM GATES committed
398
        program_donation.amount = serializer.validated_data['amount']
399
400
401
        program_donation.proof_of_bank_transfer = (
            serializer.validated_data['proof_of_bank_transfer']
        )
WILLIAM GATES's avatar
WILLIAM GATES committed
402
        program_donation.user_bank_name = serializer.validated_data['user_bank_name']
403
404
405
        program_donation.user_bank_account_name = (
            serializer.validated_data['user_bank_account_name']
        )
WILLIAM GATES's avatar
WILLIAM GATES committed
406
407
        program_donation.bank_account_transfer_destination = bank_account_transfer_destination
        program_donation.update_bank_account_transfer_destination = True
408
409
410
411
412
        program_donation.donation_status = '001'
        program_donation.save()
        return response.Response(status=status.HTTP_204_NO_CONTENT)


WILLIAM GATES's avatar
WILLIAM GATES committed
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
class ReportAPIView(rest_framework_views.APIView):
    permission_classes = [rest_framework_permissions.IsAdminUser]
    report_function = None
    serializer_class = None

    def get_filename(self, query_params):
        raise NotImplementedError

    def get_serializer(self, *args, **kwargs):
        return self.serializer_class(*args, **kwargs) # pylint: disable=not-callable

    def get(self, request, _format=None):
        assert self.report_function is not None, (
            '{} should include a `report_function` attribute.'.format(self.__class__.__name__)
        )
        assert self.report_function is not None, (
            '{} should include a `serializer_class` attribute.'.format(self.__class__.__name__)
        )
        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)
        buffer = self.report_function.__func__(serializer.validated_data)
        buffer.seek(0)
        return http.FileResponse(buffer, filename=self.get_filename(serializer.validated_data))


class ReportTransaction(ReportAPIView):
    report_function = reports_writer.create_transaction_report
    schema = schemas.ReportTransactionSchema()
    serializer_class = api_serializers.ReportTransactionSerializer

    def get_filename(self, query_params):
        filename = '{}.xlsx'.format(_( # pylint: disable=no-member
445
            'Transaction Report from {date_from} to {date_to} for {batch_name}'
WILLIAM GATES's avatar
WILLIAM GATES committed
446
        ).format(
WILLIAM GATES's avatar
WILLIAM GATES committed
447
            date_from=query_params.get('created_at_date_range_after', '_'),
448
449
            date_to=query_params.get('created_at_date_range_before', str(timezone.now())[:10]),
            batch_name=query_params.get('batch_name', '_')
WILLIAM GATES's avatar
WILLIAM GATES committed
450
451
452
453
        ))
        return filename


Rayhan Muzakki's avatar
Pbi5    
Rayhan Muzakki committed
454
455
class ReportProgramDonationCSH(ReportAPIView):
    report_function = reports_writer.create_program_donation_report_CSH
WILLIAM GATES's avatar
WILLIAM GATES committed
456
457
458
459
460
461
462
    schema = schemas.ReportProgramDonationSchema()
    serializer_class = api_serializers.ReportProgramDonationSerializer

    def get_filename(self, query_params):
        filename = '{}.xlsx'.format(_( # pylint: disable=no-member
            'Program Donation Report from {date_from} to {date_to}'
        ).format(
WILLIAM GATES's avatar
WILLIAM GATES committed
463
            date_from=query_params.get('created_at_date_range_after', '_'),
WILLIAM GATES's avatar
WILLIAM GATES committed
464
465
466
467
            date_to=query_params.get('created_at_date_range_before', str(timezone.now())[:10])
        ))
        return filename

Rayhan Muzakki's avatar
Pbi 5    
Rayhan Muzakki committed
468
469
class ReportProgramDonationGDS(ReportAPIView):
    report_function = reports_writer.create_program_donation_report_GDS
WILLIAM GATES's avatar
WILLIAM GATES committed
470
471
472
473
474
475
476
    schema = schemas.ReportProgramDonationSchema()
    serializer_class = api_serializers.ReportProgramDonationSerializer

    def get_filename(self, query_params):
        filename = '{}.xlsx'.format(_( # pylint: disable=no-member
            'Program Donation Report from {date_from} to {date_to}'
        ).format(
WILLIAM GATES's avatar
WILLIAM GATES committed
477
            date_from=query_params.get('created_at_date_range_after', '_'),
WILLIAM GATES's avatar
WILLIAM GATES committed
478
479
480
481
482
            date_to=query_params.get('created_at_date_range_before', str(timezone.now())[:10])
        ))
        return filename


483
484
485
486
487
488
489
class UserList(generics.ListCreateAPIView):
    filter_backends = [
        rest_framework.DjangoFilterBackend,
        rest_framework_filters.OrderingFilter,
        rest_framework_filters.SearchFilter,
    ]
    filterset_fields = ['username', 'phone_number']
inez nabila's avatar
inez nabila committed
490
491
    ordering_fields = [
        'username', 'full_name', 'phone_number',
492
        'total_transactions', 'total_program_donations_goods', 'total_program_donations_cash'
inez nabila's avatar
fixing    
inez nabila committed
493
    ]
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
    pagination_class = paginations.SmallResultsSetPagination
    permission_classes = [rest_framework_permissions.IsAdminUser]
    queryset = models.User.objects.all()
    search_fields = ['username', 'full_name', 'phone_number']
    serializer_class = api_serializers.UserSerializer

class UserDetail(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = [
        api_permissions.IsAdminUserOrSelf,
        rest_framework_permissions.IsAuthenticated,
    ]
    queryset = models.User.objects.all()
    serializer_class = api_serializers.UserSerializer

    def get_object(self):
WILLIAM GATES's avatar
WILLIAM GATES committed
509
        if self.kwargs.get('pk') == 'self':
510
511
512
513
            self.kwargs['pk'] = self.request.user.id
        return super().get_object()


WILLIAM GATES's avatar
WILLIAM GATES committed
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
class BankAccountTransferDestinationList(generics.ListCreateAPIView):
    filter_backends = [rest_framework_filters.SearchFilter]
    pagination_class = paginations.SmallResultsSetPagination
    permission_classes = [
        api_permissions.IsAdminUserOrReadOnly,
        rest_framework_permissions.IsAuthenticated,
    ]
    queryset = models.BankAccountTransferDestination.objects.all()
    search_fields = ['bank_name', 'bank_account_number', 'bank_account_name']
    serializer_class = api_serializers.BankAccountTransferDestinationSerializer


class BankAccountTransferDestinationDetail(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = [
        api_permissions.IsAdminUserOrReadOnly,
        rest_framework_permissions.IsAuthenticated,
    ]
    queryset = models.BankAccountTransferDestination.objects.all()
    serializer_class = api_serializers.BankAccountTransferDestinationSerializer


535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
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()
WILLIAM GATES's avatar
WILLIAM GATES committed
623
    search_fields = ['code', 'name']
624
625
    serializer_class = api_serializers.ProductSerializer

626
627
628
    def post(self, request, _format=None):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
629
630
631
632
633
        validated_image = None
        try:
            validated_image = serializer.validated_data['image']
        except KeyError:
            pass
634
635
636
637
638
639
        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'],
rayhan muzakki's avatar
rayhan muzakki committed
640
            subcategory=models.Subcategory.objects.get(name=serializer.validated_data['subcategory']),
641
            total_profit=0,
642
            unit=serializer.validated_data['unit'],
643
            image=validated_image
644
        )
rayhan muzakki's avatar
rayhan muzakki committed
645
        product.profit= (product.price - product.modal)
646
647
648
649
650
651
        product.save()
        return response.Response(
            {'id': product.id},
            status=status.HTTP_201_CREATED
        )

652

653

654
655
656
657
658
659
660
class ProductDetail(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = [
        api_permissions.IsAdminUserOrReadOnly,
        rest_framework_permissions.IsAuthenticated,
    ]
    queryset = models.Product.objects.all()
    serializer_class = api_serializers.ProductSerializer
661

662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
    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

708
709
    

710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
class ProgramProgressList(generics.ListCreateAPIView):
    permission_classes = [
        api_permissions.IsAdminUserOrReadOnly,
        rest_framework_permissions.IsAuthenticated,
    ]
    lookup_field = 'program'
    serializer_class = api_serializers.ProgramProgressSerializer

    def get_queryset(self):
        return models.ProgramProgress.objects.filter(program=self.get_program())

    def perform_create(self, serializer):
        serializer.save(program=self.get_program())

    def get_program(self):
        program = models.Program.objects.filter(id=self.kwargs.get(self.lookup_field)).first()
        if program is None:
727
            raise rest_framework_exceptions.NotFound(_(
728
729
730
                'Program not found.'
            ))
        return program
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750


class ShoppingCartList(generics.ListAPIView):
    filter_backends = [rest_framework.DjangoFilterBackend]
    filterset_fields = ['user']
    pagination_class = paginations.SmallResultsSetPagination
    permission_classes = [rest_framework_permissions.IsAdminUser]
    queryset = models.ShoppingCart.objects.all()
    serializer_class = api_serializers.ShoppingCartSerializer


class ShoppingCartDetail(generics.RetrieveAPIView):
    permission_classes = [
        api_permissions.IsAdminUserOrOwner,
        rest_framework_permissions.IsAuthenticated,
    ]
    queryset = models.ShoppingCart.objects.all()
    serializer_class = api_serializers.ShoppingCartSerializer

    def get_object(self):
WILLIAM GATES's avatar
WILLIAM GATES committed
751
        if self.kwargs.get('pk') == 'self':
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
            self.kwargs['pk'] = models.ShoppingCart.objects.get(user=self.request.user).id
        return super().get_object()


class TransactionList(generics.ListAPIView):
    filter_backends = [
        rest_framework.DjangoFilterBackend,
        rest_framework_filters.OrderingFilter,
        rest_framework_filters.SearchFilter,
    ]
    filterset_class = api_filters.TransactionFilter
    ordering_fields = ['created_at', 'updated_at']
    pagination_class = paginations.SmallResultsSetPagination
    permission_classes = [rest_framework_permissions.IsAuthenticated]
    queryset = models.Transaction.objects.all()
    schema = schemas.TransactionListSchema()
    search_fields = ['transaction_number', 'user_full_name']
    serializer_class = api_serializers.TransactionSerializer

    def filter_queryset(self, queryset):
        queryset = super().filter_queryset(queryset)
        if not self.request.user.is_staff:
            return queryset.filter(user=self.request.user)
        return queryset


class TransactionDetail(generics.RetrieveUpdateAPIView):
    permission_classes = [
        api_permissions.IsAdminUserOrOwnerReadOnly,
        rest_framework_permissions.IsAuthenticated,
    ]
    queryset = models.Transaction.objects.all()
    serializer_class = api_serializers.TransactionSerializer

    def update(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        if instance.transaction_status in ('005', '006', '007'):
            raise rest_framework_exceptions.PermissionDenied(_(
                'Cannot update transaction because it has a completed, canceled, or failed status.'
            ))
        if serializer.validated_data['transaction_status'] == '006':
            transaction_items = instance.transaction_items.all()
            api_utils.return_transaction_items_to_product_stock(transaction_items)
        return super().update(request, *args, **kwargs) # pylint: disable=no-member


class ProgramList(generics.ListCreateAPIView):
    filter_backends = [
        rest_framework.DjangoFilterBackend,
        rest_framework_filters.OrderingFilter,
        rest_framework_filters.SearchFilter,
    ]
    filterset_fields = ['code']
    ordering_fields = ['name', 'start_date_time', 'end_date_time']
    pagination_class = paginations.SmallResultsSetPagination
    permission_classes = [
        api_permissions.IsAdminUserOrReadOnly,
        rest_framework_permissions.IsAuthenticated,
    ]
    queryset = models.Program.objects.all()
WILLIAM GATES's avatar
WILLIAM GATES committed
814
    search_fields = ['code', 'name']
815
816
817
    serializer_class = api_serializers.ProgramSerializer


WILLIAM GATES's avatar
WILLIAM GATES committed
818
819
820
821
822
823
824
825
class ProgramDetail(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = [
        api_permissions.IsAdminUserOrReadOnly,
        rest_framework_permissions.IsAuthenticated,
    ]
    queryset = models.Program.objects.all()
    serializer_class = api_serializers.ProgramSerializer

826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
class ProgramDonationList(generics.ListAPIView):
    filter_backends = [
        rest_framework.DjangoFilterBackend,
        rest_framework_filters.OrderingFilter,
        rest_framework_filters.SearchFilter,
    ]
    filterset_class = api_filters.ProgramDonationFilter
    ordering_fields = ['created_at', 'updated_at']
    pagination_class = paginations.SmallResultsSetPagination
    permission_classes = [rest_framework_permissions.IsAuthenticated]
    queryset = models.ProgramDonation.objects.all()
    schema = schemas.ProgramDonationListSchema()
    search_fields = ['donation_number', 'user_full_name', 'program_name', 'donation_type']
    serializer_class = api_serializers.ProgramDonationSerializer

    def filter_queryset(self, queryset):
        queryset = super().filter_queryset(queryset)
        if not self.request.user.is_staff:
            return queryset.filter(user=self.request.user)
        return queryset

847
848
849
850
851
852
853
854
@api_view(['DELETE'])
@csrf_exempt
def delete_donation_by_program(request, pid):
    if ((request.user) and (request.user.is_staff)):
        program = models.Program.objects.get(id=pid)
        donation = models.ProgramDonation.objects.filter(program=program)
        donation.delete()
        return response.Response(status=status.HTTP_204_NO_CONTENT)
WILLIAM GATES's avatar
WILLIAM GATES committed
855

856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
class ProgramDonationListCSH(generics.ListAPIView):
    filter_backends = [
        rest_framework.DjangoFilterBackend,
        rest_framework_filters.OrderingFilter,
        rest_framework_filters.SearchFilter,
    ]
    filterset_class = api_filters.ProgramDonationFilter
    ordering_fields = ['created_at', 'updated_at']
    pagination_class = paginations.SmallResultsSetPagination
    permission_classes = [rest_framework_permissions.IsAuthenticated]
    queryset = models.ProgramDonation.objects.filter(donation_type='CSH')
    schema = schemas.ProgramDonationListSchema()
    search_fields = ['donation_number', 'user_full_name', 'program_name', 'donation_type']
    serializer_class = api_serializers.ProgramDonationSerializer

    def filter_queryset(self, queryset):
        queryset = super().filter_queryset(queryset)
        if not self.request.user.is_staff:
            return queryset.filter(user=self.request.user)
        return queryset
876

877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
class ProgramDonationListGDS(generics.ListAPIView):
    filter_backends = [
        rest_framework.DjangoFilterBackend,
        rest_framework_filters.OrderingFilter,
        rest_framework_filters.SearchFilter,
    ]
    filterset_class = api_filters.ProgramDonationFilter
    ordering_fields = ['created_at', 'updated_at']
    pagination_class = paginations.SmallResultsSetPagination
    permission_classes = [rest_framework_permissions.IsAuthenticated]
    queryset = models.ProgramDonation.objects.filter(donation_type='GDS')
    schema = schemas.ProgramDonationListSchema()
    search_fields = ['donation_number', 'user_full_name', 'program_name', 'donation_type']
    serializer_class = api_serializers.ProgramDonationSerializer

    def filter_queryset(self, queryset):
        queryset = super().filter_queryset(queryset)
        if not self.request.user.is_staff:
            return queryset.filter(user=self.request.user)
inez nabila's avatar
inez nabila committed
896
        return queryset
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949

class ProgramDonationDetail(generics.RetrieveUpdateAPIView):
    permission_classes = [
        api_permissions.IsAdminUserOrOwnerReadOnly,
        rest_framework_permissions.IsAuthenticated,
    ]
    queryset = models.ProgramDonation.objects.all()
    serializer_class = api_serializers.ProgramDonationSerializer

    def update(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        if instance.donation_status in ('002', '003'):
            raise rest_framework_exceptions.PermissionDenied(_(
                'Cannot update program donation because it has a completed or canceled status.'
            ))
        return super().update(request, *args, **kwargs) # pylint: disable=no-member


class ChoicesAPIView(rest_framework_views.APIView):
    choices = None
    permission_classes = [rest_framework_permissions.IsAuthenticated]

    def get(self, request, _format=None):
        assert self.choices is not None, (
            '{} should include a `choices` attribute.'.format(self.__class__.__name__)
        )
        return response.Response(api_utils.map_choices(self.choices), status=status.HTTP_200_OK)


class PaymentMethodChoices(ChoicesAPIView):
    choices = constants.PAYMENT_METHOD_CHOICES


class TransactionStatusChoices(ChoicesAPIView):
    choices = constants.TRANSACTION_STATUS_CHOICES


class DonationStatusChoices(ChoicesAPIView):
    choices = constants.DONATION_STATUS_CHOICES


class AppConfigDetail(generics.RetrieveUpdateAPIView):
    permission_classes = [rest_framework_permissions.IsAdminUser]
    queryset = models.AppConfig.objects.all()
    serializer_class = api_serializers.AppConfigSerializer

    def get_object(self):
        obj = shortcuts.get_object_or_404(models.AppConfig)
        return obj


WILLIAM GATES's avatar
WILLIAM GATES committed
950
class HelpContactConfigDetail(generics.RetrieveUpdateAPIView):
951
    permission_classes = [api_permissions.IsAdminUserOrReadOnly]
WILLIAM GATES's avatar
WILLIAM GATES committed
952
953
    queryset = models.HelpContactConfig.objects.all()
    serializer_class = api_serializers.HelpContactConfigSerializer
954
955

    def get_object(self):
WILLIAM GATES's avatar
WILLIAM GATES committed
956
        obj = shortcuts.get_object_or_404(models.HelpContactConfig)
957
958
959
960
961
962
963
964
965
966
967
        return obj


class ShipmentConfigDetail(generics.RetrieveUpdateAPIView):
    permission_classes = [api_permissions.IsAdminUserOrReadOnly]
    queryset = models.ShipmentConfig.objects.all()
    serializer_class = api_serializers.ShipmentConfigSerializer

    def get_object(self):
        obj = shortcuts.get_object_or_404(models.ShipmentConfig)
        return obj
inez nabila's avatar
inez nabila committed
968
969
970
971
972
973
974

class BatchList(generics.ListCreateAPIView):
    filter_backends = [
        rest_framework.DjangoFilterBackend,
        rest_framework_filters.OrderingFilter,
        rest_framework_filters.SearchFilter,
    ]
inez nabila's avatar
inez nabila committed
975

inez nabila's avatar
inez nabila committed
976
977
978
979
980
981
982
983
984
    filterset_class = api_filters.BatchFilter
    ordering_fields = ['created_at', 'updated_at']
    pagination_class = paginations.SmallResultsSetPagination
    permission_classes = [rest_framework_permissions.IsAuthenticated]
    queryset = models.Batch.objects.all()
    schema = schemas.BatchListSchema()
    search_fields = ['batch_name']
    serializer_class = api_serializers.BatchSerializer

985
986
987
    def post(self, request, _format=None):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
inez nabila's avatar
inez nabila committed
988
        if serializer.validated_data['start_date'] < serializer.validated_data['end_date']:
989
990
991
992
            batch = models.Batch.objects.create(
                batch_name=serializer.validated_data['batch_name'],
                start_date=serializer.validated_data['start_date'],
                end_date=serializer.validated_data['end_date'],
inez nabila's avatar
inez nabila committed
993
                shipping_cost=serializer.validated_data['shipping_cost'],
994
995
996
997
998
999
1000
            )
        else:
            raise rest_framework_exceptions.PermissionDenied(_(
                'Start Date must be earlier than End Date.'
            ))
        return response.Response(
            {'id': batch.id},
For faster browsing, not all history is shown. View entire blame