-
Notifications
You must be signed in to change notification settings - Fork 123
/
models.py
4811 lines (4313 loc) · 203 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
# Copyright (c) 2023, DjaoDjin inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#pylint: disable=too-many-lines
# Implementation Note:
# The models and managers are declared in the same file to avoid messy
# import loops.
"""
Subscribers and providers are both instances of ``Organization``. This is done
such that one can be a subscriber to a ``Plan`` for a service hosted on
the broker website as well as itself a provider to other subscribers.
(ex: An organization can provide a CRM tool to subscribers while paying
another app, also hosted on the broker platform, to display usage analytics
of its own product). It is possible to implement
a :doc:`symmetric double-entry bookkeeping ledger<ledger>` by having a single
model ``Organization``.
Typically if you are self-hosting a pure Software-as-a-Service, as opposed to
building a marketplace, you will define a single provider which incidently
is also the the broker (See :doc:`examples<getting-started>`).
A billing profile (credit card and deposit bank account) is represented by
an ``Organization``.
An ``Organization`` subscriber subscribes to services provided by another
``Organization`` provider through a ``Subscription`` to a ``Plan``.
An ``Organization`` represents a billing profile. The ``processor_card_key``
and ``processor_deposit_key`` fields are respectively used when an organization
acts as a subscriber or provider in the subscription relationship.
There are no mechanism provided to authenticate as an ``Organization``.
Instead ``User`` authenticate with the application (through a login page
or an API token). They are then able to access URLs related
to an ``Organization`` based on their relation with that ``Organization``
as implemented by a ``RoleDescription``.
For historical reasons, two roles are often implemented: managers
and contributors (for details see :doc:`Security <security>`).
"""
from __future__ import unicode_literals
import datetime, logging, re
from dateutil.relativedelta import relativedelta
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError as DjangoValidationError
from django.db import (DatabaseError, IntegrityError, connections, models,
transaction)
from django.db.models import Max, Q, Sum
from django.db.models.query import QuerySet
from django.db.models.signals import post_save
from django.db.utils import DEFAULT_DB_ALIAS
from django.dispatch import receiver
from django.template.defaultfilters import slugify
from django.utils.safestring import mark_safe
from django_countries.fields import CountryField
from rest_framework.exceptions import ValidationError
from . import humanize, settings, signals
from .backends import (get_processor_backend, CardError, ProcessorError,
ProcessorSetupError)
from .compat import (import_string, gettext_lazy as _,
python_2_unicode_compatible, six, urlquote)
from .utils import (SlugTitleMixin, datetime_or_now, full_name_natural_split,
generate_random_slug, handle_uniq_error)
from .utils import get_organization_model, get_role_model
LOGGER = logging.getLogger(__name__)
class InsufficientFunds(Exception):
pass
class Price(object):
def __init__(self, amount, unit):
assert isinstance(amount, six.integer_types)
self.amount = amount
self.unit = unit
if not self.unit:
self.unit = settings.DEFAULT_UNIT # XXX
def get_extra_field_class():
extra_class = settings.EXTRA_FIELD
if extra_class is None:
extra_class = models.TextField
elif isinstance(extra_class, six.string_types):
extra_class = import_string(extra_class)
return extra_class
class OrganizationManager(models.Manager):
def create_organization(self, name, creation_time):
# XXX This method seems deprecated
creation_time = datetime.datetime.fromtimestamp(creation_time)
billing_start = creation_time
if billing_start.day > 28:
# Insures that the billing cycle will be on the same day
# every month.
if billing_start.month >= 12:
billing_start = datetime.datetime(billing_start.year + 1,
1, 1)
else:
billing_start = datetime.datetime(billing_start.year,
billing_start.month + 1, 1)
customer = self.create(created_at=creation_time,
slug=name, billing_start=billing_start)
return customer
def attached(self, user):
"""
Returns the personal profile (``Organization``) associated to the user
or None if none can be reliably found.
"""
if isinstance(user, get_user_model()):
return self.filter(role__user=user, slug=user.username).first()
if isinstance(user, six.string_types):
return self.filter(role__user__username=user, slug=user).first()
return None
def accessible_by(self, user, role_descr=None): # OrganizationManager
"""
Returns a QuerySet of Organziation which *user* has an associated
role with.
When *user* is a string instead of a ``User`` instance, it will
be interpreted as a username.
"""
kwargs = {}
user_model = get_user_model()
if isinstance(user, user_model):
kwargs.update({'user': user})
else:
kwargs.update({'user__username': str(user)})
if role_descr:
if isinstance(role_descr, RoleDescription):
kwargs.update({'role_description': role_descr})
elif isinstance(role_descr, six.string_types):
kwargs.update({'role_description__slug': str(role_descr)})
else:
kwargs.update({'role_description__slug__in': [
str(descr) for descr in role_descr]})
roles = get_role_model().objects.db_manager(
using=self._db).valid_for(**kwargs)
return self.filter(
is_active=True, pk__in=roles.values('organization')).distinct()
def find_candidates_by_domain(self, domain):
return self.filter(is_active=True, email__endswith=domain)
def find_candidates(self, full_name, user=None):
"""
Returns a set of organizations based on a fuzzy match of *full_name*
and the email address of *user*.
This method is primarly intended in registration pages to help
a user decides to create a new organization or request access
to an already existing organization.
"""
queryset = self.filter(
Q(slug=slugify(full_name)) | Q(full_name__iexact=full_name))
if queryset.exists():
return queryset
if user:
email_suffix = user.email.split('@')[-1]
candidates_from_email = get_role_model().objects.valid_for(
user__email__iendswith=email_suffix,
role_description__slug=settings.MANAGER).values(
'organization')
return self.filter(pk__in=candidates_from_email)
return self.none()
def providers(self, subscriptions):
"""
Set of ``Organization`` which provides the plans referenced
by *subscriptions*.
"""
if subscriptions:
# Would be almost straightforward in a single raw SQL query
# but expressing it for the Django compiler is not easy.
selectors = set([])
for subscription in subscriptions:
selectors |= set([subscription.plan.organization.id])
return self.filter(pk__in=selectors)
return self.none()
def receivable_providers(self, invoiced_items):
"""
Returns a list of unique providers referenced by *invoiced_items*.
"""
results = set([])
for invoiced_item in invoiced_items:
assert invoiced_item.orig_account in (Transaction.RECEIVABLE,
Transaction.SETTLED)
results |= set([invoiced_item.orig_organization])
event = invoiced_item.get_event()
if event:
results |= set([event.provider])
return list(results)
def providers_to(self, organization):
"""
Set of ``Organization`` which provides active services
to a subscribed *organization*.
"""
return self.providers(Subscription.objects.valid_for(
organization=organization))
@python_2_unicode_compatible
class AbstractOrganization(models.Model):
"""
The Organization table stores information about who gets
charged (subscriber) and who gets paid (provider) for using a service.
A special ``Organization``, named processor, is used to represent
the backend charge/deposit processor.
Users can have one of multiple relationships (roles) with an Organization.
They can either be managers (all permissions) or a custom role defined
through a ``RoleDescription``.
"""
#pylint:disable=too-many-instance-attributes
ACCOUNT_UNKNOWN = 0
ACCOUNT_USER = 1
ACCOUNT_PERSONAL = 2
ACCOUNT_ORGANIZATION = 3
ACCOUNT_PROVIDER = 4
ACCOUNT_TYPE = (
(ACCOUNT_UNKNOWN, "unknown"),
(ACCOUNT_USER, "user"),
(ACCOUNT_PERSONAL, "personal"),
(ACCOUNT_ORGANIZATION, "organization"),
(ACCOUNT_PROVIDER, "provider"),
)
objects = OrganizationManager()
slug = models.SlugField(unique=True,
help_text=_("Unique identifier shown in the URL bar"))
created_at = models.DateTimeField(auto_now_add=True,
help_text=_("Date/time of creation (in ISO format)"))
is_active = models.BooleanField(default=True)
full_name = models.CharField(_("Profile name"), max_length=100, blank=True)
# contact by e-mail
email = models.EmailField()
# contact by phone
phone = models.CharField(max_length=50)
# contact by physical mail
street_address = models.CharField(_("Street address"), max_length=150)
locality = models.CharField(_("City/Town"), max_length=50)
region = models.CharField(_("State/Province/County"), max_length=50)
postal_code = models.CharField(_("Zip/Postal code"), max_length=50)
country = CountryField(_("Country"))
is_bulk_buyer = models.BooleanField(default=False,
help_text=mark_safe(_("Enable GroupBuy ("\
"<a href=\"https://www.djaodjin.com/docs/faq/#group-billing\""\
" target=\"_blank\">what is it?</a>)")))
is_provider = models.BooleanField(default=False,
help_text=_("The profile can fulfill the provider side"\
" of a subscription."))
default_timezone = models.CharField(
max_length=100, default=settings.TIME_ZONE,
help_text=_("Timezone to use when reporting metrics"))
# 2083 number is used because it is a safe option to choose based
# on some older browsers behavior
# https://stackoverflow.com/q/417142/1491475
picture = models.URLField(_("Profile picture"), max_length=2083, null=True,
blank=True, help_text=_("URL location of the profile picture"))
# Payment Processing
# ------------------
# Implementation Note: Software developpers using the Django admin
# panel to bootstrap their database will have an issue if the processor
# is not optional. This is because the processor ``Organization`` does
# not itself reference a processor.
# 2nd note: We could support multiple payment processors at the same
# time by having a relation to a separate table. For simplicity we only
# allow one processor per organization at a time.
subscribes_to = models.ManyToManyField('saas.Plan',
related_name='subscribers', through='saas.Subscription')
billing_start = models.DateField(null=True, auto_now_add=True)
funds_balance = models.PositiveIntegerField(default=0,
help_text=_("Funds escrowed in currency unit"))
nb_renewal_attempts = models.PositiveIntegerField(default=0,
help_text=_("Number of successive failed charges"))
processor = models.ForeignKey(
settings.ORGANIZATION_MODEL, null=True, blank=True,
on_delete=models.SET_NULL, related_name='processes',)
processor_card_key = models.SlugField(max_length=255, null=True, blank=True)
processor_deposit_key = models.SlugField(max_length=255, null=True,
blank=True,
help_text=_("Used to deposit funds to the organization bank account"))
processor_priv_key = models.SlugField(max_length=255, null=True, blank=True)
processor_pub_key = models.SlugField(max_length=255, null=True, blank=True)
processor_refresh_token = models.SlugField(max_length=255, null=True,
blank=True)
extra = get_extra_field_class()(null=True, blank=True,
help_text=_("Extra meta data (can be stringify JSON)"))
class Meta:
abstract = True
def __str__(self):
return str(self.slug)
@property
def is_broker(self):
"""
Returns ``True`` if the organization is the hosting platform
for the service.
"""
#pylint:disable=attribute-defined-outside-init
if not hasattr(self, '_is_broker'):
# We do a string compare here because both ``Organization`` might
# come from a different db.
organization_slug = self.slug
if settings.IS_BROKER_CALLABLE:
self._is_broker = import_string(settings.IS_BROKER_CALLABLE)(
organization_slug)
else:
self._is_broker = (get_broker().slug == organization_slug)
return self._is_broker
def get_active_subscriptions(self, at_time=None):
"""
Returns the set of active subscriptions for this organization
at time *at_time* or now if *at_time* is not specified.
"""
at_time = datetime_or_now(at_time)
return Subscription.objects.valid_for(
organization=self, ends_at__gte=at_time)
def get_ends_at_by_plan(self, at_time=None):
"""
Returns the set of churned subscriptions for this organization
at time *at_time* or now if *at_time* is not specified.
"""
at_time = datetime_or_now(at_time)
return Subscription.objects.valid_for(
organization=self).values('plan__slug').annotate(
Max('ends_at')).distinct()
def get_changes(self, update_fields):
changes = {}
for field_name in ('slug', 'full_name', 'email', 'phone',
'street_address', 'locality', 'region', 'postal_code', 'country',
'is_bulk_buyer', 'is_provider', 'default_timezone'):
pre_value = getattr(self, field_name, None)
post_value = update_fields.get(field_name, None)
if post_value is not None and pre_value != post_value:
# The changes will be used to trigger a signal and notification
# to the primary contact that can then check for potential
# nefarious activity. It is also possible the notification
# is used to keep a separate service (CRM, etc.) in sync.
if field_name == 'is_bulk_buyer':
changes['GroupBuy'] = {
'pre': _('enabled') if pre_value else _('disabled'),
'post': _('enabled') if post_value else _('disabled')}
else:
changes[field_name] = {
'pre': pre_value, 'post': post_value}
return changes
def validate_processor(self):
#pylint:disable=no-member,access-member-before-definition
#pylint:disable=attribute-defined-outside-init
organization_model = get_organization_model()
if not self.processor_id:
try:
self.processor = organization_model.objects.get(
pk=settings.PROCESSOR_ID)
except organization_model.DoesNotExist:
# If the processor organization does not exist yet, it means
# we are inserting the first record to bootstrap the db.
self.processor_id = settings.PROCESSOR_ID
self.pk = settings.PROCESSOR_ID #pylint:disable=invalid-name
return self.processor
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
self.validate_processor()
if self.slug:
with transaction.atomic():
user = self.attached_user()
if user:
# When dealing with a personal profile, keep the login
# user in sync with the billing profile.
save_user = False
first_name, _, last_name \
= full_name_natural_split(self.full_name)
if user.first_name != first_name:
user.first_name = first_name
save_user = True
if user.last_name != last_name:
user.last_name = last_name
save_user = True
if user.email != self.email and (user.email or self.email):
# When registering with a phone number only,
# self.email might be ''. We don't want to override
# `user.email is None`.
user.email = self.email
save_user = True
if save_user:
user.save()
return super(AbstractOrganization, self).save(
force_insert=force_insert, force_update=force_update,
using=using, update_fields=update_fields)
max_length = self._meta.get_field('slug').max_length
if self.full_name:
slug_base = slugify(self.full_name)
else:
slug_base = _clean_field(
self.__class__, 'slug', self.email.split('@', maxsplit=1)[0])
if len(slug_base) > (max_length - 7 - 1):
slug_base = slug_base[:(max_length - 7 - 1)]
if slug_base:
self.slug = slug_base
slug_base += '-'
else:
self.slug = generate_random_slug(
length=min(max_length, len(slug_base) + 7))
for idx in range(1, 10): #pylint:disable=unused-variable
try:
try:
with transaction.atomic():
user = self.attached_user()
if user:
user.first_name, _, user.last_name \
= full_name_natural_split(self.full_name)
if self.email:
user.email = self.email
user.save()
return super(AbstractOrganization, self).save(
force_insert=force_insert,
force_update=force_update,
using=using, update_fields=update_fields)
except IntegrityError as err:
handle_uniq_error(err)
except ValidationError as err:
if not (isinstance(err.detail, dict) and 'slug' in err.detail):
raise err
self.slug = generate_random_slug(
length=min(max_length, len(slug_base) + 7),
prefix=slug_base)
raise ValidationError({'detail':
"Unable to create a unique URL slug from '%s'" % self.full_name})
@property
def printable_name(self):
"""
Insures we can actually print a name visible on paper.
"""
if self.full_name:
return self.full_name
return self.slug
@property
def has_profile_completed(self):
return self.full_name and \
self.email and \
self.phone and \
self.street_address and \
self.locality and \
self.region and \
self.postal_code and \
self.country
@property
def has_plan(self):
return Plan.objects.filter(
organization=self).count() > 0
@property
def has_bank_account(self):
if is_broker(self):
processor_backend = self.processor_backend
return processor_backend.pub_key and processor_backend.priv_key
return self.processor_deposit_key
@property
def natural_interval(self):
plan_periods = self.plans.values('period_type').distinct()
interval = Plan.MONTHLY
if plan_periods.exists():
interval = Plan.YEARLY
for period in plan_periods:
interval = min(interval, period['period_type'])
return interval
@property
def natural_subscription_period(self):
plan_periods = self.subscribes_to.values('period_type').distinct()
period_type = Plan.MONTHLY
if plan_periods.exists():
period_type = Plan.YEARLY
for period in plan_periods:
period_type = min(period_type, period['period_type'])
return Plan.get_natural_period(1, period_type)
@property
def processor_backend(self):
#pylint:disable=attribute-defined-outside-init
if not hasattr(self, '_processor_backend'):
self._processor_backend = get_processor_backend(self)
return self._processor_backend
def get_role_description(self, role_slug):
return RoleDescription.objects.db_manager(using=self._state.db).get(
Q(organization=self) | Q(organization__isnull=True),
slug=RoleDescription.normalize_slug(role_slug))
def get_role_descriptions(self):
"""
Queryset of roles a ``User`` can take on this ``Organization``.
"""
return RoleDescription.objects.filter(
Q(organization=self) | Q(organization__isnull=True)).order_by('pk')
def get_roles(self, role_descr=None):
kwargs = {}
if role_descr:
if not isinstance(role_descr, RoleDescription):
role_descr = self.get_role_description(role_descr)
kwargs = {'role_description': role_descr}
# OK to use ``filter`` here since we want to see all pending grants
# and requests.
return get_role_model().objects.db_manager(using=self._state.db).filter(
organization=self, **kwargs)
def add_role(self, user, role_descr,
grant_key=None, at_time=None, reason=None, extra=None,
request_user=None):
"""
Adds ``user`` as a ``role_descr`` (ex: manager) on the organization.
If ``user`` already had a role on the organization, it is removed
to only keep one role per user per organization.
"""
#pylint:disable=too-many-arguments
# Implementation Note:
# Django get_or_create will call router.db_for_write without
# an instance so the using database will be lost. The following
# code saves the relation in the correct database associated
# with the organization.
if not isinstance(role_descr, RoleDescription):
role_descr = self.get_role_description(role_descr)
# OK to use ``filter`` in both subsequent queries as we are dealing
# with the whole QuerySet related to a user.
queryset = get_role_model().objects.db_manager(
using=self._state.db).filter(organization=self, user=user)
if queryset.exists():
# We have a role for the user on this organization. Let's update it.
m2m = queryset.get()
force_insert = False
else:
if not (role_descr.skip_optin_on_grant or grant_key):
grant_key = generate_random_slug()
m2m = get_role_model()(
organization=self, user=user, grant_key=grant_key)
m2m.extra = extra
force_insert = True
m2m.role_description = role_descr
m2m.request_key = None
if at_time:
m2m.created_at = at_time
m2m.save(using=self._state.db, force_insert=force_insert)
signals.role_grant_created.send(sender=__name__,
role=m2m, reason=reason, request_user=request_user)
return force_insert
def add_role_request(self, user, at_time=None, role_descr=None):
if role_descr and not isinstance(role_descr, RoleDescription):
role_descr = self.get_role_description(role_descr)
# OK to use ``filter`` in both subsequent queries as we are dealing
# with the whole QuerySet related to a user.
queryset = get_role_model().objects.db_manager(
using=self._state.db).filter(organization=self, user=user)
if not queryset.exists():
# Otherwise a role already exists
# or a request was previously sent.
at_time = datetime_or_now(at_time)
if role_descr and role_descr.implicit_create_on_none:
request_key = None
else:
request_key = generate_random_slug()
m2m = get_role_model()(created_at=at_time, organization=self,
user=user, role_description=role_descr,
request_key=request_key)
m2m.save(using=self._state.db, force_insert=True)
return m2m
return None
def add_manager(self, user, extra=None, at_time=None):
"""
Special implementation of `add_role` that does not require a grant key,
nor generates any notification.
"""
# OK to use ``filter`` in both subsequent queries as we are dealing
# with the whole QuerySet related to a user.
queryset = get_role_model().objects.db_manager(
using=self._state.db).filter(organization=self, user=user)
if queryset.exists():
# We have a role for the user on this organization. Let's update it.
m2m = queryset.get()
force_insert = False
else:
m2m = get_role_model()(organization=self, user=user)
force_insert = True
m2m.extra = extra
m2m.role_description = self.get_role_description(settings.MANAGER)
m2m.grant_key = None
m2m.request_key = None
if at_time:
m2m.created_at = at_time
m2m.save(using=self._state.db, force_insert=force_insert)
return force_insert
def remove_role(self, user, role_name):
"""
Remove user as a *role_name* (ex: manager) to organization.
"""
relation = self.get_roles(role_name).get(user=user)
relation.delete()
def with_role(self, role_name):
"""
Returns all users with a *role_name* to organization.
"""
return get_user_model().objects.db_manager(using=self._state.db).filter(
pk__in=self.get_roles(role_name).values('user')).distinct()
def attached_user(self):
"""
Returns the only ``User`` attached to the ``Organization`` or
``None`` if more than one ``User`` has access rights
to the organization.
This method is used to implement personal registration, where
from a customer perspective user auth and billing profile are
one and the same.
"""
return get_user_model().objects.db_manager(
using=self._state.db).filter(
role__organization=self, username=self.slug).first()
def last_payment(self):
"""
Returns the Transaction that corresponds to the last payment
by the organization.
"""
return Transaction.objects.filter(
orig_organization=self,
orig_account=Transaction.LIABILITY,
dest_organization=self.processor,
dest_account=Transaction.FUNDS).order_by('-created_at').first()
def last_unpaid_orders(self, subscription=None, at_time=None):
"""
Returns the set of payable transactions that happened
after the last payment.
"""
kwargs = {}
if subscription:
kwargs.update({'event_id': get_sub_event_id(subscription)})
if at_time:
kwargs.update({'created_at__lt': at_time})
last_payment = self.last_payment()
if last_payment:
kwargs.update({'created_at__gt': last_payment.created_at})
queryset = Transaction.objects.filter(
dest_organization=self,
dest_account=Transaction.PAYABLE,
orig_account=Transaction.RECEIVABLE,
**kwargs).order_by('-created_at')
return queryset
def receivables(self):
"""
Returns all ``Transaction`` for payments that are due to a *provider*.
"""
return Transaction.objects.filter(
orig_organization=self,
orig_account=Transaction.RECEIVABLE).exclude(
dest_account=Transaction.CANCELED)
def update_bank(self, bank_token):
if bank_token is None:
self.processor_deposit_key = None
self.processor_priv_key = None
self.processor_pub_key = None
self.processor_refresh_token = None
self.save()
else:
self.processor_backend.update_bank(self, bank_token)
LOGGER.info("Processor deposit key for %s updated to %s",
self, self.processor_deposit_key,
extra={'event': 'update-deposit', 'organization': self.slug,
'processor_deposit_key': self.processor_deposit_key})
signals.bank_updated.send(self)
def delete_card(self):
broker = get_broker()
broker.processor_backend.delete_card(self, broker=broker)
self.processor_card_key = None
self.save()
LOGGER.info("Processor debit key for %s was deleted.",
self, extra={'event': 'delete-debit', 'organization': self.slug})
def update_card(self, card_token, user, provider=None):
broker = get_broker()
new_card = broker.processor_backend.create_or_update_card(
self, card_token, user=user, provider=provider, broker=broker)
self.nb_renewal_attempts = 0 # reset off-session failures counter
# The following ``save`` will be rolled back in ``checkout``
# if there is any ProcessorError.
self.save()
LOGGER.info("Processor debit key for %s updated to %s",
self, self.processor_card_key,
extra={'event': 'update-debit', 'organization': self.slug,
'processor_card_key': self.processor_card_key})
return new_card
def execute_order(self, invoicables, user):
"""
From the list of *invoicables*, clear the user Cart, create
the required Transaction to record the order, create/extends
Subscription and generate the claim codes for GroupBuy.
"""
#pylint: disable=too-many-locals, too-many-statements
claim_carts = {}
invoiced_items = []
new_organizations = []
coupon_by_plans = {}
for invoicable in invoicables:
subscription = invoicable['subscription']
# If the invoicable we are checking out is somehow related to
# a user shopping cart, we mark that cart item as recorded
# unless the organization does not exist in the database,
# in which case we will create a claim_code for it.
cart_item = None
# XXX Two use charges, sync_on is username will raise a 500 error
# because of multiple CartItem.
cart_items = CartItem.objects.get_cart(user, plan=subscription.plan)
if cart_items.exists():
# We are doing a groupBuy for a specified email.
bulk_items = cart_items.filter(
sync_on__iexact=subscription.organization.email)
if bulk_items.exists():
cart_item = bulk_items.get()
else:
cart_item = cart_items.get()
# XXX We have the cart_item here for an invoicable,
# or invoicable['lines'] which will end up as ChargeItems.
if cart_item:
for invoiced_item in invoicable['lines']:
setattr(invoiced_item, 'invoice_key', cart_item.claim_code)
setattr(invoiced_item, 'sync_on', cart_item.sync_on)
if not subscription.organization.id:
# When the organization does not exist into the database,
# we will create a random (i.e. hard to guess) claim code
# that will be emailed to the expected subscriber.
key = subscription.organization.email
if not key in new_organizations:
claim_carts[key] = []
new_organizations += [subscription.organization]
if subscription.plan not in coupon_by_plans:
coupon_by_plans.update({subscription.plan: 1})
else:
coupon_by_plans[subscription.plan] += 1
assert cart_item is not None
claim_carts[key] += [cart_item]
else:
LOGGER.info("[checkout] save subscription of %s to %s",
subscription.organization, subscription.plan,
extra={'event': 'upsert-subscription',
'organization': subscription.organization.slug,
'plan': subscription.plan.slug})
subscription.save()
if cart_item:
cart_item.recorded = True
cart_item.save()
# At this point we have gathered all the ``Organization``
# which have yet to be registered. For these no ``Subscription``
# has been created yet. We create a claim_code that will
# be emailed to the expected subscribers such that it will populate
# their cart automatically.
coupons = {}
claim_codes = {}
for plan, nb_attempts in six.iteritems(coupon_by_plans):
coupon = Coupon.objects.create(
code='cpn_%s' % generate_random_slug(),
organization=plan.organization,
discount_type=Coupon.PERCENTAGE, discount_value=10000,
ends_at=None,
plan=plan,
nb_attempts=nb_attempts,
description=('Auto-generated after payment by %s'
% self.printable_name))
LOGGER.info('Auto-generated Coupon %s for %s',
coupon.code, plan.organization,
extra={'event': 'create-coupon',
'coupon': coupon.code, 'auto': True,
'provider': plan.organization.slug})
coupons.update({plan.pk: coupon})
for key, cart_items in six.iteritems(claim_carts):
claim_code = None
for cart_item in cart_items:
cart_item.sync_on = ""
cart_item.user = None
cart_item.full_name = self.printable_name
if cart_item.claim_code:
claim_codes.update({key: cart_item.claim_code})
else:
if not claim_code:
claim_code = generate_random_slug()
cart_item.claim_code = claim_code
cart_item.coupon = coupons[cart_item.plan.pk]
cart_item.save()
if claim_code:
nb_cart_items = len(cart_items)
LOGGER.info("Generated claim code '%s' for %d cart items",
claim_code, nb_cart_items, extra={
'event': 'create-claim',
'claim_code': claim_code,
'nb_cart_items': nb_cart_items})
claim_codes.update({key: claim_code})
# We now either have a ``subscription.id`` (subscriber present
# in the database) or a ``Coupon`` (subscriber absent from
# the database).
for invoicable in invoicables:
subscription = invoicable['subscription']
if subscription.id:
event_id = get_sub_event_id(subscription)
else:
coupon = coupons[subscription.plan.pk]
# XXX should we not use a `cpn_` prefixed event_id here?
# see also InvoicedItem.get_event()
event_id = coupon.code
for invoiced_item in invoicable['lines']:
# definitely invoice_key should be set by then.
invoiced_item.event_id = event_id
invoiced_items += [invoiced_item]
# Insures all invoiced_items have been stored
# as ``Transaction`` into the database.
order_executed_items = Transaction.objects.record_order(
invoiced_items, user)
return new_organizations, claim_codes, order_executed_items
def checkout(self, invoicables, user, token=None, remember_card=True):
"""
*invoicables* is a set of ``Transaction`` that will be recorded
in the ledger. Associated subscriptions will be updated such that
the ends_at is extended in the future.
"""
charge = None
with transaction.atomic():
new_organizations, claim_codes, invoiced_items = self.execute_order(
invoicables, user)
charge = Charge.objects.charge_card(self, invoiced_items,
user=user, token=token, remember_card=remember_card)
# We email users which have yet to be registerd after the charge
# is created, just that we don't inadvertently email new subscribers
# in case something goes wrong.
for organization in new_organizations:
signals.claim_code_generated.send(
sender=__name__, subscriber=organization,
claim_code=claim_codes[organization.email], user=user)
return charge
def update_address_if_empty(self, country=None, region=None, locality=None,
street_address=None, postal_code=None):
#pylint:disable=too-many-arguments
if not (self.country or self.region) and country and region:
self.country = country
self.region = region
if not self.locality and locality:
self.locality = locality
if not self.street_address and street_address:
self.street_address = street_address
if not self.postal_code and postal_code:
self.postal_code = postal_code
def get_deposit_context(self):
return self.processor_backend.get_deposit_context()
def retrieve_bank(self):
"""
Returns associated bank account as a dictionnary.
"""
context = self.processor_backend.retrieve_bank(self)
available_amount = context.get('balance_amount', 0)
if isinstance(available_amount, six.integer_types):
# The processor could return "N/A" if the organization is not
# connected to a processor account.
balance = Transaction.objects.get_balance(
organization=self, account=Transaction.FUNDS)
available_amount = min(balance['amount'], available_amount)
transfer_fee = self.processor_backend.prorate_transfer(
available_amount, self)
if available_amount > transfer_fee:
available_amount -= transfer_fee
else:
available_amount = 0
context.update({'balance_amount': available_amount})
return context
def retrieve_card(self):
"""
Returns associated credit card.
"""
broker = get_broker()
return broker.processor_backend.retrieve_card(self, broker=broker)
def get_transfers(self, reconcile=True):
"""
Returns a ``QuerySet`` of ``Transaction`` after it has been
reconcile with the withdrawals that happened in the processor
backend.
"""
if reconcile:
after = datetime_or_now() - relativedelta(months=1)
# We want to avoid looping through too many calls to the Stripe API.
queryset = Transaction.objects.filter(
orig_organization=self,
orig_account=Transaction.FUNDS,
dest_account__startswith=Transaction.WITHDRAW)
most_recent = queryset.aggregate(
Max('created_at'))['created_at__max']
if most_recent:
after = max(most_recent, after)
self.processor_backend.reconcile_transfers(self, after,
limit_to_one_request=True)
return Transaction.objects.by_organization(self)
def withdraw_funds(self, amount, user):
if amount == 0:
# Nothing to do.
return
descr = "withdraw from %s" % self.printable_name
if user:
descr += ' (%s)' % user.username
self.processor_backend.create_transfer(
self, amount, currency=settings.DEFAULT_UNIT, descr=descr)
# We will wait on a call to ``reconcile_transfers`` to create
# those ``Trnansaction`` in the database.
def create_withdraw_transactions(self, event_id, amount, unit, descr,
created_at=None, dry_run=False):
"""
Withdraw funds from the site into the provider's bank account.
We record one straightforward ``Transaction`` for the withdrawal
and an additional one in case there is a processor transfer fee::
yyyy/mm/dd po_***** withdrawal to provider bank account
processor:Withdraw amount
provider:Funds
; With StripeConnect there are no processor fees anymore
; for Payouts.
yyyy/mm/dd processor fee paid by provider