Fakultas Ilmu Komputer UI

views.py 39.6 KB
Newer Older
1

WILLIAM GATES's avatar
WILLIAM GATES committed
2
from django import http, shortcuts
3
4
5
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
6
from django.utils import timezone
7
8
9
10
11
12
13
14
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
WILLIAM GATES's avatar
WILLIAM GATES committed
15

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'
        )
inez nabila's avatar
Try Fix    
inez nabila committed
175
176
        batch = (
            None if serializer.validated_data['payment_method'] == 'TRF'
inez nabila's avatar
inez nabila committed
177
            else models.Batch.objects.filter(
inez nabila's avatar
inez nabila committed
178
                start_date__lte=timezone.now().date(),
inez nabila's avatar
inez nabila committed
179
                end_date__gte=timezone.now().date()).first()
inez nabila's avatar
Try Fix    
inez nabila committed
180
        )
181
182
183
        transaction = models.Transaction.objects.create(
            user=user,
            payment_method=serializer.validated_data['payment_method'],
WILLIAM GATES's avatar
WILLIAM GATES committed
184
            donation=serializer.validated_data['donation'],
185
            transaction_status=transaction_status,
186
        )
inez nabila's avatar
inez nabila committed
187

188
189
190
191
192
193
194
        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
195
                        product.total_profit += cart_item.quantity*product.profit
196
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
                        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
223
224
225
226
        bank_account_transfer_destination = shortcuts.get_object_or_404(
            models.BankAccountTransferDestination,
            id=serializer.validated_data['bank_account_transfer_destination']
        )
227
228
229
230
231
232
233
234
235
236
237
238
239
240
        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
241
        transaction.user_bank_name = serializer.validated_data['user_bank_name']
242
        transaction.user_bank_account_name = serializer.validated_data['user_bank_account_name']
WILLIAM GATES's avatar
WILLIAM GATES committed
243
244
        transaction.bank_account_transfer_destination = bank_account_transfer_destination
        transaction.update_bank_account_transfer_destination = True
245
        transaction.transaction_status = '002'
inez nabila's avatar
inez nabila committed
246
        transaction.batch = models.Batch.objects.filter(
inez nabila's avatar
inez nabila committed
247
            start_date__lte=timezone.now().date(),
inez nabila's avatar
inez nabila committed
248
            end_date__gte=timezone.now().date()).first()
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
        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
266
            user=request.user
267
268
        )
        if transaction.transaction_status != '004':
WILLIAM GATES's avatar
WILLIAM GATES committed
269
            raise rest_framework_exceptions.PermissionDenied(_(
WILLIAM GATES's avatar
WILLIAM GATES committed
270
                'Transaction cannot be completed unless the status is "Being shipped".'
WILLIAM GATES's avatar
WILLIAM GATES committed
271
            ))
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
        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
294
295
296
            raise rest_framework_exceptions.PermissionDenied(_(
                'Transaction cannot be canceled at this stage.'
            ))
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
        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
319
        if not program.open_donation:
WILLIAM GATES's avatar
WILLIAM GATES committed
320
            raise rest_framework_exceptions.PermissionDenied(_(
WILLIAM GATES's avatar
WILLIAM GATES committed
321
                'This program is currently not accepting donations.'
WILLIAM GATES's avatar
WILLIAM GATES committed
322
            ))
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
        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
339

340
        else:
341
342
            if serializer.validated_data['delivery_method'] == 'DLV':
                program_donation = models.ProgramDonation.objects.create(
inez nabila's avatar
inez nabila committed
343
344
345
346
347
348
349
350
                    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
                )
351
352
353
354
355
356
357
358
359
360
            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']
                )
361

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


368

369
370
371
372
373
374
375
376
377
378
379
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
380
381
382
383
        bank_account_transfer_destination = shortcuts.get_object_or_404(
            models.BankAccountTransferDestination,
            id=serializer.validated_data['bank_account_transfer_destination']
        )
384
385
386
387
388
389
390
391
392
        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.'
            ))
393
394
395
396
        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
397
        program_donation.amount = serializer.validated_data['amount']
398
399
400
        program_donation.proof_of_bank_transfer = (
            serializer.validated_data['proof_of_bank_transfer']
        )
WILLIAM GATES's avatar
WILLIAM GATES committed
401
        program_donation.user_bank_name = serializer.validated_data['user_bank_name']
402
403
404
        program_donation.user_bank_account_name = (
            serializer.validated_data['user_bank_account_name']
        )
WILLIAM GATES's avatar
WILLIAM GATES committed
405
406
        program_donation.bank_account_transfer_destination = bank_account_transfer_destination
        program_donation.update_bank_account_transfer_destination = True
407
408
409
410
411
        program_donation.donation_status = '001'
        program_donation.save()
        return response.Response(status=status.HTTP_204_NO_CONTENT)


WILLIAM GATES's avatar
WILLIAM GATES committed
412
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
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
444
            'Transaction Report from {date_from} to {date_to} for {batch_name}'
WILLIAM GATES's avatar
WILLIAM GATES committed
445
        ).format(
WILLIAM GATES's avatar
WILLIAM GATES committed
446
            date_from=query_params.get('created_at_date_range_after', '_'),
447
448
            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
449
450
451
452
        ))
        return filename


Rayhan Muzakki's avatar
Pbi5    
Rayhan Muzakki committed
453
454
class ReportProgramDonationCSH(ReportAPIView):
    report_function = reports_writer.create_program_donation_report_CSH
WILLIAM GATES's avatar
WILLIAM GATES committed
455
456
457
458
459
460
461
    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
462
            date_from=query_params.get('created_at_date_range_after', '_'),
WILLIAM GATES's avatar
WILLIAM GATES committed
463
464
465
466
            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
467
468
class ReportProgramDonationGDS(ReportAPIView):
    report_function = reports_writer.create_program_donation_report_GDS
WILLIAM GATES's avatar
WILLIAM GATES committed
469
470
471
472
473
474
475
    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
476
            date_from=query_params.get('created_at_date_range_after', '_'),
WILLIAM GATES's avatar
WILLIAM GATES committed
477
478
479
480
481
            date_to=query_params.get('created_at_date_range_before', str(timezone.now())[:10])
        ))
        return filename


482
483
484
485
486
487
488
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
489
490
491
    ordering_fields = [
        'username', 'full_name', 'phone_number',
        'number_of_transactions', 'number_of_cash_donations', 'number_of_goods_donations'
inez nabila's avatar
fixing    
inez nabila committed
492
    ]
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
629
630
631
632
633
634
    def post(self, request, _format=None):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        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'],
635
636
            subcategory= models.Subcategory.objects.get(name=serializer.validated_data['subcategory']),
            total_profit=0
637
        )
638
        product.profit= (product.price- product.modal)
639
640
641
642
643
644
        product.save()
        return response.Response(
            {'id': product.id},
            status=status.HTTP_201_CREATED
        )

645
646
647
648
649
650
651
652

class ProductDetail(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = [
        api_permissions.IsAdminUserOrReadOnly,
        rest_framework_permissions.IsAuthenticated,
    ]
    queryset = models.Product.objects.all()
    serializer_class = api_serializers.ProductSerializer
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670

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:
671
            raise rest_framework_exceptions.NotFound(_(
672
673
674
                'Program not found.'
            ))
        return program
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694


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
695
        if self.kwargs.get('pk') == 'self':
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
            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
758
    search_fields = ['code', 'name']
759
760
761
    serializer_class = api_serializers.ProgramSerializer


WILLIAM GATES's avatar
WILLIAM GATES committed
762
763
764
765
766
767
768
769
class ProgramDetail(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = [
        api_permissions.IsAdminUserOrReadOnly,
        rest_framework_permissions.IsAuthenticated,
    ]
    queryset = models.Program.objects.all()
    serializer_class = api_serializers.ProgramSerializer

770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
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

WILLIAM GATES's avatar
WILLIAM GATES committed
791

792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
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
812

813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
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
832
        return queryset
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885

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
886
class HelpContactConfigDetail(generics.RetrieveUpdateAPIView):
887
    permission_classes = [api_permissions.IsAdminUserOrReadOnly]
WILLIAM GATES's avatar
WILLIAM GATES committed
888
889
    queryset = models.HelpContactConfig.objects.all()
    serializer_class = api_serializers.HelpContactConfigSerializer
890
891

    def get_object(self):
WILLIAM GATES's avatar
WILLIAM GATES committed
892
        obj = shortcuts.get_object_or_404(models.HelpContactConfig)
893
894
895
896
897
898
899
900
901
902
903
        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
904
905
906
907
908
909
910

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

inez nabila's avatar
inez nabila committed
912
913
914
915
916
917
918
919
920
    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

921
922
923
    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
924
        if serializer.validated_data['start_date'] < serializer.validated_data['end_date']:
925
926
927
928
            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
929
                shipping_cost=serializer.validated_data['shipping_cost'],
930
931
932
933
934
935
936
937
938
939
            )
        else:
            raise rest_framework_exceptions.PermissionDenied(_(
                'Start Date must be earlier than End Date.'
            ))
        return response.Response(
            {'id': batch.id},
            status=status.HTTP_201_CREATED
        )

inez nabila's avatar
inez nabila committed
940
941
942
943
944
    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
inez nabila's avatar
inez nabila committed
945

inez nabila's avatar
inez nabila committed
946
947
948
949
950
class BatchDetail(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = [
        api_permissions.IsAdminUserOrReadOnly,
        rest_framework_permissions.IsAuthenticated,
    ]
951
    queryset = models.Batch.objects.all()
952
    serializer_class = api_serializers.BatchSerializer
inez nabila's avatar
inez nabila committed
953
954
955
956
957
958
959
960
961
962
963

class BatchCreate(rest_framework_views.APIView):
    permission_classes = [rest_framework_permissions.IsAuthenticated]
    serializer_class = api_serializers.BatchCreateSerializer

    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)
inez nabila's avatar
inez nabila committed
964
965

        if serializer.validated_data['start_date'] < serializer.validated_date['end_date']:
966
967
968
969
            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
970
                shipping_cost=serializer.validated_data['shipping_cost'],
971
972
973
974
975
            )
        else:
            raise rest_framework_exceptions.PermissionDenied(_(
                'Start Date must be earlier than End Date.'
            ))
inez nabila's avatar
inez nabila committed
976
977
978
979
        return response.Response(
            {'id': batch.id},
            status=status.HTTP_201_CREATED
        )