-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathviews.py
950 lines (745 loc) · 30.9 KB
/
views.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
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
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
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
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
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
886
887
888
889
890
891
892
893
894
895
896
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
950
import json
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.db import transaction
from django.http import HttpResponseRedirect, Http404
from django.http.response import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import CreateView
from django.views.generic import DetailView
from django.views.generic import ListView
from django.views.generic import TemplateView
from django.views.generic import UpdateView
from rest_framework import permissions
from rest_framework.views import APIView
from .forms import *
from qux.seo.mixin import SEOMixin
from .models import *
def default_n_disable_plan_products(user):
plan_products = Product.plan_queryset()
# get last paid plan
last_plan_prod = InvoiceProduct.objects.filter(
invoice__customer__primary_contact=user,
product__category__iexact='plan',
product__amount__gte=1,
invoice__payment__is_processed=True
).order_by('id').last()
last_plan_product_id = None
if last_plan_prod and plan_products.filter(id=last_plan_prod.product.id).exists():
last_plan_product_id = last_plan_prod.product.id
disabled_plan_products = []
if last_plan_product_id:
for plan_product in plan_products:
if plan_product.id == last_plan_product_id:
break
else:
disabled_plan_products.append(plan_product.id)
return last_plan_product_id, disabled_plan_products
class PaymentHome(LoginRequiredMixin, SEOMixin, TemplateView):
template_name = 'home.html'
extra_context = {
'breadcrumbs': ['Home']
}
class AddressListView(LoginRequiredMixin, PermissionRequiredMixin, ListView):
model = Address
queryset = Address.objects.all()
template_name = 'address/address_list.html'
fields = ['name', ]
extra_context = {
'breadcrumbs': ['Address'],
}
permission_required = ('core.view_address', )
def get_queryset(self):
queryset = Address.objects.all().order_by('-id')
user = self.request.user
if not user.is_staff and not user.is_superuser:
queryset = queryset.filter(
user=user
)
return queryset
class AddressCreateView(LoginRequiredMixin, PermissionRequiredMixin, CreateView):
model = Address
form_class = AddressForm
template_name = 'address/address_form.html'
permission_required = ('core.add_address', )
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['form_title'] = 'Create Address.'
context['submit_btn_text'] = 'Create'
return context
def get_success_url(self, *args, **kwargs):
return reverse('customer:address_home')
class AddressUpdateView(LoginRequiredMixin, PermissionRequiredMixin, UpdateView):
model = Address
form_class = AddressForm
template_name = 'address/address_form.html'
permission_required = ('core.change_address', )
def get_success_url(self, *args, **kwargs):
return reverse('customer:address_home')
class CustomerDetailView(LoginRequiredMixin, DetailView):
model = Customer
template_name = 'customer/customer_detail.html'
def get_object(self):
user = self.request.user
if not user.is_staff and not user.is_superuser:
customer = Customer.objects.get_or_none(
primary_contact=user
)
else:
if 'pk' not in self.kwargs:
raise Http404('URL is not valid')
customer = Customer.objects.get_or_none(pk=self.kwargs['pk'])
# if customer is None:
# raise Http404('Page does not exists')
return customer
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
if self.object:
context['invoices'] = self.object.invoice_set.all().order_by('-id')
context['payments'] = self.object.payment_set.all().order_by('-id')
return context
class InvoiceDetailView(LoginRequiredMixin, DetailView):
model = Invoice
template_name = 'invoice/invoice_item.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['invoice_seller'] = settings.INVOICE_SELLER
context['KYC_GST_PAN_REQUIRED'] = getattr(settings, 'KYC_GST_PAN_REQUIRED', True)
return context
def get_object(self):
user = self.request.user
if not user.is_staff and not user.is_superuser:
invoice = Invoice.objects.get_or_none(
slug=self.kwargs['slug'],
customer__primary_contact=user
)
else:
invoice = Invoice.objects.get_or_none(slug=self.kwargs['slug'])
if invoice is None:
invoice = Invoice()
return invoice
class CustomerListView(LoginRequiredMixin, PermissionRequiredMixin,
ListView):
model = Customer
queryset = Customer.objects.all()
template_name = 'customer/customer_list.html'
fields = ['name', ]
extra_context = {
'breadcrumbs': ['Customer'],
}
permission_required = ('customer.view_customer',)
def get_queryset(self):
queryset = Customer.objects.all().order_by('-id')
user = self.request.user
if not user.is_staff and not user.is_superuser:
queryset = queryset.filter(
primary_contact=user
)
return queryset
class CustomerCreateView(LoginRequiredMixin, PermissionRequiredMixin,
CreateView):
model = Customer
form_class = CustomerForm if settings.KYC_GST_PAN_REQUIRED else ReqCustomerForm if settings.SHIPPING_ADDRESS_REQUIRED else BaseCustomerForm
template_name = 'customer/customer_form.html'
permission_required = ('customer.add_customer', )
extra_context = {
'form_title': 'New Customer',
'submit_btn_text': 'Create'
}
# def get_context_data(self, **kwargs):
# context = super().get_context_data(**kwargs)
# context['form_title'] = 'Create Customer.'
# context['submit_btn_text'] = 'Create'
# return context
def get_success_url(self, *args, **kwargs):
return reverse('customer:customer_home')
class CustomerUpdateView(LoginRequiredMixin, PermissionRequiredMixin,
UpdateView):
model = Customer
form_class = CustomerForm if settings.KYC_GST_PAN_REQUIRED else ReqCustomerForm if settings.SHIPPING_ADDRESS_REQUIRED else BaseCustomerForm
template_name = 'customer/customer_form.html'
permission_required = ('customer.change_customer',)
def get_success_url(self, *args, **kwargs):
return reverse("customer:customer_home")
class InvoiceListView(LoginRequiredMixin, PermissionRequiredMixin,
ListView):
model = Invoice
queryset = Invoice.objects.all()
template_name = 'invoice/invoice_list.html'
fields = ['name', ]
extra_context = {
'breadcrumbs': ['Invoice'],
}
permission_required = ('customer.view_invoice',)
def get_queryset(self):
queryset = Invoice.objects.all().order_by('-id')
user = self.request.user
if not user.is_staff and not user.is_superuser:
queryset = queryset.filter(
customer__primary_contact=user
)
return queryset
class InvoiceCreateView(LoginRequiredMixin, PermissionRequiredMixin,
CreateView):
model = Invoice
form_class = InvoiceForm
template_name = 'invoice/invoice_form.html'
permission_required = ('customer.add_invoice',)
def get_initial(self):
initial = super().get_initial()
initial['invoice_number'] = Invoice.generate_slug()
return initial
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['form_title'] = 'Create Invoice.'
context['submit_btn_text'] = 'Create'
if self.request.POST:
context['items'] = InvoiceProductFormSet(self.request.POST)
else:
context['items'] = InvoiceProductFormSet()
return context
def form_valid(self, form):
context = self.get_context_data()
items = context['items']
with transaction.atomic():
self.object = form.save()
if items.is_valid():
items.instance = self.object
items.save()
else:
print('----items.errors----', items.errors)
return super().form_valid(form)
def get_success_url(self, *args, **kwargs):
return reverse('customer:invoice_home')
class InvoiceUpdateView(LoginRequiredMixin, PermissionRequiredMixin,
UpdateView):
model = Invoice
form_class = InvoiceForm
template_name = 'invoice/invoice_form.html'
permission_required = ('customer.change_invoice',)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['form_title'] = 'Update Invoice.'
context['submit_btn_text'] = 'Update'
if self.request.POST:
context['items'] = InvoiceProductFormSet(
self.request.POST, instance=self.object)
else:
context['items'] = InvoiceProductFormSet(instance=self.object)
return context
def form_valid(self, form):
context = self.get_context_data()
items = context['items']
with transaction.atomic():
self.object = form.save()
if items.is_valid():
items.instance = self.object
items.save()
return super().form_valid(form)
def get_success_url(self, *args, **kwargs):
return reverse("customer:invoice_home")
class UserInvoiceListView(LoginRequiredMixin, SEOMixin, ListView):
canonical_url = '/invoice/list/'
model = Invoice
queryset = Invoice.objects.all()
template_name = 'invoice/invoice_list.html'
extra_context = {
'breadcrumbs': ['Invoice'],
}
# permission_required = ('customer.view_invoice', )
def get_queryset(self):
user = self.request.user
queryset = Invoice.objects.filter(customer__primary_contact=user).order_by('-id')
return queryset
class PaymentListView(LoginRequiredMixin, PermissionRequiredMixin,
ListView):
model = Payment
queryset = Payment.objects.all()
template_name = 'payment/payment_list.html'
fields = ['name', ]
extra_context = {
'breadcrumbs': ['Payment'],
}
permission_required = ('customer.view_payment',)
def get_queryset(self):
queryset = Payment.objects.all().order_by('-id')
user = self.request.user
if not user.is_staff and not user.is_superuser:
queryset = queryset.filter(
customer__primary_contact=user
)
return queryset
class PaymentCreateView(LoginRequiredMixin,
PermissionRequiredMixin,
TemplateView):
model = Payment
form_class = PaymentForm
template_name = 'payment/payment_form.html'
permission_required = ('customer.add_payment',)
def get(self, request, *args, **kwargs):
form = self.form_class()
form.fields['cart'].queryset = Cart.objects.filter(is_open=True)
context_dict = {
'form_title': 'New Payment',
'submit_btn_text': 'Create',
'form': form
}
return render(request, self.template_name, context=context_dict)
def post(self, request, *args, **kwargs):
form = self.form_class(data=request.POST)
if form.is_valid():
data = form.cleaned_data
cart = data.pop('cart')
invoice = Invoice.create(cart)
payment = Payment.create(invoice)
[setattr(payment, k, v) for k, v in data.items() if k in payment.__dict__]
payment.save()
return HttpResponseRedirect(reverse('customer:payment_home'))
context_dict = {
'form_title': 'New Payment',
'submit_btn_text': 'Create',
'form': form
}
return render(request, self.template_name, context=context_dict)
class PaymentUpdateView(LoginRequiredMixin, PermissionRequiredMixin, TemplateView):
model = Payment
form_class = UpdatePaymentForm
template_name = 'payment/payment_form.html'
permission_required = ('customer.change_payment', )
def get(self, request, slug, *args, **kwargs):
payment = Payment.objects.get_or_none(slug=slug)
if not payment or not payment.invoice.cart:
raise Http404('Cart is not exists')
initial = payment.to_dict()
initial['cart'] = payment.invoice.cart.id
form = self.form_class(initial=initial)
if 'cart' in form.fields:
form.fields['cart'].queryset = Cart.objects.filter(id=payment.invoice.cart.id)
context_dict = {
'form_title': 'Update Payment',
'submit_btn_text': 'Update',
'form': form
}
return render(request, self.template_name, context=context_dict)
def post(self, request, slug, *args, **kwargs):
payment = Payment.objects.get_or_none(slug=slug)
if not payment:
raise Http404('Cart is not exists')
form = self.form_class(data=request.POST)
if form.is_valid():
data = form.cleaned_data
[setattr(payment, k, v) for k, v in data.items() if k in payment.__dict__]
payment.save()
return HttpResponseRedirect(reverse('customer:payment_home'))
context_dict = {
'form_title': 'Update Payment',
'submit_btn_text': 'Update',
'form': form
}
return render(request, self.template_name, context=context_dict)
class PaymentDetailView(LoginRequiredMixin, DetailView):
model = Payment
template_name = 'payment/payment_item.html'
def get_object(self):
user = self.request.user
if not user.is_staff and not user.is_superuser:
payment = Payment.objects.get_or_none(
slug=self.kwargs['slug'],
customer__primary_contact=user
)
else:
payment = Payment.objects.get_or_none(slug=self.kwargs['slug'])
if payment is None:
payment = Payment()
return payment
class UserPaymentListView(LoginRequiredMixin, SEOMixin, ListView):
canonical_url = '/payment/list/'
model = Payment
queryset = Payment.objects.all()
template_name = 'payment/user_payment_list.html'
extra_context = {
'breadcrumbs': ['Payment'],
}
# permission_required = ('customer.view_invoice', )
def get_queryset(self):
user = self.request.user
queryset = Payment.objects.filter(customer__primary_contact=user).order_by('-id')
return queryset
@login_required
def getcustomers(request):
if not request.user.is_superuser:
return
cust_data = []
search = request.GET.get('q', None)
if search:
cust_data = Customer.objects.filter(Q(name__icontains=search) | Q(
primary_contact__email__icontains=search)).values('id', 'name')
return JsonResponse(list(cust_data), safe=False)
@login_required
def getinvoice_by_customer(request, customer_id: int):
if not request.user.is_superuser:
return
invoices = Invoice.objects.filter(customer=customer_id).order_by('-id')
# invoices_data = list(invoices.values('id', 'invoice_number'))
invoices_data = [{'id': i.id, 'invoice_number': i.__str__()} for i in invoices]
return JsonResponse({'data': invoices_data})
@login_required
def getopen_cart_by_customer(request, customer_id: int):
if not request.user.is_superuser:
return
carts = Cart.objects.filter(customer=customer_id, is_open=True).order_by('-id')
carts_data = [{'id': i.id, 'name': '%s %s' % (i.slug, i.total_amount)} for i in carts]
return JsonResponse({'data': carts_data})
@login_required
def getuserdetails(request, user_id: int):
if not request.user.is_superuser:
return
user = User.objects.get(pk=user_id)
address = Address.objects.filter(user=user_id).order_by('-id')
address_data = list(address.values('id', 'address', 'city'))
json_data = {
'addresses': address_data,
'phone': user.profile.phone,
'email': user.email,
}
return JsonResponse(json_data)
@login_required
def getproduct_by_id(request, product_id: int):
# if not request.user.is_superuser:
# return
prod = Product.objects.get(pk=product_id)
gst = prod.amount * settings.PRODUCT_GST_PERCENT / 100
json_data = {
'amount': round(prod.amount, 2),
'gst': round(gst, 2),
'category': prod.category,
'addon_id': prod.addon.id if prod.addon else None,
'addon_description': prod.addon.description if prod.addon else None,
}
return JsonResponse(json_data)
@login_required
@csrf_exempt
def cart_validation(request, customer_id: int):
customer = Customer.objects.get(pk=customer_id)
check_for = request.POST.get('check_for')
products = request.POST.getlist('products', [])
products = list(map(int, products))
products_qr = Product.objects.filter(
id__in=products, category="plan"
)
json_data = {}
if check_for == 'has-paid-plan':
has_active_paid = InvoiceProduct.objects.filter(
invoice__customer=customer,
product__category__iexact='plan',
product__amount__gte=1,
invoice__payment__is_processed=True
).exists()
paid_item_selected = products_qr.filter(amount__gte=1).exists()
json_data['paid_plan_found'] = has_active_paid or paid_item_selected
elif check_for == 'has-more-plan-item':
json_data['has_more_plan_item'] = True if products_qr.count() >= 2 else False
return JsonResponse(json_data)
class KYCView(LoginRequiredMixin, SEOMixin, TemplateView):
model = Customer
form_class = KYCForm if settings.KYC_GST_PAN_REQUIRED else ReqKYCForm if settings.SHIPPING_ADDRESS_REQUIRED else BaseKYCForm
template_name = 'customer/kyc_form.html'
def get_initial(self, request, user):
initial = {
'contact_name': user.first_name + ' ' + user.last_name if user.first_name and
user.last_name else
user.first_name,
'phone': user.profile.phone,
'email': user.email,
}
cust = Customer.objects.get_or_none(primary_contact=user)
if cust:
initial.update({
'slug': cust.slug,
'name': cust.name,
'contact_name': cust.contact_name,
'phone': cust.phone,
'email': cust.email,
'gstin': cust.gstin,
'pan': cust.pan,
})
if cust.billing_address:
initial.update({
'billing_address': cust.billing_address.address,
'billing_city': cust.billing_address.city,
'billing_state': cust.billing_address.state,
'billing_pincode': cust.billing_address.pincode,
'billing_country': cust.billing_address.country,
})
if cust.shipping_address:
initial.update({
'shipping_address': cust.shipping_address.address,
'shipping_city': cust.shipping_address.city,
'shipping_state': cust.shipping_address.state,
'shipping_pincode': cust.shipping_address.pincode,
'shipping_country': cust.shipping_address.country,
})
if cust.billing_address_id == cust.shipping_address_id:
initial.update({
'same_as_billing_address': True,
})
else:
initial.update({
'same_as_billing_address': False,
})
return initial
def get(self, request, userid=None, *args, **kwargs):
user = request.user
if userid and (user.is_staff or user.is_superuser):
user = User.objects.get(pk=userid)
initial = self.get_initial(request, user)
form = self.form_class(user, initial=initial)
# del form.fields["same_as_billing_address"]
context_dict = {
'form_title': 'KYC.',
'submit_btn_text': 'Submit',
'first_name': user.first_name,
'last_name': user.last_name,
'slug': initial.get('slug', None),
'form': form
}
return render(request, self.template_name, context=context_dict)
def post(self, request, userid=None, *args, **kwargs):
user = request.user
if userid and (user.is_staff or user.is_superuser):
user = User.objects.get(pk=userid)
form = self.form_class(user, data=request.POST)
if form.is_valid():
data = form.cleaned_data
billing_address, created = Address.objects.get_or_create(
user=user,
address=data.get('billing_address', None),
city=data.get('billing_city', None),
state=data.get('billing_state', None),
country=data.get('billing_country', None),
pincode=data.get('billing_pincode', None),
)
same_as_billing_address = data.get('same_as_billing_address', True)
shipping_address = None
if same_as_billing_address:
shipping_address = billing_address
else:
shipping_address, created = Address.objects.get_or_create(
user=user,
address=data.get('shipping_address', None),
city=data.get('shipping_city', None),
state=data.get('shipping_state', None),
country=data.get('shipping_country', None),
pincode=data.get('shipping_pincode', None),
)
customer_obj = Customer.objects.get_or_none(primary_contact=user)
if not customer_obj:
customer_obj, created = Customer.objects.get_or_create(
primary_contact=user,
)
json_data = dict(
email=data.get('email', None),
phone=data.get('phone', None),
name=data.get('name', None),
contact_name=data.get('contact_name', None),
gstin=data.get('gstin', None),
pan=data.get('pan', None),
billing_address=billing_address,
shipping_address=shipping_address,
)
for key, value in json_data.items():
setattr(customer_obj, key, value)
customer_obj.users.add(user)
customer_obj.save()
next = request.GET.get('next', None)
if next and ((settings.KYC_GST_PAN_REQUIRED is False and customer_obj.billing_address is not None) or
(customer_obj.gstin not in ['', None] or customer_obj.pan not in ['', None])):
return HttpResponseRedirect(next)
# messages.success(request, "KYC saved successfully")
context_dict = {
'form_title': 'KYC.',
'submit_btn_text': 'Submit',
'first_name': user.first_name,
'last_name': user.last_name,
'form': form
}
return render(request, self.template_name, context=context_dict)
class CartListView(LoginRequiredMixin, PermissionRequiredMixin, ListView):
model = Cart
queryset = Cart.objects.all()
template_name = 'cart/cart_list.html'
fields = ['name', ]
extra_context = {
'breadcrumbs': ['Cart'],
}
permission_required = ('customer.view_cart',)
def get_queryset(self):
queryset = Cart.objects.all().order_by('-dtm_updated')
user = self.request.user
if not user.is_staff and not user.is_superuser:
queryset = queryset.filter(
customer__primary_contact=user
)
return queryset
class CartCreateView(LoginRequiredMixin, PermissionRequiredMixin,
CreateView):
model = Cart
form_class = CartForm
template_name = 'cart/cart_form.html'
permission_required = ('customer.add_cart',)
def get_initial(self):
initial = super().get_initial()
initial['slug'] = Cart.generate_slug()
initial['invoice_number'] = Invoice.generate_slug()
return initial
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['form_title'] = 'Create Cart.'
context['submit_btn_text'] = 'Create'
if self.request.POST:
context['items'] = CartProductFormSet(self.request.POST)
else:
context['items'] = CartProductFormSet()
return context
def form_valid(self, form):
context = self.get_context_data()
items = context['items']
with transaction.atomic():
self.object = form.save()
if items.is_valid():
items.instance = self.object
items.save()
else:
print('----items.errors----', items.errors)
self.object.reset_items()
return super().form_valid(form)
def get_success_url(self, *args, **kwargs):
return reverse('customer:cart_home')
class CartItemPage(LoginRequiredMixin, SEOMixin, TemplateView):
model = Cart
template_name = 'cart/cart_item_page.html'
extra_context = {
'form_title': 'Cart',
'submit_btn_text': 'Save'
}
def get_object(self):
cart = getcart(self.request, **self.kwargs)
return cart
def dispatch(self, request, *args, **kwargs):
user = self.request.user
if not user.is_authenticated:
nextitem = '?next='+reverse('customer:cart_edit')
return HttpResponseRedirect(reverse('login')+nextitem)
# if not user.is_staff and not user.is_superuser:
customer = get_customer(user)
if not customer or (settings.KYC_GST_PAN_REQUIRED and customer.gstin is None and customer.pan is None) or (settings.KYC_GST_PAN_REQUIRED is False and customer.billing_address is None):
nextitem = '?next='+reverse('customer:cart_edit')
return HttpResponseRedirect(reverse('customer:account_kyc')+nextitem)
if not self.get_object():
customer = get_customer(user)
cart, created = Cart.objects.get_or_create(
is_open=True,
customer=customer,
)
return super().dispatch(request, *args, **kwargs)
def get_json_data(self):
user = self.request.user
products = Product.default_queryset()
cart = self.get_object()
print('cart id =', cart.id)
plan_products = Product.plan_queryset()
last_plan_product_id, disabled_plan_products = default_n_disable_plan_products(user)
data = {
"cart": cart,
# "has_existing_paid_plan": has_existing_paid_plan,
"last_plan_product_id": last_plan_product_id,
"disabled_plan_products": disabled_plan_products,
"products": {
"plan": plan_products,
"minutes": products.filter(category="minutes"),
"agent": products.filter(category="feature", sku__istartswith="AGENT").last(),
"recording": products.filter(category="feature", sku__istartswith="RECORD").last(),
}
}
checkout_json = {
"plan": {},
}
for item in cart.items.all():
key = item.product.id
category = item.product.category.lower()
if category in ["plan"]:
checkout_json[category][key] = {"qty": item.qty}
# if plan is not added in cart then add default plan product check if no paid plan exists with customer
if len(checkout_json["plan"]) == 0:
plan_product_id = None
# choose last purchased plan if exists
if last_plan_product_id:
plan_product_id = last_plan_product_id
# choose plan product based on category if exists
if not plan_product_id:
config_product = plan_products.order_by('id').last()
if config_product:
plan_product_id = config_product.id
# choose last plan product
if not plan_product_id and plan_products:
plan_product_id = plan_products.last().id
if plan_product_id:
checkout_json["plan"][plan_product_id] = {"qty": 1}
data["initial"] = checkout_json
print("checkout_json =", checkout_json)
return data
def get(self, request, *args, **kwargs):
data = self.get_json_data()
context = self.get_context_data(**kwargs)
data.update(context)
return render(request, self.template_name, data)
def post(self, request, *args, **kwargs):
user = self.request.user
data = json.loads(request.body)
print(f'post data = {data}')
submit_btn = data.pop('submit', '')
cart = self.get_object()
print('cart id =', cart.id)
cart.items.all().delete()
for cat, val in data.items():
for p_id, jsn in val.items():
qty = jsn["qty"]
product = Product.objects.get(pk=p_id)
item = cart.create_item(
product,
qty
)
json_data = {'success': True}
if 'payment' == submit_btn and cart.total_amount >= 1:
# amount should be mroe than 1
json_data['next'] = reverse("customer:payment", kwargs={'slug': cart.slug})
elif not user.is_staff and not user.is_superuser:
json_data['next'] = reverse("customer:cart_edit")
else:
json_data['next'] = reverse("customer:cart_home")
return JsonResponse(json_data)
def get_customer(user):
customer = Customer.objects.get_or_none(primary_contact=user)
return customer
def getcart(request, **kwargs):
user = request.user
if (user.is_staff or user.is_superuser) and ('pk' in kwargs):
cartid = kwargs['pk']
cart = Cart.objects.get_or_none(pk=cartid)
else:
customer = get_customer(user)
cart = Cart.get_cart_object(customer)
if cart:
cart.remove_inactive_product()
return cart
class UserAutocomplete(APIView):
permission_classes = (permissions.IsAuthenticated,)
def get(self, request, format=None):
user_data = []
search = request.GET.get('q', None)
if search:
user_data = User.objects.filter(Q(first_name__icontains=search) | Q(
email__icontains=search)).values('id', 'email')
return JsonResponse(list(user_data), safe=False)