forked from CTI-CodeDay/WeVoteServer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodels.py
2137 lines (1914 loc) · 100 KB
/
models.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
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# stripe_donations/models.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
import textwrap
from datetime import datetime, timezone
import stripe
from django.db import models, transaction
from django.db.models import Sum, Q
import wevote_functions.admin
from exception.models import handle_exception, handle_record_found_more_than_one_exception
from voter.models import VoterManager
from wevote_functions.functions import positive_value_exists
# from organization.models import CHOSEN_FAVICON_ALLOWED, CHOSEN_FULL_DOMAIN_ALLOWED, CHOSEN_GOOGLE_ANALYTICS_ALLOWED, \
# CHOSEN_SOCIAL_SHARE_IMAGE_ALLOWED, CHOSEN_SOCIAL_SHARE_DESCRIPTION_ALLOWED, CHOSEN_PROMOTED_ORGANIZATIONS_ALLOWED
logger = wevote_functions.admin.get_logger(__name__)
# SAME_DAY_MONTHLY = 'SAME_DAY_MONTHLY'
# SAME_DAY_ANNUALLY = 'SAME_DAY_ANNUALLY'
# BILLING_FREQUENCY_CHOICES = ((SAME_DAY_MONTHLY, 'SAME_DAY_MONTHLY'),
# (SAME_DAY_ANNUALLY, 'SAME_DAY_ANNUALLY'))
# CURRENCY_USD = 'usd'
# CURRENCY_CAD = 'cad'
# CURRENCY_CHOICES = ((CURRENCY_USD, 'usd'),
# (CURRENCY_CAD, 'cad'))
# FREE = 'FREE'
# PROFESSIONAL_MONTHLY = 'PROFESSIONAL_MONTHLY'
# PROFESSIONAL_YEARLY = 'PROFESSIONAL_YEARLY'
# PROFESSIONAL_PAID_WITHOUT_STRIPE = 'PROFESSIONAL_PAID_WITHOUT_STRIPE'
# ENTERPRISE_MONTHLY = 'ENTERPRISE_MONTHLY'
# ENTERPRISE_YEARLY = 'ENTERPRISE_YEARLY'
# ENTERPRISE_PAID_WITHOUT_STRIPE = 'ENTERPRISE_YEARLY'
# ORGANIZATION_PLAN_OPTIONS = (
# (FREE, 'FREE'),
# (PROFESSIONAL_MONTHLY, 'PROFESSIONAL_MONTHLY'),
# (PROFESSIONAL_YEARLY, 'PROFESSIONAL_YEARLY'),
# (PROFESSIONAL_PAID_WITHOUT_STRIPE, 'PROFESSIONAL_PAID_WITHOUT_STRIPE'),
# (ENTERPRISE_MONTHLY, 'ENTERPRISE_MONTHLY'),
# (ENTERPRISE_YEARLY, 'ENTERPRISE_YEARLY'),
# (ENTERPRISE_PAID_WITHOUT_STRIPE, 'ENTERPRISE_PAID_WITHOUT_STRIPE'))
# Stripes currency support https://support.stripe.com/questions/which-currencies-does-stripe-support
class StripeLinkToVoter(models.Model):
"""
This table links voter_we_vote_ids with Stripe customer IDs. A row is created when a stripe donation is made for the
first time.
"""
# The unique customer id from a stripe donation
stripe_customer_id = models.CharField(verbose_name="stripe unique customer id", max_length=255,
null=False, blank=False)
# There are scenarios where a voter_we_vote_id might have multiple customer_id's
voter_we_vote_id = models.CharField(verbose_name="unique we vote user id", max_length=255, unique=False, null=False,
blank=False)
class StripeSubscription(models.Model):
"""
This table tracks subscriptions (recurring donations) and donations
"""
objects = None
DoesNotExist = None
we_plan_id = models.CharField(verbose_name="donation plan name", max_length=64, null=False, blank=True)
stripe_subscription_id = models.CharField(verbose_name="Stripe subscription id", max_length=32, null=True,
blank=True)
voter_we_vote_id = models.CharField(
verbose_name="we vote permanent id of the person who created this subscription",
max_length=64, default='', null=True, blank=True, unique=False, db_index=True)
not_loggedin_voter_we_vote_id = models.CharField(verbose_name="unique we vote user id", max_length=32, default='',
unique=False, null=True, blank=True)
stripe_customer_id = models.CharField(verbose_name="stripe customer id", max_length=32, null=True, blank=True)
# Stripe uses integer pennies for amount (ex: 2000 = $20.00)
amount = models.PositiveIntegerField(verbose_name="recurring donation amount", default=0, null=False)
billing_interval = models.CharField(verbose_name="recurring donation frequency", max_length=64, default="month",
null=False)
currency = models.CharField(verbose_name="currency", max_length=64, default="usd", null=False)
donation_plan_is_active = models.BooleanField(verbose_name="status of recurring donation plan", default=True,)
subscription_created_at = models.DateTimeField(verbose_name="stripe subscription creation timestamp",
auto_now=False, auto_now_add=False, null=True)
subscription_canceled_at = models.DateTimeField(verbose_name="stripe subscription canceled timestamp",
auto_now=False, auto_now_add=False, null=True)
subscription_ended_at = models.DateTimeField(verbose_name="stripe subscription ended timestamp", auto_now=False,
auto_now_add=False, null=True)
stripe_charge_id = models.CharField(verbose_name="Stripe charge id", max_length=32, null=True, blank=True)
last_charged = models.DateTimeField(verbose_name="stripe subscription most recent charge timestamp", auto_now=False,
auto_now_add=False, null=True)
brand = models.CharField(verbose_name="the brand of the credit card, eg. Visa, Amex", max_length=32, default="",
null=True, blank=True)
exp_month = models.PositiveIntegerField(verbose_name="the expiration month of the credit card", default=0,
null=False)
exp_year = models.PositiveIntegerField(verbose_name="the expiration year of the credit card", default=0, null=False)
last4 = models.PositiveIntegerField(verbose_name="the last 4 digits of the credit card", default=0, null=False)
# campaignx_we_vote_id = models.CharField(max_length=64, null=True)
# campaign_title = models.CharField(verbose_name="title of campaign", max_length=255, null=False, blank=False)
stripe_request_id = models.CharField(verbose_name="stripe initial request id", max_length=32, null=True, blank=True)
linked_organization_we_vote_id = models.CharField(
verbose_name="we vote permanent id of the organization who benefits from the organization subscription, "
"but does not include the organizations that get credif for Chip Ins",
max_length=64, default=None, null=True, blank=True, unique=False, db_index=True)
api_version = models.CharField(verbose_name="Stripe API Version", max_length=32, null=True, blank=True)
livemode = models.BooleanField(verbose_name="True: Live transaction, False: Test transaction", default=False,
blank=False)
client_ip = models.CharField(verbose_name="Client IP address as seen by Stripe", max_length=32,
null=True, blank=True)
class StripePayments(models.Model):
"""
This table tracks donation, subscription plans and refund activity
"""
objects = None
DoesNotExist = None
voter_we_vote_id = models.CharField(verbose_name="unique we vote user id", max_length=32, unique=False, null=True,
default='', blank=True)
not_loggedin_voter_we_vote_id = models.CharField(verbose_name="unique we vote user id", max_length=32, unique=False,
null=True, default='', blank=True)
stripe_customer_id = models.CharField(verbose_name="stripe unique customer id", max_length=32,
null=True, blank=True)
stripe_charge_id = models.CharField(verbose_name="unique charge id per specific donation", max_length=32,
default="", null=True, blank=True)
stripe_card_id = models.CharField(verbose_name="unique id for a credit/debit card", max_length=32, default="",
null=True, blank=True)
stripe_request_id = models.CharField(verbose_name="stripe initial request id", max_length=32, null=True, blank=True)
stripe_subscription_id = models.CharField(
verbose_name="unique subscription id for one voter, amount, and creation time",
max_length=32, default="", null=True, blank=True)
amount = models.PositiveIntegerField(verbose_name="donation amount", default=0, null=True)
currency = models.CharField(verbose_name="donation currency country code", max_length=8, default="", null=True,
blank=True)
funding = models.CharField(verbose_name="stripe returns 'credit' also might be debit, etc", max_length=32,
default="", null=True, blank=True)
livemode = models.BooleanField(verbose_name="True: Live transaction, False: Test transaction", default=False,
blank=True)
action_taken = models.CharField(verbose_name="action taken", max_length=64, default="", null=True, blank=True)
action_result = models.CharField(verbose_name="action result", max_length=64, default="", null=True, blank=True)
created = models.DateTimeField(verbose_name="stripe record creation timestamp", auto_now=False,
auto_now_add=False)
failure_code = models.CharField(verbose_name="failure code reported by stripe", max_length=32, default="",
null=True, blank=True)
failure_message = models.CharField(verbose_name="failure message reported by stripe", max_length=255, default="",
null=True, blank=True)
network_status = models.CharField(verbose_name="network status reported by stripe", max_length=64, default="",
null=True, blank=True)
billing_reason = models.CharField(verbose_name="reason for billing from by stripe", max_length=64, default="",
null=True, blank=True)
reason = models.CharField(verbose_name="reason for failure reported by stripe", max_length=255, default="",
null=True, blank=True)
seller_message = models.CharField(verbose_name="plain text message to us from stripe", max_length=255, default="",
null=True, blank=True)
stripe_type = models.CharField(verbose_name="authorization outcome message to us from stripe", max_length=64,
default="", null=True, blank=True)
payment_msg = models.CharField(verbose_name="payment outcome message to us from stripe", max_length=64, default="",
null=True, blank=True)
is_paid = models.BooleanField(verbose_name="Charge has been paid", default=False)
is_refunded = models.BooleanField(verbose_name="Charge has been refunded", default=False)
source_obj = models.CharField(verbose_name="stripe returns the donor's zip code", max_length=32, default="card",
null=True, blank=True)
amount_refunded = models.PositiveIntegerField(verbose_name="refund amount", default=0, null=True)
email = models.CharField(verbose_name="stripe returns the donor's email address as a name", max_length=255,
default="", null=True, blank=True)
address_zip = models.CharField(verbose_name="stripe returns the donor's zip code", max_length=32, default="",
null=True, blank=True)
brand = models.CharField(verbose_name="the brand of the credit card, eg. Visa, Amex", max_length=32, default="",
null=True, blank=True)
country = models.CharField(verbose_name="the country code of the bank that issued the credit card", max_length=8,
default="", null=True, blank=True)
exp_month = models.PositiveIntegerField(verbose_name="the expiration month of the credit card", default=0,
null=True)
exp_year = models.PositiveIntegerField(verbose_name="the expiration year of the credit card", default=0, null=True)
last4 = models.PositiveIntegerField(verbose_name="the last 4 digits of the credit card", default=0, null=True)
stripe_status = models.CharField(verbose_name="status string reported by stripe", max_length=64, default="",
null=True, blank=True)
status = models.CharField(verbose_name="our generated status message", max_length=255, default="", null=True,
blank=True)
we_plan_id = models.CharField(verbose_name="WeVote subscription plan id", max_length=64, default="",
unique=False, null=True, blank=True)
paid_at = models.DateTimeField(verbose_name="stripe subscription most recent charge timestamp", auto_now=False,
auto_now_add=False, null=True)
ip_address = models.GenericIPAddressField(verbose_name="user ip address", protocol='both', unpack_ipv4=False,
null=True, blank=True, unique=False)
is_chip_in = models.BooleanField(
verbose_name="Is this a Campaign 'Chip In' payment?", default=False)
is_premium_plan = models.BooleanField(
verbose_name="is this a premium organization plan (and not a personal donation subscription)?", default=False)
is_monthly_donation = models.BooleanField(
verbose_name="is this a repeating monthly subscription donation?", default=False)
campaignx_we_vote_id = models.CharField(
verbose_name="Campaign we vote id, in order to credit chip ins", max_length=32, unique=False, null=True,
blank=True)
record_enum = models.CharField(
verbose_name="enum of record type {PAYMENT_FROM_UI, PAYMENT_AUTO_SUBSCRIPTION, SUBSCRIPTION_SETUP_AND_INITIAL}",
max_length=32, unique=False, null=True, blank=True)
api_version = models.CharField(
verbose_name="Stripe API Version at creation time",
max_length=32, null=True, blank=True)
class StripeManager(models.Manager):
@staticmethod
def create_donate_link_to_voter(stripe_customer_id, voter_we_vote_id):
""""
:param stripe_customer_id:
:param voter_we_vote_id:
:return:
"""
new_customer_id_created = False
if not voter_we_vote_id:
success = False
status = 'MISSING_VOTER_WE_VOTE_ID'
else:
try:
new_customer_id_created = StripeLinkToVoter.objects.create(
stripe_customer_id=stripe_customer_id, voter_we_vote_id=voter_we_vote_id)
success = True
status = 'STRIPE_CUSTOMER_ID_SAVED '
except Exception as e:
success = False
status = 'STRIPE_CUSTOMER_ID_NOT_SAVED '
saved_results = {
'success': success,
'status': status,
'new_stripe_customer_id': new_customer_id_created
}
return saved_results
@staticmethod
def retrieve_stripe_customer_id_from_donate_link_to_voter(voter_we_vote_id):
"""
:param voter_we_vote_id:
:return:
"""
stripe_customer_id = ''
status = ''
success = bool
if positive_value_exists(voter_we_vote_id):
try:
stripe_customer_id_queryset = StripeLinkToVoter.objects.filter(
voter_we_vote_id__iexact=voter_we_vote_id).values()
stripe_customer_id = stripe_customer_id_queryset[0]['stripe_customer_id']
if positive_value_exists(stripe_customer_id):
success = True
status = "STRIPE_CUSTOMER_ID_RETRIEVED"
else:
success = False
status = "EXISTING_STRIPE_CUSTOMER_ID_NOT_FOUND"
except Exception as e:
success = False
status = "STRIPE_CUSTOMER_ID_RETRIEVAL_ATTEMPT_FAILED"
results = {
'success': success,
'status': status,
'stripe_customer_id': stripe_customer_id,
}
return results
@staticmethod
def retrieve_voter_we_vote_id_from_donate_link_to_voter(stripe_customer_id):
"""
:param stripe_customer_id:
:return:
"""
voter_we_vote_id = ''
status = ''
success = bool
if positive_value_exists(stripe_customer_id):
try:
voter_id_queryset = StripeLinkToVoter.objects.filter(
stripe_customer_id__iexact=stripe_customer_id).values()
voter_we_vote_id = voter_id_queryset[0]['voter_we_vote_id']
if positive_value_exists(voter_we_vote_id):
success = True
status = "VOTER_WE_VOTE_ID_RETRIEVED"
else:
success = False
status = "EXISTING_VOTER_WE_VOTE_ID_NOT_FOUND"
except Exception as e:
success = False
status = "VOTER_WE_VOTE_ID_RETRIEVAL_ATTEMPT_FAILED"
results = {
'success': success,
'status': status,
'voter_we_vote_id': voter_we_vote_id,
}
return results
@staticmethod
def retrieve_voter_we_vote_id_via_stripe_request_id(stripe_request_id):
"""
:param stripe_request_id:
:return:
"""
voter_we_vote_id = ''
not_loggedin_voter_we_vote_id = ''
status = ''
success = bool
if positive_value_exists(stripe_request_id):
try:
voter_id_queryset = StripeSubscription.objects.filter(
stripe_request_id__iexact=stripe_request_id).values()
voter_we_vote_id = voter_id_queryset[0]['voter_we_vote_id']
not_loggedin_voter_we_vote_id = voter_id_queryset[0]['not_loggedin_voter_we_vote_id']
if positive_value_exists(voter_we_vote_id) or positive_value_exists(not_loggedin_voter_we_vote_id):
success = True
status = "VOTER_WE_VOTE_ID_RETRIEVED"
else:
success = False
status = "EXISTING_VOTER_WE_VOTE_ID_NOT_FOUND"
except Exception as e:
success = False
status = "VOTER_WE_VOTE_ID_RETRIEVAL_ATTEMPT_FAILED"
results = {
'success': success,
'status': status,
'voter_we_vote_id': voter_we_vote_id,
'not_loggedin_voter_we_vote_id': not_loggedin_voter_we_vote_id,
}
return results
@staticmethod
def retrieve_voter_we_vote_id_via_amount_and_customer_id(amount, stripe_customer_id):
"""
:param amount:
:param stripe_customer_id:
:return:
"""
voter_we_vote_id = ''
status = ''
success = bool
if positive_value_exists(stripe_customer_id):
try:
subscription_queryset = StripeSubscription.objects.all().order_by('-id')
subscription_queryset = subscription_queryset.filter(
Q(amount=amount) | Q(stripe_customer_id=stripe_customer_id)
)
subscription_list = list(subscription_queryset)
highest_id_row = subscription_list[0]
voter_we_vote_id = highest_id_row.voter_we_vote_id
not_loggedin_voter_we_vote_id = highest_id_row.not_loggedin_voter_we_vote_id
if positive_value_exists(voter_we_vote_id) or positive_value_exists(not_loggedin_voter_we_vote_id):
success = True
status = "VOTER_WE_VOTE_ID_RETRIEVED"
else:
success = False
status = "EXISTING_VOTER_WE_VOTE_ID_NOT_FOUND"
except Exception as e:
success = False
status = "VOTER_WE_VOTE_ID_RETRIEVAL_ATTEMPT_FAILED"
results = {
'success': success,
'status': status,
'voter_we_vote_id': voter_we_vote_id,
'not_loggedin_voter_we_vote_id': not_loggedin_voter_we_vote_id,
}
return results
@staticmethod
def retrieve_or_create_recurring_donation_plan(voter_we_vote_id, we_plan_id, donation_amount,
is_premium_plan, coupon_code, premium_plan_type_enum,
linked_organization_we_vote_id, recurring_interval, client_ip,
stripe_customer_id, is_signed_in):
"""
June 2017, we create these records, but never read them for donations
August 2019, we read them for subscriptions and (someday) organization paid subscriptions
:param voter_we_vote_id:
:param we_plan_id:
:param donation_amount:
:param is_premium_plan:
:param coupon_code:
:param premium_plan_type_enum:
:param linked_organization_we_vote_id:
:param recurring_interval:
:param client_ip
:param stripe_customer_id
:param is_signed_in
:return:
"""
# recurring_we_plan_id = voter_we_vote_id + "-monthly-" + str(donation_amount)
# we_plan_id = we_plan_id + " Plan"
billing_interval = "monthly" # This would be a good place to start for annual payment paid subscriptions
currency = "usd"
donation_plan_is_active = True
exception_multiple_object_returned = False
status = ''
stripe_plan_id = ''
success = False
subscription_already_exists = False
try:
# the donation plan needs to exist in two places: our stripe account and our database
# plans can be created here or in our stripe account dashboard
if is_signed_in:
voter_we_vote_id_2 = voter_we_vote_id
not_loggedin_voter_we_vote_id = ''
else:
voter_we_vote_id_2 = ''
not_loggedin_voter_we_vote_id = voter_we_vote_id
subs_data = {
'we_plan_id': we_plan_id,
'amount': donation_amount,
'billing_interval': billing_interval,
'currency': currency,
'donation_plan_is_active': donation_plan_is_active,
'voter_we_vote_id': voter_we_vote_id_2,
'not_loggedin_voter_we_vote_id': not_loggedin_voter_we_vote_id,
'linked_organization_we_vote_id': linked_organization_we_vote_id,
# 'organization_subscription_plan_id=org_subs_id,
'client_ip': client_ip,
'stripe_customer_id': stripe_customer_id,
'stripe_charge_id': 'needs-match',
'brand': 'needs-match',
'exp_month': '0',
'exp_year': '0',
'last4': '0',
'billing_reason': 'donationWithStripe_Api'
}
is_new, donation_plan_query = StripeManager.stripe_subscription_create_or_update(subs_data)
if is_new:
# if a donation plan is not found, we've added it to our database
success = True
status += 'SUBSCRIPTION_PLAN_CREATED_IN_DATABASE '
else:
# if it is found, do nothing - no need to update
success = True
status += 'DONATION_PLAN_ALREADY_EXISTS_IN_DATABASE '
plan_id_query = {}
try:
plan_id_query = stripe.Plan.retrieve(we_plan_id)
except stripe.error.StripeError as stripeError:
# logger.error('Stripe (informational for splunk) error (1): %s', stripeError)
pass
if positive_value_exists(plan_id_query):
if positive_value_exists(plan_id_query.id):
stripe_plan_id = plan_id_query.id
logger.debug("Stripe, plan_id_query.id " + plan_id_query.id)
except StripeManager.MultipleObjectsReturned as e:
handle_record_found_more_than_one_exception(e, logger=logger)
success = False
status += 'MULTIPLE_MATCHING_SUBSCRIPTION_PLANS_FOUND '
exception_multiple_object_returned = True
except stripe.error.StripeError as stripeError:
logger.error('%s', 'Stripe error (2):', stripeError)
pass
except Exception as e:
handle_exception(e, logger=logger)
# if recurring_interval in ('month', 'year') and not positive_value_exists(stripe_plan_id) \
# and not org_subs_already_exists:
# # if plan doesn't exist in stripe, we need to create it (note it's already been created in database)
# plan = stripe.Plan.create(
# amount=donation_amount,
# interval=recurring_interval,
# currency="usd",
# nickname=we_plan_id,
# id=we_plan_id,
# product={
# "name": we_plan_id,
# "type": "service"
# },
# )
# if plan.id:
# success = True
# status += 'SUBSCRIPTION_PLAN_CREATED_IN_STRIPE '
# else:
# success = False
# status += 'SUBSCRIPTION_PLAN_NOT_CREATED_IN_STRIPE '
# else:
# status += 'STRIPE_PLAN_NOT_CREATED-REQUIREMENTS_NOT_SATISFIED_OR_STRIPE_PLAN_ALREADY_EXISTS '
results = {
'success': success,
'status': status,
'subscription_already_exists': subscription_already_exists,
'MultipleObjectsReturned': exception_multiple_object_returned,
'recurring_we_plan_id': we_plan_id,
}
return results
@staticmethod
def retrieve_or_create_subscription_plan_definition(
voter_we_vote_id,
linked_organization_we_vote_id,
stripe_customer_id,
we_plan_id,
subscription_cost_pennies,
coupon_code,
premium_plan_type_enum,
recurring_interval):
"""
August 2019, we read these records for organization paid subscriptions
:param voter_we_vote_id:
:param linked_organization_we_vote_id:
:param stripe_customer_id:
:param we_plan_id:
:param subscription_cost_pennies:
:param coupon_code:
:param premium_plan_type_enum:
:param recurring_interval:
:return:
"""
# recurring_interval is based on the Stripe constants: month and year
# billing_interval is based on BILLING_FREQUENCY_CHOICES: SAME_DAY_MONTHLY, SAME_DAY_ANNUALLY
# if recurring_interval == 'month':
# billing_interval = SAME_DAY_MONTHLY
# elif recurring_interval == 'year':
# billing_interval = SAME_DAY_ANNUALLY
# else:
# billing_interval = SAME_DAY_MONTHLY
currency = "usd"
exception_multiple_object_returned = False
is_new = False
is_premium_plan = True
status = ''
stripe_plan_id = ''
success = False
org_subs_id = 0
donation_plan_definition = None
donation_plan_definition_already_exists = False
donation_plan_definition_id = 0
try:
# the subscription (used to be donation plan) needs to exist in two places: our stripe acct and our database
# plans can be created here or in our stripe account dashboard
subs_data = {
# billing_interval': billing_interval,
'amount': subscription_cost_pennies,
'coupon_code': coupon_code,
'currency': currency,
'donation_plan_is_active': True,
'is_premium_plan': is_premium_plan,
'linked_organization_we_vote_id': linked_organization_we_vote_id,
'organization_subscription_plan_id': org_subs_id,
'premium_plan_type_enum': premium_plan_type_enum,
'stripe_customer_id': stripe_customer_id,
'voter_we_vote_id': voter_we_vote_id,
'we_plan_id': we_plan_id,
}
is_new, donation_plan_query = StripeManager.stripe_subscription_create_or_update(subs_data)
if is_new:
# if a donation plan is not found, we've added it to our database
success = True
status += 'SUBSCRIPTION_PLAN_DEFINITION_CREATED_IN_DATABASE '
else:
# if it is found, do nothing - no need to update
success = True
status += 'SUBSCRIPTION_PLAN_DEFINITION_ALREADY_EXISTS_IN_DATABASE '
donation_plan_definition_already_exists = True
we_plan_id = donation_plan_definition.we_plan_id
donation_plan_definition_id = donation_plan_definition.id
except StripeSubscription.MultipleObjectsReturned as e:
handle_record_found_more_than_one_exception(e, logger=logger)
success = False
status += 'MULTIPLE_MATCHING_SUBSCRIPTION_PLANS_FOUND '
exception_multiple_object_returned = True
except Exception as e:
handle_exception(e, logger=logger)
status += 'DONATION_PLAN_DEFINITION_GET_OR_CREATE-EXCEPTION: ' + str(e) + ' '
try:
stripe_plan = stripe.Plan.retrieve(we_plan_id)
if positive_value_exists(stripe_plan.id):
stripe_plan_id = stripe_plan.id
logger.debug("Stripe, stripe_plan.id " + stripe_plan.id)
status += 'EXISTING_STRIPE_PLAN_FOUND: ' + str(stripe_plan_id) + ' '
else:
status += 'EXISTING_STRIPE_PLAN_NOT_FOUND '
except Exception as e:
handle_exception(e, logger=logger)
status += 'STRIPE_PLAN_RETRIEVE-EXCEPTION: ' + str(e) + ' '
# except stripe.error.StripeError:
# pass
if not positive_value_exists(stripe_plan_id):
status += 'STRIPE_PLAN_TO_BE_CREATED '
if recurring_interval in ('month', 'year'):
# if plan doesn't exist in stripe, we need to create it (note it's already been created in database)
plan = stripe.Plan.create(
amount=subscription_cost_pennies,
interval=recurring_interval,
currency="usd",
nickname=we_plan_id,
id=we_plan_id,
product={
"name": we_plan_id,
"type": "service"
},
)
if plan.id:
stripe_plan_id = plan.id
success = True
status += 'STRIPE_PLAN_CREATED_IN_STRIPE '
else:
success = False
status += 'STRIPE_PLAN_NOT_CREATED_IN_STRIPE '
else:
status += 'STRIPE_PLAN_NOT_CREATED-REQUIREMENTS_NOT_SATISFIED '
results = {
'success': success,
'status': status,
'donation_plan_definition': donation_plan_definition,
'donation_plan_definition_id': donation_plan_definition_id,
'donation_plan_definition_already_exists': donation_plan_definition_already_exists,
'MultipleObjectsReturned': exception_multiple_object_returned,
'recurring_we_plan_id': we_plan_id,
}
return results
@staticmethod
def create_subscription_entry(subscription):
print('create_subscription_entry', subscription)
status = ''
new_history_entry = 0
try:
new_history_entry = StripeManager.stripe_subscription_create_or_update(subscription)
success = True
status = 'NEW_DONATION_PAYMENT_ENTRY_SAVED '
except Exception as e:
success = False
status += 'UNABLE_TO_SAVE_DONATION_PAYMENT_ENTRY, EXCEPTION: ' + str(e) + ' '
saved_results = {
'success': success,
'status': status,
'donation_journal_created': new_history_entry
}
return saved_results
def create_recurring_donation(self, stripe_customer_id, voter_we_vote_id, donation_amount, start_date_time, email,
is_premium_plan, coupon_code, premium_plan_type_enum, linked_organization_we_vote_id,
client_ip, payment_method_id, is_signed_in):
"""
:param stripe_customer_id:
:param voter_we_vote_id:
:param donation_amount:
:param start_date_time:
:param email:
:param is_premium_plan:
:param coupon_code:
:param premium_plan_type_enum:
:param linked_organization_we_vote_id:
:param client_ip
:param payment_method_id
:param: is_signed_in
:return:
"""
plan_error = False
status = ""
results = {}
stripe_subscription_created = False
org_segment = "organization-" if is_premium_plan else ""
periodicity = "-monthly-"
if "_YEARLY" in premium_plan_type_enum:
periodicity = "-yearly-"
we_plan_id = voter_we_vote_id + periodicity + org_segment + str(donation_amount)
donation_plan_results = self.retrieve_or_create_recurring_donation_plan(
voter_we_vote_id, we_plan_id, donation_amount, is_premium_plan, coupon_code,
premium_plan_type_enum, linked_organization_we_vote_id, 'month', client_ip, stripe_customer_id,
is_signed_in)
subscription_already_exists = donation_plan_results['subscription_already_exists']
success = donation_plan_results['success']
status += donation_plan_results['status']
if not subscription_already_exists and success:
try:
# If not logged in, this voter_we_vote_id will not be the same as the logged in id.
# Passing the voter_we_vote_id to the subscription gives us a chance to associate logged in with not
# logged in subscriptions in the future
name = "product_for_" + we_plan_id
productc = stripe.Product.create(name=name)
nickname = we_plan_id
pricec = stripe.Price.create(
unit_amount=donation_amount,
currency="usd",
recurring={"interval": "month"},
product=productc.stripe_id,
nickname=nickname
)
stripe.PaymentMethod.attach(
payment_method_id,
customer=stripe_customer_id,
)
subscription = stripe.Subscription.create(
customer=stripe_customer_id,
items=[
{'price': pricec.stripe_id, }
],
default_payment_method=payment_method_id
)
success = True
stripe_subscription_id = subscription['id']
status += "USER_SUCCESSFULLY_SUBSCRIBED_TO_PLAN "
stripe_subscription_created = True
results = {
'success': success,
'status': status,
'voter_subscription_saved': status,
'stripe_subscription_created': stripe_subscription_created,
'code': '',
'decline_code': '',
'error_message': '',
'subscription_plan_id': we_plan_id,
'subscription_created_at': subscription['created'],
'stripe_subscription_id': stripe_subscription_id,
'subscription_already_exists': False,
}
except AttributeError as err:
# Something else happened, completely unrelated to Stripe
logger.error("create_recurring_donation caught: ", err)
pass
except stripe.error.StripeError as e:
success = False
body = e.json_body
err = body['error']
status += "STRIPE_ERROR_IS_" + err['message'] + "_END"
logger.error("%s", "create_recurring_donation StripeError: " + status)
remove_results = self.remove_subscription(we_plan_id)
status += " " + remove_results['status']
results = {
'success': False,
'status': status,
'voter_subscription_saved': False,
'subscription_already_exists': False,
'stripe_subscription_created': stripe_subscription_created,
'code': err['code'],
'decline_code': err['decline_code'],
'error_message': err['message'],
'subscription_plan_id': "",
'subscription_created_at': "",
'stripe_subscription_id': ""
}
else:
results = {
'success': success,
'status': status,
'voter_subscription_saved': False,
'subscription_already_exists': subscription_already_exists,
'stripe_subscription_created': stripe_subscription_created,
'code': '',
'decline_code': '',
'error_message': '',
'subscription_plan_id': "",
'subscription_created_at': "",
'stripe_subscription_id': ""
}
return results
# def create_organization_subscription(
# self, stripe_customer_id, voter_we_vote_id, donation_amount, start_date_time, email,
# coupon_code, premium_plan_type_enum, linked_organization_we_vote_id, recurring_interval):
# """
#
# :param stripe_customer_id:
# :param voter_we_vote_id:
# :param donation_amount:
# :param start_date_time:
# :param email:
# :param coupon_code:
# :param premium_plan_type_enum:
# :param linked_organization_we_vote_id:
# :param recurring_interval:
# :return:
# """
# status = ""
# success = False
# stripe_subscription_created = False
# subscription_created_at = ''
# stripe_subscription_id = ''
#
# org_segment = "organization-"
# periodicity ="-monthly-"
# if "_YEARLY" in premium_plan_type_enum:
# periodicity = "-yearly-"
# we_plan_id = voter_we_vote_id + periodicity + org_segment + str(donation_amount)
#
# # We have already previously retrieved the coupon_price, and updated the donation_amount.
# # Here, we are incrementing the redemption counter
# increment_redemption_count = True
# coupon_price, org_subs_id = DonationManager.get_coupon_price(premium_plan_type_enum, coupon_code,
# increment_redemption_count)
#
# plan_results = self.retrieve_or_create_subscription_plan_definition(
# voter_we_vote_id, linked_organization_we_vote_id, stripe_customer_id,
# we_plan_id, donation_amount, coupon_code, premium_plan_type_enum,
# recurring_interval)
# donation_plan_definition_already_exists = plan_results['donation_plan_definition_already_exists']
# status = plan_results['status']
# donation_plan_definition_id = plan_results['donation_plan_definition_id']
# if plan_results['success']:
# donation_plan_definition = plan_results['donation_plan_definition']
# try:
# # If not logged in, this voter_we_vote_id will not be the same as the logged in id.
# # Passing the voter_we_vote_id to the subscription gives us a chance to associate logged in with not
# # logged in subscriptions in the future
# subscription = stripe.Subscription.create(
# customer=stripe_customer_id,
# plan=we_plan_id,
# metadata={
# 'linked_organization_we_vote_id': linked_organization_we_vote_id,
# 'voter_we_vote_id': voter_we_vote_id,
# 'email': email
# }
# )
# stripe_subscription_created = True
# success = True
# stripe_subscription_id = subscription['id']
# subscription_created_at = subscription['created']
# status += "USER_SUCCESSFULLY_SUBSCRIBED_TO_PLAN "
# except stripe.error.StripeError as e:
# success = False
# body = e.json_body
# err = body['error']
# status = "STRIPE_ERROR_IS_" + err['message'] + "_END"
# logger.error('%s', "create_recurring_donation StripeError: " + status)
#
# if positive_value_exists(stripe_subscription_id):
# try:
# donation_plan_definition.stripe_subscription_id = stripe_subscription_id
# donation_plan_definition.save()
# status += "STRIPE_SUBSCRIPTION_ID_SAVED_IN_DONATION_PLAN_DEFINITION "
# except Exception as e:
# status += "FAILED_TO_SAVE_STRIPE_SUBSCRIPTION_ID_IN_DONATION_PLAN_DEFINITION "
# results = {
# 'success': success,
# 'status': status,
# 'stripe_subscription_created': stripe_subscription_created,
# 'subscription_plan_id': we_plan_id,
# 'subscription_created_at': subscription_created_at,
# 'stripe_subscription_id': stripe_subscription_id,
# 'donation_plan_definition_already_exists': donation_plan_definition_already_exists,
# }
# return results
@staticmethod
def retrieve_stripe_card_error_message(error_type):
"""
:param error_type:
:return:
"""
voter_card_error_message = 'Your card has been declined for an unknown reason. Contact your bank for more' \
' information.'
card_error_message = {
'approve_with_id': 'The transaction cannot be authorized. Please try again or contact your bank.',
'card_not_supported': 'Your card does not support this type of purchase. Contact your bank for more '
'information.',
'card_velocity_exceeded': 'You have exceeded the balance or credit limit available on your card.',
'currency_not_supported': 'Your card does not support the specified currency.',
'duplicate_transaction': 'This transaction has been declined because a transaction with identical amount '
'and credit card information was submitted very recently.',
'fraudulent': 'This transaction has been flagged as potentially fraudulent. Contact your bank for more '
'information.',
'incorrect_number': 'Your card number is incorrect. Please enter the correct number and try again.',
'incorrect_pin': 'Your pin is incorrect. Please enter the correct number and try again.',
'incorrect_zip': 'Your ZIP/postal code is incorrect. Please enter the correct number and try again.',
'insufficient_funds': 'Your card has insufficient funds to complete this transaction.',
'invalid_account': 'Your card, or account the card is connected to, is invalid. Contact your bank for more'
' information.',
'invalid_amount': 'The payment amount exceeds the amount that is allowed. Contact your bank for more '
'information.',
'invalid_cvc': 'Your CVC number is incorrect. Please enter the correct number and try again.',
'invalid_expiry_year': 'The expiration year is invalid. Please enter the correct number and try again.',
'invalid_number': 'Your card number is incorrect. Please enter the correct number and try again.',
'invalid_pin': 'Your pin is incorrect. Please enter the correct number and try again.',
'issuer_not_available': 'The payment cannot be authorized. Please try again or contact your bank.',
'new_account_information_available': 'Your card, or account the card is connected to, is invalid. Contact '
'your bank for more information.',
'withdrawal_count_limit_exceeded': 'You have exceeded the balance or credit limit on your card. Please try '
'another payment method.',
'pin_try_exceeded': 'The allowable number of PIN tries has been exceeded. Please try again later or use '
'another payment method.',
'processing_error': 'An error occurred while processing the card. Please try again.'
}
for error in card_error_message:
if error == error_type:
voter_card_error_message = card_error_message[error]
break
# Any other error types that are not in this dict will use the generic voter_card_error_message
return voter_card_error_message
@staticmethod
def retrieve_donation_journal_list(voter_we_vote_id):
"""
:param voter_we_vote_id:
:return:
"""
donation_journal_list = []
status = ''
try:
donation_queryset = StripePayments.objects.all().order_by('-created')
donation_queryset = donation_queryset.filter(voter_we_vote_id__iexact=voter_we_vote_id)
donation_journal_list = list(donation_queryset)
if len(donation_journal_list):
success = True
status += ' CACHED_WE_VOTE_DONATION_PAYMENT_HISTORY_LIST_RETRIEVED '
else:
donation_journal_list = []
success = True
status += ' NO_DONATION_PAYMENT_HISTORY_EXISTS_FOR_THIS_VOTER '
except StripePayments.DoesNotExist:
status += " WE_VOTE_HISTORY_DOES_NOT_EXIST "
success = True
except Exception as e:
status += " FAILED_TO RETRIEVE_CACHED_WE_VOTE_HISTORY_LIST "
success = False
# handle_exception(e, logger=logger, exception_message=status)
results = {
'success': success,
'status': status,
'donation_journal_list': donation_journal_list,
}
return results
@staticmethod
def retrieve_donation_subscription_list(voter_we_vote_id):
"""
:param voter_we_vote_id:
:return:
"""
subscription_list = []
status = ''
try:
subscription_queryset = StripeSubscription.objects.all().order_by('-subscription_created_at')
subscription_queryset = subscription_queryset.filter(
Q(voter_we_vote_id__iexact=voter_we_vote_id) | Q(not_loggedin_voter_we_vote_id__iexact=voter_we_vote_id)
)
subscription_list = list(subscription_queryset)
if len(subscription_list):
success = True
status += ' CACHED_WE_VOTE_DONATION_SUBSCRIPTION_LIST_RETRIEVED '
else:
subscription_list = []
success = True
status += ' NO_DONATION_SUBSCRIPTION_LIST_EXISTS_FOR_THIS_VOTER '
except StripePayments.DoesNotExist:
status += " DONATION_SUBSCRIPTION_LIST_DOES_NOT_EXIST "
success = True
except Exception as e:
status += " FAILED_TO RETRIEVE_CACHED_DONATION_SUBSCRIPTION_LIST "
success = False
# handle_exception(e, logger=logger, exception_message=status)
results = {
'success': success,
'subscription_status': status,
'subscription_list': subscription_list,
}
return results
@staticmethod
def retrieve_payment_for_charge(stripe_charge_id):
status = ''