This repository has been archived by the owner on Feb 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
models.py
1525 lines (1383 loc) · 51.2 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
from collections import defaultdict
from itertools import groupby
from django.contrib.auth.models import (AbstractBaseUser,
BaseUserManager,
PermissionsMixin)
from django.contrib.gis.db import models as gis_models
from django.contrib.postgres import fields as postgres
from django.db import models
from django.db.models import Q, Count
from django.utils.dateformat import format
from allauth.account.models import EmailAddress
from simple_history.models import HistoricalRecords
from api.constants import FeatureGroups
from api.countries import COUNTRY_CHOICES
from api.oar_id import make_oar_id
from api.constants import Affiliations, Certifications, FacilitiesQueryParams
from api.helpers import prefix_a_an
class Version(models.Model):
"""
A table storing feature version numbers.
"""
name = models.CharField(
max_length=100,
null=False,
blank=False,
primary_key=True,
help_text='The name of a feature with versions.')
version = models.IntegerField(
null=False,
blank=False,
help_text='The version number of the feature.')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class EmailAsUsernameUserManager(BaseUserManager):
"""
A custom user manager which uses emails as unique identifiers for auth
instead of usernames.
"""
def _create_user(self, email, password, **extra_fields):
"""
Creates and saves a User with the given email and password.
"""
if not email:
raise ValueError('Email must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
extra_fields.setdefault('is_active', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self._create_user(email, password, **extra_fields)
class Contributor(models.Model):
"""
A participant in or observer of the supply chain that will
upload facility lists to the registry.
"""
# These choices must be kept in sync with the identical list kept in the
# React client's constants file
OTHER_CONTRIB_TYPE = 'Other'
CONTRIB_TYPE_CHOICES = (
('Auditor', 'Auditor'),
('Brand/Retailer', 'Brand/Retailer'),
('Civil Society Organization', 'Civil Society Organization'),
('Factory / Facility', 'Factory / Facility'),
('Manufacturing Group / Supplier / Vendor',
'Manufacturing Group / Supplier / Vendor'),
('Multi Stakeholder Initiative', 'Multi Stakeholder Initiative'),
('Researcher / Academic', 'Researcher / Academic'),
('Service Provider', 'Service Provider'),
('Union', 'Union'),
(OTHER_CONTRIB_TYPE, OTHER_CONTRIB_TYPE),
)
PLURAL_CONTRIB_TYPE = {
'Auditor': 'Auditors',
'Brand/Retailer': 'Brands/Retailers',
'Civil Society Organization': 'Civil Society Organizations',
'Factory / Facility': 'Factories / Facilities',
'Manufacturing Group / Supplier / Vendor':
'Manufacturing Groups / Suppliers / Vendors',
'Multi Stakeholder Initiative': 'Multi Stakeholder Initiatives',
'Researcher / Academic': 'Researchers / Academics',
'Service Provider': 'Service Providers',
'Union': 'Unions',
OTHER_CONTRIB_TYPE: 'Others',
}
admin = models.OneToOneField(
'User',
on_delete=models.PROTECT,
help_text=('The user account responsible for uploading and '
'maintaining facility lists for the contributor'))
name = models.CharField(
max_length=200,
null=False,
blank=False,
help_text='The full name of the contributor.')
description = models.TextField(
null=False,
blank=True,
help_text='A detailed description of the contributor.')
website = models.URLField(
null=False,
blank=True,
help_text='A URL linking to a web site for the contributor.')
contrib_type = models.CharField(
max_length=200,
null=False,
blank=False,
choices=CONTRIB_TYPE_CHOICES,
help_text='The category to which this contributor belongs.')
other_contrib_type = models.CharField(
max_length=200,
null=True,
blank=True,
help_text='Free text field if selected contributor type is other'
)
is_verified = models.BooleanField(
'verified',
default=False,
help_text=(
'Has this contributor has been verified by OAR staff.'
),
)
verification_notes = models.TextField(
null=False,
blank=True,
help_text=(
'A description of the manual steps taken to verify the '
'contributor.'
)
)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
history = HistoricalRecords()
def __str__(self):
return '{name} ({id})'.format(**self.__dict__)
@classmethod
def prefix_with_count(cls, value, count):
if count == 1:
if value.lower() == 'other':
# Special case to avoid returning the awkward "An Other"
return 'One {}'.format(value)
return prefix_a_an(value)
else:
return '{} {}'.format(
count, cls.PLURAL_CONTRIB_TYPE.get(value, value))
class User(AbstractBaseUser, PermissionsMixin):
USERNAME_FIELD = 'email'
objects = EmailAsUsernameUserManager()
is_staff = models.BooleanField(
('staff status'),
default=False,
help_text=('Designates whether the user can log into this site.'),
)
is_active = models.BooleanField(
('active'),
default=True,
help_text=(
'Designates whether this user should be treated as active. '
'Unselect this instead of deleting accounts.'
),
)
email = models.EmailField(
unique=True,
null=False,
blank=False,
help_text='Unique email address used as a username'
)
username = models.CharField(max_length=20, null=True, blank=True)
should_receive_newsletter = models.BooleanField(
default=False,
help_text='User has asked to receive the newsletter'
)
has_agreed_to_terms_of_service = models.BooleanField(
default=False,
help_text='User has agreed to the terms of service'
)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.email
def get_full_name(self):
return self.email
def get_short_name(self):
return self.email
def first_name(self):
pass
def last_name(self):
pass
@property
def did_register_and_confirm_email(self):
try:
email_address = EmailAddress.objects.get_primary(self.id)
if email_address:
return email_address.verified
# if no EmailAddress record exists, the User was created through the
# Django admin rather than the UI. Treat this User as verified.
return True
except EmailAddress.DoesNotExist:
return True
@property
def can_submit_privately(self):
return self.groups.filter(
name=FeatureGroups.CAN_SUBMIT_PRIVATE_FACILITY
).exists()
@property
def can_view_full_contrib_details(self):
if self.can_submit_privately:
return self.groups.filter(
name=FeatureGroups.CAN_VIEW_FULL_CONTRIB_DETAIL
).exists()
return True
class Source(models.Model):
LIST = 'LIST'
SINGLE = 'SINGLE'
SOURCE_TYPE_CHOICES = (
(LIST, LIST),
(SINGLE, SINGLE),
)
contributor = models.ForeignKey(
'Contributor',
null=True,
on_delete=models.SET_NULL,
help_text='The contributor who submitted the facility data'
)
source_type = models.CharField(
null=False,
max_length=6,
choices=SOURCE_TYPE_CHOICES,
help_text='Did the the facility data arrive in a list or a single item'
)
facility_list = models.OneToOneField(
'FacilityList',
null=True,
on_delete=models.PROTECT,
help_text='The related list if the type of the source is LIST.'
)
is_active = models.BooleanField(
null=False,
default=True,
help_text=('True if items from the source should be shown as being '
'associated with the contributor')
)
is_public = models.BooleanField(
null=False,
default=True,
help_text=('True if the public can see factories from this list '
'are associated with the contributor.')
)
create = models.BooleanField(
null=False,
default=True,
help_text=('Should a facility or facility match be created from the '
'facility data')
)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
@property
def display_name(self):
name = self.contributor.name \
if self.contributor else '[Unknown Contributor]'
if self.facility_list:
return '{} ({})'.format(name, self.facility_list.name)
return name
def __str__(self):
return '{0} ({1})'.format(
self.display_name, self.id)
class FacilityList(models.Model):
"""
Metadata for an uploaded list of facilities.
"""
name = models.CharField(
max_length=200,
null=False,
blank=False,
help_text='The name of list. Defaults to name of the uploaded file.')
description = models.TextField(
null=True,
blank=True,
help_text='The description of list.')
file_name = models.CharField(
max_length=200,
null=False,
blank=False,
editable=False,
help_text='The full name of the uploaded file.')
header = models.TextField(
null=False,
blank=False,
editable=False,
help_text='The header row of the uploaded CSV.')
replaces = models.OneToOneField(
'self',
null=True,
blank=True,
unique=True,
on_delete=models.PROTECT,
help_text=('If not null this list is an updated version of the '
'list specified by this field.'))
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
try:
if self.source.contributor is None:
return '{0} ({1})'.format(self.name, self.id)
return '{0} - {1} ({2})'.format(
self.source.contributor.name, self.name, self.id)
except Source.DoesNotExist:
return '{0} [NO SOURCE] ({1})'.format(self.name, self.id)
class FacilityListItem(models.Model):
"""
Data, metadata, and workflow status and results for a single line from a
facility list file.
"""
UPLOADED = 'UPLOADED'
PARSED = 'PARSED'
GEOCODED = 'GEOCODED'
GEOCODED_NO_RESULTS = 'GEOCODED_NO_RESULTS'
MATCHED = 'MATCHED'
POTENTIAL_MATCH = 'POTENTIAL_MATCH'
CONFIRMED_MATCH = 'CONFIRMED_MATCH'
ERROR = 'ERROR'
ERROR_PARSING = 'ERROR_PARSING'
ERROR_GEOCODING = 'ERROR_GEOCODING'
ERROR_MATCHING = 'ERROR_MATCHING'
DELETED = 'DELETED'
# NEW_FACILITY is a meta status. If the `status` of a `FacilityListItem` is
# `MATCHED` or `CONFIRMED_MATCH` and the `facility` was `created_from` the
# `FacilityListItem` then the item represents a new facility.
NEW_FACILITY = 'NEW_FACILITY'
# REMOVED is also a meta status. A `FacilityListItem` has been removed if
# any of its `FacilityMatch`es have `is_active` set to False.
REMOVED = 'REMOVED'
# These status choices must be kept in sync with the client's
# `facilityListItemStatusChoicesEnum`.
STATUS_CHOICES = (
(UPLOADED, UPLOADED),
(PARSED, PARSED),
(GEOCODED, GEOCODED),
(GEOCODED_NO_RESULTS, GEOCODED_NO_RESULTS),
(MATCHED, MATCHED),
(POTENTIAL_MATCH, POTENTIAL_MATCH),
(CONFIRMED_MATCH, CONFIRMED_MATCH),
(ERROR, ERROR),
(ERROR_PARSING, ERROR_PARSING),
(ERROR_GEOCODING, ERROR_GEOCODING),
(ERROR_MATCHING, ERROR_MATCHING),
(DELETED, DELETED),
)
ERROR_STATUSES = [ERROR, ERROR_PARSING, ERROR_GEOCODING, ERROR_MATCHING]
class Meta:
indexes = [
models.Index(fields=['source', 'row_index'],
name='api_fli_facility_list_row_idx'),
]
source = models.ForeignKey(
'Source',
null=False,
on_delete=models.PROTECT,
help_text='The source from which this item was created.'
)
row_index = models.IntegerField(
null=False,
editable=False,
help_text='Index of this line in the CSV file.')
raw_data = models.TextField(
null=False,
blank=False,
help_text='The full, unparsed CSV line as it appeared in the file.')
status = models.CharField(
max_length=200,
null=False,
blank=False,
choices=STATUS_CHOICES,
default=UPLOADED,
help_text='The current workflow progress of the line item.')
processing_started_at = models.DateTimeField(
null=True,
help_text=('When background processing of this item started. '
'Items awaiting processing will have a null value.'))
processing_completed_at = models.DateTimeField(
null=True,
help_text=('When background processing of this item finished. '
'Items awaiting or in process will have a null value.'))
processing_results = postgres.JSONField(
default=list,
help_text=('Diagnostic details logged by background processing '
'including details returned from the geocoder.'))
name = models.CharField(
max_length=200,
null=False,
blank=False,
help_text='The name of the facility taken from the raw data.')
address = models.CharField(
max_length=200,
null=False,
blank=False,
help_text='The address of the facility taken from the raw data.')
country_code = models.CharField(
max_length=2,
null=False,
blank=False,
choices=COUNTRY_CHOICES,
help_text=('The ISO 3166-1 alpha-2 country code of the facility taken '
'directly from the raw data or looked up based on a full '
'country name provided in the raw data.'))
geocoded_point = gis_models.PointField(
null=True,
help_text=('The geocoded location the facility address field taken '
'from the raw data.'))
geocoded_address = models.CharField(
max_length=1000,
null=True,
blank=True,
help_text='The geocoded address of the facility.')
facility = models.ForeignKey(
'Facility',
null=True,
on_delete=models.PROTECT,
help_text=('The facility created from this list item or the '
'previously existing facility to which this list '
'item was matched.'))
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return 'FacilityListItem {id} - {status}'.format(**self.__dict__)
class FacilityClaim(models.Model):
"""
Data submitted from a user attempting to make a verified claim of a
Facility to be evaluated by OAR moderators.
"""
EMAIL = 'EMAIL'
PHONE = 'PHONE'
PREFERRED_CONTACT_CHOICES = (
(EMAIL, EMAIL),
(PHONE, PHONE),
)
PENDING = 'PENDING'
APPROVED = 'APPROVED'
DENIED = 'DENIED'
REVOKED = 'REVOKED'
# These status choices must be kept in sync with the client's
# `facilityClaimStatusChoicesEnum`.
STATUS_CHOICES = (
(PENDING, PENDING),
(APPROVED, APPROVED),
(DENIED, DENIED),
(REVOKED, REVOKED),
)
CUT_AND_SEW = 'Cut and Sew / RMG'
DYEHOUSE = 'Dyehouse'
EMBELLISHMENTS = 'Embellishments'
FABRIC_MILL = 'Fabric Mill'
FINISHING = 'Finishing'
GINNING = 'Ginning'
KNITTING = 'Knitting'
LAUNDRY = 'Laundry'
PACKING = 'Packing'
SCOURING = 'Scouring'
SCREENPRINTING = 'Screenprinting'
STITCHING = 'Stitching (Shoes)'
TANNERY = 'Tannery'
WAREHOUSE = 'Warehouse'
WEAVING = 'Weaving'
OTHER = 'Other'
FACILITY_TYPE_CHOICES = (
(CUT_AND_SEW, CUT_AND_SEW),
(DYEHOUSE, DYEHOUSE),
(EMBELLISHMENTS, EMBELLISHMENTS),
(FABRIC_MILL, FABRIC_MILL),
(FINISHING, FINISHING),
(GINNING, GINNING),
(KNITTING, KNITTING),
(LAUNDRY, LAUNDRY),
(PACKING, PACKING),
(SCOURING, SCOURING),
(SCREENPRINTING, SCREENPRINTING),
(STITCHING, STITCHING),
(TANNERY, TANNERY),
(WAREHOUSE, WAREHOUSE),
(WEAVING, WEAVING),
(OTHER, OTHER),
)
AFFILIATION_CHOICES = [
(choice, choice)
for choice in
[
Affiliations.BENEFITS_BUSINESS_WORKERS,
Affiliations.BETTER_MILLS_PROGRAM,
Affiliations.BETTER_WORK,
Affiliations.CANOPY,
Affiliations.ETHICAL_TRADING_INITIATIVE,
Affiliations.FAIR_LABOR_ASSOCIATION,
Affiliations.FAIR_WEAR_FOUNDATION,
Affiliations.SEDEX,
Affiliations.SOCIAL_LABOR_CONVERGENCE_PLAN,
Affiliations.SUSTAINABLE_APPAREL_COALITION,
Affiliations.SWEATFREE_PURCHASING_CONSORTIUM,
]
]
CERTIFICATION_CHOICES = [
(choice, choice)
for choice in
[
Certifications.BCI,
Certifications.B_CORP,
Certifications.BLUESIGN,
Certifications.CANOPY,
Certifications.CRADLE_TO_CRADLE,
Certifications.EU_ECOLABEL,
Certifications.FSC,
Certifications.GLOBAL_RECYCLING_STANDARD,
Certifications.GOTS,
Certifications.GREEN_SCREEN,
Certifications.HIGG_INDEX,
Certifications.IMO_CONTROL,
Certifications.INTERNATIONAL_WOOL_TEXTILE,
Certifications.ISO_9000,
Certifications.IVN_LEATHER,
Certifications.LEATHER_WORKING_GROUP,
Certifications.NORDIC_SWAN,
Certifications.OEKO_TEX_STANDARD,
Certifications.OEKO_TEX_STEP,
Certifications.OEKO_TEX_ECO_PASSPORT,
Certifications.OEKO_TEX_MADE_IN_GREEN,
Certifications.PEFC,
Certifications.REACH,
Certifications.RESPONSIBLE_DOWN_STANDARD,
Certifications.RESPONSIBLE_WOOL_STANDARD,
Certifications.SAB8000,
]
]
contributor = models.ForeignKey(
'Contributor',
null=False,
on_delete=models.PROTECT,
help_text='The contributor who submitted this facility claim')
facility = models.ForeignKey(
'Facility',
null=False,
on_delete=models.PROTECT,
help_text='The facility for which this claim has been submitted')
contact_person = models.CharField(
max_length=200,
null=False,
blank=False,
verbose_name='contact person',
help_text='The contact person for the facility claim')
job_title = models.CharField(
max_length=200,
null=False,
blank=False,
help_text='The contact person\'s job title',
verbose_name='contact person\'s job title',
default='')
email = models.EmailField(
null=False,
blank=False,
verbose_name='email',
help_text='The contact email for the facility claim')
phone_number = models.CharField(
max_length=200,
null=False,
blank=False,
verbose_name='phone number',
help_text='The contact phone number for the facility claim')
company_name = models.CharField(
max_length=200,
null=False,
blank=True,
verbose_name='company name',
help_text='The company name for the facility')
website = models.CharField(
max_length=200,
null=False,
blank=True,
verbose_name='website',
help_text='The website for the facility')
facility_description = models.TextField(
null=False,
blank=False,
verbose_name='description',
help_text='A description of the facility')
linkedin_profile = models.URLField(
null=False,
blank=True,
help_text='A LinkedIn profile for verifying the facility claim',
verbose_name='verification LinkedIn profile')
verification_method = models.TextField(
null=False,
blank=True,
verbose_name='verification method',
help_text='An explanation of how the facility can be verified')
preferred_contact_method = models.CharField(
max_length=200,
null=False,
blank=False,
choices=PREFERRED_CONTACT_CHOICES,
verbose_name='preferred contact method',
help_text='The preferred contact method: email or phone')
status = models.CharField(
max_length=200,
null=False,
blank=False,
choices=STATUS_CHOICES,
default=PENDING,
verbose_name='status',
help_text='The current status of this facility claim')
status_change_reason = models.TextField(
null=True,
blank=True,
verbose_name='status change reason',
help_text='The reason entered when changing the status of this claim.')
status_change_by = models.ForeignKey(
'User',
null=True,
on_delete=models.PROTECT,
verbose_name='status changed by',
help_text='The user who changed the status of this facility claim',
related_name='approver_of_claim')
status_change_date = models.DateTimeField(
null=True,
verbose_name='status change date',
)
facility_name_english = models.CharField(
max_length=200,
null=True,
blank=True,
help_text='The editable official English facility name for the claim.',
verbose_name='facility name in English')
facility_name_native_language = models.CharField(
max_length=200,
null=True,
blank=True,
help_text='The editable official native language facility name.',
verbose_name='facility name in native language')
facility_address = models.CharField(
max_length=200,
null=True,
blank=True,
verbose_name='address',
help_text='The editable facility address for this claim.')
facility_phone_number = models.CharField(
max_length=200,
null=True,
blank=True,
verbose_name='facility phone number',
help_text='The editable facility phone number for this claim.')
facility_phone_number_publicly_visible = models.BooleanField(
null=False,
default=False,
verbose_name='is facility phone number publicly visible',
help_text='Is the editable facility phone number publicly visible?')
facility_website = models.URLField(
null=True,
blank=True,
verbose_name='facility website',
help_text='The editable facility website for this claim.')
facility_website_publicly_visible = models.BooleanField(
null=False,
default=False,
help_text='Is the website publicly visible?',
verbose_name='facility website visible')
facility_minimum_order_quantity = models.CharField(
max_length=200,
null=True,
blank=True,
verbose_name='minimum order quantity',
help_text='The editable facility min order quantity for this claim.')
facility_average_lead_time = models.CharField(
max_length=200,
null=True,
blank=True,
verbose_name='average lead time',
help_text='The editable facilty avg lead time for this claim.')
facility_workers_count = models.IntegerField(
null=True,
blank=True,
help_text='The editable facility workers count for this claim.',
verbose_name='facility workers count')
facility_female_workers_percentage = models.IntegerField(
null=True,
blank=True,
choices=[(i, i) for i in range(0, 101)],
help_text=('Integer value indicating the facility\'s percentage of '
'female workers.'),
verbose_name='percentage of female workers')
facility_affiliations = postgres.ArrayField(
models.CharField(
null=False,
blank=False,
choices=AFFILIATION_CHOICES,
max_length=50,
help_text='A group the facility is affiliated with',
verbose_name='facility affiliation',
),
null=True,
blank=True,
help_text='The facility\'s affiliations',
verbose_name='facility affilations',
)
facility_certifications = postgres.ArrayField(
models.CharField(
null=False,
blank=False,
choices=CERTIFICATION_CHOICES,
max_length=50,
help_text='A certification the facility has achieved',
verbose_name='facility certification',
),
null=True,
blank=True,
help_text='The facility\'s certifications',
verbose_name='facility certifications',
)
facility_type = models.CharField(
max_length=len(CUT_AND_SEW),
null=True,
blank=True,
choices=FACILITY_TYPE_CHOICES,
help_text='The editable facility type for this claim.',
verbose_name='facility type')
other_facility_type = models.CharField(
max_length=200,
null=True,
blank=True,
help_text='Editable alternate text when facility type is OTHER.',
verbose_name='description of other facility type')
facility_product_types = postgres.ArrayField(
models.CharField(
null=False,
blank=False,
max_length=50,
help_text='A product produced at the facility',
verbose_name='product type',
),
null=True,
blank=True,
help_text='The products produced at the facility',
verbose_name='product types',
)
facility_production_types = postgres.ArrayField(
models.CharField(
null=False,
blank=False,
max_length=50,
help_text='A production type associated with the facility',
verbose_name='production type',
),
null=True,
blank=True,
help_text='The production types associated with the facility',
verbose_name='production types',
)
point_of_contact_person_name = models.CharField(
max_length=200,
null=True,
blank=True,
verbose_name='contact person',
help_text='The editable point of contact person name')
point_of_contact_email = models.EmailField(
null=True,
blank=True,
verbose_name='contact email',
help_text='The editable point of contact email')
point_of_contact_publicly_visible = models.BooleanField(
null=False,
default=False,
verbose_name='is contact visible',
help_text='Is the point of contact info publicly visible?')
office_official_name = models.CharField(
max_length=200,
null=True,
blank=True,
verbose_name='office official name',
help_text='The editable office name for this claim.')
office_address = models.CharField(
max_length=200,
null=True,
blank=True,
verbose_name='office address',
help_text='The editable office address for this claim.')
office_country_code = models.CharField(
max_length=2,
null=True,
blank=True,
choices=COUNTRY_CHOICES,
verbose_name='office country code',
help_text='The editable office country code for this claim.')
office_phone_number = models.CharField(
max_length=200,
null=True,
blank=True,
verbose_name='office phone number',
help_text='The editable office phone number for this claim.')
office_info_publicly_visible = models.BooleanField(
null=False,
default=False,
verbose_name='is office publicly visible',
help_text='Is the office info publicly visible?')
parent_company = models.ForeignKey(
'Contributor',
related_name='parent_company',
null=True,
default=None,
on_delete=models.PROTECT,
verbose_name='parent company',
help_text='The parent company of this facility claim.')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
history = HistoricalRecords()
default_change_includes = (
'facility_name_english',
'facility_name_native_language',
'facility_address',
'facility_phone_number',
'facility_website',
'facility_minimum_order_quantity',
'facility_average_lead_time',
'facility_workers_count',
'facility_female_workers_percentage',
'facility_affiliations',
'facility_certifications',
'facility_product_types',
'facility_production_types',
'facility_type',
'other_facility_type',
'facility_description',
'facility_minimum_order_quantity',
'facility_average_lead_time',
'point_of_contact_person_name',
'point_of_contact_email',
'office_official_name',
'office_address',
'office_country_code',
'office_phone_number',
'parent_company',
)
# A dictionary where the keys are field names and the values are predicate
# functions that will be passed a FacilityClaim instance and should return
# a boolean.
change_conditions = defaultdict(
lambda: lambda c: True,
facility_phone_number=(
lambda c: c.facility_phone_number_publicly_visible),
facility_website=(
lambda c: c.facility_website_publicly_visible),
point_of_contact_person_name=(
lambda c: c.point_of_contact_publicly_visible),
point_of_contact_email=(
lambda c: c.point_of_contact_publicly_visible),
office_official_name=(
lambda c: c.office_info_publicly_visible),
office_address=(
lambda c: c.office_info_publicly_visible),
office_country_code=(
lambda c: c.office_info_publicly_visible),
office_phone_number=(
lambda c: c.office_info_publicly_visible),
)
# A dictionary where the keys are field_names and the values are functions
# that will be passed a FacilityClaim and should return a string
change_value_serializers = defaultdict(
lambda: lambda v: v,
parent_company=lambda v: v and v.name,
facility_affiliations=lambda v: ', '.join(v) if v is not None else '',
facility_certifications=lambda v: ', '.join(v)
if v is not None else '',
facility_product_types=lambda v: ', '.join(v)
if v is not None else '',
facility_production_types=lambda v: ', '.join(v)
if v is not None else '',
)
def get_changes(self, include=list(default_change_includes)):
latest = self.history.latest()
previous = latest.prev_record
changes = None
if previous is not None:
for field in FacilityClaim._meta.fields:
should_report_change_publicly = \
self.change_conditions[field.name](self)
if field.name in include and should_report_change_publicly:
curr_value = self.change_value_serializers[field.name](
getattr(self, field.name))
prev_value = self.change_value_serializers[field.name](
getattr(previous.instance, field.name))
if curr_value != prev_value:
if changes is None:
changes = []
changes.append({
'name': field.name,
'verbose_name': field.verbose_name,
'previous': prev_value,
'current': curr_value,
})
return changes
class FacilityClaimReviewNote(models.Model):
"""
A note entered by an administrator when reviewing a FacilityClaim.
"""
claim = models.ForeignKey(
'FacilityClaim',
null=False,
on_delete=models.PROTECT,
help_text='The facility claim for this note'
)
author = models.ForeignKey(
'User',
null=False,
on_delete=models.PROTECT,
help_text='The author of the facility claim review note')
note = models.TextField(
null=False,
blank=False,
help_text='The review note')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
history = HistoricalRecords()