-
Notifications
You must be signed in to change notification settings - Fork 1
/
models.py
executable file
·605 lines (513 loc) · 17.3 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
import uuid
import os
import re
import decimal
from typing import Tuple
from django.db import models
from django.utils import timezone
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.core.exceptions import ValidationError
from django.shortcuts import reverse
from django_countries.fields import CountryField
from plugins.consortial_billing import utils, logic, plugin_settings
from utils.logger import get_logger
logger = get_logger(__name__)
fs = FileSystemStorage(location=settings.MEDIA_ROOT)
CURRENCY_REGION_CHOICES = [
('EMU', 'Euro area'),
('GBR', 'United Kingdom'),
('USA', 'United States'),
]
BAND_CATEGORY_CHOICES = [
('calculated', 'Calculated'),
('special', 'Special'),
('base', 'Base'),
]
class BillingAgent(models.Model):
name = models.CharField(
max_length=255,
)
country = CountryField(
blank=True,
null=True,
help_text='If selected, will route all signups in this '
'country to this agent.',
)
default = models.BooleanField(
default=False,
help_text='Designates this as the default billing agent. ',
)
redirect_url = models.URLField(
blank=True,
help_text='If populated, the user will be redirected here '
'to complete the sign-up process',
)
def save(self, *args, **kwargs):
if self.default:
self.country = None
logic.keep_default_unique(self)
super().save(*args, **kwargs)
def __str__(self):
if self.default:
return f'{self.name} (default)'
elif self.country:
return f'{self.name} ({self.country})'
else:
return self.name
class AgentContact(models.Model):
agent = models.ForeignKey(
'consortial_billing.BillingAgent',
on_delete=models.CASCADE
)
account = models.ForeignKey(
'core.Account',
on_delete=models.CASCADE
)
@property
def email(self):
return self.account.email
def __str__(self):
return f'{self.account} <{self.email}>'
class SupporterSize(models.Model):
name = models.CharField(
max_length=50,
help_text="The name of the size band, e.g. Large Institution",
)
description = models.CharField(
max_length=200,
blank=True,
help_text='How size is determined, e.g. 0-4999 FTE staff '
'for an institution'
)
multiplier = models.DecimalField(
default=1,
decimal_places=2,
max_digits=3,
help_text="Usually a decimal number between 0.00 and 5.00. "
"The base rate is multiplied by this number "
"as part of the support fee calculation.",
)
internal_notes = models.CharField(
max_length=255,
blank=True,
help_text="Internal notes on how this was configured, "
"for when it needs updating next",
)
def __str__(self):
if self.description:
return f'{self.name} ({self.description})'
else:
return self.name
class Meta:
ordering = ('-multiplier',)
class SupportLevel(models.Model):
name = models.CharField(
max_length=30,
blank=True,
help_text="The level of support, e.g. Standard or Gold"
)
description = models.CharField(
max_length=255,
blank=True,
)
order = models.IntegerField(
blank=True,
null=True,
help_text="The order in which to display the levels "
"from highest to lowest.",
)
default = models.BooleanField(
default=False,
help_text="Designates this level as the standard level, set "
"apart from higher levels. "
"If checked, institution size will be factored "
"in to fees on this level. If unchecked, institution "
"size will not matter.",
)
internal_notes = models.CharField(
max_length=255,
blank=True,
help_text="Internal notes on how this was configured, "
"for when it needs updating next",
)
class Meta:
ordering = ('order', 'name')
def __str__(self):
if self.description:
return f'{self.name} ({self.description})'
else:
return f'{self.name}'
def save(self, *args, **kwargs):
logic.keep_default_unique(self)
super().save(*args, **kwargs)
class Currency(models.Model):
code = models.CharField(
max_length=3,
help_text="Three-letter currency code, e.g. EUR",
)
symbol = models.CharField(
blank=True,
max_length=2,
help_text="Currency symbol, e.g. €",
)
region = models.CharField(
max_length=3,
choices=CURRENCY_REGION_CHOICES,
help_text="The region or country associated with this currency "
"in World Bank data",
)
internal_notes = models.CharField(
max_length=255,
blank=True,
help_text="Internal notes on how this was configured, "
"for when it needs updating next",
)
def exchange_rate(self, base_band=None) -> Tuple[decimal.Decimal, str]:
"""
Gets most up-to-date multiplier for exchange rate
based on latest World Bank data,
which is oriented around USD
:return: tuple with the rate as decimal.Decimal plus a string warning if
matching country data could not be found
"""
if not base_band:
base_band = logic.get_base_band()
if base_band:
base_key = base_band.currency.region
else:
# This is needed during initial configuration
base_key = '---'
warning = utils.setting('missing_data_exchange_rate')
return logic.latest_multiplier_for_indicator(
plugin_settings.RATE_INDICATOR,
self.region,
base_key,
warning,
)
def convert_from(self, value, origin_currency):
if not isinstance(origin_currency, Currency):
try:
currency = Currency.objects.get(code=origin_currency)
except Currency.DoesNotExist:
logger.error(f'{origin_currency} is not a recognized currency code.')
target_exchange_rate, _warnings = self.exchange_rate()
origin_exchange_rate, _warnings = origin_currency.exchange_rate()
return value * (target_exchange_rate / origin_exchange_rate)
def __str__(self):
return self.code
class Meta:
ordering = ('code',)
verbose_name_plural = 'Currencies'
class Band(models.Model):
size = models.ForeignKey(
SupporterSize,
blank=True,
null=True,
on_delete=models.SET_NULL,
verbose_name="Institution size",
)
country = CountryField(
blank=True,
null=True,
)
currency = models.ForeignKey(
Currency,
blank=True,
null=True,
on_delete=models.SET_NULL,
verbose_name="Preferred currency",
)
level = models.ForeignKey(
SupportLevel,
blank=True,
null=True,
on_delete=models.SET_NULL,
verbose_name="Support level",
)
datetime = models.DateTimeField(
default=timezone.now,
)
fee = models.IntegerField(
blank=True,
null=True,
verbose_name='Annual fee',
)
warnings = models.CharField(
max_length=255,
blank=True,
help_text='Warning messages from the fee calculator',
)
billing_agent = models.ForeignKey(
BillingAgent,
blank=True,
null=True,
on_delete=models.SET_NULL,
help_text="Who is responsible for billing this supporter",
)
category = models.CharField(
max_length=10,
default='calculated',
choices=BAND_CATEGORY_CHOICES,
help_text='Controls how the band functions, either as the basis '
'or result of fee calculation, or as a special band '
'for one supporter with a manually set fee.',
)
@property
def economic_disparity(self) -> Tuple[decimal.Decimal, str]:
"""
Gets most up-to-date multiplier for economic disparity
based on latest GNI per capita figure
:return: tuple of the indicator as decimal.Decimal plus a string warning if
matching country data could not be found
"""
base_band = logic.get_base_band(level=self.level, country=self.country)
base_key = base_band.country.alpha3
warning = utils.setting('missing_data_economic_disparity')
return logic.latest_multiplier_for_indicator(
plugin_settings.DISPARITY_INDICATOR,
self.country.alpha3,
base_key,
warning,
)
@property
def size_difference(self) -> decimal.Decimal:
"""
Returns multiplier representing the
difference between the institution size
and the base band institution size
:return: decimal.Decimal
"""
base_band = logic.get_base_band(self.level)
base_band = logic.get_base_band(level=self.level, country=self.country)
return self.size.multiplier / base_band.size.multiplier
@property
def exchange_rate(self) -> Tuple[decimal.Decimal, str]:
"""
Returns exchange rate between this
band's currency and the base band currency
:return: a tuple with the rate as decimal.Decimal
and a string warning if no data
"""
base_band = logic.get_base_band(level=self.level, country=self.country)
return self.currency.exchange_rate(base_band=base_band)
def fee_in_currency(self, currency):
if not isinstance(currency, Currency):
try:
currency = Currency.objects.get(code=currency)
except Currency.DoesNotExist:
logger.error(f'{currency} is not a recognized currency code.')
target_exchange_rate, _warnings = currency.exchange_rate()
origin_exchange_rate, _warnings = self.exchange_rate
return self.fee * (target_exchange_rate / origin_exchange_rate)
def calculate_fee(self) -> Tuple[int, str]:
"""
Given institution size, supporter level, country,
and exchange rate, calculates supporter fee
:returns: The fee, as an int rounded to the nearest ten, and
a string containing warnings for the end user
"""
for field in [
self.size,
self.level,
self.country,
self.currency
]:
if not field:
raise ValidationError(
'Band does not have data needed for fee calculation'
)
warnings = ''
if self.country in logic.countries_with_billing_agents():
fee = logic.get_base_band(level=self.level, country=self.country).fee
else:
fee = logic.get_base_band(level=self.level).fee
if fee is None:
logger.error(
'No fee has been set on base band'
)
# Account for size of institution
# but only for standard (default) support levels,
# not for higher supporters
if self.level.default:
fee *= self.size_difference
# Account for country
disparity, warning = self.economic_disparity
fee *= disparity
warnings += warning
# Convert into preferred currency
rate, warning = self.exchange_rate
fee *= rate
warnings += warning
# Round to the nearest ten
fee = int(round(fee, -1))
# Check against minimum fee (e.g. 100)
fee = max(fee, int(utils.setting('minimum_fee')))
return fee, warnings
def determine_billing_agent(self):
return logic.determine_billing_agent(self.country)
def save(self, *args, **kwargs):
# Calculate fee if appropriate
if not self.fee and self.category == 'calculated':
self.fee, self.warnings = self.calculate_fee()
# The user has changed an existing band from calculated to special.
# In this case we want to create a new band object so we do not throw
# off other supporter fees that may be dependant on the existing band.
if self.pk and self.category == 'special':
previous_category = Band.objects.get(pk=self.pk)
if previous_category == 'calculated':
self.warnings = ''
self.pk = None
# to do: change the type if the fee entered is
# different than the calculated one
super().save(*args, **kwargs)
def __str__(self):
yyyy_mm_dd = self.datetime.strftime("%Y-%m-%d")
return f'{self.currency.symbol if self.currency else ""}' \
f'{self.fee if self.fee else "?"}, ' \
f'{self.level.name if self.level else ""}, ' \
f'{self.size.name if self.size else ""}, ' \
f'{self.country.name if self.country else ""}, ' \
f'{ self.get_category_display() }, created {yyyy_mm_dd}'
class Meta:
get_latest_by = 'datetime'
class OldBand(models.Model):
supporter = models.ForeignKey(
'consortial_billing.Supporter',
on_delete=models.CASCADE
)
band = models.ForeignKey(
Band,
on_delete=models.CASCADE
)
def __str__(self):
return f'{self.supporter}, {self.band}'
def validate_ror(url):
ror = os.path.split(url)[-1]
ror_regex = '^0[a-hj-km-np-tv-z|0-9]{6}[0-9]{2}$'
if not re.match(ror_regex, ror):
raise ValidationError(f'{ror} is not a valid ROR identifier')
class Supporter(models.Model):
# Entered by user on signup
name = models.CharField(
max_length=200,
blank=True,
verbose_name="Institution name",
)
ror = models.URLField(
blank=True,
validators=[validate_ror],
verbose_name='ROR',
help_text='Research Organization Registry identifier (URL)',
)
address = models.TextField(
max_length=255,
blank=True,
verbose_name="Billing address",
)
postal_code = models.CharField(
max_length=255,
blank=True,
)
display = models.BooleanField(
default=True,
help_text="May we include your institution name "
"in our public list of supporters?",
)
# Attached to supporter at signup or
# recalculation with new data
band = models.ForeignKey(
Band,
related_name='current_supporter',
blank=True,
null=True,
on_delete=models.SET_NULL,
help_text='Current band',
)
prospective_band = models.ForeignKey(
Band,
related_name='prospective_supporter',
blank=True,
null=True,
on_delete=models.SET_NULL,
help_text='Prospective band',
)
# Determined for the user or entered in admin
active = models.BooleanField(
default=False,
help_text="Whether the supporter is active",
)
internal_notes = models.TextField(
max_length=500,
blank=True,
help_text="Internal notes on this supporter",
)
@property
def size(self):
return self.band.size if self.band else None
@property
def level(self):
return self.band.level if self.band else None
@property
def currency(self):
return self.band.currency if self.band else None
@property
def fee(self):
return self.band.fee if self.band else None
@property
def warnings(self):
return self.band.warnings if self.band else None
@property
def datetime(self):
return self.band.datetime if self.band else None
@property
def billing_agent(self):
return self.band.billing_agent if self.band else None
@property
def url(self):
return reverse(
'edit_supporter_band',
args=(self.pk, ),
)
def get_ror(self, save=False, overwrite=False):
ror = utils.get_ror(self.name)
if ror and save and (not self.ror or overwrite):
self.ror = ror
self.save()
return ror
def __str__(self):
return self.name
def save(self, *args, **kwargs):
# If the band has been changed, create an old band record.
if self.band and self.pk:
old_band = Supporter.objects.get(pk=self.pk).band
if old_band and old_band != self.band:
OldBand.objects.get_or_create(
supporter=self,
band=old_band,
)
super().save(*args, **kwargs)
class Meta:
ordering = ('name',)
class SupporterContact(models.Model):
supporter = models.ForeignKey(
Supporter,
on_delete=models.CASCADE
)
account = models.ForeignKey(
'core.Account',
on_delete=models.CASCADE
)
@property
def email(self):
return self.account.email
def __str__(self):
return f'{self.account} <{self.email}>'
# Keep this for old migrations
def file_upload_path(instance, filename):
try:
filename = str(uuid.uuid4()) + '.' + str(filename.split('.')[1])
except IndexError:
filename = str(uuid.uuid4())
path = "plugins/{0}/".format(plugin_settings.SHORT_NAME)
return os.path.join(path, filename)